diff --git a/src/Rosetta/music/669/init.luau b/src/Rosetta/music/669/init.luau index ab4e70e..50d14d0 100644 --- a/src/Rosetta/music/669/init.luau +++ b/src/Rosetta/music/669/init.luau @@ -1,11 +1,7 @@ --!strict --- music/669: Composer 669 and UNIS 669 modules ("if" / "JN"; 8 channels, 64-row patterns with their own speed and --- break row). Ported from OpenMPT's Load_669.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads into the --- codecs/audio/Tracker Module and plays as the "s3m" effect family with 669's quirks (flags): periods in Hz (slides --- move the frequency 80 Hz per step, tone portamento 40 Hz), slides on every tick, auto portamentos that run until --- the channel's next effect, a tone portamento that keeps going, frequency adjust (D), frequency vibrato (E), speed (F), --- UNIS 669 balance slides (G) and slot retrigger (H). The tempo is fixed (78 BPM in tracker terms). --- Not supported: UNIS 669's "super fast" speed 0, writing. +-- music/669: Composer 669 / UNIS 669 modules ("if" / "JN"), ported from OpenMPT's Load_669.cpp (BSD, +-- licenses/openmpt-LICENSE.txt). Supports: 8 channels, 64-row patterns, played as the "s3m" family with 669's quirks +-- (periods in Hz, auto portamentos, effects D..H, a fixed 78 BPM). Not supported: UNIS 669's speed 0, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -25,16 +21,16 @@ local Six69 = { } export type DecodeOptions = { - maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) + maxBytes: number?, -- f32 bytes of sample data in total, default 2^28 } -- ------------------------------------------------------------------------------------------------ constants local IT = Load.IT --- the 669 effects (high nibble of the effect byte) by name +-- effects: the high nibble of the effect byte local EFFECTS = { "autoportaup", "autoportadown", "toneporta", "freqadjust", "vibrato", "speed", "panslide", "retrig" } -- ------------------------------------------------------------------------------------------------ sniff --- the 497-byte header is valid (669 has a two-byte magic only, so the rest is checked too) +-- the 497-byte header (the magic is two bytes only, so the other fields are checked too) local function validHeader(r: Bytes.Reader): boolean if r:size() < 497 then return false @@ -197,7 +193,6 @@ function Six69.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function Six69.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local m, err = Six69.decode(r, opts) if not m then diff --git a/src/Rosetta/music/ahx/init.luau b/src/Rosetta/music/ahx/init.luau index c888acf..eee4cd5 100644 --- a/src/Rosetta/music/ahx/init.luau +++ b/src/Rosetta/music/ahx/init.luau @@ -1,10 +1,7 @@ --!strict --- music/ahx: AHX (Abyss' Highest eXperience) modules, "THX\0" .. "THX\2": 4-channel Amiga synth tunes (no samples: --- triangle / sawtooth / square / noise waveforms through filters, square modulation, the PList instrument programs). --- Loads into a Types.Module-shaped value (kind "music", format "ahx": tracks as patterns, positions with per-channel --- transposes, instruments with play lists, subsongs) and renders through codecs/audio/Hively, a port of HivelyTracker's --- hvl2wav replayer (BSD-3-Clause): at 44.1 kHz with stereo = 0 the samples equal hvl2wav's. --- Not supported: writing. +-- music/ahx: AHX (Abyss' Highest eXperience) 4-channel Amiga synth modules, "THX\0" .. "THX\2", rendered through +-- codecs/audio/Hively (a port of HivelyTracker's hvl2wav, BSD-3-Clause; at 44.1 kHz, stereo 0, equal to hvl2wav). +-- Supports: tracks, positions with transposes, PList instruments, subsongs. Not supported: writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -23,7 +20,7 @@ local Ahx = { } -- ------------------------------------------------------------------------------------------------ types -export type RenderOptions = Hively.RenderOptions -- sampleRate, subsong, stereo (0..4), loop, maxDuration +export type RenderOptions = Hively.RenderOptions -- stereo 0..4 -- ------------------------------------------------------------------------------------------------ sniff function Ahx.sniff(r: Bytes.Reader): number @@ -41,7 +38,6 @@ function Ahx.decode(r: Bytes.Reader, _opts: any?): (Types.Module?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> the rendered audio Decoder (opts: RenderOptions) function Ahx.open(r: Bytes.Reader, opts: RenderOptions?): (Types.Decoder?, Err.Err?) local song, err = Ahx.decode(r) if not song then diff --git a/src/Rosetta/music/far/init.luau b/src/Rosetta/music/far/init.luau index 20861d7..c5ac494 100644 --- a/src/Rosetta/music/far/init.luau +++ b/src/Rosetta/music/far/init.luau @@ -1,11 +1,7 @@ --!strict --- music/far: Farandole Composer modules (FAR, Daniel Potter's DOS tracker; 16 channels, up to 256 patterns of any --- length with a break row, 64 samples). Ported from OpenMPT's Load_far.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads --- into the codecs/audio/Tracker Module and plays as the "s3m" effect family with Farandole's quirks (flags): periods --- in Hz (a slide step moves the frequency 36318 / 1024 Hz), a tone portamento that keeps going, fine pitch slides, --- retrigger, vibrato depth / speed, volume slides, volume portamento (as a set volume), panning, speed; the fixed --- tempo OpenMPT uses (80 BPM in tracker terms). --- Not supported: Farandole's own tempo model (fine tempo up / down, D / E), the note-offset effect (C), writing. +-- music/far: Farandole Composer modules (FAR, 16 channels), ported from OpenMPT's Load_far.cpp (BSD, +-- licenses/openmpt-LICENSE.txt). Plays as the "s3m" family with FAR's quirks (periods in Hz, a slide step of +-- 36318 / 1024 Hz, OpenMPT's fixed 80 BPM). Not supported: FAR's tempo effects (D / E), note offset (C), writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -25,7 +21,7 @@ local Far = { } export type DecodeOptions = { - maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) + maxBytes: number?, -- f32 bytes of sample data in total, default 2^28 } -- ------------------------------------------------------------------------------------------------ constants @@ -40,7 +36,7 @@ function Far.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- a pattern cell's effect byte -> effect code, parameter, volume byte (S3M coding, 0 = none) (OpenMPT's table) +-- effect byte -> S3M effect, parameter, volume byte (0 = none): OpenMPT's table local function effect(e: number): (number, number, number) local cmd, p = e // 16, e % 16 if cmd == 1 then @@ -220,7 +216,6 @@ function Far.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function Far.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local m, err = Far.decode(r, opts) if not m then diff --git a/src/Rosetta/music/hmp/init.luau b/src/Rosetta/music/hmp/init.luau index f6a7e65..e2ea95f 100644 --- a/src/Rosetta/music/hmp/init.luau +++ b/src/Rosetta/music/hmp/init.luau @@ -1,14 +1,7 @@ --!strict --- music/hmp: Human Machine Interfaces SOS music: HMP ("HMIMIDIP", and the newer "HMIMIDIP013195" with the bigger header) --- and HMI ("HMI-MIDISONG061595"), as used by Descent, Duke Nukem 3D's predecessors and other DOS games. Written from the --- HMP / HMI layout notes (header fields, chunk tables, the reversed delta encoding of HMP, HMI's note durations and FE --- events); wildmidi was used only as a reference converter in tests. Decodes to a Types.Midi (format 1, one track per --- chunk): HMP deltas (7-bit groups least significant first, the last byte flagged) and running status; loop marker --- controllers 110 / 111 with a value above 127 are skipped (meta.source.loops counts them); HMI note-ons carry a --- duration that becomes a note-off (velocity 64), HMI-only FE events are skipped. Time: the header's tick rate (HMP --- at 0x38, HMI byte 212) in ticks per second, as division 60 at 60000000 / rate us per quarter; tempo events in the --- tracks apply on top. Renders through codecs/audio/MidiRender. --- Not supported: writing; HMP branch tables (skipped). +-- music/hmp: HMI SOS music: HMP ("HMIMIDIP", "HMIMIDIP013195") and HMI ("HMI-MIDISONG061595"), from the layout +-- notes (wildmidi only as a test reference). Decodes to a Types.Midi (format 1, a track per chunk; the tick rate at +-- HMP 0x38 / HMI byte 212, as division 60). Not supported: writing, HMP branch tables. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -43,8 +36,7 @@ local readu8, readu32 = buffer.readu8, buffer.readu32 local DATA = { [8] = 2, [9] = 2, [10] = 2, [11] = 2, [12] = 1, [13] = 1, [14] = 2 } local TYPES = { [8] = "noteOff", [9] = "noteOn", [10] = "aftertouch", [11] = "controller", [12] = "program", [13] = "channelPressure", [14] = "pitchBend" } --- a delta at p -> value, next p (nil past e). hmp: least significant group first, the last byte has bit 7 set; --- otherwise the MIDI encoding +-- HMP deltas: 7-bit groups, least significant first, the last byte has bit 7 set; HMI: the MIDI encoding local function delta(b: buffer, p: number, e: number, hmp: boolean): (number?, number) local v, shift = 0, 1 for _ = 1, 5 do @@ -79,14 +71,13 @@ end type Ctx = { loops: number, budget: number } --- one track [p, e) -> events (note-offs merged in) | nil, message local function track(b: buffer, p: number, e: number, hmp: boolean, ctx: Ctx): ({ Types.MidiEvent }?, string?) local list: { Types.MidiEvent }, offs: { Render.PendingOff } = {}, {} local tick, running = 0, 0 while p < e do local d, q = delta(b, p, e, hmp) if not d then - break -- (a track cut inside its last delta: keep what was read) + break end tick += d p = q @@ -170,7 +161,6 @@ local function track(b: buffer, p: number, e: number, hmp: boolean, ctx: Ctx): ( return out, nil end --- the chunk table -> { { start, stop } } track ranges | nil, message, kind local function hmpTracks(b: buffer, base: number, limit: number): ({ { number } }?, string?, string?) local new = buffer.readstring(b, base + 8, 6) == "013195" local n = readu32(b, base + 0x30) @@ -261,7 +251,6 @@ function Hmp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Midi?, Err.Er end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> the rendered audio Decoder (opts: DecodeOptions + MidiRender.RenderOptions) function Hmp.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local midi, err = Hmp.decode(r, opts) if not midi then diff --git a/src/Rosetta/music/hvl/init.luau b/src/Rosetta/music/hvl/init.luau index ea0f81a..92cb27e 100644 --- a/src/Rosetta/music/hvl/init.luau +++ b/src/Rosetta/music/hvl/init.luau @@ -1,10 +1,7 @@ --!strict --- music/hvl: HivelyTracker modules, "HVL\0" / "HVL\1": AHX's synth extended to 4..16 channels, two effect columns, --- ring modulation, per-channel panning, mix gain and stereo separation stored in the file. Loads into a Types.Module- --- shaped value (kind "music", format "hvl": tracks as patterns, positions with per-channel transposes, instruments with --- play lists, subsongs) and renders through codecs/audio/Hively, a port of HivelyTracker's hvl2wav replayer --- (BSD-3-Clause): at 44.1 kHz the samples equal hvl2wav's. --- Not supported: writing. +-- music/hvl: HivelyTracker modules, "HVL\0" / "HVL\1" (AHX extended: 4..16 channels, two effect columns, ring +-- modulation, panning, stereo separation), rendered through codecs/audio/Hively (a port of hvl2wav, BSD-3-Clause; at +-- 44.1 kHz equal to hvl2wav). Not supported: writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -23,7 +20,7 @@ local Hvl = { } -- ------------------------------------------------------------------------------------------------ types -export type RenderOptions = Hively.RenderOptions -- sampleRate, subsong, loop, maxDuration (stereo: the file's) +export type RenderOptions = Hively.RenderOptions -- stereo comes from the file -- ------------------------------------------------------------------------------------------------ sniff function Hvl.sniff(r: Bytes.Reader): number @@ -41,7 +38,6 @@ function Hvl.decode(r: Bytes.Reader, _opts: any?): (Types.Module?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> the rendered audio Decoder (opts: RenderOptions) function Hvl.open(r: Bytes.Reader, opts: RenderOptions?): (Types.Decoder?, Err.Err?) local song, err = Hvl.decode(r) if not song then diff --git a/src/Rosetta/music/it/Itsex.luau b/src/Rosetta/music/it/Itsex.luau index 3a7daca..7176086 100644 --- a/src/Rosetta/music/it/Itsex.luau +++ b/src/Rosetta/music/it/Itsex.luau @@ -1,15 +1,11 @@ --!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. +-- music/it/Itsex: IT 2.14 / 2.15 (double-delta) sample decompression, from ITTECH.TXT: 0x8000-byte output blocks, each +-- a u16 length then an LSB-first bit stream of deltas with three width-change methods. 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 @@ -34,7 +30,6 @@ function Itsex.decompress(buf: buffer, off: number, limit: number, frames: numbe 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 @@ -90,7 +85,6 @@ function Itsex.decompress(buf: buffer, off: number, limit: number, frames: numbe continue end end - -- a delta, sign-extended from its width local x = v if width < topWidth then local shift = 2 ^ width diff --git a/src/Rosetta/music/it/init.luau b/src/Rosetta/music/it/init.luau index d271f18..bc58101 100644 --- a/src/Rosetta/music/it/init.luau +++ b/src/Rosetta/music/it/init.luau @@ -1,12 +1,7 @@ --!strict --- music/it: Impulse Tracker modules (IMPM, ITTECH.TXT; also files from OpenMPT / Schism Tracker). Reads into the --- codecs/audio/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. +-- music/it: Impulse Tracker modules (IMPM, ITTECH.TXT), played through codecs/audio/Tracker. Supports: 64 channels, +-- instrument / sample mode, old and new instrument headers, envelopes, NNAs, resonant filters (default Zxx macros), +-- IT 2.14 / 2.15 compressed samples, the message. Not supported: embedded MIDI macros, OpenMPT extensions, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -26,7 +21,7 @@ local It = { } export type DecodeOptions = { - maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) + maxBytes: number?, -- f32 bytes of sample data in total, default 2^28 } -- ------------------------------------------------------------------------------------------------ sniff @@ -173,7 +168,6 @@ function It.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) 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 } = {} @@ -187,7 +181,6 @@ function It.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) 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 @@ -258,7 +251,6 @@ function It.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) 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 @@ -266,7 +258,6 @@ function It.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end m.instruments[i] = ins end - -- samples local total = 0 for i = 1, smpnum do local h = r:sub(smpOff[i], 80) @@ -348,7 +339,6 @@ function It.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end end end - -- patterns for p = 1, patnum do local pat = Tracker.newPattern(rowsOf[p], nch) m.patterns[p] = pat @@ -415,7 +405,6 @@ function It.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) 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 diff --git a/src/Rosetta/music/med/init.luau b/src/Rosetta/music/med/init.luau index 0956498..fb4154a 100644 --- a/src/Rosetta/music/med/init.luau +++ b/src/Rosetta/music/med/init.luau @@ -1,14 +1,7 @@ --!strict --- music/med: MED / OctaMED modules (MMD0, MMD1, MMD2, MMD3; Amiga MED 2+, OctaMED 4 .. Soundstudio; 1..64 tracks, --- blocks of any length). Ported from OpenMPT's Load_med.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads the first song --- into the codecs/audio/Tracker Module and plays it as the "xm" effect family with ProTracker periods and the PAL --- clock (flags.periods = "amiga"): MED's effects mapped as OpenMPT maps them, slides on every tick unless the song asks --- for ProTracker-style slides, the SPD / 8-channel / BPM tempo modes, MMD2 / MMD3 play sequences and sections (stop --- and jump commands), track volumes and pans, hold / decay (as a volume envelope and fadeout), IFF multi-octave --- samples (instruments with keymaps), 8 / 16-bit, stereo and delta samples, instrument extras (finetune, loops, --- default pitch, volume). --- Not supported: synthetic and hybrid instruments (silent), MIDI instruments and commands, extra command pages and --- the second command parameter, songs past the first, echo / stereo separation, packed (ADPCM) samples, writing. +-- music/med: MED / OctaMED modules (MMD0..MMD3), ported from OpenMPT's Load_med.cpp (BSD, +-- licenses/openmpt-LICENSE.txt); the first song plays as the "xm" family with Amiga periods. Supports: 1..64 tracks, +-- play sequences, hold / decay, IFF multi-octave samples. Not supported: synth / MIDI instruments, echo, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -28,7 +21,7 @@ local Med = { } export type DecodeOptions = { - maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) + maxBytes: number?, -- f32 bytes of sample data in total, default 2^28 } -- ------------------------------------------------------------------------------------------------ constants @@ -78,7 +71,7 @@ end -- ------------------------------------------------------------------------------------------------ decode type Ctx = { transpose: number, is8Ch: boolean, softMix: boolean, bpm: boolean, rowsPerBeat: number, volHex: boolean, vol7bit: boolean } --- a MED tempo -> BPM (OpenMPT's MMDTempoToBPM: the SPD / 8-channel / BPM modes) +-- OpenMPT's MMDTempoToBPM (SPD / 8-channel / BPM modes) local function tempoToBpm(tempo: number, ctx: Ctx): number if ctx.bpm and not ctx.is8Ch then return if tempo < 7 then 111.5 else tempo * ctx.rowsPerBeat / 4 @@ -93,7 +86,7 @@ local function tempoToBpm(tempo: number, ctx: Ctx): number return tempo / 0.264 end --- a MED command -> MOD / XM effect, param, and a note-cut flag (OpenMPT's ConvertMEDEffect) +-- MED command -> MOD / XM effect, param, note-cut flag: OpenMPT's ConvertMEDEffect local function effect(cmd: number, p: number, ctx: Ctx): (number, number, boolean) local lo = math.min(p, 15) if cmd == 1 or cmd == 2 then @@ -179,7 +172,7 @@ local function effect(cmd: number, p: number, ctx: Ctx): (number, number, boolea return 0, 0, false end --- a MED note (with the play transpose) -> our note, or 0 (OpenMPT's octave wrapping) +-- OpenMPT's octave wrapping local function wrapNote(note: number, vol7bit: boolean): number local n = note + 12 -- OpenMPT's numbering (ProTracker notes an octave up) if n > 132 and not vol7bit then @@ -190,7 +183,6 @@ local function wrapNote(note: number, vol7bit: boolean): number return if n >= 13 then n - 12 else 0 end --- one block -> a Pattern (the main command page); returns whether a note needs the instruments' octave folding local function readBlock(r: Bytes.Reader, off: number, version: number, ctx: Ctx, nch: number): (any?, boolean) local br = r:sub(off) local ntracks, nrows, info @@ -300,7 +292,6 @@ function Med.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) if numSamples > 0 and smpOff == 0 then return nil, Err.new(Err.CORRUPT, "no sample table") end - -- channels: the widest block (at least 4) local nch = 4 local blockPtr: { number } = {} for b = 0, numBlocks - 1 do @@ -339,7 +330,6 @@ function Med.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) if ext.nameOff > 0 and ext.nameLen > 0 then m.title = r:sub(ext.nameOff, math.min(ext.nameLen, 256)):fixed(math.min(ext.nameLen, 256)) end - -- instruments and samples local needInstruments = false local instruments, samples = {}, {} local unsupported = {} @@ -419,7 +409,6 @@ function Med.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end end end - -- sample data local list = {} for i = 0, count - 1 do local s = Tracker.newSample(name) @@ -454,7 +443,6 @@ function Med.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) frames, ls, le = frames * 2, ls * 2, le * 2 end end - -- the instrument extras if xsize > 0 then if x.hold > 0 and not isSynth then local env = Tracker.newEnvelope() @@ -591,7 +579,6 @@ function Med.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end end m.preamp = preamp - -- tempo, speed, volume, the pattern context local ctx: Ctx = { transpose = 36 + playTranspose - (if version > 2 then 24 else 0), is8Ch = bit32.band(flags, 0x40) ~= 0, @@ -606,7 +593,6 @@ function Med.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) if masterVol > 0 then m.globalVolume = math.min(masterVol, 64) * 2 end - -- blocks for b = 0, numBlocks - 1 do local p = blockPtr[b + 1] local pat, high = nil, false @@ -620,7 +606,6 @@ function Med.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) for at, to in jumps do local prev = m.order[at - 1] if prev and prev < 254 and m.patterns[prev + 1] then - -- the block may be played elsewhere: give this order entry its own copy local src = m.patterns[prev + 1] local cp = Tracker.newPattern(src.rows, nch) buffer.copy(cp.data, 0, src.data) @@ -649,7 +634,6 @@ function Med.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function Med.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local m, err = Med.decode(r, opts) if not m then diff --git a/src/Rosetta/music/midi/Smf.luau b/src/Rosetta/music/midi/Smf.luau index fc7dfac..85d99c1 100644 --- a/src/Rosetta/music/midi/Smf.luau +++ b/src/Rosetta/music/midi/Smf.luau @@ -1,10 +1,6 @@ --!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); a track's name is written as a 0x03 event at tick 0 when the track --- has none. Written from the SMF 1.0 specification (no third-party code). +-- music/midi/Smf: SMF 1.0 MThd / MTrk <-> Types.Midi (running status also across meta / sysex, RIFF RMID unwrapped). +-- Writes what python mido writes: running status reset after meta / sysex, one end-of-track, track names at tick 0. local Err = require("@rosetta/core/Err") local Bytes = require("@rosetta/core/Bytes") local Types = require("@rosetta/Types") @@ -43,13 +39,11 @@ 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 @@ -140,7 +134,6 @@ local function readTrack(b: buffer, p: number, e: number, budget: { number }): ( 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 } @@ -267,7 +260,6 @@ local function byteList(d: any, want: number?): { number }? 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, "needs a Midi value with tracks") @@ -298,7 +290,6 @@ function Smf.write(midi: Types.Midi, opts: WriteOptions?): (buffer?, Err.Err?) if type(events) ~= "table" then return nil, Err.new(Err.ARG, "track " .. ti .. " has no events list") end - -- stable order by tick local sorted = true local last = 0 for i, ev in events do @@ -324,7 +315,7 @@ function Smf.write(midi: Types.Midi, opts: WriteOptions?): (buffer?, Err.Err?) return order[a] < order[c] end) end - -- track.name: written as a track-name meta event (0x03) at tick 0 when the track has none of its own +-- a track-name meta event (0x03) at tick 0 when the track has none (as mido) if type(track.name) == "string" and track.name ~= "" then local named = false for _, ev in list do diff --git a/src/Rosetta/music/midi/init.luau b/src/Rosetta/music/midi/init.luau index 1611da1..0d6c0c0 100644 --- a/src/Rosetta/music/midi/init.luau +++ b/src/Rosetta/music/midi/init.luau @@ -1,14 +1,7 @@ --!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/audio/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; .kar karaoke: --- meta.lyrics = { { time, tick, text } } from the "Words" track's text events (FF 01; the @ headers go to --- meta.karaoke and meta.tags) and from lyric events (FF 05), in time order), 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). +-- music/midi: Standard MIDI Files (SMF 1.0 formats 0 / 1 / 2, PPQ and SMPTE; RIFF RMID read), from the spec. Supports: +-- decode to a Types.Midi, .kar lyrics, encode (byte-identical to python mido by default), the tempo map, rendering +-- through codecs/audio/SoundFont. Not supported: RMID write, XMF / DLS banks, system common bytes in tracks. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -30,7 +23,7 @@ local Midi = { -- ------------------------------------------------------------------------------------------------ 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 +export type RenderOptions = Render.RenderOptions -- ------------------------------------------------------------------------------------------------ sniff function Midi.sniff(r: Bytes.Reader): number @@ -44,8 +37,7 @@ function Midi.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- karaoke(midi): .kar text (FF 01 in a track named "Words", or in any track once an "@K" / "@T" header shows up) and --- FF 05 lyric events -> meta.lyrics; "@X" headers -> meta.karaoke[X] (lists of lines) and meta.tags +-- .kar: FF 01 text in a "Words" track (or after an "@K" / "@T" header) and FF 05 lyrics; "@X" headers -> meta.karaoke[X] local function karaoke(midi: Types.Midi) local lyrics: { { time: number, tick: number, text: string } } = {} local headers: { [string]: { string } } = {} @@ -119,7 +111,6 @@ function Midi.encode(midi: Types.Midi, opts: EncodeOptions?): (buffer?, Err.Err? 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 @@ -129,26 +120,22 @@ function Midi.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) 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) +-- as python mido's MidiFile.length (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/Rosetta/music/mod/init.luau b/src/Rosetta/music/mod/init.luau index 1309897..e2fe34e 100644 --- a/src/Rosetta/music/mod/init.luau +++ b/src/Rosetta/music/mod/init.luau @@ -1,11 +1,7 @@ --!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/audio/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. +-- music/mod: ProTracker / NoiseTracker / StarTrekker MODs (M.K., M!K!, FLT4, xCHN, xxCH, xxCN, CD81, OKTA, TDZx; +-- 15-sample Soundtracker by name or extension), from the ProTracker 2.3 docs. Writes 31-sample MODs from "mod" modules +-- and XM ones that fit. Not supported: FLT8's split patterns (read as 8 channels), the E0x filter, PowerPacker files. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -24,7 +20,7 @@ local Mod = { } export type DecodeOptions = { - maxBytes: number?, -- refuse bigger sample data in total (default 64 MB of f32 samples) + maxBytes: number?, -- f32 bytes of sample data in total, default 64 MB } export type EncodeOptions = {} @@ -46,7 +42,7 @@ local FIXED: { [string]: number } = { ["EXO8"] = 8, } --- channels from the 4-byte signature at 1080, or nil +-- the 4-byte signature at offset 1080 local function signatureChannels(sig: string): number? local fixed = FIXED[sig] if fixed then @@ -143,7 +139,6 @@ function Mod.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) 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 @@ -168,7 +163,7 @@ function Mod.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) 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) +-- sample data: 8-bit signed local total = 0 for i = 1, nsamples do local s = m.samples[i] @@ -206,8 +201,6 @@ local function writeName(w: Bytes.Writer, s: string, n: number) 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 @@ -220,7 +213,6 @@ function Mod.encode(m: any, _opts: EncodeOptions?): (buffer?, Err.Err?) 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 @@ -273,7 +265,6 @@ function Mod.encode(m: any, _opts: EncodeOptions?): (buffer?, Err.Err?) 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) @@ -349,7 +340,6 @@ function Mod.encode(m: any, _opts: EncodeOptions?): (buffer?, Err.Err?) 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 diff --git a/src/Rosetta/music/mtm/init.luau b/src/Rosetta/music/mtm/init.luau index 622dea1..e8b4d8d 100644 --- a/src/Rosetta/music/mtm/init.luau +++ b/src/Rosetta/music/mtm/init.luau @@ -1,10 +1,7 @@ --!strict --- music/mtm: MultiTracker modules (MTM, Renaissance's DOS tracker, 1..32 channels; patterns built from shared --- tracks). Ported from OpenMPT's Load_mtm.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads into the --- codecs/audio/Tracker Module and plays as the "xm" effect family with Amiga periods (OpenMPT plays MTM like XM): --- MOD effects (no 8xx panning, E8x pans), 8 / 16-bit unsigned samples, finetune, the song speed / tempo quirk --- (MultiTracker resets the tempo on a speed command and the speed on a tempo command when they never share a row). --- Not supported: MultiTracker's E9x / EDx retrigger timing and its vibrato start phase (played as in XM), writing. +-- music/mtm: MultiTracker modules (MTM, 1..32 channels, patterns of shared tracks), ported from OpenMPT's Load_mtm.cpp +-- (BSD, licenses/openmpt-LICENSE.txt); played as the "xm" family with Amiga periods, as OpenMPT does. Not supported: +-- MultiTracker's E9x / EDx retrigger timing and vibrato start phase (played as in XM), writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -24,7 +21,7 @@ local Mtm = { } export type DecodeOptions = { - maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) + maxBytes: number?, -- f32 bytes of sample data in total, default 2^28 } -- ------------------------------------------------------------------------------------------------ sniff @@ -104,7 +101,6 @@ function Mtm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) for i = 1, nch do m.channelPan[i] = (pans[i] % 16) * 16 + 8 end - -- samples local sizes: { number } = {} for i = 1, numSamples do local s = Tracker.newSample(r:fixed(22)) @@ -135,7 +131,6 @@ function Mtm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) s.length = frames m.samples[i] = s end - -- the order list for i = 1, 128 do local o = r:u8() if i <= lastOrder + 1 then @@ -214,7 +209,6 @@ function Mtm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function Mtm.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local m, err = Mtm.decode(r, opts) if not m then diff --git a/src/Rosetta/music/mus/init.luau b/src/Rosetta/music/mus/init.luau index c4c1ee3..5ee9290 100644 --- a/src/Rosetta/music/mus/init.luau +++ b/src/Rosetta/music/mus/init.luau @@ -1,13 +1,7 @@ --!strict --- music/mus: DMX MUS, the music format of Doom, Heretic, Hexen and Strife ("MUS\x1a"). Written from the MUS format --- description (Vladimir Arnost's "MUS File Format", the DMX event set); wildmidi was used only as a reference converter --- in tests. Decodes to a Types.Midi (format 0, one track) the way the usual MUS-to-MIDI converters map it: MUS channel --- 15 is the percussion channel 9, the others get MIDI channels 0..8, 10..15 in order of first use (each starting at --- volume 127), MUS controllers / system events become MIDI controllers (controller 0 = program change), notes without --- a volume reuse the channel's last one (127 at first), pitch wheel 0..255 becomes a 14-bit bend. Time: 140 ticks per --- second (opts.rate), as division 70 at 500000 us per quarter. Renders through codecs/audio/MidiRender (SoundFont / --- built-in waveforms). meta.source: primaryChannels, secondaryChannels, instruments (the patch list), rate. --- Not supported: writing (save as .mid through the midi format's encoder). +-- music/mus: DMX MUS ("MUS\x1a"; Doom, Heretic, Hexen, Strife), from Vladimir Arnost's "MUS File Format" (wildmidi +-- only as a test reference). Decodes to a Types.Midi as the usual converters map it (MUS channel 15 -> 9; 140 ticks/s +-- as division 70 at 500000 us per quarter). Not supported: writing (encode as .mid with the midi format). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -43,7 +37,6 @@ end -- ------------------------------------------------------------------------------------------------ decode local readu8 = buffer.readu8 --- the score [p, e) -> events | nil, message local function score(b: buffer, p: number, e: number, primary: number, maxEvents: number): ({ Types.MidiEvent }?, string?, boolean) local events: { Types.MidiEvent } = { { tick = 0, type = "controller", channel = 9, data = { 0x07, 127 } } } local map: { [number]: number } = { [15] = 9 } @@ -151,7 +144,6 @@ function Mus.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Midi?, Err.Er end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> the rendered audio Decoder (opts: DecodeOptions + MidiRender.RenderOptions) function Mus.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local midi, err = Mus.decode(r, opts) if not midi then diff --git a/src/Rosetta/music/okt/init.luau b/src/Rosetta/music/okt/init.luau index 58d9d83..2cbadfd 100644 --- a/src/Rosetta/music/okt/init.luau +++ b/src/Rosetta/music/okt/init.luau @@ -1,11 +1,7 @@ --!strict --- music/okt: Oktalyzer modules (OKTASONG, Armin Sander's Amiga tracker; 4 to 8 channels: each of the Amiga's four can --- be split into a mixed pair). Ported from OpenMPT's Load_okt.cpp (BSD, licenses/openmpt-LICENSE.txt). An IFF-style --- chunk list (containers/Chunks) read into the codecs/audio/Tracker Module, played as the "it" effect family with --- ProTracker periods and the PAL clock (flags.periods = "amiga"), Amiga period limits, slides on every tick, sample --- loops as sustain loops (released by R), Oktalyzer's three arpeggios, note slides (D / U every tick, L / H once: --- flags.oktSlides), and its volume command: on a mixed pair the volume is the pair's channel volume. --- Not supported: the Amiga LED filter (F), writing. +-- music/okt: Oktalyzer modules (OKTASONG, 4..8 channels: each Amiga channel may be a mixed pair), ported from OpenMPT's +-- Load_okt.cpp (BSD, licenses/openmpt-LICENSE.txt); played as the "it" family with Amiga periods, loops as sustain +-- loops (released by R), the three arpeggios and note slides. Not supported: the LED filter (F), writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -26,7 +22,7 @@ local Okt = { } export type DecodeOptions = { - maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) + maxBytes: number?, -- f32 bytes of sample data in total, default 2^28 } -- ------------------------------------------------------------------------------------------------ constants @@ -39,7 +35,6 @@ function Okt.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- a negative arpeggio offset as the equivalent positive one local function invert(p: number): number p %= 16 if p == 0 then @@ -48,7 +43,6 @@ local function invert(p: number): number return if p <= 12 then 12 - p else 24 - p end --- the Oktalyzer effect of a cell -> effect name?, param, volume (0..64, the volume column) or -1, a key off local function effect(e: number, p: number, paired: boolean): (string?, number, number, boolean) if e == 1 and p > 0 then return "portaup", p, -1, false -- "portamento down (period)": the period goes down @@ -274,7 +268,6 @@ function Okt.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function Okt.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local m, err = Okt.decode(r, opts) if not m then diff --git a/src/Rosetta/music/ptm/init.luau b/src/Rosetta/music/ptm/init.luau index f24eb73..10a438b 100644 --- a/src/Rosetta/music/ptm/init.luau +++ b/src/Rosetta/music/ptm/init.luau @@ -1,11 +1,7 @@ --!strict --- music/ptm: PolyTracker modules (PTMF, Lone Ranger's DOS tracker; up to 32 channels, S3M-like packed patterns, MOD --- effect letters). Ported from OpenMPT's Load_ptm.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads into the --- codecs/audio/Tracker Module and plays as the "it" effect family with Amiga periods, IT old effects and linked Gxx --- memory (as OpenMPT converts PTM): MOD effects whose slides take S3M-style fine values, global volume, retrigger, --- fine vibrato and the note slides (G..J: Tracker.EXT), delta-coded 8-bit and 16-bit samples (8-bit deltas of the --- byte stream, as PolyTracker stores them), ping-pong loops. --- Not supported: reverse sample offset (K), sample offsets scaled for 16-bit samples, writing. +-- music/ptm: PolyTracker modules (PTMF, up to 32 channels), ported from OpenMPT's Load_ptm.cpp (BSD, +-- licenses/openmpt-LICENSE.txt); played as the "it" family with Amiga periods, as OpenMPT converts PTM. Not supported: +-- reverse sample offset (K), sample offsets scaled for 16-bit samples, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -25,7 +21,7 @@ local Ptm = { } export type DecodeOptions = { - maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) + maxBytes: number?, -- f32 bytes of sample data in total, default 2^28 } -- ------------------------------------------------------------------------------------------------ constants @@ -59,7 +55,6 @@ local function delta16(buf: buffer, off: number, frames: number, limit: number): return raw, n end --- a PolyTracker effect -> name?, param local function effect(cmd: number, param: number): (string?, number) if cmd == 0x10 then return "globalvol", math.min(param, 0x40) * 2 @@ -154,7 +149,6 @@ function Ptm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) if r.err then return nil, r.err end - -- samples local buf = r.buf for i = 1, nsmp do local h = r:slice(80) @@ -215,7 +209,6 @@ function Ptm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function Ptm.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local m, err = Ptm.decode(r, opts) if not m then diff --git a/src/Rosetta/music/s3m/init.luau b/src/Rosetta/music/s3m/init.luau index 0852553..6b14b5d 100644 --- a/src/Rosetta/music/s3m/init.luau +++ b/src/Rosetta/music/s3m/init.luau @@ -1,10 +1,7 @@ --!strict --- music/s3m: Scream Tracker 3 modules (SCRM, ST3 TECH.DOC; also files from Impulse Tracker / OpenMPT / Schism --- Tracker). Reads into the codecs/audio/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. +-- music/s3m: Scream Tracker 3 modules (SCRM, ST3 TECH.DOC). Supports: 32 PCM channels, 8 / 16-bit mono / stereo +-- samples, the panning table, ST3.00 fast slides, every ST3 effect; notes stored an octave up (S3M C-4 = note 61, as IT +-- shows S3M files). Not supported: AdLib (OPL) instruments (silent), writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -23,7 +20,7 @@ local S3m = { } export type DecodeOptions = { - maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) + maxBytes: number?, -- f32 bytes of sample data in total, default 2^28 } -- ------------------------------------------------------------------------------------------------ sniff @@ -86,7 +83,6 @@ function S3m.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) 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() @@ -126,7 +122,6 @@ function S3m.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) m.channelPan[i] = pan m.channelMute[i] = c >= 16 end - -- samples local total = 0 local unsigned = ffi ~= 1 for i = 1, insnum do @@ -154,7 +149,6 @@ function S3m.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) 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 @@ -170,7 +164,6 @@ function S3m.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end end end - -- patterns for p = 1, patnum do local pat = Tracker.newPattern(64, nch) m.patterns[p] = pat @@ -230,7 +223,6 @@ function S3m.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) 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 diff --git a/src/Rosetta/music/sf2/init.luau b/src/Rosetta/music/sf2/init.luau index f03a2a2..aac7027 100644 --- a/src/Rosetta/music/sf2/init.luau +++ b/src/Rosetta/music/sf2/init.luau @@ -1,9 +1,7 @@ --!strict --- music/sf2: SoundFont 2 banks (SoundFont 2.04 specification), read-only. A thin wrapper over codecs/audio/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. +-- music/sf2: SoundFont 2 banks (SoundFont 2.04 spec), read-only, over codecs/audio/SoundFont (a TinySoundFont port). +-- Supports: INFO, 16 / 24-bit (sm24) samples, presets / instruments with global zones, generators merged into regions. +-- Not supported: writing, SF3 (Vorbis samples), modulators (skipped). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -37,7 +35,6 @@ function Sf2.decode(r: Bytes.Reader, opts: DecodeOptions?): (SoundFont.SoundFont end -- ------------------------------------------------------------------------------------------------ extras --- synth(sf?, sampleRate?, opts?) -> a synth State (codecs/audio/SoundFont.Synth drives it) Sf2.synth = SoundFont.synth Sf2.fallback = SoundFont.fallback diff --git a/src/Rosetta/music/stm/init.luau b/src/Rosetta/music/stm/init.luau index ec82b94..cad5581 100644 --- a/src/Rosetta/music/stm/init.luau +++ b/src/Rosetta/music/stm/init.luau @@ -1,10 +1,7 @@ --!strict --- music/stm: Scream Tracker 2 modules (STM, "!Scream!" / BMOD2STM / WUZAMOD! / SWavePro; 4 channels, 31 samples). --- Ported from OpenMPT's Load_stm.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads into the codecs/audio/Tracker Module --- and plays as the "s3m" effect family with Scream Tracker 2's tempo (flags.st2Tempo: the speed byte also sets the --- tick length), no effect memory, no fine slides (the loader drops what ST2 ignores) and its deferred Bxx (the jump --- happens at the end of the pattern or at the next Cxx). --- Not supported: STX (Scream Tracker Music Interface Kit), ST2's noise for samples at volume 0 (silent here), writing. +-- music/stm: Scream Tracker 2 modules (STM, "!Scream!" / BMOD2STM / WUZAMOD! / SWavePro), ported from OpenMPT's +-- Load_stm.cpp (BSD, licenses/openmpt-LICENSE.txt); played as the "s3m" family with ST2's tempo, no effect memory and +-- its deferred Bxx. Not supported: STX, ST2's noise for samples at volume 0 (silent), writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -24,7 +21,7 @@ local Stm = { } export type DecodeOptions = { - maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) + maxBytes: number?, -- f32 bytes of sample data in total, default 2^28 } -- ------------------------------------------------------------------------------------------------ constants @@ -221,7 +218,6 @@ function Stm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function Stm.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local m, err = Stm.decode(r, opts) if not m then diff --git a/src/Rosetta/music/ult/init.luau b/src/Rosetta/music/ult/init.luau index 7f9f004..698b075 100644 --- a/src/Rosetta/music/ult/init.luau +++ b/src/Rosetta/music/ult/init.luau @@ -1,12 +1,7 @@ --!strict --- music/ult: UltraTracker modules (MAS_UTrack_V001 .. V004; up to 32 channels, two effects per cell, patterns stored --- channel by channel with run-length repeats). Ported from OpenMPT's Load_ult.cpp (BSD, licenses/openmpt-LICENSE.txt). --- Reads into the codecs/audio/Tracker Module and plays as the "it" effect family with Amiga periods, IT old effects --- and linked Gxx memory (as OpenMPT converts ULT): the two effect columns go into the IT volume column and the effect --- column (or the more important one is kept), sample loops are sustain loops (released by a key off), the tone --- portamento keeps going on later rows. 8 / 16-bit signed samples, the v1.4+ sample speed and finetune. --- Not supported: reverse playback (5x2), "no loop" (5x1), vibrato strength (E0x), sample offsets past 64 KiB (the --- high byte is dropped), the logarithmic volumes of pre-1.4 files, writing. +-- music/ult: UltraTracker modules (MAS_UTrack_V001 .. V004, up to 32 channels), ported from OpenMPT's Load_ult.cpp +-- (BSD, licenses/openmpt-LICENSE.txt); played as the "it" family with Amiga periods, as OpenMPT converts ULT. Not +-- supported: reverse (5x2), "no loop" (5x1), E0x, offsets past 64 KiB, pre-1.4 log volumes, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -26,7 +21,7 @@ local Ult = { } export type DecodeOptions = { - maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) + maxBytes: number?, -- f32 bytes of sample data in total, default 2^28 } -- ------------------------------------------------------------------------------------------------ constants @@ -45,7 +40,7 @@ function Ult.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- one effect nibble + parameter -> name?, param (OpenMPT's TranslateULTCommands) +-- OpenMPT's TranslateULTCommands local function translate(e: number, param: number, version: number): (string?, number) local name = EFFECTS[e] if e == 0 then @@ -94,7 +89,7 @@ local function translate(e: number, param: number, version: number): (string?, n return name, param end --- volume slide + vibrato / tone portamento without a parameter -> one combined effect (OpenMPT's CombineEffects) +-- OpenMPT's CombineEffects (volume slide + vibrato / tone portamento without a parameter) local function combine(a: string?, pa: number, b: string?, pb: number): (string?, number, string?, number) if a == "volslide" and (b == "vibrato" or b == "toneportavol") and pb == 0 then return if b == "vibrato" then "vibratovol" else "toneportavol", pa, nil, 0 @@ -104,8 +99,7 @@ local function combine(a: string?, pa: number, b: string?, pb: number): (string? return a, pa, b, pb end --- an event: [0xFC repeat] note instrument effects param1 param2 -> repeat, note, instrument, volume byte, fx, param, --- lost global effect (name?, param) +-- event: [0xFC repeat] note instrument effects param1 param2 local function readEvent(r: Bytes.Reader, version: number): (number, number, number, number, number, number, string?, number) local rep = 1 local b = r:u8() @@ -297,7 +291,6 @@ function Ult.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function Ult.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local m, err = Ult.decode(r, opts) if not m then diff --git a/src/Rosetta/music/umx/init.luau b/src/Rosetta/music/umx/init.luau index 6f3f971..82c172b 100644 --- a/src/Rosetta/music/umx/init.luau +++ b/src/Rosetta/music/umx/init.luau @@ -1,12 +1,7 @@ --!strict --- music/umx: Unreal music packages (.umx, Unreal / Unreal Tournament / Deus Ex era Unreal Engine 1 packages; package --- versions up to 128). Ported from OpenMPT's UMXTools.cpp / ContainerUMX.cpp (BSD, licenses/openmpt-LICENSE.txt): --- reads the package's name, import and export tables, finds the exports of class "music" and unwraps the module each --- one embeds (IT, S3M, XM or MOD, kept as it is). A format never requires another one, so decode hands the first --- module's bytes to opts.decodeModule (the api passes it: F.load / F.music.load sniff and load the inner module) and --- returns that Module with meta.container = { format = "umx", name, version }; without the hook decode is --- Err.UNSUPPORTED. Umx.extract(r) lists every embedded module without decoding it. --- Not supported: Unreal Engine 2+ packages (sounds, .uax), writing. +-- music/umx: Unreal Engine 1 music packages (.umx, versions up to 128), ported from OpenMPT's UMXTools.cpp / +-- ContainerUMX.cpp (BSD, licenses/openmpt-LICENSE.txt): the IT / S3M / XM / MOD module of a "music" export; decode +-- needs opts.decodeModule (the api passes it). Not supported: Unreal Engine 2+ packages (.uax), writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -25,8 +20,8 @@ local Umx = { } export type DecodeOptions = { - decodeModule: ((buf: buffer, format: string?) -> (any, Err.Err?))?, -- loads the inner module (the api passes it) - index: number?, -- which music export to load (1-based, default 1) + decodeModule: ((buf: buffer, format: string?) -> (any, Err.Err?))?, + index: number?, -- 1-based, default 1 } export type Entry = { name: string, data: buffer, format: string? } @@ -104,8 +99,6 @@ function Umx.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- extract(r) -> { { name, data, format? } } | nil, Err: every module embedded in the package's music exports (format: --- a guess from the inner module's signature: "it", "s3m", "xm", "mod") function Umx.extract(r: Bytes.Reader): ({ Entry }?, Err.Err?) local h = header(r) if not h then @@ -210,7 +203,6 @@ function Umx.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the embedded module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function Umx.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local m, err = Umx.decode(r, opts) if not m then diff --git a/src/Rosetta/music/xm/init.luau b/src/Rosetta/music/xm/init.luau index 124701c..bc3efe3 100644 --- a/src/Rosetta/music/xm/init.luau +++ b/src/Rosetta/music/xm/init.luau @@ -1,12 +1,7 @@ --!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/audio/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). --- ModPlug ADPCM samples decode (codecs/audio/Adpcm; written back as plain delta PCM). Not supported: OpenMPT's --- stereo-sample / extra-effect extensions on write. +-- music/xm: FastTracker 2 Extended Modules (XM 1.04), from the XM spec and FT2 behaviour notes. Supports: 8 / 16-bit +-- delta and ModPlug ADPCM samples, envelopes, linear / Amiga tables, every FT2 effect; writes "xm" (byte-identical in +-- FT2's layout) and "mod" modules. Not supported: OpenMPT's stereo-sample / extra-effect extensions on write. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -63,7 +58,6 @@ local function makeEnvelope(xs: { number }, ys: { number }, n: number, typ: numb 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 @@ -106,7 +100,6 @@ function Xm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) 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 @@ -158,7 +151,7 @@ function Xm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) param = pr:u8() end if pr.err then - break -- a short pattern: the rest stays empty + break end if note == 97 then note = 255 @@ -177,7 +170,6 @@ function Xm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end end end - -- instruments and their samples local total = 0 for i = 1, nins do local start = r:tell() @@ -186,7 +178,6 @@ function Xm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) 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 @@ -243,8 +234,7 @@ function Xm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) s.pan = h.pan local frames = h.len // bps if h.res == 0xAD and bits == 8 then - -- ModPlug ADPCM (codecs/audio/Adpcm): a 16-byte delta table, then 4 bits per sample; a cut file keeps - -- the samples whose nibbles are present +-- ModPlug ADPCM: a 16-byte delta table, then 4 bits per sample frames = math.max(0, math.min(h.len, (r:remaining() - 16) * 2)) total += frames * 4 if total > maxBytes then @@ -300,7 +290,6 @@ local function writeName(w: Bytes.Writer, s: string?, n: number) 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 @@ -365,7 +354,7 @@ local function envelopeFields(e: any): (number, number, number, number, number) 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 + typ = raw.type end local function idx(v: number): number return math.clamp(math.floor(v) - 1, 0, math.max(0, n - 1)) @@ -378,7 +367,6 @@ local function envelopeFields(e: any): (number, number, number, number, number) 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 @@ -479,7 +467,6 @@ function Xm.encode(m: any, opts: EncodeOptions?): (buffer?, Err.Err?) w:u16le(buffer.len(data)) w:bytes(data) end - -- instruments for _, it in insts do local ins = it.ins local smps = it.samples @@ -561,7 +548,6 @@ function Xm.encode(m: any, opts: EncodeOptions?): (buffer?, Err.Err?) 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 diff --git a/src/Rosetta/music/xmi/init.luau b/src/Rosetta/music/xmi/init.luau index c559028..5577258 100644 --- a/src/Rosetta/music/xmi/init.luau +++ b/src/Rosetta/music/xmi/init.luau @@ -1,12 +1,7 @@ --!strict --- music/xmi: Miles Sound System XMIDI (IFF: an optional FORM XDIR with the song count, then CAT XMID of FORM XMID songs, --- or one FORM XMID; each with TIMB / RBRN chunks and the EVNT event stream). Written from the XMIDI format description --- (Miles AIL; Ryan Nunn's notes); wildmidi was used only as a reference converter in tests. Decodes one song (opts.track, --- 1-based, default 1) to a Types.Midi (format 0): interval bytes (< 0x80, summed) become absolute ticks, each note-on's --- duration becomes a note-off (velocity 64; notes still sounding at the end-of-track event end there), tempo events are dropped: XMIDI plays at a fixed 120 ticks per second --- (division 60 at 500000 us per quarter). meta.source: songs, song, timbres ({ patch, bank } from TIMB), tempo (the --- first tempo event's value, unused). Renders through codecs/audio/MidiRender. --- Not supported: writing; the RBRN branch table (kept as meta.source.branches = count); MT-32 -> GM program mapping. +-- music/xmi: Miles XMIDI (IFF: optional FORM XDIR, then CAT XMID of FORM XMID songs with TIMB / RBRN / EVNT), from +-- the XMIDI notes (Miles AIL, Ryan Nunn; wildmidi only as a test reference). Decodes one song to a Types.Midi at the +-- fixed 120 ticks per second (division 60). Not supported: writing, the RBRN branch table, MT-32 -> GM mapping. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -45,7 +40,6 @@ local readu8 = buffer.readu8 local DATA = { [8] = 2, [9] = 2, [10] = 2, [11] = 2, [12] = 1, [13] = 1, [14] = 2 } local TYPES = { [8] = "noteOff", [9] = "noteOn", [10] = "aftertouch", [11] = "controller", [12] = "program", [13] = "channelPressure", [14] = "pitchBend" } --- a MIDI variable-length number at p -> value, next p (nil past e) local function vlq(b: buffer, p: number, e: number): (number?, number) local v = 0 for _ = 1, 4 do @@ -70,7 +64,6 @@ local function bytes(b: buffer, p: number, n: number): { number } return t end --- the EVNT stream [p, e) -> events (note-offs merged in), end tick, first tempo | nil, message local function events(b: buffer, p: number, e: number, maxEvents: number): ({ Types.MidiEvent }?, any, number?) local list: { Types.MidiEvent }, offs: { Render.PendingOff } = {}, {} local tick, tempo = 0, nil @@ -137,7 +130,6 @@ local function events(b: buffer, p: number, e: number, maxEvents: number): ({ Ty return Render.merge(list, offs), tick, tempo end --- the songs: { { evnt = Chunk, timb = Chunk? } } from the IFF tree local function songs(b: buffer, base: number, limit: number): { { [string]: Chunks.Chunk } } local out = {} local function form(c: Chunks.Chunk) @@ -203,7 +195,6 @@ function Xmi.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Midi?, Err.Er end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> the rendered audio Decoder (opts: DecodeOptions + MidiRender.RenderOptions) function Xmi.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local midi, err = Xmi.decode(r, opts) if not midi then diff --git a/src/Rosetta/video/avi/init.luau b/src/Rosetta/video/avi/init.luau index 60b37da..0196896 100644 --- a/src/Rosetta/video/avi/init.luau +++ b/src/Rosetta/video/avi/init.luau @@ -1,13 +1,7 @@ --!strict --- video/avi: AVI (Microsoft RIFF AVI 1.0, OpenDML 1.02). New in rosetta, on containers/Avi. --- Read: open() indexes every stream (OpenDML super / standard indexes, else idx1, else a movi scan; RIFF AVIX pieces --- of files over 1 GB) and returns a VideoDecoder: video through the codecs/video/Video registry by FourCC (MJPEG, MPEG-1, --- uncompressed BI_RGB 24 / 32-bit bottom-up or top-down, I420 / YV12; H.264 and others when a decoder is --- registered), audio through the api's opts.openAudio hook (PCM, A-law / mu-law, IMA / MS ADPCM with its WAVEFORMATEX, --- MP3 / MP2, AAC). Dropped frames (empty video chunks) keep their time slot. Avi.demux(r) gives the Demuxer. --- Write: MJPEG video (copied from an MJPEG source, else every frame encoded; variable frame delays such as a GIF's --- become a constant rate with repeated frames) plus PCM s16 audio, AVI 1.0 with idx1 and an odml / dmlh header. --- Not supported: writing files over 1 GB (no AVIX pieces), palette changes (##pc chunks are skipped), text streams. +-- video/avi: AVI (RIFF AVI 1.0, OpenDML 1.02: super / standard indexes, idx1, AVIX pieces). Reads video through the +-- codecs/video/Video registry by FourCC and audio through opts.openAudio; dropped frames keep their slot. Writes +-- MJPEG + PCM s16 (AVI 1.0, idx1, odml). Not supported: writing over 1 GB, palette changes (##pc), text streams. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -30,18 +24,18 @@ local AviFormat = { -- ------------------------------------------------------------------------------------------------ types export type OpenOptions = { - rgba: boolean?, -- nextFrame returns rgba8 (default false: the codec's native yuv420p; BI_RGB gives rgba8) - track: number?, -- the video track (stream index + 1) to decode - audio: boolean?, -- false: do not open the audio track + rgba: boolean?, -- default false: yuv420p; BI_RGB gives rgba8 + track: number?, -- stream index + 1 + audio: boolean?, maxPixels: number?, openAudio: any?, -- set by the api } export type EncodeOptions = { - quality: number?, -- MJPEG quality 1..100 (default 90) - reencode: boolean?, -- encode the frames even when the source is MJPEG - audio: boolean?, -- false: no audio (default: PCM s16 from the source's audio, when it has one) + quality: number?, -- 1..100, default 90 + reencode: boolean?, + audio: boolean?, -- default: PCM s16 from the source's audio video: boolean?, - maxFps: number?, -- the highest frame rate variable delays may need (default 100) + maxFps: number?, -- default 100 } -- ------------------------------------------------------------------------------------------------ constants @@ -170,7 +164,6 @@ local function audioTrack(s: Avi.Stream, id: number): Types.Track return t end --- demux(r, opts?) -> the Demuxer | nil, Err function AviFormat.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) local ok, file, err = pcall(Avi.read, r.buf, r.base, r.limit) if not ok then @@ -197,7 +190,6 @@ function AviFormat.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) end local meta = { info = file.info, index = file.index, odml = file.odml ~= nil } local dmx = Demux.new("avi", tracks, r.buf, meta) - -- packets in file order across streams: merge by offset local items: { { number } } = {} for k, st in streams do local s: Avi.Stream, t: any = st[1], st[2] @@ -227,7 +219,6 @@ function AviFormat.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ encode --- encode(video, opts?) -> buffer | nil, Err function AviFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: any = table.clone(opts or {}) o.quality = o.quality or 90 @@ -278,7 +269,6 @@ function AviFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) table.insert(wstreams, { type = "auds", handler = "\0\0\0\0", scale = align, rate = rate * align, sampleSize = align, strf = wf:finish(), ckid = "wb" }) end end - -- chunks in time order (the video packets already repeated to the constant rate) local chunks: { { any } } = {} for _, item in Source.interleave(streams) do table.insert(chunks, { item[1], item[2].data, true }) @@ -291,7 +281,6 @@ function AviFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> a VideoDecoder | nil, Err function AviFormat.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) local dmx, err = AviFormat.demux(r, opts) if not dmx then diff --git a/src/Rosetta/video/fli/init.luau b/src/Rosetta/video/fli/init.luau index ac01974..f34ed25 100644 --- a/src/Rosetta/video/fli/init.luau +++ b/src/Rosetta/video/fli/init.luau @@ -1,12 +1,7 @@ --!strict --- video/fli: Autodesk Animator FLI / Animator Pro FLC / FLX animations. New in rosetta, written from the FLIC --- file format description (Jim Kent, "FLC - Animator Pro Flic Files"; MultimediaWiki "FLIC"). --- Read: the 128-byte header (FLI 0xAF11: speed in 1/70 s; FLC 0xAF12 / DTA 0xAF44: speed in ms; depth 8, 15, 16, 24: --- an FLC that says 16 bits holds 5-5-5 pixels, as Animator Pro wrote them), prefix and other non-frame chunks skipped, --- every frame chunk (0xF1FA, and 0xF5FA) a packet of a Demuxer; open() returns a VideoDecoder whose frames are rgba8 --- (codecs/video/Legacy: palette chunks, BRUN, LC, SS2, BLACK, COPY, the deep-colour DTA chunks). The ring frame (the --- extra frame after `frames` that leads back to the first) is not shown. Fli.demux(r) gives the Demuxer. --- Not supported: writing, 1-bit FLICs, the X-COM / Magic Carpet game variants (audio chunks, 6-bit COLOR_256). +-- video/fli: Autodesk FLI / FLC / FLX animations, from Jim Kent's "FLC - Animator Pro Flic Files" (MultimediaWiki +-- "FLIC"): magics 0xAF11 (speed in 1/70 s), 0xAF12 / 0xAF44 (ms); frame chunks 0xF1FA / 0xF5FA, rgba8 through +-- codecs/video/Legacy; the ring frame is not shown. Not supported: writing, 1-bit FLICs, X-COM / Magic Carpet variants. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -27,9 +22,9 @@ local Fli = { -- ------------------------------------------------------------------------------------------------ types export type OpenOptions = { - rgba: boolean?, -- (frames are rgba8 already) + rgba: boolean?, -- frames are rgba8 already maxPixels: number?, -- default 2^26 - ringFrame: boolean?, -- true: also show the ring frame at the end (as ffmpeg does) + ringFrame: boolean?, -- also show the ring frame (as ffmpeg) } -- ------------------------------------------------------------------------------------------------ constants @@ -56,7 +51,6 @@ function Fli.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- demux(r, opts?) -> the Demuxer | nil, Err function Fli.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) local b, base, limit = r.buf, r.base, r.limit local n = limit - base @@ -108,7 +102,6 @@ function Fli.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) default = true, bitsPerPixel = depth, } - -- the frame chunks local offs, sizes = {}, {} local p = base + HEADER while p + 6 <= limit do @@ -119,7 +112,7 @@ function Fli.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) end if (cm == FRAME or cm == FRAME2) and size > 6 then if p + size > limit then - break -- a truncated last frame + break end table.insert(offs, p) table.insert(sizes, size) @@ -145,7 +138,6 @@ function Fli.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> a VideoDecoder | nil, Err function Fli.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) local dmx, err = Fli.demux(r, opts) if not dmx then diff --git a/src/Rosetta/video/flv/Amf.luau b/src/Rosetta/video/flv/Amf.luau index 98fe321..4c30ece 100644 --- a/src/Rosetta/video/flv/Amf.luau +++ b/src/Rosetta/video/flv/Amf.luau @@ -1,11 +1,6 @@ --!strict --- video/flv/Amf: AMF0 values (Adobe's Action Message Format 0, as FLV script data tags use it). Written from the AMF0 --- specification and the FLV specification v10. Read: number, boolean, string, object, null, undefined, reference --- (the referenced object), ECMA array, strict array, date (milliseconds), long string; anything else stops the --- value. Write: numbers, booleans, strings, strict arrays and ECMA arrays (ordered key / value lists). Never throws. --- --- local name, value = Amf.script(reader) -- a script tag body: "onMetaData", { duration = 12.3, ... } --- Amf.writeValue(w, v); Amf.writeEcma(w, { { "duration", 12.3 }, ... }) +-- video/flv/Amf: AMF0 values (AMF0 spec, FLV spec v10 script tags). Read: number, boolean, string, object, null, +-- undefined, reference, ECMA / strict array, date (ms), long string. Write: numbers, booleans, strings, arrays. local Bytes = require("@rosetta/core/Bytes") local Amf = {} @@ -90,13 +85,11 @@ readValue = function(r: Bytes.Reader, depth: number, refs: { any }): any return nil end --- value(reader) -> the next AMF0 value | nil (unknown type, truncated, nested too deep) function Amf.value(r: Bytes.Reader): any local ok, v = pcall(readValue, r, 0, {}) return if ok and not r.err then v else nil end --- script(reader) -> name, value: a script data tag body (an AMF0 string, then its value) | nil function Amf.script(r: Bytes.Reader): (string?, any) local name = Amf.value(r) if type(name) ~= "string" then @@ -117,7 +110,6 @@ local function writeString(w: Bytes.Writer, s: string) w:string(s) end --- writeValue(w, v): a number, boolean, string, array (strict array) or Amf.NULL; other values are written as null function Amf.writeValue(w: Bytes.Writer, v: any) local t = type(v) if t == "number" then @@ -139,8 +131,6 @@ function Amf.writeValue(w: Bytes.Writer, v: any) end end --- writeEcma(w, list): an ECMA array of { key, value } pairs (values: as writeValue; a list nested as --- { key, { pairs = { ... } } } becomes an object) function Amf.writeEcma(w: Bytes.Writer, list: { { any } }, object: boolean?) if object then w:u8(3) diff --git a/src/Rosetta/video/flv/Mux.luau b/src/Rosetta/video/flv/Mux.luau index b3f7749..8e4da8a 100644 --- a/src/Rosetta/video/flv/Mux.luau +++ b/src/Rosetta/video/flv/Mux.luau @@ -1,10 +1,6 @@ --!strict --- video/flv/Mux: the FLV writer (Adobe's Video File Format Specification v10): the header, an onMetaData script tag --- (duration, width, height, data rates, frame rate, codec ids, audio format, encoder, file size), the H.264 --- AVCDecoderConfigurationRecord / AAC AudioSpecificConfig sequence headers, the packets of codecs/video/Video/Source --- streams as tags interleaved by decode time (milliseconds, shifted so none is negative; H.264 composition times), --- and H.264's end-of-sequence tag. AAC from ADTS sources (MPEG-TS) is split into raw frames with a configuration made --- from the first ADTS header. Interpreted; never throws (returns nil, Err). +-- video/flv/Mux: the FLV writer (FLV spec v10): header, onMetaData, AVC / AAC sequence headers, tags interleaved by +-- decode time (ms, shifted so none is negative), H.264 end of sequence; ADTS AAC split into raw frames. local Err = require("@rosetta/core/Err") local Bytes = require("@rosetta/core/Bytes") local Amf = require("@rosetta/video/flv/Amf") @@ -30,7 +26,6 @@ local function isAdts(s: any): boolean return s.config == nil and p ~= nil and buffer.len(p.data) >= 7 and buffer.readu8(p.data, 0) == 0xFF and buffer.readu8(p.data, 1) >= 0xF0 end --- audioProblem(stream) -> why FLV cannot hold this audio stream | nil function Mux.audioProblem(s: any): string? local fmt = AUDIO_FORMATS[s.codec] if not fmt then @@ -124,7 +119,6 @@ local function f64At(b: buffer, at: number, v: number) end end --- mux(streams) -> buffer | nil, Err function Mux.mux(streams: { any }): (buffer?, Err.Err?) local video, audio = nil :: any, nil :: any for _, s in streams do @@ -167,7 +161,6 @@ function Mux.mux(streams: { any }): (buffer?, Err.Err?) end end end - -- times: milliseconds, shifted so the earliest decode time is 0 when any is negative local shift = 0 local duration = 0 local vBytes, aBytes = 0, 0 @@ -211,7 +204,6 @@ function Mux.mux(streams: { any }): (buffer?, Err.Err?) w:u32be(11 + n) end - -- onMetaData local props: { { any } } = { { "duration", duration } } if video then table.insert(props, { "width", video.width or 0 }) @@ -238,7 +230,6 @@ function Mux.mux(streams: { any }): (buffer?, Err.Err?) tag(18, 0, {}, metaBody) local fileSizeAt = metaAt + buffer.len(metaBody) - 3 - 8 -- the last value (filesize) before the end marker - -- sequence headers local vid = if video then VIDEO_IDS[video.codec] else 0 if video and video.codec == "h264" then tag(9, 0, { 0x10 + vid, 0, 0, 0, 0 }, video.config) diff --git a/src/Rosetta/video/flv/init.luau b/src/Rosetta/video/flv/init.luau index fc4c95d..c42d473 100644 --- a/src/Rosetta/video/flv/init.luau +++ b/src/Rosetta/video/flv/init.luau @@ -1,20 +1,7 @@ --!strict --- video/flv: Flash Video (FLV, Adobe's Video File Format Specification v10, and the Enhanced RTMP / FLV extension's --- FourCC video tags). New in rosetta. --- Read: the header, the tag stream and onMetaData (AMF0: duration, width, height, framerate, codec ids, keyframes, ... --- into meta.metadata) into a Demuxer (times in milliseconds; keyframe flags from the video tags; seeking by --- keyframes) and open() returns a VideoDecoder: video through the codecs/video/Video registry (Sorenson Spark / FLV1 --- and H.264 decode; VP6 / VP6 alpha, screen video 1 / 2 and enhanced FourCC codecs (HEVC, AV1, VP9) are known tracks --- whose decoding is UNSUPPORTED); H.264's AVCDecoderConfigurationRecord in track.config, composition time offsets --- in the pts. Audio through the api's opts.openAudio hook: MP3 (also 8 kHz), AAC (AudioSpecificConfig in track.config), --- linear PCM (platform-endian read as little-endian), A-law / mu-law, Flash ADPCM (codecs/audio/Adpcm.swf, through --- containers/AudioWrap); Nellymoser and Speex are known tracks without an audio decoder (UNSUPPORTED). Flv.demux(r) gives the Demuxer. --- Write: H.264 / Sorenson Spark / VP6 / screen video copied from the source (FLV has no codec we encode), AAC / MP3 / --- PCM / A-law / mu-law / ADPCM / Nellymoser / Speex audio copied (AAC from ADTS sources re-framed), else PCM s16 at --- the FLV sample rates (5512 / 11025 / 22050 / 44100 Hz), with onMetaData (duration, sizes, frame rate, data --- rates, codec ids, file size). --- Not supported: encrypted tags (the track's packets are dropped, track.unsupported says so), multitrack and ModEx --- enhanced packets (skipped), writing H.264 from Annex B sources (no avcC). +-- video/flv: Flash Video (Adobe FLV spec v10, Enhanced RTMP FourCC tags). Reads the tags and onMetaData (AMF0) into a +-- Demuxer; decodes Sorenson Spark and H.264 (other codecs are UNSUPPORTED tracks), audio through opts.openAudio. +-- Writes copied packets, else PCM s16 at 5512..44100 Hz. Not supported: encrypted tags, multitrack / ModEx packets. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -41,17 +28,17 @@ local Flv = { -- ------------------------------------------------------------------------------------------------ types export type OpenOptions = { - rgba: boolean?, -- nextFrame returns rgba8 images (default false: yuv420p from the codec) - track: number?, -- the video track id (1 video, 2 audio) - audio: boolean?, -- false: do not open the audio track - maxPackets: number?, -- refuse files with more tags (default 2^24) + rgba: boolean?, -- default false: yuv420p + track: number?, -- 1 video, 2 audio + audio: boolean?, + maxPackets: number?, -- default 2^24 maxPixels: number?, openAudio: any?, -- set by the api: (demuxer, track) -> audio Decoder } export type EncodeOptions = { - video: boolean?, -- false: no video - audio: boolean?, -- false: no audio; true: fail when the audio cannot be written (default: dropped) - reencodeAudio: boolean?, -- PCM s16 even when the audio could be copied + video: boolean?, + audio: boolean?, -- true: fail when the audio cannot be written (default: dropped) + reencodeAudio: boolean?, } -- ------------------------------------------------------------------------------------------------ constants @@ -118,7 +105,6 @@ local function copy(b: buffer, p: number, n: number): buffer return c end --- the picture size of a codec's first keyframe (Sorenson, VP6, screen video) | nil local function frameSize(codec: string, b: buffer, p: number, n: number): (number?, number?) if codec == "flv1" then local h = H263.header(b, p, n, true) @@ -152,7 +138,6 @@ local function frameSize(codec: string, b: buffer, p: number, n: number): (numbe return nil, nil end --- demux(r, opts?) -> the Demuxer (containers/Demux) | nil, Err function Flv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) local o: OpenOptions = opts or {} local b, base, limit = r.buf, r.base, r.limit @@ -169,7 +154,7 @@ function Flv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) local tracks: { Types.Track } = {} local dmx = Demux.new("flv", tracks, b, meta) local vt: any, at: any = nil, nil - local keyOff, keyLen = -1, 0 -- the first video keyframe + local keyOff, keyLen = -1, 0 local maxPackets = o.maxPackets or 2 ^ 24 local count = 0 local p = base + dataOffset + 4 -- after PreviousTagSize0 @@ -316,7 +301,6 @@ function Flv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) end p = d + size + 4 end - -- the track facts onMetaData and the codec headers give local md: { [string]: any } = meta.metadata or {} if type(md.duration) == "number" and md.duration > 0 then meta.duration = md.duration @@ -338,7 +322,6 @@ function Flv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) if type(fr) == "number" and fr > 0 and fr < 1000 then vt.frameRate = fr else - -- from the timestamps: the frames over the time they span local n = dmx:count(vt.id) local t0 = if n > 0 then dmx:info(vt.id, 1) else nil local t1 = if n > 1 then dmx:info(vt.id, n) else nil @@ -355,7 +338,6 @@ function Flv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ encode --- encode(video, opts?) -> buffer | nil, Err: a VideoDecoder (F.load / F.video.open) or a Demuxer function Flv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: any = opts or {} local streams, err = Source.streams(value, o, { @@ -365,7 +347,6 @@ function Flv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) if not streams then return nil, err end - -- audio FLV cannot hold (PCM at other rates): dropped, or an error with opts.audio = true for i = #streams, 1, -1 do local s = streams[i] local why = s.kind == "audio" and Mux.audioProblem(s) @@ -387,7 +368,6 @@ function Flv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> a VideoDecoder (kind "video": nextFrame / seek / audio / demuxer) | nil, Err function Flv.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) local ok, dmx, err = pcall(Flv.demux, r, opts) if not ok then diff --git a/src/Rosetta/video/h264/init.luau b/src/Rosetta/video/h264/init.luau index 30811c3..ee08e6b 100644 --- a/src/Rosetta/video/h264/init.luau +++ b/src/Rosetta/video/h264/init.luau @@ -1,12 +1,7 @@ --!strict --- video/h264: raw H.264 / AVC elementary streams (ITU-T H.264 Annex B byte stream: .h264 / .264 files, x264 / ffmpeg --- `-f h264` output, the JVT conformance bitstreams). New in rosetta. --- Read: the stream cut into access units (codecs/video/H264.accessUnits) as a one-track Demuxer; open() returns a --- VideoDecoder decoding through codecs/video/H264 (yuv420p frames in display order, numbered in output order since a raw --- stream has no timestamps; the frame rate comes from the SPS VUI timing, else opts.frameRate, else 25). --- Write: H.264 tracks copied from any video (MP4 / MKV samples are converted from length-prefixed NAL units to Annex B, --- the avcC parameter sets put in front of every keyframe). Not supported: re-encoding other codecs to H.264 (there is --- no H.264 encoder), and whatever codecs/video/H264 does not decode (interlaced, 4:2:2 / 4:4:4, > 8 bits: UNSUPPORTED). +-- video/h264: raw H.264 Annex B byte streams (.h264 / .264), cut into access units and decoded by codecs/video/H264 +-- (frame rate: the SPS VUI, else opts.frameRate, else 25). Writes H.264 tracks copied from any video (avcC to Annex B). +-- Not supported: encoding other codecs, what codecs/video/H264 does not decode (interlaced, 4:2:2 / 4:4:4, > 8 bits). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -29,10 +24,10 @@ local Format = { -- ------------------------------------------------------------------------------------------------ types export type OpenOptions = { - rgba: boolean?, -- nextFrame returns rgba8 (default false: yuv420p) - maxPixels: number?, -- largest picture (default 2^22 luma samples) - frameRate: number?, -- frames per second when the stream has no VUI timing (default 25) - deblock: boolean?, -- false skips the deblocking filter (faster, not conformant) + rgba: boolean?, -- default false: yuv420p + maxPixels: number?, -- default 2^22 luma samples + frameRate: number?, -- default 25 + deblock: boolean?, -- false: faster, not conformant } -- ------------------------------------------------------------------------------------------------ sniff @@ -65,7 +60,6 @@ function Format.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- demux(r, opts?) -> the Demuxer (one video track, one packet per access unit) | nil, Err function Format.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) local buf, base, limit = r.buf, r.base, r.limit local units = H264.accessUnits(buf, base, limit - base) @@ -106,7 +100,6 @@ function Format.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ encode --- encode(video, opts?) -> an Annex B buffer of the source's H.264 track | nil, Err (UNSUPPORTED for other codecs) function Format.encode(value: any, _opts: any?): (buffer?, Err.Err?) local streams, err = Source.streams(value, { audio = false }, { video = { copy = { h264 = true } } }) if not streams then @@ -133,7 +126,6 @@ function Format.encode(value: any, _opts: any?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> a VideoDecoder | nil, Err function Format.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) local dmx, err = Format.demux(r, opts) if not dmx then diff --git a/src/Rosetta/video/mkv/Mux.luau b/src/Rosetta/video/mkv/Mux.luau index 5c7408b..5e367f2 100644 --- a/src/Rosetta/video/mkv/Mux.luau +++ b/src/Rosetta/video/mkv/Mux.luau @@ -1,9 +1,6 @@ --!strict --- video/mkv/Mux: the Matroska / WebM muxer: EBML header, Segment with SeekHead, Info (1 ms TimecodeScale, Duration), --- Tracks (CodecPrivate, DefaultDuration, Video / Audio settings, Opus CodecDelay / SeekPreRoll), Clusters of --- SimpleBlocks (a new cluster at a video keyframe once the current one spans 2 s, and before the 16-bit relative --- timestamp would overflow), and Cues (one CuePoint per cluster, on the video track when there is one). Streams come --- from codecs/video/Video/Source (copied packets or encoded frames). Interpreted; never throws. +-- video/mkv/Mux: the Matroska / WebM muxer: EBML header, Segment (SeekHead, Info with a 1 ms TimecodeScale, Tracks, +-- Clusters of SimpleBlocks cut at keyframes after 2 s or before the 16-bit timestamp overflows, a CuePoint each). local Err = require("@rosetta/core/Err") local Ebml = require("@rosetta/containers/Ebml") local Video = require("@rosetta/codecs/video/Video") @@ -36,7 +33,6 @@ local AUDIO_IDS: { [string]: string } = { } Mux.AUDIO_IDS = AUDIO_IDS --- codecId(stream) -> the Matroska CodecID | nil function Mux.codecId(kind: string, codec: string): string? if kind == "video" then local e = Video.entry(codec) @@ -64,12 +60,10 @@ export type Options = { clusterSeconds: number?, -- default 2 } --- mux(streams, opts) -> buffer | nil, Err function Mux.mux(streams: { any }, opts: Options): (buffer?, Err.Err?) local webm = opts.webm == true local app = opts.app or "rosetta" local clusterSpan = opts.clusterSeconds or 2 - -- tracks local ids: { string } = {} local videoIndex = 0 for i, s in streams do @@ -150,7 +144,6 @@ function Mux.mux(streams: { any }, opts: Options): (buffer?, Err.Err?) end body:close(tracks) - -- clusters local cues: { { number } } = {} -- { time ms, track, cluster offset in body } local cl: number? = nil local clTime = 0 @@ -264,7 +257,6 @@ function Mux.mux(streams: { any }, opts: Options): (buffer?, Err.Err?) bodyBuf = nb end - -- the file local out = Ebml.writer(buffer.len(bodyBuf) + 256) local eb = out:open(ID.EBML) out:uint(0x4286, 1) diff --git a/src/Rosetta/video/mkv/Parse.luau b/src/Rosetta/video/mkv/Parse.luau index 1a64348..ecc0964 100644 --- a/src/Rosetta/video/mkv/Parse.luau +++ b/src/Rosetta/video/mkv/Parse.luau @@ -1,9 +1,6 @@ --!strict --- video/mkv/Parse: the Matroska / WebM demuxer: EBML header, Segment Info / Tracks / Cues / Tags / Chapters (titles --- only), and every Cluster into a containers/Demux packet index: SimpleBlock and BlockGroup (BlockDuration, --- ReferenceBlock -> not a keyframe), the three lacings (Xiph, EBML, fixed), header-stripping content compression, --- clusters of unknown size (live streams). Times: every track's timescale is 1e9 / TimecodeScale (milliseconds by --- default). Interpreted (it only walks headers); never throws. +-- video/mkv/Parse: the Matroska / WebM demuxer: EBML header, Info / Tracks / Cues / Tags / chapter titles, Clusters +-- (SimpleBlock, BlockGroup, Xiph / EBML / fixed lacing, unknown sizes); timescale 1e9 / TimecodeScale. local Err = require("@rosetta/core/Err") local Types = require("@rosetta/Types") local Ebml = require("@rosetta/containers/Ebml") @@ -138,7 +135,6 @@ local SUBS: { [string]: string } = { ["S_HDMV/PGS"] = "pgs", } --- codecFor(CodecID, bitDepth) -> our codec id local function codecFor(id: string, kind: string, bits: number?): string if kind == "video" then return Video.fromMatroska(id) or string.lower((string.gsub(id, "^V_", ""))) @@ -219,8 +215,7 @@ local function parseAudio(buf: buffer, off: number, len: number, t: any) end end --- ContentEncodings: header stripping (algo 3) and zlib (algo 0) are supported; bzip / lzo compression and encryption --- are not +-- ContentEncodings: header stripping (algo 3) and zlib (algo 0); not bzip / lzo or encryption local function parseEncodings(buf: buffer, off: number, len: number, t: any): string? for id, o, n in Ebml.children(buf, off, off + len) do if id == ID.ContentEncoding then @@ -418,7 +413,7 @@ type Ctx = { maxPackets: number, } --- one Block / SimpleBlock payload at [off, off + len): track, relative timecode, flags, lacing +-- Block / SimpleBlock: track, relative timecode, flags, lacing local function block(ctx: Ctx, off: number, len: number, clusterTime: number, simple: boolean, keyHint: boolean?, durTicks: number?, discardNs: number?) local buf = ctx.buf local limit = off + len @@ -543,7 +538,6 @@ local function block(ctx: Ctx, off: number, len: number, clusterTime: number, si end end --- a Cluster's children from off to limit (an unknown-size cluster: until a top-level ID); returns where it ended local function cluster(ctx: Ctx, off: number, limit: number, unknown: boolean): number local buf = ctx.buf local pos = off @@ -591,9 +585,6 @@ end export type Options = { maxPackets: number? } --- parse(buf, base, limit, opts) -> a Demux | nil, Err --- docType(buf, base, limit) -> the EBML header's DocType ("matroska" when it has none), the header's size and data --- offset | nil, Err function Parse.docType(buf: buffer, base: number, limit: number): (string?, any, number?) local id, size, data = Ebml.header(buf, base, limit) if id ~= ID.EBML or not size or not data then @@ -620,7 +611,6 @@ function Parse.parse(buf: buffer, base: number, limit: number, opts: Options?): return nil, Err.new(Err.UNSUPPORTED, "EBML document type " .. docType) end local pos = data + size - -- the Segment (skip anything else at the top level) local segData, segEnd = -1, limit while pos < limit do local sid, ssize, sdata = Ebml.header(buf, pos, limit) @@ -663,7 +653,6 @@ function Parse.parse(buf: buffer, base: number, limit: number, opts: Options?): tracks, problems = parseTracks(buf, cdata, cend - cdata, scaleNs) elseif cid == ID.Cluster then if unknown then - -- find its end: walk children until a top-level ID local p = cdata while p < segEnd do local xid, xsize, xdata = Ebml.header(buf, p, segEnd) diff --git a/src/Rosetta/video/mkv/init.luau b/src/Rosetta/video/mkv/init.luau index db5e356..430f9af 100644 --- a/src/Rosetta/video/mkv/init.luau +++ b/src/Rosetta/video/mkv/init.luau @@ -1,16 +1,7 @@ --!strict --- video/mkv: Matroska and WebM (the Matroska specification / RFC 9559, the WebM container guidelines). New in --- rosetta, on containers/Ebml. --- Read: open() demuxes the whole file into a packet index (SimpleBlock / BlockGroup, Xiph / EBML / fixed lacing, --- header-stripping and zlib compression, unknown-size clusters, Cues and Tags in meta) and returns a VideoDecoder: video --- through the codecs/video/Video registry (VP8 with inter frames, MJPEG, MPEG-1, raw; H.264 when registered), audio --- through the api's opts.openAudio hook (Opus, Vorbis, FLAC, MP3, PCM, AAC, ... reach the audio formats), text --- subtitle tracks as cues (Mkv.subtitles). Mkv.demux(r) gives the Demuxer alone. --- Write: WebM (opts.format = "webm" or a .webm destination: VP8 / VP9 / AV1 video and Opus / Vorbis audio, copied --- from the source since VP8 is decode-only) and Matroska (any registered video codec copied, else MJPEG encoded from --- the frames; audio copied, else PCM s16), with SeekHead, Cues and Duration. --- Not supported: bzip2 / lzo content compression and encryption (the track's packets are left as stored, --- track.unsupported says why), chapters / attachments (skipped), writing subtitles. +-- video/mkv: Matroska / WebM (RFC 9559, the WebM guidelines), on containers/Ebml. Reads every packet (all lacings, +-- header stripping and zlib, unknown-size clusters, Cues, Tags) into a Demuxer, text subtitle tracks as cues. Writes +-- WebM or Matroska (copied, else MJPEG + PCM s16). Not supported: bzip2 / lzo, encryption, chapters, attachments. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -33,22 +24,22 @@ local Mkv = { -- ------------------------------------------------------------------------------------------------ types export type OpenOptions = { - rgba: boolean?, -- nextFrame returns rgba8 images (default false: yuv420p from the codec) - track: number?, -- the video track number to decode (default: the first video track) - audio: boolean?, -- false: do not open the audio track - maxPackets: number?, -- refuse files with more packets (default 2^24) + rgba: boolean?, -- default false: yuv420p + track: number?, -- default: the first video track + audio: boolean?, + maxPackets: number?, -- default 2^24 maxPixels: number?, openAudio: any?, -- set by the api: (demuxer, track) -> audio Decoder } export type EncodeOptions = { - format: string?, -- "webm" writes WebM (DocType webm, WebM codecs only); else Matroska - webm: boolean?, -- the same as format = "webm" - quality: number?, -- MJPEG quality 1..100 when frames are encoded (default 90) - reencode: boolean?, -- encode the frames even when the video track could be copied (Matroska: MJPEG) - video: boolean?, -- false: no video stream - audio: boolean?, -- false: no audio; true: fail if the audio cannot be written (default: dropped) + format: string?, -- "webm": DocType webm, WebM codecs only; else Matroska + webm: boolean?, -- as format = "webm" + quality: number?, -- 1..100, default 90 + reencode: boolean?, + video: boolean?, + audio: boolean?, -- true: fail if the audio cannot be written (default: dropped) title: string?, - clusterSeconds: number?, -- target cluster length (default 2) + clusterSeconds: number?, -- seconds, default 2 } -- ------------------------------------------------------------------------------------------------ constants @@ -67,7 +58,6 @@ function Mkv.sniff(r: Bytes.Reader): number return 0.5 end --- variant(r) -> "webm" for a WebM file (DocType webm), else nil: the name F.detect reports (never throws) function Mkv.variant(r: Bytes.Reader): string? local ok, docType = pcall(Parse.docType, r.buf, r.pos, r.limit) if ok and docType == "webm" then @@ -77,8 +67,6 @@ function Mkv.variant(r: Bytes.Reader): string? end -- ------------------------------------------------------------------------------------------------ encode --- encode(video, opts?) -> buffer | nil, Err: a VideoDecoder (F.load / F.video.open of any video or animated image) --- or a Demuxer function Mkv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: any = opts or {} local webm = o.webm == true or (type(o.format) == "string" and string.lower(o.format) == "webm") @@ -121,7 +109,6 @@ function Mkv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- demux(r, opts?) -> the Demuxer (containers/Demux: tracks, packets, read, seek, count / get) | nil, Err function Mkv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) local ok, dmx, err = pcall(Parse.parse, r.buf, r.base, r.limit, opts) if not ok then @@ -130,7 +117,6 @@ function Mkv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) return dmx, err end --- open(r, opts?) -> a VideoDecoder (kind "video": nextFrame / seek / audio / demuxer) | nil, Err function Mkv.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) local dmx, err = Mkv.demux(r, opts) if not dmx then @@ -140,7 +126,6 @@ function Mkv.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Er end -- ------------------------------------------------------------------------------------------------ extras --- subtitles(demuxer, trackId?) -> Types.Subtitles from a text subtitle track (S_TEXT/UTF8, WebVTT, ASS text) | nil function Mkv.subtitles(dmx: any, trackId: number?): Types.Subtitles? local track = nil for _, t in dmx.tracks do diff --git a/src/Rosetta/video/mp4/init.luau b/src/Rosetta/video/mp4/init.luau index 1d76faa..4358c59 100644 --- a/src/Rosetta/video/mp4/init.luau +++ b/src/Rosetta/video/mp4/init.luau @@ -1,18 +1,7 @@ --!strict --- video/mp4: MP4 / M4V / QuickTime MOV / 3GP (ISO/IEC 14496-12 / 14496-14, the QuickTime file format), on --- containers/IsoBmff (ws-m4a's box parser, sample tables, fragments and muxer). New in rosetta. --- Read: every track's samples into a Demuxer (pts = dts + composition offset, moved by the edit list: the first --- edit's media time is subtracted (B-frame delay, AAC priming), an initial empty edit added; sync samples as --- keyframes; fragmented files too) and open() returns a VideoDecoder: video through the codecs/video/Video registry (MJPEG --- 'jpeg' / 'mjpa' / mp4v 0x6C, MPEG-1, raw; H.264 'avc1' with its avcC when a decoder is registered), audio through --- the api's opts.openAudio hook (AAC, ALAC (audio/m4a), MP3, Opus (dOps -> OpusHead), FLAC, PCM 'sowt' / 'twos' / --- 'lpcm' / 'ipcm'). --- Write: MP4 (or MOV with opts.format = "mov" / a .mov destination): H.264 / HEVC / AV1 / MJPEG / MPEG-4 video copied --- from an ISO / Matroska source (their configurations are the same boxes), else MJPEG encoded from the frames (mp4v --- object type 0x6C in MP4, 'jpeg' in MOV); AAC / ALAC / Opus / FLAC / MP3 audio copied, else PCM s16 ('sowt', MOV --- only; MP4 drops other audio unless opts.audio = true, which fails). --- Edit lists are written for a B-frame delay and an audio codec delay (AAC priming). Not supported: fragmented --- writing, timed text tracks, encrypted tracks. +-- video/mp4: MP4 / M4V / MOV / 3GP (ISO/IEC 14496-12 / 14496-14, QuickTime), on containers/IsoBmff. Reads every +-- track into a Demuxer (pts = dts + composition offset, moved by the edit list; fragments too). Writes MP4 or MOV: +-- video copied, else MJPEG; audio copied, else PCM s16 (MOV). Not supported: fragmented writing, timed text, DRM. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -36,18 +25,18 @@ local Mp4 = { -- ------------------------------------------------------------------------------------------------ types export type OpenOptions = { rgba: boolean?, - track: number?, -- the video track id (default: the first video track) + track: number?, -- default: the first video track audio: boolean?, maxPixels: number?, maxSamples: number?, openAudio: any?, -- set by the api } export type EncodeOptions = { - format: string?, -- "mov" writes QuickTime (brand 'qt '); else MP4 (brand 'isom') - quality: number?, -- MJPEG quality when frames are encoded (default 90) - reencode: boolean?, -- encode the frames to MJPEG even when the video could be copied + format: string?, -- "mov": QuickTime (brand 'qt '); else MP4 (brand 'isom') + quality: number?, -- default 90 + reencode: boolean?, video: boolean?, - audio: boolean?, -- false: no audio; true: fail when the audio cannot be written + audio: boolean?, -- true: fail when the audio cannot be written } -- ------------------------------------------------------------------------------------------------ constants @@ -106,7 +95,6 @@ local function pcmCodec(t: any): string return "pcm_s" .. bits .. (if p == nil or p.little then "le" else "be") end --- demux(r, opts?) -> the Demuxer | nil, Err function Mp4.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) local ok, movie, err = pcall(IsoBmff.parse, r, opts and opts.maxSamples and { maxSamples = opts.maxSamples } or nil) if not ok then @@ -164,7 +152,6 @@ function Mp4.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) table.insert(src, it) end local dmx = Demux.new(if movie.brand == "qt " then "mov" else "mp4", tracks, r.buf, { brand = movie.brand }) - -- samples in file order across tracks local items: { { number } } = {} for k, it in src do -- the edit list moves presentation times: minus the first edit's media time (video: the B-frame delay; audio @@ -215,7 +202,6 @@ local function dOps(head: buffer?): buffer? return w:finish() end --- encode(video, opts?) -> buffer | nil, Err function Mp4.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: any = table.clone(opts or {}) o.quality = o.quality or 90 @@ -329,7 +315,6 @@ function Mp4.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> a VideoDecoder | nil, Err function Mp4.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) local dmx, err = Mp4.demux(r, opts) if not dmx then diff --git a/src/Rosetta/video/mpegps/init.luau b/src/Rosetta/video/mpegps/init.luau index 9cca184..f722a41 100644 --- a/src/Rosetta/video/mpegps/init.luau +++ b/src/Rosetta/video/mpegps/init.luau @@ -1,12 +1,7 @@ --!strict --- video/mpegps: MPEG program streams (ISO/IEC 11172-1 system streams and 13818-1 program streams: .mpg / .mpeg / --- .vob / VCD .dat). New in rosetta, on containers/MpegPs. Video PES payloads are joined into the elementary --- stream and cut into pictures (containers/MpegEs: one packet per picture with its sequence / GOP headers, both --- fields of a field-coded frame in one); a picture takes the PTS of the PES it starts in, pictures without one get --- theirs from the GOP's temporal references. Audio packets are the PES payloads (MP1 / MP2 / MP3 frames, AC-3, LPCM). --- open() returns a VideoDecoder: MPEG-1 / MPEG-2 video through the codecs/video/Video registry (MPEG-2 told by its --- sequence extension), audio through the api's opts.openAudio hook. --- Timescale 90 kHz. Not supported: writing, H.264 in PS (packets are whole PES payloads), DVD navigation packets. +-- video/mpegps: MPEG program streams (ISO/IEC 11172-1, 13818-1: .mpg / .vob / VCD .dat), on containers/MpegPs and +-- containers/MpegEs: a packet per picture (the PTS of the PES it starts in, else from the GOP's temporal references), +-- audio packets = PES payloads; 90 kHz. Not supported: writing, H.264 in PS, DVD navigation packets. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -30,7 +25,7 @@ local Ps = { -- ------------------------------------------------------------------------------------------------ types export type OpenOptions = { rgba: boolean?, - track: number?, -- the video stream id to decode (0xE0.. ; default: the first video stream) + track: number?, -- 0xE0..; default: the first video stream audio: boolean?, maxPixels: number?, openAudio: any?, -- set by the api @@ -48,7 +43,6 @@ function Ps.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- the pictures of a video stream as packets: join the PES payloads, cut at pictures, place the timestamps local function videoPackets(dmx: any, buf: buffer, s: MpegPs.Stream, t: any) local total = 0 for _, p in s.pes do @@ -119,7 +113,6 @@ local function videoPackets(dmx: any, buf: buffer, s: MpegPs.Stream, t: any) end end --- demux(r, opts?) -> the Demuxer | nil, Err function Ps.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) if r:peek(4) == "\0\0\1\179" then -- an MPEG-1 / 2 video elementary stream (.m1v): one video stream, no timestamps @@ -181,7 +174,6 @@ function Ps.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> a VideoDecoder | nil, Err function Ps.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) local dmx, err = Ps.demux(r, opts) if not dmx then diff --git a/src/Rosetta/video/mpegts/init.luau b/src/Rosetta/video/mpegts/init.luau index 07c703b..cabffea 100644 --- a/src/Rosetta/video/mpegts/init.luau +++ b/src/Rosetta/video/mpegts/init.luau @@ -1,13 +1,7 @@ --!strict --- video/mpegts: MPEG transport streams (ISO/IEC 13818-1: .ts / .m2ts segments, HLS). The demuxer is containers/MpegTs, --- absorbed from mpegts-luau (resync, PAT / PMT with CRC, continuity checks, PES reassembly, 33-bit PTS / DTS --- unwrapped); this format turns its units into a Demuxer (timescale 90 kHz; one PES = one packet: a picture as --- muxed by ffmpeg, one or more audio frames) and returns a VideoDecoder: MPEG-1 / MPEG-2 video through the --- codecs/video/Video registry (stream types 0x01 / 0x02, and private ones such as 0x80 with a video PES stream id, --- told apart by an MPEG-2 sequence extension), H.264 when registered, audio (MP1 / MP2 / --- MP3, AAC in ADTS) through the api's opts.openAudio hook. Keyframes: MPEG-1 / 2 I-pictures, H.264 IDR access units. --- M2TS (192-byte packets with a 4-byte timestamp prefix) is read too. Not supported: writing, scrambled streams, --- PES without PTS for video before the first one (dropped). +-- video/mpegts: MPEG transport streams (ISO/IEC 13818-1: .ts, .m2ts, HLS) over containers/MpegTs (from mpegts-luau); +-- one PES = one packet, 90 kHz; MPEG-1 / 2 (types 0x01 / 0x02, private ones told by an MPEG-2 sequence extension), +-- H.264, MP1-3 / ADTS AAC. Not supported: writing, scrambled streams, video PES before the first PTS (dropped). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -31,7 +25,7 @@ local Ts = { -- ------------------------------------------------------------------------------------------------ types export type OpenOptions = { rgba: boolean?, - track: number?, -- the video PID to decode (default: the first video stream of the PMT) + track: number?, -- default: the first video stream of the PMT audio: boolean?, maxPixels: number?, openAudio: any?, -- set by the api @@ -52,8 +46,7 @@ local CODEC: { [string]: string } = { } -- ------------------------------------------------------------------------------------------------ sniff --- packetSize(r) -> 188 | 192 (M2TS) | 0, and the offset of the first sync byte: three sync bytes a packet apart --- (fewer in a short file) within the first 2 KB +-- 188 or 192 (M2TS): three sync bytes a packet apart (fewer in a short file) within the first 2 KB local function packetSize(r: Bytes.Reader): (number, number) local n = r:remaining() for start = 0, math.min(n, 2048) - 1 do @@ -112,7 +105,6 @@ local function mpegAudioCodec(u: any): string return "mp2" end --- demux(r, opts?) -> the Demuxer | nil, Err function Ts.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) local size, off = packetSize(r) if size == 0 then @@ -164,7 +156,6 @@ function Ts.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) for _, u in units do track(u.pid, u.kind, u.codec, u.streamType, nil) end - -- codec details from the first unit local seen: { [number]: boolean } = {} for _, u in units do local t = byPid[u.pid] @@ -234,7 +225,6 @@ function Ts.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> a VideoDecoder | nil, Err function Ts.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) local dmx, err = Ts.demux(r, opts) if not dmx then diff --git a/src/Rosetta/video/ogv/init.luau b/src/Rosetta/video/ogv/init.luau index 8a12660..6e5dbab 100644 --- a/src/Rosetta/video/ogv/init.luau +++ b/src/Rosetta/video/ogv/init.luau @@ -1,15 +1,7 @@ --!strict --- video/ogv: Ogg video (.ogv, or .ogg with a Theora stream: the Ogg Theora mapping of the Theora I specification, --- RFC 3533 / 5334). New in rosetta, on containers/Ogg and containers/Demux. --- Read: open() demuxes every logical stream of the first Ogg group into a packet index: Theora video (frame times from --- the granule positions: keyframe number << shift | frames since it; the three headers become track.config, --- Xiph-laced as in Matroska, so codecs/video/Theora decodes it through the codecs/video/Video registry), Vorbis / --- Opus / FLAC audio (headers in track.config, times from the granules) reaching the audio formats through the api's --- opts.openAudio hook; the Theora comment header's tags go to meta.tags. Ogv.demux(r) gives the Demuxer alone. --- Write: remux (encode): a Theora video track copied from the source (ogv / mkv), plus its Vorbis / Opus audio copied --- (the audio pages come from containers/AudioWrap and are interleaved by time). --- Not supported: chained Ogg files (only the first group of streams), Skeleton / Kate / Speex streams (skipped), --- encoding Theora (there is no encoder: other sources cannot be written). +-- video/ogv: Ogg Theora video (Theora I spec, RFC 3533 / 5334), on containers/Ogg: Theora (granule = keyframe << shift +-- | frames since; the headers Xiph-laced into track.config) and Vorbis / Opus / FLAC streams of the first group. Writes +-- copied Theora + audio. Not supported: chained files, Skeleton / Kate / Speex streams, encoding Theora. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -34,23 +26,22 @@ local Ogv = { -- ------------------------------------------------------------------------------------------------ types export type OpenOptions = { - rgba: boolean?, -- nextFrame returns rgba8 images (default false: yuv420p from the codec) - track: number?, -- the video track id to decode (default: the first video track) - audio: boolean?, -- false: do not open the audio track + rgba: boolean?, -- default false: yuv420p + track: number?, -- default: the first video track + audio: boolean?, maxPixels: number?, - verify: boolean?, -- false: skip the page CRC checks (default true) + verify: boolean?, -- default true openAudio: any?, -- set by the api: (demuxer, track) -> audio Decoder } export type EncodeOptions = { - audio: boolean?, -- false: no audio; true: fail when the audio cannot be copied (default: dropped) + audio: boolean?, -- true: fail when the audio cannot be copied (default: dropped) } -- ------------------------------------------------------------------------------------------------ constants local AUDIO = { vorbis = true, opus = true, flac = true } -- ------------------------------------------------------------------------------------------------ sniff --- 1 when one of the beginning-of-stream pages at the start of an Ogg file is a Theora identification header (plain --- Ogg Vorbis / Opus / FLAC files are left to the audio formats) +-- a Theora identification header in a bos page (plain Ogg audio is left to the audio formats) function Ogv.sniff(r: Bytes.Reader): number if r:peek(4) ~= "OggS" then return 0 @@ -78,7 +69,6 @@ function Ogv.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ encode --- the pages of an Ogg buffer: { offset, size, serial, granule, bos } local function pages(b: buffer): { { number } } local out = {} local pos = 0 @@ -93,7 +83,6 @@ local function pages(b: buffer): { { number } } return out end --- encode(video, opts?) -> an Ogg file | nil, Err: a VideoDecoder or Demuxer whose video track is Theora (ogv, mkv) function Ogv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: any = opts or {} local streams, err = Source.streams(value, o, { video = { copy = { theora = true } }, audio = { copy = { vorbis = true, opus = true } } }) @@ -137,7 +126,6 @@ function Ogv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) s:packet(p.data, key * scale + (frame + bias - key), { eos = i == #v.packets }) end local video = mux:finish() - -- audio pages: the audio track as its own Ogg stream (containers/AudioWrap), interleaved by time local audio: buffer? = nil local arate, askip = 1, 0 if as and o.audio ~= false then @@ -232,7 +220,6 @@ end type Pending = { track: number, pts: number, key: boolean, page: number, data: buffer, off: number, len: number, own: boolean } --- demux(r, opts?) -> the Demuxer (containers/Demux) | nil, Err function Ogv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) local ogg, err = Ogg.open(r, { verify = not (opts and opts.verify == false) }) if not ogg then @@ -301,7 +288,7 @@ function Ogv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) break end if p.size > 0 and buffer.readu8(p.data, p.offset) >= 0x80 then - continue -- a stray header + continue end table.insert(packets, p) if base == nil and p.granule >= 0 then @@ -392,7 +379,6 @@ function Ogv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) return dmx, nil end --- open(r, opts?) -> a VideoDecoder (kind "video": nextFrame / seek / audio / demuxer) | nil, Err function Ogv.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) local ok, dmx, err = pcall(Ogv.demux, r, opts) if not ok then diff --git a/src/Rosetta/video/smk/Audio.luau b/src/Rosetta/video/smk/Audio.luau index bde9edd..615a74a 100644 --- a/src/Rosetta/video/smk/Audio.luau +++ b/src/Rosetta/video/smk/Audio.luau @@ -1,20 +1,15 @@ --!strict --!native --!optimize 2 --- video/smk/Audio: Smacker's packed audio (SMKA: DPCM with Huffman-coded deltas), the one audio codec only Smacker --- files carry. Written from the format description (MultimediaWiki "Smacker"). A packet: the unpacked size (u32), --- then LSB-first bits: data flag, stereo, 16-bit, one 8-bit Huffman tree per channel and byte (codecs/video/Legacy/ --- Smacker trees: 1, 2 or 4), the first sample(s) raw (16-bit ones byte-swapped, the right channel first), then per --- sample a delta added with wraparound (the low byte's tree, and the high byte's for 16 bits). Raw PCM tracks (u8 / --- s16le) are converted here too. Output: interleaved floats (u8: (v - 128) / 128, s16: v / 32768), as ffmpeg gives --- them. Never throws: trees are bounded and every read past the packet gives zero bits. +-- video/smk/Audio: Smacker packed audio (SMKA, MultimediaWiki "Smacker"): u32 unpacked size, then LSB-first bits: data, +-- stereo, 16-bit flags, an 8-bit Huffman tree per channel and byte, the first samples raw (16-bit byte-swapped, right +-- first), then wrapping deltas. Raw u8 / s16le too; floats as ffmpeg gives them (u8 (v - 128) / 128, s16 v / 32768). local Smacker = require("@rosetta/codecs/video/Legacy/Smacker") local readu8, readi16 = buffer.readu8, buffer.readi16 local Audio = {} --- decode(data, channels, bits, packed) -> frames, floats (1-based interleaved) | nil, message function Audio.decode(d: buffer, channels: number, bits: number, packed: boolean): (number?, { number } | string) local n = buffer.len(d) if not packed then @@ -43,7 +38,7 @@ function Audio.decode(d: buffer, channels: number, bits: number, packed: boolean local br = Smacker.bits(d, 4, n - 4) local bit, read, walk = Smacker.bit, Smacker.read, Smacker.walk if bit(br) == 0 then - return 0, {} -- no data + return 0, {} end local stereo = bit(br) local wide = bit(br) diff --git a/src/Rosetta/video/smk/init.luau b/src/Rosetta/video/smk/init.luau index ded8c40..e741837 100644 --- a/src/Rosetta/video/smk/init.luau +++ b/src/Rosetta/video/smk/init.luau @@ -1,16 +1,7 @@ --!strict --- video/smk: RAD Game Tools' Smacker video (SMK2 and SMK4). New in rosetta, written from the format description --- (MultimediaWiki "Smacker"). --- Read: the header (size, frame count, frame time: > 0 ms, < 0 units of 10 us; the ring-frame flag), up to 7 audio --- tracks (rate, packed / 16-bit / stereo flags), the frame sizes and flags, the four Huffman trees; per frame a palette --- update (skip / copy-from-old / new 6-bit entries), the audio chunks and the video data, into a Demuxer. open() --- returns a VideoDecoder: rgba8 frames from the Smacker video codec (codecs/video/Legacy/Smacker, through the --- codecs/video/Video registry: the frame's palette rides on each packet as packet.palette), and the first audio --- track as an audio Decoder built here (Smacker's packed DPCM audio has no audio format, so the format decodes it --- itself: video/smk/Audio over codecs/audio/Stream; raw u8 / s16le tracks too). The ring frame (the extra frame that --- leads back to the first) is not shown unless opts.ringFrame. Smk.demux(r) gives the Demuxer; Smk.openAudio(dmx, --- track) the Decoder of any of its audio tracks. --- Not supported: writing, Bink audio tracks (flags 0x08 / 0x04: reported as "binkaudio", no decoder). +-- video/smk: RAD Smacker video (SMK2, SMK4), from MultimediaWiki "Smacker": header, up to 7 audio tracks, Huffman +-- trees, per-frame palette updates; rgba8 through codecs/video/Legacy/Smacker, audio through video/smk/Audio; the ring +-- frame only with opts.ringFrame. Not supported: writing, Bink audio tracks (flags 0x08 / 0x04). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -33,11 +24,11 @@ local Smk = { -- ------------------------------------------------------------------------------------------------ types export type OpenOptions = { - rgba: boolean?, -- (frames are rgba8 already) + rgba: boolean?, -- frames are rgba8 already maxPixels: number?, -- default 2^26 - audio: boolean?, -- false: do not open the audio track - ringFrame: boolean?, -- true: also show the ring frame at the end (as ffmpeg does) - openAudio: any?, -- the api's hook: used only for tracks this format cannot decode (Bink audio) + audio: boolean?, + ringFrame: boolean?, -- also show the ring frame (as ffmpeg) + openAudio: any?, -- the api's hook, only for Bink audio } -- ------------------------------------------------------------------------------------------------ constants @@ -59,7 +50,6 @@ function Smk.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- a frame's palette update over the previous palette (pal: 256 u32 R, G, B, A); false when malformed local function palette(b: buffer, p: number, stop: number, old: buffer): (buffer?) local pal = buffer.create(1024) buffer.copy(pal, 0, old, 0, 1024) @@ -96,7 +86,6 @@ local function palette(b: buffer, p: number, stop: number, old: buffer): (buffer return pal end --- demux(r, opts?) -> the Demuxer | nil, Err function Smk.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) local b, base, limit = r.buf, r.base, r.limit if limit - base < HEADER then @@ -247,7 +236,6 @@ function Smk.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- openAudio(dmx, track) -> an audio Decoder for one of the demuxer's audio tracks | nil, Err function Smk.openAudio(dmx: any, track: Types.Track): (Types.Decoder?, Err.Err?) local codec = track.codec if codec ~= "smackaudio" and codec ~= "pcm_u8" and codec ~= "pcm_s16le" then @@ -299,7 +287,6 @@ function Smk.openAudio(dmx: any, track: Types.Track): (Types.Decoder?, Err.Err?) }) end --- open(r, opts?) -> a VideoDecoder | nil, Err function Smk.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) local dmx, err = Smk.demux(r, opts) if not dmx then diff --git a/src/Rosetta/video/y4m/init.luau b/src/Rosetta/video/y4m/init.luau index 2e97994..838a642 100644 --- a/src/Rosetta/video/y4m/init.luau +++ b/src/Rosetta/video/y4m/init.luau @@ -1,11 +1,7 @@ --!strict --- video/y4m: YUV4MPEG2 (the mjpegtools / ffmpeg raw video stream). New in rosetta. --- Read: the stream header (W H F I A C X tags) and every FRAME into a raw-video Demuxer; open() returns a VideoDecoder --- with yuv420p frames (C420 / C420jpeg / C420mpeg2 / C420paldv as they are; C422 / C444 chroma averaged down; Cmono --- with neutral chroma; 9..16-bit samples (C420p10, ...) scaled to 8 bits). Y4m.demux(r) gives the Demuxer. --- Write: yuv420p 8-bit frames ("C420jpeg", as ffmpeg writes for yuv420p) from any video or animated image; rgba8 --- frames are converted (BT.601 limited range); uneven frame times (a GIF's) become a constant rate with repeated frames. Not supported: interlaced field handling (the I tag is kept in meta), --- alpha (C444alpha drops it). +-- video/y4m: YUV4MPEG2 (mjpegtools / ffmpeg). Reads the W H F I A C X tags and FRAMEs as yuv420p (C422 / C444 +-- averaged, Cmono neutral chroma, high bit depths scaled to 8). Writes "C420jpeg" as ffmpeg does for yuv420p (BT.601 +-- limited range). Not supported: interlaced field handling (the I tag is kept in meta), alpha (C444alpha drops it). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -27,13 +23,12 @@ local Y4m = { -- ------------------------------------------------------------------------------------------------ types export type OpenOptions = { - rgba: boolean?, -- nextFrame returns rgba8 (default false: yuv420p) + rgba: boolean?, -- default false: yuv420p maxPixels: number?, -- default 2^26 } export type EncodeOptions = { - frameRate: { number }?, -- { num, den } for the F tag, one frame per source frame (default: the constant rate of the - -- shortest frame, longer frames repeated) - maxFps: number?, -- the highest rate uneven frame times may need (default 100) + frameRate: { number }?, -- { num, den } of the F tag (default: the shortest frame's rate) + maxFps: number?, -- default 100 } -- ------------------------------------------------------------------------------------------------ constants @@ -77,7 +72,6 @@ local function frameSize(pf: string, bits: number, w: number, h: number): number return w * h * bps end --- demux(r, opts?) -> the raw-video Demuxer | nil, Err function Y4m.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) local buf, base, limit = r.buf, r.base, r.limit local nl = -1 @@ -164,7 +158,7 @@ function Y4m.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) end local data = e + 1 if data + size > limit then - break -- a truncated last frame is dropped + break end dmx:add(1, k, k, 1, true, data, size) k += 1 @@ -175,7 +169,6 @@ function Y4m.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ encode --- encode(video, opts?) -> buffer | nil, Err function Y4m.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local streams, err = Source.streams(value, { audio = false }, { video = { copy = nil, encode = "rawvideo" } }) if not streams then @@ -197,7 +190,6 @@ function Y4m.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> a VideoDecoder | nil, Err function Y4m.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) local dmx, err = Y4m.demux(r, opts) if not dmx then