--!strict --!native --!optimize 2 -- codecs/audio/SoundFont/Synth: a SoundFont 2 sample synthesizer with MIDI channels. -- A port of TinySoundFont (tsf.h v0.9, MIT, (c) 2017-2025 Bernhard Schelling, based on SFZero (c) 2012 Steve Folta; -- licenses/TinySoundFont-LICENSE.txt). Unlike tsf.h, the envelope gain is ramped across each 64-sample block. local Synth = {} local readf32, writef32, blen = buffer.readf32, buffer.writef32, buffer.len local exp, log, sqrt, tan, floor = math.exp, math.log, math.sqrt, math.tan, math.floor local NONE, DELAY, ATTACK, HOLD, DECAY, SUSTAIN, RELEASE, DONE = 0, 1, 2, 3, 4, 5, 6, 7 local BLOCK = 64 -- TSF_RENDER_EFFECTSAMPLEBLOCK: envelopes / LFOs / filter cutoff update per block local FASTRELEASE = 0.01 local PI = math.pi local LOOP_NONE, LOOP_SUSTAIN = 0, 2 type Env = { segment: number, isExp: boolean, isAmp: boolean, vel: number, level: number, slope: number, untilNext: number, delay: number, attack: number, hold: number, decay: number, sustain: number, release: number, } type Lfo = { untilStart: number, level: number, delta: number } export type Voice = { preset: number, key: number, channel: number, held: boolean, region: { [string]: number }, pitchIn: number, pitchOut: number, pos: number, gainDB: number, panL: number, panR: number, playIndex: number, loopStart: number, loopEnd: number, amp: Env, mod: Env, lpActive: boolean, qinv: number, a0: number, a1: number, b1: number, b2: number, z1: number, z2: number, modlfo: Lfo, viblfo: Lfo, } export type Channel = { preset: number, bank: number, pitchWheel: number, midiPan: number, midiVolume: number, midiExpression: number, midiRPN: number, midiData: number, sustain: boolean, panOffset: number, gainDB: number, pitchRange: number, tuning: number, } export type State = { presets: { { regions: { { [string]: number } }, preset: number, bank: number } }, lookup: { [number]: number }, samples: buffer, rate: number, gainDB: number, voices: { Voice }, maxVoices: number, playIndex: number, channels: { Channel }, } local function tc2s(tc: number): number return 2 ^ (tc / 1200) end local function cents2Hz(c: number): number return 8.176 * 2 ^ (c / 1200) end local function db2gain(db: number): number return if db > -100 then 10 ^ (db * 0.05) else 0 end local function gain2db(g: number): number return if g <= 0.00001 then -100 else 20 * math.log10(g) end local function releaseSamples(e: Env, rate: number): number return floor((if e.release <= 0 then FASTRELEASE else e.release) * rate) end local function nextSegment(e: Env, active: number, rate: number) local seg = active if seg == NONE then e.untilNext = floor(e.delay * rate) if e.untilNext > 0 then e.segment, e.isExp, e.level, e.slope = DELAY, false, 0, 0 return end seg = DELAY end if seg == DELAY then e.untilNext = floor(e.attack * rate) if e.untilNext > 0 then if not e.isAmp then -- the mod env attack scales with velocity (1 = full duration, 127 = 0.125 x) e.untilNext = floor(e.attack * ((145 - e.vel) / 144) * rate) end e.segment, e.isExp, e.level = ATTACK, false, 0 e.slope = if e.untilNext > 0 then 1 / e.untilNext else 1 return end seg = ATTACK end if seg == ATTACK then e.untilNext = floor(e.hold * rate) if e.untilNext > 0 then e.segment, e.isExp, e.level, e.slope = HOLD, false, 1, 0 return end seg = HOLD end if seg == HOLD then e.untilNext = floor(e.decay * rate) if e.untilNext > 0 then e.segment, e.level = DECAY, 1 if e.isAmp then local mystery = -9.226 / e.untilNext -- LinuxSampler's decay curve (as tsf.h) e.slope = exp(mystery) e.isExp = true if e.sustain > 0 then e.untilNext = floor(log(e.sustain) / mystery) end else e.slope = -1 / e.untilNext e.untilNext = floor(e.decay * (1 - e.sustain) * rate) e.isExp = false end return end seg = DECAY end if seg == DECAY then e.segment, e.level, e.slope, e.untilNext, e.isExp = SUSTAIN, e.sustain, 0, 0x7FFFFFFF, false return end if seg == SUSTAIN then e.segment = RELEASE e.untilNext = math.max(1, releaseSamples(e, rate)) if e.isAmp then e.slope = exp(-9.226 / e.untilNext) e.isExp = true else e.slope = -e.level / e.untilNext e.isExp = false end return end e.segment, e.isExp, e.level, e.slope, e.untilNext = DONE, false, 0, 0, 0x7FFFFFF end local function envSetup(e: Env, r: { [string]: number }, p: string, key: number, vel: number, isAmp: boolean, rate: number) e.delay, e.attack, e.hold, e.decay = r[p .. "Delay"], r[p .. "Attack"], r[p .. "Hold"], r[p .. "Decay"] e.sustain, e.release = r[p .. "Sustain"], r[p .. "Release"] local kh, kd = r[p .. "KeyHold"], r[p .. "KeyDecay"] if kh ~= 0 then local h = e.hold + kh * (60 - key) e.hold = if h < -10000 then 0 else tc2s(h) end if kd ~= 0 then local d = e.decay + kd * (60 - key) e.decay = if d < -10000 then 0 else tc2s(d) end e.vel, e.isAmp = vel, isAmp nextSegment(e, NONE, rate) end local function envProcess(e: Env, n: number, rate: number) local slope = e.slope if slope ~= 0 then if e.isExp then e.level *= slope ^ n else e.level += slope * n end end e.untilNext -= n if e.untilNext <= 0 then nextSegment(e, e.segment, rate) end end local function newEnv(): Env return { segment = DONE, isExp = false, isAmp = false, vel = 0, level = 0, slope = 0, untilNext = 0, delay = 0, attack = 0, hold = 0, decay = 0, sustain = 0, release = 0 } end local function lowpassSetup(v: Voice, fc: number) -- the biquad from earlevel.com (as tsf.h) local k = tan(PI * fc) local kk = k * k local norm = 1 / (1 + k * v.qinv + kk) v.a0 = kk * norm v.a1 = 2 * v.a0 v.b1 = 2 * (kk - 1) * norm v.b2 = (1 - k * v.qinv + kk) * norm end local function lfoSetup(l: Lfo, delay: number, freqCents: number, rate: number) l.untilStart = floor(delay * rate) l.delta = 4 * cents2Hz(freqCents) / rate l.level = 0 end local function lfoProcess(l: Lfo, n: number) if l.untilStart > n then l.untilStart -= n return end l.level += l.delta * n if l.level > 1 then l.delta = -l.delta l.level = 2 - l.level elseif l.level < -1 then l.delta = -l.delta l.level = -2 - l.level end end local function calcPitch(v: Voice, shift: number, rate: number) local r = v.region local note = v.key + r.transpose + r.tune / 100 local adjusted = r.keycenter + (note - r.keycenter) * (r.keytrack / 100) + shift v.pitchIn = adjusted * 100 v.pitchOut = r.sampleRate / (tc2s(r.keycenter * 100) * rate) end local function setPan(v: Voice, pan: number) if pan <= -0.5 then v.panL, v.panR = 1, 0 elseif pan >= 0.5 then v.panL, v.panR = 0, 1 else v.panL, v.panR = sqrt(0.5 - pan), sqrt(0.5 + pan) end end local function channelShift(c: Channel): number return if c.pitchWheel == 8192 then c.tuning else (c.pitchWheel / 16383 * c.pitchRange * 2) - c.pitchRange + c.tuning end local function voiceEnd(s: State, v: Voice) nextSegment(v.amp, SUSTAIN, s.rate) nextSegment(v.mod, SUSTAIN, s.rate) if v.region.loopMode == LOOP_SUSTAIN then v.loopEnd = v.loopStart end end local function voiceEndQuick(s: State, v: Voice) v.amp.release = 0 nextSegment(v.amp, SUSTAIN, s.rate) v.mod.release = 0 nextSegment(v.mod, SUSTAIN, s.rate) end local function newVoice(): Voice return { preset = -1, key = 0, channel = 0, held = false, region = {}, pitchIn = 0, pitchOut = 0, pos = 0, gainDB = 0, panL = 0, panR = 0, playIndex = 0, loopStart = 0, loopEnd = 0, amp = newEnv(), mod = newEnv(), lpActive = false, qinv = 0, a0 = 0, a1 = 0, b1 = 0, b2 = 0, z1 = 0, z2 = 0, modlfo = { untilStart = 0, level = 0, delta = 0 }, viblfo = { untilStart = 0, level = 0, delta = 0 }, } end local function newChannel(): Channel return { preset = 1, bank = 0, pitchWheel = 8192, midiPan = 8192, midiVolume = 16383, midiExpression = 16383, midiRPN = 0xFFFF, midiData = 0, sustain = false, panOffset = 0, gainDB = 0, pitchRange = 2, tuning = 0, } end function Synth.new(sf: any, rate: number, gain: number?, maxVoices: number?): State local lookup: { [number]: number } = {} for i, p in sf.presets do local k = p.bank * 128 + p.preset if lookup[k] == nil then lookup[k] = i end end local s: State = { presets = sf.presets, lookup = lookup, samples = sf.samples, rate = rate, gainDB = gain2db(gain or 0.5), voices = {}, maxVoices = maxVoices or 256, playIndex = 0, channels = {}, } for ch = 1, 16 do s.channels[ch] = newChannel() end for ch = 0, 15 do Synth.program(s, ch, 0) end return s end local function presetIndex(s: State, bank: number, preset: number): number return s.lookup[bank * 128 + preset] or -1 end function Synth.noteOn(s: State, ch: number, key: number, velocity: number) local c = s.channels[ch + 1] if not c then return end if velocity <= 0 then Synth.noteOff(s, ch, key) return end local pi = c.preset local preset = s.presets[pi] if not preset then return end local vel = math.min(velocity, 127) / 127 local midiVel = floor(vel * 127) local rate = s.rate local voices = s.voices local playIndex = s.playIndex s.playIndex += 1 for _, region in preset.regions do if key < region.lokey or key > region.hikey or midiVel < region.lovel or midiVel > region.hivel then continue end local voice: Voice? = nil if region.group ~= 0 then for _, v in voices do if v.preset == pi and v.region.group == region.group then voiceEndQuick(s, v) elseif v.preset == -1 and not voice then voice = v end end else for _, v in voices do if v.preset == -1 then voice = v break end end end if not voice then if #voices < s.maxVoices then local v = newVoice() table.insert(voices, v) voice = v else local best = -1e18 for _, v in voices do if v.amp.segment == RELEASE then local done = releaseSamples(v.amp, rate) - v.amp.untilNext if done > best then best, voice = done, v end end end if not voice then continue end end end local v = voice :: Voice v.region = region v.preset = pi v.key = key v.channel = ch v.playIndex = playIndex v.held = false v.gainDB = s.gainDB - region.attenuation - gain2db(1 / vel) + c.gainDB calcPitch(v, channelShift(c), rate) setPan(v, region.pan + c.panOffset) v.pos = region.offset local doLoop = region.loopMode ~= LOOP_NONE and region.loopStart < region.loopEnd v.loopStart = if doLoop then region.loopStart else 0 v.loopEnd = if doLoop then region.loopEnd else 0 envSetup(v.amp, region, "a", key, midiVel, true, rate) envSetup(v.mod, region, "m", key, midiVel, false, rate) local fc = if region.filterFc <= 13500 then cents2Hz(region.filterFc) / rate else 1 v.qinv = 1 / 10 ^ ((region.filterQ / 10) / 20) v.z1, v.z2 = 0, 0 v.lpActive = fc < 0.499 if v.lpActive then lowpassSetup(v, fc) end lfoSetup(v.modlfo, region.delayModLFO, region.freqModLFO, rate) lfoSetup(v.viblfo, region.delayVibLFO, region.freqVibLFO, rate) end end function Synth.noteOff(s: State, ch: number, key: number) local c = s.channels[ch + 1] if not c then return end local first = -1 for _, v in s.voices do if v.preset ~= -1 and v.channel == ch and v.key == key and v.amp.segment < RELEASE and not v.held then if first == -1 or v.playIndex < first then first = v.playIndex end end end if first == -1 then return end for _, v in s.voices do if v.preset ~= -1 and v.channel == ch and v.key == key and v.amp.segment < RELEASE and not v.held and v.playIndex == first then if c.sustain then v.held = true else voiceEnd(s, v) end end end end local function applyPitch(s: State, ch: number, c: Channel) local shift = channelShift(c) for _, v in s.voices do if v.preset ~= -1 and v.channel == ch then calcPitch(v, shift, s.rate) end end end local function setVolume(s: State, ch: number, c: Channel, volume: number) local db = gain2db(volume) if db == c.gainDB then return end local change = db - c.gainDB for _, v in s.voices do if v.preset ~= -1 and v.channel == ch then v.gainDB += change end end c.gainDB = db end local function setChannelPan(s: State, ch: number, c: Channel, pan: number) for _, v in s.voices do if v.preset ~= -1 and v.channel == ch then setPan(v, v.region.pan + pan - 0.5) end end c.panOffset = pan - 0.5 end local function setTuning(s: State, ch: number, c: Channel, tuning: number) if c.tuning ~= tuning then c.tuning = tuning applyPitch(s, ch, c) end end local function setPitchRange(s: State, ch: number, c: Channel, range: number) if c.pitchRange ~= range then c.pitchRange = range if c.pitchWheel ~= 8192 then applyPitch(s, ch, c) end end end local function setSustain(s: State, ch: number, c: Channel, on: boolean) if c.sustain == on then return end c.sustain = on if on then return end for _, v in s.voices do if v.preset ~= -1 and v.channel == ch and v.amp.segment < RELEASE and v.held then voiceEnd(s, v) end end end -- channel 9: drums (bank 128) function Synth.program(s: State, ch: number, program: number) local c = s.channels[ch + 1] if not c then return end local bank = c.bank % 32768 local idx if ch == 9 then idx = presetIndex(s, 128 + bank, program) if idx == -1 then idx = presetIndex(s, 128, program) end if idx == -1 then idx = presetIndex(s, 128, 0) end if idx == -1 then idx = presetIndex(s, bank, program) end else idx = presetIndex(s, bank, program) end if idx == -1 then idx = presetIndex(s, 0, program) end if idx ~= -1 then c.preset = idx end end function Synth.pitchBend(s: State, ch: number, value: number) local c = s.channels[ch + 1] if not c or c.pitchWheel == value then return end c.pitchWheel = value applyPitch(s, ch, c) end function Synth.control(s: State, ch: number, cc: number, value: number) local c = s.channels[ch + 1] if not c then return end local volume, pan, data = false, false, false if cc == 7 then c.midiVolume = c.midiVolume % 128 + value * 128 volume = true elseif cc == 39 then c.midiVolume = c.midiVolume - c.midiVolume % 128 + value volume = true elseif cc == 11 then c.midiExpression = c.midiExpression % 128 + value * 128 volume = true elseif cc == 43 then c.midiExpression = c.midiExpression - c.midiExpression % 128 + value volume = true elseif cc == 10 then c.midiPan = c.midiPan % 128 + value * 128 pan = true elseif cc == 42 then c.midiPan = c.midiPan - c.midiPan % 128 + value pan = true elseif cc == 6 then c.midiData = c.midiData % 128 + value * 128 data = true elseif cc == 38 then c.midiData = c.midiData - c.midiData % 128 + value data = true elseif cc == 0 then c.bank = 0x8000 + value -- bank select MSB alone acts like LSB (as tsf.h) elseif cc == 32 then c.bank = (if c.bank >= 0x8000 then (c.bank % 128) * 128 else 0) + value elseif cc == 101 then local rpn = if c.midiRPN == 0xFFFF then 0 else c.midiRPN c.midiRPN = rpn % 128 + value * 128 elseif cc == 100 then local rpn = if c.midiRPN == 0xFFFF then 0 else c.midiRPN c.midiRPN = rpn - rpn % 128 + value elseif cc == 98 or cc == 99 then c.midiRPN = 0xFFFF elseif cc == 64 then setSustain(s, ch, c, value >= 64) elseif cc == 120 then for _, v in s.voices do if v.preset ~= -1 and v.channel == ch and (v.amp.segment < RELEASE or v.amp.release ~= 0) then voiceEndQuick(s, v) end end elseif cc == 123 then for _, v in s.voices do if v.preset ~= -1 and v.channel == ch and v.amp.segment < RELEASE then voiceEnd(s, v) end end elseif cc == 121 then c.midiVolume, c.midiExpression, c.midiPan, c.bank, c.midiRPN, c.midiData = 16383, 16383, 8192, 0, 0xFFFF, 0 setVolume(s, ch, c, 1) setChannelPan(s, ch, c, 0.5) setPitchRange(s, ch, c, 2) setTuning(s, ch, c, 0) end if volume then -- the cube gives a decent MIDI volume curve (tsf.h) setVolume(s, ch, c, ((c.midiVolume / 16383) * (c.midiExpression / 16383)) ^ 3) elseif pan then setChannelPan(s, ch, c, c.midiPan / 16383) elseif data then if c.midiRPN == 0 then setPitchRange(s, ch, c, c.midiData // 128 + 0.01 * (c.midiData % 128)) elseif c.midiRPN == 1 then local t = c.tuning setTuning(s, ch, c, (if t < 0 then math.ceil(t) else floor(t)) + (c.midiData - 8192) / 8192) elseif c.midiRPN == 2 and cc == 6 then local t = c.tuning setTuning(s, ch, c, (value - 64) + (t - (if t < 0 then math.ceil(t) else floor(t)))) end end end function Synth.midi(s: State, status: number, d1: number, d2: number) local kind, ch = status // 16, status % 16 if kind == 9 then Synth.noteOn(s, ch, d1, d2) elseif kind == 8 then Synth.noteOff(s, ch, d1) elseif kind == 11 then Synth.control(s, ch, d1, d2) elseif kind == 12 then Synth.program(s, ch, d1) elseif kind == 14 then Synth.pitchBend(s, ch, d1 + d2 * 128) end end function Synth.reset(s: State) for _, v in s.voices do v.preset = -1 end for ch = 1, 16 do s.channels[ch] = newChannel() end for ch = 0, 15 do Synth.program(s, ch, 0) end end function Synth.active(s: State): number local n = 0 for _, v in s.voices do if v.preset ~= -1 then n += 1 end end return n end local function voiceRender(s: State, v: Voice, out: buffer, frame: number, numSamples: number) local region = v.region local input = s.samples local rate = s.rate local modEnvToPitch, modEnvToFilterFc = region.modEnvToPitch, region.modEnvToFilterFc local modLfoToPitch, modLfoToFilterFc, modLfoToVolume = region.modLfoToPitch, region.modLfoToFilterFc, region.modLfoToVolume local vibLfoToPitch = region.vibLfoToPitch local updateModEnv = modEnvToPitch ~= 0 or modEnvToFilterFc ~= 0 local updateModLfo = v.modlfo.delta ~= 0 and (modLfoToPitch ~= 0 or modLfoToFilterFc ~= 0 or modLfoToVolume ~= 0) local updateVibLfo = v.viblfo.delta ~= 0 and vibLfoToPitch ~= 0 local loopStart, loopEnd = v.loopStart, v.loopEnd local isLooping = loopStart < loopEnd local endD = region.stop local loopEndD = loopEnd + 1 local loopLen = loopEnd - loopStart + 1 local wrapAt = if isLooping then loopEnd else math.huge -- ip >= loopEnd and isLooping local wrapEnd = if isLooping then loopEndD else math.huge local pos = v.pos local lpActive, a0, a1, b1, b2, z1, z2 = v.lpActive, v.a0, v.a1, v.b1, v.b2, v.z1, v.z2 local dynamicLowpass = modLfoToFilterFc ~= 0 or modEnvToFilterFc ~= 0 local dynamicPitch = modLfoToPitch ~= 0 or modEnvToPitch ~= 0 or vibLfoToPitch ~= 0 local dynamicGain = modLfoToVolume ~= 0 local filterFc = region.filterFc local pitchRatio = if dynamicPitch then 0 else tc2s(v.pitchIn) * v.pitchOut local noteGain = if dynamicGain then 0 else db2gain(v.gainDB) local o = frame * 8 while numSamples > 0 do local block = if numSamples > BLOCK then BLOCK else numSamples numSamples -= block if dynamicLowpass then local fres = filterFc + v.modlfo.level * modLfoToFilterFc + v.mod.level * modEnvToFilterFc local fc = if fres <= 13500 then cents2Hz(fres) / rate else 1 lpActive = fc < 0.499 if lpActive then lowpassSetup(v, fc) a0, a1, b1, b2 = v.a0, v.a1, v.b1, v.b2 end end if dynamicPitch then pitchRatio = tc2s(v.pitchIn + (v.modlfo.level * modLfoToPitch + v.viblfo.level * vibLfoToPitch + v.mod.level * modEnvToPitch)) * v.pitchOut end if dynamicGain then noteGain = db2gain(v.gainDB + v.modlfo.level * modLfoToVolume * 0.1) end local gainMono = noteGain * v.amp.level envProcess(v.amp, block, rate) if updateModEnv then envProcess(v.mod, block, rate) end if updateModLfo then lfoProcess(v.modlfo, block) end if updateVibLfo then lfoProcess(v.viblfo, block) end -- ramp the gain across the block to the envelope's next level (tsf.h steps it per block: zipper noise) local gainNext = noteGain * v.amp.level local step = (gainNext - gainMono) / block local panL, panR = v.panL, v.panR local g = gainMono local k = block if lpActive then while k > 0 and pos < endD do k -= 1 local ip = floor(pos) local np = if ip >= wrapAt then loopStart else ip + 1 local s0 = readf32(input, ip * 4) local val = s0 + (readf32(input, np * 4) - s0) * (pos - ip) local y = val * a0 + z1 z1 = val * a1 + z2 - b1 * y z2 = val * a0 - b2 * y val = y * g g += step writef32(out, o, readf32(out, o) + val * panL) writef32(out, o + 4, readf32(out, o + 4) + val * panR) o += 8 pos += pitchRatio if pos >= wrapEnd then pos -= loopLen end end else while k > 0 and pos < endD do k -= 1 local ip = floor(pos) local np = if ip >= wrapAt then loopStart else ip + 1 local s0 = readf32(input, ip * 4) local val = (s0 + (readf32(input, np * 4) - s0) * (pos - ip)) * g g += step writef32(out, o, readf32(out, o) + val * panL) writef32(out, o + 4, readf32(out, o + 4) + val * panR) o += 8 pos += pitchRatio if pos >= wrapEnd then pos -= loopLen end end end o += k * 8 if not (pos < endD) or v.amp.segment == DONE then v.preset = -1 return end end v.pos = pos v.lpActive, v.z1, v.z2 = lpActive, z1, z2 end function Synth.render(s: State, out: buffer, frame: number, n: number) local room = blen(out) // 8 - frame if frame < 0 or room <= 0 then return end if n > room then n = room end if n <= 0 then return end -- the sample buffer must hold every region's range + the pad sample (checked once against hand-made SoundFonts) local count = blen(s.samples) // 4 - 1 for _, v in s.voices do if v.preset ~= -1 then local r = v.region if r.stop > count or r.loopEnd > count or r.offset < 0 or r.loopStart < 0 or v.pos < 0 then v.preset = -1 else voiceRender(s, v, out, frame, n) end end end end return Synth