From 7754646a86f585a4c124ce6106814fc7b04e2ecf Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:31:34 -0500 Subject: [PATCH] ws-music: music/it read + render (IT 2.14/2.15 decompression, NNA, filters, pitch-pan, OpenMPT note-fade coding), tracker tests tightened, MOD->XM + API checks, tracker bench lines, NOTICE --- docs/FORMATS.md | 1 + licenses/NOTICE.md | 2 + src/Formats/Registry.luau | 12 + src/Formats/codecs/Tracker/Player.luau | 51 ++- src/Formats/codecs/Tracker/init.luau | 15 +- src/Formats/music/it/Itsex.luau | 120 +++++++ src/Formats/music/it/init.luau | 427 +++++++++++++++++++++++++ tests/music/it.luau | 84 +++++ tests/music/mod.luau | 30 +- tests/music/s3m.luau | 2 +- tests/music/xm.luau | 2 +- tools/bench.luau | 56 ++++ tools/fixtures/_tracker.py | 4 +- tools/fixtures/it.py | 186 +++++++++++ 14 files changed, 964 insertions(+), 28 deletions(-) create mode 100644 src/Formats/music/it/Itsex.luau create mode 100644 src/Formats/music/it/init.luau create mode 100644 tests/music/it.luau create mode 100644 tools/fixtures/it.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 5ddcb80..3eb4e52 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -6,6 +6,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | Category | Format | Extensions | Read | Write | Capabilities | Test | |---|---|---|---|---|---|---| | image | png | .png .apng | yes | yes | animation: false, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.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` | diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index b69b7e3..3fd365c 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -5,6 +5,8 @@ | `src/Formats/codecs/Deflate/` (Inflate, init), `src/Formats/core/Crc32.luau`, `src/Formats/core/Adler32.luau`, `src/Formats/core/Huffman.luau` (table builder) | deflate-luau 1.0.0 (same author), written from RFC 1950-1952 | no licence chosen yet; no third-party code: [deflate-luau-NOTICE.txt](deflate-luau-NOTICE.txt) | | `src/Formats/image/png/` (init, Decode) | png-luau 1.0.0 (same author), written from the PNG specification | no licence chosen yet; no third-party code | | `tests/fixtures/pngsuite/` | PngSuite by Willem van Schaik | [PngSuite-LICENSE.txt](PngSuite-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 diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 65f9734..6df5929 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -26,6 +26,18 @@ local list: { Entry } = { return require("@formats/image/png") 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", diff --git a/src/Formats/codecs/Tracker/Player.luau b/src/Formats/codecs/Tracker/Player.luau index bf0742d..84d2079 100644 --- a/src/Formats/codecs/Tracker/Player.luau +++ b/src/Formats/codecs/Tracker/Player.luau @@ -102,6 +102,7 @@ local function newChannel(i: number, pan: number, vol: number): any smp = nil :: any, vol = 0, pan = pan, + basePan = pan, chanVol = vol, period = 0, target = 0, @@ -220,6 +221,7 @@ function Player.new(m: any, sampleRate: number, opts: any): any 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 @@ -238,10 +240,8 @@ 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 then - return 0.5 * (m.mixVolume or 48) / 48 - elseif fmt == S3M then - return (m.mixVolume or 48) / 128 -- OpenMPT: linear in the master volume, 64 = 0.5 + 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 @@ -557,16 +557,21 @@ end local function setInstrumentDefaults(st: any, c: any, smp: any, ins: any) if smp then c.vol = smp.volume - if smp.pan then - c.pan = smp.pan + 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.pan and not (smp and smp.pan) then - c.pan = ins.pan - c.surround = false - end if ins.cutoff then c.cutoff = ins.cutoff end @@ -615,7 +620,6 @@ local function trigger(st: any, c: any, note: number, insIdx: number, vcmd: numb if insIdx > 0 then local valid = if st.insMode then m.instruments[insIdx] ~= nil else m.samples[insIdx] ~= nil if valid then - local prev = c.insIdx 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) @@ -673,6 +677,7 @@ local function trigger(st: any, c: any, note: number, insIdx: number, vcmd: numb 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 @@ -724,6 +729,7 @@ local function trigger(st: any, c: any, note: number, insIdx: number, vcmd: numb 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 @@ -731,6 +737,7 @@ local function trigger(st: any, c: any, note: number, insIdx: number, vcmd: numb c.vol = v elseif v >= 128 and v <= 192 then c.pan = (v - 128) * 4 + c.basePan = c.pan c.surround = false end end @@ -748,7 +755,7 @@ local function volSlideMod(c: any, param: number) end local function tonePorta(st: any, c: any, speed: number) - if c.target == 0 or c.period == c.target then + if c.period == c.target then return end if c.period < c.target then @@ -874,6 +881,7 @@ local function fxModXm(st: any, c: any, tick: number) elseif fx == 8 then if tick == 0 then c.pan = param + c.basePan = c.pan c.surround = false end elseif fx == 0xB then @@ -935,6 +943,7 @@ local function fxModXm(st: any, c: any, tick: number) 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 @@ -1011,8 +1020,10 @@ local function fxModXm(st: any, c: any, tick: number) 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 @@ -1115,10 +1126,12 @@ local function volColXm(st: any, c: any, tick: number) 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 @@ -1230,6 +1243,7 @@ local function fxS3mIt(st: any, c: any, tick: number) 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) @@ -1308,6 +1322,7 @@ local function fxS3mIt(st: any, c: any, tick: number) elseif x == 8 then if tick == 0 then c.pan = y * 17 + c.basePan = c.pan c.surround = false end elseif x == 9 then @@ -1382,9 +1397,11 @@ local function fxS3mIt(st: any, c: any, tick: number) 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 @@ -1753,13 +1770,13 @@ local function updateVoice(st: any, v: any) 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 - if it and ins and (ins.pps or 0) ~= 0 then - pan += (v.note - (ins.ppc or 60) - 1) * ins.pps / 2 - end pan = clamp(pan, 0, 256) pan = clamp(128 + (pan - 128) * st.separation, 0, 256) local g = vol * st.master @@ -1854,8 +1871,8 @@ function Player.tick(st: any): number updateVoice(st, v) end end - -- frames for this tick: 2.5 / tempo seconds, rounded per tick as OpenMPT / FT2 do - local frames = floor(st.sr * 2.5 / max(1, st.tempo) + 0.5) + -- 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 diff --git a/src/Formats/codecs/Tracker/init.luau b/src/Formats/codecs/Tracker/init.luau index 8412ef1..391ea94 100644 --- a/src/Formats/codecs/Tracker/init.luau +++ b/src/Formats/codecs/Tracker/init.luau @@ -70,6 +70,7 @@ export type Envelope = { 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 } @@ -262,12 +263,14 @@ local function fixEnvelope(e: any): (any, string?) return e end -local function fixLoop(s: number, e: number, t: number, len: number): (number, number, number) - if not num(t, 0, 2) or t == 0 then +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 - s, e = math.floor(math.clamp(s, 0, len)), math.floor(math.clamp(e, 0, len)) - if e - s < 1 then + 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 @@ -378,7 +381,7 @@ function Tracker.validate(m: any): (boolean?, Err.Err?) ins.resonance = nil end end - return true + return true, nil end -- ------------------------------------------------------------------------------------------------ rendering @@ -402,7 +405,7 @@ function Tracker.duration(m: any, opts: RenderOptions?): (number?, Err.Err?) end frames += f end - return math.min(frames, maxFrames) / sr + return math.min(frames, maxFrames) / sr, nil end local function newPlayer(self: any) 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/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/mod.luau b/tests/music/mod.luau index 30935ae..84500de 100644 --- a/tests/music/mod.luau +++ b/tests/music/mod.luau @@ -18,7 +18,7 @@ local function load(data: string): any return Mod.decode(Bytes.reader(buffer.fromstring(data))) end -local THRESH = { gainDb = 1.0, envErr = 1.0, spectral = 0.93, balance = 0.05, duration = 0.01 } +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) @@ -47,6 +47,34 @@ for _, c in Cases do 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) diff --git a/tests/music/s3m.luau b/tests/music/s3m.luau index 989ca30..ddff1a5 100644 --- a/tests/music/s3m.luau +++ b/tests/music/s3m.luau @@ -18,7 +18,7 @@ local function load(data: string): any return S3m.decode(Bytes.reader(buffer.fromstring(data))) end -local THRESH = { gainDb = 1.0, envErr = 1.0, spectral = 0.93, balance = 0.05, duration = 0.01 } +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) diff --git a/tests/music/xm.luau b/tests/music/xm.luau index 2e47118..b117848 100644 --- a/tests/music/xm.luau +++ b/tests/music/xm.luau @@ -18,7 +18,7 @@ local function load(data: string): any return Xm.decode(Bytes.reader(buffer.fromstring(data))) end -local THRESH = { gainDb = 1.0, envErr = 1.0, spectral = 0.93, balance = 0.05, duration = 0.01 } +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) diff --git a/tools/bench.luau b/tools/bench.luau index a353be8..0304171 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -116,3 +116,59 @@ do 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/_tracker.py b/tools/fixtures/_tracker.py index 482955d..eeef247 100644 --- a/tools/fixtures/_tracker.py +++ b/tools/fixtures/_tracker.py @@ -305,7 +305,7 @@ def write_it(title, samples, instruments, orders, patterns, channels, speed=6, t instruments: None (sample mode) or [{name, nna, dct, dca, fadeout, gbv, pan | None, pps, ppc, ifc, ifr, keymap: [(note, sample)] * 120, volenv / panenv / pitchenv: {points [(tick, value)], loop, sustain, filter}}]; patterns: [[row: [(note, ins, vol, cmd, param)] * channels]] with note 0 = none else IT note + 1 (1 = C-0) or - 255 / 254 / 253; vol None or the raw volume byte; cmd 0 = none (A = 1).""" + 255 off / 254 cut / 253 fade (stored as 246, like IT); vol None or the raw volume byte; cmd 0 = none (A = 1).""" ins_list = instruments or [] ordn = list(orders) + [255] flags = 1 | (4 if instruments else 0) | (8 if linear else 0) | (16 if old else 0) | (32 if compat else 0) @@ -351,7 +351,7 @@ def write_it(title, samples, instruments, orders, patterns, channels, speed=6, t if mask: pk += bytes([(ch + 1) | 128, mask]) if note: - pk.append(note - 1 if note < 253 else note) + pk.append(note - 1 if note < 253 else (246 if note == 253 else note)) if ins: pk.append(ins) if vol is not None: 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)