diff --git a/docs/API.md b/docs/API.md index 83d0f12..22b51c0 100644 --- a/docs/API.md +++ b/docs/API.md @@ -84,6 +84,8 @@ A format never requires another format, so the api passes these to decoders / en - `opts.decodeImage(buf) -> Image | nil, Err` and `opts.encodeImage(img, format) -> buffer | nil, Err`: images inside other files (ICO PNG entries, PSD / glTF / 3MF textures, MJPEG frames, ...). +- `opts.decodeModule(buf, format?) -> Module | nil, Err`: tracker modules inside other files (the module of an Unreal + `.umx` package), loaded as music. - `opts.openAudio(demuxer, track) -> Decoder | nil, Err`: audio tracks of video containers (wrapped by `containers/AudioWrap` and opened as the matching audio format). - `opts.plugins` (default `F.plugins`): injected optional dependencies, e.g. `F.plugins.brep` (a B-rep kernel for diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 944f35d..03a6531 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -28,16 +28,26 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | image | xbm | .xbm .bm | yes | yes | depths: 1 | `tests/image/xbm.luau` | | image | xpm | .xpm .pm | yes | yes | alpha: true, palette: true, depths: 8 | `tests/image/xpm.luau` | | audio | aac | .aac .adts | yes | - | codecs: "aac", streaming: true | `tests/audio/aac.luau` | +| audio | ac3 | .ac3 .a52 | yes | - | codecs: "ac3", channels: 6, streaming: true, lossy: true | `tests/audio/ac3.luau` | +| audio | adpcm | .adpcm .ima | yes | yes | streaming: true, lossy: true, headerless: true, codecs: "ima", "ima_wav", "ms", "ima_qt", "psx" | `tests/audio/adpcm.luau` | +| audio | adx | .adx | yes | yes | streaming: true, lossy: true, loops: true, channels: 8 | `tests/audio/adx.luau` | | audio | aiff | .aiff .aif .aifc .afc | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, lossy: false | `tests/audio/aiff.luau` | +| audio | ape | .ape | yes | - | streaming: true, seek: true, lossless: true, float: true, depths: 8, 16, 24, 32 | `tests/audio/ape.luau` | | audio | au | .au .snd | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, lossy: false | `tests/audio/au.luau` | +| audio | brstm | .brstm .bcstm .bfstm | yes | - | streaming: true, lossy: true, loops: true, containers: "RSTM", "CSTM", "FSTM" | `tests/audio/brstm.luau` | | audio | caf | .caf .caff | yes | yes | codecs: "pcm", "alac", "aac", "ulaw", "alaw", encodeCodecs: "pcm", "alac", tags: true, streaming: true | `tests/audio/caf.luau` | | audio | flac | .flac .oga | yes | yes | streaming: true, depths: 4, 8, 12, 16, 20, 24, 32, ogg: true, seek: true | `tests/audio/flac.luau` | | audio | m4a | .m4a .m4b .m4r | yes | yes | codecs: "aac", "alac", encodeCodecs: "alac", tags: true, streaming: true | `tests/audio/m4a.luau` | | audio | mp3 | .mp3 .mp2 .mp1 .mpga | yes | yes | streaming: true, seek: true, layers: 1, 2, 3, encodeLayers: 2, 3, channels: 2 | `tests/audio/mp3.luau` | +| audio | mpc | .mpc .mp+ .mpp | yes | - | codecs: "musepack", versions: 7, 8, streaming: true, lossy: true | `tests/audio/mpc.luau` | | audio | opus | .opus | yes | yes | streaming: true, seek: true, lossy: true, channels: 255, rates: 48000, encodeModes: "celt", encodeChannels: 2 | `tests/audio/opus.luau` | +| audio | qoa | .qoa | yes | yes | streaming: true, lossy: true, seek: true, channels: 8 | `tests/audio/qoa.luau` | +| audio | tta | .tta | yes | - | streaming: true, seek: true, lossless: true, depths: 8, 16, 24 | `tests/audio/tta.luau` | +| audio | vag | .vag | yes | yes | streaming: true, lossy: true, loops: true, channels: 2 | `tests/audio/vag.luau` | | audio | voc | .voc | yes | yes | streaming: true, depths: 8, 16, lossy: false | `tests/audio/voc.luau` | | audio | vorbis | .ogg .oga | yes | yes | streaming: true, seek: true, lossy: true, channels: 255 | `tests/audio/vorbis.luau` | | audio | wav | .wav .wave .rf64 .bw64 | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, rf64: true | `tests/audio/wav.luau` | +| audio | wavpack | .wv | yes | - | streaming: true, seek: true, lossless: true, hybrid: true, float: true, depths: 8, 12, 16, 20, 24, 32 | `tests/audio/wavpack.luau` | | video | avi | .avi | yes | yes | streaming: true, video: "mjpeg", "mpeg1", "mpeg2", "rawvideo", audio: true, odml: true | `tests/video/avi.luau` | | video | fli | .fli .flc .flx | yes | - | streaming: true, video: "flic", depths: 8, 15, 16, 24 | `tests/video/fli.luau` | | video | h264 | .h264 .264 .avc .jsv .26l .jvt | yes | yes | streaming: true, video: "h264", depths: 8 | `tests/video/h264.luau` | @@ -107,12 +117,26 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | subtitle | ass | .ass .ssa | yes | yes | styles: true | `tests/subtitle/ass.luau` | | subtitle | srt | .srt | yes | yes | styles: false | `tests/subtitle/srt.luau` | | subtitle | vtt | .vtt .webvtt | yes | yes | styles: true | `tests/subtitle/vtt.luau` | +| music | 669 | .669 | yes | - | render: true, channels: 8, 8 | `tests/music/669.luau` | +| music | ahx | .ahx .thx | yes | - | render: true, channels: 4, 4, subsongs: true | `tests/music/ahx.luau` | +| music | far | .far | yes | - | render: true, channels: 16, 16 | `tests/music/far.luau` | +| music | hmp | .hmp .hmi | yes | - | render: true, hmi: true | `tests/music/hmp.luau` | +| music | hvl | .hvl | yes | - | render: true, channels: 4, 16, subsongs: true | `tests/music/hvl.luau` | | music | it | .it | yes | - | render: true, channels: 1, 64, compressedSamples: true | `tests/music/it.luau` | +| music | med | .med .mmd0 .mmd1 .mmd2 .mmd3 .omed | yes | - | render: true, channels: 1, 64 | `tests/music/med.luau` | | music | midi | .mid .midi .smf .kar .rmi | yes | yes | formats: 0, 1, 2, render: true, streaming: true, rmid: true | `tests/music/midi.luau` | | music | mod | .mod .m15 .stk .nst | yes | yes | render: true, channels: 1, 32 | `tests/music/mod.luau` | +| music | mtm | .mtm | yes | - | render: true, channels: 1, 32 | `tests/music/mtm.luau` | +| music | mus | .mus | yes | - | render: true | `tests/music/mus.luau` | +| music | okt | .okt .okta | yes | - | render: true, channels: 4, 8 | `tests/music/okt.luau` | +| music | ptm | .ptm | yes | - | render: true, channels: 1, 32 | `tests/music/ptm.luau` | | music | s3m | .s3m | yes | - | render: true, channels: 1, 32 | `tests/music/s3m.luau` | | music | sf2 | .sf2 | yes | - | sm24: true, sf3: false | `tests/music/sf2.luau` | +| music | stm | .stm | yes | - | render: true, channels: 4, 4 | `tests/music/stm.luau` | +| music | ult | .ult | yes | - | render: true, channels: 1, 32 | `tests/music/ult.luau` | +| music | umx | .umx | yes | - | render: true, container: true | `tests/music/umx.luau` | | music | xm | .xm | yes | yes | render: true, channels: 1, 64 | `tests/music/xm.luau` | +| music | xmi | .xmi .xmidi | yes | - | render: true, songs: true | `tests/music/xmi.luau` | | playlist | m3u | .m3u .m3u8 | yes | yes | hls: true | `tests/playlist/m3u.luau` | | playlist | pls | .pls | yes | yes | | `tests/playlist/pls.luau` | | playlist | xspf | .xspf | yes | yes | | `tests/playlist/xspf.luau` | @@ -121,18 +145,28 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - **audio** - codecs/audio/Aac: AAC-LC decoder (ISO/IEC 14496-3 subpart 4, ISO/IEC 13818-7): the AudioSpecificConfig (with a program + - codecs/audio/Ac3: AC-3 (Dolby Digital, ATSC A/52) syncframes: the syncinfo / BSI header, the CRC check, and the + - codecs/audio/Adpcm: the 4-bit ADPCM family, decode (and encode where it is cheap). New in formats-luau; the IMA and - codecs/audio/Alac: Apple Lossless (ALAC) decoder and encoder, the codec inside m4a / mov / caf. A codec (layer 1). + - codecs/audio/Ape: the Monkey's Audio codec (.ape). A codec (layer 3). Ported from the Monkey's Audio SDK 13.28 + - codecs/audio/ApeTag: APEv1 / APEv2 tags (the tag block of Monkey's Audio, WavPack, Musepack, TTA, OptimFROG and - codecs/audio/Flac: FLAC frames without the container: frame header parsing, subframe decoding (constant, verbatim, + - codecs/audio/Hively: the AHX / HivelyTracker engine behind music/ahx and music/hvl: the loader for both file formats - codecs/audio/Mdct: the MDCT / IMDCT of any window length N divisible by 4 (N / 2 coefficients), through an N / 4-point + - codecs/audio/MidiRender: the tempo map (ticks -> seconds, as python mido computes lengths), the time-ordered event list, - codecs/audio/Mpa: MPEG audio layers I / II / III (ISO/IEC 11172-3, 13818-3, MPEG-2.5) without the file around it: + - codecs/audio/Musepack: Musepack (MPC) stream versions 7 and 8: the stream headers (SV7's 32-bit word-swapped - codecs/audio/Opus: the Opus codec (RFC 6716) without its container: TOC / packet framing (Packet), the SILK and CELT - codecs/audio/Pcm: PCM plumbing shared by audio formats: raw sample formats, streaming Decoders, encoder input sources. + - codecs/audio/Qoa: the "Quite OK Audio" codec (QOA): frames of up to 256 slices per channel, each slice a 4-bit scale - codecs/audio/Resample: audio sample-rate conversion by band-limited (Kaiser-windowed sinc) interpolation, streaming or - codecs/audio/SoundFont: SoundFont 2 banks and the sample synth that plays MIDI through them. A codec (layer 1) shared by - codecs/audio/Stream: the streaming Decoder (Types.Decoder: read / seek / position) over a packetised codec, the part - - codecs/audio/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it. The four loaders read + - codecs/audio/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it, and the loaders + - codecs/audio/Tta: the TTA1 (True Audio) lossless codec. A codec (layer 3). Written from the TTA1 format description - codecs/audio/Vorbis: the Vorbis I decoder without its container: identification / comment / setup headers (Setup), - codecs/audio/VorbisComment: Vorbis comment fields ("KEY=value", the tag block of Vorbis, Opus and FLAC) <-> Types.Tags. + - codecs/audio/WavPack: the WavPack 4 / 5 audio codec (the blocks of .wv files, and of WavPack in Matroska). A codec - **compress** - codecs/compress/Brotli: Brotli (RFC 7932) decompression. A codec (layer 3): archive/br and font/woff2 build on it. Written - codecs/compress/Bzip2: bzip2 decompressor (BWT + MTF + Huffman, the .bz2 stream format of bzip2 0.9.5 / 1.0.x). A codec diff --git a/docs/guide/audio.md b/docs/guide/audio.md index 94271f6..1168fc5 100644 --- a/docs/guide/audio.md +++ b/docs/guide/audio.md @@ -99,7 +99,8 @@ the guide's [README](README.md#inputs)). Options: | Option | Formats | Meaning | |---|---|---| | `format` | all | decode as this format (`"mp3"`, `"wav"`, ...) and skip detection | -| `maxFrames` | wav, flac, mp3, aiff, au, voc, aac | `Err.LIMIT` past this many frames | +| `maxFrames` | wav, flac, mp3, aiff, au, voc, aac, mpc, ac3 | `Err.LIMIT` past this many frames | +| `drc` | ac3 | dynamic range control: 0 = off (default), 1 = as the stream says | | `stereo` | opus | downmix surround streams to stereo | ```luau @@ -179,6 +180,8 @@ Encoder options: | opus | `bitrate` (default 64000 per channel, 6000..510000); CELT only; resampled to 48 kHz | | aiff, au, voc | `sampleFormat` (see each format's `init.luau`) | | m4a, caf | ALAC (lossless); m4a and caf also keep tags | +| adx, vag | `loop = { start, stop }` (frames; default the source's `meta.source.loop`) | +| adpcm | `codec = "ima" \| "ima_wav" \| "ms"`, `blockAlign` (block codecs), `lowFirst` (ima nibble order) | `bitrate` is in **bits per second** for every encoder (`bitrate = 192000`), as the Decoder's `bitrate` field is. A value below 1000 is read as kbit/s (`bitrate = 192` is 192000), so older code that passed kbit/s to MP3 still works. @@ -189,7 +192,7 @@ Tags are written from `audio.tags`, or from the Decoder's `tags`, wherever the f | Read and write | Read only | |---|---| -| wav (+ RF64), flac (+ Ogg FLAC), mp3 / mp2, vorbis (.ogg), opus, aiff / aifc, au, voc, caf, m4a (ALAC) | aac (ADTS), m4a / caf AAC | +| wav (+ RF64), flac (+ Ogg FLAC), mp3 / mp2, vorbis (.ogg), opus, aiff / aifc, au, voc, caf, m4a (ALAC), qoa, adx, vag, adpcm (raw IMA / MS) | aac (ADTS), m4a / caf AAC, mpc (Musepack SV7 / SV8), ac3 (Dolby Digital), brstm / bcstm / bfstm, KVAG, wav / aifc / caf IMA and MS ADPCM, wavpack (.wv + .wvc), ape, tta | Each format's capabilities are listed in [FORMATS.md](../FORMATS.md). The audio tracks of video files open as Decoders too: see `v.audio` in [video.md](video.md). Music files (MOD, MIDI, ...) render to a Decoder: see @@ -243,6 +246,95 @@ end Roblox has no API to play raw samples, so on Roblox the decoded samples are data only, for example for analysis or visualisers. +### Musepack and AC-3 + +Musepack (`.mpc`, stream versions 7 and 8) decodes gapless, with its APEv2 tags. AC-3 (`.ac3`, Dolby Digital) decodes +every channel layout up to 5.1 without downmixing, in WAVE order (FL FR FC LFE SL SR), with dynamic range control off +unless `drc` asks for it. The AC-3 tracks of MKV, MP4, MPEG-TS and AVI files open as `v.audio` the same way. Both +seek exactly (Musepack SV7 like libmpcdec: 32 frames of pre-roll). E-AC-3 (Dolby Digital Plus) is `Err.UNSUPPORTED`. + +```luau +local mpc = assert(F.audio.load(mpcBytes)) -- Musepack: tags, exact length +assert(F.detect(mpcBytes) == "mpc" and mpc.tags.title == "Docs Tone") +assert(mpc.frames == 44100 and mpc.meta.source.version == 8) +local dd = assert(F.audio.open(ac3Bytes)) -- AC-3 5.1: a Decoder like any other +assert(dd.channels == 6 and dd.sampleRate == 48000) +dd:seek(0.25) +local _, n = dd:read(256) +assert(n == 256) +local stereo = assert(F.ops.audio.downmix(F.audio.load(ac3Bytes))) -- 2 channels, ITU-R BS.775 +local night = assert(F.audio.load(ac3Bytes, { drc = 1 })) -- the stream's dynamic range gains applied +assert(stereo.channels == 2 and night.channels == 6) +``` + +### Game audio and ADPCM + +Console and game engines store sound as 4-bit ADPCM or QOA: small, and cheap to decode while the game runs. They load +and save like any other audio. Loop points (ADX, VAG, BRSTM) come out in `meta.source.loop` (and `dec.loop`), in +frames, `stop` exclusive; the encoders write them back. + +```luau +local tone = F.Types.Audio.new(22050, 1, 22050) -- 1 s of 440 Hz +for i = 0, tone.frames - 1 do + buffer.writef32(tone.samples, i * 4, 0.5 * math.sin(2 * math.pi * 440 * i / 22050)) +end +local qoa = assert(F.save(tone, nil, { format = "qoa" })) -- Quite OK Audio: 3.2 bits per sample, as qoa.h writes it +assert(F.detect(qoa) == "qoa" and F.audio.load(qoa).frames == tone.frames) +local adx = assert(F.save(tone, nil, { format = "adx", loop = { start = 0, stop = tone.frames } })) -- CRI ADX +local looped = assert(F.audio.load(adx)) +assert(looped.meta.source.loop.stop == tone.frames) +local vag = assert(F.save(tone, nil, { format = "vag" })) -- PlayStation VAG (mono VAGp; stereo is VAGi) +assert(F.audio.load(vag).frames >= tone.frames) -- + the blank frame VAGs start with, and frame padding +``` + +A raw ADPCM stream has no header, so the layout comes from the options, and only `opts.format` or the `.adpcm` / `.ima` +extension finds it: + + +```luau +local raw = assert(F.save(tone, nil, { format = "adpcm", codec = "ima" })) -- 4 bits per sample +local back = assert(F.audio.load(raw, { format = "adpcm", codec = "ima", sampleRate = 22050, channels = 1 })) +assert(back.frames == tone.frames) +``` + +Read only: Nintendo BRSTM / BCSTM / BFSTM (DSP ADPCM or PCM; `F.detect` names the flavour), KVAG, and the ADPCM +inside WAV (IMA, MS), AIFF-C and CAF (ima4). Decoding is bit-exact with vgmstream (ADX, VAG, BRSTM) and ffmpeg +(IMA, MS, ima4, QOA). Seeking is exact everywhere: the decoders keep the predictor state of every block they pass. + +### Lossless: WavPack, Monkey's Audio, TTA + +WavPack (`.wv`), Monkey's Audio (`.ape`) and TTA (`.tta`) open and load like FLAC. Their tags (APEv2) come out in +`tags` with lower-case keys. Integer streams also have `readInt`, which returns the exact samples as i32. Every +frame of these formats is independent, so `seek` lands on the exact sample. + +```luau +local wv = assert(F.audio.open(wvBytes)) +assert(wv.bitsPerSample == 16 and wv.lossless and wv.tags.title == "Docs Tone") +local exact, n = wv:readInt(1024) -- i32 samples, as wvunpack writes them +assert(n == 1024 and buffer.readi32(exact, 0) == 0) +local ape = assert(F.audio.load(apeBytes)) -- any level, fast .. insane +assert(ape.meta.source.format == "ape" and ape.tags.artist == "formats-luau") +local tta = assert(F.audio.open(ttaBytes)) +tta:seek(0.5) +assert(math.abs(tta:position() - 0.5) < 1e-6) +``` + +A hybrid WavPack file holds a lossy stream. Its `.wvc` correction file makes it lossless again. Pass the correction +file as `correction`. When you load a file by path, the `.wvc` next to it is found automatically. Without it, the +file decodes lossy. + +```luau +local lossy = assert(F.audio.open(hybridWvBytes)) +local full = assert(F.audio.open(hybridWvBytes, { correction = hybridWvcBytes })) +assert(lossy.hybrid and not lossy.lossless and full.lossless) +``` + + +```luau +local song = assert(F.audio.load("assets/tone_hybrid.wv")) -- reads assets/tone_hybrid.wvc too +assert(song.meta.source.correction == true) +``` + ## Gotchas - `F.ops.audio.downmix(a)` defaults to **2** channels, so a stereo input stays stereo. Use `downmix(a, 1)` for mono. diff --git a/docs/guide/music.md b/docs/guide/music.md index 369929d..2222949 100644 --- a/docs/guide/music.md +++ b/docs/guide/music.md @@ -1,6 +1,7 @@ # Music -Music files hold notes and instruments, not a recording. Tracker modules (MOD, S3M, XM, IT) load as a **Module**: +Music files hold notes and instruments, not a recording. Tracker modules (MOD, S3M, XM, IT, and the +[other trackers](#more-tracker-formats): MTM, 669, STM, ULT, OKT, MED, PTM, FAR, UMX) load as a **Module**: the patterns, the order list, the samples and the instruments. Standard MIDI files load as a **Midi**: tracks of timed events. Both render to the standard audio [Decoder](audio.md#decoder), so every music file can also be played, analysed or saved as audio. MIDI renders through a SoundFont 2 bank, or through a small built-in set of @@ -26,7 +27,8 @@ assert(audio.channels == 2 and audio.sampleRate == 44100) | Field | Type | Meaning | |---|---|---| | `kind` | `"music"` | | -| `format` | string | `"mod"`, `"s3m"`, `"xm"` or `"it"`: the effect family the engine plays | +| `format` | string | the format it was read from: `"mod"`, `"s3m"`, `"xm"`, `"it"`, `"mtm"`, `"669"`, `"med"`, ... | +| `engine` | string? | the effect family the engine plays (`"mod"`, `"s3m"`, `"xm"`, `"it"`); absent: the same as `format`. Set by the [other trackers](#more-tracker-formats) | | `title` | string | | | `channels` | number | pattern channels | | `speed`, `tempo` | number | initial ticks per row, and BPM (a tick lasts `2.5 / tempo` seconds) | @@ -312,9 +314,108 @@ assert(F.music.load(assert(F.save(xm))).instruments[1].name == "lead") | s3m, it | yes | - | Module | | midi (.mid, .kar, RMID) | yes | yes (SMF) | Midi | | sf2 | yes | - | SoundFont | +| ahx (AHX / THX), hvl (HivelyTracker) | yes | - | Module (own synth engine) | +| mus (Doom), xmi (Miles XMIDI), hmp (HMP, HMI) | yes | - (save as midi) | Midi | +| mtm (MultiTracker) | yes | - | Module (xm family) | +| 669 (Composer 669, UNIS 669) | yes | - | Module (s3m family) | +| stm (Scream Tracker 2) | yes | - | Module (s3m family) | +| ult (UltraTracker) | yes | - | Module (it family) | +| okt (Oktalyzer) | yes | - | Module (it family) | +| med (MED / OctaMED MMD0..MMD3) | yes | - | Module (xm family) | +| ptm (PolyTracker) | yes | - | Module (it family) | +| far (Farandole Composer) | yes | - | Module (s3m family) | +| umx (Unreal package) | yes | - | the embedded IT / S3M / XM / MOD Module | See [FORMATS.md](../FORMATS.md) for each format's capabilities. +### More tracker formats + +MultiTracker, Composer 669, Scream Tracker 2, UltraTracker, Oktalyzer, MED / OctaMED, PolyTracker and Farandole +modules load as Modules too (ported from OpenMPT's loaders). Each keeps its own `format` name and plays through one of +the four effect families (`engine`), with the format's quirks in `flags`: 669 and Farandole slide in Hz, Scream +Tracker 2 has its own tempo byte, MED its tempo modes and hold / decay, Oktalyzer its mixed channel pairs. Their +cells use the family's effect coding (an MTM cell reads like an XM cell, an OKT cell like an IT cell); a few effects +of these formats have no family equivalent and use the engine's extension codes (0x40 and up: note slides, auto +portamentos, ...). + +```luau +local song = assert(F.music.load(mtmBytes)) +assert(song.format == "mtm" and song.engine == "xm" and song.channels == 6) +local med = assert(F.music.load(medBytes)) +assert(med.format == "med" and med.meta.source.version == "MMD1" and med.instrumentMode) -- hold / decay: instruments +local audio = assert(F.ops.audio.toAudio(med:render({ sampleRate = 22050 }))) +assert(audio.frames > 0) +``` + +An Unreal `.umx` package holds a module (usually IT, S3M or XM). `F.load` unwraps it and returns that module, with +the package in `meta.container`; `F.format("umx").extract` lists the embedded modules without loading them. + +```luau +local m = assert(F.music.load(umxBytes)) +assert(m.format == "s3m" and m.meta.container.format == "umx" and m.meta.container.name == "theme") +local list = assert(F.format("umx").extract(F.Bytes.reader(umxBytes))) +assert(#list == 1 and list[1].format == "s3m") +local dec = assert(F.open(umxBytes)) -- rendered, like any module +assert(dec.channels == 2) +``` + +These formats are read only. Their Modules render to audio like any other (`F.save(song, nil, { format = "wav" })`), +and the module of an UMX keeps its own format, so `F.save(m)` works when that format has a writer (MOD, XM). + +### AHX / HVL and MIDI variants + +AHX and HivelyTracker modules carry no samples: their instruments are small synth programs (waveforms, filter and +pulse-width sweeps, a performance list). They load as a Module-shaped value (`format` `"ahx"` / `"hvl"`; `patterns` are +the tracks, 6 bytes per row: note, instrument, effect, parameter, second effect, parameter; `positions` hold each +channel's track and transpose; `subsongs`) and render through their own replayer, a port of HivelyTracker's, which gives +hvl2wav's samples exactly. Render options: `sampleRate`, `subsong` (0 = the main song), `loop`, `maxDuration` (default +600 s) and, for AHX, `stereo` 0..4 (0 mono as hvl2wav renders by default, 4 the Amiga's hard L R R L panning); HVL files +store their own panning and gain. + +```luau +local song = assert(F.music.load(ahxBytes)) +assert(song.format == "ahx" and song.channels == 4 and song.title == "demo") +local dec = song:render({ stereo = 4 }) -- a Decoder, stereo f32 at 44100 Hz +assert(dec.channels == 2 and dec.duration > 1) +local hvl = assert(F.music.load(hvlBytes)) +assert(hvl.format == "hvl" and hvl.channels == 6 and #hvl.subsongs == 1) +local intro = hvl:render({ subsong = 1, sampleRate = 22050 }) +local wav = assert(F.save(intro, nil, { format = "wav" })) +assert(F.detect(wav) == "wav" and F.detect(hvlBytes) == "hvl") +``` + +Doom MUS, Miles XMIDI and HMI's HMP / HMI files load as a **Midi**, so they play through the SoundFont synth and save +as a Standard MIDI File. MUS runs at 140 ticks per second (`rate` option), XMIDI at a fixed 120 (note durations become +note-offs; `track` picks the song of a multi-song file, `meta.source.songs` counts them), HMP / HMI at the rate in +their header. + +```luau +local doom = assert(F.music.load(musBytes)) +assert(doom.kind == "midi" and doom.meta.source.format == "mus") +local audio = assert(F.ops.audio.toAudio(doom:render({ soundfont = sf2Bytes, tail = 0.2 }))) +assert(audio.channels == 2) +local xmi = assert(F.music.load(xmiBytes, { track = 2 })) -- the second song +assert(xmi.meta.source.songs == 2 and xmi.meta.source.song == 2) +local smf = assert(F.save(xmi, nil, { format = "midi" })) -- as a .mid +assert(F.detect(smf) == "midi") +local hmp = assert(F.music.load(hmpBytes)) +assert(hmp.meta.source.format == "hmp" and #hmp.tracks == 3) +``` + +Karaoke `.kar` files are MIDI files with the lyrics in text events: `meta.lyrics` lists them with their time +(`{ time, tick, text }`; a leading `\` starts a new paragraph, `/` a new line), the `@` headers land in +`meta.karaoke` (`T` = title lines, `L` language, `I` info, ...) and `meta.tags`. + +```luau +local kar = assert(F.music.load(karBytes)) +assert(kar.meta.tags.title == "Little Song" and kar.meta.tags.artist == "The Docs") +local line = {} +for _, l in kar.meta.lyrics do + table.insert(line, l.text) +end +assert(table.concat(line) == "\\Hello /karaoke" and kar.meta.lyrics[2].time == 0.5) +``` + ## Gotchas - Saving music to an audio format renders it with the options in `opts`: `F.save(song, nil, { format = "wav", @@ -325,4 +426,6 @@ See [FORMATS.md](../FORMATS.md) for each format's capabilities. - Without a SoundFont, MIDI plays on simple built-in waveforms, which is fine for testing but not General MIDI. SF3 banks (Ogg-compressed samples) are not supported. - Pattern cells keep the file's own effect numbering, which differs between MOD / XM (0..35) and S3M / IT (1..26). + The other tracker formats use their engine family's numbering (`m.engine`), not their file's. +- A Module's `meta.unsupported` lists what was read but plays silent (MED synth / hybrid / MIDI instruments). - A module's `duration` is one pass. `render({ loop = true })` keeps playing past it. diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index f74817c..186b69f 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -37,6 +37,13 @@ | `src/Formats/codecs/Vp8/` inter frames (Decode: inter headers / modes / motion vectors / references, Predict, the inter tables in Tables) | Luau translations of libvpx 1.17 (WebM Project): vp8/decoder/decodeframe.c, decodemv.c, onyxd_if.c; vp8/common/findnearmv.c, reconinter.c, filter.c, vp8_loopfilter.c, entropymode.c, entropymv.c, modecont.c | BSD-3-Clause + patent grant: [libvpx-LICENSE.txt](libvpx-LICENSE.txt) | | `tests/fixtures/vp8video/vp80-*.ivf` | the VP8 test vectors of the libvpx test data (vp80-00-comprehensive-001..018 and others) | WebM Project, BSD-3-Clause + patent grant: [libvpx-LICENSE.txt](libvpx-LICENSE.txt) | | `src/Formats/codecs/H264/` (Tables: CAVLC / CABAC / deblocking / scaling constant tables of ITU-T H.264, extracted from openh264 sources; the decoder itself is written from the spec) | openh264 2.x (Cisco) | BSD-2-Clause: [openh264-LICENSE.txt](openh264-LICENSE.txt) | +| `src/Formats/codecs/audio/Adpcm/` (the ADX coefficient derivation, PS-ADPCM / DSP / ADX decode details, followed for bit-exact output; the container layouts of audio/adx, audio/vag, audio/brstm) | vgmstream r2117 | ISC-style: [vgmstream-LICENSE.txt](vgmstream-LICENSE.txt) | +| `src/Formats/codecs/audio/Qoa/` (port of qoa.h: tables, LMS predictor, decoder, encoder); `tests/fixtures/qoa/qoa.h` (the reference, compiled at fixture time) | qoa.h (phoboslab/qoa, Dominic Szablewski) | MIT: [qoa-LICENSE.txt](qoa-LICENSE.txt) | +| `src/Formats/codecs/audio/Hively/` (Tables, Load, Player: the AHX / HVL loaders, waveform generator and replayer) | port of HivelyTracker hvl2wav replay.c 1.9 by Pete Gordon (Xeron/IRIS); `tests/gen/ahx_cases` / `hvl_cases` also embed songs from its Songs/ directory (fixture time, not committed) | BSD-3-Clause: [hivelytracker-LICENSE.txt](hivelytracker-LICENSE.txt) | +| `src/Formats/codecs/audio/Musepack/` (Decode, Tables, init: the SV7 / SV8 bitstream, Huffman tables, requantisation, synthesis, stream headers) | port of libmpcdec (musepack_src_r475, The Musepack Development Team) | BSD-3-Clause: [libmpcdec-BSD.txt](libmpcdec-BSD.txt) | +| `src/Formats/codecs/audio/WavPack/` (Block, Tables), `src/Formats/audio/wavpack/` | Luau port of the WavPack 5.9.0 decoder by David Bryant: unpack.c, read_words.c, unpack_floats.c, decorr_utils.c, entropy_utils.c (tables, wp_log2 / wp_exp2s), open_utils.c (metadata, block checksum) | BSD-3-Clause: [wavpack-LICENSE.txt](wavpack-LICENSE.txt) | +| `src/Formats/codecs/audio/Ape/` (Decode, init), `src/Formats/audio/ape/` | Luau port of the Monkey's Audio SDK 13.28 decoder by Matthew T. Ashland: UnBitArray.cpp / Old/UnBitArrayOld.cpp (range coder), NNFilter, NewPredictor.cpp, ScaledFirstOrderFilter.h, Prepare.cpp (Unprepare), APEDecompressCore.cpp, APEHeader.cpp, FloatTransform.cpp | BSD-3-Clause (since SDK v10): [monkeys-audio-LICENSE.txt](monkeys-audio-LICENSE.txt) | +| `src/Formats/music/{mtm,669,stm,ult,okt,med,ptm,far,umx}/`, `src/Formats/codecs/audio/Tracker/Load.luau` (loaders and effect conversions ported from OpenMPT's Load_*.cpp / ModCommand / UMXTools) | libopenmpt 0.8.9 (OpenMPT Project Developers, Olivier Lapicque) | BSD-3-Clause: [openmpt-LICENSE.txt](openmpt-LICENSE.txt) | | `src/Formats/codecs/video/Dsp.luau` (the 8x8 IDCT: jrevdct.c translated to Luau, branch tree and constants unchanged) | IJG jrevdct.c as shipped in ffmpeg (libavcodec/jrevdct.c; IJG-licensed, not LGPL: ffmpeg's LICENSE.md) | IJG: [libjpeg-README.ijg](libjpeg-README.ijg). This software is based in part on the work of the Independent JPEG Group. | | `tests/gen/h264_jvt` (downloaded at fixture time, not committed) | ITU-T H.264.1 / JVT conformance bitstreams (itu.int) | ITU-T test data | | `src/Formats/codecs/video/Theora/` (Header, Decoder) | a Luau port of the libtheora 1.2.0 decoder (Xiph.Org; decinfo.c, dequant.c, quant.c, huffdec.c, decode.c, state.c, idct.c, fragment.c) checked against the Theora I specification; the token storage is simplified (coefficients per fragment) and the post-processing is not ported | BSD 3-clause: [libtheora-BSD.txt](libtheora-BSD.txt) | diff --git a/licenses/hivelytracker-LICENSE.txt b/licenses/hivelytracker-LICENSE.txt new file mode 100644 index 0000000..2100428 --- /dev/null +++ b/licenses/hivelytracker-LICENSE.txt @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2006-2018, Pete Gordon +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/licenses/libmpcdec-BSD.txt b/licenses/libmpcdec-BSD.txt new file mode 100644 index 0000000..156247c --- /dev/null +++ b/licenses/libmpcdec-BSD.txt @@ -0,0 +1,36 @@ +libmpcdec (musepack_src_r475, https://files.musepack.net/source/musepack_src_r475.tar.gz), ported to +src/Formats/codecs/audio/Musepack (Decode.luau, Tables.luau, init.luau): + +Copyright (c) 2005, The Musepack Development Team +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + + * Neither the name of the The Musepack Development Team nor the + names of its contributors may be used to endorse or promote + products derived from this software without specific prior + written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +The 2005-2009 copyright headers of mpc_decoder.c / synth_filter.c / huffman.c carry the same licence. diff --git a/licenses/monkeys-audio-LICENSE.txt b/licenses/monkeys-audio-LICENSE.txt new file mode 100644 index 0000000..e4a0ca5 --- /dev/null +++ b/licenses/monkeys-audio-LICENSE.txt @@ -0,0 +1,11 @@ +Monkey's Audio License Agreement (3 clause BSD) + +Copyright 2000-2026 Matthew T. Ashland. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. +2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. +3) Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/licenses/openmpt-LICENSE.txt b/licenses/openmpt-LICENSE.txt new file mode 100644 index 0000000..6f8a33d --- /dev/null +++ b/licenses/openmpt-LICENSE.txt @@ -0,0 +1,25 @@ +Copyright (c) 2004-2026, OpenMPT Project Developers and Contributors +Copyright (c) 1997-2003, Olivier Lapicque +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the OpenMPT project nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/licenses/qoa-LICENSE.txt b/licenses/qoa-LICENSE.txt new file mode 100644 index 0000000..50ab742 --- /dev/null +++ b/licenses/qoa-LICENSE.txt @@ -0,0 +1,20 @@ +qoa.h - The "Quite OK Audio" format for fast, lossy audio compression +https://github.com/phoboslab/qoa + +Copyright (c) 2023, Dominic Szablewski - https://phoboslab.org +SPDX-License-Identifier: MIT + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the +Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/licenses/vgmstream-LICENSE.txt b/licenses/vgmstream-LICENSE.txt new file mode 100644 index 0000000..033f42a --- /dev/null +++ b/licenses/vgmstream-LICENSE.txt @@ -0,0 +1,23 @@ +Copyright (c) 2008-2025 Adam Gashlin, Fastelbja, Ronny Elfert, bnnm, + Christopher Snowhill, NicknineTheEagle, bxaimc, + Thealexbarney, CyberBotX, EdnessP, et al + +Portions Copyright (c) 2004-2008, Marko Kreen +Portions Copyright 2001-2007 jagarl / Kazunori Ueno +Portions Copyright (c) 1998, Justin Frankel/Nullsoft Inc. +Portions Copyright (C) 2006 Nullsoft, Inc. +Portions Copyright (c) 2005-2007 Paul Hsieh +Portions Copyright (C) 2000-2004 Leshade Entis, Entis-soft. +Portions Public Domain originating with Sun Microsystems + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/licenses/wavpack-LICENSE.txt b/licenses/wavpack-LICENSE.txt new file mode 100644 index 0000000..a013696 --- /dev/null +++ b/licenses/wavpack-LICENSE.txt @@ -0,0 +1,25 @@ + Copyright (c) 1998 - 2025 David Bryant + All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index ce39587..398f460 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -290,18 +290,66 @@ local list: { Entry } = { return require("@formats/audio/aac") end, }, + { + name = "ac3", + category = "audio", + path = "audio/ac3", + extensions = { "ac3", "a52" }, + mime = { "audio/ac3", "audio/x-ac3" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/Ac3" }, + caps = { decode = true, encode = false, codecs = { "ac3" }, channels = 6, streaming = true, lossy = true }, + load = function() + return require("@formats/audio/ac3") + end, + }, + { + name = "adpcm", + category = "audio", + path = "audio/adpcm", + extensions = { "adpcm", "ima" }, + mime = { "audio/x-adpcm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" }, + caps = { decode = true, encode = true, streaming = true, lossy = true, headerless = true, codecs = { "ima", "ima_wav", "ms", "ima_qt", "psx" } }, + load = function() + return require("@formats/audio/adpcm") + end, + }, + { + name = "adx", + category = "audio", + path = "audio/adx", + extensions = { "adx" }, + mime = { "audio/x-adx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" }, + caps = { decode = true, encode = true, streaming = true, lossy = true, loops = true, channels = 8 }, + load = function() + return require("@formats/audio/adx") + end, + }, { name = "aiff", category = "audio", path = "audio/aiff", extensions = { "aiff", "aif", "aifc", "afc" }, mime = { "audio/aiff", "audio/x-aiff" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "containers/Chunks" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm/Decoder", "containers/Chunks" }, caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false }, load = function() return require("@formats/audio/aiff") end, }, + { + name = "ape", + category = "audio", + path = "audio/ape", + extensions = { "ape" }, + mime = { "audio/ape", "audio/x-ape", "audio/x-monkeys-audio" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Ape" }, + caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, float = true, depths = { 8, 16, 24, 32 } }, + load = function() + return require("@formats/audio/ape") + end, + }, { name = "au", category = "audio", @@ -314,13 +362,25 @@ local list: { Entry } = { return require("@formats/audio/au") end, }, + { + name = "brstm", + category = "audio", + path = "audio/brstm", + extensions = { "brstm", "bcstm", "bfstm" }, + mime = { "audio/x-brstm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm/Decoder" }, + caps = { decode = true, encode = false, streaming = true, lossy = true, loops = true, containers = { "RSTM", "CSTM", "FSTM" } }, + load = function() + return require("@formats/audio/brstm") + end, + }, { name = "caf", category = "audio", path = "audio/caf", extensions = { "caf", "caff" }, mime = { "audio/x-caf" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Aac", "codecs/audio/Alac", "codecs/audio/Pcm", "codecs/audio/Stream", "containers/Chunks" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Aac", "codecs/audio/Adpcm/Decoder", "codecs/audio/Alac", "codecs/audio/Pcm", "codecs/audio/Stream", "containers/Chunks" }, caps = { decode = true, encode = true, codecs = { "pcm", "alac", "aac", "ulaw", "alaw" }, encodeCodecs = { "pcm", "alac" }, tags = true, streaming = true }, load = function() return require("@formats/audio/caf") @@ -362,6 +422,18 @@ local list: { Entry } = { return require("@formats/audio/mp3") end, }, + { + name = "mpc", + category = "audio", + path = "audio/mpc", + extensions = { "mpc", "mp+", "mpp" }, + mime = { "audio/x-musepack", "audio/musepack" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Musepack" }, + caps = { decode = true, encode = false, codecs = { "musepack" }, versions = { 7, 8 }, streaming = true, lossy = true }, + load = function() + return require("@formats/audio/mpc") + end, + }, { name = "opus", category = "audio", @@ -374,6 +446,42 @@ local list: { Entry } = { return require("@formats/audio/opus") end, }, + { + name = "qoa", + category = "audio", + path = "audio/qoa", + extensions = { "qoa" }, + mime = { "audio/qoa" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/Qoa" }, + caps = { decode = true, encode = true, streaming = true, lossy = true, seek = true, channels = 8 }, + load = function() + return require("@formats/audio/qoa") + end, + }, + { + name = "tta", + category = "audio", + path = "audio/tta", + extensions = { "tta" }, + mime = { "audio/x-tta", "audio/tta" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Tta" }, + caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, depths = { 8, 16, 24 } }, + load = function() + return require("@formats/audio/tta") + end, + }, + { + name = "vag", + category = "audio", + path = "audio/vag", + extensions = { "vag" }, + mime = { "audio/x-vag" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" }, + caps = { decode = true, encode = true, streaming = true, lossy = true, loops = true, channels = 2 }, + load = function() + return require("@formats/audio/vag") + end, + }, { name = "voc", category = "audio", @@ -404,12 +512,24 @@ local list: { Entry } = { path = "audio/wav", extensions = { "wav", "wave", "rf64", "bw64" }, mime = { "audio/wav", "audio/x-wav", "audio/wave", "audio/vnd.wave" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Riff", "codecs/audio/Pcm" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Riff", "codecs/audio/Pcm", "codecs/audio/Adpcm" }, caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, rf64 = true }, load = function() return require("@formats/audio/wav") end, }, + { + name = "wavpack", + category = "audio", + path = "audio/wavpack", + extensions = { "wv" }, + mime = { "audio/x-wavpack", "audio/wavpack" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/WavPack" }, + caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, hybrid = true, float = true, depths = { 8, 12, 16, 20, 24, 32 } }, + load = function() + return require("@formats/audio/wavpack") + end, + }, { name = "avi", category = "video", @@ -1238,6 +1358,66 @@ local list: { Entry } = { return require("@formats/subtitle/vtt") end, }, + { + name = "669", + category = "music", + path = "music/669", + extensions = { "669" }, + mime = { "audio/x-669" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 8, 8 } }, + load = function() + return require("@formats/music/669") + end, + }, + { + name = "ahx", + category = "music", + path = "music/ahx", + extensions = { "ahx", "thx" }, + mime = { "audio/x-ahx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Hively" }, + caps = { decode = true, encode = false, render = true, channels = { 4, 4 }, subsongs = true }, + load = function() + return require("@formats/music/ahx") + end, + }, + { + name = "far", + category = "music", + path = "music/far", + extensions = { "far" }, + mime = { "audio/x-far" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 16, 16 } }, + load = function() + return require("@formats/music/far") + end, + }, + { + name = "hmp", + category = "music", + path = "music/hmp", + extensions = { "hmp", "hmi" }, + mime = { "audio/x-hmp" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/MidiRender" }, + caps = { decode = true, encode = false, render = true, hmi = true }, + load = function() + return require("@formats/music/hmp") + end, + }, + { + name = "hvl", + category = "music", + path = "music/hvl", + extensions = { "hvl" }, + mime = { "audio/x-hvl" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Hively" }, + caps = { decode = true, encode = false, render = true, channels = { 4, 16 }, subsongs = true }, + load = function() + return require("@formats/music/hvl") + end, + }, { name = "it", category = "music", @@ -1250,13 +1430,25 @@ local list: { Entry } = { return require("@formats/music/it") end, }, + { + name = "med", + category = "music", + path = "music/med", + extensions = { "med", "mmd0", "mmd1", "mmd2", "mmd3", "omed" }, + mime = { "audio/x-med" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 64 } }, + load = function() + return require("@formats/music/med") + end, + }, { name = "midi", category = "music", path = "music/midi", extensions = { "mid", "midi", "smf", "kar", "rmi" }, mime = { "audio/midi", "audio/x-midi" }, - deps = { "core/Err", "core/Bytes", "codecs/audio/SoundFont", "Types" }, + deps = { "core/Err", "core/Bytes", "codecs/audio/MidiRender", "Types" }, caps = { decode = true, encode = true, formats = { 0, 1, 2 }, render = true, streaming = true, rmid = true }, load = function() return require("@formats/music/midi") @@ -1274,6 +1466,54 @@ local list: { Entry } = { return require("@formats/music/mod") end, }, + { + name = "mtm", + category = "music", + path = "music/mtm", + extensions = { "mtm" }, + mime = { "audio/x-mtm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 32 } }, + load = function() + return require("@formats/music/mtm") + end, + }, + { + name = "mus", + category = "music", + path = "music/mus", + extensions = { "mus" }, + mime = { "audio/x-mus" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/MidiRender" }, + caps = { decode = true, encode = false, render = true }, + load = function() + return require("@formats/music/mus") + end, + }, + { + name = "okt", + category = "music", + path = "music/okt", + extensions = { "okt", "okta" }, + mime = { "audio/x-okt" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 4, 8 } }, + load = function() + return require("@formats/music/okt") + end, + }, + { + name = "ptm", + category = "music", + path = "music/ptm", + extensions = { "ptm" }, + mime = { "audio/x-ptm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 32 } }, + load = function() + return require("@formats/music/ptm") + end, + }, { name = "s3m", category = "music", @@ -1298,18 +1538,66 @@ local list: { Entry } = { return require("@formats/music/sf2") end, }, + { + name = "stm", + category = "music", + path = "music/stm", + extensions = { "stm" }, + mime = { "audio/x-stm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 4, 4 } }, + load = function() + return require("@formats/music/stm") + end, + }, + { + name = "ult", + category = "music", + path = "music/ult", + extensions = { "ult" }, + mime = { "audio/x-ult" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 32 } }, + load = function() + return require("@formats/music/ult") + end, + }, + { + name = "umx", + category = "music", + path = "music/umx", + extensions = { "umx" }, + mime = { "audio/x-umx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" }, + caps = { decode = true, encode = false, render = true, container = true }, + load = function() + return require("@formats/music/umx") + end, + }, { name = "xm", category = "music", path = "music/xm", extensions = { "xm" }, mime = { "audio/xm", "audio/x-xm" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Adpcm" }, caps = { decode = true, encode = true, render = true, channels = { 1, 64 } }, load = function() return require("@formats/music/xm") end, }, + { + name = "xmi", + category = "music", + path = "music/xmi", + extensions = { "xmi", "xmidi" }, + mime = { "audio/x-xmidi" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/audio/MidiRender" }, + caps = { decode = true, encode = false, render = true, songs = true }, + load = function() + return require("@formats/music/xmi") + end, + }, { name = "m3u", category = "playlist", diff --git a/src/Formats/Types.luau b/src/Formats/Types.luau index a35b2aa..fd4092d 100644 --- a/src/Formats/Types.luau +++ b/src/Formats/Types.luau @@ -138,7 +138,7 @@ Types.Audio = Audio export type Module = { kind: "music", title: string, - format: string, -- "mod", "s3m", "xm", "it", "mid" + format: string, -- "mod", "s3m", "xm", "it" (codecs/audio/Tracker); "ahx", "hvl" (codecs/audio/Hively, own render) channels: number, patterns: { any }, order: { number }, diff --git a/src/Formats/audio/ac3/init.luau b/src/Formats/audio/ac3/init.luau new file mode 100644 index 0000000..c481523 --- /dev/null +++ b/src/Formats/audio/ac3/init.luau @@ -0,0 +1,147 @@ +--!strict +-- audio/ac3: raw AC-3 (Dolby Digital, ATSC A/52) elementary streams, the .ac3 files of DVD / broadcast rips, through +-- codecs/audio/Ac3 (written from the A/52 specification). Supports: every channel layout (1+1, 1/0 .. 3/2, LFE) +-- output in WAVE order without downmixing, 32 / 44.1 / 48 kHz, every bit rate, coupling, rematrixing, block +-- switching, delta bit allocation, the CRC check, resync over garbage, a truncated last frame (dropped), streaming and +-- exact seeking (one frame of pre-roll for the overlap). Dynamic range control is off by default (`drc` = 0 .. 1). +-- Not supported: writing, E-AC-3 / Dolby Digital Plus (UNSUPPORTED), bsid 9 / 10 reduced-rate streams. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/audio/Pcm") +local Stream = require("@formats/codecs/audio/Stream") +local Ac3 = require("@formats/codecs/audio/Ac3") + +-- ------------------------------------------------------------------------------------------------ contract +local Ac3Format = { + name = "ac3", + category = "audio", + extensions = { "ac3", "a52" }, + mime = { "audio/ac3", "audio/x-ac3" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/Ac3" }, + caps = { decode = true, encode = false, codecs = { "ac3" }, channels = 6, streaming = true, lossy = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + maxFrames: number?, -- refuse streams with more syncframes (default 2^22) + drc: number?, -- dynamic range control scale: 0 = off (default), 1 = full + crc: boolean?, -- check every syncframe's CRC (default true; a bad frame ends the stream with Err.CHECKSUM) +} + +-- ------------------------------------------------------------------------------------------------ sniff +-- (E-AC-3 streams sniff too, so loading one says UNSUPPORTED instead of an unknown format) +function Ac3Format.sniff(r: Bytes.Reader): number + local b, p, limit = r.buf, r.pos, r.limit + local h = Ac3.header(b, p, limit) + if not h then + return 0 + end + local h2 = Ac3.header(b, p + h.frameSize, limit) + if h2 and h2.sampleRate == h.sampleRate then + return 0.9 + end + return if p + h.frameSize >= limit then 0.6 else 0.3 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the syncframe index (resyncing over garbage: a header counts when the next one follows it, or the data ends) +local function index(r: Bytes.Reader, maxFrames: number): ({ number }, { number }, Ac3.Header?, Err.Err?) + local b, limit = r.buf, r.limit + local p = r.base + local offs, sizes = {}, {} + local first: Ac3.Header? = nil + while p + 8 <= limit do + local h = Ac3.header(b, p, limit) + if h and first and (h.sampleRate ~= first.sampleRate or h.bsid > 10) then + h = nil + end + if h and not first and p + h.frameSize + 8 <= limit then + local h2 = Ac3.header(b, p + h.frameSize, limit) + if not h2 then + h = nil -- a false sync word + end + end + if not h then + p += 1 + continue + end + if not first then + first = h + if h.bsid > 10 then + return offs, sizes, first, Err.new(Err.UNSUPPORTED, "E-AC-3 (Dolby Digital Plus)", p) + elseif h.bsid > 8 then + return offs, sizes, first, Err.new(Err.UNSUPPORTED, "reduced sample rate AC-3 (bsid " .. h.bsid .. ")", p) + end + end + if p + h.frameSize > limit then + break -- a truncated last frame + end + table.insert(offs, p) + table.insert(sizes, h.frameSize) + if #offs > maxFrames then + return offs, sizes, first, Err.new(Err.LIMIT, "more than " .. maxFrames .. " frames") + end + p += h.frameSize + end + return offs, sizes, first, nil +end + +function Ac3Format.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) + local o: DecodeOptions = opts or {} + local offs, sizes, first, ierr = index(r, o.maxFrames or 2 ^ 22) + if ierr then + return nil, ierr + end + if not first or #offs == 0 then + return nil, Err.new(Err.CORRUPT, "no AC-3 syncframe", r.base) + end + local h = first :: Ac3.Header + local d = Ac3.decoder({ drc = o.drc, crc = o.crc }) + local buf = r.buf + local n = #offs + local out = { + sampleRate = h.sampleRate, + channels = h.channels, + frames = n * 1536, + duration = n * 1536 / h.sampleRate, + bitrate = h.bitrate, + tags = {}, + codec = "ac3", + acmod = h.acmod, + lfe = h.lfeon, + } + return Stream.packets(out, { + count = n, + start = function(i: number): number + return (i - 1) * 1536 + end, + decode = function(i: number): (number?, Err.Err?) + local frames, err = d:decode(buf, offs[i], sizes[i]) + if frames and d.channels ~= h.channels then + return nil, Err.new(Err.UNSUPPORTED, "channel layout change inside the stream", offs[i]) + end + return frames, err + end, + pcm = function(): { number } + return d.pcm + end, + reset = function() + d:reset() + end, + preroll = 1, + }) +end + +function Ac3Format.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = Ac3Format.open(r, opts) + if not dec then + return nil, err + end + local d: any = dec + return Pcm.drain(d, { format = "ac3", codec = "ac3", acmod = d.acmod, lfe = d.lfe, bitrate = d.bitrate }) +end + +return Ac3Format diff --git a/src/Formats/audio/adpcm/init.luau b/src/Formats/audio/adpcm/init.luau new file mode 100644 index 0000000..16627c5 --- /dev/null +++ b/src/Formats/audio/adpcm/init.luau @@ -0,0 +1,155 @@ +--!strict +-- audio/adpcm: headerless ADPCM streams (.adpcm / .ima / .vox-style dumps), over codecs/audio/Adpcm. New in +-- formats-luau. A raw stream has no header, so nothing identifies it: sniff is always 0, F.detect only finds it by +-- extension, and the layout comes from the options (codec, sampleRate, channels, blockAlign). vgmstream plays such +-- files only through a .txth description and ffmpeg not at all (its adpcm_* codecs need a container), so the codecs +-- here are the layouts those containers use: +-- "ima" IMA nibbles from predictor 0 / step index 0, channels interleaved by nibble, the high nibble first +-- (DVI order, as KVAG / adpcm_ima_ssi); lowFirst = true for the other order +-- "ima_wav" Microsoft IMA blocks (the WAV / AVI data chunk), blockAlign bytes each (default 1024) +-- "ms" Microsoft ADPCM blocks with the 7 standard coefficient pairs (default blockAlign 1024) +-- "ima_qt" Apple ima4 packets (34 bytes per channel, 64 frames), as in AIFF-C / CAF / QuickTime +-- "psx" Sony PS-ADPCM frames (16 bytes, 28 samples), channels interleaved every `interleave` bytes (default 16) +-- Encode: "ima", "ima_wav" and "ms" (from an Audio or a Decoder). Not supported: raw DSP / ADX (their coefficients +-- live in a header: see audio/brstm and audio/adx). +-- +-- local a = Adpcm.decode(Bytes.reader(buf), { codec = "ms", sampleRate = 22050, channels = 2, blockAlign = 512 }) +-- local raw = Adpcm.encode(a, { codec = "ima" }) + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/audio/Pcm") +local Adpcm = require("@formats/codecs/audio/Adpcm") +local Decoder = require("@formats/codecs/audio/Adpcm/Decoder") + +-- ------------------------------------------------------------------------------------------------ contract +local Raw = { + name = "adpcm", + category = "audio", + extensions = { "adpcm", "ima" }, + mime = { "audio/x-adpcm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" }, + caps = { decode = true, encode = true, streaming = true, lossy = true, headerless = true, codecs = { "ima", "ima_wav", "ms", "ima_qt", "psx" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type Codec = "ima" | "ima_wav" | "ms" | "ima_qt" | "psx" +export type Options = { + codec: Codec?, -- default "ima" + sampleRate: number?, -- default 22050 (decode) + channels: number?, -- default 1 (decode) + blockAlign: number?, -- ima_wav / ms: bytes per block (default 1024 when decoding; 256 * channels when encoding) + lowFirst: boolean?, -- ima: the low nibble first + interleave: number?, -- psx: bytes per channel before the next channel (default 16) + maxFrames: number?, -- decode(): Err.LIMIT past this (default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ constants +local CODECS = { ima = true, ima_wav = true, ms = true, ima_qt = true, psx = true } + +-- ------------------------------------------------------------------------------------------------ sniff +function Raw.sniff(_r: Bytes.Reader): number + return 0 -- no header: found by extension or opts.format only +end + +-- ------------------------------------------------------------------------------------------------ decode +function Raw.decode(r: Bytes.Reader, opts: Options?): (Types.Audio?, Err.Err?) + local dec, err = Raw.open(r, opts) + if not dec then + return nil, err + end + local limit = opts and opts.maxFrames or 2 ^ 28 + if dec.frames > limit or dec.frames * dec.channels > 2 ^ 28 then + return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", dec.frames)) + end + return Pcm.drain(dec, { format = "adpcm", codec = (dec :: any).codec }, limit) +end + +-- ------------------------------------------------------------------------------------------------ encode +function Raw.encode(value: any, opts: Options?): (buffer?, Err.Err?) + local o: Options = opts or {} + local codec = o.codec or "ima" + if codec ~= "ima" and codec ~= "ima_wav" and codec ~= "ms" then + return nil, Err.new(Err.ARG, "encode: codec must be ima, ima_wav or ms") + end + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local a, cerr = Pcm.collect(src) + if not a then + return nil, cerr + end + local ch, n, x = a.channels, a.frames, a.samples + if codec == "ima" then + local out = buffer.create((n * ch + 1) // 2) + local st = buffer.create(8 * ch) + for c = 0, ch - 1 do + Adpcm.imaEncode(x, c, ch, n, st, c * 8, out, 0, c, ch, not o.lowFirst) + end + return out, nil + end + local ba = o.blockAlign or 256 * ch + local spb = Decoder.blockFrames(codec, ba, ch) + if type(ba) ~= "number" or ba ~= math.floor(ba) or ba > 65535 or not spb or spb < 2 then + return nil, Err.new(Err.ARG, "bad blockAlign " .. tostring(ba)) + end + if codec == "ima_wav" and (ba % (4 * ch) ~= 0) then + return nil, Err.new(Err.ARG, "ima_wav: blockAlign must be a multiple of 4 * channels") + end + local blocks = (n + spb - 1) // spb + local out = buffer.create(blocks * ba) + local st = buffer.create(8 * ch) + for b = 0, blocks - 1 do + local f0 = b * spb + if codec == "ms" then + Adpcm.msEncode(x, f0, n - f0, ch, spb, out, b * ba) + else + Adpcm.imaWavEncode(x, f0, n - f0, ch, spb, st, out, b * ba) + end + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Raw.open(r: Bytes.Reader, opts: Options?): (Types.Decoder?, Err.Err?) + if type(r) ~= "table" or type(r.buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "open: expected a Reader") + end + local o: Options = opts or {} + local codec = o.codec or "ima" + local rate, ch = o.sampleRate or 22050, o.channels or 1 + if not CODECS[codec] then + return nil, Err.new(Err.ARG, "unknown codec " .. tostring(codec)) + end + if type(rate) ~= "number" or rate <= 0 or rate ~= rate or type(ch) ~= "number" or ch < 1 or ch > 255 or ch ~= math.floor(ch) then + return nil, Err.new(Err.ARG, "bad sampleRate or channels") + end + local size = r.limit - r.base + local dec: any = { sampleRate = rate, channels = ch, tags = {}, codec = codec, frames = 0, duration = 0 } + local d, err + if codec == "ima" then + d, err = Decoder.nibbles(dec, { buf = r.buf, offset = r.base, size = size, hi = not o.lowFirst }) + elseif codec == "psx" then + local il = o.interleave or 16 + if type(il) ~= "number" or il < 16 or il % 16 ~= 0 then + return nil, Err.new(Err.ARG, "interleave must be a multiple of 16") + end + d, err = Decoder.interleaved(dec, { kind = "psx", buf = r.buf, offset = r.base, size = size, interleave = if ch == 1 then 16 else il }) + else + local ba = o.blockAlign or 1024 + if type(ba) ~= "number" or ba < 1 or ba ~= math.floor(ba) then + return nil, Err.new(Err.ARG, "bad blockAlign") + end + d, err = Decoder.blocks(dec, { kind = codec :: any, buf = r.buf, offset = r.base, size = size, blockAlign = ba }) + end + if not d then + return nil, err + end + d.bitrate = if d.duration > 0 then math.floor(size * 8 / d.duration) else 0 + return d, nil +end + +return Raw diff --git a/src/Formats/audio/adx/init.luau b/src/Formats/audio/adx/init.luau new file mode 100644 index 0000000..40154f8 --- /dev/null +++ b/src/Formats/audio/adx/init.luau @@ -0,0 +1,237 @@ +--!strict +-- audio/adx: CRI ADX (.adx), the game-audio ADPCM of Sega / CRI Middleware, over codecs/audio/Adpcm. New in +-- formats-luau; the header layout and the decoder details follow vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt), +-- whose output it matches bit for bit (the scale + 1 of CRI's decoders, the version 3 rounding; ffmpeg's ADX decoder +-- differs slightly on both). Supports: encoding type 3 (the standard predictor from the header's high-pass cutoff), +-- versions 3, 4 and 5, 1-8 channels, the initial history of version 4, loop points (dec.loop and +-- meta.source.loop = { start, stop } in frames, stop exclusive). Encode (Audio or Decoder): version 4, 1-8 channels, +-- loop points from opts.loop. Not supported: encrypted ADX (versions 0x0408 / 0x0409, keys needed), the fixed (2) and +-- exponential (4) encoding types, AHX. +-- +-- local dec = Adx.open(Bytes.reader(buf)) -- Types.Decoder (+ loop, version, cutoff) +-- local file = Adx.encode(audio, { loop = { start = 44100, stop = 441000 } }) + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/audio/Pcm") +local Adpcm = require("@formats/codecs/audio/Adpcm") +local Decoder = require("@formats/codecs/audio/Adpcm/Decoder") + +-- ------------------------------------------------------------------------------------------------ contract +local Adx = { + name = "adx", + category = "audio", + extensions = { "adx" }, + mime = { "audio/x-adx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" }, + caps = { decode = true, encode = true, streaming = true, lossy = true, loops = true, channels = 8 }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type Loop = { start: number, stop: number } +export type DecodeOptions = { + maxFrames: number?, -- decode(): Err.LIMIT past this (default 2^28) +} +export type EncodeOptions = { + loop: Loop?, -- loop points in frames (stop exclusive); default: the source's meta.source.loop / loop, else none + cutoff: number?, -- the predictor's high-pass cutoff in Hz (default 500, as CRI's encoders) +} + +-- ------------------------------------------------------------------------------------------------ constants +local FRAME = 18 + +-- ------------------------------------------------------------------------------------------------ sniff +function Adx.sniff(r: Bytes.Reader): number + if r:peekU8(0) ~= 0x80 or r:peekU8(1) ~= 0 then + return 0 + end + local off = r:peekU8(2) * 256 + r:peekU8(3) + return if r:peek(6, off - 2) == "(c)CRI" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Adx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = Adx.open(r) + if not dec then + return nil, err + end + local d = dec :: any + local limit = opts and opts.maxFrames or 2 ^ 28 + if d.frames > limit or d.frames * d.channels > 2 ^ 28 then + return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", d.frames)) + end + return Pcm.drain(d, { format = "adx", version = d.version, cutoff = d.cutoff, loop = d.loop }, limit) +end + +-- ------------------------------------------------------------------------------------------------ encode +function Adx.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local ch, rate = src.channels, src.sampleRate + if ch > 8 then + return nil, Err.new(Err.ARG, "ADX holds at most 8 channels") + end + if rate ~= math.floor(rate) or rate < 1 or rate >= 2 ^ 31 then + return nil, Err.new(Err.ARG, "the sample rate must be a positive integer") + end + local loop = o.loop + if loop == nil then + local v = value :: any + local m = type(v.meta) == "table" and type(v.meta.source) == "table" and v.meta.source.loop + loop = if type(m) == "table" then m else (if type(v.loop) == "table" then v.loop else nil) + end + local a, cerr = Pcm.collect(src) + if not a then + return nil, cerr + end + local n = a.frames + if loop and (type(loop.start) ~= "number" or type(loop.stop) ~= "number" or loop.start < 0 or loop.stop <= loop.start or loop.stop > n) then + return nil, Err.new(Err.ARG, "loop must be { start, stop } inside the audio") + end + local cutoff = o.cutoff or 500 + if type(cutoff) ~= "number" or cutoff < 1 or cutoff >= rate / 2 or cutoff > 65535 then + return nil, Err.new(Err.ARG, "bad cutoff") + end + cutoff = math.floor(cutoff) + local c1, c2 = Adpcm.adxCoefs(cutoff, rate) + local hist = if ch > 1 then 4 * ch else 8 + local start = 0x18 + hist + (if loop then 0x18 else 0) + 6 + start = (start + 3) // 4 * 4 + local nframes = (n + 31) // 32 + local w = Bytes.writer(start + (nframes + 1) * FRAME * ch) + w:u16be(0x8000) + w:u16be(start - 4) + w:u8(3) + w:u8(FRAME) + w:u8(4) + w:u8(ch) + w:u32be(rate) + w:u32be(n) + w:u16be(cutoff) + w:u16be(0x0400) + w:u32be(0) + w:fill(0, hist) + if loop then + local bytesAt = function(f: number): number + return start + (f // 32) * FRAME * ch + end + w:u16be(0) + w:u16be(1) + w:u32be(1) + w:u32be(loop.start) + w:u32be(bytesAt(loop.start)) + w:u32be(loop.stop) + w:u32be(bytesAt(loop.stop + 31)) + end + w:fill(0, start - 6 - w.pos) + w:string("(c)CRI") + local at = w:reserve(nframes * FRAME * ch) + local st = buffer.create(8 * ch) + for c = 0, ch - 1 do + Adpcm.adxEncode(a.samples, c, ch, n, c1, c2, st, c * 8, w.buf, at + c * FRAME, FRAME * ch) + end + w.pos = at + nframes * FRAME * ch + -- the end marker: scale 0x8001, then the padding size + w:u16be(0x8001) + w:u16be(FRAME - 4) + w:fill(0, FRAME - 4) + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Adx.open(r: Bytes.Reader, _opts: any?): (Types.Decoder?, Err.Err?) + if type(r) ~= "table" or type(r.buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "open: expected a Reader") + end + if Adx.sniff(r) == 0 then + return nil, Err.new(Err.CORRUPT, "not an ADX file") + end + local h = r:sub(0) + local copyright = (h:seek(2) and h:u16be()) or 0 + local start = copyright + 4 + local enc, fsize, bits, ch = h:u8(), h:u8(), h:u8(), h:u8() + local rate, frames, cutoff, version = h:u32be(), h:u32be(), h:u16be(), h:u16be() + if h.err then + return nil, h.err + end + if version == 0x0408 or version == 0x0409 then + return nil, Err.new(Err.UNSUPPORTED, "encrypted ADX (keys needed)") + end + if enc ~= 3 then + return nil, Err.new(Err.UNSUPPORTED, "encoding type " .. enc .. (if enc == 0x10 or enc == 0x11 then " (AHX)" else "")) + end + if fsize ~= FRAME or bits ~= 4 then + return nil, Err.new(Err.UNSUPPORTED, string.format("frame size %d, %d bits", fsize, bits)) + end + if ch < 1 or ch > 8 then + return nil, Err.new(Err.CORRUPT, "bad channel count " .. ch) + end + if rate < 1 or rate >= 2 ^ 31 then + return nil, Err.new(Err.CORRUPT, "bad sample rate " .. rate) + end + if version ~= 0x0300 and version ~= 0x0400 and version ~= 0x0500 then + return nil, Err.new(Err.UNSUPPORTED, string.format("version 0x%04X", version)) + end + local size = r.limit - r.base - start + if size < 0 then + return nil, Err.new(Err.TRUNCATED, "the header runs past the end") + end + -- loop points and the initial history (vgmstream's reading of the extra header fields) + local hist: { number }? = nil + local loopsAt: number? = nil + if version == 0x0300 then + if start - 6 >= 0x14 + 0x18 then + loopsAt = 0x14 + end + elseif version == 0x0400 then + local hsize = if ch > 1 then 4 * ch else 8 + hist = {} + for c = 0, ch - 1 do + local hh = r:sub(0x18 + c * 4, 4) + local h1, h2 = hh:i16be(), hh:i16be() + hist[c * 2 + 1], hist[c * 2 + 2] = if hh.err then 0 else h1, if hh.err then 0 else h2 + end + local ainf = 0 + local ai = r:sub(0x18 + hsize + 4, 8) + if ai:string(4) == "AINF" then + ainf = ai:u32be() + end + if start - ainf - 6 >= 0x18 + hsize + 0x18 then + loopsAt = 0x18 + hsize + end + end + local loopTable: { start: number, stop: number }? = nil + if loopsAt then + local l = r:sub(loopsAt + 4, 0x14) + local flag, ls, _, le = l:u32be(), l:u32be(), l:u32be(), l:u32be() + if not l.err and flag ~= 0 and le > ls then + loopTable = { start = ls, stop = le } + end + end + local c1, c2 = Adpcm.adxCoefs(cutoff, rate) + local dec: any = { sampleRate = rate, channels = ch, tags = {}, version = version, cutoff = cutoff, loop = loopTable } + local d, err = Decoder.interleaved(dec, { + kind = "adx", + buf = r.buf, + offset = r.base + start, + size = size, + interleave = FRAME, + frames = frames, + c1 = c1, + c2 = c2, + v3 = version == 0x0300, + hist = hist, + }) + if not d then + return nil, err + end + d.bitrate = rate * FRAME * ch * 8 // 32 + return d, nil +end + +return Adx diff --git a/src/Formats/audio/aiff/init.luau b/src/Formats/audio/aiff/init.luau index a0a4a8c..03f9b0c 100644 --- a/src/Formats/audio/aiff/init.luau +++ b/src/Formats/audio/aiff/init.luau @@ -3,8 +3,9 @@ -- Supports: decode / open of AIFF PCM (1..32 bits, big endian) and AIFF-C NONE / twos / sowt (little endian) / raw -- (unsigned 8-bit) / in24 / in32 / fl32 / fl64 / ulaw / alaw; NAME / AUTH / (c) / ANNO chunks as tags; truncated -- SSND data (the frames present are decoded, meta.source.truncated). Encode (Audio or Decoder, streamed) to AIFF 8 / --- 16 / 24 / 32-bit, or AIFF-C sowt / fl32 / fl64 / ulaw / alaw. Not supported: compressed AIFF-C codecs (ima4, MAC3 / --- MAC6, Qclp, ...: Err.UNSUPPORTED), MARK / INST loops (ignored), the ID3 chunk. +-- 16 / 24 / 32-bit, or AIFF-C sowt / fl32 / fl64 / ulaw / alaw. AIFF-C ima4 (Apple IMA ADPCM, codecs/audio/Adpcm; +-- COMM counts packets of 64 frames) decodes too. Not supported: the other compressed AIFF-C codecs (MAC3 / MAC6, +-- Qclp, ...: Err.UNSUPPORTED), MARK / INST loops (ignored), the ID3 chunk. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") @@ -12,6 +13,7 @@ local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Chunks = require("@formats/containers/Chunks") local Pcm = require("@formats/codecs/audio/Pcm") +local Adpcm = require("@formats/codecs/audio/Adpcm/Decoder") -- ------------------------------------------------------------------------------------------------ contract local Aiff = { @@ -19,7 +21,7 @@ local Aiff = { category = "audio", extensions = { "aiff", "aif", "aifc", "afc" }, mime = { "audio/aiff", "audio/x-aiff" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "containers/Chunks" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm/Decoder", "containers/Chunks" }, caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false }, } @@ -115,6 +117,8 @@ local function sampleFormat(comp: string, bits: number): (string?, string?) return "ulaw", nil elseif comp == "alaw" or comp == "ALAW" then return "alaw", nil + elseif comp == "ima4" then + return "ima4", nil -- not a Pcm format: Adpcm/Decoder.blocks end return nil, "compression " .. string.format("%q", comp) end @@ -138,6 +142,7 @@ type Info = { compression: string, aifc: boolean, dataOffset: number, -- absolute in r.buf + dataSize: number, -- bytes of sample data present truncated: boolean, tags: Types.Tags, } @@ -194,6 +199,7 @@ local function parse(r: Bytes.Reader): (Info?, Err.Err?) compression = comp, aifc = aifc, dataOffset = 0, + dataSize = 0, truncated = false, tags = tags, } @@ -228,13 +234,19 @@ local function parse(r: Bytes.Reader): (Info?, Err.Err?) if fi.frames > 0 and not ssnd then return nil, Err.new(Err.TRUNCATED, "no SSND chunk", base) end - local frameBytes = fi.channels * Pcm.Convert.SIZE[fi.format] - local present = if ssnd then ssndLen // frameBytes else 0 + local present + if fi.format == "ima4" then + fi.frames *= 64 -- COMM counts packets + present = if ssnd then ssndLen // (34 * fi.channels) * 64 else 0 + else + present = if ssnd then ssndLen // (fi.channels * Pcm.Convert.SIZE[fi.format]) else 0 + end if present < fi.frames then fi.frames = present fi.truncated = true end fi.dataOffset = ssnd or base + fi.dataSize = ssndLen return fi, nil end @@ -360,7 +372,16 @@ function Aiff.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err. if info.frames > maxFrames then return nil, Err.new(Err.LIMIT, string.format("%d frames is over the %d frame limit", info.frames, maxFrames)) end - local dec, derr = Pcm.rawDecoder(r.buf, info.dataOffset, info.frames, info.channels, info.sampleRate, info.format, info.tags) + local dec, derr + if info.format == "ima4" then + local base = { sampleRate = info.sampleRate, channels = info.channels, tags = info.tags } + dec, derr = Adpcm.blocks(base, { kind = "ima_qt", buf = r.buf, offset = info.dataOffset, size = info.dataSize, frames = info.frames }) + if dec then + (dec :: any).bitrate = math.floor(info.sampleRate * 34 * 8 * info.channels / 64) + end + else + dec, derr = Pcm.rawDecoder(r.buf, info.dataOffset, info.frames, info.channels, info.sampleRate, info.format, info.tags) + end if not dec then return nil, derr end diff --git a/src/Formats/audio/ape/init.luau b/src/Formats/audio/ape/init.luau new file mode 100644 index 0000000..72d25dc --- /dev/null +++ b/src/Formats/audio/ape/init.luau @@ -0,0 +1,134 @@ +--!strict +-- audio/ape: Monkey's Audio (.ape) files around codecs/audio/Ape: the header in front (after an optional ID3v2 tag), +-- the frames (each independent: sample-accurate seeking through the seek table), APEv2 tags at the end +-- (codecs/audio/ApeTag). Written from the Monkey's Audio SDK 13.28 (BSD 3-clause, licenses/monkeys-audio-LICENSE.txt). +-- Supports file versions 3.95 and later, every compression level, 8 - 32-bit integer and 32-bit float, 1 - 32 +-- channels (as the source WAV ordered them). Not supported: files before 3.95, encoding. +-- +-- local dec = Ape.open(Bytes.reader(buf)) -- Types.Decoder + bitsPerSample, level, version, float, md5 +-- local i32, n = dec:readInt(4096) -- integer files: the samples as `mac -d` writes them +-- local audio = Ape.decode(Bytes.reader(buf)) -- Types.Audio + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/audio/Pcm") +local Stream = require("@formats/codecs/audio/Stream") +local ApeTag = require("@formats/codecs/audio/ApeTag") +local ApeCodec = require("@formats/codecs/audio/Ape") + +-- ------------------------------------------------------------------------------------------------ contract +local Ape = { + name = "ape", + category = "audio", + extensions = { "ape" }, + mime = { "audio/ape", "audio/x-ape", "audio/x-monkeys-audio" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Ape" }, + caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, float = true, depths = { 8, 16, 24, 32 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type OpenOptions = { + maxFrames: number?, -- decode(): refuse longer streams (default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ constants +local LEVELS = { [1000] = "fast", [2000] = "normal", [3000] = "high", [4000] = "extra high", [5000] = "insane" } + +-- ------------------------------------------------------------------------------------------------ sniff +function Ape.sniff(r: Bytes.Reader): number + local head = r:peek(4) + if head == "MAC " or head == "MACF" then -- MACF: float samples + return 1 + end + if string.sub(head, 1, 3) == "ID3" then + local sz = 0 + for i = 6, 9 do + local v = r:peekU8(i) + if v < 0 then + return 0 + end + sz = sz * 128 + bit32.band(v, 127) + end + local footer = bit32.band(math.max(r:peekU8(5), 0), 0x10) ~= 0 + local id = r:peek(4, 10 + sz + (if footer then 10 else 0)) + return if id == "MAC " or id == "MACF" then 1 else 0 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(r, opts?) -> Types.Audio | nil, Err: the whole stream +function Ape.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) + local dec, err = Ape.open(r, opts) + if not dec then + return nil, err + end + local d = dec :: any + local limit = opts and opts.maxFrames or 2 ^ 28 + if d.frames > limit or d.frames * d.channels > 2 ^ 28 then + return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", d.frames)) + end + return Pcm.drain(d, d.source, limit) +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> Decoder | nil, Err +function Ape.open(r: Bytes.Reader, opts: OpenOptions?): (Types.Decoder?, Err.Err?) + if type(r) == "buffer" then + r = Bytes.reader(r :: any) + end + if type(r) ~= "table" or type(r.buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "open: expected a Reader") + end + local buf, base, limit = r.buf, r.base, r.limit + local tags, tagInfo = ApeTag.find(buf, base, limit) + local stop = if tagInfo then tagInfo.start else limit + local info, err = ApeCodec.info(buf, base, stop) + if not info then + return nil, err + end + if info.channels * info.blocksPerFrame > 2 ^ 24 then + return nil, Err.new(Err.LIMIT, "frames of " .. info.blocksPerFrame .. " blocks") + end + local codec, cerr = ApeCodec.decoder(info) + if not codec then + return nil, cerr + end + local frames = info.totalBlocks + local bpf = info.blocksPerFrame + local dec: any = { + sampleRate = info.sampleRate, + channels = info.channels, + frames = frames, + duration = frames / info.sampleRate, + bitrate = if frames > 0 then math.floor((stop - base) * 8 * info.sampleRate / frames) else 0, + tags = tags or {}, + bitsPerSample = info.bitsPerSample, + float = info.float, + level = LEVELS[info.level] or tostring(info.level), + version = info.version, + md5 = info.md5, + source = { format = "ape", bitDepth = info.bitsPerSample, float = info.float, level = info.level, version = info.version, programVersion = info.programVersion, tags = tagInfo and tagInfo.items }, + } + local count = info.totalFrames + return Stream.packets(dec, { + count = count, + start = function(i: number): number + return if i > count then frames else (i - 1) * bpf + end, + decode = function(i: number): (number?, Err.Err?) + return codec:frame(buf, i) + end, + pcm = function(): { number } + return codec.pcm + end, + reset = function() end, + stop = frames, + scale = if info.float then 1 else 1 / 2 ^ (info.bitsPerSample - 1), + ints = not info.float, + }) +end + +return Ape diff --git a/src/Formats/audio/brstm/init.luau b/src/Formats/audio/brstm/init.luau new file mode 100644 index 0000000..1e9ddeb --- /dev/null +++ b/src/Formats/audio/brstm/init.luau @@ -0,0 +1,298 @@ +--!strict +-- audio/brstm: Nintendo's streamed audio: BRSTM (Wii, "RSTM", big-endian), BCSTM (3DS, "CSTM", little-endian) and +-- BFSTM (Wii U big-endian / Switch little-endian, "FSTM"), over codecs/audio/Adpcm. New in formats-luau; the layouts +-- follow vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt), whose output it matches bit for bit. Supports: DSP +-- ADPCM (with the header's initial history; seeks into blocks not yet played use the ADPC / SEEK history table), PCM16 +-- and PCM8, 1-255 channels in block-interleaved layout, the loop start (dec.loop and meta.source.loop = { start, stop } +-- in frames, stop exclusive). Read only. Not supported: BCSTM IMA ADPCM, BRSTM version 0.1 (beta), BFSTM regions +-- (the whole stream plays), the track table (channels are not grouped). +-- +-- local dec = Brstm.open(Bytes.reader(buf)) -- Types.Decoder (+ loop, container, codec) + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/audio/Pcm") +local Decoder = require("@formats/codecs/audio/Adpcm/Decoder") + +-- ------------------------------------------------------------------------------------------------ contract +local Brstm = { + name = "brstm", + category = "audio", + extensions = { "brstm", "bcstm", "bfstm" }, + mime = { "audio/x-brstm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm/Decoder" }, + caps = { decode = true, encode = false, streaming = true, lossy = true, loops = true, containers = { "RSTM", "CSTM", "FSTM" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + maxFrames: number?, -- decode(): Err.LIMIT past this (default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ constants +local CODECS = { [0] = "pcm8", [1] = "pcm16", [2] = "dsp", [3] = "ima" } + +-- ------------------------------------------------------------------------------------------------ sniff +function Brstm.sniff(r: Bytes.Reader): number + local m = r:peek(4) + if m ~= "RSTM" and m ~= "CSTM" and m ~= "FSTM" then + return 0 + end + local bom = r:peek(2, 4) + return if bom == "\254\255" or bom == "\255\254" then 1 else 0 +end + +-- variant(r) -> "brstm" / "bcstm" / "bfstm": the flavour, for F.detect +function Brstm.variant(r: Bytes.Reader): string? + local m = r:peek(4) + return if m == "RSTM" then "brstm" elseif m == "CSTM" then "bcstm" elseif m == "FSTM" then "bfstm" else nil +end + +-- ------------------------------------------------------------------------------------------------ decode +function Brstm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = Brstm.open(r) + if not dec then + return nil, err + end + local d = dec :: any + local limit = opts and opts.maxFrames or 2 ^ 28 + if d.frames > limit or d.frames * d.channels > 2 ^ 28 then + return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", d.frames)) + end + return Pcm.drain(d, { format = "brstm", container = d.container, codec = d.codec, loop = d.loop }, limit) +end + +-- ------------------------------------------------------------------------------------------------ open +-- a reader of the whole file in its byte order: u8 / u16 / u32 / i16 / i32 at absolute offsets (relative to the file +-- start); a read out of range records the error in .err and returns 0 +local function view(r: Bytes.Reader, be: boolean) + local v = { err = nil :: string? } + local size = r.limit - r.base + local function at(o: number, n: number): Bytes.Reader? + if o < 0 or o + n > size then + v.err = "an offset points past the end" + return nil + end + return r:sub(o, n) + end + function v.u8(o: number): number + local s = at(o, 1) + return if s then s:u8() else 0 + end + function v.u16(o: number): number + local s = at(o, 2) + return if s then (if be then s:u16be() else s:u16le()) else 0 + end + function v.i16(o: number): number + local s = at(o, 2) + return if s then (if be then s:i16be() else s:i16le()) else 0 + end + function v.u32(o: number): number + local s = at(o, 4) + return if s then (if be then s:u32be() else s:u32le()) else 0 + end + function v.i32(o: number): number + local s = at(o, 4) + return if s then (if be then s:i32be() else s:i32le()) else 0 + end + return v +end + +type Layout = { + codec: number, + loop: boolean, + ch: number, + rate: number, + loopStart: number, + frames: number, + blockSize: number, + lastPadded: number, + data: number, -- the first block (absolute in the file) + adp: { number }, -- each channel's DSP info offset (coefficients, then gain, ps, yn1, yn2) + hist: number?, -- the per-block history table: (yn1, yn2) per channel per block + histEntries: number, +} + +local function parseRstm(v: any): (Layout?, string?) + if v.u16(0x06) ~= 0x0100 then + return nil, string.format("unsupported: BRSTM version %d.%d", v.u8(0x06), v.u8(0x07)) + end + local head = v.u32(0x10) + local adpc = v.u32(0x18) + if v.u32(head) ~= 0x48454144 then -- "HEAD", read big-endian + return nil, "no HEAD chunk" + end + local base = head + 8 + local info = base + v.u32(base + 4) + local chans = base + v.u32(base + 20) + local ch = v.u8(info + 2) + local L: Layout = { + codec = v.u8(info), + loop = v.u8(info + 1) ~= 0, + ch = ch, + rate = v.u16(info + 4), + loopStart = v.u32(info + 8), + frames = v.u32(info + 12), + data = v.u32(info + 16), + blockSize = v.u32(info + 24), + lastPadded = v.u32(info + 40), + adp = {}, + hist = nil, + histEntries = 0, + } + for c = 0, ch - 1 do + local ci = base + v.u32(chans + 4 + c * 8 + 4) + L.adp[c + 1] = base + v.u32(ci + 4) + end + if adpc > 0 and v.u32(adpc) == 0x41445043 then -- "ADPC" + L.hist = adpc + 8 + L.histEntries = (v.u32(adpc + 4) - 8) // math.max(1, 4 * ch) + end + return L, nil +end + +local function parseFstm(v: any): (Layout?, string?) + local info: number, seek: number, data: number = 0, 0, 0 + local seekSize: number = 0 + for i = 0, math.min(v.u16(0x10), 16) - 1 do + local id, off = v.u16(0x14 + i * 12), v.u32(0x14 + i * 12 + 4) + if id == 0x4000 then + info = off + elseif id == 0x4001 then + seek = off + seekSize = v.u32(0x14 + i * 12 + 8) :: number + elseif id == 0x4002 then + data = off + end + end + if info == 0 or data == 0 then + return nil, "no INFO or DATA block" + end + local stream = info + 8 + v.i32(info + 0x0C) + local chans = info + 8 + v.i32(info + 0x1C) + local ch = v.u8(stream + 2) + local dataRef = stream + 0x30 + local L: Layout = { + codec = v.u8(stream), + loop = v.u8(stream + 1) ~= 0, + ch = ch, + rate = v.u32(stream + 4), + loopStart = v.u32(stream + 8), + frames = v.u32(stream + 12), + blockSize = v.u32(stream + 20), + lastPadded = v.u32(stream + 36), + data = if v.u16(dataRef) == 0x1F00 then data + 8 + v.i32(dataRef + 4) else data + 0x20, + adp = {}, + hist = nil, + histEntries = 0, + } + for c = 0, ch - 1 do + local ci = chans + v.i32(chans + 4 + c * 8 + 4) + L.adp[c + 1] = ci + v.i32(ci + 4) + end + if seek > 0 and seekSize > 8 then + L.hist = seek + 8 + L.histEntries = (seekSize - 8) // math.max(1, 4 * ch) + end + return L, nil +end + +function Brstm.open(r: Bytes.Reader, _opts: any?): (Types.Decoder?, Err.Err?) + if type(r) ~= "table" or type(r.buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "open: expected a Reader") + end + if r.limit - r.base < 0x40 then + return nil, Err.new(Err.TRUNCATED, "the header runs past the end") + end + if Brstm.sniff(r) == 0 then + return nil, Err.new(Err.CORRUPT, "not a BRSTM / BCSTM / BFSTM file") + end + local magic = r:peek(4) + local be = r:peek(2, 4) == "\254\255" + local v = view(r, be) + local parsed: Layout?, msg: string? + if magic == "RSTM" then + if not be then + return nil, Err.new(Err.CORRUPT, "a little-endian BRSTM") + end + parsed, msg = parseRstm(v) + else + parsed, msg = parseFstm(v) + end + if v.err then + return nil, Err.new(Err.TRUNCATED, v.err) + elseif not parsed then + return nil, Err.from(msg) + end + local L = parsed :: Layout + local codec = CODECS[L.codec] + if not codec then + return nil, Err.new(Err.CORRUPT, "codec " .. L.codec) + elseif codec == "ima" then + return nil, Err.new(Err.UNSUPPORTED, "IMA ADPCM streams") + end + local ch = L.ch + if ch < 1 or L.rate < 1 then + return nil, Err.new(Err.CORRUPT, "bad channel count or sample rate") + end + local size = r.limit - r.base - L.data + if L.data < 0 or size < 0 then + return nil, Err.new(Err.TRUNCATED, "the data starts past the end") + end + local kind = if codec == "dsp" then "dsp" elseif codec == "pcm8" then "s8" elseif be then "s16be" else "s16le" + local coefs: buffer? = nil + local hist: { number }? = nil + if codec == "dsp" then + coefs = buffer.create(64 * ch) + hist = {} + for c = 0, ch - 1 do + local adp = L.adp[c + 1] + for k = 0, 15 do + buffer.writei32(coefs :: buffer, c * 64 + k * 4, v.i16(adp + k * 2)) + end + hist[c * 2 + 1], hist[c * 2 + 2] = v.i16(adp + 36), v.i16(adp + 38) + end + if v.err then + return nil, Err.new(Err.TRUNCATED, v.err) + end + end + local histAt, entries = L.hist, L.histEntries + local loop = if L.loop and L.loopStart < L.frames then { start = L.loopStart, stop = L.frames } else nil + local dec: any = { sampleRate = L.rate, channels = ch, tags = {}, container = magic, codec = codec, loop = loop } + local block = L.blockSize + if block < 1 or (kind == "dsp" and block % 8 ~= 0) or (kind ~= "s8" and block % 2 ~= 0) then + return nil, Err.new(Err.CORRUPT, "bad block size " .. block) + end + local d, err = Decoder.interleaved(dec, { + kind = kind :: any, + buf = r.buf, + offset = r.base + L.data, + size = size, + interleave = block, + lastInterleave = if L.lastPadded > 0 and L.lastPadded <= block then L.lastPadded else block, + frames = L.frames, + coefs = coefs, + hist = hist, + restore = if codec == "dsp" and histAt + then function(row: number, st: buffer): boolean + if row >= entries then + return false + end + for c = 0, ch - 1 do + local p = (histAt :: number) + (row * ch + c) * 4 + buffer.writei32(st, c * 8, v.i16(p)) + buffer.writei32(st, c * 8 + 4, v.i16(p + 2)) + end + return v.err == nil + end + else nil, + }) + if d then + d.bitrate = if d.duration > 0 then math.floor(size * 8 / d.duration) else 0 + end + return d, err +end + +return Brstm diff --git a/src/Formats/audio/caf/init.luau b/src/Formats/audio/caf/init.luau index fd46e96..cb6f2df 100644 --- a/src/Formats/audio/caf/init.luau +++ b/src/Formats/audio/caf/init.luau @@ -3,7 +3,8 @@ -- PCM (8 / 16 / 24 / 32-bit integer, 32 / 64-bit float, big / little endian), ALAC (codecs/audio/Alac), AAC-LC (codecs/audio/Aac, -- kuki esds), mu-law and A-law; the packet table (pakt) with priming / remainder trimming, a data chunk of unknown -- size (-1), info chunk tags; seeking. Writing linear PCM (16 / 24-bit big endian, 32-bit float) and ALAC (16 / 20 / --- 24-bit) with info tags. Not supported: IMA4, other compressed formats (UNSUPPORTED). +-- 24-bit) with info tags. IMA4 (Apple IMA ADPCM, codecs/audio/Adpcm) decodes too, with exact seeking. Not supported: +-- other compressed formats (UNSUPPORTED). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") @@ -14,6 +15,7 @@ local Pcm = require("@formats/codecs/audio/Pcm") local Stream = require("@formats/codecs/audio/Stream") local Aac = require("@formats/codecs/audio/Aac") local Alac = require("@formats/codecs/audio/Alac") +local Adpcm = require("@formats/codecs/audio/Adpcm/Decoder") -- ------------------------------------------------------------------------------------------------ contract local Caf = { @@ -21,7 +23,7 @@ local Caf = { category = "audio", extensions = { "caf", "caff" }, mime = { "audio/x-caf" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Aac", "codecs/audio/Alac", "codecs/audio/Pcm", "codecs/audio/Stream", "containers/Chunks" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Aac", "codecs/audio/Adpcm/Decoder", "codecs/audio/Alac", "codecs/audio/Pcm", "codecs/audio/Stream", "containers/Chunks" }, caps = { decode = true, encode = true, codecs = { "pcm", "alac", "aac", "ulaw", "alaw" }, encodeCodecs = { "pcm", "alac" }, tags = true, streaming = true }, } @@ -333,7 +335,7 @@ local function source(r: Bytes.Reader, p: Parsed): (Source?, Err.Err?) end -- packetised codecs local sizes = p.packets - if not sizes then + if not sizes or (#sizes == 0 and d.bytesPerPacket > 0) then -- constant packets: pakt may list none if d.bytesPerPacket > 0 then local n = (p.dataEnd - p.dataStart) // d.bytesPerPacket sizes = table.create(n, d.bytesPerPacket) @@ -425,7 +427,23 @@ function Caf.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.E if not p then return nil, err end - local s, serr = source(r, p :: Parsed) + local pp = p :: Parsed + if pp.desc.format == "ima4" then + -- Apple IMA ADPCM: 34-byte packets per channel, 64 frames; the predictor carries across packets + local ch = pp.desc.channels + local packets = (pp.dataEnd - pp.dataStart) // (34 * ch) + local frames = packets * 64 + if pp.validFrames and pp.validFrames >= 0 then + frames = math.min(frames, pp.validFrames) + end + local dec: any = { sampleRate = pp.desc.rate, channels = ch, tags = pp.tags, codec = "ima4", bitsPerSample = 16 } + local d, derr = Adpcm.blocks(dec, { kind = "ima_qt", buf = r.buf, offset = pp.dataStart, size = pp.dataEnd - pp.dataStart, frames = frames }) + if d then + d.bitrate = math.floor(pp.desc.rate * 34 * 8 * ch / 64) + end + return d, derr + end + local s, serr = source(r, pp) if not s then return nil, serr end diff --git a/src/Formats/audio/mpc/init.luau b/src/Formats/audio/mpc/init.luau new file mode 100644 index 0000000..a75a254 --- /dev/null +++ b/src/Formats/audio/mpc/init.luau @@ -0,0 +1,96 @@ +--!strict +-- audio/mpc: Musepack (.mpc / .mp+ / .mpp), stream versions 7 and 8, through codecs/audio/Musepack (a libmpcdec +-- port). Supports: SV7 (mppenc 1.x) and SV8 (mpcenc 1.30) streams, mono / stereo, every rate (32 / 37.8 / 44.1 / +-- 48 kHz), gapless length (the synthesis delay, SV8 leading silence and the last frame's length are honoured), seeking +-- (SV8: by audio packet, exact; SV7: by frame with 32 frames of pre-roll, as libmpcdec), APEv2 tags +-- (codecs/audio/ApeTag), a leading ID3v2 tag (skipped), ReplayGain values in meta (not applied). Not supported: +-- writing, SV4 - SV6 (UNSUPPORTED), chapters. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/audio/Pcm") +local Stream = require("@formats/codecs/audio/Stream") +local ApeTag = require("@formats/codecs/audio/ApeTag") +local Musepack = require("@formats/codecs/audio/Musepack") + +-- ------------------------------------------------------------------------------------------------ contract +local Mpc = { + name = "mpc", + category = "audio", + extensions = { "mpc", "mp+", "mpp" }, + mime = { "audio/x-musepack", "audio/musepack" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Musepack" }, + caps = { decode = true, encode = false, codecs = { "musepack" }, versions = { 7, 8 }, streaming = true, lossy = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + maxFrames: number?, -- Err.LIMIT past this many output sample frames (default 2^31) +} + +-- ------------------------------------------------------------------------------------------------ constants +-- the size of an ID3v2 tag at p (0 if none) +local function id3v2(b: buffer, p: number, limit: number): number + if p + 10 > limit or buffer.readstring(b, p, 3) ~= "ID3" then + return 0 + end + local n = 10 + for i = 6, 9 do + n += bit32.band(buffer.readu8(b, p + i), 127) * 128 ^ (9 - i) + end + return n + (if bit32.band(buffer.readu8(b, p + 5), 0x10) ~= 0 then 10 else 0) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Mpc.sniff(r: Bytes.Reader): number + local b, p, limit = r.buf, r.pos, r.limit + p += id3v2(b, p, limit) + local v = Musepack.magic(b, p, limit) + if v == 8 then + return 1 + end + return if v == 7 then 0.9 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Mpc.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) + local o: DecodeOptions = opts or {} + local b, base, limit = r.buf, r.base, r.limit + local start = base + id3v2(b, base, limit) + local tags, info = ApeTag.find(b, start, limit) + local stop = if info and info.start > start then info.start else limit + local s, err = Musepack.open(b, start, stop) + if not s then + return nil, err + end + if s.frames > (o.maxFrames or 2 ^ 31) then + return nil, Err.new(Err.LIMIT, "more than " .. (o.maxFrames or 2 ^ 31) .. " frames") + end + local duration = s.frames / s.sampleRate + local dec = { + sampleRate = s.sampleRate, + channels = s.channels, + frames = s.frames, + duration = duration, + bitrate = if duration > 0 then math.floor(s.bytes * 8 / duration + 0.5) else 0, + tags = tags or {}, + codec = "musepack", + version = s.version, + profile = s.profile, + gain = s.gain, + } + return Stream.packets(dec, s :: any) +end + +function Mpc.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = Mpc.open(r, opts) + if not dec then + return nil, err + end + local d: any = dec + return Pcm.drain(d, { format = "mpc", codec = "musepack", version = d.version, profile = d.profile, gain = d.gain, bitrate = d.bitrate }) +end + +return Mpc diff --git a/src/Formats/audio/qoa/init.luau b/src/Formats/audio/qoa/init.luau new file mode 100644 index 0000000..764c357 --- /dev/null +++ b/src/Formats/audio/qoa/init.luau @@ -0,0 +1,185 @@ +--!strict +-- audio/qoa: QOA, "Quite OK Audio" (.qoa), over codecs/audio/Qoa (a port of qoa.h, phoboslab, MIT). New in +-- formats-luau. Decode / open: static files and streaming files (total 0 in the header), 1-255 channels (WAVE order +-- for 1-8, as the spec lays them out), any rate up to 16777215 Hz, frame-accurate seeking (every frame carries its +-- own predictor state), a truncated file decodes its whole frames. Encode (Audio or Decoder, streamed frame by frame): +-- byte-for-byte what qoa.h's qoa_encode writes, 1-8 channels (qoa.h's limit). Not supported: frames whose channel +-- count or rate change mid-stream (Err.UNSUPPORTED). +-- +-- local dec = Qoa.open(Bytes.reader(buf)) -- Types.Decoder +-- local file = Qoa.encode(audio) + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/audio/Pcm") +local Stream = require("@formats/codecs/audio/Stream") +local Codec = require("@formats/codecs/audio/Qoa") + +-- ------------------------------------------------------------------------------------------------ contract +local Qoa = { + name = "qoa", + category = "audio", + extensions = { "qoa" }, + mime = { "audio/qoa" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/Qoa" }, + caps = { decode = true, encode = true, streaming = true, lossy = true, seek = true, channels = 8 }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + maxFrames: number?, -- decode(): Err.LIMIT past this many sample frames (default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Qoa.sniff(r: Bytes.Reader): number + return if r:peek(4) == "qoaf" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Qoa.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = Qoa.open(r) + if not dec then + return nil, err + end + local d = dec :: any + local limit = opts and opts.maxFrames or 2 ^ 28 + if d.frames > limit or d.frames * d.channels > 2 ^ 28 then + return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", d.frames)) + end + return Pcm.drain(d, { format = "qoa", streaming = d.streaming }, limit) +end + +-- ------------------------------------------------------------------------------------------------ encode +function Qoa.encode(value: any, _opts: any?): (buffer?, Err.Err?) + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local ch, rate = src.channels, src.sampleRate + if ch > 8 then + return nil, Err.new(Err.ARG, "QOA (qoa.h) holds at most 8 channels") + end + if rate ~= math.floor(rate) or rate < 1 or rate > 0xFFFFFF then + return nil, Err.new(Err.ARG, "the sample rate must be an integer in 1 .. 16777215") + end + local FL = Codec.FRAME_LEN + local w = Bytes.writer(8 + (if src.frames > 0 then Codec.frameSize(ch, (src.frames + 19) // 20) + 24 * ch * (src.frames // FL + 1) else 65536)) + w:string("qoaf") + w:u32be(0) + local lms = Codec.newLms(ch) + local fb = buffer.create(FL * ch * 4) + local tmp: buffer? = nil + local total = 0 + while true do + -- one frame: 5120 sample frames (the last may be shorter), as qoa.h cuts them + local have = 0 + while have < FL do + local b, n = src:read(FL - have, tmp) + if n <= 0 then + break + end + tmp = b + buffer.copy(fb, have * ch * 4, b, 0, n * ch * 4) + have += n + end + if have == 0 then + break + end + local at = w:reserve(Codec.frameSize(ch, (have + 19) // 20)) + w.pos = at + Codec.encodeFrame(fb, 0, have, ch, rate, lms, w.buf, at) + total += have + if have < FL then + break + end + end + if src.err then + return nil, src.err + end + if total == 0 then + return nil, Err.new(Err.ARG, "QOA needs at least one sample") + end + if total >= 2 ^ 32 then + return nil, Err.new(Err.ARG, "too many samples for QOA") + end + local out = w:finish() + buffer.writeu32(out, 4, bit32.byteswap(total)) + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Qoa.open(r: Bytes.Reader, _opts: any?): (Types.Decoder?, Err.Err?) + if type(r) ~= "table" or type(r.buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "open: expected a Reader") + end + local h = r:sub(0) + if h:string(4) ~= "qoaf" then + return nil, Err.new(Err.CORRUPT, "not a QOA file") + end + local declared = h:u32be() + if h.err then + return nil, h.err + end + local buf = r.buf + -- the frame index: offsets, first frames + local offs, starts = {}, {} + local p, total = r.base + 8, 0 + local ch, rate = 0, 0 + while p < r.limit do + local info, msg = Codec.frameInfo(buf, p, r.limit - p) + if not info then + if #offs == 0 then + return nil, Err.from(msg, p - r.base) + end + break -- a cut or damaged tail: keep the whole frames + end + if #offs == 0 then + ch, rate = info.channels, info.rate + elseif info.channels ~= ch or info.rate ~= rate then + return nil, Err.new(Err.UNSUPPORTED, "the channel count or rate changes mid-stream", p - r.base) + end + table.insert(offs, p) + table.insert(starts, total) + total += info.samples + p += info.size + if declared > 0 and total >= declared then + break + end + end + if #offs == 0 then + return nil, Err.new(Err.TRUNCATED, "no frames") + end + local frames = if declared > 0 then math.min(declared, total) else total + local pcm = buffer.create(Codec.FRAME_LEN * ch * 4) + local dec: any = { + sampleRate = rate, + channels = ch, + frames = frames, + duration = frames / rate, + bitrate = math.floor((p - r.base) * 8 / math.max(frames / rate, 1e-9)), + tags = {}, + streaming = declared == 0, + } + local limit = r.limit + return Stream.packets(dec, { + count = #offs, + start = function(i: number): number + return if i > #offs then total else starts[i] + end, + decode = function(i: number): (number?, Err.Err?) + local n, msg = Codec.decodeFrame(buf, offs[i], limit - offs[i], pcm, 0) + if not n then + return nil, Err.from(msg, offs[i] - r.base) + end + return n, nil + end, + pcm = function(): buffer + return pcm + end, + reset = function() end, + stop = frames, + }) +end + +return Qoa diff --git a/src/Formats/audio/tta/init.luau b/src/Formats/audio/tta/init.luau new file mode 100644 index 0000000..63d197f --- /dev/null +++ b/src/Formats/audio/tta/init.luau @@ -0,0 +1,123 @@ +--!strict +-- audio/tta: True Audio (.tta, TTA1) files around codecs/audio/Tta: an optional ID3v2 tag in front (skipped), the +-- header and seek table, independent frames (sample-accurate seeking), APEv2 tags at the end (codecs/audio/ApeTag). +-- Written from the TTA1 format description; no libtta / ffmpeg code. Supports 8 / 16 / 24 bits, any channel count. +-- Not supported: password-protected files (Err.UNSUPPORTED), TTA2, ID3v2 tag contents, encoding. +-- +-- local dec = Tta.open(Bytes.reader(buf)) -- Types.Decoder + bitsPerSample, readInt +-- local audio = Tta.decode(Bytes.reader(buf)) -- Types.Audio + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/audio/Pcm") +local Stream = require("@formats/codecs/audio/Stream") +local ApeTag = require("@formats/codecs/audio/ApeTag") +local TtaCodec = require("@formats/codecs/audio/Tta") + +-- ------------------------------------------------------------------------------------------------ contract +local Tta = { + name = "tta", + category = "audio", + extensions = { "tta" }, + mime = { "audio/x-tta", "audio/tta" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Tta" }, + caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, depths = { 8, 16, 24 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type OpenOptions = { + maxFrames: number?, -- decode(): refuse longer streams (default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ sniff +-- the size of an ID3v2 tag at the reader's start (0 when none) +local function id3Size(r: Bytes.Reader): number + if r:peek(3) ~= "ID3" then + return 0 + end + local sz = 0 + for i = 6, 9 do + local v = r:peekU8(i) + if v < 0 then + return 0 + end + sz = sz * 128 + bit32.band(v, 127) + end + local footer = bit32.band(math.max(r:peekU8(5), 0), 0x10) ~= 0 + return 10 + sz + (if footer then 10 else 0) +end + +function Tta.sniff(r: Bytes.Reader): number + return if r:peek(4, id3Size(r)) == "TTA1" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(r, opts?) -> Types.Audio | nil, Err: the whole stream +function Tta.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) + local dec, err = Tta.open(r, opts) + if not dec then + return nil, err + end + local d = dec :: any + local limit = opts and opts.maxFrames or 2 ^ 28 + if d.frames > limit or d.frames * d.channels > 2 ^ 28 then + return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", d.frames)) + end + return Pcm.drain(d, d.source, limit) +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> Decoder | nil, Err +function Tta.open(r: Bytes.Reader, opts: OpenOptions?): (Types.Decoder?, Err.Err?) + if type(r) == "buffer" then + r = Bytes.reader(r :: any) + end + if type(r) ~= "table" or type(r.buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "open: expected a Reader") + end + local buf, base, limit = r.buf, r.base, r.limit + local at = base + id3Size(r) + local tags, tagInfo = ApeTag.find(buf, at, limit) + local stop = if tagInfo then tagInfo.start else limit + local info, err = TtaCodec.info(buf, at, stop) + if not info then + return nil, err + end + if info.channels * info.frameLength > 2 ^ 24 then + return nil, Err.new(Err.LIMIT, info.channels .. " channels of " .. info.frameLength .. "-sample frames") + end + local codec = TtaCodec.decoder(info, stop) + local frames = info.samples + local dec: any = { + sampleRate = info.sampleRate, + channels = info.channels, + frames = frames, + duration = frames / info.sampleRate, + bitrate = if frames > 0 then math.floor((stop - base) * 8 * info.sampleRate / frames) else 0, + tags = tags or {}, + bitsPerSample = info.bitsPerSample, + float = false, + source = { format = "tta", bitDepth = info.bitsPerSample, tags = tagInfo and tagInfo.items }, + } + local fl, count = info.frameLength, info.frames + return Stream.packets(dec, { + count = count, + start = function(i: number): number + return if i > count then frames else (i - 1) * fl + end, + decode = function(i: number): (number?, Err.Err?) + return codec:frame(buf, i) + end, + pcm = function(): { number } + return codec.pcm + end, + reset = function() end, + stop = frames, + scale = 1 / 2 ^ (info.bitsPerSample - 1), + ints = true, + }) +end + +return Tta diff --git a/src/Formats/audio/vag/init.luau b/src/Formats/audio/vag/init.luau new file mode 100644 index 0000000..86c0e37 --- /dev/null +++ b/src/Formats/audio/vag/init.luau @@ -0,0 +1,231 @@ +--!strict +-- audio/vag: Sony VAG (PlayStation SPU PS-ADPCM, .vag), and Simon & Schuster / Hyperscan KVAG (IMA ADPCM, the same +-- extension), over codecs/audio/Adpcm. New in formats-luau; the header variants and the PS-ADPCM decoding follow +-- vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt), whose output it matches bit for bit. Supports: "VAGp" mono +-- (versions 0, 2, 3, 4, 6, 0x20; the name field as tags.title; loop points from the frame flags, as dec.loop and +-- meta.source.loop = { start, stop } in frames, stop exclusive), "VAGi" stereo (interleaved blocks), "KVAG" mono / +-- stereo IMA. The output starts with the blank frame Sony's tools put first (28 silent samples), as vgmstream plays it. +-- Encode (Audio or Decoder): mono to VAGp, stereo to VAGi (2048-byte interleave), loop points from opts.loop (frame +-- aligned: 28 samples). Not supported: HEVAG (VAGp versions 0x00020001 / 0x00030000, Vita / PS4), the many game +-- specific variants vgmstream knows (pGAV, VAG1 / VAG2, Jak, ...). +-- +-- local dec = Vag.open(Bytes.reader(buf)) -- Types.Decoder (+ loop, variant) +-- local file = Vag.encode(audio, { loop = { start = 0, stop = audio.frames } }) + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/audio/Pcm") +local Adpcm = require("@formats/codecs/audio/Adpcm") +local Decoder = require("@formats/codecs/audio/Adpcm/Decoder") + +-- ------------------------------------------------------------------------------------------------ contract +local Vag = { + name = "vag", + category = "audio", + extensions = { "vag" }, + mime = { "audio/x-vag" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" }, + caps = { decode = true, encode = true, streaming = true, lossy = true, loops = true, channels = 2 }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type Loop = { start: number, stop: number } +export type DecodeOptions = { + maxFrames: number?, -- decode(): Err.LIMIT past this (default 2^28) +} +export type EncodeOptions = { + loop: Loop?, -- loop points in frames of the input (stop exclusive), rounded out to 28-sample frames; default: the + -- source's meta.source.loop, else none + name: string?, -- the 16-byte name field (default: tags.title) + interleave: number?, -- stereo: bytes per channel block (default 2048, a multiple of 16) +} + +-- ------------------------------------------------------------------------------------------------ constants +local HEVAG = { [0x00020001] = true, [0x00030000] = true } + +-- ------------------------------------------------------------------------------------------------ sniff +function Vag.sniff(r: Bytes.Reader): number + local m = r:peek(4) + return if m == "VAGp" or m == "VAGi" or m == "KVAG" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Vag.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = Vag.open(r) + if not dec then + return nil, err + end + local d = dec :: any + local limit = opts and opts.maxFrames or 2 ^ 28 + if d.frames > limit or d.frames * d.channels > 2 ^ 28 then + return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", d.frames)) + end + return Pcm.drain(d, { format = "vag", variant = d.variant, codec = d.codec, loop = d.loop }, limit) +end + +-- ------------------------------------------------------------------------------------------------ encode +function Vag.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local ch, rate = src.channels, src.sampleRate + if ch > 2 then + return nil, Err.new(Err.ARG, "VAG holds mono or stereo") + end + if rate ~= math.floor(rate) or rate < 1 or rate >= 2 ^ 32 then + return nil, Err.new(Err.ARG, "the sample rate must be a positive integer") + end + local il = o.interleave or 2048 + if type(il) ~= "number" or il < 16 or il % 16 ~= 0 then + return nil, Err.new(Err.ARG, "interleave must be a multiple of 16") + end + local loop = o.loop + local v = value :: any + if loop == nil and type(v.meta) == "table" and type(v.meta.source) == "table" and type(v.meta.source.loop) == "table" then + loop = v.meta.source.loop + end + local a, cerr = Pcm.collect(src) + if not a then + return nil, cerr + end + local n = a.frames + local nf = (n + 27) // 28 -- data frames (after the blank one) + local ls, le = -1, -1 + if loop then + if type(loop.start) ~= "number" or type(loop.stop) ~= "number" or loop.start < 0 or loop.stop > n then + return nil, Err.new(Err.ARG, "loop must be { start, stop } inside the audio") + end + ls, le = loop.start // 28, (loop.stop + 27) // 28 - 1 + if le <= ls then + return nil, Err.new(Err.ARG, "the loop must span two 28-sample frames") + end + end + local chBytes = (nf + 1) * 16 + local stride = if ch == 1 then chBytes else (chBytes + il - 1) // il * il + local start = if ch == 1 then 0x30 else 0x800 + local out = buffer.create(start + stride * ch) + local title = o.name or (a.tags and a.tags.title) or "" + buffer.writestring(out, 0, if ch == 1 then "VAGp" else "VAGi") + buffer.writeu32(out, 4, bit32.byteswap(0x20)) + if ch == 2 then + buffer.writeu32(out, 8, il) + end + buffer.writeu32(out, 0x0C, bit32.byteswap(if ch == 1 then chBytes else stride)) + buffer.writeu32(out, 0x10, bit32.byteswap(rate)) + buffer.writestring(out, 0x20, string.sub(title, 1, 16)) + local st = buffer.create(8 * ch) + local plane = buffer.create(chBytes) + for c = 0, ch - 1 do + buffer.fill(plane, 0, 0) + Adpcm.psxEncode(a.samples, c, ch, n, st, c * 8, plane, 16, 16) + for k = 0, nf - 1 do + local flag = if k == ls then 6 elseif k == le then 3 elseif k > ls and k < le then 2 else 0 + if not loop and k == nf - 1 then + flag = 1 + end + buffer.writeu8(plane, 16 + k * 16 + 1, flag) + end + if ch == 1 then + buffer.copy(out, start, plane, 0, chBytes) + else + for b = 0, stride // il - 1 do + local take = math.clamp(chBytes - b * il, 0, il) + if take > 0 then + buffer.copy(out, start + (b * ch + c) * il, plane, b * il, take) + end + end + end + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- the loop from the PS-ADPCM frame flags of channel 0 (vgmstream's reading: the first start flag 6, the first end +-- flag 3), or nil +local function findLoop(buf: buffer, p: number, frames: number, il: number, ch: number): Loop? + local ls, le = -1, -1 + for k = 0, frames - 1 do + local off = p + (k * 16) // il * il * ch + (k * 16) % il + local flag = bit32.band(buffer.readu8(buf, off + 1), 15) + if flag == 6 and ls < 0 then + ls = k * 28 + elseif flag == 3 and le < 0 then + le = k * 28 + 28 + if ls >= 0 then + break + end + end + end + return if ls >= 0 and le > ls then { start = ls, stop = le } else nil +end + +function Vag.open(r: Bytes.Reader, _opts: any?): (Types.Decoder?, Err.Err?) + if type(r) ~= "table" or type(r.buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "open: expected a Reader") + end + local h = r:sub(0) + local magic = h:string(4) + local total = r.limit - r.base + if magic == "KVAG" then + local size, rate, stereo = h:u32le(), h:u32le(), h:u16le() + if h.err then + return nil, h.err + end + if rate < 1 or stereo > 1 then + return nil, Err.new(Err.CORRUPT, "bad KVAG header") + end + local dec: any = { sampleRate = rate, channels = stereo + 1, tags = {}, variant = "KVAG", codec = "ima" } + local d, err = Decoder.nibbles(dec, { buf = r.buf, offset = r.base + 14, size = math.min(size, total - 14), hi = true }) + if d then + d.bitrate = rate * 4 * (stereo + 1) + end + return d, err + end + if magic ~= "VAGp" and magic ~= "VAGi" then + return nil, Err.new(Err.CORRUPT, "not a VAG file") + end + local version, il = h:u32be(), h:u32le() + local chSize, rate = h:u32be(), h:u32be() + local name = r:sub(0x20, 16):cstring(16) + if h.err then + return nil, h.err + end + if HEVAG[version] then + return nil, Err.new(Err.UNSUPPORTED, "HEVAG (Vita / PS4 VAG)") + end + if rate < 1 or rate >= 2 ^ 31 then + return nil, Err.new(Err.CORRUPT, "bad sample rate " .. rate) + end + local ch, start = 1, 0x30 + if magic == "VAGi" then + ch, start = 2, 0x800 + if il < 16 or il % 16 ~= 0 then + return nil, Err.new(Err.CORRUPT, "bad interleave " .. il) + end + else + il = 16 + end + if total < start then + return nil, Err.new(Err.TRUNCATED, "the header runs past the end") + end + local size = math.min(chSize * ch, total - start) + local p = r.base + start + local frames = math.min(chSize // 16, (size // (il * ch)) * (il // 16) + math.clamp(size % (il * ch) - (ch - 1) * il, 0, il) // 16) + local loop = if magic == "VAGp" then findLoop(r.buf, p, frames, il, ch) else nil -- vgmstream: VAGi never loops + local tags = {} + if name ~= "" then + tags.title = name + end + local dec: any = { sampleRate = rate, channels = ch, tags = tags, variant = magic, codec = "psx", loop = loop } + local d, err = Decoder.interleaved(dec, { kind = "psx", buf = r.buf, offset = p, size = size, interleave = il, frames = frames * 28 }) + if d then + d.bitrate = rate * 16 * 8 * ch // 28 + end + return d, err +end + +return Vag diff --git a/src/Formats/audio/wav/Codecs.luau b/src/Formats/audio/wav/Codecs.luau index 4094c07..5b219bc 100644 --- a/src/Formats/audio/wav/Codecs.luau +++ b/src/Formats/audio/wav/Codecs.luau @@ -1,7 +1,8 @@ --!strict --!native --!optimize 2 --- audio/wav/Codecs: sample conversion loops (native) into interleaved f32, and back (the encoder's quantizers). +-- audio/wav/Codecs: sample conversion loops (native) into interleaved f32, and back (the encoder's quantizers). The +-- ADPCM block decoders moved to codecs/audio/Adpcm. -- Absorbed from wav-luau fd9a909 (same author); the encoder loops are new. They never throw: audio/wav (init.luau) -- only calls them with ranges it has checked against the source length and the output size. local readu8, readi8, readu16, readi16, readu32, readi32 = @@ -102,160 +103,6 @@ function Codecs.law(src: buffer, off: number, dst: buffer, d: number, count: num end end -local IMA_STEP = buffer.create(89 * 4) -do - local steps = { - 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97, - 107, 118, 130, 143, 157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449, 494, 544, 598, 658, 724, - 796, 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327, 3660, 4026, - 4428, 4871, 5358, 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, 15289, 16818, 18500, - 20350, 22385, 24623, 27086, 29794, 32767, - } - for i, s in steps do - buffer.writei32(IMA_STEP, (i - 1) * 4, s) - end -end -local IMA_INDEX = buffer.create(16 * 4) -do - local t = { -1, -1, -1, -1, 2, 4, 6, 8, -1, -1, -1, -1, 2, 4, 6, 8 } - for i, v in t do - buffer.writei32(IMA_INDEX, (i - 1) * 4, v) - end -end - --- IMA ADPCM (Microsoft / WAV layout), one block at src[off] of blockAlign bytes with `avail` bytes present (a --- truncated last block decodes the whole 8-sample groups it has). Writes interleaved f32 to dst from frame 0 and --- returns the frame count. -function Codecs.imaBlock(src: buffer, off: number, avail: number, ch: number, spb: number, dst: buffer): number - if avail < 4 * ch then - return 0 - end - -- groups of 8 samples per channel (4 bytes each) after the per-channel headers - local groups = (avail - 4 * ch) // (4 * ch) - local frames = math.min(spb, 1 + groups * 8) - for c = 0, ch - 1 do - local pred = readi16(src, off + c * 4) - local index = readu8(src, off + c * 4 + 2) - if index > 88 then - index = 88 - end - writef32(dst, c * 4, pred / 32768) - local f = 1 - local g = 0 - while f < frames do - local p = off + 4 * ch + (g * ch + c) * 4 - for k = 0, 7 do - if f >= frames then - break - end - local b = readu8(src, p + rshift(k, 1)) - local nib = if band(k, 1) == 0 then band(b, 15) else rshift(b, 4) - local step = buffer.readi32(IMA_STEP, index * 4) - local diff = rshift(step, 3) - if band(nib, 1) ~= 0 then - diff += rshift(step, 2) - end - if band(nib, 2) ~= 0 then - diff += rshift(step, 1) - end - if band(nib, 4) ~= 0 then - diff += step - end - if band(nib, 8) ~= 0 then - pred -= diff - else - pred += diff - end - if pred > 32767 then - pred = 32767 - elseif pred < -32768 then - pred = -32768 - end - index += buffer.readi32(IMA_INDEX, nib * 4) - if index < 0 then - index = 0 - elseif index > 88 then - index = 88 - end - writef32(dst, (f * ch + c) * 4, pred / 32768) - f += 1 - end - g += 1 - end - end - return frames -end - -local MS_ADAPT = buffer.create(16 * 4) -do - local t = { 230, 230, 230, 230, 307, 409, 512, 614, 768, 614, 512, 409, 307, 230, 230, 230 } - for i, v in t do - buffer.writei32(MS_ADAPT, (i - 1) * 4, v) - end -end - --- MS ADPCM, one block. coefs: i32 pairs (coef1, coef2) x ncoef (256 = 1.0). state: 5 * ch i32 scratch. --- Returns the frame count (a truncated last block decodes the whole bytes it has). -function Codecs.msBlock(src: buffer, off: number, avail: number, ch: number, spb: number, dst: buffer, - coefs: buffer, ncoef: number, state: buffer): number - local hdr = 7 * ch - if avail < hdr or ncoef < 1 then - return 0 - end - local frames = math.min(spb, 2 + ((avail - hdr) * 2) // ch) - -- state per channel: c1, c2, idelta, s1, s2 (5 i32) - for c = 0, ch - 1 do - local pi = readu8(src, off + c) - if pi >= ncoef then - pi = ncoef - 1 - end - local idelta = readi16(src, off + ch + c * 2) - local s1 = readi16(src, off + 3 * ch + c * 2) - local s2 = readi16(src, off + 5 * ch + c * 2) - local so = c * 20 - buffer.writei32(state, so, buffer.readi32(coefs, pi * 8)) - buffer.writei32(state, so + 4, buffer.readi32(coefs, pi * 8 + 4)) - buffer.writei32(state, so + 8, idelta) - buffer.writei32(state, so + 12, s1) - buffer.writei32(state, so + 16, s2) - writef32(dst, c * 4, s2 / 32768) - if frames > 1 then - writef32(dst, (ch + c) * 4, s1 / 32768) - end - end - -- nibbles, high first, channels interleaved per nibble - local total = (frames - 2) * ch - for k = 0, total - 1 do - local b = readu8(src, off + hdr + rshift(k, 1)) - local nib = if band(k, 1) == 0 then rshift(b, 4) else band(b, 15) - local c = k % ch - local so = c * 20 - local c1, c2 = buffer.readi32(state, so), buffer.readi32(state, so + 4) - local idelta = buffer.readi32(state, so + 8) - local s1, s2 = buffer.readi32(state, so + 12), buffer.readi32(state, so + 16) - local p = s1 * c1 + s2 * c2 - p = if p >= 0 then p // 256 else -((-p) // 256) - local sn = if nib >= 8 then nib - 16 else nib - p += sn * idelta - if p > 32767 then - p = 32767 - elseif p < -32768 then - p = -32768 - end - idelta = (buffer.readi32(MS_ADAPT, nib * 4) * idelta) // 256 - if idelta < 16 then - idelta = 16 - elseif idelta > 2796202 then -- INT_MAX / 768, as ffmpeg - idelta = 2796202 - end - buffer.writei32(state, so + 8, idelta) - buffer.writei32(state, so + 12, p) - buffer.writei32(state, so + 16, s1) - writef32(dst, (2 * ch + k) * 4, p / 32768) - end - return frames -end - -- copy frames from a block cache into the output: count f32 values function Codecs.copy(src: buffer, sOff: number, dst: buffer, dOff: number, count: number) buffer.copy(dst, dOff * 4, src, sOff * 4, count * 4) diff --git a/src/Formats/audio/wav/init.luau b/src/Formats/audio/wav/init.luau index cf5e65c..ccf655a 100644 --- a/src/Formats/audio/wav/init.luau +++ b/src/Formats/audio/wav/init.luau @@ -21,6 +21,7 @@ local Types = require("@formats/Types") local Pcm = require("@formats/codecs/audio/Pcm") local Riff = require("@formats/containers/Riff") local Codecs = require("@formats/audio/wav/Codecs") +local Adpcm = require("@formats/codecs/audio/Adpcm") -- ------------------------------------------------------------------------------------------------ contract local Wav = { @@ -28,7 +29,7 @@ local Wav = { category = "audio", extensions = { "wav", "wave", "rf64", "bw64" }, mime = { "audio/wav", "audio/x-wav", "audio/wave", "audio/vnd.wave" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Riff", "codecs/audio/Pcm" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Riff", "codecs/audio/Pcm", "codecs/audio/Adpcm" }, caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, rf64 = true }, } @@ -488,8 +489,7 @@ function Wav.open(r: Bytes.Reader, _opts: OpenOptions?): (Decoder?, Err.Err?) spb = computed end -- coefficients from the fmt extension, else the 7 standard pairs - local c1 = { 256, 512, 0, 192, 240, 460, 392 } - local c2 = { 0, -256, 0, 64, 0, -208, -232 } + local c1, c2 = Adpcm.MS_COEF1, Adpcm.MS_COEF2 local ncoef = 7 if fmt.avail >= 22 then local k = u16(fmt.body + 20) @@ -592,9 +592,9 @@ function Decoder.read(self: Decoder, maxFrames: number, out: buffer?): (buffer, local avail = math.min(ba, self.dataOffset + self.dataSize - off) local got if kind == "ima_adpcm" then - got = Codecs.imaBlock(self._buf, off, avail, ch, spb, cache) + got = Adpcm.imaWav(self._buf, off, avail, ch, spb, cache, 0) else - got = Codecs.msBlock(self._buf, off, avail, ch, spb, cache, self._coefs :: buffer, self._ncoef, + got = Adpcm.msBlock(self._buf, off, avail, ch, spb, cache, 0, self._coefs :: buffer, self._ncoef, self._state :: buffer) end self._cacheBlock = block diff --git a/src/Formats/audio/wavpack/init.luau b/src/Formats/audio/wavpack/init.luau new file mode 100644 index 0000000..022594b --- /dev/null +++ b/src/Formats/audio/wavpack/init.luau @@ -0,0 +1,219 @@ +--!strict +-- audio/wavpack: WavPack (.wv) files: the block sequence around codecs/audio/WavPack, APEv2 tags, the .wvc correction +-- file of hybrid lossless files. Written from the WavPack 5 file format document (David Bryant) and the WavPack 5.9.0 +-- library's file handling (open_utils.c; BSD 3-clause, licenses/wavpack-LICENSE.txt). +-- Supports: lossless and hybrid streams, integer 8 - 32 bit and 32-bit float, 1 - 4096 channels (WAV order, as the +-- encoder stores them), non-standard sample rates, the correction file (opts.correction, else opts.resolve("c") +-- on hosts with files) which makes a hybrid file lossless, garbage between blocks (resync), sample-accurate seeking +-- (every block is independent), APEv2 tags at the end (codecs/audio/ApeTag). Without a correction file a hybrid file +-- decodes lossy (as wvunpack does). Not supported: DSD (Err.UNSUPPORTED), WavPack 1 - 3 files, encoding. +-- +-- local dec = WavPack.open(Bytes.reader(buf)) -- Types.Decoder + bitsPerSample, float, hybrid, lossless, ... +-- local f32, n = dec:read(4096) +-- local i32, n = dec:readInt(4096) -- integer streams: the samples as wvunpack writes them +-- local audio = WavPack.decode(Bytes.reader(buf)) -- Types.Audio + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/audio/Pcm") +local Stream = require("@formats/codecs/audio/Stream") +local ApeTag = require("@formats/codecs/audio/ApeTag") +local WavPackCodec = require("@formats/codecs/audio/WavPack") + +-- ------------------------------------------------------------------------------------------------ contract +local WavPack = { + name = "wavpack", + category = "audio", + extensions = { "wv" }, + mime = { "audio/x-wavpack", "audio/wavpack" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/WavPack" }, + caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, hybrid = true, float = true, depths = { 8, 12, 16, 20, 24, 32 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type OpenOptions = { + correction: (buffer | string)?, -- the .wvc file of a hybrid file (default: opts.resolve(name .. "c") when given) + resolve: ((uri: string) -> buffer?)?, -- sibling files (the api passes it for paths) + name: string?, -- the file name (the api passes it) + maxFrames: number?, -- decode(): refuse longer streams (default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function WavPack.sniff(r: Bytes.Reader): number + if r:peek(4) ~= "wvpk" then + return 0 + end + local v = r:peekU8(9) + return if v == 4 then 1 else 0.5 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(r, opts?) -> Types.Audio | nil, Err: the whole stream +function WavPack.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) + local dec, err = WavPack.open(r, opts) + if not dec then + return nil, err + end + local d = dec :: any + local limit = opts and opts.maxFrames or 2 ^ 28 + if d.frames > limit or d.frames * d.channels > 2 ^ 28 then + return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", d.frames)) + end + return Pcm.drain(d, d.source, limit) +end + +-- ------------------------------------------------------------------------------------------------ open +type Index = { offsets: { { number } }, starts: { number }, samples: { number }, total: number, first: number, md5: string? } + +-- index(buf, base, limit) -> the frames (block offsets per frame) of a .wv / .wvc block sequence +local function index(buf: buffer, base: number, limit: number): (Index?, string?) + local at = base + local idx: Index = { offsets = {}, starts = {}, samples = {}, total = -1, first = -1 } + local cur: { number }? = nil + local initial = -1 + local resyncs = 0 + while at + 32 <= limit do + local h = WavPackCodec.header(buf, at, limit) + if not h then + -- garbage (or a tag) between blocks: search the next header + if resyncs > 64 then + break + end + local s = buffer.readstring(buf, at + 1, math.min(limit - at - 1, 1048576)) + local k = string.find(s, "wvpk", 1, true) + if not k then + break + end + at = at + k + resyncs += 1 + continue + end + if initial < 0 then + initial = h.index + idx.total = h.total + end + if h.samples > 0 then + if bit32.band(h.flags, WavPackCodec.INITIAL) ~= 0 or not cur then + cur = { at } + table.insert(idx.offsets, cur) + table.insert(idx.starts, h.index - initial) + table.insert(idx.samples, h.samples) + if idx.first < 0 then + idx.first = at + end + else + table.insert(cur, at) + end + if bit32.band(h.flags, WavPackCodec.FINAL) ~= 0 then + cur = nil + end + else + idx.md5 = idx.md5 or WavPackCodec.md5(buf, at, limit) + end + at += h.size + end + if idx.first < 0 then + return nil, "no audio blocks" + end + return idx, nil +end + +local function correctionFile(opts: OpenOptions?): buffer? + if not opts then + return nil + end + local c = opts.correction + if type(c) == "string" then + return buffer.fromstring(c) + elseif type(c) == "buffer" then + return c + end + if type(opts.resolve) == "function" and type(opts.name) == "string" then + local base = string.match(opts.name, "([^/\\]+)$") + if base then + local ok, b = pcall(opts.resolve, base .. "c") + if ok and type(b) == "buffer" then + return b + end + end + end + return nil +end + +-- open(r, opts?) -> Decoder | nil, Err +function WavPack.open(r: Bytes.Reader, opts: OpenOptions?): (Types.Decoder?, Err.Err?) + if type(r) == "buffer" then + r = Bytes.reader(r :: any) + end + if type(r) ~= "table" or type(r.buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "open: expected a Reader") + end + local buf, base, limit = r.buf, r.base, r.limit + local tags, tagInfo = ApeTag.find(buf, base, limit) + local stop = if tagInfo then tagInfo.start else limit + local idx, ierr = index(buf, base, stop) + if not idx then + return nil, Err.from(ierr, base) + end + local info, err = WavPackCodec.info(buf, idx.first, stop) + if not info then + return nil, err + end + if info.channels > 256 then + return nil, Err.new(Err.LIMIT, info.channels .. " channels") + end + local count = #idx.offsets + local last = idx.starts[count] + idx.samples[count] + local frames = if idx.total >= 0 then math.min(idx.total, last) else last + -- the correction file: its frames by start sample + local cbuf = if info.hybrid then correctionFile(opts) else nil + local cfor: { [number]: { number } } = {} + if cbuf then + local cidx = index(cbuf, 0, buffer.len(cbuf)) + if cidx then + for i, offs in cidx.offsets do + cfor[cidx.starts[i]] = offs + end + else + cbuf = nil + end + end + local codec = WavPackCodec.decoder(info.channels) + local dec: any = { + sampleRate = info.sampleRate, + channels = info.channels, + frames = frames, + duration = frames / info.sampleRate, + bitrate = if frames > 0 then math.floor((stop - base) * 8 * info.sampleRate / frames) else 0, + tags = tags or {}, + bitsPerSample = info.bitsPerSample, + float = info.float, + hybrid = info.hybrid, + lossless = not info.hybrid or cbuf ~= nil, + channelMask = info.channelMask, + md5 = idx.md5, + source = { format = "wavpack", bitDepth = info.bitsPerSample, float = info.float, hybrid = info.hybrid, correction = cbuf ~= nil, version = info.version, tags = tagInfo and tagInfo.items }, + } + local starts, offsets = idx.starts, idx.offsets + return Stream.packets(dec, { + count = count, + start = function(i: number): number + return if i > count then last else starts[i] + end, + decode = function(i: number): (number?, Err.Err?) + local co = if cbuf then cfor[starts[i]] else nil + return codec:frame(buf, offsets[i], if co then cbuf else nil, co) + end, + pcm = function(): { number } + return codec.pcm + end, + reset = function() end, + stop = frames, + scale = if info.float then 1 else 1 / 2 ^ (info.bytesPerSample * 8 - 1), + ints = not info.float, + }) +end + +return WavPack diff --git a/src/Formats/codecs/audio/Ac3/Decode.luau b/src/Formats/codecs/audio/Ac3/Decode.luau new file mode 100644 index 0000000..830de4a --- /dev/null +++ b/src/Formats/codecs/audio/Ac3/Decode.luau @@ -0,0 +1,916 @@ +--!strict +--!native +--!optimize 2 +-- codecs/audio/Ac3/Decode: one AC-3 syncframe (6 audio blocks of 256 samples) -> PCM. Written from ATSC A/52:2018 +-- (section 5.3 syntax, 7.1 exponents, 7.2 parametric bit allocation with delta bit allocation, 7.3 mantissas with +-- grouping and dither, 7.4 coupling with phase flags, 7.5 rematrixing, 7.7.1 dynamic range, 7.9 the 512 / 2 x 256 +-- inverse transforms with block switching) on codecs/audio/Mdct; no third-party code. The bit reader is module state +-- over a frame the caller pads by PAD bytes; every section stops when the position passes the frame. No error / +-- assert: failures return nil, "message". +local T = require("@formats/codecs/audio/Ac3/Tables") +local Mdct = require("@formats/codecs/audio/Mdct") + +local readu32, bswap, extract, band, rshift = buffer.readu32, bit32.byteswap, bit32.extract, bit32.band, bit32.rshift +local max, min = math.max, math.min + +local Decode = {} +Decode.PAD = 2048 + +local CPL, LFE = 7, 6 -- channel slots: 1 .. 5 full bandwidth, 6 LFE, 7 the coupling channel +local NFCHANS = { [0] = 2, 1, 2, 3, 3, 4, 4, 5 } + +local SLOWDEC, FASTDEC, SLOWGAIN, DBPBTAB, FLOORTAB, FASTGAIN = T.SLOWDEC, T.FASTDEC, T.SLOWGAIN, T.DBPBTAB, T.FLOORTAB, T.FASTGAIN +local BNDTAB, BNDSZ, MASKTAB, LATAB, HTH, BAPTAB = T.BNDTAB, T.BNDSZ, T.MASKTAB, T.LATAB, T.HTH, T.BAPTAB + +-- 2^-e for the exponents 0 .. 24 +local POW2 = table.create(32, 0) +for e = 0, 31 do + POW2[e + 1] = 2 ^ -e +end +-- symmetric quantiser values (Tables 7.19 - 7.23): Q1[code + 1] etc. +local function levels(n: number): { number } + local t = {} + for c = 0, n - 1 do + t[c + 1] = (2 * c - (n - 1)) / n + end + return t +end +local Q1, Q2, Q3, Q4, Q5 = levels(3), levels(5), levels(7), levels(11), levels(15) +-- bits of the asymmetric quantisers (bap 6 .. 15) +local QBITS = { [6] = 5, [7] = 6, [8] = 7, [9] = 8, [10] = 9, [11] = 10, [12] = 11, [13] = 12, [14] = 14, [15] = 16 } + +local WINDOW = Mdct.window("kbd", 512, 5) :: { number } +local PLAN512 = Mdct.new(512) :: Mdct.Plan +local PLAN256 = Mdct.new(256) :: Mdct.Plan + +-- ------------------------------------------------------------------------------------------------ bit reader +local B: buffer = buffer.create(0) +local P = 0 + +local function bits(n: number): number + if n <= 0 then + return 0 + end + if n > 24 then + local hi = bits(n - 16) + return hi * 65536 + bits(16) + end + local w = bswap(readu32(B, rshift(P, 3))) + local v = extract(w, 32 - band(P, 7) - n, n) + P += n + return v +end + +-- ------------------------------------------------------------------------------------------------ state +export type State = { + -- the frame header + fscod: number, + acmod: number, + lfeon: boolean, + nfchans: number, + channels: number, -- output channels + map: { number }, -- output index of slots 1 .. 6 + drc: number, -- the dynamic range scale (0 = off) + -- per channel slot (1 .. 7) + exp: { { number } }, + bap: { { number } }, + coef: { { number } }, + delay: { { number } }, + endmant: { number }, + chexpstr: { number }, + blksw: { boolean }, + dithflag: { boolean }, + fsnroffst: { number }, + fgaincod: { number }, + dbaOn: { boolean }, + dbaOffst: { { number } }, + dbaLen: { { number } }, + dbaBa: { { number } }, + -- coupling + cplinu: boolean, + chincpl: { boolean }, + phsflginu: boolean, + cplbegf: number, + cplendf: number, + cplbndstrc: { boolean }, -- [sbnd + 1], sbnd = 0 .. 17 (absolute sub-band) + cplco: { { number } }, -- [ch][sbnd + 1] + phsflg: { boolean }, -- [sbnd + 1] + cplfleak: number, + cplsleak: number, + rematflg: { boolean }, + -- bit allocation parameters + sdcycod: number, + fdcycod: number, + sgaincod: number, + dbpbcod: number, + floorcod: number, + csnroffst: number, + dynrng: { number }, -- gain for Ch1 / Ch2 + seed: number, -- dither generator + -- scratch + psd: { number }, + bndpsd: { number }, + excite: { number }, + mask: { number }, + y: { number }, + pcm: { number }, + blocks: { number }, -- the bit offset of each audio block in the last frame (for tools) +} + +local function arrays(n: number, size: number, v: any): { any } + local t = {} + for i = 1, n do + t[i] = table.create(size, v) + end + return t +end + +function Decode.state(): State + return { + fscod = 0, + acmod = 2, + lfeon = false, + nfchans = 2, + channels = 2, + map = { 1, 2, 3, 4, 5, 6 }, + drc = 0, + exp = arrays(7, 264, 0), + bap = arrays(7, 264, 0), + coef = arrays(7, 256, 0), + delay = arrays(6, 256, 0), + endmant = table.create(7, 0), + chexpstr = table.create(7, 0), + blksw = table.create(7, false), + dithflag = table.create(7, false), + fsnroffst = table.create(7, 0), + fgaincod = table.create(7, 0), + dbaOn = table.create(7, false), + dbaOffst = arrays(7, 8, 0), + dbaLen = arrays(7, 8, 0), + dbaBa = arrays(7, 8, 0), + cplinu = false, + chincpl = table.create(7, false), + phsflginu = false, + cplbegf = 0, + cplendf = 0, + cplbndstrc = table.create(18, false), + cplco = arrays(5, 18, 0), + phsflg = table.create(18, false), + cplfleak = 0, + cplsleak = 0, + rematflg = table.create(4, false), + sdcycod = 0, + fdcycod = 0, + sgaincod = 0, + dbpbcod = 0, + floorcod = 0, + csnroffst = 0, + dynrng = { 1, 1 }, + seed = 1, + psd = table.create(256, 0), + bndpsd = table.create(50, 0), + excite = table.create(50, 0), + mask = table.create(50, 0), + y = table.create(512, 0), + pcm = table.create(1536 * 2, 0), + blocks = table.create(6, 0), + } +end + +-- reset(st): forget the overlap (before a seek) +function Decode.reset(st: State) + for _, d in st.delay do + for i = 1, 256 do + d[i] = 0 + end + end +end + +-- ------------------------------------------------------------------------------------------------ exponents +-- read ngrps grouped exponents (7 bits = 3 deltas each) after absexp into e[first + 1 ..] (bins first ..), grpsize +-- bins per delta; false when an exponent leaves 0 .. 24 +local function exponents(e: { number }, absexp: number, ngrps: number, grpsize: number, first: number): boolean + local prev = absexp + local k = first + 1 + for _ = 1, ngrps do + local g = bits(7) + if g >= 125 then + return false + end + local d1 = g // 25 + local d2 = (g % 25) // 5 + local d3 = g % 5 + for m = 1, 3 do + local d = if m == 1 then d1 elseif m == 2 then d2 else d3 + prev += d - 2 + if prev < 0 or prev > 24 then + return false + end + for _ = 1, grpsize do + e[k] = prev + k += 1 + end + end + end + return true +end + +-- ------------------------------------------------------------------------------------------------ bit allocation +local function logadd(a: number, b: number): number + local c = a - b + local adr = min(rshift(if c >= 0 then c else -c, 1), 255) + return if c >= 0 then a + LATAB[adr + 1] else b + LATAB[adr + 1] +end + +local function lowcomp(a: number, b0: number, b1: number, bin: number): number + if bin < 7 then + if b0 + 256 == b1 then + a = 384 + elseif b0 > b1 then + a = max(0, a - 64) + end + elseif bin < 20 then + if b0 + 256 == b1 then + a = 320 + elseif b0 > b1 then + a = max(0, a - 64) + end + else + a = max(0, a - 128) + end + return a +end + +-- section 7.2.2: the bap of bins [start, stop) of channel slot ch +local function allocate(st: State, ch: number, start: number, stop: number, fgain: number, snroffset: number, isLfe: boolean) + local e, bap = st.exp[ch], st.bap[ch] + local psd, bndpsd, excite, mask = st.psd, st.bndpsd, st.excite, st.mask + local sdecay, fdecay = SLOWDEC[st.sdcycod + 1], FASTDEC[st.fdcycod + 1] + local sgain, dbknee, floor = SLOWGAIN[st.sgaincod + 1], DBPBTAB[st.dbpbcod + 1], FLOORTAB[st.floorcod + 1] + if floor >= 0x8000 then + floor -= 0x10000 -- 0xf800: a negative 16-bit value + end + for bin = start, stop - 1 do + psd[bin + 1] = 3072 - e[bin + 1] * 128 + end + -- PSD integration + local j = start + local k = MASKTAB[start + 1] + local lastbin + repeat + lastbin = min(BNDTAB[k + 1] + BNDSZ[k + 1], stop) + local v = psd[j + 1] + j += 1 + while j < lastbin do + v = logadd(v, psd[j + 1]) + j += 1 + end + bndpsd[k + 1] = v + k += 1 + until stop <= lastbin + -- excitation + local bndstrt = MASKTAB[start + 1] + local bndend = MASKTAB[stop] + 1 + local fastleak, slowleak = 0, 0 + local begin + if bndstrt == 0 then + local lc = 0 + lc = lowcomp(lc, bndpsd[1], bndpsd[2], 0) + excite[1] = bndpsd[1] - fgain - lc + lc = lowcomp(lc, bndpsd[2], bndpsd[3], 1) + excite[2] = bndpsd[2] - fgain - lc + begin = 7 + for bin = 2, 6 do + local last = isLfe and bin == 6 + if not last then + lc = lowcomp(lc, bndpsd[bin + 1], bndpsd[bin + 2], bin) + end + fastleak = bndpsd[bin + 1] - fgain + slowleak = bndpsd[bin + 1] - sgain + excite[bin + 1] = fastleak - lc + if not last and bndpsd[bin + 1] <= bndpsd[bin + 2] then + begin = bin + 1 + break + end + end + for bin = begin, min(bndend, 22) - 1 do + if not (isLfe and bin == 6) then + lc = lowcomp(lc, bndpsd[bin + 1], bndpsd[bin + 2], bin) + end + fastleak = max(fastleak - fdecay, bndpsd[bin + 1] - fgain) + slowleak = max(slowleak - sdecay, bndpsd[bin + 1] - sgain) + excite[bin + 1] = max(fastleak - lc, slowleak) + end + begin = 22 + else + begin = bndstrt + fastleak = st.cplfleak * 256 + 768 + slowleak = st.cplsleak * 256 + 768 + end + for bin = begin, bndend - 1 do + fastleak = max(fastleak - fdecay, bndpsd[bin + 1] - fgain) + slowleak = max(slowleak - sdecay, bndpsd[bin + 1] - sgain) + excite[bin + 1] = max(fastleak, slowleak) + end + -- masking curve + local hth = HTH[st.fscod + 1] + for bin = bndstrt, bndend - 1 do + local x = excite[bin + 1] + local p = bndpsd[bin + 1] + if p < dbknee then + x += (dbknee - p) // 4 + end + mask[bin + 1] = max(x, hth[bin + 1]) + end + -- delta bit allocation + if st.dbaOn[ch] then + local offs, lens, bas = st.dbaOffst[ch], st.dbaLen[ch], st.dbaBa[ch] + local b = 0 + for seg = 1, #offs do + b += offs[seg] + local ba = bas[seg] + local delta = if ba >= 4 then (ba - 3) * 128 else (ba - 4) * 128 + for _ = 1, lens[seg] do + if b < 50 then + mask[b + 1] += delta + end + b += 1 + end + end + end + -- bit allocation pointers + local i = start + j = MASKTAB[start + 1] + repeat + lastbin = min(BNDTAB[j + 1] + BNDSZ[j + 1], stop) + local m = mask[j + 1] - snroffset - floor + if m < 0 then + m = 0 + end + m = band(m, 0x1fe0) + floor + while i < lastbin do + local adr = (psd[i + 1] - m) // 32 + bap[i + 1] = BAPTAB[min(63, max(0, adr)) + 1] + i += 1 + end + j += 1 + until stop <= lastbin +end + +-- ------------------------------------------------------------------------------------------------ mantissas +-- grouped mantissa state (bap 1, 2, 4 share groups across channels within a block) +local G1, G2, G4 = table.create(3, 0), table.create(3, 0), table.create(2, 0) +local n1, n2, n4 = 0, 0, 0 + +local function dither(st: State): number + local s = (st.seed * 1664525 + 1013904223) % 4294967296 + st.seed = s + return (s / 2147483648 - 1) * 0.707 +end + +-- the mantissas of bins [start, stop) of slot ch into out[], scaled by their exponents (bap 0: dither when asked) +local function mantissas(st: State, ch: number, start: number, stop: number, out: { number }, dith: boolean) + local e, bap = st.exp[ch], st.bap[ch] + for bin = start, stop - 1 do + local b = bap[bin + 1] + local v + if b == 0 then + v = if dith then dither(st) else 0 + elseif b == 1 then + if n1 == 0 then + local g = bits(5) + if g > 26 then + g = 26 + end + G1[1], G1[2], G1[3] = Q1[g // 9 + 1], Q1[(g % 9) // 3 + 1], Q1[g % 3 + 1] + n1 = 3 + end + v = G1[4 - n1] + n1 -= 1 + elseif b == 2 then + if n2 == 0 then + local g = bits(7) + if g > 124 then + g = 124 + end + G2[1], G2[2], G2[3] = Q2[g // 25 + 1], Q2[(g % 25) // 5 + 1], Q2[g % 5 + 1] + n2 = 3 + end + v = G2[4 - n2] + n2 -= 1 + elseif b == 3 then + v = Q3[min(bits(3), 6) + 1] + elseif b == 4 then + if n4 == 0 then + local g = bits(7) + if g > 120 then + g = 120 + end + G4[1], G4[2] = Q4[g // 11 + 1], Q4[g % 11 + 1] + n4 = 2 + end + v = G4[3 - n4] + n4 -= 1 + elseif b == 5 then + v = Q5[min(bits(4), 14) + 1] + else + local nb = QBITS[b] + local m = bits(nb) + local half = 2 ^ (nb - 1) + if m >= half then + m -= 2 * half + end + v = m / half + end + out[bin + 1] = v * POW2[e[bin + 1] + 1] + end +end + +-- ------------------------------------------------------------------------------------------------ audio block +local function readDba(st: State, ch: number) + local nseg = bits(3) + 1 + local offs, lens, bas = st.dbaOffst[ch], st.dbaLen[ch], st.dbaBa[ch] + table.clear(offs) + table.clear(lens) + table.clear(bas) + for seg = 1, nseg do + offs[seg] = bits(5) + lens[seg] = bits(4) + bas[seg] = bits(3) + end +end + +local EXPGRP = { 3, 6, 12 } -- bins per group of 3 deltas, by strategy (D15 / D25 / D45) + +local function audblk(st: State, blk: number, limit: number): (boolean?, string?) + local nf, acmod = st.nfchans, st.acmod + for ch = 1, nf do + st.blksw[ch] = bits(1) == 1 + end + for ch = 1, nf do + st.dithflag[ch] = bits(1) == 1 + end + for i = 1, if acmod == 0 then 2 else 1 do + if bits(1) == 1 then + local v = bits(8) + local x = rshift(v, 5) + if x >= 4 then + x -= 8 + end + local g = 2 ^ (x + 1) * (32 + band(v, 31)) / 64 + st.dynrng[i] = if st.drc == 1 then g else g ^ st.drc + elseif blk == 0 then + st.dynrng[i] = 1 + end + end + -- coupling strategy + if bits(1) == 1 then + st.cplinu = bits(1) == 1 + if st.cplinu then + if acmod < 2 then + return nil, "coupling in a mono / dual mono stream" + end + for ch = 1, nf do + st.chincpl[ch] = bits(1) == 1 + end + st.phsflginu = if acmod == 2 then bits(1) == 1 else false + st.cplbegf = bits(4) + st.cplendf = bits(4) + if st.cplendf + 3 <= st.cplbegf then + return nil, "bad coupling range" + end + st.cplbndstrc[st.cplbegf + 1] = false + for sbnd = st.cplbegf + 1, st.cplendf + 2 do + st.cplbndstrc[sbnd + 1] = bits(1) == 1 + end + else + for ch = 1, nf do + st.chincpl[ch] = false + end + st.phsflginu = false + end + elseif blk == 0 then + return nil, "no coupling strategy in block 0" + end + local cplinu = st.cplinu + local cplbegf, cplendf = st.cplbegf, st.cplendf + local cplstrt = 37 + 12 * cplbegf + local cplend = 37 + 12 * (cplendf + 3) + -- coupling coordinates (per sub-band, duplicated over each coupling band) + if cplinu then + local anyNew = false + for ch = 1, nf do + if st.chincpl[ch] then + if bits(1) == 1 then + anyNew = true + local mstr = bits(2) * 3 + local co = st.cplco[ch] + local v = 0 + for sbnd = cplbegf, cplendf + 2 do + if not st.cplbndstrc[sbnd + 1] then + local ex, mant = bits(4), bits(4) + local m = if ex == 15 then mant / 16 else (mant + 16) / 32 + v = m * 2 ^ -(ex + mstr) + end + co[sbnd + 1] = v + end + end + end + end + if acmod == 2 and st.phsflginu and anyNew then + local f = false + for sbnd = cplbegf, cplendf + 2 do + if not st.cplbndstrc[sbnd + 1] then + f = bits(1) == 1 + end + st.phsflg[sbnd + 1] = f + end + end + end + -- rematrixing + if acmod == 2 then + if bits(1) == 1 then + local n = if not cplinu or cplbegf > 2 then 4 elseif cplbegf > 0 then 3 else 2 + for r = 1, 4 do + st.rematflg[r] = if r <= n then bits(1) == 1 else false + end + elseif blk == 0 then + for r = 1, 4 do + st.rematflg[r] = false + end + end + end + -- exponent strategies + local chexpstr = st.chexpstr + chexpstr[CPL] = if cplinu then bits(2) else 0 + for ch = 1, nf do + chexpstr[ch] = bits(2) + end + chexpstr[LFE] = if st.lfeon then bits(1) else 0 + if blk == 0 then + for ch = 1, nf do + if chexpstr[ch] == 0 then + return nil, "exponent reuse in block 0" + end + end + if (cplinu and chexpstr[CPL] == 0) or (st.lfeon and chexpstr[LFE] == 0) then + return nil, "exponent reuse in block 0" + end + end + local endmant = st.endmant + for ch = 1, nf do + if chexpstr[ch] ~= 0 then + if st.chincpl[ch] then + endmant[ch] = cplstrt + else + local bw = bits(6) + if bw > 60 then + return nil, "bad channel bandwidth code" + end + endmant[ch] = 37 + 3 * (bw + 12) + end + end + end + endmant[LFE] = 7 + -- exponents + if cplinu and chexpstr[CPL] ~= 0 then + local abs = bits(4) * 2 + local grp = EXPGRP[chexpstr[CPL]] + if not exponents(st.exp[CPL], abs, (cplend - cplstrt) // grp, grp // 3, cplstrt) then + return nil, "bad coupling exponents" + end + end + for ch = 1, nf do + local s = chexpstr[ch] + if s ~= 0 then + local grp = EXPGRP[s] + local ngrps + if s == 1 then + ngrps = (endmant[ch] - 1) // 3 + elseif s == 2 then + ngrps = (endmant[ch] - 1 + 3) // 6 + else + ngrps = (endmant[ch] - 1 + 9) // 12 + end + local e = st.exp[ch] + e[1] = bits(4) + if not exponents(e, e[1], ngrps, grp // 3, 1) then + return nil, "bad exponents" + end + bits(2) -- gainrng + end + end + if st.lfeon and chexpstr[LFE] ~= 0 then + local e = st.exp[LFE] + e[1] = bits(4) + if not exponents(e, e[1], 2, 1, 1) then + return nil, "bad LFE exponents" + end + end + if P > limit then + return nil, "truncated block" + end + -- bit allocation parameters + if bits(1) == 1 then + st.sdcycod, st.fdcycod, st.sgaincod, st.dbpbcod, st.floorcod = bits(2), bits(2), bits(2), bits(2), bits(3) + elseif blk == 0 then + return nil, "no bit allocation parameters in block 0" + end + if bits(1) == 1 then + st.csnroffst = bits(6) + if cplinu then + st.fsnroffst[CPL], st.fgaincod[CPL] = bits(4), bits(3) + end + for ch = 1, nf do + st.fsnroffst[ch], st.fgaincod[ch] = bits(4), bits(3) + end + if st.lfeon then + st.fsnroffst[LFE], st.fgaincod[LFE] = bits(4), bits(3) + end + elseif blk == 0 then + return nil, "no SNR offsets in block 0" + end + if cplinu then + if bits(1) == 1 then + st.cplfleak, st.cplsleak = bits(3), bits(3) + end + end + -- delta bit allocation + if bits(1) == 1 then + local modes = table.create(7, 0) + if cplinu then + modes[CPL] = bits(2) + end + for ch = 1, nf do + modes[ch] = bits(2) + end + if cplinu and modes[CPL] == 1 then + readDba(st, CPL) + end + for ch = 1, nf do + if modes[ch] == 1 then + readDba(st, ch) + end + end + for _, ch in { 1, 2, 3, 4, 5, CPL } do + if modes[ch] == 1 then + st.dbaOn[ch] = true + elseif modes[ch] == 2 or modes[ch] == 3 then + st.dbaOn[ch] = false + end + end + elseif blk == 0 then + for ch = 1, 7 do + st.dbaOn[ch] = false + end + end + -- skip field + if bits(1) == 1 then + P += bits(9) * 8 + end + if P > limit then + return nil, "truncated block" + end + -- bit allocation + local zero = st.csnroffst == 0 + if zero then + for ch = 1, nf do + if st.fsnroffst[ch] ~= 0 then + zero = false + end + end + if (cplinu and st.fsnroffst[CPL] ~= 0) or (st.lfeon and st.fsnroffst[LFE] ~= 0) then + zero = false + end + end + local function alloc(ch: number, start: number, stop: number, isLfe: boolean) + if zero then + for i = start + 1, stop do + st.bap[ch][i] = 0 + end + else + local snr = ((st.csnroffst - 15) * 16 + st.fsnroffst[ch]) * 4 + allocate(st, ch, start, stop, FASTGAIN[st.fgaincod[ch] + 1], snr, isLfe) + end + end + if cplinu then + alloc(CPL, cplstrt, cplend, false) + end + for ch = 1, nf do + alloc(ch, 0, endmant[ch], false) + end + if st.lfeon then + alloc(LFE, 0, 7, true) + end + -- mantissas + n1, n2, n4 = 0, 0, 0 + local gotCpl = false + local coef = st.coef + for ch = 1, nf do + local c = coef[ch] + mantissas(st, ch, 0, endmant[ch], c, st.dithflag[ch]) + for i = endmant[ch] + 1, 256 do + c[i] = 0 + end + if cplinu and st.chincpl[ch] and not gotCpl then + mantissas(st, CPL, cplstrt, cplend, coef[CPL], false) + gotCpl = true + end + if P > limit then + return nil, "truncated block" + end + end + if st.lfeon then + local c = coef[LFE] + mantissas(st, LFE, 0, 7, c, false) + for i = 8, 256 do + c[i] = 0 + end + end + if P > limit then + return nil, "truncated block" + end + -- decoupling (section 7.4): dither the coupling channel's zero-bit mantissas per channel + if cplinu then + local cc, cbap, cexp = coef[CPL], st.bap[CPL], st.exp[CPL] + for ch = 1, nf do + if st.chincpl[ch] then + local c, co = coef[ch], st.cplco[ch] + local dith = st.dithflag[ch] + local flip = acmod == 2 and ch == 2 and st.phsflginu + for sbnd = cplbegf, cplendf + 2 do + local f = co[sbnd + 1] * 8 + if flip and st.phsflg[sbnd + 1] then + f = -f + end + for k = 37 + 12 * sbnd + 1, 37 + 12 * sbnd + 12 do + local v = cc[k] + if cbap[k] == 0 then + v = if dith then dither(st) * POW2[cexp[k] + 1] else 0 + end + c[k] = v * f + end + end + for k = cplend + 1, 256 do + c[k] = 0 + end + end + end + end + -- rematrixing (section 7.5) + if acmod == 2 then + local stop = if cplinu then cplstrt else min(endmant[1], endmant[2]) + local l, r = coef[1], coef[2] + local edges = { 13, 25, 37, 61, 253 } + for rb = 1, 4 do + if st.rematflg[rb] then + for k = edges[rb] + 1, min(edges[rb + 1], stop) do + local a, b = l[k], r[k] + l[k], r[k] = a + b, a - b + end + end + end + end + return true, nil +end + +-- ------------------------------------------------------------------------------------------------ transform +-- the inverse transform of slot ch (long or two short), windowed, overlap-added into out[base + i * step] +local function synth(st: State, ch: number, short: boolean, gain: number, out: { number }, base: number, step: number) + local x, y, d, w = st.coef[ch], st.y, st.delay[ch], WINDOW + if short then + -- two 256-point transforms of the interleaved coefficients, phases alpha = -1 (n0 = 0) and +1 (n0 = N / 2) + local z = st.psd -- 256 scratch + Mdct.inverse(PLAN256, x, 1, 2, z, 1, -2 * gain) + for n = 0, 63 do + y[n + 1] = -z[n + 193] + end + for n = 64, 255 do + y[n + 1] = z[n - 63] + end + Mdct.inverse(PLAN256, x, 2, 2, z, 1, -2 * gain) + for n = 0, 191 do + y[257 + n] = z[n + 65] + end + for n = 192, 255 do + y[257 + n] = -z[n - 191] + end + else + Mdct.inverse(PLAN512, x, 1, 1, y, 1, -2 * gain) + end + local p = base + for n = 1, 256 do + out[p] = y[n] * w[n] + d[n] + d[n] = y[n + 256] * w[n + 256] + p += step + end +end + +-- ------------------------------------------------------------------------------------------------ frame +-- the output index of each slot (1 .. 5 full bandwidth, 6 LFE) in WAVE order: L R C LFE surrounds +local ORDER: { [number]: { number } } = { + [0] = { 1, 2 }, + { 1 }, + { 1, 2 }, + { 1, 3, 2 }, + { 1, 2, 3 }, + { 1, 3, 2, 4 }, + { 1, 2, 3, 4 }, + { 1, 3, 2, 4, 5 }, +} +local HAS_C = { [0] = false, true, false, true, false, true, false, true } + +-- frame(st, buf, len, drc) -> 1536 | nil, message: decodes the syncframe at buf[0 .. len) (padded by PAD bytes) +-- into st.pcm (1536 * st.channels interleaved floats, WAVE order). drc: the dynamic range scale (0 = off, 1 = full). +function Decode.frame(st: State, buf: buffer, len: number, drc: number): (number?, string?) + if len < 8 or buffer.len(buf) < len + Decode.PAD then + return nil, "truncated frame" + end + B, P = buf, 32 + local fscod = bits(2) + bits(6) + local bsid = bits(5) + if bsid > 8 then + B = buffer.create(0) + return nil, "unsupported: bsid " .. bsid .. (if bsid > 10 then " (E-AC-3)" else " (reduced sample rate)") + end + if fscod == 3 then + B = buffer.create(0) + return nil, "bad sample rate code" + end + bits(3) -- bsmod + local acmod = bits(3) + if band(acmod, 1) == 1 and acmod ~= 1 then + bits(2) + end + if band(acmod, 4) ~= 0 then + bits(2) + end + if acmod == 2 then + bits(2) + end + local lfeon = bits(1) == 1 + for _ = 1, if acmod == 0 then 2 else 1 do + bits(5) + if bits(1) == 1 then + bits(8) + end + if bits(1) == 1 then + bits(8) + end + if bits(1) == 1 then + bits(7) + end + end + bits(2) + if bits(1) == 1 then + bits(14) + end + if bits(1) == 1 then + bits(14) + end + if bits(1) == 1 then + P += (bits(6) + 1) * 8 + end + local nf = NFCHANS[acmod] + local channels = nf + (if lfeon then 1 else 0) + if st.acmod ~= acmod or st.lfeon ~= lfeon then + -- a new channel layout: build the output map and forget the overlap + local order = ORDER[acmod] + local map = table.create(6, 0) + local nfront = if HAS_C[acmod] then 3 elseif acmod == 1 then 1 else 2 + for ch = 1, nf do + local o = order[ch] + map[ch] = if lfeon and o > nfront then o + 1 else o + end + if lfeon then + map[LFE] = nfront + 1 + end + st.map = map + st.pcm = table.create(1536 * channels, 0) + Decode.reset(st) + end + st.fscod, st.acmod, st.lfeon, st.nfchans, st.channels, st.drc = fscod, acmod, lfeon, nf, channels, drc + local pcm = st.pcm + local limit = len * 8 - 16 -- crc2 + for blk = 0, 5 do + st.blocks[blk + 1] = P + local ok, err = audblk(st, blk, limit) + if not ok then + B = buffer.create(0) + return nil, err + end + local base = blk * 256 * channels + for ch = 1, nf do + local g = st.dynrng[if acmod == 0 and ch == 2 then 2 else 1] + synth(st, ch, st.blksw[ch], g, pcm, base + st.map[ch], channels) + end + if lfeon then + synth(st, LFE, false, st.dynrng[1], pcm, base + st.map[LFE], channels) + end + end + B = buffer.create(0) + return 1536, nil +end + +return Decode diff --git a/src/Formats/codecs/audio/Ac3/Tables.luau b/src/Formats/codecs/audio/Ac3/Tables.luau new file mode 100644 index 0000000..3eec9e3 --- /dev/null +++ b/src/Formats/codecs/audio/Ac3/Tables.luau @@ -0,0 +1,102 @@ +--!strict +-- codecs/audio/Ac3/Tables: the AC-3 constant tables, transcribed from ATSC A/52:2018 (Digital Audio Compression +-- Standard) section 7.2.3 (bit allocation: slowdec, fastdec, slowgain, dbpbtab, floortab, fastgain, bndtab / bndsz, +-- latab, hth, baptab) and section 5.4 (frame sizes). masktab is derived from bndtab / bndsz, the transform window +-- (Table 7.33) is the Kaiser-Bessel-derived window with alpha 5 (codecs/audio/Mdct), which Table 7.33 rounds to five +-- decimals. No third-party code. +local T = {} + +T.SLOWDEC = { 0x0f, 0x11, 0x13, 0x15 } +T.FASTDEC = { 0x3f, 0x53, 0x67, 0x7b } +T.SLOWGAIN = { 0x540, 0x4d8, 0x478, 0x410 } +T.DBPBTAB = { 0x000, 0x700, 0x900, 0xb00 } +T.FLOORTAB = { 0x2f0, 0x2b0, 0x270, 0x230, 0x1f0, 0x170, 0x0f0, 0xf800 } +T.FASTGAIN = { 0x080, 0x100, 0x180, 0x200, 0x280, 0x300, 0x380, 0x400 } + +-- the 50 bit allocation bands: first bin and width (Table 7.12) +T.BNDTAB = { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 25, 26, 27, 28, 31, 34, 37, 40, 43, 46, 49, 55, 61, 67, 73, 79, 85, 97, 109, 121, 133, 157, 181, 205, 229, +} +T.BNDSZ = { + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 6, 6, 6, 6, 6, 6, 12, 12, 12, 12, 24, 24, 24, 24, 24, +} +-- masktab[bin + 1]: the band of each bin (Table 7.13; bins 253 .. 255 map to 0) +T.MASKTAB = table.create(256, 0) +for b = 1, 50 do + for k = T.BNDTAB[b], T.BNDTAB[b] + T.BNDSZ[b] - 1 do + T.MASKTAB[k + 1] = b - 1 + end +end + +-- log-addition table (Table 7.14) +T.LATAB = { + 0x0040, 0x003f, 0x003e, 0x003d, 0x003c, 0x003b, 0x003a, 0x0039, 0x0038, 0x0037, 0x0036, 0x0035, 0x0034, 0x0034, 0x0033, 0x0032, + 0x0031, 0x0030, 0x002f, 0x002f, 0x002e, 0x002d, 0x002c, 0x002c, 0x002b, 0x002a, 0x0029, 0x0029, 0x0028, 0x0027, 0x0026, 0x0026, + 0x0025, 0x0024, 0x0024, 0x0023, 0x0023, 0x0022, 0x0021, 0x0021, 0x0020, 0x0020, 0x001f, 0x001e, 0x001e, 0x001d, 0x001d, 0x001c, + 0x001c, 0x001b, 0x001b, 0x001a, 0x001a, 0x0019, 0x0019, 0x0018, 0x0018, 0x0017, 0x0017, 0x0016, 0x0016, 0x0015, 0x0015, 0x0015, + 0x0014, 0x0014, 0x0013, 0x0013, 0x0013, 0x0012, 0x0012, 0x0012, 0x0011, 0x0011, 0x0011, 0x0010, 0x0010, 0x0010, 0x000f, 0x000f, + 0x000f, 0x000e, 0x000e, 0x000e, 0x000d, 0x000d, 0x000d, 0x000d, 0x000c, 0x000c, 0x000c, 0x000c, 0x000b, 0x000b, 0x000b, 0x000b, + 0x000a, 0x000a, 0x000a, 0x000a, 0x000a, 0x0009, 0x0009, 0x0009, 0x0009, 0x0009, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, + 0x0007, 0x0007, 0x0007, 0x0007, 0x0007, 0x0007, 0x0006, 0x0006, 0x0006, 0x0006, 0x0006, 0x0006, 0x0006, 0x0006, 0x0005, 0x0005, + 0x0005, 0x0005, 0x0005, 0x0005, 0x0005, 0x0005, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, + 0x0004, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0002, + 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, + 0x0002, 0x0002, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, + 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, + 0x0001, 0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, +} + +-- hearing threshold per band (Table 7.15): HTH[fscod + 1][band + 1] +T.HTH = { + { + 0x04d0, 0x04d0, 0x0440, 0x0400, 0x03e0, 0x03c0, 0x03b0, 0x03b0, 0x03a0, 0x03a0, + 0x03a0, 0x03a0, 0x03a0, 0x0390, 0x0390, 0x0390, 0x0380, 0x0380, 0x0370, 0x0370, + 0x0360, 0x0360, 0x0350, 0x0350, 0x0340, 0x0340, 0x0330, 0x0320, 0x0310, 0x0300, + 0x02f0, 0x02f0, 0x02f0, 0x02f0, 0x0300, 0x0310, 0x0340, 0x0390, 0x03e0, 0x0420, + 0x0460, 0x0490, 0x04a0, 0x0460, 0x0440, 0x0440, 0x0520, 0x0800, 0x0840, 0x0840, + }, + { + 0x04f0, 0x04f0, 0x0460, 0x0410, 0x03e0, 0x03d0, 0x03c0, 0x03b0, 0x03b0, 0x03a0, + 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x0390, 0x0390, 0x0390, 0x0380, 0x0380, 0x0380, + 0x0370, 0x0370, 0x0360, 0x0360, 0x0350, 0x0350, 0x0340, 0x0340, 0x0320, 0x0310, + 0x0300, 0x02f0, 0x02f0, 0x02f0, 0x02f0, 0x0300, 0x0320, 0x0350, 0x0390, 0x03e0, + 0x0420, 0x0450, 0x04a0, 0x0490, 0x0460, 0x0440, 0x0480, 0x0630, 0x0840, 0x0840, + }, + { + 0x0580, 0x0580, 0x04b0, 0x0450, 0x0420, 0x03f0, 0x03e0, 0x03d0, 0x03c0, 0x03b0, + 0x03b0, 0x03b0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, + 0x0390, 0x0390, 0x0390, 0x0390, 0x0380, 0x0380, 0x0380, 0x0370, 0x0360, 0x0350, + 0x0340, 0x0330, 0x0320, 0x0310, 0x0300, 0x02f0, 0x02f0, 0x02f0, 0x0300, 0x0310, + 0x0330, 0x0350, 0x03c0, 0x0410, 0x0470, 0x04a0, 0x0460, 0x0440, 0x0450, 0x04e0, + }, +} + +-- bit allocation pointers (Table 7.16) +T.BAPTAB = { + 0, 1, 1, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 10, + 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, +} + +-- words per syncframe (Table 5.18) for frmsizecod // 2 (the nominal bit rate in kbps) and fscod: 48 kHz = 2 x rate, +-- 32 kHz = 3 x rate, 44.1 kHz = floor(rate x 1536000 / 705600) + (frmsizecod & 1) +T.BITRATES = { 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 448, 512, 576, 640 } +T.RATES = { 48000, 44100, 32000 } + +function T.frameWords(fscod: number, frmsizecod: number): number + local kbps = T.BITRATES[frmsizecod // 2 + 1] + if not kbps or fscod > 2 then + return 0 + end + if fscod == 0 then + return 2 * kbps + elseif fscod == 2 then + return 3 * kbps + end + return kbps * 1536000 // 705600 + frmsizecod % 2 +end + +return T diff --git a/src/Formats/codecs/audio/Ac3/init.luau b/src/Formats/codecs/audio/Ac3/init.luau new file mode 100644 index 0000000..16bf136 --- /dev/null +++ b/src/Formats/codecs/audio/Ac3/init.luau @@ -0,0 +1,172 @@ +--!strict +-- codecs/audio/Ac3: AC-3 (Dolby Digital, ATSC A/52) syncframes: the syncinfo / BSI header, the CRC check, and the +-- decoder (codecs/audio/Ac3/Decode). Written from ATSC A/52:2018; no third-party code. A codec (layer 3): audio/ac3 +-- (raw .ac3 files) builds on it, and the AC-3 tracks of MKV / MP4 / MPEG-TS / AVI reach it through +-- containers/AudioWrap. +-- Supports: every acmod (1+1, 1/0 .. 3/2) with or without LFE, 32 / 44.1 / 48 kHz, all bit rates, coupling with phase +-- flags, rematrixing, block switching, delta bit allocation, dither, dynamic range control (off by default, +-- `drc` = 0 .. 1 scales it). Output: every channel in WAVE order (L R C LFE surrounds), no downmix. Not supported: +-- E-AC-3 (bsid 11 .. 16) and the reduced-rate bsid 9 / 10 streams (UNSUPPORTED). +-- +-- local h = Ac3.header(buf, offset, limit) -- { sampleRate, frameSize, channels, acmod, lfeon, bsid, bitrate } +-- local dec = Ac3.decoder({ drc = 0 }) -- dec:decode(buf, offset, length) -> 1536, dec.pcm (interleaved) +-- +-- Never throws: bad data returns nil, Err. +local Err = require("@formats/core/Err") +local T = require("@formats/codecs/audio/Ac3/Tables") +local Decode = require("@formats/codecs/audio/Ac3/Decode") + +local Ac3 = {} + +local readu8 = buffer.readu8 +local NFCHANS = { [0] = 2, 1, 2, 3, 3, 4, 4, 5 } + +export type Header = { + sampleRate: number, + frameSize: number, -- bytes + bitrate: number, -- bits per second + channels: number, + acmod: number, + lfeon: boolean, + bsid: number, +} + +-- header(buf, o, limit) -> Header | nil (not an AC-3 / E-AC-3 syncframe header at o). E-AC-3 headers (bsid > 10) +-- come back with frameSize from their own frmsiz field so a scanner can step over them. +function Ac3.header(b: buffer, o: number, limit: number): Header? + if o < 0 or o + 8 > limit or o + 8 > buffer.len(b) then + return nil + end + if readu8(b, o) ~= 0x0B or readu8(b, o + 1) ~= 0x77 then + return nil + end + local bsid = bit32.rshift(readu8(b, o + 5), 3) + if bsid > 10 then + if bsid > 16 then + return nil + end + -- E-AC-3: strmtyp(2) substreamid(3) frmsiz(11) fscod(2) ... + local words = bit32.band(readu8(b, o + 2), 7) * 256 + readu8(b, o + 3) + 1 + local fs = bit32.rshift(readu8(b, o + 4), 6) + return { + sampleRate = if fs < 3 then T.RATES[fs + 1] else 0, + frameSize = words * 2, + bitrate = 0, + channels = 0, + acmod = bit32.band(bit32.rshift(readu8(b, o + 4), 1), 7), + lfeon = false, + bsid = bsid, + } + end + local b4 = readu8(b, o + 4) + local fscod, frmsizecod = bit32.rshift(b4, 6), bit32.band(b4, 63) + local words = T.frameWords(fscod, frmsizecod) + if words == 0 then + return nil + end + local acmod = bit32.rshift(readu8(b, o + 6), 5) + -- lfeon: after acmod and the optional cmixlev / surmixlev / dsurmod fields + local skip = 0 + if bit32.band(acmod, 1) == 1 and acmod ~= 1 then + skip += 2 + end + if bit32.band(acmod, 4) ~= 0 then + skip += 2 + end + if acmod == 2 then + skip += 2 + end + local w = readu8(b, o + 6) * 256 + readu8(b, o + 7) + local lfeon = bit32.extract(w, 12 - skip, 1) == 1 + local shift = if bsid > 8 then bsid - 8 else 0 + return { + sampleRate = T.RATES[fscod + 1] // 2 ^ shift, + frameSize = words * 2, + bitrate = T.BITRATES[frmsizecod // 2 + 1] * 1000 // 2 ^ shift, + channels = NFCHANS[acmod] + (if lfeon then 1 else 0), + acmod = acmod, + lfeon = lfeon, + bsid = bsid, + } +end + +-- the CRC-16 of A/52 section 7.10.1 (x^16 + x^15 + x^2 + 1, MSB first, zero start): a syncframe checks when the CRC of +-- everything after the sync word is 0 +local CRC = table.create(256, 0) +for i = 0, 255 do + local c = i * 256 + for _ = 1, 8 do + c = if c >= 0x8000 then bit32.bxor(bit32.band(c * 2, 0xFFFF), 0x8005) else c * 2 + end + CRC[i + 1] = c +end + +function Ac3.crc(b: buffer, o: number, n: number): number + local c = 0 + for i = o, o + n - 1 do + c = bit32.bxor(bit32.band(c * 256, 0xFFFF), CRC[bit32.bxor(bit32.rshift(c, 8), readu8(b, i)) + 1]) + end + return c +end + +-- ------------------------------------------------------------------------------------------------ decoder +export type Options = { + drc: number?, -- dynamic range control: 0 = off (default, like ffmpeg -drc_scale 0), 1 = as the stream says + crc: boolean?, -- check crc2 (default true): a mismatch is Err.CHECKSUM +} + +export type Decoder = { + pcm: { number }, -- the last frame: 1536 * channels interleaved floats, WAVE order + channels: number, + sampleRate: number, + blocks: { number }, -- the bit offset of each audio block in the last frame (tools: stream editing, analysis) + decode: (self: Decoder, buf: buffer, offset: number?, length: number?) -> (number?, Err.Err?), + reset: (self: Decoder) -> (), +} + +function Ac3.decoder(opts: Options?): Decoder + local o: Options = opts or {} + local drc = math.max(0, o.drc or 0) + local checkCrc = o.crc ~= false + local st = Decode.state() + local scratch = buffer.create(3840 + Decode.PAD) + local dec: Decoder + dec = { + pcm = st.pcm, + channels = 0, + sampleRate = 0, + blocks = st.blocks, + decode = function(self: Decoder, buf: buffer, offset: number?, length: number?): (number?, Err.Err?) + local off = offset or 0 + if type(buf) ~= "buffer" or off < 0 or off >= buffer.len(buf) then + return nil, Err.new(Err.ARG, "frame range out of the buffer") + end + local h = Ac3.header(buf, off, buffer.len(buf)) + if not h then + return nil, Err.new(Err.CORRUPT, "no AC-3 syncframe", off) + end + local n = h.frameSize + if length and length < n or off + n > buffer.len(buf) then + return nil, Err.new(Err.TRUNCATED, "truncated syncframe", off) + end + if checkCrc and Ac3.crc(buf, off + 2, n - 2) ~= 0 then + return nil, Err.new(Err.CHECKSUM, "syncframe CRC", off) + end + buffer.copy(scratch, 0, buf, off, n) + local frames, msg = Decode.frame(st, scratch, n, drc) + if not frames then + return nil, Err.from(msg, off) + end + self.pcm = st.pcm + self.channels = st.channels + self.sampleRate = h.sampleRate + return frames, nil + end, + reset = function(_self: Decoder) + Decode.reset(st) + end, + } + return dec +end + +return Ac3 diff --git a/src/Formats/codecs/audio/Adpcm/Decoder.luau b/src/Formats/codecs/audio/Adpcm/Decoder.luau new file mode 100644 index 0000000..291eac1 --- /dev/null +++ b/src/Formats/codecs/audio/Adpcm/Decoder.luau @@ -0,0 +1,328 @@ +--!strict +-- codecs/audio/Adpcm/Decoder: the streaming Decoder (Types.Decoder) over an ADPCM stream cut into packets, for the +-- formats whose state carries from packet to packet (ADX, VAG, BRSTM, raw IMA): codecs/audio/Stream.packets plus +-- exact seeking. The codec state (one buffer the packet decoder advances) is snapshotted at every packet start it +-- passes; a seek restores the snapshot, else the format's own state for that packet (BRSTM's ADPC history), else +-- decodes forward from the nearest earlier snapshot. New in formats-luau. +-- +-- local dec, err = Decoder.packets(dec, { -- dec: the Decoder table (sampleRate, channels, frames, ...) +-- count = n, packetFrames = 4096, -- packets of packetFrames frames (the last may be shorter) +-- frames = total, -- output frames +-- state = st, -- the codec state buffer decode advances +-- decode = function(i, out) return frames end, -- packet i (1-based) as interleaved f32 into out from 0 +-- restore = function(i) return false end, -- optional: set st for packet i, true if it could +-- }) +-- +-- The layouts the formats share, each returning the Decoder (dec gets read / seek / position) | nil, Err: +-- Decoder.interleaved(dec, spec) psx / adx / dsp frames (or s16 / s8 PCM), channels interleaved every +-- spec.interleave bytes (VAG, ADX, BRSTM / BCSTM / BFSTM, raw PS-ADPCM) +-- Decoder.nibbles(dec, spec) an IMA nibble stream, channels interleaved by nibble (raw IMA, KVAG) +-- Decoder.blocks(dec, spec) self-contained blocks: "ms" / "ima_wav" (blockAlign bytes), "ima_qt" (34 bytes +-- per channel), raw or inside AIFF-C / CAF +-- +-- Never throws (decode failures end the stream and land in dec.error, see codecs/audio/Stream). +local Err = require("@formats/core/Err") +local Stream = require("@formats/codecs/audio/Stream") +local Adpcm = require("@formats/codecs/audio/Adpcm") + +local Decoder = {} + +export type Spec = { + count: number, + packetFrames: number, + frames: number, + state: buffer, + decode: (i: number, out: buffer) -> (number?, Err.Err?), + restore: ((i: number) -> boolean)?, +} + +function Decoder.packets(dec: any, spec: Spec): (any, Err.Err?) + local ch = dec.channels + local pf = spec.packetFrames + local st = spec.state + local out = buffer.create(pf * ch * 4) + local decodeP = spec.decode + local restore = spec.restore + local snaps: { [number]: buffer } = {} + local nextPacket = 1 + local function snap(i: number) + if not snaps[i] then + local b = buffer.create(buffer.len(st)) + buffer.copy(b, 0, st) + snaps[i] = b + end + end + snap(1) + local function decode(i: number): (number?, Err.Err?) + if i ~= nextPacket then + if snaps[i] then + buffer.copy(st, 0, snaps[i]) + elseif restore and restore(i) then + -- the format set the state (BRSTM's seek table) + else + local j = i - 1 + while j > 1 and not snaps[j] do + j -= 1 + end + buffer.copy(st, 0, snaps[j]) + for k = j, i - 1 do + local n, e = decodeP(k, out) + if not n then + return nil, e + end + snap(k + 1) + end + end + end + local n, e = decodeP(i, out) + if n then + nextPacket = i + 1 + snap(i + 1) + end + return n, e + end + return Stream.packets(dec, { + count = spec.count, + start = function(i: number): number + return (i - 1) * pf + end, + decode = decode, + pcm = function(): buffer + return out + end, + reset = function() end, + stop = spec.frames, + }) +end + +-- ------------------------------------------------------------------------------------------------ layouts +local FRAME: { [string]: number } = { psx = 16, adx = 18, dsp = 8, s16be = 2, s16le = 2, s8 = 1 } -- bytes per frame +local SPF: { [string]: number } = { psx = 28, adx = 32, dsp = 14, s16be = 1, s16le = 1, s8 = 1 } -- samples per frame + +-- PCM samples of one channel into every ds-th float of dst from float d +local function pcm(kind: string, src: buffer, p: number, n: number, dst: buffer, d: number, ds: number) + if kind == "s8" then + for k = 0, n - 1 do + buffer.writef32(dst, (d + k * ds) * 4, buffer.readi8(src, p + k) / 128) + end + elseif kind == "s16le" then + for k = 0, n - 1 do + buffer.writef32(dst, (d + k * ds) * 4, buffer.readi16(src, p + k * 2) / 32768) + end + else + for k = 0, n - 1 do + local v = buffer.readu8(src, p + k * 2) * 256 + buffer.readu8(src, p + k * 2 + 1) + buffer.writef32(dst, (d + k * ds) * 4, (if v >= 32768 then v - 65536 else v) / 32768) + end + end +end + +export type InterleavedSpec = { + kind: "psx" | "adx" | "dsp" | "s16be" | "s16le" | "s8", -- ADPCM frames, or PCM samples laid out the same way + buf: buffer, + offset: number, -- the first row + size: number, -- data bytes (rows past it are cut; a truncated file decodes its whole frames) + interleave: number, -- bytes per channel per row (a multiple of the frame size; mono: any multiple) + lastInterleave: number?, -- bytes per channel in the last row (BRSTM's padded last block), default interleave + frames: number?, -- frames to output (default: what the data holds) + c1: number?, -- adx: the predictor (Adpcm.adxCoefs) + c2: number?, + v3: boolean?, -- adx: version 3 rounding + coefs: buffer?, -- dsp: 16 i32 per channel + hist: { number }?, -- initial history, h1 / h2 per channel (default 0) + restore: ((row: number, st: buffer) -> boolean)?, -- the exact history at the start of a row (BRSTM ADPC) +} + +-- interleaved(dec, spec) -> Decoder | nil, Err +function Decoder.interleaved(dec: any, spec: InterleavedSpec): (any, Err.Err?) + local ch = dec.channels + local kind = spec.kind + local fsize, spf = FRAME[kind], SPF[kind] + local il = spec.interleave + local last = spec.lastInterleave or il + if not fsize or ch < 1 or il < fsize or il % fsize ~= 0 or last < 0 or last > il then + return nil, Err.new(Err.CORRUPT, "bad interleave " .. tostring(il)) + end + local buf, base, size = spec.buf, spec.offset, spec.size + local rowBytes = il * ch + -- rows: the full ones, then the last (which may be shorter, and may be cut by a truncated file) + local rows = math.max(1, math.ceil(size / rowBytes)) + local function rowFrames(r: number): number -- the frames row r (0-based) holds whole in every channel + local width = if r == rows - 1 then last else il + -- channel c sits at c * width in the row: the last channel is the one a cut file shortens + local per = math.clamp(size - r * rowBytes - (ch - 1) * width, 0, width) + return (per // fsize) * spf + end + local fullFrames = (il // fsize) * spf + local total = (rows - 1) * fullFrames + rowFrames(rows - 1) + local frames = math.min(spec.frames or total, total) + local st = buffer.create(8 * ch) + if spec.hist then + for c = 0, ch - 1 do + buffer.writei32(st, c * 8, spec.hist[c * 2 + 1] or 0) + buffer.writei32(st, c * 8 + 4, spec.hist[c * 2 + 2] or 0) + end + end + local rowsPer = if spec.restore then 1 else math.max(1, 4096 // fullFrames) + local pf = rowsPer * fullFrames + local c1, c2, v3, coefs = spec.c1 or 0, spec.c2 or 0, spec.v3 == true, spec.coefs + local restore = spec.restore + dec.frames = frames + dec.duration = frames / dec.sampleRate + return Decoder.packets(dec, { + count = math.max(1, math.ceil(frames / pf)), + packetFrames = pf, + frames = frames, + state = st, + restore = if restore + then function(i: number): boolean + return restore(i - 1, st) + end + else nil, + decode = function(i: number, out: buffer): (number?, Err.Err?) + local got = 0 + for r = (i - 1) * rowsPer, math.min(i * rowsPer, rows) - 1 do + local n = math.min(rowFrames(r), frames - r * fullFrames) + if n <= 0 then + break + end + local nf = math.ceil(n / spf) + local width = if r == rows - 1 then last else il + for c = 0, ch - 1 do + local p = base + r * rowBytes + c * width + local d = got * ch + c + if kind == "psx" then + Adpcm.psx(buf, p, fsize, nf, st, c * 8, out, d, ch) + elseif kind == "adx" then + Adpcm.adx(buf, p, fsize, nf, c1, c2, v3, st, c * 8, out, d, ch) + elseif kind == "dsp" then + Adpcm.dsp(buf, p, n, coefs :: buffer, c * 64, st, c * 8, out, d, ch) + else + pcm(kind, buf, p, n, out, d, ch) + end + end + got += n + end + return got, nil + end, + }) +end + +export type NibbleSpec = { + buf: buffer, + offset: number, + size: number, -- bytes + hi: boolean?, -- the high nibble first (DVI / KVAG); default low first + frames: number?, -- default: every whole frame of nibbles +} + +-- nibbles(dec, spec): an IMA stream starting from predictor 0, step index 0, channel c in nibbles c, c + ch, ... +function Decoder.nibbles(dec: any, spec: NibbleSpec): (any, Err.Err?) + local ch = dec.channels + local buf, base = spec.buf, spec.offset + local frames = math.min(spec.frames or math.huge, (spec.size * 2) // ch) + local st = buffer.create(8 * ch) + local hi = spec.hi == true + dec.frames = frames + dec.duration = frames / dec.sampleRate + return Decoder.packets(dec, { + count = math.max(1, math.ceil(frames / 4096)), + packetFrames = 4096, + frames = frames, + state = st, + decode = function(i: number, out: buffer): (number?, Err.Err?) + local f0 = (i - 1) * 4096 + local n = math.min(4096, frames - f0) + for c = 0, ch - 1 do + Adpcm.ima(buf, base, f0 * ch + c, ch, n, hi, st, c * 8, out, c, ch) + end + return n, nil + end, + }) +end + +export type BlockSpec = { + kind: "ms" | "ima_wav" | "ima_qt", + buf: buffer, + offset: number, + size: number, + blockAlign: number?, -- ms / ima_wav: bytes per block + frames: number?, -- default: what the blocks hold + coefs: { number }?, -- ms: coefficient pairs, flat (default the 7 standard pairs) +} + +-- blockFrames(kind, blockAlign, ch) -> frames per block, or nil when the block cannot hold the headers +function Decoder.blockFrames(kind: string, ba: number, ch: number): number? + if kind == "ima_qt" then + return 64 + elseif kind == "ms" then + return if ba >= 7 * ch then (ba - 7 * ch) * 2 // ch + 2 else nil + end + return if ba >= 4 * ch then (ba - 4 * ch) * 2 // ch + 1 else nil +end + +-- blocks(dec, spec): self-contained ADPCM blocks (no state across blocks); a truncated last block decodes what it has +function Decoder.blocks(dec: any, spec: BlockSpec): (any, Err.Err?) + local ch = dec.channels + local kind = spec.kind + local ba = if kind == "ima_qt" then 34 * ch else spec.blockAlign or 0 + local spb = Decoder.blockFrames(kind, ba, ch) + if not spb then + return nil, Err.new(Err.CORRUPT, "block of " .. ba .. " bytes is too small") + end + if spb * ch > 2 ^ 20 then + return nil, Err.new(Err.LIMIT, "ADPCM block too large") + end + local buf, base, size = spec.buf, spec.offset, spec.size + local full = size // ba + local rest = size - full * ba + local total = full * spb + if kind ~= "ima_qt" and rest > 0 then + -- a partial last block: the frames it holds whole + if kind == "ms" then + total += if rest >= 7 * ch then math.min(spb, 2 + ((rest - 7 * ch) * 2) // ch) else 0 + elseif rest >= 4 * ch then + total += math.min(spb, 1 + ((rest - 4 * ch) // (4 * ch)) * 8) + end + end + local frames = math.min(spec.frames or total, total) + local ncoef = 7 + local cf = spec.coefs + if cf and #cf >= 2 then + ncoef = math.min(256, #cf // 2) + end + local coefs = buffer.create(ncoef * 8) + for k = 0, ncoef - 1 do + buffer.writei32(coefs, k * 8, if cf and #cf >= 2 then cf[k * 2 + 1] else Adpcm.MS_COEF1[k + 1]) + buffer.writei32(coefs, k * 8 + 4, if cf and #cf >= 2 then cf[k * 2 + 2] else Adpcm.MS_COEF2[k + 1]) + end + local scratch = buffer.create(20 * ch) + dec.frames = frames + dec.duration = frames / dec.sampleRate + dec.blockAlign = ba + dec.samplesPerBlock = spb + return Decoder.packets(dec, { + count = math.max(1, math.ceil(frames / spb)), + packetFrames = spb, + frames = frames, + state = scratch, + decode = function(i: number, out: buffer): (number?, Err.Err?) + local off = base + (i - 1) * ba + local avail = math.min(ba, base + size - off) + if kind == "ms" then + return Adpcm.msBlock(buf, off, avail, ch, spb, out, 0, coefs, ncoef, scratch), nil + elseif kind == "ima_wav" then + return Adpcm.imaWav(buf, off, avail, ch, spb, out, 0), nil + end + if avail < ba then + return 0, nil + end + for c = 0, ch - 1 do + Adpcm.imaQt(buf, off + c * 34, scratch, c * 8, out, c, ch) + end + return 64, nil + end, + }) +end + +return Decoder diff --git a/src/Formats/codecs/audio/Adpcm/init.luau b/src/Formats/codecs/audio/Adpcm/init.luau new file mode 100644 index 0000000..9741805 --- /dev/null +++ b/src/Formats/codecs/audio/Adpcm/init.luau @@ -0,0 +1,707 @@ +--!strict +--!native +--!optimize 2 +-- codecs/audio/Adpcm: the 4-bit ADPCM family, decode (and encode where it is cheap). New in formats-luau; the IMA and +-- MS block decoders moved here from audio/wav/Codecs (wav-luau, same author). ADX coefficients, PS-ADPCM and Nintendo +-- DSP decoding follow vgmstream r2117 (ISC licence, licenses/vgmstream-LICENSE.txt) so the output is bit-exact with it: +-- the ADX scale + 1 and the version 3 rounding, PS-ADPCM's float filter (exact in integers below 2^17), DSP's 1024 +-- rounding. Codec kernels only: the formats (wav, aiff, caf, adx, vag, brstm, adpcm, ...) walk the layouts. +-- +-- Decoders write f32 (sample / 32768) to dst at float index d, every ds floats (interleaving), and keep their running +-- state in a caller-owned buffer `st` at byte offset `so` (i32 pairs: IMA pred / step index, the others hist1 / hist2), +-- so a decoder can stop between calls and snapshot the state for seeking (codecs/audio/Adpcm/Decoder). +-- +-- Adpcm.ima(src, p, q0, qs, count, hi, st, so, dst, d, ds) -- IMA nibbles: count samples, nibble q0, q0+qs, ... +-- Adpcm.imaQt(src, p, st, so, dst, d, ds) -- Apple ima4: one 34-byte packet -> 64 samples +-- Adpcm.imaWav(src, off, avail, ch, spb, dst, d) -> frames -- Microsoft IMA block (WAV / AVI) +-- Adpcm.msBlock(src, off, avail, ch, spb, dst, d, coefs, ncoef, st) -> frames -- MS ADPCM block +-- Adpcm.adx(src, p, pstride, nframes, c1, c2, v3, st, so, dst, d, ds) -- CRI ADX: 18-byte frames, 32 samples +-- Adpcm.adxCoefs(cutoff, rate) -> c1, c2 +-- Adpcm.psx(src, p, pstride, nframes, st, so, dst, d, ds) -- Sony PS-ADPCM (VAG): 16-byte frames, 28 samples +-- Adpcm.dsp(src, p, count, coefs, co, st, so, dst, d, ds) -- Nintendo DSP: 8-byte frames, 14 samples +-- Adpcm.modplug(src, p, count, dst, d) -- ModPlug ADPCM (XM / MOD samples) +-- encoders: imaEncode, imaWavEncode, msEncode, adxEncode, psxEncode, dspEncode (see each) +-- +-- Every function reads only the bytes its arguments describe: the caller checks the ranges (byte counts per call are +-- documented on each). Never throws. +local readu8, readi16, readu16, readi32 = buffer.readu8, buffer.readi16, buffer.readu16, buffer.readi32 +local writef32, readf32, writei32, writeu8, writeu16 = buffer.writef32, buffer.readf32, buffer.writei32, buffer.writeu8, buffer.writeu16 +local band, rshift, bor, lshift = bit32.band, bit32.rshift, bit32.bor, bit32.lshift +local floor = math.floor + +local Adpcm = {} + +-- ------------------------------------------------------------------------------------------------ IMA +local IMA_STEP = { + 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, + 130, 143, 157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, 876, 963, 1060, + 1166, 1282, 1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358, 5894, 6484, + 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767, +} +local IMA_ADJ = { -1, -1, -1, -1, 2, 4, 6, 8, -1, -1, -1, -1, 2, 4, 6, 8 } +-- IMA_DIFF[index * 8 + (nibble & 7) + 1]: the shift-and-add difference (step/8 + bits of step/4, step/2, step), as +-- the IMA reference computes it (not (2n + 1) * step / 8, which rounds differently) +local IMA_DIFF = table.create(89 * 8, 0) +-- IMA_NEXT[index * 16 + nibble + 1]: the next step index +local IMA_NEXT = table.create(89 * 16, 0) +for i = 0, 88 do + local step = IMA_STEP[i + 1] + for n = 0, 7 do + local d = rshift(step, 3) + if band(n, 1) ~= 0 then + d += rshift(step, 2) + end + if band(n, 2) ~= 0 then + d += rshift(step, 1) + end + if band(n, 4) ~= 0 then + d += step + end + IMA_DIFF[i * 8 + n + 1] = d + end + for n = 0, 15 do + IMA_NEXT[i * 16 + n + 1] = math.clamp(i + IMA_ADJ[n + 1], 0, 88) + end +end +Adpcm.IMA_STEP = IMA_STEP + +-- ima: `count` samples of one channel from a nibble stream at byte p: nibble q0, q0 + qs, q0 + 2 qs, ... (nibble q is +-- in byte p + q // 2, the low half first unless hi). State: st[so] predictor, st[so + 4] step index. Reads bytes +-- p .. p + (q0 + (count - 1) * qs) // 2. +function Adpcm.ima(src: buffer, p: number, q0: number, qs: number, count: number, hi: boolean, st: buffer, so: number, + dst: buffer, d: number, ds: number) + local pred = readi32(st, so) + local index = math.clamp(readi32(st, so + 4), 0, 88) + local q = q0 + local o = d * 4 + local os = ds * 4 + for _ = 1, count do + local b = readu8(src, p + rshift(q, 1)) + local nib + if (band(q, 1) == 0) == hi then + nib = rshift(b, 4) + else + nib = band(b, 15) + end + local diff = IMA_DIFF[index * 8 + band(nib, 7) + 1] + if nib >= 8 then + pred -= diff + if pred < -32768 then + pred = -32768 + end + else + pred += diff + if pred > 32767 then + pred = 32767 + end + end + index = IMA_NEXT[index * 16 + nib + 1] + writef32(dst, o, pred / 32768) + o += os + q += qs + end + writei32(st, so, pred) + writei32(st, so + 4, index) +end + +-- imaQt: one Apple ima4 packet (34 bytes at p: a big-endian header, the predictor's top 9 bits and the 7-bit step +-- index, then 64 nibbles low first) -> 64 samples. Apple's decoders keep the running full-precision predictor while +-- the header agrees with it (the same step index, the predictor within 127): st carries it from packet to packet +-- (zeros before the first). +function Adpcm.imaQt(src: buffer, p: number, st: buffer, so: number, dst: buffer, d: number, ds: number) + local h = readu8(src, p) * 256 + readu8(src, p + 1) + local pred = band(h, 0xFF80) + if pred >= 32768 then + pred -= 65536 + end + local index = band(h, 0x7F) + if index ~= readi32(st, so + 4) or math.abs(pred - readi32(st, so)) > 0x7F then + writei32(st, so, pred) + writei32(st, so + 4, index) + end + Adpcm.ima(src, p + 2, 0, 1, 64, false, st, so, dst, d, ds) +end + +-- imaWav: one Microsoft IMA ADPCM block (WAV / AVI) at src[off]: per channel a 4-byte header (s16 predictor = the +-- first sample, u8 step index, pad), then groups of 4 bytes (8 nibbles, low first) per channel in turn. avail: the +-- bytes present (a truncated last block decodes the whole groups it has). Writes interleaved frames to dst from float +-- index d; returns the frame count (<= spb). +function Adpcm.imaWav(src: buffer, off: number, avail: number, ch: number, spb: number, dst: buffer, d: number): number + if avail < 4 * ch then + return 0 + end + local groups = (avail - 4 * ch) // (4 * ch) + local frames = math.min(spb, 1 + groups * 8) + local o = d * 4 + for c = 0, ch - 1 do + local pred = readi16(src, off + c * 4) + local index = math.min(readu8(src, off + c * 4 + 2), 88) + writef32(dst, o + c * 4, pred / 32768) + local f = 1 + local g = 0 + while f < frames do + local p = off + 4 * ch + (g * ch + c) * 4 + local k = 0 + while k < 8 and f < frames do + local b = readu8(src, p + rshift(k, 1)) + local nib = if band(k, 1) == 0 then band(b, 15) else rshift(b, 4) + local diff = IMA_DIFF[index * 8 + band(nib, 7) + 1] + if nib >= 8 then + pred -= diff + if pred < -32768 then + pred = -32768 + end + else + pred += diff + if pred > 32767 then + pred = 32767 + end + end + index = IMA_NEXT[index * 16 + nib + 1] + writef32(dst, o + (f * ch + c) * 4, pred / 32768) + f += 1 + k += 1 + end + g += 1 + end + end + return frames +end + +-- ------------------------------------------------------------------------------------------------ MS ADPCM +local MS_ADAPT = { 230, 230, 230, 230, 307, 409, 512, 614, 768, 614, 512, 409, 307, 230, 230, 230 } +Adpcm.MS_COEF1 = { 256, 512, 0, 192, 240, 460, 392 } +Adpcm.MS_COEF2 = { 0, -256, 0, 64, 0, -208, -232 } + +-- msBlock: one MS ADPCM block: per channel u8 predictor index, s16 delta, s16 sample 1, s16 sample 2 (each field for +-- every channel in turn), then nibbles high first, channels interleaved per nibble. coefs: i32 pairs (coef1, coef2) x +-- ncoef (256 = 1.0). state: 20 * ch bytes of scratch. avail: the bytes present. Writes interleaved frames to dst from +-- float index d; returns the frame count (<= spb). +function Adpcm.msBlock(src: buffer, off: number, avail: number, ch: number, spb: number, dst: buffer, d: number, + coefs: buffer, ncoef: number, state: buffer): number + local hdr = 7 * ch + if avail < hdr or ncoef < 1 then + return 0 + end + local frames = math.min(spb, 2 + ((avail - hdr) * 2) // ch) + local o = d * 4 + for c = 0, ch - 1 do + local pi = math.min(readu8(src, off + c), ncoef - 1) + local idelta = readi16(src, off + ch + c * 2) + local s1 = readi16(src, off + 3 * ch + c * 2) + local s2 = readi16(src, off + 5 * ch + c * 2) + local so = c * 20 + writei32(state, so, readi32(coefs, pi * 8)) + writei32(state, so + 4, readi32(coefs, pi * 8 + 4)) + writei32(state, so + 8, idelta) + writei32(state, so + 12, s1) + writei32(state, so + 16, s2) + writef32(dst, o + c * 4, s2 / 32768) + if frames > 1 then + writef32(dst, o + (ch + c) * 4, s1 / 32768) + end + end + local total = (frames - 2) * ch + for k = 0, total - 1 do + local b = readu8(src, off + hdr + rshift(k, 1)) + local nib = if band(k, 1) == 0 then rshift(b, 4) else band(b, 15) + local so = (k % ch) * 20 + local c1, c2 = readi32(state, so), readi32(state, so + 4) + local idelta = readi32(state, so + 8) + local s1, s2 = readi32(state, so + 12), readi32(state, so + 16) + local p = s1 * c1 + s2 * c2 + p = if p >= 0 then p // 256 else -((-p) // 256) + p += (if nib >= 8 then nib - 16 else nib) * idelta + if p > 32767 then + p = 32767 + elseif p < -32768 then + p = -32768 + end + idelta = (MS_ADAPT[nib + 1] * idelta) // 256 + if idelta < 16 then + idelta = 16 + elseif idelta > 2796202 then -- INT_MAX / 768 + idelta = 2796202 + end + writei32(state, so + 8, idelta) + writei32(state, so + 12, p) + writei32(state, so + 16, s1) + writef32(dst, o + (2 * ch + k) * 4, p / 32768) + end + return frames +end + +-- ------------------------------------------------------------------------------------------------ CRI ADX +local F32 = buffer.create(4) +local function f32(x: number): number + writef32(F32, 0, x) + return readf32(F32, 0) +end + +-- adxCoefs(cutoff, rate) -> coef1, coef2 (fixed point, 12 fractional bits): the 2-pole high-pass predictor from the +-- header's cutoff frequency, in single precision as CRI's decoders (and vgmstream) compute it +function Adpcm.adxCoefs(cutoff: number, rate: number): (number, number) + if rate <= 0 then + return 0, 0 + end + local z = f32(math.cos(f32(2 * math.pi * cutoff / rate))) + local a = f32(math.sqrt(2) - z) + local b = f32(math.sqrt(2) - 1) + local c = f32(f32(a - f32(math.sqrt(f32(f32(a + b) * f32(a - b))))) / b) + local c1 = c * 8192 + local c2 = f32(c * c) * -4096 + c1 = if c1 >= 0 then floor(c1) else -floor(-c1) + c2 = if c2 >= 0 then floor(c2) else -floor(-c2) + return c1, c2 +end + +-- adx: nframes 18-byte frames of one channel (s16 big-endian scale, 32 nibbles high first), pstride bytes apart from +-- p. v3: the version 3 rounding (each product shifted on its own). A scale of 0x8001 (CRI's end marker) decodes as +-- silence. Reads p .. p + (nframes - 1) * pstride + 17; writes 32 * nframes samples. +function Adpcm.adx(src: buffer, p: number, pstride: number, nframes: number, c1: number, c2: number, v3: boolean, + st: buffer, so: number, dst: buffer, d: number, ds: number) + local h1, h2 = readi32(st, so), readi32(st, so + 4) + local o = d * 4 + local os = ds * 4 + for f = 0, nframes - 1 do + local fp = p + f * pstride + local scale = readu8(src, fp) * 256 + readu8(src, fp + 1) + if scale == 0x8001 then + scale = 0 + elseif scale >= 32768 then + scale -= 65535 -- the signed value + 1 + else + scale += 1 + end + for k = 0, 31 do + local b = readu8(src, fp + 2 + rshift(k, 1)) + local n = if band(k, 1) == 0 then rshift(b, 4) else band(b, 15) + if n >= 8 then + n -= 16 + end + local s + if v3 then + s = n * scale + (c1 * h1) // 4096 + (c2 * h2) // 4096 + else + s = n * scale + (c1 * h1 + c2 * h2) // 4096 + end + if s > 32767 then + s = 32767 + elseif s < -32768 then + s = -32768 + end + h2 = h1 + h1 = s + writef32(dst, o, s / 32768) + o += os + end + end + writei32(st, so, h1) + writei32(st, so + 4, h2) +end + +-- ------------------------------------------------------------------------------------------------ PS-ADPCM +local PSX1 = { 0, 60, 115, 98, 122 } +local PSX2 = { 0, 0, -52, -55, -60 } + +-- the filter term (c1 * h1 + c2 * h2) / 64 * 256 truncated, as vgmstream's single-precision float code computes it: +-- exact in integers while the products fit a float's 24 bits +local function psxPred(f: number, h1: number, h2: number): number + local x = PSX1[f] * h1 + PSX2[f] * h2 + if h1 > -65536 and h1 < 65536 and h2 > -65536 and h2 < 65536 then + return 4 * x + end + local v = f32(f32(f32(PSX1[f] / 64) * h1) + f32(f32(PSX2[f] / 64) * h2)) * 256 + return if v >= 0 then floor(v) else -floor(-v) +end + +-- psx: nframes 16-byte frames of one channel (filter << 4 | shift, flags, 28 nibbles low first), pstride bytes apart +-- from p. Filters past 4 decode as 0 and shifts past 12 as 9 (as vgmstream); a frame with flags 7 is silence. The +-- history keeps the unclipped value. Reads p .. p + (nframes - 1) * pstride + 15; writes 28 * nframes samples. +function Adpcm.psx(src: buffer, p: number, pstride: number, nframes: number, st: buffer, so: number, dst: buffer, + d: number, ds: number) + local h1, h2 = readi32(st, so), readi32(st, so + 4) + local o = d * 4 + local os = ds * 4 + for f = 0, nframes - 1 do + local fp = p + f * pstride + local head = readu8(src, fp) + local filter = rshift(head, 4) + local shift = band(head, 15) + if filter > 4 then + filter = 0 + end + if shift > 12 then + shift = 9 + end + local mul = 2 ^ (20 - shift) + local fi = filter + 1 + local silent = band(readu8(src, fp + 1), 15) == 7 + for k = 0, 27 do + local s = 0 + if not silent then + local b = readu8(src, fp + 2 + rshift(k, 1)) + local n = if band(k, 1) == 0 then band(b, 15) else rshift(b, 4) + if n >= 8 then + n -= 16 + end + s = (n * mul + psxPred(fi, h1, h2)) // 256 + end + h2 = h1 + h1 = s + if s > 32767 then + s = 32767 + elseif s < -32768 then + s = -32768 + end + writef32(dst, o, s / 32768) + o += os + end + end + writei32(st, so, h1) + writei32(st, so + 4, h2) +end + +-- ------------------------------------------------------------------------------------------------ Nintendo DSP +-- dsp: count samples of one channel from 8-byte frames at p (predictor << 4 | scale shift, 14 nibbles high first). +-- coefs: 16 i32 at byte co (8 pairs, 11 fractional bits); a predictor index past 7 uses pair 7. Reads p .. +-- p + ceil(count / 14) * 8 - 1. +function Adpcm.dsp(src: buffer, p: number, count: number, coefs: buffer, co: number, st: buffer, so: number, + dst: buffer, d: number, ds: number) + local h1, h2 = readi32(st, so), readi32(st, so + 4) + local o = d * 4 + local os = ds * 4 + local done = 0 + local fp = p + while done < count do + local head = readu8(src, fp) + local pi = math.min(rshift(head, 4), 7) + local scale = 2 ^ band(head, 15) * 2048 + local c1, c2 = readi32(coefs, co + pi * 8), readi32(coefs, co + pi * 8 + 4) + local n14 = math.min(14, count - done) + for k = 0, n14 - 1 do + local b = readu8(src, fp + 1 + rshift(k, 1)) + local n = if band(k, 1) == 0 then rshift(b, 4) else band(b, 15) + if n >= 8 then + n -= 16 + end + local s = (n * scale + 1024 + c1 * h1 + c2 * h2) // 2048 + if s > 32767 then + s = 32767 + elseif s < -32768 then + s = -32768 + end + h2 = h1 + h1 = s + writef32(dst, o, s / 32768) + o += os + end + done += n14 + fp += 8 + end + writei32(st, so, h1) + writei32(st, so + 4, h2) +end + +-- ------------------------------------------------------------------------------------------------ encoders +-- the nearest s16 to x * 32768 (NaN -> 0) +local function toS16(x: number): number + local v = floor(x * 32768 + 0.5) + if v ~= v then + return 0 + elseif v > 32767 then + return 32767 + elseif v < -32768 then + return -32768 + end + return v +end +Adpcm.toS16 = toS16 + +-- the IMA nibble for x from (pred, index): the one whose decoded value lands nearest (greedy, all 16 tried) +local function imaNibble(x: number, pred: number, index: number): number + local base = index * 8 + 1 + local best, bestErr = 0, math.huge + for m = 0, 7 do + local diff = IMA_DIFF[base + m] + local up = math.min(pred + diff, 32767) + local e = math.abs(x - up) + if e < bestErr then + best, bestErr = m, e + end + local down = math.max(pred - diff, -32768) + e = math.abs(x - down) + if e < bestErr then + best, bestErr = m + 8, e + end + end + return best +end + +-- imaEncode: count samples of one channel, f32 at float index xi every xs floats of x, into nibbles q0, q0 + qs, ... +-- of out at byte p (the other half of each byte is kept). State as Adpcm.ima. Writes bytes p .. +-- p + (q0 + (count - 1) * qs) // 2. +function Adpcm.imaEncode(x: buffer, xi: number, xs: number, count: number, st: buffer, so: number, out: buffer, + p: number, q0: number, qs: number, hi: boolean) + local pred = readi32(st, so) + local index = math.clamp(readi32(st, so + 4), 0, 88) + local q = q0 + for i = 0, count - 1 do + local v = toS16(readf32(x, (xi + i * xs) * 4)) + local nib = imaNibble(v, pred, index) + local diff = IMA_DIFF[index * 8 + band(nib, 7) + 1] + pred = if nib >= 8 then math.max(pred - diff, -32768) else math.min(pred + diff, 32767) + index = IMA_NEXT[index * 16 + nib + 1] + local bp = p + rshift(q, 1) + local b = readu8(out, bp) + if (band(q, 1) == 0) == hi then + b = bor(band(b, 0x0F), lshift(nib, 4)) + else + b = bor(band(b, 0xF0), nib) + end + writeu8(out, bp, b) + q += qs + end + writei32(st, so, pred) + writei32(st, so + 4, index) +end + +-- imaWavEncode: one Microsoft IMA block of spb frames (spb = 1 + 8k) from interleaved f32 x at frame xf (frames +-- available: n; the rest is padded with the last sample) to out[off] (4 * ch + (spb - 1) / 2 * ch bytes). st: 8 * ch +-- bytes carrying the step index from block to block. +function Adpcm.imaWavEncode(x: buffer, xf: number, n: number, ch: number, spb: number, st: buffer, out: buffer, off: number) + local groups = (spb - 1) // 8 + for c = 0, ch - 1 do + local so = c * 8 + local first = if n > 0 then toS16(readf32(x, (xf * ch + c) * 4)) else 0 + writei32(st, so, first) + local index = math.clamp(readi32(st, so + 4), 0, 88) + writei32(st, so + 4, index) + buffer.writei16(out, off + c * 4, first) + writeu8(out, off + c * 4 + 2, index) + writeu8(out, off + c * 4 + 3, 0) + local pred = first + for g = 0, groups - 1 do + local gp = off + 4 * ch + (g * ch + c) * 4 + for k = 0, 7 do + local f = 1 + g * 8 + k + local v = if f < n then toS16(readf32(x, ((xf + f) * ch + c) * 4)) else pred + local nib = imaNibble(v, pred, index) + local diff = IMA_DIFF[index * 8 + band(nib, 7) + 1] + pred = if nib >= 8 then math.max(pred - diff, -32768) else math.min(pred + diff, 32767) + index = IMA_NEXT[index * 16 + nib + 1] + local bp = gp + rshift(k, 1) + if band(k, 1) == 0 then + writeu8(out, bp, nib) + else + writeu8(out, bp, bor(readu8(out, bp), lshift(nib, 4))) + end + end + end + writei32(st, so + 4, index) + end +end + +-- one MS ADPCM channel run for the encoder: the nibbles for samples 2 .. n - 1 with predictor (c1, c2) and the first +-- delta; returns the squared error and the nibbles in nibs (when given) +local function msTrial(xs: { number }, n: number, c1: number, c2: number, delta0: number, nibs: { number }?): number + local s1, s2 = xs[2], xs[1] + local idelta = delta0 + local err = 0 + for i = 3, n do + local p = s1 * c1 + s2 * c2 + p = if p >= 0 then p // 256 else -((-p) // 256) + local e = xs[i] - p + local nib = if e >= 0 then (e + idelta // 2) // idelta else -((-e + idelta // 2) // idelta) + nib = math.clamp(nib, -8, 7) + local v = math.clamp(p + nib * idelta, -32768, 32767) + err += (xs[i] - v) * (xs[i] - v) + if nibs then + nibs[i] = band(nib, 15) + end + idelta = math.clamp((MS_ADAPT[band(nib, 15) + 1] * idelta) // 256, 16, 2796202) + s2 = s1 + s1 = v + end + return err +end + +-- msEncode: one MS ADPCM block of spb frames (standard 7 coefficient pairs) from interleaved f32 x at frame xf +-- (frames available: n; the rest is padded with silence) to out[off] (7 * ch + (spb - 2) * ch / 2 bytes). Each channel +-- takes the predictor with the least error. +function Adpcm.msEncode(x: buffer, xf: number, n: number, ch: number, spb: number, out: buffer, off: number) + local C1, C2 = Adpcm.MS_COEF1, Adpcm.MS_COEF2 + local xs = table.create(spb, 0) + local nibs = table.create(spb, 0) + local all = table.create(spb * ch, 0) + for c = 0, ch - 1 do + for i = 1, spb do + xs[i] = if i <= n then toS16(readf32(x, ((xf + i - 1) * ch + c) * 4)) else 0 + end + -- the first delta from the first steps + local sum = 0 + for i = 3, math.min(spb, 10) do + sum += math.abs(xs[i] - xs[i - 1]) + end + local delta0 = math.clamp(sum // 16, 16, 32767) + local best, bestErr = 1, math.huge + for k = 1, 7 do + local e = msTrial(xs, spb, C1[k], C2[k], delta0, nil) + if e < bestErr then + best, bestErr = k, e + end + end + msTrial(xs, spb, C1[best], C2[best], delta0, nibs) + writeu8(out, off + c, best - 1) + writeu16(out, off + ch + c * 2, delta0) + buffer.writei16(out, off + 3 * ch + c * 2, xs[2] or 0) + buffer.writei16(out, off + 5 * ch + c * 2, xs[1]) + for i = 3, spb do + all[(i - 3) * ch + c + 1] = nibs[i] + end + end + local total = (spb - 2) * ch + for k = 0, total - 1, 2 do + writeu8(out, off + 7 * ch + k // 2, all[k + 1] * 16 + (all[k + 2] or 0)) + end +end + +-- one ADX frame for the encoder: the squared error of encoding xs[1..32] with scale from (h1, h2) (v4 rounding), and +-- the nibbles in nibs when given; returns the error and the new history +local function adxTrial(xs: { number }, scale: number, c1: number, c2: number, h1: number, h2: number, nibs: { number }?): (number, number, number) + local err = 0 + for k = 1, 32 do + local pred = (c1 * h1 + c2 * h2) // 4096 + local e = xs[k] - pred + local n = if e >= 0 then (e + scale // 2) // scale else -((-e + scale // 2) // scale) + n = math.clamp(n, -8, 7) + local s = math.clamp(n * scale + pred, -32768, 32767) + err += (xs[k] - s) * (xs[k] - s) + if nibs then + nibs[k] = band(n, 15) + end + h2 = h1 + h1 = s + end + return err, h1, h2 +end + +-- adxEncode: count samples of one channel (f32 at float index xi every xs floats of x) as ceil(count / 32) ADX frames +-- (v4 rounding, the scale stored minus one as CRI's decoders add it back) at out[p], pstride bytes apart; the frame +-- past count is padded with silence. State as Adpcm.adx. +function Adpcm.adxEncode(x: buffer, xi: number, xs: number, count: number, c1: number, c2: number, st: buffer, so: number, + out: buffer, p: number, pstride: number) + local h1, h2 = readi32(st, so), readi32(st, so + 4) + local v = table.create(32, 0) + local nibs = table.create(32, 0) + for f = 0, (count + 31) // 32 - 1 do + local peak = 0 + local a, b = h1, h2 + for k = 1, 32 do + local i = f * 32 + k - 1 + local s = if i < count then toS16(readf32(x, (xi + i * xs) * 4)) else 0 + v[k] = s + peak = math.max(peak, math.abs(s - (c1 * a + c2 * b) // 4096)) + b = a + a = s + end + -- the scale that covers the open-loop residual peak, and a few around it, closed loop + local base = math.max(1, (peak + 6) // 7) + local best, bestErr = base, math.huge + for _, m in { 1, 0.75, 1.25, 0.5, 1.6 } do + local sc = math.clamp(floor(base * m + 0.5), 1, 0x7FFF) + local e = adxTrial(v, sc, c1, c2, h1, h2, nil) + if e < bestErr then + best, bestErr = sc, e + end + end + local _, n1, n2 = adxTrial(v, best, c1, c2, h1, h2, nibs) + h1, h2 = n1, n2 + local fp = p + f * pstride + writeu8(out, fp, rshift(best - 1, 8)) + writeu8(out, fp + 1, band(best - 1, 255)) + for k = 0, 15 do + writeu8(out, fp + 2 + k, nibs[k * 2 + 1] * 16 + nibs[k * 2 + 2]) + end + end + writei32(st, so, h1) + writei32(st, so + 4, h2) +end + +-- psxEncode: count samples of one channel (f32 at float index xi every xs floats of x) as ceil(count / 28) PS-ADPCM +-- frames at out[p], pstride bytes apart, flags byte 0 (the caller sets loop / end flags); every filter and shift is +-- tried per frame against Adpcm.psx's decoding, the least squared error wins. State as Adpcm.psx. +function Adpcm.psxEncode(x: buffer, xi: number, xs: number, count: number, st: buffer, so: number, out: buffer, + p: number, pstride: number) + local h1, h2 = readi32(st, so), readi32(st, so + 4) + local v = table.create(28, 0) + local nibs = table.create(28, 0) + for f = 0, (count + 27) // 28 - 1 do + for k = 1, 28 do + local i = f * 28 + k - 1 + v[k] = if i < count then toS16(readf32(x, (xi + i * xs) * 4)) else 0 + end + local bestErr, bestHead = math.huge, 0 + for fi = 1, 5 do + for shift = 0, 12 do + local mul = 2 ^ (20 - shift) + local a, b = h1, h2 + local err = 0 + for k = 1, 28 do + local pred = psxPred(fi, a, b) + local n = floor((v[k] * 256 - pred) / mul + 0.5) + n = if n > 7 then 7 elseif n < -8 then -8 else n + local s = (n * mul + pred) // 256 + local c = if s > 32767 then 32767 elseif s < -32768 then -32768 else s + err += (v[k] - c) * (v[k] - c) + if err >= bestErr then + break + end + b = a + a = s + end + if err < bestErr then + bestErr, bestHead = err, (fi - 1) * 16 + shift + end + end + end + -- the winner again, for its nibbles and history + local fi, shift = rshift(bestHead, 4) + 1, band(bestHead, 15) + local mul = 2 ^ (20 - shift) + for k = 1, 28 do + local pred = psxPred(fi, h1, h2) + local n = math.clamp(floor((v[k] * 256 - pred) / mul + 0.5), -8, 7) + nibs[k] = band(n, 15) + h2 = h1 + h1 = (n * mul + pred) // 256 + end + local fp = p + f * pstride + writeu8(out, fp, bestHead) + writeu8(out, fp + 1, 0) + for k = 0, 13 do + writeu8(out, fp + 2 + k, nibs[k * 2 + 1] + nibs[k * 2 + 2] * 16) + end + end + writei32(st, so, h1) + writei32(st, so + 4, h2) +end + +-- ------------------------------------------------------------------------------------------------ ModPlug +-- modplug: ModPlug / OpenMPT ADPCM samples (XM / MOD sample data marked 0xAD): a table of 16 signed byte deltas at +-- p, then count nibbles (low first) at p + 16, each adding its table delta to a running signed byte (wrapping). +-- Writes count f32 (value / 128) to dst from float index d. Reads p .. p + 16 + ceil(count / 2) - 1. +function Adpcm.modplug(src: buffer, p: number, count: number, dst: buffer, d: number) + local tab = table.create(16, 0) + for k = 0, 15 do + tab[k + 1] = buffer.readi8(src, p + k) + end + local v = 0 + for i = 0, count - 1 do + local b = readu8(src, p + 16 + rshift(i, 1)) + local nib = if band(i, 1) == 0 then band(b, 15) else rshift(b, 4) + v = (v + tab[nib + 1] + 128) % 256 - 128 + writef32(dst, (d + i) * 4, v / 128) + end +end + +return Adpcm diff --git a/src/Formats/codecs/audio/Ape/Decode.luau b/src/Formats/codecs/audio/Ape/Decode.luau new file mode 100644 index 0000000..5b9ebee --- /dev/null +++ b/src/Formats/codecs/audio/Ape/Decode.luau @@ -0,0 +1,778 @@ +--!strict +--!native +--!optimize 2 +-- codecs/audio/Ape/Decode: one Monkey's Audio frame -> samples. Ported from the Monkey's Audio SDK 13.28 (Matthew T. +-- Ashland, BSD 3-clause, licenses/monkeys-audio-LICENSE.txt): UnBitArray.cpp (the range coder and its value model, +-- 3.99+) and Old/UnBitArrayOld.cpp (CUnBitArray3891To3989, the 3.95 - 3.98 model), NNFilter / NNFilterCommon.h (the +-- neural-net filters of the normal .. insane levels), NewPredictor.cpp (CPredictorDecompress3950toCurrent, its int32 +-- and int64 flavours), ScaledFirstOrderFilter.h, Prepare.cpp (Unprepare: X / Y -> channels), APEDecompressCore.cpp +-- (special frames, the frame CRC) and FloatTransform.cpp. Never throws: returns nil, message. +local Crc32 = require("@formats/core/Crc32") + +local readu8, readu32, writeu32, byteswap = buffer.readu8, buffer.readu32, buffer.writeu32, bit32.byteswap +local writeu8, writei16, writeu16, writei32, readf32 = buffer.writeu8, buffer.writei16, buffer.writeu16, buffer.writei32, buffer.readf32 +local readi16, readi32 = buffer.readi16, buffer.readi32 +local band, bor, bnot, rshift, lshift, bxor = bit32.band, bit32.bor, bit32.bnot, bit32.rshift, bit32.lshift, bit32.bxor +local sign = math.sign + +local Decode = {} + +local TWO31, TWO32 = 2147483648, 4294967296 +local PAD = 64 + +-- the range coder's symbol models (UnBitArrayBase.h) +local RT1 = { 0, 14824, 28224, 39348, 47855, 53994, 58171, 60926, 62682, 63786, 64463, 64878, 65126, 65276, 65365, 65419, 65450, 65469, 65480, 65487, 65491, 65493, 65494, 65495, 65496, 65497, 65498, 65499, 65500, 65501, 65502, 65503, 65504, 65505, 65506, 65507, 65508, 65509, 65510, 65511, 65512, 65513, 65514, 65515, 65516, 65517, 65518, 65519, 65520, 65521, 65522, 65523, 65524, 65525, 65526, 65527, 65528, 65529, 65530, 65531, 65532, 65533, 65534, 65535, 65536 } +local RT2 = { 0, 19578, 36160, 48417, 56323, 60899, 63265, 64435, 64971, 65232, 65351, 65416, 65447, 65466, 65476, 65482, 65485, 65488, 65490, 65491, 65492, 65493, 65494, 65495, 65496, 65497, 65498, 65499, 65500, 65501, 65502, 65503, 65504, 65505, 65506, 65507, 65508, 65509, 65510, 65511, 65512, 65513, 65514, 65515, 65516, 65517, 65518, 65519, 65520, 65521, 65522, 65523, 65524, 65525, 65526, 65527, 65528, 65529, 65530, 65531, 65532, 65533, 65534, 65535, 65536 } +local KMIN = { 0, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432, 67108864, 134217728, 268435456, 536870912, 1073741824, 2147483648, 0, 0, 0, 0, 0 } + +-- symbol(total) lookup buffers (RangeOverflowTable), built on first use +local OVT: { [number]: buffer } = {} +local function overflowTable(rt: { number }): buffer + local t = OVT[rt[2]] + if t then + return t + end + t = buffer.create(65536) + local o = 0 + for z = 0, 65535 do + if z >= rt[o + 2] then + o += 1 + end + writeu8(t, z, o) + end + OVT[rt[2]] = t + return t +end + +local function wrap32(v: number): number + if v >= TWO31 or v < -TWO31 then + return (v + TWO31) % TWO32 - TWO31 + end + return v +end + +-- C integer division by 2 (toward zero) +local function half(v: number): number + return if v >= 0 then v // 2 else -((-v) // 2) +end + +export type Filter = { order: number, shift: number, M: buffer, I: buffer, D: buffer } +export type State = { + version: number, + bits: number, + channels: number, + filters: { Filter }, -- per level, applied last to first on decode (as m_spNNFilter2, 1, 0) + V: { { number } }, -- per channel: the frame's values through the stages + S: buffer, -- the frame bytes, word-swapped (+ PAD zeros) + crcbuf: buffer, + scratch: buffer, + lastX: number, + rc: Rc, +} + +local FILTERS: { [number]: { number } } = { -- level -> { order, shift, ... } in m_spNNFilter, 1, 2 order + [1000] = {}, + [2000] = { 16, 11 }, + [3000] = { 64, 11 }, + [4000] = { 256, 13, 32, 10 }, + [5000] = { 1280, 15, 256, 13, 16, 11 }, +} + +-- state(version, level, bits, channels) -> State | nil, message +function Decode.state(version: number, level: number, bits: number, channels: number): (State?, string?) + local spec = FILTERS[level] + if not spec then + return nil, "unsupported: compression level " .. level + end + local filters: { Filter } = {} + for k = 1, #spec, 2 do + local order = spec[k] + local es = if bits >= 32 then 4 else 2 + table.insert(filters, { + order = order, + shift = spec[k + 1], + M = buffer.create(order * es), + I = buffer.create((512 + order + 1) * es), + D = buffer.create((512 + order + 1) * es), + }) + end + local V = {} + for c = 1, channels do + V[c] = {} + end + return { + version = version, + bits = bits, + channels = channels, + filters = filters, + V = V, + S = buffer.create(1024), + crcbuf = buffer.create(1024), + scratch = buffer.create(4), + lastX = 0, + rc = { q = 0, low = 0, range = 0, prev = 0 }, + }, nil +end + +-- ------------------------------------------------------------------------------------------------ entropy +-- the range coder as a record (the 3.95 - 3.98 model's RangeDecodeFastWithUpdate) +type Rc = { q: number, low: number, range: number, prev: number } +local function rcBits(rc: Rc, S: buffer, nb: number): number + local q, low, range, prev = rc.q, rc.low, rc.range, rc.prev + while range <= 8388608 do + local byte = readu8(S, q) + q += 1 + low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) + prev = byte + range *= 256 + end + range = range // 2 ^ nb + local r = 0 + if range > 0 then + r = low // range + low %= range + end + rc.q, rc.low, rc.range, rc.prev = q, low, range, prev + return r +end + +-- values(st, q, n, order, old) -> q | nil, message: n blocks of range-coded values into st.V[c] for the channels of +-- `order` (decode order), from byte q of st.S (the range coder starts there) +local function values(st: State, q: number, lim: number, n: number, order: { number }, old: boolean): (number?, string?) + local S = st.S + local V = st.V + local version = st.version + -- FlushBitArray: a dummy byte, then the first byte + local prev = readu8(S, q + 1) + q += 2 + local low = rshift(prev, 1) + local range = 128 + local nch = #order + local ksum = table.create(nch, 16384) + local kk = table.create(nch, 10) + local ovt = overflowTable(if old then RT1 else RT2) + local RT = if old then RT1 else RT2 + for b = 1, n do + for ci = 1, nch do + if q > lim then + return nil, "overrun" + end + local ks = ksum[ci] + local value + -- the overflow symbol (RangeDecodeFast(16) + the model) + while range <= 8388608 do + local byte = readu8(S, q) + q += 1 + low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) + prev = byte + range *= 256 + end + range = range // 65536 + local total = low // range + if total >= 65536 then + return nil, "bad range code" + end + local ov = readu8(ovt, total) + low -= range * RT[ov + 1] + range *= RT[ov + 2] - RT[ov + 1] + if not old then + local pivot = math.max(ks // 32, 1) + while ov == 63 do + -- escape: 32 bits of overflow (two 16-bit range decodes); 1 = the overflow signal + local r = 0 + for _ = 1, 2 do + while range <= 8388608 do + local byte = readu8(S, q) + q += 1 + low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) + prev = byte + range *= 256 + end + range = range // 65536 + if range == 0 then + return nil, "bad range code" + end + r = r * 65536 + low // range + low %= range + end + ov = r + if ov == 1 then + pivot = 32768 + while range <= 8388608 do + local byte = readu8(S, q) + q += 1 + low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) + prev = byte + range *= 256 + end + range = range // 65536 + total = low // range + if total >= 65536 then + return nil, "bad range code" + end + ov = readu8(ovt, total) + low -= range * RT[ov + 1] + range *= RT[ov + 2] - RT[ov + 1] + else + break + end + end + local base + if pivot >= 65536 then + local pbits = 0 + while pivot // 2 ^ pbits > 0 do + pbits += 1 + end + local split = 2 ^ (if pbits >= 16 then pbits - 16 else 0) + local pa = pivot // split + 1 + while range <= 8388608 do + local byte = readu8(S, q) + q += 1 + low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) + prev = byte + range *= 256 + end + range = range // pa + local ba = low // range + low %= range + while range <= 8388608 do + local byte = readu8(S, q) + q += 1 + low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) + prev = byte + range *= 256 + end + range = range // split + local bb = low // range + low %= range + base = ba * split + bb + else + while range <= 8388608 do + local byte = readu8(S, q) + q += 1 + low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) + prev = byte + range *= 256 + end + range = range // pivot + base = low // range + low %= range + end + value = base + ov * pivot + else + -- 3.95 - 3.98: k bits (escape: k in 5 bits) + local rc = st.rc + rc.q, rc.low, rc.range, rc.prev = q, low, range, prev + local k + if ov == 63 then + k = rcBits(rc, S, 5) + ov = 0 + else + k = math.max(kk[ci] - 1, 0) + end + if k <= 16 or version < 3910 then + value = rcBits(rc, S, k) + else + local x1 = rcBits(rc, S, 16) + value = x1 + rcBits(rc, S, k - 16) * 65536 + end + value += ov * 2 ^ k + q = rc.q + low = rc.low + range = rc.range + prev = rc.prev + end + ks = (ks + (value + 1) // 2 - (ks + 16) // 32) % TWO32 + ksum[ci] = ks + if old then + local k = kk[ci] + if ks < KMIN[k + 1] then + kk[ci] = k - 1 + elseif KMIN[k + 2] ~= 0 and ks >= KMIN[k + 2] then + kk[ci] = k + 1 + end + end + V[order[ci]][b] = if value % 2 == 1 then (value - 1) // 2 + 1 else -(value // 2) + end + end + return q, nil +end + +-- ------------------------------------------------------------------------------------------------ NN filters +-- ((v >> s) & m) ~= 0 for an int64 v (s given as 2^s) +local function negBit(v: number, p2: number, m: number): boolean + return band((v // p2) % TWO32, m) ~= 0 +end + +-- the int16 dot product of the weights and the inputs from byte b (span bytes) +local function dot16(M: buffer, I: buffer, b: number, span: number): number + local dot = 0 + for k = 0, span - 16, 16 do + local bb = b + k + dot += readi16(I, bb) * readi16(M, k) + readi16(I, bb + 2) * readi16(M, k + 2) + + readi16(I, bb + 4) * readi16(M, k + 4) + readi16(I, bb + 6) * readi16(M, k + 6) + + readi16(I, bb + 8) * readi16(M, k + 8) + readi16(I, bb + 10) * readi16(M, k + 10) + + readi16(I, bb + 12) * readi16(M, k + 12) + readi16(I, bb + 14) * readi16(M, k + 14) + end + return dot +end + +-- the same, adapting each weight after its use: M += D * dm (int16, wrapping) +local function dotAdapt16(M: buffer, I: buffer, D: buffer, b: number, span: number, dm: number): number + local dot = 0 + for k = 0, span - 8, 8 do + local bb = b + k + local m0, m1, m2, m3 = readi16(M, k), readi16(M, k + 2), readi16(M, k + 4), readi16(M, k + 6) + dot += readi16(I, bb) * m0 + readi16(I, bb + 2) * m1 + readi16(I, bb + 4) * m2 + readi16(I, bb + 6) * m3 + writei16(M, k, m0 + readi16(D, bb) * dm) + writei16(M, k + 2, m1 + readi16(D, bb + 2) * dm) + writei16(M, k + 4, m2 + readi16(D, bb + 4) * dm) + writei16(M, k + 6, m3 + readi16(D, bb + 6) * dm) + end + return dot +end + +-- one CNNFilter over n values of v, in place (DecompressGeneric). The weights, inputs and deltas live in buffers of +-- the C types (int16 for 8 - 24-bit files, int32 for 32-bit ones: `wide`), so the weights wrap as the C shorts do +local function nnFilter(f: Filter, v: { number }, n: number, newDelta: boolean, wide: boolean) + local order, M, I, D = f.order, f.M, f.I, f.D + local es = if wide then 4 else 2 + local shift = 2 ^ f.shift + local round = shift // 2 + buffer.fill(M, 0, 0, order * es) + buffer.fill(I, 0, 0, (order + 1) * es) + buffer.fill(D, 0, 0, (order + 1) * es) + local p = order -- the current element (0-based); its history is p - order .. p - 1 + local total = 512 + order + local avg = 0 + local span = order * 2 + for t = 1, n do + local x = v[t] + local dm = -sign(x) -- the weights move by +delta when x < 0, -delta when x > 0 + local dot = 0 + if wide then + local b = (p - order) * 4 + for k = 0, order * 4 - 4, 4 do + local m = readi32(M, k) + local pr = readi32(I, b + k) * m + if pr >= TWO31 or pr < -TWO31 then + pr = (pr + TWO31) % TWO32 - TWO31 + end + dot += pr + if dm ~= 0 then + writei32(M, k, m + readi32(D, b + k) * dm) + end + end + else + local b = (p - order) * 2 + dot = if dm == 0 then dot16(M, I, b, span) else dotAdapt16(M, I, D, b, span, dm) + dot = wrap32(dot) + end + local o = x + (dot + round) // shift + if not wide then + o = wrap32(o) + end + local d = 0 + local a = if o < 0 then -o else o + if newDelta then + if a > avg * 3 then + d = if (if wide then negBit(o, 33554432, 64) else o < 0) then 32 else -32 + elseif a > (avg * 4) // 3 then + d = if (if wide then negBit(o, 67108864, 32) else o < 0) then 16 else -16 + elseif a > 0 then + d = if (if wide then negBit(o, 134217728, 16) else o < 0) then 8 else -8 + end + local dd = a - avg + avg += if dd >= 0 then dd // 16 else -((-dd) // 16) + else + d = if o == 0 then 0 elseif o < 0 then 4 else -4 + end + local sat = if o > 32767 then 32767 elseif o < -32768 then -32768 else o + if wide then + local q = p * 4 + writei32(D, q, d) + if newDelta then + writei32(D, q - 4, readi32(D, q - 4) // 2) + writei32(D, q - 8, readi32(D, q - 8) // 2) + else + writei32(D, q - 16, readi32(D, q - 16) // 2) + end + writei32(D, q - 32, readi32(D, q - 32) // 2) + writei32(I, q, sat) + else + local q = p * 2 + writei16(D, q, d) + if newDelta then + writei16(D, q - 2, readi16(D, q - 2) // 2) + writei16(D, q - 4, readi16(D, q - 4) // 2) + else + writei16(D, q - 8, readi16(D, q - 8) // 2) + end + writei16(D, q - 16, readi16(D, q - 16) // 2) + writei16(I, q, sat) + end + v[t] = o + p += 1 + if p == total then + buffer.copy(I, 0, I, (p - order) * es, order * es) + buffer.copy(D, 0, D, (p - order) * es, order * es) + p = order + end + end +end + +-- ------------------------------------------------------------------------------------------------ predictor +-- the adapt sign of a 32-bit file's int64 prediction value: ((v >> 30) & 2) - 1, or 0 +local function adaptWide(v: number): number + if v == 0 then + return 0 + end + return if (v // 1073741824) % 4 >= 2 then 1 else -1 +end + +-- predict(st, a, b?, n) : CPredictorDecompress3950toCurrent over channel a's values (nB = channel b's outputs of the +-- block, or 0), single-channel form; stereo uses predictStereo +local function predictOne(st: State, v: { number }, n: number) + local wide = st.bits >= 32 + local lastA, prevA0, A1, A2, A3 = 0, 0, 0, 0, 0 + local MA0, MA1, MA2, MA3 = 360, 317, -109, 98 + local stage = 0 + for t = 1, n do + local nA = v[t] + local A0 = lastA + A3 = A2 + A2 = A1 + A1 = A0 - prevA0 + prevA0 = A0 + local predA = A0 * MA0 + A1 * MA1 + A2 * MA2 + A3 * MA3 + local cur + if wide then + cur = nA + predA // 1024 + else + cur = wrap32(nA + wrap32(predA) // 1024) + end + local s = sign(nA) + if s ~= 0 then + if wide then + s = -s + MA0 += adaptWide(A0) * s + MA1 += adaptWide(A1) * s + MA2 += adaptWide(A2) * s + MA3 += adaptWide(A3) * s + else + MA0 += sign(A0) * s + MA1 += sign(A1) * s + MA2 += sign(A2) * s + MA3 += sign(A3) * s + end + end + stage = wrap32(cur + (stage * 31) // 32) + lastA = cur + v[t] = stage + end +end + +-- the stereo predictors: Y = P1(nY, last X), X = P0(nX, Y); X into V[1], Y into V[2] +local function predictStereo(st: State, X: { number }, Y: { number }, n: number) + local wide = st.bits >= 32 + -- predictor 1 (Y) + local yLast, yPrev, yA1, yA2, yA3 = 0, 0, 0, 0, 0 + local yBin, yBprev, yB1, yB2, yB3, yB4 = 0, 0, 0, 0, 0, 0 + local yMA0, yMA1, yMA2, yMA3 = 360, 317, -109, 98 + local yMB0, yMB1, yMB2, yMB3, yMB4 = 0, 0, 0, 0, 0 + local yStage = 0 + -- predictor 0 (X) + local xLast, xPrev, xA1, xA2, xA3 = 0, 0, 0, 0, 0 + local xBin, xBprev, xB1, xB2, xB3, xB4 = 0, 0, 0, 0, 0, 0 + local xMA0, xMA1, xMA2, xMA3 = 360, 317, -109, 98 + local xMB0, xMB1, xMB2, xMB3, xMB4 = 0, 0, 0, 0, 0 + local xStage = 0 + local lastX = 0 + for t = 1, n do + -- Y + local nA = Y[t] + local A0 = yLast + yA3 = yA2 + yA2 = yA1 + yA1 = A0 - yPrev + yPrev = A0 + local B0 = lastX - (yBin * 31) // 32 + yBin = lastX + yB4 = yB3 + yB3 = yB2 + yB2 = yB1 + yB1 = B0 - yBprev + yBprev = B0 + local predA = A0 * yMA0 + yA1 * yMA1 + yA2 * yMA2 + yA3 * yMA3 + local predB = B0 * yMB0 + yB1 * yMB1 + yB2 * yMB2 + yB3 * yMB3 + yB4 * yMB4 + local cur + if wide then + cur = nA + (predA + predB // 2) // 1024 + else + cur = wrap32(nA + wrap32(wrap32(predA) + wrap32(predB) // 2) // 1024) + end + local s = sign(nA) + if s ~= 0 then + if wide then + s = -s + yMA0 += adaptWide(A0) * s + yMA1 += adaptWide(yA1) * s + yMA2 += adaptWide(yA2) * s + yMA3 += adaptWide(yA3) * s + yMB0 += adaptWide(B0) * s + yMB1 += adaptWide(yB1) * s + yMB2 += adaptWide(yB2) * s + yMB3 += adaptWide(yB3) * s + yMB4 += adaptWide(yB4) * s + else + yMA0 += sign(A0) * s + yMA1 += sign(yA1) * s + yMA2 += sign(yA2) * s + yMA3 += sign(yA3) * s + yMB0 += sign(B0) * s + yMB1 += sign(yB1) * s + yMB2 += sign(yB2) * s + yMB3 += sign(yB3) * s + yMB4 += sign(yB4) * s + end + end + yStage = wrap32(cur + (yStage * 31) // 32) + yLast = cur + local yv = yStage + -- X + nA = X[t] + A0 = xLast + xA3 = xA2 + xA2 = xA1 + xA1 = A0 - xPrev + xPrev = A0 + B0 = yv - (xBin * 31) // 32 + xBin = yv + xB4 = xB3 + xB3 = xB2 + xB2 = xB1 + xB1 = B0 - xBprev + xBprev = B0 + predA = A0 * xMA0 + xA1 * xMA1 + xA2 * xMA2 + xA3 * xMA3 + predB = B0 * xMB0 + xB1 * xMB1 + xB2 * xMB2 + xB3 * xMB3 + xB4 * xMB4 + if wide then + cur = nA + (predA + predB // 2) // 1024 + else + cur = wrap32(nA + wrap32(wrap32(predA) + wrap32(predB) // 2) // 1024) + end + s = sign(nA) + if s ~= 0 then + if wide then + s = -s + xMA0 += adaptWide(A0) * s + xMA1 += adaptWide(xA1) * s + xMA2 += adaptWide(xA2) * s + xMA3 += adaptWide(xA3) * s + xMB0 += adaptWide(B0) * s + xMB1 += adaptWide(xB1) * s + xMB2 += adaptWide(xB2) * s + xMB3 += adaptWide(xB3) * s + xMB4 += adaptWide(xB4) * s + else + xMA0 += sign(A0) * s + xMA1 += sign(xA1) * s + xMA2 += sign(xA2) * s + xMA3 += sign(xA3) * s + xMB0 += sign(B0) * s + xMB1 += sign(xB1) * s + xMB2 += sign(xB2) * s + xMB3 += sign(xB3) * s + xMB4 += sign(xB4) * s + end + end + xStage = wrap32(cur + (xStage * 31) // 32) + xLast = cur + lastX = xStage + X[t], Y[t] = xStage, yv + end +end + +-- ------------------------------------------------------------------------------------------------ frame +-- frame(st, buf, at, rem, stop, n, P, float) -> n | nil, message: the frame whose words start at byte `at` (its first +-- byte at at + rem), reading at most up to `stop`; n blocks into P (interleaved integers, or floats when float); cut: +-- the data ends at `stop` before the frame does (a running-over decode is then "truncated", else corrupt) +function Decode.frame(st: State, buf: buffer, at: number, rem: number, stop: number, n: number, P: { number }, float: boolean, cut: boolean): (number?, string?) + local C, bits = st.channels, st.bits + local len = math.max(0, stop - at) + local words = (len + 3) // 4 + local S = st.S + if buffer.len(S) < words * 4 + PAD then + S = buffer.create(words * 4 + PAD + 4096) + st.S = S + end + buffer.fill(S, 0, 0, words * 4 + PAD) + -- the bit array: 32-bit little-endian words read MSB first + for w = 0, words - 1 do + local o = at + w * 4 + if o + 4 <= stop then + writeu32(S, w * 4, byteswap(readu32(buf, o))) + else + for k = 0, 3 do + if o + k < stop then + writeu8(S, w * 4 + 3 - k, readu8(buf, o + k)) + end + end + end + end + local function u32be(q: number): number + return readu8(S, q) * 16777216 + readu8(S, q + 1) * 65536 + readu8(S, q + 2) * 256 + readu8(S, q + 3) + end + local q = rem + if q + 16 > words * 4 + PAD then + return nil, "truncated frame" + end + local stored = u32be(q) + q += 4 + local special = 0 + if st.version > 3820 then + if stored >= TWO31 then + special = u32be(q) + q += 4 + end + stored %= TWO31 + end + -- the values + local V = st.V + local order: { number } + local mode -- "silence", "pseudo", "stereo", "mono", "multi" + if C == 1 then + if band(special, 1) ~= 0 then + mode = "silence" + order = {} + else + mode = "mono" + order = { 1 } + end + elseif C == 2 then + if band(special, 3) == 3 then + mode = "silence" + order = {} + elseif band(special, 4) ~= 0 then + mode = "pseudo" + order = { 1 } + else + mode, order = "stereo", { 2, 1 } + end + else + mode = "multi" + order = {} + for c = 1, C do + order[c] = c + end + end + local lim = words * 4 + PAD - 40 + if #order > 0 then + local qe = values(st, q, lim, n, order, st.version < 3990) + if not qe or qe > words * 4 + 8 then + return nil, if cut then "truncated frame" else "bad frame: the values run over its data" + end + -- the NN filters (last level first), then the predictors + local newDelta = st.version >= 3980 + local filters = st.filters + for _, c in order do + for f = #filters, 1, -1 do + nnFilter(filters[f], V[c], n, newDelta, bits >= 32) + end + end + if mode == "stereo" then + predictStereo(st, V[1], V[2], n) + else + for _, c in order do + predictOne(st, V[c], n) + end + end + end + -- Unprepare: values -> channels, the CRC over the output bytes as the WAV holds them + local bps = bits // 8 + local cb = st.crcbuf + if buffer.len(cb) < n * C * bps then + cb = buffer.create(n * C * bps + 1024) + st.crcbuf = cb + end + local paired: { [number]: boolean } = {} -- first channel (0-based) of an X / Y pair + if C == 2 and mode == "stereo" then + paired[0] = true + elseif C == 4 and (bits == 16 or bits == 24) then + paired[0], paired[2] = true, true + elseif C >= 6 and (bits == 16 or bits == 24) then + paired[0], paired[4] = true, true + if C >= 8 then + paired[6] = true + end + end + local o = 0 + local mono = mode == "mono" or mode == "pseudo" + local X = V[1] + for t = 1, n do + local base = (t - 1) * C + local c = 0 + while c < C do + local a: number, b2: number = 0, 0 + local pair = paired[c] + if mode == "silence" then + a = 0 + b2 = 0 + elseif mono then + a = X[t] + b2 = a + elseif pair then + local x, y = V[c + 1][t], V[c + 2][t] + a = x - half(y) + b2 = a + y + else + a = V[c + 1][t] + end + local width = if pair or (C == 2) then 2 else 1 + for k = 0, width - 1 do + local s: number = if k == 0 then a else b2 + if bits == 16 then + if s < -32768 or s > 32767 then + return nil, "sample out of range" + end + writei16(cb, o, s) + o += 2 + elseif bits == 8 then + s = (s + 128) % 256 - 128 + writeu8(cb, o, s + 128) + o += 1 + elseif bits == 24 then + s = (s + 8388608) % 16777216 - 8388608 + local u = s % 16777216 + writeu16(cb, o, u % 65536) + writeu8(cb, o + 2, u // 65536) + o += 3 + else + s = wrap32(s) + writei32(cb, o, s) + o += 4 + end + P[base + c + k + 1] = s + end + c += width + end + end + local crc = Crc32.of(cb, 0, o) + if crc // 2 ~= stored then + return nil, "checksum: frame CRC mismatch" + end + if float then + local sc = st.scratch + for k = 1, n * C do + local u = P[k] % TWO32 + local out = bor(band(u, 0xC3FFFFFF), bxor(bnot(band(u, 0x3C000000)), 0xC3FFFFFF)) + if out >= TWO31 then + out = bor(bnot(out), 0x80000000) + end + writeu32(sc, 0, out) + P[k] = readf32(sc, 0) + end + end + return n, nil +end + +return Decode diff --git a/src/Formats/codecs/audio/Ape/init.luau b/src/Formats/codecs/audio/Ape/init.luau new file mode 100644 index 0000000..91faa36 --- /dev/null +++ b/src/Formats/codecs/audio/Ape/init.luau @@ -0,0 +1,229 @@ +--!strict +-- codecs/audio/Ape: the Monkey's Audio codec (.ape). A codec (layer 3). Ported from the Monkey's Audio SDK 13.28 +-- (Matthew T. Ashland, BSD 3-clause since v10, licenses/monkeys-audio-LICENSE.txt): APEHeader.cpp (the descriptor / +-- header / seek table, and the pre-3.98 header), APEInfo / APEDecompress.cpp (frame bytes and alignment); the frame +-- decoder is codecs/audio/Ape/Decode. Supports file versions 3.95 and later (3.99+ as the current encoder writes; the +-- 3.95 - 3.98 range coder model is ported but has no reference fixture), every compression level (fast, normal, high, +-- extra high, insane), 8 / 16 / 24 / 32-bit integer and 32-bit float, 1 - 32 channels, special frames (silence, +-- pseudo stereo) and the frame CRC. Not supported: versions before 3.95 (UNSUPPORTED), the "interim" 24-bit +-- re-decode for files of the 32-bit era before 8.50, big-endian / signed 8-bit source flags (the samples are returned +-- as numbers either way). +-- +-- local info, err = Ape.info(buf, base, limit) -- header facts + the frame table +-- local dec = Ape.decoder(info) +-- local n, err = dec:frame(buf, i) -- frame i (1-based) -> dec.pcm (interleaved; integers, or floats) +-- +-- Never throws: bad data returns nil, Err. +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Decode = require("@formats/codecs/audio/Ape/Decode") + +local Ape = {} + +export type Info = { + version: number, -- file version * 1000 (3990) + programVersion: number, -- 13280 (0 when not stored) + level: number, -- 1000 (fast) .. 5000 (insane) + flags: number, + channels: number, + sampleRate: number, + bitsPerSample: number, + float: boolean, + blocksPerFrame: number, + finalFrameBlocks: number, + totalFrames: number, + totalBlocks: number, + frameStart: { number }, -- byte offset of each frame + firstFrame: number, -- byte offset of frame 1 (the word alignment origin) + dataEnd: number, -- the end of the frame data + limit: number, -- the end of the file data (frames past it are truncated) + md5: string?, +} + +local FLAG_8, FLAG_24, FLAG_PEAK, FLAG_SEEKN, FLAG_WAVHDR, FLAG_FLOAT = 1, 8, 4, 16, 32, 4096 + +-- find(buf, base, limit) -> the offset of "MAC " / "MACF" (after an ID3v2 tag) | nil +function Ape.find(buf: buffer, base: number, limit: number): number? + local at = base + if limit - at >= 10 and buffer.readstring(buf, at, 3) == "ID3" then + local size = 0 + for i = 6, 9 do + size = size * 128 + bit32.band(buffer.readu8(buf, at + i), 127) + end + local footer = bit32.band(buffer.readu8(buf, at + 5), 16) ~= 0 + at += size + (if footer then 20 else 10) + if not footer then + while at < limit and buffer.readu8(buf, at) == 0 do + at += 1 + end + end + end + if at + 4 > limit then + return nil + end + local id = buffer.readstring(buf, at, 4) + if id == "MAC " or id == "MACF" then + return at + end + local s = buffer.readstring(buf, at, math.min(limit - at, 1048576)) + local k = string.find(s, "MAC ", 1, true) + return if k then at + k - 1 else nil +end + +-- info(buf, base, limit) -> Info | nil, Err +function Ape.info(buf: buffer, base: number, limit: number): (Info?, Err.Err?) + local at = Ape.find(buf, base, limit) + if not at then + return nil, Err.new(Err.CORRUPT, "no Monkey's Audio header") + end + local junk = at - base -- seek offsets count from the start of the APE data (after any junk / ID3v2) + local r = Bytes.reader(buf, at, limit - at) + r:skip(4) + local version = r:u16le() + if r.err then + return nil, r.err + end + if version < 3950 then + return nil, Err.new(Err.UNSUPPORTED, "Monkey's Audio file version " .. version .. " (3950 and later are supported)") + end + local info: any = { version = version, programVersion = 0 } + local seekCount, seekAt + if version >= 3980 then + info.programVersion = r:u16le() + local descBytes, headBytes, seekBytes, hdrDataBytes = r:u32le(), r:u32le(), r:u32le(), r:u32le() + local dataLo, dataHi, termBytes = r:u32le(), r:u32le(), r:u32le() + local md5 = r:string(16) + r:seek(descBytes) + info.level = r:u16le() + info.flags = r:u16le() + info.blocksPerFrame = r:u32le() + info.finalFrameBlocks = r:u32le() + info.totalFrames = r:u32le() + info.bitsPerSample = r:u16le() + info.channels = r:u16le() + info.sampleRate = r:u32le() + if r.err then + return nil, r.err + end + seekAt = at + descBytes + headBytes + seekCount = seekBytes // 4 + info.dataEnd = seekAt + seekBytes + hdrDataBytes + dataLo + dataHi * 4294967296 + local _ = termBytes + local hex = table.create(16, "") + local any = false + for k = 1, 16 do + local b = string.byte(md5, k) + any = any or b ~= 0 + hex[k] = string.format("%02x", b) + end + info.md5 = if any then table.concat(hex) else nil + else + info.level = r:u16le() + info.flags = r:u16le() + info.channels = r:u16le() + info.sampleRate = r:u32le() + local headerBytes = r:u32le() + r:u32le() -- terminating bytes + info.totalFrames = r:u32le() + info.finalFrameBlocks = r:u32le() + if bit32.band(info.flags, FLAG_PEAK) ~= 0 then + r:skip(4) + end + seekCount = info.totalFrames + if bit32.band(info.flags, FLAG_SEEKN) ~= 0 then + seekCount = r:u32le() + end + if bit32.band(info.flags, FLAG_WAVHDR) == 0 then + r:skip(headerBytes) + end + if r.err then + return nil, r.err + end + info.blocksPerFrame = 73728 * 4 + info.bitsPerSample = if bit32.band(info.flags, FLAG_8) ~= 0 then 8 elseif bit32.band(info.flags, FLAG_24) ~= 0 then 24 else 16 + seekAt = r:tell() + info.dataEnd = limit + end + local C, bits = info.channels, info.bitsPerSample + if C < 1 or C > 32 then + return nil, Err.new(Err.CORRUPT, "bad channel count " .. C) + end + if bits ~= 8 and bits ~= 16 and bits ~= 24 and bits ~= 32 then + return nil, Err.new(Err.UNSUPPORTED, bits .. "-bit samples") + end + if info.sampleRate < 1 or info.blocksPerFrame < 1 or info.blocksPerFrame > 10000000 or info.finalFrameBlocks > info.blocksPerFrame then + return nil, Err.new(Err.CORRUPT, "bad header") + end + if info.totalFrames < 1 then + return nil, Err.new(Err.CORRUPT, "no frames") + end + info.float = bit32.band(info.flags, FLAG_FLOAT) ~= 0 and bits == 32 + info.totalBlocks = (info.totalFrames - 1) * info.blocksPerFrame + info.finalFrameBlocks + if seekCount < info.totalFrames or seekAt + seekCount * 4 > limit then + return nil, Err.new(Err.TRUNCATED, "the seek table is incomplete") + end + local starts = table.create(info.totalFrames, 0) + local add, prev = 0, 0 + for i = 1, info.totalFrames do + local v = buffer.readu32(buf, seekAt + (i - 1) * 4) + if v < prev then + add += 4294967296 + end + prev = v + starts[i] = base + junk + add + v + end + for i = 1, info.totalFrames do + if starts[i] < base or (i > 1 and starts[i] < starts[i - 1]) then + return nil, Err.new(Err.CORRUPT, "bad seek table entry " .. i) + end + end + info.frameStart = starts + info.firstFrame = starts[1] + info.dataEnd = math.min(math.max(info.dataEnd, starts[info.totalFrames]), limit) + info.limit = limit + return info :: Info, nil +end + +-- ------------------------------------------------------------------------------------------------ decoder +export type Decoder = { + info: Info, + pcm: { number }, + frame: (self: Decoder, buf: buffer, i: number) -> (number?, Err.Err?), + state: Decode.State, +} + +local function frame(self: Decoder, buf: buffer, i: number): (number?, Err.Err?) + local info = self.info + if i < 1 or i > info.totalFrames then + return nil, Err.new(Err.ARG, "no frame " .. i) + end + local start = info.frameStart[i] + local rem = (start - info.firstFrame) % 4 + local want = (if i < info.totalFrames then info.frameStart[i + 1] else info.dataEnd) + 4 + local stop = math.min(want, info.limit, buffer.len(buf)) + if start + 8 > stop then + return nil, Err.new(Err.TRUNCATED, "frame " .. i .. " is past the end of the data", start) + end + local n = if i < info.totalFrames then info.blocksPerFrame else info.finalFrameBlocks + local n2, msg = Decode.frame(self.state, buf, start - rem, rem, stop, n, self.pcm, info.float, stop < want - 4) + if not n2 then + return nil, Err.from(msg, start) + end + return n2, nil +end + +-- decoder(info) -> Decoder | nil, Err +function Ape.decoder(info: Info): (Decoder?, Err.Err?) + local st, msg = Decode.state(info.version, info.level, info.bitsPerSample, info.channels) + if not st then + return nil, Err.from(msg) + end + return { + info = info, + pcm = table.create(math.min(info.blocksPerFrame, 1048576) * info.channels, 0), + frame = frame, + state = st, + }, nil +end + +return Ape diff --git a/src/Formats/codecs/audio/ApeTag.luau b/src/Formats/codecs/audio/ApeTag.luau new file mode 100644 index 0000000..259bdcf --- /dev/null +++ b/src/Formats/codecs/audio/ApeTag.luau @@ -0,0 +1,110 @@ +--!strict +-- codecs/audio/ApeTag: APEv1 / APEv2 tags (the tag block of Monkey's Audio, WavPack, Musepack, TTA, OptimFROG and +-- some MP3s) -> Types.Tags. Written from the APEv2 specification (wiki.hydrogenaud.io "APEv2 specification"); no +-- third-party code. A tag sits at the end of the file (before an optional ID3v1 tag) as items + a 32-byte footer +-- "APETAGEX", with an optional 32-byte header in front (APEv2). Item keys become lower case tag keys (Year -> date, +-- Track -> track, Album Artist -> albumartist, Disc -> disc, Comment -> comment); text values holding several +-- values (NUL separated) are joined with "; "; binary items (cover art) and external links stay in info.items. +-- Never throws. +-- +-- local tags, info = ApeTag.find(buf, start, limit) -- the tag ending at limit (or before an ID3v1 tag there) +-- -- tags: { title = ..., artist = ... } | nil (no tag / malformed) +-- -- info: { start = first byte (the header when present), stop = past the footer, version = 1000 | 2000, +-- -- items = { { key = "Title", value = "...", kind = "text" | "binary" | "link" } } } +-- local tags, info = ApeTag.parse(buf, footer, start) -- the tag whose footer is at byte `footer` (>= start) +local ApeTag = {} + +export type Item = { key: string, value: string, kind: string } +export type Info = { start: number, stop: number, version: number, items: { Item } } + +local TO_TAG: { [string]: string } = { + year = "date", + ["album artist"] = "albumartist", + albumartist = "albumartist", + tracknumber = "track", + discnumber = "disc", + description = "comment", +} +local KINDS = { [0] = "text", "binary", "link", "text" } + +-- tagKey(itemKey) -> the Types.Tags key +function ApeTag.tagKey(key: string): string + local k = string.lower(key) + return TO_TAG[k] or k +end + +-- parse(buf, footer, start?) -> tags, info | nil: the tag whose 32-byte footer starts at byte `footer`; the items +-- must lie at or after `start` (default 0) +function ApeTag.parse(buf: buffer, footer: number, start: number?): ({ [string]: string }?, Info?) + local lo = start or 0 + local n = buffer.len(buf) + if footer < lo or footer + 32 > n or buffer.readstring(buf, footer, 8) ~= "APETAGEX" then + return nil, nil + end + local version = buffer.readu32(buf, footer + 8) + local size = buffer.readu32(buf, footer + 12) -- items + footer + local count = buffer.readu32(buf, footer + 16) + local flags = buffer.readu32(buf, footer + 20) + if size < 32 or footer + 32 - size < lo then + return nil, nil + end + local p = footer + 32 - size + local first = p + if version >= 2000 and bit32.band(flags, 0x80000000) ~= 0 and p - 32 >= lo and buffer.readstring(buf, p - 32, 8) == "APETAGEX" then + first = p - 32 + end + local stop = footer + local tags: { [string]: string } = {} + local items: { Item } = {} + for _ = 1, math.min(count, 65536) do + if p + 9 > stop then + break + end + local len = buffer.readu32(buf, p) + local iflags = buffer.readu32(buf, p + 4) + local k = p + 8 + while k < stop and buffer.readu8(buf, k) ~= 0 do + k += 1 + end + if k >= stop then + break + end + local key = buffer.readstring(buf, p + 8, k - p - 8) + local v0 = k + 1 + if len > stop - v0 then + break + end + local value = buffer.readstring(buf, v0, len) + local kind = if version >= 2000 then KINDS[bit32.band(bit32.rshift(iflags, 1), 3)] else "text" + table.insert(items, { key = key, value = value, kind = kind }) + if kind == "text" and key ~= "" then + local tk = ApeTag.tagKey(key) + local s = (string.gsub(value, "%z+$", "")) + s = (string.gsub(s, "%z", "; ")) + local old = tags[tk] + tags[tk] = if old then old .. "; " .. s else s + end + p = v0 + len + end + return tags, { start = first, stop = footer + 32, version = version, items = items } +end + +-- find(buf, start, limit) -> tags, info | nil: the tag at the end of [start, limit), or just before a 128-byte +-- ID3v1 tag ("TAG") there +function ApeTag.find(buf: buffer, start: number, limit: number): ({ [string]: string }?, Info?) + if limit > buffer.len(buf) then + limit = buffer.len(buf) + end + if limit - start >= 32 then + local tags, info = ApeTag.parse(buf, limit - 32, start) + if tags then + return tags, info + end + end + if limit - start >= 160 and buffer.readstring(buf, limit - 128, 3) == "TAG" then + return ApeTag.parse(buf, limit - 160, start) + end + return nil, nil +end + +return ApeTag diff --git a/src/Formats/codecs/audio/Hively/Load.luau b/src/Formats/codecs/audio/Hively/Load.luau new file mode 100644 index 0000000..342fb09 --- /dev/null +++ b/src/Formats/codecs/audio/Hively/Load.luau @@ -0,0 +1,249 @@ +--!strict +-- codecs/audio/Hively/Load: AHX ("THX\0".."THX\2") and HivelyTracker ("HVL\0", "HVL\1") module files -> the replayer's +-- Tune. Ported from hvl2wav's replay.c 1.9 loaders (hvl_load_ahx / hvl_reset; BSD-3-Clause, (c) 2006-2018 Pete Gordon; +-- licenses/hivelytracker-LICENSE.txt), with bounds checks the C code does not have. Errors are returned as +-- (nil, message, kind) for core/Err.from. +local Load = {} + +local readu8, readi8 = buffer.readu8, buffer.readi8 + +export type PlistEntry = { note: number, waveform: number, fixed: number, fx: { number }, param: { number } } +export type Instrument = { + name: string, + volume: number, + waveLength: number, + filterLower: number, + filterUpper: number, + filterSpeed: number, + squareLower: number, + squareUpper: number, + squareSpeed: number, + vibratoDelay: number, + vibratoSpeed: number, + vibratoDepth: number, + hardCutRelease: number, + hardCutReleaseFrames: number, + envelope: { aFrames: number, aVolume: number, dFrames: number, dVolume: number, sFrames: number, rFrames: number, rVolume: number }, + plist: { speed: number, length: number, entries: { PlistEntry } }, +} +export type Tune = { + format: string, -- "ahx" | "hvl" + version: number, -- the 4th byte: AHX 0..2, HVL 0..1 + title: string, + channels: number, -- 4 (AHX), 4..16 (HVL) + positionNr: number, + restart: number, + speedMultiplier: number, -- 1..4 player calls per 50 Hz frame + trackLength: number, -- rows per track, 1..64 + trackNr: number, -- the highest track number stored + instrumentNr: number, + subsongs: { number }, -- first positions of subsongs 1..n + positions: buffer, -- positionNr * 16 * 2 bytes: per channel track (u8), transpose (i8) + tracks: buffer, -- 257 * 64 * 6 bytes: per track row note, instrument, fx, param, fxb, paramb + instruments: { Instrument }, -- 1-based, as numbered in the file + mixgain: number, -- (percent * 256) / 100, HVL only (AHX: set by the stereo separation at render time) + stereo: number, -- HVL: the default stereo separation 0..4 + emptyTrack0: boolean, -- track 0 is not stored (always empty) +} + +local function cstring(b: buffer, p: number, limit: number, max: number): (string, number) + local e = p + while e < limit and e - p < max and readu8(b, e) ~= 0 do + e += 1 + end + return buffer.readstring(b, p, e - p), e +end + +-- parse(b, base, limit) -> Tune | nil, message, kind +function Load.parse(b: buffer, base: number, limit: number): (Tune?, string?, string?) + local size = limit - base + if size < 14 then + return nil, "truncated header", "truncated" + end + local function u8(o: number): number + return readu8(b, base + o) + end + local magic = buffer.readstring(b, base, 3) + local ahx = magic == "THX" and u8(3) < 3 + if not ahx and not (magic == "HVL" and u8(3) <= 1) then + return nil, "not an AHX / HVL module", nil + end + if not ahx and size < 16 then + return nil, "truncated header", "truncated" + end + local posn = bit32.band(u8(6), 0x0f) * 256 + u8(7) + local insn, ssn, trkl, trkn = u8(12), u8(13), u8(10), u8(11) + local chnn = if ahx then 4 else bit32.rshift(u8(8), 2) + 4 + local tune: Tune = { + format = if ahx then "ahx" else "hvl", + version = u8(3), + title = "", + channels = chnn, + positionNr = posn, + restart = if ahx then u8(8) * 256 + u8(9) else bit32.band(u8(8), 3) * 256 + u8(9), + speedMultiplier = bit32.band(bit32.rshift(u8(6), 5), 3) + 1, + trackLength = trkl, + trackNr = trkn, + instrumentNr = insn, + subsongs = {}, + positions = buffer.create(math.max(posn, 1) * 32), + tracks = buffer.create(257 * 64 * 6), + instruments = {}, + mixgain = if ahx then 256 else (u8(14) * 256) // 100, + stereo = if ahx then 0 else math.min(u8(15), 4), + emptyTrack0 = bit32.band(u8(6), 0x80) ~= 0, + } + if posn == 0 or posn > 1000 or trkl > 64 or trkl == 0 or insn > 64 then + return nil, string.format("bad header (positions %d, track length %d, instruments %d)", posn, trkl, insn), nil + end + if chnn > 16 then + return nil, "unsupported: more than 16 channels", "unsupported" + end + if tune.restart >= posn then + tune.restart = posn - 1 + end + local nameAt = u8(4) * 256 + u8(5) + local nptr = limit + if nameAt < size then + local title, e = cstring(b, base + nameAt, limit, 128) + tune.title = title + nptr = e + 1 + end + + local p = base + (if ahx then 14 else 16) + local function need(n: number): boolean + return p + n <= limit + end + if not need(ssn * 2 + posn * chnn * 2) then + return nil, "truncated position list", "truncated" + end + for i = 1, ssn do + local s = readu8(b, p) * 256 + readu8(b, p + 1) + if s >= posn then + s = 0 + end + tune.subsongs[i] = s + p += 2 + end + for i = 0, posn - 1 do + for j = 0, chnn - 1 do + buffer.writeu8(tune.positions, (i * 16 + j) * 2, readu8(b, p)) + buffer.writei8(tune.positions, (i * 16 + j) * 2 + 1, readi8(b, p + 1)) + p += 2 + end + end + local tracks = tune.tracks + for i = 0, trkn do + if not (tune.emptyTrack0 and i == 0) then + for j = 0, trkl - 1 do + local o = (i * 64 + j) * 6 + if ahx then + if not need(3) then + return nil, "truncated track data", "truncated" + end + local b0, b1 = readu8(b, p), readu8(b, p + 1) + buffer.writeu8(tracks, o, bit32.band(bit32.rshift(b0, 2), 0x3f)) + buffer.writeu8(tracks, o + 1, bit32.band(b0, 3) * 16 + bit32.rshift(b1, 4)) + buffer.writeu8(tracks, o + 2, bit32.band(b1, 0xf)) + buffer.writeu8(tracks, o + 3, readu8(b, p + 2)) + p += 3 + else + if not need(1) then + return nil, "truncated track data", "truncated" + end + if readu8(b, p) == 0x3f then + p += 1 + else + if not need(5) then + return nil, "truncated track data", "truncated" + end + local fx = readu8(b, p + 2) + buffer.writeu8(tracks, o, readu8(b, p)) + buffer.writeu8(tracks, o + 1, readu8(b, p + 1)) + buffer.writeu8(tracks, o + 2, bit32.rshift(fx, 4)) + buffer.writeu8(tracks, o + 3, readu8(b, p + 3)) + buffer.writeu8(tracks, o + 4, bit32.band(fx, 0xf)) + buffer.writeu8(tracks, o + 5, readu8(b, p + 4)) + p += 5 + end + end + end + end + end + local plSize = if ahx then 4 else 5 + for i = 1, insn do + if not need(22) then + return nil, "truncated instrument", "truncated" + end + local function at(k: number): number + return readu8(b, p + k) + end + local name = "" + if nptr < limit then + local e + name, e = cstring(b, nptr, limit, 128) + nptr = e + 1 + end + local plen = at(21) + local ins: Instrument = { + name = name, + volume = at(0), + filterSpeed = bit32.bor(bit32.band(bit32.rshift(at(1), 3), 0x1f), bit32.band(bit32.rshift(at(12), 2), 0x20)), + waveLength = bit32.band(at(1), 7), + envelope = { aFrames = at(2), aVolume = at(3), dFrames = at(4), dVolume = at(5), sFrames = at(6), rFrames = at(7), rVolume = at(8) }, + filterLower = bit32.band(at(12), 0x7f), + vibratoDelay = at(13), + hardCutReleaseFrames = bit32.band(bit32.rshift(at(14), 4), 7), + hardCutRelease = if bit32.band(at(14), 0x80) ~= 0 then 1 else 0, + vibratoDepth = bit32.band(at(14), 0x0f), + vibratoSpeed = at(15), + squareLower = at(16), + squareUpper = at(17), + squareSpeed = at(18), + filterUpper = bit32.band(at(19), 0x3f), + plist = { speed = at(20), length = plen, entries = {} }, + } + p += 22 + if not need(plen * plSize) then + return nil, "truncated instrument play list", "truncated" + end + for j = 1, plen do + local e: PlistEntry + local b0, b1, b2, b3 = readu8(b, p), readu8(b, p + 1), readu8(b, p + 2), readu8(b, p + 3) + if ahx then + local k = bit32.band(bit32.rshift(b0, 5), 7) + k = if k == 6 then 12 elseif k == 7 then 15 else k + local l = bit32.band(bit32.rshift(b0, 2), 7) + l = if l == 6 then 12 elseif l == 7 then 15 else l + e = { + fx = { l, k }, + waveform = bit32.band(b0 * 2, 6) + bit32.rshift(b1, 7), + fixed = bit32.band(bit32.rshift(b1, 6), 1), + note = bit32.band(b1, 0x3f), + param = { b2, b3 }, + } + -- 1.6: version 0 modules (before filters) drop the "toggle filter" half of command 4 + if tune.version == 0 and l == 4 and bit32.band(b2, 0xf0) ~= 0 then + e.param[1] = bit32.band(b2, 0x0f) + end + if tune.version == 0 and k == 4 and bit32.band(b3, 0xf0) ~= 0 then + e.param[2] = bit32.band(b3, 0x0f) + end + else + e = { + fx = { bit32.band(b0, 0xf), bit32.band(bit32.rshift(b1, 3), 0xf) }, + waveform = bit32.band(b1, 7), + fixed = bit32.band(bit32.rshift(b2, 6), 1), + note = bit32.band(b2, 0x3f), + param = { b3, readu8(b, p + 4) }, + } + end + ins.plist.entries[j] = e + p += plSize + end + tune.instruments[i] = ins + end + return tune, nil, nil +end + +return Load diff --git a/src/Formats/codecs/audio/Hively/Player.luau b/src/Formats/codecs/audio/Hively/Player.luau new file mode 100644 index 0000000..4f9be2a --- /dev/null +++ b/src/Formats/codecs/audio/Hively/Player.luau @@ -0,0 +1,970 @@ +--!strict +--!native +-- codecs/audio/Hively/Player: the AHX / HivelyTracker replayer: positions and tracks (two effect columns in HVL), the +-- instrument engine (ADSR, vibrato, the PList performance list, square modulation, the resonant filter sweep, hard cut, +-- ring modulation and panning for HVL) and the integer mixer, all as hvl2wav's replay.c 1.9 computes them so the output +-- matches hvl2wav sample for sample. Ported from HivelyTracker (BSD-3-Clause, (c) 2006-2018 Pete Gordon; +-- licenses/hivelytracker-LICENSE.txt). Where the C code reads outside its arrays on bad data this port clamps instead. +local Tables = require("@formats/codecs/audio/Hively/Tables") +local Load = require("@formats/codecs/audio/Hively/Load") + +local Player = {} + +local readu8, readi8, writei8, writef32 = buffer.readu8, buffer.readi8, buffer.writei8, buffer.writef32 +local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift + +local FILTER_SET = Tables.FILTER_SET +local WO_TRIANGLE_04, WO_SAWTOOTH_04 = Tables.WO_TRIANGLE_04, Tables.WO_SAWTOOTH_04 +local WO_SQUARES, WO_WHITENOISE = Tables.WO_SQUARES, Tables.WO_WHITENOISE +local OFFSETS, VIB, PERIOD = Tables.OFFSETS, Tables.VIB, Tables.PERIOD +local WAVEFORM_AT = { [0] = WO_TRIANGLE_04, WO_SAWTOOTH_04, 0, WO_WHITENOISE } +local WRAP = 0x280 * 65536 +local TWO32 = 4294967296 + +local f32scratch = buffer.create(4) + +local function s16(v: number): number + return (v + 32768) % 65536 - 32768 +end + +local function tdiv(a: number, b: number): number -- C integer division (truncates) + local q = a / b + return if q >= 0 then math.floor(q) else -math.floor(-q) +end + +local function period(i: number): number + return PERIOD[i] or 0 +end + +-- (3546897.f * 65536.f) / period as a float, then / mix rate as a double, truncated +local function deltaOf(p: number, freq: number): number + if p == 0 then + return 1 + end + writef32(f32scratch, 0, 232449441792 / p) -- 3546897 * 65536 = 232449441792 (exact in a float) + local d = math.floor(buffer.readf32(f32scratch, 0) / freq) + if d < 0 then + d = 0 + end + if d > WRAP then + d -= WRAP + end + if d == 0 then + d = 1 + end + return d +end + +export type Voice = { [string]: any } +export type State = { + tune: Load.Tune, + freq: number, + version: number, + channels: number, + voices: { Voice }, + tempo: number, + posNr: number, + posJump: number, + posJumpNote: number, + noteNr: number, + stepWaitFrames: number, + getNewPosition: boolean, + patternBreak: boolean, + songEndReached: boolean, + playingTime: number, + mixgain: number, + waves: buffer, + panL: { number }, + panR: { number }, +} + +local function newVoice(i: number): Voice + return { + track = 0, nextTrack = 0, transpose = 0, nextTranspose = 0, overrideTranspose = 1000, + adsrVolume = 0, aFrames = 0, aVolume = 0, dFrames = 0, dVolume = 0, sFrames = 0, rFrames = 0, rVolume = 0, + instrument = false :: any, samplePos = 0, delta = 1, instrPeriod = 0, trackPeriod = 0, vibratoPeriod = 0, + waveLength = 0, noteMaxVolume = 0, perfSubVolume = 0, newWaveform = false, waveform = 0, plantPeriod = false, + voiceVolume = 0, plantSquare = false, ignoreSquare = 0, fixedNote = 0, volumeSlideUp = 0, volumeSlideDown = 0, + hardCut = 0, hardCutRelease = 0, hardCutReleaseF = 0, periodSlideOn = false, periodSlideSpeed = 0, + periodSlidePeriod = 0, periodSlideLimit = 0, periodSlideWithLimit = false, periodPerfSlideSpeed = 0, + periodPerfSlidePeriod = 0, periodPerfSlideOn = false, vibratoDelay = 0, vibratoSpeed = 0, vibratoCurrent = 0, + vibratoDepth = 0, squareOn = 0, squareInit = 0, squareWait = 0, squareLowerLimit = 0, squareUpperLimit = 0, + squarePos = 0, squareSign = 0, squareSlidingIn = false, squareReverse = false, filterOn = 0, filterInit = 0, + filterWait = 0, filterSpeed = 0, filterUpperLimit = 0, filterLowerLimit = 0, filterPos = 0, filterSign = 0, + filterSlidingIn = false, ignoreFilter = 0, perfCurrent = 0, perfSpeed = 0, perfWait = 0, perfList = false :: any, + audioSrc = false :: any, audioOff = 0, noteDelayOn = false, noteCutOn = false, noteDelayWait = 0, noteCutWait = 0, + audioPeriod = 0, audioVolume = 0, wnHi = 0, wnLo = 0x280, + squareBuf = buffer.create(0x80), voiceBuf = buffer.create(0x284), voiceNum = i, trackMasterVolume = 0x40, + pan = 0, setPan = 0, panMultLeft = 0, panMultRight = 0, + ringSamplePos = 0, ringDelta = 0, ringMix = false, ringPlantPeriod = false, ringBasePeriod = 0, + ringAudioPeriod = 0, ringAudioOff = -1, ringNewWaveform = false, ringWaveform = 0, ringFixedPeriod = 0, + ringBuf = buffer.create(0x284), + } +end + +-- new(tune, freq, stereo, subsong) -> State | nil (subsong out of range). stereo: AHX separation 0..4 (HVL: the file's) +function Player.new(tune: Load.Tune, freq: number, stereo: number, subsong: number): State? + if subsong < 0 or subsong > #tune.subsongs then + return nil + end + local t = Tables.get() + local defstereo = if tune.format == "ahx" then math.clamp(math.floor(stereo), 0, 4) else tune.stereo + local mixgain = tune.mixgain + if tune.format == "ahx" then + local defgain = { [0] = 71, 72, 76, 85, 100 } + mixgain = (defgain[defstereo] * 256) // 100 + end + local st: State = { + tune = tune, freq = freq, version = if tune.format == "hvl" then tune.version else 0, + channels = tune.channels, voices = {}, tempo = 6, posNr = if subsong > 0 then tune.subsongs[subsong] else 0, + posJump = 0, posJumpNote = 0, noteNr = 0, stepWaitFrames = 0, getNewPosition = true, patternBreak = false, + songEndReached = false, playingTime = 0, mixgain = mixgain, waves = t.waves, panL = t.panL, panR = t.panR, + } + local left, right = Tables.STEREO_LEFT[defstereo], Tables.STEREO_RIGHT[defstereo] + for i = 0, 15 do + local v = newVoice(i) + local p = if i % 4 == 0 or i % 4 == 3 then left else right + v.pan, v.setPan, v.panMultLeft, v.panMultRight = p, p, t.panL[p], t.panR[p] + st.voices[i + 1] = v + end + return st +end + +-- ------------------------------------------------------------------------------------------------ steps +local function setPan(st: State, v: Voice, p: number) + v.pan = p + v.panMultLeft, v.panMultRight = st.panL[p], st.panR[p] +end + +local function stepfx1(st: State, v: Voice, fx: number, param: number) + if fx == 0x0 then + local lo = band(param, 0x0f) + if lo > 0 and lo <= 9 then + st.posJump = lo + end + elseif fx == 0x5 or fx == 0xa then + v.volumeSlideDown = band(param, 0x0f) + v.volumeSlideUp = rshift(param, 4) + elseif fx == 0x7 then + if param > 127 then + param -= 256 + end + setPan(st, v, param + 128) + v.setPan = param + 128 + elseif fx == 0xb then + st.posJump = (st.posJump * 100 + band(param, 0x0f) + rshift(param, 4) * 10) % 65536 + st.patternBreak = true + if st.posJump <= st.posNr then + st.songEndReached = true + end + elseif fx == 0xd then + st.posJump = st.posNr + 1 + st.posJumpNote = band(param, 0x0f) + rshift(param, 4) * 10 + st.patternBreak = true + if st.posJumpNote > st.tune.trackLength then + st.posJumpNote = 0 + end + elseif fx == 0xe then + if rshift(param, 4) == 0xc and band(param, 0x0f) < st.tempo then + v.noteCutWait = band(param, 0x0f) + if v.noteCutWait ~= 0 then + v.noteCutOn = true + v.hardCutRelease = 0 + end + end + elseif fx == 0xf then + st.tempo = param + if param == 0 then + st.songEndReached = true + end + end +end + +local function stepfx2(v: Voice, fx: number, param: number, note: number): number + if fx == 0x9 then + v.squarePos = rshift(param, 5 - v.waveLength) + v.ignoreSquare = 1 + elseif fx == 0x3 or fx == 0x5 then + if fx == 0x3 and param ~= 0 then + v.periodSlideSpeed = param + end + if note ~= 0 then + local new = period(note) + local diff = period(v.trackPeriod) - new + new = diff + v.periodSlidePeriod + if new ~= 0 then + v.periodSlideLimit = s16(-diff) + end + end + v.periodSlideOn = true + v.periodSlideWithLimit = true + note = 0 + end + return note +end + +local function stepfx3(st: State, v: Voice, fx: number, param: number) + if fx == 0x01 then + v.periodSlideSpeed = -param + v.periodSlideOn = true + v.periodSlideWithLimit = false + elseif fx == 0x02 then + v.periodSlideSpeed = param + v.periodSlideOn = true + v.periodSlideWithLimit = false + elseif fx == 0x04 then + if param == 0 or param == 0x40 then + return + end + if param < 0x40 then + v.ignoreFilter = param + return + end + if param > 0x7f then + return + end + v.filterPos = param - 0x40 + elseif fx == 0x0c then + if param <= 0x40 then + v.noteMaxVolume = param + return + end + param -= 0x50 + if param < 0 then + return + end + if param <= 0x40 then + for i = 1, st.channels do + st.voices[i].trackMasterVolume = param + end + return + end + param -= 0xa0 - 0x50 + if param < 0 then + return + end + if param <= 0x40 then + v.trackMasterVolume = param + end + elseif fx == 0xe then + local sub, lo = rshift(param, 4), band(param, 0x0f) + if sub == 0x1 then + v.periodSlidePeriod = s16(v.periodSlidePeriod - lo) + v.plantPeriod = true + elseif sub == 0x2 then + v.periodSlidePeriod = s16(v.periodSlidePeriod + lo) + v.plantPeriod = true + elseif sub == 0x4 then + v.vibratoDepth = lo + elseif sub == 0xa then + v.noteMaxVolume = math.min(v.noteMaxVolume + lo, 0x40) + elseif sub == 0xb then + v.noteMaxVolume = math.max(v.noteMaxVolume - lo, 0) + elseif sub == 0xf then + if st.version >= 1 and lo == 1 then + v.overrideTranspose = v.transpose + end + end + end +end + +local function processStep(st: State, v: Voice) + v.volumeSlideUp, v.volumeSlideDown = 0, 0 + local tune = st.tune + local track = readu8(tune.positions, (st.posNr * 16 + v.voiceNum) * 2) + local so = (track * 64 + st.noteNr) * 6 + local tracks = tune.tracks + local note, instr = readu8(tracks, so), readu8(tracks, so + 1) + local fx, fxp, fxb, fxbp = band(readu8(tracks, so + 2), 0xf), readu8(tracks, so + 3), band(readu8(tracks, so + 4), 0xf), readu8(tracks, so + 5) + + local doneNoteDel = false + if fx == 0xe and band(fxp, 0xf0) == 0xd0 then + if v.noteDelayOn then + v.noteDelayOn = false + doneNoteDel = true + elseif band(fxp, 0x0f) < st.tempo then + v.noteDelayWait = band(fxp, 0x0f) + if v.noteDelayWait ~= 0 then + v.noteDelayOn = true + return + end + end + end + if not doneNoteDel and fxb == 0xe and band(fxbp, 0xf0) == 0xd0 then + if v.noteDelayOn then + v.noteDelayOn = false + elseif band(fxbp, 0x0f) < st.tempo then + v.noteDelayWait = band(fxbp, 0x0f) + if v.noteDelayWait ~= 0 then + v.noteDelayOn = true + return + end + end + end + + if note ~= 0 then + v.overrideTranspose = 1000 + end + stepfx1(st, v, fx, fxp) + stepfx1(st, v, fxb, fxbp) + + if instr ~= 0 and instr <= tune.instrumentNr then + local ins = tune.instruments[instr] + setPan(st, v, v.setPan) + v.periodSlideSpeed, v.periodSlidePeriod, v.periodSlideLimit = 0, 0, 0 + v.perfSubVolume = 0x40 + v.adsrVolume = 0 + v.instrument = ins + v.samplePos = 0 + local env = ins.envelope + v.aFrames = env.aFrames + v.aVolume = s16(if v.aFrames ~= 0 then tdiv(env.aVolume * 256, v.aFrames) else env.aVolume * 256) + v.dFrames = env.dFrames + v.dVolume = s16(if v.dFrames ~= 0 then tdiv((env.dVolume - env.aVolume) * 256, v.dFrames) else env.dVolume * 256) + v.sFrames = env.sFrames + v.rFrames = env.rFrames + v.rVolume = s16(if v.rFrames ~= 0 then tdiv((env.rVolume - env.dVolume) * 256, v.rFrames) else env.rVolume * 256) + v.waveLength = math.min(ins.waveLength, 5) + v.noteMaxVolume = ins.volume + v.vibratoCurrent = 0 + v.vibratoDelay = ins.vibratoDelay + v.vibratoDepth = ins.vibratoDepth + v.vibratoSpeed = ins.vibratoSpeed + v.vibratoPeriod = 0 + v.hardCutRelease = ins.hardCutRelease + v.hardCut = ins.hardCutReleaseFrames + v.ignoreSquare, v.squareSlidingIn = 0, false + v.squareWait, v.squareOn = 0, 0 + local lower = rshift(ins.squareLower, 5 - v.waveLength) + local upper = rshift(ins.squareUpper, 5 - v.waveLength) + if upper < lower then + lower, upper = upper, lower + end + v.squareUpperLimit, v.squareLowerLimit = upper, lower + v.ignoreFilter, v.filterWait, v.filterOn = 0, 0, 0 + v.filterSlidingIn = false + local d6, d3, d4 = ins.filterSpeed, ins.filterLower, ins.filterUpper + v.filterSpeed = d6 + if d3 > d4 then + d3, d4 = d4, d3 + end + v.filterUpperLimit, v.filterLowerLimit = d4, d3 + v.filterPos = 32 + v.perfWait, v.perfCurrent = 0, 0 + v.perfSpeed = ins.plist.speed + v.perfList = ins.plist + v.ringMix = false + v.ringSamplePos = 0 + v.ringPlantPeriod = false + v.ringNewWaveform = false + end + + v.periodSlideOn = false + note = stepfx2(v, fx, fxp, note) + note = stepfx2(v, fxb, fxbp, note) + if note ~= 0 then + v.trackPeriod = note + v.plantPeriod = true + end + stepfx3(st, v, fx, fxp) + stepfx3(st, v, fxb, fxbp) +end + +-- ------------------------------------------------------------------------------------------------ frames +local function plistCommand(st: State, v: Voice, fx: number, param: number) + if fx == 0 then + if param > 0 and param < 0x40 then + if v.ignoreFilter ~= 0 then + v.filterPos = v.ignoreFilter + v.ignoreFilter = 0 + else + v.filterPos = param + end + v.newWaveform = true + end + elseif fx == 1 then + v.periodPerfSlideSpeed = param + v.periodPerfSlideOn = true + elseif fx == 2 then + v.periodPerfSlideSpeed = -param + v.periodPerfSlideOn = true + elseif fx == 3 then + if v.ignoreSquare == 0 then + v.squarePos = rshift(param, 5 - v.waveLength) + else + v.ignoreSquare = 0 + end + elseif fx == 4 then + if param == 0 then + v.squareOn = 1 - v.squareOn + v.squareInit = v.squareOn + v.squareSign = 1 + else + if band(param, 0x0f) ~= 0 then + v.squareOn = 1 - v.squareOn + v.squareInit = v.squareOn + v.squareSign = if band(param, 0x0f) == 0x0f then -1 else 1 + end + if band(param, 0xf0) ~= 0 then + v.filterOn = 1 - v.filterOn + v.filterInit = v.filterOn + v.filterSign = if band(param, 0xf0) == 0xf0 then -1 else 1 + end + end + elseif fx == 5 then + v.perfCurrent = param + elseif fx == 7 or fx == 8 then + if param >= 1 and param <= 0x3c then + v.ringBasePeriod = param + v.ringFixedPeriod = 1 + elseif param >= 0x81 and param <= 0xbc then + v.ringBasePeriod = param - 0x80 + v.ringFixedPeriod = 0 + else + v.ringBasePeriod = 0 + v.ringFixedPeriod = 0 + v.ringNewWaveform = false + v.ringAudioOff = -1 + v.ringMix = false + return + end + v.ringWaveform = fx - 7 + v.ringNewWaveform = true + v.ringPlantPeriod = true + elseif fx == 9 then + if param > 127 then + param -= 256 + end + setPan(st, v, param + 128) + elseif fx == 12 then + if param <= 0x40 then + v.noteMaxVolume = param + return + end + param -= 0x50 + if param < 0 then + return + end + if param <= 0x40 then + v.perfSubVolume = param + return + end + param -= 0xa0 - 0x50 + if param < 0 then + return + end + if param <= 0x40 then + v.trackMasterVolume = param + end + elseif fx == 15 then + v.perfSpeed = param + v.perfWait = param + end +end + +-- the noise offset generator (vc_WNRandom, a 64-bit `long` in hvl2wav): W += 2239384; +-- W = ((((W >> 8) | (W << 24)) + 782323) ^ 75) - 6735 +local function wnStep(v: Voice) + local hi, lo = v.wnHi, v.wnLo + 2239384 + if lo >= TWO32 then + lo -= TWO32 + hi = (hi + 1) % TWO32 + end + local shi = rshift(hi, 8) + if hi >= 0x80000000 then + shi = bor(shi, 0xff000000) + end + local nlo = bor(rshift(lo, 8), lshift(band(hi, 0xff), 24), lshift(lo, 24)) + local nhi = bor(shi, lshift(hi, 24), rshift(lo, 8)) + nlo += 782323 + if nlo >= TWO32 then + nlo -= TWO32 + nhi = (nhi + 1) % TWO32 + end + nlo = bit32.bxor(nlo, 75) + nlo -= 6735 + if nlo < 0 then + nlo += TWO32 + nhi = (nhi + TWO32 - 1) % TWO32 + end + v.wnHi, v.wnLo = nhi, nlo +end + +local function processFrame(st: State, v: Voice) + local tune = st.tune + if v.noteDelayOn then + if v.noteDelayWait <= 0 then + processStep(st, v) + else + v.noteDelayWait -= 1 + end + end + + if v.hardCut ~= 0 then + local row = st.noteNr + 1 + local nextinst + if row < tune.trackLength then + nextinst = readu8(tune.tracks, ((v.track * 64) + row) * 6 + 1) + else + nextinst = readu8(tune.tracks, (v.nextTrack * 64) * 6 + 1) + end + if nextinst ~= 0 then + local d1 = math.max(st.tempo - v.hardCut, 0) + if not v.noteCutOn then + v.noteCutOn = true + v.noteCutWait = d1 + v.hardCutReleaseF = -(d1 - st.tempo) + else + v.hardCut = 0 + end + end + end + + if v.noteCutOn then + if v.noteCutWait <= 0 then + v.noteCutOn = false + if v.hardCutRelease ~= 0 then + local ins = v.instrument + local f = v.hardCutReleaseF + v.rVolume = if f ~= 0 then s16(tdiv(-(v.adsrVolume - ins.envelope.rVolume * 256), f)) else 0 + v.rFrames = f + v.aFrames, v.dFrames, v.sFrames = 0, 0, 0 + else + v.noteMaxVolume = 0 + end + else + v.noteCutWait -= 1 + end + end + + -- ADSR envelope + if v.aFrames ~= 0 then + v.adsrVolume += v.aVolume + v.aFrames -= 1 + if v.aFrames <= 0 then + v.adsrVolume = v.instrument.envelope.aVolume * 256 + end + elseif v.dFrames ~= 0 then + v.adsrVolume += v.dVolume + v.dFrames -= 1 + if v.dFrames <= 0 then + v.adsrVolume = v.instrument.envelope.dVolume * 256 + end + elseif v.sFrames ~= 0 then + v.sFrames -= 1 + elseif v.rFrames ~= 0 then + v.adsrVolume += v.rVolume + v.rFrames -= 1 + if v.rFrames <= 0 then + v.adsrVolume = v.instrument.envelope.rVolume * 256 + end + end + + -- volume slide + v.noteMaxVolume = math.clamp(v.noteMaxVolume + v.volumeSlideUp - v.volumeSlideDown, 0, 0x40) + + -- portamento + if v.periodSlideOn then + if v.periodSlideWithLimit then + local d0 = v.periodSlidePeriod - v.periodSlideLimit + local d2 = v.periodSlideSpeed + if d0 > 0 then + d2 = -d2 + end + if d0 ~= 0 then + local sum = d0 + d2 + -- (d0 + d2) ^ d0 >= 0: the same sign (or zero) + if (sum >= 0) == (d0 >= 0) then + d0 = v.periodSlidePeriod + d2 + else + d0 = v.periodSlideLimit + end + v.periodSlidePeriod = s16(d0) + v.plantPeriod = true + end + else + v.periodSlidePeriod = s16(v.periodSlidePeriod + v.periodSlideSpeed) + v.plantPeriod = true + end + end + + -- vibrato + if v.vibratoDepth ~= 0 then + if v.vibratoDelay <= 0 then + v.vibratoPeriod = (VIB[v.vibratoCurrent] * v.vibratoDepth) // 128 + v.plantPeriod = true + v.vibratoCurrent = band(v.vibratoCurrent + v.vibratoSpeed, 0x3f) + else + v.vibratoDelay -= 1 + end + end + + -- PList + local pl = v.perfList + if pl then + if v.instrument and v.perfCurrent < v.instrument.plist.length then + local overflow = v.perfWait == 128 + v.perfWait = s16(v.perfWait - 1) + local w8 = (v.perfWait + 128) % 256 - 128 + if overflow or w8 <= 0 then + local cur = v.perfCurrent + v.perfCurrent += 1 + v.perfWait = v.perfSpeed + local e = pl.entries[cur + 1] + if e then + if e.waveform ~= 0 then + v.waveform = e.waveform - 1 + v.newWaveform = true + v.periodPerfSlideSpeed, v.periodPerfSlidePeriod = 0, 0 + end + v.periodPerfSlideOn = false + plistCommand(st, v, e.fx[1], e.param[1]) + plistCommand(st, v, e.fx[2], e.param[2]) + if e.note ~= 0 then + v.instrPeriod = e.note + v.plantPeriod = true + v.fixedNote = e.fixed + end + end + end + else + if v.perfWait ~= 0 then + v.perfWait -= 1 + else + v.periodPerfSlideSpeed = 0 + end + end + end + + -- perf portamento + if v.periodPerfSlideOn then + v.periodPerfSlidePeriod = s16(v.periodPerfSlidePeriod - v.periodPerfSlideSpeed) + if v.periodPerfSlidePeriod ~= 0 then + v.plantPeriod = true + end + end + + if v.waveform == 2 and v.squareOn ~= 0 then + v.squareWait -= 1 + if v.squareWait <= 0 then + local d1, d2, d3 = v.squareLowerLimit, v.squareUpperLimit, v.squarePos + if v.squareInit ~= 0 then + v.squareInit = 0 + if d3 <= d1 then + v.squareSlidingIn = true + v.squareSign = 1 + elseif d3 >= d2 then + v.squareSlidingIn = true + v.squareSign = -1 + end + end + if d1 == d3 or d2 == d3 then + if v.squareSlidingIn then + v.squareSlidingIn = false + else + v.squareSign = -v.squareSign + end + end + d3 += v.squareSign + v.squarePos = s16(d3) + v.plantSquare = true + local ins: any = v.instrument + v.squareWait = if ins then ins.squareSpeed else 0 + end + end + + if v.filterOn ~= 0 then + v.filterWait -= 1 + if v.filterWait <= 0 then + local d1, d2, d3 = v.filterLowerLimit, v.filterUpperLimit, v.filterPos + if v.filterInit ~= 0 then + v.filterInit = 0 + if d3 <= d1 then + v.filterSlidingIn = true + v.filterSign = 1 + elseif d3 >= d2 then + v.filterSlidingIn = true + v.filterSign = -1 + end + end + local fmax = if v.filterSpeed < 4 then 5 - v.filterSpeed else 1 + for _ = 1, fmax do + if d1 == d3 or d2 == d3 then + if v.filterSlidingIn then + v.filterSlidingIn = false + else + v.filterSign = -v.filterSign + end + end + d3 += v.filterSign + end + v.filterPos = math.clamp(d3, 1, 63) + v.newWaveform = true + v.filterWait = math.max(v.filterSpeed - 3, 1) + end + end + + local waves = st.waves + local fpos = math.clamp(v.filterPos, 1, 63) + if v.waveform == 2 or v.plantSquare then + -- CalcSquare + local sp = WO_SQUARES + (fpos - 0x20) * FILTER_SET + local x = v.squarePos * 2 ^ (5 - v.waveLength) + if x > 0x20 then + x = 0x40 - x + v.squareReverse = true + end + if x > 0 then + sp += (x - 1) * 128 + end + local delta = 32 // 2 ^ v.waveLength + local sb = v.squareBuf + for i = 0, 4 * 2 ^ v.waveLength - 1 do + writei8(sb, i, readi8(waves, sp)) + sp += delta + end + v.newWaveform = true + v.waveform = 2 + v.plantSquare = false + end + + if v.waveform == 3 then + v.newWaveform = true + end + + if v.ringNewWaveform then + if v.ringWaveform > 1 then + v.ringWaveform = 1 + end + v.ringAudioOff = WAVEFORM_AT[v.ringWaveform] + OFFSETS[v.waveLength] + end + + if v.newWaveform and v.waveform <= 3 then + if v.waveform == 2 then + v.audioSrc, v.audioOff = v.squareBuf, 0 + else + local off = WAVEFORM_AT[v.waveform] + (fpos - 0x20) * FILTER_SET + if v.waveform < 2 then + off += OFFSETS[v.waveLength] + else + off += band(band(v.wnLo, 2 * 0x280 - 1), 0xfffffffe) + wnStep(v) + end + v.audioSrc, v.audioOff = waves, off + end + end + + -- ring modulation period + if v.ringAudioOff >= 0 then + local rp = v.ringBasePeriod + if v.ringFixedPeriod == 0 then + if v.overrideTranspose ~= 1000 then + rp += v.overrideTranspose + v.trackPeriod - 1 + else + rp += v.transpose + v.trackPeriod - 1 + end + end + rp = period(math.clamp(s16(rp), 0, 60)) + if v.ringFixedPeriod == 0 then + rp += v.periodSlidePeriod + end + rp = s16(rp + v.periodPerfSlidePeriod + v.vibratoPeriod) + v.ringAudioPeriod = math.clamp(rp, 0x71, 0xd60) + end + + -- the period + local ap = v.instrPeriod + if v.fixedNote == 0 then + if v.overrideTranspose ~= 1000 then + ap += v.overrideTranspose + v.trackPeriod - 1 + else + ap += v.transpose + v.trackPeriod - 1 + end + end + ap = period(math.clamp(s16(ap), 0, 60)) + if v.fixedNote == 0 then + ap += v.periodSlidePeriod + end + ap = s16(ap + v.periodPerfSlidePeriod + v.vibratoPeriod) + v.audioPeriod = math.clamp(ap, 0x71, 0xd60) + + local vol = (v.adsrVolume // 256 * v.noteMaxVolume) // 64 + vol = (vol * v.perfSubVolume) // 64 + vol = (vol * v.trackMasterVolume) // 64 + v.audioVolume = s16(vol) +end + +-- fill the 0x280-byte voice buffer with repeats of the 4 << waveLength cycle at (src, off) +local function fillCycles(dst: buffer, src: buffer, off: number, len: number) + if off < 0 or off + len > buffer.len(src) then + buffer.fill(dst, 0, 0, 0x281) + return + end + buffer.copy(dst, 0, src, off, len) + local filled = len + while filled < 0x280 do + local k = math.min(filled, 0x280 - filled) + buffer.copy(dst, filled, dst, 0, k) + filled += k + end + writei8(dst, 0x280, readi8(dst, 0)) +end + +local function setAudio(st: State, v: Voice) + v.voiceVolume = v.audioVolume % 256 + if v.plantPeriod then + v.plantPeriod = false + v.delta = deltaOf(v.audioPeriod, st.freq) + end + local src: buffer? = v.audioSrc or nil + if v.newWaveform and src then + fillCycles(v.voiceBuf, src, v.audioOff, if v.waveform == 3 then 0x280 else 4 * 2 ^ v.waveLength) + end + if v.ringPlantPeriod then + v.ringPlantPeriod = false + v.ringDelta = deltaOf(v.ringAudioPeriod, st.freq) + end + if v.ringNewWaveform and v.ringAudioOff >= 0 then + fillCycles(v.ringBuf, st.waves, v.ringAudioOff, 4 * 2 ^ v.waveLength) + v.ringMix = true + end +end + +-- irq(st, audio): one player call (hvl_play_irq); audio = false skips the audio side (duration scans) +function Player.irq(st: State, audio: boolean) + local tune = st.tune + local nch = st.channels + local voices = st.voices + if st.stepWaitFrames == 0 then + if st.getNewPosition then + local nextpos = if st.posNr + 1 == tune.positionNr then 0 else st.posNr + 1 + local P = tune.positions + for i = 0, nch - 1 do + local v = voices[i + 1] + v.track = readu8(P, (st.posNr * 16 + i) * 2) + v.transpose = readi8(P, (st.posNr * 16 + i) * 2 + 1) + v.nextTrack = readu8(P, (nextpos * 16 + i) * 2) + v.nextTranspose = readi8(P, (nextpos * 16 + i) * 2 + 1) + end + st.getNewPosition = false + end + for i = 1, nch do + processStep(st, voices[i]) + end + st.stepWaitFrames = st.tempo + end + for i = 1, nch do + processFrame(st, voices[i]) + end + st.playingTime += 1 + st.stepWaitFrames = s16(st.stepWaitFrames - 1) + if st.stepWaitFrames == 0 then + if not st.patternBreak then + st.noteNr += 1 + if st.noteNr >= tune.trackLength then + st.posJump = st.posNr + 1 + st.posJumpNote = 0 + st.patternBreak = true + end + end + if st.patternBreak then + st.patternBreak = false + st.posNr = st.posJump + st.noteNr = st.posJumpNote + if st.posNr >= tune.positionNr then + -- (past the end is bad data: the C code reads outside its position list) + st.songEndReached = true + st.posNr = tune.restart + end + st.posJumpNote = 0 + st.posJump = 0 + st.getNewPosition = true + end + end + if audio then + for i = 1, nch do + setAudio(st, voices[i]) + end + end +end + +-- mix(st, out, at, n): n stereo frames of f32 into out at frame `at` (hvl_mixchunk: integer mixing, s16 clipping, / 32768) +function Player.mix(st: State, out: buffer, at: number, n: number) + local nch = st.channels + local voices = st.voices + local src, rsrc, delta, rdelta, vol, pos, rpos, panl, panr = {}, {}, {}, {}, {}, {}, {}, {}, {} + for i = 1, nch do + local v = voices[i] + delta[i] = math.max(v.delta, 1) + vol[i] = v.voiceVolume + pos[i] = v.samplePos + src[i] = v.voiceBuf + panl[i] = v.panMultLeft + panr[i] = v.panMultRight + rdelta[i] = math.max(v.ringDelta, 1) + rpos[i] = v.ringSamplePos + rsrc[i] = if v.ringMix then v.ringBuf else false + end + local gain = st.mixgain + local o = at * 8 + local samples = n + while samples > 0 do + local loops = samples + for i = 1, nch do + if pos[i] >= WRAP then + pos[i] -= WRAP + end + local cnt = (WRAP - pos[i] - 1) // delta[i] + 1 + if cnt < loops then + loops = cnt + end + if rsrc[i] then + if rpos[i] >= WRAP then + rpos[i] -= WRAP + end + cnt = (WRAP - rpos[i] - 1) // rdelta[i] + 1 + if cnt < loops then + loops = cnt + end + end + end + samples -= loops + for _ = 1, loops do + local a, b = 0, 0 + for i = 1, nch do + local j + local r = rsrc[i] + if r then + j = ((readi8(src[i], pos[i] // 65536) * readi8(r, rpos[i] // 65536)) // 128) * vol[i] + rpos[i] += rdelta[i] + else + j = readi8(src[i], pos[i] // 65536) * vol[i] + end + a += (j * panl[i]) // 128 + b += (j * panr[i]) // 128 + pos[i] += delta[i] + end + a = (a * gain) // 256 + b = (b * gain) // 256 + if a < -32768 then + a = -32768 + elseif a > 32767 then + a = 32767 + end + if b < -32768 then + b = -32768 + elseif b > 32767 then + b = 32767 + end + writef32(out, o, a / 32768) + writef32(out, o + 4, b / 32768) + o += 8 + end + end + for i = 1, nch do + voices[i].samplePos = pos[i] + voices[i].ringSamplePos = rpos[i] + end +end + +return Player diff --git a/src/Formats/codecs/audio/Hively/Tables.luau b/src/Formats/codecs/audio/Hively/Tables.luau new file mode 100644 index 0000000..8d76e0e --- /dev/null +++ b/src/Formats/codecs/audio/Hively/Tables.luau @@ -0,0 +1,221 @@ +--!strict +--!native +-- codecs/audio/Hively/Tables: the AHX / HivelyTracker replayer's tables: the waveform block (triangle and sawtooth at +-- six lengths, 32 square pulse widths, white noise, and the 31 low-pass and 31 high-pass filtered copies of all of +-- them, generated as hvl_replay.c does), the sine panning tables, the vibrato sine and the Amiga period table. Ported +-- from HivelyTracker's hvl2wav replay.c 1.9 (BSD-3-Clause, (c) 2006-2018 Pete Gordon; licenses/hivelytracker-LICENSE.txt) +-- as hvl2wav builds on 64-bit Linux (`long` is 64-bit there: the noise generator's shifts do not wrap at 32 bits). +local Tables = {} + +local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift + +-- the offsets inside `waves` (bytes) +local FILTER_SET = 0xfc + 0xfc + 0x80 * 0x1f + 0x80 + 3 * 0x280 -- 6520: one filtered copy of every waveform +local WHITENOISELEN = 0x280 * 3 +local WO_LOWPASSES = 0 +local WO_TRIANGLE_04 = WO_LOWPASSES + FILTER_SET * 31 +local WO_SAWTOOTH_04 = WO_TRIANGLE_04 + 0xfc +local WO_SQUARES = WO_SAWTOOTH_04 + 0xfc +local WO_WHITENOISE = WO_SQUARES + 0x80 * 0x20 +local WO_HIGHPASSES = WO_WHITENOISE + WHITENOISELEN +local WAVES_SIZE = WO_HIGHPASSES + FILTER_SET * 31 + +Tables.FILTER_SET = FILTER_SET +Tables.WO_TRIANGLE_04 = WO_TRIANGLE_04 +Tables.WO_SAWTOOTH_04 = WO_SAWTOOTH_04 +Tables.WO_SQUARES = WO_SQUARES +Tables.WO_WHITENOISE = WO_WHITENOISE +Tables.WAVES_SIZE = WAVES_SIZE +-- offset of the waveform of length 4 << n inside the triangle / sawtooth runs +Tables.OFFSETS = { [0] = 0x00, 0x04, 0x04 + 0x08, 0x04 + 0x08 + 0x10, 0x04 + 0x08 + 0x10 + 0x20, 0x04 + 0x08 + 0x10 + 0x20 + 0x40 } + +Tables.VIB = { + [0] = 0, 24, 49, 74, 97, 120, 141, 161, 180, 197, 212, 224, 235, 244, 250, 253, 255, + 253, 250, 244, 235, 224, 212, 197, 180, 161, 141, 120, 97, 74, 49, 24, + 0, -24, -49, -74, -97, -120, -141, -161, -180, -197, -212, -224, -235, -244, -250, -253, -255, + -253, -250, -244, -235, -224, -212, -197, -180, -161, -141, -120, -97, -74, -49, -24, +} + +Tables.PERIOD = { + [0] = 0x0000, 0x0D60, 0x0CA0, 0x0BE8, 0x0B40, 0x0A98, 0x0A00, 0x0970, + 0x08E8, 0x0868, 0x07F0, 0x0780, 0x0714, 0x06B0, 0x0650, 0x05F4, + 0x05A0, 0x054C, 0x0500, 0x04B8, 0x0474, 0x0434, 0x03F8, 0x03C0, + 0x038A, 0x0358, 0x0328, 0x02FA, 0x02D0, 0x02A6, 0x0280, 0x025C, + 0x023A, 0x021A, 0x01FC, 0x01E0, 0x01C5, 0x01AC, 0x0194, 0x017D, + 0x0168, 0x0153, 0x0140, 0x012E, 0x011D, 0x010D, 0x00FE, 0x00F0, + 0x00E2, 0x00D6, 0x00CA, 0x00BE, 0x00B4, 0x00AA, 0x00A0, 0x0097, + 0x008F, 0x0087, 0x007F, 0x0078, 0x0071, +} + +Tables.STEREO_LEFT = { [0] = 128, 96, 64, 32, 0 } +Tables.STEREO_RIGHT = { [0] = 128, 160, 193, 225, 255 } + +local function i8(v: number): number + v = v % 256 + return if v >= 128 then v - 256 else v +end + +local function genSawtooth(w: buffer, at: number, len: number) + local add = 256 // (len - 1) + local val = -128 + for i = 0, len - 1 do + buffer.writei8(w, at + i, i8(val)) + val += add + end +end + +local function genTriangle(w: buffer, at: number, len: number) + local d5 = len // 4 + local d1 = 128 // d5 + local d4 = -(len // 2) + local p = at + local val = 0 + for _ = 1, d5 do + buffer.writei8(w, p, i8(val)) + p += 1 + val += d1 + end + buffer.writei8(w, p, 0x7f) + p += 1 + if d5 ~= 1 then + val = 128 + for _ = 1, d5 - 1 do + val -= d1 + buffer.writei8(w, p, i8(val)) + p += 1 + end + end + local q = p + d4 + for _ = 1, d5 * 2 do + local c = buffer.readi8(w, q) + q += 1 + buffer.writei8(w, p, if c == 0x7f then -128 else i8(-c)) + p += 1 + end +end + +local function genSquare(w: buffer, at: number) + local p = at + for i = 1, 0x20 do + for _ = 1, (0x40 - i) * 2 do + buffer.writei8(w, p, -128) + p += 1 + end + for _ = 1, i * 2 do + buffer.writei8(w, p, 0x7f) + p += 1 + end + end +end + +-- hvl_GenWhiteNoise with `unsigned long` = 64 bits: (hi, lo) halves +local function genWhiteNoise(w: buffer, at: number, len: number) + local hi, lo = 0, 0x41595321 + for i = 0, len - 1 do + local s = i8(band(lo, 0xff)) + if band(lo, 0x100) ~= 0 then + s = 0x7f -- (int32)(ays & 0xffff) >= 0 always holds + end + buffer.writei8(w, at + i, s) + -- ays = (ays >> 5) | (ays << 27) + local nlo = bor(rshift(lo, 5), lshift(band(hi, 31), 27), lshift(lo, 27)) + -- (the high half is masked off next: ays & 0xffffff00 zero-extends) + lo = bor(band(nlo, 0xffffff00), bxor(band(nlo, 0xff), 0x9a)) + local bx = band(lo, 0xffff) + -- ays = (ays << 2) | (ays >> 30) + lo = bor(lshift(lo, 2), rshift(lo, 30)) + local ax = band(lo, 0xffff) + bx = band(bx + ax, 0xffff) + ax = bxor(ax, bx) + lo = bor(band(lo, 0xffff0000), ax) + -- ays = (ays >> 3) | (ays << 29) + hi = rshift(lo, 3) + lo = bor(rshift(lo, 3), lshift(lo, 29)) + end +end + +local LENTAB = { 3, 7, 0xf, 0x1f, 0x3f, 0x7f, 3, 7, 0xf, 0x1f, 0x3f, 0x7f } +for _ = 1, 32 do + table.insert(LENTAB, 0x7f) +end +table.insert(LENTAB, 0x280 * 3 - 1) + +local function clip(x: number): number + if x > 127 then + return 127 + elseif x < -128 then + return -128 + end + return x +end + +local function trunc8(x: number): number + return if x >= 0 then math.floor(x) else -math.floor(-x) +end + +local function genFilterWaves(w: buffer) + local low, high = WO_LOWPASSES, WO_HIGHPASSES + local freq = 8 + for _ = 0, 30 do + local a0 = WO_TRIANGLE_04 + local fre = freq * 1.25 / 100.0 + for wv = 1, 45 do + local n = LENTAB[wv] + local mid, lo = 0, 0 + for i = 0, n do + local h = clip(buffer.readi8(w, a0 + i) - mid - lo) + mid = clip(mid + h * fre) + lo = clip(lo + mid * fre) + end + for i = 0, n do + local h = clip(buffer.readi8(w, a0 + i) - mid - lo) + mid = clip(mid + h * fre) + lo = clip(lo + mid * fre) + buffer.writei8(w, low, trunc8(lo)) + buffer.writei8(w, high, trunc8(h)) + low += 1 + high += 1 + end + a0 += n + 1 + end + freq += 3 + end +end + +local cache: { waves: buffer, panL: { number }, panR: { number } }? = nil + +-- get() -> { waves (int8 buffer), panL, panR (0-based, 256 entries) }: built once, shared read only +function Tables.get(): { waves: buffer, panL: { number }, panR: { number } } + if cache then + return cache + end + local w = buffer.create(WAVES_SIZE) + local n = 4 + for k = 0, 5 do + genSawtooth(w, WO_SAWTOOTH_04 + Tables.OFFSETS[k], n) + genTriangle(w, WO_TRIANGLE_04 + Tables.OFFSETS[k], n) + n *= 2 + end + genSquare(w, WO_SQUARES) + genWhiteNoise(w, WO_WHITENOISE, WHITENOISELEN) + genFilterWaves(w) + -- sine panning: the start angle is a float expression in the C source ((3.14159265f * 2.0f) / 4.0f) + local f = buffer.create(4) + buffer.writef32(f, 0, 3.14159265) + local aa = buffer.readf32(f, 0) * 2 / 4 + local ab = 0.0 + local step = (3.14159265 * 2.0 / 4.0) / 256.0 + local pl: { number }, pr: { number } = {}, {} + for i = 0, 255 do + pl[i] = math.floor(math.sin(aa) * 255.0) + pr[i] = math.floor(math.sin(ab) * 255.0) + aa += step + ab += step + end + pl[255] = 0 + pr[0] = 0 + cache = { waves = w, panL = pl, panR = pr } + return cache :: any +end + +return Tables diff --git a/src/Formats/codecs/audio/Hively/init.luau b/src/Formats/codecs/audio/Hively/init.luau new file mode 100644 index 0000000..1585985 --- /dev/null +++ b/src/Formats/codecs/audio/Hively/init.luau @@ -0,0 +1,209 @@ +--!strict +-- codecs/audio/Hively: the AHX / HivelyTracker engine behind music/ahx and music/hvl: the loader for both file formats +-- (Load), the replayer with its waveform generator (Tables: triangle / sawtooth / square / noise and the 31 + 31 +-- filtered copies) and integer mixer (Player), and the render glue to a Types.Decoder (stereo f32). A port of +-- HivelyTracker's hvl2wav replay.c 1.9 (BSD-3-Clause, (c) 2006-2018 Pete Gordon; licenses/hivelytracker-LICENSE.txt): +-- at hvl2wav's settings the output equals hvl2wav's 16-bit samples / 32768, sample for sample. +-- +-- local Hively = require("@formats/codecs/audio/Hively") +-- local tune, err = Hively.parse(buf, 0, buffer.len(buf)) -- the replayer's Tune +-- local song = Hively.module(tune) -- a Types.Module-shaped value with render() +-- local dec = Hively.decoder(tune, { sampleRate = 44100 }) -- a Types.Decoder +-- +-- Not supported: hvl2wav's -a auto gain; a speed multiplier of 4 at 44.1 kHz renders 880 samples per 50 Hz frame +-- (hvl2wav pads each frame to 882 with stale samples). +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Load = require("@formats/codecs/audio/Hively/Load") +local Player = require("@formats/codecs/audio/Hively/Player") +local Pcm = require("@formats/codecs/audio/Pcm") + +local Hively = {} + +export type Tune = Load.Tune +export type RenderOptions = { + sampleRate: number?, -- default 44100 (the replayer runs at any rate: 8000..192000) + subsong: number?, -- 0 = the main song (default), 1..n the subsongs + stereo: number?, -- AHX stereo separation 0..4 (0 mono, 4 = 100 % Amiga L R R L); default 0 as hvl2wav. HVL: the file's + loop: boolean?, -- keep playing past the song end (frames / duration still give one pass) + maxDuration: number?, -- seconds, default 600 (hvl2wav's 10 minute limit) +} + +-- parse(b, base?, limit?) -> Tune | nil, Err +function Hively.parse(b: buffer, base: number?, limit: number?): (Tune?, Err.Err?) + local tune, msg, kind = Load.parse(b, base or 0, limit or buffer.len(b)) + if not tune then + return nil, Err.from(msg or "corrupt", nil, kind) + end + return tune, nil +end + +local function settings(tune: Tune, opts: RenderOptions?): (number?, number, number, Err.Err?) + local o: RenderOptions = opts or {} + local rate = o.sampleRate or 44100 + if type(rate) ~= "number" or rate < 8000 or rate > 192000 or rate % 1 ~= 0 then + return nil, 0, 0, Err.new(Err.ARG, "render: sampleRate must be an integer 8000..192000") + end + local sub = o.subsong or 0 + if type(sub) ~= "number" or sub < 0 or sub > #tune.subsongs or sub % 1 ~= 0 then + return nil, 0, 0, Err.new(Err.ARG, string.format("render: subsong must be 0..%d", #tune.subsongs)) + end + return rate, sub, tonumber(o.stereo) or 0, nil +end + +-- frameCount(tune, opts?) -> 50 Hz frames until the song end (as hvl2wav stops), capped by maxDuration +function Hively.frameCount(tune: Tune, opts: RenderOptions?): number + local rate, sub, stereo = settings(tune, opts) + local st = rate and Player.new(tune, rate :: number, stereo, sub) + if not st then + return 0 + end + local maxFrames = math.floor(((opts and opts.maxDuration) or 600) * 50) + local n = 0 + while n < maxFrames and not st.songEndReached do + for _ = 1, tune.speedMultiplier do + Player.irq(st, false) + end + n += 1 + end + return n +end + +-- decoder(tune, opts?) -> Types.Decoder | nil, Err +function Hively.decoder(tune: Tune, opts: RenderOptions?): (Types.Decoder?, Err.Err?) + local rate, sub, stereo, err = settings(tune, opts) + if not rate then + return nil, err + end + local sr = rate :: number + local mult = tune.speedMultiplier + local perIrq = sr // 50 // mult + local perFrame = perIrq * mult + local nframes = Hively.frameCount(tune, opts) + local frames = nframes * perFrame + local loop = opts ~= nil and opts.loop == true + local st = Player.new(tune, sr, stereo, sub) :: Player.State + local fbuf = buffer.create(perFrame * 8) + local fpos, ffill = 0, 0 -- read position / filled frames inside fbuf + local pos = 0 + + local function nextFrame() + for k = 0, mult - 1 do + Player.irq(st, true) + Player.mix(st, fbuf, k * perIrq, perIrq) + end + fpos, ffill = 0, perFrame + end + + local dec = { + sampleRate = sr, + channels = 2, + frames = frames, + duration = frames / sr, + bitrate = 0, + tags = { title = if tune.title ~= "" then tune.title else nil } :: Types.Tags, + } + local function read(_self: any, n: number, out: buffer?): (buffer, number) + n = math.max(0, math.floor(n)) + if not loop then + n = math.min(n, frames - pos) + end + local b = out + if not b or buffer.len(b) < n * 8 then + b = buffer.create(math.max(n, 1) * 8) + end + local ob = b :: buffer + local done = 0 + while done < n do + if fpos >= ffill then + nextFrame() + end + local k = math.min(n - done, ffill - fpos) + buffer.copy(ob, done * 8, fbuf, fpos * 8, k * 8) + fpos += k + done += k + end + pos += n + return ob, n + end + dec.read = read :: any + local scratch = buffer.create(4096 * 8) + dec.seek = function(_self: any, seconds: number) + local target = math.max(0, math.floor((tonumber(seconds) or 0) * sr)) + if not loop then + target = math.min(target, frames) + end + if target < pos then + st = Player.new(tune, sr, stereo, sub) :: Player.State + pos, fpos, ffill = 0, 0, 0 + end + while pos < target do + read(nil, math.min(4096, target - pos), scratch) + end + end :: any + dec.position = function(_self: any): number + return pos / sr + end :: any + return (dec :: any) :: Types.Decoder, nil +end + +-- module(tune) -> a Types.Module-shaped value (kind "music"): tracks as patterns (rows * 6 bytes: note, instrument, +-- fx, param, fxb, paramb), positions, instruments with their play lists, and render(opts) -> Decoder +function Hively.module(tune: Tune): Types.Module + local patterns = {} + for t = 0, tune.trackNr do + local data = buffer.create(tune.trackLength * 6) + buffer.copy(data, 0, tune.tracks, t * 64 * 6, tune.trackLength * 6) + patterns[t + 1] = { rows = tune.trackLength, data = data } + end + local order, positions = {}, {} + for i = 0, tune.positionNr - 1 do + order[i + 1] = i + local tr, tp = {}, {} + for c = 0, tune.channels - 1 do + tr[c + 1] = buffer.readu8(tune.positions, (i * 16 + c) * 2) + tp[c + 1] = buffer.readi8(tune.positions, (i * 16 + c) * 2 + 1) + end + positions[i + 1] = { tracks = tr, transpose = tp } + end + local m: any = { + kind = "music", + format = tune.format, + title = tune.title, + channels = tune.channels, + speed = 6, + tempo = 125 * tune.speedMultiplier, -- 50 Hz player calls per speed multiplier (a tick lasts 2.5 / tempo s) + patterns = patterns, + order = order, + positions = positions, + restart = tune.restart, + subsongs = table.clone(tune.subsongs), + instruments = tune.instruments, + samples = {}, + meta = { + source = { + format = tune.format, + version = tune.version, + speedMultiplier = tune.speedMultiplier, + trackLength = tune.trackLength, + tracks = tune.trackNr + 1, + mixgain = if tune.format == "hvl" then tune.mixgain else nil, + stereo = if tune.format == "hvl" then tune.stereo else nil, + }, + }, + tune = tune, + } + m.render = function(self: any, opts: RenderOptions?): Types.Decoder + local dec, derr = Hively.decoder(self.tune, opts) + if dec then + return dec + end + -- the Types contract returns a Decoder: a failed render is an empty one carrying the Err + local empty: any = Pcm.audioDecoder(Types.Audio.new(44100, 2, 0)) + empty.err = derr + return empty + end + return m :: Types.Module +end + +return Hively diff --git a/src/Formats/music/midi/Render.luau b/src/Formats/codecs/audio/MidiRender.luau similarity index 65% rename from src/Formats/music/midi/Render.luau rename to src/Formats/codecs/audio/MidiRender.luau index 9b4e1e5..c0c31e7 100644 --- a/src/Formats/music/midi/Render.luau +++ b/src/Formats/codecs/audio/MidiRender.luau @@ -1,8 +1,9 @@ --!strict --- music/midi/Render: the tempo map (ticks -> seconds, as python mido computes lengths), the time-ordered event list, +-- codecs/audio/MidiRender: the tempo map (ticks -> seconds, as python mido computes lengths), the time-ordered event list, -- and the audio Decoder that plays a Midi through codecs/audio/SoundFont's synth (a SoundFont bank, or the built-in -- waveform set). Format 0 / 1: one tempo map from every track's tempo events, tracks merged (ties keep track order). --- Format 2: each track is its own song with its own tempo map, played one after another. +-- Format 2: each track is its own song with its own tempo map, played one after another. Shared by every format that +-- decodes to a Types.Midi (music/midi, mus, xmi, hmp): attach() adds the meta summary and the render method. local Err = require("@formats/core/Err") local Types = require("@formats/Types") local SoundFont = require("@formats/codecs/audio/SoundFont") @@ -208,6 +209,14 @@ function Render.decoder(midi: Types.Midi, opts: RenderOptions?): (Types.Decoder? bitrate = 0, tags = {} :: Types.Tags, } + local mtags = type(midi.meta) == "table" and midi.meta.tags + if type(mtags) == "table" then + for k, v in mtags do + if type(k) == "string" and type(v) == "string" then + dec.tags[k] = v + end + end + end for _, t in midi.tracks do if t.name and not dec.tags.title then dec.tags.title = t.name @@ -258,4 +267,93 @@ function Render.decoder(midi: Types.Midi, opts: RenderOptions?): (Types.Decoder? return (dec :: any) :: Types.Decoder, nil end +-- tempoBytes(division, ticksPerSecond) -> the 3 data bytes of a tempo meta event making each tick last +-- 1 / ticksPerSecond seconds at that division (for formats with a fixed tick rate: MUS, XMIDI, HMP / HMI) +function Render.tempoBytes(division: number, ticksPerSecond: number): { number } + local us = math.clamp(math.floor(division * 1e6 / ticksPerSecond + 0.5), 1, 0xFFFFFF) + return { us // 65536, (us // 256) % 256, us % 256 } +end + +-- ------------------------------------------------------------------------------------------------ durations +export type PendingOff = { tick: number, onTick: number, ev: Types.MidiEvent } + +-- merge(events, offs) -> one tick-ordered event list: for formats that store a duration with each note (XMIDI, HMI). +-- events are in file order (ticks never decrease); offs are the generated note-offs. At equal ticks an off whose note +-- started earlier goes before the file's events, an off of a zero-length note after them. +function Render.merge(events: { Types.MidiEvent }, offs: { PendingOff }): { Types.MidiEvent } + for i, o in offs do + (o :: any).seq = i + end + table.sort(offs, function(a: any, b: any): boolean + if a.tick ~= b.tick then + return a.tick < b.tick + end + return a.seq < b.seq + end) + local out: { Types.MidiEvent } = table.create(#events + #offs) :: { Types.MidiEvent } + local k = 1 + for _, ev in events do + while k <= #offs and (offs[k].tick < ev.tick or (offs[k].tick == ev.tick and offs[k].onTick < ev.tick)) do + table.insert(out, offs[k].ev) + k += 1 + end + table.insert(out, ev) + end + for j = k, #offs do + table.insert(out, offs[j].ev) + end + return out +end + +-- ------------------------------------------------------------------------------------------------ attach +local function render(self: Types.Midi, opts: RenderOptions?): Types.Decoder + local dec, err = Render.decoder(self, opts) + if not dec then + -- the Types contract returns a Decoder; a failed render is an empty one (Midi.render returns the Err) + local empty: any = { + sampleRate = 44100, channels = 2, frames = 0, duration = 0, bitrate = 0, tags = {}, err = err, + read = function(_self: any, _n: number, out: buffer?): (buffer, number) + return out or buffer.create(0), 0 + end, + seek = function() end, + position = function(): number + return 0 + end, + } + return empty + end + return dec +end + +-- summarize(midi): meta.tempos / timeSignatures / keySignatures / length from the events +function Render.summarize(midi: Types.Midi) + local tempos, sigs, keys = {}, {}, {} + local map = Render.tempoMap(midi) + for ti, t in midi.tracks do + for _, ev in t.events do + if ev.type == "meta" then + local d = ev.data :: { number } + if ev.meta == 0x51 and #d >= 3 then + table.insert(tempos, { tick = ev.tick, track = ti, usPerQuarter = d[1] * 65536 + d[2] * 256 + d[3], bpm = 60000000 / math.max(1, d[1] * 65536 + d[2] * 256 + d[3]), seconds = Render.seconds(map, ev.tick) }) + elseif ev.meta == 0x58 and #d >= 4 then + table.insert(sigs, { tick = ev.tick, track = ti, numerator = d[1], denominator = 2 ^ math.min(d[2], 31), clocksPerClick = d[3], notated32ndsPerBeat = d[4] }) + elseif ev.meta == 0x59 and #d >= 2 then + table.insert(keys, { tick = ev.tick, track = ti, sharps = if d[1] >= 128 then d[1] - 256 else d[1], minor = d[2] == 1 }) + end + end + end + end + midi.meta.tempos = tempos + midi.meta.timeSignatures = sigs + midi.meta.keySignatures = keys + midi.meta.length = Render.length(midi) +end + +-- attach(midi, source): what every MIDI-like decoder does last: the meta summary, meta.source and the render method +function Render.attach(midi: Types.Midi, source: { [string]: any }) + Render.summarize(midi) + midi.meta.source = source + midi.render = render +end + return Render diff --git a/src/Formats/codecs/audio/Musepack/Decode.luau b/src/Formats/codecs/audio/Musepack/Decode.luau new file mode 100644 index 0000000..8b96245 --- /dev/null +++ b/src/Formats/codecs/audio/Musepack/Decode.luau @@ -0,0 +1,899 @@ +--!strict +--!native +--!optimize 2 +-- codecs/audio/Musepack/Decode: one Musepack SV7 / SV8 frame (1152 samples per channel): the bitstream (band +-- resolutions, scalefactor indices, quantised subband samples, with SV8's canonical Huffman / enumerative codes), +-- requantisation (M/S or L/R) and the 32-band polyphase synthesis. A line-by-line port of libmpcdec's mpc_decoder.c, +-- requant.c and synth_filter.c (musepack_src_r475, BSD-3-Clause, (c) The Musepack Development Team, +-- licenses/libmpcdec-BSD.txt) in double precision float. The bit reader is module state (decoding is synchronous) over +-- a buffer the caller pads by at least PAD bytes past `limit`: the band loops stop as soon as the position passes the +-- limit, so every read stays inside the buffer. No error / assert: failures return nil, "message". +local T = require("@formats/codecs/audio/Musepack/Tables") + +local readu32, bswap, extract, band, bor, rshift, lshift, bnot, bxor = + buffer.readu32, bit32.byteswap, bit32.extract, bit32.band, bit32.bor, bit32.rshift, bit32.lshift, bit32.bnot, bit32.bxor +local abs = math.abs + +local Decode = {} +Decode.PAD = 8192 +Decode.DELAY = 481 -- MPC_DECODER_SYNTH_DELAY +Decode.FRAME = 1152 + +-- ------------------------------------------------------------------------------------------------ tables +local L = T.lut +local HDR, SCFI7, DSCF7 = L(T.HuffHdr), L(T.HuffSCFI), L(T.HuffDSCF) +local Q7: { { T.Lut } } = { + { L(T.HuffQ1_0), L(T.HuffQ1_1) }, + { L(T.HuffQ2_0), L(T.HuffQ2_1) }, + { L(T.HuffQ3_0), L(T.HuffQ3_1) }, + { L(T.HuffQ4_0), L(T.HuffQ4_1) }, + { L(T.HuffQ5_0), L(T.HuffQ5_1) }, + { L(T.HuffQ6_0), L(T.HuffQ6_1) }, + { L(T.HuffQ7_0), L(T.HuffQ7_1) }, +} +local BANDS8 = L(T.H_Bands, T.S_Bands) +local SCFI8 = { L(T.H_SCFI_1, T.S_SCFI_1), L(T.H_SCFI_2, T.S_SCFI_2) } +local DSCF8 = { L(T.H_DSCF_1, T.S_DSCF_1), L(T.H_DSCF_2, T.S_DSCF_2) } +local RES8 = { L(T.H_Res_1, T.S_Res_1), L(T.H_Res_2, T.S_Res_2) } +local Q1_8 = L(T.H_Q1, T.S_Q1) +local Q9UP = L(T.H_Q9up, T.S_Q9up) +-- mpc_can_Q[res - 2][0 / 1] for res 2 and 5 .. 8; res 3 / 4 use Q34[res - 2] +local Q8: { [number]: { T.Lut } } = { + [2] = { L(T.H_Q2_1, T.S_Q2_1), L(T.H_Q2_2, T.S_Q2_2) }, + [5] = { L(T.H_Q5_1, T.S_Q5_1), L(T.H_Q5_2, T.S_Q5_2) }, + [6] = { L(T.H_Q6_1, T.S_Q6_1), L(T.H_Q6_2, T.S_Q6_2) }, + [7] = { L(T.H_Q7_1, T.S_Q7_1), L(T.H_Q7_2, T.S_Q7_2) }, + [8] = { L(T.H_Q8_1, T.S_Q8_1), L(T.H_Q8_2, T.S_Q8_2) }, +} +local Q34 = { L(T.H_Q3, T.S_Q3), L(T.H_Q4, T.S_Q4) } +local THRES = { [2] = 3, [5] = 1, [6] = 3, [7] = 4, [8] = 8 } +local CC, DC, RES_BIT = T.CC, T.DC, T.RES_BIT +local CNK, CNK_LEN, CNK_LOST, LOG2, LOG2_LOST = T.CNK, T.CNK_LEN, T.CNK_LOST, T.LOG2, T.LOG2_LOST + +-- the f32 rounding of the C tables (libmpcdec decodes in single precision) +local F32 = buffer.create(4) +local function f32(x: number): number + buffer.writef32(F32, 0, x) + return buffer.readf32(F32, 0) +end +for i, v in CC do + CC[i] = f32(v) +end + +-- SCF[i]: the scalefactor of index i (0 .. 255, the index's low byte): 2^-15 * 0.83298...^(s - 1), s = i as int8 +-- (libmpcdec's mpc_decoder_scale_output in float mode: 1 dB steps, the table filled outwards from index 1) +local SCF = table.create(256, 0) +do + local f1 = 1 / 32768 + local f2 = f1 + SCF[2] = f32(f1) + f1 *= 0.83298066476582673961 + f2 *= 1 / 0.83298066476582673961 + for n = 1, 128 do + SCF[band(1 + n, 255) + 1] = f32(f1) + SCF[band(1 - n, 255) + 1] = f32(f2) + f1 *= 0.83298066476582673961 + f2 *= 1 / 0.83298066476582673961 + end +end + +-- the synthesis window D (Di_opt / 65536), 32 x 16, row-major +local DW = table.create(512, 0) +for i, v in T.DI do + DW[i] = f32(v / 65536) +end + +-- ------------------------------------------------------------------------------------------------ bit reader +local B: buffer = buffer.create(0) +local P = 0 -- bit position + +local function bits(n: number): number + if n <= 0 then + return 0 + end + if n > 24 then + local hi = bits(n - 16) + return hi * 65536 + bits(16) + end + local w = bswap(readu32(B, rshift(P, 3))) + local v = extract(w, 32 - band(P, 7) - n, n) + P += n + return v +end + +local function peek16(): number + local w = bswap(readu32(B, rshift(P, 3))) + return extract(w, 16 - band(P, 7), 16) +end + +-- a table-driven Huffman symbol (plain or canonical) +local function huff(t: T.Lut): number + local code = peek16() + local k = rshift(code, 8) + 1 + local n = t.len[k] + if n > 0 then + P += n + return t.val[k] + end + local j = t.val[k] + local codes = t.codes + while code < codes[j] do + j += 1 + end + n = t.lens[j] + P += n + local sym = t.sym + if sym then + return sym[band(t.vals[j] - rshift(code, 16 - n), 255) + 1] or 0 + end + return t.vals[j] +end + +-- mpc_bits_log_dec: 0 .. max +local function logDec(max: number): number + if max <= 0 then + return 0 + end + local v = 0 + local len, lost = LOG2[max], LOG2_LOST[max] + if len > 1 then + v = bits(len - 1) + end + if v >= lost then + v = v * 2 + bits(1) - lost + end + return v +end + +-- mpc_bits_enum_dec: an n-bit word with k bits set +local function enumDec(k: number, n: number): number + local out = 0 + local code = bits(CNK_LEN[k][n] - 1) + local lost = CNK_LOST[k][n] + if code >= lost then + code = code * 2 + bits(1) - lost + end + repeat + n -= 1 + local c = CNK[k][n + 1] + if code >= c then + out = bor(out, lshift(1, n)) + code -= c + k -= 1 + end + until k <= 0 or n <= 0 + return out +end + +-- mpc_random_int: two polynomial counters, XORed +local PARITY = table.create(256, 0) +for i = 0, 255 do + local p, v = 0, i + while v > 0 do + p = bxor(p, band(v, 1)) + v = rshift(v, 1) + end + PARITY[i + 1] = p +end + +-- ------------------------------------------------------------------------------------------------ synthesis +-- mpc_compute_new_V: 32 subband samples Y[y .. y + 31] -> 64 V values at V[o .. o + 63] (the ISO 11172-3 matrixing +-- through Byeong Gi Lee's fast DCT) +local function newV(Y: { number }, y: number, V: { number }, o: number) + local A00 = Y[y] + Y[y + 31] + local A01 = Y[y + 1] + Y[y + 30] + local A02 = Y[y + 2] + Y[y + 29] + local A03 = Y[y + 3] + Y[y + 28] + local A04 = Y[y + 4] + Y[y + 27] + local A05 = Y[y + 5] + Y[y + 26] + local A06 = Y[y + 6] + Y[y + 25] + local A07 = Y[y + 7] + Y[y + 24] + local A08 = Y[y + 8] + Y[y + 23] + local A09 = Y[y + 9] + Y[y + 22] + local A10 = Y[y + 10] + Y[y + 21] + local A11 = Y[y + 11] + Y[y + 20] + local A12 = Y[y + 12] + Y[y + 19] + local A13 = Y[y + 13] + Y[y + 18] + local A14 = Y[y + 14] + Y[y + 17] + local A15 = Y[y + 15] + Y[y + 16] + local B00 = A00 + A15 + local B01 = A01 + A14 + local B02 = A02 + A13 + local B03 = A03 + A12 + local B04 = A04 + A11 + local B05 = A05 + A10 + local B06 = A06 + A09 + local B07 = A07 + A08 + local B08 = (A00 - A15) * 0.5024192929 + local B09 = (A01 - A14) * 0.5224986076 + local B10 = (A02 - A13) * 0.5669440627 + local B11 = (A03 - A12) * 0.6468217969 + local B12 = (A04 - A11) * 0.7881546021 + local B13 = (A05 - A10) * 1.0606776476 + local B14 = (A06 - A09) * 1.7224471569 + local B15 = (A07 - A08) * 5.1011486053 + A00 = B00 + B07 + A01 = B01 + B06 + A02 = B02 + B05 + A03 = B03 + B04 + A04 = (B00 - B07) * 0.5097956061 + A05 = (B01 - B06) * 0.6013448834 + A06 = (B02 - B05) * 0.8999761939 + A07 = (B03 - B04) * 2.5629155636 + A08 = B08 + B15 + A09 = B09 + B14 + A10 = B10 + B13 + A11 = B11 + B12 + A12 = (B08 - B15) * 0.5097956061 + A13 = (B09 - B14) * 0.6013448834 + A14 = (B10 - B13) * 0.8999761939 + A15 = (B11 - B12) * 2.5629155636 + B00 = A00 + A03 + B01 = A01 + A02 + B02 = (A00 - A03) * 0.5411961079 + B03 = (A01 - A02) * 1.3065630198 + B04 = A04 + A07 + B05 = A05 + A06 + B06 = (A04 - A07) * 0.5411961079 + B07 = (A05 - A06) * 1.3065630198 + B08 = A08 + A11 + B09 = A09 + A10 + B10 = (A08 - A11) * 0.5411961079 + B11 = (A09 - A10) * 1.3065630198 + B12 = A12 + A15 + B13 = A13 + A14 + B14 = (A12 - A15) * 0.5411961079 + B15 = (A13 - A14) * 1.3065630198 + A00 = B00 + B01 + A01 = (B00 - B01) * 0.7071067691 + A02 = B02 + B03 + A03 = (B02 - B03) * 0.7071067691 + A04 = B04 + B05 + A05 = (B04 - B05) * 0.7071067691 + A06 = B06 + B07 + A07 = (B06 - B07) * 0.7071067691 + A08 = B08 + B09 + A09 = (B08 - B09) * 0.7071067691 + A10 = B10 + B11 + A11 = (B10 - B11) * 0.7071067691 + A12 = B12 + B13 + A13 = (B12 - B13) * 0.7071067691 + A14 = B14 + B15 + A15 = (B14 - B15) * 0.7071067691 + V[o + 48] = -A00 + V[o] = A01 + V[o + 8] = A03 + V[o + 40] = -A02 - A03 + V[o + 12] = A07 + local t = A05 + A07 + V[o + 4] = t + V[o + 36] = -(t + A06) + V[o + 44] = -A04 - A06 - A07 + V[o + 14] = A15 + t = A11 + A15 + V[o + 10] = t + V[o + 6] = t + A13 + t = A09 + A13 + A15 + V[o + 2] = t + t = -t - A14 + V[o + 34] = t + V[o + 38] = t + A09 - A10 - A11 + t = -(A12 + A14 + A15) + V[o + 46] = t - A08 + V[o + 42] = t - A10 - A11 + A00 = (Y[y] - Y[y + 31]) * 0.5006030202 + A01 = (Y[y + 1] - Y[y + 30]) * 0.5054709315 + A02 = (Y[y + 2] - Y[y + 29]) * 0.5154473186 + A03 = (Y[y + 3] - Y[y + 28]) * 0.5310425758 + A04 = (Y[y + 4] - Y[y + 27]) * 0.5531039238 + A05 = (Y[y + 5] - Y[y + 26]) * 0.5829349756 + A06 = (Y[y + 6] - Y[y + 25]) * 0.6225041151 + A07 = (Y[y + 7] - Y[y + 24]) * 0.6748083234 + A08 = (Y[y + 8] - Y[y + 23]) * 0.7445362806 + A09 = (Y[y + 9] - Y[y + 22]) * 0.8393496275 + A10 = (Y[y + 10] - Y[y + 21]) * 0.9725682139 + A11 = (Y[y + 11] - Y[y + 20]) * 1.1694399118 + A12 = (Y[y + 12] - Y[y + 19]) * 1.4841645956 + A13 = (Y[y + 13] - Y[y + 18]) * 2.0577809811 + A14 = (Y[y + 14] - Y[y + 17]) * 3.4076085091 + A15 = (Y[y + 15] - Y[y + 16]) * 10.1900081635 + B00 = A00 + A15 + B01 = A01 + A14 + B02 = A02 + A13 + B03 = A03 + A12 + B04 = A04 + A11 + B05 = A05 + A10 + B06 = A06 + A09 + B07 = A07 + A08 + B08 = (A00 - A15) * 0.5024192929 + B09 = (A01 - A14) * 0.5224986076 + B10 = (A02 - A13) * 0.5669440627 + B11 = (A03 - A12) * 0.6468217969 + B12 = (A04 - A11) * 0.7881546021 + B13 = (A05 - A10) * 1.0606776476 + B14 = (A06 - A09) * 1.7224471569 + B15 = (A07 - A08) * 5.1011486053 + A00 = B00 + B07 + A01 = B01 + B06 + A02 = B02 + B05 + A03 = B03 + B04 + A04 = (B00 - B07) * 0.5097956061 + A05 = (B01 - B06) * 0.6013448834 + A06 = (B02 - B05) * 0.8999761939 + A07 = (B03 - B04) * 2.5629155636 + A08 = B08 + B15 + A09 = B09 + B14 + A10 = B10 + B13 + A11 = B11 + B12 + A12 = (B08 - B15) * 0.5097956061 + A13 = (B09 - B14) * 0.6013448834 + A14 = (B10 - B13) * 0.8999761939 + A15 = (B11 - B12) * 2.5629155636 + B00 = A00 + A03 + B01 = A01 + A02 + B02 = (A00 - A03) * 0.5411961079 + B03 = (A01 - A02) * 1.3065630198 + B04 = A04 + A07 + B05 = A05 + A06 + B06 = (A04 - A07) * 0.5411961079 + B07 = (A05 - A06) * 1.3065630198 + B08 = A08 + A11 + B09 = A09 + A10 + B10 = (A08 - A11) * 0.5411961079 + B11 = (A09 - A10) * 1.3065630198 + B12 = A12 + A15 + B13 = A13 + A14 + B14 = (A12 - A15) * 0.5411961079 + B15 = (A13 - A14) * 1.3065630198 + A00 = (B00 + B01) + A01 = (B00 - B01) * 0.7071067691 + A02 = (B02 + B03) + A03 = (B02 - B03) * 0.7071067691 + A04 = (B04 + B05) + A05 = (B04 - B05) * 0.7071067691 + A06 = (B06 + B07) + A07 = (B06 - B07) * 0.7071067691 + A08 = (B08 + B09) + A09 = (B08 - B09) * 0.7071067691 + A10 = (B10 + B11) + A11 = (B10 - B11) * 0.7071067691 + A12 = (B12 + B13) + A13 = (B12 - B13) * 0.7071067691 + A14 = (B14 + B15) + A15 = (B14 - B15) * 0.7071067691 + V[o + 15] = A15 + t = A07 + A15 + V[o + 13] = t + t += A11 + V[o + 11] = t + V[o + 5] = t + A05 + A13 + t = A03 + A11 + A15 + V[o + 9] = t + V[o + 7] = t + A13 + t = A01 + A09 + A13 + A15 + V[o + 1] = t + V[o + 33] = -t - A14 + t = A05 + A07 + A09 + A13 + A15 + V[o + 3] = t + V[o + 35] = -t - A06 - A14 + t = -(A10 + A11 + A13 + A14 + A15) + V[o + 37] = t - A05 - A06 - A07 + V[o + 39] = t - A02 - A03 + t += A13 - A12 + V[o + 41] = t - A02 - A03 + V[o + 43] = t - A04 - A06 - A07 + t = -(A08 + A12 + A14 + A15) + V[o + 47] = t - A00 + V[o + 45] = t - A04 - A06 - A07 + for i = 0, 15 do + V[o + 32 - i] = -V[o + i] + end + for i = 33, 47 do + V[o + 96 - i] = V[o + i] + end +end +-- ------------------------------------------------------------------------------------------------ state +export type State = { + version: number, -- 7 | 8 + maxBand: number, -- the highest band index (0 .. 31) + ms: boolean, + channels: number, + resL: { number }, -- [band + 1] + resR: { number }, + scfL: { number }, -- [band * 3 + m + 1] + scfR: { number }, + scfiL: { number }, + scfiR: { number }, + dscfL: { boolean }, + dscfR: { boolean }, + msf: { boolean }, + qL: { number }, -- [band * 36 + k + 1] + qR: { number }, + yL: { number }, -- [n * 32 + band + 1], n = 0 .. 35 + yR: { number }, + vL: { number }, -- synthesis history, 2304 + 960 + vR: { number }, + r1: number, + r2: number, + lastMaxBand: number, +} + +function Decode.state(version: number, maxBand: number, ms: boolean, channels: number): State + local st: State = { + version = version, + maxBand = maxBand, + ms = ms, + channels = channels, + resL = table.create(33, 0), + resR = table.create(33, 0), + scfL = table.create(99, 0), + scfR = table.create(99, 0), + scfiL = table.create(33, 0), + scfiR = table.create(33, 0), + dscfL = table.create(33, false), + dscfR = table.create(33, false), + msf = table.create(33, false), + qL = table.create(32 * 36, 0), + qR = table.create(32 * 36, 0), + yL = table.create(36 * 32, 0), + yR = table.create(36 * 32, 0), + vL = table.create(2304 + 960, 0), + vR = table.create(2304 + 960, 0), + r1 = 1, + r2 = 1, + lastMaxBand = 0, + } + return st +end + +-- reset(st, scf): forget the history (before a seek); scf = the scalefactor indices to assume (libmpcdec: 0 at the +-- start of the stream, 0x01010101 in the middle of an SV7 stream). The noise generator restarts too, so a seek +-- decodes like libmpcdec seeking in a freshly opened stream. +function Decode.reset(st: State, scf: number) + for i = 1, 99 do + st.scfL[i] = scf + st.scfR[i] = scf + end + for i = 1, 33 do + st.resL[i], st.resR[i] = 0, 0 + st.dscfL[i], st.dscfR[i] = false, false + st.msf[i] = false + end + for i = 1, 2304 + 960 do + st.vL[i], st.vR[i] = 0, 0 + end + st.lastMaxBand = 0 + st.r1, st.r2 = 1, 1 +end + +local function noise(st: State, q: { number }, o: number) + local r1, r2 = st.r1, st.r2 + for k = 0, 35 do + local t1 = PARITY[band(r1, 0xF5) + 1] + local t2 = PARITY[band(rshift(r2, 25), 0x63) + 1] + r1 = bor(rshift(r1, 1), lshift(t1, 31)) + r2 = bor(band(lshift(r2, 1), 0xFFFFFFFF), t2) + local t = bxor(r1, r2) + q[o + k] = band(rshift(t, 24), 255) + band(rshift(t, 16), 255) + band(rshift(t, 8), 255) + band(t, 255) - 510 + end + st.r1, st.r2 = r1, r2 +end + +-- ------------------------------------------------------------------------------------------------ SV7 +-- mpc_decoder_read_bitstream_sv7 -> true | nil, message +local function readSv7(st: State, limit: number): (boolean?, string?) + local resL, resR, msf = st.resL, st.resR, st.msf + local maxUsed = 0 + local ms = st.ms + resL[1] = bits(4) + resR[1] = bits(4) + if resL[1] ~= 0 or resR[1] ~= 0 then + if ms then + msf[1] = bits(1) == 1 + end + maxUsed = 1 + end + for n = 1, st.maxBand do + local idx = huff(HDR) + resL[n + 1] = if idx ~= 4 then resL[n] + idx else bits(4) + idx = huff(HDR) + resR[n + 1] = if idx ~= 4 then resR[n] + idx else bits(4) + local l, r = resL[n + 1], resR[n + 1] + if l < -1 or l > 17 or r < -1 or r > 17 then + return nil, "bad band resolution" + end + if l ~= 0 or r ~= 0 then + if ms then + msf[n + 1] = bits(1) == 1 + end + maxUsed = n + 1 + end + end + if resL[1] > 17 or resR[1] > 17 then + return nil, "bad band resolution" + end + -- SCFI + local scfiL, scfiR = st.scfiL, st.scfiR + for n = 1, maxUsed do + if resL[n] ~= 0 then + scfiL[n] = huff(SCFI7) + end + if resR[n] ~= 0 then + scfiR[n] = huff(SCFI7) + end + end + if P > limit then + return nil, "truncated frame" + end + -- SCF / DSCF + for n = 1, maxUsed do + for c = 1, 2 do + local res = if c == 1 then resL[n] else resR[n] + if res ~= 0 then + local scf = if c == 1 then st.scfL else st.scfR + local scfi = if c == 1 then scfiL[n] else scfiR[n] + local o = (n - 1) * 3 + local idx = huff(DSCF7) + local s0 = if idx ~= 8 then scf[o + 3] + idx else bits(6) + local s1, s2 + if scfi == 1 then + idx = huff(DSCF7) + s1 = if idx ~= 8 then s0 + idx else bits(6) + s2 = s1 + elseif scfi == 3 then + s1, s2 = s0, s0 + elseif scfi == 2 then + s1 = s0 + idx = huff(DSCF7) + s2 = if idx ~= 8 then s1 + idx else bits(6) + else + idx = huff(DSCF7) + s1 = if idx ~= 8 then s0 + idx else bits(6) + idx = huff(DSCF7) + s2 = if idx ~= 8 then s1 + idx else bits(6) + end + scf[o + 1] = if s0 > 1024 then 0x8080 else s0 + scf[o + 2] = if s1 > 1024 then 0x8080 else s1 + scf[o + 3] = if s2 > 1024 then 0x8080 else s2 + end + end + end + if P > limit then + return nil, "truncated frame" + end + -- samples + for n = 1, maxUsed do + for c = 1, 2 do + local res = if c == 1 then resL[n] else resR[n] + local q = if c == 1 then st.qL else st.qR + local o = (n - 1) * 36 + 1 + if res == -1 then + noise(st, q, o) + elseif res == 1 then + local tab = Q7[1][bits(1) + 1] + for k = 0, 35, 3 do + local idx = huff(tab) + q[o + k] = idx % 3 - 1 + q[o + k + 1] = (idx // 3) % 3 - 1 + q[o + k + 2] = idx // 9 - 1 + end + elseif res == 2 then + local tab = Q7[2][bits(1) + 1] + for k = 0, 35, 2 do + local idx = huff(tab) + q[o + k] = idx % 5 - 2 + q[o + k + 1] = idx // 5 - 2 + end + elseif res >= 3 and res <= 7 then + local tab = Q7[res][bits(1) + 1] + for k = 0, 35 do + q[o + k] = huff(tab) + end + elseif res >= 8 then + local nb, dc = RES_BIT[res], DC[res + 2] + for k = 0, 35 do + q[o + k] = bits(nb) - dc + end + end + if P > limit then + return nil, "truncated frame" + end + end + end + -- bands above maxUsed: silent + for n = maxUsed + 1, st.maxBand + 1 do + resL[n], resR[n] = 0, 0 + end + return true, nil +end + +-- ------------------------------------------------------------------------------------------------ SV8 +local function readSv8(st: State, key: boolean, limit: number): (boolean?, string?) + local resL, resR, msf = st.resL, st.resR, st.msf + local maxBand = st.maxBand + local maxUsed + if key then + maxUsed = logDec(maxBand + 1) + else + maxUsed = st.lastMaxBand + huff(BANDS8) + if maxUsed > 32 then + maxUsed -= 33 + end + end + if maxUsed > maxBand + 1 then + return nil, "bad band count" + end + st.lastMaxBand = maxUsed + if maxUsed > 0 then + local l, r = huff(RES8[1]), huff(RES8[1]) + resL[maxUsed] = if l > 15 then l - 17 else l + resR[maxUsed] = if r > 15 then r - 17 else r + for n = maxUsed - 1, 1, -1 do + l = huff(RES8[if resL[n + 1] > 2 then 2 else 1]) + resL[n + 1] + resL[n] = if l > 15 then l - 17 else l + r = huff(RES8[if resR[n + 1] > 2 then 2 else 1]) + resR[n + 1] + resR[n] = if r > 15 then r - 17 else r + end + if st.ms then + local tot = 0 + for n = 1, maxUsed do + if resL[n] ~= 0 or resR[n] ~= 0 then + tot += 1 + end + end + local cnt = logDec(tot) + local tmp = 0 + if cnt ~= 0 and cnt ~= tot then + tmp = enumDec(math.min(cnt, tot - cnt), tot) + end + if cnt * 2 > tot then + tmp = bnot(tmp) + end + for n = maxUsed, 1, -1 do + if resL[n] ~= 0 or resR[n] ~= 0 then + msf[n] = band(tmp, 1) == 1 + tmp = rshift(tmp, 1) + end + end + end + end + for n = maxUsed + 1, maxBand + 1 do + resL[n], resR[n] = 0, 0 + end + -- SCFI + local dscfL, dscfR = st.dscfL, st.dscfR + if key then + for n = 1, 32 do + dscfL[n], dscfR[n] = true, true + end + end + local scfiL, scfiR = st.scfiL, st.scfiR + for n = 1, maxUsed do + local cnt = -1 + if resL[n] ~= 0 then + cnt += 1 + end + if resR[n] ~= 0 then + cnt += 1 + end + if cnt >= 0 then + local tmp = huff(SCFI8[cnt + 1]) + if resL[n] ~= 0 then + scfiL[n] = rshift(tmp, 2 * cnt) + end + if resR[n] ~= 0 then + scfiR[n] = band(tmp, 3) + end + end + end + if P > limit then + return nil, "truncated frame" + end + -- SCF / DSCF + for n = 1, maxUsed do + for c = 1, 2 do + local res = if c == 1 then resL[n] else resR[n] + if res ~= 0 then + local scf = if c == 1 then st.scfL else st.scfR + local scfi = if c == 1 then scfiL[n] else scfiR[n] + local dscf = if c == 1 then dscfL else dscfR + local o = (n - 1) * 3 + if dscf[n] then + scf[o + 1] = bits(7) - 6 + dscf[n] = false + else + local tmp = huff(DSCF8[2]) + if tmp == 64 then + tmp += bits(6) + end + scf[o + 1] = band(scf[o + 3] - 25 + tmp, 127) - 6 + end + for m = 0, 1 do + if band(lshift(scfi, m), 2) == 0 then + local tmp = huff(DSCF8[1]) + if tmp == 31 then + tmp = 64 + bits(6) + end + scf[o + m + 2] = band(scf[o + m + 1] - 25 + tmp, 127) - 6 + else + scf[o + m + 2] = scf[o + m + 1] + end + end + end + end + end + if P > limit then + return nil, "truncated frame" + end + -- samples + for n = 1, maxUsed do + for c = 1, 2 do + local res = if c == 1 then resL[n] else resR[n] + local q = if c == 1 then st.qL else st.qR + local o = (n - 1) * 36 + 1 + if res == 2 then + local tabs = Q8[2] + local thres = 3 + local idx = 6 + for k = 0, 35, 3 do + local tmp = huff(tabs[if idx > thres then 2 else 1]) + local a, b, cc = tmp % 5 - 2, (tmp // 5) % 5 - 2, tmp // 25 - 2 + q[o + k], q[o + k + 1], q[o + k + 2] = a, b, cc + idx = rshift(idx, 1) + abs(a) + abs(b) + abs(cc) + end + elseif res == 1 then + local k = 0 + while k < 36 do + local kmax = k + 18 + local cnt = huff(Q1_8) + local idx = 0 + if cnt > 0 and cnt < 18 then + idx = enumDec(if cnt <= 9 then cnt else 18 - cnt, 18) + end + if cnt > 9 then + idx = bnot(idx) + end + while k < kmax do + q[o + k] = 0 + if band(idx, 0x20000) ~= 0 then + q[o + k] = bits(1) * 2 - 1 + end + idx = lshift(idx, 1) + k += 1 + end + end + elseif res == -1 then + noise(st, q, o) + elseif res == 3 or res == 4 then + local tab = Q34[res - 2] + for k = 0, 35, 2 do + local s = band(huff(tab), 255) + local s1, s2 = band(s, 15), rshift(s, 4) + q[o + k] = if s1 >= 8 then s1 - 16 else s1 + q[o + k + 1] = if s2 >= 8 then s2 - 16 else s2 + end + elseif res >= 5 and res <= 8 then + local tabs = Q8[res] + local thres = THRES[res] + local idx = 2 * thres + for k = 0, 35 do + local v = huff(tabs[if idx > thres then 2 else 1]) + q[o + k] = v + idx = rshift(idx, 1) + abs(v) + end + elseif res >= 9 then + local sh = res - 9 + local dc = DC[res + 2] + for k = 0, 35 do + local v = band(huff(Q9UP), 255) + if sh > 0 then + v = v * 2 ^ sh + bits(sh) + end + q[o + k] = v - dc + end + elseif res < -1 then + return nil, "bad band resolution" + end + if P > limit then + return nil, "truncated frame" + end + end + end + return true, nil +end + +-- ------------------------------------------------------------------------------------------------ requantisation +local function requant(st: State) + local resL, resR, msf = st.resL, st.resR, st.msf + local scfL, scfR, qL, qR, yL, yR = st.scfL, st.scfR, st.qL, st.qR, st.yL, st.yR + for b = 1, st.maxBand + 1 do + local rl, rr = resL[b], resR[b] + local ccl, ccr = CC[rl + 2] or 0, CC[rr + 2] or 0 + local ms = msf[b] + local o = (b - 1) * 36 + 1 + for part = 0, 2 do + local fl = if rl ~= 0 then f32(ccl * SCF[band(scfL[(b - 1) * 3 + part + 1], 255) + 1]) else 0 + local fr = if rr ~= 0 then f32(ccr * SCF[band(scfR[(b - 1) * 3 + part + 1], 255) + 1]) else 0 + local y = part * 12 * 32 + b + local qo = o + part * 12 + if ms then + for k = 0, 11 do + local l, r = fl * qL[qo + k], fr * qR[qo + k] + yL[y], yR[y] = l + r, l - r + y += 32 + end + else + for k = 0, 11 do + yL[y], yR[y] = fl * qL[qo + k], fr * qR[qo + k] + y += 32 + end + end + end + end +end + + +-- mpc_synthese_filter_float for one channel: 36 x 32 subband samples -> 1152 samples at out[base + i * step] +local function synth(V: { number }, Y: { number }, out: { number }, base: number, step: number) + table.move(V, 1, 960, 2305) + local o = 2304 + 1 + local dw = DW + local p = base + for n = 0, 35 do + o -= 64 + newV(Y, n * 32 + 1, V, o) + for k = 0, 31 do + local v = o + k + local d = k * 16 + 1 + out[p] = V[v] * dw[d] + V[v + 96] * dw[d + 1] + V[v + 128] * dw[d + 2] + V[v + 224] * dw[d + 3] + + V[v + 256] * dw[d + 4] + V[v + 352] * dw[d + 5] + V[v + 384] * dw[d + 6] + V[v + 480] * dw[d + 7] + + V[v + 512] * dw[d + 8] + V[v + 608] * dw[d + 9] + V[v + 640] * dw[d + 10] + V[v + 736] * dw[d + 11] + + V[v + 768] * dw[d + 12] + V[v + 864] * dw[d + 13] + V[v + 896] * dw[d + 14] + V[v + 992] * dw[d + 15] + p += step + end + end +end + +-- ------------------------------------------------------------------------------------------------ frames +-- frame(st, buf, bitPos, limitBits, key, out, base) -> the bit position after the frame | nil, message: decodes one +-- frame from buf (padded by PAD bytes past limitBits / 8) into out[base ..] (1152 * channels interleaved floats). +-- key: an SV8 key frame (the first of a block). bitPos < 0 decodes a silent frame (the synthesis tail). +function Decode.frame(st: State, buf: buffer, bitPos: number, limitBits: number, key: boolean, out: { number }, base: number): (number?, string?) + if bitPos >= 0 then + if rshift(limitBits, 3) + Decode.PAD > buffer.len(buf) or bitPos > limitBits then + return nil, "truncated frame" + end + B, P = buf, bitPos + local ok, err + if st.version == 8 then + ok, err = readSv8(st, key, limitBits) + else + ok, err = readSv7(st, limitBits) + end + B = buffer.create(0) + if not ok then + return nil, err + end + else + for b = 1, st.maxBand + 1 do + st.resL[b], st.resR[b] = 0, 0 + end + end + local pos = P + requant(st) + local ch = st.channels + synth(st.vL, st.yL, out, base, ch) + if ch > 1 then + synth(st.vR, st.yR, out, base + 1, ch) + end + return if bitPos >= 0 then pos else bitPos, nil +end + +-- bitsAt(buf, bitPos, n) -> n (1 .. 24) bits at bitPos (frame headers: the SV7 frame size); the caller keeps +-- bitPos / 8 + 4 inside buf +function Decode.bitsAt(buf: buffer, bitPos: number, n: number): number + local w = bswap(readu32(buf, rshift(bitPos, 3))) + return extract(w, 32 - band(bitPos, 7) - n, n) +end + +return Decode diff --git a/src/Formats/codecs/audio/Musepack/Tables.luau b/src/Formats/codecs/audio/Musepack/Tables.luau new file mode 100644 index 0000000..448ea85 --- /dev/null +++ b/src/Formats/codecs/audio/Musepack/Tables.luau @@ -0,0 +1,379 @@ +--!strict +-- codecs/audio/Musepack/Tables: the Musepack SV7 / SV8 Huffman tables, the synthesis window and the requantisation +-- constants. Ported from libmpcdec (musepack_src_r475: huffman.c, synth_filter.c, requant.c, mpc_bits_reader.c; +-- BSD-3-Clause, (c) The Musepack Development Team, licenses/libmpcdec-BSD.txt); the tables are transcribed by script. +-- Each Huffman table is a flat { code, length, value, ... } list sorted by descending left-aligned 16-bit code; +-- canonical (SV8) tables map value - (code >> (16 - length)) through their symbol list. lut(table, sym?) builds the +-- 8-bit first-level lookup the decoder uses. +local T = {} + +T.HuffHdr = { + 32768, 1, 0, 24576, 3, 1, 24064, 7, -4, 23936, 9, 3, 23808, 9, 4, 23552, 8, -5, 22528, 6, 2, 20480, 5, -3, 16384, 4, -2, 0, 2, -1, +} +T.HuffSCFI = { + 32768, 1, 1, 24576, 3, 2, 16384, 3, 0, 0, 2, 3, +} +T.HuffDSCF = { + 63488, 5, 5, 61440, 5, -4, 57344, 4, 3, 53248, 4, -3, 49152, 4, 8, 40960, 3, 1, 36864, 4, 0, 34816, 5, -5, 33792, 6, 7, 32768, 6, -7, + 24576, 3, -1, 16384, 3, 2, 12288, 4, 4, 10240, 5, 6, 8192, 5, -6, 0, 3, -2, +} +T.HuffQ1_0 = { + 57344, 3, 13, 56320, 6, 26, 55296, 6, 0, 54272, 6, 20, 53248, 6, 6, 49152, 4, 14, 45056, 4, 12, 40960, 4, 4, 36864, 4, 22, 35840, 6, 8, + 34816, 6, 18, 33792, 6, 24, 32768, 6, 2, 28672, 4, 16, 24576, 4, 10, 22528, 5, 17, 20480, 5, 9, 18432, 5, 1, 16384, 5, 25, 14336, 5, 5, + 12288, 5, 21, 10240, 5, 3, 8192, 5, 11, 6144, 5, 15, 4096, 5, 23, 2048, 5, 19, 0, 5, 7, +} +T.HuffQ1_1 = { + 32768, 1, 13, 32256, 7, 15, 31744, 7, 1, 31232, 7, 11, 30720, 7, 7, 30208, 7, 17, 29696, 7, 25, 29184, 7, 19, 29056, 9, 8, 28928, 9, 18, + 28800, 9, 2, 28672, 9, 24, 28160, 7, 3, 27648, 7, 23, 27136, 7, 21, 26624, 7, 5, 26368, 8, 0, 26112, 8, 26, 25856, 8, 6, 25600, 8, 20, + 24576, 6, 9, 20480, 4, 14, 16384, 4, 12, 12288, 4, 4, 8192, 4, 22, 4096, 4, 16, 0, 4, 10, +} +T.HuffQ2_0 = { + 61440, 4, 13, 57344, 4, 17, 53248, 4, 7, 49152, 4, 11, 48128, 6, 1, 47104, 6, 23, 46592, 7, 4, 46080, 7, 20, 45568, 7, 0, 45056, 7, 24, + 43008, 5, 22, 40960, 5, 10, 32768, 3, 12, 30720, 5, 2, 28672, 5, 14, 24576, 4, 6, 20480, 4, 18, 16384, 4, 8, 12288, 4, 16, 10240, 5, 9, + 8192, 5, 5, 6144, 5, 15, 4096, 5, 21, 2048, 5, 19, 0, 5, 3, +} +T.HuffQ2_1 = { + 63488, 5, 18, 61440, 5, 6, 59392, 5, 8, 59136, 8, 3, 59072, 10, 24, 59008, 10, 4, 58944, 10, 0, 58880, 10, 20, 58368, 7, 23, 57856, 7, 1, + 57344, 7, 19, 55296, 5, 16, 54784, 7, 15, 54272, 7, 21, 53760, 7, 9, 53248, 7, 5, 52224, 6, 2, 51200, 6, 10, 50176, 6, 14, 49152, 6, 22, + 32768, 2, 12, 24576, 3, 13, 16384, 3, 17, 8192, 3, 11, 0, 3, 7, +} +T.HuffQ3_0 = { + 57344, 3, 1, 53248, 4, 3, 49152, 4, -3, 40960, 3, 2, 32768, 3, -2, 16384, 2, 0, 0, 2, -1, +} +T.HuffQ3_1 = { + 49152, 2, 0, 32768, 2, -1, 16384, 2, 1, 12288, 4, -2, 10240, 5, 3, 8192, 5, -3, 0, 3, 2, +} +T.HuffQ4_0 = { + 57344, 3, 0, 49152, 3, -1, 40960, 3, 1, 32768, 3, -2, 24576, 3, 2, 20480, 4, -4, 16384, 4, 4, 8192, 3, 3, 0, 3, -3, +} +T.HuffQ4_1 = { + 57344, 3, 1, 53248, 4, 2, 49152, 4, -3, 32768, 2, 0, 24576, 3, -2, 20480, 4, 3, 18432, 5, -4, 16384, 5, 4, 0, 2, -1, +} +T.HuffQ5_0 = { + 61440, 4, 2, 59392, 5, 5, 58368, 6, -7, 57344, 6, 7, 53248, 4, -3, 49152, 4, 3, 47104, 5, -6, 45056, 5, 6, 40960, 4, -4, 36864, 4, 4, + 32768, 4, -5, 24576, 3, 0, 16384, 3, -1, 8192, 3, 1, 0, 3, -2, +} +T.HuffQ5_1 = { + 61440, 4, 3, 59392, 5, 4, 58880, 7, 6, 58624, 8, -7, 58368, 8, 7, 57344, 6, -6, 49152, 3, 0, 40960, 3, -1, 32768, 3, 1, 24576, 3, -2, + 16384, 3, 2, 14336, 5, -5, 12288, 5, 5, 8192, 4, -4, 0, 3, -3, +} +T.HuffQ6_0 = { + 63488, 5, 3, 61440, 5, -4, 60416, 6, -11, 59392, 6, 12, 57344, 5, 4, 55296, 5, 6, 53248, 5, -5, 51200, 5, 5, 49152, 5, 7, 47104, 5, -7, + 46080, 6, -12, 45056, 6, -13, 43008, 5, -6, 40960, 5, 8, 38912, 5, -8, 36864, 5, 9, 34816, 5, -9, 33792, 6, 13, 33280, 7, -15, 32768, 7, 15, + 28672, 4, 0, 26624, 5, -10, 24576, 5, 10, 20480, 4, -1, 16384, 4, 2, 12288, 4, 1, 8192, 4, -2, 7168, 6, 14, 6144, 6, -14, 4096, 5, 11, + 0, 4, -3, +} +T.HuffQ6_1 = { + 63488, 5, -6, 61440, 5, 6, 57344, 4, 1, 53248, 4, -1, 52736, 7, 10, 52224, 7, -10, 51968, 8, -11, 51840, 9, -12, 51808, 11, 13, 51800, 13, 15, + 51792, 13, -14, 51784, 13, 14, 51776, 13, -15, 51712, 10, -13, 51456, 8, 11, 51200, 8, 12, 50176, 6, -9, 49152, 6, 9, 45056, 4, -2, 40960, 4, 2, + 36864, 4, 3, 32768, 4, -3, 30720, 5, -7, 28672, 5, 7, 24576, 4, -4, 20480, 4, 4, 18432, 5, -8, 16384, 5, 8, 12288, 4, 5, 8192, 4, -5, + 0, 3, 0, +} +T.HuffQ7_0 = { + 64512, 6, 7, 63488, 6, 8, 62464, 6, 9, 61440, 6, -8, 60416, 6, 11, 59904, 7, 21, 59648, 8, -28, 59392, 8, 28, 58368, 6, -9, 57856, 7, -22, + 57344, 7, -21, 56320, 6, -10, 55296, 6, -11, 54272, 6, 10, 53248, 6, 12, 52224, 6, -13, 51712, 7, 22, 51200, 7, 23, 50176, 6, -12, 49152, 6, 13, + 48128, 6, 14, 47104, 6, -14, 46592, 7, -23, 46336, 8, -29, 46080, 8, 29, 45056, 6, -15, 44032, 6, 15, 43008, 6, 16, 41984, 6, -16, 41472, 7, -24, + 40960, 7, 24, 39936, 6, 17, 39424, 7, -25, 39168, 8, -30, 38912, 8, 30, 37888, 6, -17, 36864, 6, 18, 35840, 6, -18, 35328, 7, 25, 34816, 7, 26, + 33792, 6, 19, 33280, 7, -26, 32768, 7, -27, 30720, 5, 2, 29696, 6, -19, 28672, 6, 20, 26624, 5, -1, 26368, 8, -31, 26112, 8, 31, 25600, 7, 27, + 24576, 6, -20, 22528, 5, 1, 20480, 5, -5, 18432, 5, -3, 16384, 5, 3, 14336, 5, 0, 12288, 5, -2, 10240, 5, -4, 8192, 5, 4, 6144, 5, 5, + 4096, 5, -6, 2048, 5, 6, 0, 5, -7, +} +T.HuffQ7_1 = { + 63488, 5, -1, 61440, 5, 2, 59392, 5, -2, 57344, 5, 3, 57088, 8, -20, 57024, 10, 24, 57020, 14, 28, 57016, 14, -28, 57012, 14, -30, 57008, 14, 30, + 56992, 12, -27, 56988, 14, 29, 56984, 14, -29, 56980, 14, 31, 56976, 14, -31, 56960, 12, 27, 56832, 9, -22, 56320, 7, -17, 55296, 6, -11, 53248, 5, -3, + 51200, 5, 4, 49152, 5, -4, 48640, 7, 17, 48384, 8, 20, 48256, 9, 22, 48192, 10, -25, 48128, 10, -26, 47104, 6, 12, 45056, 5, 5, 43008, 5, -5, + 40960, 5, 6, 38912, 5, -6, 37888, 6, -12, 37376, 7, -18, 36864, 7, 18, 35840, 6, 13, 34816, 6, -13, 32768, 5, -7, 31744, 6, 14, 31488, 8, 21, + 31232, 8, -21, 30720, 7, -19, 28672, 5, 7, 26624, 5, 8, 25600, 6, -14, 24576, 6, -15, 22528, 5, -8, 21504, 6, 15, 20992, 7, 19, 20928, 10, 25, + 20864, 10, 26, 20736, 9, -23, 20608, 9, 23, 20480, 9, -24, 18432, 5, -9, 16384, 5, 9, 15360, 6, 16, 14336, 6, -16, 12288, 5, 10, 8192, 4, 0, + 6144, 5, -10, 4096, 5, 11, 0, 4, 1, +} +T.H_SCFI_1 = { + 32768, 1, 1, 16384, 2, 2, 0, 3, 3, +} +T.H_SCFI_2 = { + 32768, 2, 3, 16384, 3, 5, 6144, 5, 11, 1024, 6, 14, 0, 7, 15, +} +T.H_DSCF_1 = { + 40960, 3, 7, 16384, 4, 12, 10240, 5, 16, 6144, 6, 21, 3584, 7, 27, 1792, 8, 34, 896, 9, 41, 320, 10, 48, 128, 11, 53, 48, 12, 57, + 24, 13, 60, 0, 14, 63, +} +T.H_DSCF_2 = { + 24576, 3, 7, 12288, 4, 10, 6144, 5, 13, 4096, 6, 16, 2560, 7, 20, 1536, 8, 25, 896, 9, 31, 448, 10, 38, 224, 11, 45, 80, 12, 52, + 32, 13, 57, 12, 14, 61, 0, 15, 64, +} +T.H_Bands = { + 32768, 1, 1, 16384, 2, 2, 8192, 3, 3, 4096, 5, 6, 2048, 6, 8, 1536, 7, 10, 768, 8, 13, 512, 9, 16, 320, 10, 20, 192, 11, 25, + 16, 12, 31, 0, 13, 32, +} +T.H_Res_1 = { + 32768, 1, 1, 16384, 2, 2, 8192, 3, 3, 4096, 4, 4, 2048, 5, 5, 1024, 6, 6, 512, 7, 7, 256, 8, 8, 128, 9, 9, 64, 10, 10, + 32, 11, 11, 16, 12, 12, 8, 13, 13, 4, 14, 14, 2, 15, 15, 0, 16, 16, +} +T.H_Res_2 = { + 16384, 2, 3, 8192, 3, 4, 4096, 4, 5, 2048, 5, 6, 1024, 6, 7, 512, 7, 8, 256, 8, 9, 128, 9, 10, 64, 10, 11, 32, 11, 12, + 16, 12, 13, 0, 14, 16, +} +T.H_Q1 = { + 24576, 3, 7, 4096, 4, 10, 2048, 5, 11, 1024, 6, 12, 512, 7, 13, 256, 8, 14, 128, 9, 15, 64, 10, 16, 32, 11, 17, 0, 12, 18, +} +T.H_Q2_1 = { + 57344, 3, 7, 32768, 4, 14, 15360, 6, 38, 10752, 7, 53, 4608, 8, 74, 1536, 9, 92, 960, 10, 104, 96, 11, 119, 32, 12, 122, 0, 13, 124, +} +T.H_Q2_2 = { + 61440, 4, 15, 28672, 5, 30, 18432, 6, 44, 15360, 7, 62, 3072, 8, 92, 1920, 9, 104, 192, 10, 119, 64, 11, 122, 0, 12, 124, +} +T.H_Q3 = { + 57344, 3, 7, 32768, 4, 14, 20480, 5, 22, 9216, 6, 32, 2560, 7, 41, 512, 8, 46, 0, 9, 48, +} +T.H_Q4 = { + 61440, 4, 15, 36864, 5, 30, 13312, 6, 48, 6144, 7, 61, 1280, 8, 73, 256, 9, 78, 0, 10, 80, 0, 0, 90, +} +T.H_Q5_1 = { + 49152, 2, 3, 16384, 3, 6, 8192, 4, 8, 4096, 5, 10, 2048, 6, 12, 0, 7, 14, +} +T.H_Q5_2 = { + 24576, 3, 7, 8192, 4, 10, 4096, 5, 12, 0, 6, 14, +} +T.H_Q6_1 = { + 49152, 2, 3, 32768, 3, 6, 16384, 4, 10, 10240, 5, 14, 3072, 6, 19, 2048, 7, 22, 1024, 8, 26, 0, 9, 30, +} +T.H_Q6_2 = { + 20480, 4, 15, 8192, 5, 20, 4096, 6, 24, 1024, 7, 28, 0, 8, 30, +} +T.H_Q7_1 = { + 49152, 2, 3, 32768, 3, 6, 24576, 4, 10, 16384, 5, 16, 10240, 6, 24, 5120, 7, 34, 2560, 8, 44, 1024, 9, 54, 0, 10, 62, +} +T.H_Q7_2 = { + 24576, 5, 31, 9216, 6, 43, 4096, 7, 52, 512, 8, 60, 0, 9, 62, +} +T.H_Q8_1 = { + 49152, 2, 3, 32768, 3, 6, 28672, 4, 10, 22528, 5, 17, 14336, 6, 28, 10240, 7, 42, 6400, 8, 62, 3328, 9, 87, 640, 10, 113, 96, 11, 123, + 0, 12, 126, +} +T.H_Q8_2 = { + 38912, 6, 63, 10752, 7, 101, 1024, 8, 122, 0, 9, 126, +} +T.H_Q9up = { + 63488, 6, 63, 44032, 7, 125, 9728, 8, -45, 640, 9, -7, 64, 10, -2, 0, 11, -1, +} +T.S_SCFI_1 = { + 2, 3, 1, 0, +} +T.S_SCFI_2 = { + 15, 10, 14, 11, 13, 9, 7, 6, 5, 12, 8, 3, 2, 0, 4, 1, +} +T.S_DSCF_1 = { + 35, 34, 33, 36, 32, 30, 29, 27, 26, 37, 28, 25, 39, 38, 24, 23, 40, 22, 21, 20, 19, 43, 42, 41, 18, 17, 16, 15, 46, 45, 44, 14, + 13, 12, 11, 49, 48, 47, 31, 10, 9, 8, 7, 6, 52, 51, 50, 5, 4, 3, 54, 53, 2, 1, 0, 57, 56, 55, 63, 62, 61, 60, 59, 58, +} +T.S_DSCF_2 = { + 33, 32, 31, 30, 29, 34, 28, 27, 36, 35, 26, 37, 25, 38, 24, 23, 40, 39, 22, 21, 42, 41, 20, 19, 18, 45, 44, 43, 17, 16, 15, 14, + 48, 47, 46, 13, 12, 11, 10, 64, 52, 51, 50, 49, 9, 8, 7, 6, 55, 54, 53, 5, 4, 3, 58, 57, 56, 2, 1, 63, 62, 61, 60, 59, + 0, +} +T.S_Bands = { + 0, 32, 1, 31, 2, 30, 3, 4, 29, 6, 5, 28, 7, 27, 26, 8, 25, 24, 23, 9, 22, 21, 20, 18, 17, 16, 15, 14, 12, 11, 10, 19, + 13, +} +T.S_Res_1 = { + 0, 1, 16, 2, 3, 4, 5, 15, 6, 7, 8, 9, 10, 11, 12, 14, 13, +} +T.S_Res_2 = { + 16, 1, 0, 2, 15, 3, 14, 4, 5, 13, 6, 12, 7, 11, 10, 9, 8, +} +T.S_Q1 = { + 7, 6, 5, 4, 3, 10, 9, 8, 2, 1, 11, 0, 12, 13, 14, 15, 16, 18, 17, +} +T.S_Q2_1 = { + 62, 87, 67, 63, 61, 57, 37, 93, 92, 88, 86, 83, 82, 81, 68, 66, 58, 56, 42, 41, 38, 36, 32, 31, 112, 91, 72, 64, 60, 52, 43, 33, + 12, 117, 113, 111, 107, 97, 89, 85, 77, 73, 71, 69, 65, 59, 55, 53, 51, 47, 39, 35, 27, 17, 13, 11, 7, 118, 116, 108, 106, 98, 96, 94, + 90, 84, 80, 78, 76, 48, 46, 44, 40, 34, 30, 28, 26, 18, 16, 8, 6, 122, 110, 102, 74, 70, 54, 50, 22, 2, 123, 121, 119, 115, 114, 109, + 105, 103, 101, 99, 95, 79, 75, 49, 45, 29, 25, 23, 21, 19, 15, 14, 10, 9, 5, 3, 1, 124, 104, 20, 0, 120, 100, 24, 4, +} +T.S_Q2_2 = { + 62, 92, 87, 86, 82, 68, 67, 66, 63, 61, 58, 57, 56, 42, 38, 37, 32, 93, 91, 88, 83, 81, 43, 41, 36, 33, 31, 112, 72, 64, 60, 52, + 12, 118, 117, 116, 113, 111, 108, 107, 106, 98, 97, 96, 94, 90, 89, 85, 84, 80, 78, 77, 76, 73, 71, 69, 65, 59, 55, 53, 51, 48, 47, 46, + 44, 40, 39, 35, 34, 30, 28, 27, 26, 18, 17, 16, 13, 11, 8, 7, 6, 122, 110, 74, 70, 54, 50, 22, 14, 2, 123, 121, 119, 115, 114, 109, + 105, 103, 102, 101, 99, 95, 79, 75, 49, 45, 29, 25, 23, 21, 19, 15, 10, 9, 5, 3, 1, 124, 104, 20, 0, 120, 100, 24, 4, +} +T.S_Q3 = { + 0, 17, 16, 1, 15, -16, -1, 32, 31, 2, 14, -15, -32, 34, 33, 47, 46, 18, 30, -14, -2, -31, -17, -18, 49, 48, 63, 19, 29, 3, 13, -13, + -3, -30, -47, -48, -33, 50, 62, 35, 45, -29, -19, -46, -34, 51, 61, -45, -35, +} +T.S_Q4 = { + 0, 32, 17, 16, 31, 2, 1, 15, 14, -15, -16, -1, -32, 49, 48, 34, 33, 47, 46, 19, 18, 30, 29, 3, 13, -13, -14, -2, -3, -30, -31, -17, + -18, -47, -48, -33, 64, 50, 63, 62, 35, 45, 4, 12, -29, -19, -46, -34, -64, -49, 66, 65, 79, 78, 51, 61, 36, 44, 20, 28, -12, -4, -28, -20, + -45, -35, -62, -63, -50, 67, 77, 52, 60, -44, -36, -61, -51, 68, 76, -60, -52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, +} +T.S_Q5_1 = { + 0, 2, 1, -1, -2, 3, -3, 4, -4, 5, -5, 7, 6, -6, -7, +} +T.S_Q5_2 = { + 2, 1, 0, -1, -2, 4, 3, -3, -4, 5, -5, 7, 6, -6, -7, +} +T.S_Q6_1 = { + 0, 1, -1, 3, 2, -2, -3, 4, -4, -5, 8, 7, 6, 5, -6, -7, -8, 9, -9, 11, 10, -10, -11, 15, 14, 13, 12, -12, -13, -14, -15, +} +T.S_Q6_2 = { + 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, 8, 7, 6, -6, -7, -8, 10, 9, -9, -10, 13, 12, 11, -11, -12, -13, 15, 14, -14, -15, +} +T.S_Q7_1 = { + 0, 1, -1, 2, -2, 4, 3, -3, -4, 7, 6, 5, -5, -6, -7, 13, 11, 10, 9, 8, -8, -9, -10, -11, -12, 17, 16, 15, 14, 12, -13, -14, + -15, -16, -17, 28, 27, 21, 20, 19, 18, -18, -19, -20, -21, -27, -28, 31, 30, 29, 26, 25, 24, 23, 22, -22, -23, -24, -25, -26, -29, -30, -31, +} +T.S_Q7_2 = { + 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -8, -9, 17, 16, 15, 14, 13, 12, 11, -10, -11, -12, -13, -14, + -15, -16, -17, 22, 21, 20, 19, 18, -18, -19, -20, -21, -22, 29, 28, 27, 26, 25, 24, 23, -23, -24, -25, -26, -27, -28, -29, 31, 30, -30, -31, +} +T.S_Q8_1 = { + 0, 1, -1, -2, 3, 2, -3, 7, 6, 5, 4, -4, -5, -6, -7, 11, 10, 9, 8, -8, -9, -10, -11, 19, 18, 17, 16, 15, 14, 13, 12, -12, + -13, -14, -15, -16, -17, -19, 56, 55, 31, 28, 27, 26, 25, 24, 23, 22, 21, 20, -18, -20, -21, -22, -23, -24, -25, -26, -27, -33, -54, -56, 63, 62, + 61, 60, 59, 58, 57, 54, 53, 43, 40, 39, 38, 37, 36, 35, 34, 33, 32, 30, 29, -28, -29, -30, -31, -32, -34, -35, -36, -37, -38, -39, -40, -41, + -43, -53, -55, -57, -58, -59, -60, -61, 49, 47, 46, 45, 44, 42, 41, -42, -44, -45, -46, -47, -48, -49, -50, -62, -63, 52, 51, 50, 48, -51, -52, +} +T.S_Q8_2 = { + 13, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, 39, 38, 37, 36, 35, 34, + 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 12, -14, -15, -16, -17, -18, -19, -20, -21, -22, -23, -24, + -25, -26, -27, -28, -29, -30, -31, -32, -33, -34, -35, -36, -37, -38, -39, -40, -41, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, + 44, 43, 42, 41, 40, -42, -43, -44, -45, -46, -47, -48, -49, -50, -51, -52, -53, -54, -55, -56, -57, -58, -59, 63, 62, 61, 60, -60, -61, -62, -63, +} +T.S_Q9up = { + -128, 127, -108, -110, -111, -112, -113, -114, -115, -116, -117, -118, -119, -120, -121, -122, -123, -124, -125, -126, -127, 126, 125, 124, 123, 122, 121, 120, 119, 118, 117, 116, + 115, 114, 113, 112, 111, 110, 109, 108, -44, -45, -46, -47, -48, -49, -50, -51, -52, -53, -54, -55, -56, -57, -58, -59, -60, -61, -62, -63, -64, -65, -66, -67, + -68, -69, -70, -71, -72, -73, -74, -75, -76, -77, -78, -79, -80, -81, -82, -83, -84, -85, -86, -87, -88, -89, -90, -91, -92, -93, -94, -95, -96, -97, -98, -99, + -100, -101, -102, -103, -104, -105, -106, -107, -109, 107, 106, 105, 104, 103, 102, 101, 100, 99, 98, 97, 96, 95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 85, + 84, 83, 82, 81, 80, 79, 78, 77, 76, 75, 74, 73, 72, 71, 70, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, + 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 40, 20, 19, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16, -17, -18, -19, -20, -21, -22, -23, -24, + -25, -26, -27, -28, -29, -30, -31, -32, -33, -34, -35, -36, -37, -38, -39, -40, -41, -42, -43, 41, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, + 27, 26, 25, 24, 23, 22, 21, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, -3, -4, -5, -6, 4, 3, 2, 1, 0, -1, -2, +} + +-- Di_opt[32][16] (times 65536) +T.DI = { + 0, -29, 213, -459, 2037, -5153, 6574, -37489, 75038, 37489, 6574, 5153, 2037, 459, 213, 29, + -1, -31, 218, -519, 2000, -5517, 5959, -39336, 74992, 35640, 7134, 4788, 2063, 401, 208, 26, + -1, -35, 222, -581, 1952, -5879, 5288, -41176, 74856, 33791, 7640, 4425, 2080, 347, 202, 24, + -1, -38, 225, -645, 1893, -6237, 4561, -43006, 74630, 31947, 8092, 4063, 2087, 294, 196, 21, + -1, -41, 227, -711, 1822, -6589, 3776, -44821, 74313, 30112, 8492, 3705, 2085, 244, 190, 19, + -1, -45, 228, -779, 1739, -6935, 2935, -46617, 73908, 28289, 8840, 3351, 2075, 197, 183, 17, + -1, -49, 228, -848, 1644, -7271, 2037, -48390, 73415, 26482, 9139, 3004, 2057, 153, 176, 16, + -2, -53, 227, -919, 1535, -7597, 1082, -50137, 72835, 24694, 9389, 2663, 2032, 111, 169, 14, + -2, -58, 224, -991, 1414, -7910, 70, -51853, 72169, 22929, 9592, 2330, 2001, 72, 161, 13, + -2, -63, 221, -1064, 1280, -8209, -998, -53534, 71420, 21189, 9750, 2006, 1962, 36, 154, 11, + -2, -68, 215, -1137, 1131, -8491, -2122, -55178, 70590, 19478, 9863, 1692, 1919, 2, 147, 10, + -3, -73, 208, -1210, 970, -8755, -3300, -56778, 69679, 17799, 9935, 1388, 1870, -29, 139, 9, + -3, -79, 200, -1283, 794, -8998, -4533, -58333, 68692, 16155, 9966, 1095, 1817, -57, 132, 8, + -4, -85, 189, -1356, 605, -9219, -5818, -59838, 67629, 14548, 9959, 814, 1759, -83, 125, 7, + -4, -91, 177, -1428, 402, -9416, -7154, -61289, 66494, 12980, 9916, 545, 1698, -106, 117, 7, + -5, -97, 163, -1498, 185, -9585, -8540, -62684, 65290, 11455, 9838, 288, 1634, -127, 111, 6, + -5, -104, 146, -1567, -45, -9727, -9975, -64019, 64019, 9975, 9727, 45, 1567, -146, 104, 5, + -6, -111, 127, -1634, -288, -9838, -11455, -65290, 62684, 8540, 9585, -185, 1498, -163, 97, 5, + -7, -117, 106, -1698, -545, -9916, -12980, -66494, 61289, 7154, 9416, -402, 1428, -177, 91, 4, + -7, -125, 83, -1759, -814, -9959, -14548, -67629, 59838, 5818, 9219, -605, 1356, -189, 85, 4, + -8, -132, 57, -1817, -1095, -9966, -16155, -68692, 58333, 4533, 8998, -794, 1283, -200, 79, 3, + -9, -139, 29, -1870, -1388, -9935, -17799, -69679, 56778, 3300, 8755, -970, 1210, -208, 73, 3, + -10, -147, -2, -1919, -1692, -9863, -19478, -70590, 55178, 2122, 8491, -1131, 1137, -215, 68, 2, + -11, -154, -36, -1962, -2006, -9750, -21189, -71420, 53534, 998, 8209, -1280, 1064, -221, 63, 2, + -13, -161, -72, -2001, -2330, -9592, -22929, -72169, 51853, -70, 7910, -1414, 991, -224, 58, 2, + -14, -169, -111, -2032, -2663, -9389, -24694, -72835, 50137, -1082, 7597, -1535, 919, -227, 53, 2, + -16, -176, -153, -2057, -3004, -9139, -26482, -73415, 48390, -2037, 7271, -1644, 848, -228, 49, 1, + -17, -183, -197, -2075, -3351, -8840, -28289, -73908, 46617, -2935, 6935, -1739, 779, -228, 45, 1, + -19, -190, -244, -2085, -3705, -8492, -30112, -74313, 44821, -3776, 6589, -1822, 711, -227, 41, 1, + -21, -196, -294, -2087, -4063, -8092, -31947, -74630, 43006, -4561, 6237, -1893, 645, -225, 38, 1, + -24, -202, -347, -2080, -4425, -7640, -33791, -74856, 41176, -5288, 5879, -1952, 581, -222, 35, 1, + -26, -208, -401, -2063, -4788, -7134, -35640, -74992, 39336, -5959, 5517, -2000, 519, -218, 31, 1, +} + +-- requantisation: Cc[res] = 65536 / steps (res -1 .. 17, stored at res + 2), Dc[res] = (steps - 1) / 2, bits per +-- sample of the plain quantisers (res 8 .. 17) +T.CC = { + 111.285962475327, 65536.000000000000, 21845.333333333332, 13107.200000000001, 9362.285714285713, + 7281.777777777777, 4369.066666666666, 2114.064516129032, 1040.253968253968, 516.031496062992, 257.003921568627, + 128.250489236790, 64.062561094819, 32.015632633121, 16.003907203907, 8.000976681723, 4.000244155527, + 2.000061037018, 1.000015259021, +} +T.DC = { 2, 0, 1, 2, 3, 4, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383, 32767 } +T.RES_BIT = { [8] = 7, [9] = 8, [10] = 9, [11] = 10, [12] = 11, [13] = 12, [14] = 13, [15] = 14, [16] = 15, [17] = 16 } + +-- log_dec(max): ceil(log2(max + 2)) bits and the unused codes (index max + 1, max = 0 .. 31) +T.LOG2 = { 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6 } +T.LOG2_LOST = { 0, 1, 0, 3, 2, 1, 0, 7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 31 } + +-- enum_dec: CNK[k][n + 1] = C(n, k) (k = 1 .. 16, n = 0 .. 31), the code length ceil(log2 C(n, k)) and the unused +-- codes 2^len - C(n, k) (computed: libmpcdec's tables, whose last entry is 0) +T.CNK, T.CNK_LEN, T.CNK_LOST = {}, {}, {} +do + for k = 1, 16 do + local c, l, lost = table.create(32, 0), table.create(32, 0), table.create(32, 0) + for n = 0, 32 do + local v = 0 + if n >= k then + v = 1 + for i = 1, k do + v = v * (n - k + i) / i + end + v = math.floor(v + 0.5) + end + if n <= 31 then + c[n + 1] = v + end + if n >= 1 then + local bits = 0 + while 2 ^ bits < v do + bits += 1 + end + l[n] = bits + lost[n] = if v > 0 then 2 ^ bits - v else 0 + end + end + T.CNK[k], T.CNK_LEN[k], T.CNK_LOST[k] = c, l, lost + end + T.CNK_LOST[16][32] = 0 +end + +export type Lut = { + len: { number }, -- 256 entries: code length when the 8-bit prefix decides the symbol, else 0 + val: { number }, -- the symbol, or the 1-based table entry to scan from + codes: { number }, + lens: { number }, + vals: { number }, + sym: { number }?, +} + +-- lut(table, sym?) -> Lut +function T.lut(tab: { number }, sym: { number }?): Lut + local codes, lens, vals = {}, {}, {} + for i = 1, #tab, 3 do + table.insert(codes, tab[i]) + table.insert(lens, tab[i + 1]) + table.insert(vals, tab[i + 2]) + end + local function find(code: number): number + local j = 1 + while code < codes[j] do + j += 1 + end + return j + end + local function symbol(j: number, code: number): number + if sym then + local idx = bit32.band(vals[j] - bit32.rshift(code, 16 - lens[j]), 255) + return sym[idx + 1] or 0 + end + return vals[j] + end + local len, val = table.create(256, 0), table.create(256, 0) + for p = 0, 255 do + local lo, hi = find(p * 256), find(p * 256 + 255) + if lo == hi and lens[lo] <= 8 then + len[p + 1] = lens[lo] + val[p + 1] = symbol(lo, p * 256) + else + len[p + 1] = 0 + val[p + 1] = hi + end + end + return { len = len, val = val, codes = codes, lens = lens, vals = vals, sym = sym } +end + +return T diff --git a/src/Formats/codecs/audio/Musepack/init.luau b/src/Formats/codecs/audio/Musepack/init.luau new file mode 100644 index 0000000..3e29f0b --- /dev/null +++ b/src/Formats/codecs/audio/Musepack/init.luau @@ -0,0 +1,359 @@ +--!strict +-- codecs/audio/Musepack: Musepack (MPC) stream versions 7 and 8: the stream headers (SV7's 32-bit word-swapped +-- header, SV8's key / size packets: SH with its CRC, RG, EI, AP, SE), the frame / audio packet index, and the +-- decoder (codecs/audio/Musepack/Decode: subband bitstream, requantisation, polyphase synthesis). A port of libmpcdec +-- (musepack_src_r475: mpc_demux.c, streaminfo.c, mpc_decoder.c; BSD-3-Clause, (c) The Musepack Development Team, +-- licenses/libmpcdec-BSD.txt), gapless like libmpcdec (the 481-sample synthesis delay and SV8's leading silence are +-- dropped, the length is exact). Not supported: SV4 - SV6 (UNSUPPORTED), the SV8 seek table (the packets are indexed +-- instead), chapters. +-- +-- local s, err = Musepack.open(buf, start, limit) -- start: the "MP+" / "MPCK" magic (after an ID3v2 tag) +-- -- s: { version, sampleRate, channels, frames, maxBand, ms, profile, encoder, gapless, gain, ... } plus the +-- -- codecs/audio/Stream spec: count, start(i), decode(i), pcm(), reset(), skip, stop, preroll +-- +-- Never throws: bad data returns nil, Err. +local Err = require("@formats/core/Err") +local Crc32 = require("@formats/core/Crc32") +local Decode = require("@formats/codecs/audio/Musepack/Decode") + +local Musepack = {} + +local RATES = { 44100, 48000, 37800, 32000 } +local FRAME, DELAY, PAD = Decode.FRAME, Decode.DELAY, Decode.PAD +local readu8 = buffer.readu8 + +export type Stream = { + version: number, + sampleRate: number, + channels: number, + frames: number, -- output sample frames (gapless) + maxBand: number, + ms: boolean, + profile: number, -- SV7: the profile index (7 telephone .. 13 braindead); SV8: the quality (0 .. 15.875) + encoder: number, -- encoder version (SV7: one byte; SV8: major * 2^24 + minor * 2^16 + build * 2^8) + gapless: boolean, + pns: boolean?, + gain: { titleGain: number, titlePeak: number, albumGain: number, albumPeak: number }?, + blockFrames: number, -- frames per packet (SV7: 1; SV8: 2^block_pwr) + bytes: number, -- the stream's size in bytes (for the bitrate) + -- the codecs/audio/Stream spec + count: number, + start: (i: number) -> number, + decode: (i: number) -> (number?, Err.Err?), + pcm: () -> { number }, + reset: () -> (), + skip: number, + stop: number, + preroll: number, +} + +-- ------------------------------------------------------------------------------------------------ SV7 +-- SV7 reads the stream as little-endian 32-bit words, most significant bit first: swap them into a padded copy +local function swapped(buf: buffer, p: number, limit: number): buffer + local n = limit - p + local words = (n + 3) // 4 + local out = buffer.create(words * 4 + PAD) + buffer.copy(out, 0, buf, p, n) + for i = 0, words - 1 do + buffer.writeu32(out, i * 4, bit32.byteswap(buffer.readu32(out, i * 4))) + end + return out +end + +local function sv7(buf: buffer, start: number, limit: number): (Stream?, Err.Err?) + if limit - start < 32 then + return nil, Err.new(Err.TRUNCATED, "SV7 header", start) + end + local ver = bit32.band(readu8(buf, start + 3), 15) + if ver ~= 7 then + return nil, Err.new(Err.UNSUPPORTED, "Musepack stream version " .. ver .. " (SV7 and SV8 only)", start) + end + local s = swapped(buf, start + 4, limit) + local totalBits = (limit - start - 4) * 8 + local at = Decode.bitsAt + local frames = at(s, 0, 16) * 65536 + at(s, 16, 16) + local ms = at(s, 33, 1) == 1 + local maxBand = at(s, 34, 6) + local profile = at(s, 40, 4) + local rate = RATES[at(s, 46, 2) + 1] + local gainTitle, peakTitle = at(s, 64, 16), at(s, 80, 16) + local gainAlbum, peakAlbum = at(s, 96, 16), at(s, 112, 16) + local gapless = at(s, 128, 1) == 1 + local last = at(s, 129, 11) + local encoder = at(s, 160, 8) + if maxBand == 0 or maxBand >= 32 then + return nil, Err.new(Err.CORRUPT, "bad band count " .. maxBand, start) + end + if last == 0 then + last = FRAME + elseif last > FRAME then + return nil, Err.new(Err.CORRUPT, "bad last frame length", start) + end + if frames == 0 then + return nil, Err.new(Err.CORRUPT, "no frames", start) + end + if frames > 2 ^ 24 then + return nil, Err.new(Err.LIMIT, "more than 2^24 frames", start) + end + local samples = frames * FRAME - (if gapless then FRAME - last else DELAY) + -- the frame index: a 20-bit size in front of each frame (the last one has 11 more bits: its length) + local offs: { number }, sizes: { number } = {}, {} + local pos = 168 + for i = 1, frames do + if pos + 20 > totalBits then + break + end + local size = at(s, pos, 20) + local stop = pos + 20 + size + (if i == frames then 11 else 0) + if stop > totalBits then + break -- a truncated last frame + end + offs[i], sizes[i] = pos + 20, size + pos = stop + end + local have = #offs + if have == 0 then + return nil, Err.new(Err.TRUNCATED, "no complete frame", start) + end + -- frames past the stream (a truncated file, or the synthesis tail of a gapless stream) decode as silence + local need = math.min((samples + DELAY + FRAME - 1) // FRAME, have + 1) + local stopAt = math.min(samples + DELAY, have * FRAME + (if have < frames then 0 else FRAME)) + local st = Decode.state(7, maxBand, ms, 2) + local pcm = table.create(FRAME * 2, 0) + local prev = 0 + local out: Stream = { + version = 7, + sampleRate = rate, + channels = 2, + frames = math.max(0, stopAt - DELAY), + maxBand = maxBand, + ms = ms, + profile = profile, + encoder = encoder, + gapless = gapless, + gain = { titleGain = gainTitle, titlePeak = peakTitle, albumGain = gainAlbum, albumPeak = peakAlbum }, + blockFrames = 1, + bytes = limit - start, + count = need, + start = function(i: number): number + return (i - 1) * FRAME + end, + decode = function(i: number): (number?, Err.Err?) + if i ~= prev + 1 then + Decode.reset(st, if i == 1 then 0 else 0x01010101) + end + prev = i + local o: number? = offs[i] + if o == nil then + Decode.frame(st, s, -1, 0, false, pcm, 1) + return FRAME, nil + end + local e, msg = Decode.frame(st, s, o, o + sizes[i], false, pcm, 1) + if not e then + return nil, Err.from(msg, start + 4 + o // 8) + end + if e ~= o + sizes[i] then + return nil, Err.new(Err.CORRUPT, "frame " .. i .. " has the wrong size", start + 4 + o // 8) + end + return FRAME, nil + end, + pcm = function(): { number } + return pcm + end, + reset = function() + prev = -1 + end, + skip = DELAY, + stop = stopAt, + preroll = 32, + } + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ SV8 +-- a packet size: 7 bits per byte, most significant first, bit 7 = more +local function varint(buf: buffer, p: number, limit: number): (number, number) + local v = 0 + for k = 0, 7 do + if p + k >= limit then + return -1, p + end + local b = readu8(buf, p + k) + v = v * 128 + bit32.band(b, 127) + if b < 128 then + return v, p + k + 1 + end + end + return -1, p +end + +local function sv8(buf: buffer, start: number, limit: number): (Stream?, Err.Err?) + local p = start + 4 + local sh: { [string]: any }? = nil + local gain, pns, profile, encoder = nil, nil, 0, 0 + local apOff: { number }, apSize: { number } = {}, {} + while p + 2 < limit do + local k1, k2 = readu8(buf, p), readu8(buf, p + 1) + if k1 < 65 or k1 > 90 or k2 < 65 or k2 > 90 then + return nil, Err.new(Err.CORRUPT, "bad packet key", p) + end + local key = buffer.readstring(buf, p, 2) + local size, body = varint(buf, p + 2, limit) + if size < 0 or size < body - p then + return nil, Err.new(Err.CORRUPT, "bad packet size", p) + end + local stop = p + size + if stop > limit then + if key == "AP" then + break -- a truncated last packet + end + return nil, Err.new(Err.TRUNCATED, key .. " packet", p) + end + if key == "SH" then + if stop - body < 6 then + return nil, Err.new(Err.CORRUPT, "short stream header", p) + end + local crc = buffer.readu32(buf, body) + crc = bit32.byteswap(crc) + if Crc32.of(buf, body + 4, stop - body - 4) ~= crc then + return nil, Err.new(Err.CHECKSUM, "stream header CRC", p) + end + if readu8(buf, body + 4) ~= 8 then + return nil, Err.new(Err.UNSUPPORTED, "Musepack stream version " .. readu8(buf, body + 4), p) + end + local samples, q = varint(buf, body + 5, stop) + local silence, q2 = varint(buf, q, stop) + if samples < 0 or silence < 0 or q2 + 2 > stop then + return nil, Err.new(Err.CORRUPT, "bad stream header", p) + end + local b0, b1 = readu8(buf, q2), readu8(buf, q2 + 1) + sh = { + samples = samples, + silence = silence, + rate = RATES[bit32.rshift(b0, 5) + 1], + maxBand = bit32.band(b0, 31) + 1, + channels = bit32.rshift(b1, 4) + 1, + ms = bit32.band(b1, 8) ~= 0, + blockPwr = bit32.band(b1, 7) * 2, + } + elseif key == "RG" and stop - body >= 9 and readu8(buf, body) == 1 then + local function u16(o: number): number + return readu8(buf, body + o) * 256 + readu8(buf, body + o + 1) + end + gain = { titleGain = u16(1), titlePeak = u16(3), albumGain = u16(5), albumPeak = u16(7) } + elseif key == "EI" and stop - body >= 4 then + local b = readu8(buf, body) + profile = bit32.rshift(b, 1) / 8 + pns = bit32.band(b, 1) == 1 + encoder = readu8(buf, body + 1) * 2 ^ 24 + readu8(buf, body + 2) * 2 ^ 16 + readu8(buf, body + 3) * 2 ^ 8 + elseif key == "AP" then + table.insert(apOff, body) + table.insert(apSize, stop - body) + elseif key == "SE" then + break + end + p = stop + end + if not sh then + return nil, Err.new(Err.CORRUPT, "no stream header", start) + end + local h = sh :: { [string]: any } + local samples, silence, maxBand, channels = h.samples, h.silence, h.maxBand, h.channels + if maxBand >= 32 or channels > 2 or silence > samples then + return nil, Err.new(Err.UNSUPPORTED, string.format("%d bands, %d channels", maxBand, channels), start) + end + if samples > 2 ^ 34 then + return nil, Err.new(Err.LIMIT, "too many samples", start) + end + if #apOff == 0 then + return nil, Err.new(Err.CORRUPT, "no audio packet", start) + end + local per = 2 ^ h.blockPwr + if per * FRAME * channels > 2 ^ 22 then + return nil, Err.new(Err.LIMIT, per .. " frames per audio packet", start) + end + local needFrames = (samples + DELAY + FRAME - 1) // FRAME + local count = math.min(#apOff, (needFrames + per - 1) // per) + local stopAt = math.min(samples + DELAY, count * per * FRAME) + local st = Decode.state(8, maxBand, h.ms, channels) + local pcm = table.create(per * FRAME * channels, 0) + local scratch = buffer.create(0) + local out: Stream = { + version = 8, + sampleRate = h.rate, + channels = channels, + frames = math.max(0, stopAt - DELAY - silence), + maxBand = maxBand, + ms = h.ms, + profile = profile, + encoder = encoder, + gapless = true, + pns = pns, + gain = gain, + blockFrames = per, + bytes = limit - start, + count = count, + start = function(i: number): number + return (i - 1) * per * FRAME + end, + decode = function(i: number): (number?, Err.Err?) + local o: number, size: number = apOff[i], apSize[i] + if buffer.len(scratch) < size + PAD then + scratch = buffer.create(size + PAD) + end + buffer.copy(scratch, 0, buf, o, size) + local nf = math.min(per, needFrames - (i - 1) * per) + local pos = 0 + for f = 1, nf do + local e, msg = Decode.frame(st, scratch, pos, size * 8, f == 1, pcm, (f - 1) * FRAME * channels + 1) + if not e then + return nil, Err.from(msg, o) + end + pos = e + end + if nf == per and size * 8 - pos > 7 then + return nil, Err.new(Err.CORRUPT, "audio packet " .. i .. " has unused data", o) + end + return nf * FRAME, nil + end, + pcm = function(): { number } + return pcm + end, + reset = function() + Decode.reset(st, 0) + end, + skip = DELAY + silence, + stop = stopAt, + preroll = 1, + } + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- magic(buf, p, limit) -> 7 | 8 | 0 (other: "MP+" with another version is 7's family, reported by open) +function Musepack.magic(buf: buffer, p: number, limit: number): number + if p + 4 > limit then + return 0 + end + local m = buffer.readstring(buf, p, 4) + if m == "MPCK" then + return 8 + end + if string.sub(m, 1, 3) == "MP+" then + return 7 + end + return 0 +end + +-- open(buf, start, limit) -> Stream | nil, Err +function Musepack.open(buf: buffer, start: number, limit: number): (Stream?, Err.Err?) + local v = Musepack.magic(buf, start, limit) + if v == 8 then + return sv8(buf, start, limit) + elseif v == 7 then + return sv7(buf, start, limit) + end + return nil, Err.new(Err.CORRUPT, "not a Musepack stream", start) +end + +return Musepack diff --git a/src/Formats/codecs/audio/Qoa/init.luau b/src/Formats/codecs/audio/Qoa/init.luau new file mode 100644 index 0000000..0e7560a --- /dev/null +++ b/src/Formats/codecs/audio/Qoa/init.luau @@ -0,0 +1,297 @@ +--!strict +--!native +--!optimize 2 +-- codecs/audio/Qoa: the "Quite OK Audio" codec (QOA): frames of up to 256 slices per channel, each slice a 4-bit scale +-- factor and 20 3-bit residuals over a 4-tap sign-sign LMS predictor. Ported from qoa.h (phoboslab/qoa, Dominic +-- Szablewski, MIT: licenses/qoa-LICENSE.txt): the tables, the predictor, the decoder and the encoder's brute-force +-- scale factor search, so encoding is byte-for-byte qoa.h's (including its 32-bit wrap in the reciprocal division). +-- The 64-bit slices are handled as two 32-bit halves. +-- +-- local info = Qoa.frameInfo(buf, p, avail) -- { channels, rate, samples, size } | nil, message +-- local n, msg = Qoa.decodeFrame(buf, p, avail, dst, d) -- one frame -> interleaved f32 at float index d +-- local size = Qoa.encodeFrame(x, xf, n, ch, rate, lms, out, p) -- n frames of f32 at frame xf -> bytes at out[p] +-- local lms = Qoa.newLms(ch) -- the encoder state (history 0, weights 0, 0, -1, 2) +-- +-- Never throws: decodeFrame checks the frame against avail before reading; encodeFrame needs Qoa.frameSize bytes. +local readu8, readu32, readf32, writef32, writeu32 = buffer.readu8, buffer.readu32, buffer.readf32, buffer.writef32, buffer.writeu32 +local readi32, writei32 = buffer.readi32, buffer.writei32 +local band, rshift, bor, lshift, byteswap = bit32.band, bit32.rshift, bit32.bor, bit32.lshift, bit32.byteswap +local floor = math.floor + +local Qoa = {} + +Qoa.SLICE_LEN = 20 +Qoa.SLICES_PER_FRAME = 256 +Qoa.FRAME_LEN = 256 * 20 +Qoa.MAX_CHANNELS = 255 + +local QUANT = { 7, 7, 7, 5, 5, 3, 3, 1, 0, 0, 2, 2, 4, 4, 6, 6, 6 } -- residual -8 .. 8 -> code +local RECIP = { 65536, 9363, 3121, 1457, 781, 475, 311, 216, 156, 117, 90, 71, 57, 47, 39, 32 } +-- DEQ[sf * 8 + q + 1] +local DEQ = { + 1, -1, 3, -3, 5, -5, 7, -7, + 5, -5, 18, -18, 32, -32, 49, -49, + 16, -16, 53, -53, 95, -95, 147, -147, + 34, -34, 113, -113, 203, -203, 315, -315, + 63, -63, 210, -210, 378, -378, 588, -588, + 104, -104, 345, -345, 621, -621, 966, -966, + 158, -158, 528, -528, 950, -950, 1477, -1477, + 228, -228, 760, -760, 1368, -1368, 2128, -2128, + 316, -316, 1053, -1053, 1895, -1895, 2947, -2947, + 422, -422, 1405, -1405, 2529, -2529, 3934, -3934, + 548, -548, 1828, -1828, 3290, -3290, 5117, -5117, + 696, -696, 2320, -2320, 4176, -4176, 6496, -6496, + 868, -868, 2893, -2893, 5207, -5207, 8099, -8099, + 1064, -1064, 3548, -3548, 6386, -6386, 9933, -9933, + 1286, -1286, 4288, -4288, 7718, -7718, 12005, -12005, + 1536, -1536, 5120, -5120, 9216, -9216, 14336, -14336, +} + +local function be32(b: buffer, p: number): number + return byteswap(readu32(b, p)) +end + +local function s16(v: number): number + return if v >= 32768 then v - 65536 else v +end + +-- frameSize(channels, slices) -> bytes +function Qoa.frameSize(ch: number, slices: number): number + return 8 + 16 * ch + 8 * slices * ch +end + +export type FrameInfo = { channels: number, rate: number, samples: number, size: number } + +-- frameInfo(buf, p, avail) -> the frame header's facts, checked against avail and the slice count | nil, message +function Qoa.frameInfo(b: buffer, p: number, avail: number): (FrameInfo?, string?) + if avail < 8 then + return nil, "truncated frame header" + end + local hi, lo = be32(b, p), be32(b, p + 4) + local ch = rshift(hi, 24) + local rate = band(hi, 0xFFFFFF) + local samples = rshift(lo, 16) + local size = band(lo, 0xFFFF) + if ch == 0 or rate == 0 or samples == 0 then + return nil, "bad frame header" + end + local slices = (samples + 19) // 20 + local head = 8 + 16 * ch + if slices > 256 or size < head or slices * ch > (size - head) // 8 then + return nil, "bad frame size" + end + if size > avail then + return nil, "truncated frame" + end + return { channels = ch, rate = rate, samples = samples, size = size }, nil +end + +-- decodeFrame(buf, p, avail, dst, d) -> samples per channel, frame bytes | nil, message: one frame (its own LMS state +-- in the header) as interleaved f32 into dst from float index d (dst holds samples * channels floats there) +function Qoa.decodeFrame(b: buffer, p: number, avail: number, dst: buffer, d: number): (number?, number | string) + local info, msg = Qoa.frameInfo(b, p, avail) + if not info then + return nil, msg :: string + end + local ch, samples = info.channels, info.samples + for c = 0, ch - 1 do + local lp = p + 8 + c * 16 + local hA, hB, hC, hD = be32(b, lp), be32(b, lp + 4), be32(b, lp + 8), be32(b, lp + 12) + local h0, h1, h2, h3 = s16(rshift(hA, 16)), s16(band(hA, 0xFFFF)), s16(rshift(hB, 16)), s16(band(hB, 0xFFFF)) + local w0, w1, w2, w3 = s16(rshift(hC, 16)), s16(band(hC, 0xFFFF)), s16(rshift(hD, 16)), s16(band(hD, 0xFFFF)) + local sp = p + 8 + 16 * ch + c * 8 + local o = (d + c) * 4 + local os = ch * 4 + local s0 = 0 + while s0 < samples do + local hi, lo = be32(b, sp), be32(b, sp + 4) + local base = rshift(hi, 28) * 8 + 1 + local n = math.min(20, samples - s0) + for k = 0, n - 1 do + local q + if k < 9 then + q = band(rshift(hi, 25 - 3 * k), 7) + elseif k == 9 then + q = band(hi, 1) * 4 + rshift(lo, 30) + else + q = band(rshift(lo, 57 - 3 * k), 7) + end + local pred = (w0 * h0 + w1 * h1 + w2 * h2 + w3 * h3) // 8192 + local dq = DEQ[base + q] + local r = pred + dq + if r > 32767 then + r = 32767 + elseif r < -32768 then + r = -32768 + end + writef32(dst, o, r / 32768) + o += os + local delta = dq // 16 + w0 += if h0 < 0 then -delta else delta + w1 += if h1 < 0 then -delta else delta + w2 += if h2 < 0 then -delta else delta + w3 += if h3 < 0 then -delta else delta + h0, h1, h2, h3 = h1, h2, h3, r + end + s0 += 20 + sp += 8 * ch + end + end + return samples, info.size +end + +-- ------------------------------------------------------------------------------------------------ encoder +-- newLms(ch) -> the encoder's LMS state: 8 i32 per channel (history 0..3, weights 0..3), weights 0, 0, -1, 2 (<< 13) +function Qoa.newLms(ch: number): buffer + local st = buffer.create(32 * ch) + for c = 0, ch - 1 do + writei32(st, c * 32 + 24, -8192) + writei32(st, c * 32 + 28, 16384) + end + return st +end + +-- the nearest s16 to x * 32768 (NaN -> 0) +local function toS16(x: number): number + local v = floor(x * 32768 + 0.5) + if v ~= v then + return 0 + elseif v > 32767 then + return 32767 + elseif v < -32768 then + return -32768 + end + return v +end + +-- qoa.h's qoa_div: a rounding division by the scale factor through its .16 reciprocal (in 32-bit int arithmetic, which +-- wraps for big residuals at scale factor 0), rounding away from zero +local function qdiv(v: number, sf: number): number + local x = v * RECIP[sf + 1] + 32768 + if x >= 2147483648 or x < -2147483648 then + x = (x + 2147483648) % 4294967296 - 2147483648 + end + local n = x // 65536 + local sv = if v > 0 then 1 elseif v < 0 then -1 else 0 + local sn = if n > 0 then 1 elseif n < 0 then -1 else 0 + return n + sv - sn +end + +-- encodeFrame(x, xf, n, ch, rate, lms, out, p) -> bytes written: frames xf .. xf + n - 1 (n <= 5120) of interleaved f32 x +-- as one QOA frame at out[p] (Qoa.frameSize(ch, ceil(n / 20)) bytes); lms carries the encoder state between frames +function Qoa.encodeFrame(x: buffer, xf: number, n: number, ch: number, rate: number, lms: buffer, out: buffer, p: number): number + local slices = (n + 19) // 20 + local size = Qoa.frameSize(ch, slices) + writeu32(out, p, byteswap(bor(lshift(ch, 24), rate))) + writeu32(out, p + 4, byteswap(bor(lshift(n, 16), size))) + for c = 0, ch - 1 do + local so = c * 32 + -- the history and weights as big-endian i16 x 4 + for i = 0, 3 do + local hv = band(readi32(lms, so + i * 4), 0xFFFF) + local wv = band(readi32(lms, so + 16 + i * 4), 0xFFFF) + buffer.writeu8(out, p + 8 + c * 16 + i * 2, rshift(hv, 8)) + buffer.writeu8(out, p + 8 + c * 16 + i * 2 + 1, band(hv, 255)) + buffer.writeu8(out, p + 8 + c * 16 + 8 + i * 2, rshift(wv, 8)) + buffer.writeu8(out, p + 8 + c * 16 + 8 + i * 2 + 1, band(wv, 255)) + end + end + local xs = table.create(20, 0) + local codes = table.create(20, 0) + local best = table.create(20, 0) + local prevSf = table.create(ch, 0) + local sp = p + 8 + 16 * ch + for s = 0, slices - 1 do + local len = math.min(20, n - s * 20) + for c = 0, ch - 1 do + for k = 1, len do + xs[k] = toS16(readf32(x, ((xf + s * 20 + k - 1) * ch + c) * 4)) + end + local so = c * 32 + local H0, H1, H2, H3 = readi32(lms, so), readi32(lms, so + 4), readi32(lms, so + 8), readi32(lms, so + 12) + local W0, W1, W2, W3 = readi32(lms, so + 16), readi32(lms, so + 20), readi32(lms, so + 24), readi32(lms, so + 28) + local bestRank, bestSf = math.huge, 0 + local b0, b1, b2, b3, bw0, bw1, bw2, bw3 = H0, H1, H2, H3, W0, W1, W2, W3 + for sfi = 0, 15 do + local sf = (sfi + prevSf[c + 1]) % 16 + local h0, h1, h2, h3, w0, w1, w2, w3 = H0, H1, H2, H3, W0, W1, W2, W3 + local rank = 0 + local base = sf * 8 + 1 + for k = 1, len do + local v = xs[k] + local pred = (w0 * h0 + w1 * h1 + w2 * h2 + w3 * h3) // 8192 + local res = v - pred + local sc = qdiv(res, sf) + if sc > 8 then + sc = 8 + elseif sc < -8 then + sc = -8 + end + local q = QUANT[sc + 9] + local dq = DEQ[base + q] + local r = pred + dq + if r > 32767 then + r = 32767 + elseif r < -32768 then + r = -32768 + end + local sq = w0 * w0 + w1 * w1 + w2 * w2 + w3 * w3 + if sq >= 2147483648 then -- C int arithmetic + sq = (sq + 2147483648) % 4294967296 - 2147483648 + end + local pen = sq // 262144 - 0x8ff + if pen < 0 then + pen = 0 + end + local e = v - r + rank += e * e + pen * pen + if rank > bestRank then + break + end + local delta = dq // 16 + w0 += if h0 < 0 then -delta else delta + w1 += if h1 < 0 then -delta else delta + w2 += if h2 < 0 then -delta else delta + w3 += if h3 < 0 then -delta else delta + h0, h1, h2, h3 = h1, h2, h3, r + codes[k] = q + end + if rank < bestRank then + bestRank, bestSf = rank, sf + b0, b1, b2, b3, bw0, bw1, bw2, bw3 = h0, h1, h2, h3, w0, w1, w2, w3 + for k = 1, len do + best[k] = codes[k] + end + end + end + prevSf[c + 1] = bestSf + writei32(lms, so, b0) + writei32(lms, so + 4, b1) + writei32(lms, so + 8, b2) + writei32(lms, so + 12, b3) + writei32(lms, so + 16, bw0) + writei32(lms, so + 20, bw1) + writei32(lms, so + 24, bw2) + writei32(lms, so + 28, bw3) + -- the slice: sf in the top 4 bits, then the codes, unused codes 0 + local hi, lo = bestSf * 268435456, 0 + for k = 0, 19 do + local q = if k < len then best[k + 1] else 0 + if k < 9 then + hi += q * 2 ^ (25 - 3 * k) + elseif k == 9 then + hi += rshift(q, 2) + lo += band(q, 3) * 1073741824 + else + lo += q * 2 ^ (57 - 3 * k) + end + end + writeu32(out, sp, byteswap(hi)) + writeu32(out, sp + 4, byteswap(lo)) + sp += 8 + end + end + return size +end + +return Qoa diff --git a/src/Formats/codecs/audio/Stream.luau b/src/Formats/codecs/audio/Stream.luau index ef69611..63a0079 100644 --- a/src/Formats/codecs/audio/Stream.luau +++ b/src/Formats/codecs/audio/Stream.luau @@ -10,11 +10,13 @@ -- count = n, -- frames, duration, bitrate, tags, ...); read / seek / position -- start = function(i) return ... end, -- are added. start(i): packet i's first frame (absolute, before -- decode = function(i) return n, err end,-- trimming); decode(i) -> frames | nil, Err, the samples in pcm() --- pcm = function() return floats end, -- (interleaved, 1-based) until the next decode +-- pcm = function() return floats end, -- (interleaved, 1-based; or a buffer of f32) until the next decode -- reset = function() end, -- forget codec state (before a seek) -- skip = priming, stop = lastFrame, -- output = absolute frames [skip, stop) -- preroll = 1, -- packets decoded before the one holding a seek target (AAC: 1) --- }) +-- scale = 1 / 32768, -- optional: read() writes pcm() values * scale (default 1) +-- ints = true, -- optional: pcm() holds integers; adds dec:readInt(n, out?), the +-- }) -- same frames as read() as i32 (bit-exact checks) -- -- A decode failure ends the stream and is kept in dec.error (Pcm.drain reports it); a failing first packet is -- returned by packets() as the open error. Never throws. @@ -26,12 +28,14 @@ export type Spec = { count: number, start: (i: number) -> number, decode: (i: number) -> (number?, Err.Err?), - pcm: () -> { number }, + pcm: () -> { number } | buffer, -- a buffer: interleaved f32 from byte 0 reset: () -> (), skip: number?, -- default 0 stop: number?, -- default start(count + 1) preroll: number?, -- default 0 cumulative: boolean?, -- frames after a packet = frames before + its output (default: start(i) + its output) + scale: number?, -- read() writes pcm() values times this (default 1) + ints: boolean?, -- pcm() values are integers: dec:readInt(n, out?) returns them as i32 } -- packets(dec, spec) -> dec (with read / seek / position) | nil, Err (the first packet failed) @@ -75,12 +79,13 @@ function Stream.packets(dec: any, spec: Spec): (any, Err.Err?) end end - function dec.read(_self: any, n: number, out: buffer?): (buffer, number) + local scale = spec.scale or 1 + local function pull(n: number, out: buffer?, asInt: boolean): (buffer, number) local want = math.max(0, math.floor(n)) local need = want * ch * 4 local ob = if out and buffer.len(out) >= need then out else buffer.create(need) local got = 0 - local writef32 = buffer.writef32 + local writef32, writei32 = buffer.writef32, buffer.writei32 while got < want do if pendPos >= pendN then if failed or not fill() then @@ -91,9 +96,35 @@ function Stream.packets(dec: any, spec: Spec): (any, Err.Err?) local src = pcmOf() local q = got * ch * 4 local s = pendPos * ch - for k = 1, take * ch do - writef32(ob, q, src[s + k]) - q += 4 + if type(src) == "buffer" then + if scale == 1 and not asInt then + buffer.copy(ob, q, src, s * 4, take * ch * 4) + else + for k = 0, take * ch - 1 do + local v = buffer.readf32(src, (s + k) * 4) + if asInt then + writei32(ob, q, v) + else + writef32(ob, q, v * scale) + end + q += 4 + end + end + elseif asInt then + for k = 1, take * ch do + writei32(ob, q, src[s + k]) + q += 4 + end + elseif scale == 1 then + for k = 1, take * ch do + writef32(ob, q, src[s + k]) + q += 4 + end + else + for k = 1, take * ch do + writef32(ob, q, src[s + k] * scale) + q += 4 + end end pendPos += take got += take @@ -102,6 +133,15 @@ function Stream.packets(dec: any, spec: Spec): (any, Err.Err?) return ob, got end + function dec.read(_self: any, n: number, out: buffer?): (buffer, number) + return pull(n, out, false) + end + if spec.ints then + function dec.readInt(_self: any, n: number, out: buffer?): (buffer, number) + return pull(n, out, true) + end + end + function dec.seek(_self: any, seconds: number) local sec = if type(seconds) == "number" and seconds == seconds then seconds else 0 local target = math.clamp(math.floor(sec * sr + 0.5), 0, frames) + skip -- absolute frame diff --git a/src/Formats/codecs/audio/Tracker/Load.luau b/src/Formats/codecs/audio/Tracker/Load.luau new file mode 100644 index 0000000..884a77a --- /dev/null +++ b/src/Formats/codecs/audio/Tracker/Load.luau @@ -0,0 +1,291 @@ +--!strict +-- codecs/audio/Tracker/Load: helpers shared by the tracker loaders that map another format's effects onto one of the +-- engine's families (music/mtm, 669, stm, ult, okt, med, ptm, far). Effects are first named the way OpenMPT's loaders +-- name them ("portaup", "volslide", "modex", ...), then written in the family's own cell coding: S3M / IT letter +-- codes (A = 1) with the IT volume column, or MOD / XM numbers. Ported from OpenMPT's ModCommand helpers +-- (ConvertModCommand, ConvertToVolCommand, FillInTwoCommands, GetEffectWeight, CPattern::WriteEffect; BSD licence, +-- licenses/openmpt-LICENSE.txt), reduced to what the engine plays. +local Err = require("@formats/core/Err") +local Player = require("@formats/codecs/audio/Tracker/Player") +local Pcm = require("@formats/codecs/audio/Tracker/Pcm") +local Tables = require("@formats/codecs/audio/Tracker/Tables") + +local Load = {} + +local EXT = Player.EXT + +-- the S3M / IT letter code of each effect name (engine extension effects included) +local IT: { [string]: number } = { + speed = 1, + jump = 2, + ["break"] = 3, + volslide = 4, + portadown = 5, + portaup = 6, + toneporta = 7, + vibrato = 8, + tremor = 9, + arpeggio = 10, + vibratovol = 11, + toneportavol = 12, + chanvol = 13, + chanvolslide = 14, + offset = 15, + panslide = 16, + retrig = 17, + tremolo = 18, + s3mex = 19, + tempo = 20, + finevibrato = 21, + globalvol = 22, + globalvolslide = 23, + panning8 = 24, + panbrello = 25, + noteslideup = EXT.NOTE_SLIDE_UP, + noteslidedown = EXT.NOTE_SLIDE_DOWN, + noteslideupretrig = EXT.NOTE_SLIDE_UP_RETRIG, + noteslidedownretrig = EXT.NOTE_SLIDE_DOWN_RETRIG, + autoportaup = EXT.AUTO_PORTA_UP, + autoportadown = EXT.AUTO_PORTA_DOWN, + freqadjust = EXT.FREQ_ADJUST, +} +Load.IT = IT + +-- OpenMPT's effect weights (low to high): which of two effects a cell keeps when only one fits +local WEIGHT: { [string]: number } = {} +for i, n in + { + "none", "keyoff", "tremolo", "finevibrato", "vibrato", "panbrello", "s3mex", "modex", "panslide", "panning8", + "noteslideupretrig", "noteslideup", "noteslidedownretrig", "noteslidedown", "portaup", "autoportaup", + "portadown", "autoportadown", "volslide", "vibratovol", "volume", "volume8", "offset", "tremor", "retrig", + "arpeggio", "toneporta", "toneportavol", "chanvolslide", "chanvol", "globalvolslide", "globalvol", "tempo", + "speed", "jump", "break", + } +do + WEIGHT[n] = i +end + +local GLOBAL = { jump = true, ["break"] = true, speed = true, tempo = true, globalvol = true, globalvolslide = true } + +-- isGlobal(name, param) -> the effect acts on the whole song (OpenMPT's IsGlobalCommand) +function Load.isGlobal(name: string?, param: number): boolean + if name == nil then + return false + end + if GLOBAL[name] then + return true + end + local x = param // 16 + if name == "modex" then + return x == 0 or x == 6 or x == 0xE + elseif name == "s3mex" then + return x == 6 or x == 0xB or x == 0xE + end + return false +end + +-- modCommand(cmd, param) -> name?, param: a MOD / XM effect number (0..F, XM letters 16..) by name (ConvertModCommand) +local MODFX: { [number]: string } = { + [0] = "arpeggio", [1] = "portaup", [2] = "portadown", [3] = "toneporta", [4] = "vibrato", [5] = "toneportavol", + [6] = "vibratovol", [7] = "tremolo", [8] = "panning8", [9] = "offset", [10] = "volslide", [11] = "jump", + [12] = "volume", [13] = "break", [14] = "modex", [15] = "tempo", [16] = "globalvol", [17] = "globalvolslide", + [20] = "keyoff", [25] = "panslide", [27] = "retrig", [29] = "tremor", +} +function Load.modCommand(cmd: number, param: number): (string?, number) + if cmd == 0 and param == 0 then + return nil, 0 + elseif cmd == 0xF and param < 0x20 then + return "speed", param + end + local n = MODFX[cmd] + if n == "break" then + param = (param // 16) * 10 + param % 16 + end + return n, param +end + +-- itVolume(name, param, force) -> the IT volume-column byte + 1 (the engine's coding) for an effect that fits there, +-- or nil (OpenMPT's ConvertToVolCommand; force: fit it with some loss of precision) +function Load.itVolume(name: string?, param: number, force: boolean): number? + if name == "volume" then + return math.min(param, 64) + 1 + elseif name == "volume8" then + if not force and param % 4 ~= 0 then + return nil + end + return (param + 3) // 4 + 1 + elseif name == "portaup" or name == "portadown" then + if not force and (param % 4 ~= 0 or param >= 0xE0) then + return nil + end + return (if name == "portaup" then 115 else 105) + math.min(param // 4, 9) + 1 + elseif name == "toneporta" then + if param >= 0xF0 then + return 193 + 9 + 1 + end + for n = 0, 9 do + local v = Tables.IT_VOLPORTA[n + 1] + if (force and param <= v) or param == v then + return 193 + n + 1 + end + end + return nil + elseif name == "vibrato" then + if force then + param = math.min(param % 16, 9) + elseif param % 16 > 9 or param >= 16 then + return nil + end + return 203 + param % 16 + 1 + elseif name == "panning8" then + return 128 + (if param == 255 then 64 else param // 4) + 1 + elseif name == "volslide" then + local x, y = param // 16, param % 16 + if param == 0 then + return nil + elseif y == 0 then + return 85 + math.min(x, 9) + 1 + elseif x == 0 then + return 95 + math.min(y, 9) + 1 + elseif y == 0xF then + return 65 + math.min(x, 9) + 1 + elseif x == 0xF then + return 75 + math.min(y, 9) + 1 + end + return nil + elseif name == "s3mex" and param // 16 == 8 then + return 128 + (param % 16) * 4 + 2 + 1 + end + return nil +end + +-- itEffect(name, param) -> effect code, param in S3M / IT coding (0, 0 for none or an effect the family lacks; MOD's +-- extended E commands become their S3M equivalents) +function Load.itEffect(name: string?, param: number): (number, number) + if name == nil then + return 0, 0 + end + if name == "modex" then + local x, y = param // 16, param % 16 + if x == 1 then + return IT.portaup, 0xF0 + y + elseif x == 2 then + return IT.portadown, 0xF0 + y + elseif x == 9 then + return IT.retrig, y + elseif x == 0xA then + return IT.volslide, y * 16 + 0xF + elseif x == 0xB then + return IT.volslide, 0xF0 + y + end + local s = ({ [3] = 1, [4] = 3, [5] = 2, [6] = 0xB, [7] = 4, [8] = 8, [0xC] = 0xC, [0xD] = 0xD, [0xE] = 0xE })[x] + if s then + return IT.s3mex, s * 16 + y + end + return 0, 0 + end + local code = IT[name] + if code == nil then + return 0, 0 + end + return code, param +end + +-- fillTwo(name1, param1, name2, param2, lowResOffset?) -> volume byte (engine IT coding, 0 none), effect name, param, +-- lost name?, lost param: two effects of one cell into the IT volume column and the effect column, keeping the +-- heavier one when both cannot fit (OpenMPT's FillInTwoCommands) +function Load.fillTwo(e1: string?, p1: number, e2: string?, p2: number): (number, string?, number, string?, number) + if e1 ~= nil and e1 == e2 then + e2 = nil -- the same effect twice: keep one (most are absolute; slides are kept once too, a simplification) + end + for n = 0, 3 do + local v = Load.itVolume(e1, p1, n > 1) + if e1 == nil or v then + if v == nil and (e2 == "volume" or e2 == "volume8") then + -- the engine's IT family sets volumes in the volume column only + return Load.itVolume(e2, p2, true) or 0, nil, 0, nil, 0 + end + return v or 0, e2, p2, nil, 0 + end + e1, p1, e2, p2 = e2, p2, e1, p1 + end + if (WEIGHT[e1 :: string] or 0) > (WEIGHT[e2 :: string] or 0) then + e1, p1, e2, p2 = e2, p2, e1, p1 + end + return 0, e2, p2, e1, p1 +end + +-- writeEffect(m, pattern (0-based), row, fx, param, retry?, channel?, multiple?) -> true when written: puts an effect +-- into a free effect slot of the row (any channel, or the given 1-based one); none free: the next row (retry "next") or +-- the previous one ("prev"). The same effect already on the row counts as written unless multiple (OpenMPT's +-- CPattern::WriteEffect). +function Load.writeEffect(m: any, pattern: number, row: number, fx: number, param: number, retry: string?, channel: number?, multiple: boolean?): boolean + local p = m.patterns[pattern + 1] + if not p then + return false + end + local fam = m.engine or m.format + local modLike = fam == "mod" or fam == "xm" + local nch = m.channels + local d = p.data + local guard = 0 + while row >= 0 and row < p.rows and guard < 1024 do + guard += 1 + local c0, c1 = 1, nch + if channel then + c0, c1 = channel, channel + end + for c = c0, c1 do + local o = (row * nch + c - 1) * 5 + if not multiple and buffer.readu8(d, o + 3) == fx and (fx ~= 0 or not modLike) then + return true + end + end + for c = c0, c1 do + local o = (row * nch + c - 1) * 5 + local f, q = buffer.readu8(d, o + 3), buffer.readu8(d, o + 4) + if f == 0 and (not modLike or q == 0) then + buffer.writeu8(d, o + 3, fx) + buffer.writeu8(d, o + 4, param) + return true + end + end + if retry == "next" then + row += 1 + elseif retry == "prev" then + row -= 1 + else + return false + end + end + return false +end + +-- readSample(buf, offset, frames, spec, sample, budget) -> true | nil, Err: decodes raw PCM (codecs/audio/Tracker/Pcm +-- spec) at the absolute buffer offset into the sample (data, length, bits, channels). A short file keeps the frames +-- that are there (end = the buffer's length, or spec.limit). budget = { left = f32 bytes still allowed } (maxBytes). +function Load.readSample(buf: buffer, offset: number, frames: number, spec: any, s: any, budget: { left: number }): (boolean?, Err.Err?) + local nch = spec.channels or 1 + local bps = spec.bits // 8 + local limit = math.min(spec.limit or buffer.len(buf), buffer.len(buf)) + local avail = math.max(0, limit - offset) // (nch * bps) + local n = math.max(0, math.min(math.floor(frames), avail)) + budget.left -= n * nch * 4 + if budget.left < 0 then + return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit") + end + local data = Pcm.decode(buf, offset, n, spec) + if not data then + return nil, Err.new(Err.TRUNCATED, "sample data", offset) + end + s.data, s.length, s.bits, s.channels = data, n, spec.bits, nch + return true, nil +end + +-- bcd(n) -> n as the two decimal digits S3M / MOD pattern breaks store (0..99) +function Load.bcd(n: number): number + n = math.clamp(math.floor(n), 0, 99) + return (n // 10) * 16 + n % 10 +end + +return Load diff --git a/src/Formats/codecs/audio/Tracker/Player.luau b/src/Formats/codecs/audio/Tracker/Player.luau index 62df8b3..4454d57 100644 --- a/src/Formats/codecs/audio/Tracker/Player.luau +++ b/src/Formats/codecs/audio/Tracker/Player.luau @@ -23,6 +23,20 @@ local MOD, S3M, XM, IT = 1, 2, 3, 4 Player.MOD, Player.S3M, Player.XM, Player.IT = MOD, S3M, XM, IT local FAMILY = { mod = MOD, s3m = S3M, xm = XM, it = IT } +-- engine extension effects: format-specific commands of the other tracker formats, in any family (see +-- codecs/audio/Tracker) +local EXT = { + NOTE_SLIDE_UP = 0x40, + NOTE_SLIDE_DOWN = 0x41, + NOTE_SLIDE_UP_RETRIG = 0x42, + NOTE_SLIDE_DOWN_RETRIG = 0x43, + AUTO_PORTA_UP = 0x44, + AUTO_PORTA_DOWN = 0x45, + FREQ_ADJUST = 0x46, + TEMPO_256 = 0x47, -- set the tempo to 256 + param (0x48: 512 + param, 0x49: 768 + param) +} +Player.EXT = EXT + local BG_VOICES = 64 -- voices beyond one per channel, for IT new note actions -- ------------------------------------------------------------------------------------------------ state @@ -171,12 +185,20 @@ local function newChannel(i: number, pan: number, vol: number): any pitchEnvOn = true, muted = false, triggered = false, + autoPorta = 0, -- auto portamento (EXT 0x44 / 0x45): period units per tick, + down + autoTone = false, -- flags.autoTonePorta: the tone portamento keeps running + hzAdd = 0, -- EXT 0x46: Hz added to the frequency (669) + slideCount = 0, -- note slides: ticks to the next step + mNoteSlide = 0, + tonePortaRow = false, } end -- new(module, opts) -> player state (module validated by the caller) function Player.new(m: any, sampleRate: number, opts: any): any - local fmt = FAMILY[m.format] or MOD + local fmt = FAMILY[m.engine or m.format] or MOD + local flags = m.flags + local ptPeriods = fmt == MOD or flags.periods == "amiga" local st: any = { m = m, fmt = fmt, @@ -189,8 +211,19 @@ function Player.new(m: any, sampleRate: number, opts: any): any insMode = m.instrumentMode and #m.instruments > 0, oldFx = m.flags.oldEffects or false, compatG = m.flags.compatGxx or false, - fastSlides = m.flags.fastSlides or false, - amigaLimits = m.flags.amigaLimits or false, + fastSlides = flags.fastSlides or false, + amigaLimits = flags.amigaLimits or false, + ptPeriods = ptPeriods, -- ProTracker periods (integer table periods, PAL clock) + hz = flags.periods == "hz", -- periods are frequencies in Hz + hzScale = if type(flags.hzSlide) == "number" then flags.hzSlide else 1, + hzTone = if type(flags.hzTonePorta) == "number" then flags.hzTonePorta else 1, + fastPortas = flags.fastPortas or false, + autoTonePorta = flags.autoTonePorta or false, + autoReset = flags.autoReset or false, + st2Tempo = flags.st2Tempo or false, + oktSlides = flags.oktSlides or false, + ft2Pan = flags.panLaw == "ft2", + envHold = flags.envRowHold or false, ord = 0, row = 0, tick = 0, @@ -214,7 +247,7 @@ function Player.new(m: any, sampleRate: number, opts: any): any master = 1, rows = 0, ramp = 64, - amiga = if fmt == MOD then AMIGA_PAL else AMIGA, + amiga = if ptPeriods then AMIGA_PAL else AMIGA, loopAllowed = opts and opts.loop or false, } for i = 1, m.channels do @@ -240,6 +273,9 @@ end -- the output scale per format, calibrated against OpenMPT's default mix levels (tools/fixtures: a full-scale sine at -- volume 64 on one centred channel) function Player.masterGain(m: any, fmt: number): number + if type(m.preamp) == "number" then + return m.preamp / 128 -- OpenMPT's sample pre-amp, as set by the format's loader + end if fmt == IT or fmt == S3M then return (m.mixVolume or 48) / 128 -- OpenMPT: linear in the mix / master volume, 64 = 0.5 end @@ -335,10 +371,15 @@ local function notePeriod(st: any, note: number, smp: any, ft: number?): (number end end local plin = (ref - note) * 64 - tr - if st.fmt == MOD then + if st.hz then + -- periods are frequencies (Hz, rounded as OpenMPT does): the sample's rate at C-5 + return floor((smp.c5speed or 8363) * 2 ^ ((note - 61) / 12)), base + end + if st.ptPeriods then -- ProTracker: integer periods from the finetune tables (finetune 0 table scaled by 2^(-ft / 96), rounded) local ftp = (ft or smp.finetune or 0) / 16 - return 4 * floor(Tables.noteToPeriod(note) * 2 ^ (-ftp / 12 / 8) + 0.5), base + local n = note + (if st.fmt == MOD or st.fmt == XM then smp.relativeNote or 0 else 0) + return 4 * floor(Tables.noteToPeriod(n) * 2 ^ (-ftp / 12 / 8) + 0.5), base end if st.linear then return plin, base @@ -350,6 +391,9 @@ local function arpPeriod(st: any, period: number, semis: number): number if semis == 0 then return period end + if st.hz then + return period * 2 ^ (semis / 12) + end if st.linear then return period - semis * 64 end @@ -357,7 +401,9 @@ local function arpPeriod(st: any, period: number, semis: number): number end local function clampPeriod(st: any, c: any) - if st.linear then + if st.hz then + c.period = clamp(c.period, 1, 1e6) + elseif st.linear then c.period = clamp(c.period, -6000, 6000) elseif st.amigaLimits then c.period = clamp(c.period, 113 * 4, 856 * 4) @@ -366,6 +412,17 @@ local function clampPeriod(st: any, c: any) end end +-- slide(st, c, units): a pitch slide in period units (positive: down; 4 per effect unit); in Hz mode the frequency +-- moves units * hzSlide Hz the other way +local function slide(st: any, c: any, units: number) + if st.hz then + c.period -= units * st.hzScale + else + c.period += units + end + clampPeriod(st, c) +end + -- ------------------------------------------------------------------------------------------------ voices local function allocVoice(st: any): any local best, bestScore = nil, math.huge @@ -674,6 +731,7 @@ local function trigger(st: any, c: any, note: number, insIdx: number, vcmd: numb keep = if c.voice.ins == ins then true else "release" end c.triggered = true + c.hzAdd = 0 c.tremorOn = true c.retrigCount = 0 v = startVoice(st, c, smp, smpIdx, ins, useIns, realNote, period, base, keep) @@ -758,6 +816,9 @@ local function tonePorta(st: any, c: any, speed: number) if c.period == c.target then return end + if st.hz then + speed *= st.hzScale * st.hzTone + end if c.period < c.target then c.period = min(c.period + speed, c.target) else @@ -837,23 +898,21 @@ local function fxModXm(st: any, c: any, tick: number) if xm and param > 0 then c.mPortaUp = param end - if tick > 0 then - c.period -= (if xm then c.mPortaUp else param) * 4 - clampPeriod(st, c) + if tick > 0 or st.fastPortas then + slide(st, c, -(if xm then c.mPortaUp else param) * 4) end elseif fx == 2 then if xm and param > 0 then c.mPortaDn = param end - if tick > 0 then - c.period += (if xm then c.mPortaDn else param) * 4 - clampPeriod(st, c) + if tick > 0 or st.fastPortas then + slide(st, c, (if xm then c.mPortaDn else param) * 4) end elseif fx == 3 or fx == 5 then if fx == 3 and param > 0 then c.portaSpeed = param end - if tick > 0 then + if tick > 0 or st.fastPortas then tonePorta(st, c, c.portaSpeed * 4) end elseif fx == 4 or fx == 6 then @@ -909,16 +968,14 @@ local function fxModXm(st: any, c: any, tick: number) c.mFineUp = y end if tick == 0 then - c.period -= (if xm then c.mFineUp else y) * 4 - clampPeriod(st, c) + slide(st, c, -(if xm then c.mFineUp else y) * 4) end elseif x == 2 then if xm and y > 0 then c.mFineDn = y end if tick == 0 then - c.period += (if xm then c.mFineDn else y) * 4 - clampPeriod(st, c) + slide(st, c, (if xm then c.mFineDn else y) * 4) end elseif x == 4 then c.vibWave = y % 8 @@ -1054,16 +1111,14 @@ local function fxModXm(st: any, c: any, tick: number) c.mXFineUp = y end if tick == 0 then - c.period -= c.mXFineUp - clampPeriod(st, c) + slide(st, c, -c.mXFineUp) end elseif x == 2 then if y > 0 then c.mXFineDn = y end if tick == 0 then - c.period += c.mXFineDn - clampPeriod(st, c) + slide(st, c, c.mXFineDn) end end end @@ -1073,10 +1128,10 @@ local function fxModXm(st: any, c: any, tick: number) if param > 0 then c.mVolSlide = param end - if tick > 0 then + if tick > 0 or st.fastSlides then volSlideMod(c, c.mVolSlide) end - elseif tick > 0 then + elseif tick > 0 or st.fastSlides then volSlideMod(c, param) end end @@ -1161,16 +1216,15 @@ end local function portaS3m(st: any, c: any, p: number, tick: number, sign: number) if p >= 0xF0 then if tick == 0 then - c.period += sign * (p % 16) * 4 + slide(st, c, sign * (p % 16) * 4) end elseif p >= 0xE0 then if tick == 0 then - c.period += sign * (p % 16) + slide(st, c, sign * (p % 16)) end - elseif tick > 0 then - c.period += sign * p * 4 + elseif tick > 0 or st.fastPortas then + slide(st, c, sign * p * 4) end - clampPeriod(st, c) end local function fxS3mIt(st: any, c: any, tick: number) @@ -1178,7 +1232,11 @@ local function fxS3mIt(st: any, c: any, tick: number) local it = st.fmt == IT if fx == 1 then -- A speed if tick == 0 and param > 0 then - st.speed = param + if st.st2Tempo then + st.speed, st.tempo = Tables.st2Tempo(param) + else + st.speed = param + end end elseif fx == 2 then -- B jump if tick == 0 then @@ -1446,7 +1504,7 @@ local function fxS3mIt(st: any, c: any, tick: number) c.portaSpeed = c.mEF end end - if tick > 0 then + if tick > 0 or st.fastPortas then tonePorta(st, c, c.portaSpeed * 4) end end @@ -1514,8 +1572,7 @@ local function volColIt(st: any, c: any, tick: number) c.mEF = p end if tick > 0 then - c.period += c.mEF * 4 - clampPeriod(st, c) + slide(st, c, c.mEF * 4) end elseif v <= 124 then local p = (v - 115) * 4 @@ -1523,8 +1580,7 @@ local function volColIt(st: any, c: any, tick: number) c.mEF = p end if tick > 0 then - c.period -= c.mEF * 4 - clampPeriod(st, c) + slide(st, c, -c.mEF * 4) end elseif v >= 193 and v <= 202 then local p = Tables.IT_VOLPORTA[v - 192] or 0 @@ -1550,6 +1606,66 @@ local function volColIt(st: any, c: any, tick: number) end end +-- ------------------------------------------------------------------------------------------------ extension effects +-- the engine extension effects (EXT, codes 0x40..) and the auto slides, in any family +local function fxExt(st: any, c: any, tick: number) + local fx, param = c.fx, c.param + if fx >= EXT.NOTE_SLIDE_UP and fx <= EXT.NOTE_SLIDE_DOWN_RETRIG then + -- note slides (PTM, Oktalyzer): every (param >> 4) ticks by (param & 15) semitones; Oktalyzer (flags.oktSlides): + -- 1x = every tick, 5x = once on the first tick + if tick == 0 then + if param // 16 > 0 then + c.mNoteSlide = (param // 16) * 16 + c.mNoteSlide % 16 + end + if param % 16 > 0 then + c.mNoteSlide = (c.mNoteSlide // 16) * 16 + param % 16 + end + c.slideCount = c.mNoteSlide // 16 + end + local p = c.mNoteSlide + local go + if st.oktSlides then + go = p // 16 == 1 or tick == 0 + else + go = false + if tick > 0 then + c.slideCount -= 1 + go = c.slideCount == 0 + end + end + if go and c.smp and c.realNote > 0 then + c.slideCount = p // 16 + local up = fx == EXT.NOTE_SLIDE_UP or fx == EXT.NOTE_SLIDE_UP_RETRIG + c.realNote = clamp(c.realNote + (if up then p % 16 else -(p % 16)), 1, 120) + c.period = notePeriod(st, c.realNote, c.smp, c.finetune) + if fx >= EXT.NOTE_SLIDE_UP_RETRIG then + retrigVoice(st, c) + end + end + elseif fx == EXT.AUTO_PORTA_UP or fx == EXT.AUTO_PORTA_DOWN then + if tick == 0 then + c.autoPorta = (if fx == EXT.AUTO_PORTA_UP then -param else param) * 4 + end + elseif fx == EXT.FREQ_ADJUST then + if tick == 0 then + c.hzAdd = param * 80 + end + elseif fx >= EXT.TEMPO_256 and fx <= EXT.TEMPO_256 + 2 then + if tick == 0 then + st.tempo = (fx - EXT.TEMPO_256 + 1) * 256 + param + end + end + -- auto slides: every tick (fast portamentos) or every tick but the first + if tick > 0 or st.fastPortas then + if c.autoPorta ~= 0 then + slide(st, c, c.autoPorta) + end + if c.autoTone and not c.tonePortaRow then + tonePorta(st, c, c.portaSpeed * 4) + end + end +end + -- ------------------------------------------------------------------------------------------------ rows and ticks local function noteDelayOf(st: any, fx: number, param: number): number if (st.fmt == MOD or st.fmt == XM) and fx == 0xE and param // 16 == 0xD then @@ -1573,6 +1689,9 @@ end local function runEffects(st: any, c: any, tick: number) c.vibDelta, c.arp = 0, 0 + if (c.fx >= 0x40 and c.fx < 0x50) or c.autoPorta ~= 0 or c.autoTone then + fxExt(st, c, tick) + end if st.fmt == MOD or st.fmt == XM then fxModXm(st, c, tick) if st.fmt == XM then @@ -1621,6 +1740,15 @@ local function processRow(st: any) end c.fx, c.param, c.vcmd = fx, param, vcmd c.cutTick, c.keyOffTick = -1, -1 + if st.autoReset and fx ~= 0 and fx ~= 255 then + -- 669: any effect stops the auto slides + c.autoPorta, c.autoTone = 0, false + end + local tp = isPorta(st, fx, vcmd) + c.tonePortaRow = tp + if tp and st.autoTonePorta then + c.autoTone = param ~= 0 or not st.autoReset or not isPorta(st, fx, 0) + end c.triggered = false local delay = noteDelayOf(st, fx, param) c.finetune = finetuneOf(st, fx, param) @@ -1684,10 +1812,11 @@ local function updateVoice(st: any, v: any) local envVol, envPan, envPitch = 64, 0, 0 local filterEnv = nil if ins then + local hold = st.envHold and st.tick == 0 -- MED: the envelopes do not move on a row's first tick local e = ins.volEnv if e and e.enabled and v.volEnvOn then local val, np, ended = updateEnvelope(e, v.volEnvPos, v.keyOn, it) - envVol, v.volEnvPos = val, np + envVol, v.volEnvPos = val, if hold then v.volEnvPos else np if ended and it then if val <= 0 then v.active = false @@ -1699,12 +1828,12 @@ local function updateVoice(st: any, v: any) e = ins.panEnv if e and e.enabled and v.panEnvOn then local val, np = updateEnvelope(e, v.panEnvPos, v.keyOn, it) - envPan, v.panEnvPos = val, np + envPan, v.panEnvPos = val, if hold then v.panEnvPos else np end e = ins.pitchEnv if e and e.enabled and v.pitchEnvOn then local val, np = updateEnvelope(e, v.pitchEnvPos, v.keyOn, it) - v.pitchEnvPos = np + v.pitchEnvPos = if hold then v.pitchEnvPos else np if e.filter then filterEnv = val else @@ -1750,7 +1879,9 @@ local function updateVoice(st: any, v: any) -- frequency local P = v.periodOut + avDelta local freq - if st.linear then + if st.hz then + freq = max(0, P + (v.hzAdd or 0)) + elseif st.linear then freq = v.base * 2 ^ (-P / 768) else freq = if P > 0 then st.amiga / P else 0 @@ -1762,9 +1893,9 @@ local function updateVoice(st: any, v: any) -- volume local smp = v.smp local vol = v.vol / 64 * envVol / 64 * v.fade / 65536 * st.gvol / 128 - if it then - vol *= v.chanVol / 64 * (if smp then (smp.globalVolume or 64) / 64 else 1) * (if ins then (ins.globalVolume or 128) / 128 else 1) - end + -- channel, sample and instrument global volumes (64 / 64 / 128 unless an IT file, or another format's loader, + -- sets them) + vol *= v.chanVol / 64 * (if smp then (smp.globalVolume or 64) / 64 else 1) * (if ins then (ins.globalVolume or 128) / 128 else 1) if v.tremorMute then vol = 0 end @@ -1782,6 +1913,10 @@ local function updateVoice(st: any, v: any) local g = vol * st.master if v.surround then v.tl, v.tr = g * 0.5, -g * 0.5 + elseif st.ft2Pan then + -- FT2's square-root pan law (OpenMPT's CompatibleFT2 mix levels), pan at most 255 + local p = min(pan, 255) + v.tl, v.tr = g * math.sqrt((256 - p) / 256), g * math.sqrt(p / 256) else v.tl, v.tr = g * (256 - pan) / 256, g * pan / 256 end @@ -1853,8 +1988,9 @@ function Player.tick(st: any): number local c = st.chans[i] local v = c.voice if v and v.active and v.chan == i and not v.bg then - local P = arpPeriod(st, c.period, c.arp) + c.vibDelta + local P = arpPeriod(st, c.period, c.arp) + (if st.hz then -c.vibDelta * st.hzScale else c.vibDelta) v.period, v.periodOut, v.base = c.period, P, c.base + v.hzAdd = c.hzAdd v.vol = clamp(c.vol + c.tremDelta, 0, 64) if c.muted then v.vol = 0 diff --git a/src/Formats/codecs/audio/Tracker/Tables.luau b/src/Formats/codecs/audio/Tracker/Tables.luau index 90e78d8..2378fee 100644 --- a/src/Formats/codecs/audio/Tracker/Tables.luau +++ b/src/Formats/codecs/audio/Tracker/Tables.luau @@ -110,4 +110,17 @@ Tables.AMIGA = 8363 * 1712 -- MOD: the PAL Amiga clock (7093789.2 Hz / 2 per ProTracker period unit; period 428 plays at 8287 Hz) Tables.AMIGA_PAL = 7093789.2 / 2 * 4 +-- st2Tempo(byte) -> speed, tempo: a Scream Tracker 2 tempo byte (high nibble ticks per row, low nibble a fine factor) +-- as OpenMPT plays it (ConvertST2Tempo: ST2's tick length at its 23863 Hz mixing rate, as a fractional BPM) +local ST2_FACTOR = { 140, 50, 25, 15, 10, 7, 6, 4, 3, 3, 2, 2, 2, 2, 1, 1 } +function Tables.st2Tempo(byte: number): (number, number) + local hi, lo = byte // 16, byte % 16 + local d = 50 - (ST2_FACTOR[hi + 1] * lo) // 16 -- never 0; negative at tempo 06..0F (C integer division truncates) + local spt = if d > 0 then 23863 // d else -(23863 // -d) + if spt <= 0 then + spt += 65536 + end + return math.max(hi, 1), math.floor((23863 * 50000 + spt) / (spt * 2)) / 10000 +end + return Tables diff --git a/src/Formats/codecs/audio/Tracker/init.luau b/src/Formats/codecs/audio/Tracker/init.luau index 55056f6..f185acc 100644 --- a/src/Formats/codecs/audio/Tracker/init.luau +++ b/src/Formats/codecs/audio/Tracker/init.luau @@ -1,6 +1,7 @@ --!strict --- codecs/audio/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it. The four loaders read --- their files into one Module structure (below); render(module, opts) plays any of them through the standard audio +-- codecs/audio/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it, and the loaders +-- that map other trackers onto those four effect families (music/mtm, 669, stm, ult, okt, med, ptm, far; helpers in +-- codecs/audio/Tracker/Load). The loaders read their files into one Module structure (below); render(module, opts) plays any of them through the standard audio -- Decoder (Types.Decoder: stereo f32). Written for this library from the format documents (ProTracker 2.3, the XM -- spec + FT2 behaviour, ST3 TECH.DOC, ITTECH.TXT); libxmp / OpenMPT were used only as reference players for tests. -- @@ -9,14 +10,25 @@ -- local seconds = Tracker.duration(module) -- one pass, song loops detected -- -- Module (Types.Module plus the engine fields; pattern / instrument / sample numbers are as in the file): --- format "mod" | "s3m" | "xm" | "it": selects the effect family and the format quirks +-- format the file format ("mod", "s3m", "xm", "it", "mtm", "669", ...): what the module was read from +-- engine "mod" | "s3m" | "xm" | "it": the effect family the engine plays (default: format, so the four +-- families need no engine field). Other formats map their effects onto one family (music/mtm: "xm", +-- music/669: "s3m", ...) and set the quirks they need in flags. +-- preamp optional 0..256: the output gain as OpenMPT's sample pre-amp (gain = preamp / 128); default per family -- title, channels, speed (ticks per row), tempo (BPM: a tick lasts 2.5 / tempo s) -- globalVolume 0..128 (S3M / XM 0..64 are stored doubled), mixVolume 0..128 (IT mix volume, S3M master volume) -- order { pattern number (0-based) | 254 skip ("+++") | 255 end ("---") }, restart (0-based order index) -- linear linear frequency slides (XM / IT flag) or Amiga periods -- instrumentMode XM, IT with instruments: notes go through Instrument keymaps; otherwise the instrument column -- is a sample number (MOD, S3M, IT sample mode) --- flags { oldEffects, compatGxx (IT), fastSlides (ST3.00 volume slides), amigaLimits (MOD) } +-- flags { oldEffects, compatGxx (IT), fastSlides (ST3.00 volume slides: also on tick 0; any family), +-- amigaLimits (MOD), and the quirks of the other formats (any family): +-- periods = "amiga" (ProTracker period table + PAL clock, as MOD) | "hz" (periods are frequencies in +-- Hz: 669, FAR; slides move hzSlide Hz per unit, tone portamento hzSlide * hzTonePorta), +-- fastPortas (slides on tick 0 too), autoTonePorta (a tone portamento keeps running on later rows), +-- autoReset (669: any effect stops the auto slides), st2Tempo (S3M family A: Scream Tracker 2 tempo), +-- oktSlides (Oktalyzer note slides), panLaw = "ft2" (square-root panning, OpenMPT's FT2 mix levels), +-- envRowHold (MED: envelopes do not advance on a row's first tick) } -- channelPan { 0..256 per channel (128 centre; 512 = surround); MOD: 64 / 192 (Amiga L R R L at half width, -- as OpenMPT plays it; set 0 / 256 or render with stereoSeparation = 200 for hard panning) }, channelVolume { 0..64 }, channelMute { bool } -- patterns { Pattern } (pattern n at patterns[n + 1]); Pattern = { rows, data }: data holds rows * channels @@ -25,7 +37,11 @@ -- speed), 253 note fade, 254 note cut, 255 key off. The volume column and effects are kept in the -- file's own coding: MOD / XM effects 0..35 (XM letters G.. = 16..), XM volume byte as stored; -- S3M / IT effects 1..26 (A = 1), S3M volume 0 = none else volume + 1, IT volume byte + 1 --- (0 = none). Tracker.cell / Tracker.setCell read and write cells. +-- (0 = none). Engine extension effects (any family, for the other formats): Tracker.EXT (0x40 note +-- slide up, 0x41 down, 0x42 / 0x43 the same with retrigger: param = ticks per step << 4 | semitones; +-- 0x44 / 0x45 auto portamento up / down (669: every tick until another effect), 0x46 frequency +-- adjust (+ param * 80 Hz, 669), 0x47 / 0x48 / 0x49 tempo 256 / 512 / 768 + param (MED)). +-- Tracker.cell / Tracker.setCell read and write cells. -- samples { Sample }: { name, data (f32, interleaved when stereo), length (frames), channels, bits (8 | 16, -- for writers), loopStart, loopEnd (frames, end exclusive), loopType (0 none, 1 forward, 2 ping-pong), -- susStart, susEnd, susType (IT sustain loop), volume 0..64, globalVolume 0..64, pan (0..256 or nil), @@ -85,12 +101,29 @@ export type RenderOptions = { local CELL = 5 +-- engine extension effects (see the Module notes above) +Tracker.EXT = Player.EXT + +-- st2Tempo(byte) -> speed, tempo (BPM): a Scream Tracker 2 tempo byte +Tracker.st2Tempo = Tables.st2Tempo + +local FAMILIES = { mod = true, s3m = true, xm = true, it = true } + +-- family(module) -> "mod" | "s3m" | "xm" | "it" | nil: the effect family a module plays as +function Tracker.family(m: any): string? + local f = m.engine or m.format + return if type(f) == "string" and FAMILIES[f] then f else nil +end + -- ------------------------------------------------------------------------------------------------ constructors --- newModule(format, channels) -> an empty Module (no patterns / samples) with the format's defaults -function Tracker.newModule(format: string, channels: number): any +-- newModule(format, channels, engine?) -> an empty Module (no patterns / samples) with the defaults of the effect family +-- (engine, default format) +function Tracker.newModule(format: string, channels: number, engine: string?): any + local fam = engine or format local m = { kind = "music", format = format, + engine = engine, title = "", channels = channels, speed = 6, @@ -99,8 +132,8 @@ function Tracker.newModule(format: string, channels: number): any mixVolume = 48, order = {}, restart = 0, - linear = format == "xm" or format == "it", - instrumentMode = format == "xm" or format == "it", + linear = fam == "xm" or fam == "it", + instrumentMode = fam == "xm" or fam == "it", flags = {}, channelPan = {}, channelVolume = {}, @@ -113,7 +146,7 @@ function Tracker.newModule(format: string, channels: number): any } for i = 1, channels do m.channelVolume[i] = 64 - if format == "mod" then + if fam == "mod" then local k = (i - 1) % 4 m.channelPan[i] = if k == 0 or k == 3 then 64 else 192 -- the Amiga's L R R L, at OpenMPT's default width else @@ -285,8 +318,11 @@ function Tracker.validate(m: any): (boolean?, Err.Err?) if type(m) ~= "table" then return nil, Err.new(Err.ARG, "not a module") end - if m.format ~= "mod" and m.format ~= "s3m" and m.format ~= "xm" and m.format ~= "it" then - return nil, Err.new(Err.ARG, "unknown tracker format " .. tostring(m.format)) + if not Tracker.family(m) then + return nil, Err.new(Err.ARG, "unknown tracker format " .. tostring(m.engine or m.format)) + end + if m.preamp ~= nil and not num(m.preamp, 0, 256) then + m.preamp = nil end if not num(m.channels, 1, 128) or m.channels % 1 ~= 0 then return nil, Err.new(Err.ARG, "bad channel count") diff --git a/src/Formats/codecs/audio/Tta/Decode.luau b/src/Formats/codecs/audio/Tta/Decode.luau new file mode 100644 index 0000000..1ce9094 --- /dev/null +++ b/src/Formats/codecs/audio/Tta/Decode.luau @@ -0,0 +1,259 @@ +--!strict +--!native +--!optimize 2 +-- codecs/audio/Tta/Decode: one TTA1 frame -> samples. Written from the TTA1 format description (the True Audio +-- format notes: adaptive Rice codes with two running sums per channel, the order-8 sign-LMS "hybrid" filter, the +-- first-order fixed predictor, inter-channel decorrelation, a CRC-32 per frame); no libtta / ffmpeg code. Checked +-- bit-exact against the ttaenc 3.4.1 decoder (tools/fixtures/tta.py). Never throws: returns nil, message. +local Crc32 = require("@formats/core/Crc32") + +local readu8, readu32 = buffer.readu8, buffer.readu32 +local band, rshift = bit32.band, bit32.rshift +local min, max, floor = math.min, math.max, math.floor + +local Decode = {} + +local TWO31, TWO32 = 2147483648, 4294967296 +local INV31 = 1 / TWO31 +local PAD = 16 +local P2: { number } = table.create(40, 0) -- P2[k + 1] = 2^k +for i = 0, 39 do + P2[i + 1] = 2 ^ i +end +-- ONES[b + 1]: the trailing 1 bits of the byte b +local ONES: { number } = table.create(256, 0) +for b = 0, 255 do + local n, v = 0, b + while v % 2 == 1 do + n += 1 + v //= 2 + end + ONES[b + 1] = n +end + +-- longUnary(S, pos, lim) -> the count of 1 bits from pos, the position after the 0 | nil (past lim) +local function longUnary(S: buffer, pos: number, lim: number): (number?, number) + local unary = 0 + while pos <= lim do + local w = rshift(readu32(S, rshift(pos, 3)), band(pos, 7)) + local ones = ONES[band(w, 255) + 1] + if ones < 8 then + return unary + ones, pos + ones + 1 + end + unary += 8 + pos += 8 + end + return nil, pos +end + +export type State = { + channels: number, + bytes: number, -- 1 .. 3 + S: buffer, -- the frame's bits (+ PAD zeros) + -- per channel: rice k0, k1, sum0, sum1; filter error, Q (weights), X (steps), L (delay line) x 8; the last value + R: { number }, + Q: { number }, + X: { number }, + L: { number }, + E: { number }, + last: { number }, + cur: { number }, +} + +function Decode.state(channels: number, bytes: number): State + return { + channels = channels, + bytes = bytes, + S = buffer.create(4096), + R = table.create(channels * 4, 0), + Q = table.create(channels * 8, 0), + X = table.create(channels * 8, 0), + L = table.create(channels * 8, 0), + E = table.create(channels, 0), + last = table.create(channels, 0), + cur = table.create(channels, 0), + } +end + +-- frame(st, buf, o, len, n, P) -> n | nil, message: the frame of len bytes at o (its CRC-32 last) holding n samples per +-- channel, into P (interleaved integers) +function Decode.frame(st: State, buf: buffer, o: number, len: number, n: number, P: { number }): (number?, string?) + if len < 4 then + return nil, "truncated frame" + end + local dlen = len - 4 + if Crc32.of(buf, o, dlen) ~= readu32(buf, o + dlen) then + return nil, "checksum: frame CRC mismatch" + end + local S = st.S + if buffer.len(S) < dlen + PAD then + S = buffer.create(dlen + PAD + 4096) + st.S = S + end + buffer.copy(S, 0, buf, o, dlen) + buffer.fill(S, dlen, 0, PAD) + local C, bytes = st.channels, st.bytes + local shift = if bytes == 2 then 9 else 10 -- the filter's precision per sample size + local fdiv = 2 ^ shift + local round = fdiv // 2 + local pk = if bytes == 1 then 16 else 32 -- the fixed predictor: last * (pk - 1) / pk + local R, Q, X, L, E, last, cur = st.R, st.Q, st.X, st.L, st.E, st.last, st.cur + for c = 0, C - 1 do + R[c * 4 + 1], R[c * 4 + 2], R[c * 4 + 3], R[c * 4 + 4] = 10, 10, 16384, 16384 + E[c + 1], last[c + 1] = 0, 0 + for i = 1, 8 do + Q[c * 8 + i], X[c * 8 + i], L[c * 8 + i] = 0, 0, 0 + end + end + local pos = 0 -- bit position + local lim = dlen * 8 + local c = 0 -- the channel of the sample at idx + for idx = 1, n * C do + do + if pos > lim then + return nil, "truncated frame" + end + -- the unary prefix: 1 bits up to a 0 (a run past one byte goes to longUnary) + local unary + local w = rshift(readu32(S, rshift(pos, 3)), band(pos, 7)) + local ones = ONES[band(w, 255) + 1] + if ones < 8 then + unary = ones + pos += ones + 1 + else + local u, p2 = longUnary(S, pos, lim) + if not u then + return nil, "truncated frame" + end + unary, pos = u, p2 + end + local rb = c * 4 + local k0, k1, s0, s1 = R[rb + 1], R[rb + 2], R[rb + 3], R[rb + 4] + local deep = unary > 0 + local k + if deep then + k = k1 + unary -= 1 + else + k = k0 + end + local value = unary + if k > 0 then + local bits + if k <= 24 then + bits = band(rshift(readu32(S, rshift(pos, 3)), band(pos, 7)), P2[k + 1] - 1) + else + local lo = band(rshift(readu32(S, rshift(pos, 3)), band(pos, 7)), 0xFFFF) + local p2 = pos + 16 + bits = lo + band(rshift(readu32(S, rshift(p2, 3)), band(p2, 7)), P2[k - 15] - 1) * 65536 + end + pos += k + value = unary * P2[k + 1] + bits + end + if deep then + s1 += value - s1 // 16 + if k1 > 0 and s1 < P2[k1 + 5] then + k1 -= 1 + elseif s1 > P2[k1 + 6] then + k1 += 1 + end + value += P2[k0 + 1] + end + s0 += value - s0 // 16 + if k0 > 0 and s0 < P2[k0 + 5] then + k0 -= 1 + elseif s0 > P2[k0 + 6] then + k0 += 1 + end + R[rb + 1] = math.min(k0, 31) + R[rb + 2] = math.min(k1, 31) + R[rb + 3] = s0 + R[rb + 4] = s1 + local odd = value % 2 -- odd -> (v + 1) / 2, even -> -v / 2 (branch-free) + value = (value + odd) // 2 * (2 * odd - 1) + -- the adaptive filter: the weights step toward the sign of the last residual + local fb = c * 8 + local err = E[c + 1] + -- (one assignment per statement: LuaJIT cannot coalesce long multiple assignments) + local dq = max(-1, min(1, err)) + local x1, x2, x3, x4 = X[fb + 1], X[fb + 2], X[fb + 3], X[fb + 4] + local x5, x6, x7, x8 = X[fb + 5], X[fb + 6], X[fb + 7], X[fb + 8] + local q1 = Q[fb + 1] + x1 * dq + local q2 = Q[fb + 2] + x2 * dq + local q3 = Q[fb + 3] + x3 * dq + local q4 = Q[fb + 4] + x4 * dq + local q5 = Q[fb + 5] + x5 * dq + local q6 = Q[fb + 6] + x6 * dq + local q7 = Q[fb + 7] + x7 * dq + local q8 = Q[fb + 8] + x8 * dq + Q[fb + 1] = q1 + Q[fb + 2] = q2 + Q[fb + 3] = q3 + Q[fb + 4] = q4 + Q[fb + 5] = q5 + Q[fb + 6] = q6 + Q[fb + 7] = q7 + Q[fb + 8] = q8 + local l2, l3, l4, l5 = L[fb + 2], L[fb + 3], L[fb + 4], L[fb + 5] + local l6, l7, l8 = L[fb + 6], L[fb + 7], L[fb + 8] + local sum = round + L[fb + 1] * q1 + l2 * q2 + l3 * q3 + l4 * q4 + l5 * q5 + l6 * q6 + l7 * q7 + l8 * q8 + if sum >= TWO31 or sum < -TWO31 then + sum = (sum + TWO31) % TWO32 - TWO31 + end + -- the steps follow the delay line's signs (x 1, 2, 2, 4) + X[fb + 1] = x2 + X[fb + 2] = x3 + X[fb + 3] = x4 + X[fb + 4] = x5 + X[fb + 5] = 1 + 2 * floor(l5 * INV31) -- -1 for a negative value, else 1 (branch-free) + X[fb + 6] = 2 + 4 * floor(l6 * INV31) + X[fb + 7] = 2 + 4 * floor(l7 * INV31) + X[fb + 8] = 4 + 8 * floor(l8 * INV31) + E[c + 1] = value + value += sum // fdiv + -- the delay line: the last value and its first and second differences + local n7 = value - l8 + local n6 = n7 - l7 + L[fb + 1] = l2 + L[fb + 2] = l3 + L[fb + 3] = l4 + L[fb + 4] = l5 + L[fb + 5] = n6 - l6 + L[fb + 6] = n6 + L[fb + 7] = n7 + L[fb + 8] = value + -- the fixed predictor + value += (last[c + 1] * (pk - 1)) // pk + last[c + 1] = value + cur[c + 1] = value + end + c += 1 + if c == C then + -- inter-channel decorrelation: the last channel carries half the previous one, the others are differences + c = 0 + local o = idx - C + if C == 1 then + P[idx] = cur[1] + elseif C == 2 then + local a = cur[1] + local b = cur[2] + (if a >= 0 then a // 2 else -((-a) // 2)) + P[o + 1], P[o + 2] = b - a, b + else + local a = cur[C - 1] + cur[C] += if a >= 0 then a // 2 else -((-a) // 2) + for r = C - 1, 1, -1 do + cur[r] = cur[r + 1] - cur[r] + end + for k = 1, C do + P[o + k] = cur[k] + end + end + end + end + if pos > lim then + return nil, "truncated frame" + end + return n, nil +end + +return Decode diff --git a/src/Formats/codecs/audio/Tta/init.luau b/src/Formats/codecs/audio/Tta/init.luau new file mode 100644 index 0000000..db0dc48 --- /dev/null +++ b/src/Formats/codecs/audio/Tta/init.luau @@ -0,0 +1,126 @@ +--!strict +-- codecs/audio/Tta: the TTA1 (True Audio) lossless codec. A codec (layer 3). Written from the TTA1 format description +-- (the 22-byte header with its CRC-32, the seek table of frame sizes with its CRC-32, frames of 256 / 245 seconds); +-- no libtta / ffmpeg code (those are LGPL). The frame decoder is codecs/audio/Tta/Decode. Supports format 1 (plain +-- PCM), 8 / 16 / 24 bits, any channel count, the header / seek table / frame CRCs. Not supported: format 2 +-- (password-protected: UNSUPPORTED), TTA2. +-- +-- local info, err = Tta.info(buf, at, limit) -- the header at `at` (after any ID3v2 tag) + the frame table +-- local dec = Tta.decoder(info) +-- local n, err = dec:frame(buf, i) -- frame i (1-based) -> dec.pcm (interleaved integers) +-- +-- Never throws: bad data returns nil, Err. +local Err = require("@formats/core/Err") +local Crc32 = require("@formats/core/Crc32") +local Decode = require("@formats/codecs/audio/Tta/Decode") + +local Tta = {} + +export type Info = { + format: number, + channels: number, + bitsPerSample: number, + sampleRate: number, + samples: number, -- per channel + frameLength: number, -- samples per frame (256 * rate / 245) + frames: number, + offsets: { number }, -- each frame's byte offset + sizes: { number }, +} + +-- info(buf, at, limit) -> Info | nil, Err: the TTA1 header at byte `at` +function Tta.info(buf: buffer, at: number, limit: number): (Info?, Err.Err?) + if at + 22 > limit then + return nil, Err.new(Err.TRUNCATED, "truncated header") + end + if buffer.readstring(buf, at, 4) ~= "TTA1" then + return nil, Err.new(Err.CORRUPT, "no TTA1 header") + end + if Crc32.of(buf, at, 18) ~= buffer.readu32(buf, at + 18) then + return nil, Err.new(Err.CHECKSUM, "header CRC mismatch", at) + end + local format = buffer.readu16(buf, at + 4) + local info: Info = { + format = format, + channels = buffer.readu16(buf, at + 6), + bitsPerSample = buffer.readu16(buf, at + 8), + sampleRate = buffer.readu32(buf, at + 10), + samples = buffer.readu32(buf, at + 14), + frameLength = 0, + frames = 0, + offsets = {}, + sizes = {}, + } + if format == 2 then + return nil, Err.new(Err.UNSUPPORTED, "password-protected TTA") + elseif format ~= 1 then + return nil, Err.new(Err.UNSUPPORTED, "TTA format " .. format) + end + local bits = info.bitsPerSample + if bits ~= 8 and bits ~= 16 and bits ~= 24 then + return nil, Err.new(Err.UNSUPPORTED, bits .. "-bit TTA") + end + if info.channels < 1 or info.sampleRate < 1 then + return nil, Err.new(Err.CORRUPT, "bad header") + end + info.frameLength = (256 * info.sampleRate) // 245 + if info.frameLength < 1 then + return nil, Err.new(Err.CORRUPT, "bad sample rate") + end + local frames = (info.samples + info.frameLength - 1) // info.frameLength + info.frames = frames + local st = at + 22 + if st + frames * 4 + 4 > limit then + return nil, Err.new(Err.TRUNCATED, "truncated seek table") + end + if Crc32.of(buf, st, frames * 4) ~= buffer.readu32(buf, st + frames * 4) then + return nil, Err.new(Err.CHECKSUM, "seek table CRC mismatch", st) + end + local o = st + frames * 4 + 4 + for i = 1, frames do + local size = buffer.readu32(buf, st + (i - 1) * 4) + info.offsets[i] = o + info.sizes[i] = size + o += size + end + return info, nil +end + +-- ------------------------------------------------------------------------------------------------ decoder +export type Decoder = { + info: Info, + pcm: { number }, + limit: number, + frame: (self: Decoder, buf: buffer, i: number) -> (number?, Err.Err?), + state: Decode.State, +} + +local function frame(self: Decoder, buf: buffer, i: number): (number?, Err.Err?) + local info = self.info + if i < 1 or i > info.frames then + return nil, Err.new(Err.ARG, "no frame " .. i) + end + local o, size = info.offsets[i], info.sizes[i] + if o + size > self.limit then + return nil, Err.new(Err.TRUNCATED, "frame " .. i .. " runs past the end", o) + end + local n = if i < info.frames then info.frameLength else info.samples - (info.frames - 1) * info.frameLength + local got, msg = Decode.frame(self.state, buf, o, size, n, self.pcm) + if not got then + return nil, Err.from(msg, o) + end + return got, nil +end + +-- decoder(info, limit) -> Decoder (limit: the end of the file data) +function Tta.decoder(info: Info, limit: number): Decoder + return { + info = info, + pcm = table.create(info.frameLength * info.channels, 0), + limit = limit, + frame = frame, + state = Decode.state(info.channels, info.bitsPerSample // 8), + } +end + +return Tta diff --git a/src/Formats/codecs/audio/WavPack/Block.luau b/src/Formats/codecs/audio/WavPack/Block.luau new file mode 100644 index 0000000..714d2d8 --- /dev/null +++ b/src/Formats/codecs/audio/WavPack/Block.luau @@ -0,0 +1,1483 @@ +--!strict +--!native +--!optimize 2 +-- codecs/audio/WavPack/Block: one WavPack 4 / 5 block (one mono or stereo stream of a frame) -> samples. Ported from +-- WavPack 5.9.0 (David Bryant, BSD 3-clause, licenses/wavpack-LICENSE.txt): unpack.c (the decorrelation passes, joint +-- stereo, the hybrid lossy and hybrid lossless (+ wvc) paths with noise shaping and cross decorrelation, fixup_samples), +-- read_words.c (the median-adaptive entropy decoder: get_words_lossless, get_word, read_code), unpack_floats.c, +-- decorr_utils.c / entropy_utils.c (the metadata) and open_utils.c (metadata parsing, the block checksum). The block +-- CRC (and the wvx CRC) is checked. Not ported: DSD blocks (UNSUPPORTED), pre-4.0 streams, the lossy "mute" heuristics. +-- Never throws: returns nil, message. +local Tables = require("@formats/codecs/audio/WavPack/Tables") + +local readu8, readi8, readu16, readi16, readu32 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32 +local writeu32, readf32 = buffer.writeu32, buffer.readf32 +local band, rshift, countlz = bit32.band, bit32.rshift, bit32.countlz +local exp2s, log2, restoreWeight = Tables.exp2s, Tables.log2, Tables.restoreWeight +local sign, clamp = math.sign, math.clamp + +local Block = {} + +local TWO32 = 4294967296 +local P2: { number } = table.create(34, 0) -- P2[k + 1] = 2^k +for i = 0, 33 do + P2[i + 1] = 2 ^ i +end +-- ONES[b + 1]: the number of trailing 1 bits of the byte b +local ONES: { number } = table.create(256, 0) +for b = 0, 255 do + local n, v = 0, b + while v % 2 == 1 do + n += 1 + v = v // 2 + end + ONES[b + 1] = n +end + +-- header flags +local MONO_FLAG, HYBRID, JOINT, CROSS, SHAPE, FLOAT, INT32 = 4, 8, 0x10, 0x20, 0x40, 0x80, 0x100 +local HBITRATE, HBALANCE, NEW_SHAPING, FALSE_STEREO, DSD = 0x200, 0x400, 0x20000000, 0x40000000, 0x80000000 +local FLOAT_SHIFT_ONES, FLOAT_SHIFT_SAME, FLOAT_SHIFT_SENT, FLOAT_ZEROS_SENT, FLOAT_NEG_ZEROS = 1, 2, 4, 8, 0x10 +local PAD = 64 -- zero bytes after each copied bitstream: reads past the end stay in the buffer +local MAX_SAMPLES = 2 ^ 20 -- per block +local D2, D1 = 17, 9 -- the first data index of the work table (stereo / mono): 8 frames of history in front + +-- ------------------------------------------------------------------------------------------------ metadata +export type Meta = { [number]: number } -- id -> offset; id + 256 -> byte length + +-- meta(buf, p, size) -> Meta | nil, message: the metadata sub-blocks of the block at p (header included in size) +function Block.meta(buf: buffer, p: number, size: number): (Meta?, string?) + local m: Meta = {} + local q, stop = p + 32, p + size + while stop - q >= 2 do + local id = readu8(buf, q) + local len = readu8(buf, q + 1) * 2 + q += 2 + if band(id, 0x80) ~= 0 then + if stop - q < 2 then + return nil, "truncated metadata" + end + len += readu8(buf, q) * 512 + readu8(buf, q + 1) * 131072 + q += 2 + id -= 0x80 + end + local odd = 0 + if band(id, 0x40) ~= 0 then + if len == 0 then + return nil, "odd-sized empty metadata" + end + id -= 0x40 + len -= 1 + odd = 1 + end + if stop - q < len + odd then + return nil, "truncated metadata" + end + m[id] = q + m[id + 256] = len + q += len + odd + end + return m, nil +end + +-- checksum(buf, p, size, m) -> true | false: the ID_BLOCK_CHECKSUM (when there is one) matches +function Block.checksum(buf: buffer, p: number, m: Meta): boolean + local o = m[0x2F] + if not o then + return true + end + local len = m[0x2F + 256] + if len ~= 2 and len ~= 4 then + return false + end + local words = (o - 2 - p) // 2 + local csum = TWO32 - 1 + for i = 0, words - 1 do + csum = (csum * 3 + readu16(buf, p + i * 2)) % TWO32 + end + if len == 4 then + return readu32(buf, o) == csum + end + csum = bit32.bxor(csum, rshift(csum, 16)) + return readu16(buf, o) == band(csum, 0xFFFF) +end + +-- ------------------------------------------------------------------------------------------------ state +export type Reader = { b: buffer, p: number, e: number, n: number } +export type State = { [string]: any } + +function Block.state(): State + return { + W = table.create(D2 + 2 * 4096, 0), + term = table.create(16, 0), + delta = table.create(16, 0), + wA = table.create(16, 0), + wB = table.create(16, 0), + sA = table.create(16 * 8, 0), + sB = table.create(16 * 8, 0), + med = table.create(6, 0), + slow = { 0, 0 }, + limit = { 0, 0 }, + bacc = { 0, 0 }, + bdelta = { 0, 0 }, + sacc = { 0, 0 }, + sdelta = { 0, 0 }, + err = { 0, 0 }, + R1 = { b = buffer.create(0), p = 0, e = 0, n = 0 } :: Reader, + R2 = { b = buffer.create(0), p = 0, e = 0, n = 0 } :: Reader, + R3 = { b = buffer.create(0), p = 0, e = 0, n = 0 } :: Reader, + scratch = buffer.create(4), + } +end + +-- open a bitstream: the bytes [o, o + len) copied with PAD zero bytes after them +local function openReader(R: Reader, buf: buffer, o: number, len: number) + if buffer.len(R.b) < len + PAD then + R.b = buffer.create(len + PAD + 1024) + else + buffer.fill(R.b, len, 0, PAD) + end + buffer.copy(R.b, 0, buf, o, len) + R.p = 0 + R.e = len * 8 + R.n = len + PAD +end + +-- ------------------------------------------------------------------------------------------------ bit reading +-- bits(R, n) -> the next n (<= 32) bits, LSB first +local function bits(R: Reader, n: number): number + if n <= 0 then + return 0 + end + local p = R.p + local byte = rshift(p, 3) + if byte + 8 > R.n then + R.p = R.e + 1 -- overrun: the caller's end check fails + return 0 + end + local b = R.b + if n <= 25 then + R.p = p + n + return band(rshift(readu32(b, byte), band(p, 7)), P2[n + 1] - 1) + end + local lo = band(rshift(readu32(b, byte), band(p, 7)), 0xFFFF) + p += 16 + R.p = p + n - 16 + return lo + band(rshift(readu32(b, rshift(p, 3)), band(p, 7)), P2[n - 15] - 1) * 65536 +end + +local function bit(R: Reader): number + return bits(R, 1) +end + +-- trailing(R, max) -> the number of 1 bits from the read position (up to max; a byte at a time), consumed with the 0 +-- after them when fewer than max +local function trailing(R: Reader, max: number): number + local c = 0 + while c < max do + local p = R.p + local byte = rshift(p, 3) + if byte + 8 > R.n then + R.p = R.e + 1 + return max + end + local ones = ONES[band(rshift(readu32(R.b, byte), band(p, 7)), 255) + 1] + if ones < 8 then + if c + ones >= max then + R.p = p + (max - c) + return max + end + R.p = p + ones + 1 + return c + ones + end + c += 8 + R.p = p + 8 + end + -- (max reached inside a run of 8: give back the extra ones) + R.p -= c - max + return max +end + +-- the "Elias gamma"-like count (cbits ones, a zero, cbits - 1 bits) -> value | nil (33 ones) +local function gamma(R: Reader): number? + local c = trailing(R, 33) + if c == 33 then + return nil + end + if c < 2 then + return c + end + return bits(R, c - 1) + P2[c] +end + +-- readCode(R, maxcode) -> 0 .. maxcode (read_code) +local function readCode(R: Reader, maxcode: number): number + if maxcode < 2 then + return if maxcode == 1 then bits(R, 1) else 0 + end + local bc = 32 - countlz(maxcode) + local extras = P2[bc + 1] - maxcode - 1 + local code = bits(R, bc - 1) + if code >= extras then + code = code * 2 - extras + bits(R, 1) + end + return code +end + +-- ones(R) -> the unary count with its escape (LIMIT_ONES = 16) | nil (the end marker) +local function onesCount(R: Reader): number? + local c = trailing(R, 17) + if c == 17 then + return nil + end + if c == 16 then + local g = gamma(R) + if not g then + return nil + end + c = g + 16 + end + return c +end + +-- ------------------------------------------------------------------------------------------------ lossless entropy +-- wordsLossless(st, n, stereo) -> true | nil: n samples (n * 2 when stereo) into st.W from the data index (the hot +-- loop of get_words_lossless, with the bit reader in locals) +local function wordsLossless(st: State, count: number, d: number): boolean + local R: Reader = st.R1 + local b, pos, lim = R.b, R.p, R.e + local W = st.W + local med = st.med + local stereo = d == D2 + -- (a0, a1, a2): the current channel's medians, (c0, c1, c2) the other's; swapped every sample when stereo + local a0, a1, a2, c0, c1, c2 = med[4], med[5], med[6], med[1], med[2], med[3] + if not stereo then + a0, a1, a2, c0, c1, c2 = med[1], med[2], med[3], 0, 0, 0 + end + local hz, ho, za = 0, 0, 0 + for idx = d, d + count - 1 do + if stereo then + a0, a1, a2, c0, c1, c2 = c0, c1, c2, a0, a1, a2 + end + if pos > lim then + return false + end + if hz ~= 0 then + hz = 0 + local maxcode = a0 // 16 + a0 -= ((a0 + 126) // 128) * 2 + local w = rshift(readu32(b, rshift(pos, 3)), band(pos, 7)) + local low, used = 0, 0 + if maxcode < 2 then + if maxcode == 1 then + low, used = band(w, 1), 1 + end + else + local bc = 32 - countlz(maxcode) + if bc > 24 then + R.p = pos + low = readCode(R, maxcode) + pos = R.p + w = rshift(readu32(b, rshift(pos, 3)), band(pos, 7)) + else + local extras = P2[bc + 1] - maxcode - 1 + low = band(w, P2[bc] - 1) + if low >= extras then + low = low * 2 - extras + band(rshift(w, bc - 1), 1) + used = bc + else + used = bc - 1 + end + end + end + if band(rshift(w, used), 1) ~= 0 then + W[idx] = -low - 1 + else + W[idx] = low + end + pos += used + 1 + continue + end + if a0 < 2 and ho == 0 and c0 < 2 then + if za > 0 then + za -= 1 + if za > 0 then + W[idx] = 0 + continue + end + else + R.p = pos + local g = gamma(R) + pos = R.p + if not g then + return false + end + za = g + if za > 0 then + a0, a1, a2, c0, c1, c2 = 0, 0, 0, 0, 0, 0 + W[idx] = 0 + continue + end + end + end + local w = rshift(readu32(b, rshift(pos, 3)), band(pos, 7)) + local ones = ONES[band(w, 255) + 1] + if ones == 8 then + ones = 8 + ONES[band(rshift(w, 8), 255) + 1] + end + if ones < 16 then + pos += ones + 1 + else + if band(w, 0x10000) ~= 0 then + return false + end + R.p = pos + 17 + local g = gamma(R) + pos = R.p + if not g then + return false + end + ones = g + 16 + end + local hold = ho + ho = band(ones, 1) + hz = 1 - ho + ones = ones // 2 + hold + local low, high + if ones == 0 then + low = 0 + high = a0 // 16 + a0 -= ((a0 + 126) // 128) * 2 + else + low = a0 // 16 + 1 + a0 += ((a0 + 128) // 128) * 5 + if ones == 1 then + high = low + a1 // 16 + a1 -= ((a1 + 62) // 64) * 2 + else + low += a1 // 16 + 1 + a1 += ((a1 + 64) // 64) * 5 + if ones == 2 then + high = low + a2 // 16 + a2 -= ((a2 + 30) // 32) * 2 + else + low += (ones - 2) * (a2 // 16 + 1) + high = low + a2 // 16 + a2 += ((a2 + 32) // 32) * 5 + end + end + end + local maxcode = high - low + w = rshift(readu32(b, rshift(pos, 3)), band(pos, 7)) + local used = 0 + if maxcode < 2 then + if maxcode == 1 then + low += band(w, 1) + used = 1 + end + else + if maxcode >= 536870912 then + return false + end + local bc = 32 - countlz(maxcode) + if bc > 24 then + R.p = pos + low += readCode(R, maxcode) + pos = R.p + w = rshift(readu32(b, rshift(pos, 3)), band(pos, 7)) + else + local extras = P2[bc + 1] - maxcode - 1 + local code = band(w, P2[bc] - 1) + if code >= extras then + code = code * 2 - extras + band(rshift(w, bc - 1), 1) + used = bc + else + used = bc - 1 + end + low += code + end + end + if band(rshift(w, used), 1) ~= 0 then + W[idx] = -low - 1 + else + W[idx] = low + end + pos += used + 1 + end + R.p = pos + return pos <= lim +end + +-- ------------------------------------------------------------------------------------------------ hybrid entropy +local function updateErrorLimit(st: State, flags: number, mono: boolean) + local bacc, bdelta, slow, limit = st.bacc, st.bdelta, st.slow, st.limit + bacc[1] = (bacc[1] + bdelta[1]) % TWO32 + local br0 = bacc[1] // 65536 + if mono then + if band(flags, HBITRATE) ~= 0 then + local sl0 = (slow[1] + 128) // 256 + limit[1] = if sl0 - br0 > -256 then exp2s(sl0 - br0 + 256) % TWO32 else 0 + else + limit[1] = exp2s(br0) % TWO32 + end + return + end + bacc[2] = (bacc[2] + bdelta[2]) % TWO32 + local br1 = bacc[2] // 65536 + if band(flags, HBITRATE) ~= 0 then + local sl0 = (slow[1] + 128) // 256 + local sl1 = (slow[2] + 128) // 256 + if band(flags, HBALANCE) ~= 0 then + local balance = (sl1 - sl0 + br1 + 1) // 2 + if balance > br0 then + br1 = br0 * 2 + br0 = 0 + elseif -balance > br0 then + br0 = br0 * 2 + br1 = 0 + else + br1 = br0 + balance + br0 = br0 - balance + end + end + limit[1] = if sl0 - br0 > -256 then exp2s(sl0 - br0 + 256) % TWO32 else 0 + limit[2] = if sl1 - br1 > -256 then exp2s(sl1 - br1 + 256) % TWO32 else 0 + else + limit[1] = exp2s(br0) % TWO32 + limit[2] = exp2s(br1) % TWO32 + end +end + +-- getWord(st, chan, flags, mono) -> value, correction | nil (get_word; chan 0 / 1) +local function getWord(st: State, chan: number, flags: number, mono: boolean): (number?, number) + local R: Reader = st.R1 + local med = st.med + local mb = chan * 3 + local correction = 0 + if R.p > R.e then + return nil, 0 + end + if med[1] < 2 and st.hz == 0 and st.ho == 0 and med[4] < 2 then + if st.za > 0 then + st.za -= 1 + if st.za > 0 then + local s = st.slow + s[chan + 1] -= (s[chan + 1] + 128) // 256 + return 0, 0 + end + else + local g = gamma(R) + if not g then + return nil, 0 + end + st.za = g + if g > 0 then + local s = st.slow + s[chan + 1] -= (s[chan + 1] + 128) // 256 + for k = 1, 6 do + med[k] = 0 + end + return 0, 0 + end + end + end + local ones + if st.hz ~= 0 then + ones = 0 + st.hz = 0 + else + local c = onesCount(R) + if not c then + return nil, 0 + end + ones = c + if st.ho ~= 0 then + st.ho = band(ones, 1) + ones = ones // 2 + 1 + else + st.ho = band(ones, 1) + ones = ones // 2 + end + st.hz = 1 - st.ho + end + if band(flags, HYBRID) ~= 0 and chan == 0 then + updateErrorLimit(st, flags, mono) + end + local m0, m1, m2 = med[mb + 1], med[mb + 2], med[mb + 3] + local low, high + if ones == 0 then + low = 0 + high = m0 // 16 + m0 -= ((m0 + 126) // 128) * 2 + else + low = m0 // 16 + 1 + m0 += ((m0 + 128) // 128) * 5 + if ones == 1 then + high = low + m1 // 16 + m1 -= ((m1 + 62) // 64) * 2 + else + low += m1 // 16 + 1 + m1 += ((m1 + 64) // 64) * 5 + if ones == 2 then + high = low + m2 // 16 + m2 -= ((m2 + 30) // 32) * 2 + else + low += (ones - 2) * (m2 // 16 + 1) + high = low + m2 // 16 + m2 += ((m2 + 32) // 32) * 5 + end + end + end + med[mb + 1], med[mb + 2], med[mb + 3] = m0 % TWO32, m1 % TWO32, m2 % TWO32 + low = band(low % TWO32, 0x7FFFFFFF) + high = band(high % TWO32, 0x7FFFFFFF) + if low > high then + high = low + end + local mid = (high + low + 1) // 2 + local limit = st.limit[chan + 1] + if limit == 0 then + mid = readCode(R, high - low) + low + else + while high - low > limit do + if R.p > R.e then + return nil, 0 + end + if bits(R, 1) == 1 then + low = mid + mid = (high + low + 1) // 2 + else + high = mid - 1 + mid = (high + low + 1) // 2 + end + end + end + local sign = bits(R, 1) + if st.wvc and limit ~= 0 then + local value = readCode(st.R2, high - low) + low + correction = if sign == 1 then mid - value else value - mid + end + if band(flags, HBITRATE) ~= 0 then + local s = st.slow + s[chan + 1] = s[chan + 1] - (s[chan + 1] + 128) // 256 + log2(mid) + end + return if sign == 1 then -mid - 1 else mid, correction +end + +-- ------------------------------------------------------------------------------------------------ decorrelation +-- the decorrelation passes over the whole block (stereo, from W[D2]): unpack.c decorr_stereo_pass +local function passesStereo(st: State, n: number) + local W = st.W + local last = D2 + 2 * n - 2 + local terms, deltas, wAs, wBs, sA, sB = st.term, st.delta, st.wA, st.wB, st.sA, st.sB + for t = 1, st.nterms do + local term, delta, wA, wB = terms[t], deltas[t], wAs[t], wBs[t] + local so = (t - 1) * 8 + if term > 8 then + local a0, a1, b0, b1 = sA[so + 1], sA[so + 2], sB[so + 1], sB[so + 2] + local dv = term - 16 -- 17: 2 a0 - a1, 18: a0 + (a0 - a1) / 2 + for i = D2, last, 2 do + local sam = a0 + (a0 - a1) // dv + local x = W[i] + local o = (wA * sam + 512) // 1024 + x + wA += delta * sign(sam * x) + a1, a0 = a0, o + W[i] = o + sam = b0 + (b0 - b1) // dv + x = W[i + 1] + o = (wB * sam + 512) // 1024 + x + wB += delta * sign(sam * x) + b1, b0 = b0, o + W[i + 1] = o + end + elseif term > 0 then + for j = 0, term - 1 do + W[D2 + 2 * (j - term)] = sA[so + j + 1] + W[D2 + 1 + 2 * (j - term)] = sB[so + j + 1] + end + local back = 2 * term + for i = D2, last, 2 do + local sam = W[i - back] + local x = W[i] + W[i] = (wA * sam + 512) // 1024 + x + wA += delta * sign(sam * x) + sam = W[i + 1 - back] + x = W[i + 1] + W[i + 1] = (wB * sam + 512) // 1024 + x + wB += delta * sign(sam * x) + end + elseif term == -1 then + local sa = sA[so + 1] + for i = D2, last, 2 do + local x = W[i] + local sam = x + (wA * sa + 512) // 1024 + wA = clamp(wA + delta * sign(sa * x), -1024, 1024) + W[i] = sam + x = W[i + 1] + sa = x + (wB * sam + 512) // 1024 + wB = clamp(wB + delta * sign(sam * x), -1024, 1024) + W[i + 1] = sa + end + elseif term == -2 then + local sb = sB[so + 1] + for i = D2, last, 2 do + local x = W[i + 1] + local sam = x + (wB * sb + 512) // 1024 + wB = clamp(wB + delta * sign(sb * x), -1024, 1024) + W[i + 1] = sam + x = W[i] + sb = x + (wA * sam + 512) // 1024 + wA = clamp(wA + delta * sign(sam * x), -1024, 1024) + W[i] = sb + end + else -- -3 + local sa, sb = sA[so + 1], sB[so + 1] + for i = D2, last, 2 do + local x = W[i] + local samA = x + (wA * sa + 512) // 1024 + wA = clamp(wA + delta * sign(sa * x), -1024, 1024) + x = W[i + 1] + local samB = x + (wB * sb + 512) // 1024 + wB = clamp(wB + delta * sign(sb * x), -1024, 1024) + W[i], W[i + 1] = samA, samB + sa, sb = samB, samA + end + end + end +end + +-- the decorrelation passes (mono, from W[D1]): unpack.c decorr_mono_pass +local function passesMono(st: State, n: number) + local W = st.W + local last = D1 + n - 1 + local terms, deltas, wAs, sA = st.term, st.delta, st.wA, st.sA + for t = 1, st.nterms do + local term, delta, wA = terms[t], deltas[t], wAs[t] + local so = (t - 1) * 8 + if term > 8 then + local a0, a1 = sA[so + 1], sA[so + 2] + local dv = term - 16 -- 17: 2 a0 - a1, 18: a0 + (a0 - a1) / 2 + for i = D1, last do + local sam = a0 + (a0 - a1) // dv + local x = W[i] + local o = (wA * sam + 512) // 1024 + x + wA += delta * sign(sam * x) + a1, a0 = a0, o + W[i] = o + end + else + for j = 0, term - 1 do + W[D1 + j - term] = sA[so + j + 1] + end + for i = D1, last do + local sam = W[i - term] + local x = W[i] + W[i] = (wA * sam + 512) // 1024 + x + wA += delta * sign(sam * x) + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ hybrid lossless +local function shaped(st: State, c: number, flags: number, correction: number): number + -- returns the value to subtract (temp) and updates the error state (noise shaping, unpack.c) + local sacc, sdelta, err = st.sacc, st.sdelta, st.err + sacc[c] = (sacc[c] + sdelta[c]) % TWO32 + local sw = sacc[c] // 65536 + if sw >= 32768 then + sw -= 65536 + end + local temp = -((sw * err[c] + 512) // 1024) + if band(flags, NEW_SHAPING) ~= 0 and sw < 0 and temp ~= 0 then + if temp == err[c] then + temp = if temp < 0 then temp + 1 else temp - 1 + end + err[c] = temp - correction + else + err[c] = -correction + end + return temp +end + +local function hybridMono(st: State, n: number, flags: number): boolean + local W = st.W + local terms, deltas, wAs, sA = st.term, st.delta, st.wA, st.sA + local nterms = st.nterms + local m = 0 + local crc = TWO32 - 1 + for i = 0, n - 1 do + local word, corr = getWord(st, 0, flags, true) + if not word then + return false + end + local rw = word + for t = 1, nterms do + local term, so = terms[t], (t - 1) * 8 + local sam, k + if term > 8 then + sam = if term % 2 == 1 then 2 * sA[so + 1] - sA[so + 2] else (3 * sA[so + 1] - sA[so + 2]) // 2 + sA[so + 2] = sA[so + 1] + k = 0 + else + sam = sA[so + m + 1] + k = band(m + term, 7) + end + local temp = (wAs[t] * sam + 512) // 1024 + rw + wAs[t] += deltas[t] * sign(sam * rw) + sA[so + k + 1] = temp + rw = temp + end + m = band(m + 1, 7) + if band(flags, SHAPE) ~= 0 then + local temp = shaped(st, 1, flags, corr) + rw += corr - temp + else + rw += corr + end + crc = (crc * 3 + rw) % TWO32 + W[D1 + i] = rw + end + st.crcv = crc + return true +end + +local function hybridStereo(st: State, n: number, flags: number): boolean + local W = st.W + local terms, deltas, wAs, wBs, sA, sB = st.term, st.delta, st.wA, st.wB, st.sA, st.sB + local nterms = st.nterms + local m = 0 + local crc = TWO32 - 1 + local cross = band(flags, CROSS) ~= 0 + local joint = band(flags, JOINT) ~= 0 + for i = 0, n - 1 do + local left, corr0 = getWord(st, 0, flags, false) + if not left then + return false + end + local right, corr1 = getWord(st, 1, flags, false) + if not right then + return false + end + local leftc, rightc = 0, 0 + if cross then + leftc, rightc = left + corr0, right + corr1 + for t = 1, nterms do + local term, so = terms[t], (t - 1) * 8 + if term > 0 then + local samA, samB + if term > 8 then + if term % 2 == 1 then + samA = 2 * sA[so + 1] - sA[so + 2] + samB = 2 * sB[so + 1] - sB[so + 2] + else + samA = (3 * sA[so + 1] - sA[so + 2]) // 2 + samB = (3 * sB[so + 1] - sB[so + 2]) // 2 + end + else + samA, samB = sA[so + m + 1], sB[so + m + 1] + end + leftc += (wAs[t] * samA + 512) // 1024 + rightc += (wBs[t] * samB + 512) // 1024 + elseif term == -1 then + leftc += (wAs[t] * sA[so + 1] + 512) // 1024 + rightc += (wBs[t] * leftc + 512) // 1024 + else + rightc += (wBs[t] * sB[so + 1] + 512) // 1024 + if term == -3 then + leftc += (wAs[t] * sA[so + 1] + 512) // 1024 + else + leftc += (wAs[t] * rightc + 512) // 1024 + end + end + end + if joint then + rightc -= leftc // 2 + leftc += rightc + end + end + for t = 1, nterms do + local term, delta, so = terms[t], deltas[t], (t - 1) * 8 + if term > 0 then + local samA, samB, k + if term > 8 then + if term % 2 == 1 then + samA = 2 * sA[so + 1] - sA[so + 2] + samB = 2 * sB[so + 1] - sB[so + 2] + else + samA = (3 * sA[so + 1] - sA[so + 2]) // 2 + samB = (3 * sB[so + 1] - sB[so + 2]) // 2 + end + sA[so + 2] = sA[so + 1] + sB[so + 2] = sB[so + 1] + k = 0 + else + samA, samB = sA[so + m + 1], sB[so + m + 1] + k = band(m + term, 7) + end + local left2 = (wAs[t] * samA + 512) // 1024 + left + local right2 = (wBs[t] * samB + 512) // 1024 + right + wAs[t] += delta * sign(samA * left) + wBs[t] += delta * sign(samB * right) + left, right = left2, right2 + sA[so + k + 1], sB[so + k + 1] = left, right + elseif term == -1 then + local sa = sA[so + 1] + local left2 = left + (wAs[t] * sa + 512) // 1024 + wAs[t] = clamp(wAs[t] + delta * sign(sa * left), -1024, 1024) + left = left2 + local right2 = right + (wBs[t] * left2 + 512) // 1024 + wBs[t] = clamp(wBs[t] + delta * sign(left2 * right), -1024, 1024) + right = right2 + sA[so + 1] = right + else + local sb = sB[so + 1] + local right2 = right + (wBs[t] * sb + 512) // 1024 + wBs[t] = clamp(wBs[t] + delta * sign(sb * right), -1024, 1024) + right = right2 + if term == -3 then + right2 = sA[so + 1] + sA[so + 1] = right + end + local left2 = left + (wAs[t] * right2 + 512) // 1024 + wAs[t] = clamp(wAs[t] + delta * sign(right2 * left), -1024, 1024) + left = left2 + sB[so + 1] = left + end + end + m = band(m + 1, 7) + if not cross then + leftc, rightc = left + corr0, right + corr1 + if joint then + rightc -= leftc // 2 + leftc += rightc + end + end + if joint then + right -= left // 2 + left += right + end + if band(flags, SHAPE) ~= 0 then + local temp = shaped(st, 1, flags, leftc - left) + left = leftc - temp + temp = shaped(st, 2, flags, rightc - right) + right = rightc - temp + else + left, right = leftc, rightc + end + crc = (crc * 9 + left * 3 + right) % TWO32 + W[D2 + 2 * i], W[D2 + 2 * i + 1] = left, right + end + st.crcv = crc + return true +end + +-- ------------------------------------------------------------------------------------------------ metadata -> state +local function readMeta(st: State, buf: buffer, m: Meta, flags: number, version: number): string? + local mono = band(flags, MONO_FLAG + FALSE_STEREO) ~= 0 + local o = m[2] + if o then -- decorrelation terms + local cnt = m[2 + 256] + if cnt > 16 then + return "too many decorrelation terms" + end + st.nterms = cnt + for i = 0, cnt - 1 do + local v = readu8(buf, o + i) + local t = cnt - i + local term = band(v, 0x1F) - 5 + if term == 0 or term < -3 or (term > 8 and term < 17) or term > 18 or (mono and term < 0) then + return "bad decorrelation term" + end + st.term[t] = term + st.delta[t] = band(rshift(v, 5), 7) + end + end + local nterms = st.nterms + o = m[3] + if o then -- weights, from the last pass back + for t = 1, nterms do + st.wA[t], st.wB[t] = 0, 0 + end + local cnt = m[3 + 256] + if not mono then + cnt //= 2 + end + if cnt > nterms then + return "too many decorrelation weights" + end + local q = o + for t = nterms, nterms - cnt + 1, -1 do + st.wA[t] = restoreWeight(readi8(buf, q)) + q += 1 + if not mono then + st.wB[t] = restoreWeight(readi8(buf, q)) + q += 1 + end + end + end + local sA, sB = st.sA, st.sB + o = m[4] + if o then -- decorrelation samples, from the last pass back + for k = 1, nterms * 8 do + sA[k], sB[k] = 0, 0 + end + local q, stop = o, o + m[4 + 256] + if version == 0x402 and band(flags, HYBRID) ~= 0 then + if q + (if mono then 2 else 4) > stop then + return "bad decorrelation samples" + end + st.err[1] = exp2s(readi16(buf, q)) + q += 2 + if not mono then + st.err[2] = exp2s(readi16(buf, q)) + q += 2 + end + end + local t = nterms + while t >= 1 and q < stop do + local term, so = st.term[t], (t - 1) * 8 + if term > 8 then + if q + (if mono then 4 else 8) > stop then + return "bad decorrelation samples" + end + sA[so + 1], sA[so + 2] = exp2s(readi16(buf, q)), exp2s(readi16(buf, q + 2)) + q += 4 + if not mono then + sB[so + 1], sB[so + 2] = exp2s(readi16(buf, q)), exp2s(readi16(buf, q + 2)) + q += 4 + end + elseif term < 0 then + if q + 4 > stop then + return "bad decorrelation samples" + end + sA[so + 1], sB[so + 1] = exp2s(readi16(buf, q)), exp2s(readi16(buf, q + 2)) + q += 4 + else + for k = 1, term do + if q + (if mono then 2 else 4) > stop then + return "bad decorrelation samples" + end + sA[so + k] = exp2s(readi16(buf, q)) + q += 2 + if not mono then + sB[so + k] = exp2s(readi16(buf, q)) + q += 2 + end + end + end + t -= 1 + end + if q ~= stop then + return "bad decorrelation samples" + end + end + o = m[5] + if o then -- entropy medians + if m[5 + 256] ~= (if mono then 6 else 12) then + return "bad entropy variables" + end + for k = 0, (if mono then 2 else 5) do + st.med[k + 1] = exp2s(readu16(buf, o + k * 2)) % TWO32 + end + end + o = m[6] + if o then -- hybrid profile + local q, stop = o, o + m[6 + 256] + local w = if mono then 2 else 4 + if band(flags, HBITRATE) ~= 0 then + if q + w > stop then + return "bad hybrid profile" + end + st.slow[1] = exp2s(readu16(buf, q)) % TWO32 + if not mono then + st.slow[2] = exp2s(readu16(buf, q + 2)) % TWO32 + end + q += w + end + if q + w > stop then + return "bad hybrid profile" + end + st.bacc[1] = readu16(buf, q) * 65536 + if not mono then + st.bacc[2] = readu16(buf, q + 2) * 65536 + end + q += w + if q < stop then + if q + w > stop then + return "bad hybrid profile" + end + st.bdelta[1] = exp2s(readi16(buf, q)) + if not mono then + st.bdelta[2] = exp2s(readi16(buf, q + 2)) + end + q += w + if q < stop then + return "bad hybrid profile" + end + end + end + o = m[7] + if o then -- noise shaping + local len = m[7 + 256] + if len == 2 then + st.sacc[1] = (restoreWeight(readi8(buf, o)) * 65536) % TWO32 + st.sacc[2] = (restoreWeight(readi8(buf, o + 1)) * 65536) % TWO32 + elseif len >= (if mono then 4 else 8) then + st.err[1] = exp2s(readi16(buf, o)) + st.sacc[1] = exp2s(readi16(buf, o + 2)) % TWO32 + if not mono then + st.err[2] = exp2s(readi16(buf, o + 4)) + st.sacc[2] = exp2s(readi16(buf, o + 6)) % TWO32 + end + local q = o + (if mono then 4 else 8) + if len == (if mono then 6 else 12) then + st.sdelta[1] = exp2s(readi16(buf, q)) % TWO32 + if not mono then + st.sdelta[2] = exp2s(readi16(buf, q + 2)) % TWO32 + end + end + else + return "bad shaping weights" + end + end + o = m[8] + if o then + if m[8 + 256] ~= 4 then + return "bad float info" + end + st.fflags, st.fshift, st.fmaxexp = readu8(buf, o), readu8(buf, o + 1), readu8(buf, o + 2) + end + o = m[9] + if o then + if m[9 + 256] ~= 4 then + return "bad int32 info" + end + st.isent, st.izeros, st.iones, st.idups = readu8(buf, o), readu8(buf, o + 1), readu8(buf, o + 2), readu8(buf, o + 3) + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ fixup + output +-- the float conversion of one value (float_values; R = the wvx stream or nil) +local function floatValue(st: State, v: number, R: Reader?): number + local fflags, exp = st.fflags, st.fmaxexp + local mant, e, sign = 0, 0, 0 + if v == 0 then + if R then + if band(fflags, FLOAT_ZEROS_SENT) ~= 0 then + if bits(R, 1) == 1 then + mant = bits(R, 23) + if exp >= 25 then + e = bits(R, 8) + end + sign = bits(R, 1) + elseif band(fflags, FLOAT_NEG_ZEROS) ~= 0 then + sign = bits(R, 1) + end + end + end + else + v = (v * P2[band(st.fshift, 31) + 1]) % TWO32 + if v >= 2147483648 then + v -= TWO32 + end + if v < 0 then + v = -v + sign = 1 + end + if R then + if v == 0x1000000 then + if bits(R, 1) == 1 then + mant = bits(R, 23) + end + e = 255 + else + local shift = 0 + if exp > 0 then + while v < 0x800000 do + exp -= 1 + if exp == 0 then + break + end + shift += 1 + v *= 2 + end + end + shift = band(shift, 31) + if shift > 0 then + if band(fflags, FLOAT_SHIFT_ONES) ~= 0 or (band(fflags, FLOAT_SHIFT_SAME) ~= 0 and bits(R, 1) == 1) then + v += P2[shift + 1] - 1 + elseif band(fflags, FLOAT_SHIFT_SENT) ~= 0 then + local mask = P2[shift + 1] - 1 + local zeros = 0 + local maxOnes, minZeros = st.fmaxones, st.fminzeros + if maxOnes > 0 and shift > maxOnes then + zeros = shift - maxOnes + end + if minZeros > zeros then + zeros = if minZeros > shift then shift else minZeros + end + local sc = shift - zeros + if sc > 0 then + v = bit32.bor(v % TWO32, band(bits(R, sc) * P2[zeros + 1], mask)) + end + end + end + mant = band(v % TWO32, 0x7FFFFF) + e = band(exp, 255) + end + else + if v >= 0x1000000 then + while band(v, 0xF000000) ~= 0 do + v //= 2 + exp += 1 + end + elseif exp > 0 then + local shift = 0 + while v < 0x800000 do + exp -= 1 + if exp == 0 then + break + end + shift += 1 + v *= 2 + end + shift = band(shift, 31) + if shift > 0 and band(fflags, FLOAT_SHIFT_ONES) ~= 0 then + v += P2[shift + 1] - 1 + end + end + mant = band(v % TWO32, 0x7FFFFF) + e = band(exp, 255) + end + end + if R then + st.crcx = (st.crcx * 27 + mant * 9 + e * 3 + sign) % TWO32 + end + local sc = st.scratch + writeu32(sc, 0, sign * 2147483648 + e * 8388608 + mant) + return readf32(sc, 0) +end + +-- emit: fixup_samples + false stereo + interleave into P (stride C, first channel c0 0-based) +local function emit(st: State, flags: number, n: number, d: number, P: { number }, c0: number, C: number, lossy: boolean) + local W = st.W + local s = if d == D2 then 2 else 1 + local count = n * s + local R: Reader? = if st.wvx then st.R3 else nil + if band(flags, FLOAT) ~= 0 then + for k = 0, count - 1 do + W[d + k] = floatValue(st, W[d + k], R) + end + else + local shift = band(rshift(flags, 13), 31) + if band(flags, INT32) ~= 0 then + local sent, zeros, ones, dups = band(st.isent, 31), band(st.izeros, 31), band(st.iones, 31), band(st.idups, 31) + if R then + local maxw = st.imaxw + local crc = st.crcx + for k = d, d + count - 1 do + local v = W[k] + if sent > 0 then + if maxw > 0 then + local pv = if v < 0 then -v - 1 else v + local width = (32 - countlz(pv)) + sent + local btr = sent + if width > maxw then + btr -= width - maxw + end + if width <= maxw or btr > 0 then + v = (v * P2[btr + 1] + bits(R, btr)) * P2[sent - btr + 1] + else + v *= P2[sent + 1] + end + else + v = v * P2[sent + 1] + bits(R, sent) + end + end + if zeros > 0 then + v *= P2[zeros + 1] + elseif ones > 0 then + v = (v + 1) * P2[ones + 1] - 1 + elseif dups > 0 then + local lo = v % 2 + v = (v + lo) * P2[dups + 1] - lo + end + v %= TWO32 + if v >= 2147483648 then + v -= TWO32 + end + crc = (crc * 9 + (v % 65536) * 3 + (v // 65536) % 65536) % TWO32 + W[k] = v + end + st.crcx = crc + elseif sent == 0 and zeros + ones + dups > 0 then + while lossy and band(flags, 3) == 3 and shift < 8 do + if zeros > 0 then + zeros -= 1 + elseif ones > 0 then + ones -= 1 + elseif dups > 0 then + dups -= 1 + else + break + end + shift += 1 + end + for k = d, d + count - 1 do + local v = W[k] + if zeros > 0 then + v *= P2[zeros + 1] + elseif ones > 0 then + v = (v + 1) * P2[ones + 1] - 1 + elseif dups > 0 then + local lo = v % 2 + v = (v + lo) * P2[dups + 1] - lo + end + W[k] = v + end + else + shift += zeros + sent + ones + dups + end + end + shift = band(shift, 31) + if lossy then + local bytes = band(flags, 3) + local top = if bytes == 0 then 127 elseif bytes == 1 then 32767 elseif bytes == 2 then 8388607 else 2147483647 + local minv, maxv = (-top - 1) // P2[shift + 1], top // P2[shift + 1] + local mul = P2[shift + 1] + for k = d, d + count - 1 do + local v = W[k] + if v < minv then + v = minv + elseif v > maxv then + v = maxv + end + W[k] = v * mul + end + elseif shift > 0 then + local mul = P2[shift + 1] + for k = d, d + count - 1 do + W[k] *= mul + end + end + end + -- interleave + if s == 2 then + if c0 == 0 and C == 2 then + for k = 0, count - 1 do + P[k + 1] = W[d + k] + end + elseif c0 + 2 <= C then + for i = 0, n - 1 do + P[i * C + c0 + 1] = W[d + 2 * i] + P[i * C + c0 + 2] = W[d + 2 * i + 1] + end + else + for i = 0, n - 1 do + P[i * C + c0 + 1] = W[d + 2 * i] + end + end + elseif band(flags, FALSE_STEREO) ~= 0 and c0 + 2 <= C then + for i = 0, n - 1 do + local v = W[d + i] + P[i * C + c0 + 1] = v + P[i * C + c0 + 2] = v + end + elseif C == 1 then + for k = 0, n - 1 do + P[k + 1] = W[d + k] + end + else + for i = 0, n - 1 do + P[i * C + c0 + 1] = W[d + i] + end + end +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(st, buf, p, size, P, c0, C, cbuf?, cp?, csize?) -> channels written (1 / 2) | nil, message: the block at p +-- (header included in size) into P (interleaved, stride C, from channel c0), with its correction block if given +function Block.decode(st: State, buf: buffer, p: number, size: number, P: { number }, c0: number, C: number, cbuf: buffer?, cp: number?, csize: number?): (number?, string?) + local version = readu16(buf, p + 8) + local n = readu32(buf, p + 20) + local flags = readu32(buf, p + 24) + local crcWant = readu32(buf, p + 28) + if band(flags, DSD) ~= 0 then + return nil, "unsupported: DSD audio" + end + if version < 0x402 or version > 0x410 then + return nil, "unsupported: stream version " .. version + end + if n > MAX_SAMPLES then + return nil, "limit: block of " .. n .. " samples" + end + if band(flags, MONO_FLAG + FALSE_STEREO) == MONO_FLAG + FALSE_STEREO then + return nil, "bad block flags" + end + local mm, merr = Block.meta(buf, p, size) + if not mm then + return nil, merr + end + local m: Meta = mm + local cm: Meta = {} + local cb: buffer = buf + local hasC = false + if cbuf and cp and csize then + local cmeta, cerr = Block.meta(cbuf, cp, csize) + if not cmeta then + return nil, cerr + end + cm, cb, hasC = cmeta, cbuf, true + crcWant = readu32(cbuf, cp + 28) + end + -- reset + st.nterms = 0 + local sA, sB, wA, wB = st.sA, st.sB, st.wA, st.wB + for k = 1, 128 do + sA[k], sB[k] = 0, 0 + end + for t = 1, 16 do + wA[t], wB[t] = 0, 0 + end + local med = st.med + for k = 1, 6 do + med[k] = 0 + end + st.slow[1], st.slow[2], st.limit[1], st.limit[2] = 0, 0, 0, 0 + st.bacc[1], st.bacc[2], st.bdelta[1], st.bdelta[2] = 0, 0, 0, 0 + st.sacc[1], st.sacc[2], st.sdelta[1], st.sdelta[2], st.err[1], st.err[2] = 0, 0, 0, 0, 0, 0 + st.fflags, st.fshift, st.fmaxexp, st.fminzeros, st.fmaxones = 0, 0, 0, 0, 0 + st.isent, st.izeros, st.iones, st.idups, st.imaxw = 0, 0, 0, 0, 0 + st.hz, st.ho, st.za = 0, 0, 0 + st.crcx = TWO32 - 1 + st.wvc, st.wvx = false, false + local e = readMeta(st, buf, m, flags, version) + if e then + return nil, e + end + if hasC then + e = readMeta(st, cb, cm, flags, version) + if e then + return nil, e + end + end + local mono = band(flags, MONO_FLAG + FALSE_STEREO) ~= 0 + local out = if band(flags, MONO_FLAG) ~= 0 then 1 else 2 + if n == 0 then + return out, nil + end + -- bitstreams + local o = m[0xA] + if not o or m[0xA + 256] == 0 or m[0xA + 256] % 2 == 1 then + return nil, "no audio bitstream" + end + openReader(st.R1, buf, o, m[0xA + 256]) + if hasC then + local co = cm[0xB] + if co and cm[0xB + 256] > 0 and cm[0xB + 256] % 2 == 0 then + openReader(st.R2, cb, co, cm[0xB + 256]) + st.wvc = true + end + end + -- the wvx stream: in the wv block (pure lossless) or the wvc block (hybrid lossless) + local xb, xm = buf, m + if hasC and (cm[0xC] or cm[0x2C]) then + xb, xm = cb, cm + end + local xid = if xm[0x2C] then 0x2C elseif xm[0xC] then 0xC else nil + if xid then + local xo, xl = xm[xid], xm[xid + 256] + if xl <= 4 or xl % 2 == 1 then + return nil, "bad wvx bitstream" + end + st.crcwvx = readu32(xb, xo) + openReader(st.R3, xb, xo + 4, xl - 4) + st.wvx = true + if xid == 0x2C then + if band(flags, FLOAT) ~= 0 then + st.fminzeros = bits(st.R3, 5) + st.fmaxones = bits(st.R3, 5) + else + st.imaxw = bits(st.R3, 5) + end + end + end + local hybrid = band(flags, HYBRID) ~= 0 + local d = if mono then D1 else D2 + local W = st.W + if #W < d + 2 * n then + W = table.create(d + 2 * n + 64, 0) + st.W = W + end + local crc = TWO32 - 1 + if not st.wvc then + if hybrid then + if mono then + for i = 0, n - 1 do + local v = getWord(st, 0, flags, true) + if not v then + return nil, "bad audio bitstream" + end + W[d + i] = v + end + else + for i = 0, n - 1 do + local l = getWord(st, 0, flags, false) + local r = l and getWord(st, 1, flags, false) + if not l or not r then + return nil, "bad audio bitstream" + end + W[d + 2 * i], W[d + 2 * i + 1] = l, r + end + end + elseif not wordsLossless(st, if mono then n else 2 * n, d) then + return nil, "bad audio bitstream" + end + if mono then + passesMono(st, n) + for k = d, d + n - 1 do + crc = (crc * 3 + W[k]) % TWO32 + end + else + passesStereo(st, n) + local last = d + 2 * n - 2 + if band(flags, JOINT) ~= 0 then + for k = d, last, 2 do + local l = W[k] + local r = W[k + 1] - l // 2 + l += r + W[k], W[k + 1] = l, r + crc = (crc * 9 + l * 3 + r) % TWO32 + end + else + for k = d, last, 2 do + crc = (crc * 9 + W[k] * 3 + W[k + 1]) % TWO32 + end + end + end + else + local ok = if mono then hybridMono(st, n, flags) else hybridStereo(st, n, flags) + if not ok then + return nil, "bad audio bitstream" + end + crc = st.crcv + end + if st.R1.p > st.R1.e or (st.wvc and st.R2.p > st.R2.e) then + return nil, "truncated audio bitstream" + end + if crc ~= crcWant then + return nil, "checksum: block CRC mismatch" + end + emit(st, flags, n, d, P, c0, C, hybrid and not st.wvc) + if st.wvx and (st.R3.p > st.R3.e or st.crcx ~= st.crcwvx) then + return nil, "checksum: wvx CRC mismatch" + end + return out, nil +end + +Block.bits = bits +Block.bit = bit + +return Block diff --git a/src/Formats/codecs/audio/WavPack/Tables.luau b/src/Formats/codecs/audio/WavPack/Tables.luau new file mode 100644 index 0000000..e06596d --- /dev/null +++ b/src/Formats/codecs/audio/WavPack/Tables.luau @@ -0,0 +1,65 @@ +--!strict +--!native +--!optimize 2 +-- codecs/audio/WavPack/Tables: the WavPack log2 / exp2 tables and the conversions built on them (wp_log2, wp_exp2s, +-- restore_weight). Ported from WavPack 5.9.0 entropy_utils.c (David Bryant, BSD 3-clause, licenses/wavpack-LICENSE.txt). +local band, rshift, lshift, countlz = bit32.band, bit32.rshift, bit32.lshift, bit32.countlz + +local Tables = {} + +-- LOG2[x + 1], EXP2[x + 1] for x = 0 .. 255 +local LOG2: { number } = { + 0, 1, 3, 4, 6, 7, 9, 10, 11, 13, 14, 16, 17, 18, 20, 21, 22, 24, 25, 26, 28, 29, 30, 32, 33, 34, 36, 37, 38, 40, 41, 42, + 44, 45, 46, 47, 49, 50, 51, 52, 54, 55, 56, 57, 59, 60, 61, 62, 63, 65, 66, 67, 68, 69, 71, 72, 73, 74, 75, 77, 78, 79, 80, 81, + 82, 84, 85, 86, 87, 88, 89, 90, 92, 93, 94, 95, 96, 97, 98, 99, 100, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 116, 117, + 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, + 150, 151, 152, 153, 154, 155, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 178, + 179, 180, 181, 182, 183, 184, 185, 185, 186, 187, 188, 189, 190, 191, 192, 192, 193, 194, 195, 196, 197, 198, 198, 199, 200, 201, 202, 203, 203, 204, 205, 206, + 207, 208, 208, 209, 210, 211, 212, 212, 213, 214, 215, 216, 216, 217, 218, 219, 220, 220, 221, 222, 223, 224, 224, 225, 226, 227, 228, 228, 229, 230, 231, 231, + 232, 233, 234, 234, 235, 236, 237, 238, 238, 239, 240, 241, 241, 242, 243, 244, 244, 245, 246, 247, 247, 248, 249, 249, 250, 251, 252, 252, 253, 254, 255, 255, +} +local EXP2: { number } = { + 0, 1, 1, 2, 3, 3, 4, 5, 6, 6, 7, 8, 8, 9, 10, 11, 11, 12, 13, 14, 14, 15, 16, 16, 17, 18, 19, 19, 20, 21, 22, 22, + 23, 24, 25, 25, 26, 27, 28, 29, 29, 30, 31, 32, 32, 33, 34, 35, 36, 36, 37, 38, 39, 40, 40, 41, 42, 43, 44, 44, 45, 46, 47, 48, + 48, 49, 50, 51, 52, 53, 53, 54, 55, 56, 57, 58, 58, 59, 60, 61, 62, 63, 64, 65, 65, 66, 67, 68, 69, 70, 71, 72, 72, 73, 74, 75, + 76, 77, 78, 79, 80, 81, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, + 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 135, 136, 137, 138, + 139, 140, 141, 142, 143, 144, 145, 146, 147, 149, 150, 151, 152, 153, 154, 155, 156, 157, 159, 160, 161, 162, 163, 164, 165, 166, 168, 169, 170, 171, 172, 173, + 175, 176, 177, 178, 179, 180, 182, 183, 184, 185, 186, 188, 189, 190, 191, 192, 194, 195, 196, 197, 198, 200, 201, 202, 203, 205, 206, 207, 208, 210, 211, 212, + 214, 215, 216, 217, 219, 220, 221, 222, 224, 225, 226, 228, 229, 230, 232, 233, 234, 236, 237, 238, 240, 241, 242, 244, 245, 246, 248, 249, 250, 252, 253, 255, +} + +-- exp2s(log) -> the int32 the signed log stands for (wp_exp2s) +function Tables.exp2s(lg: number): number + if lg < 0 then + local v = Tables.exp2s(-lg) + v = -(if v >= 2147483648 then v - 4294967296 else v) + return if v >= 2147483648 then v - 4294967296 else v + end + local value = bit32.bor(EXP2[band(lg, 255) + 1], 0x100) + local k = lg // 256 + local r = if k <= 9 then rshift(value, 9 - k) else lshift(value, band(k - 9, 31)) + return if r >= 2147483648 then r - 4294967296 else r +end + +-- log2(v) -> wp_log2 of the uint32 v +function Tables.log2(v: number): number + v = (v + rshift(v, 9)) % 4294967296 + if v < 256 then + local dbits = 32 - countlz(v) + return dbits * 256 + LOG2[band(lshift(v, 9 - dbits), 255) + 1] + end + local dbits = 32 - countlz(v) + return dbits * 256 + LOG2[band(rshift(v, dbits - 9), 255) + 1] +end + +-- restoreWeight(signed byte) -> the decorrelation weight (restore_weight) +function Tables.restoreWeight(w: number): number + local r = w * 8 + if r > 0 then + r += (r + 64) // 128 + end + return r +end + +return Tables diff --git a/src/Formats/codecs/audio/WavPack/init.luau b/src/Formats/codecs/audio/WavPack/init.luau new file mode 100644 index 0000000..e774a5f --- /dev/null +++ b/src/Formats/codecs/audio/WavPack/init.luau @@ -0,0 +1,238 @@ +--!strict +-- codecs/audio/WavPack: the WavPack 4 / 5 audio codec (the blocks of .wv files, and of WavPack in Matroska). A codec +-- (layer 3). Ported from WavPack 5.9.0 (David Bryant, BSD 3-clause, licenses/wavpack-LICENSE.txt); the hot code is in +-- codecs/audio/WavPack/Block. Lossless and hybrid (lossy, and lossless with the .wvc correction blocks), integer 8 - 32 +-- bit (with the extended int32 modes) and 32-bit float, mono / stereo / multichannel (one block per mono or stereo +-- stream, INITIAL .. FINAL), every decorrelation pass (terms 1 - 8, 17, 18, -1 .. -3), joint stereo, cross +-- decorrelation, noise shaping, block CRCs and block checksums. Not supported: DSD, pre-4.0 streams (version < 0x402). +-- +-- local h, err = WavPack.header(buf, at, limit) -- the 32-byte block header at `at` (nil, message if none) +-- local info, err = WavPack.info(buf, at, limit) -- stream facts from the first audio block (channels, rate, ...) +-- local dec = WavPack.decoder(info.channels) +-- local frames, err = dec:frame(buf, blocks, cbuf?, cblocks?) -- blocks = { offset, ... } of one frame (+ wvc) +-- -- dec.pcm: interleaved samples (integers in the container range, or float values), WAV channel order +-- +-- Never throws: bad data returns nil, Err. +local Err = require("@formats/core/Err") +local Block = require("@formats/codecs/audio/WavPack/Block") + +local WavPack = {} + +export type Header = { + size: number, -- the whole block (ckSize + 8) + version: number, + index: number, -- the first sample of the block (40 bits) + total: number, -- total samples of the file (-1: unknown) + samples: number, + flags: number, + crc: number, +} + +local RATES = { 6000, 8000, 9600, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000, 64000, 88200, 96000, 192000 } +WavPack.MONO, WavPack.HYBRID, WavPack.FLOAT, WavPack.INITIAL, WavPack.FINAL = 4, 8, 0x80, 0x800, 0x1000 +WavPack.DSD = 0x80000000 + +-- header(buf, at, limit?) -> Header | nil, message: a valid "wvpk" block header at byte `at` whose block ends by limit +function WavPack.header(buf: buffer, at: number, limit: number?): (Header?, string?) + local lim = math.min(limit or buffer.len(buf), buffer.len(buf)) + if at < 0 or at + 32 > lim then + return nil, "truncated block header" + end + if buffer.readstring(buf, at, 4) ~= "wvpk" then + return nil, "no block header" + end + local ck = buffer.readu32(buf, at + 4) + local version = buffer.readu16(buf, at + 8) + if ck % 2 == 1 or ck < 24 or ck > 0x1000000 then + return nil, "bad block size" + end + if version < 0x402 or version > 0x410 then + return nil, "unsupported: stream version " .. string.format("0x%x", version) + end + local total = buffer.readu32(buf, at + 12) + local tu8 = buffer.readu8(buf, at + 11) + local h: Header = { + size = ck + 8, + version = version, + index = buffer.readu32(buf, at + 16) + buffer.readu8(buf, at + 10) * 4294967296, + total = if total == 0xFFFFFFFF then -1 else total + tu8 * 4294967296 - tu8, + samples = buffer.readu32(buf, at + 20), + flags = buffer.readu32(buf, at + 24), + crc = buffer.readu32(buf, at + 28), + } + if at + h.size > lim then + return nil, "truncated block" + end + return h, nil +end + +export type Info = { + channels: number, + channelMask: number, + sampleRate: number, + bitsPerSample: number, -- the source depth (container bytes * 8 - shift) + bytesPerSample: number, -- the container: 1 .. 4 + float: boolean, + hybrid: boolean, + md5: string?, -- 32 hex digits when stored + version: number, +} + +-- info(buf, at, limit?) -> Info | nil, Err: the facts of the stream whose first audio block is at `at` +function WavPack.info(buf: buffer, at: number, limit: number?): (Info?, Err.Err?) + local h, herr = WavPack.header(buf, at, limit) + if not h then + return nil, Err.from(herr, at) + end + local m, merr = Block.meta(buf, at, h.size) + if not m then + return nil, Err.from(merr, at) + end + local flags = h.flags + if bit32.band(flags, WavPack.DSD) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "DSD audio") + end + local bytes = bit32.band(flags, 3) + 1 + local info: Info = { + channels = if bit32.band(flags, WavPack.MONO) ~= 0 then 1 else 2, + channelMask = 0, + sampleRate = 44100, + bitsPerSample = bytes * 8 - bit32.band(bit32.rshift(flags, 13), 31), + bytesPerSample = bytes, + float = bit32.band(flags, WavPack.FLOAT) ~= 0, + hybrid = bit32.band(flags, WavPack.HYBRID) ~= 0, + version = h.version, + } + info.channelMask = if info.channels == 1 then 4 else 3 + local sr = bit32.band(bit32.rshift(flags, 23), 15) + if sr < 15 then + info.sampleRate = RATES[sr + 1] + end + local o = m[0x27] -- ID_SAMPLE_RATE + if o and (m[0x27 + 256] == 3 or m[0x27 + 256] == 4) then + local rate = buffer.readu8(buf, o) + buffer.readu8(buf, o + 1) * 256 + buffer.readu8(buf, o + 2) * 65536 + if m[0x27 + 256] == 4 then + rate += bit32.band(buffer.readu8(buf, o + 3), 0x7F) * 16777216 + end + info.sampleRate = rate + end + o = m[0xD] -- ID_CHANNEL_INFO + if o then + local len = m[0xD + 256] + if len == 0 or len > 7 then + return nil, Err.new(Err.CORRUPT, "bad channel info", o) + end + local mask = 0 + if len >= 6 then + info.channels = buffer.readu8(buf, o) + bit32.band(buffer.readu8(buf, o + 2), 0xF) * 256 + 1 + mask = buffer.readu8(buf, o + 3) + buffer.readu8(buf, o + 4) * 256 + buffer.readu8(buf, o + 5) * 65536 + if len == 7 then + mask += buffer.readu8(buf, o + 6) * 16777216 + end + else + info.channels = buffer.readu8(buf, o) + for k = 1, len - 1 do + mask += buffer.readu8(buf, o + k) * 256 ^ (k - 1) + end + end + info.channelMask = mask + end + if info.channels < 1 then + return nil, Err.new(Err.CORRUPT, "no channels") + end + if info.sampleRate < 1 then + return nil, Err.new(Err.CORRUPT, "bad sample rate") + end + return info, nil +end + +-- md5(buf, at, limit?) -> 32 hex digits | nil: an ID_MD5_CHECKSUM in the block at `at` +function WavPack.md5(buf: buffer, at: number, limit: number?): string? + local h = WavPack.header(buf, at, limit) + if not h then + return nil + end + local m = Block.meta(buf, at, h.size) + if not m then + return nil + end + local o = m[0x26] + if not o or m[0x26 + 256] ~= 16 then + return nil + end + local hex = table.create(16, "") + for k = 0, 15 do + hex[k + 1] = string.format("%02x", buffer.readu8(buf, o + k)) + end + return table.concat(hex) +end + +-- ------------------------------------------------------------------------------------------------ decoder +export type Decoder = { + channels: number, + pcm: { number }, -- the last frame's samples, interleaved (integers in the container range, or floats) + frame: (self: Decoder, buf: buffer, blocks: { number }, cbuf: buffer?, cblocks: { number }?) -> (number?, Err.Err?), + state: Block.State, +} + +-- frame(buf, blocks, cbuf?, cblocks?) -> frames | nil, Err: decode one frame (the blocks of one sample range, one per +-- mono / stereo stream, in channel order) into dec.pcm; cblocks are the matching .wvc blocks (hybrid lossless) +local function frame(self: Decoder, buf: buffer, blocks: { number }, cbuf: buffer?, cblocks: { number }?): (number?, Err.Err?) + local C = self.channels + local n = -1 + local c0 = 0 + for i, at in blocks do + if c0 >= C then + break + end + local h, herr = WavPack.header(buf, at) + if not h then + return nil, Err.from(herr, at) + end + if n < 0 then + n = h.samples + if n * C > 16777216 then + return nil, Err.new(Err.LIMIT, "a frame of " .. n .. " samples x " .. C .. " channels", at) + end + if #self.pcm < n * C then + self.pcm = table.create(n * C, 0) + end + elseif h.samples ~= n then + return nil, Err.new(Err.CORRUPT, "blocks of a frame differ in length", at) + end + local cb, cp, cs = nil, nil, nil + if cbuf and cblocks and cblocks[i] then + local ch = WavPack.header(cbuf, cblocks[i]) + if ch and ch.samples == h.samples and ch.index == h.index then + cb, cp, cs = cbuf, cblocks[i], ch.size + end + end + local got, msg = Block.decode(self.state, buf, at, h.size, self.pcm, c0, C, cb, cp, cs) + if not got then + return nil, Err.from(msg, at) + end + c0 += got + end + if n < 0 then + return 0, nil + end + if c0 < C then + return nil, Err.new(Err.CORRUPT, "a frame is missing channels") + end + return n, nil +end + +-- decoder(channels) -> Decoder +function WavPack.decoder(channels: number): Decoder + return { + channels = channels, + pcm = table.create(4096 * channels, 0), + frame = frame, + state = Block.state(), + } +end + +WavPack.checksum = Block.checksum +WavPack.meta = Block.meta + +return WavPack diff --git a/src/Formats/containers/AudioWrap.luau b/src/Formats/containers/AudioWrap.luau index ac51aee..4a0f3da 100644 --- a/src/Formats/containers/AudioWrap.luau +++ b/src/Formats/containers/AudioWrap.luau @@ -8,7 +8,8 @@ -- flac -> "fLaC" + the metadata blocks (CodecPrivate / dfLa) + the frames; -- opus -> Ogg Opus (OpusHead from the config or made up, OpusTags, packets with granules from their TOC durations); -- vorbis -> Ogg Vorbis (the three headers from Matroska's Xiph-laced CodecPrivate or MP4's esds-less layout); --- aac -> ADTS (from the AudioSpecificConfig) for audio/aac. +-- aac -> ADTS (from the AudioSpecificConfig) for audio/aac; +-- ac3 -> the syncframes back to back (format "ac3"; E-AC-3 tracks stay UNSUPPORTED). -- -- local buf, format, err = AudioWrap.wrap(demuxer, track) -- then F.open(buf, { format = format }) local Err = require("@formats/core/Err") @@ -407,6 +408,9 @@ function AudioWrap.wrap(dmx: any, track: Types.Track): (buffer?, string?, Err.Er if codec == "mp3" or codec == "mp2" or codec == "mp1" then return concat(packets), "mp3", nil end + if codec == "ac3" then + return concat(packets), "ac3", nil + end if codec == "flac" then local c = track.config local prefix: buffer? = nil diff --git a/src/Formats/init.luau b/src/Formats/init.luau index 8aa73f7..4fca743 100644 --- a/src/Formats/init.luau +++ b/src/Formats/init.luau @@ -279,9 +279,12 @@ end -- the embedded parts) when called directly. -- They also see the injected plug-ins as opts.plugins (F.plugins: the B-rep kernel for cad/step) unless given their own. -- +-- Tracker modules inside other files (music/umx): opts.decodeModule(buf, format?) -> Module | nil, Err, the bytes loaded +-- as music (sniffed, or as the given format). +-- -- Audio tracks of video containers: opts.openAudio(demuxer, track) -> audio Decoder | nil, Err. The track's packets -- become a stream an audio format reads (containers/AudioWrap: PCM -> WAV, Opus / Vorbis -> Ogg, AAC -> ADTS, MP3 / --- FLAC as they are), opened through F.open with that format. +-- FLAC / AC-3 as they are), opened through F.open with that format. local function openAudio(demuxer: any, track: any): (any, Err.Err?) local buf, fmt, err = AudioWrap.wrap(demuxer, track) if not buf then @@ -302,7 +305,7 @@ local function openAudio(demuxer: any, track: any): (any, Err.Err?) end local function withHooks(o: Options): Options - if o.decodeImage ~= nil and o.encodeImage ~= nil and o.plugins ~= nil and o.openAudio ~= nil then + if o.decodeImage ~= nil and o.encodeImage ~= nil and o.plugins ~= nil and o.openAudio ~= nil and o.decodeModule ~= nil then return o end local c = table.clone(o) @@ -322,6 +325,12 @@ local function withHooks(o: Options): Options return F.save(img, nil, { format = format, category = "image" }) end end + if c.decodeModule == nil then + -- tracker modules inside other files (music/umx: the module of an Unreal package), as their own format + c.decodeModule = function(b: buffer, format: string?): (any, Err.Err?) + return F.load(b, { category = "music", format = format }) + end + end return c end @@ -482,8 +491,10 @@ local function videoToImage(v: any, o: Options): (any, Err.Err?) return img, nil end --- renderMusic(value, opts) -> the audio Decoder of a Module (codecs/audio/Tracker) or a Midi (music/midi render) | +-- renderMusic(value, opts) -> the audio Decoder of a Module (codecs/audio/Tracker, or the Module's own render method +-- for other engines) or a Midi (music/midi render) | -- nil, Err. opts are the render options: sampleRate, soundfont, gain, tail, interpolation, stereoSeparation, ... +local TRACKER_FAMILY = { mod = true, s3m = true, xm = true, it = true } local function renderMusic(value: any, o: Options): (any, Err.Err?) local ok, dec, err if value.kind == "midi" then @@ -492,6 +503,13 @@ local function renderMusic(value: any, o: Options): (any, Err.Err?) return nil, merr end ok, dec, err = pcall(m.render, value, o) + elseif TRACKER_FAMILY[value.engine or value.format] == nil and type(value.render) == "function" then + -- a Module with its own engine (AHX / HVL: codecs/audio/Hively): its render method (a failed render is an + -- empty Decoder carrying .err) + ok, dec = pcall(value.render, value, o) + if ok and type(dec) == "table" and dec.err then + return nil, dec.err + end else local Tracker: any = require("@formats/codecs/audio/Tracker") ok, dec, err = pcall(Tracker.render, value, o) diff --git a/src/Formats/music/669/init.luau b/src/Formats/music/669/init.luau new file mode 100644 index 0000000..051ed29 --- /dev/null +++ b/src/Formats/music/669/init.luau @@ -0,0 +1,209 @@ +--!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. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Tracker = require("@formats/codecs/audio/Tracker") +local Load = require("@formats/codecs/audio/Tracker/Load") + +-- ------------------------------------------------------------------------------------------------ contract +local Six69 = { + name = "669", + category = "music", + extensions = { "669" }, + mime = { "audio/x-669" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 8, 8 } }, +} + +export type DecodeOptions = { + maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ constants +local IT = Load.IT +-- the 669 effects (high nibble of the effect byte) by name +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) +local function validHeader(r: Bytes.Reader): boolean + if r:size() < 497 then + return false + end + local magic = r:peek(2) + if magic ~= "if" and magic ~= "JN" then + return false + end + local nsmp, npat, restart = r:peekU8(110), r:peekU8(111), r:peekU8(112) + if nsmp > 64 or restart >= 128 or npat > 128 then + return false + end + local bad = 0 + for i = 2, 109 do + local c = r:peekU8(i) + if c > 0 and c <= 31 then + bad += 1 + if bad > 40 then + return false + end + end + end + for i = 0, 127 do + local o, t, b = r:peekU8(113 + i), r:peekU8(241 + i), r:peekU8(369 + i) + if (o >= 128 and o < 0xFE) or (o < 128 and t == 0) or t > 15 or b >= 64 then + return false + end + end + return true +end + +function Six69.sniff(r: Bytes.Reader): number + return if validHeader(r) then 0.6 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Six69.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local budget = { left = opts and opts.maxBytes or 2 ^ 28 } + if not validHeader(r) then + return nil, Err.new(if r:size() < 497 then Err.TRUNCATED else Err.CORRUPT, "not a 669 module") + end + local extended = r:peek(2) == "JN" + r:skip(2) + local message = r:string(108) + local nsmp, npat, restart = r:u8(), r:u8(), r:u8() + local orders, tempos, breaks = {}, {}, {} + for i = 1, 128 do + orders[i] = r:u8() + end + for i = 1, 128 do + tempos[i] = r:u8() + end + for i = 1, 128 do + breaks[i] = r:u8() + end + if not r:need(nsmp * 25 + npat * 1536) then + return nil, r.err + end + local m = Tracker.newModule("669", 8, "s3m") + m.title = (string.gsub(string.sub(message, 1, 36), "[%z ]+$", "")) + m.meta.message = message + m.speed, m.tempo = 4, 78 + m.linear = false + m.instrumentMode = false + m.flags.periods, m.flags.hzSlide, m.flags.hzTonePorta = "hz", 20, 0.5 + m.flags.fastPortas, m.flags.autoTonePorta, m.flags.autoReset = true, true, true + for i = 1, 8 do + m.channelPan[i] = if i % 2 == 0 then 0xD0 else 0x30 + end + local lengths: { number } = {} + for i = 1, nsmp do + local s = Tracker.newSample(r:fixed(13)) + local len, ls, le = r:u32le(), r:u32le(), r:u32le() + if len >= 0x4000000 then + return nil, Err.new(Err.CORRUPT, "sample " .. i .. " too long") + end + s.c5speed = 8363 + if not (le > len and ls == 0) and le ~= 0 then + s.loopStart, s.loopEnd, s.loopType = ls, math.min(le, len), 1 + end + lengths[i] = len + m.samples[i] = s + end + for i = 1, 128 do + m.order[i] = orders[i] + end + while #m.order > 0 and m.order[#m.order] == 255 do + table.remove(m.order) + end + if orders[restart + 1] < npat then + m.restart = restart + end + -- patterns: 64 rows x 8 channels x 3 bytes (note / instrument, instrument / volume, effect / parameter) + local buf = r.buf + for p = 0, npat - 1 do + local pat = Tracker.newPattern(64, 8) + m.patterns[p + 1] = pat + local d = pat.data + local effect = table.create(8, 0xFF) -- the last effect per channel (balance slides repeat) + for row = 0, 63 do + for ch = 0, 7 do + local o = r.pos + (row * 8 + ch) * 3 + local ni, iv, ep = buffer.readu8(buf, o), buffer.readu8(buf, o + 1), buffer.readu8(buf, o + 2) + local q = (row * 8 + ch) * 5 + local hasNote = ni < 0xFE + if hasNote then + buffer.writeu8(d, q, ni // 4 + 37) + buffer.writeu8(d, q + 1, (ni % 4) * 16 + iv // 16 + 1) + effect[ch + 1] = 0xFF + end + if ni <= 0xFE then + buffer.writeu8(d, q + 2, ((iv % 16) * 64 + 8) // 15 + 1) + end + if ep ~= 0xFF then + effect[ch + 1] = ep + end + local e = effect[ch + 1] + if e ~= 0xFF then + local cmd, param = e // 16, e % 16 + local name = EFFECTS[cmd + 1] + if cmd == 4 then + param = param * 17 -- vibrato: speed = depth + elseif cmd == 6 then + param = if param == 0 then 0x4F elseif param == 1 then 0xF4 else -1 + elseif cmd == 7 and not (hasNote and extended) then + name = nil + end + if name ~= "panslide" then + effect[ch + 1] = 0xFF + end + if name and param >= 0 then + buffer.writeu8(d, q + 3, IT[name]) + buffer.writeu8(d, q + 4, param) + end + end + end + end + r:skip(1536) + if breaks[p + 1] < 63 then + Load.writeEffect(m, p, breaks[p + 1], IT["break"], 0, "next") + end + Load.writeEffect(m, p, 0, IT.speed, tempos[p + 1], "next") + end + -- sample data: unsigned 8-bit + local pos = r.pos + for i = 1, nsmp do + local s = m.samples[i] + local ok, err = Load.readSample(buf, pos, lengths[i], { bits = 8, signed = false, limit = r.limit }, s, budget) + if not ok then + return nil, err + end + pos += lengths[i] + end + m.meta.source = { format = "669", tracker = if extended then "UNIS 669" else "Composer 669" } + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function Six69.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Six69.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Six69 diff --git a/src/Formats/music/ahx/init.luau b/src/Formats/music/ahx/init.luau new file mode 100644 index 0000000..28aa9bc --- /dev/null +++ b/src/Formats/music/ahx/init.luau @@ -0,0 +1,53 @@ +--!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. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Hively = require("@formats/codecs/audio/Hively") + +-- ------------------------------------------------------------------------------------------------ contract +local Ahx = { + name = "ahx", + category = "music", + extensions = { "ahx", "thx" }, + mime = { "audio/x-ahx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Hively" }, + caps = { decode = true, encode = false, render = true, channels = { 4, 4 }, subsongs = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type RenderOptions = Hively.RenderOptions -- sampleRate, subsong, stereo (0..4), loop, maxDuration + +-- ------------------------------------------------------------------------------------------------ sniff +function Ahx.sniff(r: Bytes.Reader): number + local m = r:peek(4) + return if m and #m == 4 and string.sub(m, 1, 3) == "THX" and string.byte(m, 4) < 3 then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Ahx.decode(r: Bytes.Reader, _opts: any?): (Types.Module?, Err.Err?) + local tune, err = Hively.parse(r.buf, r.base, r.limit) + if not tune or tune.format ~= "ahx" then + return nil, err or Err.new(Err.CORRUPT, "not an AHX module") + end + return Hively.module(tune), nil +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 + return nil, err + end + return Hively.decoder((song :: any).tune, opts) +end + +return Ahx diff --git a/src/Formats/music/far/init.luau b/src/Formats/music/far/init.luau new file mode 100644 index 0000000..232b758 --- /dev/null +++ b/src/Formats/music/far/init.luau @@ -0,0 +1,232 @@ +--!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. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Tracker = require("@formats/codecs/audio/Tracker") +local Load = require("@formats/codecs/audio/Tracker/Load") + +-- ------------------------------------------------------------------------------------------------ contract +local Far = { + name = "far", + category = "music", + extensions = { "far" }, + mime = { "audio/x-far" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 16, 16 } }, +} + +export type DecodeOptions = { + maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ constants +local IT = Load.IT + +-- ------------------------------------------------------------------------------------------------ sniff +function Far.sniff(r: Bytes.Reader): number + if r:size() >= 98 and r:peek(4) == "FAR\xFE" and r:peek(3, 44) == "\r\n\x1A" and r:peekU8(47) + r:peekU8(48) * 256 >= 98 then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- a pattern cell's effect byte -> effect code, parameter, volume byte (S3M coding, 0 = none) (OpenMPT's table) +local function effect(e: number): (number, number, number) + local cmd, p = e // 16, e % 16 + if cmd == 1 then + return IT.portaup, 0xF0 + p, 0 + elseif cmd == 2 then + return IT.portadown, 0xF0 + p, 0 + elseif cmd == 3 then + return IT.toneporta, if p ~= 0 then 60 // p else 0, 0 + elseif cmd == 4 then + return IT.retrig, 6 // (1 + p) + 1, 0 + elseif cmd == 5 or cmd == 9 then + return IT.vibrato, p, 0 + elseif cmd == 6 then + return IT.vibrato, p * 8, 0 + elseif cmd == 7 then + return IT.volslide, p * 8, 0 + elseif cmd == 8 then + return IT.volslide, p, 0 + elseif cmd == 0xA then + return 0, 0, p * 4 + 4 + 1 -- volume portamento: a set volume + elseif cmd == 0xB then + return IT.s3mex, 0x80 + p, 0 + elseif cmd == 0xF then + return IT.speed, p, 0 + end + return 0, 0, 0 +end + +function Far.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local budget = { left = opts and opts.maxBytes or 2 ^ 28 } + if Far.sniff(r) == 0 then + return nil, Err.new(if r:size() < 98 then Err.TRUNCATED else Err.CORRUPT, "not a Farandole module") + end + r:skip(4) + local title = r:fixed(40) + r:skip(3) + local headerLength, version = r:u16le(), r:u8() + local onOff, pans = {}, {} + for i = 1, 16 do + onOff[i] = r:u8() + end + r:skip(9) + local speed = r:u8() + for i = 1, 16 do + pans[i] = r:u8() + end + r:skip(4) + local msgLen = r:u16le() + local message = r:string(msgLen) + local orders = {} + for i = 1, 256 do + orders[i] = r:u8() + end + local _npat, nord, restart = r:u8(), r:u8(), r:u8() + local sizes = {} + for i = 1, 256 do + sizes[i] = r:u16le() + end + if r.err then + return nil, r.err + end + local m = Tracker.newModule("far", 16, "s3m") + m.title = title + m.meta.message = message + m.speed, m.tempo = if speed > 0 then speed else 4, 80 + m.mixVolume = 32 -- OpenMPT's pre-amp for FAR + m.linear = false + m.instrumentMode = false + m.flags.periods, m.flags.hzSlide = "hz", 36318 / 1024 + m.flags.autoTonePorta = true + for i = 1, 16 do + m.channelMute[i] = onOff[i] == 0 + m.channelPan[i] = (pans[i] % 16) * 16 + 8 + end + for i = 1, nord do + m.order[i] = orders[i] + end + while #m.order > 0 and m.order[#m.order] == 255 do + table.remove(m.order) + end + m.restart = restart + -- patterns: (size - 2) / 64 rows of 16 channels x (note, instrument, volume, effect), after a break row byte + if not r:seek(headerLength) then + return nil, r.err + end + local last = -1 + for p = 0, 255 do + if sizes[p + 1] > 0 then + last = p + end + end + for p = 0, last do + local size = sizes[p + 1] + local rows = math.clamp((size - 2) // 64, 1, 1024) + local pat = Tracker.newPattern(if size > 0 then rows else 64, 16) + m.patterns[p + 1] = pat + if size > 0 then + local pr = r:slice(size) + if r.err then + return nil, r.err + end + local br = pr:u8() + pr:skip(1) + local d = pat.data + for row = 0, rows - 1 do + for ch = 0, 15 do + local note, ins, vol, e = pr:u8(), pr:u8(), pr:u8(), pr:u8() + if pr.err then + break + end + local q = (row * 16 + ch) * 5 + if note > 0 and note <= 72 then + buffer.writeu8(d, q, note + 36) + buffer.writeu8(d, q + 1, ins + 1) + end + if vol > 0 and vol <= 16 then + buffer.writeu8(d, q + 2, (vol - 1) * 64 // 15 + 1) + end + local fx, param, setVol = effect(e) + if setVol > 0 then + buffer.writeu8(d, q + 2, setVol) + end + buffer.writeu8(d, q + 3, fx) + buffer.writeu8(d, q + 4, param) + end + end + if br > 0 and br < rows - 2 then + Load.writeEffect(m, p, br + 1, IT["break"], 0, "next") + end + end + end + -- samples: a 64-bit map of the stored ones, each a 48-byte header + signed 8 / 16-bit data + local map = {} + for i = 1, 8 do + map[i] = r:u8() + end + r.err = nil + for i = 0, 63 do + if bit32.band(map[i // 8 + 1] or 0, bit32.lshift(1, i % 8)) ~= 0 then + local h = r:slice(48) + if r.err then + break + end + local s = Tracker.newSample(h:fixed(32)) + local len = h:u32le() + h:skip(1) + local vol = h:u8() + local ls, le = h:u32le(), h:u32le() + local typ, loop = h:u8(), h:u8() + local bits = if typ % 2 == 1 then 16 else 8 + local frames = if bits == 16 then len // 2 else len + if bits == 16 then + ls, le = ls // 2, le // 2 + end + s.c5speed = 8363 * 2 + s.volume = math.min(vol * 4, 64) + local ok, err = Load.readSample(r.buf, r.pos, frames, { bits = bits, signed = true, limit = r.limit }, s, budget) + if not ok then + return nil, err + end + r:skip(math.min(len, r:remaining())) + if bit32.band(loop, 8) ~= 0 and le > ls then + s.loopStart, s.loopEnd, s.loopType = ls, math.min(le, s.length), 1 + end + for k = #m.samples + 1, i do + m.samples[k] = Tracker.newSample() + end + m.samples[i + 1] = s + end + end + m.meta.source = { format = "far", version = version } + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function Far.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Far.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Far diff --git a/src/Formats/music/hmp/init.luau b/src/Formats/music/hmp/init.luau new file mode 100644 index 0000000..b93ddc8 --- /dev/null +++ b/src/Formats/music/hmp/init.luau @@ -0,0 +1,273 @@ +--!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). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Render = require("@formats/codecs/audio/MidiRender") + +-- ------------------------------------------------------------------------------------------------ contract +local Hmp = { + name = "hmp", + category = "music", + extensions = { "hmp", "hmi" }, + mime = { "audio/x-hmp" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/MidiRender" }, + caps = { decode = true, encode = false, render = true, hmi = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + maxEvents: number?, -- default 2^24 +} + +-- ------------------------------------------------------------------------------------------------ sniff +local HMI_MAGIC = "HMI-MIDISONG061595" + +function Hmp.sniff(r: Bytes.Reader): number + return if r:peek(8) == "HMIMIDIP" or r:peek(18) == HMI_MAGIC then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +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 +local function delta(b: buffer, p: number, e: number, hmp: boolean): (number?, number) + local v, shift = 0, 1 + for _ = 1, 5 do + if p >= e then + return nil, p + end + local c = readu8(b, p) + p += 1 + if hmp then + v += (c % 128) * shift + shift *= 128 + if c >= 128 then + return v, p + end + else + v = v * 128 + c % 128 + if c < 128 then + return v, p + end + end + end + return nil, p +end + +local function bytes(b: buffer, p: number, n: number): { number } + local t: { number } = table.create(n) :: { number } + for i = 1, n do + t[i] = readu8(b, p + i - 1) + end + return t +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) + end + tick += d + p = q + if p >= e then + return nil, "truncated event" + end + local st = readu8(b, p) + if st == 0xFE and not hmp then + -- HMI-only events: FE 10 (with a length at +4), FE 15, others 4 bytes + local n = 4 + if p + 1 < e and readu8(b, p + 1) == 0x10 then + n = if p + 4 < e then readu8(b, p + 4) + 9 else e - p + 1 + elseif p + 1 < e and readu8(b, p + 1) == 0x15 then + n = 8 + end + if p + n > e then + return nil, "truncated FE event" + end + p += n + elseif st == 0xFF then + local kind = if p + 1 < e then readu8(b, p + 1) else -1 + local n, r = delta(b, p + 2, e, false) + if kind < 0 or not n or r + n > e then + return nil, "truncated meta event" + end + if kind == 0x2F then + break + end + table.insert(list, { tick = tick, type = "meta", meta = kind, data = bytes(b, r, n) }) + p = r + n + elseif st == 0xF0 or st == 0xF7 then + local n, r = delta(b, p + 1, e, false) + if not n or r + n > e then + return nil, "truncated sysex" + end + table.insert(list, { tick = tick, type = if st == 0xF0 then "sysex" else "escape", data = bytes(b, r, n) }) + p = r + n + running = 0 + else + if st >= 0x80 then + if st >= 0xF0 then + return nil, string.format("unexpected status byte 0x%02X", st) + end + running = st + p += 1 + elseif running == 0 then + return nil, "running status without a status byte" + end + local hi, ch = running // 16, running % 16 + local n = DATA[hi] + if p + n > e then + return nil, "truncated event" + end + local data = bytes(b, p, n) + p += n + if hmp and hi == 11 and (data[1] == 110 or data[1] == 111) and data[2] > 127 then + ctx.loops += 1 + else + for i = 1, n do + data[i] %= 128 + end + table.insert(list, { tick = tick, type = TYPES[hi], channel = ch, data = data }) + end + if hi == 9 and not hmp then + local dur, r = delta(b, p, e, false) + if not dur then + return nil, "truncated note duration" + end + p = r + table.insert(offs, { tick = tick + dur, onTick = tick, ev = { tick = tick + dur, type = "noteOff", channel = ch, data = { data[1], 64 } } }) + end + end + ctx.budget -= 1 + if ctx.budget < 0 then + return nil, "limit: too many events" + end + end + -- (notes still sounding at the end of an HMI track keep their full duration, as wildmidi plays them) + local out = Render.merge(list, offs) + table.insert(out, { tick = math.max(tick, if #out > 0 then out[#out].tick else 0), type = "meta", meta = 0x2F, data = {} }) + 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) + local p = base + (if new then 0x388 else 0x308) + if n == 0 or n > 256 then + return nil, string.format("bad track count %d", n), nil + end + local ranges = {} + for _ = 1, n do + if p + 12 > limit then + return nil, "truncated chunk header", "truncated" + end + local len = readu32(b, p + 4) + if len < 12 or p + len > limit then + return nil, "truncated chunk", "truncated" + end + table.insert(ranges, { p + 12, p + len }) + p += len + end + return ranges, nil, nil +end + +local function hmiTracks(b: buffer, base: number, limit: number): ({ { number } }?, string?, string?) + local n = readu8(b, base + 228) + if n == 0 then + return nil, "no tracks", nil + end + if base + 370 + n * 4 > limit then + return nil, "truncated track table", "truncated" + end + local ranges, heads = {}, {} + for i = 0, n - 1 do + local at = base + readu32(b, base + 370 + i * 4) + if at < base or at + 0x5B > limit or buffer.readstring(b, at, 13) ~= "HMI-MIDITRACK" then + return nil, string.format("bad track %d header", i), nil + end + local start = at + readu32(b, at + 0x57) + if start >= limit then + return nil, "truncated track", "truncated" + end + table.insert(ranges, { start, limit }) + table.insert(heads, at) + end + -- a track ends where the next track header starts (or at the end of the file) + for _, rg in ranges do + for _, h in heads do + if h >= rg[1] and h < rg[2] then + rg[2] = h + end + end + end + return ranges, nil, nil +end + +function Hmp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Midi?, Err.Err?) + local b, base, limit = r.buf, r.base, r.limit + local hmi = r:peek(18) == HMI_MAGIC + if not hmi and r:peek(8) ~= "HMIMIDIP" then + return nil, Err.new(Err.CORRUPT, "not an HMP / HMI file") + end + if limit - base < (if hmi then 371 else 0x40) then + return nil, Err.new(Err.TRUNCATED, "truncated header") + end + local rate = if hmi then readu8(b, base + 212) else readu32(b, base + 0x38) + if rate == 0 or rate > 100000 then + return nil, Err.new(Err.CORRUPT, "bad tick rate " .. rate) + end + local ranges, msg, kind = (if hmi then hmiTracks else hmpTracks)(b, base, limit) + if not ranges then + return nil, Err.from(msg :: string, nil, kind) + end + local ctx: Ctx = { loops = 0, budget = (opts and opts.maxEvents) or 2 ^ 24 } + local midi = Types.Midi.new(60) + for i, rg in ranges do + local evs, err = track(b, rg[1], rg[2], not hmi, ctx) + if not evs then + return nil, Err.from(err :: string, rg[1]) + end + if i == 1 then + local us = math.min(60000000 // rate, 0xFFFFFF) + table.insert(evs, 1, { tick = 0, type = "meta", meta = 0x51, data = { us // 65536, (us // 256) % 256, us % 256 } }) + end + midi.tracks[i] = { events = evs } + end + local version = if hmi then "hmi" elseif buffer.readstring(b, base + 8, 6) == "013195" then "013195" else "hmp" + Render.attach(midi, { format = if hmi then "hmi" else "hmp", version = version, rate = rate, loops = ctx.loops }) + return midi, nil +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 + return nil, err + end + return Render.decoder(midi, opts) +end + +return Hmp diff --git a/src/Formats/music/hvl/init.luau b/src/Formats/music/hvl/init.luau new file mode 100644 index 0000000..c731c6c --- /dev/null +++ b/src/Formats/music/hvl/init.luau @@ -0,0 +1,53 @@ +--!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. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Hively = require("@formats/codecs/audio/Hively") + +-- ------------------------------------------------------------------------------------------------ contract +local Hvl = { + name = "hvl", + category = "music", + extensions = { "hvl" }, + mime = { "audio/x-hvl" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Hively" }, + caps = { decode = true, encode = false, render = true, channels = { 4, 16 }, subsongs = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type RenderOptions = Hively.RenderOptions -- sampleRate, subsong, loop, maxDuration (stereo: the file's) + +-- ------------------------------------------------------------------------------------------------ sniff +function Hvl.sniff(r: Bytes.Reader): number + local m = r:peek(4) + return if m and #m == 4 and string.sub(m, 1, 3) == "HVL" and string.byte(m, 4) <= 1 then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Hvl.decode(r: Bytes.Reader, _opts: any?): (Types.Module?, Err.Err?) + local tune, err = Hively.parse(r.buf, r.base, r.limit) + if not tune or tune.format ~= "hvl" then + return nil, err or Err.new(Err.CORRUPT, "not an HVL module") + end + return Hively.module(tune), nil +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 + return nil, err + end + return Hively.decoder((song :: any).tune, opts) +end + +return Hvl diff --git a/src/Formats/music/med/init.luau b/src/Formats/music/med/init.luau new file mode 100644 index 0000000..4cc328e --- /dev/null +++ b/src/Formats/music/med/init.luau @@ -0,0 +1,661 @@ +--!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. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Tracker = require("@formats/codecs/audio/Tracker") +local Load = require("@formats/codecs/audio/Tracker/Load") + +-- ------------------------------------------------------------------------------------------------ contract +local Med = { + name = "med", + category = "music", + extensions = { "med", "mmd0", "mmd1", "mmd2", "mmd3", "omed" }, + mime = { "audio/x-med" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 64 } }, +} + +export type DecodeOptions = { + maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ constants +-- IFF multi-octave samples: the sample (0 = the lowest octave stored first... as OpenMPT orders them) and the +-- transpose used per octave of the keyboard, by the number of octaves stored (2..7) +local OCT_SAMPLE = { + { 1, 1, 0, 0, 0, 0, 0, 0 }, + { 2, 2, 1, 1, 0, 0, 0, 0 }, + { 3, 3, 2, 2, 1, 0, 0, 0 }, + { 4, 3, 2, 1, 1, 0, 0, 0 }, + { 5, 4, 3, 2, 1, 0, 0, 0 }, + { 6, 5, 4, 3, 2, 1, 0, 0 }, +} +local OCT_TRANSPOSE = { + { 0, 0, -12, -12, -24, -36, -48, -60 }, + { 0, 0, -12, -12, -24, -36, -48, -60 }, + { 0, 0, -12, -12, -24, -36, -48, -60 }, + { 12, 0, -12, -24, -24, -36, -48, -60 }, + { 12, 0, -12, -24, -36, -48, -48, -60 }, + { 12, 0, -12, -24, -36, -48, -60, -72 }, +} +local SAMPLES_PER_TYPE = { [0] = 1, 5, 3, 2, 4, 6, 7 } +local TEMPO_8CH = { 179, 164, 152, 141, 131, 123, 116, 110, 104, 99 } + +-- ------------------------------------------------------------------------------------------------ sniff +local function validHeader(r: Bytes.Reader): boolean + if r:size() < 52 or r:peek(3) ~= "MMD" then + return false + end + local v = r:peekU8(3) + if v < 0x30 or v > 0x33 then + return false + end + local h = r:sub(8, 44) + local songOff = h:u32be() + h:skip(4) + local blockOff = h:u32be() + h:skip(4) + local smpOff = h:u32be() + return songOff >= 52 and songOff + 63 * 8 + 284 <= r:size() and blockOff >= 52 and (smpOff == 0 or smpOff >= 52) +end + +function Med.sniff(r: Bytes.Reader): number + return if validHeader(r) then 1 else 0 +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) +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 + end + if ctx.is8Ch and tempo > 0 then + return TEMPO_8CH[math.min(tempo, 10)] + elseif not ctx.softMix and tempo > 0 and tempo <= 10 then + return 6 * 1773447 / 14500 / tempo -- SoundTracker-compatible tempo + elseif ctx.softMix and tempo < 8 then + return 157.86 + end + return tempo / 0.264 +end + +-- a MED command -> MOD / XM effect, param, and a 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 + return if p > 0 then cmd else 0, p, false + elseif cmd == 4 then + return 4, p - p % 16 + math.min((p % 16) * 2, 15), false -- twice as deep as ProTracker's + elseif cmd == 5 then + return if p > 0 then 5 else 3, p, false + elseif cmd == 6 then + return if p > 0 then 6 else 4, p, false + elseif cmd == 8 or cmd == 0xE or cmd == 0x10 or cmd == 0x1C or cmd == 0x20 or cmd == 0x29 then + return 0, 0, false -- hold / decay (instrument data), synth jump, MIDI, reverse, relative offset + elseif cmd == 9 then + return if p > 0 and p <= 0x20 then 0xF else 0, math.min(p, 0x1F), false + elseif cmd == 0xC then + if not ctx.volHex and p < 0x99 then + return 0xC, (p // 16) * 10 + p % 16, false + elseif ctx.volHex and not ctx.vol7bit then + return 0xC, math.min(p % 128, 64), false + elseif ctx.volHex then + return 0xC, (p % 128 + 1) // 2, false + end + return 0, 0, false + elseif cmd == 0xD then + return if p > 0 then 0xA else 0, p, false + elseif cmd == 0xF then + if p == 0 then + return 0xD, 0, false + elseif p <= 0xF0 then + local bpm = if p < 3 then 0x70 else math.floor(tempoToBpm(p, ctx) + 0.5) + if bpm > 255 then + local ext = Tracker.EXT.TEMPO_256 + math.min(bpm // 256, 3) - 1 -- tempos past 255 (EXT 0x47..0x49) + return ext, math.min(bpm - (ext - Tracker.EXT.TEMPO_256 + 1) * 256, 255), false + end + return 0xF, math.max(bpm, 0x20), false + elseif p == 0xF1 then + return 0xE, 0x93, false + elseif p == 0xF2 then + return 0xE, 0xD3, false + elseif p == 0xF3 then + return 0xE, 0x92, false + elseif p == 0xFF then + return 0, 0, true + end + return 0, 0, false + elseif cmd == 0x11 then + return 0xE, 0x10 + lo, false + elseif cmd == 0x12 then + return 0xE, 0x20 + lo, false + elseif cmd == 0x14 then + return 4, p, false -- ProTracker depth, faster + elseif cmd == 0x15 then + return 0xE, 0x50 + p % 16, false + elseif cmd == 0x16 then + return 0xE, 0x60 + lo, false + elseif cmd == 0x18 then + return 0xE, 0xC0 + lo, false + elseif cmd == 0x19 then + return 9, p, false + elseif cmd == 0x1A then + return 0xE, 0xA0 + lo, false + elseif cmd == 0x1B then + return 0xE, 0xB0 + lo, false + elseif cmd == 0x1D then + return 0xD, Load.bcd(p), false -- pattern break, the row in hex + elseif cmd == 0x1E then + return 0xE, 0xE0 + lo, false + elseif cmd == 0x1F then + if p >= 16 then + return 0xE, 0xD0 + p // 16, false + elseif p > 0 then + return 0xE, 0x90 + p, false + end + return 0, 0, false + elseif cmd == 0x2E then + if p <= 0x10 or p >= 0xF0 then + return 8, math.clamp((bit32.bxor(p, 0x80) - 0x70) * 8, 0, 255), false + end + return 0, 0, false + elseif cmd < 0x10 and (cmd > 0 or p > 0) then + return cmd, p, false -- the remaining ProTracker effects as they are (0, 3, 7, 8, A, B) + end + return 0, 0, false +end + +-- a MED note (with the play transpose) -> our note, or 0 (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 + n -= 108 + elseif n > 120 then + n -= (n - 109) - (n - 109) % 12 + end + 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 + if version < 1 then + ntracks, nrows, info = br:u8(), br:u8() + 1, 0 + else + ntracks, nrows, info = br:u16be(), br:u16be() + 1, br:u32be() + end + if br.err or nrows > 1024 then + return nil, false + end + local cmdExt: Bytes.Reader? = nil + if version >= 1 and info > 0 then + local ir = r:sub(info, 36) + ir:skip(16) + local ext = ir:u32be() + if not ir.err and ext > 0 then + local p = r:sub(ext, 4):u32be() + if p > 0 then + cmdExt = r:sub(p) + end + end + end + local lctx = table.clone(ctx) + lctx.vol7bit = cmdExt ~= nil + local pat = Tracker.newPattern(nrows, nch) + local d = pat.data + local high = false + local used = math.min(ntracks, nch) + for row = 0, nrows - 1 do + for ch = 0, ntracks - 1 do + local note, ins, cmd, param, cut = 0, 0, 0, 0, false + if version < 1 then + local ni, ic, p = br:u8(), br:u8(), br:u8() + if ni % 64 > 0 then + note = ni % 64 + lctx.transpose + end + ins = ic // 16 + bit32.rshift(bit32.band(ni, 0x80), 3) + bit32.rshift(bit32.band(ni, 0x40), 1) + cmd, param = ic % 16, p + else + local nv, iv, c, p = br:u8(), br:u8(), br:u8(), br:u8() + if nv % 128 > 0 then + note = nv % 128 + lctx.transpose + elseif nv == 0x80 then + cut = true + end + ins, cmd, param = iv % 64, c, p + end + if br.err then + return pat, high + end + if ch < used then + local q = (row * nch + ch) * 5 + if note >= 61 + 24 - 12 then + high = true + end + local n = wrapNote(note, lctx.vol7bit) + if n > 0 then + buffer.writeu8(d, q, n) + elseif cut then + buffer.writeu8(d, q, 254) + end + buffer.writeu8(d, q + 1, ins) + if cmd ~= 0 or param ~= 0 then + local fx, fp, noteCut = effect(cmd, param, lctx) + if noteCut and n == 0 then + buffer.writeu8(d, q, 254) + end + buffer.writeu8(d, q + 3, fx) + buffer.writeu8(d, q + 4, fp) + end + end + end + end + return pat, high +end + +function Med.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local budget = { left = opts and opts.maxBytes or 2 ^ 28 } + if not validHeader(r) then + return nil, Err.new(if r:size() < 52 then Err.TRUNCATED else Err.CORRUPT, "not a MED module") + end + local version = r:peekU8(3) - 0x30 + local h = r:sub(8, 44) + local songOff = h:u32be() + h:skip(4) + local blockOff = h:u32be() + h:skip(4) + local smpOff = h:u32be() + h:skip(4) + local expOff = h:u32be() + -- the song: 63 sample headers, then the song header + local sh = r:sub(songOff, 63 * 8) + local song = r:sub(songOff + 63 * 8, 284) + local numBlocks, songLength = song:u16be(), song:u16be() + local seq = song:sub(4, 256) + song:skip(256) + local defTempo, playTranspose, flags, flags2, tempo2 = song:u16be(), song:i8(), song:u8(), song:u8(), song:u8() + local trackVol = {} + for i = 1, 16 do + trackVol[i] = song:u8() + end + local masterVol, numSamples = song:u8(), song:u8() + if song.err or numSamples > 63 or numBlocks > 0x7FFF then + return nil, Err.new(Err.CORRUPT, "bad song header") + end + 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 + local p = r:sub(blockOff + b * 4, 4):u32be() + blockPtr[b + 1] = p + if p > 0 and p < r:size() then + local w = if version < 1 then r:peekU8(p) else r:peekU8(p) * 256 + r:peekU8(p + 1) + nch = math.max(nch, w) + end + end + if nch > 64 then + return nil, Err.new(Err.UNSUPPORTED, nch .. " tracks") + end + local m = Tracker.newModule("med", nch, "xm") + m.linear = false + m.instrumentMode = false + m.flags.periods, m.flags.envRowHold = "amiga", true + local stSlides = bit32.band(flags, 0x20) ~= 0 + m.flags.fastSlides, m.flags.fastPortas = not stSlides, not stSlides + local hardwareMix = version < 2 or bit32.band(flags2, 0x80) == 0 + m.flags.amigaLimits = hardwareMix + -- the expansion data: instrument extras and names, the song name + local ext = { instrExt = 0, instrExtN = 0, instrExtSize = 0, infoOff = 0, infoN = 0, infoSize = 0, nameOff = 0, nameLen = 0, annoOff = 0, annoLen = 0 } + if expOff > 0 then + local e = r:sub(expOff, 80) + e:skip(4) + ext.instrExt, ext.instrExtN, ext.instrExtSize = e:u32be(), e:u16be(), e:u16be() + ext.annoOff, ext.annoLen = e:u32be(), e:u32be() + ext.infoOff, ext.infoN, ext.infoSize = e:u32be(), e:u16be(), e:u16be() + e:skip(16) + ext.nameOff, ext.nameLen = e:u32be(), e:u32be() + if e.err then + ext.instrExt, ext.infoOff, ext.nameOff, ext.annoOff = 0, 0, 0, 0 + end + end + 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 = {} + for ins = 1, numSamples do + local smpHead = sh:sub((ins - 1) * 8, 8) + local loopStart, loopLen = smpHead:u16be() * 2, smpHead:u16be() * 2 + local midiCh, _midiPreset, volume, transpose = smpHead:u8(), smpHead:u8(), smpHead:u8(), smpHead:i8() + local x = { hold = 0, decay = 0, finetune = 0, pitch = 0, flags = 0, loopStart = 0, loopLen = 0, volume = 0 } + local xsize = 0 + if ext.instrExt > 0 and ins <= ext.instrExtN then + xsize = ext.instrExtSize + local xr = r:sub(ext.instrExt + (ins - 1) * xsize, xsize) + x.hold, x.decay = xr:u8(), xr:u8() + xr:skip(1) + x.finetune = xr:i8() + x.pitch, x.flags = xr:u8(), xr:u8() + xr:skip(4) + x.loopStart, x.loopLen = xr:u32be(), xr:u32be() + x.volume = xr:u8() + end + local name = "" + if ext.infoOff > 0 and ins <= ext.infoN then + name = r:sub(ext.infoOff + (ins - 1) * ext.infoSize, math.min(ext.infoSize, 40)):fixed(math.min(ext.infoSize, 40)) + end + local instr = Tracker.newInstrument(name) + instruments[ins] = instr + local iptr = if smpOff > 0 then r:sub(smpOff + (ins - 1) * 4, 4):u32be() else 0 + local length, typ = 0, 0 + if iptr > 0 then + local ih = r:sub(iptr, 6) + length, typ = ih:u32be(), ih:i16be() + if ih.err then + length, typ = 0, 0 + end + end + local isSynth = typ < 0 + local masked = bit32.band(typ % 65536, 0x0F) + local count = if not isSynth then (SAMPLES_PER_TYPE[masked] or 1) else 1 + if isSynth then + table.insert(unsupported, "synth / hybrid instrument " .. ins) + needInstruments = needInstruments or typ == -1 or typ == -2 + end + if midiCh > 0 and midiCh <= 16 then + needInstruments = true + table.insert(unsupported, "MIDI instrument " .. ins) + end + local first = #samples + 1 + -- keymap: one sample per note, multi-octave samples spread over the octaves + for n = 1, 120 do + instr.sampleMap[n] = first + end + if count > 1 then + needInstruments = true + for n = 1, 120 do + local note = n + 11 + transpose -- OpenMPT's keyboard index + if note < 0 then + note = -note % 12 + end + local oct = math.clamp(note // 12 - 4, 0, 7) + instr.sampleMap[n] = first + OCT_SAMPLE[count - 1][oct + 1] + instr.noteMap[n] = math.clamp(1 + note + OCT_TRANSPOSE[count - 1][oct + 1] - 12, 1, 120) + end + transpose = 0 + elseif masked == 7 then + needInstruments = true -- two extra-low octaves + for n = 1, 120 do + instr.noteMap[n] = math.clamp(n - 24, 1, 120) + end + end + if midiCh == 0 then + -- notes past the mixer's range fold down (by octaves) + local top = 61 + (if hardwareMix then 24 else 36) + for n = 1, 120 do + local real = instr.noteMap[n] + 12 + transpose + if real >= top then + instr.noteMap[n] = math.max(1, instr.noteMap[n] - ((real - top + 12) - (real - top + 12) % 12)) + end + end + end + -- sample data + local list = {} + for i = 0, count - 1 do + local s = Tracker.newSample(name) + s.volume = math.min(volume, 64) + s.relativeNote = transpose + list[i + 1] = s + samples[first + i] = s + end + local hasLoop = loopLen > 2 + if not isSynth and iptr > 0 and length > 0 then + local bits = if bit32.band(typ, 0x10) ~= 0 then 16 else 8 + local stereo = bit32.band(typ, 0x20) ~= 0 + local nchs = if stereo then 2 else 1 + local bytes = length * nchs + local frames = length // (bits // 8) + if count > 1 then + frames //= (2 ^ count - 1) + end + local pos = r.base + iptr + 6 + local ls, le = loopStart, loopStart + loopLen + for i = 1, count do + local s = list[i] + local spec = { bits = bits, signed = true, bigEndian = true, channels = nchs, planar = stereo, delta = bit32.band(typ, 0x40) ~= 0, limit = math.min(r.limit, r.base + iptr + 6 + bytes) } + local ok, err = Load.readSample(r.buf, pos, frames, spec, s, budget) + if not ok then + return nil, err + end + pos += frames * nchs * bits // 8 + if hasLoop then + s.loopStart, s.loopEnd, s.loopType = ls, math.min(le, s.length), 1 + end + 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() + env.enabled = true + local fall = x.hold + (if x.decay > 0 then 64 // x.decay else 0) + if x.hold == 1 then + env.ticks, env.values = { 0, fall }, { 64, 0 } + else + env.ticks, env.values = { 0, x.hold - 1, fall }, { 64, 64, 0 } + end + instr.volEnv = env + instr.fadeout = if x.decay > 0 then math.min(x.decay * 512, 65535) else 32767 + needInstruments = true + end + if xsize > 4 and x.pitch ~= 0 then + instr.noteMap[24 - 12 + 1] = math.clamp(x.pitch + 1 + 23 - 12, 1, 120) + needInstruments = true + end + if xsize > 18 then + instr.globalVolume = (x.volume + 1) // 2 * 2 + end + local ls, le = x.loopStart, x.loopStart + x.loopLen + for _, s in list do + s.finetune = math.clamp(x.finetune * 16, -128, 127) + if not isSynth and xsize > 14 then + s.loopStart, s.loopEnd = ls, math.min(le, s.length) + ls, le = ls * 2, le * 2 + end + if xsize > 5 then + if not isSynth then + s.loopType = if bit32.band(x.flags, 1) == 0 then 0 elseif bit32.band(x.flags, 8) ~= 0 then 2 else 1 + end + if bit32.band(x.flags, 4) ~= 0 then + s.globalVolume = 0 + end + end + end + end + end + -- the play order: MMD0 / MMD1 a sequence of blocks; MMD2 / MMD3 sections of play sequences (stop / jump commands) + local jumps: { [number]: number } = {} + local preamp = 32 + if version < 2 then + if songLength > 256 then + return nil, Err.new(Err.CORRUPT, "bad song length") + end + for i = 1, songLength do + m.order[i] = seq:u8() + end + for i = 1, nch do + local k = (i - 1) % 4 + m.channelPan[i] = if k == 1 or k == 2 then 0xC0 else 0x40 + if i <= 16 then + m.channelVolume[i] = math.min(trackVol[i], 64) + end + end + else + local s2 = song:sub(4, 256) + local playSeqTable, sectionTable, trackVolsOff = s2:u32be(), s2:u32be(), s2:u32be() + local numTracks, numPlaySeqs = s2:u16be(), s2:u16be() + local trackPanOff, flags3, volAdjust = s2:u32be(), s2:u32be(), s2:u16be() + if numTracks < 1 or numTracks > 64 then + return nil, Err.new(Err.CORRUPT, "bad track count") + end + local freePan = not hardwareMix and bit32.band(flags3, 2) ~= 0 + if volAdjust > 0 then + preamp = (preamp * math.min(volAdjust, 800) + 50) // 100 + end + if freePan then + preamp //= 2 + end + if trackVolsOff > 0 then + for i = 1, nch do + m.channelVolume[i] = math.min(r:sub(trackVolsOff + i - 1, 1):u8(), 64) + end + end + local pans = (freePan or version > 2) and trackPanOff > 0 + for i = 1, nch do + if pans then + m.channelPan[i] = (math.clamp(r:sub(trackPanOff + i - 1, 1):i8(), -16, 16) + 16) * 8 + else + local k = (i - 1) % 4 + m.channelPan[i] = if k == 1 or k == 2 then 0xC0 else 0x40 + end + end + local sections = r:sub(sectionTable, songLength * 2) + for _ = 1, songLength do + local sec = sections:u16be() + if sections.err then + break + end + if sec <= numPlaySeqs then + local ps = r:sub(playSeqTable + sec * 4, 4):u32be() + local pr = r:sub(ps, 42) + pr:skip(32) + local cmdTable = pr:u32be() + pr:skip(4) + local len = pr:u16be() + if not pr.err then + if #m.order > 0 then + table.insert(m.order, 254) + end + local start = #m.order + local er = r:sub(ps + 42, len * 2) + for _ = 1, len do + local b = er:u16be() + if er.err then + break + end + if b < 0x8000 then + table.insert(m.order, math.min(b, 253)) + end + end + if cmdTable > 0 then + local cr = r:sub(cmdTable) + for _ = 1, 4096 do + local off, c, extra = cr:u16be(), cr:u8(), cr:u8() + local arg = if extra >= 2 then cr:sub(cr:tell(), 2):u16be() else 0 + cr:skip(extra) + local at = start + off + 1 + if cr.err or off == 0xFFFF or at > #m.order then + break + end + if c == 1 then + m.order[at] = 255 + elseif c == 2 then + jumps[at] = arg + m.order[at] = 254 + end + end + end + end + end + 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, + softMix = bit32.band(flags2, 0x80) ~= 0, + bpm = bit32.band(flags2, 0x20) ~= 0, + rowsPerBeat = 1 + bit32.band(flags2, 0x1F), + volHex = bit32.band(flags, 0x10) ~= 0, + vol7bit = false, + } + m.tempo = tempoToBpm(defTempo, ctx) + m.speed = math.clamp(tempo2, 1, 32) + 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 + if p and p > 0 then + pat, high = readBlock(r, p, version, ctx, nch) + end + m.patterns[b + 1] = pat or Tracker.newPattern(64, nch) + needInstruments = needInstruments or high + end + -- play-sequence jumps: a jump effect at the end of the block before the command + 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) + table.insert(m.patterns, cp) + m.order[at - 1] = #m.patterns - 1 + Load.writeEffect(m, #m.patterns - 1, cp.rows - 1, 0xB, math.min(to, 255), "prev") + end + end + m.samples = samples + if needInstruments then + m.instrumentMode = true + m.instruments = instruments + end + if #unsupported > 0 then + m.meta.unsupported = unsupported + end + if ext.annoOff > 0 and ext.annoLen > 1 then + m.meta.message = r:sub(ext.annoOff, ext.annoLen - 1):string(math.min(ext.annoLen - 1, r:size())) + end + m.meta.source = { format = "med", version = "MMD" .. version, instruments = needInstruments } + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function Med.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Med.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Med diff --git a/src/Formats/music/midi/init.luau b/src/Formats/music/midi/init.luau index ac60034..4bbaad9 100644 --- a/src/Formats/music/midi/init.luau +++ b/src/Formats/music/midi/init.luau @@ -3,7 +3,9 @@ -- 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), encode (running +-- 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). @@ -13,7 +15,7 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Smf = require("@formats/music/midi/Smf") -local Render = require("@formats/music/midi/Render") +local Render = require("@formats/codecs/audio/MidiRender") -- ------------------------------------------------------------------------------------------------ contract local Midi = { @@ -21,7 +23,7 @@ local Midi = { category = "music", extensions = { "mid", "midi", "smf", "kar", "rmi" }, mime = { "audio/midi", "audio/x-midi" }, - deps = { "core/Err", "core/Bytes", "codecs/audio/SoundFont", "Types" }, + deps = { "core/Err", "core/Bytes", "codecs/audio/MidiRender", "Types" }, caps = { decode = true, encode = true, formats = { 0, 1, 2 }, render = true, streaming = true, rmid = true }, } @@ -42,46 +44,63 @@ function Midi.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode -local function render(self: Types.Midi, opts: RenderOptions?): Types.Decoder - local dec, err = Render.decoder(self, opts) - if not dec then - -- the Types contract returns a Decoder; a failed render is an empty one (Midi.render returns the Err) - local empty: any = { - sampleRate = 44100, channels = 2, frames = 0, duration = 0, bitrate = 0, tags = {}, err = err, - read = function(_self: any, _n: number, out: buffer?): (buffer, number) - return out or buffer.create(0), 0 - end, - seek = function() end, - position = function(): number - return 0 - end, - } - return empty - end - return dec -end - -local function summarize(midi: Types.Midi) - local tempos, sigs, keys = {}, {}, {} +-- 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 +local function karaoke(midi: Types.Midi) + local lyrics: { { time: number, tick: number, text: string } } = {} + local headers: { [string]: { string } } = {} local map = Render.tempoMap(midi) - for ti, t in midi.tracks do + local kar, hasWords = false, false + for _, t in midi.tracks do + if t.name == "Words" then + kar, hasWords = true, true + end for _, ev in t.events do - if ev.type == "meta" then - local d = ev.data :: { number } - if ev.meta == 0x51 and #d >= 3 then - table.insert(tempos, { tick = ev.tick, track = ti, usPerQuarter = d[1] * 65536 + d[2] * 256 + d[3], bpm = 60000000 / math.max(1, d[1] * 65536 + d[2] * 256 + d[3]), seconds = Render.seconds(map, ev.tick) }) - elseif ev.meta == 0x58 and #d >= 4 then - table.insert(sigs, { tick = ev.tick, track = ti, numerator = d[1], denominator = 2 ^ math.min(d[2], 31), clocksPerClick = d[3], notated32ndsPerBeat = d[4] }) - elseif ev.meta == 0x59 and #d >= 2 then - table.insert(keys, { tick = ev.tick, track = ti, sharps = if d[1] >= 128 then d[1] - 256 else d[1], minor = d[2] == 1 }) + if ev.type == "meta" and ev.meta == 1 and type(ev.data) == "table" and ev.data[1] == 64 then + local c = ev.data[2] + if c == 75 or c == 84 then -- @K, @T + kar = true end end end end - midi.meta.tempos = tempos - midi.meta.timeSignatures = sigs - midi.meta.keySignatures = keys - midi.meta.length = Render.length(midi) + for ti, t in midi.tracks do + local tmap = if midi.format == 2 then Render.tempoMap(midi, ti) else map + local words = kar and (t.name == "Words" or not hasWords) + for _, ev in t.events do + if ev.type == "meta" and type(ev.data) == "table" and (ev.meta == 5 or (ev.meta == 1 and words)) then + local text = Smf.text(ev.data :: { number }) + if ev.meta == 1 and string.sub(text, 1, 1) == "@" and #text >= 2 then + local key = string.sub(text, 2, 2) + local list = headers[key] or {} + headers[key] = list + table.insert(list, string.sub(text, 3)) + else + table.insert(lyrics, { time = Render.seconds(tmap, ev.tick), tick = ev.tick, text = text }) + end + end + end + end + if #lyrics == 0 and next(headers) == nil then + return + end + table.sort(lyrics, function(a: { time: number, tick: number, text: string }, b: { time: number, tick: number, text: string }): boolean + return a.time < b.time + end) + midi.meta.lyrics = lyrics + midi.meta.karaoke = headers + local tags: { [string]: string } = {} + if headers.T then + tags.title = headers.T[1] + tags.artist = headers.T[2] + end + if headers.L then + tags.language = headers.L[1] + end + if headers.I then + tags.comment = table.concat(headers.I, "\n") + end + midi.meta.tags = tags end function Midi.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Midi?, Err.Err?) @@ -89,9 +108,8 @@ function Midi.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Midi?, Err.E if not midi then return nil, err end - summarize(midi) - midi.meta.source = { format = "midi", smf = midi.format } - midi.render = render + Render.attach(midi, { format = "midi", smf = midi.format }) + karaoke(midi) return midi, nil end diff --git a/src/Formats/music/mtm/init.luau b/src/Formats/music/mtm/init.luau new file mode 100644 index 0000000..049bb85 --- /dev/null +++ b/src/Formats/music/mtm/init.luau @@ -0,0 +1,226 @@ +--!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. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Tracker = require("@formats/codecs/audio/Tracker") +local Load = require("@formats/codecs/audio/Tracker/Load") + +-- ------------------------------------------------------------------------------------------------ contract +local Mtm = { + name = "mtm", + category = "music", + extensions = { "mtm" }, + mime = { "audio/x-mtm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 32 } }, +} + +export type DecodeOptions = { + maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Mtm.sniff(r: Bytes.Reader): number + if r:size() >= 66 and r:peek(3) == "MTM" and r:peekU8(3) < 0x20 and r:peekU8(33) >= 1 and r:peekU8(33) <= 32 then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- MultiTracker: a speed command resets the tempo to 125 and a tempo command the speed to 6, unless the module puts +-- both on one row somewhere (then it was written for players that treat them as ProTracker does) +local function speedTempoQuirk(m: any) + local speed, tempo, together = false, false, false + for _, p in m.patterns do + for row = 0, p.rows - 1 do + local s, t = false, false + for c = 1, m.channels do + local o = (row * m.channels + c - 1) * 5 + local fx, param = buffer.readu8(p.data, o + 3), buffer.readu8(p.data, o + 4) + if fx == 0xF then + if param < 0x20 then + s = true + else + t = true + end + end + end + speed, tempo, together = speed or s, tempo or t, together or (s and t) + end + end + if not (speed and tempo) or together then + return + end + for pi, p in m.patterns do + for row = 0, p.rows - 1 do + for c = 1, m.channels do + local o = (row * m.channels + c - 1) * 5 + local fx, param = buffer.readu8(p.data, o + 3), buffer.readu8(p.data, o + 4) + if fx == 0xF then + Load.writeEffect(m, pi - 1, row, 0xF, if param < 0x20 then 125 else 6, nil, nil, true) + break + end + end + end + end +end + +function Mtm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local budget = { left = opts and opts.maxBytes or 2 ^ 28 } + if r:size() < 66 then + return nil, Err.new(Err.TRUNCATED, "header") + end + if r:peek(3) ~= "MTM" then + return nil, Err.new(Err.CORRUPT, "no MTM signature") + end + r:skip(3) + local version = r:u8() + local title = r:fixed(20) + local numTracks, lastPattern, lastOrder = r:u16le(), r:u8(), r:u8() + local commentSize, numSamples, _attr, rowsPerTrack, nch = r:u16le(), r:u8(), r:u8(), r:u8(), r:u8() + local pans: { number } = {} + for i = 1, 32 do + pans[i] = r:u8() + end + if r.err then + return nil, r.err + end + if version >= 0x20 or lastOrder > 127 or rowsPerTrack > 64 or nch == 0 or nch > 32 then + return nil, Err.new(Err.CORRUPT, "bad header") + end + local m = Tracker.newModule("mtm", nch, "xm") + m.title = title + m.linear = false + m.instrumentMode = false + 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)) + local len, ls, le = r:u32le(), r:u32le(), r:u32le() + local ft, vol, attr = r:i8(), r:u8(), r:u8() + if r.err then + return nil, r.err + end + s.volume = math.min(vol, 64) + s.finetune = math.clamp(ft * 16, -128, 127) + local bits = if attr % 2 == 1 then 16 else 8 + s.bits = bits + local frames = 0 + if len > 2 then + frames = len + le = math.min(math.max(le, 1) - 1, len) + if ls + 4 >= le then + ls, le = 0, 0 + end + if bits == 16 then + frames, ls, le = frames // 2, ls // 2, le // 2 + end + if le > 2 then + s.loopStart, s.loopEnd, s.loopType = ls, le, 1 + end + end + sizes[i] = if len > 2 then len else 0 + 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 + m.order[i] = o + end + end + if r.err then + return nil, r.err + end + -- tracks (64 rows of 3 bytes each) and the patterns made of them + local rows = if rowsPerTrack > 0 then rowsPerTrack else 64 + local tracks = r:tell() + if not r:skip(192 * numTracks) then + return nil, r.err + end + local buf = r.buf + for p = 0, lastPattern do + local pat = Tracker.newPattern(rows, nch) + m.patterns[p + 1] = pat + for ch = 0, 31 do + local track = r:u16le() + if r.err then + return nil, r.err + end + if track > 0 and track <= numTracks and ch < nch then + local base = r.base + tracks + 192 * (track - 1) + for row = 0, rows - 1 do + local o = base + row * 3 + local b0, b1, b2 = buffer.readu8(buf, o), buffer.readu8(buf, o + 1), buffer.readu8(buf, o + 2) + local q = (row * nch + ch) * 5 + if b0 >= 4 then + buffer.writeu8(pat.data, q, b0 // 4 + 25) -- C-4 = 49 plays the sample at 8363 Hz (OpenMPT keeps MTM / XM notes an octave up) + end + buffer.writeu8(pat.data, q + 1, (b0 % 4) * 16 + b1 // 16) + local cmd, param = b1 % 16, b2 + if cmd == 0xA then + param = if param >= 16 then param - param % 16 else param + elseif cmd == 8 then + cmd, param = 0, 0 -- no 8xx panning in MultiTracker + elseif cmd == 0xE then + local x = param // 16 + if x == 0 or x == 3 or x == 4 or x == 6 or x == 7 or x == 0xF then + cmd, param = 0, 0 -- not in MultiTracker + end + end + buffer.writeu8(pat.data, q + 3, cmd) + buffer.writeu8(pat.data, q + 4, param) + end + end + end + end + speedTempoQuirk(m) + -- the song message (40-character lines), then the sample data (unsigned PCM) + m.meta.message = r:string(commentSize) + if r.err then + r.err = nil + end + local pos = r.pos + for i = 1, numSamples do + local s = m.samples[i] + if sizes[i] > 0 then + local ok, err = Load.readSample(buf, pos, s.length, { bits = s.bits, signed = false, limit = r.limit }, s, budget) + if not ok then + return nil, err + end + pos += sizes[i] + s.loopEnd = math.min(s.loopEnd, s.length) + end + end + m.meta.source = { format = "mtm", version = version, tracks = numTracks } + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function Mtm.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Mtm.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Mtm diff --git a/src/Formats/music/mus/init.luau b/src/Formats/music/mus/init.luau new file mode 100644 index 0000000..c36d954 --- /dev/null +++ b/src/Formats/music/mus/init.luau @@ -0,0 +1,163 @@ +--!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). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Render = require("@formats/codecs/audio/MidiRender") + +-- ------------------------------------------------------------------------------------------------ contract +local Mus = { + name = "mus", + category = "music", + extensions = { "mus" }, + mime = { "audio/x-mus" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/MidiRender" }, + caps = { decode = true, encode = false, render = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + rate: number?, -- ticks per second, default 140 (Doom); some players use 70 + maxEvents: number?, -- default 2^24 +} + +-- ------------------------------------------------------------------------------------------------ constants +-- MUS controller / system event number -> MIDI controller (0 is the program change) +local CONTROLLER = { [0] = 0, 0, 0x01, 0x07, 0x0A, 0x0B, 0x5B, 0x5D, 0x40, 0x43, 0x78, 0x7B, 0x7E, 0x7F, 0x79 } + +-- ------------------------------------------------------------------------------------------------ sniff +function Mus.sniff(r: Bytes.Reader): number + return if r:peek(4) == "MUS\x1a" then 1 else 0 +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 } + local volume: { [number]: number } = {} + local nextChannel = 0 + local tick = 0 + while p < e do + local ev = readu8(b, p) + p += 1 + local kind, mch = bit32.band(bit32.rshift(ev, 4), 7), bit32.band(ev, 15) + if kind == 6 then + return events, nil, false + end + local ch = map[mch] + if not ch then + ch = nextChannel + map[mch] = ch + nextChannel += if nextChannel == 8 then 2 else 1 + table.insert(events, { tick = tick, type = "controller", channel = ch, data = { 0x07, 127 } }) + end + local need = if kind == 1 then (if p < e and readu8(b, p) >= 128 then 2 else 1) elseif kind == 4 then 2 elseif kind == 5 then 0 else 1 + if kind == 7 then + return nil, "unknown event type 7", false + elseif p + need > e then + return events, nil, true + end + local d1, d2 = if need > 0 then readu8(b, p) else 0, if need > 1 then readu8(b, p + 1) else 0 + p += need + if kind == 0 then + table.insert(events, { tick = tick, type = "noteOff", channel = ch, data = { d1 % 128, 64 } }) + elseif kind == 1 then + if need == 2 then + volume[ch] = math.min(d2, 127) + end + table.insert(events, { tick = tick, type = "noteOn", channel = ch, data = { d1 % 128, volume[ch] or 127 } }) + elseif kind == 2 then + table.insert(events, { tick = tick, type = "pitchBend", channel = ch, data = { bit32.band(d1, 1) * 64, bit32.rshift(d1, 1) } }) + elseif kind == 3 or kind == 4 then + local c, v = d1, if kind == 3 then (if d1 == 12 then math.min(primary + 1, 127) else 0) else math.min(d2, 127) + if CONTROLLER[c] == nil then + return nil, string.format("unknown controller %d", c), false + end + if kind == 4 and c == 0 then + table.insert(events, { tick = tick, type = "program", channel = ch, data = { v } }) + else + table.insert(events, { tick = tick, type = "controller", channel = ch, data = { CONTROLLER[c], v } }) + end + end + if #events > maxEvents then + return nil, "limit: more than " .. maxEvents .. " events", false + end + if ev >= 128 then + local delay = 0 + repeat + if p >= e then + return events, nil, true + end + local c = readu8(b, p) + p += 1 + delay = delay * 128 + c % 128 + until c < 128 or delay > 2 ^ 28 + tick += delay + end + end + return events, nil, true +end + +function Mus.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Midi?, Err.Err?) + local o: DecodeOptions = opts or {} + local rate = o.rate or 140 + if type(rate) ~= "number" or rate < 1 or rate > 100000 then + return nil, Err.new(Err.ARG, "rate must be 1..100000 ticks per second") + end + if r:peek(4) ~= "MUS\x1a" then + return nil, Err.new(Err.CORRUPT, "not a MUS file") + end + r:skip(4) + local len, start, primary, secondary, ninst = r:u16le(), r:u16le(), r:u16le(), r:u16le(), r:u16le() + r:skip(2) + local instruments = {} + for i = 1, ninst do + instruments[i] = r:u16le() + end + if r.err then + return nil, r.err + end + local size = r.limit - r.base + if start > size then + return nil, Err.new(Err.TRUNCATED, "score starts past the end") + end + local p = r.base + start + local events, msg, truncated = score(r.buf, p, math.min(p + len, r.limit), primary, o.maxEvents or 2 ^ 24) + if not events then + return nil, Err.from(msg :: string, p) + end + local last = events[#events].tick + table.insert(events, 1, { tick = 0, type = "meta", meta = 0x51, data = Render.tempoBytes(70, rate) }) + table.insert(events, { tick = last, type = "meta", meta = 0x2F, data = {} }) + local midi = Types.Midi.new(70) + midi.format = 0 + midi.tracks = { { events = events } } + Render.attach(midi, { format = "mus", primaryChannels = primary, secondaryChannels = secondary, instruments = instruments, rate = rate }) + midi.meta.truncated = truncated or p + len > r.limit + return midi, nil +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 + return nil, err + end + return Render.decoder(midi, opts) +end + +return Mus diff --git a/src/Formats/music/okt/init.luau b/src/Formats/music/okt/init.luau new file mode 100644 index 0000000..d23eab3 --- /dev/null +++ b/src/Formats/music/okt/init.luau @@ -0,0 +1,286 @@ +--!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. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Chunks = require("@formats/containers/Chunks") +local Tracker = require("@formats/codecs/audio/Tracker") +local Load = require("@formats/codecs/audio/Tracker/Load") + +-- ------------------------------------------------------------------------------------------------ contract +local Okt = { + name = "okt", + category = "music", + extensions = { "okt", "okta" }, + mime = { "audio/x-okt" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 4, 8 } }, +} + +export type DecodeOptions = { + maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ constants +local IT = Load.IT +local LAYOUT = table.freeze({ bigEndian = true }) :: Chunks.Layout + +-- ------------------------------------------------------------------------------------------------ sniff +function Okt.sniff(r: Bytes.Reader): number + return if r:peek(8) == "OKTASONG" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- a negative arpeggio offset as the equivalent positive one +local function invert(p: number): number + p %= 16 + if p == 0 then + return 0 + end + 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 + elseif e == 2 and p > 0 then + return "portadown", p, -1, false + elseif e == 10 and p > 0 then + return "arpeggio", p % 16 + invert(p // 16) * 16, -1, false -- down, original, up + elseif e == 11 and p > 0 then + return "arpeggio", p - p % 16 + invert(p % 16), -1, false -- original, up, original, down + elseif e == 12 and p > 0 then + return "arpeggio", p, -1, false -- up, up, original + elseif e == 13 and p > 0 then + return "noteslidedown", 0x10 + math.min(p, 15), -1, false + elseif e == 30 and p > 0 then + return "noteslideup", 0x10 + math.min(p, 15), -1, false + elseif e == 21 and p > 0 then + return "noteslidedown", 0x50 + math.min(p, 15), -1, false + elseif e == 17 and p > 0 then + return "noteslideup", 0x50 + math.min(p, 15), -1, false + elseif e == 25 then + return "jump", p, -1, false + elseif e == 27 then + return nil, 0, -1, true + elseif e == 28 and p < 0x20 then + return "speed", p, -1, false + elseif e == 31 then + local x, y = p // 16, p % 16 + local slide = if paired then "chanvolslide" else "volslide" + if p <= 0x40 then + if paired then + return "chanvol", p, -1, false + end + return nil, 0, p, false + elseif x == 4 then + return slide, y, -1, false + elseif x == 5 then + return slide, y * 16, -1, false + elseif x == 6 then + return slide, 0xF0 + math.min(y, 0xE), -1, false + elseif x == 7 then + return slide, math.min(y, 0xE) * 16 + 0xF, -1, false + end + end + return nil, 0, -1, false +end + +function Okt.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local budget = { left = opts and opts.maxBytes or 2 ^ 28 } + if r:peek(8) ~= "OKTASONG" then + return nil, Err.new(if r:size() < 8 then Err.TRUNCATED else Err.CORRUPT, "no OKTASONG signature") + end + local buf = r.buf + local list = Chunks.walk(buf, r.base + 8, r.limit, LAYOUT) + local cmod = Chunks.find(list, "CMOD") + if not cmod or cmod.avail < 8 then + return nil, Err.new(Err.CORRUPT, "no channel table (CMOD)") + end + -- channels: each Amiga channel is one channel, or a mixed pair + local paired: { number } = {} -- 1: the first of a pair, -1: the second, 0: a raw Paula channel + local pans: { number } = {} + for ch = 0, 3 do + local pan = if ch == 1 or ch == 2 then 0xC0 else 0x40 + if buffer.readu16(buf, cmod.offset + ch * 2) ~= 0 then + table.insert(paired, 1) + table.insert(pans, pan) + table.insert(paired, -1) + else + table.insert(paired, 0) + end + table.insert(pans, pan) + end + local nch = #paired + local m = Tracker.newModule("okt", nch, "it") + m.linear = false + m.instrumentMode = false + m.tempo = 125 + m.flags.periods, m.flags.amigaLimits, m.flags.fastPortas, m.flags.oktSlides = "amiga", true, true, true + for i = 1, nch do + m.channelPan[i] = pans[i] + end + -- samples: 32-byte headers (name, length, loop start / length in words, volume, type 0 / 1 / 2) + local types: { number } = {} + local samp = Chunks.find(list, "SAMP") + if samp then + for i = 1, math.min(samp.avail // 32, 36) do + local h = Bytes.reader(buf, samp.offset + (i - 1) * 32, 32) + local s = Tracker.newSample(h:fixed(20)) + local len, ls, ll, vol, typ = h:u32be(), h:u16be() * 2, h:u16be() * 2, h:u16be(), h:u16be() + s.c5speed = 8287 + s.volume = math.min(vol, 64) + s.length = len - len % 2 + if ll > 2 and ls + ll <= s.length then + s.susStart, s.susEnd, s.susType = ls, ls + ll, 1 + end + types[i] = typ + m.samples[i] = s + end + end + local spee = Chunks.find(list, "SPEE") + if spee and spee.avail >= 2 then + m.speed = math.clamp(buffer.readu8(buf, spee.offset) * 256 + buffer.readu8(buf, spee.offset + 1), 1, 255) + end + local nord = 0 + local plen = Chunks.find(list, "PLEN") + if plen and plen.avail >= 2 then + nord = buffer.readu8(buf, plen.offset) * 256 + buffer.readu8(buf, plen.offset + 1) + end + local patt = Chunks.find(list, "PATT") + for i = 1, math.min(nord, if patt then patt.avail else 0) do + m.order[i] = buffer.readu8(buf, (patt :: Chunks.Chunk).offset + i - 1) + end + -- patterns (PBOD: rows, then 4 bytes per cell: note 1..36, sample, effect, parameter) + local copies: { [number]: boolean } = {} -- type B samples with a loop also need an unlooped copy (paired channels) + local npat = 0 + for _, c in list do + if c.id == "PBOD" and npat < 256 then + local pr = Bytes.reader(buf, c.offset, c.avail) + local rows = if c.avail >= 2 then math.clamp(pr:u16be(), 1, 1024) else 64 + local pat = Tracker.newPattern(rows, nch) + npat += 1 + m.patterns[npat] = pat + local d = pat.data + for row = 0, rows - 1 do + for ch = 0, nch - 1 do + local note, ins, e, p = pr:u8(), pr:u8(), pr:u8(), pr:u8() + if pr.err then + break + end + local q = (row * nch + ch) * 5 + local pair = paired[ch + 1] ~= 0 + if note > 0 and note <= 36 then + local n = note + 36 -- note 13 = C-4 = ProTracker period 428 (OpenMPT keeps MOD notes an octave up) + if pair and n >= 49 + 22 then + n = 49 + 21 -- the mixer's highest note + end + local smp = ins + 1 + local s = m.samples[smp] + if s then + if pair and s.volume < 64 then + buffer.writeu8(d, q + 2, 64 + 1) -- the default volume only works on raw Paula channels + end + local t = types[smp] + if (t == 1 and pair) or (t == 0 and not pair) then + smp += 100 -- a sample of the wrong type stops the channel + elseif t == 2 and pair and s.susType > 0 then + copies[smp] = true + smp += 36 + end + end + buffer.writeu8(d, q, n) + buffer.writeu8(d, q + 1, smp) + end + local name, param, vol, off = effect(e, p, pair) + if off then + buffer.writeu8(d, q, 255) + buffer.writeu8(d, q + 1, 0) + end + if vol >= 0 then + buffer.writeu8(d, q + 2, vol + 1) + end + local fx, fp = Load.itEffect(name, param) + if fx ~= 0 then + buffer.writeu8(d, q + 3, fx) + buffer.writeu8(d, q + 4, fp) + if name == "chanvol" or name == "chanvolslide" then + -- a mixed pair shares its volume: the other channel gets it too (the second one wins) + local other = ch + paired[ch + 1] + local o2 = (row * nch + other) * 5 + local ofx = buffer.readu8(d, o2 + 3) + if ofx == 0 or ofx == IT.chanvol or ofx == IT.chanvolslide then + buffer.writeu8(d, o2 + 3, fx) + buffer.writeu8(d, o2 + 4, fp) + end + end + end + end + end + end + end + -- sample data: SBOD chunks in order (signed 8-bit), for the samples with a length + local k = 0 + local bodies: { Chunks.Chunk } = {} + for _, c in list do + if c.id == "SBOD" and c.avail > 0 then + table.insert(bodies, c) + end + end + local nsmp = #m.samples + for i = 1, nsmp do + local s = m.samples[i] + if s.length > 0 then + k += 1 + local c = bodies[k] + if not c then + s.length = 0 + continue + end + local ok, err = Load.readSample(buf, c.offset, math.min(s.length, c.avail), { bits = 8, signed = true, limit = c.offset + c.avail }, s, budget) + if not ok then + return nil, err + end + end + end + for i = 1, nsmp do + local s = m.samples[i] + if copies[i] then + local cp = Tracker.newSample(s.name) + cp.c5speed, cp.volume, cp.data, cp.length = s.c5speed, s.volume, s.data, s.length + m.samples[i + 36] = cp + end + end + for i = 1, (if next(copies) then 72 else nsmp) do + if m.samples[i] == nil then + m.samples[i] = Tracker.newSample() + end + end + m.meta.source = { format = "okt", channels = nch } + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function Okt.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Okt.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Okt diff --git a/src/Formats/music/ptm/init.luau b/src/Formats/music/ptm/init.luau new file mode 100644 index 0000000..66818a1 --- /dev/null +++ b/src/Formats/music/ptm/init.luau @@ -0,0 +1,227 @@ +--!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. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Tracker = require("@formats/codecs/audio/Tracker") +local Load = require("@formats/codecs/audio/Tracker/Load") + +-- ------------------------------------------------------------------------------------------------ contract +local Ptm = { + name = "ptm", + category = "music", + extensions = { "ptm" }, + mime = { "audio/x-ptm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 32 } }, +} + +export type DecodeOptions = { + maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ constants +-- PolyTracker's effects past MOD's 0..F +local EXTRA = { "globalvol", "retrig", "finevibrato", "noteslideup", "noteslidedown", "noteslideupretrig", "noteslidedownretrig" } + +-- ------------------------------------------------------------------------------------------------ sniff +local function validHeader(r: Bytes.Reader): boolean + if r:size() < 608 or r:peek(4, 44) ~= "PTMF" or r:peekU8(28) ~= 26 or r:peekU8(30) > 2 then + return false + end + local h = r:sub(32, 10) + local nord, nsmp, npat, nch, flags = h:u16le(), h:u16le(), h:u16le(), h:u16le(), h:u16le() + return flags == 0 and nch >= 1 and nch <= 32 and nord >= 1 and nord <= 256 and nsmp >= 1 and nsmp <= 255 and npat >= 1 and npat <= 128 +end + +function Ptm.sniff(r: Bytes.Reader): number + return if validHeader(r) then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- 16-bit samples: the byte stream is 8-bit delta coded, then read as little-endian 16-bit values +local function delta16(buf: buffer, off: number, frames: number, limit: number): (buffer, number) + local n = math.max(0, math.min(frames, (limit - off) // 2)) + local raw = buffer.create(n * 2) + local acc = 0 + for i = 0, n * 2 - 1 do + acc = (acc + buffer.readu8(buf, off + i)) % 256 + buffer.writeu8(raw, i, acc) + end + 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 + elseif cmd > 0x10 then + return EXTRA[cmd - 0x10 + 1], param + elseif cmd == 8 then + return "s3mex", 0x80 + (math.max(param // 8, 1) - 1) % 16 -- 8xx pans in 16 steps + end + return Load.modCommand(cmd, param) +end + +-- one pattern (S3M-style packing: 0 ends a row; channel | 0x20 note + instrument, 0x40 effect, 0x80 volume) +local function readPattern(pr: Bytes.Reader, d: buffer, nch: number) + local row = 0 + while row < 64 and not pr:eof() do + local b = pr:u8() + if b == 0 then + row += 1 + else + local ch = b % 32 + local q = (row * nch + ch) * 5 + local ok = ch < nch + if bit32.band(b, 0x20) ~= 0 then + local note, ins = pr:u8(), pr:u8() + if note == 254 then + note = 254 + elseif note == 0 or note > 120 then + note = 0 + end + if ok then + buffer.writeu8(d, q, note) + buffer.writeu8(d, q + 1, ins) + end + end + if bit32.band(b, 0x40) ~= 0 then + local name, param = effect(pr:u8(), pr:u8()) + if ok then + if name == "volume" then + if buffer.readu8(d, q + 2) == 0 then + buffer.writeu8(d, q + 2, math.min(param, 64) + 1) + end + else + local fx, fp = Load.itEffect(name, param) + buffer.writeu8(d, q + 3, fx) + buffer.writeu8(d, q + 4, fp) + end + end + end + if bit32.band(b, 0x80) ~= 0 then + local v = pr:u8() + if ok then + buffer.writeu8(d, q + 2, math.min(v, 64) + 1) + end + end + end + end +end + +function Ptm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local budget = { left = opts and opts.maxBytes or 2 ^ 28 } + if not validHeader(r) then + return nil, Err.new(if r:size() < 608 then Err.TRUNCATED else Err.CORRUPT, "not a PolyTracker module") + end + local title = r:fixed(28) + r:skip(1) + local vlo, vhi = r:u8(), r:u8() + r:skip(1) + local nord, nsmp, npat, nch = r:u16le(), r:u16le(), r:u16le(), r:u16le() + r:seek(64) + local m = Tracker.newModule("ptm", nch, "it") + m.title = title + m.linear = false + m.instrumentMode = false + m.flags.oldEffects, m.flags.compatGxx = true, true + m.flags.panLaw = "ft2" -- OpenMPT plays PTM with its FT2 mix levels + for i = 1, 32 do + local p = r:u8() + if i <= nch then + m.channelPan[i] = (p % 16) * 16 + 4 + end + end + for i = 1, 256 do + local o = r:u8() + if i <= nord then + m.order[i] = o + end + end + local patOff: { number } = {} + for i = 1, 128 do + patOff[i] = r:u16le() * 16 + end + if r.err then + return nil, r.err + end + -- samples + local buf = r.buf + for i = 1, nsmp do + local h = r:slice(80) + if r.err then + return nil, r.err + end + local flags = h:u8() + h:skip(12) + local vol, c4 = h:u8(), h:u16le() + h:skip(2) + local off, len, ls, le = h:u32le(), h:u32le(), h:u32le(), h:u32le() + h:skip(14) + local s = Tracker.newSample(h:fixed(28)) + m.samples[i] = s + s.volume = math.min(vol, 64) + s.c5speed = math.max(1, c4 * 2) + if flags % 4 == 1 and len > 0 then + local bits = if bit32.band(flags, 0x10) ~= 0 then 16 else 8 + if le > ls then + le -= 1 + end + local frames = len + if bits == 16 then + frames, ls, le = frames // 2, ls // 2, le // 2 + end + local at = r.base + off + if at < r.limit then + local ok, err + if bits == 16 then + local raw, n = delta16(buf, at, frames, r.limit) + ok, err = Load.readSample(raw, 0, n, { bits = 16, signed = true }, s, budget) + else + ok, err = Load.readSample(buf, at, frames, { bits = 8, signed = true, delta = true, limit = r.limit }, s, budget) + end + if not ok then + return nil, err + end + end + if bit32.band(flags, 4) ~= 0 and le > ls then + s.loopStart, s.loopEnd = ls, math.min(le, s.length) + s.loopType = if bit32.band(flags, 8) ~= 0 then 2 else 1 + end + end + end + for p = 1, npat do + local pat = Tracker.newPattern(64, nch) + m.patterns[p] = pat + if patOff[p] > 0 and patOff[p] < r:size() then + readPattern(r:sub(patOff[p]), pat.data, nch) + end + end + m.meta.source = { format = "ptm", version = string.format("%d.%02x", vhi, vlo) } + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function Ptm.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Ptm.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Ptm diff --git a/src/Formats/music/stm/init.luau b/src/Formats/music/stm/init.luau new file mode 100644 index 0000000..c2bf826 --- /dev/null +++ b/src/Formats/music/stm/init.luau @@ -0,0 +1,233 @@ +--!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. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Tracker = require("@formats/codecs/audio/Tracker") +local Load = require("@formats/codecs/audio/Tracker/Load") + +-- ------------------------------------------------------------------------------------------------ contract +local Stm = { + name = "stm", + category = "music", + extensions = { "stm" }, + mime = { "audio/x-stm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 4, 4 } }, +} + +export type DecodeOptions = { + maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ constants +local IT = Load.IT +-- .ABCDEFGHIJ (K..O do nothing) +local EFFECTS = { "speed", "jump", "break", "volslide", "portadown", "portaup", "toneporta", "vibrato", "tremor", "arpeggio" } + +-- ------------------------------------------------------------------------------------------------ sniff +local function validHeader(r: Bytes.Reader): boolean + if r:size() < 48 then + return false + end + local eof, ftype, major, minor = r:peekU8(28), r:peekU8(29), r:peekU8(30), r:peekU8(31) + local npat, gv = r:peekU8(33), r:peekU8(34) + if ftype ~= 2 or (eof ~= 0x1A and eof ~= 2) or major ~= 2 or (minor ~= 0 and minor ~= 10 and minor ~= 20 and minor ~= 21) then + return false + end + if npat > 64 or (gv > 64 and gv ~= 0x58) then + return false + end + for i = 20, 27 do + local c = r:peekU8(i) + if c < 0x20 or c >= 0x7F then + return false + end + end + return true +end + +function Stm.sniff(r: Bytes.Reader): number + return if validHeader(r) then 0.7 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- a tempo byte of files before ST 2.21 is decimal +local function tempoByte(v: number, minor: number): number + return if minor < 21 then (v // 10) * 16 + v % 10 else v +end + +function Stm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local budget = { left = opts and opts.maxBytes or 2 ^ 28 } + if not validHeader(r) then + return nil, Err.new(if r:size() < 48 then Err.TRUNCATED else Err.CORRUPT, "not a Scream Tracker 2 module") + end + local title = r:fixed(20) + local tracker = r:fixed(8) + r:skip(3) + local minor, initTempo, npat, gv = r:u8(), r:u8(), r:u8(), r:u8() + r:skip(13) + local m = Tracker.newModule("stm", 4, "s3m") + m.title = title + m.linear = false + m.instrumentMode = false + m.flags.st2Tempo = true + initTempo = tempoByte(initTempo, minor) + if initTempo == 0 then + initTempo = 0x60 + end + m.speed, m.tempo = Tracker.st2Tempo(initTempo) + if minor > 10 then + m.globalVolume = math.min(gv, 64) * 2 + end + local offsets: { number } = {} + for i = 1, 31 do + local s = Tracker.newSample(r:fixed(12)) + local zero = r:u8() + r:skip(1) + local off, len, ls, le = r:u16le(), r:u16le(), r:u16le(), r:u16le() + local vol = r:u8() + r:skip(1) + local rate = r:u16le() + r:skip(6) + if r.err then + return nil, r.err + end + if zero ~= 0 and zero ~= 46 then + return nil, Err.new(Err.CORRUPT, "bad sample header " .. i) + end + s.c5speed = if rate > 0 then rate else 8363 + s.volume = math.min(vol, 64) + if len < 2 then + len = 0 + end + if ls < len and le > ls and le ~= 0xFFFF then + s.loopStart, s.loopEnd, s.loopType = ls, le, 1 + len = math.max(le, len) -- ST2 lets a loop run into the next sample's data + end + s.length = len + offsets[i] = off * 16 + m.samples[i] = s + end + for i = 1, (if minor == 0 then 64 else 128) do + local o = r:u8() + if o == 99 or o == 255 then + o = 255 + elseif o > 63 then + return nil, Err.new(Err.CORRUPT, "bad order list") + end + m.order[i] = o + end + if r.err then + return nil, r.err + end + while #m.order > 0 and m.order[#m.order] == 255 do + table.remove(m.order) + end + -- patterns: 64 rows x 4 channels; one byte 0xFB (C-0, volume 0), 0xFC (nothing) or 0xFD (note cut), else 4 bytes + for p = 0, npat - 1 do + local pat = Tracker.newPattern(64, 4) + m.patterns[p + 1] = pat + local d = pat.data + local breakPos, breakRow = -1, 63 -- ST2: Bxx only sets the next order, taken at the pattern's end or a Cxx + for row = 0, 63 do + for ch = 0, 3 do + local q = (row * 4 + ch) * 5 + local note = r:u8() + local insVol, volCmd, info = 0, 0, 0 + if note == 0xFB then + note = 0 -- a C-0 at volume 0 (OpenMPT reads it so) + elseif note == 0xFD then + buffer.writeu8(d, q, 254) + elseif note ~= 0xFC then + insVol, volCmd, info = r:u8(), r:u8(), r:u8() + end + if note ~= 0xFC and note ~= 0xFD then + if note == 0xFE then + buffer.writeu8(d, q, 254) + elseif note < 0x60 then + buffer.writeu8(d, q, (note // 16) * 12 + note % 16 + 37) + end + local ins = insVol // 8 + buffer.writeu8(d, q + 1, if ins > 31 then 0 else ins) + local vol = insVol % 8 + (volCmd // 16) * 8 + if vol <= 64 then + buffer.writeu8(d, q + 2, vol + 1) + end + local name, param = EFFECTS[volCmd % 16], info + if name == "volslide" then + param = if param % 16 > 0 then param % 16 else param - param % 16 + elseif name == "break" then + param = ((param - param % 16) * 10 + param % 16) % 256 + if breakPos >= 0 and param == 0 then + name, param = "jump", breakPos -- Bxx + C00 is a plain Bxx + breakPos = -1 + end + breakRow = math.min(breakRow, row) + if name == "break" then + param = Load.bcd(param) + end + elseif name == "jump" then + breakPos, breakRow = param, 63 + name = nil + elseif name == "speed" then + param = tempoByte(param, minor) + if param == 0 then + name = nil + end + elseif name ~= "tremor" and param == 0 then + name = nil -- no effect memory in ST2 + end + if name then + buffer.writeu8(d, q + 3, IT[name]) + buffer.writeu8(d, q + 4, param) + end + end + end + end + if r.err then + return nil, r.err + end + if breakPos >= 0 then + Load.writeEffect(m, p, breakRow, IT.jump, breakPos, "prev") + end + end + -- sample data: signed 8-bit at the paragraph offsets (samples at volume 0 are not read) + local buf = r.buf + for i = 1, 31 do + local s = m.samples[i] + local len = s.length + s.length = 0 + if len > 0 and s.volume > 0 and offsets[i] > 48 then + local ok, err = Load.readSample(buf, r.base + offsets[i], len, { bits = 8, signed = true, limit = r.limit }, s, budget) + if not ok then + return nil, err + end + end + end + m.meta.source = { format = "stm", tracker = tracker, version = "2." .. minor } + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function Stm.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Stm.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Stm diff --git a/src/Formats/music/ult/init.luau b/src/Formats/music/ult/init.luau new file mode 100644 index 0000000..6071b0a --- /dev/null +++ b/src/Formats/music/ult/init.luau @@ -0,0 +1,309 @@ +--!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. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Tracker = require("@formats/codecs/audio/Tracker") +local Load = require("@formats/codecs/audio/Tracker/Load") + +-- ------------------------------------------------------------------------------------------------ contract +local Ult = { + name = "ult", + category = "music", + extensions = { "ult" }, + mime = { "audio/x-ult" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 32 } }, +} + +export type DecodeOptions = { + maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ constants +local EFFECTS: { [number]: string } = { + [0] = "arpeggio", [1] = "portaup", [2] = "portadown", [3] = "toneporta", [4] = "vibrato", [7] = "tremolo", + [9] = "offset", [10] = "volslide", [11] = "panning8", [12] = "volume8", [13] = "break", [15] = "speed", +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Ult.sniff(r: Bytes.Reader): number + local v = r:peekU8(14) + if r:size() >= 48 and r:peek(14) == "MAS_UTrack_V00" and v >= 0x31 and v <= 0x34 then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- one effect nibble + parameter -> name?, param (OpenMPT's TranslateULTCommands) +local function translate(e: number, param: number, version: number): (string?, number) + local name = EFFECTS[e] + if e == 0 then + if param == 0 or version < 3 then + name = nil + end + elseif e == 5 then + if (param % 16 == 0xC or param // 16 == 0xC) and version >= 3 then + return "keyoff", 0 + end + elseif e == 7 then + if version < 4 then + name = nil + end + elseif e == 0xA then + if param >= 16 then + param -= param % 16 + end + elseif e == 0xB then + param = (param % 16) * 0x11 + elseif e == 0xD then + param = 10 * (param // 16) + param % 16 + elseif e == 0xE then + local x, y = param // 16, param % 16 + if x == 1 then + return "portaup", 0xF0 + y + elseif x == 2 then + return "portadown", 0xF0 + y + elseif x == 8 and version >= 4 then + return "s3mex", 0x60 + y + elseif x == 9 then + return "retrig", y + elseif x == 0xA then + return "volslide", y * 16 + 0xF + elseif x == 0xB then + return "volslide", 0xF0 + y + elseif x == 0xC or x == 0xD then + return "s3mex", param + end + return nil, param + elseif e == 0xF then + if param > 0x2F then + name = "tempo" + end + end + return name, param +end + +-- volume slide + vibrato / tone portamento without a parameter -> one combined effect (OpenMPT's CombineEffects) +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 + elseif b == "volslide" and (a == "vibrato" or a == "toneportavol") and pa == 0 then + return if a == "vibrato" then "vibratovol" else "toneportavol", pb, nil, 0 + end + 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) +local function readEvent(r: Bytes.Reader, version: number): (number, number, number, number, number, number, string?, number) + local rep = 1 + local b = r:u8() + if b == 0xFC then + rep = r:u8() + b = r:u8() + end + local note = if b > 0 and b < 97 then b + 24 else 0 + local ins, cmd, p1, p2 = r:u8(), r:u8(), r:u8(), r:u8() + local c1, q1 = translate(cmd % 16, p1, version) + local c2, q2 = translate(cmd // 16, p2, version) + if c1 == "offset" and c2 == "offset" then + local off = (p2 * 256 + p1) // 64 + return rep, note, ins, 0, Load.IT.offset, off % 256, nil, 0 + elseif c1 == "offset" then + q1 = math.min(p1 * 4, 255) + elseif c2 == "offset" then + q2 = math.min(p2 * 4, 255) + elseif c1 ~= nil and c1 == c2 then + c2 = nil + end + if c2 == nil then -- (OpenMPT also swaps for CMD_VOLUME, which ULT never produces) + c1, q1, c2, q2 = c2, q2, c1, q1 + end + c2, q2, c1, q1 = combine(c2, q2, c1, q1) + if c1 == "keyoff" or c2 == "keyoff" then + -- key off (5xC): a note-off when the cell has no note + if note == 0 then + note = 255 + end + if c1 == "keyoff" then + c1 = nil + else + c2 = nil + end + end + local vol, name, param, lost, lostParam = Load.fillTwo(c1, q1, c2, q2) + local fx, fp = Load.itEffect(name, param) + return rep, note, ins, vol, fx, fp, lost, lostParam +end + +function Ult.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local budget = { left = opts and opts.maxBytes or 2 ^ 28 } + if Ult.sniff(r) == 0 then + return nil, Err.new(if r:size() < 48 then Err.TRUNCATED else Err.CORRUPT, "not an UltraTracker module") + end + r:skip(14) + local version = r:u8() - 0x30 + local title = (string.gsub(r:fixed(32), " +$", "")) + local lines = r:u8() + local message = r:string(lines * 32) + local nsmp = r:u8() + if r.err then + return nil, r.err + end + local samples, sizes = {}, {} + for i = 1, nsmp do + local s = Tracker.newSample((string.gsub(r:fixed(32), " +$", ""))) + r:skip(12) + local ls, le, ss, se = r:u32le(), r:u32le(), r:u32le(), r:u32le() + local vol, flags = r:u8(), r:u8() + local speed, finetune = 8363, 0 + if version >= 4 then + speed, finetune = r:u16le(), r:i16le() + else + finetune = r:i16le() + end + if r.err then + return nil, r.err + end + local bits = if bit32.band(flags, 4) ~= 0 then 16 else 8 + s.bits = bits + sizes[i] = 0 + if se > ss then + s.length = se - ss + sizes[i] = s.length * bits // 8 + s.volume = vol / 4 + s.c5speed = math.max(1, speed * 2 * 2 ^ (finetune / (12 * 32768))) + if bit32.band(flags, 8) ~= 0 then + if bits == 16 then + ls, le = ls // 2, le // 2 + end + s.susStart, s.susEnd = ls, le + s.susType = if bit32.band(flags, 16) ~= 0 then 2 else 1 + end + end + samples[i] = s + end + local order = {} + for i = 1, 256 do + order[i] = r:u8() + end + local nch, npat = r:u8() + 1, r:u8() + 1 + if r.err then + return nil, r.err + end + if nch > 32 then + return nil, Err.new(Err.UNSUPPORTED, nch .. " channels") + end + local m = Tracker.newModule("ult", nch, "it") + m.title = title + m.meta.message = message + m.linear = false + m.instrumentMode = false + m.flags.oldEffects, m.flags.compatGxx, m.flags.autoTonePorta = true, true, true + m.samples = samples + for i = 1, 256 do + m.order[i] = order[i] + end + while #m.order > 0 and m.order[#m.order] == 255 do + table.remove(m.order) + end + for i = 1, nch do + m.channelPan[i] = if version >= 3 then (r:u8() % 16) * 16 + 8 elseif i % 2 == 0 then 192 else 64 + end + for p = 1, npat do + m.patterns[p] = Tracker.newPattern(64, nch) + end + -- events, channel by channel, pattern by pattern + local speed0 = false + for ch = 0, nch - 1 do + for p = 0, npat - 1 do + if r:remaining() < 5 then + break + end + local d = m.patterns[p + 1].data + local row = 0 + while row < 64 do + local rep, note, ins, vol, fx, param, lost, lostParam = readEvent(r, version) + if r.err then + break + end + if lost and Load.isGlobal(lost, lostParam) then + local lf, lp = Load.itEffect(lost, lostParam) + Load.writeEffect(m, p, row, lf, lp, "next") + end + rep = math.min(rep, 64 - row) + if rep == 0 then + break + end + if fx == Load.IT.speed and param == 0 then + speed0 = true + end + for _ = 1, rep do + local q = (row * nch + ch) * 5 + buffer.writeu8(d, q, note) + buffer.writeu8(d, q + 1, ins) + buffer.writeu8(d, q + 2, vol) + buffer.writeu8(d, q + 3, fx) + buffer.writeu8(d, q + 4, param) + row += 1 + end + end + end + end + r.err = nil + if speed0 then + -- speed 0 resets the song speed and tempo (UltraTracker) + for p, pat in m.patterns do + for row = 0, 63 do + for ch = 0, nch - 1 do + local q = (row * nch + ch) * 5 + if buffer.readu8(pat.data, q + 3) == Load.IT.speed and buffer.readu8(pat.data, q + 4) == 0 then + buffer.writeu8(pat.data, q + 4, 6) + Load.writeEffect(m, p - 1, row, Load.IT.tempo, 125, "next") + end + end + end + end + end + -- sample data: signed 8 / 16-bit + local pos = r.pos + for i = 1, nsmp do + local s = samples[i] + if sizes[i] > 0 then + local ok, err = Load.readSample(r.buf, pos, s.length, { bits = s.bits, signed = true, limit = r.limit }, s, budget) + if not ok then + return nil, err + end + pos += sizes[i] + end + end + m.meta.source = { format = "ult", version = version } + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function Ult.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Ult.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Ult diff --git a/src/Formats/music/umx/init.luau b/src/Formats/music/umx/init.luau new file mode 100644 index 0000000..47b3640 --- /dev/null +++ b/src/Formats/music/umx/init.luau @@ -0,0 +1,222 @@ +--!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. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Tracker = require("@formats/codecs/audio/Tracker") + +-- ------------------------------------------------------------------------------------------------ contract +local Umx = { + name = "umx", + category = "music", + extensions = { "umx" }, + mime = { "audio/x-umx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" }, + caps = { decode = true, encode = false, render = true, container = true }, +} + +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) +} + +export type Entry = { name: string, data: buffer, format: string? } + +-- ------------------------------------------------------------------------------------------------ constants +local MAGIC = "\xC1\x83\x2A\x9E" + +-- ------------------------------------------------------------------------------------------------ sniff +type Header = { version: number, nameCount: number, nameOffset: number, exportCount: number, exportOffset: number, importCount: number, importOffset: number } + +local function header(r: Bytes.Reader): Header? + if r:size() < 36 or r:peek(4) ~= MAGIC then + return nil + end + local h = r:sub(4, 32) + local version = h:u16le() + h:skip(6) + local hd: Header = { + version = version, + nameCount = h:u32le(), + nameOffset = h:u32le(), + exportCount = h:u32le(), + exportOffset = h:u32le(), + importCount = h:u32le(), + importOffset = h:u32le(), + } + if h.err or hd.nameOffset < 36 or hd.exportOffset < 36 or hd.importOffset < 36 then + return nil + end + if hd.nameCount == 0 or hd.exportCount == 0 or hd.importCount == 0 or hd.nameCount > 2 ^ 20 or hd.exportCount > 2 ^ 20 or hd.importCount > 2 ^ 20 then + return nil + end + return hd +end + +-- a compact index: sign and 6 bits, then 7 bits per byte while the continue bits are set +local function index(r: Bytes.Reader): number + local b = r:u8() + local neg = b >= 0x80 + local v = b % 64 + if bit32.band(b, 0x40) ~= 0 then + local shift = 6 + repeat + b = r:u8() + v += (b % 128) * 2 ^ shift + shift += 7 + until b < 0x80 or shift >= 32 + end + return if neg then -v else v +end + +-- the name table (lower case) +local function names(r: Bytes.Reader, h: Header): { string } + local list = {} + local nr = r:sub(h.nameOffset) + for _ = 1, math.min(h.nameCount, 65536) do + if nr:remaining() < 5 then + break + end + if h.version >= 64 then + index(nr) + end + table.insert(list, string.lower(nr:cstring(1024))) + nr:skip(4) + end + return list +end + +function Umx.sniff(r: Bytes.Reader): number + local h = header(r) + if not h then + return 0 + end + return if table.find(names(r, h), "music") then 1 else 0.3 +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 + return nil, Err.new(if r:size() < 36 then Err.TRUNCATED else Err.CORRUPT, "not an Unreal package") + end + local nm = names(r, h) + -- imports: the class names objects refer to + local classes = {} + local ir = r:sub(h.importOffset) + for _ = 1, math.min(h.importCount, 65536) do + if ir:remaining() < 4 then + break + end + index(ir) + index(ir) + if h.version >= 60 then + ir:skip(4) + else + index(ir) + end + local obj = index(ir) + if obj >= 0 and obj < #nm then + table.insert(classes, obj) + end + end + local out: { Entry } = {} + local er = r:sub(h.exportOffset) + for _ = 1, math.min(h.exportCount, 65536) do + if er:remaining() < 8 then + break + end + local cls = -index(er) - 1 -- ~index: the import the class is + index(er) + if h.version >= 60 then + er:skip(4) + end + local objName = index(er) + er:skip(4) + local size, offset = index(er), index(er) + if er.err then + break + end + if cls >= 0 and cls < #classes and nm[classes[cls + 1] + 1] == "music" and size > 0 and offset > 36 then + local c = r:sub(offset, size) + if h.version < 40 then + c:skip(8) + end + if h.version < 60 then + c:skip(16) + end + index(c) -- the property list's "none" + if h.version >= 120 then + index(c) + c:skip(8) + elseif h.version >= 100 then + c:skip(4) + index(c) + c:skip(4) + elseif h.version >= 62 then + index(c) + c:skip(4) + else + index(c) + end + local len = index(c) + if not c.err and len > 0 and len <= c:remaining() then + local data = c:bytes(len) + local sig = Bytes.reader(data) + local fmt = if sig:peek(4) == "IMPM" then "it" elseif sig:peek(4, 44) == "SCRM" then "s3m" elseif sig:peek(17) == "Extended Module: " then "xm" elseif buffer.len(data) >= 1084 then "mod" else nil + table.insert(out, { name = nm[objName + 1] or "", data = data, format = fmt }) + end + end + end + return out, nil +end + +function Umx.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local list, err = Umx.extract(r) + if not list then + return nil, err + end + local i = opts and opts.index or 1 + local e = list[i] + if not e then + return nil, Err.new(Err.CORRUPT, "no music export" .. (if i > 1 then " " .. i else "")) + end + local hook = opts and opts.decodeModule + if type(hook) ~= "function" then + return nil, Err.new(Err.UNSUPPORTED, "the embedded " .. (e.format or "tracker") .. " module needs opts.decodeModule (F.load passes it; Umx.extract gives the bytes)") + end + local m, merr = hook(e.data, nil) + if not m then + return nil, merr + end + if type(m) ~= "table" or m.kind ~= "music" then + return nil, Err.new(Err.UNSUPPORTED, "the embedded module is not a tracker module") + end + local h = header(r) :: Header + m.meta = if type(m.meta) == "table" then m.meta else {} + m.meta.container = { format = "umx", name = e.name, version = h.version, count = #list } + return m, nil +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 + return nil, err + end + return Tracker.render(m, opts) +end + +return Umx diff --git a/src/Formats/music/xm/init.luau b/src/Formats/music/xm/init.luau index 080795c..cab28dd 100644 --- a/src/Formats/music/xm/init.luau +++ b/src/Formats/music/xm/init.luau @@ -5,13 +5,15 @@ -- delta samples, multi-sample instruments with volume / panning envelopes, fadeout and auto-vibrato, linear and Amiga -- frequency tables, every FT2 effect and volume-column command. Writes XM from "xm" modules (byte-identical for files -- in FT2's layout) and from "mod" modules (one instrument per sample, Amiga frequencies). --- Not supported: ModPlug ADPCM samples (read as silence), OpenMPT's stereo-sample / extra-effect extensions on write. +-- ModPlug ADPCM samples decode (codecs/audio/Adpcm; written back as plain delta PCM). Not supported: OpenMPT's +-- stereo-sample / extra-effect extensions on write. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Tracker = require("@formats/codecs/audio/Tracker") +local Adpcm = require("@formats/codecs/audio/Adpcm") -- ------------------------------------------------------------------------------------------------ contract local Xm = { @@ -19,7 +21,7 @@ local Xm = { category = "music", extensions = { "xm" }, mime = { "audio/xm", "audio/x-xm" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Adpcm" }, caps = { decode = true, encode = true, render = true, channels = { 1, 64 } }, } @@ -240,12 +242,19 @@ function Xm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) s.relativeNote = h.rel s.pan = h.pan local frames = h.len // bps - if h.res == 0xAD then - -- ModPlug ADPCM: 16-byte table + 4 bits per sample (not decoded: silence of the right length) - local bytes = 16 + (h.len + 1) // 2 - r:skip(math.min(bytes, r:remaining())) - frames = h.len + 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 + frames = math.max(0, math.min(h.len, (r:remaining() - 16) * 2)) + total += frames * 4 + if total > maxBytes then + return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit") + end s.data = buffer.create(frames * 4) + if frames > 0 then + Adpcm.modplug(r.buf, r.pos, frames, s.data, 0) + end + r:skip(math.min(16 + (h.len + 1) // 2, r:remaining())) else local avail = r:remaining() // bps local got = math.min(frames, avail) diff --git a/src/Formats/music/xmi/init.luau b/src/Formats/music/xmi/init.luau new file mode 100644 index 0000000..0d18f74 --- /dev/null +++ b/src/Formats/music/xmi/init.luau @@ -0,0 +1,215 @@ +--!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. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Chunks = require("@formats/containers/Chunks") +local Render = require("@formats/codecs/audio/MidiRender") + +-- ------------------------------------------------------------------------------------------------ contract +local Xmi = { + name = "xmi", + category = "music", + extensions = { "xmi", "xmidi" }, + mime = { "audio/x-xmidi" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/audio/MidiRender" }, + caps = { decode = true, encode = false, render = true, songs = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + track: number?, -- the song (1-based), default 1 + maxEvents: number?, -- default 2^24 +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Xmi.sniff(r: Bytes.Reader): number + local id, kind = r:peek(4), r:peek(4, 8) + if id == "FORM" and (kind == "XDIR" or kind == "XMID") then + return 1 + end + return if id == "CAT " and kind == "XMID" then 0.9 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +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 + if p >= e then + return nil, p + end + local c = readu8(b, p) + p += 1 + v = v * 128 + c % 128 + if c < 128 then + return v, p + end + end + return nil, p +end + +local function bytes(b: buffer, p: number, n: number): { number } + local t: { number } = table.create(n) :: { number } + for i = 1, n do + t[i] = readu8(b, p + i - 1) + end + 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 + while p < e do + local st = readu8(b, p) + p += 1 + if st < 0x80 then + tick += st + elseif st == 0xFF then + if p >= e then + return nil, "truncated meta event" + end + local kind = readu8(b, p) + local n, q = vlq(b, p + 1, e) + if not n or q + n > e then + return nil, "truncated meta event" + end + if kind == 0x2F then + break + elseif kind == 0x51 and n >= 3 then + tempo = tempo or readu8(b, q) * 65536 + readu8(b, q + 1) * 256 + readu8(b, q + 2) + else + table.insert(list, { tick = tick, type = "meta", meta = kind, data = bytes(b, q, n) }) + end + p = q + n + elseif st == 0xF0 or st == 0xF7 then + local n, q = vlq(b, p, e) + if not n or q + n > e then + return nil, "truncated sysex" + end + table.insert(list, { tick = tick, type = if st == 0xF0 then "sysex" else "escape", data = bytes(b, q, n) }) + p = q + n + elseif st < 0xF0 then + local hi, ch = st // 16, st % 16 + local n = DATA[hi] + if p + n > e then + return nil, "truncated event" + end + local d = bytes(b, p, n) + p += n + table.insert(list, { tick = tick, type = TYPES[hi], channel = ch, data = d }) + if hi == 9 then + local dur, q = vlq(b, p, e) + if not dur then + return nil, "truncated note duration" + end + p = q + table.insert(offs, { tick = tick + dur, onTick = tick, ev = { tick = tick + dur, type = "noteOff", channel = ch, data = { d[1] % 128, 64 } } }) + end + else + return nil, string.format("unexpected status byte 0x%02X", st) + end + if #list + #offs > maxEvents then + return nil, "limit: more than " .. maxEvents .. " events" + end + end + -- the sequence stops at its end-of-track event: notes still sounding end there (wildmidi leaves them hanging) + for _, o in offs do + if o.tick > tick then + o.tick = tick + o.ev.tick = tick + end + end + 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) + local song = {} + for _, s in Chunks.walk(b, c.offset + 4, c.offset + c.avail, Chunks.IFF) do + song[s.id] = song[s.id] or s + end + if song.EVNT then + table.insert(out, song) + end + end + for _, c in Chunks.walk(b, base, limit, Chunks.IFF) do + local kind = if c.avail >= 4 then buffer.readstring(b, c.offset, 4) else "" + if c.id == "FORM" and kind == "XMID" then + form(c) + elseif c.id == "CAT " and kind == "XMID" then + for _, s in Chunks.walk(b, c.offset + 4, c.offset + c.avail, Chunks.IFF) do + if s.id == "FORM" and s.avail >= 4 and buffer.readstring(b, s.offset, 4) == "XMID" then + form(s) + end + end + end + end + return out +end + +function Xmi.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Midi?, Err.Err?) + local o: DecodeOptions = opts or {} + if Xmi.sniff(r) == 0 then + return nil, Err.new(Err.CORRUPT, "not an XMIDI file") + end + local list = songs(r.buf, r.base, r.limit) + local index = o.track or 1 + if #list == 0 then + return nil, Err.new(Err.CORRUPT, "no XMID song with an EVNT chunk") + elseif type(index) ~= "number" or index < 1 or index > #list or index % 1 ~= 0 then + return nil, Err.new(Err.ARG, string.format("track must be 1..%d", #list)) + end + local song = list[index] + local ev = song.EVNT + local evs, endTick, tempo = events(r.buf, ev.offset, ev.offset + ev.avail, o.maxEvents or 2 ^ 24) + if not evs then + return nil, Err.from(endTick :: string, ev.offset) + end + local last = math.max(endTick :: number, if #evs > 0 then evs[#evs].tick else 0) + table.insert(evs, 1, { tick = 0, type = "meta", meta = 0x51, data = Render.tempoBytes(60, 120) }) + table.insert(evs, { tick = last, type = "meta", meta = 0x2F, data = {} }) + local timbres = {} + local tb = song.TIMB + if tb and tb.avail >= 2 then + for i = 0, math.min(buffer.readu16(r.buf, tb.offset), (tb.avail - 2) // 2) - 1 do + table.insert(timbres, { patch = readu8(r.buf, tb.offset + 2 + i * 2), bank = readu8(r.buf, tb.offset + 3 + i * 2) }) + end + end + local rb = song.RBRN + local branches = if rb and rb.avail >= 2 then buffer.readu16(r.buf, rb.offset) else 0 + local midi = Types.Midi.new(60) + midi.format = 0 + midi.tracks = { { events = evs } } + Render.attach(midi, { format = "xmi", songs = #list, song = index, timbres = timbres, tempo = tempo, branches = branches }) + midi.meta.truncated = ev.truncated + return midi, nil +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 + return nil, err + end + return Render.decoder(midi, opts) +end + +return Xmi diff --git a/src/Formats/ops/MusicOps.luau b/src/Formats/ops/MusicOps.luau index 1d1cae0..8afd0d3 100644 --- a/src/Formats/ops/MusicOps.luau +++ b/src/Formats/ops/MusicOps.luau @@ -27,7 +27,8 @@ local function bad(what: string): (nil, Err.Err) end local function isModule(m: any): boolean - return type(m) == "table" and m.kind == "music" and FORMATS[m.format] == true and type(m.patterns) == "table" + -- (the engine family: modules of the other tracker formats, music/mtm etc., play as one of the four) + return type(m) == "table" and m.kind == "music" and FORMATS[Tracker.family(m) or ""] == true and type(m.patterns) == "table" end local function int(v: any, lo: number, hi: number): boolean @@ -243,7 +244,7 @@ function MusicOps.addSample(m: any, spec: SampleSpec): (number?, Err.Err?) local copy = buffer.create(length * channels * 4) buffer.copy(copy, 0, data, 0, length * channels * 4) s.data, s.length, s.channels = copy, length, channels - s.bits = spec.bits or (if m.format == "mod" then 8 else 16) + s.bits = spec.bits or (if Tracker.family(m) == "mod" then 8 else 16) if s.bits ~= 8 and s.bits ~= 16 then return bad("addSample: bits must be 8 or 16") end @@ -298,7 +299,7 @@ function MusicOps.addInstrument(m: any, spec: InstrumentSpec): (number?, Err.Err if not isModule(m) then return bad("addInstrument: needs a tracker Module") end - if m.format ~= "xm" and m.format ~= "it" then + if Tracker.family(m) ~= "xm" and Tracker.family(m) ~= "it" then return bad("addInstrument: only xm and it modules have instruments (mod / s3m cells name samples)") end if type(spec) ~= "table" then diff --git a/tests/audio/_adpcm.luau b/tests/audio/_adpcm.luau new file mode 100644 index 0000000..1f61f2c --- /dev/null +++ b/tests/audio/_adpcm.luau @@ -0,0 +1,59 @@ +-- tests/audio/_adpcm: shared checks of the ADPCM game-audio formats (adx, vag, brstm): a file against the reference +-- decoder's s16le output, bit-exact, through decode() and through open() with seeks (forward into unvisited packets, +-- back, the end), loop points; the SNR of an encoder's round trip. +local Bytes = require("@formats/core/Bytes") + +local H = {} + +-- same(f32 buffer, s16le reference buffer, first reference sample, count) -> true when every sample is equal +function H.same(out: buffer, ref: buffer, from: number, count: number): boolean + for i = 0, count - 1 do + if buffer.readf32(out, i * 4) * 32768 ~= buffer.readi16(ref, (from + i) * 2) then + return false + end + end + return true +end + +function H.snr(x: buffer, y: buffer, count: number): number + local sig, err = 0, 0 + for i = 0, count - 1 do + local a = buffer.readf32(x, i * 4) + local e = a - buffer.readf32(y, i * 4) + sig += a * a + err += e * e + end + return if err == 0 then 200 else 10 * math.log10(sig / err) +end + +-- check(t, Fmt, c, opts?): c = { name, data, rate, ch, frames?, ref, loopStart?, loopEnd? } +function H.check(t: any, Fmt: any, c: any, opts: any?) + local ref = buffer.fromstring(c.ref) + local frames = buffer.len(ref) // (2 * c.ch) + local a, err = Fmt.decode(Bytes.reader(buffer.fromstring(c.data)), opts) + t:check(a, c.name .. ": decode: " .. tostring(err)) + if not a then + return + end + t:eq(a.frames, frames, c.name .. ": frames") + t:eq(a.channels, c.ch, c.name .. ": channels") + t:eq(a.sampleRate, c.rate, c.name .. ": rate") + t:check(H.same(a.samples, ref, 0, frames * c.ch), c.name .. ": bit-exact with the reference") + t:eq(a.meta.source.format, Fmt.name, c.name .. ": meta.source.format") + if c.loopStart then + local l = a.meta.source.loop + t:check(l and l.start == c.loopStart and l.stop == c.loopEnd, c.name .. ": loop " .. tostring(l and l.start) .. " " .. tostring(l and l.stop)) + else + t:eq(a.meta.source.loop, nil, c.name .. ": no loop") + end + -- open: seek forward first (unvisited packets), then back, then the end + local dec = Fmt.open(Bytes.reader(buffer.fromstring(c.data)), opts) :: any + for _, f in { frames * 3 // 4, 5, frames // 2 + 13, frames - 2, 0, 4097 } do + f = math.min(f, frames) + dec:seek(f / c.rate) + local b, n = dec:read(50) + t:check(n == math.min(50, frames - f) and H.same(b, ref, f * c.ch, n * c.ch), c.name .. ": seek to " .. f) + end +end + +return H diff --git a/tests/audio/_lossless.luau b/tests/audio/_lossless.luau new file mode 100644 index 0000000..77174b7 --- /dev/null +++ b/tests/audio/_lossless.luau @@ -0,0 +1,136 @@ +-- Shared checks of the lossless audio format tests (wavpack, ape, tta): every fixture opened, decoded bit-exact +-- against the reference decoder's samples (readInt for integer streams, the f32 bytes for float ones), f32 scaling +-- and output reuse, seeking to sample-accurate positions, reading past the end, tags, sniff. A fixture is a table +-- { name, data, rate, channels, bits, float, frames, crc, tags?, partial? } (partial: a cut file whose decode stops +-- with an error; the reference decoded its first `frames` frames). +local T = require("@tests/T") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") + +local L = {} + +local f32buf = buffer.create(4) +local function f32(x: number): number + buffer.writef32(f32buf, 0, x) + return buffer.readf32(f32buf, 0) +end + +local function open(mod: any, b: any, opts: any?): (any, any) + return mod.open(Bytes.reader(if type(b) == "string" then buffer.fromstring(b) else b), opts) +end +L.open = open + +-- all(dec, fx) -> crc of every sample read (i32 for integer streams, f32 bytes for floats), frames, the values +function L.all(dec: any, fx: any): (number, number, { number }) + local ch = dec.channels + local vals = table.create(fx.frames * ch, 0) + local crc, n, k = 0, 0, 0 + local sizes = { 4096, 1, 777, 10000, 3 } + while true do + k += 1 + local out, got + if fx.float then + out, got = dec:read(sizes[k % #sizes + 1]) + else + out, got = dec:readInt(sizes[k % #sizes + 1]) + end + if got == 0 then + break + end + if fx.partial then -- a cut file: the reference decoded fx.frames (whole frames); the rest may decode too + got = math.min(got, fx.frames - n) + if got <= 0 then + continue + end + end + crc = Crc32.of(out, 0, got * ch * 4, crc) + for i = 0, got * ch - 1 do + vals[n * ch + i + 1] = if fx.float then buffer.readf32(out, i * 4) else buffer.readi32(out, i * 4) + end + n += got + end + return crc, n, vals +end + +-- cases(t, mod, cases, optsOf?) -> seeks checked: the per-fixture checks; optsOf(fx) gives the open options +function L.cases(t: any, mod: any, cases: { any }, optsOf: ((any) -> any)?): number + local seekChecks = 0 + for _, fx in cases do + local name = fx.name + local dec, err = open(mod, fx.data, optsOf and optsOf(fx)) + t:check(dec, name .. ": open: " .. tostring(err)) + t:check(dec.sampleRate == fx.rate and dec.channels == fx.channels, name .. ": format") + if not fx.partial then + t:eq(dec.frames, fx.frames, name .. ": frames") + t:check(math.abs(dec.duration - fx.frames / fx.rate) < 1e-9, name .. ": duration") + end + t:eq(dec.float, fx.float, name .. ": float") + local crc, n, vals = L.all(dec, fx) + if fx.partial then + t:check(dec.error ~= nil, name .. ": the cut frame is reported") + else + t:eq(dec.error, nil, name .. ": no decode error") + end + t:eq(n, fx.frames, name .. ": decoded frames") + t:eq(crc, fx.crc, name .. ": samples identical to the reference decoder") + -- f32 scaling, output reuse + local ch = dec.channels + dec:seek(0) + local reuse = buffer.create(100 * ch * 4) + local f, gotf = dec:read(100, reuse) + t:check(f == reuse, name .. ": output buffer reused") + local scale = if fx.float then 1 else 2 ^ ((fx.container or fx.bits) - 1) + local bad = 0 + for i = 0, math.min(gotf, 100) * ch - 1 do + if buffer.readf32(f, i * 4) ~= f32(vals[i + 1] / scale) then + bad += 1 + end + end + t:eq(bad, 0, name .. ": f32 samples") + -- seeking (sample-accurate: seek(s / rate) lands on frame s) + local last = if fx.partial then fx.frames - 50 else fx.frames + local rand = T.rng(7) + local targets = { 0, 1, last - 1, last // 2, 22050, 22049, 73729, 73727 } + for _ = 1, 6 do + table.insert(targets, rand(math.max(last, 1))) + end + for _, s in targets do + if s >= 0 and s < last then + dec:seek(s / fx.rate) + t:check(math.abs(dec:position() * fx.rate - s) < 1e-6, name .. ": position after seek " .. s) + local out, got = dec:read(50) + t:eq(got, math.min(50, fx.frames - s), name .. ": read after seek " .. s) + local diff = 0 + for i = 0, got * ch - 1 do + if buffer.readf32(out, i * 4) ~= f32(vals[s * ch + i + 1] / scale) then + diff += 1 + end + end + t:eq(diff, 0, name .. ": samples after seek " .. s) + seekChecks += 1 + end + end + dec:seek(dec.duration + 5) + t:eq(select(2, dec:read(10)), 0, name .. ": read past the end") + for key, v in fx.tags or {} do + t:eq(dec.tags[key], v, name .. ": tag " .. key) + end + t:eq(mod.sniff(Bytes.reader(buffer.fromstring(fx.data))), 1, name .. ": sniff") + end + return seekChecks +end + +-- subrange(t, mod, fx, depth) : decode() from a Reader over a sub-range equals read(); meta.source +function L.subrange(t: any, mod: any, fx: any, format: string) + local name = fx.name + local big = buffer.create(#fx.data + 13) + buffer.writestring(big, 6, fx.data) + local a, err = mod.decode(Bytes.reader(big, 6, #fx.data)) + t:check(a and a.kind == "audio" and a.frames == fx.frames and a.channels == fx.channels, name .. ": decode: " .. tostring(err)) + local ref = open(mod, fx.data):read(fx.frames) + t:check(buffer.tostring(ref) == buffer.tostring(a.samples), name .. ": decode = read") + t:eq(a.meta.source.format, format, name .. ": meta.source") + t:eq(a.meta.source.bitDepth, if fx.float then 32 else fx.bits, name .. ": bit depth") +end + +return L diff --git a/tests/audio/ac3.luau b/tests/audio/ac3.luau new file mode 100644 index 0000000..7b67ca4 --- /dev/null +++ b/tests/audio/ac3.luau @@ -0,0 +1,155 @@ +-- audio/ac3 tests: AC-3 streams from ffmpeg (every acmod with and without LFE, coupling incl. cplbegf 0, rematrixing, +-- 32 / 44.1 / 48 kHz) and aften (block switching, 1+1 dual mono, dynamic range profiles, the alternate BSI) against +-- ffmpeg's float decode, or liba52's for block-switched streams (SNR, max difference; dithflags cleared in the +-- fixture step so both sides decode the same numbers); dynamic range on; the encoders' dithered originals; AC-3 tracks +-- of MKV / MP4 / MPEG-TS / AVI through the api's audio hook; exact seeking; resync and truncation; error codes (E-AC-3, +-- CRC); the fuzz no-throw pass. Fixtures: tools/fixtures/ac3.py. +local T = require("@tests/T") +local F = require("@formats") +local Ac3F = require("@formats/audio/ac3") +local Ac3 = require("@formats/codecs/audio/Ac3") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/ac3_cases") +local Tracks = require("@tests/gen/ac3_tracks") + +local t = T.suite("ac3") + +local function reader(s: string): Bytes.Reader + return Bytes.reader(buffer.fromstring(s)) +end + +-- SNR (dB) and the largest difference of interleaved f32 `got` against the f32le reference `ref` +local function compare(got: buffer, ref: string, count: number): (number, number) + local rb = buffer.fromstring(ref) + local n = math.min(count, #ref // 4, buffer.len(got) // 4) + local sig, err, maxd = 0, 0, 0 + for i = 0, n - 1 do + local r = buffer.readf32(rb, i * 4) + local d = buffer.readf32(got, i * 4) - r + sig += r * r + err += d * d + maxd = math.max(maxd, math.abs(d)) + end + return if err == 0 then math.huge else 10 * math.log10(sig / err), maxd +end + +t:eq(Ac3F.name, "ac3", "name") +t:check(Ac3F.caps.decode and not Ac3F.caps.encode and Ac3F.encode == nil, "caps: decode only") + +local byName = {} +for _, c in Fx do + byName[c.name] = c + local r = reader(c.data) + t:check(Ac3F.sniff(r) >= 0.9, c.name .. ": sniff") + local a, err = Ac3F.decode(r) + t:check(a, c.name .. ": " .. tostring(err)) + if not a then + continue + end + t:check(a.channels == c.channels and a.sampleRate == c.rate, c.name .. ": format") + t:eq(a.frames, c.frames, c.name .. ": frames") + -- liba52's 6-channel output is 16-bit + local min = if c.refTool == "a52dec" and c.channels > 2 then 80 else 95 + local s, maxd = compare(a.samples, c.ref, a.frames * a.channels) + t:check(s > min, string.format("%s: SNR %.1f dB vs %s", c.name, s, c.refTool)) + t:note("%s: %d ch %d Hz, %d frames: SNR %.1f dB, max diff %.1e vs %s", c.name, a.channels, a.sampleRate, a.frames, s, maxd, c.refTool) + if c.refDrc then + local d = Ac3F.decode(r, { drc = 1 }) :: any + local sd = compare(d.samples, c.refDrc, d.frames * d.channels) + t:check(sd > min, string.format("%s: dynamic range on: SNR %.1f dB vs %s", c.name, sd, c.refTool)) + local off = compare(d.samples, c.ref, d.frames * d.channels) + t:check(off < 40, c.name .. ": the dynamic range gains change the output") + end + if c.dithered then + -- the encoder's own stream (dithflag set): our dither against the reference's undithered decode + local dd = Ac3F.decode(reader(c.dithered)) :: any + local sd = compare(dd.samples, c.ref, dd.frames * dd.channels) + t:check(dd and sd > 10, string.format("%s: dithered original decodes (SNR %.1f dB, the dither noise)", c.name, sd)) + end +end + +-- AC-3 tracks of video containers, through the api's audio hook (containers/AudioWrap -> audio/ac3) +for _, c in Tracks do + local v, err = F.video.open(buffer.fromstring(c.data)) + t:check(v, c.name .. ": open: " .. tostring(err)) + if not v then + continue + end + t:check(v.audio, c.name .. ": audio track opens: " .. tostring(v.audioError)) + if v.audio then + local a = assert(F.ops.audio.toAudio(v.audio)) + t:check(a.channels == c.channels and a.sampleRate == c.rate, c.name .. ": audio format") + local s = compare(a.samples, c.ref, a.frames * a.channels) + t:check(s > 95, string.format("%s: AC-3 track SNR %.1f dB vs ffmpeg", c.name, s)) + t:note("%s: AC-3 track, %d ch, %d frames, SNR %.1f dB", c.name, a.channels, a.frames, s) + end +end + +-- streaming + exact seeking (one frame of pre-roll for the overlap) +do + local c = byName["5.1_448"] + local whole = Ac3F.decode(reader(c.data)) :: any + local dec = Ac3F.open(reader(c.data)) :: any + local _ = dec:read(3000) + for _, at in { 0.1, 0.0, 0.0517 } do + dec:seek(at) + local b, n = dec:read(700) + local f0 = math.floor(at * c.rate + 0.5) + local maxd = 0 + for i = 0, n * 6 - 1 do + maxd = math.max(maxd, math.abs(buffer.readf32(b, i * 4) - buffer.readf32(whole.samples, (f0 * 6 + i) * 4))) + end + t:check(n == 700 and maxd < 1e-6, string.format("seek %.4f s (max diff %g)", at, maxd)) + end +end + +-- resync over garbage, a truncated last frame, the raw codec API +do + local c = byName.stereo_44k + local a = Ac3F.decode(reader("\0\11\119garbage" .. c.data)) :: any + t:check(a and a.frames == c.frames, "garbage in front: same frames") + local h = Ac3.header(buffer.fromstring(c.data), 0, #c.data) :: Ac3.Header + t:check(h.sampleRate == 44100 and h.channels == 2 and h.acmod == 2 and h.bitrate == 192000, "header fields") + local cut = Ac3F.decode(reader(string.sub(c.data, 1, #c.data - 10))) :: any + t:check(cut and cut.frames == c.frames - 1536, "truncated last frame dropped") + local d = Ac3.decoder() + local n = d:decode(buffer.fromstring(c.data), 0, h.frameSize) + t:check(n == 1536 and d.channels == 2 and #d.pcm == 1536 * 2, "decoder: one syncframe") +end + +-- errors +do + local c = byName.stereo_44k.data + t:eq(Ac3F.sniff(reader("RIFF....WAVE")), 0, "sniff a WAV") + local _, e = Ac3F.decode(reader(string.rep("\0", 100))) + t:check(e and e.code == Err.CORRUPT, "no frames: " .. tostring(e)) + -- an E-AC-3 header: bsid 16, frmsiz 255 (512 bytes), then the same again + local eac3 = "\11\119\0\255\128\128" .. string.rep("\0", 506) + _, e = Ac3F.decode(reader(eac3 .. eac3)) + t:check(e and e.code == Err.UNSUPPORTED, "E-AC-3: " .. tostring(e)) + local _, fe = F.audio.load(buffer.fromstring(eac3 .. eac3)) + t:check(fe and fe.code == Err.UNSUPPORTED, "E-AC-3 through the api: " .. tostring(fe)) + -- a flipped bit in the middle of the first frame: the CRC catches it + local bad = string.sub(c, 1, 300) .. string.char(bit32.bxor(string.byte(c, 301), 4)) .. string.sub(c, 302) + _, e = Ac3F.decode(reader(bad)) + t:check(e and e.code == Err.CHECKSUM, "CRC: " .. tostring(e)) + _, e = Ac3F.decode(reader(c), { maxFrames = 2 }) + t:check(e and e.code == Err.LIMIT, "maxFrames: " .. tostring(e)) +end + +-- fuzz (without the CRC check, so mutations reach the decoder) +do + local samples = {} + for _, c in Fx do + table.insert(samples, string.sub(c.data, 1, 4000)) + end + t:fuzz("decode", function(b: buffer) + return Ac3F.decode(Bytes.reader(b), { crc = false }) + end, samples, { mutations = 25 }) + t:fuzz("decode (crc)", function(b: buffer) + return Ac3F.decode(Bytes.reader(b)) + end, samples, { mutations = 4, garbage = 20 }) +end + +t:done() diff --git a/tests/audio/adpcm.luau b/tests/audio/adpcm.luau new file mode 100644 index 0000000..bf3ca90 --- /dev/null +++ b/tests/audio/adpcm.luau @@ -0,0 +1,127 @@ +-- audio/adpcm tests: headerless streams (IMA nibbles, IMA WAV / MS blocks, Apple ima4, PS-ADPCM) decoded with the +-- layout in the options, bit-exact against ffmpeg / vgmstream (tools/fixtures/adpcm.py), with seeking; our encoder's +-- streams (ima, ms, ima_wav) as ffmpeg decodes them (wrapped in KVAG / WAV in the fixture step) against our decode of +-- the same bytes, and their quality; options and errors; the api by format name; the fuzz pass. +local T = require("@tests/T") +local Raw = require("@formats/audio/adpcm") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local F = require("@formats") +local Cases = require("@tests/gen/adpcm_raw") +local Ours = require("@tests/gen/adpcm_ours") +local Sig = require("@tests/gen/adpcm_sig") + +local t = T.suite("adpcm") + +t:eq(Raw.name, "adpcm", "name") +t:check(Raw.caps.decode and Raw.caps.encode and Raw.open ~= nil, "caps") +t:eq(Raw.sniff(Bytes.reader(buffer.fromstring("RIFF....WAVE"))), 0, "sniff is always 0") + +local function same(out: buffer, ref: buffer, from: number, count: number): boolean + for i = 0, count - 1 do + if buffer.readf32(out, i * 4) * 32768 ~= buffer.readi16(ref, (from + i) * 2) then + return false + end + end + return true +end + +local samples = {} +for _, c in Cases do + table.insert(samples, c.data) + local opts = { codec = c.codec, sampleRate = c.rate, channels = c.ch, blockAlign = c.blockAlign } + local ref = buffer.fromstring(c.ref) + local frames = buffer.len(ref) // (2 * c.ch) + local a, err = Raw.decode(Bytes.reader(buffer.fromstring(c.data)), opts) + t:check(a, c.name .. ": " .. tostring(err)) + t:eq(a.frames, frames, c.name .. ": frames") + t:check(same(a.samples, ref, 0, frames * c.ch), c.name .. ": bit-exact") + t:eq(a.meta.source.codec, c.codec, c.name .. ": meta.source.codec") + local dec = Raw.open(Bytes.reader(buffer.fromstring(c.data)), opts) :: any + for _, f in { frames // 2, 7, frames - 3, 1000, 0 } do + dec:seek(f / c.rate) + local b, n = dec:read(40) + t:check(n == math.min(40, frames - f) and same(b, ref, f * c.ch, n * c.ch), c.name .. ": seek to " .. f) + end +end +t:note("%d raw streams bit-exact with ffmpeg / vgmstream", #Cases) + +-- ------------------------------------------------------------------------------------------------ encoder +local function snr(x: buffer, y: buffer, count: number): number + local sig, err = 0, 0 + for i = 0, count - 1 do + local a = buffer.readf32(x, i * 4) + local e = a - buffer.readf32(y, i * 4) + sig += a * a + err += e * e + end + return if err == 0 then 200 else 10 * math.log10(sig / err) +end + +local audio = Types.Audio.new(Sig.rate, Sig.channels, Sig.frames) +buffer.writestring(audio.samples, 0, Sig.data) +for _, c in Ours do + local opts = (if c.name == "ima" then { codec = "ima" } else { codec = c.name, blockAlign = 512 }) :: any + opts.channels, opts.sampleRate = 2, Sig.rate + local out, err = Raw.encode(audio, opts) + t:check(out and buffer.tostring(out) == c.data, c.name .. ": encode is deterministic: " .. tostring(err)) + local ref = buffer.fromstring(c.ref) + local back = Raw.decode(Bytes.reader(buffer.fromstring(c.data)), opts) :: any + local n = buffer.len(ref) // 4 + t:eq(back.frames, n, c.name .. ": ffmpeg and we decode as many frames") + t:check(same(back.samples, ref, 0, n * 2), c.name .. ": ffmpeg decodes our stream as we do") + local s = snr(audio.samples, back.samples, Sig.frames * 2) + t:check(s > 20, string.format("%s: %.1f dB", c.name, s)) + t:note("encode %s: %.1f dB", c.name, s) + -- from a streaming Decoder too + local again = Raw.encode(Raw.open(Bytes.reader(out :: buffer), opts) :: any, opts) + t:check(again ~= nil, c.name .. ": encode from a Decoder") +end +do + local _, e1 = Raw.encode(audio, { codec = "psx" } :: any) + t:check(e1 and e1.code == Err.ARG, "encode psx: ARG") + local _, e2 = Raw.encode(audio, { codec = "ms", blockAlign = 8 }) + t:check(e2 and e2.code == Err.ARG, "encode: tiny blockAlign") + local _, e3 = Raw.encode(audio, { codec = "ima_wav", blockAlign = 514 }) + t:check(e3 and e3.code == Err.ARG, "encode ima_wav: blockAlign not a multiple of 4 * channels") + local _, e4 = Raw.encode({} :: any) + t:check(e4 and e4.code == Err.ARG, "encode {}") + local _, e5 = Raw.open(Bytes.reader(buffer.create(10)), { codec = "dsp" } :: any) + t:check(e5 and e5.code == Err.ARG, "open: unknown codec") + local _, e6 = Raw.open(Bytes.reader(buffer.create(10)), { channels = 0 }) + t:check(e6 and e6.code == Err.ARG, "open: 0 channels") + local _, e7 = Raw.open(Bytes.reader(buffer.create(10)), { codec = "ms", channels = 2, blockAlign = 9 }) + t:check(e7 and e7.code == Err.CORRUPT, "open: block too small") + local _, e8 = Raw.decode(Bytes.reader(buffer.create(100)), { maxFrames = 10 }) + t:check(e8 and e8.code == Err.LIMIT, "maxFrames") + local lo = Raw.decode(Bytes.reader(buffer.fromstring("\1\2\3")), { lowFirst = true }) :: any + local hi = Raw.decode(Bytes.reader(buffer.fromstring("\16\32\48"))) :: any + t:check(lo.frames == 6 and buffer.tostring(lo.samples) == buffer.tostring(hi.samples), "nibble order") +end + +-- ------------------------------------------------------------------------------------------------ api +do + local c = Cases[1] + local a, err = F.audio.load(c.data, { format = "adpcm", codec = c.codec, sampleRate = c.rate, channels = c.ch }) + t:check(a and a.frames == buffer.len(buffer.fromstring(c.ref)) // (2 * c.ch), "F.audio.load by format: " .. tostring(err)) + t:eq(F.detect(c.data, { name = "sound.ima" }), "adpcm", "F.detect by extension") + local out = F.save(a, nil, { format = "adpcm", codec = "ms" }) + t:check(out ~= nil and buffer.len(out) % 256 == 0, "F.save adpcm") +end + +-- ------------------------------------------------------------------------------------------------ fuzz +local kinds = { "ima", "ima_wav", "ms", "ima_qt", "psx" } +local k = 0 +t:fuzz("open + read + seek", function(b: buffer) + k += 1 + local dec = Raw.open(Bytes.reader(b), { codec = kinds[k % 5 + 1] :: any, channels = k % 3 + 1, blockAlign = 64 + k % 7 * 4, interleave = 32 }) + if dec then + dec:read(100000) + dec:seek(dec.duration / 3) + dec:read(77) + end + return dec +end, samples, { mutations = 6 }) + +t:done() diff --git a/tests/audio/adx.luau b/tests/audio/adx.luau new file mode 100644 index 0000000..aa8b480 --- /dev/null +++ b/tests/audio/adx.luau @@ -0,0 +1,90 @@ +-- audio/adx tests: ffmpeg's ADX files (version 3) and a version 4 file with history and loop points, bit-exact with +-- vgmstream (tools/fixtures/adx.py) through decode and open with seeks; our encoder's files as vgmstream decodes them +-- (equal to our decode, loops reported) and their quality; header errors; the api; the fuzz pass. +local T = require("@tests/T") +local Adx = require("@formats/audio/adx") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local F = require("@formats") +local H = require("@tests/audio/_adpcm") +local Cases = require("@tests/gen/adx_cases") +local Ours = require("@tests/gen/adx_ours") +local Sig = require("@tests/gen/adx_sig") + +local t = T.suite("adx") +t:eq(Adx.name, "adx", "name") +t:check(Adx.caps.decode and Adx.caps.encode, "caps") + +local samples = {} +for _, c in Cases do + table.insert(samples, c.data) + t:eq(Adx.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, c.name .. ": sniff") + H.check(t, Adx, c) +end +t:note("%d files bit-exact with vgmstream", #Cases) + +-- ------------------------------------------------------------------------------------------------ encoder +local audio = Types.Audio.new(Sig.rate, Sig.channels, Sig.frames) +buffer.writestring(audio.samples, 0, Sig.data) +for _, c in Ours do + H.check(t, Adx, c) + local a = Adx.decode(Bytes.reader(buffer.fromstring(c.data))) :: any + local s = H.snr(audio.samples, a.samples, Sig.frames * Sig.channels) + t:check(s > 22, string.format("ours %s: %.1f dB", c.name, s)) + t:note("encode %s: %.1f dB", c.name, s) + -- deterministic, and the same from a streaming Decoder; the loop is kept through a re-encode + local again = Adx.encode(a) + local back = Adx.decode(Bytes.reader(again :: buffer)) :: any + t:check(back and (c.loopStart == nil or (back.meta.source.loop.start == c.loopStart)), c.name .. ": loop kept on re-encode") +end +do + local out = Adx.encode(audio, { loop = { start = 1000, stop = 8000 } }) + t:check(out and buffer.tostring(out) == Ours[2].data, "encode is deterministic") + local _, e1 = Adx.encode(audio, { loop = { start = 10, stop = 5 } }) + t:check(e1 and e1.code == Err.ARG, "bad loop") + local _, e2 = Adx.encode(Types.Audio.new(8000, 9, 10)) + t:check(e2 and e2.code == Err.ARG, "9 channels") + local _, e3 = Adx.encode(audio, { cutoff = 1e6 }) + t:check(e3 and e3.code == Err.ARG, "bad cutoff") +end + +-- ------------------------------------------------------------------------------------------------ errors +do + local base = Cases[1].data + local function patch(at: number, bytes: string): buffer + local b = buffer.fromstring(base) + buffer.writestring(b, at, bytes) + return b + end + local function fails(b: buffer, code: string, label: string) + local d, e = Adx.open(Bytes.reader(b)) + t:check(d == nil and e and e.code == code, label .. ": " .. tostring(e)) + end + fails(patch(0x12, "\4\9"), Err.UNSUPPORTED, "encrypted") + fails(patch(0x04, "\4"), Err.UNSUPPORTED, "exponential type") + fails(patch(0x04, "\17"), Err.UNSUPPORTED, "AHX") + fails(patch(0x07, "\0"), Err.CORRUPT, "0 channels") + fails(patch(0x12, "\6\0"), Err.UNSUPPORTED, "version 6") + fails(buffer.fromstring("not adx at all"), Err.CORRUPT, "not adx") + t:eq(F.detect(base), "adx", "F.detect") + local a = F.audio.load(base) + t:check(a and a.frames == Cases[1].frames, "F.audio.load") + local out = F.save(a, nil, { format = "adx" }) + t:check(out and F.detect(out) == "adx", "F.save adx") +end + +t:fuzz("open + read + seek", function(b: buffer) + local dec = Adx.open(Bytes.reader(b)) + if dec then + dec:read(100000) + dec:seek(dec.duration / 2) + dec:read(33) + end + return dec +end, samples, { mutations = 10 }) +t:fuzz("header", function(b: buffer) + return Adx.decode(Bytes.reader(b)) +end, samples, { mutations = 10, keepHeader = 0, garbage = 50 }) + +t:done() diff --git a/tests/audio/aiff.luau b/tests/audio/aiff.luau index 079f34a..52b4609 100644 --- a/tests/audio/aiff.luau +++ b/tests/audio/aiff.luau @@ -1,5 +1,5 @@ -- audio/aiff tests: files written by ffmpeg and sox in every sample format (AIFF 8 / 12 / 16 / 24 / 32-bit, AIFF-C --- sowt / fl32 / fl64 / ulaw / alaw, 6 channels, text chunks) against ffmpeg's decode; streaming reads and seeks; +-- sowt / fl32 / fl64 / ulaw / alaw / ima4, 6 channels, text chunks) against ffmpeg's decode; streaming reads and seeks; -- our encoder's output for every sample format decoded by ffmpeg (fixture step) and by us; errors; fuzz. -- Fixtures: tools/fixtures/aiff.py. local T = require("@tests/T") @@ -149,9 +149,11 @@ do t:check(e and e.code == Err.CORRUPT, "wrong FORM type: " .. tostring(e)) local c = case("ffmpeg-fl32").data local p = string.find(c, "fl32", 1, true) :: number - local ima = string.sub(c, 1, p - 1) .. "ima4" .. string.sub(c, p + 4) - local _, e2 = Aiff.decode(reader(ima)) - t:check(e2 and e2.code == Err.UNSUPPORTED, "ima4: UNSUPPORTED: " .. tostring(e2)) + local mac = string.sub(c, 1, p - 1) .. "MAC3" .. string.sub(c, p + 4) + local _, e2 = Aiff.decode(reader(mac)) + t:check(e2 and e2.code == Err.UNSUPPORTED, "MAC3: UNSUPPORTED: " .. tostring(e2)) + local i4 = Aiff.decode(reader(case("ffmpeg-ima4").data)) :: any + t:check(i4.meta.source.compression == "ima4" and i4.frames % 64 == 0, "ima4 meta / whole packets") local _, e3 = Aiff.decode(reader(string.sub(c, 1, 30))) t:check(e3 and (e3.code == Err.TRUNCATED or e3.code == Err.CORRUPT), "cut in COMM: " .. tostring(e3)) local _, e4 = Aiff.decode(reader(case("ffmpeg-s16be").data), { maxFrames = 10 }) diff --git a/tests/audio/ape.luau b/tests/audio/ape.luau new file mode 100644 index 0000000..2d83725 --- /dev/null +++ b/tests/audio/ape.luau @@ -0,0 +1,90 @@ +-- audio/ape tests: every fixture from tools/fixtures/ape.py (mac -c1000 .. -c5000, 8 - 32-bit int and 32-bit float, +-- 1 - 8 channels, special frames (silence, pseudo stereo), odd rates and lengths, a second frame, APEv2 tags, the FATE +-- sample of an older 3.99 encoder cut mid-frame) decoded bit-exact against `mac -d`; seeking; f32 scaling and output +-- reuse; decode() from a sub-range Reader; an ID3v2 tag in front; the header facts; sniff; the api; a damaged frame +-- (CRC); the fuzz pass. Fixtures: tools/fixtures/ape.py. +local T = require("@tests/T") +local Ape = require("@formats/audio/ape") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local F = require("@formats") +local Cases = require("@tests/gen/ape_cases") +local L = require("@tests/audio/_lossless") + +local t = T.suite("ape") +local byName = {} +for _, c in Cases do + byName[c.name] = c +end +local function open(b: any, opts: any?): (any, any) + return L.open(Ape, b, opts) +end + +t:eq(Ape.name, "ape", "name") +t:check(Ape.caps.decode and not Ape.caps.encode, "caps") + +local seekChecks = L.cases(t, Ape, Cases) +t:note("%d fixtures bit-exact against mac -d, %d seeks", #Cases, seekChecks) + +for _, name in { "s16_c2000", "tags", "f32", "ch6" } do + L.subrange(t, Ape, byName[name], "ape") +end + +-- header facts +do + local d = open(byName.s16_c5000.data) + t:eq(d.level, "insane", "level") + t:eq(d.bitsPerSample, 16, "bits") + t:check(d.version >= 3990, "version") + t:eq(open(byName.s24_c4000.data).level, "extra high", "level 4000") + t:eq(open(byName.s16_c1000.data).level, "fast", "level 1000") +end + +-- an ID3v2 tag in front of the descriptor (the seek table counts from the descriptor) +do + local fx = byName.s16_c3000 + local id3 = "ID3\4\0\0\0\0\0\20" .. "TIT2\0\0\0\10\0\0\3hello id3" + local b = buffer.fromstring(id3 .. fx.data) + t:eq(Ape.sniff(Bytes.reader(b)), 1, "sniff ID3 + MAC") + local dec = open(b) + t:check(dec and (L.all(dec, fx)) == fx.crc, "ID3v2 in front") +end + +-- the api +do + local fx = byName.s16_c2000 + local _ = fx + t:eq(F.detect(buffer.fromstring(fx.data)), "ape", "detect") + local a = F.audio.load(fx.data) + t:check(a and a.frames == fx.frames and a.meta.source.format == "ape", "F.audio.load") +end + +-- errors: a damaged frame fails its CRC, bad headers +do + local fx = byName.s16_long -- two frames: the second is damaged + local b = buffer.fromstring(fx.data) + local at = #fx.data - 2000 + buffer.writeu8(b, at, bit32.bxor(buffer.readu8(b, at), 0x40)) + local dec = open(b) + local _, got = dec:read(fx.frames) + t:check(dec.error and (dec.error.code == Err.CHECKSUM or dec.error.code == Err.CORRUPT) and got == 73728, "damaged frame: " .. tostring(dec.error)) + local _, e0 = open(buffer.fromstring(string.sub(fx.data, 1, 2000) .. string.rep("\0", 100))) + t:check(e0 ~= nil, "a broken first frame fails open: " .. tostring(e0)) + local _, e1 = open("MAC ") + t:check(e1 and Err.is(e1), "too short: " .. tostring(e1)) + local old = buffer.fromstring(fx.data) + buffer.writeu16(old, 4, 3800) + local _, e2 = open(old) + t:check(e2 and e2.code == Err.UNSUPPORTED, "old version: " .. tostring(e2)) + t:eq(Ape.sniff(Bytes.reader(buffer.fromstring("RIFF"))), 0, "sniff RIFF") +end + +-- the fuzz pass +local samples = {} +for _, name in { "s16_c2000", "s16_c4000", "mono", "s24", "s32", "f32", "ch6", "silence", "pseudo_stereo" } do + table.insert(samples, buffer.fromstring(byName[name].data)) +end +t:fuzz("decode", function(b: buffer) + return Ape.decode(Bytes.reader(b)) +end, samples, { mutations = 50 }) +t:done() diff --git a/tests/audio/brstm.luau b/tests/audio/brstm.luau new file mode 100644 index 0000000..9a4b6a1 --- /dev/null +++ b/tests/audio/brstm.luau @@ -0,0 +1,54 @@ +-- audio/brstm tests: BRSTM / BCSTM / BFSTM files (DSP ADPCM, PCM16, PCM8; big- and little-endian; loops) from our +-- Python writer, bit-exact with vgmstream (tools/fixtures/brstm.py) through decode and open with seeks (forward seeks +-- start from the ADPC / SEEK history table); errors; the api; the fuzz pass. +local T = require("@tests/T") +local Brstm = require("@formats/audio/brstm") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local F = require("@formats") +local H = require("@tests/audio/_adpcm") +local Cases = require("@tests/gen/brstm_cases") + +local t = T.suite("brstm") +t:eq(Brstm.name, "brstm", "name") + +local samples = {} +for _, c in Cases do + table.insert(samples, c.data) + t:eq(Brstm.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, c.name .. ": sniff") + H.check(t, Brstm, c) + local flavour = ({ RSTM = "brstm", CSTM = "bcstm", FSTM = "bfstm" })[string.sub(c.data, 1, 4)] + t:eq(F.detect(c.data), flavour, c.name .. ": F.detect names the flavour") + t:check(F.format(flavour) ~= nil or F.format("brstm") ~= nil, c.name .. ": the flavour resolves") +end +t:note("%d files bit-exact with vgmstream", #Cases) + +do + local base = Cases[1].data + local function fails(b: buffer, code: string, label: string) + local d, e = Brstm.open(Bytes.reader(b)) + t:check(d == nil and e and e.code == code, label .. ": " .. tostring(e)) + end + local beta = buffer.fromstring(base) + buffer.writeu16(beta, 6, 0x0100) -- bytes 01 00 read big-endian: version 0.1 + fails(beta, Err.UNSUPPORTED, "version 0.1") + fails(buffer.fromstring(string.sub(base, 1, 0x30)), Err.TRUNCATED, "short") + fails(buffer.fromstring("RSTM\254\255\1\0" .. string.rep("\0", 100)), Err.CORRUPT, "no HEAD") + local a = F.audio.load(Cases[2].data) + t:check(a and a.meta.source.loop and a.meta.source.loop.start == Cases[2].loopStart, "F.audio.load keeps the loop") +end + +t:fuzz("open + read + seek", function(b: buffer) + local dec = Brstm.open(Bytes.reader(b)) + if dec then + dec:read(100000) + dec:seek(dec.duration / 2) + dec:read(33) + end + return dec +end, samples, { mutations = 8 }) +t:fuzz("header", function(b: buffer) + return Brstm.decode(Bytes.reader(b)) +end, samples, { mutations = 12, keepHeader = 0, garbage = 50 }) + +t:done() diff --git a/tests/audio/caf.luau b/tests/audio/caf.luau index c0f40ff..450b085 100644 --- a/tests/audio/caf.luau +++ b/tests/audio/caf.luau @@ -174,4 +174,16 @@ do end, samples, { mutations = 30 }) end +-- ------------------------------------------------------------------------------------------------ IMA4 +do + local H = require("@tests/audio/_adpcm") + local Ima4 = require("@tests/gen/caf_ima4") + for _, c in Ima4 do + H.check(t, Caf, c) + local a = Caf.decode(Bytes.reader(buffer.fromstring(c.data))) :: any + t:eq(a.meta.source.codec, "ima4", c.name .. ": codec") + end + t:note("%d IMA4 files bit-exact with ffmpeg", #Ima4) +end + t:done() diff --git a/tests/audio/mpc.luau b/tests/audio/mpc.luau new file mode 100644 index 0000000..bc29eb2 --- /dev/null +++ b/tests/audio/mpc.luau @@ -0,0 +1,145 @@ +-- audio/mpc tests: Musepack SV8 (mpcenc 1.30: stereo / mono, 32 / 44.1 / 48 kHz, quality 1 .. 9, 1 / 4 / 16 / 64 +-- frames per packet) and SV7 (mppenc 1.16, quality 2 / 5 / 8) against libmpcdec's float output (mpcf32: gapless +-- length, near bit-exact) and ffmpeg's decode (SNR); APEv2 tags; seeking (SV8 exact, SV7 like libmpcdec); a leading +-- ID3v2 tag; truncated files; error codes; the fuzz no-throw pass. Fixtures: tools/fixtures/mpc.py. +local T = require("@tests/T") +local Mpc = require("@formats/audio/mpc") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/mpc_cases") +local Seek = require("@tests/gen/mpc_seek") + +local t = T.suite("mpc") + +local function reader(s: string): Bytes.Reader + return Bytes.reader(buffer.fromstring(s)) +end + +-- SNR (dB) and the largest difference of frames [from, to) of got against a f32le reference (frames from 0) +local function compare(got: buffer, gotFrom: number, ref: string, ch: number, frames: number): (number, number) + local rb = buffer.fromstring(ref) + local n = math.min(frames * ch, #ref // 4) + local sig, err, maxd = 0, 0, 0 + for i = 0, n - 1 do + local r = buffer.readf32(rb, i * 4) + local d = buffer.readf32(got, (gotFrom * ch + i) * 4) - r + sig += r * r + err += d * d + maxd = math.max(maxd, math.abs(d)) + end + return if err == 0 then math.huge else 10 * math.log10(sig / err), maxd +end + +t:eq(Mpc.name, "mpc", "name") +t:check(Mpc.caps.decode and not Mpc.caps.encode and Mpc.encode == nil, "caps: decode only") + +local byName = {} +for _, c in Fx do + byName[c.name] = c + local r = reader(c.data) + t:check(Mpc.sniff(r) >= 0.9, c.name .. ": sniff") + local a, err = Mpc.decode(r) + t:check(a, c.name .. ": " .. tostring(err)) + if not a then + continue + end + t:check(a.channels == c.channels and a.sampleRate == c.rate, c.name .. ": format") + t:eq(a.frames, c.frames, c.name .. ": gapless length") + t:eq(a.meta.source.version, c.version, c.name .. ": stream version") + local s, maxd = compare(a.samples, 0, c.ref, c.channels, c.exact) + t:check(s > 120 and maxd < 1e-5, string.format("%s: SNR %.1f dB, max diff %g vs libmpcdec", c.name, s, maxd)) + local all = compare(a.samples, 0, c.ref, c.channels, c.frames) + t:check(all > 60, string.format("%s: whole SNR %.1f dB", c.name, all)) + local line = string.format("%s: SV%d %d ch %d Hz, %d frames, SNR %.1f dB (max diff %.2g) vs libmpcdec", c.name, c.version, c.channels, c.rate, a.frames, s, maxd) + if c.ff then + local f = compare(a.samples, 0, c.ff, c.channels, c.frames) + t:check(f > 80, string.format("%s: SNR %.1f dB vs ffmpeg", c.name, f)) + line ..= string.format(", %.1f dB vs ffmpeg (s16)", f) + end + t:note("%s", line) + if c.tags then + for k, v in c.tags do + t:eq(a.tags[k], v, c.name .. ": tag " .. k) + end + end +end + +-- seeking: SV8 is exact (one packet of pre-roll); SV7 decodes like libmpcdec's seek (32 frames of pre-roll from reset +-- scalefactors) +for _, sk in Seek do + local c = byName[sk.name] + local whole = Mpc.decode(reader(c.data)) :: any + local dec = Mpc.open(reader(c.data)) :: any + local _ = dec:read(5000) -- decode a little first: the seek must forget the state + dec:seek(sk.at / c.rate) + t:check(math.abs(dec:position() - sk.at / c.rate) < 1e-9, sk.name .. ": position after seek") + local b, n = dec:read(4096) + t:eq(n, 4096, sk.name .. ": read after seek") + if c.version == 8 then + local _, own = compare(b, 0, string.sub(buffer.tostring(whole.samples), sk.at * 8 + 1, (sk.at + 4096) * 8), 2, 4096) + t:check(own < 1e-6, string.format("%s: seek to %d is exact (max diff %g)", sk.name, sk.at, own)) + -- libmpcdec seeks without warming the synthesis up: compare after its first frame + local _, lib = compare(b, 1152, string.sub(sk.ref, 1152 * 8 + 1), 2, 4096 - 1152) + t:check(lib < 1e-5, string.format("%s: seek matches libmpcdec past 1152 frames (max diff %g)", sk.name, lib)) + else + local s, lib = compare(b, 0, sk.ref, 2, 4096) + t:check(lib < 1e-5, string.format("%s: seek to %d matches libmpcdec's (max diff %g)", sk.name, sk.at, lib)) + local own = compare(b, 0, string.sub(buffer.tostring(whole.samples), sk.at * 8 + 1, (sk.at + 4096) * 8), 2, 4096) + t:note("%s: seek %d: SNR %.1f dB vs the continuous decode (SV7 seeks restart the scalefactors: not always exact)", sk.name, sk.at, own) + local _ = s + end + dec:seek(0) + local b0, n0 = dec:read(1000) + local _, d0 = compare(b0, 0, c.ref, 2, n0) + t:check(n0 == 1000 and d0 < 1e-5, sk.name .. ": seek back to 0") +end + +-- an ID3v2 tag in front; truncated files +do + local c = byName.sv8_q5_stereo + local id3 = "ID3\3\0\0\0\0\0\20" .. string.rep("\0", 20) + local a = Mpc.decode(reader(id3 .. c.data)) :: any + t:check(a and a.frames == c.frames, "ID3v2 in front") + t:check(Mpc.sniff(reader(id3 .. c.data)) == 1, "ID3v2 in front: sniff") + for _, name in { "sv8_q5_stereo", "sv7_q5_stereo" } do + local d = byName[name] + local cut = Mpc.decode(reader(string.sub(d.data, 1, #d.data * 2 // 3))) :: any + t:check(cut and cut.frames > 0 and cut.frames < d.frames, name .. ": truncated file decodes its start") + if cut then + local _, m = compare(cut.samples, 0, d.ref, 2, math.min(cut.frames - 1152, d.exact)) + t:check(m < 1e-5, name .. ": truncated file: same start") + end + end +end + +-- errors +do + local c8, c7 = byName.sv8_q5_stereo.data, byName.sv7_q5_stereo.data + t:eq(Mpc.sniff(reader("RIFF....WAVE")), 0, "sniff a WAV") + local _, e = Mpc.decode(reader("MPCX" .. string.rep("\0", 64))) + t:check(e and e.code == Err.CORRUPT, "bad magic: " .. tostring(e)) + -- the stream header's CRC (SH is the first packet: "SH", size, CRC, version ...) + local p = string.find(c8, "SH", 5, true) :: number + local bad = string.sub(c8, 1, p + 7) .. string.char((string.byte(c8, p + 8) + 1) % 256) .. string.sub(c8, p + 9) + _, e = Mpc.decode(reader(bad)) + t:check(e and e.code == Err.CHECKSUM, "SH CRC: " .. tostring(e)) + _, e = Mpc.decode(reader("MP+\6" .. string.sub(c7, 5))) + t:check(e and e.code == Err.UNSUPPORTED, "SV6: " .. tostring(e)) + _, e = Mpc.decode(reader(string.sub(c7, 1, 20))) + t:check(e and e.code == Err.TRUNCATED, "short SV7 header: " .. tostring(e)) + _, e = Mpc.decode(reader(c8), { maxFrames = 1000 }) + t:check(e and e.code == Err.LIMIT, "maxFrames: " .. tostring(e)) +end + +-- fuzz +do + local samples = {} + for _, c in Fx do + table.insert(samples, string.sub(c.data, 1, 3000)) + end + t:fuzz("decode", function(b: buffer) + return Mpc.decode(Bytes.reader(b)) + end, samples, { mutations = 25, keepHeader = 4 }) +end + +t:done() diff --git a/tests/audio/qoa.luau b/tests/audio/qoa.luau new file mode 100644 index 0000000..b7343ff --- /dev/null +++ b/tests/audio/qoa.luau @@ -0,0 +1,95 @@ +-- audio/qoa tests: files written by qoa.h (tools/fixtures/qoa.py; 1, 2 and 6 channels, a frame boundary, a partial +-- last slice, clipping signals) decoded bit-exact against ffmpeg and qoa.h; our encoder byte-for-byte equal to +-- qoa.h's qoa_encode, from an Audio and from a streaming Decoder; seeking; streaming files (total 0); a cut file; errors; +-- the api; the fuzz pass. +local T = require("@tests/T") +local Qoa = require("@formats/audio/qoa") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/audio/Pcm") +local F = require("@formats") +local H = require("@tests/audio/_adpcm") +local Cases = require("@tests/gen/qoa_cases") + +local Sigs = { + qoa_sig_stereo_44k = require("@tests/gen/qoa_sig_stereo_44k"), + qoa_sig_mono_22k = require("@tests/gen/qoa_sig_mono_22k"), + qoa_sig_6ch_48k = require("@tests/gen/qoa_sig_6ch_48k"), + qoa_sig_loud_mono = require("@tests/gen/qoa_sig_loud_mono"), + qoa_sig_square_stereo = require("@tests/gen/qoa_sig_square_stereo"), +} + +local t = T.suite("qoa") +t:eq(Qoa.name, "qoa", "name") +t:check(Qoa.caps.decode and Qoa.caps.encode, "caps") + +local samples = {} +for _, c in Cases do + table.insert(samples, c.data) + t:eq(Qoa.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, c.name .. ": sniff") + t:check(c.ref == c.qoaref, c.name .. ": ffmpeg and qoa.h agree") + H.check(t, Qoa, c) + -- our encoder: the same bytes as qoa.h + local S = Sigs[c.sig] + local a = Types.Audio.new(S.rate, S.channels, S.frames) + buffer.writestring(a.samples, 0, S.data) + local out, err = Qoa.encode(a) + local same = out ~= nil and buffer.tostring(out) == c.data + if not same and out then + local o = buffer.tostring(out) + for i = 1, math.max(#o, #c.data) do + if string.byte(o, i) ~= string.byte(c.data, i) then + t:note("%s: first difference at byte %d of %d / %d", c.name, i - 1, #o, #c.data) + break + end + end + end + t:check(same, c.name .. ": encode identical to qoa.h: " .. tostring(err)) + local streamed = Qoa.encode(Pcm.audioDecoder(a)) + t:check(streamed and buffer.tostring(streamed) == c.data, c.name .. ": encode from a Decoder") +end +t:note("%d qoa.h files decoded bit-exact (ffmpeg, qoa.h) and re-encoded byte-for-byte", #Cases) + +-- ------------------------------------------------------------------------------------------------ variants +do + local c = Cases[1] + local ref = buffer.fromstring(c.ref) + -- streaming: total 0 in the header + local s = buffer.fromstring(c.data) + buffer.writeu32(s, 4, 0) + local a = Qoa.decode(Bytes.reader(s)) :: any + t:check(a and a.frames == buffer.len(ref) // (2 * c.ch) and H.same(a.samples, ref, 0, a.frames * c.ch), "streaming file") + t:check(a.meta.source.streaming == true, "meta.source.streaming") + -- a cut file keeps its whole frames + local cut = Qoa.decode(Bytes.reader(buffer.fromstring(string.sub(c.data, 1, #c.data - 100)))) :: any + t:check(cut and cut.frames == 5120 * 2 and H.same(cut.samples, ref, 0, cut.frames * c.ch), "cut file: the whole frames") + -- errors + local _, e1 = Qoa.open(Bytes.reader(buffer.fromstring("qoaf\0\0\0\1"))) + t:check(e1 and e1.code == Err.TRUNCATED, "no frames: " .. tostring(e1)) + local bad = buffer.fromstring(c.data) + buffer.writeu8(bad, 8, 0) -- 0 channels + local _, e2 = Qoa.open(Bytes.reader(bad)) + t:check(e2 and e2.code == Err.CORRUPT, "0 channels: " .. tostring(e2)) + local _, e3 = Qoa.encode(Types.Audio.new(8000, 9, 10)) + t:check(e3 and e3.code == Err.ARG, "9 channels") + local _, e4 = Qoa.encode(Types.Audio.new(8000, 1, 0)) + t:check(e4 and e4.code == Err.ARG, "no samples") + local _, e5 = Qoa.decode(Bytes.reader(buffer.fromstring(c.data)), { maxFrames = 10 }) + t:check(e5 and e5.code == Err.LIMIT, "maxFrames") + t:eq(F.detect(c.data), "qoa", "F.detect") + local back = F.save(F.audio.load(c.data), nil, { format = "qoa" }) + t:check(back and F.detect(back) == "qoa", "F.save qoa") +end + +t:fuzz("open + read + seek", function(b: buffer) + local dec = Qoa.open(Bytes.reader(b)) + if dec then + dec:read(100000) + dec:seek(dec.duration / 2) + dec:read(33) + end + return dec +end, samples, { mutations = 10 }) + +t:done() diff --git a/tests/audio/tta.luau b/tests/audio/tta.luau new file mode 100644 index 0000000..9a46b83 --- /dev/null +++ b/tests/audio/tta.luau @@ -0,0 +1,100 @@ +-- audio/tta tests: every fixture from tools/fixtures/tta.py (ttaenc 3.4.1: 8 / 16 / 24 bits, 1 - 6 channels, odd +-- rates and lengths, several frames, silence, noise; the FATE sample inside.tta cut mid-file) decoded bit-exact +-- against `ttaenc -d`; seeking; f32 scaling and output reuse; decode() from a sub-range Reader; an ID3v2 tag in front +-- and an APEv2 tag at the end; password-protected files (UNSUPPORTED); header / seek table / frame CRCs; sniff; the +-- api; the fuzz pass. Fixtures: tools/fixtures/tta.py. +local T = require("@tests/T") +local Tta = require("@formats/audio/tta") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local F = require("@formats") +local Cases = require("@tests/gen/tta_cases") +local L = require("@tests/audio/_lossless") + +local t = T.suite("tta") +local byName = {} +for _, c in Cases do + byName[c.name] = c +end +local function open(b: any, opts: any?): (any, any) + return L.open(Tta, b, opts) +end + +t:eq(Tta.name, "tta", "name") +t:check(Tta.caps.decode and not Tta.caps.encode, "caps") + +local seekChecks = L.cases(t, Tta, Cases) +t:note("%d fixtures bit-exact against ttaenc -d, %d seeks", #Cases, seekChecks) + +for _, name in { "s16", "s24", "ch6", "u8" } do + L.subrange(t, Tta, byName[name], "tta") +end + +local function u32(v: number): string + return string.char(v % 256, (v // 256) % 256, (v // 65536) % 256, (v // 16777216) % 256) +end + +-- an ID3v2 tag in front, an APEv2 tag at the end +do + local fx = byName.s16 + local id3 = "ID3\4\0\0\0\0\0\20" .. "TIT2\0\0\0\10\0\0\3hello id3" + local item = u32(5) .. u32(0) .. "Title\0" .. "Hello" + local tail = item .. "APETAGEX" .. u32(2000) .. u32(#item + 32) .. u32(1) .. u32(0) .. string.rep("\0", 8) + local b = buffer.fromstring(id3 .. fx.data .. tail) + t:eq(Tta.sniff(Bytes.reader(b)), 1, "sniff ID3 + TTA1") + local dec = open(b) + t:check(dec and (L.all(dec, fx)) == fx.crc, "ID3v2 + APEv2 around the file") + t:eq(dec.tags.title, "Hello", "APEv2 title") +end + +-- errors: password protection, CRCs +do + local fx = byName.s16 + local b = buffer.fromstring(fx.data) + buffer.writeu16(b, 4, 2) + buffer.writeu32(b, 18, Crc32.of(b, 0, 18)) + local _, e1 = open(b) + t:check(e1 and e1.code == Err.UNSUPPORTED, "password-protected: " .. tostring(e1)) + local h = buffer.fromstring(fx.data) + buffer.writeu8(h, 10, 0x45) + local _, e2 = open(h) + t:check(e2 and e2.code == Err.CHECKSUM, "header CRC: " .. tostring(e2)) + local long = byName.s16_long + local d = buffer.fromstring(long.data) + local at = #long.data - 3000 + buffer.writeu8(d, at, bit32.bxor(buffer.readu8(d, at), 1)) + local dec = open(d) + local _, got = dec:read(long.frames) + t:check(dec.error and dec.error.code == Err.CHECKSUM and got == 2 * 46080, "frame CRC: " .. tostring(dec.error)) + local _, e3 = open("TTA1") + t:check(e3 and Err.is(e3), "too short: " .. tostring(e3)) + t:eq(Tta.sniff(Bytes.reader(buffer.fromstring("RIFF"))), 0, "sniff RIFF") +end + +-- the api +do + local fx = byName.s16 + t:eq(F.detect(buffer.fromstring(fx.data)), "tta", "detect") + local a = F.audio.load(fx.data) + t:check(a and a.frames == fx.frames and a.meta.source.format == "tta", "F.audio.load") +end + +-- the fuzz pass (the frame CRC rejects most mutations; the second set skips it to reach the decoder) +local samples = {} +for _, name in { "s16", "mono", "s24", "u8", "ch6" } do + table.insert(samples, buffer.fromstring(byName[name].data)) +end +t:fuzz("decode", function(b: buffer) + return Tta.decode(Bytes.reader(b)) +end, samples, { mutations = 150 }) +local Decode = require("@formats/codecs/audio/Tta/Decode") +t:fuzz("frames without CRC", function(b: buffer) + local n = buffer.len(b) + local c = buffer.create(n + 4) + buffer.copy(c, 0, b) + buffer.writeu32(c, n, Crc32.of(b)) + local st = Decode.state(2, 2) + return Decode.frame(st, c, 0, n + 4, 2000, table.create(4000, 0)) +end, { buffer.fromstring(string.sub(byName.s16.data, 22 + 4 + 4 + 1, 22 + 4 + 4 + 3000)) }, { mutations = 300 }) +t:done() diff --git a/tests/audio/vag.luau b/tests/audio/vag.luau new file mode 100644 index 0000000..4b16073 --- /dev/null +++ b/tests/audio/vag.luau @@ -0,0 +1,89 @@ +-- audio/vag tests: VAGp (with and without loop flags), VAGi and KVAG files from our Python encoders, bit-exact with +-- vgmstream / ffmpeg (tools/fixtures/vag.py) through decode and open with seeks; our encoder's files as vgmstream +-- decodes them (loops reported where vgmstream reads them), their quality; errors; the api; the fuzz pass. +local T = require("@tests/T") +local Vag = require("@formats/audio/vag") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local F = require("@formats") +local H = require("@tests/audio/_adpcm") +local Cases = require("@tests/gen/vag_cases") +local Ours = require("@tests/gen/vag_ours") +local Sig = require("@tests/gen/vag_sig") +local Sig1 = require("@tests/gen/vag_sig1") + +local t = T.suite("vag") +t:eq(Vag.name, "vag", "name") + +local samples = {} +for _, c in Cases do + table.insert(samples, c.data) + t:eq(Vag.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, c.name .. ": sniff") + H.check(t, Vag, c) + if c.title then + t:eq(Vag.decode(Bytes.reader(buffer.fromstring(c.data))).tags.title, c.title, c.name .. ": title") + end +end +t:note("%d files bit-exact with vgmstream / ffmpeg", #Cases) + +-- ------------------------------------------------------------------------------------------------ encoder +local function audioOf(S: any): any + local a = Types.Audio.new(S.rate, S.channels, S.frames) + buffer.writestring(a.samples, 0, S.data) + return a +end +for _, c in Ours do + H.check(t, Vag, c) + local src = audioOf(if c.ch == 1 then Sig1 else Sig) + local a = Vag.decode(Bytes.reader(buffer.fromstring(c.data))) :: any + -- the output starts with the blank frame: 28 samples later + local s = H.snr(src.samples, buffer.fromstring(buffer.readstring(a.samples, 28 * c.ch * 4, src.frames * c.ch * 4)), src.frames * c.ch) + t:check(s > 25, string.format("ours %s: %.1f dB", c.name, s)) + t:note("encode %s: %.1f dB", c.name, s) +end +do + local mono = audioOf(Sig1) + local out = Vag.encode(mono, { loop = { start = 600, stop = 5000 } }) + t:check(out and buffer.tostring(out) == Ours[2].data, "encode is deterministic") + mono.tags = { title = "A Title That Is Long" } + local named = Vag.decode(Bytes.reader(Vag.encode(mono) :: buffer)) :: any + t:eq(named.tags.title, "A Title That Is ", "the name field holds 16 bytes") + local _, e1 = Vag.encode(Types.Audio.new(8000, 3, 10)) + t:check(e1 and e1.code == Err.ARG, "3 channels") + local _, e2 = Vag.encode(mono, { loop = { start = 0, stop = 10 } }) + t:check(e2 and e2.code == Err.ARG, "a loop inside one frame") + local _, e3 = Vag.encode(audioOf(Sig), { interleave = 100 }) + t:check(e3 and e3.code == Err.ARG, "bad interleave") +end + +-- ------------------------------------------------------------------------------------------------ errors +do + local base = Cases[1].data + local hevag = buffer.fromstring(base) + buffer.writeu32(hevag, 4, bit32.byteswap(0x00030000)) + local _, e1 = Vag.open(Bytes.reader(hevag)) + t:check(e1 and e1.code == Err.UNSUPPORTED, "HEVAG: " .. tostring(e1)) + local _, e2 = Vag.open(Bytes.reader(buffer.fromstring("VAGp\0\0"))) + t:check(e2 and e2.code == Err.TRUNCATED, "short header: " .. tostring(e2)) + local _, e3 = Vag.open(Bytes.reader(buffer.fromstring("RIFF0000WAVE"))) + t:check(e3 and e3.code == Err.CORRUPT, "not vag") + t:eq(F.detect(base), "vag", "F.detect") + local a = F.audio.load(Cases[4].data) + t:check(a and a.channels == 1 and a.meta.source.codec == "ima", "F.audio.load KVAG") +end + +t:fuzz("open + read + seek", function(b: buffer) + local dec = Vag.open(Bytes.reader(b)) + if dec then + dec:read(100000) + dec:seek(dec.duration / 2) + dec:read(33) + end + return dec +end, samples, { mutations = 10 }) +t:fuzz("header", function(b: buffer) + return Vag.decode(Bytes.reader(b)) +end, samples, { mutations = 10, keepHeader = 0, garbage = 50 }) + +t:done() diff --git a/tests/audio/wavpack.luau b/tests/audio/wavpack.luau new file mode 100644 index 0000000..58acc7b --- /dev/null +++ b/tests/audio/wavpack.luau @@ -0,0 +1,116 @@ +-- audio/wavpack tests: every fixture from tools/fixtures/wavpack.py (wavpack -f / -g / -h / -hh / -x1..6, joint stereo +-- on / off, 8 - 32-bit int and 32-bit float, 1 - 8 channels, odd rates and lengths, hybrid lossy and hybrid lossless +-- with the .wvc, noise shaping, ffmpeg's encoder) decoded bit-exact against wvunpack; seeking; f32 scaling and output +-- reuse; decode() from a sub-range Reader; APEv2 tags and the MD5; the correction file through opts.resolve; sniff; +-- the api; damaged blocks; the fuzz pass. Fixtures: tools/fixtures/wavpack.py. +local T = require("@tests/T") +local WavPack = require("@formats/audio/wavpack") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local F = require("@formats") +local Cases = require("@tests/gen/wavpack_cases") +local L = require("@tests/audio/_lossless") + +local t = T.suite("wavpack") + +local function open(b: any, opts: any?): (any, any) + return WavPack.open(Bytes.reader(if type(b) == "string" then buffer.fromstring(b) else b), opts) +end +local byName = {} +for _, c in Cases do + byName[c.name] = c +end + +t:eq(WavPack.name, "wavpack", "name") +t:check(WavPack.caps.decode and not WavPack.caps.encode, "caps") + +local all = L.all +local seekChecks = L.cases(t, WavPack, Cases, function(fx: any): any + return if fx.wvc then { correction = fx.wvc } else nil +end) +for _, fx in Cases do + local dec = open(fx.data, if fx.wvc then { correction = fx.wvc } else nil) + t:eq(dec.lossless, not fx.lossy, fx.name .. ": lossless") + if fx.wvc then + local lossy = open(fx.data) + t:eq(lossy.lossless, false, fx.name .. ": without wvc: lossy") + t:eq((all(lossy, fx)), fx.lossy_crc, fx.name .. ": without wvc: identical to wvunpack -i") + end +end +t:note("%d fixtures bit-exact against wvunpack, %d seeks", #Cases, seekChecks) + +-- decode() from a sub-range Reader +for _, name in { "s16_g", "md5_tags", "f32", "ch6" } do + L.subrange(t, WavPack, byName[name], "wavpack") +end + +-- tags, md5, the source facts +do + local dec = open(byName.md5_tags.data) + t:eq(#dec.md5, 32, "md5") + t:eq(dec.bitsPerSample, 16, "bitsPerSample") + t:eq(open(byName.s20.data).bitsPerSample, 20, "20-bit") + t:eq(open(byName.s12.data).bitsPerSample, 12, "12-bit") + t:eq(open(byName.hyb_c3.data).hybrid, true, "hybrid") + t:eq(open(byName.ch6.data).channelMask, 0x3F, "channel mask") +end + +-- the correction file through opts.resolve + opts.name (as the api passes them for paths) +do + local fx = byName.hyb_c3 + local asked = nil + local dec = open(fx.data, { + name = "music/song.wv", + resolve = function(uri: string): buffer? + asked = uri + return buffer.fromstring(fx.wvc) + end, + }) + t:eq(asked, "song.wvc", "resolve asks for the .wvc") + t:check(dec.lossless and (all(dec, fx)) == fx.crc, "resolve: lossless") + local dec2 = open(fx.data, { name = "x.wv", resolve = function(): buffer? return nil end }) + t:check(dec2 and not dec2.lossless, "resolve: no wvc -> lossy") +end + +-- the api +do + local fx = byName.s16_g + t:eq(F.detect(buffer.fromstring(fx.data)), "wavpack", "detect") + local a = F.audio.load(fx.data) + t:check(a and a.frames == fx.frames and a.meta.source.format == "wavpack", "F.audio.load") + local d = F.audio.open(fx.data) + t:check(d and d.sampleRate == fx.rate, "F.audio.open") +end + +-- errors: damaged data, a bad CRC, no audio +do + local fx = byName.s16_g + local b = buffer.fromstring(fx.data) + buffer.writeu8(b, 200, bit32.bxor(buffer.readu8(b, 200), 0x55)) + local dec = open(b) + if dec then + local _, got = dec:read(fx.frames) + t:check(dec.error ~= nil or got < fx.frames, "damaged block reported") + else + t:check(true, "damaged block reported") + end + local _, e1 = open("wvpk") + t:check(e1 and Err.is(e1), "too short: " .. tostring(e1)) + local _, e2 = open(string.rep("\0", 100)) + t:check(e2 and e2.code == Err.CORRUPT, "no blocks: " .. tostring(e2)) + t:eq(WavPack.sniff(Bytes.reader(buffer.fromstring("RIFF"))), 0, "sniff RIFF") +end + +-- the fuzz pass +local samples = {} +for _, name in { "s16_g", "f32", "hyb_b3", "s32_hh", "ch6", "u8" } do + table.insert(samples, buffer.fromstring(byName[name].data)) +end +t:fuzz("decode", function(b: buffer) + return WavPack.decode(Bytes.reader(b)) +end, samples, { mutations = 150 }) +local fxw = byName.hyb_c3 +t:fuzz("decode with wvc", function(b: buffer) + return WavPack.decode(Bytes.reader(buffer.fromstring(fxw.data)), { correction = b }) +end, { buffer.fromstring(fxw.wvc) }, { mutations = 100 }) +t:done() diff --git a/tests/codecs/ac3.luau b/tests/codecs/ac3.luau new file mode 100644 index 0000000..dbac64a --- /dev/null +++ b/tests/codecs/ac3.luau @@ -0,0 +1,57 @@ +-- codecs/audio/Ac3 tests: the codec API under audio/ac3 and the container hook: header fields of every fixture layout, +-- the CRC (a syncframe checks to 0), one-frame decodes against the reference (frame by frame, as a container feeds +-- them), the block offsets, reset, argument / data errors, and a fuzz pass over single frames (CRC off). +-- Fixtures: tools/fixtures/ac3.py. +local T = require("@tests/T") +local Ac3 = require("@formats/codecs/audio/Ac3") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/ac3_cases") + +local t = T.suite("codecs/ac3") + +local ACMOD_CH = { [0] = 2, 1, 2, 3, 3, 4, 4, 5 } +local frames = {} +for _, c in Fx do + local b = buffer.fromstring(c.data) + local h = Ac3.header(b, 0, buffer.len(b)) + t:check(h, c.name .. ": header") + if not h then + continue + end + t:check(h.sampleRate == c.rate and h.channels == c.channels, c.name .. ": header rate / channels") + t:eq(ACMOD_CH[h.acmod] + (if h.lfeon then 1 else 0), c.channels, c.name .. ": acmod + lfe") + t:eq(Ac3.crc(b, 2, h.frameSize - 2), 0, c.name .. ": crc2 checks") + -- frame by frame, fresh decoder: the second frame against the reference + local d = Ac3.decoder() + local n1 = d:decode(b, 0, h.frameSize) + local h2 = Ac3.header(b, h.frameSize, buffer.len(b)) :: Ac3.Header + local n2, err = d:decode(b, h.frameSize, h2.frameSize) + t:check(n1 == 1536 and n2 == 1536, c.name .. ": two frames: " .. tostring(err)) + local rb = buffer.fromstring(c.ref) + local maxd = 0 + for i = 1, 1536 * c.channels do + maxd = math.max(maxd, math.abs(d.pcm[i] - buffer.readf32(rb, (1536 * c.channels + i - 1) * 4))) + end + t:check(maxd < 1e-4, string.format("%s: frame 2 (max diff %g)", c.name, maxd)) + t:check(#d.blocks == 6 and d.blocks[1] > 40 and d.blocks[6] < h2.frameSize * 8, c.name .. ": block offsets") + d:reset() + table.insert(frames, buffer.readstring(b, 0, h.frameSize)) +end + +-- errors +do + local d = Ac3.decoder() + local _, e = d:decode(buffer.create(10), 20) + t:check(e and e.code == Err.ARG, "offset past the buffer: " .. tostring(e)) + _, e = d:decode(buffer.fromstring(string.rep("\0", 64)), 0) + t:check(e and e.code == Err.CORRUPT, "no sync: " .. tostring(e)) + _, e = d:decode(buffer.fromstring(string.sub(frames[1], 1, 100)), 0) + t:check(e and e.code == Err.TRUNCATED, "short frame: " .. tostring(e)) + t:check(Ac3.header(buffer.fromstring("\11\119\0\0\255\0\0\0"), 0, 8) == nil, "frmsizecod 63 / fscod 3: no header") +end + +t:fuzz("decode one frame (crc off)", function(b: buffer) + return Ac3.decoder({ crc = false }):decode(b, 0) +end, frames, { mutations = 30, keepHeader = 6 }) + +t:done() diff --git a/tests/codecs/adpcm.luau b/tests/codecs/adpcm.luau new file mode 100644 index 0000000..6742105 --- /dev/null +++ b/tests/codecs/adpcm.luau @@ -0,0 +1,247 @@ +-- codecs/adpcm tests: every decoder kernel of codecs/audio/Adpcm against a reference decoder, bit-exact as s16 +-- (tools/fixtures/adpcm.py: ADX from ffmpeg and PS-ADPCM / DSP from our Python encoders decoded by vgmstream, Apple +-- ima4 from ffmpeg, IMA nibble streams decoded by ffmpeg); ADX coefficients; the encoders (IMA nibbles, IMA WAV +-- blocks, MS blocks) decoded back with a signal-to-noise floor; the Decoder layouts (seeking matches a straight +-- read); a fuzz pass of random bytes through every kernel (ranges valid, contents random) and the layouts. +local T = require("@tests/T") +local Adpcm = require("@formats/codecs/audio/Adpcm") +local Decoder = require("@formats/codecs/audio/Adpcm/Decoder") +local Cases = require("@tests/gen/adpcm_codec") +local Sig = require("@tests/gen/adpcm_sig") + +local t = T.suite("adpcm codec") + +-- s16le reference vs interleaved f32: the count of differing samples and the first one +local function compare(out: buffer, ref: string, count: number): (number, number) + local r = buffer.fromstring(ref) + local bad, first = 0, -1 + for i = 0, count - 1 do + if buffer.readf32(out, i * 4) * 32768 ~= buffer.readi16(r, i * 2) then + bad += 1 + if first < 0 then + first = i + end + end + end + return bad, first +end + +-- ------------------------------------------------------------------------------------------------ kernels +for _, c in Cases do + local src = buffer.fromstring(c.data) + local ch, frames = c.ch, c.frames + local out = buffer.create((frames + 64) * ch * 4) + local st = buffer.create(8 * ch) + if c.kind == "adx" then + local c1, c2 = Adpcm.adxCoefs(c.cutoff, c.rate) + local nf = math.ceil(frames / 32) + for k = 0, ch - 1 do + Adpcm.adx(src, k * 18, 18 * ch, nf, c1, c2, c.v3, st, k * 8, out, k, ch) + end + elseif c.kind == "psx" then + Adpcm.psx(src, 0, 16, frames // 28, st, 0, out, 0, 1) + elseif c.kind == "dsp" then + local coefs = buffer.create(64) + for i, v in c.coefs do + buffer.writei32(coefs, (i - 1) * 4, v) + end + -- in pieces: the state carries over + Adpcm.dsp(src, 0, 14 * 9, coefs, 0, st, 0, out, 0, 1) + Adpcm.dsp(src, 8 * 9, frames - 14 * 9, coefs, 0, st, 0, out, 14 * 9, 1) + elseif c.kind == "ima_qt" then + for p = 0, frames // 64 - 1 do + for k = 0, ch - 1 do + Adpcm.imaQt(src, (p * ch + k) * 34, st, k * 8, out, p * 64 * ch + k, ch) + end + end + elseif c.kind == "ima" then + for k = 0, ch - 1 do + Adpcm.ima(src, 0, k, ch, frames, true, st, k * 8, out, k, ch) + end + end + local bad, first = compare(out, c.ref, frames * ch) + t:check(bad == 0, string.format("%s: %d of %d samples differ (first at %d)", c.name, bad, frames * ch, first)) +end +t:note("%d streams bit-exact with the reference decoders", #Cases) + +-- ADX coefficients: 500 Hz at 44.1 kHz / 22.05 kHz (CRI's single-precision derivation, as vgmstream) +do + local a1, a2 = Adpcm.adxCoefs(500, 44100) + t:check(a1 == 7334 and a2 == -3283, "adx coefs 44100: " .. a1 .. " " .. a2) + local z1, z2 = Adpcm.adxCoefs(0, 0) + t:check(z1 == 0 and z2 == 0, "adx coefs of rate 0") +end + +-- ModPlug ADPCM: deltas from the table, wrapping as a signed byte +do + local src = buffer.create(18) + for k = 0, 15 do + buffer.writei8(src, k, if k == 1 then 100 elseif k == 2 then -3 else 0) + end + buffer.writeu8(src, 16, 0x11) -- +100, +100 (wraps to -56) + buffer.writeu8(src, 17, 0x02) -- -3, +0 + local out = buffer.create(16) + Adpcm.modplug(src, 0, 4, out, 0) + local want = { 100, -56, -59, -59 } + for i, v in want do + t:eq(buffer.readf32(out, (i - 1) * 4) * 128, v, "modplug sample " .. i) + end +end + +-- ------------------------------------------------------------------------------------------------ encoders +local function snr(x: buffer, y: buffer, count: number): number + local sig, err = 0, 0 + for i = 0, count - 1 do + local a = buffer.readf32(x, i * 4) + local e = a - buffer.readf32(y, i * 4) + sig += a * a + err += e * e + end + return if err == 0 then 200 else 10 * math.log10(sig / err) +end + +do + local x = buffer.fromstring(Sig.data) + local ch, n = Sig.channels, Sig.frames + -- IMA nibbles, both nibble orders + for _, hi in { true, false } do + local raw = buffer.create((n * ch + 1) // 2) + local st = buffer.create(8 * ch) + for c = 0, ch - 1 do + Adpcm.imaEncode(x, c, ch, n, st, c * 8, raw, 0, c, ch, hi) + end + local back = buffer.create(n * ch * 4) + local ds = buffer.create(8 * ch) + for c = 0, ch - 1 do + Adpcm.ima(raw, 0, c, ch, n, hi, ds, c * 8, back, c, ch) + end + local s = snr(x, back, n * ch) + t:check(s > 20, string.format("ima encode (hi %s): %.1f dB", tostring(hi), s)) + t:check(buffer.readi32(st, 0) == buffer.readi32(ds, 0), "ima encoder and decoder end in the same state") + end + -- IMA WAV and MS blocks + for _, kind in { "ima_wav", "ms" } do + local ba = 512 + local spb = Decoder.blockFrames(kind, ba, ch) :: number + local blocks = (n + spb - 1) // spb + local raw = buffer.create(blocks * ba) + local st = buffer.create(8 * ch) + for b = 0, blocks - 1 do + if kind == "ms" then + Adpcm.msEncode(x, b * spb, n - b * spb, ch, spb, raw, b * ba) + else + Adpcm.imaWavEncode(x, b * spb, n - b * spb, ch, spb, st, raw, b * ba) + end + end + local back = buffer.create(blocks * spb * ch * 4) + local coefs = buffer.create(56) + for k = 0, 6 do + buffer.writei32(coefs, k * 8, Adpcm.MS_COEF1[k + 1]) + buffer.writei32(coefs, k * 8 + 4, Adpcm.MS_COEF2[k + 1]) + end + local scratch = buffer.create(20 * ch) + for b = 0, blocks - 1 do + local got + if kind == "ms" then + got = Adpcm.msBlock(raw, b * ba, ba, ch, spb, back, b * spb * ch, coefs, 7, scratch) + else + got = Adpcm.imaWav(raw, b * ba, ba, ch, spb, back, b * spb * ch) + end + t:eq(got, spb, kind .. ": block frames") + end + local s = snr(x, back, n * ch) + t:check(s > (if kind == "ms" then 24 else 20), string.format("%s encode: %.1f dB", kind, s)) + end +end + +-- ------------------------------------------------------------------------------------------------ Decoder layouts +local function readAll(dec: any, step: number): buffer + local out = buffer.create(dec.frames * dec.channels * 4) + local got = 0 + while true do + local b, n = dec:read(step) + if n == 0 then + break + end + buffer.copy(out, got * dec.channels * 4, b, 0, n * dec.channels * 4) + got += n + end + t:eq(got, dec.frames, "layout: frames read") + return out +end + +do + -- psx in rows of 64 bytes per channel (stereo), seeking back and forth lands on the same samples + local rng = T.rng(5) + local ch, il, rows = 2, 64, 40 + local data = buffer.create(il * ch * rows) + for i = 0, buffer.len(data) - 1 do + buffer.writeu8(data, i, if i % 16 == 0 then rng(5) * 16 + rng(13) elseif i % 16 == 1 then 0 else rng(256)) + end + for _, kind in { "psx", "dsp" } do + local coefs = buffer.create(64 * ch) + for k = 0, 16 * ch - 1 do + buffer.writei32(coefs, k * 4, (k % 2 == 0) and 1800 or -700) + end + local il2 = if kind == "dsp" then 64 else il + local dec = Decoder.interleaved({ sampleRate = 8000, channels = ch, tags = {} }, { + kind = kind :: any, buf = data, offset = 0, size = buffer.len(data), interleave = il2, coefs = coefs }) + t:check(dec ~= nil, kind .. ": interleaved decoder") + local all = readAll(dec, 1000) + for _, f in { 500, 3, dec.frames - 7, 1234, 0 } do + dec:seek(f / 8000) + local b, n = dec:read(5) + local same = n == math.min(5, dec.frames - f) + for k = 0, n * ch - 1 do + same = same and buffer.readf32(b, k * 4) == buffer.readf32(all, (f * ch + k) * 4) + end + t:check(same, kind .. ": seek to " .. f .. " is exact") + end + end + -- a cut file: the whole frames of every channel + local dec = Decoder.interleaved({ sampleRate = 8000, channels = 2, tags = {} }, { + kind = "psx", buf = data, offset = 0, size = il * ch * 3 + il + 20, interleave = il }) + t:eq(dec.frames, 3 * 4 * 28 + 28, "cut interleaved: the whole frames both channels have") +end + +-- ------------------------------------------------------------------------------------------------ fuzz +local samples = {} +for _, c in Cases do + table.insert(samples, c.data) +end +t:fuzz("kernels", function(b: buffer) + local n = buffer.len(b) + local out = buffer.create(64 * 64 * 4) + local st = buffer.create(64) + local coefs = buffer.create(64) + for k = 0, 15 do + buffer.writei32(coefs, k * 4, if n > k then buffer.readi8(b, k) * 64 else 0) + end + if n >= 18 then + Adpcm.adx(b, 0, 18, 1, 7334, -3283, n % 2 == 0, st, 0, out, 0, 1) + end + if n >= 16 then + Adpcm.psx(b, 0, 16, 1, st, 8, out, 0, 1) + end + if n >= 8 then + Adpcm.dsp(b, 0, 14, coefs, 0, st, 16, out, 0, 1) + end + if n >= 34 then + Adpcm.imaQt(b, 0, st, 24, out, 0, 1) + end + if n >= 1 then + Adpcm.ima(b, 0, 0, 1, math.min(n * 2, 1000), true, st, 32, out, 0, 1) + end + if n >= 17 then + Adpcm.modplug(b, 0, math.min((n - 16) * 2, 1000), out, 0) + end + Adpcm.imaWav(b, 0, n, 2, 1017, buffer.create(1017 * 2 * 4), 0) + Adpcm.msBlock(b, 0, n, 2, 1012, buffer.create(1012 * 2 * 4), 0, coefs, 8, buffer.create(40)) + local dec = Decoder.interleaved({ sampleRate = 8000, channels = 2, tags = {} }, { kind = "adx", buf = b, offset = 0, size = n, interleave = 18, c1 = 7334, c2 = -3283 }) + if dec then + dec:read(100000) + dec:seek(0) + end + return true +end, samples, { mutations = 6, garbage = 60 }) +t:done() diff --git a/tests/codecs/apetag.luau b/tests/codecs/apetag.luau new file mode 100644 index 0000000..5506acc --- /dev/null +++ b/tests/codecs/apetag.luau @@ -0,0 +1,79 @@ +-- codecs/audio/ApeTag tests: APEv2 tags with and without a header, APEv1, multi-value items, binary items, an ID3v1 +-- tag after the APE tag, a tag inside a sub-range, malformed sizes / counts; the fuzz no-throw pass. The real files +-- (wavpack -w, mac -t, ...) are covered by tests/audio/wavpack.luau and tests/audio/ape.luau. +local T = require("@tests/T") +local ApeTag = require("@formats/codecs/audio/ApeTag") + +local t = T.suite("apetag") + +local function u32(v: number): string + return string.char(v % 256, (v // 256) % 256, (v // 65536) % 256, (v // 16777216) % 256) +end +-- tag(items, version, header) -> the tag bytes; items = { { key, value, flags? } } +local function tag(items: { any }, version: number, header: boolean): string + local body = {} + for _, it in items do + table.insert(body, u32(#it[2]) .. u32(it[3] or 0) .. it[1] .. "\0" .. it[2]) + end + local b = table.concat(body) + local flags = if header then 0x80000000 else 0 + local function block(isHeader: boolean): string + return "APETAGEX" .. u32(version) .. u32(#b + 32) .. u32(#items) .. u32(flags + (if isHeader then 0x20000000 else 0)) .. string.rep("\0", 8) + end + return (if header then block(true) else "") .. b .. block(false) +end + +do + local s = "audio data" .. tag({ { "Title", "Hello" }, { "Artist", "A\0B" }, { "Year", "2026" }, { "Track", "3/9" }, + { "Cover Art (Front)", "f.png\0PNG", 2 }, { "Album Artist", "Band" } }, 2000, true) + local b = buffer.fromstring(s) + local tags, info = ApeTag.find(b, 0, #s) + t:check(tags and info, "v2 found") + t:eq(tags.title, "Hello", "title") + t:eq(tags.artist, "A; B", "multi value") + t:eq(tags.date, "2026", "year -> date") + t:eq(tags.track, "3/9", "track") + t:eq(tags.albumartist, "Band", "album artist") + t:eq(tags["cover art (front)"], nil, "binary item not a tag") + t:eq(info.start, 10, "start at the header") + t:eq(info.stop, #s, "stop") + t:eq(info.version, 2000, "version") + t:eq(#info.items, 6, "items") + t:eq(info.items[5].kind, "binary", "binary kind") + t:eq(info.items[5].value, "f.png\0PNG", "binary value") + -- ID3v1 after it + local s2 = s .. "TAG" .. string.rep("x", 125) + local tags2, info2 = ApeTag.find(buffer.fromstring(s2), 0, #s2) + t:check(tags2 and tags2.title == "Hello" and info2.stop == #s, "before ID3v1") + -- inside a sub-range + local s3 = "zz" .. s .. "yyy" + local tags3, info3 = ApeTag.find(buffer.fromstring(s3), 2, 2 + #s) + t:check(tags3 and tags3.title == "Hello" and info3.start == 12, "sub-range") + -- the start bounds the header + local tags4, info4 = ApeTag.find(b, 50, #s) + t:check(tags4 == nil and info4 == nil, "items before start") +end +do + local s = tag({ { "Title", "Old" } }, 1000, false) + local tags, info = ApeTag.find(buffer.fromstring(s), 0, #s) + t:check(tags and tags.title == "Old" and info.start == 0 and info.version == 1000, "v1") + t:eq(ApeTag.find(buffer.fromstring("no tag here at all, not even close to it"), 0, 40), nil, "none") +end +-- malformed: a huge item length, a huge count, a size larger than the file +do + local s = tag({ { "Title", "Hello" } }, 2000, false) + local bad = string.sub(s, 1, 0) .. u32(0x7FFFFFFF) .. string.sub(s, 5) + local tags = ApeTag.find(buffer.fromstring(bad), 0, #bad) + t:check(tags and tags.title == nil, "bad item length stops") + local big = string.sub(s, 1, #s - 32 + 12) .. u32(1e9) .. string.sub(s, #s - 32 + 17) + t:eq(ApeTag.find(buffer.fromstring(big), 0, #big), nil, "size past the start") +end + +local samples = { + buffer.fromstring("data" .. tag({ { "Title", "Hello" }, { "Artist", "X" } }, 2000, true)), + buffer.fromstring(tag({ { "A", "b" } }, 1000, false) .. "TAG" .. string.rep("\0", 125)), +} +t:fuzz("find", function(b: buffer) + return ApeTag.find(b, 0, buffer.len(b)) +end, samples, { mutations = 400 }) +t:done() diff --git a/tests/codecs/musepack.luau b/tests/codecs/musepack.luau new file mode 100644 index 0000000..1deb78b --- /dev/null +++ b/tests/codecs/musepack.luau @@ -0,0 +1,58 @@ +-- codecs/audio/Musepack tests: the codec API under audio/mpc: magic, the stream fields of SV7 / SV8 fixtures (version, +-- rate, channels, band count, packet layout, gapless length), packets decoded by hand against libmpcdec (the +-- synthesis delay at the front), out-of-order decodes, and a fuzz pass over open + every packet. Fixtures: +-- tools/fixtures/mpc.py. +local T = require("@tests/T") +local Musepack = require("@formats/codecs/audio/Musepack") +local Fx = require("@tests/gen/mpc_cases") + +local t = T.suite("codecs/musepack") + +for _, c in Fx do + local b = buffer.fromstring(c.data) + t:eq(Musepack.magic(b, 0, buffer.len(b)), c.version, c.name .. ": magic") + local s, err = Musepack.open(b, 0, buffer.len(b)) + t:check(s, c.name .. ": open: " .. tostring(err)) + if not s then + continue + end + t:check(s.version == c.version and s.sampleRate == c.rate and s.channels == c.channels, c.name .. ": fields") + t:eq(s.frames, c.frames, c.name .. ": gapless length") + t:check(s.maxBand >= 1 and s.maxBand <= 31 and s.count >= 1 and s.skip >= 481, c.name .. ": bands / packets") + t:eq(s.stop - s.skip, c.frames, c.name .. ": stop - skip = length") + -- the first packet by hand: output frame k is raw frame skip + k + local n = s.decode(1) + t:check(n and n > 0 and n % 1152 == 0 and n <= s.blockFrames * 1152, c.name .. ": first packet length") + local pcm = s.pcm() + local rb = buffer.fromstring(c.ref) + local ch = c.channels + local maxd = 0 + for k = 0, math.min(500, (n :: number) - s.skip - 1) do + for j = 1, ch do + maxd = math.max(maxd, math.abs(pcm[(s.skip + k) * ch + j] - buffer.readf32(rb, (k * ch + j - 1) * 4))) + end + end + t:check(maxd < 1e-5, string.format("%s: first packet matches libmpcdec (max diff %g)", c.name, maxd)) + if s.count >= 3 then + s.reset() + t:check(s.decode(3) ~= nil and s.decode(1) ~= nil, c.name .. ": decodes out of order after reset") + end +end + +local samples = {} +for _, c in Fx do + table.insert(samples, string.sub(c.data, 1, 2500)) +end +t:fuzz("open + every packet", function(b: buffer) + local s = Musepack.open(b, 0, buffer.len(b)) + if s then + for i = 1, math.min(s.count, 40) do + if not s.decode(i) then + break + end + end + end + return s +end, samples, { mutations = 25, keepHeader = 4 }) + +t:done() diff --git a/tests/fixtures/qoa/qoa.h b/tests/fixtures/qoa/qoa.h new file mode 100644 index 0000000..4f52be9 --- /dev/null +++ b/tests/fixtures/qoa/qoa.h @@ -0,0 +1,758 @@ +/* + +Copyright (c) 2023, Dominic Szablewski - https://phoboslab.org +SPDX-License-Identifier: MIT + +QOA - The "Quite OK Audio" format for fast, lossy audio compression + + +-- Data Format + +QOA encodes pulse-code modulated (PCM) audio data with up to 31 channels, +sample rates from 1 up to 16777215 hertz and a bit depth of 16 bits. + +The compression method employed in QOA is lossy; it discards some information +from the uncompressed PCM data. For many types of audio signals this compression +is "transparent", i.e. the difference from the original file is often not +audible. + +QOA encodes 20 samples of 16 bit PCM data into slices of 64 bits. A single +sample therefore requires 3.2 bits of storage space, resulting in a 5x +compression (16 / 3.2). + +A QOA file consists of an 8 byte file header, followed by a number of frames. +Each frame contains an 8 byte frame header, the current 16 byte en-/decoder +state per channel and 256 slices per channel. Each slice is 8 bytes wide and +encodes 20 samples of audio data. + +All values, including the slices, are big endian. The file layout is as follows: + +struct { + struct { + char magic[4]; // magic bytes "qoaf" + uint32_t samples; // samples per channel in this file + } file_header; + + struct { + struct { + uint8_t num_channels; // no. of channels + uint24_t samplerate; // samplerate in hz + uint16_t fsamples; // samples per channel in this frame + uint16_t fsize; // frame size (includes this header) + } frame_header; + + struct { + int16_t history[4]; // most recent last + int16_t weights[4]; // most recent last + } lms_state[num_channels]; + + qoa_slice_t slices[256][num_channels]; + + } frames[ceil(samples / (256 * 20))]; +} qoa_file_t; + +Each `qoa_slice_t` contains a quantized scalefactor `sf_quant` and 20 quantized +residuals `qrNN`: + +.- QOA_SLICE -- 64 bits, 20 samples --------------------------/ /------------. +| Byte[0] | Byte[1] | Byte[2] \ \ Byte[7] | +| 7 6 5 4 3 2 1 0 | 7 6 5 4 3 2 1 0 | 7 6 5 / / 2 1 0 | +|------------+--------+--------+--------+---------+---------+-\ \--+---------| +| sf_quant | qr00 | qr01 | qr02 | qr03 | qr04 | / / | qr19 | +`-------------------------------------------------------------\ \------------` + +Each frame except the last must contain exactly 256 slices per channel. The last +frame may contain between 1 .. 256 (inclusive) slices per channel. The last +slice (for each channel) in the last frame may contain less than 20 samples; the +slice still must be 8 bytes wide, with the unused samples zeroed out. + +Channels are interleaved per slice. E.g. for 2 channel stereo: +slice[0] = L, slice[1] = R, slice[2] = L, slice[3] = R ... + +A valid QOA file or stream must have at least one frame. Each frame must contain +at least one channel and one sample with a samplerate between 1 .. 16777215 +(inclusive). + +If the total number of samples is not known by the encoder, the samples in the +file header may be set to 0x00000000 to indicate that the encoder is +"streaming". In a streaming context, the samplerate and number of channels may +differ from frame to frame. For static files (those with samples set to a +non-zero value), each frame must have the same number of channels and same +samplerate. + +Note that this implementation of QOA only handles files with a known total +number of samples. + +A decoder should support at least 8 channels. The channel layout for channel +counts 1 .. 8 is: + + 1. Mono + 2. L, R + 3. L, R, C + 4. FL, FR, B/SL, B/SR + 5. FL, FR, C, B/SL, B/SR + 6. FL, FR, C, LFE, B/SL, B/SR + 7. FL, FR, C, LFE, B, SL, SR + 8. FL, FR, C, LFE, BL, BR, SL, SR + +QOA predicts each audio sample based on the previously decoded ones using a +"Sign-Sign Least Mean Squares Filter" (LMS). This prediction plus the +dequantized residual forms the final output sample. + +*/ + + + +/* ----------------------------------------------------------------------------- + Header - Public functions */ + +#ifndef QOA_H +#define QOA_H + +#ifdef __cplusplus +extern "C" { +#endif + +#define QOA_MIN_FILESIZE 16 +#define QOA_MAX_CHANNELS 8 + +#define QOA_SLICE_LEN 20 +#define QOA_SLICES_PER_FRAME 256 +#define QOA_FRAME_LEN (QOA_SLICES_PER_FRAME * QOA_SLICE_LEN) +#define QOA_LMS_LEN 4 +#define QOA_MAGIC 0x716f6166 /* 'qoaf' */ + +#define QOA_FRAME_SIZE(channels, slices) \ + (8 + QOA_LMS_LEN * 4 * channels + 8 * slices * channels) + +typedef struct { + int history[QOA_LMS_LEN]; + int weights[QOA_LMS_LEN]; +} qoa_lms_t; + +typedef struct { + unsigned int channels; + unsigned int samplerate; + unsigned int samples; + qoa_lms_t lms[QOA_MAX_CHANNELS]; + #ifdef QOA_RECORD_TOTAL_ERROR + double error; + #endif +} qoa_desc; + +unsigned int qoa_encode_header(qoa_desc *qoa, unsigned char *bytes); +unsigned int qoa_encode_frame(const short *sample_data, qoa_desc *qoa, unsigned int frame_len, unsigned char *bytes); +void *qoa_encode(const short *sample_data, qoa_desc *qoa, unsigned int *out_len); + +unsigned int qoa_max_frame_size(qoa_desc *qoa); +unsigned int qoa_decode_header(const unsigned char *bytes, int size, qoa_desc *qoa); +unsigned int qoa_decode_frame(const unsigned char *bytes, unsigned int size, qoa_desc *qoa, short *sample_data, unsigned int *frame_len); +short *qoa_decode(const unsigned char *bytes, int size, qoa_desc *file); + +#ifndef QOA_NO_STDIO + +int qoa_write(const char *filename, const short *sample_data, qoa_desc *qoa); +void *qoa_read(const char *filename, qoa_desc *qoa); + +#endif /* QOA_NO_STDIO */ + + +#ifdef __cplusplus +} +#endif +#endif /* QOA_H */ + + +/* ----------------------------------------------------------------------------- + Implementation */ + +#ifdef QOA_IMPLEMENTATION +#include + +#ifndef QOA_MALLOC + #define QOA_MALLOC(sz) malloc(sz) + #define QOA_FREE(p) free(p) +#endif + +typedef unsigned long long qoa_uint64_t; + + +/* The quant_tab provides an index into the dequant_tab for residuals in the +range of -8 .. 8. It maps this range to just 3bits and becomes less accurate at +the higher end. Note that the residual zero is identical to the lowest positive +value. This is mostly fine, since the qoa_div() function always rounds away +from zero. */ + +static const int qoa_quant_tab[17] = { + 7, 7, 7, 5, 5, 3, 3, 1, /* -8..-1 */ + 0, /* 0 */ + 0, 2, 2, 4, 4, 6, 6, 6 /* 1.. 8 */ +}; + + +/* We have 16 different scalefactors. Like the quantized residuals these become +less accurate at the higher end. In theory, the highest scalefactor that we +would need to encode the highest 16bit residual is (2**16)/8 = 8192. However we +rely on the LMS filter to predict samples accurately enough that a maximum +residual of one quarter of the 16 bit range is sufficient. I.e. with the +scalefactor 2048 times the quant range of 8 we can encode residuals up to 2**14. + +The scalefactor values are computed as: +scalefactor_tab[s] <- round(pow(s + 1, 2.75)) */ + +static const int qoa_scalefactor_tab[16] = { + 1, 7, 21, 45, 84, 138, 211, 304, 421, 562, 731, 928, 1157, 1419, 1715, 2048 +}; + + +/* The reciprocal_tab maps each of the 16 scalefactors to their rounded +reciprocals 1/scalefactor. This allows us to calculate the scaled residuals in +the encoder with just one multiplication instead of an expensive division. We +do this in .16 fixed point with integers, instead of floats. + +The reciprocal_tab is computed as: +reciprocal_tab[s] <- ((1<<16) + scalefactor_tab[s] - 1) / scalefactor_tab[s] */ + +static const int qoa_reciprocal_tab[16] = { + 65536, 9363, 3121, 1457, 781, 475, 311, 216, 156, 117, 90, 71, 57, 47, 39, 32 +}; + + +/* The dequant_tab maps each of the scalefactors and quantized residuals to +their unscaled & dequantized version. + +Since qoa_div rounds away from the zero, the smallest entries are mapped to 3/4 +instead of 1. The dequant_tab assumes the following dequantized values for each +of the quant_tab indices and is computed as: +float dqt[8] = {0.75, -0.75, 2.5, -2.5, 4.5, -4.5, 7, -7}; +dequant_tab[s][q] <- round_ties_away_from_zero(scalefactor_tab[s] * dqt[q]) + +The rounding employed here is "to nearest, ties away from zero", i.e. positive +and negative values are treated symmetrically. +*/ + +static const int qoa_dequant_tab[16][8] = { + { 1, -1, 3, -3, 5, -5, 7, -7}, + { 5, -5, 18, -18, 32, -32, 49, -49}, + { 16, -16, 53, -53, 95, -95, 147, -147}, + { 34, -34, 113, -113, 203, -203, 315, -315}, + { 63, -63, 210, -210, 378, -378, 588, -588}, + { 104, -104, 345, -345, 621, -621, 966, -966}, + { 158, -158, 528, -528, 950, -950, 1477, -1477}, + { 228, -228, 760, -760, 1368, -1368, 2128, -2128}, + { 316, -316, 1053, -1053, 1895, -1895, 2947, -2947}, + { 422, -422, 1405, -1405, 2529, -2529, 3934, -3934}, + { 548, -548, 1828, -1828, 3290, -3290, 5117, -5117}, + { 696, -696, 2320, -2320, 4176, -4176, 6496, -6496}, + { 868, -868, 2893, -2893, 5207, -5207, 8099, -8099}, + {1064, -1064, 3548, -3548, 6386, -6386, 9933, -9933}, + {1286, -1286, 4288, -4288, 7718, -7718, 12005, -12005}, + {1536, -1536, 5120, -5120, 9216, -9216, 14336, -14336}, +}; + + +/* The Least Mean Squares Filter is the heart of QOA. It predicts the next +sample based on the previous 4 reconstructed samples. It does so by continuously +adjusting 4 weights based on the residual of the previous prediction. + +The next sample is predicted as the sum of (weight[i] * history[i]). + +The adjustment of the weights is done with a "Sign-Sign-LMS" that adds or +subtracts the residual to each weight, based on the corresponding sample from +the history. This, surprisingly, is sufficient to get worthwhile predictions. + +This is all done with fixed point integers. Hence the right-shifts when updating +the weights and calculating the prediction. */ + +static int qoa_lms_predict(qoa_lms_t *lms) { + int prediction = 0; + for (int i = 0; i < QOA_LMS_LEN; i++) { + prediction += lms->weights[i] * lms->history[i]; + } + return prediction >> 13; +} + +static void qoa_lms_update(qoa_lms_t *lms, int sample, int residual) { + int delta = residual >> 4; + for (int i = 0; i < QOA_LMS_LEN; i++) { + lms->weights[i] += lms->history[i] < 0 ? -delta : delta; + } + + for (int i = 0; i < QOA_LMS_LEN-1; i++) { + lms->history[i] = lms->history[i+1]; + } + lms->history[QOA_LMS_LEN-1] = sample; +} + + +/* qoa_div() implements a rounding division, but avoids rounding to zero for +small numbers. E.g. 0.1 will be rounded to 1. Note that 0 itself still +returns as 0, which is handled in the qoa_quant_tab[]. +qoa_div() takes an index into the .16 fixed point qoa_reciprocal_tab as an +argument, so it can do the division with a cheaper integer multiplication. */ + +static inline int qoa_div(int v, int scalefactor) { + int reciprocal = qoa_reciprocal_tab[scalefactor]; + int n = (v * reciprocal + (1 << 15)) >> 16; + n = n + ((v > 0) - (v < 0)) - ((n > 0) - (n < 0)); /* round away from 0 */ + return n; +} + +static inline int qoa_clamp(int v, int min, int max) { + if (v < min) { return min; } + if (v > max) { return max; } + return v; +} + +/* This specialized clamp function for the signed 16 bit range improves decode +performance quite a bit. The extra if() statement works nicely with the CPUs +branch prediction as this branch is rarely taken. */ + +static inline int qoa_clamp_s16(int v) { + if ((unsigned int)(v + 32768) > 65535) { + if (v < -32768) { return -32768; } + if (v > 32767) { return 32767; } + } + return v; +} + +static inline qoa_uint64_t qoa_read_u64(const unsigned char *bytes, unsigned int *p) { + bytes += *p; + *p += 8; + return + ((qoa_uint64_t)(bytes[0]) << 56) | ((qoa_uint64_t)(bytes[1]) << 48) | + ((qoa_uint64_t)(bytes[2]) << 40) | ((qoa_uint64_t)(bytes[3]) << 32) | + ((qoa_uint64_t)(bytes[4]) << 24) | ((qoa_uint64_t)(bytes[5]) << 16) | + ((qoa_uint64_t)(bytes[6]) << 8) | ((qoa_uint64_t)(bytes[7]) << 0); +} + +static inline void qoa_write_u64(qoa_uint64_t v, unsigned char *bytes, unsigned int *p) { + bytes += *p; + *p += 8; + bytes[0] = (v >> 56) & 0xff; + bytes[1] = (v >> 48) & 0xff; + bytes[2] = (v >> 40) & 0xff; + bytes[3] = (v >> 32) & 0xff; + bytes[4] = (v >> 24) & 0xff; + bytes[5] = (v >> 16) & 0xff; + bytes[6] = (v >> 8) & 0xff; + bytes[7] = (v >> 0) & 0xff; +} + + +/* ----------------------------------------------------------------------------- + Encoder */ + +unsigned int qoa_encode_header(qoa_desc *qoa, unsigned char *bytes) { + unsigned int p = 0; + qoa_write_u64(((qoa_uint64_t)QOA_MAGIC << 32) | qoa->samples, bytes, &p); + return p; +} + +unsigned int qoa_encode_frame(const short *sample_data, qoa_desc *qoa, unsigned int frame_len, unsigned char *bytes) { + unsigned int channels = qoa->channels; + + unsigned int p = 0; + unsigned int slices = (frame_len + QOA_SLICE_LEN - 1) / QOA_SLICE_LEN; + unsigned int frame_size = QOA_FRAME_SIZE(channels, slices); + int prev_scalefactor[QOA_MAX_CHANNELS] = {0}; + + /* Write the frame header */ + qoa_write_u64(( + (qoa_uint64_t)qoa->channels << 56 | + (qoa_uint64_t)qoa->samplerate << 32 | + (qoa_uint64_t)frame_len << 16 | + (qoa_uint64_t)frame_size + ), bytes, &p); + + + for (unsigned int c = 0; c < channels; c++) { + /* Write the current LMS state */ + qoa_uint64_t weights = 0; + qoa_uint64_t history = 0; + for (int i = 0; i < QOA_LMS_LEN; i++) { + history = (history << 16) | (qoa->lms[c].history[i] & 0xffff); + weights = (weights << 16) | (qoa->lms[c].weights[i] & 0xffff); + } + qoa_write_u64(history, bytes, &p); + qoa_write_u64(weights, bytes, &p); + } + + /* We encode all samples with the channels interleaved on a slice level. + E.g. for stereo: (ch-0, slice 0), (ch 1, slice 0), (ch 0, slice 1), ...*/ + for (unsigned int sample_index = 0; sample_index < frame_len; sample_index += QOA_SLICE_LEN) { + + for (unsigned int c = 0; c < channels; c++) { + int slice_len = qoa_clamp(QOA_SLICE_LEN, 0, frame_len - sample_index); + int slice_start = sample_index * channels + c; + int slice_end = (sample_index + slice_len) * channels + c; + + /* Brute force search for the best scalefactor. Just go through all + 16 scalefactors, encode all samples for the current slice and + meassure the total squared error. */ + qoa_uint64_t best_rank = -1; + #ifdef QOA_RECORD_TOTAL_ERROR + qoa_uint64_t best_error = -1; + #endif + qoa_uint64_t best_slice = 0; + qoa_lms_t best_lms; + int best_scalefactor = 0; + + for (int sfi = 0; sfi < 16; sfi++) { + /* There is a strong correlation between the scalefactors of + neighboring slices. As an optimization, start testing + the best scalefactor of the previous slice first. */ + int scalefactor = (sfi + prev_scalefactor[c]) & (16 - 1); + + /* We have to reset the LMS state to the last known good one + before trying each scalefactor, as each pass updates the LMS + state when encoding. */ + qoa_lms_t lms = qoa->lms[c]; + qoa_uint64_t slice = scalefactor; + qoa_uint64_t current_rank = 0; + #ifdef QOA_RECORD_TOTAL_ERROR + qoa_uint64_t current_error = 0; + #endif + + for (int si = slice_start; si < slice_end; si += channels) { + int sample = sample_data[si]; + int predicted = qoa_lms_predict(&lms); + + int residual = sample - predicted; + int scaled = qoa_div(residual, scalefactor); + int clamped = qoa_clamp(scaled, -8, 8); + int quantized = qoa_quant_tab[clamped + 8]; + int dequantized = qoa_dequant_tab[scalefactor][quantized]; + int reconstructed = qoa_clamp_s16(predicted + dequantized); + + + /* If the weights have grown too large, we introduce a penalty + here. This prevents pops/clicks in certain problem cases */ + int weights_penalty = (( + lms.weights[0] * lms.weights[0] + + lms.weights[1] * lms.weights[1] + + lms.weights[2] * lms.weights[2] + + lms.weights[3] * lms.weights[3] + ) >> 18) - 0x8ff; + if (weights_penalty < 0) { + weights_penalty = 0; + } + + long long error = (sample - reconstructed); + qoa_uint64_t error_sq = error * error; + + current_rank += error_sq + weights_penalty * weights_penalty; + #ifdef QOA_RECORD_TOTAL_ERROR + current_error += error_sq; + #endif + if (current_rank > best_rank) { + break; + } + + qoa_lms_update(&lms, reconstructed, dequantized); + slice = (slice << 3) | quantized; + } + + if (current_rank < best_rank) { + best_rank = current_rank; + #ifdef QOA_RECORD_TOTAL_ERROR + best_error = current_error; + #endif + best_slice = slice; + best_lms = lms; + best_scalefactor = scalefactor; + } + } + + prev_scalefactor[c] = best_scalefactor; + + qoa->lms[c] = best_lms; + #ifdef QOA_RECORD_TOTAL_ERROR + qoa->error += best_error; + #endif + + /* If this slice was shorter than QOA_SLICE_LEN, we have to left- + shift all encoded data, to ensure the rightmost bits are the empty + ones. This should only happen in the last frame of a file as all + slices are completely filled otherwise. */ + best_slice <<= (QOA_SLICE_LEN - slice_len) * 3; + qoa_write_u64(best_slice, bytes, &p); + } + } + + return p; +} + +void *qoa_encode(const short *sample_data, qoa_desc *qoa, unsigned int *out_len) { + if ( + qoa->samples == 0 || + qoa->samplerate == 0 || qoa->samplerate > 0xffffff || + qoa->channels == 0 || qoa->channels > QOA_MAX_CHANNELS + ) { + return NULL; + } + + /* Calculate the encoded size and allocate */ + unsigned int num_frames = (qoa->samples + QOA_FRAME_LEN-1) / QOA_FRAME_LEN; + unsigned int num_slices = (qoa->samples + QOA_SLICE_LEN-1) / QOA_SLICE_LEN; + unsigned int encoded_size = 8 + /* 8 byte file header */ + num_frames * 8 + /* 8 byte frame headers */ + num_frames * QOA_LMS_LEN * 4 * qoa->channels + /* 4 * 4 bytes lms state per channel */ + num_slices * 8 * qoa->channels; /* 8 byte slices */ + + unsigned char *bytes = QOA_MALLOC(encoded_size); + + for (unsigned int c = 0; c < qoa->channels; c++) { + /* Set the initial LMS weights to {0, 0, -1, 2}. This helps with the + prediction of the first few ms of a file. */ + qoa->lms[c].weights[0] = 0; + qoa->lms[c].weights[1] = 0; + qoa->lms[c].weights[2] = -(1<<13); + qoa->lms[c].weights[3] = (1<<14); + + /* Explicitly set the history samples to 0, as we might have some + garbage in there. */ + for (int i = 0; i < QOA_LMS_LEN; i++) { + qoa->lms[c].history[i] = 0; + } + } + + + /* Encode the header and go through all frames */ + unsigned int p = qoa_encode_header(qoa, bytes); + #ifdef QOA_RECORD_TOTAL_ERROR + qoa->error = 0; + #endif + + int frame_len = QOA_FRAME_LEN; + for (unsigned int sample_index = 0; sample_index < qoa->samples; sample_index += frame_len) { + frame_len = qoa_clamp(QOA_FRAME_LEN, 0, qoa->samples - sample_index); + const short *frame_samples = sample_data + sample_index * qoa->channels; + unsigned int frame_size = qoa_encode_frame(frame_samples, qoa, frame_len, bytes + p); + p += frame_size; + } + + *out_len = p; + return bytes; +} + + + +/* ----------------------------------------------------------------------------- + Decoder */ + +unsigned int qoa_max_frame_size(qoa_desc *qoa) { + return QOA_FRAME_SIZE(qoa->channels, QOA_SLICES_PER_FRAME); +} + +unsigned int qoa_decode_header(const unsigned char *bytes, int size, qoa_desc *qoa) { + unsigned int p = 0; + if (size < QOA_MIN_FILESIZE) { + return 0; + } + + + /* Read the file header, verify the magic number ('qoaf') and read the + total number of samples. */ + qoa_uint64_t file_header = qoa_read_u64(bytes, &p); + + if ((file_header >> 32) != QOA_MAGIC) { + return 0; + } + + qoa->samples = file_header & 0xffffffff; + if (!qoa->samples) { + return 0; + } + + /* Peek into the first frame header to get the number of channels and + the samplerate. */ + qoa_uint64_t frame_header = qoa_read_u64(bytes, &p); + qoa->channels = (frame_header >> 56) & 0x0000ff; + qoa->samplerate = (frame_header >> 32) & 0xffffff; + + if ( + qoa->channels == 0 || qoa->samples == 0 || qoa->samplerate == 0 || + qoa->channels > QOA_MAX_CHANNELS + ) { + return 0; + } + + return 8; +} + +unsigned int qoa_decode_frame(const unsigned char *bytes, unsigned int size, qoa_desc *qoa, short *sample_data, unsigned int *frame_len) { + unsigned int p = 0; + if (frame_len) { + *frame_len = 0; + } + + if (size < 8 + QOA_LMS_LEN * 4 * qoa->channels) { + return 0; + } + + /* Read and verify the frame header */ + qoa_uint64_t frame_header = qoa_read_u64(bytes, &p); + unsigned int channels = (frame_header >> 56) & 0x0000ff; + unsigned int samplerate = (frame_header >> 32) & 0xffffff; + unsigned int samples = (frame_header >> 16) & 0x00ffff; + unsigned int frame_size = (frame_header ) & 0x00ffff; + + unsigned int header_size = 8 + QOA_LMS_LEN * 4 * channels; + unsigned int data_size = frame_size - header_size; + unsigned int max_total_slices = data_size / 8; + unsigned int num_slices = (samples + QOA_SLICE_LEN - 1) / QOA_SLICE_LEN; + + if ( + channels != qoa->channels || + samplerate != qoa->samplerate || + frame_size < header_size || + frame_size > size || + num_slices > QOA_SLICES_PER_FRAME || + num_slices * channels > max_total_slices + ) { + return 0; + } + + + /* Read the LMS state: 4 x 2 bytes history, 4 x 2 bytes weights per channel */ + for (unsigned int c = 0; c < channels; c++) { + qoa_uint64_t history = qoa_read_u64(bytes, &p); + qoa_uint64_t weights = qoa_read_u64(bytes, &p); + for (int i = 0; i < QOA_LMS_LEN; i++) { + qoa->lms[c].history[i] = ((signed short)(history >> 48)); + history <<= 16; + qoa->lms[c].weights[i] = ((signed short)(weights >> 48)); + weights <<= 16; + } + } + + + /* Decode all slices for all channels in this frame */ + for (unsigned int sample_index = 0; sample_index < samples; sample_index += QOA_SLICE_LEN) { + for (unsigned int c = 0; c < channels; c++) { + qoa_uint64_t slice = qoa_read_u64(bytes, &p); + + int scalefactor = (slice >> 60) & 0xf; + slice <<= 4; + + int slice_start = sample_index * channels + c; + int slice_end = qoa_clamp(sample_index + QOA_SLICE_LEN, 0, samples) * channels + c; + + for (int si = slice_start; si < slice_end; si += channels) { + int predicted = qoa_lms_predict(&qoa->lms[c]); + int quantized = (slice >> 61) & 0x7; + int dequantized = qoa_dequant_tab[scalefactor][quantized]; + int reconstructed = qoa_clamp_s16(predicted + dequantized); + + sample_data[si] = reconstructed; + slice <<= 3; + + qoa_lms_update(&qoa->lms[c], reconstructed, dequantized); + } + } + } + + if (frame_len) { + *frame_len = samples; + } + return p; +} + +short *qoa_decode(const unsigned char *bytes, int size, qoa_desc *qoa) { + unsigned int p = qoa_decode_header(bytes, size, qoa); + if (!p) { + return NULL; + } + + /* Calculate the required size of the sample buffer and allocate, round up to full frames */ + unsigned long long num_frames = ((unsigned long long)qoa->samples + QOA_FRAME_LEN - 1) / QOA_FRAME_LEN; + unsigned long long total_samples_ull = num_frames * QOA_FRAME_LEN * (unsigned long long)qoa->channels; + + if (total_samples_ull > 0x7fffffff) { return NULL; } + + unsigned int total_samples = (unsigned int)total_samples_ull; + short *sample_data = QOA_MALLOC(total_samples * sizeof(short)); + if (!sample_data) { return NULL; } + + unsigned int sample_index = 0; + unsigned int frame_len; + unsigned int frame_size; + + /* Decode all frames */ + do { + short *sample_ptr = sample_data + sample_index * qoa->channels; + frame_size = qoa_decode_frame(bytes + p, size - p, qoa, sample_ptr, &frame_len); + + p += frame_size; + sample_index += frame_len; + } while (frame_len == QOA_FRAME_LEN && sample_index < qoa->samples); + + qoa->samples = sample_index; + return sample_data; +} + + + +/* ----------------------------------------------------------------------------- + File read/write convenience functions */ + +#ifndef QOA_NO_STDIO +#include + +int qoa_write(const char *filename, const short *sample_data, qoa_desc *qoa) { + FILE *f = fopen(filename, "wb"); + unsigned int size; + void *encoded; + + if (!f) { + return 0; + } + + encoded = qoa_encode(sample_data, qoa, &size); + if (!encoded) { + fclose(f); + return 0; + } + + fwrite(encoded, 1, size, f); + fclose(f); + + QOA_FREE(encoded); + return size; +} + +void *qoa_read(const char *filename, qoa_desc *qoa) { + FILE *f = fopen(filename, "rb"); + int size, bytes_read; + void *data; + short *sample_data; + + if (!f) { + return NULL; + } + + fseek(f, 0, SEEK_END); + size = ftell(f); + if (size <= 0) { + fclose(f); + return NULL; + } + fseek(f, 0, SEEK_SET); + + data = QOA_MALLOC(size); + if (!data) { + fclose(f); + return NULL; + } + + bytes_read = fread(data, 1, size, f); + fclose(f); + + sample_data = qoa_decode(data, bytes_read, qoa); + QOA_FREE(data); + return sample_data; +} + +#endif /* QOA_NO_STDIO */ +#endif /* QOA_IMPLEMENTATION */ diff --git a/tests/fixtures/qoa/qoa_ref.c b/tests/fixtures/qoa/qoa_ref.c new file mode 100644 index 0000000..f691b54 --- /dev/null +++ b/tests/fixtures/qoa/qoa_ref.c @@ -0,0 +1,52 @@ +/* tests/fixtures/qoa/qoa_ref.c: the qoa.h reference encoder / decoder for tools/fixtures/qoa.py. + qoa_ref enc encode raw interleaved s16le with qoa_encode + qoa_ref dec decode with qoa_decode (prints channels rate samples) */ +#include +#include +#include +#define QOA_IMPLEMENTATION +#include "qoa.h" + +static unsigned char *slurp(const char *path, long *size) { + FILE *f = fopen(path, "rb"); + if (!f) return NULL; + fseek(f, 0, SEEK_END); + *size = ftell(f); + fseek(f, 0, SEEK_SET); + unsigned char *d = malloc(*size ? *size : 1); + if (fread(d, 1, *size, f) != (size_t)*size) { fclose(f); return NULL; } + fclose(f); + return d; +} + +int main(int argc, char **argv) { + if (argc == 6 && !strcmp(argv[1], "enc")) { + long size; + short *pcm = (short *)slurp(argv[4], &size); + qoa_desc q; + memset(&q, 0, sizeof q); + q.channels = atoi(argv[2]); + q.samplerate = atoi(argv[3]); + q.samples = size / 2 / q.channels; + unsigned int len; + void *out = qoa_encode(pcm, &q, &len); + if (!out) return 1; + FILE *f = fopen(argv[5], "wb"); + fwrite(out, 1, len, f); + fclose(f); + return 0; + } + if (argc == 4 && !strcmp(argv[1], "dec")) { + long size; + unsigned char *d = slurp(argv[2], &size); + qoa_desc q; + short *pcm = qoa_decode(d, (int)size, &q); + if (!pcm) return 1; + FILE *f = fopen(argv[3], "wb"); + fwrite(pcm, 2, (size_t)q.samples * q.channels, f); + fclose(f); + printf("%u %u %u\n", q.channels, q.samplerate, q.samples); + return 0; + } + return 2; +} diff --git a/tests/music/669.luau b/tests/music/669.luau new file mode 100644 index 0000000..668b967 --- /dev/null +++ b/tests/music/669.luau @@ -0,0 +1,19 @@ +-- music/669 tests: generated Composer 669 / UNIS 669 modules (tools/fixtures/669.py) parsed, rendered through +-- codecs/audio/Tracker and compared with openmpt123's render (loudness envelope, band spectrum, stereo balance, song +-- length), the contract, and the fuzz no-throw pass. +local T = require("@tests/T") +local S = require("@tests/music/_similar") +local Six69 = require("@formats/music/669") +local Cases = require("@tests/gen/669_cases") + +local t = T.suite("669") + +t:eq(Six69.name, "669", "name") +t:eq(Six69.category, "music", "category") +t:check(Six69.caps.decode and not Six69.caps.encode, "caps") + +local mods = S.against(t, Six69, Cases, { gainDb = 0.5, envErr = 1.0, spectral = 0.95, balance = 0.04, duration = 0.01 }, "s3m") +t:check(mods[2] and mods[2].meta.source.tracker == "UNIS 669", "UNIS 669") + +t:fuzz("decode", S.fuzzer(Six69), S.samples(Cases), { mutations = 30 }) +t:done() diff --git a/tests/music/_hively.luau b/tests/music/_hively.luau new file mode 100644 index 0000000..4081503 --- /dev/null +++ b/tests/music/_hively.luau @@ -0,0 +1,45 @@ +-- tests/music/_hively: shared helper of the AHX / HVL tests (not a test itself): renders a fixture case through the +-- format and compares it with hvl2wav's output exactly (16-bit samples: CRC-32 of the whole stream, the first +-- differing frame located inside the raw head kept by tools/fixtures/ahx.py / hvl.py). +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") + +local H = {} + +-- check(t, Format, c): decode + render + exact comparison; returns the song +function H.check(t: any, Format: any, c: any): any + local song, err = Format.decode(Bytes.reader(buffer.fromstring(c.data))) + t:check(song, c.name .. ": " .. tostring(err)) + if not song then + return nil + end + t:check(Format.sniff(Bytes.reader(buffer.fromstring(c.data))) == 1, c.name .. ": sniff") + local dec = song:render({ sampleRate = c.sampleRate, stereo = c.stereo, subsong = c.subsong, maxDuration = c.maxDuration }) + t:check(dec.err == nil, c.name .. ": render " .. tostring(dec.err)) + local frames = if c.prefix then math.min(dec.frames, c.frames) else dec.frames + if not c.prefix then + t:eq(dec.frames, c.frames, c.name .. ": frames (song end as hvl2wav finds it)") + end + local f32 = dec:read(frames) + local s16 = buffer.create(frames * 4) + for i = 0, frames * 2 - 1 do + buffer.writei16(s16, i * 2, math.floor(buffer.readf32(f32, i * 4) * 32768 + 0.5)) + end + -- (a time-limited reference whose song ends earlier than the limit: only the head can be compared) + local exact = (frames == c.frames and Crc32.of(s16) == c.crc) or (c.prefix and frames < c.frames) + local head = buffer.fromstring(c.head) + local firstDiff = -1 + for i = 0, math.min(frames, buffer.len(head) // 4) * 2 - 1 do + if buffer.readi16(s16, i * 2) ~= buffer.readi16(head, i * 2) then + firstDiff = i // 2 + break + end + end + t:check(firstDiff < 0, string.format("%s: first differing frame %d (ours %d, hvl2wav %d)", c.name, firstDiff, + if firstDiff >= 0 then buffer.readi16(s16, firstDiff * 4) else 0, if firstDiff >= 0 then buffer.readi16(head, firstDiff * 4) else 0)) + t:check(exact, c.name .. ": samples equal hvl2wav's (CRC-32 of " .. frames .. " frames)") + t:note("%-22s %6d frames %s", c.name, frames, if exact and firstDiff < 0 then "bit-exact vs hvl2wav" else "DIFFERS") + return song +end + +return H diff --git a/tests/music/_midivar.luau b/tests/music/_midivar.luau new file mode 100644 index 0000000..2461821 --- /dev/null +++ b/tests/music/_midivar.luau @@ -0,0 +1,92 @@ +-- tests/music/_midivar: shared helper of the MUS / XMI / HMP tests (not a test itself): compares a decoded Midi's +-- channel events (codecs/audio/MidiRender.timeline: play order, seconds) with wildmidi -x's conversion +-- (tools/fixtures/_midivar.py): notes on / off, program changes, pitch bends (MSB) and controllers, matched per +-- (kind, channel, data) in time order, times within 0.1 ms + 1e-5 relative. +local Render = require("@formats/codecs/audio/MidiRender") + +local M = {} + +local function kindOf(status: number, d1: number, d2: number): string? + local hi = status // 16 + if hi == 9 and d2 > 0 then + return "on" + elseif hi == 8 or hi == 9 then + return "off" + elseif hi == 12 then + return "program" + elseif hi == 14 then + return "bend" + elseif hi == 11 then + return "cc" + end + return nil +end + +-- the comparable events of a list of { seconds, status, d1, d2 }: key -> { seconds } +local function index(list: { { number } }, opts: any): ({ [string]: { number } }, { [string]: number }) + local by: { [string]: { number } }, counts: { [string]: number } = {}, {} + for _, e in list do + local k = kindOf(e[2], e[3], e[4]) + if k and not (opts.skip and opts.skip[k]) then + local d = if k == "bend" then e[4] elseif k == "cc" then e[3] * 256 + e[4] else e[3] + local key = string.format("%s %d %d", k, e[2] % 16, d) + by[key] = by[key] or {} + table.insert(by[key], e[1]) + counts[k] = (counts[k] or 0) + 1 + end + end + return by, counts +end + +-- compare(t, midi, ref, label, opts?) -> worst time difference (s). opts.skip = { cc = true, ... } +function M.compare(t: any, midi: any, ref: any, label: string, opts: any?): number + local o = opts or {} + local tl = Render.timeline(midi) + local ours = {} + local refEnd = 0 + for _, e in ref.events do + refEnd = math.max(refEnd, e[1]) + end + for i = 1, #tl.time do + -- o.hangingOffs: wildmidi drops the note-offs past the end of the song (we end those notes at the end) + local hanging = o.hangingOffs and kindOf(tl.status[i], tl.d1[i], tl.d2[i]) == "off" and tl.time[i] > refEnd + 1e-6 + if not hanging then + table.insert(ours, { tl.time[i], tl.status[i], tl.d1[i], tl.d2[i] }) + end + end + local a, ca = index(ours, o) + local b, cb = index(ref.events, o) + for _, k in { "on", "off", "program", "bend", "cc" } do + if not (o.skip and o.skip[k]) then + t:eq(ca[k] or 0, cb[k] or 0, label .. ": " .. k .. " events") + end + end + local worst, bad = 0, 0 + for key, times in b do + local mine = a[key] or {} + table.sort(times) + table.sort(mine) + if #mine ~= #times then + bad += 1 + if bad <= 3 then + t:check(false, string.format("%s: %s: %d events, wildmidi %d", label, key, #mine, #times)) + end + else + for i, tm in times do + local d = math.abs(mine[i] - tm) + worst = math.max(worst, d) + if d > 1e-4 + 1e-5 * tm then + bad += 1 + if bad <= 3 then + t:check(false, string.format("%s: %s at %.4f s, wildmidi %.4f s", label, key, mine[i], tm)) + end + end + end + end + end + t:check(bad == 0, label .. ": event times match wildmidi's") + t:note("%-12s %4d notes, worst time difference %.2g s", label, ca.on or 0, worst) + return worst +end + +return M diff --git a/tests/music/_similar.luau b/tests/music/_similar.luau index e97f7eb..50127be 100644 --- a/tests/music/_similar.luau +++ b/tests/music/_similar.luau @@ -206,4 +206,79 @@ function S.worst(a: any, b: any, count: number): { { number } } return out end +-- against(t, Fmt, cases, thresh, family?): the shared body of the tracker loader tests (ws-audio2: mtm, 669, stm, ult, +-- okt, med, ptm, far, umx): each case decodes, sniffs, plays as long as openmpt's render (thresh.duration s) and +-- matches its loudness / envelope / spectrum / balance within thresh; then a seek. cases: { name, data, ref, +-- duration }. Returns the decoded modules. The tests run their fuzz pass with S.fuzzer / S.samples. +function S.against(t: any, Fmt: any, cases: { any }, thresh: any, family: string?): { any } + local Bytes = require("@formats/core/Bytes") + local Tracker = require("@formats/codecs/audio/Tracker") + local mods = {} + for _, c in cases do + local m, err = Fmt.decode(Bytes.reader(buffer.fromstring(c.data))) + t:check(m, c.name .. ": " .. tostring(err)) + if not m then + continue + end + table.insert(mods, m) + t:eq(m.format, Fmt.name, c.name .. ": format") + if family then + t:eq(Tracker.family(m), family, c.name .. ": engine family") + end + t:check(Fmt.sniff(Bytes.reader(buffer.fromstring(c.data))) > 0, c.name .. ": sniff") + local dec = m:render({ sampleRate = S.SR }) + t:check(dec, c.name .. ": render") + t:check(math.abs(dec.duration - c.duration) < thresh.duration, string.format("%s: duration %.3f s, openmpt %.3f s", c.name, dec.duration, c.duration)) + local buf, frames = S.renderAll(dec, math.floor(c.duration * S.SR)) + local f = S.features(buf, frames) + local r = S.compare(f, c.ref) + t:note("%-8s gain %+.2f dB, loudness error %.2f dB, spectrum %.3f, balance %.3f, %.2f s", c.name, r.gainDb, r.envErr, r.spectral, r.balance, dec.duration) + if r.spectral < thresh.spectral or r.envErr > thresh.envErr then + for _, w in S.worst(f, c.ref, 6) do + t:note(" block %d (%.2f s): spectrum %.3f, ours %.1f dB, ref %.1f dB", w[1], (w[1] - 1) * 2048 / S.SR, w[2], w[3], w[4]) + end + end + t:check(math.abs(r.gainDb) < thresh.gainDb, c.name .. ": loudness") + t:check(r.envErr < thresh.envErr, c.name .. ": loudness envelope") + t:check(r.spectral > thresh.spectral, c.name .. ": spectrum") + t:check(r.balance < thresh.balance, c.name .. ": stereo balance") + end + -- seek: the position after a seek and the output continuing + local m = mods[1] + if m then + local dec = m:render() + dec:seek(1) + t:check(math.abs(dec:position() - 1) < 0.001, "seek position") + local _, n = dec:read(1000) + t:eq(n, 1000, "read after seek") + t:check(Tracker.duration(m) == dec.duration, "duration()") + end + return mods +end + +-- fuzzer(Fmt) -> the fuzz function of a tracker loader: decode, and a short render of whatever decodes +function S.fuzzer(Fmt: any): (buffer) -> any + local Bytes = require("@formats/core/Bytes") + local Tracker = require("@formats/codecs/audio/Tracker") + return function(b: buffer): any + local fm = Fmt.decode(Bytes.reader(b)) + if fm then + local d = Tracker.render(fm, { maxDuration = 0.5, sampleRate = 8000 }) + if d then + d:read(4000) + end + end + return fm + end +end + +-- samples(cases) -> the fuzz seeds (each case's data) +function S.samples(cases: { any }): { string } + local out = {} + for _, c in cases do + table.insert(out, c.data) + end + return out +end + return S diff --git a/tests/music/ahx.luau b/tests/music/ahx.luau new file mode 100644 index 0000000..adc9bc1 --- /dev/null +++ b/tests/music/ahx.luau @@ -0,0 +1,79 @@ +-- music/ahx tests: AHX songs written by tools/fixtures/_hively.py (every waveform, filter and square sweeps, PList +-- commands, effects, subsongs, AHX versions 0..2) and karma.ahx from the HivelyTracker source, rendered through +-- codecs/audio/Hively and compared sample for sample with hvl2wav at several stereo separations and rates; the Module +-- shape, bad input, and the fuzz no-throw pass. Fixtures: tools/fixtures/ahx.py. +local T = require("@tests/T") +local H = require("@tests/music/_hively") +local Ahx = require("@formats/music/ahx") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Cases = require("@tests/gen/ahx_cases") + +local t = T.suite("ahx") + +t:eq(Ahx.name, "ahx", "name") +t:eq(Ahx.category, "music", "category") +t:check(Ahx.caps.decode and not Ahx.caps.encode, "caps") +t:eq(Ahx.sniff(Bytes.reader(buffer.fromstring("HVL\1"))), 0, "sniff HVL") + +local samples = {} +for _, c in Cases do + local song = H.check(t, Ahx, c) + if song and c.name == "demo" then + t:eq(song.kind, "music", "kind") + t:eq(song.format, "ahx", "format") + t:eq(song.title, "demo", "title") + t:eq(song.channels, 4, "channels") + t:eq(#song.order, 2, "positions") + t:eq(song.instruments[1].name, "tri", "instrument name") + t:eq(#song.instruments[3].plist.entries, 4, "play list") + t:eq(song.patterns[2].rows, 16, "track rows") + t:eq(buffer.readu8(song.patterns[2].data, 0), 25, "track 1 row 0 note") + t:eq(#song.subsongs, 1, "subsongs") + -- seek back and read again: the same samples + local dec = song:render() + local a = dec:read(4410) + dec:seek(0.5) + dec:seek(0) + local b = dec:read(4410) + t:check(buffer.tostring(a) == buffer.tostring(b), "seek restarts exactly") + end + if #samples < 4 then + table.insert(samples, buffer.fromstring(c.data)) + end +end + +-- bad input +local function code(s: string): string? + local _, e = Ahx.decode(Bytes.reader(buffer.fromstring(s))) + return e and e.code +end +t:eq(code("THX"), Err.TRUNCATED, "short header") +t:eq(code("THX\1\0\14\0\0\0\0\16\0\0\0"), Err.CORRUPT, "no positions") +t:eq(code(string.sub(Cases[1].data, 1, 60)), Err.TRUNCATED, "truncated") +local song = assert(Ahx.decode(Bytes.reader(buffer.fromstring(Cases[1].data)))) +t:check(song:render({ subsong = 9 }).err ~= nil, "subsong out of range") + +-- through the api: a Module saved as audio renders through its own engine +do + local F = require("@formats") + local wav, err = F.save(song, nil, { format = "wav", sampleRate = 22050 }) + t:check(wav, "F.save as wav: " .. tostring(err)) + t:eq(F.detect(wav :: buffer), "wav", "F.save as wav") + t:eq(F.detect(buffer.fromstring(Cases[1].data)), "ahx", "F.detect") + local _, e2 = F.save(song, nil, { format = "wav", subsong = 7 }) + t:check(e2 ~= nil, "F.save: a failed render is an error") +end + +t:fuzz("decode", function(b: buffer) + return Ahx.decode(Bytes.reader(b)) +end, samples) +t:fuzz("decode + render", function(b: buffer) + local s = Ahx.decode(Bytes.reader(b)) + if s then + local d = s:render({ sampleRate = 8000, maxDuration = 0.5 }) + d:read(4000) + end + return s +end, samples, { mutations = 150, garbage = 20 }) +t:done() diff --git a/tests/music/far.luau b/tests/music/far.luau new file mode 100644 index 0000000..f5b1abb --- /dev/null +++ b/tests/music/far.luau @@ -0,0 +1,19 @@ +-- music/far tests: generated Farandole Composer modules (tools/fixtures/far.py) parsed, rendered through +-- codecs/audio/Tracker and compared with openmpt123's render (loudness envelope, band spectrum, stereo balance, song +-- length), the contract, and the fuzz no-throw pass. +local T = require("@tests/T") +local S = require("@tests/music/_similar") +local Far = require("@formats/music/far") +local Cases = require("@tests/gen/far_cases") + +local t = T.suite("far") + +t:eq(Far.name, "far", "name") +t:eq(Far.category, "music", "category") +t:check(Far.caps.decode and not Far.caps.encode, "caps") + +local mods = S.against(t, Far, Cases, { gainDb = 0.5, envErr = 1.0, spectral = 0.95, balance = 0.04, duration = 0.01 }, "s3m") +t:check(mods[1] and mods[1].patterns[2].rows == 48 and mods[1].channelMute[10], "pattern length, muted channel") + +t:fuzz("decode", S.fuzzer(Far), S.samples(Cases), { mutations = 30 }) +t:done() diff --git a/tests/music/hmp.luau b/tests/music/hmp.luau new file mode 100644 index 0000000..944f2a8 --- /dev/null +++ b/tests/music/hmp.luau @@ -0,0 +1,57 @@ +-- music/hmp tests: HMP (old and "013195" headers, several tick rates) and HMI files (tools/fixtures/hmp.py) decoded and +-- compared with wildmidi -x's conversion (notes, HMI note durations, programs, bends, controllers), the FE / loop +-- events skipped, a render, bad input, and the fuzz no-throw pass. +local T = require("@tests/T") +local V = require("@tests/music/_midivar") +local Hmp = require("@formats/music/hmp") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Cases = require("@tests/gen/hmp_cases") + +local t = T.suite("hmp") + +local function decode(s: string, opts: any?): (any, any) + return Hmp.decode(Bytes.reader(buffer.fromstring(s)), opts) +end + +t:eq(Hmp.name, "hmp", "name") +t:check(Hmp.caps.decode and not Hmp.caps.encode, "caps") +t:eq(Hmp.sniff(Bytes.reader(buffer.fromstring("HMIMIDIP013195"))), 1, "sniff HMP") +t:eq(Hmp.sniff(Bytes.reader(buffer.fromstring("HMI-MIDISONG061595"))), 1, "sniff HMI") +t:eq(Hmp.sniff(Bytes.reader(buffer.fromstring("HMI-MIDITRACK"))), 0, "sniff other") + +local samples = {} +for _, c in Cases do + local m, err = decode(c.data) + t:check(m, c.name .. ": " .. tostring(err)) + if m then + t:eq(m.meta.source.format, c.kind, c.name .. ": kind") + t:eq(m.meta.source.rate, c.rate, c.name .. ": tick rate") + V.compare(t, m, c.ref, c.name) + end + table.insert(samples, buffer.fromstring(c.data)) +end + +do + local m = assert(decode(Cases[1].data)) + local dec = m:render({ sampleRate = 22050, tail = 0.2 }) + t:check(math.abs(dec.duration - (m.meta.length + 0.2)) < 0.01, "render duration") +end + +local _, e1 = decode("HMIMIDIP") +t:eq(e1 and e1.code, Err.TRUNCATED, "short header") +local bad = string.sub(Cases[1].data, 1, 0x308 + 20) +local _, e2 = decode(bad) +t:eq(e2 and e2.code, Err.TRUNCATED, "truncated chunk") + +t:fuzz("decode", function(b: buffer) + return Hmp.decode(Bytes.reader(b)) +end, samples) +t:fuzz("decode + render", function(b: buffer) + local m = Hmp.decode(Bytes.reader(b)) + if m and m.meta.length < 30 then + m:render({ sampleRate = 8000 }):read(2000) + end + return m +end, samples, { mutations = 60, garbage = 10 }) +t:done() diff --git a/tests/music/hvl.luau b/tests/music/hvl.luau new file mode 100644 index 0000000..cf4fbdb --- /dev/null +++ b/tests/music/hvl.luau @@ -0,0 +1,71 @@ +-- music/hvl tests: HVL songs written by tools/fixtures/_hively.py (4..8 channels, two effect columns, ring modulation, +-- panning, mix gain / stereo from the file, subsongs) and songs from the HivelyTracker source, rendered through +-- codecs/audio/Hively and compared sample for sample with hvl2wav (44.1 and 48 kHz); the Module shape, bad input, and +-- the fuzz no-throw pass. Fixtures: tools/fixtures/hvl.py. +local T = require("@tests/T") +local H = require("@tests/music/_hively") +local Hvl = require("@formats/music/hvl") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Cases = require("@tests/gen/hvl_cases") + +local t = T.suite("hvl") + +t:eq(Hvl.name, "hvl", "name") +t:eq(Hvl.category, "music", "category") +t:check(Hvl.caps.decode and not Hvl.caps.encode, "caps") +t:eq(Hvl.sniff(Bytes.reader(buffer.fromstring("THX\1"))), 0, "sniff AHX") + +local samples = {} +for _, c in Cases do + local song = H.check(t, Hvl, c) + if song and c.name == "demo" then + t:eq(song.kind, "music", "kind") + t:eq(song.format, "hvl", "format") + t:eq(song.title, "demo", "title") + t:eq(song.channels, 6, "channels") + t:eq(song.meta.source.stereo, 3, "stereo") + t:eq(#song.instruments, 6, "instruments") + t:eq(#song.order, 2, "positions") + t:eq(song.instruments[1].name, "tri", "instrument name") + t:eq(#song.instruments[3].plist.entries, 4, "play list") + t:eq(song.patterns[2].rows, 16, "track rows") + t:eq(buffer.readu8(song.patterns[2].data, 0), 25, "track 1 row 0 note") + t:eq(#song.subsongs, 1, "subsongs") + -- seek back and read again: the same samples + local dec = song:render() + local a = dec:read(4410) + dec:seek(0.5) + dec:seek(0) + local b = dec:read(4410) + t:check(buffer.tostring(a) == buffer.tostring(b), "seek restarts exactly") + end + if #samples < 4 then + table.insert(samples, buffer.fromstring(c.data)) + end +end + +-- bad input +local function code(s: string): string? + local _, e = Hvl.decode(Bytes.reader(buffer.fromstring(s))) + return e and e.code +end +t:eq(code("HVL\1\0\16\0\1\0"), Err.TRUNCATED, "short header") +t:eq(code("HVL\1\0\16\0\0\0\0\16\0\0\0\100\2"), Err.CORRUPT, "no positions") +t:eq(code("HVL\1\0\16\0\1\255\0\16\0\0\0\100\2"), Err.UNSUPPORTED, "67 channels") +t:eq(code(string.sub(Cases[1].data, 1, 60)), Err.TRUNCATED, "truncated") +local song = assert(Hvl.decode(Bytes.reader(buffer.fromstring(Cases[1].data)))) +t:check(song:render({ subsong = 9 }).err ~= nil, "subsong out of range") + +t:fuzz("decode", function(b: buffer) + return Hvl.decode(Bytes.reader(b)) +end, samples) +t:fuzz("decode + render", function(b: buffer) + local s = Hvl.decode(Bytes.reader(b)) + if s then + local d = s:render({ sampleRate = 8000, maxDuration = 0.5 }) + d:read(4000) + end + return s +end, samples, { mutations = 150, garbage = 20 }) +t:done() diff --git a/tests/music/med.luau b/tests/music/med.luau new file mode 100644 index 0000000..ef53518 --- /dev/null +++ b/tests/music/med.luau @@ -0,0 +1,22 @@ +-- music/med tests: generated MED / OctaMED modules (tools/fixtures/med.py: MMD0, MMD1 with hold / decay and finetune, +-- MMD2 with a play sequence, an IFF 3-octave sample) parsed, rendered through codecs/audio/Tracker and compared with openmpt123's render +-- (loudness envelope, band spectrum, stereo balance, song length), the contract, and the fuzz no-throw pass. +local T = require("@tests/T") +local S = require("@tests/music/_similar") +local Med = require("@formats/music/med") +local Cases = require("@tests/gen/med_cases") + +local t = T.suite("med") + +t:eq(Med.name, "med", "name") +t:eq(Med.category, "music", "category") +t:check(Med.caps.decode and not Med.caps.encode, "caps") + +local mods = S.against(t, Med, Cases, { gainDb = 0.5, envErr = 1.0, spectral = 0.95, balance = 0.04, duration = 0.01 }, "xm") +t:check(mods[2] and mods[2].instrumentMode and mods[2].instruments[1].volEnv ~= nil, "MMD1 hold / decay: an instrument envelope") +t:check(mods[2] and mods[2].title == "med test", "song name") +t:check(mods[3] and mods[3].channels == 6 and mods[3].meta.source.version == "MMD2", "MMD2") +t:check(mods[4] and mods[4].instrumentMode and #mods[4].samples == 4 and mods[4].samples[3].length == 128, "IFF 3-octave sample") + +t:fuzz("decode", S.fuzzer(Med), S.samples(Cases), { mutations = 30 }) +t:done() diff --git a/tests/music/midi.luau b/tests/music/midi.luau index 78f4aa6..e659b27 100644 --- a/tests/music/midi.luau +++ b/tests/music/midi.luau @@ -271,6 +271,40 @@ for _, c in Cases do table.insert(samples, c.data) end end +-- .kar karaoke: the "Words" track's text events (FF 01) with @ headers, plus FF 05 lyrics, timed through the tempo map +do + local function txt(tick: number, meta: number, s: string): any + return { tick = tick, type = "meta", meta = meta, data = { string.byte(s, 1, -1) } } + end + local k = Types.Midi.new(96) + table.insert(k.tracks, { events = { + { tick = 0, type = "meta", meta = 0x51, data = { 0x0F, 0x42, 0x40 } }, -- 1 s per quarter + txt(0, 1, "Copyright notice, not a lyric"), + { tick = 192, type = "noteOn", channel = 0, data = { 60, 100 } }, + { tick = 288, type = "noteOff", channel = 0, data = { 60, 0 } }, + } }) + table.insert(k.tracks, { events = { + txt(0, 3, "Words"), txt(0, 1, "@KMIDI KARAOKE FILE"), txt(0, 1, "@LENG"), txt(0, 1, "@TSong title"), + txt(0, 1, "@TThe artist"), txt(0, 1, "@Isome info"), txt(96, 1, "\\Hel"), txt(144, 1, "lo"), + txt(192, 1, "/world"), txt(240, 5, "!"), + } }) + local m = assert(decode(Midi.encode(k))) + local ly = m.meta.lyrics + t:eq(#ly, 4, "kar: lyric count") + t:eq(ly[1].text, "\\Hel", "kar: first lyric (paragraph marker kept)") + t:eq(ly[1].tick, 96, "kar: tick") + t:check(math.abs(ly[1].time - 1) < 1e-9 and math.abs(ly[3].time - 2) < 1e-9, "kar: times through the tempo map") + t:eq(ly[4].text, "!", "kar: FF 05 lyric") + t:eq(m.meta.karaoke.T[2], "The artist", "kar: @T lines") + t:eq(m.meta.karaoke.K[1], "MIDI KARAOKE FILE", "kar: @K") + t:eq(m.meta.tags.title, "Song title", "kar: tags.title") + t:eq(m.meta.tags.artist, "The artist", "kar: tags.artist") + t:eq(m.meta.tags.language, "ENG", "kar: tags.language") + t:eq(m:render().tags.title, "Song title", "kar: decoder title") + local plain = assert(decode(Midi.encode(Types.Midi.new(96)))) + t:eq(plain.meta.lyrics, nil, "no lyrics without text events") +end + t:fuzz("decode", function(b: buffer) return decode(b) end, samples, { mutations = 40 }) diff --git a/tests/music/mtm.luau b/tests/music/mtm.luau new file mode 100644 index 0000000..2e1a784 --- /dev/null +++ b/tests/music/mtm.luau @@ -0,0 +1,20 @@ +-- music/mtm tests: generated MultiTracker modules (tools/fixtures/mtm.py) parsed, rendered through codecs/audio/Tracker +-- and compared with openmpt123's render (loudness envelope, band spectrum, stereo balance, song length), the contract, +-- and the fuzz no-throw pass. +local T = require("@tests/T") +local S = require("@tests/music/_similar") +local Mtm = require("@formats/music/mtm") +local Cases = require("@tests/gen/mtm_cases") + +local t = T.suite("mtm") + +t:eq(Mtm.name, "mtm", "name") +t:eq(Mtm.category, "music", "category") +t:check(Mtm.caps.decode and not Mtm.caps.encode, "caps") + +local mods = S.against(t, Mtm, Cases, { gainDb = 0.5, envErr = 1.0, spectral = 0.95, balance = 0.04, duration = 0.01 }, "xm") +t:check(mods[1] and #mods[1].samples == 5 and mods[1].samples[3].bits == 16, "16-bit sample") +t:check(mods[1] and mods[1].meta.message ~= nil, "message") + +t:fuzz("decode", S.fuzzer(Mtm), S.samples(Cases), { mutations = 30 }) +t:done() diff --git a/tests/music/mus.luau b/tests/music/mus.luau new file mode 100644 index 0000000..8194775 --- /dev/null +++ b/tests/music/mus.luau @@ -0,0 +1,93 @@ +-- music/mus tests: Doom MUS files (tools/fixtures/mus.py) decoded and compared with wildmidi -x's conversion (notes, +-- programs, pitch bend MSB, controllers; times at wildmidi's tick rate), system events / measure ends, the tick rate +-- option, a render, bad input, and the fuzz no-throw pass. +local T = require("@tests/T") +local V = require("@tests/music/_midivar") +local Mus = require("@formats/music/mus") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Render = require("@formats/codecs/audio/MidiRender") +local Cases = require("@tests/gen/mus_cases") +local Measures = require("@tests/gen/mus_measures") + +local t = T.suite("mus") + +local function decode(s: string, opts: any?): (any, any) + return Mus.decode(Bytes.reader(buffer.fromstring(s)), opts) +end + +t:eq(Mus.name, "mus", "name") +t:check(Mus.caps.decode and not Mus.caps.encode, "caps") +t:eq(Mus.sniff(Bytes.reader(buffer.fromstring("MUS\x1a"))), 1, "sniff") +t:eq(Mus.sniff(Bytes.reader(buffer.fromstring("MThd"))), 0, "sniff MThd") + +local samples = {} +for _, c in Cases do + local m, err = decode(c.data, { rate = c.rate }) + t:check(m, c.name .. ": " .. tostring(err)) + if m then + t:eq(m.kind, "midi", c.name .. ": kind") + t:eq(m.meta.source.format, "mus", c.name .. ": source") + t:eq(#m.meta.source.instruments, 3, c.name .. ": instrument list") + V.compare(t, m, c.ref, c.name) + -- Doom's 140 Hz: the same events, times scaled by rate / 140 + local d = assert(decode(c.data)) + t:check(math.abs(d.meta.length * 140 - m.meta.length * c.rate) < 1e-5 * d.meta.length * 140 + 1e-6, c.name .. ": 140 Hz default") + end + table.insert(samples, buffer.fromstring(c.data)) +end + +-- system events and measure ends inserted with no delay: the same notes at the same times, more controllers +do + local p, q = assert(decode(Measures.plain)), assert(decode(Measures.marked)) + local a, b = Render.timeline(p), Render.timeline(q) + local function notes(tl: any): { string } + local out = {} + for i = 1, #tl.time do + if tl.status[i] // 16 == 8 or tl.status[i] // 16 == 9 then + table.insert(out, string.format("%.6f %d %d %d", tl.time[i], tl.status[i], tl.d1[i], tl.d2[i])) + end + end + return out + end + local na, nb = notes(a), notes(b) + t:eq(#nb, #na, "measures: note count") + t:eq(table.concat(nb, ","), table.concat(na, ","), "measures: same notes") + t:check(#b.time > #a.time, "measures: system events become controllers") + t:eq(q.meta.length, p.meta.length, "measures: same length") +end + +-- a render through the built-in waveforms +do + local m = assert(decode(Cases[1].data)) + local dec = m:render({ sampleRate = 22050, tail = 0.2 }) + t:check(dec.frames > 0 and math.abs(dec.duration - (m.meta.length + 0.2)) < 0.01, "render duration") + local buf, n = dec:read(dec.frames) + local peak = 0 + for i = 0, n * 2 - 1 do + peak = math.max(peak, math.abs(buffer.readf32(buf, i * 4))) + end + t:check(peak > 0.01, "render makes sound") +end + +-- bad input +local _, e1 = decode("MUS\x1a\1\0") +t:eq(e1 and e1.code, Err.TRUNCATED, "short header") +local _, e2 = decode("MUS\x1a\2\0\200\0\1\0\0\0\0\0\0\0") +t:eq(e2 and e2.code, Err.TRUNCATED, "score past the end") +local _, e3 = decode("MUS\x1a\2\0\16\0\1\0\0\0\0\0\0\0\112\0") +t:eq(e3 and e3.code, Err.CORRUPT, "event type 7") +local _, e4 = decode(Cases[1].data, { rate = 0 }) +t:eq(e4 and e4.code, Err.ARG, "bad rate") + +t:fuzz("decode", function(b: buffer) + return Mus.decode(Bytes.reader(b)) +end, samples) +t:fuzz("decode + render", function(b: buffer) + local m = Mus.decode(Bytes.reader(b)) + if m and m.meta.length < 30 then + m:render({ sampleRate = 8000 }):read(2000) + end + return m +end, samples, { mutations = 60, garbage = 10 }) +t:done() diff --git a/tests/music/okt.luau b/tests/music/okt.luau new file mode 100644 index 0000000..b96f51c --- /dev/null +++ b/tests/music/okt.luau @@ -0,0 +1,19 @@ +-- music/okt tests: generated Oktalyzer modules (tools/fixtures/okt.py) parsed, rendered through codecs/audio/Tracker +-- and compared with openmpt123's render (loudness envelope, band spectrum, stereo balance, song length), the contract, +-- and the fuzz no-throw pass. +local T = require("@tests/T") +local S = require("@tests/music/_similar") +local Okt = require("@formats/music/okt") +local Cases = require("@tests/gen/okt_cases") + +local t = T.suite("okt") + +t:eq(Okt.name, "okt", "name") +t:eq(Okt.category, "music", "category") +t:check(Okt.caps.decode and not Okt.caps.encode, "caps") + +local mods = S.against(t, Okt, Cases, { gainDb = 0.5, envErr = 1.0, spectral = 0.95, balance = 0.04, duration = 0.01 }, "it") +t:check(mods[2] and mods[2].channels == 6, "two mixed pairs: 6 channels") + +t:fuzz("decode", S.fuzzer(Okt), S.samples(Cases), { mutations = 30 }) +t:done() diff --git a/tests/music/ptm.luau b/tests/music/ptm.luau new file mode 100644 index 0000000..b58ccc2 --- /dev/null +++ b/tests/music/ptm.luau @@ -0,0 +1,19 @@ +-- music/ptm tests: generated PolyTracker modules (tools/fixtures/ptm.py) parsed, rendered through codecs/audio/Tracker +-- and compared with openmpt123's render (loudness envelope, band spectrum, stereo balance, song length), the contract, +-- and the fuzz no-throw pass. +local T = require("@tests/T") +local S = require("@tests/music/_similar") +local Ptm = require("@formats/music/ptm") +local Cases = require("@tests/gen/ptm_cases") + +local t = T.suite("ptm") + +t:eq(Ptm.name, "ptm", "name") +t:eq(Ptm.category, "music", "category") +t:check(Ptm.caps.decode and not Ptm.caps.encode, "caps") + +local mods = S.against(t, Ptm, Cases, { gainDb = 0.5, envErr = 1.0, spectral = 0.95, balance = 0.04, duration = 0.01 }, "it") +t:check(mods[1] and mods[1].samples[3].bits == 16 and mods[1].samples[3].loopType == 2, "16-bit ping-pong loop") + +t:fuzz("decode", S.fuzzer(Ptm), S.samples(Cases), { mutations = 30 }) +t:done() diff --git a/tests/music/stm.luau b/tests/music/stm.luau new file mode 100644 index 0000000..4b2ccfa --- /dev/null +++ b/tests/music/stm.luau @@ -0,0 +1,19 @@ +-- music/stm tests: generated Scream Tracker 2 modules (tools/fixtures/stm.py) parsed, rendered through +-- codecs/audio/Tracker and compared with openmpt123's render (loudness envelope, band spectrum, stereo balance, song +-- length), the contract, and the fuzz no-throw pass. +local T = require("@tests/T") +local S = require("@tests/music/_similar") +local Stm = require("@formats/music/stm") +local Cases = require("@tests/gen/stm_cases") + +local t = T.suite("stm") + +t:eq(Stm.name, "stm", "name") +t:eq(Stm.category, "music", "category") +t:check(Stm.caps.decode and not Stm.caps.encode, "caps") + +local mods = S.against(t, Stm, Cases, { gainDb = 0.5, envErr = 1.0, spectral = 0.95, balance = 0.04, duration = 0.01 }, "s3m") +t:check(mods[1] and mods[1].meta.source.tracker == "!Scream!", "tracker name") + +t:fuzz("decode", S.fuzzer(Stm), S.samples(Cases), { mutations = 30 }) +t:done() diff --git a/tests/music/ult.luau b/tests/music/ult.luau new file mode 100644 index 0000000..3df1f53 --- /dev/null +++ b/tests/music/ult.luau @@ -0,0 +1,19 @@ +-- music/ult tests: generated UltraTracker modules (tools/fixtures/ult.py) parsed, rendered through codecs/audio/Tracker +-- and compared with openmpt123's render (loudness envelope, band spectrum, stereo balance, song length), the contract, +-- and the fuzz no-throw pass. +local T = require("@tests/T") +local S = require("@tests/music/_similar") +local Ult = require("@formats/music/ult") +local Cases = require("@tests/gen/ult_cases") + +local t = T.suite("ult") + +t:eq(Ult.name, "ult", "name") +t:eq(Ult.category, "music", "category") +t:check(Ult.caps.decode and not Ult.caps.encode, "caps") + +local mods = S.against(t, Ult, Cases, { gainDb = 0.5, envErr = 1.0, spectral = 0.95, balance = 0.04, duration = 0.01 }, "it") +t:check(mods[1] and mods[1].samples[3].bits == 16 and mods[1].samples[3].susType == 2, "16-bit ping-pong sustain loop") + +t:fuzz("decode", S.fuzzer(Ult), S.samples(Cases), { mutations = 30 }) +t:done() diff --git a/tests/music/umx.luau b/tests/music/umx.luau new file mode 100644 index 0000000..edb61f6 --- /dev/null +++ b/tests/music/umx.luau @@ -0,0 +1,51 @@ +-- music/umx tests: Unreal packages wrapping generated S3M / IT modules (tools/fixtures/umx.py): the export found and +-- unwrapped (bytes equal to the module put in), loaded through the api's decodeModule hook and rendered like +-- openmpt123 renders the package, UNSUPPORTED without the hook, the contract, and the fuzz no-throw pass. +local T = require("@tests/T") +local S = require("@tests/music/_similar") +local F = require("@formats") +local Umx = require("@formats/music/umx") +local Bytes = require("@formats/core/Bytes") +local Cases = require("@tests/gen/umx_cases") + +local t = T.suite("umx") + +t:eq(Umx.name, "umx", "name") +t:eq(Umx.category, "music", "category") +t:check(Umx.caps.decode and not Umx.caps.encode, "caps") + +local THRESH = { gainDb = 0.5, envErr = 1.0, spectral = 0.95, balance = 0.04, duration = 0.01 } +local function hook(b: buffer, format: string?): (any, any) + return F.load(b, { category = "music", format = format }) +end + +for _, c in Cases do + local r = Bytes.reader(buffer.fromstring(c.data)) + t:check(Umx.sniff(r) == 1, c.name .. ": sniff") + local list = Umx.extract(r) + t:check(list and #list == 1 and list[1].name == string.lower(c.name) and list[1].format == c.format, c.name .. ": extract") + t:eq(list and buffer.tostring(list[1].data), c.inner, c.name .. ": the embedded module's bytes") + local _, err = Umx.decode(Bytes.reader(buffer.fromstring(c.data))) + t:check(err and err.code == F.Err.UNSUPPORTED, c.name .. ": no hook: UNSUPPORTED") + local m, merr = Umx.decode(Bytes.reader(buffer.fromstring(c.data)), { decodeModule = hook }) + t:check(m and m.format == c.format and m.meta.container.format == "umx", c.name .. ": decode " .. tostring(merr)) + local viaApi = F.load(c.data) + t:check(viaApi and viaApi.kind == "music" and viaApi.meta.container and viaApi.meta.container.name == string.lower(c.name), c.name .. ": F.load") + t:eq(F.detect(c.data), "umx", c.name .. ": F.detect") + local dec = m:render({ sampleRate = S.SR }) + t:check(math.abs(dec.duration - c.duration) < THRESH.duration, string.format("%s: duration %.3f s, openmpt %.3f s", c.name, dec.duration, c.duration)) + local buf, frames = S.renderAll(dec, math.floor(c.duration * S.SR)) + local res = S.compare(S.features(buf, frames), c.ref) + t:note("%-10s gain %+.2f dB, loudness error %.2f dB, spectrum %.3f, balance %.3f, %.2f s", c.name, res.gainDb, res.envErr, res.spectral, res.balance, dec.duration) + t:check(math.abs(res.gainDb) < THRESH.gainDb and res.envErr < THRESH.envErr, c.name .. ": loudness") + t:check(res.spectral > THRESH.spectral and res.balance < THRESH.balance, c.name .. ": spectrum, balance") + local d2 = F.open(c.data) + t:check(d2 and d2.channels == 2, c.name .. ": F.open renders") +end + +t:fuzz("decode", function(b: buffer) + local m = Umx.decode(Bytes.reader(b), { decodeModule = hook }) + Umx.extract(Bytes.reader(b)) + return m +end, S.samples(Cases), { mutations = 30 }) +t:done() diff --git a/tests/music/xm.luau b/tests/music/xm.luau index 0afd6e2..df696ed 100644 --- a/tests/music/xm.luau +++ b/tests/music/xm.luau @@ -1,5 +1,6 @@ -- music/xm tests: generated FastTracker 2 modules (tools/fixtures/xm.py) parsed, rendered through codecs/audio/Tracker and --- compared with openmpt123's render (loudness envelope, band spectrum, stereo balance, song length), the XM writer's +-- compared with openmpt123's render (loudness envelope, band spectrum, stereo balance, song length; a ModPlug ADPCM +-- sample), the XM writer's -- round trip, the contract, and the fuzz no-throw pass. local T = require("@tests/T") local S = require("@tests/music/_similar") @@ -44,7 +45,12 @@ for _, c in Cases do t:check(out, c.name .. ": encode " .. tostring(werr)) local m2 = Xm.decode(Bytes.reader(out :: buffer)) t:check(m2, c.name .. ": re-decode") - t:eq(buffer.tostring(out :: buffer), c.data, c.name .. ": round trip bytes") + if c.name == "adpcm" then + -- ModPlug ADPCM is written back as delta PCM: the same samples, not the same bytes + t:eq(buffer.tostring(m2.samples[1].data), buffer.tostring(m.samples[1].data), c.name .. ": samples kept") + else + t:eq(buffer.tostring(out :: buffer), c.data, c.name .. ": round trip bytes") + end end -- seek: the position after a seek and the output continuing diff --git a/tests/music/xmi.luau b/tests/music/xmi.luau new file mode 100644 index 0000000..e1552f4 --- /dev/null +++ b/tests/music/xmi.luau @@ -0,0 +1,73 @@ +-- music/xmi tests: XMIDI files (tools/fixtures/xmi.py: XDIR + CAT XMID with one or two songs, a bare FORM XMID, with +-- and without TIMB) decoded and compared with wildmidi -x's conversion of song 1 (notes from durations, programs, +-- bends, controllers; 120 Hz), song selection, export to SMF, a render, bad input, and the fuzz no-throw pass. +local T = require("@tests/T") +local V = require("@tests/music/_midivar") +local Xmi = require("@formats/music/xmi") +local Midi = require("@formats/music/midi") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Cases = require("@tests/gen/xmi_cases") + +local t = T.suite("xmi") + +local function decode(s: string, opts: any?): (any, any) + return Xmi.decode(Bytes.reader(buffer.fromstring(s)), opts) +end + +t:eq(Xmi.name, "xmi", "name") +t:check(Xmi.caps.decode and not Xmi.caps.encode, "caps") +t:eq(Xmi.sniff(Bytes.reader(buffer.fromstring("FORM\0\0\0\0XDIR"))), 1, "sniff XDIR") +t:eq(Xmi.sniff(Bytes.reader(buffer.fromstring("FORM\0\0\0\0AIFF"))), 0, "sniff AIFF") + +local samples = {} +for _, c in Cases do + local m, err = decode(c.data) + t:check(m, c.name .. ": " .. tostring(err)) + if m then + t:eq(m.meta.source.songs, c.songs, c.name .. ": songs") + t:eq(m.division, 60, c.name .. ": division") + V.compare(t, m, c.ref, c.name, { hangingOffs = true }) + if c.songs > 1 then + local s2 = assert(decode(c.data, { track = 2 })) + t:eq(s2.meta.source.song, 2, c.name .. ": song 2") + t:check(#s2.tracks[1].events ~= #m.tracks[1].events, c.name .. ": song 2 differs") + local _, e = decode(c.data, { track = 3 }) + t:eq(e and e.code, Err.ARG, c.name .. ": no song 3") + end + -- export to a Standard MIDI File and back: the same timeline + local smf = assert(Midi.encode(m)) + local back = assert(Midi.decode(Bytes.reader(smf))) + t:check(math.abs(back.meta.length - m.meta.length) < 1e-9, c.name .. ": SMF export keeps the timing") + end + table.insert(samples, buffer.fromstring(c.data)) +end + +do + local m = assert(decode(Cases[1].data)) + local dec = m:render({ sampleRate = 22050, tail = 0.2 }) + t:check(math.abs(dec.duration - (m.meta.length + 0.2)) < 0.01, "render duration") + local buf, n = dec:read(dec.frames) + local peak = 0 + for i = 0, n * 2 - 1 do + peak = math.max(peak, math.abs(buffer.readf32(buf, i * 4))) + end + t:check(peak > 0.01, "render makes sound") +end + +local _, e1 = decode("FORM\0\0\0\4XDIR") +t:eq(e1 and e1.code, Err.CORRUPT, "no songs") +local _, e2 = decode("FORM\0\0\0\14XMIDEVNT\0\0\0\2\144\60") +t:eq(e2 and e2.code, Err.TRUNCATED, "truncated note") + +t:fuzz("decode", function(b: buffer) + return Xmi.decode(Bytes.reader(b)) +end, samples) +t:fuzz("decode + render", function(b: buffer) + local m = Xmi.decode(Bytes.reader(b)) + if m and m.meta.length < 30 then + m:render({ sampleRate = 8000 }):read(2000) + end + return m +end, samples, { mutations = 60, garbage = 10 }) +t:done() diff --git a/tools/bench.luau b/tools/bench.luau index 03b7c52..6b3d544 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -1538,3 +1538,201 @@ do Exr.encode(img) end) end +-- ------------------------------------------------------------------------------------------- ws-video2-legacy: fps +do + -- the legacy codecs (codecs/video/Legacy) through F.video.open, rgba8 frames out: ffmpeg's encoders at 320x240 + -- (tools/fixtures/legacy.py), a 320x200 FLC (fli.py) and a 320x200 SMK4 (smk.py, textured: mostly FULL blocks); + -- frames per second of the whole decode (and the Smacker audio track, seconds of audio per second) + local F = require("@formats") + local LB = require("@tests/gen/legacy_bench") + local cases = table.clone(LB) + table.insert(cases, { name = "fli.flc", data = require("@tests/gen/fli_bench").data, width = 320, height = 200 }) + table.insert(cases, { name = "smk4.smk", data = require("@tests/gen/smk_bench").data, width = 320, height = 200 }) + for _, c in cases do + local data = buffer.fromstring(c.data) + local frames = 0 + local dt = math.huge + for _ = 1, 3 do + local t0 = os.clock() + local v = assert(F.video.open(data, { audio = false })) + frames = 0 + while v:nextFrame() do + frames += 1 + end + dt = math.min(dt, os.clock() - t0) + end + print(string.format("%-8s %-30s %8.2f ms %7.1f fps", runtime, string.format("legacy %s %dx%d", c.name, c.width, c.height), dt * 1000 / frames, frames / dt)) + end + local v = assert(F.video.open(buffer.fromstring(require("@tests/gen/smk_bench").data))) + local a = assert(v.audio) + local t0 = os.clock() + local n = 0 + while true do + local _, got = a:read(4096) + if got == 0 then + break + end + n += got + end + local dt = os.clock() - t0 + print(string.format("%-8s %-30s %8.2f ms %7.1fx real time", runtime, "smacker audio 22 kHz stereo", dt * 1000, n / a.sampleRate / dt)) +end +-- ws-audio2: chip/midi +do + -- AHX / HVL (codecs/audio/Hively): a whole song rendered at 44.1 kHz (tools/fixtures/ahx.py karma.ahx, 3 s; hvl.py + -- the 6-channel demo with ring modulation); MB/s of stereo f32 output, and how many times faster than real time + local Ahx, Hvl = require("@formats/music/ahx"), require("@formats/music/hvl") + local AC, HC = require("@tests/gen/ahx_cases"), require("@tests/gen/hvl_cases") + for _, spec in { { Ahx, AC, "karma.ahx", "ahx render karma (4 ch)" }, { Hvl, HC, "demo", "hvl render demo (6 ch)" } } do + for _, c in spec[2] do + if c.name == spec[3] then + local song = assert(spec[1].decode(Bytes.reader(buffer.fromstring(c.data)))) + local frames = 0 + local dt = bench(spec[4], 3, c.frames * 8, function() + local dec = song:render({ maxDuration = c.maxDuration }) + frames = dec.frames + dec:read(frames) + end) + print(string.format("%-8s %-30s %8.1f x real time", runtime, "", frames / 44100 / dt)) + end + end + end +end +-- ws-audio2: lossy +do + -- Musepack (codecs/audio/Musepack) SV8 / SV7 and AC-3 5.1 (codecs/audio/Ac3): whole-file decodes, MB/s of f32 output + -- (tools/fixtures/mpc.py: 1.2 s of 44.1 kHz stereo at quality 5; tools/fixtures/ac3.py: 0.16 s of 48 kHz 5.1 at + -- 448 kbps, decoded 4 times per run) + local Mpc = require("@formats/audio/mpc") + local MpcFx = require("@tests/gen/mpc_cases") + local Ac3F = require("@formats/audio/ac3") + local Ac3Fx = require("@tests/gen/ac3_cases") + for _, c in MpcFx do + if c.name == "sv8_q5_stereo" or c.name == "sv7_q5_stereo" then + local b = buffer.fromstring(c.data) + bench("mpc " .. c.name, 5, c.frames * c.channels * 4, function() + assert(Mpc.decode(Bytes.reader(b))) + end) + end + end + for _, c in Ac3Fx do + if c.name == "5.1_448" then + local b = buffer.fromstring(c.data) + bench("ac3 5.1 448 kbps", 5, c.frames * c.channels * 4 * 4, function() + for _ = 1, 4 do + assert(Ac3F.decode(Bytes.reader(b))) + end + end) + end + end +end +-- ws-audio2: adpcm / qoa +do + -- codecs/audio/Adpcm (IMA nibble stream, Nintendo DSP frames) and QOA decode / encode, over generated signals; MB/s + -- of f32 output (MB/s of input for the encoder) + local Adpcm = require("@formats/codecs/audio/Adpcm") + local QoaCodec = require("@formats/codecs/audio/Qoa") + local Qoa = require("@formats/audio/qoa") + local n = 44100 * 5 + local sig = Types.Audio.new(44100, 2, n) + for i = 0, n - 1 do + local t = i / 44100 + buffer.writef32(sig.samples, i * 8, 0.5 * math.sin(2 * math.pi * 440 * t) + 0.1 * math.sin(2 * math.pi * 3000 * t)) + buffer.writef32(sig.samples, i * 8 + 4, 0.4 * math.sin(2 * math.pi * 660 * t + 1)) + end + -- IMA: encode the left channel as a nibble stream, then decode it + local ima = buffer.create(n // 2) + Adpcm.imaEncode(sig.samples, 0, 2, n, buffer.create(8), 0, ima, 0, 0, 1, false) + local out = buffer.create(n * 4) + bench("adpcm ima decode", 5, n * 4, function() + Adpcm.ima(ima, 0, 0, 1, n, false, buffer.create(8), 0, out, 0, 1) + end) + -- DSP: random frames with 8 coefficient pairs + local frames = n // 14 + local dsp = buffer.create(frames * 8) + local seed = 1 + for i = 0, frames * 8 - 1 do + seed = (seed * 1103515245 + 12345) % 2147483648 + local v = seed // 65536 % 256 + buffer.writeu8(dsp, i, if i % 8 == 0 then (v % 8) * 16 + v % 12 else v) + end + local coefs = buffer.create(64) + for k = 0, 7 do + buffer.writei32(coefs, k * 8, 1800 + k * 200) + buffer.writei32(coefs, k * 8 + 4, -900 - k * 100) + end + bench("adpcm dsp decode", 5, frames * 14 * 4, function() + Adpcm.dsp(dsp, 0, frames * 14, coefs, 0, buffer.create(8), 0, out, 0, 1) + end) + -- QOA (stereo 44.1 kHz) + local file = assert(Qoa.encode(sig)) + bench("qoa encode", 2, n * 2 * 4, function() + Qoa.encode(sig) + end) + local pcm = buffer.create(QoaCodec.FRAME_LEN * 2 * 4) + bench("qoa decode", 5, n * 2 * 4, function() + local p = 8 + while p < buffer.len(file) do + local _, size = QoaCodec.decodeFrame(file, p, buffer.len(file) - p, pcm, 0) + p += size :: number + end + end) + bench("qoa decode (F.load path)", 5, n * 2 * 4, function() + Qoa.decode(Bytes.reader(file)) + end) +end +-- ws-audio2: lossless +do + -- WavPack / Monkey's Audio / TTA decoders (tools/fixtures/wavpack.py, ape.py, tta.py): MB/s of f32 output + local function lossless(label: string, mod: any, data: string) + local b = buffer.fromstring(data) + local dec = assert(mod.open(Bytes.reader(b))) + bench(label, 5, dec.frames * dec.channels * 4, function() + mod.decode(Bytes.reader(b)) + end) + end + local Wv = require("@formats/audio/wavpack") + for _, c in require("@tests/gen/wavpack_cases") do + if c.name == "s16_long" or c.name == "s16_hh" or c.name == "s24_hh" or c.name == "f32" or c.name == "hyb_b3" then + lossless("wavpack " .. c.name, Wv, c.data) + end + end + local ApeF = require("@formats/audio/ape") + for _, c in require("@tests/gen/ape_cases") do + if c.name == "s16_long" or c.name == "s16_long_c4000" or c.name == "s16_c5000" or c.name == "s24" or c.name == "s16_c1000" then + lossless("ape " .. c.name, ApeF, c.data) + end + end + local TtaF = require("@formats/audio/tta") + for _, c in require("@tests/gen/tta_cases") do + if c.name == "s16_long" or c.name == "s24" or c.name == "ch6" then + lossless("tta " .. c.name, TtaF, c.data) + end + end +end +-- ws-audio2: trackers +do + -- the other tracker loaders on the shared engine: a 669 (Hz periods, auto slides) and an MMD1 (hold / decay + -- envelopes, instruments) from tools/fixtures/{669,med}.py, decoded and rendered at 44.1 kHz + local Six69 = require("@formats/music/669") + local Med = require("@formats/music/med") + local songs = { { Six69, require("@tests/gen/669_cases")[1].data }, { Med, require("@tests/gen/med_cases")[2].data } } + local best, frames = math.huge, 0 + local out = buffer.create(4096 * 8) + for _ = 1, 3 do + frames = 0 + local t0 = os.clock() + for _, s in songs do + local dec = (s[1].decode(Bytes.reader(buffer.fromstring(s[2]))) :: any):render() + while true do + local _, n = dec:read(4096, out) + if n == 0 then + break + end + frames += n + end + end + best = math.min(best, os.clock() - t0) + end + print(string.format("%-8s %-30s %8.2f ms %7.1f x realtime", runtime, "render 669 / med", best * 1000, frames / 44100 / best)) +end diff --git a/tools/fixtures/669.py b/tools/fixtures/669.py new file mode 100644 index 0000000..df848ab --- /dev/null +++ b/tools/fixtures/669.py @@ -0,0 +1,94 @@ +# 669 fixtures (tools/fixtures.py): generated Composer 669 / UNIS 669 modules exercising the effects, rendered by +# openmpt123. +# tests/gen/669_cases.luau { name, data (the module), ref (features of openmpt's render, tools/fixtures/_tracker.py), +# duration (openmpt's song length) } +import os, sys + +# the shared tracker module, loaded by path (tools/fixtures/ must not go on sys.path: xml.py there would shadow xml) +T = sys.modules.get("_tracker") +if T is None: + import importlib.util + _spec = importlib.util.spec_from_file_location("_tracker", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tracker.py")) + T = importlib.util.module_from_spec(_spec) + sys.modules["_tracker"] = T + _spec.loader.exec_module(T) + +INPUTS = ["tools/fixtures/_tracker.py"] + + +def empty(): + return [[(0, 0, None, None) for _ in range(8)] for _ in range(64)] + + +def put(p, row, ch, note=0, ins=0, vol=None, cmd=None, param=0): + p[row][ch] = (note, ins, vol, None if cmd is None else (cmd << 4) | param) + + +def samples(): + return [ + {"name": "sine", "data": T.u8(T.synth("sine", 64, 64)), "loop": (0, 64)}, + {"name": "square", "data": T.u8(T.synth("square", 64, 64, 0.5)), "loop": (0, 64)}, + {"name": "saw", "data": T.u8(T.synth("saw", 100, 100, 0.6)), "loop": (0, 100)}, + {"name": "noise", "data": T.u8(T.synth("noise", 6000, 1, 0.7, decay=1500))}, + {"name": "tri", "data": T.u8(T.synth("tri", 50, 50, 0.8)), "loop": (0, 50)}, + ] + + +def song_effects(keep=None): + a, b = empty(), empty() + mel = [61, 65, 68, 73, 68, 65, 63, 61] + for i in range(16): + put(a, i * 4, 0, mel[i % 8], 1, 15) + put(a, 0, 1, 49, 2, 12) + put(a, 8, 1, 0, 0, None, 0, 2) # auto portamento up (runs until the next effect) + put(a, 16, 1, 0, 0, None, 1, 3) # auto portamento down + put(a, 24, 1, 0, 0, None, 5, 3) # speed (stops the auto slide) + put(a, 28, 1, 56, 2, 10) + put(a, 32, 1, 61, 2, None, 2, 2) # tone portamento (keeps going) + put(a, 40, 1, 49, 2, None, 2, 4) + put(a, 48, 1, 0, 0, 6, 3, 5) # frequency adjust + put(a, 52, 1, 0, 0, None, 4, 3) # frequency vibrato + for r in range(0, 64, 8): + put(a, r, 3, 61, 4, 15 - r // 8) + put(a, 4, 2, 37, 3, 15) + put(a, 36, 2, 0, 0, 4) + put(a, 10, 4, 73, 5, 9) + put(a, 20, 4, 0, 0, None, 4, 6) + # b: speed per pattern, a break row, more slides + put(b, 0, 0, 49, 1, 15) + put(b, 4, 0, 0, 0, None, 1, 1) + put(b, 12, 0, 61, 1, 15) + put(b, 16, 0, 0, 0, None, 0, 1) + put(b, 20, 0, 0, 0, 10, None) + put(b, 0, 2, 37, 3, 12) + put(b, 8, 2, 44, 3, None, 2, 1) + put(b, 24, 2, 0, 0, None, 3, 2) + put(b, 0, 5, 56, 5, 13) + put(b, 16, 5, 52, 2, 13) + if keep is not None: + for p in (a, b): + for row in p: + for ch in range(8): + if ch not in keep: + row[ch] = (0, 0, None, None) + return T.write_669("effects 669", samples(), [0, 1], [a, b], [4, 3], [63, 40]) + + +def song_unis(): + """UNIS 669: balance slides, slot retrigger, a restart position""" + a = empty() + put(a, 0, 0, 61, 1, 15, 6, 0) # balance slide left (repeats until the next note) + put(a, 16, 0, 64, 1, 15, 6, 1) # right + put(a, 32, 1, 49, 4, 15, 7, 3) # slot retrigger + put(a, 40, 1, 49, 4, 15, 7, 6) + put(a, 8, 2, 68, 2, 11) + put(a, 48, 3, 56, 3, 14) + return T.write_669("unis", samples(), [0, 0], [a], [5], [63], extended=True) + + +def generate(ctx): + cases = [] + for nm, data in (("effects", song_effects()), ("unis", song_unis())): + ref = T.reference(ctx, data, "669") + cases.append({"name": nm, "data": data, "ref": ref, "duration": ref["duration"]}) + ctx.emit("669_cases", cases) diff --git a/tools/fixtures/_adpcm.py b/tools/fixtures/_adpcm.py new file mode 100644 index 0000000..823fb91 --- /dev/null +++ b/tools/fixtures/_adpcm.py @@ -0,0 +1,377 @@ +# Shared helpers for the ADPCM fixture generators (adpcm, adx, vag, brstm): small Python ADPCM encoders that build the +# game containers ffmpeg cannot write (Sony VAG, Nintendo BRSTM / BCSTM / BFSTM, Simon & Schuster KVAG); the files are +# decoded by vgmstream / ffmpeg as the references, so these encoders only need to be valid, not good. +# A = _adpcm.load() +# A.ima_encode(samples, ch, high_first=False) -> raw IMA nibble stream (state 0 / 0; channels interleaved by nibble) +# A.kvag(samples, rate, ch) -> a KVAG file (IMA, high nibble first) +# A.psx_encode(samples) -> bytes of 16-byte PS-ADPCM frames (mono); A.vag(samples, rate, name, loop=None) +# A.dsp_encode(samples, coefs) -> bytes of 8-byte DSP frames (mono); A.DSP_COEFS: the 16 coefficients used +# A.rstm(samples, rate, ch, kind="RSTM"|"CSTM"|"FSTM", loop=None, block=0x2000, le=None, codec="dsp"|"pcm16"|"pcm8") +# A.s16(floats) -> clipped ints +import math, struct, sys + +IMA_STEP = [ + 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, + 130, 143, 157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, 876, 963, 1060, + 1166, 1282, 1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358, 5894, 6484, + 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767] +IMA_INDEX = [-1, -1, -1, -1, 2, 4, 6, 8] + + +def load(): + return sys.modules[__name__] + + +def s16(floats): + return [max(-32768, min(32767, int(math.floor(v * 32768 + 0.5)))) for v in floats] + + +def clamp16(v): + return -32768 if v < -32768 else 32767 if v > 32767 else v + + +def ima_step(pred, index, nib): + step = IMA_STEP[index] + d = step >> 3 + if nib & 1: + d += step >> 2 + if nib & 2: + d += step >> 1 + if nib & 4: + d += step + pred = clamp16(pred - d if nib & 8 else pred + d) + index = max(0, min(88, index + IMA_INDEX[nib & 7])) + return pred, index + + +def ima_nibble(pred, index, x): + best = None + for nib in range(16): + p, _ = ima_step(pred, index, nib) + e = abs(x - p) + if best is None or e < best[0]: + best = (e, nib) + return best[1] + + +def ima_encode(samples, ch, high_first=False): + ints = s16(samples) + st = [[0, 0] for _ in range(ch)] + nibs = [] + for i, x in enumerate(ints): + c = i % ch + n = ima_nibble(st[c][0], st[c][1], x) + st[c][0], st[c][1] = ima_step(st[c][0], st[c][1], n) + nibs.append(n) + if len(nibs) % 2: + nibs.append(0) + out = bytearray() + for k in range(0, len(nibs), 2): + a, b = nibs[k], nibs[k + 1] + out.append((a << 4 | b) if high_first else (b << 4 | a)) + return bytes(out) + + +def kvag(samples, rate, ch): + data = ima_encode(samples, ch, high_first=True) # DVI order: the high nibble first (ffmpeg adpcm_ima_ssi, vgmstream) + return b"KVAG" + struct.pack("> 8; pick the nibble closest to x + want = ((x << 8) - pred) / (1 << (20 - shift)) + n = max(-8, min(7, int(round(want)))) + s = (n * (1 << (20 - shift)) + pred) >> 8 + cs = clamp16(s) + err += (x - cs) ** 2 + nibs.append(n & 15) + a, b = s, a + if best is not None and err >= best[0]: + break + else: + if best is None or err < best[0]: + best = (err, f << 4 | shift, nibs, a, b) + return best + + +def psx_encode(samples, loop=None): + """PS-ADPCM frames (mono ints) after the usual blank frame; loop = (start frame, end frame) sets the flags""" + out = bytearray(16) + h1 = h2 = 0 + n = (len(samples) + 27) // 28 + for k in range(n): + xs = samples[k * 28:(k + 1) * 28] + xs = xs + [0] * (28 - len(xs)) + _, head, nibs, h1, h2 = psx_frame(xs, h1, h2) + flag = 0 + if loop: + if k == loop[0]: + flag = 6 + elif k == loop[1] - 1: + flag = 3 + elif loop[0] < k < loop[1] - 1: + flag = 2 + elif k == n - 1: + flag = 1 + out += bytes([head, flag]) + bytes(nibs[i] | nibs[i + 1] << 4 for i in range(0, 28, 2)) + return bytes(out) + + +def vag(samples, rate, name=b"formats-luau", loop=None): + data = psx_encode(s16(samples), loop) + head = b"VAGp" + struct.pack(">IIII", 0x20, 0, len(data), rate) + b"\0" * 12 + name[:16].ljust(16, b"\0") + return head + data + + +# ------------------------------------------------------------------------------------------------ Nintendo DSP +DSP_COEFS = [0, 0, 2048, 0, 0, 2048, 4096, -2048, 3600, -1700, 3000, -1100, 1024, 0, 3900, -1950] + + +def dsp_frame(xs, h1, h2, coefs): + best = None + for p in range(8): + c1, c2 = coefs[2 * p], coefs[2 * p + 1] + for sc in range(12): + scale = 1 << sc + a, b = h1, h2 + err = 0 + nibs = [] + outs = [] + for x in xs: + base = 1024 + c1 * a + c2 * b + want = ((x << 11) - base) / (scale << 11) + n = max(-8, min(7, int(round(want)))) + s = clamp16(((n * scale) << 11) + base >> 11) + err += (x - s) ** 2 + nibs.append(n & 15) + outs.append(s) + a, b = s, a + if best is not None and err >= best[0]: + break + else: + if best is None or err < best[0]: + best = (err, p << 4 | sc, nibs, outs) + return best + + +def dsp_encode(samples, coefs=DSP_COEFS, decoded=None): + """DSP frames; decoded (a list) receives the decoded samples (the history a seek table stores)""" + out = bytearray() + h1 = h2 = 0 + for k in range(0, len(samples), 14): + xs = samples[k:k + 14] + n = len(xs) + xs = xs + [0] * (14 - n) + _, head, nibs, outs = dsp_frame(xs, h1, h2, coefs) + out.append(head) + out += bytes(nibs[i] << 4 | nibs[i + 1] for i in range(0, 14, 2)) + h1, h2 = outs[-1], outs[-2] + if decoded is not None: + decoded += outs[:n] + return bytes(out) + + +def hist(dec, b, spb): + """(yn1, yn2) before block b: the last two decoded samples of the previous block""" + if b == 0 or not dec: + return (0, 0) + return (dec[b * spb - 1], dec[b * spb - 2]) + + +def rstm(samples, rate, ch, kind="RSTM", loop=None, block=0x2000, le=None, codec="dsp", coefs=DSP_COEFS): + """a BRSTM (kind RSTM, big-endian), BCSTM (CSTM, little-endian) or BFSTM (FSTM, big-endian unless le) file""" + ints = s16(samples) + frames = len(ints) // ch + chans = [ints[c::ch] for c in range(ch)] + decs = [[] for _ in range(ch)] + if codec == "dsp": + enc = [dsp_encode(x, coefs, decs[c]) for c, x in enumerate(chans)] + spb = block // 8 * 14 + elif codec == "pcm16": + big = kind == "RSTM" or (kind == "FSTM" and not le) + enc = [b"".join(struct.pack(">h" if big else "> 8) & 255 for v in x) for x in chans] + spb = block + nblocks = (frames + spb - 1) // spb + last_samples = frames - (nblocks - 1) * spb + last_size = len(enc[0]) - (nblocks - 1) * block + last_padded = (last_size + 31) // 32 * 32 + data = bytearray() + for b in range(nblocks): + for c in range(ch): + part = enc[c][b * block:(b + 1) * block] + if b == nblocks - 1: + part = part.ljust(last_padded, b"\0") + data += part + codec_id = {"pcm8": 0, "pcm16": 1, "dsp": 2}[codec] + ls, le_ = (loop if loop else (0, frames)) + if kind == "RSTM": + info = struct.pack(">BBBBHHIIIIIIIIIIII", codec_id, 1 if loop else 0, ch, 0, rate, 0, ls, frames, 0, nblocks, + block, spb, last_size, last_samples, last_padded, spb, 4, 0) + # HEAD: 3 references, the stream info, track info, channel info + + def ref(off): + return struct.pack(">II", 0x01000000, off) + p_info = 0x18 + p_track = p_info + len(info) + track_table = struct.pack(">BBBB", 1, 0, 0, 0) # 1 track, type 0 + p_trackent = p_track + 4 + 8 + track_ent = struct.pack(">BBBB", 127, 64, 0, 0) + struct.pack(">I", 0) + struct.pack(">BBBB", ch, 0, 1, 0) + track_blob = track_table + ref(p_trackent) + track_ent + p_chan = p_track + len(track_blob) + chan_head = struct.pack(">BBBB", ch, 0, 0, 0) + p_chinfo = p_chan + 4 + 8 * ch + chan_refs = b"" + chan_infos = b"" + for c in range(ch): + me = p_chinfo + len(chan_infos) + chan_refs += ref(me) + adp = struct.pack(">16h", *coefs) + struct.pack(">HHhhHhhH", 0, enc[c][0] if codec == "dsp" else 0, 0, 0, 0, 0, 0, 0) + chan_infos += ref(me + 8) + adp + body = info + track_blob + chan_head + chan_refs + chan_infos + body = ref(p_info) + ref(p_track) + ref(p_chan) + body + head = b"HEAD" + struct.pack(">I", 0) + body + head = head.ljust((len(head) + 31) // 32 * 32, b"\0") + head = head[:4] + struct.pack(">I", len(head)) + head[8:] + adpc_body = b"".join(b"".join(struct.pack(">hh", *hist(decs[c], b, spb)) for c in range(ch)) for b in range(nblocks)) + adpc = b"ADPC" + struct.pack(">I", 0) + adpc_body + adpc = adpc.ljust((len(adpc) + 31) // 32 * 32, b"\0") + adpc = adpc[:4] + struct.pack(">I", len(adpc)) + adpc[8:] + hsize = 0x40 + o_head = hsize + o_adpc = o_head + len(head) + o_data = o_adpc + len(adpc) + datac = b"DATA" + struct.pack(">II", len(data) + 0x20, 0x18) + b"\0" * 0x14 + bytes(data) + start = o_data + 0x20 + head = bytearray(head) + struct.pack_into(">I", head, 8 + 8 * 3 + 0x10, start) # data offset (absolute) + total = o_data + len(datac) + hdr = b"RSTM" + struct.pack(">HHIHH", 0xFEFF, 0x0100, total, hsize, 2) + struct.pack(">IIIIII", o_head, len(head), o_adpc, + len(adpc), o_data, len(datac)) + hdr = hdr.ljust(hsize, b"\0") + return hdr + bytes(head) + adpc + datac + # CSTM / FSTM + E = ">" if (kind == "FSTM" and not le) else "<" + + def ref(t, off): + return struct.pack(E + "HHi", t, 0, off) + # INFO: refs (stream info, track table, channel table), stream info, channel table, channel infos, dsp infos + stream_info = struct.pack(E + "BBBB", codec_id, 1 if loop else 0, ch, 0) + struct.pack( + E + "IIIIIIIIIII", rate, ls, frames, nblocks, block, spb, last_size, last_samples, last_padded, 4 * ch, spb) + stream_info += ref(0x1F00, 0x18) # sample data: DATA + 8 + 0x18 + p_stream = 0x18 + p_chtab = p_stream + len(stream_info) + chtab = struct.pack(E + "I", ch) + p_chinfo = p_chtab + 4 + 8 * ch + infos = b"" + adps = b"" + for c in range(ch): + chtab += ref(0x4102, p_chinfo + 8 * c - p_chtab) + p_adp = p_chinfo + 8 * ch + for c in range(ch): + me = p_chinfo + 8 * c + adp_at = p_adp + len(adps) + infos += ref(0x0300, adp_at - me) if codec == "dsp" else ref(0, -1) + adps += struct.pack(E + "16h", *coefs) + struct.pack(E + "HhhHhhH", enc[c][0] if codec == "dsp" else 0, 0, 0, 0, 0, 0, 0) + body = ref(0x4100, p_stream) + ref(0, -1) + ref(0x0101, p_chtab) + stream_info + chtab + infos + adps + info = b"INFO" + struct.pack(E + "I", 0) + body + info = info.ljust((len(info) + 31) // 32 * 32, b"\0") + info = info[:4] + struct.pack(E + "I", len(info)) + info[8:] + seek = b"SEEK" + struct.pack(E + "I", 0) + b"".join(b"".join(struct.pack(E + "hh", *hist(decs[c], b, spb)) for c in range(ch)) for b in range(nblocks)) + seek = seek.ljust((len(seek) + 31) // 32 * 32, b"\0") + seek = seek[:4] + struct.pack(E + "I", len(seek)) + seek[8:] + datac = b"DATA" + struct.pack(E + "I", len(data) + 0x20) + b"\0" * 0x18 + bytes(data) + hsize = 0x40 + o_info = hsize + o_seek = o_info + len(info) + o_data = o_seek + len(seek) + total = o_data + len(datac) + ver = 0x02000000 if kind == "CSTM" else 0x00040000 + hdr = kind.encode() + (b"\xfe\xff" if E == ">" else b"\xff\xfe") + struct.pack(E + "HII", hsize, ver, total) + hdr += struct.pack(E + "HH", 3, 0) + hdr += struct.pack(E + "HHII", 0x4000, 0, o_info, len(info)) + hdr += struct.pack(E + "HHII", 0x4001, 0, o_seek, len(seek)) + hdr += struct.pack(E + "HHII", 0x4002, 0, o_data, len(datac)) + hdr = hdr.ljust(hsize, b"\0") + return hdr + info + seek + datac + + +# ------------------------------------------------------------------------------------------------ references +def wav_pcm(data): + """(rate, channels, s16le bytes) of a 16-bit PCM WAV (vgmstream's output)""" + p = 12 + rate = ch = None + while p + 8 <= len(data): + cid, size = data[p:p + 4], struct.unpack_from("I", 0x20) + struct.pack("II", size, rate) + return head.ljust(0x800, b"\0") + data diff --git a/tools/fixtures/_hively.py b/tools/fixtures/_hively.py new file mode 100644 index 0000000..739ad94 --- /dev/null +++ b/tools/fixtures/_hively.py @@ -0,0 +1,205 @@ +# AHX / HVL fixture helpers (not a generator; tools/fixtures/ahx.py and hvl.py load it): small writers for both module +# formats (the layouts hvl2wav's replay.c reads), hand-made and random songs exercising the waveforms, filters, square +# modulation, PList commands, effects, ring modulation and panning, and the reference render through hvl2wav +# (nixpkgs#hivelytracker). hvl2wav on Linux is built with -D_BIG_ENDIAN_ and so byte-swaps every 16-bit sample it +# writes: the swap is undone here. Songs from the HivelyTracker source tree (Songs/, BSD-3) add real-world cases. +import os, struct, subprocess, tempfile + +AHX_FX = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 12: 6, 15: 7} + + +def ins_header(ins): + a = ins.get("env", (1, 64, 10, 48, 10, 10, 0)) + fs = ins.get("filter_speed", 0) + vib = ins.get("vib", (0, 0, 0)) + hc = ins.get("hardcut", (0, 0)) + sq = ins.get("square", (0x20, 0x3f, 1)) + return bytes([ + ins.get("volume", 64), ((fs & 0x1f) << 3) | ins.get("wavelen", 3), + a[0], a[1], a[2], a[3], a[4], a[5], a[6], 0, 0, 0, + ((fs & 0x20) << 2) | ins.get("filter_lower", 1), vib[0], (0x80 if hc[0] else 0) | ((hc[1] & 7) << 4) | (vib[2] & 15), vib[1], + sq[0], sq[1], sq[2], ins.get("filter_upper", 0x3f), ins.get("plist_speed", 1), len(ins.get("plist", [])), + ]) + + +def names(song): + return b"".join(s.encode("latin-1") + b"\0" for s in [song.get("title", "")] + [i.get("name", "") for i in song["instruments"]]) + + +def header_common(song): + posn = len(song["positions"]) + flag6 = (0x80 if song.get("empty_track0") else 0) | ((song.get("speedmult", 1) - 1) << 5) | (posn >> 8) + return flag6, posn + + +def write_ahx(song): + trkl = song["trkl"] + tracks = song["tracks"] + flag6, posn = header_common(song) + body = b"".join(struct.pack(">H", s) for s in song.get("subsongs", [])) + for pos in song["positions"]: + for tr, tp in pos: + body += bytes([tr, tp & 0xff]) + for i, t in enumerate(tracks): + if i == 0 and song.get("empty_track0"): + continue + for j in range(trkl): + note, ins, fx, par = (t[j] + (0, 0, 0, 0))[:4] if j < len(t) else (0, 0, 0, 0) + body += bytes([(note << 2) | (ins >> 4), ((ins & 15) << 4) | fx, par]) + for ins in song["instruments"]: + body += ins_header(ins) + for (note, fixed, wave, fx0, p0, fx1, p1) in ins.get("plist", []): + body += bytes([(AHX_FX[fx1] << 5) | (AHX_FX[fx0] << 2) | (wave >> 1), ((wave & 1) << 7) | (fixed << 6) | note, p0, p1]) + nameat = 14 + len(body) + hdr = b"THX" + bytes([song.get("version", 1)]) + struct.pack(">HBBHBBBB", nameat, flag6, posn & 0xff, + song.get("restart", 0), trkl, len(tracks) - 1, + len(song["instruments"]), len(song.get("subsongs", []))) + return hdr + body + names(song) + + +def write_hvl(song): + trkl = song["trkl"] + tracks = song["tracks"] + ch = song["channels"] + flag6, posn = header_common(song) + restart = song.get("restart", 0) + body = b"".join(struct.pack(">H", s) for s in song.get("subsongs", [])) + for pos in song["positions"]: + for tr, tp in pos: + body += bytes([tr, tp & 0xff]) + for i, t in enumerate(tracks): + if i == 0 and song.get("empty_track0"): + continue + for j in range(trkl): + row = (tuple(t[j]) + (0,) * 6)[:6] if j < len(t) else (0,) * 6 + if row == (0,) * 6 and j % 3 == 0: + body += b"\x3f" # the one-byte empty step (sometimes: both encodings are valid) + else: + note, ins, fx, par, fxb, parb = row + body += bytes([note, ins, (fx << 4) | fxb, par, parb]) + for ins in song["instruments"]: + body += ins_header(ins) + for (note, fixed, wave, fx0, p0, fx1, p1) in ins.get("plist", []): + body += bytes([fx0, (fx1 << 3) | wave, (fixed << 6) | note, p0, p1]) + nameat = 16 + len(body) + hdr = b"HVL" + bytes([song.get("version", 1)]) + struct.pack(">HBBBBBBBBBB", nameat, flag6, posn & 0xff, + ((ch - 4) << 2) | (restart >> 8), restart & 0xff, trkl, + len(tracks) - 1, len(song["instruments"]), + len(song.get("subsongs", [])), song.get("mixgain", 100), + song.get("stereo", 2)) + return hdr + body + names(song) + + +def hvl2wav(ctx, data, ext, args=()): + """the reference render: (s16le interleaved stereo bytes, frames)""" + with tempfile.TemporaryDirectory() as d: + src = os.path.join(d, "song." + ext) + out = os.path.join(d, "out.wav") + with open(src, "wb") as f: + f.write(data) + ctx.nix("hivelytracker", ["hvl2wav", "-o" + out] + list(args) + [src]) + raw = open(out, "rb").read() + assert raw[:4] == b"RIFF" and raw[36:40] == b"data", "hvl2wav: unexpected wav" + pcm = bytearray(raw[44:]) + pcm[0::2], pcm[1::2] = pcm[1::2], pcm[0::2] # undo the -D_BIG_ENDIAN_ byte swap + return bytes(pcm), len(pcm) // 4 + + +def source_songs(ctx): + """{name: bytes} from the HivelyTracker source's Songs/ directory""" + path = subprocess.run(["nix", "build", "nixpkgs#hivelytracker.src", "--no-link", "--print-out-paths"], + capture_output=True, check=True).stdout.decode().strip() + songs = {} + for f in sorted(os.listdir(os.path.join(path, "Songs"))): + with open(os.path.join(path, "Songs", f), "rb") as fh: + songs[f] = fh.read() + return songs + + +# ---------------------------------------------------------------------------------------------------- songs +def instruments(hvl): + """a set exercising every waveform, the filter and square sweeps and the PList commands""" + ins = [ + # 1: triangle lead with vibrato and a filter set (cmd 0) + perf slide up (cmd 1) + dict(name="tri", wavelen=4, env=(2, 64, 8, 40, 20, 12, 0), vib=(6, 3, 4), plist_speed=2, + plist=[(0, 0, 1, 0, 0x18, 1, 2), (0, 0, 0, 2, 3, 0, 0), (0, 0, 0, 12, 0x30, 0, 0)]), + # 2: sawtooth with the filter sweep (cmd 4 high nibble) and fixed notes + dict(name="saw", wavelen=5, filter_speed=3, filter_lower=8, filter_upper=50, env=(1, 64, 20, 30, 10, 20, 0), + plist_speed=3, plist=[(1, 0, 2, 4, 0x10, 0, 0), (25, 1, 0, 0, 0, 0, 0), (0, 0, 0, 0, 0, 0, 0)]), + # 3: square with modulation (cmd 4 low nibble, cmd 3 offset), hard cut release + dict(name="square", wavelen=3, square=(0x08, 0x38, 2), hardcut=(1, 3), env=(3, 50, 6, 40, 30, 8, 10), + plist_speed=1, plist=[(0, 0, 3, 3, 0x20, 4, 0x01), (0, 0, 0, 0, 0, 0, 0), (0, 0, 0, 15, 4, 0, 0), + (0, 0, 0, 5, 1, 0, 0)]), + # 4: noise drum: fixed note, falling filter, volume steps (cmd C) + dict(name="noise", wavelen=2, env=(1, 64, 4, 20, 2, 6, 0), filter_speed=1, filter_lower=1, filter_upper=40, + plist_speed=1, plist=[(40, 1, 4, 12, 0x40, 4, 0xf0), (30, 1, 0, 12, 0x20, 0, 0), (20, 1, 1, 0, 0, 0, 0)]), + # 5: square + filter toggles together (cmd 4 0xff: negative directions), perf slide down + dict(name="pwm", wavelen=5, square=(0x3f, 0x10, 1), filter_speed=5, filter_lower=20, filter_upper=60, + env=(4, 60, 10, 50, 40, 10, 0), plist_speed=2, + plist=[(0, 0, 3, 4, 0xff, 2, 4), (0, 0, 0, 0, 0, 1, 1), (12, 0, 2, 3, 0x10, 0, 0)]), + ] + if hvl: + # 6: ring modulation (cmd 7 triangle relative / cmd 8 saw fixed) and PList panning (cmd 9) + ins.append(dict(name="ring", wavelen=4, env=(1, 64, 10, 48, 20, 10, 0), plist_speed=2, + plist=[(0, 0, 2, 7, 0x8c, 9, 0x40), (0, 0, 0, 8, 0x20, 0, 0), (0, 0, 3, 7, 0x85, 9, 0xc0), + (0, 0, 0, 7, 0, 0, 0)])) + return ins + + +def demo_song(hvl): + """hand-written: notes on every instrument and the main effects""" + E = [] + t1 = [(25, 1), (), (27, 0, 0xA, 0x02), (), (29, 2, 0x1, 0x04), (), (0, 0, 0x2, 0x04), (), (30, 3), (), (0, 0, 0xE, 0x13), + (32, 4), (25, 5, 0xC, 0x30), (), (37, 1, 0x3, 0x08), (0, 0, 0x4, 0x50)] + t2 = [(13, 4), (), (13, 4, 0xE, 0xD2), (), (20, 3, 0x9, 0x10), (), (13, 4, 0xE, 0xC2), (), (13, 2, 0xE, 0xA4), (), + (15, 2, 0xE, 0x24), (), (13, 4, 0xC, 0x60), (), (17, 5, 0x5, 0x31), ()] + t3 = [(37, 2), (), (), (), (39, 1, 0xE, 0x44), (), (), (), (41, 5), (), (), (), (36, 3, 0xF, 0x04), (), (), (0, 0, 0xD, 0x00)] + if hvl: + t2 = [r + ((0x7, 0x30) if len(r) == 4 else ()) if r else r for r in t2] + t1[0] = (25, 6, 0x7, 0xd0, 0x1, 0x01) + t3[4] = (39, 6, 0xE, 0x44, 0xC, 0x20) + tracks = [E, t1, t2, t3] + ch = 6 if hvl else 4 + pos = [] + for k in range(2): + row = [(1, 0), (2, 0), (3, k * 2), (0, 0)] + if hvl: + row += [(3, -12), (1, 5)] + pos.append(row) + return dict(title="demo", trkl=16, tracks=tracks, positions=pos, channels=ch, instruments=instruments(hvl), + empty_track0=True, mixgain=110, stereo=3, subsongs=[1]) + + +def random_song(rng, hvl, n_tracks=6, trkl=16, n_pos=3): + ins = instruments(hvl) + ch = rng.choice([4, 5, 8]) if hvl else 4 + fxs = [0x1, 0x2, 0x3, 0x4, 0x5, 0x9, 0xA, 0xC, 0xE] + ([0x7] if hvl else []) + tracks = [[]] + for _ in range(n_tracks): + t = [] + for _ in range(trkl): + r = rng.random() + if r < 0.45: + t.append(()) + continue + note = rng.randint(1, 60) if rng.random() < 0.8 else 0 + inst = rng.randint(1, len(ins)) if rng.random() < 0.7 else 0 + fx, par = 0, 0 + if rng.random() < 0.5: + fx = rng.choice(fxs) + par = rng.randint(0, 255) + if fx == 0xE: + par = rng.choice([0x1, 0x2, 0x4, 0xA, 0xB, 0xC, 0xD]) << 4 | rng.randint(0, 5) + if fx == 0xC: + par = rng.choice([rng.randint(0, 0x40), 0x50 + rng.randint(0, 0x40), 0xa0 + rng.randint(0, 0x40)]) + if fx == 0x4: + par = rng.randint(0x41, 0x7f) if rng.random() < 0.6 else rng.randint(1, 0x3f) + row = (note, inst, fx, par) + if hvl and rng.random() < 0.3: + row += (rng.choice([0x1, 0x2, 0xA, 0xC, 0x7]), rng.randint(0, 0x40)) + t.append(row) + tracks.append(t) + pos = [[(rng.randint(0, n_tracks), rng.randint(-5, 5)) for _ in range(ch)] for _ in range(n_pos)] + return dict(title="random", trkl=trkl, tracks=tracks, positions=pos, channels=ch, instruments=ins, + speedmult=rng.choice([1, 1, 2, 3]), mixgain=rng.choice([80, 100, 140]), stereo=rng.randint(0, 4), + version=rng.choice([0, 1, 2]) if not hvl else 1) diff --git a/tools/fixtures/_midivar.py b/tools/fixtures/_midivar.py new file mode 100644 index 0000000..c360848 --- /dev/null +++ b/tools/fixtures/_midivar.py @@ -0,0 +1,320 @@ +# MIDI-variant fixture helpers (not a generator; tools/fixtures/mus.py, xmi.py and hmp.py load it): small writers for +# Doom MUS, Miles XMIDI and HMI HMP, random event streams, and the reference conversion through wildmidi -x +# (nixpkgs#wildmidi: it writes a Standard MIDI File; only its event stream is used, read back by the small SMF reader +# below into channel events with times in seconds). +import os, random, struct, subprocess, tempfile + + +def vlq(v): + out = [v & 127] + v >>= 7 + while v: + out.insert(0, (v & 127) | 128) + v >>= 7 + return bytes(out) + + +def vlq_hmp(v): + """HMP deltas: 7-bit groups least significant first, the last byte has bit 7 set""" + out = [] + while True: + b = v & 127 + v >>= 7 + if v == 0: + out.append(b | 128) + return bytes(out) + out.append(b) + + +# ---------------------------------------------------------------------------------------------------- MUS +def write_mus(events, instruments=(), primary=4, secondary=0): + """events: [(delay_after, type, channel, data bytes)]; the last flag is set when delay_after > 0""" + score = b"" + for delay, typ, ch, data in events: + score += bytes([(0x80 if delay else 0) | (typ << 4) | ch]) + bytes(data) + if delay: + score += vlq(delay) + hdr_len = 16 + 2 * len(instruments) + hdr = b"MUS\x1a" + struct.pack(" 0 inserts that many system events (type 3, which wildmidi misreads: it takes two data + bytes) and measure ends (type 5, which wildmidi refuses), each with no delay, without changing anything else""" + ev = [] + held = {} + for ch in [0, 1, 2, 15]: + ev.append((0, 4, ch, [0, rng.randint(0, 127) if ch != 15 else 0])) # program change + for _ in range(n): + ch = rng.choice([0, 1, 2, 3, 15, 9]) + r = rng.random() + delay = rng.choice([0, 0, 1, 5, 17, 140, 200]) + if r < 0.45: + note = rng.randint(30, 90) + if rng.random() < 0.6: + ev.append((delay, 1, ch, [note | 0x80, rng.randint(1, 127)])) + else: + ev.append((delay, 1, ch, [note])) + held.setdefault(ch, []).append(note) + elif r < 0.75 and held.get(ch): + ev.append((delay, 0, ch, [held[ch].pop(0)])) + elif r < 0.85: + ev.append((delay, 2, ch, [rng.randint(0, 255)])) + else: + ev.append((delay, 4, ch, [rng.randint(0, 9), rng.randint(0, 127)])) + for ch, notes in held.items(): + for nt in notes: + ev.append((3, 0, ch, [nt])) + xr = random.Random(extras) + for _ in range(extras): + at = xr.randint(1, len(ev) - 1) + ch = ev[at][2] + ev.insert(at, (0, 5, ch, []) if xr.random() < 0.5 else (0, 3, ch, [xr.choice([10, 11, 12, 13, 14])])) + ev.append((0, 6, 0, [])) + return write_mus(ev, instruments=[1, 30, 128 + 7]) + + +# ---------------------------------------------------------------------------------------------------- XMI +def iff(cid, body): + return cid + struct.pack(">I", len(body)) + body + (b"\0" if len(body) % 2 else b"") + + +def xmi_events(events): + """events: [(delay, bytes)]: a delay is written as interval bytes (each <= 0x7F) before the event""" + out = b"" + for delay, ev in events: + while delay > 0x7f: + out += b"\x7f" + delay -= 0x7f + if delay: + out += bytes([delay]) + out += ev + return out + + +def write_xmi(songs, with_xdir=True, timb=True): + forms = [] + for evs in songs: + body = b"XMID" + if timb: + body += iff(b"TIMB", struct.pack(" HMP track data (ends with an end-of-track meta)""" + return b"".join(vlq_hmp(d) + e for d, e in events) + + +def random_hmp_tracks(rng, ntracks=3, n=60, running=True): + tracks = [hmp_track([(0, b"\xff\x2f\x00")])] # track 0: tempo / meta only, as in game files + for t in range(1, ntracks): + ch = t - 1 if t < 4 else 9 + ev = [(0, bytes([0xC0 | ch, rng.randint(0, 127)]))] + on = [] + running_ok, running = running, False + for _ in range(n): + d = rng.choice([0, 0, 5, 30, 60, 120, 400]) + r = rng.random() + if r < 0.5: + note = rng.randint(30, 90) + on.append(note) + # running status (status byte left out) now and then + ev.append((d, (b"" if running else bytes([0x90 | ch])) + bytes([note, rng.randint(1, 127)]))) + running = running_ok and rng.random() < 0.5 + elif r < 0.8 and on: + ev.append((d, bytes([0x80 | ch, on.pop(0), 64]))) + running = False + elif r < 0.9: + ev.append((d, bytes([0xB0 | ch, rng.choice([7, 10, 64]), rng.randint(0, 127)]))) + running = False + else: + ev.append((d, bytes([0xE0 | ch, rng.randint(0, 127), rng.randint(0, 127)]))) + running = False + for note in on: + ev.append((10, bytes([0x80 | ch, note, 0]))) + ev.append((0, b"\xff\x2f\x00")) + tracks.append(hmp_track(ev)) + return tracks + + +# ---------------------------------------------------------------------------------------------------- wildmidi +def read_smf(data): + """-> (division, [(tick, track, status, d1, d2)] channel events, [(tick, us)] tempos); format 2: track 1 only (its + first song: wildmidi writes every XMIDI song as a track of a format 2 file)""" + assert data[:4] == b"MThd" + fmt, ntrk, div = struct.unpack(">HHH", data[8:14]) + if fmt == 2: + ntrk = 1 + p = 8 + struct.unpack(">I", data[4:8])[0] + events, tempos = [], [] + for ti in range(ntrk): + assert data[p:p + 4] == b"MTrk" + n = struct.unpack(">I", data[p + 4:p + 8])[0] + q, e = p + 8, p + 8 + n + tick, run = 0, 0 + while q < e: + d = 0 + while True: + c = data[q] + q += 1 + d = d * 128 + (c & 127) + if c < 128: + break + tick += d + st = data[q] + if st < 0x80: + st = run + else: + q += 1 + if st == 0xFF: + typ = data[q] + q += 1 + ln = 0 + while True: + c = data[q] + q += 1 + ln = ln * 128 + (c & 127) + if c < 128: + break + if typ == 0x51: + tempos.append((tick, int.from_bytes(data[q:q + 3], "big"))) + q += ln + elif st in (0xF0, 0xF7): + ln = 0 + while True: + c = data[q] + q += 1 + ln = ln * 128 + (c & 127) + if c < 128: + break + q += ln + else: + run = st + k = 1 if st >> 4 in (0xC, 0xD) else 2 + d1 = data[q] + d2 = data[q + 1] if k == 2 else 0 + q += k + events.append((tick, ti, st, d1, d2)) + p = e + return div, events, tempos + + +def seconds(div, tempos, tick): + tempos = sorted(tempos) + t, last, us = 0.0, 0, 500000 + for tk, u in tempos: + if tk >= tick: + break + t += (tk - last) * us / 1e6 / div + last, us = tk, u + return t + (tick - last) * us / 1e6 / div + + +def wildmidi(ctx, data, ext, args=()): + """the reference: wildmidi -x's SMF as { division, tempo (first), events = { {time, status, d1, d2} } }""" + with tempfile.TemporaryDirectory() as d: + src = os.path.join(d, "in." + ext) + out = os.path.join(d, "out.mid") + with open(src, "wb") as f: + f.write(data) + r = subprocess.run(["nix", "shell", "nixpkgs#wildmidi", "-c", "wildmidi"] + list(args) + ["-x", out, src], + capture_output=True) + if not os.path.exists(out): + raise RuntimeError("wildmidi failed: " + r.stdout.decode(errors="replace")[-400:] + r.stderr.decode(errors="replace")[-400:]) + smf = open(out, "rb").read() + div, events, tempos = read_smf(smf) + events.sort(key=lambda e: (e[0], e[1])) + return {"division": div, "tempo": tempos[0][1] if tempos else 500000, + "events": [[seconds(div, tempos, tk), st, d1, d2] for tk, _, st, d1, d2 in events]} + + +# ---------------------------------------------------------------------------------------------------- HMI +def write_hmi(tracks, bpm=120): + """tracks: [bytes of event data (MIDI deltas; note-ons followed by a duration)]""" + hdr_len = 0x5B + head = bytearray(b"HMI-MIDISONG061595".ljust(370, b"\0")) + head[212] = bpm + head[228] = len(tracks) + table = b"" + body = b"" + at = 370 + 4 * len(tracks) + for data in tracks: + table += struct.pack("= 25)""" + tracks, index = [], {} + table = [] + for pat in patterns: + ids = [] + for ch in range(32): + if ch >= channels: + ids.append(0) + continue + tb = bytearray() + for r in range(rows): + note, ins, fx, param = pat[r][ch] if r < len(pat) else (0, 0, 0, 0) + n = note - 25 if note else 0 + tb += bytes([(n << 2) | (ins >> 4), ((ins & 15) << 4) | fx, param]) + tb = bytes(tb) + b"\0" * (192 - len(tb)) + if not any(tb): + ids.append(0) + continue + if tb not in index: + tracks.append(tb) + index[tb] = len(tracks) + ids.append(index[tb]) + table.append(ids) + out = bytearray(b"MTM\x10" + name(title, 20)) + out += struct.pack("= 37), ins 1-based, vol 0..15 or None, effect byte (cmd << 4 | param) + or None; tempos / breaks: per pattern""" + out = bytearray(b"JN" if extended else b"if") + msg = message.encode()[:108] + out += msg + b" " * (108 - len(msg)) + out += bytes([len(samples), len(patterns), restart]) + out += bytes(orders) + b"\xff" * (128 - len(orders)) + out += bytes(tempos) + b"\x04" * (128 - len(tempos)) + out += bytes(breaks) + b"\x3f" * (128 - len(breaks)) + for s in samples: + ls, le = s.get("loop") or (0, 0xFFFFF) + out += name(s.get("name", ""), 13) + struct.pack("> 4), ((i & 15) << 4) | (vol if vol is not None else 0)]) + elif vol is not None: + out += bytes([0xFE, vol]) + else: + out += b"\xff\x00" + out.append(0xFF if eff is None else eff) + for s in samples: + out += s["data"] + return bytes(out) + + +def write_stm(title, samples, orders, patterns, tempo=0x60, gvol=64, minor=21): + """samples: [{name, data (signed bytes), volume, c2spd, loop: (start, end) | None}] (up to 31); patterns: [[row: + [(note, ins, vol, cmd, info)] * 4] * 64] with note 0 = none, 254 = cut, else our note (>= 37); vol None = none; + cmd 0 = none (A = 1, letters as in S3M)""" + head = bytearray(name(title, 20) + b"!Scream!" + bytes([0x1A, 2, 2, minor, tempo, len(patterns), gvol]) + b"\0" * 13) + smp_at = len(head) + head += b"\0" * (31 * 32) + head += bytes(orders) + bytes([99] * ((64 if minor == 0 else 128) - len(orders))) + for pat in patterns: + for row in pat: + for (note, ins, vol, cmd, info) in row: + if note in ("skip", "fb"): + head.append(0xFC if note == "skip" else 0xFB) # nothing / a C-0 at volume 0 + continue + if note == 254: + nb = 0xFE + elif note: + n = note - 37 + nb = (n // 12) << 4 | (n % 12) + else: + nb = 0xFF + v = 65 if vol is None else vol + head += bytes([nb, (ins << 3) | (v & 7), ((v >> 3) << 4) | cmd, info]) + body = head + for i in range(31): + h = bytearray(32) + if i < len(samples): + s = samples[i] + while len(body) % 16: + body.append(0) + off = len(body) // 16 + body += s["data"] + ls, le = s.get("loop") or (0, 0xFFFF) + h[0:12] = name(s.get("name", ""), 12) + struct.pack_into("= 4: + out += struct.pack("= 3: + out += bytes(pans or [(i % 2) * 15 for i in range(channels)]) + for ch in range(channels): + for pat in patterns: + evs = [] + for row in pat: + note, ins, e1, p1, e2, p2 = row[ch] + evs.append(bytes([note - 24 if note else 0, ins, (e2 << 4) | e1, p1, p2])) + i = 0 + while i < len(evs): + j = i + while j + 1 < len(evs) and evs[j + 1] == evs[i] and j - i < 250: + j += 1 + if j > i: + out += bytes([0xFC, j - i + 1]) + evs[i] + else: + out += evs[i] + i = j + 1 + for s in samples: + out += s["data"] + return bytes(out) + + +def write_ptm(title, samples, orders, patterns, channels, pans=None): + """samples: [{name, data (signed bytes; 16-bit little-endian), bits 8|16, volume, c4spd, loop: (start, end) in + frames | None, pingpong}] (stored delta coded: 8-bit deltas of the byte stream, also for 16-bit); patterns: [[row: + [(note, ins, vol, cmd, param)] * channels] * 64] with note 0 = none, 254 = cut, else our note (1..120); vol None = + none; cmd None = none, else 0..0x16 (MOD effects 0..F, then PolyTracker's G..)""" + head = bytearray(name(title, 28) + bytes([26, 3, 2, 0])) + head += struct.pack("> 3] |= 1 << (i & 7) + body += smap + for s in samples: + bps = 2 if s.get("bits", 8) == 16 else 1 + ls, le = s.get("loop") or (0, 0) + body += name(s.get("name", ""), 32) + struct.pack("I", len(data)) + data + out = bytearray(b"OKTASONG") + out += chunk(b"CMOD", b"".join(struct.pack(">H", c) for c in cmod)) + sh = bytearray() + for i in range(36): + if i < len(samples): + s = samples[i] + ls, ll = s.get("loop") or (0, 0) + sh += name(s.get("name", ""), 20) + struct.pack(">IHHHH", len(s["data"]), ls // 2, ll // 2, s.get("volume", 64), s.get("type", 2)) + else: + sh += b"\0" * 32 + out += chunk(b"SAMP", bytes(sh)) + out += chunk(b"SPEE", struct.pack(">H", speed)) + out += chunk(b"SLEN", struct.pack(">H", len(patterns))) + out += chunk(b"PLEN", struct.pack(">H", len(orders))) + out += chunk(b"PATT", bytes(orders) + b"\0" * (128 - len(orders))) + for pat in patterns: + pb = bytearray(struct.pack(">H", len(pat))) + for row in pat: + for (note, ins, fx, param) in row: + pb += bytes([note, max(0, ins - 1), fx, param]) + out += chunk(b"PBOD", bytes(pb)) + for s in samples: + out += chunk(b"SBOD", s["data"]) + return bytes(out) + + +def write_med(version, samples, blocks, sequence, tempo=125, tempo2=6, flags=0, flags2=0, trackvols=None, + pans=None, master=64, play_transpose=0, sections=None, title=None): + """an MMD0 .. MMD3 module. samples: [{data (signed 8-bit bytes, or big-endian 16-bit with bits 16), bits, volume, + transpose, loop: (start, length) in bytes (even) | None, hold, decay, finetune, octaves (IFF multi-octave count: + data holds the octaves from the lowest, each twice as long)}]; blocks: [[row: [(note, ins, cmd, param)] * tracks] + * rows] with note 0 = none else the MED note (1 = C-1; MMD1+: 0x80 = note off); sequence: block numbers (MMD0 / 1) + or the play sequence (MMD2 / 3; sections: [[playseq numbers]] and playseqs = [sequence])""" + out = bytearray(52) + song_at = 52 + out += b"\0" * (63 * 8 + 284) + need_ext = any(s.get("hold") or s.get("finetune") for s in samples) or title is not None + + def align(): + while len(out) % 4: + out.append(0) + + # blocks + block_ptrs = [] + for blk in blocks: + align() + block_ptrs.append(len(out)) + ntr = len(blk[0]) + if version == 0: + out += bytes([ntr, len(blk) - 1]) + else: + out += struct.pack(">HHI", ntr, len(blk) - 1, 0) + for row in blk: + for (note, ins, cmd, param) in row: + if version == 0: + out += bytes([(note & 0x3F) | ((ins & 0x10) << 3) | ((ins & 0x20) << 1), ((ins & 15) << 4) | (cmd & 15), param]) + else: + out += bytes([note, ins & 0x3F, cmd, param]) + align() + block_arr = len(out) + for p in block_ptrs: + out += struct.pack(">I", p) + # instruments + inst_ptrs = [] + for s in samples: + align() + inst_ptrs.append(len(out)) + oct_ = s.get("octaves", 1) + typ = {1: 0, 5: 1, 3: 2, 2: 3, 4: 4, 6: 5, 7: 6}[oct_] | (0x10 if s.get("bits", 8) == 16 else 0) + out += struct.pack(">Ih", len(s["data"]), typ) + s["data"] + align() + smp_arr = len(out) + for p in inst_ptrs: + out += struct.pack(">I", p) + # play sequences (MMD2 / 3) + seq_info = None + if version >= 2: + align() + psq = [] + for sq in [sequence]: + psq.append(len(out)) + out += name("seq", 32) + struct.pack(">IIH", 0, 0, len(sq)) + b"".join(struct.pack(">H", b) for b in sq) + align() + ps_table = len(out) + for p in psq: + out += struct.pack(">I", p) + sec_table = len(out) + secs = sections or [0] + for sc in secs: + out += struct.pack(">H", sc) + align() + tv = len(out) + out += bytes(trackvols or [64] * len(blocks[0][0])) + tp = 0 + if pans: + tp = len(out) + out += bytes([p & 255 for p in pans]) + seq_info = (ps_table, sec_table, tv, tp, len(secs)) + # expansion: instrument extras + song name + exp = 0 + if need_ext: + align() + ie = len(out) + for s in samples: + ls, ll = s.get("loop") or (0, 0) + out += struct.pack(">BBBbBBHBBIIBBH", s.get("hold", 0), s.get("decay", 0), 0, s.get("finetune", 0), 0, + 1 if s.get("loop") else 0, 0, 0, 0, ls, ll, 127, 0, 0) + nm = (title or "").encode() + b"\0" + na = len(out) + out += nm + align() + exp = len(out) + e = bytearray(80) + struct.pack_into(">IIHH", e, 0, 0, ie, len(samples), 22) + struct.pack_into(">II", e, 44, na, len(nm)) + out += e + # the song header + for i, s in enumerate(samples): + ls, ll = s.get("loop") or (0, 0) + struct.pack_into(">HHBBBb", out, song_at + 8 * i, ls // 2, ll // 2, 0, 0, s.get("volume", 64), s.get("transpose", 0)) + sh = song_at + 63 * 8 + if version < 2: + struct.pack_into(">HH", out, sh, len(blocks), len(sequence)) + out[sh + 4:sh + 4 + len(sequence)] = bytes(sequence) + else: + ps_table, sec_table, tv, tp, nsec = seq_info + struct.pack_into(">HH", out, sh, len(blocks), nsec) + struct.pack_into(">IIIHHIIHH", out, sh + 4, ps_table, sec_table, tv, len(blocks[0][0]), 1, tp, 0, 100, 0) + struct.pack_into(">HbBBB", out, sh + 260, tempo, play_transpose, flags, flags2, tempo2) + out[sh + 266:sh + 282] = bytes((trackvols or [64] * 16)[:16]) + bytes(max(0, 16 - len(trackvols or [0] * 16))) + out[sh + 282] = master + out[sh + 283] = len(samples) + hdr = bytearray(b"MMD" + bytes([0x30 + version])) + hdr += struct.pack(">IIHHIB3sIIII11sB", len(out), song_at, 0, 0, block_arr, 0, b"\0\0\0", smp_arr, 0, exp, 0, b"\0" * 11, 0) + out[0:52] = hdr + return bytes(out) + + +def umx_index(v): + """an Unreal compact index""" + neg, v = v < 0, abs(v) + out = bytearray([(0x80 if neg else 0) | (v & 0x3F) | (0x40 if v > 0x3F else 0)]) + v >>= 6 + while v: + out.append((v & 0x7F) | (0x80 if v > 0x7F else 0)) + v >>= 7 + return bytes(out) + + +def write_umx(modules, version=69): + """an Unreal package (UT99-era, package version 61..99) whose exports are Music objects: modules = [(object + name, module bytes)]""" + names = ["None", "Music", "Core", "Class"] + [n for n, _ in modules] + out = bytearray(36) + name_at = len(out) + for n in names: + b = n.encode() + b"\0" + out += (umx_index(len(b)) if version >= 64 else b"") + b + struct.pack("> 1) + (words >> 3)) * 2 + # crc1 is the first word of the span: solve the linear map W -> crc(W || 0...) for crc(W || rest) == 0 + rest = crc16(bytes(2) + bytes(f[4:n58])) + basis = [crc16(bytes([(1 << i) >> 8, (1 << i) & 255]) + bytes(n58 - 4)) for i in range(16)] + rows = [(basis[i], 1 << i) for i in range(16)] + pivots = {} + for v, m in rows: + for bit in range(15, -1, -1): + if not v >> bit & 1: + continue + if bit in pivots: + pv, pm = pivots[bit] + v, m = v ^ pv, m ^ pm + else: + pivots[bit] = (v, m) + break + w, target = 0, rest + for bit in range(15, -1, -1): + if target >> bit & 1: + pv, pm = pivots[bit] + target ^= pv + w ^= pm + f[2], f[3] = w >> 8, w & 255 + assert crc16(bytes(f[2:n58])) == 0 + c2 = crc16(bytes(f[2:-2])) + f[-2], f[-1] = c2 >> 8, c2 & 255 + assert crc16(bytes(f[2:])) == 0 + + +def undither(ctx, data): + """clear every dithflag (after the blksw flags at each audio block's start) and fix the CRCs""" + code = """ +local Ac3 = require("@formats/codecs/audio/Ac3") +local b = buffer.fromstring(%s) +local dec = Ac3.decoder() +local o, n = 0, buffer.len(b) +while o + 8 <= n do + local h = Ac3.header(b, o, n) + if not h then break end + assert(dec:decode(b, o, h.frameSize)) + print(o, h.frameSize, h.acmod, table.concat(dec.blocks, " ")) + o += h.frameSize +end +""" % _lit(data) + out = bytearray(data) + for line in A.luau(ctx, code).decode().strip().split("\n"): + v = [int(x) for x in line.split()] + o, size, acmod, blocks = v[0], v[1], v[2], v[3:] + nf = NFCHANS[acmod] + f = out[o:o + size] + for p in blocks: + for k in range(nf): + bit = p + nf + k + f[bit >> 3] &= ~(0x80 >> (bit & 7)) & 255 + fix_crcs(f) + out[o:o + size] = f + return bytes(out) + + +# name, encoder, layout (ffmpeg) or (acmod, lfe) (aften), rate, kbps, extra options +CASES = [ + ("mono_48k", "ffmpeg", "mono", 48000, 96, []), + ("stereo_44k", "ffmpeg", "stereo", 44100, 192, []), + ("stereo_cpl_48k", "ffmpeg", "stereo", 48000, 96, ["-channel_coupling", "1", "-cpl_start_band", "1"]), + ("stereo_cpl0_48k", "ffmpeg", "stereo", 48000, 64, ["-channel_coupling", "1", "-cpl_start_band", "0"]), + ("stereo_32k", "ffmpeg", "stereo", 32000, 64, []), + ("3.0_48k", "ffmpeg", "3.0", 48000, 256, []), + ("2.1_48k", "ffmpeg", "2.1", 48000, 192, []), + ("3.0back_48k", "ffmpeg", "3.0(back)", 48000, 192, []), + ("4.0_48k", "ffmpeg", "4.0", 48000, 256, []), + ("4.1_44k", "ffmpeg", "4.1", 44100, 320, []), + ("quad_side_48k", "ffmpeg", "quad(side)", 48000, 256, []), + ("5.0_side_32k", "ffmpeg", "5.0(side)", 32000, 320, []), + ("5.1_448", "ffmpeg", "5.1(side)", 48000, 448, []), + ("5.1_cpl_256", "ffmpeg", "5.1(side)", 48000, 256, ["-channel_coupling", "1"]), + ("aften_blksw_stereo", "aften", (2, 0), 48000, 192, ["-s", "1"]), + ("aften_dualmono", "aften", (0, 0), 48000, 128, []), + ("aften_5.1_blksw", "aften", (7, 1), 48000, 384, ["-s", "1"]), + ("aften_5.1_drc", "aften", (7, 1), 48000, 384, ["-dynrng", "1"]), + ("aften_xbsi_2.2", "aften", (6, 0), 44100, 256, ["-xbsi1", "1", "-xbsi2", "1", "-s", "1"]), +] +CHANNELS = {"mono": 1, "stereo": 2, "3.0": 3, "2.1": 3, "3.0(back)": 3, "4.0": 4, "4.1": 5, "quad(side)": 4, + "5.0(side)": 5, "5.1(side)": 6} +ACMOD_CH = {0: 2, 1: 1, 2: 2, 3: 3, 4: 3, 5: 4, 6: 4, 7: 5} + + +def signal(frames, ch, rate, seed): + """per-channel tones with vibrato, noise bursts and clicks (transients for block switching)""" + rng = random.Random(seed) + out = [0.0] * (frames * ch) + for c in range(ch): + f = 110.0 * (c + 2) * (1.0 + 0.07 * c) + for i in range(frames): + t = i / rate + v = 0.2 * math.sin(2 * math.pi * f * t + 2 * math.sin(2 * math.pi * 4 * t)) + v += 0.06 * math.sin(2 * math.pi * (2500 + 700 * c) * t) + if (i // (rate // 10) + c) % 4 == 1: + v += 0.12 * (rng.random() * 2 - 1) + k = i % (rate // 7) + if k < 60: + v += 0.5 * (1 - k / 60) * (1 if (i // 5) % 2 else -1) + out[i * ch + c] = v + return out + + +def raw(samples): + return struct.pack("<%df" % len(samples), *samples) + + +def a52dec(run, d, name, ch): + """liba52's decode: float (planar per 256-sample block) for stereo, 16-bit wav6 otherwise -> f32le, WAVE order""" + flags = "-a -r" + if ch == 2: + raw_ = run("a52dec -o float %s %s 2>/dev/null" % (flags, name)) + v = struct.unpack("<%df" % (len(raw_) // 4), raw_) + out = [0.0] * len(v) + for b in range(len(v) // 512): + for i in range(256): + out[(b * 256 + i) * 2] = v[b * 512 + i] + out[(b * 256 + i) * 2 + 1] = v[b * 512 + 256 + i] + return raw(out) + wav = run("a52dec -o wav6 %s %s 2>/dev/null" % (flags, name)) + p = wav.index(b"data") + 8 + pcm = struct.unpack("<%dh" % ((len(wav) - p) // 2), wav[p:p + (len(wav) - p) // 2 * 2]) + return raw([x / 32768 for x in pcm]) + + +def generate(ctx): + d = tempfile.mkdtemp(prefix="fmt-ac3-") + cases, tracks = [], [] + try: + def run(cmd): + return ctx.nix(["ffmpeg", "aften", "a52dec"], ["sh", "-c", "cd '%s' && %s" % (d, cmd)]) + + for name, enc, layout, rate, kbps, extra in CASES: + ch = CHANNELS[layout] if enc == "ffmpeg" else ACMOD_CH[layout[0]] + layout[1] + frames = int(rate * SECONDS) + sig = signal(frames, ch, rate, len(name)) + with open(os.path.join(d, name + ".raw"), "wb") as f: + f.write(raw(sig)) + out = name + ".ac3" + if enc == "ffmpeg": + run("ffmpeg -v error -y -f f32le -ar %d -ch_layout '%s' -i %s.raw -c:a ac3 -b:a %dk %s %s" + % (rate, layout, name, kbps, " ".join(extra), out)) + else: + with open(os.path.join(d, name + ".wav"), "wb") as f: + f.write(A.wav(sig, rate, ch)) + run("aften -v 0 -threads 1 -b %d -acmod %d -lfe %d %s %s.wav %s" % (kbps, layout[0], layout[1], " ".join(extra), name, out)) + with open(os.path.join(d, out), "rb") as f: + orig = f.read() + data = undither(ctx, orig) + with open(os.path.join(d, "u_" + out), "wb") as f: + f.write(data) + c = {"name": name, "data": data, "channels": ch, "rate": rate} + if "-s" in extra: + c["ref"], c["refTool"] = a52dec(run, d, "u_" + out, ch), "a52dec" + else: + c["ref"], c["refTool"] = run("ffmpeg -v error -drc_scale 0 -i u_%s -f f32le -" % out), "ffmpeg" + if "-dynrng" in extra: + c["refDrc"] = run("ffmpeg -v error -drc_scale 1 -i u_%s -f f32le -" % out) + c["frames"] = len(c["ref"]) // (4 * ch) + if name in DITHERED: + c["dithered"] = orig + cases.append(c) + # AC-3 tracks in containers: the (undithered) AC-3 remuxed with a tiny Motion-JPEG / MPEG-1 picture track + sig = signal(int(48000 * 0.3), 6, 48000, 7) + with open(os.path.join(d, "t.raw"), "wb") as f: + f.write(raw(sig)) + for name, video, layout in (("ac3.mkv", "-c:v mjpeg -pix_fmt yuvj420p", "5.1(side)"), + ("ac3.mp4", "-c:v mjpeg -pix_fmt yuvj420p", "stereo"), ("ac3.ts", "-c:v mpeg1video", "stereo"), + ("ac3.avi", "-c:v mjpeg -pix_fmt yuvj420p", "stereo")): + run("ffmpeg -v error -y -f f32le -ar 48000 -ch_layout '5.1(side)' -i t.raw -af aformat=channel_layouts='%s' " + "-c:a ac3 -b:a 192k t.ac3" % layout) + with open(os.path.join(d, "t.ac3"), "rb") as f: + es = undither(ctx, f.read()) + with open(os.path.join(d, "u.ac3"), "wb") as f: + f.write(es) + run("ffmpeg -v error -y -f lavfi -i testsrc=size=64x48:rate=25:duration=0.3 -i u.ac3 %s -c:a copy -shortest %s" + % (video, name)) + with open(os.path.join(d, name), "rb") as f: + data = f.read() + ref = run("ffmpeg -v error -drc_scale 0 -i u.ac3 -f f32le -") + tracks.append({"name": name, "data": data, "channels": CHANNELS[layout], "rate": 48000, "ref": ref}) + finally: + shutil.rmtree(d, ignore_errors=True) + ctx.emit("ac3_cases", cases) + ctx.emit("ac3_tracks", tracks) diff --git a/tools/fixtures/adpcm.py b/tools/fixtures/adpcm.py new file mode 100644 index 0000000..a365f86 --- /dev/null +++ b/tools/fixtures/adpcm.py @@ -0,0 +1,138 @@ +# ADPCM fixtures (tools/fixtures.py): codecs/audio/Adpcm and the raw audio/adpcm format. +# tests/gen/adpcm_codec.luau raw codec streams with the reference decoder's s16le output: { name, kind, data, ch, +# frames, ref, rate?, cutoff?, v3?, coefs? } +# adx ffmpeg -f adx (version 3), the frames after the header; vgmstream decodes (scale + 1, v3 rounding) +# psx our Python PS-ADPCM encoder (tools/fixtures/_adpcm.py) in a VAG; vgmstream decodes +# dsp our Python DSP encoder in a mono BRSTM; vgmstream decodes +# ima_qt ffmpeg adpcm_ima_qt in AIFF-C (the SSND packets); ffmpeg decodes +# ima our Python IMA encoder in KVAG (high nibble first, stereo by nibble); ffmpeg (adpcm_ima_ssi) decodes +# tests/gen/adpcm_raw.luau headerless streams for audio/adpcm: { name, codec, data, rate, ch, blockAlign?, ref } +# ima / ima-stereo (KVAG data, ffmpeg), ms (ffmpeg adpcm_ms WAV data chunk, ffmpeg), ima_wav (ffmpeg +# adpcm_ima_wav), ima_qt (the AIFF-C packets), psx (VAG data), dsp (mono), adx-free +# tests/gen/adpcm_ours.luau our encoder's raw output (audio/adpcm encode, run in this step) wrapped in a container +# ffmpeg reads, ffmpeg's decode, and our own decode of the same bytes (must match) +# tests/gen/adpcm_sig.luau the encoder input (stereo) +import importlib.util, os, struct + +_dir = os.path.dirname(os.path.abspath(__file__)) + + +def _load(name): + spec = importlib.util.spec_from_file_location(name, os.path.join(_dir, name + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +A = _load("_audio") +D = _load("_adpcm") + +INPUTS = ["tools/fixtures/_adpcm.py", "src/Formats/codecs/audio/Adpcm", "src/Formats/audio/adpcm"] +RATE = 22050 + + +def aiff_ssnd(d): + p = 12 + while p + 8 <= len(d): + cid, size = d[p:p + 4], struct.unpack_from(">I", d, p + 4)[0] + if cid == b"SSND": + off = struct.unpack_from(">I", d, p + 8)[0] + return d[p + 16 + off:p + 8 + size] + p += 8 + size + (size & 1) + raise ValueError("no SSND") + + +def wav_data(d): + p = 12 + fmt = None + while p + 8 <= len(d): + cid, size = d[p:p + 4], struct.unpack_from("H", f, 2)[0] + 4 + rate, frames, cutoff, ver = struct.unpack_from(">IIHH", f, 8) + _, rch, ref = D.vgdecode(ctx, f, "adx") + assert rch == ch and len(ref) == frames * ch * 2, (len(ref), frames) + codec.append(dict(name=name, kind="adx", data=f[start:], ch=ch, frames=frames, ref=ref, rate=rate, + cutoff=cutoff, v3=ver == 0x0300)) + + # PS-ADPCM in a VAG (mono) + v = D.vag(mono, RATE) + _, _, ref = D.vgdecode(ctx, v, "vag") + codec.append(dict(name="psx", kind="psx", data=v[0x30:], ch=1, frames=len(ref) // 2, ref=ref)) + raw.append(dict(name="psx", codec="psx", data=v[0x30:], rate=RATE, ch=1, ref=ref)) + + # DSP in a mono BRSTM (one block holds everything) + ints = D.s16(mono) + dspdata = D.dsp_encode(ints) + f = D.rstm(mono, RATE, 1, "RSTM", block=(len(dspdata) + 31) // 32 * 32) + _, _, ref = D.vgdecode(ctx, f, "brstm") + assert len(ref) == len(ints) * 2 + codec.append(dict(name="dsp", kind="dsp", data=dspdata, ch=1, frames=len(ints), ref=ref, coefs=D.DSP_COEFS)) + + # Apple ima4 (AIFF-C) + for name, w, ch in (("ima_qt-mono", w1, 1), ("ima_qt-stereo", w2, 2)): + f = D.ffencode(ctx, w, ["-c:a", "adpcm_ima_qt", "-f", "aiff"], "aiff") + data = aiff_ssnd(f) + ref = D.ffs16(ctx, f, "aiff") + codec.append(dict(name=name, kind="ima_qt", data=data, ch=ch, frames=len(ref) // (2 * ch), ref=ref)) + raw.append(dict(name=name, codec="ima_qt", data=data, rate=RATE, ch=ch, ref=ref)) + + # IMA nibble streams (KVAG, high nibble first) + for name, sig, ch in (("ima-mono", mono, 1), ("ima-stereo", stereo, 2)): + f = D.kvag(sig, RATE, ch) + ref = D.ffs16(ctx, f, "vag", fmt="kvag") + codec.append(dict(name=name, kind="ima", data=f[14:], ch=ch, frames=len(ref) // (2 * ch), ref=ref)) + raw.append(dict(name=name, codec="ima", data=f[14:], rate=RATE, ch=ch, ref=ref)) + + # MS ADPCM / IMA WAV blocks (ffmpeg), as raw block streams + for name, codec_, w, ch in (("ms-stereo", "adpcm_ms", w2, 2), ("ms-mono", "adpcm_ms", w1, 1), + ("ima_wav-stereo", "adpcm_ima_wav", w2, 2)): + f = D.ffencode(ctx, w, ["-c:a", codec_, "-f", "wav"], "wav") + fmt, data = wav_data(f) + ba = struct.unpack_from(" containers ffmpeg reads -> ffmpeg's decode; the test decodes the same bytes itself + A.emit_signal(ctx, "adpcm_sig", stereo, RATE, 2) + ours = [] + for codec_, opts in (("ima", '{ codec = "ima" }'), ("ms", '{ codec = "ms", blockAlign = 512 }'), + ("ima_wav", '{ codec = "ima_wav", blockAlign = 512 }')): + data = A.encode_luau(ctx, "audio/adpcm", "adpcm_sig", opts) + if codec_ == "ima": + f = b"KVAG" + struct.pack("H", f, 2)[0] + 4 + frames_ = f[start:] + rate, n = struct.unpack_from(">II", f, 8) + head = bytearray(f[:0x14]) + struct.pack_into(">H", head, 0x12, 0x0400) + head += b"\0" * 4 + struct.pack(">hhhh", 300, -200, -150, 90) # 0x14 flags, 0x18 history (2 channels) + head += struct.pack(">HHIIIII", 0, 1, 1, 1024, 0, 6000, 0) + newstart = len(head) + 6 + struct.pack_into(">H", head, 2, newstart - 4) + cases.append(case(ctx, "v4-hist-loop", bytes(head) + b"(c)CRI" + frames_)) + ctx.emit("adx_cases", cases) + + sig = A.signal("music", 32000, 2, 9000, seed=11) + A.emit_signal(ctx, "adx_sig", sig, 32000, 2) + ours = [] + for name, opts in (("plain", "nil"), ("loop", "{ loop = { start = 1000, stop = 8000 } }")): + data = A.encode_luau(ctx, "audio/adx", "adx_sig", opts) + e = case(ctx, name, data) + e["opts"] = opts + ours.append(e) + ctx.emit("adx_ours", ours) diff --git a/tools/fixtures/ahx.py b/tools/fixtures/ahx.py new file mode 100644 index 0000000..bd70a3b --- /dev/null +++ b/tools/fixtures/ahx.py @@ -0,0 +1,36 @@ +# AHX fixtures (tools/fixtures.py): songs written by tools/fixtures/_hively.py (a hand-made demo over every waveform, +# filter / square sweeps, PList commands and effects; random songs) plus karma.ahx from the HivelyTracker source, each +# rendered by hvl2wav (nixpkgs#hivelytracker) as the reference. +# tests/gen/ahx_cases.luau { { name, data, crc (CRC-32 of hvl2wav's s16le stereo output), head (its first HEAD frames), frames, sampleRate, stereo, subsong, maxDuration?, +# prefix (true: hvl2wav ran with a time limit, compare the first frames only) } } +import importlib.util, os, zlib + +INPUTS = ["tools/fixtures/_hively.py"] +_spec = importlib.util.spec_from_file_location("_hively", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_hively.py")) +H = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(H) + + +HEAD = 11025 # frames of hvl2wav output kept as raw samples (to locate a mismatch); the rest is checked by CRC + + +def case(ctx, name, data, rate=44100, stereo=0, subsong=0, limit=None): + args = ["-f%d" % rate, "-x%d" % stereo, "-s%d" % subsong] + (["-t0:%02d" % limit] if limit else []) + pcm, frames = H.hvl2wav(ctx, data, "ahx", args) + c = {"name": name, "data": data, "crc": zlib.crc32(pcm), "head": pcm[:HEAD * 4], "frames": frames, "sampleRate": rate, "stereo": stereo, + "subsong": subsong, "prefix": limit is not None} + if limit: + c["maxDuration"] = limit + return c + + +def generate(ctx): + rng = ctx.rng(0xA4) + demo = H.write_ahx(H.demo_song(False)) + cases = [case(ctx, "demo", demo), case(ctx, "demo stereo 4", demo, stereo=4), + case(ctx, "demo 22050 Hz stereo 2", demo, rate=22050, stereo=2), case(ctx, "demo subsong 1", demo, subsong=1)] + for i in range(4): + cases.append(case(ctx, "random %d" % i, H.write_ahx(H.random_song(rng, False)), stereo=i)) + songs = H.source_songs(ctx) + cases.append(case(ctx, "karma.ahx", songs["karma.ahx"], stereo=4, limit=3)) + ctx.emit("ahx_cases", cases) diff --git a/tools/fixtures/aiff.py b/tools/fixtures/aiff.py index 1dafc07..d31fa69 100644 --- a/tools/fixtures/aiff.py +++ b/tools/fixtures/aiff.py @@ -10,7 +10,7 @@ _spec = importlib.util.spec_from_file_location("_audio", os.path.join(os.path.di A = importlib.util.module_from_spec(_spec) _spec.loader.exec_module(A) -INPUTS = ["src/Formats/audio/aiff", "src/Formats/codecs/audio/Pcm"] +INPUTS = ["src/Formats/audio/aiff", "src/Formats/codecs/audio/Pcm", "src/Formats/codecs/audio/Adpcm"] def ff(codec, src="{in}", extra=()): @@ -34,6 +34,8 @@ def generate(ctx): ("sox-aiff-s16", "sox", ["sox", "{in}", "-t", "aiff", "{out}"]), ("sox-aiff-s24-mono", "sox", ["sox", "{in_mono}", "-b", "24", "-t", "aiff", "{out}"]), ("sox-aifc-s16", "sox", ["sox", "{in}", "-t", "aifc", "{out}"]), + ("ffmpeg-ima4", "ffmpeg", ff("adpcm_ima_qt")), + ("ffmpeg-ima4-mono", "ffmpeg", ff("adpcm_ima_qt", "{in_mono}")), ] encodes = [ ("s16", "nil", 2), diff --git a/tools/fixtures/ape.py b/tools/fixtures/ape.py new file mode 100644 index 0000000..2e80483 --- /dev/null +++ b/tools/fixtures/ape.py @@ -0,0 +1,137 @@ +# Monkey's Audio fixtures (tools/fixtures.py): audio/ape, codecs/audio/Ape. +# tests/gen/ape_cases.luau synthetic signals encoded by the reference encoder (mac 13.28: -c1000 .. -c5000, 8 / 16 / +# 24 / 32-bit int and 32-bit float, 1 / 2 / 3 / 4 / 6 / 8 channels, odd rates, short and +# odd lengths, silence (special frames), mono-in-stereo (pseudo stereo), APEv2 tags), and +# the ffmpeg FATE samples luckynight-partial.ape (an older 3.99 encoder, cut) and +# NoLegacy-cut.ape (downloaded at fixture time, not committed); each with the CRC-32 of +# `mac -d`'s samples (integers as i32 LE, floats as their f32 bytes) +import importlib.util, os, struct, tempfile, urllib.request, zlib + +_spec = importlib.util.spec_from_file_location("_wv", os.path.join(os.path.dirname(os.path.abspath(__file__)), "wavpack.py")) +WV = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(WV) + +CTX = None +TMP = None +CASES = [] +FATE = "https://fate-suite.ffmpeg.org/lossless-audio/" + + +def wav_samples(path): + """(rate, channels, bits, float, ints-or-raw-bytes) of a WAV file (PCM / float, plain or extensible)""" + d = open(path, "rb").read() + i = 12 + fmt = data = None + while i + 8 <= len(d): + cid, size = d[i:i + 4], struct.unpack_from("I", len(body)) + body + + def text(s, kind=1): + s = s.encode() + return bytes([0xFF, kind]) + V.vlq(len(s)) + s + + melody = [(0, b"\xff\x51\x03\x07\xa1\x20"), (0, b"\xc0\x00")] + for n in (60, 62, 64, 65): + melody += [(0, bytes([0x90, n, 100])), (480, bytes([0x80, n, 0]))] + words = [(0, text("Words", 3)), (0, text("@KMIDI KARAOKE FILE")), (0, text("@TLittle Song")), (0, text("@TThe Docs")), + (0, text("\\Hel")), (480, text("lo ")), (480, text("/kar")), (480, text("aoke"))] + return b"MThd" + struct.pack(">IHHh", 6, 1, 2, 480) + trk(melody) + trk(words) + + +def generate(ctx): + dc = load(ctx, "docs_check") + H = load(ctx, "fixtures/_hively") + V = load(ctx, "fixtures/_midivar") + rng = random.Random(5) + files = { + "demo.ahx": H.write_ahx(H.demo_song(False)), + "demo.hvl": H.write_hvl(H.demo_song(True)), + "e1m1.mus": V.random_mus(rng, n=40), + "song.xmi": V.write_xmi([V.random_xmi_song(rng, n=30, tempo=500000), V.random_xmi_song(rng, n=10, tempo=500000)]), + "song.hmp": V.write_hmp(V.random_hmp_tracks(rng, ntracks=3, n=20, running=False)), + "song.kar": kar(V), + } + dc.emit_inputs(ctx, files, {"ahxBytes": "demo.ahx", "hvlBytes": "demo.hvl", "musBytes": "e1m1.mus", + "xmiBytes": "song.xmi", "hmpBytes": "song.hmp", "karBytes": "song.kar"}) diff --git a/tools/fixtures/docs_lossless.py b/tools/fixtures/docs_lossless.py new file mode 100644 index 0000000..825e520 --- /dev/null +++ b/tools/fixtures/docs_lossless.py @@ -0,0 +1,40 @@ +# Docs inputs for the guide's lossless audio section (tools/fixtures.py; tools/docs_check.py reads them): the docs +# stereo tone (tools/fixtures/docs_inputs.py) encoded by the reference encoders, with tags: WavPack lossless, WavPack +# hybrid (.wv + its .wvc correction file), Monkey's Audio (-c2000) and TTA. +# tests/gen/docs_lossless.luau { files = { [name] = bytes }, vars = { wvBytes = "tone.wv", ... } } +# tests/gen/docs_files/assets/ the same files, for the snippets that load by path +import importlib.util, os, tempfile + +INPUTS = ["tools/docs_check.py", "tools/fixtures/docs_inputs.py"] + + +def load(ctx, name): + spec = importlib.util.spec_from_file_location("docs_lossless_" + name.replace("/", "_"), + os.path.join(ctx.root, "tools", name + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def generate(ctx): + dc = load(ctx, "docs_check") + di = load(ctx, "fixtures/docs_inputs") + files = {} + with tempfile.TemporaryDirectory() as d: + wav = os.path.join(d, "tone.wav") + with open(wav, "wb") as f: + f.write(di.tone(44100, 1.0)) + tags = ["-w", "Title=Docs Tone", "-w", "Artist=formats-luau"] + ctx.nix("wavpack", ["wavpack", "-q", "-y", "-h"] + tags + [wav, "-o", os.path.join(d, "tone.wv")]) + ctx.nix("wavpack", ["wavpack", "-q", "-y", "-b3", "-c"] + tags + [wav, "-o", os.path.join(d, "tone_hybrid.wv")]) + ctx.nix("monkeys-audio", ["mac", wav, os.path.join(d, "tone.ape"), "-c2000", "-t", "Title=Docs Tone|Artist=formats-luau"]) + ctx.nix("ttaenc", ["ttaenc", "-e", wav, "-o", os.path.join(d, "tone.tta")]) + for name in ("tone.wv", "tone_hybrid.wv", "tone_hybrid.wvc", "tone.ape", "tone.tta"): + files[name] = open(os.path.join(d, name), "rb").read() + dc.emit_inputs(ctx, files, { + "wvBytes": "tone.wv", + "hybridWvBytes": "tone_hybrid.wv", + "hybridWvcBytes": "tone_hybrid.wvc", + "apeBytes": "tone.ape", + "ttaBytes": "tone.tta", + }) diff --git a/tools/fixtures/docs_lossy.py b/tools/fixtures/docs_lossy.py new file mode 100644 index 0000000..42f6f50 --- /dev/null +++ b/tools/fixtures/docs_lossy.py @@ -0,0 +1,39 @@ +# Docs inputs for the Musepack / AC-3 section of docs/guide/audio.md (tools/docs_check.py): a tagged stereo tone as +# Musepack SV8 (mpcenc, built by tools/fixtures/mpc.py's nix expression) and a 5.1 tone as AC-3 (ffmpeg). +# tests/gen/docs_lossy.luau { files = { [name] = bytes }, vars = { mpcBytes = "tone.mpc", ac3Bytes = "tone.ac3" } } +import importlib.util, math, os, shutil, struct, subprocess, tempfile + +INPUTS = ["tools/docs_check.py", "tools/fixtures/mpc.py"] + + +def load(ctx, rel, name): + spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, rel)) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def generate(ctx): + dc = load(ctx, "tools/docs_check.py", "docs_check") + mpc = load(ctx, "tools/fixtures/mpc.py", "docs_lossy_mpc") + d = tempfile.mkdtemp(prefix="fmt-docs-lossy-") + try: + rate, n = 44100, 44100 + st = [0.3 * math.sin(2 * math.pi * f * i / rate) for i in range(n) for f in (440, 660)] + with open(os.path.join(d, "tone.wav"), "wb") as f: + f.write(mpc.A.wav(st, rate, 2)) + subprocess.run([os.path.join(mpc.tools(), "mpcenc"), "--silent", "--overwrite", "--quality", "4", + "--tag", "Title=Docs Tone", "--artist", "formats-luau", os.path.join(d, "tone.wav"), + os.path.join(d, "tone.mpc")], capture_output=True, check=True) + six = [0.2 * math.sin(2 * math.pi * (200 + 100 * c) * i / 48000) for i in range(24000) for c in range(6)] + with open(os.path.join(d, "six.raw"), "wb") as f: + f.write(struct.pack("<%df" % len(six), *six)) + ctx.nix("ffmpeg", ["sh", "-c", "cd '%s' && ffmpeg -v error -y -f f32le -ar 48000 -ch_layout '5.1(side)' -i six.raw " + "-c:a ac3 -b:a 384k tone.ac3" % d]) + files = {} + for name in ("tone.mpc", "tone.ac3"): + with open(os.path.join(d, name), "rb") as f: + files[name] = f.read() + finally: + shutil.rmtree(d, ignore_errors=True) + dc.emit_inputs(ctx, files, {"mpcBytes": "tone.mpc", "ac3Bytes": "tone.ac3"}) diff --git a/tools/fixtures/far.py b/tools/fixtures/far.py new file mode 100644 index 0000000..25c4df0 --- /dev/null +++ b/tools/fixtures/far.py @@ -0,0 +1,81 @@ +# FAR fixtures (tools/fixtures.py): generated Farandole Composer modules exercising the effects, rendered by openmpt123. +# tests/gen/far_cases.luau { name, data (the module), ref (features of openmpt's render, tools/fixtures/_tracker.py), +# duration (openmpt's song length) } +import os, sys + +# the shared tracker module, loaded by path (tools/fixtures/ must not go on sys.path: xml.py there would shadow xml) +T = sys.modules.get("_tracker") +if T is None: + import importlib.util + _spec = importlib.util.spec_from_file_location("_tracker", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tracker.py")) + T = importlib.util.module_from_spec(_spec) + sys.modules["_tracker"] = T + _spec.loader.exec_module(T) + +INPUTS = ["tools/fixtures/_tracker.py"] + + +def empty(rows=64): + return [[(0, 0, 0, 0) for _ in range(16)] for _ in range(rows)] + + +def put(p, row, ch, note=0, ins=0, vol=0, cmd=None, param=0): + p[row][ch] = (note, ins, vol, 0 if cmd is None else (cmd << 4) | param) + + +def samples(): + return [ + {"name": "sine", "data": T.s8(T.synth("sine", 64, 64)), "volume": 15, "loop": (0, 64)}, + {"name": "square", "data": T.s8(T.synth("square", 64, 64, 0.5)), "volume": 11, "loop": (0, 64)}, + {"name": "saw16", "data": T.s16(T.synth("saw", 200, 100, 0.6)), "bits": 16, "volume": 15, "loop": (0, 200)}, + {"name": "noise", "data": T.s8(T.synth("noise", 6000, 1, 0.7, decay=1500)), "volume": 14}, + {"name": "tri", "data": T.s8(T.synth("tri", 50, 50, 0.8)), "volume": 12, "loop": (0, 50)}, + ] + + +def song_effects(keep=None): + a, b = empty(), empty(48) + mel = [61, 65, 68, 73, 68, 65, 63, 61] + for i in range(16): + put(a, i * 4, 0, mel[i % 8], 1, 16 - i % 4) + put(a, 0, 1, 49, 2, 12) + put(a, 4, 1, 0, 0, 0, 0x1, 0x3) # fine porta up + put(a, 8, 1, 0, 0, 0, 0x2, 0x5) + put(a, 12, 1, 0, 0, 0, 0x8, 0x2) # volume slide down + put(a, 16, 1, 51, 2, 14, 0x7, 0x1) # up + put(a, 20, 1, 0, 0, 0, 0x5, 0x4) # vibrato depth + put(a, 21, 1, 0, 0, 0, 0x6, 0x2) # vibrato speed + put(a, 28, 1, 56, 2, 14) + put(a, 32, 1, 61, 2, 0, 0x3, 0x4) # tone portamento (keeps going) + put(a, 40, 1, 49, 2, 0, 0x3, 0x2) + put(a, 48, 1, 0, 0, 0, 0xA, 0x8) # volume portamento + for r in range(0, 64, 8): + put(a, r, 3, 61, 4, 16 - r // 8) + put(a, 36, 3, 61, 4, 16, 0x4, 0x2) # retrigger + put(a, 4, 2, 37, 3, 12) + put(a, 2, 4, 73, 5, 10, 0xB, 0x2) # panning + put(a, 30, 4, 0, 0, 0, 0xB, 0xD) + put(a, 10, 5, 56, 1, 12) + put(a, 24, 5, 0, 0, 0, 0xF, 0x3) # speed + put(b, 0, 0, 49, 1, 16) + put(b, 8, 0, 61, 1, 16, 0x2, 0x8) + put(b, 0, 2, 37, 3, 12) + put(b, 16, 2, 44, 3, 10, 0x9, 0x3) + put(b, 20, 6, 68, 5, 16) + put(b, 24, 9, 56, 2, 16) # a muted channel + if keep is not None: + for p in (a, b): + for row in p: + for ch in range(16): + if ch not in keep and (row[ch][3] >> 4) != 0xF: + row[ch] = (0, 0, 0, 0) + return T.write_far("effects", samples(), [0, 1], [a, b], speed=5, breaks=[0, 30], mute=(9,), + pans=[3, 12, 7, 0, 15, 9, 5, 10, 8, 8, 8, 8, 8, 8, 8, 8], message=b"far test") + + +def generate(ctx): + cases = [] + for nm, data in (("effects", song_effects()),): + ref = T.reference(ctx, data, "far") + cases.append({"name": nm, "data": data, "ref": ref, "duration": ref["duration"]}) + ctx.emit("far_cases", cases) diff --git a/tools/fixtures/hmp.py b/tools/fixtures/hmp.py new file mode 100644 index 0000000..ab67aeb --- /dev/null +++ b/tools/fixtures/hmp.py @@ -0,0 +1,24 @@ +# HMP / HMI fixtures (tools/fixtures.py): HMP (old and "013195" headers) and HMI files written by +# tools/fixtures/_midivar.py (several tracks, running status in HMI, HMI note durations and FE events, tick rates) and +# wildmidi -x's conversion of each as the reference event stream (wildmidi reads HMP without running status, so the +# HMP files use none). +# tests/gen/hmp_cases.luau { { name, data, kind, rate, ref = { division, tempo, events = { {seconds, status, d1, d2} } } } } +import importlib.util, os + +INPUTS = ["tools/fixtures/_midivar.py"] +_spec = importlib.util.spec_from_file_location("_midivar", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_midivar.py")) +M = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(M) + + +def generate(ctx): + rng = ctx.rng(0x484D50) + cases = [] + for i, (new, rate) in enumerate([(False, 120), (True, 120), (False, 60), (True, 140)]): + data = M.write_hmp(M.random_hmp_tracks(rng, ntracks=2 + i, n=40, running=False), bpm=rate, new=new) + cases.append({"name": "hmp %d%s" % (i, " 013195" if new else ""), "data": data, "kind": "hmp", "rate": rate, + "ref": M.wildmidi(ctx, data, "hmp")}) + for i, rate in enumerate([120, 100]): + data = M.write_hmi(M.random_hmi_tracks(rng, ntracks=2 + i), bpm=rate) + cases.append({"name": "hmi %d" % i, "data": data, "kind": "hmi", "rate": rate, "ref": M.wildmidi(ctx, data, "hmi")}) + ctx.emit("hmp_cases", cases) diff --git a/tools/fixtures/hvl.py b/tools/fixtures/hvl.py new file mode 100644 index 0000000..92d6d6c --- /dev/null +++ b/tools/fixtures/hvl.py @@ -0,0 +1,35 @@ +# HVL fixtures (tools/fixtures.py): songs written by tools/fixtures/_hively.py (a hand-made 6-channel demo with ring +# modulation, panning and two effect columns; random 4..8 channel songs) plus songs from the HivelyTracker source, each +# rendered by hvl2wav (nixpkgs#hivelytracker) as the reference. +# tests/gen/hvl_cases.luau { { name, data, crc (CRC-32 of hvl2wav's s16le stereo output), head (its first HEAD frames), frames, sampleRate, subsong, maxDuration?, prefix } } +import importlib.util, os, zlib + +INPUTS = ["tools/fixtures/_hively.py"] +_spec = importlib.util.spec_from_file_location("_hively", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_hively.py")) +H = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(H) + + +HEAD = 11025 # frames of hvl2wav output kept as raw samples (to locate a mismatch); the rest is checked by CRC + + +def case(ctx, name, data, rate=44100, subsong=0, limit=None): + args = ["-f%d" % rate, "-s%d" % subsong] + (["-t0:%02d" % limit] if limit else []) + pcm, frames = H.hvl2wav(ctx, data, "hvl", args) + c = {"name": name, "data": data, "crc": zlib.crc32(pcm), "head": pcm[:HEAD * 4], "frames": frames, "sampleRate": rate, "subsong": subsong, + "prefix": limit is not None} + if limit: + c["maxDuration"] = limit + return c + + +def generate(ctx): + rng = ctx.rng(0x4E1) + demo = H.write_hvl(H.demo_song(True)) + cases = [case(ctx, "demo", demo), case(ctx, "demo 48000 Hz", demo, rate=48000), case(ctx, "demo subsong 1", demo, subsong=1)] + for i in range(4): + cases.append(case(ctx, "random %d" % i, H.write_hvl(H.random_song(rng, True)))) + songs = H.source_songs(ctx) + for name in ["chiprolled.hvl", "sunspots.hvl", "syphus-Afterstorm.hvl"]: + cases.append(case(ctx, name, songs[name], limit=3)) + ctx.emit("hvl_cases", cases) diff --git a/tools/fixtures/med.py b/tools/fixtures/med.py new file mode 100644 index 0000000..7e8a2ea --- /dev/null +++ b/tools/fixtures/med.py @@ -0,0 +1,113 @@ +# MED fixtures (tools/fixtures.py): generated MED / OctaMED modules (MMD0, MMD1 with instrument extras, MMD2 with a play +# sequence) exercising the effects, rendered by openmpt123. +# tests/gen/med_cases.luau { name, data (the module), ref (features of openmpt's render, tools/fixtures/_tracker.py), +# duration (openmpt's song length) } +import os, sys + +# the shared tracker module, loaded by path (tools/fixtures/ must not go on sys.path: xml.py there would shadow xml) +T = sys.modules.get("_tracker") +if T is None: + import importlib.util + _spec = importlib.util.spec_from_file_location("_tracker", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tracker.py")) + T = importlib.util.module_from_spec(_spec) + sys.modules["_tracker"] = T + _spec.loader.exec_module(T) + +INPUTS = ["tools/fixtures/_tracker.py"] + + +def empty(ch, rows=64): + return [[(0, 0, 0, 0) for _ in range(ch)] for _ in range(rows)] + + +def put(p, row, ch, note=0, ins=0, cmd=0, param=0): + p[row][ch] = (note, ins, cmd, param) + + +def samples(extras=False): + s = [ + {"data": T.s8(T.synth("sine", 64, 64)), "volume": 64, "loop": (0, 64)}, + {"data": T.s8(T.synth("square", 64, 64, 0.5)), "volume": 44, "loop": (0, 64)}, + {"data": T.s8(T.synth("saw", 128, 64, 0.6)), "volume": 64, "loop": (64, 64), "transpose": -12}, + {"data": T.s8(T.synth("noise", 4000, 1, 0.7, decay=1200)), "volume": 60}, + {"data": T.s8(T.synth("tri", 32, 32, 0.8)), "volume": 52, "loop": (0, 32)}, + ] + if extras: + s[0]["hold"], s[0]["decay"] = 6, 4 # hold / decay: a volume envelope + s[1]["finetune"] = 3 + s[4]["hold"], s[4]["decay"] = 2, 0 + return s + + +def song_basic(keep=None, version=0): + a, b = empty(4), empty(4, 32) + mel = [13, 17, 20, 25, 20, 17, 15, 13] + for i in range(16): + put(a, i * 4, 0, mel[i % 8], 1) + put(a, 2, 0, 0, 0, 0x0, 0x37) # arpeggio + put(a, 0, 1, 1, 2) + put(a, 4, 1, 0, 0, 0x1, 0x02) + put(a, 12, 1, 0, 0, 0x2, 0x03) + put(a, 20, 1, 13, 2, 0xC, 0x32) # volume (decimal: 32) + put(a, 24, 1, 0, 0, 0xD, 0x03) # volume slide down (every tick) + put(a, 28, 1, 0, 0, 0xD, 0x20) + put(a, 32, 1, 8, 2, 0x4, 0x34) # vibrato (twice as deep) + put(a, 40, 1, 13, 2) + put(a, 41, 1, 20, 0, 0x3, 0x10) # tone portamento + put(a, 48, 1, 0, 0, 0x5, 0x01) + for r in range(0, 64, 8): + put(a, r, 3, 13, 4, 0xC, 0x64 - r) + put(a, 2, 2, 25, 3) + put(a, 36, 2, 1, 5, 0xF, 0xF2) # delay note + put(a, 44, 2, 1, 5, 0xF, 0xF1) # play twice + put(a, 34, 3, 0, 0, 0x9, 0x04) # secondary speed + put(a, 50, 3, 0, 0, 0xF, 0x90) # tempo 0x90 (BPM 144 / 0.264...) + put(b, 0, 0, 13, 1) + put(b, 8, 1, 20, 2) + put(b, 16, 2, 13, 3, 0x8, 0x40) # panning (8xx) + put(b, 24, 3, 25, 5, 0xF, 0x00) # pattern break + if keep is not None: + for p in (a, b): + for row in p: + for ch in range(4): + if ch not in keep and row[ch][2] not in (0x9, 0xF): + row[ch] = (0, 0, 0, 0) + return T.write_med(version, samples(version > 0), [a, b], [0, 1, 0], tempo=0x21 if version == 0 else 125, tempo2=6, + flags=0x10 if version > 0 else 0, flags2=0x23 if version > 0 else 0, title="med test" if version > 0 else None) + + +def song_mmd2(): + """MMD2: 6 tracks, a play sequence with a section, ProTracker-style slides, BPM tempo, track volumes""" + a = empty(6, 48) + for r in range(0, 48, 4): + put(a, r, r // 4 % 6, 13 + (r // 4) % 12, 1 + r // 4 % 5) + put(a, 6, 1, 0, 0, 0x1, 0x04) + put(a, 10, 2, 0, 0, 0xD, 0x02) + put(a, 20, 4, 0, 0, 0x16, 0x00) # loop start + put(a, 23, 4, 0, 0, 0x16, 0x01) # loop once + put(a, 30, 5, 0, 0, 0x1F, 0x20) # note delay 2 + put(a, 44, 0, 0, 0, 0x1D, 0x08) # break to row 8 (hex) + b = empty(6, 16) + put(b, 0, 0, 25, 2, 0x0C, 0x20) + put(b, 8, 3, 30, 4) + return T.write_med(2, samples(), [a, b], [0, 1], tempo=120, tempo2=5, flags=0x20 | 0x10, flags2=0x20 | 3, + trackvols=[64, 48, 64, 32, 64, 64]) + + +def song_octaves(): + """MMD1 with an IFF 3-octave sample (three copies of a waveform, each twice as long as the last): a keymap""" + w = T.s8(T.synth("saw", 32, 32, 0.7)) + T.s8(T.synth("saw", 64, 64, 0.7)) + T.s8(T.synth("saw", 128, 128, 0.7)) + smp = [{"data": w, "volume": 64, "octaves": 3, "loop": (0, 32)}, samples()[0]] + a = empty(2, 48) + for i, n in enumerate([1, 8, 13, 20, 25, 32, 37, 30, 18, 6, 13, 25]): + put(a, i * 4, 0, n, 1) + put(a, i * 4 + 2, 1, n, 2, 0xC, 0x20) + return T.write_med(1, smp, [a], [0], tempo=125, tempo2=6, flags=0x10, flags2=0x23) + + +def generate(ctx): + cases = [] + for nm, data in (("mmd0", song_basic()), ("mmd1", song_basic(version=1)), ("mmd2", song_mmd2()), ("octaves", song_octaves())): + ref = T.reference(ctx, data, "med") + cases.append({"name": nm, "data": data, "ref": ref, "duration": ref["duration"]}) + ctx.emit("med_cases", cases) diff --git a/tools/fixtures/mpc.py b/tools/fixtures/mpc.py new file mode 100644 index 0000000..8aee074 --- /dev/null +++ b/tools/fixtures/mpc.py @@ -0,0 +1,130 @@ +# Musepack fixtures (tools/fixtures.py). There is no Musepack encoder in nixpkgs, so the reference tools are built +# here from the official sources through nix (fetchurl with pinned hashes): mpcenc / libmpcdec from musepack_src_r475 +# (SV8, BSD / LGPL tools), mppenc 1.16 (SV7), and `mpcf32`, a 20-line C program linked against r475's libmpcdec that +# writes its float output (gapless, the reference) as f32le, optionally after mpc_demux_seek_sample. +# tests/gen/mpc_cases.luau { name, data, version, channels, rate, frames, exact (frames that match libmpcdec +# exactly), ref (mpcf32's f32le, the first REF frames), ff? (ffmpeg's s16 decode as f32le, +# aligned: ffmpeg is not gapless), tags? } +# tests/gen/mpc_seek.luau { name (a case), at (sample), ref (mpcf32 after seeking to `at`, SEEK_REF stereo frames) } +import importlib.util, os, subprocess, tempfile, shutil + +_spec = importlib.util.spec_from_file_location("_audio", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_audio.py")) +A = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(A) + +INPUTS = ["tools/fixtures/_audio.py"] + +NIX = r''' +with import {}; +let + flags = "-fcommon -Wno-error -Wno-implicit-function-declaration -Wno-incompatible-pointer-types -Wno-int-conversion"; + f32 = writeText "mpcf32.c" '' + #include + #include + #include + int main(int argc, char **argv) { + mpc_reader r; mpc_streaminfo si; MPC_SAMPLE_FORMAT b[MPC_DECODER_BUFFER_LENGTH]; + if (argc < 2 || mpc_reader_init_stdio(&r, argv[1]) < 0) return 1; + mpc_demux *d = mpc_demux_init(&r); if (!d) return 2; + mpc_demux_get_info(d, &si); + if (argc > 2) mpc_demux_seek_sample(d, (mpc_uint64_t) atoll(argv[2])); + for (;;) { mpc_frame_info f; f.buffer = b; + if (mpc_demux_decode(d, &f) != MPC_STATUS_OK) { fprintf(stderr, "error\n"); return 3; } + if (f.bits == -1) break; + fwrite(b, sizeof(float), f.samples * si.channels, stdout); } + return 0; } + ''; +in symlinkJoin { name = "musepack-tools"; paths = [ + (stdenv.mkDerivation { + pname = "musepack"; version = "r475"; + src = fetchurl { url = "https://files.musepack.net/source/musepack_src_r475.tar.gz"; sha256 = "a4b1742f997f83e1056142d556a8c20845ba764b70365ff9ccf2e3f81c427b2b"; }; + nativeBuildInputs = [ cmake ]; + NIX_CFLAGS_COMPILE = flags; + postPatch = "sed -i -e /mpcgain/d -e /mpcchap/d -e /wavcmp/d -e /mpccut/d CMakeLists.txt"; + cmakeFlags = [ "-DCMAKE_POLICY_VERSION_MINIMUM=3.5" "-DSHARED=OFF" ]; + postBuild = "$CC -O2 -I../include ${f32} libmpcdec/libmpcdec_static.a -lm -o mpcf32"; + installPhase = "mkdir -p $out/bin; cp mpcenc/mpcenc mpcdec/mpcdec mpcf32 $out/bin/"; + }) + (stdenv.mkDerivation { + pname = "mppenc"; version = "1.16"; + src = fetchurl { url = "https://files.musepack.net/source/mppenc-1.16.tar.bz2"; sha256 = "f90781856ca7b6ce1ec7033321fadbcd04fe264d0349c20b49ad05f7cb2655ad"; }; + nativeBuildInputs = [ cmake ]; + NIX_CFLAGS_COMPILE = flags; + cmakeFlags = [ "-DCMAKE_POLICY_VERSION_MINIMUM=3.5" ]; + installPhase = "mkdir -p $out/bin; cp src/mppenc $out/bin/"; + }) +]; } +''' + +# name, encoder (mpcenc = SV8, mppenc = SV7), signal, rate, channels, seconds, extra options +CASES = [ + ("sv8_q5_stereo", "mpcenc", "music", 44100, 2, 1.2, ["--quality", "5", "--num_frames", "1"]), + ("sv8_q3_mono32k", "mpcenc", "sweep", 32000, 1, 0.5, ["--quality", "3"]), + ("sv8_q9_noise48k", "mpcenc", "noise", 48000, 2, 0.4, ["--quality", "9", "--num_frames", "2"]), + ("sv8_q1_sine", "mpcenc", "sine", 44100, 2, 0.3, ["--quality", "1", "--num_frames", "0", + "--artist", "Some One", "--tag", "Title=Mpc Tone", "--tag", "Year=2026"]), + ("sv7_q5_stereo", "mppenc", "music", 44100, 2, 1.2, ["--quality", "5"]), + ("sv7_q8_noise", "mppenc", "noise", 44100, 2, 0.3, ["--quality", "8"]), + ("sv7_q2_sweep", "mppenc", "sweep", 48000, 2, 0.5, ["--quality", "2"]), +] +REF = 22050 # frames of reference output kept per case (the fixture module stays small) +FF = ("sv8_q5_stereo", "sv7_q5_stereo") # cases also compared with ffmpeg +SEEKS = [("sv8_q5_stereo", 30000), ("sv8_q9_noise48k", 9000), ("sv7_q5_stereo", 40000)] +SEEK_REF = 4096 + + +def tools(): + out = subprocess.run(["nix", "build", "--impure", "--no-link", "--print-out-paths", "--expr", NIX], + capture_output=True, check=True).stdout.decode().strip().split("\n")[-1] + return os.path.join(out, "bin") + + +def generate(ctx): + bin_ = tools() + d = tempfile.mkdtemp(prefix="fmt-mpc-") + cases, seeks, files = [], [], {} + try: + for name, enc, kind, rate, ch, secs, extra in CASES: + frames = int(rate * secs) + sig = A.signal(kind, rate, ch, frames, seed=len(name)) + wav = os.path.join(d, name + ".wav") + mpc = os.path.join(d, name + ".mpc") + with open(wav, "wb") as f: + f.write(A.wav(sig, rate, ch)) + subprocess.run([os.path.join(bin_, enc)] + extra + ["--silent", "--overwrite", wav, mpc], capture_output=True, check=True) + with open(mpc, "rb") as f: + data = f.read() + files[name] = mpc + ref = subprocess.run([os.path.join(bin_, "mpcf32"), mpc], capture_output=True, check=True).stdout + got = len(ref) // (4 * ch) + assert got == frames, (name, got, frames) + # SV7: libmpcdec decodes the zero-filled data past the last frame for the synthesis tail (reading past + # its tables); we decode silence there, so only the frames before it compare exactly + exact = frames + if enc == "mppenc": + exact = min(frames, int.from_bytes(data[4:8], "little") * 1152 - 481) + c = {"name": name, "data": data, "version": 8 if enc == "mpcenc" else 7, "channels": ch, "rate": rate, + "frames": frames, "exact": exact, "ref": ref[:REF * ch * 4]} + if name in FF: + _, _, ff = A.ffdecode(ctx, data, ext="mpc") + # ffmpeg decodes without the gapless trimming: find the lag of the reference inside its output + refl = A.from_f32le(ref) + best = None + for lag in range(0, 2400): + if (lag + 200) * ch > len(ff): + break + e = sum((ff[(lag + i) * ch] - refl[i * ch]) ** 2 for i in range(100, 200)) + if best is None or e < best[0]: + best = (e, lag) + c["ff"] = A.f32le(ff[best[1] * ch:(best[1] + REF) * ch]) + if "--artist" in extra: + c["tags"] = {"artist": "Some One", "title": "Mpc Tone", "date": "2026"} + cases.append(c) + for name, at in SEEKS: + ref = subprocess.run([os.path.join(bin_, "mpcf32"), files[name], str(at)], capture_output=True, check=True).stdout + data = next(c["data"] for c in cases if c["name"] == name) + seeks.append({"name": name, "at": at, "ref": ref[:SEEK_REF * 8]}) + finally: + shutil.rmtree(d, ignore_errors=True) + ctx.emit("mpc_cases", cases) + ctx.emit("mpc_seek", seeks) diff --git a/tools/fixtures/mtm.py b/tools/fixtures/mtm.py new file mode 100644 index 0000000..61ea542 --- /dev/null +++ b/tools/fixtures/mtm.py @@ -0,0 +1,105 @@ +# MTM fixtures (tools/fixtures.py): generated MultiTracker modules exercising the effects, rendered by openmpt123. +# tests/gen/mtm_cases.luau { name, data (the module), ref (features of openmpt's render, tools/fixtures/_tracker.py), +# duration (openmpt's song length) } +import os, sys + +# the shared tracker module, loaded by path (tools/fixtures/ must not go on sys.path: xml.py there would shadow xml) +T = sys.modules.get("_tracker") +if T is None: + import importlib.util + _spec = importlib.util.spec_from_file_location("_tracker", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tracker.py")) + T = importlib.util.module_from_spec(_spec) + sys.modules["_tracker"] = T + _spec.loader.exec_module(T) + +INPUTS = ["tools/fixtures/_tracker.py"] + + +def empty(ch, rows=64): + return [[(0, 0, 0, 0) for _ in range(ch)] for _ in range(rows)] + + +def put(p, row, ch, note=0, ins=0, fx=0, param=0): + p[row][ch] = (note, ins, fx, param) + + +def samples(): + return [ + {"name": "sine", "data": T.u8(T.synth("sine", 64, 64)), "volume": 64, "loop": (0, 64)}, + {"name": "square", "data": T.u8(T.synth("square", 64, 64, 0.5)), "volume": 44, "loop": (0, 64)}, + {"name": "saw16", "data": T.u16(T.synth("saw", 128, 64, 0.6)), "bits": 16, "volume": 64, "loop": (0, 256)}, + {"name": "noise", "data": T.u8(T.synth("noise", 5000, 1, 0.7, decay=1500)), "volume": 60}, + {"name": "tri ft", "data": T.u8(T.synth("tri", 32, 32, 0.8)), "volume": 52, "finetune": 3, "loop": (0, 32)}, + ] + + +def song_effects(keep=None): + a, b = empty(6), empty(6) + mel = [49, 53, 56, 61, 56, 53, 51, 49] + for i in range(16): + put(a, i * 4, 0, mel[i % 8], 1) + put(a, i * 4, 1, 37 + (i % 4) * 2, 2, 0x0, 0x37 if i % 2 else 0) + put(a, 0, 2, 49, 3, 0x1, 0x02) + put(a, 16, 2, 0, 0, 0x2, 0x03) + put(a, 32, 2, 61, 3, 0xC, 0x30) + put(a, 33, 2, 0, 0, 0xA, 0x02) + put(a, 48, 2, 0, 0, 0xA, 0x40) + for r in range(0, 64, 8): + put(a, r, 3, 61, 4, 0xC, 0x40 - r // 2) + put(a, 60, 3, 61, 4, 0xE, 0xC2) + put(a, 2, 4, 56, 5, 0xE, 0x84) + put(a, 20, 4, 0, 0, 0xE, 0x8C) + put(a, 8, 5, 44, 2, 0xE, 0x82) + put(a, 40, 5, 0, 0, 0x0, 0x00) + # pattern b: portamento, vibrato, tremolo, offsets, fine slides, break + put(b, 0, 0, 49, 1) + put(b, 4, 0, 61, 0, 0x3, 0x08) + put(b, 8, 0, 0, 0, 0x3, 0x00) + put(b, 12, 0, 49, 0, 0x5, 0x02) + put(b, 16, 0, 56, 5, 0x4, 0x46) + put(b, 20, 0, 0, 0, 0x6, 0x01) + put(b, 24, 0, 0, 0, 0x4, 0x8F) + put(b, 0, 1, 37, 2, 0x7, 0x48) + put(b, 8, 1, 0, 0, 0x7, 0x00) + put(b, 16, 1, 44, 2, 0xE, 0x12) + put(b, 17, 1, 0, 0, 0xE, 0x12) + put(b, 20, 1, 0, 0, 0xE, 0x24) + put(b, 24, 1, 0, 0, 0xE, 0xB8) + put(b, 28, 1, 0, 0, 0xE, 0xA4) + put(b, 0, 3, 49, 4, 0x9, 0x08) + put(b, 24, 2, 49, 3, 0xF, 0x03) + put(b, 24, 4, 0, 0, 0xF, 0x8C) + put(b, 40, 2, 53, 3, 0xF, 0x06) + put(b, 40, 4, 0, 0, 0xF, 0x7D) + put(b, 44, 0, 49, 5) + put(b, 48, 0, 0, 0, 0xD, 0x00) + if keep is not None: # debugging: only some channels + for p in (a, b): + for row in p: + for ch in range(6): + if ch not in keep and row[ch][2] not in (0xB, 0xD, 0xF): + row[ch] = (0, 0, 0, 0) + return T.write_mtm("effects", samples(), [0, 1], [a, b], 6, pans=[3, 12, 7, 0, 15, 9], comment=b"test song".ljust(40, b"\0")) + + +def song_quirk(): + """speed and tempo commands never on one row: MultiTracker's reset (speed -> tempo 125, tempo -> speed 6)""" + a, b = empty(4), empty(4) + for r in range(0, 64, 4): + put(a, r, 0, 49 + (r // 4) % 12, 1) + put(b, r, 1, 61 - (r // 4) % 12, 2) + put(a, 0, 3, 0, 0, 0xF, 0x03) + put(a, 32, 3, 0, 0, 0xF, 0xA0) + put(b, 16, 3, 0, 0, 0xF, 0x04) + put(b, 40, 3, 0, 0, 0xF, 0x50) + put(b, 0, 2, 37, 4, 0xB, 0x02) + return T.write_mtm("quirk", samples(), [0, 1, 0], [a, b], 4) + + +def generate(ctx): + cases = [] + for nm, data in (("effects", song_effects()), ("quirk", song_quirk())): + ref = T.reference(ctx, data, "mtm") + cases.append({"name": nm, "data": data, "ref": ref, "duration": ref["duration"]}) + ctx.emit("mtm_cases", cases) + diff --git a/tools/fixtures/mus.py b/tools/fixtures/mus.py new file mode 100644 index 0000000..27f15a1 --- /dev/null +++ b/tools/fixtures/mus.py @@ -0,0 +1,28 @@ +# MUS fixtures (tools/fixtures.py): Doom MUS files written by tools/fixtures/_midivar.py (notes with and without volume, +# releases, pitch wheel, controllers, program changes; system events and measure ends only in mus_measures, as wildmidi +# misreads the first and refuses the second) and wildmidi -x's conversion of each as the reference event stream. +# tests/gen/mus_cases.luau { { name, data, rate (wildmidi's effective tick rate), ref = { division, tempo, +# events = { {seconds, status, d1, d2} } } } } +import importlib.util, os + +INPUTS = ["tools/fixtures/_midivar.py"] +_spec = importlib.util.spec_from_file_location("_midivar", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_midivar.py")) +M = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(M) + + +def generate(ctx): + rng = ctx.rng(0x4D55) + cases = [] + for i in range(4): + data = M.random_mus(rng, n=60 + 60 * i) + ref = M.wildmidi(ctx, data, "mus") + # wildmidi writes its tempo bytes in the wrong order (0x1B8A06 for 0x068A1B) at division 257: its MUS tick + # rate is 257 / 1.804806 s, not Doom's 140 Hz + rate = ref["division"] * 1e6 / ref["tempo"] + cases.append({"name": "random %d" % i, "data": data, "rate": rate, "ref": ref}) + # system events and measure ends inserted with no delay: the same notes at the same times, more controllers + plain = M.random_mus(ctx.rng(7), n=80) + marked = M.random_mus(ctx.rng(7), n=80, extras=12) + ctx.emit("mus_cases", cases) + ctx.emit("mus_measures", {"plain": plain, "marked": marked}) diff --git a/tools/fixtures/okt.py b/tools/fixtures/okt.py new file mode 100644 index 0000000..5a22364 --- /dev/null +++ b/tools/fixtures/okt.py @@ -0,0 +1,105 @@ +# OKT fixtures (tools/fixtures.py): generated Oktalyzer modules exercising the effects and the mixed channel pairs, +# rendered by openmpt123. +# tests/gen/okt_cases.luau { name, data (the module), ref (features of openmpt's render, tools/fixtures/_tracker.py), +# duration (openmpt's song length) } +import os, sys + +# the shared tracker module, loaded by path (tools/fixtures/ must not go on sys.path: xml.py there would shadow xml) +T = sys.modules.get("_tracker") +if T is None: + import importlib.util + _spec = importlib.util.spec_from_file_location("_tracker", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tracker.py")) + T = importlib.util.module_from_spec(_spec) + sys.modules["_tracker"] = T + _spec.loader.exec_module(T) + +INPUTS = ["tools/fixtures/_tracker.py"] + + +def empty(ch, rows=64): + return [[(0, 0, 0, 0) for _ in range(ch)] for _ in range(rows)] + + +def put(p, row, ch, note=0, ins=0, fx=0, param=0): + p[row][ch] = (note, ins, fx, param) + + +def samples(): + return [ + {"name": "sine", "data": T.s8(T.synth("sine", 64, 64)), "volume": 64, "type": 2, "loop": (0, 64)}, + {"name": "square", "data": T.s8(T.synth("square", 64, 64, 0.5)), "volume": 44, "type": 1, "loop": (0, 64)}, + {"name": "saw", "data": T.s8(T.synth("saw", 128, 64, 0.6)), "volume": 64, "type": 0, "loop": (64, 64)}, + {"name": "noise", "data": T.s8(T.synth("noise", 4000, 1, 0.7, decay=1200)), "volume": 60, "type": 2}, + {"name": "tri", "data": T.s8(T.synth("tri", 32, 32, 0.8)), "volume": 52, "type": 2, "loop": (0, 32)}, + ] + + +def song_raw(keep=None): + """four raw Paula channels: slides, arpeggios, note slides, volume, release""" + a, b = empty(4), empty(4, 48) + mel = [13, 17, 20, 25, 20, 17, 15, 13] + for i in range(16): + put(a, i * 4, 0, mel[i % 8], 1) + put(a, 2, 0, 0, 0, 10, 0x37) # arpeggio 1 + put(a, 10, 0, 0, 0, 11, 0x37) # arpeggio 2 + put(a, 18, 0, 0, 0, 12, 0x37) # arpeggio 3 + put(a, 0, 1, 1, 2) + put(a, 4, 1, 0, 0, 1, 0x02) # period down (pitch up) + put(a, 12, 1, 0, 0, 2, 0x03) + put(a, 20, 1, 13, 2, 31, 0x20) # volume 0x20 + put(a, 24, 1, 0, 0, 31, 0x43) # slide down + put(a, 28, 1, 0, 0, 31, 0x52) # slide up + put(a, 32, 1, 0, 0, 31, 0x64) # fine down + put(a, 36, 1, 0, 0, 31, 0x76) # fine up + put(a, 40, 1, 8, 2, 30, 0x01) # note slide up every tick + put(a, 44, 1, 0, 0, 13, 0x02) + put(a, 48, 1, 0, 0, 17, 0x03) # once + put(a, 52, 1, 0, 0, 21, 0x05) + for r in range(0, 64, 8): + put(a, r, 3, 13, 4) + put(a, 2, 2, 25, 5) + put(a, 30, 2, 0, 0, 27, 0) # release: the sustain loop ends + put(a, 36, 2, 1, 5) + put(a, 34, 3, 0, 0, 28, 0x04) # speed + put(b, 0, 0, 13, 1) + put(b, 8, 1, 20, 2) + put(b, 16, 2, 13, 3) # a paired-only sample on a raw channel: stops it + put(b, 24, 3, 25, 5, 25, 0x00) # jump to 0 (song end) + if keep is not None: + for p in (a, b): + for row in p: + for ch in range(4): + if ch not in keep and row[ch][2] not in (25, 28): + row[ch] = (0, 0, 0, 0) + return T.write_okt(samples(), [0, 1], [a, b], speed=6) + + +def song_pairs(keep=None): + """two mixed pairs (channels 2 / 3 and 5 / 6) and two raw channels""" + a = empty(6) + for r in range(0, 64, 4): + put(a, r, 0, 13 + (r // 4) % 12, 1) + put(a, r, 1, 1 + (r // 4) % 7, 3) + put(a, r + 2, 2, 20, 1) + put(a, 16, 1, 0, 0, 31, 0x30) # pair volume (shared) + put(a, 32, 2, 0, 0, 31, 0x10) # the second channel's volume wins + put(a, 40, 1, 0, 0, 31, 0x52) # pair volume slide + put(a, 0, 3, 13, 2) + put(a, 8, 4, 25, 4) + put(a, 10, 5, 13, 5) + put(a, 20, 5, 30, 1) # too high on a pair: clamped + put(a, 48, 4, 13, 1, 31, 0x18) + if keep is not None: + for row in a: + for ch in range(6): + if ch not in keep: + row[ch] = (0, 0, 0, 0) + return T.write_okt(samples(), [0], [a], cmod=(1, 0, 1, 0), speed=5) + + +def generate(ctx): + cases = [] + for nm, data in (("raw", song_raw()), ("pairs", song_pairs())): + ref = T.reference(ctx, data, "okt") + cases.append({"name": nm, "data": data, "ref": ref, "duration": ref["duration"]}) + ctx.emit("okt_cases", cases) diff --git a/tools/fixtures/ptm.py b/tools/fixtures/ptm.py new file mode 100644 index 0000000..1adf671 --- /dev/null +++ b/tools/fixtures/ptm.py @@ -0,0 +1,89 @@ +# PTM fixtures (tools/fixtures.py): generated PolyTracker modules exercising the effects, rendered by openmpt123. +# tests/gen/ptm_cases.luau { name, data (the module), ref (features of openmpt's render, tools/fixtures/_tracker.py), +# duration (openmpt's song length) } +import os, sys + +# the shared tracker module, loaded by path (tools/fixtures/ must not go on sys.path: xml.py there would shadow xml) +T = sys.modules.get("_tracker") +if T is None: + import importlib.util + _spec = importlib.util.spec_from_file_location("_tracker", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tracker.py")) + T = importlib.util.module_from_spec(_spec) + sys.modules["_tracker"] = T + _spec.loader.exec_module(T) + +INPUTS = ["tools/fixtures/_tracker.py"] + + +def empty(ch): + return [[(0, 0, None, None, 0) for _ in range(ch)] for _ in range(64)] + + +def put(p, row, ch, note=0, ins=0, vol=None, cmd=None, param=0): + p[row][ch] = (note, ins, vol, cmd, param) + + +def samples(): + return [ + {"name": "sine", "data": T.s8(T.synth("sine", 64, 64)), "volume": 64, "c4spd": 8363, "loop": (0, 64)}, + {"name": "square", "data": T.s8(T.synth("square", 64, 64, 0.5)), "volume": 40, "c4spd": 16726, "loop": (0, 64)}, + {"name": "saw16", "data": T.s16(T.synth("saw", 200, 100, 0.6)), "bits": 16, "volume": 64, "c4spd": 13000, "loop": (0, 200), "pingpong": True}, + {"name": "noise", "data": T.s8(T.synth("noise", 6000, 1, 0.7, decay=1500)), "volume": 60, "c4spd": 8363}, + {"name": "tri", "data": T.s8(T.synth("tri", 50, 50, 0.8)), "volume": 50, "c4spd": 10000, "loop": (0, 50)}, + ] + + +def song_effects(keep=None): + a, b = empty(6), empty(6) + mel = [61, 65, 68, 73, 68, 65, 63, 61] + for i in range(16): + put(a, i * 4, 0, mel[i % 8], 1, None, 0x0 if i % 4 == 1 else None, 0x37) + put(a, 0, 1, 49, 2, 48) + put(a, 4, 1, 0, 0, None, 0xA, 0x04) + put(a, 8, 1, 0, 0, None, 0xA, 0x20) + put(a, 12, 1, 0, 0, None, 0xA, 0xF2) # S3M-style fine slide + put(a, 16, 1, 51, 2, None, 0x2, 0x03) + put(a, 20, 1, 0, 0, None, 0x1, 0x06) + put(a, 24, 1, 0, 0, None, 0x1, 0xF4) # fine porta + put(a, 28, 1, 56, 2, None, 0x4, 0x46) + put(a, 36, 1, 0, 0, None, 0x6, 0x02) + put(a, 40, 1, 49, 2) + put(a, 41, 1, 61, 0, None, 0x3, 0x10) + put(a, 44, 1, 0, 0, None, 0x5, 0x01) + put(a, 48, 1, 54, 2, None, 0x7, 0x58) + put(a, 56, 1, 0, 0, None, 0xC, 0x20) + for r in range(0, 64, 8): + put(a, r, 3, 61, 4, 64 - r // 2) + put(a, 20, 3, 61, 4, None, 0x9, 0x08) + put(a, 32, 3, 61, 4, None, 0xE, 0xC3) + put(a, 40, 3, 61, 4, None, 0xE, 0xD2) + put(a, 48, 3, 61, 4, None, 0x11, 0x03) # retrigger + put(a, 4, 2, 37, 3, 50) + put(a, 2, 4, 73, 5, None, 0x8, 0x30) # panning + put(a, 18, 4, 0, 0, None, 0x8, 0xD0) + put(a, 10, 5, 56, 1, None, 0x12, 0x46) # fine vibrato + put(a, 24, 5, 0, 0, None, 0x13, 0x22) # note slide up: every 2 ticks by 2 + put(a, 30, 5, 0, 0, None, 0x14, 0x31) # note slide down + put(a, 36, 5, 60, 1, None, 0x15, 0x21) # with retrigger + put(b, 0, 0, 49, 1, None, 0xF, 0x04) + put(b, 4, 0, 0, 0, None, 0xF, 0x90) + put(b, 8, 0, 61, 1, None, 0x10, 0x20) # global volume + put(b, 24, 0, 0, 0, None, 0x10, 0x40) + put(b, 0, 2, 37, 3) + put(b, 16, 2, 0, 0, None, 0xE, 0x92) + put(b, 32, 4, 68, 5, None, 0xD, 0x00) + if keep is not None: + for p in (a, b): + for row in p: + for ch in range(6): + if ch not in keep and row[ch][3] not in (0xD, 0xF, 0x10): + row[ch] = (0, 0, None, None, 0) + return T.write_ptm("effects", samples(), [0, 1], [a, b], 6, pans=[3, 12, 7, 0, 15, 9]) + + +def generate(ctx): + cases = [] + for nm, data in (("effects", song_effects()),): + ref = T.reference(ctx, data, "ptm") + cases.append({"name": nm, "data": data, "ref": ref, "duration": ref["duration"]}) + ctx.emit("ptm_cases", cases) diff --git a/tools/fixtures/qoa.py b/tools/fixtures/qoa.py new file mode 100644 index 0000000..b4b2859 --- /dev/null +++ b/tools/fixtures/qoa.py @@ -0,0 +1,48 @@ +# QOA fixtures (tools/fixtures.py): audio/qoa and codecs/audio/Qoa. The reference is qoa.h itself +# (tests/fixtures/qoa/qoa.h, MIT, compiled here with nix gcc through tests/fixtures/qoa/qoa_ref.c) plus ffmpeg's decoder. +# tests/gen/qoa_cases.luau { name, data (qoa.h's encoding of the signal), rate, ch, ref (ffmpeg s16le), +# qoaref (qoa.h's decode, s16le), sig (the signal module name) } +# tests/gen/qoa_sig_*.luau the signals (our encoder must write the same bytes as qoa.h) +import importlib.util, os, shutil, struct, subprocess, tempfile + +_dir = os.path.dirname(os.path.abspath(__file__)) + + +def _load(name): + spec = importlib.util.spec_from_file_location(name, os.path.join(_dir, name + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +A = _load("_audio") +D = _load("_adpcm") + +INPUTS = ["tests/fixtures/qoa", "src/Formats/codecs/audio/Qoa"] + + +def generate(ctx): + work = tempfile.mkdtemp(prefix="fmt-qoa-") + try: + exe = os.path.join(work, "qoa_ref") + ctx.nix("gcc", ["gcc", "-O2", "-o", exe, os.path.join(ctx.root, "tests/fixtures/qoa/qoa_ref.c")]) + cases = [] + for name, kind, rate, ch, frames in (("stereo-44k", "music", 44100, 2, 12000), ("mono-22k", "sweep", 22050, 1, 5120), + ("6ch-48k", "sine", 48000, 6, 700), ("loud-mono", "loud", 8000, 1, 5121), + ("square-stereo", "square", 32000, 2, 6000)): + sig = A.signal(kind, rate, ch, frames, seed=len(cases) + 40) + mod = "qoa_sig_" + name.replace("-", "_") + A.emit_signal(ctx, mod, sig, rate, ch) + raw = os.path.join(work, "in.raw") + with open(raw, "wb") as f: + f.write(struct.pack("<%dh" % len(sig), *D.s16(sig))) + qoa = os.path.join(work, "out.qoa") + subprocess.run([exe, "enc", str(ch), str(rate), raw, qoa], check=True) + data = open(qoa, "rb").read() + dec = os.path.join(work, "dec.raw") + subprocess.run([exe, "dec", qoa, dec], check=True, capture_output=True) + ref = D.ffs16(ctx, data, "qoa") + cases.append(dict(name=name, data=data, rate=rate, ch=ch, ref=ref, qoaref=open(dec, "rb").read(), sig=mod)) + ctx.emit("qoa_cases", cases) + finally: + shutil.rmtree(work, ignore_errors=True) diff --git a/tools/fixtures/stm.py b/tools/fixtures/stm.py new file mode 100644 index 0000000..92d1554 --- /dev/null +++ b/tools/fixtures/stm.py @@ -0,0 +1,90 @@ +# STM fixtures (tools/fixtures.py): generated Scream Tracker 2 modules exercising the effects, rendered by openmpt123. +# tests/gen/stm_cases.luau { name, data (the module), ref (features of openmpt's render, tools/fixtures/_tracker.py), +# duration (openmpt's song length) } +import os, sys + +# the shared tracker module, loaded by path (tools/fixtures/ must not go on sys.path: xml.py there would shadow xml) +T = sys.modules.get("_tracker") +if T is None: + import importlib.util + _spec = importlib.util.spec_from_file_location("_tracker", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tracker.py")) + T = importlib.util.module_from_spec(_spec) + sys.modules["_tracker"] = T + _spec.loader.exec_module(T) + +INPUTS = ["tools/fixtures/_tracker.py"] + +A, B, C, D, E, F, G, H, I, J = range(1, 11) + + +def empty(): + return [[(0, 0, None, 0, 0) for _ in range(4)] for _ in range(64)] + + +def put(p, row, ch, note=0, ins=0, vol=None, cmd=0, info=0): + p[row][ch] = (note, ins, vol, cmd, info) + + +def samples(): + return [ + {"name": "sine", "data": T.s8(T.synth("sine", 64, 64)), "volume": 64, "c2spd": 8363, "loop": (0, 64)}, + {"name": "square", "data": T.s8(T.synth("square", 64, 64, 0.5)), "volume": 40, "c2spd": 16726, "loop": (0, 64)}, + {"name": "saw", "data": T.s8(T.synth("saw", 100, 100, 0.6)), "volume": 64, "c2spd": 13000, "loop": (0, 100)}, + {"name": "noise", "data": T.s8(T.synth("noise", 6000, 1, 0.7, decay=1500)), "volume": 60, "c2spd": 8363}, + {"name": "tri", "data": T.s8(T.synth("tri", 50, 50, 0.8)), "volume": 50, "c2spd": 10000, "loop": (0, 50)}, + ] + + +def song_effects(): + a, b, c = empty(), empty(), empty() + mel = [61, 65, 68, 73, 68, 65, 63, 61] + for i in range(16): + put(a, i * 4, 0, mel[i % 8], 1, None, J if i % 4 == 1 else 0, 0x47 if i % 4 == 1 else 0) + put(a, 0, 1, 49, 2, 48) + put(a, 4, 1, 0, 0, None, D, 0x04) + put(a, 8, 1, 0, 0, None, D, 0x20) + put(a, 16, 1, 51, 2, None, E, 0x03) + put(a, 20, 1, 0, 0, None, F, 0x06) + put(a, 28, 1, 56, 2, None, H, 0x46) + put(a, 40, 1, 49, 2, None, G, 0x00) + put(a, 41, 1, 61, 0, None, G, 0x10) + put(a, 52, 1, 0, 0, None, I, 0x21) + for r in range(0, 64, 8): + put(a, r, 3, 61, 4, 64 - r // 2) + put(a, 24, 3, 254) + put(a, 48, 2, 37, 3) + put(a, 32, 2, 0, 0, None, A, 0x40) # ST2 tempo byte: speed 4, a fine tick length + put(b, 0, 2, 49, 3, None, A, 0x63) + put(b, 8, 2, 52, 5) + put(b, 10, 0, 64, 1) + put(b, 20, 0, 61, 1, 30) + put(b, 24, 0, 254) + put(b, 16, 1, 0, 0, None, B, 0x02) # deferred: taken at the C below (unreachable orders would be openmpt subsongs) + put(b, 40, 3, 0, 0, None, C, 0x08) + put(c, 8, 0, 49, 1, 32) + put(c, 12, 1, 61, 2) + put(c, 20, 0, 0, 0, None, B, 0x00) # deferred to the end of the pattern + put(c, 30, 2, 0, 0, None, A, 0x8F) + return T.write_stm("effects", samples(), [0, 1, 2], [a, b, c], tempo=0x60) + + +def song_old(): + """an ST 2.00 file: decimal tempo bytes, a short order list, no global volume""" + a = empty() + put(a, 0, 0, 61, 1) + put(a, 8, 1, 68, 2) + put(a, 16, 0, 0, 0, None, H, 0x28) + put(a, 32, 1, 0, 0, None, A, 50) # decimal 50 = 0x50 + put(a, 40, 2, 49, 5, 40) + put(a, 44, 3, 56, 3) + put(a, 52, 3, "fb") + put(a, 2, 0, "skip") + return T.write_stm("old", samples(), [0], [a], tempo=72, gvol=20, minor=0) + + +def generate(ctx): + cases = [] + for nm, data in (("effects", song_effects()), ("old", song_old())): + ref = T.reference(ctx, data, "stm") + cases.append({"name": nm, "data": data, "ref": ref, "duration": ref["duration"]}) + ctx.emit("stm_cases", cases) diff --git a/tools/fixtures/tta.py b/tools/fixtures/tta.py new file mode 100644 index 0000000..400924e --- /dev/null +++ b/tools/fixtures/tta.py @@ -0,0 +1,93 @@ +# TTA fixtures (tools/fixtures.py): audio/tta, codecs/audio/Tta. +# tests/gen/tta_cases.luau synthetic signals encoded by the reference encoder (ttaenc 3.4.1: 8 / 16 / 24 bits, +# 1 / 2 / 3 / 6 channels, odd rates, short and odd lengths, several frames, silence, noise, +# full scale) and the ffmpeg FATE sample inside.tta (downloaded at fixture time, cut after 2 +# frames, not committed); each with the CRC-32 of `ttaenc -d`'s samples (i32 LE) +import importlib.util, os, struct, tempfile, urllib.request, zlib + +_dir = os.path.dirname(os.path.abspath(__file__)) +_spec = importlib.util.spec_from_file_location("_wv", os.path.join(_dir, "wavpack.py")) +WV = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(WV) +_spec = importlib.util.spec_from_file_location("_ape", os.path.join(_dir, "ape.py")) +APE = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(APE) + +CTX = None +TMP = None +CASES = [] +FATE = "https://fate-suite.ffmpeg.org/lossless-audio/" + + +def emit(name, tta, note, partial=False, keep=None): + out = tta + ".out.wav" + try: + CTX.nix("ttaenc", ["ttaenc", "-d", tta, "-o", out]) + except Exception: + if not partial: + raise + rate, ch, bits, fl, s = APE.wav_samples(out) + if keep is not None: # a cut file: ttaenc also writes the broken frame; keep the whole ones + s = s[:keep * ch] + CASES.append({"name": name, "note": note, "data": open(tta, "rb").read(), "rate": rate, "channels": ch, + "bits": bits, "float": False, "frames": len(s) // ch, + "crc": zlib.crc32(b"".join(struct.pack(" volume column + put(b, 16, 0, 56, 1, 0x3, 0x08, 0x4, 0x05) # tone porta + vibrato depth + put(b, 24, 2, 49, 3, 0xE, 0x84) # fine pattern delay + put(b, 0, 5, 37, 2, 0xA, 0xF0, 0x3, 0x00) + put(b, 32, 4, 68, 5, 0xD, 0x00, 0xC, 0x60) # break + volume + if keep is not None: # debugging: only some channels (their speed / tempo / break effects stay) + for p in (a, b): + for row in p: + for ch in range(6): + if ch not in keep and row[ch][2] not in (0xD, 0xF) and row[ch][4] not in (0xD, 0xF): + row[ch] = (0, 0, 0, 0, 0, 0) + return T.write_ult("effects", samples(), [0, 1], [a, b], 6, pans=[3, 12, 7, 0, 15, 9]) + + +def song_old(): + """a v1.3 file: no tremolo, no sample speed; arpeggio""" + a = empty(4) + for r in range(0, 64, 4): + put(a, r, r // 4 % 4, 49 + (r // 4) % 12, 1 + r // 4 % 3, 0x0, 0x37) + put(a, 32, 0, 0, 0, 0xF, 0x03) + return T.write_ult("old", samples(), [0, 0], [a], 4, version=3) + + +def generate(ctx): + cases = [] + for nm, data in (("effects", song_effects()), ("old", song_old())): + ref = T.reference(ctx, data, "ult") + cases.append({"name": nm, "data": data, "ref": ref, "duration": ref["duration"]}) + ctx.emit("ult_cases", cases) diff --git a/tools/fixtures/umx.py b/tools/fixtures/umx.py new file mode 100644 index 0000000..bff46f9 --- /dev/null +++ b/tools/fixtures/umx.py @@ -0,0 +1,34 @@ +# UMX fixtures (tools/fixtures.py): Unreal music packages wrapping generated modules (an S3M from tools/fixtures/s3m.py, +# an IT from tools/fixtures/it.py), rendered by openmpt123 (which unwraps the package itself). +# tests/gen/umx_cases.luau { name, data (the package), inner (the embedded module), format (its format), ref +# (features of openmpt's render, tools/fixtures/_tracker.py), duration } +import importlib.util, os, sys + +# the shared tracker module, loaded by path (tools/fixtures/ must not go on sys.path: xml.py there would shadow xml) +T = sys.modules.get("_tracker") +if T is None: + _spec = importlib.util.spec_from_file_location("_tracker", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tracker.py")) + T = importlib.util.module_from_spec(_spec) + sys.modules["_tracker"] = T + _spec.loader.exec_module(T) + +INPUTS = ["tools/fixtures/_tracker.py", "tools/fixtures/s3m.py", "tools/fixtures/it.py"] + + +def sibling(name): + spec = importlib.util.spec_from_file_location("umx_" + name, os.path.join(os.path.dirname(os.path.abspath(__file__)), name + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def generate(ctx): + s3m = sibling("s3m").song_mono() + it = sibling("it").song_effects() + cases = [] + items = [("s3m", "Mono_Theme", s3m, 69), ("it", "Effects", it, 63)] + for fmt, nm, data, ver in items: + pkg = T.write_umx([(nm, data)], version=ver) + ref = T.reference(ctx, pkg, "umx") + cases.append({"name": nm, "data": pkg, "inner": data, "format": fmt, "ref": ref, "duration": ref["duration"]}) + ctx.emit("umx_cases", cases) diff --git a/tools/fixtures/vag.py b/tools/fixtures/vag.py new file mode 100644 index 0000000..796d19c --- /dev/null +++ b/tools/fixtures/vag.py @@ -0,0 +1,55 @@ +# Sony VAG / KVAG fixtures (tools/fixtures.py): audio/vag. Our Python PS-ADPCM / IMA encoders (tools/fixtures/_adpcm.py) +# write the files; vgmstream decodes VAGp / VAGi (and reports the loops), ffmpeg decodes KVAG (adpcm_ima_ssi). +# tests/gen/vag_cases.luau { name, data, rate, ch, ref (s16le), loopStart?, loopEnd?, title? } +# tests/gen/vag_ours.luau our encoder's files (run in this step) as vgmstream decodes them +# tests/gen/vag_sig.luau / vag_sig1.luau the encoder inputs (stereo / mono) +import importlib.util, os, re + +_dir = os.path.dirname(os.path.abspath(__file__)) + + +def _load(name): + spec = importlib.util.spec_from_file_location(name, os.path.join(_dir, name + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +A = _load("_audio") +D = _load("_adpcm") + +INPUTS = ["tools/fixtures/_adpcm.py", "src/Formats/codecs/audio/Adpcm", "src/Formats/audio/vag"] + + +def vgcase(ctx, name, data, **extra): + rate, ch, ref = D.vgdecode(ctx, data, "vag") + e = dict(name=name, data=data, rate=rate, ch=ch, ref=ref, **extra) + m = re.search(r"loop start: (\d+) samples.*?loop end: (\d+) samples", D.vginfo(ctx, data, "vag"), re.S) + if m: + e["loopStart"], e["loopEnd"] = int(m.group(1)), int(m.group(2)) + return e + + +def generate(ctx): + mono = A.signal("music", 22050, 1, 6000, seed=21) + stereo = A.signal("sine", 32000, 2, 5000, seed=22) + cases = [ + vgcase(ctx, "vagp-mono", D.vag(mono, 22050, b"Mono Song"), title="Mono Song"), + vgcase(ctx, "vagp-loop", D.vag(mono, 22050, loop=(20, 150))), + vgcase(ctx, "vagi-stereo", D.vagi(stereo, 32000)), + ] + for name, sig, ch, rate in (("kvag-mono", mono, 1, 22050), ("kvag-stereo", stereo, 2, 32000)): + f = D.kvag(sig, rate, ch) + cases.append(dict(name=name, data=f, rate=rate, ch=ch, ref=D.ffs16(ctx, f, "vag", fmt="kvag"))) + ctx.emit("vag_cases", cases) + + A.emit_signal(ctx, "vag_sig", stereo, 32000, 2) + A.emit_signal(ctx, "vag_sig1", mono, 22050, 1) + ours = [] + for name, sigmod, opts in (("mono", "vag_sig1", "nil"), ("mono-loop", "vag_sig1", "{ loop = { start = 600, stop = 5000 } }"), + ("stereo", "vag_sig", "nil")): + data = A.encode_luau(ctx, "audio/vag", sigmod, opts) + e = vgcase(ctx, name, data) + e["opts"] = opts + ours.append(e) + ctx.emit("vag_ours", ours) diff --git a/tools/fixtures/wavpack.py b/tools/fixtures/wavpack.py new file mode 100644 index 0000000..53738e9 --- /dev/null +++ b/tools/fixtures/wavpack.py @@ -0,0 +1,177 @@ +# WavPack fixtures (tools/fixtures.py): audio/wavpack, codecs/audio/WavPack. +# tests/gen/wavpack_cases.luau synthetic signals encoded by the reference encoder (wavpack 5.9: -f / default / -h / +# -hh / -x1..6, joint stereo on / off, 8 / 12 / 16 / 20 / 24 / 32-bit int and 32-bit +# float, 1 / 2 / 3 / 6 / 8 channels, odd rates, short and odd lengths, small blocks, +# hybrid lossy (-b, noise shaping) and hybrid lossless (+ the .wvc), APEv2 tags, MD5) +# and by ffmpeg's encoder; each with the CRC-32 of wvunpack's raw output (integers as +# i32 LE, floats as their f32 bytes) +import math, os, random, struct, tempfile, zlib + +CTX = None +TMP = None +CASES = [] + + +def signal(secs, rate, ch, kind="music", seed=1, frames=None): + """floats in -1..1, interleaved""" + rnd = random.Random(seed) + n = frames if frames is not None else int(secs * rate) + out = [] + notes = [(rnd.uniform(80, 1500), rnd.uniform(0, max(n, 1)), rnd.uniform(0.1, 0.5) * rate) for _ in range(int(n / rate * 6) + 3)] + for i in range(n): + t = i / rate + for c in range(ch): + if kind == "noise": + v = rnd.uniform(-0.95, 0.95) + elif kind == "silence": + v = 0.0 + elif kind == "mixed": # silence, a tone, noise bursts, full scale + seg = (i * 8 // max(n, 1)) + if seg in (0, 4): + v = 0.0 + elif seg == 5: + v = rnd.uniform(-1, 1) + elif seg == 6: + v = 0.999 if (i // 37) % 2 else -1.0 + else: + v = 0.7 * math.sin(2 * math.pi * (300 + 50 * c) * t) + else: + v = 0.0 + for f, st, dur in notes: + if st <= i < st + dur: + e = math.exp(-3 * (i - st) / dur) * min(1.0, (i - st) / 100) + v += 0.25 * e * (math.sin(2 * math.pi * f * (1 + 0.002 * c) * t) + 0.3 * math.sin(6 * math.pi * f * t + c)) + v += 0.003 * (rnd.random() - 0.5) + 0.04 * math.sin(2 * math.pi * (60 + 7 * c) * t) + out.append(max(-1.0, min(1.0, v))) + return out + + +def write_wav(path, vals, ch, rate, bits, fl=False): + container = 32 if fl else (bits + 7) // 8 * 8 + data = bytearray() + top = (1 << (bits - 1)) - 1 + for v in vals: + if fl: + data += struct.pack("= 128 else b + best = min(range(16), key=lambda k: abs(((cur + TABLE[k] + 128) % 256 - 128) - want)) + cur = (cur + TABLE[best] + 128) % 256 - 128 + nibs.append(best) + if len(nibs) % 2: + nibs.append(0) + return bytes(t & 255 for t in TABLE) + bytes(nibs[i] | nibs[i + 1] << 4 for i in range(0, len(nibs), 2)) + + +def song_adpcm(): + """a ModPlug ADPCM sample (OpenMPT's compressed 8-bit samples) played at a few pitches""" + raw = T.s8(T.synth("saw", 400, 100, 0.6)) + smp = {"name": "adpcm", "data": raw, "adpcm": modplug_adpcm(raw), "volume": 64, "pan": 128, "loop": (0, 400, 1)} + p = empty(2) + for i, note in enumerate((49, 53, 56, 61)): + put(p, i * 8, 0, note, 1) + put(p, i * 8 + 4, 1, note - 12, 1) + return T.write_xm("adpcm", [{"name": "adpcm", "samples": [smp]}], [0], [p], 2, speed=4, tempo=125) + + def generate(ctx): cases = [] - for nm, data in (("instruments", song_instruments()), ("effects", song_effects()), ("amiga", song_effects(False))): + for nm, data in (("instruments", song_instruments()), ("effects", song_effects()), ("amiga", song_effects(False)), + ("adpcm", song_adpcm())): ref = T.reference(ctx, data, "xm") cases.append({"name": nm, "data": data, "ref": ref, "duration": ref["duration"]}) ctx.emit("xm_cases", cases) diff --git a/tools/fixtures/xmi.py b/tools/fixtures/xmi.py new file mode 100644 index 0000000..9be934c --- /dev/null +++ b/tools/fixtures/xmi.py @@ -0,0 +1,26 @@ +# XMIDI fixtures (tools/fixtures.py): XMI files written by tools/fixtures/_midivar.py (FORM XDIR + CAT XMID with one or +# two songs, a bare FORM XMID (its reference converted from the same song with XDIR); every channel event, note durations, sysex, meta) and wildmidi -x's conversion of song 1 +# as the reference event stream. Each song starts with a tempo event, as real files do (wildmidi derives its 120 Hz +# conversion from the first tempo event). +# tests/gen/xmi_cases.luau { { name, data, songs, ref = { division, tempo, events = { {seconds, status, d1, d2} } } } } +import importlib.util, os + +INPUTS = ["tools/fixtures/_midivar.py"] +_spec = importlib.util.spec_from_file_location("_midivar", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_midivar.py")) +M = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(M) + + +def generate(ctx): + rng = ctx.rng(0x584D49) + cases = [] + for i in range(4): + songs = [M.random_xmi_song(rng, n=60 + 40 * i, tempo=rng.choice([500000, 1000000, 400000]))] + if i == 1: + songs.append(M.random_xmi_song(rng, n=20, tempo=500000)) + data = M.write_xmi(songs, timb=(i != 3)) + ref = M.wildmidi(ctx, data, "xmi") + if i == 2: + data = M.write_xmi(songs, with_xdir=False) # a bare FORM XMID (wildmidi wants XDIR: the reference comes from the full file) + cases.append({"name": "random %d" % i, "data": data, "songs": len(songs), "ref": ref}) + ctx.emit("xmi_cases", cases)