--!strict -- ops/MusicOps: building and editing tracker Modules (layer 5.5, over codecs/audio/Tracker) without touching the -- engine's internal layout (5-byte cells, f32 sample buffers, tuning fields): a new module, patterns, cells by name, -- samples from an Audio, instruments. New code. F.music.new / addPattern / setCell / getCell / addSample / -- addInstrument / note in the api (also F.ops.music). -- -- local M = require("@formats/ops/MusicOps") -- local song = M.new({ format = "mod", channels = 4, title = "demo" }) -- local s = M.addSample(song, { name = "beep", audio = someAudio, loop = "forward" }) -- sample 1 -- local p = M.addPattern(song) -- pattern 0 (64 rows), appended to the order list -- M.setCell(song, p, 0, 1, { note = "C-4", instrument = s, effect = 0xC, param = 40 }) -- local wav = F.save(song, nil, { format = "wav" }) -- rendered; or F.save(song) for the .mod -- -- Conventions: pattern numbers are 0-based (as the order list names them), rows 0-based, channels 1-based, sample -- and instrument numbers 1-based (0 = none in a cell). Notes are numbers (1 = C-0, 49 = C-4, 61 = C-5; 254 cut, 255 -- key off, 253 fade) or names: "C-4", "C#4", "Db4", "off", "cut", "fade". Effects keep the format's own numbering -- (MOD / XM 0..35, S3M / IT 1..26 = A..Z). Never throws: bad arguments return nil, Err.ARG. local Err = require("@formats/core/Err") local Tracker = require("@formats/codecs/audio/Tracker") local MusicOps = {} local FORMATS = { mod = true, xm = true, s3m = true, it = true } local function bad(what: string): (nil, Err.Err) return nil, Err.new(Err.ARG, what) end local function isModule(m: any): boolean return type(m) == "table" and m.kind == "music" and FORMATS[m.format] == true and type(m.patterns) == "table" end local function int(v: any, lo: number, hi: number): boolean return type(v) == "number" and v == v and v % 1 == 0 and v >= lo and v <= hi end -- ------------------------------------------------------------------------------------------------ module export type NewOptions = { format: string?, -- "mod" (default), "xm", "s3m", "it": the effect family (mod and xm can be saved) channels: number?, -- 1..32 for mod, else 1..64 (default 4) title: string?, speed: number?, -- ticks per row (default 6) tempo: number?, -- BPM (default 125) } -- new(opts?) -> an empty Module (kind "music") with a render method; meta.source.format = the format function MusicOps.new(opts: NewOptions?): (any, Err.Err?) local o: NewOptions = opts or {} local format = o.format or "mod" if not FORMATS[format] then return bad("new: format must be mod, xm, s3m or it") end local channels = o.channels or 4 if not int(channels, 1, if format == "mod" then 32 else 64) then return bad("new: bad channel count") end local m = Tracker.newModule(format, channels) m.title = if type(o.title) == "string" then o.title else "" if o.speed ~= nil then if not int(o.speed, 1, 255) then return bad("new: speed must be 1..255") end m.speed = o.speed end if o.tempo ~= nil then if type(o.tempo) ~= "number" or o.tempo < 32 or o.tempo > 1000 then return bad("new: tempo must be 32..1000") end m.tempo = o.tempo end m.meta = { source = { format = format } } return m, nil end -- ------------------------------------------------------------------------------------------------ patterns -- addPattern(module, rows?, opts?) -> the new pattern's number (0-based) | nil, Err. rows default 64 (MOD needs 64). -- The pattern is appended to the order list unless opts.order == false. function MusicOps.addPattern(m: any, rows: number?, opts: { order: boolean? }?): (number?, Err.Err?) if not isModule(m) then return bad("addPattern: needs a tracker Module") end local n = rows or 64 if not int(n, 1, 1024) then return bad("addPattern: rows must be 1..1024") end table.insert(m.patterns, Tracker.newPattern(n, m.channels)) local index = #m.patterns - 1 if not (opts and opts.order == false) then table.insert(m.order, index) end return index, nil end local NAMES: { [string]: number } = { c = 0, d = 2, e = 4, f = 5, g = 7, a = 9, b = 11 } local SPECIAL: { [string]: number } = { off = 255, ["==="] = 255, cut = 254, ["^^^"] = 254, fade = 253, ["~~~"] = 253 } -- note(nameOrNumber) -> the note number (1 = C-0 .. 120 = B-9, 253 / 254 / 255) | nil, Err: "C-4" = 49, "C#4" = 50, -- "Db4" = 50, "off", "cut", "fade" function MusicOps.note(v: any): (number?, Err.Err?) if type(v) == "number" then if int(v, 0, 120) or v == 253 or v == 254 or v == 255 then return v, nil end return bad("note: number must be 0..120 or 253..255") end if type(v) ~= "string" then return bad("note: expected a number or a name") end local s = string.lower(v) if SPECIAL[s] then return SPECIAL[s], nil end local letter, acc, oct = string.match(s, "^([a-g])([#b%-]?)(%d)$") if not letter then return bad("note: bad name " .. v) end local n = NAMES[letter :: string] + (if acc == "#" then 1 elseif acc == "b" then -1 else 0) local num = 1 + (tonumber(oct) :: number) * 12 + n if num < 1 or num > 120 then return bad("note: out of range " .. v) end return num, nil end export type Cell = { note: (number | string)?, -- 0 / nil = none instrument: number?, -- 1-based sample (MOD / S3M) or instrument (XM / IT); 0 = none volume: number?, -- the volume column as the format stores it (0 = none) effect: number?, -- the format's effect number (MOD / XM 0..35; S3M / IT 1..26) param: number?, -- 0..255 } local function patternAt(m: any, pattern: any, row: any, channel: any): (any, Err.Err?) if not isModule(m) then return bad("needs a tracker Module") end local p: any = if int(pattern, 0, 1e6) then m.patterns[pattern + 1] else nil if p == nil then return bad("no pattern " .. tostring(pattern)) end if not int(row, 0, p.rows - 1) then return bad("row " .. tostring(row) .. " outside 0.." .. (p.rows - 1)) end if not int(channel, 1, m.channels) then return bad("channel " .. tostring(channel) .. " outside 1.." .. m.channels) end return p, nil end -- setCell(module, pattern, row, channel, cell) -> true | nil, Err: writes one cell (missing fields = 0) function MusicOps.setCell(m: any, pattern: number, row: number, channel: number, cell: Cell): (boolean?, Err.Err?) local p, err = patternAt(m, pattern, row, channel) if not p then return nil, err end if type(cell) ~= "table" then return bad("setCell: cell must be a table") end local note = 0 if cell.note ~= nil then local n, nerr = MusicOps.note(cell.note) if not n then return nil, nerr end note = n end for _, k in { "instrument", "volume", "effect", "param" } do local v = (cell :: any)[k] if v ~= nil and not int(v, 0, 255) then return bad("setCell: " .. k .. " must be 0..255") end end Tracker.setCell(m, pattern, row, channel, note, cell.instrument or 0, cell.volume or 0, cell.effect or 0, cell.param or 0) return true, nil end -- getCell(module, pattern, row, channel) -> { note, instrument, volume, effect, param } (numbers) | nil, Err function MusicOps.getCell(m: any, pattern: number, row: number, channel: number): (Cell?, Err.Err?) local p, err = patternAt(m, pattern, row, channel) if not p then return nil, err end local note, ins, vol, fx, param = Tracker.cell(m, pattern, row, channel) return { note = note, instrument = ins, volume = vol, effect = fx, param = param }, nil end -- ------------------------------------------------------------------------------------------------ samples export type SampleSpec = { name: string?, audio: any?, -- an Audio (1 or 2 channels): the sample data and, unless rate is given, its rate data: buffer?, -- or raw f32 frames (interleaved when channels = 2) ... length: number?, -- ... with their frame count (default: the whole buffer) channels: number?, -- 1 (default) or 2, for data rate: number?, -- Hz the sample plays at on C-4 (MOD / XM) or C-5 (S3M / IT); default the Audio's, else 8363 loop: string?, -- "none" (default), "forward", "pingpong" loopStart: number?, -- frames (default 0) loopEnd: number?, -- frames, exclusive (default the length) volume: number?, -- 0..64 (default 64) pan: number?, -- 0..256 (XM / IT; nil = the channel's) bits: number?, -- 8 or 16: what writers store (default 8 for MOD, else 16) } local LOOPS: { [string]: number } = { none = 0, forward = 1, pingpong = 2 } -- addSample(module, spec) -> the new sample's number (1-based) | nil, Err. The rate sets the tuning: c5speed for -- S3M / IT, relativeNote + finetune (1/128 semitones from 8363 Hz) for MOD / XM (MOD files store only the finetune, -- -1..+7/8 semitone: use rates near 8363 Hz when saving a MOD). function MusicOps.addSample(m: any, spec: SampleSpec): (number?, Err.Err?) if not isModule(m) then return bad("addSample: needs a tracker Module") end if type(spec) ~= "table" then return bad("addSample: spec must be a table") end local data: buffer, length: number, channels: number local rate = spec.rate local a = spec.audio if a ~= nil then if type(a) ~= "table" or a.kind ~= "audio" or type(a.samples) ~= "buffer" or not int(a.frames, 0, 2 ^ 31) or (a.channels ~= 1 and a.channels ~= 2) or buffer.len(a.samples) < a.frames * a.channels * 4 then return bad("addSample: audio must be a mono or stereo Audio") end data, length, channels = a.samples, a.frames, a.channels rate = rate or a.sampleRate elseif type(spec.data) == "buffer" then channels = spec.channels or 1 if channels ~= 1 and channels ~= 2 then return bad("addSample: channels must be 1 or 2") end local d: buffer = spec.data length = spec.length or buffer.len(d) // (4 * channels) if not int(length, 0, 2 ^ 31) or buffer.len(d) < length * channels * 4 then return bad("addSample: data shorter than length") end data = d else return bad("addSample: needs audio or data") end rate = rate or 8363 if type(rate) ~= "number" or rate < 1 or rate > 1e7 then return bad("addSample: bad rate") end local s = Tracker.newSample(spec.name) local copy = buffer.create(length * channels * 4) buffer.copy(copy, 0, data, 0, length * channels * 4) s.data, s.length, s.channels = copy, length, channels s.bits = spec.bits or (if m.format == "mod" then 8 else 16) if s.bits ~= 8 and s.bits ~= 16 then return bad("addSample: bits must be 8 or 16") end s.c5speed = rate local semis = 12 * math.log(rate / 8363) / math.log(2) local rn = math.floor(semis + 0.5) if rn < -96 or rn > 95 then return bad("addSample: rate out of range") end s.relativeNote = rn s.finetune = math.clamp(math.floor((semis - rn) * 128 + 0.5), -128, 127) local lt = LOOPS[spec.loop or "none"] if lt == nil then return bad("addSample: loop must be none, forward or pingpong") end if lt > 0 then local ls, le = spec.loopStart or 0, spec.loopEnd or length if not int(ls, 0, length) or not int(le, 0, length) or le - ls < 1 then return bad("addSample: bad loop") end s.loopStart, s.loopEnd, s.loopType = ls, le, lt end if spec.volume ~= nil then if type(spec.volume) ~= "number" or spec.volume < 0 or spec.volume > 64 then return bad("addSample: volume must be 0..64") end s.volume = spec.volume end if spec.pan ~= nil then if type(spec.pan) ~= "number" or spec.pan < 0 or spec.pan > 256 then return bad("addSample: pan must be 0..256") end s.pan = spec.pan end table.insert(m.samples, s) return #m.samples, nil end -- ------------------------------------------------------------------------------------------------ instruments export type InstrumentSpec = { name: string?, sample: number?, -- the sample every note plays (1-based) samples: { [number]: number }?, -- or a keymap: note number -> sample number (other notes: none) fadeout: number?, -- volume fade per tick after key off, as the format stores it (XM 0..4095, IT 0..1024) envelope: { points: { { number } }, sustain: number?, loopStart: number?, loopEnd: number? }?, -- volume -- envelope: points { tick, 0..64 } with ticks increasing; sustain / loop points are 1-based point indexes } -- addInstrument(module, spec) -> the new instrument's number (1-based) | nil, Err. XM and IT modules only (MOD / -- S3M cells name samples directly). function MusicOps.addInstrument(m: any, spec: InstrumentSpec): (number?, Err.Err?) if not isModule(m) then return bad("addInstrument: needs a tracker Module") end if m.format ~= "xm" and m.format ~= "it" then return bad("addInstrument: only xm and it modules have instruments (mod / s3m cells name samples)") end if type(spec) ~= "table" then return bad("addInstrument: spec must be a table") end local ins = Tracker.newInstrument(spec.name) if spec.sample ~= nil then if not int(spec.sample, 1, #m.samples) then return bad("addInstrument: no sample " .. tostring(spec.sample)) end for n = 1, 120 do ins.sampleMap[n] = spec.sample end elseif type(spec.samples) == "table" then for note, smp in spec.samples do if not int(note, 1, 120) or not int(smp, 0, #m.samples) then return bad("addInstrument: bad keymap entry") end ins.sampleMap[note] = smp end end if spec.fadeout ~= nil then if not int(spec.fadeout, 0, 65535) then return bad("addInstrument: bad fadeout") end ins.fadeout = spec.fadeout end local e = spec.envelope if e ~= nil then if type(e) ~= "table" or type(e.points) ~= "table" or #e.points == 0 then return bad("addInstrument: envelope needs points") end local env = Tracker.newEnvelope() local last = -1 for i, pt in e.points do local tick: any, value: any = nil, nil if type(pt) == "table" then tick, value = pt[1], pt[2] end if not int(tick, 0, 65535) or type(value) ~= "number" or value < 0 or value > 64 or (tick :: number) <= last then return bad("addInstrument: envelope point " .. i .. " must be { tick, 0..64 } with increasing ticks") end last = tick :: number env.ticks[i], env.values[i] = tick, value end env.enabled = true local n = #e.points if e.sustain ~= nil then if not int(e.sustain, 1, n) then return bad("addInstrument: bad sustain point") end env.sustain, env.susStart, env.susEnd = true, e.sustain, e.sustain end if e.loopStart ~= nil or e.loopEnd ~= nil then local ls, le = e.loopStart or 1, e.loopEnd or n if not int(ls, 1, n) or not int(le, ls, n) then return bad("addInstrument: bad envelope loop") end env.loop, env.loopStart, env.loopEnd = true, ls, le end ins.volEnv = env end table.insert(m.instruments, ins) return #m.instruments, nil end return MusicOps