diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 49b00c4..539efa1 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -57,6 +57,12 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | subtitle | ass | .ass .ssa | yes | yes | styles: true | `tests/subtitle/ass.luau` | | subtitle | srt | .srt | yes | yes | styles: false | `tests/subtitle/srt.luau` | | subtitle | vtt | .vtt .webvtt | yes | yes | styles: true | `tests/subtitle/vtt.luau` | +| music | it | .it | yes | - | render: true, channels: 1, 64, compressedSamples: true | `tests/music/it.luau` | +| music | midi | .mid .midi .smf .kar .rmi | yes | yes | formats: 0, 1, 2, render: true, streaming: true, rmid: true | `tests/music/midi.luau` | +| music | mod | .mod .m15 .stk .nst | yes | yes | render: true, channels: 1, 32 | `tests/music/mod.luau` | +| music | s3m | .s3m | yes | - | render: true, channels: 1, 32 | `tests/music/s3m.luau` | +| music | sf2 | .sf2 | yes | - | sm24: true, sf3: false | `tests/music/sf2.luau` | +| music | xm | .xm | yes | yes | render: true, channels: 1, 64 | `tests/music/xm.luau` | | playlist | m3u | .m3u .m3u8 | yes | yes | hls: true | `tests/playlist/m3u.luau` | | playlist | pls | .pls | yes | yes | | `tests/playlist/pls.luau` | | playlist | xspf | .xspf | yes | yes | | `tests/playlist/xspf.luau` | @@ -79,7 +85,9 @@ Codecs (layer 1, shared by formats; not loadable on their own): - codecs/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). Walks - codecs/Quantize: palette quantization of rgba8 pixels. A codec (layer 1): image/gif (and later any palette - codecs/Raster: an antialiased scanline rasterizer for paths of lines, quadratic and cubic Béziers, under an affine +- codecs/SoundFont: SoundFont 2 banks and the sample synth that plays MIDI through them. A codec (layer 1) shared by - codecs/Text: text decoding helpers for the text formats: a UTF-8 BOM is stripped, text that is not valid UTF-8 is +- codecs/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it. The four loaders read - codecs/TrueType: the sfnt font container (TrueType .ttf, OpenType .otf with CFF outlines, collections .ttc) parsed - codecs/Url: RFC 3986 reference resolution (section 5.2), the classification of a playlist / manifest location (URL, - codecs/Vp8: the VP8 video codec (RFC 6386), decode only. A codec (layer 1): image/webp uses it for lossy frames, the diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index 10ddbbe..bc49697 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -27,6 +27,9 @@ | `tests/fixtures/vox/ogt_*.vox` | jpaver/opengametools `demo/vox/` (files saved by MagicaVoxel 0.99.x) | MIT: [opengametools-LICENSE.txt](opengametools-LICENSE.txt) | | `tests/fixtures/gltf/` | KhronosGroup/glTF-Sample-Assets `Models/` (one LICENSE.md per model folder; `UnicodeTest` is `Unicode❤♻Test` renamed) | CC-BY-4.0 or CC0-1.0 per model, see each folder's LICENSE.md | | `src/Formats/codecs/Vp8/` (Decode, Yuv, Tables), `src/Formats/codecs/Vp8L/Decode.luau`, `src/Formats/image/webp/` (Alpha unfilters, Anim.coalesce) | ports of libwebp 1.6.0 (Google): src/dec, src/dsp, src/utils, src/demux/anim_decode.c | BSD-3-Clause + patent grant: [libwebp-LICENSE.txt](libwebp-LICENSE.txt) | +| `src/Formats/codecs/Tracker/`, `src/Formats/music/{mod,s3m,xm,it}/` | written for this library from the format documents: ProTracker 2.3 effect docs, the XM specification (Mr.H / Triton) and FT2 behaviour notes, ST3 TECH.DOC (Sami Tammilehto / Future Crew), ITTECH.TXT (Jeffrey Lim); OpenMPT (libopenmpt, BSD) was used only as the reference player in the tests, and its documented playback quirks (mix levels, MOD panning, FT2 E6x / tremor / instrument behaviour) are matched | no third-party code | +| `tools/fixtures/{mod,s3m,xm,it}.py` test modules | generated by the fixture scripts (synthesized samples) | no third-party data | +| `src/Formats/codecs/SoundFont/` (Synth, the zone merging in Parse) | port of TinySoundFont v0.9 (tsf.h) by Bernhard Schelling, based on SFZero by Steve Folta | MIT: [TinySoundFont-LICENSE.txt](TinySoundFont-LICENSE.txt) | Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this folder (see docs/STYLE.md, "Absorbing an existing repo"). 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 1458dcf..ab394ee 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -638,6 +638,78 @@ local list: { Entry } = { return require("@formats/subtitle/vtt") end, }, + { + name = "it", + category = "music", + path = "music/it", + extensions = { "it" }, + mime = { "audio/it", "audio/x-it" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 64 }, compressedSamples = true }, + load = function() + return require("@formats/music/it") + 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 = "mod", + category = "music", + path = "music/mod", + extensions = { "mod", "m15", "stk", "nst" }, + mime = { "audio/x-mod", "audio/mod" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" }, + caps = { decode = true, encode = true, render = true, channels = { 1, 32 } }, + load = function() + return require("@formats/music/mod") + end, + }, + { + name = "s3m", + category = "music", + path = "music/s3m", + extensions = { "s3m" }, + mime = { "audio/s3m", "audio/x-s3m" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 32 } }, + load = function() + return require("@formats/music/s3m") + 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, + }, + { + name = "xm", + category = "music", + path = "music/xm", + extensions = { "xm" }, + mime = { "audio/xm", "audio/x-xm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" }, + caps = { decode = true, encode = true, render = true, channels = { 1, 64 } }, + load = function() + return require("@formats/music/xm") + end, + }, { name = "m3u", category = "playlist", diff --git a/src/Formats/Types.luau b/src/Formats/Types.luau index 6464e98..f776c3c 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..90cdfcc --- /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_SAMPLEID = 41, 53 + +-- generator op -> { field, mode, limit }. modes: f / i (value, merged by adding then clamping), a (sample address +-- add), a15 (coarse address add: * 32768), kr / vr (key / velocity range), loop, group, key (overriding root key) +local LIM12K5K = { 1, -12000, 5000 } +local LIM12K8K = { 1, -12000, 8000 } +local LIM1200 = { 1, -1200, 1200 } +local GEN: { [number]: { any } } = { + [0] = { "offset", "a" }, + [1] = { "stop", "a" }, + [2] = { "loopStart", "a" }, + [3] = { "loopEnd", "a" }, + [4] = { "offset", "a15" }, + [5] = { "modLfoToPitch", "i", { 1, -12000, 12000 } }, + [6] = { "vibLfoToPitch", "i", { 1, -12000, 12000 } }, + [7] = { "modEnvToPitch", "i", { 1, -12000, 12000 } }, + [8] = { "filterFc", "i", { 1, 1500, 13500 } }, + [9] = { "filterQ", "i", { 1, 0, 960 } }, + [10] = { "modLfoToFilterFc", "i", { 1, -12000, 12000 } }, + [11] = { "modEnvToFilterFc", "i", { 1, -12000, 12000 } }, + [12] = { "stop", "a15" }, + [13] = { "modLfoToVolume", "i", { 1, -960, 960 } }, + [17] = { "pan", "f", { 0.001, -0.5, 0.5 } }, + [21] = { "delayModLFO", "f", LIM12K5K }, + [22] = { "freqModLFO", "i", { 1, -16000, 4500 } }, + [23] = { "delayVibLFO", "f", LIM12K5K }, + [24] = { "freqVibLFO", "i", { 1, -16000, 4500 } }, + [25] = { "mDelay", "f", LIM12K5K }, + [26] = { "mAttack", "f", LIM12K8K }, + [27] = { "mHold", "f", LIM12K5K }, + [28] = { "mDecay", "f", LIM12K8K }, + [29] = { "mSustain", "f", { 1, 0, 1000 } }, + [30] = { "mRelease", "f", LIM12K8K }, + [31] = { "mKeyHold", "f", LIM1200 }, + [32] = { "mKeyDecay", "f", LIM1200 }, + [33] = { "aDelay", "f", LIM12K5K }, + [34] = { "aAttack", "f", LIM12K8K }, + [35] = { "aHold", "f", LIM12K5K }, + [36] = { "aDecay", "f", LIM12K8K }, + [37] = { "aSustain", "f", { 1, 0, 1440 } }, + [38] = { "aRelease", "f", LIM12K8K }, + [39] = { "aKeyHold", "f", LIM1200 }, + [40] = { "aKeyDecay", "f", LIM1200 }, + [43] = { "", "kr" }, + [44] = { "", "vr" }, + [45] = { "loopStart", "a15" }, + [48] = { "attenuation", "f", { 0.04, 0, 57.6 } }, + [50] = { "loopEnd", "a15" }, + [51] = { "transpose", "i" }, + [52] = { "tune", "i" }, + [54] = { "loopMode", "loop" }, + [56] = { "keytrack", "i" }, + [57] = { "group", "group" }, + [58] = { "keycenter", "key" }, +} +-- the merged fields: value generators once each (several ops share a field), then the four address fields +local MERGE: { { any } } = {} +do + local seen: { [string]: boolean } = {} + for op = 0, 58 do + local g = GEN[op] + if g and (g[2] == "f" or g[2] == "i" or g[2] == "a") and not seen[g[1]] then + seen[g[1]] = true + table.insert(MERGE, g) + end + end +end + +local FIELDS = { + "loopMode", "sampleRate", "lokey", "hikey", "lovel", "hivel", "group", "offset", "stop", "loopStart", "loopEnd", + "transpose", "tune", "keycenter", "keytrack", "attenuation", "pan", "filterQ", "filterFc", "modEnvToPitch", + "modEnvToFilterFc", "modLfoToFilterFc", "modLfoToVolume", "delayModLFO", "freqModLFO", "modLfoToPitch", + "delayVibLFO", "freqVibLFO", "vibLfoToPitch", "aDelay", "aAttack", "aHold", "aDecay", "aSustain", "aRelease", + "aKeyHold", "aKeyDecay", "mDelay", "mAttack", "mHold", "mDecay", "mSustain", "mRelease", "mKeyHold", "mKeyDecay", + "sampleIndex", +} + +-- clear(relative): tsf_region_clear. relative = a preset zone (all zero: values add to the instrument's) +local function clear(relative: boolean): Region + local r: Region = {} + for _, f in FIELDS do + r[f] = 0 + end + r.hikey, r.hivel, r.keycenter = 127, 127, 60 + if relative then + return r + end + r.keytrack = 100 + r.keycenter = -1 + for _, p in { "a", "m" } do + for _, s in { "Delay", "Attack", "Hold", "Decay", "Release" } do + r[p .. s] = -12000 + end + end + r.filterFc = 13500 + r.delayModLFO, r.delayVibLFO = -12000, -12000 + return r +end + +local function copy(r: Region): Region + local c: Region = {} + for k, v in r do + c[k] = v + end + return c +end + +-- the region defaults in absolute form (seconds, levels): what Fallback builds its regions from +function Parse.defaultRegion(): Region + local r = clear(false) + r.keycenter = 60 + for _, p in { "a", "m" } do + for _, s in { "Delay", "Attack", "Hold", "Decay", "Release" } do + r[p .. s] = 0 + end + end + r.aSustain, r.mSustain = 1, 1 + r.delayModLFO, r.delayVibLFO = 0, 0 + return r +end + +-- set one generator (tsf_region_operator with an amount); lo / hi = the two bytes, s = signed 16, w = unsigned 16 +local function operator(r: Region, op: number, lo: number, hi: number, s: number, w: number) + local g = GEN[op] + if not g then + return + end + local mode = g[2] + if mode == "f" or mode == "i" then + r[g[1]] = s + elseif mode == "a" then + r[g[1]] += s + elseif mode == "a15" then + r[g[1]] += s * 32768 + elseif mode == "kr" then + r.lokey, r.hikey = lo, hi + elseif mode == "vr" then + r.lovel, r.hivel = lo, hi + elseif mode == "loop" then + local m = w % 4 + r.loopMode = if m == 3 then 2 elseif m == 1 then 1 else 0 + elseif mode == "group" then + r.group = w + elseif mode == "key" then + r.keycenter = s + end +end + +-- merge(zone, preset): zone += preset, then clamp (tsf_region_operator without an amount) +local function merge(z: Region, p: Region) + for _, g in MERGE do + local f = g[1] + local v = z[f] + p[f] + local lim = g[3] + if lim then + v *= lim[1] + v = math.clamp(v, lim[2], lim[3]) + end + z[f] = v + end +end + +local function tc2s(tc: number): number + return 2 ^ (tc / 1200) +end + +-- envtosecs (tsf_region_envtosecs): timecents to seconds; hold / decay stay in timecents when they scale by key +local function envToSecs(r: Region, p: string, sustainIsGain: boolean) + for _, s in { "Delay", "Attack", "Release" } do + local v = r[p .. s] + r[p .. s] = if v < -11950 then 0 else tc2s(v) + end + if r[p .. "KeyHold"] == 0 then + local v = r[p .. "Hold"] + r[p .. "Hold"] = if v < -11950 then 0 else tc2s(v) + end + if r[p .. "KeyDecay"] == 0 then + local v = r[p .. "Decay"] + r[p .. "Decay"] = if v < -11950 then 0 else tc2s(v) + end + local sus = r[p .. "Sustain"] + if sus < 0 then + sus = 0 + elseif sustainIsGain then + sus = if -sus / 10 > -100 then 10 ^ (-sus / 10 * 0.05) else 0 + else + sus = 1 - sus / 1000 + end + r[p .. "Sustain"] = sus +end + +-- ------------------------------------------------------------------------------------------------ RIFF +type Hydra = { [string]: { { number } } } + +-- record layouts: field byte widths (2 / 4 = little endian unsigned, -2 signed, 20 = name, 1 = byte, -1 = signed byte) +local LAYOUT: { [string]: { number } } = { + phdr = { 20, 2, 2, 2, 4, 4, 4 }, + pbag = { 2, 2 }, + pmod = { 2, 2, -2, 2, 2 }, + pgen = { 2, 2 }, + inst = { 20, 2 }, + ibag = { 2, 2 }, + imod = { 2, 2, -2, 2, 2 }, + igen = { 2, 2 }, + shdr = { 20, 4, 4, 4, 4, 4, 1, -1, 2, 2 }, +} +local RECSIZE: { [string]: number } = { phdr = 38, pbag = 4, pmod = 10, pgen = 4, inst = 22, ibag = 4, imod = 10, igen = 4, shdr = 46 } + +local INFO_NAMES = { + isng = "engine", INAM = "name", irom = "rom", ICRD = "date", IENG = "author", IPRD = "product", + ICOP = "copyright", ICMT = "comment", ISFT = "software", +} + +export type Options = { maxRegions: number?, maxSamples: number? } + +-- parse(r, opts?) -> SoundFont | nil, Err +function Parse.parse(r: Bytes.Reader, opts: Options?): (SoundFont?, Err.Err?) + local maxRegions = opts and opts.maxRegions or 1000000 + local maxSamples = opts and opts.maxSamples or 2 ^ 28 + if r:string(4) ~= "RIFF" then + return r:fail(Err.CORRUPT, "not a RIFF file") + end + local riffSize = r:u32le() + if r:string(4) ~= "sfbk" then + return r:fail(Err.CORRUPT, "not a SoundFont (no sfbk)") + end + if r.err then + return nil, r.err + end + local body = r:sub(12, math.max(0, riffSize - 4)) + local info: { [string]: string } = {} + local hydra: Hydra = {} + local smpl: Bytes.Reader? = nil + local sm24: Bytes.Reader? = nil + local version = "" + while body:remaining() >= 8 do + local id, size = body:string(4), body:u32le() + local chunk = body:slice(size) + if size % 2 == 1 and body:remaining() > 0 then + body:skip(1) + end + if id == "LIST" and chunk:remaining() >= 4 then + local kind = chunk:string(4) + while chunk:remaining() >= 8 do + local sid, ssize = chunk:string(4), chunk:u32le() + local sub = chunk:slice(ssize) + if ssize % 2 == 1 and chunk:remaining() > 0 then + chunk:skip(1) + end + if kind == "INFO" then + if sid == "ifil" and sub:remaining() >= 4 then + local major, minor = sub:u16le(), sub:u16le() + version = string.format("%d.%02d", major, minor) + elseif INFO_NAMES[sid] then + info[INFO_NAMES[sid]] = sub:fixed(sub:remaining()) + end + elseif kind == "sdta" then + if sid == "smpl" and not smpl then + smpl = sub + elseif sid == "sm24" then + sm24 = sub + end + elseif kind == "pdta" then + local layout = LAYOUT[sid] + if layout and not hydra[sid] then + local rs = RECSIZE[sid] + local n = sub:remaining() // rs + local recs: { { number } } = 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: { { [string]: any } } = 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: { { name: string, zones: number } } = 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..c133423 --- /dev/null +++ b/src/Formats/codecs/SoundFont/Synth.luau @@ -0,0 +1,803 @@ +--!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: the envelope gain is ramped across each 64-sample block (tsf.h steps it); 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 + -- ramp the gain across the block to the envelope's next level (tsf.h steps it per block: zipper noise) + local gainNext = noteGain * v.amp.level + local step = (gainNext - gainMono) / block + local panL, panR = v.panL, v.panR + local g = gainMono + local k = block + 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 + val *= g + g += step + writef32(out, o, readf32(out, o) + val * panL) + writef32(out, o + 4, readf32(out, o + 4) + val * panR) + o += 8 + pos += pitchRatio + if pos >= 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/codecs/Tracker/Mixer.luau b/src/Formats/codecs/Tracker/Mixer.luau new file mode 100644 index 0000000..193a034 --- /dev/null +++ b/src/Formats/codecs/Tracker/Mixer.luau @@ -0,0 +1,173 @@ +--!strict +--!native +-- codecs/Tracker/Mixer: mixes the player's active voices into an interleaved stereo f32 buffer. Per voice: sample +-- loops (forward, ping-pong, IT sustain loops while the key is held), linear or no interpolation, the IT two-pole +-- resonant filter, and a short gain ramp per tick against clicks. Written for this library (no third-party code). +-- +-- Never throws: sample indexes are clamped to the sample, every loop is bounded, and the caller (codecs/Tracker) +-- validates the sample buffers' sizes. +local floor, ceil, min = math.floor, math.ceil, math.min +local readf32, writef32 = buffer.readf32, buffer.writef32 + +local Mixer = {} + +-- mixVoice(v, out?, off, n, linear, ramp): n frames of voice v added at frame off of out (nil: only advance) +local function mixVoice(v: any, out: buffer?, off: number, n: number, linear: boolean, ramp: number) + local data: buffer = v.data + local nch = v.nch + local inc = v.inc + if not (inc > 0 and inc < 1e6) then + return + end + local len = v.len + local hi = len - 1 + local i = 0 + local guard = 0 + while i < n do + guard += 1 + if guard > n + 64 then + return + end + local s, e, t + if v.keyOn and v.susT > 0 then + s, e, t = v.susS, v.susE, v.susT + elseif v.loopT > 0 then + s, e, t = v.loopS, v.loopE, v.loopT + else + s, e, t = 0, len, 0 + end + local p = v.p + local dir = v.dir + local count + if dir > 0 then + local lim = if t == 2 then e - 1 else e + if p >= lim then + if t == 0 then + v.active = false + return + elseif t == 1 then + p = s + (p - e) % (e - s) + else + p = 2 * (e - 1) - p + if p < s then + p = s + end + v.dir = -1 + end + v.p = p + continue + end + count = ceil((lim - p) / inc) + else + if p < s then + p = 2 * s - p + if p > e - 1 then + p = e - 1 + end + v.p = p + v.dir = 1 + continue + end + count = floor((p - s) / inc) + 1 + end + if count < 1 then + count = 1 + end + local m = min(n - i, count) + local step = inc * dir + if out == nil then + v.p = p + step * m + i += m + continue + end + local wrapJ = if t == 1 then s else e - 1 + local gl, gr = v.gl, v.gr + local rl = v.rampN + local dl, dr = 0, 0 + local tl, tr = v.tl, v.tr + if rl > 0 then + dl, dr = (tl - gl) / rl, (tr - gr) / rl + end + local fOn = v.fOn + local fa, fb0, fb1 = v.fa, v.fb0, v.fb1 + local y1l, y2l, y1r, y2r = v.y1l, v.y2l, v.y1r, v.y2r + local o = (off + i) * 8 + for _ = 1, m do + local idx = floor(p) + if idx > hi then + idx = hi + elseif idx < 0 then + idx = 0 + end + local j = idx + 1 + if j >= e then + j = wrapJ + end + if j > hi then + j = hi + end + local xl, xr + if nch == 1 then + local a = readf32(data, idx * 4) + if linear then + local b = readf32(data, j * 4) + xl = a + (b - a) * (p - idx) + else + xl = a + end + if fOn then + local y = xl * fa + y1l * fb0 + y2l * fb1 + y2l, y1l = y1l, y + xl = y + end + xr = xl + else + local al = readf32(data, idx * 8) + local ar = readf32(data, idx * 8 + 4) + if linear then + local f = p - idx + xl = al + (readf32(data, j * 8) - al) * f + xr = ar + (readf32(data, j * 8 + 4) - ar) * f + else + xl, xr = al, ar + end + if fOn then + local y = xl * fa + y1l * fb0 + y2l * fb1 + y2l, y1l = y1l, y + xl = y + y = xr * fa + y1r * fb0 + y2r * fb1 + y2r, y1r = y1r, y + xr = y + end + end + if rl > 0 then + gl += dl + gr += dr + rl -= 1 + if rl == 0 then + gl, gr = tl, tr + end + end + writef32(out, o, readf32(out, o) + xl * gl) + writef32(out, o + 4, readf32(out, o + 4) + xr * gr) + o += 8 + p += step + end + v.p = p + v.gl, v.gr, v.rampN = gl, gr, rl + v.y1l, v.y2l, v.y1r, v.y2r = y1l, y2l, y1r, y2r + i += m + end + local _ = ramp +end + +-- mix(st, out?, off, n, linear): every active voice of player st; out nil only advances the sample positions +function Mixer.mix(st: any, out: buffer?, off: number, n: number, linear: boolean) + for _, v in st.voices do + if v.active and v.data then + mixVoice(v, out, off, n, linear, 0) + end + end +end + +return Mixer diff --git a/src/Formats/codecs/Tracker/Pcm.luau b/src/Formats/codecs/Tracker/Pcm.luau new file mode 100644 index 0000000..30c59c8 --- /dev/null +++ b/src/Formats/codecs/Tracker/Pcm.luau @@ -0,0 +1,132 @@ +--!strict +--!native +-- codecs/Tracker/Pcm: sample data conversions shared by the tracker formats. Raw 8 / 16-bit PCM (signed or unsigned, +-- plain or delta coded as in XM / IT 2.15, interleaved or planar stereo) to the engine's f32 samples, and back. +-- +-- Never throws: reads past the source are refused up front (decode returns nil). +local readu8, readi8, readu16, readi16 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16 +local writef32, readf32, writeu8, writei16 = buffer.writef32, buffer.readf32, buffer.writeu8, buffer.writei16 +local floor = math.floor + +local Pcm = {} + +export type Spec = { + bits: number, -- 8 | 16 + signed: boolean, + delta: boolean?, -- each value is the difference to the previous one (XM, IT 2.15 "delta" flag) + channels: number?, -- 1 (default) | 2 + planar: boolean?, -- stereo stored as all left then all right (XM, IT); default interleaved + bigEndian: boolean?, +} + +-- bytes(frames, spec) -> the size of the raw data +function Pcm.bytes(frames: number, spec: Spec): number + return frames * (spec.channels or 1) * (spec.bits // 8) +end + +-- decode(buf, off, frames, spec) -> f32 buffer (frames * channels, interleaved) | nil when the source is too short +function Pcm.decode(buf: buffer, off: number, frames: number, spec: Spec): buffer? + local nch = spec.channels or 1 + local bps = spec.bits // 8 + local total = frames * nch + if frames < 0 or off < 0 or off + total * bps > buffer.len(buf) then + return nil + end + local out = buffer.create(total * 4) + local planar = spec.planar and nch == 2 + for c = 0, nch - 1 do + local acc = 0 + for i = 0, frames - 1 do + local k = if planar then c * frames + i else i * nch + c + local v + if bps == 1 then + if spec.signed then + v = readi8(buf, off + k) + else + v = readu8(buf, off + k) - 128 + end + if spec.delta then + acc = (acc + v + 128) % 256 - 128 + v = acc + end + writef32(out, (i * nch + c) * 4, v / 128) + else + local p = off + k * 2 + if spec.bigEndian then + v = readu8(buf, p) * 256 + readu8(buf, p + 1) + if spec.signed and v >= 32768 then + v -= 65536 + end + elseif spec.signed then + v = readi16(buf, p) + else + v = readu16(buf, p) + end + if not spec.signed then + v -= 32768 + end + if spec.delta then + acc = (acc + v + 32768) % 65536 - 32768 + v = acc + end + writef32(out, (i * nch + c) * 4, v / 32768) + end + end + end + return out +end + +-- encode(samples, frames, spec) -> raw PCM (signed or unsigned, optional delta, interleaved or planar) +function Pcm.encode(samples: buffer, frames: number, spec: Spec): buffer + local nch = spec.channels or 1 + local bps = spec.bits // 8 + local out = buffer.create(frames * nch * bps) + local planar = spec.planar and nch == 2 + local avail = buffer.len(samples) // 4 + for c = 0, nch - 1 do + local prev = 0 + for i = 0, frames - 1 do + local si = i * nch + c + local x = if si < avail then readf32(samples, si * 4) else 0 + local k = if planar then c * frames + i else i * nch + c + if bps == 1 then + local v = math.clamp(floor(x * 128 + 0.5), -128, 127) + local w = v + if spec.delta then + w = (v - prev) % 256 + prev = v + else + w = if spec.signed then v % 256 else v + 128 + end + writeu8(out, k, w) + else + local v = math.clamp(floor(x * 32768 + 0.5), -32768, 32767) + local w = v + if spec.delta then + w = (v - prev + 32768) % 65536 - 32768 + prev = v + elseif not spec.signed then + w = v + 32768 + if w >= 32768 then + w -= 65536 + end + end + writei16(out, k * 2, w) + end + end + end + return out +end + +-- bits(samples) -> 8 when every value is exactly representable in 8 bits (data loaded from 8-bit), else 16 +function Pcm.bitsNeeded(samples: buffer): number + for i = 0, buffer.len(samples) // 4 - 1 do + local x = readf32(samples, i * 4) * 128 + if x ~= floor(x) then + return 16 + end + end + return 8 +end + +return Pcm diff --git a/src/Formats/codecs/Tracker/Player.luau b/src/Formats/codecs/Tracker/Player.luau new file mode 100644 index 0000000..84d2079 --- /dev/null +++ b/src/Formats/codecs/Tracker/Player.luau @@ -0,0 +1,1890 @@ +--!strict +--!native +-- codecs/Tracker/Player: the sequencer of the tracker engine. One player for MOD, S3M, XM and IT: rows, orders, +-- speed / tempo, every effect of the four formats (interpreted per format family: ProTracker / FastTracker 2 numeric +-- effects, ScreamTracker 3 / Impulse Tracker letter effects), instruments with volume / panning / pitch envelopes, +-- fadeout and auto-vibrato, IT new note actions (background voices), duplicate checks and resonant filters, and song +-- end / loop detection. Written from the format documents (ProTracker 2.3 docs, the XM spec and FT2 behaviour notes, +-- ST3 TECH.DOC, ITTECH.TXT); no third-party code. Mixing is codecs/Tracker/Mixer. +-- +-- Never throws: the module is validated by codecs/Tracker before a player is made, and every table lookup here is +-- guarded. +local Tables = require("@formats/codecs/Tracker/Tables") + +local wave64, autoWave = Tables.wave64, Tables.autoWave +local AMIGA = Tables.AMIGA +local AMIGA_PAL = Tables.AMIGA_PAL +local floor, min, max, clamp, abs = math.floor, math.min, math.max, math.clamp, math.abs +local readu8 = buffer.readu8 + +local Player = {} + +local MOD, S3M, XM, IT = 1, 2, 3, 4 +Player.MOD, Player.S3M, Player.XM, Player.IT = MOD, S3M, XM, IT +local FAMILY = { mod = MOD, s3m = S3M, xm = XM, it = IT } + +local BG_VOICES = 64 -- voices beyond one per channel, for IT new note actions + +-- ------------------------------------------------------------------------------------------------ state +local function newVoice(): any + return { + active = false, + chan = 0, + bg = false, + data = nil :: buffer?, + nch = 1, + len = 0, + loopS = 0, + loopE = 0, + loopT = 0, + susS = 0, + susE = 0, + susT = 0, + p = 0, + dir = 1, + inc = 0, + smp = nil :: any, + smpIdx = 0, + ins = nil :: any, + insIdx = 0, + note = 0, + vol = 0, + pan = 128, + chanVol = 64, + period = 0, + periodOut = 0, + base = 8363, + keyOn = true, + fading = false, + fade = 65536, + volEnvPos = 0, + panEnvPos = 0, + pitchEnvPos = 0, + volEnvOn = true, + panEnvOn = true, + pitchEnvOn = true, + envVol = 64, + envPan = 0, + envPitch = 0, + avPos = 0, + avAmp = 0, + gl = 0, + gr = 0, + tl = 0, + tr = 0, + started = false, + cutoff = 127, + reso = 0, + fOn = false, + fa = 1, + fb0 = 0, + fb1 = 0, + y1l = 0, + y2l = 0, + y1r = 0, + y2r = 0, + tremorMute = false, + surround = false, + rampN = 0, + owner = 0, -- the channel whose foreground voice this is (0: free or background) + order = 0, -- allocation age + } +end + +local function newChannel(i: number, pan: number, vol: number): any + return { + idx = i, + voice = nil :: any, + note = 0, + realNote = 0, + insIdx = 0, + smpIdx = 0, + smp = nil :: any, + vol = 0, + pan = pan, + basePan = pan, + chanVol = vol, + period = 0, + target = 0, + portaSpeed = 0, + base = 8363, + finetune = nil :: number?, + fx = 0, + param = 0, + vcmd = 0, + -- memories + mPortaUp = 0, + mPortaDn = 0, + mFineUp = 0, + mFineDn = 0, + mXFineUp = 0, + mXFineDn = 0, + mVolSlide = 0, + mFineVolUp = 0, + mFineVolDn = 0, + mOffset = 0, + mHighOffset = 0, + mPanSlide = 0, + mGVolSlide = 0, + mRetrig = 0, + mTremor = 0, + mArp = 0, + mS3M = 0, + mEF = 0, + mChanVolSlide = 0, + mTempo = 0, + mVolCol = 0, + mS = 0, + vibSpeed = 0, + vibDepth = 0, + vibPos = 0, + vibWave = 0, + tremSpeed = 0, + tremDepth = 0, + tremPos = 0, + tremWave = 0, + panbSpeed = 0, + panbDepth = 0, + panbPos = 0, + panbWave = 0, + vibDelta = 0, + tremDelta = 0, + panbDelta = 0, + arp = 0, + loopRow = 0, + loopCount = 0, + retrigCount = 0, + tremorCount = 0, + tremorOn = true, + delayTick = -1, + dNote = 0, + dIns = 0, + dVol = 0, + cutTick = -1, + keyOffTick = -1, + nna = -1, + surround = false, + cutoff = 127, + reso = 0, + volEnvOn = true, + panEnvOn = true, + pitchEnvOn = true, + muted = false, + triggered = false, + } +end + +-- new(module, opts) -> player state (module validated by the caller) +function Player.new(m: any, sampleRate: number, opts: any): any + local fmt = FAMILY[m.format] or MOD + local st: any = { + m = m, + fmt = fmt, + sr = sampleRate, + nch = m.channels, + speed = m.speed, + tempo = m.tempo, + gvol = m.globalVolume, + linear = m.linear, + insMode = m.instrumentMode and #m.instruments > 0, + oldFx = m.flags.oldEffects or false, + compatG = m.flags.compatGxx or false, + fastSlides = m.flags.fastSlides or false, + amigaLimits = m.flags.amigaLimits or false, + ord = 0, + row = 0, + tick = 0, + pat = nil :: any, + patIdx = -1, + patDelay = 0, + patDelayRep = 0, + fineDelay = 0, + jumpOrd = -1, + ft2BreakPos = 0, + breakRow = -1, + loopJump = -1, + ended = false, + visited = {} :: { [number]: boolean }, + chans = {}, + voices = {}, + age = 0, + tickFrames = 0, + frac = 0, + separation = math.clamp((opts and opts.stereoSeparation or 100) / 100, 0, 2), + master = 1, + rows = 0, + ramp = 64, + amiga = if fmt == MOD then AMIGA_PAL else AMIGA, + loopAllowed = opts and opts.loop or false, + } + for i = 1, m.channels do + local pan = m.channelPan[i] or 128 + local cv = m.channelVolume[i] or 64 + local c = newChannel(i, pan, cv) + c.basePan = pan + c.muted = m.channelMute[i] or false + if pan == 512 then -- surround marker + c.pan = 128 + c.surround = true + end + st.chans[i] = c + end + for i = 1, m.channels + BG_VOICES do + st.voices[i] = newVoice() + end + st.master = Player.masterGain(m, fmt) + Player.startOrder(st, 0, 0) + return st +end + +-- the output scale per format, calibrated against OpenMPT's default mix levels (tools/fixtures: a full-scale sine at +-- volume 64 on one centred channel) +function Player.masterGain(m: any, fmt: number): number + if fmt == IT or fmt == S3M then + return (m.mixVolume or 48) / 128 -- OpenMPT: linear in the mix / master volume, 64 = 0.5 + end + if fmt == XM then + return 0.375 -- OpenMPT's XM pre-amp (48 / 128), whatever the channel count + end + -- MOD: OpenMPT scales by the channel count (4 channels: 0.5; 2 / channels between 2 and 8) + return 2 / clamp(m.channels, 2, 8) +end + +-- ------------------------------------------------------------------------------------------------ orders and rows +-- startOrder(st, ord, row): resolve skip markers / the end of the order list; sets st.pat or st.ended +function Player.startOrder(st: any, ord: number, row: number) + local m = st.m + local order = m.order + local n = #order + local guard = 0 + local o = ord + while true do + guard += 1 + if guard > n + 2 then + st.ended = true + return + end + if o >= n then + o = m.restart or 0 + if o >= n or o < 0 then + o = 0 + end + if n == 0 then + st.ended = true + return + end + end + local p = order[o + 1] + if p == 255 then + o = n -- the end marker: wrap to the restart position + elseif p == 254 or m.patterns[p + 1] == nil then + o += 1 + else + st.ord = o + st.patIdx = p + st.pat = m.patterns[p + 1] + st.row = if row < st.pat.rows then row else 0 + return + end + end +end + +local function advanceRow(st: any) + if st.stopAfterRow then + st.ended = true + return + end + local loopRow = st.loopJump + if st.jumpOrd >= 0 or st.breakRow >= 0 then + local o = if st.jumpOrd >= 0 then st.jumpOrd else st.ord + 1 + local r = if st.breakRow >= 0 then st.breakRow else 0 + st.jumpOrd, st.breakRow, st.loopJump = -1, -1, -1 + st.ft2BreakPos = 0 + Player.startOrder(st, o, r) + return + end + if loopRow >= 0 then + st.loopJump = -1 + -- the rows inside a pattern loop are played again on purpose: forget them for the song-end check + for r = loopRow, st.row do + st.visited[st.ord * 1024 + r] = nil + end + st.row = loopRow + return + end + st.row += 1 + if st.row >= st.pat.rows then + -- FT2 (XM): the next pattern starts at the row a pattern loop last jumped to (the E6x "bug" FT2 players keep) + local r = if st.fmt == XM then st.ft2BreakPos else 0 + st.ft2BreakPos = 0 + Player.startOrder(st, st.ord + 1, r) + end +end + +-- ------------------------------------------------------------------------------------------------ pitch +-- the period of a note for a sample (see codecs/Tracker for the two period spaces) +local function notePeriod(st: any, note: number, smp: any, ft: number?): (number, number) + local base, ref, tr + if st.fmt == MOD or st.fmt == XM then + base, ref = 8363, 49 + tr = (smp.relativeNote or 0) * 64 + (ft or smp.finetune or 0) / 2 + else + base, ref, tr = smp.c5speed or 8363, 61, 0 + if base <= 0 then + base = 8363 + end + end + local plin = (ref - note) * 64 - tr + if st.fmt == MOD then + -- ProTracker: integer periods from the finetune tables (finetune 0 table scaled by 2^(-ft / 96), rounded) + local ftp = (ft or smp.finetune or 0) / 16 + return 4 * floor(Tables.noteToPeriod(note) * 2 ^ (-ftp / 12 / 8) + 0.5), base + end + if st.linear then + return plin, base + end + return 1712 * 8363 / base * 2 ^ (plin / 768), base +end + +local function arpPeriod(st: any, period: number, semis: number): number + if semis == 0 then + return period + end + if st.linear then + return period - semis * 64 + end + return period * 2 ^ (-semis / 12) +end + +local function clampPeriod(st: any, c: any) + if st.linear then + c.period = clamp(c.period, -6000, 6000) + elseif st.amigaLimits then + c.period = clamp(c.period, 113 * 4, 856 * 4) + else + c.period = clamp(c.period, 1, 1e6) + end +end + +-- ------------------------------------------------------------------------------------------------ voices +local function allocVoice(st: any): any + local best, bestScore = nil, math.huge + for _, v in st.voices do + if not v.active and v.owner == 0 then + return v + end + if v.bg then + local s = (v.vol * v.envVol * v.fade) / 1e9 + v.order * 1e-9 + if s < bestScore then + best, bestScore = v, s + end + end + end + if best then + best.active = false + return best + end + -- every voice is busy in the foreground (more channels than voices): reuse an inactive one anyway + for _, v in st.voices do + if not v.active then + local c = st.chans[v.owner] + if c and c.voice == v then + c.voice = nil + end + return v + end + end + return st.voices[1] -- unreachable: there are more voices than channels +end + +local function keyOff(st: any, v: any) + if not v or not v.active then + return + end + v.keyOn = false + local ins = v.ins + if st.fmt == XM then + if not (ins and ins.volEnv and ins.volEnv.enabled) then + v.vol = 0 + local c = st.chans[v.chan] + if c and c.voice == v then + c.vol = 0 + end + else + v.fading = true + end + elseif st.fmt == IT then + if ins then + local env = ins.volEnv + if not (env and env.enabled and v.volEnvOn) or env.loop then + v.fading = true + end + end + end +end + +local function noteFade(v: any) + if v and v.active then + v.fading = true + end +end + +local function cutVoice(v: any) + if v then + v.active = false + end +end + +-- start(st, c, smp, smpIdx, ins, insIdx, note, period, base, offset): a fresh voice for channel c +local function startVoice(st: any, c: any, smp: any, smpIdx: number, ins: any, insIdx: number, note: number, period: number, base: number, keepEnv: any) + local v = c.voice + if v == nil or v.bg then + v = allocVoice(st) + c.voice = v + v.owner = c.idx + end + local wasActive = v.active + v.active = smp.length > 0 and smp.data ~= nil + v.chan = c.idx + v.bg = false + v.smp = smp + v.smpIdx = smpIdx + v.data = smp.data + v.nch = smp.channels or 1 + v.len = smp.length + v.loopS, v.loopE, v.loopT = smp.loopStart, smp.loopEnd, smp.loopType + v.susS, v.susE, v.susT = smp.susStart or 0, smp.susEnd or 0, smp.susType or 0 + v.p = 0 + v.dir = 1 + v.ins = ins + v.insIdx = insIdx + v.note = note + v.period = period + v.periodOut = period + v.base = base + st.age += 1 + v.order = st.age + if keepEnv ~= true then + if keepEnv ~= "release" then + v.keyOn = true + v.fading = false + end + v.fade = 65536 + v.volEnvPos, v.panEnvPos, v.pitchEnvPos = 0, 0, 0 + v.avPos, v.avAmp = 0, 0 + v.envVol, v.envPan, v.envPitch = 64, 0, 0 + v.volEnvOn, v.panEnvOn, v.pitchEnvOn = true, true, true + v.y1l, v.y2l, v.y1r, v.y2r = 0, 0, 0, 0 + end + if not wasActive then + v.gl, v.gr = 0, 0 + end + return v +end + +-- IT new note actions on the channel's current voice (and duplicate checks on all its voices) +local function newNoteAction(st: any, c: any, ins: any, insIdx: number, note: number, smpIdx: number) + -- duplicate check: voices of this channel playing the same instrument + if ins and ins.dct and ins.dct > 0 then + for _, u in st.voices do + if u.active and u.chan == c.idx and u.insIdx == insIdx then + local dup = (ins.dct == 1 and u.note == note) or (ins.dct == 2 and u.smpIdx == smpIdx) or ins.dct == 3 + if dup then + local a = ins.dca or 0 + if a == 0 then + cutVoice(u) + elseif a == 1 then + keyOff(st, u) + else + noteFade(u) + end + end + end + end + end + local v = c.voice + if v == nil or not v.active then + return + end + local nna = c.nna + if nna < 0 then + nna = if v.ins then (v.ins.nna or 0) else 0 + end + if nna == 0 then + -- cut: the voice is reused for the new note (a short click is avoided by its ramp from the old gains) + v.active = false + return + end + v.bg = true + v.owner = 0 + c.voice = nil + if nna == 2 then + keyOff(st, v) + elseif nna == 3 then + noteFade(v) + end +end + +-- ------------------------------------------------------------------------------------------------ triggering +local function isPorta(st: any, fx: number, vcmd: number): boolean + local f = st.fmt + if f == MOD then + return fx == 3 or fx == 5 + elseif f == XM then + return fx == 3 or fx == 5 or (vcmd >= 0xF0) + end + -- S3M / IT: G (7) or L (12); IT volume column g (193..202, stored + 1) + return fx == 7 or fx == 12 or (f == IT and vcmd >= 194 and vcmd <= 203) +end + +-- the sample and real note for an instrument number + note +local function resolve(st: any, insIdx: number, note: number): (any, number, any, number) + local m = st.m + if st.insMode then + local ins = m.instruments[insIdx] + if not ins or note < 1 or note > 120 then + return nil, 0, ins, note + end + local si = ins.sampleMap[note] or 0 + local rn = ins.noteMap[note] or note + local smp = m.samples[si] + return smp, si, ins, rn + end + local smp = m.samples[insIdx] + return smp, insIdx, nil, note +end + +local function setInstrumentDefaults(st: any, c: any, smp: any, ins: any) + if smp then + c.vol = smp.volume + end + if st.fmt == IT then + -- IT: a sample's or instrument's default panning holds for its notes; the channel panning (set by the + -- effects) comes back for the others + local p = (smp and smp.pan) or (ins and ins.pan) + c.pan = p or c.basePan + if p then + c.surround = false + end + elseif smp and smp.pan then + c.pan = smp.pan + c.basePan = c.pan + c.surround = false + end + if ins and st.fmt == IT then + if ins.cutoff then + c.cutoff = ins.cutoff + end + if ins.resonance then + c.reso = ins.resonance + end + end +end + +local function sampleOffset(st: any, c: any, v: any) + local f = st.fmt + local fx, param = c.fx, c.param + local off = -1 + if (f == MOD or f == XM) and fx == 9 then + if param > 0 then + c.mOffset = param + end + off = (if f == XM then c.mOffset else param) * 256 + elseif (f == S3M or f == IT) and fx == 15 then + if param > 0 then + c.mOffset = param + end + off = c.mOffset * 256 + (if f == IT then c.mHighOffset * 65536 else 0) + end + if off > 0 and v and v.active then + if off >= v.len then + if v.loopT > 0 and f ~= MOD then + off = v.loopS + elseif f == MOD and v.loopT > 0 then + off = v.loopS + else + v.active = false + return + end + end + v.p = off + end +end + +-- trigger(st, c, note, insIdx, vcmd): the note / instrument / volume column part of a cell +local function trigger(st: any, c: any, note: number, insIdx: number, vcmd: number) + local f = st.fmt + local m = st.m + local porta = isPorta(st, c.fx, vcmd) + local hasNote = note >= 1 and note <= 120 + if insIdx > 0 then + local valid = if st.insMode then m.instruments[insIdx] ~= nil else m.samples[insIdx] ~= nil + if valid then + c.insIdx = insIdx + local n = if hasNote then note else c.note + local smp, _, ins = resolve(st, insIdx, if n > 0 then n else 61) + setInstrumentDefaults(st, c, smp, ins) + if not hasNote then + local v = c.voice + if f == XM and v then + -- an instrument number alone (FT2 / OpenMPT): the playing note's envelopes restart (key on, no + -- fadeout); the new instrument applies from the next note + v.keyOn, v.fading, v.fade = true, false, 65536 + v.volEnvPos, v.panEnvPos, v.avPos, v.avAmp = 0, 0, 0, 0 + elseif (f == MOD or f == S3M) and smp then + c.smp, c.smpIdx = smp, insIdx + end + end + elseif f == XM and hasNote then + -- an empty instrument: the note stops the channel + c.insIdx = insIdx + if c.voice then + c.voice.active = false + end + hasNote = false + end + end + if hasNote then + local useIns = c.insIdx + local smp, smpIdx, ins, realNote = resolve(st, useIns, note) + if smp == nil then + if (f == MOD or f == S3M) and c.smp then + smp, smpIdx = c.smp, c.smpIdx + end + end + if smp then + local ft = c.finetune + local period, base = notePeriod(st, realNote, smp, ft) + local v = c.voice + if porta and ((v and v.active) or f == MOD or f == XM) then + -- tone portamento: a new target, no new note (ProTracker / FT2 never start a note with it) + c.target = period + if st.fmt == IT or st.fmt == S3M then + c.note = note + end + else + if f == IT and st.insMode then + newNoteAction(st, c, ins, useIns, realNote, smpIdx) + end + -- FT2: a note without an instrument number restarts the sample only (envelopes, key off and + -- fadeout carry on); with another instrument than the playing one, its envelopes and fadeout start + -- over but a key off stays + local keep: any = false + if f == XM and insIdx == 0 and c.voice ~= nil then + keep = if c.voice.ins == ins then true else "release" + end + c.triggered = true + c.tremorOn = true + c.retrigCount = 0 + v = startVoice(st, c, smp, smpIdx, ins, useIns, realNote, period, base, keep) + v.patNote = note + c.period, c.target, c.base = period, period, base + c.note, c.realNote = note, realNote + c.smp, c.smpIdx = smp, smpIdx + if insIdx > 0 or f == MOD or f == S3M then + -- volume was set by the instrument; MOD / S3M keep the channel volume + end + if c.vibWave < 4 then + c.vibPos = 0 + end + if c.tremWave < 4 then + c.tremPos = 0 + end + v.cutoff, v.reso = c.cutoff, c.reso + v.volEnvOn, v.panEnvOn, v.pitchEnvOn = true, true, true + c.nna = -1 + sampleOffset(st, c, v) + end + elseif f == IT or f == XM then + -- a note mapped to no sample cuts + if c.voice and not porta then + if f == IT and st.insMode then + newNoteAction(st, c, nil, 0, note, 0) + end + if c.voice then + c.voice.active = false + end + end + end + elseif note == 255 then + if f == S3M or f == MOD then + cutVoice(c.voice) + elseif c.voice then + keyOff(st, c.voice) + end + elseif note == 254 then + cutVoice(c.voice) + if f ~= IT then + c.vol = 0 + end + elseif note == 253 then + noteFade(c.voice) + end + -- the volume column's set-volume / set-panning parts (the rest runs with the effects) + if vcmd > 0 then + if f == S3M then + c.vol = min(vcmd - 1, 64) + elseif f == XM then + if vcmd >= 0x10 and vcmd <= 0x50 then + c.vol = vcmd - 0x10 + elseif vcmd >= 0xC0 and vcmd <= 0xCF then + c.pan = (vcmd - 0xC0) * 16 + c.basePan = c.pan + end + elseif f == IT then + local v = vcmd - 1 + if v <= 64 then + c.vol = v + elseif v >= 128 and v <= 192 then + c.pan = (v - 128) * 4 + c.basePan = c.pan + c.surround = false + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ effect helpers +local function volSlideMod(c: any, param: number) + local x, y = param // 16, param % 16 + if x > 0 then + c.vol = min(64, c.vol + x) + else + c.vol = max(0, c.vol - y) + end +end + +local function tonePorta(st: any, c: any, speed: number) + if c.period == c.target then + return + end + if c.period < c.target then + c.period = min(c.period + speed, c.target) + else + c.period = max(c.period - speed, c.target) + end +end + +local function vibrato(st: any, c: any, scale: number) + c.vibDelta = wave64(c.vibWave % 4, c.vibPos) * c.vibDepth * scale + c.vibPos = (c.vibPos + c.vibSpeed) % 64 +end + +local function tremolo(c: any, scale: number) + c.tremDelta = floor(wave64(c.tremWave % 4, c.tremPos) * c.tremDepth * scale) + c.tremPos = (c.tremPos + c.tremSpeed) % 64 +end + +local function retrigVoice(st: any, c: any) + local v = c.voice + if v and v.smp then + v.active = v.smp.length > 0 + v.p = 0 + v.dir = 1 + end +end + +local function retrigVolume(c: any, x: number) + if x == 0 or x == 8 then + return + end + local mul = Tables.RETRIG_MUL[x + 1] + if mul ~= 1 then + c.vol = floor(c.vol * mul) + else + c.vol += Tables.RETRIG_ADD[x + 1] + end + c.vol = clamp(c.vol, 0, 64) +end + +-- S3M / IT D-style slide of a value: returns the new value (fine parts only on tick 0, normal parts on other ticks; +-- fast: normal parts on tick 0 too) +local function dSlide(value: number, param: number, tick: number, fast: boolean, hi: number): number + local x, y = param // 16, param % 16 + if y == 0xF and x > 0 then + if tick == 0 then + return min(hi, value + x) + end + return value + elseif x == 0xF and y > 0 then + if tick == 0 then + return max(0, value - y) + end + return value + end + if tick == 0 and not fast then + return value + end + if y == 0 then + return min(hi, value + x) + elseif x == 0 then + return max(0, value - y) + end + return value +end + +-- ------------------------------------------------------------------------------------------------ MOD / XM effects +local function fxModXm(st: any, c: any, tick: number) + local fx, param = c.fx, c.param + local xm = st.fmt == XM + local x, y = param // 16, param % 16 + if fx == 0 then + if param ~= 0 then + local k = tick % 3 + c.arp = if k == 1 then x elseif k == 2 then y else 0 + end + elseif fx == 1 then + if xm and param > 0 then + c.mPortaUp = param + end + if tick > 0 then + c.period -= (if xm then c.mPortaUp else param) * 4 + clampPeriod(st, c) + end + elseif fx == 2 then + if xm and param > 0 then + c.mPortaDn = param + end + if tick > 0 then + c.period += (if xm then c.mPortaDn else param) * 4 + clampPeriod(st, c) + end + elseif fx == 3 or fx == 5 then + if fx == 3 and param > 0 then + c.portaSpeed = param + end + if tick > 0 then + tonePorta(st, c, c.portaSpeed * 4) + end + elseif fx == 4 or fx == 6 then + if fx == 4 then + if x > 0 then + c.vibSpeed = x + end + if y > 0 then + c.vibDepth = y + end + end + if tick > 0 then + vibrato(st, c, 8 / 255) + end + elseif fx == 7 then + if x > 0 then + c.tremSpeed = x + end + if y > 0 then + c.tremDepth = y + end + if tick > 0 then + tremolo(c, 1 / 64) + end + elseif fx == 8 then + if tick == 0 then + c.pan = param + c.basePan = c.pan + c.surround = false + end + elseif fx == 0xB then + if tick == 0 then + st.jumpOrd = param + if st.breakRow < 0 then + st.breakRow = 0 + end + end + elseif fx == 0xC then + if tick == 0 then + c.vol = min(param, 64) + end + elseif fx == 0xD then + if tick == 0 then + local r = x * 10 + y + if r > 63 then + r = 0 + end + st.breakRow = r + end + elseif fx == 0xE then + if x == 1 then + if xm and y > 0 then + c.mFineUp = y + end + if tick == 0 then + c.period -= (if xm then c.mFineUp else y) * 4 + clampPeriod(st, c) + end + elseif x == 2 then + if xm and y > 0 then + c.mFineDn = y + end + if tick == 0 then + c.period += (if xm then c.mFineDn else y) * 4 + clampPeriod(st, c) + end + elseif x == 4 then + c.vibWave = y % 8 + elseif x == 6 then + if tick == 0 then + if y == 0 then + c.loopRow = st.row + elseif c.loopCount == 0 then + c.loopCount = y + st.loopJump = c.loopRow + st.ft2BreakPos = c.loopRow + else + c.loopCount -= 1 + if c.loopCount > 0 then + st.loopJump = c.loopRow + end + st.ft2BreakPos = c.loopRow + end + end + elseif x == 7 then + c.tremWave = y % 8 + elseif x == 8 then + if tick == 0 then -- FT2 ignores E8x in XM; OpenMPT (the reference) applies it + c.pan = y * 17 + c.basePan = c.pan + c.surround = false + end + elseif x == 9 then + if y > 0 and tick > 0 and tick % y == 0 then + retrigVoice(st, c) + end + elseif x == 0xA then + if xm and y > 0 then + c.mFineVolUp = y + end + if tick == 0 then + c.vol = min(64, c.vol + (if xm then c.mFineVolUp else y)) + end + elseif x == 0xB then + if xm and y > 0 then + c.mFineVolDn = y + end + if tick == 0 then + c.vol = max(0, c.vol - (if xm then c.mFineVolDn else y)) + end + elseif x == 0xC then + if tick == y then + c.vol = 0 + end + elseif x == 0xE then + if tick == 0 and st.patDelayRep == 0 and st.patDelay == 0 then + st.patDelay = y + end + end + elseif fx == 0xF then + if tick == 0 then + if param == 0 then + if not xm then + st.stopAfterRow = true -- ProTracker F00: the song stops (after this row, as OpenMPT plays it) + end + elseif param < 32 then + st.speed = param + else + st.tempo = param + end + end + elseif fx == 16 then -- G + if tick == 0 then + st.gvol = min(param, 64) * 2 + end + elseif fx == 17 then -- H + if param > 0 then + c.mGVolSlide = param + end + if tick > 0 then + local p = c.mGVolSlide + local px, py = p // 16, p % 16 + if px > 0 then + st.gvol = min(128, st.gvol + px * 2) + else + st.gvol = max(0, st.gvol - py * 2) + end + end + elseif fx == 20 then -- K + if tick == param then + keyOff(st, c.voice) + end + elseif fx == 21 then -- L + if tick == 0 and c.voice then + c.voice.volEnvPos = param + c.voice.panEnvPos = param + end + elseif fx == 25 then -- P + if param > 0 then + c.mPanSlide = param + end + if tick > 0 then + local p = c.mPanSlide + local px, py = p // 16, p % 16 + if px > 0 then + c.pan = min(255, c.pan + px) + c.basePan = c.pan + else + c.pan = max(0, c.pan - py) + c.basePan = c.pan + end + end + elseif fx == 27 then -- R + if x > 0 then + c.mRetrig = c.mRetrig % 16 + x * 16 + end + if y > 0 then + c.mRetrig = (c.mRetrig // 16) * 16 + y + end + local interval = c.mRetrig % 16 + if tick == 0 and c.triggered then + c.retrigCount = 0 + else + c.retrigCount += 1 + end + if interval > 0 and c.retrigCount >= interval then + c.retrigCount = 0 + retrigVolume(c, c.mRetrig // 16) + retrigVoice(st, c) + end + elseif fx == 29 then -- T + if param > 0 then + c.mTremor = param + end + elseif fx == 33 then -- X + if x == 1 then + if y > 0 then + c.mXFineUp = y + end + if tick == 0 then + c.period -= c.mXFineUp + clampPeriod(st, c) + end + elseif x == 2 then + if y > 0 then + c.mXFineDn = y + end + if tick == 0 then + c.period += c.mXFineDn + clampPeriod(st, c) + end + end + end + -- the volume slide half of 5xy / 6xy and Axy + if fx == 0xA or fx == 5 or fx == 6 then + if xm then + if param > 0 then + c.mVolSlide = param + end + if tick > 0 then + volSlideMod(c, c.mVolSlide) + end + elseif tick > 0 then + volSlideMod(c, param) + end + end + -- tremor (XM Txy): on x + 1 ticks, off y + 1 ticks + if fx == 29 and tick > 0 then + local on, off = c.mTremor // 16 + 1, c.mTremor % 16 + 1 + c.tremorCount %= on + off + c.tremorOn = c.tremorCount < on + c.tremorCount += 1 + end +end + +-- the XM volume column (everything but set volume / set panning, done by trigger) +local function volColXm(st: any, c: any, tick: number) + local v = c.vcmd + if v < 0x60 then + return + end + local hi, lo = v // 16, v % 16 + if hi == 6 then + if tick > 0 then + c.vol = max(0, c.vol - lo) + end + elseif hi == 7 then + if tick > 0 then + c.vol = min(64, c.vol + lo) + end + elseif hi == 8 then + if tick == 0 then + c.vol = max(0, c.vol - lo) + end + elseif hi == 9 then + if tick == 0 then + c.vol = min(64, c.vol + lo) + end + elseif hi == 0xA then + if lo > 0 then + c.vibSpeed = lo + end + elseif hi == 0xB then + if lo > 0 then + c.vibDepth = lo + end + if tick > 0 then + vibrato(st, c, 8 / 255) + end + elseif hi == 0xD then + if tick > 0 then + c.pan = max(0, c.pan - lo) + c.basePan = c.pan + end + elseif hi == 0xE then + if tick > 0 then + c.pan = min(255, c.pan + lo) + c.basePan = c.pan + end + elseif hi == 0xF then + if lo > 0 then + c.portaSpeed = lo * 16 + end + if tick > 0 then + tonePorta(st, c, c.portaSpeed * 4) + end + end +end + +-- ------------------------------------------------------------------------------------------------ S3M / IT effects +-- the parameter after memory: IT keeps one memory per effect group, ST3 one memory for most effects +local function mem(st: any, c: any, field: string, param: number): number + if st.fmt == S3M then + if param > 0 then + c.mS3M = param + end + return c.mS3M + end + if param > 0 then + c[field] = param + end + return c[field] +end + +local function portaS3m(st: any, c: any, p: number, tick: number, sign: number) + if p >= 0xF0 then + if tick == 0 then + c.period += sign * (p % 16) * 4 + end + elseif p >= 0xE0 then + if tick == 0 then + c.period += sign * (p % 16) + end + elseif tick > 0 then + c.period += sign * p * 4 + end + clampPeriod(st, c) +end + +local function fxS3mIt(st: any, c: any, tick: number) + local fx, param = c.fx, c.param + local it = st.fmt == IT + if fx == 1 then -- A speed + if tick == 0 and param > 0 then + st.speed = param + end + elseif fx == 2 then -- B jump + if tick == 0 then + st.jumpOrd = param + if st.breakRow < 0 then + st.breakRow = 0 + end + end + elseif fx == 3 then -- C break + if tick == 0 then + st.breakRow = if it then param else (param // 16) * 10 + param % 16 + end + elseif fx == 4 or fx == 11 or fx == 12 then -- D volume slide (K, L: + vibrato / tone portamento) + local p = mem(st, c, "mVolSlide", param) + c.vol = dSlide(c.vol, p, tick, st.fastSlides, 64) + elseif fx == 5 then -- E porta down + local p = mem(st, c, "mEF", param) + portaS3m(st, c, p, tick, 1) + elseif fx == 6 then -- F porta up + local p = mem(st, c, "mEF", param) + portaS3m(st, c, p, tick, -1) + elseif fx == 9 then -- I tremor + local p = mem(st, c, "mTremor", param) + if tick > 0 or not it then + local on, off = p // 16, p % 16 + if it and st.oldFx or not it then + on, off = on + 1, off + 1 + end + on, off = max(on, 1), max(off, 1) + c.tremorCount %= on + off + c.tremorOn = c.tremorCount < on + c.tremorCount += 1 + end + elseif fx == 10 then -- J arpeggio + local p = mem(st, c, "mArp", param) + local k = tick % 3 + c.arp = if k == 1 then p // 16 elseif k == 2 then p % 16 else 0 + elseif fx == 13 then -- M channel volume + if tick == 0 and param <= 64 then + c.chanVol = param + end + elseif fx == 14 then -- N channel volume slide + local p = mem(st, c, "mChanVolSlide", param) + c.chanVol = dSlide(c.chanVol, p, tick, false, 64) + elseif fx == 16 then -- P panning slide (0..64 scale x 4) + local p = mem(st, c, "mPanSlide", param) + local pan64 = c.pan / 4 + local x, y = p // 16, p % 16 + if y == 0xF and x > 0 then + if tick == 0 then + pan64 = max(0, pan64 - x) + end + elseif x == 0xF and y > 0 then + if tick == 0 then + pan64 = min(64, pan64 + y) + end + elseif tick > 0 then + if y == 0 then + pan64 = max(0, pan64 - x) + elseif x == 0 then + pan64 = min(64, pan64 + y) + end + end + c.pan = pan64 * 4 + c.basePan = c.pan + c.surround = false + elseif fx == 17 then -- Q retrigger + volume change + local p = mem(st, c, "mRetrig", param) + local interval = p % 16 + if interval > 0 then + if tick == 0 and c.retrigCount <= 0 then + c.retrigCount = interval + end + if tick > 0 then + c.retrigCount -= 1 + if c.retrigCount <= 0 then + c.retrigCount = interval + retrigVolume(c, p // 16) + retrigVoice(st, c) + end + end + end + elseif fx == 18 then -- R tremolo + if param // 16 > 0 then + c.tremSpeed = param // 16 + end + if param % 16 > 0 then + c.tremDepth = param % 16 + end + if tick > 0 then + tremolo(c, 1 / 64) + end + elseif fx == 19 then -- S extended + local p = if it then mem(st, c, "mS", param) else mem(st, c, "mS", param) + local x, y = p // 16, p % 16 + if x == 3 then + c.vibWave = y % 8 + elseif x == 4 then + c.tremWave = y % 8 + elseif x == 5 then + c.panbWave = y % 8 + elseif x == 6 then + if tick == 0 then + st.fineDelay += y + end + elseif x == 7 then + if tick == 0 then + if y <= 2 then + for _, u in st.voices do + if u.active and u.bg and u.chan == c.idx then + if y == 0 then + cutVoice(u) + elseif y == 1 then + keyOff(st, u) + else + noteFade(u) + end + end + end + elseif y <= 6 then + c.nna = y - 3 + else + local v = c.voice + if v then + if y == 7 then + v.volEnvOn = false + elseif y == 8 then + v.volEnvOn = true + elseif y == 9 then + v.panEnvOn = false + elseif y == 10 then + v.panEnvOn = true + elseif y == 11 then + v.pitchEnvOn = false + elseif y == 12 then + v.pitchEnvOn = true + end + end + end + end + elseif x == 8 then + if tick == 0 then + c.pan = y * 17 + c.basePan = c.pan + c.surround = false + end + elseif x == 9 then + if tick == 0 and y == 1 then + c.surround = true + end + elseif x == 0xA then + if tick == 0 then + c.mHighOffset = y + end + elseif x == 0xB then + if tick == 0 then + if y == 0 then + c.loopRow = st.row + elseif c.loopCount == 0 then + c.loopCount = y + st.loopJump = c.loopRow + else + c.loopCount -= 1 + if c.loopCount > 0 then + st.loopJump = c.loopRow + elseif it then + c.loopRow = st.row + 1 + end + end + end + elseif x == 0xC then + local at = if y == 0 and it then 1 else y + if tick == at and (y > 0 or it) then + if it then + cutVoice(c.voice) + end + c.vol = 0 + end + elseif x == 0xE then + if tick == 0 and st.patDelayRep == 0 and st.patDelay == 0 then + st.patDelay = y + end + end + elseif fx == 20 then -- T tempo + if param >= 0x20 then + if tick == 0 then + st.tempo = param + end + elseif it then + if param > 0 then + c.mTempo = param + end + local p = c.mTempo + if tick > 0 then + if p >= 0x10 then + st.tempo = min(255, st.tempo + (p - 0x10)) + else + st.tempo = max(32, st.tempo - p) + end + end + end + elseif fx == 22 then -- V global volume + if tick == 0 then + if it then + if param <= 128 then + st.gvol = param + end + else + st.gvol = min(param, 64) * 2 + end + end + elseif fx == 23 then -- W global volume slide + local p = mem(st, c, "mGVolSlide", param) + st.gvol = dSlide(st.gvol, p, tick, false, 128) + elseif fx == 24 then -- X panning + if tick == 0 then + if it then + c.pan = param + c.basePan = c.pan + c.surround = false + elseif param <= 0x80 then + c.pan = param * 2 + c.basePan = c.pan + c.surround = false + elseif param == 0xA4 then + c.surround = true + end + end + elseif fx == 25 then -- Y panbrello + if param // 16 > 0 then + c.panbSpeed = param // 16 + end + if param % 16 > 0 then + c.panbDepth = param % 16 + end + c.panbDelta = wave64(c.panbWave % 4, c.panbPos // 4) * c.panbDepth / 16 + c.panbPos = (c.panbPos + c.panbSpeed) % 256 + elseif fx == 26 then -- Z MIDI macro: the default IT macros (Z00..Z7F cutoff, Z80..Z8F resonance) + if tick == 0 then + if param < 0x80 then + c.cutoff = param + elseif param < 0x90 then + c.reso = (param - 0x80) * 8 + end + if c.voice then + c.voice.cutoff, c.voice.reso = c.cutoff, c.reso + end + end + end + -- tone portamento (G, L) + if fx == 7 or fx == 12 then + if fx == 7 then + if st.fmt == S3M then + if param > 0 then + c.portaSpeed = param + end + elseif st.compatG then + if param > 0 then + c.portaSpeed = param + end + else + if param > 0 then + c.mEF = param + end + c.portaSpeed = c.mEF + end + end + if tick > 0 then + tonePorta(st, c, c.portaSpeed * 4) + end + end + -- vibrato (H, U, K) + if fx == 8 or fx == 21 or fx == 11 then + if fx ~= 11 then + if param // 16 > 0 then + c.vibSpeed = param // 16 + end + if param % 16 > 0 then + c.vibDepth = param % 16 + end + end + local scale = if fx == 21 then 2 / 255 else 8 / 255 + if it and not st.oldFx then + scale /= 2 + end + if tick > 0 or (it and not st.oldFx) then + vibrato(st, c, scale) + end + end +end + +-- the IT volume column (value stored + 1): slides, portamento, vibrato +local function volColIt(st: any, c: any, tick: number) + local v = c.vcmd - 1 + if v < 65 then + return + end + if v <= 74 then + local p = v - 65 + if p > 0 then + c.mVolCol = p + end + if tick == 0 then + c.vol = min(64, c.vol + c.mVolCol) + end + elseif v <= 84 then + local p = v - 75 + if p > 0 then + c.mVolCol = p + end + if tick == 0 then + c.vol = max(0, c.vol - c.mVolCol) + end + elseif v <= 94 then + local p = v - 85 + if p > 0 then + c.mVolCol = p + end + if tick > 0 then + c.vol = min(64, c.vol + c.mVolCol) + end + elseif v <= 104 then + local p = v - 95 + if p > 0 then + c.mVolCol = p + end + if tick > 0 then + c.vol = max(0, c.vol - c.mVolCol) + end + elseif v <= 114 then + local p = (v - 105) * 4 + if p > 0 then + c.mEF = p + end + if tick > 0 then + c.period += c.mEF * 4 + clampPeriod(st, c) + end + elseif v <= 124 then + local p = (v - 115) * 4 + if p > 0 then + c.mEF = p + end + if tick > 0 then + c.period -= c.mEF * 4 + clampPeriod(st, c) + end + elseif v >= 193 and v <= 202 then + local p = Tables.IT_VOLPORTA[v - 192] or 0 + if p > 0 then + if st.compatG then + c.portaSpeed = p + else + c.mEF = p + c.portaSpeed = p + end + end + if tick > 0 then + tonePorta(st, c, c.portaSpeed * 4) + end + elseif v >= 203 and v <= 212 then + local d = v - 203 + if d > 0 then + c.vibDepth = d + end + if tick > 0 or not st.oldFx then + vibrato(st, c, if st.oldFx then 8 / 255 else 4 / 255) + end + end +end + +-- ------------------------------------------------------------------------------------------------ rows and ticks +local function noteDelayOf(st: any, fx: number, param: number): number + if (st.fmt == MOD or st.fmt == XM) and fx == 0xE and param // 16 == 0xD then + return param % 16 + elseif (st.fmt == S3M or st.fmt == IT) and fx == 19 and param // 16 == 0xD then + return param % 16 + end + return 0 +end + +local function finetuneOf(st: any, fx: number, param: number): number? + if (st.fmt == MOD or st.fmt == XM) and fx == 0xE and param // 16 == 5 then + local y = param % 16 + if st.fmt == MOD then + return (if y >= 8 then y - 16 else y) * 16 + end + return (y - 8) * 16 + end + return nil +end + +local function runEffects(st: any, c: any, tick: number) + c.vibDelta, c.arp = 0, 0 + if st.fmt == MOD or st.fmt == XM then + fxModXm(st, c, tick) + if st.fmt == XM then + volColXm(st, c, tick) + end + else + if st.fmt == IT then + volColIt(st, c, tick) + end + fxS3mIt(st, c, tick) + end + -- keep the tremolo / panbrello offsets only while their effect runs + local fx = c.fx + if st.fmt == MOD or st.fmt == XM then + if fx ~= 7 then + c.tremDelta = 0 + end + -- XM: a tremor that ends in its off phase keeps the channel silent until the next note (OpenMPT / FT2) + else + if fx ~= 18 then + c.tremDelta = 0 + end + if fx ~= 9 then + c.tremorOn = true + end + if fx ~= 25 then + c.panbDelta = 0 + end + end +end + +local function processRow(st: any) + local m = st.m + local pat = st.pat + local nch = st.nch + local data = pat.data + local base = st.row * nch * 5 + st.visited[st.ord * 1024 + st.row] = true + st.rows += 1 + for i = 1, nch do + local c = st.chans[i] + local o = base + (i - 1) * 5 + local note, ins, vcmd, fx, param = readu8(data, o), readu8(data, o + 1), readu8(data, o + 2), readu8(data, o + 3), readu8(data, o + 4) + if (st.fmt == MOD or st.fmt == XM) and fx == 0 and param == 0 then + fx = 255 + end + c.fx, c.param, c.vcmd = fx, param, vcmd + c.cutTick, c.keyOffTick = -1, -1 + c.triggered = false + local delay = noteDelayOf(st, fx, param) + c.finetune = finetuneOf(st, fx, param) + if delay > 0 then + c.delayTick, c.dNote, c.dIns, c.dVol = delay, note, ins, vcmd + else + c.delayTick = -1 + trigger(st, c, note, ins, vcmd) + end + runEffects(st, c, 0) + end + local _ = m +end + +local function updateEnvelope(env: any, pos: number, keyOn: boolean, it: boolean): (number, number, boolean) + -- returns value, next position, ended + local ticks, values = env.ticks, env.values + local n = #ticks + if n == 0 then + return 0, pos, true + end + local value + if pos <= ticks[1] then + value = values[1] + elseif pos >= ticks[n] then + value = values[n] + else + local i = 1 + while i < n and ticks[i + 1] <= pos do + i += 1 + end + local t0, t1 = ticks[i], ticks[i + 1] + if t1 > t0 then + value = values[i] + (values[i + 1] - values[i]) * (pos - t0) / (t1 - t0) + else + value = values[i + 1] + end + end + local nextPos = pos + 1 + local ended = false + -- sustain / loop: only when the position runs over the end point (a position set past it, by Lxx, runs on) + -- FT2 jumps when the position reaches the end tick (its value is not played: a loop lasts end - start ticks), + -- IT after playing it (end - start + 1 ticks) + local se, le = ticks[env.susEnd], ticks[env.loopEnd] + local over = if it then 1 else 0 + if keyOn and env.sustain and se and pos <= se and nextPos >= se + over then + nextPos = ticks[env.susStart] or nextPos + elseif env.loop and le and pos <= le and nextPos >= le + over then + nextPos = ticks[env.loopStart] or nextPos + elseif nextPos > ticks[n] then + nextPos = ticks[n] + ended = true + end + return value, nextPos, ended +end + +-- per-tick voice update: envelopes, fadeout, auto-vibrato, final frequency, gains and filter +local function updateVoice(st: any, v: any) + local ins = v.ins + local it = st.fmt == IT + local envVol, envPan, envPitch = 64, 0, 0 + local filterEnv = nil + if ins then + local e = ins.volEnv + if e and e.enabled and v.volEnvOn then + local val, np, ended = updateEnvelope(e, v.volEnvPos, v.keyOn, it) + envVol, v.volEnvPos = val, np + if ended and it then + if val <= 0 then + v.active = false + return + end + v.fading = true + end + end + e = ins.panEnv + if e and e.enabled and v.panEnvOn then + local val, np = updateEnvelope(e, v.panEnvPos, v.keyOn, it) + envPan, v.panEnvPos = val, np + end + e = ins.pitchEnv + if e and e.enabled and v.pitchEnvOn then + local val, np = updateEnvelope(e, v.pitchEnvPos, v.keyOn, it) + v.pitchEnvPos = np + if e.filter then + filterEnv = val + else + envPitch = val + end + end + if v.fading then + local fo = ins.fadeout or 0 + v.fade -= if it then fo * 64 else fo * 2 + if v.fade <= 0 then + v.fade = 0 + v.active = false + return + end + end + end + v.envVol = envVol + -- auto-vibrato: XM per instrument, IT per sample + local avSrc = if it then v.smp else ins + local avDelta = 0 + if avSrc and (avSrc.vibDepth or 0) > 0 then + local depth = avSrc.vibDepth + local sweep = avSrc.vibSweep or 0 + if it then + -- IT: the depth ramps up by the rate (vibSweep here) every tick, in 1/256 steps + local target = depth * 256 + if sweep == 0 then + v.avAmp = target + elseif v.avAmp < target then + v.avAmp = min(target, v.avAmp + sweep) + end + avDelta = autoWave(avSrc.vibType or 0, v.avPos, true) * v.avAmp / (256 * 64) * 4 + else + if sweep == 0 then + v.avAmp = depth * 256 + elseif v.keyOn then + v.avAmp = min(depth * 256, v.avAmp + depth * 256 / sweep) + end + avDelta = autoWave(avSrc.vibType or 0, v.avPos, false) * v.avAmp / (256 * 64) + end + v.avPos = (v.avPos + (avSrc.vibRate or 0)) % 256 + end + -- frequency + local P = v.periodOut + avDelta + local freq + if st.linear then + freq = v.base * 2 ^ (-P / 768) + else + freq = if P > 0 then st.amiga / P else 0 + end + if envPitch ~= 0 then + freq *= 2 ^ (envPitch / 24) + end + v.inc = freq / st.sr + -- volume + local smp = v.smp + local vol = v.vol / 64 * envVol / 64 * v.fade / 65536 * st.gvol / 128 + if it then + vol *= v.chanVol / 64 * (if smp then (smp.globalVolume or 64) / 64 else 1) * (if ins then (ins.globalVolume or 128) / 128 else 1) + end + if v.tremorMute then + vol = 0 + end + -- panning + local pan = v.pan + if it and ins and (ins.pps or 0) ~= 0 then + pan = clamp(pan + ((v.patNote or v.note) - (ins.ppc or 60) - 1) * ins.pps / 2, 0, 256) + end + if envPan ~= 0 then + local range = 128 - abs(pan - 128) + pan += envPan * range / 32 + end + pan = clamp(pan, 0, 256) + pan = clamp(128 + (pan - 128) * st.separation, 0, 256) + local g = vol * st.master + if v.surround then + v.tl, v.tr = g * 0.5, -g * 0.5 + else + v.tl, v.tr = g * (256 - pan) / 256, g * pan / 256 + end + v.rampN = st.ramp + -- IT resonant filter + local cutoff = v.cutoff + if filterEnv ~= nil or cutoff < 127 or v.reso > 0 then + local cc = cutoff + if filterEnv ~= nil then + cc = cutoff * (filterEnv + 32) / 64 + end + local fhz = 110 * 2 ^ (0.25 + cc / 24) + fhz = clamp(fhz, 120, min(20000, st.sr / 2)) + local dmp = 10 ^ (-v.reso * (24 / 128) / 20) + local fc = fhz * 2 * math.pi / st.sr + local d = (1 - 2 * dmp) * fc + if d > 2 then + d = 2 + end + d = (2 * dmp - d) / fc + local e = 1 / (fc * fc) + local den = 1 + d + e + v.fa, v.fb0, v.fb1 = 1 / den, (d + e + e) / den, -e / den + v.fOn = not (cc >= 127 and v.reso == 0) + else + v.fOn = false + end +end + +-- tick(st) -> frames to mix for this tick (0 when the song ended) +function Player.tick(st: any): number + if st.ended then + return 0 + end + local tick = st.tick + if tick == 0 and st.patDelayRep == 0 then + local key = st.ord * 1024 + st.row + if st.visited[key] and not st.loopAllowed then + st.ended = true + return 0 + end + if st.visited[key] then + -- looping on: forget the song so far, keep playing + table.clear(st.visited) + end + st.fineDelay = 0 + processRow(st) + else + local t = tick % st.speed + local rep = tick >= st.speed or st.patDelayRep > 0 + for i = 1, st.nch do + local c = st.chans[i] + if c.delayTick == tick and not rep then + c.delayTick = -1 + trigger(st, c, c.dNote, c.dIns, c.dVol) + end + if rep and t == 0 then + c.vibDelta, c.arp = 0, 0 + else + runEffects(st, c, if t == 0 then 1 else t) + end + end + end + if st.ended then + return 0 + end + -- channel -> foreground voice + for i = 1, st.nch do + local c = st.chans[i] + local v = c.voice + if v and v.active and v.chan == i and not v.bg then + local P = arpPeriod(st, c.period, c.arp) + c.vibDelta + v.period, v.periodOut, v.base = c.period, P, c.base + v.vol = clamp(c.vol + c.tremDelta, 0, 64) + if c.muted then + v.vol = 0 + end + v.pan = clamp(c.pan + c.panbDelta, 0, 256) + v.surround = c.surround + v.chanVol = c.chanVol + v.tremorMute = not c.tremorOn + v.cutoff, v.reso = c.cutoff, c.reso + end + end + for _, v in st.voices do + if v.active then + updateVoice(st, v) + end + end + -- frames for this tick: 2.5 / tempo seconds, truncated per tick (as OpenMPT does) + local frames = floor(st.sr * 2.5 / max(1, st.tempo)) + -- advance + st.tick += 1 + if st.tick >= st.speed + st.fineDelay then + st.tick = 0 + if st.patDelayRep < st.patDelay then + st.patDelayRep += 1 + else + st.patDelay, st.patDelayRep = 0, 0 + advanceRow(st) + end + end + return frames +end + +return Player diff --git a/src/Formats/codecs/Tracker/Tables.luau b/src/Formats/codecs/Tracker/Tables.luau new file mode 100644 index 0000000..c621ec1 --- /dev/null +++ b/src/Formats/codecs/Tracker/Tables.luau @@ -0,0 +1,113 @@ +--!strict +--!native +-- codecs/Tracker/Tables: lookup tables of the tracker engine. Waveforms for vibrato / tremolo / panbrello and the +-- auto-vibrato, the ProTracker period table (finetune 0, used to map MOD periods to notes and back) and the IT / S3M +-- volume-column tone-portamento and retrigger tables. All values are from the public format documents (ProTracker +-- 2.3 effect docs, FT2 / XM spec, ST3 TECH.DOC, ITTECH.TXT). +local Tables = {} + +-- the ProTracker half-sine (32 steps, 0..255) +local SINE32 = { 0, 24, 49, 74, 97, 120, 141, 161, 180, 197, 212, 224, 235, 244, 250, 253, 255, 253, 250, 244, 235, 224, 212, 197, 180, 161, 141, 120, 97, 74, 49, 24 } + +-- wave64(type, pos) -> -255..255 for pos 0..63: 0 sine, 1 ramp down, 2 square, 3 random (deterministic) +local RANDOM: { number } = {} +do + local s = 12345 + for i = 1, 64 do + s = (s * 1103515245 + 12345) % 2147483648 + RANDOM[i] = (s // 65536) % 511 - 255 + end +end +function Tables.wave64(kind: number, pos: number): number + local p = pos % 64 + if kind == 1 then + return 255 - p * 8 + elseif kind == 2 then + return if p < 32 then 255 else -255 + elseif kind == 3 then + return RANDOM[p + 1] + end + local v = SINE32[(p % 32) + 1] + return if p >= 32 then -v else v +end + +-- autoWave(type, pos, it) -> -64..64 for pos 0..255. XM: 0 sine, 1 square, 2 ramp down, 3 ramp up. +-- IT: 0 sine, 1 ramp down, 2 square, 3 random. +local SINE256: { number } = {} +for i = 0, 255 do + SINE256[i + 1] = math.floor(math.sin(i * math.pi / 128) * 64 + 0.5) +end +function Tables.autoWave(kind: number, pos: number, it: boolean): number + local p = pos % 256 + if it then + if kind == 1 then + return 64 - (p + 1) // 2 + elseif kind == 2 then + return if p < 128 then 64 else -64 + elseif kind == 3 then + return RANDOM[(p % 64) + 1] // 4 + end + return SINE256[p + 1] + end + if kind == 1 then + return if p < 128 then 64 else -64 + elseif kind == 2 then + return 64 - (p + 1) // 2 + elseif kind == 3 then + return (p + 1) // 2 - 64 + end + return SINE256[p + 1] +end + +-- ProTracker periods, finetune 0, C-0 .. B-4 (60 notes; ProTracker itself uses C-1 .. B-3). Our note numbers: +-- 1 = C-0 (FT2 numbering), so ProTracker C-1 (856) = note 37 and C-2 (428) = note 49, the note that plays a sample at +-- its base rate (8363 Hz). +local PERIODS = { + 3424, 3232, 3048, 2880, 2712, 2560, 2416, 2280, 2152, 2032, 1920, 1812, + 1712, 1616, 1524, 1440, 1356, 1280, 1208, 1140, 1076, 1016, 960, 906, + 856, 808, 762, 720, 678, 640, 604, 570, 538, 508, 480, 453, + 428, 404, 381, 360, 339, 320, 302, 285, 269, 254, 240, 226, + 214, 202, 190, 180, 170, 160, 151, 143, 135, 127, 120, 113, + 107, 101, 95, 90, 85, 80, 75, 71, 67, 63, 60, 56, +} +Tables.PERIODS = PERIODS +Tables.PERIOD_FIRST_NOTE = 13 -- PERIODS[1] is note 13 (C-1 in FT2 numbering = ProTracker octave -1) + +-- periodToNote(period) -> note (1..120), 0 for period 0 +function Tables.periodToNote(period: number): number + if period <= 0 then + return 0 + end + -- exact match first, then the nearest note on a log scale + for i = 1, #PERIODS do + if PERIODS[i] == period then + return i + Tables.PERIOD_FIRST_NOTE - 1 + end + end + local n = 49 + math.floor(12 * math.log(428 / period) / math.log(2) + 0.5) + return math.clamp(n, 1, 120) +end + +-- noteToPeriod(note) -> ProTracker period (finetune 0) for a note, computed past the table's ends +function Tables.noteToPeriod(note: number): number + local i = note - Tables.PERIOD_FIRST_NOTE + 1 + if i >= 1 and i <= #PERIODS then + return PERIODS[i] + end + return math.max(1, math.floor(428 * 2 ^ ((49 - note) / 12) + 0.5)) +end + +-- IT volume column "g" (tone portamento) speeds +Tables.IT_VOLPORTA = { 0, 1, 4, 8, 16, 32, 64, 96, 128, 255 } + +-- XM Rxy / S3M-IT Qxy volume changes: kind 0 add, 1 multiply; value +Tables.RETRIG_ADD = { 0, -1, -2, -4, -8, -16, 0, 0, 0, 1, 2, 4, 8, 16, 0, 0 } +Tables.RETRIG_MUL = { 1, 1, 1, 1, 1, 1, 2 / 3, 0.5, 1, 1, 1, 1, 1, 1, 1.5, 2 } + +-- the Amiga clock constant: frequency = AMIGA / period, with period 1712 playing an 8363 Hz sample at its base rate +-- (FT2 / ST3 period units, 4x ProTracker's) +Tables.AMIGA = 8363 * 1712 +-- MOD: the PAL Amiga clock (7093789.2 Hz / 2 per ProTracker period unit; period 428 plays at 8287 Hz) +Tables.AMIGA_PAL = 7093789.2 / 2 * 4 + +return Tables diff --git a/src/Formats/codecs/Tracker/init.luau b/src/Formats/codecs/Tracker/init.luau new file mode 100644 index 0000000..391ea94 --- /dev/null +++ b/src/Formats/codecs/Tracker/init.luau @@ -0,0 +1,516 @@ +--!strict +-- codecs/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it. The four loaders read +-- their files into one Module structure (below); render(module, opts) plays any of them through the standard audio +-- Decoder (Types.Decoder: stereo f32). Written for this library from the format documents (ProTracker 2.3, the XM +-- spec + FT2 behaviour, ST3 TECH.DOC, ITTECH.TXT); libxmp / OpenMPT were used only as reference players for tests. +-- +-- local Tracker = require("@formats/codecs/Tracker") +-- local dec, err = Tracker.render(module, { sampleRate = 44100 }) -- a Types.Decoder +-- local seconds = Tracker.duration(module) -- one pass, song loops detected +-- +-- Module (Types.Module plus the engine fields; pattern / instrument / sample numbers are as in the file): +-- format "mod" | "s3m" | "xm" | "it": selects the effect family and the format quirks +-- title, channels, speed (ticks per row), tempo (BPM: a tick lasts 2.5 / tempo s) +-- globalVolume 0..128 (S3M / XM 0..64 are stored doubled), mixVolume 0..128 (IT mix volume, S3M master volume) +-- order { pattern number (0-based) | 254 skip ("+++") | 255 end ("---") }, restart (0-based order index) +-- linear linear frequency slides (XM / IT flag) or Amiga periods +-- instrumentMode XM, IT with instruments: notes go through Instrument keymaps; otherwise the instrument column +-- is a sample number (MOD, S3M, IT sample mode) +-- flags { oldEffects, compatGxx (IT), fastSlides (ST3.00 volume slides), amigaLimits (MOD) } +-- channelPan { 0..256 per channel (128 centre; 512 = surround); MOD: 64 / 192 (Amiga L R R L at half width, +-- as OpenMPT plays it; set 0 / 256 or render with stereoSeparation = 200 for hard panning) }, channelVolume { 0..64 }, channelMute { bool } +-- patterns { Pattern } (pattern n at patterns[n + 1]); Pattern = { rows, data }: data holds rows * channels +-- cells of 5 bytes: note, instrument, volume column, effect, parameter. Notes: 0 none, 1..120 (1 = +-- C-0; C-4 = 49 plays an XM / MOD sample at its base rate, C-5 = 61 an S3M / IT sample at its C5 +-- speed), 253 note fade, 254 note cut, 255 key off. The volume column and effects are kept in the +-- file's own coding: MOD / XM effects 0..35 (XM letters G.. = 16..), XM volume byte as stored; +-- S3M / IT effects 1..26 (A = 1), S3M volume 0 = none else volume + 1, IT volume byte + 1 +-- (0 = none). Tracker.cell / Tracker.setCell read and write cells. +-- samples { Sample }: { name, data (f32, interleaved when stereo), length (frames), channels, bits (8 | 16, +-- for writers), loopStart, loopEnd (frames, end exclusive), loopType (0 none, 1 forward, 2 ping-pong), +-- susStart, susEnd, susType (IT sustain loop), volume 0..64, globalVolume 0..64, pan (0..256 or nil), +-- c5speed (S3M / IT), relativeNote, finetune -128..127 (MOD / XM), vibType / vibSweep / vibDepth / +-- vibRate (IT auto-vibrato) } +-- instruments { Instrument }: { name, sampleMap = { [note] = sample number }, noteMap = { [note] = note }, +-- volEnv / panEnv / pitchEnv (Envelope?), fadeout (as stored: XM 0..4095, IT 0..1024), nna (0 cut, +-- 1 continue, 2 note off, 3 fade), dct (0 off, 1 note, 2 sample, 3 instrument), dca (0 cut, 1 off, +-- 2 fade), globalVolume 0..128, pan (0..256 or nil), pps, ppc (pitch-pan separation / centre), +-- cutoff, resonance (0..127 or nil), vibType / vibSweep / vibDepth / vibRate (XM auto-vibrato) } +-- Envelope { enabled, ticks = { tick }, values = { volume 0..64 | pan / pitch -32..32 }, loop, loopStart, +-- loopEnd, sustain, susStart, susEnd (1-based point indexes), filter (IT pitch envelope as filter) } +-- +-- Pitch: two period spaces. Linear: P = (ref - note) * 64 - transpose (64 per semitone), frequency = base * 2^(-P/768). +-- Amiga: P = 1712 * 8363 / base * 2^(Plinear / 768), frequency = 8363 * 1712 / P (FT2 / ST3 period units; slides add +-- 4 per effect unit in both). MOD / XM: base 8363, ref 49, transpose = relativeNote * 64 + finetune / 2; S3M / IT: +-- base = c5speed, ref 61. +-- +-- Not supported: MIDI macros other than IT's default filter macros (Z00..Z8F), glissando, ST3 / IT finetune effects +-- (S2x), random volume / pan variation, OPL (AdLib) instruments, MOD Amiga low-pass filter emulation. +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Player = require("@formats/codecs/Tracker/Player") +local Mixer = require("@formats/codecs/Tracker/Mixer") +local Pcm = require("@formats/codecs/Tracker/Pcm") +local Tables = require("@formats/codecs/Tracker/Tables") + +local Tracker = {} + +Tracker.Pcm = Pcm +Tracker.Tables = Tables + +export type Envelope = { + enabled: boolean, + ticks: { number }, + values: { number }, + loop: boolean, + loopStart: number, + loopEnd: number, + sustain: boolean, + susStart: number, + susEnd: number, + carry: boolean?, + filter: boolean?, + raw: any?, -- format-specific fields kept for a faithful re-save (XM) +} + +export type Pattern = { rows: number, data: buffer } + +export type RenderOptions = { + sampleRate: number?, -- default 44100 + interpolation: ("linear" | "none")?, -- default "linear" + stereoSeparation: number?, -- 0..200 % (default 100: the panning as stored; 200 doubles every distance from centre) + loop: boolean?, -- keep playing past the song's end (frames / duration still give one pass); default false + maxDuration: number?, -- seconds; the render stops there (default 3600) +} + +local CELL = 5 + +-- ------------------------------------------------------------------------------------------------ constructors +-- newModule(format, channels) -> an empty Module (no patterns / samples) with the format's defaults +function Tracker.newModule(format: string, channels: number): any + local m = { + kind = "music", + format = format, + title = "", + channels = channels, + speed = 6, + tempo = 125, + globalVolume = 128, + mixVolume = 48, + order = {}, + restart = 0, + linear = format == "xm" or format == "it", + instrumentMode = format == "xm" or format == "it", + flags = {}, + channelPan = {}, + channelVolume = {}, + channelMute = {}, + patterns = {}, + instruments = {}, + samples = {}, + meta = {}, + render = Tracker.renderMethod, + } + for i = 1, channels do + m.channelVolume[i] = 64 + if format == "mod" then + local k = (i - 1) % 4 + m.channelPan[i] = if k == 0 or k == 3 then 64 else 192 -- the Amiga's L R R L, at OpenMPT's default width + else + m.channelPan[i] = 128 + end + end + return m +end + +-- newPattern(rows, channels) -> an empty Pattern +function Tracker.newPattern(rows: number, channels: number): Pattern + return { rows = rows, data = buffer.create(rows * channels * CELL) } +end + +-- newSample() -> an empty Sample +function Tracker.newSample(name: string?): any + return { + name = name or "", + data = buffer.create(0), + length = 0, + channels = 1, + bits = 8, + loopStart = 0, + loopEnd = 0, + loopType = 0, + susStart = 0, + susEnd = 0, + susType = 0, + volume = 64, + globalVolume = 64, + pan = nil :: number?, + c5speed = 8363, + relativeNote = 0, + finetune = 0, + vibType = 0, + vibSweep = 0, + vibDepth = 0, + vibRate = 0, + } +end + +function Tracker.newEnvelope(): Envelope + return { enabled = false, ticks = {}, values = {}, loop = false, loopStart = 1, loopEnd = 1, sustain = false, susStart = 1, susEnd = 1 } +end + +-- newInstrument() -> an Instrument mapping every note to sample 0 (none) +function Tracker.newInstrument(name: string?): any + local sm, nm = table.create(120, 0), table.create(120, 0) + for i = 1, 120 do + nm[i] = i + end + return { + name = name or "", + sampleMap = sm, + noteMap = nm, + volEnv = nil :: Envelope?, + panEnv = nil :: Envelope?, + pitchEnv = nil :: Envelope?, + fadeout = 0, + nna = 0, + dct = 0, + dca = 0, + globalVolume = 128, + pan = nil :: number?, + pps = 0, + ppc = 60, + cutoff = nil :: number?, + resonance = nil :: number?, + vibType = 0, + vibSweep = 0, + vibDepth = 0, + vibRate = 0, + } +end + +-- cell(module, pattern, row, channel) -> note, instrument, volume, effect, parameter (pattern 0-based, row 0-based, +-- channel 1-based); nil when out of range +function Tracker.cell(m: any, pattern: number, row: number, channel: number): (number?, number, number, number, number) + local p = m.patterns[pattern + 1] + if not p or row < 0 or row >= p.rows or channel < 1 or channel > m.channels then + return nil, 0, 0, 0, 0 + end + local o = (row * m.channels + channel - 1) * CELL + local d = p.data + return buffer.readu8(d, o), buffer.readu8(d, o + 1), buffer.readu8(d, o + 2), buffer.readu8(d, o + 3), buffer.readu8(d, o + 4) +end + +-- setCell(module, pattern, row, channel, note, instrument, volume, effect, parameter) -> true | false (out of range) +function Tracker.setCell(m: any, pattern: number, row: number, channel: number, note: number, ins: number, vol: number, fx: number, param: number): boolean + local p = m.patterns[pattern + 1] + if not p or row < 0 or row >= p.rows or channel < 1 or channel > m.channels then + return false + end + local o = (row * m.channels + channel - 1) * CELL + local d = p.data + buffer.writeu8(d, o, note % 256) + buffer.writeu8(d, o + 1, ins % 256) + buffer.writeu8(d, o + 2, vol % 256) + buffer.writeu8(d, o + 3, fx % 256) + buffer.writeu8(d, o + 4, param % 256) + return true +end + +-- ------------------------------------------------------------------------------------------------ validation +local function num(v: any, lo: number, hi: number): boolean + return type(v) == "number" and v == v and v >= lo and v <= hi +end + +local function fixEnvelope(e: any): (any, string?) + if e == nil then + return nil + end + if type(e) ~= "table" or type(e.ticks) ~= "table" or type(e.values) ~= "table" then + return nil, "bad envelope" + end + local n = math.min(#e.ticks, #e.values) + local last = -1 + for i = 1, n do + local t, v = e.ticks[i], e.values[i] + if not num(t, 0, 1e6) or not num(v, -64, 64) or t <= last then + -- points must go forward: keep the valid prefix + n = i - 1 + break + end + last = t + end + for i = #e.ticks, n + 1, -1 do + e.ticks[i] = nil + end + for i = #e.values, n + 1, -1 do + e.values[i] = nil + end + if n == 0 then + e.enabled = false + end + local function idx(v: any): number + return if num(v, 1, math.max(1, n)) then math.floor(v) else 1 + end + e.loopStart, e.loopEnd = idx(e.loopStart), idx(e.loopEnd) + e.susStart, e.susEnd = idx(e.susStart), idx(e.susEnd) + if e.loopEnd < e.loopStart then + e.loop = false + end + if e.susEnd < e.susStart then + e.sustain = false + end + return e +end + +local function fixLoop(s0: any, e0: any, t0: any, len: number): (number, number, number) + if not num(t0, 0, 2) or t0 == 0 or not num(s0, -2 ^ 52, 2 ^ 52) or not num(e0, -2 ^ 52, 2 ^ 52) then + return 0, 0, 0 + end + local s: number = math.floor(math.clamp(s0, 0, len)) + local e: number = math.floor(math.clamp(e0, 0, len)) + local t: number = math.floor(t0) + if e - s < 1 or t == 0 then + return 0, 0, 0 + end + if t == 2 and e - s < 2 then + t = 1 + end + return s, e, t +end + +-- validate(module) -> true | nil, Err: checks the structure the engine relies on, clamps loops, envelopes and +-- numbers into range (in place) +function Tracker.validate(m: any): (boolean?, Err.Err?) + if type(m) ~= "table" then + return nil, Err.new(Err.ARG, "not a module") + end + if m.format ~= "mod" and m.format ~= "s3m" and m.format ~= "xm" and m.format ~= "it" then + return nil, Err.new(Err.ARG, "unknown tracker format " .. tostring(m.format)) + end + if not num(m.channels, 1, 128) or m.channels % 1 ~= 0 then + return nil, Err.new(Err.ARG, "bad channel count") + end + if type(m.order) ~= "table" or type(m.patterns) ~= "table" or type(m.samples) ~= "table" then + return nil, Err.new(Err.ARG, "module without order / patterns / samples") + end + m.instruments = if type(m.instruments) == "table" then m.instruments else {} + m.flags = if type(m.flags) == "table" then m.flags else {} + m.channelPan = if type(m.channelPan) == "table" then m.channelPan else {} + m.channelVolume = if type(m.channelVolume) == "table" then m.channelVolume else {} + m.channelMute = if type(m.channelMute) == "table" then m.channelMute else {} + for i = 1, m.channels do + local p = m.channelPan[i] + if p ~= 512 and not num(p, 0, 256) then + m.channelPan[i] = 128 + end + if not num(m.channelVolume[i], 0, 64) then + m.channelVolume[i] = 64 + end + end + m.speed = if num(m.speed, 1, 255) then math.floor(m.speed) else 6 + m.tempo = if num(m.tempo, 1, 1000) then m.tempo else 125 + m.globalVolume = if num(m.globalVolume, 0, 128) then m.globalVolume else 128 + m.mixVolume = if num(m.mixVolume, 0, 256) then m.mixVolume else 48 + m.restart = if num(m.restart, 0, 1e6) then math.floor(m.restart) else 0 + for i, o in m.order do + if not num(o, 0, 255) then + return nil, Err.new(Err.ARG, "bad order entry " .. i) + end + end + for i, p in m.patterns do + if type(p) ~= "table" or not num(p.rows, 1, 1024) or type(p.data) ~= "buffer" or buffer.len(p.data) < p.rows * m.channels * CELL then + return nil, Err.new(Err.ARG, "bad pattern " .. (i - 1)) + end + end + for i, s in m.samples do + if type(s) ~= "table" then + return nil, Err.new(Err.ARG, "bad sample " .. i) + end + local nch = if s.channels == 2 then 2 else 1 + s.channels = nch + if not num(s.length, 0, 2 ^ 31) or type(s.data) ~= "buffer" or buffer.len(s.data) < math.floor(s.length) * nch * 4 then + return nil, Err.new(Err.ARG, "sample " .. i .. ": data shorter than its length") + end + s.length = math.floor(s.length) + s.loopStart, s.loopEnd, s.loopType = fixLoop(s.loopStart or 0, s.loopEnd or 0, s.loopType or 0, s.length) + s.susStart, s.susEnd, s.susType = fixLoop(s.susStart or 0, s.susEnd or 0, s.susType or 0, s.length) + s.volume = if num(s.volume, 0, 64) then s.volume else 64 + s.globalVolume = if num(s.globalVolume, 0, 64) then s.globalVolume else 64 + if s.pan ~= nil and not num(s.pan, 0, 256) then + s.pan = nil + end + s.c5speed = if num(s.c5speed, 1, 1e7) then s.c5speed else 8363 + s.relativeNote = if num(s.relativeNote, -128, 127) then s.relativeNote else 0 + s.finetune = if num(s.finetune, -128, 127) then s.finetune else 0 + end + for i, ins in m.instruments do + if type(ins) ~= "table" or type(ins.sampleMap) ~= "table" or type(ins.noteMap) ~= "table" then + return nil, Err.new(Err.ARG, "bad instrument " .. i) + end + for n = 1, 120 do + if not num(ins.sampleMap[n], 0, 1e6) then + ins.sampleMap[n] = 0 + end + if not num(ins.noteMap[n], 1, 120) then + ins.noteMap[n] = n + end + end + local err + ins.volEnv, err = fixEnvelope(ins.volEnv) + if err then + return nil, Err.new(Err.ARG, "instrument " .. i .. ": " .. err) + end + ins.panEnv, err = fixEnvelope(ins.panEnv) + if err then + return nil, Err.new(Err.ARG, "instrument " .. i .. ": " .. err) + end + ins.pitchEnv, err = fixEnvelope(ins.pitchEnv) + if err then + return nil, Err.new(Err.ARG, "instrument " .. i .. ": " .. err) + end + ins.fadeout = if num(ins.fadeout, 0, 65535) then ins.fadeout else 0 + ins.globalVolume = if num(ins.globalVolume, 0, 128) then ins.globalVolume else 128 + if ins.pan ~= nil and not num(ins.pan, 0, 256) then + ins.pan = nil + end + if ins.cutoff ~= nil and not num(ins.cutoff, 0, 127) then + ins.cutoff = nil + end + if ins.resonance ~= nil and not num(ins.resonance, 0, 127) then + ins.resonance = nil + end + end + return true, nil +end + +-- ------------------------------------------------------------------------------------------------ rendering +local Decoder = {} +Decoder.__index = Decoder + +-- duration(module, opts?) -> seconds of one pass (song loops and the end of the order list detected), or nil, Err +function Tracker.duration(m: any, opts: RenderOptions?): (number?, Err.Err?) + local ok, err = Tracker.validate(m) + if not ok then + return nil, err + end + local sr = opts and opts.sampleRate or 44100 + local maxFrames = (opts and opts.maxDuration or 3600) * sr + local st = Player.new(m, sr, { stereoSeparation = 100 }) + local frames = 0 + while frames < maxFrames do + local f = Player.tick(st) + if f == 0 and st.ended then + break + end + frames += f + end + return math.min(frames, maxFrames) / sr, nil +end + +local function newPlayer(self: any) + self.st = Player.new(self.module, self.sampleRate, self.opts) + self.st.ramp = math.max(1, math.floor(self.sampleRate * 0.0015)) + self.left = 0 + self.pos = 0 +end + +-- render(module, opts?) -> Types.Decoder (stereo f32) | nil, Err +function Tracker.render(m: any, opts: RenderOptions?): (Types.Decoder?, Err.Err?) + local o: RenderOptions = opts or {} + local sr = o.sampleRate or 44100 + if type(sr) ~= "number" or sr < 1000 or sr > 384000 then + return nil, Err.new(Err.ARG, "sampleRate must be 1000..384000") + end + local seconds, err = Tracker.duration(m, o) + if not seconds then + return nil, err + end + local frames = math.floor(seconds * sr + 0.5) + local self = setmetatable({ + sampleRate = sr, + channels = 2, + frames = frames, + duration = frames / sr, + bitrate = 0, + tags = { title = m.title or "" }, + module = m, + opts = o, + linear = o.interpolation ~= "none", + maxFrames = (o.maxDuration or 3600) * sr, + st = nil :: any, + left = 0, + pos = 0, + }, Decoder) + newPlayer(self) + return self :: any, nil +end + +-- the Module method: module:render(opts) +function Tracker.renderMethod(self: any, opts: RenderOptions?): Types.Decoder + local dec = Tracker.render(self, opts) + return dec :: any +end + +-- run(self, out?, n) -> frames produced (out nil: advance without mixing) +local function run(self: any, out: buffer?, n: number): number + local st = self.st + local done = 0 + while done < n do + if self.left <= 0 then + if self.pos + done >= self.maxFrames then + break + end + local f = Player.tick(st) + if f == 0 and st.ended then + break + end + self.left = f + if f == 0 then + continue + end + end + local k = math.min(self.left, n - done) + Mixer.mix(st, out, done, k, self.linear) + self.left -= k + done += k + end + self.pos += done + return done +end + +-- read(n, out?) -> interleaved stereo f32 buffer, frames read (0 at the end) +function Decoder.read(self: any, n: number, out: buffer?): (buffer, number) + n = math.max(0, math.floor(tonumber(n) or 0)) + local o = out + if o == nil or buffer.len(o) < n * 8 then + o = buffer.create(n * 8) + else + buffer.fill(o, 0, 0, n * 8) + end + local got = run(self, o, n) + return o :: buffer, got +end + +-- seek(seconds): replays the song silently up to the position (sample positions included) +function Decoder.seek(self: any, seconds: number) + local target = math.max(0, math.floor((tonumber(seconds) or 0) * self.sampleRate)) + newPlayer(self) + local chunk = 65536 + while self.pos < target do + local got = run(self, nil, math.min(chunk, target - self.pos)) + if got == 0 then + break + end + end + -- the gains ramp in from silence after a seek + for _, v in self.st.voices do + v.gl, v.gr = 0, 0 + end +end + +function Decoder.position(self: any): number + return self.pos / self.sampleRate +end + +return Tracker diff --git a/src/Formats/music/it/Itsex.luau b/src/Formats/music/it/Itsex.luau new file mode 100644 index 0000000..3a7daca --- /dev/null +++ b/src/Formats/music/it/Itsex.luau @@ -0,0 +1,120 @@ +--!strict +--!native +-- music/it/Itsex: Impulse Tracker sample decompression (IT 2.14 and the IT 2.15 double-delta variant, 8 and 16-bit). +-- Written from the algorithm description in ITTECH.TXT / the public notes on the format: blocks of 0x8000 bytes of +-- output, each a u16 length then an LSB-first bit stream of deltas with three width-change methods. +-- +-- Never throws: every read is bounds-checked; corrupt streams return nil, message. +local readu8, readu16, writef32 = buffer.readu8, buffer.readu16, buffer.writef32 + +local Itsex = {} + +-- decompress(buf, off, limit, frames, bits, it215) -> f32 buffer (frames), bytes consumed | nil, message +function Itsex.decompress(buf: buffer, off: number, limit: number, frames: number, bits: number, it215: boolean): (buffer?, number | string) + local out = buffer.create(frames * 4) + local blockLen = if bits == 16 then 0x4000 else 0x8000 + local topWidth = if bits == 16 then 17 else 9 + local fetchA = if bits == 16 then 4 else 3 + local lowerB = if bits == 16 then -8 else -4 + local upperB = if bits == 16 then 7 else 3 + local scale = if bits == 16 then 1 / 32768 else 1 / 128 + local wrap = if bits == 16 then 65536 else 256 + local half = wrap // 2 + local p = off + local done = 0 + while done < frames do + if p + 2 > limit then + return nil, "compressed sample truncated" + end + local clen = readu16(buf, p) + p += 2 + local bstart = p + local bend = p + clen + if bend > limit then + return nil, "compressed block runs past the end" + end + p = bend + -- bit reader over [bstart, bend) + local bytePos = bstart + local bitBuf = 0 + local bitCount = 0 + local function readBits(n: number): number + while bitCount < n do + if bytePos >= bend then + return -1 + end + bitBuf += readu8(buf, bytePos) * 2 ^ bitCount + bytePos += 1 + bitCount += 8 + end + local v = bitBuf % 2 ^ n + bitBuf = (bitBuf - v) / 2 ^ n + bitCount -= n + return v + end + local count = math.min(blockLen, frames - done) + local width = topWidth + local d1, d2 = 0, 0 + local i = 0 + while i < count do + if width < 1 or width > topWidth then + return nil, "bad bit width" + end + local v = readBits(width) + if v < 0 then + return nil, "compressed block ends early" + end + if width < 7 then + -- method A: a marker value, then the new width in fetchA bits + if v == 2 ^ (width - 1) then + local nw = readBits(fetchA) + if nw < 0 then + return nil, "compressed block ends early" + end + nw += 1 + width = if nw < width then nw else nw + 1 + continue + end + elseif width < topWidth then + -- method B: values just below the top of the range encode the new width + local border = bit32.rshift(if bits == 16 then 0xFFFF else 0xFF, topWidth - width) + lowerB + if v > border and v <= border + (upperB - lowerB + 1) then + local nw = v - border + width = if nw < width then nw else nw + 1 + continue + end + else + -- method C: the top bit flags a width change + if v >= wrap then + width = (v + 1) % 256 + continue + end + end + -- a delta, sign-extended from its width + local x = v + if width < topWidth then + local shift = 2 ^ width + if x >= shift / 2 then + x -= shift + end + else + x = v % wrap + if x >= half then + x -= wrap + end + end + d1 = (d1 + x + half) % wrap - half + local s = d1 + if it215 then + d2 = (d2 + d1 + half) % wrap - half + s = d2 + end + writef32(out, (done + i) * 4, s * scale) + i += 1 + end + done += count + end + return out, p - off +end + +return Itsex diff --git a/src/Formats/music/it/init.luau b/src/Formats/music/it/init.luau new file mode 100644 index 0000000..d73cec0 --- /dev/null +++ b/src/Formats/music/it/init.luau @@ -0,0 +1,427 @@ +--!strict +-- music/it: Impulse Tracker modules (IMPM, ITTECH.TXT; also files from OpenMPT / Schism Tracker). Reads into the +-- codecs/Tracker Module and plays through its engine (Module:render() / open() -> an audio Decoder). Supports: up to +-- 64 channels, instrument and sample mode, new and old (pre-2.0) instrument headers, volume / panning / pitch (or +-- filter) envelopes with loops and sustain loops, new note actions and duplicate checks, pitch-pan separation, +-- resonant filters (instrument cutoff / resonance, default Zxx macros), 8 / 16-bit signed or unsigned mono / stereo +-- samples, IT 2.14 / 2.15 compressed samples, sustain loops, auto-vibrato, the song message. +-- Not supported: embedded MIDI macro configurations (the default filter macros are used), MIDI output, OpenMPT's +-- extension chunks (plugins, extended instrument properties), writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Tracker = require("@formats/codecs/Tracker") +local Itsex = require("@formats/music/it/Itsex") + +-- ------------------------------------------------------------------------------------------------ contract +local It = { + name = "it", + category = "music", + extensions = { "it" }, + mime = { "audio/it", "audio/x-it" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 64 }, compressedSamples = true }, +} + +export type DecodeOptions = { + maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function It.sniff(r: Bytes.Reader): number + return if r:peek(4) == "IMPM" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the 82-byte envelope of a new-format instrument +local function readEnvelope(r: Bytes.Reader, kind: string): any + local flags, n = r:u8(), r:u8() + local lb, le, sb, se = r:u8(), r:u8(), r:u8(), r:u8() + local e = Tracker.newEnvelope() + n = math.min(n, 25) + for i = 1, 25 do + local y, x = r:i8(), r:u16le() + if i <= n then + e.ticks[i] = x + e.values[i] = if kind == "vol" then math.clamp(y, 0, 64) else math.clamp(y, -32, 32) + end + end + r:skip(1) + e.enabled = bit32.band(flags, 1) ~= 0 and n > 0 + e.loop = bit32.band(flags, 2) ~= 0 + e.sustain = bit32.band(flags, 4) ~= 0 + e.carry = bit32.band(flags, 8) ~= 0 + e.filter = kind == "pitch" and bit32.band(flags, 128) ~= 0 + e.loopStart, e.loopEnd = lb + 1, le + 1 + e.susStart, e.susEnd = sb + 1, se + 1 + return e +end + +local function readInstrument(r: Bytes.Reader, old: boolean): (any?, string?) + if r:string(4) ~= "IMPI" then + return nil, "bad instrument signature" + end + local ins = Tracker.newInstrument() + r:skip(13) + if old then + -- the pre-2.0 layout: volume envelope only (flags, loop and sustain points), fadeout 0..64 of 512 + local flg, vls, vle, sls, sle = r:u8(), r:u8(), r:u8(), r:u8(), r:u8() + r:skip(2) + ins.fadeout = r:u16le() * 2 + ins.nna = r:u8() + ins.dct = if r:u8() ~= 0 then 1 else 0 + r:skip(4) + ins.name = r:fixed(26) + r:skip(6) + for n = 1, 120 do + local note, smp = r:u8(), r:u8() + ins.noteMap[n] = math.clamp(note + 1, 1, 120) + ins.sampleMap[n] = smp + end + r:skip(200) + local e = Tracker.newEnvelope() + for i = 1, 25 do + local t, v = r:u8(), r:u8() + if t == 0xFF or (i > 1 and t <= (e.ticks[#e.ticks] or -1)) then + r:skip((25 - i) * 2) + break + end + table.insert(e.ticks, t) + table.insert(e.values, math.min(v, 64)) + end + e.enabled = bit32.band(flg, 1) ~= 0 and #e.ticks > 0 + e.loop = bit32.band(flg, 2) ~= 0 + e.sustain = bit32.band(flg, 4) ~= 0 + e.loopStart, e.loopEnd, e.susStart, e.susEnd = vls + 1, vle + 1, sls + 1, sle + 1 + ins.volEnv = e + return ins + end + ins.nna, ins.dct, ins.dca = r:u8() % 4, r:u8() % 4, r:u8() % 3 + ins.fadeout = math.min(r:u16le(), 1024) + ins.pps, ins.ppc = r:i8(), r:u8() + ins.globalVolume = math.min(r:u8(), 128) + local dfp = r:u8() + if dfp < 128 then + ins.pan = math.min(dfp, 64) * 4 + end + r:skip(2 + 2 + 1 + 1) + ins.name = r:fixed(26) + local ifc, ifr = r:u8(), r:u8() + if ifc >= 128 then + ins.cutoff = ifc - 128 + end + if ifr >= 128 then + ins.resonance = ifr - 128 + end + r:skip(4) + for n = 1, 120 do + local note, smp = r:u8(), r:u8() + ins.noteMap[n] = math.clamp(note + 1, 1, 120) + ins.sampleMap[n] = smp + end + ins.volEnv = readEnvelope(r, "vol") + ins.panEnv = readEnvelope(r, "pan") + ins.pitchEnv = readEnvelope(r, "pitch") + if r.err then + return nil, "instrument truncated" + end + return ins +end + +function It.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local maxBytes = opts and opts.maxBytes or 2 ^ 28 + if r:peek(4) ~= "IMPM" then + return nil, Err.new(Err.CORRUPT, "no IMPM signature") + end + r:skip(4) + local title = r:fixed(26) + r:skip(2) + local ordnum, insnum, smpnum, patnum = r:u16le(), r:u16le(), r:u16le(), r:u16le() + local cwt, cmwt, flags, special = r:u16le(), r:u16le(), r:u16le(), r:u16le() + local gv, mv, speed, tempo, _sep, _pwd = r:u8(), r:u8(), r:u8(), r:u8(), r:u8(), r:u8() + local msgLen, msgOff = r:u16le(), r:u32le() + r:skip(4) + local chnPan, chnVol = {}, {} + for i = 1, 64 do + chnPan[i] = r:u8() + end + for i = 1, 64 do + chnVol[i] = r:u8() + end + if r.err then + return nil, r.err + end + if ordnum > 256 or insnum > 255 or smpnum > 255 or patnum > 255 then + return nil, Err.new(Err.CORRUPT, "bad header counts") + end + local orders = {} + for i = 1, ordnum do + orders[i] = r:u8() + end + local insOff, smpOff, patOff = {}, {}, {} + for i = 1, insnum do + insOff[i] = r:u32le() + end + for i = 1, smpnum do + smpOff[i] = r:u32le() + end + for i = 1, patnum do + patOff[i] = r:u32le() + end + if r.err then + return nil, r.err + end + -- channels: the highest one any pattern uses + local nch = 1 + local packed: { Bytes.Reader? } = {} + local rowsOf: { number } = {} + for p = 1, patnum do + if patOff[p] > 0 then + local pr = r:sub(patOff[p]) + local len, rows = pr:u16le(), pr:u16le() + pr:skip(4) + if pr.err or rows < 1 or rows > 1024 then + return nil, Err.new(Err.CORRUPT, "bad pattern " .. (p - 1), r.base + patOff[p]) + end + local data = pr:slice(len) + packed[p], rowsOf[p] = data, rows + -- scan for the channel count + local scan = data:sub(0) + local seen: { [number]: number } = {} + while not scan:eof() do + local cv = scan:u8() + if cv == 0 then + continue + end + local ch = (cv - 1) % 64 + nch = math.max(nch, ch + 1) + local mask = 0 + if cv >= 128 then + mask = scan:u8() + seen[ch] = mask + else + mask = seen[ch] or 0 + end + if bit32.band(mask, 1) ~= 0 then + scan:skip(1) + end + if bit32.band(mask, 2) ~= 0 then + scan:skip(1) + end + if bit32.band(mask, 4) ~= 0 then + scan:skip(1) + end + if bit32.band(mask, 8) ~= 0 then + scan:skip(2) + end + end + else + rowsOf[p] = 64 + end + end + local m = Tracker.newModule("it", nch) + m.title = title + m.speed = if speed > 0 then speed else 6 + m.tempo = if tempo >= 31 then tempo else 125 + m.globalVolume = math.min(gv, 128) + m.mixVolume = math.min(mv, 128) + m.linear = bit32.band(flags, 8) ~= 0 + m.instrumentMode = bit32.band(flags, 4) ~= 0 + m.flags.oldEffects = bit32.band(flags, 16) ~= 0 + m.flags.compatGxx = bit32.band(flags, 32) ~= 0 + local stereo = bit32.band(flags, 1) ~= 0 + for i = 1, nch do + local p = chnPan[i] + if p >= 128 then + m.channelMute[i] = true + p -= 128 + end + if not stereo then + m.channelPan[i] = 128 + elseif p == 100 then + m.channelPan[i] = 512 + else + m.channelPan[i] = math.min(p, 64) * 4 + end + m.channelVolume[i] = math.min(chnVol[i], 64) + end + for i = 1, ordnum do + if orders[i] == 255 then + break + end + table.insert(m.order, orders[i]) + end + m.meta.source = { format = "it", tracker = cwt, compatible = cmwt } + if bit32.band(special, 1) ~= 0 and msgLen > 0 then + local mr = r:sub(msgOff, msgLen) + m.meta.message = string.gsub(mr:fixed(msgLen), "\r", "\n") + end + -- instruments + for i = 1, insnum do + local ins, ierr = readInstrument(r:sub(insOff[i]), cmwt < 0x200) + if not ins then + return nil, Err.new(Err.CORRUPT, "instrument " .. i .. ": " .. tostring(ierr), r.base + insOff[i]) + end + m.instruments[i] = ins + end + -- samples + local total = 0 + for i = 1, smpnum do + local h = r:sub(smpOff[i], 80) + if h:string(4) ~= "IMPS" then + return nil, Err.new(Err.CORRUPT, "sample " .. i .. ": bad signature", r.base + smpOff[i]) + end + h:skip(13) + local s = Tracker.newSample() + m.samples[i] = s + local gvl, flg, vol = h:u8(), h:u8(), h:u8() + s.name = h:fixed(26) + local cvt, dfp = h:u8(), h:u8() + local len, lb, le, c5, slb, sle, ptr = h:u32le(), h:u32le(), h:u32le(), h:u32le(), h:u32le(), h:u32le(), h:u32le() + local vis, vid, vir, vit = h:u8(), h:u8(), h:u8(), h:u8() + if h.err then + return nil, Err.new(Err.TRUNCATED, "sample header " .. i) + end + s.globalVolume = math.min(gvl, 64) + s.volume = math.min(vol, 64) + if dfp >= 128 then + s.pan = math.min(dfp - 128, 64) * 4 + end + s.c5speed = if c5 > 0 then c5 else 8363 + s.vibRate, s.vibDepth, s.vibSweep, s.vibType = vis, vid, vir, vit % 4 + local bits = if bit32.band(flg, 2) ~= 0 then 16 else 8 + local nchs = if bit32.band(flg, 4) ~= 0 then 2 else 1 + s.bits = bits + if bit32.band(flg, 1) ~= 0 and len > 0 then + len = math.min(len, 2 ^ 26) + total += len * nchs * 4 + if total > maxBytes then + return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit") + end + local data: buffer? = nil + if bit32.band(flg, 8) ~= 0 then + -- compressed: each channel separately + local it215 = bit32.band(cvt, 4) ~= 0 + local p = r.base + ptr + local parts = {} + for c = 1, nchs do + local d, used = Itsex.decompress(r.buf, p, r.limit, len, bits, it215) + if not d then + return nil, Err.new(Err.CORRUPT, "sample " .. i .. ": " .. tostring(used)) + end + parts[c] = d + p += used :: number + end + if nchs == 1 then + data = parts[1] + else + local inter = buffer.create(len * 8) + for f = 0, len - 1 do + buffer.writef32(inter, f * 8, buffer.readf32(parts[1], f * 4)) + buffer.writef32(inter, f * 8 + 4, buffer.readf32(parts[2], f * 4)) + end + data = inter + end + else + local bps = bits // 8 + local avail = math.max(0, r:size() - ptr) // (bps * nchs) + len = math.min(len, avail) + data = Tracker.Pcm.decode(r.buf, r.base + ptr, len, { + bits = bits, + signed = bit32.band(cvt, 1) ~= 0, + bigEndian = bit32.band(cvt, 2) ~= 0, + delta = bit32.band(cvt, 4) ~= 0, + channels = nchs, + planar = true, + }) + end + if data then + s.data, s.length, s.channels = data, len, nchs + if bit32.band(flg, 16) ~= 0 then + s.loopStart, s.loopEnd, s.loopType = lb, math.min(le, len), if bit32.band(flg, 64) ~= 0 then 2 else 1 + end + if bit32.band(flg, 32) ~= 0 then + s.susStart, s.susEnd, s.susType = slb, math.min(sle, len), if bit32.band(flg, 128) ~= 0 then 2 else 1 + end + end + end + end + -- patterns + for p = 1, patnum do + local pat = Tracker.newPattern(rowsOf[p], nch) + m.patterns[p] = pat + local pr = packed[p] + if pr then + local d = pat.data + local lastMask, lastNote, lastIns, lastVol, lastFx, lastParam = {}, {}, {}, {}, {}, {} + local row = 0 + while row < pat.rows and not pr:eof() do + local cv = pr:u8() + if cv == 0 then + row += 1 + continue + end + local ch = (cv - 1) % 64 + local mask = if cv >= 128 then pr:u8() else (lastMask[ch] or 0) + lastMask[ch] = mask + local note, ins, vol, fx, param = 0, 0, 0, 0, 0 + if bit32.band(mask, 1) ~= 0 then + local n = pr:u8() + -- 255 note off, 254 note cut, 246 note fade (as IT and OpenMPT store "~~~"); other values: nothing + note = if n < 120 then n + 1 elseif n == 255 then 255 elseif n == 254 then 254 elseif n == 246 then 253 else 0 + lastNote[ch] = note + elseif bit32.band(mask, 16) ~= 0 then + note = lastNote[ch] or 0 + end + if bit32.band(mask, 2) ~= 0 then + ins = pr:u8() + lastIns[ch] = ins + elseif bit32.band(mask, 32) ~= 0 then + ins = lastIns[ch] or 0 + end + if bit32.band(mask, 4) ~= 0 then + vol = math.min(pr:u8(), 212) + 1 + lastVol[ch] = vol + elseif bit32.band(mask, 64) ~= 0 then + vol = lastVol[ch] or 0 + end + if bit32.band(mask, 8) ~= 0 then + fx, param = pr:u8(), pr:u8() + if fx > 26 then + fx, param = 0, 0 + end + lastFx[ch], lastParam[ch] = fx, param + elseif bit32.band(mask, 128) ~= 0 then + fx, param = lastFx[ch] or 0, lastParam[ch] or 0 + end + if ch < nch then + local o = (row * nch + ch) * 5 + buffer.writeu8(d, o, note) + buffer.writeu8(d, o + 1, ins) + buffer.writeu8(d, o + 2, vol) + buffer.writeu8(d, o + 3, fx) + buffer.writeu8(d, o + 4, param) + end + end + end + end + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function It.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = It.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return It 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..ed69595 --- /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: { number } = 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/mod/init.luau b/src/Formats/music/mod/init.luau new file mode 100644 index 0000000..7f4eb88 --- /dev/null +++ b/src/Formats/music/mod/init.luau @@ -0,0 +1,361 @@ +--!strict +-- music/mod: ProTracker / NoiseTracker / StarTrekker MOD modules (the 31-sample "M.K." family: M.K., M!K!, FLT4, +-- 4CHN .. 9CHN, 10CH .. 32CH, xxCN, CD81, OKTA / OCTA, TDZx; 15-sample Soundtracker files when asked for by name or +-- extension). Written from the ProTracker 2.3 documentation. Reads into the codecs/Tracker Module and plays through +-- its engine (Module:render() / open() -> an audio Decoder). Writes 31-sample MODs (M.K. / xCHN / xxCH) from "mod" +-- modules, and from XM modules that fit (one sample per instrument, effects 0..F, 64-row patterns). +-- Not supported: FLT8's split 4 + 4 channel patterns (read as 8 plain channels), the Amiga hardware low-pass filter +-- (E0x), PowerPacker-packed files. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Tracker = require("@formats/codecs/Tracker") + +-- ------------------------------------------------------------------------------------------------ contract +local Mod = { + name = "mod", + category = "music", + extensions = { "mod", "m15", "stk", "nst" }, + mime = { "audio/x-mod", "audio/mod" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" }, + caps = { decode = true, encode = true, render = true, channels = { 1, 32 } }, +} + +export type DecodeOptions = { + maxBytes: number?, -- refuse bigger sample data in total (default 64 MB of f32 samples) +} +export type EncodeOptions = {} + +-- ------------------------------------------------------------------------------------------------ constants +local Pcm = Tracker.Pcm +local Tables = Tracker.Tables + +local FIXED: { [string]: number } = { + ["M.K."] = 4, + ["M!K!"] = 4, + ["M&K!"] = 4, + ["N.T."] = 4, + ["FLT4"] = 4, + ["FLT8"] = 8, + ["CD81"] = 8, + ["OKTA"] = 8, + ["OCTA"] = 8, + ["EXO4"] = 4, + ["EXO8"] = 8, +} + +-- channels from the 4-byte signature at 1080, or nil +local function signatureChannels(sig: string): number? + local fixed = FIXED[sig] + if fixed then + return fixed + end + local d = string.match(sig, "^(%d)CHN$") + if d then + local n = tonumber(d) :: number + return if n >= 1 then n else nil + end + local dd = string.match(sig, "^(%d%d)C[HN]$") + if dd then + local n = tonumber(dd) :: number + return if n >= 1 and n <= 32 then n else nil + end + local t = string.match(sig, "^TDZ(%d)$") + if t then + local n = tonumber(t) :: number + return if n >= 1 then n else nil + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Mod.sniff(r: Bytes.Reader): number + if r:size() < 1084 then + return 0 + end + local sig = r:peek(4, 1080) + if signatureChannels(sig) then + return 0.8 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Mod.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local maxBytes = opts and opts.maxBytes or 2 ^ 26 + local size = r:size() + local sig = if size >= 1084 then r:peek(4, 1080) else "" + local channels = signatureChannels(sig) + local nsamples = 31 + if not channels then + -- a 15-sample Soundtracker module (no signature): only when the header is plausible + nsamples, channels = 15, 4 + end + local nch = channels :: number + local m = Tracker.newModule("mod", nch) + m.title = r:fixed(20) + local lengths: { number } = {} + for i = 1, nsamples do + local s = Tracker.newSample(r:fixed(22)) + local len = r:u16be() * 2 + local ft = r:u8() % 16 + local vol = r:u8() + local ls = r:u16be() * 2 + local ll = r:u16be() * 2 + if r.err then + return nil, r.err + end + if nsamples == 15 and (vol > 64 or ft ~= 0) then + return nil, Err.new(Err.CORRUPT, "not a MOD (bad sample header)") + end + s.finetune = (if ft >= 8 then ft - 16 else ft) * 16 + s.volume = math.min(vol, 64) + s.bits = 8 + if ll > 2 then + s.loopStart, s.loopEnd, s.loopType = ls, ls + ll, 1 + end + lengths[i] = len + m.samples[i] = s + end + local songLength = r:u8() + local restart = r:u8() + local order: { number } = {} + local maxPat = 0 + for i = 1, 128 do + local p = r:u8() + order[i] = p + maxPat = math.max(maxPat, p) + end + if r.err then + return nil, r.err + end + if songLength == 0 or songLength > 128 or maxPat >= 128 then + return nil, Err.new(Err.CORRUPT, "not a MOD (bad order list)") + end + if nsamples == 31 then + r:skip(4) + end + for i = 1, songLength do + m.order[i] = order[i] + end + m.restart = if restart < songLength then restart else 0 + m.meta.signature = if nsamples == 31 then sig else nil + m.flags.amigaLimits = nch == 4 + -- patterns + local npat = maxPat + 1 + local patBytes = 64 * nch * 4 + if not r:need(npat * patBytes) then + return nil, r.err + end + local buf = r.buf + for p = 0, npat - 1 do + local pat = Tracker.newPattern(64, nch) + local base = r.pos + p * patBytes + local d = pat.data + for i = 0, 64 * nch - 1 do + local o = base + i * 4 + local b0, b1, b2, b3 = buffer.readu8(buf, o), buffer.readu8(buf, o + 1), buffer.readu8(buf, o + 2), buffer.readu8(buf, o + 3) + local period = (b0 % 16) * 256 + b1 + local ins = (b0 // 16) * 16 + b2 // 16 + local q = i * 5 + buffer.writeu8(d, q, Tables.periodToNote(period)) + buffer.writeu8(d, q + 1, ins) + buffer.writeu8(d, q + 3, b2 % 16) + buffer.writeu8(d, q + 4, b3) + end + m.patterns[p + 1] = pat + end + r:skip(npat * patBytes) + -- sample data (8-bit signed; the last samples of a truncated file are cut short) + local total = 0 + for i = 1, nsamples do + local s = m.samples[i] + local len = math.min(lengths[i], r:remaining()) + total += len * 4 + if total > maxBytes then + return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit") + end + local data = Pcm.decode(buf, r.pos, len, { bits = 8, signed = true }) + if not data then + return nil, Err.new(Err.TRUNCATED, "sample data", r.pos) + end + r:skip(len) + s.data, s.length = data, len + if s.loopEnd > len then + s.loopEnd = len + if s.loopEnd - s.loopStart < 2 then + s.loopType, s.loopStart, s.loopEnd = 0, 0, 0 + end + end + end + m.meta.source = { format = "mod", samples = nsamples } + m.render = Tracker.renderMethod + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function writeName(w: Bytes.Writer, s: string, n: number) + local t = string.sub(s or "", 1, n) + w:string(t) + w:fill(0, n - #t) +end + +-- encode(module) -> MOD bytes. The module must be "mod", or an "xm" module whose instruments each map every note to +-- one sample; patterns must have 64 rows, at most 31 samples, effects 0..F. +function Mod.encode(m: any, _opts: EncodeOptions?): (buffer?, Err.Err?) + local ok, verr = Tracker.validate(m) + if not ok then + return nil, verr + end + if m.format ~= "mod" and m.format ~= "xm" then + return nil, Err.new(Err.UNSUPPORTED, "only mod and xm modules can be written as MOD (got " .. tostring(m.format) .. "); xm is the closest writable format") + end + local nch = m.channels + if nch > 32 then + return nil, Err.new(Err.ARG, "MOD holds at most 32 channels") + end + -- the sample for each instrument number + local smpOf: { any } = {} + if m.format == "xm" then + for i, ins in m.instruments do + local first = 0 + for n = 1, 120 do + local s = ins.sampleMap[n] + if s ~= 0 then + if first ~= 0 and s ~= first then + return nil, Err.new(Err.ARG, "instrument " .. i .. " uses several samples") + end + first = s + end + end + smpOf[i] = m.samples[first] or Tracker.newSample(ins.name) + end + else + for i, s in m.samples do + smpOf[i] = s + end + end + if #smpOf > 31 then + return nil, Err.new(Err.ARG, "MOD holds at most 31 samples") + end + local order: { number } = {} + for _, o in m.order do + if o == 255 then + break + elseif o ~= 254 then + table.insert(order, o) + end + end + if #order == 0 or #order > 128 then + return nil, Err.new(Err.ARG, "MOD needs 1..128 order entries") + end + local npat = #m.patterns + if npat > 100 then + return nil, Err.new(Err.ARG, "too many patterns for MOD") + end + for p, pat in m.patterns do + if pat.rows ~= 64 then + return nil, Err.new(Err.ARG, "pattern " .. (p - 1) .. " has " .. pat.rows .. " rows (MOD patterns have 64)") + end + end + local w = Bytes.writer(1084 + npat * 64 * nch * 4 + 65536) + writeName(w, m.title or "", 20) + local datas: { buffer } = {} + for i = 1, 31 do + local s = smpOf[i] + if s then + local len = math.min(s.length, 131070) + local pcm = Pcm.encode(s.data, len, { bits = 8, signed = true, channels = 1 }) + if s.channels == 2 then + -- mix stereo samples down + local mono = buffer.create(len * 4) + for k = 0, len - 1 do + buffer.writef32(mono, k * 4, (buffer.readf32(s.data, k * 8) + buffer.readf32(s.data, k * 8 + 4)) / 2) + end + pcm = Pcm.encode(mono, len, { bits = 8, signed = true }) + end + local even = len + len % 2 + local padded = buffer.create(even) + buffer.copy(padded, 0, pcm, 0, len) + datas[i] = padded + writeName(w, s.name or "", 22) + w:u16be(even // 2) + local ft = math.clamp(math.floor((s.finetune or 0) / 16 + 0.5), -8, 7) + w:u8(ft % 16) + w:u8(math.clamp(math.floor(s.volume), 0, 64)) + if s.loopType > 0 and s.loopEnd <= even then + w:u16be(s.loopStart // 2) + w:u16be(math.max(1, (s.loopEnd - s.loopStart) // 2)) + else + w:u16be(0) + w:u16be(1) + end + else + w:fill(0, 22) + w:u16be(0) + w:u8(0) + w:u8(0) + w:u16be(0) + w:u16be(1) + end + end + w:u8(#order) + w:u8(if m.restart < #order and m.restart > 0 then m.restart else 127) + for i = 1, 128 do + w:u8(order[i] or 0) + end + local sig + if nch == 4 then + sig = if npat > 64 then "M!K!" else "M.K." + elseif nch < 10 then + sig = nch .. "CHN" + else + sig = nch .. "CH" + end + w:string(sig) + for p = 1, npat do + local d = m.patterns[p].data + for i = 0, 64 * nch - 1 do + local q = i * 5 + local note, ins, fx, param = buffer.readu8(d, q), buffer.readu8(d, q + 1), buffer.readu8(d, q + 3), buffer.readu8(d, q + 4) + local period = if note >= 1 and note <= 120 then Tables.noteToPeriod(note) else 0 + if period > 4095 then + period = 0 + end + if fx > 15 then + fx, param = 0, 0 + end + if ins > 31 then + ins = 0 + end + w:u8((ins // 16) * 16 + period // 256) + w:u8(period % 256) + w:u8((ins % 16) * 16 + fx) + w:u8(param) + end + end + for i = 1, 31 do + if datas[i] then + w:bytes(datas[i]) + end + end + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function Mod.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Mod.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Mod diff --git a/src/Formats/music/s3m/init.luau b/src/Formats/music/s3m/init.luau new file mode 100644 index 0000000..f7a80f7 --- /dev/null +++ b/src/Formats/music/s3m/init.luau @@ -0,0 +1,241 @@ +--!strict +-- music/s3m: Scream Tracker 3 modules (SCRM, ST3 TECH.DOC; also files from Impulse Tracker / OpenMPT / Schism +-- Tracker). Reads into the codecs/Tracker Module and plays through its engine (Module:render() / open() -> an audio +-- Decoder). Supports: up to 32 PCM channels, 8 / 16-bit signed or unsigned, mono or stereo samples, loops, the panning +-- table, ST3.00 fast volume slides, every ST3 effect. Notes are stored one octave up (S3M C-4 = note 61 = the C5 +-- speed reference, as IT shows S3M files). +-- Not supported: AdLib (OPL) instruments and channels (read as silent), writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Tracker = require("@formats/codecs/Tracker") + +-- ------------------------------------------------------------------------------------------------ contract +local S3m = { + name = "s3m", + category = "music", + extensions = { "s3m" }, + mime = { "audio/s3m", "audio/x-s3m" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 32 } }, +} + +export type DecodeOptions = { + maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function S3m.sniff(r: Bytes.Reader): number + if r:size() >= 48 and r:peek(4, 44) == "SCRM" then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function S3m.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local maxBytes = opts and opts.maxBytes or 2 ^ 28 + if r:size() < 96 then + return nil, Err.new(Err.TRUNCATED, "header") + end + if r:peek(4, 44) ~= "SCRM" then + return nil, Err.new(Err.CORRUPT, "no SCRM signature") + end + local title = r:fixed(28) + r:seek(32) + local ordnum, insnum, patnum = r:u16le(), r:u16le(), r:u16le() + local flags, cwt, ffi = r:u16le(), r:u16le(), r:u16le() + r:seek(48) + local gv, speed, tempo, mv, _uc, dp = r:u8(), r:u8(), r:u8(), r:u8(), r:u8(), r:u8() + r:seek(64) + local chnset: { number } = {} + for i = 1, 32 do + chnset[i] = r:u8() + end + if r.err then + return nil, r.err + end + if ordnum > 256 or insnum > 256 or patnum > 256 then + return nil, Err.new(Err.CORRUPT, "bad header counts") + end + -- channels: enabled PCM channels (0..15); the count is the last used one + local nch = 0 + for i = 1, 32 do + local c = chnset[i] + if c < 16 then + nch = i + end + end + if nch == 0 then + return nil, Err.new(Err.UNSUPPORTED, "no PCM channels (AdLib only)") + end + local m = Tracker.newModule("s3m", nch) + m.title = title + m.speed = if speed > 0 and speed < 255 then speed else 6 + m.tempo = if tempo >= 33 then tempo else 125 + m.globalVolume = math.min(gv, 64) * 2 + m.mixVolume = math.max(mv % 128, 16) + if mv < 128 then + -- mono files play at 8 / 11 of the master volume (ST3's stereo boost is missing; OpenMPT does the same) + m.mixVolume = math.floor(m.mixVolume * 8 / 11 + 0.5) + end + m.linear = false + m.instrumentMode = false + m.flags.fastSlides = cwt == 0x1300 or bit32.band(flags, 64) ~= 0 + m.flags.amigaLimits = bit32.band(flags, 16) ~= 0 + m.meta.source = { format = "s3m", tracker = cwt, stereo = mv >= 128 } + -- orders, parapointers, panning + r:seek(96) + for i = 1, ordnum do + local o = r:u8() + table.insert(m.order, o) + end + local insPtr, patPtr = {}, {} + for i = 1, insnum do + insPtr[i] = r:u16le() * 16 + end + for i = 1, patnum do + patPtr[i] = r:u16le() * 16 + end + local pans: { number } = {} + if dp == 252 then + for i = 1, 32 do + pans[i] = r:u8() + end + end + if r.err then + return nil, r.err + end + -- drop trailing end markers; keep inner "+++" / "---" + while #m.order > 0 and m.order[#m.order] == 255 do + table.remove(m.order) + end + local stereo = mv >= 128 + for i = 1, nch do + local c = chnset[i] + local pan = 128 + if stereo then + pan = if c % 16 >= 8 then 0xCC else 0x33 + local p = pans[i] + if p and bit32.band(p, 0x20) ~= 0 then + pan = (p % 16) * 0x11 + end + end + m.channelPan[i] = pan + m.channelMute[i] = c >= 16 + end + -- samples + local total = 0 + local unsigned = ffi ~= 1 + for i = 1, insnum do + local s = Tracker.newSample() + m.samples[i] = s + local h = r:sub(insPtr[i], 80) + if h:size() < 80 then + return nil, Err.new(Err.TRUNCATED, "sample header " .. i, insPtr[i]) + end + local typ = h:u8() + h:skip(12) + local hi = h:u8() + local lo = h:u16le() + local len, ls, le = h:u32le(), h:u32le(), h:u32le() + local vol = h:u8() + h:skip(1) + local pack, sflags = h:u8(), h:u8() + local c2spd = h:u32le() + h:seek(48) + s.name = h:fixed(28) + s.volume = math.min(vol, 64) + s.c5speed = if c2spd > 0 then c2spd else 8363 + if typ == 1 and len > 0 and pack == 0 then + local bits = if bit32.band(sflags, 4) ~= 0 then 16 else 8 + local nchs = if bit32.band(sflags, 2) ~= 0 then 2 else 1 + local off = (hi * 65536 + lo) * 16 + len = math.min(len, 2 ^ 26) + -- a short file: keep what is there + local avail = math.max(0, r:size() - off) // (nchs * bits // 8) + len = math.min(len, avail) + total += len * nchs * 4 + if total > maxBytes then + return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit") + end + local data = Tracker.Pcm.decode(r.buf, r.base + off, len, { bits = bits, signed = not unsigned, channels = nchs, planar = true }) + if data then + s.data, s.length, s.bits, s.channels = data, len, bits, nchs + if bit32.band(sflags, 1) ~= 0 and le > ls then + s.loopStart, s.loopEnd, s.loopType = ls, math.min(le, len), 1 + end + end + end + end + -- patterns + for p = 1, patnum do + local pat = Tracker.newPattern(64, nch) + m.patterns[p] = pat + local ptr = patPtr[p] + if ptr > 0 then + local pr = r:sub(ptr) + local plen = pr:u16le() + pr = pr:sub(2, math.max(0, plen - 2)) + local d = pat.data + local row = 0 + while row < 64 and not pr:eof() do + local what = pr:u8() + if what == 0 then + row += 1 + else + local ch = what % 32 + local note, ins, vol, cmd, info = 0, 0, 0, 0, 0 + if bit32.band(what, 0x20) ~= 0 then + local nb = pr:u8() + ins = pr:u8() + if nb == 254 then + note = 254 + elseif nb < 254 and nb % 16 < 12 then + note = (nb // 16) * 12 + nb % 16 + 13 + if note > 120 then + note = 0 + end + end + end + if bit32.band(what, 0x40) ~= 0 then + vol = math.min(pr:u8(), 64) + 1 + end + if bit32.band(what, 0x80) ~= 0 then + cmd, info = pr:u8(), pr:u8() + if cmd > 26 then + cmd, info = 0, 0 + end + end + if ch < nch then + local o = (row * nch + ch) * 5 + buffer.writeu8(d, o, note) + buffer.writeu8(d, o + 1, ins) + buffer.writeu8(d, o + 2, vol) + buffer.writeu8(d, o + 3, cmd) + buffer.writeu8(d, o + 4, info) + end + end + end + end + end + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function S3m.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = S3m.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return S3m 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/src/Formats/music/xm/init.luau b/src/Formats/music/xm/init.luau new file mode 100644 index 0000000..d2cbafa --- /dev/null +++ b/src/Formats/music/xm/init.luau @@ -0,0 +1,560 @@ +--!strict +-- music/xm: FastTracker 2 Extended Modules (XM 1.04, the "Extended Module: " format; also OpenMPT / MilkyTracker / +-- Skale files). Written from the XM specification and FT2 behaviour notes. Reads into the codecs/Tracker Module and +-- plays through its engine (Module:render() / open() -> an audio Decoder): up to 32 channels (more are read), 8 / 16-bit +-- delta samples, multi-sample instruments with volume / panning envelopes, fadeout and auto-vibrato, linear and Amiga +-- frequency tables, every FT2 effect and volume-column command. Writes XM from "xm" modules (byte-identical for files +-- in FT2's layout) and from "mod" modules (one instrument per sample, Amiga frequencies). +-- Not supported: ModPlug ADPCM samples (read as silence), OpenMPT's stereo-sample / extra-effect extensions on write. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Tracker = require("@formats/codecs/Tracker") + +-- ------------------------------------------------------------------------------------------------ contract +local Xm = { + name = "xm", + category = "music", + extensions = { "xm" }, + mime = { "audio/xm", "audio/x-xm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" }, + caps = { decode = true, encode = true, render = true, channels = { 1, 64 } }, +} + +export type DecodeOptions = { + maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) +} +export type EncodeOptions = { + tracker: string?, -- the tracker name field (default: the source file's, else "formats-luau") +} + +-- ------------------------------------------------------------------------------------------------ constants +local MAGIC = "Extended Module: " +local Pcm = Tracker.Pcm + +-- ------------------------------------------------------------------------------------------------ sniff +function Xm.sniff(r: Bytes.Reader): number + return if r:peek(17) == MAGIC then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function readEnvelope(r: Bytes.Reader): ({ number }, { number }) + local xs, ys = {}, {} + for i = 1, 12 do + xs[i] = r:u16le() + ys[i] = r:u16le() + end + return xs, ys +end + +local function makeEnvelope(xs: { number }, ys: { number }, n: number, typ: number, sus: number, ls: number, le: number, pan: boolean): any + local e = Tracker.newEnvelope() + n = math.min(n, 12) + for i = 1, n do + e.ticks[i] = xs[i] + e.values[i] = if pan then math.clamp(ys[i], 0, 64) - 32 else math.clamp(ys[i], 0, 64) + end + e.enabled = bit32.band(typ, 1) ~= 0 and n > 0 + e.sustain = bit32.band(typ, 2) ~= 0 + e.loop = bit32.band(typ, 4) ~= 0 + e.susStart, e.susEnd = sus + 1, sus + 1 + e.loopStart, e.loopEnd = ls + 1, le + 1 + -- the raw fields, for a faithful re-save + e.raw = { type = typ, sustain = sus, loopStart = ls, loopEnd = le, count = n } + return e +end + +function Xm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local maxBytes = opts and opts.maxBytes or 2 ^ 28 + if r:peek(17) ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "no XM signature") + end + r:skip(17) + local title = r:fixed(20) + r:skip(1) + local tracker = r:fixed(20) + local version = r:u16le() + local hdrStart = r:tell() + local hdrSize = r:u32le() + local songLen, restart, nch, npat, nins = r:u16le(), r:u16le(), r:u16le(), r:u16le(), r:u16le() + local flags, speed, bpm = r:u16le(), r:u16le(), r:u16le() + local orders = {} + for i = 1, 256 do + orders[i] = r:u8() + end + if r.err then + return nil, r.err + end + if nch < 1 or nch > 128 or npat > 256 or nins > 256 or songLen > 256 then + return nil, Err.new(Err.CORRUPT, "bad header counts") + end + if version < 0x0104 then + return nil, Err.new(Err.UNSUPPORTED, string.format("XM version %x (only 1.04 is supported)", version)) + end + local m = Tracker.newModule("xm", nch) + m.title = title + m.speed = if speed > 0 and speed < 256 then speed else 6 + m.tempo = if bpm >= 32 and bpm <= 999 then bpm else 125 + m.linear = bit32.band(flags, 1) ~= 0 + m.restart = restart + for i = 1, songLen do + m.order[i] = orders[i] + end + m.meta.tracker = tracker + m.meta.source = { format = "xm", tracker = tracker, version = version } + -- patterns + if not r:seek(hdrStart + hdrSize) then + return nil, r.err + end + for p = 1, npat do + local start = r:tell() + local plen = r:u32le() + r:u8() + local rows = r:u16le() + local psize = r:u16le() + if r.err then + return nil, r.err + end + if rows < 1 or rows > 256 then + return nil, Err.new(Err.CORRUPT, "pattern " .. (p - 1) .. " has " .. rows .. " rows", r.pos) + end + r:seek(start + plen) + local pat = Tracker.newPattern(rows, nch) + m.patterns[p] = pat + local pr = r:slice(psize) + if r.err then + return nil, r.err + end + local d = pat.data + if psize > 0 then + for i = 0, rows * nch - 1 do + local b = pr:u8() + local note, ins, vol, fx, param = 0, 0, 0, 0, 0 + if b >= 128 then + if bit32.band(b, 1) ~= 0 then + note = pr:u8() + end + if bit32.band(b, 2) ~= 0 then + ins = pr:u8() + end + if bit32.band(b, 4) ~= 0 then + vol = pr:u8() + end + if bit32.band(b, 8) ~= 0 then + fx = pr:u8() + end + if bit32.band(b, 16) ~= 0 then + param = pr:u8() + end + else + note, ins, vol, fx, param = b, pr:u8(), pr:u8(), pr:u8(), pr:u8() + end + if pr.err then + break -- a short pattern: the rest stays empty + end + if note == 97 then + note = 255 + elseif note > 96 then + note = 0 + end + if fx > 35 then + fx, param = 0, 0 + end + local o = i * 5 + buffer.writeu8(d, o, note) + buffer.writeu8(d, o + 1, ins) + buffer.writeu8(d, o + 2, vol) + buffer.writeu8(d, o + 3, fx) + buffer.writeu8(d, o + 4, param) + end + end + end + -- instruments and their samples + local total = 0 + for i = 1, nins do + local start = r:tell() + local isize = r:u32le() + local ins = Tracker.newInstrument(r:fixed(22)) + r:u8() + local ns = r:u16le() + if r.err then + -- a file cut inside the instruments: keep what was read + r.err = nil + break + end + m.instruments[i] = ins + ins.samples = {} + if ns == 0 then + r:seek(start + math.max(isize, 29)) + continue + end + if ns > 256 then + return nil, Err.new(Err.CORRUPT, "instrument " .. i .. " has " .. ns .. " samples") + end + local shSize = r:u32le() + local keymap = {} + for n = 1, 96 do + keymap[n] = r:u8() + end + local vx, vy = readEnvelope(r) + local px, py = readEnvelope(r) + local nv, np = r:u8(), r:u8() + local vs, vls, vle, ps, pls, ple = r:u8(), r:u8(), r:u8(), r:u8(), r:u8(), r:u8() + local vt, pt = r:u8(), r:u8() + ins.vibType, ins.vibSweep, ins.vibDepth, ins.vibRate = r:u8(), r:u8(), r:u8(), r:u8() + ins.fadeout = r:u16le() + if r.err then + return nil, r.err + end + ins.volEnv = makeEnvelope(vx, vy, nv, vt, vs, vls, vle, false) + ins.panEnv = makeEnvelope(px, py, np, pt, ps, pls, ple, true) + ins.headerSize = isize + r:seek(start + isize) + local base = #m.samples + local heads = {} + for k = 1, ns do + local hs = r:tell() + local len, ls, ll = r:u32le(), r:u32le(), r:u32le() + local vol, ft, typ, pan, rel, res = r:u8(), r:i8(), r:u8(), r:u8(), r:i8(), r:u8() + local nm = r:fixed(22) + r:seek(hs + math.max(shSize, 40)) + heads[k] = { len = len, ls = ls, ll = ll, vol = vol, ft = ft, typ = typ, pan = pan, rel = rel, res = res, name = nm } + end + if r.err then + return nil, r.err + end + for k = 1, ns do + local h = heads[k] + local s = Tracker.newSample(h.name) + local bits = if bit32.band(h.typ, 16) ~= 0 then 16 else 8 + local bps = bits // 8 + s.bits = bits + s.volume = math.min(h.vol, 64) + s.finetune = h.ft + s.relativeNote = h.rel + s.pan = h.pan + local frames = h.len // bps + if h.res == 0xAD then + -- ModPlug ADPCM: 16-byte table + 4 bits per sample (not decoded: silence of the right length) + local bytes = 16 + (h.len + 1) // 2 + r:skip(math.min(bytes, r:remaining())) + frames = h.len + s.data = buffer.create(frames * 4) + else + local avail = r:remaining() // bps + local got = math.min(frames, avail) + total += got * 4 + if total > maxBytes then + return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit") + end + local data = Pcm.decode(r.buf, r.pos, got, { bits = bits, signed = true, delta = true }) + r:skip(got * bps) + s.data = data or buffer.create(0) + frames = if data then got else 0 + end + s.length = frames + local lt = h.typ % 4 + if lt == 3 then + lt = 2 + end + if lt > 0 and h.ll > 0 then + s.loopStart = h.ls // bps + s.loopEnd = (h.ls + h.ll) // bps + s.loopType = lt + end + m.samples[base + k] = s + table.insert(ins.samples, base + k) + end + for n = 1, 120 do + local k = keymap[math.min(n, 96)] + ins.sampleMap[n] = if n <= 96 and k < ns then base + k + 1 else 0 + end + ins.keymap = keymap + end + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function writeName(w: Bytes.Writer, s: string?, n: number) + local t = string.sub(s or "", 1, n) + w:string(t) + w:fill(0, n - #t) +end + +-- the instruments to write: { name, samples = { sample table }, keymap = { 96 local indexes }, ins? } +local function instrumentsOf(m: any): ({ any }?, string?) + local out = {} + if m.format == "mod" then + for i, s in m.samples do + local km = table.create(96, 0) + out[i] = { name = s.name, samples = if s.length > 0 then { s } else {}, keymap = km, ins = nil } + end + return out + end + for i, ins in m.instruments do + local list: { number } = {} + if type(ins.samples) == "table" then + for _, g in ins.samples do + table.insert(list, g) + end + end + local index: { [number]: number } = {} + for k, g in list do + index[g] = k - 1 + end + local km = table.create(96, 0) + for n = 1, 96 do + local g = ins.sampleMap[n] or 0 + if g > 0 and m.samples[g] then + if index[g] == nil then + table.insert(list, g) + index[g] = #list - 1 + end + km[n] = index[g] + end + end + if #list > 255 then + return nil, "instrument " .. i .. " uses more than 255 samples" + end + local smps = {} + for k, g in list do + smps[k] = m.samples[g] or Tracker.newSample() + end + out[i] = { name = ins.name, samples = smps, keymap = km, ins = ins } + end + return out +end + +local function writeEnvelope(w: Bytes.Writer, e: any, pan: boolean) + local n = if e then math.min(#e.ticks, 12) else 0 + for i = 1, 12 do + if i <= n then + w:u16le(math.clamp(math.floor(e.ticks[i]), 0, 65535)) + w:u16le(math.clamp(math.floor(e.values[i] + (if pan then 32 else 0) + 0.5), 0, 64)) + else + w:u32le(0) + end + end +end + +-- envelope count, type, sustain, loop start, loop end +local function envelopeFields(e: any): (number, number, number, number, number) + if not e then + return 0, 0, 0, 0, 0 + end + local n = math.min(#e.ticks, 12) + local typ = (if e.enabled then 1 else 0) + (if e.sustain then 2 else 0) + (if e.loop then 4 else 0) + local raw = e.raw + if raw and raw.type % 8 == typ then + typ = raw.type -- keep unknown bits + end + local function idx(v: number): number + return math.clamp(math.floor(v) - 1, 0, math.max(0, n - 1)) + end + local sus = idx(e.susStart) + local ls, le = idx(e.loopStart), idx(e.loopEnd) + if raw and n == 0 then + sus, ls, le = raw.sustain, raw.loopStart, raw.loopEnd + end + return n, typ, sus, ls, le +end + +-- encode(module, opts) -> XM bytes ("xm" or "mod" modules) +function Xm.encode(m: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local ok, verr = Tracker.validate(m) + if not ok then + return nil, verr + end + if m.format ~= "xm" and m.format ~= "mod" then + return nil, Err.new(Err.UNSUPPORTED, "only xm and mod modules can be written as XM (got " .. tostring(m.format) .. ")") + end + local nch = m.channels + if nch > 64 then + return nil, Err.new(Err.ARG, "XM holds at most 64 channels") + end + local insts, ierr = instrumentsOf(m) + if not insts then + return nil, Err.new(Err.ARG, ierr or "bad instruments") + end + if #insts > 128 then + return nil, Err.new(Err.ARG, "XM holds at most 128 instruments") + end + if #m.patterns > 256 then + return nil, Err.new(Err.ARG, "XM holds at most 256 patterns") + end + local order: { number } = {} + for _, o in m.order do + if o == 255 then + break + elseif o ~= 254 then + table.insert(order, o) + end + end + if #order > 256 then + return nil, Err.new(Err.ARG, "XM holds at most 256 order entries") + end + local w = Bytes.writer(65536) + w:string(MAGIC) + writeName(w, m.title, 20) + w:u8(0x1A) + writeName(w, opts and opts.tracker or (m.meta and m.meta.tracker) or "formats-luau", 20) + w:u16le(0x0104) + w:u32le(276) + w:u16le(#order) + w:u16le(if m.restart < #order then m.restart else 0) + w:u16le(nch) + w:u16le(#m.patterns) + w:u16le(#insts) + w:u16le(if m.linear then 1 else 0) + w:u16le(m.speed) + w:u16le(math.clamp(math.floor(m.tempo), 32, 999)) + for i = 1, 256 do + w:u8(order[i] or 0) + end + -- patterns (every cell packed, as FT2-compatible writers may) + for _, pat in m.patterns do + local pk = Bytes.writer(pat.rows * nch * 2) + local d = pat.data + for i = 0, pat.rows * nch - 1 do + local o = i * 5 + local note, ins, vol, fx, param = buffer.readu8(d, o), buffer.readu8(d, o + 1), buffer.readu8(d, o + 2), buffer.readu8(d, o + 3), buffer.readu8(d, o + 4) + if note == 255 then + note = 97 + elseif note > 96 then + note = 0 + end + if m.format == "mod" then + vol = 0 + if fx > 15 then + fx, param = 0, 0 + end + end + if ins > 128 then + ins = 0 + end + local flags = 0x80 + (if note > 0 then 1 else 0) + (if ins > 0 then 2 else 0) + (if vol > 0 then 4 else 0) + (if fx > 0 then 8 else 0) + (if param > 0 then 16 else 0) + pk:u8(flags) + if note > 0 then + pk:u8(note) + end + if ins > 0 then + pk:u8(ins) + end + if vol > 0 then + pk:u8(vol) + end + if fx > 0 then + pk:u8(fx) + end + if param > 0 then + pk:u8(param) + end + end + local data = pk:finish() + if buffer.len(data) > 65535 then + return nil, Err.new(Err.ARG, "a pattern packs to more than 64 KB") + end + w:u32le(9) + w:u8(0) + w:u16le(pat.rows) + w:u16le(buffer.len(data)) + w:bytes(data) + end + -- instruments + for _, it in insts do + local ins = it.ins + local smps = it.samples + if #smps == 0 then + w:u32le(29) + writeName(w, it.name, 22) + w:u8(0) + w:u16le(0) + continue + end + w:u32le(263) + writeName(w, it.name, 22) + w:u8(0) + w:u16le(#smps) + w:u32le(40) + for n = 1, 96 do + w:u8(it.keymap[n]) + end + local ve, pe = ins and ins.volEnv, ins and ins.panEnv + writeEnvelope(w, ve, false) + writeEnvelope(w, pe, true) + local vn, vt, vs, vls, vle = envelopeFields(ve) + local pn, pt, ps, pls, ple = envelopeFields(pe) + w:u8(vn) + w:u8(pn) + w:u8(vs) + w:u8(vls) + w:u8(vle) + w:u8(ps) + w:u8(pls) + w:u8(ple) + w:u8(vt) + w:u8(pt) + w:u8(ins and ins.vibType or 0) + w:u8(ins and ins.vibSweep or 0) + w:u8(ins and ins.vibDepth or 0) + w:u8(ins and ins.vibRate or 0) + w:u16le(ins and math.clamp(ins.fadeout, 0, 0xFFF) or 0) + w:fill(0, 22) + local datas = {} + for k, s in smps do + local mono = s.data + if s.channels == 2 then + mono = buffer.create(s.length * 4) + for f = 0, s.length - 1 do + buffer.writef32(mono, f * 4, (buffer.readf32(s.data, f * 8) + buffer.readf32(s.data, f * 8 + 4)) / 2) + end + end + local bits = if s.bits == 16 then 16 else 8 + local bps = bits // 8 + datas[k] = Pcm.encode(mono, s.length, { bits = bits, signed = true, delta = true }) + local typ = (if bits == 16 then 16 else 0) + local ls, ll = 0, 0 + if s.loopType > 0 then + typ += s.loopType + ls, ll = s.loopStart * bps, (s.loopEnd - s.loopStart) * bps + end + local ft = s.finetune + local rel = s.relativeNote + if m.format == "mod" then + rel = 0 + end + w:u32le(s.length * bps) + w:u32le(ls) + w:u32le(ll) + w:u8(math.clamp(math.floor(s.volume), 0, 64)) + w:u8(math.clamp(math.floor(ft), -128, 127) % 256) + w:u8(typ) + w:u8(math.clamp(math.floor(s.pan or 128), 0, 255)) + w:u8(math.clamp(math.floor(rel), -128, 127) % 256) + w:u8(0) + writeName(w, s.name, 22) + end + for _, dd in datas do + w:bytes(dd) + end + end + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function Xm.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Xm.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Xm diff --git a/tests/music/_similar.luau b/tests/music/_similar.luau new file mode 100644 index 0000000..e97f7eb --- /dev/null +++ b/tests/music/_similar.luau @@ -0,0 +1,209 @@ +-- tests/music/_similar: shared helper of the tracker tests (not a test itself): renders a module through a Decoder and +-- compares it with a reference render's features (tools/fixtures/_tracker.py: per 2048-frame block the RMS of left, +-- right and mid, and 40 log-spaced band magnitudes of mid from a Hann-windowed FFT). Same definitions on both sides. +local S = {} + +local SR, HOP, BANDS = 44100, 2048, 40 +local F_LO, F_HI = 150, 16000 +S.SR = SR + +local WINDOW = table.create(HOP, 0) +for i = 0, HOP - 1 do + WINDOW[i + 1] = 0.5 - 0.5 * math.cos(2 * math.pi * i / HOP) +end +local BAND_OF = table.create(HOP // 2, -1) +for b = 1, HOP // 2 - 1 do + local f = b * SR / HOP + if f >= F_LO and f < F_HI then + BAND_OF[b + 1] = math.min(BANDS - 1, math.floor(math.log(f / F_LO) / math.log(F_HI / F_LO) * BANDS)) + end +end + +local function fft(re: { number }, im: { number }, n: number) + local j = 0 + for i = 1, n - 1 do + local bit = n // 2 + while bit > 0 and j >= bit and (j // bit) % 2 == 1 do + j -= bit + bit //= 2 + end + j += bit + if i < j then + re[i + 1], re[j + 1] = re[j + 1], re[i + 1] + im[i + 1], im[j + 1] = im[j + 1], im[i + 1] + end + end + local size = 2 + while size <= n do + local ang = -2 * math.pi / size + local wr, wi = math.cos(ang), math.sin(ang) + local half = size // 2 + for start = 0, n - 1, size do + local cr, ci = 1, 0 + for k = 0, half - 1 do + local a, b = start + k + 1, start + k + half + 1 + local tr = re[b] * cr - im[b] * ci + local ti = re[b] * ci + im[b] * cr + re[b], im[b] = re[a] - tr, im[a] - ti + re[a], im[a] = re[a] + tr, im[a] + ti + cr, ci = cr * wr - ci * wi, cr * wi + ci * wr + end + end + size *= 2 + end +end + +-- features(samples (interleaved stereo f32 buffer), frames) -> { frames, rmsL, rmsR, rmsM, bands } +function S.features(buf: buffer, frames: number): any + local n = frames // HOP + local out = { frames = n, rmsL = {}, rmsR = {}, rmsM = {}, bands = {} } + local re, im = table.create(HOP, 0), table.create(HOP, 0) + for k = 0, n - 1 do + local sl, sr, sm = 0, 0, 0 + for i = 0, HOP - 1 do + local o = ((k * HOP + i) * 2) * 4 + local l, r = buffer.readf32(buf, o), buffer.readf32(buf, o + 4) + local m = (l + r) / 2 + sl += l * l + sr += r * r + sm += m * m + re[i + 1] = m * WINDOW[i + 1] + im[i + 1] = 0 + end + table.insert(out.rmsL, math.sqrt(sl / HOP)) + table.insert(out.rmsR, math.sqrt(sr / HOP)) + table.insert(out.rmsM, math.sqrt(sm / HOP)) + fft(re, im, HOP) + local e = table.create(BANDS, 0) + for b = 1, HOP // 2 - 1 do + local j = BAND_OF[b + 1] + if j >= 0 then + e[j + 1] += re[b + 1] * re[b + 1] + im[b + 1] * im[b + 1] + end + end + for j = 1, BANDS do + table.insert(out.bands, math.sqrt(e[j])) + end + end + return out +end + +-- renderAll(decoder, maxFrames) -> interleaved buffer, frames +function S.renderAll(dec: any, maxFrames: number): (buffer, number) + local total = math.min(dec.frames, maxFrames) + local out = buffer.create(math.max(1, total) * 8) + local pos = 0 + local chunk = buffer.create(4096 * 8) + while pos < total do + local _, n = dec:read(math.min(4096, total - pos), chunk) + if n == 0 then + break + end + buffer.copy(out, pos * 8, chunk, 0, n * 8) + pos += n + end + return out, pos +end + +local function db(x: number): number + return 20 * math.log10(x + 1e-6) +end + +-- compare(ours, ref) -> { gainDb, envCorr, spectral, balance } over the common frames: +-- gainDb total mid energy ratio in dB (ours / ref) +-- envCorr Pearson correlation of the per-block mid loudness in dB (blocks above -60 dB in either) +-- envErr mean absolute difference of the per-block mid loudness in dB, after removing gainDb (same blocks) +-- spectral mean cosine similarity of the band magnitude vectors (blocks where ref is above -50 dB) +-- balance mean absolute difference of the per-block left / right balance (L - R) / (L + R) (loud blocks) +function S.compare(a: any, b: any): any + local n = math.min(a.frames, b.frames) + local ea, eb = 0, 0 + for k = 1, n do + ea += a.rmsM[k] ^ 2 + eb += b.rmsM[k] ^ 2 + end + local gainDb = 10 * math.log10((ea + 1e-12) / (eb + 1e-12)) + local xs, ys = {}, {} + for k = 1, n do + local x, y = db(a.rmsM[k]), db(b.rmsM[k]) + if x > -60 or y > -60 then + table.insert(xs, x) + table.insert(ys, y) + end + end + local mx, my = 0, 0 + for i = 1, #xs do + mx += xs[i] + my += ys[i] + end + mx /= math.max(1, #xs) + my /= math.max(1, #ys) + local sxy, sxx, syy = 0, 0, 0 + for i = 1, #xs do + sxy += (xs[i] - mx) * (ys[i] - my) + sxx += (xs[i] - mx) ^ 2 + syy += (ys[i] - my) ^ 2 + end + local envCorr = if sxx > 0 and syy > 0 then sxy / math.sqrt(sxx * syy) else 1 + -- the mean loudness difference per block once the overall gain is taken out (dB, each side clamped at -60) + local envErr = 0 + for i = 1, #xs do + envErr += math.abs(math.max(xs[i], -60) - math.max(ys[i], -60) - gainDb) + end + envErr /= math.max(1, #xs) + local cs, cn = 0, 0 + local bal, bn = 0, 0 + for k = 1, n do + if db(b.rmsM[k]) > -50 then + local dot, na, nb = 0, 0, 0 + for j = 1, BANDS do + local x, y = a.bands[(k - 1) * BANDS + j], b.bands[(k - 1) * BANDS + j] + dot += x * y + na += x * x + nb += y * y + end + cs += if na > 0 and nb > 0 then dot / math.sqrt(na * nb) else 0 + cn += 1 + end + local la, ra, lb, rb = a.rmsL[k], a.rmsR[k], b.rmsL[k], b.rmsR[k] + if lb + rb > 0.01 then + bal += math.abs((la - ra) / (la + ra + 1e-9) - (lb - rb) / (lb + rb)) + bn += 1 + end + end + return { + gainDb = gainDb, + envCorr = envCorr, + envErr = envErr, + spectral = if cn > 0 then cs / cn else 1, + balance = if bn > 0 then bal / bn else 0, + frames = n, + } +end + +-- worst(ours, ref, count) -> the blocks with the lowest spectral similarity (for debugging): { {block, sim} } +function S.worst(a: any, b: any, count: number): { { number } } + local list = {} + for k = 1, math.min(a.frames, b.frames) do + if db(b.rmsM[k]) > -50 then + local dot, na, nb = 0, 0, 0 + for j = 1, BANDS do + local x, y = a.bands[(k - 1) * BANDS + j], b.bands[(k - 1) * BANDS + j] + dot += x * y + na += x * x + nb += y * y + end + table.insert(list, { k, if na > 0 and nb > 0 then dot / math.sqrt(na * nb) else 0, db(a.rmsM[k]), db(b.rmsM[k]) }) + end + end + table.sort(list, function(x, y) + return x[2] < y[2] + end) + local out = {} + for i = 1, math.min(count, #list) do + out[i] = list[i] + end + return out +end + +return S diff --git a/tests/music/it.luau b/tests/music/it.luau new file mode 100644 index 0000000..b06ac8b --- /dev/null +++ b/tests/music/it.luau @@ -0,0 +1,84 @@ +-- music/it tests: generated Impulse Tracker modules (tools/fixtures/it.py) parsed, rendered through codecs/Tracker and +-- compared with openmpt123's render (loudness envelope, band spectrum, stereo balance, song length), the contract, +-- and the fuzz no-throw pass. +local T = require("@tests/T") +local S = require("@tests/music/_similar") +local It = require("@formats/music/it") +local Tracker = require("@formats/codecs/Tracker") +local Bytes = require("@formats/core/Bytes") +local Cases = require("@tests/gen/it_cases") + +local t = T.suite("it") + +t:eq(It.name, "it", "name") +t:eq(It.category, "music", "category") +t:check(It.caps.decode and not It.caps.encode, "caps") + +local function load(data: string): any + return It.decode(Bytes.reader(buffer.fromstring(data))) +end + +local THRESH = { gainDb = 0.5, envErr = 1.0, spectral = 0.95, balance = 0.04, duration = 0.01 } + +for _, c in Cases do + local m, err = load(c.data) + t:check(m, c.name .. ": " .. tostring(err)) + t:check(It.sniff(Bytes.reader(buffer.fromstring(c.data))) > 0, c.name .. ": sniff") + local dec = m:render({ sampleRate = S.SR }) + t:check(dec, c.name .. ": render") + t:check(math.abs(dec.duration - c.duration) < THRESH.duration, string.format("%s: duration %.3f s, openmpt %.3f s", c.name, dec.duration, c.duration)) + local buf, frames = S.renderAll(dec, math.floor(c.duration * S.SR)) + local r = S.compare(S.features(buf, frames), c.ref) + t:note("%-7s gain %+.2f dB, loudness error %.2f dB, spectrum %.3f, balance %.3f, %.2f s", c.name, r.gainDb, r.envErr, r.spectral, r.balance, dec.duration) + if r.spectral < THRESH.spectral or r.envErr > THRESH.envErr then + for _, w in S.worst(S.features(buf, frames), c.ref, 6) do + t:note(" block %d (%.2f s): spectrum %.3f, ours %.1f dB, ref %.1f dB", w[1], (w[1] - 1) * 2048 / S.SR, w[2], w[3], w[4]) + end + end + t:check(math.abs(r.gainDb) < THRESH.gainDb, c.name .. ": loudness") + t:check(r.envErr < THRESH.envErr, c.name .. ": loudness envelope") + t:check(r.spectral > THRESH.spectral, c.name .. ": spectrum") + t:check(r.balance < THRESH.balance, c.name .. ": stereo balance") +end + +-- compressed samples (IT 2.14 / 2.15, 8 and 16-bit, mono and stereo) decode to exactly the uncompressed data +for _, c in Cases do + if c.plain then + local a, b = load(c.data), load(c.plain) + local same = #a.samples == #b.samples + for i, s in a.samples do + local o = b.samples[i] + same = same and s.length == o.length and s.channels == o.channels and buffer.tostring(s.data) == buffer.tostring(o.data) + end + t:check(same, c.name .. ": samples equal the uncompressed ones") + end +end + +-- seek: the position after a seek and the output continuing +do + local m = load(Cases[1].data) + local dec = m:render() + dec:seek(2) + t:check(math.abs(dec:position() - 2) < 0.001, "seek position") + local _, n = dec:read(1000) + t:eq(n, 1000, "read after seek") + t:check(Tracker.duration(m) == dec.duration, "duration()") +end + +-- the fuzz pass: decode, and a short render of whatever decodes +local samples = {} +for _, c in Cases do + table.insert(samples, c.data) +end +t:fuzz("decode", function(b: buffer) + local m = It.decode(Bytes.reader(b)) + if m then + local dec = Tracker.render(m, { maxDuration = 0.5, sampleRate = 8000 }) + if dec then + dec:read(4000) + end + end + return m +end, samples, { mutations = 30 }) + +t:done() 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/tests/music/mod.luau b/tests/music/mod.luau new file mode 100644 index 0000000..79e8941 --- /dev/null +++ b/tests/music/mod.luau @@ -0,0 +1,127 @@ +-- music/mod tests: generated ProTracker modules (tools/fixtures/mod.py) parsed, rendered through codecs/Tracker and +-- compared with openmpt123's render (loudness envelope, band spectrum, stereo balance, song length), the MOD writer's +-- round trip, the contract, and the fuzz no-throw pass. +local T = require("@tests/T") +local S = require("@tests/music/_similar") +local Mod = require("@formats/music/mod") +local Tracker = require("@formats/codecs/Tracker") +local Bytes = require("@formats/core/Bytes") +local Cases = require("@tests/gen/mod_cases") + +local t = T.suite("mod") + +t:eq(Mod.name, "mod", "name") +t:eq(Mod.category, "music", "category") +t:check(Mod.caps.decode and Mod.caps.encode, "caps") + +local function load(data: string): any + return Mod.decode(Bytes.reader(buffer.fromstring(data))) +end + +local THRESH = { gainDb = 0.5, envErr = 1.0, spectral = 0.95, balance = 0.04, duration = 0.01 } + +for _, c in Cases do + local m, err = load(c.data) + t:check(m, c.name .. ": " .. tostring(err)) + t:check(Mod.sniff(Bytes.reader(buffer.fromstring(c.data))) > 0, c.name .. ": sniff") + local dec = m:render({ sampleRate = S.SR }) + t:check(dec, c.name .. ": render") + t:check(math.abs(dec.duration - c.duration) < THRESH.duration, string.format("%s: duration %.3f s, openmpt %.3f s", c.name, dec.duration, c.duration)) + local buf, frames = S.renderAll(dec, math.floor(c.duration * S.SR)) + local r = S.compare(S.features(buf, frames), c.ref) + t:note("%-7s gain %+.2f dB, loudness error %.2f dB, spectrum %.3f, balance %.3f, %.2f s", c.name, r.gainDb, r.envErr, r.spectral, r.balance, dec.duration) + if r.spectral < THRESH.spectral or r.envErr > THRESH.envErr then + for _, w in S.worst(S.features(buf, frames), c.ref, 6) do + t:note(" block %d (%.2f s): spectrum %.3f, ours %.1f dB, ref %.1f dB", w[1], (w[1] - 1) * 2048 / S.SR, w[2], w[3], w[4]) + end + end + t:check(math.abs(r.gainDb) < THRESH.gainDb, c.name .. ": loudness") + t:check(r.envErr < THRESH.envErr, c.name .. ": loudness envelope") + t:check(r.spectral > THRESH.spectral, c.name .. ": spectrum") + t:check(r.balance < THRESH.balance, c.name .. ": stereo balance") + -- the writer: MOD -> MOD gives the same bytes back (the fixtures are canonical ProTracker files) + local out, werr = Mod.encode(m) + t:check(out, c.name .. ": encode " .. tostring(werr)) + local m2 = Mod.decode(Bytes.reader(out :: buffer)) + t:check(m2, c.name .. ": re-decode") + t:eq(buffer.tostring(out :: buffer), c.data, c.name .. ": round trip bytes") +end + +-- MOD -> XM: the converted module plays as long, and sounds alike (XM has no channel panning and uses FT2's NTSC +-- Amiga clock, so only the duration and the band spectrum are compared) +local Xm = require("@formats/music/xm") +for _, c in Cases do + local m = load(c.data) + local xb, xerr = Xm.encode(m) + t:check(xb, c.name .. ": mod -> xm " .. tostring(xerr)) + local x = Xm.decode(Bytes.reader(xb :: buffer)) + t:check(x and x.format == "xm" and #x.instruments == #m.samples, c.name .. ": the xm decodes") + local dec = x:render() + t:check(math.abs(dec.duration - c.duration) < THRESH.duration, c.name .. ": xm duration") + local buf, frames = S.renderAll(dec, math.floor(c.duration * S.SR)) + local r = S.compare(S.features(buf, frames), c.ref) + t:check(r.spectral > 0.9, string.format("%s: xm spectrum %.3f", c.name, r.spectral)) +end + +-- through the API: load sniffs the MOD, open gives a Decoder, save converts to XM, load(as audio) renders +do + local F = require("@formats") + local m, err = F.load(Cases[1].data) + t:check(m and m.kind == "music" and m.format == "mod", "F.load: " .. tostring(err)) + local dec = F.open(Cases[1].data) + t:check(dec and dec.channels == 2 and dec.sampleRate == 44100, "F.open: a Decoder") + local xb = F.save(m, nil, { format = "xm" }) + t:check(xb and F.load(xb).format == "xm", "F.save as xm") + t:eq(F.saveString(m, { format = "mod" }), Cases[1].data, "F.saveString keeps the MOD bytes") +end + +-- seek: the position after a seek and the output continuing +do + local m = load(Cases[1].data) + local dec = m:render() + dec:seek(2) + t:check(math.abs(dec:position() - 2) < 0.001, "seek position") + local _, n = dec:read(1000) + t:eq(n, 1000, "read after seek") + t:check(Tracker.duration(m) == dec.duration, "duration()") + -- the same samples as playing up to that point (after the short fade-in that follows a seek) + local a, b = m:render(), m:render() + a:seek(3.5) + local at = math.floor(3.5 * S.SR) + while at > 0 do + local _, n = b:read(math.min(at, 8192)) + at -= n + end + local x, y = a:read(4096), b:read(4096) + local worst = 0 + for i = 256, 4095 * 2 do + worst = math.max(worst, math.abs(buffer.readf32(x, i * 4) - buffer.readf32(y, i * 4))) + end + t:check(worst < 1e-4, "seek then read matches reading through (" .. worst .. ")") + -- loop = true keeps playing past the end (frames / duration still give one pass) + local l = m:render({ loop = true, sampleRate = 8000 }) + local total = 0 + for _ = 1, 30 do + local _, n = l:read(8000) + total += n + end + t:check(total == 240000 and math.abs(l.duration - dec.duration) < 0.01, "loop plays past the end") +end + +-- the fuzz pass: decode, and a short render of whatever decodes +local samples = {} +for _, c in Cases do + table.insert(samples, c.data) +end +t:fuzz("decode", function(b: buffer) + local m = Mod.decode(Bytes.reader(b)) + if m then + local dec = Tracker.render(m, { maxDuration = 0.5, sampleRate = 8000 }) + if dec then + dec:read(4000) + end + end + return m +end, samples, { mutations = 30 }) + +t:done() diff --git a/tests/music/s3m.luau b/tests/music/s3m.luau new file mode 100644 index 0000000..ddff1a5 --- /dev/null +++ b/tests/music/s3m.luau @@ -0,0 +1,71 @@ +-- music/s3m tests: generated Scream Tracker 3 modules (tools/fixtures/s3m.py) parsed, rendered through codecs/Tracker and +-- compared with openmpt123's render (loudness envelope, band spectrum, stereo balance, song length), the contract, +-- and the fuzz no-throw pass. +local T = require("@tests/T") +local S = require("@tests/music/_similar") +local S3m = require("@formats/music/s3m") +local Tracker = require("@formats/codecs/Tracker") +local Bytes = require("@formats/core/Bytes") +local Cases = require("@tests/gen/s3m_cases") + +local t = T.suite("s3m") + +t:eq(S3m.name, "s3m", "name") +t:eq(S3m.category, "music", "category") +t:check(S3m.caps.decode and not S3m.caps.encode, "caps") + +local function load(data: string): any + return S3m.decode(Bytes.reader(buffer.fromstring(data))) +end + +local THRESH = { gainDb = 0.5, envErr = 1.0, spectral = 0.95, balance = 0.04, duration = 0.01 } + +for _, c in Cases do + local m, err = load(c.data) + t:check(m, c.name .. ": " .. tostring(err)) + t:check(S3m.sniff(Bytes.reader(buffer.fromstring(c.data))) > 0, c.name .. ": sniff") + local dec = m:render({ sampleRate = S.SR }) + t:check(dec, c.name .. ": render") + t:check(math.abs(dec.duration - c.duration) < THRESH.duration, string.format("%s: duration %.3f s, openmpt %.3f s", c.name, dec.duration, c.duration)) + local buf, frames = S.renderAll(dec, math.floor(c.duration * S.SR)) + local r = S.compare(S.features(buf, frames), c.ref) + t:note("%-7s gain %+.2f dB, loudness error %.2f dB, spectrum %.3f, balance %.3f, %.2f s", c.name, r.gainDb, r.envErr, r.spectral, r.balance, dec.duration) + if r.spectral < THRESH.spectral or r.envErr > THRESH.envErr then + for _, w in S.worst(S.features(buf, frames), c.ref, 6) do + t:note(" block %d (%.2f s): spectrum %.3f, ours %.1f dB, ref %.1f dB", w[1], (w[1] - 1) * 2048 / S.SR, w[2], w[3], w[4]) + end + end + t:check(math.abs(r.gainDb) < THRESH.gainDb, c.name .. ": loudness") + t:check(r.envErr < THRESH.envErr, c.name .. ": loudness envelope") + t:check(r.spectral > THRESH.spectral, c.name .. ": spectrum") + t:check(r.balance < THRESH.balance, c.name .. ": stereo balance") +end + +-- seek: the position after a seek and the output continuing +do + local m = load(Cases[1].data) + local dec = m:render() + dec:seek(2) + t:check(math.abs(dec:position() - 2) < 0.001, "seek position") + local _, n = dec:read(1000) + t:eq(n, 1000, "read after seek") + t:check(Tracker.duration(m) == dec.duration, "duration()") +end + +-- the fuzz pass: decode, and a short render of whatever decodes +local samples = {} +for _, c in Cases do + table.insert(samples, c.data) +end +t:fuzz("decode", function(b: buffer) + local m = S3m.decode(Bytes.reader(b)) + if m then + local dec = Tracker.render(m, { maxDuration = 0.5, sampleRate = 8000 }) + if dec then + dec:read(4000) + end + end + return m +end, samples, { mutations = 30 }) + +t:done() diff --git a/tests/music/sf2.luau b/tests/music/sf2.luau new file mode 100644 index 0000000..057b30e --- /dev/null +++ b/tests/music/sf2.luau @@ -0,0 +1,338 @@ +-- music/sf2 + codecs/SoundFont tests: a self-made SF2 parsed (INFO, presets, sample headers, instruments, generator +-- merging with preset / instrument global zones, 16-bit and sm24 samples), a test song rendered through it compared +-- with FluidSynth's render (loudness envelope and per-segment band spectra by correlation, pitch peaks), bad files, +-- the built-in fallback waveform set, and the fuzz no-throw pass. Fixtures: tools/fixtures/sf2.py. +local T = require("@tests/T") +local Sf2 = require("@formats/music/sf2") +local Midi = require("@formats/music/midi") +local SoundFont = require("@formats/codecs/SoundFont") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/sf2_cases") + +local t = T.suite("sf2") + +local function reader(s: string): Bytes.Reader + return Bytes.reader(buffer.fromstring(s)) +end + +-- the contract +t:eq(Sf2.name, "sf2", "name") +t:eq(Sf2.category, "music", "category") +t:check(Sf2.caps.decode and not Sf2.caps.encode, "caps") +t:eq(Sf2.sniff(reader(Fx.sf2)), 1, "sniff") +t:eq(Sf2.sniff(reader("RIFF\0\0\0\0WAVE")), 0, "sniff WAVE") + +-- parse +local sf, err = Sf2.decode(reader(Fx.sf2)) +t:check(sf, "decode: " .. tostring(err)) +local E = Fx.expect +t:eq(sf.kind, "soundfont", "kind") +t:eq(sf.info.name, E.info.name, "INAM") +t:eq(sf.info.engine, E.info.engine, "isng") +t:eq(sf.meta.source.version, E.info.version, "ifil") +t:eq(#sf.presets, #E.presets, "preset count") +for i, p in E.presets do + t:eq(sf.presets[i].name, p.name, "preset " .. i .. " name") + t:eq(sf.presets[i].bank, p.bank, "preset " .. i .. " bank") + t:eq(sf.presets[i].preset, p.preset, "preset " .. i .. " number") +end +t:eq(#sf.sampleHeaders, #E.samples, "sample headers") +for i, s in E.samples do + for k, v in s do + t:eq(sf.sampleHeaders[i][k], v, "sample " .. i .. " " .. k) + end +end +for i, n in E.instruments do + t:eq(sf.instruments[i].name, n, "instrument " .. i) +end +local function preset(name: string): any + for _, p in sf.presets do + if p.name == name then + return p + end + end + return nil +end +do + local sine, saw, drums = preset("Sine"), preset("Saw"), preset("Drums") + t:eq(#sine.regions, 1, "Sine: the preset global zone is not a region") + t:check(math.abs(sine.regions[1].attenuation - 30 * 0.04) < 1e-9, "Sine: the preset global zone's attenuation applies") + t:check(math.abs(sine.regions[1].aRelease - 0.2) < 0.001, "Sine: release in seconds") + t:check(math.abs(sine.regions[1].aSustain - 10 ^ (-6 / 20)) < 1e-6, "Sine: sustain 60 cB = -6 dB") + t:eq(sine.regions[1].loopMode, 1, "Sine: looped") + t:eq(sine.regions[1].keycenter, 69, "Sine: root key from the sample header") + t:eq(sine.regions[1].tune, -4, "Sine: pitch correction") + t:eq(#saw.regions, 1, "Saw: the instrument global zone is not a region") + t:check(math.abs(saw.regions[1].filterFc - math.floor(1200 * math.log(2500 / 8.176, 2) + 0.5)) <= 1, "Saw: the instrument global zone's filter applies") + t:eq(saw.regions[1].modEnvToFilterFc, 2400, "Saw: mod env to filter") + t:eq(#drums.regions, 4, "Drums: four key zones") + local groups = 0 + for _, r in drums.regions do + t:check(math.abs(r.aRelease - 0.05) < 0.001, "Drums: release from the instrument global zone") + if r.group == 1 then + groups += 1 + end + end + t:eq(groups, 2, "Drums: two hats in exclusive class 1") + t:eq(drums.regions[1].lokey, 35, "Drums: key range lo") + t:eq(drums.regions[1].hikey, 36, "Drums: key range hi") +end +-- samples: 16-bit, and 24-bit with sm24 +do + local sf24 = Sf2.decode(reader(Fx.sf2_24)) + t:check(sf24 and sf24.meta.source.sm24, "sm24 read") + t:eq(sf.meta.source.sm24, false, "no sm24") + for _, v in E.values do + local i, hi, lo = v[1], v[2], v[3] + local a = buffer.readf32(sf.samples, i * 4) + local b = buffer.readf32(sf24.samples, i * 4) + t:check(math.abs(a - hi / 32767) < 1e-6, "16-bit sample " .. i) + t:check(math.abs(b - (hi * 256 + lo) / 8388607) < 1e-6, "24-bit sample " .. i) + end + t:eq(buffer.len(sf.samples), (sf.sampleCount + 1) * 4, "samples: one pad sample") +end + +-- ------------------------------------------------------------------------------------------------ vs FluidSynth +local F = Fx.fluid +local song = Midi.decode(reader(Fx.song)) +t:check(song, "song decodes") +local dec = assert(Midi.render(song, { soundfont = sf, tail = 2 })) +local frames = math.min(dec.frames, F.frames) +local mono = table.create(frames, 0) +do + local got = 0 + while got < frames do + local b, n = dec:read(math.min(8192, frames - got)) + if n == 0 then + break + end + for i = 0, n - 1 do + mono[got + i + 1] = (buffer.readf32(b, i * 8) + buffer.readf32(b, i * 8 + 4)) * 0.5 + end + got += n + end + t:eq(got, frames, "rendered the compared length") +end + +local function pearson(a: { number }, b: { number }): number + local n = math.min(#a, #b) + local ma, mb = 0, 0 + for i = 1, n do + ma += a[i] + mb += b[i] + end + ma /= n + mb /= n + local sab, saa, sbb = 0, 0, 0 + for i = 1, n do + local x, y = a[i] - ma, b[i] - mb + sab += x * y + saa += x * x + sbb += y * y + end + return sab / math.sqrt(saa * sbb + 1e-30) +end + +-- in-place radix-2 FFT of re / im (1-based arrays of length n, a power of two) +local function fft(re: { number }, im: { number }, n: number) + local j = 0 + for i = 0, n - 2 do + if i < j then + re[i + 1], re[j + 1] = re[j + 1], re[i + 1] + im[i + 1], im[j + 1] = im[j + 1], im[i + 1] + end + local m = n // 2 + while m >= 1 and j >= m do + j -= m + m //= 2 + end + j += m + end + local len = 2 + while len <= n do + local ang = -2 * math.pi / len + local wr, wi = math.cos(ang), math.sin(ang) + for s = 0, n - 1, len do + local cr, ci = 1, 0 + for k = 0, len // 2 - 1 do + local a, b = s + k + 1, s + k + len // 2 + 1 + local xr = re[b] * cr - im[b] * ci + local xi = re[b] * ci + im[b] * cr + re[b], im[b] = re[a] - xr, im[a] - xi + re[a], im[a] = re[a] + xr, im[a] + xi + cr, ci = cr * wr - ci * wi, cr * wi + ci * wr + end + end + len *= 2 + end +end + +local function power(start: number, n: number): { number } + local re, im = table.create(n, 0), table.create(n, 0) + for i = 0, n - 1 do + re[i + 1] = (mono[start + i + 1] or 0) * (0.5 - 0.5 * math.cos(2 * math.pi * i / n)) + end + fft(re, im, n) + local p = table.create(n // 2 + 1, 0) + for k = 0, n // 2 do + p[k + 1] = re[k + 1] ^ 2 + im[k + 1] ^ 2 + end + return p +end + +local rate = F.rate +-- the loudness envelope (50 ms RMS) +local env = {} +for i = 0, frames - 2205, 2205 do + local s = 0 + for k = 1, 2205 do + local v = mono[i + k] + s += v * v + end + table.insert(env, math.sqrt(s / 2205)) +end +local envCorr = pearson(env, F.env) +local ENV_MIN = 0.95 +t:check(envCorr > ENV_MIN, string.format("loudness envelope correlation %.3f > %.2f", envCorr, ENV_MIN)) +t:note("loudness envelope vs FluidSynth: r = %.3f (%d windows)", envCorr, #env) + +-- per-segment band spectra +local BAND_MIN = 0.93 +local worstBand = 1 +for si, seg in F.segments do + local acc = table.create(24, 0) + local count = 0 + for s = math.floor(seg[1] * rate), math.floor(seg[2] * rate) - 2048, 1024 do + local p = power(s, 2048) + for k = 0, 1024 do + local f = k * rate / 2048 + for b = 1, 24 do + if f >= F.edges[b] and f < F.edges[b + 1] then + acc[b] += p[k + 1] + break + end + end + end + count += 1 + end + local db = table.create(24, 0) + for b = 1, 24 do + db[b] = 10 * math.log10(acc[b] / math.max(count, 1) + 1e-12) + end + local r = pearson(db, F.bands[si]) + worstBand = math.min(worstBand, r) + t:check(r > BAND_MIN, string.format("segment %d band spectrum correlation %.3f > %.2f", si, r, BAND_MIN)) + t:note("segment %d (%g-%g s) band spectrum vs FluidSynth: r = %.3f", si, seg[1], seg[2], r) +end + +-- pitch peaks (vibrato square, a note bent an octave with an RPN 0 range of 12, the saw melody's first note) +for wi, w in F.windows do + local acc = table.create(4097, 0) + for s = math.floor(w[1] * rate), math.floor(w[2] * rate) - 8192, 2048 do + local p = power(s, 8192) + for k = 1, 4097 do + acc[k] += p[k] + end + end + local best, bk = -1, 2 + for k = 2, 4096 do + if acc[k] > best then + best, bk = acc[k], k + end + end + local y0, y1, y2 = math.log(acc[bk - 1] + 1e-30), math.log(acc[bk] + 1e-30), math.log(acc[bk + 1] + 1e-30) + local hz = ((bk - 1) + 0.5 * (y0 - y2) / (y0 - 2 * y1 + y2)) * rate / 8192 + local ratio = hz / F.peaks[wi] + t:check(math.abs(ratio - 1) < 0.015, string.format("window %d peak %.1f Hz vs FluidSynth %.1f Hz", wi, hz, F.peaks[wi])) + t:note("window %g-%g s: peak %.1f Hz (FluidSynth %.1f Hz)", w[1], w[2], hz, F.peaks[wi]) +end + +-- ------------------------------------------------------------------------------------------------ bad files +local function bad(data: string, code: string, label: string) + local ok, v, e = pcall(Sf2.decode, reader(data)) + t:check(ok, label .. ": threw " .. tostring(v)) + t:check(v == nil and Err.is(e) and e.code == code, label .. ": " .. tostring(e)) +end +bad("RIFX\0\0\0\0sfbk", Err.CORRUPT, "not RIFF") +bad("RIFF\4\0\0\0WAVE", Err.CORRUPT, "not sfbk") +bad("RIFF\4\0\0\0sfbk", Err.CORRUPT, "no chunks") +bad(string.sub(Fx.sf2, 1, 40), Err.CORRUPT, "truncated in INFO") +local lim, lerr = Sf2.decode(reader(Fx.sf2), { maxSamples = 100 }) +t:check(lim == nil and lerr.code == Err.LIMIT, "maxSamples: LIMIT") +local lim2, lerr2 = Sf2.decode(reader(Fx.sf2), { maxRegions = 3 }) +t:check(lim2 == nil and lerr2.code == Err.LIMIT, "maxRegions: LIMIT") +local p, perr = SoundFont.parse(42 :: any) +t:check(p == nil and perr.code == Err.ARG, "parse: bad argument") + +-- ------------------------------------------------------------------------------------------------ fallback +do + local fb = SoundFont.fallback() + t:eq(#fb.presets, 129, "fallback: 128 programs + a drum kit") + local s = SoundFont.synth(nil, 22050) + local Synth = SoundFont.Synth + local out = buffer.create(2205 * 8) + for program = 0, 127, 8 do + Synth.reset(s) + Synth.midi(s, 0xC0, program, 0) + Synth.midi(s, 0x90, 60, 100) + buffer.fill(out, 0, 0) + Synth.render(s, out, 0, 2205) + local e = 0 + for i = 0, 2205 * 2 - 1 do + local v = buffer.readf32(out, i * 4) + t:check(v == v and math.abs(v) < 4, "fallback: finite samples") + e += v * v + end + t:check(e > 0.01, "fallback program " .. program .. " sounds") + end + for _, key in { 35, 36, 38, 42, 46, 49, 51, 60 } do + Synth.reset(s) + Synth.midi(s, 0x99, key, 120) + buffer.fill(out, 0, 0) + Synth.render(s, out, 0, 2205) + local e = 0 + for i = 0, 2205 * 2 - 1 do + e += buffer.readf32(out, i * 4) ^ 2 + end + t:check(e > 0.01, "fallback drum " .. key .. " sounds") + end + -- exclusive class: a closed hat cuts the open hat + Synth.reset(s) + Synth.midi(s, 0x99, 46, 120) + t:eq(Synth.active(s), 1, "open hat") + Synth.midi(s, 0x99, 42, 120) + Synth.render(s, out, 0, 2205) + t:eq(Synth.active(s), 1, "closed hat ends the open hat (exclusive class)") + -- render range clipping: never writes past the buffer + Synth.render(s, out, 2200, 100000) + Synth.render(s, out, -5, 10) + t:check(true, "out-of-range render requests are clipped") +end + +-- the fuzz no-throw pass (parse, then a few notes through whatever parsed) +t:fuzz("decode", function(b: buffer) + local f = Sf2.decode(Bytes.reader(b)) + if f then + local s = SoundFont.synth(f, 22050) + for ch = 0, 15 do + SoundFont.Synth.midi(s, 0xC0 + ch, ch * 8, 0) + SoundFont.Synth.midi(s, 0x90 + ch, 30 + ch * 5, 100) + end + local out = buffer.create(512 * 8) + SoundFont.Synth.render(s, out, 0, 512) + end +end, { Fx.sf2 }, { mutations = 60, garbage = 100 }) +-- mutations inside the hydra (the last ~1 KB) exercise the zone / index clamping +t:fuzz("hydra", function(b: buffer) + local f = Sf2.decode(Bytes.reader(b)) + if f then + local s = SoundFont.synth(f, 22050) + SoundFont.Synth.midi(s, 0x90, 60, 100) + SoundFont.Synth.midi(s, 0x99, 36, 100) + local out = buffer.create(256 * 8) + SoundFont.Synth.render(s, out, 0, 256) + end +end, { Fx.sf2 }, { mutations = 200, garbage = 0, keepHeader = #Fx.sf2 - 1200 }) + +t:done() diff --git a/tests/music/xm.luau b/tests/music/xm.luau new file mode 100644 index 0000000..b117848 --- /dev/null +++ b/tests/music/xm.luau @@ -0,0 +1,77 @@ +-- music/xm tests: generated FastTracker 2 modules (tools/fixtures/xm.py) parsed, rendered through codecs/Tracker and +-- compared with openmpt123's render (loudness envelope, band spectrum, stereo balance, song length), the XM writer's +-- round trip, the contract, and the fuzz no-throw pass. +local T = require("@tests/T") +local S = require("@tests/music/_similar") +local Xm = require("@formats/music/xm") +local Tracker = require("@formats/codecs/Tracker") +local Bytes = require("@formats/core/Bytes") +local Cases = require("@tests/gen/xm_cases") + +local t = T.suite("xm") + +t:eq(Xm.name, "xm", "name") +t:eq(Xm.category, "music", "category") +t:check(Xm.caps.decode and Xm.caps.encode, "caps") + +local function load(data: string): any + return Xm.decode(Bytes.reader(buffer.fromstring(data))) +end + +local THRESH = { gainDb = 0.5, envErr = 1.0, spectral = 0.95, balance = 0.04, duration = 0.01 } + +for _, c in Cases do + local m, err = load(c.data) + t:check(m, c.name .. ": " .. tostring(err)) + t:check(Xm.sniff(Bytes.reader(buffer.fromstring(c.data))) > 0, c.name .. ": sniff") + local dec = m:render({ sampleRate = S.SR }) + t:check(dec, c.name .. ": render") + t:check(math.abs(dec.duration - c.duration) < THRESH.duration, string.format("%s: duration %.3f s, openmpt %.3f s", c.name, dec.duration, c.duration)) + local buf, frames = S.renderAll(dec, math.floor(c.duration * S.SR)) + local r = S.compare(S.features(buf, frames), c.ref) + t:note("%-7s gain %+.2f dB, loudness error %.2f dB, spectrum %.3f, balance %.3f, %.2f s", c.name, r.gainDb, r.envErr, r.spectral, r.balance, dec.duration) + if r.spectral < THRESH.spectral or r.envErr > THRESH.envErr then + for _, w in S.worst(S.features(buf, frames), c.ref, 6) do + t:note(" block %d (%.2f s): spectrum %.3f, ours %.1f dB, ref %.1f dB", w[1], (w[1] - 1) * 2048 / S.SR, w[2], w[3], w[4]) + end + end + t:check(math.abs(r.gainDb) < THRESH.gainDb, c.name .. ": loudness") + t:check(r.envErr < THRESH.envErr, c.name .. ": loudness envelope") + t:check(r.spectral > THRESH.spectral, c.name .. ": spectrum") + t:check(r.balance < THRESH.balance, c.name .. ": stereo balance") + -- the writer: XM -> XM gives the same bytes back (the fixtures use the FT2 layout) + local out, werr = Xm.encode(m) + t:check(out, c.name .. ": encode " .. tostring(werr)) + local m2 = Xm.decode(Bytes.reader(out :: buffer)) + t:check(m2, c.name .. ": re-decode") + t:eq(buffer.tostring(out :: buffer), c.data, c.name .. ": round trip bytes") +end + +-- seek: the position after a seek and the output continuing +do + local m = load(Cases[1].data) + local dec = m:render() + dec:seek(2) + t:check(math.abs(dec:position() - 2) < 0.001, "seek position") + local _, n = dec:read(1000) + t:eq(n, 1000, "read after seek") + t:check(Tracker.duration(m) == dec.duration, "duration()") +end + +-- the fuzz pass: decode, and a short render of whatever decodes +local samples = {} +for _, c in Cases do + table.insert(samples, c.data) +end +t:fuzz("decode", function(b: buffer) + local m = Xm.decode(Bytes.reader(b)) + if m then + local dec = Tracker.render(m, { maxDuration = 0.5, sampleRate = 8000 }) + if dec then + dec:read(4000) + end + end + return m +end, samples, { mutations = 30 }) + +t:done() diff --git a/tools/bench.luau b/tools/bench.luau index 544434f..21ab2f7 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -599,3 +599,119 @@ do end) local _ = dt end + +-- MIDI through the SoundFont synth (tools/fixtures/sf2.py's test song; tools/fixtures/midi.py's "song" through the +-- built-in waveform set): seconds of stereo 44.1 kHz audio rendered per second of CPU +do + local Midi = require("@formats/music/midi") + local Sf2 = require("@formats/music/sf2") + local SF = require("@tests/gen/sf2_cases") + local MC = require("@tests/gen/midi_cases") + local sf = assert(Sf2.decode(Bytes.reader(buffer.fromstring(SF.sf2)))) + local function realtime(label: string, data: string, font: any) + local song = assert(Midi.decode(Bytes.reader(buffer.fromstring(data)))) + local best = math.huge + local frames = 0 + for _ = 1, 3 do + local dec = assert(Midi.render(song, { soundfont = font, tail = 0 })) + local out = buffer.create(4096 * 8) + local t0 = os.clock() + frames = 0 + while true do + local _, n = dec:read(4096, out) + if n == 0 then + break + end + frames += n + end + best = math.min(best, os.clock() - t0) + end + print(string.format("%-8s %-30s %8.2f ms %7.1f x realtime", runtime, label, best * 1000, frames / 44100 / best)) + end + realtime("midi render sf2 (test song)", SF.song, sf) + for _, c in MC do + if c.name == "song" then + realtime("midi render fallback", c.data, nil) + end + end +end +-- the synth's per-voice cost: 32 sustained, filtered, looped voices (sf2 saw preset with a mod env) for 2 s +do + local SoundFont = require("@formats/codecs/SoundFont") + local Sf2 = require("@formats/music/sf2") + local SF = require("@tests/gen/sf2_cases") + local sf = assert(Sf2.decode(Bytes.reader(buffer.fromstring(SF.sf2)))) + local frames = 88200 + local out = buffer.create(frames * 8) + local best = math.huge + for _ = 1, 3 do + local s = SoundFont.synth(sf, 44100) + SoundFont.Synth.midi(s, 0xC0, 1, 0) + for k = 0, 31 do + SoundFont.Synth.midi(s, 0x90, 40 + k, 100) + end + buffer.fill(out, 0, 0) + local t0 = os.clock() + for f = 0, frames - 1, 1024 do + SoundFont.Synth.render(s, out, f, 1024) + end + best = math.min(best, os.clock() - t0) + end + print(string.format("%-8s %-30s %8.2f ms %7.1f M voice-samples/s", runtime, "synth 32 voices x 2 s", best * 1000, 32 * frames / best / 1e6)) +end +-- the tracker engine: 32 channels of looped samples (one note each, linear interpolation, volume ramps), and an +-- IT-style module with background voices (NNA continue) and resonant filters on every channel +do + local Tracker = require("@formats/codecs/Tracker") + local function song(format: string, filter: boolean): any + local m = Tracker.newModule(format, 32) + m.order = { 0 } + m.patterns[1] = Tracker.newPattern(64, 32) + local s = Tracker.newSample("saw") + s.length = 1000 + s.data = buffer.create(4000) + for i = 0, 999 do + buffer.writef32(s.data, i * 4, (i % 100) / 50 - 1) + end + s.loopStart, s.loopEnd, s.loopType = 0, 1000, 1 + m.samples[1] = s + if format == "it" then + local ins = Tracker.newInstrument("nna") + for n = 1, 120 do + ins.sampleMap[n] = 1 + end + ins.nna = 1 + ins.fadeout = 64 + if filter then + ins.cutoff, ins.resonance = 60, 40 + end + m.instruments[1] = ins + end + for ch = 1, 32 do + for row = 0, 63, 16 do + Tracker.setCell(m, 0, row, ch, 37 + ch + row // 16, 1, 0, 0, 0) + end + end + return m + end + local function realtime(label: string, m: any, voices: number) + local best, frames = math.huge, 0 + local out = buffer.create(4096 * 8) + for _ = 1, 3 do + local dec = Tracker.render(m) :: any + frames = 0 + local t0 = os.clock() + while true do + local _, n = dec:read(4096, out) + if n == 0 then + break + end + frames += n + end + best = math.min(best, os.clock() - t0) + end + print(string.format("%-8s %-30s %8.2f ms %7.1f x realtime %5.1f M voice-samples/s", runtime, label, best * 1000, frames / 44100 / best, voices * frames / best / 1e6)) + end + realtime("tracker 32 ch (mod)", song("mod", false), 32) + realtime("tracker 32 ch + NNA, filters", song("it", true), 64) +end 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/_sf2_features.py b/tools/fixtures/_sf2_features.py new file mode 100644 index 0000000..09f39fb --- /dev/null +++ b/tools/fixtures/_sf2_features.py @@ -0,0 +1,61 @@ +# Audio features of a WAV on stdin (run by tools/fixtures/sf2.py through ctx.python(["numpy"], ...); not a generator). +# tests/music/sf2.luau computes the same features from formats-luau's render and compares them: +# env RMS of the mono mix per 50 ms window (2205 frames) +# bands per 2 s segment: mean power in 24 log-spaced bands (60 Hz .. 16 kHz) of 2048-point Hann frames (hop 1024), +# in dB +# peaks the strongest frequency (parabolic interpolation) of the mean 8192-point Hann spectrum in a few windows +import io, json, sys, wave +import numpy as np + +w = wave.open(io.BytesIO(sys.stdin.buffer.read())) +rate, ch, width, n = w.getframerate(), w.getnchannels(), w.getsampwidth(), w.getnframes() +raw = w.readframes(n) +assert width == 2, width +x = np.frombuffer(raw, dtype="= edges[k]) & (freqs < edges[k + 1])].sum() + frames += 1 + return [float(10 * np.log10(v / max(frames, 1) + 1e-12)) for v in acc] + + +PN = 8192 +phan = 0.5 - 0.5 * np.cos(2 * np.pi * np.arange(PN) / PN) +WINDOWS = [(4.2, 5.4), (8.05, 8.45), (8.55, 8.95), (2.02, 2.33)] + + +def peak(a, b): + acc = np.zeros(PN // 2 + 1) + for s in range(int(a * rate), int(b * rate) - PN + 1, PN // 4): + acc += np.abs(np.fft.rfft(mono[s:s + PN] * phan)) ** 2 + k = int(np.argmax(acc[1:-1])) + 1 + y0, y1, y2 = np.log(acc[k - 1] + 1e-30), np.log(acc[k] + 1e-30), np.log(acc[k + 1] + 1e-30) + d = 0.5 * (y0 - y2) / (y0 - 2 * y1 + y2) + return float((k + d) * rate / PN) + + +json.dump({ + "rate": rate, + "frames": len(mono), + "env": env, + "edges": edges, + "segments": [list(s) for s in SEGMENTS], + "bands": [bands(a, b) for a, b in SEGMENTS], + "windows": [list(wd) for wd in WINDOWS], + "peaks": [peak(a, b) for a, b in WINDOWS], +}, sys.stdout) diff --git a/tools/fixtures/_tracker.py b/tools/fixtures/_tracker.py new file mode 100644 index 0000000..eeef247 --- /dev/null +++ b/tools/fixtures/_tracker.py @@ -0,0 +1,495 @@ +# Tracker fixture helpers (used by tools/fixtures/{mod,s3m,xm,it}.py): small writers for MOD, S3M, XM and IT +# (including IT 2.14 / 2.15 sample compression), synthesized samples, reference renders through openmpt123 (nix +# libopenmpt) and the comparison features (per 2048-frame block: RMS of left / right / mid and 40 log-spaced band +# magnitudes of the mid signal), computed the same way in tests/music/_similar.luau. Every module is generated here +# (no third-party files), so the fixtures carry no licence. +import json, math, os, struct, subprocess, tempfile + +SR = 44100 +HOP = 2048 +BANDS = 40 +F_LO, F_HI = 150.0, 16000.0 + + +# ---------------------------------------------------------------------------------------------- samples +def synth(kind, n, period, amp=0.9, seed=1, decay=None): + """float samples in [-1, 1]: sine / square / saw / tri / noise / pluck""" + out = [] + s = seed + for i in range(n): + ph = (i % period) / period + if kind == "sine": + v = math.sin(2 * math.pi * ph) + elif kind == "square": + v = 1.0 if ph < 0.5 else -1.0 + elif kind == "saw": + v = 2 * ph - 1 + elif kind == "tri": + v = 4 * ph - 1 if ph < 0.5 else 3 - 4 * ph + else: # noise + s = (s * 1103515245 + 12345) % 2147483648 + v = (s / 2147483648) * 2 - 1 + if decay: + v *= math.exp(-i / decay) + out.append(v * amp) + return out + + +def s8(xs): + return bytes((max(-128, min(127, int(round(x * 127)))) & 255) for x in xs) + + +def u8(xs): + return bytes(max(0, min(255, int(round(x * 127)) + 128)) for x in xs) + + +def s16(xs): + return b"".join(struct.pack("= 128 else b + out.append((v - prev) & 255) + prev = v + return bytes(out) + + +def delta16(raw): + out, prev = bytearray(), 0 + for i in range(0, len(raw), 2): + v = struct.unpack_from("HBBHH", len(s["data"]) // 2, s.get("finetune", 0) & 15, + s.get("volume", 64), ls // 2, ll // 2) + else: + out += b"\0" * 22 + struct.pack(">HBBHH", 0, 0, 0, 0, 1) + out += bytes([len(orders), restart]) + bytes(orders) + b"\0" * (128 - len(orders)) + out += b"M.K." if channels == 4 else (b"%dCHN" % channels if channels < 10 else b"%dCH" % channels) + for pat in patterns: + for row in pat: + for (note, ins, fx, param) in row: + p = mod_period(note) + out += bytes([(ins & 0xF0) | (p >> 8), p & 255, ((ins & 15) << 4) | fx, param]) + for s in samples: + out += s["data"] + return bytes(out) + + +# ---------------------------------------------------------------------------------------------- S3M +def write_s3m(title, samples, orders, patterns, channels, speed=6, tempo=125, gvol=64, mvol=48 | 128, pans=None, + flags=0, cwt=0x1320, chanset=None): + """samples: [{name, data (u8 bytes), volume, c2spd, loop: (start, end) | None}]; + patterns: [[row: [(note, ins, vol, cmd, info)] * channels] * 64] with note 0 = none, 254 = cut, else S3M byte + (octave << 4 | semitone); vol None = none; cmd 0 = none (A = 1).""" + ordn = list(orders) + [255] + if len(ordn) % 2: + ordn.append(255) + nins, npat = len(samples), len(patterns) + head = bytearray(name(title, 28) + bytes([0x1A, 16, 0, 0])) + head += struct.pack("> 16 + struct.pack_into(" the S3M note byte""" + n = note - 13 + return (n // 12) << 4 | (n % 12) + + +# ---------------------------------------------------------------------------------------------- XM +def env_bytes(points): + b = bytearray() + for (x, y) in points[:12]: + b += struct.pack("= 128 else b for b in raw] + else: + vals = [struct.unpack_from("= 8: + data.append(acc & 255) + acc >>= 8 + nbits -= 8 + if nbits: + data.append(acc & 255) + out += struct.pack("> 1 + while j & bit: + j ^= bit + bit >>= 1 + j |= bit + if i < j: + re[i], re[j] = re[j], re[i] + im[i], im[j] = im[j], im[i] + size = 2 + while size <= n: + ang = -2 * math.pi / size + wr, wi = math.cos(ang), math.sin(ang) + for start in range(0, n, size): + cr, ci = 1.0, 0.0 + half = size // 2 + for k in range(half): + a, b = start + k, start + k + half + tr = re[b] * cr - im[b] * ci + ti = re[b] * ci + im[b] * cr + re[b], im[b] = re[a] - tr, im[a] - ti + re[a], im[a] = re[a] + tr, im[a] + ti + cr, ci = cr * wr - ci * wi, cr * wi + ci * wr + size *= 2 + + +EDGES = [F_LO * (F_HI / F_LO) ** (j / BANDS) for j in range(BANDS + 1)] +WINDOW = [0.5 - 0.5 * math.cos(2 * math.pi * i / HOP) for i in range(HOP)] + + +def features(left, right): + """{frames, rmsL, rmsR, rmsM, bands (frames * BANDS magnitudes)} of a stereo signal""" + n = len(left) // HOP + out = {"frames": n, "rmsL": [], "rmsR": [], "rmsM": [], "bands": []} + for k in range(n): + o = k * HOP + L, R = left[o:o + HOP], right[o:o + HOP] + M = [(a + b) / 2 for a, b in zip(L, R)] + out["rmsL"].append(math.sqrt(sum(x * x for x in L) / HOP)) + out["rmsR"].append(math.sqrt(sum(x * x for x in R) / HOP)) + out["rmsM"].append(math.sqrt(sum(x * x for x in M) / HOP)) + re = [M[i] * WINDOW[i] for i in range(HOP)] + im = [0.0] * HOP + fft(re, im) + e = [0.0] * BANDS + for b in range(1, HOP // 2): + f = b * SR / HOP + if f < F_LO or f >= F_HI: + continue + j = min(BANDS - 1, int(math.log(f / F_LO) / math.log(F_HI / F_LO) * BANDS)) + e[j] += re[b] * re[b] + im[b] * im[b] + out["bands"] += [math.sqrt(x) for x in e] + return out + + +def duration(ctx, data, ext): + """openmpt123 --info's song length in seconds""" + with tempfile.TemporaryDirectory() as d: + p = os.path.join(d, "song." + ext) + with open(p, "wb") as f: + f.write(data) + info = ctx.nix("libopenmpt", ["openmpt123", "--info", p]).decode(errors="replace") + for line in info.splitlines(): + if line.startswith("Duration"): + secs = 0.0 + for part in line.split(":", 1)[1].strip().split(":"): + secs = secs * 60 + float(part) + return secs + raise RuntimeError("openmpt123 --info: no duration") + + +def reference(ctx, data, ext, extra=()): + left, right = openmpt(ctx, data, ext, extra) + f = features(left, right) + f["duration"] = duration(ctx, data, ext) + return f diff --git a/tools/fixtures/it.py b/tools/fixtures/it.py new file mode 100644 index 0000000..39ae6d6 --- /dev/null +++ b/tools/fixtures/it.py @@ -0,0 +1,186 @@ +# IT fixtures (tools/fixtures.py): generated Impulse Tracker modules exercising instruments (new note actions, +# duplicate checks, envelopes, filters, sustain loops, auto-vibrato, keymaps), sample mode with the IT effects, Amiga +# slides with old effects, and IT 2.14 / 2.15 compressed, 16-bit and stereo samples, rendered by openmpt123. +# tests/gen/it_cases.luau { name, data (the module), ref (features of openmpt's render, tools/fixtures/_tracker.py), +# duration (openmpt's song length), plain (for "compressed": the same song uncompressed) } +import os, sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import _tracker as T # noqa: E402 + +INPUTS = ["tools/fixtures/_tracker.py"] + +A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, Tt, U, V, W, X, Y, Z = range(1, 27) +OFF, CUT, FADE = 255, 254, 253 + + +def empty(ch, rows=64): + return [[(0, 0, None, 0, 0) for _ in range(ch)] for _ in range(rows)] + + +def put(p, row, ch, note=0, ins=0, vol=None, cmd=0, param=0): + p[row][ch] = (note, ins, vol, cmd, param) + + +def samples(compress=None): + return [ + {"name": "sine", "data": T.s8(T.synth("sine", 64, 64)), "volume": 64, "c5": 8363, "loop": (0, 64, False), "compress": compress}, + {"name": "square", "data": T.s8(T.synth("square", 64, 64, 0.5)), "volume": 48, "c5": 16726, "loop": (0, 64, False), "gv": 48}, + {"name": "saw16", "data": T.s16(T.synth("saw", 128, 64, 0.6)), "bits": 16, "volume": 64, "c5": 11025, "loop": (0, 128, False), + "compress": compress}, + {"name": "noise", "data": T.s8(T.synth("noise", 6000, 1, 0.7, decay=1500)), "volume": 60, "c5": 8363, "pan": 16}, + {"name": "ping sus", "data": T.s8(T.synth("tri", 400, 50, 0.8)), "volume": 64, "c5": 9000, "sus": (100, 300, True), + "loop": (0, 400, False), "vib": (8, 16, 4, 0)}, + {"name": "stereo", "data": T.s16(T.synth("sine", 256, 32, 0.6) + T.synth("saw", 256, 64, 0.5)), "bits": 16, "stereo": True, + "volume": 56, "c5": 8363, "loop": (0, 256, True), "compress": compress}, + {"name": "pluck", "data": T.s8(T.synth("saw", 3000, 40, 0.8, decay=900)), "volume": 64, "c5": 8363}, + ] + + +def keymap(sample, transpose=0, split=None): + km = [] + for n in range(120): + smp = sample if split is None or n < split[0] else split[1] + km.append((max(0, min(119, n + transpose)), smp)) + return km + + +def instruments(): + return [ + {"name": "nna cont", "nna": 1, "fadeout": 256, "keymap": keymap(7), + "volenv": {"points": [(0, 64), (10, 48), (40, 0)]}}, + {"name": "nna off", "nna": 2, "fadeout": 128, "keymap": keymap(1), + "volenv": {"points": [(0, 0), (3, 64), (8, 40), (20, 30)], "sustain": (2, 3)}}, + {"name": "nna fade dct", "nna": 3, "dct": 1, "dca": 0, "fadeout": 64, "keymap": keymap(2)}, + {"name": "pan pitch", "fadeout": 512, "keymap": keymap(3, 12), "pan": 48, "pps": 16, "ppc": 60, + "panenv": {"points": [(0, -32), (16, 32), (32, -32)], "loop": (0, 2)}, + "pitchenv": {"points": [(0, 0), (10, 12), (20, -12), (30, 0)], "loop": (1, 2)}}, + {"name": "filter", "keymap": keymap(3), "ifc": 128 + 40, "ifr": 128 + 64, "fadeout": 300, + "pitchenv": {"points": [(0, -32), (30, 32), (60, -32)], "loop": (0, 2), "filter": True}}, + {"name": "sus loop", "keymap": keymap(5), "fadeout": 400, "gbv": 96}, + {"name": "split stereo", "keymap": keymap(6, 0, (60, 1)), "fadeout": 200, + "volenv": {"points": [(0, 64), (5, 32), (10, 64), (15, 32)], "sustain": (0, 3), "loop": (1, 2)}}, + ] + + +def song_instruments(compress=None): + a, b = empty(5), empty(5) + # new note actions: continue / note off / fade, with the duplicate check cutting same-note repeats + for i, n in enumerate((61, 64, 68, 73)): + put(a, i * 4, 0, n, 1) + put(a, i * 4, 1, n - 12, 2) + put(a, 16, 1, 0, 0, None, S, 0x71) + put(a, 20, 1, 49, 2) + put(a, 22, 1, 0, 0, None, S, 0x73) + put(a, 24, 1, 56, 2) + put(a, 28, 1, OFF) + for r in (0, 4, 8, 9, 12, 16): + put(a, r, 2, 61 if r != 12 else 64, 3) + put(a, 20, 2, 0, 0, None, S, 0x70) + put(a, 24, 2, 61, 3, None, S, 0x75) + put(a, 26, 2, 66, 3) + put(a, 30, 2, FADE) + # panning / pitch envelopes, pitch-pan separation, instrument pan + put(a, 32, 0, 37, 4) + put(a, 32, 1, 61, 4) + put(a, 40, 1, 73, 4, None, S, 0x7B) + put(a, 44, 1, 0, 0, None, S, 0x7C) + put(a, 48, 0, OFF) + put(a, 56, 1, CUT) + # filters: instrument cutoff + resonance, filter envelope, Zxx + put(a, 36, 3, 49, 5) + put(a, 44, 3, 0, 0, None, Z, 0x20) + put(a, 48, 3, 0, 0, None, Z, 0x60) + put(a, 52, 3, 0, 0, None, Z, 0x88) + put(a, 60, 3, OFF) + # sustain loop + ping-pong, auto-vibrato, instrument global volume, a stereo / mono key split + put(b, 0, 0, 61, 6) + put(b, 16, 0, OFF) + put(b, 0, 1, 49, 7) + put(b, 8, 1, 73, 7) + put(b, 16, 1, 49, 7, 32) + put(b, 24, 1, OFF) + put(b, 32, 1, 85, 7) + put(b, 8, 4, 61, 1, None, H, 0x44) + put(b, 12, 4, 61, 1, None, S, 0x77) + put(b, 20, 4, 0, 0, None, S, 0x78) + put(b, 40, 4, 61, 3, 0, M, 0x20) + put(b, 44, 4, 0, 0, None, N, 0x04) + put(b, 48, 4, 0, 0, None, N, 0x30) + return T.write_it("instruments", samples(compress), instruments(), [0, 1], [a, b], 5, speed=5, tempo=135, + pans=[16, 48, 32, 32, 40], mv=64) + + +def song_effects(linear=True, old=False, compat=False): + a, b = empty(4), empty(4) + put(a, 0, 0, 61, 1, 48, D, 0x00) + put(a, 4, 0, 0, 0, 70) + put(a, 5, 0, 0, 0, 80) + put(a, 8, 0, 0, 0, 88) + put(a, 12, 0, 0, 0, 99) + put(a, 16, 0, 0, 0, 110) + put(a, 20, 0, 0, 0, 120) + put(a, 24, 0, 49, 0, 196) + put(a, 28, 0, 0, 0, 205, H, 0x46) + put(a, 32, 0, 0, 0, 160) + put(a, 36, 0, 0, 0, None, Y, 0x48) + put(a, 44, 0, 0, 0, None, P, 0x08) + put(a, 48, 0, 0, 0, None, P, 0x30) + put(a, 52, 0, 0, 0, None, P, 0xF4) + put(a, 56, 0, 0, 0, None, X, 0xC0) + put(a, 0, 1, 49, 2, None, E, 0x04) + put(a, 4, 1, 0, 0, None, F, 0x10) + put(a, 8, 1, 0, 0, None, E, 0xF8) + put(a, 9, 1, 0, 0, None, F, 0xE8) + put(a, 12, 1, 49, 2, None, G, 0x08) + put(a, 13, 1, 61, 0, None, G, 0x00) + put(a, 16, 1, 0, 0, None, E, 0x00) + put(a, 20, 1, 56, 2, None, J, 0x37) + put(a, 24, 1, 0, 0, None, U, 0x88) + put(a, 28, 1, 0, 0, None, R, 0x46) + put(a, 32, 1, 0, 0, None, I, 0x31) + put(a, 36, 1, 0, 0, None, Q, 0x84) + put(a, 40, 1, 0, 0, None, K, 0x02) + put(a, 44, 1, 49, 2, None, L, 0x20) + put(a, 48, 1, 0, 0, None, O, 0x00) + put(a, 52, 1, 61, 4, None, O, 0x04) + put(a, 56, 1, 61, 4, None, S, 0xD3) + put(a, 60, 1, 61, 4, None, S, 0xC2) + put(a, 0, 2, 37, 3, None, V, 0x60) + put(a, 8, 2, 0, 0, None, W, 0x04) + put(a, 16, 2, 0, 0, None, W, 0x60) + put(a, 24, 2, 0, 0, None, Tt, 0x10 + 0x06) + put(a, 28, 2, 0, 0, None, Tt, 0x04) + put(a, 32, 2, 0, 0, None, Tt, 0x90) + put(a, 36, 2, 0, 0, None, S, 0xB0) + put(a, 38, 2, 0, 0, None, S, 0xB1) + put(a, 40, 2, 0, 0, None, S, 0xE2) + put(a, 44, 2, 0, 0, None, S, 0x63) + put(a, 48, 2, 0, 0, None, A, 0x04) + put(a, 52, 2, 0, 0, None, M, 0x30) + put(a, 56, 2, 0, 0, None, N, 0x02) + put(a, 0, 3, 73, 7, None, S, 0x91) + put(a, 16, 3, 73, 7, None, X, 0x40) + put(a, 32, 3, 61, 3, None, S, 0x8C) + put(b, 0, 0, 61, 1) + put(b, 0, 1, 64, 2) + put(b, 0, 2, 68, 3) + put(b, 8, 0, CUT) + put(b, 12, 1, OFF) + put(b, 16, 2, FADE) + put(b, 20, 3, 61, 7, None, B, 0x01) + return T.write_it("effects", samples(), None, [0, 1], [a, b], 4, speed=4, tempo=140, linear=linear, old=old, + compat=compat, pans=[0, 64, 20, 44], vols=[64, 48, 64, 56], gv=112, mv=80) + + +def generate(ctx): + cases = [] + plain = song_instruments() + for nm, data in (("instruments", plain), ("effects", song_effects()), ("amiga old", song_effects(False, True, True)), + ("compressed 2.14", song_instruments(214)), ("compressed 2.15", song_instruments(215))): + ref = T.reference(ctx, data, "it") + c = {"name": nm, "data": data, "ref": ref, "duration": ref["duration"]} + if nm.startswith("compressed"): + c["plain"] = plain + cases.append(c) + ctx.emit("it_cases", cases) 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]}) diff --git a/tools/fixtures/mod.py b/tools/fixtures/mod.py new file mode 100644 index 0000000..6b63f81 --- /dev/null +++ b/tools/fixtures/mod.py @@ -0,0 +1,104 @@ +# MOD fixtures (tools/fixtures.py): generated ProTracker modules exercising the effects, rendered by openmpt123. +# tests/gen/mod_cases.luau { name, data (the module), ref (features of openmpt's render, tools/fixtures/_tracker.py), +# duration (openmpt's song length) } +import os, sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import _tracker as T # noqa: E402 + +INPUTS = ["tools/fixtures/_tracker.py"] + + +def empty(ch): + return [[(0, 0, 0, 0) for _ in range(ch)] for _ in range(64)] + + +def put(p, row, ch, note=0, ins=0, fx=0, param=0): + p[row][ch] = (note, ins, fx, param) + + +def samples(): + return [ + {"name": "sine", "data": T.s8(T.synth("sine", 64, 64)), "volume": 64, "loop": (0, 64)}, + {"name": "square", "data": T.s8(T.synth("square", 64, 64, 0.5)), "volume": 48, "loop": (0, 64)}, + {"name": "saw", "data": T.s8(T.synth("saw", 128, 64, 0.6)), "volume": 64, "loop": (64, 64)}, + {"name": "noise", "data": T.s8(T.synth("noise", 4000, 1, 0.7, decay=1200)), "volume": 64}, + {"name": "tri ft", "data": T.s8(T.synth("tri", 32, 32, 0.8)), "volume": 56, "finetune": 3, "loop": (0, 32)}, + ] + + +def song_basic(): + a, b = empty(4), empty(4) + mel = [49, 53, 56, 61, 56, 53, 51, 49] + for i in range(16): + put(a, i * 4, 0, mel[i % 8], 1) + put(a, i * 4, 1, 37 + (i % 4) * 2, 2, 0x0, 0x37 if i % 2 else 0) + put(a, 0, 2, 49, 3, 0x1, 0x02) + put(a, 16, 2, 0, 0, 0x2, 0x03) + put(a, 32, 2, 61, 3, 0xC, 0x30) + put(a, 33, 2, 0, 0, 0xA, 0x02) + put(a, 48, 2, 0, 0, 0xA, 0x40) + for r in range(0, 64, 8): + put(a, r, 3, 61, 4, 0xC, 0x40 - r // 2) + put(a, 60, 3, 61, 4, 0xE, 0xC2) + # pattern b: portamento, vibrato, tremolo, offsets, retrig, delay, fine slides, speed change, break + put(b, 0, 0, 49, 1) + put(b, 4, 0, 61, 0, 0x3, 0x08) + put(b, 8, 0, 0, 0, 0x3, 0x00) + put(b, 12, 0, 49, 0, 0x5, 0x02) + put(b, 16, 0, 56, 5, 0x4, 0x46) + put(b, 20, 0, 0, 0, 0x6, 0x01) + put(b, 24, 0, 0, 0, 0x4, 0x8F) + put(b, 0, 1, 37, 2, 0x7, 0x48) + put(b, 8, 1, 0, 0, 0x7, 0x00) + put(b, 16, 1, 44, 2, 0xE, 0x12) + put(b, 17, 1, 0, 0, 0xE, 0x12) + put(b, 20, 1, 0, 0, 0xE, 0x24) + put(b, 24, 1, 0, 0, 0xE, 0xB8) + put(b, 28, 1, 0, 0, 0xE, 0xA4) + put(b, 0, 3, 49, 4, 0x9, 0x08) + put(b, 8, 3, 49, 4, 0xE, 0x93) + put(b, 16, 3, 56, 4, 0xE, 0xD3) + put(b, 24, 2, 49, 3, 0xF, 0x03) + put(b, 32, 2, 51, 3, 0xF, 0x90) + put(b, 40, 2, 53, 3, 0xF, 0x06) + put(b, 40, 3, 61, 4, 0x9, 0x04) + put(b, 44, 0, 49, 5, 0xE, 0x53) + put(b, 48, 0, 0, 0, 0xD, 0x00) + return T.write_mod("basic", samples(), [0, 1], [a, b]) + + +def song_loops(): + a, b, c = empty(4), empty(4), empty(4) + put(a, 0, 0, 49, 1, 0xF, 0x04) + put(a, 4, 0, 0, 0, 0xE, 0x60) + put(a, 5, 1, 61, 2) + put(a, 8, 0, 53, 1, 0xE, 0x62) + put(a, 16, 0, 56, 1, 0xE, 0xE3) + put(a, 17, 2, 37, 3, 0xA, 0x01) + put(a, 32, 0, 0, 0, 0xD, 0x16) + put(b, 16, 0, 61, 1) + put(b, 20, 3, 49, 4, 0xF, 0x70) + put(b, 24, 0, 0, 0, 0xB, 0x02) + put(c, 0, 1, 50, 5) + put(c, 4, 1, 0, 0, 0xB, 0x01) + return T.write_mod("loops", samples(), [0, 1, 2], [a, b, c]) + + +def song_8ch(): + a = empty(8) + for ch in range(8): + put(a, ch * 2, ch, 37 + ch * 5, 1 + ch % 3, 0x8, ch * 32) + put(a, 32, 0, 61, 5, 0xE, 0x84) + put(a, 32, 7, 49, 4, 0x8, 0xFF) + put(a, 63, 0, 0, 0, 0xF, 0x00) + return T.write_mod("eight", samples(), [0], [a], channels=8) + + +def generate(ctx): + cases = [] + for nm, data in (("basic", song_basic()), ("loops", song_loops()), ("8ch", song_8ch())): + ref = T.reference(ctx, data, "mod") + cases.append({"name": nm, "data": data, "ref": ref, "duration": ref["duration"]}) + ctx.emit("mod_cases", cases) + diff --git a/tools/fixtures/s3m.py b/tools/fixtures/s3m.py new file mode 100644 index 0000000..17ea196 --- /dev/null +++ b/tools/fixtures/s3m.py @@ -0,0 +1,124 @@ +# S3M fixtures (tools/fixtures.py): generated Scream Tracker 3 modules exercising the effects, rendered by openmpt123. +# tests/gen/s3m_cases.luau { name, data (the module), ref (features of openmpt's render, tools/fixtures/_tracker.py), +# duration (openmpt's song length) } +import os, sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import _tracker as T # noqa: E402 + +INPUTS = ["tools/fixtures/_tracker.py"] + +A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, Tt, U, V, W, X, Y, Z = range(1, 27) + + +def empty(ch, rows=64): + return [[(0, 0, None, 0, 0) for _ in range(ch)] for _ in range(rows)] + + +def put(p, row, ch, note=0, ins=0, vol=None, cmd=0, info=0): + p[row][ch] = (T.s3m_note(note) if 0 < note < 254 else note, ins, vol, cmd, info) + + +def samples(): + return [ + {"name": "sine", "data": T.u8(T.synth("sine", 64, 64)), "volume": 64, "c2spd": 8363, "loop": (0, 64)}, + {"name": "square", "data": T.u8(T.synth("square", 64, 64, 0.5)), "volume": 40, "c2spd": 16726, "loop": (0, 64)}, + {"name": "saw", "data": T.u8(T.synth("saw", 100, 100, 0.6)), "volume": 64, "c2spd": 13000, "loop": (0, 100)}, + {"name": "noise", "data": T.u8(T.synth("noise", 6000, 1, 0.7, decay=1500)), "volume": 60, "c2spd": 8363}, + {"name": "tri", "data": T.u8(T.synth("tri", 50, 50, 0.8)), "volume": 50, "c2spd": 10000, "loop": (0, 50)}, + ] + + +def song_effects(keep=None): + """keep: debugging aid, a set of channels to keep (the others keep only their global effects)""" + a, b, c = empty(4), empty(4), empty(4) + mel = [61, 65, 68, 73, 68, 65, 63, 61] + for i in range(16): + put(a, i * 4, 0, mel[i % 8], 1, None, J if i % 4 == 1 else 0, 0x47 if i % 4 == 1 else 0) + put(a, 0, 1, 49, 2, 48) + put(a, 4, 1, 0, 0, None, D, 0x04) + put(a, 8, 1, 0, 0, None, D, 0x20) + put(a, 12, 1, 0, 0, None, D, 0xF2) + put(a, 13, 1, 0, 0, None, D, 0x3F) + put(a, 14, 1, 0, 0, None, D, 0x00) + put(a, 16, 1, 51, 2, None, E, 0x03) + put(a, 20, 1, 0, 0, None, F, 0x06) + put(a, 24, 1, 0, 0, None, E, 0xF4) + put(a, 25, 1, 0, 0, None, F, 0xE8) + put(a, 28, 1, 56, 2, None, H, 0x46) + put(a, 32, 1, 0, 0, None, U, 0x48) + put(a, 36, 1, 0, 0, None, K, 0x02) + put(a, 40, 1, 49, 2, None, G, 0x00) + put(a, 41, 1, 61, 0, None, G, 0x10) + put(a, 44, 1, 0, 0, None, L, 0x01) + put(a, 48, 1, 54, 2, None, R, 0x58) + put(a, 52, 1, 0, 0, None, I, 0x21) + put(a, 56, 1, 0, 0, None, X, 0x20) + put(a, 60, 1, 0, 0, None, S, 0x8C) + for r in range(0, 64, 8): + put(a, r, 3, 61, 4, 64 - r // 2) + put(a, 20, 3, 0, 0, None, O, 0x08) + put(a, 24, 3, 61, 4, None, Q, 0x83) + put(a, 32, 3, 61, 4, None, S, 0xC3) + put(a, 40, 3, 61, 4, None, S, 0xD2) + put(a, 48, 2, 37, 3, None, V, 0x30) + put(a, 56, 2, 0, 0, None, V, 0x40) + put(b, 0, 2, 49, 3, None, A, 0x04) + put(b, 4, 2, 0, 0, None, Tt, 0x90) + put(b, 8, 2, 52, 5, None, S, 0xB0) + put(b, 10, 0, 64, 1) + put(b, 12, 2, 0, 0, None, S, 0xB2) + put(b, 16, 2, 56, 5, None, S, 0xE2) + put(b, 20, 0, 61, 1, None, O, 0x00) + put(b, 24, 0, 254) + put(b, 28, 2, 0, 0, None, C, 0x08) + put(c, 8, 0, 49, 1, 32) + put(c, 12, 1, 61, 2, None, X, 0x80) + put(c, 16, 1, 0, 0, None, S, 0x82) + put(c, 20, 0, 0, 0, None, B, 0x05) + if keep is not None: # debugging: only some channels + for p in (a, b, c): + for row in p: + for ch in range(4): + if ch not in keep and row[ch][3] not in (A, B, C, Tt, V): + row[ch] = (0, 0, None, 0, 0) + return T.write_s3m("effects", samples(), [0, 1, 254, 2], [a, b, c], 4) + + +def song_memory(): + """ST3's shared effect memory, fast slides (ST3.00), the panning table, global volume, an order loop""" + a = empty(6) + put(a, 0, 0, 61, 1, None, D, 0x08) + put(a, 4, 0, 0, 0, None, E, 0x02) + put(a, 8, 0, 0, 0, None, D, 0x00) + put(a, 12, 0, 0, 0, None, F, 0x00) + put(a, 0, 1, 49, 3, None, D, 0x80) + put(a, 2, 1, 0, 0, None, D, 0x00) + put(a, 16, 2, 73, 5) + put(a, 20, 2, 0, 0, None, Q, 0x02) + put(a, 24, 2, 0, 0, None, Q, 0x00) + put(a, 28, 3, 56, 2, 20) + put(a, 28, 4, 63, 1, 30) + put(a, 32, 5, 37, 3, None, X, 0x00) + put(a, 40, 5, 0, 0, None, S, 0xE3) + put(a, 48, 0, 0, 0, None, V, 0x20) + put(a, 63, 0, 0, 0, None, B, 0x00) + return T.write_s3m("memory", samples(), [0], [a], 6, speed=5, tempo=140, cwt=0x1300, + pans=[2, 13, 5, 10, 7, 15], mvol=64 | 128, gvol=48) + + +def song_mono(): + a = empty(2) + put(a, 0, 0, 61, 1) + put(a, 8, 1, 68, 2) + put(a, 16, 0, 0, 0, None, H, 0x28) + put(a, 32, 1, 0, 0, None, F, 0x10) + return T.write_s3m("mono", samples(), [0], [a], 2, mvol=32) + + +def generate(ctx): + cases = [] + for nm, data in (("effects", song_effects()), ("memory", song_memory()), ("mono", song_mono())): + ref = T.reference(ctx, data, "s3m") + cases.append({"name": nm, "data": data, "ref": ref, "duration": ref["duration"]}) + ctx.emit("s3m_cases", cases) diff --git a/tools/fixtures/sf2.py b/tools/fixtures/sf2.py new file mode 100644 index 0000000..638d874 --- /dev/null +++ b/tools/fixtures/sf2.py @@ -0,0 +1,227 @@ +# SoundFont fixtures (tools/fixtures.py): a small self-made SF2 (band-limited sine / saw / square loops + a noise +# burst; melodic presets with envelopes, a filter + mod envelope, vibrato, a preset global zone, an instrument global +# zone, a drum kit on bank 128 with exclusive classes), a 12.5 s test song (SMF written here) that plays each preset in +# its own 2 s segment (chords, pitch bend with an RPN 0 range of 12, sustain pedal, CC7 / CC11), the song rendered by +# FluidSynth (nixpkgs#fluidsynth, reverb and chorus off) and analysed with numpy (tools/fixtures/_sf2_features.py): +# tests/gen/sf2_cases.luau { sf2, sf2_24 (the same with an sm24 chunk), song, fluid = { env, bands, peaks }, +# expect = { presets, samples, instruments, info, values } } +import json, math, os, random, struct, subprocess, tempfile + +INPUTS = ["tools/fixtures/_sf2_features.py"] +RATE = 44100 +PERIOD = 100 # 441 Hz loops +CYCLES = 50 + + +def tc(sec): + return int(round(1200 * math.log2(sec))) + + +def hz_cents(hz): + return int(round(1200 * math.log2(hz / 8.176))) + + +def wave(kind, rng): + n = PERIOD * CYCLES + out = [] + for i in range(n): + ph = 2 * math.pi * i / PERIOD + if kind == "sine": + v = math.sin(ph) * 0.8 + elif kind == "saw": + v = sum(math.sin(k * ph) / k for k in range(1, 50)) * 0.45 + else: + v = sum(math.sin(k * ph) / k for k in range(1, 50, 2)) * 0.6 + out.append(v) + return out + + +def chunk(cid, data): + pad = b"\x00" if len(data) % 2 else b"" + return cid + struct.pack("> 8, x & 255 + pcm += struct.pack(" root 69, correction -4 makes it play 440 Hz-ish at key 69 + headers.append((name, start, end, start, end, RATE, 69, -4, 0, 1)) + if len(pcm24) % 2: + pcm24 += b"\x00" + info = lst(b"INFO", [chunk(b"ifil", struct.pack(">= 7 + while v: + out.insert(0, (v & 127) | 128) + v >>= 7 + return bytes(out) + + +def song(): + tpq, us = 480, 500000 # 1 beat = 0.5 s + ev = [] # (seconds, bytes) + + def at(sec, *b): + ev.append((sec, bytes(b))) + at(0, 0xC0, 0) + at(0, 0xC1, 1) + at(0, 0xC2, 2) + # seg 0: a sine chord + for n in (60, 64, 67): + at(0.0, 0x90, n, 127) + at(1.5, 0x80, n, 0) + # seg 1: a saw melody (filter + mod env) + for k, n in enumerate((48, 52, 55, 60)): + at(2.0 + 0.4 * k, 0x91, n, 127) + at(2.35 + 0.4 * k, 0x81, n, 0) + # seg 2: a square with vibrato + at(4.0, 0x92, 69, 127) + at(5.5, 0x82, 69, 0) + # seg 3: drums (hats cut each other: exclusive class) + for sec, n in ((6.0, 36), (6.25, 42), (6.5, 38), (6.75, 42), (7.0, 46), (7.25, 42), (7.5, 36)): + at(sec, 0x99, n, 127) + at(sec + 0.1, 0x89, n, 0) + # seg 4: sine with a pitch-bend range of 12 (RPN 0), a bend up an octave, the sustain pedal + at(7.9, 0xB0, 101, 0) + at(7.9, 0xB0, 100, 0) + at(7.9, 0xB0, 6, 12) + at(8.0, 0x90, 72, 127) + at(8.5, 0xE0, 0x7F, 0x7F) + at(9.0, 0xE0, 0x00, 0x40) + at(9.1, 0xB0, 64, 127) + at(9.2, 0x80, 72, 0) + at(9.6, 0xB0, 64, 0) + # seg 5: saw with volume and expression changes + at(10.0, 0x91, 57, 127) + at(10.75, 0xB1, 7, 60) + at(11.25, 0xB1, 11, 64) + at(11.6, 0x81, 57, 0) + ev.sort(key=lambda e: e[0]) + body, last = bytearray(), 0 + body += b"\x00\xff\x51\x03" + struct.pack(">I", us)[1:] + for sec, b in ev: + tick = int(round(sec * tpq * 1e6 / us)) + body += vlq(tick - last) + b + last = tick + end = int(round(12.5 * tpq * 1e6 / us)) + body += vlq(end - last) + b"\xff\x2f\x00" + return b"MThd" + struct.pack(">IHHH", 6, 0, 1, tpq) + b"MTrk" + struct.pack(">I", len(body)) + bytes(body) + + +def generate(ctx): + sf2, expect = build_sf2(False) + sf2_24, _ = build_sf2(True) + mid = song() + with tempfile.TemporaryDirectory() as d: + fp, mp, wp = os.path.join(d, "t.sf2"), os.path.join(d, "t.mid"), os.path.join(d, "t.wav") + with open(fp, "wb") as f: + f.write(sf2) + with open(mp, "wb") as f: + f.write(mid) + ctx.nix("fluidsynth", ["fluidsynth", "-ni", "-q", "-R", "0", "-C", "0", "-g", "0.5", "-r", "44100", "-F", wp, fp, mp]) + with open(wp, "rb") as f: + wav = f.read() + fluid = json.loads(ctx.python(["numpy"], ctx.read("tools/fixtures/_sf2_features.py").decode(), input=wav)) + ctx.emit("sf2_cases", {"sf2": sf2, "sf2_24": sf2_24, "song": mid, "fluid": fluid, "expect": expect}) diff --git a/tools/fixtures/xm.py b/tools/fixtures/xm.py new file mode 100644 index 0000000..fd40898 --- /dev/null +++ b/tools/fixtures/xm.py @@ -0,0 +1,161 @@ +# XM fixtures (tools/fixtures.py): generated FastTracker 2 modules exercising instruments (envelopes, fadeout, +# auto-vibrato, keymaps, 16-bit and ping-pong samples) and the effects, rendered by openmpt123. +# tests/gen/xm_cases.luau { name, data (the module), ref (features of openmpt's render, tools/fixtures/_tracker.py), +# duration (openmpt's song length) } +import os, sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import _tracker as T # noqa: E402 + +INPUTS = ["tools/fixtures/_tracker.py"] + +OFF = 97 +Gx, Hx, Kx, Lx, Px, Rx, Tx, Xx = 16, 17, 20, 21, 25, 27, 29, 33 + + +def empty(ch, rows=64): + return [[(0, 0, 0, 0, 0) for _ in range(ch)] for _ in range(rows)] + + +def put(p, row, ch, note=0, ins=0, vol=0, fx=0, param=0): + p[row][ch] = (note, ins, vol, fx, param) + + +def instruments(): + sine = {"name": "sine", "data": T.s8(T.synth("sine", 64, 64)), "volume": 64, "pan": 128, "loop": (0, 64, 1)} + tri = {"name": "tri", "data": T.s8(T.synth("tri", 32, 32, 0.8)), "volume": 48, "pan": 96, "relnote": 12, "finetune": -20, + "loop": (0, 32, 1)} + saw16 = {"name": "saw16", "data": T.s16(T.synth("saw", 128, 64, 0.6)), "bits": 16, "volume": 56, "pan": 160, + "loop": (0, 128, 1)} + ping = {"name": "ping", "data": T.s8(T.synth("saw", 200, 200, 0.7)), "volume": 64, "pan": 128, "finetune": 30, + "loop": (20, 150, 2)} + noise = {"name": "noise", "data": T.s8(T.synth("noise", 5000, 1, 0.7, decay=1500)), "volume": 60, "pan": 128} + square = {"name": "square", "data": T.s8(T.synth("square", 64, 64, 0.5)), "volume": 64, "pan": 128, "loop": (0, 64, 1)} + return [ + {"name": "env", "samples": [sine], "volenv": {"points": [(0, 0), (4, 64), (10, 40), (30, 20), (40, 0)], "sustain": 2}, + "fadeout": 1024}, + {"name": "panloop", "samples": [square], "panenv": {"points": [(0, 0), (8, 64), (16, 0)], "loop": (0, 2)}, + "volenv": {"points": [(0, 64), (20, 48), (60, 32)], "loop": (1, 2)}, "fadeout": 512}, + {"name": "autovib", "samples": [saw16], "vib": (0, 10, 8, 6)}, + {"name": "multi", "samples": [sine, tri], "keymap": [0] * 48 + [1] * 48}, + {"name": "ping", "samples": [ping]}, + {"name": "noise", "samples": [noise]}, + {"name": "sq vib", "samples": [square], "vib": (1, 0, 4, 20)}, + {"name": "empty"}, + ] + + +def song_instruments(): + a, b = empty(4), empty(4) + put(a, 0, 0, 49, 1) + put(a, 12, 0, OFF) + put(a, 20, 0, 56, 1) + put(a, 24, 0, 0, 0, 0, Kx, 3) + put(a, 32, 0, 61, 1) + put(a, 33, 0, 0, 0, 0, Lx, 20) + put(a, 40, 0, 63) + put(a, 44, 0, OFF) + put(a, 48, 0, 0, 1) + put(a, 0, 1, 37, 2) + put(a, 30, 1, OFF) + put(a, 40, 1, 44, 2) + put(a, 0, 2, 49, 3) + put(a, 32, 2, 56, 3) + put(a, 8, 3, 37, 4) + put(a, 16, 3, 61, 4) + put(a, 24, 3, 73, 4) + put(a, 32, 3, 85, 4) + put(a, 40, 3, 49, 5) + put(a, 52, 3, 61, 5) + put(a, 60, 3, 61, 8) + put(b, 0, 0, 49, 7) + put(b, 0, 1, 56, 3, 0x30) + put(b, 8, 1, 0, 3) + put(b, 16, 2, 61, 6, 0x40) + put(b, 20, 2, 61, 6, 0, 0x9, 0x08) + put(b, 24, 2, 61, 6, 0, 0xE, 0x93) + put(b, 32, 3, 49, 1) + put(b, 36, 3, 61) + put(b, 40, 3, OFF) + put(b, 44, 3, 63) + put(b, 48, 0, 0, 0, 0, 0xD, 0x00) + return T.write_xm("instruments", instruments(), [0, 1], [a, b], 4) + + +def song_effects(linear=True): + a, b = empty(6), empty(6, 48) + put(a, 0, 0, 49, 7, 0, 0x1, 0x04) + put(a, 4, 0, 0, 0, 0, 0x1, 0x00) + put(a, 8, 0, 0, 0, 0, 0x2, 0x08) + put(a, 12, 0, 0, 0, 0, 0xE, 0x18) + put(a, 13, 0, 0, 0, 0, 0xE, 0x10) + put(a, 14, 0, 0, 0, 0, 0xE, 0x2F) + put(a, 16, 0, 0, 0, 0, Xx, 0x1F) + put(a, 17, 0, 0, 0, 0, Xx, 0x10) + put(a, 18, 0, 0, 0, 0, Xx, 0x28) + put(a, 20, 0, 49, 7, 0, 0x3, 0x10) + put(a, 21, 0, 61, 0, 0, 0x3, 0x00) + put(a, 24, 0, 0, 0, 0, 0x5, 0x02) + put(a, 28, 0, 56, 0, 0, 0x4, 0x48) + put(a, 32, 0, 0, 0, 0, 0x6, 0x20) + put(a, 36, 0, 0, 0, 0, 0x7, 0x6F) + put(a, 40, 0, 0, 0, 0, Tx, 0x21) + put(a, 44, 0, 0, 0, 0, 0xA, 0x0F) + put(a, 46, 0, 0, 0, 0, 0xE, 0xA8) + put(a, 48, 0, 61, 7, 0, 0x0, 0x37) + put(a, 52, 0, 0, 0, 0, 0xE, 0xC3) + # channel 1: the volume column + put(a, 0, 1, 56, 6, 0x30) + put(a, 4, 1, 0, 0, 0x64) + put(a, 8, 1, 0, 0, 0x73) + put(a, 12, 1, 0, 0, 0x85) + put(a, 13, 1, 0, 0, 0x9A) + put(a, 16, 1, 0, 0, 0xA6) + put(a, 17, 1, 0, 0, 0xB8) + put(a, 24, 1, 0, 0, 0xC2) + put(a, 28, 1, 0, 0, 0xE4) + put(a, 32, 1, 0, 0, 0xD6) + put(a, 36, 1, 61, 0, 0xF8) + put(a, 40, 1, 49, 0, 0xF0) + # channel 2: panning, retrig, offset, delay + put(a, 0, 2, 61, 2, 0, 0x8, 0x20) + put(a, 8, 2, 0, 0, 0, Px, 0x30) + put(a, 16, 2, 0, 0, 0, Px, 0x06) + put(a, 24, 2, 61, 6, 0, Rx, 0x83) + put(a, 32, 2, 61, 6, 0, Rx, 0x32) + put(a, 40, 2, 61, 6, 0, 0x9, 0x06) + put(a, 48, 2, 61, 6, 0, 0xE, 0xD3) + put(a, 56, 2, 61, 6, 0x20, 0xE, 0xC2) + # channel 3: global volume, pattern loop, pattern delay, speed / tempo + put(a, 0, 3, 37, 3, 0, Gx, 0x30) + put(a, 8, 3, 0, 0, 0, Hx, 0x02) + put(a, 16, 3, 0, 0, 0, Hx, 0x40) + put(a, 24, 3, 0, 0, 0, 0xE, 0x60) + put(a, 26, 3, 0, 0, 0, 0xE, 0x62) + put(a, 32, 3, 0, 0, 0, 0xE, 0xE2) + put(a, 40, 3, 0, 0, 0, 0xF, 0x05) + put(a, 48, 3, 0, 0, 0, 0xF, 0x96) + # channel 4 / 5: an instrument change without a note, an empty instrument, a note after key off + put(a, 0, 4, 49, 1) + put(a, 8, 4, 0, 2) + put(a, 16, 4, OFF) + put(a, 24, 4, 51) + put(a, 32, 4, 51, 8) + put(a, 40, 4, 53, 1) + put(a, 4, 5, 73, 5, 0, 0xE, 0x80) + put(a, 20, 5, 0, 0, 0, 0x8, 0xC0) + # pattern b (48 rows): portamento in the other direction, arpeggio, a break and a jump back (song loop) + put(b, 0, 0, 73, 7, 0, 0x4, 0x00) + put(b, 0, 1, 61, 4) + put(b, 4, 1, 0, 0, 0, 0x0, 0x47) + put(b, 16, 1, 25, 4, 0, 0x2, 0x10) + put(b, 32, 0, 0, 0, 0, 0xB, 0x01) + return T.write_xm("effects", instruments(), [0, 1], [a, b], 6, speed=5, tempo=130, linear=linear, restart=1) + + +def generate(ctx): + cases = [] + for nm, data in (("instruments", song_instruments()), ("effects", song_effects()), ("amiga", song_effects(False))): + ref = T.reference(ctx, data, "xm") + cases.append({"name": nm, "data": data, "ref": ref, "duration": ref["duration"]}) + ctx.emit("xm_cases", cases)