The Win64 build's -Wshorten-64-to-32 narrowings are made explicit where
the value is bounded: socket()/accept() handles kept as RetroArch's int
descriptors, ai_addrlen passed as socklen_t, UDP and pipe lengths,
COM/D3D counts and shader frame counters, WASAPI/XAudio2 buffer sizes.
net_socket clamps each send/recv to Winsock's int count on _WIN32 and
lets the existing loops move the rest; the remote-input descriptors are
plain ints on every platform, as socket_init returns them.
xaudio29.h declares its interfaces through a macro that, in C, leaves
out DECLARE_INTERFACE's second typedef of the forward-declared names.
The narrowings the Linux build reports under -Wshorten-64-to-32 are
made explicit where the value is bounded (read() returns into small
buffers, X11 property lengths, statestream index counts, clamped H.265
weights, VP9 transform outputs), and the joypad scan loops count with
the unsigned index their callees take. gl1 sizes its readback with
VIDEO_SCALE_AREA directly, and rdds' swap is three statements.
The VP9 casts sit only on the stores into the rvp9_tran output arrays,
so the decoder's object code stays instruction-identical under gcc and
clang.
CoreMIDI's notification of a removed object moves one atomic count
on, and touches no instance; each instance's read and write look for
its endpoint again only when the count has moved, on the thread that
calls them, so a read or write lists no devices while none has gone.
The instance registry and its lock go, and with them the cap of eight
instances. The receive callback's shutdown flag is an atomic.
samples/midi/coremidi_driver builds the driver against a stand-in for
CoreMIDI: reads and writes list no devices until one is removed, a
removed input drops the notes queued from it, every instance finds a
removal, and removals notified from another thread run beside reads.
When midiOutPrepareHeader failed on buffer i, the unwind loop
"while (--i <= 0)" ran on an unsigned i: a failure on buffer 2 left
buffers 0 and 1 prepared, and a failure on buffer 1 unprepared buffer
0 and stopped only because i wrapped. Count down with i-- > 0.
Tests: under wine, with a harness that includes winmm_midi.c and fakes
the two header calls. Before: a failure on the last buffer gives
prepared 2, unprepared 0. After: a failure on buffer 0, 1 or 2
unprepares exactly what was prepared. Cross-compiled with
x86_64-w64-mingw32-gcc -Wall -Wsign-compare, no warnings.
Co-authored-by: Claude Opus 5.5 <[email protected]>
The event queue is a ring of slots, each under its own sequence word.
A writer claims the next number with an atomic add and fills its slot;
the renderer takes slots in order, stops at one still being written,
and skips one the ring has gone past, so a full ring still loses its
oldest messages. Neither side waits.
Dropped messages are counted, and reported once when the synth is
freed rather than from the audio thread.
samples/midi/fmsynth_queue renders while one and two writers send, and
checks order, overflow, a slot claimed and not yet written, and that
every event under unthrottled writers is applied or counted dropped.
It runs in the TSan lane.
Each side owns one index of the ring and publishes it with release
ordering; the slot one behind the read index is never written, so the
event read() hands out stays intact until the next read. A clear from
the notification thread or set_input() is a flag the next read acts
on, since only the reader moves the read index.
Asked whether MIDI is on the threaded pipeline. It is, by inheritance:
the synth renders inside audio_driver_flush(), which the pipeline
consumer runs on the audio thread. But only the rendering moved.
fmsynth_midi_write() still applies a message straight into the voice
table from whichever thread the core calls it on - the frame - while
fmsynth_render() walks that same table on the audio thread, and there
is no synchronisation anywhere in the file.
Measured rather than argued: a core emitting a note on and a note off
every frame, under ThreadSanitizer, reports twenty-four distinct races
with the threaded pipeline on and none with it off. Every voice field,
the channel state, the allocator. Turning the pipeline on by default
turned that on for every core that uses MIDI.
Writes queue now and the renderer applies them at the top of the block
it is about to synthesise. The lock is held for the copy in and the
copy out and never across the synthesis, so a core writing a note is
never held for a render. Applying at a block boundary changes nothing
audible: the renderer already produced a whole block per call, so a
message arriving mid-block took effect at the next one either way.
A full queue drops the oldest rather than the newest, and says so once
per block: a dropped note-off leaves a voice sounding until its
envelope ends, a dropped note-on is silence nobody notices. 256
messages is a whole GM reset across sixteen channels and then some;
the test core never filled it.
Without HAVE_THREADS there is no lock and write() applies directly, as
before - correct on a build where the renderer runs on the caller's
thread.
Zero reports over four runs after, twenty-four before, and the notes
still arrive: 400 note-ons over 400 frames with the pipeline on and
off alike, no drops. ASan and LSan clean both ways, win32 syntax clean.
Four more families where one patch served eight instruments that behave
differently. Add per-program overrides for the clearest outliers and improve
the pipe default, each change validated by a measurable property:
- Church organ (19): full additive pipe organ, slow swell (attack 0.069 s vs
the drawbar default's 0.008 s), extra ranks, slight per-rank detune.
- Accordion (21, 23): two reedy voices in a +/-0.5 Hz musette detune (1.0 Hz
beat).
- Brass section (61): two detuned brass voices panned wide (1.0 Hz beat) with
a slower swell than the solo-brass default; synth brass (62, 63): bright and
fully sustained.
- Clarinet (71): ratio-2 modulator puts the energy on odd harmonics for the
hollow closed-pipe tone (odd/even 577 vs 2.3).
- Pipe family default: gentle 5 Hz player's vibrato on the flute.
Family fallback for every other program in these families is unchanged; prior
splits and the engine invariants are unaffected.
Programs 32-39 shared one patch, so synth bass sounded like the acoustic/
electric bass. Warm the fingered default (lower modulation index for a
stronger fundamental) and override the synth basses:
- Bass family default: warm fingered electric, fundamental-strong.
- GM 38/39 override: punchy, fully sustained, brighter via a modest
modulator self-feedback - kept deliberately below the feedback level where
the harmonics run away, so it stays bass-heavy rather than fizzy.
Measured at E2: synth bass centroid 10.0 vs fingered 6.8 (brighter but still
bass-weighted) and sustains ~2.8x longer (0.042 vs 0.015 at 1 s). Family
fallback for the acoustic/pick/fretless/slap basses is unchanged.
The chromatic-percussion family (8-15) played every program as one inharmonic
bell, so the wooden and metallic mallets were indistinguishable. Override the
three with the clearest physical differences, leaving the bell default for
celesta, glockenspiel, music box, tubular bells and dulcimer:
- Vibraphone (11): metallic, rings while held, with the ~5 Hz rotating-disc
tremolo that defines it.
- Marimba (12): wooden and harmonic (4:1 overtone), fast two-stage decay.
- Xylophone (13): harder/brighter (3:1), very fast decay.
Measured at C5: marimba and xylophone carry 0% inharmonic energy versus 61%
for the bell default, and the vibraphone's amplitude tremolo lands at 5.00 Hz.
Family fallback for the remaining programs is unchanged.
Programs 24-31 all shared one family patch that plateaued at a low level, so
acoustic guitars rang forever instead of decaying and overdriven/distortion
guitars (heavily used in game music) were a quiet, clean decay - wrong for
both. Give the family default the acoustic treatment and override the rock
guitars:
- Guitar family default: a plucked two-stage decay to silence.
- GM 29/30 override: a sustained patch with modulator self-feedback for the
buzzy overdrive grit.
Measured at C4: acoustic (24) now falls to silence by ~3 s; distortion (30)
holds a steady ~0.05 with a far brighter spectrum (centroid 20 vs 2.9). Family
fallback for the other guitar programs is unchanged.
The piano carrier decayed linearly to a 0.20 sustain plateau, so a held note
rang at a constant level forever - nothing like a struck string. Rebuild it
with the two-stage envelope now available: a fast initial decay then a slow
tail to silence (approximating the double-exponential decay of a real string),
with the FM modulator decaying faster than the carrier so the bright attack
mellows into a warm tail.
Measured at C4: amplitude now falls continuously (0.048 -> 0.026 -> 0.019 ->
0.015 -> 0.013 -> 0.004 over 3.5 s) instead of plateauing at 0.009, and the
spectral centroid drops from 2.98 to 1.91 harmonics from attack to tail. New
OPCP/OPMP macros build the two-stage carrier and modulator.
Ensemble and pad were single-voice 2-operator patches, so they had none of
the chorus that defines those sounds. Now that operators carry a frequency
offset, rebuild both as two unison voices detuned by a few Hz and panned
apart: ensemble +/-0.4 Hz, pad +/-0.6 Hz.
Measured: ensemble beats at 0.8 Hz, pad at 1.2 Hz (the detune spacing), each
with real stereo width (side/mid 0.18 and 0.29) and pitch unchanged. The new
OPCO macro adds a carrier with a fixed Hz detune. First real use of the
freq_offset parameter added with the libfmsynth operator model.
libfmsynth's README describes phase-integration FM, while this engine adds the
modulation matrix output to each operator's phase at lookup (DX7-style phase
modulation). These are the same synthesis - identical Bessel sideband spectra
for a given index - differing only in parameterisation: PM's index is pitch
independent, integrated FM's is deviation/modulator-frequency. Matching the
latter would require scaling every depth by the modulator frequency for the
same result, or retuning every patch and risking DC drift on the feedback
operators. Record why PM is kept so the divergence from the reference isn't
mistaken for a bug and "fixed".
Bring the operator parameters up to libfmsynth's full set so the engine is as
capable as the reference, closing the remaining gaps:
- Envelope is now three linear ramps to successive targets (env_target/
env_time) followed by sustain at the final target and a release ramp,
a superset of the previous ADSR.
- Per-operator frequency offset (fixed Hz) on top of the ratio, for detuned
and inharmonic voices.
- Keyboard scaling by breakpoint with separate below/above factors
(ks_mid/ks_low/ks_high) instead of a single exponent.
- Per-operator mod-wheel sensitivity feeding each operator's vibrato.
The operator constructor macros map the old (attack, decay, sustain, release)
shorthand onto target {1, sus, sus} over times {atk, dec, 0} then release, and
default keyboard scaling / mod sensitivity to the previous behaviour, so every
existing family and override sounds identical - verified: organ pitch, voice
release, LFO rate, stability and the harpsichord/clavi overrides are unchanged.
New capability is validated directly: a +30 Hz offset shifts A4 440 -> 470 Hz,
and an envelope targeting {1.0, 0.5, 0.2} produces that staged decay.
The GM mapping groups eight programs per family (program >> 3), which is too
coarse for instruments whose family default is plainly wrong - harpsichord
and clavi (programs 6, 7) played as a sustained piano.
Add a small per-program override checked before the family fallback: a switch
mapping specific programs to dedicated patches, trivial to extend as more are
voiced. Seed it with harpsichord (plucked, bright 3:1 colour, no sustain) and
clavi (percussive 1:1, very short sustain).
Measured against the piano default: harpsichord centroid 1342 -> 2723 Hz and
its held level falls to ~0 (plucked decay); clavi sits lower and shorter.
Family fallback for every other program is unchanged. The two voicings follow
standard FM principles and are starting points for ear-tuning, not finished
instruments - the value here is the mechanism.
The oscillator read the 2048-point sine table with a truncated index, a
~55 dB quantization floor. In FM that is worse than it sounds: every
modulator runs through the same table, so its quantization error becomes
audible sidebands around the carrier.
Interpolate linearly between the two adjacent table entries. The lookup
floor rises past ~120 dB (now float-limited) for one extra fetch and a lerp
per operator. The fundamental and harmonics are unchanged - only the noise
floor drops - so timbres are identical, just cleaner.
Dense polyphony could exceed unity and hard-clip: sixteen loud brass/reed
notes peaked at ~1.30. The operator self-feedback in the brass patch also
left a small DC offset (~0.015) that wasted headroom and could click on note
transitions.
Add a final per-channel output stage run over every frame (including the
reverb tail):
- a one-pole high-pass DC blocker (FMSYNTH_DC_HZ ~ 8 Hz corner, pole scaled
to the output rate in fmsynth_set_rate) removes the offset;
- a soft clipper that is identity below +/-FMSYNTH_CLIP_T (0.75) and curves
via a tanh knee toward +/-1.0 above it, so it can never exceed unity.
Measured: 16-note peak 1.30 -> 0.996, brass DC 0.0154 -> 0.0003. Single
notes (well under the knee) are spectrally unchanged - the fundamental and
harmonics pass through untouched - so normal playing is unaffected and only
loud stacks are gently limited.
Refactor the in-process FM synth so its architecture mirrors Themaister's
libfmsynth (MIT) within our single-file, C89/MSVC, scalar, in-RetroArch
constraints. No code is vendored - only the design is adopted.
Engine (fmsynth_midi.c):
- 8 operators per voice (was 4).
- Free modulation matrix: any operator may modulate any other, including
itself, held as a sparse connection list (the C89-friendly form of
libfmsynth's dense NxN matrix). This replaces the fixed algorithm tables
and the single top-op feedback term.
- Per-operator velocity sensitivity, keyboard scaling and LFO depth, plus a
per-operator carrier flag and pan.
- One per-voice sine LFO modulates both amplitude (tremolo) and frequency
(vibrato); the mod wheel feeds the same vibrato path.
- Per-carrier stereo panning summed into the mix.
- Envelopes and the LFO are advanced at control rate (every 32 samples,
FMSYNTH_CONTROL); the per-sample loop runs only the oscillator bank and
the modulation matrix.
Patches (fmsynth_patches.h):
- New fmsynth_op_t (ratio, amp, pan, ADSR, vel_sens, key_scale, lfo_amp,
lfo_freq, carrier) and fmsynth_conn_t (to, from, depth) describing the
matrix sparsely; fmsynth_patch_t carries op[8], a connection list and a
voice LFO rate.
- 16 GM families re-expressed in this form: most 2-operator, with the organ
as four additive carriers, strings as two L/R-panned stacks with vibrato,
and brass/lead using stack routing plus operator self-feedback.
Percussion, reverb, MIDI dispatch and the driver vtable are unchanged.
The Schroeder/Freeverb-derived reverb was mono: one comb+allpass network
whose wet output was added equally to both channels, so the tail sat dead
centre. Duplicate the network per channel and offset the right channel's
comb and allpass delay lengths by a stereo spread (23 samples at 44.1kHz,
rate-scaled, the Freeverb default). Both networks take the same mono send;
the spread decorrelates their outputs so the tail spreads across the image.
The dry path and the wet mix level are unchanged, so notes themselves are
unaffected; only the reverb tail gains width. State doubles to two
networks (struct ~0.24 MB, still a single heap allocation).
Validated: in the pure reverb tail (all voices decayed) L/R correlation
falls from 1.000 (mono) to ~0 and the side/mid ratio rises from 0 to
~1.0 - fully decorrelated - with output bounded and no NaN. C89-clean.
Adds an optional per-voice sine LFO (an idea taken from Themaister's
libfmsynth, MIT, where one LFO per voice modulates both amplitude and
frequency). Each patch gains lfo_rate (Hz), lfo_trem (amplitude depth)
and lfo_vib (pitch depth, semitones); a single phase accumulator drives
both effects per sample. The mod-wheel vibrato is unchanged and simply
adds to the patch vibrato.
The LFO is fully gated: with lfo_rate 0 (every 2-op-mapped GM family) the
code path is inert and output is unchanged. It is voiced only on the
sustained 4-op patches - organ (slow tremolo), strings (gentle vibrato +
tremolo, atop the existing detune shimmer), brass and synth lead
(vibrato) - to give them some movement.
Validated: organ amplitude envelope shows its strongest AM at exactly
6.00 Hz (the configured rate) while a no-LFO patch (piano) shows only
noise-floor AM ~8x weaker; lead vibrato measures 0.111 semitone RMS,
matching a +/-0.15 semitone sine. All prior core checks still pass
(piano A4 440.0 Hz, additive organ partials, distinct centroids, bounded
output, percussion intact). C89/MSVC-clean.
A voice's base_inc (freq/rate) and drum_dec (1/(time*rate)) are baked at
note-on from the output rate in force at that moment. If the rate changed
afterwards the voice kept its old pitch/decay for its whole lifetime. The
common trigger is a note arriving on the very first frame, before
audio_driver.c has supplied the real rate: with the 44100 default still
in place, a note rendered at 48000 played ~9% sharp.
Rescale every active voice's baked rate-dependent state by old/new in
fmsynth_set_rate whenever the rate changes. The work happens only on an
actual rate change (rare), needs no extra per-voice state, and corrects
both the first-frame case and any later rate switch.
Validated: a note triggered before the first render now sounds 440.0 Hz
(was ~480), and a 48000->44100 switch mid-note holds 440.0 Hz.
Replaces the fixed 2-operator melodic voice with a 4-operator engine and
a small set of routing "algorithms" (an idea taken from flexible-routing
FM designs such as Themaister's libfmsynth, MIT, and the classic 4-op
Yamaha chips). Each operator has its own frequency ratio, output level
(amplitude for carriers, modulation index in carrier cycles for
modulators) and ADSR envelope; operators are evaluated high-to-low each
sample so modulators feed carriers within one sample, and the top
operator supports self-feedback.
Eight algorithms cover serial, dual-stack, branch, additive and
multi-carrier routings. Most GM families keep their prior sound by
mapping to a faithful 2-operator subset (FMSYNTH_ALG_TWO_OP, operators 2
and 3 silent); organ now uses 4 additive carriers, strings a dual stack,
and brass/synth-lead a feedback stack, to exercise the wider palette.
All existing behaviour is preserved: velocity->brightness (on
modulators), mod-wheel vibrato, keyboard scaling, pan, channel
volume/expression, RPN pitch-bend range, sustain pedal and reverb. The
channel-10 percussion path is unchanged.
Validated: piano A4 fundamental 440.0 Hz; additive organ shows partials
at 1x-4x the fundamental; piano/strings/brass/organ spectral centroids
remain distinct; output bounded with no NaN across all 16 families;
percussion intact. C89/MSVC-clean.
Decay and release rates now scale with note pitch (an idea taken from
Themaister's libfmsynth, MIT): higher notes decay and release faster,
lower notes ring longer, as on real struck/plucked instruments. The
rate multiplier is 2^((note-60)*FMSYNTH_KEY_SCALE), clamped to a sane
span so extreme notes stay reasonable. Measured on a sustained patch,
the fraction of amplitude remaining 60ms after note-off falls
monotonically from ~0.92 (C3) to ~0.57 (C6).
Controller completeness so arbitrary GM streams (not just simple game
music) play correctly. Engine-only; no audio-path or interface change.
- Sustain pedal (CC64): note-offs while the pedal is down are deferred;
voices keep sounding until the pedal is released, then all held voices
on the channel enter release. Without this, piano music releases notes
that should ring.
- Mod wheel (CC1): adds a per-voice ~5.5Hz pitch-vibrato LFO whose depth
scales with the wheel (up to +/- half a semitone), applied per sample
to the carrier and modulator phase increments.
- RPN pitch-bend range (RPN 0,0 via CC101/CC100 + Data Entry CC6):
replaces the hardcoded +/-2 semitones with a per-channel range, so
music that requests a wider bend (e.g. an octave) bends correctly.
Adds per-channel sustain/mod_wheel/bend_range/rpn state and per-voice
held/lfo_phase fields; all variables declared at block top (MSVC C89).
Three quality improvements to the FM synth, all confined to the engine
(no change to the audio path or driver interface):
- Voice allocation now steals intelligently instead of always taking
voice 0: a free voice first, then the quietest voice already in its
release stage, then the oldest voice. Dense passages no longer cut
arbitrary notes.
- Velocity now scales FM modulation index (brightness), not just
amplitude, so harder hits open up the timbre the way real instruments
do. Measured: a soft note vs a hard note moves the spectral centroid
from ~800Hz to ~1380Hz.
- A Schroeder reverb (4 comb + 2 allpass, rate-scaled, lightly damped)
is mixed over the summed output, with the tail serviced for ~1.6s
after the last voice ends so it rings out rather than being cut. Dry
FM is sterile; a little room makes it sound produced.
fmsynth_midi_init() returned NULL when called with a NULL output (the
default, since the MIDI Output device defaults to "Off"). That aborted
midi_driver_init(), which freed the available-device list, leaving the
MIDI Output menu empty ("No Entries to Display") and making the fmsynth
output impossible to select - a deadlock.
Construction must not depend on a selected device: the output selection
only gates the frontend's output_enabled flag (as in winmm). Make init
succeed regardless of input/output, and let set_output accept disabling
(NULL) as well.
Add a software General MIDI synthesizer as a new MIDI driver. Unlike the
winmm/alsa/coremidi drivers, fmsynth does not route to an external OS MIDI
device: it renders MIDI events to PCM in-process and that PCM is mixed into
RetroArch's audio output stream.
This solves two problems:
- WASAPI exclusive mode. An OS software synth (e.g. the Windows GS
Wavetable Synth) renders to the shared mixer, so it cannot produce
sound while RetroArch holds the device in exclusive mode. fmsynth needs
no OS device, so MIDI now works under exclusive mode.
- Platform parity. winmm is Windows-only and there is no built-in synth
on Linux/macOS/mobile. fmsynth is pure integer/float arithmetic with no
platform headers or external dependencies, so it behaves identically on
every target. It also embeds no instrument sample data; every timbre is
produced by a 2-operator FM engine from a compact GM->FM parameter
table reconstructed from the General MIDI layout and OPL/GENMIDI
conventions.
Driver (midi/drivers/fmsynth_midi.c, midi/drivers/fmsynth_patches.h):
- 2-op FM voice with carrier amplitude ADSR and a modulator-index
envelope, up to 64-voice polyphony.
- GM family patch table (16 templates) with a per-program override hook,
plus a channel-10 percussion map (FM and noise hits).
- Channel volume (CC7), expression (CC11), pan (CC10), pitch bend.
Audio integration (audio/audio_driver.c):
- midi_driver_t gains an optional 'render' member; external-device
drivers leave it NULL (zero-initialised), so they are unchanged.
- audio_driver_flush() mixes synth PCM into the float input buffer
before the resampler, so it shares the core's resampler, gain and
output path. The mix is a no-op unless a render-capable MIDI driver is
active and sounding.
- When such a synth is active the resampler fast path is disabled, since
write_raw drivers (e.g. coremidi/coreaudio) would otherwise bypass the
mix. No cost when no synth is active.
midi_driver.h is also made self-contained for size_t/uint8_t/uint32_t,
which it previously relied on includers to provide.
The driver is registered unconditionally (no HAVE_ guard) as it has no
external dependency.
Appears to be enough to silence any lingering notes when midi is playing
and core is suddenly closed. Tried adding this on the core side but
midi_free comes first before retro_deinit/retro_unload_game so the
driver was already closed.
Another way to fix this in the core's side is to call 'flush'
immediately after any midi writes, but that doesn't appear to be the
api's design, flush is supposed to get called at the end of the
retro_run.
Im open for any better methods. but this should work for the issue
without causing other problems.
Co-authored-by: negativeExponent <[email protected]>
When an underlying MIDI device does not understand/support a MIDI message (very common with sysex messages) it returns an error code.
With this fix MIDI output can continue gracefully even after an emulated game sends an unsupported message.
midiStreamStop can freeze the process when there has been a NOTE-ON message without a corresponding NOTE-OFF.
Just removing the call to midiStreamStop and letting the midiStreamClose below it do the entire stopping and closing fixes that.