diff --git a/licenses/TinySoundFont-LICENSE.txt b/licenses/TinySoundFont-LICENSE.txt new file mode 100644 index 0000000..bf4692a --- /dev/null +++ b/licenses/TinySoundFont-LICENSE.txt @@ -0,0 +1,22 @@ +TinySoundFont v0.9 (https://github.com/schellingb/TinySoundFont), tsf.h + +LICENSE (MIT) + +Copyright (C) 2017-2025 Bernhard Schelling +Based on SFZero, Copyright (C) 2012 Steve Folta (https://github.com/stevefolta/SFZero) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons +to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index ba09f70..0b33666 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -26,6 +26,30 @@ local list: { Entry } = { return require("@formats/image/png") end, }, + { + name = "midi", + category = "music", + path = "music/midi", + extensions = { "mid", "midi", "smf", "kar", "rmi" }, + mime = { "audio/midi", "audio/x-midi" }, + deps = { "core/Err", "core/Bytes", "codecs/SoundFont", "Types" }, + caps = { decode = true, encode = true, formats = { 0, 1, 2 }, render = true, streaming = true, rmid = true }, + load = function() + return require("@formats/music/midi") + end, + }, + { + name = "sf2", + category = "music", + path = "music/sf2", + extensions = { "sf2" }, + mime = { "audio/x-soundfont" }, + deps = { "core/Err", "core/Bytes", "codecs/SoundFont" }, + caps = { decode = true, encode = false, sm24 = true, sf3 = false }, + load = function() + return require("@formats/music/sf2") + end, + }, } return list diff --git a/src/Formats/Types.luau b/src/Formats/Types.luau index 9f37bd1..170314b 100644 --- a/src/Formats/Types.luau +++ b/src/Formats/Types.luau @@ -154,6 +154,7 @@ export type Midi = { division: number, -- ticks per quarter note (or SMPTE, negative) tracks: { { events: { MidiEvent }, name: string? } }, meta: { [string]: any }, + render: ((self: any, opts: any?) -> Decoder)?, -- set by music/midi decode: the SoundFont synth as an audio Decoder } local Midi = {} function Midi.new(division: number?): Midi diff --git a/src/Formats/codecs/SoundFont/Fallback.luau b/src/Formats/codecs/SoundFont/Fallback.luau new file mode 100644 index 0000000..ae8f8ca --- /dev/null +++ b/src/Formats/codecs/SoundFont/Fallback.luau @@ -0,0 +1,149 @@ +--!strict +-- codecs/SoundFont/Fallback: the built-in General MIDI set used when no SoundFont is given. A generated SoundFont +-- (the same shape Parse returns, so the same synth plays it): single-cycle sine / triangle / square / saw waves and a +-- looped noise sample, one preset per GM family of 8 programs (piano, chromatic percussion, organ, guitar, bass, +-- strings, ensemble, brass, reed, pipe, lead, pad, synth fx, ethnic, percussive, sound fx) with family envelopes, +-- filters and vibrato, plus a drum kit on bank 128 (pitch-swept sine kicks and toms, filtered noise snares, hats with +-- an exclusive class, cymbals). Written for this library (no third-party code). +local Parse = require("@formats/codecs/SoundFont/Parse") + +local Fallback = {} + +local CYCLE = 256 +local NOISE = 32768 +local C4 = 261.6255653005986 + +local function hzToCents(hz: number): number + return 1200 * math.log(hz / 8.176, 2) +end + +local cached: any = nil + +-- build() -> a SoundFont value (kind "soundfont"); built once, shared (the synth never writes to it) +function Fallback.build(): any + if cached then + return cached + end + local waves = { "sine", "triangle", "square", "saw" } + local count = #waves * CYCLE + NOISE + local samples = buffer.create((count + 1) * 4) + local starts: { [string]: number } = {} + for w, name in waves do + local base = (w - 1) * CYCLE + starts[name] = base + for i = 0, CYCLE - 1 do + local ph = i / CYCLE + local v + if name == "sine" then + v = math.sin(2 * math.pi * ph) + elseif name == "triangle" then + v = if ph < 0.25 then 4 * ph elseif ph < 0.75 then 2 - 4 * ph else 4 * ph - 4 + elseif name == "square" then + v = if ph < 0.5 then 0.6 else -0.6 + else + v = (1 - 2 * ph) * 0.7 + end + buffer.writef32(samples, (base + i) * 4, v) + end + end + local noiseStart = #waves * CYCLE + starts.noise = noiseStart + local seed = 12345 + for i = 0, NOISE - 1 do + seed = (seed * 1103515245 + 12345) % 2147483648 + buffer.writef32(samples, (noiseStart + i) * 4, (seed / 1073741824 - 1) * 0.7) + end + + local function region(wave: string, fields: { [string]: number }): { [string]: number } + local r = Parse.defaultRegion() + local s = starts[wave] + r.offset = s + r.loopMode = 1 + r.loopStart = s + if wave == "noise" then + r.stop, r.loopEnd, r.sampleRate, r.keycenter = s + NOISE, s + NOISE - 1, 44100, 60 + else + r.stop, r.loopEnd, r.sampleRate, r.keycenter = s + CYCLE, s + CYCLE - 1, CYCLE * C4, 60 + end + r.aRelease = 0.08 + for k, v in fields do + r[k] = v + end + return r + end + + -- the 16 GM families: wave + envelope / filter / vibrato + local families: { { any } } = { + { "piano", "triangle", { aDecay = 2.5, aSustain = 0, aRelease = 0.25 } }, + { "chromatic", "sine", { aDecay = 1.2, aSustain = 0, aRelease = 0.3 } }, + { "organ", "square", { aAttack = 0.005, aRelease = 0.05, filterFc = hzToCents(5000) } }, + { "guitar", "saw", { aDecay = 1.5, aSustain = 0, aRelease = 0.15, filterFc = hzToCents(3000) } }, + { "bass", "triangle", { aDecay = 1.5, aSustain = 0.4, aRelease = 0.1 } }, + { "strings", "saw", { aAttack = 0.08, aRelease = 0.3, filterFc = hzToCents(4000), freqVibLFO = hzToCents(5.5), vibLfoToPitch = 8, delayVibLFO = 0.2 } }, + { "ensemble", "saw", { aAttack = 0.12, aRelease = 0.4, filterFc = hzToCents(3500), freqVibLFO = hzToCents(5), vibLfoToPitch = 10 } }, + { "brass", "saw", { aAttack = 0.03, aRelease = 0.12, filterFc = hzToCents(1200), mAttack = 0.05, mDecay = 0.3, mSustain = 0.4, modEnvToFilterFc = 2400 } }, + { "reed", "square", { aAttack = 0.02, aRelease = 0.08, filterFc = hzToCents(2500) } }, + { "pipe", "sine", { aAttack = 0.04, aRelease = 0.12, freqVibLFO = hzToCents(5), vibLfoToPitch = 12, delayVibLFO = 0.3 } }, + { "lead", "square", { aAttack = 0.005, aRelease = 0.1, filterFc = hzToCents(6000) } }, + { "pad", "saw", { aAttack = 0.4, aRelease = 0.8, filterFc = hzToCents(1800), freqModLFO = hzToCents(0.5), modLfoToFilterFc = 600 } }, + { "synthfx", "triangle", { aAttack = 0.2, aRelease = 1.0, freqModLFO = hzToCents(3), modLfoToVolume = 60 } }, + { "ethnic", "saw", { aDecay = 1.0, aSustain = 0, aRelease = 0.2, filterFc = hzToCents(3000) } }, + { "percussive", "sine", { aDecay = 0.4, aSustain = 0, aRelease = 0.1, mDecay = 0.1, mSustain = 0, modEnvToPitch = 1200 } }, + { "sfx", "noise", { aAttack = 0.05, aRelease = 0.5, filterFc = hzToCents(3000) } }, + } + local presets = {} + for program = 0, 127 do + local f = families[program // 8 + 1] + table.insert(presets, { name = "fallback " .. f[1], preset = program, bank = 0, regions = { region(f[2], f[3]) } }) + end + + -- the drum kit (bank 128, every program): one region per key + local kit = {} + -- fields.semis: the pitch (semitones from the sample's natural pitch) at keytrack 0 + local function drum(lo: number, hi: number, wave: string, fields: { [string]: number }) + local r = region(wave, fields) + r.lokey, r.hikey = lo, hi + r.sampleRate *= 2 ^ ((fields.semis or 0) / 12) + r.semis = nil :: any + table.insert(kit, r) + end + local sweep = { mDecay = 0.06, mSustain = 0, modEnvToPitch = 2400 } + local function with(a: { [string]: number }, b: { [string]: number }): { [string]: number } + local c = table.clone(a) + for k, v in b do + c[k] = v + end + return c + end + drum(0, 34, "noise", { aDecay = 0.1, aSustain = 0, keytrack = 0, filterFc = hzToCents(4000) }) + drum(35, 36, "sine", with(sweep, { aDecay = 0.35, aSustain = 0, aRelease = 0.05, keytrack = 0, semis = -26 })) + drum(37, 37, "noise", { aDecay = 0.05, aSustain = 0, keytrack = 0, filterFc = hzToCents(5000) }) + drum(38, 38, "noise", { aDecay = 0.2, aSustain = 0, keytrack = 0, filterFc = hzToCents(6000) }) + drum(39, 39, "noise", { aDecay = 0.15, aSustain = 0, keytrack = 0, filterFc = hzToCents(8000) }) + drum(40, 40, "noise", { aDecay = 0.18, aSustain = 0, keytrack = 0, filterFc = hzToCents(7000) }) + for _, k in { 41, 43, 45, 47, 48, 50 } do + drum(k, k, "sine", with(sweep, { aDecay = 0.4, aSustain = 0, semis = (k - 41) - 12, keytrack = 0 })) + end + drum(42, 42, "noise", { aDecay = 0.05, aSustain = 0, group = 1, keytrack = 0, semis = 12 }) + drum(44, 44, "noise", { aDecay = 0.08, aSustain = 0, group = 1, keytrack = 0, semis = 12 }) + drum(46, 46, "noise", { aDecay = 0.45, aSustain = 0, group = 1, keytrack = 0, semis = 12 }) + drum(49, 49, "noise", { aDecay = 1.5, aSustain = 0, keytrack = 0, semis = 7 }) + drum(51, 51, "noise", { aDecay = 1.0, aSustain = 0, keytrack = 0, semis = 10, filterFc = hzToCents(9000) }) + drum(52, 59, "noise", { aDecay = 1.2, aSustain = 0, keytrack = 0, semis = 5 }) + drum(60, 127, "noise", { aDecay = 0.12, aSustain = 0, keytrack = 30, filterFc = hzToCents(5000) }) + table.insert(presets, { name = "fallback drums", preset = 0, bank = 128, regions = kit }) + + cached = { + kind = "soundfont", + info = { name = "formats-luau fallback" }, + samples = samples, + sampleCount = count, + presets = presets, + sampleHeaders = {}, + instruments = {}, + meta = { source = { format = "fallback" } }, + } + return cached +end + +return Fallback diff --git a/src/Formats/codecs/SoundFont/Parse.luau b/src/Formats/codecs/SoundFont/Parse.luau new file mode 100644 index 0000000..8e4f60a --- /dev/null +++ b/src/Formats/codecs/SoundFont/Parse.luau @@ -0,0 +1,523 @@ +--!strict +-- codecs/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_KEYRANGE, GEN_VELRANGE, GEN_SAMPLEID = 41, 43, 44, 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 = { 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) + 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) + 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) + 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 diff --git a/src/Formats/codecs/SoundFont/Synth.luau b/src/Formats/codecs/SoundFont/Synth.luau new file mode 100644 index 0000000..0bde0cd --- /dev/null +++ b/src/Formats/codecs/SoundFont/Synth.luau @@ -0,0 +1,797 @@ +--!strict +--!native +-- codecs/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): +-- voices with the DAHDSR volume envelope (exponential decay / release), the modulation envelope to pitch and filter +-- cutoff, the modulation and vibrato LFOs (triangle) to pitch / filter / volume, a resonant biquad low-pass, linear +-- interpolation, loop modes (none / continuous / until release), 3 dB pan law, exclusive classes; channels with +-- program / bank select (CC0 / CC32), drums (bank 128), pitch bend with RPN 0 range and RPN 1 / 2 tuning, CC7 volume, +-- CC10 pan, CC11 expression, CC64 sustain, CC120 / 121 / 123. Effects (reverb, chorus) and modulators are not +-- implemented (as in tsf.h). Output: interleaved stereo f32, mixed into the caller's buffer. +-- Differences from tsf.h: a voice limit (oldest release voice stolen, else the note is dropped), channels 0..15 only. +-- Native, never throws: every buffer index is in range by construction (the regions are clamped by Parse / Fallback, +-- the sample buffer has a zero pad sample, the output range is checked before mixing). +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, -- 1-based preset index, -1 = idle + key: number, + channel: number, + held: boolean, -- note off while sustain was down + region: { [string]: number }, + pitchIn: number, -- timecents + 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 }, -- bank * 128 + preset -> preset index + samples: buffer, + rate: number, + gainDB: number, + voices: { Voice }, + maxVoices: number, + playIndex: number, + channels: { Channel }, -- [1..16] = MIDI channels 0..15 +} + +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 + +-- ------------------------------------------------------------------------------------------------ envelope +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 + +-- ------------------------------------------------------------------------------------------------ filter / lfo +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 + +-- ------------------------------------------------------------------------------------------------ voices +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 -- keep playing, stop looping + 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 + +-- new(sf, sampleRate, opts) -> State. sf: { presets, samples } (Parse.parse or Fallback.build). +-- opts.gain: output gain (linear, default 0.5); opts.maxVoices (default 256) +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 + +-- noteOn(s, channel, key, velocity 0..127) +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 + +-- noteOff(s, channel, key): ends the oldest matching note (all its regions); held while sustain is down +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 + +-- program(s, channel, program): bank select + program change (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 + +-- pitchBend(s, channel, 0..16383) +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 + +-- control(s, channel, controller, value 0..127) +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 + +-- midi(s, status, d1, d2): one channel message +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 + +-- reset(s): all voices off, channels back to their defaults +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 + +-- active(s) -> the number of sounding voices +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 + +-- ------------------------------------------------------------------------------------------------ render +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 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 + local gl, gr = gainMono * v.panL, gainMono * v.panR + local k = block + while k > 0 and pos < endD do + k -= 1 + local ip = floor(pos) + local np = if ip >= loopEnd and isLooping then loopStart else ip + 1 + local s0 = readf32(input, ip * 4) + local val = s0 + (readf32(input, np * 4) - s0) * (pos - ip) + if lpActive then + local y = val * a0 + z1 + z1 = val * a1 + z2 - b1 * y + z2 = val * a0 - b2 * y + val = y + end + writef32(out, o, readf32(out, o) + val * gl) + writef32(out, o + 4, readf32(out, o + 4) + val * gr) + o += 8 + pos += pitchRatio + if pos >= loopEndD and isLooping then + pos -= loopLen + 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 + +-- render(s, out, frame, n): mixes n stereo frames into out (interleaved f32) starting at frame; out-of-range +-- requests are clipped to the buffer +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 (Parse / Fallback guarantee it; checked here + -- once so a hand-made SoundFont cannot index outside it) + 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 diff --git a/src/Formats/codecs/SoundFont/init.luau b/src/Formats/codecs/SoundFont/init.luau new file mode 100644 index 0000000..a1c8feb --- /dev/null +++ b/src/Formats/codecs/SoundFont/init.luau @@ -0,0 +1,69 @@ +--!strict +-- codecs/SoundFont: SoundFont 2 banks and the sample synth that plays MIDI through them. A codec (layer 1) shared by +-- music/sf2 (the file format) and music/midi (rendering). The synth is a port of TinySoundFont (tsf.h v0.9, MIT, +-- (c) 2017-2025 Bernhard Schelling; licenses/TinySoundFont-LICENSE.txt); see Parse / Synth for what is covered. +-- Without a bank, fallback() is a generated General MIDI set of simple waveforms (sine / triangle / square / saw / +-- noise) with a drum kit. +-- +-- local SoundFont = require("@formats/codecs/SoundFont") +-- local sf, err = SoundFont.parse(buf) -- buffer | string | core/Bytes Reader -> SoundFont | nil, Err +-- local sf = SoundFont.fallback() -- the built-in waveform set +-- local s = SoundFont.synth(sf, 44100, { gain = 0.5 }) -- a synth State; SoundFont.Synth.midi(s, 0x90, 60, 100) +-- SoundFont.Synth.render(s, out, frame, n) -- mix n stereo f32 frames into out at frame +-- +-- Never throws: bad data returns nil, Err. +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Parse = require("@formats/codecs/SoundFont/Parse") +local Synth = require("@formats/codecs/SoundFont/Synth") +local Fallback = require("@formats/codecs/SoundFont/Fallback") + +local SoundFont = {} + +export type SoundFont = Parse.SoundFont +export type State = Synth.State + +SoundFont.Synth = Synth +SoundFont.defaultRegion = Parse.defaultRegion + +-- sniff(r) -> true when r starts with RIFF....sfbk +function SoundFont.sniff(r: Bytes.Reader): boolean + return r:peek(4) == "RIFF" and r:peek(4, 8) == "sfbk" +end + +-- parse(src, opts?) -> SoundFont | nil, Err. src: buffer | string | Reader. opts.maxRegions (default 10^6), +-- opts.maxSamples (default 2^28) +function SoundFont.parse(src: any, opts: Parse.Options?): (SoundFont?, Err.Err?) + local r: Bytes.Reader + if type(src) == "string" then + r = Bytes.reader(buffer.fromstring(src)) + elseif type(src) == "buffer" then + r = Bytes.reader(src) + elseif type(src) == "table" and type(src.buf) == "buffer" then + r = Bytes.reader(src.buf, src.pos, src.limit - src.pos) + else + return nil, Err.new(Err.ARG, "soundfont: expected a buffer, string or Reader") + end + local ok, sf, err = pcall(Parse.parse, r, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "soundfont parser failed: " .. tostring(sf)) + end + return sf, err +end + +-- fallback() -> the built-in General MIDI waveform set +function SoundFont.fallback(): SoundFont + return Fallback.build() +end + +-- isSoundFont(v) -> true for a parsed / fallback SoundFont value +function SoundFont.isSoundFont(v: any): boolean + return type(v) == "table" and v.kind == "soundfont" and type(v.samples) == "buffer" and type(v.presets) == "table" +end + +-- synth(sf?, sampleRate?, opts?) -> State. opts.gain (linear, default 0.5), opts.maxVoices (default 256) +function SoundFont.synth(sf: SoundFont?, sampleRate: number?, opts: { gain: number?, maxVoices: number? }?): State + return Synth.new(sf or Fallback.build(), sampleRate or 44100, opts and opts.gain, opts and opts.maxVoices) +end + +return SoundFont diff --git a/src/Formats/music/midi/Render.luau b/src/Formats/music/midi/Render.luau new file mode 100644 index 0000000..657246a --- /dev/null +++ b/src/Formats/music/midi/Render.luau @@ -0,0 +1,261 @@ +--!strict +-- music/midi/Render: the tempo map (ticks -> seconds, as python mido computes lengths), the time-ordered event list, +-- and the audio Decoder that plays a Midi through codecs/SoundFont's synth (a SoundFont bank, or the built-in +-- waveform set). Format 0 / 1: one tempo map from every track's tempo events, tracks merged (ties keep track order). +-- Format 2: each track is its own song with its own tempo map, played one after another. +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local SoundFont = require("@formats/codecs/SoundFont") + +local Synth = SoundFont.Synth + +local Render = {} + +export type TempoMap = { ticks: { number }, secs: { number }, us: { number }, division: number } + +local STATUS = { noteOff = 0x80, noteOn = 0x90, aftertouch = 0xA0, controller = 0xB0, program = 0xC0, channelPressure = 0xD0, pitchBend = 0xE0 } + +local function tempoOf(ev: any): number? + if ev.type == "meta" and ev.meta == 0x51 and type(ev.data) == "table" and #ev.data >= 3 then + return ev.data[1] * 65536 + ev.data[2] * 256 + ev.data[3] + end + return nil +end + +-- tempoMap(midi, track?) -> TempoMap: from every track (format 0 / 1) or from one track (format 2) +function Render.tempoMap(midi: Types.Midi, track: number?): TempoMap + local changes: { { number } } = {} + for ti, t in midi.tracks do + if track == nil or track == ti then + for i, ev in t.events do + local us = tempoOf(ev) + if us then + table.insert(changes, { ev.tick, ti, i, us }) + end + end + end + end + table.sort(changes, function(a: { number }, b: { number }): boolean + if a[1] ~= b[1] then + return a[1] < b[1] + end + if a[2] ~= b[2] then + return a[2] < b[2] + end + return a[3] < b[3] + end) + local map: TempoMap = { ticks = { 0 }, secs = { 0 }, us = { 500000 }, division = midi.division } + local div = midi.division + for _, c in changes do + local n = #map.ticks + local tick = c[1] + local sec = map.secs[n] + (tick - map.ticks[n]) * map.us[n] * 1e-6 / div + if tick == map.ticks[n] then + map.us[n] = c[4] + else + table.insert(map.ticks, tick) + table.insert(map.secs, sec) + table.insert(map.us, c[4]) + end + end + return map +end + +-- seconds(map, tick) -> seconds (PPQ through the tempo map; SMPTE divisions are fixed time) +function Render.seconds(map: TempoMap, tick: number): number + local div = map.division + if div < 0 then + local fps = -(div // 256) + local tpf = div % 256 + if tpf == 0 then + return 0 + end + return tick / ((if fps == 29 then 29.97 else fps) * tpf) + end + local ticks = map.ticks + -- binary search for the last change at or before tick + local lo, hi = 1, #ticks + while lo < hi do + local mid = (lo + hi + 1) // 2 + if ticks[mid] <= tick then + lo = mid + else + hi = mid - 1 + end + end + return map.secs[lo] + (tick - ticks[lo]) * map.us[lo] * 1e-6 / div +end + +-- length(midi) -> seconds to the last event (format 2: the tracks one after another) +function Render.length(midi: Types.Midi): number + if #midi.tracks == 0 then + return 0 + end + if midi.format == 2 then + local total = 0 + for ti, t in midi.tracks do + local map = Render.tempoMap(midi, ti) + local last = 0 + for _, ev in t.events do + last = math.max(last, ev.tick) + end + total += Render.seconds(map, last) + end + return total + end + local map = Render.tempoMap(midi) + local last = 0 + for _, t in midi.tracks do + for _, ev in t.events do + last = math.max(last, ev.tick) + end + end + return Render.seconds(map, last) +end + +export type Timeline = { time: { number }, status: { number }, d1: { number }, d2: { number }, length: number } + +-- timeline(midi) -> the channel messages in play order with their times in seconds +function Render.timeline(midi: Types.Midi): Timeline + local items: { { any } } = {} + local offset = 0 + local function add(map: TempoMap, ti: number, t: any, base: number) + for i, ev in t.events do + local st = STATUS[ev.type] + if st and type(ev.data) == "table" then + local ch = ev.channel or 0 + table.insert(items, { base + Render.seconds(map, ev.tick), ti, i, st + ch % 16, ev.data[1] or 0, ev.data[2] or 0 }) + end + end + end + if midi.format == 2 then + for ti, t in midi.tracks do + local map = Render.tempoMap(midi, ti) + add(map, ti, t, offset) + local last = 0 + for _, ev in t.events do + last = math.max(last, ev.tick) + end + offset += Render.seconds(map, last) + end + else + local map = Render.tempoMap(midi) + for ti, t in midi.tracks do + add(map, ti, t, 0) + end + end + table.sort(items, function(a: { any }, b: { any }): boolean + if a[1] ~= b[1] then + return a[1] < b[1] + end + if a[2] ~= b[2] then + return a[2] < b[2] + end + return a[3] < b[3] + end) + local tl: Timeline = { time = table.create(#items), status = table.create(#items), d1 = table.create(#items), d2 = table.create(#items), length = Render.length(midi) } + for i, it in items do + tl.time[i], tl.status[i], tl.d1[i], tl.d2[i] = it[1], it[4], it[5] % 128, it[6] % 128 + end + return tl +end + +export type RenderOptions = { + sampleRate: number?, -- default 44100 + soundfont: any?, -- a SoundFont (music/sf2 decode, codecs/SoundFont.parse) or SF2 bytes (buffer / string); default the built-in waveforms + gain: number?, -- linear output gain, default 0.5 + tail: number?, -- seconds rendered after the last event (release tails), default 1 + maxVoices: number?, -- default 256 +} + +-- decoder(midi, opts?) -> Types.Decoder | nil, Err +function Render.decoder(midi: Types.Midi, opts: RenderOptions?): (Types.Decoder?, Err.Err?) + if type(midi) ~= "table" or type(midi.tracks) ~= "table" or type(midi.division) ~= "number" or midi.division == 0 then + return nil, Err.new(Err.ARG, "render: needs a Midi value") + end + local o: RenderOptions = opts or {} + local rate = o.sampleRate or 44100 + if type(rate) ~= "number" or rate < 1000 or rate > 384000 then + return nil, Err.new(Err.ARG, "render: sampleRate must be 1000..384000") + end + local sf = o.soundfont + if sf == nil then + sf = SoundFont.fallback() + elseif not SoundFont.isSoundFont(sf) then + local parsed, err = SoundFont.parse(sf) + if not parsed then + return nil, err + end + sf = parsed + end + local tl = Render.timeline(midi) + local tail = o.tail or 1 + local frames = math.max(0, math.ceil((tl.length + tail) * rate)) + local nev = #tl.time + local evFrame = table.create(nev) + for i = 1, nev do + evFrame[i] = math.floor(tl.time[i] * rate + 0.5) + end + local gain, maxVoices = o.gain, o.maxVoices + local state = Synth.new(sf, rate, gain, maxVoices) + local pos, nextEv = 0, 1 + + local dec = { + sampleRate = rate, + channels = 2, + frames = frames, + duration = frames / rate, + bitrate = 0, + tags = {} :: Types.Tags, + } + for _, t in midi.tracks do + if t.name and not dec.tags.title then + dec.tags.title = t.name + end + end + + local function read(_self: any, n: number, out: buffer?): (buffer, number) + n = math.max(0, math.min(math.floor(n), frames - pos)) + local buf = out + if not buf or buffer.len(buf) < n * 8 then + buf = buffer.create(math.max(n, 1) * 8) + end + local b = buf :: buffer + buffer.fill(b, 0, 0, n * 8) + local i = 0 + while i < n do + while nextEv <= nev and evFrame[nextEv] <= pos + i do + Synth.midi(state, tl.status[nextEv], tl.d1[nextEv], tl.d2[nextEv]) + nextEv += 1 + end + local stop = n + if nextEv <= nev then + stop = math.min(n, evFrame[nextEv] - pos) + end + if stop > i then + Synth.render(state, b, i, stop - i) + i = stop + end + end + pos += n + return b, n + end + dec.read = read :: any + local scratch = buffer.create(4096 * 8) + dec.seek = function(_self: any, seconds: number) + local target = math.clamp(math.floor((tonumber(seconds) or 0) * rate), 0, frames) + if target < pos then + Synth.reset(state) + pos, nextEv = 0, 1 + end + while pos < target do + read(nil, math.min(4096, target - pos), scratch) + end + end :: any + dec.position = function(_self: any): number + return pos / rate + end :: any + return (dec :: any) :: Types.Decoder, nil +end + +return Render diff --git a/src/Formats/music/midi/Smf.luau b/src/Formats/music/midi/Smf.luau new file mode 100644 index 0000000..4c0ec1f --- /dev/null +++ b/src/Formats/music/midi/Smf.luau @@ -0,0 +1,402 @@ +--!strict +-- music/midi/Smf: Standard MIDI File chunks <-> Types.Midi. Reads MThd / MTrk (formats 0, 1, 2; PPQ and SMPTE +-- divisions; running status, also across meta / sysex events as most players accept), skips unknown chunks, unwraps +-- RIFF RMID. Writes MThd + MTrk with optional running status; with running status on (the default) the bytes are +-- those python mido writes for the same events (running status reset after meta / sysex, one end-of-track at the +-- end, mid-track end-of-track events dropped). Written from the SMF 1.0 specification (no third-party code). +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") + +local Smf = {} + +local readu8 = buffer.readu8 + +local CHANNEL_TYPES = { [8] = "noteOff", [9] = "noteOn", [10] = "aftertouch", [11] = "controller", [12] = "program", [13] = "channelPressure", [14] = "pitchBend" } +local TYPE_STATUS = { noteOff = 0x80, noteOn = 0x90, aftertouch = 0xA0, controller = 0xB0, program = 0xC0, channelPressure = 0xD0, pitchBend = 0xE0 } +Smf.TYPE_STATUS = TYPE_STATUS + +export type ReadOptions = { + strict: boolean?, -- a truncated track / file is an error (default false: keep the events read so far, meta.truncated) + maxEvents: number?, -- default 2^24 +} +export type WriteOptions = { + runningStatus: boolean?, -- default true +} + +local function bytesOf(b: buffer, p: number, n: number): { number } + local t = table.create(n) + for i = 0, n - 1 do + t[i + 1] = readu8(b, p + i) + end + return t +end + +local function text(data: { number }): string + local parts = table.create(#data) + for i, c in data do + parts[i] = string.char(c) + end + return table.concat(parts) +end +Smf.text = text + +-- ------------------------------------------------------------------------------------------------ read +-- one MTrk body [p, e): events | nil, message, truncated +local function readTrack(b: buffer, p: number, e: number, budget: { number }): ({ Types.MidiEvent }?, string?, boolean) + local events: { Types.MidiEvent } = {} + local tick = 0 + local running = 0 + while p < e do + -- delta time + local delta, n = 0, 0 + repeat + if p >= e then + return events, nil, true + end + local c = readu8(b, p) + p += 1 + n += 1 + delta = delta * 128 + c % 128 + if n > 4 then + return nil, "delta time longer than 4 bytes", false + end + until c < 128 + tick += delta + if p >= e then + return events, nil, true + end + local status = readu8(b, p) + if status < 0x80 then + if running == 0 then + return nil, "running status without a previous status byte", false + end + status = running + else + p += 1 + if status < 0xF0 then + running = status + end + end + budget[1] -= 1 + if budget[1] < 0 then + return nil, "LIMIT", false + end + if status == 0xFF or status == 0xF0 or status == 0xF7 then + local mtype = 0 + if status == 0xFF then + if p >= e then + return events, nil, true + end + mtype = readu8(b, p) + p += 1 + end + local len, m = 0, 0 + repeat + if p >= e then + return events, nil, true + end + local c = readu8(b, p) + p += 1 + m += 1 + len = len * 128 + c % 128 + if m > 4 then + return nil, "length longer than 4 bytes", false + end + until c < 128 + if p + len > e then + return events, nil, true + end + local data = bytesOf(b, p, len) + p += len + if status == 0xFF then + table.insert(events, { tick = tick, type = "meta", meta = mtype, data = data }) + else + table.insert(events, { tick = tick, type = if status == 0xF0 then "sysex" else "escape", data = data }) + end + elseif status >= 0xF0 then + return nil, string.format("unexpected status byte 0x%02x in a track", status), false + else + local kind = status // 16 + local count = if kind == 12 or kind == 13 then 1 else 2 + if p + count > e then + return events, nil, true + end + local d1 = readu8(b, p) + local d2 = if count == 2 then readu8(b, p + 1) else 0 + if d1 >= 128 or d2 >= 128 then + return nil, "data byte over 127", false + end + p += count + table.insert(events, { + tick = tick, + type = CHANNEL_TYPES[kind], + channel = status % 16, + data = if count == 2 then { d1, d2 } else { d1 }, + }) + end + end + return events, nil, false +end + +-- read(r, opts?) -> Midi | nil, Err +function Smf.read(r: Bytes.Reader, opts: ReadOptions?): (Types.Midi?, Err.Err?) + local strict = opts and opts.strict or false + local budget = { opts and opts.maxEvents or 2 ^ 24 } + local b = r.buf + local base, limit = r.base, r.limit + local rmid = false + -- RIFF RMID: the SMF is the "data" chunk + if r:peek(4) == "RIFF" and r:peek(4, 8) == "RMID" then + local q = base + 12 + local found = false + while q + 8 <= limit do + local id = buffer.readstring(b, q, 4) + local size = buffer.readu32(b, q + 4) + if id == "data" then + base = q + 8 + limit = math.min(limit, base + size) + found = true + break + end + q += 8 + size + size % 2 + end + if not found then + return nil, Err.new(Err.CORRUPT, "RMID without a data chunk", r.base) + end + rmid = true + end + local h = Bytes.reader(b, base, limit - base) + if h:string(4) ~= "MThd" then + return nil, Err.new(Err.CORRUPT, "no MThd header", base) + end + local hlen = h:u32be() + local format, ntrks, division = h:u16be(), h:u16be(), h:i16be() + if h.err then + return nil, h.err + end + if hlen < 6 then + return nil, Err.new(Err.CORRUPT, "MThd shorter than 6 bytes", base + 4) + end + if format > 2 then + return nil, Err.new(Err.UNSUPPORTED, "SMF format " .. format, base + 8) + end + if division == 0 then + return nil, Err.new(Err.CORRUPT, "zero ticks per quarter note", base + 12) + end + local midi = Types.Midi.new(division) + midi.format = format + local truncated = false + local p = base + 8 + hlen + while #midi.tracks < ntrks and p + 8 <= limit do + local id = buffer.readstring(b, p, 4) + local size = bit32.byteswap(buffer.readu32(b, p + 4)) + local s = p + 8 + local e = s + size + if e > limit then + e = limit + truncated = true + end + if id == "MTrk" then + local events, msg, short = readTrack(b, s, e, budget) + if not events then + if msg == "LIMIT" then + return nil, Err.new(Err.LIMIT, "over the event limit") + end + return nil, Err.new(Err.CORRUPT, msg or "bad track", s) + end + truncated = truncated or short + local track: { events: { Types.MidiEvent }, name: string? } = { events = events, name = nil } + for _, ev in events do + if ev.type == "meta" and ev.meta == 3 then + track.name = text(ev.data :: { number }) + break + end + end + table.insert(midi.tracks, track) + end + p = s + size + end + if #midi.tracks < ntrks and p < limit then + truncated = true + elseif #midi.tracks < ntrks then + truncated = true + end + if truncated and strict then + return nil, Err.new(Err.TRUNCATED, "the file ends inside a track (or before all tracks)") + end + midi.meta.declaredTracks = ntrks + midi.meta.truncated = truncated + midi.meta.rmid = rmid + if division < 0 then + local fps = -(division // 256) + midi.meta.smpte = { fps = if fps == 29 then 29.97 else fps, ticksPerFrame = division % 256 } + end + return midi, nil +end + +-- ------------------------------------------------------------------------------------------------ write +local function vlq(w: Bytes.Writer, v: number) + if v < 128 then + w:u8(v) + return + end + local bytes = {} + while v > 0 do + table.insert(bytes, 1, v % 128) + v = v // 128 + end + for i, c in bytes do + w:u8(if i < #bytes then c + 128 else c) + end +end + +local function byteList(d: any, want: number?): { number }? + if type(d) ~= "table" then + return if want == 0 then {} else nil + end + for i, v in d do + if type(i) ~= "number" or type(v) ~= "number" or v < 0 or v > 255 or v % 1 ~= 0 then + return nil + end + end + if want and #d < want then + return nil + end + return d +end + +-- write(midi, opts?) -> buffer | nil, Err +function Smf.write(midi: Types.Midi, opts: WriteOptions?): (buffer?, Err.Err?) + if type(midi) ~= "table" or type(midi.tracks) ~= "table" then + return nil, Err.new(Err.ARG, "midi encode: needs a Midi value with tracks") + end + local running = not (opts and opts.runningStatus == false) + local format = midi.format or 1 + local division = midi.division or 480 + if type(format) ~= "number" or format < 0 or format > 2 or format % 1 ~= 0 then + return nil, Err.new(Err.ARG, "midi encode: format must be 0, 1 or 2") + end + if type(division) ~= "number" or division == 0 or division < -32768 or division > 32767 or division % 1 ~= 0 then + return nil, Err.new(Err.ARG, "midi encode: division must be a non-zero 16-bit integer") + end + if format == 0 and #midi.tracks ~= 1 then + return nil, Err.new(Err.ARG, "midi encode: format 0 needs exactly one track") + end + if #midi.tracks > 65535 then + return nil, Err.new(Err.ARG, "midi encode: too many tracks") + end + local w = Bytes.writer(1024) + w:string("MThd") + w:u32be(6) + w:u16be(format) + w:u16be(#midi.tracks) + w:u16be(if division < 0 then division + 65536 else division) + for ti, track in midi.tracks do + local events = if type(track) == "table" then track.events else nil + if type(events) ~= "table" then + return nil, Err.new(Err.ARG, "midi encode: track " .. ti .. " has no events list") + end + -- stable order by tick + local sorted = true + local last = 0 + for i, ev in events do + if type(ev) ~= "table" or type(ev.tick) ~= "number" or ev.tick < 0 or ev.tick % 1 ~= 0 then + return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d needs a whole non-negative tick", ti, i)) + end + if ev.tick < last then + sorted = false + end + last = ev.tick + end + local list = events + if not sorted then + list = table.clone(events) + local order: { [any]: number } = {} + for i, ev in list do + order[ev] = i + end + table.sort(list, function(a: any, c: any): boolean + if a.tick ~= c.tick then + return a.tick < c.tick + end + return order[a] < order[c] + end) + end + w:string("MTrk") + local lenAt = w:tell() + w:u32be(0) + local start = w:tell() + local prev = 0 + local status = 0 + local endTick = 0 + for i, ev in list do + local t = ev.type + endTick = ev.tick + if t == "meta" and ev.meta == 0x2F then + continue -- written once at the end + end + local delta = ev.tick - prev + if delta > 0x0FFFFFFF then + return nil, Err.new(Err.ARG, "midi encode: a delta time over 0x0FFFFFFF ticks") + end + local base = TYPE_STATUS[t] + if base then + local ch = ev.channel or 0 + if type(ch) ~= "number" or ch < 0 or ch > 15 or ch % 1 ~= 0 then + return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d: channel must be 0..15", ti, i)) + end + local n = if base == 0xC0 or base == 0xD0 then 1 else 2 + local d = byteList(ev.data, n) + if not d or d[1] > 127 or (n == 2 and d[2] > 127) then + return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d: %s needs %d data bytes 0..127", ti, i, t, n)) + end + vlq(w, delta) + local st = base + ch + if not (running and st == status) then + w:u8(st) + end + status = st + w:u8(d[1]) + if n == 2 then + w:u8(d[2]) + end + elseif t == "meta" or t == "sysex" or t == "escape" then + local d = byteList(ev.data, 0) + if not d then + return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d: data must be bytes", ti, i)) + end + vlq(w, delta) + if t == "meta" then + local m = ev.meta + if type(m) ~= "number" or m < 0 or m > 127 or m % 1 ~= 0 then + return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d: meta type must be 0..127", ti, i)) + end + w:u8(0xFF) + w:u8(m) + else + w:u8(if t == "sysex" then 0xF0 else 0xF7) + end + if #d > 0x0FFFFFFF then + return nil, Err.new(Err.ARG, "midi encode: event data too long") + end + vlq(w, #d) + for _, c in d do + w:u8(c) + end + status = 0 + else + return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d: unknown type %s", ti, i, tostring(t))) + end + prev = ev.tick + end + vlq(w, math.max(0, endTick - prev)) + w:u8(0xFF) + w:u8(0x2F) + w:u8(0) + w:setU32be(lenAt, w:tell() - start) + end + return w:finish(), nil +end + +return Smf diff --git a/src/Formats/music/midi/init.luau b/src/Formats/music/midi/init.luau new file mode 100644 index 0000000..fcaeb46 --- /dev/null +++ b/src/Formats/music/midi/init.luau @@ -0,0 +1,136 @@ +--!strict +-- music/midi: Standard MIDI Files (SMF 1.0: formats 0, 1 and 2; PPQ and SMPTE time; RIFF RMID read). Written from the +-- specification (no third-party code); rendering goes through codecs/SoundFont (a TinySoundFont port). +-- Supports: decode to a Types.Midi (absolute ticks; channel events noteOff / noteOn / aftertouch / controller / +-- program / channelPressure / pitchBend with their raw data bytes, sysex / escape with the bytes after the length, +-- meta events with meta = the meta type; meta.tempos / timeSignatures / keySignatures, track names), encode (running +-- status optional, byte-identical to python mido's writer by default), the tempo map (tickToSeconds, length), and +-- render / open: an audio Decoder (stereo f32) through an SF2 SoundFont (opts.soundfont) or the built-in waveform set. +-- Not supported: RMID write, XMF / RMI DLS banks, system common / realtime bytes inside tracks (CORRUPT). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Smf = require("@formats/music/midi/Smf") +local Render = require("@formats/music/midi/Render") + +-- ------------------------------------------------------------------------------------------------ contract +local Midi = { + name = "midi", + category = "music", + extensions = { "mid", "midi", "smf", "kar", "rmi" }, + mime = { "audio/midi", "audio/x-midi" }, + deps = { "core/Err", "core/Bytes", "codecs/SoundFont", "Types" }, + caps = { decode = true, encode = true, formats = { 0, 1, 2 }, render = true, streaming = true, rmid = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = Smf.ReadOptions -- strict (default false), maxEvents (default 2^24) +export type EncodeOptions = Smf.WriteOptions -- runningStatus (default true) +export type RenderOptions = Render.RenderOptions -- sampleRate, soundfont, gain, tail, maxVoices + +-- ------------------------------------------------------------------------------------------------ sniff +function Midi.sniff(r: Bytes.Reader): number + if r:peek(4) == "MThd" then + return 1 + end + if r:peek(4) == "RIFF" and r:peek(4, 8) == "RMID" then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function render(self: Types.Midi, opts: RenderOptions?): Types.Decoder + local dec, err = Render.decoder(self, opts) + if not dec then + -- the Types contract returns a Decoder; a failed render is an empty one (Midi.render returns the Err) + local empty: any = { + sampleRate = 44100, channels = 2, frames = 0, duration = 0, bitrate = 0, tags = {}, err = err, + read = function(_self: any, _n: number, out: buffer?): (buffer, number) + return out or buffer.create(0), 0 + end, + seek = function() end, + position = function(): number + return 0 + end, + } + return empty + end + return dec +end + +local function summarize(midi: Types.Midi) + local tempos, sigs, keys = {}, {}, {} + local map = Render.tempoMap(midi) + for ti, t in midi.tracks do + for _, ev in t.events do + if ev.type == "meta" then + local d = ev.data :: { number } + if ev.meta == 0x51 and #d >= 3 then + table.insert(tempos, { tick = ev.tick, track = ti, usPerQuarter = d[1] * 65536 + d[2] * 256 + d[3], bpm = 60000000 / math.max(1, d[1] * 65536 + d[2] * 256 + d[3]), seconds = Render.seconds(map, ev.tick) }) + elseif ev.meta == 0x58 and #d >= 4 then + table.insert(sigs, { tick = ev.tick, track = ti, numerator = d[1], denominator = 2 ^ math.min(d[2], 31), clocksPerClick = d[3], notated32ndsPerBeat = d[4] }) + elseif ev.meta == 0x59 and #d >= 2 then + table.insert(keys, { tick = ev.tick, track = ti, sharps = if d[1] >= 128 then d[1] - 256 else d[1], minor = d[2] == 1 }) + end + end + end + end + midi.meta.tempos = tempos + midi.meta.timeSignatures = sigs + midi.meta.keySignatures = keys + midi.meta.length = Render.length(midi) +end + +function Midi.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Midi?, Err.Err?) + local midi, err = Smf.read(r, opts) + if not midi then + return nil, err + end + summarize(midi) + midi.meta.source = { format = "midi", smf = midi.format } + midi.render = render + return midi, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Midi.encode(midi: Types.Midi, opts: EncodeOptions?): (buffer?, Err.Err?) + return Smf.write(midi, opts) +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> the rendered audio Decoder (opts: DecodeOptions + RenderOptions) +function Midi.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local midi, err = Midi.decode(r, opts) + if not midi then + return nil, err + end + return Render.decoder(midi, opts) +end + +-- ------------------------------------------------------------------------------------------------ extras +-- render(midi, opts?) -> Decoder | nil, Err (also works on a Midi built by hand with Types.Midi.new) +function Midi.render(midi: Types.Midi, opts: RenderOptions?): (Types.Decoder?, Err.Err?) + return Render.decoder(midi, opts) +end + +-- tickToSeconds(midi, tick, track?) -> seconds (track: format 2's per-track tempo map) +function Midi.tickToSeconds(midi: Types.Midi, tick: number, track: number?): number + return Render.seconds(Render.tempoMap(midi, track), tick) +end + +-- tempoMap(midi, track?) -> { ticks, secs, us, division } (change points) +Midi.tempoMap = Render.tempoMap +Midi.seconds = Render.seconds + +-- length(midi) -> seconds to the last event (what python mido's MidiFile.length reports for formats 0 / 1) +function Midi.length(midi: Types.Midi): number + return Render.length(midi) +end + +-- text(data) -> the bytes of a text meta event as a string +Midi.text = Smf.text + +return Midi diff --git a/src/Formats/music/sf2/init.luau b/src/Formats/music/sf2/init.luau new file mode 100644 index 0000000..a7fcc20 --- /dev/null +++ b/src/Formats/music/sf2/init.luau @@ -0,0 +1,44 @@ +--!strict +-- music/sf2: SoundFont 2 banks (SoundFont 2.04 specification), read-only. A thin wrapper over codecs/SoundFont (the +-- parser and the TinySoundFont-port synth music/midi renders with). Supports: INFO, 16-bit samples (+ sm24 24-bit), +-- presets / instruments / sample headers with global zones, generator merging into playable regions. +-- Not supported: writing, SF3 (Ogg Vorbis samples), modulators (read past, not applied). +-- decode returns the SoundFont value (kind "soundfont"): pass it to music/midi render as opts.soundfont. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local SoundFont = require("@formats/codecs/SoundFont") + +-- ------------------------------------------------------------------------------------------------ contract +local Sf2 = { + name = "sf2", + category = "music", + extensions = { "sf2" }, + mime = { "audio/x-soundfont" }, + deps = { "core/Err", "core/Bytes", "codecs/SoundFont" }, + caps = { decode = true, encode = false, sm24 = true, sf3 = false }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + maxRegions: number?, -- default 10^6 + maxSamples: number?, -- default 2^28 +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Sf2.sniff(r: Bytes.Reader): number + return if SoundFont.sniff(r) then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Sf2.decode(r: Bytes.Reader, opts: DecodeOptions?): (SoundFont.SoundFont?, Err.Err?) + return SoundFont.parse(r, opts) +end + +-- ------------------------------------------------------------------------------------------------ extras +-- synth(sf?, sampleRate?, opts?) -> a synth State (codecs/SoundFont.Synth drives it) +Sf2.synth = SoundFont.synth +Sf2.fallback = SoundFont.fallback + +return Sf2 diff --git a/tests/music/midi.luau b/tests/music/midi.luau new file mode 100644 index 0000000..a906337 --- /dev/null +++ b/tests/music/midi.luau @@ -0,0 +1,272 @@ +-- music/midi tests: SMF formats 0 / 1 / 2 + SMPTE + RMID parsed exactly as python mido parses them, mido's own files +-- re-encoded byte for byte, round trips without running status, the tempo map against mido's message times and +-- lengths, meta summaries, crafted bad files, truncation (lenient / strict), the fallback-synth render (duration, +-- level, seek), and the fuzz no-throw pass (decode, and decode + a short render). Fixtures: tools/fixtures/midi.py. +local T = require("@tests/T") +local Midi = require("@formats/music/midi") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Cases = require("@tests/gen/midi_cases") +local Bad = require("@tests/gen/midi_bad") +local Trunc = require("@tests/gen/midi_trunc") + +local t = T.suite("midi") + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return Midi.decode(Bytes.reader(b), opts) +end + +-- the contract +t:eq(Midi.name, "midi", "name") +t:eq(Midi.category, "music", "category") +t:check(table.find(Midi.extensions, "mid") ~= nil, "extensions") +t:check(Midi.caps.decode and Midi.caps.encode, "caps") +t:eq(Midi.sniff(Bytes.reader(buffer.fromstring("MThd\0\0\0\6"))), 1, "sniff MThd") +t:eq(Midi.sniff(Bytes.reader(buffer.fromstring("RIFF\0\0\0\0RMID"))), 1, "sniff RMID") +t:eq(Midi.sniff(Bytes.reader(buffer.fromstring("RIFF\0\0\0\0WAVE"))), 0, "sniff WAVE") + +local function sameEvents(got: { any }, want: { any }, label: string) + t:eq(#got, #want, label .. ": event count") + for i, w in want do + local g = got[i] + local l = label .. " event " .. i + t:eq(g.tick, w[1], l .. " tick") + t:eq(g.type, w[2], l .. " type") + t:eq(g.channel or -1, w[3], l .. " channel") + t:eq(if g.type == "meta" then g.meta else -1, w[5], l .. " meta type") + local d = g.data or {} + t:eq(#d, #w[4], l .. " data length") + for k, v in w[4] do + if d[k] ~= v then + t:eq(d[k], v, l .. " data byte " .. k) + end + end + end +end + +local function trackEvents(m: any): { { any } } + local out = {} + for ti, tr in m.tracks do + local evs = {} + for _, ev in tr.events do + table.insert(evs, { ev.tick, ev.type, ev.channel or -1, ev.data or {}, if ev.type == "meta" then ev.meta else -1 }) + end + out[ti] = evs + end + return out +end + +local byName = {} +for _, c in Cases do + byName[c.name] = c + local m, err = decode(c.data) + t:check(m, c.name .. ": " .. tostring(err)) + t:eq(m.kind, "midi", c.name .. ": kind") + t:eq(m.format, c.type, c.name .. ": format") + t:eq(m.division, c.division, c.name .. ": division") + t:eq(#m.tracks, #c.tracks, c.name .. ": tracks") + for ti, want in c.tracks do + sameEvents(m.tracks[ti].events, want, c.name .. " track " .. ti) + end + -- mido's own bytes come back exactly (running status as mido writes it) + if c.exact then + local out, eerr = Midi.encode(m) + t:check(out, c.name .. ": encode " .. tostring(eerr)) + t:eq(buffer.tostring(out :: buffer) == c.data, true, c.name .. ": re-encoded bytes equal mido's") + end + -- without running status: longer (or equal), and the same events + local plain = Midi.encode(m, { runningStatus = false }) :: buffer + local withRs = Midi.encode(m) :: buffer + t:check(buffer.len(plain) >= buffer.len(withRs), c.name .. ": running status saves bytes") + local back = decode(plain) + t:check(back, c.name .. ": re-decode") + for ti, want in trackEvents(m) do + sameEvents(back.tracks[ti].events, want, c.name .. " round trip track " .. ti) + end + -- tempo map: every event's time against mido's merged message times + if c.times then + local secs = {} + for _, tr in m.tracks do + for _, ev in tr.events do + if not (ev.type == "meta" and ev.meta == 0x2F) then -- mido merges the end-of-track events into one + table.insert(secs, Midi.tickToSeconds(m, ev.tick)) + end + end + end + table.sort(secs) + t:eq(#secs, #c.times - 1, c.name .. ": event count vs mido") + local worst = 0 + for i, s in secs do + worst = math.max(worst, math.abs(s - c.times[i])) + end + t:check(worst < 1e-6, c.name .. ": event times match mido (worst " .. worst .. " s)") + t:check(math.abs(Midi.length(m) - c.length) < 1e-6, c.name .. ": length " .. Midi.length(m) .. " vs mido " .. c.length) + t:check(math.abs(m.meta.length - c.length) < 1e-6, c.name .. ": meta.length") + end +end +t:note("%d files parse as mido parses them; mido's files re-encode byte for byte", #Cases) + +-- meta summaries +do + local m = decode(byName.format0.data) + t:eq(m.tracks[1].name, "format zero", "track name") + t:eq(#m.meta.tempos, 3, "tempo changes") + t:eq(m.meta.tempos[1].usPerQuarter, 500000, "first tempo") + t:eq(m.meta.tempos[1].bpm, 120, "bpm") + t:eq(#m.meta.timeSignatures, 2, "time signatures") + t:eq(m.meta.timeSignatures[1].numerator, 3, "3/4 numerator") + t:eq(m.meta.timeSignatures[1].denominator, 4, "3/4 denominator") + t:eq(m.meta.timeSignatures[2].denominator, 8, "6/8 denominator") + t:eq(m.meta.keySignatures[1].sharps, -3, "Eb: 3 flats") + t:eq(m.meta.keySignatures[1].minor, false, "Eb major") + local s = decode(byName.smpte.data) + t:eq(s.meta.smpte.fps, 25, "smpte fps") + t:eq(s.meta.smpte.ticksPerFrame, 40, "smpte ticks per frame") + t:check(math.abs(Midi.tickToSeconds(s, 1000) - 1) < 1e-12, "smpte: 1000 ticks at 25 x 40 = 1 s") + t:eq(decode(byName.rmid.data).meta.rmid, true, "rmid flag") + -- format 2: per-track tempo maps, the tracks one after another + local f2 = decode(byName.format2.data) + local total = 0 + for ti, tr in f2.tracks do + local last = tr.events[#tr.events].tick + total += Midi.tickToSeconds(f2, last, ti) + end + t:check(math.abs(Midi.length(f2) - total) < 1e-9, "format 2 length = the tracks in sequence") +end + +-- a value built by hand: unsorted events are written in tick order, end of track added, bad values refused +do + local m = Types.Midi.new(96) + m.format = 0 + m.tracks[1] = { events = { + { tick = 50, type = "noteOff", channel = 2, data = { 60, 0 } }, + { tick = 0, type = "noteOn", channel = 2, data = { 60, 100 } }, + { tick = 50, type = "meta", meta = 0x2F, data = {} }, + { tick = 20, type = "controller", channel = 2, data = { 64, 127 } }, + } } + local b = Midi.encode(m) :: buffer + local back = decode(b) + sameEvents(back.tracks[1].events, { + { 0, "noteOn", 2, { 60, 100 }, -1 }, { 20, "controller", 2, { 64, 127 }, -1 }, { 50, "noteOff", 2, { 60, 0 }, -1 }, + { 50, "meta", -1, {}, 0x2F }, + }, "sorted on write") + local function refuses(mut: (any) -> (), label: string) + local x = Types.Midi.new(96) + x.tracks[1] = { events = { { tick = 0, type = "noteOn", channel = 0, data = { 60, 100 } } } } + mut(x) + local out, err = Midi.encode(x) + t:check(out == nil and Err.is(err) and err.code == Err.ARG, "encode refuses " .. label) + end + refuses(function(x) x.tracks[1].events[1].channel = 16 end, "channel 16") + refuses(function(x) x.tracks[1].events[1].data = { 60, 128 } end, "data byte 128") + refuses(function(x) x.tracks[1].events[1].tick = -1 end, "negative tick") + refuses(function(x) x.tracks[1].events[1].type = "wobble" end, "unknown type") + refuses(function(x) x.division = 0 end, "zero division") + refuses(function(x) x.format = 0; x.tracks[2] = { events = {} } end, "format 0 with two tracks") + local nope, nerr = Midi.encode(nil :: any) + t:check(nope == nil and nerr.code == Err.ARG, "encode refuses nil") +end + +-- crafted bad files +for _, c in Bad do + local ok, m, err = pcall(decode, c.data) + t:check(ok, c.name .. ": threw " .. tostring(m)) + t:check(m == nil and Err.is(err), c.name .. ": decoded") + t:eq(err.code, c.code, c.name .. ": error code (" .. tostring(err) .. ")") +end + +-- truncation: lenient keeps what it read, strict fails +do + local m = decode(Trunc.data) + t:check(m and m.meta.truncated, "truncated file decodes leniently, flagged") + local n = 0 + for _, tr in m.tracks do + n += #tr.events + end + t:check(n > 50, "truncated file keeps its events (" .. n .. ")") + local s, err = decode(Trunc.data, { strict = true }) + t:check(s == nil and err.code == Err.TRUNCATED, "strict: TRUNCATED") + t:eq(decode(byName.format1.data, { strict = true }).meta.truncated, false, "strict: a whole file passes") + local l, lerr = decode(byName.random.data, { maxEvents = 100 }) + t:check(l == nil and lerr.code == Err.LIMIT, "maxEvents: LIMIT") +end + +-- render through the built-in waveform set +do + local song = decode(byName.song.data) + local dec = song:render({ tail = 0.5 }) + local want = math.ceil((byName.song.length + 0.5) * 44100) + t:eq(dec.frames, want, "render: frames = (length + tail) * rate") + t:eq(dec.channels, 2, "render: stereo") + t:eq(dec.sampleRate, 44100, "render: rate") + local total, sumsq, peak = 0, 0, 0 + local out = buffer.create(4096 * 8) + while true do + local b, n = dec:read(4096, out) + if n == 0 then + break + end + for i = 0, n * 2 - 1 do + local v = buffer.readf32(b, i * 4) + sumsq += v * v + peak = math.max(peak, math.abs(v)) + end + total += n + end + t:eq(total, want, "render: reads every frame") + local rms = math.sqrt(sumsq / (total * 2)) + t:check(rms > 0.01 and peak < 4 and peak == peak, string.format("render: audible and sane (rms %.3f, peak %.3f)", rms, peak)) + t:note("fallback render: %.2f s, rms %.3f, peak %.3f", total / 44100, rms, peak) + -- seek: the same samples as playing through + local a = song:render({ tail = 0.5 }) + a:seek(1.5) + t:check(math.abs(a:position() - 1.5) < 1e-4, "seek position") + local x = buffer.create(1024 * 8) + a:read(1024, x) + local c = song:render({ tail = 0.5 }) + c:read(66150) + local y = c:read(1024) + local same = true + for i = 0, 2047 do + if buffer.readf32(x, i * 4) ~= buffer.readf32(y, i * 4) then + same = false + break + end + end + t:check(same, "seek renders the same samples as reading through") + a:seek(0.25) -- backwards + t:check(math.abs(a:position() - 0.25) < 1e-4, "seek backwards") + -- open = decode + render + local o = Midi.open(Bytes.reader(buffer.fromstring(byName.song.data)), { sampleRate = 22050, tail = 0 }) + t:check(o and o.sampleRate == 22050, "open: a Decoder at the asked rate") + local bad, berr = Midi.render(song, { sampleRate = 5 }) + t:check(bad == nil and berr.code == Err.ARG, "render: bad sampleRate") + local bs, bserr = Midi.render(song, { soundfont = "not a soundfont" }) + t:check(bs == nil and Err.is(bserr), "render: bad soundfont bytes") +end + +-- the fuzz no-throw pass +local samples = {} +for _, c in Cases do + if #c.data < 20000 then + table.insert(samples, c.data) + end +end +t:fuzz("decode", function(b: buffer) + return decode(b) +end, samples, { mutations = 40 }) +t:fuzz("decode + render", function(b: buffer) + local m = decode(b) + if m then + local dec = Midi.render(m, { tail = 0.1 }) + if dec then + dec:read(2048) + dec:read(2048) + end + Midi.encode(m) + end +end, samples, { mutations = 20, garbage = 50 }) + +t:done() diff --git a/tools/fixtures/_midi_ref.py b/tools/fixtures/_midi_ref.py new file mode 100644 index 0000000..dd17630 --- /dev/null +++ b/tools/fixtures/_midi_ref.py @@ -0,0 +1,183 @@ +# MIDI reference cases (run by tools/fixtures/midi.py through ctx.python(["mido"], ...); not a generator itself). +# Builds Standard MIDI Files with python mido (formats 0 / 1 / 2, tempo changes, time / key signatures, running +# status, sysex, pitch bend, every channel message, a random stress file), saves them with mido, and prints JSON: +# per file the bytes, mido's parse in formats-luau's event shape and mido's lengths / message times. +import io, json, random, sys +import mido +from mido import Message, MetaMessage, MidiFile, MidiTrack + + +def ours(msg): + """a mido message -> [type, channel, data, meta] in formats-luau's shape (data = raw bytes)""" + t = msg.type + if msg.is_meta: + b = msg.bytes() + i = 2 + while b[i] & 0x80: + i += 1 + return ["meta", -1, list(b[i + 1:]), b[1]] + if t == "sysex": + return ["sysex", -1, list(msg.data) + [0xF7], -1] + if t == "note_on": + return ["noteOn", msg.channel, [msg.note, msg.velocity], -1] + if t == "note_off": + return ["noteOff", msg.channel, [msg.note, msg.velocity], -1] + if t == "polytouch": + return ["aftertouch", msg.channel, [msg.note, msg.value], -1] + if t == "control_change": + return ["controller", msg.channel, [msg.control, msg.value], -1] + if t == "program_change": + return ["program", msg.channel, [msg.program], -1] + if t == "aftertouch": + return ["channelPressure", msg.channel, [msg.value], -1] + if t == "pitchwheel": + v = msg.pitch + 8192 + return ["pitchBend", msg.channel, [v & 127, v >> 7], -1] + raise ValueError(t) + + +def describe(name, mid): + buf = io.BytesIO() + mid.save(file=buf) + data = buf.getvalue() + back = MidiFile(file=io.BytesIO(data)) + tracks = [] + for tr in back.tracks: + tick, evs = 0, [] + for msg in tr: + tick += msg.time + evs.append([tick] + ours(msg)) + tracks.append(evs) + case = {"name": name, "hex": data.hex(), "type": back.type, "division": back.ticks_per_beat, "tracks": tracks} + if back.type != 2 and back.ticks_per_beat > 0: + case["length"] = back.length + t, times = 0.0, [] + for msg in back: + t += msg.time + times.append(t) + case["times"] = times + return case + + +def notes(track, ch, rng, n, prog=None, start=0): + if prog is not None: + track.append(Message("program_change", channel=ch, program=prog, time=start)) + start = 0 + for i in range(n): + note = rng.randint(30, 90) + track.append(Message("note_on", channel=ch, note=note, velocity=rng.randint(1, 127), time=start if i == 0 else rng.randint(0, 120))) + track.append(Message("note_off", channel=ch, note=note, velocity=rng.randint(0, 127), time=rng.randint(1, 480))) + + +cases = [] +rng = random.Random(7) + +# format 0: one track with everything +mid = MidiFile(type=0, ticks_per_beat=480) +t = MidiTrack() +mid.tracks.append(t) +t.append(MetaMessage("track_name", name="format zero")) +t.append(MetaMessage("set_tempo", tempo=500000)) +t.append(MetaMessage("time_signature", numerator=3, denominator=4, clocks_per_click=24, notated_32nd_notes_per_beat=8)) +t.append(MetaMessage("key_signature", key="Eb")) +t.append(MetaMessage("text", text="hello")) +t.append(Message("program_change", channel=0, program=5)) +t.append(Message("control_change", channel=0, control=7, value=100)) +t.append(Message("control_change", channel=0, control=10, value=20)) +t.append(Message("note_on", channel=0, note=60, velocity=100, time=0)) +t.append(Message("note_on", channel=0, note=64, velocity=90, time=10)) # running status +t.append(Message("note_on", channel=0, note=67, velocity=80, time=10)) +t.append(Message("pitchwheel", channel=0, pitch=-8192, time=100)) +t.append(Message("pitchwheel", channel=0, pitch=8191, time=100)) +t.append(Message("pitchwheel", channel=0, pitch=0, time=100)) +t.append(Message("polytouch", channel=0, note=60, value=33, time=5)) +t.append(Message("aftertouch", channel=0, value=44, time=5)) +t.append(Message("sysex", data=[0x7E, 0x7F, 0x09, 0x01], time=0)) +t.append(MetaMessage("set_tempo", tempo=300000, time=240)) +t.append(Message("note_off", channel=0, note=60, velocity=0, time=480)) +t.append(Message("note_on", channel=0, note=64, velocity=0, time=0)) # note on, velocity 0 +t.append(Message("note_off", channel=0, note=67, velocity=64, time=0)) +t.append(Message("note_on", channel=9, note=36, velocity=127, time=100)) +t.append(Message("note_off", channel=9, note=36, velocity=0, time=100)) +t.append(MetaMessage("time_signature", numerator=6, denominator=8, time=0)) +t.append(MetaMessage("set_tempo", tempo=1000000, time=10)) +t.append(Message("note_on", channel=1, note=72, velocity=50, time=0)) +t.append(Message("note_off", channel=1, note=72, velocity=50, time=960)) +cases.append(describe("format0", mid)) + +# format 1: a conductor track + 3 instrument tracks, tempo changes in the conductor +mid = MidiFile(type=1, ticks_per_beat=96) +cond = MidiTrack() +mid.tracks.append(cond) +cond.append(MetaMessage("track_name", name="conductor")) +cond.append(MetaMessage("time_signature", numerator=4, denominator=4)) +for i, tempo in enumerate([500000, 400000, 600000, 250000, 750000]): + cond.append(MetaMessage("set_tempo", tempo=tempo, time=0 if i == 0 else 384)) +for ch in range(3): + tr = MidiTrack() + mid.tracks.append(tr) + tr.append(MetaMessage("track_name", name="part %d" % ch)) + notes(tr, ch, rng, 40, prog=ch * 10) +cases.append(describe("format1", mid)) + +# format 2: independent patterns, each with its own tempo +mid = MidiFile(type=2, ticks_per_beat=240) +for k in range(3): + tr = MidiTrack() + mid.tracks.append(tr) + tr.append(MetaMessage("set_tempo", tempo=400000 + 100000 * k)) + notes(tr, k, rng, 10) +cases.append(describe("format2", mid)) + +# a random stress file: many tracks / channels / controller streams (long running-status runs) +mid = MidiFile(type=1, ticks_per_beat=480) +for k in range(6): + tr = MidiTrack() + mid.tracks.append(tr) + if k == 0: + for j in range(20): + tr.append(MetaMessage("set_tempo", tempo=rng.randint(200000, 1500000), time=rng.randint(0, 2000))) + continue + ch = rng.randint(0, 15) + for j in range(400): + r = rng.random() + dt = rng.choice([0, 0, 1, 7, 120, 480, 20000]) + if r < 0.4: + tr.append(Message("note_on", channel=ch, note=rng.randint(0, 127), velocity=rng.randint(0, 127), time=dt)) + elif r < 0.6: + tr.append(Message("note_off", channel=ch, note=rng.randint(0, 127), velocity=rng.randint(0, 127), time=dt)) + elif r < 0.8: + tr.append(Message("control_change", channel=ch, control=rng.randint(0, 127), value=rng.randint(0, 127), time=dt)) + elif r < 0.9: + tr.append(Message("pitchwheel", channel=ch, pitch=rng.randint(-8192, 8191), time=dt)) + elif r < 0.95: + tr.append(Message("program_change", channel=ch, program=rng.randint(0, 127), time=dt)) + else: + tr.append(Message("sysex", data=[rng.randint(0, 127) for _ in range(rng.randint(0, 200))], time=dt)) +cases.append(describe("random", mid)) + +# SMPTE time (25 fps, 40 ticks per frame): division = -(25 << 8) + 40 as a signed 16-bit value +mid = MidiFile(type=0, ticks_per_beat=-6360) +t = MidiTrack() +mid.tracks.append(t) +t.append(Message("note_on", note=60, velocity=64, time=0)) +t.append(Message("note_off", note=60, velocity=64, time=1000)) +cases.append(describe("smpte", mid)) + +# the song the fallback / SoundFont render tests play (tools/fixtures/sf2.py has its own); its mido length +mid = MidiFile(type=1, ticks_per_beat=480) +cond = MidiTrack() +mid.tracks.append(cond) +cond.append(MetaMessage("set_tempo", tempo=500000)) +cond.append(MetaMessage("set_tempo", tempo=250000, time=1920)) +tr = MidiTrack() +mid.tracks.append(tr) +notes(tr, 0, rng, 12, prog=0) +dr = MidiTrack() +mid.tracks.append(dr) +for k in range(16): + dr.append(Message("note_on", channel=9, note=[36, 38, 42, 46][k % 4], velocity=110, time=0 if k == 0 else 120)) + dr.append(Message("note_off", channel=9, note=[36, 38, 42, 46][k % 4], velocity=0, time=120)) +cases.append(describe("song", mid)) + +json.dump(cases, sys.stdout) diff --git a/tools/fixtures/midi.py b/tools/fixtures/midi.py new file mode 100644 index 0000000..d1f47c5 --- /dev/null +++ b/tools/fixtures/midi.py @@ -0,0 +1,72 @@ +# MIDI fixtures (tools/fixtures.py). Reference parses from python mido (tools/fixtures/_midi_ref.py, run in a nix +# python with mido) plus hand-made byte strings for what mido does not write. +# tests/gen/midi_cases.luau { { name, data, type, division, tracks = { { {tick, type, channel, data, meta} } }, +# length?, times?, exact? } }: channel / meta = -1 when absent; exact = the bytes are +# what an encoder with running status writes (mido's own output) +# tests/gen/midi_bad.luau { { name, data, code } }: crafted bad files and the Err code expected +# tests/gen/midi_trunc.luau { name, data }: a mido file cut short (lenient decode keeps the events, strict fails) +import json, struct + +INPUTS = ["tools/fixtures/_midi_ref.py"] + + +def vlq(v): + out = [v & 127] + v >>= 7 + while v: + out.insert(0, (v & 127) | 128) + v >>= 7 + return bytes(out) + + +def smf(tracks, fmt=0, division=96, extra=b""): + out = b"MThd" + struct.pack(">IHHh", 6, fmt, len(tracks), division) + extra + for body in tracks: + out += b"MTrk" + struct.pack(">I", len(body)) + body + return out + + +def generate(ctx): + ref = json.loads(ctx.python(["mido"], ctx.read("tools/fixtures/_midi_ref.py").decode())) + cases = [] + by_name = {} + for c in ref: + case = {"name": c["name"], "data": bytes.fromhex(c["hex"]), "type": c["type"], "division": c["division"], + "tracks": c["tracks"], "exact": True} + if "length" in c: + case["length"] = c["length"] + case["times"] = c["times"] + cases.append(case) + by_name[c["name"]] = case + + # running status across meta and escape events (mido's writer never relies on it), and an F7 escape + body = (b"\x00\x90\x3c\x40" + b"\x00\xff\x01\x01\x41" + b"\x10\x3c\x00" + b"\x00\xf7\x02\xf3\x01" + b"\x05\x3e\x7f" + + b"\x00\xff\x2f\x00") + cases.append({"name": "running-after-meta", "data": smf([body]), "type": 0, "division": 96, "exact": False, "tracks": [[ + [0, "noteOn", 0, [60, 64], -1], [0, "meta", -1, [0x41], 1], [16, "noteOn", 0, [60, 0], -1], + [16, "escape", -1, [0xF3, 0x01], -1], [21, "noteOn", 0, [62, 127], -1], [21, "meta", -1, [], 0x2F]]]}) + # an unknown chunk between MThd and MTrk, a longer MThd, and an RMID wrapper + f0 = by_name["format0"] + raw = f0["data"] + hdr, rest = raw[:14], raw[14:] + cases.append(dict(f0, name="unknown-chunk", exact=False, data=hdr + b"XFIH" + struct.pack(">I", 5) + b"abcde" + rest)) + long_hdr = b"MThd" + struct.pack(">I", 8) + raw[8:14] + b"\x00\x00" + rest + cases.append(dict(f0, name="long-mthd", exact=False, data=long_hdr)) + riff = b"RMID" + b"data" + struct.pack("IHHh", 6, 3, 0, 96), "code": "UNSUPPORTED"}, + {"name": "zero-division", "data": b"MThd" + struct.pack(">IHHh", 6, 0, 0, 0), "code": "CORRUPT"}, + {"name": "short-header", "data": b"MThd\x00\x00\x00\x06\x00", "code": "TRUNCATED"}, + {"name": "system-common", "data": smf([b"\x00\xf2\x01\x02"]), "code": "CORRUPT"}, + {"name": "rmid-without-data", "data": b"RIFF\x0c\x00\x00\x00RMIDLIST\x00\x00\x00\x00", "code": "CORRUPT"}, + ] + ctx.emit("midi_bad", bad) + f1 = by_name["format1"]["data"] + ctx.emit("midi_trunc", {"name": "format1-cut", "data": f1[: len(f1) * 3 // 5]})