--!strict -- codecs/audio/SoundFont/Parse: SoundFont 2.0x (sfbk RIFF) reader. The INFO list, the sdta samples (smpl 16-bit, + sm24 -- when present) as one f32 buffer, and the pdta "hydra" (phdr pbag pmod pgen inst ibag imod igen shdr), flattened -- into playable regions per preset: the instrument global zone, the preset global zone and the preset zone's -- generators merged the way TinySoundFont (tsf.h v0.9, MIT, (c) Bernhard Schelling; licenses/TinySoundFont-LICENSE.txt) -- does (tsf_load_presets / tsf_region_operator / tsf_region_envtosecs), with every index and sample offset clamped -- so the synth never reads outside the sample buffer. -- Differences from tsf.h: initialAttenuation is cB * 0.04 dB (FluidSynth's EMU-compatible scale; tsf uses 0.01); -- SF3 (Ogg samples) is not supported; modulators (pmod / imod) are read but not applied (as in tsf.h). -- Never throws: a bad file returns nil, Err. local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Parse = {} -- a region (one sample zone of a preset), in "absolute" form: envelope / LFO times in seconds, sustain as a level export type Region = { [string]: number } export type Preset = { name: string, preset: number, bank: number, regions: { Region } } export type SoundFont = { kind: "soundfont", info: { [string]: string }, samples: buffer, -- f32 mono, sampleCount + 1 floats (a zero pad sample past the end) sampleCount: number, presets: { Preset }, -- sorted by bank, then preset number sampleHeaders: { { [string]: any } }, instruments: { { name: string, zones: number } }, meta: { [string]: any }, } local GEN_INSTRUMENT, GEN_SAMPLEID = 41, 53 -- generator op -> { field, mode, limit }. modes: f / i (value, merged by adding then clamping), a (sample address -- add), a15 (coarse address add: * 32768), kr / vr (key / velocity range), loop, group, key (overriding root key) local LIM12K5K = { 1, -12000, 5000 } local LIM12K8K = { 1, -12000, 8000 } local LIM1200 = { 1, -1200, 1200 } local GEN: { [number]: { any } } = { [0] = { "offset", "a" }, [1] = { "stop", "a" }, [2] = { "loopStart", "a" }, [3] = { "loopEnd", "a" }, [4] = { "offset", "a15" }, [5] = { "modLfoToPitch", "i", { 1, -12000, 12000 } }, [6] = { "vibLfoToPitch", "i", { 1, -12000, 12000 } }, [7] = { "modEnvToPitch", "i", { 1, -12000, 12000 } }, [8] = { "filterFc", "i", { 1, 1500, 13500 } }, [9] = { "filterQ", "i", { 1, 0, 960 } }, [10] = { "modLfoToFilterFc", "i", { 1, -12000, 12000 } }, [11] = { "modEnvToFilterFc", "i", { 1, -12000, 12000 } }, [12] = { "stop", "a15" }, [13] = { "modLfoToVolume", "i", { 1, -960, 960 } }, [17] = { "pan", "f", { 0.001, -0.5, 0.5 } }, [21] = { "delayModLFO", "f", LIM12K5K }, [22] = { "freqModLFO", "i", { 1, -16000, 4500 } }, [23] = { "delayVibLFO", "f", LIM12K5K }, [24] = { "freqVibLFO", "i", { 1, -16000, 4500 } }, [25] = { "mDelay", "f", LIM12K5K }, [26] = { "mAttack", "f", LIM12K8K }, [27] = { "mHold", "f", LIM12K5K }, [28] = { "mDecay", "f", LIM12K8K }, [29] = { "mSustain", "f", { 1, 0, 1000 } }, [30] = { "mRelease", "f", LIM12K8K }, [31] = { "mKeyHold", "f", LIM1200 }, [32] = { "mKeyDecay", "f", LIM1200 }, [33] = { "aDelay", "f", LIM12K5K }, [34] = { "aAttack", "f", LIM12K8K }, [35] = { "aHold", "f", LIM12K5K }, [36] = { "aDecay", "f", LIM12K8K }, [37] = { "aSustain", "f", { 1, 0, 1440 } }, [38] = { "aRelease", "f", LIM12K8K }, [39] = { "aKeyHold", "f", LIM1200 }, [40] = { "aKeyDecay", "f", LIM1200 }, [43] = { "", "kr" }, [44] = { "", "vr" }, [45] = { "loopStart", "a15" }, [48] = { "attenuation", "f", { 0.04, 0, 57.6 } }, [50] = { "loopEnd", "a15" }, [51] = { "transpose", "i" }, [52] = { "tune", "i" }, [54] = { "loopMode", "loop" }, [56] = { "keytrack", "i" }, [57] = { "group", "group" }, [58] = { "keycenter", "key" }, } -- the merged fields: value generators once each (several ops share a field), then the four address fields local MERGE: { { any } } = {} do local seen: { [string]: boolean } = {} for op = 0, 58 do local g = GEN[op] if g and (g[2] == "f" or g[2] == "i" or g[2] == "a") and not seen[g[1]] then seen[g[1]] = true table.insert(MERGE, g) end end end local FIELDS = { "loopMode", "sampleRate", "lokey", "hikey", "lovel", "hivel", "group", "offset", "stop", "loopStart", "loopEnd", "transpose", "tune", "keycenter", "keytrack", "attenuation", "pan", "filterQ", "filterFc", "modEnvToPitch", "modEnvToFilterFc", "modLfoToFilterFc", "modLfoToVolume", "delayModLFO", "freqModLFO", "modLfoToPitch", "delayVibLFO", "freqVibLFO", "vibLfoToPitch", "aDelay", "aAttack", "aHold", "aDecay", "aSustain", "aRelease", "aKeyHold", "aKeyDecay", "mDelay", "mAttack", "mHold", "mDecay", "mSustain", "mRelease", "mKeyHold", "mKeyDecay", "sampleIndex", } -- clear(relative): tsf_region_clear. relative = a preset zone (all zero: values add to the instrument's) local function clear(relative: boolean): Region local r: Region = {} for _, f in FIELDS do r[f] = 0 end r.hikey, r.hivel, r.keycenter = 127, 127, 60 if relative then return r end r.keytrack = 100 r.keycenter = -1 for _, p in { "a", "m" } do for _, s in { "Delay", "Attack", "Hold", "Decay", "Release" } do r[p .. s] = -12000 end end r.filterFc = 13500 r.delayModLFO, r.delayVibLFO = -12000, -12000 return r end local function copy(r: Region): Region local c: Region = {} for k, v in r do c[k] = v end return c end -- the region defaults in absolute form (seconds, levels): what Fallback builds its regions from function Parse.defaultRegion(): Region local r = clear(false) r.keycenter = 60 for _, p in { "a", "m" } do for _, s in { "Delay", "Attack", "Hold", "Decay", "Release" } do r[p .. s] = 0 end end r.aSustain, r.mSustain = 1, 1 r.delayModLFO, r.delayVibLFO = 0, 0 return r end -- set one generator (tsf_region_operator with an amount); lo / hi = the two bytes, s = signed 16, w = unsigned 16 local function operator(r: Region, op: number, lo: number, hi: number, s: number, w: number) local g = GEN[op] if not g then return end local mode = g[2] if mode == "f" or mode == "i" then r[g[1]] = s elseif mode == "a" then r[g[1]] += s elseif mode == "a15" then r[g[1]] += s * 32768 elseif mode == "kr" then r.lokey, r.hikey = lo, hi elseif mode == "vr" then r.lovel, r.hivel = lo, hi elseif mode == "loop" then local m = w % 4 r.loopMode = if m == 3 then 2 elseif m == 1 then 1 else 0 elseif mode == "group" then r.group = w elseif mode == "key" then r.keycenter = s end end -- merge(zone, preset): zone += preset, then clamp (tsf_region_operator without an amount) local function merge(z: Region, p: Region) for _, g in MERGE do local f = g[1] local v = z[f] + p[f] local lim = g[3] if lim then v *= lim[1] v = math.clamp(v, lim[2], lim[3]) end z[f] = v end end local function tc2s(tc: number): number return 2 ^ (tc / 1200) end -- envtosecs (tsf_region_envtosecs): timecents to seconds; hold / decay stay in timecents when they scale by key local function envToSecs(r: Region, p: string, sustainIsGain: boolean) for _, s in { "Delay", "Attack", "Release" } do local v = r[p .. s] r[p .. s] = if v < -11950 then 0 else tc2s(v) end if r[p .. "KeyHold"] == 0 then local v = r[p .. "Hold"] r[p .. "Hold"] = if v < -11950 then 0 else tc2s(v) end if r[p .. "KeyDecay"] == 0 then local v = r[p .. "Decay"] r[p .. "Decay"] = if v < -11950 then 0 else tc2s(v) end local sus = r[p .. "Sustain"] if sus < 0 then sus = 0 elseif sustainIsGain then sus = if -sus / 10 > -100 then 10 ^ (-sus / 10 * 0.05) else 0 else sus = 1 - sus / 1000 end r[p .. "Sustain"] = sus end -- ------------------------------------------------------------------------------------------------ RIFF type Hydra = { [string]: { { number } } } -- record layouts: field byte widths (2 / 4 = little endian unsigned, -2 signed, 20 = name, 1 = byte, -1 = signed byte) local LAYOUT: { [string]: { number } } = { phdr = { 20, 2, 2, 2, 4, 4, 4 }, pbag = { 2, 2 }, pmod = { 2, 2, -2, 2, 2 }, pgen = { 2, 2 }, inst = { 20, 2 }, ibag = { 2, 2 }, imod = { 2, 2, -2, 2, 2 }, igen = { 2, 2 }, shdr = { 20, 4, 4, 4, 4, 4, 1, -1, 2, 2 }, } local RECSIZE: { [string]: number } = { phdr = 38, pbag = 4, pmod = 10, pgen = 4, inst = 22, ibag = 4, imod = 10, igen = 4, shdr = 46 } local INFO_NAMES = { isng = "engine", INAM = "name", irom = "rom", ICRD = "date", IENG = "author", IPRD = "product", ICOP = "copyright", ICMT = "comment", ISFT = "software", } export type Options = { maxRegions: number?, maxSamples: number? } -- parse(r, opts?) -> SoundFont | nil, Err function Parse.parse(r: Bytes.Reader, opts: Options?): (SoundFont?, Err.Err?) local maxRegions = opts and opts.maxRegions or 1000000 local maxSamples = opts and opts.maxSamples or 2 ^ 28 if r:string(4) ~= "RIFF" then return r:fail(Err.CORRUPT, "not a RIFF file") end local riffSize = r:u32le() if r:string(4) ~= "sfbk" then return r:fail(Err.CORRUPT, "not a SoundFont (no sfbk)") end if r.err then return nil, r.err end local body = r:sub(12, math.max(0, riffSize - 4)) local info: { [string]: string } = {} local hydra: Hydra = {} local smpl: Bytes.Reader? = nil local sm24: Bytes.Reader? = nil local version = "" while body:remaining() >= 8 do local id, size = body:string(4), body:u32le() local chunk = body:slice(size) if size % 2 == 1 and body:remaining() > 0 then body:skip(1) end if id == "LIST" and chunk:remaining() >= 4 then local kind = chunk:string(4) while chunk:remaining() >= 8 do local sid, ssize = chunk:string(4), chunk:u32le() local sub = chunk:slice(ssize) if ssize % 2 == 1 and chunk:remaining() > 0 then chunk:skip(1) end if kind == "INFO" then if sid == "ifil" and sub:remaining() >= 4 then local major, minor = sub:u16le(), sub:u16le() version = string.format("%d.%02d", major, minor) elseif INFO_NAMES[sid] then info[INFO_NAMES[sid]] = sub:fixed(sub:remaining()) end elseif kind == "sdta" then if sid == "smpl" and not smpl then smpl = sub elseif sid == "sm24" then sm24 = sub end elseif kind == "pdta" then local layout = LAYOUT[sid] if layout and not hydra[sid] then local rs = RECSIZE[sid] local n = sub:remaining() // rs local recs = table.create(n) :: { { number } } for i = 1, n do local rec = {} for _, w in layout do if w == 20 then table.insert(rec, 0) -- the name is read separately sub:skip(20) elseif w == 4 then table.insert(rec, sub:u32le()) elseif w == 2 then table.insert(rec, sub:u16le()) elseif w == -2 then table.insert(rec, sub:i16le()) elseif w == 1 then table.insert(rec, sub:u8()) else table.insert(rec, sub:i8()) end end recs[i] = rec end hydra[sid] = recs if sid == "phdr" or sid == "inst" or sid == "shdr" then local names = table.create(n) for i = 0, n - 1 do names[i + 1] = sub:sub(i * rs, 20):fixed(20) end hydra[sid .. "Names"] = names :: any end end end end end end if not smpl then return nil, Err.new(Err.CORRUPT, "no sample data (sdta smpl)") end for _, k in { "phdr", "pbag", "pgen", "inst", "ibag", "igen", "shdr" } do if not hydra[k] or #hydra[k] == 0 then return nil, Err.new(Err.CORRUPT, "incomplete hydra: no " .. k .. " records") end end -- samples local sr = smpl :: Bytes.Reader local count = sr:remaining() // 2 if count > maxSamples then return nil, Err.new(Err.LIMIT, string.format("%d samples is over the %d sample limit", count, maxSamples)) end local samples = buffer.create((count + 1) * 4) do local b, p = sr.buf, sr.pos local readi16, writef32 = buffer.readi16, buffer.writef32 local s24 = sm24 if s24 and s24:remaining() >= count then local q = s24.pos local readu8 = buffer.readu8 for i = 0, count - 1 do writef32(samples, i * 4, (readi16(b, p + i * 2) * 256 + readu8(s24.buf, q + i)) / 8388607) end else s24 = nil for i = 0, count - 1 do writef32(samples, i * 4, readi16(b, p + i * 2) / 32767) end end sm24 = s24 end -- presets (tsf_load_presets) local phdr, pbag, pgen = hydra.phdr, hydra.pbag, hydra.pgen local inst, ibag, igen, shdr = hydra.inst, hydra.ibag, hydra.igen, hydra.shdr local phdrNames, instNames, shdrNames = (hydra :: any).phdrNames, (hydra :: any).instNames, (hydra :: any).shdrNames local nInst = #inst - 1 -- the last record of each list is the terminal one local nShdr = #shdr - 1 local function range(list: { { number } }, i: number, field: number, limit: number): (number, number) -- [list[i][field], list[i + 1][field]) clamped to [1, limit] (1-based record indexes) local a = list[i][field] + 1 local b = if list[i + 1] then list[i + 1][field] + 1 else a return math.max(1, a), math.min(b, limit + 1) end local presets: { Preset } = {} local regionTotal = 0 for pi = 1, #phdr - 1 do local ph = phdr[pi] local preset: Preset = { name = phdrNames[pi], preset = ph[2], bank = ph[3], regions = {} } local globalRegion = clear(true) local b0, b1 = range(phdr, pi, 4, #pbag) for bi = b0, b1 - 1 do local presetRegion = copy(globalRegion) local hadInstrument = false local g0, g1 = range(pbag, bi, 1, #pgen) for gi = g0, g1 - 1 do local pg = pgen[gi] local op, amount = pg[1], pg[2] local lo, hi = amount % 256, amount // 256 local s = if amount >= 32768 then amount - 65536 else amount if op == GEN_INSTRUMENT then hadInstrument = true if amount < nInst then local instRegion = clear(false) local ib0, ib1 = range(inst, amount + 1, 2, #ibag) for ibi = ib0, ib1 - 1 do local zone = copy(instRegion) local hadSample = false local ig0, ig1 = range(ibag, ibi, 1, #igen) for igi = ig0, ig1 - 1 do local ig = igen[igi] local iop, iamt = ig[1], ig[2] if iop == GEN_SAMPLEID then hadSample = true if iamt >= nShdr then break end local ok = not (zone.hikey < presetRegion.lokey or zone.lokey > presetRegion.hikey) and not (zone.hivel < presetRegion.lovel or zone.lovel > presetRegion.hivel) if ok then local z = copy(zone) z.lokey = math.max(z.lokey, presetRegion.lokey) z.hikey = math.min(z.hikey, presetRegion.hikey) z.lovel = math.max(z.lovel, presetRegion.lovel) z.hivel = math.min(z.hivel, presetRegion.hivel) merge(z, presetRegion) envToSecs(z, "a", true) envToSecs(z, "m", false) z.delayModLFO = if z.delayModLFO < -11950 then 0 else tc2s(z.delayModLFO) z.delayVibLFO = if z.delayVibLFO < -11950 then 0 else tc2s(z.delayVibLFO) local sh = shdr[iamt + 1] local sStart, sEnd, sLoopStart, sLoopEnd = sh[2], sh[3], sh[4], sh[5] z.offset = math.clamp(z.offset + sStart, 0, count) local stop = z.stop + sEnd if stop > 0 and stop < count then stop += 1 else stop = count end z.stop = math.clamp(stop, 0, count) z.loopStart = math.clamp(z.loopStart + sLoopStart, 0, count) local le = z.loopEnd + sLoopEnd if sLoopEnd > 0 then le -= 1 end z.loopEnd = math.clamp(le, 0, count) if z.keycenter == -1 then z.keycenter = sh[7] end z.tune += sh[8] z.sampleRate = sh[6] z.sampleIndex = iamt regionTotal += 1 if regionTotal > maxRegions then return nil, Err.new(Err.LIMIT, "over " .. maxRegions .. " regions") end table.insert(preset.regions, z) end break -- sampleID ends a zone's generator list else local ilo, ihi = iamt % 256, iamt // 256 operator(zone, iop, ilo, ihi, if iamt >= 32768 then iamt - 65536 else iamt, iamt) end end if ibi == ib0 and not hadSample then instRegion = zone -- the instrument's global zone end end end break -- instrument ends a preset zone's generator list else operator(presetRegion, op, lo, hi, s, amount) end end if bi == b0 and not hadInstrument then globalRegion = presetRegion -- the preset's global zone end end table.insert(presets, preset) end -- sorted by bank, then preset, then file order (tsf's sortedIndex) for i, p in presets do (p :: any)._order = i end table.sort(presets, function(a: Preset, b: Preset): boolean if a.bank ~= b.bank then return a.bank < b.bank end if a.preset ~= b.preset then return a.preset < b.preset end return (a :: any)._order < (b :: any)._order end) for _, p in presets do (p :: any)._order = nil end local headers = table.create(nShdr) :: { { [string]: any } } for i = 1, nShdr do local sh = shdr[i] headers[i] = { name = shdrNames[i], start = sh[2], stop = sh[3], loopStart = sh[4], loopEnd = sh[5], sampleRate = sh[6], originalPitch = sh[7], pitchCorrection = sh[8], link = sh[9], type = sh[10], } end local instruments = table.create(nInst) :: { { name: string, zones: number } } for i = 1, nInst do instruments[i] = { name = instNames[i], zones = math.max(0, (inst[i + 1][2] or 0) - inst[i][2]) } end local sf: SoundFont = { kind = "soundfont", info = info, samples = samples, sampleCount = count, presets = presets, sampleHeaders = headers, instruments = instruments, meta = { source = { format = "sf2", version = version, sm24 = sm24 ~= nil } }, } return sf, nil end return Parse