diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 40e275f..5328084 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -16,10 +16,24 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | image | tga | .tga .icb .vda .vst .tpic | yes | yes | alpha: true, palette: true, depths: 8, 15, 16, 24, 32 | `tests/image/tga.luau` | | image | tiff | .tif .tiff | yes | yes | alpha: true, pages: true, depths: 1, 2, 4, 8, 16, 32, float: true | `tests/image/tiff.luau` | | image | webp | .webp | yes | yes | animation: true, alpha: true, lossy: true, lossless: true, depths: 8 | `tests/image/webp.luau` | -| audio | flac | .flac .oga | yes | - | streaming: true, depths: 4, 8, 12, 16, 20, 24, 32, ogg: true, seek: true | `tests/audio/flac.luau` | -| audio | mp3 | .mp3 .mp2 .mp1 .mpga | yes | - | streaming: true, seek: true, layers: 1, 2, 3, channels: 2 | `tests/audio/mp3.luau` | -| audio | opus | .opus | yes | - | streaming: true, seek: true, lossy: true, channels: 255, rates: 48000 | `tests/audio/opus.luau` | +| audio | aac | .aac .adts | yes | - | codecs: "aac", streaming: true | `tests/audio/aac.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 | au | .au .snd | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, lossy: false | `tests/audio/au.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, channels: 2 | `tests/audio/mp3.luau` | +| audio | opus | .opus | yes | yes | streaming: true, seek: true, lossy: true, channels: 255, rates: 48000, encodeModes: "celt" | `tests/audio/opus.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` | +| video | avi | .avi | yes | yes | streaming: true, video: "mjpeg", "mpeg1", "rawvideo", audio: true, odml: true | `tests/video/avi.luau` | +| video | h264 | .h264 .264 .avc .jsv .26l .jvt | yes | yes | streaming: true, video: "h264", depths: 8 | **missing** | +| video | mkv | .mkv .webm .mka .mk3d | yes | yes | streaming: true, remux: true, video: "vp8", "mjpeg", "mpeg1", "rawvideo", audio: true, subtitles: true | `tests/video/mkv.luau` | +| video | mp4 | .mp4 .m4v .mov .qt .3gp .3g2 .mj2 | yes | yes | streaming: true, remux: true, video: "mjpeg", "mpeg1", "h264", audio: true, fragments: true | `tests/video/mp4.luau` | +| video | mpegps | .mpg .mpeg .vob .m1v .mpv .dat | yes | - | streaming: true, video: "mpeg1", audio: true | `tests/video/mpegps.luau` | +| video | mpegts | .ts .m2ts .mts .tsv | yes | - | streaming: true, video: "mpeg1", "h264", audio: true | `tests/video/mpegts.luau` | +| video | y4m | .y4m | yes | yes | streaming: true, video: "rawvideo", depths: 8, 10, 12, 16 | `tests/video/y4m.luau` | | model | gltf | .gltf .glb | yes | yes | binary: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true | `tests/model/gltf.luau` | | model | obj | .obj | yes | yes | materials: true, polygons: true, vertexColors: true | `tests/model/obj.luau` | | model | off | .off | yes | yes | polygons: true, points: true, colors: true, binary: false | `tests/model/off.luau` | @@ -54,12 +68,20 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | subtitle | ass | .ass .ssa | yes | yes | styles: true | `tests/subtitle/ass.luau` | | subtitle | srt | .srt | yes | yes | styles: false | `tests/subtitle/srt.luau` | | subtitle | vtt | .vtt .webvtt | yes | yes | styles: true | `tests/subtitle/vtt.luau` | +| music | it | .it | yes | - | render: true, channels: 1, 64, compressedSamples: true | `tests/music/it.luau` | +| music | midi | .mid .midi .smf .kar .rmi | yes | yes | formats: 0, 1, 2, render: true, streaming: true, rmid: true | `tests/music/midi.luau` | +| music | mod | .mod .m15 .stk .nst | yes | yes | render: true, channels: 1, 32 | `tests/music/mod.luau` | +| music | s3m | .s3m | yes | - | render: true, channels: 1, 32 | `tests/music/s3m.luau` | +| music | sf2 | .sf2 | yes | - | sm24: true, sf3: false | `tests/music/sf2.luau` | +| music | xm | .xm | yes | yes | render: true, channels: 1, 64 | `tests/music/xm.luau` | | playlist | m3u | .m3u .m3u8 | yes | yes | hls: true | `tests/playlist/m3u.luau` | | playlist | pls | .pls | yes | yes | | `tests/playlist/pls.luau` | | playlist | xspf | .xspf | yes | yes | | `tests/playlist/xspf.luau` | Codecs (layer 1, shared by formats; not loadable on their own): +- codecs/Aac: AAC-LC decoder (ISO/IEC 14496-3 subpart 4, ISO/IEC 13818-7): the AudioSpecificConfig (with a program +- codecs/Alac: Apple Lossless (ALAC) decoder and encoder, the codec inside m4a / mov / caf. A codec (layer 1). - codecs/Base64: RFC 4648 base64 (standard alphabet, and base64url with opts.url) encode / decode, for data: URIs - codecs/Blend: layer compositing on rgba8 buffers (straight alpha): source-over with the separable and non-separable - codecs/Brotli: Brotli (RFC 7932) decompression. A codec (layer 3): archive/br and font/woff2 build on it. Written @@ -67,16 +89,25 @@ Codecs (layer 1, shared by formats; not loadable on their own): - codecs/Cff: Compact Font Format (Adobe TN #5176) and Type 2 charstrings (TN #5177): the outlines of OpenType fonts - codecs/Dct: the 8x8 DCTs JPEG, Motion-JPEG and MPEG-1 share (native; never throws). - codecs/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers. +- codecs/H264: an H.264 / AVC (ITU-T H.264 | ISO/IEC 14496-10) video decoder in pure Luau. A codec (layer 1): the +- codecs/Jpeg: the JPEG codec (ITU T.81) on byte ranges: image/jpeg is a thin format over it, and the Motion-JPEG - codecs/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code. - codecs/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. A codec (layer 3): - codecs/Lzw: LZW decoder and encoder in the two variants file formats use. A codec (layer 1): image/gif and +- codecs/Mdct: the MDCT / IMDCT of any window length N divisible by 4 (N / 2 coefficients), through an N / 4-point - codecs/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). Walks +- codecs/Mpeg1: an MPEG-1 video decoder (ISO/IEC 11172-2) for the MPEG-TS / MPEG-PS video formats. Absorbed from +- codecs/Pcm: PCM plumbing shared by audio formats: raw sample formats, streaming Decoders, encoder input sources. - codecs/Quantize: palette quantization of rgba8 pixels. A codec (layer 1): image/gif (and later any palette - codecs/Raster: an antialiased scanline rasterizer for paths of lines, quadratic and cubic Béziers, under an affine +- codecs/SoundFont: SoundFont 2 banks and the sample synth that plays MIDI through them. A codec (layer 1) shared by - codecs/Text: text decoding helpers for the text formats: a UTF-8 BOM is stripped, text that is not valid UTF-8 is +- codecs/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it. The four loaders read - codecs/TrueType: the sfnt font container (TrueType .ttf, OpenType .otf with CFF outlines, collections .ttc) parsed - codecs/Url: RFC 3986 reference resolution (section 5.2), the classification of a playlist / manifest location (URL, +- codecs/Video: the video codec registry and the generic VideoDecoder. New in formats-luau. - codecs/Vp8: the VP8 video codec (RFC 6386), decode only. A codec (layer 1): image/webp uses it for lossy frames, the - codecs/Vp8L: WebP lossless (VP8L, "WebP Lossless Bitstream Specification", RFC 9649 section 3). A codec (layer 1): - codecs/Xml: XML 1.0 parse (DOM and pull events) and serialize, the engine data/xml, SVG, DAE, 3MF, TMX, plist, ... +- codecs/Yuv: planar 4:2:0 Y'CbCr <-> rgba8 for the video codecs and writers (native; never throws). BT.601 or - codecs/Zstd: Zstandard decompression (RFC 8878). A codec (layer 3): archive/zst and anything else carrying zstd diff --git a/docs/video.md b/docs/video.md new file mode 100644 index 0000000..ce04b20 --- /dev/null +++ b/docs/video.md @@ -0,0 +1,62 @@ +# Video + +```luau +local v = F.video.open(src) -- MKV / WebM, AVI, MP4 / MOV, MPEG-TS / PS, Y4M, and animated GIF / APNG / WebP +while true do + local f, err = v:nextFrame() -- f.image: yuv420p (codec output) or rgba8; f.pts / f.duration in seconds + if not f then break end + local rgba = v:toRGBA(f) +end +v:seek(12.5) -- the next frame is the first at or after 12.5 s +local pcm = v.audio and v.audio:read(4096) -- the first audio track, as an audio Decoder (nil + v.audioError otherwise) +for p in v.demuxer:packets(v.track.id) do end -- raw packets (pts / dts / duration in track ticks) +F.save(v, "out.webm") -- remux (VP8 / Opus / Vorbis copied), or "out.avi" / ".mkv" / ".mp4" (MJPEG) +F.convert(gif, "avi") -- animated images become videos (uneven delays: repeated frames) +``` + +`F.load` of a video returns the same VideoDecoder (`kind = "video"`, decoded lazily). + +## Layers + +| Module | Role | +|---|---| +| `Types` (Video section) | `Track`, `Packet`, `Demuxer`, `VideoFrame`, `VideoDecoder`, `VideoCodecDecoder` | +| `containers/Demux` | the indexed Demuxer every container builds: per-track cursors, keyframe seek, `count` / `get` / `info` | +| `containers/Ebml`, `Avi`, `IsoBmff`, `MpegTs`, `MpegPs`, `MpegEs` | container structures | +| `containers/AudioWrap` | an audio track as a stream an audio format reads (PCM -> WAV, Opus / Vorbis -> Ogg, AAC -> ADTS, ...) | +| `codecs/Video` | the codec registry and the generic VideoDecoder (`Video.open(demuxer, opts)`, `Video.fromFrames`) | +| `codecs/Video/Source` | what writers write: copied packets or frames encoded by a registry encoder, PCM from the audio | +| `codecs/Yuv` | yuv420p <-> rgba8 (BT.601 / 709, limited / full range from `image.meta.yuv`), range remap | +| `codecs/Vp8`, `Jpeg`, `Mpeg1` | the decoders (and the JPEG encoder) | +| `video/` | the formats: demux into `containers/Demux`, `open` = `Video.open(demuxer, opts)`, `encode` via Source | + +Audio tracks reach the audio formats through the api hook `opts.openAudio(demuxer, track)` (a format never requires +another format): `F.video.open` / `F.load` set it; calling a video format's `open` directly gives `v.audio = nil` and +`v.audioError` unless you pass your own. + +## Adding a codec (H.264, ...) + +The registry is static (Roblox has no dynamic require): add an entry to `BUILTIN` in `src/Formats/codecs/Video/init.luau` +with a `new` constructor that requires the codec lazily, or call `Video.register(entry)` at run time +(`F.video.codecs.register`). + +```luau +{ id = "h264", name = "H.264 / AVC", fourcc = { "avc1", "avc3", "H264", ... }, matroska = { "V_MPEG4/ISO/AVC" }, + new = function(track, opts) return require("@formats/codecs/H264").newVideoDecoder(track, opts) end } +``` + +`new(track, opts)` returns a `Types.VideoCodecDecoder`: + +- `decode(self, packet) -> Err?`: one packet in decode order. `track.config` holds the codec configuration (avcC from + MP4 / Matroska; nil for Annex B streams from MPEG-TS / AVI, whose packets carry the parameter sets). +- `receive(self) -> image?, pts?, keyframe?`: the next picture in display order and the pts (track ticks) of the packet + it came from. Return a fresh `yuv420p` Image (set `image.meta.yuv = { range = "limited", matrix = "bt601" }`). +- `flush(self)`: end of stream (release pictures held for reordering). `reset(self)`: after a seek. + +`Video.simpleDecoder(decodeOne, reset)` wraps a codec with one picture per packet and no reordering. Encoders are an +entry's `encode(image, opts) -> buffer` (MJPEG), used by the writers when they cannot copy the source's packets. + +## Speed (one Zen 5 core, `taskset -c 2`) + +Whole pipeline (`F.video.open` + `nextFrame`, yuv / rgba output): see `tools/bench.luau` (ws-video block) and the +codec lines (ws-video-codecs, VP8). diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index dab5523..f56488b 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -12,18 +12,30 @@ | `src/Formats/audio/mp3/` | mp3-luau c755bbf (same author), a port of minimp3 by lieff (https://github.com/lieff/minimp3) | minimp3: CC0 1.0, [minimp3-CC0.txt](minimp3-CC0.txt) | | `tests/fixtures/mp3/` | made by ffmpeg (libmp3lame / mp2) from a synthetic signal; `*.ref` are minimp3 decodes of them | test data, no third-party content | | `src/Formats/audio/opus/` (Decoder, Celt, Silk, Mdct, RangeDecoder, Packet, CeltTables, SilkTables) | opus-luau dd2b4e5 (same author): a port of the libopus 1.6 decoder (git bafd40dcbd50; tables generated from its sources); the stereo downmix weights follow opusfile | libopus BSD 3-clause (Xiph.Org, Skype, Octasic, J.-M. Valin, T. B. Terriberry, CSIRO, G. Maxwell, M. Borgerding, E. de Castro Lopo, Mozilla, Amazon), opusfile BSD 3-clause: [libopus-BSD.txt](libopus-BSD.txt) | +| `src/Formats/audio/vorbis/` (Setup, Codebook, Packet, Tables) | a Luau port of stb_vorbis 1.22 by Sean Barrett (https://github.com/nothings/stb): setup parsing, codebooks, floor 1, residues, coupling (the IMDCT is codecs/Mdct; the timing follows libvorbis / the spec) | public domain or MIT (dual): [stb_vorbis-LICENSE.txt](stb_vorbis-LICENSE.txt) | | `src/Formats/audio/flac/` | flac-luau 7083d0d (same author), written from RFC 9639 | no licence chosen yet; no third-party code | | `src/Formats/image/bmp/` | bmp-luau b86aed6 (same author), written from the Microsoft BMP documentation | no licence chosen yet; no third-party code | | `tests/fixtures/bmpsuite/` | BMP Suite 2.8 by Jason Summers (generated images) | public domain: [bmpsuite-NOTICE.txt](bmpsuite-NOTICE.txt) | | `src/Formats/containers/Zip/` (the reader), `src/Formats/archive/zip/` | zip-luau 121d4b0 (same author), written from PKWARE's APPNOTE.TXT 6.3 | no licence chosen yet; no third-party code | +| `src/Formats/audio/mp3/EncTables.luau` (ws-audio encoders) | PDMP3 by Krister Lagerström et al. (https://github.com/technosaurus/PDMP3): the ISO/IEC 11172-3 synthesis window and layer III Huffman trees | public domain (unlicense): [PDMP3-UNLICENSE.txt](PDMP3-UNLICENSE.txt) | | `src/Formats/playlist/` (m3u, pls; xspf is new), `src/Formats/codecs/Url/`, `src/Formats/codecs/Text/` | playlist-luau 3fc7fd3 (same author), written from RFC 3986 / RFC 8216 | no licence chosen yet; no third-party code | -| `src/Formats/image/jpeg/` (Decode, Scan, Color), `src/Formats/codecs/Dct/` (inverse DCTs) | jpeg-luau 1.0 (same author); the IDCTs, upsampling, colour conversion and IDCT-size choice are Luau translations of libjpeg / libjpeg-turbo (jidctint.c, jidctred.c, jdsample.c, jdcolor.c, jdmaster.c) | IJG licence + libjpeg-turbo BSD: [libjpeg-turbo-LICENSE.md](libjpeg-turbo-LICENSE.md), [libjpeg-README.ijg](libjpeg-README.ijg). This software is based in part on the work of the Independent JPEG Group. | -| `src/Formats/image/jpeg/Arith.luau`, `src/Formats/image/jpeg/Encode.luau`, `src/Formats/codecs/Dct/` (forward DCT) | new; Luau translations of libjpeg-turbo 3.2 jdarith.c / jaricom.c (Guido Vollbeding), jccolor.c, jcsample.c, jccoefct.c, jfdctint.c, jcdctmgr.c, jchuff.c, jcphuff.c, jcparam.c | as above | +| `src/Formats/codecs/Jpeg/` (Decode, Scan, Color, Yuv; moved from image/jpeg), `src/Formats/codecs/Dct/` (inverse DCTs) | jpeg-luau 1.0 (same author); the IDCTs, upsampling, colour conversion and IDCT-size choice are Luau translations of libjpeg / libjpeg-turbo (jidctint.c, jidctred.c, jdsample.c, jdcolor.c, jdmaster.c) | IJG licence + libjpeg-turbo BSD: [libjpeg-turbo-LICENSE.md](libjpeg-turbo-LICENSE.md), [libjpeg-README.ijg](libjpeg-README.ijg). This software is based in part on the work of the Independent JPEG Group. | +| `src/Formats/codecs/Jpeg/Arith.luau`, `src/Formats/codecs/Jpeg/Encode.luau`, `src/Formats/codecs/Dct/` (forward DCT) | new; Luau translations of libjpeg-turbo 3.2 jdarith.c / jaricom.c (Guido Vollbeding), jccolor.c, jcsample.c, jccoefct.c, jfdctint.c, jcdctmgr.c, jchuff.c, jcphuff.c, jcparam.c | as above | +| `src/Formats/codecs/Mpeg1/` (init, Decoder, Vlc, Tables) | mpeg1-luau e2e2898 (same author), a port of jsmpeg's MPEG-1 video decoder (https://github.com/phoboslab/jsmpeg, src/mpeg1.js; the tables are generated from it) by Dominic Szablewski | MIT: [jsmpeg-MIT.txt](jsmpeg-MIT.txt) | +| `src/Formats/containers/MpegTs/` | mpegts-luau 6e16197 (same author), written from ISO/IEC 13818-1 | no licence chosen yet; no third-party code | +| `src/Formats/codecs/Aac/Tables.luau` | the Huffman codebooks, scalefactor band offsets and TNS limits of ISO/IEC 14496-3 (Annex 4.A), transcribed mechanically from FFmpeg's `libavcodec/aactab.c` (tables of the standard only; no FFmpeg code) | FFmpeg is LGPL-2.1-or-later; the tables are the standard's data | +| `src/Formats/codecs/Aac/`, `codecs/Alac/`, `codecs/Mdct/`, `containers/IsoBmff/`, `audio/m4a`, `audio/aac`, `audio/caf` | written for this library from ISO/IEC 14496-3 / 14496-12 / 23008-12, Apple's ALAC and CAF specifications | no third-party code | +| `src/Formats/audio/opus/CeltEncoder.luau`, `src/Formats/audio/opus/RangeEncoder.luau` | the encoder side of libopus 1.6 (celt_encoder.c, entenc.c, quant_bands.c, laplace.c, rate.c, bands.c, vq.c, cwrs.c), ported to mirror the absorbed decoder; analysis simplified (ws-m4a) | libopus BSD 3-clause: [libopus-BSD.txt](libopus-BSD.txt) | | `tests/fixtures/pngsuite/` | PngSuite by Willem van Schaik | [PngSuite-LICENSE.txt](PngSuite-LICENSE.txt) | | `tests/fixtures/vox/{chr_knight,chr_sword,deer,maze}.vox`, `tests/fixtures/vox/MagicaVoxel-file-format-vox*.txt` (the format spec) | ephtracy/voxel-model (MagicaVoxel sample models) | MIT: [voxel-model-LICENSE.txt](voxel-model-LICENSE.txt) | | `tests/fixtures/vox/ogt_*.vox` | jpaver/opengametools `demo/vox/` (files saved by MagicaVoxel 0.99.x) | MIT: [opengametools-LICENSE.txt](opengametools-LICENSE.txt) | | `tests/fixtures/gltf/` | KhronosGroup/glTF-Sample-Assets `Models/` (one LICENSE.md per model folder; `UnicodeTest` is `Unicode❤♻Test` renamed) | CC-BY-4.0 or CC0-1.0 per model, see each folder's LICENSE.md | | `src/Formats/codecs/Vp8/` (Decode, Yuv, Tables), `src/Formats/codecs/Vp8L/Decode.luau`, `src/Formats/image/webp/` (Alpha unfilters, Anim.coalesce) | ports of libwebp 1.6.0 (Google): src/dec, src/dsp, src/utils, src/demux/anim_decode.c | BSD-3-Clause + patent grant: [libwebp-LICENSE.txt](libwebp-LICENSE.txt) | +| `src/Formats/codecs/Tracker/`, `src/Formats/music/{mod,s3m,xm,it}/` | written for this library from the format documents: ProTracker 2.3 effect docs, the XM specification (Mr.H / Triton) and FT2 behaviour notes, ST3 TECH.DOC (Sami Tammilehto / Future Crew), ITTECH.TXT (Jeffrey Lim); OpenMPT (libopenmpt, BSD) was used only as the reference player in the tests, and its documented playback quirks (mix levels, MOD panning, FT2 E6x / tremor / instrument behaviour) are matched | no third-party code | +| `tools/fixtures/{mod,s3m,xm,it}.py` test modules | generated by the fixture scripts (synthesized samples) | no third-party data | +| `src/Formats/codecs/SoundFont/` (Synth, the zone merging in Parse) | port of TinySoundFont v0.9 (tsf.h) by Bernhard Schelling, based on SFZero by Steve Folta | MIT: [TinySoundFont-LICENSE.txt](TinySoundFont-LICENSE.txt) | +| `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) | Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this folder (see docs/STYLE.md, "Absorbing an existing repo"). diff --git a/licenses/PDMP3-UNLICENSE.txt b/licenses/PDMP3-UNLICENSE.txt new file mode 100644 index 0000000..abdbb5f --- /dev/null +++ b/licenses/PDMP3-UNLICENSE.txt @@ -0,0 +1,27 @@ +PDMP3 (https://github.com/technosaurus/PDMP3), public domain decoder by Krister Lagerstrom et al. +Tables used in src/Formats/audio/mp3/EncTables.luau. + +Public Domain (www.unlicense.org) + This is free and unencumbered software released into the public domain. + Anyone is free to copy, modify, publish, use, compile, sell, or distribute this + software, either in source code form or as a compiled binary, for any purpose, + commercial or non-commercial, and by any means. + In jurisdictions that recognize copyright laws, the author or authors of this + software dedicate any and all copyright interest in the software to the public + domain. We make this dedication for the benefit of the public at large and to + the detriment of our heirs and successors. We intend this dedication to be an + overt act of relinquishment in perpetuity of all present and future rights to + this software under copyright law. + 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 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. + + Original version written by Krister Lagerström(krister@kmlager.com) + Website: https://sites.google.com/a/kmlager.com/www/projects + + Contributors: + technosaurus + Erik Hofman (added a subset of the libmpg123 compatible streaming API) diff --git a/licenses/TinySoundFont-LICENSE.txt b/licenses/TinySoundFont-LICENSE.txt new file mode 100644 index 0000000..bf4692a --- /dev/null +++ b/licenses/TinySoundFont-LICENSE.txt @@ -0,0 +1,22 @@ +TinySoundFont v0.9 (https://github.com/schellingb/TinySoundFont), tsf.h + +LICENSE (MIT) + +Copyright (C) 2017-2025 Bernhard Schelling +Based on SFZero, Copyright (C) 2012 Steve Folta (https://github.com/stevefolta/SFZero) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons +to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/licenses/jsmpeg-MIT.txt b/licenses/jsmpeg-MIT.txt new file mode 100644 index 0000000..896c374 --- /dev/null +++ b/licenses/jsmpeg-MIT.txt @@ -0,0 +1,8 @@ +The MIT License (MIT) +Copyright (c) 2017 Dominic Szablewski + +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/libvpx-LICENSE.txt b/licenses/libvpx-LICENSE.txt new file mode 100644 index 0000000..5a2665d --- /dev/null +++ b/licenses/libvpx-LICENSE.txt @@ -0,0 +1,56 @@ +Copyright (c) 2010, The WebM Project authors. 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 Google, nor the WebM 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. + + +----- PATENTS ----- +Additional IP Rights Grant (Patents) +------------------------------------ + +"These implementations" means the copyrightable works that implement the WebM +codecs distributed by Google as part of the WebM Project. + +Google hereby grants to you a perpetual, worldwide, non-exclusive, no-charge, +royalty-free, irrevocable (except as stated in this section) patent license to +make, have made, use, offer to sell, sell, import, transfer, and otherwise +run, modify and propagate the contents of these implementations of WebM, where +such license applies only to those patent claims, both currently owned by +Google and acquired in the future, licensable by Google that are necessarily +infringed by these implementations of WebM. This grant does not include claims +that would be infringed only as a consequence of further modification of these +implementations. If you or your agent or exclusive licensee institute or order +or agree to the institution of patent litigation or any other patent +enforcement activity against any entity (including a cross-claim or +counterclaim in a lawsuit) alleging that any of these implementations of WebM +or any code incorporated within any of these implementations of WebM +constitute direct or contributory patent infringement, or inducement of +patent infringement, then any patent rights granted to you under this License +for these implementations of WebM shall terminate as of the date such +litigation is filed. diff --git a/licenses/stb_vorbis-LICENSE.txt b/licenses/stb_vorbis-LICENSE.txt new file mode 100644 index 0000000..6e4b8d2 --- /dev/null +++ b/licenses/stb_vorbis-LICENSE.txt @@ -0,0 +1,41 @@ +stb_vorbis.c v1.22 (https://github.com/nothings/stb), by Sean Barrett and contributors. +Ported to Luau in src/Formats/audio/vorbis/ (decoder). + +This software is available under 2 licenses -- choose whichever you prefer. +------------------------------------------------------------------------------ +ALTERNATIVE A - MIT License +Copyright (c) 2017 Sean Barrett +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. +------------------------------------------------------------------------------ +ALTERNATIVE B - Public Domain (www.unlicense.org) +This is free and unencumbered software released into the public domain. +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. +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 BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +------------------------------------------------------------------------------ diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index d514aa9..0866b80 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -68,7 +68,7 @@ local list: { Entry } = { path = "image/jpeg", extensions = { "jpg", "jpeg", "jpe", "jfif" }, mime = { "image/jpeg" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Dct" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Jpeg" }, caps = { decode = true, encode = true, lossy = true, alpha = false, depths = { 8, 12 }, progressive = true, arithmetic = true }, load = function() return require("@formats/image/jpeg") @@ -146,26 +146,86 @@ local list: { Entry } = { return require("@formats/image/webp") end, }, + { + name = "aac", + category = "audio", + path = "audio/aac", + extensions = { "aac", "adts" }, + mime = { "audio/aac", "audio/aacp", "audio/x-aac" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac" }, + caps = { decode = true, encode = false, codecs = { "aac" }, streaming = true }, + load = function() + return require("@formats/audio/aac") + 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/Pcm" }, + 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 = "au", + category = "audio", + path = "audio/au", + extensions = { "au", "snd" }, + mime = { "audio/basic", "audio/x-au" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" }, + caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false }, + load = function() + return require("@formats/audio/au") + end, + }, + { + name = "caf", + category = "audio", + path = "audio/caf", + extensions = { "caf", "caff" }, + mime = { "audio/x-caf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac", "codecs/Alac" }, + 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") + end, + }, { name = "flac", category = "audio", path = "audio/flac", extensions = { "flac", "oga" }, mime = { "audio/flac", "audio/x-flac" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg" }, - caps = { decode = true, encode = false, streaming = true, depths = { 4, 8, 12, 16, 20, 24, 32 }, ogg = true, seek = true }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "core/Md5", "codecs/Pcm" }, + caps = { decode = true, encode = true, streaming = true, depths = { 4, 8, 12, 16, 20, 24, 32 }, ogg = true, seek = true }, load = function() return require("@formats/audio/flac") end, }, + { + name = "m4a", + category = "audio", + path = "audio/m4a", + extensions = { "m4a", "m4b", "m4r" }, + mime = { "audio/mp4", "audio/x-m4a", "audio/m4a" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "codecs/Aac", "codecs/Alac" }, + caps = { decode = true, encode = true, codecs = { "aac", "alac" }, encodeCodecs = { "alac" }, tags = true, streaming = true }, + load = function() + return require("@formats/audio/m4a") + end, + }, { name = "mp3", category = "audio", path = "audio/mp3", extensions = { "mp3", "mp2", "mp1", "mpga" }, mime = { "audio/mpeg", "audio/mp3", "audio/mpa" }, - deps = { "core/Err", "core/Bytes", "Types" }, - caps = { decode = true, encode = false, streaming = true, seek = true, layers = { 1, 2, 3 }, channels = 2 }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" }, + caps = { decode = true, encode = true, streaming = true, seek = true, layers = { 1, 2, 3 }, channels = 2 }, load = function() return require("@formats/audio/mp3") end, @@ -176,12 +236,36 @@ local list: { Entry } = { path = "audio/opus", extensions = { "opus" }, mime = { "audio/opus", "audio/ogg" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg" }, - caps = { decode = true, encode = false, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 } }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct" }, + caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 }, encodeModes = { "celt" } }, load = function() return require("@formats/audio/opus") end, }, + { + name = "voc", + category = "audio", + path = "audio/voc", + extensions = { "voc" }, + mime = { "audio/x-voc" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" }, + caps = { decode = true, encode = true, streaming = true, depths = { 8, 16 }, lossy = false }, + load = function() + return require("@formats/audio/voc") + end, + }, + { + name = "vorbis", + category = "audio", + path = "audio/vorbis", + extensions = { "ogg", "oga" }, + mime = { "audio/ogg", "audio/vorbis" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct", "codecs/Pcm" }, + caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255 }, + load = function() + return require("@formats/audio/vorbis") + end, + }, { name = "wav", category = "audio", @@ -194,6 +278,90 @@ local list: { Entry } = { return require("@formats/audio/wav") end, }, + { + name = "avi", + category = "video", + path = "video/avi", + extensions = { "avi" }, + mime = { "video/x-msvideo", "video/avi" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Avi", "containers/Demux", "codecs/Video", "codecs/Video/Source" }, + caps = { decode = true, encode = true, streaming = true, video = { "mjpeg", "mpeg1", "rawvideo" }, audio = true, odml = true }, + load = function() + return require("@formats/video/avi") + end, + }, + { + name = "h264", + category = "video", + path = "video/h264", + extensions = { "h264", "264", "avc", "jsv", "26l", "jvt" }, + mime = { "video/h264" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/Video", "codecs/Video/Source", "codecs/H264" }, + caps = { decode = true, encode = true, streaming = true, video = { "h264" }, depths = { 8 } }, + load = function() + return require("@formats/video/h264") + end, + }, + { + name = "mkv", + category = "video", + path = "video/mkv", + extensions = { "mkv", "webm", "mka", "mk3d" }, + mime = { "video/x-matroska", "video/webm", "audio/x-matroska", "audio/webm" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ebml", "containers/Demux", "codecs/Deflate", "codecs/Video", "codecs/Video/Source" }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "rawvideo" }, audio = true, subtitles = true }, + load = function() + return require("@formats/video/mkv") + end, + }, + { + name = "mp4", + category = "video", + path = "video/mp4", + extensions = { "mp4", "m4v", "mov", "qt", "3gp", "3g2", "mj2" }, + mime = { "video/mp4", "video/quicktime", "video/3gpp" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "containers/Demux", "codecs/Video", "codecs/Video/Source" }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "mjpeg", "mpeg1", "h264" }, audio = true, fragments = true }, + load = function() + return require("@formats/video/mp4") + end, + }, + { + name = "mpegps", + category = "video", + path = "video/mpegps", + extensions = { "mpg", "mpeg", "vob", "m1v", "mpv", "dat" }, + mime = { "video/mpeg" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/MpegPs", "containers/MpegEs", "containers/Demux", "codecs/Video" }, + caps = { decode = true, encode = false, streaming = true, video = { "mpeg1" }, audio = true }, + load = function() + return require("@formats/video/mpegps") + end, + }, + { + name = "mpegts", + category = "video", + path = "video/mpegts", + extensions = { "ts", "m2ts", "mts", "tsv" }, + mime = { "video/mp2t" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/MpegTs", "containers/MpegEs", "containers/Demux", "codecs/Video" }, + caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "h264" }, audio = true }, + load = function() + return require("@formats/video/mpegts") + end, + }, + { + name = "y4m", + category = "video", + path = "video/y4m", + extensions = { "y4m" }, + mime = { "video/x-yuv4mpeg" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/Video", "codecs/Video/Source" }, + caps = { decode = true, encode = true, streaming = true, video = { "rawvideo" }, depths = { 8, 10, 12, 16 } }, + load = function() + return require("@formats/video/y4m") + end, + }, { name = "gltf", category = "model", @@ -602,6 +770,78 @@ local list: { Entry } = { return require("@formats/subtitle/vtt") end, }, + { + name = "it", + category = "music", + path = "music/it", + extensions = { "it" }, + mime = { "audio/it", "audio/x-it" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 64 }, compressedSamples = true }, + load = function() + return require("@formats/music/it") + end, + }, + { + name = "midi", + category = "music", + path = "music/midi", + extensions = { "mid", "midi", "smf", "kar", "rmi" }, + mime = { "audio/midi", "audio/x-midi" }, + deps = { "core/Err", "core/Bytes", "codecs/SoundFont", "Types" }, + caps = { decode = true, encode = true, formats = { 0, 1, 2 }, render = true, streaming = true, rmid = true }, + load = function() + return require("@formats/music/midi") + end, + }, + { + name = "mod", + category = "music", + path = "music/mod", + extensions = { "mod", "m15", "stk", "nst" }, + mime = { "audio/x-mod", "audio/mod" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" }, + caps = { decode = true, encode = true, render = true, channels = { 1, 32 } }, + load = function() + return require("@formats/music/mod") + end, + }, + { + name = "s3m", + category = "music", + path = "music/s3m", + extensions = { "s3m" }, + mime = { "audio/s3m", "audio/x-s3m" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 32 } }, + load = function() + return require("@formats/music/s3m") + end, + }, + { + name = "sf2", + category = "music", + path = "music/sf2", + extensions = { "sf2" }, + mime = { "audio/x-soundfont" }, + deps = { "core/Err", "core/Bytes", "codecs/SoundFont" }, + caps = { decode = true, encode = false, sm24 = true, sf3 = false }, + load = function() + return require("@formats/music/sf2") + end, + }, + { + name = "xm", + category = "music", + path = "music/xm", + extensions = { "xm" }, + mime = { "audio/xm", "audio/x-xm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" }, + caps = { decode = true, encode = true, render = true, channels = { 1, 64 } }, + load = function() + return require("@formats/music/xm") + end, + }, { name = "m3u", category = "playlist", diff --git a/src/Formats/Types.luau b/src/Formats/Types.luau index 6464e98..7914957 100644 --- a/src/Formats/Types.luau +++ b/src/Formats/Types.luau @@ -154,6 +154,7 @@ export type Midi = { division: number, -- ticks per quarter note (or SMPTE, negative) tracks: { { events: { MidiEvent }, name: string? } }, meta: { [string]: any }, + render: ((self: any, opts: any?) -> Decoder)?, -- set by music/midi decode: the SoundFont synth as an audio Decoder } local Midi = {} function Midi.new(division: number?): Midi @@ -162,38 +163,90 @@ end Types.Midi = Midi -- ------------------------------------------------------------------------------------------------ Video +-- A video file opens (F.video.open / a video format's open) as a VideoDecoder; F.load returns the same object (kind = +-- "video", decoded lazily). Underneath sits a Demuxer: the container's tracks and their packets. Video tracks decode +-- through the codec registry (codecs/Video: by codec id or FourCC, so other codecs can plug in), audio tracks through +-- the audio formats (the api hook opts.openAudio, since a format never requires another format). +-- +-- Times: Packet pts / dts / duration are integer ticks of the track's timescale (exact, for remuxing); VideoFrame pts +-- / duration and every `duration` / `seek` argument are seconds. export type Track = { - id: number, + id: number, -- the container's track number (Matroska TrackNumber, AVI stream index + 1, TS PID, ...) kind: "video" | "audio" | "subtitle" | "data", - codec: string, -- "h264", "vp8", "mpeg1", "mjpeg", "aac", "mp3", "opus", ... - timescale: number, -- ticks per second for pts / duration + codec: string, -- our codec id: "vp8", "mjpeg", "mpeg1", "h264", "rawvideo"; "pcm_s16le", "mp3", "opus", "vorbis", ... + codecTag: string?, -- the container's own id ("V_VP8", "MJPG", stream_type "0x01", "avc1", ...) + timescale: number, -- ticks per second for pts / dts / duration duration: number?, -- seconds + default: boolean?, + language: string?, + name: string?, + -- video width: number?, height: number?, + frameRate: number?, -- frames per second (nominal; 0 / nil when unknown) + pixelFormat: string?, -- raw video: "yuv420p", "rgb24", "bgr24", ... + -- audio sampleRate: number?, channels: number?, - config: buffer?, -- codec configuration (avcC, CodecPrivate, ...) + bitsPerSample: number?, + config: buffer?, -- codec configuration (CodecPrivate, avcC, OpusHead, Vorbis headers, AVI strf extra, ...) [string]: any, } -export type Packet = { track: number, pts: number, dts: number?, duration: number?, keyframe: boolean, data: buffer } +export type Packet = { + track: number, -- Track.id + pts: number, -- presentation time, ticks + dts: number?, -- decode time, ticks (nil = pts) + duration: number?, -- ticks + keyframe: boolean, + data: buffer, -- the packet's bytes (its own buffer) +} export type Demuxer = { + kind: "demuxer", + format: string, -- the container format name tracks: { Track }, - duration: number, - -- packets(trackId?) -> iterator of Packets in file order (one track, or all) + duration: number, -- seconds (0 = unknown) + startTime: number, -- seconds: the first video / audio packet's presentation time (VideoFrame times count from it) + meta: { [string]: any }, -- title, tags, ... + -- packets(trackId?) -> iterator of Packets in file order (one track, or all), from the current position packets: (self: any, track: number?) -> () -> Packet?, - seek: ((self: any, seconds: number) -> ())?, + -- read(trackId?) -> the next Packet (one track, or any) | nil at the end + read: (self: any, track: number?) -> Packet?, + -- seek(seconds): every track to its last keyframe at or before the time + seek: (self: any, seconds: number) -> (), + track: (self: any, kind: string) -> Track?, -- the first (default) track of a kind +} +export type VideoFrame = { + image: Image, -- yuv420p (the codecs' native output) or rgba8 (opts.rgba = true, MJPEG without yuv, frames-backed) + pts: number, -- seconds from the start of the stream (the demuxer's startTime) + duration: number, -- seconds + keyframe: boolean?, + index: number, -- 1-based, in output order } -export type VideoFrame = { image: Image, pts: number, duration: number } export type VideoDecoder = { + kind: "video", + format: string, -- the container format name ("mkv", "avi", "gif", ...) + codec: string, -- the video codec id ("vp8", "mjpeg", "frames" for animated images) width: number, height: number, - frameRate: number, - duration: number, + frameRate: number, -- frames per second (nominal) + frames: number, -- frame count when known (0 = unknown) + duration: number, -- seconds + track: Track?, -- the video track decoded nextFrame: (self: any) -> (VideoFrame?, Err?), -- nil, nil at the end - toRGBA: (self: any, frame: VideoFrame) -> Image, - seek: ((self: any, seconds: number) -> ())?, - audio: Decoder?, -- the first audio track, decoded - demuxer: Demuxer?, + toRGBA: (self: any, frame: VideoFrame | Image) -> Image, -- an rgba8 Image (the frame's own image if already rgba8) + seek: (self: any, seconds: number) -> (), -- the next frame is the first at or after the time (decoded from the keyframe before it) + reset: (self: any) -> (), -- back to the start + audio: Decoder?, -- the first audio track, decoded (nil if none or its codec is unavailable: see audioError) + audioError: Err?, + demuxer: Demuxer?, -- nil for frames-backed videos (animated images) + meta: { [string]: any }, +} +-- a codec's decoder instance (codecs/Video registry entries create them): packets in, pictures out +export type VideoCodecDecoder = { + decode: (self: any, packet: Packet) -> Err?, -- feed one packet (decode order) + receive: (self: any) -> (Image?, number?, boolean?), -- the next picture, the pts (ticks) it carries, keyframe | nil + flush: (self: any) -> (), -- end of stream: pictures held for reordering become available to receive() + reset: (self: any) -> (), -- after a seek: drop references / held pictures } -- ------------------------------------------------------------------------------------------------ Scene (3D, glTF-shaped) diff --git a/src/Formats/audio/aac/init.luau b/src/Formats/audio/aac/init.luau new file mode 100644 index 0000000..6c3e45d --- /dev/null +++ b/src/Formats/audio/aac/init.luau @@ -0,0 +1,277 @@ +--!strict +-- audio/aac: raw AAC in ADTS framing (ISO/IEC 13818-7 / 14496-3 1.A.3), the .aac files encoders and radio streams +-- write. Supports: reading AAC-LC through codecs/Aac (1 - 8 channels, every rate, multi-block frames, CRC-protected +-- headers skipped), a leading ID3v2 tag (skipped; its text frames become tags), resync after garbage, seeking (by +-- frame), HE-AAC streams play their AAC-LC core. Not supported: writing (AAC encoding is out of scope), ADIF, LATM. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Aac = require("@formats/codecs/Aac") + +-- ------------------------------------------------------------------------------------------------ contract +local AacFormat = { + name = "aac", + category = "audio", + extensions = { "aac", "adts" }, + mime = { "audio/aac", "audio/aacp", "audio/x-aac" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac" }, + caps = { decode = true, encode = false, codecs = { "aac" }, streaming = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + maxFrames: number?, -- refuse streams with more ADTS frames (default 2^22) +} + +-- ------------------------------------------------------------------------------------------------ constants +local readu8 = buffer.readu8 + +-- the size of an ID3v2 tag at p (0 if none) +local function id3Size(b: buffer, p: number, limit: number): number + if p + 10 > limit or buffer.readstring(b, p, 3) ~= "ID3" then + return 0 + end + local s = 0 + for i = 6, 9 do + s = s * 128 + bit32.band(readu8(b, p + i), 127) + end + local footer = if bit32.band(readu8(b, p + 5), 0x10) ~= 0 then 10 else 0 + return 10 + s + footer +end + +-- a few ID3v2.3 / 2.4 text frames -> tags +local ID3_TAGS: { [string]: string } = { + TIT2 = "title", TPE1 = "artist", TALB = "album", TYER = "date", TDRC = "date", TCON = "genre", TRCK = "track", + COMM = "comment", TCOM = "composer", TPE2 = "albumartist", +} +local function id3Tags(b: buffer, p: number, size: number): Types.Tags + local tags: Types.Tags = {} + local ver = readu8(b, p + 3) + if ver < 3 then + return tags + end + local q, stop = p + 10, p + size + while q + 10 <= stop do + local id = buffer.readstring(b, q, 4) + if not string.match(id, "^[A-Z0-9][A-Z0-9][A-Z0-9][A-Z0-9]$") then + break + end + local n = 0 + for i = 4, 7 do + n = if ver == 4 then n * 128 + bit32.band(readu8(b, q + i), 127) else n * 256 + readu8(b, q + i) + end + if n < 1 or q + 10 + n > stop then + break + end + local key = ID3_TAGS[id] + local enc = readu8(b, q + 10) + if key and (enc == 0 or enc == 3) then + local s = buffer.readstring(b, q + 11, n - 1) + if id == "COMM" and #s > 3 then + s = string.sub(s, 4) + local z = string.find(s, "\0", 1, true) + if z then + s = string.sub(s, z + 1) + end + end + s = (string.gsub(s, "%z+$", "")) + tags[key] = s + end + q += 10 + n + end + return tags +end + +-- ------------------------------------------------------------------------------------------------ sniff +function AacFormat.sniff(r: Bytes.Reader): number + local b, p, limit = r.buf, r.pos, r.limit + p += id3Size(b, p, limit) + local h = Aac.adts(b, p, limit) + if not h then + return 0 + end + -- a second header right after the first makes it certain + local h2 = Aac.adts(b, p + h.frameSize, limit) + if h2 and h2.sfIndex == h.sfIndex and h2.channelConfig == h.channelConfig then + return 0.9 + end + return if p + h.frameSize >= limit then 0.7 else 0.4 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the frame index: offsets of every ADTS frame (resyncing over garbage) +local function index(r: Bytes.Reader, maxFrames: number): ({ number }, { number }, Aac.Adts?, Err.Err?) + local b, limit = r.buf, r.limit + local p = r.base + id3Size(b, r.base, limit) + local offs, sizes = {}, {} + local first: Aac.Adts? = nil + while p + 7 <= limit do + local h = Aac.adts(b, p, limit) + if h and first and (h.sfIndex ~= first.sfIndex or h.channelConfig ~= first.channelConfig) then + h = nil -- a false sync inside the data + end + if not h then + p += 1 + continue + end + if p + h.frameSize > limit then + break -- a truncated last frame + end + if not first then + first = h + end + if h.blocks ~= 1 then + return offs, sizes, first, Err.new(Err.UNSUPPORTED, "ADTS frames with " .. h.blocks .. " raw data blocks", p) + end + table.insert(offs, p + h.headerSize) + table.insert(sizes, h.frameSize - h.headerSize) + 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 AacFormat.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) + local o = opts or {} + local offs, sizes, first, ierr = index(r, o.maxFrames or 2 ^ 22) + if ierr then + return nil, ierr + end + if not first then + return nil, Err.new(Err.CORRUPT, "no ADTS frame", r.base) + end + local h = first :: Aac.Adts + if h.objectType ~= 2 then + return nil, Err.new(Err.UNSUPPORTED, "ADTS profile " .. h.objectType .. " (only AAC-LC)") + end + if h.channelConfig == 0 then + return nil, Err.new(Err.UNSUPPORTED, "ADTS with a program config element (channel configuration 0)") + end + local channels = ({ 1, 2, 3, 4, 5, 6, 8 })[h.channelConfig] :: number + local dec, derr = Aac.decoder({ sfIndex = h.sfIndex, channels = channels, channelConfig = h.channelConfig }) + if not dec then + return nil, derr + end + local d = dec :: Aac.Decoder + local sr = d.sampleRate + local nframes = #offs + local total = nframes * 1024 + local bytes = 0 + for _, s in sizes do + bytes += s + end + local id3 = id3Size(r.buf, r.base, r.limit) + local tags = if id3 > 0 then id3Tags(r.buf, r.base, id3) else {} + local buf = r.buf + local nextFrame = 1 + local pendPos, pendN = 0, 0 + local drop = 0 + local pos = 0 + local failed: Err.Err? = nil + local out: any = { + sampleRate = sr, + channels = channels, + frames = total, + duration = total / sr, + bitrate = if total > 0 then math.floor(bytes * 8 * sr / total) else 0, + tags = tags, + codec = "aac", + error = nil, + } + local function fill(): boolean + while true do + if nextFrame > nframes then + return false + end + local i = nextFrame + nextFrame += 1 + local n, e = d:decode(buf, offs[i], sizes[i]) + if not n then + failed = e + out.error = e + return false + end + if drop >= n then + drop -= n + else + pendPos, pendN = drop, n + drop = 0 + return true + end + end + end + function out.read(_self: any, n: number, ob: buffer?): (buffer, number) + local want = math.max(0, math.floor(n)) + local need = want * channels * 4 + local res = if ob and buffer.len(ob) >= need then ob else buffer.create(need) + local got = 0 + local writef32 = buffer.writef32 + while got < want do + if pendPos >= pendN then + if failed or not fill() then + break + end + end + local take = math.min(want - got, pendN - pendPos) + local src = d.pcm + local q = got * channels * 4 + local s = pendPos * channels + for k = 1, take * channels do + writef32(res, q, src[s + k]) + q += 4 + end + pendPos += take + got += take + end + pos += got + return res, got + end + function out.seek(_self: any, seconds: number) + local target = math.clamp(math.floor(seconds * sr + 0.5), 0, total) + local f = target // 1024 -- frame holding the target (0-based) + local start = math.max(0, f - 1) -- one frame of pre-roll for the overlap + d:reset() + nextFrame = start + 1 + drop = target - start * 1024 + pendPos, pendN = 0, 0 + failed = nil + pos = target + end + function out.position(_self: any): number + return pos / sr + end + if nframes > 0 and not fill() and failed then + return nil, failed + end + return out, nil +end + +function AacFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = AacFormat.open(r, opts) + if not dec then + return nil, err + end + local d: any = dec + local audio = Types.Audio.new(d.sampleRate, d.channels, d.frames) + local done = 0 + while done < d.frames do + local b, n = d:read(math.min(65536, d.frames - done)) + if n == 0 then + break + end + buffer.copy(audio.samples, done * d.channels * 4, b, 0, n * d.channels * 4) + done += n + end + if d.error then + return nil, d.error + end + audio.tags = d.tags + audio.meta.source = { format = "aac", codec = "aac", bitrate = d.bitrate } + return audio, nil +end + +return AacFormat diff --git a/src/Formats/audio/aiff/init.luau b/src/Formats/audio/aiff/init.luau new file mode 100644 index 0000000..94b02c2 --- /dev/null +++ b/src/Formats/audio/aiff/init.luau @@ -0,0 +1,384 @@ +--!strict +-- audio/aiff: AIFF and AIFF-C (Apple Audio Interchange File Format 1.3, AIFF-C draft 1991). New code from the specs. +-- 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. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/Pcm") + +-- ------------------------------------------------------------------------------------------------ contract +local Aiff = { + name = "aiff", + category = "audio", + extensions = { "aiff", "aif", "aifc", "afc" }, + mime = { "audio/aiff", "audio/x-aiff" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" }, + caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false }, +} + +export type DecodeOptions = { + maxFrames: number?, -- refuse more sample frames (default 2^28) +} +export type EncodeOptions = { + sampleFormat: ("s8" | "s16" | "s24" | "s32" | "f32" | "f64" | "ulaw" | "alaw")?, -- default "s16" + littleEndian: boolean?, -- 16-bit samples as AIFF-C "sowt" (default false: big endian; readers such as ffmpeg only + -- take 16-bit sowt, so other formats return Err.ARG) + aifc: boolean?, -- always write AIFF-C (default: only when the sample format needs it) +} + +-- ------------------------------------------------------------------------------------------------ constants +local TEXT_TAGS = { NAME = "title", AUTH = "artist", ["(c) "] = "copyright", ANNO = "comment" } +local TEXT_ORDER = { { "NAME", "title" }, { "AUTH", "artist" }, { "(c) ", "copyright" }, { "ANNO", "comment" } } +local AIFC_VERSION = 0xA2805140 + +-- ext80(b, o) -> the 80-bit IEEE extended float at b[o] (big endian) +local function ext80(b: buffer, o: number): number + local se = buffer.readu8(b, o) * 256 + buffer.readu8(b, o + 1) + local hi = bit32.byteswap(buffer.readu32(b, o + 2)) + local lo = bit32.byteswap(buffer.readu32(b, o + 6)) + local e = bit32.band(se, 0x7FFF) + if e == 0 and hi == 0 and lo == 0 then + return 0 + end + if e == 0x7FFF then + return math.huge + end + local v = (hi * 4294967296 + lo) * 2 ^ (e - 16383 - 63) + return if se >= 0x8000 then -v else v +end + +-- the 10 bytes of x (> 0) as an 80-bit extended float +local function writeExt80(w: Bytes.Writer, x: number) + if x <= 0 or x ~= x then + w:fill(0, 10) + return + end + local e = 0 + while x >= 2 ^ (e + 1) do + e += 1 + end + while x < 2 ^ e do + e -= 1 + end + local m = x * 2 ^ (63 - e) -- in [2^63, 2^64) + local hi = math.floor(m / 4294967296) + local lo = m - hi * 4294967296 + w:u16be(e + 16383) + w:u32be(hi) + w:u32be(math.floor(lo)) +end + +-- the sample format of a COMM chunk: Pcm format name | nil, message +local function sampleFormat(comp: string, bits: number): (string?, string?) + if comp == "NONE" or comp == "twos" or comp == "" then + if bits >= 1 and bits <= 8 then + return "s8" + elseif bits <= 16 then + return "s16be" + elseif bits <= 24 then + return "s24be" + elseif bits <= 32 then + return "s32be" + end + return nil, "bad sample size " .. bits + elseif comp == "sowt" then + if bits >= 1 and bits <= 8 then + return "s8" + elseif bits <= 16 then + return "s16le" + elseif bits <= 24 then + return "s24le" + elseif bits <= 32 then + return "s32le" + end + return nil, "bad sample size " .. bits + elseif comp == "raw " then + return "u8" + elseif comp == "in24" then + return "s24be" + elseif comp == "in32" then + return "s32be" + elseif comp == "42ni" then + return "s32le" + elseif comp == "fl32" or comp == "FL32" then + return "f32be" + elseif comp == "fl64" or comp == "FL64" then + return "f64be" + elseif comp == "ulaw" or comp == "ULAW" then + return "ulaw" + elseif comp == "alaw" or comp == "ALAW" then + return "alaw" + end + return nil, "compression " .. string.format("%q", comp) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Aiff.sniff(r: Bytes.Reader): number + if r:remaining() < 12 or r:peek(4) ~= "FORM" then + return 0 + end + local form = buffer.readstring(r.buf, r.pos + 8, 4) + return if form == "AIFF" or form == "AIFC" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Info = { + channels: number, + frames: number, + sampleRate: number, + bits: number, + format: string, + compression: string, + aifc: boolean, + dataOffset: number, -- absolute in r.buf + truncated: boolean, + tags: Types.Tags, +} + +-- parse(r) -> Info | nil, Err (walks the chunks; does not decode samples) +local function parse(r: Bytes.Reader): (Info?, Err.Err?) + local b = r.buf + local base, limit = r.base, r.limit + if limit - base < 12 or buffer.readstring(b, base, 4) ~= "FORM" then + return nil, Err.new(Err.CORRUPT, "not a FORM file", base) + end + local form = buffer.readstring(b, base + 8, 4) + if form ~= "AIFF" and form ~= "AIFC" then + return nil, Err.new(Err.CORRUPT, "FORM type " .. string.format("%q", form) .. " is not AIFF / AIFC", base + 8) + end + local aifc = form == "AIFC" + local formEnd = math.min(limit, base + 8 + bit32.byteswap(buffer.readu32(b, base + 4))) + local info: Info? = nil + local comm = false + local ssnd: number? = nil + local ssndLen = 0 + local tags: Types.Tags = {} + local p = base + 12 + while p + 8 <= formEnd do + local id = buffer.readstring(b, p, 4) + local len = bit32.byteswap(buffer.readu32(b, p + 4)) + local d = p + 8 + local avail = math.min(len, limit - d) + if id == "COMM" then + if avail < 18 or (aifc and avail < 22) then + return nil, Err.new(Err.TRUNCATED, "COMM chunk too short", p) + end + local ch = buffer.readu8(b, d) * 256 + buffer.readu8(b, d + 1) + local frames = bit32.byteswap(buffer.readu32(b, d + 2)) + local bits = buffer.readu8(b, d + 6) * 256 + buffer.readu8(b, d + 7) + local rate = ext80(b, d + 8) + local comp = if aifc then buffer.readstring(b, d + 18, 4) else "NONE" + if ch < 1 then + return nil, Err.new(Err.CORRUPT, "no channels", d) + end + if not (rate > 0 and rate < 2 ^ 31) then + return nil, Err.new(Err.CORRUPT, "bad sample rate", d + 8) + end + local fmt, why = sampleFormat(comp, bits) + if not fmt then + return nil, Err.new(if comp == "NONE" or comp == "twos" or comp == "sowt" then Err.CORRUPT else Err.UNSUPPORTED, why :: string, d + 18) + end + info = { + channels = ch, + frames = frames, + sampleRate = rate, + bits = bits, + format = fmt, + compression = comp, + aifc = aifc, + dataOffset = 0, + truncated = false, + tags = tags, + } + comm = true + elseif id == "SSND" then + if avail < 8 then + return nil, Err.new(Err.TRUNCATED, "SSND chunk too short", p) + end + local off = bit32.byteswap(buffer.readu32(b, d)) + ssnd = d + 8 + off + ssndLen = math.max(0, avail - 8 - off) + if len >= 8 + off then + ssndLen = math.min(ssndLen, len - 8 - off) + end + elseif TEXT_TAGS[id] then + local s = buffer.readstring(b, d, avail) + local z = string.find(s, "\0", 1, true) + if z then + s = string.sub(s, 1, z - 1) + end + local key = TEXT_TAGS[id] + tags[key] = if tags[key] then tags[key] .. "\n" .. s else s + end + if len > formEnd - d then + break + end + p = d + len + len % 2 + end + if not comm or not info then + return nil, Err.new(Err.CORRUPT, "no COMM chunk", base) + end + local fi = info :: Info + 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 + if present < fi.frames then + fi.frames = present + fi.truncated = true + end + fi.dataOffset = ssnd or base + return fi, nil +end + +-- info(r) -> { channels, frames, sampleRate, bits, format, compression, aifc, tags } | nil, Err +function Aiff.info(r: Bytes.Reader): (Info?, Err.Err?) + return parse(r) +end + +function Aiff.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = Aiff.open(r, opts) + if not dec then + return nil, err + end + local d = dec :: any + local a = Types.Audio.new(d.sampleRate, d.channels, d.frames) + d:read(d.frames, a.samples) + a.tags = d.tags + a.meta.source = d.source + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local FORMATS = { + s8 = { "s8", 8, "NONE" }, + s16 = { "s16be", 16, "NONE" }, + s24 = { "s24be", 24, "NONE" }, + s32 = { "s32be", 32, "NONE" }, + f32 = { "f32be", 32, "fl32" }, + f64 = { "f64be", 64, "fl64" }, + ulaw = { "ulaw", 16, "ulaw" }, + alaw = { "alaw", 16, "alaw" }, +} +local LE = { s16be = "s16le" } +local COMP_NAMES = { NONE = "not compressed", sowt = "", fl32 = "32-bit floating point", fl64 = "64-bit floating point", ulaw = "\181Law 2:1", alaw = "ALaw 2:1" } + +function Aiff.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local o: EncodeOptions = opts or {} + local spec = FORMATS[o.sampleFormat or "s16"] + if not spec then + return nil, Err.new(Err.ARG, "unknown sampleFormat " .. tostring(o.sampleFormat)) + end + local fmt, bits, comp = spec[1], spec[2], spec[3] + if o.littleEndian then + if not LE[fmt] then + return nil, Err.new(Err.ARG, "littleEndian needs 16-bit samples") + end + fmt, comp = LE[fmt], "sowt" + end + if src.channels > 65535 then + return nil, Err.new(Err.ARG, "too many channels") + end + local aifc = o.aifc or comp ~= "NONE" + local w = Bytes.writer(65536) + w:string("FORM") + w:u32be(0) -- patched + w:string(if aifc then "AIFC" else "AIFF") + if aifc then + w:string("FVER") + w:u32be(4) + w:u32be(AIFC_VERSION) + end + -- text chunks from the tags + for _, pair in TEXT_ORDER do + local id, key = pair[1], pair[2] + local s = src.tags[key] + if type(s) == "string" and #s > 0 then + w:string(id) + w:u32be(#s) + w:string(s) + if #s % 2 == 1 then + w:u8(0) + end + end + end + local commAt = w:tell() + w:string("COMM") + if aifc then + local name = COMP_NAMES[comp] or "" + local plen = 1 + #name + plen += plen % 2 + w:u32be(22 + plen) + else + w:u32be(18) + end + w:u16be(src.channels) + w:u32be(0) -- frames, patched + w:u16be(bits) + writeExt80(w, src.sampleRate) + if aifc then + w:string(comp) + local name = COMP_NAMES[comp] or "" + w:u8(#name) + w:string(name) + if (1 + #name) % 2 == 1 then + w:u8(0) + end + end + local ssndAt = w:tell() + w:string("SSND") + w:u32be(0) -- patched + w:u32be(0) -- offset + w:u32be(0) -- block size + local frames, perr = Pcm.encode(src, fmt, w) + if not frames then + return nil, perr + end + local dataLen = w:tell() - ssndAt - 16 + if dataLen % 2 == 1 then + w:u8(0) + end + w:setU32be(ssndAt + 4, dataLen + 8) + w:setU32be(commAt + 10, frames) + w:setU32be(4, w:tell() - 8) + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Aiff.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) + local info, err = parse(r) + if not info then + return nil, err + end + local maxFrames = opts and opts.maxFrames or 2 ^ 28 + 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) + if not dec then + return nil, derr + end + local d = dec :: any + d.source = { + format = "aiff", + aifc = info.aifc, + compression = info.compression, + bitDepth = info.bits, + sampleFormat = info.format, + truncated = info.truncated or nil, + } + return dec, nil +end + +return Aiff diff --git a/src/Formats/audio/au/init.luau b/src/Formats/audio/au/init.luau new file mode 100644 index 0000000..0215799 --- /dev/null +++ b/src/Formats/audio/au/init.luau @@ -0,0 +1,166 @@ +--!strict +-- audio/au: Sun / NeXT audio (.au / .snd), big endian. New code from the Sun audio file format description. +-- Supports: decode / open of encodings 1 (G.711 mu-law), 2 (8-bit), 3 (16-bit), 4 (24-bit), 5 (32-bit linear), +-- 6 (32-bit float), 7 (64-bit float), 27 (G.711 A-law); an unknown data size (0xFFFFFFFF: to the end of the file); +-- the annotation as tags.comment. Encode (Audio or Decoder, streamed) to any of those encodings (default 16-bit). +-- Not supported: G.721 / G.722 / G.723 ADPCM and the other NeXT encodings (Err.UNSUPPORTED). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/Pcm") + +-- ------------------------------------------------------------------------------------------------ contract +local Au = { + name = "au", + category = "audio", + extensions = { "au", "snd" }, + mime = { "audio/basic", "audio/x-au" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" }, + caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false }, +} + +export type DecodeOptions = { + maxFrames: number?, -- refuse more sample frames (default 2^28) +} +export type EncodeOptions = { + sampleFormat: ("s8" | "s16" | "s24" | "s32" | "f32" | "f64" | "ulaw" | "alaw")?, -- default "s16" +} + +-- ------------------------------------------------------------------------------------------------ constants +local ENCODINGS: { [number]: string } = { + [1] = "ulaw", + [2] = "s8", + [3] = "s16be", + [4] = "s24be", + [5] = "s32be", + [6] = "f32be", + [7] = "f64be", + [27] = "alaw", +} +local WRITE = { + ulaw = { 1, "ulaw" }, + s8 = { 2, "s8" }, + s16 = { 3, "s16be" }, + s24 = { 4, "s24be" }, + s32 = { 5, "s32be" }, + f32 = { 6, "f32be" }, + f64 = { 7, "f64be" }, + alaw = { 27, "alaw" }, +} +local BITS = { ulaw = 8, alaw = 8, s8 = 8, s16be = 16, s24be = 24, s32be = 32, f32be = 32, f64be = 64 } + +local function be32(b: buffer, o: number): number + return bit32.byteswap(buffer.readu32(b, o)) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Au.sniff(r: Bytes.Reader): number + return if r:peek(4) == ".snd" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Au.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = Au.open(r, opts) + if not dec then + return nil, err + end + local d = dec :: any + local a = Types.Audio.new(d.sampleRate, d.channels, d.frames) + d:read(d.frames, a.samples) + a.tags = d.tags + a.meta.source = d.source + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Au.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local o: EncodeOptions = opts or {} + local spec = WRITE[o.sampleFormat or "s16"] + if not spec then + return nil, Err.new(Err.ARG, "unknown sampleFormat " .. tostring(o.sampleFormat)) + end + if src.sampleRate ~= math.floor(src.sampleRate) or src.sampleRate >= 2 ^ 32 then + return nil, Err.new(Err.ARG, "the sample rate must be an integer") + end + -- annotation: the comment tag, NUL-terminated, padded to a multiple of 8 (at least 4 bytes, as Sun requires) + local note = if type(src.tags.comment) == "string" then src.tags.comment else "" + local alen = #note + 1 + alen = math.max(8, alen + (8 - alen % 8) % 8) + local w = Bytes.writer(65536) + w:string(".snd") + w:u32be(24 + alen) + w:u32be(0xFFFFFFFF) -- patched + w:u32be(spec[1]) + w:u32be(src.sampleRate) + w:u32be(src.channels) + w:string(note) + w:fill(0, alen - #note) + local frames, perr = Pcm.encode(src, spec[2], w) + if not frames then + return nil, perr + end + w:setU32be(8, w:tell() - 24 - alen) + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Au.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) + local b, base, limit = r.buf, r.base, r.limit + if limit - base < 24 or buffer.readstring(b, base, 4) ~= ".snd" then + return nil, Err.new(Err.CORRUPT, "bad magic", base) + end + local off, size, enc, rate, ch = be32(b, base + 4), be32(b, base + 8), be32(b, base + 12), be32(b, base + 16), be32(b, base + 20) + local fmt = ENCODINGS[enc] + if not fmt then + return nil, Err.new(Err.UNSUPPORTED, "encoding " .. enc, base + 12) + end + if ch < 1 or ch > 65535 then + return nil, Err.new(Err.CORRUPT, "bad channel count " .. ch, base + 20) + end + if rate < 1 then + return nil, Err.new(Err.CORRUPT, "bad sample rate", base + 16) + end + if off < 24 or off > limit - base then + return nil, Err.new(Err.CORRUPT, "bad data offset", base + 4) + end + local tags: Types.Tags = {} + if off > 24 then + local s = buffer.readstring(b, base + 24, off - 24) + local z = string.find(s, "\0", 1, true) + if z then + s = string.sub(s, 1, z - 1) + end + if #s > 0 then + tags.comment = s + end + end + local avail = limit - base - off + local truncated = false + if size == 0xFFFFFFFF then + size = avail + elseif size > avail then + size = avail + truncated = true + end + local frameBytes = ch * Pcm.Convert.SIZE[fmt] + local frames = size // frameBytes + local maxFrames = opts and opts.maxFrames or 2 ^ 28 + if frames > maxFrames then + return nil, Err.new(Err.LIMIT, string.format("%d frames is over the %d frame limit", frames, maxFrames)) + end + local dec, derr = Pcm.rawDecoder(b, base + off, frames, ch, rate, fmt, tags) + if not dec then + return nil, derr + end + local d = dec :: any + d.source = { format = "au", encoding = enc, sampleFormat = fmt, bitDepth = BITS[fmt], truncated = truncated or nil } + return dec, nil +end + +return Au diff --git a/src/Formats/audio/caf/init.luau b/src/Formats/audio/caf/init.luau new file mode 100644 index 0000000..f602434 --- /dev/null +++ b/src/Formats/audio/caf/init.luau @@ -0,0 +1,746 @@ +--!strict +-- audio/caf: Apple Core Audio Format (CAF 1.0, Apple's "Core Audio Format Specification"). Supports reading linear +-- PCM (8 / 16 / 24 / 32-bit integer, 32 / 64-bit float, big / little endian), ALAC (codecs/Alac), AAC-LC (codecs/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). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Aac = require("@formats/codecs/Aac") +local Alac = require("@formats/codecs/Alac") + +-- ------------------------------------------------------------------------------------------------ contract +local Caf = { + name = "caf", + category = "audio", + extensions = { "caf", "caff" }, + mime = { "audio/x-caf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac", "codecs/Alac" }, + caps = { decode = true, encode = true, codecs = { "pcm", "alac", "aac", "ulaw", "alaw" }, encodeCodecs = { "pcm", "alac" }, tags = true, streaming = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + maxPackets: number?, -- packet table limit (default 2^24) +} +export type EncodeOptions = { + codec: ("pcm" | "alac")?, -- default "alac" + bitDepth: number?, -- pcm: 16 (default), 24, 32 (float); alac: 16 (default), 20, 24 + tags: Types.Tags?, -- default: the audio's tags +} + +-- ------------------------------------------------------------------------------------------------ constants +local INFO_TAGS: { [string]: string } = { + title = "title", artist = "artist", album = "album", year = "date", genre = "genre", ["track number"] = "track", + comments = "comment", composer = "composer", copyright = "copyright", lyricist = "lyricist", + ["encoding application"] = "encoder", ["recorded date"] = "recorded", tempo = "bpm", +} +local TAG_INFO: { [string]: string } = {} +for k, v in INFO_TAGS do + TAG_INFO[v] = k +end + +-- mu-law / A-law -> linear 16-bit +local ULAW, ALAW = table.create(256, 0), table.create(256, 0) +for i = 0, 255 do + local u = 255 - i + local t = (bit32.band(u, 15) * 8 + 132) * 2 ^ bit32.band(bit32.rshift(u, 4), 7) + ULAW[i + 1] = if bit32.band(u, 128) ~= 0 then 132 - t else t - 132 + local a = bit32.bxor(i, 0x55) + local seg = bit32.band(bit32.rshift(a, 4), 7) + local m = bit32.band(a, 15) * 16 + 8 + if seg > 0 then + m = (m + 256) * 2 ^ (seg - 1) + end + ALAW[i + 1] = if bit32.band(a, 128) ~= 0 then m else -m +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Caf.sniff(r: Bytes.Reader): number + local h = r:peek(8) + if #h == 8 and string.sub(h, 1, 4) == "caff" and string.byte(h, 5) == 0 and string.byte(h, 6) == 1 then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Desc = { rate: number, format: string, flags: number, bytesPerPacket: number, framesPerPacket: number, channels: number, bits: number } +type Parsed = { + desc: Desc, + dataStart: number, -- absolute offset of the audio data + dataEnd: number, + cookie: buffer?, + packets: { number }?, -- sizes (pakt) + packetFrames: { number }?, + priming: number, + remainder: number, + validFrames: number?, + tags: Types.Tags, +} + +-- the esds payload in a kuki (version / flags, then the ES_Descriptor) -> the DecoderSpecificInfo +local function esdsConfig(b: buffer): buffer? + local r = Bytes.reader(b) + if r:peekU8() ~= 3 then + r:skip(4) -- the esds atom's version / flags + end + local function len(): number + local n = 0 + for _ = 1, 4 do + local c = r:u8() + n = n * 128 + bit32.band(c, 127) + if c < 128 then + break + end + end + return n + end + while not r:eof() and not r.err do + local tag = r:u8() + local n = len() + if tag == 3 then + r:skip(2) + local f = r:u8() + if bit32.band(f, 0x80) ~= 0 then + r:skip(2) + end + if bit32.band(f, 0x40) ~= 0 then + r:skip(r:u8()) + end + if bit32.band(f, 0x20) ~= 0 then + r:skip(2) + end + elseif tag == 4 then + r:skip(13) + elseif tag == 5 then + if n > 0 and r:need(n) then + return r:bytes(n) + end + return nil + else + r:skip(n) + end + end + return nil +end + +local function vlq(r: Bytes.Reader): number + local v = 0 + for _ = 1, 8 do + local c = r:u8() + v = v * 128 + bit32.band(c, 127) + if c < 128 then + return v + end + end + r:fail(Err.CORRUPT, "bad packet table entry") + return 0 +end + +local function parse(r: Bytes.Reader, o: DecodeOptions): (Parsed?, Err.Err?) + if Caf.sniff(r) == 0 then + return nil, Err.new(Err.CORRUPT, "not a CAF file", r.base) + end + r:seek(8) + local p: Parsed = { desc = nil :: any, dataStart = 0, dataEnd = 0, priming = 0, remainder = 0, tags = {} } + local haveData = false + while r:remaining() >= 12 do + local typ = r:string(4) + local size = r:i64be() + local start = r.pos + if size == -1 and typ == "data" then + size = r.limit - start + end + if size < 0 then + return nil, Err.new(Err.CORRUPT, "bad chunk size", start - 12) + end + local stop = start + size + if stop > r.limit then + if typ ~= "data" then + return nil, Err.new(Err.TRUNCATED, "chunk '" .. typ .. "' runs past the end", start - 12) + end + stop = r.limit -- a truncated data chunk: play what is there + end + local c = Bytes.reader(r.buf, start, stop - start) + if typ == "desc" then + p.desc = { + rate = c:f64be(), + format = c:string(4), + flags = c:u32be(), + bytesPerPacket = c:u32be(), + framesPerPacket = c:u32be(), + channels = c:u32be(), + bits = c:u32be(), + } + if c.err then + return nil, c.err + end + elseif typ == "data" then + p.dataStart = start + 4 -- edit count + p.dataEnd = stop + haveData = true + elseif typ == "kuki" then + p.cookie = c:bytes(stop - start) + elseif typ == "pakt" then + local n = c:i64be() + p.validFrames = c:i64be() + p.priming = c:i32be() + p.remainder = c:i32be() + if c.err then + return nil, c.err + end + if n < 0 or n > (o.maxPackets or 2 ^ 24) or n > c:remaining() then + return nil, Err.new(Err.LIMIT, "packet table of " .. n .. " entries", start) + end + local d = p.desc + if not d then + return nil, Err.new(Err.CORRUPT, "pakt before desc", start) + end + local sizes, frames = table.create(n, 0), nil + if d.framesPerPacket == 0 then + frames = table.create(n, 0) + end + for i = 1, n do + sizes[i] = if d.bytesPerPacket == 0 then vlq(c) else d.bytesPerPacket + if frames then + frames[i] = vlq(c) + end + end + if c.err then + return nil, c.err + end + p.packets, p.packetFrames = sizes, frames + elseif typ == "info" then + local n = c:u32be() + for _ = 1, math.min(n, 1000) do + local k = c:cstring() + local v = c:cstring() + if c.err then + break + end + p.tags[INFO_TAGS[string.lower(k)] or k] = v + end + end + r.pos = stop + if typ == "data" and stop >= r.limit then + break + end + end + if not p.desc then + return nil, Err.new(Err.CORRUPT, "no desc chunk", r.base) + end + if not haveData then + return nil, Err.new(Err.CORRUPT, "no data chunk", r.base) + end + local d = p.desc + if d.channels < 1 or d.channels > 64 or d.rate <= 0 or d.rate ~= d.rate or d.rate > 1e7 then + return nil, Err.new(Err.CORRUPT, "bad stream description") + end + return p, nil +end + +-- the packet decoder: decode(i) -> frames into pcm (interleaved floats) | nil, Err +type Source = { + channels: number, + rate: number, + packetCount: number, + packetFrames: (number) -> number, + decode: (number) -> (number?, Err.Err?), + pcm: { number }, + reset: () -> (), + codec: string, + bits: number?, +} + +local function source(r: Bytes.Reader, p: Parsed): (Source?, Err.Err?) + local d = p.desc + local b = r.buf + local ch = d.channels + local fmt = d.format + if fmt == "lpcm" or fmt == "ulaw" or fmt == "alaw" then + local bits = if fmt == "lpcm" then d.bits else 8 + local float = fmt == "lpcm" and bit32.band(d.flags, 1) ~= 0 + local little = fmt == "lpcm" and bit32.band(d.flags, 2) ~= 0 + local bpf = d.bytesPerPacket + if bpf == 0 then + bpf = ch * (bits // 8) + end + if not (bits == 8 or bits == 16 or bits == 24 or bits == 32 or (bits == 64 and float)) or (float and bits < 32) then + return nil, Err.new(Err.UNSUPPORTED, "linear PCM with " .. bits .. " bits") + end + local bps = bits // 8 + if bpf < ch * bps then + return nil, Err.new(Err.CORRUPT, "bytes per packet smaller than a frame") + end + local total = (p.dataEnd - p.dataStart) // bpf + local per = 1024 + local pcm = table.create(per * ch, 0) + local scale = 1 / 2 ^ (bits - 1) + local readu8, readi8 = buffer.readu8, buffer.readi8 + local src: Source = { + channels = ch, + rate = d.rate, + packetCount = (total + per - 1) // per, + packetFrames = function(i: number): number + return math.min(per, total - (i - 1) * per) + end, + pcm = pcm, + reset = function() end, + codec = if fmt == "lpcm" then "pcm" else fmt, + bits = bits, + decode = function(i: number): (number?, Err.Err?) + local f0 = (i - 1) * per + local n = math.min(per, total - f0) + local k = 1 + for f = f0, f0 + n - 1 do + local q = p.dataStart + f * bpf + for _ = 1, ch do + local v + if fmt == "ulaw" then + v = ULAW[readu8(b, q) + 1] / 32768 + elseif fmt == "alaw" then + v = ALAW[readu8(b, q) + 1] / 32768 + elseif float then + if bits == 32 then + v = if little then buffer.readf32(b, q) else Bytes.reader(b, q, 4):f32be() + else + v = if little then buffer.readf64(b, q) else Bytes.reader(b, q, 8):f64be() + end + elseif bits == 8 then + v = readi8(b, q) * scale + elseif bits == 16 then + v = if little then buffer.readi16(b, q) else readi8(b, q) * 256 + readu8(b, q + 1) + v *= scale + elseif bits == 24 then + if little then + v = readi8(b, q + 2) * 65536 + readu8(b, q + 1) * 256 + readu8(b, q) + else + v = readi8(b, q) * 65536 + readu8(b, q + 1) * 256 + readu8(b, q + 2) + end + v *= scale + else + if little then + v = buffer.readi32(b, q) + else + v = readi8(b, q) * 16777216 + readu8(b, q + 1) * 65536 + readu8(b, q + 2) * 256 + readu8(b, q + 3) + end + v *= scale + end + pcm[k] = v + k += 1 + q += bps + end + end + return n, nil + end, + } + return src, nil + end + -- packetised codecs + local sizes = p.packets + if not sizes then + if d.bytesPerPacket > 0 then + local n = (p.dataEnd - p.dataStart) // d.bytesPerPacket + sizes = table.create(n, d.bytesPerPacket) + else + return nil, Err.new(Err.CORRUPT, "compressed CAF without a packet table") + end + end + local offsets = table.create(#sizes, 0) + local o = p.dataStart + for i, s in sizes :: { number } do + offsets[i] = o + o += s + if o > p.dataEnd then + -- a truncated file: keep the whole packets + offsets[i] = nil :: any + sizes = table.move(sizes :: { number }, 1, i - 1, 1, {}) + break + end + end + local count = #(sizes :: { number }) + local fpp = d.framesPerPacket + local pf = p.packetFrames + local function framesOf(i: number): number + return if pf then pf[i] else fpp + end + local cookie = p.cookie + if fmt == "alac" then + if not cookie then + return nil, Err.new(Err.CORRUPT, "ALAC without a magic cookie") + end + local cfg, err = Alac.config(cookie :: buffer) + if not cfg then + return nil, err + end + local dec = Alac.decoder(cfg) + local pcm = table.create(cfg.frameLength * cfg.channels, 0) + local scale = 1 / 2 ^ (cfg.bitDepth - 1) + return { + channels = cfg.channels, + rate = d.rate, + packetCount = count, + packetFrames = framesOf, + pcm = pcm, + reset = function() end, + codec = "alac", + bits = cfg.bitDepth, + decode = function(i: number): (number?, Err.Err?) + local n, e = dec:decode(b, offsets[i], (sizes :: { number })[i]) + if not n then + return nil, e + end + local src = dec.pcm + for k = 1, n * cfg.channels do + pcm[k] = src[k] * scale + end + return n, nil + end, + }, nil + elseif fmt == "aac " then + local asc = if cookie then esdsConfig(cookie :: buffer) else nil + if not asc then + return nil, Err.new(Err.CORRUPT, "AAC without an esds magic cookie") + end + local dec, err = Aac.decoder(asc :: buffer) + if not dec then + return nil, err + end + local ad = dec :: Aac.Decoder + return { + channels = ad.channels, + rate = d.rate, + packetCount = count, + packetFrames = framesOf, + pcm = ad.pcm, + reset = function() + ad:reset() + end, + codec = "aac", + decode = function(i: number): (number?, Err.Err?) + return ad:decode(b, offsets[i], (sizes :: { number })[i]) + end, + }, nil + end + return nil, Err.new(Err.UNSUPPORTED, "CAF format '" .. fmt .. "'") +end + +function Caf.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) + local p, err = parse(r, opts or {}) + if not p then + return nil, err + end + local s, serr = source(r, p :: Parsed) + if not s then + return nil, serr + end + local src = s :: Source + local ch, rate = src.channels, src.rate + local starts = table.create(src.packetCount + 1, 0) + local total = 0 + for i = 1, src.packetCount do + starts[i] = total + total += src.packetFrames(i) + end + starts[src.packetCount + 1] = total + local skip = math.max(0, p.priming) + local stopAt = total + if p.validFrames and p.validFrames >= 0 then + stopAt = math.min(total, skip + p.validFrames) + elseif p.remainder > 0 then + stopAt = math.max(skip, total - p.remainder) + end + local frames = math.max(0, stopAt - skip) + local nextPacket = 1 + local decoded = 0 + local pendPos, pendN = 0, 0 + local dropUntil = skip + local pos = 0 + local failed: Err.Err? = nil + local dec: any = { + sampleRate = rate, + channels = ch, + frames = frames, + duration = frames / rate, + bitrate = if frames > 0 then math.floor((p.dataEnd - p.dataStart) * 8 * rate / frames) else 0, + tags = p.tags, + codec = src.codec, + bitsPerSample = src.bits, + error = nil, + } + local function fill(): boolean + while true do + if nextPacket > src.packetCount or decoded >= stopAt then + return false + end + local i = nextPacket + nextPacket += 1 + local start = starts[i] + local n, e = src.decode(i) + if not n then + failed = e + dec.error = e + return false + end + decoded = start + n + local a = math.max(start, dropUntil) + local b = math.min(decoded, stopAt) + if b > a then + pendPos, pendN = a - start, b - start + return true + end + end + end + function dec.read(_self: any, n: number, out: buffer?): (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 + while got < want do + if pendPos >= pendN then + if failed or not fill() then + break + end + end + local take = math.min(want - got, pendN - pendPos) + local q = got * ch * 4 + local sidx = pendPos * ch + local pcm = src.pcm + for k = 1, take * ch do + writef32(ob, q, pcm[sidx + k]) + q += 4 + end + pendPos += take + got += take + end + pos += got + return ob, got + end + function dec.seek(_self: any, seconds: number) + local target = math.clamp(math.floor(seconds * rate + 0.5), 0, frames) + skip + local lo, hi, found = 1, src.packetCount, 1 + while lo <= hi do + local mid = (lo + hi) // 2 + if starts[mid] <= target then + found = mid + lo = mid + 1 + else + hi = mid - 1 + end + end + if src.codec == "aac" then + found = math.max(1, found - 1) + end + src.reset() + nextPacket = found + decoded = starts[found] + dropUntil = target + pendPos, pendN = 0, 0 + failed = nil + pos = target - skip + end + function dec.position(_self: any): number + return pos / rate + end + if src.packetCount > 0 and frames > 0 and not fill() and failed then + return nil, failed + end + return dec, nil +end + +function Caf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = Caf.open(r, opts) + if not dec then + return nil, err + end + local d: any = dec + local audio = Types.Audio.new(d.sampleRate, d.channels, d.frames) + local done = 0 + while done < d.frames do + local b, n = d:read(math.min(65536, d.frames - done)) + if n == 0 then + break + end + buffer.copy(audio.samples, done * d.channels * 4, b, 0, n * d.channels * 4) + done += n + end + if d.error then + return nil, d.error + end + audio.tags = d.tags + audio.meta.source = { format = "caf", codec = d.codec, bitsPerSample = d.bitsPerSample } + return audio, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function chunk(w: Bytes.Writer, typ: string, size: number) + w:string(typ) + w:i64be(size) +end + +-- encode(audio | decoder, opts?) -> buffer | nil, Err +function Caf.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o = opts or {} + if type(value) ~= "table" or type(value.sampleRate) ~= "number" or type(value.channels) ~= "number" then + return nil, Err.new(Err.ARG, "expected an Audio or a Decoder") + end + local codec = o.codec or "alac" + if codec ~= "alac" and codec ~= "pcm" then + return nil, Err.new(Err.ARG, "codec must be 'alac' or 'pcm'") + end + local sr, ch = value.sampleRate, value.channels + local depth = o.bitDepth or 16 + if codec == "pcm" and depth ~= 16 and depth ~= 24 and depth ~= 32 then + return nil, Err.new(Err.ARG, "pcm bitDepth 16, 24 or 32 (float)") + end + if ch < 1 or ch > 64 or sr <= 0 then + return nil, Err.new(Err.ARG, "bad sample rate / channels") + end + -- the source frames + local isAudio = value.kind == "audio" and type(value.samples) == "buffer" + if not isAudio and type(value.read) ~= "function" then + return nil, Err.new(Err.ARG, "expected an Audio or a Decoder") + end + if isAudio and buffer.len(value.samples) < value.frames * ch * 4 then + return nil, Err.new(Err.ARG, "audio.samples is shorter than frames * channels") + end + local done = 0 + local chunkBuf: buffer? = nil + local function nextBlock(n: number): (buffer?, number, number) + if isAudio then + local k = math.min(n, value.frames - done) + local base = done * ch * 4 + done += k + return value.samples, base, k + end + local b, got = value:read(n, chunkBuf) + chunkBuf = b + done += got + return b, 0, got + end + local readf32 = buffer.readf32 + local data = Bytes.writer(65536) + local sizes: { number } = {} + local enc: Alac.Encoder? = nil + if codec == "alac" then + local e, err = Alac.encoder({ sampleRate = math.floor(sr), channels = ch, bitDepth = depth }) + if not e then + return nil, err + end + enc = e + local ints = table.create(4096 * ch, 0) + local peak = 2 ^ (depth - 1) + while true do + local b, base, n = nextBlock(4096) + if not b or n <= 0 then + break + end + for i = 0, n * ch - 1 do + local v = math.floor(readf32(b, base + i * 4) * peak + 0.5) + ints[i + 1] = math.clamp(v, -peak, peak - 1) + end + local pkt, perr = (e :: Alac.Encoder):encode(ints, 1, n) + if not pkt then + return nil, perr + end + data:bytes(pkt) + table.insert(sizes, buffer.len(pkt)) + end + else + local peak = 2 ^ (depth - 1) + while true do + local b, base, n = nextBlock(4096) + if not b or n <= 0 then + break + end + for i = 0, n * ch - 1 do + local f = readf32(b, base + i * 4) + if depth == 32 then + data:f32be(f) + else + local v = math.clamp(math.floor(f * peak + 0.5), -peak, peak - 1) + if depth == 16 then + data:u16be(v % 65536) + else + data:u24be(v % 16777216) + end + end + end + end + end + local frames = done + local w = Bytes.writer(data:tell() + 1024) + w:string("caff") + w:u16be(1) + w:u16be(0) + chunk(w, "desc", 32) + w:f64be(sr) + if codec == "alac" then + w:string("alac") + w:u32be(({ [16] = 1, [20] = 2, [24] = 3, [32] = 4 })[depth] or 1) + w:u32be(0) + w:u32be(4096) + w:u32be(ch) + w:u32be(0) + else + w:string("lpcm") + w:u32be(if depth == 32 then 1 else 0) -- float / big-endian integer + w:u32be(ch * depth // 8) + w:u32be(1) + w:u32be(ch) + w:u32be(depth) + end + local tags = o.tags or value.tags or {} + local keys = {} + for k, v in tags do + if type(v) == "string" then + table.insert(keys, k) + end + end + table.sort(keys) + if #keys > 0 then + local info = Bytes.writer(256) + info:u32be(#keys) + for _, k in keys do + info:cstring(TAG_INFO[k] or k) + info:cstring(tags[k]) + end + chunk(w, "info", info:tell()) + w:bytes(info.buf, 0, info:tell()) + end + if enc then + local cookie = Alac.cookie(enc.config) + chunk(w, "kuki", buffer.len(cookie)) + w:bytes(cookie) + local pk = Bytes.writer(64 + #sizes * 2) + pk:i64be(#sizes) + pk:i64be(frames) + pk:u32be(0) + pk:u32be(#sizes * 4096 - frames) + for _, s in sizes do + -- BER variable-length integer + local bytes = { s % 128 } + local v = s // 128 + while v > 0 do + table.insert(bytes, 1, 128 + v % 128) + v //= 128 + end + for _, x in bytes do + pk:u8(x) + end + end + chunk(w, "pakt", pk:tell()) + w:bytes(pk.buf, 0, pk:tell()) + end + chunk(w, "data", data:tell() + 4) + w:u32be(0) -- edit count + w:bytes(data.buf, 0, data:tell()) + return w:finish(), nil +end + +return Caf diff --git a/src/Formats/audio/flac/Encode.luau b/src/Formats/audio/flac/Encode.luau new file mode 100644 index 0000000..499f4c0 --- /dev/null +++ b/src/Formats/audio/flac/Encode.luau @@ -0,0 +1,1038 @@ +--!strict +--!native +--!optimize 2 +-- audio/flac/Encode: the FLAC encoder (RFC 9639). New code, written from the RFC; the presets mirror libFLAC's -0 .. -8 +-- (block size 1152 / 4096, max LPC order 0 / 6 / 8 / 12, Rice partition order 3 .. 6, independent / adaptive / +-- exhaustive stereo decorrelation). Subframes: CONSTANT, VERBATIM, FIXED (order 0..4, chosen by the residual sum), +-- LPC (Levinson-Durbin on the tukey(0.5)-windowed autocorrelation, error-feedback coefficient quantization with +-- libFLAC's precision table, the order estimated from the prediction error or searched exhaustively at -8), wasted +-- bits; Rice / Rice2 partitions with the partition order and parameters searched per subframe. Frames carry CRC-8 / +-- CRC-16; STREAMINFO carries the sizes, total samples and the MD5 of the PCM; VORBIS_COMMENT from the tags; an optional +-- SEEKTABLE. Streams: input blocks are pulled from a codecs/Pcm Source, so a Decoder is encoded without decoding it +-- whole. Never throws: bad options are rejected by audio/flac before calling in. +local Md5 = require("@formats/core/Md5") + +local Encode = {} + +local floor, abs, log = math.floor, math.abs, math.log +local readf32, writeu8 = buffer.readf32, buffer.writeu8 + +local POW = table.create(64, 0) +for i = 0, 63 do + POW[i + 1] = 2 ^ i +end + +-- ------------------------------------------------------------------------------------------------ CRCs +local CRC8 = table.create(256, 0) +local CRC16 = table.create(256, 0) +for i = 0, 255 do + local c = i + for _ = 1, 8 do + c = if c >= 128 then bit32.bxor((c * 2) % 256, 0x07) else c * 2 + end + CRC8[i + 1] = c + local d = i * 256 + for _ = 1, 8 do + d = if d >= 32768 then bit32.bxor((d * 2) % 65536, 0x8005) else d * 2 + end + CRC16[i + 1] = d +end +local function crc8(b: buffer, o: number, n: number): number + local c = 0 + for i = o, o + n - 1 do + c = CRC8[bit32.bxor(c, buffer.readu8(b, i)) + 1] + end + return c +end +local function crc16(b: buffer, o: number, n: number): number + local c = 0 + for i = o, o + n - 1 do + c = bit32.bxor((c * 256) % 65536, CRC16[bit32.bxor(c // 256, buffer.readu8(b, i)) + 1]) + end + return c +end +Encode.crc8, Encode.crc16 = crc8, crc16 + +-- ------------------------------------------------------------------------------------------------ bit writer (MSB first) +type W = { buf: buffer, pos: number, acc: number, cnt: number } + +local function ensure(w: W, n: number) + local need = w.pos + n + 16 + local cap = buffer.len(w.buf) + if need > cap then + local nb = buffer.create(math.max(cap * 2, need)) + buffer.copy(nb, 0, w.buf, 0, w.pos) + w.buf = nb + end +end + +-- put(w, v, n): the low n bits (n <= 32) of the non-negative integer v +local function put(w: W, v: number, n: number) + if n == 0 then + return + end + local acc = w.acc * POW[n + 1] + v + local cnt = w.cnt + n + local b, p = w.buf, w.pos + while cnt >= 8 do + cnt -= 8 + local m = POW[cnt + 1] + local byte = floor(acc / m) + writeu8(b, p, byte) + p += 1 + acc -= byte * m + end + w.acc, w.cnt, w.pos = acc, cnt, p +end + +local function putSigned(w: W, v: number, n: number) + put(w, if v < 0 then v + POW[n + 1] else v, n) +end + +local function alignByte(w: W) + if w.cnt > 0 then + put(w, 0, 8 - w.cnt) + end +end + +local function putUtf8(w: W, v: number) + if v < 0x80 then + put(w, v, 8) + return + end + local n = if v < 0x800 then 2 elseif v < 0x10000 then 3 elseif v < 0x200000 then 4 elseif v < 0x4000000 then 5 elseif v < 0x80000000 then 6 else 7 + local first = if n == 7 then 0xFE else (0xFF00 // POW[n + 1]) % 256 -- n leading ones + local shift = 6 * (n - 1) + put(w, first + floor(v / POW[shift + 1]), 8) + for k = n - 2, 0, -1 do + put(w, 0x80 + floor(v / POW[6 * k + 1]) % 64, 8) + end +end + +-- ------------------------------------------------------------------------------------------------ presets +export type Config = { + blockSize: number, + maxLpcOrder: number, + maxPartitionOrder: number, + stereo: string, -- "independent" | "adaptive" | "exhaustive" + exhaustiveOrder: boolean, +} +local PRESETS: { Config } = { + { blockSize = 1152, maxLpcOrder = 0, maxPartitionOrder = 3, stereo = "independent", exhaustiveOrder = false }, + { blockSize = 1152, maxLpcOrder = 0, maxPartitionOrder = 3, stereo = "adaptive", exhaustiveOrder = false }, + { blockSize = 1152, maxLpcOrder = 0, maxPartitionOrder = 3, stereo = "exhaustive", exhaustiveOrder = false }, + { blockSize = 4096, maxLpcOrder = 6, maxPartitionOrder = 4, stereo = "independent", exhaustiveOrder = false }, + { blockSize = 4096, maxLpcOrder = 8, maxPartitionOrder = 4, stereo = "adaptive", exhaustiveOrder = false }, + { blockSize = 4096, maxLpcOrder = 8, maxPartitionOrder = 5, stereo = "exhaustive", exhaustiveOrder = false }, + { blockSize = 4096, maxLpcOrder = 8, maxPartitionOrder = 6, stereo = "exhaustive", exhaustiveOrder = false }, + { blockSize = 4096, maxLpcOrder = 12, maxPartitionOrder = 6, stereo = "exhaustive", exhaustiveOrder = false }, + { blockSize = 4096, maxLpcOrder = 12, maxPartitionOrder = 6, stereo = "exhaustive", exhaustiveOrder = true }, +} +Encode.PRESETS = PRESETS + +-- ------------------------------------------------------------------------------------------------ analysis +-- a subframe plan for one channel signal +type Plan = { + kind: number, -- 0 constant, 1 verbatim, 2 fixed, 3 lpc + bits: number, -- estimated size in bits (with the subframe header) + order: number, + wasted: number, + bps: number, -- sample size after removing wasted bits + res: { number }, -- residual (fixed / lpc), indices 1..n + porder: number, + params: { number }, + method: number, -- 0 Rice (4-bit params), 1 Rice2 (5-bit) + qlp: { number }, + shift: number, + precision: number, + x: { number }, -- the (shifted) samples +} + +local function newPlan(n: number): Plan + return { + kind = 1, + bits = 0, + order = 0, + wasted = 0, + bps = 16, + res = table.create(n, 0), + porder = 0, + params = table.create(64, 0), + method = 0, + qlp = table.create(32, 0), + shift = 0, + precision = 0, + x = table.create(n, 0), + } +end + +-- scratch per encoder +type Scratch = { + sums: { number }, + counts: { number }, + ks: { number }, + bestKs: { number }, + tmpRes: { number }, + win: { number }, + winN: number, + wx: { number }, + autoc: { number }, + lpc: { { number } }, + err: { number }, + qlp: { number }, +} + +-- rice(res, n, order, maxP, plan?) -> bits, porder, method (fills scratch.bestKs with the parameters) +local function rice(sc: Scratch, res: { number }, n: number, order: number, maxP: number): (number, number, number) + -- the finest usable partition order + local p = maxP + while p > 0 and (n % POW[p + 1] ~= 0 or n // POW[p + 1] <= order) do + p -= 1 + end + local sums, counts = sc.sums, sc.counts + local parts = POW[p + 1] + local ps = n // parts + -- sums of zig-zag values at the finest order + for j = 0, parts - 1 do + local s = 0 + local a = if j == 0 then order + 1 else j * ps + 1 + local e = (j + 1) * ps + for i = a, e do + local r = res[i] + s += if r >= 0 then 2 * r else -2 * r - 1 + end + sums[j + 1] = s + counts[j + 1] = e - a + 1 + end + local bestBits, bestP, bestMethod = math.huge, 0, 0 + local ks, bestKs = sc.ks, sc.bestKs + local q = p + while true do + local np = POW[q + 1] + local total = 0 + local maxk = 0 + for j = 1, np do + local s, c = sums[j], counts[j] + local k = 0 + local cost = s + c -- k = 0: unary s, plus one stop bit per sample + if c > 0 and s > c then + local k0 = floor(log(s / c) / 0.6931471805599453) + for kk = math.max(0, k0 - 1), math.min(30, k0 + 1) do + local cc = c * (kk + 1) + floor(s / POW[kk + 1]) + if cc < cost then + cost, k = cc, kk + end + end + end + ks[j] = k + if k > maxk then + maxk = k + end + total += cost + end + local method = if maxk > 14 then 1 else 0 + total += np * (if method == 1 then 5 else 4) + 2 + 4 + if total < bestBits then + bestBits, bestP, bestMethod = total, q, method + for j = 1, np do + bestKs[j] = ks[j] + end + end + if q == 0 then + break + end + -- merge pairs into the next coarser order + for j = 1, np // 2 do + sums[j] = sums[2 * j - 1] + sums[2 * j] + counts[j] = counts[2 * j - 1] + counts[2 * j] + end + q -= 1 + end + return bestBits, bestP, bestMethod +end + +local function keepRice(sc: Scratch, plan: Plan, porder: number, method: number) + plan.porder, plan.method = porder, method + local params = plan.params + for j = 1, POW[porder + 1] do + params[j] = sc.bestKs[j] + end +end + +-- fixed predictor residuals +local function fixedResidual(x: { number }, n: number, order: number, res: { number }) + for i = 1, order do + res[i] = 0 + end + if order == 0 then + for i = 1, n do + res[i] = x[i] + end + elseif order == 1 then + for i = 2, n do + res[i] = x[i] - x[i - 1] + end + elseif order == 2 then + for i = 3, n do + res[i] = x[i] - 2 * x[i - 1] + x[i - 2] + end + elseif order == 3 then + for i = 4, n do + res[i] = x[i] - 3 * x[i - 1] + 3 * x[i - 2] - x[i - 3] + end + else + for i = 5, n do + res[i] = x[i] - 4 * x[i - 1] + 6 * x[i - 2] - 4 * x[i - 3] + x[i - 4] + end + end +end + +-- the fixed order with the smallest residual magnitude (libFLAC's estimate) +local function bestFixedOrder(x: { number }, n: number): (number, number) + if n <= 4 then + return 0, 0 + end + local s0, s1, s2, s3, s4 = 0, 0, 0, 0, 0 + local a, b, c, d = x[4], x[4] - x[3], x[4] - 2 * x[3] + x[2], x[4] - 3 * x[3] + 3 * x[2] - x[1] + for i = 5, n do + local e0 = x[i] + local e1 = e0 - a + local e2 = e1 - b + local e3 = e2 - c + local e4 = e3 - d + s0 += abs(e0) + s1 += abs(e1) + s2 += abs(e2) + s3 += abs(e3) + s4 += abs(e4) + a, b, c, d = e0, e1, e2, e3 + end + local best, bs = 0, s0 + if s1 < bs then + best, bs = 1, s1 + end + if s2 < bs then + best, bs = 2, s2 + end + if s3 < bs then + best, bs = 3, s3 + end + if s4 < bs then + best, bs = 4, s4 + end + return best, bs +end +Encode.bestFixedOrder = bestFixedOrder + +-- libFLAC's default QLP coefficient precision for a block size +local function qlpPrecision(bps: number, n: number): number + if bps > 16 then + return 15 + end + if n <= 192 then + return 7 + elseif n <= 384 then + return 8 + elseif n <= 576 then + return 9 + elseif n <= 1152 then + return 10 + elseif n <= 2304 then + return 11 + elseif n <= 4608 then + return 12 + end + return 13 +end + +-- quantize coefficients lp[1..order] to precision bits: qlp[1..order], shift | nil +local function quantize(lp: { number }, order: number, precision: number, qlp: { number }): number? + local cmax = 0 + for i = 1, order do + local a = abs(lp[i]) + if a > cmax then + cmax = a + end + end + if cmax <= 0 or cmax ~= cmax or cmax == math.huge then + return nil + end + local log2cmax = 0 + while cmax >= 1 do + cmax /= 2 + log2cmax += 1 + end + while cmax < 0.5 do + cmax *= 2 + log2cmax -= 1 + end + -- frexp: cmax = m * 2^log2cmax with m in [0.5, 1) + log2cmax -= 1 + local p = precision - 1 + local qmax = POW[p + 1] - 1 + local qmin = -POW[p + 1] + local shift = p - log2cmax - 1 + if shift > 15 then + shift = 15 + elseif shift < 0 then + return nil + end + local err = 0 + local scale = POW[shift + 1] + for i = 1, order do + err += lp[i] * scale + local q = floor(err + 0.5) + if q > qmax then + q = qmax + elseif q < qmin then + q = qmin + end + err -= q + qlp[i] = q + end + return shift +end + +local function lpcResidual(x: { number }, n: number, order: number, qlp: { number }, shift: number, res: { number }) + local d = POW[shift + 1] + for i = 1, order do + res[i] = 0 + end + for i = order + 1, n do + local s = 0 + for j = 1, order do + s += qlp[j] * x[i - j] + end + res[i] = x[i] - floor(s / d) + end +end + +-- Levinson-Durbin: sc.lpc[o][1..o] and sc.err[o] for o = 1 .. maxOrder; returns the highest usable order +local function levinson(sc: Scratch, maxOrder: number): number + local r = sc.autoc + local e = r[1] + if e <= 0 then + return 0 + end + local a = table.create(maxOrder + 1, 0) + local tmp = table.create(maxOrder + 1, 0) + for o = 1, maxOrder do + local acc = r[o + 1] + for j = 1, o - 1 do + acc -= a[j] * r[o - j + 1] + end + local k = acc / e + for j = 1, o - 1 do + tmp[j] = a[j] - k * a[o - j] + end + for j = 1, o - 1 do + a[j] = tmp[j] + end + a[o] = k + e *= (1 - k * k) + local row = sc.lpc[o] + for j = 1, o do + row[j] = a[j] + end + sc.err[o] = e + if e <= 0 then + return o + end + end + return maxOrder +end + +-- choose the subframe for signal x (n samples, bps bits) into plan (reusing its arrays) +local function analyze(sc: Scratch, cfg: Config, src: { number }, n: number, bps: number, plan: Plan) + local x = plan.x + -- constant? + local first = src[1] + local constant = true + for i = 1, n do + local v = src[i] + if v ~= first then + constant = false + end + end + if constant then + plan.kind, plan.bits, plan.wasted, plan.bps = 0, 8 + bps, 0, bps + plan.res[1] = first + return + end + -- wasted bits: the common trailing zeros + local wasted = 0 + do + local w = 0 + while w < bps - 1 do + local m = POW[w + 2] + local all = true + for i = 1, n do + if src[i] % m ~= 0 then + all = false + break + end + end + if not all then + break + end + w += 1 + end + wasted = w + end + local d = POW[wasted + 1] + for i = 1, n do + x[i] = src[i] / d + end + local b = bps - wasted + local hdr = 8 + wasted + plan.wasted, plan.bps = wasted, b + -- verbatim + plan.kind, plan.bits = 1, hdr + n * b + -- fixed + local fo = bestFixedOrder(x, n) + if n > fo then + local tmp = sc.tmpRes + fixedResidual(x, n, fo, tmp) + local rb, po, me = rice(sc, tmp, n, fo, cfg.maxPartitionOrder) + local bits = hdr + fo * b + rb + if bits < plan.bits then + plan.kind, plan.bits, plan.order = 2, bits, fo + sc.tmpRes, plan.res = plan.res, tmp + keepRice(sc, plan, po, me) + end + end + -- lpc + local maxOrder = math.min(cfg.maxLpcOrder, n - 1, 32) + if maxOrder > 0 then + -- windowed autocorrelation + local win = sc.win + if sc.winN ~= n then + -- tukey(0.5) + local np = floor(0.25 * n) + for i = 1, n do + win[i] = 1 + end + if np > 0 then + for i = 0, np - 1 do + local v = 0.5 - 0.5 * math.cos(math.pi * i / np) + win[i + 1] = v + win[n - i] = v + end + end + sc.winN = n + end + local wx = sc.wx + for i = 1, n do + wx[i] = x[i] * win[i] + end + local ac = sc.autoc + for lag = 0, maxOrder do + local s = 0 + for i = lag + 1, n do + s += wx[i] * wx[i - lag] + end + ac[lag + 1] = s + end + local top = levinson(sc, maxOrder) + if top > 0 then + local precision = qlpPrecision(b, n) + local orders = {} + if cfg.exhaustiveOrder then + for o = 1, top do + table.insert(orders, o) + end + else + -- estimated bits: (n - o) * 0.5 * log2(err_o / n) + o * precision + local bestO, bestE = 1, math.huge + for o = 1, top do + local e = sc.err[o] + local est = if e > 0 then (n - o) * 0.5 * log(e / n) / 0.6931471805599453 + o * (precision + b) else -math.huge + if est < bestE then + bestO, bestE = o, est + end + end + orders[1] = bestO + end + local qlp = sc.qlp + for _, o in orders do + local prec = precision + local shift = quantize(sc.lpc[o], o, prec, qlp) + if shift then + local tmp = sc.tmpRes + lpcResidual(x, n, o, qlp, shift, tmp) + local rb, po, me = rice(sc, tmp, n, o, cfg.maxPartitionOrder) + local bits = hdr + o * b + 4 + 5 + o * prec + rb + if bits < plan.bits then + plan.kind, plan.bits, plan.order = 3, bits, o + plan.shift, plan.precision = shift, prec + for j = 1, o do + plan.qlp[j] = qlp[j] + end + sc.tmpRes, plan.res = plan.res, tmp + keepRice(sc, plan, po, me) + end + end + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ writing +local function writeResidual(w: W, plan: Plan, n: number) + local method = plan.method + put(w, method, 2) + local porder = plan.porder + put(w, porder, 4) + local parts = POW[porder + 1] + local ps = n // parts + local res = plan.res + local pbits = if method == 1 then 5 else 4 + for j = 0, parts - 1 do + local k = plan.params[j + 1] + put(w, k, pbits) + local a = if j == 0 then plan.order + 1 else j * ps + 1 + local e = (j + 1) * ps + local mk = POW[k + 1] + for i = a, e do + local r = res[i] + local u = if r >= 0 then 2 * r else -2 * r - 1 + local hi = floor(u / mk) + local lo = u - hi * mk + if hi + 1 + k <= 32 then + put(w, mk + lo, hi + 1 + k) + else + local q = hi + while q > 24 do + put(w, 0, 24) + q -= 24 + end + put(w, 1, q + 1) + put(w, lo, k) + end + end + end +end + +local function writeSubframe(w: W, plan: Plan, n: number) + local kind = plan.kind + local typ = if kind == 0 then 0 elseif kind == 1 then 1 elseif kind == 2 then 8 + plan.order else 32 + plan.order - 1 + put(w, 0, 1) + put(w, typ, 6) + if kind ~= 0 and plan.wasted > 0 then + put(w, 1, 1) + put(w, 1, plan.wasted) -- k - 1 zeros, then a one + else + put(w, 0, 1) + end + local b = plan.bps + if kind == 0 then + putSigned(w, plan.res[1], b) + return + end + local x = plan.x + if kind == 1 then + for i = 1, n do + putSigned(w, x[i], b) + end + return + end + for i = 1, plan.order do + putSigned(w, x[i], b) + end + if kind == 3 then + put(w, plan.precision - 1, 4) + put(w, plan.shift, 5) + for j = 1, plan.order do + putSigned(w, plan.qlp[j], plan.precision) + end + end + writeResidual(w, plan, n) +end + +local RATE_CODES: { [number]: number } = { + [88200] = 1, + [176400] = 2, + [192000] = 3, + [8000] = 4, + [16000] = 5, + [22050] = 6, + [24000] = 7, + [32000] = 8, + [44100] = 9, + [48000] = 10, + [96000] = 11, +} +local SIZE_CODES: { [number]: number } = { [8] = 1, [12] = 2, [16] = 4, [20] = 5, [24] = 6, [32] = 7 } + +local function blockCode(n: number): (number, number) -- code, extra bits (0, 8, 16) + if n == 192 then + return 1, 0 + end + for k = 2, 5 do + if n == 576 * POW[k - 1] then + return k, 0 + end + end + for k = 8, 15 do + if n == 256 * POW[k - 7] then + return k, 0 + end + end + if n <= 256 then + return 6, 8 + end + return 7, 16 +end + +-- ------------------------------------------------------------------------------------------------ encoder +export type Source = { + sampleRate: number, + channels: number, + frames: number, + tags: { [string]: string }, + read: (self: any, n: number, out: buffer?) -> (buffer, number), + err: any, +} +export type Options = { + level: number, + bits: number, + blockSize: number?, + seekInterval: number, -- seconds between seek points (0 = no SEEKTABLE) + padding: number, -- bytes of PADDING + vendor: string, +} + +local TAG_NAMES = { track = "TRACKNUMBER" } + +-- encode(src, opts) -> buffer | nil, message +function Encode.encode(src: Source, opts: Options): (buffer?, string?) + local cfg = PRESETS[opts.level + 1] + local ch, rate, bps = src.channels, src.sampleRate, opts.bits + local bs = opts.blockSize or cfg.blockSize + local w: W = { buf = buffer.create(65536), pos = 0, acc = 0, cnt = 0 } + -- metadata + put(w, 0x664C6143, 32) -- "fLaC" + put(w, 0, 1) + put(w, 0, 7) + put(w, 34, 24) + local siData = w.pos + for _ = 1, 34 do + put(w, 0, 8) + end + -- seek table placeholders (when the length is known) + local seekPoints = 0 + local seekAt = 0 + local interval = floor(opts.seekInterval * rate) + if interval > 0 and src.frames > 0 then + seekPoints = (src.frames - 1) // interval + 1 + if seekPoints > 65535 // 18 * 18 then + seekPoints = 0 + end + end + -- vorbis comment + local comments = {} + local keys = {} + for k in src.tags do + if type(k) == "string" then + table.insert(keys, k) + end + end + table.sort(keys) + for _, k in keys do + local v = src.tags[k] + if type(v) == "string" then + table.insert(comments, (TAG_NAMES[k] or string.upper(k)) .. "=" .. v) + end + end + local vendor = opts.vendor + local vcLen = 4 + #vendor + 4 + for _, c in comments do + vcLen += 4 + #c + end + -- SEEKTABLE + if seekPoints > 0 then + put(w, 0, 1) + put(w, 3, 7) + put(w, seekPoints * 18, 24) + seekAt = w.pos + ensure(w, seekPoints * 18) + for _ = 1, seekPoints do + put(w, 0xFFFFFFFF, 32) -- sample number: a placeholder until a frame fills it + put(w, 0xFFFFFFFF, 32) + put(w, 0, 32) -- byte offset + put(w, 0, 32) + put(w, 0, 16) -- frame samples + end + end + -- VORBIS_COMMENT (little-endian lengths) + local function le32(v: number) + put(w, v % 256, 8) + put(w, (v // 256) % 256, 8) + put(w, (v // 65536) % 256, 8) + put(w, v // 16777216, 8) + end + ensure(w, vcLen + 8) + put(w, if opts.padding > 0 then 0 else 1, 1) -- the last metadata block unless PADDING follows + put(w, 4, 7) + put(w, vcLen, 24) + le32(#vendor) + for i = 1, #vendor do + put(w, string.byte(vendor, i), 8) + end + le32(#comments) + for _, c in comments do + ensure(w, #c + 8) + le32(#c) + for i = 1, #c do + put(w, string.byte(c, i), 8) + end + end + if opts.padding > 0 then + ensure(w, opts.padding + 8) + put(w, 1, 1) + put(w, 1, 7) + put(w, opts.padding, 24) + for _ = 1, opts.padding do + put(w, 0, 8) + end + end + local audioStart = w.pos + -- frames + local md5 = Md5.new() + local mbytes = (bps + 7) // 8 + local mbuf = buffer.create(bs * ch * mbytes) + local scale = POW[bps] + local maxv, minv = scale - 1, -scale + local X = table.create(ch) + for c = 1, ch do + X[c] = table.create(bs, 0) + end + local side = table.create(bs, 0) + local mid = table.create(bs, 0) + local plans = {} + for i = 1, 4 do + plans[i] = newPlan(bs) + end + for c = 1, ch do + plans[4 + c] = newPlan(bs) + end + local lpcRows = {} + for o = 1, 32 do + lpcRows[o] = table.create(o, 0) + end + local sc: Scratch = { + sums = table.create(64, 0), + counts = table.create(64, 0), + ks = table.create(64, 0), + bestKs = table.create(64, 0), + tmpRes = table.create(bs, 0), + win = table.create(bs, 0), + winN = 0, + wx = table.create(bs, 0), + autoc = table.create(33, 0), + lpc = lpcRows, + err = table.create(32, 0), + qlp = table.create(32, 0), + } + local frameNo = 0 + local total = 0 + local minFrame, maxFrame = math.huge, 0 + local seekNext = 0 + local seekIdx = 0 + local rateCode = RATE_CODES[rate] or 0 + local sizeCode = SIZE_CODES[bps] or 0 + local tmp: buffer? = nil + local pendingBuf: buffer? = nil + local pendingN, pendingOff = 0, 0 + -- read exactly bs frames (fewer only at the end) + local function readBlock(): (buffer?, number) + local out = buffer.create(bs * ch * 4) + local got = 0 + while got < bs do + if pendingN == 0 then + local b, n = src:read(math.max(bs, 4096), tmp) + if n <= 0 then + break + end + tmp = b + pendingBuf, pendingN, pendingOff = b, n, 0 + end + local take = math.min(bs - got, pendingN) + buffer.copy(out, got * ch * 4, pendingBuf :: buffer, pendingOff * ch * 4, take * ch * 4) + got += take + pendingN -= take + pendingOff += take + end + return out, got + end + while true do + local fb, n = readBlock() + if n <= 0 or fb == nil then + break + end + -- to integers (+ the MD5 bytes, signed little endian) + local mo = 0 + for i = 0, n - 1 do + for c = 1, ch do + local v = floor(readf32(fb, (i * ch + c - 1) * 4) * scale + 0.5) + if v ~= v then + v = 0 + elseif v > maxv then + v = maxv + elseif v < minv then + v = minv + end + X[c][i + 1] = v + local u = if v < 0 then v + 4294967296 else v + for k = 0, mbytes - 1 do + writeu8(mbuf, mo, floor(u / POW[8 * k + 1]) % 256) + mo += 1 + end + end + end + md5:update(mbuf, 0, mo) + -- channel decorrelation + local assign = ch - 1 + local chosen: { Plan } = {} + if ch == 2 and cfg.stereo ~= "independent" then + local L, R = X[1], X[2] + for i = 1, n do + local l, r = L[i], R[i] + side[i] = l - r + mid[i] = floor((l + r) / 2) + end + local pl, pr, pm, ps = plans[1], plans[2], plans[3], plans[4] + if cfg.stereo == "adaptive" then + local _, el = bestFixedOrder(L, n) + local _, er = bestFixedOrder(R, n) + local _, em = bestFixedOrder(mid, n) + local _, es = bestFixedOrder(side, n) + -- the estimate picks one decorrelated pair; it is kept only if it beats left / right for real + local best = math.min(el + es, er + es, em + es) + analyze(sc, cfg, L, n, bps, pl) + analyze(sc, cfg, R, n, bps, pr) + chosen, assign = { pl, pr }, 1 + if best < el + er then + analyze(sc, cfg, side, n, bps + 1, ps) + if best == em + es then + analyze(sc, cfg, mid, n, bps, pm) + if pm.bits + ps.bits < pl.bits + pr.bits then + chosen, assign = { pm, ps }, 10 + end + elseif best == el + es then + if pl.bits + ps.bits < pl.bits + pr.bits then + chosen, assign = { pl, ps }, 8 + end + elseif ps.bits + pr.bits < pl.bits + pr.bits then + chosen, assign = { ps, pr }, 9 + end + end + else + analyze(sc, cfg, L, n, bps, pl) + analyze(sc, cfg, R, n, bps, pr) + analyze(sc, cfg, mid, n, bps, pm) + analyze(sc, cfg, side, n, bps + 1, ps) + local lr, ls, rs, msb = pl.bits + pr.bits, pl.bits + ps.bits, ps.bits + pr.bits, pm.bits + ps.bits + local best = math.min(lr, ls, rs, msb) + if best == lr then + chosen, assign = { pl, pr }, 1 + elseif best == msb then + chosen, assign = { pm, ps }, 10 + elseif best == ls then + chosen, assign = { pl, ps }, 8 + else + chosen, assign = { ps, pr }, 9 + end + end + else + for c = 1, ch do + analyze(sc, cfg, X[c], n, bps, plans[4 + c]) + chosen[c] = plans[4 + c] + end + end + -- the frame + local need = n * ch * 4 + 64 + for _, p in chosen do + need += (p.bits // 8) + 8 + end + ensure(w, need) + local start = w.pos + -- seek points: the first frame at or after each multiple of the interval + while seekIdx < seekPoints and total >= seekNext do + local at = seekAt + seekIdx * 18 + local sn, off = total, start - audioStart + local tb = w.buf + for k = 0, 7 do + writeu8(tb, at + k, floor(sn / POW[8 * (7 - k) + 1]) % 256) + writeu8(tb, at + 8 + k, floor(off / POW[8 * (7 - k) + 1]) % 256) + end + writeu8(tb, at + 16, n // 256) + writeu8(tb, at + 17, n % 256) + seekIdx += 1 + seekNext = seekIdx * interval + end + put(w, 0x3FFE, 14) + put(w, 0, 1) + put(w, 0, 1) -- fixed block size + local bcode, bextra = blockCode(n) + put(w, bcode, 4) + put(w, rateCode, 4) + put(w, assign, 4) + put(w, sizeCode, 3) + put(w, 0, 1) + putUtf8(w, frameNo) + if bextra > 0 then + put(w, n - 1, bextra) + end + put(w, crc8(w.buf, start, w.pos - start), 8) + for _, p in chosen do + writeSubframe(w, p, n) + end + alignByte(w) + local c16 = crc16(w.buf, start, w.pos - start) + put(w, c16, 16) + local fsize = w.pos - start + if fsize < minFrame then + minFrame = fsize + end + if fsize > maxFrame then + maxFrame = fsize + end + frameNo += 1 + total += n + if n < bs then + break + end + end + if src.err then + return nil, tostring(src.err) + end + -- unused seek points stay placeholders; STREAMINFO + local out = buffer.create(w.pos) + buffer.copy(out, 0, w.buf, 0, w.pos) + local si = Encode.streaminfo(bs, if frameNo > 0 then minFrame else 0, maxFrame, rate, ch, bps, total, md5:digest()) + buffer.copy(out, siData, si, 0, 34) + return out, nil +end + +-- streaminfo(...) -> the 34-byte STREAMINFO body +function Encode.streaminfo(bs: number, minFrame: number, maxFrame: number, rate: number, ch: number, bps: number, total: number, md5: string): buffer + local w: W = { buf = buffer.create(64), pos = 0, acc = 0, cnt = 0 } + put(w, bs, 16) + put(w, bs, 16) + put(w, minFrame, 24) + put(w, maxFrame, 24) + put(w, rate, 20) + put(w, ch - 1, 3) + put(w, bps - 1, 5) + put(w, floor(total / 2 ^ 32), 4) + put(w, total % 2 ^ 32, 32) + for i = 1, 16 do + put(w, string.byte(md5, i), 8) + end + local out = buffer.create(34) + buffer.copy(out, 0, w.buf, 0, 34) + return out +end + +return Encode diff --git a/src/Formats/audio/flac/init.luau b/src/Formats/audio/flac/init.luau index bcf2578..88e5f22 100644 --- a/src/Formats/audio/flac/init.luau +++ b/src/Formats/audio/flac/init.luau @@ -5,7 +5,9 @@ -- with escapes, every stereo mode, 4-32 bits, 1-8 channels, any sample rate, fixed and variable block sizes, frame -- CRC-16 checks with resync past corrupt frames, sample-accurate seeking (seek table + bisection), an ID3v2 tag in -- front, STREAMINFO / SEEKTABLE / VORBIS_COMMENT / PICTURE metadata, the total length from the last frame when --- STREAMINFO has none. Not supported: encoding (ws-audio), MD5 verification, chained Ogg streams. +-- STREAMINFO has none. Encode (audio/flac/Encode, ws-audio): native FLAC from an Audio or a streamed Decoder, levels +-- 0-8 like libFLAC's presets, 4-24 bits, 1-8 channels, MD5, VORBIS_COMMENT, SEEKTABLE. Not supported: MD5 +-- verification on decode, chained Ogg streams, Ogg FLAC output. -- -- local dec = Flac.open(Bytes.reader(buf)) -- the Types.Decoder (+ bitsPerSample, readInt, seekSample, ...) -- local f32, n = dec:read(4096) -- interleaved f32 in [-1, 1); n = 0 at the end @@ -18,6 +20,8 @@ local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Ogg = require("@formats/containers/Ogg") local Stream = require("@formats/audio/flac/Stream") +local Encode = require("@formats/audio/flac/Encode") +local Pcm = require("@formats/codecs/Pcm") -- ------------------------------------------------------------------------------------------------ contract local Flac = { @@ -25,8 +29,8 @@ local Flac = { category = "audio", extensions = { "flac", "oga" }, mime = { "audio/flac", "audio/x-flac" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg" }, - caps = { decode = true, encode = false, streaming = true, depths = { 4, 8, 12, 16, 20, 24, 32 }, ogg = true, seek = true }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "core/Md5", "codecs/Pcm" }, + caps = { decode = true, encode = true, streaming = true, depths = { 4, 8, 12, 16, 20, 24, 32 }, ogg = true, seek = true }, } -- ------------------------------------------------------------------------------------------------ types @@ -35,6 +39,13 @@ export type OpenOptions = { crc16: boolean?, -- check every frame's CRC-16 (default true; a bad frame is skipped by resyncing) maxFrames: number?, -- decode(): refuse streams longer than this many sample frames (default 2^28) } +export type EncodeOptions = { + level: number?, -- 0..8 like libFLAC's -0 .. -8 (default 5) + bits: number?, -- bits per sample 4..24 (default: the source's meta.source.bitDepth / bitsPerSample if 4..24, else 16) + blockSize: number?, -- 16..65535 (default: the level's, 1152 or 4096) + seekInterval: number?, -- seconds between SEEKTABLE points when the length is known (default 10; 0 = none) + padding: number?, -- bytes of PADDING after the metadata (default 0) +} -- ------------------------------------------------------------------------------------------------ sniff function Flac.sniff(r: Bytes.Reader): number @@ -108,6 +119,51 @@ function Flac.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Er return a, nil end +-- ------------------------------------------------------------------------------------------------ encode +-- encode(audioOrDecoder, opts?) -> FLAC file buffer | nil, Err +function Flac.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local o: EncodeOptions = opts or {} + local level = o.level or 5 + if type(level) ~= "number" or level ~= math.floor(level) or level < 0 or level > 8 then + return nil, Err.new(Err.ARG, "level must be 0..8") + end + local bits = o.bits + if bits == nil then + local v = value :: any + local sb = (type(v.meta) == "table" and type(v.meta.source) == "table" and v.meta.source.bitDepth) or v.bitsPerSample + bits = if type(sb) == "number" and sb >= 4 and sb <= 24 then sb else 16 + end + if type(bits) ~= "number" or bits ~= math.floor(bits) or bits < 4 or bits > 24 then + return nil, Err.new(Err.ARG, "bits must be 4..24") + end + local bs = o.blockSize + if bs ~= nil and (type(bs) ~= "number" or bs ~= math.floor(bs) or bs < 16 or bs > 65535) then + return nil, Err.new(Err.ARG, "blockSize must be 16..65535") + end + if src.channels > 8 then + return nil, Err.new(Err.ARG, "FLAC holds at most 8 channels") + end + if src.sampleRate ~= math.floor(src.sampleRate) or src.sampleRate < 1 or src.sampleRate >= 2 ^ 20 then + return nil, Err.new(Err.ARG, "the sample rate must be an integer below 2^20") + end + local out, msg = Encode.encode(src :: any, { + level = level, + bits = bits :: number, + blockSize = bs, + seekInterval = math.max(0, o.seekInterval or 10), + padding = math.clamp(math.floor(o.padding or 0), 0, 0xFFFFFF), + vendor = "formats-luau", + }) + if not out then + return nil, Err.new(Err.CORRUPT, tostring(msg)) + end + return out, nil +end + -- ------------------------------------------------------------------------------------------------ open -- open(r, opts?) -> Decoder | nil, Err function Flac.open(r: Bytes.Reader, opts: OpenOptions?): (Decoder?, Err.Err?) diff --git a/src/Formats/audio/m4a/init.luau b/src/Formats/audio/m4a/init.luau new file mode 100644 index 0000000..bf64abb --- /dev/null +++ b/src/Formats/audio/m4a/init.luau @@ -0,0 +1,441 @@ +--!strict +-- audio/m4a: MPEG-4 audio files (M4A / M4B / MP4 / MOV audio tracks) through containers/IsoBmff. Supports: reading +-- AAC-LC (codecs/Aac; HE-AAC files play their AAC-LC core at the core rate) and ALAC (codecs/Alac) tracks, gapless +-- trimming through the edit list (encoder priming / padding), seeking, iTunes tags and cover art (dec.pictures); +-- writing ALAC (16 / 20 / 24-bit, 1 - 8 channels) with tags and cover art. Not supported: writing AAC, other codecs +-- inside MP4 (MP3 / Opus / FLAC / AC-3: UNSUPPORTED), encrypted files. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local IsoBmff = require("@formats/containers/IsoBmff") +local Aac = require("@formats/codecs/Aac") +local Alac = require("@formats/codecs/Alac") + +-- ------------------------------------------------------------------------------------------------ contract +local M4a = { + name = "m4a", + category = "audio", + extensions = { "m4a", "m4b", "m4r" }, + mime = { "audio/mp4", "audio/x-m4a", "audio/m4a" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "codecs/Aac", "codecs/Alac" }, + caps = { decode = true, encode = true, codecs = { "aac", "alac" }, encodeCodecs = { "alac" }, tags = true, streaming = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + track: number?, -- the track id to play (default: the first AAC / ALAC track) + gapless: boolean?, -- apply the edit list (default true) + maxSamples: number?, -- sample table limit (default 2^25) +} +export type EncodeOptions = { + bitDepth: number?, -- 16 (default), 20 or 24 + frameLength: number?, -- samples per packet, default 4096 + tags: Types.Tags?, -- default: the audio's tags + pictures: { { mime: string, data: buffer } }?, -- cover art (default: audio.meta.pictures) +} + +-- ------------------------------------------------------------------------------------------------ constants +local AUDIO_BRANDS: { [string]: number } = { ["M4A "] = 1, ["M4B "] = 1, ["M4P "] = 1, ["M4V "] = 0.3 } + +-- ------------------------------------------------------------------------------------------------ sniff +function M4a.sniff(r: Bytes.Reader): number + local brand = IsoBmff.sniff(r) + if brand == nil then + return 0 + end + if AUDIO_BRANDS[brand] then + return AUDIO_BRANDS[brand] + end + if brand == "avif" or brand == "avis" or brand == "heic" or brand == "heix" or brand == "mif1" or brand == "msf1" or brand == "crx " then + return 0 + end + return 0.4 -- an MP4 / MOV that may hold audio; a video format claims it more strongly +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the packet decoder of a track: decode(buf, off, len) -> frames | nil, Err; pcm: interleaved floats +type PacketDecoder = { + channels: number, + sampleRate: number, + frameSize: number, + pcm: { number }, + decode: (buf: buffer, off: number, len: number) -> (number?, Err.Err?), + reset: () -> (), +} + +local function packetDecoder(t: IsoBmff.Track): (PacketDecoder?, Err.Err?) + if not t.config then + return nil, Err.new(Err.CORRUPT, "track " .. t.id .. " (" .. t.codec .. ") has no codec configuration") + end + if t.codec == "alac" then + local cfg, err = Alac.config(t.config :: buffer) + if not cfg then + return nil, err + end + local dec = Alac.decoder(cfg) + local pcm = table.create(cfg.frameLength * cfg.channels, 0) + local scale = 1 / 2 ^ (cfg.bitDepth - 1) + local pd: PacketDecoder = { + channels = cfg.channels, + sampleRate = if cfg.sampleRate > 0 then cfg.sampleRate else (t.sampleRate or 44100), + frameSize = cfg.frameLength, + pcm = pcm, + decode = function(buf: buffer, off: number, len: number): (number?, Err.Err?) + local n, e = dec:decode(buf, off, len) + if not n then + return nil, e + end + local src = dec.pcm + for i = 1, n * cfg.channels do + pcm[i] = src[i] * scale + end + return n, nil + end, + reset = function() end, + } + return pd, nil + elseif t.codec == "aac" then + local dec, err = Aac.decoder(t.config :: buffer) + if not dec then + return nil, err + end + local d = dec :: Aac.Decoder + local pd: PacketDecoder = { + channels = d.channels, + sampleRate = d.sampleRate, + frameSize = d.frameLength, + pcm = d.pcm, + decode = function(buf: buffer, off: number, len: number): (number?, Err.Err?) + return d:decode(buf, off, len) + end, + reset = function() + d:reset() + end, + } + return pd, nil + end + return nil, Err.new(Err.UNSUPPORTED, "audio codec " .. t.codec .. " in MP4") +end + +-- open(r, opts?) -> Types.Decoder | nil, Err +function M4a.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) + local o = opts or {} + local movie, err = IsoBmff.parse(r, { maxSamples = o.maxSamples }) + if not movie then + return nil, err + end + local track: IsoBmff.Track? = nil + local other: IsoBmff.Track? = nil + for _, t in movie.tracks do + if t.kind == "audio" then + if o.track and t.id ~= o.track then + continue + end + if t.codec == "aac" or t.codec == "alac" then + track = t + break + end + other = other or t + end + end + if not track then + if other then + return nil, Err.new(Err.UNSUPPORTED, "audio codec " .. other.codec .. " in MP4") + end + return nil, Err.new(Err.CORRUPT, "no audio track") + end + local t = track :: IsoBmff.Track + local pd, perr = packetDecoder(t) + if not pd then + return nil, perr + end + local p = pd :: PacketDecoder + local channels, sr = p.channels, p.sampleRate + -- media ticks -> sample frames + local tickScale = sr / t.timescale + local gapless = o.gapless ~= false + local skip = if gapless then math.floor(t.skip * tickScale + 0.5) else 0 + local total = 0 + for i = 1, t.sampleCount do + total += t.durations[i] + end + total = math.floor(total * tickScale + 0.5) + if gapless and t.playDuration then + total = math.min(total, skip + math.floor(t.playDuration * tickScale + 0.5)) + end + local tags, pictures = IsoBmff.tags(r, movie) + -- iTunes gapless info (fdkaac, iTunes) when there is no edit list: " 0 ..." (hex) + local smpb = tags.iTunSMPB + if gapless and not t.edits and smpb then + local f = {} + for w in string.gmatch(smpb, "%x+") do + table.insert(f, tonumber(w, 16)) + end + if #f >= 4 and f[2] and f[4] and f[4] > 0 and f[2] + f[4] <= total then + skip = f[2] + total = f[2] + f[4] + end + end + local frames = math.max(0, total - skip) + local buf = r.buf + -- streaming state + local nextPacket = 1 + local decoded = 0 -- frames produced by the packets decoded so far (before trimming) + local pend, pendPos, pendN = p.pcm, 0, 0 -- the current packet: frames pendPos .. pendN - 1 not yet returned + local dropUntil = skip -- absolute frame index of the first frame to return + local stopAt = total + local pos = 0 -- frames returned + local failed: Err.Err? = nil + + local dec: any = { + sampleRate = sr, + channels = channels, + frames = frames, + duration = frames / sr, + bitrate = 0, + tags = tags, + pictures = pictures, + codec = t.codec, + track = t, + movie = movie, + error = nil, + } + local bytes = 0 + for i = 1, t.sampleCount do + bytes += t.sizes[i] + end + dec.bitrate = if frames > 0 then math.floor(bytes * 8 * sr / frames) else (t.bitrate or 0) + + -- decode the next packet into pend; false at the end / on an error + local function fill(): boolean + while true do + if nextPacket > t.sampleCount or decoded >= stopAt then + return false + end + local i = nextPacket + nextPacket += 1 + local start = decoded + local n, e = p.decode(buf, t.offsets[i], t.sizes[i]) + if not n then + failed = e + dec.error = e + return false + end + decoded += n + -- the part of this packet inside [dropUntil, stopAt) + local a = math.max(start, dropUntil) + local b = math.min(decoded, stopAt) + if b > a then + pendPos = a - start + pendN = b - start + return true + end + end + end + + function dec.read(_self: any, n: number, out: buffer?): (buffer, number) + local want = math.max(0, math.floor(n)) + local need = want * channels * 4 + local ob = if out and buffer.len(out) >= need then out else buffer.create(need) + local got = 0 + local writef32 = buffer.writef32 + while got < want do + if pendPos >= pendN then + if failed or not fill() then + break + end + end + local take = math.min(want - got, pendN - pendPos) + local src = pend + local o = got * channels * 4 + local s = pendPos * channels + for k = 1, take * channels do + writef32(ob, o, src[s + k]) + o += 4 + end + pendPos += take + got += take + end + pos += got + return ob, got + end + + function dec.seek(_self: any, seconds: number) + local target = math.clamp(math.floor(seconds * sr + 0.5), 0, frames) + skip -- absolute frame + -- the last packet starting at or before the target, minus one for the codec's overlap (AAC) + local ticks = target / tickScale + local lo, hi, found = 1, t.sampleCount, 1 + while lo <= hi do + local mid = (lo + hi) // 2 + if t.dts[mid] <= ticks then + found = mid + lo = mid + 1 + else + hi = mid - 1 + end + end + local startPacket = if t.codec == "aac" then math.max(1, found - 1) else found + p.reset() + nextPacket = startPacket + decoded = math.floor((t.dts[startPacket] or 0) * tickScale + 0.5) + dropUntil = math.max(target, skip) + pendPos, pendN = 0, 0 + failed = nil + pos = target - skip + end + + function dec.position(_self: any): number + return pos / sr + end + + -- prime: surface a broken first packet as an open error + if t.sampleCount > 0 and frames > 0 then + if not fill() and failed then + return nil, failed + end + end + return dec, nil +end + +-- decode(r, opts?) -> Types.Audio | nil, Err (the whole stream, tags, cover pictures in meta.pictures) +function M4a.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = M4a.open(r, opts) + if not dec then + return nil, err + end + local d: any = dec + local audio = Types.Audio.new(d.sampleRate, d.channels, d.frames) + local done = 0 + local chunk = buffer.create(65536 * d.channels * 4) + while done < d.frames do + local b, n = d:read(math.min(65536, d.frames - done), chunk) + if n == 0 then + break + end + buffer.copy(audio.samples, done * d.channels * 4, b, 0, n * d.channels * 4) + done += n + end + if d.error then + return nil, d.error + end + if done < d.frames then + local short = buffer.create(done * d.channels * 4) + buffer.copy(short, 0, audio.samples, 0, buffer.len(short)) + audio.samples = short + audio.frames = done + end + audio.tags = d.tags + audio.meta.source = { format = "m4a", codec = d.codec, bitsPerSample = d.track.bitsPerSample, brand = d.movie.brand } + if #d.pictures > 0 then + audio.meta.pictures = d.pictures + end + return audio, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- encode(audio | decoder, opts?) -> buffer | nil, Err: an ALAC M4A +function M4a.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o = opts or {} + if type(value) ~= "table" or type(value.sampleRate) ~= "number" or type(value.channels) ~= "number" then + return nil, Err.new(Err.ARG, "expected an Audio or a Decoder") + end + local sr, ch = value.sampleRate, value.channels + local enc, eerr = Alac.encoder({ sampleRate = sr, channels = ch, bitDepth = o.bitDepth or 16, frameLength = o.frameLength }) + if not enc then + return nil, eerr + end + local e = enc :: Alac.Encoder + local depth = e.config.bitDepth + local fl = e.config.frameLength + local peak = 2 ^ (depth - 1) + local packets: { buffer } = {} + local durations: { number } = {} + local ints = table.create(fl * ch, 0) + local floor = math.floor + local readf32 = buffer.readf32 + -- frames from an Audio buffer or a streaming Decoder + local src: buffer, srcFrames = nil :: any, 0 + local isAudio = value.kind == "audio" and type(value.samples) == "buffer" + if isAudio then + src, srcFrames = value.samples, value.frames + if buffer.len(src) < srcFrames * ch * 4 then + return nil, Err.new(Err.ARG, "audio.samples is shorter than frames * channels") + end + elseif type(value.read) ~= "function" then + return nil, Err.new(Err.ARG, "expected an Audio or a Decoder") + end + local done = 0 + local chunk: buffer? = nil + while true do + local n, b, base + if isAudio then + n = math.min(fl, srcFrames - done) + b, base = src, done * ch * 4 + else + local got + b, got = value:read(fl, chunk) + chunk = b + n, base = got, 0 + end + if n <= 0 then + break + end + for i = 0, n * ch - 1 do + local v = floor(readf32(b, base + i * 4) * peak + 0.5) + if v >= peak then + v = peak - 1 + elseif v < -peak then + v = -peak + end + ints[i + 1] = v + end + local pkt, perr = e:encode(ints, 1, n) + if not pkt then + return nil, perr + end + table.insert(packets, pkt) + table.insert(durations, n) + done += n + if isAudio and done >= srcFrames then + break + end + end + local tags = o.tags or value.tags or {} + local pictures = o.pictures or (value.meta and value.meta.pictures) or nil + local timescale = if sr < 65536 then sr else 0 + local file, merr = IsoBmff.mux({ + brand = "M4A ", + minor = 0, + compatible = { "M4A ", "mp42", "isom" }, + timescale = 1000, + tracks = { + { + kind = "audio", + entry = "alac", + timescale = if timescale > 0 then timescale else 48000, + samples = packets, + durations = if timescale > 0 then durations else (function() + local d = {} + for i, v in durations do + d[i] = math.floor(v * 48000 / sr + 0.5) + end + return d + end)(), + sampleRate = sr, + channels = ch, + bitsPerSample = depth, + config = Alac.cookie(e.config), + }, + }, + tags = tags, + pictures = pictures, + }) + if not file then + return nil, merr + end + return file, nil +end + +return M4a diff --git a/src/Formats/audio/mp3/Analysis.luau b/src/Formats/audio/mp3/Analysis.luau new file mode 100644 index 0000000..782b023 --- /dev/null +++ b/src/Formats/audio/mp3/Analysis.luau @@ -0,0 +1,63 @@ +--!strict +--!native +--!optimize 2 +-- audio/mp3/Analysis: the MPEG audio polyphase analysis filterbank (ISO/IEC 11172-3 section C.1.3, figure C.4): 32 +-- input samples -> one sample in each of the 32 subbands, with the standard's 512-tap window C = D / 32 (D from +-- audio/mp3/EncTables) and the matrixing M[k][i] = cos((2k + 1)(i - 16) pi / 64). Shared by the layer II and layer III +-- encoders. New code from the standard's flow chart. Never throws. +-- +-- local st = Analysis.new() +-- Analysis.run(st, samples, start, out, outStart) -- samples[start .. start + 31] -> out[outStart .. outStart + 31] +local E = require("@formats/audio/mp3/EncTables") + +local Analysis = {} + +local C = table.create(512, 0) +for i = 1, 512 do + C[i] = E.D[i] / 32 +end +local M = table.create(32 * 64, 0) -- M[k * 64 + i + 1] +for k = 0, 31 do + for i = 0, 63 do + M[k * 64 + i + 1] = math.cos((2 * k + 1) * (i - 16) * math.pi / 64) + end +end + +export type State = { x: { number }, off: number, y: { number } } + +function Analysis.new(): State + return { x = table.create(1024, 0), off = 0, y = table.create(64, 0) } +end + +-- run(st, s, si, out, oi): s[si .. si + 31] (oldest first) -> out[oi .. oi + 31] (subbands 0 .. 31) +function Analysis.run(st: State, s: { number }, si: number, out: { number }, oi: number) + -- the window X is kept twice (x[p] and x[p + 512]) so X[i] = x[off + i + 1] without a modulo + local x = st.x + local off = (st.off - 32) % 512 + st.off = off + for j = 0, 31 do + local v = s[si + j] + local p = (off + 31 - j) % 512 + 1 -- X[31 - j]: the first new sample goes to X[31], the newest to X[0] + x[p] = v + x[p + 512] = v + end + local y = st.y + for i = 0, 63 do + local acc = 0 + local b = off + i + 1 + for j = 0, 7 do + acc += C[i + 64 * j + 1] * x[b + 64 * j] + end + y[i + 1] = acc + end + for k = 0, 31 do + local acc = 0 + local mb = k * 64 + for i = 1, 64 do + acc += M[mb + i] * y[i] + end + out[oi + k] = acc + end +end + +return Analysis diff --git a/src/Formats/audio/mp3/EncTables.luau b/src/Formats/audio/mp3/EncTables.luau new file mode 100644 index 0000000..e730723 --- /dev/null +++ b/src/Formats/audio/mp3/EncTables.luau @@ -0,0 +1,292 @@ +--!strict +-- audio/mp3/EncTables: tables for the MPEG audio encoders, from PDMP3 (public domain / unlicense, by Krister +-- Lagerstrom and contributors: licenses/PDMP3-UNLICENSE.txt), which transcribes ISO/IEC 11172-3: the synthesis window D +-- (the analysis window is C = D / 32) and the layer III Huffman code trees (the encoders derive codeword tables from +-- them). Trees use the standard's decoder layout: an entry with a high byte is a node (high byte: left offset, low +-- byte: right offset), otherwise a leaf (x << 4 | y; count1 tables: v w x y bits). +local E = {} +E.D = { + 0.000000000, -0.000015259, -0.000015259, -0.000015259, -0.000015259, -0.000015259, -0.000015259, -0.000030518, + -0.000030518, -0.000030518, -0.000030518, -0.000045776, -0.000045776, -0.000061035, -0.000061035, -0.000076294, + -0.000076294, -0.000091553, -0.000106812, -0.000106812, -0.000122070, -0.000137329, -0.000152588, -0.000167847, + -0.000198364, -0.000213623, -0.000244141, -0.000259399, -0.000289917, -0.000320435, -0.000366211, -0.000396729, + -0.000442505, -0.000473022, -0.000534058, -0.000579834, -0.000625610, -0.000686646, -0.000747681, -0.000808716, + -0.000885010, -0.000961304, -0.001037598, -0.001113892, -0.001205444, -0.001296997, -0.001388550, -0.001480103, + -0.001586914, -0.001693726, -0.001785278, -0.001907349, -0.002014160, -0.002120972, -0.002243042, -0.002349854, + -0.002456665, -0.002578735, -0.002685547, -0.002792358, -0.002899170, -0.002990723, -0.003082275, -0.003173828, + 0.003250122, 0.003326416, 0.003387451, 0.003433228, 0.003463745, 0.003479004, 0.003479004, 0.003463745, + 0.003417969, 0.003372192, 0.003280640, 0.003173828, 0.003051758, 0.002883911, 0.002700806, 0.002487183, + 0.002227783, 0.001937866, 0.001617432, 0.001266479, 0.000869751, 0.000442505, -0.000030518, -0.000549316, + -0.001098633, -0.001693726, -0.002334595, -0.003005981, -0.003723145, -0.004486084, -0.005294800, -0.006118774, + -0.007003784, -0.007919312, -0.008865356, -0.009841919, -0.010848999, -0.011886597, -0.012939453, -0.014022827, + -0.015121460, -0.016235352, -0.017349243, -0.018463135, -0.019577026, -0.020690918, -0.021789551, -0.022857666, + -0.023910522, -0.024932861, -0.025909424, -0.026840210, -0.027725220, -0.028533936, -0.029281616, -0.029937744, + -0.030532837, -0.031005859, -0.031387329, -0.031661987, -0.031814575, -0.031845093, -0.031738281, -0.031478882, + 0.031082153, 0.030517578, 0.029785156, 0.028884888, 0.027801514, 0.026535034, 0.025085449, 0.023422241, + 0.021575928, 0.019531250, 0.017257690, 0.014801025, 0.012115479, 0.009231567, 0.006134033, 0.002822876, + -0.000686646, -0.004394531, -0.008316040, -0.012420654, -0.016708374, -0.021179199, -0.025817871, -0.030609131, + -0.035552979, -0.040634155, -0.045837402, -0.051132202, -0.056533813, -0.061996460, -0.067520142, -0.073059082, + -0.078628540, -0.084182739, -0.089706421, -0.095169067, -0.100540161, -0.105819702, -0.110946655, -0.115921021, + -0.120697021, -0.125259399, -0.129562378, -0.133590698, -0.137298584, -0.140670776, -0.143676758, -0.146255493, + -0.148422241, -0.150115967, -0.151306152, -0.151962280, -0.152069092, -0.151596069, -0.150497437, -0.148773193, + -0.146362305, -0.143264771, -0.139450073, -0.134887695, -0.129577637, -0.123474121, -0.116577148, -0.108856201, + 0.100311279, 0.090927124, 0.080688477, 0.069595337, 0.057617188, 0.044784546, 0.031082153, 0.016510010, + 0.001068115, -0.015228271, -0.032379150, -0.050354004, -0.069168091, -0.088775635, -0.109161377, -0.130310059, + -0.152206421, -0.174789429, -0.198059082, -0.221984863, -0.246505737, -0.271591187, -0.297210693, -0.323318481, + -0.349868774, -0.376800537, -0.404083252, -0.431655884, -0.459472656, -0.487472534, -0.515609741, -0.543823242, + -0.572036743, -0.600219727, -0.628295898, -0.656219482, -0.683914185, -0.711318970, -0.738372803, -0.765029907, + -0.791213989, -0.816864014, -0.841949463, -0.866363525, -0.890090942, -0.913055420, -0.935195923, -0.956481934, + -0.976852417, -0.996246338, -1.014617920, -1.031936646, -1.048156738, -1.063217163, -1.077117920, -1.089782715, + -1.101211548, -1.111373901, -1.120223999, -1.127746582, -1.133926392, -1.138763428, -1.142211914, -1.144287109, + 1.144989014, 1.144287109, 1.142211914, 1.138763428, 1.133926392, 1.127746582, 1.120223999, 1.111373901, + 1.101211548, 1.089782715, 1.077117920, 1.063217163, 1.048156738, 1.031936646, 1.014617920, 0.996246338, + 0.976852417, 0.956481934, 0.935195923, 0.913055420, 0.890090942, 0.866363525, 0.841949463, 0.816864014, + 0.791213989, 0.765029907, 0.738372803, 0.711318970, 0.683914185, 0.656219482, 0.628295898, 0.600219727, + 0.572036743, 0.543823242, 0.515609741, 0.487472534, 0.459472656, 0.431655884, 0.404083252, 0.376800537, + 0.349868774, 0.323318481, 0.297210693, 0.271591187, 0.246505737, 0.221984863, 0.198059082, 0.174789429, + 0.152206421, 0.130310059, 0.109161377, 0.088775635, 0.069168091, 0.050354004, 0.032379150, 0.015228271, + -0.001068115, -0.016510010, -0.031082153, -0.044784546, -0.057617188, -0.069595337, -0.080688477, -0.090927124, + 0.100311279, 0.108856201, 0.116577148, 0.123474121, 0.129577637, 0.134887695, 0.139450073, 0.143264771, + 0.146362305, 0.148773193, 0.150497437, 0.151596069, 0.152069092, 0.151962280, 0.151306152, 0.150115967, + 0.148422241, 0.146255493, 0.143676758, 0.140670776, 0.137298584, 0.133590698, 0.129562378, 0.125259399, + 0.120697021, 0.115921021, 0.110946655, 0.105819702, 0.100540161, 0.095169067, 0.089706421, 0.084182739, + 0.078628540, 0.073059082, 0.067520142, 0.061996460, 0.056533813, 0.051132202, 0.045837402, 0.040634155, + 0.035552979, 0.030609131, 0.025817871, 0.021179199, 0.016708374, 0.012420654, 0.008316040, 0.004394531, + 0.000686646, -0.002822876, -0.006134033, -0.009231567, -0.012115479, -0.014801025, -0.017257690, -0.019531250, + -0.021575928, -0.023422241, -0.025085449, -0.026535034, -0.027801514, -0.028884888, -0.029785156, -0.030517578, + 0.031082153, 0.031478882, 0.031738281, 0.031845093, 0.031814575, 0.031661987, 0.031387329, 0.031005859, + 0.030532837, 0.029937744, 0.029281616, 0.028533936, 0.027725220, 0.026840210, 0.025909424, 0.024932861, + 0.023910522, 0.022857666, 0.021789551, 0.020690918, 0.019577026, 0.018463135, 0.017349243, 0.016235352, + 0.015121460, 0.014022827, 0.012939453, 0.011886597, 0.010848999, 0.009841919, 0.008865356, 0.007919312, + 0.007003784, 0.006118774, 0.005294800, 0.004486084, 0.003723145, 0.003005981, 0.002334595, 0.001693726, + 0.001098633, 0.000549316, 0.000030518, -0.000442505, -0.000869751, -0.001266479, -0.001617432, -0.001937866, + -0.002227783, -0.002487183, -0.002700806, -0.002883911, -0.003051758, -0.003173828, -0.003280640, -0.003372192, + -0.003417969, -0.003463745, -0.003479004, -0.003479004, -0.003463745, -0.003433228, -0.003387451, -0.003326416, + 0.003250122, 0.003173828, 0.003082275, 0.002990723, 0.002899170, 0.002792358, 0.002685547, 0.002578735, + 0.002456665, 0.002349854, 0.002243042, 0.002120972, 0.002014160, 0.001907349, 0.001785278, 0.001693726, + 0.001586914, 0.001480103, 0.001388550, 0.001296997, 0.001205444, 0.001113892, 0.001037598, 0.000961304, + 0.000885010, 0.000808716, 0.000747681, 0.000686646, 0.000625610, 0.000579834, 0.000534058, 0.000473022, + 0.000442505, 0.000396729, 0.000366211, 0.000320435, 0.000289917, 0.000259399, 0.000244141, 0.000213623, + 0.000198364, 0.000167847, 0.000152588, 0.000137329, 0.000122070, 0.000106812, 0.000106812, 0.000091553, + 0.000076294, 0.000076294, 0.000061035, 0.000061035, 0.000045776, 0.000045776, 0.000030518, 0.000030518, + 0.000030518, 0.000030518, 0.000015259, 0.000015259, 0.000015259, 0.000015259, 0.000015259, 0.000015259, +} +E.LINBITS = { [0] = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 8, 10, 13, 4, 5, 6, 7, 8, 9, 11, 13, 0, 0 } +-- trees by table number (tables 16..23 share 16's tree, 24..31 share 24's) +E.TREES = { + [1] = { + 0x0201, 0x0000, 0x0201, 0x0010, 0x0201, 0x0001, 0x0011, + }, + [2] = { + 0x0201, 0x0000, 0x0401, 0x0201, 0x0010, 0x0001, 0x0201, 0x0011, 0x0401, 0x0201, 0x0020, 0x0021, 0x0201, 0x0012, 0x0201, 0x0002, + 0x0022, + }, + [3] = { + 0x0401, 0x0201, 0x0000, 0x0001, 0x0201, 0x0011, 0x0201, 0x0010, 0x0401, 0x0201, 0x0020, 0x0021, 0x0201, 0x0012, 0x0201, 0x0002, + 0x0022, + }, + [5] = { + 0x0201, 0x0000, 0x0401, 0x0201, 0x0010, 0x0001, 0x0201, 0x0011, 0x0801, 0x0401, 0x0201, 0x0020, 0x0002, 0x0201, 0x0021, 0x0012, + 0x0801, 0x0401, 0x0201, 0x0022, 0x0030, 0x0201, 0x0003, 0x0013, 0x0201, 0x0031, 0x0201, 0x0032, 0x0201, 0x0023, 0x0033, + }, + [6] = { + 0x0601, 0x0401, 0x0201, 0x0000, 0x0010, 0x0011, 0x0601, 0x0201, 0x0001, 0x0201, 0x0020, 0x0021, 0x0601, 0x0201, 0x0012, 0x0201, + 0x0002, 0x0022, 0x0401, 0x0201, 0x0031, 0x0013, 0x0401, 0x0201, 0x0030, 0x0032, 0x0201, 0x0023, 0x0201, 0x0003, 0x0033, + }, + [7] = { + 0x0201, 0x0000, 0x0401, 0x0201, 0x0010, 0x0001, 0x0801, 0x0201, 0x0011, 0x0401, 0x0201, 0x0020, 0x0002, 0x0021, 0x1201, 0x0601, + 0x0201, 0x0012, 0x0201, 0x0022, 0x0030, 0x0401, 0x0201, 0x0031, 0x0013, 0x0401, 0x0201, 0x0003, 0x0032, 0x0201, 0x0023, 0x0004, + 0x0a01, 0x0401, 0x0201, 0x0040, 0x0041, 0x0201, 0x0014, 0x0201, 0x0042, 0x0024, 0x0c01, 0x0601, 0x0401, 0x0201, 0x0033, 0x0043, + 0x0050, 0x0401, 0x0201, 0x0034, 0x0005, 0x0051, 0x0601, 0x0201, 0x0015, 0x0201, 0x0052, 0x0025, 0x0401, 0x0201, 0x0044, 0x0035, + 0x0401, 0x0201, 0x0053, 0x0054, 0x0201, 0x0045, 0x0055, + }, + [8] = { + 0x0601, 0x0201, 0x0000, 0x0201, 0x0010, 0x0001, 0x0201, 0x0011, 0x0401, 0x0201, 0x0021, 0x0012, 0x0e01, 0x0401, 0x0201, 0x0020, + 0x0002, 0x0201, 0x0022, 0x0401, 0x0201, 0x0030, 0x0003, 0x0201, 0x0031, 0x0013, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0032, 0x0023, + 0x0201, 0x0040, 0x0004, 0x0201, 0x0041, 0x0201, 0x0014, 0x0042, 0x0c01, 0x0601, 0x0201, 0x0024, 0x0201, 0x0033, 0x0050, 0x0401, + 0x0201, 0x0043, 0x0034, 0x0051, 0x0601, 0x0201, 0x0015, 0x0201, 0x0005, 0x0052, 0x0601, 0x0201, 0x0025, 0x0201, 0x0044, 0x0035, + 0x0201, 0x0053, 0x0201, 0x0045, 0x0201, 0x0054, 0x0055, + }, + [9] = { + 0x0801, 0x0401, 0x0201, 0x0000, 0x0010, 0x0201, 0x0001, 0x0011, 0x0a01, 0x0401, 0x0201, 0x0020, 0x0021, 0x0201, 0x0012, 0x0201, + 0x0002, 0x0022, 0x0c01, 0x0601, 0x0401, 0x0201, 0x0030, 0x0003, 0x0031, 0x0201, 0x0013, 0x0201, 0x0032, 0x0023, 0x0c01, 0x0401, + 0x0201, 0x0041, 0x0014, 0x0401, 0x0201, 0x0040, 0x0033, 0x0201, 0x0042, 0x0024, 0x0a01, 0x0601, 0x0401, 0x0201, 0x0004, 0x0050, + 0x0043, 0x0201, 0x0034, 0x0051, 0x0801, 0x0401, 0x0201, 0x0015, 0x0052, 0x0201, 0x0025, 0x0044, 0x0601, 0x0401, 0x0201, 0x0005, + 0x0054, 0x0053, 0x0201, 0x0035, 0x0201, 0x0045, 0x0055, + }, + [10] = { + 0x0201, 0x0000, 0x0401, 0x0201, 0x0010, 0x0001, 0x0a01, 0x0201, 0x0011, 0x0401, 0x0201, 0x0020, 0x0002, 0x0201, 0x0021, 0x0012, + 0x1c01, 0x0801, 0x0401, 0x0201, 0x0022, 0x0030, 0x0201, 0x0031, 0x0013, 0x0801, 0x0401, 0x0201, 0x0003, 0x0032, 0x0201, 0x0023, + 0x0040, 0x0401, 0x0201, 0x0041, 0x0014, 0x0401, 0x0201, 0x0004, 0x0033, 0x0201, 0x0042, 0x0024, 0x1c01, 0x0a01, 0x0601, 0x0401, + 0x0201, 0x0050, 0x0005, 0x0060, 0x0201, 0x0061, 0x0016, 0x0c01, 0x0601, 0x0401, 0x0201, 0x0043, 0x0034, 0x0051, 0x0201, 0x0015, + 0x0201, 0x0052, 0x0025, 0x0401, 0x0201, 0x0026, 0x0036, 0x0071, 0x1401, 0x0801, 0x0201, 0x0017, 0x0401, 0x0201, 0x0044, 0x0053, + 0x0006, 0x0601, 0x0401, 0x0201, 0x0035, 0x0045, 0x0062, 0x0201, 0x0070, 0x0201, 0x0007, 0x0064, 0x0e01, 0x0401, 0x0201, 0x0072, + 0x0027, 0x0601, 0x0201, 0x0063, 0x0201, 0x0054, 0x0055, 0x0201, 0x0046, 0x0073, 0x0801, 0x0401, 0x0201, 0x0037, 0x0065, 0x0201, + 0x0056, 0x0074, 0x0601, 0x0201, 0x0047, 0x0201, 0x0066, 0x0075, 0x0401, 0x0201, 0x0057, 0x0076, 0x0201, 0x0067, 0x0077, + }, + [11] = { + 0x0601, 0x0201, 0x0000, 0x0201, 0x0010, 0x0001, 0x0801, 0x0201, 0x0011, 0x0401, 0x0201, 0x0020, 0x0002, 0x0012, 0x1801, 0x0801, + 0x0201, 0x0021, 0x0201, 0x0022, 0x0201, 0x0030, 0x0003, 0x0401, 0x0201, 0x0031, 0x0013, 0x0401, 0x0201, 0x0032, 0x0023, 0x0401, + 0x0201, 0x0040, 0x0004, 0x0201, 0x0041, 0x0014, 0x1e01, 0x1001, 0x0a01, 0x0401, 0x0201, 0x0042, 0x0024, 0x0401, 0x0201, 0x0033, + 0x0043, 0x0050, 0x0401, 0x0201, 0x0034, 0x0051, 0x0061, 0x0601, 0x0201, 0x0016, 0x0201, 0x0006, 0x0026, 0x0201, 0x0062, 0x0201, + 0x0015, 0x0201, 0x0005, 0x0052, 0x1001, 0x0a01, 0x0601, 0x0401, 0x0201, 0x0025, 0x0044, 0x0060, 0x0201, 0x0063, 0x0036, 0x0401, + 0x0201, 0x0070, 0x0017, 0x0071, 0x1001, 0x0601, 0x0401, 0x0201, 0x0007, 0x0064, 0x0072, 0x0201, 0x0027, 0x0401, 0x0201, 0x0053, + 0x0035, 0x0201, 0x0054, 0x0045, 0x0a01, 0x0401, 0x0201, 0x0046, 0x0073, 0x0201, 0x0037, 0x0201, 0x0065, 0x0056, 0x0a01, 0x0601, + 0x0401, 0x0201, 0x0055, 0x0057, 0x0074, 0x0201, 0x0047, 0x0066, 0x0401, 0x0201, 0x0075, 0x0076, 0x0201, 0x0067, 0x0077, + }, + [12] = { + 0x0c01, 0x0401, 0x0201, 0x0010, 0x0001, 0x0201, 0x0011, 0x0201, 0x0000, 0x0201, 0x0020, 0x0002, 0x1001, 0x0401, 0x0201, 0x0021, + 0x0012, 0x0401, 0x0201, 0x0022, 0x0031, 0x0201, 0x0013, 0x0201, 0x0030, 0x0201, 0x0003, 0x0040, 0x1a01, 0x0801, 0x0401, 0x0201, + 0x0032, 0x0023, 0x0201, 0x0041, 0x0033, 0x0a01, 0x0401, 0x0201, 0x0014, 0x0042, 0x0201, 0x0024, 0x0201, 0x0004, 0x0050, 0x0401, + 0x0201, 0x0043, 0x0034, 0x0201, 0x0051, 0x0015, 0x1c01, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0052, 0x0025, 0x0201, 0x0053, 0x0035, + 0x0401, 0x0201, 0x0060, 0x0016, 0x0061, 0x0401, 0x0201, 0x0062, 0x0026, 0x0601, 0x0401, 0x0201, 0x0005, 0x0006, 0x0044, 0x0201, + 0x0054, 0x0045, 0x1201, 0x0a01, 0x0401, 0x0201, 0x0063, 0x0036, 0x0401, 0x0201, 0x0070, 0x0007, 0x0071, 0x0401, 0x0201, 0x0017, + 0x0064, 0x0201, 0x0046, 0x0072, 0x0a01, 0x0601, 0x0201, 0x0027, 0x0201, 0x0055, 0x0073, 0x0201, 0x0037, 0x0056, 0x0801, 0x0401, + 0x0201, 0x0065, 0x0074, 0x0201, 0x0047, 0x0066, 0x0401, 0x0201, 0x0075, 0x0057, 0x0201, 0x0076, 0x0201, 0x0067, 0x0077, + }, + [13] = { + 0x0201, 0x0000, 0x0601, 0x0201, 0x0010, 0x0201, 0x0001, 0x0011, 0x1c01, 0x0801, 0x0401, 0x0201, 0x0020, 0x0002, 0x0201, 0x0021, + 0x0012, 0x0801, 0x0401, 0x0201, 0x0022, 0x0030, 0x0201, 0x0003, 0x0031, 0x0601, 0x0201, 0x0013, 0x0201, 0x0032, 0x0023, 0x0401, + 0x0201, 0x0040, 0x0004, 0x0041, 0x4601, 0x1c01, 0x0e01, 0x0601, 0x0201, 0x0014, 0x0201, 0x0033, 0x0042, 0x0401, 0x0201, 0x0024, + 0x0050, 0x0201, 0x0043, 0x0034, 0x0401, 0x0201, 0x0051, 0x0015, 0x0401, 0x0201, 0x0005, 0x0052, 0x0201, 0x0025, 0x0201, 0x0044, + 0x0053, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0060, 0x0006, 0x0201, 0x0061, 0x0016, 0x0401, 0x0201, 0x0080, 0x0008, 0x0081, 0x1001, + 0x0801, 0x0401, 0x0201, 0x0035, 0x0062, 0x0201, 0x0026, 0x0054, 0x0401, 0x0201, 0x0045, 0x0063, 0x0201, 0x0036, 0x0070, 0x0601, + 0x0401, 0x0201, 0x0007, 0x0055, 0x0071, 0x0201, 0x0017, 0x0201, 0x0027, 0x0037, 0x4801, 0x1801, 0x0c01, 0x0401, 0x0201, 0x0018, + 0x0082, 0x0201, 0x0028, 0x0401, 0x0201, 0x0064, 0x0046, 0x0072, 0x0801, 0x0401, 0x0201, 0x0084, 0x0048, 0x0201, 0x0090, 0x0009, + 0x0201, 0x0091, 0x0019, 0x1801, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0073, 0x0065, 0x0201, 0x0056, 0x0074, 0x0401, 0x0201, 0x0047, + 0x0066, 0x0083, 0x0601, 0x0201, 0x0038, 0x0201, 0x0075, 0x0057, 0x0201, 0x0092, 0x0029, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0067, + 0x0085, 0x0201, 0x0058, 0x0039, 0x0201, 0x0093, 0x0201, 0x0049, 0x0086, 0x0601, 0x0201, 0x00a0, 0x0201, 0x0068, 0x000a, 0x0201, + 0x00a1, 0x001a, 0x4401, 0x1801, 0x0c01, 0x0401, 0x0201, 0x00a2, 0x002a, 0x0401, 0x0201, 0x0095, 0x0059, 0x0201, 0x00a3, 0x003a, + 0x0801, 0x0401, 0x0201, 0x004a, 0x0096, 0x0201, 0x00b0, 0x000b, 0x0201, 0x00b1, 0x001b, 0x1401, 0x0801, 0x0201, 0x00b2, 0x0401, + 0x0201, 0x0076, 0x0077, 0x0094, 0x0601, 0x0401, 0x0201, 0x0087, 0x0078, 0x00a4, 0x0401, 0x0201, 0x0069, 0x00a5, 0x002b, 0x0c01, + 0x0601, 0x0401, 0x0201, 0x005a, 0x0088, 0x00b3, 0x0201, 0x003b, 0x0201, 0x0079, 0x00a6, 0x0601, 0x0401, 0x0201, 0x006a, 0x00b4, + 0x00c0, 0x0401, 0x0201, 0x000c, 0x0098, 0x00c1, 0x3c01, 0x1601, 0x0a01, 0x0601, 0x0201, 0x001c, 0x0201, 0x0089, 0x00b5, 0x0201, + 0x005b, 0x00c2, 0x0401, 0x0201, 0x002c, 0x003c, 0x0401, 0x0201, 0x00b6, 0x006b, 0x0201, 0x00c4, 0x004c, 0x1001, 0x0801, 0x0401, + 0x0201, 0x00a8, 0x008a, 0x0201, 0x00d0, 0x000d, 0x0201, 0x00d1, 0x0201, 0x004b, 0x0201, 0x0097, 0x00a7, 0x0c01, 0x0601, 0x0201, + 0x00c3, 0x0201, 0x007a, 0x0099, 0x0401, 0x0201, 0x00c5, 0x005c, 0x00b7, 0x0401, 0x0201, 0x001d, 0x00d2, 0x0201, 0x002d, 0x0201, + 0x007b, 0x00d3, 0x3401, 0x1c01, 0x0c01, 0x0401, 0x0201, 0x003d, 0x00c6, 0x0401, 0x0201, 0x006c, 0x00a9, 0x0201, 0x009a, 0x00d4, + 0x0801, 0x0401, 0x0201, 0x00b8, 0x008b, 0x0201, 0x004d, 0x00c7, 0x0401, 0x0201, 0x007c, 0x00d5, 0x0201, 0x005d, 0x00e0, 0x0a01, + 0x0401, 0x0201, 0x00e1, 0x001e, 0x0401, 0x0201, 0x000e, 0x002e, 0x00e2, 0x0801, 0x0401, 0x0201, 0x00e3, 0x006d, 0x0201, 0x008c, + 0x00e4, 0x0401, 0x0201, 0x00e5, 0x00ba, 0x00f0, 0x2601, 0x1001, 0x0401, 0x0201, 0x00f1, 0x001f, 0x0601, 0x0401, 0x0201, 0x00aa, + 0x009b, 0x00b9, 0x0201, 0x003e, 0x0201, 0x00d6, 0x00c8, 0x0c01, 0x0601, 0x0201, 0x004e, 0x0201, 0x00d7, 0x007d, 0x0201, 0x00ab, + 0x0201, 0x005e, 0x00c9, 0x0601, 0x0201, 0x000f, 0x0201, 0x009c, 0x006e, 0x0201, 0x00f2, 0x002f, 0x2001, 0x1001, 0x0601, 0x0401, + 0x0201, 0x00d8, 0x008d, 0x003f, 0x0601, 0x0201, 0x00f3, 0x0201, 0x00e6, 0x00ca, 0x0201, 0x00f4, 0x004f, 0x0801, 0x0401, 0x0201, + 0x00bb, 0x00ac, 0x0201, 0x00e7, 0x00f5, 0x0401, 0x0201, 0x00d9, 0x009d, 0x0201, 0x005f, 0x00e8, 0x1e01, 0x0c01, 0x0601, 0x0201, + 0x006f, 0x0201, 0x00f6, 0x00cb, 0x0401, 0x0201, 0x00bc, 0x00ad, 0x00da, 0x0801, 0x0201, 0x00f7, 0x0401, 0x0201, 0x007e, 0x007f, + 0x008e, 0x0601, 0x0401, 0x0201, 0x009e, 0x00ae, 0x00cc, 0x0201, 0x00f8, 0x008f, 0x1201, 0x0801, 0x0401, 0x0201, 0x00db, 0x00bd, + 0x0201, 0x00ea, 0x00f9, 0x0401, 0x0201, 0x009f, 0x00eb, 0x0201, 0x00be, 0x0201, 0x00cd, 0x00fa, 0x0e01, 0x0401, 0x0201, 0x00dd, + 0x00ec, 0x0601, 0x0401, 0x0201, 0x00e9, 0x00af, 0x00dc, 0x0201, 0x00ce, 0x00fb, 0x0801, 0x0401, 0x0201, 0x00bf, 0x00de, 0x0201, + 0x00cf, 0x00ee, 0x0401, 0x0201, 0x00df, 0x00ef, 0x0201, 0x00ff, 0x0201, 0x00ed, 0x0201, 0x00fd, 0x0201, 0x00fc, 0x00fe, + }, + [15] = { + 0x1001, 0x0601, 0x0201, 0x0000, 0x0201, 0x0010, 0x0001, 0x0201, 0x0011, 0x0401, 0x0201, 0x0020, 0x0002, 0x0201, 0x0021, 0x0012, + 0x3201, 0x1001, 0x0601, 0x0201, 0x0022, 0x0201, 0x0030, 0x0031, 0x0601, 0x0201, 0x0013, 0x0201, 0x0003, 0x0040, 0x0201, 0x0032, + 0x0023, 0x0e01, 0x0601, 0x0401, 0x0201, 0x0004, 0x0014, 0x0041, 0x0401, 0x0201, 0x0033, 0x0042, 0x0201, 0x0024, 0x0043, 0x0a01, + 0x0601, 0x0201, 0x0034, 0x0201, 0x0050, 0x0005, 0x0201, 0x0051, 0x0015, 0x0401, 0x0201, 0x0052, 0x0025, 0x0401, 0x0201, 0x0044, + 0x0053, 0x0061, 0x5a01, 0x2401, 0x1201, 0x0a01, 0x0601, 0x0201, 0x0035, 0x0201, 0x0060, 0x0006, 0x0201, 0x0016, 0x0062, 0x0401, + 0x0201, 0x0026, 0x0054, 0x0201, 0x0045, 0x0063, 0x0a01, 0x0601, 0x0201, 0x0036, 0x0201, 0x0070, 0x0007, 0x0201, 0x0071, 0x0055, + 0x0401, 0x0201, 0x0017, 0x0064, 0x0201, 0x0072, 0x0027, 0x1801, 0x1001, 0x0801, 0x0401, 0x0201, 0x0046, 0x0073, 0x0201, 0x0037, + 0x0065, 0x0401, 0x0201, 0x0056, 0x0080, 0x0201, 0x0008, 0x0074, 0x0401, 0x0201, 0x0081, 0x0018, 0x0201, 0x0082, 0x0028, 0x1001, + 0x0801, 0x0401, 0x0201, 0x0047, 0x0066, 0x0201, 0x0083, 0x0038, 0x0401, 0x0201, 0x0075, 0x0057, 0x0201, 0x0084, 0x0048, 0x0601, + 0x0401, 0x0201, 0x0090, 0x0019, 0x0091, 0x0401, 0x0201, 0x0092, 0x0076, 0x0201, 0x0067, 0x0029, 0x5c01, 0x2401, 0x1201, 0x0a01, + 0x0401, 0x0201, 0x0085, 0x0058, 0x0401, 0x0201, 0x0009, 0x0077, 0x0093, 0x0401, 0x0201, 0x0039, 0x0094, 0x0201, 0x0049, 0x0086, + 0x0a01, 0x0601, 0x0201, 0x0068, 0x0201, 0x00a0, 0x000a, 0x0201, 0x00a1, 0x001a, 0x0401, 0x0201, 0x00a2, 0x002a, 0x0201, 0x0095, + 0x0059, 0x1a01, 0x0e01, 0x0601, 0x0201, 0x00a3, 0x0201, 0x003a, 0x0087, 0x0401, 0x0201, 0x0078, 0x00a4, 0x0201, 0x004a, 0x0096, + 0x0601, 0x0401, 0x0201, 0x0069, 0x00b0, 0x00b1, 0x0401, 0x0201, 0x001b, 0x00a5, 0x00b2, 0x0e01, 0x0801, 0x0401, 0x0201, 0x005a, + 0x002b, 0x0201, 0x0088, 0x0097, 0x0201, 0x00b3, 0x0201, 0x0079, 0x003b, 0x0801, 0x0401, 0x0201, 0x006a, 0x00b4, 0x0201, 0x004b, + 0x00c1, 0x0401, 0x0201, 0x0098, 0x0089, 0x0201, 0x001c, 0x00b5, 0x5001, 0x2201, 0x1001, 0x0601, 0x0401, 0x0201, 0x005b, 0x002c, + 0x00c2, 0x0601, 0x0401, 0x0201, 0x000b, 0x00c0, 0x00a6, 0x0201, 0x00a7, 0x007a, 0x0a01, 0x0401, 0x0201, 0x00c3, 0x003c, 0x0401, + 0x0201, 0x000c, 0x0099, 0x00b6, 0x0401, 0x0201, 0x006b, 0x00c4, 0x0201, 0x004c, 0x00a8, 0x1401, 0x0a01, 0x0401, 0x0201, 0x008a, + 0x00c5, 0x0401, 0x0201, 0x00d0, 0x005c, 0x00d1, 0x0401, 0x0201, 0x00b7, 0x007b, 0x0201, 0x001d, 0x0201, 0x000d, 0x002d, 0x0c01, + 0x0401, 0x0201, 0x00d2, 0x00d3, 0x0401, 0x0201, 0x003d, 0x00c6, 0x0201, 0x006c, 0x00a9, 0x0601, 0x0401, 0x0201, 0x009a, 0x00b8, + 0x00d4, 0x0401, 0x0201, 0x008b, 0x004d, 0x0201, 0x00c7, 0x007c, 0x4401, 0x2201, 0x1201, 0x0a01, 0x0401, 0x0201, 0x00d5, 0x005d, + 0x0401, 0x0201, 0x00e0, 0x000e, 0x00e1, 0x0401, 0x0201, 0x001e, 0x00e2, 0x0201, 0x00aa, 0x002e, 0x0801, 0x0401, 0x0201, 0x00b9, + 0x009b, 0x0201, 0x00e3, 0x00d6, 0x0401, 0x0201, 0x006d, 0x003e, 0x0201, 0x00c8, 0x008c, 0x1001, 0x0801, 0x0401, 0x0201, 0x00e4, + 0x004e, 0x0201, 0x00d7, 0x007d, 0x0401, 0x0201, 0x00e5, 0x00ba, 0x0201, 0x00ab, 0x005e, 0x0801, 0x0401, 0x0201, 0x00c9, 0x009c, + 0x0201, 0x00f1, 0x001f, 0x0601, 0x0401, 0x0201, 0x00f0, 0x006e, 0x00f2, 0x0201, 0x002f, 0x00e6, 0x2601, 0x1201, 0x0801, 0x0401, + 0x0201, 0x00d8, 0x00f3, 0x0201, 0x003f, 0x00f4, 0x0601, 0x0201, 0x004f, 0x0201, 0x008d, 0x00d9, 0x0201, 0x00bb, 0x00ca, 0x0801, + 0x0401, 0x0201, 0x00ac, 0x00e7, 0x0201, 0x007e, 0x00f5, 0x0801, 0x0401, 0x0201, 0x009d, 0x005f, 0x0201, 0x00e8, 0x008e, 0x0201, + 0x00f6, 0x00cb, 0x2201, 0x1201, 0x0a01, 0x0601, 0x0401, 0x0201, 0x000f, 0x00ae, 0x006f, 0x0201, 0x00bc, 0x00da, 0x0401, 0x0201, + 0x00ad, 0x00f7, 0x0201, 0x007f, 0x00e9, 0x0801, 0x0401, 0x0201, 0x009e, 0x00cc, 0x0201, 0x00f8, 0x008f, 0x0401, 0x0201, 0x00db, + 0x00bd, 0x0201, 0x00ea, 0x00f9, 0x1001, 0x0801, 0x0401, 0x0201, 0x009f, 0x00dc, 0x0201, 0x00cd, 0x00eb, 0x0401, 0x0201, 0x00be, + 0x00fa, 0x0201, 0x00af, 0x00dd, 0x0e01, 0x0601, 0x0401, 0x0201, 0x00ec, 0x00ce, 0x00fb, 0x0401, 0x0201, 0x00bf, 0x00ed, 0x0201, + 0x00de, 0x00fc, 0x0601, 0x0401, 0x0201, 0x00cf, 0x00fd, 0x00ee, 0x0401, 0x0201, 0x00df, 0x00fe, 0x0201, 0x00ef, 0x00ff, + }, + [16] = { + 0x0201, 0x0000, 0x0601, 0x0201, 0x0010, 0x0201, 0x0001, 0x0011, 0x2a01, 0x0801, 0x0401, 0x0201, 0x0020, 0x0002, 0x0201, 0x0021, + 0x0012, 0x0a01, 0x0601, 0x0201, 0x0022, 0x0201, 0x0030, 0x0003, 0x0201, 0x0031, 0x0013, 0x0a01, 0x0401, 0x0201, 0x0032, 0x0023, + 0x0401, 0x0201, 0x0040, 0x0004, 0x0041, 0x0601, 0x0201, 0x0014, 0x0201, 0x0033, 0x0042, 0x0401, 0x0201, 0x0024, 0x0050, 0x0201, + 0x0043, 0x0034, 0x8a01, 0x2801, 0x1001, 0x0601, 0x0401, 0x0201, 0x0005, 0x0015, 0x0051, 0x0401, 0x0201, 0x0052, 0x0025, 0x0401, + 0x0201, 0x0044, 0x0035, 0x0053, 0x0a01, 0x0601, 0x0401, 0x0201, 0x0060, 0x0006, 0x0061, 0x0201, 0x0016, 0x0062, 0x0801, 0x0401, + 0x0201, 0x0026, 0x0054, 0x0201, 0x0045, 0x0063, 0x0401, 0x0201, 0x0036, 0x0070, 0x0071, 0x2801, 0x1201, 0x0801, 0x0201, 0x0017, + 0x0201, 0x0007, 0x0201, 0x0055, 0x0064, 0x0401, 0x0201, 0x0072, 0x0027, 0x0401, 0x0201, 0x0046, 0x0065, 0x0073, 0x0a01, 0x0601, + 0x0201, 0x0037, 0x0201, 0x0056, 0x0008, 0x0201, 0x0080, 0x0081, 0x0601, 0x0201, 0x0018, 0x0201, 0x0074, 0x0047, 0x0201, 0x0082, + 0x0201, 0x0028, 0x0066, 0x1801, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0083, 0x0038, 0x0201, 0x0075, 0x0084, 0x0401, 0x0201, 0x0048, + 0x0090, 0x0091, 0x0601, 0x0201, 0x0019, 0x0201, 0x0009, 0x0076, 0x0201, 0x0092, 0x0029, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0085, + 0x0058, 0x0201, 0x0093, 0x0039, 0x0401, 0x0201, 0x00a0, 0x000a, 0x001a, 0x0801, 0x0201, 0x00a2, 0x0201, 0x0067, 0x0201, 0x0057, + 0x0049, 0x0601, 0x0201, 0x0094, 0x0201, 0x0077, 0x0086, 0x0201, 0x00a1, 0x0201, 0x0068, 0x0095, 0xdc01, 0x7e01, 0x3201, 0x1a01, + 0x0c01, 0x0601, 0x0201, 0x002a, 0x0201, 0x0059, 0x003a, 0x0201, 0x00a3, 0x0201, 0x0087, 0x0078, 0x0801, 0x0401, 0x0201, 0x00a4, + 0x004a, 0x0201, 0x0096, 0x0069, 0x0401, 0x0201, 0x00b0, 0x000b, 0x00b1, 0x0a01, 0x0401, 0x0201, 0x001b, 0x00b2, 0x0201, 0x002b, + 0x0201, 0x00a5, 0x005a, 0x0601, 0x0201, 0x00b3, 0x0201, 0x00a6, 0x006a, 0x0401, 0x0201, 0x00b4, 0x004b, 0x0201, 0x000c, 0x00c1, + 0x1e01, 0x0e01, 0x0601, 0x0401, 0x0201, 0x00b5, 0x00c2, 0x002c, 0x0401, 0x0201, 0x00a7, 0x00c3, 0x0201, 0x006b, 0x00c4, 0x0801, + 0x0201, 0x001d, 0x0401, 0x0201, 0x0088, 0x0097, 0x003b, 0x0401, 0x0201, 0x00d1, 0x00d2, 0x0201, 0x002d, 0x00d3, 0x1201, 0x0601, + 0x0401, 0x0201, 0x001e, 0x002e, 0x00e2, 0x0601, 0x0401, 0x0201, 0x0079, 0x0098, 0x00c0, 0x0201, 0x001c, 0x0201, 0x0089, 0x005b, + 0x0e01, 0x0601, 0x0201, 0x003c, 0x0201, 0x007a, 0x00b6, 0x0401, 0x0201, 0x004c, 0x0099, 0x0201, 0x00a8, 0x008a, 0x0601, 0x0201, + 0x000d, 0x0201, 0x00c5, 0x005c, 0x0401, 0x0201, 0x003d, 0x00c6, 0x0201, 0x006c, 0x009a, 0x5801, 0x5601, 0x2401, 0x1001, 0x0801, + 0x0401, 0x0201, 0x008b, 0x004d, 0x0201, 0x00c7, 0x007c, 0x0401, 0x0201, 0x00d5, 0x005d, 0x0201, 0x00e0, 0x000e, 0x0801, 0x0201, + 0x00e3, 0x0401, 0x0201, 0x00d0, 0x00b7, 0x007b, 0x0601, 0x0401, 0x0201, 0x00a9, 0x00b8, 0x00d4, 0x0201, 0x00e1, 0x0201, 0x00aa, + 0x00b9, 0x1801, 0x0a01, 0x0601, 0x0401, 0x0201, 0x009b, 0x00d6, 0x006d, 0x0201, 0x003e, 0x00c8, 0x0601, 0x0401, 0x0201, 0x008c, + 0x00e4, 0x004e, 0x0401, 0x0201, 0x00d7, 0x00e5, 0x0201, 0x00ba, 0x00ab, 0x0c01, 0x0401, 0x0201, 0x009c, 0x00e6, 0x0401, 0x0201, + 0x006e, 0x00d8, 0x0201, 0x008d, 0x00bb, 0x0801, 0x0401, 0x0201, 0x00e7, 0x009d, 0x0201, 0x00e8, 0x008e, 0x0401, 0x0201, 0x00cb, + 0x00bc, 0x009e, 0x00f1, 0x0201, 0x001f, 0x0201, 0x000f, 0x002f, 0x4201, 0x3801, 0x0201, 0x00f2, 0x3401, 0x3201, 0x1401, 0x0801, + 0x0201, 0x00bd, 0x0201, 0x005e, 0x0201, 0x007d, 0x00c9, 0x0601, 0x0201, 0x00ca, 0x0201, 0x00ac, 0x007e, 0x0401, 0x0201, 0x00da, + 0x00ad, 0x00cc, 0x0a01, 0x0601, 0x0201, 0x00ae, 0x0201, 0x00db, 0x00dc, 0x0201, 0x00cd, 0x00be, 0x0601, 0x0401, 0x0201, 0x00eb, + 0x00ed, 0x00ee, 0x0601, 0x0401, 0x0201, 0x00d9, 0x00ea, 0x00e9, 0x0201, 0x00de, 0x0401, 0x0201, 0x00dd, 0x00ec, 0x00ce, 0x003f, + 0x00f0, 0x0401, 0x0201, 0x00f3, 0x00f4, 0x0201, 0x004f, 0x0201, 0x00f5, 0x005f, 0x0a01, 0x0201, 0x00ff, 0x0401, 0x0201, 0x00f6, + 0x006f, 0x0201, 0x00f7, 0x007f, 0x0c01, 0x0601, 0x0201, 0x008f, 0x0201, 0x00f8, 0x00f9, 0x0401, 0x0201, 0x009f, 0x00fa, 0x00af, + 0x0801, 0x0401, 0x0201, 0x00fb, 0x00bf, 0x0201, 0x00fc, 0x00cf, 0x0401, 0x0201, 0x00fd, 0x00df, 0x0201, 0x00fe, 0x00ef, + }, + [24] = { + 0x3c01, 0x0801, 0x0401, 0x0201, 0x0000, 0x0010, 0x0201, 0x0001, 0x0011, 0x0e01, 0x0601, 0x0401, 0x0201, 0x0020, 0x0002, 0x0021, + 0x0201, 0x0012, 0x0201, 0x0022, 0x0201, 0x0030, 0x0003, 0x0e01, 0x0401, 0x0201, 0x0031, 0x0013, 0x0401, 0x0201, 0x0032, 0x0023, + 0x0401, 0x0201, 0x0040, 0x0004, 0x0041, 0x0801, 0x0401, 0x0201, 0x0014, 0x0033, 0x0201, 0x0042, 0x0024, 0x0601, 0x0401, 0x0201, + 0x0043, 0x0034, 0x0051, 0x0601, 0x0401, 0x0201, 0x0050, 0x0005, 0x0015, 0x0201, 0x0052, 0x0025, 0xfa01, 0x6201, 0x2201, 0x1201, + 0x0a01, 0x0401, 0x0201, 0x0044, 0x0053, 0x0201, 0x0035, 0x0201, 0x0060, 0x0006, 0x0401, 0x0201, 0x0061, 0x0016, 0x0201, 0x0062, + 0x0026, 0x0801, 0x0401, 0x0201, 0x0054, 0x0045, 0x0201, 0x0063, 0x0036, 0x0401, 0x0201, 0x0071, 0x0055, 0x0201, 0x0064, 0x0046, + 0x2001, 0x0e01, 0x0601, 0x0201, 0x0072, 0x0201, 0x0027, 0x0037, 0x0201, 0x0073, 0x0401, 0x0201, 0x0070, 0x0007, 0x0017, 0x0a01, + 0x0401, 0x0201, 0x0065, 0x0056, 0x0401, 0x0201, 0x0080, 0x0008, 0x0081, 0x0401, 0x0201, 0x0074, 0x0047, 0x0201, 0x0018, 0x0082, + 0x1001, 0x0801, 0x0401, 0x0201, 0x0028, 0x0066, 0x0201, 0x0083, 0x0038, 0x0401, 0x0201, 0x0075, 0x0057, 0x0201, 0x0084, 0x0048, + 0x0801, 0x0401, 0x0201, 0x0091, 0x0019, 0x0201, 0x0092, 0x0076, 0x0401, 0x0201, 0x0067, 0x0029, 0x0201, 0x0085, 0x0058, 0x5c01, + 0x2201, 0x1001, 0x0801, 0x0401, 0x0201, 0x0093, 0x0039, 0x0201, 0x0094, 0x0049, 0x0401, 0x0201, 0x0077, 0x0086, 0x0201, 0x0068, + 0x00a1, 0x0801, 0x0401, 0x0201, 0x00a2, 0x002a, 0x0201, 0x0095, 0x0059, 0x0401, 0x0201, 0x00a3, 0x003a, 0x0201, 0x0087, 0x0201, + 0x0078, 0x004a, 0x1601, 0x0c01, 0x0401, 0x0201, 0x00a4, 0x0096, 0x0401, 0x0201, 0x0069, 0x00b1, 0x0201, 0x001b, 0x00a5, 0x0601, + 0x0201, 0x00b2, 0x0201, 0x005a, 0x002b, 0x0201, 0x0088, 0x00b3, 0x1001, 0x0a01, 0x0601, 0x0201, 0x0090, 0x0201, 0x0009, 0x00a0, + 0x0201, 0x0097, 0x0079, 0x0401, 0x0201, 0x00a6, 0x006a, 0x00b4, 0x0c01, 0x0601, 0x0201, 0x001a, 0x0201, 0x000a, 0x00b0, 0x0201, + 0x003b, 0x0201, 0x000b, 0x00c0, 0x0401, 0x0201, 0x004b, 0x00c1, 0x0201, 0x0098, 0x0089, 0x4301, 0x2201, 0x1001, 0x0801, 0x0401, + 0x0201, 0x001c, 0x00b5, 0x0201, 0x005b, 0x00c2, 0x0401, 0x0201, 0x002c, 0x00a7, 0x0201, 0x007a, 0x00c3, 0x0a01, 0x0601, 0x0201, + 0x003c, 0x0201, 0x000c, 0x00d0, 0x0201, 0x00b6, 0x006b, 0x0401, 0x0201, 0x00c4, 0x004c, 0x0201, 0x0099, 0x00a8, 0x1001, 0x0801, + 0x0401, 0x0201, 0x008a, 0x00c5, 0x0201, 0x005c, 0x00d1, 0x0401, 0x0201, 0x00b7, 0x007b, 0x0201, 0x001d, 0x00d2, 0x0901, 0x0401, + 0x0201, 0x002d, 0x00d3, 0x0201, 0x003d, 0x00c6, 0x55fa, 0x0401, 0x0201, 0x006c, 0x00a9, 0x0201, 0x009a, 0x00d4, 0x2001, 0x1001, + 0x0801, 0x0401, 0x0201, 0x00b8, 0x008b, 0x0201, 0x004d, 0x00c7, 0x0401, 0x0201, 0x007c, 0x00d5, 0x0201, 0x005d, 0x00e1, 0x0801, + 0x0401, 0x0201, 0x001e, 0x00e2, 0x0201, 0x00aa, 0x00b9, 0x0401, 0x0201, 0x009b, 0x00e3, 0x0201, 0x00d6, 0x006d, 0x1401, 0x0a01, + 0x0601, 0x0201, 0x003e, 0x0201, 0x002e, 0x004e, 0x0201, 0x00c8, 0x008c, 0x0401, 0x0201, 0x00e4, 0x00d7, 0x0401, 0x0201, 0x007d, + 0x00ab, 0x00e5, 0x0a01, 0x0401, 0x0201, 0x00ba, 0x005e, 0x0201, 0x00c9, 0x0201, 0x009c, 0x006e, 0x0801, 0x0201, 0x00e6, 0x0201, + 0x000d, 0x0201, 0x00e0, 0x000e, 0x0401, 0x0201, 0x00d8, 0x008d, 0x0201, 0x00bb, 0x00ca, 0x4a01, 0x0201, 0x00ff, 0x4001, 0x3a01, + 0x2001, 0x1001, 0x0801, 0x0401, 0x0201, 0x00ac, 0x00e7, 0x0201, 0x007e, 0x00d9, 0x0401, 0x0201, 0x009d, 0x00e8, 0x0201, 0x008e, + 0x00cb, 0x0801, 0x0401, 0x0201, 0x00bc, 0x00da, 0x0201, 0x00ad, 0x00e9, 0x0401, 0x0201, 0x009e, 0x00cc, 0x0201, 0x00db, 0x00bd, + 0x1001, 0x0801, 0x0401, 0x0201, 0x00ea, 0x00ae, 0x0201, 0x00dc, 0x00cd, 0x0401, 0x0201, 0x00eb, 0x00be, 0x0201, 0x00dd, 0x00ec, + 0x0801, 0x0401, 0x0201, 0x00ce, 0x00ed, 0x0201, 0x00de, 0x00ee, 0x000f, 0x0401, 0x0201, 0x00f0, 0x001f, 0x00f1, 0x0401, 0x0201, + 0x00f2, 0x002f, 0x0201, 0x00f3, 0x003f, 0x1201, 0x0801, 0x0401, 0x0201, 0x00f4, 0x004f, 0x0201, 0x00f5, 0x005f, 0x0401, 0x0201, + 0x00f6, 0x006f, 0x0201, 0x00f7, 0x0201, 0x007f, 0x008f, 0x0a01, 0x0401, 0x0201, 0x00f8, 0x00f9, 0x0401, 0x0201, 0x009f, 0x00af, + 0x00fa, 0x0801, 0x0401, 0x0201, 0x00fb, 0x00bf, 0x0201, 0x00fc, 0x00cf, 0x0401, 0x0201, 0x00fd, 0x00df, 0x0201, 0x00fe, 0x00ef, + }, + [32] = { + 0x0201, 0x0000, 0x0801, 0x0401, 0x0201, 0x0008, 0x0004, 0x0201, 0x0001, 0x0002, 0x0801, 0x0401, 0x0201, 0x000c, 0x000a, 0x0201, + 0x0003, 0x0006, 0x0601, 0x0201, 0x0009, 0x0201, 0x0005, 0x0007, 0x0401, 0x0201, 0x000e, 0x000d, 0x0201, 0x000f, 0x000b, + }, + [33] = { + 0x1001, 0x0801, 0x0401, 0x0201, 0x0000, 0x0001, 0x0201, 0x0002, 0x0003, 0x0401, 0x0201, 0x0004, 0x0005, 0x0201, 0x0006, 0x0007, + 0x0801, 0x0401, 0x0201, 0x0008, 0x0009, 0x0201, 0x000a, 0x000b, 0x0401, 0x0201, 0x000c, 0x000d, 0x0201, 0x000e, 0x000f, + }, +} +return E diff --git a/src/Formats/audio/mp3/Encode2.luau b/src/Formats/audio/mp3/Encode2.luau new file mode 100644 index 0000000..0a6af36 --- /dev/null +++ b/src/Formats/audio/mp3/Encode2.luau @@ -0,0 +1,407 @@ +--!strict +--!native +--!optimize 2 +-- audio/mp3/Encode2: an MPEG audio layer II (MP2) encoder: constant bit rate, MPEG-1 (32 / 44.1 / 48 kHz) and MPEG-2 +-- low sampling frequencies (16 / 22.05 / 24 kHz), mono or stereo. New code written from ISO/IEC 11172-3 (2.4.2.3, +-- C.1.5.2): the polyphase analysis (audio/mp3/Analysis), one scalefactor per 12-sample part (scfsi 0: all three are +-- sent), the standard bit allocation tables (in minimp3's compact form, CC0: licenses/minimp3-CC0.txt, as the decoder +-- in this folder reads them), a greedy allocation that always gives the next step to the band with the most noise +-- (signal level minus the quantizer's SNR; no psychoacoustic model), uniform midtread quantization and grouping of +-- 3 / 5 / 9-level samples. Never throws. +local T = require("@formats/audio/mp3/Tables") +local Analysis = require("@formats/audio/mp3/Analysis") + +local Encode2 = {} + +local floor, log = math.floor, math.log +local writeu8 = buffer.writeu8 + +local POW = table.create(40, 0) +for i = 0, 39 do + POW[i + 1] = 2 ^ i +end + +-- the allocation tables: { bit-allocation-code offset into g_bitalloc_code_tab, bits, band count } runs (minimp3) +local ALLOC_L2M1 = { 0, 4, 3, 16, 4, 8, 32, 3, 12, 40, 2, 7 } +local ALLOC_L2M1_LOW = { 44, 4, 2, 44, 3, 10 } +local ALLOC_L2M2 = { 60, 4, 4, 44, 3, 7, 44, 2, 19 } +local CODE = T.g_bitalloc_code_tab + +-- quantizer classes (minimp3's ba): 1..16 -> 2^ba - 1 levels in ba bits; 17 / 18 / 19 -> 3 / 5 / 9 levels grouped +local function levels(ba: number): number + if ba >= 17 then + return if ba == 17 then 3 elseif ba == 18 then 5 else 9 + end + return POW[ba + 1] - 1 +end +-- bits for the 3 samples of one granule +local function tripleBits(ba: number): number + if ba >= 17 then + return if ba == 17 then 5 elseif ba == 18 then 7 else 10 + end + return 3 * ba +end +-- the quantizer's signal-to-noise ratio in dB (ISO 11172-3 table C.5) +local SNR: { [number]: number } = {} +do + local byLevels = { + [3] = 7.00, + [5] = 11.00, + [7] = 16.00, + [9] = 20.84, + [15] = 25.28, + [31] = 31.59, + [63] = 37.75, + [127] = 43.84, + [255] = 49.89, + [511] = 55.93, + [1023] = 61.96, + [2047] = 67.98, + [4095] = 74.01, + [8191] = 80.03, + [16383] = 86.05, + [32767] = 92.01, + [65535] = 98.01, + } + for ba = 1, 19 do + SNR[ba] = byLevels[levels(ba)] or (6.02 * ba) + end +end + +-- scalefactors 2^(1 - i/3), i = 0 .. 62 +local SCF = table.create(63, 0) +for i = 0, 62 do + SCF[i + 1] = 2 ^ (1 - i / 3) +end + +local RATES = { + [44100] = { 3, 0 }, + [48000] = { 3, 1 }, + [32000] = { 3, 2 }, + [22050] = { 2, 0 }, + [24000] = { 2, 1 }, + [16000] = { 2, 2 }, +} +Encode2.RATES = RATES +local BITRATES_V1 = { 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384 } +local BITRATES_V2 = { 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160 } +Encode2.BITRATES = { [1] = BITRATES_V1, [2] = BITRATES_V2 } + +type W = { buf: buffer, pos: number, acc: number, cnt: number } +local function put(w: W, v: number, n: number) + if n == 0 then + return + end + local acc = w.acc * POW[n + 1] + v + local cnt = w.cnt + n + local b, p = w.buf, w.pos + while cnt >= 8 do + cnt -= 8 + local m = POW[cnt + 1] + local byte = floor(acc / m) + writeu8(b, p, byte) + p += 1 + acc -= byte * m + end + w.acc, w.cnt, w.pos = acc, cnt, p +end + +export type Source = { + sampleRate: number, + channels: number, + frames: number, + read: (self: any, n: number, out: buffer?) -> (buffer, number), + err: any, +} +export type Options = { bitrate: number, mode: string, prefix: buffer? } + +-- encode(src, opts) -> buffer | nil, message +function Encode2.encode(src: Source, opts: Options): (buffer?, string?) + local rate = src.sampleRate + local info = RATES[rate] + if not info then + return nil, "unsupported sample rate" + end + local version, srIndex = info[1], info[2] + local mpeg1 = version == 3 + local inCh = src.channels + local nch = if opts.mode == "mono" then 1 else 2 + local kbps = opts.bitrate + local list = if mpeg1 then BITRATES_V1 else BITRATES_V2 + local brIndex = table.find(list, kbps) + if not brIndex then + return nil, "unsupported bit rate" + end + -- the allocation table (the decoder's choice from the header) + local alloc, nbands + if not mpeg1 then + alloc, nbands = ALLOC_L2M2, 30 + else + local perCh = if nch == 2 then kbps // 2 else kbps + alloc, nbands = ALLOC_L2M1, 27 + if perCh < 56 then + alloc, nbands = ALLOC_L2M1_LOW, if srIndex == 2 then 12 else 8 + elseif perCh >= 96 and srIndex ~= 1 then + nbands = 30 + end + end + local bandOff, bandBits = table.create(nbands, 0), table.create(nbands, 0) + do + local k, ai = 0, 1 + local off, bits = 0, 0 + for i = 0, nbands - 1 do + if i == k then + off, bits, k = alloc[ai], alloc[ai + 1], k + alloc[ai + 2] + ai += 3 + end + bandOff[i + 1], bandBits[i + 1] = off, bits + end + end + -- per band: the classes it can take, in increasing order (index into the code table = the value written) + local steps: { { { number } } } = {} + for i = 1, nbands do + local s = {} + for v = 1, POW[bandBits[i] + 1] - 1 do + local ba = CODE[bandOff[i] + v] + if ba and ba > 0 then + table.insert(s, { v, ba }) + end + end + steps[i] = s + end + local w: W = { buf = buffer.create(65536), pos = 0, acc = 0, cnt = 0 } + if opts.prefix then + local pf = opts.prefix :: buffer + if buffer.len(pf) > buffer.len(w.buf) - 16 then + w.buf = buffer.create(buffer.len(pf) + 65536) + end + buffer.copy(w.buf, 0, pf, 0, buffer.len(pf)) + w.pos = buffer.len(pf) + end + local ana = { Analysis.new(), Analysis.new() } + local pcm = { table.create(1152, 0), table.create(1152, 0) } + -- subband samples: sb[c][band * 36 + t + 1], t = 0 .. 35 + local sbs = { table.create(32 * 36, 0), table.create(32 * 36, 0) } + local sub = table.create(32, 0) + local scf = { table.create(32 * 3, 0), table.create(32 * 3, 0) } -- scalefactor index per band and part + local bal = { table.create(32, 0), table.create(32, 0) } -- allocation step (0 = none) per band + local slot = 144000 * kbps + local rest = 0 + local tmp: buffer? = nil + local pending: buffer? = nil + local pendN, pendOff = 0, 0 + local srcDone, flushed = false, false + while true do + local got = 0 + while got < 1152 and not srcDone do + if pendN == 0 then + local b, n = src:read(4096, tmp) + if n <= 0 then + srcDone = true + break + end + tmp = b + pending, pendN, pendOff = b, n, 0 + end + local take = math.min(1152 - got, pendN) + local pb = pending :: buffer + for i = 0, take - 1 do + local base = (pendOff + i) * inCh * 4 + local l = buffer.readf32(pb, base) + local r = if inCh > 1 then buffer.readf32(pb, base + 4) else l + if nch == 1 then + pcm[1][got + i + 1] = if inCh > 1 then (l + r) * 0.5 else l + else + pcm[1][got + i + 1] = l + pcm[2][got + i + 1] = r + end + end + got += take + pendN -= take + pendOff += take + end + if got == 0 then + if flushed then + break + end + flushed = true + end + for c = 1, nch do + local s = pcm[c] + for i = got + 1, 1152 do + s[i] = 0 + end + local sb = sbs[c] + for t = 0, 35 do + Analysis.run(ana[c], s, t * 32 + 1, sub, 1) + for b = 0, 31 do + sb[b * 36 + t + 1] = sub[b + 1] + end + end + -- scalefactors: the smallest scalefactor (largest index) still >= the part's peak + local sc = scf[c] + for b = 0, nbands - 1 do + for part = 0, 2 do + local m = 0 + local o = b * 36 + part * 12 + for t = 1, 12 do + local v = math.abs(sb[o + t]) + if v > m then + m = v + end + end + local idx = 62 + if m > 0 then + idx = math.clamp(floor(3 * (1 - log(m) / log(2))), 0, 62) + while idx > 0 and SCF[idx + 1] < m do + idx -= 1 + end + while idx < 62 and SCF[idx + 2] >= m do + idx += 1 + end + end + sc[b * 3 + part + 1] = idx + end + end + end + -- the frame size and the bits left for scalefactors and samples + local frameBytes = slot // rate + rest += slot % rate + local padding = 0 + if rest >= rate then + rest -= rate + padding = 1 + frameBytes += 1 + end + local avail = frameBytes * 8 - 32 + for b = 1, nbands do + avail -= bandBits[b] * nch + end + -- greedy allocation: the band with the most noise gets its next step while it fits + local level = { table.create(nbands, 0), table.create(nbands, 0) } -- signal level (dB) per band + for c = 1, nch do + local sc = scf[c] + for b = 1, nbands do + local best = math.min(sc[(b - 1) * 3 + 1], sc[(b - 1) * 3 + 2], sc[(b - 1) * 3 + 3]) + level[c][b] = 20 * math.log10(SCF[best + 1]) + bal[c][b] = 0 + end + end + while true do + local bestC, bestB, bestNoise, bestCost = 0, 0, -math.huge, 0 + for c = 1, nch do + for b = 1, nbands do + local st = bal[c][b] + local s = steps[b] + if st < #s and level[c][b] > -110 then + local cur = if st == 0 then 0 else s[st][2] + local nxt = s[st + 1][2] + local noise = level[c][b] - (if st == 0 then 0 else SNR[cur]) + local cost = 12 * tripleBits(nxt) - (if st == 0 then 0 else 12 * tripleBits(cur)) + if st == 0 then + cost += 2 + 18 -- scfsi + three scalefactors + end + if cost <= avail and noise > bestNoise then + bestC, bestB, bestNoise, bestCost = c, b, noise, cost + end + end + end + end + if bestC == 0 then + break + end + bal[bestC][bestB] += 1 + avail -= bestCost + end + -- write the frame + if w.pos + frameBytes + 64 > buffer.len(w.buf) then + local nb = buffer.create(buffer.len(w.buf) * 2 + frameBytes) + buffer.copy(nb, 0, w.buf, 0, w.pos) + w.buf = nb + end + local start = w.pos + put(w, 0x7FF, 11) + put(w, version, 2) + put(w, 2, 2) -- layer II + put(w, 1, 1) -- no CRC + put(w, brIndex, 4) + put(w, srIndex, 2) + put(w, padding, 1) + put(w, 0, 1) + put(w, if nch == 1 then 3 else 0, 2) + put(w, 0, 2) + put(w, 0, 1) + put(w, 1, 1) + put(w, 0, 2) + -- bit allocation + for b = 1, nbands do + for c = 1, nch do + local st = bal[c][b] + put(w, if st == 0 then 0 else steps[b][st][1], bandBits[b]) + end + end + -- scfsi (0: three scalefactors) and the scalefactors + for b = 1, nbands do + for c = 1, nch do + if bal[c][b] > 0 then + put(w, 0, 2) + end + end + end + for b = 1, nbands do + for c = 1, nch do + if bal[c][b] > 0 then + for part = 1, 3 do + put(w, scf[c][(b - 1) * 3 + part], 6) + end + end + end + end + -- samples: 12 granules of 3, band by band, channel by channel + for gr = 0, 11 do + local part = gr // 4 + for b = 1, nbands do + for c = 1, nch do + local st = bal[c][b] + if st > 0 then + local ba = steps[b][st][2] + local L = levels(ba) + local inv = 1 / SCF[scf[c][(b - 1) * 3 + part + 1] + 1] + local o = (b - 1) * 36 + gr * 3 + local sb = sbs[c] + local q0, q1, q2 + do + local function quant(x: number): number + local q = floor((x * inv + 1) * L / 2) + return if q < 0 then 0 elseif q > L - 1 then L - 1 else q + end + q0, q1, q2 = quant(sb[o + 1]), quant(sb[o + 2]), quant(sb[o + 3]) + end + if ba >= 17 then + put(w, q0 + L * (q1 + L * q2), tripleBits(ba)) + else + put(w, q0, ba) + put(w, q1, ba) + put(w, q2, ba) + end + end + end + end + end + if w.cnt > 0 then + put(w, 0, 8 - w.cnt) + end + while w.pos < start + frameBytes do + writeu8(w.buf, w.pos, 0) + w.pos += 1 + end + end + if src.err then + return nil, tostring(src.err) + end + local out = buffer.create(w.pos) + buffer.copy(out, 0, w.buf, 0, w.pos) + return out, nil +end + +return Encode2 diff --git a/src/Formats/audio/mp3/Encode3.luau b/src/Formats/audio/mp3/Encode3.luau new file mode 100644 index 0000000..39e6dbf --- /dev/null +++ b/src/Formats/audio/mp3/Encode3.luau @@ -0,0 +1,680 @@ +--!strict +--!native +--!optimize 2 +-- audio/mp3/Encode3: an MPEG audio layer III encoder in the spirit of shine: constant bit rate, long blocks only, +-- global-gain rate control (no psychoacoustic model, scalefactors all zero), no bit reservoir (main_data_begin = 0), +-- MPEG-1 (32 / 44.1 / 48 kHz, two granules), MPEG-2 (16 / 22.05 / 24 kHz) and MPEG-2.5 (8 / 11.025 / 12 kHz), mono, +-- stereo or joint (mid / side) stereo. New code written from ISO/IEC 11172-3 / 13818-3 (no shine / LAME code): the +-- analysis filterbank (audio/mp3/Analysis), the 36-point MDCT with the sine window, the alias-reduction butterflies, +-- the x^(3/4) quantizer, big_values / count1 partitioning with per-region Huffman table choice; the Huffman codes are +-- derived from the standard's decoder trees (audio/mp3/EncTables, from PDMP3, public domain). Never throws. +local E = require("@formats/audio/mp3/EncTables") +local T = require("@formats/audio/mp3/Tables") +local Analysis = require("@formats/audio/mp3/Analysis") + +local Encode3 = {} + +local floor, sqrt, cos, pi = math.floor, math.sqrt, math.cos, math.pi +local writeu8 = buffer.writeu8 + +local POW = table.create(40, 0) +for i = 0, 39 do + POW[i + 1] = 2 ^ i +end + +-- ------------------------------------------------------------------------------------------------ Huffman codes +-- CODE[t][x * 16 + y + 1], LEN[t][...] for the pair tables 1..31 (16..23 and 24..31 share a tree); count1 tables A +-- (32) and B (33) indexed by v * 8 + w * 4 + x * 2 + y + 1 +local CODE: { [number]: { number } } = {} +local LEN: { [number]: { number } } = {} +local XLEN: { [number]: number } = {} + +local function walk(tree: { number }, codes: { number }, lens: { number }, p: number, code: number, len: number) + local v = tree[p + 1] + if bit32.band(v, 0xFF00) == 0 then + local idx = bit32.band(v, 0xFF) + 1 + if lens[idx] == 0 then + codes[idx], lens[idx] = code, len + end + return + end + -- left (bit 0): offsets of 250+ chain + local q = p + while bit32.rshift(tree[q + 1], 8) >= 250 do + q += bit32.rshift(tree[q + 1], 8) + end + q += bit32.rshift(tree[q + 1], 8) + walk(tree, codes, lens, q, code * 2, len + 1) + q = p + while bit32.band(tree[q + 1], 0xFF) >= 250 do + q += bit32.band(tree[q + 1], 0xFF) + end + q += bit32.band(tree[q + 1], 0xFF) + walk(tree, codes, lens, q, code * 2 + 1, len + 1) +end + +for t = 1, 33 do + local src = if t >= 16 and t <= 23 then 16 elseif t >= 24 and t <= 31 then 24 else t + local tree = E.TREES[src] + if tree then + local codes, lens = table.create(256, 0), table.create(256, 0) + walk(tree, codes, lens, 0, 0, 0) + -- the leaf value of pair tables is x << 4 | y: index x * 16 + y + 1 (count1: the 4-bit vwxy) + CODE[t], LEN[t] = codes, lens + local xl = 0 + for idx = 1, 256 do + if lens[idx] > 0 then + local x = (idx - 1) // 16 + if x + 1 > xl then + xl = x + 1 + end + end + end + XLEN[t] = xl + end +end +local LINBITS = E.LINBITS +-- the tables that hold values up to m (m <= 15), smallest first +local SMALL: { [number]: { number } } = {} +for m = 0, 15 do + local list = {} + for _, t in { 1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15 } do + if XLEN[t] and XLEN[t] - 1 >= m then + table.insert(list, t) + end + end + SMALL[m] = list +end + +-- ------------------------------------------------------------------------------------------------ bit writer +type W = { buf: buffer, pos: number, acc: number, cnt: number } + +local function put(w: W, v: number, n: number) + if n == 0 then + return + end + local acc = w.acc * POW[n + 1] + v + local cnt = w.cnt + n + local b, p = w.buf, w.pos + while cnt >= 8 do + cnt -= 8 + local m = POW[cnt + 1] + local byte = floor(acc / m) + writeu8(b, p, byte) + p += 1 + acc -= byte * m + end + w.acc, w.cnt, w.pos = acc, cnt, p +end +Encode3.put = put + +-- ------------------------------------------------------------------------------------------------ constants +local RATES = { + -- rate -> version bits (3 MPEG-1, 2 MPEG-2, 0 MPEG-2.5), sample rate index, scalefactor band group (g_scf_long) + [44100] = { 3, 0, 5 }, + [48000] = { 3, 1, 6 }, + [32000] = { 3, 2, 7 }, + [22050] = { 2, 0, 2 }, + [24000] = { 2, 1, 3 }, + [16000] = { 2, 2, 4 }, + [11025] = { 0, 0, 0 }, + [12000] = { 0, 1, 0 }, + [8000] = { 0, 2, 1 }, +} +Encode3.RATES = RATES +local BITRATES_V1 = { 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320 } +local BITRATES_V2 = { 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160 } +Encode3.BITRATES = { [1] = BITRATES_V1, [2] = BITRATES_V2 } + +-- the 36-point MDCT (long blocks): X[k] = 1/9 sum_i w_i z_i cos(pi/72 (2i + 19)(2k + 1)), w_i = sin(pi/36 (i + 1/2)) +local MDCT = table.create(18 * 36, 0) +for k = 0, 17 do + for i = 0, 35 do + MDCT[k * 36 + i + 1] = math.sin(pi / 36 * (i + 0.5)) * cos(pi / 72 * (2 * i + 19) * (2 * k + 1)) / 9 + end +end +-- alias reduction coefficients +local CI = { -0.6, -0.535, -0.33, -0.185, -0.095, -0.041, -0.0142, -0.0037 } +local CS, CA = table.create(8, 0), table.create(8, 0) +for i = 1, 8 do + local s = sqrt(1 + CI[i] * CI[i]) + CS[i], CA[i] = 1 / s, CI[i] / s +end + +-- ------------------------------------------------------------------------------------------------ Huffman planning +type Plan = { + bits: number, + bigValues: number, -- pairs + count1: number, -- quadruples + tables: { number }, -- 3 region tables + region0: number, + region1: number, + c1table: number, -- 0 = A (table 32), 1 = B (33) + addr1: number, -- coefficient index where region 1 starts + addr2: number, +} + +local function newPlan(): Plan + return { bits = 0, bigValues = 0, count1 = 0, tables = { 0, 0, 0 }, region0 = 0, region1 = 0, c1table = 0, addr1 = 0, addr2 = 0 } +end + +-- bits of the pairs ix[a .. b) with table t (ix 1-based: ix[i + 1] is coefficient i) +local function pairBits(ix: { number }, a: number, b: number, t: number): number + if t == 0 then + return 0 + end + local lens = LEN[t] + local lb = LINBITS[t] + local bits = 0 + for i = a, b - 1, 2 do + local x, y = ix[i + 1], ix[i + 2] + local extra = 0 + if x > 14 then + x = 15 + extra += lb + end + if y > 14 then + y = 15 + extra += lb + end + bits += lens[x * 16 + y + 1] + extra + if x ~= 0 then + bits += 1 + end + if y ~= 0 then + bits += 1 + end + end + return bits +end + +-- the best table for the pairs ix[a .. b): table, bits +local function chooseTable(ix: { number }, a: number, b: number): (number, number) + if b <= a then + return 0, 0 + end + local m = 0 + for i = a + 1, b do + local v = ix[i] + if v > m then + m = v + end + end + if m == 0 then + return 0, 0 + end + if m <= 15 then + local best, bestBits = 0, math.huge + for _, t in SMALL[m] do + local bits = pairBits(ix, a, b, t) + if bits < bestBits then + best, bestBits = t, bits + end + end + return best, bestBits + end + local need = m - 15 + local best, bestBits = 0, math.huge + for _, group in { 16, 24 } do + for t = group, group + 7 do + if POW[LINBITS[t] + 1] - 1 >= need then + local bits = pairBits(ix, a, b, t) + if bits < bestBits then + best, bestBits = t, bits + end + break + end + end + end + return best, bestBits +end + +-- plan the Huffman coding of ix (576 values, max <= 8206) into p; bounds = scalefactor band starts (1-based list) +local function plan(ix: { number }, bounds: { number }, p: Plan) + local i = 576 + while i > 1 and ix[i] == 0 and ix[i - 1] == 0 do + i -= 2 + end + -- count1 region: quadruples of values <= 1 + local c1 = 0 + while i > 3 and ix[i] <= 1 and ix[i - 1] <= 1 and ix[i - 2] <= 1 and ix[i - 3] <= 1 do + i -= 4 + c1 += 1 + end + local bv = i -- big_values * 2 coefficients + p.bigValues, p.count1 = bv // 2, c1 + -- count1 bits, table A vs B + local ba, bb = 0, 0 + local lensA = LEN[32] + for q = 0, c1 - 1 do + local o = bv + q * 4 + local v, w, x, y = ix[o + 1], ix[o + 2], ix[o + 3], ix[o + 4] + local s = v + w + x + y + ba += lensA[v * 8 + w * 4 + x * 2 + y + 1] + s + bb += 4 + s + end + p.c1table = if bb < ba then 1 else 0 + local bits = if bb < ba then bb else ba + -- regions: region 0 / 1 / 2 split at scalefactor band boundaries + local j = 0 + while j + 1 < #bounds and bounds[j + 2] <= bv do + j += 1 + end + local r0 = math.clamp(floor((j + 1) / 3), 0, 15) + local r1 = math.clamp(floor((j + 1) / 3), 0, 7) + if r0 + r1 + 2 > 22 then + r1 = 22 - r0 - 2 + end + local a1 = math.min(bounds[r0 + 2] or 576, bv) + local a2 = math.min(bounds[r0 + r1 + 3] or 576, bv) + p.region0, p.region1, p.addr1, p.addr2 = r0, r1, a1, a2 + local t1, b1 = chooseTable(ix, 0, a1) + local t2, b2 = chooseTable(ix, a1, a2) + local t3, b3 = chooseTable(ix, a2, bv) + p.tables[1], p.tables[2], p.tables[3] = t1, t2, t3 + p.bits = bits + b1 + b2 + b3 +end + +local function writePairs(w: W, ix: { number }, sign: { boolean }, a: number, b: number, t: number) + if t == 0 then + return + end + local codes, lens = CODE[t], LEN[t] + local lb = LINBITS[t] + for i = a, b - 1, 2 do + local x, y = ix[i + 1], ix[i + 2] + local cx, cy = if x > 14 then 15 else x, if y > 14 then 15 else y + local idx = cx * 16 + cy + 1 + put(w, codes[idx], lens[idx]) + if cx == 15 then + put(w, x - 15, lb) + end + if x ~= 0 then + put(w, if sign[i + 1] then 1 else 0, 1) + end + if cy == 15 then + put(w, y - 15, lb) + end + if y ~= 0 then + put(w, if sign[i + 2] then 1 else 0, 1) + end + end +end + +local function writeHuffman(w: W, ix: { number }, sign: { boolean }, p: Plan) + local bv = p.bigValues * 2 + writePairs(w, ix, sign, 0, p.addr1, p.tables[1]) + writePairs(w, ix, sign, p.addr1, p.addr2, p.tables[2]) + writePairs(w, ix, sign, p.addr2, bv, p.tables[3]) + local codesA, lensA = CODE[32], LEN[32] + for q = 0, p.count1 - 1 do + local o = bv + q * 4 + local v, ww, x, y = ix[o + 1], ix[o + 2], ix[o + 3], ix[o + 4] + local idx = v * 8 + ww * 4 + x * 2 + y + if p.c1table == 1 then + put(w, 15 - idx, 4) -- table B: the 4 bits inverted + else + put(w, codesA[idx + 1], lensA[idx + 1]) + end + for k = 1, 4 do + if ix[o + k] ~= 0 then + put(w, if sign[o + k] then 1 else 0, 1) + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ quantization +type Unit = { + xr: { number }, -- 576 MDCT coefficients + xa: { number }, -- |xr|^(3/4) + ix: { number }, + sign: { boolean }, + plan: Plan, + gain: number, +} + +local function newUnit(): Unit + return { + xr = table.create(576, 0), + xa = table.create(576, 0), + ix = table.create(576, 0), + sign = table.create(576, false), + plan = newPlan(), + gain = 210, + } +end + +-- quantize with global gain g: false when a value overflows 8206 +local function quantize(u: Unit, g: number): boolean + local step = 2 ^ (-(g - 210) * 3 / 16) + local xa, ix = u.xa, u.ix + for i = 1, 576 do + local v = floor(xa[i] * step + 0.4054) + if v > 8206 then + return false + end + ix[i] = v + end + return true +end + +-- the finest global gain whose Huffman size fits budget bits +local function rateLoop(u: Unit, budget: number, bounds: { number }) + local xr, xa, sign = u.xr, u.xa, u.sign + local maxa = 0 + for i = 1, 576 do + local v = xr[i] + sign[i] = v < 0 + local a = math.abs(v) ^ 0.75 + xa[i] = a + if a > maxa then + maxa = a + end + end + local p = u.plan + if maxa < 1e-12 then + for i = 1, 576 do + u.ix[i] = 0 + end + plan(u.ix, bounds, p) + u.gain = 0 + return + end + -- the gain where the largest value quantizes to 0: an upper bound + local lo, hi = 0, 255 + local best = -1 + while lo <= hi do + local mid = (lo + hi) // 2 + if quantize(u, mid) then + plan(u.ix, bounds, p) + if p.bits <= budget then + best = mid + hi = mid - 1 + else + lo = mid + 1 + end + else + lo = mid + 1 + end + end + if best < 0 then + best = 255 + end + quantize(u, best) + plan(u.ix, bounds, p) + if p.bits > budget then -- give up on this granule: silence fits any budget + for i = 1, 576 do + u.ix[i] = 0 + end + plan(u.ix, bounds, p) + end + u.gain = best +end + +-- ------------------------------------------------------------------------------------------------ encoder +export type Source = { + sampleRate: number, + channels: number, + frames: number, + read: (self: any, n: number, out: buffer?) -> (buffer, number), + err: any, +} +export type Options = { + bitrate: number, -- kbps, valid for the version + mode: string, -- "stereo" | "joint" | "mono" + prefix: buffer?, -- bytes written before the first frame (an ID3v2 tag) +} + +-- encode(src, opts) -> buffer | nil, message +function Encode3.encode(src: Source, opts: Options): (buffer?, string?) + local rate = src.sampleRate + local info = RATES[rate] + if not info then + return nil, "unsupported sample rate" + end + local version, srIndex, group = info[1], info[2], info[3] + local mpeg1 = version == 3 + local granules = if mpeg1 then 2 else 1 + local spf = 576 * granules + local inCh = src.channels + local mode = opts.mode + local nch = if mode == "mono" then 1 else 2 + local kbps = opts.bitrate + local list = if mpeg1 then BITRATES_V1 else BITRATES_V2 + local brIndex = table.find(list, kbps) + if not brIndex then + return nil, "unsupported bit rate" + end + local sideBytes = if mpeg1 then (if nch == 1 then 17 else 32) else (if nch == 1 then 9 else 17) + local slotNum = (if mpeg1 then 144000 else 72000) * kbps -- frame bytes * rate + -- scalefactor band starts (long blocks) + local bounds = { 0 } + do + local acc = 0 + for k = 0, 21 do + acc += T.g_scf_long[group * 23 + k] + table.insert(bounds, acc) + end + end + local w: W = { buf = buffer.create(65536), pos = 0, acc = 0, cnt = 0 } + if opts.prefix then + local pf = opts.prefix :: buffer + local need = buffer.len(pf) + if need > buffer.len(w.buf) - 16 then + w.buf = buffer.create(need + 65536) + end + buffer.copy(w.buf, 0, pf, 0, need) + w.pos = need + end + local ana = { Analysis.new(), Analysis.new() } + local prev = { table.create(576, 0), table.create(576, 0) } -- previous granule's subband samples [sb * 18 + k + 1] + local cur = { table.create(576, 0), table.create(576, 0) } + local units = {} + for g = 1, 2 do + units[g] = { newUnit(), newUnit() } + end + local pcm = { table.create(spf, 0), table.create(spf, 0) } + local sub = table.create(32, 0) + local z = table.create(36, 0) + local rest = 0 + local tmp: buffer? = nil + local pending: buffer? = nil + local pendN, pendOff = 0, 0 + local srcDone = false + local flushed = false + while true do + -- one frame of input (zero padded at the end; one more silent frame flushes the filterbank delay) + local got = 0 + while got < spf and not srcDone do + if pendN == 0 then + local b, n = src:read(4096, tmp) + if n <= 0 then + srcDone = true + break + end + tmp = b + pending, pendN, pendOff = b, n, 0 + end + local take = math.min(spf - got, pendN) + local pb = pending :: buffer + for i = 0, take - 1 do + local base = (pendOff + i) * inCh * 4 + local l = buffer.readf32(pb, base) + local r = if inCh > 1 then buffer.readf32(pb, base + 4) else l + if nch == 1 then + if inCh > 1 then + l = (l + r) * 0.5 + end + pcm[1][got + i + 1] = l + else + pcm[1][got + i + 1] = l + pcm[2][got + i + 1] = r + end + end + got += take + pendN -= take + pendOff += take + end + if got == 0 then + if flushed then + break + end + flushed = true -- one silent frame after the input pushes its tail through the filterbank delay + end + for c = 1, nch do + local s = pcm[c] + for i = got + 1, spf do + s[i] = 0 + end + end + -- analysis + MDCT per granule and channel + for g = 1, granules do + for c = 1, nch do + local cu, pv = cur[c], prev[c] + local s = pcm[c] + for k = 0, 17 do + Analysis.run(ana[c], s, (g - 1) * 576 + k * 32 + 1, sub, 1) + for sb = 0, 31 do + local v = sub[sb + 1] + if sb % 2 == 1 and k % 2 == 1 then + v = -v -- frequency inversion of the odd subbands + end + cu[sb * 18 + k + 1] = v + end + end + local xr = units[g][c].xr + for sb = 0, 31 do + local o = sb * 18 + for i = 1, 18 do + z[i] = pv[o + i] + z[i + 18] = cu[o + i] + end + for k = 0, 17 do + local acc = 0 + local mb = k * 36 + for i = 1, 36 do + acc += MDCT[mb + i] * z[i] + end + xr[o + k + 1] = acc + end + end + -- alias reduction butterflies (the inverse of the decoder's) + for sb = 1, 31 do + local o = sb * 18 + for i = 0, 7 do + local a, b = xr[o - i], xr[o + i + 1] + xr[o - i] = a * CS[i + 1] + b * CA[i + 1] + xr[o + i + 1] = b * CS[i + 1] - a * CA[i + 1] + end + end + prev[c], cur[c] = cu, pv + end + if mode == "joint" then + local x0, x1 = units[g][1].xr, units[g][2].xr + local r2 = sqrt(0.5) + for i = 1, 576 do + local l, r = x0[i], x1[i] + x0[i], x1[i] = (l + r) * r2, (l - r) * r2 + end + end + end + -- the frame size + local frameBytes = slotNum // rate + rest += slotNum % rate + local padding = 0 + if rest >= rate then + rest -= rate + padding = 1 + frameBytes += 1 + end + local avail = (frameBytes - 4 - sideBytes) * 8 + local left = avail + local nUnits = granules * nch + local done = 0 + for g = 1, granules do + for c = 1, nch do + local budget = math.min(4095, left // (nUnits - done)) + local u = units[g][c] + rateLoop(u, budget, bounds) + left -= u.plan.bits + done += 1 + end + end + -- header + if w.pos + frameBytes + 64 > buffer.len(w.buf) then + local nb = buffer.create(buffer.len(w.buf) * 2 + frameBytes) + buffer.copy(nb, 0, w.buf, 0, w.pos) + w.buf = nb + end + local start = w.pos + put(w, 0x7FF, 11) + put(w, version, 2) + put(w, 1, 2) -- layer III + put(w, 1, 1) -- no CRC + put(w, brIndex, 4) + put(w, srIndex, 2) + put(w, padding, 1) + put(w, 0, 1) + put(w, if mode == "mono" then 3 elseif mode == "joint" then 1 else 0, 2) + put(w, if mode == "joint" then 2 else 0, 2) -- mode extension: mid / side on, intensity off + put(w, 0, 1) + put(w, 1, 1) -- original + put(w, 0, 2) + -- side info + if mpeg1 then + put(w, 0, 9) -- main_data_begin + put(w, 0, if nch == 1 then 5 else 3) + for _ = 1, nch do + put(w, 0, 4) -- scfsi + end + else + put(w, 0, 8) + put(w, 0, if nch == 1 then 1 else 2) + end + for g = 1, granules do + for c = 1, nch do + local u = units[g][c] + local p = u.plan + put(w, p.bits, 12) -- part2_3_length (no scalefactor bits) + put(w, p.bigValues, 9) + put(w, u.gain, 8) + put(w, 0, if mpeg1 then 4 else 9) -- scalefac_compress + put(w, 0, 1) -- window switching off + put(w, p.tables[1], 5) + put(w, p.tables[2], 5) + put(w, p.tables[3], 5) + put(w, p.region0, 4) + put(w, p.region1, 3) + if mpeg1 then + put(w, 0, 1) -- preflag + end + put(w, 0, 1) -- scalefac_scale + put(w, p.c1table, 1) + end + end + -- main data + for g = 1, granules do + for c = 1, nch do + local u = units[g][c] + writeHuffman(w, u.ix, u.sign, u.plan) + end + end + if w.cnt > 0 then + put(w, 0, 8 - w.cnt) + end + -- ancillary padding to the frame size + while w.pos < start + frameBytes do + writeu8(w.buf, w.pos, 0) + w.pos += 1 + end + end + if src.err then + return nil, tostring(src.err) + end + local out = buffer.create(w.pos) + buffer.copy(out, 0, w.buf, 0, w.pos) + return out, nil +end + +return Encode3 diff --git a/src/Formats/audio/mp3/init.luau b/src/Formats/audio/mp3/init.luau index 649970d..e3bd87d 100644 --- a/src/Formats/audio/mp3/init.luau +++ b/src/Formats/audio/mp3/init.luau @@ -4,8 +4,9 @@ -- layers I / II / III, mono / stereo / joint stereo / dual channel, CBR / VBR / free format, gapless playback (Xing / -- Info + LAME delay and padding), exact length and sample-accurate seeking from a frame index built on open, resync -- past garbage, mono / stereo switches (upmixed), ID3v2.2 / 2.3 / 2.4 and ID3v1 / 1.1 tags (APEv2 skipped). --- Float output (minimp3's MINIMP3_FLOAT_OUTPUT scalar path). Not supported: encoding (see the mp3 encoder in the --- audio workstream), MPEG-2 multichannel extension, CRC checks. +-- Float output (minimp3's MINIMP3_FLOAT_OUTPUT scalar path). Encode (ws-audio, audio/mp3/Encode3 + Encode2): layer III +-- (shine-style CBR, MPEG-1 / 2 / 2.5) and layer II (MPEG-1 / 2), mono / stereo / joint stereo, an ID3v2.4 tag from +-- the tags. Not supported: MPEG-2 multichannel extension, CRC checks, VBR / Xing output, encoder resampling. -- -- local dec = Mp3.open(Bytes.reader(buf)) -- the streaming Types.Decoder (+ layer, version, vbr, delay, -- local pcm, n = dec:read(4096) -- padding, mpegFrames, id3, :seekFrame(i), :readAll()) @@ -19,6 +20,9 @@ local Header = require("@formats/audio/mp3/Header") local Index = require("@formats/audio/mp3/Index") local Tags = require("@formats/audio/mp3/Tags") local Stream = require("@formats/audio/mp3/Stream") +local Encode3 = require("@formats/audio/mp3/Encode3") +local Encode2 = require("@formats/audio/mp3/Encode2") +local Pcm = require("@formats/codecs/Pcm") -- ------------------------------------------------------------------------------------------------ contract local Mp3 = { @@ -26,8 +30,8 @@ local Mp3 = { category = "audio", extensions = { "mp3", "mp2", "mp1", "mpga" }, mime = { "audio/mpeg", "audio/mp3", "audio/mpa" }, - deps = { "core/Err", "core/Bytes", "Types" }, - caps = { decode = true, encode = false, streaming = true, seek = true, layers = { 1, 2, 3 }, channels = 2 }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" }, + caps = { decode = true, encode = true, streaming = true, seek = true, layers = { 1, 2, 3 }, channels = 2 }, } -- ------------------------------------------------------------------------------------------------ types @@ -35,6 +39,13 @@ export type OpenOptions = { maxFrames: number?, -- refuse streams longer than this many sample frames per channel (default 2^31) } export type Decoder = Stream.Decoder +export type EncodeOptions = { + layer: number?, -- 3 (MP3, default) or 2 (MP2) + bitrate: number?, -- kbps, constant (default 128 for layer III, 192 for layer II; MPEG-2 / 2.5 rates: 64 / 96) + mode: ("stereo" | "joint" | "mono")?, -- default "joint" (mid / side) for stereo layer III, "stereo" for layer II, + -- "mono" for mono input; layer II has no joint stereo (intensity) and writes "joint" as "stereo" + id3: boolean?, -- write an ID3v2.4 tag from the tags (default true when there are tags) +} -- ------------------------------------------------------------------------------------------------ constants local MAX_FRAMES = 2 ^ 31 @@ -85,6 +96,115 @@ function Mp3.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err return a, nil end +-- ------------------------------------------------------------------------------------------------ encode +local ID3_FRAMES = { + { "title", "TIT2" }, + { "artist", "TPE1" }, + { "album", "TALB" }, + { "albumArtist", "TPE2" }, + { "year", "TDRC" }, + { "date", "TDRC" }, + { "track", "TRCK" }, + { "genre", "TCON" }, + { "composer", "TCOM" }, +} + +-- an ID3v2.4 tag (UTF-8 text frames + a COMM frame) | nil when there is nothing to write +local function id3Tag(tags: { [string]: any }): buffer? + local w = Bytes.writer(256) + local seen: { [string]: boolean } = {} + local function syncsafe(v: number) + w:u8((v // 2097152) % 128) + w:u8((v // 16384) % 128) + w:u8((v // 128) % 128) + w:u8(v % 128) + end + for _, f in ID3_FRAMES do + local v = tags[f[1]] + if type(v) == "string" and #v > 0 and not seen[f[2]] then + seen[f[2]] = true + w:string(f[2]) + syncsafe(#v + 1) + w:u16be(0) + w:u8(3) -- UTF-8 + w:string(v) + end + end + if type(tags.comment) == "string" and #tags.comment > 0 then + local v = tags.comment + w:string("COMM") + syncsafe(#v + 5) + w:u16be(0) + w:u8(3) + w:string("eng") + w:u8(0) -- empty description + w:string(v) + end + local body = w:finish() + if buffer.len(body) == 0 then + return nil + end + local out = Bytes.writer(buffer.len(body) + 10) + out:string("ID3") + out:u8(4) + out:u8(0) + out:u8(0) + local n = buffer.len(body) + out:u8((n // 2097152) % 128) + out:u8((n // 16384) % 128) + out:u8((n // 128) % 128) + out:u8(n % 128) + out:bytes(body) + return out:finish() +end + +-- encode(audioOrDecoder, opts?) -> an MP3 (layer III) or MP2 (layer II) file | nil, Err +function Mp3.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local o: EncodeOptions = opts or {} + local layer = o.layer or 3 + if layer ~= 2 and layer ~= 3 then + return nil, Err.new(Err.ARG, "layer must be 2 or 3") + end + local Enc = if layer == 3 then Encode3 else Encode2 + local info = Enc.RATES[src.sampleRate] + if not info then + return nil, Err.new(Err.ARG, string.format("layer %d cannot hold %s Hz (no resampling)", layer, tostring(src.sampleRate))) + end + local mpeg1 = info[1] == 3 + local mode = o.mode or (if src.channels == 1 then "mono" elseif layer == 3 then "joint" else "stereo") + if mode ~= "stereo" and mode ~= "joint" and mode ~= "mono" then + return nil, Err.new(Err.ARG, "mode must be stereo, joint or mono") + end + if src.channels > 2 then + return nil, Err.new(Err.ARG, "MPEG audio holds 1 or 2 channels") + end + if layer == 2 and mode == "joint" then + mode = "stereo" + end + local bitrate = o.bitrate or (if mpeg1 then (if layer == 3 then 128 else 192) else (if layer == 3 then 64 else 96)) + if not table.find(Enc.BITRATES[if mpeg1 then 1 else 2], bitrate) then + return nil, Err.new(Err.ARG, string.format("%s kbps is not a layer %d bit rate at %d Hz", tostring(bitrate), layer, src.sampleRate)) + end + if layer == 2 and mpeg1 then + -- the standard's allowed bit rate / mode combinations + if mode == "mono" and bitrate > 192 then + return nil, Err.new(Err.ARG, "layer II mono is at most 192 kbps") + elseif mode ~= "mono" and (bitrate == 32 or bitrate == 48 or bitrate == 56 or bitrate == 80) then + return nil, Err.new(Err.ARG, "layer II stereo needs 64 kbps or more (and not 80)") + end + end + local prefix = if o.id3 == false then nil else id3Tag(src.tags) + local out, msg = Enc.encode(src :: any, { bitrate = bitrate, mode = mode, prefix = prefix }) + if not out then + return nil, Err.new(Err.ARG, tostring(msg)) + end + return out, nil +end + -- ------------------------------------------------------------------------------------------------ open -- the string-valued tag fields (title, artist, album, albumArtist, year, track, disc, genre, composer, comment) local function stringTags(t: any): { [string]: string } diff --git a/src/Formats/audio/opus/CeltEncoder.luau b/src/Formats/audio/opus/CeltEncoder.luau new file mode 100644 index 0000000..7c8225a --- /dev/null +++ b/src/Formats/audio/opus/CeltEncoder.luau @@ -0,0 +1,1078 @@ +--!strict +--!native +--!optimize 2 +-- audio/opus/CeltEncoder: a fixed-frame CELT encoder (RFC 6716 section 5.3): 20 ms frames (LM 3), full band, constant +-- bit rate, long MDCTs only (no transient detection), no pitch pre-filter, normal spreading, default allocation trim, +-- mono, or stereo as mid / side per band (the angle, intensity when it has no bits; dual L / R stereo on request). The bitstream side is a port of the libopus 1.6 encoder paths +-- (celt_encoder.c, quant_bands.c, laplace.c, rate.c, bands.c, vq.c, cwrs.c; BSD: licenses/libopus-BSD.txt) that +-- mirror audio/opus/Celt's decoder step for step; the analysis is simplified. The MDCT is codecs/Mdct. +-- Never throws. +local RE = require("@formats/audio/opus/RangeEncoder") +local T = require("@formats/audio/opus/CeltTables") +local Mdct = require("@formats/codecs/Mdct") + +local CeltEncoder = {} + +local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift +local min, max, sqrt, floor, cos, log, atan2 = math.min, math.max, math.sqrt, math.floor, math.cos, math.log, math.atan2 +local encBitLogp, encIcdf, encBits, encUint, encEncode, encEncodeBin = RE.bitLogp, RE.icdf, RE.bits, RE.uint, RE.encode, RE.encodeBin +local tell, tellFrac = RE.tell, RE.tellFrac + +local NB_EBANDS = 21 +local OVERLAP = 120 +local SHORT_MDCT = 120 +local BITRES = 3 +local MAX_FINE_BITS = 8 +local FINE_OFFSET = 21 +local QTHETA_OFFSET = 4 +local PREEMPH = 0.85000610 +local LM = 3 -- 20 ms frames +local M = 8 +local N = 960 + +local EB = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 34, 40, 48, 60, 78, 100 } +local ALLOC = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 90, 80, 75, 69, 63, 56, 49, 40, 34, 29, 20, 18, 10, 0, 0, 0, 0, 0, 0, 0, 0, + 110, 100, 90, 84, 78, 71, 65, 58, 51, 45, 39, 32, 26, 20, 12, 0, 0, 0, 0, 0, 0, + 118, 110, 103, 93, 86, 80, 75, 70, 65, 59, 53, 47, 40, 31, 23, 15, 4, 0, 0, 0, 0, + 126, 119, 112, 104, 95, 89, 83, 78, 72, 66, 60, 54, 47, 39, 32, 25, 17, 12, 1, 0, 0, + 134, 127, 120, 114, 103, 97, 91, 85, 78, 72, 66, 60, 54, 47, 41, 35, 29, 23, 16, 10, 1, + 144, 137, 130, 124, 113, 107, 101, 95, 88, 82, 76, 70, 64, 57, 51, 45, 39, 33, 26, 15, 1, + 152, 145, 138, 132, 123, 117, 111, 105, 98, 92, 86, 80, 74, 67, 61, 55, 49, 43, 36, 20, 1, + 162, 155, 148, 142, 133, 127, 121, 115, 108, 102, 96, 90, 84, 77, 71, 65, 59, 53, 46, 30, 1, + 172, 165, 158, 152, 143, 137, 131, 125, 118, 112, 106, 100, 94, 87, 81, 75, 69, 63, 56, 45, 20, + 200, 200, 200, 200, 200, 200, 200, 200, 198, 193, 188, 183, 178, 173, 168, 163, 158, 153, 148, 129, 104, +} +local NB_ALLOC_VECTORS = 11 +local LOG2_FRAC_TABLE = { 0, 8, 13, 16, 19, 21, 23, 24, 26, 27, 28, 29, 30, 31, 32, 32, 33, 34, 34, 35, 36, 36, 37, 37 } +local LOGN = T.logN400 +local CACHE_INDEX = T.cache_index50 +local CACHE_BITS = T.cache_bits50 +local CACHE_CAPS = T.cache_caps50 +local E_PROB = T.e_prob_model +local E_MEANS = { + 6.437500, 6.250000, 5.750000, 5.312500, 5.062500, 4.812500, 4.500000, 4.375000, 4.875000, 4.687500, + 4.562500, 4.437500, 4.875000, 4.625000, 4.312500, 4.500000, 4.375000, 4.625000, 4.750000, 4.437500, + 3.750000, +} +local PRED_COEF = { 29440 / 32768, 26112 / 32768, 21248 / 32768, 16384 / 32768 } +local BETA_COEF = { 30147 / 32768, 22282 / 32768, 12124 / 32768, 6554 / 32768 } +local BETA_INTRA = 4915 / 32768 +local TF_SELECT = { 0, -2, 0, -3, 3, 0, 1, -1 } -- LM 3 +local TRIM_ICDF = { 126, 124, 119, 109, 87, 41, 19, 9, 4, 2, 0 } +local SPREAD_ICDF = { 25, 23, 2, 0 } +local SMALL_ENERGY_ICDF = { 2, 1, 0 } +local EXP2_TABLE8 = { 16384, 17866, 19483, 21247, 23170, 25267, 27554, 30048 } +local SPREAD_NORMAL = 2 +local SPREAD_FACTOR = { 15, 10, 5 } + +-- the MDCT window (the decoder's) and plan +local WINDOW = table.create(OVERLAP, 0) +for i = 0, OVERLAP - 1 do + local s = math.sin(0.5 * math.pi * (i + 0.5) / OVERLAP) + WINDOW[i + 1] = math.sin(0.5 * math.pi * s * s) +end +local PLAN = Mdct.new(2 * N) :: Mdct.Plan +-- forward scale matching the decoder's backward MDCT (calibrated against audio/opus/Mdct: tests/audio/opus_encode) +local MDCT_SCALE = 2 / N + +-- PVQ codebook sizes U(n, k), flat: U[n * UK + k + 1] +local UK = 177 +local U = table.create(UK * UK, 0) +U[1] = 1 +for n = 1, UK - 1 do + for k = 1, UK - 1 do + U[n * UK + k + 1] = U[(n - 1) * UK + k + 1] + U[n * UK + k] + U[(n - 1) * UK + k] + end +end +local function pvqU(n: number, k: number): number + return U[n * UK + k + 1] +end + +local function imin(a: number, b: number): number + return if a < b then a else b +end +local function imax(a: number, b: number): number + return if a > b then a else b +end +local function tdiv(a: number, b: number): number + local q = a / b + return if q >= 0 then floor(q) else -floor(-q) +end +local function fracMul16(a: number, b: number): number + return (16384 + a * b) // 32768 +end +local function bitexactCos(x: number): number + local x2 = (4096 + x * x) // 8192 + x2 = (32767 - x2) + fracMul16(x2, (-7651 + fracMul16(x2, (8277 + fracMul16(-626, x2))))) + return 1 + x2 +end +local function bitexactLog2tan(isin: number, icos: number): number + local lc = RE.ilog(icos) + local ls = RE.ilog(isin) + icos = icos * 2 ^ (15 - lc) + isin = isin * 2 ^ (15 - ls) + return (ls - lc) * 2048 + fracMul16(isin, fracMul16(isin, -2597) + 7932) - fracMul16(icos, fracMul16(icos, -2597) + 7932) +end + +-- ------------------------------------------------------------------------------------------------ energy +-- ec_laplace_encode: returns the value actually coded (clamped in the flat tail) +local function laplaceEncode(enc: RE.Enc, value: number, fs: number, decay: number): number + local fl = 0 + local val = value + if val ~= 0 then + local s = if val < 0 then -1 else 0 + val = if val < 0 then -val else val + fl = fs + fs = ((32768 - 32 - fs) * (16384 - decay)) // 32768 -- ec_laplace_get_freq1 + local i = 1 + while fs > 0 and i < val do + fs *= 2 + fl += fs + 2 + fs = (fs * decay) // 32768 + i += 1 + end + if fs == 0 then + local ndiMax = 32768 - fl + 1 - 1 + ndiMax = rshift(ndiMax - s, 1) + local di = imin(val - i, ndiMax - 1) + fl += (2 * di + 1 + s) + fs = imin(1, 32768 - fl) + value = if s ~= 0 then -(i + di) else i + di + else + fs += 1 + if s == 0 then + fl += fs + end + end + end + encEncodeBin(enc, fl, fl + fs, 15) + return value +end + +export type State = { + channels: number, + oldBandE: { number }, -- the decoder's view (2 * 21) + preMem: { number }, + inMem: { { number } }, -- the last OVERLAP pre-emphasised samples per channel + frames: number, + X: { { number } }, -- per channel 960 normalised coefficients + bandLogE: { number }, + bandE: { number }, -- linear band amplitudes (intensity stereo weights) + error: { number }, + work: { number }, + tmp: { number }, + iy: { number }, + remaining: number, + spread: number, + dual: boolean, -- stereo: L / R coded independently (default false: mid / side) +} + +-- new(channels) -> State +function CeltEncoder.new(channels: number): State + local inMem = {} + local X = {} + for c = 1, channels do + inMem[c] = table.create(OVERLAP, 0) + X[c] = table.create(N, 0) + end + return { + channels = channels, + oldBandE = table.create(2 * NB_EBANDS, 0), + preMem = table.create(channels, 0), + inMem = inMem, + frames = 0, + X = X, + bandLogE = table.create(2 * NB_EBANDS, 0), + bandE = table.create(2 * NB_EBANDS, 0), + error = table.create(2 * NB_EBANDS, 0), + work = table.create(2 * N, 0), + tmp = table.create(2 * N, 0), + iy = table.create(256, 0), + remaining = 0, + spread = SPREAD_NORMAL, + dual = false, + } +end + +local function quantCoarseEnergy(st: State, intra: boolean, enc: RE.Enc, C: number, budget: number, nbBytes: number) + local oldE, bandLogE, err = st.oldBandE, st.bandLogE, st.error + local probBase = LM * 84 + (if intra then 42 else 0) + local coef, beta + if intra then + coef, beta = 0, BETA_INTRA + else + coef, beta = PRED_COEF[LM + 1], BETA_COEF[LM + 1] + end + local maxDecay = min(16, nbBytes / 8) + local prev0, prev1 = 0, 0 + for i = 0, NB_EBANDS - 1 do + for c = 0, C - 1 do + local k = c * NB_EBANDS + i + 1 + local x = bandLogE[k] + local e = max(-9, oldE[k]) + local prev = if c == 0 then prev0 else prev1 + local f = x - coef * e - prev + local qi = floor(0.5 + f) + local decayBound = max(-28, oldE[k]) - maxDecay + if qi < 0 and x < decayBound then + qi += tdiv(decayBound - x, 1) + if qi > 0 then + qi = 0 + end + end + local t = tell(enc) + local bitsLeft = budget - t - 3 * C * (NB_EBANDS - i) + if i ~= 0 and bitsLeft < 30 then + if bitsLeft < 24 then + qi = imin(1, qi) + end + if bitsLeft < 16 then + qi = imax(-1, qi) + end + end + if budget - t >= 15 then + local pi = 2 * imin(i, 20) + qi = laplaceEncode(enc, qi, E_PROB[probBase + pi + 1] * 128, E_PROB[probBase + pi + 2] * 64) + elseif budget - t >= 2 then + qi = imax(-1, imin(qi, 1)) + encIcdf(enc, if qi < 0 then 1 else 2 * qi, SMALL_ENERGY_ICDF, 2) + elseif budget - t >= 1 then + qi = imin(0, qi) + encBitLogp(enc, qi ~= 0, 1) + else + qi = -1 + end + err[k] = f - qi + oldE[k] = coef * e + prev + qi + prev = prev + qi - beta * qi + if c == 0 then + prev0 = prev + else + prev1 = prev + end + end + end +end + +local function quantFineEnergy(st: State, fineQuant: { number }, enc: RE.Enc, C: number) + local oldE, err = st.oldBandE, st.error + for i = 0, NB_EBANDS - 1 do + local extra = fineQuant[i + 1] + if extra <= 0 then + continue + end + if tell(enc) + C * extra > enc.storage * 8 then + continue + end + local frac = 2 ^ extra + for c = 0, C - 1 do + local k = c * NB_EBANDS + i + 1 + local q2 = floor((err[k] + 0.5) * frac) + q2 = math.clamp(q2, 0, frac - 1) + encBits(enc, q2, extra) + local offset = (q2 + 0.5) * 2 ^ (14 - extra) * (1 / 16384) - 0.5 + oldE[k] += offset + err[k] -= offset + end + end +end + +local function quantEnergyFinalise(st: State, fineQuant: { number }, finePriority: { number }, bitsLeft: number, enc: RE.Enc, C: number) + local oldE, err = st.oldBandE, st.error + for prio = 0, 1 do + local i = 0 + while i < NB_EBANDS and bitsLeft >= C do + if fineQuant[i + 1] >= MAX_FINE_BITS or finePriority[i + 1] ~= prio then + i += 1 + continue + end + for c = 0, C - 1 do + local k = c * NB_EBANDS + i + 1 + local q2 = if err[k] < 0 then 0 else 1 + encBits(enc, q2, 1) + local offset = (q2 - 0.5) * 2 ^ (14 - fineQuant[i + 1] - 1) * (1 / 16384) + oldE[k] += offset + err[k] -= offset + bitsLeft -= 1 + end + i += 1 + end + end +end + +-- ------------------------------------------------------------------------------------------------ allocation +local function bits2pulses(bandI: number, lm: number, bits: number): number + local base = CACHE_INDEX[(lm + 1) * NB_EBANDS + bandI + 1] + local lo, hi = 0, CACHE_BITS[base + 1] + bits -= 1 + for _ = 1, 6 do + local mid = rshift(lo + hi + 1, 1) + if CACHE_BITS[base + mid + 1] >= bits then + hi = mid + else + lo = mid + end + end + local loBits = if lo == 0 then -1 else CACHE_BITS[base + lo + 1] + if bits - loBits <= CACHE_BITS[base + hi + 1] - bits then + return lo + end + return hi +end + +local function pulses2bits(bandI: number, lm: number, pulses: number): number + if pulses == 0 then + return 0 + end + local base = CACHE_INDEX[(lm + 1) * NB_EBANDS + bandI + 1] + return CACHE_BITS[base + pulses + 1] + 1 +end + +local function getPulses(i: number): number + if i < 8 then + return i + end + return lshift(8 + band(i, 7), rshift(i, 3) - 1) +end + +-- clt_compute_allocation (encoder side): keeps every band it can, no intensity stereo, dual stereo for C == 2 +local function computeAllocation(offsets: { number }, cap: { number }, allocTrim: number, total: number, + pulses: { number }, ebits: { number }, finePriority: { number }, C: number, enc: RE.Enc, wantDual: boolean) + local start, endb = 0, NB_EBANDS + total = imax(total, 0) + local len = NB_EBANDS + local skipStart = start + local skipRsv = if total >= 8 then 8 else 0 + total -= skipRsv + local intensityRsv, dualStereoRsv = 0, 0 + if C == 2 then + intensityRsv = LOG2_FRAC_TABLE[endb - start + 1] + if intensityRsv > total then + intensityRsv = 0 + else + total -= intensityRsv + dualStereoRsv = if total >= 8 then 8 else 0 + total -= dualStereoRsv + end + end + local bits1, bits2, thresh, trimOffset = {}, {}, {}, {} + for j = start, endb - 1 do + local w = EB[j + 2] - EB[j + 1] + thresh[j + 1] = imax(C * 8, (3 * w * 2 ^ LM * 8) // 16) + trimOffset[j + 1] = (C * w * (allocTrim - 5 - LM) * (endb - j - 1) * 2 ^ (LM + BITRES)) // 64 + if w * 2 ^ LM == 1 then + trimOffset[j + 1] -= C * 8 + end + end + local lo, hi = 1, NB_ALLOC_VECTORS - 1 + repeat + local done = false + local psum = 0 + local mid = rshift(lo + hi, 1) + for j = endb - 1, start, -1 do + local Nw = EB[j + 2] - EB[j + 1] + local bitsj = (C * Nw * ALLOC[mid * len + j + 1] * 2 ^ LM) // 4 + if bitsj > 0 then + bitsj = imax(0, bitsj + trimOffset[j + 1]) + end + bitsj += offsets[j + 1] + if bitsj >= thresh[j + 1] or done then + done = true + psum += imin(bitsj, cap[j + 1]) + elseif bitsj >= C * 8 then + psum += C * 8 + end + end + if psum > total then + hi = mid - 1 + else + lo = mid + 1 + end + until lo > hi + hi = lo + lo -= 1 + for j = start, endb - 1 do + local Nw = EB[j + 2] - EB[j + 1] + local bits1j = (C * Nw * ALLOC[lo * len + j + 1] * 2 ^ LM) // 4 + local bits2j = if hi >= NB_ALLOC_VECTORS then cap[j + 1] else (C * Nw * ALLOC[hi * len + j + 1] * 2 ^ LM) // 4 + if bits1j > 0 then + bits1j = imax(0, bits1j + trimOffset[j + 1]) + end + if bits2j > 0 then + bits2j = imax(0, bits2j + trimOffset[j + 1]) + end + if lo > 0 then + bits1j += offsets[j + 1] + end + bits2j += offsets[j + 1] + if offsets[j + 1] > 0 then + skipStart = j + end + bits2j = imax(0, bits2j - bits1j) + bits1[j + 1] = bits1j + bits2[j + 1] = bits2j + end + -- interp_bits2pulses + local bits = pulses + local allocFloor = C * 8 + local stereo = if C > 1 then 1 else 0 + local logM = LM * 8 + lo, hi = 0, 64 + for _ = 1, 6 do + local mid = rshift(lo + hi, 1) + local psum = 0 + local done = false + for j = endb - 1, start, -1 do + local tmp = bits1[j + 1] + (mid * bits2[j + 1]) // 64 + if tmp >= thresh[j + 1] or done then + done = true + psum += imin(tmp, cap[j + 1]) + elseif tmp >= allocFloor then + psum += allocFloor + end + end + if psum > total then + hi = mid + else + lo = mid + end + end + local psum = 0 + local done = false + for j = endb - 1, start, -1 do + local tmp = bits1[j + 1] + (lo * bits2[j + 1]) // 64 + if tmp < thresh[j + 1] and not done then + if tmp >= allocFloor then + tmp = allocFloor + else + tmp = 0 + end + else + done = true + end + tmp = imin(tmp, cap[j + 1]) + bits[j + 1] = tmp + psum += tmp + end + local codedBands = endb + while true do + local j = codedBands - 1 + if j <= skipStart then + total += skipRsv + break + end + local left = total - psum + local percoeff = left // (EB[codedBands + 1] - EB[start + 1]) + left -= (EB[codedBands + 1] - EB[start + 1]) * percoeff + local rem = imax(left - (EB[j + 1] - EB[start + 1]), 0) + local bandWidth = EB[codedBands + 1] - EB[j + 1] + local bandBits = bits[j + 1] + percoeff * bandWidth + rem + if bandBits >= imax(thresh[j + 1], allocFloor + 8) then + -- keep every band that can be coded: signal "no more skipping" + encBitLogp(enc, true, 1) + break + end + psum -= bits[j + 1] + intensityRsv + if intensityRsv > 0 then + intensityRsv = LOG2_FRAC_TABLE[j - start + 1] + end + psum += intensityRsv + if bandBits >= allocFloor then + psum += allocFloor + bits[j + 1] = allocFloor + else + bits[j + 1] = 0 + end + codedBands -= 1 + end + local intensity, dualStereo = 0, false + if intensityRsv > 0 then + intensity = codedBands -- no intensity stereo + encUint(enc, intensity - start, codedBands + 1 - start) + end + if intensity <= start then + total += dualStereoRsv + dualStereoRsv = 0 + end + if dualStereoRsv > 0 then + dualStereo = wantDual + encBitLogp(enc, dualStereo, 1) + end + local left = total - psum + local percoeff = left // (EB[codedBands + 1] - EB[start + 1]) + left -= (EB[codedBands + 1] - EB[start + 1]) * percoeff + for j = start, codedBands - 1 do + bits[j + 1] += percoeff * (EB[j + 2] - EB[j + 1]) + end + for j = start, codedBands - 1 do + local tmp = imin(left, EB[j + 2] - EB[j + 1]) + bits[j + 1] += tmp + left -= tmp + end + local balance = 0 + local j = start + while j < codedBands do + local N0 = EB[j + 2] - EB[j + 1] + local Nw = N0 * 2 ^ LM + local bit = bits[j + 1] + balance + local excess + if Nw > 1 then + excess = imax(bit - cap[j + 1], 0) + bits[j + 1] = bit - excess + local den = C * Nw + (if C == 2 and Nw > 2 and not dualStereo and j < intensity then 1 else 0) + local NClogN = den * (LOGN[j + 1] + logM) + local offset = (NClogN // 2) - den * FINE_OFFSET + if Nw == 2 then + offset += (den * 8) // 4 + end + if bits[j + 1] + offset < den * 2 * 8 then + offset += NClogN // 4 + elseif bits[j + 1] + offset < den * 3 * 8 then + offset += NClogN // 8 + end + local eb = imax(0, bits[j + 1] + offset + den * 4) + eb = (eb // den) // 8 + if C * eb > (bits[j + 1] // 8) then + eb = (bits[j + 1] // 2 ^ stereo) // 8 + end + eb = imin(eb, MAX_FINE_BITS) + finePriority[j + 1] = if eb * (den * 8) >= bits[j + 1] + offset then 1 else 0 + bits[j + 1] -= C * eb * 8 + ebits[j + 1] = eb + else + excess = imax(0, bit - C * 8) + bits[j + 1] = bit - excess + ebits[j + 1] = 0 + finePriority[j + 1] = 1 + end + if excess > 0 then + local extraFine = imin(excess // 2 ^ (stereo + BITRES), MAX_FINE_BITS - ebits[j + 1]) + ebits[j + 1] += extraFine + local extraBits = extraFine * C * 8 + finePriority[j + 1] = if extraBits >= excess - balance then 1 else 0 + excess -= extraBits + end + balance = excess + j += 1 + end + while j < endb do + ebits[j + 1] = (bits[j + 1] // 2 ^ stereo) // 8 + bits[j + 1] = 0 + finePriority[j + 1] = if ebits[j + 1] < 1 then 1 else 0 + j += 1 + end + return codedBands, balance, intensity, dualStereo +end + +-- ------------------------------------------------------------------------------------------------ PVQ +-- icwrs: the index of the pulse vector iy[1..n] +local function icwrs(n: number, iy: { number }): number + local j = n -- 1-based position of _y[n - 1] + local i = if iy[j] < 0 then 1 else 0 + local k = math.abs(iy[j]) + repeat + j -= 1 + local nn = n - (j - 1) -- _n - j with 0-based j + i += pvqU(nn, k) + k += math.abs(iy[j]) + if iy[j] < 0 then + i += pvqU(nn, k + 1) + end + until j <= 1 + return i +end + +local function expRotation1(X: { number }, xo: number, len: number, stride: number, c: number, s: number) + local ms = -s + local p = xo + 1 + for _ = 0, len - stride - 1 do + local x1 = X[p] + local x2 = X[p + stride] + X[p + stride] = c * x2 + s * x1 + X[p] = c * x1 + ms * x2 + p += 1 + end + p = xo + len - 2 * stride + for _ = len - 2 * stride - 1, 0, -1 do + local x1 = X[p] + local x2 = X[p + stride] + X[p + stride] = c * x2 + s * x1 + X[p] = c * x1 + ms * x2 + p -= 1 + end +end + +-- exp_rotation(X, len, dir = 1, stride, K, spread): the encoder's spreading rotation +local function expRotation(X: { number }, xo: number, len: number, stride: number, K: number, spread: number) + if 2 * K >= len or spread == 0 then + return + end + local factor = SPREAD_FACTOR[spread] + local gain = len / (len + factor * K) + local theta = 0.5 * (gain * gain) + local c = cos(0.5 * math.pi * theta) + local s = cos(0.5 * math.pi * (1 - theta)) + local stride2 = 0 + if len >= 8 * stride then + stride2 = 1 + while (stride2 * stride2 + stride2) * stride + rshift(stride, 2) < len do + stride2 += 1 + end + end + len = len // stride + for i = 0, stride - 1 do + local x = xo + i * len + expRotation1(X, x, len, 1, c, -s) + if stride2 ~= 0 then + expRotation1(X, x, len, stride2, s, -c) + end + end +end + +-- op_pvq_search: the K-pulse vector closest to X[xo + 1 .. xo + n] into iy[1..n] +local function pvqSearch(X: { number }, xo: number, n: number, K: number, iy: { number }, y: { number }, absx: { number }) + local sign = y -- reuse: y holds 2 * |pulses| during the search, signs kept in absx's sign + local xy, yy = 0, 0 + local pulsesLeft = K + for j = 1, n do + local v = X[xo + j] + absx[j] = if v < 0 then -v else v + sign[j] = 0 + iy[j] = 0 + end + if K > rshift(n, 1) then + local sum = 0 + for j = 1, n do + sum += absx[j] + end + if not (sum > 1e-15 and sum < 64) then + absx[1] = 1 + for j = 2, n do + absx[j] = 0 + end + sum = 1 + end + local rcp = (K + 0.8) / sum + for j = 1, n do + local p = floor(rcp * absx[j]) + iy[j] = p + yy += p * p + xy += absx[j] * p + sign[j] = 2 * p + pulsesLeft -= p + end + end + if pulsesLeft > n + 3 then + yy += pulsesLeft * pulsesLeft + pulsesLeft * sign[1] + iy[1] += pulsesLeft + pulsesLeft = 0 + end + for _ = 1, pulsesLeft do + yy += 1 + local best = 1 + local rxy = xy + absx[1] + local bestNum = rxy * rxy + local bestDen = yy + sign[1] + for j = 2, n do + rxy = xy + absx[j] + local num = rxy * rxy + local den = yy + sign[j] + if bestDen * num > den * bestNum then + bestDen, bestNum, best = den, num, j + end + end + xy += absx[best] + yy += sign[best] + sign[best] += 2 + iy[best] += 1 + end + for j = 1, n do + if X[xo + j] < 0 then + iy[j] = -iy[j] + end + end +end + +local SCRATCH_Y = table.create(256, 0) +local SCRATCH_A = table.create(256, 0) +local ROT = table.create(256, 0) + +local function algQuant(st: State, X: { number }, xo: number, n: number, K: number, enc: RE.Enc) + -- rotate a copy (the original band stays for nothing else, but keep it intact) + for j = 1, n do + ROT[j] = X[xo + j] + end + expRotation(ROT, 0, n, 1, K, st.spread) + local iy = st.iy + pvqSearch(ROT, 0, n, K, iy, SCRATCH_Y, SCRATCH_A) + encUint(enc, icwrs(n, iy), pvqU(n, K) + pvqU(n, K + 1)) +end + +-- ------------------------------------------------------------------------------------------------ bands +local function computeQn(n: number, b: number, offset: number, pulseCap: number): number + local N2 = 2 * n - 1 + local qb = tdiv(b + N2 * offset, N2) + qb = imin(b - pulseCap - 32, qb) + qb = imin(64, qb) + if qb < 4 then + return 1 + end + local qn = rshift(EXP2_TABLE8[band(qb, 7) + 1], 14 - rshift(qb, 3)) + return lshift(rshift(qn + 1, 1), 1) +end + +-- quant_partition (encoder, B = 1, mono): returns nothing (no resynthesis) +local function quantPartition(st: State, bandI: number, X: { number }, xo: number, n: number, b: number, lm: number, enc: RE.Enc) + local split = false + if lm ~= -1 and n > 2 then + local base = CACHE_INDEX[(lm + 1) * NB_EBANDS + bandI + 1] + split = b > CACHE_BITS[base + CACHE_BITS[base + 1] + 1] + 12 + end + if split then + n = rshift(n, 1) + local yo = xo + n + lm -= 1 + -- compute_theta (mono split, B0 = 1: triangular pdf) + local pulseCap = LOGN[bandI + 1] + lm * 8 + local offset = (pulseCap // 2) - QTHETA_OFFSET + local qn = computeQn(n, b, offset, pulseCap) + local t0 = tellFrac(enc) + local itheta = 0 + if qn ~= 1 then + local emid, eside = 1e-15, 1e-15 + for j = 1, n do + emid += X[xo + j] * X[xo + j] + eside += X[yo + j] * X[yo + j] + end + local it = floor(0.5 + 16384 * 0.63662 * atan2(sqrt(eside), sqrt(emid))) + itheta = (it * qn + 8192) // 16384 + local h = rshift(qn, 1) + local ft = (h + 1) * (h + 1) + local fs = if itheta <= h then itheta + 1 else qn + 1 - itheta + local fl = if itheta <= h then rshift(itheta * (itheta + 1), 1) else ft - rshift((qn + 1 - itheta) * (qn + 2 - itheta), 1) + encEncode(enc, fl, fl + fs, ft) + itheta = (itheta * 16384) // qn + end + local qalloc = tellFrac(enc) - t0 + b -= qalloc + local delta + if itheta == 0 then + delta = -16384 + elseif itheta == 16384 then + delta = 16384 + else + local imid = bitexactCos(itheta) + local iside = bitexactCos(16384 - itheta) + delta = fracMul16((n - 1) * 128, bitexactLog2tan(iside, imid)) + end + local mbits = imax(0, imin(b, tdiv(b - delta, 2))) + local sbits = b - mbits + st.remaining -= qalloc + local rebalance = st.remaining + if mbits >= sbits then + quantPartition(st, bandI, X, xo, n, mbits, lm, enc) + rebalance = mbits - (rebalance - st.remaining) + if rebalance > 24 and itheta ~= 0 then + sbits += rebalance - 24 + end + quantPartition(st, bandI, X, yo, n, sbits, lm, enc) + else + quantPartition(st, bandI, X, yo, n, sbits, lm, enc) + rebalance = sbits - (rebalance - st.remaining) + if rebalance > 24 and itheta ~= 16384 then + mbits += rebalance - 24 + end + quantPartition(st, bandI, X, xo, n, mbits, lm, enc) + end + else + local q = bits2pulses(bandI, lm, b) + local currBits = pulses2bits(bandI, lm, q) + st.remaining -= currBits + while st.remaining < 0 and q > 0 do + st.remaining += currBits + q -= 1 + currBits = pulses2bits(bandI, lm, q) + st.remaining -= currBits + end + if q ~= 0 then + algQuant(st, X, xo, n, getPulses(q), enc) + end + end +end + +-- quant_band_stereo (encoder, N > 2, B = 1): the mid / side angle (step pdf), then mid and side as mono bands; +-- qn == 1 falls back to intensity stereo (with the inversion bit when there is room) +local function quantBandStereo(st: State, i: number, n: number, xo: number, b: number, enc: RE.Enc) + local L, R = st.X[1], st.X[2] + local pulseCap = LOGN[i + 1] + LM * 8 + local offset = (pulseCap // 2) - QTHETA_OFFSET + local qn = computeQn(n, b, offset, pulseCap) + -- stereo_itheta: the angle between mid and side energies + local emid, eside = 1e-15, 1e-15 + for j = 1, n do + local m = 0.5 * L[xo + j] + 0.5 * R[xo + j] + local sd = 0.5 * L[xo + j] - 0.5 * R[xo + j] + emid += m * m + eside += sd * sd + end + local itheta = floor(0.5 + 16384 * 0.63662 * atan2(sqrt(eside), sqrt(emid))) + local t0 = tellFrac(enc) + local function intensityStereo() + local left, right = st.bandE[i + 1], st.bandE[NB_EBANDS + i + 1] + local norm = 1e-15 + sqrt(1e-15 + left * left + right * right) + local a1, a2 = left / norm, right / norm + for j = 1, n do + L[xo + j] = a1 * L[xo + j] + a2 * R[xo + j] + end + end + if qn ~= 1 then + itheta = (itheta * qn + 8192) // 16384 + local p0 = 3 + local x0 = qn // 2 + local ft = p0 * (x0 + 1) + x0 + if itheta <= x0 then + encEncode(enc, p0 * itheta, p0 * (itheta + 1), ft) + else + encEncode(enc, (itheta - 1 - x0) + (x0 + 1) * p0, (itheta - x0) + (x0 + 1) * p0, ft) + end + itheta = (itheta * 16384) // qn + if itheta == 0 then + intensityStereo() + else + -- stereo_split: mid / side + for j = 1, n do + local l = 0.70710678 * L[xo + j] + local r = 0.70710678 * R[xo + j] + L[xo + j] = l + r + R[xo + j] = r - l + end + end + else + local inv = itheta > 8192 + if inv then + for j = 1, n do + R[xo + j] = -R[xo + j] + end + end + intensityStereo() + if b > 16 and st.remaining > 16 then + encBitLogp(enc, inv, 2) + end + itheta = 0 + end + local qalloc = tellFrac(enc) - t0 + b -= qalloc + local delta + if itheta == 0 then + delta = -16384 + elseif itheta == 16384 then + delta = 16384 + else + local imid = bitexactCos(itheta) + local iside = bitexactCos(16384 - itheta) + delta = fracMul16((n - 1) * 128, bitexactLog2tan(iside, imid)) + end + local mbits = imax(0, imin(b, tdiv(b - delta, 2))) + local sbits = b - mbits + st.remaining -= qalloc + local rebalance = st.remaining + if mbits >= sbits then + quantPartition(st, i, L, xo, n, mbits, LM, enc) + rebalance = mbits - (rebalance - st.remaining) + if rebalance > 24 and itheta ~= 0 then + sbits += rebalance - 24 + end + quantPartition(st, i, R, xo, n, sbits, LM, enc) + else + quantPartition(st, i, R, xo, n, sbits, LM, enc) + rebalance = sbits - (rebalance - st.remaining) + if rebalance > 24 and itheta ~= 16384 then + mbits += rebalance - 24 + end + quantPartition(st, i, L, xo, n, mbits, LM, enc) + end +end + +-- quant_all_bands (encoder): mono, dual stereo or mid / side stereo +local function quantAllBands(st: State, C: number, pulses: { number }, dualStereo: boolean, totalBits: number, + balance: number, enc: RE.Enc, codedBands: number, intensity: number) + for i = 0, NB_EBANDS - 1 do + local xo = M * EB[i + 1] + local nb = M * EB[i + 2] - M * EB[i + 1] + local t = tellFrac(enc) + if i ~= 0 then + balance -= t + end + local remainingBits = totalBits - t - 1 + st.remaining = remainingBits + local b + if i <= codedBands - 1 then + local currBalance = tdiv(balance, imin(3, codedBands - i)) + b = imax(0, imin(16383, imin(remainingBits + 1, pulses[i + 1] + currBalance))) + else + b = 0 + end + if dualStereo and i == intensity then + dualStereo = false + end + if C == 2 and dualStereo then + quantPartition(st, i, st.X[1], xo, nb, b // 2, LM, enc) + quantPartition(st, i, st.X[2], xo, nb, b // 2, LM, enc) + elseif C == 2 then + quantBandStereo(st, i, nb, xo, b, enc) + else + quantPartition(st, i, st.X[1], xo, nb, b, LM, enc) + end + balance += pulses[i + 1] + t + end +end + +-- ------------------------------------------------------------------------------------------------ frame +-- encodeFrame(st, pcm, base, stride, nbBytes) -> buffer: one CELT frame of nbBytes from 960 samples per channel +-- (pcm[base + k * stride + c], floats -1 .. 1, interleaved) +function CeltEncoder.encodeFrame(st: State, pcm: { number }, base: number, stride: number, nbBytes: number): buffer + local C = st.channels + local work, tmp = st.work, st.tmp + local silent = true + -- pre-emphasis, the windowed 1920-sample MDCT input, band energies, normalisation + for c = 1, C do + local inMem = st.inMem[c] + local m = st.preMem[c] + -- tmp[1..1080] = the last 120 pre-emphasised samples + this frame's 960 + for k = 1, OVERLAP do + tmp[k] = inMem[k] + end + for k = 0, N - 1 do + local x = pcm[base + k * stride + c - 1] * 32768 + if x ~= 0 then + silent = false + end + tmp[OVERLAP + k + 1] = x - m + m = PREEMPH * x + end + st.preMem[c] = m + for k = 1, OVERLAP do + inMem[k] = tmp[N + k] + end + local q = 420 -- (2N - (N + OVERLAP)) / 2 zeros at each end + for k = 1, q do + work[k] = 0 + work[2 * N - k + 1] = 0 + end + for k = 1, OVERLAP do + work[q + k] = tmp[k] * WINDOW[k] + work[q + N + k] = tmp[N + k] * WINDOW[OVERLAP - k + 1] + end + for k = OVERLAP + 1, N do + work[q + k] = tmp[k] + end + local X = st.X[c] + Mdct.forward(PLAN, work, 1, X, 1, 1, MDCT_SCALE) + for i = 0, NB_EBANDS - 1 do + local a, z = M * EB[i + 1] + 1, M * EB[i + 2] + local s = 1e-27 + for k = a, z do + s += X[k] * X[k] + end + local E = sqrt(s) + st.bandE[(c - 1) * NB_EBANDS + i + 1] = E + st.bandLogE[(c - 1) * NB_EBANDS + i + 1] = log(E) / log(2) - E_MEANS[i + 1] + local g = 1 / (1e-27 + E) + for k = a, z do + X[k] *= g + end + end + end + local enc = RE.new(nbBytes) + local totalBits = nbBytes * 8 + local oldE = st.oldBandE + -- silence + if silent then + encBitLogp(enc, true, 15) + enc.nbits_total += totalBits - tell(enc) + RE.done(enc) + for i = 1, 2 * NB_EBANDS do + oldE[i] = -28 + end + st.frames += 1 + return enc.buf + end + encBitLogp(enc, false, 15) + if tell(enc) + 16 <= totalBits then + encBitLogp(enc, false, 1) -- no post-filter + end + if tell(enc) + 3 <= totalBits then + encBitLogp(enc, false, 3) -- not transient + end + local intra = st.frames == 0 + if tell(enc) + 3 <= totalBits then + encBitLogp(enc, intra, 3) + else + intra = false + end + if C == 1 then + for i = 1, NB_EBANDS do + oldE[i] = max(oldE[i], oldE[NB_EBANDS + i]) + end + end + quantCoarseEnergy(st, intra, enc, C, totalBits, nbBytes) + -- tf_encode: no changes + do + local budget = totalBits + local tt = tell(enc) + local logp = 4 + if tt + logp + 1 <= budget then + budget -= 1 + end + for _ = 0, NB_EBANDS - 1 do + if tt + logp <= budget then + encBitLogp(enc, false, logp) + tt = tell(enc) + end + logp = 5 + end + -- tf_select is only coded when it changes something: not for LM 3 without changes + local _ = TF_SELECT + end + if tell(enc) + 4 <= totalBits then + encIcdf(enc, st.spread, SPREAD_ICDF, 5) + end + local cap = {} + for i = 0, NB_EBANDS - 1 do + local Nw = (EB[i + 2] - EB[i + 1]) * 2 ^ LM + cap[i + 1] = rshift((CACHE_CAPS[NB_EBANDS * (2 * LM + C - 1) + i + 1] + 64) * C * Nw, 2) + end + local offsets = table.create(NB_EBANDS, 0) + local total8 = totalBits * 8 + local t = tellFrac(enc) + for i = 0, NB_EBANDS - 1 do + if t + 6 * 8 < total8 and 0 < cap[i + 1] then + encBitLogp(enc, false, 6) -- no dynamic allocation boost + t = tellFrac(enc) + end + end + if t + 48 <= total8 then + encIcdf(enc, 5, TRIM_ICDF, 7) + end + local bits = nbBytes * 64 - tellFrac(enc) - 1 + local pulses, fineQuant, finePriority = table.create(NB_EBANDS, 0), table.create(NB_EBANDS, 0), table.create(NB_EBANDS, 0) + local codedBands, balance, intensity, dualStereo = computeAllocation(offsets, cap, 5, bits, pulses, fineQuant, finePriority, C, enc, st.dual) + quantFineEnergy(st, fineQuant, enc, C) + quantAllBands(st, C, pulses, dualStereo, nbBytes * 64, balance, enc, codedBands, intensity) + quantEnergyFinalise(st, fineQuant, finePriority, totalBits - tell(enc), enc, C) + RE.done(enc) + if C == 1 then + for i = 1, NB_EBANDS do + oldE[NB_EBANDS + i] = oldE[i] + end + end + st.frames += 1 + st.lastError = enc.error + return enc.buf +end + +CeltEncoder.FRAME = N +CeltEncoder.DELAY = OVERLAP -- the decoder's output lags the input by the MDCT overlap +return CeltEncoder diff --git a/src/Formats/audio/opus/Encode.luau b/src/Formats/audio/opus/Encode.luau new file mode 100644 index 0000000..13e4c05 --- /dev/null +++ b/src/Formats/audio/opus/Encode.luau @@ -0,0 +1,181 @@ +--!strict +-- audio/opus/Encode: Ogg Opus writing (RFC 7845) around audio/opus/CeltEncoder: CELT-only packets (TOC config 31: +-- full band, 20 ms, code 0), OpusHead (mapping family 0, the pre-skip = the encoder's delay), OpusTags (vendor + +-- the tags as Vorbis comments), granule positions with end trimming, pages through containers/Ogg's muxer. Input at +-- other rates is resampled to 48 kHz (a Kaiser-windowed sinc; quality enough for a codec input). New in formats-luau. +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Ogg = require("@formats/containers/Ogg") +local CeltEncoder = require("@formats/audio/opus/CeltEncoder") + +local Encode = {} + +export type Options = { + bitrate: number?, -- bits per second (default 64000 per channel; 6000 .. 510000, constant) + tags: { [string]: string }?, -- default: the audio's tags + vendor: string?, -- OpusTags vendor (default "formats-luau") + serial: number?, -- Ogg stream serial (default 0x4f707573) +} + +local floor, sin, pi, sqrt = math.floor, math.sin, math.pi, math.sqrt + +local function besselI0(x: number): number + local sum, term = 1, 1 + for k = 1, 60 do + term *= (x / (2 * k)) ^ 2 + sum += term + if term < sum * 1e-15 then + break + end + end + return sum +end + +-- resample(src (interleaved f32 buffer), frames, channels, from, to) -> { number } interleaved, frames out +local function resample(src: buffer, frames: number, channels: number, from: number, to: number): ({ number }, number) + local outFrames = floor(frames * to / from + 0.5) + local out = table.create(outFrames * channels, 0) + local ratio = to / from + local cutoff = 0.97 * math.min(1, ratio) -- of the input Nyquist + local half = 16 -- zero crossings each side (at the cutoff) + local width = half / cutoff + local beta = 8 + local i0b = besselI0(beta) + local readf32 = buffer.readf32 + for j = 0, outFrames - 1 do + local t = j / ratio -- the input position + local first = math.max(0, floor(t - width) + 1) + local last = math.min(frames - 1, floor(t + width)) + for c = 0, channels - 1 do + local acc, wsum = 0, 0 + for i = first, last do + local d = i - t + local x = d * cutoff + local s = if x == 0 then 1 else sin(pi * x) / (pi * x) + local r = d / width + local w = besselI0(beta * sqrt(math.max(0, 1 - r * r))) / i0b + local h = s * w + acc += readf32(src, (i * channels + c) * 4) * h + wsum += h + end + out[j * channels + c + 1] = if wsum ~= 0 then acc / wsum else 0 + end + end + return out, outFrames +end + +local TAG_NAMES: { [string]: string } = { + title = "TITLE", artist = "ARTIST", album = "ALBUM", albumartist = "ALBUMARTIST", date = "DATE", genre = "GENRE", + track = "TRACKNUMBER", tracktotal = "TRACKTOTAL", disc = "DISCNUMBER", comment = "COMMENT", composer = "COMPOSER", +} + +-- encode(audio | decoder, opts) -> buffer | nil, Err +function Encode.encode(value: any, opts: Options?): (buffer?, Err.Err?) + local o = opts or {} + if type(value) ~= "table" or type(value.sampleRate) ~= "number" or type(value.channels) ~= "number" then + return nil, Err.new(Err.ARG, "expected an Audio or a Decoder") + end + local ch = value.channels + if ch ~= 1 and ch ~= 2 then + return nil, Err.new(Err.UNSUPPORTED, "the CELT encoder writes mono or stereo (got " .. ch .. " channels)") + end + local rate = value.sampleRate + if rate < 1000 or rate > 768000 then + return nil, Err.new(Err.ARG, "bad sample rate " .. tostring(rate)) + end + local bitrate = o.bitrate or 64000 * ch + if type(bitrate) ~= "number" or bitrate < 6000 or bitrate > 510000 then + return nil, Err.new(Err.ARG, "bitrate 6000 .. 510000") + end + -- the whole input as an interleaved f32 buffer + local samples: buffer, frames: number + if value.kind == "audio" and type(value.samples) == "buffer" then + samples, frames = value.samples, value.frames + if buffer.len(samples) < frames * ch * 4 then + return nil, Err.new(Err.ARG, "audio.samples is shorter than frames * channels") + end + elseif type(value.read) == "function" then + local w = Bytes.writer(65536) + frames = 0 + local chunk: buffer? = nil + while true do + local b, n = value:read(16384, chunk) + chunk = b + if n <= 0 then + break + end + w:bytes(b, 0, n * ch * 4) + frames += n + end + samples = w:finish() + else + return nil, Err.new(Err.ARG, "expected an Audio or a Decoder") + end + -- 48 kHz floats + local pcm: { number }, n48: number + if rate == 48000 then + n48 = frames + pcm = table.create(frames * ch, 0) + for i = 1, frames * ch do + pcm[i] = buffer.readf32(samples, (i - 1) * 4) + end + else + pcm, n48 = resample(samples, frames, ch, rate, 48000) + end + local FRAME = CeltEncoder.FRAME + local preSkip = CeltEncoder.DELAY + local packets = (n48 + preSkip + FRAME - 1) // FRAME + -- zero padding to whole frames + for i = n48 * ch + 1, packets * FRAME * ch do + pcm[i] = 0 + end + local bytes = math.clamp(floor(bitrate * FRAME / 48000 / 8), if ch == 2 then 40 else 20, 1275 - 1) + local st = CeltEncoder.new(ch) + local mux = Ogg.muxer({ pageSize = 4096 }) + local s = mux:stream(o.serial or 0x4f707573) + -- OpusHead + local head = Bytes.writer(19) + head:string("OpusHead") + head:u8(1) + head:u8(ch) + head:u16le(preSkip) + head:u32le(floor(rate)) + head:u16le(0) + head:u8(0) + s:packet(head:finish(), 0, { flush = true }) + -- OpusTags + local tags = o.tags or value.tags or {} + local tw = Bytes.writer(256) + tw:string("OpusTags") + local vendor = o.vendor or "formats-luau" + tw:u32le(#vendor) + tw:string(vendor) + local keys = {} + for k, v in tags do + if type(k) == "string" and type(v) == "string" then + table.insert(keys, k) + end + end + table.sort(keys) + tw:u32le(#keys) + for _, k in keys do + local field = (TAG_NAMES[k] or string.upper(k)) .. "=" .. tags[k] + tw:u32le(#field) + tw:string(field) + end + s:packet(tw:finish(), 0, { flush = true }) + -- audio + local toc = 31 * 8 + (if ch == 2 then 4 else 0) + for p = 0, packets - 1 do + local frame = CeltEncoder.encodeFrame(st, pcm, p * FRAME * ch + 1, ch, bytes) + local pkt = buffer.create(bytes + 1) + buffer.writeu8(pkt, 0, toc) + buffer.copy(pkt, 1, frame, 0, bytes) + local last = p == packets - 1 + local granule = if last then preSkip + n48 else (p + 1) * FRAME + s:packet(pkt, granule, { eos = last }) + end + return mux:finish(), nil +end + +return Encode diff --git a/src/Formats/audio/opus/RangeEncoder.luau b/src/Formats/audio/opus/RangeEncoder.luau new file mode 100644 index 0000000..13bf3c6 --- /dev/null +++ b/src/Formats/audio/opus/RangeEncoder.luau @@ -0,0 +1,252 @@ +--!strict +--!native +--!optimize 2 +-- audio/opus/RangeEncoder: the range encoder (RFC 6716 section 5.1), a port of libopus celt/entenc.c (BSD: +-- licenses/libopus-BSD.txt), the mirror of audio/opus/RangeDecoder. Writes one fixed-size frame: the range-coded +-- symbols from the front, the raw bits (ec_enc_bits) from the back, zeros between. Values stay below 2^32 as plain +-- numbers. Never throws: running out of room sets `error`. +local RangeEncoder = {} + +export type Enc = { + buf: buffer, + storage: number, + offs: number, + end_offs: number, + end_window: number, + nend_bits: number, + nbits_total: number, + rng: number, + val: number, + rem: number, + ext: number, + error: number, +} + +local CODE_TOP = 2147483648 -- 1 << 31 +local CODE_BOT = 8388608 -- CODE_TOP >> 8 +local CODE_SHIFT = 23 +local SYM_MAX = 255 + +local countlz = bit32.countlz +local band = bit32.band +local readu8, writeu8 = buffer.readu8, buffer.writeu8 +local floor = math.floor + +local function ilog(x: number): number + return 32 - countlz(x) +end +RangeEncoder.ilog = ilog + +-- new(storage) -> Enc over a fresh zeroed buffer of storage bytes +function RangeEncoder.new(storage: number): Enc + return { + buf = buffer.create(math.max(storage, 1)), + storage = storage, + offs = 0, + end_offs = 0, + end_window = 0, + nend_bits = 0, + nbits_total = 33, -- EC_CODE_BITS + 1 + rng = CODE_TOP, + val = 0, + rem = -1, + ext = 0, + error = 0, + } +end + +local function writeByte(e: Enc, v: number) + if e.offs + e.end_offs >= e.storage then + e.error = -1 + return + end + writeu8(e.buf, e.offs, band(v, 255)) + e.offs += 1 +end + +local function writeByteAtEnd(e: Enc, v: number) + if e.offs + e.end_offs >= e.storage then + e.error = -1 + return + end + e.end_offs += 1 + writeu8(e.buf, e.storage - e.end_offs, band(v, 255)) +end + +local function carryOut(e: Enc, c: number) + if c ~= SYM_MAX then + local carry = if c >= 256 then 1 else 0 + if e.rem >= 0 then + writeByte(e, e.rem + carry) + end + if e.ext > 0 then + local sym = band(SYM_MAX + carry, 255) + repeat + writeByte(e, sym) + e.ext -= 1 + until e.ext <= 0 + end + e.rem = band(c, 255) + else + e.ext += 1 + end +end + +local function normalize(e: Enc) + while e.rng <= CODE_BOT do + carryOut(e, floor(e.val / 8388608)) + e.val = (e.val * 256) % CODE_TOP + e.rng *= 256 + e.nbits_total += 8 + end +end + +-- encode(fl, fh, ft): the symbol [fl, fh) of ft +function RangeEncoder.encode(e: Enc, fl: number, fh: number, ft: number) + local r = floor(e.rng / ft) + if fl > 0 then + e.val += e.rng - r * (ft - fl) + e.rng = r * (fh - fl) + else + e.rng -= r * (ft - fh) + end + normalize(e) +end + +-- encodeBin(fl, fh, bits): ft = 2^bits +function RangeEncoder.encodeBin(e: Enc, fl: number, fh: number, bits: number) + local ft = 2 ^ bits + local r = floor(e.rng / ft) + if fl > 0 then + e.val += e.rng - r * (ft - fl) + e.rng = r * (fh - fl) + else + e.rng -= r * (ft - fh) + end + normalize(e) +end + +-- bitLogp(v, logp): a bit whose probability of being 1 is 2^-logp +function RangeEncoder.bitLogp(e: Enc, v: boolean, logp: number) + local r = e.rng + local s = floor(r / 2 ^ logp) + r -= s + if v then + e.val += r + e.rng = s + else + e.rng = r + end + normalize(e) +end + +-- icdf(s, icdf, ftb): symbol s (0-based) of an inverse CDF table (1-based Luau array) with 2^ftb total +function RangeEncoder.icdf(e: Enc, s: number, icdf: { number }, ftb: number) + local r = floor(e.rng / 2 ^ ftb) + if s > 0 then + e.val += e.rng - r * icdf[s] + e.rng = r * (icdf[s] - icdf[s + 1]) + else + e.rng -= r * icdf[s + 1] + end + normalize(e) +end + +-- bits(fl, n): n raw bits (n <= 25), written from the end of the frame +function RangeEncoder.bits(e: Enc, fl: number, n: number) + local window = e.end_window + local used = e.nend_bits + if used + n > 32 then + repeat + writeByteAtEnd(e, window % 256) + window = floor(window / 256) + used -= 8 + until used < 8 + end + window += fl * 2 ^ used + used += n + e.end_window = window + e.nend_bits = used + e.nbits_total += n +end + +-- uint(fl, ft): fl uniformly in [0, ft), ft up to 2^32 +function RangeEncoder.uint(e: Enc, fl: number, ft: number) + ft -= 1 + local ftb = ilog(ft) + if ftb > 8 then + ftb -= 8 + local sh = 2 ^ ftb + local ft1 = floor(ft / sh) + 1 + local hi = floor(fl / sh) + RangeEncoder.encode(e, hi, hi + 1, ft1) + RangeEncoder.bits(e, fl - hi * sh, ftb) + else + RangeEncoder.encode(e, fl, fl + 1, ft + 1) + end +end + +function RangeEncoder.tell(e: Enc): number + return e.nbits_total - ilog(e.rng) +end + +local CORRECTION = { 35733, 38967, 42495, 46340, 50535, 55109, 60097, 65535 } +function RangeEncoder.tellFrac(e: Enc): number + local nbits = e.nbits_total * 8 + local l = ilog(e.rng) + local r = floor(e.rng / 2 ^ (l - 16)) + local b = floor(r / 4096) - 8 + if r > CORRECTION[b + 1] then + b += 1 + end + return nbits - (l * 8 + b) +end + +-- done(): flush; the frame is e.buf (storage bytes) +function RangeEncoder.done(e: Enc) + local l = 32 - ilog(e.rng) + local msk = floor((CODE_TOP - 1) / 2 ^ l) + local stop = floor((e.val + msk) / (msk + 1)) * (msk + 1) + if stop + msk >= e.val + e.rng then + l += 1 + msk = floor(msk / 2) + stop = floor((e.val + msk) / (msk + 1)) * (msk + 1) + end + while l > 0 do + carryOut(e, floor(stop / 8388608)) + stop = (stop * 256) % CODE_TOP + l -= 8 + end + if e.rem >= 0 or e.ext > 0 then + carryOut(e, 0) + end + local window = e.end_window + local used = e.nend_bits + while used >= 8 do + writeByteAtEnd(e, window % 256) + window = floor(window / 256) + used -= 8 + end + if e.error == 0 then + local a, b = e.offs, e.storage - e.end_offs + if b > a then + buffer.fill(e.buf, a, 0, b - a) + end + if used > 0 then + if e.end_offs >= e.storage then + e.error = -1 + else + l = -l + if e.offs + e.end_offs >= e.storage and l < used then + window = window % 2 ^ l + e.error = -1 + end + local p = e.storage - e.end_offs - 1 + writeu8(e.buf, p, bit32.bor(readu8(e.buf, p), window)) + end + end + end +end + +local _ = CODE_SHIFT +return RangeEncoder diff --git a/src/Formats/audio/opus/init.luau b/src/Formats/audio/opus/init.luau index 08852eb..2d80432 100644 --- a/src/Formats/audio/opus/init.luau +++ b/src/Formats/audio/opus/init.luau @@ -5,14 +5,17 @@ -- Supports: decode of every Opus mode / bandwidth / frame size, mono, stereo and surround (optional stereo downmix, -- opts.stereo), pre-skip, end trimming, output gain, OpusTags, sample-accurate seeking (granule bisection + 80 ms -- pre-roll), damaged files (concealment). Output is always 48 kHz f32. --- Not supported: encoding, mapping family 3 (ambisonics projection), chained streams (the first Opus stream is --- decoded), CELT pitch PLC (noise PLC only). +-- Encoding (audio/opus/Encode + CeltEncoder, ws-m4a): a CELT-only fixed-frame encoder (20 ms, full band, constant +-- bit rate, mono or dual stereo; other input rates resampled to 48 kHz) writing Ogg Opus with OpusTags. +-- Not supported: SILK / hybrid encoding, transients / pitch pre-filter in the encoder, mapping family 3 (ambisonics +-- projection), chained streams (the first Opus stream is decoded), CELT pitch PLC (noise PLC only). -- Changes from opus-luau: the injected Ogg demuxer is containers/Ogg; errors are core/Err values; read() takes an -- optional output buffer; decode() fully decodes to an Audio. -- -- local dec, err = Opus.open(Bytes.reader(buf)) -- the Types.Decoder: dec:read(n, out?), dec:seek(s), ... -- local audio = Opus.decode(Bytes.reader(buf)) -- a Types.Audio -- Opus.Decoder.new(channels) + Opus.Decoder.decode(st, buf, off, len, pcm, base, maxFrames) -- raw packets +-- local file = Opus.encode(audio, { bitrate = 96000 }) -- Ogg Opus (CELT only) -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") @@ -24,6 +27,7 @@ local Packet = require("@formats/audio/opus/Packet") local RangeDecoder = require("@formats/audio/opus/RangeDecoder") local Celt = require("@formats/audio/opus/Celt") local Silk = require("@formats/audio/opus/Silk") +local Encode = require("@formats/audio/opus/Encode") -- ------------------------------------------------------------------------------------------------ contract local Opus = { @@ -31,8 +35,8 @@ local Opus = { category = "audio", extensions = { "opus" }, mime = { "audio/opus", "audio/ogg" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg" }, - caps = { decode = true, encode = false, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 } }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct" }, + caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 }, encodeModes = { "celt" } }, } -- ------------------------------------------------------------------------------------------------ types @@ -213,6 +217,12 @@ function Opus.decode(r: any, opts: OpenOptions?): (Types.Audio?, Err.Err?) return a, nil end +-- ------------------------------------------------------------------------------------------------ encode +-- encode(audio | decoder, opts?) -> Ogg Opus buffer | nil, Err (CELT only; see audio/opus/Encode) +function Opus.encode(value: any, opts: Encode.Options?): (buffer?, Err.Err?) + return Encode.encode(value, opts) +end + -- ------------------------------------------------------------------------------------------------ open local Stream = {} Stream.__index = Stream diff --git a/src/Formats/audio/voc/init.luau b/src/Formats/audio/voc/init.luau new file mode 100644 index 0000000..3feca49 --- /dev/null +++ b/src/Formats/audio/voc/init.luau @@ -0,0 +1,278 @@ +--!strict +-- audio/voc: Creative Voice File (.voc, Sound Blaster). New code from the Creative file format description. +-- Supports: decode / open of block types 1 (sound data: 8-bit unsigned, 16-bit), 2 (continuation), 3 (silence), +-- 5 (text: tags.comment), 8 (extended: stereo / high rates for the next type 1 block), 9 (new sound data: 8-bit +-- unsigned, 16-bit signed, A-law, mu-law, any rate / channel count); markers and repeat loops are skipped (played +-- once, as ffmpeg does); truncated files decode the data present. Encode (Audio or Decoder, streamed) as version +-- 1.20 type 9 blocks of u8 / s16 (default) / alaw / ulaw. Not supported: Creative 4 / 2.6 / 2-bit ADPCM +-- (Err.UNSUPPORTED), blocks that change the channel count mid-file (the sample rate of the first block is used). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/Pcm") + +-- ------------------------------------------------------------------------------------------------ contract +local Voc = { + name = "voc", + category = "audio", + extensions = { "voc" }, + mime = { "audio/x-voc" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" }, + caps = { decode = true, encode = true, streaming = true, depths = { 8, 16 }, lossy = false }, +} + +export type DecodeOptions = { + maxFrames: number?, -- refuse more sample frames (default 2^28) +} +export type EncodeOptions = { + sampleFormat: ("u8" | "s16" | "alaw" | "ulaw")?, -- default "s16" +} + +-- ------------------------------------------------------------------------------------------------ constants +local MAGIC = "Creative Voice File\26" +local T9_CODECS: { [number]: string } = { [0] = "u8", [4] = "s16le", [6] = "alaw", [7] = "ulaw" } +local T1_CODECS: { [number]: string } = { [0] = "u8", [4] = "s16le" } +local WRITE = { u8 = { 0, "u8", 8 }, s16 = { 4, "s16le", 16 }, alaw = { 6, "alaw", 8 }, ulaw = { 7, "ulaw", 8 } } +local MAX_BLOCK = 0xFFFFFF - 12 -- payload bytes of one type 9 block (a 24-bit size, 12 header bytes) + +local readu8 = buffer.readu8 +local function u16(b: buffer, o: number): number + return readu8(b, o) + readu8(b, o + 1) * 256 +end +local function u24(b: buffer, o: number): number + return readu8(b, o) + readu8(b, o + 1) * 256 + readu8(b, o + 2) * 65536 +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Voc.sniff(r: Bytes.Reader): number + return if r:peek(20) == MAGIC then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Segment = { at: number, frames: number, fmt: string? } -- fmt nil: silence + +function Voc.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local b, base, limit = r.buf, r.base, r.limit + if limit - base < 26 or buffer.readstring(b, base, 20) ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "bad magic", base) + end + local hsize = u16(b, base + 20) + local version = u16(b, base + 22) + if hsize < 26 or hsize > limit - base then + return nil, Err.new(Err.CORRUPT, "bad header size", base + 20) + end + local maxFrames = opts and opts.maxFrames or 2 ^ 28 + local rate, channels = 0, 0 + local extRate, extChannels = 0, 0 -- a type 8 block's settings for the next type 1 block + local lastFmt: string? = nil + local codec = -1 + local segments: { Segment } = {} + local total = 0 + local truncated = false + local tags: Types.Tags = {} + local p = base + hsize + -- add(at, bytes, fmt, ch, sr): a run of samples (or silence when fmt is nil and bytes = frames) + local function add(at: number, bytes: number, fmt: string?, ch: number, sr: number): Err.Err? + if channels == 0 then + channels, rate = ch, sr + elseif ch ~= channels then + return Err.new(Err.UNSUPPORTED, "the channel count changes mid-file", at) + end + local frames = if fmt then bytes // (ch * Pcm.Convert.SIZE[fmt]) else bytes + if frames > 0 then + total += frames + if total > maxFrames then + return Err.new(Err.LIMIT, string.format("over the %d frame limit", maxFrames)) + end + table.insert(segments, { at = at, frames = frames, fmt = fmt }) + end + return nil + end + while p < limit do + local t = readu8(b, p) + if t == 0 then + break + end + if p + 4 > limit then + truncated = true + break + end + local size = u24(b, p + 1) + local d = p + 4 + local avail = math.min(size, limit - d) + if avail < size then + truncated = true + end + local err: Err.Err? = nil + if t == 1 then + if avail < 2 then + break + end + local div, c = readu8(b, d), readu8(b, d + 1) + local fmt = T1_CODECS[c] + if not fmt then + return nil, Err.new(Err.UNSUPPORTED, "Creative ADPCM (codec " .. c .. ")", d + 1) + end + local ch, sr = 1, 1000000 // (256 - div) + if extChannels > 0 then + ch, sr = extChannels, extRate + extChannels = 0 + end + lastFmt, codec = fmt, c + err = add(d + 2, avail - 2, fmt, ch, sr) + elseif t == 2 then + if lastFmt == nil then + return nil, Err.new(Err.CORRUPT, "continuation block before any sound data", p) + end + err = add(d, avail, lastFmt, channels, rate) + elseif t == 3 then + if avail < 3 then + break + end + local len, div = u16(b, d) + 1, readu8(b, d + 2) + err = add(d, len, nil, if channels > 0 then channels else 1, if rate > 0 then rate else 1000000 // (256 - div)) + elseif t == 5 then + local s = buffer.readstring(b, d, avail) + local z = string.find(s, "\0", 1, true) + if z then + s = string.sub(s, 1, z - 1) + end + tags.comment = if tags.comment then tags.comment .. "\n" .. s else s + elseif t == 8 then + if avail < 4 then + break + end + local tc, mode = u16(b, d), readu8(b, d + 3) + extChannels = mode + 1 + extRate = 256000000 // (extChannels * (65536 - tc)) + elseif t == 9 then + if avail < 12 then + break + end + local sr = readu8(b, d) + readu8(b, d + 1) * 256 + readu8(b, d + 2) * 65536 + readu8(b, d + 3) * 16777216 + local ch, c = readu8(b, d + 5), u16(b, d + 6) + local fmt = T9_CODECS[c] + if not fmt then + return nil, Err.new(Err.UNSUPPORTED, "codec " .. c, d + 6) + end + if ch < 1 or sr < 1 then + return nil, Err.new(Err.CORRUPT, "bad channels or sample rate", d) + end + lastFmt, codec = fmt, c + err = add(d + 12, avail - 12, fmt, ch, sr) + end + if err then + return nil, err + end + p = d + size + end + if channels == 0 then + return nil, Err.new(if truncated then Err.TRUNCATED else Err.CORRUPT, "no sound data", p) + end + local a = Types.Audio.new(rate, channels, total) + local o = 0 + for _, s in segments do + local n = s.frames * channels + if s.fmt then + Pcm.Convert.decode(b, s.at, s.fmt :: string, n, a.samples, o) + end -- silence: the buffer is already zero + o += n * 4 + end + a.tags = tags + a.meta.source = { + format = "voc", + version = string.format("%d.%02d", version // 256, version % 256), + codec = codec, + sampleFormat = lastFmt, + bitDepth = if lastFmt == "s16le" then 16 else 8, + truncated = truncated or nil, + } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Voc.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local o: EncodeOptions = opts or {} + local spec = WRITE[o.sampleFormat or "s16"] + if not spec then + return nil, Err.new(Err.ARG, "unknown sampleFormat " .. tostring(o.sampleFormat)) + end + if src.channels > 255 then + return nil, Err.new(Err.ARG, "at most 255 channels") + end + if src.sampleRate ~= math.floor(src.sampleRate) or src.sampleRate >= 2 ^ 32 then + return nil, Err.new(Err.ARG, "the sample rate must be an integer") + end + local w = Bytes.writer(65536) + w:string(MAGIC) + w:u16le(26) + w:u16le(0x0114) + w:u16le((0xFFFF - 0x0114 + 0x1234 + 1) % 65536) -- ~version + 0x1234 + if type(src.tags.comment) == "string" and #src.tags.comment > 0 then + local s = string.sub(src.tags.comment, 1, 0xFFFFFE) + w:u8(5) + w:u24le(#s + 1) + w:string(s) + w:u8(0) + end + local size = Pcm.Convert.SIZE[spec[2]] + local frameBytes = size * src.channels + local framesPerBlock = MAX_BLOCK // frameBytes + local blockAt, blockFrames = -1, 0 + local tmp: buffer? = nil + while true do + local bf, n = src:read(math.min(8192, framesPerBlock), tmp) + if n <= 0 then + break + end + tmp = bf + local i = 0 + while i < n do + if blockAt < 0 or blockFrames == framesPerBlock then + blockAt = w:tell() + blockFrames = 0 + w:u8(9) + w:u24le(0) -- patched + w:u32le(src.sampleRate) + w:u8(spec[3]) + w:u8(src.channels) + w:u16le(spec[1]) + w:u32le(0) + end + local take = math.min(n - i, framesPerBlock - blockFrames) + local at = w:reserve(take * frameBytes) + Pcm.Convert.encode(bf, i * src.channels * 4, take * src.channels, spec[2], w.buf, at) + w.pos = at + take * frameBytes + blockFrames += take + i += take + local len = blockFrames * frameBytes + 12 + w:setU8(blockAt + 1, len % 256) + w:setU8(blockAt + 2, (len // 256) % 256) + w:setU8(blockAt + 3, len // 65536) + end + end + if src.err then + return nil, src.err + end + w:u8(0) -- terminator + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Voc.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) + local a, err = Voc.decode(r, opts) + if not a then + return nil, err + end + local dec = Pcm.audioDecoder(a) :: any + dec.source = a.meta.source + return dec, nil +end + +return Voc diff --git a/src/Formats/audio/vorbis/Codebook.luau b/src/Formats/audio/vorbis/Codebook.luau new file mode 100644 index 0000000..19c0da5 --- /dev/null +++ b/src/Formats/audio/vorbis/Codebook.luau @@ -0,0 +1,394 @@ +--!strict +--!native +--!optimize 2 +-- audio/vorbis/Codebook: the Vorbis LSB-first packet bit reader and codebooks (Vorbis I spec sections 2 and 3): +-- reading a codebook from the setup header (ordered / sparse length lists, lookup types 1 and 2, float32_unpack), +-- the codeword assignment, and Huffman / VQ decoding. Ported from stb_vorbis 1.22 (public domain / MIT; see +-- licenses/stb_vorbis-LICENSE.txt): compute_codewords' lowest-free-leaf assignment, lookup1_values; the decode side +-- is a fast table (up to 10 bits) plus a binary tree for longer codes instead of stb's sorted binary search. +-- +-- Never throws. Reading past the packet end gives zero bits and sets br.eop (the spec's end-of-packet condition); +-- an invalid codeword also sets eop and decodes to -1. +local Codebook = {} + +local readu8 = buffer.readu8 +local floor = math.floor + +local POW = table.create(41, 0) +for i = 0, 40 do + POW[i + 1] = 2 ^ i +end + +-- ------------------------------------------------------------------------------------------------ bit reader +export type Br = { + buf: buffer, + pos: number, -- next byte to load + limit: number, + acc: number, -- loaded, unread bits (LSB first) + cnt: number, + pad: number, -- how many of the top bits of acc are past the end of the packet + eop: boolean, -- read past the end of the packet +} + +function Codebook.reader(buf: buffer, offset: number, size: number): Br + return { buf = buf, pos = offset, limit = offset + size, acc = 0, cnt = 0, pad = 0, eop = false } +end + +-- bits(br, n) -> the next n (0..32) bits as an unsigned number +local function bits(br: Br, n: number): number + if n == 0 then + return 0 + end + local acc, cnt = br.acc, br.cnt + if cnt < n then + local b, p, lim = br.buf, br.pos, br.limit + repeat + if p < lim then + acc += readu8(b, p) * POW[cnt + 1] + p += 1 + else + br.pad += 8 + end + cnt += 8 + until cnt >= n + br.pos = p + end + local m = POW[n + 1] + local v = acc % m + br.acc = (acc - v) / m + cnt -= n + br.cnt = cnt + if cnt < br.pad then + br.eop = true + br.pad = cnt + end + return v +end +Codebook.bits = bits + +-- ilog(x): the number of bits needed to hold x (0 for x <= 0) +local function ilog(x: number): number + local n = 0 + while x > 0 do + n += 1 + x = floor(x / 2) + end + return n +end +Codebook.ilog = ilog + +-- float32_unpack (spec 9.2.2) +local function float32Unpack(x: number): number + local mantissa = x % 2097152 + local sign = x >= 2147483648 + local exp = floor((x % 2147483648) / 2097152) + local v = mantissa * 2 ^ (exp - 788) + return if sign then -v else v +end + +-- ------------------------------------------------------------------------------------------------ codebooks +export type Book = { + dims: number, + entries: number, + fastBits: number, + fastLen: { number }, -- per fastBits-bit prefix: code length (> 0), 0 = continue in the tree, -1 = invalid + fastSym: { number }, -- symbol, or the tree node to continue from + c0: { number }, -- tree: child for bit 0 / 1: > 0 node, < 0 leaf (-symbol - 1), 0 none + c1: { number }, + lookup: number, -- 0, 1, 2 + vq: { number }?, -- entries * dims values (lookup 1 / 2, expanded) + used: number, -- entries with a codeword +} + +local MAX_ENTRIES = 2 ^ 20 +local MAX_VQ = 2 ^ 22 + +-- lookup1_values(entries, dims): the largest r with r^dims <= entries +local function lookup1Values(entries: number, dims: number): number + local r = floor(math.exp(math.log(entries) / dims)) + if floor((r + 1) ^ dims) <= entries then + r += 1 + end + if (r + 1) ^ dims <= entries then + return -1 + end + if floor(r ^ dims) > entries then + return -1 + end + return r +end + +-- assign codewords (spec 3.2.1: in entry order, the lowest free leaf) and build the decode tree + fast table +local function build(book: Book, lengths: { number }): string? + local n = book.entries + local c0, c1 = book.c0, book.c1 + local nodes = 1 + c0[1], c1[1] = 0, 0 + local available = table.create(33, 0) -- available[l]: the free code at depth l, as a 32-bit left-aligned value + 1 (0 = none) + local first = true + local used = 0 + local maxLen = 0 + for i = 0, n - 1 do + local len = lengths[i + 1] + if len > 0 then + local code: number + if first then + first = false + code = 0 + for l = 1, len do + available[l + 1] = POW[33 - l] + 1 + end + else + local z = len + while z > 0 and available[z + 1] == 0 do + z -= 1 + end + if z == 0 then + return "over-subscribed codebook" + end + code = available[z + 1] - 1 + available[z + 1] = 0 + for y = len, z + 1, -1 do + available[y + 1] = code + POW[33 - y] + 1 + end + end + -- walk the MSB-first code into the tree + local node = 1 + for d = 1, len do + local bit = floor(code / POW[33 - d]) % 2 + local child = if bit == 0 then c0[node] else c1[node] + if d == len then + if child ~= 0 then + return "ambiguous codeword" + end + if bit == 0 then + c0[node] = -(i + 1) + else + c1[node] = -(i + 1) + end + else + if child < 0 then + return "ambiguous codeword" + elseif child == 0 then + nodes += 1 + c0[nodes], c1[nodes] = 0, 0 + child = nodes + if bit == 0 then + c0[node] = child + else + c1[node] = child + end + end + node = child + end + end + used += 1 + if len > maxLen then + maxLen = len + end + end + end + book.used = used + -- the fast table: every fastBits-bit prefix (read LSB first) walked down the tree + local fb = math.clamp(maxLen, 1, 10) + book.fastBits = fb + local size = POW[fb + 1] + local fl, fs = table.create(size, -1), table.create(size, 0) + for idx = 0, size - 1 do + local node = 1 + local v = idx + for d = 1, fb do + local bit = v % 2 + v = (v - bit) / 2 + local child = if bit == 0 then c0[node] else c1[node] + if child < 0 then + fl[idx + 1], fs[idx + 1] = d, -child - 1 + break + elseif child == 0 then + break -- invalid (-1) + end + node = child + if d == fb then + fl[idx + 1], fs[idx + 1] = 0, node + end + end + end + book.fastLen, book.fastSym = fl, fs + return nil +end + +-- read(br) -> Book | nil, message: one codebook from the setup header +function Codebook.read(br: Br): (Book?, string?) + if bits(br, 24) ~= 0x564342 then + return nil, "bad codebook sync" + end + local dims = bits(br, 16) + local entries = bits(br, 24) + local ordered = bits(br, 1) + if br.eop then + return nil, "setup header ends in a codebook" + end + if dims == 0 and entries ~= 0 then + return nil, "codebook with 0 dimensions" + end + if entries > MAX_ENTRIES then + return nil, "codebook with " .. entries .. " entries" + end + local lengths = table.create(entries, 0) + if ordered == 1 then + local cur = 0 + local len = bits(br, 5) + 1 + while cur < entries do + local num = bits(br, ilog(entries - cur)) + if len >= 32 or cur + num > entries or br.eop then + return nil, "bad ordered codebook lengths" + end + for k = cur + 1, cur + num do + lengths[k] = len + end + cur += num + len += 1 + end + else + local sparse = bits(br, 1) + for j = 1, entries do + if sparse == 0 or bits(br, 1) == 1 then + local l = bits(br, 5) + 1 + if l == 32 then + return nil, "codeword length 32" + end + lengths[j] = l + end + end + end + if br.eop then + return nil, "setup header ends in a codebook" + end + local book: Book = { + dims = dims, + entries = entries, + fastBits = 1, + fastLen = {}, + fastSym = {}, + c0 = {}, + c1 = {}, + lookup = 0, + vq = nil, + used = 0, + } + local err = build(book, lengths) + if err then + return nil, err + end + local lookup = bits(br, 4) + if lookup > 2 then + return nil, "lookup type " .. lookup + end + book.lookup = lookup + if lookup > 0 then + local minimum = float32Unpack(bits(br, 32)) + local delta = float32Unpack(bits(br, 32)) + local valueBits = bits(br, 4) + 1 + local seq = bits(br, 1) == 1 + local nvalues + if lookup == 1 then + nvalues = lookup1Values(entries, dims) + if nvalues < 0 then + return nil, "bad lookup1 size" + end + else + nvalues = entries * dims + end + if nvalues == 0 then + return nil, "empty lookup table" + end + if entries * dims > MAX_VQ or nvalues > MAX_VQ then + return nil, "lookup table too large" + end + local mults = table.create(nvalues, 0) + for j = 1, nvalues do + mults[j] = bits(br, valueBits) + end + if br.eop then + return nil, "setup header ends in a lookup table" + end + -- expand to one vector per entry (spec 3.2.1, "VQ lookup table vector representation") + local vq = table.create(entries * dims, 0) + for e = 0, entries - 1 do + local last = 0 + local div = 1 + for k = 0, dims - 1 do + local off + if lookup == 1 then + off = floor(e / div) % nvalues + div *= nvalues + else + off = e * dims + k + end + local v = mults[off + 1] * delta + minimum + last + if seq then + last = v + end + vq[e * dims + k + 1] = v + end + end + book.vq = vq + end + return book, nil +end + +-- decode(br, book) -> entry number | -1 (end of packet / invalid codeword: br.eop is set) +local function decode(br: Br, book: Book): number + local fb = book.fastBits + local acc, cnt = br.acc, br.cnt + if cnt < fb then + local b, p, lim = br.buf, br.pos, br.limit + repeat + if p < lim then + acc += readu8(b, p) * POW[cnt + 1] + p += 1 + else + br.pad += 8 + end + cnt += 8 + until cnt >= fb + br.pos = p + br.acc, br.cnt = acc, cnt + end + local idx = acc % POW[fb + 1] + 1 + local l = book.fastLen[idx] + if l > 0 then + local m = POW[l + 1] + br.acc = (acc - acc % m) / m + cnt -= l + br.cnt = cnt + if cnt < br.pad then + br.eop = true + br.pad = cnt + return -1 + end + return book.fastSym[idx] + elseif l == 0 then + bits(br, fb) + local node = book.fastSym[idx] + local c0, c1 = book.c0, book.c1 + while true do + local child = if bits(br, 1) == 0 then c0[node] else c1[node] + if br.eop then + return -1 + end + if child < 0 then + return -child - 1 + elseif child == 0 then + br.eop = true + return -1 + end + node = child + end + end + br.eop = true + return -1 +end +Codebook.decode = decode + +return Codebook diff --git a/src/Formats/audio/vorbis/Encode.luau b/src/Formats/audio/vorbis/Encode.luau new file mode 100644 index 0000000..f15a212 --- /dev/null +++ b/src/Formats/audio/vorbis/Encode.luau @@ -0,0 +1,825 @@ +--!strict +--!native +--!optimize 2 +-- audio/vorbis/Encode: a basic but valid Vorbis I encoder in Ogg. New code written from the Vorbis I specification +-- (no libvorbis code). Design: long blocks only (2048 samples; blocksize 0 is declared as 256 but never used), the +-- Vorbis window, the MDCT (codecs/Mdct, scale 4/N for the decoder's unscaled IMDCT); one floor 1 per channel with a +-- fixed post list of 30 points (bisection order, multiplier 2) fitted to the spectral envelope minus a quality- +-- dependent SNR, so the residue is quantized in steps of the floor; stereo square-polar coupling of the integer +-- residues (lossless); residue type 2 with 16-values-per-channel partitions and six classes (silent, |v| <= 1, 4, 15, then +-- cascades of x16 / x256 books for larger values); a fixed codebook set whose Huffman lengths come from Laplacian +-- models computed at load time (codewords assigned exactly as the spec's decoder does). Granules are sample-exact +-- (frames centred on multiples of 1024 from sample 0; the last page's granule trims the end). Never throws. +local Mdct = require("@formats/codecs/Mdct") +local Ogg = require("@formats/containers/Ogg") +local Tables = require("@formats/audio/vorbis/Tables") + +local Encode = {} + +local floor, log, exp, abs = math.floor, math.log, math.exp, math.abs +local writeu8 = buffer.writeu8 + +local POW = table.create(40, 0) +for i = 0, 39 do + POW[i + 1] = 2 ^ i +end + +local N = 2048 +local N2 = 1024 +local PSIZE_PER_CHANNEL = 16 -- residue partitions hold 16 values per channel (libvorbis needs a multiple of ch) +local MULT = 2 -- floor1 multiplier (range 128) +local RANGE = 128 +local NCLASS = 6 + +-- ------------------------------------------------------------------------------------------------ LSB-first bit writer +type W = { buf: buffer, pos: number, acc: number, cnt: number } + +local function newW(size: number): W + return { buf = buffer.create(size), pos = 0, acc = 0, cnt = 0 } +end + +local function put(w: W, v: number, n: number) + if n == 0 then + return + end + local acc = w.acc + v * POW[w.cnt + 1] + local cnt = w.cnt + n + local b, p = w.buf, w.pos + if p + 8 > buffer.len(b) then + local nb = buffer.create(buffer.len(b) * 2 + 64) + buffer.copy(nb, 0, b, 0, p) + b = nb + w.buf = nb + end + while cnt >= 8 do + local byte = acc % 256 + writeu8(b, p, byte) + p += 1 + acc = (acc - byte) / 256 + cnt -= 8 + end + w.acc, w.cnt, w.pos = acc, cnt, p +end + +local function finish(w: W): buffer + if w.cnt > 0 then + put(w, 0, 8 - w.cnt) + end + local out = buffer.create(w.pos) + buffer.copy(out, 0, w.buf, 0, w.pos) + return out +end + +local function putString(w: W, s: string) + for i = 1, #s do + put(w, string.byte(s, i), 8) + end +end + +local function ilog(x: number): number + local n = 0 + while x > 0 do + n += 1 + x = floor(x / 2) + end + return n +end + +-- ------------------------------------------------------------------------------------------------ codebooks +type Book = { + dims: number, + entries: number, + lengths: { number }, + codes: { number }, -- bit-reversed codewords (ready for the LSB-first writer) + lookup: number, -- 0 or 1 + minimum: number, + delta: number, + values: number, -- lookup1 values per dimension +} + +-- Huffman code lengths for weights w[1..n] (all > 0), at most 24 bits long (weights are floored to keep it so) +local function huffmanLengths(w: { number }): { number } + local n = #w + local total = 0 + for i = 1, n do + total += w[i] + end + local lens = table.create(n, 0) + if n == 1 then + lens[1] = 1 + return lens + end + local minw = total * 2 ^ -20 + -- nodes: leaves 1..n then internal; a simple O(n^2)-free approach with two sorted queues + local order = table.create(n, 0) + for i = 1, n do + order[i] = i + end + local weight = table.create(2 * n, 0) + local parent = table.create(2 * n, 0) + for i = 1, n do + weight[i] = math.max(w[i], minw) + end + table.sort(order, function(a: number, b: number): boolean + if weight[a] ~= weight[b] then + return weight[a] < weight[b] + end + return a < b + end) + local q1, h1 = order, 1 -- leaves, ascending + local q2, h2, t2 = table.create(n, 0), 1, 0 -- internal nodes, created in ascending weight order + local nextId = n + local function pop(): number + local a = if h1 <= n then q1[h1] else nil + local b = if h2 <= t2 then q2[h2] else nil + if a and (not b or weight[a] <= weight[b]) then + h1 += 1 + return a + end + h2 += 1 + return b :: number + end + for _ = 1, n - 1 do + local a = pop() + local b = pop() + nextId += 1 + weight[nextId] = weight[a] + weight[b] + parent[a], parent[b] = nextId, nextId + t2 += 1 + q2[t2] = nextId + end + for i = 1, n do + local d, x = 0, i + while parent[x] ~= 0 do + x = parent[x] + d += 1 + end + lens[i] = d + end + return lens +end + +-- the spec's codeword assignment (lowest free leaf, in entry order); returns bit-reversed codes +local function assign(lens: { number }): { number } + local codes = table.create(#lens, 0) + local available = table.create(33, 0) + local first = true + for i, len in lens do + if len > 0 then + local code + if first then + first = false + code = 0 + for l = 1, len do + available[l + 1] = POW[33 - l] + 1 + end + else + local z = len + while z > 0 and available[z + 1] == 0 do + z -= 1 + end + code = available[z + 1] - 1 + available[z + 1] = 0 + for y = len, z + 1, -1 do + available[y + 1] = code + POW[33 - y] + 1 + end + end + -- the top len bits of the 32-bit left-aligned code, MSB first, reversed for the LSB-first writer + local msb = floor(code / POW[33 - len]) + local rev = 0 + for _ = 1, len do + rev = rev * 2 + msb % 2 + msb = floor(msb / 2) + end + codes[i] = rev + end + end + return codes +end + +local function makeBook(dims: number, entries: number, weight: (number) -> number, lookup: number, minimum: number, delta: number, values: number): Book + local w = table.create(entries, 0) + for e = 0, entries - 1 do + w[e + 1] = weight(e) + end + local lens = huffmanLengths(w) + return { dims = dims, entries = entries, lengths = lens, codes = assign(lens), lookup = lookup, minimum = minimum, delta = delta, values = values } +end + +-- a VQ book of `dims` dimensions over integer values -h .. h times `scale`, Laplacian weights exp(-|v| / s) +local function vqBook(dims: number, h: number, scale: number, s: number, zeroBoost: number): Book + local values = 2 * h + 1 + local entries = values ^ dims + return makeBook(dims, entries, function(e: number): number + local wt = 1 + local x = e + for _ = 1, dims do + local v = x % values - h + x = x // values + wt *= exp(-abs(v) / s) * (if v == 0 then zeroBoost else 1) + end + return wt + end, 1, -h * scale, scale, values) +end + +local BOOK_FLOOR = makeBook(1, RANGE, function(e: number): number + return exp(-e / 7) + 0.002 +end, 0, 0, 0, 0) +local CLASS_W = { 0.30, 0.30, 0.20, 0.12, 0.06, 0.02 } +local BOOK_CLASS = makeBook(2, NCLASS * NCLASS, function(e: number): number + return CLASS_W[e % NCLASS + 1] * CLASS_W[e // NCLASS + 1] +end, 0, 0, 0, 0) +local BOOK_A = vqBook(4, 1, 1, 0.6, 2.5) -- |v| <= 1, 4 at a time (mostly zeros) +local BOOK_B = vqBook(2, 4, 1, 1.4, 1) -- |v| <= 4 +local BOOK_C = vqBook(2, 15, 1, 4, 1) -- |v| <= 15 +local BOOK_D = vqBook(2, 15, 16, 3, 1) -- multiples of 16 up to 240 +local BOOK_E = vqBook(2, 15, 256, 3, 1) -- multiples of 256 up to 3840 +local BOOKS = { BOOK_FLOOR, BOOK_CLASS, BOOK_A, BOOK_B, BOOK_C, BOOK_D, BOOK_E } +local FLOOR_BOOK, CLASS_BOOK, A_BOOK, B_BOOK, C_BOOK, D_BOOK, E_BOOK = 0, 1, 2, 3, 4, 5, 6 +-- the books of each residue class per pass (book numbers; -1 = none) +local CLASS_BOOKS = { + { -1, -1, -1 }, + { A_BOOK, -1, -1 }, + { B_BOOK, -1, -1 }, + { C_BOOK, -1, -1 }, + { D_BOOK, C_BOOK, -1 }, + { E_BOOK, D_BOOK, C_BOOK }, +} +local CLASS_MAX = { 0, 1, 4, 15, 255, 4095 } + +-- float32_pack (spec 9.2.2) of an integer-valued x +local function float32Pack(x: number): number + local sign = if x < 0 then 2147483648 else 0 + local m = abs(x) + local e = 788 + while m >= 2097152 do + m /= 2 + e += 1 + end + return sign + e * 2097152 + floor(m) +end + +local function writeBook(w: W, b: Book) + put(w, 0x564342, 24) + put(w, b.dims, 16) + put(w, b.entries, 24) + put(w, 0, 1) -- not ordered + put(w, 0, 1) -- not sparse + for i = 1, b.entries do + put(w, b.lengths[i] - 1, 5) + end + put(w, b.lookup, 4) + if b.lookup == 1 then + put(w, float32Pack(b.minimum), 32) + put(w, float32Pack(b.delta), 32) + local vb = ilog(b.values - 1) + put(w, vb - 1, 4) + put(w, 0, 1) -- sequence_p + for j = 0, b.values - 1 do + put(w, j, vb) + end + end +end + +local function putEntry(w: W, b: Book, e: number) + put(w, b.codes[e + 1], b.lengths[e + 1]) +end + +-- ------------------------------------------------------------------------------------------------ floor posts +-- x positions: 0, 1024, then 28 log-spaced points in bisection order (coarse first) so predictions are good +local POSTS: { number } = { 0, N2 } +do + local xs = {} + local seen = { [0] = true, [N2] = true } + for j = 0, 27 do + local x = floor(3 + 957 * (j / 27) ^ 2.2 + 0.5) -- 3 .. 960, denser at low frequencies + while seen[x] do + x += 1 + end + seen[x] = true + table.insert(xs, x) + end + table.sort(xs) + -- bisection order over the sorted list + local queue = { { 1, #xs } } + local qh = 1 + while qh <= #queue do + local r = queue[qh] + qh += 1 + if r[1] <= r[2] then + local m = (r[1] + r[2]) // 2 + table.insert(POSTS, xs[m]) + table.insert(queue, { r[1], m - 1 }) + table.insert(queue, { m + 1, r[2] }) + end + end +end +local NPOSTS = #POSTS -- 30 +local FLOOR_PARTS = (NPOSTS - 2) // 4 -- 7 partitions of one class with 4 dimensions +local SORTED: { number } = table.create(NPOSTS, 0) -- post indices (1-based) by increasing x +for i = 1, NPOSTS do + SORTED[i] = i +end +table.sort(SORTED, function(a: number, b: number): boolean + return POSTS[a] < POSTS[b] +end) +local LOW, HIGH = table.create(NPOSTS, 0), table.create(NPOSTS, 0) +for j = 3, NPOSTS do + local lo, hi = -1, 65536 + local x = POSTS[j] + for k = 1, j - 1 do + local xv = POSTS[k] + if xv > lo and xv < x then + LOW[j], lo = k, xv + end + if xv < hi and xv > x then + HIGH[j], hi = k, xv + end + end +end +-- the floor value (0..127) closest to an amplitude, through the spec's inverse dB table +local DB = table.create(RANGE, 0) +for y = 0, RANGE - 1 do + DB[y + 1] = 20 * math.log10(Tables[y * MULT + 1]) +end +local function yOf(db: number): number + local y = floor((db - DB[1]) / (DB[RANGE] - DB[1]) * (RANGE - 1) + 0.5) + return math.clamp(y, 0, RANGE - 1) +end + +local function predict(x: number, x0: number, x1: number, y0: number, y1: number): number + local dy = y1 - y0 + local adx = x1 - x0 + local off = (abs(dy) * (x - x0)) // adx + return if dy < 0 then y0 - off else y0 + off +end + +-- render the decoder's floor curve for final Y values into F[1..N2] (only the posts the decoder marks used) +local function renderFloor(Y: { number }, used: { boolean }, F: { number }) + local lx, ly = 0, Y[1] * MULT + for q = 2, NPOSTS do + local j = SORTED[q] + if not used[j] then + continue + end + local hx, hy = POSTS[j], Y[j] * MULT + -- draw_line(lx, ly, hx, hy) + local dy = hy - ly + local adx = hx - lx + local ady = abs(dy) + local base = if dy < 0 then -(ady // adx) else ady // adx + local sy = if dy < 0 then base - 1 else base + 1 + ady -= abs(base) * adx + local x, y, err = lx, ly, 0 + local x1 = math.min(hx, N2) + if x < x1 then + F[x + 1] = Tables[y % 256 + 1] + x += 1 + while x < x1 do + err += ady + if err >= adx then + err -= adx + y += sy + else + y += base + end + F[x + 1] = Tables[y % 256 + 1] + x += 1 + end + end + lx, ly = hx, hy + end + for x = lx + 1, N2 do + F[x] = Tables[ly % 256 + 1] + end +end + +-- the coded value for target t at post j given the final values of its neighbours (spec 7.2.4 step 1, inverted) +local function floorVal(Y: { number }, j: number): number + local lo, hi = LOW[j], HIGH[j] + local pred = predict(POSTS[j], POSTS[lo], POSTS[hi], Y[lo], Y[hi]) + local t = Y[j] + local d = t - pred + if d == 0 then + return 0 + end + local highroom = RANGE - pred + local lowroom = pred + local room = if highroom < lowroom then highroom * 2 else lowroom * 2 + local cands = { if d > 0 then 2 * d else -2 * d - 1, d + lowroom, -d + highroom - 1 } + for _, v in cands do + if v > 0 and v < RANGE then + local got + if v >= room then + got = if highroom > lowroom then v - lowroom + pred else pred - v + highroom - 1 + elseif v % 2 == 1 then + got = pred - (v + 1) // 2 + else + got = pred + v // 2 + end + if got == t then + return v + end + end + end + return 0 -- unreachable for t in range; fall back to the prediction +end + +-- ------------------------------------------------------------------------------------------------ headers +local function identHeader(ch: number, rate: number, nominal: number): buffer + local w = newW(64) + put(w, 1, 8) + putString(w, "vorbis") + put(w, 0, 32) + put(w, ch, 8) + put(w, rate, 32) + put(w, 0, 32) + put(w, nominal, 32) + put(w, 0, 32) + put(w, 8, 4) -- blocksize 0: 256 + put(w, 11, 4) -- blocksize 1: 2048 + put(w, 1, 1) + return finish(w) +end + +local function commentHeader(vendor: string, tags: { [string]: string }): buffer + local w = newW(256) + put(w, 3, 8) + putString(w, "vorbis") + put(w, #vendor, 32) + putString(w, vendor) + local keys = {} + for k, v in tags do + if type(k) == "string" and type(v) == "string" then + table.insert(keys, k) + end + end + table.sort(keys) + put(w, #keys, 32) + for _, k in keys do + local name = if k == "track" then "TRACKNUMBER" else string.upper(k) + local s = name .. "=" .. tags[k] + put(w, #s, 32) + putString(w, s) + end + put(w, 1, 1) + return finish(w) +end + +local function setupHeader(ch: number): buffer + local w = newW(8192) + put(w, 5, 8) + putString(w, "vorbis") + -- codebooks + put(w, #BOOKS - 1, 8) + for _, b in BOOKS do + writeBook(w, b) + end + -- time domain placeholders + put(w, 0, 6) + put(w, 0, 16) + -- one floor 1 + put(w, 0, 6) + put(w, 1, 16) + put(w, FLOOR_PARTS, 5) + for _ = 1, FLOOR_PARTS do + put(w, 0, 4) -- class 0 + end + put(w, 3, 3) -- class 0: 4 dimensions + put(w, 0, 2) -- no subclasses + put(w, FLOOR_BOOK + 1, 8) -- its one subclass book (+1) + put(w, MULT - 1, 2) + put(w, 10, 4) -- rangebits: x in 0 .. 1024 + for j = 3, NPOSTS do + put(w, POSTS[j], 10) + end + -- one residue 2 + put(w, 0, 6) + put(w, 2, 16) + put(w, 0, 24) -- begin + put(w, N2 * ch, 24) -- end + put(w, PSIZE_PER_CHANNEL * ch - 1, 24) + put(w, NCLASS - 1, 6) + put(w, CLASS_BOOK, 8) + for c = 1, NCLASS do + local bits = 0 + for pass = 1, 3 do + if CLASS_BOOKS[c][pass] >= 0 then + bits += POW[pass] + end + end + put(w, bits % 8, 3) + if bits >= 8 then + put(w, 1, 1) + put(w, bits // 8, 5) + else + put(w, 0, 1) + end + end + for c = 1, NCLASS do + for pass = 1, 3 do + local b = CLASS_BOOKS[c][pass] + if b >= 0 then + put(w, b, 8) + end + end + end + -- one mapping + put(w, 0, 6) + put(w, 0, 16) + put(w, 0, 1) -- one submap + if ch == 2 then + put(w, 1, 1) + put(w, 0, 8) -- one coupling step + put(w, 0, 1) -- magnitude: channel 0 + put(w, 1, 1) -- angle: channel 1 + else + put(w, 0, 1) + end + put(w, 0, 2) + put(w, 0, 8) -- submap 0: time (unused) + put(w, 0, 8) -- floor 0 + put(w, 0, 8) -- residue 0 + -- one mode: long blocks + put(w, 0, 6) + put(w, 1, 1) + put(w, 0, 16) + put(w, 0, 16) + put(w, 0, 8) + put(w, 1, 1) -- framing + return finish(w) +end + +-- ------------------------------------------------------------------------------------------------ encoder +export type Source = { + sampleRate: number, + channels: number, + frames: number, + tags: { [string]: string }, + read: (self: any, n: number, out: buffer?) -> (buffer, number), + err: any, +} +export type Options = { + quality: number, -- -1 .. 10 + vendor: string, + serial: number, +} + +-- the residue of one partition: vectors of each pass for class c +local function writePartition(w: W, v: { number }, o: number, psize: number, c: number, pass: number) + local b = CLASS_BOOKS[c][pass] + if b < 0 then + return + end + local book = BOOKS[b + 1] + local dims, h = book.dims, (book.values - 1) // 2 + local scale = book.delta + local values = book.values + local i = 0 + while i < psize do + local e = 0 + local m = 1 + for k = 0, dims - 1 do + local x = v[o + i + k + 1] + -- the part of x this pass carries (coarse passes take the rounded multiple of their scale) + local q + if pass < 3 and CLASS_BOOKS[c][pass + 1] >= 0 then + q = math.clamp(floor(x / scale + 0.5), -h, h) + else + q = math.clamp(x // scale, -h, h) + end + v[o + i + k + 1] = x - q * scale + e += (q + h) * m + m *= values + end + putEntry(w, book, e) + i += dims + end +end + +function Encode.encode(src: Source, opts: Options): (buffer?, string?) + local ch, rate = src.channels, src.sampleRate + local q = math.clamp(opts.quality, -1, 10) + local snrDb = 2 * q - 1 -- floor level below the band energy (at low frequencies; 8 dB less at the top) + local mux = Ogg.muxer({ pageSize = 4096 }) + local stream = mux:stream(opts.serial) + local nominal = floor(math.clamp(rate * ch * (0.6 + 0.12 * q), 32000, 500000)) + stream:packet(identHeader(ch, rate, nominal), 0, { flush = true }) + stream:packet(commentHeader(opts.vendor, src.tags), 0) + stream:packet(setupHeader(ch), 0, { flush = true }) + local plan = Mdct.new(N) :: Mdct.Plan + local win = Mdct.window("vorbis", N) :: { number } + -- input ring: per channel the samples of the current frame [k*1024 - 1024, k*1024 + 1024) + local frame = table.create(ch) + for c = 1, ch do + frame[c] = table.create(N, 0) + end + local blk = table.create(N, 0) + local X = table.create(ch) + local R = table.create(ch) + for c = 1, ch do + X[c] = table.create(N2, 0) + R[c] = table.create(N2, 0) + end + local F = table.create(N2, 0) + local Y = table.create(NPOSTS, 0) + local vals = table.create(NPOSTS, 0) + local used = table.create(NPOSTS, false) + local inter = table.create(N2 * ch, 0) + local psize = PSIZE_PER_CHANNEL * ch + local npart = N2 * ch // psize + local classes = table.create(npart + 2, 0) + local total = 0 + local srcDone = false + local tmp: buffer? = nil + local pending: buffer? = nil + local pendN, pendOff = 0, 0 + local k = 0 + local lastWanted = -1 -- the last packet index needed (known once the input ends) + while true do + -- shift in the next 1024 input samples (zeros past the end) + for c = 1, ch do + local fr = frame[c] + table.move(fr, N2 + 1, N, 1) + end + local got = 0 + while got < N2 and not srcDone do + if pendN == 0 then + local b, n = src:read(4096, tmp) + if n <= 0 then + srcDone = true + break + end + tmp = b + pending, pendN, pendOff = b, n, 0 + end + local take = math.min(N2 - got, pendN) + local pb = pending :: buffer + for i = 0, take - 1 do + local base = (pendOff + i) * ch * 4 + for c = 1, ch do + frame[c][N2 + got + i + 1] = buffer.readf32(pb, base + (c - 1) * 4) + end + end + got += take + pendN -= take + pendOff += take + end + for c = 1, ch do + local fr = frame[c] + for i = N2 + got + 1, N do + fr[i] = 0 + end + end + total += got + if srcDone and lastWanted < 0 then + lastWanted = (total + N2 - 1) // N2 -- packets 0 .. lastWanted (packet j returns [(j-1)*1024, j*1024)) + end + -- this frame is centred on k*1024; its first half is [k*1024 - 1024, k*1024) + -- (frame k holds input [(k - 1) * 1024, (k + 1) * 1024): the shift above moved the window by 1024) + -- MDCT per channel + local energy = 0 + for c = 1, ch do + local fr = frame[c] + for i = 1, N do + blk[i] = fr[i] * win[i] + end + Mdct.forward(plan, blk, 1, X[c], 1, 1, 4 / N) + local xc = X[c] + for i = 1, N2 do + energy += xc[i] * xc[i] + end + end + local w = newW(2048) + put(w, 0, 1) -- audio packet + -- (one mode: 0 bits) long block, previous and next long + put(w, 1, 1) + put(w, 1, 1) + local silent = energy < 1e-18 + if silent then + for _ = 1, ch do + put(w, 0, 1) -- no floor: the channel is zero + end + else + -- the floor from the loudest channel's band energies at each post + for j = 1, NPOSTS do + local x = POSTS[j] + -- the band around x: halfway to the neighbouring posts in x order + local idx = table.find(SORTED, j) :: number + local lo = if idx > 1 then (POSTS[SORTED[idx - 1]] + x) // 2 else 0 + local hi = if idx < NPOSTS then (POSTS[SORTED[idx + 1]] + x) // 2 else N2 - 1 + if hi < lo then + hi = lo + end + local e = 0 + for c = 1, ch do + local xc = X[c] + local s = 0 + for i = lo + 1, math.min(hi + 1, N2) do + s += xc[i] * xc[i] + end + s /= (hi - lo + 1) + if s > e then + e = s + end + end + local db = if e > 0 then 10 * math.log10(e) - snrDb + 8 * x / N2 else -200 + Y[j] = yOf(db) + end + -- the decoder's step 2 flags: a point is drawn when its value or a later neighbour's value is nonzero + used[1], used[2] = true, true + for j = 3, NPOSTS do + local v = floorVal(Y, j) + vals[j] = v + used[j] = v ~= 0 + if v ~= 0 then + used[LOW[j]], used[HIGH[j]] = true, true + end + end + renderFloor(Y, used, F) + -- residues: X / F rounded, then coupling, then interleaving + for c = 1, ch do + local xc, rc = X[c], R[c] + for i = 1, N2 do + local v = floor(xc[i] / F[i] + 0.5) + rc[i] = math.clamp(v, -4095, 4095) + end + end + if ch == 2 then + local l, r = R[1], R[2] + for i = 1, N2 do + local a, b = l[i], r[i] + local m, an + if abs(a) > abs(b) then + m = a + an = if a > 0 then a - b else b - a + else + m = b + an = if b > 0 then a - b else b - a + end + -- keep the angle inside the books' range + l[i], r[i] = m, math.clamp(an, -4095, 4095) + end + end + for c = 1, ch do + local rc = R[c] + for i = 1, N2 do + inter[(i - 1) * ch + c] = rc[i] + end + end + -- floors + for _ = 1, ch do + put(w, 1, 1) + put(w, Y[1], 7) + put(w, Y[2], 7) + for j = 3, NPOSTS do + putEntry(w, BOOK_FLOOR, vals[j]) + end + end + -- residue classes + for p = 0, npart - 1 do + local m = 0 + for i = 1, psize do + local a = abs(inter[p * psize + i]) + if a > m then + m = a + end + end + local c = 1 + while CLASS_MAX[c] < m do + c += 1 + end + classes[p + 1] = c + end + classes[npart + 1] = 1 + for pass = 1, 3 do + for p = 0, npart - 1, 2 do + if pass == 1 then + putEntry(w, BOOK_CLASS, (classes[p + 1] - 1) * NCLASS + (classes[p + 2] - 1)) -- first partition: the high digit + end + writePartition(w, inter, p * psize, psize, classes[p + 1], pass) + if p + 1 < npart then + writePartition(w, inter, (p + 1) * psize, psize, classes[p + 2], pass) + end + end + end + end + local pk = finish(w) + local last = lastWanted >= 0 and k >= lastWanted + local granule = if k == 0 then 0 else math.min(k * N2, if lastWanted >= 0 then total else math.huge) + stream:packet(pk, granule, if last then { eos = true } else nil) + if last then + break + end + k += 1 + end + if src.err then + return nil, tostring(src.err) + end + return mux:finish(), nil +end + +-- the codebooks (tests check the Huffman lengths are a valid prefix code) +Encode.BOOKS = BOOKS + +return Encode diff --git a/src/Formats/audio/vorbis/Packet.luau b/src/Formats/audio/vorbis/Packet.luau new file mode 100644 index 0000000..ca69d79 --- /dev/null +++ b/src/Formats/audio/vorbis/Packet.luau @@ -0,0 +1,586 @@ +--!strict +--!native +--!optimize 2 +-- audio/vorbis/Packet: Vorbis audio packet decoding (Vorbis I spec sections 4.3, 7, 8): mode and window shape, floor 1 +-- curves, residue types 0 / 1 / 2, inverse channel coupling, the IMDCT (codecs/Mdct), windowing and overlap-add. +-- Floors, residues and coupling are ported from stb_vorbis 1.22 vorbis_decode_packet_rest / decode_residue / +-- do_floor / draw_line (public domain / MIT; see licenses/stb_vorbis-LICENSE.txt). The overlap follows libvorbis: +-- each packet after the first returns the n_prev/4 + n_cur/4 samples between the centres of the two windows, so +-- granule positions count exactly the samples returned (the first packet returns none). +-- +-- local st = Packet.new(ident, setup) +-- local n = Packet.decode(st, buf, offset, size) -- frames now in st.out[ch][1 .. n]; -1 = not an audio packet +-- Packet.reset(st) -- forget the overlap (after a seek / a gap) +-- local bs = Packet.blocksize(st, buf, offset, size) -- the packet's block size (0 = not audio), header bits only +-- Never throws: a damaged packet decodes as far as its bits go (the spec's end-of-packet rule) or returns -1. +local Codebook = require("@formats/audio/vorbis/Codebook") +local Setup = require("@formats/audio/vorbis/Setup") +local Tables = require("@formats/audio/vorbis/Tables") +local Mdct = require("@formats/codecs/Mdct") + +local Packet = {} + +local bits, decode = Codebook.bits, Codebook.decode +local ilog = Codebook.ilog +local INV_DB = Tables +local RANGE = { 256, 128, 86, 64 } + +export type State = { + channels: number, + n0: number, + n1: number, + setup: Setup.Setup, + plans: { [number]: Mdct.Plan }, + slopes: { [number]: { number } }, -- rising half-window of overlap length L (= blocksize / 2) + spec: { { number } }, -- per channel: n/2 spectral values (residue, then times the floor) + frame: { { number } }, -- per channel: n windowed time samples + tail: { { number } }, -- per channel: the previous frame from its centre on + tailLen: number, + prevN: number, -- the previous block size, 0 = no previous frame + out: { { number } }, -- per channel: the returned samples + finalY: { { number } }, + step2: { number }, + inter: { number }, -- residue type 2 interleaved scratch + zero: { boolean }, + reallyZero: { boolean }, + partClass: { { { number } } }, +} + +function Packet.new(id: Setup.Ident, setup: Setup.Setup): State? + local n0, n1, ch = id.blocksize0, id.blocksize1, id.channels + local plans: { [number]: Mdct.Plan } = {} + local slopes: { [number]: { number } } = {} + for _, n in { n0, n1 } do + local p = Mdct.new(n) + if not p then + return nil + end + plans[n] = p + local w = Mdct.window("vorbis", n) :: { number } + local half = table.create(n // 2, 0) + for i = 1, n // 2 do + half[i] = w[i] + end + slopes[n // 2] = half + end + local function arrays(len: number): { { number } } + local t = table.create(ch) + for c = 1, ch do + t[c] = table.create(len, 0) + end + return t + end + local partClass = table.create(ch) + for c = 1, ch do + partClass[c] = {} + end + return { + channels = ch, + n0 = n0, + n1 = n1, + setup = setup, + plans = plans, + slopes = slopes, + spec = arrays(n1 // 2), + frame = arrays(n1), + tail = arrays(n1 // 2), + tailLen = 0, + prevN = 0, + out = arrays(n1), + finalY = arrays(math.max(2, setup.maxFloorValues)), + step2 = table.create(math.max(2, setup.maxFloorValues), 0), + inter = table.create(n1 // 2 * ch, 0), + zero = table.create(ch, false), + reallyZero = table.create(ch, false), + partClass = partClass, + } +end + +function Packet.reset(st: State) + st.prevN = 0 + st.tailLen = 0 +end + +-- blocksize(st, buf, off, size) -> the block size of an audio packet (0 if not audio) +function Packet.blocksize(st: State, b: buffer, off: number, size: number): number + if size < 1 then + return 0 + end + local br = Codebook.reader(b, off, size) + if bits(br, 1) ~= 0 then + return 0 + end + local m = bits(br, st.setup.modeBits) + local mode = st.setup.modes[m + 1] + if not mode or br.eop then + return 0 + end + return if mode.blockflag == 1 then st.n1 else st.n0 +end + +-- ------------------------------------------------------------------------------------------------ floor 1 +local function predict(x: number, x0: number, x1: number, y0: number, y1: number): number + local dy = y1 - y0 + local adx = x1 - x0 + local off = ((if dy < 0 then -dy else dy) * (x - x0)) // adx + return if dy < 0 then y0 - off else y0 + off +end + +-- multiply out[x0 .. x1) by the floor line from (x0, y0) to (x1, y1) (stb draw_line) +local function drawLine(out: { number }, x0: number, y0: number, x1: number, y1: number, n: number) + local dy = y1 - y0 + local adx = x1 - x0 + local ady = if dy < 0 then -dy else dy + local base = if dy < 0 then -(ady // adx) else ady // adx + local sy = if dy < 0 then base - 1 else base + 1 + ady -= (if base < 0 then -base else base) * adx + if x1 > n then + x1 = n + end + local x, y, err = x0, y0, 0 + if x < x1 then + out[x + 1] *= INV_DB[y % 256 + 1] + x += 1 + while x < x1 do + err += ady + if err >= adx then + err -= adx + y += sy + else + y += base + end + out[x + 1] *= INV_DB[y % 256 + 1] + x += 1 + end + end +end + +-- decode the floor of one channel into finalY (-1 = unused point); false = this channel is silent +local function floorDecode(st: State, br: Codebook.Br, g: Setup.Floor1, finalY: { number }): boolean + if bits(br, 1) == 0 then + return false + end + local books = st.setup.books + local range = RANGE[g.multiplier] + local yb = ilog(range) - 1 + finalY[1] = bits(br, yb) + finalY[2] = bits(br, yb) + local offset = 2 + for j = 1, g.partitions do + local pclass = g.partitionClass[j] + 1 + local cdim = g.classDims[pclass] + local cbits = g.classSubs[pclass] + local csub = 2 ^ cbits + local cval = 0 + if cbits > 0 then + cval = decode(br, books[g.classMaster[pclass] + 1]) + if cval < 0 then + return false + end + end + local subs = g.subBooks[pclass] + for _ = 1, cdim do + local book = subs[cval % csub + 1] + cval = cval // csub + if book >= 0 then + local v = decode(br, books[book + 1]) + if v < 0 then + return false + end + finalY[offset + 1] = v + else + finalY[offset + 1] = 0 + end + offset += 1 + end + end + if br.eop then + return false + end + -- step 1: amplitude value synthesis + local step2 = st.step2 + step2[1], step2[2] = 1, 1 + local xl, low, high = g.xlist, g.low, g.high + for j = 2, g.values - 1 do + local lo, hi = low[j + 1], high[j + 1] + local pred = predict(xl[j + 1], xl[lo + 1], xl[hi + 1], finalY[lo + 1], finalY[hi + 1]) + local val = finalY[j + 1] + local highroom = range - pred + local lowroom = pred + local room = if highroom < lowroom then highroom * 2 else lowroom * 2 + if val ~= 0 then + step2[lo + 1], step2[hi + 1], step2[j + 1] = 1, 1, 1 + if val >= room then + if highroom > lowroom then + finalY[j + 1] = val - lowroom + pred + else + finalY[j + 1] = pred - val + highroom - 1 + end + elseif val % 2 == 1 then + finalY[j + 1] = pred - (val + 1) // 2 + else + finalY[j + 1] = pred + val // 2 + end + else + step2[j + 1] = 0 + finalY[j + 1] = pred + end + end + for j = 1, g.values do + if step2[j] == 0 then + finalY[j] = -1 + end + end + return true +end + +-- multiply target[1 .. n2] by the floor curve (stb do_floor) +local function floorCurve(g: Setup.Floor1, finalY: { number }, target: { number }, n2: number) + local mult = g.multiplier + local lx, ly = 0, finalY[1] * mult + local sorted, xl = g.sorted, g.xlist + for q = 2, g.values do + local j = sorted[q] + 1 + local fy = finalY[j] + if fy >= 0 then + local hy = fy * mult + local hx = xl[j] + if lx ~= hx then + drawLine(target, lx, ly, hx, hy, n2) + end + lx, ly = hx, hy + end + end + if lx < n2 then + local v = INV_DB[ly % 256 + 1] + for j = lx + 1, n2 do + target[j] *= v + end + end +end + +-- ------------------------------------------------------------------------------------------------ residue +-- add the vectors of one partition to target at offset (0-based) .. offset + psize (bounded by limit) +local function partition(br: Codebook.Br, book: Codebook.Book, target: { number }, offset: number, psize: number, rtype: number, limit: number): boolean + local vq = book.vq + if not vq then + br.eop = true -- a scalar book in a vector context: invalid stream + return false + end + local dims = book.dims + if rtype == 0 then + local step = psize // dims + for k = 0, step - 1 do + local e = decode(br, book) + if e < 0 then + return false + end + local base = e * dims + for i = 0, dims - 1 do + local at = offset + k + i * step + if at < limit then + target[at + 1] += vq[base + i + 1] + end + end + end + else + local k = 0 + while k < psize do + local e = decode(br, book) + if e < 0 then + return false + end + local base = e * dims + local len = math.min(dims, psize - k) + local at = offset + k + for i = 0, len - 1 do + if at + i < limit then + target[at + i + 1] += vq[base + i + 1] + end + end + k += dims + end + end + return true +end + +-- decode residue r for the channels `targets` (nil = do not decode) of length n2 each +local function residue(st: State, br: Codebook.Br, r: Setup.Residue, targets: { { number } | false }, ch: number, n2: number) + local books = st.setup.books + local rtype = r.type + local cbook = books[r.classbook + 1] + local classwords = cbook.dims + for j = 1, ch do + local t = targets[j] + if t then + for i = 1, n2 do + (t :: { number })[i] = 0 + end + end + end + local any = false + for j = 1, ch do + if targets[j] then + any = true + end + end + if not any then + return + end + local psize = r.partSize + local rb = r.books + local classdata = r.classdata + if rtype == 2 and ch > 1 then + local total = n2 * ch + local inter = st.inter + for i = 1, total do + inter[i] = 0 + end + local lb = math.min(r.begin, total) + local le = math.min(r.finish, total) + local partRead = (le - lb) // psize + local pc = st.partClass[1] + local done = false + for pass = 1, 8 do + if done then + break + end + local pcount, classSet = 0, 1 + while pcount < partRead do + if pass == 1 then + local q = decode(br, cbook) + if q < 0 then + done = true + break + end + pc[classSet] = classdata[q + 1] + end + local cls = pc[classSet] + local i = 0 + while i < classwords and pcount < partRead do + local b = rb[cls[i + 1] + 1][pass] + if b >= 0 then + if not partition(br, books[b + 1], inter, r.begin + pcount * psize, psize, 1, total) then + done = true + break + end + end + i += 1 + pcount += 1 + end + if done then + break + end + classSet += 1 + end + end + -- de-interleave into the channels that are decoded + for j = 1, ch do + local t = targets[j] + if t then + local tt = t :: { number } + local v = j + for i = 1, n2 do + tt[i] = inter[v] + v += ch + end + end + end + return + end + local lb = math.min(r.begin, n2) + local le = math.min(r.finish, n2) + local partRead = (le - lb) // psize + local pcs = st.partClass + for pass = 1, 8 do + local pcount, classSet = 0, 1 + while pcount < partRead do + if pass == 1 then + for j = 1, ch do + if targets[j] then + local q = decode(br, cbook) + if q < 0 then + return + end + pcs[j][classSet] = classdata[q + 1] + end + end + end + local i = 0 + while i < classwords and pcount < partRead do + for j = 1, ch do + local t = targets[j] + if t then + local c = pcs[j][classSet][i + 1] + local b = rb[c + 1][pass] + if b >= 0 then + if not partition(br, books[b + 1], t :: { number }, r.begin + pcount * psize, psize, rtype, n2) then + return + end + end + end + end + i += 1 + pcount += 1 + end + classSet += 1 + end + end +end + +-- ------------------------------------------------------------------------------------------------ packet +-- decode(st, buf, off, size) -> frames returned in st.out (0 for the first packet), -1 for a non-audio / bad packet +function Packet.decode(st: State, b: buffer, off: number, size: number): number + if size < 1 then + return -1 + end + local setup = st.setup + local br = Codebook.reader(b, off, size) + if bits(br, 1) ~= 0 then + return -1 + end + local mode = setup.modes[bits(br, setup.modeBits) + 1] + if not mode then + return -1 + end + local n, prevLong, nextLong + if mode.blockflag == 1 then + n = st.n1 + prevLong = bits(br, 1) == 1 + nextLong = bits(br, 1) == 1 + else + n = st.n0 + prevLong, nextLong = false, false + end + if br.eop then + return -1 + end + local n2 = n // 2 + local n0 = st.n0 + local leftStart, leftEnd, rightStart, rightEnd + if mode.blockflag == 1 and not prevLong then + leftStart, leftEnd = (n - n0) // 4, (n + n0) // 4 + else + leftStart, leftEnd = 0, n2 + end + if mode.blockflag == 1 and not nextLong then + rightStart, rightEnd = (n * 3 - n0) // 4, (n * 3 + n0) // 4 + else + rightStart, rightEnd = n2, n + end + local map = setup.mappings[mode.mapping + 1] + local ch = st.channels + local spec, zero, reallyZero = st.spec, st.zero, st.reallyZero + -- floors + for c = 1, ch do + local s = map.mux[c] + 1 + local g = setup.floors[map.submapFloor[s] + 1] + local ok = floorDecode(st, br, g, st.finalY[c]) + zero[c] = not ok + reallyZero[c] = not ok + end + -- channels coupled to a non-silent channel are decoded too + for i = 1, map.couplingSteps do + local m, a = map.magnitude[i] + 1, map.angle[i] + 1 + if not zero[m] or not zero[a] then + zero[m], zero[a] = false, false + end + end + -- residues, per submap + for i = 1, map.submaps do + local targets: { { number } | false } = {} + local k = 0 + for c = 1, ch do + if map.mux[c] == i - 1 then + k += 1 + targets[k] = if zero[c] then false else spec[c] + end + end + residue(st, br, setup.residues[map.submapResidue[i] + 1], targets, k, n2) + end + -- inverse coupling + for i = map.couplingSteps, 1, -1 do + local m, a = spec[map.magnitude[i] + 1], spec[map.angle[i] + 1] + for j = 1, n2 do + local mv, av = m[j], a[j] + local m2, a2 + if mv > 0 then + if av > 0 then + m2, a2 = mv, mv - av + else + a2, m2 = mv, mv + av + end + else + if av > 0 then + m2, a2 = mv, mv + av + else + a2, m2 = mv, mv - av + end + end + m[j], a[j] = m2, a2 + end + end + -- floor curves, IMDCT, windows + local plan = st.plans[n] + local lslope = st.slopes[leftEnd - leftStart] + local rslope = st.slopes[rightEnd - rightStart] + for c = 1, ch do + local sp = spec[c] + local fr = st.frame[c] + if reallyZero[c] then + for j = 1, n do + fr[j] = 0 + end + else + local s = map.mux[c] + 1 + floorCurve(setup.floors[map.submapFloor[s] + 1], st.finalY[c], sp, n2) + Mdct.inverse(plan, sp, 1, 1, fr, 1) + for j = 1, leftStart do + fr[j] = 0 + end + local L = leftEnd - leftStart + for j = 0, L - 1 do + fr[leftStart + j + 1] *= lslope[j + 1] + end + local R = rightEnd - rightStart + for j = 0, R - 1 do + fr[rightStart + j + 1] *= rslope[R - j] + end + for j = rightEnd + 1, n do + fr[j] = 0 + end + end + end + -- overlap-add with the previous frame; return the samples between the two centres + local prevN = st.prevN + local count = 0 + if prevN > 0 then + count = prevN // 4 + n // 4 + local o = prevN // 4 - n // 4 -- this frame starts o samples after the previous centre + local tl = st.tailLen + for c = 1, ch do + local out, tail, fr = st.out[c], st.tail[c], st.frame[c] + for j = 0, count - 1 do + local v = if j < tl then tail[j + 1] else 0 + local fi = j - o + if fi >= 0 then + v += fr[fi + 1] + end + out[j + 1] = v + end + end + end + -- the new tail: this frame from its centre to the end of its window + local tl = rightEnd - n2 + for c = 1, ch do + local tail, fr = st.tail[c], st.frame[c] + for j = 1, tl do + tail[j] = fr[n2 + j] + end + end + st.tailLen = tl + st.prevN = n + return count +end + +return Packet diff --git a/src/Formats/audio/vorbis/Setup.luau b/src/Formats/audio/vorbis/Setup.luau new file mode 100644 index 0000000..e5eb312 --- /dev/null +++ b/src/Formats/audio/vorbis/Setup.luau @@ -0,0 +1,429 @@ +--!strict +--!native +-- audio/vorbis/Setup: the three Vorbis header packets (Vorbis I spec section 4.2): identification (channels, rate, +-- bitrates, blocksizes), comment (vendor + user comments -> tags) and setup (codebooks, floors, residues, mappings, +-- modes). Ported from stb_vorbis 1.22 start_decoder (public domain / MIT; see licenses/stb_vorbis-LICENSE.txt). +-- Floor 0 is rejected as unsupported, as stb_vorbis does (no encoder has produced it since 2000). +-- Never throws: every parser returns nil, message on bad data. +local Codebook = require("@formats/audio/vorbis/Codebook") + +local Setup = {} + +local bits, ilog = Codebook.bits, Codebook.ilog +local readu8, readu32 = buffer.readu8, buffer.readu32 + +export type Ident = { + channels: number, + sampleRate: number, + bitrateMax: number, + bitrateNominal: number, + bitrateMin: number, + blocksize0: number, + blocksize1: number, +} + +export type Floor1 = { + partitions: number, + partitionClass: { number }, -- 1-based list of class numbers (0-based values) + classDims: { number }, -- [class + 1] + classSubs: { number }, + classMaster: { number }, + subBooks: { { number } }, -- [class + 1][sub + 1] = book (0-based) or -1 + multiplier: number, + xlist: { number }, -- [j + 1] + values: number, + sorted: { number }, -- point indices (0-based) by increasing x + low: { number }, -- neighbours, [j + 1] (0-based indices) + high: { number }, +} + +export type Residue = { + type: number, + begin: number, + finish: number, + partSize: number, + classifications: number, + classbook: number, + books: { { number } }, -- [class + 1][pass + 1] = book or -1 + classdata: { { number } }, -- [classbook entry + 1][k + 1] = class +} + +export type Mapping = { + submaps: number, + couplingSteps: number, + magnitude: { number }, -- [step + 1] channel (0-based) + angle: { number }, + mux: { number }, -- [channel + 1] submap (0-based) + submapFloor: { number }, + submapResidue: { number }, +} + +export type Mode = { blockflag: number, mapping: number } + +export type Setup = { + books: { Codebook.Book }, + floors: { Floor1 }, + residues: { Residue }, + mappings: { Mapping }, + modes: { Mode }, + modeBits: number, + maxFloorValues: number, +} + +local function isVorbis(b: buffer, o: number, n: number, kind: number): boolean + return n >= 7 and readu8(b, o) == kind and buffer.readstring(b, o + 1, 6) == "vorbis" +end +Setup.isVorbis = isVorbis + +-- ident(buf, offset, size) -> Ident | nil, message +function Setup.ident(b: buffer, o: number, n: number): (Ident?, string?) + if not isVorbis(b, o, n, 1) then + return nil, "not a Vorbis identification header" + end + if n < 30 then + return nil, "short identification header" + end + if readu32(b, o + 7) ~= 0 then + return nil, "Vorbis version " .. readu32(b, o + 7) + end + local ch = readu8(b, o + 11) + local rate = readu32(b, o + 12) + local bs = readu8(b, o + 28) + local l0, l1 = bs % 16, bs // 16 + if ch == 0 or rate == 0 then + return nil, "no channels or no sample rate" + end + if l0 < 6 or l0 > 13 or l1 < 6 or l1 > 13 or l0 > l1 then + return nil, "bad blocksizes" + end + if readu8(b, o + 29) % 2 == 0 then + return nil, "identification header framing bit not set" + end + return { + channels = ch, + sampleRate = rate, + bitrateMax = buffer.readi32(b, o + 16), + bitrateNominal = buffer.readi32(b, o + 20), + bitrateMin = buffer.readi32(b, o + 24), + blocksize0 = 2 ^ l0, + blocksize1 = 2 ^ l1, + }, + nil +end + +-- comment(buf, offset, size) -> vendor, { "KEY=value" } | nil, message +function Setup.comment(b: buffer, o: number, n: number): (string?, { string }?) + if not isVorbis(b, o, n, 3) then + return nil, nil + end + local p, e = o + 7, o + n + if p + 4 > e then + return nil, nil + end + local vlen = readu32(b, p) + p += 4 + if vlen > e - p then + return nil, nil + end + local vendor = buffer.readstring(b, p, vlen) + p += vlen + local list = {} + if p + 4 > e then + return vendor, list + end + local count = readu32(b, p) + p += 4 + for _ = 1, count do + if p + 4 > e then + break + end + local len = readu32(b, p) + p += 4 + if len > e - p then + break + end + table.insert(list, buffer.readstring(b, p, len)) + p += len + end + return vendor, list +end + +-- setup(buf, offset, size, ident) -> Setup | nil, message +function Setup.setup(b: buffer, o: number, n: number, id: Ident): (Setup?, string?) + if not isVorbis(b, o, n, 5) then + return nil, "not a Vorbis setup header" + end + local br = Codebook.reader(b, o + 7, n - 7) + local channels = id.channels + -- codebooks + local books: { Codebook.Book } = {} + local nbooks = bits(br, 8) + 1 + for i = 1, nbooks do + local book, err = Codebook.read(br) + if not book then + return nil, "codebook " .. (i - 1) .. ": " .. tostring(err) + end + books[i] = book + end + -- time domain transforms (placeholders) + local ntimes = bits(br, 6) + 1 + for _ = 1, ntimes do + if bits(br, 16) ~= 0 then + return nil, "bad time domain transform" + end + end + -- floors + local floors: { Floor1 } = {} + local maxValues = 0 + local nfloors = bits(br, 6) + 1 + for i = 1, nfloors do + local ftype = bits(br, 16) + if ftype == 0 then + return nil, "floor 0" + elseif ftype ~= 1 then + return nil, "bad floor type " .. ftype + end + local parts = bits(br, 5) + local pclass = table.create(parts, 0) + local maxClass = -1 + for j = 1, parts do + pclass[j] = bits(br, 4) + if pclass[j] > maxClass then + maxClass = pclass[j] + end + end + local cdims, csubs, cmaster, subBooks = {}, {}, {}, {} + for j = 1, maxClass + 1 do + cdims[j] = bits(br, 3) + 1 + csubs[j] = bits(br, 2) + cmaster[j] = -1 + if csubs[j] > 0 then + cmaster[j] = bits(br, 8) + if cmaster[j] >= nbooks then + return nil, "bad floor master book" + end + end + local sb = {} + for k = 1, 2 ^ csubs[j] do + sb[k] = bits(br, 8) - 1 + if sb[k] >= nbooks then + return nil, "bad floor subclass book" + end + end + subBooks[j] = sb + end + local mult = bits(br, 2) + 1 + local rangebits = bits(br, 4) + local xlist = { 0, 2 ^ rangebits } + for j = 1, parts do + local c = pclass[j] + for _ = 1, cdims[c + 1] do + table.insert(xlist, bits(br, rangebits)) + end + end + local values = #xlist + if values > 65 * 8 then + return nil, "too many floor points" + end + if br.eop then + return nil, "setup header ends in a floor" + end + local order = table.create(values, 0) + for j = 1, values do + order[j] = j - 1 + end + table.sort(order, function(a: number, c: number): boolean + return xlist[a + 1] < xlist[c + 1] + end) + for j = 1, values - 1 do + if xlist[order[j] + 1] == xlist[order[j + 1] + 1] then + return nil, "duplicate floor x" + end + end + local low, high = table.create(values, 0), table.create(values, 0) + for j = 2, values - 1 do + local lo, hi = -1, 65536 + local x = xlist[j + 1] + for k = 0, j - 1 do + local xv = xlist[k + 1] + if xv > lo and xv < x then + low[j + 1], lo = k, xv + end + if xv < hi and xv > x then + high[j + 1], hi = k, xv + end + end + end + floors[i] = { + partitions = parts, + partitionClass = pclass, + classDims = cdims, + classSubs = csubs, + classMaster = cmaster, + subBooks = subBooks, + multiplier = mult, + xlist = xlist, + values = values, + sorted = order, + low = low, + high = high, + } + if values > maxValues then + maxValues = values + end + end + -- residues + local residues: { Residue } = {} + local nres = bits(br, 6) + 1 + for i = 1, nres do + local rtype = bits(br, 16) + if rtype > 2 then + return nil, "bad residue type " .. rtype + end + local rbegin, rend = bits(br, 24), bits(br, 24) + local psize = bits(br, 24) + 1 + local ncls = bits(br, 6) + 1 + local cbook = bits(br, 8) + if rend < rbegin then + return nil, "residue end before begin" + end + if cbook >= nbooks then + return nil, "bad residue classbook" + end + local cascade = table.create(ncls, 0) + for j = 1, ncls do + local lowBits = bits(br, 3) + local highBits = if bits(br, 1) == 1 then bits(br, 5) else 0 + cascade[j] = highBits * 8 + lowBits + end + local rbooks = {} + for j = 1, ncls do + local row = table.create(8, -1) + local c = cascade[j] + for k = 1, 8 do + if c % 2 == 1 then + row[k] = bits(br, 8) + if row[k] >= nbooks then + return nil, "bad residue book" + end + end + c = c // 2 + end + rbooks[j] = row + end + if br.eop then + return nil, "setup header ends in a residue" + end + -- class numbers of each classbook entry (stb's classdata) + local cb = books[cbook + 1] + local cw = cb.dims + if cb.entries * cw > 2 ^ 22 then + return nil, "residue classbook too large" + end + local classdata = table.create(cb.entries) + for j = 0, cb.entries - 1 do + local row = table.create(cw, 0) + local tmp = j + for k = cw, 1, -1 do + row[k] = tmp % ncls + tmp = tmp // ncls + end + classdata[j + 1] = row + end + residues[i] = { + type = rtype, + begin = rbegin, + finish = rend, + partSize = psize, + classifications = ncls, + classbook = cbook, + books = rbooks, + classdata = classdata, + } + end + -- mappings + local mappings: { Mapping } = {} + local nmaps = bits(br, 6) + 1 + local chBits = ilog(channels - 1) + for i = 1, nmaps do + if bits(br, 16) ~= 0 then + return nil, "bad mapping type" + end + local submaps = if bits(br, 1) == 1 then bits(br, 4) + 1 else 1 + local steps = 0 + local mag, ang = {}, {} + if bits(br, 1) == 1 then + steps = bits(br, 8) + 1 + if steps > channels then + return nil, "too many coupling steps" + end + for k = 1, steps do + mag[k] = bits(br, chBits) + ang[k] = bits(br, chBits) + if mag[k] >= channels or ang[k] >= channels or mag[k] == ang[k] then + return nil, "bad coupling channels" + end + end + end + if bits(br, 2) ~= 0 then + return nil, "mapping reserved bits set" + end + local mux = table.create(channels, 0) + if submaps > 1 then + for j = 1, channels do + mux[j] = bits(br, 4) + if mux[j] >= submaps then + return nil, "bad channel mux" + end + end + end + local sf, sr = {}, {} + for j = 1, submaps do + bits(br, 8) + sf[j] = bits(br, 8) + sr[j] = bits(br, 8) + if sf[j] >= nfloors or sr[j] >= nres then + return nil, "bad submap floor / residue" + end + end + mappings[i] = { + submaps = submaps, + couplingSteps = steps, + magnitude = mag, + angle = ang, + mux = mux, + submapFloor = sf, + submapResidue = sr, + } + end + -- modes + local modes: { Mode } = {} + local nmodes = bits(br, 6) + 1 + for i = 1, nmodes do + local bf = bits(br, 1) + local wt, tt = bits(br, 16), bits(br, 16) + local m = bits(br, 8) + if wt ~= 0 or tt ~= 0 or m >= nmaps then + return nil, "bad mode" + end + modes[i] = { blockflag = bf, mapping = m } + end + if br.eop then + return nil, "setup header truncated" + end + if bits(br, 1) ~= 1 then + return nil, "setup header framing bit not set" + end + return { + books = books, + floors = floors, + residues = residues, + mappings = mappings, + modes = modes, + modeBits = ilog(nmodes - 1), + maxFloorValues = maxValues, + }, + nil +end + +return Setup diff --git a/src/Formats/audio/vorbis/Tables.luau b/src/Formats/audio/vorbis/Tables.luau new file mode 100644 index 0000000..435f719 --- /dev/null +++ b/src/Formats/audio/vorbis/Tables.luau @@ -0,0 +1,37 @@ +--!strict +-- audio/vorbis/Tables: the floor 1 inverse dB table (Vorbis I specification, section 10.1, as in stb_vorbis 1.22, +-- public domain / MIT, licenses/stb_vorbis-LICENSE.txt). 256 values, index = floor value (1-based here). +return table.freeze({ + 1.0649863e-07, 1.1341951e-07, 1.2079015e-07, 1.2863978e-07, 1.3699951e-07, 1.4590251e-07, 1.5538408e-07, 1.6548181e-07, + 1.7623575e-07, 1.8768855e-07, 1.9988561e-07, 2.1287530e-07, 2.2670913e-07, 2.4144197e-07, 2.5713223e-07, 2.7384213e-07, + 2.9163793e-07, 3.1059021e-07, 3.3077411e-07, 3.5226968e-07, 3.7516214e-07, 3.9954229e-07, 4.2550680e-07, 4.5315863e-07, + 4.8260743e-07, 5.1396998e-07, 5.4737065e-07, 5.8294187e-07, 6.2082472e-07, 6.6116941e-07, 7.0413592e-07, 7.4989464e-07, + 7.9862701e-07, 8.5052630e-07, 9.0579828e-07, 9.6466216e-07, 1.0273513e-06, 1.0941144e-06, 1.1652161e-06, 1.2409384e-06, + 1.3215816e-06, 1.4074654e-06, 1.4989305e-06, 1.5963394e-06, 1.7000785e-06, 1.8105592e-06, 1.9282195e-06, 2.0535261e-06, + 2.1869758e-06, 2.3290978e-06, 2.4804557e-06, 2.6416497e-06, 2.8133190e-06, 2.9961443e-06, 3.1908506e-06, 3.3982101e-06, + 3.6190449e-06, 3.8542308e-06, 4.1047004e-06, 4.3714470e-06, 4.6555282e-06, 4.9580707e-06, 5.2802740e-06, 5.6234160e-06, + 5.9888572e-06, 6.3780469e-06, 6.7925283e-06, 7.2339451e-06, 7.7040476e-06, 8.2047000e-06, 8.7378876e-06, 9.3057248e-06, + 9.9104632e-06, 1.0554501e-05, 1.1240392e-05, 1.1970856e-05, 1.2748789e-05, 1.3577278e-05, 1.4459606e-05, 1.5399272e-05, + 1.6400004e-05, 1.7465768e-05, 1.8600792e-05, 1.9809576e-05, 2.1096914e-05, 2.2467911e-05, 2.3928002e-05, 2.5482978e-05, + 2.7139006e-05, 2.8902651e-05, 3.0780908e-05, 3.2781225e-05, 3.4911534e-05, 3.7180282e-05, 3.9596466e-05, 4.2169667e-05, + 4.4910090e-05, 4.7828601e-05, 5.0936773e-05, 5.4246931e-05, 5.7772202e-05, 6.1526565e-05, 6.5524908e-05, 6.9783085e-05, + 7.4317983e-05, 7.9147585e-05, 8.4291040e-05, 8.9768747e-05, 9.5602426e-05, 0.00010181521, 0.00010843174, 0.00011547824, + 0.00012298267, 0.00013097477, 0.00013948625, 0.00014855085, 0.00015820453, 0.00016848555, 0.00017943469, 0.00019109536, + 0.00020351382, 0.00021673929, 0.00023082423, 0.00024582449, 0.00026179955, 0.00027881276, 0.00029693158, 0.00031622787, + 0.00033677814, 0.00035866388, 0.00038197188, 0.00040679456, 0.00043323036, 0.00046138411, 0.00049136745, 0.00052329927, + 0.00055730621, 0.00059352311, 0.00063209358, 0.00067317058, 0.00071691700, 0.00076350630, 0.00081312324, 0.00086596457, + 0.00092223983, 0.00098217216, 0.0010459992, 0.0011139742, 0.0011863665, 0.0012634633, 0.0013455702, 0.0014330129, + 0.0015261382, 0.0016253153, 0.0017309374, 0.0018434235, 0.0019632195, 0.0020908006, 0.0022266726, 0.0023713743, + 0.0025254795, 0.0026895994, 0.0028643847, 0.0030505286, 0.0032487691, 0.0034598925, 0.0036847358, 0.0039241906, + 0.0041792066, 0.0044507950, 0.0047400328, 0.0050480668, 0.0053761186, 0.0057254891, 0.0060975636, 0.0064938176, + 0.0069158225, 0.0073652516, 0.0078438871, 0.0083536271, 0.0088964928, 0.009474637, 0.010090352, 0.010746080, + 0.011444421, 0.012188144, 0.012980198, 0.013823725, 0.014722068, 0.015678791, 0.016697687, 0.017782797, + 0.018938423, 0.020169149, 0.021479854, 0.022875735, 0.024362330, 0.025945531, 0.027631618, 0.029427276, + 0.031339626, 0.033376252, 0.035545228, 0.037855157, 0.040315199, 0.042935108, 0.045725273, 0.048696758, + 0.051861348, 0.055231591, 0.058820850, 0.062643361, 0.066714279, 0.071049749, 0.075666962, 0.080584227, + 0.085821044, 0.091398179, 0.097337747, 0.10366330, 0.11039993, 0.11757434, 0.12521498, 0.13335215, + 0.14201813, 0.15124727, 0.16107617, 0.17154380, 0.18269168, 0.19456402, 0.20720788, 0.22067342, + 0.23501402, 0.25028656, 0.26655159, 0.28387361, 0.30232132, 0.32196786, 0.34289114, 0.36517414, + 0.38890521, 0.41417847, 0.44109412, 0.46975890, 0.50028648, 0.53279791, 0.56742212, 0.60429640, + 0.64356699, 0.68538959, 0.72993007, 0.77736504, 0.82788260, 0.88168307, 0.9389798, 1.0, +}) diff --git a/src/Formats/audio/vorbis/init.luau b/src/Formats/audio/vorbis/init.luau new file mode 100644 index 0000000..e432adf --- /dev/null +++ b/src/Formats/audio/vorbis/init.luau @@ -0,0 +1,486 @@ +--!strict +-- audio/vorbis: Ogg Vorbis (Vorbis I specification, Xiph.Org; RFC 5215 for the Ogg mapping). The decoder is a Luau +-- port of stb_vorbis 1.22 (public domain / MIT, licenses/stb_vorbis-LICENSE.txt) on containers/Ogg and codecs/Mdct, +-- with libvorbis' sample-exact timing: start trimming from the first page's granule, end trimming from the last +-- page's, granule-exact seeking (bisection, then decoding forward to a page boundary to recover the position). +-- Supports: decode / open of any channel count (1..255), rates, block sizes 64..8192, floor 1, residues 0 / 1 / 2, +-- coupling, sparse / ordered codebooks, lookup types 1 / 2; comment-header tags (lower-cased keys); a packet-level +-- decoder (Vorbis.packetDecoder) for Vorbis in Matroska / WebM / MP4. Encode (audio/vorbis/Encode, new code): a basic +-- Ogg Vorbis encoder from an Audio or a streamed Decoder (long blocks, floor 1, coupled residue 2, a fixed codebook +-- set, quality -1 .. 10). Not supported: floor 0 (Err.UNSUPPORTED, as in stb_vorbis; no encoder has produced it since +-- 2000), chained streams (the first logical Vorbis stream is decoded), short blocks in the encoder. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Ogg = require("@formats/containers/Ogg") +local Setup = require("@formats/audio/vorbis/Setup") +local Packet = require("@formats/audio/vorbis/Packet") +local Encode = require("@formats/audio/vorbis/Encode") +local Pcm = require("@formats/codecs/Pcm") + +-- ------------------------------------------------------------------------------------------------ contract +local Vorbis = { + name = "vorbis", + category = "audio", + extensions = { "ogg", "oga" }, + mime = { "audio/ogg", "audio/vorbis" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct", "codecs/Pcm" }, + caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255 }, +} + +export type OpenOptions = { + verify: boolean?, -- check the Ogg page CRCs (default true) +} +export type EncodeOptions = { + quality: number?, -- -1 .. 10 (default 3): the floor sits 2 * quality - 1 dB under the band energies (8 dB + -- less at the top of the spectrum), which sets the residue's quantization step + serial: number?, -- the Ogg stream serial number (default 0x464C5541) +} + +-- ------------------------------------------------------------------------------------------------ constants +local TAG_KEYS = { tracknumber = "track", description = "comment" } + +local function tagsOf(comments: { string }): Types.Tags + local tags: Types.Tags = {} + for _, s in comments do + local eq = string.find(s, "=", 1, true) + if eq then + local k = string.lower(string.sub(s, 1, eq - 1)) + local v = string.sub(s, eq + 1) + k = TAG_KEYS[k] or k + tags[k] = if tags[k] then tags[k] .. "; " .. v else v + end + end + return tags +end + +-- the three headers -> ident, setup, vendor, tags | nil, Err +local function headers(h1: any, h2: any, h3: any): (any, any, string?, Types.Tags?, Err.Err?) + local id, ierr = Setup.ident(h1.data, h1.offset, h1.size) + if not id then + return nil, nil, nil, nil, Err.new(Err.CORRUPT, ierr or "bad identification header") + end + local vendor, comments = Setup.comment(h2.data, h2.offset, h2.size) + if not vendor then + return nil, nil, nil, nil, Err.new(Err.CORRUPT, "bad comment header") + end + local setup, serr = Setup.setup(h3.data, h3.offset, h3.size, id) + if not setup then + local code = if serr == "floor 0" then Err.UNSUPPORTED else Err.CORRUPT + return nil, nil, nil, nil, Err.new(code, serr or "bad setup header") + end + return id, setup, vendor, tagsOf(comments or {}), nil +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Vorbis.sniff(r: Bytes.Reader): number + if r:remaining() < 35 or r:peek(4) ~= "OggS" then + return 0 + end + local b, p = r.buf, r.pos + local nseg = buffer.readu8(b, p + 26) + local d = p + 27 + nseg + if d + 7 > r.limit then + return 0 + end + return if buffer.readu8(b, d) == 1 and buffer.readstring(b, d + 1, 6) == "vorbis" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Vorbis.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) + local dec, err = Vorbis.open(r, opts) + if not dec then + return nil, err + end + local d = dec :: any + local ch = d.channels + local parts, total = {}, 0 + while true do + local b, n = d:read(65536) + if n == 0 then + break + end + local copy = buffer.create(n * ch * 4) + buffer.copy(copy, 0, b, 0, n * ch * 4) + table.insert(parts, copy) + total += n + end + local a = Types.Audio.new(d.sampleRate, ch, total) + local o = 0 + for _, p in parts do + buffer.copy(a.samples, o, p) + o += buffer.len(p) + end + a.tags = d.tags + a.meta.source = d.source + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- encode(audioOrDecoder, opts?) -> an Ogg Vorbis file | nil, Err +function Vorbis.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local o: EncodeOptions = opts or {} + local q = o.quality or 3 + if type(q) ~= "number" or q ~= q or q < -1 or q > 10 then + return nil, Err.new(Err.ARG, "quality must be -1 .. 10") + end + if src.channels > 255 then + return nil, Err.new(Err.ARG, "at most 255 channels") + end + if src.sampleRate ~= math.floor(src.sampleRate) or src.sampleRate < 1 or src.sampleRate >= 2 ^ 32 then + return nil, Err.new(Err.ARG, "the sample rate must be a positive integer") + end + local serial = o.serial or 0x464C5541 + if type(serial) ~= "number" or serial ~= math.floor(serial) or serial < 0 or serial >= 2 ^ 32 then + return nil, Err.new(Err.ARG, "serial must be a 32-bit unsigned integer") + end + local out, msg = Encode.encode(src :: any, { quality = q, vendor = "formats-luau Vorbis encoder", serial = serial }) + if not out then + return nil, Err.new(Err.CORRUPT, tostring(msg)) + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ open +local Stream = {} +Stream.__index = Stream + +-- queue the chunk arrays[first .. first + count - 1] whose first sample has granule g0, trimmed to [lo, hi) +local function push(self: any, arrays: { { number } }, g0: number, count: number, hi: number) + local lo = math.max(g0, self.startG, self.skipTo) + if hi > g0 + count then + hi = g0 + count + end + if hi > lo then + table.insert(self.queue, { arrays, lo - g0 + 1, hi - g0, lo }) + end +end + +local function copyOut(self: any, count: number): { { number } } + local t = table.create(self.channels) + for c = 1, self.channels do + local src = self.st.out[c] + local a = table.create(count, 0) + table.move(src, 1, count, 1, a) + t[c] = a + end + return t +end + +-- decode packets until something is queued; false at the end of the stream +local function decodeMore(self: any): boolean + local reader, st = self.reader, self.st + while not self.ended do + local p = reader:nextPacket() + if p == nil then + self.ended = true + break + end + if p.gap then + Packet.reset(st) + self.syncing, self.pend, self.pendCount = true, {}, 0 + end + local count = Packet.decode(st, p.data, p.offset, p.size) + if count >= 0 then + local endG = if p.eos and p.granule >= 0 then p.granule else math.huge + if self.syncing then + if count > 0 then + table.insert(self.pend, { copyOut(self, count), count }) + self.pendCount += count + end + if p.granule >= 0 then + -- the position is known again: this packet's output ends at its granule + local g = p.granule - self.pendCount + if p.eos and self.pendCount > 0 then + g = math.max(g, self.pos) -- an end-trimmed last page: keep the running position + end + for _, c in self.pend do + push(self, c[1], g, c[2], endG) + g += c[2] + end + self.pos = g + self.syncing, self.pend, self.pendCount = false, {}, 0 + end + else + local g0 = self.pos + self.pos += count + if count > 0 then + push(self, st.out, g0, count, endG) + end + if p.granule >= 0 and not p.eos then + self.pos = p.granule + end + end + if p.eos then + self.ended = true + end + if #self.queue > 0 then + return true + end + end + end + return #self.queue > 0 +end + +function Stream.read(self: any, n: number, out: buffer?): (buffer, number) + local ch = self.channels + n = math.max(0, math.floor(n)) + local b = if out and buffer.len(out) >= n * ch * 4 then out else buffer.create(n * ch * 4) + local got = 0 + local writef32 = buffer.writef32 + while got < n do + local q = self.queue[1] + if q == nil then + if not decodeMore(self) then + break + end + q = self.queue[1] + end + local arrays, first, last = q[1], q[2], q[3] + local take = math.min(n - got, last - first + 1) + for c = 1, ch do + local a = arrays[c] + local o = got * ch * 4 + (c - 1) * 4 + for i = first, first + take - 1 do + writef32(b, o, a[i]) + o += ch * 4 + end + end + got += take + self.next = q[4] + take + if first + take > last then + table.remove(self.queue, 1) + else + q[2] = first + take + q[4] += take + end + end + if got > 0 then + self.skipTo = -math.huge + end + return b, got +end + +function Stream.position(self: any): number + return (self.next - self.startG) / self.sampleRate +end + +-- back to the first audio packet +local function restart(self: any) + local r = self.reader + r:rewind() + for _ = 1, 3 do + r:nextPacket() + end + Packet.reset(self.st) + self.pos = self.base + self.syncing, self.pend, self.pendCount = false, {}, 0 + self.ended = false + self.queue = {} +end + +function Stream.seek(self: any, seconds: number) + local target = self.startG + math.floor(math.max(0, seconds) * self.sampleRate + 0.5) + if target ~= target then + target = self.startG + end + if self.lastG >= 0 and target > self.lastG then + target = self.lastG + end + self.skipTo = target + self.next = target + local r = self.reader + local g = target - self.st.n1 + for _ = 1, 16 do + if g <= self.startG then + break + end + local G = r:seekGranule(g) + if G == nil or G < 0 then + break + end + -- decode forward to the next page boundary to learn the exact position + Packet.reset(self.st) + self.queue = {} + self.ended = false + self.syncing, self.pend, self.pendCount = true, {}, 0 + self.pos = G + local ok = false + while true do + local p = r:nextPacket() + if p == nil then + break + end + local count = Packet.decode(self.st, p.data, p.offset, p.size) + if count > 0 then + table.insert(self.pend, { copyOut(self, count), count }) + self.pendCount += count + end + if p.granule >= 0 then + if not p.eos then + local g0 = p.granule - self.pendCount + for _, c in self.pend do + push(self, c[1], g0, c[2], math.huge) + g0 += c[2] + end + self.pos = p.granule + self.syncing, self.pend, self.pendCount = false, {}, 0 + ok = true + end + break + end + end + if ok then + return + end + g = G - 1 -- the last page: start one page earlier + end + restart(self) + self.skipTo = target + self.next = target +end + +function Vorbis.open(r: any, opts: OpenOptions?): (Types.Decoder?, Err.Err?) + local demux, derr = Ogg.open(r, if opts and opts.verify == false then { verify = false } else nil) + if not demux then + return nil, derr + end + local serial = demux:find("vorbis") + if serial == nil then + return nil, Err.new(Err.CORRUPT, "no Vorbis stream in the Ogg file") + end + local reader = demux:reader(serial) + local h1 = reader:nextPacket() + if h1 == nil then + return nil, Err.new(Err.TRUNCATED, "missing identification header") + end + local id0, ierr = Setup.ident(h1.data, h1.offset, h1.size) + if not id0 then + return nil, Err.new(Err.CORRUPT, ierr or "bad identification header") + end + local h2 = reader:nextPacket() + if h2 == nil then + return nil, Err.new(Err.TRUNCATED, "missing comment header") + end + local h2copy = { data = Ogg.copy(h2), offset = 0, size = h2.size } + local h3 = reader:nextPacket() + if h3 == nil then + return nil, Err.new(Err.TRUNCATED, "missing setup header") + end + local id, setup, vendor, tags, herr = headers(h1, h2copy, h3) + if not id then + return nil, herr + end + local st = Packet.new(id, setup) + if not st then + return nil, Err.new(Err.CORRUPT, "bad block sizes") + end + -- the granule of the first returned sample: the first granule page minus what its packets return + local base = 0 + do + local prev, sum = 0, 0 + while true do + local p = reader:nextPacket() + if p == nil then + break + end + local bs = Packet.blocksize(st, p.data, p.offset, p.size) + if bs > 0 then + if prev > 0 then + sum += prev // 4 + bs // 4 + end + prev = bs + end + if p.granule >= 0 then + base = p.granule - sum + if p.eos then + base = 0 -- one page holds the whole stream: the spec trims its end, not its start + end + break + end + end + end + local info = demux:stream(serial) + local lastG = if info and info.lastGranule and info.lastGranule >= 0 then info.lastGranule else -1 + local startG = math.max(base, 0) + local frames = if lastG >= 0 then math.max(0, lastG - startG) else 0 + local rate = id.sampleRate + local self = setmetatable({ + sampleRate = rate, + channels = id.channels, + frames = frames, + duration = frames / rate, + bitrate = if frames > 0 then math.floor(demux.size * 8 / (frames / rate)) else id.bitrateNominal, + tags = tags, + vendor = vendor, + ident = id, + source = { + format = "vorbis", + codec = "vorbis", + vendor = vendor, + blocksizes = { id.blocksize0, id.blocksize1 }, + nominalBitrate = id.bitrateNominal, + }, + demux = demux, + reader = reader, + st = st, + base = base, + startG = startG, + lastG = lastG, + pos = base, + next = startG, + skipTo = -math.huge, + queue = {}, + syncing = false, + pend = {}, + pendCount = 0, + ended = false, + }, Stream) + restart(self) + return self :: any, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- packetDecoder(ident, comment, setup) -> a decoder of raw Vorbis packets (Matroska / WebM / MP4 carry the three +-- headers in their codec private data) | nil, Err. Each argument is a buffer holding one header packet. +-- local pd = Vorbis.packetDecoder(h1, h2, h3) +-- local n = pd:decode(buf, offset, size) -- frames returned (first packet 0; -1 = not audio); pd.out[ch][1 .. n] +-- pd:reset() -- after a seek +function Vorbis.packetDecoder(h1: buffer, h2: buffer, h3: buffer): (any, Err.Err?) + local function pk(b: buffer): any + return { data = b, offset = 0, size = buffer.len(b) } + end + local id, setup, vendor, tags, err = headers(pk(h1), pk(h2), pk(h3)) + if not id then + return nil, err + end + local st = Packet.new(id, setup) + if not st then + return nil, Err.new(Err.CORRUPT, "bad block sizes") + end + return { + sampleRate = id.sampleRate, + channels = id.channels, + vendor = vendor, + tags = tags, + out = st.out, + decode = function(_self: any, b: buffer, offset: number, size: number): number + if offset < 0 or size < 0 or offset + size > buffer.len(b) then + return -1 + end + return Packet.decode(st, b, offset, size) + end, + reset = function(_self: any) + Packet.reset(st) + end, + }, + nil +end + +return Vorbis diff --git a/src/Formats/codecs/Aac/Decode.luau b/src/Formats/codecs/Aac/Decode.luau new file mode 100644 index 0000000..ce4a88b --- /dev/null +++ b/src/Formats/codecs/Aac/Decode.luau @@ -0,0 +1,903 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Aac/Decode: the AAC-LC raw_data_block decoder (ISO/IEC 14496-3 subpart 4): SCE / CPE / LFE / DSE / PCE / +-- FIL / END elements, ics_info with window grouping, section data, scalefactors (with noise energies and intensity +-- positions), pulse data, TNS, the eleven spectral codebooks with escapes, dequantisation, M/S and intensity stereo, +-- perceptual noise substitution (FFmpeg's LCG so the noise matches it), the filterbank (sine / KBD windows, the four +-- window sequences, IMDCT through codecs/Mdct, overlap-add). FIL extension payloads (SBR / PS) are reported to a hook +-- and otherwise skipped. Written from the standard; no third-party code. Never throws: returns nil, message. +local Mdct = require("@formats/codecs/Mdct") +local Tables = require("@formats/codecs/Aac/Tables") + +local readu32, byteswap, lshift, rshift, band = buffer.readu32, bit32.byteswap, bit32.lshift, bit32.rshift, bit32.band +local floor, sqrt, abs = math.floor, math.sqrt, math.abs + +local Decode = {} + +local ONLY_LONG, LONG_START, EIGHT_SHORT, LONG_STOP = 0, 1, 2, 3 +local ZERO_HCB, ESC_HCB, NOISE_HCB, INTENSITY_HCB2, INTENSITY_HCB = 0, 11, 13, 14, 15 + +-- ------------------------------------------------------------------------------------------------ bit reader +-- one packet at a time: module-level cursor over a zero-padded copy (a frame decode never yields) +local B: buffer = buffer.create(16) +local BP = 0 -- bit position +local BL = 0 -- bit limit +local OVER = false + +local function getBits(n: number): number -- 1 .. 25 + local p = BP + BP = p + n + if p > BL then + OVER = true + return 0 + end + return rshift(lshift(byteswap(readu32(B, rshift(p, 3))), band(p, 7)), 32 - n) +end +local function peekBits(n: number): number + local p = BP + if p > BL then + return 0 + end + return rshift(lshift(byteswap(readu32(B, rshift(p, 3))), band(p, 7)), 32 - n) +end +local function getLong(n: number): number + if n > 24 then + local hi = getBits(n - 16) + return hi * 65536 + getBits(16) + end + return getBits(n) +end + +-- ------------------------------------------------------------------------------------------------ Huffman +local PEEK = 10 +type Book = { tab: { number }, map: { [number]: number }, maxLen: number } + +local function book(codes: { number }, bits: { number }): Book + local tab = table.create(2 ^ PEEK, 0) + local map = {} + local maxLen = 0 + for s = 1, #codes do + local c, l = codes[s], bits[s] + maxLen = math.max(maxLen, l) + if l <= PEEK then + local shift = 2 ^ (PEEK - l) + for k = 0, shift - 1 do + tab[c * shift + k + 1] = (s - 1) * 32 + l + end + else + map[l * 2 ^ 20 + c] = s - 1 + end + end + return { tab = tab, map = map, maxLen = maxLen } +end + +local SF_BOOK = book(Tables.SF_CODES, Tables.SF_BITS) +local SPEC_BOOK: { Book } = {} +for i = 1, 11 do + SPEC_BOOK[i] = book(Tables.SPEC_CODES[i], Tables.SPEC_BITS[i]) +end + +-- the next symbol of a book, -1 for an invalid code +local function huff(bk: Book): number + local e = bk.tab[peekBits(PEEK) + 1] + if e > 0 then + BP += band(e, 31) + return rshift(e, 5) + end + -- a code longer than PEEK bits + local code = getBits(PEEK) + local map = bk.map + for l = PEEK + 1, bk.maxLen do + code = code * 2 + getBits(1) + local s = map[l * 1048576 + code] + if s then + return s + end + end + return -1 +end + +-- per codebook: dimension, unsigned, modulus, offset +local DIM = { 4, 4, 4, 4, 2, 2, 2, 2, 2, 2, 2 } +local UNSIGNED = { false, false, true, true, false, false, true, true, true, true, true } +local MOD = { 3, 3, 3, 3, 9, 9, 8, 8, 13, 13, 17 } +local OFF = { 1, 1, 0, 0, 4, 4, 0, 0, 0, 0, 0 } + +-- |q|^(4/3) +local POW43 = table.create(8192, 0) +for i = 0, 8191 do + POW43[i + 1] = i ^ (4 / 3) +end + +-- ------------------------------------------------------------------------------------------------ windows +local SINE_LONG = Mdct.window("sine", 2048) :: { number } +local KBD_LONG = Mdct.window("kbd", 2048, 4) :: { number } +local SINE_SHORT = Mdct.window("sine", 256) :: { number } +local KBD_SHORT = Mdct.window("kbd", 256, 6) :: { number } +local PLAN_LONG = Mdct.new(2048) :: Mdct.Plan +local PLAN_SHORT = Mdct.new(256) :: Mdct.Plan + +-- ------------------------------------------------------------------------------------------------ state +export type Channel = { + spec: { number }, -- 1024 dequantised coefficients (8 x 128 for short windows) + overlap: { number }, -- 1024 samples carried to the next frame + prevShape: number, + -- this frame's ics + windowSequence: number, + windowShape: number, + maxSfb: number, + numGroups: number, + groupLen: { number }, + bandType: { number }, -- [g * maxSfb + sfb + 1] + sf: { number }, + -- tns + tnsFilters: { { number } }, -- per window: { length, order, direction, coefs ... } flattened per filter +} + +export type State = { + sfIndex: number, + channels: number, -- configured channels (0: as found) + frameLength: number, + ch: { Channel }, + pcm: { number }, -- interleaved output floats + random: number, -- PNS generator state + time: { number }, -- 2048 IMDCT scratch + frame: { number }, -- 2048 windowed frame scratch + short: { number }, -- 256 scratch + onExtension: ((kind: number, element: number, buf: buffer, bitPos: number, bits: number) -> ())?, + extensions: number, -- extension payloads seen (SBR / PS / ...) + sbr: boolean, -- an SBR payload was seen + map: { number }?, -- element channel order -> output channel (1-based) +} + +local function newChannel(): Channel + return { + spec = table.create(1024, 0), + overlap = table.create(1024, 0), + prevShape = 0, + windowSequence = 0, + windowShape = 0, + maxSfb = 0, + numGroups = 1, + groupLen = { 1, 0, 0, 0, 0, 0, 0, 0 }, + bandType = table.create(8 * 64, 0), + sf = table.create(8 * 64, 0), + tnsFilters = {}, + } +end +Decode.newChannel = newChannel + +-- ------------------------------------------------------------------------------------------------ ics +local function icsInfo(st: State, c: Channel): string? + if getBits(1) ~= 0 then + return "reserved ics bit set" + end + c.windowSequence = getBits(2) + c.windowShape = getBits(1) + if c.windowSequence == EIGHT_SHORT then + c.maxSfb = getBits(4) + local grouping = getBits(7) + local ng = 1 + local gl = c.groupLen + gl[1] = 1 + for w = 1, 7 do + if band(grouping, 2 ^ (6 - (w - 1))) ~= 0 then + gl[ng] += 1 + else + ng += 1 + gl[ng] = 1 + end + end + c.numGroups = ng + if c.maxSfb > Tables.NUM_SWB_SHORT[st.sfIndex + 1] then + return "max_sfb over the short band count" + end + else + c.maxSfb = getBits(6) + c.numGroups = 1 + c.groupLen[1] = 1 + if getBits(1) ~= 0 then + return "prediction (AAC Main / LTP) is not supported" + end + if c.maxSfb > Tables.NUM_SWB_LONG[st.sfIndex + 1] then + return "max_sfb over the long band count" + end + end + return nil +end + +local function sectionData(c: Channel): string? + local long = c.windowSequence ~= EIGHT_SHORT + local bits = if long then 5 else 3 + local esc = 2 ^ bits - 1 + local maxSfb = c.maxSfb + local bt = c.bandType + for g = 0, c.numGroups - 1 do + local k = 0 + while k < maxSfb do + local cb = getBits(4) + if cb == 12 then + return "reserved codebook 12" + end + local len = 0 + while true do + local inc = getBits(bits) + len += inc + if inc ~= esc then + break + end + if OVER then + return "section data runs past the end" + end + end + if k + len > maxSfb then + return "section runs past max_sfb" + end + for s = k, k + len - 1 do + bt[g * maxSfb + s + 1] = cb + end + k += len + if OVER then + return "section data runs past the end" + end + end + end + return nil +end + +local function scaleFactors(c: Channel, globalGain: number): string? + local sfv = globalGain + local noise = globalGain - 90 + local is = 0 + local firstNoise = true + local maxSfb = c.maxSfb + local bt, sf = c.bandType, c.sf + for g = 0, c.numGroups - 1 do + for s = 0, maxSfb - 1 do + local i = g * maxSfb + s + 1 + local cb = bt[i] + if cb == ZERO_HCB then + sf[i] = 0 + elseif cb == INTENSITY_HCB or cb == INTENSITY_HCB2 then + local d = huff(SF_BOOK) + if d < 0 then + return "bad scalefactor code" + end + is += d - 60 + sf[i] = math.clamp(is, -155, 100) + elseif cb == NOISE_HCB then + if firstNoise then + noise += getBits(9) - 256 + firstNoise = false + else + local d = huff(SF_BOOK) + if d < 0 then + return "bad scalefactor code" + end + noise += d - 60 + end + sf[i] = math.clamp(noise, -100, 155) + else + local d = huff(SF_BOOK) + if d < 0 then + return "bad scalefactor code" + end + sfv += d - 60 + if sfv < 0 or sfv > 255 then + return "scalefactor out of range" + end + sf[i] = sfv + end + end + end + return nil +end + +local function tnsData(st: State, c: Channel): string? + local short = c.windowSequence == EIGHT_SHORT + local nw = if short then 8 else 1 + local filters = {} + for w = 1, nw do + local list = {} + local nFilt = getBits(if short then 1 else 2) + if nFilt > 0 then + local coefRes = getBits(1) + for _ = 1, nFilt do + local length = getBits(if short then 4 else 6) + local order = getBits(if short then 3 else 5) + local f = { length, order, 0 } + if order > (if short then 7 else 12) then + return "TNS order too high" + end + if order > 0 then + f[3] = getBits(1) + local compress = getBits(1) + local resBits = coefRes + 3 + local nb = resBits - compress + local iq = ((2 ^ (resBits - 1)) - 0.5) / (math.pi / 2) + local iqm = ((2 ^ (resBits - 1)) + 0.5) / (math.pi / 2) + local tmp = table.create(order, 0) + for k = 1, order do + local v = getBits(nb) + if v >= 2 ^ (nb - 1) then + v -= 2 ^ nb + end + tmp[k] = math.sin(v / (if v >= 0 then iq else iqm)) + end + -- parcor -> LPC + local a = table.create(order + 1, 0) + local b = table.create(order + 1, 0) + a[1] = 1 + for m = 1, order do + for i = 1, m - 1 do + b[i + 1] = a[i + 1] + tmp[m] * a[m - i + 1] + end + for i = 1, m - 1 do + a[i + 1] = b[i + 1] + end + a[m + 1] = tmp[m] + end + for k = 1, order do + f[3 + k] = a[k + 1] + end + end + table.insert(list, f) + end + end + filters[w] = list + end + c.tnsFilters = filters + local _ = st + return nil +end + +local function applyTns(st: State, c: Channel) + local short = c.windowSequence == EIGHT_SHORT + local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1] + local numSwb = if short then Tables.NUM_SWB_SHORT[st.sfIndex + 1] else Tables.NUM_SWB_LONG[st.sfIndex + 1] + local maxBands = if short then Tables.TNS_MAX_BANDS_SHORT[st.sfIndex + 1] else Tables.TNS_MAX_BANDS_LONG[st.sfIndex + 1] + local mmm = math.min(maxBands, c.maxSfb) + if mmm == 0 then + return + end + local spec = c.spec + for w, list in c.tnsFilters do + local bottom = numSwb + for _, f in list do + local top = bottom + bottom = math.max(0, top - f[1]) + local order = f[2] + if order > 0 then + local start = swb[math.min(bottom, mmm) + 1] + local stop = swb[math.min(top, mmm) + 1] + local size = stop - start + if size > 0 then + local inc = 1 + local p = (w - 1) * 128 + start + 1 + if f[3] == 1 then + inc = -1 + p = (w - 1) * 128 + stop + end + for m = 0, size - 1 do + local y = spec[p] + local lim = if m < order then m else order + for i = 1, lim do + y -= spec[p - i * inc] * f[3 + i] + end + spec[p] = y + p += inc + end + end + end + end + end +end + +-- the spectral data of one channel, dequantised into c.spec (also pulses, noise, intensity zeros) +local function spectralData(st: State, c: Channel, pulses: { number }?): string? + local short = c.windowSequence == EIGHT_SHORT + local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1] + local spec = c.spec + for i = 1, 1024 do + spec[i] = 0 + end + local maxSfb = c.maxSfb + local bt, sf = c.bandType, c.sf + local win = 0 + for g = 0, c.numGroups - 1 do + local glen = c.groupLen[g + 1] + for s = 0, maxSfb - 1 do + local idx = g * maxSfb + s + 1 + local cb = bt[idx] + local lo, hi = swb[s + 1], swb[s + 2] + local width = hi - lo + if cb == ZERO_HCB or cb == INTENSITY_HCB or cb == INTENSITY_HCB2 then + -- zeros (intensity bands are filled from the other channel later) + continue + elseif cb == NOISE_HCB then + local scale = 2 ^ (0.25 * sf[idx]) + for w = 0, glen - 1 do + local base = (win + w) * 128 + lo + local energy = 0 + local r = st.random + for k = 1, width do + r = (r * 1664525 + 1013904223) % 4294967296 + local v = if r >= 2147483648 then r - 4294967296 else r + spec[base + k] = v + energy += v * v + end + st.random = r + local m = if energy > 0 then scale / sqrt(energy) else 0 + for k = 1, width do + spec[base + k] *= m + end + end + continue + end + local bk = SPEC_BOOK[cb] + local dim, uns, mod, off = DIM[cb], UNSIGNED[cb], MOD[cb], OFF[cb] + local gain = 2 ^ (0.25 * (sf[idx] - 100)) + for w = 0, glen - 1 do + local base = (win + w) * 128 + lo + local k = 0 + while k < width do + local sym = huff(bk) + if sym < 0 then + return "bad spectral code" + end + -- unpack the symbol into dim values (first value most significant) + local vals1, vals2, vals3, vals4 + if dim == 4 then + vals4 = sym % mod - off + sym = (sym - (sym % mod)) / mod + vals3 = sym % mod - off + sym = (sym - (sym % mod)) / mod + vals2 = sym % mod - off + sym = (sym - (sym % mod)) / mod + vals1 = sym % mod - off + else + vals2 = sym % mod - off + vals1 = (sym - (sym % mod)) / mod - off + end + if uns then + if vals1 ~= 0 and getBits(1) == 1 then + vals1 = -vals1 + end + if vals2 ~= 0 and getBits(1) == 1 then + vals2 = -vals2 + end + if dim == 4 then + if vals3 ~= 0 and getBits(1) == 1 then + vals3 = -vals3 + end + if vals4 ~= 0 and getBits(1) == 1 then + vals4 = -vals4 + end + end + if cb == ESC_HCB then + for e = 1, 2 do + local v = if e == 1 then vals1 else vals2 + if v == 16 or v == -16 then + local n = 0 + while getBits(1) == 1 do + n += 1 + if n > 8 or OVER then + return "bad escape" + end + end + local esc = 2 ^ (n + 4) + getBits(n + 4) + if v < 0 then + esc = -esc + end + if e == 1 then + vals1 = esc + else + vals2 = esc + end + end + end + end + end + local p = base + k + 1 + spec[p] = vals1 + spec[p + 1] = vals2 + if dim == 4 then + spec[p + 2] = vals3 + spec[p + 3] = vals4 + end + k += dim + end + if OVER then + return "spectral data runs past the end" + end + end + -- dequantise (pulses are added to the quantised values first: long windows only, applied below) + if not pulses then + for w = 0, glen - 1 do + local base = (win + w) * 128 + lo + for k = 1, width do + local q = spec[base + k] + if q ~= 0 then + local aq = if q < 0 then -q else q + local v = (POW43[aq + 1] or aq ^ (4 / 3)) * gain + spec[base + k] = if q < 0 then -v else v + end + end + end + end + end + win += glen + end + if pulses then + -- long window: add the pulses to the quantised values, then dequantise every band + for i = 1, #pulses, 2 do + local pos = pulses[i] + 1 + if pos <= 1024 then + local q = spec[pos] + spec[pos] = if q > 0 then q + pulses[i + 1] else q - pulses[i + 1] + end + end + for s = 0, maxSfb - 1 do + local idx = s + 1 + local cb = bt[idx] + if cb ~= ZERO_HCB and cb < NOISE_HCB then + local gain = 2 ^ (0.25 * (sf[idx] - 100)) + for k = swb[s + 1] + 1, swb[s + 2] do + local q = spec[k] + if q ~= 0 then + local aq = if q < 0 then -q else q + local v = (POW43[aq + 1] or aq ^ (4 / 3)) * gain + spec[k] = if q < 0 then -v else v + end + end + end + end + end + return nil +end + +-- individual_channel_stream +local function ics(st: State, c: Channel, commonWindow: boolean): string? + local globalGain = getBits(8) + if not commonWindow then + local e = icsInfo(st, c) + if e then + return e + end + end + local e = sectionData(c) + if e then + return e + end + e = scaleFactors(c, globalGain) + if e then + return e + end + local pulses: { number }? = nil + if getBits(1) == 1 then + if c.windowSequence == EIGHT_SHORT then + return "pulse data in a short window" + end + local n = getBits(2) + 1 + local startSfb = getBits(6) + if startSfb >= Tables.NUM_SWB_LONG[st.sfIndex + 1] then + return "bad pulse start band" + end + local pos = Tables.SWB_LONG[st.sfIndex + 1][startSfb + 1] + local list = {} + for _ = 1, n do + pos += getBits(5) + table.insert(list, pos) + table.insert(list, getBits(4)) + end + pulses = list + end + c.tnsFilters = {} + if getBits(1) == 1 then + e = tnsData(st, c) + if e then + return e + end + end + if getBits(1) == 1 then + return "gain control (AAC SSR) is not supported" + end + if OVER then + return "channel stream runs past the end" + end + return spectralData(st, c, pulses) +end + +-- ------------------------------------------------------------------------------------------------ stereo +local function msStereo(st: State, l: Channel, r: Channel, mask: { number }) + local short = l.windowSequence == EIGHT_SHORT + local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1] + local maxSfb = l.maxSfb + local a, b = l.spec, r.spec + local win = 0 + for g = 0, l.numGroups - 1 do + local glen = l.groupLen[g + 1] + for s = 0, maxSfb - 1 do + local idx = g * maxSfb + s + 1 + if mask[idx] == 1 and l.bandType[idx] < NOISE_HCB and r.bandType[idx] < NOISE_HCB then + for w = 0, glen - 1 do + local base = (win + w) * 128 + for k = base + swb[s + 1] + 1, base + swb[s + 2] do + local m, sd = a[k], b[k] + a[k], b[k] = m + sd, m - sd + end + end + end + end + win += glen + end +end + +local function intensity(st: State, l: Channel, r: Channel, mask: { number }, msPresent: number) + local short = r.windowSequence == EIGHT_SHORT + local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1] + local maxSfb = r.maxSfb + local a, b = l.spec, r.spec + local win = 0 + for g = 0, r.numGroups - 1 do + local glen = r.groupLen[g + 1] + for s = 0, maxSfb - 1 do + local idx = g * maxSfb + s + 1 + local cb = r.bandType[idx] + if cb == INTENSITY_HCB or cb == INTENSITY_HCB2 then + local sign = if cb == INTENSITY_HCB then 1 else -1 + if msPresent ~= 0 and mask[idx] == 1 then + sign = -sign + end + local scale = sign * 0.5 ^ (0.25 * r.sf[idx]) + for w = 0, glen - 1 do + local base = (win + w) * 128 + for k = base + swb[s + 1] + 1, base + swb[s + 2] do + b[k] = a[k] * scale + end + end + end + end + win += glen + end +end + +-- ------------------------------------------------------------------------------------------------ filterbank +local function filterbank(st: State, c: Channel, out: { number }, stride: number, offset: number) + local seq, shape, prev = c.windowSequence, c.windowShape, c.prevShape + local spec, overlap = c.spec, c.overlap + local frame = st.frame + local scale = 1 / 32768 + if seq == EIGHT_SHORT then + for i = 1, 2048 do + frame[i] = 0 + end + local tmp = st.short + local rise0 = if prev == 1 then KBD_SHORT else SINE_SHORT + local wcur = if shape == 1 then KBD_SHORT else SINE_SHORT + for w = 0, 7 do + Mdct.inverse(PLAN_SHORT, spec, w * 128 + 1, 1, tmp, 1, 2 / 256) + local rise = if w == 0 then rise0 else wcur + local base = 448 + w * 128 + for n = 1, 128 do + frame[base + n] += tmp[n] * rise[n] + frame[base + 128 + n] += tmp[128 + n] * wcur[128 + n] + end + end + else + local t = st.time + Mdct.inverse(PLAN_LONG, spec, 1, 1, t, 1, 2 / 2048) + -- left half + if seq == LONG_STOP then + local rise = if prev == 1 then KBD_SHORT else SINE_SHORT + for n = 1, 448 do + frame[n] = 0 + end + for n = 1, 128 do + frame[448 + n] = t[448 + n] * rise[n] + end + for n = 577, 1024 do + frame[n] = t[n] + end + else + local rise = if prev == 1 then KBD_LONG else SINE_LONG + for n = 1, 1024 do + frame[n] = t[n] * rise[n] + end + end + -- right half + if seq == LONG_START then + local fall = if shape == 1 then KBD_SHORT else SINE_SHORT + for n = 1025, 1472 do + frame[n] = t[n] + end + for n = 1, 128 do + frame[1472 + n] = t[1472 + n] * fall[128 + n] + end + for n = 1601, 2048 do + frame[n] = 0 + end + else + local fall = if shape == 1 then KBD_LONG else SINE_LONG + for n = 1025, 2048 do + frame[n] = t[n] * fall[n] + end + end + end + local p = offset + for n = 1, 1024 do + out[p] = (frame[n] + overlap[n]) * scale + overlap[n] = frame[1024 + n] + p += stride + end + c.prevShape = shape +end + +-- ------------------------------------------------------------------------------------------------ frame +-- frame(st, buf, off, len) -> channels decoded | nil, message. Output: st.pcm, 1024 frames interleaved. +function Decode.frame(st: State, buf: buffer, off: number, len: number): (number?, string?) + if buffer.len(B) < len + 16 then + B = buffer.create(len + 256) + end + buffer.copy(B, 0, buf, off, len) + buffer.fill(B, len, 0, 16) + BP, BL, OVER = 0, len * 8, false + local chans = st.ch + local nextCh = 1 + local order: { Channel } = {} + local lastElement = -1 + while true do + if BP + 3 > BL then + break -- tolerate a missing END + end + local id = getBits(3) + if id == 7 then + break + end + if id == 0 or id == 3 then -- SCE / LFE + getBits(4) + local c = chans[nextCh] + if not c then + c = newChannel() + chans[nextCh] = c + end + local e = ics(st, c, false) + if e then + return nil, e + end + applyTns(st, c) + table.insert(order, c) + nextCh += 1 + lastElement = id + elseif id == 1 then -- CPE + getBits(4) + local l, r = chans[nextCh], chans[nextCh + 1] + if not l then + l = newChannel() + chans[nextCh] = l + end + if not r then + r = newChannel() + chans[nextCh + 1] = r + end + local common = getBits(1) == 1 + local msPresent = 0 + local mask = table.create(8 * 64, 0) + if common then + local e = icsInfo(st, l) + if e then + return nil, e + end + r.windowSequence, r.windowShape, r.maxSfb, r.numGroups = l.windowSequence, l.windowShape, l.maxSfb, l.numGroups + for i = 1, 8 do + r.groupLen[i] = l.groupLen[i] + end + msPresent = getBits(2) + if msPresent == 1 then + for i = 1, l.numGroups * l.maxSfb do + mask[i] = getBits(1) + end + elseif msPresent == 2 then + for i = 1, l.numGroups * l.maxSfb do + mask[i] = 1 + end + elseif msPresent == 3 then + return nil, "reserved ms_mask_present" + end + end + local e = ics(st, l, common) + if e then + return nil, e + end + e = ics(st, r, common) + if e then + return nil, e + end + if common and msPresent ~= 0 then + msStereo(st, l, r, mask) + end + if common then + intensity(st, l, r, mask, msPresent) + end + applyTns(st, l) + applyTns(st, r) + table.insert(order, l) + table.insert(order, r) + nextCh += 2 + lastElement = id + elseif id == 2 then + return nil, "coupling channel elements are not supported" + elseif id == 4 then -- DSE + getBits(4) + local align = getBits(1) + local count = getBits(8) + if count == 255 then + count += getBits(8) + end + if align == 1 then + BP = (BP + 7) // 8 * 8 + end + BP += count * 8 + elseif id == 5 then -- PCE: skipped here (parsed from the configuration) + return nil, "program config element inside the stream is not supported" + elseif id == 6 then -- FIL + local count = getBits(4) + if count == 15 then + count += getBits(8) - 1 + end + if count > 0 then + local start = BP + local kind = getBits(4) + if kind == 13 or kind == 14 then -- EXT_SBR_DATA / EXT_SBR_DATA_CRC + st.sbr = true + end + st.extensions += 1 + local hook = st.onExtension + if hook then + hook(kind, lastElement, B, start, count * 8) + end + BP = start + count * 8 + end + end + if OVER or BP > BL then + return nil, "frame runs past the end" + end + if nextCh > 9 then + return nil, "more than 8 channels" + end + end + local n = #order + if n == 0 then + return 0, nil + end + local pcm = st.pcm + local map = st.map + for i, c in order do + local o = if map and map[i] then map[i] else i + filterbank(st, c, pcm, n, o) + end + return n, nil +end + +function Decode.state(sfIndex: number): State + return { + sfIndex = sfIndex, + channels = 0, + frameLength = 1024, + ch = {}, + pcm = table.create(1024 * 8, 0), + random = 0x1f2e3d4c, + time = table.create(2048, 0), + frame = table.create(2048, 0), + short = table.create(256, 0), + onExtension = nil, + extensions = 0, + sbr = false, + map = nil, + } +end + +local _ = abs +local _2 = floor +return Decode diff --git a/src/Formats/codecs/Aac/Tables.luau b/src/Formats/codecs/Aac/Tables.luau new file mode 100644 index 0000000..65305fb --- /dev/null +++ b/src/Formats/codecs/Aac/Tables.luau @@ -0,0 +1,335 @@ +--!strict +-- codecs/Aac/Tables: the AAC-LC tables of ISO/IEC 14496-3 (subpart 4, Annex 4.A): the scalefactor and the eleven +-- spectral Huffman codebooks (code, length per symbol), the scalefactor band offsets per sampling rate (1024 and 128 +-- lines) and the TNS band limits. Transcribed from FFmpeg libavcodec/aactab.c (tables of the standard, no code; +-- see licenses/NOTICE.md). Generated; do not edit. +local Tables = {} + +Tables.SF_CODES = { + 262120, 262118, 262119, 262117, 524277, 524273, 524269, 524278, 524270, 524271, 524272, 524284, 524285, 524287, 524286, 524279, + 524280, 524283, 524281, 262116, 524282, 262115, 131055, 131056, 65525, 131054, 65522, 65523, 65524, 65521, 32758, 32759, + 16377, 16373, 16375, 16371, 16374, 16370, 8183, 8181, 4089, 4087, 4086, 2041, 4084, 2040, 1017, 1015, + 1013, 504, 503, 250, 248, 246, 121, 58, 56, 26, 11, 4, 0, 10, 12, 27, + 57, 59, 120, 122, 247, 249, 502, 505, 1012, 1014, 1016, 2037, 2036, 2038, 2039, 4085, + 4088, 8180, 8182, 8184, 16376, 16372, 65520, 32756, 65526, 32757, 262114, 524249, 524250, 524251, 524252, 524253, + 524254, 524248, 524242, 524243, 524244, 524245, 524246, 524274, 524255, 524263, 524264, 524265, 524266, 524267, 524262, 524256, + 524257, 524258, 524259, 524260, 524261, 524247, 524268, 524276, 524275, +} + +Tables.SF_BITS = { + 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 18, 19, 18, 17, 17, 16, 17, 16, 16, 16, 16, + 15, 15, 14, 14, 14, 14, 14, 14, 13, 13, 12, 12, 12, 11, 12, 11, 10, 10, 10, 9, 9, 8, 8, 8, 7, 6, 6, 5, 4, 3, + 1, 4, 4, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 10, 11, 11, 11, 11, 12, 12, 13, 13, 13, 14, 14, 16, 15, 16, 15, + 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, + 19, +} + +Tables.SPEC_CODES = { + { + 2040, 497, 2045, 1013, 104, 1008, 2039, 492, 2037, 1009, 114, 1012, 116, 17, 118, 491, + 108, 1014, 2044, 481, 2033, 496, 97, 502, 2034, 490, 2043, 498, 105, 493, 119, 23, + 111, 486, 100, 485, 103, 21, 98, 18, 0, 20, 101, 22, 109, 489, 99, 484, + 107, 19, 113, 483, 112, 499, 2046, 487, 2035, 495, 96, 494, 2032, 482, 2042, 1011, + 106, 488, 117, 16, 115, 500, 110, 1015, 2038, 480, 2041, 1010, 102, 501, 2047, 503, + 2036, + }, + { + 499, 111, 509, 235, 35, 234, 503, 232, 506, 242, 45, 112, 32, 6, 43, 110, + 40, 233, 505, 102, 248, 231, 27, 241, 500, 107, 501, 236, 42, 108, 44, 10, + 39, 103, 26, 245, 36, 8, 31, 9, 0, 7, 29, 11, 48, 239, 28, 100, + 30, 12, 41, 243, 47, 240, 508, 113, 498, 244, 33, 230, 247, 104, 504, 238, + 34, 101, 49, 2, 38, 237, 37, 106, 507, 114, 510, 105, 46, 246, 511, 109, + 502, + }, + { + 0, 9, 239, 11, 25, 240, 491, 486, 1010, 10, 53, 495, 52, 55, 489, 493, + 487, 1011, 494, 1005, 8186, 492, 498, 2041, 2040, 1016, 4088, 8, 56, 1014, 54, 117, + 1009, 1003, 1004, 4084, 24, 118, 2036, 57, 116, 1007, 499, 500, 2038, 488, 1002, 8188, + 242, 497, 4091, 1013, 2035, 4092, 238, 1015, 32766, 496, 2037, 32765, 8187, 16378, 65535, 241, + 1008, 16380, 490, 1006, 16379, 4086, 4090, 32764, 2034, 4085, 65534, 1012, 2039, 32763, 4087, 4089, + 32762, + }, + { + 7, 22, 246, 24, 8, 239, 495, 243, 2040, 25, 23, 237, 21, 1, 226, 240, + 112, 1008, 494, 241, 2042, 238, 228, 1010, 2038, 1007, 2045, 5, 20, 242, 9, 4, + 229, 244, 232, 1012, 6, 2, 231, 3, 0, 107, 227, 105, 499, 235, 230, 1014, + 110, 106, 500, 1004, 496, 1017, 245, 236, 2043, 234, 111, 1015, 2041, 1011, 4095, 233, + 109, 1016, 108, 104, 501, 1006, 498, 2036, 2039, 1009, 4094, 1005, 497, 2037, 2046, 1013, + 2044, + }, + { + 8191, 4087, 2036, 2024, 1009, 2030, 2041, 4088, 8189, 4093, 2033, 1000, 488, 240, 492, 1006, + 2034, 4090, 4084, 1007, 498, 232, 112, 236, 496, 1002, 2035, 2027, 491, 234, 26, 8, + 25, 238, 495, 2029, 1008, 242, 115, 11, 0, 10, 113, 243, 2025, 2031, 494, 239, + 24, 9, 27, 235, 489, 2028, 2038, 1003, 499, 237, 114, 233, 497, 1005, 2039, 4086, + 2032, 1001, 493, 241, 490, 1004, 2040, 4089, 8188, 4092, 4085, 2026, 1011, 1010, 2037, 4091, + 8190, + }, + { + 2046, 1021, 497, 491, 500, 490, 496, 1020, 2045, 1014, 485, 234, 108, 113, 104, 240, + 486, 1015, 499, 239, 50, 39, 40, 38, 49, 235, 503, 488, 111, 46, 8, 4, + 6, 41, 107, 494, 495, 114, 45, 2, 0, 3, 47, 115, 506, 487, 110, 43, + 7, 1, 5, 44, 109, 492, 505, 238, 48, 36, 42, 37, 51, 236, 498, 1016, + 484, 237, 106, 112, 105, 116, 241, 1018, 2047, 1017, 502, 493, 504, 489, 501, 1019, + 2044, + }, + { + 0, 5, 55, 116, 242, 491, 1005, 2039, 4, 12, 53, 113, 236, 238, 494, 501, + 54, 52, 114, 234, 241, 489, 499, 1013, 115, 112, 235, 240, 497, 496, 1004, 1018, + 243, 237, 488, 495, 1007, 1009, 1017, 2043, 493, 239, 490, 498, 1011, 1016, 2041, 2044, + 1006, 492, 500, 1012, 1015, 2040, 4093, 4094, 2038, 1008, 1010, 1014, 2042, 2045, 4092, 4095, + }, + { + 14, 5, 16, 48, 111, 241, 506, 1022, 3, 0, 4, 18, 44, 106, 117, 248, + 15, 2, 6, 20, 46, 105, 114, 245, 47, 17, 19, 42, 50, 108, 236, 250, + 113, 43, 45, 49, 109, 112, 242, 505, 239, 104, 51, 107, 110, 238, 249, 1020, + 504, 116, 115, 237, 240, 246, 502, 509, 1021, 243, 244, 247, 503, 507, 508, 1023, + }, + { + 0, 5, 55, 231, 478, 974, 985, 1992, 1997, 4040, 4061, 8164, 8172, 4, 12, 53, + 114, 234, 237, 482, 977, 979, 992, 2008, 4047, 4053, 54, 52, 113, 232, 236, 481, + 975, 989, 987, 2000, 4039, 4052, 4068, 230, 112, 233, 477, 483, 978, 988, 1996, 1994, + 2014, 4056, 4074, 8155, 479, 235, 476, 486, 981, 990, 1995, 2013, 2012, 4045, 4066, 4071, + 8161, 976, 480, 484, 982, 1989, 2001, 2011, 4050, 2016, 4057, 4075, 8163, 8169, 1988, 485, + 983, 1990, 1999, 2010, 4043, 4058, 4067, 4073, 8166, 8179, 8183, 2003, 984, 993, 2004, 2009, + 4051, 4062, 8157, 8153, 8162, 8170, 8177, 8182, 2002, 980, 986, 1991, 2007, 2018, 4046, 4059, + 8152, 8174, 16368, 8180, 16370, 2017, 991, 1993, 2006, 4042, 4048, 4069, 4070, 8171, 8175, 16371, + 16372, 16373, 4064, 1998, 2005, 4038, 4049, 4065, 8160, 8168, 8176, 16369, 16376, 16374, 32764, 4072, + 2015, 4041, 4055, 4060, 8156, 8159, 8173, 8181, 16377, 16379, 32765, 32766, 8167, 4044, 4054, 4063, + 8158, 8154, 8165, 8178, 16378, 16375, 16380, 16381, 32767, + }, + { + 34, 8, 29, 38, 95, 211, 463, 976, 983, 1005, 2032, 2038, 4093, 7, 0, 1, + 9, 32, 84, 96, 213, 220, 468, 973, 990, 2023, 28, 2, 6, 12, 30, 40, + 91, 205, 217, 462, 476, 985, 1009, 37, 11, 10, 13, 36, 87, 97, 204, 221, + 460, 478, 979, 999, 93, 33, 31, 35, 39, 89, 100, 216, 223, 466, 482, 989, + 1006, 209, 85, 41, 86, 88, 98, 206, 224, 226, 474, 980, 995, 2027, 457, 94, + 90, 92, 99, 202, 218, 455, 458, 480, 987, 1000, 2028, 483, 210, 203, 208, 215, + 219, 454, 469, 472, 970, 986, 2026, 2033, 481, 212, 207, 214, 222, 225, 464, 470, + 977, 981, 1010, 2030, 2043, 1001, 461, 456, 459, 465, 471, 479, 975, 992, 1007, 2022, + 2040, 4090, 1003, 477, 467, 473, 475, 978, 972, 988, 1002, 2029, 2035, 2041, 4089, 2034, + 974, 484, 971, 984, 982, 994, 997, 2024, 2036, 2037, 2039, 4091, 2042, 1004, 991, 993, + 996, 998, 1008, 2025, 2031, 4088, 4094, 4092, 4095, + }, + { + 0, 6, 25, 61, 156, 198, 423, 912, 962, 991, 2022, 2035, 4091, 2028, 4090, 4094, + 910, 5, 1, 8, 20, 55, 66, 146, 175, 401, 421, 437, 926, 960, 930, 973, + 2006, 174, 23, 7, 9, 24, 57, 64, 142, 163, 184, 409, 428, 449, 945, 918, + 958, 970, 157, 60, 21, 22, 26, 59, 68, 145, 165, 190, 406, 430, 441, 929, + 913, 933, 981, 148, 154, 54, 56, 58, 65, 140, 155, 176, 195, 414, 427, 444, + 927, 911, 937, 975, 147, 191, 62, 63, 67, 69, 158, 167, 185, 404, 418, 442, + 451, 934, 935, 955, 980, 159, 416, 143, 141, 144, 152, 166, 182, 196, 415, 431, + 447, 921, 959, 948, 969, 999, 168, 438, 171, 164, 170, 178, 194, 197, 408, 420, + 440, 908, 932, 964, 966, 989, 1000, 173, 943, 402, 189, 188, 398, 407, 410, 419, + 433, 909, 920, 951, 979, 977, 987, 2013, 180, 990, 425, 411, 412, 417, 426, 429, + 435, 907, 946, 952, 974, 993, 992, 2002, 2021, 183, 2019, 443, 424, 422, 432, 434, + 439, 923, 922, 954, 949, 982, 2007, 996, 2008, 2026, 186, 2024, 928, 445, 436, 906, + 452, 914, 938, 944, 956, 983, 2004, 2012, 2011, 2005, 2032, 193, 2043, 968, 931, 917, + 925, 940, 942, 965, 984, 994, 998, 2020, 2023, 2016, 2025, 2039, 400, 2034, 915, 446, + 448, 916, 919, 941, 963, 961, 978, 2010, 2009, 2015, 2027, 2036, 2042, 405, 2040, 957, + 924, 939, 936, 947, 953, 976, 995, 997, 2018, 2014, 2029, 2033, 2041, 2044, 403, 4093, + 988, 950, 967, 972, 971, 985, 986, 2003, 2017, 2030, 2031, 2037, 2038, 4092, 4095, 413, + 450, 181, 161, 150, 151, 149, 153, 160, 162, 172, 169, 177, 179, 187, 192, 399, + 4, + }, +} + +Tables.SPEC_BITS = { + { + 11, 9, 11, 10, 7, 10, 11, 9, 11, 10, 7, 10, 7, 5, 7, 9, 7, 10, 11, 9, 11, 9, 7, 9, 11, 9, 11, 9, 7, 9, + 7, 5, 7, 9, 7, 9, 7, 5, 7, 5, 1, 5, 7, 5, 7, 9, 7, 9, 7, 5, 7, 9, 7, 9, 11, 9, 11, 9, 7, 9, + 11, 9, 11, 10, 7, 9, 7, 5, 7, 9, 7, 10, 11, 9, 11, 10, 7, 9, 11, 9, 11, + }, + { + 9, 7, 9, 8, 6, 8, 9, 8, 9, 8, 6, 7, 6, 5, 6, 7, 6, 8, 9, 7, 8, 8, 6, 8, 9, 7, 9, 8, 6, 7, + 6, 5, 6, 7, 6, 8, 6, 5, 6, 5, 3, 5, 6, 5, 6, 8, 6, 7, 6, 5, 6, 8, 6, 8, 9, 7, 9, 8, 6, 8, + 8, 7, 9, 8, 6, 7, 6, 4, 6, 8, 6, 7, 9, 7, 9, 7, 6, 8, 9, 7, 9, + }, + { + 1, 4, 8, 4, 5, 8, 9, 9, 10, 4, 6, 9, 6, 6, 9, 9, 9, 10, 9, 10, 13, 9, 9, 11, 11, 10, 12, 4, 6, 10, + 6, 7, 10, 10, 10, 12, 5, 7, 11, 6, 7, 10, 9, 9, 11, 9, 10, 13, 8, 9, 12, 10, 11, 12, 8, 10, 15, 9, 11, 15, + 13, 14, 16, 8, 10, 14, 9, 10, 14, 12, 12, 15, 11, 12, 16, 10, 11, 15, 12, 12, 15, + }, + { + 4, 5, 8, 5, 4, 8, 9, 8, 11, 5, 5, 8, 5, 4, 8, 8, 7, 10, 9, 8, 11, 8, 8, 10, 11, 10, 11, 4, 5, 8, + 4, 4, 8, 8, 8, 10, 4, 4, 8, 4, 4, 7, 8, 7, 9, 8, 8, 10, 7, 7, 9, 10, 9, 10, 8, 8, 11, 8, 7, 10, + 11, 10, 12, 8, 7, 10, 7, 7, 9, 10, 9, 11, 11, 10, 12, 10, 9, 11, 11, 10, 11, + }, + { + 13, 12, 11, 11, 10, 11, 11, 12, 13, 12, 11, 10, 9, 8, 9, 10, 11, 12, 12, 10, 9, 8, 7, 8, 9, 10, 11, 11, 9, 8, + 5, 4, 5, 8, 9, 11, 10, 8, 7, 4, 1, 4, 7, 8, 11, 11, 9, 8, 5, 4, 5, 8, 9, 11, 11, 10, 9, 8, 7, 8, + 9, 10, 11, 12, 11, 10, 9, 8, 9, 10, 11, 12, 13, 12, 12, 11, 10, 10, 11, 12, 13, + }, + { + 11, 10, 9, 9, 9, 9, 9, 10, 11, 10, 9, 8, 7, 7, 7, 8, 9, 10, 9, 8, 6, 6, 6, 6, 6, 8, 9, 9, 7, 6, + 4, 4, 4, 6, 7, 9, 9, 7, 6, 4, 4, 4, 6, 7, 9, 9, 7, 6, 4, 4, 4, 6, 7, 9, 9, 8, 6, 6, 6, 6, + 6, 8, 9, 10, 9, 8, 7, 7, 7, 7, 8, 10, 11, 10, 9, 9, 9, 9, 9, 10, 11, + }, + { + 1, 3, 6, 7, 8, 9, 10, 11, 3, 4, 6, 7, 8, 8, 9, 9, 6, 6, 7, 8, 8, 9, 9, 10, 7, 7, 8, 8, 9, 9, + 10, 10, 8, 8, 9, 9, 10, 10, 10, 11, 9, 8, 9, 9, 10, 10, 11, 11, 10, 9, 9, 10, 10, 11, 12, 12, 11, 10, 10, 10, + 11, 11, 12, 12, + }, + { + 5, 4, 5, 6, 7, 8, 9, 10, 4, 3, 4, 5, 6, 7, 7, 8, 5, 4, 4, 5, 6, 7, 7, 8, 6, 5, 5, 6, 6, 7, + 8, 8, 7, 6, 6, 6, 7, 7, 8, 9, 8, 7, 6, 7, 7, 8, 8, 10, 9, 7, 7, 8, 8, 8, 9, 9, 10, 8, 8, 8, + 9, 9, 9, 10, + }, + { + 1, 3, 6, 8, 9, 10, 10, 11, 11, 12, 12, 13, 13, 3, 4, 6, 7, 8, 8, 9, 10, 10, 10, 11, 12, 12, 6, 6, 7, 8, + 8, 9, 10, 10, 10, 11, 12, 12, 12, 8, 7, 8, 9, 9, 10, 10, 11, 11, 11, 12, 12, 13, 9, 8, 9, 9, 10, 10, 11, 11, + 11, 12, 12, 12, 13, 10, 9, 9, 10, 11, 11, 11, 12, 11, 12, 12, 13, 13, 11, 9, 10, 11, 11, 11, 12, 12, 12, 12, 13, 13, + 13, 11, 10, 10, 11, 11, 12, 12, 13, 13, 13, 13, 13, 13, 11, 10, 10, 11, 11, 11, 12, 12, 13, 13, 14, 13, 14, 11, 10, 11, + 11, 12, 12, 12, 12, 13, 13, 14, 14, 14, 12, 11, 11, 12, 12, 12, 13, 13, 13, 14, 14, 14, 15, 12, 11, 12, 12, 12, 13, 13, + 13, 13, 14, 14, 15, 15, 13, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, + }, + { + 6, 5, 6, 6, 7, 8, 9, 10, 10, 10, 11, 11, 12, 5, 4, 4, 5, 6, 7, 7, 8, 8, 9, 10, 10, 11, 6, 4, 5, 5, + 6, 6, 7, 8, 8, 9, 9, 10, 10, 6, 5, 5, 5, 6, 7, 7, 8, 8, 9, 9, 10, 10, 7, 6, 6, 6, 6, 7, 7, 8, + 8, 9, 9, 10, 10, 8, 7, 6, 7, 7, 7, 8, 8, 8, 9, 10, 10, 11, 9, 7, 7, 7, 7, 8, 8, 9, 9, 9, 10, 10, + 11, 9, 8, 8, 8, 8, 8, 9, 9, 9, 10, 10, 11, 11, 9, 8, 8, 8, 8, 8, 9, 9, 10, 10, 10, 11, 11, 10, 9, 9, + 9, 9, 9, 9, 10, 10, 10, 11, 11, 12, 10, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 12, 11, 10, 9, 10, 10, 10, 10, + 10, 11, 11, 11, 11, 12, 11, 10, 10, 10, 10, 10, 10, 11, 11, 12, 12, 12, 12, + }, + { + 4, 5, 6, 7, 8, 8, 9, 10, 10, 10, 11, 11, 12, 11, 12, 12, 10, 5, 4, 5, 6, 7, 7, 8, 8, 9, 9, 9, 10, 10, + 10, 10, 11, 8, 6, 5, 5, 6, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 8, 7, 6, 6, 6, 7, 7, 8, 8, 8, + 9, 9, 9, 10, 10, 10, 10, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 8, 8, 7, 7, 7, 7, + 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 8, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 10, 8, 9, + 8, 8, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 10, 10, 8, 10, 9, 8, 8, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, + 10, 11, 8, 10, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 11, 11, 8, 11, 9, 9, 9, 9, 9, 9, 10, 10, 10, + 10, 10, 11, 10, 11, 11, 8, 11, 10, 9, 9, 10, 9, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 8, 11, 10, 10, 10, 10, 10, + 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 9, 11, 10, 9, 9, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 9, 11, 10, + 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 9, 12, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 12, + 12, 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 5, + }, +} + +Tables.SWB_LONG = { + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 96, + 108, 120, 132, 144, 156, 172, 188, 212, 240, 276, 320, 384, 448, 512, 576, 640, 704, 768, 832, 896, + 960, 1024, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 96, + 108, 120, 132, 144, 156, 172, 188, 212, 240, 276, 320, 384, 448, 512, 576, 640, 704, 768, 832, 896, + 960, 1024, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 100, + 112, 124, 140, 156, 172, 192, 216, 240, 268, 304, 344, 384, 424, 464, 504, 544, 584, 624, 664, 704, + 744, 784, 824, 864, 904, 944, 984, 1024, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120, + 132, 144, 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640, + 672, 704, 736, 768, 800, 832, 864, 896, 928, 1024, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120, + 132, 144, 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640, + 672, 704, 736, 768, 800, 832, 864, 896, 928, 1024, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120, + 132, 144, 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640, + 672, 704, 736, 768, 800, 832, 864, 896, 928, 960, 992, 1024, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 52, 60, 68, 76, 84, 92, 100, 108, + 116, 124, 136, 148, 160, 172, 188, 204, 220, 240, 260, 284, 308, 336, 364, 396, 432, 468, 508, 552, + 600, 652, 704, 768, 832, 896, 960, 1024, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 52, 60, 68, 76, 84, 92, 100, 108, + 116, 124, 136, 148, 160, 172, 188, 204, 220, 240, 260, 284, 308, 336, 364, 396, 432, 468, 508, 552, + 600, 652, 704, 768, 832, 896, 960, 1024, + }, + { + 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124, 136, 148, 160, 172, 184, + 196, 212, 228, 244, 260, 280, 300, 320, 344, 368, 396, 424, 456, 492, 532, 572, 616, 664, 716, 772, + 832, 896, 960, 1024, + }, + { + 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124, 136, 148, 160, 172, 184, + 196, 212, 228, 244, 260, 280, 300, 320, 344, 368, 396, 424, 456, 492, 532, 572, 616, 664, 716, 772, + 832, 896, 960, 1024, + }, + { + 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124, 136, 148, 160, 172, 184, + 196, 212, 228, 244, 260, 280, 300, 320, 344, 368, 396, 424, 456, 492, 532, 572, 616, 664, 716, 772, + 832, 896, 960, 1024, + }, + { + 0, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156, 172, 188, 204, 220, 236, 252, + 268, 288, 308, 328, 348, 372, 396, 420, 448, 476, 508, 544, 580, 620, 664, 712, 764, 820, 880, 944, + 1024, + }, + { + 0, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156, 172, 188, 204, 220, 236, 252, + 268, 288, 308, 328, 348, 372, 396, 420, 448, 476, 508, 544, 580, 620, 664, 712, 764, 820, 880, 944, + 1024, + }, +} + +Tables.SWB_SHORT = { + { + 0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128, + }, + { + 0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128, + }, + { + 0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128, + }, + { + 0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 64, 76, 92, 108, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 64, 76, 92, 108, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 60, 72, 88, 108, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 60, 72, 88, 108, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 60, 72, 88, 108, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 60, 72, 88, 108, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 60, 72, 88, 108, 128, + }, +} + +Tables.NUM_SWB_LONG = { + 41, 41, 47, 49, 49, 51, 47, 47, 43, 43, 43, 40, 40, +} + +Tables.NUM_SWB_SHORT = { + 12, 12, 12, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, +} + +Tables.TNS_MAX_BANDS_LONG = { + 31, 31, 34, 40, 42, 51, 46, 46, 42, 42, 42, 39, 39, +} + +Tables.TNS_MAX_BANDS_SHORT = { + 9, 9, 10, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, +} + +return Tables + diff --git a/src/Formats/codecs/Aac/init.luau b/src/Formats/codecs/Aac/init.luau new file mode 100644 index 0000000..c7e5e0b --- /dev/null +++ b/src/Formats/codecs/Aac/init.luau @@ -0,0 +1,336 @@ +--!strict +-- codecs/Aac: AAC-LC decoder (ISO/IEC 14496-3 subpart 4, ISO/IEC 13818-7): the AudioSpecificConfig (with a program +-- config element, explicit and backward-compatible SBR signalling), ADTS headers, and raw_data_block decoding +-- (codecs/Aac/Decode). A codec (layer 1): audio/m4a, audio/aac (ADTS), and later MP4 / MKV / MPEG-TS video build on it. +-- Written from the standard (tables: codecs/Aac/Tables); no third-party code. +-- Supports: AAC-LC (object type 2) 1 - 8 channels, all sampling rates, long / short / start / stop windows, sine and KBD +-- windows, M/S, intensity stereo, PNS, TNS, pulses. HE-AAC (SBR, PS: object types 5 / 29, or implicit SBR payloads) +-- decodes its AAC-LC core at the core rate; `decoder.onExtension` receives every FIL extension payload (the hook for a +-- later SBR / PS module), `decoder.sbr` says whether one was seen. Not supported: AAC Main prediction, LTP, SSR gain +-- control, coupling channels, 960-sample frames, ER / USAC object types (UNSUPPORTED). +-- +-- local Aac = require("@formats/codecs/Aac") +-- local dec, err = Aac.decoder(asc) -- an AudioSpecificConfig (buffer) or { objectType, sfIndex, channels } +-- local frames, err = dec:decode(buf, offset, length) -- one raw_data_block -> dec.pcm (frames * channels floats) +-- local h = Aac.adts(buf, offset, limit) -- an ADTS header: { headerSize, frameSize, objectType, sfIndex, ... } +-- +-- Never throws: bad data returns nil, Err. +local Err = require("@formats/core/Err") +local Bits = require("@formats/core/Bits") +local Decode = require("@formats/codecs/Aac/Decode") + +local Aac = {} + +Aac.RATES = { 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350 } +local CONFIG_CHANNELS = { 1, 2, 3, 4, 5, 6, 8 } +-- element order (AAC: C, L, R, ...) -> WAV order (L, R, C, LFE, ...) for channel configurations 3 .. 7 +local CONFIG_MAP: { [number]: { number } } = { + [3] = { 3, 1, 2 }, + [4] = { 3, 1, 2, 4 }, + [5] = { 3, 1, 2, 4, 5 }, + [6] = { 3, 1, 2, 5, 6, 4 }, + [7] = { 3, 7, 8, 1, 2, 5, 6, 4 }, +} + +export type Config = { + objectType: number, -- 2 = AAC-LC (the core object type when SBR / PS is signalled) + sfIndex: number, + sampleRate: number, -- the core rate + channelConfig: number, + channels: number, + sbr: boolean, -- SBR signalled (explicitly or backward-compatibly) + ps: boolean, + extensionRate: number?, -- the SBR output rate + frameLength: number, +} + +local function rateIndex(rate: number): number + -- the nearest standard rate (ISO 14496-3 table 4.82 mapping for explicit frequencies) + local best, bi = math.huge, 4 + for i, r in Aac.RATES do + if math.abs(r - rate) < best then + best, bi = math.abs(r - rate), i - 1 + end + end + return bi +end + +local function objectType(br: Bits.BitReader): number + local t = br:read(5) + if t == 31 then + t = 32 + br:read(6) + end + return t +end + +local function frequency(br: Bits.BitReader): (number, number) + local i = br:read(4) + if i == 15 then + local f = br:read(24) + return rateIndex(f), f + end + return i, Aac.RATES[i + 1] or 0 +end + +-- pce(br) -> channels (program_config_element) +local function pce(br: Bits.BitReader): number + br:read(4 + 2 + 4) + local front, side, back = br:read(4), br:read(4), br:read(4) + local lfe, assoc, cc = br:read(2), br:read(3), br:read(4) + if br:read(1) == 1 then + br:read(4) + end + if br:read(1) == 1 then + br:read(4) + end + if br:read(1) == 1 then + br:read(3) + end + local channels = 0 + for _ = 1, front + side + back do + channels += if br:read(1) == 1 then 2 else 1 + br:read(4) + end + channels += lfe + br:skip(lfe * 4 + assoc * 4 + cc * 5) + br:align() + br:skip(br:read(8) * 8) + return channels +end + +-- config(asc) -> Config | nil, Err: parse an AudioSpecificConfig +function Aac.config(asc: buffer): (Config?, Err.Err?) + if type(asc) ~= "buffer" or buffer.len(asc) < 2 then + return nil, Err.new(Err.TRUNCATED, "AudioSpecificConfig is shorter than 2 bytes") + end + local br = Bits.msbReader(asc) + local aot = objectType(br) + local sfi, rate = frequency(br) + local chcfg = br:read(4) + local sbr, ps = false, false + local extRate: number? = nil + if aot == 5 or aot == 29 then + sbr = true + ps = aot == 29 + local _, er = frequency(br) + extRate = er + aot = objectType(br) + if aot == 22 then + br:read(4) + end + end + if aot ~= 2 and aot ~= 1 and aot ~= 4 then + if aot == 0 or br.err then + return nil, Err.new(Err.CORRUPT, "bad AudioSpecificConfig") + end + return nil, Err.new(Err.UNSUPPORTED, "AAC object type " .. aot .. " (only AAC-LC)") + end + if aot ~= 2 then + return nil, Err.new(Err.UNSUPPORTED, if aot == 1 then "AAC Main" else "AAC LTP") + end + -- GASpecificConfig + local frameLengthFlag = br:read(1) + if br:read(1) == 1 then + br:read(14) + end + local ext = br:read(1) + local channels = CONFIG_CHANNELS[chcfg] or 0 + if chcfg == 0 then + channels = pce(br) + elseif chcfg > 7 then + return nil, Err.new(Err.UNSUPPORTED, "channel configuration " .. chcfg) + end + if ext == 1 then + br:read(1) -- extensionFlag3 + end + -- backward-compatible SBR signalling + if not sbr and br:bitsLeft() >= 16 then + if br:read(11) == 0x2b7 then + local et = objectType(br) + if et == 5 and br:read(1) == 1 then + sbr = true + local _, er = frequency(br) + extRate = er + if br:bitsLeft() >= 12 and br:read(11) == 0x548 then + ps = br:read(1) == 1 + end + end + end + end + if br.err and channels == 0 then + return nil, br.err + end + if sfi > 12 or rate <= 0 then + return nil, Err.new(Err.CORRUPT, "bad sampling frequency index " .. sfi) + end + if frameLengthFlag == 1 then + return nil, Err.new(Err.UNSUPPORTED, "960-sample AAC frames") + end + if channels < 1 or channels > 8 then + return nil, Err.new(Err.UNSUPPORTED, channels .. " channels") + end + return { + objectType = aot, + sfIndex = sfi, + sampleRate = rate, + channelConfig = chcfg, + channels = channels, + sbr = sbr, + ps = ps, + extensionRate = extRate, + frameLength = 1024, + }, nil +end + +-- asc(objectType, sfIndex, channelConfig) -> a 2-byte AudioSpecificConfig +function Aac.asc(aot: number, sfIndex: number, channelConfig: number): buffer + local b = buffer.create(2) + local v = aot * 2048 + sfIndex * 128 + channelConfig * 8 + buffer.writeu8(b, 0, bit32.rshift(v, 8)) + buffer.writeu8(b, 1, bit32.band(v, 255)) + return b +end + +export type Adts = { + headerSize: number, -- 7, or 9 with a CRC + frameSize: number, -- the whole frame, header included + objectType: number, + sfIndex: number, + sampleRate: number, + channelConfig: number, + blocks: number, -- raw_data_blocks in the frame (1 .. 4) + protected: boolean, +} + +-- adts(buf, offset, limit) -> Adts | nil (not a valid header at offset) +function Aac.adts(b: buffer, o: number, limit: number): Adts? + if o < 0 or o + 7 > limit or o + 7 > buffer.len(b) then + return nil + end + local b0, b1, b2, b3, b4, b5, b6 = buffer.readu8(b, o), buffer.readu8(b, o + 1), buffer.readu8(b, o + 2), buffer.readu8(b, o + 3), buffer.readu8(b, o + 4), buffer.readu8(b, o + 5), buffer.readu8(b, o + 6) + if b0 ~= 0xFF or bit32.band(b1, 0xF6) ~= 0xF0 then -- sync, layer 0 + return nil + end + local protected = bit32.band(b1, 1) == 0 + local profile = bit32.rshift(b2, 6) + local sfi = bit32.band(bit32.rshift(b2, 2), 15) + local ch = bit32.band(b2, 1) * 4 + bit32.rshift(b3, 6) + local size = bit32.band(b3, 3) * 2048 + b4 * 8 + bit32.rshift(b5, 5) + local blocks = bit32.band(b6, 3) + 1 + local hs = if protected then 9 else 7 + if sfi > 12 or size < hs then + return nil + end + return { + headerSize = hs, + frameSize = size, + objectType = profile + 1, + sfIndex = sfi, + sampleRate = Aac.RATES[sfi + 1], + channelConfig = ch, + blocks = blocks, + protected = protected, + } +end + +-- ------------------------------------------------------------------------------------------------ decoder +export type Decoder = { + config: Config, + channels: number, + sampleRate: number, + frameLength: number, + pcm: { number }, -- the last frame: 1024 * channels interleaved floats (-1 .. 1), WAV channel order + sbr: boolean, -- SBR payloads seen in the stream (implicit signalling) or signalled + onExtension: ((kind: number, element: number, buf: buffer, bitPos: number, bits: number) -> ())?, + decode: (self: Decoder, buf: buffer, offset: number?, length: number?) -> (number?, Err.Err?), + reset: (self: Decoder) -> (), + state: Decode.State, +} + +local function decode(self: Decoder, buf: buffer, offset: number?, length: number?): (number?, Err.Err?) + local o = offset or 0 + local n = length or (buffer.len(buf) - o) + if type(buf) ~= "buffer" or o < 0 or n < 0 or o + n > buffer.len(buf) then + return nil, Err.new(Err.ARG, "packet range out of the buffer") + end + local st = self.state + st.onExtension = self.onExtension + local chans, msg = Decode.frame(st, buf, o, n) + if not chans then + return nil, Err.new(Err.CORRUPT, msg or "bad frame", o) + end + if st.sbr then + self.sbr = true + end + if chans == 0 then + -- an empty frame (only fill elements): silence + for i = 1, 1024 * self.channels do + st.pcm[i] = 0 + end + return 1024, nil + end + if chans ~= self.channels then + return nil, Err.new(Err.CORRUPT, string.format("frame has %d channels, the configuration %d", chans, self.channels), o) + end + return 1024, nil +end + +local function reset(self: Decoder) + for _, c in self.state.ch do + for i = 1, 1024 do + c.overlap[i] = 0 + end + c.prevShape = 0 + end +end + +-- decoder(asc | { objectType?, sfIndex, channels }) -> Decoder | nil, Err +function Aac.decoder(asc: any): (Decoder?, Err.Err?) + local cfg: Config + if type(asc) == "buffer" then + local c, err = Aac.config(asc) + if not c then + return nil, err + end + cfg = c + elseif type(asc) == "table" and type(asc.sfIndex) == "number" and type(asc.channels) == "number" then + local sfi = asc.sfIndex + if sfi < 0 or sfi > 12 or asc.channels < 1 or asc.channels > 8 then + return nil, Err.new(Err.ARG, "bad sampling index / channels") + end + if (asc.objectType or 2) ~= 2 then + return nil, Err.new(Err.UNSUPPORTED, "AAC object type " .. asc.objectType .. " (only AAC-LC)") + end + cfg = { + objectType = 2, + sfIndex = sfi, + sampleRate = Aac.RATES[sfi + 1], + channelConfig = asc.channelConfig or asc.channels, + channels = asc.channels, + sbr = false, + ps = false, + frameLength = 1024, + } + else + return nil, Err.new(Err.ARG, "decoder: expected an AudioSpecificConfig buffer") + end + local st = Decode.state(cfg.sfIndex) + st.channels = cfg.channels + if cfg.channelConfig >= 3 then + st.map = CONFIG_MAP[cfg.channelConfig] + end + return { + config = cfg, + channels = cfg.channels, + sampleRate = cfg.sampleRate, + frameLength = 1024, + pcm = st.pcm, + sbr = cfg.sbr, + onExtension = nil, + decode = decode, + reset = reset, + state = st, + }, nil +end + +return Aac diff --git a/src/Formats/codecs/Alac/Decode.luau b/src/Formats/codecs/Alac/Decode.luau new file mode 100644 index 0000000..932d7e7 --- /dev/null +++ b/src/Formats/codecs/Alac/Decode.luau @@ -0,0 +1,427 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Alac/Decode: the ALAC frame decoder: elements SCE / CPE / LFE / DSE / FIL / END, the adaptive Golomb-Rice +-- residuals with zero runs, the adaptive FIR predictor (orders 0, 31 and 1 .. 30), stereo unmixing, shifted low bytes, +-- uncompressed (escape) frames, 16 / 20 / 24 / 32-bit samples. Written from the ALAC format as published by Apple +-- (ALACDecoder / ag_dec / dp_dec, Apache 2.0; behaviour, not code). Never throws: returns nil, message. +local readu32, readu8 = buffer.readu32, buffer.readu8 +local byteswap, lshift, rshift, band, countlz, bnot = bit32.byteswap, bit32.lshift, bit32.rshift, bit32.band, bit32.countlz, bit32.bnot +local floor = math.floor + +local Decode = {} + +export type State = { + frameLength: number, + bitDepth: number, + pb: number, + mb: number, + kb: number, + channels: number, + maxRun: number, + scratch: buffer, -- the packet + 16 zero bytes (reads past the end are safe; the overrun is checked) + pred: { { number } }, -- per element channel (0, 1): residuals / predictor output + mix: { { number } }, + shift: { number }, + out: { number }, -- interleaved output samples (integers), frames * channels +} + +local POW = table.create(64, 0) +for i = 0, 63 do + POW[i + 1] = 2 ^ i +end + +-- bit reader over st.scratch: pos = bit position. bits(n) for n <= 25. +local function bitsAt(b: buffer, pos: number, n: number): number + local w = byteswap(readu32(b, rshift(pos, 3))) + return rshift(lshift(w, band(pos, 7)), 32 - n) +end + +local function signExtend(v: number, bits: number): number + local m = POW[bits + 1] + v = v % m + if v >= m / 2 then + v -= m + end + return v +end + +-- the adaptive Golomb-Rice value: unary prefix (escape after 9 ones: `bps` raw bits), then k bits +local function scalar(b: buffer, pos: number, k: number, m: number, bps: number): (number, number) + local w = lshift(byteswap(readu32(b, rshift(pos, 3))), band(pos, 7)) + local pre = countlz(bnot(w)) + if pre >= 9 then + pos += 9 + local v + if bps > 25 then + v = bitsAt(b, pos, bps - 16) * 65536 + bitsAt(b, pos + bps - 16, 16) + else + v = bitsAt(b, pos, bps) + end + return v, pos + bps + end + pos += pre + 1 + if k == 1 then + return pre, pos + end + local v = bitsAt(b, pos, k) + local x = pre * m + if v > 1 then + return x + v - 1, pos + k + end + return x, pos + k - 1 +end + +-- residuals: n values into out[1..n]; returns the new bit position or -1 +local function rice(b: buffer, pos: number, limit: number, out: { number }, n: number, bps: number, mult: number, st: State): number + local history = st.mb + local kb = st.kb + local signMod = 0 + local i = 1 + while i <= n do + if pos > limit then + return -1 -- each value reads at most 41 bits past here: inside the 16 padding bytes + end + local k = 31 - countlz(floor(history / 512) + 3) + if k > kb then + k = kb + end + local x + x, pos = scalar(b, pos, k, POW[k + 1] - 1, bps) + x += signMod + signMod = 0 + out[i] = if x % 2 == 0 then x / 2 else -(x + 1) / 2 + if x > 0xFFFF then + history = 0xFFFF + else + history += x * mult - floor(history * mult / 512) + end + if history < 128 and i < n then + if pos > limit then + return -1 + end + local lg = if history > 0 then 31 - countlz(history) else 0 + k = 7 - lg + floor((history + 16) / 64) + if k > kb then + k = kb + end + local run + run, pos = scalar(b, pos, k, POW[k + 1] - 1, 16) + if run > 0 then + if run > n - i then + return -1 + end + for j = i + 1, i + run do + out[j] = 0 + end + i += run + end + if run < 0xFFFF then + signMod = 1 -- the next value is not 0 (unless the run hit its maximum) + end + history = 0 + end + i += 1 + end + return pos +end + +-- the adaptive FIR predictor: err[1..n] -> out[1..n] (may be the same array); coefs adapt in place +local function predict(err: { number }, out: { number }, n: number, bps: number, coefs: { number }, order: number, quant: number) + out[1] = err[1] + if n <= 1 then + return + end + if order == 0 then + if out ~= err then + for i = 2, n do + out[i] = err[i] + end + end + return + end + if order == 31 then + for i = 2, n do + out[i] = signExtend(out[i - 1] + err[i], bps) + end + return + end + local i = 2 + while i <= order + 1 and i <= n do + out[i] = signExtend(out[i - 1] + err[i], bps) + i += 1 + end + local half = if quant > 0 then POW[quant] else 0 + local qd = POW[quant + 1] + -- coefs[1] multiplies the most recent sample + while i <= n do + local d = out[i - order - 1] + local val = 0 + for j = 1, order do + val += (out[i - j] - d) * coefs[j] + end + val = floor((val + half) / qd) + local e = err[i] + out[i] = signExtend(val + d + e, bps) + if e ~= 0 then + local es = if e > 0 then 1 else -1 + -- adapt from the oldest sample to the newest while the error keeps its sign + for j = order, 1, -1 do + if e * es <= 0 then + break + end + local v = d - out[i - j] + local sgn = if v > 0 then es elseif v < 0 then -es else 0 + coefs[j] -= sgn + e -= floor(v * sgn / qd) * (order - j + 1) + end + end + i += 1 + end +end + +-- decode(st, buf, off, len) -> frames | nil, message. Samples land interleaved in st.out (integers), channels in the +-- ALAC element order. +function Decode.frame(st: State, buf: buffer, off: number, len: number): (number?, string?) + if len <= 0 then + return nil, "empty packet" + end + local b = st.scratch + if buffer.len(b) < len + 16 then + b = buffer.create(len + 64) + st.scratch = b + end + buffer.copy(b, 0, buf, off, len) + buffer.fill(b, len, 0, 16) + local limit = len * 8 + local pos = 0 + local channels = st.channels + local ch = 0 -- next output channel + local frames = -1 + local out = st.out + while true do + if pos + 3 > limit then + return nil, "frame runs past the end" + end + local tag = bitsAt(b, pos, 3) + pos += 3 + if tag == 7 then -- END + break + elseif tag == 0 or tag == 1 or tag == 3 then -- SCE / CPE / LFE + local nch = if tag == 1 then 2 else 1 + if ch + nch > channels then + return nil, "more channels than the configuration" + end + pos += 4 -- element instance tag + if bitsAt(b, pos, 12) ~= 0 then + return nil, "bad element header" + end + pos += 12 + local h = bitsAt(b, pos, 4) + pos += 4 + local partial = rshift(h, 3) + local shiftBytes = band(rshift(h, 1), 3) + local escape = band(h, 1) + if shiftBytes == 3 then + return nil, "bad shift" + end + local n = st.frameLength + if partial == 1 then + n = bitsAt(b, pos, 16) * 65536 + bitsAt(b, pos + 16, 16) + pos += 32 + end + if n < 1 or n > st.frameLength then + return nil, "bad frame length " .. n + end + if frames >= 0 and n ~= frames then + return nil, "elements of different lengths" + end + frames = n + if #out < n * channels then + for k = #out + 1, n * channels do + out[k] = 0 + end + end + local shift = shiftBytes * 8 + local bps = st.bitDepth - shift + nch - 1 + if bps > 32 or bps < 1 then + return nil, "bad sample size" + end + if pos > limit then + return nil, "frame runs past the end" + end + local mixBits, mixRes = 0, 0 + local p0, p1 = st.pred[1], st.pred[2] + local m0, m1 = st.mix[1], st.mix[2] + local shiftBuf = st.shift + if escape == 0 then + mixBits = bitsAt(b, pos, 8) + mixRes = bitsAt(b, pos + 8, 8) + pos += 16 + if mixRes >= 128 then + mixRes -= 256 + end + local mode, denShift, pbFactor, order = {}, {}, {}, {} + local coefs = { {}, {} } + for c = 1, nch do + local x = bitsAt(b, pos, 8) + local y = bitsAt(b, pos + 8, 8) + pos += 16 + mode[c], denShift[c] = rshift(x, 4), band(x, 15) + pbFactor[c], order[c] = rshift(y, 5), band(y, 31) + if pos + order[c] * 16 > limit then + return nil, "frame runs past the end" + end + for j = 1, order[c] do + local v = bitsAt(b, pos, 16) + pos += 16 + coefs[c][j] = if v >= 32768 then v - 65536 else v + end + end + if pos > limit then + return nil, "frame runs past the end" + end + local shiftPos = pos + if shift > 0 then + pos += shift * n * nch + end + for c = 1, nch do + local p = if c == 1 then p0 else p1 + local mb = if c == 1 then m0 else m1 + pos = rice(b, pos, limit, p, n, bps, floor(st.pb * pbFactor[c] / 4), st) + if pos < 0 or pos > limit then + return nil, "bad residuals" + end + if mode[c] == 15 then + predict(p, p, n, bps, {}, 31, 0) + elseif mode[c] ~= 0 then + return nil, "unknown prediction mode " .. mode[c] + end + predict(p, mb, n, bps, coefs[c], order[c], denShift[c]) + end + if shift > 0 then + local sp = shiftPos + for i = 1, n * nch do + shiftBuf[i] = bitsAt(b, sp, shift) + sp += shift + end + end + else + -- uncompressed: interleaved samples of bitDepth bits + local bits = st.bitDepth + if pos + n * nch * bits > limit then + return nil, "frame runs past the end" + end + for i = 1, n do + for c = 1, nch do + local v + if bits > 25 then + v = bitsAt(b, pos, bits - 16) * 65536 + bitsAt(b, pos + bits - 16, 16) + else + v = bitsAt(b, pos, bits) + end + pos += bits + v = signExtend(v, bits) + if c == 1 then + m0[i] = v + else + m1[i] = v + end + end + end + shift = 0 + end + -- unmix + shifted bytes -> interleaved output + local sm = POW[shift + 1] + if nch == 2 then + local den = POW[mixBits + 1] + for i = 1, n do + local u, v = m0[i], m1[i] + local l, r + if mixRes ~= 0 then + l = u + v - floor(mixRes * v / den) + r = l - v + else + l, r = u, v + end + if shift > 0 then + l = l * sm + shiftBuf[2 * i - 1] + r = r * sm + shiftBuf[2 * i] + end + local o = (i - 1) * channels + ch + 1 + out[o] = l + out[o + 1] = r + end + else + for i = 1, n do + local v = m0[i] + if shift > 0 then + v = v * sm + shiftBuf[i] + end + out[(i - 1) * channels + ch + 1] = v + end + end + ch += nch + elseif tag == 4 then -- DSE + pos += 4 + local align = bitsAt(b, pos, 1) + local count = bitsAt(b, pos + 1, 8) + pos += 9 + if count == 255 then + count += bitsAt(b, pos, 8) + pos += 8 + end + if align == 1 then + pos = (pos + 7) // 8 * 8 + end + pos += count * 8 + elseif tag == 6 then -- FIL + local count = bitsAt(b, pos, 4) + pos += 4 + if count == 15 then + count += bitsAt(b, pos, 8) - 1 + pos += 8 + end + pos += count * 8 + else + return nil, "unsupported element " .. tag + end + if pos > limit then + return nil, "frame runs past the end" + end + end + if frames < 0 then + return 0, nil + end + if ch < channels then + -- missing channels: silence + for i = 1, frames do + for c = ch + 1, channels do + out[(i - 1) * channels + c] = 0 + end + end + end + return frames, nil +end + +-- the scratch state for a configuration +function Decode.state(cfg: any): State + local n = cfg.frameLength + return { + frameLength = n, + bitDepth = cfg.bitDepth, + pb = cfg.pb, + mb = cfg.mb, + kb = cfg.kb, + channels = cfg.channels, + maxRun = cfg.maxRun, + scratch = buffer.create(math.max(64, cfg.maxFrameBytes or 0) + 64), + pred = { table.create(n, 0), table.create(n, 0) }, + mix = { table.create(n, 0), table.create(n, 0) }, + shift = table.create(n * 2, 0), + out = table.create(n * cfg.channels, 0), + } +end + +local _ = readu8 +return Decode diff --git a/src/Formats/codecs/Alac/Encode.luau b/src/Formats/codecs/Alac/Encode.luau new file mode 100644 index 0000000..4309bd5 --- /dev/null +++ b/src/Formats/codecs/Alac/Encode.luau @@ -0,0 +1,427 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Alac/Encode: an ALAC frame encoder: per element (SCE / CPE) the stereo mix (mixBits 2, the best mixRes of +-- 0 .. 4 by first-difference energy), per channel LPC coefficients (Levinson-Durbin on a windowed autocorrelation, +-- orders 4 and 8 tried, quantised with denShift 9), residuals through the same adaptive FIR the decoder runs, the +-- adaptive Golomb-Rice code with zero runs; an uncompressed (escape) frame when that is smaller. 16 / 20 / 24-bit +-- input. Written for this library from the ALAC format; no third-party code. Never throws. +local band, rshift, bor, lshift, countlz = bit32.band, bit32.rshift, bit32.bor, bit32.lshift, bit32.countlz +local readu8, writeu8 = buffer.readu8, buffer.writeu8 +local floor, abs = math.floor, math.abs + +local Encode = {} + +local POW = table.create(64, 0) +for i = 0, 63 do + POW[i + 1] = 2 ^ i +end + +local DENSHIFT = 9 +local PB_FACTOR = 4 + +export type State = { + frameLength: number, + bitDepth: number, + pb: number, + mb: number, + kb: number, + channels: number, + out: buffer, -- packet scratch + pos: number, -- bit position in out + cap: number, -- bits available + u: { number }, + v: { number }, + err: { number }, + work: { number }, +} + +-- ------------------------------------------------------------------------------------------------ bit writer +local function put(st: State, v: number, n: number) + local pos = st.pos + if pos + n > st.cap then + st.pos = st.cap + 1 -- overflow: the caller falls back to an uncompressed frame + return + end + local b = st.out + while n > 0 do + local byte = rshift(pos, 3) + local free = 8 - band(pos, 7) + local take = if n < free then n else free + local bits = band(rshift(v, n - take), POW[take + 1] - 1) + writeu8(b, byte, bor(readu8(b, byte), lshift(bits, free - take))) + pos += take + n -= take + end + st.pos = pos +end + +local function putBig(st: State, v: number, n: number) + if n > 24 then + local lo = v % 65536 + put(st, (v - lo) / 65536, n - 16) + put(st, lo, 16) + else + put(st, v, n) + end +end + +-- ------------------------------------------------------------------------------------------------ rice code +local function signExtend(v: number, bits: number): number + local m = POW[bits + 1] + v = v % m + if v >= m / 2 then + v -= m + end + return v +end + +-- the bits of one scalar (no writing) +local function scalarBits(x: number, k: number, m: number, bps: number): number + local pre = if k == 1 then x else floor(x / m) + if pre >= 9 then + return 9 + bps + end + if k == 1 then + return pre + 1 + end + local r = x - pre * m + return pre + 1 + (if r == 0 then k - 1 else k) +end + +local function scalar(st: State, x: number, k: number, m: number, bps: number) + local pre = if k == 1 then x else floor(x / m) + if pre >= 9 then + put(st, 511, 9) + putBig(st, x, bps) + return + end + -- pre ones and a zero + put(st, POW[pre + 2] - 2, pre + 1) + if k ~= 1 then + local r = x - pre * m + if r == 0 then + put(st, 0, k - 1) + else + put(st, r + 1, k) + end + end +end + +-- code the residuals e[1..n] (write = false: just count the bits) +local function rice(st: State, e: { number }, n: number, bps: number, mult: number, write: boolean): number + local history = st.mb + local kb = st.kb + local signMod = 0 + local bits = 0 + local i = 1 + while i <= n do + local k = 31 - countlz(floor(history / 512) + 3) + if k > kb then + k = kb + end + local v = e[i] + local zz = if v >= 0 then 2 * v else -2 * v - 1 + local x = zz - signMod + signMod = 0 + local m = POW[k + 1] - 1 + if write then + scalar(st, x, k, m, bps) + else + bits += scalarBits(x, k, m, bps) + end + if zz > 0xFFFF then -- the decoder adapts on the value with its sign modifier added back + history = 0xFFFF + else + history += zz * mult - floor(history * mult / 512) + end + if history < 128 and i < n then + local lg = if history > 0 then 31 - countlz(history) else 0 + k = 7 - lg + floor((history + 16) / 64) + if k > kb then + k = kb + end + local run = 0 + while i + run < n and e[i + run + 1] == 0 and run < 0xFFFF do + run += 1 + end + m = POW[k + 1] - 1 + if write then + scalar(st, run, k, m, 16) + else + bits += scalarBits(run, k, m, 16) + end + i += run + if run < 0xFFFF then + signMod = 1 + end + history = 0 + end + i += 1 + end + return bits +end + +-- ------------------------------------------------------------------------------------------------ prediction +-- residuals of x[1..n] under the decoder's adaptive FIR starting from coefs (adapted in place, like the decoder) +local function residuals(x: { number }, e: { number }, n: number, bps: number, coefs: { number }, order: number, quant: number) + e[1] = x[1] + if n <= 1 then + return + end + local i = 2 + while i <= order + 1 and i <= n do + e[i] = signExtend(x[i] - x[i - 1], bps) + i += 1 + end + local half = POW[quant] + local qd = POW[quant + 1] + while i <= n do + local d = x[i - order - 1] + local val = 0 + for j = 1, order do + val += (x[i - j] - d) * coefs[j] + end + val = floor((val + half) / qd) + local r = signExtend(x[i] - val - d, bps) + e[i] = r + if r ~= 0 then + local es = if r > 0 then 1 else -1 + for j = order, 1, -1 do + if r * es <= 0 then + break + end + local v = d - x[i - j] + local sgn = if v > 0 then es elseif v < 0 then -es else 0 + coefs[j] -= sgn + r -= floor(v * sgn / qd) * (order - j + 1) + end + end + i += 1 + end +end + +-- LPC coefficients of x[1..n] for the given order (Levinson-Durbin on a Welch-windowed autocorrelation), quantised +local function lpc(x: { number }, n: number, order: number, work: { number }): { number } + local ac = table.create(order + 1, 0) + for i = 1, n do + local t = (2 * (i - 1) - (n - 1)) / (n + 1) + work[i] = x[i] * (1 - t * t) + end + for lag = 0, order do + local s = 0 + for i = lag + 1, n do + s += work[i] * work[i - lag] + end + ac[lag + 1] = s + end + local coefs = table.create(order, 0) + if ac[1] <= 0 then + return coefs + end + ac[1] *= 1.0001 -- a little white noise: keeps the recursion stable + local a = table.create(order + 1, 0) + local tmp = table.create(order + 1, 0) + local errv = ac[1] + for i = 1, order do + local acc = ac[i + 1] + for j = 1, i - 1 do + acc -= a[j] * ac[i - j + 1] + end + local kc = acc / errv + for j = 1, i - 1 do + tmp[j] = a[j] - kc * a[i - j] + end + for j = 1, i - 1 do + a[j] = tmp[j] + end + a[i] = kc + errv *= (1 - kc * kc) + if errv <= 0 then + break + end + end + local scale = POW[DENSHIFT + 1] + for j = 1, order do + coefs[j] = math.clamp(floor(a[j] * scale + 0.5), -32768, 32767) + end + return coefs +end + +-- choose order / coefficients for one channel: returns order, coefs (as transmitted), bits +local function analyse(st: State, x: { number }, n: number, bps: number): (number, { number }, number) + local mult = floor(st.pb * PB_FACTOR / 4) + local bestOrder, bestCoefs, bestBits = 0, {}, math.huge + for _, order in { 4, 8 } do + if order >= n then + continue + end + local coefs = lpc(x, n, order, st.work) + local trial = table.clone(coefs) + residuals(x, st.err, n, bps, trial, order, DENSHIFT) + local bits = rice(st, st.err, n, bps, mult, false) + order * 16 + if bits < bestBits then + bestOrder, bestCoefs, bestBits = order, coefs, bits + end + end + if bestBits == math.huge then + -- tiny frames: first-order prediction (order 31 is only a decoder mode; order 0 = no prediction) + for i = 1, n do + st.err[i] = x[i] + end + return 0, {}, rice(st, st.err, n, bps, mult, false) + end + return bestOrder, bestCoefs, bestBits +end + +-- ------------------------------------------------------------------------------------------------ frame +-- frame(st, samples, first, frames, map) -> buffer: samples interleaved (integers, WAV channel order) from index +-- `first`; map[k] = the input channel (1-based) of ALAC channel k; elements: list of 1 / 2 channel counts +function Encode.frame(st: State, samples: { number }, first: number, frames: number, map: { number }, elements: { number }): buffer + local channels, depth = st.channels, st.bitDepth + local n = frames + local partial = n ~= st.frameLength + local rawBits = n * channels * depth + local need = rawBits + 64 * #elements + 64 + if st.cap < need + 8 * 32 * 2 * #elements * 16 then + local bytes = (need + 8 * 32 * 2 * #elements * 16) // 8 + 16 + st.out = buffer.create(bytes) + st.cap = bytes * 8 + end + buffer.fill(st.out, 0, 0) + st.pos = 0 + local u, v = st.u, st.v + local mult = floor(st.pb * PB_FACTOR / 4) + local compressed = true + local ch = 1 + for _, nch in elements do + local a, b = map[ch], map[ch + 1] + local bps = depth + nch - 1 + local mixRes = 0 + if nch == 2 then + -- the mix with the smallest first-difference energy + local best = math.huge + for res = 0, 4 do + local cost = 0 + local pu, pv = 0, 0 + for i = 0, n - 1 do + local l = samples[first + i * channels + a - 1] + local r = samples[first + i * channels + b - 1] + local uu, vv + if res == 0 then + uu, vv = l, r + else + uu, vv = floor((res * l + (4 - res) * r) / 4), l - r + end + cost += abs(uu - pu) + abs(vv - pv) + pu, pv = uu, vv + end + if cost < best then + best, mixRes = cost, res + end + end + for i = 1, n do + local l = samples[first + (i - 1) * channels + a - 1] + local r = samples[first + (i - 1) * channels + b - 1] + if mixRes == 0 then + u[i], v[i] = l, r + else + u[i], v[i] = floor((mixRes * l + (4 - mixRes) * r) / 4), l - r + end + end + else + for i = 1, n do + u[i] = samples[first + (i - 1) * channels + a - 1] + end + end + -- header + put(st, if nch == 2 then 1 else 0, 3) + put(st, 0, 4) + put(st, 0, 12) + put(st, if partial then 1 else 0, 1) + put(st, 0, 2) + put(st, 0, 1) + if partial then + putBig(st, n, 32) + end + put(st, if mixRes == 0 then 0 else 2, 8) + put(st, mixRes, 8) + local orders, coefsList = {}, {} + for c = 1, nch do + local x = if c == 1 then u else v + local order, coefs = analyse(st, x, n, bps) + orders[c], coefsList[c] = order, coefs + put(st, 0 * 16 + DENSHIFT, 8) -- mode 0, denShift + put(st, PB_FACTOR * 32 + order, 8) + for j = 1, order do + put(st, coefs[j] % 65536, 16) + end + end + for c = 1, nch do + local x = if c == 1 then u else v + local order = orders[c] + if order == 0 then + for i = 1, n do + st.err[i] = x[i] + end + else + residuals(x, st.err, n, bps, table.clone(coefsList[c]), order, DENSHIFT) + end + rice(st, st.err, n, bps, mult, true) + end + ch += nch + if st.pos > rawBits + 64 * #elements then + compressed = false + break + end + end + if not compressed then + -- uncompressed frame + buffer.fill(st.out, 0, 0) + st.pos = 0 + ch = 1 + for _, nch in elements do + put(st, if nch == 2 then 1 else 0, 3) + put(st, 0, 4) + put(st, 0, 12) + put(st, if partial then 1 else 0, 1) + put(st, 0, 2) + put(st, 1, 1) + if partial then + putBig(st, n, 32) + end + for i = 0, n - 1 do + for c = 0, nch - 1 do + putBig(st, samples[first + i * channels + map[ch + c] - 1] % POW[depth + 1], depth) + end + end + ch += nch + end + end + put(st, 7, 3) -- END + local bytes = (st.pos + 7) // 8 + local pkt = buffer.create(bytes) + buffer.copy(pkt, 0, st.out, 0, bytes) + return pkt +end + +function Encode.state(cfg: any): State + local n = cfg.frameLength + return { + frameLength = n, + bitDepth = cfg.bitDepth, + pb = cfg.pb, + mb = cfg.mb, + kb = cfg.kb, + channels = cfg.channels, + out = buffer.create(16), + pos = 0, + cap = 0, + u = table.create(n, 0), + v = table.create(n, 0), + err = table.create(n, 0), + work = table.create(n, 0), + } +end + +return Encode diff --git a/src/Formats/codecs/Alac/init.luau b/src/Formats/codecs/Alac/init.luau new file mode 100644 index 0000000..7af082b --- /dev/null +++ b/src/Formats/codecs/Alac/init.luau @@ -0,0 +1,251 @@ +--!strict +-- codecs/Alac: Apple Lossless (ALAC) decoder and encoder, the codec inside m4a / mov / caf. A codec (layer 1). +-- Written from the ALAC format as Apple published it (ALACSpecificConfig, the element syntax, adaptive Golomb-Rice +-- residuals, the adaptive FIR predictor); no third-party code. 1 - 8 channels, 16 / 20 / 24 / 32-bit decode, 16 / 20 / +-- 24-bit encode. Channels come out (and go in) in WAV order (ALAC stores C L R ... for 3+ channels). +-- +-- local Alac = require("@formats/codecs/Alac") +-- local cfg, err = Alac.config(cookie) -- the 24-byte ALACSpecificConfig (frma / alac atoms skipped) +-- local dec = Alac.decoder(cfg) +-- local frames, err = dec:decode(buf, offset, length) -- one packet -> dec.pcm (interleaved integers, WAV order) +-- local enc = Alac.encoder({ sampleRate = 44100, channels = 2, bitDepth = 16 }) +-- local packet = enc:encode(samples, first, frames) -- interleaved integers -> one packet (frames <= 4096) +-- local cookie = Alac.cookie(enc.config) -- after encoding: maxFrameBytes / avgBitRate filled +-- +-- Never throws: bad data returns nil, Err (CORRUPT / TRUNCATED / UNSUPPORTED), bad arguments Err.ARG. +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Decode = require("@formats/codecs/Alac/Decode") +local Encode = require("@formats/codecs/Alac/Encode") + +local Alac = {} + +export type Config = { + frameLength: number, -- samples per packet (4096) + compatibleVersion: number, + bitDepth: number, + pb: number, -- 40 + mb: number, -- 10 + kb: number, -- 14 + channels: number, + maxRun: number, -- 255 + maxFrameBytes: number, + avgBitRate: number, + sampleRate: number, +} + +-- ALAC channel k (1-based) -> WAV channel (1-based), per channel count +local TO_WAV: { { number } } = { + { 1 }, + { 1, 2 }, + { 3, 1, 2 }, + { 3, 1, 2, 4 }, + { 3, 1, 2, 4, 5 }, + { 3, 1, 2, 5, 6, 4 }, + { 3, 1, 2, 5, 6, 7, 4 }, + { 3, 7, 8, 1, 2, 5, 6, 4 }, +} +-- the element layout (channels per element) the encoder writes +local ELEMENTS: { { number } } = { + { 1 }, + { 2 }, + { 1, 2 }, + { 1, 2, 1 }, + { 1, 2, 2 }, + { 1, 2, 2, 1 }, + { 1, 2, 2, 1, 1 }, + { 1, 2, 2, 2, 1 }, +} +Alac.TO_WAV = TO_WAV + +-- config(buf, offset?, length?) -> Config | nil, Err +function Alac.config(buf: buffer, offset: number?, length: number?): (Config?, Err.Err?) + local r = Bytes.reader(buf, offset, length) + -- a QuickTime 'wave' payload may hold frma + alac atoms ahead of the cookie + for _ = 1, 2 do + local typ = r:peek(4, 4) + if typ == "frma" then + r:skip(12) + elseif typ == "alac" then + r:skip(12) + end + end + if r:remaining() < 24 then + return nil, Err.new(Err.TRUNCATED, "ALAC configuration is shorter than 24 bytes") + end + local c: Config = { + frameLength = r:u32be(), + compatibleVersion = r:u8(), + bitDepth = r:u8(), + pb = r:u8(), + mb = r:u8(), + kb = r:u8(), + channels = r:u8(), + maxRun = r:u16be(), + maxFrameBytes = r:u32be(), + avgBitRate = r:u32be(), + sampleRate = r:u32be(), + } + if c.compatibleVersion ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "ALAC version " .. c.compatibleVersion) + end + if c.frameLength < 1 or c.frameLength > 65536 then + return nil, Err.new(Err.CORRUPT, "bad ALAC frame length " .. c.frameLength) + end + if c.bitDepth ~= 16 and c.bitDepth ~= 20 and c.bitDepth ~= 24 and c.bitDepth ~= 32 then + return nil, Err.new(Err.UNSUPPORTED, "ALAC bit depth " .. c.bitDepth) + end + if c.channels < 1 or c.channels > 8 then + return nil, Err.new(Err.UNSUPPORTED, "ALAC with " .. c.channels .. " channels") + end + if c.kb < 1 or c.kb > 24 then + return nil, Err.new(Err.CORRUPT, "bad ALAC rice limit " .. c.kb) + end + return c, nil +end + +-- cookie(cfg) -> the 24-byte ALACSpecificConfig +function Alac.cookie(c: Config): buffer + local w = Bytes.writer(24) + w:u32be(c.frameLength) + w:u8(0) + w:u8(c.bitDepth) + w:u8(c.pb) + w:u8(c.mb) + w:u8(c.kb) + w:u8(c.channels) + w:u16be(c.maxRun) + w:u32be(c.maxFrameBytes) + w:u32be(c.avgBitRate) + w:u32be(c.sampleRate) + return w:finish() +end + +-- ------------------------------------------------------------------------------------------------ decoder +export type Decoder = { + config: Config, + pcm: { number }, -- the last packet's samples, interleaved, WAV order (integers of config.bitDepth bits) + decode: (self: Decoder, buf: buffer, offset: number?, length: number?) -> (number?, Err.Err?), + state: Decode.State, +} + +local function decode(self: Decoder, buf: buffer, offset: number?, length: number?): (number?, Err.Err?) + local o = offset or 0 + local n = length or (buffer.len(buf) - o) + if o < 0 or n < 0 or o + n > buffer.len(buf) then + return nil, Err.new(Err.ARG, "packet range out of the buffer") + end + local frames, msg = Decode.frame(self.state, buf, o, n) + if not frames then + return nil, Err.new(Err.CORRUPT, msg or "bad packet", o) + end + local ch = self.config.channels + local src, dst = self.state.out, self.pcm + if ch <= 2 then + for i = 1, frames * ch do + dst[i] = src[i] + end + else + local map = TO_WAV[ch] + for f = 0, frames - 1 do + local base = f * ch + for k = 1, ch do + dst[base + map[k]] = src[base + k] + end + end + end + return frames, nil +end + +-- decoder(cfg) -> Decoder +function Alac.decoder(cfg: Config): Decoder + return { + config = cfg, + pcm = table.create(cfg.frameLength * cfg.channels, 0), + decode = decode, + state = Decode.state(cfg), + } +end + +-- ------------------------------------------------------------------------------------------------ encoder +export type Encoder = { + config: Config, + encode: (self: Encoder, samples: { number }, first: number, frames: number) -> (buffer?, Err.Err?), + state: Encode.State, + bytes: number, + frames: number, +} + +local function encode(self: Encoder, samples: { number }, first: number, frames: number): (buffer?, Err.Err?) + local cfg = self.config + if type(samples) ~= "table" or frames < 1 or frames > cfg.frameLength or frames % 1 ~= 0 then + return nil, Err.new(Err.ARG, "encode: 1 .. " .. cfg.frameLength .. " frames of interleaved integer samples") + end + if first < 1 or first + frames * cfg.channels - 1 > #samples then + return nil, Err.new(Err.ARG, "encode: the samples end early") + end + local ch = cfg.channels + local pkt = Encode.frame(self.state, samples, first, frames, TO_WAV[ch], ELEMENTS[ch]) + local n = buffer.len(pkt) + self.bytes += n + self.frames += frames + if n > cfg.maxFrameBytes then + cfg.maxFrameBytes = n + end + if self.frames > 0 then + cfg.avgBitRate = math.floor(self.bytes * 8 * cfg.sampleRate / self.frames) + end + return pkt, nil +end + +export type EncoderOptions = { + sampleRate: number, + channels: number, -- 1 .. 8 + bitDepth: number?, -- 16 (default), 20 or 24 + frameLength: number?, -- default 4096 +} + +-- encoder(opts) -> Encoder | nil, Err +function Alac.encoder(opts: EncoderOptions): (Encoder?, Err.Err?) + if type(opts) ~= "table" then + return nil, Err.new(Err.ARG, "encoder: expected options") + end + local depth = opts.bitDepth or 16 + local ch = opts.channels + if depth ~= 16 and depth ~= 20 and depth ~= 24 then + return nil, Err.new(Err.ARG, "encoder: bitDepth 16, 20 or 24") + end + if type(ch) ~= "number" or ch < 1 or ch > 8 or ch % 1 ~= 0 then + return nil, Err.new(Err.ARG, "encoder: 1 .. 8 channels") + end + local sr = opts.sampleRate + if type(sr) ~= "number" or sr < 1 or sr % 1 ~= 0 then + return nil, Err.new(Err.ARG, "encoder: bad sampleRate") + end + local fl = opts.frameLength or 4096 + if fl < 16 or fl > 16384 or fl % 1 ~= 0 then + return nil, Err.new(Err.ARG, "encoder: frameLength 16 .. 16384") + end + local cfg: Config = { + frameLength = fl, + compatibleVersion = 0, + bitDepth = depth, + pb = 40, + mb = 10, + kb = 14, + channels = ch, + maxRun = 255, + maxFrameBytes = 0, + avgBitRate = 0, + sampleRate = sr, + } + return { + config = cfg, + encode = encode, + state = Encode.state(cfg), + bytes = 0, + frames = 0, + }, nil +end + +return Alac diff --git a/src/Formats/codecs/H264/Decoder.luau b/src/Formats/codecs/H264/Decoder.luau index 850b27d..963c91d 100644 --- a/src/Formats/codecs/H264/Decoder.luau +++ b/src/Formats/codecs/H264/Decoder.luau @@ -152,6 +152,7 @@ local function emit(self: any, p: any) if sps.sarW and sps.sarH then img.meta.sar = { sps.sarW, sps.sarH } end + img.meta.yuv = { range = if sps.fullRange then "full" else "limited", matrix = if sps.matrix == 1 then "bt709" else "bt601" } table.insert(self.out, { image = img, pts = p.pts, duration = 0, poc = p.poc, keyframe = p.idr }) release(self, p) end @@ -743,9 +744,11 @@ local function finishPicture(self: any) bump(self, 0) end if mmco5 then + -- 8.2.1: after MMCO 5 the picture counts as frame_num 0 with its POC moved to 0 local t = p.poc p.topPoc -= t p.poc = 0 + p.frameNum = 0 end -- POC / frame_num state for the next pictures if sh.nalRefIdc ~= 0 then diff --git a/src/Formats/codecs/H264/init.luau b/src/Formats/codecs/H264/init.luau index 2da8dd1..94dae44 100644 --- a/src/Formats/codecs/H264/init.luau +++ b/src/Formats/codecs/H264/init.luau @@ -27,6 +27,7 @@ local Err = require("@formats/core/Err") local Types = require("@formats/Types") local Bitstream = require("@formats/codecs/H264/Bitstream") local Decoder = require("@formats/codecs/H264/Decoder") +local Params = require("@formats/codecs/H264/Params") local H264 = {} @@ -195,6 +196,196 @@ function H264.parseAvcC(data: any): (any, Err.Err?) return cfg, nil end +-- ------------------------------------------------------------------------------------------------ video layer +-- newVideoDecoder(track, opts?) -> a Types.VideoCodecDecoder (the codecs/Video registry entry for "h264"): +-- track.config = avcC (MP4 / Matroska; packets length-prefixed) or nil (Annex B packets: MPEG-TS, AVI, raw .h264). +-- Pictures come out in display order with the pts of the packet that carried them; a track with +-- `ptsInOutputOrder` (raw Annex B, no timestamps) numbers them in output order instead. +function H264.newVideoDecoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + local o: Options = { maxPixels = opts and opts.maxPixels, deblock = opts and opts.deblock, lowDelay = opts and opts.lowDelay } + local function make(): (H264Decoder?, Err.Err?) + local d, err = H264.newDecoder(o) + if d and track.config then + local ok, e = d:configure(track.config) + if not ok then + return nil, e + end + end + return d, err + end + local dec, err = make() + if not dec then + return nil, err + end + local queue: { any } = {} + local outIndex: number? = if track.ptsInOutputOrder then 0 else nil + local self: any = {} + local function push(frames: { Frame }) + for _, f in frames do + local pts = f.pts + if track.ptsInOutputOrder then + pts = outIndex or 0 + outIndex = pts + 1 + end + table.insert(queue, { f.image, pts, f.keyframe }) + end + end + function self.decode(_: any, packet: Types.Packet): Err.Err? + if not dec then + return Err.new(Err.CORRUPT, "decoder not available") + end + if outIndex == nil and track.ptsInOutputOrder then + outIndex = packet.pts + end + local frames, e = (dec :: H264Decoder):decode(packet.data, packet.pts) + if not frames then + return e + end + push(frames) + return nil + end + function self.receive(_: any): (Types.Image?, number?, boolean?) + local q = table.remove(queue, 1) + if q then + return q[1], q[2], q[3] + end + return nil + end + function self.flush(_: any) + if dec then + push((dec :: H264Decoder):flush()) + end + end + function self.reset(_: any) + dec = make() + table.clear(queue) + if track.ptsInOutputOrder then + outIndex = nil + end + end + return self, nil +end + +-- accessUnits(buf, off?, len?) -> { off, len, keyframe, ... } (triples): an Annex B stream cut into access units +-- (7.4.1.2.3: a new unit starts at an AUD, SPS, PPS or SEI after a slice, or at a slice with first_mb_in_slice 0 +-- after a slice). keyframe: the unit holds an IDR slice. +function H264.accessUnits(data: any, off: number?, len: number?): { any } + local b = toBuffer(data) + local out = {} + if not b then + return out + end + local n = buffer.len(b) + local o = math.clamp(off or 0, 0, n) + local l = math.clamp(len or (n - o), 0, n - o) + local nals = Bitstream.splitAnnexB(b, o, l) + local start, hasSlice, key = o, false, false + for i = 1, #nals, 2 do + local p, nl = nals[i], nals[i + 1] + local t = buffer.readu8(b, p) % 32 + local isSlice = t == 1 or t == 5 + local boundary = false + if hasSlice then + if t == 9 or t == 7 or t == 8 or t == 6 or (t >= 14 and t <= 18) then + boundary = true + elseif isSlice and nl > 1 and buffer.readu8(b, p + 1) >= 128 then + boundary = true + end + end + if boundary then + -- the unit ends where this NAL's start code begins + local s = p + while s > start and buffer.readu8(b, s - 1) ~= 1 do + s -= 1 + end + s -= 1 + while s > start and buffer.readu8(b, s - 1) == 0 do + s -= 1 + end + table.insert(out, start) + table.insert(out, s - start) + table.insert(out, key) + start, hasSlice, key = s, false, false + end + if isSlice then + hasSlice = true + if t == 5 then + key = true + end + end + end + if hasSlice and o + l > start then + table.insert(out, start) + table.insert(out, o + l - start) + table.insert(out, key) + end + return out +end + +-- toAnnexB(config, sample) -> buffer: a length-prefixed sample (MP4 / Matroska) as Annex B; with config (avcC) the +-- parameter sets are prepended (pass it for the first sample / keyframes). nil, Err on a bad avcC / sample +function H264.toAnnexB(config: buffer?, sample: buffer): (buffer?, Err.Err?) + local parts = {} + local lengthSize = 4 + if config then + local cfg, err = Bitstream.parseAvcC(config, 0, buffer.len(config)) + if not cfg then + return nil, Err.new(Err.CORRUPT, err or "bad avcC") + end + lengthSize = cfg.lengthSize + for i = 1, #cfg.nals, 2 do + table.insert(parts, "\0\0\0\1" .. buffer.readstring(config, cfg.nals[i], cfg.nals[i + 1])) + end + end + local nals = Bitstream.splitLength(sample, 0, buffer.len(sample), lengthSize) + if not nals then + return nil, Err.new(Err.CORRUPT, "NAL length past the end of the sample") + end + for i = 1, #nals, 2 do + table.insert(parts, "\0\0\0\1" .. buffer.readstring(sample, nals[i], nals[i + 1])) + end + return buffer.fromstring(table.concat(parts)), nil +end + +-- info(data) -> { width, height, profile, level, frameRate?, ... } of the first SPS of an Annex B stream or avcC | nil +function H264.info(data: any): any + local b = toBuffer(data) + if not b then + return nil + end + local nals + if buffer.len(b) > 6 and buffer.readu8(b, 0) == 1 then + local cfg = Bitstream.parseAvcC(b, 0, buffer.len(b)) + nals = if cfg then cfg.nals else {} + else + nals = Bitstream.splitAnnexB(b, 0, buffer.len(b)) + end + for i = 1, #nals, 2 do + if buffer.readu8(b, nals[i]) % 32 == 7 then + local sps = Params.sps(Bitstream.reader(b, nals[i], nals[i + 1], 1)) + if sps then + local fps = nil + if sps.unitsInTick and sps.timeScale and sps.unitsInTick > 0 then + fps = sps.timeScale / (2 * sps.unitsInTick) + end + return { + width = sps.width, + height = sps.height, + profile = sps.profile, + level = sps.level, + chromaFormat = sps.chromaFormat, + bitDepth = sps.bitDepth, + interlaced = not sps.frameMbsOnly, + frameRate = fps, + maxRefFrames = sps.maxRefFrames, + numReorderFrames = sps.numReorderFrames, + } + end + end + end + return nil +end + -- planes(img) -> y, u, v offsets in img.pixels and the chroma width / height function H264.planes(img: Types.Image): (number, number, number, number, number) local cw, ch = (img.width + 1) // 2, (img.height + 1) // 2 diff --git a/src/Formats/image/jpeg/Arith.luau b/src/Formats/codecs/Jpeg/Arith.luau similarity index 99% rename from src/Formats/image/jpeg/Arith.luau rename to src/Formats/codecs/Jpeg/Arith.luau index a1044e2..984c8a5 100644 --- a/src/Formats/image/jpeg/Arith.luau +++ b/src/Formats/codecs/Jpeg/Arith.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- image/jpeg/Arith: arithmetic-coded scans (ITU T.81 annex D / F.1.4, sequential and progressive) into quantised +-- codecs/Jpeg/Arith: arithmetic-coded scans (ITU T.81 annex D / F.1.4, sequential and progressive) into quantised -- DCT coefficients (native; never throws). A Luau translation of libjpeg-turbo's jdarith.c (Guido Vollbeding's -- decoder, IJG licence: licenses/libjpeg-turbo-LICENSE.md) and the jaricom.c probability table. -- diff --git a/src/Formats/image/jpeg/Color.luau b/src/Formats/codecs/Jpeg/Color.luau similarity index 98% rename from src/Formats/image/jpeg/Color.luau rename to src/Formats/codecs/Jpeg/Color.luau index af39c11..46e1cf8 100644 --- a/src/Formats/image/jpeg/Color.luau +++ b/src/Formats/codecs/Jpeg/Color.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- image/jpeg/Color: chroma upsampling and colour conversion to RGBA8, one output row at a time (native; never +-- codecs/Jpeg/Color: chroma upsampling and colour conversion to RGBA8, one output row at a time (native; never -- throws). Absorbed from jpeg-luau 1.0 src/Jpeg/Color.luau (same author); a Luau translation of libjpeg-turbo's -- jdsample.c / jdcolor.c (IJG licence: licenses/libjpeg-turbo-LICENSE.md). -- diff --git a/src/Formats/image/jpeg/Decode.luau b/src/Formats/codecs/Jpeg/Decode.luau similarity index 80% rename from src/Formats/image/jpeg/Decode.luau rename to src/Formats/codecs/Jpeg/Decode.luau index 11d2f64..05a0a7f 100644 --- a/src/Formats/image/jpeg/Decode.luau +++ b/src/Formats/codecs/Jpeg/Decode.luau @@ -1,12 +1,15 @@ --!strict --- image/jpeg/Decode: the JPEG marker parser and output stage (interpreted; it validates everything the native Scan / --- Arith / Dct / Color loops index). Absorbed from jpeg-luau 1.0 src/Jpeg/init.luau (same author) and extended: --- arithmetic-coded frames (SOF9 / SOF10, DAC), a reader range instead of a whole buffer, APP1 EXIF / APP2 ICC / COM --- / JFIF density collected for meta. The IDCT size choice for scaled decodes follows libjpeg-turbo's jdmaster.c. -local Scan = require("@formats/image/jpeg/Scan") -local Arith = require("@formats/image/jpeg/Arith") -local Color = require("@formats/image/jpeg/Color") -local Tables = require("@formats/image/jpeg/Tables") +-- codecs/Jpeg/Decode: the JPEG marker parser and output stage (interpreted; it validates everything the native Scan / +-- Arith / Dct / Color / Yuv loops index). Absorbed from jpeg-luau 1.0 src/Jpeg/init.luau (same author) and extended: +-- arithmetic-coded frames (SOF9 / SOF10, DAC), a byte range instead of a whole buffer, APP1 EXIF / APP2 ICC / COM +-- / JFIF density collected for meta, the AVI1 APP0 field polarity and the end of the image (Motion-JPEG), and a +-- yuv420p output straight from the IDCT planes (outputYuv). The IDCT size choice for scaled decodes follows +-- libjpeg-turbo's jdmaster.c. Moved from image/jpeg/Decode to codecs/Jpeg/Decode for the video formats. +local Scan = require("@formats/codecs/Jpeg/Scan") +local Arith = require("@formats/codecs/Jpeg/Arith") +local Color = require("@formats/codecs/Jpeg/Color") +local Tables = require("@formats/codecs/Jpeg/Tables") +local Yuv = require("@formats/codecs/Jpeg/Yuv") local Dct = require("@formats/codecs/Dct") local readu8 = buffer.readu8 @@ -226,6 +229,8 @@ export type State = { comments: { string }, truncated: boolean, scale: number, + avi1: number?, -- the AVI1 APP0 field polarity (0 = progressive, 1 / 2 = interlaced: two fields back to back) + endPos: number, -- the byte after the EOI marker (or the end of the data) } -- parse(b, base, limit, opts, headerOnly) -> State | nil, code, message. Walks the markers in b[base, limit); with @@ -255,6 +260,8 @@ function Decode.parse(b: buffer, base: number, n: number, opts: any, headerOnly: comments = {}, truncated = false, scale = scale, + avi1 = nil, + endPos = n, } local iccChunks: { buffer } = {} local ri = 0 @@ -277,6 +284,7 @@ function Decode.parse(b: buffer, base: number, n: number, opts: any, headerOnly: local m = readu8(b, pos) pos += 1 if m == 0xD9 then + st.endPos = pos break -- EOI elseif m == 0 or m == 0x01 or m == 0xD8 or (m >= 0xD0 and m <= 0xD7) then continue -- standalone markers (or stray stuffing) @@ -303,6 +311,8 @@ function Decode.parse(b: buffer, base: number, n: number, opts: any, headerOnly: if e - p >= 12 and buffer.readstring(b, p, 5) == "JFIF\0" then st.jfif = true st.density = { unit = readu8(b, p + 7), x = be16(b, p + 8), y = be16(b, p + 10) } + elseif e - p >= 5 and buffer.readstring(b, p, 4) == "AVI1" then + st.avi1 = readu8(b, p + 4) end elseif m == 0xE1 then local t, o = exif(b, p, e) @@ -663,4 +673,90 @@ function Decode.output(st: State): (number?, any, any, string?) return outW, outH, pixels, space end +-- outputYuv(st) -> width, height, yuv420p pixels, sampling | nil when the frame has no direct yuv420p form (the +-- caller falls back to output). The IDCT output planes as they are, cropped to the image, without colour conversion +-- or upsampling: 8-bit YCbCr whose chroma is sampled at half the luma rate both ways ("420", 2x2 / 1x1); half +-- horizontally ("422", 2x1 / 1x1 or ffmpeg's 2x2 / 1x2: each pair of chroma rows averaged, rounding up); at the luma +-- rate ("444", 1x1 or ffmpeg's 1x2 everywhere: each 2 x 2 chroma block averaged, rounding to nearest); grey ("gray": +-- chroma 128). Full scale only (opts.scale = 1). +-- one IDCT plane at a time is live (each is cropped into the output before the next component): frame-sized planes +-- (up to 4 MB) are kept between calls, so a stream of video frames does not allocate them per frame +local scratch: buffer? = nil +local function scratchPlane(n: number): buffer + local sc = scratch + if sc and buffer.len(sc) >= n then + return sc + end + local b = buffer.create(n) + if n <= 4 * 1024 * 1024 then + scratch = b + end + return b +end + +function Decode.outputYuv(st: State): (number?, number?, buffer?, string?) + local f: Frame = st.frame + if st.scale ~= 1 or f.precision ~= 8 then + return nil + end + local comps = f.comps + local space = colorSpaceOf(f, st.adobe, st.jfif) + local mode = nil + if space == "gray" then + mode = "gray" + elseif space == "ycbcr" then + -- the ratios of luma to chroma sampling (ffmpeg writes 4:2:2 as 2x2 / 1x2 and 4:4:4 as 1x2 everywhere) + local l, cb, cr = comps[1], comps[2], comps[3] + if l.h == f.hmax and l.v == f.vmax and cb.h == cr.h and cb.v == cr.v then + local rh, rv = f.hmax // cb.h, f.vmax // cb.v + if rh * cb.h ~= f.hmax or rv * cb.v ~= f.vmax then + mode = nil + elseif rh == 2 and rv == 2 then + mode = "420" + elseif rh == 2 and rv == 1 then + mode = "422" + elseif rh == 1 and rv == 1 then + mode = "444" + end + end + end + if not mode then + return nil + end + for _, c in comps do + if c.coef and not c.quant then + return nil -- output() reports the missing table + end + end + local w, h = f.width, f.height + local cw, ch = (w + 1) // 2, (h + 1) // 2 + local out = buffer.create(w * h + 2 * cw * ch) + local zeroQ: buffer? = nil + for i, c in comps do + local stride, rows = c.bpl * 8, c.bpc * 8 + local plane = scratchPlane(stride * rows * 2) + local coef = c.coef or buffer.create(c.bpl * c.bpc * 128) + local q = c.quant + if not q then + zeroQ = zeroQ or buffer.create(128) -- the component never appeared in a scan: mid grey + q = zeroQ + end + Dct.idctComponent(coef, q :: buffer, c.bpl, c.bpc, 8, plane, 2, 128, 255) + if i == 1 then + Yuv.crop(plane, stride, w, h, out, 0) + elseif mode == "420" then + Yuv.crop(plane, stride, cw, ch, out, w * h + (i - 2) * cw * ch) + elseif mode == "422" then + Yuv.rows(plane, stride, cw, h, out, w * h + (i - 2) * cw * ch) + else + Yuv.box(plane, stride, w, h, out, w * h + (i - 2) * cw * ch) + end + c.coef = nil + end + if mode == "gray" then + buffer.fill(out, w * h, 128, 2 * cw * ch) + end + return w, h, out, mode +end + return Decode diff --git a/src/Formats/image/jpeg/Encode.luau b/src/Formats/codecs/Jpeg/Encode.luau similarity index 93% rename from src/Formats/image/jpeg/Encode.luau rename to src/Formats/codecs/Jpeg/Encode.luau index 0ecf6eb..642b737 100644 --- a/src/Formats/image/jpeg/Encode.luau +++ b/src/Formats/codecs/Jpeg/Encode.luau @@ -1,15 +1,16 @@ --!strict --!native --!optimize 2 --- image/jpeg/Encode: the JPEG encoder (native; never throws). Baseline (SOF0) with the standard or optimised Huffman +-- codecs/Jpeg/Encode: the JPEG encoder (native; never throws). Baseline (SOF0) with the standard or optimised Huffman -- tables and progressive (SOF2, libjpeg's jpeg_simple_progression script, optimised tables per scan); grey or YCbCr --- 4:4:4 / 4:2:2 / 4:2:0; restart intervals. It follows libjpeg-turbo's encoder step for step so that its output is --- byte-identical to cjpeg's for the same settings: jccolor.c (fixed-point RGB -> YCbCr), jcsample.c (box downsampling --- with alternating rounding bias, right-edge replication), jccoefct.c (dummy edge blocks), jfdctint.c + jcdctmgr.c --- (codecs/Dct), jchuff.c (sequential coding, jpeg_gen_optimal_table) and jcphuff.c (progressive coding: EOB runs, +-- 4:4:4 / 4:2:2 / 4:2:0, or yuv420p planes coded as they are (4:2:0, no colour conversion: the Motion-JPEG +-- encoders); restart intervals. Moved from image/jpeg/Encode to codecs/Jpeg/Encode. It follows libjpeg-turbo's +-- encoder step for step so that its output is byte-identical to cjpeg's for the same settings: jccolor.c +-- (fixed-point RGB -> YCbCr), jcsample.c (box downsampling with alternating rounding bias, right-edge replication), +-- jccoefct.c (dummy edge blocks), jfdctint.c + jcdctmgr.c (codecs/Dct), jchuff.c (sequential coding, jpeg_gen_optimal_table) and jcphuff.c (progressive coding: EOB runs, -- correction-bit buffering). Luau translation of IJG code: licenses/libjpeg-turbo-LICENSE.md. local Dct = require("@formats/codecs/Dct") -local Tables = require("@formats/image/jpeg/Tables") +local Tables = require("@formats/codecs/Jpeg/Tables") local readu8, writeu8, readi16, writei16, readu16, writeu16 = buffer.readu8, buffer.writeu8, buffer.readi16, buffer.writei16, buffer.readu16, buffer.writeu16 local band, countlz = bit32.band, bit32.countlz @@ -574,8 +575,9 @@ export type Options = { density: { unit: number, x: number, y: number }?, } --- run(pixels, w, h, bpp, opts) -> buffer. pixels: w * h * bpp bytes (bpp 4 rgba8 / 3 rgb8 / 1 gray8); the caller --- validated sizes (1..65535) and options. +-- run(pixels, w, h, bpp, opts) -> buffer. pixels: w * h * bpp bytes (bpp 4 rgba8 / 3 rgb8 / 1 gray8), or bpp 0: +-- yuv420p (w * h luma, then ceil(w / 2) * ceil(h / 2) Cb and Cr; opts.sampling must be "420" unless opts.gray). The +-- caller validated sizes (1..65535), the buffer length and options. function Encode.run(px: buffer, w: number, h: number, bpp: number, o: Options): buffer OUT = buffer.create(math.max(1024, w * h // 2)) CAP = buffer.len(OUT) @@ -584,7 +586,19 @@ function Encode.run(px: buffer, w: number, h: number, bpp: number, o: Options): GATHER = false EOBRUN, BE = 0, 0 - local Y, Cb, Cr = planes(px, w, h, bpp, o.gray) + local yuv = bpp == 0 + local Y, Cb, Cr + if yuv then + local n, cn = w * h, ((w + 1) // 2) * ((h + 1) // 2) + Y = px + if not o.gray then + Cb, Cr = buffer.create(cn), buffer.create(cn) + buffer.copy(Cb :: buffer, 0, px, n, cn) + buffer.copy(Cr :: buffer, 0, px, n + cn, cn) + end + else + Y, Cb, Cr = planes(px, w, h, bpp, o.gray) + end local hs, vs = 1, 1 if not o.gray then if o.sampling == "420" then @@ -615,7 +629,9 @@ function Encode.run(px: buffer, w: number, h: number, bpp: number, o: Options): local bw, bh = math.ceil(cw / 8), math.ceil(chh / 8) local bpl, bpc = mcusX * ch, mcusY * cv local plane, pw, ph = src, w, h - if ch < hs or cv < vs then + if yuv and i > 1 then + pw, ph = (w + 1) // 2, (h + 1) // 2 -- already 4:2:0: fdctQuantize repeats the edges as jcsample.c does + elseif ch < hs or cv < vs then pw, ph = bw * 8, chh plane = downsample(src, w, h, hs // ch, vs // cv, pw, ph) end diff --git a/src/Formats/image/jpeg/Scan.luau b/src/Formats/codecs/Jpeg/Scan.luau similarity index 99% rename from src/Formats/image/jpeg/Scan.luau rename to src/Formats/codecs/Jpeg/Scan.luau index ec8f45f..f8f62eb 100644 --- a/src/Formats/image/jpeg/Scan.luau +++ b/src/Formats/codecs/Jpeg/Scan.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- image/jpeg/Scan: Huffman-coded scan decoding into quantised DCT coefficients (native; never throws). Absorbed from +-- codecs/Jpeg/Scan: Huffman-coded scan decoding into quantised DCT coefficients (native; never throws). Absorbed from -- jpeg-luau 1.0 src/Jpeg/Scan.luau (same author); unchanged but for this header. -- -- `destuff` copies one scan's entropy-coded bytes into a clean buffer: it drops the stuffed 0x00 after each 0xFF, diff --git a/src/Formats/image/jpeg/Tables.luau b/src/Formats/codecs/Jpeg/Tables.luau similarity index 96% rename from src/Formats/image/jpeg/Tables.luau rename to src/Formats/codecs/Jpeg/Tables.luau index e524d54..9e9c4df 100644 --- a/src/Formats/image/jpeg/Tables.luau +++ b/src/Formats/codecs/Jpeg/Tables.luau @@ -1,5 +1,5 @@ --!strict --- image/jpeg/Tables: the standard tables of ITU T.81 annex K: the example Huffman tables (K.3, which every baseline +-- codecs/Jpeg/Tables: the standard tables of ITU T.81 annex K: the example Huffman tables (K.3, which every baseline -- encoder without optimisation writes and Motion-JPEG frames leave out) and the luminance / chrominance quantisation -- tables (K.1) with libjpeg's quality scaling (jcparam.c jpeg_quality_scaling / jpeg_add_quant_table). local Tables = {} diff --git a/src/Formats/codecs/Jpeg/Yuv.luau b/src/Formats/codecs/Jpeg/Yuv.luau new file mode 100644 index 0000000..edb2778 --- /dev/null +++ b/src/Formats/codecs/Jpeg/Yuv.luau @@ -0,0 +1,76 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Jpeg/Yuv: the yuv420p output of the JPEG decoder (native; never throws): the IDCT output planes (u16 +-- samples, block-padded) cropped into u8 yuv420p planes without colour conversion or upsampling, 4:2:2 / 4:4:4 +-- chroma reduced to 4:2:0 by averaging, and the interleaving of two fields (AVI1 interlaced Motion-JPEG). +-- The callers (codecs/Jpeg/Decode, codecs/Jpeg) size every buffer; each loop reads and writes inside those sizes. +local readu16, writeu8, readu32, writeu32 = buffer.readu16, buffer.writeu8, buffer.readu32, buffer.writeu32 + +local Yuv = {} + +-- crop(src, stride, w, h, dst, doff): the top-left w x h samples of a u16 plane (stride samples per row) into u8 +-- samples at dst[doff], w per row +function Yuv.crop(src: buffer, stride: number, w: number, h: number, dst: buffer, doff: number) + local quads = w // 4 + local rest = w - quads * 4 + for y = 0, h - 1 do + local s = y * stride * 2 + local d = doff + y * w + -- four samples (two u32 reads of two u16 samples, each 0..255) per u32 write + for _ = 1, quads do + local a, b = readu32(src, s), readu32(src, s + 4) + writeu32(dst, d, a % 65536 + (a // 65536) * 256 + (b % 65536) * 65536 + (b // 65536) * 16777216) + s += 8 + d += 4 + end + for k = 0, rest - 1 do + writeu8(dst, d + k, readu16(src, s + k * 2)) + end + end +end + +-- rows(src, stride, w, h, dst, doff): a u16 plane of w x h samples (4:2:2 chroma) -> u8 w x ceil(h / 2), each output +-- row the rounded mean of two source rows (the last row alone when h is odd) +function Yuv.rows(src: buffer, stride: number, w: number, h: number, dst: buffer, doff: number) + local oh = (h + 1) // 2 + for y = 0, oh - 1 do + local a = 2 * y * stride * 2 + local b = if 2 * y + 1 < h then a + stride * 2 else a + local d = doff + y * w + for x = 0, w - 1 do + writeu8(dst, d + x, (readu16(src, a + x * 2) + readu16(src, b + x * 2) + 1) // 2) + end + end +end + +-- box(src, stride, w, h, dst, doff): a u16 plane of w x h samples (4:4:4 chroma) -> u8 ceil(w / 2) x ceil(h / 2), +-- each output sample the rounded mean of a 2 x 2 block (edges repeat the last row / column) +function Yuv.box(src: buffer, stride: number, w: number, h: number, dst: buffer, doff: number) + local ow, oh = (w + 1) // 2, (h + 1) // 2 + for y = 0, oh - 1 do + local a = 2 * y * stride * 2 + local b = if 2 * y + 1 < h then a + stride * 2 else a + local d = doff + y * ow + for x = 0, ow - 1 do + local x0 = 2 * x * 2 + local x1 = if 2 * x + 1 < w then x0 + 2 else x0 + writeu8(dst, d + x, (readu16(src, a + x0) + readu16(src, a + x1) + readu16(src, b + x0) + readu16(src, b + x1) + 2) // 4) + end + end +end + +-- weave(top, toff, bottom, boff, rowBytes, rows, dst, doff): interleave rows of two planes (field 1 on the even rows, field +-- 2 on the odd rows) into rows output rows at dst[doff]; top holds ceil(rows / 2) rows, bottom floor(rows / 2) +function Yuv.weave(top: buffer, toff: number, bottom: buffer, boff: number, rowBytes: number, rows: number, dst: buffer, doff: number) + for y = 0, rows - 1 do + local k = y // 2 + if y % 2 == 0 then + buffer.copy(dst, doff + y * rowBytes, top, toff + k * rowBytes, rowBytes) + else + buffer.copy(dst, doff + y * rowBytes, bottom, boff + k * rowBytes, rowBytes) + end + end +end + +return Yuv diff --git a/src/Formats/codecs/Jpeg/init.luau b/src/Formats/codecs/Jpeg/init.luau new file mode 100644 index 0000000..3163222 --- /dev/null +++ b/src/Formats/codecs/Jpeg/init.luau @@ -0,0 +1,387 @@ +--!strict +-- codecs/Jpeg: the JPEG codec (ITU T.81) on byte ranges: image/jpeg is a thin format over it, and the Motion-JPEG +-- video tracks (AVI / Matroska / QuickTime) decode and encode their frames with it. The engine (Huffman and +-- arithmetic scan decoding, IDCTs through codecs/Dct, libjpeg-turbo's upsampling and colour conversion, the encoder) +-- was absorbed from jpeg-luau 1.0 (same author) into image/jpeg and moved down here; it is bit-exact with libjpeg-turbo's +-- djpeg and byte-identical with cjpeg. IJG-derived parts: licenses/libjpeg-turbo-LICENSE.md. +-- +-- local img, err = Jpeg.decode(buf, off?, len?, opts?) -- one JPEG -> rgba8 (or gray8 / yuv420p) Types.Image +-- local img = Jpeg.decode(frame, 0, n, { yuv = true }) -- video: yuv420p straight from the IDCT planes +-- local out, err = Jpeg.encode(img, opts?) -- rgba8 / rgb8 / gray8 / yuv420p Image -> buffer +-- local info, err = Jpeg.info(buf, off?, len?) -- the headers up to the frame header +-- +-- Decode: baseline, extended and progressive frames, Huffman or arithmetic coded (SOF0/1/2/9/10), 8 and 12-bit +-- samples, 1, 3 or 4 components with any sampling factors 1..4, restart intervals (resynchronising after corrupt +-- data), grey / YCbCr / RGB / CMYK / YCCK (Adobe APP14), scaled decodes (opts.scale = 2, 4, 8), EXIF orientation +-- (meta.orientation, applied with opts.orient). Truncated or corrupt scans decode as far as they go +-- (meta.truncated = true). +-- Motion-JPEG: frames without DHT segments use the T.81 annex K tables; the AVI1 APP0 segment is read (its field +-- polarity) and data after EOI is ignored. Two fields back to back (AVI1 interlaced: two JPEGs of half the frame +-- height, polarity 1 or 2, or opts.fields = true) are decoded and woven into one frame, the first field on the even +-- rows (top field first, as ffmpeg, which ignores the polarity value); a missing or different-sized second field +-- leaves the first field alone (meta.source.fields = 1). +-- opts.yuv: 8-bit YCbCr frames come out as yuv420p (full-range BT.601, meta.source.range = "full") without colour +-- conversion or upsampling: 4:2:0 (2x2 luma) as the planes are; 4:2:2 (2x1 luma, the usual Motion-JPEG camera +-- layout) with each pair of chroma rows averaged; 4:4:4 with 2 x 2 chroma averages; grey with chroma 128. Other +-- layouts (RGB, CMYK, 4:1:1, 4:4:0, 12-bit) and scaled decodes fall back to rgba8 (check img.format). +-- Encode: baseline (standard or optimised Huffman tables) and progressive (libjpeg's simple progression), grey or +-- YCbCr 4:4:4 / 4:2:2 / 4:2:0, libjpeg quality tables, restart intervals, extra APPn / COM segments +-- (opts.segments); yuv420p input is coded from its planes as they are (4:2:0, no colour conversion). +-- Not supported: lossless (SOF3) and hierarchical frames, DNL, 2-component images, 12-bit or CMYK encoding. +-- Never throws: bad data or arguments return nil, Err. +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Decode = require("@formats/codecs/Jpeg/Decode") +local Encode = require("@formats/codecs/Jpeg/Encode") +local Yuv = require("@formats/codecs/Jpeg/Yuv") + +local Jpeg = {} + +export type DecodeOptions = { + scale: number?, -- 1 (default), 2, 4 or 8: decode at ceil(size / scale) (8 reads the DC coefficients only) + orient: boolean?, -- apply the EXIF orientation (default false: reported in meta.orientation only; rgba8 / gray8) + native: boolean?, -- grey files decode to gray8 (default false: rgba8) + yuv: boolean?, -- 8-bit YCbCr / grey frames decode to yuv420p (default false); see the header for the layouts + fields: boolean?, -- two JPEGs back to back are two fields of one frame (default: when the AVI1 segment says so) + maxPixels: number?, -- refuse larger images (default 2^26) +} +export type EncodeOptions = { + quality: number?, -- 1..100 (default 90), libjpeg's scaling of the T.81 annex K tables + subsampling: ("420" | "422" | "444")?, -- chroma subsampling (default "420"; yuv420p input is always 4:2:0) + progressive: boolean?, -- default false + optimize: boolean?, -- optimised Huffman tables for baseline files (default false; progressive always optimises) + gray: boolean?, -- a one-component file (default: true for gray8 images) + restart: number?, -- restart interval in MCUs (default 0 = none) + jfif: boolean?, -- write the JFIF APP0 header (default true) + density: { unit: number, x: number, y: number }?, -- the JFIF density (default unit 0, 1 x 1) + segments: { { marker: number, data: buffer } }?, -- APPn / COM segments written after the JFIF header +} + +export type Info = { + width: number, + height: number, + components: number, + progressive: boolean, + arithmetic: boolean, + precision: number, + colorSpace: string, + sampling: { { number } }, -- { h, v } per component + orientation: number, + adobe: number?, + jfif: boolean, + avi1: number?, -- the AVI1 field polarity, when the segment comes before the frame header +} + +local CODES = { corrupt = Err.CORRUPT, unsupported = Err.UNSUPPORTED, limit = Err.LIMIT, truncated = Err.TRUNCATED, arg = Err.ARG } + +local function range(buf: buffer, off: number?, len: number?): (number, number) + local n = buffer.len(buf) + local o = math.clamp(math.floor(tonumber(off) or 0), 0, n) + return o, math.clamp(math.floor(tonumber(len) or (n - o)), 0, n - o) +end + +-- the marker parser over [o, o + l): State | nil, Err +local function parse(buf: buffer, o: number, l: number, opts: any, headerOnly: boolean): (Decode.State?, Err.Err?) + local ok, st, code, msg = pcall(Decode.parse, buf, o, o + l, opts, headerOnly) + if not ok then + return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(st)) + end + if not st then + return nil, Err.new(CODES[code :: string] or Err.CORRUPT, msg or "decode failed", o) + end + return st, nil +end + +local function samplingOf(f: any): { { number } } + local sampling = {} + for _, c in f.comps do + table.insert(sampling, { c.h, c.v }) + end + return sampling +end + +-- info(buf, off?, len?) -> Info | nil, Err (reads the headers up to the frame header) +function Jpeg.info(buf: buffer, off: number?, len: number?): (Info?, Err.Err?) + if type(buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "expected a buffer") + end + local o, l = range(buf, off, len) + local st, err = parse(buf, o, l, nil, true) + if not st then + return nil, err + end + local f = st.frame + return { + width = f.width, + height = f.height, + components = #f.comps, + progressive = f.progressive, + arithmetic = f.arithmetic, + precision = f.precision, + colorSpace = Decode.colorSpaceOf(f, st.adobe, st.jfif), + sampling = samplingOf(f), + orientation = st.orientation, + adobe = st.adobe, + jfif = st.jfif, + avi1 = st.avi1, + }, + nil +end + +-- the EXIF orientation applied to rgba8 pixels: buffer, width, height +local function orient(px: buffer, w: number, h: number, o: number): (buffer, number, number) + if o <= 1 or o > 8 then + return px, w, h + end + local swap = o >= 5 + local ow, oh = if swap then h else w, if swap then w else h + local out = buffer.create(ow * oh * 4) + local readu32, writeu32 = buffer.readu32, buffer.writeu32 + for y = 0, oh - 1 do + for x = 0, ow - 1 do + local col, row + if o == 2 then + col, row = w - 1 - x, y + elseif o == 3 then + col, row = w - 1 - x, h - 1 - y + elseif o == 4 then + col, row = x, h - 1 - y + elseif o == 5 then + col, row = y, x + elseif o == 6 then + col, row = y, h - 1 - x + elseif o == 7 then + col, row = w - 1 - y, h - 1 - x + else + col, row = w - 1 - y, x + end + writeu32(out, (y * ow + x) * 4, readu32(px, (row * w + col) * 4)) + end + end + return out, ow, oh +end + +-- one JPEG at [o, o + l): Image, State | nil, Err +local function decodeOne(buf: buffer, o: number, l: number, opts: DecodeOptions?): (Types.Image?, any) + local st, err = parse(buf, o, l, opts, false) + if not st then + return nil, err + end + local s = st :: Decode.State + local img = Types.Image.new(0, 0) + local space, mode = nil, nil + if opts and opts.yuv then + local ok, w, h, px, m = pcall(Decode.outputYuv, s) + if not ok then + return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(w)) + end + if w then + img.width, img.height, img.pixels, img.format = w, h :: number, px :: buffer, "yuv420p" + mode = m + space = Decode.colorSpaceOf(s.frame, s.adobe, s.jfif) + end + end + if not mode then + local ok, w, h, px, sp = pcall(Decode.output, s) + if not ok then + return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(w)) + end + if not w then + return nil, Err.new(CODES[h :: string] or Err.CORRUPT, tostring(px), o) + end + space = sp + if opts and opts.orient then + px, w, h = orient(px, w, h, s.orientation) + end + img.width, img.height, img.pixels = w, h, px + if opts and opts.native and space == "gray" then + local g = buffer.create(w * h) + for i = 0, w * h - 1 do + buffer.writeu8(g, i, buffer.readu8(px, i * 4)) + end + img.pixels, img.format = g, "gray8" + end + end + local f = s.frame + local meta = img.meta + meta.orientation = s.orientation + meta.oriented = (opts and opts.orient and not mode) or false + meta.exif = s.exif + meta.icc = s.icc + if #s.comments > 0 then + meta.text = { comment = table.concat(s.comments, "\n") } + end + if s.density and s.density.unit > 0 and s.density.x > 0 and s.density.y > 0 then + local k = if s.density.unit == 2 then 2.54 else 1 + meta.dpi = { x = s.density.x * k, y = s.density.y * k } + end + meta.truncated = s.truncated + meta.source = { + format = "jpeg", + bitDepth = f.precision, + colorType = space, + components = #f.comps, + progressive = f.progressive, + arithmetic = f.arithmetic, + sampling = samplingOf(f), + scale = s.scale, + adobe = s.adobe, + jfif = s.jfif, + avi1 = s.avi1, + yuv = mode, -- "420" | "422" | "444" | "gray": how the yuv420p planes were made (opts.yuv) + range = if mode then "full" else nil, + fields = 1, + } + return img, s +end + +-- the start of a second JPEG (FF D8 FF) at or after p, before e; -1 if none +local function nextSoi(buf: buffer, p: number, e: number): number + local readu8 = buffer.readu8 + while p + 3 <= e do + if readu8(buf, p) == 0xFF and readu8(buf, p + 1) == 0xD8 and readu8(buf, p + 2) == 0xFF then + return p + end + p += 1 + end + return -1 +end + +-- two fields (same size and format) -> one frame of twice the height, field a on the even rows +local function weave(a: Types.Image, b: Types.Image): Types.Image + local w, hf = a.width, a.height + local h = hf * 2 + local out = Types.Image.new(w, h, a.format) + local dst = out.pixels + if a.format == "yuv420p" then + local cw, chf = (w + 1) // 2, (hf + 1) // 2 + local ch = (h + 1) // 2 -- = hf + Yuv.weave(a.pixels, 0, b.pixels, 0, w, h, dst, 0) + for k = 0, 1 do + Yuv.weave(a.pixels, w * hf + k * cw * chf, b.pixels, w * hf + k * cw * chf, cw, ch, dst, w * h + k * cw * ch) + end + else + local bpp = Types.Image.bpp(a.format) or 4 + Yuv.weave(a.pixels, 0, b.pixels, 0, w * bpp, h, dst, 0) + end + out.meta = a.meta + return out +end + +-- decode(buf, off?, len?, opts?) -> Image | nil, Err: one JPEG (or one interlaced Motion-JPEG frame) in [off, off + len) +function Jpeg.decode(buf: buffer, off: number?, len: number?, opts: DecodeOptions?): (Types.Image?, Err.Err?) + if type(buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "expected a buffer") + end + if opts ~= nil and type(opts) ~= "table" then + return nil, Err.new(Err.ARG, "options must be a table") + end + local o, l = range(buf, off, len) + local img, st = decodeOne(buf, o, l, opts) + if not img then + return nil, st + end + local s = st :: Decode.State + local wantFields = if opts and opts.fields ~= nil then opts.fields else (s.avi1 == 1 or s.avi1 == 2) + if wantFields and not (opts and opts.orient) then + local e = o + l + local p = nextSoi(buf, s.endPos, e) + if p >= 0 then + local o2 = table.clone(opts or {}) :: any + if o2.maxPixels then + o2.maxPixels = math.max(0, o2.maxPixels - img.width * img.height) + end + local b = decodeOne(buf, p, e - p, o2) + if b and b.width == img.width and b.height == img.height and b.format == img.format then + local truncated = img.meta.truncated or b.meta.truncated + img = weave(img, b) + img.meta.truncated = truncated + local source: any = img.meta.source + source.fields = 2 + end + end + end + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local BPP = { rgba8 = 4, rgb8 = 3, gray8 = 1, yuv420p = 0 } + +-- encode(img, opts?) -> buffer | nil, Err: an rgba8 / rgb8 / gray8 / yuv420p Image as a baseline or progressive JPEG +function Jpeg.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or type(img.pixels) ~= "buffer" or type(img.width) ~= "number" or type(img.height) ~= "number" then + return nil, Err.new(Err.ARG, "needs an Image") + end + local bpp = BPP[img.format] + if not bpp then + return nil, Err.new(Err.ARG, "needs an rgba8, rgb8, gray8 or yuv420p Image (got " .. tostring(img.format) .. ")") + end + local w, h = img.width, img.height + local need = if bpp == 0 then w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2) else w * h * bpp + if w < 1 or h < 1 or w > 65535 or h > 65535 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < need then + return nil, Err.new(Err.ARG, "bad image size or pixel buffer (1..65535 per side)") + end + if opts ~= nil and type(opts) ~= "table" then + return nil, Err.new(Err.ARG, "options must be a table") + end + local o: any = opts or {} + local quality = o.quality or 90 + if type(quality) ~= "number" or quality < 1 or quality > 100 then + return nil, Err.new(Err.ARG, "quality must be 1..100") + end + local sub = o.subsampling or "420" + if sub ~= "420" and sub ~= "422" and sub ~= "444" then + return nil, Err.new(Err.ARG, "subsampling must be \"420\", \"422\" or \"444\"") + end + if bpp == 0 then + sub = "420" + end + local restart = o.restart or 0 + if type(restart) ~= "number" or restart < 0 or restart > 65535 or restart % 1 ~= 0 then + return nil, Err.new(Err.ARG, "restart must be 0..65535 MCUs") + end + local gray = o.gray + if gray == nil then + gray = img.format == "gray8" + end + local segments = {} + if o.segments ~= nil then + if type(o.segments) ~= "table" then + return nil, Err.new(Err.ARG, "segments must be a list of { marker, data }") + end + for _, sg in o.segments do + if type(sg) ~= "table" or type(sg.data) ~= "buffer" or buffer.len(sg.data) > 65533 or type(sg.marker) ~= "number" then + return nil, Err.new(Err.ARG, "bad segment (marker 0xE0..0xEF / 0xFE, at most 65533 bytes)") + end + if not ((sg.marker >= 0xE0 and sg.marker <= 0xEF) or sg.marker == 0xFE) then + return nil, Err.new(Err.ARG, "bad segment marker (0xE0..0xEF / 0xFE)") + end + table.insert(segments, sg) + end + end + local density = o.density + if density ~= nil then + if type(density) ~= "table" or type(density.unit) ~= "number" or type(density.x) ~= "number" or type(density.y) ~= "number" then + return nil, Err.new(Err.ARG, "bad density") + end + density = { + unit = math.clamp(math.floor(density.unit), 0, 2), + x = math.clamp(math.floor(density.x), 1, 65535), + y = math.clamp(math.floor(density.y), 1, 65535), + } + end + local out = Encode.run(img.pixels, w, h, bpp, { + quality = quality, + sampling = sub, + progressive = o.progressive == true, + optimize = o.optimize == true, + gray = gray, + restart = restart, + segments = segments, + jfif = o.jfif ~= false, + density = density, + }) + return out, nil +end + +return Jpeg diff --git a/src/Formats/codecs/Mdct/Fft.luau b/src/Formats/codecs/Mdct/Fft.luau new file mode 100644 index 0000000..b4900df --- /dev/null +++ b/src/Formats/codecs/Mdct/Fft.luau @@ -0,0 +1,211 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Mdct/Fft: mixed-radix complex FFT of any size (radix 4, 2, 3, 5 butterflies, a generic odd-radix pass for +-- other primes), self-sorting Stockham passes ping-ponging between the data and a scratch array (the FFTPACK / +-- pocketfft pass structure, written from the textbook decimation-in-frequency derivation; no third-party code). +-- Data are separate real / imaginary arrays, 1-based. Never throws. +local Fft = {} + +export type Plan = { + n: number, + factors: { number }, + -- per pass: twiddles exp(-2 pi i u i l1 / n) for u = 1 .. p - 1, i = 0 .. ido - 1 at [(u - 1) * ido + i + 1] + twr: { { number } }, + twi: { { number } }, + -- per pass, generic odd radix: exp(-2 pi i k / p) for k = 0 .. p - 1 + rr: { { number } }, + ri: { { number } }, + sre: { number }, -- scratch + sim: { number }, +} + +local cos, sin, pi = math.cos, math.sin, math.pi + +-- new(n) -> Plan | nil (n < 1 or not an integer) +function Fft.new(n: number): Plan? + if type(n) ~= "number" or n < 1 or n % 1 ~= 0 or n > 2 ^ 24 then + return nil + end + local factors = {} + local m = n + while m % 4 == 0 do + table.insert(factors, 4) + m //= 4 + end + while m % 2 == 0 do + table.insert(factors, 2) + m //= 2 + end + local f = 3 + while m > 1 do + while m % f == 0 do + table.insert(factors, f) + m //= f + end + f += 2 + if f * f > m and m > 1 then + table.insert(factors, m) + m = 1 + end + end + local twr, twi, rr, ri = {}, {}, {}, {} + local l1 = 1 + for k, p in factors do + local ido = n // (l1 * p) + local tr, ti = table.create((p - 1) * ido, 0), table.create((p - 1) * ido, 0) + for u = 1, p - 1 do + for i = 0, ido - 1 do + local a = -2 * pi * u * i * l1 / n + tr[(u - 1) * ido + i + 1] = cos(a) + ti[(u - 1) * ido + i + 1] = sin(a) + end + end + twr[k], twi[k] = tr, ti + local cr, ci = table.create(p, 0), table.create(p, 0) + for j = 0, p - 1 do + cr[j + 1] = cos(-2 * pi * j / p) + ci[j + 1] = sin(-2 * pi * j / p) + end + rr[k], ri[k] = cr, ci + l1 *= p + end + return { + n = n, + factors = factors, + twr = twr, + twi = twi, + rr = rr, + ri = ri, + sre = table.create(n, 0), + sim = table.create(n, 0), + } +end + +-- one pass of radix p: cc (i, v, k) = src[1 + i + ido * (v + p * k)] -> ch (i, k, u) = dst[1 + i + ido * (k + l1 * u)] +local function pass(p: number, ido: number, l1: number, ar: { number }, ai: { number }, br: { number }, bi: { number }, tr: { number }, ti: { number }, cr: { number }, ci: { number }) + local lp = ido * l1 + if p == 4 then + for k = 0, l1 - 1 do + for i = 0, ido - 1 do + local s = 1 + i + ido * 4 * k + local a0r, a0i = ar[s], ai[s] + local a1r, a1i = ar[s + ido], ai[s + ido] + local a2r, a2i = ar[s + 2 * ido], ai[s + 2 * ido] + local a3r, a3i = ar[s + 3 * ido], ai[s + 3 * ido] + local t0r, t0i = a0r + a2r, a0i + a2i + local t1r, t1i = a0r - a2r, a0i - a2i + local t2r, t2i = a1r + a3r, a1i + a3i + local t3r, t3i = a1r - a3r, a1i - a3i + local d = 1 + i + ido * k + br[d], bi[d] = t0r + t2r, t0i + t2i + local y1r, y1i = t1r + t3i, t1i - t3r + local y2r, y2i = t0r - t2r, t0i - t2i + local y3r, y3i = t1r - t3i, t1i + t3r + if i == 0 then + br[d + lp], bi[d + lp] = y1r, y1i + br[d + 2 * lp], bi[d + 2 * lp] = y2r, y2i + br[d + 3 * lp], bi[d + 3 * lp] = y3r, y3i + else + local w1r, w1i = tr[i + 1], ti[i + 1] + local w2r, w2i = tr[ido + i + 1], ti[ido + i + 1] + local w3r, w3i = tr[2 * ido + i + 1], ti[2 * ido + i + 1] + br[d + lp], bi[d + lp] = y1r * w1r - y1i * w1i, y1r * w1i + y1i * w1r + br[d + 2 * lp], bi[d + 2 * lp] = y2r * w2r - y2i * w2i, y2r * w2i + y2i * w2r + br[d + 3 * lp], bi[d + 3 * lp] = y3r * w3r - y3i * w3i, y3r * w3i + y3i * w3r + end + end + end + elseif p == 2 then + for k = 0, l1 - 1 do + for i = 0, ido - 1 do + local s = 1 + i + ido * 2 * k + local a0r, a0i = ar[s], ai[s] + local a1r, a1i = ar[s + ido], ai[s + ido] + local d = 1 + i + ido * k + br[d], bi[d] = a0r + a1r, a0i + a1i + local yr, yi = a0r - a1r, a0i - a1i + if i == 0 then + br[d + lp], bi[d + lp] = yr, yi + else + local wr, wi = tr[i + 1], ti[i + 1] + br[d + lp], bi[d + lp] = yr * wr - yi * wi, yr * wi + yi * wr + end + end + end + elseif p == 3 then + local c = 0.86602540378443864676 -- sin(pi / 3) + for k = 0, l1 - 1 do + for i = 0, ido - 1 do + local s = 1 + i + ido * 3 * k + local a0r, a0i = ar[s], ai[s] + local a1r, a1i = ar[s + ido], ai[s + ido] + local a2r, a2i = ar[s + 2 * ido], ai[s + 2 * ido] + local tr_, ti_ = a1r + a2r, a1i + a2i + local sr, si = a1r - a2r, a1i - a2i + local d = 1 + i + ido * k + br[d], bi[d] = a0r + tr_, a0i + ti_ + local mr, mi = a0r - 0.5 * tr_, a0i - 0.5 * ti_ + local y1r, y1i = mr + c * si, mi - c * sr + local y2r, y2i = mr - c * si, mi + c * sr + if i == 0 then + br[d + lp], bi[d + lp] = y1r, y1i + br[d + 2 * lp], bi[d + 2 * lp] = y2r, y2i + else + local w1r, w1i = tr[i + 1], ti[i + 1] + local w2r, w2i = tr[ido + i + 1], ti[ido + i + 1] + br[d + lp], bi[d + lp] = y1r * w1r - y1i * w1i, y1r * w1i + y1i * w1r + br[d + 2 * lp], bi[d + 2 * lp] = y2r * w2r - y2i * w2i, y2r * w2i + y2i * w2r + end + end + end + else + -- generic radix: y_u = sum_v a_v exp(-2 pi i u v / p), then the twiddle + for k = 0, l1 - 1 do + for i = 0, ido - 1 do + local s = 1 + i + ido * p * k + local d = 1 + i + ido * k + for u = 0, p - 1 do + local yr, yi = 0, 0 + local j = 0 + for v = 0, p - 1 do + local xr, xi = ar[s + v * ido], ai[s + v * ido] + local wr, wi = cr[j + 1], ci[j + 1] + yr += xr * wr - xi * wi + yi += xr * wi + xi * wr + j += u + if j >= p then + j -= p + end + end + if u > 0 and i > 0 then + local wr, wi = tr[(u - 1) * ido + i + 1], ti[(u - 1) * ido + i + 1] + yr, yi = yr * wr - yi * wi, yr * wi + yi * wr + end + br[d + u * lp], bi[d + u * lp] = yr, yi + end + end + end + end +end + +-- forward(plan, re, im): in-place forward DFT X[k] = sum x[j] exp(-2 pi i j k / n) of re[1..n], im[1..n]. +-- The inverse (without the 1 / n) is forward(plan, im, re). +function Fft.forward(plan: Plan, re: { number }, im: { number }) + local n = plan.n + local ar, ai, br, bi = re, im, plan.sre, plan.sim + local l1 = 1 + for k, p in plan.factors do + local ido = n // (l1 * p) + pass(p, ido, l1, ar, ai, br, bi, plan.twr[k], plan.twi[k], plan.rr[k], plan.ri[k]) + ar, ai, br, bi = br, bi, ar, ai + l1 *= p + end + if ar ~= re then + for j = 1, n do + re[j], im[j] = ar[j], ai[j] + end + end +end + +return Fft diff --git a/src/Formats/codecs/Mdct/init.luau b/src/Formats/codecs/Mdct/init.luau new file mode 100644 index 0000000..316bc21 --- /dev/null +++ b/src/Formats/codecs/Mdct/init.luau @@ -0,0 +1,203 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Mdct: the MDCT / IMDCT of any window length N divisible by 4 (N / 2 coefficients), through an N / 4-point +-- complex FFT (codecs/Mdct/Fft, mixed radix: AAC 2048 / 256, Vorbis 64 .. 8192, CELT 1920 / 240 / ...), plus the +-- DCT-IV, a plain FFT and the sine / KBD / Vorbis windows. Shared by AAC, Vorbis and Opus (decoders and encoders). +-- Written from the textbook definitions (MDCT = DCT-IV of the folded input; DCT-IV through a half-size complex FFT +-- with pre / post twiddles); no third-party code. +-- +-- X[k] = sum_{j=0}^{N-1} x[j] cos(2 pi / N (j + 1/2 + N/4) (k + 1/2)) forward, k = 0 .. N/2 - 1 +-- y[j] = sum_{k=0}^{N/2-1} X[k] cos(2 pi / N (j + 1/2 + N/4) (k + 1/2)) inverse, j = 0 .. N - 1 +-- +-- Both are unnormalised (times `scale`, default 1): windowed forward + inverse + overlap-add with a Princen-Bradley +-- window gives the input times N / 4 (AAC: the spec IMDCT is inverse(..., 2 / N), its MDCT has a factor 2). Arrays +-- are Luau arrays; `xi` / `yi` are the 1-based index of element 0, coefficient arrays may be strided (CELT +-- interleaves its short blocks). +-- +-- local Mdct = require("@formats/codecs/Mdct") +-- local plan = Mdct.new(2048) -- nil when N is not a multiple of 4 +-- Mdct.forward(plan, x, 1, X, 1) -- 2048 samples -> 1024 coefficients +-- Mdct.inverse(plan, X, 1, 1, y, 1, 2 / 2048) -- 1024 coefficients -> 2048 samples +-- local w = Mdct.window("sine", 2048) -- or "kbd" (alpha), "vorbis": N values +-- +-- Never throws: bad sizes return nil from new(); the transforms trust the plan and the array ranges (the caller +-- sizes them). +local Fft = require("@formats/codecs/Mdct/Fft") + +local cos, sin, pi, sqrt = math.cos, math.sin, math.pi, math.sqrt + +local Mdct = {} +Mdct.Fft = Fft + +export type Plan = { + n: number, -- window length N + m: number, -- coefficients N / 2 + fft: Fft.Plan, -- N / 4 points + twc: { number }, -- cos / sin (pi (p + 1/8) / M), p = 0 .. N/4 - 1 + tws: { number }, + re: { number }, -- scratch + im: { number }, + c: { number }, -- DCT-IV output scratch (M) +} + +-- new(N) -> Plan | nil +function Mdct.new(n: number): Plan? + if type(n) ~= "number" or n < 4 or n % 4 ~= 0 or n > 2 ^ 24 then + return nil + end + local m = n // 2 + local q = n // 4 + local fft = Fft.new(q) + if not fft then + return nil + end + local twc, tws = table.create(q, 0), table.create(q, 0) + for p = 0, q - 1 do + local a = pi * (p + 0.125) / m + twc[p + 1], tws[p + 1] = cos(a), sin(a) + end + return { + n = n, + m = m, + fft = fft, + twc = twc, + tws = tws, + re = table.create(q, 0), + im = table.create(q, 0), + c = table.create(m, 0), + } +end + +-- the DCT-IV of the M values u (already in plan.re / plan.im as the pre-twiddled pairs) into out[oi + k * os] +local function dct4Post(plan: Plan, out: { number }, oi: number, os: number, scale: number) + local q, m = plan.n // 4, plan.m + local re, im, twc, tws = plan.re, plan.im, plan.twc, plan.tws + Fft.forward(plan.fft, re, im) + for k = 0, q - 1 do + local c, s = twc[k + 1], tws[k + 1] + local tr, ti = re[k + 1], im[k + 1] + out[oi + 2 * k * os] = (tr * c + ti * s) * scale + out[oi + (m - 1 - 2 * k) * os] = -(ti * c - tr * s) * scale + end +end + +-- dct4(plan, u, ui, us, out, oi, os, scale?): C[k] = sum_{n=0}^{M-1} u[n] cos(pi / M (n + 1/2) (k + 1/2)) for the +-- plan's M = N / 2 (its own inverse up to 2 / M) +function Mdct.dct4(plan: Plan, u: { number }, ui: number, us: number, out: { number }, oi: number, os: number, scale: number?) + local q, m = plan.n // 4, plan.m + local re, im, twc, tws = plan.re, plan.im, plan.twc, plan.tws + for p = 0, q - 1 do + local a, b = u[ui + 2 * p * us], u[ui + (m - 1 - 2 * p) * us] + local c, s = twc[p + 1], tws[p + 1] + re[p + 1] = a * c + b * s + im[p + 1] = b * c - a * s + end + dct4Post(plan, out, oi, os, scale or 1) +end + +-- forward(plan, x, xi, X, Xi, Xs?, scale?): N samples x[xi ..] -> N / 2 coefficients X[Xi + k * Xs] +function Mdct.forward(plan: Plan, x: { number }, xi: number, out: { number }, oi: number, os: number?, scale: number?) + local q, m = plan.n // 4, plan.m + local h = m // 2 -- N / 4 + local re, im, twc, tws = plan.re, plan.im, plan.twc, plan.tws + -- fold: u[j] = -x[3M/2 - 1 - j] - x[3M/2 + j] (j < M/2), x[j - M/2] - x[3M/2 - 1 - j] (j >= M/2) + local b3 = xi + 3 * h + for p = 0, q - 1 do + local j = 2 * p + local a + if j < h then + a = -x[b3 - 1 - j] - x[b3 + j] + else + a = x[xi + j - h] - x[b3 - 1 - j] + end + j = m - 1 - 2 * p + local b + if j < h then + b = -x[b3 - 1 - j] - x[b3 + j] + else + b = x[xi + j - h] - x[b3 - 1 - j] + end + local c, s = twc[p + 1], tws[p + 1] + re[p + 1] = a * c + b * s + im[p + 1] = b * c - a * s + end + dct4Post(plan, out, oi, os or 1, scale or 1) +end + +-- inverse(plan, X, Xi, Xs?, y, yi, scale?): N / 2 coefficients X[Xi + k * Xs] -> N samples y[yi ..] (no window) +function Mdct.inverse(plan: Plan, inp: { number }, ii: number, is: number?, y: { number }, yi: number, scale: number?) + local m = plan.m + local h = m // 2 + local c = plan.c + Mdct.dct4(plan, inp, ii, is or 1, c, 1, 1, scale) + -- unfold: y = (C2, -C2 reversed, -C1 reversed, -C1) + for j = 0, h - 1 do + y[yi + j] = c[h + j + 1] + y[yi + h + j] = -c[m - j] + y[yi + m + j] = -c[h - j] + y[yi + 3 * h + j] = -c[j + 1] + end +end + +-- ------------------------------------------------------------------------------------------------ windows +local function besselI0(x: number): number + local sum, term = 1, 1 + local k = 1 + while k < 200 do + term *= (x / (2 * k)) ^ 2 + sum += term + if term < sum * 1e-17 then + break + end + k += 1 + end + return sum +end +Mdct.besselI0 = besselI0 + +-- window(kind, N, alpha?) -> N values: "sine" sin(pi (n + 1/2) / N); "kbd" Kaiser-Bessel-derived (alpha: AAC uses 4 +-- for long, 6 for short windows); "vorbis" sin(pi / 2 sin^2(pi (n + 1/2) / N)). All satisfy w[n]^2 + w[n + N/2]^2 = 1. +function Mdct.window(kind: string, n: number, alpha: number?): { number }? + if type(n) ~= "number" or n < 2 or n % 2 ~= 0 then + return nil + end + local w = table.create(n, 0) + if kind == "sine" then + for i = 0, n - 1 do + w[i + 1] = sin(pi * (i + 0.5) / n) + end + elseif kind == "vorbis" then + for i = 0, n - 1 do + local s = sin(pi * (i + 0.5) / n) + w[i + 1] = sin(pi / 2 * s * s) + end + elseif kind == "kbd" then + local half = n // 2 + local a = alpha or 4 + local kais = table.create(half + 1, 0) + local total = 0 + for i = 0, half do + local r = 2 * i / half - 1 + kais[i + 1] = besselI0(pi * a * sqrt(math.max(0, 1 - r * r))) + total += kais[i + 1] + end + local acc = 0 + for i = 0, half - 1 do + acc += kais[i + 1] + local v = sqrt(acc / total) + w[i + 1] = v + w[n - i] = v + end + else + return nil + end + return w +end + +-- fft(n) -> an Fft plan (Fft.forward(plan, re, im) transforms in place) +function Mdct.fft(n: number): Fft.Plan? + return Fft.new(n) +end + +return Mdct diff --git a/src/Formats/codecs/Mpeg1/Decoder.luau b/src/Formats/codecs/Mpeg1/Decoder.luau new file mode 100644 index 0000000..c9a054c --- /dev/null +++ b/src/Formats/codecs/Mpeg1/Decoder.luau @@ -0,0 +1,1136 @@ +--!strict +--!native +-- codecs/Mpeg1/Decoder: the MPEG-1 video decoding core (ISO/IEC 11172-2; native, never throws): I, P and B pictures, +-- half-pel motion compensation, custom quantiser matrices, sequence headers anywhere in the stream. Absorbed from +-- mpeg1-luau e2e2898 (same author; src/Mpeg1/Decoder.luau, unchanged but for this header and the requires), a port +-- of jsmpeg's decoder (src/mpeg1.js by Dominic Szablewski, MIT, licenses/jsmpeg-MIT.txt) with these changes for +-- speed and accuracy in Luau: +-- * table-driven VLC decoding (Vlc.luau) on a 32-bit peek instead of a bit-by-bit tree walk; +-- * an accurate integer IDCT (the LL&M / "islow" factorisation, 13-bit constants) instead of jsmpeg's AAN +-- approximation, so P-picture drift stays close to ffmpeg's decode; dequantisation follows the standard +-- (magnitude, truncation toward zero, oddification); +-- * B pictures (forward, backward and interpolated prediction, skipped macroblocks), which jsmpeg skips; +-- * motion compensation four bytes at a time (SWAR rounding averages); +-- * BT.601 limited-range YCbCr -> RGBA8 (jsmpeg's canvas path treats Y as full range). +-- +-- The IDCT is not codecs/Dct's: it computes the same islow transform (its put mode is bit-identical to +-- Dct.idctBlock with a unit quantiser and no level shift, checked on 20000 random blocks), but MPEG-1 adds the +-- residual of P / B blocks to the prediction before clamping, dequantises into i32 coefficients itself (MPEG +-- rounding and oddification, not JPEG's q multiply) and writes u8 samples four per writeu32, where Dct clamps to +-- 0..maxv, dequantises JPEG-style and writes u16 planes. +-- +-- Everything works on flat buffers allocated per sequence size: no allocation per block, macroblock or picture. +-- Native code must never throw (an error unwinding through native code crashes Roblox Studio): every read +-- position is checked against the data end (plus a zero pad that bounds the overrun of one macroblock), motion +-- vectors are clamped to the reference picture, and bad data ends the slice instead of raising. +local V = require("@formats/codecs/Mpeg1/Vlc") +local T = require("@formats/codecs/Mpeg1/Tables") + +local readu8 = buffer.readu8 +local writeu8 = buffer.writeu8 +local readu32 = buffer.readu32 +local writeu32 = buffer.writeu32 +local readi32 = buffer.readi32 +local writei32 = buffer.writei32 +local band = bit32.band +local bor = bit32.bor +local bxor = bit32.bxor +local lshift = bit32.lshift +local rshift = bit32.rshift +local bswap = bit32.byteswap + +local PAD = 4096 -- zero bytes after the data: a macroblock reads at most ~1.5 KB, the pos check runs per macroblock + +local D = {} + +D.PICTURE_I = 1 +D.PICTURE_P = 2 +D.PICTURE_B = 3 + +local ZZ = buffer.create(64) +local DEF_INTRA = buffer.create(64) -- scan order (Q[n] = matrix[ZZ[n]]) +local DEF_NON_INTRA = buffer.create(64) +for i = 0, 63 do + buffer.writeu8(ZZ, i, T.ZIG_ZAG[i]) + buffer.writeu8(DEF_INTRA, i, T.DEFAULT_INTRA_QUANT_MATRIX[T.ZIG_ZAG[i]]) + buffer.writeu8(DEF_NON_INTRA, i, T.DEFAULT_NON_INTRA_QUANT_MATRIX[T.ZIG_ZAG[i]]) +end + +-- clamp to 0..255 by lookup: CLAMP[v + COFF] for any v in [-COFF, COFF]. IDCT outputs are bounded by +-- 64 * 2048 / 4 = 32768 for any coefficients, plus a prediction of up to 255. +local COFF = 40000 +local CLAMP = buffer.create(2 * COFF + 256) +for i = 0, 2 * COFF + 255 do + buffer.writeu8(CLAMP, i, math.clamp(i - COFF, 0, 255)) +end + +-- BT.601 limited range: R = 1.164 (Y - 16) + 1.596 (Cr - 128), G = 1.164 (Y - 16) - 0.392 (Cb - 128) - 0.813 (Cr - +-- 128), B = 1.164 (Y - 16) + 2.017 (Cb - 128), in 8-bit fixed point. The rounding offsets (-128, -160, -72 / 256) +-- are fitted to ffmpeg's swscale output, which lands about half a level below round-to-nearest. +-- the constant terms, plus COFF * 256 so the sums stay positive for rshift +local RBIAS = COFF * 256 - 298 * 16 - 409 * 128 - 128 +local GBIAS = COFF * 256 - 298 * 16 + 100 * 128 + 208 * 128 - 160 +local BBIAS = COFF * 256 - 298 * 16 - 516 * 128 - 72 + +local MBAI, MBAI_BITS = V.MBAI, V.MBAI_BITS +local CBP, CBP_BITS = V.CBP, V.CBP_BITS +local MOTION, MOTION_BITS = V.MOTION, V.MOTION_BITS +local DC_LUMA, DC_LUMA_BITS = V.DC_LUMA, V.DC_LUMA_BITS +local DC_CHROMA, DC_CHROMA_BITS = V.DC_CHROMA, V.DC_CHROMA_BITS +local DCT_FIRST, DCT_NEXT = V.DCT_FIRST, V.DCT_NEXT +local SUB, ESC, EOB = V.SUB, V.ESC, V.EOB +local MBTYPE = { V.MBTYPE_I, V.MBTYPE_P, V.MBTYPE_B } +local MBTYPE_BITS = { V.MBTYPE_I_BITS, V.MBTYPE_P_BITS, V.MBTYPE_B_BITS } + +-- Integer IDCT (LL&M factorisation as in the IJG "islow" IDCT: CONST_BITS 13, PASS1_BITS 2) of the 64 i32 +-- coefficients in blk (natural order), written to dst (put) or added to it (add), clamped to 0..255. +local function idct(blk: buffer, ws: buffer, dst: buffer, off: number, stride: number, add: boolean) + -- pass 1: columns, into ws scaled by 4 + for c = 0, 28, 4 do + local d0 = readi32(blk, c) + local d1 = readi32(blk, c + 32) + local d2 = readi32(blk, c + 64) + local d3 = readi32(blk, c + 96) + local d4 = readi32(blk, c + 128) + local d5 = readi32(blk, c + 160) + local d6 = readi32(blk, c + 192) + local d7 = readi32(blk, c + 224) + if d1 == 0 and d2 == 0 and d3 == 0 and d4 == 0 and d5 == 0 and d6 == 0 and d7 == 0 then + local dc = d0 * 4 + writei32(ws, c, dc) + writei32(ws, c + 32, dc) + writei32(ws, c + 64, dc) + writei32(ws, c + 96, dc) + writei32(ws, c + 128, dc) + writei32(ws, c + 160, dc) + writei32(ws, c + 192, dc) + writei32(ws, c + 224, dc) + else + -- even part + local z1 = (d2 + d6) * 4433 + local t2 = z1 - d6 * 15137 + local t3 = z1 + d2 * 6270 + local t0 = (d0 + d4) * 8192 + local t1 = (d0 - d4) * 8192 + local t10 = t0 + t3 + local t13 = t0 - t3 + local t11 = t1 + t2 + local t12 = t1 - t2 + -- odd part + local o0, o1, o2, o3 = d7, d5, d3, d1 + local y1 = o0 + o3 + local y2 = o1 + o2 + local y3 = o0 + o2 + local y4 = o1 + o3 + local z5 = (y3 + y4) * 9633 + o0 *= 2446 + o1 *= 16819 + o2 *= 25172 + o3 *= 12299 + y1 *= -7373 + y2 *= -20995 + y3 = y3 * -16069 + z5 + y4 = y4 * -3196 + z5 + o0 += y1 + y3 + o1 += y2 + y4 + o2 += y2 + y3 + o3 += y1 + y4 + writei32(ws, c, (t10 + o3 + 1024) // 2048) + writei32(ws, c + 224, (t10 - o3 + 1024) // 2048) + writei32(ws, c + 32, (t11 + o2 + 1024) // 2048) + writei32(ws, c + 192, (t11 - o2 + 1024) // 2048) + writei32(ws, c + 64, (t12 + o1 + 1024) // 2048) + writei32(ws, c + 160, (t12 - o1 + 1024) // 2048) + writei32(ws, c + 96, (t13 + o0 + 1024) // 2048) + writei32(ws, c + 128, (t13 - o0 + 1024) // 2048) + end + end + -- pass 2: rows, descaled by 2^18 (13 + 2 + 3), into the picture + for r = 0, 224, 32 do + local d0 = readi32(ws, r) + local d1 = readi32(ws, r + 4) + local d2 = readi32(ws, r + 8) + local d3 = readi32(ws, r + 12) + local d4 = readi32(ws, r + 16) + local d5 = readi32(ws, r + 20) + local d6 = readi32(ws, r + 24) + local d7 = readi32(ws, r + 28) + local p0, p1, p2, p3, p4, p5, p6, p7 + if d1 == 0 and d2 == 0 and d3 == 0 and d4 == 0 and d5 == 0 and d6 == 0 and d7 == 0 then + local v = (d0 + 16) // 32 + p0, p1, p2, p3, p4, p5, p6, p7 = v, v, v, v, v, v, v, v + else + local z1 = (d2 + d6) * 4433 + local t2 = z1 - d6 * 15137 + local t3 = z1 + d2 * 6270 + local t0 = (d0 + d4) * 8192 + local t1 = (d0 - d4) * 8192 + local t10 = t0 + t3 + 131072 + local t13 = t0 - t3 + 131072 + local t11 = t1 + t2 + 131072 + local t12 = t1 - t2 + 131072 + local o0, o1, o2, o3 = d7, d5, d3, d1 + local y1 = o0 + o3 + local y2 = o1 + o2 + local y3 = o0 + o2 + local y4 = o1 + o3 + local z5 = (y3 + y4) * 9633 + o0 *= 2446 + o1 *= 16819 + o2 *= 25172 + o3 *= 12299 + y1 *= -7373 + y2 *= -20995 + y3 = y3 * -16069 + z5 + y4 = y4 * -3196 + z5 + o0 += y1 + y3 + o1 += y2 + y4 + o2 += y2 + y3 + o3 += y1 + y4 + p0 = (t10 + o3) // 262144 + p7 = (t10 - o3) // 262144 + p1 = (t11 + o2) // 262144 + p6 = (t11 - o2) // 262144 + p2 = (t12 + o1) // 262144 + p5 = (t12 - o1) // 262144 + p3 = (t13 + o0) // 262144 + p4 = (t13 - o0) // 262144 + end + if add then + p0 += readu8(dst, off) + p1 += readu8(dst, off + 1) + p2 += readu8(dst, off + 2) + p3 += readu8(dst, off + 3) + p4 += readu8(dst, off + 4) + p5 += readu8(dst, off + 5) + p6 += readu8(dst, off + 6) + p7 += readu8(dst, off + 7) + end + writeu32( + dst, + off, + readu8(CLAMP, p0 + COFF) + + readu8(CLAMP, p1 + COFF) * 256 + + readu8(CLAMP, p2 + COFF) * 65536 + + readu8(CLAMP, p3 + COFF) * 16777216 + ) + writeu32( + dst, + off + 4, + readu8(CLAMP, p4 + COFF) + + readu8(CLAMP, p5 + COFF) * 256 + + readu8(CLAMP, p6 + COFF) * 65536 + + readu8(CLAMP, p7 + COFF) * 16777216 + ) + off += stride + end +end +D.idct = idct + +-- a constant 8x8 block (DC only): put or add v +local function fillBlock(dst: buffer, off: number, stride: number, v: number, add: boolean) + if not add then + local c = readu8(CLAMP, v + COFF) * 0x01010101 + for _ = 1, 8 do + writeu32(dst, off, c) + writeu32(dst, off + 4, c) + off += stride + end + else + for _ = 1, 8 do + for i = off, off + 7 do + writeu8(dst, i, readu8(CLAMP, readu8(dst, i) + v + COFF)) + end + off += stride + end + end +end + +-- Motion-compensated prediction of a size x size block (16 luma, 8 chroma) from src at sOff to dst at dOff with +-- half-pel flags hx / hy; avg averages into what dst holds (the second prediction of a B macroblock). Four bytes at +-- a time: avg(a, b) rounding up = (a | b) - ((a ^ b) & 0xFE..) >> 1; the 4-tap average splits each byte into its +-- low 2 bits and high 6 bits so no lane overflows. +local function mc(src: buffer, dst: buffer, stride: number, sOff: number, dOff: number, size: number, hx: number, hy: number, avg: boolean) + for _ = 1, size do + for i = 0, size - 4, 4 do + local p + if hx == 0 then + if hy == 0 then + p = readu32(src, sOff + i) + else + local a, b = readu32(src, sOff + i), readu32(src, sOff + i + stride) + p = bor(a, b) - rshift(band(bxor(a, b), 0xFEFEFEFE), 1) + end + elseif hy == 0 then + local a, b = readu32(src, sOff + i), readu32(src, sOff + i + 1) + p = bor(a, b) - rshift(band(bxor(a, b), 0xFEFEFEFE), 1) + else + local a, b = readu32(src, sOff + i), readu32(src, sOff + i + 1) + local c, d = readu32(src, sOff + i + stride), readu32(src, sOff + i + stride + 1) + local l = band(a, 0x03030303) + band(b, 0x03030303) + band(c, 0x03030303) + band(d, 0x03030303) + 0x02020202 + local h = rshift(band(a, 0xFCFCFCFC), 2) + rshift(band(b, 0xFCFCFCFC), 2) + rshift(band(c, 0xFCFCFCFC), 2) + rshift(band(d, 0xFCFCFCFC), 2) + p = h + band(rshift(l, 2), 0x0F0F0F0F) + end + if avg then + local q = readu32(dst, dOff + i) + p = bor(p, q) - rshift(band(bxor(p, q), 0xFEFEFEFE), 1) + end + writeu32(dst, dOff + i, p) + end + sOff += stride + dOff += stride + end +end +D.mc = mc + +-- YCbCr 4:2:0 planes (coded strides) -> RGBA8 (alpha 255), w x h, nearest chroma like ffmpeg's default swscale path +local function toRgba(Y: buffer, Cb: buffer, Cr: buffer, cw: number, w: number, h: number, out: buffer) + -- 2 x 2 pixels per chroma sample: the chroma terms are computed once per block of four + local chw = cw // 2 + local w2 = w // 2 -- whole pixel pairs per row + local stride = w * 4 + for y = 0, h - 1, 2 do + local yo = y * cw + local co = (y // 2) * chw + local o = y * stride + local two = y + 1 < h + for _ = 1, w2 do + local cb, cr = readu8(Cb, co), readu8(Cr, co) + co += 1 + local rr = cr * 409 + RBIAS + local gg = GBIAS - cb * 100 - cr * 208 + local bb = cb * 516 + BBIAS + local yv = readu8(Y, yo) * 298 + writeu32(out, o, math.clamp(rshift(yv + rr, 8) - COFF, 0, 255) + math.clamp(rshift(yv + gg, 8) - COFF, 0, 255) * 256 + math.clamp(rshift(yv + bb, 8) - COFF, 0, 255) * 65536 + 0xFF000000) + yv = readu8(Y, yo + 1) * 298 + writeu32(out, o + 4, math.clamp(rshift(yv + rr, 8) - COFF, 0, 255) + math.clamp(rshift(yv + gg, 8) - COFF, 0, 255) * 256 + math.clamp(rshift(yv + bb, 8) - COFF, 0, 255) * 65536 + 0xFF000000) + if two then + yv = readu8(Y, yo + cw) * 298 + writeu32(out, o + stride, math.clamp(rshift(yv + rr, 8) - COFF, 0, 255) + math.clamp(rshift(yv + gg, 8) - COFF, 0, 255) * 256 + math.clamp(rshift(yv + bb, 8) - COFF, 0, 255) * 65536 + 0xFF000000) + yv = readu8(Y, yo + cw + 1) * 298 + writeu32(out, o + stride + 4, math.clamp(rshift(yv + rr, 8) - COFF, 0, 255) + math.clamp(rshift(yv + gg, 8) - COFF, 0, 255) * 256 + math.clamp(rshift(yv + bb, 8) - COFF, 0, 255) * 65536 + 0xFF000000) + end + yo += 2 + o += 8 + end + if w % 2 == 1 then + -- the last column of an odd width + local cb, cr = readu8(Cb, co), readu8(Cr, co) + local rr = cr * 409 + RBIAS + local gg = GBIAS - cb * 100 - cr * 208 + local bb = cb * 516 + BBIAS + for k = 0, if two then 1 else 0 do + local yv = readu8(Y, yo + k * cw) * 298 + writeu32(out, o + k * stride, math.clamp(rshift(yv + rr, 8) - COFF, 0, 255) + math.clamp(rshift(yv + gg, 8) - COFF, 0, 255) * 256 + math.clamp(rshift(yv + bb, 8) - COFF, 0, 255) * 65536 + 0xFF000000) + end + end + end +end +D.toRgba = toRgba + +export type Store = { y: buffer, cb: buffer, cr: buffer, w: number, h: number, cw: number, tref: number, ptype: number, tag: any } + +export type Core = { + -- data + write: (src: buffer, off: number, n: number) -> (), + -- decodes the next picture; atEnd: the end of the data ends the picture. Returns the store decoded into (nil when + -- no picture is complete or it could not be decoded), and whether more data is needed. + nextPicture: (atEnd: boolean, tag: any) -> (Store?, boolean), + toRgba: (s: Store, out: buffer) -> (), + reset: () -> (), + state: { + width: number, + height: number, + codedWidth: number, + codedHeight: number, + frameRate: number, + aspect: number, + bitRate: number, + sizeChanged: boolean, + pictures: number, + errors: number, + skipped: number, + clamped: number, -- motion vectors pointing outside the reference (clamped) + maxPixels: number, + refOld: Store?, + refNew: Store?, + }, +} + +function D.new(maxPixels: number?): Core + local state = { + width = 0, + height = 0, + codedWidth = 0, + codedHeight = 0, + frameRate = 0, + aspect = 0, + bitRate = 0, + sizeChanged = false, + pictures = 0, + errors = 0, + skipped = 0, + clamped = 0, + maxPixels = maxPixels or 4096 * 2304, + refOld = nil :: Store?, + refNew = nil :: Store?, + } + + -- bitstream + local data = buffer.create(64 * 1024 + PAD) + local dataLen = 0 + local readByte = 0 -- next byte to look at for a start code + local scanPos = 0 -- resume point of the picture-end scan + local pos = 0 -- bit position inside data + local err = false + + -- sequence + local hasSeq = false + local mbW, mbH, mbSize = 0, 0, 0 + local cw, chw = 0, 0 -- luma / chroma strides (coded widths) + local intraQ = buffer.create(64) + local nonIntraQ = buffer.create(64) + buffer.copy(intraQ, 0, DEF_INTRA, 0, 64) + buffer.copy(nonIntraQ, 0, DEF_NON_INTRA, 0, 64) + local stores: { Store } = {} + local bStore: Store? = nil + + -- picture / slice / macroblock state + local ptype = 0 + local fullPelFw, fwRSize, fwF = false, 0, 1 + local fullPelBw, bwRSize, bwF = false, 0, 1 + local curY, curCb, curCr = data, data, data + local fwY, fwCb, fwCr = data, data, data + local bwY, bwCb, bwCr = data, data, data + local qs = 1 + local mbAddr, mbRow, mbCol = 0, 0, 0 + local dcY, dcCb, dcCr = 128, 128, 128 + local pmvFwH, pmvFwV, pmvBwH, pmvBwV = 0, 0, 0, 0 + local mvFwH, mvFwV, mvBwH, mvBwV = 0, 0, 0, 0 + local mbIntra = false + local motFw, motBw = false, false + local blk = buffer.create(256) + local ws = buffer.create(256) + + local function peek32(): number + local bp = rshift(pos, 3) + local w = bswap(readu32(data, bp)) + local s = band(pos, 7) + if s ~= 0 then + w = bor(lshift(w, s), rshift(readu8(data, bp + 4), 8 - s)) + end + return w + end + + local function read(n: number): number + local v = rshift(peek32(), 32 - n) + pos += n + return v + end + + local function vlc(lut: buffer, k: number): number + local e = readu32(lut, rshift(peek32(), 32 - k) * 4) + local l = rshift(e, 16) + if l == 0 then + err = true + return 0 + end + pos += l + return band(e, 0xFFFF) - 32768 + end + + -- byte offset of the next 00 00 01 xx at or after from (with xx before to), or -1 + local function findStart(from: number, to: number): number + local i = from + while i + 3 < to do + local c = readu8(data, i + 2) + if c > 1 then + i += 3 + elseif c == 1 then + if readu8(data, i) == 0 and readu8(data, i + 1) == 0 then + return i + end + i += 3 + else + i += 1 + end + end + return -1 + end + + local function newStore(): Store + local sz = cw * mbH * 16 + local y = buffer.create(sz) + local cb = buffer.create(sz // 4) + local cr = buffer.create(sz // 4) + buffer.fill(y, 0, 16) -- black until a picture is decoded into it + buffer.fill(cb, 0, 128) + buffer.fill(cr, 0, 128) + return { y = y, cb = cb, cr = cr, w = state.width, h = state.height, cw = cw, tref = 0, ptype = 0, tag = nil } + end + + -- sequence header at byte p (after the start code); returns false when invalid + local function sequenceHeader(p: number): boolean + pos = p * 8 + local w = read(12) + local h = read(12) + local aspect = read(4) + local rate = read(4) + local bitRate = read(18) + pos += 1 + 10 + 1 -- marker, vbv_buffer_size, constrained_parameters_flag + if w == 0 or h == 0 or w * h > state.maxPixels then + return false + end + if read(1) == 1 then + for i = 0, 63 do + local v = read(8) + writeu8(intraQ, i, if v == 0 then 1 else v) + end + else + buffer.copy(intraQ, 0, DEF_INTRA, 0, 64) + end + if read(1) == 1 then + for i = 0, 63 do + local v = read(8) + writeu8(nonIntraQ, i, if v == 0 then 1 else v) + end + else + buffer.copy(nonIntraQ, 0, DEF_NON_INTRA, 0, 64) + end + state.frameRate = T.PICTURE_RATE[rate] or 0 + state.aspect = aspect + state.bitRate = bitRate * 400 + if w ~= state.width or h ~= state.height then + state.width = w + state.height = h + mbW = (w + 15) // 16 + mbH = (h + 15) // 16 + mbSize = mbW * mbH + cw = mbW * 16 + chw = mbW * 8 + state.codedWidth = cw + state.codedHeight = mbH * 16 + stores = { newStore(), newStore() } + bStore = newStore() + state.refOld = nil + state.refNew = nil + state.sizeChanged = true + end + hasSeq = true + return true + end + + local function decodeMotion(rsize: number, f: number, pmv: number): number + local code = vlc(MOTION, MOTION_BITS) + local d = code + if code ~= 0 and f ~= 1 then + local r = read(rsize) + d = (math.abs(code) - 1) * f + r + 1 + if code < 0 then + d = -d + end + end + local v = pmv + d + if v > f * 16 - 1 then + v -= f * 32 + elseif v < -f * 16 then + v += f * 32 + end + return v + end + + -- prediction of the current macroblock from one reference (avg: average into the first prediction) + local function predict(rY: buffer, rCb: buffer, rCr: buffer, mvH: number, mvV: number, avg: boolean) + local ch = mbH * 16 + -- luma + local hx, hy = band(mvH, 1), band(mvV, 1) + local sx = mbCol * 16 + mvH // 2 + local sy = mbRow * 16 + mvV // 2 + if sx < 0 or sy < 0 or sx + 16 + hx > cw or sy + 16 + hy > ch then + -- outside the picture: a corrupt vector, clamped (full-pel) + hx, hy = 0, 0 + sx = if sx < 0 then 0 elseif sx > cw - 16 then cw - 16 else sx + sy = if sy < 0 then 0 elseif sy > ch - 16 then ch - 16 else sy + state.clamped += 1 + end + mc(rY, curY, cw, sy * cw + sx, mbRow * 16 * cw + mbCol * 16, 16, hx, hy, avg) + -- chroma: vector / 2 truncated toward zero + local cH = if mvH < 0 then -((-mvH) // 2) else mvH // 2 + local cV = if mvV < 0 then -((-mvV) // 2) else mvV // 2 + hx, hy = band(cH, 1), band(cV, 1) + sx = mbCol * 8 + cH // 2 + sy = mbRow * 8 + cV // 2 + local chh = mbH * 8 + if sx < 0 or sy < 0 or sx + 8 + hx > chw or sy + 8 + hy > chh then + hx, hy = 0, 0 + sx = if sx < 0 then 0 elseif sx > chw - 8 then chw - 8 else sx + sy = if sy < 0 then 0 elseif sy > chh - 8 then chh - 8 else sy + end + local so = sy * chw + sx + local dof = mbRow * 8 * chw + mbCol * 8 + mc(rCb, curCb, chw, so, dof, 8, hx, hy, avg) + mc(rCr, curCr, chw, so, dof, 8, hx, hy, avg) + end + + -- prediction of a non-intra macroblock from the current motion state + local function predictMb() + if ptype == 2 then + predict(fwY, fwCb, fwCr, mvFwH, mvFwV, false) + elseif motFw then + predict(fwY, fwCb, fwCr, mvFwH, mvFwV, false) + if motBw then + predict(bwY, bwCb, bwCr, mvBwH, mvBwV, true) + end + elseif motBw then + predict(bwY, bwCb, bwCr, mvBwH, mvBwV, false) + end + end + + -- Macroblocks no slice covers. ffmpeg's encoder skips the last macroblock of a row at the end of an MPEG-1 + -- slice (the next slice starts on the next row), and ffmpeg's decoder conceals it as a skipped macroblock; so do + -- we: P (and a damaged I) copies the reference with a zero vector, B repeats the prediction of the macroblock + -- before the gap. + local covered = 0 + local gapFw, gapBw = false, false + local gapFwH, gapFwV, gapBwH, gapBwV = 0, 0, 0, 0 + local hasRef = false + local function conceal(from: number, to: number) + if from > to or not hasRef then + return + end + local sFw, sBw, sFwH, sFwV, sBwH, sBwV = motFw, motBw, mvFwH, mvFwV, mvBwH, mvBwV + if ptype == 3 then + motFw, motBw, mvFwH, mvFwV, mvBwH, mvBwV = gapFw, gapBw, gapFwH, gapFwV, gapBwH, gapBwV + if not motFw and not motBw then + motFw = true + mvFwH, mvFwV = 0, 0 + end + elseif ptype == 2 and gapFw then + mvFwH, mvFwV = gapFwH, gapFwV + else + mvFwH, mvFwV = 0, 0 + end + local pt = ptype + if pt == 1 then + ptype = 2 -- a damaged I picture: copy the previous reference + end + for a = from, to do + mbRow = a // mbW + mbCol = a % mbW + predictMb() + end + ptype = pt + motFw, motBw, mvFwH, mvFwV, mvBwH, mvBwV = sFw, sBw, sFwH, sFwV, sBwH, sBwV + end + + -- one 8x8 block: coefficients, dequantisation, IDCT into the picture. False on a bitstream error. + local function decodeBlock(b: number): boolean + local n = 0 + local q: buffer + local onlyDc = true + if mbIntra then + local dc + if b < 4 then + local size = vlc(DC_LUMA, DC_LUMA_BITS) + dc = dcY + if size > 0 then + local diff = read(size) + if band(diff, lshift(1, size - 1)) == 0 then + diff = diff + 1 - lshift(1, size) + end + dc += diff + end + dcY = dc + else + local size = vlc(DC_CHROMA, DC_CHROMA_BITS) + dc = if b == 4 then dcCb else dcCr + if size > 0 then + local diff = read(size) + if band(diff, lshift(1, size - 1)) == 0 then + diff = diff + 1 - lshift(1, size) + end + dc += diff + end + if b == 4 then + dcCb = dc + else + dcCr = dc + end + end + if err then + return false + end + if dc < 0 or dc > 255 then + -- out of range (corrupt data): clamp, which also bounds the IDCT input + dc = if dc < 0 then 0 else 255 + if b < 4 then + dcY = dc + elseif b == 4 then + dcCb = dc + else + dcCr = dc + end + end + writei32(blk, 0, dc * 8) + q = intraQ + n = 1 + else + q = nonIntraQ + end + local lut = if n == 0 then DCT_FIRST else DCT_NEXT + local intra = mbIntra + local qscale = qs + while true do + -- inline peek + local bp = rshift(pos, 3) + local w = bswap(readu32(data, bp)) + local s = band(pos, 7) + if s ~= 0 then + w = bor(lshift(w, s), rshift(readu8(data, bp + 4), 8 - s)) + end + local e = readu32(lut, rshift(w, 24) * 4) + if e >= SUB then + e = readu32(lut, (band(e, 0xFFFF) * 256 + band(rshift(w, 16), 255)) * 4) + end + local l = rshift(e, 16) + if l == 0 then + err = true + return false + end + local v = band(e, 0xFFFF) + lut = DCT_NEXT + if v == EOB then + pos += l + break + end + local run, level, neg + if v == ESC then + -- 6-bit run, then an 8-bit level or 0x00 / 0x80 and 8 more bits + pos += l + run = read(6) + level = read(8) + if level == 0 then + level = read(8) + elseif level == 128 then + level = read(8) - 256 + elseif level > 128 then + level -= 256 + end + neg = level < 0 + if neg then + level = -level + end + if level == 0 then + err = true + return false + end + else + run = rshift(v, 8) + level = band(v, 255) + neg = band(lshift(w, l), 0x80000000) ~= 0 -- the sign bit follows the code + pos += l + 1 + end + n += run + if n > 63 then + err = true + return false + end + -- dequantise the magnitude (truncating), make it odd toward zero, clamp + local m + if intra then + m = (level * 2 * qscale * readu8(q, n)) // 16 + else + m = ((level * 2 + 1) * qscale * readu8(q, n)) // 16 + end + if band(m, 1) == 0 and m ~= 0 then + m -= 1 + end + if neg then + if m > 2048 then + m = 2048 + end + m = -m + elseif m > 2047 then + m = 2047 + end + local zz = readu8(ZZ, n) + if zz ~= 0 then + onlyDc = false + end + writei32(blk, zz * 4, m) + n += 1 + end + -- reconstruction + local dst, off, stride + if b < 4 then + dst = curY + stride = cw + off = (mbRow * 16 + (if b >= 2 then 8 else 0)) * cw + mbCol * 16 + (if b % 2 == 1 then 8 else 0) + else + dst = if b == 4 then curCb else curCr + stride = chw + off = mbRow * 8 * chw + mbCol * 8 + end + if onlyDc then + fillBlock(dst, off, stride, (readi32(blk, 0) + 4) // 8, not intra) + writei32(blk, 0, 0) + else + idct(blk, ws, dst, off, stride, not intra) + buffer.fill(blk, 0, 0, 256) + end + return true + end + + local function resetMv() + pmvFwH, pmvFwV, pmvBwH, pmvBwV = 0, 0, 0, 0 + mvFwH, mvFwV, mvBwH, mvBwV = 0, 0, 0, 0 + end + + -- one macroblock (with the skipped ones before it). False on a bitstream error or the end of the slice data. + local function decodeMacroblock(first: boolean, endBits: number): boolean + local inc = 0 + local t = vlc(MBAI, MBAI_BITS) + while t == 34 and not err and pos < endBits do -- stuffing + t = vlc(MBAI, MBAI_BITS) + end + while t == 35 and not err and pos < endBits do -- escape + inc += 33 + t = vlc(MBAI, MBAI_BITS) + end + if err or t < 1 or t > 33 then + err = true + return false + end + inc += t + if first then + mbAddr += inc + if mbAddr > covered and mbAddr <= mbSize then + conceal(covered, mbAddr - 1) + end + else + if mbAddr + inc >= mbSize then + err = true + return false + end + if inc > 1 then + dcY, dcCb, dcCr = 128, 128, 128 + if ptype == 2 then + resetMv() + end + -- skipped macroblocks: P copies the reference (zero vector), B repeats the previous prediction + for _ = 2, inc do + mbAddr += 1 + mbRow = mbAddr // mbW + mbCol = mbAddr % mbW + if ptype == 1 then + err = true -- no skipped macroblocks in I pictures + return false + end + predictMb() + end + end + mbAddr += 1 + end + if mbAddr < 0 or mbAddr >= mbSize then + err = true + return false + end + mbRow = mbAddr // mbW + mbCol = mbAddr % mbW + covered = mbAddr + 1 + + local mt = vlc(MBTYPE[ptype], MBTYPE_BITS[ptype]) + if err then + return false + end + mbIntra = band(mt, 1) ~= 0 + if band(mt, 0x10) ~= 0 then + qs = read(5) + if qs == 0 then + err = true + return false + end + end + if mbIntra then + resetMv() + else + dcY, dcCb, dcCr = 128, 128, 128 + motFw = band(mt, 8) ~= 0 + motBw = band(mt, 4) ~= 0 + if motFw then + pmvFwH = decodeMotion(fwRSize, fwF, pmvFwH) + pmvFwV = decodeMotion(fwRSize, fwF, pmvFwV) + mvFwH = if fullPelFw then pmvFwH * 2 else pmvFwH + mvFwV = if fullPelFw then pmvFwV * 2 else pmvFwV + elseif ptype == 2 then + resetMv() + end + if motBw then + pmvBwH = decodeMotion(bwRSize, bwF, pmvBwH) + pmvBwV = decodeMotion(bwRSize, bwF, pmvBwV) + mvBwH = if fullPelBw then pmvBwH * 2 else pmvBwH + mvBwV = if fullPelBw then pmvBwV * 2 else pmvBwV + end + if err then + return false + end + predictMb() + end + local cbp + if band(mt, 2) ~= 0 then + cbp = vlc(CBP, CBP_BITS) + if err then + return false + end + else + cbp = if mbIntra then 63 else 0 + end + if cbp ~= 0 then + for b = 0, 5 do + if band(cbp, rshift(32, b)) ~= 0 then + if not decodeBlock(b) then + return false + end + end + end + end + return pos <= endBits + end + + local function decodeSlice(row: number, endByte: number) + if row > mbH then + return + end + mbAddr = (row - 1) * mbW - 1 + resetMv() + dcY, dcCb, dcCr = 128, 128, 128 + motFw, motBw = false, false + qs = read(5) + local endBits = endByte * 8 + while read(1) == 1 and pos < endBits do + pos += 8 + end + if qs == 0 then + return + end + local first = true + while true do + if not decodeMacroblock(first, endBits) then + state.errors += 1 + buffer.fill(blk, 0, 0, 256) -- a block may have stopped half decoded + break + end + first = false + -- the slice ends at a start code (byte aligned) or at the end of the picture data + local i = rshift(pos + 7, 3) + if i >= endByte then + break + end + if readu8(data, i) == 0 and readu8(data, i + 1) == 0 and readu8(data, i + 2) == 1 then + break + end + end + -- the motion state a gap after this slice repeats (B pictures) + if mbIntra then + gapFw, gapBw = false, false + else + gapFw, gapBw, gapFwH, gapFwV, gapBwH, gapBwV = motFw, motBw, mvFwH, mvFwV, mvBwH, mvBwV + end + end + + -- the picture whose header starts at byte p (after 00 00 01 00) and ends at byte stop + local function decodePicture(p: number, stop: number, tag: any): Store? + pos = p * 8 + local tref = read(10) + ptype = read(3) + pos += 16 -- vbv_delay + if ptype < 1 or ptype > 3 then + state.skipped += 1 -- D pictures and invalid types + return nil + end + if ptype >= 2 then + fullPelFw = read(1) == 1 + local fcode = read(3) + if fcode == 0 then + state.skipped += 1 + return nil + end + fwRSize = fcode - 1 + fwF = lshift(1, fwRSize) + end + if ptype == 3 then + fullPelBw = read(1) == 1 + local bcode = read(3) + if bcode == 0 then + state.skipped += 1 + return nil + end + bwRSize = bcode - 1 + bwF = lshift(1, bwRSize) + end + -- references: P from the newest, B between the two newest + local target: Store + local refOld, refNew = state.refOld, state.refNew + if ptype == 1 then + target = if stores[1] == refNew then stores[2] else stores[1] + if refNew then + fwY, fwCb, fwCr = refNew.y, refNew.cb, refNew.cr + end + elseif ptype == 2 then + if refNew == nil then + state.skipped += 1 + return nil + end + target = if stores[1] == refNew then stores[2] else stores[1] + fwY, fwCb, fwCr = refNew.y, refNew.cb, refNew.cr + else + if refOld == nil or refNew == nil or bStore == nil then + state.skipped += 1 + return nil + end + target = bStore :: Store + local ro, rn = refOld :: Store, refNew :: Store + fwY, fwCb, fwCr = ro.y, ro.cb, ro.cr + bwY, bwCb, bwCr = rn.y, rn.cb, rn.cr + end + curY, curCb, curCr = target.y, target.cb, target.cr + err = false + covered = 0 + hasRef = refNew ~= nil + gapFw, gapBw = false, false + mbIntra = false + + -- slices + local at = findStart(rshift(pos + 7, 3), stop) + while at >= 0 do + local code = readu8(data, at + 3) + if code >= 0x01 and code <= 0xAF then + pos = (at + 4) * 8 + err = false + decodeSlice(code, stop) + local nb = rshift(pos + 7, 3) + if nb >= stop then + break + end + at = findStart(nb, stop) + elseif code == 0xB2 or code == 0xB5 then + at = findStart(at + 4, stop) + else + break + end + end + conceal(covered, mbSize - 1) + state.pictures += 1 + target.tref = tref + target.ptype = ptype + target.tag = tag + if ptype ~= 3 then + -- the new picture becomes the newest reference + state.refOld = refNew + state.refNew = target + end + return target + end + + local core = {} :: Core + core.state = state + + function core.write(src: buffer, off: number, n: number) + if n <= 0 then + return + end + -- drop consumed bytes, keeping the scan state relative + if readByte > 0 then + local keep = dataLen - readByte + if keep > 0 then + buffer.copy(data, 0, data, readByte, keep) + end + scanPos = math.max(0, scanPos - readByte) + dataLen = keep + readByte = 0 + end + local need = dataLen + n + PAD + if need > buffer.len(data) then + local cap = buffer.len(data) + while cap < need do + cap *= 2 + end + local nb = buffer.create(cap) + buffer.copy(nb, 0, data, 0, dataLen) + data = nb + end + buffer.copy(data, dataLen, src, off, n) + dataLen += n + buffer.fill(data, dataLen, 0, PAD) + end + + function core.nextPicture(atEnd: boolean, tag: any): (Store?, boolean) + while true do + local at = findStart(readByte, dataLen) + if at < 0 then + -- keep the last 3 bytes: a start code may straddle the next write + readByte = math.max(readByte, dataLen - 3) + if atEnd then + readByte = dataLen + end + return nil, true + end + local code = readu8(data, at + 3) + if code == 0xB3 or code == 0x00 then + -- a unit is complete when the next unit start (or the end of the data) follows it + local stop = dataLen + do + local s = findStart(math.max(at + 4, scanPos), dataLen) + while s >= 0 do + local c = readu8(data, s + 3) + if c == 0x00 or c == 0xB3 or c == 0xB7 or c == 0xB8 then + break + end + s = findStart(s + 4, dataLen) + end + if s < 0 then + if not atEnd then + scanPos = math.max(at + 4, dataLen - 3) + readByte = at + return nil, true + end + else + stop = s + end + end + scanPos = 0 + readByte = stop + if code == 0xB3 then + if not sequenceHeader(at + 4) then + state.errors += 1 + end + elseif hasSeq then + local s = decodePicture(at + 4, stop, tag) + if s then + return s, false + end + else + state.skipped += 1 + end + else + readByte = at + 4 -- GOP header, sequence end, user data, stray slices + end + end + end + + function core.toRgba(s: Store, out: buffer) + toRgba(s.y, s.cb, s.cr, s.cw, s.w, s.h, out) + end + + function core.reset() + dataLen = 0 + readByte = 0 + scanPos = 0 + state.refOld = nil + state.refNew = nil + end + + return core +end + +return D diff --git a/src/Formats/codecs/Mpeg1/Tables.luau b/src/Formats/codecs/Mpeg1/Tables.luau new file mode 100644 index 0000000..3e330ef --- /dev/null +++ b/src/Formats/codecs/Mpeg1/Tables.luau @@ -0,0 +1,117 @@ +--!strict +-- codecs/Mpeg1/Tables: the constant tables of jsmpeg's MPEG-1 video decoder (https://github.com/phoboslab/jsmpeg, +-- Dominic Szablewski, MIT, licenses/jsmpeg-MIT.txt), generated by mpeg1-luau's tools/gen_tables.py (absorbed from +-- mpeg1-luau e2e2898). Lists are 0-based like the JS arrays. +local T = {} +T.PICTURE_RATE = { [0] = 0.0, + 23.976, 24.0, 25.0, 29.97, 30.0, 50.0, 59.94, 60.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, +} +T.ZIG_ZAG = { [0] = 0, + 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, + 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, + 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63, +} +T.DEFAULT_INTRA_QUANT_MATRIX = { [0] = 8, + 16, 19, 22, 26, 27, 29, 34, 16, 16, 22, 24, 27, 29, 34, 37, 19, 22, 26, 27, 29, 34, 34, 38, 22, + 22, 26, 27, 29, 34, 37, 40, 22, 26, 27, 29, 32, 35, 40, 48, 26, 27, 29, 32, 35, 40, 48, 58, 26, + 27, 29, 34, 38, 46, 56, 69, 27, 29, 35, 38, 46, 56, 69, 83, +} +T.DEFAULT_NON_INTRA_QUANT_MATRIX = { [0] = 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, +} +T.MACROBLOCK_ADDRESS_INCREMENT = { [0] = 3, + 6, 0, 9, 12, 0, 0, 0, 1, 15, 18, 0, 21, 24, 0, 27, 30, 0, 33, 36, 0, 0, 0, 3, 0, + 0, 2, 39, 42, 0, 45, 48, 0, 0, 0, 5, 0, 0, 4, 51, 54, 0, 57, 60, 0, 0, 0, 7, 0, + 0, 6, 63, 66, 0, 69, 72, 0, 75, 78, 0, 81, 84, 0, -1, 87, 0, -1, 90, 0, 93, 96, 0, 99, + 102, 0, 105, 108, 0, 111, 114, 0, 0, 0, 9, 0, 0, 8, 117, 120, 0, 123, 126, 0, 129, 132, 0, 135, + 138, 0, 0, 0, 15, 0, 0, 14, 0, 0, 13, 0, 0, 12, 0, 0, 11, 0, 0, 10, 141, -1, 0, -1, + 144, 0, 147, 150, 0, 153, 156, 0, 159, 162, 0, 165, 168, 0, 171, 174, 0, 177, 180, 0, 183, -1, 0, -1, + 186, 0, 189, 192, 0, 195, 198, 0, 201, 204, 0, 207, 210, 0, 213, 216, 0, 219, 222, 0, 0, 0, 21, 0, + 0, 20, 0, 0, 19, 0, 0, 18, 0, 0, 17, 0, 0, 16, 0, 0, 35, 0, 0, 34, 0, 0, 33, 0, + 0, 32, 0, 0, 31, 0, 0, 30, 0, 0, 29, 0, 0, 28, 0, 0, 27, 0, 0, 26, 0, 0, 25, 0, + 0, 24, 0, 0, 23, 0, 0, 22, +} +T.MACROBLOCK_TYPE_INTRA = { [0] = 3, + 6, 0, -1, 9, 0, 0, 0, 1, 0, 0, 17, +} +T.MACROBLOCK_TYPE_PREDICTIVE = { [0] = 3, + 6, 0, 9, 12, 0, 0, 0, 10, 15, 18, 0, 0, 0, 2, 21, 24, 0, 0, 0, 8, 27, 30, 0, 33, + 36, 0, -1, 39, 0, 0, 0, 18, 0, 0, 26, 0, 0, 1, 0, 0, 17, +} +T.MACROBLOCK_TYPE_B = { [0] = 3, + 6, 0, 9, 15, 0, 12, 18, 0, 24, 21, 0, 0, 0, 12, 27, 30, 0, 0, 0, 14, 39, 42, 0, 36, + 33, 0, 0, 0, 4, 0, 0, 6, 54, 48, 0, 45, 51, 0, 0, 0, 8, 0, 0, 10, -1, 57, 0, 0, + 0, 1, 60, 63, 0, 0, 0, 30, 0, 0, 17, 0, 0, 22, 0, 0, 26, +} +T.CODE_BLOCK_PATTERN = { [0] = 6, + 3, 0, 9, 18, 0, 12, 15, 0, 24, 33, 0, 36, 39, 0, 27, 21, 0, 30, 42, 0, 60, 57, 0, 54, + 48, 0, 69, 51, 0, 81, 75, 0, 63, 84, 0, 45, 66, 0, 72, 78, 0, 0, 0, 60, 105, 120, 0, 132, + 144, 0, 114, 108, 0, 126, 141, 0, 87, 93, 0, 117, 96, 0, 0, 0, 32, 135, 138, 0, 99, 123, 0, 129, + 102, 0, 0, 0, 4, 90, 111, 0, 0, 0, 8, 0, 0, 16, 0, 0, 44, 150, 168, 0, 0, 0, 28, 0, + 0, 52, 0, 0, 62, 183, 177, 0, 156, 180, 0, 0, 0, 1, 165, 162, 0, 0, 0, 61, 0, 0, 56, 171, + 174, 0, 0, 0, 2, 0, 0, 40, 153, 186, 0, 0, 0, 48, 192, 189, 0, 147, 159, 0, 0, 0, 20, 0, + 0, 12, 240, 249, 0, 0, 0, 63, 231, 225, 0, 195, 219, 0, 252, 198, 0, 0, 0, 24, 0, 0, 36, 0, + 0, 3, 207, 261, 0, 243, 237, 0, 204, 213, 0, 210, 234, 0, 201, 228, 0, 216, 222, 0, 258, 255, 0, 264, + 246, 0, -1, 282, 0, 285, 291, 0, 0, 0, 33, 0, 0, 9, 318, 330, 0, 306, 348, 0, 0, 0, 5, 0, + 0, 10, 279, 267, 0, 0, 0, 6, 0, 0, 18, 0, 0, 17, 0, 0, 34, 339, 357, 0, 309, 312, 0, 270, + 276, 0, 327, 321, 0, 351, 354, 0, 303, 297, 0, 294, 288, 0, 300, 273, 0, 342, 345, 0, 315, 324, 0, 336, + 333, 0, 363, 375, 0, 0, 0, 41, 0, 0, 14, 0, 0, 21, 372, 366, 0, 360, 369, 0, 0, 0, 11, 0, + 0, 19, 0, 0, 7, 0, 0, 35, 0, 0, 13, 0, 0, 50, 0, 0, 49, 0, 0, 58, 0, 0, 37, 0, + 0, 25, 0, 0, 45, 0, 0, 57, 0, 0, 26, 0, 0, 29, 0, 0, 38, 0, 0, 53, 0, 0, 23, 0, + 0, 43, 0, 0, 46, 0, 0, 42, 0, 0, 22, 0, 0, 54, 0, 0, 51, 0, 0, 15, 0, 0, 30, 0, + 0, 39, 0, 0, 47, 0, 0, 55, 0, 0, 27, 0, 0, 59, 0, 0, 31, +} +T.MOTION = { [0] = 3, + 6, 0, 12, 9, 0, 0, 0, 0, 18, 15, 0, 24, 21, 0, 0, 0, -1, 0, 0, 1, 27, 30, 0, 36, + 33, 0, 0, 0, 2, 0, 0, -2, 42, 45, 0, 48, 39, 0, 60, 54, 0, 0, 0, 3, 0, 0, -3, 51, + 57, 0, -1, 69, 0, 81, 75, 0, 78, 63, 0, 72, 66, 0, 96, 84, 0, 87, 93, 0, -1, 99, 0, 108, + 105, 0, 0, 0, -4, 90, 102, 0, 0, 0, 4, 0, 0, -7, 0, 0, 5, 111, 123, 0, 0, 0, -5, 0, + 0, 7, 114, 120, 0, 126, 117, 0, 0, 0, -6, 0, 0, 6, 153, 162, 0, 150, 147, 0, 135, 138, 0, 156, + 141, 0, 129, 159, 0, 132, 144, 0, 0, 0, 10, 0, 0, 9, 0, 0, 8, 0, 0, -8, 171, 198, 0, 0, + 0, -9, 180, 192, 0, 168, 183, 0, 165, 186, 0, 174, 189, 0, 0, 0, -10, 177, 195, 0, 0, 0, 12, 0, + 0, 16, 0, 0, 13, 0, 0, 14, 0, 0, 11, 0, 0, 15, 0, 0, -16, 0, 0, -12, 0, 0, -14, 0, + 0, -15, 0, 0, -11, 0, 0, -13, +} +T.DCT_DC_SIZE_LUMINANCE = { [0] = 6, + 3, 0, 18, 15, 0, 9, 12, 0, 0, 0, 1, 0, 0, 2, 27, 24, 0, 21, 30, 0, 0, 0, 0, 36, + 33, 0, 0, 0, 4, 0, 0, 3, 39, 42, 0, 0, 0, 5, 0, 0, 6, 48, 45, 0, 51, -1, 0, 0, + 0, 7, 0, 0, 8, +} +T.DCT_DC_SIZE_CHROMINANCE = { [0] = 6, + 3, 0, 12, 9, 0, 18, 15, 0, 24, 21, 0, 0, 0, 2, 0, 0, 1, 0, 0, 0, 30, 27, 0, 0, + 0, 3, 36, 33, 0, 0, 0, 4, 42, 39, 0, 0, 0, 5, 48, 45, 0, 0, 0, 6, 51, -1, 0, 0, + 0, 7, 0, 0, 8, +} +T.DCT_COEFF = { [0] = 3, + 6, 0, 12, 9, 0, 0, 0, 1, 21, 24, 0, 18, 15, 0, 39, 27, 0, 33, 30, 0, 42, 36, 0, 0, + 0, 257, 60, 66, 0, 54, 63, 0, 48, 57, 0, 0, 0, 513, 51, 45, 0, 0, 0, 2, 0, 0, 3, 81, + 75, 0, 87, 93, 0, 72, 78, 0, 96, 90, 0, 0, 0, 1025, 69, 84, 0, 0, 0, 769, 0, 0, 258, 0, + 0, 1793, 0, 0, 65535, 0, 0, 1537, 111, 108, 0, 0, 0, 1281, 105, 102, 0, 117, 114, 0, 99, 126, 0, 120, + 123, 0, 156, 150, 0, 162, 159, 0, 144, 147, 0, 129, 135, 0, 138, 132, 0, 0, 0, 2049, 0, 0, 4, 0, + 0, 514, 0, 0, 2305, 153, 141, 0, 165, 171, 0, 180, 168, 0, 177, 174, 0, 183, 186, 0, 0, 0, 2561, 0, + 0, 3329, 0, 0, 6, 0, 0, 259, 0, 0, 5, 0, 0, 770, 0, 0, 2817, 0, 0, 3073, 228, 225, 0, 201, + 210, 0, 219, 213, 0, 234, 222, 0, 216, 231, 0, 207, 192, 0, 204, 189, 0, 198, 195, 0, 243, 261, 0, 273, + 240, 0, 246, 237, 0, 249, 258, 0, 279, 276, 0, 252, 255, 0, 270, 282, 0, 264, 267, 0, 0, 0, 515, 0, + 0, 260, 0, 0, 7, 0, 0, 1026, 0, 0, 1282, 0, 0, 4097, 0, 0, 3841, 0, 0, 3585, 315, 321, 0, 333, + 342, 0, 312, 291, 0, 375, 357, 0, 288, 294, 0, -1, 369, 0, 285, 303, 0, 318, 363, 0, 297, 306, 0, 339, + 309, 0, 336, 348, 0, 330, 300, 0, 372, 345, 0, 351, 366, 0, 327, 354, 0, 360, 324, 0, 381, 408, 0, 417, + 420, 0, 390, 378, 0, 435, 438, 0, 384, 387, 0, 0, 0, 2050, 396, 402, 0, 465, 462, 0, 0, 0, 8, 411, + 399, 0, 429, 432, 0, 453, 414, 0, 426, 423, 0, 0, 0, 10, 0, 0, 9, 0, 0, 11, 0, 0, 5377, 0, + 0, 1538, 0, 0, 771, 0, 0, 5121, 0, 0, 1794, 0, 0, 4353, 0, 0, 4609, 0, 0, 4865, 444, 456, 0, 0, + 0, 1027, 459, 450, 0, 0, 0, 261, 393, 405, 0, 0, 0, 516, 447, 441, 0, 516, 519, 0, 486, 474, 0, 510, + 483, 0, 504, 498, 0, 471, 537, 0, 507, 501, 0, 522, 513, 0, 534, 531, 0, 468, 477, 0, 492, 495, 0, 549, + 546, 0, 525, 528, 0, 0, 0, 263, 0, 0, 2562, 0, 0, 2306, 0, 0, 5633, 0, 0, 5889, 0, 0, 6401, 0, + 0, 6145, 0, 0, 1283, 0, 0, 772, 0, 0, 13, 0, 0, 12, 0, 0, 14, 0, 0, 15, 0, 0, 517, 0, + 0, 6657, 0, 0, 262, 540, 543, 0, 480, 489, 0, 588, 597, 0, 0, 0, 27, 609, 555, 0, 606, 603, 0, 0, + 0, 19, 0, 0, 22, 591, 621, 0, 0, 0, 18, 573, 576, 0, 564, 570, 0, 0, 0, 20, 552, 582, 0, 0, + 0, 21, 558, 579, 0, 0, 0, 23, 612, 594, 0, 0, 0, 25, 0, 0, 24, 600, 615, 0, 0, 0, 31, 0, + 0, 30, 0, 0, 28, 0, 0, 29, 0, 0, 26, 0, 0, 17, 0, 0, 16, 567, 618, 0, 561, 585, 0, 654, + 633, 0, 0, 0, 37, 645, 648, 0, 0, 0, 36, 630, 636, 0, 0, 0, 34, 639, 627, 0, 663, 666, 0, 657, + 624, 0, 651, 642, 0, 669, 660, 0, 0, 0, 35, 0, 0, 267, 0, 0, 40, 0, 0, 268, 0, 0, 266, 0, + 0, 32, 0, 0, 264, 0, 0, 265, 0, 0, 38, 0, 0, 269, 0, 0, 270, 0, 0, 33, 0, 0, 39, 0, + 0, 7937, 0, 0, 6913, 0, 0, 7681, 0, 0, 4098, 0, 0, 7425, 0, 0, 7169, 0, 0, 271, 0, 0, 274, 0, + 0, 273, 0, 0, 272, 0, 0, 1539, 0, 0, 2818, 0, 0, 3586, 0, 0, 3330, 0, 0, 3074, 0, 0, 3842, +} +return T diff --git a/src/Formats/codecs/Mpeg1/Vlc.luau b/src/Formats/codecs/Mpeg1/Vlc.luau new file mode 100644 index 0000000..8d34e39 --- /dev/null +++ b/src/Formats/codecs/Mpeg1/Vlc.luau @@ -0,0 +1,116 @@ +--!strict +-- codecs/Mpeg1/Vlc: lookup tables for the MPEG-1 variable-length codes, built at load time from jsmpeg's binary trees (Tables.luau). +-- +-- A flat table is indexed by the next K bits of the stream (K = the longest code) and holds +-- len * 65536 + (value + 32768) per entry; len = 0 marks an invalid code. The DCT coefficient tables are two-level +-- (8 bits, then 8 more for the long codes) and hold len * 65536 + value, value = run * 256 + level, ESC = 0xFFFF, +-- EOB = 0xFFFE, or SUB + subtable for a long-code prefix. DCT_NEXT is the table for every coefficient after the +-- first one of a block, where "10" is end_of_block and "11" is run 0 / level 1 (jsmpeg reads this as "1" and one +-- more bit); DCT_FIRST keeps "1" as run 0 / level 1. Absorbed from mpeg1-luau e2e2898 (same author), unchanged but +-- for this header and the require. +local T = require("@formats/codecs/Mpeg1/Tables") + +local V = {} + +type Leaf = { code: number, len: number, value: number } + +local function leaves(tree: { [number]: number }): { Leaf } + local out: { Leaf } = {} + local function walk(state: number, code: number, len: number) + if tree[state] == 0 and len > 0 then + table.insert(out, { code = code, len = len, value = tree[state + 2] }) + return + end + for bit = 0, 1 do + local nxt = tree[state + bit] + if nxt ~= nil and nxt > 0 then + walk(nxt, code * 2 + bit, len + 1) + end + end + end + walk(0, 0, 0) + return out +end + +local function flat(tree: { [number]: number }): (buffer, number) + local ls = leaves(tree) + local k = 0 + for _, l in ls do + k = math.max(k, l.len) + end + local lut = buffer.create(4 * 2 ^ k) + for _, l in ls do + local shift = k - l.len + local first = l.code * 2 ^ shift + for i = first, first + 2 ^ shift - 1 do + buffer.writeu32(lut, i * 4, l.len * 65536 + l.value + 32768) + end + end + return lut, k +end + +V.SUB = 0x1000000 +V.ESC = 0xFFFF +V.EOB = 0xFFFE + +-- two-level table: 256 first-level entries, then 256-entry subtables for prefixes of codes longer than 8 bits +local function twoLevel(ls: { Leaf }): buffer + local subs: { [number]: number } = {} + local nsub = 0 + for _, l in ls do + if l.len > 8 then + local prefix = l.code // 2 ^ (l.len - 8) + if subs[prefix] == nil then + nsub += 1 + subs[prefix] = nsub + end + end + end + local lut = buffer.create(4 * 256 * (1 + nsub)) + for _, l in ls do + if l.len <= 8 then + local shift = 8 - l.len + local first = l.code * 2 ^ shift + for i = first, first + 2 ^ shift - 1 do + buffer.writeu32(lut, i * 4, l.len * 65536 + l.value) + end + else + local prefix = l.code // 2 ^ (l.len - 8) + local s = subs[prefix] + buffer.writeu32(lut, prefix * 4, V.SUB + s) + local rest = l.code % 2 ^ (l.len - 8) + local shift = 16 - l.len + local first = rest * 2 ^ shift + for i = first, first + 2 ^ shift - 1 do + buffer.writeu32(lut, (s * 256 + i) * 4, l.len * 65536 + l.value) + end + end + end + return lut +end + +V.MBAI, V.MBAI_BITS = flat(T.MACROBLOCK_ADDRESS_INCREMENT) -- 34 = stuffing, 35 = escape +V.MBTYPE_I, V.MBTYPE_I_BITS = flat(T.MACROBLOCK_TYPE_INTRA) +V.MBTYPE_P, V.MBTYPE_P_BITS = flat(T.MACROBLOCK_TYPE_PREDICTIVE) +V.MBTYPE_B, V.MBTYPE_B_BITS = flat(T.MACROBLOCK_TYPE_B) +V.CBP, V.CBP_BITS = flat(T.CODE_BLOCK_PATTERN) +V.MOTION, V.MOTION_BITS = flat(T.MOTION) +V.DC_LUMA, V.DC_LUMA_BITS = flat(T.DCT_DC_SIZE_LUMINANCE) +V.DC_CHROMA, V.DC_CHROMA_BITS = flat(T.DCT_DC_SIZE_CHROMINANCE) + +do + local ls = leaves(T.DCT_COEFF) + V.DCT_FIRST = twoLevel(ls) + local nextLs: { Leaf } = {} + for _, l in ls do + if l.len == 1 and l.code == 1 then + table.insert(nextLs, { code = 2, len = 2, value = V.EOB }) -- "10" + table.insert(nextLs, { code = 3, len = 2, value = 0x0001 }) -- "11" + else + table.insert(nextLs, l) + end + end + V.DCT_NEXT = twoLevel(nextLs) +end + +return V diff --git a/src/Formats/codecs/Mpeg1/init.luau b/src/Formats/codecs/Mpeg1/init.luau new file mode 100644 index 0000000..2ff3118 --- /dev/null +++ b/src/Formats/codecs/Mpeg1/init.luau @@ -0,0 +1,262 @@ +--!strict +-- codecs/Mpeg1: an MPEG-1 video decoder (ISO/IEC 11172-2) for the MPEG-TS / MPEG-PS video formats. Absorbed from +-- mpeg1-luau e2e2898 (same author; README, docs/api.md and docs/performance.md there), a port of jsmpeg's decoder +-- (https://github.com/phoboslab/jsmpeg, Dominic Szablewski, MIT: licenses/jsmpeg-MIT.txt) extended with B-pictures, +-- an islow integer IDCT, table-driven VLC decoding and BT.601 RGBA8 output; added here: frameImage. +-- Supports: I, P and B pictures (D-pictures skipped), half / full-pel motion vectors with any f_code, custom +-- quantiser matrices, sequence headers anywhere (size changes), any size up to 4095 x 4095 (maxPixels), display +-- reordering. Accuracy: within ~0.75 MAE per RGBA channel of ffmpeg's decode (tests/codecs/mpeg1.luau). +-- Not supported: MPEG-2 streams (no picture coding extension parsing), field pictures, D-picture decoding. +-- +-- local dec = Mpeg1.new({ reorder = true, rgba = false }) +-- local frame = dec:decode(packetData, 0, len, pts) -- one picture (+ sequence / GOP headers) -> Frame?, tag = pts +-- local img = Mpeg1.frameImage(frame) -- a fresh yuv420p Types.Image (rgba8 with frameImage(f, true)) +-- dec:write(bytes); local f = dec:decodeFrame() -- or an elementary stream in pieces +-- while true do local f = dec:flush(); if not f then break end end -- at the end; dec:reset() after a seek +-- -- frame = { width, height, pixels (RGBA8 or nil, decoder-owned), y / cb / cr / codedWidth, pictureType, ... } +-- +-- Nothing here throws: bad arguments return nil / false, bad data is skipped (see Decoder.luau). +local Types = require("@formats/Types") +local D = require("@formats/codecs/Mpeg1/Decoder") + +local Mpeg1 = {} + +Mpeg1.PICTURE_I = 1 +Mpeg1.PICTURE_P = 2 +Mpeg1.PICTURE_B = 3 + +export type Frame = { + width: number, + height: number, + pixels: buffer?, -- RGBA8, width * height * 4 bytes, row-major, alpha 255; nil with { rgba = false } + pictureType: number, -- 1 I, 2 P, 3 B + temporalReference: number, -- the picture's 10-bit display index within its GOP + index: number, -- frames returned so far (1-based) + tag: any, -- the tag passed to decode() with this picture's data (follows the picture through reordering) + -- the decoded YCbCr 4:2:0 planes (decoder-owned, valid until the next decode): luma stride codedWidth, + -- chroma stride codedWidth / 2 + y: buffer, + cb: buffer, + cr: buffer, + codedWidth: number, +} + +export type Options = { + reorder: boolean?, -- true: return frames in display order (B-frame streams; one frame of delay, flush() at the + -- end). Default false: every picture is returned as soon as it is decoded (decode order, no delay), which is + -- display order for streams without B-frames. + rgba: boolean?, -- default true; false skips the RGBA conversion (use frame.y / cb / cr) + maxPixels: number?, -- larger sequence headers are rejected (default 4096 * 2304) +} + +local Decoder = {} +Decoder.__index = Decoder + +export type Decoder = typeof(setmetatable( + {} :: { + _core: D.Core, + _reorder: boolean, + _rgba: boolean, + _held: D.Store?, + _pixels: buffer?, + _count: number, + width: number, + height: number, + frameRate: number, + bitRate: number, + stats: { pictures: number, errors: number, skipped: number }, + }, + Decoder +)) + +function Mpeg1.new(opts: Options?): Decoder + local o: Options = if type(opts) == "table" then opts else {} + local core = D.new(o.maxPixels) + return setmetatable({ + _core = core, + _reorder = o.reorder == true, + _rgba = o.rgba ~= false, + _held = nil, + _pixels = nil, + _count = 0, + width = 0, + height = 0, + frameRate = 0, + bitRate = 0, + stats = { pictures = 0, errors = 0, skipped = 0 }, + }, Decoder) +end + +local function emit(self: Decoder, s: D.Store): Frame + local core = self._core + local pixels: buffer? = nil + if self._rgba then + local need = s.w * s.h * 4 + local px = self._pixels + if px == nil or buffer.len(px) ~= need then + px = buffer.create(need) + self._pixels = px + end + core.toRgba(s, px :: buffer) + pixels = px + end + self._count += 1 + return { + width = s.w, + height = s.h, + pixels = pixels, + pictureType = s.ptype, + temporalReference = s.tref, + index = self._count, + tag = s.tag, + y = s.y, + cb = s.cb, + cr = s.cr, + codedWidth = s.cw, + } +end + +local function sync(self: Decoder) + local st = self._core.state + self.width = st.width + self.height = st.height + self.frameRate = st.frameRate + self.bitRate = st.bitRate + self.stats.pictures = st.pictures + self.stats.errors = st.errors + self.stats.skipped = st.skipped +end + +-- a decoded picture -> the frame to return now (nil while reordering holds it) +local function handle(self: Decoder, s: D.Store): Frame? + if not self._reorder or s.ptype == D.PICTURE_B then + return emit(self, s) + end + local prev = self._held + self._held = s + if prev then + return emit(self, prev) + end + return nil +end + +local function run(self: Decoder, atEnd: boolean, tag: any): Frame? + local core = self._core + while true do + local s, needData = core.nextPicture(atEnd, tag) + sync(self) + if s then + local f = handle(self, s) + if f then + return f + end + elseif needData then + return nil + end + end +end + +local function append(self: Decoder, data: any, offset: number?, len: number?): boolean + local src: buffer + if type(data) == "string" then + src = buffer.fromstring(data) + elseif type(data) == "buffer" then + src = data + else + return false + end + local total = buffer.len(src) + local off = math.floor(tonumber(offset) or 0) + if off < 0 or off > total then + return false + end + local n = math.floor(tonumber(len) or (total - off)) + if n < 0 or off + n > total then + return false + end + self._core.write(src, off, n) + return true +end + +-- Appends elementary-stream bytes (buffer or string; offset / len select a part). False for a bad argument. +function Decoder.write(self: Decoder, data: buffer | string, offset: number?, len: number?): boolean + return append(self, data, offset, len) +end + +-- The next complete picture of the written stream as a frame, or nil when more data is needed (a picture is +-- complete once the next picture / sequence / GOP start code has been written; flush() ends the last one). +function Decoder.decodeFrame(self: Decoder): Frame? + return run(self, false, nil) +end + +-- Decodes one access unit (a picture, optionally preceded by sequence / GOP headers: a TS video unit's data). +-- The end of the data ends the picture. tag (any value, e.g. the unit's pts) comes back as frame.tag. +function Decoder.decode(self: Decoder, data: buffer | string, offset: number?, len: number?, tag: any): Frame? + if not append(self, data, offset, len) then + return nil + end + return run(self, true, tag) +end + +-- At the end of the stream: decodes what is left of the written data, then returns the reference picture held +-- for reordering. Call until it returns nil. +function Decoder.flush(self: Decoder): Frame? + local f = run(self, true, nil) + if f then + return f + end + local held = self._held + if held then + self._held = nil + return emit(self, held) + end + return nil +end + +-- Forgets buffered data and references (after a seek: the next picture decoded is the next I-picture). +function Decoder.reset(self: Decoder) + self._core.reset() + self._held = nil +end + +-- frameImage(frame, rgba?) -> Types.Image: a copy of a decoded frame (the decoder reuses its planes), cropped to +-- width x height: yuv420p from frame.y / cb / cr (BT.601 limited range, meta.source.range = "limited"), or rgba8 +-- (the decoder's BT.601 conversion) when rgba is true. nil for a value that is not a Frame. +function Mpeg1.frameImage(frame: Frame, rgba: boolean?): Types.Image? + if type(frame) ~= "table" or type(frame.y) ~= "buffer" or type(frame.cb) ~= "buffer" or type(frame.cr) ~= "buffer" then + return nil + end + local w, h, cw = frame.width, frame.height, frame.codedWidth + if type(w) ~= "number" or type(h) ~= "number" or type(cw) ~= "number" or w < 1 or h < 1 or cw < w then + return nil + end + local chw, ow, oh = cw // 2, (w + 1) // 2, (h + 1) // 2 + if buffer.len(frame.y) < cw * h or buffer.len(frame.cb) < chw * oh or buffer.len(frame.cr) < chw * oh then + return nil + end + local img + if rgba then + img = Types.Image.new(w, h) + D.toRgba(frame.y, frame.cb, frame.cr, cw, w, h, img.pixels) + else + img = Types.Image.new(w, h, "yuv420p") + local px = img.pixels + for y = 0, h - 1 do + buffer.copy(px, y * w, frame.y, y * cw, w) + end + local o = w * h + for y = 0, oh - 1 do + buffer.copy(px, o + y * ow, frame.cb, y * chw, ow) + buffer.copy(px, o + ow * oh + y * ow, frame.cr, y * chw, ow) + end + end + img.meta.source = { + format = "mpeg1", + pictureType = frame.pictureType, + temporalReference = frame.temporalReference, + range = if rgba then nil else "limited", + } + return img +end + +return Mpeg1 diff --git a/src/Formats/codecs/Pcm/Convert.luau b/src/Formats/codecs/Pcm/Convert.luau new file mode 100644 index 0000000..5d88d6e --- /dev/null +++ b/src/Formats/codecs/Pcm/Convert.luau @@ -0,0 +1,308 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Pcm/Convert: raw sample formats <-> interleaved f32 (the hot loops of codecs/Pcm). Integers map to +-- v / 2^(bits-1) (as ffmpeg does); encoding rounds to nearest and clips. G.711 A-law / mu-law per ITU-T G.711 (the +-- classic Sun g711.c algorithm, written from the spec). +-- +-- Formats: u8 s8 s16le s16be s24le s24be s32le s32be f32le f32be f64le f64be alaw ulaw (u8: offset binary). +-- Never throws: callers check ranges (Convert.SIZE[fmt] * count bytes) before calling. +local Convert = {} + +local readu8, readi8, readi16, readi32, readu32 = buffer.readu8, buffer.readi8, buffer.readi16, buffer.readi32, buffer.readu32 +local readf32, readf64, writef32, writef64 = buffer.readf32, buffer.readf64, buffer.writef32, buffer.writef64 +local writeu8, writeu16, writeu32, writei16, writei32 = buffer.writeu8, buffer.writeu16, buffer.writeu32, buffer.writei16, buffer.writei32 +local floor = math.floor +local byteswap = bit32.byteswap + +local SIZE: { [string]: number } = { + u8 = 1, + s8 = 1, + s16le = 2, + s16be = 2, + s24le = 3, + s24be = 3, + s32le = 4, + s32be = 4, + f32le = 4, + f32be = 4, + f64le = 8, + f64be = 8, + alaw = 1, + ulaw = 1, +} +Convert.SIZE = SIZE +-- the integer bit depth of each format (float: 32 / 64; G.711: 16 after expansion) +Convert.BITS = { + u8 = 8, + s8 = 8, + s16le = 16, + s16be = 16, + s24le = 24, + s24be = 24, + s32le = 32, + s32be = 32, + f32le = 32, + f32be = 32, + f64le = 64, + f64be = 64, + alaw = 16, + ulaw = 16, +} + +-- ------------------------------------------------------------------------------------------------ G.711 +local ALAW = table.create(256, 0) -- code -> linear s16 +local ULAW = table.create(256, 0) +for code = 0, 255 do + -- A-law + local a = bit32.bxor(code, 0x55) + local t = bit32.band(a, 0x0F) * 16 + local seg = bit32.rshift(bit32.band(a, 0x70), 4) + if seg == 0 then + t += 8 + elseif seg == 1 then + t += 0x108 + else + t = (t + 0x108) * 2 ^ (seg - 1) + end + ALAW[code + 1] = if bit32.band(a, 0x80) ~= 0 then t else -t + -- mu-law + local u = bit32.bxor(code, 0xFF) + local m = (bit32.band(u, 0x0F) * 8 + 0x84) * 2 ^ bit32.rshift(bit32.band(u, 0x70), 4) + ULAW[code + 1] = if bit32.band(u, 0x80) ~= 0 then 0x84 - m else m - 0x84 +end + +local SEG_AEND = { 0x1F, 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF } +local SEG_UEND = { 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF, 0x1FFF } +local function segment(v: number, ends: { number }): number + for i = 1, 8 do + if v <= ends[i] then + return i - 1 + end + end + return 8 +end + +-- linear s16 -> A-law code +local function alawEncode(pcm: number): number + local mask + local v = floor(pcm / 8) -- 13-bit magnitude domain + if v >= 0 then + mask = 0xD5 + else + mask = 0x55 + v = -v - 1 + end + local seg = segment(v, SEG_AEND) + local aval + if seg >= 8 then + aval = 0x7F + else + aval = seg * 16 + if seg < 2 then + aval += bit32.band(floor(v / 2), 0x0F) + else + aval += bit32.band(floor(v / 2 ^ seg), 0x0F) + end + end + return bit32.bxor(aval, mask) +end + +-- linear s16 -> mu-law code +local function ulawEncode(pcm: number): number + local v = floor(pcm / 4) -- 14-bit + local mask + if v < 0 then + v = -v + mask = 0x7F + else + mask = 0xFF + end + if v > 8159 then + v = 8159 + end + v += 0x21 + local seg = segment(v, SEG_UEND) + local uval + if seg >= 8 then + uval = 0x7F + else + uval = seg * 16 + bit32.band(floor(v / 2 ^ (seg + 1)), 0x0F) + end + return bit32.bxor(uval, mask) +end +Convert.alawEncode = alawEncode +Convert.ulawEncode = ulawEncode +Convert.ALAW = ALAW +Convert.ULAW = ULAW + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(src, so, fmt, count, dst, do_) -> true | false (unknown fmt): count samples at src[so] -> f32 at dst[do_] +function Convert.decode(src: buffer, so: number, fmt: string, count: number, dst: buffer, d: number): boolean + if fmt == "s16le" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, readi16(src, so + i * 2) / 32768) + end + elseif fmt == "s16be" then + for i = 0, count - 1 do + local p = so + i * 2 + local v = readu8(src, p) * 256 + readu8(src, p + 1) + if v >= 32768 then + v -= 65536 + end + writef32(dst, d + i * 4, v / 32768) + end + elseif fmt == "u8" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, (readu8(src, so + i) - 128) / 128) + end + elseif fmt == "s8" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, readi8(src, so + i) / 128) + end + elseif fmt == "s24le" then + for i = 0, count - 1 do + local p = so + i * 3 + local v = readu8(src, p) + readu8(src, p + 1) * 256 + readi8(src, p + 2) * 65536 + writef32(dst, d + i * 4, v / 8388608) + end + elseif fmt == "s24be" then + for i = 0, count - 1 do + local p = so + i * 3 + local v = readi8(src, p) * 65536 + readu8(src, p + 1) * 256 + readu8(src, p + 2) + writef32(dst, d + i * 4, v / 8388608) + end + elseif fmt == "s32le" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, readi32(src, so + i * 4) / 2147483648) + end + elseif fmt == "s32be" then + for i = 0, count - 1 do + local v = byteswap(readu32(src, so + i * 4)) + if v >= 2147483648 then + v -= 4294967296 + end + writef32(dst, d + i * 4, v / 2147483648) + end + elseif fmt == "f32le" then + buffer.copy(dst, d, src, so, count * 4) + elseif fmt == "f32be" then + for i = 0, count - 1 do + writeu32(dst, d + i * 4, byteswap(readu32(src, so + i * 4))) + end + elseif fmt == "f64le" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, readf64(src, so + i * 8)) + end + elseif fmt == "f64be" then + local tmp = buffer.create(8) + for i = 0, count - 1 do + local p = so + i * 8 + writeu32(tmp, 0, byteswap(readu32(src, p + 4))) + writeu32(tmp, 4, byteswap(readu32(src, p))) + writef32(dst, d + i * 4, readf64(tmp, 0)) + end + elseif fmt == "alaw" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, ALAW[readu8(src, so + i) + 1] / 32768) + end + elseif fmt == "ulaw" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, ULAW[readu8(src, so + i) + 1] / 32768) + end + else + return false + end + return true +end + +-- ------------------------------------------------------------------------------------------------ encode +local function q(x: number, s: number): number + local v = floor(x * s + 0.5) + if v ~= v then + return 0 + end + if v >= s then + return s - 1 + elseif v < -s then + return -s + end + return v +end + +-- encode(src, so, count, fmt, dst, do_) -> true | false: count f32 samples at src[so] -> fmt at dst[do_] +function Convert.encode(src: buffer, so: number, count: number, fmt: string, dst: buffer, d: number): boolean + if fmt == "s16le" then + for i = 0, count - 1 do + writei16(dst, d + i * 2, q(readf32(src, so + i * 4), 32768)) + end + elseif fmt == "s16be" then + for i = 0, count - 1 do + local v = q(readf32(src, so + i * 4), 32768) % 65536 + writeu16(dst, d + i * 2, (v % 256) * 256 + v // 256) + end + elseif fmt == "u8" then + for i = 0, count - 1 do + writeu8(dst, d + i, q(readf32(src, so + i * 4), 128) + 128) + end + elseif fmt == "s8" then + for i = 0, count - 1 do + writeu8(dst, d + i, q(readf32(src, so + i * 4), 128) % 256) + end + elseif fmt == "s24le" then + for i = 0, count - 1 do + local v = q(readf32(src, so + i * 4), 8388608) % 16777216 + local p = d + i * 3 + writeu8(dst, p, v % 256) + writeu8(dst, p + 1, (v // 256) % 256) + writeu8(dst, p + 2, v // 65536) + end + elseif fmt == "s24be" then + for i = 0, count - 1 do + local v = q(readf32(src, so + i * 4), 8388608) % 16777216 + local p = d + i * 3 + writeu8(dst, p, v // 65536) + writeu8(dst, p + 1, (v // 256) % 256) + writeu8(dst, p + 2, v % 256) + end + elseif fmt == "s32le" then + for i = 0, count - 1 do + writei32(dst, d + i * 4, q(readf32(src, so + i * 4), 2147483648)) + end + elseif fmt == "s32be" then + for i = 0, count - 1 do + writeu32(dst, d + i * 4, byteswap(q(readf32(src, so + i * 4), 2147483648) % 4294967296)) + end + elseif fmt == "f32le" then + buffer.copy(dst, d, src, so, count * 4) + elseif fmt == "f32be" then + for i = 0, count - 1 do + writeu32(dst, d + i * 4, byteswap(readu32(src, so + i * 4))) + end + elseif fmt == "f64le" then + for i = 0, count - 1 do + writef64(dst, d + i * 8, readf32(src, so + i * 4)) + end + elseif fmt == "f64be" then + local tmp = buffer.create(8) + for i = 0, count - 1 do + writef64(tmp, 0, readf32(src, so + i * 4)) + local p = d + i * 8 + writeu32(dst, p, byteswap(readu32(tmp, 4))) + writeu32(dst, p + 4, byteswap(readu32(tmp, 0))) + end + elseif fmt == "alaw" then + for i = 0, count - 1 do + writeu8(dst, d + i, alawEncode(q(readf32(src, so + i * 4), 32768))) + end + elseif fmt == "ulaw" then + for i = 0, count - 1 do + writeu8(dst, d + i, ulawEncode(q(readf32(src, so + i * 4), 32768))) + end + else + return false + end + return true +end + +return Convert diff --git a/src/Formats/codecs/Pcm/init.luau b/src/Formats/codecs/Pcm/init.luau new file mode 100644 index 0000000..8d60d05 --- /dev/null +++ b/src/Formats/codecs/Pcm/init.luau @@ -0,0 +1,234 @@ +--!strict +-- codecs/Pcm: PCM plumbing shared by audio formats: raw sample formats, streaming Decoders, encoder input sources. +-- An encoder accepts a Types.Audio (fully decoded) or a Types.Decoder (streamed); Pcm.source turns either into one +-- pull interface, so encoders stream in blocks without caring which they got. Uncompressed containers (aiff, au, +-- voc, ...) get their Decoder from Pcm.rawDecoder (over a sample region of the file) or Pcm.audioDecoder. +-- +-- local src, err = Pcm.source(audioOrDecoder) -- nil, Err.ARG for anything else +-- local buf, n = src:read(4096) -- interleaved f32, n frames (0 at the end), like Decoder:read +-- local audio = Pcm.collect(src) -- read everything into a Types.Audio +-- local dec = Pcm.rawDecoder(buf, offset, frames, channels, rate, "s16be", tags?) -- a Types.Decoder +-- local dec = Pcm.audioDecoder(audio) -- a Types.Decoder over a decoded Audio +-- local raw = Pcm.encode(src, "s24le", writer) -- every frame of src appended to a core/Bytes Writer +-- Pcm.Convert.decode / encode / SIZE / BITS -- the raw sample loops (codecs/Pcm/Convert) +-- local s16 = Pcm.toInt(x, 16) -- round, clip to [-32768, 32767] +-- local x = Pcm.fromInt(s16, 16) -- s / 32768 +-- +-- Sample formats: u8 s8 s16le s16be s24le s24be s32le s32be f32le f32be f64le f64be alaw ulaw. +-- Never throws (a decoder's read that throws is caught and ends the stream). +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Convert = require("@formats/codecs/Pcm/Convert") + +local Pcm = {} +Pcm.Convert = Convert + +export type Source = { + sampleRate: number, + channels: number, + frames: number, -- total frames, 0 = unknown (a streaming decoder without an index) + tags: Types.Tags, + -- read(n, out?) -> interleaved f32 buffer, frames read (0 at the end) + read: (self: Source, n: number, out: buffer?) -> (buffer, number), + err: Err.Err?, -- set when the underlying decoder failed mid-stream +} + +local function audioRead(self: any, n: number, out: buffer?): (buffer, number) + local a = self._audio + local ch = a.channels + local left = a.frames - self._pos + if n > left then + n = left + end + if n <= 0 then + return out or buffer.create(0), 0 + end + local bytes = n * ch * 4 + local b = if out and buffer.len(out) >= bytes then out else buffer.create(bytes) + buffer.copy(b, 0, a.samples, self._pos * ch * 4, bytes) + self._pos += n + return b, n +end + +local function decoderRead(self: any, n: number, out: buffer?): (buffer, number) + if self._done then + return out or buffer.create(0), 0 + end + local ok, b, got = pcall(self._dec.read, self._dec, n, out) + if not ok then + self._done = true + self.err = Err.new(Err.CORRUPT, "source decoder failed: " .. tostring(b)) + return out or buffer.create(0), 0 + end + if type(b) ~= "buffer" or type(got) ~= "number" or got <= 0 then + self._done = true + return out or buffer.create(0), 0 + end + local ch = self.channels + if buffer.len(b) < got * ch * 4 then + got = buffer.len(b) // (ch * 4) + end + return b, got +end + +-- source(v) -> Source | nil, Err.ARG: v is a Types.Audio or a Types.Decoder (anything with sampleRate, channels, read) +function Pcm.source(v: any): (Source?, Err.Err?) + if type(v) ~= "table" then + return nil, Err.new(Err.ARG, "needs an Audio or an audio Decoder") + end + local sr, ch = v.sampleRate, v.channels + if type(sr) ~= "number" or sr <= 0 or sr ~= sr or type(ch) ~= "number" or ch < 1 or ch ~= math.floor(ch) then + return nil, Err.new(Err.ARG, "bad sampleRate or channels") + end + if v.kind == "audio" and type(v.samples) == "buffer" then + local frames = v.frames + if type(frames) ~= "number" or frames < 0 or buffer.len(v.samples) < frames * ch * 4 then + return nil, Err.new(Err.ARG, "the Audio's samples buffer is shorter than frames * channels * 4") + end + return { sampleRate = sr, channels = ch, frames = frames, tags = v.tags or {}, read = audioRead, _audio = v, _pos = 0 } :: any, nil + end + if type(v.read) == "function" then + local frames = if type(v.frames) == "number" and v.frames > 0 then v.frames else 0 + return { sampleRate = sr, channels = ch, frames = frames, tags = v.tags or {}, read = decoderRead, _dec = v, _done = false } :: any, nil + end + return nil, Err.new(Err.ARG, "needs an Audio or an audio Decoder") +end + +-- collect(src, maxFrames?) -> Types.Audio | nil, Err (everything the source has; Err.LIMIT past maxFrames) +function Pcm.collect(src: Source, maxFrames: number?): (Types.Audio?, Err.Err?) + local ch = src.channels + local cap = math.max(src.frames, 4096) + local data = buffer.create(cap * ch * 4) + local total = 0 + local limit = maxFrames or 2 ^ 31 + local tmp: buffer? = nil + while true do + local b, n = src:read(16384, tmp) + if n <= 0 then + break + end + tmp = b + if total + n > limit then + return nil, Err.new(Err.LIMIT, string.format("more than %d frames", limit)) + end + if total + n > cap then + cap = math.max(cap * 2, total + n) + local nd = buffer.create(cap * ch * 4) + buffer.copy(nd, 0, data, 0, total * ch * 4) + data = nd + end + buffer.copy(data, total * ch * 4, b, 0, n * ch * 4) + total += n + end + if src.err then + return nil, src.err + end + local a = Types.Audio.new(src.sampleRate, ch, 0) + a.frames = total + if buffer.len(data) == total * ch * 4 then + a.samples = data + else + a.samples = buffer.create(total * ch * 4) + buffer.copy(a.samples, 0, data, 0, total * ch * 4) + end + a.tags = table.clone(src.tags) + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ decoders +-- rawDecoder(buf, offset, frames, channels, sampleRate, fmt, tags?) -> Types.Decoder | nil, Err.ARG: a streaming +-- decoder over frames * channels samples of fmt at buf[offset] (the caller has checked the range is inside buf) +function Pcm.rawDecoder(buf: buffer, offset: number, frames: number, channels: number, sampleRate: number, fmt: string, tags: Types.Tags?): (Types.Decoder?, Err.Err?) + local size = Convert.SIZE[fmt] + if not size then + return nil, Err.new(Err.ARG, "unknown sample format " .. tostring(fmt)) + end + if channels < 1 or sampleRate <= 0 or frames < 0 or offset < 0 or offset + frames * channels * size > buffer.len(buf) then + return nil, Err.new(Err.ARG, "bad raw PCM layout") + end + local pos = 0 + local frameBytes = channels * size + local dec = { + sampleRate = sampleRate, + channels = channels, + frames = frames, + duration = frames / sampleRate, + bitrate = sampleRate * frameBytes * 8, + tags = tags or {}, + } + function dec.read(_self: any, n: number, out: buffer?): (buffer, number) + n = math.clamp(math.floor(n), 0, frames - pos) + local bytes = n * channels * 4 + local b = if out and buffer.len(out) >= bytes then out else buffer.create(bytes) + if n > 0 then + Convert.decode(buf, offset + pos * frameBytes, fmt, n * channels, b, 0) + pos += n + end + return b, n + end + function dec.seek(_self: any, seconds: number) + local f = math.floor(seconds * sampleRate + 0.5) + pos = if f ~= f then 0 else math.clamp(f, 0, frames) + end + function dec.position(_self: any): number + return pos / sampleRate + end + return dec :: any, nil +end + +-- audioDecoder(audio) -> Types.Decoder over a decoded Audio (no copy of the samples) +function Pcm.audioDecoder(a: Types.Audio): Types.Decoder + local d = Pcm.rawDecoder(a.samples, 0, a.frames, a.channels, a.sampleRate, "f32le", a.tags) :: any + d.bitrate = a.sampleRate * a.channels * 32 + return d +end + +-- encode(src, fmt, w) -> frames written | nil, Err: drains src into the Writer w as fmt samples +function Pcm.encode(src: Source, fmt: string, w: Bytes.Writer): (number?, Err.Err?) + local size = Convert.SIZE[fmt] + if not size then + return nil, Err.new(Err.ARG, "unknown sample format " .. tostring(fmt)) + end + local ch = src.channels + local total = 0 + local tmp: buffer? = nil + while true do + local b, n = src:read(8192, tmp) + if n <= 0 then + break + end + tmp = b + local at = w:reserve(n * ch * size) + Convert.encode(b, 0, n * ch, fmt, w.buf, at) + w.pos = at + n * ch * size + total += n + end + if src.err then + return nil, src.err + end + return total, nil +end + +-- ------------------------------------------------------------------------------------------------ conversions +-- toInt(x, bits) -> the nearest bits-wide signed integer to x * 2^(bits-1), clipped (NaN -> 0) +function Pcm.toInt(x: number, bits: number): number + local s = 2 ^ (bits - 1) + local v = math.floor(x * s + 0.5) + if v ~= v then + return 0 + end + if v >= s then + return s - 1 + elseif v < -s then + return -s + end + return v +end + +-- fromInt(v, bits) -> v / 2^(bits-1) +function Pcm.fromInt(v: number, bits: number): number + return v / 2 ^ (bits - 1) +end + +return Pcm diff --git a/src/Formats/codecs/SoundFont/Fallback.luau b/src/Formats/codecs/SoundFont/Fallback.luau new file mode 100644 index 0000000..ae8f8ca --- /dev/null +++ b/src/Formats/codecs/SoundFont/Fallback.luau @@ -0,0 +1,149 @@ +--!strict +-- codecs/SoundFont/Fallback: the built-in General MIDI set used when no SoundFont is given. A generated SoundFont +-- (the same shape Parse returns, so the same synth plays it): single-cycle sine / triangle / square / saw waves and a +-- looped noise sample, one preset per GM family of 8 programs (piano, chromatic percussion, organ, guitar, bass, +-- strings, ensemble, brass, reed, pipe, lead, pad, synth fx, ethnic, percussive, sound fx) with family envelopes, +-- filters and vibrato, plus a drum kit on bank 128 (pitch-swept sine kicks and toms, filtered noise snares, hats with +-- an exclusive class, cymbals). Written for this library (no third-party code). +local Parse = require("@formats/codecs/SoundFont/Parse") + +local Fallback = {} + +local CYCLE = 256 +local NOISE = 32768 +local C4 = 261.6255653005986 + +local function hzToCents(hz: number): number + return 1200 * math.log(hz / 8.176, 2) +end + +local cached: any = nil + +-- build() -> a SoundFont value (kind "soundfont"); built once, shared (the synth never writes to it) +function Fallback.build(): any + if cached then + return cached + end + local waves = { "sine", "triangle", "square", "saw" } + local count = #waves * CYCLE + NOISE + local samples = buffer.create((count + 1) * 4) + local starts: { [string]: number } = {} + for w, name in waves do + local base = (w - 1) * CYCLE + starts[name] = base + for i = 0, CYCLE - 1 do + local ph = i / CYCLE + local v + if name == "sine" then + v = math.sin(2 * math.pi * ph) + elseif name == "triangle" then + v = if ph < 0.25 then 4 * ph elseif ph < 0.75 then 2 - 4 * ph else 4 * ph - 4 + elseif name == "square" then + v = if ph < 0.5 then 0.6 else -0.6 + else + v = (1 - 2 * ph) * 0.7 + end + buffer.writef32(samples, (base + i) * 4, v) + end + end + local noiseStart = #waves * CYCLE + starts.noise = noiseStart + local seed = 12345 + for i = 0, NOISE - 1 do + seed = (seed * 1103515245 + 12345) % 2147483648 + buffer.writef32(samples, (noiseStart + i) * 4, (seed / 1073741824 - 1) * 0.7) + end + + local function region(wave: string, fields: { [string]: number }): { [string]: number } + local r = Parse.defaultRegion() + local s = starts[wave] + r.offset = s + r.loopMode = 1 + r.loopStart = s + if wave == "noise" then + r.stop, r.loopEnd, r.sampleRate, r.keycenter = s + NOISE, s + NOISE - 1, 44100, 60 + else + r.stop, r.loopEnd, r.sampleRate, r.keycenter = s + CYCLE, s + CYCLE - 1, CYCLE * C4, 60 + end + r.aRelease = 0.08 + for k, v in fields do + r[k] = v + end + return r + end + + -- the 16 GM families: wave + envelope / filter / vibrato + local families: { { any } } = { + { "piano", "triangle", { aDecay = 2.5, aSustain = 0, aRelease = 0.25 } }, + { "chromatic", "sine", { aDecay = 1.2, aSustain = 0, aRelease = 0.3 } }, + { "organ", "square", { aAttack = 0.005, aRelease = 0.05, filterFc = hzToCents(5000) } }, + { "guitar", "saw", { aDecay = 1.5, aSustain = 0, aRelease = 0.15, filterFc = hzToCents(3000) } }, + { "bass", "triangle", { aDecay = 1.5, aSustain = 0.4, aRelease = 0.1 } }, + { "strings", "saw", { aAttack = 0.08, aRelease = 0.3, filterFc = hzToCents(4000), freqVibLFO = hzToCents(5.5), vibLfoToPitch = 8, delayVibLFO = 0.2 } }, + { "ensemble", "saw", { aAttack = 0.12, aRelease = 0.4, filterFc = hzToCents(3500), freqVibLFO = hzToCents(5), vibLfoToPitch = 10 } }, + { "brass", "saw", { aAttack = 0.03, aRelease = 0.12, filterFc = hzToCents(1200), mAttack = 0.05, mDecay = 0.3, mSustain = 0.4, modEnvToFilterFc = 2400 } }, + { "reed", "square", { aAttack = 0.02, aRelease = 0.08, filterFc = hzToCents(2500) } }, + { "pipe", "sine", { aAttack = 0.04, aRelease = 0.12, freqVibLFO = hzToCents(5), vibLfoToPitch = 12, delayVibLFO = 0.3 } }, + { "lead", "square", { aAttack = 0.005, aRelease = 0.1, filterFc = hzToCents(6000) } }, + { "pad", "saw", { aAttack = 0.4, aRelease = 0.8, filterFc = hzToCents(1800), freqModLFO = hzToCents(0.5), modLfoToFilterFc = 600 } }, + { "synthfx", "triangle", { aAttack = 0.2, aRelease = 1.0, freqModLFO = hzToCents(3), modLfoToVolume = 60 } }, + { "ethnic", "saw", { aDecay = 1.0, aSustain = 0, aRelease = 0.2, filterFc = hzToCents(3000) } }, + { "percussive", "sine", { aDecay = 0.4, aSustain = 0, aRelease = 0.1, mDecay = 0.1, mSustain = 0, modEnvToPitch = 1200 } }, + { "sfx", "noise", { aAttack = 0.05, aRelease = 0.5, filterFc = hzToCents(3000) } }, + } + local presets = {} + for program = 0, 127 do + local f = families[program // 8 + 1] + table.insert(presets, { name = "fallback " .. f[1], preset = program, bank = 0, regions = { region(f[2], f[3]) } }) + end + + -- the drum kit (bank 128, every program): one region per key + local kit = {} + -- fields.semis: the pitch (semitones from the sample's natural pitch) at keytrack 0 + local function drum(lo: number, hi: number, wave: string, fields: { [string]: number }) + local r = region(wave, fields) + r.lokey, r.hikey = lo, hi + r.sampleRate *= 2 ^ ((fields.semis or 0) / 12) + r.semis = nil :: any + table.insert(kit, r) + end + local sweep = { mDecay = 0.06, mSustain = 0, modEnvToPitch = 2400 } + local function with(a: { [string]: number }, b: { [string]: number }): { [string]: number } + local c = table.clone(a) + for k, v in b do + c[k] = v + end + return c + end + drum(0, 34, "noise", { aDecay = 0.1, aSustain = 0, keytrack = 0, filterFc = hzToCents(4000) }) + drum(35, 36, "sine", with(sweep, { aDecay = 0.35, aSustain = 0, aRelease = 0.05, keytrack = 0, semis = -26 })) + drum(37, 37, "noise", { aDecay = 0.05, aSustain = 0, keytrack = 0, filterFc = hzToCents(5000) }) + drum(38, 38, "noise", { aDecay = 0.2, aSustain = 0, keytrack = 0, filterFc = hzToCents(6000) }) + drum(39, 39, "noise", { aDecay = 0.15, aSustain = 0, keytrack = 0, filterFc = hzToCents(8000) }) + drum(40, 40, "noise", { aDecay = 0.18, aSustain = 0, keytrack = 0, filterFc = hzToCents(7000) }) + for _, k in { 41, 43, 45, 47, 48, 50 } do + drum(k, k, "sine", with(sweep, { aDecay = 0.4, aSustain = 0, semis = (k - 41) - 12, keytrack = 0 })) + end + drum(42, 42, "noise", { aDecay = 0.05, aSustain = 0, group = 1, keytrack = 0, semis = 12 }) + drum(44, 44, "noise", { aDecay = 0.08, aSustain = 0, group = 1, keytrack = 0, semis = 12 }) + drum(46, 46, "noise", { aDecay = 0.45, aSustain = 0, group = 1, keytrack = 0, semis = 12 }) + drum(49, 49, "noise", { aDecay = 1.5, aSustain = 0, keytrack = 0, semis = 7 }) + drum(51, 51, "noise", { aDecay = 1.0, aSustain = 0, keytrack = 0, semis = 10, filterFc = hzToCents(9000) }) + drum(52, 59, "noise", { aDecay = 1.2, aSustain = 0, keytrack = 0, semis = 5 }) + drum(60, 127, "noise", { aDecay = 0.12, aSustain = 0, keytrack = 30, filterFc = hzToCents(5000) }) + table.insert(presets, { name = "fallback drums", preset = 0, bank = 128, regions = kit }) + + cached = { + kind = "soundfont", + info = { name = "formats-luau fallback" }, + samples = samples, + sampleCount = count, + presets = presets, + sampleHeaders = {}, + instruments = {}, + meta = { source = { format = "fallback" } }, + } + return cached +end + +return Fallback diff --git a/src/Formats/codecs/SoundFont/Parse.luau b/src/Formats/codecs/SoundFont/Parse.luau new file mode 100644 index 0000000..90cdfcc --- /dev/null +++ b/src/Formats/codecs/SoundFont/Parse.luau @@ -0,0 +1,523 @@ +--!strict +-- codecs/SoundFont/Parse: SoundFont 2.0x (sfbk RIFF) reader. The INFO list, the sdta samples (smpl 16-bit, + sm24 +-- when present) as one f32 buffer, and the pdta "hydra" (phdr pbag pmod pgen inst ibag imod igen shdr), flattened +-- into playable regions per preset: the instrument global zone, the preset global zone and the preset zone's +-- generators merged the way TinySoundFont (tsf.h v0.9, MIT, (c) Bernhard Schelling; licenses/TinySoundFont-LICENSE.txt) +-- does (tsf_load_presets / tsf_region_operator / tsf_region_envtosecs), with every index and sample offset clamped +-- so the synth never reads outside the sample buffer. +-- Differences from tsf.h: initialAttenuation is cB * 0.04 dB (FluidSynth's EMU-compatible scale; tsf uses 0.01); +-- SF3 (Ogg samples) is not supported; modulators (pmod / imod) are read but not applied (as in tsf.h). +-- Never throws: a bad file returns nil, Err. +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") + +local Parse = {} + +-- a region (one sample zone of a preset), in "absolute" form: envelope / LFO times in seconds, sustain as a level +export type Region = { [string]: number } + +export type Preset = { name: string, preset: number, bank: number, regions: { Region } } + +export type SoundFont = { + kind: "soundfont", + info: { [string]: string }, + samples: buffer, -- f32 mono, sampleCount + 1 floats (a zero pad sample past the end) + sampleCount: number, + presets: { Preset }, -- sorted by bank, then preset number + sampleHeaders: { { [string]: any } }, + instruments: { { name: string, zones: number } }, + meta: { [string]: any }, +} + +local GEN_INSTRUMENT, GEN_SAMPLEID = 41, 53 + +-- generator op -> { field, mode, limit }. modes: f / i (value, merged by adding then clamping), a (sample address +-- add), a15 (coarse address add: * 32768), kr / vr (key / velocity range), loop, group, key (overriding root key) +local LIM12K5K = { 1, -12000, 5000 } +local LIM12K8K = { 1, -12000, 8000 } +local LIM1200 = { 1, -1200, 1200 } +local GEN: { [number]: { any } } = { + [0] = { "offset", "a" }, + [1] = { "stop", "a" }, + [2] = { "loopStart", "a" }, + [3] = { "loopEnd", "a" }, + [4] = { "offset", "a15" }, + [5] = { "modLfoToPitch", "i", { 1, -12000, 12000 } }, + [6] = { "vibLfoToPitch", "i", { 1, -12000, 12000 } }, + [7] = { "modEnvToPitch", "i", { 1, -12000, 12000 } }, + [8] = { "filterFc", "i", { 1, 1500, 13500 } }, + [9] = { "filterQ", "i", { 1, 0, 960 } }, + [10] = { "modLfoToFilterFc", "i", { 1, -12000, 12000 } }, + [11] = { "modEnvToFilterFc", "i", { 1, -12000, 12000 } }, + [12] = { "stop", "a15" }, + [13] = { "modLfoToVolume", "i", { 1, -960, 960 } }, + [17] = { "pan", "f", { 0.001, -0.5, 0.5 } }, + [21] = { "delayModLFO", "f", LIM12K5K }, + [22] = { "freqModLFO", "i", { 1, -16000, 4500 } }, + [23] = { "delayVibLFO", "f", LIM12K5K }, + [24] = { "freqVibLFO", "i", { 1, -16000, 4500 } }, + [25] = { "mDelay", "f", LIM12K5K }, + [26] = { "mAttack", "f", LIM12K8K }, + [27] = { "mHold", "f", LIM12K5K }, + [28] = { "mDecay", "f", LIM12K8K }, + [29] = { "mSustain", "f", { 1, 0, 1000 } }, + [30] = { "mRelease", "f", LIM12K8K }, + [31] = { "mKeyHold", "f", LIM1200 }, + [32] = { "mKeyDecay", "f", LIM1200 }, + [33] = { "aDelay", "f", LIM12K5K }, + [34] = { "aAttack", "f", LIM12K8K }, + [35] = { "aHold", "f", LIM12K5K }, + [36] = { "aDecay", "f", LIM12K8K }, + [37] = { "aSustain", "f", { 1, 0, 1440 } }, + [38] = { "aRelease", "f", LIM12K8K }, + [39] = { "aKeyHold", "f", LIM1200 }, + [40] = { "aKeyDecay", "f", LIM1200 }, + [43] = { "", "kr" }, + [44] = { "", "vr" }, + [45] = { "loopStart", "a15" }, + [48] = { "attenuation", "f", { 0.04, 0, 57.6 } }, + [50] = { "loopEnd", "a15" }, + [51] = { "transpose", "i" }, + [52] = { "tune", "i" }, + [54] = { "loopMode", "loop" }, + [56] = { "keytrack", "i" }, + [57] = { "group", "group" }, + [58] = { "keycenter", "key" }, +} +-- the merged fields: value generators once each (several ops share a field), then the four address fields +local MERGE: { { any } } = {} +do + local seen: { [string]: boolean } = {} + for op = 0, 58 do + local g = GEN[op] + if g and (g[2] == "f" or g[2] == "i" or g[2] == "a") and not seen[g[1]] then + seen[g[1]] = true + table.insert(MERGE, g) + end + end +end + +local FIELDS = { + "loopMode", "sampleRate", "lokey", "hikey", "lovel", "hivel", "group", "offset", "stop", "loopStart", "loopEnd", + "transpose", "tune", "keycenter", "keytrack", "attenuation", "pan", "filterQ", "filterFc", "modEnvToPitch", + "modEnvToFilterFc", "modLfoToFilterFc", "modLfoToVolume", "delayModLFO", "freqModLFO", "modLfoToPitch", + "delayVibLFO", "freqVibLFO", "vibLfoToPitch", "aDelay", "aAttack", "aHold", "aDecay", "aSustain", "aRelease", + "aKeyHold", "aKeyDecay", "mDelay", "mAttack", "mHold", "mDecay", "mSustain", "mRelease", "mKeyHold", "mKeyDecay", + "sampleIndex", +} + +-- clear(relative): tsf_region_clear. relative = a preset zone (all zero: values add to the instrument's) +local function clear(relative: boolean): Region + local r: Region = {} + for _, f in FIELDS do + r[f] = 0 + end + r.hikey, r.hivel, r.keycenter = 127, 127, 60 + if relative then + return r + end + r.keytrack = 100 + r.keycenter = -1 + for _, p in { "a", "m" } do + for _, s in { "Delay", "Attack", "Hold", "Decay", "Release" } do + r[p .. s] = -12000 + end + end + r.filterFc = 13500 + r.delayModLFO, r.delayVibLFO = -12000, -12000 + return r +end + +local function copy(r: Region): Region + local c: Region = {} + for k, v in r do + c[k] = v + end + return c +end + +-- the region defaults in absolute form (seconds, levels): what Fallback builds its regions from +function Parse.defaultRegion(): Region + local r = clear(false) + r.keycenter = 60 + for _, p in { "a", "m" } do + for _, s in { "Delay", "Attack", "Hold", "Decay", "Release" } do + r[p .. s] = 0 + end + end + r.aSustain, r.mSustain = 1, 1 + r.delayModLFO, r.delayVibLFO = 0, 0 + return r +end + +-- set one generator (tsf_region_operator with an amount); lo / hi = the two bytes, s = signed 16, w = unsigned 16 +local function operator(r: Region, op: number, lo: number, hi: number, s: number, w: number) + local g = GEN[op] + if not g then + return + end + local mode = g[2] + if mode == "f" or mode == "i" then + r[g[1]] = s + elseif mode == "a" then + r[g[1]] += s + elseif mode == "a15" then + r[g[1]] += s * 32768 + elseif mode == "kr" then + r.lokey, r.hikey = lo, hi + elseif mode == "vr" then + r.lovel, r.hivel = lo, hi + elseif mode == "loop" then + local m = w % 4 + r.loopMode = if m == 3 then 2 elseif m == 1 then 1 else 0 + elseif mode == "group" then + r.group = w + elseif mode == "key" then + r.keycenter = s + end +end + +-- merge(zone, preset): zone += preset, then clamp (tsf_region_operator without an amount) +local function merge(z: Region, p: Region) + for _, g in MERGE do + local f = g[1] + local v = z[f] + p[f] + local lim = g[3] + if lim then + v *= lim[1] + v = math.clamp(v, lim[2], lim[3]) + end + z[f] = v + end +end + +local function tc2s(tc: number): number + return 2 ^ (tc / 1200) +end + +-- envtosecs (tsf_region_envtosecs): timecents to seconds; hold / decay stay in timecents when they scale by key +local function envToSecs(r: Region, p: string, sustainIsGain: boolean) + for _, s in { "Delay", "Attack", "Release" } do + local v = r[p .. s] + r[p .. s] = if v < -11950 then 0 else tc2s(v) + end + if r[p .. "KeyHold"] == 0 then + local v = r[p .. "Hold"] + r[p .. "Hold"] = if v < -11950 then 0 else tc2s(v) + end + if r[p .. "KeyDecay"] == 0 then + local v = r[p .. "Decay"] + r[p .. "Decay"] = if v < -11950 then 0 else tc2s(v) + end + local sus = r[p .. "Sustain"] + if sus < 0 then + sus = 0 + elseif sustainIsGain then + sus = if -sus / 10 > -100 then 10 ^ (-sus / 10 * 0.05) else 0 + else + sus = 1 - sus / 1000 + end + r[p .. "Sustain"] = sus +end + +-- ------------------------------------------------------------------------------------------------ RIFF +type Hydra = { [string]: { { number } } } + +-- record layouts: field byte widths (2 / 4 = little endian unsigned, -2 signed, 20 = name, 1 = byte, -1 = signed byte) +local LAYOUT: { [string]: { number } } = { + phdr = { 20, 2, 2, 2, 4, 4, 4 }, + pbag = { 2, 2 }, + pmod = { 2, 2, -2, 2, 2 }, + pgen = { 2, 2 }, + inst = { 20, 2 }, + ibag = { 2, 2 }, + imod = { 2, 2, -2, 2, 2 }, + igen = { 2, 2 }, + shdr = { 20, 4, 4, 4, 4, 4, 1, -1, 2, 2 }, +} +local RECSIZE: { [string]: number } = { phdr = 38, pbag = 4, pmod = 10, pgen = 4, inst = 22, ibag = 4, imod = 10, igen = 4, shdr = 46 } + +local INFO_NAMES = { + isng = "engine", INAM = "name", irom = "rom", ICRD = "date", IENG = "author", IPRD = "product", + ICOP = "copyright", ICMT = "comment", ISFT = "software", +} + +export type Options = { maxRegions: number?, maxSamples: number? } + +-- parse(r, opts?) -> SoundFont | nil, Err +function Parse.parse(r: Bytes.Reader, opts: Options?): (SoundFont?, Err.Err?) + local maxRegions = opts and opts.maxRegions or 1000000 + local maxSamples = opts and opts.maxSamples or 2 ^ 28 + if r:string(4) ~= "RIFF" then + return r:fail(Err.CORRUPT, "not a RIFF file") + end + local riffSize = r:u32le() + if r:string(4) ~= "sfbk" then + return r:fail(Err.CORRUPT, "not a SoundFont (no sfbk)") + end + if r.err then + return nil, r.err + end + local body = r:sub(12, math.max(0, riffSize - 4)) + local info: { [string]: string } = {} + local hydra: Hydra = {} + local smpl: Bytes.Reader? = nil + local sm24: Bytes.Reader? = nil + local version = "" + while body:remaining() >= 8 do + local id, size = body:string(4), body:u32le() + local chunk = body:slice(size) + if size % 2 == 1 and body:remaining() > 0 then + body:skip(1) + end + if id == "LIST" and chunk:remaining() >= 4 then + local kind = chunk:string(4) + while chunk:remaining() >= 8 do + local sid, ssize = chunk:string(4), chunk:u32le() + local sub = chunk:slice(ssize) + if ssize % 2 == 1 and chunk:remaining() > 0 then + chunk:skip(1) + end + if kind == "INFO" then + if sid == "ifil" and sub:remaining() >= 4 then + local major, minor = sub:u16le(), sub:u16le() + version = string.format("%d.%02d", major, minor) + elseif INFO_NAMES[sid] then + info[INFO_NAMES[sid]] = sub:fixed(sub:remaining()) + end + elseif kind == "sdta" then + if sid == "smpl" and not smpl then + smpl = sub + elseif sid == "sm24" then + sm24 = sub + end + elseif kind == "pdta" then + local layout = LAYOUT[sid] + if layout and not hydra[sid] then + local rs = RECSIZE[sid] + local n = sub:remaining() // rs + local recs: { { number } } = table.create(n) + for i = 1, n do + local rec = {} + for _, w in layout do + if w == 20 then + table.insert(rec, 0) -- the name is read separately + sub:skip(20) + elseif w == 4 then + table.insert(rec, sub:u32le()) + elseif w == 2 then + table.insert(rec, sub:u16le()) + elseif w == -2 then + table.insert(rec, sub:i16le()) + elseif w == 1 then + table.insert(rec, sub:u8()) + else + table.insert(rec, sub:i8()) + end + end + recs[i] = rec + end + hydra[sid] = recs + if sid == "phdr" or sid == "inst" or sid == "shdr" then + local names = table.create(n) + for i = 0, n - 1 do + names[i + 1] = sub:sub(i * rs, 20):fixed(20) + end + hydra[sid .. "Names"] = names :: any + end + end + end + end + end + end + if not smpl then + return nil, Err.new(Err.CORRUPT, "no sample data (sdta smpl)") + end + for _, k in { "phdr", "pbag", "pgen", "inst", "ibag", "igen", "shdr" } do + if not hydra[k] or #hydra[k] == 0 then + return nil, Err.new(Err.CORRUPT, "incomplete hydra: no " .. k .. " records") + end + end + -- samples + local sr = smpl :: Bytes.Reader + local count = sr:remaining() // 2 + if count > maxSamples then + return nil, Err.new(Err.LIMIT, string.format("%d samples is over the %d sample limit", count, maxSamples)) + end + local samples = buffer.create((count + 1) * 4) + do + local b, p = sr.buf, sr.pos + local readi16, writef32 = buffer.readi16, buffer.writef32 + local s24 = sm24 + if s24 and s24:remaining() >= count then + local q = s24.pos + local readu8 = buffer.readu8 + for i = 0, count - 1 do + writef32(samples, i * 4, (readi16(b, p + i * 2) * 256 + readu8(s24.buf, q + i)) / 8388607) + end + else + s24 = nil + for i = 0, count - 1 do + writef32(samples, i * 4, readi16(b, p + i * 2) / 32767) + end + end + sm24 = s24 + end + -- presets (tsf_load_presets) + local phdr, pbag, pgen = hydra.phdr, hydra.pbag, hydra.pgen + local inst, ibag, igen, shdr = hydra.inst, hydra.ibag, hydra.igen, hydra.shdr + local phdrNames, instNames, shdrNames = (hydra :: any).phdrNames, (hydra :: any).instNames, (hydra :: any).shdrNames + local nInst = #inst - 1 -- the last record of each list is the terminal one + local nShdr = #shdr - 1 + local function range(list: { { number } }, i: number, field: number, limit: number): (number, number) + -- [list[i][field], list[i + 1][field]) clamped to [1, limit] (1-based record indexes) + local a = list[i][field] + 1 + local b = if list[i + 1] then list[i + 1][field] + 1 else a + return math.max(1, a), math.min(b, limit + 1) + end + local presets: { Preset } = {} + local regionTotal = 0 + for pi = 1, #phdr - 1 do + local ph = phdr[pi] + local preset: Preset = { name = phdrNames[pi], preset = ph[2], bank = ph[3], regions = {} } + local globalRegion = clear(true) + local b0, b1 = range(phdr, pi, 4, #pbag) + for bi = b0, b1 - 1 do + local presetRegion = copy(globalRegion) + local hadInstrument = false + local g0, g1 = range(pbag, bi, 1, #pgen) + for gi = g0, g1 - 1 do + local pg = pgen[gi] + local op, amount = pg[1], pg[2] + local lo, hi = amount % 256, amount // 256 + local s = if amount >= 32768 then amount - 65536 else amount + if op == GEN_INSTRUMENT then + hadInstrument = true + if amount < nInst then + local instRegion = clear(false) + local ib0, ib1 = range(inst, amount + 1, 2, #ibag) + for ibi = ib0, ib1 - 1 do + local zone = copy(instRegion) + local hadSample = false + local ig0, ig1 = range(ibag, ibi, 1, #igen) + for igi = ig0, ig1 - 1 do + local ig = igen[igi] + local iop, iamt = ig[1], ig[2] + if iop == GEN_SAMPLEID then + hadSample = true + if iamt >= nShdr then + break + end + local ok = not (zone.hikey < presetRegion.lokey or zone.lokey > presetRegion.hikey) + and not (zone.hivel < presetRegion.lovel or zone.lovel > presetRegion.hivel) + if ok then + local z = copy(zone) + z.lokey = math.max(z.lokey, presetRegion.lokey) + z.hikey = math.min(z.hikey, presetRegion.hikey) + z.lovel = math.max(z.lovel, presetRegion.lovel) + z.hivel = math.min(z.hivel, presetRegion.hivel) + merge(z, presetRegion) + envToSecs(z, "a", true) + envToSecs(z, "m", false) + z.delayModLFO = if z.delayModLFO < -11950 then 0 else tc2s(z.delayModLFO) + z.delayVibLFO = if z.delayVibLFO < -11950 then 0 else tc2s(z.delayVibLFO) + local sh = shdr[iamt + 1] + local sStart, sEnd, sLoopStart, sLoopEnd = sh[2], sh[3], sh[4], sh[5] + z.offset = math.clamp(z.offset + sStart, 0, count) + local stop = z.stop + sEnd + if stop > 0 and stop < count then + stop += 1 + else + stop = count + end + z.stop = math.clamp(stop, 0, count) + z.loopStart = math.clamp(z.loopStart + sLoopStart, 0, count) + local le = z.loopEnd + sLoopEnd + if sLoopEnd > 0 then + le -= 1 + end + z.loopEnd = math.clamp(le, 0, count) + if z.keycenter == -1 then + z.keycenter = sh[7] + end + z.tune += sh[8] + z.sampleRate = sh[6] + z.sampleIndex = iamt + regionTotal += 1 + if regionTotal > maxRegions then + return nil, Err.new(Err.LIMIT, "over " .. maxRegions .. " regions") + end + table.insert(preset.regions, z) + end + break -- sampleID ends a zone's generator list + else + local ilo, ihi = iamt % 256, iamt // 256 + operator(zone, iop, ilo, ihi, if iamt >= 32768 then iamt - 65536 else iamt, iamt) + end + end + if ibi == ib0 and not hadSample then + instRegion = zone -- the instrument's global zone + end + end + end + break -- instrument ends a preset zone's generator list + else + operator(presetRegion, op, lo, hi, s, amount) + end + end + if bi == b0 and not hadInstrument then + globalRegion = presetRegion -- the preset's global zone + end + end + table.insert(presets, preset) + end + -- sorted by bank, then preset, then file order (tsf's sortedIndex) + for i, p in presets do + (p :: any)._order = i + end + table.sort(presets, function(a: Preset, b: Preset): boolean + if a.bank ~= b.bank then + return a.bank < b.bank + end + if a.preset ~= b.preset then + return a.preset < b.preset + end + return (a :: any)._order < (b :: any)._order + end) + for _, p in presets do + (p :: any)._order = nil + end + local headers: { { [string]: any } } = table.create(nShdr) + for i = 1, nShdr do + local sh = shdr[i] + headers[i] = { + name = shdrNames[i], + start = sh[2], + stop = sh[3], + loopStart = sh[4], + loopEnd = sh[5], + sampleRate = sh[6], + originalPitch = sh[7], + pitchCorrection = sh[8], + link = sh[9], + type = sh[10], + } + end + local instruments: { { name: string, zones: number } } = table.create(nInst) + for i = 1, nInst do + instruments[i] = { name = instNames[i], zones = math.max(0, (inst[i + 1][2] or 0) - inst[i][2]) } + end + local sf: SoundFont = { + kind = "soundfont", + info = info, + samples = samples, + sampleCount = count, + presets = presets, + sampleHeaders = headers, + instruments = instruments, + meta = { source = { format = "sf2", version = version, sm24 = sm24 ~= nil } }, + } + return sf, nil +end + +return Parse diff --git a/src/Formats/codecs/SoundFont/Synth.luau b/src/Formats/codecs/SoundFont/Synth.luau new file mode 100644 index 0000000..c133423 --- /dev/null +++ b/src/Formats/codecs/SoundFont/Synth.luau @@ -0,0 +1,803 @@ +--!strict +--!native +-- codecs/SoundFont/Synth: a SoundFont 2 sample synthesizer with MIDI channels. A port of TinySoundFont (tsf.h v0.9, +-- MIT, (c) 2017-2025 Bernhard Schelling, based on SFZero (c) 2012 Steve Folta; licenses/TinySoundFont-LICENSE.txt): +-- voices with the DAHDSR volume envelope (exponential decay / release), the modulation envelope to pitch and filter +-- cutoff, the modulation and vibrato LFOs (triangle) to pitch / filter / volume, a resonant biquad low-pass, linear +-- interpolation, loop modes (none / continuous / until release), 3 dB pan law, exclusive classes; channels with +-- program / bank select (CC0 / CC32), drums (bank 128), pitch bend with RPN 0 range and RPN 1 / 2 tuning, CC7 volume, +-- CC10 pan, CC11 expression, CC64 sustain, CC120 / 121 / 123. Effects (reverb, chorus) and modulators are not +-- implemented (as in tsf.h). Output: interleaved stereo f32, mixed into the caller's buffer. +-- Differences from tsf.h: the envelope gain is ramped across each 64-sample block (tsf.h steps it); a voice limit (oldest release voice stolen, else the note is dropped), channels 0..15 only. +-- Native, never throws: every buffer index is in range by construction (the regions are clamped by Parse / Fallback, +-- the sample buffer has a zero pad sample, the output range is checked before mixing). +local Synth = {} + +local readf32, writef32, blen = buffer.readf32, buffer.writef32, buffer.len +local exp, log, sqrt, tan, floor = math.exp, math.log, math.sqrt, math.tan, math.floor + +local NONE, DELAY, ATTACK, HOLD, DECAY, SUSTAIN, RELEASE, DONE = 0, 1, 2, 3, 4, 5, 6, 7 +local BLOCK = 64 -- TSF_RENDER_EFFECTSAMPLEBLOCK: envelopes / LFOs / filter cutoff update per block +local FASTRELEASE = 0.01 +local PI = math.pi +local LOOP_NONE, LOOP_SUSTAIN = 0, 2 + +type Env = { + segment: number, + isExp: boolean, + isAmp: boolean, + vel: number, + level: number, + slope: number, + untilNext: number, + delay: number, + attack: number, + hold: number, + decay: number, + sustain: number, + release: number, +} +type Lfo = { untilStart: number, level: number, delta: number } +export type Voice = { + preset: number, -- 1-based preset index, -1 = idle + key: number, + channel: number, + held: boolean, -- note off while sustain was down + region: { [string]: number }, + pitchIn: number, -- timecents + pitchOut: number, + pos: number, + gainDB: number, + panL: number, + panR: number, + playIndex: number, + loopStart: number, + loopEnd: number, + amp: Env, + mod: Env, + lpActive: boolean, + qinv: number, + a0: number, + a1: number, + b1: number, + b2: number, + z1: number, + z2: number, + modlfo: Lfo, + viblfo: Lfo, +} +export type Channel = { + preset: number, + bank: number, + pitchWheel: number, + midiPan: number, + midiVolume: number, + midiExpression: number, + midiRPN: number, + midiData: number, + sustain: boolean, + panOffset: number, + gainDB: number, + pitchRange: number, + tuning: number, +} +export type State = { + presets: { { regions: { { [string]: number } }, preset: number, bank: number } }, + lookup: { [number]: number }, -- bank * 128 + preset -> preset index + samples: buffer, + rate: number, + gainDB: number, + voices: { Voice }, + maxVoices: number, + playIndex: number, + channels: { Channel }, -- [1..16] = MIDI channels 0..15 +} + +local function tc2s(tc: number): number + return 2 ^ (tc / 1200) +end +local function cents2Hz(c: number): number + return 8.176 * 2 ^ (c / 1200) +end +local function db2gain(db: number): number + return if db > -100 then 10 ^ (db * 0.05) else 0 +end +local function gain2db(g: number): number + return if g <= 0.00001 then -100 else 20 * math.log10(g) +end + +-- ------------------------------------------------------------------------------------------------ envelope +local function releaseSamples(e: Env, rate: number): number + return floor((if e.release <= 0 then FASTRELEASE else e.release) * rate) +end + +local function nextSegment(e: Env, active: number, rate: number) + local seg = active + if seg == NONE then + e.untilNext = floor(e.delay * rate) + if e.untilNext > 0 then + e.segment, e.isExp, e.level, e.slope = DELAY, false, 0, 0 + return + end + seg = DELAY + end + if seg == DELAY then + e.untilNext = floor(e.attack * rate) + if e.untilNext > 0 then + if not e.isAmp then + -- the mod env attack scales with velocity (1 = full duration, 127 = 0.125 x) + e.untilNext = floor(e.attack * ((145 - e.vel) / 144) * rate) + end + e.segment, e.isExp, e.level = ATTACK, false, 0 + e.slope = if e.untilNext > 0 then 1 / e.untilNext else 1 + return + end + seg = ATTACK + end + if seg == ATTACK then + e.untilNext = floor(e.hold * rate) + if e.untilNext > 0 then + e.segment, e.isExp, e.level, e.slope = HOLD, false, 1, 0 + return + end + seg = HOLD + end + if seg == HOLD then + e.untilNext = floor(e.decay * rate) + if e.untilNext > 0 then + e.segment, e.level = DECAY, 1 + if e.isAmp then + local mystery = -9.226 / e.untilNext -- LinuxSampler's decay curve (as tsf.h) + e.slope = exp(mystery) + e.isExp = true + if e.sustain > 0 then + e.untilNext = floor(log(e.sustain) / mystery) + end + else + e.slope = -1 / e.untilNext + e.untilNext = floor(e.decay * (1 - e.sustain) * rate) + e.isExp = false + end + return + end + seg = DECAY + end + if seg == DECAY then + e.segment, e.level, e.slope, e.untilNext, e.isExp = SUSTAIN, e.sustain, 0, 0x7FFFFFFF, false + return + end + if seg == SUSTAIN then + e.segment = RELEASE + e.untilNext = math.max(1, releaseSamples(e, rate)) + if e.isAmp then + e.slope = exp(-9.226 / e.untilNext) + e.isExp = true + else + e.slope = -e.level / e.untilNext + e.isExp = false + end + return + end + e.segment, e.isExp, e.level, e.slope, e.untilNext = DONE, false, 0, 0, 0x7FFFFFF +end + +local function envSetup(e: Env, r: { [string]: number }, p: string, key: number, vel: number, isAmp: boolean, rate: number) + e.delay, e.attack, e.hold, e.decay = r[p .. "Delay"], r[p .. "Attack"], r[p .. "Hold"], r[p .. "Decay"] + e.sustain, e.release = r[p .. "Sustain"], r[p .. "Release"] + local kh, kd = r[p .. "KeyHold"], r[p .. "KeyDecay"] + if kh ~= 0 then + local h = e.hold + kh * (60 - key) + e.hold = if h < -10000 then 0 else tc2s(h) + end + if kd ~= 0 then + local d = e.decay + kd * (60 - key) + e.decay = if d < -10000 then 0 else tc2s(d) + end + e.vel, e.isAmp = vel, isAmp + nextSegment(e, NONE, rate) +end + +local function envProcess(e: Env, n: number, rate: number) + local slope = e.slope + if slope ~= 0 then + if e.isExp then + e.level *= slope ^ n + else + e.level += slope * n + end + end + e.untilNext -= n + if e.untilNext <= 0 then + nextSegment(e, e.segment, rate) + end +end + +local function newEnv(): Env + return { segment = DONE, isExp = false, isAmp = false, vel = 0, level = 0, slope = 0, untilNext = 0, delay = 0, attack = 0, hold = 0, decay = 0, sustain = 0, release = 0 } +end + +-- ------------------------------------------------------------------------------------------------ filter / lfo +local function lowpassSetup(v: Voice, fc: number) + -- the biquad from earlevel.com (as tsf.h) + local k = tan(PI * fc) + local kk = k * k + local norm = 1 / (1 + k * v.qinv + kk) + v.a0 = kk * norm + v.a1 = 2 * v.a0 + v.b1 = 2 * (kk - 1) * norm + v.b2 = (1 - k * v.qinv + kk) * norm +end + +local function lfoSetup(l: Lfo, delay: number, freqCents: number, rate: number) + l.untilStart = floor(delay * rate) + l.delta = 4 * cents2Hz(freqCents) / rate + l.level = 0 +end + +local function lfoProcess(l: Lfo, n: number) + if l.untilStart > n then + l.untilStart -= n + return + end + l.level += l.delta * n + if l.level > 1 then + l.delta = -l.delta + l.level = 2 - l.level + elseif l.level < -1 then + l.delta = -l.delta + l.level = -2 - l.level + end +end + +-- ------------------------------------------------------------------------------------------------ voices +local function calcPitch(v: Voice, shift: number, rate: number) + local r = v.region + local note = v.key + r.transpose + r.tune / 100 + local adjusted = r.keycenter + (note - r.keycenter) * (r.keytrack / 100) + shift + v.pitchIn = adjusted * 100 + v.pitchOut = r.sampleRate / (tc2s(r.keycenter * 100) * rate) +end + +local function setPan(v: Voice, pan: number) + if pan <= -0.5 then + v.panL, v.panR = 1, 0 + elseif pan >= 0.5 then + v.panL, v.panR = 0, 1 + else + v.panL, v.panR = sqrt(0.5 - pan), sqrt(0.5 + pan) + end +end + +local function channelShift(c: Channel): number + return if c.pitchWheel == 8192 then c.tuning else (c.pitchWheel / 16383 * c.pitchRange * 2) - c.pitchRange + c.tuning +end + +local function voiceEnd(s: State, v: Voice) + nextSegment(v.amp, SUSTAIN, s.rate) + nextSegment(v.mod, SUSTAIN, s.rate) + if v.region.loopMode == LOOP_SUSTAIN then + v.loopEnd = v.loopStart -- keep playing, stop looping + end +end + +local function voiceEndQuick(s: State, v: Voice) + v.amp.release = 0 + nextSegment(v.amp, SUSTAIN, s.rate) + v.mod.release = 0 + nextSegment(v.mod, SUSTAIN, s.rate) +end + +local function newVoice(): Voice + return { + preset = -1, key = 0, channel = 0, held = false, region = {}, pitchIn = 0, pitchOut = 0, pos = 0, gainDB = 0, + panL = 0, panR = 0, playIndex = 0, loopStart = 0, loopEnd = 0, amp = newEnv(), mod = newEnv(), + lpActive = false, qinv = 0, a0 = 0, a1 = 0, b1 = 0, b2 = 0, z1 = 0, z2 = 0, + modlfo = { untilStart = 0, level = 0, delta = 0 }, viblfo = { untilStart = 0, level = 0, delta = 0 }, + } +end + +local function newChannel(): Channel + return { + preset = 1, bank = 0, pitchWheel = 8192, midiPan = 8192, midiVolume = 16383, midiExpression = 16383, + midiRPN = 0xFFFF, midiData = 0, sustain = false, panOffset = 0, gainDB = 0, pitchRange = 2, tuning = 0, + } +end + +-- new(sf, sampleRate, opts) -> State. sf: { presets, samples } (Parse.parse or Fallback.build). +-- opts.gain: output gain (linear, default 0.5); opts.maxVoices (default 256) +function Synth.new(sf: any, rate: number, gain: number?, maxVoices: number?): State + local lookup: { [number]: number } = {} + for i, p in sf.presets do + local k = p.bank * 128 + p.preset + if lookup[k] == nil then + lookup[k] = i + end + end + local s: State = { + presets = sf.presets, + lookup = lookup, + samples = sf.samples, + rate = rate, + gainDB = gain2db(gain or 0.5), + voices = {}, + maxVoices = maxVoices or 256, + playIndex = 0, + channels = {}, + } + for ch = 1, 16 do + s.channels[ch] = newChannel() + end + for ch = 0, 15 do + Synth.program(s, ch, 0) + end + return s +end + +local function presetIndex(s: State, bank: number, preset: number): number + return s.lookup[bank * 128 + preset] or -1 +end + +-- noteOn(s, channel, key, velocity 0..127) +function Synth.noteOn(s: State, ch: number, key: number, velocity: number) + local c = s.channels[ch + 1] + if not c then + return + end + if velocity <= 0 then + Synth.noteOff(s, ch, key) + return + end + local pi = c.preset + local preset = s.presets[pi] + if not preset then + return + end + local vel = math.min(velocity, 127) / 127 + local midiVel = floor(vel * 127) + local rate = s.rate + local voices = s.voices + local playIndex = s.playIndex + s.playIndex += 1 + for _, region in preset.regions do + if key < region.lokey or key > region.hikey or midiVel < region.lovel or midiVel > region.hivel then + continue + end + local voice: Voice? = nil + if region.group ~= 0 then + for _, v in voices do + if v.preset == pi and v.region.group == region.group then + voiceEndQuick(s, v) + elseif v.preset == -1 and not voice then + voice = v + end + end + else + for _, v in voices do + if v.preset == -1 then + voice = v + break + end + end + end + if not voice then + if #voices < s.maxVoices then + local v = newVoice() + table.insert(voices, v) + voice = v + else + local best = -1e18 + for _, v in voices do + if v.amp.segment == RELEASE then + local done = releaseSamples(v.amp, rate) - v.amp.untilNext + if done > best then + best, voice = done, v + end + end + end + if not voice then + continue + end + end + end + local v = voice :: Voice + v.region = region + v.preset = pi + v.key = key + v.channel = ch + v.playIndex = playIndex + v.held = false + v.gainDB = s.gainDB - region.attenuation - gain2db(1 / vel) + c.gainDB + calcPitch(v, channelShift(c), rate) + setPan(v, region.pan + c.panOffset) + v.pos = region.offset + local doLoop = region.loopMode ~= LOOP_NONE and region.loopStart < region.loopEnd + v.loopStart = if doLoop then region.loopStart else 0 + v.loopEnd = if doLoop then region.loopEnd else 0 + envSetup(v.amp, region, "a", key, midiVel, true, rate) + envSetup(v.mod, region, "m", key, midiVel, false, rate) + local fc = if region.filterFc <= 13500 then cents2Hz(region.filterFc) / rate else 1 + v.qinv = 1 / 10 ^ ((region.filterQ / 10) / 20) + v.z1, v.z2 = 0, 0 + v.lpActive = fc < 0.499 + if v.lpActive then + lowpassSetup(v, fc) + end + lfoSetup(v.modlfo, region.delayModLFO, region.freqModLFO, rate) + lfoSetup(v.viblfo, region.delayVibLFO, region.freqVibLFO, rate) + end +end + +-- noteOff(s, channel, key): ends the oldest matching note (all its regions); held while sustain is down +function Synth.noteOff(s: State, ch: number, key: number) + local c = s.channels[ch + 1] + if not c then + return + end + local first = -1 + for _, v in s.voices do + if v.preset ~= -1 and v.channel == ch and v.key == key and v.amp.segment < RELEASE and not v.held then + if first == -1 or v.playIndex < first then + first = v.playIndex + end + end + end + if first == -1 then + return + end + for _, v in s.voices do + if v.preset ~= -1 and v.channel == ch and v.key == key and v.amp.segment < RELEASE and not v.held and v.playIndex == first then + if c.sustain then + v.held = true + else + voiceEnd(s, v) + end + end + end +end + +local function applyPitch(s: State, ch: number, c: Channel) + local shift = channelShift(c) + for _, v in s.voices do + if v.preset ~= -1 and v.channel == ch then + calcPitch(v, shift, s.rate) + end + end +end + +local function setVolume(s: State, ch: number, c: Channel, volume: number) + local db = gain2db(volume) + if db == c.gainDB then + return + end + local change = db - c.gainDB + for _, v in s.voices do + if v.preset ~= -1 and v.channel == ch then + v.gainDB += change + end + end + c.gainDB = db +end + +local function setChannelPan(s: State, ch: number, c: Channel, pan: number) + for _, v in s.voices do + if v.preset ~= -1 and v.channel == ch then + setPan(v, v.region.pan + pan - 0.5) + end + end + c.panOffset = pan - 0.5 +end + +local function setTuning(s: State, ch: number, c: Channel, tuning: number) + if c.tuning ~= tuning then + c.tuning = tuning + applyPitch(s, ch, c) + end +end + +local function setPitchRange(s: State, ch: number, c: Channel, range: number) + if c.pitchRange ~= range then + c.pitchRange = range + if c.pitchWheel ~= 8192 then + applyPitch(s, ch, c) + end + end +end + +local function setSustain(s: State, ch: number, c: Channel, on: boolean) + if c.sustain == on then + return + end + c.sustain = on + if on then + return + end + for _, v in s.voices do + if v.preset ~= -1 and v.channel == ch and v.amp.segment < RELEASE and v.held then + voiceEnd(s, v) + end + end +end + +-- program(s, channel, program): bank select + program change (channel 9: drums, bank 128) +function Synth.program(s: State, ch: number, program: number) + local c = s.channels[ch + 1] + if not c then + return + end + local bank = c.bank % 32768 + local idx + if ch == 9 then + idx = presetIndex(s, 128 + bank, program) + if idx == -1 then + idx = presetIndex(s, 128, program) + end + if idx == -1 then + idx = presetIndex(s, 128, 0) + end + if idx == -1 then + idx = presetIndex(s, bank, program) + end + else + idx = presetIndex(s, bank, program) + end + if idx == -1 then + idx = presetIndex(s, 0, program) + end + if idx ~= -1 then + c.preset = idx + end +end + +-- pitchBend(s, channel, 0..16383) +function Synth.pitchBend(s: State, ch: number, value: number) + local c = s.channels[ch + 1] + if not c or c.pitchWheel == value then + return + end + c.pitchWheel = value + applyPitch(s, ch, c) +end + +-- control(s, channel, controller, value 0..127) +function Synth.control(s: State, ch: number, cc: number, value: number) + local c = s.channels[ch + 1] + if not c then + return + end + local volume, pan, data = false, false, false + if cc == 7 then + c.midiVolume = c.midiVolume % 128 + value * 128 + volume = true + elseif cc == 39 then + c.midiVolume = c.midiVolume - c.midiVolume % 128 + value + volume = true + elseif cc == 11 then + c.midiExpression = c.midiExpression % 128 + value * 128 + volume = true + elseif cc == 43 then + c.midiExpression = c.midiExpression - c.midiExpression % 128 + value + volume = true + elseif cc == 10 then + c.midiPan = c.midiPan % 128 + value * 128 + pan = true + elseif cc == 42 then + c.midiPan = c.midiPan - c.midiPan % 128 + value + pan = true + elseif cc == 6 then + c.midiData = c.midiData % 128 + value * 128 + data = true + elseif cc == 38 then + c.midiData = c.midiData - c.midiData % 128 + value + data = true + elseif cc == 0 then + c.bank = 0x8000 + value -- bank select MSB alone acts like LSB (as tsf.h) + elseif cc == 32 then + c.bank = (if c.bank >= 0x8000 then (c.bank % 128) * 128 else 0) + value + elseif cc == 101 then + local rpn = if c.midiRPN == 0xFFFF then 0 else c.midiRPN + c.midiRPN = rpn % 128 + value * 128 + elseif cc == 100 then + local rpn = if c.midiRPN == 0xFFFF then 0 else c.midiRPN + c.midiRPN = rpn - rpn % 128 + value + elseif cc == 98 or cc == 99 then + c.midiRPN = 0xFFFF + elseif cc == 64 then + setSustain(s, ch, c, value >= 64) + elseif cc == 120 then + for _, v in s.voices do + if v.preset ~= -1 and v.channel == ch and (v.amp.segment < RELEASE or v.amp.release ~= 0) then + voiceEndQuick(s, v) + end + end + elseif cc == 123 then + for _, v in s.voices do + if v.preset ~= -1 and v.channel == ch and v.amp.segment < RELEASE then + voiceEnd(s, v) + end + end + elseif cc == 121 then + c.midiVolume, c.midiExpression, c.midiPan, c.bank, c.midiRPN, c.midiData = 16383, 16383, 8192, 0, 0xFFFF, 0 + setVolume(s, ch, c, 1) + setChannelPan(s, ch, c, 0.5) + setPitchRange(s, ch, c, 2) + setTuning(s, ch, c, 0) + end + if volume then + -- the cube gives a decent MIDI volume curve (tsf.h) + setVolume(s, ch, c, ((c.midiVolume / 16383) * (c.midiExpression / 16383)) ^ 3) + elseif pan then + setChannelPan(s, ch, c, c.midiPan / 16383) + elseif data then + if c.midiRPN == 0 then + setPitchRange(s, ch, c, c.midiData // 128 + 0.01 * (c.midiData % 128)) + elseif c.midiRPN == 1 then + local t = c.tuning + setTuning(s, ch, c, (if t < 0 then math.ceil(t) else floor(t)) + (c.midiData - 8192) / 8192) + elseif c.midiRPN == 2 and cc == 6 then + local t = c.tuning + setTuning(s, ch, c, (value - 64) + (t - (if t < 0 then math.ceil(t) else floor(t)))) + end + end +end + +-- midi(s, status, d1, d2): one channel message +function Synth.midi(s: State, status: number, d1: number, d2: number) + local kind, ch = status // 16, status % 16 + if kind == 9 then + Synth.noteOn(s, ch, d1, d2) + elseif kind == 8 then + Synth.noteOff(s, ch, d1) + elseif kind == 11 then + Synth.control(s, ch, d1, d2) + elseif kind == 12 then + Synth.program(s, ch, d1) + elseif kind == 14 then + Synth.pitchBend(s, ch, d1 + d2 * 128) + end +end + +-- reset(s): all voices off, channels back to their defaults +function Synth.reset(s: State) + for _, v in s.voices do + v.preset = -1 + end + for ch = 1, 16 do + s.channels[ch] = newChannel() + end + for ch = 0, 15 do + Synth.program(s, ch, 0) + end +end + +-- active(s) -> the number of sounding voices +function Synth.active(s: State): number + local n = 0 + for _, v in s.voices do + if v.preset ~= -1 then + n += 1 + end + end + return n +end + +-- ------------------------------------------------------------------------------------------------ render +local function voiceRender(s: State, v: Voice, out: buffer, frame: number, numSamples: number) + local region = v.region + local input = s.samples + local rate = s.rate + local modEnvToPitch, modEnvToFilterFc = region.modEnvToPitch, region.modEnvToFilterFc + local modLfoToPitch, modLfoToFilterFc, modLfoToVolume = region.modLfoToPitch, region.modLfoToFilterFc, region.modLfoToVolume + local vibLfoToPitch = region.vibLfoToPitch + local updateModEnv = modEnvToPitch ~= 0 or modEnvToFilterFc ~= 0 + local updateModLfo = v.modlfo.delta ~= 0 and (modLfoToPitch ~= 0 or modLfoToFilterFc ~= 0 or modLfoToVolume ~= 0) + local updateVibLfo = v.viblfo.delta ~= 0 and vibLfoToPitch ~= 0 + local loopStart, loopEnd = v.loopStart, v.loopEnd + local isLooping = loopStart < loopEnd + local endD = region.stop + local loopEndD = loopEnd + 1 + local loopLen = loopEnd - loopStart + 1 + local pos = v.pos + local lpActive, a0, a1, b1, b2, z1, z2 = v.lpActive, v.a0, v.a1, v.b1, v.b2, v.z1, v.z2 + local dynamicLowpass = modLfoToFilterFc ~= 0 or modEnvToFilterFc ~= 0 + local dynamicPitch = modLfoToPitch ~= 0 or modEnvToPitch ~= 0 or vibLfoToPitch ~= 0 + local dynamicGain = modLfoToVolume ~= 0 + local filterFc = region.filterFc + local pitchRatio = if dynamicPitch then 0 else tc2s(v.pitchIn) * v.pitchOut + local noteGain = if dynamicGain then 0 else db2gain(v.gainDB) + local o = frame * 8 + while numSamples > 0 do + local block = if numSamples > BLOCK then BLOCK else numSamples + numSamples -= block + if dynamicLowpass then + local fres = filterFc + v.modlfo.level * modLfoToFilterFc + v.mod.level * modEnvToFilterFc + local fc = if fres <= 13500 then cents2Hz(fres) / rate else 1 + lpActive = fc < 0.499 + if lpActive then + lowpassSetup(v, fc) + a0, a1, b1, b2 = v.a0, v.a1, v.b1, v.b2 + end + end + if dynamicPitch then + pitchRatio = tc2s(v.pitchIn + (v.modlfo.level * modLfoToPitch + v.viblfo.level * vibLfoToPitch + v.mod.level * modEnvToPitch)) * v.pitchOut + end + if dynamicGain then + noteGain = db2gain(v.gainDB + v.modlfo.level * modLfoToVolume * 0.1) + end + local gainMono = noteGain * v.amp.level + envProcess(v.amp, block, rate) + if updateModEnv then + envProcess(v.mod, block, rate) + end + if updateModLfo then + lfoProcess(v.modlfo, block) + end + if updateVibLfo then + lfoProcess(v.viblfo, block) + end + -- ramp the gain across the block to the envelope's next level (tsf.h steps it per block: zipper noise) + local gainNext = noteGain * v.amp.level + local step = (gainNext - gainMono) / block + local panL, panR = v.panL, v.panR + local g = gainMono + local k = block + while k > 0 and pos < endD do + k -= 1 + local ip = floor(pos) + local np = if ip >= loopEnd and isLooping then loopStart else ip + 1 + local s0 = readf32(input, ip * 4) + local val = s0 + (readf32(input, np * 4) - s0) * (pos - ip) + if lpActive then + local y = val * a0 + z1 + z1 = val * a1 + z2 - b1 * y + z2 = val * a0 - b2 * y + val = y + end + val *= g + g += step + writef32(out, o, readf32(out, o) + val * panL) + writef32(out, o + 4, readf32(out, o + 4) + val * panR) + o += 8 + pos += pitchRatio + if pos >= loopEndD and isLooping then + pos -= loopLen + end + end + o += k * 8 + if not (pos < endD) or v.amp.segment == DONE then + v.preset = -1 + return + end + end + v.pos = pos + v.lpActive, v.z1, v.z2 = lpActive, z1, z2 +end + +-- render(s, out, frame, n): mixes n stereo frames into out (interleaved f32) starting at frame; out-of-range +-- requests are clipped to the buffer +function Synth.render(s: State, out: buffer, frame: number, n: number) + local room = blen(out) // 8 - frame + if frame < 0 or room <= 0 then + return + end + if n > room then + n = room + end + if n <= 0 then + return + end + -- the sample buffer must hold every region's range + the pad sample (Parse / Fallback guarantee it; checked here + -- once so a hand-made SoundFont cannot index outside it) + local count = blen(s.samples) // 4 - 1 + for _, v in s.voices do + if v.preset ~= -1 then + local r = v.region + if r.stop > count or r.loopEnd > count or r.offset < 0 or r.loopStart < 0 or v.pos < 0 then + v.preset = -1 + else + voiceRender(s, v, out, frame, n) + end + end + end +end + +return Synth diff --git a/src/Formats/codecs/SoundFont/init.luau b/src/Formats/codecs/SoundFont/init.luau new file mode 100644 index 0000000..a1c8feb --- /dev/null +++ b/src/Formats/codecs/SoundFont/init.luau @@ -0,0 +1,69 @@ +--!strict +-- codecs/SoundFont: SoundFont 2 banks and the sample synth that plays MIDI through them. A codec (layer 1) shared by +-- music/sf2 (the file format) and music/midi (rendering). The synth is a port of TinySoundFont (tsf.h v0.9, MIT, +-- (c) 2017-2025 Bernhard Schelling; licenses/TinySoundFont-LICENSE.txt); see Parse / Synth for what is covered. +-- Without a bank, fallback() is a generated General MIDI set of simple waveforms (sine / triangle / square / saw / +-- noise) with a drum kit. +-- +-- local SoundFont = require("@formats/codecs/SoundFont") +-- local sf, err = SoundFont.parse(buf) -- buffer | string | core/Bytes Reader -> SoundFont | nil, Err +-- local sf = SoundFont.fallback() -- the built-in waveform set +-- local s = SoundFont.synth(sf, 44100, { gain = 0.5 }) -- a synth State; SoundFont.Synth.midi(s, 0x90, 60, 100) +-- SoundFont.Synth.render(s, out, frame, n) -- mix n stereo f32 frames into out at frame +-- +-- Never throws: bad data returns nil, Err. +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Parse = require("@formats/codecs/SoundFont/Parse") +local Synth = require("@formats/codecs/SoundFont/Synth") +local Fallback = require("@formats/codecs/SoundFont/Fallback") + +local SoundFont = {} + +export type SoundFont = Parse.SoundFont +export type State = Synth.State + +SoundFont.Synth = Synth +SoundFont.defaultRegion = Parse.defaultRegion + +-- sniff(r) -> true when r starts with RIFF....sfbk +function SoundFont.sniff(r: Bytes.Reader): boolean + return r:peek(4) == "RIFF" and r:peek(4, 8) == "sfbk" +end + +-- parse(src, opts?) -> SoundFont | nil, Err. src: buffer | string | Reader. opts.maxRegions (default 10^6), +-- opts.maxSamples (default 2^28) +function SoundFont.parse(src: any, opts: Parse.Options?): (SoundFont?, Err.Err?) + local r: Bytes.Reader + if type(src) == "string" then + r = Bytes.reader(buffer.fromstring(src)) + elseif type(src) == "buffer" then + r = Bytes.reader(src) + elseif type(src) == "table" and type(src.buf) == "buffer" then + r = Bytes.reader(src.buf, src.pos, src.limit - src.pos) + else + return nil, Err.new(Err.ARG, "soundfont: expected a buffer, string or Reader") + end + local ok, sf, err = pcall(Parse.parse, r, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "soundfont parser failed: " .. tostring(sf)) + end + return sf, err +end + +-- fallback() -> the built-in General MIDI waveform set +function SoundFont.fallback(): SoundFont + return Fallback.build() +end + +-- isSoundFont(v) -> true for a parsed / fallback SoundFont value +function SoundFont.isSoundFont(v: any): boolean + return type(v) == "table" and v.kind == "soundfont" and type(v.samples) == "buffer" and type(v.presets) == "table" +end + +-- synth(sf?, sampleRate?, opts?) -> State. opts.gain (linear, default 0.5), opts.maxVoices (default 256) +function SoundFont.synth(sf: SoundFont?, sampleRate: number?, opts: { gain: number?, maxVoices: number? }?): State + return Synth.new(sf or Fallback.build(), sampleRate or 44100, opts and opts.gain, opts and opts.maxVoices) +end + +return SoundFont diff --git a/src/Formats/codecs/Tracker/Mixer.luau b/src/Formats/codecs/Tracker/Mixer.luau new file mode 100644 index 0000000..193a034 --- /dev/null +++ b/src/Formats/codecs/Tracker/Mixer.luau @@ -0,0 +1,173 @@ +--!strict +--!native +-- codecs/Tracker/Mixer: mixes the player's active voices into an interleaved stereo f32 buffer. Per voice: sample +-- loops (forward, ping-pong, IT sustain loops while the key is held), linear or no interpolation, the IT two-pole +-- resonant filter, and a short gain ramp per tick against clicks. Written for this library (no third-party code). +-- +-- Never throws: sample indexes are clamped to the sample, every loop is bounded, and the caller (codecs/Tracker) +-- validates the sample buffers' sizes. +local floor, ceil, min = math.floor, math.ceil, math.min +local readf32, writef32 = buffer.readf32, buffer.writef32 + +local Mixer = {} + +-- mixVoice(v, out?, off, n, linear, ramp): n frames of voice v added at frame off of out (nil: only advance) +local function mixVoice(v: any, out: buffer?, off: number, n: number, linear: boolean, ramp: number) + local data: buffer = v.data + local nch = v.nch + local inc = v.inc + if not (inc > 0 and inc < 1e6) then + return + end + local len = v.len + local hi = len - 1 + local i = 0 + local guard = 0 + while i < n do + guard += 1 + if guard > n + 64 then + return + end + local s, e, t + if v.keyOn and v.susT > 0 then + s, e, t = v.susS, v.susE, v.susT + elseif v.loopT > 0 then + s, e, t = v.loopS, v.loopE, v.loopT + else + s, e, t = 0, len, 0 + end + local p = v.p + local dir = v.dir + local count + if dir > 0 then + local lim = if t == 2 then e - 1 else e + if p >= lim then + if t == 0 then + v.active = false + return + elseif t == 1 then + p = s + (p - e) % (e - s) + else + p = 2 * (e - 1) - p + if p < s then + p = s + end + v.dir = -1 + end + v.p = p + continue + end + count = ceil((lim - p) / inc) + else + if p < s then + p = 2 * s - p + if p > e - 1 then + p = e - 1 + end + v.p = p + v.dir = 1 + continue + end + count = floor((p - s) / inc) + 1 + end + if count < 1 then + count = 1 + end + local m = min(n - i, count) + local step = inc * dir + if out == nil then + v.p = p + step * m + i += m + continue + end + local wrapJ = if t == 1 then s else e - 1 + local gl, gr = v.gl, v.gr + local rl = v.rampN + local dl, dr = 0, 0 + local tl, tr = v.tl, v.tr + if rl > 0 then + dl, dr = (tl - gl) / rl, (tr - gr) / rl + end + local fOn = v.fOn + local fa, fb0, fb1 = v.fa, v.fb0, v.fb1 + local y1l, y2l, y1r, y2r = v.y1l, v.y2l, v.y1r, v.y2r + local o = (off + i) * 8 + for _ = 1, m do + local idx = floor(p) + if idx > hi then + idx = hi + elseif idx < 0 then + idx = 0 + end + local j = idx + 1 + if j >= e then + j = wrapJ + end + if j > hi then + j = hi + end + local xl, xr + if nch == 1 then + local a = readf32(data, idx * 4) + if linear then + local b = readf32(data, j * 4) + xl = a + (b - a) * (p - idx) + else + xl = a + end + if fOn then + local y = xl * fa + y1l * fb0 + y2l * fb1 + y2l, y1l = y1l, y + xl = y + end + xr = xl + else + local al = readf32(data, idx * 8) + local ar = readf32(data, idx * 8 + 4) + if linear then + local f = p - idx + xl = al + (readf32(data, j * 8) - al) * f + xr = ar + (readf32(data, j * 8 + 4) - ar) * f + else + xl, xr = al, ar + end + if fOn then + local y = xl * fa + y1l * fb0 + y2l * fb1 + y2l, y1l = y1l, y + xl = y + y = xr * fa + y1r * fb0 + y2r * fb1 + y2r, y1r = y1r, y + xr = y + end + end + if rl > 0 then + gl += dl + gr += dr + rl -= 1 + if rl == 0 then + gl, gr = tl, tr + end + end + writef32(out, o, readf32(out, o) + xl * gl) + writef32(out, o + 4, readf32(out, o + 4) + xr * gr) + o += 8 + p += step + end + v.p = p + v.gl, v.gr, v.rampN = gl, gr, rl + v.y1l, v.y2l, v.y1r, v.y2r = y1l, y2l, y1r, y2r + i += m + end + local _ = ramp +end + +-- mix(st, out?, off, n, linear): every active voice of player st; out nil only advances the sample positions +function Mixer.mix(st: any, out: buffer?, off: number, n: number, linear: boolean) + for _, v in st.voices do + if v.active and v.data then + mixVoice(v, out, off, n, linear, 0) + end + end +end + +return Mixer diff --git a/src/Formats/codecs/Tracker/Pcm.luau b/src/Formats/codecs/Tracker/Pcm.luau new file mode 100644 index 0000000..30c59c8 --- /dev/null +++ b/src/Formats/codecs/Tracker/Pcm.luau @@ -0,0 +1,132 @@ +--!strict +--!native +-- codecs/Tracker/Pcm: sample data conversions shared by the tracker formats. Raw 8 / 16-bit PCM (signed or unsigned, +-- plain or delta coded as in XM / IT 2.15, interleaved or planar stereo) to the engine's f32 samples, and back. +-- +-- Never throws: reads past the source are refused up front (decode returns nil). +local readu8, readi8, readu16, readi16 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16 +local writef32, readf32, writeu8, writei16 = buffer.writef32, buffer.readf32, buffer.writeu8, buffer.writei16 +local floor = math.floor + +local Pcm = {} + +export type Spec = { + bits: number, -- 8 | 16 + signed: boolean, + delta: boolean?, -- each value is the difference to the previous one (XM, IT 2.15 "delta" flag) + channels: number?, -- 1 (default) | 2 + planar: boolean?, -- stereo stored as all left then all right (XM, IT); default interleaved + bigEndian: boolean?, +} + +-- bytes(frames, spec) -> the size of the raw data +function Pcm.bytes(frames: number, spec: Spec): number + return frames * (spec.channels or 1) * (spec.bits // 8) +end + +-- decode(buf, off, frames, spec) -> f32 buffer (frames * channels, interleaved) | nil when the source is too short +function Pcm.decode(buf: buffer, off: number, frames: number, spec: Spec): buffer? + local nch = spec.channels or 1 + local bps = spec.bits // 8 + local total = frames * nch + if frames < 0 or off < 0 or off + total * bps > buffer.len(buf) then + return nil + end + local out = buffer.create(total * 4) + local planar = spec.planar and nch == 2 + for c = 0, nch - 1 do + local acc = 0 + for i = 0, frames - 1 do + local k = if planar then c * frames + i else i * nch + c + local v + if bps == 1 then + if spec.signed then + v = readi8(buf, off + k) + else + v = readu8(buf, off + k) - 128 + end + if spec.delta then + acc = (acc + v + 128) % 256 - 128 + v = acc + end + writef32(out, (i * nch + c) * 4, v / 128) + else + local p = off + k * 2 + if spec.bigEndian then + v = readu8(buf, p) * 256 + readu8(buf, p + 1) + if spec.signed and v >= 32768 then + v -= 65536 + end + elseif spec.signed then + v = readi16(buf, p) + else + v = readu16(buf, p) + end + if not spec.signed then + v -= 32768 + end + if spec.delta then + acc = (acc + v + 32768) % 65536 - 32768 + v = acc + end + writef32(out, (i * nch + c) * 4, v / 32768) + end + end + end + return out +end + +-- encode(samples, frames, spec) -> raw PCM (signed or unsigned, optional delta, interleaved or planar) +function Pcm.encode(samples: buffer, frames: number, spec: Spec): buffer + local nch = spec.channels or 1 + local bps = spec.bits // 8 + local out = buffer.create(frames * nch * bps) + local planar = spec.planar and nch == 2 + local avail = buffer.len(samples) // 4 + for c = 0, nch - 1 do + local prev = 0 + for i = 0, frames - 1 do + local si = i * nch + c + local x = if si < avail then readf32(samples, si * 4) else 0 + local k = if planar then c * frames + i else i * nch + c + if bps == 1 then + local v = math.clamp(floor(x * 128 + 0.5), -128, 127) + local w = v + if spec.delta then + w = (v - prev) % 256 + prev = v + else + w = if spec.signed then v % 256 else v + 128 + end + writeu8(out, k, w) + else + local v = math.clamp(floor(x * 32768 + 0.5), -32768, 32767) + local w = v + if spec.delta then + w = (v - prev + 32768) % 65536 - 32768 + prev = v + elseif not spec.signed then + w = v + 32768 + if w >= 32768 then + w -= 65536 + end + end + writei16(out, k * 2, w) + end + end + end + return out +end + +-- bits(samples) -> 8 when every value is exactly representable in 8 bits (data loaded from 8-bit), else 16 +function Pcm.bitsNeeded(samples: buffer): number + for i = 0, buffer.len(samples) // 4 - 1 do + local x = readf32(samples, i * 4) * 128 + if x ~= floor(x) then + return 16 + end + end + return 8 +end + +return Pcm diff --git a/src/Formats/codecs/Tracker/Player.luau b/src/Formats/codecs/Tracker/Player.luau new file mode 100644 index 0000000..84d2079 --- /dev/null +++ b/src/Formats/codecs/Tracker/Player.luau @@ -0,0 +1,1890 @@ +--!strict +--!native +-- codecs/Tracker/Player: the sequencer of the tracker engine. One player for MOD, S3M, XM and IT: rows, orders, +-- speed / tempo, every effect of the four formats (interpreted per format family: ProTracker / FastTracker 2 numeric +-- effects, ScreamTracker 3 / Impulse Tracker letter effects), instruments with volume / panning / pitch envelopes, +-- fadeout and auto-vibrato, IT new note actions (background voices), duplicate checks and resonant filters, and song +-- end / loop detection. Written from the format documents (ProTracker 2.3 docs, the XM spec and FT2 behaviour notes, +-- ST3 TECH.DOC, ITTECH.TXT); no third-party code. Mixing is codecs/Tracker/Mixer. +-- +-- Never throws: the module is validated by codecs/Tracker before a player is made, and every table lookup here is +-- guarded. +local Tables = require("@formats/codecs/Tracker/Tables") + +local wave64, autoWave = Tables.wave64, Tables.autoWave +local AMIGA = Tables.AMIGA +local AMIGA_PAL = Tables.AMIGA_PAL +local floor, min, max, clamp, abs = math.floor, math.min, math.max, math.clamp, math.abs +local readu8 = buffer.readu8 + +local Player = {} + +local MOD, S3M, XM, IT = 1, 2, 3, 4 +Player.MOD, Player.S3M, Player.XM, Player.IT = MOD, S3M, XM, IT +local FAMILY = { mod = MOD, s3m = S3M, xm = XM, it = IT } + +local BG_VOICES = 64 -- voices beyond one per channel, for IT new note actions + +-- ------------------------------------------------------------------------------------------------ state +local function newVoice(): any + return { + active = false, + chan = 0, + bg = false, + data = nil :: buffer?, + nch = 1, + len = 0, + loopS = 0, + loopE = 0, + loopT = 0, + susS = 0, + susE = 0, + susT = 0, + p = 0, + dir = 1, + inc = 0, + smp = nil :: any, + smpIdx = 0, + ins = nil :: any, + insIdx = 0, + note = 0, + vol = 0, + pan = 128, + chanVol = 64, + period = 0, + periodOut = 0, + base = 8363, + keyOn = true, + fading = false, + fade = 65536, + volEnvPos = 0, + panEnvPos = 0, + pitchEnvPos = 0, + volEnvOn = true, + panEnvOn = true, + pitchEnvOn = true, + envVol = 64, + envPan = 0, + envPitch = 0, + avPos = 0, + avAmp = 0, + gl = 0, + gr = 0, + tl = 0, + tr = 0, + started = false, + cutoff = 127, + reso = 0, + fOn = false, + fa = 1, + fb0 = 0, + fb1 = 0, + y1l = 0, + y2l = 0, + y1r = 0, + y2r = 0, + tremorMute = false, + surround = false, + rampN = 0, + owner = 0, -- the channel whose foreground voice this is (0: free or background) + order = 0, -- allocation age + } +end + +local function newChannel(i: number, pan: number, vol: number): any + return { + idx = i, + voice = nil :: any, + note = 0, + realNote = 0, + insIdx = 0, + smpIdx = 0, + smp = nil :: any, + vol = 0, + pan = pan, + basePan = pan, + chanVol = vol, + period = 0, + target = 0, + portaSpeed = 0, + base = 8363, + finetune = nil :: number?, + fx = 0, + param = 0, + vcmd = 0, + -- memories + mPortaUp = 0, + mPortaDn = 0, + mFineUp = 0, + mFineDn = 0, + mXFineUp = 0, + mXFineDn = 0, + mVolSlide = 0, + mFineVolUp = 0, + mFineVolDn = 0, + mOffset = 0, + mHighOffset = 0, + mPanSlide = 0, + mGVolSlide = 0, + mRetrig = 0, + mTremor = 0, + mArp = 0, + mS3M = 0, + mEF = 0, + mChanVolSlide = 0, + mTempo = 0, + mVolCol = 0, + mS = 0, + vibSpeed = 0, + vibDepth = 0, + vibPos = 0, + vibWave = 0, + tremSpeed = 0, + tremDepth = 0, + tremPos = 0, + tremWave = 0, + panbSpeed = 0, + panbDepth = 0, + panbPos = 0, + panbWave = 0, + vibDelta = 0, + tremDelta = 0, + panbDelta = 0, + arp = 0, + loopRow = 0, + loopCount = 0, + retrigCount = 0, + tremorCount = 0, + tremorOn = true, + delayTick = -1, + dNote = 0, + dIns = 0, + dVol = 0, + cutTick = -1, + keyOffTick = -1, + nna = -1, + surround = false, + cutoff = 127, + reso = 0, + volEnvOn = true, + panEnvOn = true, + pitchEnvOn = true, + muted = false, + triggered = false, + } +end + +-- new(module, opts) -> player state (module validated by the caller) +function Player.new(m: any, sampleRate: number, opts: any): any + local fmt = FAMILY[m.format] or MOD + local st: any = { + m = m, + fmt = fmt, + sr = sampleRate, + nch = m.channels, + speed = m.speed, + tempo = m.tempo, + gvol = m.globalVolume, + linear = m.linear, + insMode = m.instrumentMode and #m.instruments > 0, + oldFx = m.flags.oldEffects or false, + compatG = m.flags.compatGxx or false, + fastSlides = m.flags.fastSlides or false, + amigaLimits = m.flags.amigaLimits or false, + ord = 0, + row = 0, + tick = 0, + pat = nil :: any, + patIdx = -1, + patDelay = 0, + patDelayRep = 0, + fineDelay = 0, + jumpOrd = -1, + ft2BreakPos = 0, + breakRow = -1, + loopJump = -1, + ended = false, + visited = {} :: { [number]: boolean }, + chans = {}, + voices = {}, + age = 0, + tickFrames = 0, + frac = 0, + separation = math.clamp((opts and opts.stereoSeparation or 100) / 100, 0, 2), + master = 1, + rows = 0, + ramp = 64, + amiga = if fmt == MOD then AMIGA_PAL else AMIGA, + loopAllowed = opts and opts.loop or false, + } + for i = 1, m.channels do + local pan = m.channelPan[i] or 128 + local cv = m.channelVolume[i] or 64 + local c = newChannel(i, pan, cv) + c.basePan = pan + c.muted = m.channelMute[i] or false + if pan == 512 then -- surround marker + c.pan = 128 + c.surround = true + end + st.chans[i] = c + end + for i = 1, m.channels + BG_VOICES do + st.voices[i] = newVoice() + end + st.master = Player.masterGain(m, fmt) + Player.startOrder(st, 0, 0) + return st +end + +-- the output scale per format, calibrated against OpenMPT's default mix levels (tools/fixtures: a full-scale sine at +-- volume 64 on one centred channel) +function Player.masterGain(m: any, fmt: number): number + if fmt == IT or fmt == S3M then + return (m.mixVolume or 48) / 128 -- OpenMPT: linear in the mix / master volume, 64 = 0.5 + end + if fmt == XM then + return 0.375 -- OpenMPT's XM pre-amp (48 / 128), whatever the channel count + end + -- MOD: OpenMPT scales by the channel count (4 channels: 0.5; 2 / channels between 2 and 8) + return 2 / clamp(m.channels, 2, 8) +end + +-- ------------------------------------------------------------------------------------------------ orders and rows +-- startOrder(st, ord, row): resolve skip markers / the end of the order list; sets st.pat or st.ended +function Player.startOrder(st: any, ord: number, row: number) + local m = st.m + local order = m.order + local n = #order + local guard = 0 + local o = ord + while true do + guard += 1 + if guard > n + 2 then + st.ended = true + return + end + if o >= n then + o = m.restart or 0 + if o >= n or o < 0 then + o = 0 + end + if n == 0 then + st.ended = true + return + end + end + local p = order[o + 1] + if p == 255 then + o = n -- the end marker: wrap to the restart position + elseif p == 254 or m.patterns[p + 1] == nil then + o += 1 + else + st.ord = o + st.patIdx = p + st.pat = m.patterns[p + 1] + st.row = if row < st.pat.rows then row else 0 + return + end + end +end + +local function advanceRow(st: any) + if st.stopAfterRow then + st.ended = true + return + end + local loopRow = st.loopJump + if st.jumpOrd >= 0 or st.breakRow >= 0 then + local o = if st.jumpOrd >= 0 then st.jumpOrd else st.ord + 1 + local r = if st.breakRow >= 0 then st.breakRow else 0 + st.jumpOrd, st.breakRow, st.loopJump = -1, -1, -1 + st.ft2BreakPos = 0 + Player.startOrder(st, o, r) + return + end + if loopRow >= 0 then + st.loopJump = -1 + -- the rows inside a pattern loop are played again on purpose: forget them for the song-end check + for r = loopRow, st.row do + st.visited[st.ord * 1024 + r] = nil + end + st.row = loopRow + return + end + st.row += 1 + if st.row >= st.pat.rows then + -- FT2 (XM): the next pattern starts at the row a pattern loop last jumped to (the E6x "bug" FT2 players keep) + local r = if st.fmt == XM then st.ft2BreakPos else 0 + st.ft2BreakPos = 0 + Player.startOrder(st, st.ord + 1, r) + end +end + +-- ------------------------------------------------------------------------------------------------ pitch +-- the period of a note for a sample (see codecs/Tracker for the two period spaces) +local function notePeriod(st: any, note: number, smp: any, ft: number?): (number, number) + local base, ref, tr + if st.fmt == MOD or st.fmt == XM then + base, ref = 8363, 49 + tr = (smp.relativeNote or 0) * 64 + (ft or smp.finetune or 0) / 2 + else + base, ref, tr = smp.c5speed or 8363, 61, 0 + if base <= 0 then + base = 8363 + end + end + local plin = (ref - note) * 64 - tr + if st.fmt == MOD then + -- ProTracker: integer periods from the finetune tables (finetune 0 table scaled by 2^(-ft / 96), rounded) + local ftp = (ft or smp.finetune or 0) / 16 + return 4 * floor(Tables.noteToPeriod(note) * 2 ^ (-ftp / 12 / 8) + 0.5), base + end + if st.linear then + return plin, base + end + return 1712 * 8363 / base * 2 ^ (plin / 768), base +end + +local function arpPeriod(st: any, period: number, semis: number): number + if semis == 0 then + return period + end + if st.linear then + return period - semis * 64 + end + return period * 2 ^ (-semis / 12) +end + +local function clampPeriod(st: any, c: any) + if st.linear then + c.period = clamp(c.period, -6000, 6000) + elseif st.amigaLimits then + c.period = clamp(c.period, 113 * 4, 856 * 4) + else + c.period = clamp(c.period, 1, 1e6) + end +end + +-- ------------------------------------------------------------------------------------------------ voices +local function allocVoice(st: any): any + local best, bestScore = nil, math.huge + for _, v in st.voices do + if not v.active and v.owner == 0 then + return v + end + if v.bg then + local s = (v.vol * v.envVol * v.fade) / 1e9 + v.order * 1e-9 + if s < bestScore then + best, bestScore = v, s + end + end + end + if best then + best.active = false + return best + end + -- every voice is busy in the foreground (more channels than voices): reuse an inactive one anyway + for _, v in st.voices do + if not v.active then + local c = st.chans[v.owner] + if c and c.voice == v then + c.voice = nil + end + return v + end + end + return st.voices[1] -- unreachable: there are more voices than channels +end + +local function keyOff(st: any, v: any) + if not v or not v.active then + return + end + v.keyOn = false + local ins = v.ins + if st.fmt == XM then + if not (ins and ins.volEnv and ins.volEnv.enabled) then + v.vol = 0 + local c = st.chans[v.chan] + if c and c.voice == v then + c.vol = 0 + end + else + v.fading = true + end + elseif st.fmt == IT then + if ins then + local env = ins.volEnv + if not (env and env.enabled and v.volEnvOn) or env.loop then + v.fading = true + end + end + end +end + +local function noteFade(v: any) + if v and v.active then + v.fading = true + end +end + +local function cutVoice(v: any) + if v then + v.active = false + end +end + +-- start(st, c, smp, smpIdx, ins, insIdx, note, period, base, offset): a fresh voice for channel c +local function startVoice(st: any, c: any, smp: any, smpIdx: number, ins: any, insIdx: number, note: number, period: number, base: number, keepEnv: any) + local v = c.voice + if v == nil or v.bg then + v = allocVoice(st) + c.voice = v + v.owner = c.idx + end + local wasActive = v.active + v.active = smp.length > 0 and smp.data ~= nil + v.chan = c.idx + v.bg = false + v.smp = smp + v.smpIdx = smpIdx + v.data = smp.data + v.nch = smp.channels or 1 + v.len = smp.length + v.loopS, v.loopE, v.loopT = smp.loopStart, smp.loopEnd, smp.loopType + v.susS, v.susE, v.susT = smp.susStart or 0, smp.susEnd or 0, smp.susType or 0 + v.p = 0 + v.dir = 1 + v.ins = ins + v.insIdx = insIdx + v.note = note + v.period = period + v.periodOut = period + v.base = base + st.age += 1 + v.order = st.age + if keepEnv ~= true then + if keepEnv ~= "release" then + v.keyOn = true + v.fading = false + end + v.fade = 65536 + v.volEnvPos, v.panEnvPos, v.pitchEnvPos = 0, 0, 0 + v.avPos, v.avAmp = 0, 0 + v.envVol, v.envPan, v.envPitch = 64, 0, 0 + v.volEnvOn, v.panEnvOn, v.pitchEnvOn = true, true, true + v.y1l, v.y2l, v.y1r, v.y2r = 0, 0, 0, 0 + end + if not wasActive then + v.gl, v.gr = 0, 0 + end + return v +end + +-- IT new note actions on the channel's current voice (and duplicate checks on all its voices) +local function newNoteAction(st: any, c: any, ins: any, insIdx: number, note: number, smpIdx: number) + -- duplicate check: voices of this channel playing the same instrument + if ins and ins.dct and ins.dct > 0 then + for _, u in st.voices do + if u.active and u.chan == c.idx and u.insIdx == insIdx then + local dup = (ins.dct == 1 and u.note == note) or (ins.dct == 2 and u.smpIdx == smpIdx) or ins.dct == 3 + if dup then + local a = ins.dca or 0 + if a == 0 then + cutVoice(u) + elseif a == 1 then + keyOff(st, u) + else + noteFade(u) + end + end + end + end + end + local v = c.voice + if v == nil or not v.active then + return + end + local nna = c.nna + if nna < 0 then + nna = if v.ins then (v.ins.nna or 0) else 0 + end + if nna == 0 then + -- cut: the voice is reused for the new note (a short click is avoided by its ramp from the old gains) + v.active = false + return + end + v.bg = true + v.owner = 0 + c.voice = nil + if nna == 2 then + keyOff(st, v) + elseif nna == 3 then + noteFade(v) + end +end + +-- ------------------------------------------------------------------------------------------------ triggering +local function isPorta(st: any, fx: number, vcmd: number): boolean + local f = st.fmt + if f == MOD then + return fx == 3 or fx == 5 + elseif f == XM then + return fx == 3 or fx == 5 or (vcmd >= 0xF0) + end + -- S3M / IT: G (7) or L (12); IT volume column g (193..202, stored + 1) + return fx == 7 or fx == 12 or (f == IT and vcmd >= 194 and vcmd <= 203) +end + +-- the sample and real note for an instrument number + note +local function resolve(st: any, insIdx: number, note: number): (any, number, any, number) + local m = st.m + if st.insMode then + local ins = m.instruments[insIdx] + if not ins or note < 1 or note > 120 then + return nil, 0, ins, note + end + local si = ins.sampleMap[note] or 0 + local rn = ins.noteMap[note] or note + local smp = m.samples[si] + return smp, si, ins, rn + end + local smp = m.samples[insIdx] + return smp, insIdx, nil, note +end + +local function setInstrumentDefaults(st: any, c: any, smp: any, ins: any) + if smp then + c.vol = smp.volume + end + if st.fmt == IT then + -- IT: a sample's or instrument's default panning holds for its notes; the channel panning (set by the + -- effects) comes back for the others + local p = (smp and smp.pan) or (ins and ins.pan) + c.pan = p or c.basePan + if p then + c.surround = false + end + elseif smp and smp.pan then + c.pan = smp.pan + c.basePan = c.pan + c.surround = false + end + if ins and st.fmt == IT then + if ins.cutoff then + c.cutoff = ins.cutoff + end + if ins.resonance then + c.reso = ins.resonance + end + end +end + +local function sampleOffset(st: any, c: any, v: any) + local f = st.fmt + local fx, param = c.fx, c.param + local off = -1 + if (f == MOD or f == XM) and fx == 9 then + if param > 0 then + c.mOffset = param + end + off = (if f == XM then c.mOffset else param) * 256 + elseif (f == S3M or f == IT) and fx == 15 then + if param > 0 then + c.mOffset = param + end + off = c.mOffset * 256 + (if f == IT then c.mHighOffset * 65536 else 0) + end + if off > 0 and v and v.active then + if off >= v.len then + if v.loopT > 0 and f ~= MOD then + off = v.loopS + elseif f == MOD and v.loopT > 0 then + off = v.loopS + else + v.active = false + return + end + end + v.p = off + end +end + +-- trigger(st, c, note, insIdx, vcmd): the note / instrument / volume column part of a cell +local function trigger(st: any, c: any, note: number, insIdx: number, vcmd: number) + local f = st.fmt + local m = st.m + local porta = isPorta(st, c.fx, vcmd) + local hasNote = note >= 1 and note <= 120 + if insIdx > 0 then + local valid = if st.insMode then m.instruments[insIdx] ~= nil else m.samples[insIdx] ~= nil + if valid then + c.insIdx = insIdx + local n = if hasNote then note else c.note + local smp, _, ins = resolve(st, insIdx, if n > 0 then n else 61) + setInstrumentDefaults(st, c, smp, ins) + if not hasNote then + local v = c.voice + if f == XM and v then + -- an instrument number alone (FT2 / OpenMPT): the playing note's envelopes restart (key on, no + -- fadeout); the new instrument applies from the next note + v.keyOn, v.fading, v.fade = true, false, 65536 + v.volEnvPos, v.panEnvPos, v.avPos, v.avAmp = 0, 0, 0, 0 + elseif (f == MOD or f == S3M) and smp then + c.smp, c.smpIdx = smp, insIdx + end + end + elseif f == XM and hasNote then + -- an empty instrument: the note stops the channel + c.insIdx = insIdx + if c.voice then + c.voice.active = false + end + hasNote = false + end + end + if hasNote then + local useIns = c.insIdx + local smp, smpIdx, ins, realNote = resolve(st, useIns, note) + if smp == nil then + if (f == MOD or f == S3M) and c.smp then + smp, smpIdx = c.smp, c.smpIdx + end + end + if smp then + local ft = c.finetune + local period, base = notePeriod(st, realNote, smp, ft) + local v = c.voice + if porta and ((v and v.active) or f == MOD or f == XM) then + -- tone portamento: a new target, no new note (ProTracker / FT2 never start a note with it) + c.target = period + if st.fmt == IT or st.fmt == S3M then + c.note = note + end + else + if f == IT and st.insMode then + newNoteAction(st, c, ins, useIns, realNote, smpIdx) + end + -- FT2: a note without an instrument number restarts the sample only (envelopes, key off and + -- fadeout carry on); with another instrument than the playing one, its envelopes and fadeout start + -- over but a key off stays + local keep: any = false + if f == XM and insIdx == 0 and c.voice ~= nil then + keep = if c.voice.ins == ins then true else "release" + end + c.triggered = true + c.tremorOn = true + c.retrigCount = 0 + v = startVoice(st, c, smp, smpIdx, ins, useIns, realNote, period, base, keep) + v.patNote = note + c.period, c.target, c.base = period, period, base + c.note, c.realNote = note, realNote + c.smp, c.smpIdx = smp, smpIdx + if insIdx > 0 or f == MOD or f == S3M then + -- volume was set by the instrument; MOD / S3M keep the channel volume + end + if c.vibWave < 4 then + c.vibPos = 0 + end + if c.tremWave < 4 then + c.tremPos = 0 + end + v.cutoff, v.reso = c.cutoff, c.reso + v.volEnvOn, v.panEnvOn, v.pitchEnvOn = true, true, true + c.nna = -1 + sampleOffset(st, c, v) + end + elseif f == IT or f == XM then + -- a note mapped to no sample cuts + if c.voice and not porta then + if f == IT and st.insMode then + newNoteAction(st, c, nil, 0, note, 0) + end + if c.voice then + c.voice.active = false + end + end + end + elseif note == 255 then + if f == S3M or f == MOD then + cutVoice(c.voice) + elseif c.voice then + keyOff(st, c.voice) + end + elseif note == 254 then + cutVoice(c.voice) + if f ~= IT then + c.vol = 0 + end + elseif note == 253 then + noteFade(c.voice) + end + -- the volume column's set-volume / set-panning parts (the rest runs with the effects) + if vcmd > 0 then + if f == S3M then + c.vol = min(vcmd - 1, 64) + elseif f == XM then + if vcmd >= 0x10 and vcmd <= 0x50 then + c.vol = vcmd - 0x10 + elseif vcmd >= 0xC0 and vcmd <= 0xCF then + c.pan = (vcmd - 0xC0) * 16 + c.basePan = c.pan + end + elseif f == IT then + local v = vcmd - 1 + if v <= 64 then + c.vol = v + elseif v >= 128 and v <= 192 then + c.pan = (v - 128) * 4 + c.basePan = c.pan + c.surround = false + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ effect helpers +local function volSlideMod(c: any, param: number) + local x, y = param // 16, param % 16 + if x > 0 then + c.vol = min(64, c.vol + x) + else + c.vol = max(0, c.vol - y) + end +end + +local function tonePorta(st: any, c: any, speed: number) + if c.period == c.target then + return + end + if c.period < c.target then + c.period = min(c.period + speed, c.target) + else + c.period = max(c.period - speed, c.target) + end +end + +local function vibrato(st: any, c: any, scale: number) + c.vibDelta = wave64(c.vibWave % 4, c.vibPos) * c.vibDepth * scale + c.vibPos = (c.vibPos + c.vibSpeed) % 64 +end + +local function tremolo(c: any, scale: number) + c.tremDelta = floor(wave64(c.tremWave % 4, c.tremPos) * c.tremDepth * scale) + c.tremPos = (c.tremPos + c.tremSpeed) % 64 +end + +local function retrigVoice(st: any, c: any) + local v = c.voice + if v and v.smp then + v.active = v.smp.length > 0 + v.p = 0 + v.dir = 1 + end +end + +local function retrigVolume(c: any, x: number) + if x == 0 or x == 8 then + return + end + local mul = Tables.RETRIG_MUL[x + 1] + if mul ~= 1 then + c.vol = floor(c.vol * mul) + else + c.vol += Tables.RETRIG_ADD[x + 1] + end + c.vol = clamp(c.vol, 0, 64) +end + +-- S3M / IT D-style slide of a value: returns the new value (fine parts only on tick 0, normal parts on other ticks; +-- fast: normal parts on tick 0 too) +local function dSlide(value: number, param: number, tick: number, fast: boolean, hi: number): number + local x, y = param // 16, param % 16 + if y == 0xF and x > 0 then + if tick == 0 then + return min(hi, value + x) + end + return value + elseif x == 0xF and y > 0 then + if tick == 0 then + return max(0, value - y) + end + return value + end + if tick == 0 and not fast then + return value + end + if y == 0 then + return min(hi, value + x) + elseif x == 0 then + return max(0, value - y) + end + return value +end + +-- ------------------------------------------------------------------------------------------------ MOD / XM effects +local function fxModXm(st: any, c: any, tick: number) + local fx, param = c.fx, c.param + local xm = st.fmt == XM + local x, y = param // 16, param % 16 + if fx == 0 then + if param ~= 0 then + local k = tick % 3 + c.arp = if k == 1 then x elseif k == 2 then y else 0 + end + elseif fx == 1 then + if xm and param > 0 then + c.mPortaUp = param + end + if tick > 0 then + c.period -= (if xm then c.mPortaUp else param) * 4 + clampPeriod(st, c) + end + elseif fx == 2 then + if xm and param > 0 then + c.mPortaDn = param + end + if tick > 0 then + c.period += (if xm then c.mPortaDn else param) * 4 + clampPeriod(st, c) + end + elseif fx == 3 or fx == 5 then + if fx == 3 and param > 0 then + c.portaSpeed = param + end + if tick > 0 then + tonePorta(st, c, c.portaSpeed * 4) + end + elseif fx == 4 or fx == 6 then + if fx == 4 then + if x > 0 then + c.vibSpeed = x + end + if y > 0 then + c.vibDepth = y + end + end + if tick > 0 then + vibrato(st, c, 8 / 255) + end + elseif fx == 7 then + if x > 0 then + c.tremSpeed = x + end + if y > 0 then + c.tremDepth = y + end + if tick > 0 then + tremolo(c, 1 / 64) + end + elseif fx == 8 then + if tick == 0 then + c.pan = param + c.basePan = c.pan + c.surround = false + end + elseif fx == 0xB then + if tick == 0 then + st.jumpOrd = param + if st.breakRow < 0 then + st.breakRow = 0 + end + end + elseif fx == 0xC then + if tick == 0 then + c.vol = min(param, 64) + end + elseif fx == 0xD then + if tick == 0 then + local r = x * 10 + y + if r > 63 then + r = 0 + end + st.breakRow = r + end + elseif fx == 0xE then + if x == 1 then + if xm and y > 0 then + c.mFineUp = y + end + if tick == 0 then + c.period -= (if xm then c.mFineUp else y) * 4 + clampPeriod(st, c) + end + elseif x == 2 then + if xm and y > 0 then + c.mFineDn = y + end + if tick == 0 then + c.period += (if xm then c.mFineDn else y) * 4 + clampPeriod(st, c) + end + elseif x == 4 then + c.vibWave = y % 8 + elseif x == 6 then + if tick == 0 then + if y == 0 then + c.loopRow = st.row + elseif c.loopCount == 0 then + c.loopCount = y + st.loopJump = c.loopRow + st.ft2BreakPos = c.loopRow + else + c.loopCount -= 1 + if c.loopCount > 0 then + st.loopJump = c.loopRow + end + st.ft2BreakPos = c.loopRow + end + end + elseif x == 7 then + c.tremWave = y % 8 + elseif x == 8 then + if tick == 0 then -- FT2 ignores E8x in XM; OpenMPT (the reference) applies it + c.pan = y * 17 + c.basePan = c.pan + c.surround = false + end + elseif x == 9 then + if y > 0 and tick > 0 and tick % y == 0 then + retrigVoice(st, c) + end + elseif x == 0xA then + if xm and y > 0 then + c.mFineVolUp = y + end + if tick == 0 then + c.vol = min(64, c.vol + (if xm then c.mFineVolUp else y)) + end + elseif x == 0xB then + if xm and y > 0 then + c.mFineVolDn = y + end + if tick == 0 then + c.vol = max(0, c.vol - (if xm then c.mFineVolDn else y)) + end + elseif x == 0xC then + if tick == y then + c.vol = 0 + end + elseif x == 0xE then + if tick == 0 and st.patDelayRep == 0 and st.patDelay == 0 then + st.patDelay = y + end + end + elseif fx == 0xF then + if tick == 0 then + if param == 0 then + if not xm then + st.stopAfterRow = true -- ProTracker F00: the song stops (after this row, as OpenMPT plays it) + end + elseif param < 32 then + st.speed = param + else + st.tempo = param + end + end + elseif fx == 16 then -- G + if tick == 0 then + st.gvol = min(param, 64) * 2 + end + elseif fx == 17 then -- H + if param > 0 then + c.mGVolSlide = param + end + if tick > 0 then + local p = c.mGVolSlide + local px, py = p // 16, p % 16 + if px > 0 then + st.gvol = min(128, st.gvol + px * 2) + else + st.gvol = max(0, st.gvol - py * 2) + end + end + elseif fx == 20 then -- K + if tick == param then + keyOff(st, c.voice) + end + elseif fx == 21 then -- L + if tick == 0 and c.voice then + c.voice.volEnvPos = param + c.voice.panEnvPos = param + end + elseif fx == 25 then -- P + if param > 0 then + c.mPanSlide = param + end + if tick > 0 then + local p = c.mPanSlide + local px, py = p // 16, p % 16 + if px > 0 then + c.pan = min(255, c.pan + px) + c.basePan = c.pan + else + c.pan = max(0, c.pan - py) + c.basePan = c.pan + end + end + elseif fx == 27 then -- R + if x > 0 then + c.mRetrig = c.mRetrig % 16 + x * 16 + end + if y > 0 then + c.mRetrig = (c.mRetrig // 16) * 16 + y + end + local interval = c.mRetrig % 16 + if tick == 0 and c.triggered then + c.retrigCount = 0 + else + c.retrigCount += 1 + end + if interval > 0 and c.retrigCount >= interval then + c.retrigCount = 0 + retrigVolume(c, c.mRetrig // 16) + retrigVoice(st, c) + end + elseif fx == 29 then -- T + if param > 0 then + c.mTremor = param + end + elseif fx == 33 then -- X + if x == 1 then + if y > 0 then + c.mXFineUp = y + end + if tick == 0 then + c.period -= c.mXFineUp + clampPeriod(st, c) + end + elseif x == 2 then + if y > 0 then + c.mXFineDn = y + end + if tick == 0 then + c.period += c.mXFineDn + clampPeriod(st, c) + end + end + end + -- the volume slide half of 5xy / 6xy and Axy + if fx == 0xA or fx == 5 or fx == 6 then + if xm then + if param > 0 then + c.mVolSlide = param + end + if tick > 0 then + volSlideMod(c, c.mVolSlide) + end + elseif tick > 0 then + volSlideMod(c, param) + end + end + -- tremor (XM Txy): on x + 1 ticks, off y + 1 ticks + if fx == 29 and tick > 0 then + local on, off = c.mTremor // 16 + 1, c.mTremor % 16 + 1 + c.tremorCount %= on + off + c.tremorOn = c.tremorCount < on + c.tremorCount += 1 + end +end + +-- the XM volume column (everything but set volume / set panning, done by trigger) +local function volColXm(st: any, c: any, tick: number) + local v = c.vcmd + if v < 0x60 then + return + end + local hi, lo = v // 16, v % 16 + if hi == 6 then + if tick > 0 then + c.vol = max(0, c.vol - lo) + end + elseif hi == 7 then + if tick > 0 then + c.vol = min(64, c.vol + lo) + end + elseif hi == 8 then + if tick == 0 then + c.vol = max(0, c.vol - lo) + end + elseif hi == 9 then + if tick == 0 then + c.vol = min(64, c.vol + lo) + end + elseif hi == 0xA then + if lo > 0 then + c.vibSpeed = lo + end + elseif hi == 0xB then + if lo > 0 then + c.vibDepth = lo + end + if tick > 0 then + vibrato(st, c, 8 / 255) + end + elseif hi == 0xD then + if tick > 0 then + c.pan = max(0, c.pan - lo) + c.basePan = c.pan + end + elseif hi == 0xE then + if tick > 0 then + c.pan = min(255, c.pan + lo) + c.basePan = c.pan + end + elseif hi == 0xF then + if lo > 0 then + c.portaSpeed = lo * 16 + end + if tick > 0 then + tonePorta(st, c, c.portaSpeed * 4) + end + end +end + +-- ------------------------------------------------------------------------------------------------ S3M / IT effects +-- the parameter after memory: IT keeps one memory per effect group, ST3 one memory for most effects +local function mem(st: any, c: any, field: string, param: number): number + if st.fmt == S3M then + if param > 0 then + c.mS3M = param + end + return c.mS3M + end + if param > 0 then + c[field] = param + end + return c[field] +end + +local function portaS3m(st: any, c: any, p: number, tick: number, sign: number) + if p >= 0xF0 then + if tick == 0 then + c.period += sign * (p % 16) * 4 + end + elseif p >= 0xE0 then + if tick == 0 then + c.period += sign * (p % 16) + end + elseif tick > 0 then + c.period += sign * p * 4 + end + clampPeriod(st, c) +end + +local function fxS3mIt(st: any, c: any, tick: number) + local fx, param = c.fx, c.param + local it = st.fmt == IT + if fx == 1 then -- A speed + if tick == 0 and param > 0 then + st.speed = param + end + elseif fx == 2 then -- B jump + if tick == 0 then + st.jumpOrd = param + if st.breakRow < 0 then + st.breakRow = 0 + end + end + elseif fx == 3 then -- C break + if tick == 0 then + st.breakRow = if it then param else (param // 16) * 10 + param % 16 + end + elseif fx == 4 or fx == 11 or fx == 12 then -- D volume slide (K, L: + vibrato / tone portamento) + local p = mem(st, c, "mVolSlide", param) + c.vol = dSlide(c.vol, p, tick, st.fastSlides, 64) + elseif fx == 5 then -- E porta down + local p = mem(st, c, "mEF", param) + portaS3m(st, c, p, tick, 1) + elseif fx == 6 then -- F porta up + local p = mem(st, c, "mEF", param) + portaS3m(st, c, p, tick, -1) + elseif fx == 9 then -- I tremor + local p = mem(st, c, "mTremor", param) + if tick > 0 or not it then + local on, off = p // 16, p % 16 + if it and st.oldFx or not it then + on, off = on + 1, off + 1 + end + on, off = max(on, 1), max(off, 1) + c.tremorCount %= on + off + c.tremorOn = c.tremorCount < on + c.tremorCount += 1 + end + elseif fx == 10 then -- J arpeggio + local p = mem(st, c, "mArp", param) + local k = tick % 3 + c.arp = if k == 1 then p // 16 elseif k == 2 then p % 16 else 0 + elseif fx == 13 then -- M channel volume + if tick == 0 and param <= 64 then + c.chanVol = param + end + elseif fx == 14 then -- N channel volume slide + local p = mem(st, c, "mChanVolSlide", param) + c.chanVol = dSlide(c.chanVol, p, tick, false, 64) + elseif fx == 16 then -- P panning slide (0..64 scale x 4) + local p = mem(st, c, "mPanSlide", param) + local pan64 = c.pan / 4 + local x, y = p // 16, p % 16 + if y == 0xF and x > 0 then + if tick == 0 then + pan64 = max(0, pan64 - x) + end + elseif x == 0xF and y > 0 then + if tick == 0 then + pan64 = min(64, pan64 + y) + end + elseif tick > 0 then + if y == 0 then + pan64 = max(0, pan64 - x) + elseif x == 0 then + pan64 = min(64, pan64 + y) + end + end + c.pan = pan64 * 4 + c.basePan = c.pan + c.surround = false + elseif fx == 17 then -- Q retrigger + volume change + local p = mem(st, c, "mRetrig", param) + local interval = p % 16 + if interval > 0 then + if tick == 0 and c.retrigCount <= 0 then + c.retrigCount = interval + end + if tick > 0 then + c.retrigCount -= 1 + if c.retrigCount <= 0 then + c.retrigCount = interval + retrigVolume(c, p // 16) + retrigVoice(st, c) + end + end + end + elseif fx == 18 then -- R tremolo + if param // 16 > 0 then + c.tremSpeed = param // 16 + end + if param % 16 > 0 then + c.tremDepth = param % 16 + end + if tick > 0 then + tremolo(c, 1 / 64) + end + elseif fx == 19 then -- S extended + local p = if it then mem(st, c, "mS", param) else mem(st, c, "mS", param) + local x, y = p // 16, p % 16 + if x == 3 then + c.vibWave = y % 8 + elseif x == 4 then + c.tremWave = y % 8 + elseif x == 5 then + c.panbWave = y % 8 + elseif x == 6 then + if tick == 0 then + st.fineDelay += y + end + elseif x == 7 then + if tick == 0 then + if y <= 2 then + for _, u in st.voices do + if u.active and u.bg and u.chan == c.idx then + if y == 0 then + cutVoice(u) + elseif y == 1 then + keyOff(st, u) + else + noteFade(u) + end + end + end + elseif y <= 6 then + c.nna = y - 3 + else + local v = c.voice + if v then + if y == 7 then + v.volEnvOn = false + elseif y == 8 then + v.volEnvOn = true + elseif y == 9 then + v.panEnvOn = false + elseif y == 10 then + v.panEnvOn = true + elseif y == 11 then + v.pitchEnvOn = false + elseif y == 12 then + v.pitchEnvOn = true + end + end + end + end + elseif x == 8 then + if tick == 0 then + c.pan = y * 17 + c.basePan = c.pan + c.surround = false + end + elseif x == 9 then + if tick == 0 and y == 1 then + c.surround = true + end + elseif x == 0xA then + if tick == 0 then + c.mHighOffset = y + end + elseif x == 0xB then + if tick == 0 then + if y == 0 then + c.loopRow = st.row + elseif c.loopCount == 0 then + c.loopCount = y + st.loopJump = c.loopRow + else + c.loopCount -= 1 + if c.loopCount > 0 then + st.loopJump = c.loopRow + elseif it then + c.loopRow = st.row + 1 + end + end + end + elseif x == 0xC then + local at = if y == 0 and it then 1 else y + if tick == at and (y > 0 or it) then + if it then + cutVoice(c.voice) + end + c.vol = 0 + end + elseif x == 0xE then + if tick == 0 and st.patDelayRep == 0 and st.patDelay == 0 then + st.patDelay = y + end + end + elseif fx == 20 then -- T tempo + if param >= 0x20 then + if tick == 0 then + st.tempo = param + end + elseif it then + if param > 0 then + c.mTempo = param + end + local p = c.mTempo + if tick > 0 then + if p >= 0x10 then + st.tempo = min(255, st.tempo + (p - 0x10)) + else + st.tempo = max(32, st.tempo - p) + end + end + end + elseif fx == 22 then -- V global volume + if tick == 0 then + if it then + if param <= 128 then + st.gvol = param + end + else + st.gvol = min(param, 64) * 2 + end + end + elseif fx == 23 then -- W global volume slide + local p = mem(st, c, "mGVolSlide", param) + st.gvol = dSlide(st.gvol, p, tick, false, 128) + elseif fx == 24 then -- X panning + if tick == 0 then + if it then + c.pan = param + c.basePan = c.pan + c.surround = false + elseif param <= 0x80 then + c.pan = param * 2 + c.basePan = c.pan + c.surround = false + elseif param == 0xA4 then + c.surround = true + end + end + elseif fx == 25 then -- Y panbrello + if param // 16 > 0 then + c.panbSpeed = param // 16 + end + if param % 16 > 0 then + c.panbDepth = param % 16 + end + c.panbDelta = wave64(c.panbWave % 4, c.panbPos // 4) * c.panbDepth / 16 + c.panbPos = (c.panbPos + c.panbSpeed) % 256 + elseif fx == 26 then -- Z MIDI macro: the default IT macros (Z00..Z7F cutoff, Z80..Z8F resonance) + if tick == 0 then + if param < 0x80 then + c.cutoff = param + elseif param < 0x90 then + c.reso = (param - 0x80) * 8 + end + if c.voice then + c.voice.cutoff, c.voice.reso = c.cutoff, c.reso + end + end + end + -- tone portamento (G, L) + if fx == 7 or fx == 12 then + if fx == 7 then + if st.fmt == S3M then + if param > 0 then + c.portaSpeed = param + end + elseif st.compatG then + if param > 0 then + c.portaSpeed = param + end + else + if param > 0 then + c.mEF = param + end + c.portaSpeed = c.mEF + end + end + if tick > 0 then + tonePorta(st, c, c.portaSpeed * 4) + end + end + -- vibrato (H, U, K) + if fx == 8 or fx == 21 or fx == 11 then + if fx ~= 11 then + if param // 16 > 0 then + c.vibSpeed = param // 16 + end + if param % 16 > 0 then + c.vibDepth = param % 16 + end + end + local scale = if fx == 21 then 2 / 255 else 8 / 255 + if it and not st.oldFx then + scale /= 2 + end + if tick > 0 or (it and not st.oldFx) then + vibrato(st, c, scale) + end + end +end + +-- the IT volume column (value stored + 1): slides, portamento, vibrato +local function volColIt(st: any, c: any, tick: number) + local v = c.vcmd - 1 + if v < 65 then + return + end + if v <= 74 then + local p = v - 65 + if p > 0 then + c.mVolCol = p + end + if tick == 0 then + c.vol = min(64, c.vol + c.mVolCol) + end + elseif v <= 84 then + local p = v - 75 + if p > 0 then + c.mVolCol = p + end + if tick == 0 then + c.vol = max(0, c.vol - c.mVolCol) + end + elseif v <= 94 then + local p = v - 85 + if p > 0 then + c.mVolCol = p + end + if tick > 0 then + c.vol = min(64, c.vol + c.mVolCol) + end + elseif v <= 104 then + local p = v - 95 + if p > 0 then + c.mVolCol = p + end + if tick > 0 then + c.vol = max(0, c.vol - c.mVolCol) + end + elseif v <= 114 then + local p = (v - 105) * 4 + if p > 0 then + c.mEF = p + end + if tick > 0 then + c.period += c.mEF * 4 + clampPeriod(st, c) + end + elseif v <= 124 then + local p = (v - 115) * 4 + if p > 0 then + c.mEF = p + end + if tick > 0 then + c.period -= c.mEF * 4 + clampPeriod(st, c) + end + elseif v >= 193 and v <= 202 then + local p = Tables.IT_VOLPORTA[v - 192] or 0 + if p > 0 then + if st.compatG then + c.portaSpeed = p + else + c.mEF = p + c.portaSpeed = p + end + end + if tick > 0 then + tonePorta(st, c, c.portaSpeed * 4) + end + elseif v >= 203 and v <= 212 then + local d = v - 203 + if d > 0 then + c.vibDepth = d + end + if tick > 0 or not st.oldFx then + vibrato(st, c, if st.oldFx then 8 / 255 else 4 / 255) + end + end +end + +-- ------------------------------------------------------------------------------------------------ rows and ticks +local function noteDelayOf(st: any, fx: number, param: number): number + if (st.fmt == MOD or st.fmt == XM) and fx == 0xE and param // 16 == 0xD then + return param % 16 + elseif (st.fmt == S3M or st.fmt == IT) and fx == 19 and param // 16 == 0xD then + return param % 16 + end + return 0 +end + +local function finetuneOf(st: any, fx: number, param: number): number? + if (st.fmt == MOD or st.fmt == XM) and fx == 0xE and param // 16 == 5 then + local y = param % 16 + if st.fmt == MOD then + return (if y >= 8 then y - 16 else y) * 16 + end + return (y - 8) * 16 + end + return nil +end + +local function runEffects(st: any, c: any, tick: number) + c.vibDelta, c.arp = 0, 0 + if st.fmt == MOD or st.fmt == XM then + fxModXm(st, c, tick) + if st.fmt == XM then + volColXm(st, c, tick) + end + else + if st.fmt == IT then + volColIt(st, c, tick) + end + fxS3mIt(st, c, tick) + end + -- keep the tremolo / panbrello offsets only while their effect runs + local fx = c.fx + if st.fmt == MOD or st.fmt == XM then + if fx ~= 7 then + c.tremDelta = 0 + end + -- XM: a tremor that ends in its off phase keeps the channel silent until the next note (OpenMPT / FT2) + else + if fx ~= 18 then + c.tremDelta = 0 + end + if fx ~= 9 then + c.tremorOn = true + end + if fx ~= 25 then + c.panbDelta = 0 + end + end +end + +local function processRow(st: any) + local m = st.m + local pat = st.pat + local nch = st.nch + local data = pat.data + local base = st.row * nch * 5 + st.visited[st.ord * 1024 + st.row] = true + st.rows += 1 + for i = 1, nch do + local c = st.chans[i] + local o = base + (i - 1) * 5 + local note, ins, vcmd, fx, param = readu8(data, o), readu8(data, o + 1), readu8(data, o + 2), readu8(data, o + 3), readu8(data, o + 4) + if (st.fmt == MOD or st.fmt == XM) and fx == 0 and param == 0 then + fx = 255 + end + c.fx, c.param, c.vcmd = fx, param, vcmd + c.cutTick, c.keyOffTick = -1, -1 + c.triggered = false + local delay = noteDelayOf(st, fx, param) + c.finetune = finetuneOf(st, fx, param) + if delay > 0 then + c.delayTick, c.dNote, c.dIns, c.dVol = delay, note, ins, vcmd + else + c.delayTick = -1 + trigger(st, c, note, ins, vcmd) + end + runEffects(st, c, 0) + end + local _ = m +end + +local function updateEnvelope(env: any, pos: number, keyOn: boolean, it: boolean): (number, number, boolean) + -- returns value, next position, ended + local ticks, values = env.ticks, env.values + local n = #ticks + if n == 0 then + return 0, pos, true + end + local value + if pos <= ticks[1] then + value = values[1] + elseif pos >= ticks[n] then + value = values[n] + else + local i = 1 + while i < n and ticks[i + 1] <= pos do + i += 1 + end + local t0, t1 = ticks[i], ticks[i + 1] + if t1 > t0 then + value = values[i] + (values[i + 1] - values[i]) * (pos - t0) / (t1 - t0) + else + value = values[i + 1] + end + end + local nextPos = pos + 1 + local ended = false + -- sustain / loop: only when the position runs over the end point (a position set past it, by Lxx, runs on) + -- FT2 jumps when the position reaches the end tick (its value is not played: a loop lasts end - start ticks), + -- IT after playing it (end - start + 1 ticks) + local se, le = ticks[env.susEnd], ticks[env.loopEnd] + local over = if it then 1 else 0 + if keyOn and env.sustain and se and pos <= se and nextPos >= se + over then + nextPos = ticks[env.susStart] or nextPos + elseif env.loop and le and pos <= le and nextPos >= le + over then + nextPos = ticks[env.loopStart] or nextPos + elseif nextPos > ticks[n] then + nextPos = ticks[n] + ended = true + end + return value, nextPos, ended +end + +-- per-tick voice update: envelopes, fadeout, auto-vibrato, final frequency, gains and filter +local function updateVoice(st: any, v: any) + local ins = v.ins + local it = st.fmt == IT + local envVol, envPan, envPitch = 64, 0, 0 + local filterEnv = nil + if ins then + local e = ins.volEnv + if e and e.enabled and v.volEnvOn then + local val, np, ended = updateEnvelope(e, v.volEnvPos, v.keyOn, it) + envVol, v.volEnvPos = val, np + if ended and it then + if val <= 0 then + v.active = false + return + end + v.fading = true + end + end + e = ins.panEnv + if e and e.enabled and v.panEnvOn then + local val, np = updateEnvelope(e, v.panEnvPos, v.keyOn, it) + envPan, v.panEnvPos = val, np + end + e = ins.pitchEnv + if e and e.enabled and v.pitchEnvOn then + local val, np = updateEnvelope(e, v.pitchEnvPos, v.keyOn, it) + v.pitchEnvPos = np + if e.filter then + filterEnv = val + else + envPitch = val + end + end + if v.fading then + local fo = ins.fadeout or 0 + v.fade -= if it then fo * 64 else fo * 2 + if v.fade <= 0 then + v.fade = 0 + v.active = false + return + end + end + end + v.envVol = envVol + -- auto-vibrato: XM per instrument, IT per sample + local avSrc = if it then v.smp else ins + local avDelta = 0 + if avSrc and (avSrc.vibDepth or 0) > 0 then + local depth = avSrc.vibDepth + local sweep = avSrc.vibSweep or 0 + if it then + -- IT: the depth ramps up by the rate (vibSweep here) every tick, in 1/256 steps + local target = depth * 256 + if sweep == 0 then + v.avAmp = target + elseif v.avAmp < target then + v.avAmp = min(target, v.avAmp + sweep) + end + avDelta = autoWave(avSrc.vibType or 0, v.avPos, true) * v.avAmp / (256 * 64) * 4 + else + if sweep == 0 then + v.avAmp = depth * 256 + elseif v.keyOn then + v.avAmp = min(depth * 256, v.avAmp + depth * 256 / sweep) + end + avDelta = autoWave(avSrc.vibType or 0, v.avPos, false) * v.avAmp / (256 * 64) + end + v.avPos = (v.avPos + (avSrc.vibRate or 0)) % 256 + end + -- frequency + local P = v.periodOut + avDelta + local freq + if st.linear then + freq = v.base * 2 ^ (-P / 768) + else + freq = if P > 0 then st.amiga / P else 0 + end + if envPitch ~= 0 then + freq *= 2 ^ (envPitch / 24) + end + v.inc = freq / st.sr + -- volume + local smp = v.smp + local vol = v.vol / 64 * envVol / 64 * v.fade / 65536 * st.gvol / 128 + if it then + vol *= v.chanVol / 64 * (if smp then (smp.globalVolume or 64) / 64 else 1) * (if ins then (ins.globalVolume or 128) / 128 else 1) + end + if v.tremorMute then + vol = 0 + end + -- panning + local pan = v.pan + if it and ins and (ins.pps or 0) ~= 0 then + pan = clamp(pan + ((v.patNote or v.note) - (ins.ppc or 60) - 1) * ins.pps / 2, 0, 256) + end + if envPan ~= 0 then + local range = 128 - abs(pan - 128) + pan += envPan * range / 32 + end + pan = clamp(pan, 0, 256) + pan = clamp(128 + (pan - 128) * st.separation, 0, 256) + local g = vol * st.master + if v.surround then + v.tl, v.tr = g * 0.5, -g * 0.5 + else + v.tl, v.tr = g * (256 - pan) / 256, g * pan / 256 + end + v.rampN = st.ramp + -- IT resonant filter + local cutoff = v.cutoff + if filterEnv ~= nil or cutoff < 127 or v.reso > 0 then + local cc = cutoff + if filterEnv ~= nil then + cc = cutoff * (filterEnv + 32) / 64 + end + local fhz = 110 * 2 ^ (0.25 + cc / 24) + fhz = clamp(fhz, 120, min(20000, st.sr / 2)) + local dmp = 10 ^ (-v.reso * (24 / 128) / 20) + local fc = fhz * 2 * math.pi / st.sr + local d = (1 - 2 * dmp) * fc + if d > 2 then + d = 2 + end + d = (2 * dmp - d) / fc + local e = 1 / (fc * fc) + local den = 1 + d + e + v.fa, v.fb0, v.fb1 = 1 / den, (d + e + e) / den, -e / den + v.fOn = not (cc >= 127 and v.reso == 0) + else + v.fOn = false + end +end + +-- tick(st) -> frames to mix for this tick (0 when the song ended) +function Player.tick(st: any): number + if st.ended then + return 0 + end + local tick = st.tick + if tick == 0 and st.patDelayRep == 0 then + local key = st.ord * 1024 + st.row + if st.visited[key] and not st.loopAllowed then + st.ended = true + return 0 + end + if st.visited[key] then + -- looping on: forget the song so far, keep playing + table.clear(st.visited) + end + st.fineDelay = 0 + processRow(st) + else + local t = tick % st.speed + local rep = tick >= st.speed or st.patDelayRep > 0 + for i = 1, st.nch do + local c = st.chans[i] + if c.delayTick == tick and not rep then + c.delayTick = -1 + trigger(st, c, c.dNote, c.dIns, c.dVol) + end + if rep and t == 0 then + c.vibDelta, c.arp = 0, 0 + else + runEffects(st, c, if t == 0 then 1 else t) + end + end + end + if st.ended then + return 0 + end + -- channel -> foreground voice + for i = 1, st.nch do + local c = st.chans[i] + local v = c.voice + if v and v.active and v.chan == i and not v.bg then + local P = arpPeriod(st, c.period, c.arp) + c.vibDelta + v.period, v.periodOut, v.base = c.period, P, c.base + v.vol = clamp(c.vol + c.tremDelta, 0, 64) + if c.muted then + v.vol = 0 + end + v.pan = clamp(c.pan + c.panbDelta, 0, 256) + v.surround = c.surround + v.chanVol = c.chanVol + v.tremorMute = not c.tremorOn + v.cutoff, v.reso = c.cutoff, c.reso + end + end + for _, v in st.voices do + if v.active then + updateVoice(st, v) + end + end + -- frames for this tick: 2.5 / tempo seconds, truncated per tick (as OpenMPT does) + local frames = floor(st.sr * 2.5 / max(1, st.tempo)) + -- advance + st.tick += 1 + if st.tick >= st.speed + st.fineDelay then + st.tick = 0 + if st.patDelayRep < st.patDelay then + st.patDelayRep += 1 + else + st.patDelay, st.patDelayRep = 0, 0 + advanceRow(st) + end + end + return frames +end + +return Player diff --git a/src/Formats/codecs/Tracker/Tables.luau b/src/Formats/codecs/Tracker/Tables.luau new file mode 100644 index 0000000..c621ec1 --- /dev/null +++ b/src/Formats/codecs/Tracker/Tables.luau @@ -0,0 +1,113 @@ +--!strict +--!native +-- codecs/Tracker/Tables: lookup tables of the tracker engine. Waveforms for vibrato / tremolo / panbrello and the +-- auto-vibrato, the ProTracker period table (finetune 0, used to map MOD periods to notes and back) and the IT / S3M +-- volume-column tone-portamento and retrigger tables. All values are from the public format documents (ProTracker +-- 2.3 effect docs, FT2 / XM spec, ST3 TECH.DOC, ITTECH.TXT). +local Tables = {} + +-- the ProTracker half-sine (32 steps, 0..255) +local SINE32 = { 0, 24, 49, 74, 97, 120, 141, 161, 180, 197, 212, 224, 235, 244, 250, 253, 255, 253, 250, 244, 235, 224, 212, 197, 180, 161, 141, 120, 97, 74, 49, 24 } + +-- wave64(type, pos) -> -255..255 for pos 0..63: 0 sine, 1 ramp down, 2 square, 3 random (deterministic) +local RANDOM: { number } = {} +do + local s = 12345 + for i = 1, 64 do + s = (s * 1103515245 + 12345) % 2147483648 + RANDOM[i] = (s // 65536) % 511 - 255 + end +end +function Tables.wave64(kind: number, pos: number): number + local p = pos % 64 + if kind == 1 then + return 255 - p * 8 + elseif kind == 2 then + return if p < 32 then 255 else -255 + elseif kind == 3 then + return RANDOM[p + 1] + end + local v = SINE32[(p % 32) + 1] + return if p >= 32 then -v else v +end + +-- autoWave(type, pos, it) -> -64..64 for pos 0..255. XM: 0 sine, 1 square, 2 ramp down, 3 ramp up. +-- IT: 0 sine, 1 ramp down, 2 square, 3 random. +local SINE256: { number } = {} +for i = 0, 255 do + SINE256[i + 1] = math.floor(math.sin(i * math.pi / 128) * 64 + 0.5) +end +function Tables.autoWave(kind: number, pos: number, it: boolean): number + local p = pos % 256 + if it then + if kind == 1 then + return 64 - (p + 1) // 2 + elseif kind == 2 then + return if p < 128 then 64 else -64 + elseif kind == 3 then + return RANDOM[(p % 64) + 1] // 4 + end + return SINE256[p + 1] + end + if kind == 1 then + return if p < 128 then 64 else -64 + elseif kind == 2 then + return 64 - (p + 1) // 2 + elseif kind == 3 then + return (p + 1) // 2 - 64 + end + return SINE256[p + 1] +end + +-- ProTracker periods, finetune 0, C-0 .. B-4 (60 notes; ProTracker itself uses C-1 .. B-3). Our note numbers: +-- 1 = C-0 (FT2 numbering), so ProTracker C-1 (856) = note 37 and C-2 (428) = note 49, the note that plays a sample at +-- its base rate (8363 Hz). +local PERIODS = { + 3424, 3232, 3048, 2880, 2712, 2560, 2416, 2280, 2152, 2032, 1920, 1812, + 1712, 1616, 1524, 1440, 1356, 1280, 1208, 1140, 1076, 1016, 960, 906, + 856, 808, 762, 720, 678, 640, 604, 570, 538, 508, 480, 453, + 428, 404, 381, 360, 339, 320, 302, 285, 269, 254, 240, 226, + 214, 202, 190, 180, 170, 160, 151, 143, 135, 127, 120, 113, + 107, 101, 95, 90, 85, 80, 75, 71, 67, 63, 60, 56, +} +Tables.PERIODS = PERIODS +Tables.PERIOD_FIRST_NOTE = 13 -- PERIODS[1] is note 13 (C-1 in FT2 numbering = ProTracker octave -1) + +-- periodToNote(period) -> note (1..120), 0 for period 0 +function Tables.periodToNote(period: number): number + if period <= 0 then + return 0 + end + -- exact match first, then the nearest note on a log scale + for i = 1, #PERIODS do + if PERIODS[i] == period then + return i + Tables.PERIOD_FIRST_NOTE - 1 + end + end + local n = 49 + math.floor(12 * math.log(428 / period) / math.log(2) + 0.5) + return math.clamp(n, 1, 120) +end + +-- noteToPeriod(note) -> ProTracker period (finetune 0) for a note, computed past the table's ends +function Tables.noteToPeriod(note: number): number + local i = note - Tables.PERIOD_FIRST_NOTE + 1 + if i >= 1 and i <= #PERIODS then + return PERIODS[i] + end + return math.max(1, math.floor(428 * 2 ^ ((49 - note) / 12) + 0.5)) +end + +-- IT volume column "g" (tone portamento) speeds +Tables.IT_VOLPORTA = { 0, 1, 4, 8, 16, 32, 64, 96, 128, 255 } + +-- XM Rxy / S3M-IT Qxy volume changes: kind 0 add, 1 multiply; value +Tables.RETRIG_ADD = { 0, -1, -2, -4, -8, -16, 0, 0, 0, 1, 2, 4, 8, 16, 0, 0 } +Tables.RETRIG_MUL = { 1, 1, 1, 1, 1, 1, 2 / 3, 0.5, 1, 1, 1, 1, 1, 1, 1.5, 2 } + +-- the Amiga clock constant: frequency = AMIGA / period, with period 1712 playing an 8363 Hz sample at its base rate +-- (FT2 / ST3 period units, 4x ProTracker's) +Tables.AMIGA = 8363 * 1712 +-- MOD: the PAL Amiga clock (7093789.2 Hz / 2 per ProTracker period unit; period 428 plays at 8287 Hz) +Tables.AMIGA_PAL = 7093789.2 / 2 * 4 + +return Tables diff --git a/src/Formats/codecs/Tracker/init.luau b/src/Formats/codecs/Tracker/init.luau new file mode 100644 index 0000000..391ea94 --- /dev/null +++ b/src/Formats/codecs/Tracker/init.luau @@ -0,0 +1,516 @@ +--!strict +-- codecs/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it. The four loaders read +-- their files into one Module structure (below); render(module, opts) plays any of them through the standard audio +-- Decoder (Types.Decoder: stereo f32). Written for this library from the format documents (ProTracker 2.3, the XM +-- spec + FT2 behaviour, ST3 TECH.DOC, ITTECH.TXT); libxmp / OpenMPT were used only as reference players for tests. +-- +-- local Tracker = require("@formats/codecs/Tracker") +-- local dec, err = Tracker.render(module, { sampleRate = 44100 }) -- a Types.Decoder +-- local seconds = Tracker.duration(module) -- one pass, song loops detected +-- +-- Module (Types.Module plus the engine fields; pattern / instrument / sample numbers are as in the file): +-- format "mod" | "s3m" | "xm" | "it": selects the effect family and the format quirks +-- title, channels, speed (ticks per row), tempo (BPM: a tick lasts 2.5 / tempo s) +-- globalVolume 0..128 (S3M / XM 0..64 are stored doubled), mixVolume 0..128 (IT mix volume, S3M master volume) +-- order { pattern number (0-based) | 254 skip ("+++") | 255 end ("---") }, restart (0-based order index) +-- linear linear frequency slides (XM / IT flag) or Amiga periods +-- instrumentMode XM, IT with instruments: notes go through Instrument keymaps; otherwise the instrument column +-- is a sample number (MOD, S3M, IT sample mode) +-- flags { oldEffects, compatGxx (IT), fastSlides (ST3.00 volume slides), amigaLimits (MOD) } +-- channelPan { 0..256 per channel (128 centre; 512 = surround); MOD: 64 / 192 (Amiga L R R L at half width, +-- as OpenMPT plays it; set 0 / 256 or render with stereoSeparation = 200 for hard panning) }, channelVolume { 0..64 }, channelMute { bool } +-- patterns { Pattern } (pattern n at patterns[n + 1]); Pattern = { rows, data }: data holds rows * channels +-- cells of 5 bytes: note, instrument, volume column, effect, parameter. Notes: 0 none, 1..120 (1 = +-- C-0; C-4 = 49 plays an XM / MOD sample at its base rate, C-5 = 61 an S3M / IT sample at its C5 +-- speed), 253 note fade, 254 note cut, 255 key off. The volume column and effects are kept in the +-- file's own coding: MOD / XM effects 0..35 (XM letters G.. = 16..), XM volume byte as stored; +-- S3M / IT effects 1..26 (A = 1), S3M volume 0 = none else volume + 1, IT volume byte + 1 +-- (0 = none). Tracker.cell / Tracker.setCell read and write cells. +-- samples { Sample }: { name, data (f32, interleaved when stereo), length (frames), channels, bits (8 | 16, +-- for writers), loopStart, loopEnd (frames, end exclusive), loopType (0 none, 1 forward, 2 ping-pong), +-- susStart, susEnd, susType (IT sustain loop), volume 0..64, globalVolume 0..64, pan (0..256 or nil), +-- c5speed (S3M / IT), relativeNote, finetune -128..127 (MOD / XM), vibType / vibSweep / vibDepth / +-- vibRate (IT auto-vibrato) } +-- instruments { Instrument }: { name, sampleMap = { [note] = sample number }, noteMap = { [note] = note }, +-- volEnv / panEnv / pitchEnv (Envelope?), fadeout (as stored: XM 0..4095, IT 0..1024), nna (0 cut, +-- 1 continue, 2 note off, 3 fade), dct (0 off, 1 note, 2 sample, 3 instrument), dca (0 cut, 1 off, +-- 2 fade), globalVolume 0..128, pan (0..256 or nil), pps, ppc (pitch-pan separation / centre), +-- cutoff, resonance (0..127 or nil), vibType / vibSweep / vibDepth / vibRate (XM auto-vibrato) } +-- Envelope { enabled, ticks = { tick }, values = { volume 0..64 | pan / pitch -32..32 }, loop, loopStart, +-- loopEnd, sustain, susStart, susEnd (1-based point indexes), filter (IT pitch envelope as filter) } +-- +-- Pitch: two period spaces. Linear: P = (ref - note) * 64 - transpose (64 per semitone), frequency = base * 2^(-P/768). +-- Amiga: P = 1712 * 8363 / base * 2^(Plinear / 768), frequency = 8363 * 1712 / P (FT2 / ST3 period units; slides add +-- 4 per effect unit in both). MOD / XM: base 8363, ref 49, transpose = relativeNote * 64 + finetune / 2; S3M / IT: +-- base = c5speed, ref 61. +-- +-- Not supported: MIDI macros other than IT's default filter macros (Z00..Z8F), glissando, ST3 / IT finetune effects +-- (S2x), random volume / pan variation, OPL (AdLib) instruments, MOD Amiga low-pass filter emulation. +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Player = require("@formats/codecs/Tracker/Player") +local Mixer = require("@formats/codecs/Tracker/Mixer") +local Pcm = require("@formats/codecs/Tracker/Pcm") +local Tables = require("@formats/codecs/Tracker/Tables") + +local Tracker = {} + +Tracker.Pcm = Pcm +Tracker.Tables = Tables + +export type Envelope = { + enabled: boolean, + ticks: { number }, + values: { number }, + loop: boolean, + loopStart: number, + loopEnd: number, + sustain: boolean, + susStart: number, + susEnd: number, + carry: boolean?, + filter: boolean?, + raw: any?, -- format-specific fields kept for a faithful re-save (XM) +} + +export type Pattern = { rows: number, data: buffer } + +export type RenderOptions = { + sampleRate: number?, -- default 44100 + interpolation: ("linear" | "none")?, -- default "linear" + stereoSeparation: number?, -- 0..200 % (default 100: the panning as stored; 200 doubles every distance from centre) + loop: boolean?, -- keep playing past the song's end (frames / duration still give one pass); default false + maxDuration: number?, -- seconds; the render stops there (default 3600) +} + +local CELL = 5 + +-- ------------------------------------------------------------------------------------------------ constructors +-- newModule(format, channels) -> an empty Module (no patterns / samples) with the format's defaults +function Tracker.newModule(format: string, channels: number): any + local m = { + kind = "music", + format = format, + title = "", + channels = channels, + speed = 6, + tempo = 125, + globalVolume = 128, + mixVolume = 48, + order = {}, + restart = 0, + linear = format == "xm" or format == "it", + instrumentMode = format == "xm" or format == "it", + flags = {}, + channelPan = {}, + channelVolume = {}, + channelMute = {}, + patterns = {}, + instruments = {}, + samples = {}, + meta = {}, + render = Tracker.renderMethod, + } + for i = 1, channels do + m.channelVolume[i] = 64 + if format == "mod" then + local k = (i - 1) % 4 + m.channelPan[i] = if k == 0 or k == 3 then 64 else 192 -- the Amiga's L R R L, at OpenMPT's default width + else + m.channelPan[i] = 128 + end + end + return m +end + +-- newPattern(rows, channels) -> an empty Pattern +function Tracker.newPattern(rows: number, channels: number): Pattern + return { rows = rows, data = buffer.create(rows * channels * CELL) } +end + +-- newSample() -> an empty Sample +function Tracker.newSample(name: string?): any + return { + name = name or "", + data = buffer.create(0), + length = 0, + channels = 1, + bits = 8, + loopStart = 0, + loopEnd = 0, + loopType = 0, + susStart = 0, + susEnd = 0, + susType = 0, + volume = 64, + globalVolume = 64, + pan = nil :: number?, + c5speed = 8363, + relativeNote = 0, + finetune = 0, + vibType = 0, + vibSweep = 0, + vibDepth = 0, + vibRate = 0, + } +end + +function Tracker.newEnvelope(): Envelope + return { enabled = false, ticks = {}, values = {}, loop = false, loopStart = 1, loopEnd = 1, sustain = false, susStart = 1, susEnd = 1 } +end + +-- newInstrument() -> an Instrument mapping every note to sample 0 (none) +function Tracker.newInstrument(name: string?): any + local sm, nm = table.create(120, 0), table.create(120, 0) + for i = 1, 120 do + nm[i] = i + end + return { + name = name or "", + sampleMap = sm, + noteMap = nm, + volEnv = nil :: Envelope?, + panEnv = nil :: Envelope?, + pitchEnv = nil :: Envelope?, + fadeout = 0, + nna = 0, + dct = 0, + dca = 0, + globalVolume = 128, + pan = nil :: number?, + pps = 0, + ppc = 60, + cutoff = nil :: number?, + resonance = nil :: number?, + vibType = 0, + vibSweep = 0, + vibDepth = 0, + vibRate = 0, + } +end + +-- cell(module, pattern, row, channel) -> note, instrument, volume, effect, parameter (pattern 0-based, row 0-based, +-- channel 1-based); nil when out of range +function Tracker.cell(m: any, pattern: number, row: number, channel: number): (number?, number, number, number, number) + local p = m.patterns[pattern + 1] + if not p or row < 0 or row >= p.rows or channel < 1 or channel > m.channels then + return nil, 0, 0, 0, 0 + end + local o = (row * m.channels + channel - 1) * CELL + local d = p.data + return buffer.readu8(d, o), buffer.readu8(d, o + 1), buffer.readu8(d, o + 2), buffer.readu8(d, o + 3), buffer.readu8(d, o + 4) +end + +-- setCell(module, pattern, row, channel, note, instrument, volume, effect, parameter) -> true | false (out of range) +function Tracker.setCell(m: any, pattern: number, row: number, channel: number, note: number, ins: number, vol: number, fx: number, param: number): boolean + local p = m.patterns[pattern + 1] + if not p or row < 0 or row >= p.rows or channel < 1 or channel > m.channels then + return false + end + local o = (row * m.channels + channel - 1) * CELL + local d = p.data + buffer.writeu8(d, o, note % 256) + buffer.writeu8(d, o + 1, ins % 256) + buffer.writeu8(d, o + 2, vol % 256) + buffer.writeu8(d, o + 3, fx % 256) + buffer.writeu8(d, o + 4, param % 256) + return true +end + +-- ------------------------------------------------------------------------------------------------ validation +local function num(v: any, lo: number, hi: number): boolean + return type(v) == "number" and v == v and v >= lo and v <= hi +end + +local function fixEnvelope(e: any): (any, string?) + if e == nil then + return nil + end + if type(e) ~= "table" or type(e.ticks) ~= "table" or type(e.values) ~= "table" then + return nil, "bad envelope" + end + local n = math.min(#e.ticks, #e.values) + local last = -1 + for i = 1, n do + local t, v = e.ticks[i], e.values[i] + if not num(t, 0, 1e6) or not num(v, -64, 64) or t <= last then + -- points must go forward: keep the valid prefix + n = i - 1 + break + end + last = t + end + for i = #e.ticks, n + 1, -1 do + e.ticks[i] = nil + end + for i = #e.values, n + 1, -1 do + e.values[i] = nil + end + if n == 0 then + e.enabled = false + end + local function idx(v: any): number + return if num(v, 1, math.max(1, n)) then math.floor(v) else 1 + end + e.loopStart, e.loopEnd = idx(e.loopStart), idx(e.loopEnd) + e.susStart, e.susEnd = idx(e.susStart), idx(e.susEnd) + if e.loopEnd < e.loopStart then + e.loop = false + end + if e.susEnd < e.susStart then + e.sustain = false + end + return e +end + +local function fixLoop(s0: any, e0: any, t0: any, len: number): (number, number, number) + if not num(t0, 0, 2) or t0 == 0 or not num(s0, -2 ^ 52, 2 ^ 52) or not num(e0, -2 ^ 52, 2 ^ 52) then + return 0, 0, 0 + end + local s: number = math.floor(math.clamp(s0, 0, len)) + local e: number = math.floor(math.clamp(e0, 0, len)) + local t: number = math.floor(t0) + if e - s < 1 or t == 0 then + return 0, 0, 0 + end + if t == 2 and e - s < 2 then + t = 1 + end + return s, e, t +end + +-- validate(module) -> true | nil, Err: checks the structure the engine relies on, clamps loops, envelopes and +-- numbers into range (in place) +function Tracker.validate(m: any): (boolean?, Err.Err?) + if type(m) ~= "table" then + return nil, Err.new(Err.ARG, "not a module") + end + if m.format ~= "mod" and m.format ~= "s3m" and m.format ~= "xm" and m.format ~= "it" then + return nil, Err.new(Err.ARG, "unknown tracker format " .. tostring(m.format)) + end + if not num(m.channels, 1, 128) or m.channels % 1 ~= 0 then + return nil, Err.new(Err.ARG, "bad channel count") + end + if type(m.order) ~= "table" or type(m.patterns) ~= "table" or type(m.samples) ~= "table" then + return nil, Err.new(Err.ARG, "module without order / patterns / samples") + end + m.instruments = if type(m.instruments) == "table" then m.instruments else {} + m.flags = if type(m.flags) == "table" then m.flags else {} + m.channelPan = if type(m.channelPan) == "table" then m.channelPan else {} + m.channelVolume = if type(m.channelVolume) == "table" then m.channelVolume else {} + m.channelMute = if type(m.channelMute) == "table" then m.channelMute else {} + for i = 1, m.channels do + local p = m.channelPan[i] + if p ~= 512 and not num(p, 0, 256) then + m.channelPan[i] = 128 + end + if not num(m.channelVolume[i], 0, 64) then + m.channelVolume[i] = 64 + end + end + m.speed = if num(m.speed, 1, 255) then math.floor(m.speed) else 6 + m.tempo = if num(m.tempo, 1, 1000) then m.tempo else 125 + m.globalVolume = if num(m.globalVolume, 0, 128) then m.globalVolume else 128 + m.mixVolume = if num(m.mixVolume, 0, 256) then m.mixVolume else 48 + m.restart = if num(m.restart, 0, 1e6) then math.floor(m.restart) else 0 + for i, o in m.order do + if not num(o, 0, 255) then + return nil, Err.new(Err.ARG, "bad order entry " .. i) + end + end + for i, p in m.patterns do + if type(p) ~= "table" or not num(p.rows, 1, 1024) or type(p.data) ~= "buffer" or buffer.len(p.data) < p.rows * m.channels * CELL then + return nil, Err.new(Err.ARG, "bad pattern " .. (i - 1)) + end + end + for i, s in m.samples do + if type(s) ~= "table" then + return nil, Err.new(Err.ARG, "bad sample " .. i) + end + local nch = if s.channels == 2 then 2 else 1 + s.channels = nch + if not num(s.length, 0, 2 ^ 31) or type(s.data) ~= "buffer" or buffer.len(s.data) < math.floor(s.length) * nch * 4 then + return nil, Err.new(Err.ARG, "sample " .. i .. ": data shorter than its length") + end + s.length = math.floor(s.length) + s.loopStart, s.loopEnd, s.loopType = fixLoop(s.loopStart or 0, s.loopEnd or 0, s.loopType or 0, s.length) + s.susStart, s.susEnd, s.susType = fixLoop(s.susStart or 0, s.susEnd or 0, s.susType or 0, s.length) + s.volume = if num(s.volume, 0, 64) then s.volume else 64 + s.globalVolume = if num(s.globalVolume, 0, 64) then s.globalVolume else 64 + if s.pan ~= nil and not num(s.pan, 0, 256) then + s.pan = nil + end + s.c5speed = if num(s.c5speed, 1, 1e7) then s.c5speed else 8363 + s.relativeNote = if num(s.relativeNote, -128, 127) then s.relativeNote else 0 + s.finetune = if num(s.finetune, -128, 127) then s.finetune else 0 + end + for i, ins in m.instruments do + if type(ins) ~= "table" or type(ins.sampleMap) ~= "table" or type(ins.noteMap) ~= "table" then + return nil, Err.new(Err.ARG, "bad instrument " .. i) + end + for n = 1, 120 do + if not num(ins.sampleMap[n], 0, 1e6) then + ins.sampleMap[n] = 0 + end + if not num(ins.noteMap[n], 1, 120) then + ins.noteMap[n] = n + end + end + local err + ins.volEnv, err = fixEnvelope(ins.volEnv) + if err then + return nil, Err.new(Err.ARG, "instrument " .. i .. ": " .. err) + end + ins.panEnv, err = fixEnvelope(ins.panEnv) + if err then + return nil, Err.new(Err.ARG, "instrument " .. i .. ": " .. err) + end + ins.pitchEnv, err = fixEnvelope(ins.pitchEnv) + if err then + return nil, Err.new(Err.ARG, "instrument " .. i .. ": " .. err) + end + ins.fadeout = if num(ins.fadeout, 0, 65535) then ins.fadeout else 0 + ins.globalVolume = if num(ins.globalVolume, 0, 128) then ins.globalVolume else 128 + if ins.pan ~= nil and not num(ins.pan, 0, 256) then + ins.pan = nil + end + if ins.cutoff ~= nil and not num(ins.cutoff, 0, 127) then + ins.cutoff = nil + end + if ins.resonance ~= nil and not num(ins.resonance, 0, 127) then + ins.resonance = nil + end + end + return true, nil +end + +-- ------------------------------------------------------------------------------------------------ rendering +local Decoder = {} +Decoder.__index = Decoder + +-- duration(module, opts?) -> seconds of one pass (song loops and the end of the order list detected), or nil, Err +function Tracker.duration(m: any, opts: RenderOptions?): (number?, Err.Err?) + local ok, err = Tracker.validate(m) + if not ok then + return nil, err + end + local sr = opts and opts.sampleRate or 44100 + local maxFrames = (opts and opts.maxDuration or 3600) * sr + local st = Player.new(m, sr, { stereoSeparation = 100 }) + local frames = 0 + while frames < maxFrames do + local f = Player.tick(st) + if f == 0 and st.ended then + break + end + frames += f + end + return math.min(frames, maxFrames) / sr, nil +end + +local function newPlayer(self: any) + self.st = Player.new(self.module, self.sampleRate, self.opts) + self.st.ramp = math.max(1, math.floor(self.sampleRate * 0.0015)) + self.left = 0 + self.pos = 0 +end + +-- render(module, opts?) -> Types.Decoder (stereo f32) | nil, Err +function Tracker.render(m: any, opts: RenderOptions?): (Types.Decoder?, Err.Err?) + local o: RenderOptions = opts or {} + local sr = o.sampleRate or 44100 + if type(sr) ~= "number" or sr < 1000 or sr > 384000 then + return nil, Err.new(Err.ARG, "sampleRate must be 1000..384000") + end + local seconds, err = Tracker.duration(m, o) + if not seconds then + return nil, err + end + local frames = math.floor(seconds * sr + 0.5) + local self = setmetatable({ + sampleRate = sr, + channels = 2, + frames = frames, + duration = frames / sr, + bitrate = 0, + tags = { title = m.title or "" }, + module = m, + opts = o, + linear = o.interpolation ~= "none", + maxFrames = (o.maxDuration or 3600) * sr, + st = nil :: any, + left = 0, + pos = 0, + }, Decoder) + newPlayer(self) + return self :: any, nil +end + +-- the Module method: module:render(opts) +function Tracker.renderMethod(self: any, opts: RenderOptions?): Types.Decoder + local dec = Tracker.render(self, opts) + return dec :: any +end + +-- run(self, out?, n) -> frames produced (out nil: advance without mixing) +local function run(self: any, out: buffer?, n: number): number + local st = self.st + local done = 0 + while done < n do + if self.left <= 0 then + if self.pos + done >= self.maxFrames then + break + end + local f = Player.tick(st) + if f == 0 and st.ended then + break + end + self.left = f + if f == 0 then + continue + end + end + local k = math.min(self.left, n - done) + Mixer.mix(st, out, done, k, self.linear) + self.left -= k + done += k + end + self.pos += done + return done +end + +-- read(n, out?) -> interleaved stereo f32 buffer, frames read (0 at the end) +function Decoder.read(self: any, n: number, out: buffer?): (buffer, number) + n = math.max(0, math.floor(tonumber(n) or 0)) + local o = out + if o == nil or buffer.len(o) < n * 8 then + o = buffer.create(n * 8) + else + buffer.fill(o, 0, 0, n * 8) + end + local got = run(self, o, n) + return o :: buffer, got +end + +-- seek(seconds): replays the song silently up to the position (sample positions included) +function Decoder.seek(self: any, seconds: number) + local target = math.max(0, math.floor((tonumber(seconds) or 0) * self.sampleRate)) + newPlayer(self) + local chunk = 65536 + while self.pos < target do + local got = run(self, nil, math.min(chunk, target - self.pos)) + if got == 0 then + break + end + end + -- the gains ramp in from silence after a seek + for _, v in self.st.voices do + v.gl, v.gr = 0, 0 + end +end + +function Decoder.position(self: any): number + return self.pos / self.sampleRate +end + +return Tracker diff --git a/src/Formats/codecs/Video/Source.luau b/src/Formats/codecs/Video/Source.luau new file mode 100644 index 0000000..2779bf5 --- /dev/null +++ b/src/Formats/codecs/Video/Source.luau @@ -0,0 +1,305 @@ +--!strict +-- codecs/Video/Source: what a video writer (Matroska / WebM, AVI, Y4M, MP4) gets to write, from whatever it was given: +-- a VideoDecoder (F.load / F.video.open of any video or animated image) or a Demuxer. Each output stream is either +-- copied (the source track's packets, when the target container takes that codec: remuxing, e.g. VP8 into WebM, +-- since VP8 is decode-only) or produced (decoded frames encoded with a registered encoder such as MJPEG, raw +-- yuv420p frames, PCM audio from the audio Decoder). New in formats-luau. +-- +-- local streams, err = Source.streams(value, opts, { +-- video = { copy = { vp8 = true }, encode = "mjpeg" }, -- copy: codec ids the container takes ("*" = any) +-- audio = { copy = { opus = true, vorbis = true }, pcm = true }, +-- }) +-- -- streams[i] = { kind, codec, copied, width, height, frameRate, sampleRate, channels, bitsPerSample, config, +-- -- track, packets = { { pts, duration (seconds), keyframe, data } } } +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Yuv = require("@formats/codecs/Yuv") + +local Source = {} + +export type OutPacket = { pts: number, dts: number?, duration: number, keyframe: boolean, data: buffer } +export type Stream = { + kind: "video" | "audio", + codec: string, + copied: boolean, + width: number?, + height: number?, + frameRate: number?, + sampleRate: number?, + channels: number?, + bitsPerSample: number?, + config: buffer?, + track: Types.Track?, + packets: { OutPacket }, +} +export type Want = { + video: { copy: { [string]: boolean }?, encode: string? }?, + audio: { copy: { [string]: boolean }?, pcm: boolean? }?, +} + +local function allows(set: { [string]: boolean }?, codec: string): boolean + return set ~= nil and (set[codec] == true or set["*"] == true) +end + +-- the packets of a source track, times in seconds +local function copyPackets(dmx: any, track: Types.Track): { OutPacket } + local out = {} + local scale = if track.timescale and track.timescale > 0 then track.timescale else 1 + local n = dmx:count(track.id) + for k = 1, n do + local p = dmx:get(track.id, k) + if p then + table.insert(out, { pts = p.pts / scale, dts = (p.dts or p.pts) / scale, duration = (p.duration or 0) / scale, keyframe = p.keyframe, data = p.data }) + end + end + return out +end + +local function trackStream(track: Types.Track, packets: { OutPacket }): Stream + return { + kind = track.kind :: any, + codec = track.codec, + copied = true, + width = track.width, + height = track.height, + frameRate = track.frameRate, + sampleRate = track.sampleRate, + channels = track.channels, + bitsPerSample = track.bitsPerSample, + config = track.config, + track = track, + packets = packets, + } +end + +-- encodeFrames(video, codec, opts) -> the video's frames encoded with the registry's encoder for codec ("rawvideo": +-- yuv420p planes) +local function encodeFrames(v: any, codec: string, opts: any): (Stream?, Err.Err?) + local encode: ((img: Types.Image, opts: any) -> (buffer?, Err.Err?))? = nil + if codec ~= "rawvideo" then + local Video = require("@formats/codecs/Video") + local e = Video.entry(codec) + encode = e and e.encode + if not encode then + return nil, Err.new(Err.UNSUPPORTED, "no " .. codec .. " encoder") + end + end + if type(v.reset) == "function" then + v:reset() + end + local packets: { OutPacket } = {} + local w, h = v.width, v.height + local maxFrames = opts.maxFrames or math.huge + while #packets < maxFrames do + local f, err = v:nextFrame() + if not f then + if err then + return nil, err + end + break + end + local img: Types.Image = f.image + if (w == 0 or h == 0) and #packets == 0 then + w, h = img.width, img.height + end + if img.width ~= w or img.height ~= h then + return nil, Err.new(Err.UNSUPPORTED, "frame size changes mid-stream (" .. img.width .. "x" .. img.height .. ")") + end + local data: buffer? + if codec == "rawvideo" then + local y = if img.format == "yuv420p" then img else Yuv.imageFromRgba(img, "limited", "bt601") + if not y then + return nil, Err.new(Err.UNSUPPORTED, "frame format " .. img.format) + end + data = y.pixels + else + local e2 + data, e2 = (encode :: any)(img, opts) + if not data then + return nil, e2 or Err.new(Err.ARG, "frame " .. f.index .. " failed to encode") + end + end + table.insert(packets, { pts = f.pts, duration = f.duration, keyframe = true, data = data :: buffer }) + end + if #packets == 0 then + return nil, Err.new(Err.ARG, "no frames to write") + end + local fr = v.frameRate + if not fr or fr <= 0 then + local d = packets[1].duration + fr = if d > 0 then 1 / d else 25 + end + return { + kind = "video", + codec = codec, + copied = false, + width = w, + height = h, + frameRate = fr, + packets = packets, + } :: Stream, nil +end + +-- pcmFrom(decoder, opts) -> an s16le stream from an audio Decoder (chunks of opts.audioChunk frames, default 4096) +local function pcmFrom(dec: any, opts: any): (Stream?, Err.Err?) + local ch, rate = dec.channels, dec.sampleRate + if type(ch) ~= "number" or ch < 1 or type(rate) ~= "number" or rate <= 0 then + return nil, Err.new(Err.ARG, "audio decoder without channels / sample rate") + end + pcall(dec.seek, dec, 0) + local chunk = opts.audioChunk or 4096 + local packets: { OutPacket } = {} + local pos = 0 + local tmp: buffer? = nil + while true do + local ok, out, n = pcall(dec.read, dec, chunk, tmp) + if not ok or not out or not n or n <= 0 then + break + end + tmp = out + local data = buffer.create(n * ch * 2) + for i = 0, n * ch - 1 do + local s = buffer.readf32(out, i * 4) + local v = math.floor(s * 32768 + 0.5) + if v > 32767 then + v = 32767 + elseif v < -32768 then + v = -32768 + elseif v ~= v then + v = 0 + end + buffer.writei16(data, i * 2, v) + end + table.insert(packets, { pts = pos / rate, duration = n / rate, keyframe = true, data = data }) + pos += n + end + return { + kind = "audio", + codec = "pcm_s16le", + copied = false, + sampleRate = rate, + channels = ch, + bitsPerSample = 16, + packets = packets, + } :: Stream, nil +end + +-- streams(value, opts, want) -> { Stream } | nil, Err +function Source.streams(value: any, opts: any?, want: Want): ({ Stream }?, Err.Err?) + local o = opts or {} + if type(value) ~= "table" or (value.kind ~= "video" and value.kind ~= "demuxer") then + return nil, Err.new(Err.ARG, "expected a video (VideoDecoder) or a Demuxer") + end + local dmx = if value.kind == "demuxer" then value else value.demuxer + local out: { Stream } = {} + -- video + local vt: Types.Track? = if value.kind == "video" then value.track else (dmx and dmx:track("video")) + local wv = want.video + if wv and o.video ~= false then + if vt and dmx and allows(wv.copy, vt.codec) and not o.reencode then + table.insert(out, trackStream(vt, copyPackets(dmx, vt))) + elseif value.kind == "video" and wv.encode then + local s, err = encodeFrames(value, wv.encode, o) + if not s then + return nil, err + end + table.insert(out, s) + elseif vt then + return nil, Err.new(Err.UNSUPPORTED, "cannot write " .. vt.codec .. " video" .. (if wv.encode then "" else " (this container cannot take it and it cannot be re-encoded)")) + end + end + -- audio + local wa = want.audio + if wa and o.audio ~= false then + local at: Types.Track? = dmx and dmx:track("audio") + if at and dmx and allows(wa.copy, at.codec) and not o.reencodeAudio then + table.insert(out, trackStream(at, copyPackets(dmx, at))) + elseif wa.pcm and value.kind == "video" and value.audio then + local s, err = pcmFrom(value.audio, o) + if not s then + return nil, err + end + if #s.packets > 0 then + table.insert(out, s) + end + elseif at and o.audio == true then + return nil, Err.new(Err.UNSUPPORTED, "cannot write " .. at.codec .. " audio to this container") + end + end + if #out == 0 then + return nil, Err.new(Err.ARG, "nothing to write (no video or audio stream)") + end + return out, nil +end + +-- rational(fps) -> num, den: integer rates as n / 1, NTSC rates as n * 1000 / 1001, else to a millisecond +function Source.rational(fps: number): (number, number) + if fps ~= fps or fps <= 0 then + return 25, 1 + end + if math.abs(fps - math.floor(fps + 0.5)) < 1e-6 then + return math.floor(fps + 0.5), 1 + end + local ntsc = fps * 1001 / 1000 + if math.abs(ntsc - math.floor(ntsc + 0.5)) < 1e-4 then + return math.floor(ntsc + 0.5) * 1000, 1001 + end + return math.floor(fps * 1000 + 0.5), 1000 +end + +-- constantRate(stream, maxFps?) -> num, den, { OutPacket }: a video stream at a constant frame rate for the +-- containers that have one (AVI, Y4M): the rate of the shortest frame (at most maxFps, default 100), each packet +-- repeated to fill its duration (a GIF's 100 / 50 / 200 ms frames become 2, 1 and 4 frames at 20 fps) +function Source.constantRate(s: Stream, maxFps: number?): (number, number, { OutPacket }) + local fd = math.huge + for _, p in s.packets do + if p.duration and p.duration > 0 and p.duration < fd then + fd = p.duration + end + end + if fd == math.huge then + fd = if s.frameRate and s.frameRate > 0 then 1 / s.frameRate else 0.04 + end + fd = math.max(fd, 1 / (maxFps or 100)) + local num, den = Source.rational(1 / fd) + local step = den / num + local out: { OutPacket } = {} + local slots = 0 + local t0 = if s.packets[1] then s.packets[1].pts else 0 + for _, p in s.packets do + local stop = p.pts - t0 + (if p.duration and p.duration > 0 then p.duration else step) + local n = math.max(1, math.floor(stop / step + 0.5) - slots) + for _ = 1, n do + table.insert(out, { pts = t0 + slots * step, duration = step, keyframe = p.keyframe, data = p.data }) + slots += 1 + end + end + return num, den, out +end + +-- interleave(streams) -> { { stream index, packet } } merged by decode time (dts, else pts); each stream keeps its +-- own order +function Source.interleave(streams: { Stream }): { { any } } + local order = {} + local pos = table.create(#streams, 1) + while true do + local best, bt = 0, math.huge + for si, s in streams do + local p = s.packets[pos[si]] + if p then + local t = p.dts or p.pts + if best == 0 or t < bt then + best, bt = si, t + end + end + end + if best == 0 then + break + end + table.insert(order, { best, streams[best].packets[pos[best]] }) + pos[best] += 1 + end + return order +end + +return Source diff --git a/src/Formats/codecs/Video/init.luau b/src/Formats/codecs/Video/init.luau new file mode 100644 index 0000000..6c514ad --- /dev/null +++ b/src/Formats/codecs/Video/init.luau @@ -0,0 +1,584 @@ +--!strict +-- codecs/Video: the video codec registry and the generic VideoDecoder. New in formats-luau. +-- +-- Registry: our codec ids ("vp8", "mjpeg", "mpeg1", "h264", "rawvideo", ...) with the containers' names for them +-- (AVI / MOV FourCCs, Matroska CodecIDs, MPEG stream types) and, for the codecs we can decode, a constructor of a +-- Types.VideoCodecDecoder (packets in, pictures out). Containers map their own ids through Video.fromFourcc / +-- Video.fromMatroska so a track's codec is known even without a decoder (remuxing still works). Another codec plugs +-- in with one line in BUILTIN (static: Roblox has no dynamic require) or at run time with Video.register(entry). +-- +-- local Video = require("@formats/codecs/Video") +-- Video.fromFourcc("MJPG") --> "mjpeg" Video.fromMatroska("V_VP8") --> "vp8" +-- local dec = Video.decoder(track, opts) -- a VideoCodecDecoder | nil, Err (UNSUPPORTED: no decoder) +-- local v = Video.open(demuxer, opts) -- a Types.VideoDecoder over a Types.Demuxer (formats' open()) +-- local v = Video.fromFrames(images, delays) -- a frames-backed VideoDecoder (animated GIF / APNG / WebP) +-- +-- Never throws: bad data / missing codecs come back as nil, Err. +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Yuv = require("@formats/codecs/Yuv") + +local Video = {} + +export type Entry = { + id: string, -- our codec id + name: string, -- a human name + fourcc: { string }?, -- AVI biCompression / MOV sample entry FourCCs + matroska: { string }?, -- Matroska / WebM CodecIDs + -- new(track, opts) -> a decoder instance (nil = decode not supported) + new: ((track: Types.Track, opts: any?) -> (Types.VideoCodecDecoder?, Err.Err?))?, + [string]: any, +} + +-- ------------------------------------------------------------------------------------------------ simple decoders +-- one picture per packet, no reordering: decodeOne(data, packet) -> Image | nil, Err (nil, nil: a packet with no +-- picture to show, such as a hidden VP8 altref frame) +function Video.simpleDecoder(decodeOne: (data: buffer, packet: Types.Packet) -> (Types.Image?, Err.Err?), resetFn: (() -> ())?): Types.VideoCodecDecoder + local queue: { any } = {} + local self = {} + function self.decode(_: any, packet: Types.Packet): Err.Err? + local ok, img, err = pcall(decodeOne, packet.data, packet) + if not ok then + return Err.new(Err.CORRUPT, "decoder threw: " .. tostring(img)) + end + if img then + table.insert(queue, { img, packet.pts, packet.keyframe }) + end + return err + end + function self.receive(_: any): (Types.Image?, number?, boolean?) + local q = table.remove(queue, 1) + if q then + return q[1], q[2], q[3] + end + return nil + end + function self.flush(_: any) end + function self.reset(_: any) + table.clear(queue) + if resetFn then + resetFn() + end + end + return self :: any +end + +-- raw video: yuv420p (I420 / IYUV / y4m), yv12 (V before U), yuv422p / yuv444p / yuva444p / gray (chroma averaged +-- down to 4:2:0, alpha dropped), track.bitDepth 9..16 (little-endian 16-bit samples scaled to 8 bits), rgb24 / bgr24 / +-- bgra / rgba (AVI DIBs: track.flip = bottom-up rows, track.stride = padded rows) +local function rawPlanar(data: buffer, pf: string, bits: number, w: number, h: number): Types.Image + local img = Types.Image.new(w, h, "yuv420p") + local px = img.pixels + local cw, ch = (w + 1) // 2, (h + 1) // 2 + local bps = if bits > 8 then 2 else 1 + local shift = 2 ^ (bits - 8) + local function sample(o: number): number + if bps == 1 then + return buffer.readu8(data, o) + end + return math.min(255, buffer.readu16(data, o) // shift) + end + for i = 0, w * h - 1 do + buffer.writeu8(px, i, sample(i * bps)) + end + local scw, sch = w, h -- source chroma plane size + if pf == "yuv420p" then + scw, sch = cw, ch + elseif pf == "yuv422p" then + scw, sch = cw, h + end + local uo, vo = w * h * bps, (w * h + scw * sch) * bps + for cy = 0, ch - 1 do + for cx = 0, cw - 1 do + local i = cy * cw + cx + local u, v + if pf == "gray" then + u, v = 128, 128 + elseif pf == "yuv420p" then + u, v = sample(uo + i * bps), sample(vo + i * bps) + elseif pf == "yuv422p" then + local y0, y1 = cy * 2, math.min(cy * 2 + 1, h - 1) + u = (sample(uo + (y0 * scw + cx) * bps) + sample(uo + (y1 * scw + cx) * bps) + 1) // 2 + v = (sample(vo + (y0 * scw + cx) * bps) + sample(vo + (y1 * scw + cx) * bps) + 1) // 2 + else + local x0, x1 = cx * 2, math.min(cx * 2 + 1, w - 1) + local y0, y1 = cy * 2, math.min(cy * 2 + 1, h - 1) + local a, b, c, d = (y0 * w + x0) * bps, (y0 * w + x1) * bps, (y1 * w + x0) * bps, (y1 * w + x1) * bps + u = (sample(uo + a) + sample(uo + b) + sample(uo + c) + sample(uo + d) + 2) // 4 + v = (sample(vo + a) + sample(vo + b) + sample(vo + c) + sample(vo + d) + 2) // 4 + end + buffer.writeu8(px, w * h + i, u) + buffer.writeu8(px, w * h + cw * ch + i, v) + end + end + return img +end + +local PLANAR_SIZE: { [string]: (w: number, h: number, cw: number, ch: number) -> number } = { + yuv420p = function(w, h, cw, ch) + return w * h + 2 * cw * ch + end, + yv12 = function(w, h, cw, ch) + return w * h + 2 * cw * ch + end, + yuv422p = function(w, h, cw, _ch) + return w * h + 2 * cw * h + end, + yuv444p = function(w, h) + return w * h * 3 + end, + yuva444p = function(w, h) + return w * h * 4 + end, + gray = function(w, h) + return w * h + end, +} + +local function rawDecoder(track: Types.Track, _opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + local w, h = track.width or 0, track.height or 0 + if w <= 0 or h <= 0 or w * h > 2 ^ 26 then + return nil, Err.new(Err.CORRUPT, "raw video without a valid size") + end + local pf = track.pixelFormat or "yuv420p" + local bits = track.bitDepth or 8 + local cw, ch = (w + 1) // 2, (h + 1) // 2 + local flip = track.flip == true + local planar = PLANAR_SIZE[pf] + return Video.simpleDecoder(function(data: buffer): (Types.Image?, Err.Err?) + local n = buffer.len(data) + if planar then + local need = planar(w, h, cw, ch) * (if bits > 8 then 2 else 1) + if n < need then + return nil, Err.new(Err.TRUNCATED, "raw frame: " .. n .. " of " .. need .. " bytes") + end + if pf == "yuv420p" and bits == 8 then + local img = Types.Image.new(w, h, "yuv420p") + buffer.copy(img.pixels, 0, data, 0, need) + return img + elseif pf == "yv12" then + local img = Types.Image.new(w, h, "yuv420p") + buffer.copy(img.pixels, 0, data, 0, w * h) + buffer.copy(img.pixels, w * h, data, w * h + cw * ch, cw * ch) + buffer.copy(img.pixels, w * h + cw * ch, data, w * h, cw * ch) + return img + end + return rawPlanar(data, pf, bits, w, h) + end + local bpp = if pf == "bgra" or pf == "rgba" then 4 else 3 + local stride = if track.stride then track.stride else w * bpp + if n < stride * (h - 1) + w * bpp then + return nil, Err.new(Err.TRUNCATED, "raw frame too short") + end + local img = Types.Image.new(w, h, "rgba8") + local px = img.pixels + local bgr = pf == "bgr24" or pf == "bgra" + for y = 0, h - 1 do + local s = (if flip then h - 1 - y else y) * stride + local o = y * w * 4 + for x = 0, w - 1 do + local p = s + x * bpp + local a, b, c = buffer.readu8(data, p), buffer.readu8(data, p + 1), buffer.readu8(data, p + 2) + if bgr then + a, c = c, a + end + buffer.writeu32(px, o + x * 4, a + b * 256 + c * 65536 + 0xff000000) + end + end + return img + end) +end + +local function vp8Decoder(_track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + local Vp8 = require("@formats/codecs/Vp8") + local dec = Vp8.newDecoder() + local o = { maxPixels = opts and opts.maxPixels } + return Video.simpleDecoder(function(data: buffer): (Types.Image?, Err.Err?) + local img, err = dec:decodeFrame(data, 0, buffer.len(data), o) + if not img then + return nil, err + end + local src = img.meta.source + if type(src) == "table" and src.show == false then + return nil, nil + end + img.meta.yuv = { range = "limited", matrix = "bt601" } + return img, nil + end, function() + if dec.reset then + dec:reset() + else + dec = Vp8.newDecoder() + end + end) +end + +-- Motion JPEG: every packet one JPEG (or two fields), yuv420p straight from the planes (full range) when the layout +-- allows, else rgba8 +local function mjpegDecoder(_track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + local Jpeg = require("@formats/codecs/Jpeg") + local o = { yuv = true, maxPixels = opts and opts.maxPixels } + return Video.simpleDecoder(function(data: buffer): (Types.Image?, Err.Err?) + local img, err = Jpeg.decode(data, 0, buffer.len(data), o) + if img and img.format == "yuv420p" then + img.meta.yuv = { range = "full", matrix = "bt601" } + end + return img, err + end) +end + +-- the MJPEG encoder (writers): JPEG is full-range, so limited-range yuv420p frames are remapped first +local function mjpegEncode(img: Types.Image, opts: any?): (buffer?, Err.Err?) + local Jpeg = require("@formats/codecs/Jpeg") + local src = img + if img.format == "yuv420p" then + local range = Yuv.info(img) + if range ~= "full" then + src = Yuv.toFullRange(img) + end + end + return Jpeg.encode(src, { quality = opts and opts.quality or 90 }) +end + +-- MPEG-1 video: pictures in decode order, reordered for display (the packet's pts travels with its picture) +local function mpeg1Decoder(_track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + local Mpeg1 = require("@formats/codecs/Mpeg1") + local dec = Mpeg1.new({ reorder = true, rgba = false, maxPixels = opts and opts.maxPixels }) + local queue: { any } = {} + local function push(f: any) + local img = Mpeg1.frameImage(f) + if img then + img.meta.yuv = { range = "limited", matrix = "bt601" } + local tag = f.tag + table.insert(queue, { img, if type(tag) == "table" then tag[1] else nil, f.pictureType == 1 }) + end + end + local self = {} + function self.decode(_: any, packet: Types.Packet): Err.Err? + local ok, f = pcall(dec.decode, dec, packet.data, 0, buffer.len(packet.data), { packet.pts }) + if not ok then + return Err.new(Err.CORRUPT, "decoder threw: " .. tostring(f)) + end + if f then + push(f) + end + return nil + end + function self.receive(_: any): (Types.Image?, number?, boolean?) + local q = table.remove(queue, 1) + if q then + return q[1], q[2], q[3] + end + return nil + end + function self.flush(_: any) + for _ = 1, 4 do + local f = dec:flush() + if not f then + break + end + push(f) + end + end + function self.reset(_: any) + dec:reset() + table.clear(queue) + end + return self :: any, nil +end + +-- H.264 / AVC (codecs/H264): avcC from track.config (MP4 / Matroska) or Annex B packets (MPEG-TS, AVI, raw .h264); +-- pictures in display order with the pts of their packet +local function h264Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + local H264 = require("@formats/codecs/H264") + return H264.newVideoDecoder(track, opts) +end + +-- ------------------------------------------------------------------------------------------------ registry +-- the codecs known by name (decoders where `new` is set). FourCCs compare case-sensitively first, then upper-cased. +local BUILTIN: { Entry } = { + { id = "vp8", name = "VP8", fourcc = { "VP80", "vp08" }, matroska = { "V_VP8" }, new = vp8Decoder }, + { id = "mjpeg", name = "Motion JPEG", fourcc = { "MJPG", "mjpa", "mjpb", "jpeg", "AVRn", "AVDJ", "dmb1", "LJPG", "JPGL", "MJLS", "ijpg" }, matroska = { "V_MJPEG" }, new = mjpegDecoder, encode = mjpegEncode }, + { id = "mpeg1", name = "MPEG-1 video", fourcc = { "mpg1", "MPG1", "PIM1", "m1v " }, matroska = { "V_MPEG1" }, new = mpeg1Decoder }, + { id = "rawvideo", name = "raw video", fourcc = { "\0\0\0\0", "I420", "IYUV", "YV12", "raw ", "DIB " }, matroska = { "V_UNCOMPRESSED" }, new = rawDecoder }, + { id = "mpeg2", name = "MPEG-2 video", fourcc = { "mpg2", "MPG2", "MPEG", "mp2v" }, matroska = { "V_MPEG2" } }, + { id = "mpeg4", name = "MPEG-4 part 2", fourcc = { "mp4v", "FMP4", "XVID", "DIVX", "DX50", "MP4V" }, matroska = { "V_MPEG4/ISO/SP", "V_MPEG4/ISO/ASP", "V_MPEG4/ISO/AP" } }, + { id = "h264", name = "H.264 / AVC", fourcc = { "avc1", "avc3", "H264", "h264", "X264", "x264", "AVC1", "DAVC", "VSSH" }, matroska = { "V_MPEG4/ISO/AVC" }, new = h264Decoder }, + { id = "hevc", name = "H.265 / HEVC", fourcc = { "hvc1", "hev1", "HEVC", "H265" }, matroska = { "V_MPEGH/ISO/HEVC" } }, + { id = "vp9", name = "VP9", fourcc = { "VP90", "vp09" }, matroska = { "V_VP9" } }, + { id = "av1", name = "AV1", fourcc = { "AV01", "av01" }, matroska = { "V_AV1" } }, + { id = "theora", name = "Theora", matroska = { "V_THEORA" } }, + { id = "png", name = "PNG", fourcc = { "png ", "MPNG" }, matroska = { "V_PNG" } }, +} + +local byId: { [string]: Entry } = {} +local byFourcc: { [string]: string } = {} +local byMatroska: { [string]: string } = {} + +-- register(entry): adds or replaces a codec (by id); its fourcc / matroska names map to it +function Video.register(entry: Entry): (boolean, Err.Err?) + if type(entry) ~= "table" or type(entry.id) ~= "string" then + return false, Err.new(Err.ARG, "register: needs an entry with an id") + end + local old = byId[entry.id] + if old and entry.new == nil then + entry.new = old.new + end + byId[entry.id] = entry + for _, f in entry.fourcc or {} do + byFourcc[f] = entry.id + end + for _, m in entry.matroska or {} do + byMatroska[m] = entry.id + end + return true +end +for _, e in BUILTIN do + Video.register(e) +end + +-- the registry (read only by convention): id -> Entry +Video.codecs = byId + +-- fromFourcc(fourcc) -> codec id | nil +function Video.fromFourcc(fcc: string): string? + return byFourcc[fcc] or byFourcc[string.upper(fcc)] or byFourcc[string.lower(fcc)] +end + +-- fromMatroska(codecId) -> codec id | nil (V_MPEG4/ISO/AVC -> h264, ...) +function Video.fromMatroska(id: string): string? + return byMatroska[id] +end + +-- names(codecId) -> the Entry (FourCCs / Matroska ids for writers) | nil +function Video.entry(id: string): Entry? + return byId[id] +end + +-- canDecode(codecId) -> boolean +function Video.canDecode(id: string): boolean + local e = byId[id] + return e ~= nil and e.new ~= nil +end + +-- decoder(track, opts?) -> a VideoCodecDecoder for the track's codec | nil, Err (UNSUPPORTED when none is registered) +function Video.decoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + local e = byId[track.codec] + if not e or not e.new then + return nil, Err.new(Err.UNSUPPORTED, "no decoder for video codec " .. tostring(track.codec)) + end + local ok, dec, err = pcall(e.new :: any, track, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "codec " .. track.codec .. " failed to start: " .. tostring(dec)) + end + return dec, err +end + +-- ------------------------------------------------------------------------------------------------ VideoDecoder +local function toRGBA(_self: any, f: any): Types.Image + local img = if type(f) == "table" and f.image then f.image else f + local out = Yuv.imageToRgba(img) + return out or img +end + +export type OpenOptions = { + rgba: boolean?, -- nextFrame returns rgba8 images (default false: the codec's native yuv420p) + track: number?, -- the video track id (default: the first video track) + maxPixels: number?, + openAudio: ((demuxer: Types.Demuxer, track: Types.Track) -> (Types.Decoder?, Err.Err?))?, -- the api's audio hook + audio: boolean?, -- false: do not open the audio track + [string]: any, +} + +-- open(demuxer, opts?) -> a Types.VideoDecoder over the demuxer's video track (and audio track through +-- opts.openAudio). A video track without a decoder still opens: nextFrame returns nil, Err.UNSUPPORTED, and +-- the demuxer (remuxing) and audio work. +function Video.open(demuxer: Types.Demuxer, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local o: OpenOptions = opts or {} + local track: Types.Track? = nil + if o.track then + for _, t in demuxer.tracks do + if t.id == o.track then + track = t + end + end + if not track then + return nil, Err.new(Err.ARG, "no track " .. tostring(o.track)) + end + else + track = demuxer:track("video") + end + local codec: Types.VideoCodecDecoder? = nil + local codecErr: Err.Err? = nil + if track then + codec, codecErr = Video.decoder(track, o) + else + codecErr = Err.new(Err.UNSUPPORTED, "no video track") + end + local v: any = { + kind = "video", + format = demuxer.format, + codec = if track then track.codec else "none", + width = if track then track.width or 0 else 0, + height = if track then track.height or 0 else 0, + frameRate = if track then track.frameRate or 0 else 0, + frames = if track then track.frames or 0 else 0, + duration = if track and track.duration and track.duration > 0 then track.duration else demuxer.duration, + track = track, + demuxer = demuxer, + meta = demuxer.meta or {}, + decodeError = codecErr, + toRGBA = toRGBA, + } + if v.frames == 0 and v.frameRate > 0 and v.duration > 0 then + v.frames = math.floor(v.duration * v.frameRate + 0.5) + end + -- audio + if o.audio ~= false then + local at = demuxer:track("audio") + if at then + if o.openAudio then + local ok, dec, err = pcall(o.openAudio, demuxer, at) + if ok and dec then + v.audio = dec + else + v.audioError = if ok then err else Err.new(Err.CORRUPT, "audio: " .. tostring(dec)) + end + else + v.audioError = Err.new(Err.UNSUPPORTED, "no audio hook (open through the api: F.video.open)") + end + end + end + local index, flushed, skipUntil = 0, false, -math.huge + local tid = if track then track.id else -1 + local scale = if track and track.timescale and track.timescale > 0 then track.timescale else 1000 + local start = demuxer.startTime or 0 + v.startTime = start + local defaultDur = if v.frameRate > 0 then 1 / v.frameRate else 0 + local lastPts = nil :: number? + function v.nextFrame(self: any): (Types.VideoFrame?, Err.Err?) + if not codec then + return nil, codecErr + end + local dec = codec :: Types.VideoCodecDecoder + while true do + local img, pts, key = dec:receive() + if img then + local t = (pts or 0) / scale - start + if t + 1e-9 >= skipUntil then + index += 1 + local d = defaultDur + if lastPts and t > lastPts and defaultDur == 0 then + d = t - lastPts + end + lastPts = t + if o.rgba then + img = Yuv.imageToRgba(img) or img + end + return { image = img, pts = t, duration = d, keyframe = key, index = index }, nil + end + else + local p = demuxer:read(tid) + if p == nil then + if flushed then + return nil, nil + end + flushed = true + dec:flush() + else + local err = dec:decode(p) + if err then + return nil, err + end + end + end + end + end + function v.seek(self: any, seconds: number) + demuxer:seek(seconds + start) + if codec then + codec:reset() + end + flushed = false + skipUntil = seconds + lastPts = nil + if self.audio then + pcall(self.audio.seek, self.audio, seconds) + end + end + function v.reset(self: any) + self:seek(0) + skipUntil = -math.huge + index = 0 + end + return v, nil +end + +-- ------------------------------------------------------------------------------------------------ frames-backed +-- fromFrames(images, delays, opts?) -> a VideoDecoder over full-canvas images (animated GIF / APNG / WebP after +-- coalescing): delays[i] seconds (a number = every frame). opts.format / opts.loops / opts.meta are recorded. +function Video.fromFrames(images: { Types.Image }, delays: (number | { number })?, opts: any?): (Types.VideoDecoder?, Err.Err?) + if type(images) ~= "table" or #images == 0 or type(images[1]) ~= "table" then + return nil, Err.new(Err.ARG, "fromFrames: needs a list of Images") + end + local w, h = images[1].width, images[1].height + local pts: { number } = {} + local durs: { number } = {} + local t = 0 + for i, img in images do + if type(img) ~= "table" or img.width ~= w or img.height ~= h then + return nil, Err.new(Err.ARG, "fromFrames: frame " .. i .. " is not a " .. w .. "x" .. h .. " Image") + end + local d = if type(delays) == "table" then delays[i] or 0.1 else (delays or 0.1) + if type(d) ~= "number" or d ~= d or d < 0 then + d = 0.1 + end + pts[i] = t + durs[i] = d + t += d + end + local n = #images + local o = opts or {} + local v: any = { + kind = "video", + format = o.format or "frames", + codec = "frames", + width = w, + height = h, + frameRate = if t > 0 then n / t else 10, + frames = n, + duration = t, + loops = o.loops, + meta = o.meta or {}, + toRGBA = toRGBA, + images = images, + } + local i = 0 + function v.nextFrame(self: any): (Types.VideoFrame?, Err.Err?) + i += 1 + if i > n then + i = n + return nil, nil + end + local img = images[i] + if o.rgba then + img = Yuv.imageToRgba(img) or img + end + return { image = img, pts = pts[i], duration = durs[i], keyframe = true, index = i }, nil + end + function v.seek(self: any, seconds: number) + local k = 0 + for j = 1, n do + if pts[j] <= seconds + 1e-9 then + k = j - 1 + end + end + i = k + end + function v.reset(self: any) + i = 0 + end + return v, nil +end + +return Video diff --git a/src/Formats/codecs/Vp8/Decode.luau b/src/Formats/codecs/Vp8/Decode.luau index eacff53..88f5652 100644 --- a/src/Formats/codecs/Vp8/Decode.luau +++ b/src/Formats/codecs/Vp8/Decode.luau @@ -1,19 +1,27 @@ --!strict --!native --!optimize 2 --- codecs/Vp8/Decode: the VP8 key frame decoder (RFC 6386): the boolean entropy decoder, frame / segment / filter / +-- codecs/Vp8/Decode: the VP8 frame decoder (RFC 6386): the boolean entropy decoder, frame / segment / filter / -- quantizer headers, token probability updates, intra modes, residual tokens, the inverse WHT and DCT, intra --- prediction (16x16, 4x4, chroma), and the normal and simple loop filters. A port of libwebp 1.6 src/dec/vp8_dec.c, +-- prediction (16x16, 4x4, chroma), and the normal and simple loop filters: a port of libwebp 1.6 src/dec/vp8_dec.c, -- tree_dec.c, quant_dec.c, frame_dec.c, src/dsp/dec.c and src/utils/bit_reader* (BSD-3-Clause, --- licenses/libwebp-LICENSE.txt), bit-exact with it (libwebp is deterministic; so is this). +-- licenses/libwebp-LICENSE.txt). Inter frames after libvpx 1.17 vp8/decoder/decodeframe.c, decodemv.c and +-- vp8/common/findnearmv.c, vp8_loopfilter.c (BSD-3-Clause, licenses/libvpx-LICENSE.txt): reference updates and sign +-- bias, the frame context saved around frames that do not refresh it, persistent segment maps and loop filter deltas, +-- inter modes from the near vectors, motion vectors, split macroblocks, intra macroblocks in inter frames, per +-- reference / mode loop filter levels; the prediction itself is codecs/Vp8/Predict. Bit-exact with libvpx / ffmpeg +-- (and with libwebp on key frames). Where libvpx and ffmpeg disagree on streams no encoder writes (an intermediate +-- clamp of segment filter levels, copying golden to altref and altref to golden in one frame), this follows ffmpeg. -- --- The decoder state (Decode.new) keeps what persists between frames (token probabilities, segment and filter --- headers) so inter frames can be added later for WebM: decodeFrame() returns UNSUPPORTED for them today. --- Never throws: bad data returns nil, "message" ("truncated: ..." when the data ends early). +-- The decoder state (Decode.new) keeps what persists between frames: the frame context, segment / filter headers, the +-- segment map, the last / golden / altref frames. Never throws: bad data returns nil, "message" ("truncated: ..." when +-- the data ends early). local Tables = require("@formats/codecs/Vp8/Tables") +local Predict = require("@formats/codecs/Vp8/Predict") local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift local readu8, writeu8, readi16, writei16 = buffer.readu8, buffer.writeu8, buffer.readi16, buffer.writei16 +local readu32, writeu32 = buffer.readu32, buffer.writeu32 local bfill, bcopy, bcreate = buffer.fill, buffer.copy, buffer.create local abs = math.abs @@ -68,6 +76,8 @@ local function newBr(buf: buffer, off: number, len: number): Br return br end +-- getBit without a branch on the decoded bit (one inlined copy per call site keeps LuaJIT's trace count down): +-- bit = 1 when value >> bits > split, then range = bit ? range - split : split + 1, value -= bit * (split + 1) << bits local function getBit(br: Br, prob: number): number if br.bits < 0 then load(br) @@ -75,16 +85,11 @@ local function getBit(br: Br, prob: number): number local range = br.range local pos = br.bits local split = rshift(range * prob, 8) - local bit = 0 - if rshift(br.value, pos) > split then - range -= split - br.value -= (split + 1) * 2 ^ pos - bit = 1 - else - range = split + 1 - end - local shift = SHIFT[range + 1] - br.range = lshift(range, shift) - 1 + local bit = rshift(split - rshift(br.value, pos), 31) + local r = split + 1 + bit * (range - split - split - 1) + br.value -= bit * lshift(split + 1, pos) + local shift = SHIFT[r + 1] + br.range = lshift(r, shift) - 1 br.bits = pos - shift return bit end @@ -105,37 +110,88 @@ end -- ------------------------------------------------------------------------------------------------ state export type Quant = { y1dc: number, y1ac: number, y2dc: number, y2ac: number, uvdc: number, uvac: number } +-- a decoded frame / reference: the macroblock aligned planes with a Predict.BORDER pixel border +export type Ref = Predict.Planes & { extended: boolean } + export type State = { - -- persistent between frames (inter frames: TODO) + -- the frame context (saved and restored around frames that do not refresh it) proba: { number }, -- 4 * 8 * 3 * 11 token probabilities + ymodeProb: { number }, -- 4 + uvmodeProb: { number }, -- 3 + mvProb: { number }, -- 2 * 19 + -- persistent between frames (reset by key frames) segProba: { number }, -- 3 useSegment: boolean, updateMap: boolean, absoluteDelta: boolean, segQuant: { number }, -- 4 segFilter: { number }, -- 4 - refLfDelta: { number }, -- 4 - modeLfDelta: { number }, -- 4 + refLfDelta: { number }, -- 4: intra, last, golden, altref + modeLfDelta: { number }, -- 4: B_PRED, zero, nearest / near / new, split + signBias: { number }, -- 4 (by reference frame + 1) + segMap: { number }, -- the segment of every macroblock width: number, height: number, + mbw: number, + mbh: number, + hasKey: boolean, -- a key frame was decoded (inter frames need one) + last: Ref?, + golden: Ref?, + alt: Ref?, + pool: { Ref }, + -- the mode info of the current inter frame, (mbw + 1) x (mbh + 1) with a zero top row and left column + miRef: { number }, + miMode: { number }, + miMvR: { number }, + miMvC: { number }, + miSubR: { number }, -- 16 per macroblock + miSubC: { number }, + miN: number, -- the size of the mode info arrays (allocated by the first inter frame) + pred: buffer?, -- the inter predictions of a row } function Decode.new(): State return { proba = table.clone(COEFF_PROBA0), + ymodeProb = table.clone(Tables.YMODE_PROB), + uvmodeProb = table.clone(Tables.UVMODE_PROB), + mvProb = table.clone(Tables.MV_DEFAULT), segProba = { 255, 255, 255 }, useSegment = false, updateMap = false, - absoluteDelta = true, + absoluteDelta = false, segQuant = { 0, 0, 0, 0 }, segFilter = { 0, 0, 0, 0 }, refLfDelta = { 0, 0, 0, 0 }, modeLfDelta = { 0, 0, 0, 0 }, + signBias = { 0, 0, 0, 0 }, + segMap = {}, width = 0, height = 0, + mbw = 0, + mbh = 0, + hasKey = false, + last = nil, + golden = nil, + alt = nil, + pool = {}, + miRef = {}, + miMode = {}, + miMvR = {}, + miMvC = {}, + miSubR = {}, + miSubC = {}, + miN = 0, + pred = nil, } end +-- reset(state): drops the references; the next frame must be a key frame +function Decode.reset(st: State) + st.hasKey = false + st.last, st.golden, st.alt = nil, nil, nil +end + -- header(buf, off, len) -> { keyFrame, profile, show, partitionLength, width, height, xscale, yscale } | nil, msg function Decode.header(buf: buffer, off: number, len: number): (any, string?) if len < 3 then @@ -333,7 +389,11 @@ local function getCoeffs(br: Br, P: { number }, t: number, ctx: number, dqDc: nu v = -v end end - writei16(out, o + ZIGZAG[n + 1] * 2, v * (if n > 0 then dqAc else dqDc)) + if n > 0 then + writei16(out, o + ZIGZAG[n + 1] * 2, v * dqAc) + else + writei16(out, o + ZIGZAG[n + 1] * 2, v * dqDc) + end n += 1 end br.value, br.bits, br.range, br.pos = value, bits, range, pos @@ -465,7 +525,10 @@ end -- prediction: modes 0 DC, 1 TM, 2 VE, 3 HE; 4 DC no top, 5 DC no left, 6 DC no top-left (16x16 and chroma) local function fill(b: buffer, dst: number, size: number, v: number) for j = 0, size - 1 do - bfill(b, dst + j * BPS, v, size) + local o = dst + j * BPS + for i = o, o + size - 4, 4 do + writeu32(b, i, v * 0x01010101) + end end end @@ -492,11 +555,18 @@ local function predictBlock(b: buffer, dst: number, size: number, mode: number) trueMotion(b, dst, size) elseif mode == 2 then for j = 0, size - 1 do - bcopy(b, dst + j * BPS, b, dst - BPS, size) + local o = dst + j * BPS + for i = 0, size - 4, 4 do + writeu32(b, o + i, readu32(b, dst - BPS + i)) + end end elseif mode == 3 then for j = 0, size - 1 do - bfill(b, dst + j * BPS, readu8(b, dst + j * BPS - 1), size) + local o = dst + j * BPS + local v = readu8(b, o - 1) * 0x01010101 + for i = o, o + size - 4, 4 do + writeu32(b, i, v) + end end elseif mode == 4 then -- no top: left samples local dc = size // 2 @@ -545,10 +615,10 @@ local function predict4(b: buffer, dst: number, mode: number) elseif mode == 3 then local A, B, C, D = readu8(b, dst - 1 - BPS), readu8(b, dst - 1), readu8(b, dst - 1 + BPS), readu8(b, dst - 1 + 2 * BPS) local E = readu8(b, dst - 1 + 3 * BPS) - bfill(b, dst, avg3(A, B, C), 4) - bfill(b, dst + BPS, avg3(B, C, D), 4) - bfill(b, dst + 2 * BPS, avg3(C, D, E), 4) - bfill(b, dst + 3 * BPS, avg3(D, E, E), 4) + writeu32(b, dst, avg3(A, B, C) * 0x01010101) + writeu32(b, dst + BPS, avg3(B, C, D) * 0x01010101) + writeu32(b, dst + 2 * BPS, avg3(C, D, E) * 0x01010101) + writeu32(b, dst + 3 * BPS, avg3(D, E, E) * 0x01010101) else local I, J, K, L = readu8(b, dst - 1), readu8(b, dst - 1 + BPS), readu8(b, dst - 1 + 2 * BPS), readu8(b, dst - 1 + 3 * BPS) local t = dst - BPS @@ -703,75 +773,92 @@ local function checkMode(mbx: number, mby: number, mode: number): number end -- ------------------------------------------------------------------------------------------------ loop filter -local function sclip1(v: number): number - return if v < -128 then -128 elseif v > 127 then 127 else v -end -local function sclip2(v: number): number - return if v < -16 then -16 elseif v > 15 then 15 else v -end - -local function doFilter2(b: buffer, p: number, step: number) - local p1, p0, q0, q1 = readu8(b, p - 2 * step), readu8(b, p - step), readu8(b, p), readu8(b, p + step) - local a = 3 * (q0 - p0) + sclip1(p1 - q1) - local a1 = sclip2((a + 4) // 8) - local a2 = sclip2((a + 3) // 8) - writeu8(b, p - step, clip8(p0 + a2)) - writeu8(b, p, clip8(q0 - a1)) -end - -local function doFilter4(b: buffer, p: number, step: number) - local p1, p0, q0, q1 = readu8(b, p - 2 * step), readu8(b, p - step), readu8(b, p), readu8(b, p + step) - local a = 3 * (q0 - p0) - local a1 = sclip2((a + 4) // 8) - local a2 = sclip2((a + 3) // 8) - local a3 = (a1 + 1) // 2 - writeu8(b, p - 2 * step, clip8(p1 + a3)) - writeu8(b, p - step, clip8(p0 + a2)) - writeu8(b, p, clip8(q0 - a1)) - writeu8(b, p + step, clip8(q1 - a3)) -end - -local function doFilter6(b: buffer, p: number, step: number) - local p2, p1, p0 = readu8(b, p - 3 * step), readu8(b, p - 2 * step), readu8(b, p - step) - local q0, q1, q2 = readu8(b, p), readu8(b, p + step), readu8(b, p + 2 * step) - local a = sclip1(3 * (q0 - p0) + sclip1(p1 - q1)) - local a1 = (27 * a + 63) // 128 - local a2 = (18 * a + 63) // 128 - local a3 = (9 * a + 63) // 128 - writeu8(b, p - 3 * step, clip8(p2 + a3)) - writeu8(b, p - 2 * step, clip8(p1 + a2)) - writeu8(b, p - step, clip8(p0 + a1)) - writeu8(b, p, clip8(q0 - a1)) - writeu8(b, p + step, clip8(q1 - a2)) - writeu8(b, p + 2 * step, clip8(q2 - a3)) -end +-- the filters are libwebp's DoFilter2 / DoFilter4 / DoFilter6 inlined into their loops (VP8ksclip1 clamps to +-- [-128, 127], VP8ksclip2 to [-16, 15], VP8kclip1 to [0, 255]). Arithmetic shifts of small signed values are +-- logical shifts of the value plus a bias: (a + 4) >> 3 = rshift(a + 4 + 1024, 3) - 128 for a >= -1024. +-- simpleFilter(b, p, step, along, thresh): SimpleVFilter16 / SimpleHFilter16 (16 positions). A position whose filter +-- value a is 0 changes nothing and is skipped before the mask (flat areas). local function simpleFilter(b: buffer, p: number, step: number, along: number, thresh: number) local t2 = 2 * thresh + 1 - for i = 0, 15 do - local q = p + i * along - local p1, p0, q0, q1 = readu8(b, q - 2 * step), readu8(b, q - step), readu8(b, q), readu8(b, q + step) - if 4 * abs(p0 - q0) + abs(p1 - q1) <= t2 then - doFilter2(b, q, step) + for _ = 1, 16 do + local p1, p0, q0, q1 = readu8(b, p - 2 * step), readu8(b, p - step), readu8(b, p), readu8(b, p + step) + local w = p1 - q1 + local a = 3 * (q0 - p0) + (if w < -128 then -128 elseif w > 127 then 127 else w) + if a ~= 0 and 4 * abs(p0 - q0) + abs(w) <= t2 then + local a1 = rshift(a + 1028, 3) - 128 + if a1 < -16 then + a1 = -16 + elseif a1 > 15 then + a1 = 15 + end + local a2 = rshift(a + 1027, 3) - 128 + if a2 < -16 then + a2 = -16 + elseif a2 > 15 then + a2 = 15 + end + local v = p0 + a2 + writeu8(b, p - step, if v < 0 then 0 elseif v > 255 then 255 else v) + v = q0 - a1 + writeu8(b, p, if v < 0 then 0 elseif v > 255 then 255 else v) end + p += along end end --- filterLoop(b, p, hstride, vstride, size, thresh, ithresh, hevThresh, six): FilterLoop26 (six) / FilterLoop24 -local function filterLoop(b: buffer, p: number, hs: number, vs: number, size: number, thresh: number, it: number, hevT: number, six: boolean) +-- filterEdge(b, p, hs, vs, size, thresh, it, hevT): the macroblock edge filter (FilterLoop26) +local function filterEdge(b: buffer, p: number, hs: number, vs: number, size: number, thresh: number, it: number, hevT: number) local t2 = 2 * thresh + 1 for _ = 1, size do local p1, p0, q0, q1 = readu8(b, p - 2 * hs), readu8(b, p - hs), readu8(b, p), readu8(b, p + hs) - if 4 * abs(p0 - q0) + abs(p1 - q1) <= t2 and abs(p1 - p0) <= it and abs(q1 - q0) <= it then - local p3, p2 = readu8(b, p - 4 * hs), readu8(b, p - 3 * hs) - local q2, q3 = readu8(b, p + 2 * hs), readu8(b, p + 3 * hs) - if abs(p3 - p2) <= it and abs(p2 - p1) <= it and abs(q3 - q2) <= it and abs(q2 - q1) <= it then - if abs(p1 - p0) > hevT or abs(q1 - q0) > hevT then - doFilter2(b, p, hs) - elseif six then - doFilter6(b, p, hs) - else - doFilter4(b, p, hs) + local w = p1 - q1 + local a = 3 * (q0 - p0) + (if w < -128 then -128 elseif w > 127 then 127 else w) + if a ~= 0 then + local dp, dq = abs(p1 - p0), abs(q1 - q0) + if 4 * abs(p0 - q0) + abs(w) <= t2 and dp <= it and dq <= it then + local p3, p2 = readu8(b, p - 4 * hs), readu8(b, p - 3 * hs) + local q2, q3 = readu8(b, p + 2 * hs), readu8(b, p + 3 * hs) + if abs(p3 - p2) <= it and abs(p2 - p1) <= it and abs(q3 - q2) <= it and abs(q2 - q1) <= it then + if dp > hevT or dq > hevT then + local a1 = rshift(a + 1028, 3) - 128 + if a1 < -16 then + a1 = -16 + elseif a1 > 15 then + a1 = 15 + end + local a2 = rshift(a + 1027, 3) - 128 + if a2 < -16 then + a2 = -16 + elseif a2 > 15 then + a2 = 15 + end + local v = p0 + a2 + writeu8(b, p - hs, if v < 0 then 0 elseif v > 255 then 255 else v) + v = q0 - a1 + writeu8(b, p, if v < 0 then 0 elseif v > 255 then 255 else v) + else + if a < -128 then + a = -128 + elseif a > 127 then + a = 127 + end + local a1 = rshift(27 * a + 4159, 7) - 32 + local a2 = rshift(18 * a + 4159, 7) - 32 + local a3 = rshift(9 * a + 4159, 7) - 32 + local v = p2 + a3 + writeu8(b, p - 3 * hs, if v < 0 then 0 elseif v > 255 then 255 else v) + v = p1 + a2 + writeu8(b, p - 2 * hs, if v < 0 then 0 elseif v > 255 then 255 else v) + v = p0 + a1 + writeu8(b, p - hs, if v < 0 then 0 elseif v > 255 then 255 else v) + v = q0 - a1 + writeu8(b, p, if v < 0 then 0 elseif v > 255 then 255 else v) + v = q1 - a2 + writeu8(b, p + hs, if v < 0 then 0 elseif v > 255 then 255 else v) + v = q2 - a3 + writeu8(b, p + 2 * hs, if v < 0 then 0 elseif v > 255 then 255 else v) + end end end end @@ -779,51 +866,436 @@ local function filterLoop(b: buffer, p: number, hs: number, vs: number, size: nu end end +-- filterInner(b, p, hs, vs, size, thresh, it, hevT): the inner edge filter (FilterLoop24); nothing changes when +-- q0 == p0 and p1 == q1 +local function filterInner(b: buffer, p: number, hs: number, vs: number, size: number, thresh: number, it: number, hevT: number) + local t2 = 2 * thresh + 1 + for _ = 1, size do + local p1, p0, q0, q1 = readu8(b, p - 2 * hs), readu8(b, p - hs), readu8(b, p), readu8(b, p + hs) + local w = p1 - q1 + if q0 ~= p0 or w ~= 0 then + local dp, dq = abs(p1 - p0), abs(q1 - q0) + if 4 * abs(p0 - q0) + abs(w) <= t2 and dp <= it and dq <= it then + local p3, p2 = readu8(b, p - 4 * hs), readu8(b, p - 3 * hs) + local q2, q3 = readu8(b, p + 2 * hs), readu8(b, p + 3 * hs) + if abs(p3 - p2) <= it and abs(p2 - p1) <= it and abs(q3 - q2) <= it and abs(q2 - q1) <= it then + local hev = dp > hevT or dq > hevT + local a = 3 * (q0 - p0) + if hev then + a += if w < -128 then -128 elseif w > 127 then 127 else w + end + local a1 = rshift(a + 1028, 3) - 128 + if a1 < -16 then + a1 = -16 + elseif a1 > 15 then + a1 = 15 + end + local a2 = rshift(a + 1027, 3) - 128 + if a2 < -16 then + a2 = -16 + elseif a2 > 15 then + a2 = 15 + end + local v = p0 + a2 + writeu8(b, p - hs, if v < 0 then 0 elseif v > 255 then 255 else v) + v = q0 - a1 + writeu8(b, p, if v < 0 then 0 elseif v > 255 then 255 else v) + if not hev then + local a3 = rshift(a1 + 17, 1) - 8 + v = p1 + a3 + writeu8(b, p - 2 * hs, if v < 0 then 0 elseif v > 255 then 255 else v) + v = q1 - a3 + writeu8(b, p + hs, if v < 0 then 0 elseif v > 255 then 255 else v) + end + end + end + end + p += vs + end +end + +-- ------------------------------------------------------------------------------------------------ inter modes +local MODE_CTX = Tables.MODE_CONTEXTS +local SUB_MV_REF_PROB = Tables.SUB_MV_REF_PROB +local SPLIT_OFFSET, SPLIT_FILL, SPLIT_COUNT = Tables.SPLIT_OFFSET, Tables.SPLIT_FILL, Tables.SPLIT_COUNT +local BMODE_PROB = Tables.BMODE_PROB +local MV_UPDATE = Tables.MV_UPDATE + +-- macroblock modes (the row arrays and miMode): 0 DC, 1 TM, 2 V, 3 H (16x16 intra, libwebp's numbering), 4 B_PRED, +-- 5 ZEROMV, 6 NEARESTMV, 7 NEARMV, 8 NEWMV, 9 SPLITMV. Their loop filter mode delta index: +local MODE_LF = { 1, 1, 1, 1, 0, 1, 2, 2, 2, 3 } + +-- a 4x4 intra mode with the fixed probabilities P[o + 1 .. o + 9] (libvpx vp8_bmode_tree, libwebp's numbering) +local function readBMode(br: Br, P: { number }, o: number): number + if getBit(br, P[o + 1]) == 0 then + return 0 + elseif getBit(br, P[o + 2]) == 0 then + return 1 + elseif getBit(br, P[o + 3]) == 0 then + return 2 + elseif getBit(br, P[o + 4]) == 0 then + if getBit(br, P[o + 5]) == 0 then + return 3 + end + return if getBit(br, P[o + 6]) == 0 then 4 else 5 + elseif getBit(br, P[o + 7]) == 0 then + return 6 + elseif getBit(br, P[o + 8]) == 0 then + return 7 + end + return if getBit(br, P[o + 9]) == 0 then 8 else 9 +end + +-- one motion vector component (libvpx read_mvcomponent) with the probabilities P[o + 1 .. o + 19], in quarter pixels +local function readMvComponent(br: Br, P: { number }, o: number): number + local x + if getBit(br, P[o + 1]) == 1 then -- long: bits 0-2, then 9-4, then bit 3 (implicit when nothing above it is set) + x = getBit(br, P[o + 10]) + 2 * getBit(br, P[o + 11]) + 4 * getBit(br, P[o + 12]) + for i = 9, 4, -1 do + x += getBit(br, P[o + 10 + i]) * lshift(1, i) + end + if x < 16 or getBit(br, P[o + 13]) == 1 then + x += 8 + end + elseif getBit(br, P[o + 3]) == 0 then -- short tree + if getBit(br, P[o + 4]) == 0 then + x = getBit(br, P[o + 5]) + else + x = 2 + getBit(br, P[o + 6]) + end + elseif getBit(br, P[o + 7]) == 0 then + x = 4 + getBit(br, P[o + 8]) + else + x = 6 + getBit(br, P[o + 9]) + end + if x ~= 0 and getBit(br, P[o + 2]) == 1 then + x = -x + end + return x +end + +export type Rows = { + i4: { boolean }, -- no Y2 block (B_PRED or SPLITMV) + modes: { number }, -- 16 per macroblock: the 16x16 intra mode or the 4x4 ones + uv: { number }, + ref: { number }, -- 0 intra, 1 last, 2 golden, 3 altref + mode: { number }, -- 0..9 (see MODE_LF) + part: { number }, -- SPLITMV partitioning (0 16x8, 1 8x16, 2 8x8, 3 4x4) or -1 +} + +local nr, nc, cnt = table.create(4, 0), table.create(4, 0), table.create(4, 0) + +-- readInterMb(st, br, probs, mi, mbx, mby, rows): the modes and motion vectors of one inter frame macroblock (libvpx +-- read_mb_modes_mv with vp8_find_near_mvs); mi: its 1-based index in the mode info arrays +local function readInterMb(st: State, br: Br, probIntra: number, probLast: number, probGf: number, mi: number, mbx: number, mby: number, rows: Rows) + local miRef, miMode, miMvR, miMvC = st.miRef, st.miMode, st.miMvR, st.miMvC + local x1 = mbx + 1 + if getBit(br, probIntra) == 0 then + local P = st.ymodeProb + local ymode + if getBit(br, P[1]) == 0 then + ymode = 0 + elseif getBit(br, P[2]) == 0 then + ymode = if getBit(br, P[3]) == 0 then 2 else 3 + else + ymode = if getBit(br, P[4]) == 0 then 1 else 4 + end + local modes = rows.modes + if ymode == 4 then + for k = mbx * 16 + 1, mbx * 16 + 16 do + modes[k] = readBMode(br, BMODE_PROB, 0) + end + else + modes[mbx * 16 + 1] = ymode + end + local U = st.uvmodeProb + if getBit(br, U[1]) == 0 then + rows.uv[x1] = 0 + elseif getBit(br, U[2]) == 0 then + rows.uv[x1] = 2 + else + rows.uv[x1] = if getBit(br, U[3]) == 0 then 3 else 1 + end + rows.i4[x1] = ymode == 4 + rows.ref[x1] = 0 + rows.mode[x1] = ymode + rows.part[x1] = -1 + miRef[mi], miMode[mi], miMvR[mi], miMvC[mi] = 0, ymode, 0, 0 + return + end + local ref = 1 + if getBit(br, probLast) == 1 then + ref = 2 + getBit(br, probGf) + end + -- the near motion vectors of the above, left and above-left macroblocks, sign corrected + local bias = st.signBias + local sb = bias[ref + 1] + local a = mi - (st.mbw + 1) + local l = mi - 1 + local al = a - 1 + for k = 1, 4 do + nr[k], nc[k], cnt[k] = 0, 0, 0 + end + local n = 1 + local rf = miRef[a] + if rf ~= 0 then + local r, c = miMvR[a], miMvC[a] + if r ~= 0 or c ~= 0 then + if bias[rf + 1] ~= sb then + r, c = -r, -c + end + n = 2 + nr[2], nc[2] = r, c + end + cnt[n] += 2 + end + rf = miRef[l] + if rf ~= 0 then + local r, c = miMvR[l], miMvC[l] + if r ~= 0 or c ~= 0 then + if bias[rf + 1] ~= sb then + r, c = -r, -c + end + if r ~= nr[n] or c ~= nc[n] then + n += 1 + nr[n], nc[n] = r, c + end + cnt[n] += 2 + else + cnt[1] += 2 + end + end + rf = miRef[al] + if rf ~= 0 then + local r, c = miMvR[al], miMvC[al] + if r ~= 0 or c ~= 0 then + if bias[rf + 1] ~= sb then + r, c = -r, -c + end + if r ~= nr[n] or c ~= nc[n] then + n += 1 + nr[n], nc[n] = r, c + end + cnt[n] += 1 + else + cnt[1] += 1 + end + end + -- clamping bounds (vp8_clamp_mv2), in eighth pixels + local mbw, mbh = st.mbw, st.mbh + local toL, toR = -mbx * 128 - 128, (mbw - 1 - mbx) * 128 + 128 + local toT, toB = -mby * 128 - 128, (mbh - 1 - mby) * 128 + 128 + local mode, mvr, mvc, part = 5, 0, 0, -1 + if getBit(br, MODE_CTX[cnt[1] * 4 + 1]) == 1 then + if cnt[4] > 0 and nr[n] == nr[2] and nc[n] == nc[2] then + cnt[2] += 1 + end + if cnt[3] > cnt[2] then + cnt[2], cnt[3] = cnt[3], cnt[2] + nr[2], nr[3] = nr[3], nr[2] + nc[2], nc[3] = nc[3], nc[2] + end + local k + if getBit(br, MODE_CTX[cnt[2] * 4 + 2]) == 0 then + mode, k = 6, 2 + elseif getBit(br, MODE_CTX[cnt[3] * 4 + 3]) == 0 then + mode, k = 7, 3 + else + k = if cnt[2] >= cnt[1] then 2 else 1 + end + mvr, mvc = nr[k], nc[k] + if mvc < toL then + mvc = toL + elseif mvc > toR then + mvc = toR + end + if mvr < toT then + mvr = toT + elseif mvr > toB then + mvr = toB + end + if mode == 5 then + -- mvr, mvc: the best vector; new or split + local P = st.mvProb + local sc = (if miMode[a] == 9 then 2 else 0) + (if miMode[l] == 9 then 2 else 0) + (if miMode[al] == 9 then 1 else 0) + if getBit(br, MODE_CTX[sc * 4 + 4]) == 0 then + mode = 8 + mvr += readMvComponent(br, P, 0) * 2 + mvc += readMvComponent(br, P, 19) * 2 + else + mode = 9 + local bestR, bestC = mvr, mvc + local s, nump + if getBit(br, 110) == 1 then + if getBit(br, 111) == 1 then + s, nump = getBit(br, 150), 2 + else + s, nump = 2, 4 + end + else + s, nump = 3, 16 + end + part = s + local subR, subC = st.miSubR, st.miSubC + local sb0 = (mi - 1) * 16 + local lb, ab = (l - 1) * 16, (a - 1) * 16 + local splitL, splitA = miMode[l] == 9, miMode[a] == 9 + local count = SPLIT_COUNT[s + 1] + for j = 0, nump - 1 do + local b = SPLIT_OFFSET[s * 16 + j + 1] + local lr, lc, ar, ac + if b % 4 ~= 0 then + lr, lc = subR[sb0 + b], subC[sb0 + b] + elseif splitL then + lr, lc = subR[lb + b + 4], subC[lb + b + 4] + else + lr, lc = miMvR[l], miMvC[l] + end + if b >= 4 then + ar, ac = subR[sb0 + b - 3], subC[sb0 + b - 3] + elseif splitA then + ar, ac = subR[ab + b + 13], subC[ab + b + 13] + else + ar, ac = miMvR[a], miMvC[a] + end + local pi = ((if ar == 0 and ac == 0 then 4 else 0) + (if lr == 0 and lc == 0 then 2 else 0) + (if lr == ar and lc == ac then 1 else 0)) * 3 + local r, c + if getBit(br, SUB_MV_REF_PROB[pi + 1]) == 0 then + r, c = lr, lc + elseif getBit(br, SUB_MV_REF_PROB[pi + 2]) == 0 then + r, c = ar, ac + elseif getBit(br, SUB_MV_REF_PROB[pi + 3]) == 0 then + r, c = 0, 0 + else + r = bestR + readMvComponent(br, P, 0) * 2 + c = bestC + readMvComponent(br, P, 19) * 2 + end + local fo = s * 16 + j * count + for i = fo + 1, fo + count do + local q = sb0 + SPLIT_FILL[i] + 1 + subR[q], subC[q] = r, c + end + end + mvr, mvc = subR[sb0 + 16], subC[sb0 + 16] + end + end + end + rows.i4[x1] = mode == 9 + rows.ref[x1] = ref + rows.mode[x1] = mode + rows.part[x1] = part + miRef[mi], miMode[mi], miMvR[mi], miMvC[mi] = ref, mode, mvr, mvc +end + -- ------------------------------------------------------------------------------------------------ frame export type Frame = { width: number, height: number, - y: buffer, -- width * height - u: buffer, -- ceil(w / 2) * ceil(h / 2) - v: buffer, + ref: Ref, -- the decoded planes (the decoder keeps them as a reference: copy them out, see cropTo) header: any, } --- decodeFrame(state, buf, off, len, maxPixels) -> Frame | nil, message +local BORDER = Predict.BORDER + +local function newRef(mbw: number, mbh: number): Ref + local ys, uvs = mbw * 16 + 2 * BORDER, mbw * 8 + 2 * BORDER + return { + Y = bcreate(ys * (mbh * 16 + 2 * BORDER)), + U = bcreate(uvs * (mbh * 8 + 2 * BORDER)), + V = bcreate(uvs * (mbh * 8 + 2 * BORDER)), + ys = ys, + uvs = uvs, + yb = BORDER * ys + BORDER, + uvb = BORDER * uvs + BORDER, + mbw = mbw, + mbh = mbh, + extended = false, + } +end + +-- a frame buffer no reference uses +local function freeRef(st: State): Ref + for _, r in st.pool do + if r ~= st.last and r ~= st.golden and r ~= st.alt then + return r + end + end + local r = newRef(st.mbw, st.mbh) + table.insert(st.pool, r) + return r +end + +-- cropTo(frame, dy, oy, du, ou, dv, ov): copies the visible planes out (luma stride width, chroma ceil(width / 2)) +function Decode.cropTo(f: Frame, dy: buffer, oy: number, du: buffer, ou: number, dv: buffer, ov: number) + local r = f.ref + local w, h = f.width, f.height + local cw, chh = (w + 1) // 2, (h + 1) // 2 + local Y, U, V, ys, uvs, yb, uvb = r.Y, r.U, r.V, r.ys, r.uvs, r.yb, r.uvb + for j = 0, h - 1 do + bcopy(dy, oy + j * w, Y, yb + j * ys, w) + end + for j = 0, chh - 1 do + bcopy(du, ou + j * cw, U, uvb + j * uvs, cw) + bcopy(dv, ov + j * cw, V, uvb + j * uvs, cw) + end +end + +-- decodeFrame(state, buf, off, len, maxPixels) -> Frame | nil, message: one key or inter frame of the stream function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, maxPixels: number): (Frame?, string?) local hdr, herr = Decode.header(buf, off, len) if not hdr then return nil, herr end - if not hdr.keyFrame then - return nil, "unsupported: inter frames" + local key = hdr.keyFrame + local width, height, p, left + if key then + width, height = hdr.width, hdr.height + if width == 0 or height == 0 then + return nil, "zero frame size" + end + if width * height > maxPixels then + return nil, "limit: " .. width .. " x " .. height .. " is over maxPixels" + end + p, left = off + 10, len - 10 + else + if not st.hasKey then + return nil, "inter frame without a key frame" + end + width, height = st.width, st.height + p, left = off + 3, len - 3 end - if not hdr.show then - return nil, "unsupported: invisible frame" - end - local width, height = hdr.width, hdr.height - if width == 0 or height == 0 then - return nil, "zero frame size" - end - if width * height > maxPixels then - return nil, "limit: " .. width .. " x " .. height .. " is over maxPixels" - end - st.width, st.height = width, height - local p = off + 10 - local left = len - 10 if hdr.partitionLength > left then return nil, "truncated: first partition" end - -- key frame: reset the probabilities and the segment header - st.segProba = { 255, 255, 255 } - st.useSegment, st.updateMap, st.absoluteDelta = false, false, true - st.segQuant = { 0, 0, 0, 0 } - st.segFilter = { 0, 0, 0, 0 } + local mbw, mbh = (width + 15) // 16, (height + 15) // 16 + if key then + st.hasKey = false + if width ~= st.width or height ~= st.height then + st.width, st.height, st.mbw, st.mbh = width, height, mbw, mbh + st.last, st.golden, st.alt, st.pool = nil, nil, nil, {} + st.miN, st.pred = 0, nil + st.segMap = table.create(mbw * mbh, 0) + end + -- key frames reset the frame context, the segment and loop filter deltas + st.proba = table.clone(COEFF_PROBA0) + st.ymodeProb = table.clone(Tables.YMODE_PROB) + st.uvmodeProb = table.clone(Tables.UVMODE_PROB) + st.mvProb = table.clone(Tables.MV_DEFAULT) + st.segProba = { 255, 255, 255 } + st.useSegment, st.updateMap, st.absoluteDelta = false, false, false + st.segQuant = { 0, 0, 0, 0 } + st.segFilter = { 0, 0, 0, 0 } + st.refLfDelta = { 0, 0, 0, 0 } + st.modeLfDelta = { 0, 0, 0, 0 } + st.signBias = { 0, 0, 0, 0 } + end local br = newBr(buf, p, hdr.partitionLength) p += hdr.partitionLength left -= hdr.partitionLength - getValue(br, 1) -- colour space - getValue(br, 1) -- clamping type + if key then + getValue(br, 1) -- colour space + getValue(br, 1) -- clamping type + end -- segment header st.useSegment = getValue(br, 1) == 1 if st.useSegment then @@ -928,71 +1400,140 @@ function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, ma uvac = AC_TABLE[cq(q + dquvac, 127) + 1], } end - getValue(br, 1) -- refresh entropy probabilities (ignored, as libwebp does) + -- reference updates (inter frames) + local refreshGolden, refreshAlt, copyToGolden, copyToAlt = true, true, 0, 0 + if not key then + refreshGolden = getValue(br, 1) == 1 + refreshAlt = getValue(br, 1) == 1 + copyToGolden = if refreshGolden then 0 else getValue(br, 2) + copyToAlt = if refreshAlt then 0 else getValue(br, 2) + st.signBias[3] = getValue(br, 1) + st.signBias[4] = getValue(br, 1) + end + -- a frame that does not refresh the context decodes with the updates below, then the context comes back + local saved: { { number } }? = nil + if getValue(br, 1) == 0 then + saved = { table.clone(st.proba), table.clone(st.ymodeProb), table.clone(st.uvmodeProb), table.clone(st.mvProb) } + end + local refreshLast = key or getValue(br, 1) == 1 -- token probabilities local P = st.proba for i = 1, 1056 do - P[i] = if getBit(br, COEFF_UPDATE_PROBA[i]) == 1 then getValue(br, 8) else COEFF_PROBA0[i] + if getBit(br, COEFF_UPDATE_PROBA[i]) == 1 then + P[i] = getValue(br, 8) + end end local useSkip = getValue(br, 1) == 1 local skipP = if useSkip then getValue(br, 8) else 0 + local probIntra, probLast, probGf = 0, 0, 0 + if not key then + probIntra = getValue(br, 8) + probLast = getValue(br, 8) + probGf = getValue(br, 8) + if getValue(br, 1) == 1 then + for i = 1, 4 do + st.ymodeProb[i] = getValue(br, 8) + end + end + if getValue(br, 1) == 1 then + for i = 1, 3 do + st.uvmodeProb[i] = getValue(br, 8) + end + end + local M = st.mvProb + for i = 1, 38 do + if getBit(br, MV_UPDATE[i]) == 1 then + local x = getValue(br, 7) + M[i] = if x == 0 then 1 else x * 2 + end + end + end + local function fail(msg: string): (Frame?, string?) + if saved then + st.proba, st.ymodeProb, st.uvmodeProb, st.mvProb = saved[1], saved[2], saved[3], saved[4] + end + return nil, msg + end if br.eof then - return nil, "truncated: frame header" + return fail("truncated: frame header") end - -- filter strengths per segment and i4x4: { limit, ilevel, hevThresh } - local fstr: { { number } } = {} - for s = 1, 4 do - local base - if st.useSegment then - base = st.segFilter[s] - if not st.absoluteDelta then - base += level + -- loop filter levels [segment][reference][mode delta index] and, per level, the interior limit and hev threshold + local lvlTab = table.create(64, 0) + local ilTab, hevTab = table.create(64, 0), table.create(64, 0) + if filterType > 0 then + for s = 0, 3 do + local base + if st.useSegment then + base = st.segFilter[s + 1] + if not st.absoluteDelta then + base += level + end + else + base = level + end + for rf = 0, 3 do + for m = 0, 3 do + local lv = base + if useLfDelta then + lv += st.refLfDelta[rf + 1] + if rf > 0 or m == 0 then + lv += st.modeLfDelta[m + 1] + end + end + lvlTab[s * 16 + rf * 4 + m + 1] = if lv < 0 then 0 elseif lv > 63 then 63 else lv + end end - else - base = level end - for i4 = 0, 1 do - local lv = base - if useLfDelta then - lv += st.refLfDelta[1] - if i4 == 1 then - lv += st.modeLfDelta[1] + for lv = 1, 63 do + local il = lv + if sharpness > 0 then + il = rshift(il, if sharpness > 4 then 2 else 1) + if il > 9 - sharpness then + il = 9 - sharpness end end - lv = if lv < 0 then 0 elseif lv > 63 then 63 else lv - local e = { 0, 0, 0 } - if lv > 0 then - local il = lv - if sharpness > 0 then - if sharpness > 4 then - il = rshift(il, 2) - else - il = rshift(il, 1) - end - if il > 9 - sharpness then - il = 9 - sharpness - end - end - if il < 1 then - il = 1 - end - e[1] = 2 * lv + il - e[2] = il - e[3] = if lv >= 40 then 2 elseif lv >= 15 then 1 else 0 + ilTab[lv] = if il < 1 then 1 else il + if key then + hevTab[lv] = if lv >= 40 then 2 elseif lv >= 15 then 1 else 0 + else + hevTab[lv] = if lv >= 40 then 3 elseif lv >= 20 then 2 elseif lv >= 15 then 1 else 0 end - fstr[(s - 1) * 2 + i4 + 1] = e end end - -- the frame, macroblock aligned - local mbw, mbh = (width + 15) // 16, (height + 15) // 16 - local ys, uvs = mbw * 16, mbw * 8 - local Y = bcreate(ys * mbh * 16) - local U = bcreate(uvs * mbh * 8) - local V = bcreate(uvs * mbh * 8) - local topY, topU, topV = bcreate(ys), bcreate(uvs), bcreate(uvs) + -- the frame buffer (macroblock aligned, with a border) and the references + local cur = freeRef(st) + cur.extended = false + local Y, U, V, ys, uvs, yb, uvb = cur.Y, cur.U, cur.V, cur.ys, cur.uvs, cur.yb, cur.uvb + local refs: { Ref } = {} + local bil, full = hdr.profile > 0, hdr.profile == 3 + if not key then + local rl, rg, ra = st.last :: Ref, st.golden :: Ref, st.alt :: Ref + refs[1], refs[2], refs[3] = rl, rg, ra + for k = 1, 3 do + local r = refs[k] + if not r.extended then + Predict.extend(r) + r.extended = true + end + end + end + local topY, topU, topV = bcreate(mbw * 16), bcreate(mbw * 8), bcreate(mbw * 8) local yuv = bcreate(YUV_SIZE) + local pred = yuv + if not key then + local nmi = (mbw + 1) * (mbh + 1) + if st.miN ~= nmi then + -- zero top row and left column: never written, they read as intra macroblocks without motion + st.miRef, st.miMode = table.create(nmi, 0), table.create(nmi, 0) + st.miMvR, st.miMvC = table.create(nmi, 0), table.create(nmi, 0) + st.miSubR, st.miSubC = table.create(nmi * 16, 0), table.create(nmi * 16, 0) + st.miN = nmi + st.pred = bcreate(YUV_SIZE * mbw) + end + pred = st.pred :: buffer + end local coeffs = bcreate(mbw * 768) local dcb = bcreate(32) -- per macroblock column / row state @@ -1000,9 +1541,15 @@ function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, ma local intraL = table.create(4, 0) local topNz = table.create(mbw, 0) local topNzDc = table.create(mbw, 0) - local mbI4 = table.create(mbw, false) - local mbModes = table.create(mbw * 16, 0) - local mbUv = table.create(mbw, 0) + local rows: Rows = { + i4 = table.create(mbw, false), + modes = table.create(mbw * 16, 0), + uv = table.create(mbw, 0), + ref = table.create(mbw, 0), + mode = table.create(mbw, 0), + part = table.create(mbw, -1), + } + local mbI4, mbModes, mbUv, mbRef, mbMode, mbPart = rows.i4, rows.modes, rows.uv, rows.ref, rows.mode, rows.part local mbSeg = table.create(mbw, 0) local mbSkip = table.create(mbw, 0) local mbNzY = table.create(mbw, 0) @@ -1013,26 +1560,46 @@ function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, ma local fInner = table.create(mbw * mbh, 0) local fHev = table.create(mbw * mbh, 0) local segProba = st.segProba + local segMap = st.segMap + local updateMap = st.updateMap + local miMvR, miMvC, miSubR, miSubC = st.miMvR, st.miMvC, st.miSubR, st.miSubC for mby = 0, mbh - 1 do local tbr = parts[band(mby, lastPart) + 1] - -- intra modes of the row (first partition) + -- modes of the row (first partition) for k = 1, 4 do intraL[k] = 0 end for mbx = 0, mbw - 1 do - local seg = 0 - if st.updateMap then + local x1 = mbx + 1 + local si = mby * mbw + x1 + local seg + if updateMap then if getBit(br, segProba[1]) == 0 then seg = getBit(br, segProba[2]) else seg = getBit(br, segProba[3]) + 2 end + segMap[si] = seg + elseif key then + seg = 0 + segMap[si] = 0 + else + seg = segMap[si] end - mbSeg[mbx + 1] = seg - mbSkip[mbx + 1] = if useSkip then getBit(br, skipP) else 0 + mbSeg[x1] = seg + mbSkip[x1] = 0 + if useSkip then + mbSkip[x1] = getBit(br, skipP) + end + if not key then + readInterMb(st, br, probIntra, probLast, probGf, (mby + 1) * (mbw + 1) + x1 + 1, mbx, mby, rows) + continue + end + mbRef[x1] = 0 + mbPart[x1] = -1 local i4 = getBit(br, 145) == 0 - mbI4[mbx + 1] = i4 + mbI4[x1] = i4 local t0 = mbx * 4 if not i4 then local ymode @@ -1042,11 +1609,13 @@ function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, ma ymode = if getBit(br, 163) == 1 then 2 else 0 end mbModes[mbx * 16 + 1] = ymode + mbMode[x1] = ymode for k = 1, 4 do intraT[t0 + k] = ymode intraL[k] = ymode end else + mbMode[x1] = 4 for y = 0, 3 do local ymode = intraL[y + 1] for x = 0, 3 do @@ -1081,15 +1650,15 @@ function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, ma end end if getBit(br, 142) == 0 then - mbUv[mbx + 1] = 0 + mbUv[x1] = 0 elseif getBit(br, 114) == 0 then - mbUv[mbx + 1] = 2 + mbUv[x1] = 2 else - mbUv[mbx + 1] = if getBit(br, 183) == 1 then 1 else 3 + mbUv[x1] = if getBit(br, 183) == 1 then 1 else 3 end end if br.eof then - return nil, "truncated: first partition (intra modes)" + return fail("truncated: first partition (modes)") end -- residuals (token partition) @@ -1103,13 +1672,14 @@ function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, ma local co = mbx * 768 bfill(coeffs, co, 0, 768) local first, acType + local dcNz = 0 if not i4 then bfill(dcb, 0, 0, 32) local ctx = topNzDc[x1] + leftNzDc local nz = getCoeffs(tbr, P, 1, ctx, q.y2dc, q.y2ac, 0, dcb, 0) - local f = if nz > 0 then 1 else 0 - topNzDc[x1] = f - leftNzDc = f + dcNz = if nz > 0 then 1 else 0 + topNzDc[x1] = dcNz + leftNzDc = dcNz if nz > 1 then transformWHT(dcb, coeffs, co) else @@ -1169,7 +1739,8 @@ function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, ma leftNz = band(outL, 255) mbNzY[x1] = nzY mbNzUv[x1] = nzUv - skip = if nzY == 0 and nzUv == 0 then 1 else 0 + -- no coefficient at all (libvpx: eobtotal == 0) skips the inner edges of the loop filter + skip = if nzY == 0 and nzUv == 0 and dcNz == 0 then 1 else 0 else topNz[x1] = 0 leftNz = 0 @@ -1181,19 +1752,27 @@ function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, ma mbNzUv[x1] = 0 end if filterType > 0 then - local e = fstr[mbSeg[x1] * 2 + (if i4 then 1 else 0) + 1] + local lv = lvlTab[mbSeg[x1] * 16 + mbRef[x1] * 4 + MODE_LF[mbMode[x1] + 1] + 1] local fi = mby * mbw + x1 - fLimit[fi] = e[1] - fIlevel[fi] = e[2] - fHev[fi] = e[3] + if lv > 0 then + local il = ilTab[lv] + fLimit[fi] = 2 * lv + il + fIlevel[fi] = il + fHev[fi] = hevTab[lv] + else + fLimit[fi] = 0 + end fInner[fi] = if i4 or skip == 0 then 1 else 0 end if tbr.eof then - return nil, "truncated: token partition" + return fail("truncated: token partition") end end - -- reconstruct the row (libwebp ReconstructRow) + -- reconstruct the row (libwebp ReconstructRow; inter macroblocks predict from the references) + if not key then + Predict.row(refs :: any, mby, mbw, mbRef, mbPart, miMvR, miMvC, miSubR, miSubC, (mby + 1) * (mbw + 1) + 1, pred, YUV_SIZE, Y_OFF, U_OFF, V_OFF, bil, full) + end for j = 0, 15 do writeu8(yuv, Y_OFF + j * BPS - 1, 129) end @@ -1212,67 +1791,106 @@ function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, ma end for mbx = 0, mbw - 1 do local x1 = mbx + 1 - if mbx > 0 then + local co = mbx * 768 + local bits = mbNzY[x1] + local rf = mbRef[x1] + if rf == 0 and mbx > 0 then + -- the left context of an intra macroblock: the previous macroblock's last columns for j = -1, 15 do - bcopy(yuv, Y_OFF + j * BPS - 4, yuv, Y_OFF + j * BPS + 12, 4) + writeu32(yuv, Y_OFF + j * BPS - 4, readu32(yuv, Y_OFF + j * BPS + 12)) end for j = -1, 7 do - bcopy(yuv, U_OFF + j * BPS - 4, yuv, U_OFF + j * BPS + 4, 4) - bcopy(yuv, V_OFF + j * BPS - 4, yuv, V_OFF + j * BPS + 4, 4) + writeu32(yuv, U_OFF + j * BPS - 4, readu32(yuv, U_OFF + j * BPS + 4)) + writeu32(yuv, V_OFF + j * BPS - 4, readu32(yuv, V_OFF + j * BPS + 4)) end end if mby > 0 then - bcopy(yuv, Y_OFF - BPS, topY, mbx * 16, 16) - bcopy(yuv, U_OFF - BPS, topU, mbx * 8, 8) - bcopy(yuv, V_OFF - BPS, topV, mbx * 8, 8) + local t = mbx * 16 + writeu32(yuv, Y_OFF - BPS, readu32(topY, t)) + writeu32(yuv, Y_OFF - BPS + 4, readu32(topY, t + 4)) + writeu32(yuv, Y_OFF - BPS + 8, readu32(topY, t + 8)) + writeu32(yuv, Y_OFF - BPS + 12, readu32(topY, t + 12)) + t = mbx * 8 + writeu32(yuv, U_OFF - BPS, readu32(topU, t)) + writeu32(yuv, U_OFF - BPS + 4, readu32(topU, t + 4)) + writeu32(yuv, V_OFF - BPS, readu32(topV, t)) + writeu32(yuv, V_OFF - BPS + 4, readu32(topV, t + 4)) end - local co = mbx * 768 - local bits = mbNzY[x1] - if mbI4[x1] then - local tr = Y_OFF - BPS + 16 - if mby > 0 then - if mbx >= mbw - 1 then - bfill(yuv, tr, readu8(topY, mbx * 16 + 15), 4) - else - bcopy(yuv, tr, topY, mbx * 16 + 16, 4) - end - end - bcopy(yuv, tr + 4 * BPS, yuv, tr, 4) - bcopy(yuv, tr + 8 * BPS, yuv, tr, 4) - bcopy(yuv, tr + 12 * BPS, yuv, tr, 4) - for n = 0, 15 do - local dst = Y_OFF + (n % 4) * 4 + (n // 4) * 4 * BPS - predict4(yuv, dst, mbModes[mbx * 16 + n + 1]) - doTransform(band(rshift(bits, 30 - 2 * n), 3), coeffs, co + n * 32, yuv, dst) - end - else - predictBlock(yuv, Y_OFF, 16, checkMode(mbx, mby, mbModes[mbx * 16 + 1])) + if rf > 0 then + -- the prediction (Predict.row): luma rows 0..15, then the chroma rows (U and V side by side) + local o = mbx * YUV_SIZE + bcopy(yuv, Y_OFF, pred, o + Y_OFF, 15 * BPS + 16) + bcopy(yuv, U_OFF, pred, o + U_OFF, 7 * BPS + 24) if bits ~= 0 then for n = 0, 15 do local dst = Y_OFF + (n % 4) * 4 + (n // 4) * 4 * BPS doTransform(band(rshift(bits, 30 - 2 * n), 3), coeffs, co + n * 32, yuv, dst) end end + else + if mbI4[x1] then + local tr = Y_OFF - BPS + 16 + if mby > 0 then + if mbx >= mbw - 1 then + writeu32(yuv, tr, readu8(topY, mbx * 16 + 15) * 0x01010101) + else + writeu32(yuv, tr, readu32(topY, mbx * 16 + 16)) + end + end + local trv = readu32(yuv, tr) + writeu32(yuv, tr + 4 * BPS, trv) + writeu32(yuv, tr + 8 * BPS, trv) + writeu32(yuv, tr + 12 * BPS, trv) + for n = 0, 15 do + local dst = Y_OFF + (n % 4) * 4 + (n // 4) * 4 * BPS + predict4(yuv, dst, mbModes[mbx * 16 + n + 1]) + doTransform(band(rshift(bits, 30 - 2 * n), 3), coeffs, co + n * 32, yuv, dst) + end + else + predictBlock(yuv, Y_OFF, 16, checkMode(mbx, mby, mbModes[mbx * 16 + 1])) + if bits ~= 0 then + for n = 0, 15 do + local dst = Y_OFF + (n % 4) * 4 + (n // 4) * 4 * BPS + doTransform(band(rshift(bits, 30 - 2 * n), 3), coeffs, co + n * 32, yuv, dst) + end + end + end + local uvm = checkMode(mbx, mby, mbUv[x1]) + predictBlock(yuv, U_OFF, 8, uvm) + predictBlock(yuv, V_OFF, 8, uvm) end - local uvm = checkMode(mbx, mby, mbUv[x1]) - predictBlock(yuv, U_OFF, 8, uvm) - predictBlock(yuv, V_OFF, 8, uvm) local buv = mbNzUv[x1] doUVTransform(buv, coeffs, co + 16 * 32, yuv, U_OFF) doUVTransform(rshift(buv, 8), coeffs, co + 20 * 32, yuv, V_OFF) if mby < mbh - 1 then - bcopy(topY, mbx * 16, yuv, Y_OFF + 15 * BPS, 16) - bcopy(topU, mbx * 8, yuv, U_OFF + 7 * BPS, 8) - bcopy(topV, mbx * 8, yuv, V_OFF + 7 * BPS, 8) + local t = mbx * 16 + local r = Y_OFF + 15 * BPS + writeu32(topY, t, readu32(yuv, r)) + writeu32(topY, t + 4, readu32(yuv, r + 4)) + writeu32(topY, t + 8, readu32(yuv, r + 8)) + writeu32(topY, t + 12, readu32(yuv, r + 12)) + t = mbx * 8 + r = U_OFF + 7 * BPS + writeu32(topU, t, readu32(yuv, r)) + writeu32(topU, t + 4, readu32(yuv, r + 4)) + writeu32(topV, t, readu32(yuv, r + 16)) + writeu32(topV, t + 4, readu32(yuv, r + 20)) end - local yo = mby * 16 * ys + mbx * 16 + local yo = yb + mby * 16 * ys + mbx * 16 for j = 0, 15 do - bcopy(Y, yo + j * ys, yuv, Y_OFF + j * BPS, 16) + local d, r = yo + j * ys, Y_OFF + j * BPS + writeu32(Y, d, readu32(yuv, r)) + writeu32(Y, d + 4, readu32(yuv, r + 4)) + writeu32(Y, d + 8, readu32(yuv, r + 8)) + writeu32(Y, d + 12, readu32(yuv, r + 12)) end - local uo = mby * 8 * uvs + mbx * 8 + local uo = uvb + mby * 8 * uvs + mbx * 8 for j = 0, 7 do - bcopy(U, uo + j * uvs, yuv, U_OFF + j * BPS, 8) - bcopy(V, uo + j * uvs, yuv, V_OFF + j * BPS, 8) + local d, r = uo + j * uvs, U_OFF + j * BPS + writeu32(U, d, readu32(yuv, r)) + writeu32(U, d + 4, readu32(yuv, r + 4)) + writeu32(V, d, readu32(yuv, r + 16)) + writeu32(V, d + 4, readu32(yuv, r + 20)) end end end @@ -1285,7 +1903,7 @@ function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, ma local limit = fLimit[fi] if limit ~= 0 then local inner = fInner[fi] == 1 - local yp = mby * 16 * ys + mbx * 16 + local yp = yb + mby * 16 * ys + mbx * 16 if filterType == 1 then if mbx > 0 then simpleFilter(Y, yp, 1, ys, limit + 4) @@ -1305,30 +1923,30 @@ function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, ma end else local il, hev = fIlevel[fi], fHev[fi] - local up = mby * 8 * uvs + mbx * 8 + local up = uvb + mby * 8 * uvs + mbx * 8 if mbx > 0 then - filterLoop(Y, yp, 1, ys, 16, limit + 4, il, hev, true) - filterLoop(U, up, 1, uvs, 8, limit + 4, il, hev, true) - filterLoop(V, up, 1, uvs, 8, limit + 4, il, hev, true) + filterEdge(Y, yp, 1, ys, 16, limit + 4, il, hev) + filterEdge(U, up, 1, uvs, 8, limit + 4, il, hev) + filterEdge(V, up, 1, uvs, 8, limit + 4, il, hev) end if inner then for k = 1, 3 do - filterLoop(Y, yp + 4 * k, 1, ys, 16, limit, il, hev, false) + filterInner(Y, yp + 4 * k, 1, ys, 16, limit, il, hev) end - filterLoop(U, up + 4, 1, uvs, 8, limit, il, hev, false) - filterLoop(V, up + 4, 1, uvs, 8, limit, il, hev, false) + filterInner(U, up + 4, 1, uvs, 8, limit, il, hev) + filterInner(V, up + 4, 1, uvs, 8, limit, il, hev) end if mby > 0 then - filterLoop(Y, yp, ys, 1, 16, limit + 4, il, hev, true) - filterLoop(U, up, uvs, 1, 8, limit + 4, il, hev, true) - filterLoop(V, up, uvs, 1, 8, limit + 4, il, hev, true) + filterEdge(Y, yp, ys, 1, 16, limit + 4, il, hev) + filterEdge(U, up, uvs, 1, 8, limit + 4, il, hev) + filterEdge(V, up, uvs, 1, 8, limit + 4, il, hev) end if inner then for k = 1, 3 do - filterLoop(Y, yp + 4 * k * ys, ys, 1, 16, limit, il, hev, false) + filterInner(Y, yp + 4 * k * ys, ys, 1, 16, limit, il, hev) end - filterLoop(U, up + 4 * uvs, uvs, 1, 8, limit, il, hev, false) - filterLoop(V, up + 4 * uvs, uvs, 1, 8, limit, il, hev, false) + filterInner(U, up + 4 * uvs, uvs, 1, 8, limit, il, hev) + filterInner(V, up + 4 * uvs, uvs, 1, 8, limit, il, hev) end end end @@ -1336,18 +1954,34 @@ function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, ma end end - -- crop to the frame size - local cw, chh = (width + 1) // 2, (height + 1) // 2 - local oy = bcreate(width * height) - for j = 0, height - 1 do - bcopy(oy, j * width, Y, j * ys, width) + -- the references (libvpx swap_frame_buffers; copies read the references of the previous frame, as ffmpeg does) + if key then + st.last, st.golden, st.alt = cur, cur, cur + st.hasKey = true + else + local oldLast, oldGolden, oldAlt = st.last, st.golden, st.alt + if refreshGolden then + st.golden = cur + elseif copyToGolden == 1 then + st.golden = oldLast + elseif copyToGolden == 2 then + st.golden = oldAlt + end + if refreshAlt then + st.alt = cur + elseif copyToAlt == 1 then + st.alt = oldLast + elseif copyToAlt == 2 then + st.alt = oldGolden + end + if refreshLast then + st.last = cur + end end - local ou, ov = bcreate(cw * chh), bcreate(cw * chh) - for j = 0, chh - 1 do - bcopy(ou, j * cw, U, j * uvs, cw) - bcopy(ov, j * cw, V, j * uvs, cw) + if saved then + st.proba, st.ymodeProb, st.uvmodeProb, st.mvProb = saved[1], saved[2], saved[3], saved[4] end - return { width = width, height = height, y = oy, u = ou, v = ov, header = hdr }, nil + return { width = width, height = height, ref = cur, header = hdr }, nil end return Decode diff --git a/src/Formats/codecs/Vp8/Predict.luau b/src/Formats/codecs/Vp8/Predict.luau new file mode 100644 index 0000000..536ddea --- /dev/null +++ b/src/Formats/codecs/Vp8/Predict.luau @@ -0,0 +1,274 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Vp8/Predict: VP8 inter prediction (RFC 6386 section 18): the six-tap sub-pixel filters (version 0), the +-- bilinear ones (versions 1-3; version 3 also rounds chroma vectors to full pixels), chroma vectors derived from the +-- luma ones, split macroblocks, and the reference frame borders. After libvpx 1.17 vp8/common/reconinter.c and +-- filter.c (BSD-3-Clause, licenses/libvpx-LICENSE.txt). Out-of-frame motion reads the reference as if its edge pixels +-- extended forever, which is exactly what libvpx computes with its 32 pixel border plus its motion vector clamping (the +-- clamps only kick in once every tap is in the border). The planes keep a BORDER pixel border filled by extend(); a +-- block whose taps leave it is first copied with clamped coordinates. Never throws. +local Tables = require("@formats/codecs/Vp8/Tables") + +local readu8, writeu8, bcopy, bcreate, bfill = buffer.readu8, buffer.writeu8, buffer.copy, buffer.create, buffer.fill +local readu32, writeu32 = buffer.readu32, buffer.writeu32 +local rshift, band = bit32.rshift, bit32.band +local SIX, BIL = Tables.SIXTAP, Tables.BILINEAR + +local Predict = {} + +local BORDER = 32 +Predict.BORDER = BORDER + +-- the work buffer stride (codecs/Vp8/Decode: BPS) +local BPS = 32 + +local emu = bcreate(32 * 32) -- a block with its taps, edges replicated +local tmp = bcreate(32 * 32) -- the first (horizontal) pass of a two-dimensional filter + +-- the six-tap filter along rows: dst[i] = clamp((sum of src[i - 2 .. i + 3] * taps + 64) >> 7). Each output reads +-- its six pixels (a sliding window of locals is no faster in Luau and stops LuaJIT's register allocator). +local function sixH(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number) + local k = f * 6 + local t0, t1, t2, t3, t4, t5 = SIX[k + 1], SIX[k + 2], SIX[k + 3], SIX[k + 4], SIX[k + 5], SIX[k + 6] + for _ = 1, h do + for i = so - 2, so + w - 3 do + local v = readu8(src, i) * t0 + readu8(src, i + 1) * t1 + readu8(src, i + 2) * t2 + readu8(src, i + 3) * t3 + + readu8(src, i + 4) * t4 + readu8(src, i + 5) * t5 + 64 + writeu8(dst, d + i - so + 2, if v < 0 then 0 elseif v >= 32768 then 255 else rshift(v, 7)) + end + so += ss + d += ds + end +end + +-- the six-tap filter along columns +local function sixV(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number) + local k = f * 6 + local t0, t1, t2, t3, t4, t5 = SIX[k + 1], SIX[k + 2], SIX[k + 3], SIX[k + 4], SIX[k + 5], SIX[k + 6] + local s1, s2, s3 = ss, 2 * ss, 3 * ss + for _ = 1, h do + local p = so - s2 + for i = 0, w - 1 do + local q = p + i + local v = readu8(src, q) * t0 + readu8(src, q + s1) * t1 + readu8(src, q + s2) * t2 + readu8(src, q + s3) * t3 + + readu8(src, q + s2 + s2) * t4 + readu8(src, q + s2 + s3) * t5 + 64 + writeu8(dst, d + i, if v < 0 then 0 elseif v >= 32768 then 255 else rshift(v, 7)) + end + so += ss + d += ds + end +end + +-- the bilinear filters: dst[i] = (src[i] * t0 + src[i + 1] * t1 + 64) >> 7 +local function bilH(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number) + local t0, t1 = BIL[f * 2 + 1], BIL[f * 2 + 2] + for _ = 1, h do + for i = 0, w - 1 do + writeu8(dst, d + i, rshift(readu8(src, so + i) * t0 + readu8(src, so + i + 1) * t1 + 64, 7)) + end + so += ss + d += ds + end +end + +local function bilV(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number) + local t0, t1 = BIL[f * 2 + 1], BIL[f * 2 + 2] + for _ = 1, h do + for i = 0, w - 1 do + writeu8(dst, d + i, rshift(readu8(src, so + i) * t0 + readu8(src, so + ss + i) * t1 + 64, 7)) + end + so += ss + d += ds + end +end + +-- block(src, stride, base, wmax, hmax, x, y, mvx, mvy, w, h, dst, d, bil): predicts the w x h block at plane pixel +-- (x, y) moved by (mvx, mvy) eighth pixels into dst at d (stride BPS). base: the offset of plane pixel (0, 0); wmax, +-- hmax: the last pixel column / row of the (macroblock aligned) plane. +local function block(src: buffer, stride: number, base: number, wmax: number, hmax: number, x: number, y: number, mvx: number, mvy: number, w: number, h: number, dst: buffer, d: number, bil: boolean) + local fx, fy = band(mvx, 7), band(mvy, 7) + local px, py = x + (mvx - fx) // 8, y + (mvy - fy) // 8 + local sb, so, ss = src, 0, stride + if px >= 2 - BORDER and py >= 2 - BORDER and px + w + 3 <= wmax + 1 + BORDER and py + h + 3 <= hmax + 1 + BORDER then + so = base + py * stride + px + else + for r = 0, h + 4 do + local sy = py - 2 + r + if sy < 0 then + sy = 0 + elseif sy > hmax then + sy = hmax + end + local row = base + sy * stride + local o = r * 32 + for c = 0, w + 4 do + local sx = px - 2 + c + if sx < 0 then + sx = 0 + elseif sx > wmax then + sx = wmax + end + writeu8(emu, o + c, readu8(src, row + sx)) + end + end + sb, so, ss = emu, 66, 32 + end + if fx == 0 then + if fy == 0 then + for _ = 1, h do + for i = 0, w - 4, 4 do + writeu32(dst, d + i, readu32(sb, so + i)) + end + so += ss + d += BPS + end + elseif bil then + bilV(sb, so, ss, dst, d, BPS, w, h, fy) + else + sixV(sb, so, ss, dst, d, BPS, w, h, fy) + end + elseif fy == 0 then + if bil then + bilH(sb, so, ss, dst, d, BPS, w, h, fx) + else + sixH(sb, so, ss, dst, d, BPS, w, h, fx) + end + elseif bil then + bilH(sb, so, ss, tmp, 0, 32, w, h + 1, fx) + bilV(tmp, 0, 32, dst, d, BPS, w, h, fy) + else + sixH(sb, so - 2 * ss, ss, tmp, 0, 32, w, h + 5, fx) + sixV(tmp, 64, 32, dst, d, BPS, w, h, fy) + end +end + +local function chroma16(v: number): number + -- the chroma vector of a whole macroblock: half the luma one, rounded away from zero + if v < 0 then + return -((1 - v) // 2) + end + return (v + 1) // 2 +end + +local function chroma4(s: number): number + -- the chroma vector of a 2x2 group of luma blocks: the sum of their 4 vectors / 8, rounded half away from zero + if s < 0 then + return -((4 - s) // 8) + end + return (s + 4) // 8 +end + +export type Planes = { + Y: buffer, + U: buffer, + V: buffer, + ys: number, -- luma stride + uvs: number, -- chroma stride + yb: number, -- offset of luma pixel (0, 0) + uvb: number, + mbw: number, + mbh: number, +} + +-- mb(ref, mbx, mby, mvr, mvc, split, subR, subC, sb, dst, yo, uo, vo, bil, full): the prediction of one inter +-- macroblock into the work buffer (luma at yo, chroma at uo / vo). Not split: one vector (mvr, mvc) in eighth pixels; +-- split: the 16 block vectors subR / subC[sb + 1 .. sb + 16] (part < 3: the four 8x8 quarters share them). +function Predict.mb(ref: Planes, mbx: number, mby: number, mvr: number, mvc: number, part: number, subR: { number }, subC: { number }, sb: number, dst: buffer, yo: number, uo: number, vo: number, bil: boolean, full: boolean) + local Y, U, V, ys, uvs, yb, uvb = ref.Y, ref.U, ref.V, ref.ys, ref.uvs, ref.yb, ref.uvb + local wl, hl = ref.mbw * 16 - 1, ref.mbh * 16 - 1 + local wc, hc = ref.mbw * 8 - 1, ref.mbh * 8 - 1 + local x, y = mbx * 16, mby * 16 + local cx, cy = mbx * 8, mby * 8 + if part < 0 then + block(Y, ys, yb, wl, hl, x, y, mvc, mvr, 16, 16, dst, yo, bil) + local cr, cc = chroma16(mvr), chroma16(mvc) + if full then + cr -= band(cr, 7) + cc -= band(cc, 7) + end + block(U, uvs, uvb, wc, hc, cx, cy, cc, cr, 8, 8, dst, uo, bil) + block(V, uvs, uvb, wc, hc, cx, cy, cc, cr, 8, 8, dst, vo, bil) + return + end + if part < 3 then + for q = 0, 3 do + local bx, by = (q % 2) * 8, (q // 2) * 8 + local k = sb + by + bx // 4 + 1 + block(Y, ys, yb, wl, hl, x + bx, y + by, subC[k], subR[k], 8, 8, dst, yo + by * BPS + bx, bil) + end + else + for b = 0, 15, 2 do + local k = sb + b + 1 + local bx, by = (b % 4) * 4, (b // 4) * 4 + local r0, c0 = subR[k], subC[k] + if r0 == subR[k + 1] and c0 == subC[k + 1] then + block(Y, ys, yb, wl, hl, x + bx, y + by, c0, r0, 8, 4, dst, yo + by * BPS + bx, bil) + else + block(Y, ys, yb, wl, hl, x + bx, y + by, c0, r0, 4, 4, dst, yo + by * BPS + bx, bil) + block(Y, ys, yb, wl, hl, x + bx + 4, y + by, subC[k + 1], subR[k + 1], 4, 4, dst, yo + by * BPS + bx + 4, bil) + end + end + end + for i = 0, 1 do + local rr, rc = 0, 0 + for j = 0, 1 do + local k = sb + i * 8 + j * 2 + 1 + local cr = chroma4(subR[k] + subR[k + 1] + subR[k + 4] + subR[k + 5]) + local cc = chroma4(subC[k] + subC[k + 1] + subC[k + 4] + subC[k + 5]) + if full then + cr -= band(cr, 7) + cc -= band(cc, 7) + end + if j == 0 then + rr, rc = cr, cc + elseif cr == rr and cc == rc then + -- both 4x4 chroma blocks of the row share one vector: one 8x4 block + block(U, uvs, uvb, wc, hc, cx, cy + i * 4, cc, cr, 8, 4, dst, uo + i * 4 * BPS, bil) + block(V, uvs, uvb, wc, hc, cx, cy + i * 4, cc, cr, 8, 4, dst, vo + i * 4 * BPS, bil) + else + block(U, uvs, uvb, wc, hc, cx, cy + i * 4, rc, rr, 4, 4, dst, uo + i * 4 * BPS, bil) + block(V, uvs, uvb, wc, hc, cx, cy + i * 4, rc, rr, 4, 4, dst, vo + i * 4 * BPS, bil) + block(U, uvs, uvb, wc, hc, cx + 4, cy + i * 4, cc, cr, 4, 4, dst, uo + i * 4 * BPS + 4, bil) + block(V, uvs, uvb, wc, hc, cx + 4, cy + i * 4, cc, cr, 4, 4, dst, vo + i * 4 * BPS + 4, bil) + end + end + end +end + +-- row(refs, mby, mbw, ref, part, miMvR, miMvC, miSubR, miSubC, mi0, pred, chunk, yo, uo, vo, bil, full): predicts the +-- inter macroblocks of a row (ref[mbx + 1] > 0: refs[ref]) into pred, macroblock mbx at mbx * chunk + yo / uo / vo; +-- mi0 + mbx + 1: the mode info index of macroblock mbx. A loop of its own (LuaJIT traces it apart from the decoder). +function Predict.row(refs: { Planes }, mby: number, mbw: number, ref: { number }, part: { number }, miMvR: { number }, miMvC: { number }, miSubR: { number }, miSubC: { number }, mi0: number, pred: buffer, chunk: number, yo: number, uo: number, vo: number, bil: boolean, full: boolean) + for mbx = 0, mbw - 1 do + local rf = ref[mbx + 1] + if rf > 0 then + local mi = mi0 + mbx + 1 + local o = mbx * chunk + Predict.mb(refs[rf], mbx, mby, miMvR[mi], miMvC[mi], part[mbx + 1], miSubR, miSubC, (mi - 1) * 16, pred, o + yo, o + uo, o + vo, bil, full) + end + end +end + +-- extend(P, stride, base, w, h): fills the BORDER pixels around a w x h plane with its edge pixels +local function extend(P: buffer, stride: number, base: number, w: number, h: number) + for r = 0, h - 1 do + local o = base + r * stride + bfill(P, o - BORDER, readu8(P, o), BORDER) + bfill(P, o + w, readu8(P, o + w - 1), BORDER) + end + local top = base - BORDER + local bottom = base + (h - 1) * stride - BORDER + for r = 1, BORDER do + bcopy(P, top - r * stride, P, top, stride) + bcopy(P, bottom + r * stride, P, bottom, stride) + end +end + +function Predict.extend(ref: Planes) + extend(ref.Y, ref.ys, ref.yb, ref.mbw * 16, ref.mbh * 16) + extend(ref.U, ref.uvs, ref.uvb, ref.mbw * 8, ref.mbh * 8) + extend(ref.V, ref.uvs, ref.uvb, ref.mbw * 8, ref.mbh * 8) +end + +return Predict diff --git a/src/Formats/codecs/Vp8/Tables.luau b/src/Formats/codecs/Vp8/Tables.luau index e8a9320..21dc1cf 100644 --- a/src/Formats/codecs/Vp8/Tables.luau +++ b/src/Formats/codecs/Vp8/Tables.luau @@ -1,6 +1,9 @@ --!strict -- codecs/Vp8/Tables: the constant VP8 tables of RFC 6386 (sections 13.5, 13.4, 11.5, 14.1), copied from libwebp 1.6 --- src/dec/tree_dec.c and src/dec/quant_dec.c (BSD-3-Clause, licenses/libwebp-LICENSE.txt). Flat 1-based arrays. +-- src/dec/tree_dec.c and src/dec/quant_dec.c (BSD-3-Clause, licenses/libwebp-LICENSE.txt); the inter frame tables +-- (sections 16-18: mode / motion vector probabilities, mode contexts, split partitions, sub-pixel filters) from +-- libvpx 1.17 vp8/common (entropymode.c, vp8_entropymodedata.h, entropymv.c, modecont.c, decodemv.c, filter.c; +-- BSD-3-Clause, licenses/libvpx-LICENSE.txt). Flat 1-based arrays. local Tables = {} -- default token probabilities [type 4][band 8][ctx 3][proba 11]: index ((t * 8 + b) * 3 + c) * 11 + p + 1 @@ -177,4 +180,70 @@ Tables.CAT4 = { 176, 155, 140, 135 } Tables.CAT5 = { 180, 157, 141, 134, 130 } Tables.CAT6 = { 254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129 } +-- inter frames: default intra mode probabilities (16x16 / chroma, kept in the frame context) and the fixed 4x4 ones +Tables.YMODE_PROB = { 112, 86, 140, 37 } +Tables.UVMODE_PROB = { 162, 101, 204 } +Tables.BMODE_PROB = { 120, 90, 79, 133, 87, 85, 80, 111, 151 } + +-- motion vector probabilities, row then column (19 each): is short, sign, short tree (7), long bits (10) +Tables.MV_DEFAULT = { + 162, 128, 225, 146, 172, 147, 214, 39, 156, 128, 129, 132, 75, 145, 178, 206, 239, 254, 254, + 164, 128, 204, 170, 119, 235, 140, 230, 228, 128, 130, 130, 74, 148, 180, 203, 236, 254, 254, +} +Tables.MV_UPDATE = { + 237, 246, 253, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 250, 250, 252, 254, 254, + 231, 243, 245, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 251, 251, 254, 254, 254, +} + +-- mode contexts [count 0..5][tree node 0..3]: index count * 4 + node + 1 +Tables.MODE_CONTEXTS = { + 7, 1, 1, 143, + 14, 18, 14, 107, + 135, 64, 57, 68, + 60, 56, 128, 65, + 159, 134, 128, 34, + 234, 188, 128, 28, +} + +-- sub-block motion vector reference probabilities [(above zero << 2) | (left zero << 1) | (left == above)][3] +Tables.SUB_MV_REF_PROB = { + 147, 136, 18, + 223, 1, 34, + 106, 145, 1, + 208, 1, 1, + 179, 121, 1, + 223, 1, 34, + 179, 121, 1, + 208, 1, 1, +} + +-- split partitions (16x8, 8x16, 8x8, 4x4): the first block of each partition [s * 16 + j + 1], the blocks of each +-- partition in order [s * 16 + j * count + i + 1], and the number of blocks per partition +Tables.SPLIT_OFFSET = { + 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 2, 8, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, +} +Tables.SPLIT_FILL = { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 0, 1, 4, 5, 8, 9, 12, 13, 2, 3, 6, 7, 10, 11, 14, 15, + 0, 1, 4, 5, 2, 3, 6, 7, 8, 9, 12, 13, 10, 11, 14, 15, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, +} +Tables.SPLIT_COUNT = { 8, 8, 4, 1 } + +-- the six-tap sub-pixel filters [fraction 0..7][tap 0..5] and the bilinear ones [fraction][2] (versions 1-3) +Tables.SIXTAP = { + 0, 0, 128, 0, 0, 0, + 0, -6, 123, 12, -1, 0, + 2, -11, 108, 36, -8, 1, + 0, -9, 93, 50, -6, 0, + 3, -16, 77, 77, -16, 3, + 0, -6, 50, 93, -9, 0, + 1, -8, 36, 108, -11, 2, + 0, -1, 12, 123, -6, 0, +} +Tables.BILINEAR = { 128, 0, 112, 16, 96, 32, 80, 48, 64, 64, 48, 80, 32, 96, 16, 112 } + return Tables diff --git a/src/Formats/codecs/Vp8/init.luau b/src/Formats/codecs/Vp8/init.luau index 05f56f1..d9a6f2a 100644 --- a/src/Formats/codecs/Vp8/init.luau +++ b/src/Formats/codecs/Vp8/init.luau @@ -1,16 +1,23 @@ --!strict -- codecs/Vp8: the VP8 video codec (RFC 6386), decode only. A codec (layer 1): image/webp uses it for lossy frames, the --- WebM / Matroska and IVF video tracks can use it too. A port of libwebp 1.6 (BSD-3-Clause, +-- WebM / Matroska and IVF video tracks use its decoder object. Key frames are a port of libwebp 1.6 (BSD-3-Clause, -- licenses/libwebp-LICENSE.txt), bit-exact with libwebp: the yuv420p planes equal `dwebp -yuv`, and toRgba equals --- `dwebp -pam` (fancy upsampling) or `dwebp -nofancy -pam`. --- Supports: key frames (intra 16x16 / 4x4 / chroma prediction, segments, both loop filters, token partitions, --- probability updates, skip). Not supported yet: inter frames (decodeFrame returns UNSUPPORTED; the decoder object --- keeps the cross-frame state so they can be added), the horizontal / vertical scale bits (ignored, as libwebp does). +-- `dwebp -pam` (fancy upsampling) or `dwebp -nofancy -pam`. Inter frames follow libvpx 1.17 (BSD-3-Clause, +-- licenses/libvpx-LICENSE.txt), bit-exact with libvpx / ffmpeg on the official test vectors and libvpx streams. +-- Supports: key and inter frames of every version / profile (0: six-tap filters, normal loop filter; 1-2: bilinear; +-- 3: bilinear with full pixel chroma; the loop filter type is the header's), last / golden / altref references with +-- sign bias, hidden (altref) frames, token partitions, segments, loop filter deltas, probability context save / +-- restore. Not supported: the horizontal / vertical scale bits (ignored, as libwebp and ffmpeg do), error +-- concealment (a damaged frame returns an Err). +-- Speed (one Zen 5 core): 640x480 inter frames ~190 fps under luau --codegen, ~220 fps under LuaJIT with the trace +-- limits the host module sets (maxtrace=8000; with LuaJIT's default 1000 traces the decoder thrashes: ~70 fps). -- -- local Vp8 = require("@formats/codecs/Vp8") --- local frame, err = Vp8.decodeFrame(buf, off, len) -- a yuv420p Types.Image (+ frame.meta.source.vp8 header) +-- local frame, err = Vp8.decodeFrame(buf, off, len) -- one key frame: a yuv420p Types.Image -- local rgba = Vp8.toRgba(frame) -- rgba8 Image (libwebp's fancy upsampling) --- local dec = Vp8.newDecoder(); dec:decodeFrame(...) -- a stream of frames (WebM) +-- local dec = Vp8.newDecoder() -- a stream (WebM, IVF): key and inter frames +-- local img, err = dec:decodeFrame(buf, off, len) -- img.meta.source.show == false: a hidden frame +-- dec:reset() -- after a seek: the next frame must be a key frame -- -- Never throws: bad data returns nil, Err (core/Err codes TRUNCATED / CORRUPT / UNSUPPORTED / LIMIT / ARG). local Err = require("@formats/core/Err") @@ -67,7 +74,9 @@ function Vp8.newDecoder(): Decoder return setmetatable({ state = Decode.new() }, DecoderMeta) end --- decoder:decodeFrame(buf, off?, len?, opts?) -> a yuv420p Image | nil, Err +-- decoder:decodeFrame(buf, off?, len?, opts?) -> a yuv420p Image (a fresh buffer) | nil, Err. Key and inter frames; +-- meta.source = { format = "vp8", keyFrame, show (false: a hidden frame, decoded as a reference but not displayed), +-- profile, width, height }. An inter frame before the first key frame (or after reset) returns CORRUPT. function DecoderMeta.decodeFrame(self: Decoder, buf: buffer, off: number?, len: number?, opts: Options?): (Types.Image?, Err.Err?) if type(buf) ~= "buffer" then return nil, Err.new(Err.ARG, "decodeFrame: expected a buffer") @@ -79,14 +88,18 @@ function DecoderMeta.decodeFrame(self: Decoder, buf: buffer, off: number?, len: end local img = Types.Image.new(f.width, f.height, "yuv420p") local ny = f.width * f.height - local nc = buffer.len(f.u) - buffer.copy(img.pixels, 0, f.y, 0, ny) - buffer.copy(img.pixels, ny, f.u, 0, nc) - buffer.copy(img.pixels, ny + nc, f.v, 0, nc) - img.meta.source = { format = "vp8", keyFrame = f.header.keyFrame, profile = f.header.profile } + local nc = ((f.width + 1) // 2) * ((f.height + 1) // 2) + Decode.cropTo(f, img.pixels, 0, img.pixels, ny, img.pixels, ny + nc) + local h = f.header + img.meta.source = { format = "vp8", keyFrame = h.keyFrame, show = h.show, profile = h.profile, width = f.width, height = f.height } return img, nil end +-- decoder:reset(): drops the reference frames (after a seek); the next frame must be a key frame +function DecoderMeta.reset(self: Decoder) + Decode.reset(self.state) +end + -- decodeFrame(buf, off?, len?, opts?) -> a yuv420p Image | nil, Err (one key frame) function Vp8.decodeFrame(buf: buffer, off: number?, len: number?, opts: Options?): (Types.Image?, Err.Err?) return Vp8.newDecoder():decodeFrame(buf, off, len, opts) @@ -102,7 +115,10 @@ function Vp8.decodePlanes(buf: buffer, off: number?, len: number?, opts: Options if not f then return nil, fail(err, o) end - return f.y, f.u, f.v, f.width, f.height + local nc = ((f.width + 1) // 2) * ((f.height + 1) // 2) + local y, u, v = buffer.create(f.width * f.height), buffer.create(nc), buffer.create(nc) + Decode.cropTo(f, y, 0, u, 0, v, 0) + return y, u, v, f.width, f.height end -- planes(img) -> y, u, v offsets in img.pixels and the chroma width / height diff --git a/src/Formats/codecs/Yuv.luau b/src/Formats/codecs/Yuv.luau new file mode 100644 index 0000000..f6926e4 --- /dev/null +++ b/src/Formats/codecs/Yuv.luau @@ -0,0 +1,225 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Yuv: planar 4:2:0 Y'CbCr <-> rgba8 for the video codecs and writers (native; never throws). BT.601 or +-- BT.709 matrices, limited ("tv", 16..235 / 16..240: VP8, MPEG-1, H.264) or full ("pc", 0..255: MJPEG / JPEG) range. +-- yuv -> rgb uses nearest chroma and 16-bit fixed point with swscale's default (non-accurate) coefficients, so the +-- result is within about one level of `ffmpeg -pix_fmt rgba`; rgb -> yuv averages each 2x2 block for the chroma +-- (ffmpeg's default rgb -> yuv420p chroma siting is close to this). +-- +-- Yuv.toRgba(planes, w, h, uo, vo, cw, range?, matrix?, out?) -> rgba8 buffer (alpha 255) +-- Yuv.fromRgba(rgba, w, h, range?, matrix?, out?) -> yuv420p buffer (Y, then U, then V; ceil(w/2) x ceil(h/2)) +-- Yuv.imageToRgba(img) / Yuv.imageFromRgba(img, range?, matrix?) -> Types.Image +local Types = require("@formats/Types") + +local readu8, writeu8, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu32 +local bcreate = buffer.create +local floor = math.floor + +local Yuv = {} + +-- coefficients (x 65536): r = y' + crv * v; g = y' - cgu * u - cgv * v; b = y' + cbu * u +-- limited: y' = (y - 16) * 255 / 219, chroma scaled by 255 / 224 +local MATRIX = { + bt601 = { kr = 0.299, kb = 0.114 }, + bt709 = { kr = 0.2126, kb = 0.0722 }, +} + +type Coeffs = { ys: number, yo: number, crv: number, cgu: number, cgv: number, cbu: number, cs: number } + +local cache: { [string]: Coeffs } = {} +local function coeffs(range: string?, matrix: string?): Coeffs + local key = (range or "limited") .. (matrix or "bt601") + local c = cache[key] + if c then + return c + end + local m = MATRIX[matrix or "bt601"] or MATRIX.bt601 + local kr, kb = m.kr, m.kb + local kg = 1 - kr - kb + local full = range == "full" + local ys = if full then 1 else 255 / 219 + local cs = if full then 1 else 255 / 224 + c = { + ys = floor(ys * 65536 + 0.5), + yo = if full then 0 else 16, + crv = floor(2 * (1 - kr) * cs * 65536 + 0.5), + cbu = floor(2 * (1 - kb) * cs * 65536 + 0.5), + cgu = floor(2 * (1 - kb) * kb / kg * cs * 65536 + 0.5), + cgv = floor(2 * (1 - kr) * kr / kg * cs * 65536 + 0.5), + cs = cs, + } + cache[key] = c + return c +end + +-- CLIP[v + 1024] = clamp(v, 0, 255) for v in -1024..1279 +local CLIP = bcreate(2304) +for i = 0, 2303 do + writeu8(CLIP, i, math.clamp(i - 1024, 0, 255)) +end + +-- toRgba(src, w, h, uo, vo, cw, range?, matrix?, out?) -> rgba8 (w * h * 4) from planes in one buffer: Y at 0 with +-- stride w, U at uo and V at vo with stride cw (ceil(w/2) rows of ceil(h/2)) +function Yuv.toRgba(src: buffer, w: number, h: number, uo: number, vo: number, cw: number, range: string?, matrix: string?, out: buffer?): buffer + local dst = out or bcreate(w * h * 4) + local c = coeffs(range, matrix) + local ys, yo, crv, cgu, cgv, cbu = c.ys, c.yo, c.crv, c.cgu, c.cgv, c.cbu + local ch = (h + 1) // 2 + if buffer.len(src) < vo + cw * ch or buffer.len(dst) < w * h * 4 or uo + cw * ch > buffer.len(src) then + return dst + end + for y = 0, h - 1 do + local yrow = y * w + local crow = (y // 2) * cw + local o = yrow * 4 + for x = 0, w - 1, 2 do + local ci = crow + (x // 2) + local u = readu8(src, uo + ci) - 128 + local v = readu8(src, vo + ci) - 128 + local rv = (crv * v + 32768) // 65536 + local gv = (cgu * u + cgv * v + 32768) // 65536 + local bu = (cbu * u + 32768) // 65536 + local yy = (ys * (readu8(src, yrow + x) - yo) + 32768) // 65536 + 1024 + writeu32(dst, o, readu8(CLIP, yy + rv) + readu8(CLIP, yy - gv) * 256 + readu8(CLIP, yy + bu) * 65536 + 0xff000000) + if x + 1 < w then + yy = (ys * (readu8(src, yrow + x + 1) - yo) + 32768) // 65536 + 1024 + writeu32(dst, o + 4, readu8(CLIP, yy + rv) + readu8(CLIP, yy - gv) * 256 + readu8(CLIP, yy + bu) * 65536 + 0xff000000) + end + o += 8 + end + end + return dst +end + +-- fromRgba(rgba, w, h, range?, matrix?, out?) -> yuv420p +function Yuv.fromRgba(src: buffer, w: number, h: number, range: string?, matrix: string?, out: buffer?): buffer + local cw, ch = (w + 1) // 2, (h + 1) // 2 + local uo, vo = w * h, w * h + cw * ch + local dst = out or bcreate(w * h + 2 * cw * ch) + if buffer.len(src) < w * h * 4 or buffer.len(dst) < w * h + 2 * cw * ch then + return dst + end + local m = MATRIX[matrix or "bt601"] or MATRIX.bt601 + local kr, kb = m.kr, m.kb + local kg = 1 - kr - kb + local full = range == "full" + local ysc = if full then 1 else 219 / 255 + local csc = if full then 1 else 224 / 255 + local yof = if full then 0.5 else 16.5 + -- fixed point x 65536 + local yr, yg, yb = floor(kr * ysc * 65536 + 0.5), floor(kg * ysc * 65536 + 0.5), floor(kb * ysc * 65536 + 0.5) + local yoff = floor(yof * 65536) + local ur = floor(-kr / (2 * (1 - kb)) * csc * 65536 + 0.5) + local ug = floor(-kg / (2 * (1 - kb)) * csc * 65536 + 0.5) + local ub = floor(0.5 * csc * 65536 + 0.5) + local vr = ub + local vg = floor(-kg / (2 * (1 - kr)) * csc * 65536 + 0.5) + local vb = floor(-kb / (2 * (1 - kr)) * csc * 65536 + 0.5) + local coff4 = floor(128.5 * 65536) * 4 + for i = 0, w * h - 1 do + local o = i * 4 + local r, g, b = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2) + writeu8(dst, i, readu8(CLIP, (yr * r + yg * g + yb * b + yoff) // 65536 + 1024)) + end + for cy = 0, ch - 1 do + local y0 = cy * 2 + local y1 = if y0 + 1 < h then y0 + 1 else y0 + for cx = 0, cw - 1 do + local x0 = cx * 2 + local x1 = if x0 + 1 < w then x0 + 1 else x0 + local a, b2, c2, d = (y0 * w + x0) * 4, (y0 * w + x1) * 4, (y1 * w + x0) * 4, (y1 * w + x1) * 4 + local r = readu8(src, a) + readu8(src, b2) + readu8(src, c2) + readu8(src, d) + local g = readu8(src, a + 1) + readu8(src, b2 + 1) + readu8(src, c2 + 1) + readu8(src, d + 1) + local b = readu8(src, a + 2) + readu8(src, b2 + 2) + readu8(src, c2 + 2) + readu8(src, d + 2) + local i = cy * cw + cx + writeu8(dst, uo + i, readu8(CLIP, (ur * r + ug * g + ub * b + coff4) // 262144 + 1024)) + writeu8(dst, vo + i, readu8(CLIP, (vr * r + vg * g + vb * b + coff4) // 262144 + 1024)) + end + end + return dst +end + +-- the range / matrix an Image's meta records (meta.yuv = { range, matrix }); limited BT.601 when absent +local function info(img: Types.Image): (string, string) + local m = img.meta + local y = m and m.yuv + if type(y) == "table" then + return y.range or "limited", y.matrix or "bt601" + end + local src = m and m.source + if type(src) == "table" and src.range == "full" then + return "full", "bt601" + end + return "limited", "bt601" +end +Yuv.info = info + +-- planes(w, h) -> uo, vo, cw, ch of a yuv420p buffer +function Yuv.planes(w: number, h: number): (number, number, number, number) + local cw, ch = (w + 1) // 2, (h + 1) // 2 + return w * h, w * h + cw * ch, cw, ch +end + +-- FULL_Y / FULL_C: limited -> full range sample maps +local FULL_Y = bcreate(256) +local FULL_C = bcreate(256) +for v = 0, 255 do + writeu8(FULL_Y, v, math.clamp(floor((v - 16) * 255 / 219 + 0.5), 0, 255)) + writeu8(FULL_C, v, math.clamp(floor((v - 128) * 255 / 224 + 128.5), 0, 255)) +end + +-- toFullRange(img) -> a yuv420p Image in full range (a limited-range one remapped; a full-range one returned) +function Yuv.toFullRange(img: Types.Image): Types.Image + if img.format ~= "yuv420p" or info(img) == "full" then + return img + end + local w, h = img.width, img.height + local out = Types.Image.new(w, h, "yuv420p") + local src, dst = img.pixels, out.pixels + local ny = w * h + local n = math.min(buffer.len(src), buffer.len(dst)) + for i = 0, math.min(ny, n) - 1 do + writeu8(dst, i, readu8(FULL_Y, readu8(src, i))) + end + for i = ny, n - 1 do + writeu8(dst, i, readu8(FULL_C, readu8(src, i))) + end + out.meta.yuv = { range = "full", matrix = select(2, info(img)) } + out.meta.source = img.meta.source + return out +end + +-- imageToRgba(img) -> an rgba8 Image (yuv420p converted; rgba8 returned as is; nil for other formats) +function Yuv.imageToRgba(img: Types.Image): Types.Image? + if img.format == "rgba8" then + return img + end + if img.format ~= "yuv420p" then + return nil + end + local w, h = img.width, img.height + local uo, vo, cw = Yuv.planes(w, h) + local range, matrix = info(img) + local out = Types.Image.new(w, h, "rgba8") + Yuv.toRgba(img.pixels, w, h, uo, vo, cw, range, matrix, out.pixels) + out.meta.source = img.meta.source + return out +end + +-- imageFromRgba(img, range?, matrix?) -> a yuv420p Image (meta.yuv records the range / matrix) +function Yuv.imageFromRgba(img: Types.Image, range: string?, matrix: string?): Types.Image? + if img.format == "yuv420p" then + return img + end + if img.format ~= "rgba8" then + return nil + end + local out = Types.Image.new(img.width, img.height, "yuv420p") + Yuv.fromRgba(img.pixels, img.width, img.height, range, matrix, out.pixels) + out.meta.yuv = { range = range or "limited", matrix = matrix or "bt601" } + out.meta.source = img.meta.source + return out +end + +return Yuv diff --git a/src/Formats/containers/AudioWrap.luau b/src/Formats/containers/AudioWrap.luau new file mode 100644 index 0000000..a2fa1d4 --- /dev/null +++ b/src/Formats/containers/AudioWrap.luau @@ -0,0 +1,463 @@ +--!strict +-- containers/AudioWrap: an audio track of a video container (a Types.Demuxer track and its packets) as a standalone +-- stream that an audio format reads, so the api can open it with the audio formats (a format never requires another +-- format). New in formats-luau. +-- PCM (pcm_u8 / s16 / s24 / s32 le and be, f32 / f64, alaw, mulaw) -> WAV (big-endian samples byte-swapped); +-- an AVI audio track with its WAVEFORMATEX (track.waveFormat: IMA / MS ADPCM, ...) -> WAV with that fmt chunk; +-- mp3 / mp2 / mp1 -> the frames back to back (format "mp3"); +-- 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. +-- +-- local buf, format, err = AudioWrap.wrap(demuxer, track) -- then F.open(buf, { format = format }) +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Mux = require("@formats/containers/Ogg/Mux") + +local AudioWrap = {} + +local function allPackets(dmx: any, track: Types.Track): { Types.Packet } + local out = {} + local n = if dmx.count then dmx:count(track.id) else 0 + if n > 0 and dmx.get then + for k = 1, n do + local p = dmx:get(track.id, k) + if p then + table.insert(out, p) + end + end + end + return out +end + +local function concat(packets: { Types.Packet }, prefix: buffer?): buffer + local total = if prefix then buffer.len(prefix) else 0 + for _, p in packets do + total += buffer.len(p.data) + end + local out = buffer.create(total) + local o = 0 + if prefix then + buffer.copy(out, 0, prefix) + o = buffer.len(prefix) + end + for _, p in packets do + buffer.copy(out, o, p.data) + o += buffer.len(p.data) + end + return out +end + +-- ------------------------------------------------------------------------------------------------ WAV +local PCM: { [string]: { number } } = { -- tag, bits, bytes swapped (big-endian source) + pcm_u8 = { 1, 8, 0 }, + pcm_s8 = { 1, 8, 0 }, + pcm_s16le = { 1, 16, 0 }, + pcm_s24le = { 1, 24, 0 }, + pcm_s32le = { 1, 32, 0 }, + pcm_s16be = { 1, 16, 1 }, + pcm_s24be = { 1, 24, 1 }, + pcm_s32be = { 1, 32, 1 }, + pcm_f32le = { 3, 32, 0 }, + pcm_f64le = { 3, 64, 0 }, + pcm_f32be = { 3, 32, 1 }, + pcm_f64be = { 3, 64, 1 }, + pcm_alaw = { 6, 8, 0 }, + pcm_mulaw = { 7, 8, 0 }, +} + +local function wav(fmt: buffer, data: buffer): buffer + local w = Bytes.writer(buffer.len(data) + buffer.len(fmt) + 64) + local fl = buffer.len(fmt) + local dl = buffer.len(data) + w:string("RIFF") + w:u32le(4 + 8 + fl + (fl % 2) + 8 + dl + (dl % 2)) + w:string("WAVE") + w:string("fmt ") + w:u32le(fl) + w:bytes(fmt) + if fl % 2 == 1 then + w:u8(0) + end + w:string("data") + w:u32le(dl) + w:bytes(data) + if dl % 2 == 1 then + w:u8(0) + end + return w:finish() +end + +local function pcmWav(track: Types.Track, packets: { Types.Packet }): (buffer?, Err.Err?) + local spec = PCM[track.codec] + local ch = track.channels or 1 + local rate = math.floor((track.sampleRate or 0) + 0.5) + if ch < 1 or rate <= 0 then + return nil, Err.new(Err.CORRUPT, "PCM track without channels / sample rate") + end + local bits = spec[2] + local data = concat(packets) + if spec[3] == 1 then + local bps = bits // 8 + for i = 0, buffer.len(data) - bps, bps do + for k = 0, bps // 2 - 1 do + local a, b = buffer.readu8(data, i + k), buffer.readu8(data, i + bps - 1 - k) + buffer.writeu8(data, i + k, b) + buffer.writeu8(data, i + bps - 1 - k, a) + end + end + end + if track.codec == "pcm_s8" then + for i = 0, buffer.len(data) - 1 do + buffer.writeu8(data, i, (buffer.readu8(data, i) + 128) % 256) + end + end + local f = Bytes.writer(16) + local align = ch * bits // 8 + f:u16le(spec[1]) + f:u16le(ch) + f:u32le(rate) + f:u32le(rate * align) + f:u16le(align) + f:u16le(bits) + return wav(f:finish(), data), nil +end + +-- ------------------------------------------------------------------------------------------------ Ogg +-- the number of 48 kHz samples in an Opus packet (RFC 6716 section 3.1) +local function opusSamples(b: buffer): number + local n = buffer.len(b) + if n < 1 then + return 0 + end + local toc = buffer.readu8(b, 0) + local config = toc // 8 + local fs: number + if config < 12 then + fs = ({ 480, 960, 1920, 2880 })[config % 4 + 1] + elseif config < 16 then + fs = if config % 2 == 0 then 480 else 960 + else + fs = ({ 120, 240, 480, 960 })[config % 4 + 1] + end + local c = toc % 4 + local frames = if c == 0 then 1 elseif c == 3 then (if n >= 2 then buffer.readu8(b, 1) % 64 else 0) else 2 + return fs * frames +end + +local function opusHead(track: Types.Track): buffer + local c = track.config + if c and buffer.len(c) >= 19 and buffer.readstring(c, 0, 8) == "OpusHead" then + return c + end + local w = Bytes.writer(19) + w:string("OpusHead") + w:u8(1) + w:u8(math.clamp(track.channels or 2, 1, 2)) + w:u16le(math.floor((track.codecDelay or 0) * 48000 + 0.5)) + w:u32le(math.floor(track.sampleRate or 48000)) + w:u16le(0) + w:u8(0) + return w:finish() +end + +local function opusTags(): buffer + local w = Bytes.writer(32) + w:string("OpusTags") + local vendor = "formats-luau" + w:u32le(#vendor) + w:string(vendor) + w:u32le(0) + return w:finish() +end + +local function ogg(headers: { buffer }, packets: { Types.Packet }, granuleOf: (p: Types.Packet, i: number) -> number): buffer + local mux = Mux.new({ pageSize = 4096 }) + local s = mux:stream(1) + for i, h in headers do + s:packet(h, 0, { flush = i == 1 or i == #headers }) + end + for i, p in packets do + s:packet(p.data, granuleOf(p, i), { eos = i == #packets }) + end + return mux:finish() +end + +-- Matroska's Vorbis CodecPrivate: Xiph-laced headers (count - 1, sizes, data) +local function xiphHeaders(c: buffer): { buffer }? + local n = buffer.len(c) + if n < 3 then + return nil + end + local count = buffer.readu8(c, 0) + 1 + local p = 1 + local sizes = {} + local total = 0 + for k = 1, count - 1 do + local s = 0 + while true do + if p >= n then + return nil + end + local b = buffer.readu8(c, p) + p += 1 + s += b + if b ~= 255 then + break + end + end + sizes[k] = s + total += s + end + sizes[count] = n - p - total + if sizes[count] < 0 then + return nil + end + local out = {} + for k = 1, count do + local b = buffer.create(sizes[k]) + buffer.copy(b, 0, c, p, sizes[k]) + p += sizes[k] + out[k] = b + end + return out +end + +-- Vorbis packet sizes: the block sizes from the identification header and each mode's block flag from the end of the +-- setup header (read backwards from its framing bit: mode entries are 41 bits whose window / transform types are 0, +-- preceded by the 6-bit mode count), so the Ogg granules are exact: a packet yields (previous + current block) / 4 +-- samples (the first one as if its previous block had its own size, as ffmpeg times it). +local function bit(b: buffer, k: number): number + return bit32.extract(buffer.readu8(b, k // 8), k % 8, 1) +end +local function bits(b: buffer, k: number, n: number): number + local v = 0 + for i = n - 1, 0, -1 do + v = v * 2 + bit(b, k + i) + end + return v +end + +local function vorbisModes(id: buffer, setup: buffer): ({ number }?, { boolean }?) + if buffer.len(id) < 30 or buffer.len(setup) < 8 then + return nil + end + local bs = buffer.readu8(id, 28) + local sizes = { 2 ^ (bs % 16), 2 ^ (bs // 16) } + -- the framing bit: the highest set bit of the last non-zero byte + local last = buffer.len(setup) - 1 + while last > 0 and buffer.readu8(setup, last) == 0 do + last -= 1 + end + local v = buffer.readu8(setup, last) + local hb = 7 + while hb > 0 and bit32.extract(v, hb, 1) == 0 do + hb -= 1 + end + local f = last * 8 + hb + local flags: { boolean } = {} + local pos = f + while #flags < 64 and pos - 41 >= 7 * 8 do + local s0 = pos - 41 + if bits(setup, s0 + 1, 16) ~= 0 or bits(setup, s0 + 17, 16) ~= 0 then + break + end + table.insert(flags, 1, bit(setup, s0) == 1) + pos = s0 + end + -- the largest count whose 6-bit field matches + for n = #flags, 1, -1 do + local start = f - 41 * n + if start - 6 >= 0 and bits(setup, start - 6, 6) == n - 1 then + local out = {} + for i = #flags - n + 1, #flags do + table.insert(out, flags[i]) + end + return sizes, out + end + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ ADTS +local function adts(track: Types.Track, packets: { Types.Packet }): (buffer?, Err.Err?) + local c = track.config + local profile, rateIndex, chanConfig + if c and buffer.len(c) >= 2 then + local b0, b1 = buffer.readu8(c, 0), buffer.readu8(c, 1) + profile = b0 // 8 -- audio object type + rateIndex = (b0 % 8) * 2 + b1 // 128 + chanConfig = (b1 // 8) % 16 + else + local rates = { 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350 } + profile = 2 + rateIndex = 4 + for i, r in rates do + if r == math.floor((track.sampleRate or 44100) + 0.5) then + rateIndex = i - 1 + end + end + chanConfig = track.channels or 2 + end + if profile < 1 or profile > 4 or rateIndex > 12 then + return nil, Err.new(Err.UNSUPPORTED, "AAC object type " .. tostring(profile) .. " in ADTS") + end + local w = Bytes.writer(64) + for _, p in packets do + local len = buffer.len(p.data) + 7 + w:u8(0xFF) + w:u8(0xF1) + w:u8((profile - 1) * 64 + rateIndex * 4 + chanConfig // 4) + w:u8((chanConfig % 4) * 64 + (len // 2048) % 4) + w:u8((len // 8) % 256) + w:u8((len % 8) * 32 + 0x1F) + w:u8(0xFC) + w:bytes(p.data) + end + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ trim +-- trim(decoder, frames) -> an audio Decoder that drops the first `frames` sample frames (a container's codec delay: +-- Matroska CodecDelay for MP2 / MP3 / AAC, which ffmpeg drops too; Opus handles its pre-skip itself) +function AudioWrap.trim(dec: any, skip: number): any + if skip <= 0 then + return dec + end + local rate = dec.sampleRate + local w: any = setmetatable({}, { __index = dec }) + w.frames = math.max(0, (dec.frames or 0) - skip) + w.duration = math.max(0, (dec.duration or 0) - skip / rate) + local function drop() + local left = skip + while left > 0 do + local _, n = dec:read(math.min(left, 4096)) + if not n or n <= 0 then + break + end + left -= n + end + end + local started = false + function w.read(_: any, n: number, out: buffer?): (buffer, number) + if not started then + started = true + drop() + end + return dec:read(n, out) + end + function w.seek(_: any, seconds: number) + started = true + if seconds <= 0 then + dec:seek(0) + drop() + else + dec:seek(seconds + skip / rate) + end + end + function w.position(_: any): number + return math.max(0, dec:position() - skip / rate) + end + return w +end + +-- ------------------------------------------------------------------------------------------------ wrap +-- wrap(demuxer, track) -> buffer, audio format name | nil, nil, Err +function AudioWrap.wrap(dmx: any, track: Types.Track): (buffer?, string?, Err.Err?) + if type(track) ~= "table" or track.kind ~= "audio" then + return nil, nil, Err.new(Err.ARG, "not an audio track") + end + if track.unsupported then + return nil, nil, Err.new(Err.UNSUPPORTED, track.unsupported) + end + local codec = track.codec + local packets = allPackets(dmx, track) + if #packets == 0 then + return nil, nil, Err.new(Err.CORRUPT, "audio track without packets") + end + if track.waveFormat and string.sub(codec, 1, 6) == "adpcm_" then + return wav(track.waveFormat, concat(packets)), "wav", nil + end + if PCM[codec] then + local b, err = pcmWav(track, packets) + return b, if b then "wav" else nil, err + end + if codec == "mp3" or codec == "mp2" or codec == "mp1" then + return concat(packets), "mp3", nil + end + if codec == "flac" then + local c = track.config + local prefix: buffer? = nil + if c and buffer.len(c) >= 4 and buffer.readstring(c, 0, 4) == "fLaC" then + prefix = c + elseif c and buffer.len(c) >= 34 then + -- metadata blocks without the marker (MP4 dfLa payload after version / flags) + local start = if buffer.len(c) >= 38 and buffer.readu8(c, 0) == 0 and buffer.readu8(c, 4) % 128 == 0 then 4 else 0 + local b = buffer.create(4 + buffer.len(c) - start) + buffer.writestring(b, 0, "fLaC") + buffer.copy(b, 4, c, start) + prefix = b + else + return nil, nil, Err.new(Err.CORRUPT, "FLAC track without its STREAMINFO") + end + return concat(packets, prefix), "flac", nil + end + if codec == "opus" then + local head = opusHead(track) + local pre = buffer.readu16(head, 10) + local g = pre + local out = ogg({ head, opusTags() }, packets, function(p: Types.Packet): number + g += opusSamples(p.data) + local d = (p :: any).discardPadding + if type(d) == "number" and d > 0 then + return g - math.floor(d * 48000 + 0.5) -- the end trimming (WebM DiscardPadding) + end + return g + end) + return out, "opus", nil + end + if codec == "vorbis" then + local c = track.config + local headers = c and xiphHeaders(c) + if not headers or #headers ~= 3 then + return nil, nil, Err.new(Err.CORRUPT, "Vorbis track without its three headers") + end + local sizes, modes = vorbisModes(headers[1], headers[3]) + local granule, prev = 0, nil :: number? + local rate = track.sampleRate or 44100 + local scale = track.timescale + local out = ogg(headers, packets, function(p: Types.Packet): number + if not sizes or not modes then + return math.floor((p.pts + (p.duration or 0)) / scale * rate + 0.5) -- from the container's times + end + local d = p.data + if buffer.len(d) == 0 or buffer.readu8(d, 0) % 2 ~= 0 then + return granule + end + local mb = 0 + while 2 ^ mb < #modes do + mb += 1 + end + local m = if mb > 0 and buffer.len(d) * 8 > mb then bits(d, 1, mb) else 0 + local cur = sizes[if modes[m + 1] then 2 else 1] + if prev then + granule += (prev + cur) // 4 + end + prev = cur + return granule + end) + return out, "vorbis", nil + end + if codec == "aac" then + if track.adts then + return concat(packets), "aac", nil -- already ADTS (MPEG-TS) + end + local b, err = adts(track, packets) + return b, if b then "aac" else nil, err + end + return nil, nil, Err.new(Err.UNSUPPORTED, "no audio format for codec " .. tostring(codec)) +end + +return AudioWrap diff --git a/src/Formats/containers/Avi/init.luau b/src/Formats/containers/Avi/init.luau new file mode 100644 index 0000000..521dbe9 --- /dev/null +++ b/src/Formats/containers/Avi/init.luau @@ -0,0 +1,523 @@ +--!strict +-- containers/Avi: the AVI RIFF form (Microsoft AVI 1.0 + the OpenDML 1.02 extensions). New in formats-luau. +-- Reading: hdrl (avih, strl: strh / strf / strn / indx), every RIFF piece (RIFF AVI + RIFF AVIX ...), and the chunk +-- index of every stream: from the OpenDML super index (indx -> ix## standard / field indexes), else idx1 (offsets +-- relative to the movi list or absolute, detected), else a linear scan of the movi lists (LIST rec included). +-- Writing: AVI 1.0 (avih, strl, LIST movi, idx1) with an OpenDML odml / dmlh header, chunks interleaved as given. +-- +-- local avi, err = Avi.read(buf, base, limit) +-- avi.streams[i] = { type = "vids" | "auds" | ..., handler, scale, rate, start, length, sampleSize, strf +-- (buffer), name, chunks = { { offset, size, key } } } -- offsets of the chunk data, absolute +-- local w = Avi.writer({ streams = {...}, avih = {...} }); w:chunk(streamIndex, data, key); local file = w:finish() +-- +-- Never throws: malformed data returns nil, Err (a damaged index falls back to scanning). +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") + +local readu8, readu16, readu32, readstring = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readstring + +local Avi = {} + +export type Chunk = { offset: number, size: number, key: boolean } +export type Stream = { + index: number, -- 0-based stream number (the "##" of the chunk ids) + type: string, -- strh fccType: "vids", "auds", "txts", "mids" + handler: string, + flags: number, + scale: number, + rate: number, + start: number, + length: number, + suggestedBufferSize: number, + sampleSize: number, + frame: { number }, -- rcFrame left, top, right, bottom + strf: buffer, -- the format block (BITMAPINFOHEADER / WAVEFORMATEX ...) + name: string?, + chunks: { Chunk }, +} +export type File = { + avih: { microSecPerFrame: number, flags: number, totalFrames: number, streams: number, width: number, height: number }, + streams: { Stream }, + odml: { totalFrames: number }?, + info: { [string]: string }, + index: string, -- "odml" | "idx1" | "scan" +} + +local function u32(b: buffer, o: number): number + return readu32(b, o) +end + +-- chunk walker over [p, limit): calls fn(id, dataOffset, size, listType?) for each chunk (LIST bodies are not +-- entered); returns where it stopped +local function walk(b: buffer, p: number, limit: number, fn: (id: string, data: number, size: number, ltype: string?) -> boolean?): number + while p + 8 <= limit do + local id = readstring(b, p, 4) + local size = u32(b, p + 4) + local data = p + 8 + local ltype: string? = nil + if (id == "LIST" or id == "RIFF") and data + 4 <= limit then + ltype = readstring(b, data, 4) + end + if data + size > limit then + size = limit - data + end + if fn(id, data, size, ltype) == false then + return p + end + p = data + size + (size % 2) + end + return p +end + +local function streamNumber(id: string): number? + local a, b = string.byte(id, 1, 2) + if not a or not b then + return nil + end + local function hex(c: number): number? + if c >= 48 and c <= 57 then + return c - 48 + elseif c >= 65 and c <= 70 then + return c - 55 + elseif c >= 97 and c <= 102 then + return c - 87 + end + return nil + end + local h, l = hex(a), hex(b) + if h and l then + return h * 16 + l + end + return nil +end +Avi.streamNumber = streamNumber + +local function parseStrl(b: buffer, data: number, size: number, index: number): Stream + local s: Stream = { + index = index, + type = "", + handler = "", + flags = 0, + scale = 1, + rate = 1, + start = 0, + length = 0, + suggestedBufferSize = 0, + sampleSize = 0, + frame = { 0, 0, 0, 0 }, + strf = buffer.create(0), + chunks = {}, + } + local indx: { number }? = nil + walk(b, data + 4, data + size, function(id: string, d: number, n: number): boolean? + if id == "strh" and n >= 48 then + s.type = readstring(b, d, 4) + s.handler = readstring(b, d + 4, 4) + s.flags = u32(b, d + 8) + s.scale = u32(b, d + 20) + s.rate = u32(b, d + 24) + s.start = u32(b, d + 28) + s.length = u32(b, d + 32) + s.suggestedBufferSize = u32(b, d + 36) + s.sampleSize = u32(b, d + 44) + if n >= 56 then + s.frame = { buffer.readi16(b, d + 48), buffer.readi16(b, d + 50), buffer.readi16(b, d + 52), buffer.readi16(b, d + 54) } + end + elseif id == "strf" then + local f = buffer.create(n) + buffer.copy(f, 0, b, d, n) + s.strf = f + elseif id == "strn" then + local str = readstring(b, d, n) + s.name = string.match(str, "^[^%z]*") + elseif id == "indx" and n >= 24 then + indx = { d, n } + end + return nil + end) + ;(s :: any)._indx = indx + return s +end + +-- an OpenDML index chunk (indx super index or ix## standard index) at d with n bytes: appends chunks to s +local function readIndex(b: buffer, d: number, n: number, s: Stream, limit: number, depth: number): boolean + if n < 24 or depth > 2 then + return false + end + local longsPerEntry = readu16(b, d) + local subType = readu8(b, d + 2) + local indexType = readu8(b, d + 3) + local entries = u32(b, d + 4) + if indexType == 0 then -- AVI_INDEX_OF_INDEXES: { qwOffset, dwSize, dwDuration } + if longsPerEntry ~= 4 then + return false + end + local p = d + 24 + for _ = 1, entries do + if p + 16 > d + n then + break + end + local off = u32(b, p) + u32(b, p + 4) * 4294967296 + local size = u32(b, p + 8) + p += 16 + if off > 0 and off + 8 <= limit then + local sz = math.min(u32(b, off + 4), limit - off - 8) + readIndex(b, off + 8, if size > 0 then math.min(sz, size) else sz, s, limit, depth + 1) + end + end + return #s.chunks > 0 + elseif indexType == 1 then -- AVI_INDEX_OF_CHUNKS: base offset, { dwOffset, dwSize } (or field index: 3 longs) + if n < 24 then + return false + end + local base = u32(b, d + 12) + u32(b, d + 16) * 4294967296 + local per = if subType == 1 then 12 else 8 -- AVI_INDEX_2FIELD + local p = d + 24 + for _ = 1, entries do + if p + per > d + n then + break + end + local off = u32(b, p) + local size = u32(b, p + 4) + p += per + local key = size < 0x80000000 + size %= 0x80000000 + local at = base + off + if at >= 0 and at + size <= limit then + table.insert(s.chunks, { offset = at, size = size, key = key }) + end + end + return true + end + return false +end + +-- read(buf, base, limit) -> File | nil, Err +function Avi.read(b: buffer, base: number, limit: number): (File?, Err.Err?) + if limit - base < 12 or readstring(b, base, 4) ~= "RIFF" or readstring(b, base + 8, 4) ~= "AVI " then + return nil, Err.new(Err.CORRUPT, "not an AVI file", base) + end + local file: File = { + avih = { microSecPerFrame = 0, flags = 0, totalFrames = 0, streams = 0, width = 0, height = 0 }, + streams = {}, + odml = nil, + info = {}, + index = "scan", + } + local movis: { { number } } = {} -- { data offset of the 'movi' fourcc, end } + local idx1: { number }? = nil + local hdrl = false + -- every RIFF piece (AVI, then AVIX for OpenDML files) + walk(b, base, limit, function(id: string, d: number, n: number, ltype: string?): boolean? + if id ~= "RIFF" then + return nil + end + walk(b, d + 4, d + n, function(cid: string, cd: number, cn: number, cltype: string?): boolean? + if cid == "LIST" and cltype == "hdrl" and not hdrl then + hdrl = true + local si = 0 + walk(b, cd + 4, cd + cn, function(hid: string, hd: number, hn: number, hltype: string?): boolean? + if hid == "avih" and hn >= 40 then + file.avih = { + microSecPerFrame = u32(b, hd), + flags = u32(b, hd + 12), + totalFrames = u32(b, hd + 16), + streams = u32(b, hd + 24), + width = u32(b, hd + 32), + height = u32(b, hd + 36), + } + elseif hid == "LIST" and hltype == "strl" then + table.insert(file.streams, parseStrl(b, hd, hn, si)) + si += 1 + elseif hid == "LIST" and hltype == "odml" then + walk(b, hd + 4, hd + hn, function(oid: string, od: number, on: number): boolean? + if oid == "dmlh" and on >= 4 then + file.odml = { totalFrames = u32(b, od) } + end + return nil + end) + end + return nil + end) + elseif cid == "LIST" and cltype == "movi" then + table.insert(movis, { cd, cd + cn }) + elseif cid == "LIST" and cltype == "INFO" then + walk(b, cd + 4, cd + cn, function(iid: string, idd: number, inn: number): boolean? + file.info[iid] = string.match(readstring(b, idd, inn), "^[^%z]*") or "" + return nil + end) + elseif cid == "idx1" and not idx1 then + idx1 = { cd, cn } + end + return nil + end) + return nil + end) + if not hdrl then + return nil, Err.new(Err.CORRUPT, "no hdrl list") + end + if #file.streams == 0 then + return nil, Err.new(Err.CORRUPT, "no streams") + end + -- 1. OpenDML indexes + local odml = true + for _, s in file.streams do + local ix = (s :: any)._indx + if not ix or not readIndex(b, ix[1], ix[2], s, limit, 0) then + odml = false + end + end + if odml then + file.index = "odml" + else + for _, s in file.streams do + table.clear(s.chunks) + end + -- 2. idx1 + local ok = false + if idx1 and movis[1] then + local d, n = idx1[1], idx1[2] + local count = n // 16 + local moviBase = movis[1][1] -- the 'movi' fourcc + -- relative or absolute offsets: check the first entry that points at a chunk id + local rel = true + if count > 0 then + local off = u32(b, d + 8) + local ckid = readstring(b, d, 4) + local relAt, absAt = moviBase + off, base + off + if relAt + 4 <= limit and readstring(b, relAt, 4) == ckid then + rel = true + elseif absAt + 4 <= limit and readstring(b, absAt, 4) == ckid then + rel = false + end + end + for k = 0, count - 1 do + local e = d + k * 16 + local ckid = readstring(b, e, 4) + local flags = u32(b, e + 4) + local off = u32(b, e + 8) + local size = u32(b, e + 12) + local sn = streamNumber(ckid) + local s = sn and file.streams[sn + 1] + if s and string.sub(ckid, 3, 4) ~= "pc" then + local at = (if rel then moviBase else base) + off + 8 + if at + size <= limit then + table.insert(s.chunks, { offset = at, size = size, key = bit32.band(flags, 0x10) ~= 0 }) + ok = true + end + end + end + end + if ok then + file.index = "idx1" + else + for _, s in file.streams do + table.clear(s.chunks) + end + -- 3. scan the movi lists + local function scan(d0: number, e0: number) + walk(b, d0, e0, function(id: string, d: number, n: number, ltype: string?): boolean? + if id == "LIST" and ltype == "rec " then + scan(d + 4, d + n) + return nil + end + local sn = streamNumber(id) + local s = sn and file.streams[sn + 1] + if s and string.sub(id, 1, 2) ~= "ix" and string.sub(id, 3, 4) ~= "pc" then + table.insert(s.chunks, { offset = d, size = n, key = true }) + end + return nil + end) + end + for _, m in movis do + scan(m[1] + 4, m[2]) + end + file.index = "scan" + end + end + for _, s in file.streams do + (s :: any)._indx = nil + end + return file, nil +end + +-- ------------------------------------------------------------------------------------------------ writing +export type WStream = { + type: string, -- "vids" | "auds" + handler: string, -- fccHandler (4 chars) + scale: number, + rate: number, + sampleSize: number, -- 0 = every chunk one sample (video, VBR audio) + strf: buffer, + name: string?, + width: number?, + height: number?, + quality: number?, + ckid: string?, -- the chunk id suffix: "dc" (video), "wb" (audio) +} +export type WOptions = { + streams: { WStream }, + microSecPerFrame: number, + width: number, + height: number, + software: string?, +} + +-- write(opts, chunks) -> buffer: chunks = { { stream (1-based), data: buffer, key: boolean } } in file order +function Avi.write(opts: WOptions, chunks: { { any } }): buffer + local ns = #opts.streams + local lengths = table.create(ns, 0) + local maxChunk = table.create(ns, 0) + local bytes = table.create(ns, 0) + local total = 0 + for _, c in chunks do + local si, data = c[1], c[2] + local n = buffer.len(data) + local s = opts.streams[si] + if s.sampleSize > 0 then + lengths[si] += n // s.sampleSize + else + lengths[si] += 1 + end + bytes[si] += n + if n > maxChunk[si] then + maxChunk[si] = n + end + total += n + 8 + (n % 2) + end + local frames = 0 + for si, s in opts.streams do + if s.type == "vids" and frames == 0 then + frames = lengths[si] + end + end + local w = Bytes.writer(total + 4096 + #chunks * 16) + w:string("RIFF") + local riffSize = w:tell() + w:u32le(0) + w:string("AVI ") + -- hdrl + w:string("LIST") + local hdrlSize = w:tell() + w:u32le(0) + w:string("hdrl") + w:string("avih") + w:u32le(56) + local duration = if opts.microSecPerFrame > 0 then frames * opts.microSecPerFrame / 1e6 else 1 + local maxBytes = 0 + for si = 1, ns do + maxBytes += bytes[si] + end + w:u32le(math.floor(opts.microSecPerFrame + 0.5)) + w:u32le(if duration > 0 then math.floor(maxBytes / duration) else 0) + w:u32le(0) -- padding granularity + w:u32le(0x10 + 0x100) -- AVIF_HASINDEX | AVIF_ISINTERLEAVED + w:u32le(frames) + w:u32le(0) -- initial frames + w:u32le(ns) + local suggested = 0 + for si = 1, ns do + suggested = math.max(suggested, maxChunk[si] + 8) + end + w:u32le(suggested) + w:u32le(opts.width) + w:u32le(opts.height) + for _ = 1, 4 do + w:u32le(0) + end + for si, s in opts.streams do + w:string("LIST") + local strlSize = w:tell() + w:u32le(0) + w:string("strl") + w:string("strh") + w:u32le(56) + w:string(s.type) + w:string(s.handler) + w:u32le(0) -- flags + w:u16le(0) -- priority + w:u16le(0) -- language + w:u32le(0) -- initial frames + w:u32le(s.scale) + w:u32le(s.rate) + w:u32le(0) -- start + w:u32le(lengths[si]) + w:u32le(maxChunk[si]) + w:u32le(if s.quality then s.quality else 0xFFFFFFFF) + w:u32le(s.sampleSize) + w:u16le(0) + w:u16le(0) + w:u16le(s.width or 0) + w:u16le(s.height or 0) + w:string("strf") + w:u32le(buffer.len(s.strf)) + w:bytes(s.strf) + if buffer.len(s.strf) % 2 == 1 then + w:u8(0) + end + if s.name then + local nm = s.name .. "\0" + w:string("strn") + w:u32le(#nm) + w:string(nm) + if #nm % 2 == 1 then + w:u8(0) + end + end + w:setU32le(strlSize, w:tell() - strlSize - 4) + end + -- OpenDML extended header (total frames) + w:string("LIST") + w:u32le(16) + w:string("odml") + w:string("dmlh") + w:u32le(4) + w:u32le(frames) + w:setU32le(hdrlSize, w:tell() - hdrlSize - 4) + -- INFO + local sw = (opts.software or "formats-luau") .. "\0" + if #sw % 2 == 1 then + sw ..= "\0" + end + w:string("LIST") + w:u32le(4 + 8 + #sw) + w:string("INFO") + w:string("ISFT") + w:u32le(#sw) + w:string(sw) + -- movi + w:string("LIST") + local moviSize = w:tell() + w:u32le(0) + local moviBase = w:tell() + w:string("movi") + local index = table.create(#chunks) + for _, c in chunks do + local si, data, key = c[1], c[2], c[3] + local s = opts.streams[si] + local id = string.format("%02d", si - 1) .. (s.ckid or (if s.type == "vids" then "dc" else "wb")) + local at = w:tell() + local n = buffer.len(data) + w:string(id) + w:u32le(n) + w:bytes(data) + if n % 2 == 1 then + w:u8(0) + end + table.insert(index, { id, if key then 0x10 else 0, at - moviBase, n }) + end + w:setU32le(moviSize, w:tell() - moviSize - 4) + -- idx1 + w:string("idx1") + w:u32le(#index * 16) + for _, e in index do + w:string(e[1]) + w:u32le(e[2]) + w:u32le(e[3]) + w:u32le(e[4]) + end + w:setU32le(riffSize, w:tell() - 8) + return w:finish() +end + +return Avi diff --git a/src/Formats/containers/Demux.luau b/src/Formats/containers/Demux.luau new file mode 100644 index 0000000..1ceec61 --- /dev/null +++ b/src/Formats/containers/Demux.luau @@ -0,0 +1,296 @@ +--!strict +-- containers/Demux: the indexed Types.Demuxer every video container builds (Matroska, AVI, MPEG-TS / PS, Y4M, MP4). +-- New in formats-luau. A container parses its file once into an index of packets (track, pts, dts, duration, +-- keyframe, and the bytes as an offset + length into the source buffer or a buffer of their own); this module gives +-- that index the Demuxer interface: per-track cursors (a video decoder and an audio decoder read the same file +-- independently), a file-order cursor, keyframe seeking, packet copies on demand. +-- +-- local d = Demux.new("mkv", tracks, src, meta) +-- d:add(trackId, pts, dts, duration, keyframe, offset, length) -- in file order +-- d:addData(trackId, pts, dts, duration, keyframe, buffer) -- bytes that are not one range of src +-- d:finish() -- durations, per-track indexes +-- for p in d:packets(1) do ... end; d:read(); d:seek(12.5); d:count(1); d:get(1, i) +local Types = require("@formats/Types") + +local Demux = {} +local D = {} +D.__index = D + +export type Demux = typeof(setmetatable( + {} :: { + kind: "demuxer", + format: string, + tracks: { Types.Track }, + duration: number, + startTime: number, + meta: { [string]: any }, + src: buffer, + n: number, + tr: { number }, + pts: { number }, + dts: { number }, + dur: { number }, + key: { boolean }, + off: { number }, + len: { number }, + data: { [number]: buffer }, + extra: { [number]: { [string]: any } }, + byTrack: { [number]: { number } }, + cur: { [number]: number }, + gcur: number, + }, + D +)) + +-- new(format, tracks, src, meta?) -> an empty index +function Demux.new(format: string, tracks: { Types.Track }, src: buffer, meta: { [string]: any }?): Demux + return setmetatable({ + kind = "demuxer" :: "demuxer", + format = format, + tracks = tracks, + duration = 0, + startTime = 0, + meta = meta or {}, + src = src, + n = 0, + tr = {}, + pts = {}, + dts = {}, + dur = {}, + key = {}, + off = {}, + len = {}, + data = {}, + extra = {}, + byTrack = {}, + cur = {}, + gcur = 1, + }, D) +end + +-- add(track, pts, dts?, duration?, keyframe, offset, length): a packet whose bytes are src[offset, offset + length) +function D.add(self: Demux, track: number, pts: number, dts: number?, duration: number?, keyframe: boolean, offset: number, length: number) + local i = self.n + 1 + self.n = i + self.tr[i] = track + self.pts[i] = pts + self.dts[i] = dts or pts + self.dur[i] = duration or 0 + self.key[i] = keyframe + self.off[i] = offset + self.len[i] = length +end + +-- addData(track, pts, dts?, duration?, keyframe, data): a packet with its own bytes +function D.addData(self: Demux, track: number, pts: number, dts: number?, duration: number?, keyframe: boolean, data: buffer) + self:add(track, pts, dts, duration, keyframe, -1, buffer.len(data)) + self.data[self.n] = data +end + +-- setExtra(key, value): a field for the last packet added (Packet[key] = value: discardPadding, ...) +function D.setExtra(self: Demux, key: string, value: any) + local e = self.extra[self.n] + if not e then + e = {} + self.extra[self.n] = e + end + e[key] = value +end + +-- finish(): builds the per-track indexes, fills missing packet durations from the next packet's pts (or the track's +-- frame rate), and the track / file durations (seconds) where the container gave none +function D.finish(self: Demux) + local byTrack: { [number]: { number } } = {} + for _, t in self.tracks do + byTrack[t.id] = {} + end + for i = 1, self.n do + local list = byTrack[self.tr[i]] + if list then + table.insert(list, i) + end + end + self.byTrack = byTrack + local total = self.duration + local start = math.huge + for _, t in self.tracks do + local list = byTrack[t.id] + local scale = if t.timescale and t.timescale > 0 then t.timescale else 1 + t.timescale = scale + local frameTicks = if t.frameRate and t.frameRate > 0 then scale / t.frameRate else 0 + -- durations from the next packet in presentation order + if #list > 0 then + local order = table.clone(list) + table.sort(order, function(a: number, b: number): boolean + return self.pts[a] < self.pts[b] + end) + for k = 1, #order do + local i = order[k] + if self.dur[i] <= 0 then + local nx = order[k + 1] + if nx and self.pts[nx] > self.pts[i] then + self.dur[i] = self.pts[nx] - self.pts[i] + elseif frameTicks > 0 then + self.dur[i] = frameTicks + elseif k > 1 then + self.dur[i] = self.dur[order[k - 1]] + end + end + end + local first, last = order[1], order[#order] + if t.kind == "video" or t.kind == "audio" then + start = math.min(start, self.pts[first] / scale) + end + local d = (self.pts[last] + self.dur[last] - math.min(0, self.pts[first])) / scale + if not t.duration or t.duration <= 0 then + t.duration = d + end + t.frames = t.frames or #list + end + if t.duration and t.duration > total then + total = t.duration + end + self.cur[t.id] = 1 + end + self.duration = total + -- the presentation time of the first video / audio packet (MPEG-TS streams start at ~1.4 s): VideoDecoders count + -- frame times from it + self.startTime = if start ~= math.huge and start > 0 then start else 0 +end + +-- the Packet for index entry i (a copy of its bytes) +function D._packet(self: Demux, i: number): Types.Packet + local data = self.data[i] + if not data then + local o, l = self.off[i], self.len[i] + local src = self.src + local n = buffer.len(src) + if o < 0 or o > n then + o, l = n, 0 + elseif o + l > n then + l = n - o + end + data = buffer.create(l) + buffer.copy(data, 0, src, o, l) + end + local p: any = { + track = self.tr[i], + pts = self.pts[i], + dts = self.dts[i], + duration = self.dur[i], + keyframe = self.key[i], + data = data :: buffer, + } + local e = self.extra[i] + if e then + for k, v in e do + p[k] = v + end + end + return p +end + +-- read(track?) -> the next Packet of the track (or of any track, in file order) | nil at the end +function D.read(self: Demux, track: number?): Types.Packet? + if track == nil then + local i = self.gcur + if i > self.n then + return nil + end + self.gcur = i + 1 + return self:_packet(i) + end + local list = self.byTrack[track] + if not list then + return nil + end + local c = self.cur[track] or 1 + local i = list[c] + if not i then + return nil + end + self.cur[track] = c + 1 + return self:_packet(i) +end + +-- packets(track?) -> an iterator of Packets from the current position (advancing it) +function D.packets(self: Demux, track: number?): () -> Types.Packet? + return function(): Types.Packet? + return self:read(track) + end +end + +-- count(track) -> number of packets; get(track, k) -> the k-th packet (1-based) without moving cursors +function D.count(self: Demux, track: number): number + local list = self.byTrack[track] + return if list then #list else 0 +end +function D.get(self: Demux, track: number, k: number): Types.Packet? + local list = self.byTrack[track] + local i = list and list[k] + if not i then + return nil + end + return self:_packet(i) +end + +-- info(track, k) -> pts, dts, duration, keyframe, length of the k-th packet (no copy) +function D.info(self: Demux, track: number, k: number): (number?, number?, number?, boolean?, number?) + local list = self.byTrack[track] + local i = list and list[k] + if not i then + return nil + end + return self.pts[i], self.dts[i], self.dur[i], self.key[i], self.len[i] +end + +-- rewind(track?): a track's cursor (or every cursor) back to the start +function D.rewind(self: Demux, track: number?) + if track then + self.cur[track] = 1 + return + end + for id in self.cur do + self.cur[id] = 1 + end + self.gcur = 1 +end + +-- seek(seconds): each track to its last keyframe at or before the time (the file-order cursor to the earliest) +function D.seek(self: Demux, seconds: number) + local g = self.n + 1 + for _, t in self.tracks do + local list = self.byTrack[t.id] + if list and #list > 0 then + local target = seconds * t.timescale + local best = 1 + for k = 1, #list do + local i = list[k] + if self.key[i] and self.pts[i] <= target + 1e-6 then + best = k + end + end + self.cur[t.id] = best + if list[best] < g then + g = list[best] + end + end + end + self.gcur = if g > self.n then 1 else g +end + +-- track(kind) -> the first default track of the kind, else the first of the kind +function D.track(self: Demux, kind: string): Types.Track? + local first = nil + for _, t in self.tracks do + if t.kind == kind then + if t.default then + return t + end + first = first or t + end + end + return first +end + +return Demux diff --git a/src/Formats/containers/Ebml/init.luau b/src/Formats/containers/Ebml/init.luau new file mode 100644 index 0000000..2efc113 --- /dev/null +++ b/src/Formats/containers/Ebml/init.luau @@ -0,0 +1,335 @@ +--!strict +-- containers/Ebml: EBML (RFC 8794), the binary structure under Matroska and WebM. New in formats-luau. +-- Reading: element headers (IDs keep their length marker bits, as the specs write them: 0x1A45DFA3; sizes drop it; +-- an all-ones size is "unknown"), children iteration, and the value types (unsigned / signed integers, floats, +-- strings, binary). Writing: a byte builder with nested master elements whose 8-byte sizes are patched on close, and +-- minimal-length value elements. +-- +-- local id, size, data = Ebml.header(buf, pos, limit) -- size = -1: unknown; nil when malformed / truncated +-- for id, off, size in Ebml.children(buf, off, limit) do ... end +-- local w = Ebml.writer(); local m = w:open(0x18538067); w:uint(0xD7, 1); w:close(m); local out = w:finish() +-- +-- Never throws: malformed input gives nil (readers) or stops iteration. +local Bytes = require("@formats/core/Bytes") + +local readu8 = buffer.readu8 + +local Ebml = {} + +Ebml.UNKNOWN = -1 + +-- vint(buf, pos, limit) -> value (marker removed), length | nil. All-ones values (unknown sizes) return -1. +function Ebml.vint(buf: buffer, pos: number, limit: number): (number?, number?) + if pos >= limit then + return nil + end + local b = readu8(buf, pos) + if b == 0 then + return nil + end + local len = 1 + local mask = 0x80 + while bit32.band(b, mask) == 0 do + len += 1 + mask = mask // 2 + end + if pos + len > limit then + return nil + end + local v = bit32.band(b, mask - 1) + local allOnes = v == mask - 1 + for i = 1, len - 1 do + local c = readu8(buf, pos + i) + v = v * 256 + c + if c ~= 255 then + allOnes = false + end + end + if allOnes then + return -1, len + end + return v, len +end + +-- svint(buf, pos, limit) -> a signed vint (EBML lacing deltas) | nil +function Ebml.svint(buf: buffer, pos: number, limit: number): (number?, number?) + local v, len = Ebml.vint(buf, pos, limit) + if v == nil or len == nil then + return nil + end + if v == -1 then + return nil + end + return v - (2 ^ (7 * len - 1) - 1), len +end + +-- id(buf, pos, limit) -> the element ID with its marker bits, length | nil (IDs are 1..4 bytes) +function Ebml.id(buf: buffer, pos: number, limit: number): (number?, number?) + if pos >= limit then + return nil + end + local b = readu8(buf, pos) + local len = if b >= 0x80 then 1 elseif b >= 0x40 then 2 elseif b >= 0x20 then 3 elseif b >= 0x10 then 4 else 0 + if len == 0 or pos + len > limit then + return nil + end + local v = b + for i = 1, len - 1 do + v = v * 256 + readu8(buf, pos + i) + end + return v, len +end + +-- header(buf, pos, limit) -> id, size (-1 = unknown), data offset | nil +function Ebml.header(buf: buffer, pos: number, limit: number): (number?, number?, number?) + local id, il = Ebml.id(buf, pos, limit) + if not id or not il then + return nil + end + local size, sl = Ebml.vint(buf, pos + il, limit) + if not size or not sl then + return nil + end + return id, size, pos + il + sl +end + +-- children(buf, off, limit) -> iterator of id, data offset, size (an unknown size runs to limit; a size past the +-- limit is clipped; a malformed header ends the iteration) +function Ebml.children(buf: buffer, off: number, limit: number): () -> (number?, number, number) + local pos = off + return function(): (number?, number, number) + if pos >= limit then + return nil, 0, 0 + end + local id, size, data = Ebml.header(buf, pos, limit) + if not id or not size or not data then + pos = limit + return nil, 0, 0 + end + if size < 0 or data + size > limit then + size = limit - data + end + pos = data + size + return id, data, size + end +end + +-- uint(buf, off, len) / int / float / string: element values (0 / "" for empty elements) +function Ebml.uint(buf: buffer, off: number, len: number): number + local v = 0 + for i = 0, math.min(len, 8) - 1 do + v = v * 256 + readu8(buf, off + i) + end + return v +end +function Ebml.int(buf: buffer, off: number, len: number): number + if len <= 0 then + return 0 + end + local v = Ebml.uint(buf, off, len) + local n = math.min(len, 8) + if readu8(buf, off) >= 0x80 then + v -= 2 ^ (8 * n) + end + return v +end +function Ebml.float(buf: buffer, off: number, len: number): number + local r = Bytes.reader(buf, off, len) + if len == 4 then + return r:f32be() + elseif len == 8 then + return r:f64be() + end + return 0 +end +function Ebml.string(buf: buffer, off: number, len: number): string + local s = buffer.readstring(buf, off, len) + local z = string.find(s, "\0", 1, true) + if z then + s = string.sub(s, 1, z - 1) + end + return s +end +function Ebml.binary(buf: buffer, off: number, len: number): buffer + local b = buffer.create(len) + buffer.copy(b, 0, buf, off, len) + return b +end + +-- ------------------------------------------------------------------------------------------------ writing +local W = {} +W.__index = W + +export type Writer = typeof(setmetatable({} :: { w: Bytes.Writer }, W)) + +-- writer(capacity?) -> an EBML byte builder +function Ebml.writer(capacity: number?): Writer + return setmetatable({ w = Bytes.writer(capacity or 65536) }, W) +end + +-- idBytes(id) -> the ID's bytes as written +local function writeId(w: Bytes.Writer, id: number) + if id >= 0x1000000 then + w:u32be(id) + elseif id >= 0x10000 then + w:u24be(id) + elseif id >= 0x100 then + w:u16be(id) + else + w:u8(id) + end +end + +-- size as a minimal vint (n bytes: force a length) +local function writeSize(w: Bytes.Writer, size: number, n: number?) + local len = n or 1 + if not n then + while size >= 2 ^ (7 * len) - 1 do + len += 1 + end + end + local v = size + 2 ^ (7 * len) -- the marker bit + local bytes = table.create(len, 0) + for i = len, 1, -1 do + bytes[i] = v % 256 + v = v // 256 + end + for i = 1, len do + w:u8(bytes[i]) + end +end +Ebml.writeSize = writeSize + +-- vintBytes(v, n?) -> the vint encoding of v as a string (lacing, block track numbers) +function Ebml.vintString(v: number, n: number?): string + local w = Bytes.writer(8) + writeSize(w, v, n) + return buffer.readstring(w:finish(), 0, w:tell()) +end + +function W.tell(self: Writer): number + return self.w:tell() +end + +-- open(id) -> a handle for close(): writes the ID and an 8-byte size placeholder +function W.open(self: Writer, id: number): number + writeId(self.w, id) + local at = self.w:tell() + for _ = 1, 8 do + self.w:u8(0) + end + return at +end + +-- close(handle): patches the size of the element opened at handle +function W.close(self: Writer, at: number) + local w = self.w + local v = w:tell() - at - 8 + w:setU8(at, 0x01) + for i = 7, 1, -1 do + w:setU8(at + i, v % 256) + v = v // 256 + end +end + +-- unknownSize(id): a master element with an unknown size (live streams) +function W.openUnknown(self: Writer, id: number) + writeId(self.w, id) + self.w:u8(0x01) + for _ = 1, 7 do + self.w:u8(0xFF) + end +end + +function W.uint(self: Writer, id: number, v: number) + local n = 1 + while v >= 2 ^ (8 * n) and n < 8 do + n += 1 + end + writeId(self.w, id) + writeSize(self.w, n) + local bytes = table.create(n, 0) + local x = v + for i = n, 1, -1 do + bytes[i] = x % 256 + x = x // 256 + end + for i = 1, n do + self.w:u8(bytes[i]) + end +end + +function W.int(self: Writer, id: number, v: number) + local n = 1 + while (v < -(2 ^ (8 * n - 1)) or v >= 2 ^ (8 * n - 1)) and n < 8 do + n += 1 + end + local u = if v < 0 then v + 2 ^ (8 * n) else v + writeId(self.w, id) + writeSize(self.w, n) + local bytes = table.create(n, 0) + for i = n, 1, -1 do + bytes[i] = u % 256 + u = u // 256 + end + for i = 1, n do + self.w:u8(bytes[i]) + end +end + +function W.float(self: Writer, id: number, v: number) + writeId(self.w, id) + writeSize(self.w, 8) + self.w:f64be(v) +end + +function W.string(self: Writer, id: number, s: string) + writeId(self.w, id) + writeSize(self.w, #s) + self.w:string(s) +end + +-- binary(id, buf, off?, len?) +function W.binary(self: Writer, id: number, b: buffer, off: number?, len: number?) + local o = off or 0 + local n = len or (buffer.len(b) - o) + writeId(self.w, id) + writeSize(self.w, n) + self.w:bytes(b, o, n) +end + +-- raw bytes (a pre-built element, block headers) +function W.raw(self: Writer, s: string) + self.w:string(s) +end +function W.rawBuffer(self: Writer, b: buffer, off: number?, len: number?) + local o = off or 0 + self.w:bytes(b, o, len or (buffer.len(b) - o)) +end +-- element header for a binary element whose payload follows in pieces: id + size +function W.header(self: Writer, id: number, size: number) + writeId(self.w, id) + writeSize(self.w, size) +end + +-- void(n): an EBML Void element of exactly n bytes (n >= 2), for reserved space +function W.void(self: Writer, n: number) + self.w:u8(0xEC) + if n - 2 < 127 then + writeSize(self.w, n - 2, 1) + for _ = 1, n - 2 do + self.w:u8(0) + end + else + writeSize(self.w, n - 9, 8) + for _ = 1, n - 9 do + self.w:u8(0) + end + end +end + +function W.finish(self: Writer): buffer + return self.w:finish() +end + +return Ebml diff --git a/src/Formats/containers/IsoBmff/Box.luau b/src/Formats/containers/IsoBmff/Box.luau new file mode 100644 index 0000000..769d22e --- /dev/null +++ b/src/Formats/containers/IsoBmff/Box.luau @@ -0,0 +1,193 @@ +--!strict +-- containers/IsoBmff/Box: the box tree of an ISO BMFF / QuickTime file (ISO/IEC 14496-12 4.2): 32-bit, 64-bit +-- (size 1) and to-the-end (size 0) sizes, uuid boxes, full-box version / flags, and the recursion into the container +-- boxes (moov / trak / mdia / minf / stbl / udta / meta / ilst items / moof / traf / iprp / ipco / iref / dinf / ...). +-- Sample descriptions (stsd) are left to the demuxer, which knows the sample entry layouts. Never throws. +local Err = require("@formats/core/Err") + +local readu8, readu32, readstring = buffer.readu8, buffer.readu32, buffer.readstring +local byteswap = bit32.byteswap + +local Box = {} + +export type Box = { + type: string, -- four characters ("moov", "\169nam", ...); "uuid" boxes also have `uuid` + start: number, -- absolute offset of the box in the buffer + size: number, -- the whole box, header included + data: number, -- absolute offset of the payload (after size / type / largesize / uuid) + stop: number, -- absolute offset just past the box (start + size, clamped to the parent) + uuid: string?, + children: { Box }?, -- container boxes + truncated: boolean?, -- the box claims more bytes than its parent has (clamped) +} + +-- plain container boxes: their payload is a list of boxes +local CONTAINERS = { + moov = true, trak = true, mdia = true, minf = true, stbl = true, dinf = true, edts = true, udta = true, + mvex = true, moof = true, traf = true, mfra = true, tref = true, iprp = true, ipco = true, sinf = true, + schi = true, wave = true, gmhd = true, tapt = true, ilst = true, clip = true, matt = true, rinf = true, + strk = true, strd = true, grpl = true, meco = true, mere = true, +} +-- full boxes (version + flags) whose payload is then a list of boxes, after `skip` more bytes +local FULL_CONTAINERS: { [string]: number } = { meta = 0, iref = 0, dref = 4 } +Box.CONTAINERS = CONTAINERS + +local function be32(b: buffer, o: number): number + return byteswap(readu32(b, o)) +end +Box.be32 = be32 + +-- the ilst item boxes ("\169nam", "trkn", "----", ...) contain data / mean / name boxes +local function isIlstItem(parentType: string?): boolean + return parentType == "ilst" +end + +-- header(buf, p, limit) -> Box (without children) | nil, Err +function Box.header(b: buffer, p: number, limit: number): (Box?, Err.Err?) + if p + 8 > limit then + return nil, Err.new(Err.TRUNCATED, "box header runs past the end", p) + end + local size = be32(b, p) + local typ = readstring(b, p + 4, 4) + local data = p + 8 + if size == 1 then + if p + 16 > limit then + return nil, Err.new(Err.TRUNCATED, "64-bit box size runs past the end", p) + end + size = be32(b, p + 8) * 4294967296 + be32(b, p + 12) + data = p + 16 + elseif size == 0 then + size = limit - p + end + local uuid: string? = nil + if typ == "uuid" then + if data + 16 > limit then + return nil, Err.new(Err.TRUNCATED, "uuid runs past the end", p) + end + uuid = readstring(b, data, 16) + data += 16 + end + if size < data - p then + return nil, Err.new(Err.CORRUPT, string.format("box '%s' size %d is smaller than its header", typ, size), p) + end + local stop = p + size + local truncated: boolean? = nil + if stop > limit then + stop = limit + truncated = true + end + return { type = typ, start = p, size = size, data = data, stop = stop, uuid = uuid, children = nil, truncated = truncated }, nil +end + +-- list(buf, p, limit, parentType?, depth?) -> { Box } (a run of sibling boxes, containers parsed recursively). A +-- broken box ends the list (its siblings so far are kept); the second value is the first error met, if any. +function Box.list(b: buffer, p: number, limit: number, parentType: string?, depth: number?): ({ Box }, Err.Err?) + local d = depth or 0 + local out: { Box } = {} + local firstErr: Err.Err? = nil + if d > 32 then + return out, Err.new(Err.CORRUPT, "boxes nested too deep", p) + end + while p + 8 <= limit do + local box, err = Box.header(b, p, limit) + if not box then + firstErr = firstErr or err + break + end + if box.truncated then + firstErr = firstErr or Err.new(Err.TRUNCATED, "box '" .. box.type .. "' runs past the end", p) + end + local t = box.type + local kids: { Box }? = nil + local kerr: Err.Err? = nil + if CONTAINERS[t] or isIlstItem(parentType) then + kids, kerr = Box.list(b, box.data, box.stop, t, d + 1) + elseif FULL_CONTAINERS[t] then + local q = box.data + 4 + FULL_CONTAINERS[t] + -- QuickTime writes udta/meta as a plain container: its first child box follows directly + if t == "meta" and box.data + 8 <= box.stop and readstring(b, box.data + 4, 4) == "hdlr" then + q = box.data + end + if q <= box.stop then + kids, kerr = Box.list(b, q, box.stop, t, d + 1) + end + elseif t == "iinf" then + if box.data + 4 <= box.stop then + local v = readu8(b, box.data) + local q = box.data + 4 + (if v == 0 then 2 else 4) + if q <= box.stop then + kids, kerr = Box.list(b, q, box.stop, t, d + 1) + end + end + end + box.children = kids + if kerr then + firstErr = firstErr or kerr + end + table.insert(out, box) + if box.stop <= p then + break + end + p = box.stop + end + return out, firstErr +end + +-- child(box, type) -> the first child of that type +function Box.child(box: Box?, typ: string): Box? + if not box or not box.children then + return nil + end + for _, c in box.children :: { Box } do + if c.type == typ then + return c + end + end + return nil +end + +-- children(box, type) -> every child of that type +function Box.childrenOf(box: Box?, typ: string): { Box } + local out = {} + if box and box.children then + for _, c in box.children :: { Box } do + if c.type == typ then + table.insert(out, c) + end + end + end + return out +end + +-- path(boxes or box, "moov/trak/mdia") -> the first box along the path +function Box.path(root: any, path: string): Box? + local cur: any = root + for part in string.gmatch(path, "[^/]+") do + if cur == nil then + return nil + end + local list = if cur.children ~= nil or cur.type ~= nil then cur.children else cur + local found = nil + if list then + for _, c in list do + if c.type == part then + found = c + break + end + end + end + cur = found + end + return cur +end + +-- version / flags of a full box +function Box.fullHeader(b: buffer, box: Box): (number, number) + if box.data + 4 > box.stop then + return -1, 0 + end + local v = be32(b, box.data) + return bit32.rshift(v, 24), bit32.band(v, 0xFFFFFF) +end + +return Box diff --git a/src/Formats/containers/IsoBmff/Demux.luau b/src/Formats/containers/IsoBmff/Demux.luau new file mode 100644 index 0000000..6a5a4cb --- /dev/null +++ b/src/Formats/containers/IsoBmff/Demux.luau @@ -0,0 +1,848 @@ +--!strict +-- containers/IsoBmff/Demux: tracks and sample tables of an ISO BMFF / QuickTime file (ISO/IEC 14496-12 8.3 - 8.8): +-- tkhd / mdhd / hdlr, sample descriptions (audio v0 / QuickTime v1 / v2, video, other) with the codec configuration +-- (esds DecoderSpecificInfo, alac, dOps, dfLa, avcC, hvcC, av1C, vpcC, dac3, ...), stts / ctts / stsc / stsz / stz2 / +-- stco / co64 / stss, edit lists (elst), and fragmented files (mvex / trex, moof / traf / tfhd / tfdt / trun). +-- The per-sample tables are columnar arrays (offsets / sizes / dts / durations / cts / sync), offsets absolute in the +-- reader's buffer. Never throws. +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Box = require("@formats/containers/IsoBmff/Box") + +local readstring = buffer.readstring + +local Demux = {} + +export type Edit = { duration: number, mediaTime: number, rate: number } -- duration in movie ticks, mediaTime in media ticks (-1 = empty) + +-- a track: Types.Track (id, kind, codec, timescale, duration, width, height, sampleRate, channels, config) plus the +-- sample tables and the ISO facts +export type Track = { + id: number, + kind: "video" | "audio" | "subtitle" | "data", + codec: string, -- "aac", "alac", "mp3", "opus", "flac", "pcm", "h264", "hevc", "av1", "vp8", "vp9", "mpeg4", "mjpeg", "ac3", "eac3", "tx3g", ... or the entry fourcc + entry: string, -- the sample entry fourcc ("mp4a", "alac", "avc1", ...) + handler: string, -- hdlr type ("soun", "vide", "subt", "text", "pict", ...) + timescale: number, + duration: number, -- seconds (media duration; the edit list may shorten it) + mediaDuration: number, -- ticks + language: string?, -- ISO 639-2 ("und", "eng", ...) + width: number?, + height: number?, + sampleRate: number?, + channels: number?, + bitsPerSample: number?, + config: buffer?, -- codec configuration (AudioSpecificConfig, ALAC cookie, dOps, avcC, ...) + objectType: number?, -- esds objectTypeIndication + pcm: { bits: number, float: boolean, little: boolean }?, + entryBoxes: { Box.Box }, -- the sample entry's child boxes (esds, btrt, colr, pasp, ...) + edits: { Edit }?, + skip: number, -- media ticks to drop at the start (the first edit's media time: AAC priming) + delay: number, -- movie ticks of an initial empty edit + playDuration: number?, -- media ticks the edit list plays (nil: all) + -- samples + sampleCount: number, + offsets: { number }, -- absolute offsets in the buffer + sizes: { number }, + dts: { number }, -- decode times in ticks + durations: { number }, + cts: { number }?, -- composition offsets (pts = dts + cts) when the track has ctts / trun offsets + sync: { [number]: boolean }?, -- sync samples (nil: every sample is a sync sample) + sampleDescription: { number }?, -- stsd index per sample when there are several entries + [string]: any, +} + +export type Options = { maxSamples: number? } + +local HANDLER_KIND: { [string]: "video" | "audio" | "subtitle" | "data" } = { + soun = "audio", vide = "video", pict = "video", auxv = "video", subt = "subtitle", text = "subtitle", + sbtl = "subtitle", clcp = "subtitle", +} +local CODEC: { [string]: string } = { + mp4a = "aac", alac = "alac", Opus = "opus", fLaC = "flac", [".mp3"] = "mp3", ["ac-3"] = "ac3", ["ec-3"] = "eac3", + lpcm = "pcm", sowt = "pcm", twos = "pcm", ["raw "] = "pcm", in24 = "pcm", in32 = "pcm", fl32 = "pcm", fl64 = "pcm", + ipcm = "pcm", fpcm = "pcm", ulaw = "ulaw", alaw = "alaw", samr = "amr", sawb = "amrwb", + avc1 = "h264", avc3 = "h264", hvc1 = "hevc", hev1 = "hevc", av01 = "av1", vp08 = "vp8", vp09 = "vp9", + mp4v = "mpeg4", jpeg = "mjpeg", mjpa = "mjpeg", mjpb = "mjpeg", png = "png", ["s263"] = "h263", ["mp1v"] = "mpeg1", + ["mp2v"] = "mpeg2", tx3g = "tx3g", wvtt = "webvtt", stpp = "ttml", c608 = "cea608", text = "text", +} +-- esds objectTypeIndication -> codec +local OTI: { [number]: string } = { + [0x40] = "aac", [0x66] = "aac", [0x67] = "aac", [0x68] = "aac", [0x69] = "mp3", [0x6B] = "mp3", [0x6A] = "mpeg1", + [0x60] = "mpeg2", [0x61] = "mpeg2", [0x20] = "mpeg4", [0x21] = "h264", [0x6C] = "mjpeg", [0xA5] = "ac3", + [0xA6] = "eac3", [0xAD] = "opus", [0xDD] = "vorbis", +} +-- the box holding each video / audio codec's configuration +local CONFIG_BOX = { "avcC", "hvcC", "av1C", "vpcC", "dOps", "dfLa", "dac3", "dec3", "d263", "glbl" } +local FULL_CONFIG: { [string]: boolean } = { vpcC = true, dfLa = true, alac = true } + +local function payload(b: buffer, box: Box.Box, skip: number?): buffer + local o = box.data + (skip or 0) + local n = math.max(0, box.stop - o) + local out = buffer.create(n) + if n > 0 then + buffer.copy(out, 0, b, o, n) + end + return out +end + +local function reader(b: buffer, box: Box.Box): Bytes.Reader + return Bytes.reader(b, box.data, box.stop - box.data) +end + +-- expandable descriptor length (ISO 14496-1 8.3.3) +local function descLen(r: Bytes.Reader): number + local n = 0 + for _ = 1, 4 do + local c = r:u8() + n = n * 128 + bit32.band(c, 127) + if c < 128 then + break + end + end + return n +end + +-- esds -> objectTypeIndication, DecoderSpecificInfo, avg bitrate +function Demux.esds(b: buffer, box: Box.Box): (number?, buffer?, number?) + local r = reader(b, box) + r:skip(4) -- version / flags + if r:u8() ~= 3 then + return nil, nil, nil + end + descLen(r) + r:skip(2) -- ES_ID + local flags = r:u8() + if bit32.band(flags, 0x80) ~= 0 then + r:skip(2) + end + if bit32.band(flags, 0x40) ~= 0 then + r:skip(r:u8()) + end + if bit32.band(flags, 0x20) ~= 0 then + r:skip(2) + end + if r:u8() ~= 4 then + return nil, nil, nil + end + local dlen = descLen(r) + local dstart = r.pos + local oti = r:u8() + r:skip(1 + 3 + 4) -- streamType, bufferSize, maxBitrate + local avg = r:u32be() + local dsi: buffer? = nil + if r.pos < dstart + dlen and r:u8() == 5 then + local n = descLen(r) + if n > 0 and r:need(n) then + dsi = r:bytes(n) + end + end + if r.err then + return oti, nil, nil + end + return oti, dsi, avg +end + +-- the sample entry `e` of a track with handler `handler`: fills the codec facts into t +local function sampleEntry(b: buffer, e: Box.Box, handler: string, t: Track) + local r = reader(b, e) + r:skip(6) + r:skip(2) -- data reference index + local typ = e.type + t.entry = typ + t.codec = CODEC[typ] or typ + local kind = t.kind + local childStart + if kind == "audio" then + local version = r:u16be() + r:skip(2 + 4) -- revision, vendor + local channels = r:u16be() + local bits = r:u16be() + r:skip(4) -- compression id, packet size + local rate = r:u32be() / 65536 + if version == 1 then + r:skip(16) + elseif version == 2 then + r:skip(4) + rate = r:f64be() + channels = r:u32be() + r:skip(4) + bits = r:u32be() + local lpcmFlags = r:u32be() + r:skip(8) + if typ == "lpcm" then + t.pcm = { + bits = bits, + float = bit32.band(lpcmFlags, 1) ~= 0, + little = bit32.band(lpcmFlags, 2) == 0, + } + end + end + t.channels, t.sampleRate, t.bitsPerSample = channels, rate, bits + if not t.pcm and t.codec == "pcm" then + local B: { [string]: number } = { sowt = 16, twos = 16, ["raw "] = 8, in24 = 24, in32 = 32, fl32 = 32, fl64 = 64 } + t.pcm = { + bits = B[typ] or bits, + float = typ == "fl32" or typ == "fl64", + little = typ == "sowt", + } + end + childStart = r.pos + elseif kind == "video" then + r:skip(16) + t.width = r:u16be() + t.height = r:u16be() + r:skip(4 + 4 + 4 + 2 + 32 + 2 + 2) + childStart = r.pos + else + childStart = r.pos + end + if r.err then + t.entryBoxes = {} + return + end + local kids = Box.list(b, childStart, e.stop, typ) + t.entryBoxes = kids + -- QuickTime puts the codec boxes inside 'wave' + local all = table.clone(kids) + local wave = Box.child({ type = "", start = 0, size = 0, data = 0, stop = 0, children = kids } :: any, "wave") + if wave and wave.children then + for _, c in wave.children :: { Box.Box } do + table.insert(all, c) + end + end + local holder = { type = "", start = 0, size = 0, data = 0, stop = 0, children = all } :: any + local esds = Box.child(holder, "esds") + if esds then + local oti, dsi, avg = Demux.esds(b, esds) + t.objectType = oti + if oti and OTI[oti] then + t.codec = OTI[oti] + end + t.config = dsi + if avg and avg > 0 then + t.bitrate = avg + end + end + if typ == "alac" then + local a = Box.child(holder, "alac") + if a then + t.config = payload(b, a, 4) + end + end + for _, name in CONFIG_BOX do + local c = Box.child(holder, name) + if c then + t.config = payload(b, c, if FULL_CONFIG[name] then 4 else 0) + break + end + end +end + +-- media handler / header / sample tables of one trak -> Track | nil, Err +local function track(b: buffer, trak: Box.Box, movieTimescale: number, trex: { [number]: any }, o: Options): (Track?, Err.Err?) + local tkhd = Box.child(trak, "tkhd") + local mdia = Box.child(trak, "mdia") + if not tkhd or not mdia then + return nil, Err.new(Err.CORRUPT, "trak without tkhd / mdia", trak.start) + end + local t: Track = { + id = 0, kind = "data", codec = "", entry = "", handler = "", timescale = 1, duration = 0, mediaDuration = 0, + entryBoxes = {}, skip = 0, delay = 0, sampleCount = 0, offsets = {}, sizes = {}, dts = {}, durations = {}, + } + do + local r = reader(b, tkhd) + local v = r:u8() + r:skip(3) + if v == 1 then + r:skip(16) + t.id = r:u32be() + r:skip(4 + 8) + else + r:skip(8) + t.id = r:u32be() + r:skip(4 + 4) + end + r:skip(8 + 2 + 2 + 2 + 2 + 36) + local w, h = r:u32be() / 65536, r:u32be() / 65536 + if r.err then + return nil, r.err + end + if w > 0 and h > 0 then + t.width, t.height = math.floor(w), math.floor(h) + end + end + local mdhd = Box.child(mdia, "mdhd") + if mdhd then + local r = reader(b, mdhd) + local v = r:u8() + r:skip(3) + if v == 1 then + r:skip(16) + t.timescale = r:u32be() + t.mediaDuration = r:u64be() + else + r:skip(8) + t.timescale = r:u32be() + t.mediaDuration = r:u32be() + end + local lang = r:u16be() + if not r.err and lang ~= 0 and lang ~= 0x7FFF then + t.language = string.char( + 96 + bit32.band(bit32.rshift(lang, 10), 31), + 96 + bit32.band(bit32.rshift(lang, 5), 31), + 96 + bit32.band(lang, 31) + ) + end + if t.timescale == 0 then + t.timescale = 1 + end + end + local hdlr = Box.child(mdia, "hdlr") + if hdlr and hdlr.data + 12 <= hdlr.stop then + t.handler = readstring(b, hdlr.data + 8, 4) + end + t.kind = HANDLER_KIND[t.handler] or "data" + local stbl = Box.path(mdia, "minf/stbl") + if not stbl then + return nil, Err.new(Err.CORRUPT, "track " .. t.id .. " has no sample table", mdia.start) + end + -- sample descriptions + local stsd = Box.child(stbl, "stsd") + if stsd and stsd.data + 8 <= stsd.stop then + local entries = Box.list(b, stsd.data + 8, stsd.stop, "stsd") + if entries[1] then + sampleEntry(b, entries[1], t.handler, t) + end + t.sampleEntries = entries + end + -- edit list + local elst = Box.path(trak, "edts/elst") + if elst then + local r = reader(b, elst) + local v = r:u8() + r:skip(3) + local n = r:u32be() + if n <= (elst.stop - elst.data) // 12 then + local edits = {} + for _ = 1, n do + local dur, mt + if v == 1 then + dur, mt = r:u64be(), r:i64be() + else + dur, mt = r:u32be(), r:i32be() + end + local rate = r:i32be() / 65536 + if r.err then + break + end + table.insert(edits, { duration = dur, mediaTime = mt, rate = rate }) + end + t.edits = edits + local play = 0 + local started = false + for _, ed in edits do + if ed.mediaTime == -1 then + if not started then + t.delay += ed.duration + end + else + if not started then + t.skip = ed.mediaTime + started = true + end + play += ed.duration * t.timescale / math.max(1, movieTimescale) + end + end + if started and play > 0 then + t.playDuration = math.floor(play + 0.5) + end + end + end + -- sample sizes + local maxSamples = o.maxSamples or 2 ^ 25 + local sizes = t.sizes + local count = 0 + local stsz = Box.child(stbl, "stsz") + local stz2 = Box.child(stbl, "stz2") + if stsz then + local r = reader(b, stsz) + r:skip(4) + local fixed = r:u32be() + count = r:u32be() + if r.err then + return nil, r.err + end + if count > maxSamples then + return nil, Err.new(Err.LIMIT, string.format("track %d has %d samples (limit %d)", t.id, count, maxSamples), stsz.start) + end + if fixed ~= 0 then + for i = 1, count do + sizes[i] = fixed + end + else + if count * 4 > r:remaining() then + return nil, Err.new(Err.TRUNCATED, "stsz table runs past its box", stsz.start) + end + for i = 1, count do + sizes[i] = r:u32be() + end + end + elseif stz2 then + local r = reader(b, stz2) + r:skip(4 + 3) + local fieldSize = r:u8() + count = r:u32be() + if r.err then + return nil, r.err + end + if fieldSize ~= 4 and fieldSize ~= 8 and fieldSize ~= 16 then + return nil, Err.new(Err.CORRUPT, "bad stz2 field size " .. fieldSize, stz2.start) + end + if count * fieldSize / 8 > r:remaining() + 1 then + return nil, Err.new(Err.TRUNCATED, "stz2 table runs past its box", stz2.start) + end + for i = 1, count do + if fieldSize == 16 then + sizes[i] = r:u16be() + elseif fieldSize == 8 then + sizes[i] = r:u8() + else + local byte = r:peekU8() + if i % 2 == 1 then + sizes[i] = bit32.rshift(math.max(byte, 0), 4) + else + sizes[i] = bit32.band(math.max(byte, 0), 15) + r:skip(1) + end + end + end + end + -- decode times + local dts, durs = t.dts, t.durations + local stts = Box.child(stbl, "stts") + if stts and count > 0 then + local r = reader(b, stts) + r:skip(4) + local n = r:u32be() + if n * 8 > r:remaining() then + return nil, Err.new(Err.TRUNCATED, "stts table runs past its box", stts.start) + end + local i, time = 1, 0 + for _ = 1, n do + local c, d = r:u32be(), r:u32be() + for _ = 1, c do + if i > count then + break + end + dts[i], durs[i] = time, d + time += d + i += 1 + end + end + -- fewer stts entries than samples: repeat the last duration + local last = if i > 1 then durs[i - 1] else 0 + while i <= count do + dts[i], durs[i] = time, last + time += last + i += 1 + end + else + for i = 1, count do + dts[i], durs[i] = 0, 0 + end + end + -- composition offsets + local ctts = Box.child(stbl, "ctts") + if ctts and count > 0 then + local r = reader(b, ctts) + local v = r:u8() + r:skip(3) + local n = r:u32be() + if n * 8 <= r:remaining() then + local cts = table.create(count, 0) + local i = 1 + for _ = 1, n do + local c = r:u32be() + local off = if v == 1 then r:i32be() else r:u32be() + if v == 0 and off >= 2147483648 then + off -= 4294967296 -- writers put negative offsets in version 0 too + end + for _ = 1, c do + if i > count then + break + end + cts[i] = off + i += 1 + end + end + t.cts = cts + end + end + -- sync samples + local stss = Box.child(stbl, "stss") + if stss then + local r = reader(b, stss) + r:skip(4) + local n = r:u32be() + if n * 4 <= r:remaining() then + local sync = {} + for _ = 1, n do + sync[r:u32be()] = true + end + t.sync = sync + end + end + -- chunk offsets + sample-to-chunk -> sample offsets + local stco = Box.child(stbl, "stco") + local co64 = Box.child(stbl, "co64") + local chunks: { number } = {} + if stco or co64 then + local box = (stco or co64) :: Box.Box + local r = reader(b, box) + r:skip(4) + local n = r:u32be() + local w = if co64 then 8 else 4 + if n * w > r:remaining() then + return nil, Err.new(Err.TRUNCATED, "chunk offset table runs past its box", box.start) + end + for i = 1, n do + chunks[i] = if co64 then r:u64be() else r:u32be() + end + end + local stsc = Box.child(stbl, "stsc") + local offsets = t.offsets + if count > 0 then + if not stsc or #chunks == 0 then + return nil, Err.new(Err.CORRUPT, "track " .. t.id .. " has samples but no stsc / stco", stbl.start) + end + local r = reader(b, stsc) + r:skip(4) + local n = r:u32be() + if n * 12 > r:remaining() then + return nil, Err.new(Err.TRUNCATED, "stsc table runs past its box", stsc.start) + end + local first, per, desc = {}, {}, {} + for k = 1, n do + first[k], per[k], desc[k] = r:u32be(), r:u32be(), r:u32be() + end + local sdi: { number }? = nil + if n > 0 then + for k = 1, n do + if desc[k] ~= desc[1] then + sdi = table.create(count, 1) + end + end + end + local i = 1 + local base = 0 -- added by the caller (the file's offset in the buffer) + for k = 1, n do + local c0 = first[k] + local c1 = if k < n then first[k + 1] - 1 else #chunks + if c0 < 1 then + return nil, Err.new(Err.CORRUPT, "stsc first chunk 0", stsc.start) + end + for c = c0, math.min(c1, #chunks) do + local off = chunks[c] + base + for _ = 1, per[k] do + if i > count then + break + end + offsets[i] = off + if sdi then + sdi[i] = desc[k] + end + off += sizes[i] + i += 1 + end + if i > count then + break + end + end + if i > count then + break + end + end + if i <= count then + return nil, Err.new(Err.CORRUPT, string.format("track %d: the chunks hold %d of %d samples", t.id, i - 1, count), stsc.start) + end + t.sampleDescription = sdi + end + t.sampleCount = count + -- QuickTime PCM: one "sample" per sample frame (constant size, duration 1). Regroup into packets of up to 1024 + -- frames within each chunk (as ffmpeg does), so a packet is a useful amount of audio. + if t.kind == "audio" and count > 1 and not t.cts and not t.sync then + local fixed = sizes[1] + local uniform = fixed > 0 + for i = 1, count do + if sizes[i] ~= fixed or durs[i] ~= 1 then + uniform = false + break + end + end + if uniform then + local no, ns, nd, nu = {}, {}, {}, {} + local i = 1 + while i <= count do + local k = 1 + while k < 1024 and i + k <= count and offsets[i + k] == offsets[i] + k * fixed do + k += 1 + end + table.insert(no, offsets[i]) + table.insert(ns, k * fixed) + table.insert(nd, dts[i]) + table.insert(nu, k) + i += k + end + t.offsets, t.sizes, t.dts, t.durations = no, ns, nd, nu + t.sampleCount = #no + t.frameSize = fixed + t.sampleDescription = nil + end + end + -- fragment defaults + t.trex = trex[t.id] + return t, nil +end + +-- the movie fragments (moof) after the moov: appends their samples to the tracks +local function fragments(b: buffer, fileBase: number, top: { Box.Box }, byId: { [number]: Track }, o: Options): Err.Err? + local maxSamples = o.maxSamples or 2 ^ 25 + for _, moof in top do + if moof.type ~= "moof" then + continue + end + local moofStart = moof.start - fileBase -- file offsets (r.base is added at the end) + local prevEnd = moofStart + for _, traf in Box.childrenOf(moof, "traf") do + local tfhd = Box.child(traf, "tfhd") + if not tfhd then + continue + end + local r = reader(b, tfhd) + r:skip(1) + local flags = r:u24be() + local id = r:u32be() + local t = byId[id] + if r.err or not t then + continue + end + local trex = t.trex or {} + local base + if bit32.band(flags, 0x1) ~= 0 then + base = r:u64be() + elseif bit32.band(flags, 0x20000) ~= 0 then + base = moofStart + else + base = prevEnd + end + if bit32.band(flags, 0x2) ~= 0 then + r:skip(4) + end + local defDur = if bit32.band(flags, 0x8) ~= 0 then r:u32be() else (trex.duration or 0) + local defSize = if bit32.band(flags, 0x10) ~= 0 then r:u32be() else (trex.size or 0) + local defFlags = if bit32.band(flags, 0x20) ~= 0 then r:u32be() else (trex.flags or 0) + if r.err then + return r.err + end + local n0 = t.sampleCount + local time = if n0 > 0 then t.dts[n0] + t.durations[n0] else 0 + local tfdt = Box.child(traf, "tfdt") + if tfdt then + local q = reader(b, tfdt) + local v = q:u8() + q:skip(3) + local bt = if v == 1 then q:u64be() else q:u32be() + if not q.err then + time = bt + end + end + local dataPos = base + for _, trun in Box.childrenOf(traf, "trun") do + local q = reader(b, trun) + local v = q:u8() + local tf = q:u24be() + local n = q:u32be() + if q.err then + return q.err + end + if t.sampleCount + n > maxSamples then + return Err.new(Err.LIMIT, "too many fragment samples", trun.start) + end + if bit32.band(tf, 0x1) ~= 0 then + dataPos = base + q:i32be() + end + local firstFlags = if bit32.band(tf, 0x4) ~= 0 then q:u32be() else nil + local per = 0 + for _, bit in { 0x100, 0x200, 0x400, 0x800 } do + if bit32.band(tf, bit) ~= 0 then + per += 4 + end + end + if n * per > q:remaining() then + return Err.new(Err.TRUNCATED, "trun table runs past its box", trun.start) + end + for k = 1, n do + local dur = if bit32.band(tf, 0x100) ~= 0 then q:u32be() else defDur + local size = if bit32.band(tf, 0x200) ~= 0 then q:u32be() else defSize + local sf = if bit32.band(tf, 0x400) ~= 0 then q:u32be() else (if k == 1 and firstFlags then firstFlags else defFlags) + local cto = 0 + if bit32.band(tf, 0x800) ~= 0 then + cto = if v == 1 then q:i32be() else q:u32be() + end + local i = t.sampleCount + 1 + t.sampleCount = i + t.offsets[i] = dataPos + t.sizes[i] = size + t.dts[i] = time + t.durations[i] = dur + if cto ~= 0 or t.cts then + if not t.cts then + t.cts = table.create(i - 1, 0) + end + (t.cts :: { number })[i] = cto + end + -- sample_is_non_sync_sample (bit 16) + local nonSync = bit32.band(sf, 0x10000) ~= 0 + if nonSync then + if not t.sync then + local s = {} + for j = 1, i - 1 do + s[j] = true + end + t.sync = s + end + elseif t.sync then + (t.sync :: any)[i] = true + end + time += dur + dataPos += size + end + prevEnd = dataPos + end + end + end + return nil +end + +export type Movie = { + brand: string?, + minor: number?, + compatible: { string }, + timescale: number, + duration: number, -- seconds + tracks: { Track }, + boxes: { Box.Box }, + moov: Box.Box?, + fragmented: boolean, +} + +-- parse(r, opts) -> Movie | nil, Err: the box tree, ftyp, mvhd and every track (fragments included) +function Demux.parse(r: Bytes.Reader, opts: Options?): (Movie?, Err.Err?) + local o = opts or {} + local b = r.buf + local top, terr = Box.list(b, r.base, r.limit) + if #top == 0 then + return nil, terr or Err.new(Err.CORRUPT, "no boxes", r.base) + end + local m: Movie = { compatible = {}, timescale = 1000, duration = 0, tracks = {}, boxes = top, fragmented = false } + local ftyp = Box.child({ children = top } :: any, "ftyp") + if ftyp and ftyp.data + 8 <= ftyp.stop then + m.brand = readstring(b, ftyp.data, 4) + m.minor = Box.be32(b, ftyp.data + 4) + local p = ftyp.data + 8 + while p + 4 <= ftyp.stop do + table.insert(m.compatible, readstring(b, p, 4)) + p += 4 + end + end + local moov = Box.child({ children = top } :: any, "moov") + m.moov = moov + if not moov then + return m, nil -- an image file (HEIF / AVIF) or a fragment: no tracks + end + local mvhd = Box.child(moov, "mvhd") + local movieDuration = 0 + if mvhd then + local q = reader(b, mvhd) + local v = q:u8() + q:skip(3) + if v == 1 then + q:skip(16) + m.timescale = q:u32be() + movieDuration = q:u64be() + else + q:skip(8) + m.timescale = q:u32be() + movieDuration = q:u32be() + end + if q.err or m.timescale == 0 then + m.timescale = 1000 + end + end + local trex = {} + local mvex = Box.child(moov, "mvex") + if mvex then + m.fragmented = true + for _, x in Box.childrenOf(mvex, "trex") do + local q = reader(b, x) + q:skip(4) + local id = q:u32be() + q:skip(4) + local d = { duration = q:u32be(), size = q:u32be(), flags = q:u32be() } + if not q.err then + trex[id] = d + end + end + end + local byId = {} + for _, trak in Box.childrenOf(moov, "trak") do + local t, err = track(b, trak, m.timescale, trex, o) + if not t then + return nil, err + end + table.insert(m.tracks, t) + byId[t.id] = t + end + if m.fragmented then + local ferr = fragments(b, r.base, top, byId, o) + if ferr then + return nil, ferr + end + end + -- durations; drop samples outside the buffer (a truncated file) but keep what is there + for _, t in m.tracks do + local n = t.sampleCount + local ticks = t.mediaDuration + if n > 0 then + ticks = math.max(ticks, t.dts[n] + t.durations[n]) + end + t.mediaDuration = ticks + t.duration = ticks / t.timescale + for i = 1, n do + local off = t.offsets[i] + if off < 0 or off + t.sizes[i] > r.limit - r.base then + t.sampleCount = i - 1 + t.truncated = true + break + end + end + -- the tables hold file offsets; make them buffer offsets + local base = r.base + if base ~= 0 then + local offs = t.offsets + for i = 1, t.sampleCount do + offs[i] += base + end + end + end + m.duration = movieDuration / m.timescale + if m.duration == 0 then + for _, t in m.tracks do + m.duration = math.max(m.duration, t.duration) + end + end + return m, nil +end + +return Demux diff --git a/src/Formats/containers/IsoBmff/Meta.luau b/src/Formats/containers/IsoBmff/Meta.luau new file mode 100644 index 0000000..a7c44ca --- /dev/null +++ b/src/Formats/containers/IsoBmff/Meta.luau @@ -0,0 +1,526 @@ +--!strict +-- containers/IsoBmff/Meta: the metadata boxes. HEIF / AVIF items (ISO/IEC 23008-12: pitm, iinf / infe, iloc +-- versions 0 - 2, iref, iprp / ipco / ipma, idat; the common properties ispe / pixi / colr / irot / imir / clap / auxC +-- decoded, codec configurations av1C / hvcC / avcC kept raw) and the iTunes tags (udta / meta / ilst: text, trkn / +-- disk, tmpo / cpil, gnre, covr pictures, '----' freeform), plus the ilst writer used by the muxer. +-- Never throws. +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Box = require("@formats/containers/IsoBmff/Box") + +local readstring = buffer.readstring + +local Meta = {} + +local function reader(b: buffer, box: Box.Box): Bytes.Reader + return Bytes.reader(b, box.data, box.stop - box.data) +end + +local function uint(r: Bytes.Reader, size: number): number + if size == 0 then + return 0 + elseif size == 4 then + return r:u32be() + elseif size == 8 then + return r:u64be() + elseif size == 2 then + return r:u16be() + elseif size == 1 then + return r:u8() + end + r:fail(Err.CORRUPT, "bad iloc field size " .. size) + return 0 +end + +-- ------------------------------------------------------------------------------------------------ HEIF items +export type Property = { type: string, box: Box.Box, [string]: any } +export type Item = { + id: number, + type: string, -- "av01", "hvc1", "grid", "Exif", "mime", ... + name: string, + contentType: string?, + hidden: boolean, + construction: number, -- iloc construction method (0 file offset, 1 idat, 2 item) + baseOffset: number, + extents: { { offset: number, length: number } }, + properties: { Property }, -- in ipma order + essential: { [number]: boolean }, -- by index into properties + refs: { [string]: { number } }, -- iref type -> item ids (dimg, thmb, auxl, cdsc, ...) +} +export type Items = { + primary: number?, + items: { [number]: Item }, + order: { number }, -- item ids in iinf order + idat: Box.Box?, + properties: { Property }, -- ipco, in order +} + +local function property(b: buffer, box: Box.Box): Property + local p: Property = { type = box.type, box = box } + local r = reader(b, box) + local t = box.type + if t == "ispe" then + r:skip(4) + p.width, p.height = r:u32be(), r:u32be() + elseif t == "pixi" then + r:skip(4) + local n = r:u8() + local bits = {} + for i = 1, math.min(n, 16) do + bits[i] = r:u8() + end + p.bits = bits + elseif t == "colr" then + local ct = r:string(4) + p.colourType = ct + if ct == "nclx" then + p.primaries, p.transfer, p.matrix = r:u16be(), r:u16be(), r:u16be() + p.fullRange = bit32.band(r:u8(), 0x80) ~= 0 + elseif ct == "rICC" or ct == "prof" then + p.icc = r:bytes(r:remaining()) + end + elseif t == "irot" then + p.angle = bit32.band(r:u8(), 3) * 90 + elseif t == "imir" then + p.axis = bit32.band(r:u8(), 1) + elseif t == "clap" then + local function frac(): number + local n, d = r:i32be(), r:u32be() + return if d == 0 then 0 else n / d + end + p.width, p.height, p.horizOff, p.vertOff = frac(), frac(), frac(), frac() + elseif t == "auxC" then + r:skip(4) + p.auxType = r:cstring() + else + local n = box.stop - box.data + local cfg = buffer.create(math.max(0, n)) + if n > 0 then + buffer.copy(cfg, 0, b, box.data, n) + end + p.config = cfg + end + return p +end + +-- items(buf, meta) -> Items | nil, Err (meta: a top-level 'meta' box) +function Meta.items(b: buffer, meta: Box.Box): (Items?, Err.Err?) + local out: Items = { items = {}, order = {}, properties = {} } + local pitm = Box.child(meta, "pitm") + if pitm then + local r = reader(b, pitm) + local v = r:u8() + r:skip(3) + out.primary = if v == 0 then r:u16be() else r:u32be() + end + local iinf = Box.child(meta, "iinf") + if iinf then + for _, infe in Box.childrenOf(iinf, "infe") do + local r = reader(b, infe) + local v = r:u8() + local flags = r:u24be() + local it: Item = { + id = 0, type = "", name = "", hidden = bit32.band(flags, 1) ~= 0, construction = 0, baseOffset = 0, + extents = {}, properties = {}, essential = {}, refs = {}, + } + if v >= 2 then + it.id = if v == 2 then r:u16be() else r:u32be() + r:skip(2) + it.type = r:string(4) + it.name = r:cstring() + if it.type == "mime" and r:remaining() > 0 then + it.contentType = r:cstring() + end + else + it.id = r:u16be() + r:skip(2) + it.name = r:cstring() + it.contentType = r:cstring() + it.type = "mime" + end + if r.err and it.id == 0 then + return nil, r.err + end + out.items[it.id] = it + table.insert(out.order, it.id) + end + end + local iloc = Box.child(meta, "iloc") + if iloc then + local r = reader(b, iloc) + local v = r:u8() + r:skip(3) + local a, c = r:u8(), r:u8() + local offSize, lenSize, baseSize = bit32.rshift(a, 4), bit32.band(a, 15), bit32.rshift(c, 4) + local idxSize = if v >= 1 then bit32.band(c, 15) else 0 + local n = if v < 2 then r:u16be() else r:u32be() + if r.err then + return nil, r.err + end + for _ = 1, n do + local id = if v < 2 then r:u16be() else r:u32be() + local method = 0 + if v >= 1 then + method = bit32.band(r:u16be(), 15) + end + r:skip(2) -- data reference index + local base = uint(r, baseSize) + local ne = r:u16be() + if r.err then + return nil, r.err + end + if ne * (offSize + lenSize + idxSize) > r:remaining() then + return nil, Err.new(Err.TRUNCATED, "iloc extents run past the box", iloc.start) + end + local extents = {} + for k = 1, ne do + if idxSize > 0 then + uint(r, idxSize) + end + extents[k] = { offset = base + uint(r, offSize), length = uint(r, lenSize) } + end + if r.err then + return nil, r.err + end + local it = out.items[id] + if not it then + it = { + id = id, type = "", name = "", hidden = false, construction = 0, baseOffset = 0, extents = {}, + properties = {}, essential = {}, refs = {}, + } + out.items[id] = it + table.insert(out.order, id) + end + it.construction, it.baseOffset, it.extents = method, base, extents + end + end + local iref = Box.child(meta, "iref") + if iref then + local v = Box.fullHeader(b, iref) + for _, ref in (iref.children or {}) :: { Box.Box } do + local r = reader(b, ref) + local from = if v == 0 then r:u16be() else r:u32be() + local n = r:u16be() + local to = {} + for k = 1, n do + to[k] = if v == 0 then r:u16be() else r:u32be() + end + local it = out.items[from] + if it and not r.err then + it.refs[ref.type] = to + end + end + end + local ipco = Box.path(meta, "iprp/ipco") + if ipco and ipco.children then + for i, pb in ipco.children :: { Box.Box } do + out.properties[i] = property(b, pb) + end + end + local ipma = Box.path(meta, "iprp/ipma") + if ipma then + local r = reader(b, ipma) + local v = r:u8() + local flags = r:u24be() + local n = r:u32be() + for _ = 1, n do + if r.err then + break + end + local id = if v < 1 then r:u16be() else r:u32be() + local na = r:u8() + local it = out.items[id] + for _ = 1, na do + local idx, ess + if bit32.band(flags, 1) ~= 0 then + local x = r:u16be() + idx, ess = bit32.band(x, 0x7FFF), x >= 0x8000 + else + local x = r:u8() + idx, ess = bit32.band(x, 0x7F), x >= 0x80 + end + local p = out.properties[idx] + if it and p and not r.err then + table.insert(it.properties, p) + if ess then + it.essential[#it.properties] = true + end + end + end + end + end + out.idat = Box.child(meta, "idat") + return out, nil +end + +-- itemData(buf, base, limit, items, id) -> buffer | nil, Err: the item's bytes (extents concatenated); base / limit +-- bound the file in the buffer +function Meta.itemData(b: buffer, base: number, limit: number, items: Items, id: number): (buffer?, Err.Err?) + local it = items.items[id] + if not it then + return nil, Err.new(Err.CORRUPT, "no item " .. id) + end + local origin, stop + if it.construction == 0 then + origin, stop = base, limit + elseif it.construction == 1 then + local idat = items.idat + if not idat then + return nil, Err.new(Err.CORRUPT, "item " .. id .. " is in a missing idat") + end + origin, stop = idat.data, idat.stop + else + return nil, Err.new(Err.UNSUPPORTED, "item construction method " .. it.construction) + end + local total = 0 + for _, e in it.extents do + local len = e.length + if len == 0 then -- the whole rest of the file + len = stop - origin - e.offset + end + if e.offset < 0 or len < 0 or origin + e.offset + len > stop then + return nil, Err.new(Err.TRUNCATED, "item " .. id .. " runs past the end") + end + total += len + end + if total > 2 ^ 30 then + return nil, Err.new(Err.LIMIT, "item " .. id .. " is too big") + end + local out = buffer.create(total) + local p = 0 + for _, e in it.extents do + local len = if e.length == 0 then stop - origin - e.offset else e.length + buffer.copy(out, p, b, origin + e.offset, len) + p += len + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ iTunes tags +-- ilst item -> standard tag name +local TAG: { [string]: string } = { + ["\169nam"] = "title", ["\169ART"] = "artist", aART = "albumartist", ["\169alb"] = "album", ["\169day"] = "date", + ["\169gen"] = "genre", ["\169cmt"] = "comment", ["\169wrt"] = "composer", ["\169too"] = "encoder", + ["\169lyr"] = "lyrics", ["\169grp"] = "grouping", cprt = "copyright", desc = "description", ldes = "longdescription", + sonm = "titlesort", soar = "artistsort", soal = "albumsort", soaa = "albumartistsort", soco = "composersort", + tvsh = "show", ["\169st3"] = "subtitle", ["\169wrk"] = "work", ["\169mvn"] = "movement", purd = "purchasedate", + ["\169pub"] = "publisher", ["\169xyz"] = "location", +} +local TAG_ATOM: { [string]: string } = {} +for atom, name in TAG do + TAG_ATOM[name] = atom +end +Meta.TAG = TAG +Meta.TAG_ATOM = TAG_ATOM + +-- the ID3v1 genres gnre indexes (1-based in gnre) +local GENRES = { + "Blues", "Classic Rock", "Country", "Dance", "Disco", "Funk", "Grunge", "Hip-Hop", "Jazz", "Metal", "New Age", + "Oldies", "Other", "Pop", "R&B", "Rap", "Reggae", "Rock", "Techno", "Industrial", "Alternative", "Ska", + "Death Metal", "Pranks", "Soundtrack", "Euro-Techno", "Ambient", "Trip-Hop", "Vocal", "Jazz+Funk", "Fusion", + "Trance", "Classical", "Instrumental", "Acid", "House", "Game", "Sound Clip", "Gospel", "Noise", "AlternRock", + "Bass", "Soul", "Punk", "Space", "Meditative", "Instrumental Pop", "Instrumental Rock", "Ethnic", "Gothic", + "Darkwave", "Techno-Industrial", "Electronic", "Pop-Folk", "Eurodance", "Dream", "Southern Rock", "Comedy", "Cult", + "Gangsta", "Top 40", "Christian Rap", "Pop/Funk", "Jungle", "Native American", "Cabaret", "New Wave", + "Psychadelic", "Rave", "Showtunes", "Trailer", "Lo-Fi", "Tribal", "Acid Punk", "Acid Jazz", "Polka", "Retro", + "Musical", "Rock & Roll", "Hard Rock", +} + +export type Picture = { mime: string, data: buffer } + +-- tags(buf, ilst) -> Tags, { Picture } +function Meta.tags(b: buffer, ilst: Box.Box?): ({ [string]: string }, { Picture }) + local tags: { [string]: string } = {} + local pics: { Picture } = {} + if not ilst or not ilst.children then + return tags, pics + end + for _, item in ilst.children :: { Box.Box } do + local typ = item.type + local freeName: string? = nil + if typ == "----" then + local nm = Box.child(item, "name") + if nm and nm.data + 4 <= nm.stop then + freeName = readstring(b, nm.data + 4, nm.stop - nm.data - 4) + end + end + for _, d in Box.childrenOf(item, "data") do + if d.data + 8 > d.stop then + continue + end + local kind = bit32.band(Box.be32(b, d.data), 0xFFFFFF) + local p, n = d.data + 8, d.stop - d.data - 8 + if typ == "trkn" or typ == "disk" then + if n >= 6 then + local num = Box.be32(b, p) % 65536 + local total = Box.be32(b, p + 2) % 65536 + local key = if typ == "trkn" then "track" else "disc" + if num > 0 then + tags[key] = tostring(num) + end + if total > 0 then + tags[key .. "total"] = tostring(total) + end + end + elseif typ == "gnre" then + if n >= 2 then + local g = GENRES[Box.be32(b, p - 2) % 65536] + if g and not tags.genre then + tags.genre = g + end + end + elseif typ == "tmpo" then + if n >= 2 then + tags.bpm = tostring(Box.be32(b, p - 2) % 65536) + end + elseif typ == "cpil" or typ == "pgap" then + if n >= 1 then + tags[if typ == "cpil" then "compilation" else "gapless"] = tostring(buffer.readu8(b, p)) + end + elseif typ == "covr" then + local mime = if kind == 14 then "image/png" elseif kind == 27 then "image/bmp" else "image/jpeg" + local data = buffer.create(n) + buffer.copy(data, 0, b, p, n) + table.insert(pics, { mime = mime, data = data }) + elseif kind == 1 or kind == 0 then + local s = readstring(b, p, n) + local key = freeName or TAG[typ] or typ + if typ == "\169gen" or not tags[key] then + tags[key] = s + end + end + end + end + return tags, pics +end + +-- ------------------------------------------------------------------------------------------------ ilst writer +local function box(w: Bytes.Writer, typ: string, body: (Bytes.Writer) -> ()) + local start = w:tell() + w:u32be(0) + w:string(typ) + body(w) + w:setU32be(start, w:tell() - start) +end +Meta.box = box + +local function dataBox(w: Bytes.Writer, kind: number, value: string | buffer) + box(w, "data", function() + w:u32be(kind) + w:u32be(0) + if type(value) == "string" then + w:string(value) + else + w:bytes(value) + end + end) +end + +local function num(s: string?): number + local v = tonumber(s or "") + if not v then + return 0 + end + return math.clamp(math.floor(v), 0, 65535) +end + +-- writeIlst(w, tags, pictures?): an ilst box with the tags (standard names -> iTunes atoms; unknown names -> '----' +-- freeform com.apple.iTunes items) and cover pictures +function Meta.writeIlst(w: Bytes.Writer, tags: { [string]: string }, pictures: { Picture }?) + box(w, "ilst", function() + local keys = {} + for k in tags do + table.insert(keys, k) + end + table.sort(keys) + local done: { [string]: boolean } = {} + for _, k in keys do + local v = tags[k] + if type(v) ~= "string" or done[k] then + continue + end + if k == "track" or k == "tracktotal" or k == "disc" or k == "disctotal" then + local base = if k == "track" or k == "tracktotal" then "track" else "disc" + if done[base] then + continue + end + done[base] = true + local atom = if base == "track" then "trkn" else "disk" + local n, total = num(tags[base]), num(tags[base .. "total"]) + box(w, atom, function() + box(w, "data", function() + w:u32be(0) + w:u32be(0) + w:u16be(0) + w:u16be(n) + w:u16be(total) + if atom == "trkn" then + w:u16be(0) + end + end) + end) + elseif k == "bpm" then + box(w, "tmpo", function() + box(w, "data", function() + w:u32be(21) + w:u32be(0) + w:u16be(num(v)) + end) + end) + elseif k == "compilation" or k == "gapless" then + box(w, if k == "compilation" then "cpil" else "pgap", function() + box(w, "data", function() + w:u32be(21) + w:u32be(0) + w:u8(if num(v) ~= 0 then 1 else 0) + end) + end) + elseif TAG_ATOM[k] then + box(w, TAG_ATOM[k], function() + dataBox(w, 1, v) + end) + else + box(w, "----", function() + box(w, "mean", function() + w:u32be(0) + w:string("com.apple.iTunes") + end) + box(w, "name", function() + w:u32be(0) + w:string(k) + end) + dataBox(w, 1, v) + end) + end + done[k] = true + end + if pictures and #pictures > 0 then + box(w, "covr", function() + for _, p in pictures do + dataBox(w, if p.mime == "image/png" then 14 elseif p.mime == "image/bmp" then 27 else 13, p.data) + end + end) + end + end) +end + +-- writeUdta(w, tags, pictures?): udta / meta (hdlr mdir) / ilst +function Meta.writeUdta(w: Bytes.Writer, tags: { [string]: string }, pictures: { Picture }?) + box(w, "udta", function() + box(w, "meta", function() + w:u32be(0) + box(w, "hdlr", function() + w:u32be(0) + w:u32be(0) + w:string("mdir") + w:string("appl") + w:u32be(0) + w:u32be(0) + w:u8(0) + end) + Meta.writeIlst(w, tags, pictures) + end) + end) +end + +return Meta diff --git a/src/Formats/containers/IsoBmff/Mux.luau b/src/Formats/containers/IsoBmff/Mux.luau new file mode 100644 index 0000000..d268c39 --- /dev/null +++ b/src/Formats/containers/IsoBmff/Mux.luau @@ -0,0 +1,519 @@ +--!strict +-- containers/IsoBmff/Mux: writes a progressive (non-fragmented) ISO BMFF / MP4 / M4A file: ftyp, moov (mvhd, one trak +-- per track with tkhd / edts / mdia / mdhd / hdlr / minf / [sv]mhd / dinf / stbl), the samples interleaved in chunks +-- in one mdat, and udta / meta / ilst tags. moov goes first ("fast start"); co64 replaces stco past 4 GB. Sample +-- entries: audio (mp4a + esds, alac, Opus + dOps, fLaC + dfLa, ...) and video (avc1 / hvc1 / av01 / vp09 / ... + +-- their configuration box), plus any raw child boxes. Never throws: bad specs return nil, Err.ARG. +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Meta = require("@formats/containers/IsoBmff/Meta") + +local Mux = {} + +export type MuxTrack = { + kind: "audio" | "video" | "subtitle" | "data", + entry: string, -- sample entry fourcc: "alac", "mp4a", "Opus", "fLaC", "avc1", "hvc1", "av01", "vp09", ... + timescale: number, -- ticks per second (audio: the sample rate) + samples: { buffer }?, -- one buffer per sample, or + data: buffer?, -- the samples back to back, with + sizes: { number }?, -- their sizes + durations: { number } | number, -- ticks per sample (or one constant) + cts: { number }?, -- composition offsets (video with B-frames) + sync: { [number]: boolean }?, -- sync samples (nil: all) + sampleRate: number?, + channels: number?, + bitsPerSample: number?, -- default 16 + width: number?, + height: number?, + config: buffer?, -- the codec configuration, written as the entry's configuration box + configBox: string?, -- its box type (default by entry: esds, alac, dOps, dfLa, avcC, hvcC, av1C, vpcC) + objectType: number?, -- esds objectTypeIndication (default 0x40, AAC) + bitrate: number?, -- esds average bitrate + boxes: { { type: string, data: buffer } }?, -- extra sample entry child boxes (raw payloads) + language: string?, -- ISO 639-2, default "und" + name: string?, -- hdlr name + skip: number?, -- media ticks to skip at the start (edit list media time: AAC priming) + playDuration: number?, -- media ticks to play (edit list) +} +export type MuxSpec = { + brand: string?, -- default "isom" + minor: number?, + compatible: { string }?, + timescale: number?, -- movie timescale, default 1000 + tracks: { MuxTrack }, + tags: { [string]: string }?, + pictures: { Meta.Picture }?, + chunkDuration: number?, -- seconds of samples per chunk, default 1 +} + +local DEFAULT_CONFIG_BOX: { [string]: string } = { + mp4a = "esds", mp4v = "esds", alac = "alac", Opus = "dOps", fLaC = "dfLa", avc1 = "avcC", avc3 = "avcC", + hvc1 = "hvcC", hev1 = "hvcC", av01 = "av1C", vp08 = "vpcC", vp09 = "vpcC", ["ac-3"] = "dac3", ["ec-3"] = "dec3", +} +local FULL_BOX: { [string]: boolean } = { alac = true, dfLa = true, vpcC = true } +local HANDLER = { audio = "soun", video = "vide", subtitle = "sbtl", data = "meta" } + +local box = Meta.box + +local function lang(s: string?): number + local l = s or "und" + if #l ~= 3 then + l = "und" + end + local v = 0 + for i = 1, 3 do + v = v * 32 + bit32.band(string.byte(l, i) - 96, 31) + end + return v +end + +local function descriptor(w: Bytes.Writer, tag: number, body: (Bytes.Writer) -> ()) + local inner = Bytes.writer(64) + body(inner) + local n = inner:tell() + w:u8(tag) + -- 4-byte expandable length (the common iTunes / ffmpeg form) + w:u8(0x80 + bit32.band(bit32.rshift(n, 21), 127)) + w:u8(0x80 + bit32.band(bit32.rshift(n, 14), 127)) + w:u8(0x80 + bit32.band(bit32.rshift(n, 7), 127)) + w:u8(bit32.band(n, 127)) + w:bytes(inner.buf, 0, n) +end + +local function esds(w: Bytes.Writer, t: MuxTrack) + box(w, "esds", function() + w:u32be(0) + descriptor(w, 3, function(d) + d:u16be(0) -- ES_ID + d:u8(0) + descriptor(d, 4, function(c) + c:u8(t.objectType or 0x40) + c:u8(if t.kind == "video" then 0x11 else 0x15) -- streamType << 2 | upStream 0 | reserved 1 + c:u24be(0) + c:u32be(t.bitrate or 0) + c:u32be(t.bitrate or 0) + if t.config and buffer.len(t.config) > 0 then -- (MJPEG / MP3 have no decoder-specific info) + descriptor(c, 5, function(s) + s:bytes(t.config :: buffer) + end) + end + end) + descriptor(d, 6, function(s) + s:u8(2) + end) + end) + end) +end + +local function sampleEntry(w: Bytes.Writer, t: MuxTrack) + box(w, t.entry, function() + w:fill(0, 6) + w:u16be(1) -- data reference index + if t.kind == "audio" then + w:u16be(0) -- version + w:u16be(0) + w:u32be(0) + w:u16be(t.channels or 2) + w:u16be(t.bitsPerSample or 16) + w:u16be(0) + w:u16be(0) + local sr = t.sampleRate or t.timescale + w:u32be(if sr < 65536 then sr * 65536 else 0) + elseif t.kind == "video" then + w:fill(0, 16) + w:u16be(t.width or 0) + w:u16be(t.height or 0) + w:u32be(0x00480000) + w:u32be(0x00480000) + w:u32be(0) + w:u16be(1) -- frame count + w:fill(0, 32) -- compressor name + w:u16be(0x18) + w:i16be(-1) + end + local cb = t.configBox or DEFAULT_CONFIG_BOX[t.entry] + if t.config and cb then + if cb == "esds" then + esds(w, t) + else + box(w, cb, function() + if FULL_BOX[cb] then + w:u32be(0) + end + w:bytes(t.config :: buffer) + end) + end + end + for _, x in t.boxes or {} do + box(w, x.type, function() + w:bytes(x.data) + end) + end + end) +end + +type Chunk = { track: number, first: number, count: number, time: number, offset: number } + +-- runs of equal values: { { count, value } } +local function runs(n: number, value: (number) -> number): { { number } } + local out = {} + for i = 1, n do + local v = value(i) + local last = out[#out] + if last and last[2] == v then + last[1] += 1 + else + table.insert(out, { 1, v }) + end + end + return out +end + +type Prepared = { + t: MuxTrack, + n: number, + sizes: { number }, + dur: (number) -> number, + total: number, -- media ticks + chunks: { Chunk }, + sample: (number) -> (buffer, number), -- buffer, offset +} + +local function moov(w: Bytes.Writer, spec: MuxSpec, prep: { Prepared }, co64: boolean) + local mts = spec.timescale or 1000 + local function toMovie(p: Prepared, ticks: number): number + return math.floor(ticks * mts / p.t.timescale + 0.5) + end + local movieDur = 0 + for _, p in prep do + local play = p.t.playDuration or (p.total - (p.t.skip or 0)) + movieDur = math.max(movieDur, toMovie(p, play)) + end + box(w, "moov", function() + box(w, "mvhd", function() + w:u32be(0) + w:u32be(0) + w:u32be(0) + w:u32be(mts) + w:u32be(movieDur) + w:u32be(0x00010000) + w:u16be(0x0100) + w:fill(0, 10) + for _, v in { 0x00010000, 0, 0, 0, 0x00010000, 0, 0, 0, 0x40000000 } do + w:u32be(v) + end + w:fill(0, 24) + w:u32be(#prep + 1) + end) + for id, p in prep do + local t = p.t + local play = t.playDuration or (p.total - (t.skip or 0)) + box(w, "trak", function() + box(w, "tkhd", function() + w:u32be(3) -- enabled, in movie + w:u32be(0) + w:u32be(0) + w:u32be(id) + w:u32be(0) + w:u32be(toMovie(p, play)) + w:fill(0, 8) + w:u16be(0) + w:u16be(0) + w:u16be(if t.kind == "audio" then 0x0100 else 0) + w:u16be(0) + for _, v in { 0x00010000, 0, 0, 0, 0x00010000, 0, 0, 0, 0x40000000 } do + w:u32be(v) + end + w:u32be((t.width or 0) * 65536) + w:u32be((t.height or 0) * 65536) + end) + if t.skip or t.playDuration then + box(w, "edts", function() + box(w, "elst", function() + w:u32be(0) + w:u32be(1) + w:u32be(toMovie(p, play)) + w:u32be(t.skip or 0) + w:u32be(0x00010000) + end) + end) + end + box(w, "mdia", function() + box(w, "mdhd", function() + w:u32be(0) + w:u32be(0) + w:u32be(0) + w:u32be(t.timescale) + w:u32be(p.total) + w:u16be(lang(t.language)) + w:u16be(0) + end) + box(w, "hdlr", function() + w:u32be(0) + w:u32be(0) + w:string(HANDLER[t.kind] or "meta") + w:fill(0, 12) + w:cstring(t.name or (if t.kind == "audio" then "SoundHandler" elseif t.kind == "video" then "VideoHandler" else "DataHandler")) + end) + box(w, "minf", function() + if t.kind == "audio" then + box(w, "smhd", function() + w:u32be(0) + w:u32be(0) + end) + elseif t.kind == "video" then + box(w, "vmhd", function() + w:u32be(1) + w:fill(0, 8) + end) + else + box(w, "nmhd", function() + w:u32be(0) + end) + end + box(w, "dinf", function() + box(w, "dref", function() + w:u32be(0) + w:u32be(1) + box(w, "url ", function() + w:u32be(1) -- self-contained + end) + end) + end) + box(w, "stbl", function() + box(w, "stsd", function() + w:u32be(0) + w:u32be(1) + sampleEntry(w, t) + end) + local stts = runs(p.n, p.dur) + box(w, "stts", function() + w:u32be(0) + w:u32be(#stts) + for _, r in stts do + w:u32be(r[1]) + w:u32be(r[2]) + end + end) + local cts = t.cts + if cts then + local cr = runs(p.n, function(i) + return cts[i] or 0 + end) + box(w, "ctts", function() + w:u32be(0x01000000) -- version 1: signed offsets + w:u32be(#cr) + for _, r in cr do + w:u32be(r[1]) + w:i32be(r[2]) + end + end) + end + local sync = t.sync + if sync then + local list = {} + for i = 1, p.n do + if sync[i] then + table.insert(list, i) + end + end + box(w, "stss", function() + w:u32be(0) + w:u32be(#list) + for _, i in list do + w:u32be(i) + end + end) + end + local stsc = runs(#p.chunks, function(i) + return p.chunks[i].count + end) + box(w, "stsc", function() + w:u32be(0) + w:u32be(#stsc) + local c = 1 + for _, r in stsc do + w:u32be(c) + w:u32be(r[2]) + w:u32be(1) + c += r[1] + end + end) + box(w, "stsz", function() + w:u32be(0) + local fixed = p.sizes[1] or 0 + for i = 2, p.n do + if p.sizes[i] ~= fixed then + fixed = -1 + break + end + end + if fixed >= 0 and p.n > 0 then + w:u32be(fixed) + w:u32be(p.n) + else + w:u32be(0) + w:u32be(p.n) + for i = 1, p.n do + w:u32be(p.sizes[i]) + end + end + end) + box(w, if co64 then "co64" else "stco", function() + w:u32be(0) + w:u32be(#p.chunks) + for _, c in p.chunks do + if co64 then + w:u64be(c.offset) + else + w:u32be(c.offset) + end + end + end) + end) + end) + end) + end) + end + if spec.tags and next(spec.tags) or spec.pictures and #spec.pictures > 0 then + Meta.writeUdta(w, spec.tags or {}, spec.pictures) + end + end) +end + +-- mux(spec) -> buffer | nil, Err +function Mux.mux(spec: MuxSpec): (buffer?, Err.Err?) + if type(spec) ~= "table" or type(spec.tracks) ~= "table" or #spec.tracks == 0 then + return nil, Err.new(Err.ARG, "mux: expected { tracks = { ... } }") + end + local prep: { Prepared } = {} + local all: { Chunk } = {} + for k, t in spec.tracks do + if type(t) ~= "table" or type(t.entry) ~= "string" or #t.entry ~= 4 or type(t.timescale) ~= "number" or t.timescale <= 0 then + return nil, Err.new(Err.ARG, "mux: track " .. k .. " needs a 4-character entry and a timescale") + end + if not HANDLER[t.kind] then + return nil, Err.new(Err.ARG, "mux: track " .. k .. ": bad kind " .. tostring(t.kind)) + end + local n, sizes, sample + if t.samples then + local list = t.samples + n = #list + sizes = table.create(n, 0) + for i = 1, n do + if type(list[i]) ~= "buffer" then + return nil, Err.new(Err.ARG, "mux: track " .. k .. ": sample " .. i .. " is not a buffer") + end + sizes[i] = buffer.len(list[i]) + end + sample = function(i: number): (buffer, number) + return list[i], 0 + end + elseif t.data and t.sizes then + n = #t.sizes + sizes = t.sizes + local starts = table.create(n, 0) + local o = 0 + for i = 1, n do + starts[i] = o + o += sizes[i] + end + if o > buffer.len(t.data) then + return nil, Err.new(Err.ARG, "mux: track " .. k .. ": sizes exceed the data") + end + local data = t.data + sample = function(i: number): (buffer, number) + return data, starts[i] + end + else + return nil, Err.new(Err.ARG, "mux: track " .. k .. " needs samples or data + sizes") + end + local durs = t.durations + local dur + if type(durs) == "number" then + dur = function(_: number): number + return durs + end + elseif type(durs) == "table" then + dur = function(i: number): number + return durs[i] or 0 + end + else + return nil, Err.new(Err.ARG, "mux: track " .. k .. " needs durations") + end + local total = 0 + local chunks: { Chunk } = {} + local per = (spec.chunkDuration or 1) * t.timescale + local cur: Chunk? = nil + for i = 1, n do + if not cur or total - cur.time >= per then + cur = { track = k, first = i, count = 0, time = total, offset = 0 } + table.insert(chunks, cur :: Chunk) + table.insert(all, cur :: Chunk) + end + (cur :: Chunk).count += 1 + total += dur(i) + end + prep[k] = { t = t, n = n, sizes = sizes, dur = dur, total = total, chunks = chunks, sample = sample } + end + -- interleave the chunks by time + table.sort(all, function(a: Chunk, b: Chunk): boolean + local ta = a.time / prep[a.track].t.timescale + local tb = b.time / prep[b.track].t.timescale + if ta ~= tb then + return ta < tb + end + if a.track ~= b.track then + return a.track < b.track + end + return a.first < b.first + end) + local mdatSize = 0 + for _, c in all do + local p = prep[c.track] + for i = c.first, c.first + c.count - 1 do + mdatSize += p.sizes[i] + end + end + local co64 = mdatSize > 4294967295 - 2 ^ 24 + -- ftyp + local w = Bytes.writer(mdatSize + 4096) + box(w, "ftyp", function() + w:string(spec.brand or "isom") + w:u32be(spec.minor or 0x200) + for _, c in spec.compatible or { spec.brand or "isom", "iso2", "mp41" } do + w:string(string.sub(c .. " ", 1, 4)) + end + end) + -- moov twice: the first pass measures it, the second has the real chunk offsets + local probe = Bytes.writer(4096) + moov(probe, spec, prep, co64) + local mdatHeader = if mdatSize + 8 > 4294967295 then 16 else 8 + local o = w:tell() + probe:tell() + mdatHeader + for _, c in all do + c.offset = o + local p = prep[c.track] + for i = c.first, c.first + c.count - 1 do + o += p.sizes[i] + end + end + moov(w, spec, prep, co64) + if mdatHeader == 16 then + w:u32be(1) + w:string("mdat") + w:u64be(mdatSize + 16) + else + w:u32be(mdatSize + 8) + w:string("mdat") + end + for _, c in all do + local p = prep[c.track] + for i = c.first, c.first + c.count - 1 do + local b, off = p.sample(i) + w:bytes(b, off, p.sizes[i]) + end + end + return w:finish(), nil +end + +return Mux diff --git a/src/Formats/containers/IsoBmff/init.luau b/src/Formats/containers/IsoBmff/init.luau new file mode 100644 index 0000000..dab62b9 --- /dev/null +++ b/src/Formats/containers/IsoBmff/init.luau @@ -0,0 +1,188 @@ +--!strict +-- containers/IsoBmff: ISO base media file format (ISO/IEC 14496-12) and its relatives: MP4 / M4A / M4V / MOV (QuickTime) +-- / 3GP, fragmented MP4 (moof), HEIF / AVIF items (ISO/IEC 23008-12), iTunes tags. A container (layer 2): m4a, mp4, +-- mov, heif, avif build on it. Written from the specifications; no third-party code. +-- +-- local IsoBmff = require("@formats/containers/IsoBmff") +-- local movie, err = IsoBmff.parse(r) -- ftyp brand, tracks (Demux.Track: codec, config, sample tables) +-- local dmx = IsoBmff.demux(r) -- Types.Demuxer: tracks, duration, packets(trackId?), seek(s) +-- local tags, pictures = IsoBmff.tags(r, movie) -- moov/udta/meta/ilst (or a top-level meta) +-- local items = IsoBmff.items(r, movie) -- HEIF / AVIF: primary item, items, properties, refs +-- local data = IsoBmff.itemData(r, items, id) -- an item's bytes +-- local file = IsoBmff.mux({ brand = "M4A ", tracks = { { kind = "audio", entry = "alac", ... } }, tags = ... }) +-- +-- Sample offsets in tracks are absolute offsets into r.buf (r may cover part of a bigger buffer). Supports: 32 / 64-bit +-- boxes, stsz / stz2, stco / co64, ctts v0 / v1, stss, elst v0 / v1, QuickTime sound descriptions v1 / v2 and 'wave', +-- fragments with trex defaults / tfdt / data offsets. Not supported: external data references (dref urls), +-- encrypted tracks (sinf / senc are left to the caller), fragmented writing. Never throws. +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Box = require("@formats/containers/IsoBmff/Box") +local Demux = require("@formats/containers/IsoBmff/Demux") +local Meta = require("@formats/containers/IsoBmff/Meta") +local Mux = require("@formats/containers/IsoBmff/Mux") + +local IsoBmff = {} +IsoBmff.Box = Box +IsoBmff.Demux = Demux +IsoBmff.Meta = Meta + +export type Track = Demux.Track +export type Movie = Demux.Movie +export type Items = Meta.Items +export type Item = Meta.Item +export type MuxSpec = Mux.MuxSpec +export type MuxTrack = Mux.MuxTrack +export type Picture = Meta.Picture + +local TOP: { [string]: boolean } = { + ftyp = true, moov = true, mdat = true, free = true, skip = true, wide = true, pnot = true, moof = true, + styp = true, sidx = true, meta = true, uuid = true, PICT = true, +} + +-- sniff(r) -> brand ("M4A ", "isom", "qt ", "avif", "heic", ...) or "" when the file starts with another top-level box, +-- nil when it is not an ISO BMFF file +function IsoBmff.sniff(r: Bytes.Reader): string? + local head = r:peek(12) + if #head < 8 then + return nil + end + local typ = string.sub(head, 5, 8) + if typ == "ftyp" then + return if #head >= 12 then string.sub(head, 9, 12) else "" + end + if TOP[typ] then + local size = string.byte(head, 1) * 16777216 + string.byte(head, 2) * 65536 + string.byte(head, 3) * 256 + string.byte(head, 4) + if size == 1 or size == 0 or size >= 8 then + return "" + end + end + return nil +end + +-- parse(r, opts?) -> Movie | nil, Err +function IsoBmff.parse(r: Bytes.Reader, opts: Demux.Options?): (Movie?, Err.Err?) + return Demux.parse(r, opts) +end + +-- tags(r, movie) -> Tags, { Picture }: iTunes tags from moov/udta/meta/ilst (or moov/meta/ilst, or a top-level meta) +function IsoBmff.tags(r: Bytes.Reader, movie: Movie): ({ [string]: string }, { Picture }) + local ilst = Box.path(movie.boxes, "moov/udta/meta/ilst") or Box.path(movie.boxes, "moov/meta/ilst") or Box.path(movie.boxes, "meta/ilst") + return Meta.tags(r.buf, ilst) +end + +-- items(r, movie) -> Items | nil, Err (the top-level meta box of a HEIF / AVIF file) +function IsoBmff.items(r: Bytes.Reader, movie: Movie): (Items?, Err.Err?) + local meta = Box.path(movie.boxes, "meta") + if not meta then + return nil, Err.new(Err.CORRUPT, "no top-level meta box") + end + return Meta.items(r.buf, meta) +end + +-- itemData(r, items, id) -> buffer | nil, Err +function IsoBmff.itemData(r: Bytes.Reader, items: Items, id: number): (buffer?, Err.Err?) + return Meta.itemData(r.buf, r.base, r.limit, items, id) +end + +-- sample(r, track, i) -> a copy of sample i (1-based) +function IsoBmff.sample(r: Bytes.Reader, t: Track, i: number): buffer? + if i < 1 or i > t.sampleCount then + return nil + end + local n = t.sizes[i] + local out = buffer.create(n) + buffer.copy(out, 0, r.buf, t.offsets[i], n) + return out +end + +-- demux(r, opts?) -> Types.Demuxer (tracks, duration, packets(trackId?), seek(seconds)) | nil, Err. Packets carry pts / +-- dts / duration in their track's timescale ticks and a copy of the sample bytes. +function IsoBmff.demux(r: Bytes.Reader, opts: Demux.Options?): (any, Err.Err?) + local movie, err = Demux.parse(r, opts) + if not movie then + return nil, err + end + local cursor: { [number]: number } = {} + local byId: { [number]: Track } = {} + for _, t in movie.tracks do + cursor[t.id] = 1 + byId[t.id] = t + end + local dmx = { tracks = movie.tracks, duration = movie.duration, movie = movie } + local function packet(t: Track, i: number): any + local dts = t.dts[i] + local cts = t.cts + return { + track = t.id, + dts = dts, + pts = dts + (if cts then cts[i] or 0 else 0), + duration = t.durations[i], + keyframe = t.sync == nil or (t.sync :: any)[i] == true, + data = IsoBmff.sample(r, t, i), + index = i, + } + end + function dmx.packets(_self: any, trackId: number?): () -> any + return function(): any + if trackId then + local t = byId[trackId] + if not t then + return nil + end + local i = cursor[trackId] + if i > t.sampleCount then + return nil + end + cursor[trackId] = i + 1 + return packet(t, i) + end + -- all tracks in file order + local best: Track? = nil + local bestOff = math.huge + for _, t in movie.tracks do + local i = cursor[t.id] + if i <= t.sampleCount and t.offsets[i] < bestOff then + best, bestOff = t, t.offsets[i] + end + end + if not best then + return nil + end + local i = cursor[best.id] + cursor[best.id] = i + 1 + return packet(best, i) + end + end + -- seek(seconds): every track to its last sync sample at or before the time + function dmx.seek(_self: any, seconds: number) + for _, t in movie.tracks do + local target = seconds * t.timescale + local lo, hi = 1, t.sampleCount + local found = 1 + while lo <= hi do + local mid = (lo + hi) // 2 + if t.dts[mid] <= target then + found = mid + lo = mid + 1 + else + hi = mid - 1 + end + end + if t.sync then + while found > 1 and not (t.sync :: any)[found] do + found -= 1 + end + end + cursor[t.id] = found + end + end + return dmx, nil +end + +-- mux(spec) -> buffer | nil, Err (see containers/IsoBmff/Mux) +function IsoBmff.mux(spec: MuxSpec): (buffer?, Err.Err?) + return Mux.mux(spec) +end + +return IsoBmff diff --git a/src/Formats/containers/MpegEs.luau b/src/Formats/containers/MpegEs.luau new file mode 100644 index 0000000..f84a0bf --- /dev/null +++ b/src/Formats/containers/MpegEs.luau @@ -0,0 +1,145 @@ +--!strict +-- containers/MpegEs: helpers over MPEG video elementary streams for the MPEG-TS / PS demuxers. New in formats-luau. +-- Start-code scanning, MPEG-1 / MPEG-2 video access units (a picture with the sequence / GOP headers before it, +-- picture type and temporal reference, the sequence's frame rate and size, MPEG-2 detection by its sequence +-- extension) and H.264 Annex B keyframes (an IDR slice, or a recovery-point SEI). Interpreted; never throws. +local readu8 = buffer.readu8 + +local MpegEs = {} + +-- next start code (00 00 01 xx) at or after p, before limit: position of the 00 00 01 | nil +function MpegEs.findStart(b: buffer, p: number, limit: number): number? + local i = p + while i + 3 <= limit do + local c = readu8(b, i + 2) + if c > 1 then + i += 3 + elseif c == 1 then + if readu8(b, i) == 0 and readu8(b, i + 1) == 0 then + return i + end + i += 3 + else -- c == 0: the start code may begin at i + 1 or i + 2 + i += 1 + end + end + return nil +end + +local FRAME_RATES = { 24000 / 1001, 24, 25, 30000 / 1001, 30, 50, 60000 / 1001, 60 } + +export type Picture = { + offset: number, -- start of the access unit (its first header's start code) + size: number, + type: number, -- 1 I, 2 P, 3 B, 4 D (0 unknown) + temporal: number, -- temporal_reference + gop: boolean, -- a GOP header precedes the picture + sequence: boolean, -- a sequence header precedes the picture +} +export type Info = { width: number, height: number, frameRate: number, mpeg2: boolean } + +-- info(b, off, limit) -> the first sequence header's facts | nil +function MpegEs.info(b: buffer, off: number, limit: number): Info? + local p = MpegEs.findStart(b, off, limit) + local info: Info? = nil + local count = 0 + while p and count < 64 do + count += 1 + local code = if p + 3 < limit then readu8(b, p + 3) else -1 + if code == 0xB3 and p + 11 < limit and not info then + local w = readu8(b, p + 4) * 16 + readu8(b, p + 5) // 16 + local h = (readu8(b, p + 5) % 16) * 256 + readu8(b, p + 6) + local fr = readu8(b, p + 7) % 16 + info = { width = w, height = h, frameRate = FRAME_RATES[fr] or 0, mpeg2 = false } + elseif code == 0xB5 and info then + info.mpeg2 = true + return info + elseif code == 0x00 and info then + return info + end + p = MpegEs.findStart(b, p + 4, limit) + end + return info +end + +-- pictureType(b, off, limit) -> the type (1 I, 2 P, 3 B) and temporal reference of the first picture header | 0 +function MpegEs.pictureType(b: buffer, off: number, limit: number): (number, number) + local p = MpegEs.findStart(b, off, limit) + local count = 0 + while p and count < 32 do + count += 1 + if p + 5 < limit and readu8(b, p + 3) == 0x00 then + local x = readu8(b, p + 4) * 256 + readu8(b, p + 5) + return (x // 8) % 8, x // 64 + end + p = MpegEs.findStart(b, p + 4, limit) + end + return 0, 0 +end + +-- pictures(b, off, limit) -> access units of an MPEG-1 / 2 video elementary stream: each picture starts at its +-- sequence / GOP header when one precedes it and runs to the next unit's start +function MpegEs.pictures(b: buffer, off: number, limit: number): { Picture } + local out: { Picture } = {} + local unitStart: number? = nil + local seq, gop = false, false + local cur: Picture? = nil + local p = MpegEs.findStart(b, off, limit) + while p do + local code = if p + 3 < limit then readu8(b, p + 3) else -1 + if code == 0xB3 or code == 0xB8 or code == 0x00 or code == 0xB7 then + -- a sequence / GOP header or a picture after a picture closes it + if cur and (code ~= 0xB7) then + cur.size = p - cur.offset + table.insert(out, cur) + cur = nil + end + if code == 0xB3 then + unitStart = unitStart or p + seq = true + elseif code == 0xB8 then + unitStart = unitStart or p + gop = true + elseif code == 0x00 then + local t, tr = 0, 0 + if p + 5 < limit then + local x = readu8(b, p + 4) * 256 + readu8(b, p + 5) + t, tr = (x // 8) % 8, x // 64 + end + cur = { offset = unitStart or p, size = 0, type = t, temporal = tr, gop = gop, sequence = seq } + unitStart, seq, gop = nil, false, false + elseif code == 0xB7 and cur then + cur.size = p + 4 - cur.offset + table.insert(out, cur) + cur = nil + end + end + p = MpegEs.findStart(b, p + 4, limit) + end + if cur then + cur.size = limit - cur.offset + table.insert(out, cur) + end + return out +end + +-- h264Key(b, off, limit) -> an Annex B access unit holds an IDR slice (NAL type 5) +function MpegEs.h264Key(b: buffer, off: number, limit: number): boolean + local p = MpegEs.findStart(b, off, limit) + local count = 0 + while p and count < 64 do + count += 1 + if p + 3 < limit then + local t = readu8(b, p + 3) % 32 + if t == 5 then + return true + elseif t == 1 then + return false + end + end + p = MpegEs.findStart(b, p + 3, limit) + end + return false +end + +return MpegEs diff --git a/src/Formats/containers/MpegPs/init.luau b/src/Formats/containers/MpegPs/init.luau new file mode 100644 index 0000000..53f75be --- /dev/null +++ b/src/Formats/containers/MpegPs/init.luau @@ -0,0 +1,224 @@ +--!strict +-- containers/MpegPs: the MPEG program stream (ISO/IEC 11172-1 system streams and ISO/IEC 13818-1 program streams: +-- .mpg / .mpeg / .vob). New in formats-luau. Pack headers (MPEG-1 and MPEG-2 layouts), system headers, the program +-- stream map (stream types), padding, and PES packets of the video (0xE0..0xEF), audio (0xC0..0xDF) and private +-- stream 1 (0xBD: AC-3 / DTS / LPCM / subpicture sub-streams) ids with their PTS / DTS (both PES header layouts, +-- 33-bit timestamps unwrapped). Data between packs that is not a start code is skipped (resync). +-- +-- local ps, err = MpegPs.read(buf, base, limit) +-- ps.streams[id] = { id, kind, codec, streamType, pes = { { pts?, dts?, offset, size } } } (id: stream_id, or +-- 0xBD00 + sub-stream id for private stream 1); ps.order = the ids in order of appearance +-- +-- Never throws: malformed packets are skipped and counted in ps.errors. +local Err = require("@formats/core/Err") +local MpegEs = require("@formats/containers/MpegEs") + +local readu8 = buffer.readu8 + +local MpegPs = {} + +export type Pes = { pts: number?, dts: number?, offset: number, size: number } +export type Stream = { id: number, kind: string, codec: string, streamType: number?, pes: { Pes } } +export type File = { streams: { [number]: Stream }, order: { number }, mpeg2: boolean, errors: number } + +local WRAP = 8589934592 -- 2^33 + +-- PSM stream_type -> kind, codec +local TYPES: { [number]: { string } } = { + [0x01] = { "video", "mpeg1" }, + [0x02] = { "video", "mpeg2" }, + [0x03] = { "audio", "mp2" }, + [0x04] = { "audio", "mp2" }, + [0x0F] = { "audio", "aac" }, + [0x10] = { "video", "mpeg4" }, + [0x1B] = { "video", "h264" }, + [0x24] = { "video", "hevc" }, + [0x81] = { "audio", "ac3" }, +} + +local function ts(b: buffer, p: number): number + local a = readu8(b, p) + local v = (a // 2) % 8 + v = v * 32768 + (readu8(b, p + 1) * 256 + readu8(b, p + 2)) // 2 + v = v * 32768 + (readu8(b, p + 3) * 256 + readu8(b, p + 4)) // 2 + return v +end + +-- read(buf, base, limit) -> File | nil, Err +function MpegPs.read(b: buffer, base: number, limit: number): (File?, Err.Err?) + local file: File = { streams = {}, order = {}, mpeg2 = false, errors = 0 } + local types: { [number]: number } = {} + local last: { [number]: number } = {} + local wrap: { [number]: number } = {} + local packs = 0 + local p = MpegEs.findStart(b, base, limit) + local function unwrap(id: number, v: number): number + local off = wrap[id] or 0 + local prev = last[id] + local t = v + off + if prev and t < prev - WRAP / 2 then + off += WRAP + wrap[id] = off + t = v + off + end + last[id] = t + return t + end + while p do + if p + 4 > limit then + break + end + local code = readu8(b, p + 3) + local nextP = p + 4 + if code == 0xBA then + packs += 1 + if p + 5 > limit then + break + end + local m = readu8(b, p + 4) + if m // 64 == 1 then -- MPEG-2 pack: 14 bytes + stuffing + file.mpeg2 = true + if p + 14 > limit then + break + end + nextP = p + 14 + readu8(b, p + 13) % 8 + else + nextP = p + 12 + end + elseif code == 0xB9 then + nextP = p + 4 + elseif code >= 0xBB then + if p + 6 > limit then + break + end + local len = readu8(b, p + 4) * 256 + readu8(b, p + 5) + local stop = p + 6 + len + if stop > limit then + stop = limit + end + nextP = stop + if code == 0xBC and len >= 10 then -- program stream map + local infoLen = readu8(b, p + 8) * 256 + readu8(b, p + 9) + local q = p + 10 + infoLen + if q + 2 <= stop then + local mapLen = readu8(b, q) * 256 + readu8(b, q + 1) + q += 2 + local e = math.min(stop, q + mapLen) + while q + 4 <= e do + local st, sid = readu8(b, q), readu8(b, q + 1) + local il = readu8(b, q + 2) * 256 + readu8(b, q + 3) + types[sid] = st + q += 4 + il + end + end + elseif code == 0xBD or (code >= 0xC0 and code <= 0xEF) then + -- a PES packet + local q = p + 6 + local pts, dts: number? = nil, nil + local ok = true + if q < stop and readu8(b, q) // 64 == 2 then -- MPEG-2 PES header + if q + 3 > stop then + ok = false + else + local flags = readu8(b, q + 1) + local hlen = readu8(b, q + 2) + local h = q + 3 + if flags >= 0x80 and h + 5 <= stop then + pts = ts(b, h) + if flags // 64 == 3 and h + 10 <= stop then + dts = ts(b, h + 5) + end + end + q = h + hlen + end + else -- MPEG-1 packet header + local n = 0 + while q < stop and readu8(b, q) == 0xFF and n < 16 do + q += 1 + n += 1 + end + if q < stop and readu8(b, q) // 64 == 1 then + q += 2 + end + if q < stop then + local c = readu8(b, q) // 16 + if c == 2 and q + 5 <= stop then + pts = ts(b, q) + q += 5 + elseif c == 3 and q + 10 <= stop then + pts = ts(b, q) + dts = ts(b, q + 5) + q += 10 + elseif readu8(b, q) == 0x0F then + q += 1 + else + ok = false + end + end + end + if ok and q <= stop then + local id = code + local kind, codec = "other", "unknown" + if code == 0xBD then + if q >= stop then + ok = false + else + local sub = readu8(b, q) + id = 0xBD00 + sub + if sub >= 0x80 and sub <= 0x87 then + kind, codec = "audio", "ac3" + q += 4 + elseif sub >= 0x88 and sub <= 0x8F then + kind, codec = "audio", "dts" + q += 4 + elseif sub >= 0xA0 and sub <= 0xA7 then + kind, codec = "audio", "pcm_dvd" + q += 7 + elseif sub >= 0x20 and sub <= 0x3F then + kind, codec = "subtitle", "dvdsub" + q += 1 + else + q += 1 + end + end + elseif code >= 0xE0 then + kind, codec = "video", "mpeg1" + else + kind, codec = "audio", "mp2" + end + local st = types[code] + if st and TYPES[st] then + kind, codec = TYPES[st][1], TYPES[st][2] + end + if ok and q <= stop then + local s = file.streams[id] + if not s then + s = { id = id, kind = kind, codec = codec, streamType = st, pes = {} } + file.streams[id] = s + table.insert(file.order, id) + end + table.insert(s.pes, { + pts = if pts then unwrap(id, pts) else nil, + dts = if dts then unwrap(id + 0x10000, dts) else nil, + offset = q, + size = stop - q, + }) + end + end + if not ok then + file.errors += 1 + end + end + else + -- a start code that is not a system one (stray ES data between packets): resync + file.errors += 1 + end + p = MpegEs.findStart(b, nextP, limit) + end + if packs == 0 and #file.order == 0 then + return nil, Err.new(Err.CORRUPT, "no MPEG pack or PES packet", base) + end + return file, nil +end + +return MpegPs diff --git a/src/Formats/containers/MpegTs/init.luau b/src/Formats/containers/MpegTs/init.luau new file mode 100644 index 0000000..693b034 --- /dev/null +++ b/src/Formats/containers/MpegTs/init.luau @@ -0,0 +1,831 @@ +--!strict +--!native +-- containers/MpegTs: an MPEG transport stream demuxer (ISO/IEC 13818-1). Absorbed from mpegts-luau 6e16197 (same +-- author; no third-party code). Changed: this header, and the unit queue keeps an explicit tail (pull() used #q on a +-- table with holes at its front, which LuaJIT's border rule makes lose units). 188-byte packets with resync, PAT / PMT sections +-- (assembled across packets, CRC-checked), adaptation fields (PCR, discontinuity, random access), continuity +-- counter checks (gaps are flagged on the unit, duplicates dropped), PES reassembly with 33-bit PTS / DTS. +-- +-- local units = MpegTs.demux(buf) -- whole segment: { video = {...}, audio = {...}, streams, ... } +-- local d = MpegTs.new(); d:push(chunk); local u = d:pull() ... d:flush() -- streamed +-- +-- Native code must never throw (an error unwinding through native code crashes Roblox Studio), so every read is +-- bounds-checked by construction and bad input is skipped and counted in `stats`, never raised. + +local MpegTs = {} + +export type Stream = { + pid: number, + streamType: number, -- PMT stream_type (0 when the stream was found without a PMT) + kind: string, -- "video" | "audio" | "other" + codec: string, -- "mpeg1video" | "mpeg2video" | "mpegaudio" | "aac" | "h264" | "hevc" | "ac3" | "unknown" ... + program: number, -- program_number (0 without a PMT) + language: string?, -- ISO 639 language descriptor, when present +} + +export type Unit = { + pid: number, + kind: string, + codec: string, + streamType: number, + streamId: number, -- PES stream_id (0xE0.. video, 0xC0.. audio) + pts: number?, -- seconds (33-bit 90 kHz clock, unwrapped per PID) + dts: number?, -- seconds; equals pts when the PES carries no DTS + pts90: number?, -- the same in 90 kHz ticks + dts90: number?, + data: buffer, -- the PES payload (one access unit for video as muxed by ffmpeg; one or more frames for audio) + ccError: boolean, -- a continuity counter gap (lost packets) happened inside this unit + randomAccess: boolean, -- the first packet's adaptation field had random_access_indicator set + discontinuity: boolean, -- the first packet's adaptation field had discontinuity_indicator set +} + +export type Stats = { + packets: number, + syncLosses: number, -- resyncs (bytes skipped to find 0x47 again) + skippedBytes: number, + teiErrors: number, -- transport_error_indicator packets (dropped) + ccErrors: number, -- continuity counter gaps + duplicates: number, -- duplicate packets (same CC), dropped + crcErrors: number, -- PSI sections with a bad CRC (ignored) + pesErrors: number, -- PES units without a valid header (dropped) + scrambled: number, -- scrambled packets (dropped) + pcr: number?, -- last PCR seen, seconds +} + +export type Demuxed = { + video: { Unit }, -- units of the selected video PID (first video stream of the PMT), in stream order + audio: { Unit }, -- units of the selected audio PID + streams: { Stream }, -- every elementary stream, PMT order + units: { Unit }, -- every unit of every PID, in completion order + videoPid: number?, + audioPid: number?, + stats: Stats, +} + +type PesState = { + buf: buffer, + len: number, + active: boolean, + expected: number, -- total PES bytes when PES_packet_length is set, else 0 (ends at the next unit start) + hdrChecked: boolean, + ccError: boolean, + randomAccess: boolean, + discontinuity: boolean, + lastPts: number, -- for 33-bit wrap unwrapping + wrapOffset: number, +} + +type SectionState = { buf: buffer, len: number, active: boolean } + +local TS_SIZE = 188 +local SYNC = 0x47 +local MAX_SECTION = 4096 + 188 +local WRAP = 8589934592 -- 2^33 + +local readu8 = buffer.readu8 +local band = bit32.band +local bor = bit32.bor +local lshift = bit32.lshift +local rshift = bit32.rshift + +local CODECS: { [number]: { string } } = { + [0x01] = { "video", "mpeg1video" }, + [0x02] = { "video", "mpeg2video" }, + [0x03] = { "audio", "mpegaudio" }, + [0x04] = { "audio", "mpegaudio" }, + [0x0F] = { "audio", "aac" }, + [0x10] = { "video", "mpeg4" }, + [0x11] = { "audio", "aac_latm" }, + [0x1B] = { "video", "h264" }, + [0x24] = { "video", "hevc" }, + [0x81] = { "audio", "ac3" }, + [0x87] = { "audio", "eac3" }, +} + +-- CRC-32/MPEG-2 (poly 0x04C11DB7, init 0xFFFFFFFF, MSB first, no final xor): a section including its CRC sums to 0 +local CRC = buffer.create(256 * 4) +for i = 0, 255 do + local c = lshift(i, 24) + for _ = 1, 8 do + if band(c, 0x80000000) ~= 0 then + c = bit32.bxor(lshift(c, 1), 0x04C11DB7) + else + c = lshift(c, 1) + end + end + buffer.writeu32(CRC, i * 4, c) +end + +local function crc32(b: buffer, off: number, n: number): number + local c = 0xFFFFFFFF + for i = off, off + n - 1 do + c = bit32.bxor(lshift(c, 8), buffer.readu32(CRC, band(bit32.bxor(rshift(c, 24), readu8(b, i)), 255) * 4)) + end + return c +end +MpegTs.crc32 = crc32 + +local function u16(b: buffer, p: number): number + return readu8(b, p) * 256 + readu8(b, p + 1) +end + +-- 33-bit timestamp from the 5-byte PES encoding at p +local function readTs(b: buffer, p: number): number + local b0 = readu8(b, p) + local hi = band(rshift(b0, 1), 7) * 1073741824 -- bits 32..30 + local mid = bor(lshift(readu8(b, p + 1), 7), rshift(readu8(b, p + 2), 1)) -- bits 29..15 + local lo = bor(lshift(readu8(b, p + 3), 7), rshift(readu8(b, p + 4), 1)) -- bits 14..0 + return hi + mid * 32768 + lo +end + +local Demuxer = {} +Demuxer.__index = Demuxer + +export type Demuxer = typeof(setmetatable( + {} :: { + _pend: buffer, + _pendLen: number, + _pmtPids: { [number]: number }, + _streams: { [number]: Stream }, + _pes: { [number]: PesState }, + _sections: { [number]: SectionState }, + _cc: { [number]: number }, + _queue: { Unit }, + _qhead: number, + _qtail: number, + streams: { Stream }, + stats: Stats, + }, + Demuxer +)) + +function MpegTs.new(): Demuxer + local self = setmetatable({ + _pend = buffer.create(64 * 1024), + _pendLen = 0, + _pmtPids = {}, + _streams = {}, + _pes = {}, + _sections = {}, + _cc = {}, + _queue = {}, + _qhead = 1, + _qtail = 0, + streams = {}, + stats = { + packets = 0, + syncLosses = 0, + skippedBytes = 0, + teiErrors = 0, + ccErrors = 0, + duplicates = 0, + crcErrors = 0, + pesErrors = 0, + scrambled = 0, + pcr = nil, + } :: Stats, + }, Demuxer) + return self +end + +-- PSI --------------------------------------------------------------------------------------------------------- + +local function addStream(self: Demuxer, pid: number, streamType: number, program: number, language: string?) + local info = CODECS[streamType] + local s = self._streams[pid] + if s == nil then + s = { + pid = pid, + streamType = streamType, + kind = if info then info[1] else "other", + codec = if info then info[2] else "unknown", + program = program, + language = language, + } + self._streams[pid] = s + table.insert(self.streams, s) + else + s.streamType = streamType + s.kind = if info then info[1] else "other" + s.codec = if info then info[2] else "unknown" + s.program = program + s.language = language + end +end + +local function parseSection(self: Demuxer, pid: number, b: buffer, n: number) + -- n >= 3 bytes: table_id, section_length (n = 3 + section_length) + if n < 12 then + return + end + if band(readu8(b, 1), 0x80) == 0 then + return -- no section_syntax_indicator: not a PAT / PMT + end + if crc32(b, 0, n) ~= 0 then + self.stats.crcErrors += 1 + return + end + if band(readu8(b, 5), 1) == 0 then + return -- current_next_indicator = 0: a future table + end + local tid = readu8(b, 0) + local stop = n - 4 + if tid == 0x00 and pid == 0 then + local p = 8 + while p + 4 <= stop do + local prog = u16(b, p) + local pmt = band(u16(b, p + 2), 0x1FFF) + if prog ~= 0 then + self._pmtPids[pmt] = prog + end + p += 4 + end + elseif tid == 0x02 and self._pmtPids[pid] ~= nil then + local program = u16(b, 3) + local p = 12 + band(u16(b, 10), 0x0FFF) + while p + 5 <= stop do + local st = readu8(b, p) + local epid = band(u16(b, p + 1), 0x1FFF) + local esl = band(u16(b, p + 3), 0x0FFF) + local d = p + 5 + local dend = math.min(d + esl, stop) + local language: string? = nil + while d + 2 <= dend do + local tag, len = readu8(b, d), readu8(b, d + 1) + if tag == 0x0A and len >= 3 and d + 5 <= dend then + language = buffer.readstring(b, d + 2, 3) + end + d += 2 + len + end + addStream(self, epid, st, program, language) + p += 5 + esl + end + end +end + +local function sectionBytes(self: Demuxer, pid: number, s: SectionState, src: buffer, from: number, to: number) + local n = to - from + if n <= 0 then + return + end + if s.len + n > MAX_SECTION then + s.active = false + s.len = 0 + return + end + buffer.copy(s.buf, s.len, src, from, n) + s.len += n + -- every complete section in the buffer + while s.active and s.len >= 3 do + if readu8(s.buf, 0) == 0xFF then + s.active = false -- stuffing: no more sections until the next unit start + s.len = 0 + return + end + local need = 3 + band(u16(s.buf, 1), 0x0FFF) + if s.len < need then + return + end + parseSection(self, pid, s.buf, need) + local rest = s.len - need + if rest > 0 then + buffer.copy(s.buf, 0, s.buf, need, rest) + end + s.len = rest + end +end + +local function sectionPayload(self: Demuxer, pid: number, pusi: boolean, b: buffer, pos: number, stop: number) + local s = self._sections[pid] + if s == nil then + s = { buf = buffer.create(MAX_SECTION), len = 0, active = false } + self._sections[pid] = s + end + if pusi then + if pos >= stop then + return + end + local ptr = readu8(b, pos) + pos += 1 + local tail = math.min(pos + ptr, stop) + if s.active then + sectionBytes(self, pid, s, b, pos, tail) -- the end of the previous section + end + s.active = true + s.len = 0 + pos = tail + elseif not s.active then + return + end + sectionBytes(self, pid, s, b, pos, stop) +end + +-- PES --------------------------------------------------------------------------------------------------------- + +local function completePes(self: Demuxer, pid: number, st: PesState) + st.active = false + local b, len = st.buf, st.len + if len < 6 or readu8(b, 0) ~= 0 or readu8(b, 1) ~= 0 or readu8(b, 2) ~= 1 then + self.stats.pesErrors += 1 + return + end + local sid = readu8(b, 3) + local stop = if st.expected > 0 then math.min(st.expected, len) else len + local start = 6 + local pts: number?, dts: number? = nil, nil + if not (sid == 0xBC or sid == 0xBE or sid == 0xBF or sid == 0xF0 or sid == 0xF1 or sid == 0xF2 or sid == 0xF8 or sid == 0xFF) then + if stop < 9 then + self.stats.pesErrors += 1 + return + end + if band(readu8(b, 6), 0xC0) == 0x80 then + -- MPEG-2 PES header + local flags = readu8(b, 7) + local hl = readu8(b, 8) + start = 9 + hl + if band(flags, 0x80) ~= 0 and hl >= 5 and 14 <= stop then + pts = readTs(b, 9) + if band(flags, 0x40) ~= 0 and hl >= 10 and 19 <= stop then + dts = readTs(b, 14) + end + end + else + -- MPEG-1 (ISO 11172-1) packet header: stuffing, STD buffer, PTS / DTS + local p = 6 + local k = 0 + while p < stop and readu8(b, p) == 0xFF and k < 16 do + p += 1 + k += 1 + end + if p < stop and band(readu8(b, p), 0xC0) == 0x40 then + p += 2 + end + if p < stop then + local c = band(readu8(b, p), 0xF0) + if c == 0x20 and p + 5 <= stop then + pts = readTs(b, p) + p += 5 + elseif c == 0x30 and p + 10 <= stop then + pts = readTs(b, p) + dts = readTs(b, p + 5) + p += 10 + else + p += 1 + end + end + start = p + end + end + if start > stop then + self.stats.pesErrors += 1 + return + end + -- unwrap the 33-bit clock (per PID) + if pts ~= nil then + pts += st.wrapOffset + if st.lastPts >= 0 then + if pts < st.lastPts - WRAP / 2 then + st.wrapOffset += WRAP + pts += WRAP + elseif pts > st.lastPts + WRAP / 2 and st.wrapOffset >= WRAP then + st.wrapOffset -= WRAP + pts -= WRAP + end + end + st.lastPts = pts + if dts ~= nil then + dts += st.wrapOffset + if dts > pts + WRAP / 2 then + dts -= WRAP + elseif dts < pts - WRAP / 2 then + dts += WRAP + end + else + dts = pts + end + end + local n = stop - start + local data = buffer.create(n) + if n > 0 then + buffer.copy(data, 0, b, start, n) + end + local s = self._streams[pid] + local kind, codec, streamType + if s then + kind, codec, streamType = s.kind, s.codec, s.streamType + elseif sid >= 0xE0 and sid <= 0xEF then + kind, codec, streamType = "video", "unknown", 0 + elseif sid >= 0xC0 and sid <= 0xDF then + kind, codec, streamType = "audio", "mpegaudio", 0 + else + kind, codec, streamType = "other", "unknown", 0 + end + local unit: Unit = { + pid = pid, + kind = kind, + codec = codec, + streamType = streamType, + streamId = sid, + pts = if pts then pts / 90000 else nil, + dts = if dts then dts / 90000 else nil, + pts90 = pts, + dts90 = dts, + data = data, + ccError = st.ccError, + randomAccess = st.randomAccess, + discontinuity = st.discontinuity, + } + local tail = self._qtail + 1 + self._qtail = tail + self._queue[tail] = unit +end + +local function pesPayload( + self: Demuxer, + pid: number, + pusi: boolean, + b: buffer, + pos: number, + stop: number, + ccError: boolean, + randomAccess: boolean, + discontinuity: boolean +) + local st = self._pes[pid] + -- a unit starts with a PES start code; anything else on a PID outside the PMT (SDT, EIT ...) is ignored + local startCode = pusi + and stop - pos >= 3 + and readu8(b, pos) == 0 + and readu8(b, pos + 1) == 0 + and readu8(b, pos + 2) == 1 + if st == nil then + if not startCode then + return + end + st = { + buf = buffer.create(16 * 1024), + len = 0, + active = false, + expected = 0, + hdrChecked = false, + ccError = false, + randomAccess = false, + discontinuity = false, + lastPts = -1, + wrapOffset = 0, + } + self._pes[pid] = st + end + if ccError and st.active then + st.ccError = true -- packets of the unit in progress were lost + end + if pusi then + if st.active then + completePes(self, pid, st) + end + if not startCode then + if self._streams[pid] ~= nil then + self.stats.pesErrors += 1 + end + return + end + st.active = true + st.len = 0 + st.expected = 0 + st.hdrChecked = false + st.ccError = false + st.randomAccess = randomAccess + st.discontinuity = discontinuity + elseif not st.active then + return + end + local n = stop - pos + if n <= 0 then + return + end + if st.len + n > buffer.len(st.buf) then + local cap = buffer.len(st.buf) * 2 + while cap < st.len + n do + cap *= 2 + end + if cap > 64 * 1024 * 1024 then + st.active = false -- runaway unit (no unit start for 64 MB): drop it + st.len = 0 + self.stats.pesErrors += 1 + return + end + local nb = buffer.create(cap) + buffer.copy(nb, 0, st.buf, 0, st.len) + st.buf = nb + end + buffer.copy(st.buf, st.len, b, pos, n) + st.len += n + if not st.hdrChecked and st.len >= 6 then + st.hdrChecked = true + local plen = u16(st.buf, 4) + if plen > 0 then + st.expected = 6 + plen + end + end + if st.expected > 0 and st.len >= st.expected then + completePes(self, pid, st) + end +end + +-- packets ----------------------------------------------------------------------------------------------------- + +local function packet(self: Demuxer, b: buffer, pk: number) + local stats = self.stats + stats.packets += 1 + local b1 = readu8(b, pk + 1) + if band(b1, 0x80) ~= 0 then + stats.teiErrors += 1 + return + end + local pusi = band(b1, 0x40) ~= 0 + local pid = band(b1, 0x1F) * 256 + readu8(b, pk + 2) + if pid == 0x1FFF then + return + end + local b3 = readu8(b, pk + 3) + if band(b3, 0xC0) ~= 0 then + stats.scrambled += 1 + return + end + local afc = band(rshift(b3, 4), 3) + local cc = band(b3, 15) + if afc == 0 then + return + end + local pos = pk + 4 + local stop = pk + TS_SIZE + local discontinuity, randomAccess = false, false + if afc >= 2 then + local afl = readu8(b, pos) + pos += 1 + if afl > 183 then + return + end + if afl > 0 then + local flags = readu8(b, pos) + discontinuity = band(flags, 0x80) ~= 0 + randomAccess = band(flags, 0x40) ~= 0 + if band(flags, 0x10) ~= 0 and afl >= 7 then + local base = readu8(b, pos + 1) * 33554432 + + readu8(b, pos + 2) * 131072 + + readu8(b, pos + 3) * 512 + + readu8(b, pos + 4) * 2 + + rshift(readu8(b, pos + 5), 7) + local ext = band(readu8(b, pos + 5), 1) * 256 + readu8(b, pos + 6) + stats.pcr = base / 90000 + ext / 27000000 + end + end + pos += afl + if afc == 2 then + if discontinuity then + self._cc[pid] = nil + end + return -- adaptation field only: the counter does not advance + end + end + -- continuity counter + local ccError = false + local last = self._cc[pid] + if last ~= nil and not discontinuity then + if cc == last then + stats.duplicates += 1 + return + elseif cc ~= band(last + 1, 15) then + ccError = true + stats.ccErrors += 1 + end + end + self._cc[pid] = cc + if pid == 0 or self._pmtPids[pid] ~= nil then + sectionPayload(self, pid, pusi, b, pos, stop) + elseif pid >= 0x10 then + pesPayload(self, pid, pusi, b, pos, stop, ccError, randomAccess, discontinuity) + end +end + +-- Appends bytes (a buffer, or a string) and demuxes every whole packet in them. Completed units queue up for +-- pull(). Returns false for a bad argument. +function Demuxer.push(self: Demuxer, data: buffer | string, offset: number?, len: number?): boolean + local src: buffer + if type(data) == "string" then + src = buffer.fromstring(data) + elseif type(data) == "buffer" then + src = data + else + return false + end + local off = math.max(0, math.floor(offset or 0)) + local total = buffer.len(src) + if off > total then + return false + end + local n = math.min(math.floor(len or (total - off)), total - off) + if n < 0 then + return false + end + -- append to the pending bytes + local need = self._pendLen + n + if need > buffer.len(self._pend) then + local cap = buffer.len(self._pend) + while cap < need do + cap *= 2 + end + local nb = buffer.create(cap) + buffer.copy(nb, 0, self._pend, 0, self._pendLen) + self._pend = nb + end + if n > 0 then + buffer.copy(self._pend, self._pendLen, src, off, n) + end + self._pendLen = need + local b, avail = self._pend, self._pendLen + local p = 0 + while p + TS_SIZE <= avail do + if readu8(b, p) ~= SYNC then + -- resync: the next 0x47 that is followed by another one 188 bytes later (or by the end of the data) + self.stats.syncLosses += 1 + local q = p + 1 + local found = -1 + local waitAt = -1 + while q < avail do + if readu8(b, q) == SYNC then + if q + TS_SIZE < avail then + if readu8(b, q + TS_SIZE) == SYNC then + found = q + break + end + elseif q + TS_SIZE == avail then + found = q + break + else + waitAt = q -- not enough bytes to confirm: wait for more + break + end + end + q += 1 + end + if found >= 0 then + self.stats.skippedBytes += found - p + p = found + elseif waitAt >= 0 then + self.stats.skippedBytes += waitAt - p + p = waitAt + break + else + self.stats.skippedBytes += avail - p + p = avail + break + end + else + packet(self, b, p) + p += TS_SIZE + end + end + local rest = avail - p + if rest > 0 and p > 0 then + buffer.copy(b, 0, b, p, rest) + end + self._pendLen = rest + return true +end + +-- The next completed unit (any PID), or nil. +function Demuxer.pull(self: Demuxer): Unit? + local q = self._queue + local h = self._qhead + local u = q[h] + if u == nil then + return nil + end + q[h] = nil :: any + h += 1 + if h > self._qtail then + table.clear(q) + h = 1 + self._qtail = 0 + end + self._qhead = h + return u +end + +-- Ends every unit in progress (call at the end of the data: a video PES with no length only ends at the next +-- unit start). Units still queue up for pull(). +function Demuxer.flush(self: Demuxer) + local pids = {} + for pid, st in self._pes do + if st.active then + table.insert(pids, pid) + end + end + table.sort(pids) + for _, pid in pids do + completePes(self, pid, self._pes[pid]) + end + self._pendLen = 0 +end + +-- Forgets buffered bytes, units in progress and continuity state, but keeps the PAT / PMT (for a seek). +function Demuxer.reset(self: Demuxer) + self._pendLen = 0 + for _, st in self._pes do + st.active = false + st.len = 0 + st.lastPts = -1 + st.wrapOffset = 0 + end + for _, s in self._sections do + s.active = false + s.len = 0 + end + table.clear(self._cc) + table.clear(self._queue) + self._qhead = 1 + self._qtail = 0 +end + +-- Streams by kind: the first video / audio PID in PMT order (or in unit order without a PMT). +function Demuxer.streamFor(self: Demuxer, kind: string): Stream? + for _, s in self.streams do + if s.kind == kind then + return s + end + end + return nil +end + +export type DemuxOptions = { videoPid: number?, audioPid: number? } + +-- Demuxes a whole buffer (one segment). Video and audio are the units of one PID each: opts.videoPid / +-- opts.audioPid, else the first video / audio stream of the PMT, else the first PID whose units look like video / +-- audio (PES stream_id). Never throws; a bad argument gives empty lists. +function MpegTs.demux(data: buffer | string, opts: DemuxOptions?): Demuxed + local d = MpegTs.new() + d:push(data) + d:flush() + local units = {} + while true do + local u = d:pull() + if u == nil then + break + end + table.insert(units, u) + end + local videoPid = opts and opts.videoPid + local audioPid = opts and opts.audioPid + if videoPid == nil then + local s = d:streamFor("video") + videoPid = if s then s.pid else nil + end + if audioPid == nil then + local s = d:streamFor("audio") + audioPid = if s then s.pid else nil + end + for _, u in units do + if videoPid == nil and u.kind == "video" then + videoPid = u.pid + end + if audioPid == nil and u.kind == "audio" then + audioPid = u.pid + end + end + local video, audio = {}, {} + for _, u in units do + if u.pid == videoPid then + table.insert(video, u) + elseif u.pid == audioPid then + table.insert(audio, u) + end + end + return { + video = video, + audio = audio, + streams = d.streams, + units = units, + videoPid = videoPid, + audioPid = audioPid, + stats = d.stats, + } +end + +-- Concatenates the data of a list of units (e.g. a segment's audio access units, for Mp3.open). +function MpegTs.concat(units: { Unit }): buffer + local n = 0 + for _, u in units do + n += buffer.len(u.data) + end + local out = buffer.create(n) + local p = 0 + for _, u in units do + local l = buffer.len(u.data) + buffer.copy(out, p, u.data, 0, l) + p += l + end + return out +end + +return MpegTs diff --git a/src/Formats/core/Md5.luau b/src/Formats/core/Md5.luau new file mode 100644 index 0000000..3ec4379 --- /dev/null +++ b/src/Formats/core/Md5.luau @@ -0,0 +1,164 @@ +--!strict +--!native +--!optimize 2 +-- core/Md5: MD5 (RFC 1321), incremental. Written from the RFC. Used by the FLAC encoder (STREAMINFO's MD5 of the PCM); +-- not for security. +-- +-- local h = Md5.new() +-- h:update(buf, offset?, length?) -- any number of times +-- local digest = h:digest() -- 16-byte string (the state is finished; make a new one to hash again) +-- Md5.hex(digest) / Md5.of(buf) -> hex string +-- Never throws (ranges are clamped to the buffer). +local Md5 = {} + +local band, bor, bxor, bnot, lrotate = bit32.band, bit32.bor, bit32.bxor, bit32.bnot, bit32.lrotate +local readu32, writeu32, writeu8 = buffer.readu32, buffer.writeu32, buffer.writeu8 + +local K = table.create(64, 0) +for i = 0, 63 do + K[i + 1] = math.floor(math.abs(math.sin(i + 1)) * 4294967296) % 4294967296 +end +local S = { + 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, + 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, + 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, + 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, +} +local G = table.create(64, 0) +for i = 0, 63 do + if i < 16 then + G[i + 1] = i + elseif i < 32 then + G[i + 1] = (5 * i + 1) % 16 + elseif i < 48 then + G[i + 1] = (3 * i + 5) % 16 + else + G[i + 1] = (7 * i) % 16 + end +end + +export type State = { + a: number, + b: number, + c: number, + d: number, + block: buffer, -- 64-byte pending block + fill: number, + total: number, -- bytes hashed + update: (self: State, buf: buffer, offset: number?, length: number?) -> (), + digest: (self: State) -> string, +} + +local M = table.create(16, 0) + +local function compress(st: State, blk: buffer, o: number) + for i = 0, 15 do + M[i + 1] = readu32(blk, o + i * 4) + end + local a, b, c, d = st.a, st.b, st.c, st.d + for i = 0, 63 do + local f + if i < 16 then + f = bor(band(b, c), band(bnot(b), d)) + elseif i < 32 then + f = bor(band(d, b), band(bnot(d), c)) + elseif i < 48 then + f = bxor(b, c, d) + else + f = bxor(c, bor(b, bnot(d))) + end + local tmp = d + d = c + c = b + b = (b + lrotate((a + f + K[i + 1] + M[G[i + 1] + 1]) % 4294967296, S[i + 1])) % 4294967296 + a = tmp + end + st.a = (st.a + a) % 4294967296 + st.b = (st.b + b) % 4294967296 + st.c = (st.c + c) % 4294967296 + st.d = (st.d + d) % 4294967296 +end + +local function update(self: State, buf: buffer, offset: number?, length: number?) + local n = buffer.len(buf) + local o = math.clamp(offset or 0, 0, n) + local len = math.clamp(length or (n - o), 0, n - o) + self.total += len + local blk = self.block + if self.fill > 0 then + local take = math.min(64 - self.fill, len) + buffer.copy(blk, self.fill, buf, o, take) + self.fill += take + o += take + len -= take + if self.fill == 64 then + compress(self, blk, 0) + self.fill = 0 + end + end + while len >= 64 do + compress(self, buf, o) + o += 64 + len -= 64 + end + if len > 0 then + buffer.copy(blk, 0, buf, o, len) + self.fill = len + end +end + +local function digest(self: State): string + local bits = self.total * 8 + local blk = self.block + local f = self.fill + writeu8(blk, f, 0x80) + f += 1 + if f > 56 then + buffer.fill(blk, f, 0, 64 - f) + compress(self, blk, 0) + f = 0 + end + buffer.fill(blk, f, 0, 56 - f) + writeu32(blk, 56, bits % 4294967296) + writeu32(blk, 60, math.floor(bits / 4294967296) % 4294967296) + compress(self, blk, 0) + self.fill = 0 + local out = buffer.create(16) + writeu32(out, 0, self.a) + writeu32(out, 4, self.b) + writeu32(out, 8, self.c) + writeu32(out, 12, self.d) + return buffer.tostring(out) +end + +function Md5.new(): State + return { + a = 0x67452301, + b = 0xEFCDAB89, + c = 0x98BADCFE, + d = 0x10325476, + block = buffer.create(64), + fill = 0, + total = 0, + update = update, + digest = digest, + } +end + +-- hex(digest) -> 32 lower-case hex digits +function Md5.hex(d: string): string + local out = table.create(#d) + for i = 1, #d do + out[i] = string.format("%02x", string.byte(d, i)) + end + return table.concat(out) +end + +-- of(buf, offset?, length?) -> hex digest +function Md5.of(buf: buffer, offset: number?, length: number?): string + local h = Md5.new() + h:update(buf, offset, length) + return Md5.hex(h:digest()) +end + +return Md5 diff --git a/src/Formats/image/jpeg/init.luau b/src/Formats/image/jpeg/init.luau index f6c3077..aeffeea 100644 --- a/src/Formats/image/jpeg/init.luau +++ b/src/Formats/image/jpeg/init.luau @@ -1,7 +1,10 @@ --!strict --- image/jpeg: JPEG / JFIF / EXIF (ITU T.81). Absorbed from jpeg-luau 1.0 (same author: the Huffman decoder, IDCTs, --- upsampling and colour conversion, bit-exact with libjpeg-turbo's djpeg) and extended with arithmetic coding, meta --- (EXIF, ICC, comments, density) and an encoder. IJG-derived parts: licenses/libjpeg-turbo-LICENSE.md. +-- image/jpeg: JPEG / JFIF / EXIF (ITU T.81), a thin format over codecs/Jpeg (the engine, shared with the Motion-JPEG +-- video tracks; absorbed from jpeg-luau 1.0, same author, bit-exact with libjpeg-turbo's djpeg and byte-identical +-- with cjpeg; IJG-derived parts: licenses/libjpeg-turbo-LICENSE.md). This module is the contract, the sniff, the +-- options and the meta segments: meta.exif (APP1), meta.icc (APP2 chunks), meta.text.comment (COM) and meta.dpi +-- (JFIF density) are written from the Image on encode and read back on decode. Encode also takes yuv420p Images +-- (coded 4:2:0 from the planes as they are). -- Decode: baseline, extended and progressive frames, Huffman or arithmetic coded (SOF0/1/2/9/10), 8 and 12-bit -- samples, 1, 3 or 4 components with any sampling factors 1..4, restart intervals (resynchronising after corrupt -- data), grey / YCbCr / RGB / CMYK / YCCK (Adobe APP14), scaled decodes (opts.scale = 2, 4, 8 through libjpeg's @@ -17,8 +20,7 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Decode = require("@formats/image/jpeg/Decode") -local Encode = require("@formats/image/jpeg/Encode") +local Codec = require("@formats/codecs/Jpeg") -- ------------------------------------------------------------------------------------------------ contract local Jpeg = { @@ -26,7 +28,7 @@ local Jpeg = { category = "image", extensions = { "jpg", "jpeg", "jpe", "jfif" }, mime = { "image/jpeg" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Dct" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Jpeg" }, caps = { decode = true, encode = true, lossy = true, alpha = false, depths = { 8, 12 }, progressive = true, arithmetic = true }, } @@ -48,22 +50,7 @@ export type EncodeOptions = { meta: boolean?, -- write meta.exif (APP1), meta.icc (APP2) and meta.text.comment (COM) (default true) } -export type Info = { - width: number, - height: number, - components: number, - progressive: boolean, - arithmetic: boolean, - precision: number, - colorSpace: string, - sampling: { { number } }, -- { h, v } per component - orientation: number, - adobe: number?, - jfif: boolean, -} - --- ------------------------------------------------------------------------------------------------ constants -local CODES = { corrupt = Err.CORRUPT, unsupported = Err.UNSUPPORTED, limit = Err.LIMIT, truncated = Err.TRUNCATED, arg = Err.ARG } +export type Info = Codec.Info -- ------------------------------------------------------------------------------------------------ sniff function Jpeg.sniff(r: Bytes.Reader): number @@ -72,214 +59,91 @@ function Jpeg.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode -local function parse(r: Bytes.Reader, opts: any, headerOnly: boolean): (Decode.State?, Err.Err?) - local ok, st, code, msg = pcall(Decode.parse, r.buf, r.base, r.limit, opts, headerOnly) - if not ok then - return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(st)) - end - if not st then - return nil, Err.new(CODES[code :: string] or Err.CORRUPT, msg or "decode failed") - end - return st, nil -end - -- info(r) -> Info | nil, Err (reads the headers up to the frame header) function Jpeg.info(r: Bytes.Reader): (Info?, Err.Err?) - local st, err = parse(r, nil, true) - if not st then - return nil, err - end - local f = st.frame - local sampling = {} - for _, c in f.comps do - table.insert(sampling, { c.h, c.v }) - end - return { - width = f.width, - height = f.height, - components = #f.comps, - progressive = f.progressive, - arithmetic = f.arithmetic, - precision = f.precision, - colorSpace = Decode.colorSpaceOf(f, st.adobe, st.jfif), - sampling = sampling, - orientation = st.orientation, - adobe = st.adobe, - jfif = st.jfif, - }, - nil -end - --- the EXIF orientation applied to rgba8 pixels: buffer, width, height -local function orient(px: buffer, w: number, h: number, o: number): (buffer, number, number) - if o <= 1 or o > 8 then - return px, w, h - end - local swap = o >= 5 - local ow, oh = if swap then h else w, if swap then w else h - local out = buffer.create(ow * oh * 4) - local readu32, writeu32 = buffer.readu32, buffer.writeu32 - for y = 0, oh - 1 do - for x = 0, ow - 1 do - local col, row - if o == 2 then - col, row = w - 1 - x, y - elseif o == 3 then - col, row = w - 1 - x, h - 1 - y - elseif o == 4 then - col, row = x, h - 1 - y - elseif o == 5 then - col, row = y, x - elseif o == 6 then - col, row = y, h - 1 - x - elseif o == 7 then - col, row = w - 1 - y, h - 1 - x - else - col, row = w - 1 - y, x - end - writeu32(out, (y * ow + x) * 4, readu32(px, (row * w + col) * 4)) - end - end - return out, ow, oh + return Codec.info(r.buf, r.base, r.limit - r.base) end function Jpeg.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) - local st, err = parse(r, opts, false) - if not st then - return nil, err + if opts ~= nil and type(opts) ~= "table" then + return nil, Err.new(Err.ARG, "options must be a table") end - local ok, w, h, px, space = pcall(Decode.output, st :: Decode.State) - if not ok then - return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(w)) - end - if not w then - return nil, Err.new(CODES[h :: string] or Err.CORRUPT, tostring(px)) - end - local orientation = st.orientation - if opts and opts.orient then - px, w, h = orient(px, w, h, orientation) - end - local img = Types.Image.new(1, 1) - img.width, img.height, img.pixels = w, h, px - if opts and opts.native and space == "gray" then - local g = buffer.create(w * h) - for i = 0, w * h - 1 do - buffer.writeu8(g, i, buffer.readu8(px, i * 4)) - end - img.pixels, img.format = g, "gray8" - end - local f = st.frame - local sampling = {} - for _, c in f.comps do - table.insert(sampling, { c.h, c.v }) - end - img.meta.orientation = orientation - img.meta.oriented = (opts and opts.orient) or false - img.meta.exif = st.exif - img.meta.icc = st.icc - if #st.comments > 0 then - img.meta.text = { comment = table.concat(st.comments, "\n") } - end - if st.density and st.density.unit > 0 and st.density.x > 0 and st.density.y > 0 then - local k = if st.density.unit == 2 then 2.54 else 1 - img.meta.dpi = { x = st.density.x * k, y = st.density.y * k } - end - img.meta.truncated = st.truncated - img.meta.source = { - format = "jpeg", - bitDepth = f.precision, - colorType = space, - components = #f.comps, - progressive = f.progressive, - arithmetic = f.arithmetic, - sampling = sampling, - scale = st.scale, - adobe = st.adobe, - jfif = st.jfif, - } - return img, nil + local o = opts or {} :: DecodeOptions + -- one image: no yuv output, no field weaving (two JPEGs back to back are an image and a preview, as in MPF) + return Codec.decode(r.buf, r.base, r.limit - r.base, { + scale = o.scale, + orient = o.orient, + native = o.native, + maxPixels = o.maxPixels, + fields = false, + }) end -- ------------------------------------------------------------------------------------------------ encode -local BPP = { rgba8 = 4, rgb8 = 3, gray8 = 1 } - -function Jpeg.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) - if type(img) ~= "table" or type(img.pixels) ~= "buffer" or type(img.width) ~= "number" or type(img.height) ~= "number" then - return nil, Err.new(Err.ARG, "needs an Image") - end - local bpp = BPP[img.format] - if not bpp then - return nil, Err.new(Err.ARG, "needs an rgba8, rgb8 or gray8 Image (got " .. tostring(img.format) .. ")") - end - local w, h = img.width, img.height - if w < 1 or h < 1 or w > 65535 or h > 65535 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < w * h * bpp then - return nil, Err.new(Err.ARG, "bad image size or pixel buffer (1..65535 per side)") - end - local o: any = opts or {} - local quality = o.quality or 90 - if type(quality) ~= "number" or quality < 1 or quality > 100 then - return nil, Err.new(Err.ARG, "quality must be 1..100") - end - local sub = o.subsampling or "420" - if sub ~= "420" and sub ~= "422" and sub ~= "444" then - return nil, Err.new(Err.ARG, "subsampling must be \"420\", \"422\" or \"444\"") - end - local restart = o.restart or 0 - if type(restart) ~= "number" or restart < 0 or restart > 65535 or restart % 1 ~= 0 then - return nil, Err.new(Err.ARG, "restart must be 0..65535 MCUs") - end - local gray = o.gray - if gray == nil then - gray = img.format == "gray8" - end +-- the APP1 / APP2 / COM segments and the JFIF density from img.meta +local function metaSegments(meta: any): ({ { marker: number, data: buffer } }, { unit: number, x: number, y: number }?) local segments = {} - local meta = img.meta or {} - if o.meta ~= false then - if type(meta.exif) == "buffer" and buffer.len(meta.exif) <= 65527 then - local d = buffer.create(buffer.len(meta.exif) + 6) - buffer.writestring(d, 0, "Exif\0\0") - buffer.copy(d, 6, meta.exif) - table.insert(segments, { marker = 0xE1, data = d }) - end - if type(meta.icc) == "buffer" then - local icc = meta.icc :: buffer - local n = buffer.len(icc) - local chunk = 65519 - local count = math.max(1, math.ceil(n / chunk)) - if count <= 255 then - for i = 1, count do - local a = (i - 1) * chunk - local l = math.min(chunk, n - a) - local d = buffer.create(l + 14) - buffer.writestring(d, 0, "ICC_PROFILE\0") - buffer.writeu8(d, 12, i) - buffer.writeu8(d, 13, count) - buffer.copy(d, 14, icc, a, l) - table.insert(segments, { marker = 0xE2, data = d }) - end + if type(meta.exif) == "buffer" and buffer.len(meta.exif) <= 65527 then + local d = buffer.create(buffer.len(meta.exif) + 6) + buffer.writestring(d, 0, "Exif\0\0") + buffer.copy(d, 6, meta.exif) + table.insert(segments, { marker = 0xE1, data = d }) + end + if type(meta.icc) == "buffer" then + local icc = meta.icc :: buffer + local n = buffer.len(icc) + local chunk = 65519 + local count = math.max(1, math.ceil(n / chunk)) + if count <= 255 then + for i = 1, count do + local a = (i - 1) * chunk + local l = math.min(chunk, n - a) + local d = buffer.create(l + 14) + buffer.writestring(d, 0, "ICC_PROFILE\0") + buffer.writeu8(d, 12, i) + buffer.writeu8(d, 13, count) + buffer.copy(d, 14, icc, a, l) + table.insert(segments, { marker = 0xE2, data = d }) end end - local text = meta.text - if type(text) == "table" and type(text.comment) == "string" and #text.comment <= 65533 then - table.insert(segments, { marker = 0xFE, data = buffer.fromstring(text.comment) }) - end + end + local text = meta.text + if type(text) == "table" and type(text.comment) == "string" and #text.comment <= 65533 then + table.insert(segments, { marker = 0xFE, data = buffer.fromstring(text.comment) }) end local density = nil if type(meta.dpi) == "table" and type(meta.dpi.x) == "number" and type(meta.dpi.y) == "number" then density = { unit = 1, x = math.clamp(math.floor(meta.dpi.x + 0.5), 1, 65535), y = math.clamp(math.floor(meta.dpi.y + 0.5), 1, 65535) } end - local out = Encode.run(img.pixels, w, h, bpp, { - quality = quality, - sampling = sub, - progressive = o.progressive == true, - optimize = o.optimize == true, - gray = gray, - restart = restart, - segments = segments, - jfif = o.jfif ~= false, + return segments, density +end + +function Jpeg.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" then + return nil, Err.new(Err.ARG, "needs an Image") + end + if opts ~= nil and type(opts) ~= "table" then + return nil, Err.new(Err.ARG, "options must be a table") + end + local o: any = opts or {} + local segments, density = {}, nil + if o.meta ~= false then + segments, density = metaSegments(img.meta or {}) + elseif type(img.meta) == "table" then + local _ + _, density = metaSegments({ dpi = img.meta.dpi }) + end + return Codec.encode(img, { + quality = o.quality, + subsampling = o.subsampling, + progressive = o.progressive, + optimize = o.optimize, + gray = o.gray, + restart = o.restart, + jfif = o.jfif, density = density, + segments = segments, }) - return out, nil end return Jpeg diff --git a/src/Formats/init.luau b/src/Formats/init.luau index 19fd6c7..a5604b2 100644 --- a/src/Formats/init.luau +++ b/src/Formats/init.luau @@ -19,6 +19,9 @@ local Bytes = require("@formats/core/Bytes") local Input = require("@formats/core/Input") local Types = require("@formats/Types") local Registry = require("@formats/Registry") +local Video = require("@formats/codecs/Video") +local AudioWrap = require("@formats/containers/AudioWrap") +local ImageOps = require("@formats/ops/ImageOps") local host = require("@formats/host") local F = {} @@ -35,6 +38,7 @@ F.plugins = {} :: { [string]: any } -- injected optional dependencies (plugins.b local KIND_CATEGORY: { [string]: string } = { image = "image", audio = "audio", + video = "video", scene = "model", cad = "cad", font = "font", @@ -255,11 +259,32 @@ end -- so the api hands decoders opts.decodeImage(buf) -> Image | nil, Err and encoders opts.encodeImage(img, format) -> -- buffer | nil, Err (unless the caller passed its own). Formats work without them (returning Err.UNSUPPORTED for -- the embedded parts) when called directly. +-- +-- 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. +local function openAudio(demuxer: any, track: any): (any, Err.Err?) + local buf, fmt, err = AudioWrap.wrap(demuxer, track) + if not buf then + return nil, err + end + local dec, oerr = F.open(buf, { format = fmt, category = "audio" }) + -- Matroska CodecDelay: ffmpeg drops it for MPEG audio / AAC; Opus has its own pre-skip and Vorbis's delay is + -- already the decoder's own (its first packet returns nothing) + if dec and fmt ~= "opus" and fmt ~= "vorbis" and type(track.codecDelay) == "number" and track.codecDelay > 0 then + dec = AudioWrap.trim(dec, math.floor(track.codecDelay * dec.sampleRate + 0.5)) + end + return dec, oerr +end + local function withHooks(o: Options): Options - if o.decodeImage ~= nil and o.encodeImage ~= nil then + if o.decodeImage ~= nil and o.encodeImage ~= nil and o.openAudio ~= nil then return o end local c = table.clone(o) + if c.openAudio == nil then + c.openAudio = openAudio + end if c.decodeImage == nil then c.decodeImage = function(b: buffer): (any, Err.Err?) return F.load(b, { category = "image" }) @@ -305,12 +330,12 @@ function F.load(src: any, opts: Options?): (any, Err.Err?) end value, err = v, e elseif m.open then - local ok, dec, e = pcall(m.open, Bytes.reader(buf), o) + local ok, dec, e = pcall(m.open, Bytes.reader(buf), withHooks(o)) if not ok then return nil, Err.wrap(Err.new(Err.CORRUPT, "decoder threw: " .. tostring(dec)), entry.name) end if dec then - value = drain(dec) + value = if type(dec) == "table" and dec.kind == "video" then dec else drain(dec) end err = e else @@ -333,6 +358,9 @@ function F.open(src: any, opts: Options?): (any, Err.Err?) return nil, ierr end local entry, derr = detect(buf, name, o.category, o.format) + if not entry and o.category == "video" and o.format == nil then + entry = detect(buf, name, "image", nil) -- animated images open as frames-backed videos + end if not entry then return nil, derr end @@ -340,10 +368,20 @@ function F.open(src: any, opts: Options?): (any, Err.Err?) if not m then return nil, merr end + if not m.open and entry.category == "image" and o.category == "video" then + local io = table.clone(o) + io.category = "image" + io.format = entry.name + local img, lerr = F.load(buf, io) + if not img then + return nil, lerr + end + return F.video.fromImage(img, o) + end if not m.open then return nil, Err.wrap(Err.new(Err.UNSUPPORTED, "no streaming decoder (use load)"), entry.name) end - local ok, dec, e = pcall(m.open, Bytes.reader(buf), o) + local ok, dec, e = pcall(m.open, Bytes.reader(buf), withHooks(o)) if not ok then return nil, Err.wrap(Err.new(Err.CORRUPT, "decoder threw: " .. tostring(dec)), entry.name) end @@ -369,6 +407,9 @@ local function encoderFor(value: any, dest: string?, o: Options): (Registry.Entr return nil, nil, Err.new(Err.ARG, "save: no format (pass opts.format or a destination with an extension)") end local entry = find(key, category) + if not entry and category == "image" and type(value) == "table" and value.kind == "image" then + entry = find(key, "video") -- an (animated) image written as a video: F.convert(gif, "avi") + end if not entry then return nil, nil, Err.new(Err.UNKNOWN_FORMAT, "no format named " .. key .. (if category then " for " .. category else "")) end @@ -423,6 +464,13 @@ function F.save(value: any, dest: string?, opts: Options?): (any, Err.Err?) o.files = {} end end + if entry.category == "video" and type(value) == "table" and value.kind == "image" then + local v, verr = F.video.fromImage(value) + if not v then + return nil, verr + end + value = v + end if type(value) == "table" and value.kind == "scene" then local terr = encodeTextures(value) if terr then @@ -539,6 +587,41 @@ for category in Types.CATEGORIES do end F.data.null = Types.null +-- F.video.fromImage(img, opts?) -> a frames-backed VideoDecoder: an animated GIF / APNG / WebP (img.frames, composited +-- onto full canvases by ImageOps.coalesce) or a still image (one frame). opts.rgba is accepted (frames are rgba8). +F.video.fromImage = function(img: any, opts: Options?): (any, Err.Err?) + if type(img) ~= "table" or img.kind ~= "image" then + return nil, Err.new(Err.ARG, "fromImage: expected an Image") + end + local frames, delays = { img }, { 0.1 } + if type(img.frames) == "table" and #img.frames > 0 then + local list, cerr = ImageOps.coalesce(img) + if not list then + return nil, cerr + end + frames = list + delays = {} + for i, f in img.frames do + delays[i] = if type(f.delay) == "number" and f.delay > 0 then f.delay else 0.1 + end + elseif img.format ~= "rgba8" and img.format ~= "yuv420p" then + local c, cerr = ImageOps.convert(img, "rgba8") + if not c then + return nil, cerr + end + frames = { c } + end + local src = type(img.meta) == "table" and img.meta.source + return Video.fromFrames(frames, delays, { format = type(src) == "table" and src.format or "image", loops = img.loops, meta = img.meta }) +end +-- F.video.fromFrames(images, delays?, opts?) -> a VideoDecoder over a list of same-size images (an image sequence: +-- F.save(F.video.fromFrames(list, 1 / 25), "out.avi")); delays in seconds (a number = every frame, default 0.1) +F.video.fromFrames = function(images: any, delays: any?, opts: Options?): (any, Err.Err?) + return Video.fromFrames(images, delays, opts) +end +-- F.video.codecs: the video codec registry (codecs/Video: register / entry / fromFourcc / fromMatroska / decoder) +F.video.codecs = Video + -- F.model.loadTextures(scene, opts?) -> scene, { [index]: Err }: decodes each texture's encoded bytes (texture.data, or -- texture.uri through opts.resolve) into texture.image with F.image.load. Model formats never decode images -- themselves (a format does not require another format); this is the lazy step at the api layer. Textures whose diff --git a/src/Formats/music/it/Itsex.luau b/src/Formats/music/it/Itsex.luau new file mode 100644 index 0000000..3a7daca --- /dev/null +++ b/src/Formats/music/it/Itsex.luau @@ -0,0 +1,120 @@ +--!strict +--!native +-- music/it/Itsex: Impulse Tracker sample decompression (IT 2.14 and the IT 2.15 double-delta variant, 8 and 16-bit). +-- Written from the algorithm description in ITTECH.TXT / the public notes on the format: blocks of 0x8000 bytes of +-- output, each a u16 length then an LSB-first bit stream of deltas with three width-change methods. +-- +-- Never throws: every read is bounds-checked; corrupt streams return nil, message. +local readu8, readu16, writef32 = buffer.readu8, buffer.readu16, buffer.writef32 + +local Itsex = {} + +-- decompress(buf, off, limit, frames, bits, it215) -> f32 buffer (frames), bytes consumed | nil, message +function Itsex.decompress(buf: buffer, off: number, limit: number, frames: number, bits: number, it215: boolean): (buffer?, number | string) + local out = buffer.create(frames * 4) + local blockLen = if bits == 16 then 0x4000 else 0x8000 + local topWidth = if bits == 16 then 17 else 9 + local fetchA = if bits == 16 then 4 else 3 + local lowerB = if bits == 16 then -8 else -4 + local upperB = if bits == 16 then 7 else 3 + local scale = if bits == 16 then 1 / 32768 else 1 / 128 + local wrap = if bits == 16 then 65536 else 256 + local half = wrap // 2 + local p = off + local done = 0 + while done < frames do + if p + 2 > limit then + return nil, "compressed sample truncated" + end + local clen = readu16(buf, p) + p += 2 + local bstart = p + local bend = p + clen + if bend > limit then + return nil, "compressed block runs past the end" + end + p = bend + -- bit reader over [bstart, bend) + local bytePos = bstart + local bitBuf = 0 + local bitCount = 0 + local function readBits(n: number): number + while bitCount < n do + if bytePos >= bend then + return -1 + end + bitBuf += readu8(buf, bytePos) * 2 ^ bitCount + bytePos += 1 + bitCount += 8 + end + local v = bitBuf % 2 ^ n + bitBuf = (bitBuf - v) / 2 ^ n + bitCount -= n + return v + end + local count = math.min(blockLen, frames - done) + local width = topWidth + local d1, d2 = 0, 0 + local i = 0 + while i < count do + if width < 1 or width > topWidth then + return nil, "bad bit width" + end + local v = readBits(width) + if v < 0 then + return nil, "compressed block ends early" + end + if width < 7 then + -- method A: a marker value, then the new width in fetchA bits + if v == 2 ^ (width - 1) then + local nw = readBits(fetchA) + if nw < 0 then + return nil, "compressed block ends early" + end + nw += 1 + width = if nw < width then nw else nw + 1 + continue + end + elseif width < topWidth then + -- method B: values just below the top of the range encode the new width + local border = bit32.rshift(if bits == 16 then 0xFFFF else 0xFF, topWidth - width) + lowerB + if v > border and v <= border + (upperB - lowerB + 1) then + local nw = v - border + width = if nw < width then nw else nw + 1 + continue + end + else + -- method C: the top bit flags a width change + if v >= wrap then + width = (v + 1) % 256 + continue + end + end + -- a delta, sign-extended from its width + local x = v + if width < topWidth then + local shift = 2 ^ width + if x >= shift / 2 then + x -= shift + end + else + x = v % wrap + if x >= half then + x -= wrap + end + end + d1 = (d1 + x + half) % wrap - half + local s = d1 + if it215 then + d2 = (d2 + d1 + half) % wrap - half + s = d2 + end + writef32(out, (done + i) * 4, s * scale) + i += 1 + end + done += count + end + return out, p - off +end + +return Itsex diff --git a/src/Formats/music/it/init.luau b/src/Formats/music/it/init.luau new file mode 100644 index 0000000..d73cec0 --- /dev/null +++ b/src/Formats/music/it/init.luau @@ -0,0 +1,427 @@ +--!strict +-- music/it: Impulse Tracker modules (IMPM, ITTECH.TXT; also files from OpenMPT / Schism Tracker). Reads into the +-- codecs/Tracker Module and plays through its engine (Module:render() / open() -> an audio Decoder). Supports: up to +-- 64 channels, instrument and sample mode, new and old (pre-2.0) instrument headers, volume / panning / pitch (or +-- filter) envelopes with loops and sustain loops, new note actions and duplicate checks, pitch-pan separation, +-- resonant filters (instrument cutoff / resonance, default Zxx macros), 8 / 16-bit signed or unsigned mono / stereo +-- samples, IT 2.14 / 2.15 compressed samples, sustain loops, auto-vibrato, the song message. +-- Not supported: embedded MIDI macro configurations (the default filter macros are used), MIDI output, OpenMPT's +-- extension chunks (plugins, extended instrument properties), writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Tracker = require("@formats/codecs/Tracker") +local Itsex = require("@formats/music/it/Itsex") + +-- ------------------------------------------------------------------------------------------------ contract +local It = { + name = "it", + category = "music", + extensions = { "it" }, + mime = { "audio/it", "audio/x-it" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 64 }, compressedSamples = true }, +} + +export type DecodeOptions = { + maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function It.sniff(r: Bytes.Reader): number + return if r:peek(4) == "IMPM" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the 82-byte envelope of a new-format instrument +local function readEnvelope(r: Bytes.Reader, kind: string): any + local flags, n = r:u8(), r:u8() + local lb, le, sb, se = r:u8(), r:u8(), r:u8(), r:u8() + local e = Tracker.newEnvelope() + n = math.min(n, 25) + for i = 1, 25 do + local y, x = r:i8(), r:u16le() + if i <= n then + e.ticks[i] = x + e.values[i] = if kind == "vol" then math.clamp(y, 0, 64) else math.clamp(y, -32, 32) + end + end + r:skip(1) + e.enabled = bit32.band(flags, 1) ~= 0 and n > 0 + e.loop = bit32.band(flags, 2) ~= 0 + e.sustain = bit32.band(flags, 4) ~= 0 + e.carry = bit32.band(flags, 8) ~= 0 + e.filter = kind == "pitch" and bit32.band(flags, 128) ~= 0 + e.loopStart, e.loopEnd = lb + 1, le + 1 + e.susStart, e.susEnd = sb + 1, se + 1 + return e +end + +local function readInstrument(r: Bytes.Reader, old: boolean): (any?, string?) + if r:string(4) ~= "IMPI" then + return nil, "bad instrument signature" + end + local ins = Tracker.newInstrument() + r:skip(13) + if old then + -- the pre-2.0 layout: volume envelope only (flags, loop and sustain points), fadeout 0..64 of 512 + local flg, vls, vle, sls, sle = r:u8(), r:u8(), r:u8(), r:u8(), r:u8() + r:skip(2) + ins.fadeout = r:u16le() * 2 + ins.nna = r:u8() + ins.dct = if r:u8() ~= 0 then 1 else 0 + r:skip(4) + ins.name = r:fixed(26) + r:skip(6) + for n = 1, 120 do + local note, smp = r:u8(), r:u8() + ins.noteMap[n] = math.clamp(note + 1, 1, 120) + ins.sampleMap[n] = smp + end + r:skip(200) + local e = Tracker.newEnvelope() + for i = 1, 25 do + local t, v = r:u8(), r:u8() + if t == 0xFF or (i > 1 and t <= (e.ticks[#e.ticks] or -1)) then + r:skip((25 - i) * 2) + break + end + table.insert(e.ticks, t) + table.insert(e.values, math.min(v, 64)) + end + e.enabled = bit32.band(flg, 1) ~= 0 and #e.ticks > 0 + e.loop = bit32.band(flg, 2) ~= 0 + e.sustain = bit32.band(flg, 4) ~= 0 + e.loopStart, e.loopEnd, e.susStart, e.susEnd = vls + 1, vle + 1, sls + 1, sle + 1 + ins.volEnv = e + return ins + end + ins.nna, ins.dct, ins.dca = r:u8() % 4, r:u8() % 4, r:u8() % 3 + ins.fadeout = math.min(r:u16le(), 1024) + ins.pps, ins.ppc = r:i8(), r:u8() + ins.globalVolume = math.min(r:u8(), 128) + local dfp = r:u8() + if dfp < 128 then + ins.pan = math.min(dfp, 64) * 4 + end + r:skip(2 + 2 + 1 + 1) + ins.name = r:fixed(26) + local ifc, ifr = r:u8(), r:u8() + if ifc >= 128 then + ins.cutoff = ifc - 128 + end + if ifr >= 128 then + ins.resonance = ifr - 128 + end + r:skip(4) + for n = 1, 120 do + local note, smp = r:u8(), r:u8() + ins.noteMap[n] = math.clamp(note + 1, 1, 120) + ins.sampleMap[n] = smp + end + ins.volEnv = readEnvelope(r, "vol") + ins.panEnv = readEnvelope(r, "pan") + ins.pitchEnv = readEnvelope(r, "pitch") + if r.err then + return nil, "instrument truncated" + end + return ins +end + +function It.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local maxBytes = opts and opts.maxBytes or 2 ^ 28 + if r:peek(4) ~= "IMPM" then + return nil, Err.new(Err.CORRUPT, "no IMPM signature") + end + r:skip(4) + local title = r:fixed(26) + r:skip(2) + local ordnum, insnum, smpnum, patnum = r:u16le(), r:u16le(), r:u16le(), r:u16le() + local cwt, cmwt, flags, special = r:u16le(), r:u16le(), r:u16le(), r:u16le() + local gv, mv, speed, tempo, _sep, _pwd = r:u8(), r:u8(), r:u8(), r:u8(), r:u8(), r:u8() + local msgLen, msgOff = r:u16le(), r:u32le() + r:skip(4) + local chnPan, chnVol = {}, {} + for i = 1, 64 do + chnPan[i] = r:u8() + end + for i = 1, 64 do + chnVol[i] = r:u8() + end + if r.err then + return nil, r.err + end + if ordnum > 256 or insnum > 255 or smpnum > 255 or patnum > 255 then + return nil, Err.new(Err.CORRUPT, "bad header counts") + end + local orders = {} + for i = 1, ordnum do + orders[i] = r:u8() + end + local insOff, smpOff, patOff = {}, {}, {} + for i = 1, insnum do + insOff[i] = r:u32le() + end + for i = 1, smpnum do + smpOff[i] = r:u32le() + end + for i = 1, patnum do + patOff[i] = r:u32le() + end + if r.err then + return nil, r.err + end + -- channels: the highest one any pattern uses + local nch = 1 + local packed: { Bytes.Reader? } = {} + local rowsOf: { number } = {} + for p = 1, patnum do + if patOff[p] > 0 then + local pr = r:sub(patOff[p]) + local len, rows = pr:u16le(), pr:u16le() + pr:skip(4) + if pr.err or rows < 1 or rows > 1024 then + return nil, Err.new(Err.CORRUPT, "bad pattern " .. (p - 1), r.base + patOff[p]) + end + local data = pr:slice(len) + packed[p], rowsOf[p] = data, rows + -- scan for the channel count + local scan = data:sub(0) + local seen: { [number]: number } = {} + while not scan:eof() do + local cv = scan:u8() + if cv == 0 then + continue + end + local ch = (cv - 1) % 64 + nch = math.max(nch, ch + 1) + local mask = 0 + if cv >= 128 then + mask = scan:u8() + seen[ch] = mask + else + mask = seen[ch] or 0 + end + if bit32.band(mask, 1) ~= 0 then + scan:skip(1) + end + if bit32.band(mask, 2) ~= 0 then + scan:skip(1) + end + if bit32.band(mask, 4) ~= 0 then + scan:skip(1) + end + if bit32.band(mask, 8) ~= 0 then + scan:skip(2) + end + end + else + rowsOf[p] = 64 + end + end + local m = Tracker.newModule("it", nch) + m.title = title + m.speed = if speed > 0 then speed else 6 + m.tempo = if tempo >= 31 then tempo else 125 + m.globalVolume = math.min(gv, 128) + m.mixVolume = math.min(mv, 128) + m.linear = bit32.band(flags, 8) ~= 0 + m.instrumentMode = bit32.band(flags, 4) ~= 0 + m.flags.oldEffects = bit32.band(flags, 16) ~= 0 + m.flags.compatGxx = bit32.band(flags, 32) ~= 0 + local stereo = bit32.band(flags, 1) ~= 0 + for i = 1, nch do + local p = chnPan[i] + if p >= 128 then + m.channelMute[i] = true + p -= 128 + end + if not stereo then + m.channelPan[i] = 128 + elseif p == 100 then + m.channelPan[i] = 512 + else + m.channelPan[i] = math.min(p, 64) * 4 + end + m.channelVolume[i] = math.min(chnVol[i], 64) + end + for i = 1, ordnum do + if orders[i] == 255 then + break + end + table.insert(m.order, orders[i]) + end + m.meta.source = { format = "it", tracker = cwt, compatible = cmwt } + if bit32.band(special, 1) ~= 0 and msgLen > 0 then + local mr = r:sub(msgOff, msgLen) + m.meta.message = string.gsub(mr:fixed(msgLen), "\r", "\n") + end + -- instruments + for i = 1, insnum do + local ins, ierr = readInstrument(r:sub(insOff[i]), cmwt < 0x200) + if not ins then + return nil, Err.new(Err.CORRUPT, "instrument " .. i .. ": " .. tostring(ierr), r.base + insOff[i]) + end + m.instruments[i] = ins + end + -- samples + local total = 0 + for i = 1, smpnum do + local h = r:sub(smpOff[i], 80) + if h:string(4) ~= "IMPS" then + return nil, Err.new(Err.CORRUPT, "sample " .. i .. ": bad signature", r.base + smpOff[i]) + end + h:skip(13) + local s = Tracker.newSample() + m.samples[i] = s + local gvl, flg, vol = h:u8(), h:u8(), h:u8() + s.name = h:fixed(26) + local cvt, dfp = h:u8(), h:u8() + local len, lb, le, c5, slb, sle, ptr = h:u32le(), h:u32le(), h:u32le(), h:u32le(), h:u32le(), h:u32le(), h:u32le() + local vis, vid, vir, vit = h:u8(), h:u8(), h:u8(), h:u8() + if h.err then + return nil, Err.new(Err.TRUNCATED, "sample header " .. i) + end + s.globalVolume = math.min(gvl, 64) + s.volume = math.min(vol, 64) + if dfp >= 128 then + s.pan = math.min(dfp - 128, 64) * 4 + end + s.c5speed = if c5 > 0 then c5 else 8363 + s.vibRate, s.vibDepth, s.vibSweep, s.vibType = vis, vid, vir, vit % 4 + local bits = if bit32.band(flg, 2) ~= 0 then 16 else 8 + local nchs = if bit32.band(flg, 4) ~= 0 then 2 else 1 + s.bits = bits + if bit32.band(flg, 1) ~= 0 and len > 0 then + len = math.min(len, 2 ^ 26) + total += len * nchs * 4 + if total > maxBytes then + return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit") + end + local data: buffer? = nil + if bit32.band(flg, 8) ~= 0 then + -- compressed: each channel separately + local it215 = bit32.band(cvt, 4) ~= 0 + local p = r.base + ptr + local parts = {} + for c = 1, nchs do + local d, used = Itsex.decompress(r.buf, p, r.limit, len, bits, it215) + if not d then + return nil, Err.new(Err.CORRUPT, "sample " .. i .. ": " .. tostring(used)) + end + parts[c] = d + p += used :: number + end + if nchs == 1 then + data = parts[1] + else + local inter = buffer.create(len * 8) + for f = 0, len - 1 do + buffer.writef32(inter, f * 8, buffer.readf32(parts[1], f * 4)) + buffer.writef32(inter, f * 8 + 4, buffer.readf32(parts[2], f * 4)) + end + data = inter + end + else + local bps = bits // 8 + local avail = math.max(0, r:size() - ptr) // (bps * nchs) + len = math.min(len, avail) + data = Tracker.Pcm.decode(r.buf, r.base + ptr, len, { + bits = bits, + signed = bit32.band(cvt, 1) ~= 0, + bigEndian = bit32.band(cvt, 2) ~= 0, + delta = bit32.band(cvt, 4) ~= 0, + channels = nchs, + planar = true, + }) + end + if data then + s.data, s.length, s.channels = data, len, nchs + if bit32.band(flg, 16) ~= 0 then + s.loopStart, s.loopEnd, s.loopType = lb, math.min(le, len), if bit32.band(flg, 64) ~= 0 then 2 else 1 + end + if bit32.band(flg, 32) ~= 0 then + s.susStart, s.susEnd, s.susType = slb, math.min(sle, len), if bit32.band(flg, 128) ~= 0 then 2 else 1 + end + end + end + end + -- patterns + for p = 1, patnum do + local pat = Tracker.newPattern(rowsOf[p], nch) + m.patterns[p] = pat + local pr = packed[p] + if pr then + local d = pat.data + local lastMask, lastNote, lastIns, lastVol, lastFx, lastParam = {}, {}, {}, {}, {}, {} + local row = 0 + while row < pat.rows and not pr:eof() do + local cv = pr:u8() + if cv == 0 then + row += 1 + continue + end + local ch = (cv - 1) % 64 + local mask = if cv >= 128 then pr:u8() else (lastMask[ch] or 0) + lastMask[ch] = mask + local note, ins, vol, fx, param = 0, 0, 0, 0, 0 + if bit32.band(mask, 1) ~= 0 then + local n = pr:u8() + -- 255 note off, 254 note cut, 246 note fade (as IT and OpenMPT store "~~~"); other values: nothing + note = if n < 120 then n + 1 elseif n == 255 then 255 elseif n == 254 then 254 elseif n == 246 then 253 else 0 + lastNote[ch] = note + elseif bit32.band(mask, 16) ~= 0 then + note = lastNote[ch] or 0 + end + if bit32.band(mask, 2) ~= 0 then + ins = pr:u8() + lastIns[ch] = ins + elseif bit32.band(mask, 32) ~= 0 then + ins = lastIns[ch] or 0 + end + if bit32.band(mask, 4) ~= 0 then + vol = math.min(pr:u8(), 212) + 1 + lastVol[ch] = vol + elseif bit32.band(mask, 64) ~= 0 then + vol = lastVol[ch] or 0 + end + if bit32.band(mask, 8) ~= 0 then + fx, param = pr:u8(), pr:u8() + if fx > 26 then + fx, param = 0, 0 + end + lastFx[ch], lastParam[ch] = fx, param + elseif bit32.band(mask, 128) ~= 0 then + fx, param = lastFx[ch] or 0, lastParam[ch] or 0 + end + if ch < nch then + local o = (row * nch + ch) * 5 + buffer.writeu8(d, o, note) + buffer.writeu8(d, o + 1, ins) + buffer.writeu8(d, o + 2, vol) + buffer.writeu8(d, o + 3, fx) + buffer.writeu8(d, o + 4, param) + end + end + end + end + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function It.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = It.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return It diff --git a/src/Formats/music/midi/Render.luau b/src/Formats/music/midi/Render.luau new file mode 100644 index 0000000..657246a --- /dev/null +++ b/src/Formats/music/midi/Render.luau @@ -0,0 +1,261 @@ +--!strict +-- music/midi/Render: the tempo map (ticks -> seconds, as python mido computes lengths), the time-ordered event list, +-- and the audio Decoder that plays a Midi through codecs/SoundFont's synth (a SoundFont bank, or the built-in +-- waveform set). Format 0 / 1: one tempo map from every track's tempo events, tracks merged (ties keep track order). +-- Format 2: each track is its own song with its own tempo map, played one after another. +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local SoundFont = require("@formats/codecs/SoundFont") + +local Synth = SoundFont.Synth + +local Render = {} + +export type TempoMap = { ticks: { number }, secs: { number }, us: { number }, division: number } + +local STATUS = { noteOff = 0x80, noteOn = 0x90, aftertouch = 0xA0, controller = 0xB0, program = 0xC0, channelPressure = 0xD0, pitchBend = 0xE0 } + +local function tempoOf(ev: any): number? + if ev.type == "meta" and ev.meta == 0x51 and type(ev.data) == "table" and #ev.data >= 3 then + return ev.data[1] * 65536 + ev.data[2] * 256 + ev.data[3] + end + return nil +end + +-- tempoMap(midi, track?) -> TempoMap: from every track (format 0 / 1) or from one track (format 2) +function Render.tempoMap(midi: Types.Midi, track: number?): TempoMap + local changes: { { number } } = {} + for ti, t in midi.tracks do + if track == nil or track == ti then + for i, ev in t.events do + local us = tempoOf(ev) + if us then + table.insert(changes, { ev.tick, ti, i, us }) + end + end + end + end + table.sort(changes, function(a: { number }, b: { number }): boolean + if a[1] ~= b[1] then + return a[1] < b[1] + end + if a[2] ~= b[2] then + return a[2] < b[2] + end + return a[3] < b[3] + end) + local map: TempoMap = { ticks = { 0 }, secs = { 0 }, us = { 500000 }, division = midi.division } + local div = midi.division + for _, c in changes do + local n = #map.ticks + local tick = c[1] + local sec = map.secs[n] + (tick - map.ticks[n]) * map.us[n] * 1e-6 / div + if tick == map.ticks[n] then + map.us[n] = c[4] + else + table.insert(map.ticks, tick) + table.insert(map.secs, sec) + table.insert(map.us, c[4]) + end + end + return map +end + +-- seconds(map, tick) -> seconds (PPQ through the tempo map; SMPTE divisions are fixed time) +function Render.seconds(map: TempoMap, tick: number): number + local div = map.division + if div < 0 then + local fps = -(div // 256) + local tpf = div % 256 + if tpf == 0 then + return 0 + end + return tick / ((if fps == 29 then 29.97 else fps) * tpf) + end + local ticks = map.ticks + -- binary search for the last change at or before tick + local lo, hi = 1, #ticks + while lo < hi do + local mid = (lo + hi + 1) // 2 + if ticks[mid] <= tick then + lo = mid + else + hi = mid - 1 + end + end + return map.secs[lo] + (tick - ticks[lo]) * map.us[lo] * 1e-6 / div +end + +-- length(midi) -> seconds to the last event (format 2: the tracks one after another) +function Render.length(midi: Types.Midi): number + if #midi.tracks == 0 then + return 0 + end + if midi.format == 2 then + local total = 0 + for ti, t in midi.tracks do + local map = Render.tempoMap(midi, ti) + local last = 0 + for _, ev in t.events do + last = math.max(last, ev.tick) + end + total += Render.seconds(map, last) + end + return total + end + local map = Render.tempoMap(midi) + local last = 0 + for _, t in midi.tracks do + for _, ev in t.events do + last = math.max(last, ev.tick) + end + end + return Render.seconds(map, last) +end + +export type Timeline = { time: { number }, status: { number }, d1: { number }, d2: { number }, length: number } + +-- timeline(midi) -> the channel messages in play order with their times in seconds +function Render.timeline(midi: Types.Midi): Timeline + local items: { { any } } = {} + local offset = 0 + local function add(map: TempoMap, ti: number, t: any, base: number) + for i, ev in t.events do + local st = STATUS[ev.type] + if st and type(ev.data) == "table" then + local ch = ev.channel or 0 + table.insert(items, { base + Render.seconds(map, ev.tick), ti, i, st + ch % 16, ev.data[1] or 0, ev.data[2] or 0 }) + end + end + end + if midi.format == 2 then + for ti, t in midi.tracks do + local map = Render.tempoMap(midi, ti) + add(map, ti, t, offset) + local last = 0 + for _, ev in t.events do + last = math.max(last, ev.tick) + end + offset += Render.seconds(map, last) + end + else + local map = Render.tempoMap(midi) + for ti, t in midi.tracks do + add(map, ti, t, 0) + end + end + table.sort(items, function(a: { any }, b: { any }): boolean + if a[1] ~= b[1] then + return a[1] < b[1] + end + if a[2] ~= b[2] then + return a[2] < b[2] + end + return a[3] < b[3] + end) + local tl: Timeline = { time = table.create(#items), status = table.create(#items), d1 = table.create(#items), d2 = table.create(#items), length = Render.length(midi) } + for i, it in items do + tl.time[i], tl.status[i], tl.d1[i], tl.d2[i] = it[1], it[4], it[5] % 128, it[6] % 128 + end + return tl +end + +export type RenderOptions = { + sampleRate: number?, -- default 44100 + soundfont: any?, -- a SoundFont (music/sf2 decode, codecs/SoundFont.parse) or SF2 bytes (buffer / string); default the built-in waveforms + gain: number?, -- linear output gain, default 0.5 + tail: number?, -- seconds rendered after the last event (release tails), default 1 + maxVoices: number?, -- default 256 +} + +-- decoder(midi, opts?) -> Types.Decoder | nil, Err +function Render.decoder(midi: Types.Midi, opts: RenderOptions?): (Types.Decoder?, Err.Err?) + if type(midi) ~= "table" or type(midi.tracks) ~= "table" or type(midi.division) ~= "number" or midi.division == 0 then + return nil, Err.new(Err.ARG, "render: needs a Midi value") + end + local o: RenderOptions = opts or {} + local rate = o.sampleRate or 44100 + if type(rate) ~= "number" or rate < 1000 or rate > 384000 then + return nil, Err.new(Err.ARG, "render: sampleRate must be 1000..384000") + end + local sf = o.soundfont + if sf == nil then + sf = SoundFont.fallback() + elseif not SoundFont.isSoundFont(sf) then + local parsed, err = SoundFont.parse(sf) + if not parsed then + return nil, err + end + sf = parsed + end + local tl = Render.timeline(midi) + local tail = o.tail or 1 + local frames = math.max(0, math.ceil((tl.length + tail) * rate)) + local nev = #tl.time + local evFrame = table.create(nev) + for i = 1, nev do + evFrame[i] = math.floor(tl.time[i] * rate + 0.5) + end + local gain, maxVoices = o.gain, o.maxVoices + local state = Synth.new(sf, rate, gain, maxVoices) + local pos, nextEv = 0, 1 + + local dec = { + sampleRate = rate, + channels = 2, + frames = frames, + duration = frames / rate, + bitrate = 0, + tags = {} :: Types.Tags, + } + for _, t in midi.tracks do + if t.name and not dec.tags.title then + dec.tags.title = t.name + end + end + + local function read(_self: any, n: number, out: buffer?): (buffer, number) + n = math.max(0, math.min(math.floor(n), frames - pos)) + local buf = out + if not buf or buffer.len(buf) < n * 8 then + buf = buffer.create(math.max(n, 1) * 8) + end + local b = buf :: buffer + buffer.fill(b, 0, 0, n * 8) + local i = 0 + while i < n do + while nextEv <= nev and evFrame[nextEv] <= pos + i do + Synth.midi(state, tl.status[nextEv], tl.d1[nextEv], tl.d2[nextEv]) + nextEv += 1 + end + local stop = n + if nextEv <= nev then + stop = math.min(n, evFrame[nextEv] - pos) + end + if stop > i then + Synth.render(state, b, i, stop - i) + i = stop + end + end + pos += n + return b, n + end + dec.read = read :: any + local scratch = buffer.create(4096 * 8) + dec.seek = function(_self: any, seconds: number) + local target = math.clamp(math.floor((tonumber(seconds) or 0) * rate), 0, frames) + if target < pos then + Synth.reset(state) + pos, nextEv = 0, 1 + end + while pos < target do + read(nil, math.min(4096, target - pos), scratch) + end + end :: any + dec.position = function(_self: any): number + return pos / rate + end :: any + return (dec :: any) :: Types.Decoder, nil +end + +return Render diff --git a/src/Formats/music/midi/Smf.luau b/src/Formats/music/midi/Smf.luau new file mode 100644 index 0000000..ed69595 --- /dev/null +++ b/src/Formats/music/midi/Smf.luau @@ -0,0 +1,402 @@ +--!strict +-- music/midi/Smf: Standard MIDI File chunks <-> Types.Midi. Reads MThd / MTrk (formats 0, 1, 2; PPQ and SMPTE +-- divisions; running status, also across meta / sysex events as most players accept), skips unknown chunks, unwraps +-- RIFF RMID. Writes MThd + MTrk with optional running status; with running status on (the default) the bytes are +-- those python mido writes for the same events (running status reset after meta / sysex, one end-of-track at the +-- end, mid-track end-of-track events dropped). Written from the SMF 1.0 specification (no third-party code). +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") + +local Smf = {} + +local readu8 = buffer.readu8 + +local CHANNEL_TYPES = { [8] = "noteOff", [9] = "noteOn", [10] = "aftertouch", [11] = "controller", [12] = "program", [13] = "channelPressure", [14] = "pitchBend" } +local TYPE_STATUS = { noteOff = 0x80, noteOn = 0x90, aftertouch = 0xA0, controller = 0xB0, program = 0xC0, channelPressure = 0xD0, pitchBend = 0xE0 } +Smf.TYPE_STATUS = TYPE_STATUS + +export type ReadOptions = { + strict: boolean?, -- a truncated track / file is an error (default false: keep the events read so far, meta.truncated) + maxEvents: number?, -- default 2^24 +} +export type WriteOptions = { + runningStatus: boolean?, -- default true +} + +local function bytesOf(b: buffer, p: number, n: number): { number } + local t: { number } = table.create(n) + for i = 0, n - 1 do + t[i + 1] = readu8(b, p + i) + end + return t +end + +local function text(data: { number }): string + local parts = table.create(#data) + for i, c in data do + parts[i] = string.char(c) + end + return table.concat(parts) +end +Smf.text = text + +-- ------------------------------------------------------------------------------------------------ read +-- one MTrk body [p, e): events | nil, message, truncated +local function readTrack(b: buffer, p: number, e: number, budget: { number }): ({ Types.MidiEvent }?, string?, boolean) + local events: { Types.MidiEvent } = {} + local tick = 0 + local running = 0 + while p < e do + -- delta time + local delta, n = 0, 0 + repeat + if p >= e then + return events, nil, true + end + local c = readu8(b, p) + p += 1 + n += 1 + delta = delta * 128 + c % 128 + if n > 4 then + return nil, "delta time longer than 4 bytes", false + end + until c < 128 + tick += delta + if p >= e then + return events, nil, true + end + local status = readu8(b, p) + if status < 0x80 then + if running == 0 then + return nil, "running status without a previous status byte", false + end + status = running + else + p += 1 + if status < 0xF0 then + running = status + end + end + budget[1] -= 1 + if budget[1] < 0 then + return nil, "LIMIT", false + end + if status == 0xFF or status == 0xF0 or status == 0xF7 then + local mtype = 0 + if status == 0xFF then + if p >= e then + return events, nil, true + end + mtype = readu8(b, p) + p += 1 + end + local len, m = 0, 0 + repeat + if p >= e then + return events, nil, true + end + local c = readu8(b, p) + p += 1 + m += 1 + len = len * 128 + c % 128 + if m > 4 then + return nil, "length longer than 4 bytes", false + end + until c < 128 + if p + len > e then + return events, nil, true + end + local data = bytesOf(b, p, len) + p += len + if status == 0xFF then + table.insert(events, { tick = tick, type = "meta", meta = mtype, data = data }) + else + table.insert(events, { tick = tick, type = if status == 0xF0 then "sysex" else "escape", data = data }) + end + elseif status >= 0xF0 then + return nil, string.format("unexpected status byte 0x%02x in a track", status), false + else + local kind = status // 16 + local count = if kind == 12 or kind == 13 then 1 else 2 + if p + count > e then + return events, nil, true + end + local d1 = readu8(b, p) + local d2 = if count == 2 then readu8(b, p + 1) else 0 + if d1 >= 128 or d2 >= 128 then + return nil, "data byte over 127", false + end + p += count + table.insert(events, { + tick = tick, + type = CHANNEL_TYPES[kind], + channel = status % 16, + data = if count == 2 then { d1, d2 } else { d1 }, + }) + end + end + return events, nil, false +end + +-- read(r, opts?) -> Midi | nil, Err +function Smf.read(r: Bytes.Reader, opts: ReadOptions?): (Types.Midi?, Err.Err?) + local strict = opts and opts.strict or false + local budget = { opts and opts.maxEvents or 2 ^ 24 } + local b = r.buf + local base, limit = r.base, r.limit + local rmid = false + -- RIFF RMID: the SMF is the "data" chunk + if r:peek(4) == "RIFF" and r:peek(4, 8) == "RMID" then + local q = base + 12 + local found = false + while q + 8 <= limit do + local id = buffer.readstring(b, q, 4) + local size = buffer.readu32(b, q + 4) + if id == "data" then + base = q + 8 + limit = math.min(limit, base + size) + found = true + break + end + q += 8 + size + size % 2 + end + if not found then + return nil, Err.new(Err.CORRUPT, "RMID without a data chunk", r.base) + end + rmid = true + end + local h = Bytes.reader(b, base, limit - base) + if h:string(4) ~= "MThd" then + return nil, Err.new(Err.CORRUPT, "no MThd header", base) + end + local hlen = h:u32be() + local format, ntrks, division = h:u16be(), h:u16be(), h:i16be() + if h.err then + return nil, h.err + end + if hlen < 6 then + return nil, Err.new(Err.CORRUPT, "MThd shorter than 6 bytes", base + 4) + end + if format > 2 then + return nil, Err.new(Err.UNSUPPORTED, "SMF format " .. format, base + 8) + end + if division == 0 then + return nil, Err.new(Err.CORRUPT, "zero ticks per quarter note", base + 12) + end + local midi = Types.Midi.new(division) + midi.format = format + local truncated = false + local p = base + 8 + hlen + while #midi.tracks < ntrks and p + 8 <= limit do + local id = buffer.readstring(b, p, 4) + local size = bit32.byteswap(buffer.readu32(b, p + 4)) + local s = p + 8 + local e = s + size + if e > limit then + e = limit + truncated = true + end + if id == "MTrk" then + local events, msg, short = readTrack(b, s, e, budget) + if not events then + if msg == "LIMIT" then + return nil, Err.new(Err.LIMIT, "over the event limit") + end + return nil, Err.new(Err.CORRUPT, msg or "bad track", s) + end + truncated = truncated or short + local track: { events: { Types.MidiEvent }, name: string? } = { events = events, name = nil } + for _, ev in events do + if ev.type == "meta" and ev.meta == 3 then + track.name = text(ev.data :: { number }) + break + end + end + table.insert(midi.tracks, track) + end + p = s + size + end + if #midi.tracks < ntrks and p < limit then + truncated = true + elseif #midi.tracks < ntrks then + truncated = true + end + if truncated and strict then + return nil, Err.new(Err.TRUNCATED, "the file ends inside a track (or before all tracks)") + end + midi.meta.declaredTracks = ntrks + midi.meta.truncated = truncated + midi.meta.rmid = rmid + if division < 0 then + local fps = -(division // 256) + midi.meta.smpte = { fps = if fps == 29 then 29.97 else fps, ticksPerFrame = division % 256 } + end + return midi, nil +end + +-- ------------------------------------------------------------------------------------------------ write +local function vlq(w: Bytes.Writer, v: number) + if v < 128 then + w:u8(v) + return + end + local bytes = {} + while v > 0 do + table.insert(bytes, 1, v % 128) + v = v // 128 + end + for i, c in bytes do + w:u8(if i < #bytes then c + 128 else c) + end +end + +local function byteList(d: any, want: number?): { number }? + if type(d) ~= "table" then + return if want == 0 then {} else nil + end + for i, v in d do + if type(i) ~= "number" or type(v) ~= "number" or v < 0 or v > 255 or v % 1 ~= 0 then + return nil + end + end + if want and #d < want then + return nil + end + return d +end + +-- write(midi, opts?) -> buffer | nil, Err +function Smf.write(midi: Types.Midi, opts: WriteOptions?): (buffer?, Err.Err?) + if type(midi) ~= "table" or type(midi.tracks) ~= "table" then + return nil, Err.new(Err.ARG, "midi encode: needs a Midi value with tracks") + end + local running = not (opts and opts.runningStatus == false) + local format = midi.format or 1 + local division = midi.division or 480 + if type(format) ~= "number" or format < 0 or format > 2 or format % 1 ~= 0 then + return nil, Err.new(Err.ARG, "midi encode: format must be 0, 1 or 2") + end + if type(division) ~= "number" or division == 0 or division < -32768 or division > 32767 or division % 1 ~= 0 then + return nil, Err.new(Err.ARG, "midi encode: division must be a non-zero 16-bit integer") + end + if format == 0 and #midi.tracks ~= 1 then + return nil, Err.new(Err.ARG, "midi encode: format 0 needs exactly one track") + end + if #midi.tracks > 65535 then + return nil, Err.new(Err.ARG, "midi encode: too many tracks") + end + local w = Bytes.writer(1024) + w:string("MThd") + w:u32be(6) + w:u16be(format) + w:u16be(#midi.tracks) + w:u16be(if division < 0 then division + 65536 else division) + for ti, track in midi.tracks do + local events = if type(track) == "table" then track.events else nil + if type(events) ~= "table" then + return nil, Err.new(Err.ARG, "midi encode: track " .. ti .. " has no events list") + end + -- stable order by tick + local sorted = true + local last = 0 + for i, ev in events do + if type(ev) ~= "table" or type(ev.tick) ~= "number" or ev.tick < 0 or ev.tick % 1 ~= 0 then + return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d needs a whole non-negative tick", ti, i)) + end + if ev.tick < last then + sorted = false + end + last = ev.tick + end + local list = events + if not sorted then + list = table.clone(events) + local order: { [any]: number } = {} + for i, ev in list do + order[ev] = i + end + table.sort(list, function(a: any, c: any): boolean + if a.tick ~= c.tick then + return a.tick < c.tick + end + return order[a] < order[c] + end) + end + w:string("MTrk") + local lenAt = w:tell() + w:u32be(0) + local start = w:tell() + local prev = 0 + local status = 0 + local endTick = 0 + for i, ev in list do + local t = ev.type + endTick = ev.tick + if t == "meta" and ev.meta == 0x2F then + continue -- written once at the end + end + local delta = ev.tick - prev + if delta > 0x0FFFFFFF then + return nil, Err.new(Err.ARG, "midi encode: a delta time over 0x0FFFFFFF ticks") + end + local base = TYPE_STATUS[t] + if base then + local ch = ev.channel or 0 + if type(ch) ~= "number" or ch < 0 or ch > 15 or ch % 1 ~= 0 then + return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d: channel must be 0..15", ti, i)) + end + local n = if base == 0xC0 or base == 0xD0 then 1 else 2 + local d = byteList(ev.data, n) + if not d or d[1] > 127 or (n == 2 and d[2] > 127) then + return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d: %s needs %d data bytes 0..127", ti, i, t, n)) + end + vlq(w, delta) + local st = base + ch + if not (running and st == status) then + w:u8(st) + end + status = st + w:u8(d[1]) + if n == 2 then + w:u8(d[2]) + end + elseif t == "meta" or t == "sysex" or t == "escape" then + local d = byteList(ev.data, 0) + if not d then + return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d: data must be bytes", ti, i)) + end + vlq(w, delta) + if t == "meta" then + local m = ev.meta + if type(m) ~= "number" or m < 0 or m > 127 or m % 1 ~= 0 then + return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d: meta type must be 0..127", ti, i)) + end + w:u8(0xFF) + w:u8(m) + else + w:u8(if t == "sysex" then 0xF0 else 0xF7) + end + if #d > 0x0FFFFFFF then + return nil, Err.new(Err.ARG, "midi encode: event data too long") + end + vlq(w, #d) + for _, c in d do + w:u8(c) + end + status = 0 + else + return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d: unknown type %s", ti, i, tostring(t))) + end + prev = ev.tick + end + vlq(w, math.max(0, endTick - prev)) + w:u8(0xFF) + w:u8(0x2F) + w:u8(0) + w:setU32be(lenAt, w:tell() - start) + end + return w:finish(), nil +end + +return Smf diff --git a/src/Formats/music/midi/init.luau b/src/Formats/music/midi/init.luau new file mode 100644 index 0000000..fcaeb46 --- /dev/null +++ b/src/Formats/music/midi/init.luau @@ -0,0 +1,136 @@ +--!strict +-- music/midi: Standard MIDI Files (SMF 1.0: formats 0, 1 and 2; PPQ and SMPTE time; RIFF RMID read). Written from the +-- specification (no third-party code); rendering goes through codecs/SoundFont (a TinySoundFont port). +-- Supports: decode to a Types.Midi (absolute ticks; channel events noteOff / noteOn / aftertouch / controller / +-- program / channelPressure / pitchBend with their raw data bytes, sysex / escape with the bytes after the length, +-- meta events with meta = the meta type; meta.tempos / timeSignatures / keySignatures, track names), encode (running +-- status optional, byte-identical to python mido's writer by default), the tempo map (tickToSeconds, length), and +-- render / open: an audio Decoder (stereo f32) through an SF2 SoundFont (opts.soundfont) or the built-in waveform set. +-- Not supported: RMID write, XMF / RMI DLS banks, system common / realtime bytes inside tracks (CORRUPT). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Smf = require("@formats/music/midi/Smf") +local Render = require("@formats/music/midi/Render") + +-- ------------------------------------------------------------------------------------------------ contract +local Midi = { + name = "midi", + category = "music", + extensions = { "mid", "midi", "smf", "kar", "rmi" }, + mime = { "audio/midi", "audio/x-midi" }, + deps = { "core/Err", "core/Bytes", "codecs/SoundFont", "Types" }, + caps = { decode = true, encode = true, formats = { 0, 1, 2 }, render = true, streaming = true, rmid = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = Smf.ReadOptions -- strict (default false), maxEvents (default 2^24) +export type EncodeOptions = Smf.WriteOptions -- runningStatus (default true) +export type RenderOptions = Render.RenderOptions -- sampleRate, soundfont, gain, tail, maxVoices + +-- ------------------------------------------------------------------------------------------------ sniff +function Midi.sniff(r: Bytes.Reader): number + if r:peek(4) == "MThd" then + return 1 + end + if r:peek(4) == "RIFF" and r:peek(4, 8) == "RMID" then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function render(self: Types.Midi, opts: RenderOptions?): Types.Decoder + local dec, err = Render.decoder(self, opts) + if not dec then + -- the Types contract returns a Decoder; a failed render is an empty one (Midi.render returns the Err) + local empty: any = { + sampleRate = 44100, channels = 2, frames = 0, duration = 0, bitrate = 0, tags = {}, err = err, + read = function(_self: any, _n: number, out: buffer?): (buffer, number) + return out or buffer.create(0), 0 + end, + seek = function() end, + position = function(): number + return 0 + end, + } + return empty + end + return dec +end + +local function summarize(midi: Types.Midi) + local tempos, sigs, keys = {}, {}, {} + local map = Render.tempoMap(midi) + for ti, t in midi.tracks do + for _, ev in t.events do + if ev.type == "meta" then + local d = ev.data :: { number } + if ev.meta == 0x51 and #d >= 3 then + table.insert(tempos, { tick = ev.tick, track = ti, usPerQuarter = d[1] * 65536 + d[2] * 256 + d[3], bpm = 60000000 / math.max(1, d[1] * 65536 + d[2] * 256 + d[3]), seconds = Render.seconds(map, ev.tick) }) + elseif ev.meta == 0x58 and #d >= 4 then + table.insert(sigs, { tick = ev.tick, track = ti, numerator = d[1], denominator = 2 ^ math.min(d[2], 31), clocksPerClick = d[3], notated32ndsPerBeat = d[4] }) + elseif ev.meta == 0x59 and #d >= 2 then + table.insert(keys, { tick = ev.tick, track = ti, sharps = if d[1] >= 128 then d[1] - 256 else d[1], minor = d[2] == 1 }) + end + end + end + end + midi.meta.tempos = tempos + midi.meta.timeSignatures = sigs + midi.meta.keySignatures = keys + midi.meta.length = Render.length(midi) +end + +function Midi.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Midi?, Err.Err?) + local midi, err = Smf.read(r, opts) + if not midi then + return nil, err + end + summarize(midi) + midi.meta.source = { format = "midi", smf = midi.format } + midi.render = render + return midi, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Midi.encode(midi: Types.Midi, opts: EncodeOptions?): (buffer?, Err.Err?) + return Smf.write(midi, opts) +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> the rendered audio Decoder (opts: DecodeOptions + RenderOptions) +function Midi.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local midi, err = Midi.decode(r, opts) + if not midi then + return nil, err + end + return Render.decoder(midi, opts) +end + +-- ------------------------------------------------------------------------------------------------ extras +-- render(midi, opts?) -> Decoder | nil, Err (also works on a Midi built by hand with Types.Midi.new) +function Midi.render(midi: Types.Midi, opts: RenderOptions?): (Types.Decoder?, Err.Err?) + return Render.decoder(midi, opts) +end + +-- tickToSeconds(midi, tick, track?) -> seconds (track: format 2's per-track tempo map) +function Midi.tickToSeconds(midi: Types.Midi, tick: number, track: number?): number + return Render.seconds(Render.tempoMap(midi, track), tick) +end + +-- tempoMap(midi, track?) -> { ticks, secs, us, division } (change points) +Midi.tempoMap = Render.tempoMap +Midi.seconds = Render.seconds + +-- length(midi) -> seconds to the last event (what python mido's MidiFile.length reports for formats 0 / 1) +function Midi.length(midi: Types.Midi): number + return Render.length(midi) +end + +-- text(data) -> the bytes of a text meta event as a string +Midi.text = Smf.text + +return Midi diff --git a/src/Formats/music/mod/init.luau b/src/Formats/music/mod/init.luau new file mode 100644 index 0000000..7f4eb88 --- /dev/null +++ b/src/Formats/music/mod/init.luau @@ -0,0 +1,361 @@ +--!strict +-- music/mod: ProTracker / NoiseTracker / StarTrekker MOD modules (the 31-sample "M.K." family: M.K., M!K!, FLT4, +-- 4CHN .. 9CHN, 10CH .. 32CH, xxCN, CD81, OKTA / OCTA, TDZx; 15-sample Soundtracker files when asked for by name or +-- extension). Written from the ProTracker 2.3 documentation. Reads into the codecs/Tracker Module and plays through +-- its engine (Module:render() / open() -> an audio Decoder). Writes 31-sample MODs (M.K. / xCHN / xxCH) from "mod" +-- modules, and from XM modules that fit (one sample per instrument, effects 0..F, 64-row patterns). +-- Not supported: FLT8's split 4 + 4 channel patterns (read as 8 plain channels), the Amiga hardware low-pass filter +-- (E0x), PowerPacker-packed files. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Tracker = require("@formats/codecs/Tracker") + +-- ------------------------------------------------------------------------------------------------ contract +local Mod = { + name = "mod", + category = "music", + extensions = { "mod", "m15", "stk", "nst" }, + mime = { "audio/x-mod", "audio/mod" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" }, + caps = { decode = true, encode = true, render = true, channels = { 1, 32 } }, +} + +export type DecodeOptions = { + maxBytes: number?, -- refuse bigger sample data in total (default 64 MB of f32 samples) +} +export type EncodeOptions = {} + +-- ------------------------------------------------------------------------------------------------ constants +local Pcm = Tracker.Pcm +local Tables = Tracker.Tables + +local FIXED: { [string]: number } = { + ["M.K."] = 4, + ["M!K!"] = 4, + ["M&K!"] = 4, + ["N.T."] = 4, + ["FLT4"] = 4, + ["FLT8"] = 8, + ["CD81"] = 8, + ["OKTA"] = 8, + ["OCTA"] = 8, + ["EXO4"] = 4, + ["EXO8"] = 8, +} + +-- channels from the 4-byte signature at 1080, or nil +local function signatureChannels(sig: string): number? + local fixed = FIXED[sig] + if fixed then + return fixed + end + local d = string.match(sig, "^(%d)CHN$") + if d then + local n = tonumber(d) :: number + return if n >= 1 then n else nil + end + local dd = string.match(sig, "^(%d%d)C[HN]$") + if dd then + local n = tonumber(dd) :: number + return if n >= 1 and n <= 32 then n else nil + end + local t = string.match(sig, "^TDZ(%d)$") + if t then + local n = tonumber(t) :: number + return if n >= 1 then n else nil + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Mod.sniff(r: Bytes.Reader): number + if r:size() < 1084 then + return 0 + end + local sig = r:peek(4, 1080) + if signatureChannels(sig) then + return 0.8 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Mod.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local maxBytes = opts and opts.maxBytes or 2 ^ 26 + local size = r:size() + local sig = if size >= 1084 then r:peek(4, 1080) else "" + local channels = signatureChannels(sig) + local nsamples = 31 + if not channels then + -- a 15-sample Soundtracker module (no signature): only when the header is plausible + nsamples, channels = 15, 4 + end + local nch = channels :: number + local m = Tracker.newModule("mod", nch) + m.title = r:fixed(20) + local lengths: { number } = {} + for i = 1, nsamples do + local s = Tracker.newSample(r:fixed(22)) + local len = r:u16be() * 2 + local ft = r:u8() % 16 + local vol = r:u8() + local ls = r:u16be() * 2 + local ll = r:u16be() * 2 + if r.err then + return nil, r.err + end + if nsamples == 15 and (vol > 64 or ft ~= 0) then + return nil, Err.new(Err.CORRUPT, "not a MOD (bad sample header)") + end + s.finetune = (if ft >= 8 then ft - 16 else ft) * 16 + s.volume = math.min(vol, 64) + s.bits = 8 + if ll > 2 then + s.loopStart, s.loopEnd, s.loopType = ls, ls + ll, 1 + end + lengths[i] = len + m.samples[i] = s + end + local songLength = r:u8() + local restart = r:u8() + local order: { number } = {} + local maxPat = 0 + for i = 1, 128 do + local p = r:u8() + order[i] = p + maxPat = math.max(maxPat, p) + end + if r.err then + return nil, r.err + end + if songLength == 0 or songLength > 128 or maxPat >= 128 then + return nil, Err.new(Err.CORRUPT, "not a MOD (bad order list)") + end + if nsamples == 31 then + r:skip(4) + end + for i = 1, songLength do + m.order[i] = order[i] + end + m.restart = if restart < songLength then restart else 0 + m.meta.signature = if nsamples == 31 then sig else nil + m.flags.amigaLimits = nch == 4 + -- patterns + local npat = maxPat + 1 + local patBytes = 64 * nch * 4 + if not r:need(npat * patBytes) then + return nil, r.err + end + local buf = r.buf + for p = 0, npat - 1 do + local pat = Tracker.newPattern(64, nch) + local base = r.pos + p * patBytes + local d = pat.data + for i = 0, 64 * nch - 1 do + local o = base + i * 4 + local b0, b1, b2, b3 = buffer.readu8(buf, o), buffer.readu8(buf, o + 1), buffer.readu8(buf, o + 2), buffer.readu8(buf, o + 3) + local period = (b0 % 16) * 256 + b1 + local ins = (b0 // 16) * 16 + b2 // 16 + local q = i * 5 + buffer.writeu8(d, q, Tables.periodToNote(period)) + buffer.writeu8(d, q + 1, ins) + buffer.writeu8(d, q + 3, b2 % 16) + buffer.writeu8(d, q + 4, b3) + end + m.patterns[p + 1] = pat + end + r:skip(npat * patBytes) + -- sample data (8-bit signed; the last samples of a truncated file are cut short) + local total = 0 + for i = 1, nsamples do + local s = m.samples[i] + local len = math.min(lengths[i], r:remaining()) + total += len * 4 + if total > maxBytes then + return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit") + end + local data = Pcm.decode(buf, r.pos, len, { bits = 8, signed = true }) + if not data then + return nil, Err.new(Err.TRUNCATED, "sample data", r.pos) + end + r:skip(len) + s.data, s.length = data, len + if s.loopEnd > len then + s.loopEnd = len + if s.loopEnd - s.loopStart < 2 then + s.loopType, s.loopStart, s.loopEnd = 0, 0, 0 + end + end + end + m.meta.source = { format = "mod", samples = nsamples } + m.render = Tracker.renderMethod + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function writeName(w: Bytes.Writer, s: string, n: number) + local t = string.sub(s or "", 1, n) + w:string(t) + w:fill(0, n - #t) +end + +-- encode(module) -> MOD bytes. The module must be "mod", or an "xm" module whose instruments each map every note to +-- one sample; patterns must have 64 rows, at most 31 samples, effects 0..F. +function Mod.encode(m: any, _opts: EncodeOptions?): (buffer?, Err.Err?) + local ok, verr = Tracker.validate(m) + if not ok then + return nil, verr + end + if m.format ~= "mod" and m.format ~= "xm" then + return nil, Err.new(Err.UNSUPPORTED, "only mod and xm modules can be written as MOD (got " .. tostring(m.format) .. "); xm is the closest writable format") + end + local nch = m.channels + if nch > 32 then + return nil, Err.new(Err.ARG, "MOD holds at most 32 channels") + end + -- the sample for each instrument number + local smpOf: { any } = {} + if m.format == "xm" then + for i, ins in m.instruments do + local first = 0 + for n = 1, 120 do + local s = ins.sampleMap[n] + if s ~= 0 then + if first ~= 0 and s ~= first then + return nil, Err.new(Err.ARG, "instrument " .. i .. " uses several samples") + end + first = s + end + end + smpOf[i] = m.samples[first] or Tracker.newSample(ins.name) + end + else + for i, s in m.samples do + smpOf[i] = s + end + end + if #smpOf > 31 then + return nil, Err.new(Err.ARG, "MOD holds at most 31 samples") + end + local order: { number } = {} + for _, o in m.order do + if o == 255 then + break + elseif o ~= 254 then + table.insert(order, o) + end + end + if #order == 0 or #order > 128 then + return nil, Err.new(Err.ARG, "MOD needs 1..128 order entries") + end + local npat = #m.patterns + if npat > 100 then + return nil, Err.new(Err.ARG, "too many patterns for MOD") + end + for p, pat in m.patterns do + if pat.rows ~= 64 then + return nil, Err.new(Err.ARG, "pattern " .. (p - 1) .. " has " .. pat.rows .. " rows (MOD patterns have 64)") + end + end + local w = Bytes.writer(1084 + npat * 64 * nch * 4 + 65536) + writeName(w, m.title or "", 20) + local datas: { buffer } = {} + for i = 1, 31 do + local s = smpOf[i] + if s then + local len = math.min(s.length, 131070) + local pcm = Pcm.encode(s.data, len, { bits = 8, signed = true, channels = 1 }) + if s.channels == 2 then + -- mix stereo samples down + local mono = buffer.create(len * 4) + for k = 0, len - 1 do + buffer.writef32(mono, k * 4, (buffer.readf32(s.data, k * 8) + buffer.readf32(s.data, k * 8 + 4)) / 2) + end + pcm = Pcm.encode(mono, len, { bits = 8, signed = true }) + end + local even = len + len % 2 + local padded = buffer.create(even) + buffer.copy(padded, 0, pcm, 0, len) + datas[i] = padded + writeName(w, s.name or "", 22) + w:u16be(even // 2) + local ft = math.clamp(math.floor((s.finetune or 0) / 16 + 0.5), -8, 7) + w:u8(ft % 16) + w:u8(math.clamp(math.floor(s.volume), 0, 64)) + if s.loopType > 0 and s.loopEnd <= even then + w:u16be(s.loopStart // 2) + w:u16be(math.max(1, (s.loopEnd - s.loopStart) // 2)) + else + w:u16be(0) + w:u16be(1) + end + else + w:fill(0, 22) + w:u16be(0) + w:u8(0) + w:u8(0) + w:u16be(0) + w:u16be(1) + end + end + w:u8(#order) + w:u8(if m.restart < #order and m.restart > 0 then m.restart else 127) + for i = 1, 128 do + w:u8(order[i] or 0) + end + local sig + if nch == 4 then + sig = if npat > 64 then "M!K!" else "M.K." + elseif nch < 10 then + sig = nch .. "CHN" + else + sig = nch .. "CH" + end + w:string(sig) + for p = 1, npat do + local d = m.patterns[p].data + for i = 0, 64 * nch - 1 do + local q = i * 5 + local note, ins, fx, param = buffer.readu8(d, q), buffer.readu8(d, q + 1), buffer.readu8(d, q + 3), buffer.readu8(d, q + 4) + local period = if note >= 1 and note <= 120 then Tables.noteToPeriod(note) else 0 + if period > 4095 then + period = 0 + end + if fx > 15 then + fx, param = 0, 0 + end + if ins > 31 then + ins = 0 + end + w:u8((ins // 16) * 16 + period // 256) + w:u8(period % 256) + w:u8((ins % 16) * 16 + fx) + w:u8(param) + end + end + for i = 1, 31 do + if datas[i] then + w:bytes(datas[i]) + end + end + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function Mod.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Mod.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Mod diff --git a/src/Formats/music/s3m/init.luau b/src/Formats/music/s3m/init.luau new file mode 100644 index 0000000..f7a80f7 --- /dev/null +++ b/src/Formats/music/s3m/init.luau @@ -0,0 +1,241 @@ +--!strict +-- music/s3m: Scream Tracker 3 modules (SCRM, ST3 TECH.DOC; also files from Impulse Tracker / OpenMPT / Schism +-- Tracker). Reads into the codecs/Tracker Module and plays through its engine (Module:render() / open() -> an audio +-- Decoder). Supports: up to 32 PCM channels, 8 / 16-bit signed or unsigned, mono or stereo samples, loops, the panning +-- table, ST3.00 fast volume slides, every ST3 effect. Notes are stored one octave up (S3M C-4 = note 61 = the C5 +-- speed reference, as IT shows S3M files). +-- Not supported: AdLib (OPL) instruments and channels (read as silent), writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Tracker = require("@formats/codecs/Tracker") + +-- ------------------------------------------------------------------------------------------------ contract +local S3m = { + name = "s3m", + category = "music", + extensions = { "s3m" }, + mime = { "audio/s3m", "audio/x-s3m" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 32 } }, +} + +export type DecodeOptions = { + maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function S3m.sniff(r: Bytes.Reader): number + if r:size() >= 48 and r:peek(4, 44) == "SCRM" then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function S3m.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local maxBytes = opts and opts.maxBytes or 2 ^ 28 + if r:size() < 96 then + return nil, Err.new(Err.TRUNCATED, "header") + end + if r:peek(4, 44) ~= "SCRM" then + return nil, Err.new(Err.CORRUPT, "no SCRM signature") + end + local title = r:fixed(28) + r:seek(32) + local ordnum, insnum, patnum = r:u16le(), r:u16le(), r:u16le() + local flags, cwt, ffi = r:u16le(), r:u16le(), r:u16le() + r:seek(48) + local gv, speed, tempo, mv, _uc, dp = r:u8(), r:u8(), r:u8(), r:u8(), r:u8(), r:u8() + r:seek(64) + local chnset: { number } = {} + for i = 1, 32 do + chnset[i] = r:u8() + end + if r.err then + return nil, r.err + end + if ordnum > 256 or insnum > 256 or patnum > 256 then + return nil, Err.new(Err.CORRUPT, "bad header counts") + end + -- channels: enabled PCM channels (0..15); the count is the last used one + local nch = 0 + for i = 1, 32 do + local c = chnset[i] + if c < 16 then + nch = i + end + end + if nch == 0 then + return nil, Err.new(Err.UNSUPPORTED, "no PCM channels (AdLib only)") + end + local m = Tracker.newModule("s3m", nch) + m.title = title + m.speed = if speed > 0 and speed < 255 then speed else 6 + m.tempo = if tempo >= 33 then tempo else 125 + m.globalVolume = math.min(gv, 64) * 2 + m.mixVolume = math.max(mv % 128, 16) + if mv < 128 then + -- mono files play at 8 / 11 of the master volume (ST3's stereo boost is missing; OpenMPT does the same) + m.mixVolume = math.floor(m.mixVolume * 8 / 11 + 0.5) + end + m.linear = false + m.instrumentMode = false + m.flags.fastSlides = cwt == 0x1300 or bit32.band(flags, 64) ~= 0 + m.flags.amigaLimits = bit32.band(flags, 16) ~= 0 + m.meta.source = { format = "s3m", tracker = cwt, stereo = mv >= 128 } + -- orders, parapointers, panning + r:seek(96) + for i = 1, ordnum do + local o = r:u8() + table.insert(m.order, o) + end + local insPtr, patPtr = {}, {} + for i = 1, insnum do + insPtr[i] = r:u16le() * 16 + end + for i = 1, patnum do + patPtr[i] = r:u16le() * 16 + end + local pans: { number } = {} + if dp == 252 then + for i = 1, 32 do + pans[i] = r:u8() + end + end + if r.err then + return nil, r.err + end + -- drop trailing end markers; keep inner "+++" / "---" + while #m.order > 0 and m.order[#m.order] == 255 do + table.remove(m.order) + end + local stereo = mv >= 128 + for i = 1, nch do + local c = chnset[i] + local pan = 128 + if stereo then + pan = if c % 16 >= 8 then 0xCC else 0x33 + local p = pans[i] + if p and bit32.band(p, 0x20) ~= 0 then + pan = (p % 16) * 0x11 + end + end + m.channelPan[i] = pan + m.channelMute[i] = c >= 16 + end + -- samples + local total = 0 + local unsigned = ffi ~= 1 + for i = 1, insnum do + local s = Tracker.newSample() + m.samples[i] = s + local h = r:sub(insPtr[i], 80) + if h:size() < 80 then + return nil, Err.new(Err.TRUNCATED, "sample header " .. i, insPtr[i]) + end + local typ = h:u8() + h:skip(12) + local hi = h:u8() + local lo = h:u16le() + local len, ls, le = h:u32le(), h:u32le(), h:u32le() + local vol = h:u8() + h:skip(1) + local pack, sflags = h:u8(), h:u8() + local c2spd = h:u32le() + h:seek(48) + s.name = h:fixed(28) + s.volume = math.min(vol, 64) + s.c5speed = if c2spd > 0 then c2spd else 8363 + if typ == 1 and len > 0 and pack == 0 then + local bits = if bit32.band(sflags, 4) ~= 0 then 16 else 8 + local nchs = if bit32.band(sflags, 2) ~= 0 then 2 else 1 + local off = (hi * 65536 + lo) * 16 + len = math.min(len, 2 ^ 26) + -- a short file: keep what is there + local avail = math.max(0, r:size() - off) // (nchs * bits // 8) + len = math.min(len, avail) + total += len * nchs * 4 + if total > maxBytes then + return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit") + end + local data = Tracker.Pcm.decode(r.buf, r.base + off, len, { bits = bits, signed = not unsigned, channels = nchs, planar = true }) + if data then + s.data, s.length, s.bits, s.channels = data, len, bits, nchs + if bit32.band(sflags, 1) ~= 0 and le > ls then + s.loopStart, s.loopEnd, s.loopType = ls, math.min(le, len), 1 + end + end + end + end + -- patterns + for p = 1, patnum do + local pat = Tracker.newPattern(64, nch) + m.patterns[p] = pat + local ptr = patPtr[p] + if ptr > 0 then + local pr = r:sub(ptr) + local plen = pr:u16le() + pr = pr:sub(2, math.max(0, plen - 2)) + local d = pat.data + local row = 0 + while row < 64 and not pr:eof() do + local what = pr:u8() + if what == 0 then + row += 1 + else + local ch = what % 32 + local note, ins, vol, cmd, info = 0, 0, 0, 0, 0 + if bit32.band(what, 0x20) ~= 0 then + local nb = pr:u8() + ins = pr:u8() + if nb == 254 then + note = 254 + elseif nb < 254 and nb % 16 < 12 then + note = (nb // 16) * 12 + nb % 16 + 13 + if note > 120 then + note = 0 + end + end + end + if bit32.band(what, 0x40) ~= 0 then + vol = math.min(pr:u8(), 64) + 1 + end + if bit32.band(what, 0x80) ~= 0 then + cmd, info = pr:u8(), pr:u8() + if cmd > 26 then + cmd, info = 0, 0 + end + end + if ch < nch then + local o = (row * nch + ch) * 5 + buffer.writeu8(d, o, note) + buffer.writeu8(d, o + 1, ins) + buffer.writeu8(d, o + 2, vol) + buffer.writeu8(d, o + 3, cmd) + buffer.writeu8(d, o + 4, info) + end + end + end + end + end + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function S3m.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = S3m.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return S3m diff --git a/src/Formats/music/sf2/init.luau b/src/Formats/music/sf2/init.luau new file mode 100644 index 0000000..a7fcc20 --- /dev/null +++ b/src/Formats/music/sf2/init.luau @@ -0,0 +1,44 @@ +--!strict +-- music/sf2: SoundFont 2 banks (SoundFont 2.04 specification), read-only. A thin wrapper over codecs/SoundFont (the +-- parser and the TinySoundFont-port synth music/midi renders with). Supports: INFO, 16-bit samples (+ sm24 24-bit), +-- presets / instruments / sample headers with global zones, generator merging into playable regions. +-- Not supported: writing, SF3 (Ogg Vorbis samples), modulators (read past, not applied). +-- decode returns the SoundFont value (kind "soundfont"): pass it to music/midi render as opts.soundfont. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local SoundFont = require("@formats/codecs/SoundFont") + +-- ------------------------------------------------------------------------------------------------ contract +local Sf2 = { + name = "sf2", + category = "music", + extensions = { "sf2" }, + mime = { "audio/x-soundfont" }, + deps = { "core/Err", "core/Bytes", "codecs/SoundFont" }, + caps = { decode = true, encode = false, sm24 = true, sf3 = false }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + maxRegions: number?, -- default 10^6 + maxSamples: number?, -- default 2^28 +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Sf2.sniff(r: Bytes.Reader): number + return if SoundFont.sniff(r) then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Sf2.decode(r: Bytes.Reader, opts: DecodeOptions?): (SoundFont.SoundFont?, Err.Err?) + return SoundFont.parse(r, opts) +end + +-- ------------------------------------------------------------------------------------------------ extras +-- synth(sf?, sampleRate?, opts?) -> a synth State (codecs/SoundFont.Synth drives it) +Sf2.synth = SoundFont.synth +Sf2.fallback = SoundFont.fallback + +return Sf2 diff --git a/src/Formats/music/xm/init.luau b/src/Formats/music/xm/init.luau new file mode 100644 index 0000000..d2cbafa --- /dev/null +++ b/src/Formats/music/xm/init.luau @@ -0,0 +1,560 @@ +--!strict +-- music/xm: FastTracker 2 Extended Modules (XM 1.04, the "Extended Module: " format; also OpenMPT / MilkyTracker / +-- Skale files). Written from the XM specification and FT2 behaviour notes. Reads into the codecs/Tracker Module and +-- plays through its engine (Module:render() / open() -> an audio Decoder): up to 32 channels (more are read), 8 / 16-bit +-- delta samples, multi-sample instruments with volume / panning envelopes, fadeout and auto-vibrato, linear and Amiga +-- frequency tables, every FT2 effect and volume-column command. Writes XM from "xm" modules (byte-identical for files +-- in FT2's layout) and from "mod" modules (one instrument per sample, Amiga frequencies). +-- Not supported: ModPlug ADPCM samples (read as silence), OpenMPT's stereo-sample / extra-effect extensions on write. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Tracker = require("@formats/codecs/Tracker") + +-- ------------------------------------------------------------------------------------------------ contract +local Xm = { + name = "xm", + category = "music", + extensions = { "xm" }, + mime = { "audio/xm", "audio/x-xm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" }, + caps = { decode = true, encode = true, render = true, channels = { 1, 64 } }, +} + +export type DecodeOptions = { + maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) +} +export type EncodeOptions = { + tracker: string?, -- the tracker name field (default: the source file's, else "formats-luau") +} + +-- ------------------------------------------------------------------------------------------------ constants +local MAGIC = "Extended Module: " +local Pcm = Tracker.Pcm + +-- ------------------------------------------------------------------------------------------------ sniff +function Xm.sniff(r: Bytes.Reader): number + return if r:peek(17) == MAGIC then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function readEnvelope(r: Bytes.Reader): ({ number }, { number }) + local xs, ys = {}, {} + for i = 1, 12 do + xs[i] = r:u16le() + ys[i] = r:u16le() + end + return xs, ys +end + +local function makeEnvelope(xs: { number }, ys: { number }, n: number, typ: number, sus: number, ls: number, le: number, pan: boolean): any + local e = Tracker.newEnvelope() + n = math.min(n, 12) + for i = 1, n do + e.ticks[i] = xs[i] + e.values[i] = if pan then math.clamp(ys[i], 0, 64) - 32 else math.clamp(ys[i], 0, 64) + end + e.enabled = bit32.band(typ, 1) ~= 0 and n > 0 + e.sustain = bit32.band(typ, 2) ~= 0 + e.loop = bit32.band(typ, 4) ~= 0 + e.susStart, e.susEnd = sus + 1, sus + 1 + e.loopStart, e.loopEnd = ls + 1, le + 1 + -- the raw fields, for a faithful re-save + e.raw = { type = typ, sustain = sus, loopStart = ls, loopEnd = le, count = n } + return e +end + +function Xm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local maxBytes = opts and opts.maxBytes or 2 ^ 28 + if r:peek(17) ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "no XM signature") + end + r:skip(17) + local title = r:fixed(20) + r:skip(1) + local tracker = r:fixed(20) + local version = r:u16le() + local hdrStart = r:tell() + local hdrSize = r:u32le() + local songLen, restart, nch, npat, nins = r:u16le(), r:u16le(), r:u16le(), r:u16le(), r:u16le() + local flags, speed, bpm = r:u16le(), r:u16le(), r:u16le() + local orders = {} + for i = 1, 256 do + orders[i] = r:u8() + end + if r.err then + return nil, r.err + end + if nch < 1 or nch > 128 or npat > 256 or nins > 256 or songLen > 256 then + return nil, Err.new(Err.CORRUPT, "bad header counts") + end + if version < 0x0104 then + return nil, Err.new(Err.UNSUPPORTED, string.format("XM version %x (only 1.04 is supported)", version)) + end + local m = Tracker.newModule("xm", nch) + m.title = title + m.speed = if speed > 0 and speed < 256 then speed else 6 + m.tempo = if bpm >= 32 and bpm <= 999 then bpm else 125 + m.linear = bit32.band(flags, 1) ~= 0 + m.restart = restart + for i = 1, songLen do + m.order[i] = orders[i] + end + m.meta.tracker = tracker + m.meta.source = { format = "xm", tracker = tracker, version = version } + -- patterns + if not r:seek(hdrStart + hdrSize) then + return nil, r.err + end + for p = 1, npat do + local start = r:tell() + local plen = r:u32le() + r:u8() + local rows = r:u16le() + local psize = r:u16le() + if r.err then + return nil, r.err + end + if rows < 1 or rows > 256 then + return nil, Err.new(Err.CORRUPT, "pattern " .. (p - 1) .. " has " .. rows .. " rows", r.pos) + end + r:seek(start + plen) + local pat = Tracker.newPattern(rows, nch) + m.patterns[p] = pat + local pr = r:slice(psize) + if r.err then + return nil, r.err + end + local d = pat.data + if psize > 0 then + for i = 0, rows * nch - 1 do + local b = pr:u8() + local note, ins, vol, fx, param = 0, 0, 0, 0, 0 + if b >= 128 then + if bit32.band(b, 1) ~= 0 then + note = pr:u8() + end + if bit32.band(b, 2) ~= 0 then + ins = pr:u8() + end + if bit32.band(b, 4) ~= 0 then + vol = pr:u8() + end + if bit32.band(b, 8) ~= 0 then + fx = pr:u8() + end + if bit32.band(b, 16) ~= 0 then + param = pr:u8() + end + else + note, ins, vol, fx, param = b, pr:u8(), pr:u8(), pr:u8(), pr:u8() + end + if pr.err then + break -- a short pattern: the rest stays empty + end + if note == 97 then + note = 255 + elseif note > 96 then + note = 0 + end + if fx > 35 then + fx, param = 0, 0 + end + local o = i * 5 + buffer.writeu8(d, o, note) + buffer.writeu8(d, o + 1, ins) + buffer.writeu8(d, o + 2, vol) + buffer.writeu8(d, o + 3, fx) + buffer.writeu8(d, o + 4, param) + end + end + end + -- instruments and their samples + local total = 0 + for i = 1, nins do + local start = r:tell() + local isize = r:u32le() + local ins = Tracker.newInstrument(r:fixed(22)) + r:u8() + local ns = r:u16le() + if r.err then + -- a file cut inside the instruments: keep what was read + r.err = nil + break + end + m.instruments[i] = ins + ins.samples = {} + if ns == 0 then + r:seek(start + math.max(isize, 29)) + continue + end + if ns > 256 then + return nil, Err.new(Err.CORRUPT, "instrument " .. i .. " has " .. ns .. " samples") + end + local shSize = r:u32le() + local keymap = {} + for n = 1, 96 do + keymap[n] = r:u8() + end + local vx, vy = readEnvelope(r) + local px, py = readEnvelope(r) + local nv, np = r:u8(), r:u8() + local vs, vls, vle, ps, pls, ple = r:u8(), r:u8(), r:u8(), r:u8(), r:u8(), r:u8() + local vt, pt = r:u8(), r:u8() + ins.vibType, ins.vibSweep, ins.vibDepth, ins.vibRate = r:u8(), r:u8(), r:u8(), r:u8() + ins.fadeout = r:u16le() + if r.err then + return nil, r.err + end + ins.volEnv = makeEnvelope(vx, vy, nv, vt, vs, vls, vle, false) + ins.panEnv = makeEnvelope(px, py, np, pt, ps, pls, ple, true) + ins.headerSize = isize + r:seek(start + isize) + local base = #m.samples + local heads = {} + for k = 1, ns do + local hs = r:tell() + local len, ls, ll = r:u32le(), r:u32le(), r:u32le() + local vol, ft, typ, pan, rel, res = r:u8(), r:i8(), r:u8(), r:u8(), r:i8(), r:u8() + local nm = r:fixed(22) + r:seek(hs + math.max(shSize, 40)) + heads[k] = { len = len, ls = ls, ll = ll, vol = vol, ft = ft, typ = typ, pan = pan, rel = rel, res = res, name = nm } + end + if r.err then + return nil, r.err + end + for k = 1, ns do + local h = heads[k] + local s = Tracker.newSample(h.name) + local bits = if bit32.band(h.typ, 16) ~= 0 then 16 else 8 + local bps = bits // 8 + s.bits = bits + s.volume = math.min(h.vol, 64) + s.finetune = h.ft + s.relativeNote = h.rel + s.pan = h.pan + local frames = h.len // bps + if h.res == 0xAD then + -- ModPlug ADPCM: 16-byte table + 4 bits per sample (not decoded: silence of the right length) + local bytes = 16 + (h.len + 1) // 2 + r:skip(math.min(bytes, r:remaining())) + frames = h.len + s.data = buffer.create(frames * 4) + else + local avail = r:remaining() // bps + local got = math.min(frames, avail) + total += got * 4 + if total > maxBytes then + return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit") + end + local data = Pcm.decode(r.buf, r.pos, got, { bits = bits, signed = true, delta = true }) + r:skip(got * bps) + s.data = data or buffer.create(0) + frames = if data then got else 0 + end + s.length = frames + local lt = h.typ % 4 + if lt == 3 then + lt = 2 + end + if lt > 0 and h.ll > 0 then + s.loopStart = h.ls // bps + s.loopEnd = (h.ls + h.ll) // bps + s.loopType = lt + end + m.samples[base + k] = s + table.insert(ins.samples, base + k) + end + for n = 1, 120 do + local k = keymap[math.min(n, 96)] + ins.sampleMap[n] = if n <= 96 and k < ns then base + k + 1 else 0 + end + ins.keymap = keymap + end + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function writeName(w: Bytes.Writer, s: string?, n: number) + local t = string.sub(s or "", 1, n) + w:string(t) + w:fill(0, n - #t) +end + +-- the instruments to write: { name, samples = { sample table }, keymap = { 96 local indexes }, ins? } +local function instrumentsOf(m: any): ({ any }?, string?) + local out = {} + if m.format == "mod" then + for i, s in m.samples do + local km = table.create(96, 0) + out[i] = { name = s.name, samples = if s.length > 0 then { s } else {}, keymap = km, ins = nil } + end + return out + end + for i, ins in m.instruments do + local list: { number } = {} + if type(ins.samples) == "table" then + for _, g in ins.samples do + table.insert(list, g) + end + end + local index: { [number]: number } = {} + for k, g in list do + index[g] = k - 1 + end + local km = table.create(96, 0) + for n = 1, 96 do + local g = ins.sampleMap[n] or 0 + if g > 0 and m.samples[g] then + if index[g] == nil then + table.insert(list, g) + index[g] = #list - 1 + end + km[n] = index[g] + end + end + if #list > 255 then + return nil, "instrument " .. i .. " uses more than 255 samples" + end + local smps = {} + for k, g in list do + smps[k] = m.samples[g] or Tracker.newSample() + end + out[i] = { name = ins.name, samples = smps, keymap = km, ins = ins } + end + return out +end + +local function writeEnvelope(w: Bytes.Writer, e: any, pan: boolean) + local n = if e then math.min(#e.ticks, 12) else 0 + for i = 1, 12 do + if i <= n then + w:u16le(math.clamp(math.floor(e.ticks[i]), 0, 65535)) + w:u16le(math.clamp(math.floor(e.values[i] + (if pan then 32 else 0) + 0.5), 0, 64)) + else + w:u32le(0) + end + end +end + +-- envelope count, type, sustain, loop start, loop end +local function envelopeFields(e: any): (number, number, number, number, number) + if not e then + return 0, 0, 0, 0, 0 + end + local n = math.min(#e.ticks, 12) + local typ = (if e.enabled then 1 else 0) + (if e.sustain then 2 else 0) + (if e.loop then 4 else 0) + local raw = e.raw + if raw and raw.type % 8 == typ then + typ = raw.type -- keep unknown bits + end + local function idx(v: number): number + return math.clamp(math.floor(v) - 1, 0, math.max(0, n - 1)) + end + local sus = idx(e.susStart) + local ls, le = idx(e.loopStart), idx(e.loopEnd) + if raw and n == 0 then + sus, ls, le = raw.sustain, raw.loopStart, raw.loopEnd + end + return n, typ, sus, ls, le +end + +-- encode(module, opts) -> XM bytes ("xm" or "mod" modules) +function Xm.encode(m: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local ok, verr = Tracker.validate(m) + if not ok then + return nil, verr + end + if m.format ~= "xm" and m.format ~= "mod" then + return nil, Err.new(Err.UNSUPPORTED, "only xm and mod modules can be written as XM (got " .. tostring(m.format) .. ")") + end + local nch = m.channels + if nch > 64 then + return nil, Err.new(Err.ARG, "XM holds at most 64 channels") + end + local insts, ierr = instrumentsOf(m) + if not insts then + return nil, Err.new(Err.ARG, ierr or "bad instruments") + end + if #insts > 128 then + return nil, Err.new(Err.ARG, "XM holds at most 128 instruments") + end + if #m.patterns > 256 then + return nil, Err.new(Err.ARG, "XM holds at most 256 patterns") + end + local order: { number } = {} + for _, o in m.order do + if o == 255 then + break + elseif o ~= 254 then + table.insert(order, o) + end + end + if #order > 256 then + return nil, Err.new(Err.ARG, "XM holds at most 256 order entries") + end + local w = Bytes.writer(65536) + w:string(MAGIC) + writeName(w, m.title, 20) + w:u8(0x1A) + writeName(w, opts and opts.tracker or (m.meta and m.meta.tracker) or "formats-luau", 20) + w:u16le(0x0104) + w:u32le(276) + w:u16le(#order) + w:u16le(if m.restart < #order then m.restart else 0) + w:u16le(nch) + w:u16le(#m.patterns) + w:u16le(#insts) + w:u16le(if m.linear then 1 else 0) + w:u16le(m.speed) + w:u16le(math.clamp(math.floor(m.tempo), 32, 999)) + for i = 1, 256 do + w:u8(order[i] or 0) + end + -- patterns (every cell packed, as FT2-compatible writers may) + for _, pat in m.patterns do + local pk = Bytes.writer(pat.rows * nch * 2) + local d = pat.data + for i = 0, pat.rows * nch - 1 do + local o = i * 5 + local note, ins, vol, fx, param = buffer.readu8(d, o), buffer.readu8(d, o + 1), buffer.readu8(d, o + 2), buffer.readu8(d, o + 3), buffer.readu8(d, o + 4) + if note == 255 then + note = 97 + elseif note > 96 then + note = 0 + end + if m.format == "mod" then + vol = 0 + if fx > 15 then + fx, param = 0, 0 + end + end + if ins > 128 then + ins = 0 + end + local flags = 0x80 + (if note > 0 then 1 else 0) + (if ins > 0 then 2 else 0) + (if vol > 0 then 4 else 0) + (if fx > 0 then 8 else 0) + (if param > 0 then 16 else 0) + pk:u8(flags) + if note > 0 then + pk:u8(note) + end + if ins > 0 then + pk:u8(ins) + end + if vol > 0 then + pk:u8(vol) + end + if fx > 0 then + pk:u8(fx) + end + if param > 0 then + pk:u8(param) + end + end + local data = pk:finish() + if buffer.len(data) > 65535 then + return nil, Err.new(Err.ARG, "a pattern packs to more than 64 KB") + end + w:u32le(9) + w:u8(0) + w:u16le(pat.rows) + w:u16le(buffer.len(data)) + w:bytes(data) + end + -- instruments + for _, it in insts do + local ins = it.ins + local smps = it.samples + if #smps == 0 then + w:u32le(29) + writeName(w, it.name, 22) + w:u8(0) + w:u16le(0) + continue + end + w:u32le(263) + writeName(w, it.name, 22) + w:u8(0) + w:u16le(#smps) + w:u32le(40) + for n = 1, 96 do + w:u8(it.keymap[n]) + end + local ve, pe = ins and ins.volEnv, ins and ins.panEnv + writeEnvelope(w, ve, false) + writeEnvelope(w, pe, true) + local vn, vt, vs, vls, vle = envelopeFields(ve) + local pn, pt, ps, pls, ple = envelopeFields(pe) + w:u8(vn) + w:u8(pn) + w:u8(vs) + w:u8(vls) + w:u8(vle) + w:u8(ps) + w:u8(pls) + w:u8(ple) + w:u8(vt) + w:u8(pt) + w:u8(ins and ins.vibType or 0) + w:u8(ins and ins.vibSweep or 0) + w:u8(ins and ins.vibDepth or 0) + w:u8(ins and ins.vibRate or 0) + w:u16le(ins and math.clamp(ins.fadeout, 0, 0xFFF) or 0) + w:fill(0, 22) + local datas = {} + for k, s in smps do + local mono = s.data + if s.channels == 2 then + mono = buffer.create(s.length * 4) + for f = 0, s.length - 1 do + buffer.writef32(mono, f * 4, (buffer.readf32(s.data, f * 8) + buffer.readf32(s.data, f * 8 + 4)) / 2) + end + end + local bits = if s.bits == 16 then 16 else 8 + local bps = bits // 8 + datas[k] = Pcm.encode(mono, s.length, { bits = bits, signed = true, delta = true }) + local typ = (if bits == 16 then 16 else 0) + local ls, ll = 0, 0 + if s.loopType > 0 then + typ += s.loopType + ls, ll = s.loopStart * bps, (s.loopEnd - s.loopStart) * bps + end + local ft = s.finetune + local rel = s.relativeNote + if m.format == "mod" then + rel = 0 + end + w:u32le(s.length * bps) + w:u32le(ls) + w:u32le(ll) + w:u8(math.clamp(math.floor(s.volume), 0, 64)) + w:u8(math.clamp(math.floor(ft), -128, 127) % 256) + w:u8(typ) + w:u8(math.clamp(math.floor(s.pan or 128), 0, 255)) + w:u8(math.clamp(math.floor(rel), -128, 127) % 256) + w:u8(0) + writeName(w, s.name, 22) + end + for _, dd in datas do + w:bytes(dd) + end + end + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function Xm.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Xm.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Xm diff --git a/src/Formats/video/avi/init.luau b/src/Formats/video/avi/init.luau new file mode 100644 index 0000000..80545df --- /dev/null +++ b/src/Formats/video/avi/init.luau @@ -0,0 +1,299 @@ +--!strict +-- video/avi: AVI (Microsoft RIFF AVI 1.0, OpenDML 1.02). New in formats-luau, on containers/Avi. +-- Read: open() indexes every stream (OpenDML super / standard indexes, else idx1, else a movi scan; RIFF AVIX pieces +-- of files over 1 GB) and returns a VideoDecoder: video through the codecs/Video registry by FourCC (MJPEG, MPEG-1, +-- uncompressed BI_RGB 24 / 32-bit bottom-up or top-down, I420 / YV12; H.264 and others when a decoder is +-- registered), audio through the api's opts.openAudio hook (PCM, A-law / mu-law, IMA / MS ADPCM with its WAVEFORMATEX, +-- MP3 / MP2, AAC). Dropped frames (empty video chunks) keep their time slot. Avi.demux(r) gives the Demuxer. +-- Write: MJPEG video (copied from an MJPEG source, else every frame encoded; variable frame delays such as a GIF's +-- become a constant rate with repeated frames) plus PCM s16 audio, AVI 1.0 with idx1 and an odml / dmlh header. +-- Not supported: writing files over 1 GB (no AVIX pieces), palette changes (##pc chunks are skipped), text streams. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Avi = require("@formats/containers/Avi") +local Demux = require("@formats/containers/Demux") +local Video = require("@formats/codecs/Video") +local Source = require("@formats/codecs/Video/Source") + +-- ------------------------------------------------------------------------------------------------ contract +local AviFormat = { + name = "avi", + category = "video", + extensions = { "avi" }, + mime = { "video/x-msvideo", "video/avi" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Avi", "containers/Demux", "codecs/Video", "codecs/Video/Source" }, + caps = { decode = true, encode = true, streaming = true, video = { "mjpeg", "mpeg1", "rawvideo" }, audio = true, odml = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type OpenOptions = { + rgba: boolean?, -- nextFrame returns rgba8 (default false: the codec's native yuv420p; BI_RGB gives rgba8) + track: number?, -- the video track (stream index + 1) to decode + audio: boolean?, -- false: do not open the audio track + maxPixels: number?, + openAudio: any?, -- set by the api +} +export type EncodeOptions = { + quality: number?, -- MJPEG quality 1..100 (default 90) + reencode: boolean?, -- encode the frames even when the source is MJPEG + audio: boolean?, -- false: no audio (default: PCM s16 from the source's audio, when it has one) + video: boolean?, + maxFps: number?, -- the highest frame rate variable delays may need (default 100) +} + +-- ------------------------------------------------------------------------------------------------ constants +-- WAVEFORMATEX wFormatTag -> codec id +local AUDIO_TAGS: { [number]: string } = { + [0x0001] = "pcm", + [0x0002] = "adpcm_ms", + [0x0003] = "pcm_f", + [0x0006] = "pcm_alaw", + [0x0007] = "pcm_mulaw", + [0x0011] = "adpcm_ima_wav", + [0x0050] = "mp2", + [0x0055] = "mp3", + [0x00FF] = "aac", + [0x1610] = "aac", + [0x706D] = "aac", + [0x2000] = "ac3", + [0x2001] = "dts", + [0xF1AC] = "flac", +} + +-- ------------------------------------------------------------------------------------------------ sniff +function AviFormat.sniff(r: Bytes.Reader): number + if r:peek(4) == "RIFF" and r:peek(4, 8) == "AVI " then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function videoTrack(s: Avi.Stream, id: number): Types.Track + local f = s.strf + local t: any = { + id = id, + kind = "video", + codec = "", + codecTag = s.handler, + timescale = if s.scale > 0 then s.rate / s.scale else 25, + frameRate = if s.scale > 0 then s.rate / s.scale else 0, + default = true, + name = s.name, + frames = s.length, + } + if buffer.len(f) >= 40 then + local w = buffer.readi32(f, 4) + local h = buffer.readi32(f, 8) + local bits = buffer.readu16(f, 14) + local comp = buffer.readstring(f, 16, 4) + t.width = math.abs(w) + t.height = math.abs(h) + t.codecTag = comp + t.bitsPerPixel = bits + if comp == "\0\0\0\0" or comp == "DIB " or comp == "RGB " then + t.codec = "rawvideo" + t.pixelFormat = if bits == 32 then "bgra" else "bgr24" + t.flip = h > 0 + t.stride = ((math.abs(w) * bits + 31) // 32) * 4 + if bits ~= 24 and bits ~= 32 then + t.codec = "rawvideo_" .. bits + end + else + t.codec = Video.fromFourcc(comp) or Video.fromFourcc(s.handler) or string.lower((string.gsub(comp, "%z", ""))) + if comp == "YV12" then + t.pixelFormat = "yv12" + elseif t.codec == "rawvideo" then + t.pixelFormat = "yuv420p" + end + end + local size = buffer.readu32(f, 0) + if size > 40 and buffer.len(f) > 40 then + local c = buffer.create(buffer.len(f) - 40) + buffer.copy(c, 0, f, 40) + t.config = c + end + else + t.codec = Video.fromFourcc(s.handler) or string.lower(s.handler) + local fr = s.frame + t.width, t.height = fr[3] - fr[1], fr[4] - fr[2] + end + return t +end + +local function audioTrack(s: Avi.Stream, id: number): Types.Track + local f = s.strf + local t: any = { + id = id, + kind = "audio", + codec = "unknown", + codecTag = s.handler, + timescale = if s.scale > 0 then s.rate / s.scale else 1, + default = true, + name = s.name, + waveFormat = f, + } + if buffer.len(f) >= 16 then + local tag = buffer.readu16(f, 0) + t.channels = buffer.readu16(f, 2) + t.sampleRate = buffer.readu32(f, 4) + t.blockAlign = buffer.readu16(f, 12) + local bits = buffer.readu16(f, 14) + t.bitsPerSample = bits + if tag == 0xFFFE and buffer.len(f) >= 26 then + tag = buffer.readu16(f, 24) -- WAVE_FORMAT_EXTENSIBLE: the sub-format GUID's tag + end + t.formatTag = tag + local c = AUDIO_TAGS[tag] or string.format("wav_0x%04x", tag) + if c == "pcm" then + c = if bits == 8 then "pcm_u8" else "pcm_s" .. bits .. "le" + elseif c == "pcm_f" then + c = "pcm_f" .. bits .. "le" + end + t.codec = c + if buffer.len(f) >= 18 then + local cb = buffer.readu16(f, 16) + if cb > 0 and 18 + cb <= buffer.len(f) and c ~= "mp3" then + local cfg = buffer.create(cb) + buffer.copy(cfg, 0, f, 18, cb) + t.config = cfg + end + end + end + return t +end + +-- demux(r, opts?) -> the Demuxer | nil, Err +function AviFormat.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) + local ok, file, err = pcall(Avi.read, r.buf, r.base, r.limit) + if not ok then + return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(file)) + end + if not file then + return nil, err + end + local tracks: { Types.Track } = {} + local streams: { { any } } = {} + for i, s in file.streams do + local t: Types.Track? = nil + if s.type == "vids" then + t = videoTrack(s, i) + elseif s.type == "auds" then + t = audioTrack(s, i) + elseif s.type == "txts" then + t = { id = i, kind = "subtitle", codec = "text", timescale = if s.scale > 0 then s.rate / s.scale else 1 } + end + if t then + table.insert(tracks, t) + table.insert(streams, { s, t }) + end + end + local meta = { info = file.info, index = file.index, odml = file.odml ~= nil } + local dmx = Demux.new("avi", tracks, r.buf, meta) + -- packets in file order across streams: merge by offset + local items: { { number } } = {} + for k, st in streams do + local s: Avi.Stream, t: any = st[1], st[2] + local tick = s.start + for _, c in s.chunks do + local dur = if s.sampleSize > 0 then c.size / s.sampleSize else 1 + if t.kind == "audio" and s.sampleSize == 0 and (t.blockAlign or 0) > 0 and t.codec:sub(1, 3) == "pcm" then + dur = c.size / t.blockAlign + end + if c.size > 0 then + table.insert(items, { c.offset, k, tick, dur, if c.key then 1 else 0, c.size }) + tick += dur + elseif t.kind == "video" then + tick += 1 -- an empty video chunk: a dropped frame keeps its slot (empty audio chunks are padding) + end + end + end + table.sort(items, function(a: { number }, b: { number }): boolean + return a[1] < b[1] + end) + for _, it in items do + local t: any = streams[it[2]][2] + dmx:add(t.id, it[3], nil, it[4], it[5] == 1 or t.kind ~= "video" or t.codec == "mjpeg" or t.codec == "rawvideo", it[1], it[6]) + end + dmx:finish() + return dmx, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- encode(video, opts?) -> buffer | nil, Err +function AviFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: any = table.clone(opts or {}) + o.quality = o.quality or 90 + local streams, err = Source.streams(value, o, { + video = { copy = { mjpeg = true }, encode = "mjpeg" }, + audio = { copy = { pcm_s16le = true, pcm_u8 = true }, pcm = true }, + }) + if not streams then + return nil, err + end + local wstreams: { Avi.WStream } = {} + local width, height, usPerFrame = 0, 0, 0 + local frameDur = 0 + for _, s in streams do + if s.kind == "video" then + -- a constant frame rate: the shortest frame duration (variable delays repeat frames) + local num, den, packets = Source.constantRate(s, o.maxFps) + s.packets = packets + frameDur = den / num + width, height = s.width or 0, s.height or 0 + usPerFrame = 1e6 * frameDur + local bih = Bytes.writer(40) + bih:u32le(40) + bih:u32le(width) + bih:u32le(height) + bih:u16le(1) + bih:u16le(24) + bih:string("MJPG") + bih:u32le(width * height * 3) + bih:u32le(0) + bih:u32le(0) + bih:u32le(0) + bih:u32le(0) + table.insert(wstreams, { type = "vids", handler = "MJPG", scale = den, rate = num, sampleSize = 0, strf = bih:finish(), width = width, height = height, ckid = "dc" }) + else + local ch = s.channels or 1 + local bits = if s.codec == "pcm_u8" then 8 else 16 + local align = ch * bits // 8 + local rate = math.floor((s.sampleRate or 44100) + 0.5) + local wf = Bytes.writer(18) + wf:u16le(1) + wf:u16le(ch) + wf:u32le(rate) + wf:u32le(rate * align) + wf:u16le(align) + wf:u16le(bits) + wf:u16le(0) + table.insert(wstreams, { type = "auds", handler = "\0\0\0\0", scale = align, rate = rate * align, sampleSize = align, strf = wf:finish(), ckid = "wb" }) + end + end + -- chunks in time order (the video packets already repeated to the constant rate) + local chunks: { { any } } = {} + for _, item in Source.interleave(streams) do + table.insert(chunks, { item[1], item[2].data, true }) + end + local ok, buf = pcall(Avi.write, { streams = wstreams, microSecPerFrame = usPerFrame, width = width, height = height }, chunks) + if not ok then + return nil, Err.new(Err.ARG, "internal error: " .. tostring(buf)) + end + return buf, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> a VideoDecoder | nil, Err +function AviFormat.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local dmx, err = AviFormat.demux(r, opts) + if not dmx then + return nil, err + end + return Video.open(dmx, opts) +end + +return AviFormat diff --git a/src/Formats/video/h264/init.luau b/src/Formats/video/h264/init.luau new file mode 100644 index 0000000..978ad52 --- /dev/null +++ b/src/Formats/video/h264/init.luau @@ -0,0 +1,145 @@ +--!strict +-- video/h264: raw H.264 / AVC elementary streams (ITU-T H.264 Annex B byte stream: .h264 / .264 files, x264 / ffmpeg +-- `-f h264` output, the JVT conformance bitstreams). New in formats-luau. +-- Read: the stream cut into access units (codecs/H264.accessUnits) as a one-track Demuxer; open() returns a +-- VideoDecoder decoding through codecs/H264 (yuv420p frames in display order, numbered in output order since a raw +-- stream has no timestamps; the frame rate comes from the SPS VUI timing, else opts.frameRate, else 25). +-- Write: H.264 tracks copied from any video (MP4 / MKV samples are converted from length-prefixed NAL units to Annex B, +-- the avcC parameter sets put in front of every keyframe). Not supported: re-encoding other codecs to H.264 (there is +-- no H.264 encoder), and whatever codecs/H264 does not decode (interlaced, 4:2:2 / 4:4:4, > 8 bits: UNSUPPORTED). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Demux = require("@formats/containers/Demux") +local Video = require("@formats/codecs/Video") +local Source = require("@formats/codecs/Video/Source") +local H264 = require("@formats/codecs/H264") + +-- ------------------------------------------------------------------------------------------------ contract +local Format = { + name = "h264", + category = "video", + extensions = { "h264", "264", "avc", "jsv", "26l", "jvt" }, + mime = { "video/h264" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/Video", "codecs/Video/Source", "codecs/H264" }, + caps = { decode = true, encode = true, streaming = true, video = { "h264" }, depths = { 8 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type OpenOptions = { + rgba: boolean?, -- nextFrame returns rgba8 (default false: yuv420p) + maxPixels: number?, -- largest picture (default 2^22 luma samples) + frameRate: number?, -- frames per second when the stream has no VUI timing (default 25) + deblock: boolean?, -- false skips the deblocking filter (faster, not conformant) +} + +-- ------------------------------------------------------------------------------------------------ sniff +-- a start code then an SPS / AUD / SEI / PPS NAL header (forbidden bit 0) +function Format.sniff(r: Bytes.Reader): number + local s = r:peek(5) + if not s or #s < 4 then + return 0 + end + local hdr + if string.byte(s, 1) == 0 and string.byte(s, 2) == 0 and string.byte(s, 3) == 1 then + hdr = string.byte(s, 4) + elseif #s >= 5 and string.byte(s, 1) == 0 and string.byte(s, 2) == 0 and string.byte(s, 3) == 0 and string.byte(s, 4) == 1 then + hdr = string.byte(s, 5) + else + return 0 + end + if hdr >= 128 then + return 0 + end + local t = hdr % 32 + if t == 7 then + return 0.8 + elseif t == 9 or t == 6 or t == 8 then + return 0.5 + elseif t == 5 then + return 0.4 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- demux(r, opts?) -> the Demuxer (one video track, one packet per access unit) | nil, Err +function Format.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) + local buf, base, limit = r.buf, r.base, r.limit + local units = H264.accessUnits(buf, base, limit - base) + if #units == 0 then + return nil, Err.new(Err.CORRUPT, "no access units (no slices after a start code)", base) + end + local info = H264.info(buffer.readstring(buf, base, math.min(limit - base, 4096))) or {} + if info.interlaced or (info.chromaFormat and info.chromaFormat ~= 1) or (info.bitDepth and info.bitDepth ~= 8) then + -- still demuxable (remuxing works); decoding reports UNSUPPORTED + info.unsupported = true + end + local fps = info.frameRate or (opts and opts.frameRate) or 25 + if fps <= 0 or fps > 1000 then + fps = 25 + end + local track: Types.Track = { + id = 1, + kind = "video", + codec = "h264", + timescale = fps, + width = info.width, + height = info.height, + frameRate = fps, + profile = info.profile, + level = info.level, + ptsInOutputOrder = true, + default = true, + } + local dmx = Demux.new("h264", { track }, buf, { profile = info.profile, level = info.level }) + local k = 0 + for i = 1, #units, 3 do + dmx:add(1, k, k, 1, units[i + 2] or k == 0, units[i], units[i + 1]) + k += 1 + end + track.frames = k + dmx:finish() + return dmx, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- encode(video, opts?) -> an Annex B buffer of the source's H.264 track | nil, Err (UNSUPPORTED for other codecs) +function Format.encode(value: any, _opts: any?): (buffer?, Err.Err?) + local streams, err = Source.streams(value, { audio = false }, { video = { copy = { h264 = true } } }) + if not streams then + return nil, err + end + local s = streams[1] + if not s or s.codec ~= "h264" then + return nil, Err.new(Err.UNSUPPORTED, "only H.264 tracks can be written as a raw H.264 stream") + end + local parts = {} + for i, p in s.packets do + local data = p.data + if s.config then + local key = i == 1 or p.keyframe + local out, e = H264.toAnnexB(if key then s.config else nil, data) + if not out then + return nil, e + end + data = out + end + table.insert(parts, buffer.tostring(data)) + end + return buffer.fromstring(table.concat(parts)), nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> a VideoDecoder | nil, Err +function Format.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local dmx, err = Format.demux(r, opts) + if not dmx then + return nil, err + end + return Video.open(dmx, opts) +end + +return Format diff --git a/src/Formats/video/mkv/Mux.luau b/src/Formats/video/mkv/Mux.luau new file mode 100644 index 0000000..6eed3cc --- /dev/null +++ b/src/Formats/video/mkv/Mux.luau @@ -0,0 +1,285 @@ +--!strict +-- video/mkv/Mux: the Matroska / WebM muxer: EBML header, Segment with SeekHead, Info (1 ms TimecodeScale, Duration), +-- Tracks (CodecPrivate, DefaultDuration, Video / Audio settings, Opus CodecDelay / SeekPreRoll), Clusters of +-- SimpleBlocks (a new cluster at a video keyframe once the current one spans 2 s, and before the 16-bit relative +-- timestamp would overflow), and Cues (one CuePoint per cluster, on the video track when there is one). Streams come +-- from codecs/Video/Source (copied packets or encoded frames). Interpreted; never throws. +local Err = require("@formats/core/Err") +local Ebml = require("@formats/containers/Ebml") +local Video = require("@formats/codecs/Video") +local Source = require("@formats/codecs/Video/Source") +local Parse = require("@formats/video/mkv/Parse") + +local ID = Parse.ID +local Mux = {} + +local AUDIO_IDS: { [string]: string } = { + vorbis = "A_VORBIS", + opus = "A_OPUS", + flac = "A_FLAC", + mp3 = "A_MPEG/L3", + mp2 = "A_MPEG/L2", + mp1 = "A_MPEG/L1", + aac = "A_AAC", + ac3 = "A_AC3", + eac3 = "A_EAC3", + alac = "A_ALAC", + pcm_u8 = "A_PCM/INT/LIT", + pcm_s16le = "A_PCM/INT/LIT", + pcm_s24le = "A_PCM/INT/LIT", + pcm_s32le = "A_PCM/INT/LIT", + pcm_s16be = "A_PCM/INT/BIG", + pcm_s24be = "A_PCM/INT/BIG", + pcm_s32be = "A_PCM/INT/BIG", + pcm_f32le = "A_PCM/FLOAT/IEEE", + pcm_f64le = "A_PCM/FLOAT/IEEE", +} +Mux.AUDIO_IDS = AUDIO_IDS + +-- codecId(stream) -> the Matroska CodecID | nil +function Mux.codecId(kind: string, codec: string): string? + if kind == "video" then + local e = Video.entry(codec) + local m = e and e.matroska + return m and m[1] + end + return AUDIO_IDS[codec] +end + +local function pcmBits(codec: string): number? + local b = string.match(codec, "^pcm_[suf](%d+)") + if b then + return tonumber(b) + end + if codec == "pcm_u8" then + return 8 + end + return nil +end + +export type Options = { + webm: boolean?, + title: string?, + app: string?, + clusterSeconds: number?, -- default 2 +} + +-- mux(streams, opts) -> buffer | nil, Err +function Mux.mux(streams: { any }, opts: Options): (buffer?, Err.Err?) + local webm = opts.webm == true + local app = opts.app or "formats-luau" + local clusterSpan = opts.clusterSeconds or 2 + -- tracks + local ids: { string } = {} + local videoIndex = 0 + for i, s in streams do + local cid = Mux.codecId(s.kind, s.codec) + if not cid then + return nil, Err.new(Err.UNSUPPORTED, "no Matroska CodecID for " .. s.kind .. " codec " .. s.codec) + end + ids[i] = cid + if s.kind == "video" and videoIndex == 0 then + videoIndex = i + end + end + local order = Source.interleave(streams) + local duration = 0 + for _, s in streams do + for _, p in s.packets do + local e = p.pts + (p.duration or 0) + if e > duration then + duration = e + end + end + end + + -- segment body: Info, Tracks, Clusters, Cues (the SeekHead goes in front once their offsets are known) + local body = Ebml.writer(65536) + local infoAt = body:tell() + local info = body:open(ID.Info) + body:uint(ID.TimecodeScale, 1000000) + body:string(ID.MuxingApp, app) + body:string(ID.WritingApp, app) + if opts.title then + body:string(ID.Title, opts.title) + end + body:float(ID.Duration, duration * 1000) + body:close(info) + + local tracksAt = body:tell() + local tracks = body:open(ID.Tracks) + for i, s in streams do + local te = body:open(ID.TrackEntry) + body:uint(ID.TrackNumber, i) + body:uint(ID.TrackUID, i) + body:uint(ID.TrackType, if s.kind == "video" then 1 else 2) + body:uint(ID.FlagLacing, 0) + body:string(ID.Language, "und") + body:string(ID.CodecID, ids[i]) + if s.config and buffer.len(s.config) > 0 then + body:binary(ID.CodecPrivate, s.config) + end + if s.kind == "video" then + if s.frameRate and s.frameRate > 0 then + body:uint(ID.DefaultDuration, math.floor(1e9 / s.frameRate + 0.5)) + end + local v = body:open(ID.Video) + body:uint(ID.PixelWidth, s.width or 0) + body:uint(ID.PixelHeight, s.height or 0) + body:close(v) + else + if s.codec == "opus" then + local pre = 0 + local c = s.config + if c and buffer.len(c) >= 12 then + pre = buffer.readu16(c, 10) + end + body:uint(ID.CodecDelay, math.floor(pre * 1e9 / 48000 + 0.5)) + body:uint(ID.SeekPreRoll, 80000000) + end + local a = body:open(ID.Audio) + body:float(ID.SamplingFrequency, s.sampleRate or 48000) + body:uint(ID.Channels, s.channels or 1) + local bits = pcmBits(s.codec) or s.bitsPerSample + if bits and string.sub(s.codec, 1, 4) == "pcm_" then + body:uint(ID.BitDepth, bits) + end + body:close(a) + end + body:close(te) + end + body:close(tracks) + + -- clusters + local cues: { { number } } = {} -- { time ms, track, cluster offset in body } + local cl: number? = nil + local clTime = 0 + local clStart = 0 + for _, item in order do + local si: number, p = item[1], item[2] + local ms = math.floor(p.pts * 1000 + 0.5) + local isVideoKey = si == videoIndex and p.keyframe + local need = cl == nil + or ms - clTime > 30000 + or ms < clTime + or (isVideoKey and ms - clStart >= clusterSpan * 1000) + or (videoIndex == 0 and ms - clStart >= clusterSpan * 1000) + if need then + if cl then + body:close(cl) + end + local at = body:tell() + cl = body:open(ID.Cluster) + clTime = ms + clStart = ms + body:uint(ID.Timecode, ms) + if videoIndex == 0 or isVideoKey then + table.insert(cues, { ms, if videoIndex > 0 then videoIndex else si, at }) + end + end + local data: buffer = p.data + local hdr = Ebml.vintString(si, 1) + local rel = ms - clTime + local size = #hdr + 3 + buffer.len(data) + body:header(ID.SimpleBlock, size) + body:raw(hdr) + body:raw(string.char(rel // 256, rel % 256, if p.keyframe or streams[si].kind ~= "video" then 0x80 else 0)) + body:rawBuffer(data) + end + if cl then + body:close(cl) + end + local cuesAt = body:tell() + if #cues > 0 then + local c = body:open(ID.Cues) + for _, q in cues do + local cp = body:open(ID.CuePoint) + body:uint(ID.CueTime, q[1]) + local tp = body:open(ID.CueTrackPositions) + body:uint(ID.CueTrack, q[2]) + body:uint(ID.CueClusterPosition, q[3]) -- patched below by the SeekHead length + body:close(tp) + body:close(cp) + end + body:close(c) + end + local bodyBuf = body:finish() + + -- the SeekHead: its own length shifts every position, so build it until its size is stable + local function seekHead(shift: number): buffer + local w = Ebml.writer(256) + local sh = w:open(ID.SeekHead) + local entries = { { ID.Info, infoAt }, { ID.Tracks, tracksAt } } + if #cues > 0 then + table.insert(entries, { ID.Cues, cuesAt }) + end + for _, e in entries do + local sk = w:open(0x4DBB) + local idv = e[1] + local bytes = {} + while idv > 0 do + table.insert(bytes, 1, idv % 256) + idv = idv // 256 + end + w:header(0x53AB, #bytes) + for _, b in bytes do + w:raw(string.char(b)) + end + w:uint(0x53AC, e[2] + shift) + w:close(sk) + end + w:close(sh) + return w:finish() + end + local shift = 0 + local head = seekHead(0) + for _ = 1, 4 do + local n = buffer.len(head) + if n == shift then + break + end + shift = n + head = seekHead(shift) + end + shift = buffer.len(head) + -- cue cluster positions (relative to the segment data) must include the SeekHead: rewrite the Cues element + -- (its uint widths may grow, but Cues are last, so nothing after them moves) + if #cues > 0 then + local w = Ebml.writer(4096) + local c = w:open(ID.Cues) + for _, q in cues do + local cp = w:open(ID.CuePoint) + w:uint(ID.CueTime, q[1]) + local tp = w:open(ID.CueTrackPositions) + w:uint(ID.CueTrack, q[2]) + w:uint(ID.CueClusterPosition, q[3] + shift) + w:close(tp) + w:close(cp) + end + w:close(c) + local cuesBuf = w:finish() + local nb = buffer.create(cuesAt + buffer.len(cuesBuf)) + buffer.copy(nb, 0, bodyBuf, 0, cuesAt) + buffer.copy(nb, cuesAt, cuesBuf) + bodyBuf = nb + end + + -- the file + local out = Ebml.writer(buffer.len(bodyBuf) + 256) + local eb = out:open(ID.EBML) + out:uint(0x4286, 1) + out:uint(0x42F7, 1) + out:uint(0x42F2, 4) + out:uint(0x42F3, 8) + out:string(ID.DocType, if webm then "webm" else "matroska") + out:uint(0x4287, 4) + out:uint(0x4285, 2) + out:close(eb) + local seg = out:open(ID.Segment) + out:rawBuffer(head) + out:rawBuffer(bodyBuf) + out:close(seg) + return out:finish(), nil +end + +return Mux diff --git a/src/Formats/video/mkv/Parse.luau b/src/Formats/video/mkv/Parse.luau new file mode 100644 index 0000000..ce5b489 --- /dev/null +++ b/src/Formats/video/mkv/Parse.luau @@ -0,0 +1,681 @@ +--!strict +-- video/mkv/Parse: the Matroska / WebM demuxer: EBML header, Segment Info / Tracks / Cues / Tags / Chapters (titles +-- only), and every Cluster into a containers/Demux packet index: SimpleBlock and BlockGroup (BlockDuration, +-- ReferenceBlock -> not a keyframe), the three lacings (Xiph, EBML, fixed), header-stripping content compression, +-- clusters of unknown size (live streams). Times: every track's timescale is 1e9 / TimecodeScale (milliseconds by +-- default). Interpreted (it only walks headers); never throws. +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Ebml = require("@formats/containers/Ebml") +local Demux = require("@formats/containers/Demux") +local Video = require("@formats/codecs/Video") +local Deflate = require("@formats/codecs/Deflate") + +local Parse = {} + +-- element IDs +local ID = { + EBML = 0x1A45DFA3, + DocType = 0x4282, + Segment = 0x18538067, + SeekHead = 0x114D9B74, + Info = 0x1549A966, + TimecodeScale = 0x2AD7B1, + Duration = 0x4489, + Title = 0x7BA9, + MuxingApp = 0x4D80, + WritingApp = 0x5741, + DateUTC = 0x4461, + Tracks = 0x1654AE6B, + TrackEntry = 0xAE, + TrackNumber = 0xD7, + TrackUID = 0x73C5, + TrackType = 0x83, + FlagEnabled = 0xB9, + FlagDefault = 0x88, + FlagForced = 0x55AA, + FlagLacing = 0x9C, + DefaultDuration = 0x23E383, + Name = 0x536E, + Language = 0x22B59C, + LanguageBCP47 = 0x22B59D, + CodecID = 0x86, + CodecPrivate = 0x63A2, + CodecDelay = 0x56AA, + SeekPreRoll = 0x56BB, + Video = 0xE0, + PixelWidth = 0xB0, + PixelHeight = 0xBA, + DisplayWidth = 0x54B0, + DisplayHeight = 0x54BA, + ColourSpace = 0x2EB524, + Audio = 0xE1, + SamplingFrequency = 0xB5, + OutputSamplingFrequency = 0x78B5, + Channels = 0x9F, + BitDepth = 0x6264, + ContentEncodings = 0x6D80, + ContentEncoding = 0x6240, + ContentEncodingType = 0x5033, + ContentEncodingScope = 0x5032, + ContentCompression = 0x5034, + ContentCompAlgo = 0x4254, + ContentCompSettings = 0x4255, + ContentEncryption = 0x5035, + Cluster = 0x1F43B675, + Timecode = 0xE7, + SimpleBlock = 0xA3, + BlockGroup = 0xA0, + Block = 0xA1, + BlockDuration = 0x9B, + ReferenceBlock = 0xFB, + DiscardPadding = 0x75A2, + Cues = 0x1C53BB6B, + CuePoint = 0xBB, + CueTime = 0xB3, + CueTrackPositions = 0xB7, + CueTrack = 0xF7, + CueClusterPosition = 0xF1, + CueRelativePosition = 0xF0, + Tags = 0x1254C367, + Tag = 0x7373, + SimpleTag = 0x67C8, + TagName = 0x45A3, + TagString = 0x4487, + Targets = 0x63C0, + Chapters = 0x1043A770, + Attachments = 0x1941A469, + Void = 0xEC, + Crc32 = 0xBF, +} +Parse.ID = ID + +-- the top-level children of a Segment (an unknown-size Cluster ends where one of these starts) +local TOP: { [number]: boolean } = { + [ID.SeekHead] = true, + [ID.Info] = true, + [ID.Tracks] = true, + [ID.Cluster] = true, + [ID.Cues] = true, + [ID.Tags] = true, + [ID.Chapters] = true, + [ID.Attachments] = true, + [ID.Segment] = true, + [ID.EBML] = true, +} + +-- Matroska audio / subtitle CodecIDs -> our codec ids (video ids come from the codecs/Video registry) +local AUDIO: { [string]: string } = { + A_VORBIS = "vorbis", + A_OPUS = "opus", + A_FLAC = "flac", + ["A_MPEG/L3"] = "mp3", + ["A_MPEG/L2"] = "mp2", + ["A_MPEG/L1"] = "mp1", + A_AAC = "aac", + ["A_AAC/MPEG4/LC"] = "aac", + ["A_AAC/MPEG4/LC/SBR"] = "aac", + ["A_AAC/MPEG2/LC"] = "aac", + A_AC3 = "ac3", + A_EAC3 = "eac3", + A_DTS = "dts", + A_ALAC = "alac", + A_TTA1 = "tta", + A_WAVPACK4 = "wavpack", + ["A_MS/ACM"] = "acm", +} +local SUBS: { [string]: string } = { + ["S_TEXT/UTF8"] = "text", + ["S_TEXT/ASCII"] = "text", + ["S_TEXT/WEBVTT"] = "webvtt", + ["S_TEXT/ASS"] = "ass", + ["S_TEXT/SSA"] = "ssa", + ["S_ASS"] = "ass", + ["S_SSA"] = "ssa", + ["S_VOBSUB"] = "dvdsub", + ["S_HDMV/PGS"] = "pgs", +} + +-- codecFor(CodecID, bitDepth) -> our codec id +local function codecFor(id: string, kind: string, bits: number?): string + if kind == "video" then + return Video.fromMatroska(id) or string.lower((string.gsub(id, "^V_", ""))) + end + if id == "A_PCM/INT/LIT" then + return if bits == 8 then "pcm_u8" else "pcm_s" .. (bits or 16) .. "le" + elseif id == "A_PCM/INT/BIG" then + return if bits == 8 then "pcm_u8" else "pcm_s" .. (bits or 16) .. "be" + elseif id == "A_PCM/FLOAT/IEEE" then + return "pcm_f" .. (bits or 32) .. "le" + end + return AUDIO[id] or SUBS[id] or string.lower((string.gsub(id, "^[AS]_", ""))) +end +Parse.codecFor = codecFor + +type TrackInfo = Types.Track & { strip: buffer?, lacing: boolean?, defaultDurationNs: number? } + +local function parseVideo(buf: buffer, off: number, len: number, t: any) + for id, o, n in Ebml.children(buf, off, off + len) do + if id == ID.PixelWidth then + t.width = Ebml.uint(buf, o, n) + elseif id == ID.PixelHeight then + t.height = Ebml.uint(buf, o, n) + elseif id == ID.DisplayWidth then + t.displayWidth = Ebml.uint(buf, o, n) + elseif id == ID.DisplayHeight then + t.displayHeight = Ebml.uint(buf, o, n) + elseif id == ID.ColourSpace then + t.colourSpace = buffer.readstring(buf, o, math.min(n, 4)) + end + end +end + +local function parseAudio(buf: buffer, off: number, len: number, t: any) + for id, o, n in Ebml.children(buf, off, off + len) do + if id == ID.SamplingFrequency then + t.sampleRate = Ebml.float(buf, o, n) + elseif id == ID.OutputSamplingFrequency then + t.outputSampleRate = Ebml.float(buf, o, n) + elseif id == ID.Channels then + t.channels = Ebml.uint(buf, o, n) + elseif id == ID.BitDepth then + t.bitsPerSample = Ebml.uint(buf, o, n) + end + end +end + +-- ContentEncodings: header stripping (algo 3) and zlib (algo 0) are supported; bzip / lzo compression and encryption +-- are not +local function parseEncodings(buf: buffer, off: number, len: number, t: any): string? + for id, o, n in Ebml.children(buf, off, off + len) do + if id == ID.ContentEncoding then + local etype = 0 + local scope = 1 + for id2, o2, n2 in Ebml.children(buf, o, o + n) do + if id2 == ID.ContentEncodingScope then + scope = Ebml.uint(buf, o2, n2) + elseif id2 == ID.ContentEncodingType then + etype = Ebml.uint(buf, o2, n2) + elseif id2 == ID.ContentCompression then + local algo, settings = 0, nil + for id3, o3, n3 in Ebml.children(buf, o2, o2 + n2) do + if id3 == ID.ContentCompAlgo then + algo = Ebml.uint(buf, o3, n3) + elseif id3 == ID.ContentCompSettings then + settings = Ebml.binary(buf, o3, n3) + end + end + if algo == 3 then + t.strip = settings + elseif algo == 0 then + t.zlib = scope -- 1: frames, 2: CodecPrivate + else + return "content compression algorithm " .. algo + end + elseif id2 == ID.ContentEncryption then + return "encrypted track" + end + end + if etype ~= 0 then + return "encrypted track" + end + end + end + return nil +end + +local function parseTracks(buf: buffer, off: number, len: number, scaleNs: number): ({ TrackInfo }, { [number]: string }) + local tracks: { TrackInfo } = {} + local problems: { [number]: string } = {} + for id, o, n in Ebml.children(buf, off, off + len) do + if id == ID.TrackEntry then + local t: any = { id = 0, kind = "data", codec = "", timescale = 1e9 / scaleNs, default = true, lacing = true, language = "eng" } + local ttype, codecId = 0, "" + local problem: string? = nil + for id2, o2, n2 in Ebml.children(buf, o, o + n) do + if id2 == ID.TrackNumber then + t.id = Ebml.uint(buf, o2, n2) + elseif id2 == ID.TrackUID then + t.uid = Ebml.uint(buf, o2, n2) + elseif id2 == ID.TrackType then + ttype = Ebml.uint(buf, o2, n2) + elseif id2 == ID.FlagDefault then + t.default = Ebml.uint(buf, o2, n2) ~= 0 + elseif id2 == ID.FlagEnabled then + t.enabled = Ebml.uint(buf, o2, n2) ~= 0 + elseif id2 == ID.FlagLacing then + t.lacing = Ebml.uint(buf, o2, n2) ~= 0 + elseif id2 == ID.DefaultDuration then + t.defaultDurationNs = Ebml.uint(buf, o2, n2) + elseif id2 == ID.Name then + t.name = Ebml.string(buf, o2, n2) + elseif id2 == ID.Language then + t.language = Ebml.string(buf, o2, n2) + elseif id2 == ID.CodecID then + codecId = Ebml.string(buf, o2, n2) + elseif id2 == ID.CodecPrivate then + t.config = Ebml.binary(buf, o2, n2) + elseif id2 == ID.CodecDelay then + t.codecDelay = Ebml.uint(buf, o2, n2) / 1e9 + elseif id2 == ID.SeekPreRoll then + t.seekPreRoll = Ebml.uint(buf, o2, n2) / 1e9 + elseif id2 == ID.Video then + parseVideo(buf, o2, n2, t) + elseif id2 == ID.Audio then + parseAudio(buf, o2, n2, t) + elseif id2 == ID.ContentEncodings then + problem = parseEncodings(buf, o2, n2, t) + end + end + if t.zlib and bit32.band(t.zlib, 2) ~= 0 and t.config then + local c = Deflate.zlib(t.config) + if c then + t.config = c + else + problem = "bad zlib-compressed CodecPrivate" + end + end + t.kind = if ttype == 1 then "video" elseif ttype == 2 then "audio" elseif ttype == 17 then "subtitle" else "data" + t.codecTag = codecId + t.codec = codecFor(codecId, t.kind, t.bitsPerSample) + if t.kind == "audio" then + t.sampleRate = t.sampleRate or 8000 + t.channels = t.channels or 1 + end + if t.defaultDurationNs and t.defaultDurationNs > 0 and t.kind == "video" then + t.frameRate = 1e9 / t.defaultDurationNs + end + if t.id > 0 then + table.insert(tracks, t) + if problem then + problems[t.id] = problem + end + end + end + end + return tracks, problems +end + +local function parseInfo(buf: buffer, off: number, len: number, meta: { [string]: any }): (number, number?) + local scale, duration = 1000000, nil + for id, o, n in Ebml.children(buf, off, off + len) do + if id == ID.TimecodeScale then + scale = Ebml.uint(buf, o, n) + elseif id == ID.Duration then + duration = Ebml.float(buf, o, n) + elseif id == ID.Title then + meta.title = Ebml.string(buf, o, n) + elseif id == ID.MuxingApp then + meta.muxingApp = Ebml.string(buf, o, n) + elseif id == ID.WritingApp then + meta.writingApp = Ebml.string(buf, o, n) + end + end + if scale <= 0 then + scale = 1000000 + end + return scale, duration +end + +local function parseCues(buf: buffer, off: number, len: number, segData: number): { { time: number, track: number, position: number } } + local cues = {} + for id, o, n in Ebml.children(buf, off, off + len) do + if id == ID.CuePoint then + local time = 0 + local positions = {} + for id2, o2, n2 in Ebml.children(buf, o, o + n) do + if id2 == ID.CueTime then + time = Ebml.uint(buf, o2, n2) + elseif id2 == ID.CueTrackPositions then + local tr, pos = 0, 0 + for id3, o3, n3 in Ebml.children(buf, o2, o2 + n2) do + if id3 == ID.CueTrack then + tr = Ebml.uint(buf, o3, n3) + elseif id3 == ID.CueClusterPosition then + pos = Ebml.uint(buf, o3, n3) + end + end + table.insert(positions, { tr, pos }) + end + end + for _, p in positions do + table.insert(cues, { time = time, track = p[1], position = segData + p[2] }) + end + end + end + return cues +end + +local function parseTags(buf: buffer, off: number, len: number, meta: { [string]: any }) + local tags = meta.tags or {} + meta.tags = tags + for id, o, n in Ebml.children(buf, off, off + len) do + if id == ID.Tag then + for id2, o2, n2 in Ebml.children(buf, o, o + n) do + if id2 == ID.SimpleTag then + local name, value = nil, nil + for id3, o3, n3 in Ebml.children(buf, o2, o2 + n2) do + if id3 == ID.TagName then + name = Ebml.string(buf, o3, n3) + elseif id3 == ID.TagString then + value = Ebml.string(buf, o3, n3) + end + end + if name and value and tags[string.lower(name)] == nil then + tags[string.lower(name)] = value + end + end + end + end + end +end + +type Ctx = { + buf: buffer, + dmx: any, + byNum: { [number]: TrackInfo }, + scaleNs: number, + err: string?, + maxPackets: number, +} + +-- one Block / SimpleBlock payload at [off, off + len): track, relative timecode, flags, lacing +local function block(ctx: Ctx, off: number, len: number, clusterTime: number, simple: boolean, keyHint: boolean?, durTicks: number?, discardNs: number?) + local buf = ctx.buf + local limit = off + len + local tn, tl = Ebml.vint(buf, off, limit) + if not tn or not tl or tn < 0 or off + tl + 3 > limit then + return + end + local p = off + tl + local rel = buffer.readu8(buf, p) * 256 + buffer.readu8(buf, p + 1) + if rel >= 32768 then + rel -= 65536 + end + local flags = buffer.readu8(buf, p + 2) + p += 3 + local t = ctx.byNum[tn] + if not t then + return + end + local key = if simple then bit32.band(flags, 0x80) ~= 0 else (keyHint ~= false) + if t.kind == "audio" or t.kind == "subtitle" then + key = true + end + local pts = clusterTime + rel + local lacing = bit32.band(bit32.rshift(flags, 1), 3) + local sizes: { number } = {} + if lacing == 0 then + sizes[1] = limit - p + else + if p >= limit then + return + end + local count = buffer.readu8(buf, p) + 1 + p += 1 + if lacing == 1 then -- Xiph + local total = 0 + for k = 1, count - 1 do + local s = 0 + while true do + if p >= limit then + return + end + local b = buffer.readu8(buf, p) + p += 1 + s += b + if b ~= 255 then + break + end + end + sizes[k] = s + total += s + end + sizes[count] = limit - p - total + elseif lacing == 3 then -- EBML + local s, l = Ebml.vint(buf, p, limit) + if not s or not l or s < 0 then + return + end + p += l + sizes[1] = s + local total = s + for k = 2, count - 1 do + local d, dl = Ebml.svint(buf, p, limit) + if not d or not dl then + return + end + p += dl + s += d + if s < 0 then + return + end + sizes[k] = s + total += s + end + sizes[count] = limit - p - total + else -- fixed + local each = (limit - p) // count + for k = 1, count do + sizes[k] = each + end + end + if sizes[count] < 0 then + return + end + end + -- frames after the first of a lace: the track's default duration + local stepTicks = 0 + if t.defaultDurationNs and t.defaultDurationNs > 0 then + stepTicks = t.defaultDurationNs / ctx.scaleNs + elseif durTicks and #sizes > 0 then + stepTicks = durTicks / #sizes + end + local dmx = ctx.dmx + for k, s in sizes do + if p + s > limit then + return + end + if dmx.n >= ctx.maxPackets then + ctx.err = "too many packets" + return + end + local d = if #sizes == 1 then durTicks else (if stepTicks > 0 then stepTicks else nil) + local kf = key and (k == 1 or t.kind ~= "video") + local strip = t.strip + local z = (t :: any).zlib + if z and bit32.band(z, 1) ~= 0 then + local out = Deflate.zlib(buf, p, s) + if out then + dmx:addData(tn, pts + (k - 1) * stepTicks, nil, d, kf, out) + end + elseif strip then + local nb = buffer.create(buffer.len(strip) + s) + buffer.copy(nb, 0, strip) + buffer.copy(nb, buffer.len(strip), buf, p, s) + dmx:addData(tn, pts + (k - 1) * stepTicks, nil, d, kf, nb) + else + dmx:add(tn, pts + (k - 1) * stepTicks, nil, d, kf, p, s) + end + if discardNs and k == #sizes then + dmx:setExtra("discardPadding", discardNs / 1e9) + end + p += s + end +end + +-- a Cluster's children from off to limit (an unknown-size cluster: until a top-level ID); returns where it ended +local function cluster(ctx: Ctx, off: number, limit: number, unknown: boolean): number + local buf = ctx.buf + local pos = off + local time = 0 + while pos < limit and not ctx.err do + local id, size, data = Ebml.header(buf, pos, limit) + if not id or not size or not data then + return limit + end + if unknown and TOP[id] then + return pos + end + if size < 0 then + size = limit - data -- an unknown-size child: to the end + end + if data + size > limit then + size = limit - data + end + if id == ID.Timecode then + time = Ebml.uint(buf, data, size) + elseif id == ID.SimpleBlock then + block(ctx, data, size, time, true) + elseif id == ID.BlockGroup then + local bo, bl = -1, 0 + local ref, dur, discard = false, nil, nil + for id2, o2, n2 in Ebml.children(buf, data, data + size) do + if id2 == ID.Block then + bo, bl = o2, n2 + elseif id2 == ID.ReferenceBlock then + ref = true + elseif id2 == ID.BlockDuration then + dur = Ebml.uint(buf, o2, n2) + elseif id2 == ID.DiscardPadding then + discard = Ebml.int(buf, o2, n2) + end + end + if bo >= 0 then + block(ctx, bo, bl, time, false, not ref, dur, discard) + end + end + pos = data + size + end + return pos +end + +export type Options = { maxPackets: number? } + +-- parse(buf, base, limit, opts) -> a Demux | nil, Err +function Parse.parse(buf: buffer, base: number, limit: number, opts: Options?): (any, Err.Err?) + local id, size, data = Ebml.header(buf, base, limit) + if id ~= ID.EBML or not size or not data then + return nil, Err.new(Err.CORRUPT, "not an EBML file", base) + end + if size < 0 then + return nil, Err.new(Err.CORRUPT, "EBML header of unknown size", base) + end + local docType = "matroska" + for cid, o, n in Ebml.children(buf, data, math.min(limit, data + size)) do + if cid == ID.DocType then + docType = Ebml.string(buf, o, n) + end + end + if docType ~= "matroska" and docType ~= "webm" then + return nil, Err.new(Err.UNSUPPORTED, "EBML document type " .. docType) + end + local pos = data + size + -- the Segment (skip anything else at the top level) + local segData, segEnd = -1, limit + while pos < limit do + local sid, ssize, sdata = Ebml.header(buf, pos, limit) + if not sid or not ssize or not sdata then + break + end + if sid == ID.Segment then + segData = sdata + segEnd = if ssize < 0 or sdata + ssize > limit then limit else sdata + ssize + break + end + if ssize < 0 then + break + end + pos = sdata + ssize + end + if segData < 0 then + return nil, Err.new(Err.TRUNCATED, "no Segment") + end + local meta: { [string]: any } = { docType = docType } + local scaleNs, duration = 1000000, nil :: number? + local tracks: { TrackInfo } = {} + local problems: { [number]: string } = {} + local cuesAt: { number } = {} + local clusters: { { number } } = {} + -- first pass: the top-level elements (clusters are walked after Info / Tracks, which may come later via SeekHead) + pos = segData + while pos < segEnd do + local cid, csize, cdata = Ebml.header(buf, pos, segEnd) + if not cid or not csize or not cdata then + break + end + local unknown = csize < 0 + local cend = if unknown or cdata + csize > segEnd then segEnd else cdata + csize + if cid == ID.Info then + local d + scaleNs, d = parseInfo(buf, cdata, cend - cdata, meta) + duration = d + elseif cid == ID.Tracks then + tracks, problems = parseTracks(buf, cdata, cend - cdata, scaleNs) + elseif cid == ID.Cluster then + if unknown then + -- find its end: walk children until a top-level ID + local p = cdata + while p < segEnd do + local xid, xsize, xdata = Ebml.header(buf, p, segEnd) + if not xid or not xsize or not xdata or TOP[xid] then + break + end + if xsize < 0 then + p = segEnd + break + end + p = math.min(segEnd, xdata + xsize) + end + cend = p + end + table.insert(clusters, { cdata, cend }) + elseif cid == ID.Cues then + table.insert(cuesAt, cdata) + table.insert(cuesAt, cend - cdata) + elseif cid == ID.Tags then + parseTags(buf, cdata, cend - cdata, meta) + end + if cend <= pos then + break + end + pos = cend + end + if #tracks == 0 then + return nil, Err.new(Err.CORRUPT, "no tracks") + end + -- track timescales follow the final TimecodeScale (Info may follow Tracks) + local byNum: { [number]: TrackInfo } = {} + for _, t in tracks do + t.timescale = 1e9 / scaleNs + byNum[t.id] = t + end + local dmx = Demux.new(if docType == "webm" then "webm" else "mkv", tracks :: any, buf, meta) + local ctx: Ctx = { buf = buf, dmx = dmx, byNum = byNum, scaleNs = scaleNs, err = nil, maxPackets = opts and opts.maxPackets or 2 ^ 24 } + for _, c in clusters do + cluster(ctx, c[1], c[2], false) + if ctx.err then + return nil, Err.new(Err.LIMIT, ctx.err) + end + end + if duration then + dmx.duration = duration * scaleNs / 1e9 + end + local cues = {} + for k = 1, #cuesAt, 2 do + for _, c in parseCues(buf, cuesAt[k], cuesAt[k + 1], segData) do + c.time = c.time * scaleNs / 1e9 + table.insert(cues, c) + end + end + meta.cues = cues + meta.timecodeScale = scaleNs + for tid, msg in problems do + local t = byNum[tid] + t.unsupported = msg + end + dmx:finish() + return dmx, nil +end + +return Parse diff --git a/src/Formats/video/mkv/init.luau b/src/Formats/video/mkv/init.luau new file mode 100644 index 0000000..be9766a --- /dev/null +++ b/src/Formats/video/mkv/init.luau @@ -0,0 +1,160 @@ +--!strict +-- video/mkv: Matroska and WebM (the Matroska specification / RFC 9559, the WebM container guidelines). New in +-- formats-luau, on containers/Ebml. +-- Read: open() demuxes the whole file into a packet index (SimpleBlock / BlockGroup, Xiph / EBML / fixed lacing, +-- header-stripping and zlib compression, unknown-size clusters, Cues and Tags in meta) and returns a VideoDecoder: video +-- through the codecs/Video registry (VP8 with inter frames, MJPEG, MPEG-1, raw; H.264 when registered), audio +-- through the api's opts.openAudio hook (Opus, Vorbis, FLAC, MP3, PCM, AAC, ... reach the audio formats), text +-- subtitle tracks as cues (Mkv.subtitles). Mkv.demux(r) gives the Demuxer alone. +-- Write: WebM (opts.format = "webm" or a .webm destination: VP8 / VP9 / AV1 video and Opus / Vorbis audio, copied +-- from the source since VP8 is decode-only) and Matroska (any registered video codec copied, else MJPEG encoded from +-- the frames; audio copied, else PCM s16), with SeekHead, Cues and Duration. +-- Not supported: bzip2 / lzo content compression and encryption (the track's packets are left as stored, +-- track.unsupported says why), chapters / attachments (skipped), writing subtitles. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Video = require("@formats/codecs/Video") +local Source = require("@formats/codecs/Video/Source") +local Parse = require("@formats/video/mkv/Parse") +local Mux = require("@formats/video/mkv/Mux") + +-- ------------------------------------------------------------------------------------------------ contract +local Mkv = { + name = "mkv", + category = "video", + extensions = { "mkv", "webm", "mka", "mk3d" }, + mime = { "video/x-matroska", "video/webm", "audio/x-matroska", "audio/webm" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ebml", "containers/Demux", "codecs/Deflate", "codecs/Video", "codecs/Video/Source" }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "rawvideo" }, audio = true, subtitles = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type OpenOptions = { + rgba: boolean?, -- nextFrame returns rgba8 images (default false: yuv420p from the codec) + track: number?, -- the video track number to decode (default: the first video track) + audio: boolean?, -- false: do not open the audio track + maxPackets: number?, -- refuse files with more packets (default 2^24) + maxPixels: number?, + openAudio: any?, -- set by the api: (demuxer, track) -> audio Decoder +} +export type EncodeOptions = { + format: string?, -- "webm" writes WebM (DocType webm, WebM codecs only); else Matroska + webm: boolean?, -- the same as format = "webm" + quality: number?, -- MJPEG quality 1..100 when frames are encoded (default 90) + reencode: boolean?, -- encode the frames even when the video track could be copied (Matroska: MJPEG) + video: boolean?, -- false: no video stream + audio: boolean?, -- false: no audio; true: fail if the audio cannot be written (default: dropped) + title: string?, + clusterSeconds: number?, -- target cluster length (default 2) +} + +-- ------------------------------------------------------------------------------------------------ constants +local WEBM_VIDEO = { vp8 = true, vp9 = true, av1 = true } +local WEBM_AUDIO = { opus = true, vorbis = true } + +-- ------------------------------------------------------------------------------------------------ sniff +function Mkv.sniff(r: Bytes.Reader): number + if r:peek(4) ~= "\26\69\223\163" then + return 0 + end + local head = r:peek(math.min(64, r:remaining())) + if string.find(head, "webm", 1, true) or string.find(head, "matroska", 1, true) then + return 1 + end + return 0.5 +end + +-- ------------------------------------------------------------------------------------------------ encode +-- encode(video, opts?) -> buffer | nil, Err: a VideoDecoder (F.load / F.video.open of any video or animated image) +-- or a Demuxer +function Mkv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: any = opts or {} + local webm = o.webm == true or (type(o.format) == "string" and string.lower(o.format) == "webm") + local want: Source.Want + if webm then + want = { video = { copy = WEBM_VIDEO }, audio = { copy = WEBM_AUDIO } } + else + local copy: { [string]: boolean } = {} + for id, e in Video.codecs do + if e.matroska then + copy[id] = true + end + end + want = { video = { copy = copy, encode = "mjpeg" }, audio = { copy = { ["*"] = true }, pcm = true } } + end + local so = table.clone(o) + so.quality = so.quality or 90 + local streams, err = Source.streams(value, so, want) + if not streams then + return nil, err + end + if not webm then + -- audio codecs Matroska cannot name: PCM instead + for i, s in streams do + if s.kind == "audio" and not Mux.codecId("audio", s.codec) then + local alt, aerr = Source.streams(value, { video = false, reencodeAudio = true }, { audio = { pcm = true } }) + if alt and alt[1] then + streams[i] = alt[1] + else + return nil, aerr + end + end + end + end + local ok, buf, merr = pcall(Mux.mux, streams, { webm = webm, title = o.title, clusterSeconds = o.clusterSeconds }) + if not ok then + return nil, Err.new(Err.ARG, "internal error: " .. tostring(buf)) + end + return buf, merr +end + +-- ------------------------------------------------------------------------------------------------ open +-- demux(r, opts?) -> the Demuxer (containers/Demux: tracks, packets, read, seek, count / get) | nil, Err +function Mkv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) + local ok, dmx, err = pcall(Parse.parse, r.buf, r.base, r.limit, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(dmx)) + end + return dmx, err +end + +-- open(r, opts?) -> a VideoDecoder (kind "video": nextFrame / seek / audio / demuxer) | nil, Err +function Mkv.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local dmx, err = Mkv.demux(r, opts) + if not dmx then + return nil, err + end + return Video.open(dmx, opts) +end + +-- ------------------------------------------------------------------------------------------------ extras +-- subtitles(demuxer, trackId?) -> Types.Subtitles from a text subtitle track (S_TEXT/UTF8, WebVTT, ASS text) | nil +function Mkv.subtitles(dmx: any, trackId: number?): Types.Subtitles? + local track = nil + for _, t in dmx.tracks do + if t.kind == "subtitle" and (trackId == nil or t.id == trackId) then + track = t + break + end + end + if not track then + return nil + end + local subs = Types.Subtitles.new() + subs.meta.codec = track.codec + subs.meta.language = track.language + for k = 1, dmx:count(track.id) do + local p = dmx:get(track.id, k) + if p then + local start = p.pts / track.timescale + local stop = start + (p.duration or 0) / track.timescale + table.insert(subs.cues, { start = start, stop = stop, text = buffer.tostring(p.data) }) + end + end + return subs +end + +return Mkv diff --git a/src/Formats/video/mp4/init.luau b/src/Formats/video/mp4/init.luau new file mode 100644 index 0000000..63d5924 --- /dev/null +++ b/src/Formats/video/mp4/init.luau @@ -0,0 +1,324 @@ +--!strict +-- video/mp4: MP4 / M4V / QuickTime MOV / 3GP (ISO/IEC 14496-12 / 14496-14, the QuickTime file format), on +-- containers/IsoBmff (ws-m4a's box parser, sample tables, fragments and muxer). New in formats-luau. +-- Read: every track's samples into a Demuxer (pts = dts + composition offset, moved by the edit list: the first +-- edit's media time is subtracted (B-frame delay, AAC priming), an initial empty edit added; sync samples as +-- keyframes; fragmented files too) and open() returns a VideoDecoder: video through the codecs/Video registry (MJPEG +-- 'jpeg' / 'mjpa' / mp4v 0x6C, MPEG-1, raw; H.264 'avc1' with its avcC when a decoder is registered), audio through +-- the api's opts.openAudio hook (AAC, ALAC (audio/m4a), MP3, Opus (dOps -> OpusHead), FLAC, PCM 'sowt' / 'twos' / +-- 'lpcm' / 'ipcm'). +-- Write: MP4 (or MOV with opts.format = "mov" / a .mov destination): H.264 / HEVC / AV1 / MJPEG / MPEG-4 video copied +-- from an ISO / Matroska source (their configurations are the same boxes), else MJPEG encoded from the frames (mp4v +-- object type 0x6C in MP4, 'jpeg' in MOV); AAC / ALAC / Opus / FLAC / MP3 audio copied, else PCM s16 ('sowt', MOV +-- only; MP4 drops other audio unless opts.audio = true, which fails). +-- Edit lists are written for a B-frame delay and an audio codec delay (AAC priming). Not supported: fragmented +-- writing, timed text tracks, encrypted tracks. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local IsoBmff = require("@formats/containers/IsoBmff") +local Demux = require("@formats/containers/Demux") +local Video = require("@formats/codecs/Video") +local Source = require("@formats/codecs/Video/Source") + +-- ------------------------------------------------------------------------------------------------ contract +local Mp4 = { + name = "mp4", + category = "video", + extensions = { "mp4", "m4v", "mov", "qt", "3gp", "3g2", "mj2" }, + mime = { "video/mp4", "video/quicktime", "video/3gpp" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "containers/Demux", "codecs/Video", "codecs/Video/Source" }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "mjpeg", "mpeg1", "h264" }, audio = true, fragments = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type OpenOptions = { + rgba: boolean?, + track: number?, -- the video track id (default: the first video track) + audio: boolean?, + maxPixels: number?, + maxSamples: number?, + openAudio: any?, -- set by the api +} +export type EncodeOptions = { + format: string?, -- "mov" writes QuickTime (brand 'qt '); else MP4 (brand 'isom') + quality: number?, -- MJPEG quality when frames are encoded (default 90) + reencode: boolean?, -- encode the frames to MJPEG even when the video could be copied + video: boolean?, + audio: boolean?, -- false: no audio; true: fail when the audio cannot be written +} + +-- ------------------------------------------------------------------------------------------------ constants +local IMAGE_BRANDS = { avif = true, avis = true, heic = true, heix = true, mif1 = true, msf1 = true, ["crx "] = true } +local AUDIO_BRANDS = { ["M4A "] = true, ["M4B "] = true, ["M4P "] = true } +-- copied video codecs -> sample entry (MP4 / MOV) +local VIDEO_ENTRY: { [string]: string } = { h264 = "avc1", hevc = "hvc1", av1 = "av01", vp9 = "vp09" } +local AUDIO_ENTRY: { [string]: string } = { aac = "mp4a", alac = "alac", opus = "Opus", flac = "fLaC", mp3 = "mp4a" } + +-- ------------------------------------------------------------------------------------------------ sniff +function Mp4.sniff(r: Bytes.Reader): number + local brand = IsoBmff.sniff(r) + if brand == nil or IMAGE_BRANDS[brand] then + return 0 + end + if AUDIO_BRANDS[brand] then + return 0.2 + end + if brand == "M4V " then + return 0.9 + end + return if brand == "" then 0.6 else 0.8 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- OpusHead (RFC 7845, little-endian) from an ISO dOps box payload (big-endian) +local function opusHead(d: buffer): buffer? + if buffer.len(d) < 11 then + return nil + end + local w = Bytes.writer(19 + buffer.len(d)) + w:string("OpusHead") + w:u8(1) + local ch = buffer.readu8(d, 1) + w:u8(ch) + w:u16le(buffer.readu8(d, 2) * 256 + buffer.readu8(d, 3)) + w:u32le(((buffer.readu8(d, 4) * 256 + buffer.readu8(d, 5)) * 256 + buffer.readu8(d, 6)) * 256 + buffer.readu8(d, 7)) + w:u16le(buffer.readu8(d, 8) * 256 + buffer.readu8(d, 9)) + local family = buffer.readu8(d, 10) + w:u8(family) + if family ~= 0 and buffer.len(d) >= 13 + ch then + w:bytes(d, 11, 2 + ch) -- stream count, coupled count, mapping + end + return w:finish() +end + +local function pcmCodec(t: any): string + local p = t.pcm + local bits = if p then p.bits else (t.bitsPerSample or 16) + if p and p.float then + return "pcm_f" .. bits .. (if p.little then "le" else "be") + end + if bits == 8 then + return if t.entry == "raw " then "pcm_u8" else "pcm_s8" + end + return "pcm_s" .. bits .. (if p == nil or p.little then "le" else "be") +end + +-- demux(r, opts?) -> the Demuxer | nil, Err +function Mp4.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) + local ok, movie, err = pcall(IsoBmff.parse, r, opts and opts.maxSamples and { maxSamples = opts.maxSamples } or nil) + if not ok then + return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(movie)) + end + if not movie then + return nil, err + end + local tracks: { Types.Track } = {} + local src = {} + for _, it in movie.tracks do + local t: any = { + id = it.id, + kind = it.kind, + codec = it.codec, + codecTag = it.entry, + timescale = it.timescale, + duration = it.duration, + language = it.language, + width = it.width, + height = it.height, + sampleRate = it.sampleRate, + channels = it.channels, + bitsPerSample = it.bitsPerSample, + config = it.config, + default = true, + } + if it.kind == "video" then + if not Video.entry(t.codec) then + t.codec = Video.fromFourcc(it.entry) or t.codec + end + if it.sampleCount > 0 and it.duration > 0 then + t.frameRate = it.sampleCount / it.duration + end + elseif it.kind == "audio" then + if it.codec == "pcm" then + t.codec = pcmCodec(it) + elseif it.codec == "ulaw" then + t.codec = "pcm_mulaw" + elseif it.codec == "alaw" then + t.codec = "pcm_alaw" + elseif it.codec == "opus" and it.config then + t.config = opusHead(it.config) + end + if it.skip and it.skip > 0 then + t.codecDelay = it.skip / it.timescale -- AAC priming: dropped like ffmpeg + end + end + table.insert(tracks, t) + table.insert(src, it) + end + local dmx = Demux.new(if movie.brand == "qt " then "mov" else "mp4", tracks, r.buf, { brand = movie.brand }) + -- samples in file order across tracks + local items: { { number } } = {} + for k, it in src do + -- the edit list moves presentation times: minus the first edit's media time (video: the B-frame delay; audio + -- keeps it as its codec delay), plus an initial empty edit (converted to media ticks) + local shift = 0 + if it.kind == "video" then + shift = -(it.skip or 0) + end + if it.delay and it.delay > 0 and movie.timescale and movie.timescale > 0 then + shift += it.delay / movie.timescale * it.timescale + end + for i = 1, it.sampleCount do + table.insert(items, { it.offsets[i], k, i, shift }) + end + end + table.sort(items, function(a: { number }, b: { number }): boolean + return a[1] < b[1] + end) + for _, e in items do + local it = src[e[2]] + local i = e[3] + local dts = it.dts[i] + local pts = dts + (if it.cts then it.cts[i] or 0 else 0) + e[4] + dmx:add(it.id, pts, dts + e[4], it.durations[i], it.sync == nil or it.sync[i] == true, it.offsets[i], it.sizes[i]) + end + dmx:finish() + return dmx, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- OpusHead -> dOps payload +local function dOps(head: buffer?): buffer? + if not head or buffer.len(head) < 19 then + return nil + end + local w = Bytes.writer(16) + w:u8(0) + local ch = buffer.readu8(head, 9) + w:u8(ch) + w:u16be(buffer.readu16(head, 10)) + w:u32be(buffer.readu32(head, 12)) + w:u16be(buffer.readu16(head, 16)) + local family = buffer.readu8(head, 18) + w:u8(family) + if family ~= 0 and buffer.len(head) >= 21 + ch then + w:bytes(head, 19, 2 + ch) + end + return w:finish() +end + +-- encode(video, opts?) -> buffer | nil, Err +function Mp4.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: any = table.clone(opts or {}) + o.quality = o.quality or 90 + local mov = type(o.format) == "string" and (string.lower(o.format) == "mov" or string.lower(o.format) == "qt") + local vcopy: { [string]: boolean } = { mjpeg = true } + for id in VIDEO_ENTRY do + vcopy[id] = true + end + local acopy: { [string]: boolean } = {} + for id in AUDIO_ENTRY do + acopy[id] = true + end + acopy.pcm_s16le = mov + local streams, err = Source.streams(value, o, { + video = { copy = vcopy, encode = "mjpeg" }, + audio = { copy = acopy, pcm = mov }, + }) + if not streams then + return nil, err + end + local mtracks = {} + for _, s in streams do + local scale = if s.kind == "audio" then math.floor((s.sampleRate or 48000) + 0.5) else 90000 + if s.kind == "video" and s.track and s.track.timescale and s.copied and s.track.timescale == math.floor(s.track.timescale) then + scale = s.track.timescale + end + local samples, durations, cts, sync = {}, {}, {}, {} + local anyCts = false + local firstDts = nil :: number? + for i, p in s.packets do + samples[i] = p.data + local dts = p.dts or p.pts + firstDts = firstDts or dts + local nextP = s.packets[i + 1] + local d = if nextP then (nextP.dts or nextP.pts) - dts else p.duration + durations[i] = math.max(0, math.floor(d * scale + 0.5)) + local c = math.floor((p.pts - dts) * scale + 0.5) + cts[i] = c + if c ~= 0 then + anyCts = true + end + if p.keyframe then + sync[i] = true + end + end + -- an edit list keeps the source's start: video decode times before 0 (B-frame delay), audio codec delay + local skip = 0 + if firstDts and firstDts < 0 then + skip = math.floor(-firstDts * scale + 0.5) + end + if s.kind == "audio" and s.track and s.track.codecDelay and s.copied then + skip = math.floor(s.track.codecDelay * scale + 0.5) + end + local t: any = { + kind = s.kind, + timescale = scale, + skip = if skip > 0 then skip else nil, + samples = samples, + durations = durations, + cts = if anyCts then cts else nil, + sync = sync, + width = s.width, + height = s.height, + sampleRate = s.sampleRate and math.floor(s.sampleRate + 0.5), + channels = s.channels, + } + if s.kind == "video" then + if s.codec == "mjpeg" then + t.entry = if mov then "jpeg" else "mp4v" + if not mov then + t.objectType = 0x6C + t.configBox = "esds" + t.config = buffer.create(0) + end + else + t.entry = VIDEO_ENTRY[s.codec] + t.config = s.config + end + else + if s.codec == "pcm_s16le" then + t.entry = "sowt" + t.bitsPerSample = 16 + else + t.entry = AUDIO_ENTRY[s.codec] + t.config = if s.codec == "opus" then dOps(s.config) else s.config + if s.codec == "mp3" then + t.objectType = 0x6B + t.configBox = "esds" + t.config = buffer.create(0) + end + end + end + if not t.entry then + return nil, Err.new(Err.UNSUPPORTED, "no sample entry for " .. s.kind .. " codec " .. s.codec) + end + table.insert(mtracks, t) + end + return IsoBmff.mux({ brand = if mov then "qt " else "isom", compatible = if mov then { "qt " } else { "isom", "iso2", "mp41" }, tracks = mtracks }) +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> a VideoDecoder | nil, Err +function Mp4.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local dmx, err = Mp4.demux(r, opts) + if not dmx then + return nil, err + end + return Video.open(dmx, opts) +end + +return Mp4 diff --git a/src/Formats/video/mpegps/init.luau b/src/Formats/video/mpegps/init.luau new file mode 100644 index 0000000..5ab6dac --- /dev/null +++ b/src/Formats/video/mpegps/init.luau @@ -0,0 +1,192 @@ +--!strict +-- video/mpegps: MPEG program streams (ISO/IEC 11172-1 system streams and 13818-1 program streams: .mpg / .mpeg / +-- .vob / VCD .dat). New in formats-luau, on containers/MpegPs. Video PES payloads are joined into the elementary +-- stream and cut into pictures (containers/MpegEs: one packet per picture with its sequence / GOP headers); a +-- picture takes the PTS of the PES it starts in, pictures without one get theirs from the GOP's temporal references. +-- Audio packets are the PES payloads (MP1 / MP2 / MP3 frames, AC-3, LPCM). open() returns a VideoDecoder: MPEG-1 +-- video through the codecs/Video registry (MPEG-2 detected and reported), audio through the api's opts.openAudio hook. +-- Timescale 90 kHz. Not supported: writing, H.264 in PS (packets are whole PES payloads), DVD navigation packets. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local MpegPs = require("@formats/containers/MpegPs") +local MpegEs = require("@formats/containers/MpegEs") +local Demux = require("@formats/containers/Demux") +local Video = require("@formats/codecs/Video") + +-- ------------------------------------------------------------------------------------------------ contract +local Ps = { + name = "mpegps", + category = "video", + extensions = { "mpg", "mpeg", "vob", "m1v", "mpv", "dat" }, + mime = { "video/mpeg" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/MpegPs", "containers/MpegEs", "containers/Demux", "codecs/Video" }, + caps = { decode = true, encode = false, streaming = true, video = { "mpeg1" }, audio = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type OpenOptions = { + rgba: boolean?, + track: number?, -- the video stream id to decode (0xE0.. ; default: the first video stream) + audio: boolean?, + maxPixels: number?, + openAudio: any?, -- set by the api +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Ps.sniff(r: Bytes.Reader): number + if r:peek(4) == "\0\0\1\186" then + return 0.9 + end + if r:peek(4) == "\0\0\1\179" then + return 0.5 -- an MPEG-1 / 2 video elementary stream (sequence header) + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the pictures of a video stream as packets: join the PES payloads, cut at pictures, place the timestamps +local function videoPackets(dmx: any, buf: buffer, s: MpegPs.Stream, t: any) + local total = 0 + for _, p in s.pes do + total += p.size + end + local es = buffer.create(total) + local starts: { number } = {} + local o = 0 + for i, p in s.pes do + starts[i] = o + buffer.copy(es, o, buf, p.offset, p.size) + o += p.size + end + local info = MpegEs.info(es, 0, total) + if info then + t.width, t.height, t.frameRate = info.width, info.height, info.frameRate + if info.mpeg2 then + t.codec = "mpeg2" + end + end + local pics = MpegEs.pictures(es, 0, total) + local fd = if t.frameRate and t.frameRate > 0 then 90000 / t.frameRate else 3600 + -- the PTS of the PES each picture starts in (only the first picture starting in a PES takes it) + local k = 1 + local used: { [number]: boolean } = {} + local ptsOf: { [number]: number } = {} + for i, pic in pics do + while k < #s.pes and starts[k + 1] <= pic.offset do + k += 1 + end + -- a PES whose payload starts inside this picture's headers also labels it + local pes = s.pes[k] + if pes and pes.pts and not used[k] then + used[k] = true + ptsOf[i] = pes.pts + end + end + -- fill the rest from the temporal references of each GOP (an elementary stream without any PTS: from 0) + local anchorPts, anchorTr = nil :: number?, 0 + local lastPts = nil :: number? + local timed = next(ptsOf) ~= nil + local count = 0 + for i, pic in pics do + if pic.gop then + anchorPts = nil + if not timed then + anchorPts, anchorTr = count * fd, 0 + end + end + if not timed and anchorPts == nil then + anchorPts, anchorTr = count * fd, pic.temporal + end + count += 1 + local pts = ptsOf[i] + if pts then + anchorPts, anchorTr = pts, pic.temporal + elseif anchorPts then + pts = anchorPts + (pic.temporal - anchorTr) * fd + elseif lastPts then + pts = lastPts + fd + end + if pts then + lastPts = pts + local d = buffer.create(pic.size) + buffer.copy(d, 0, es, pic.offset, pic.size) + dmx:addData(t.id, pts, nil, fd, pic.type == 1, d) + end + end +end + +-- demux(r, opts?) -> the Demuxer | nil, Err +function Ps.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) + if r:peek(4) == "\0\0\1\179" then + -- an MPEG-1 / 2 video elementary stream (.m1v): one video stream, no timestamps + local t: any = { id = 0xE0, kind = "video", codec = "mpeg1", codecTag = "es", timescale = 90000, streamId = 0xE0 } + local dmx = Demux.new("mpegps", { t }, r.buf, { elementary = true }) + videoPackets(dmx, r.buf, { id = 0xE0, kind = "video", codec = "mpeg1", pes = { { offset = r.base, size = r.limit - r.base } } }, t) + dmx:finish() + return dmx, nil + end + local ok, file, err = pcall(MpegPs.read, r.buf, r.base, r.limit) + if not ok then + return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(file)) + end + if not file then + return nil, err + end + local tracks: { Types.Track } = {} + for _, id in file.order do + local s = file.streams[id] + table.insert(tracks, { + id = id, + kind = s.kind :: any, + codec = s.codec, + codecTag = string.format("0x%02x", id % 256), + timescale = 90000, + streamId = id, + }) + end + local dmx = Demux.new("mpegps", tracks, r.buf, { mpeg2 = file.mpeg2, errors = file.errors }) + for i, id in file.order do + local s = file.streams[id] + local t: any = tracks[i] + if t.kind == "video" and (t.codec == "mpeg1" or t.codec == "mpeg2") then + videoPackets(dmx, r.buf, s, t) + else + local last = nil :: number? + for _, p in s.pes do + local pts = p.pts or last + if pts and p.size > 0 then + last = pts + dmx:add(id, pts, p.dts, nil, true, p.offset, p.size) + end + end + if t.codec == "mp2" and #s.pes > 0 then + local p = s.pes[1] + local b = r.buf + for i2 = p.offset, math.min(p.offset + p.size, r.limit) - 2 do + if buffer.readu8(b, i2) == 0xFF and buffer.readu8(b, i2 + 1) >= 0xE0 then + local layer = (buffer.readu8(b, i2 + 1) // 2) % 4 + t.codec = if layer == 1 then "mp3" elseif layer == 3 then "mp1" else "mp2" + break + end + end + end + end + end + dmx:finish() -- (read() without a track gives the video packets first, then the audio ones) + return dmx, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> a VideoDecoder | nil, Err +function Ps.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local dmx, err = Ps.demux(r, opts) + if not dmx then + return nil, err + end + return Video.open(dmx, opts) +end + +return Ps diff --git a/src/Formats/video/mpegts/init.luau b/src/Formats/video/mpegts/init.luau new file mode 100644 index 0000000..b07bf6f --- /dev/null +++ b/src/Formats/video/mpegts/init.luau @@ -0,0 +1,245 @@ +--!strict +-- video/mpegts: MPEG transport streams (ISO/IEC 13818-1: .ts / .m2ts segments, HLS). The demuxer is containers/MpegTs, +-- absorbed from mpegts-luau (resync, PAT / PMT with CRC, continuity checks, PES reassembly, 33-bit PTS / DTS +-- unwrapped); this format turns its units into a Demuxer (timescale 90 kHz; one PES = one packet: a picture as +-- muxed by ffmpeg, one or more audio frames) and returns a VideoDecoder: MPEG-1 video through the codecs/Video +-- registry (stream type 0x02 checked for an MPEG-2 sequence extension), H.264 when registered, audio (MP1 / MP2 / +-- MP3, AAC in ADTS) through the api's opts.openAudio hook. Keyframes: MPEG-1 / 2 I-pictures, H.264 IDR access units. +-- M2TS (192-byte packets with a 4-byte timestamp prefix) is read too. Not supported: writing, scrambled streams, +-- PES without PTS for video before the first one (dropped). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local MpegTs = require("@formats/containers/MpegTs") +local MpegEs = require("@formats/containers/MpegEs") +local Demux = require("@formats/containers/Demux") +local Video = require("@formats/codecs/Video") + +-- ------------------------------------------------------------------------------------------------ contract +local Ts = { + name = "mpegts", + category = "video", + extensions = { "ts", "m2ts", "mts", "tsv" }, + mime = { "video/mp2t" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/MpegTs", "containers/MpegEs", "containers/Demux", "codecs/Video" }, + caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "h264" }, audio = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type OpenOptions = { + rgba: boolean?, + track: number?, -- the video PID to decode (default: the first video stream of the PMT) + audio: boolean?, + maxPixels: number?, + openAudio: any?, -- set by the api +} + +-- ------------------------------------------------------------------------------------------------ constants +local CODEC: { [string]: string } = { + mpeg1video = "mpeg1", + mpeg2video = "mpeg2", + mpegaudio = "mp2", + aac = "aac", + aac_latm = "aac_latm", + h264 = "h264", + hevc = "hevc", + mpeg4 = "mpeg4", + ac3 = "ac3", + eac3 = "eac3", +} + +-- ------------------------------------------------------------------------------------------------ sniff +-- packetSize(r) -> 188 | 192 (M2TS) | 0, and the offset of the first sync byte: three sync bytes a packet apart +-- (fewer in a short file) within the first 2 KB +local function packetSize(r: Bytes.Reader): (number, number) + local n = r:remaining() + for start = 0, math.min(n, 2048) - 1 do + if r:peekU8(start) == 0x47 then + for _, size in { 188, 192 } do + local hits, need = 0, math.min(3, (n - start - 1) // size + 1) + for k = 0, 2 do + local at = start + k * size + if at < n and r:peekU8(at) == 0x47 then + hits += 1 + end + end + if hits >= need and (need >= 2 or start == 0) then + if size == 192 and start >= 4 then + return 192, start - 4 + elseif size == 188 then + return 188, start + end + end + end + end + end + return 0, 0 +end + +function Ts.sniff(r: Bytes.Reader): number + local s, off = packetSize(r) + if s == 0 then + return 0 + end + if off > 0 then + return 0.6 + end + return if r:remaining() >= 3 * s then 0.9 else 0.5 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the 188-byte packets of an M2TS file (192-byte packets: drop the 4-byte timestamps) +local function strip192(b: buffer, base: number, limit: number): buffer + local n = (limit - base) // 192 + local out = buffer.create(n * 188) + for i = 0, n - 1 do + buffer.copy(out, i * 188, b, base + i * 192 + 4, 188) + end + return out +end + +local function mpegAudioCodec(u: any): string + local d: buffer = u.data + for i = 0, math.min(buffer.len(d), 4096) - 2 do + if buffer.readu8(d, i) == 0xFF and buffer.readu8(d, i + 1) >= 0xE0 then + local layer = (buffer.readu8(d, i + 1) // 2) % 4 + return if layer == 1 then "mp3" elseif layer == 3 then "mp1" else "mp2" + end + end + return "mp2" +end + +-- demux(r, opts?) -> the Demuxer | nil, Err +function Ts.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) + local size, off = packetSize(r) + if size == 0 then + return nil, Err.new(Err.CORRUPT, "no transport stream sync", r.base) + end + local d = MpegTs.new() + if size == 192 then + local b = strip192(r.buf, r.base + off, r.limit) + d:push(b, 0, buffer.len(b)) + else + d:push(r.buf, r.base + off, r.limit - r.base - off) + end + d:flush() + local units = {} + while true do + local u = d:pull() + if u == nil then + break + end + table.insert(units, u) + end + if #units == 0 then + return nil, Err.new(Err.CORRUPT, "no PES units") + end + -- tracks: the PMT's streams, then PIDs found without one + local tracks: { Types.Track } = {} + local byPid: { [number]: any } = {} + local function track(pid: number, kind: string, codec: string, st: number, lang: string?): any + local t = byPid[pid] + if t then + return t + end + t = { + id = pid, + kind = if kind == "other" then "data" else kind, + codec = CODEC[codec] or codec, + codecTag = string.format("0x%02x", st), + timescale = 90000, + language = lang, + streamType = st, + } + byPid[pid] = t + table.insert(tracks, t) + return t + end + for _, s in d.streams do + track(s.pid, s.kind, s.codec, s.streamType, s.language) + end + for _, u in units do + track(u.pid, u.kind, u.codec, u.streamType, nil) + end + -- codec details from the first unit + local seen: { [number]: boolean } = {} + for _, u in units do + local t = byPid[u.pid] + if not seen[u.pid] then + seen[u.pid] = true + if t.codec == "unknown" or t.kind == "data" then + -- a private / unknown stream type: go by the PES stream id and the payload + local sid = u.streamId or 0 + if sid >= 0xE0 and sid <= 0xEF then + t.kind = "video" + local info = MpegEs.info(u.data, 0, buffer.len(u.data)) + t.codec = if info then (if info.mpeg2 then "mpeg2" else "mpeg1") elseif MpegEs.findStart(u.data, 0, math.min(buffer.len(u.data), 8)) then "h264" else "unknown" + elseif sid >= 0xC0 and sid <= 0xDF then + t.kind, t.codec = "audio", "mp2" + end + end + if t.codec == "mpeg1" or t.codec == "mpeg2" then + local info = MpegEs.info(u.data, 0, buffer.len(u.data)) + if info then + t.codec = if info.mpeg2 then "mpeg2" else "mpeg1" + t.width, t.height, t.frameRate = info.width, info.height, info.frameRate + end + elseif t.codec == "mp2" then + t.codec = mpegAudioCodec(u) + elseif t.codec == "aac" then + t.adts = true + local b: buffer = u.data + if buffer.len(b) >= 4 and buffer.readu8(b, 0) == 0xFF then + local rates = { 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350 } + t.sampleRate = rates[(buffer.readu8(b, 2) // 4) % 16 + 1] + t.channels = (buffer.readu8(b, 2) % 2) * 4 + buffer.readu8(b, 3) // 64 + end + end + end + end + local dmx = Demux.new("mpegts", tracks, r.buf, { stats = d.stats }) + local lastPts: { [number]: number } = {} + for _, u in units do + local t = byPid[u.pid] + local pts = u.pts90 or u.dts90 + if pts == nil then + local prev = lastPts[u.pid] + if prev and t.frameRate and t.frameRate > 0 then + pts = prev + 90000 / t.frameRate + else + pts = prev + end + end + if pts ~= nil then + lastPts[u.pid] = pts + local key = true + local data: buffer = u.data + if t.kind == "video" then + if t.codec == "mpeg1" or t.codec == "mpeg2" then + key = MpegEs.pictureType(data, 0, buffer.len(data)) == 1 + elseif t.codec == "h264" then + key = u.randomAccess or MpegEs.h264Key(data, 0, buffer.len(data)) + else + key = u.randomAccess + end + end + dmx:addData(u.pid, pts, u.dts90 or pts, nil, key, data) + end + end + dmx:finish() + return dmx, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> a VideoDecoder | nil, Err +function Ts.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local dmx, err = Ts.demux(r, opts) + if not dmx then + return nil, err + end + return Video.open(dmx, opts) +end + +return Ts diff --git a/src/Formats/video/y4m/init.luau b/src/Formats/video/y4m/init.luau new file mode 100644 index 0000000..a5f4c06 --- /dev/null +++ b/src/Formats/video/y4m/init.luau @@ -0,0 +1,209 @@ +--!strict +-- video/y4m: YUV4MPEG2 (the mjpegtools / ffmpeg raw video stream). New in formats-luau. +-- Read: the stream header (W H F I A C X tags) and every FRAME into a raw-video Demuxer; open() returns a VideoDecoder +-- with yuv420p frames (C420 / C420jpeg / C420mpeg2 / C420paldv as they are; C422 / C444 chroma averaged down; Cmono +-- with neutral chroma; 9..16-bit samples (C420p10, ...) scaled to 8 bits). Y4m.demux(r) gives the Demuxer. +-- Write: yuv420p 8-bit frames ("C420jpeg", as ffmpeg writes for yuv420p) from any video or animated image; rgba8 +-- frames are converted (BT.601 limited range); uneven frame times (a GIF's) become a constant rate with repeated frames. Not supported: interlaced field handling (the I tag is kept in meta), +-- alpha (C444alpha drops it). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Demux = require("@formats/containers/Demux") +local Video = require("@formats/codecs/Video") +local Source = require("@formats/codecs/Video/Source") + +-- ------------------------------------------------------------------------------------------------ contract +local Y4m = { + name = "y4m", + category = "video", + extensions = { "y4m" }, + mime = { "video/x-yuv4mpeg" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/Video", "codecs/Video/Source" }, + caps = { decode = true, encode = true, streaming = true, video = { "rawvideo" }, depths = { 8, 10, 12, 16 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type OpenOptions = { + rgba: boolean?, -- nextFrame returns rgba8 (default false: yuv420p) + maxPixels: number?, -- default 2^26 +} +export type EncodeOptions = { + frameRate: { number }?, -- { num, den } for the F tag, one frame per source frame (default: the constant rate of the + -- shortest frame, longer frames repeated) + maxFps: number?, -- the highest rate uneven frame times may need (default 100) +} + +-- ------------------------------------------------------------------------------------------------ constants +local MAGIC = "YUV4MPEG2 " +-- C tag -> pixel format, bits +local COLOR: { [string]: { any } } = { + ["420jpeg"] = { "yuv420p", 8 }, + ["420paldv"] = { "yuv420p", 8 }, + ["420mpeg2"] = { "yuv420p", 8 }, + ["420"] = { "yuv420p", 8 }, + ["422"] = { "yuv422p", 8 }, + ["444"] = { "yuv444p", 8 }, + ["444alpha"] = { "yuva444p", 8 }, + mono = { "gray", 8 }, +} +for _, b in { 9, 10, 12, 14, 16 } do + COLOR["420p" .. b] = { "yuv420p", b } + COLOR["422p" .. b] = { "yuv422p", b } + COLOR["444p" .. b] = { "yuv444p", b } + COLOR["mono" .. b] = { "gray", b } +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Y4m.sniff(r: Bytes.Reader): number + return if r:peek(10) == MAGIC then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function frameSize(pf: string, bits: number, w: number, h: number): number + local bps = if bits > 8 then 2 else 1 + local cw, ch = (w + 1) // 2, (h + 1) // 2 + if pf == "yuv420p" then + return (w * h + 2 * cw * ch) * bps + elseif pf == "yuv422p" then + return (w * h + 2 * cw * h) * bps + elseif pf == "yuv444p" then + return w * h * 3 * bps + elseif pf == "yuva444p" then + return w * h * 4 * bps + end + return w * h * bps +end + +-- demux(r, opts?) -> the raw-video Demuxer | nil, Err +function Y4m.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) + local buf, base, limit = r.buf, r.base, r.limit + local nl = -1 + for i = base, math.min(limit, base + 4096) - 1 do + if buffer.readu8(buf, i) == 10 then + nl = i + break + end + end + if limit - base < 10 or buffer.readstring(buf, base, 10) ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "not a YUV4MPEG2 stream", base) + end + if nl < 0 then + return nil, Err.new(Err.TRUNCATED, "no end of the stream header", base) + end + local header = buffer.readstring(buf, base + 10, nl - base - 10) + local w, h, fn, fd = 0, 0, 25, 1 + local ctag, itag, atag = "420jpeg", "p", "0:0" + local extra = {} + for tok in string.gmatch(header, "%S+") do + local k, v = string.sub(tok, 1, 1), string.sub(tok, 2) + if k == "W" then + w = tonumber(v) or 0 + elseif k == "H" then + h = tonumber(v) or 0 + elseif k == "F" then + local a, b = string.match(v, "^(%d+):(%d+)$") + if a and b and tonumber(a) > 0 and tonumber(b) > 0 then + fn, fd = tonumber(a) :: number, tonumber(b) :: number + end + elseif k == "C" then + ctag = v + elseif k == "I" then + itag = v + elseif k == "A" then + atag = v + elseif k == "X" then + table.insert(extra, v) + end + end + local color = COLOR[ctag] + if not color then + return nil, Err.new(Err.UNSUPPORTED, "colour space C" .. ctag) + end + if w <= 0 or h <= 0 or w > 65535 or h > 65535 then + return nil, Err.new(Err.CORRUPT, "bad frame size " .. w .. "x" .. h) + end + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, "frame of " .. w .. "x" .. h .. " pixels") + end + local pf, bits = color[1], color[2] + local size = frameSize(pf, bits, w, h) + local track: Types.Track = { + id = 1, + kind = "video", + codec = "rawvideo", + codecTag = "C" .. ctag, + timescale = fn / fd, + width = w, + height = h, + frameRate = fn / fd, + pixelFormat = pf, + bitDepth = bits, + default = true, + } + local meta = { interlace = itag, aspect = atag, extra = extra, colorTag = ctag } + local dmx = Demux.new("y4m", { track }, buf, meta) + local pos = nl + 1 + local k = 0 + while pos + 5 <= limit do + if buffer.readstring(buf, pos, 5) ~= "FRAME" then + return nil, Err.new(Err.CORRUPT, "expected FRAME", pos) + end + local e = -1 + for i = pos + 5, math.min(limit, pos + 4096) - 1 do + if buffer.readu8(buf, i) == 10 then + e = i + break + end + end + if e < 0 then + break + end + local data = e + 1 + if data + size > limit then + break -- a truncated last frame is dropped + end + dmx:add(1, k, k, 1, true, data, size) + k += 1 + pos = data + size + end + dmx:finish() + return dmx, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- encode(video, opts?) -> buffer | nil, Err +function Y4m.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local streams, err = Source.streams(value, { audio = false }, { video = { copy = nil, encode = "rawvideo" } }) + if not streams then + return nil, err + end + local s = streams[1] + local fn, fd, packets = Source.constantRate(s, opts and opts.maxFps) + if opts and type(opts.frameRate) == "table" then + fn, fd, packets = opts.frameRate[1], opts.frameRate[2], s.packets + end + s.packets = packets + local w = Bytes.writer(64 + #s.packets * (buffer.len(s.packets[1].data) + 6)) + w:string(string.format("YUV4MPEG2 W%d H%d F%d:%d Ip A1:1 C420jpeg XYSCSS=420JPEG\n", s.width or 0, s.height or 0, fn, fd)) + for _, p in s.packets do + w:string("FRAME\n") + w:bytes(p.data) + end + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> a VideoDecoder | nil, Err +function Y4m.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local dmx, err = Y4m.demux(r, opts) + if not dmx then + return nil, err + end + return Video.open(dmx, opts) +end + +return Y4m diff --git a/tests/audio/_encode_cases.luau b/tests/audio/_encode_cases.luau new file mode 100644 index 0000000..1e7bd23 --- /dev/null +++ b/tests/audio/_encode_cases.luau @@ -0,0 +1,12 @@ +-- tests/audio/_encode_cases: the files our ALAC / CAF writers produce for the reference check (tools/fixtures/m4a.py +-- runs tools/fixtures/_m4a_encode.luau over them; tests/audio/m4a.luau and caf.luau re-encode and compare). +return { + { name = "ours_alac16_stereo", container = "m4a", rate = 44100, frames = 4096 * 3 + 1234, channels = 2, bits = 16, seed = 1, tags = { title = "Our Title \u{e9}", artist = "formats-luau", album = "Tests", track = "5", tracktotal = "10", date = "2026", genre = "Test", comment = "round trip" } }, + { name = "ours_alac16_mono", container = "m4a", rate = 22050, frames = 5000, channels = 1, bits = 16, seed = 2 }, + { name = "ours_alac24_stereo", container = "m4a", rate = 48000, frames = 9000, channels = 2, bits = 24, seed = 3 }, + { name = "ours_alac16_6ch", container = "m4a", rate = 48000, frames = 4500, channels = 6, bits = 16, seed = 4 }, + { name = "ours_alac20_stereo", container = "m4a", rate = 96000, frames = 3000, channels = 2, bits = 20, seed = 5 }, + { name = "ours_caf_alac16", container = "caf", codec = "alac", rate = 44100, frames = 7000, channels = 2, bits = 16, seed = 6 }, + { name = "ours_caf_pcm16", container = "caf", codec = "pcm", rate = 44100, frames = 3000, channels = 2, bits = 16, seed = 7 }, + { name = "ours_caf_pcm24", container = "caf", codec = "pcm", rate = 48000, frames = 2000, channels = 1, bits = 24, seed = 8 }, +} diff --git a/tests/audio/_opus_cases.luau b/tests/audio/_opus_cases.luau new file mode 100644 index 0000000..1163827 --- /dev/null +++ b/tests/audio/_opus_cases.luau @@ -0,0 +1,42 @@ +-- tests/audio/_opus_cases: the inputs of the CELT encoder reference check (tools/fixtures/opus_celt.py runs +-- tools/fixtures/_opus_encode.luau over them; tests/audio/opus_encode.luau re-encodes and compares): a deterministic +-- music-like signal (chord + vibrato + chirp + clicks + a silent stretch) at a given rate / channel count. +local Types = require("@formats/Types") + +local Cases = {} + +Cases.list = { + { name = "celt_mono_64k", rate = 48000, channels = 1, seconds = 1.5, bitrate = 64000, minSnr = 15 }, + { name = "celt_stereo_128k", rate = 48000, channels = 2, seconds = 1.5, bitrate = 128000, minSnr = 15 }, + { name = "celt_stereo_256k", rate = 48000, channels = 2, seconds = 1, bitrate = 256000, minSnr = 22 }, + { name = "celt_mono_24k", rate = 48000, channels = 1, seconds = 1, bitrate = 24000, minSnr = 8 }, + { name = "celt_44k_stereo_96k", rate = 44100, channels = 2, seconds = 1, bitrate = 96000, minSnr = 0, tags = { title = "Celt \u{e9}", artist = "formats-luau", album = "Opus" } }, + { name = "celt_short", rate = 48000, channels = 1, seconds = 0.01, bitrate = 48000, minSnr = -100 }, +} + +function Cases.signal(c: any): Types.Audio + local n = math.floor(c.seconds * c.rate + 0.5) + local a = Types.Audio.new(c.rate, c.channels, n) + local s = 7 + for i = 0, n - 1 do + local t = i / c.rate + for ch = 0, c.channels - 1 do + s = (s * 48271) % 2147483647 + local v = 0.18 * math.sin(2 * math.pi * 220 * t + 2 * math.sin(2 * math.pi * 5 * t)) + v += 0.12 * math.sin(2 * math.pi * (277.2 + ch * 2) * t) + 0.1 * math.sin(2 * math.pi * 329.6 * t) + v += 0.08 * math.sin(2 * math.pi * (1000 + 3000 * t) * t) + v += 0.01 * (s / 2147483647 - 0.5) + if i % (c.rate // 4) < 30 then + v += 0.4 * (if (i // 5) % 2 == 0 then 1 else -1) + end + if t > 0.6 and t < 0.75 then + v = 0 -- digital silence (the encoder's silence frames) + end + buffer.writef32(a.samples, (i * c.channels + ch) * 4, v) + end + end + a.tags = c.tags or {} + return a +end + +return Cases diff --git a/tests/audio/_signal.luau b/tests/audio/_signal.luau new file mode 100644 index 0000000..4986a7e --- /dev/null +++ b/tests/audio/_signal.luau @@ -0,0 +1,42 @@ +-- tests/audio/_signal: the deterministic integer test signal of tools/fixtures/_m4a_signal.py (the same numbers), as +-- an interleaved integer array and as a Types.Audio (f32, exact for up to 24 bits). Used by the m4a / caf tests and the +-- fixture-time encoder runs (tools/fixtures/_m4a_encode.luau). +local Types = require("@formats/Types") + +local Signal = {} + +function Signal.ints(frames: number, channels: number, bits: number, seed: number): { number } + local s = seed + local peak = 2 ^ (bits - 1) - 1 + local out = table.create(frames * channels, 0) + local k = 1 + for i = 0, frames - 1 do + for c = 0, channels - 1 do + s = (s * 48271) % 2147483647 + local p1 = 97 + 31 * c + local tri = math.abs((i % p1) * 2 - p1) * 2 - p1 + local v = tri * (peak // (4 * p1)) + local p2 = 1500 + 200 * c + v += if (i // p2) % 2 == 0 then peak // 6 else -(peak // 6) + v += ((s // 65536) % 4096 - 2048) * (peak // 65536 + 1) + if i % 7001 < 3 then + v += peak // 2 + end + out[k] = math.clamp(v, -peak - 1, peak) + k += 1 + end + end + return out +end + +function Signal.audio(rate: number, frames: number, channels: number, bits: number, seed: number): Types.Audio + local ints = Signal.ints(frames, channels, bits, seed) + local a = Types.Audio.new(rate, channels, frames) + local scale = 1 / 2 ^ (bits - 1) + for i, v in ints do + buffer.writef32(a.samples, (i - 1) * 4, v * scale) + end + return a +end + +return Signal diff --git a/tests/audio/aac.luau b/tests/audio/aac.luau new file mode 100644 index 0000000..360d39a --- /dev/null +++ b/tests/audio/aac.luau @@ -0,0 +1,117 @@ +-- audio/aac tests: ADTS streams from ffmpeg and fdkaac (stereo, mono 32 kHz) against ffmpeg's float decode (SNR, +-- length); an HE-AAC ADTS stream plays its core; a leading ID3v2 tag (skipped, text frames as tags) and garbage before +-- the first frame (resync); a truncated last frame; streaming + seek; sniff; errors; the fuzz no-throw pass. +-- Fixtures: tools/fixtures/m4a.py. +local T = require("@tests/T") +local AacF = require("@formats/audio/aac") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/m4a_aac") +local He = require("@tests/gen/m4a_he") + +local t = T.suite("aac") + +local function reader(s: string): Bytes.Reader + return Bytes.reader(buffer.fromstring(s)) +end + +local function snr(a: any, ref: string, skip: number?): number + local off = (skip or 0) * a.channels + local n = math.min(a.frames * a.channels - off, #ref // 4) + local rb = buffer.fromstring(ref) + local sig, err = 0, 0 + for i = 0, n - 1 do + local r = buffer.readf32(rb, i * 4) + local d = buffer.readf32(a.samples, (off + i) * 4) - r + sig += r * r + err += d * d + end + return if err == 0 then math.huge else 10 * math.log10(sig / err) +end + +t:eq(AacF.name, "aac", "name") +t:check(AacF.caps.decode and not AacF.caps.encode and AacF.encode == nil, "caps: decode only") + +local first +for _, c in Fx do + if c.container ~= "adts" then + continue + end + first = first or c + local r = reader(c.data) + t:check(AacF.sniff(r) >= 0.9, c.name .. ": sniff") + local a, err = AacF.decode(r) + t:check(a, c.name .. ": " .. tostring(err)) + t:check(a.channels == c.channels and a.sampleRate == c.rate, c.name .. ": format") + t:eq(a.frames, c.frames, c.name .. ": frames (ADTS keeps the priming)") + local s = snr(a, c.ref) + t:check(s > 90, string.format("%s: SNR %.1f dB", c.name, s)) + t:note("%s: %d ch %d Hz, %d frames, SNR %.1f dB vs ffmpeg", c.name, c.channels, c.rate, a.frames, s) +end + +-- HE-AAC ADTS: the core +for _, c in He do + if string.sub(c.name, -4) == ".aac" then + local a, err = AacF.decode(reader(c.data)) + t:check(a and a.sampleRate == c.rate // 2 and a.frames > 0, c.name .. ": core decode: " .. tostring(err)) + end +end + +-- ID3v2 in front + garbage, truncated tail +do + local function frame(id: string, text: string): string + local body = "\3" .. text + local n = #body + return id .. string.char(0, 0, n // 128, n % 128) .. "\0\0" .. body + end + local frames = frame("TIT2", "Adts Title") .. frame("TPE1", "Someone") + local n = #frames + local id3 = "ID3\4\0\0" .. string.char(0, 0, n // 128, n % 128) .. frames + local data = id3 .. "\0\1\2garbage" .. first.data + local a, err = AacF.decode(reader(data)) + t:check(a, "id3 + garbage: " .. tostring(err)) + t:check(a.tags.title == "Adts Title" and a.tags.artist == "Someone", "id3 tags") + t:eq(a.frames, first.frames, "id3 + garbage: same frames") + t:check(snr(a, first.ref) > 90, "id3 + garbage: same audio") + local cut = AacF.decode(reader(string.sub(first.data, 1, #first.data - 5))) :: any + t:check(cut and cut.frames == first.frames - 1024, "truncated last frame dropped") +end + +-- streaming + seek +do + local whole = AacF.decode(reader(first.data)) :: any + local dec = AacF.open(reader(first.data)) :: any + for _, at in { 0.3, 0.0, 0.5123 } do + dec:seek(at) + local b, n = dec:read(600) + local f0 = math.floor(at * whole.sampleRate + 0.5) + local maxd = 0 + for i = 0, n * whole.channels - 1 do + maxd = math.max(maxd, math.abs(buffer.readf32(b, i * 4) - buffer.readf32(whole.samples, (f0 * whole.channels + i) * 4))) + end + -- (the stream has no PNS: noise substitution would draw different noise after a seek) + t:check(n == 600 and maxd < 1e-6, string.format("seek %.3f s (max diff %g)", at, maxd)) + end +end + +-- errors +do + t:eq(AacF.sniff(reader("RIFF....WAVE")), 0, "sniff a WAV") + local _, e = AacF.decode(reader(string.rep("\0", 100))) + t:check(e and e.code == Err.CORRUPT, "no frames: " .. tostring(e)) +end + +-- fuzz +do + local samples = {} + for _, c in Fx do + if c.container == "adts" then + table.insert(samples, string.sub(c.data, 1, 6000)) + end + end + t:fuzz("decode", function(b: buffer) + return AacF.decode(Bytes.reader(b)) + end, samples, { mutations = 30 }) +end + +t:done() diff --git a/tests/audio/aiff.luau b/tests/audio/aiff.luau new file mode 100644 index 0000000..079f34a --- /dev/null +++ b/tests/audio/aiff.luau @@ -0,0 +1,183 @@ +-- 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; +-- 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") +local Aiff = require("@formats/audio/aiff") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Cases = require("@tests/gen/aiff_cases") +local Enc = require("@tests/gen/aiff_enc") +local Sig = require("@tests/gen/aiff_sig") + +local t = T.suite("aiff") + +local function reader(s: string): Bytes.Reader + return Bytes.reader(buffer.fromstring(s)) +end +-- max |a - b| over n f32 samples (a at byte ao, b at byte bo) +local function maxDiff(a: buffer, ao: number, b: buffer, bo: number, n: number): number + local m = 0 + for i = 0, n - 1 do + local d = math.abs(buffer.readf32(a, ao + i * 4) - buffer.readf32(b, bo + i * 4)) + if d > m then + m = d + end + end + return m +end + +-- the contract +t:eq(Aiff.name, "aiff", "name") +t:eq(Aiff.category, "audio", "category") +t:check(Aiff.caps.decode and Aiff.caps.encode and table.find(Aiff.extensions, "aif") ~= nil, "caps / extensions") + +-- reference files: decode, stream, seek +for _, c in Cases do + local a, err = Aiff.decode(reader(c.data)) + t:check(a, c.name .. ": " .. tostring(err)) + t:check(a.kind == "audio" and a.sampleRate == c.rate and a.channels == c.channels, c.name .. ": format") + t:eq(a.frames, c.frames, c.name .. ": frames") + local ref = buffer.fromstring(c.ref) + local n = c.frames * c.channels + t:check(maxDiff(a.samples, 0, ref, 0, n) < 1e-6, c.name .. ": samples match ffmpeg") + -- streaming in odd chunks + local dec = Aiff.open(reader(c.data)) :: Types.Decoder + local got, out = 0, buffer.create(0) + local ok = true + while true do + local b, k = dec:read(777, out) + if k == 0 then + break + end + out = b + ok = ok and maxDiff(b, 0, ref, got * c.channels * 4, k * c.channels) < 1e-6 + got += k + end + t:check(ok and got == c.frames, c.name .. ": streamed reads") + dec:seek(1000 / c.rate) + t:check(math.abs(dec:position() - 1000 / c.rate) < 1e-9, c.name .. ": position") + local b, k = dec:read(50) + t:check(k == 50 and maxDiff(b, 0, ref, 1000 * c.channels * 4, 50 * c.channels) < 1e-6, c.name .. ": seek") +end +t:note("%d reference files match ffmpeg", #Cases) + +-- details of particular files +local function case(name: string): any + for _, c in Cases do + if c.name == name then + return c + end + end + error("no case " .. name) +end +do + local a = Aiff.decode(reader(case("ffmpeg-tags").data)) :: Types.Audio + t:eq(a.tags.title, "Song Name", "NAME chunk") + t:eq(a.tags.artist, "Some One", "AUTH chunk") + local fl = Aiff.decode(reader(case("ffmpeg-fl32").data)) :: Types.Audio + t:check(fl.meta.source.aifc and fl.meta.source.compression == "fl32", "fl32 meta") + -- a 12-bit sample size: samples sit left-justified in 16-bit containers + local s16 = case("sox-aiff-s16") + local q = string.find(s16.data, "COMM", 1, true) :: number + local d12 = string.sub(s16.data, 1, q + 13) .. "\0\12" .. string.sub(s16.data, q + 16) + local s12 = Aiff.decode(reader(d12)) :: Types.Audio + t:check(s12.meta.source.bitDepth == 12 and maxDiff(s12.samples, 0, buffer.fromstring(s16.ref), 0, s16.frames * 2) < 1e-6, "12-bit sample size") + local sw = Aiff.info(reader(case("ffmpeg-sowt").data)) + t:check(sw and sw.compression == "sowt" and sw.format == "s16le", "info: sowt") + -- inside a bigger buffer + local c = case("ffmpeg-s16be") + local big = buffer.create(#c.data + 9) + buffer.writestring(big, 5, c.data) + local a2 = Aiff.decode(Bytes.reader(big, 5, #c.data)) :: Types.Audio + t:check(a2 and maxDiff(a2.samples, 0, buffer.fromstring(c.ref), 0, c.frames * c.channels) < 1e-6, "decode from a sub-range") + -- truncated sample data: the frames present + local cut = string.sub(c.data, 1, #c.data - 1001) + local a3 = Aiff.decode(reader(cut)) :: Types.Audio + t:check(a3 and a3.frames < c.frames and a3.frames > 0 and a3.meta.source.truncated, "truncated SSND") +end + +-- our encoder: ffmpeg decodes every sample format (fixture step), within the format's step; streamed == from Audio +local TOL = { s8 = 0.5 / 128, ["s16-mono"] = 0.5 / 32768, s16 = 0.5 / 32768, sowt16 = 0.5 / 32768, ["aifc-s16"] = 0.5 / 32768, s24 = 0.5 / 8388608, sowt24 = 0.5 / 8388608, s32 = 1e-7, f32 = 0, f64 = 0, ulaw = 0.04, alaw = 0.04 } +local sig = buffer.fromstring(Sig.data) +for _, e in Enc do + t:eq(e.ffmpegErrors, "", e.name .. ": ffmpeg reads our file without errors") + t:check(e.frames == Sig.frames and e.rate == Sig.rate, e.name .. ": ffmpeg frames / rate") + t:check(e.maxDiff <= TOL[e.name] + 1e-7, string.format("%s: ffmpeg decode within %g (max diff %g)", e.name, TOL[e.name], e.maxDiff)) + t:check(e.sameStreamed, e.name .. ": encoding a Decoder gives the same bytes") + local back = Aiff.decode(reader(e.data)) :: Types.Audio + t:check(back and back.frames == Sig.frames and back.channels == e.channels, e.name .. ": our decoder reads our file") + if e.channels == 2 then + t:check(maxDiff(back.samples, 0, sig, 0, Sig.frames * 2) <= TOL[e.name] + 1e-7, e.name .. ": round trip") + end +end +t:note("%d encoder outputs read back by ffmpeg and by us", #Enc) + +-- encoder: tags, odd sizes, errors +do + local a = Types.Audio.new(44100, 1, 3) + buffer.writef32(a.samples, 0, 0.5) + buffer.writef32(a.samples, 4, -1) + buffer.writef32(a.samples, 8, 2) -- clips + a.tags = { title = "odd", artist = "me", comment = "x" } + local b = Aiff.encode(a, { sampleFormat = "s8" }) :: buffer + local back = Aiff.decode(Bytes.reader(b)) :: Types.Audio + t:check(back.frames == 3 and back.tags.title == "odd" and back.tags.artist == "me" and back.tags.comment == "x", "odd length + tags") + t:check(buffer.readf32(back.samples, 0) == 0.5 and buffer.readf32(back.samples, 4) == -1 and buffer.readf32(back.samples, 8) == 127 / 128, "s8 values, clipping") + t:eq(buffer.len(b) % 2, 0, "chunks padded to even sizes") + t:check(Aiff.info(Bytes.reader(b)).sampleRate == 44100, "80-bit rate round trip") + local empty = Aiff.encode(Types.Audio.new(8000, 2, 0)) :: buffer + local e0 = Aiff.decode(Bytes.reader(empty)) + t:check(e0 and e0.frames == 0, "empty audio") + local _, e1 = Aiff.encode({} :: any) + t:check(e1 and e1.code == Err.ARG, "encode junk: ARG") + local _, e2 = Aiff.encode(a, { sampleFormat = "s12" } :: any) + t:check(e2 and e2.code == Err.ARG, "bad sampleFormat: ARG") + local _, e3 = Aiff.encode(a, { sampleFormat = "f32", littleEndian = true }) + t:check(e3 and e3.code == Err.ARG, "littleEndian float: ARG") + local _, e5 = Aiff.encode(a, { sampleFormat = "s24", littleEndian = true }) + t:check(e5 and e5.code == Err.ARG, "littleEndian 24-bit: ARG") + t:eq(Aiff.sniff(Bytes.reader(b)), 1, "sniff") + t:eq(Aiff.sniff(reader("RIFF....WAVE")), 0, "sniff wav") + t:eq(Aiff.sniff(reader("")), 0, "sniff nothing") +end + +-- errors +do + local _, e = Aiff.decode(reader("FORM\0\0\0\4WAVE")) + 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 _, 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 }) + t:check(e4 and e4.code == Err.LIMIT, "maxFrames: LIMIT") +end + +-- fuzz +do + local samples = {} + for i, c in Cases do + if i % 3 == 1 then + table.insert(samples, string.sub(c.data, 1, 600)) + end + end + t:fuzz("decode", function(b: buffer) + return Aiff.decode(Bytes.reader(b)) + end, samples, { mutations = 30, keepHeader = 0 }) + t:fuzz("open + read", function(b: buffer) + local d = Aiff.open(Bytes.reader(b)) + if d then + d:read(100) + d:seek(0.001) + d:read(100) + end + return d + end, samples, { mutations = 10, garbage = 50 }) +end + +t:done() diff --git a/tests/audio/au.luau b/tests/audio/au.luau new file mode 100644 index 0000000..c38e8c5 --- /dev/null +++ b/tests/audio/au.luau @@ -0,0 +1,147 @@ +-- audio/au tests: files written by ffmpeg and sox in every encoding (8 / 16 / 24 / 32-bit, float, double, mu-law, +-- A-law, an annotation) against ffmpeg's decode; streaming reads and seeks; our encoder's output for every encoding +-- decoded by ffmpeg (fixture step) and by us; an unknown data size; errors; fuzz. Fixtures: tools/fixtures/au.py. +local T = require("@tests/T") +local Au = require("@formats/audio/au") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Cases = require("@tests/gen/au_cases") +local Enc = require("@tests/gen/au_enc") +local Sig = require("@tests/gen/au_sig") + +local t = T.suite("au") + +local function reader(s: string): Bytes.Reader + return Bytes.reader(buffer.fromstring(s)) +end +local function maxDiff(a: buffer, ao: number, b: buffer, bo: number, n: number): number + local m = 0 + for i = 0, n - 1 do + local d = math.abs(buffer.readf32(a, ao + i * 4) - buffer.readf32(b, bo + i * 4)) + if d > m then + m = d + end + end + return m +end +local function case(name: string): any + for _, c in Cases do + if c.name == name then + return c + end + end + error("no case " .. name) +end + +t:eq(Au.name, "au", "name") +t:eq(Au.category, "audio", "category") +t:check(Au.caps.decode and Au.caps.encode and table.find(Au.extensions, "snd") ~= nil, "caps / extensions") + +for _, c in Cases do + local a, err = Au.decode(reader(c.data)) + t:check(a, c.name .. ": " .. tostring(err)) + t:check(a.sampleRate == c.rate and a.channels == c.channels, c.name .. ": format") + t:eq(a.frames, c.frames, c.name .. ": frames") + local ref = buffer.fromstring(c.ref) + t:check(maxDiff(a.samples, 0, ref, 0, c.frames * c.channels) < 1e-6, c.name .. ": samples match ffmpeg") + local dec = Au.open(reader(c.data)) :: Types.Decoder + local got, ok = 0, true + while true do + local b, k = dec:read(1000) + if k == 0 then + break + end + ok = ok and maxDiff(b, 0, ref, got * c.channels * 4, k * c.channels) < 1e-6 + got += k + end + t:check(ok and got == c.frames, c.name .. ": streamed reads") + dec:seek(700 / c.rate) + local b, k = dec:read(40) + t:check(k == 40 and maxDiff(b, 0, ref, 700 * c.channels * 4, 40 * c.channels) < 1e-6, c.name .. ": seek") +end +t:note("%d reference files match ffmpeg", #Cases) + +do + local a = Au.decode(reader(case("sox-comment").data)) :: Types.Audio + t:check(a.tags.comment ~= nil and string.find(a.tags.comment, "hello sun", 1, true) ~= nil, "annotation as comment") + -- an unknown data size (0xFFFFFFFF) runs to the end of the file + local c = case("ffmpeg-s16be") + local unk = string.sub(c.data, 1, 8) .. "\255\255\255\255" .. string.sub(c.data, 13) + local a2 = Au.decode(reader(unk)) :: Types.Audio + t:check(a2 and a2.frames == c.frames, "unknown data size") + local cut = Au.decode(reader(string.sub(c.data, 1, #c.data - 400))) :: Types.Audio + t:check(cut and cut.frames == c.frames - 100 and cut.meta.source.truncated, "truncated data") + local big = buffer.create(#c.data + 3) + buffer.writestring(big, 3, c.data) + local a3 = Au.decode(Bytes.reader(big, 3, #c.data)) :: Types.Audio + t:check(a3 and maxDiff(a3.samples, 0, buffer.fromstring(c.ref), 0, c.frames * 2) < 1e-6, "decode from a sub-range") +end + +local TOL = { s8 = 0.5 / 128, ["s16-mono"] = 0.5 / 32768, s16 = 0.5 / 32768, s24 = 0.5 / 8388608, s32 = 1e-7, f32 = 0, f64 = 0, ulaw = 0.04, alaw = 0.04 } +local sig = buffer.fromstring(Sig.data) +for _, e in Enc do + t:eq(e.ffmpegErrors, "", e.name .. ": ffmpeg reads our file without errors") + t:check(e.frames == Sig.frames and e.rate == Sig.rate, e.name .. ": ffmpeg frames / rate") + t:check(e.maxDiff <= TOL[e.name] + 1e-7, string.format("%s: ffmpeg decode within %g (max diff %g)", e.name, TOL[e.name], e.maxDiff)) + t:check(e.sameStreamed, e.name .. ": encoding a Decoder gives the same bytes") + local back = Au.decode(reader(e.data)) :: Types.Audio + t:check(back and back.frames == Sig.frames and back.channels == e.channels, e.name .. ": our decoder reads our file") + if e.channels == 2 then + t:check(maxDiff(back.samples, 0, sig, 0, Sig.frames * 2) <= TOL[e.name] + 1e-7, e.name .. ": round trip") + end +end +t:note("%d encoder outputs read back by ffmpeg and by us", #Enc) + +do + local a = Types.Audio.new(8000, 1, 2) + buffer.writef32(a.samples, 0, 0.25) + buffer.writef32(a.samples, 4, -0.25) + a.tags = { comment = "annotated!" } + local b = Au.encode(a) :: buffer + t:eq(bit32.byteswap(buffer.readu32(b, 4)) % 8, 0, "data offset is a multiple of 8") + local back = Au.decode(Bytes.reader(b)) :: Types.Audio + t:check(back.frames == 2 and back.tags.comment == "annotated!" and buffer.readf32(back.samples, 0) == 0.25, "comment + samples") + local _, e1 = Au.encode(42 :: any) + t:check(e1 and e1.code == Err.ARG, "encode junk: ARG") + local _, e2 = Au.encode(a, { sampleFormat = "u8" } :: any) + t:check(e2 and e2.code == Err.ARG, "bad sampleFormat: ARG") + local frac = Types.Audio.new(8000.5, 1, 1) + local _, e3 = Au.encode(frac) + t:check(e3 and e3.code == Err.ARG, "fractional rate: ARG") + t:eq(Au.sniff(Bytes.reader(b)), 1, "sniff") + t:eq(Au.sniff(reader("FORM")), 0, "sniff other") + -- G.721 ADPCM (encoding 23): unsupported + local adpcm = string.sub(buffer.tostring(b), 1, 12) .. "\0\0\0\23" .. string.sub(buffer.tostring(b), 17) + local _, e4 = Au.decode(reader(adpcm)) + t:check(e4 and e4.code == Err.UNSUPPORTED, "encoding 23: UNSUPPORTED") + local _, e5 = Au.decode(reader(".snd\0\0\0\24")) + t:check(e5 and e5.code == Err.CORRUPT, "short header: CORRUPT") + local _, e6 = Au.decode(reader(case("ffmpeg-s16be").data), { maxFrames = 5 }) + t:check(e6 and e6.code == Err.LIMIT, "maxFrames: LIMIT") +end + +do + local samples = {} + for i, c in Cases do + if i % 2 == 1 then + table.insert(samples, string.sub(c.data, 1, 400)) + end + end + t:fuzz("decode", function(b: buffer) + return Au.decode(Bytes.reader(b)) + end, samples, { mutations = 30 }) + t:fuzz("open + read", function(b: buffer) + local d = Au.open(Bytes.reader(b)) + if d then + d:read(64) + d:seek(1e9) + d:read(64) + d:seek(-1) + d:read(64) + end + return d + end, samples, { mutations = 10, garbage = 50 }) +end + +t:done() diff --git a/tests/audio/caf.luau b/tests/audio/caf.luau new file mode 100644 index 0000000..c0f40ff --- /dev/null +++ b/tests/audio/caf.luau @@ -0,0 +1,177 @@ +-- audio/caf tests: ALAC CAF from ffmpeg bit-exact; AAC CAF (ffmpeg's ADTS frames wrapped by the fixture) against +-- ffmpeg's float decode; our CAF writer (PCM 16 / 24-bit, ALAC; re-encoded here and compared with the bytes ffmpeg +-- decoded bit-exactly); PCM layouts (little / big endian, float) through our writer + a hand-built header; info tags; +-- seek; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/m4a.py. +local T = require("@tests/T") +local Caf = require("@formats/audio/caf") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Signal = require("@tests/audio/_signal") +local Cases = require("@tests/audio/_encode_cases") +local Alac = require("@tests/gen/m4a_alac") +local Aac = require("@tests/gen/m4a_aac") +local Ours = require("@tests/gen/m4a_ours") + +local t = T.suite("caf") + +local function reader(s: string | buffer): Bytes.Reader + return Bytes.reader(if type(s) == "string" then buffer.fromstring(s) else s) +end + +local function intCrc(a: any, bits: number): number + local n = a.frames * a.channels + local b = buffer.create(n * 4) + local scale = 2 ^ (bits - 1) + for i = 0, n - 1 do + buffer.writei32(b, i * 4, math.floor(buffer.readf32(a.samples, i * 4) * scale + 0.5)) + end + return Crc32.of(b) +end + +t:eq(Caf.name, "caf", "name") +t:check(Caf.caps.decode and Caf.caps.encode, "caps") + +for _, c in Alac do + if c.container == "caf" then + local r = reader(c.data) + t:eq(Caf.sniff(r), 1, c.name .. ": sniff") + local a, err = Caf.decode(r) + t:check(a, c.name .. ": " .. tostring(err)) + t:check(a.channels == c.channels and a.sampleRate == c.rate and a.frames == c.frames, c.name .. ": format / length (pakt)") + t:eq(intCrc(a, c.bits), c.crc, c.name .. ": bit-exact") + end +end + +for _, c in Aac do + if c.container == "caf" then + local a, err = Caf.decode(reader(c.data)) + t:check(a, c.name .. ": " .. tostring(err)) + t:eq(a.frames, c.frames, c.name .. ": frames") + local rb = buffer.fromstring(c.ref) + local sig, e = 0, 0 + for i = 0, a.frames * a.channels - 1 do + local r = buffer.readf32(rb, i * 4) + sig += r * r + e += (buffer.readf32(a.samples, i * 4) - r) ^ 2 + end + local snr = if e == 0 then math.huge else 10 * math.log10(sig / e) + t:check(snr > 90, string.format("%s: SNR %.1f dB", c.name, snr)) + t:note("%s: SNR %.1f dB vs ffmpeg", c.name, snr) + end +end + +-- our writer: the bytes ffmpeg validated +do + local byName = {} + for _, o in Ours do + byName[o.name] = o + end + for _, c in Cases do + if c.container ~= "caf" then + continue + end + local o = byName[c.name] + t:check(o and o.ffmpeg, c.name .. ": ffmpeg decoded it bit-exactly") + local a = Signal.audio(c.rate, c.frames, c.channels, c.bits, c.seed) + local file = Caf.encode(a, { codec = c.codec, bitDepth = c.bits }) :: buffer + t:eq(string.format("%08x", Crc32.of(file)), string.format("%08x", o.crc), c.name .. ": the validated bytes") + local back = Caf.decode(reader(file)) :: any + t:check(back and back.frames == c.frames, c.name .. ": our length") + local ints = Signal.ints(c.frames, c.channels, c.bits, c.seed) + local ok = true + local scale = 2 ^ (c.bits - 1) + for i = 1, #ints do + ok = ok and math.floor(buffer.readf32(back.samples, (i - 1) * 4) * scale + 0.5) == ints[i] + end + t:check(ok, c.name .. ": round trip") + end +end + +-- float PCM, tags, a decoder as the source, a hand-built little-endian header +do + local a = Signal.audio(32000, 3000, 3, 16, 12) + a.tags = { title = "Caf Title", artist = "A", date = "1999", comment = "c", custom = "x" } + local file = Caf.encode(a, { codec = "pcm", bitDepth = 32 }) :: buffer + local back = Caf.decode(reader(file)) :: any + t:check(back.frames == 3000 and buffer.tostring(back.samples) == buffer.tostring(a.samples), "float PCM round trip") + for k, v in a.tags do + t:eq(back.tags[k], v, "tag " .. k) + end + local dec = Caf.open(reader(file)) :: any + local again = Caf.encode(dec, { codec = "alac" }) :: buffer + local b2 = Caf.decode(reader(again)) :: any + t:check(b2.frames == 3000 and buffer.tostring(b2.samples) == buffer.tostring(a.samples), "ALAC from a streaming decoder") + -- little-endian 24-bit integer PCM, data chunk of unknown size (-1) + local w = Bytes.writer(64) + w:string("caff") + w:u16be(1) + w:u16be(0) + w:string("desc") + w:u64be(32) + w:f64be(8000) + w:string("lpcm") + w:u32be(2) + w:u32be(3) + w:u32be(1) + w:u32be(1) + w:u32be(24) + w:string("data") + w:u32be(0xFFFFFFFF) + w:u32be(0xFFFFFFFF) + w:u32be(0) + for _, v in { 0, 4194304, -4194304, 8388607, -8388608 } do + w:u24le(v % 16777216) + end + local le = Caf.decode(Bytes.reader(w:finish())) :: any + t:check(le and le.frames == 5, "24-bit LE, data size -1") + t:check(le and math.abs(buffer.readf32(le.samples, 4) - 0.5) < 1e-7 and math.abs(buffer.readf32(le.samples, 16) + 1) < 1e-7, "24-bit LE values") +end + +-- seek +do + local c = Alac[#Alac] + local whole = Caf.decode(reader(c.data)) :: any + local dec = Caf.open(reader(c.data)) :: any + for _, at in { 0.1, 0.0, 0.15 } do + dec:seek(at) + local b, n = dec:read(400) + local f0 = math.floor(at * whole.sampleRate + 0.5) + local same = n == 400 + for i = 0, n * whole.channels - 1 do + same = same and buffer.readf32(b, i * 4) == buffer.readf32(whole.samples, (f0 * whole.channels + i) * 4) + end + t:check(same, string.format("seek %.2f s", at)) + end +end + +-- errors +do + t:eq(Caf.sniff(reader("caff\0\2\0\0")), 0, "sniff: wrong version") + local _, e = Caf.decode(reader("caff\0\1\0\0")) + t:check(e and e.code == Err.CORRUPT, "no desc: " .. tostring(e)) + local _, e2 = Caf.encode(Signal.audio(8000, 10, 1, 16, 1), { codec = "mp3" } :: any) + t:check(e2 and e2.code == Err.ARG, "bad codec: " .. tostring(e2)) +end + +-- fuzz +do + local samples = {} + for _, c in Alac do + if c.container == "caf" then + table.insert(samples, string.sub(c.data, 1, 9000)) + end + end + for _, c in Aac do + if c.container == "caf" then + table.insert(samples, string.sub(c.data, 1, 6000)) + end + end + local pcm = Caf.encode(Signal.audio(8000, 300, 2, 16, 3), { codec = "pcm" }) :: buffer + table.insert(samples, buffer.tostring(pcm)) + t:fuzz("decode", function(b: buffer) + return Caf.decode(Bytes.reader(b)) + end, samples, { mutations = 30 }) +end + +t:done() diff --git a/tests/audio/flac.luau b/tests/audio/flac.luau index c1d2305..3f0f9a3 100644 --- a/tests/audio/flac.luau +++ b/tests/audio/flac.luau @@ -22,7 +22,7 @@ for _, c in Cases do end t:eq(Flac.name, "flac", "name") -t:check(Flac.caps.decode and not Flac.caps.encode, "caps") +t:check(Flac.caps.decode and Flac.caps.encode, "caps") -- encode: ws-audio (tests/audio/flac_encode.luau) local seekChecks = 0 for _, fx in Cases do @@ -156,8 +156,8 @@ do t:check(a and a.frames == fx.frames, "F.audio.load") local d = F.audio.open(byName.s16_l3.data) t:check(d and d.frames == byName.s16_l3.frames, "F.audio.open") - local _, se = F.save(a, nil, { format = "flac" }) - t:check(se and se.code == Err.UNSUPPORTED, "F.save flac is read-only here: " .. tostring(se)) + local saved, se = F.save(a, nil, { format = "flac" }) -- the encoder (ws-audio) + t:check(saved and F.audio.load(saved).frames == fx.frames, "F.save flac: " .. tostring(se)) end -- a damaged frame is dropped, the rest decodes diff --git a/tests/audio/flac_encode.luau b/tests/audio/flac_encode.luau new file mode 100644 index 0000000..7a0f204 --- /dev/null +++ b/tests/audio/flac_encode.luau @@ -0,0 +1,109 @@ +-- audio/flac encoder tests: every fixture-step encode (levels 0-8, 1 / 2 / 6 channels, 8 / 12 / 16 / 20 / 24 bits, +-- odd lengths and block sizes, odd rates, seek tables, padding) passed `flac -t` and carries the MD5 of the quantized +-- input; sizes within 10% of libFLAC at the same level; each decodes bit-exactly through our own decoder; streaming +-- from a Decoder gives the same bytes; tags; option errors. Fixtures: tools/fixtures/flac_enc.py. +local T = require("@tests/T") +local Flac = require("@formats/audio/flac") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/Pcm") +local Enc = require("@tests/gen/flac_enc") +local Sigs = require("@tests/gen/flac_enc_sigs") + +local t = T.suite("flac_encode") + +local sigCache: { [string]: any } = {} +local function sig(name: string): Types.Audio + local s = sigCache[name] + if not s then + local m = Sigs[name] + s = Types.Audio.new(m.rate, m.channels, m.frames) + buffer.writestring(s.samples, 0, m.data) + sigCache[name] = s + end + return s +end + +t:check(Flac.caps.encode and Flac.encode ~= nil, "caps.encode") + +local worst = 0 +for _, e in Enc do + t:eq(e.flacTest, "", e.name .. ": flac -t") + t:eq(e.md5, e.wantMd5, e.name .. ": STREAMINFO MD5 = MD5 of the quantized input") + if e.refSize then + local ratio = e.size / e.refSize + worst = math.max(worst, ratio) + t:check(ratio < 1.1, string.format("%s: %d bytes, libFLAC %d (%.3f)", e.name, e.size, e.refSize, ratio)) + end + -- our decoder: bit-exact against the input quantized to e.bits + local a = sig(e.sig) + local back, err = Flac.decode(Bytes.reader(buffer.fromstring(e.data))) + t:check(back, e.name .. ": our decoder: " .. tostring(err)) + t:check(back.frames == a.frames and back.channels == a.channels and back.sampleRate == a.sampleRate, e.name .. ": format") + local s = 2 ^ (e.bits - 1) + local exact = true + for i = 0, a.frames * a.channels - 1 do + local want = math.clamp(math.floor(buffer.readf32(a.samples, i * 4) * s + 0.5), -s, s - 1) + if math.floor(buffer.readf32(back.samples, i * 4) * s + 0.5) ~= want then + exact = false + break + end + end + t:check(exact, e.name .. ": bit-exact round trip") + t:eq(back.meta.source.bitDepth, e.bits, e.name .. ": bits per sample") +end +t:note("%d encodes pass flac -t with the right MD5 and decode bit-exactly; worst size vs libFLAC %.3f", #Enc, worst) + +-- streaming: a Decoder source gives the same bytes as the Audio +do + local a = sig("flacsig_music_2_7000_44100") + local f1 = Flac.encode(a, { level = 5 }) :: buffer + local f2 = Flac.encode(Pcm.audioDecoder(a), { level = 5 }) :: buffer + t:check(buffer.tostring(f1) == buffer.tostring(f2), "Decoder source = Audio source") + -- a decoder of our own output re-encodes to the same stream (its bit depth carries over) + local dec = Flac.open(Bytes.reader(f1)) :: any + local f3 = Flac.encode(dec, { level = 5 }) :: buffer + t:check(buffer.tostring(f3) == buffer.tostring(f1), "FLAC -> FLAC through the streaming decoder") +end + +-- tags, bit depth from the source +do + local a = Types.Audio.new(48000, 1, 3000) + for i = 0, 2999 do + buffer.writef32(a.samples, i * 4, math.floor(math.sin(i / 7) * 100) / 128) + end + a.tags = { title = "Tïtle", artist = "Artist", track = "3" } + a.meta.source = { format = "wav", bitDepth = 8 } + local f = Flac.encode(a) :: buffer + local back = Flac.decode(Bytes.reader(f)) :: Types.Audio + t:eq(back.meta.source.bitDepth, 8, "bit depth from meta.source") + -- (the absorbed FLAC decoder keeps Vorbis comment keys upper case) + local tags = back.tags :: any + t:eq(tags.title or tags.TITLE, "Tïtle", "title") + t:eq(tags.artist or tags.ARTIST, "Artist", "artist") + t:eq(tags.track or tags.TRACKNUMBER, "3", "track number") + local empty = Flac.encode(Types.Audio.new(44100, 2, 0)) :: buffer + local e0 = Flac.decode(Bytes.reader(empty)) + t:check(e0 and e0.frames == 0, "empty audio") +end + +-- errors +do + local a = Types.Audio.new(44100, 2, 10) + local function code(v: any, o: any): string? + local _, e = Flac.encode(v, o) + return e and e.code + end + t:eq(code({}, nil), Err.ARG, "junk value") + t:eq(code(a, { level = 9 }), Err.ARG, "level 9") + t:eq(code(a, { level = 2.5 }), Err.ARG, "level 2.5") + t:eq(code(a, { bits = 32 }), Err.ARG, "32 bits") + t:eq(code(a, { bits = 3 }), Err.ARG, "3 bits") + t:eq(code(a, { blockSize = 8 }), Err.ARG, "block size 8") + t:eq(code(Types.Audio.new(44100, 9, 1), nil), Err.ARG, "9 channels") + t:eq(code(Types.Audio.new(44100.5, 1, 1), nil), Err.ARG, "fractional rate") +end + +-- (the decoder's fuzz pass is in tests/audio/flac.luau; the encoder takes no untrusted bytes) +t:done() diff --git a/tests/audio/m4a.luau b/tests/audio/m4a.luau new file mode 100644 index 0000000..273f71e --- /dev/null +++ b/tests/audio/m4a.luau @@ -0,0 +1,218 @@ +-- audio/m4a tests: ALAC files from ffmpeg decode bit-exactly (16 / 24-bit, mono / stereo / 5.1, partial frames); +-- AAC-LC files from ffmpeg and fdkaac (stereo / mono / 5.1, 8 - 96 kHz, PNS / intensity / M/S / TNS) against ffmpeg's +-- float decode (SNR, gapless length through the edit list); HE-AAC / HE-AACv2 play their core; our ALAC writer +-- (re-encoded here, compared with the bytes ffmpeg decoded bit-exactly and MP4Box accepted in the fixture step); tags +-- and cover art round trips; streaming reads, seeking; the contract; the fuzz no-throw pass. +-- Fixtures: tools/fixtures/m4a.py. +local T = require("@tests/T") +local M4a = require("@formats/audio/m4a") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Signal = require("@tests/audio/_signal") +local Cases = require("@tests/audio/_encode_cases") +local Alac = require("@tests/gen/m4a_alac") +local Aac = require("@tests/gen/m4a_aac") +local He = require("@tests/gen/m4a_he") +local Ours = require("@tests/gen/m4a_ours") + +local t = T.suite("m4a") + +local function reader(s: string | buffer): Bytes.Reader + return Bytes.reader(if type(s) == "string" then buffer.fromstring(s) else s) +end + +-- the integers of a decoded Audio (exact for <= 24-bit sources), CRC-32 as little-endian int32 +local function intCrc(a: any, bits: number): number + local n = a.frames * a.channels + local b = buffer.create(n * 4) + local scale = 2 ^ (bits - 1) + for i = 0, n - 1 do + buffer.writei32(b, i * 4, math.floor(buffer.readf32(a.samples, i * 4) * scale + 0.5)) + end + return Crc32.of(b) +end + +local function snr(a: any, ref: string): (number, number) + local n = math.min(a.frames * a.channels, #ref // 4) + local rb = buffer.fromstring(ref) + local sig, err = 0, 0 + for i = 0, n - 1 do + local r = buffer.readf32(rb, i * 4) + local d = buffer.readf32(a.samples, i * 4) - r + sig += r * r + err += d * d + end + if err == 0 then + return math.huge, n + end + return 10 * math.log10(sig / err), n +end + +-- the contract +t:eq(M4a.name, "m4a", "name") +t:eq(M4a.category, "audio", "category") +t:check(M4a.caps.decode and M4a.caps.encode, "caps") + +-- ALAC from ffmpeg: bit-exact +for _, c in Alac do + if c.container ~= "m4a" then + continue + end + local r = reader(c.data) + t:check(M4a.sniff(r) == 1, c.name .. ": sniff") + local a, err = M4a.decode(r) + t:check(a, c.name .. ": " .. tostring(err)) + t:check(a.channels == c.channels and a.sampleRate == c.rate, c.name .. ": format") + t:eq(a.frames, c.frames, c.name .. ": frames") + t:eq(intCrc(a, c.bits), c.crc, c.name .. ": samples bit-exact") + t:eq(a.meta.source.codec, "alac", c.name .. ": codec") +end +t:note("%d ffmpeg ALAC files decode bit-exactly", #Alac - 1) + +-- AAC: against ffmpeg's float decode +local worst = math.huge +for _, c in Aac do + if c.container ~= "m4a" then + continue + end + local a, err = M4a.decode(reader(c.data)) + t:check(a, c.name .. ": " .. tostring(err)) + t:check(a.channels == c.channels and a.sampleRate == c.rate, c.name .. ": format") + t:eq(a.frames, c.frames, c.name .. ": gapless length") + local s = snr(a, c.ref) + worst = math.min(worst, s) + t:check(s > 90, string.format("%s: SNR %.1f dB vs ffmpeg", c.name, s)) + t:note("%s: %d ch %d Hz, %d frames, SNR %.1f dB vs ffmpeg", c.name, c.channels, c.rate, a.frames, s) +end + +-- HE-AAC: the AAC-LC core at half the rate, SBR seen +for _, c in He do + if string.sub(c.name, -4) ~= ".m4a" then + continue + end + local dec, err = M4a.open(reader(c.data)) + t:check(dec, c.name .. ": " .. tostring(err)) + t:eq(dec.sampleRate, c.rate // 2, c.name .. ": core rate") + local b, n = dec:read(8192) + local e = 0 + for i = 0, n * dec.channels - 1 do + e += buffer.readf32(b, i * 4) ^ 2 + end + t:check(n == 8192 and e > 1, c.name .. ": the core decodes (energy " .. e .. ")") +end + +-- our ALAC writer: the bytes ffmpeg validated +do + local byName = {} + for _, o in Ours do + byName[o.name] = o + end + for _, c in Cases do + if c.container ~= "m4a" then + continue + end + local o = byName[c.name] + t:check(o and o.ffmpeg and o.mp4box and o.codec == "alac", c.name .. ": ffmpeg decoded it bit-exactly, MP4Box read it") + t:eq(o.frames, c.frames, c.name .. ": ffmpeg's length") + local a = Signal.audio(c.rate, c.frames, c.channels, c.bits, c.seed) + a.tags = c.tags or {} + local file, err = M4a.encode(a, { bitDepth = c.bits }) + t:check(file, c.name .. ": encode: " .. tostring(err)) + t:eq(string.format("%08x", Crc32.of(file :: buffer)), string.format("%08x", o.crc), c.name .. ": the validated bytes") + -- and our own decoder gets the integers back + local back = M4a.decode(Bytes.reader(file :: buffer)) :: any + local ints = Signal.ints(c.frames, c.channels, c.bits, c.seed) + local ok = back.frames == c.frames + local scale = 2 ^ (c.bits - 1) + for i = 1, #ints, 7 do + ok = ok and math.floor(buffer.readf32(back.samples, (i - 1) * 4) * scale + 0.5) == ints[i] + end + t:check(ok, c.name .. ": round trip") + if c.tags then + for k, v in c.tags do + t:eq(back.tags[k], v, c.name .. ": tag " .. k) + end + t:eq(o.tags.title, c.tags.title, c.name .. ": ffprobe title") + t:eq(o.tags.track, c.tags.track .. "/" .. c.tags.tracktotal, c.name .. ": ffprobe track") + t:eq(o.tags.artist, c.tags.artist, c.name .. ": ffprobe artist") + end + t:note("%s: %d bytes (%.0f%% of PCM)", c.name, buffer.len(file :: buffer), 100 * buffer.len(file :: buffer) / (c.frames * c.channels * c.bits / 8)) + end +end + +-- cover art + streaming a decoder into the encoder +do + local a = Signal.audio(44100, 5000, 2, 16, 9) + a.meta.pictures = { { mime = "image/png", data = buffer.fromstring("\137PNG fake") } } + a.tags = { title = "Pic" } + local file = M4a.encode(a) :: buffer + local back = M4a.decode(Bytes.reader(file)) :: any + t:check(back.meta.pictures and #back.meta.pictures == 1 and back.meta.pictures[1].mime == "image/png", "cover art round trip") + local dec = M4a.open(Bytes.reader(file)) :: any + local again = M4a.encode(dec) :: buffer + local back2 = M4a.decode(Bytes.reader(again)) :: any + t:check(back2.frames == 5000 and buffer.tostring(back2.samples) == buffer.tostring(back.samples), "encode from a streaming decoder") + local _, e = M4a.encode({} :: any) + t:check(e and e.code == Err.ARG, "encode of a non-audio returns Err.ARG") + local _, e2 = M4a.encode(a, { bitDepth = 12 }) + t:check(e2 and e2.code == Err.ARG, "bad bitDepth returns Err.ARG") +end + +-- streaming + seek (AAC without PNS: its noise is random, so a seek changes it; and ALAC) +for _, c in { Aac[1], Alac[1] } do + local whole = M4a.decode(reader(c.data)) :: any + local dec = M4a.open(reader(c.data)) :: any + t:eq(dec.frames, whole.frames, c.name .. ": decoder frames") + -- read in odd chunks + local got, out = 0, buffer.create(whole.frames * whole.channels * 4) + while true do + local b, n = dec:read(777) + if n == 0 then + break + end + buffer.copy(out, got * whole.channels * 4, b, 0, n * whole.channels * 4) + got += n + end + t:check(got == whole.frames and buffer.tostring(out) == buffer.tostring(whole.samples), c.name .. ": chunked reads equal the whole decode") + for _, at in { 0.1, 0.0, 0.05 } do + dec:seek(at) + local b, n = dec:read(500) + local f0 = math.floor(at * whole.sampleRate + 0.5) + local maxd = 0 + for i = 0, n * whole.channels - 1 do + maxd = math.max(maxd, math.abs(buffer.readf32(b, i * 4) - buffer.readf32(whole.samples, (f0 * whole.channels + i) * 4))) + end + t:check(n == 500 and maxd < 1e-6, string.format("%s: seek %.2f s (max diff %g)", c.name, at, maxd)) + t:check(math.abs(dec:position() - (f0 + 500) / whole.sampleRate) < 1e-9, c.name .. ": position after seek") + end +end + +-- errors +do + local _, e = M4a.decode(reader("\0\0\0\8ftypM4A ")) + t:check(e ~= nil, "a lone ftyp: " .. tostring(e)) + local _, e2 = M4a.decode(reader("hello world, not an mp4")) + t:check(e2 ~= nil and Err.is(e2), "junk: " .. tostring(e2)) + t:eq(M4a.sniff(reader("hello")), 0, "sniff junk") +end + +-- fuzz +do + local samples = {} + for i, c in Alac do + if c.container == "m4a" and i <= 2 then + table.insert(samples, string.sub(c.data, 1, 12000)) + end + end + for i, c in Aac do + if c.container == "m4a" and i <= 2 then + table.insert(samples, string.sub(c.data, 1, 9000)) + end + end + t:fuzz("decode", function(b: buffer) + return M4a.decode(Bytes.reader(b)) + end, samples, { mutations = 25 }) +end + +t:done() diff --git a/tests/audio/mp3.luau b/tests/audio/mp3.luau index f973803..9d4412a 100644 --- a/tests/audio/mp3.luau +++ b/tests/audio/mp3.luau @@ -82,7 +82,7 @@ local rand = T.rng(12345) t:eq(Mp3.name, "mp3", "name") t:eq(Mp3.category, "audio", "category") t:check(table.find(Mp3.extensions, "mp3") ~= nil and table.find(Mp3.extensions, "mp2") ~= nil, "extensions") -t:check(Mp3.caps.decode and not Mp3.caps.encode and Mp3.open ~= nil, "caps") +t:check(Mp3.caps.decode and Mp3.caps.encode and Mp3.open ~= nil, "caps") -- encode: ws-audio (tests/audio/mp3_encode.luau) -- ------------------------------------------------------------------------------------------------ decode vs references for _, c in Cases do @@ -487,8 +487,8 @@ do t:check(a and a.kind == "audio" and a.frames == 22050 and a.tags.title == "Test Title", "F.audio.load: " .. tostring(err)) local dec = F.audio.open(data) t:check(dec and dec.sampleRate == 44100 and dec.frames == 22050, "F.audio.open") - local _, serr = F.save(a, nil, { format = "mp3" }) - t:check(serr and serr.code == Err.UNSUPPORTED, "F.save mp3: read-only") + local saved, serr = F.save(a, nil, { format = "mp3" }) -- the layer III encoder (ws-audio) + t:check(saved and F.audio.load(saved).sampleRate == 44100, "F.save mp3: " .. tostring(serr)) end -- ------------------------------------------------------------------------------------------------ fuzz diff --git a/tests/audio/mp3_encode.luau b/tests/audio/mp3_encode.luau new file mode 100644 index 0000000..f710cc9 --- /dev/null +++ b/tests/audio/mp3_encode.luau @@ -0,0 +1,143 @@ +-- audio/mp3 encoder tests (layer III and layer II): every fixture-step encode (sample rates of MPEG-1 / 2 / 2.5, +-- bit rates 24 .. 384 kbps, stereo / joint / mono) decodes in ffmpeg without errors and in LAME, with the expected +-- length and an SNR over a per-bit-rate floor after aligning the decoder delay; our own decoder (the minimp3 port) +-- agrees; streaming from a Decoder gives the same bytes; the ID3v2 tag round-trips; option errors. +-- Fixtures: tools/fixtures/mp3_enc.py. +local T = require("@tests/T") +local Mp3 = require("@formats/audio/mp3") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/Pcm") +local Enc = require("@tests/gen/mp3_enc") +local Sigs = require("@tests/gen/mp3_enc_sigs") + +local t = T.suite("mp3_encode") + +local function audio(name: string): Types.Audio + local s = Sigs[name] + local a = Types.Audio.new(s.rate, s.channels, s.frames) + buffer.writestring(a.samples, 0, s.data) + return a +end + +-- SNR of y (delayed by lag frames) against x over frames [from, to) +local function snr(x: Types.Audio, y: Types.Audio, lag: number, from: number, to: number): number + local ch = x.channels + local sig, er = 0, 0 + for i = from, to - 1 do + local j = i + lag + if j >= 0 and j < y.frames then + for c = 0, ch - 1 do + local a = buffer.readf32(x.samples, (i * ch + c) * 4) + local b = buffer.readf32(y.samples, (j * y.channels + math.min(c, y.channels - 1)) * 4) + sig += a * a + er += (a - b) * (a - b) + end + end + end + if er == 0 then + return 200 + end + return if sig > 0 then 10 * math.log10(sig / er) else -200 +end + +-- the SNR floors (dB) on the music / sine / sweep signals, by layer and bit rate per channel +local function floorFor(e: any): number + if string.find(e.name, "silence", 1, true) then + return -math.huge + elseif string.find(e.name, "noise", 1, true) then + return 8 -- white noise has no spectral structure to exploit + end + local perCh = e.bitrate / (if e.mode == "mono" then 1 else 2) + local nyquistBand = e.rate <= 16000 -- low rates lose little to the encoder's band limit + if e.layer == 3 then + if perCh >= 64 then + return 14 + elseif perCh >= 32 or nyquistBand then + return 8 + end + return 4 + end + if perCh >= 96 then + return 14 + elseif perCh >= 48 then + return 8 + end + return 4 +end + +t:check(Mp3.caps.encode and Mp3.encode ~= nil, "caps.encode") + +local minByLayer = { [2] = math.huge, [3] = math.huge } +for _, e in Enc do + t:eq(e.ffErrors, "", e.name .. ": ffmpeg decodes without errors") + t:check(e.ffRate == e.rate, e.name .. ": rate") + t:check(e.ffChannels == (if e.mode == "mono" then 1 else 2), e.name .. ": channels") + -- the stream covers the input: the encoder adds one frame of flush and the filterbank delay + local spf = if e.layer == 3 and e.rate < 32000 then 576 else 1152 + t:check(e.ffFrames >= e.frames and e.ffFrames <= e.frames + 3 * spf, string.format("%s: %d decoded frames for %d", e.name, e.ffFrames, e.frames)) + local f = floorFor(e) + t:check(e.ffSnr >= f, string.format("%s: ffmpeg SNR %.1f dB (floor %g)", e.name, e.ffSnr, f)) + if e.lameSnr then + t:check(e.lameSnr >= f, string.format("%s: LAME SNR %.1f dB (floor %g)", e.name, e.lameSnr, f)) + end + if f > -math.huge then + minByLayer[e.layer] = math.min(minByLayer[e.layer], e.ffSnr) + end + -- our decoder agrees with ffmpeg + local x = audio(e.sig) + local y, err = Mp3.decode(Bytes.reader(buffer.fromstring(e.data))) + t:check(y, e.name .. ": our decoder: " .. tostring(err)) + if e.channels == y.channels then + local s = snr(x, y, e.ffLag, 200, x.frames) + t:check(s >= f and math.abs(s - e.ffSnr) < 3, string.format("%s: our decoder %.1f dB, ffmpeg %.1f dB", e.name, s, e.ffSnr)) + end +end +t:note("%d encodes: ffmpeg + LAME decode them; lowest SNR layer III %.1f dB, layer II %.1f dB", #Enc, minByLayer[3], minByLayer[2]) + +-- streaming, tags, defaults +do + local a = audio("music_2_44100") + local f1 = Mp3.encode(a, { bitrate = 128 }) :: buffer + local f2 = Mp3.encode(Pcm.audioDecoder(a), { bitrate = 128 }) :: buffer + t:check(buffer.tostring(f1) == buffer.tostring(f2), "Decoder source = Audio source") + a.tags = { title = "Ünïcode title", artist = "An Artist", album = "Album", track = "4", comment = "made here" } + local f3 = Mp3.encode(a, { layer = 2 }) :: buffer + t:eq(buffer.readstring(f3, 0, 3), "ID3", "an ID3v2 tag in front") + local back = Mp3.open(Bytes.reader(f3)) :: any + t:eq(back.tags.title, "Ünïcode title", "title") + t:eq(back.tags.artist, "An Artist", "artist") + t:eq(back.tags.album, "Album", "album") + t:eq(back.tags.track, "4", "track") + t:eq(back.layer, 2, "layer II by default bit rate 192") + local f4 = Mp3.encode(a, { id3 = false }) :: buffer + t:check(buffer.readu8(f4, 0) == 0xFF, "id3 = false") + local m = Types.Audio.new(22050, 1, 3000) + local fm = Mp3.encode(m) :: buffer + local dm = Mp3.open(Bytes.reader(fm)) :: any + t:check(dm.channels == 1 and dm.sampleRate == 22050, "mono MPEG-2 default") + local empty = Mp3.encode(Types.Audio.new(44100, 2, 0)) :: buffer + t:check(empty and buffer.len(empty) > 0, "empty input: one flush frame") +end + +-- errors +do + local function code(v: any, o: any): string? + local _, e = Mp3.encode(v, o) + return e and e.code + end + local a = Types.Audio.new(44100, 2, 100) + t:eq(code({}, nil), Err.ARG, "junk") + t:eq(code(a, { layer = 1 }), Err.ARG, "layer I") + t:eq(code(a, { bitrate = 100 }), Err.ARG, "100 kbps") + t:eq(code(a, { mode = "dual" }), Err.ARG, "dual mode") + t:eq(code(Types.Audio.new(44000, 2, 10), nil), Err.ARG, "44 kHz") + t:eq(code(Types.Audio.new(8000, 2, 10), { layer = 2 }), Err.ARG, "layer II at 8 kHz") + t:eq(code(Types.Audio.new(44100, 3, 10), nil), Err.ARG, "3 channels") + t:eq(code(a, { layer = 2, bitrate = 32 }), Err.ARG, "layer II stereo at 32 kbps") + t:eq(code(Types.Audio.new(44100, 1, 10), { layer = 2, bitrate = 320 }), Err.ARG, "layer II mono at 320 kbps") +end + +-- (the decoder's fuzz pass is in tests/audio/mp3.luau; the encoders take no untrusted bytes) +t:done() diff --git a/tests/audio/opus.luau b/tests/audio/opus.luau index c876dce..8403251 100644 --- a/tests/audio/opus.luau +++ b/tests/audio/opus.luau @@ -81,7 +81,7 @@ end -- ------------------------------------------------------------------------------------------------ contract t:eq(Opus.name, "opus", "name") t:eq(Opus.category, "audio", "category") -t:check(Opus.caps.decode and not Opus.caps.encode and Opus.open ~= nil and Opus.decode ~= nil, "caps") +t:check(Opus.caps.decode and Opus.caps.encode and Opus.open ~= nil and Opus.decode ~= nil and Opus.encode ~= nil, "caps (the CELT encoder: tests/audio/opus_encode.luau)") t:eq(Opus.sniff(Bytes.reader(FX.celt_st_128.data)), 1, "sniff an Opus file") t:eq(Opus.sniff(Bytes.reader(buffer.fromstring("OggS" .. string.rep("\0", 40)))), 0, "sniff another Ogg") t:eq(Opus.sniff(Bytes.reader(buffer.create(0))), 0, "sniff nothing") diff --git a/tests/audio/opus_encode.luau b/tests/audio/opus_encode.luau new file mode 100644 index 0000000..c3aeff4 --- /dev/null +++ b/tests/audio/opus_encode.luau @@ -0,0 +1,114 @@ +-- audio/opus encoder tests (the CELT-only writer, ws-m4a; mono and mid / side stereo): our Ogg Opus files (re-encoded here, compared with the bytes +-- checked in the fixture step) decode in libopus' opusdec to the input's exact length (pre-skip + end trimming) with a +-- minimum SNR, opusinfo finds no problem, ffmpeg reads them, OpusTags carry the tags; our decoder agrees with opusdec; +-- resampled 44.1 kHz input; silence frames; streaming input; errors; a fuzz no-throw pass over our files. +-- Fixtures: tools/fixtures/opus_celt.py. +local T = require("@tests/T") +local Opus = require("@formats/audio/opus") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Cases = require("@tests/audio/_opus_cases") +local Fx = require("@tests/gen/opus_celt") + +local t = T.suite("opus-encode") + +t:check(Opus.caps.encode and Opus.encode ~= nil, "caps: encode") + +local byName = {} +for _, f in Fx do + byName[f.name] = f +end + +local function snr(ref: buffer, refBase: number, got: buffer, n: number): number + local s, e = 0, 0 + for i = 0, n - 1 do + local x = buffer.readf32(ref, (refBase + i) * 4) + local d = buffer.readf32(got, (refBase + i) * 4) - x + s += x * x + e += d * d + end + return if e == 0 then math.huge else 10 * math.log10(s / math.max(e, 1e-30)) +end + +local files = {} +for _, c in Cases.list do + local fx = byName[c.name] + t:check(fx, c.name .. ": fixture") + local input = Cases.signal(c) + local file, err = Opus.encode(input, { bitrate = c.bitrate }) + t:check(file, c.name .. ": encode: " .. tostring(err)) + table.insert(files, file) + t:eq(string.format("%08x", Crc32.of(file :: buffer)), string.format("%08x", fx.crc), c.name .. ": the bytes the reference tools checked") + t:check(fx.opusinfo, c.name .. ": opusinfo reports no problem") + t:check(fx.ffmpeg, c.name .. ": ffmpeg decodes it") + local frames48 = math.floor(input.frames * 48000 / c.rate + 0.5) + local ch = c.channels + t:eq(#fx.opusdec // (4 * ch), frames48, c.name .. ": opusdec length = the input's (pre-skip + end trimming)") + t:eq(fx.ffmpegFrames, frames48, c.name .. ": ffmpeg length") + -- our decoder vs opusdec + local ours = Opus.decode(Bytes.reader(file :: buffer)) :: any + t:eq(ours.frames, frames48, c.name .. ": our decoder's length") + local ref = buffer.fromstring(fx.opusdec) + local agree = snr(ref, 0, ours.samples, frames48 * ch) + t:check(agree > 60, string.format("%s: our decoder vs opusdec %.1f dB", c.name, agree)) + -- quality vs the input (48 kHz inputs; skip the edges) + if c.rate == 48000 and frames48 > 4000 then + local s = snr(input.samples, 960 * ch, ref, (frames48 - 1920) * ch) + t:check(s >= c.minSnr, string.format("%s: SNR %.1f dB (minimum %d)", c.name, s, c.minSnr)) + t:note("%s: %d bytes, SNR %.1f dB vs the input, our decoder vs opusdec %.1f dB", c.name, buffer.len(file :: buffer), s, agree) + end + if c.tags then + for k, v in c.tags do + t:eq(fx.comments[k], v, c.name .. ": opusinfo comment " .. k) + t:eq(ours.tags[k], v, c.name .. ": our tag " .. k) + end + end +end + +-- silence frames decode to silence +do + local c = Cases.list[1] + local ref = buffer.fromstring(byName[c.name].opusdec) + local peak = 0 + for i = math.floor(0.62 * 48000), math.floor(0.73 * 48000) do + peak = math.max(peak, math.abs(buffer.readf32(ref, i * 4))) + end + t:check(peak < 1e-3, "digital silence stays silent (peak " .. peak .. ")") +end + +-- a streaming decoder as the input +do + local c = Cases.list[1] + local dec = Opus.open(Bytes.reader(files[1] :: buffer)) :: any + local again, err = Opus.encode(dec, { bitrate = 64000 }) + t:check(again, "encode from a decoder: " .. tostring(err)) + local back = Opus.decode(Bytes.reader(again :: buffer)) :: any + t:eq(back.frames, math.floor(c.seconds * 48000 + 0.5), "re-encoded length") +end + +-- errors +do + local three = Cases.signal({ rate = 48000, channels = 3, seconds = 0.05 }) + local _, e = Opus.encode(three) + t:check(e and e.code == Err.UNSUPPORTED, "3 channels: " .. tostring(e)) + local _, e2 = Opus.encode(Cases.signal(Cases.list[6]), { bitrate = 1000 }) + t:check(e2 and e2.code == Err.ARG, "bitrate too low") + local _, e3 = Opus.encode({} :: any) + t:check(e3 and e3.code == Err.ARG, "not audio") +end + +-- fuzz the decoder over our files +do + local samples = {} + for i, f in files do + if i <= 3 then + table.insert(samples, string.sub(buffer.tostring(f :: buffer), 1, 4000)) + end + end + t:fuzz("decode our files", function(b: buffer) + return Opus.decode(Bytes.reader(b)) + end, samples, { mutations = 10, garbage = 30 }) +end + +t:done() diff --git a/tests/audio/voc.luau b/tests/audio/voc.luau new file mode 100644 index 0000000..129c6b6 --- /dev/null +++ b/tests/audio/voc.luau @@ -0,0 +1,129 @@ +-- audio/voc tests: files written by ffmpeg (type 1 + 8 blocks for 8-bit, type 9 otherwise) and sox against ffmpeg's +-- decode; silence / text / continuation blocks and repeat markers built here; 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/voc.py. +local T = require("@tests/T") +local Voc = require("@formats/audio/voc") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Cases = require("@tests/gen/voc_cases") +local Enc = require("@tests/gen/voc_enc") +local Sig = require("@tests/gen/voc_sig") + +local t = T.suite("voc") + +local function reader(s: string): Bytes.Reader + return Bytes.reader(buffer.fromstring(s)) +end +local function maxDiff(a: buffer, ao: number, b: buffer, bo: number, n: number): number + local m = 0 + for i = 0, n - 1 do + local d = math.abs(buffer.readf32(a, ao + i * 4) - buffer.readf32(b, bo + i * 4)) + if d > m then + m = d + end + end + return m +end + +t:eq(Voc.name, "voc", "name") +t:eq(Voc.category, "audio", "category") +t:check(Voc.caps.decode and Voc.caps.encode, "caps") + +for _, c in Cases do + local a, err = Voc.decode(reader(c.data)) + t:check(a, c.name .. ": " .. tostring(err)) + t:check(a.sampleRate == c.rate and a.channels == c.channels, string.format("%s: format %d Hz x %d, want %d x %d", c.name, a.sampleRate, a.channels, c.rate, c.channels)) + t:eq(a.frames, c.frames, c.name .. ": frames") + local ref = buffer.fromstring(c.ref) + t:check(maxDiff(a.samples, 0, ref, 0, c.frames * c.channels) < 1e-6, c.name .. ": samples match ffmpeg") + local dec = Voc.open(reader(c.data)) :: Types.Decoder + dec:seek(500 / c.rate) + local b, k = dec:read(64) + t:check(k == 64 and maxDiff(b, 0, ref, 500 * c.channels * 4, 64 * c.channels) < 1e-6, c.name .. ": seek") +end +t:note("%d reference files match ffmpeg", #Cases) + +-- hand-built blocks: text, type 1 u8, silence, continuation, repeat markers, terminator +do + local hdr = "Creative Voice File\26\26\0\10\1\41\17" + local function blk(typ: number, payload: string): string + local n = #payload + return string.char(typ, n % 256, (n // 256) % 256, n // 65536) .. payload + end + local data = hdr + .. blk(5, "made by hand\0") + .. blk(1, string.char(156, 0) .. string.char(128, 192, 64)) -- 10 kHz, 3 samples + .. blk(3, string.char(4, 0, 156)) -- 5 frames of silence + .. blk(6, string.char(2, 0)) -- repeat start (ignored) + .. blk(2, string.char(255, 0)) -- continuation + .. blk(7, "") -- repeat end + .. blk(4, string.char(1, 0)) -- marker + .. "\0" + local a, err = Voc.decode(reader(data)) + t:check(a, "hand-built: " .. tostring(err)) + t:check(a.sampleRate == 10000 and a.channels == 1 and a.frames == 10, "hand-built: 10 kHz, 3 + 5 + 2 frames") + t:eq(a.tags.comment, "made by hand", "text block") + local want = { 0, 0.5, -0.5, 0, 0, 0, 0, 0, 127 / 128, -1 } + local ok = true + for i, v in want do + ok = ok and buffer.readf32(a.samples, (i - 1) * 4) == v + end + t:check(ok, "hand-built samples") + -- no terminator, a block cut short: the data present + local cut = Voc.decode(reader(string.sub(data, 1, 26 + 17 + 4 + 2 + 2))) + t:check(cut and cut.frames == 2 and cut.meta.source.truncated, "cut in a block") + -- Creative ADPCM: unsupported + local _, e = Voc.decode(reader(hdr .. blk(1, string.char(156, 1) .. "\0\0") .. "\0")) + t:check(e and e.code == Err.UNSUPPORTED, "ADPCM: UNSUPPORTED") + local _, e2 = Voc.decode(reader(hdr .. blk(2, "\0\0") .. "\0")) + t:check(e2 and e2.code == Err.CORRUPT, "continuation first: CORRUPT") + local _, e3 = Voc.decode(reader(hdr .. "\0")) + t:check(e3 and e3.code == Err.CORRUPT, "no sound: CORRUPT") + local _, e4 = Voc.decode(reader("Creative Voice Fil")) + t:check(e4 and e4.code == Err.CORRUPT, "short: CORRUPT") + t:eq(Voc.sniff(reader(data)), 1, "sniff") + t:eq(Voc.sniff(reader(".snd")), 0, "sniff other") +end + +local TOL = { s16 = 0.5 / 32768, ["s16-mono"] = 0.5 / 32768, u8 = 0.5 / 128, ulaw = 0.04, alaw = 0.04 } +local sig = buffer.fromstring(Sig.data) +for _, e in Enc do + t:eq(e.ffmpegErrors, "", e.name .. ": ffmpeg reads our file without errors") + t:check(e.frames == Sig.frames and e.rate == Sig.rate, e.name .. ": ffmpeg frames / rate") + t:check(e.maxDiff <= TOL[e.name] + 1e-7, string.format("%s: ffmpeg decode within %g (max diff %g)", e.name, TOL[e.name], e.maxDiff)) + t:check(e.sameStreamed, e.name .. ": encoding a Decoder gives the same bytes") + local back = Voc.decode(reader(e.data)) :: Types.Audio + t:check(back and back.frames == Sig.frames and back.channels == e.channels, e.name .. ": our decoder reads our file") + if e.channels == 2 then + t:check(maxDiff(back.samples, 0, sig, 0, Sig.frames * 2) <= TOL[e.name] + 1e-7, e.name .. ": round trip") + end +end +t:note("%d encoder outputs read back by ffmpeg and by us", #Enc) + +do + local a = Types.Audio.new(22050, 2, 1) + a.tags = { comment = "hi" } + local b = Voc.encode(a) :: buffer + local back = Voc.decode(Bytes.reader(b)) :: Types.Audio + t:check(back.frames == 1 and back.tags.comment == "hi", "one frame + comment") + local _, e1 = Voc.encode(nil :: any) + t:check(e1 and e1.code == Err.ARG, "encode nil: ARG") + local _, e2 = Voc.encode(a, { sampleFormat = "s24" } :: any) + t:check(e2 and e2.code == Err.ARG, "bad sampleFormat: ARG") + local _, e3 = Voc.decode(reader(Cases[1].data), { maxFrames = 5 }) + t:check(e3 and e3.code == Err.LIMIT, "maxFrames: LIMIT") +end + +do + local samples = {} + for _, c in Cases do + table.insert(samples, string.sub(c.data, 1, 300)) + end + t:fuzz("decode", function(b: buffer) + return Voc.decode(Bytes.reader(b)) + end, samples, { mutations = 30 }) +end + +t:done() diff --git a/tests/audio/vorbis.luau b/tests/audio/vorbis.luau new file mode 100644 index 0000000..2cc5c01 --- /dev/null +++ b/tests/audio/vorbis.luau @@ -0,0 +1,193 @@ +-- audio/vorbis tests: oggenc / ffmpeg streams (qualities -1 .. 10, managed bitrate, 8 .. 96 kHz, mono / stereo / 5.1, +-- transients, silence, tags, sub-block lengths) against oggdec (libvorbisfile: sample counts and 16-bit samples, so +-- start / end trimming is exact) and ffmpeg's f32 decode (SNR); streaming reads; seeking (sample-exact against the +-- reference at the target); the packet-level decoder; errors; fuzz. Fixtures: tools/fixtures/vorbis.py. +local T = require("@tests/T") +local Vorbis = require("@formats/audio/vorbis") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Ogg = require("@formats/containers/Ogg") +local Cases = require("@tests/gen/vorbis_cases") + +local t = T.suite("vorbis") + +local function reader(s: string): Bytes.Reader + return Bytes.reader(buffer.fromstring(s)) +end +local function s16(x: number): number + local v = math.floor(x * 32768 + 0.5) + return math.clamp(v, -32768, 32767) +end +-- the largest |our sample as s16 - oggdec's| over n samples of ours at byte a0 against ref16 from sample r0 +local function maxDiff16(a: buffer, a0: number, ref: buffer, r0: number, n: number): number + local m = 0 + for i = 0, n - 1 do + local d = math.abs(s16(buffer.readf32(a, a0 + i * 4)) - buffer.readi16(ref, (r0 + i) * 2)) + if d > m then + m = d + end + end + return m +end +local function snr(a: buffer, ref: buffer, n: number): number + local sig, er = 0, 0 + for i = 0, n - 1 do + local x = buffer.readf32(ref, i * 4) + local d = x - buffer.readf32(a, i * 4) + sig += x * x + er += d * d + end + if er == 0 then + return 200 + end + return if sig > 0 then 10 * math.log10(sig / er) else -200 +end + +t:eq(Vorbis.name, "vorbis", "name") +t:eq(Vorbis.category, "audio", "category") +t:check(Vorbis.caps.decode and Vorbis.open ~= nil, "caps") + +local minSnr = math.huge +for _, c in Cases do + local a, err = Vorbis.decode(reader(c.data)) + t:check(a, c.name .. ": " .. tostring(err)) + t:check(a.sampleRate == c.rate and a.channels == c.channels, c.name .. ": format") + t:eq(a.frames, c.frames, c.name .. ": frames = oggdec's") + t:eq(a.frames, c.inputFrames, c.name .. ": frames = the encoder's input") + local ref16 = buffer.fromstring(c.ref16) + local n = c.frames * c.channels + local d = maxDiff16(a.samples, 0, ref16, 0, n) + t:check(d <= 1, string.format("%s: within 1 LSB of oggdec (max %d)", c.name, d)) + if c.ffRef then + local s = snr(a.samples, buffer.fromstring(c.ffRef), n) + minSnr = math.min(minSnr, s) + t:check(s > 100, string.format("%s: SNR vs ffmpeg %.1f dB", c.name, s)) + end + -- streaming in odd chunks gives the same samples + local dec = Vorbis.open(reader(c.data)) :: Types.Decoder + t:eq(dec.frames, c.frames, c.name .. ": Decoder.frames") + local got, ok = 0, true + while true do + local b, k = dec:read(1013) + if k == 0 then + break + end + for i = 0, k * c.channels - 1, 7 do + ok = ok and buffer.readf32(b, i * 4) == buffer.readf32(a.samples, got * c.channels * 4 + i * 4) + end + got += k + end + t:check(ok and got == c.frames, c.name .. ": streamed reads") + -- seeks: sample-exact against the full decode + for _, frac in { 0.5, 0.1, 0.93, 0 } do + local target = math.floor(c.frames * frac) + dec:seek(target / c.rate) + t:check(math.abs(dec:position() - target / c.rate) < 1e-9, c.name .. ": position after seek") + local b, k = dec:read(300) + local want = math.min(300, c.frames - target) + t:eq(k, want, string.format("%s: frames after seek to %d", c.name, target)) + local same = true + for i = 0, k * c.channels - 1 do + same = same and buffer.readf32(b, i * 4) == buffer.readf32(a.samples, (target * c.channels + i) * 4) + end + t:check(same, string.format("%s: samples after seek to %d", c.name, target)) + end +end +t:note("%d streams match oggdec (counts, 1 LSB) and ffmpeg (min SNR %.1f dB)", #Cases, minSnr) + +local function case(name: string): any + for _, c in Cases do + if c.name == name then + return c + end + end + error("no case " .. name) +end + +-- tags, meta, sniff, sub-range +do + local c = case("q2-stereo-32k-tags") + local dec = Vorbis.open(reader(c.data)) :: any + t:eq(dec.tags.title, "A Title", "title tag") + t:eq(dec.tags.artist, "An Artist", "artist tag") + t:eq(dec.tags.album, "The Album", "album tag") + t:eq(dec.tags.track, "7", "track tag") + t:eq(dec.tags.comment, "hello vorbis", "comment tag") + t:check(type(dec.vendor) == "string" and string.find(dec.vendor, "Xiph", 1, true) ~= nil, "vendor") + t:check(dec.bitrate > 0 and math.abs(dec.duration - c.frames / c.rate) < 1e-9, "bitrate / duration") + t:eq(Vorbis.sniff(reader(c.data)), 1, "sniff") + t:eq(Vorbis.sniff(reader("OggS")), 0, "sniff short") + t:eq(Vorbis.sniff(reader("RIFF")), 0, "sniff other") + local big = buffer.create(#c.data + 11) + buffer.writestring(big, 11, c.data) + local a = Vorbis.decode(Bytes.reader(big, 11, #c.data)) + t:check(a and a.frames == c.frames, "decode from a sub-range") +end + +-- the packet-level decoder (as Matroska / MP4 would use it) gives the same samples, minus the Ogg trimming +do + local c = case("q5-stereo-44k-music") + local full = Vorbis.decode(reader(c.data)) :: Types.Audio + local demux = Ogg.open(buffer.fromstring(c.data)) + local serial = demux:find("vorbis") + local h = {} + for i = 1, 3 do + h[i] = Ogg.copy(demux:nextPacket(serial)) + end + local pd = Vorbis.packetDecoder(h[1], h[2], h[3]) + t:check(pd and pd.channels == 2 and pd.sampleRate == 44100, "packetDecoder") + local total, same = 0, true + for p in demux:packets(serial) do + local n = pd:decode(p.data, p.offset, p.size) + for i = 1, n, 13 do + if total + i <= full.frames then + same = same and math.abs(pd.out[1][i] - buffer.readf32(full.samples, (total + i - 1) * 8)) < 1e-6 + end + end + total += math.max(n, 0) + end + t:check(same and total >= full.frames, "packetDecoder samples") + local _, e = Vorbis.packetDecoder(h[2], h[1], h[3]) + t:check(e and e.code == Err.CORRUPT, "packetDecoder with headers swapped") +end + +-- errors +do + local _, e1 = Vorbis.decode(reader("OggS but not really")) + t:check(e1 and Err.is(e1), "junk: " .. tostring(e1)) + local c = case("short-100").data + local _, e2 = Vorbis.decode(reader(string.sub(c, 1, 60))) + t:check(e2 and Err.is(e2), "cut in the headers: " .. tostring(e2)) + -- a truncated stream decodes what is there + local q = case("q5-stereo-44k-music") + local cut = Vorbis.decode(reader(string.sub(q.data, 1, #q.data // 2)), { verify = false }) + t:check(cut and cut.frames > 0 and cut.frames < q.frames, "truncated stream") +end + +-- fuzz: whole streams with mutations past the headers, truncations, garbage +do + local samples = {} + for _, name in { "short-100", "short-3000-mono", "q-1-mono-8k-music", "ffmpeg-mono-16k" } do + table.insert(samples, case(name).data) + end + t:fuzz("decode", function(b: buffer) + return Vorbis.decode(Bytes.reader(b), { verify = false }) + end, samples, { mutations = 40 }) + t:fuzz("decode (CRC checked)", function(b: buffer) + return Vorbis.decode(Bytes.reader(b)) + end, samples, { mutations = 5, garbage = 20 }) + t:fuzz("open + seek", function(b: buffer) + local d = Vorbis.open(Bytes.reader(b), { verify = false }) + if d then + d:read(500) + d:seek(0.05) + d:read(500) + d:seek(1e9) + d:read(10) + end + return d + end, samples, { mutations = 10, garbage = 20 }) +end + +t:done() diff --git a/tests/audio/vorbis_encode.luau b/tests/audio/vorbis_encode.luau new file mode 100644 index 0000000..c85a39d --- /dev/null +++ b/tests/audio/vorbis_encode.luau @@ -0,0 +1,110 @@ +-- audio/vorbis encoder tests: every fixture-step encode (qualities -1 .. 10, mono / stereo / 5.1, 8 .. 96 kHz, odd +-- lengths, silence) passes ogginfo, decodes in oggdec (libvorbisfile) with the exact input length and an SNR over a +-- per-quality floor, and in ffmpeg; our own decoder gives the same; the codebooks are valid prefix codes; streaming +-- from a Decoder gives the same bytes; tags round-trip; option errors. Fixtures: tools/fixtures/vorbis_enc.py. +local T = require("@tests/T") +local Vorbis = require("@formats/audio/vorbis") +local VEnc = require("@formats/audio/vorbis/Encode") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/Pcm") +local Enc = require("@tests/gen/vorbis_enc") +local Sigs = require("@tests/gen/vorbis_enc_sigs") + +local t = T.suite("vorbis_encode") + +local function audio(name: string): Types.Audio + local s = Sigs[name] + local a = Types.Audio.new(s.rate, s.channels, s.frames) + buffer.writestring(a.samples, 0, s.data) + return a +end +local function snr(x: Types.Audio, y: Types.Audio): number + local sig, er = 0, 0 + for i = 0, math.min(x.frames, y.frames) * x.channels - 1 do + local a = buffer.readf32(x.samples, i * 4) + local d = a - buffer.readf32(y.samples, i * 4) + sig += a * a + er += d * d + end + if er == 0 then + return 200 + end + return if sig > 0 then 10 * math.log10(sig / er) else -200 +end +local function floorFor(q: number): number + return 8 + 1.2 * math.max(q, 0) +end + +t:check(Vorbis.caps.encode and Vorbis.encode ~= nil, "caps.encode") + +-- the codebooks: Kraft sums of exactly 1 (complete prefix codes) and lengths 1 .. 24 +for i, b in VEnc.BOOKS do + local k, okLen = 0, true + for _, l in b.lengths do + k += 2 ^ -l + okLen = okLen and l >= 1 and l <= 24 + end + t:check(math.abs(k - 1) < 1e-9 and okLen, "codebook " .. (i - 1) .. ": complete prefix code") +end + +local minSnr = math.huge +for _, e in Enc do + t:eq(e.ogginfo, "", e.name .. ": ogginfo reports no warnings / errors") + t:eq(e.oggdecFrames, e.frames, e.name .. ": oggdec frames = input frames") + t:eq(e.ffErrors, "", e.name .. ": ffmpeg decodes without errors") + local silent = string.find(e.name, "silence", 1, true) ~= nil + local f = if silent then -math.huge else floorFor(e.quality) + t:check(e.oggdecSnr >= f, string.format("%s: oggdec SNR %.1f dB (floor %.1f)", e.name, e.oggdecSnr, f)) + if e.frames >= 2048 then + -- (ffmpeg does not trim the end of a stream that fits on one Ogg page: up to a block more) + t:check(e.ffFrames >= e.frames and e.ffFrames <= e.frames + 1024, string.format("%s: ffmpeg frames %d", e.name, e.ffFrames)) + t:check(e.ffSnr >= f, string.format("%s: ffmpeg SNR %.1f dB", e.name, e.ffSnr)) + end + if not silent then + minSnr = math.min(minSnr, e.oggdecSnr) + end + -- our decoder: the same length and quality (it is sample-exact with libvorbis) + local x = audio(e.sig) + local y, err = Vorbis.decode(Bytes.reader(buffer.fromstring(e.data))) + t:check(y, e.name .. ": our decoder: " .. tostring(err)) + t:eq(y.frames, e.frames, e.name .. ": our decoder's frames") + local s = snr(x, y) + t:check(math.abs(s - e.oggdecSnr) < 0.5 or s >= 100, string.format("%s: our decoder %.1f dB, oggdec %.1f dB", e.name, s, e.oggdecSnr)) +end +t:note("%d encodes pass ogginfo / oggdec / ffmpeg; lowest SNR %.1f dB", #Enc, minSnr) + +-- streaming, tags +do + local a = audio("music_2_3000_44100") + local f1 = Vorbis.encode(a) :: buffer + local f2 = Vorbis.encode(Pcm.audioDecoder(a)) :: buffer + t:check(buffer.tostring(f1) == buffer.tostring(f2), "Decoder source = Audio source") + a.tags = { title = "Tïtle", artist = "Artist", track = "9" } + local f3 = Vorbis.encode(a, { quality = 1, serial = 77 }) :: buffer + local d = Vorbis.open(Bytes.reader(f3)) :: any + t:eq(d.tags.title, "Tïtle", "title tag") + t:eq(d.tags.track, "9", "track tag") + t:check(string.find(d.vendor, "formats-luau", 1, true) ~= nil, "vendor") + local empty = Vorbis.encode(Types.Audio.new(44100, 1, 0)) :: buffer + local e0 = Vorbis.decode(Bytes.reader(empty)) + t:check(e0 and e0.frames == 0, "empty input") +end + +-- errors +do + local a = Types.Audio.new(44100, 2, 10) + local function code(v: any, o: any): string? + local _, e = Vorbis.encode(v, o) + return e and e.code + end + t:eq(code("x", nil), Err.ARG, "junk") + t:eq(code(a, { quality = 11 }), Err.ARG, "quality 11") + t:eq(code(a, { quality = -2 }), Err.ARG, "quality -2") + t:eq(code(a, { serial = -1 }), Err.ARG, "serial -1") + t:eq(code(Types.Audio.new(44100.5, 1, 1), nil), Err.ARG, "fractional rate") +end + +-- (the decoder's fuzz pass is in tests/audio/vorbis.luau; the encoder takes no untrusted bytes) +t:done() diff --git a/tests/codecs/aac.luau b/tests/codecs/aac.luau new file mode 100644 index 0000000..b340bd4 --- /dev/null +++ b/tests/codecs/aac.luau @@ -0,0 +1,182 @@ +-- codecs/Aac tests: AudioSpecificConfig parsing (every fixture's esds, explicit SBR / PS signalling from fdkaac, +-- crafted configs: PCE channel counts, 960-sample frames, Main / LTP object types), ADTS headers, raw frames decoded +-- straight from ADTS against ffmpeg's float decode, the FIL extension hook on HE-AAC (implicit SBR), reset, errors, +-- the fuzz no-throw pass on raw frames. Fixtures: tools/fixtures/m4a.py. +local T = require("@tests/T") +local Aac = require("@formats/codecs/Aac") +local IsoBmff = require("@formats/containers/IsoBmff") +local Bytes = require("@formats/core/Bytes") +local Bits = require("@formats/core/Bits") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/m4a_aac") +local He = require("@tests/gen/m4a_he") + +local t = T.suite("aac-codec") + +-- ADTS frames of a stream: { offset, size } of the raw blocks +local function frames(data: buffer): ({ { number } }, Aac.Adts?) + local out, p, first = {}, 0, nil + while true do + local h = Aac.adts(data, p, buffer.len(data)) + if not h or p + h.frameSize > buffer.len(data) then + break + end + first = first or h + table.insert(out, { p + h.headerSize, h.frameSize - h.headerSize }) + p += h.frameSize + end + return out, first +end + +-- ASCs from the M4A fixtures +for _, c in Fx do + if c.container == "m4a" then + local r = Bytes.reader(buffer.fromstring(c.data)) + local movie = IsoBmff.parse(r) :: IsoBmff.Movie + local cfg, err = Aac.config(movie.tracks[1].config :: buffer) + t:check(cfg, c.name .. ": " .. tostring(err)) + t:check(cfg.objectType == 2 and cfg.sampleRate == c.rate and cfg.channels == c.channels and not cfg.sbr, c.name .. ": AAC-LC config") + end +end +for _, c in He do + if string.sub(c.name, -4) == ".m4a" then + local r = Bytes.reader(buffer.fromstring(c.data)) + local movie = IsoBmff.parse(r) :: IsoBmff.Movie + local cfg, err = Aac.config(movie.tracks[1].config :: buffer) + t:check(cfg, c.name .. ": " .. tostring(err)) + t:check(cfg.sbr and cfg.sampleRate == c.rate // 2 and cfg.extensionRate == c.rate, c.name .. ": SBR signalled, core at half rate") + t:eq(cfg.ps, c.ps, c.name .. ": PS signalled") + end +end + +-- crafted configs +do + local asc = Aac.asc(2, 4, 2) + local cfg = Aac.config(asc) :: Aac.Config + t:check(cfg and cfg.sampleRate == 44100 and cfg.channels == 2, "asc(2, 44.1 kHz, stereo)") + local _, e1 = Aac.config(Aac.asc(1, 4, 2)) + t:check(e1 and e1.code == Err.UNSUPPORTED, "AAC Main: " .. tostring(e1)) + local _, e2 = Aac.config(Aac.asc(23, 4, 2)) + t:check(e2 and e2.code == Err.UNSUPPORTED, "ER AAC LD") + local b960 = Aac.asc(2, 3, 1) + buffer.writeu8(b960, 1, bit32.bor(buffer.readu8(b960, 1), 4)) -- frameLengthFlag + local _, e3 = Aac.config(b960) + t:check(e3 and e3.code == Err.UNSUPPORTED, "960-sample frames") + -- channel configuration 0 with a PCE: front C (SCE) + L/R (CPE), back L/R (CPE), one LFE = 6 channels + local bw = Bits.msbWriter() + bw:write(2, 5) + bw:write(3, 4) + bw:write(0, 4) + bw:write(0, 3) -- GASpecificConfig flags + bw:write(0, 4) -- PCE: tag + bw:write(1, 2) + bw:write(3, 4) + bw:write(2, 4) -- front + bw:write(0, 4) -- side + bw:write(1, 4) -- back + bw:write(1, 2) -- lfe + bw:write(0, 3) + bw:write(0, 4) + bw:write(0, 3) -- mixdowns + bw:write(0, 5) + bw:write(16 + 1, 5) -- front: SCE 0, CPE 1 + bw:write(16 + 2, 5) -- back: CPE 2 + bw:write(0, 4) -- lfe tag + bw:align() + bw:write(0, 8) -- comment + local pcfg, perr = Aac.config(bw:finish()) + t:check(pcfg and pcfg.channels == 6 and pcfg.channelConfig == 0, "PCE: 6 channels: " .. tostring(perr)) + local _, e4 = Aac.decoder("nope" :: any) + t:check(e4 and e4.code == Err.ARG, "decoder of a string") +end + +-- ADTS headers + raw frames against ffmpeg +for _, c in Fx do + if c.container ~= "adts" then + continue + end + local data = buffer.fromstring(c.data) + local list, h = frames(data) + t:check(h and h.objectType == 2 and h.sampleRate == c.rate, c.name .. ": ADTS header") + local dec = Aac.decoder({ sfIndex = (h :: Aac.Adts).sfIndex, channels = c.channels }) :: Aac.Decoder + local ref = buffer.fromstring(c.ref) + local sig, err = 0, 0 + local o = 0 + for _, f in list do + local n, e = dec:decode(data, f[1], f[2]) + t:check(n == 1024, c.name .. ": frame: " .. tostring(e)) + for k = 1, 1024 * c.channels do + local r = buffer.readf32(ref, o) + sig += r * r + err += (dec.pcm[k] - r) ^ 2 + o += 4 + end + end + local snr = 10 * math.log10(sig / math.max(err, 1e-30)) + t:check(snr > 90, string.format("%s: SNR %.1f dB", c.name, snr)) + t:note("%s: %d raw frames, SNR %.1f dB vs ffmpeg", c.name, #list, snr) + -- reset: decoding again from the start gives the same first frames + dec:reset() + dec:decode(data, list[1][1], list[1][2]) + local again = table.clone(dec.pcm) + local dec2 = Aac.decoder({ sfIndex = (h :: Aac.Adts).sfIndex, channels = c.channels }) :: Aac.Decoder + dec2:decode(data, list[1][1], list[1][2]) + local same = true + for k = 1, 1024 * c.channels do + same = same and again[k] == dec2.pcm[k] + end + t:check(same, c.name .. ": reset clears the overlap") +end + +-- the extension hook on HE-AAC (implicit SBR in ADTS) +for _, c in He do + if string.sub(c.name, -4) == ".aac" then + local data = buffer.fromstring(c.data) + local list, h = frames(data) + local dec = Aac.decoder({ sfIndex = (h :: Aac.Adts).sfIndex, channels = 2 }) :: Aac.Decoder + local seen, bits = 0, 0 + dec.onExtension = function(kind: number, _element: number, _buf: buffer, _pos: number, n: number) + if kind == 13 or kind == 14 then + seen += 1 + bits += n + end + end + for _, f in list do + dec:decode(data, f[1], f[2]) + end + t:check(seen == #list and dec.sbr, string.format("%s: an SBR payload per frame (%d of %d, %d bits)", c.name, seen, #list, bits)) + end +end + +-- errors +do + local dec = Aac.decoder(Aac.asc(2, 4, 2)) :: Aac.Decoder + local _, e = dec:decode(buffer.fromstring("\x20\x00\x00\x00\x00")) + t:check(e and e.code == Err.CORRUPT, "garbage frame: " .. tostring(e)) + local _, e2 = dec:decode(buffer.create(4), 3, 10) + t:check(e2 and e2.code == Err.ARG, "range out of the buffer") + t:check(Aac.adts(buffer.fromstring("\255\241"), 0, 2) == nil, "short ADTS header") +end + +-- fuzz raw frames (stereo with every tool, mono, 5.1) +do + local pick = {} + for _, c in Fx do + if c.container == "adts" then + local data = buffer.fromstring(c.data) + local list, h = frames(data) + local f = list[math.min(#list, 9)] + local raw = buffer.create(f[2]) + buffer.copy(raw, 0, data, f[1], f[2]) + table.insert(pick, { raw, (h :: Aac.Adts).sfIndex, c.channels }) + end + end + for _, p in pick do + local dec = Aac.decoder({ sfIndex = p[2], channels = p[3] }) :: Aac.Decoder + t:fuzz("raw frame " .. p[3] .. " ch", function(b: buffer) + return dec:decode(b) + end, { p[1] }, { mutations = 60, garbage = 100 }) + end +end + +t:done() diff --git a/tests/codecs/alac.luau b/tests/codecs/alac.luau new file mode 100644 index 0000000..8dff395 --- /dev/null +++ b/tests/codecs/alac.luau @@ -0,0 +1,181 @@ +-- codecs/Alac tests: encoder -> decoder round trips over silence (zero runs), full-scale noise (uncompressed frames), +-- tones, steps, 1 - 8 channels, 16 / 20 / 24 bits, partial and tiny frames, custom frame lengths; ffmpeg's ALAC +-- packets (through containers/IsoBmff) decode to the source integers; the magic cookie (plain, behind frma / alac atoms, +-- bad versions / depths); errors; the fuzz no-throw pass on packets. Fixtures: tools/fixtures/m4a.py. +local T = require("@tests/T") +local Alac = require("@formats/codecs/Alac") +local IsoBmff = require("@formats/containers/IsoBmff") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/m4a_alac") + +local t = T.suite("alac") +local rand = T.rng(42) + +local function roundTrip(label: string, ch: number, bits: number, frames: number, gen: (number, number) -> number, fl: number?) + local enc = Alac.encoder({ sampleRate = 44100, channels = ch, bitDepth = bits, frameLength = fl }) :: Alac.Encoder + t:check(enc, label .. ": encoder") + local per = enc.config.frameLength + local src = table.create(frames * ch, 0) + for i = 0, frames - 1 do + for c = 1, ch do + src[i * ch + c] = gen(i, c) + end + end + local packets = {} + local bytes = 0 + local f = 0 + while f < frames do + local n = math.min(per, frames - f) + local p, err = enc:encode(src, f * ch + 1, n) + t:check(p, label .. ": encode: " .. tostring(err)) + table.insert(packets, { p, n }) + bytes += buffer.len(p :: buffer) + f += n + end + local cfg = Alac.config(Alac.cookie(enc.config)) :: Alac.Config + t:check(cfg and cfg.maxFrameBytes >= 1 and cfg.channels == ch and cfg.bitDepth == bits, label .. ": cookie") + local dec = Alac.decoder(cfg) + local ok = true + local at = 0 + for _, pk in packets do + local n, err = dec:decode(pk[1]) + if n ~= pk[2] then + ok = false + t:check(false, label .. ": decode: " .. tostring(err)) + break + end + for k = 1, n * ch do + if dec.pcm[k] ~= src[at * ch + k] then + ok = false + end + end + at += n + end + t:check(ok, label .. ": round trip") + return bytes / (frames * ch * bits / 8) +end + +local peakOf = function(bits: number): number + return 2 ^ (bits - 1) +end + +for _, bits in { 16, 20, 24 } do + local pk = peakOf(bits) + for _, ch in { 1, 2, 3, 6, 8 } do + local r1 = roundTrip(string.format("tone %d-bit %d ch", bits, ch), ch, bits, 9000, function(i, c) + return math.floor(math.sin(i * 0.031 * c) * (pk * 0.6) + math.sin(i * 0.0071) * pk * 0.2) + end) + if ch == 2 then + t:note("%d-bit stereo tone: %.0f%% of PCM", bits, r1 * 100) + end + end + roundTrip(bits .. "-bit silence (zero runs)", 2, bits, 10000, function() + return 0 + end) + local r = roundTrip(bits .. "-bit full-scale noise (escape frames)", 2, bits, 5000, function() + return rand(2 ^ bits) - pk + end) + t:check(r < 1.01, bits .. "-bit noise stays near PCM size") + roundTrip(bits .. "-bit extremes", 1, bits, 600, function(i) + return if i % 2 == 0 then pk - 1 else -pk + end) + roundTrip(bits .. "-bit sparse clicks (zero runs + values)", 2, bits, 7000, function(i, c) + return if i % 997 == c then pk // 3 else 0 + end) +end +for _, n in { 1, 2, 3, 5, 9, 17, 4095 } do + roundTrip("partial frame of " .. n, 2, 16, n, function(i, c) + return (i * 37 + c * 1000) % 3000 - 1500 + end) +end +roundTrip("frame length 1024", 2, 16, 5000, function(i) + return math.floor(math.sin(i * 0.05) * 10000) +end, 1024) +roundTrip("identical channels", 2, 16, 5000, function(i) + return math.floor(math.sin(i * 0.02) * 20000) +end) + +-- ffmpeg's packets +for _, c in Fx do + if c.container == "m4a" then + local r = Bytes.reader(buffer.fromstring(c.data)) + local movie = IsoBmff.parse(r) :: IsoBmff.Movie + local tr = movie.tracks[1] + local cfg = Alac.config(tr.config :: buffer) :: Alac.Config + t:check(cfg and cfg.bitDepth == c.bits and cfg.channels == c.channels, c.name .. ": cookie") + local dec = Alac.decoder(cfg) + local out = buffer.create(c.frames * c.channels * 4) + local o = 0 + for i = 1, tr.sampleCount do + local n, err = dec:decode(r.buf, tr.offsets[i], tr.sizes[i]) + t:check(n, c.name .. ": packet " .. i .. ": " .. tostring(err)) + for k = 1, (n :: number) * c.channels do + buffer.writei32(out, o, dec.pcm[k]) + o += 4 + end + end + t:eq(Crc32.of(out), c.crc, c.name .. ": ffmpeg's packets decode to the source") + end +end + +-- the cookie behind QuickTime atoms, bad cookies +do + local enc = Alac.encoder({ sampleRate = 48000, channels = 2 }) :: Alac.Encoder + local plain = Alac.cookie(enc.config) + local w = Bytes.writer(64) + w:u32be(12) + w:string("frma") + w:string("alac") + w:u32be(36) + w:string("alac") + w:u32be(0) + w:bytes(plain) + local cfg = Alac.config(w:finish()) + t:check(cfg and cfg.sampleRate == 48000 and cfg.frameLength == 4096, "cookie behind frma / alac atoms") + local bad = buffer.fromstring(buffer.tostring(plain)) + buffer.writeu8(bad, 5, 12) + local _, e = Alac.config(bad) + t:check(e and e.code == Err.UNSUPPORTED, "12-bit cookie: " .. tostring(e)) + local _, e2 = Alac.config(buffer.create(10)) + t:check(e2 and e2.code == Err.TRUNCATED, "short cookie") + local _, e3 = Alac.encoder({ sampleRate = 44100, channels = 9 }) + t:check(e3 and e3.code == Err.ARG, "9 channels") + local _, e4 = enc:encode({ 1, 2 }, 1, 5) + t:check(e4 and e4.code == Err.ARG, "too few samples") + local dec = Alac.decoder(cfg :: Alac.Config) + local _, e5 = dec:decode(buffer.fromstring("\1\255\255\255")) + t:check(e5 and e5.code == Err.CORRUPT, "bad packet: " .. tostring(e5)) +end + +-- fuzz the packet decoder +do + local enc = Alac.encoder({ sampleRate = 44100, channels = 2, bitDepth = 16 }) :: Alac.Encoder + local src = table.create(2 * 3000, 0) + for i = 1, #src do + src[i] = math.floor(math.sin(i * 0.01) * 8000) + rand(64) + end + local samples = {} + table.insert(samples, (enc:encode(src, 1, 3000))) + for i = 1, #src do + src[i] = if i % 300 < 3 then 5000 else 0 + end + table.insert(samples, (enc:encode(src, 1, 3000))) + local dec = Alac.decoder(enc.config) + local enc24 = Alac.encoder({ sampleRate = 44100, channels = 1, bitDepth = 24 }) :: Alac.Encoder + local dec24 = Alac.decoder(enc24.config) + local s24 = table.create(2000, 0) + for i = 1, 2000 do + s24[i] = rand(2 ^ 24) - 2 ^ 23 + end + local p24 = enc24:encode(s24, 1, 2000) :: buffer + t:fuzz("decode packet", function(b: buffer) + return dec:decode(b) + end, samples, { mutations = 40 }) + t:fuzz("decode 24-bit escape packet", function(b: buffer) + return dec24:decode(b) + end, { p24 }, { mutations = 20, garbage = 50 }) +end + +t:done() diff --git a/tests/codecs/jpeg.luau b/tests/codecs/jpeg.luau new file mode 100644 index 0000000..5b42f8d --- /dev/null +++ b/tests/codecs/jpeg.luau @@ -0,0 +1,273 @@ +-- codecs/Jpeg tests (the Motion-JPEG side; tests/image/jpeg.luau covers the still-image decoder and encoder through +-- image/jpeg): ffmpeg mjpeg frames (4:2:0, 4:2:2, 4:4:4, odd sizes, stripped DHT, AVI1 + junk after EOI) decoded +-- to yuv420p bit-exact with libjpeg-turbo's IDCT planes (TurboJPEG) and to rgba8 bit-exact with djpeg, and within +-- PSNR thresholds of ffmpeg's own decode; an interlaced AVI1 frame (two fields) woven; the yuv420p encoder +-- byte-identical to TurboJPEG's tj3CompressFromYUV8, read back by djpeg (exact) and ffmpeg (PSNR); the API's +-- arguments; the fuzz no-throw pass. Fixtures: tools/fixtures/mjpeg.py. +local T = require("@tests/T") +local Jpeg = require("@formats/codecs/Jpeg") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Base64 = require("@formats/core/Base64") +local Deflate = require("@formats/codecs/Deflate") +local Fx = require("@tests/gen/mjpeg_cases") +local Enc = require("@tests/gen/mjpeg_enc") + +local t = T.suite("codecs/jpeg") + +-- the fixtures' binary fields: base64, and base64 of zlib data for raw planes / pixels +local function b64(s: string): string + return buffer.tostring(Base64.decode(s) :: buffer) +end +local function z64(s: string): buffer + return Deflate.zlib(Base64.decode(s) :: buffer) :: buffer +end +for _, s in Fx.streams do + for _, f in s.frames do + f.data = b64(f.data) + end + s.ff.yuv = z64(s.ff.yuv) + if s.ff.rgba then + s.ff.rgba = z64(s.ff.rgba) + end +end +Fx.fields.data = b64(Fx.fields.data) +for _, c in Enc do + c.want = b64(c.want) +end + +-- PSNR of n bytes of a at ao against b at bo +local function psnr(a: buffer, ao: number, b: buffer, bo: number, n: number): number + local se = 0 + for i = 0, n - 1 do + local d = buffer.readu8(a, ao + i) - buffer.readu8(b, bo + i) + se += d * d + end + if se == 0 then + return 99 + end + return 10 * math.log10(255 * 255 * n / se) +end + +-- PSNR of the RGB channels of two rgba8 buffers of n pixels +local function psnrRgb(a: buffer, b: buffer, n: number): number + local se = 0 + for i = 0, n - 1 do + for k = 0, 2 do + local d = buffer.readu8(a, i * 4 + k) - buffer.readu8(b, i * 4 + k) + se += d * d + end + end + if se == 0 then + return 99 + end + return 10 * math.log10(255 * 255 * n * 3 / se) +end + +local function hasDht(s: string): boolean + local at = string.find(s, "\255\196", 1, true) + local sos = string.find(s, "\255\218", 1, true) + return at ~= nil and sos ~= nil and at < sos +end + +-- 1. ffmpeg's frames: yuv420p (TurboJPEG planes) and rgba8 (djpeg) bit-exact, PSNR against ffmpeg's decode +do + local frames, worstY, worstC, worstRgb = 0, 99, 99, 99 + for _, s in Fx.streams do + local w, h = s.width, s.height + local cw, ch = (w + 1) // 2, (h + 1) // 2 + for i, f in s.frames do + local label = string.format("%s frame %d", s.name, i) + local b = buffer.fromstring(f.data) + local img, err = Jpeg.decode(b, 0, buffer.len(b), { yuv = true }) + t:check(img, label .. ": " .. tostring(err)) + t:check(img.format == "yuv420p" and img.width == w and img.height == h, label .. ": a yuv420p " .. w .. "x" .. h .. " Image") + t:eq(buffer.len(img.pixels), w * h + 2 * cw * ch, label .. ": plane sizes") + t:check(img.meta.source.yuv == s.sampling and img.meta.source.range == "full", label .. ": meta.source.yuv " .. tostring(img.meta.source.yuv)) + t:check(not img.meta.truncated, label .. ": not truncated") + t:eq(Crc32.of(img.pixels), f.yuv, label .. ": yuv420p planes = TurboJPEG's") + local rgba = Jpeg.decode(b) :: Types.Image + t:check(rgba and rgba.format == "rgba8", label .. ": rgba8") + t:eq(Crc32.of(rgba.pixels), f.rgba, label .. ": rgba8 = djpeg") + if i == 1 then + local ref = s.ff.yuv + local py = psnr(img.pixels, 0, ref, 0, w * h) + local pc = math.min(psnr(img.pixels, w * h, ref, w * h, cw * ch), psnr(img.pixels, w * h + cw * ch, ref, w * h + cw * ch, cw * ch)) + -- ffmpeg's IDCT differs from libjpeg's islow by rounding only; its 4:2:2 / 4:4:4 -> 4:2:0 is a filter + t:check(py > 55, string.format("%s: luma PSNR %.1f dB against ffmpeg", s.name, py)) + t:check(pc > (if s.sampling == "420" then 55 else 20), string.format("%s: chroma PSNR %.1f dB against ffmpeg", s.name, pc)) + worstY, worstC = math.min(worstY, py), math.min(worstC, pc) + if s.ff.rgba then + local pr = psnrRgb(rgba.pixels, s.ff.rgba, w * h) + -- swscale upsamples chroma differently from libjpeg (fancy): testsrc2's sharp colour edges cost ~10 dB + t:check(pr > 25, string.format("%s: rgba PSNR %.1f dB against ffmpeg", s.name, pr)) + worstRgb = math.min(worstRgb, pr) + end + end + if string.find(s.name, "nodht") then + t:check(not hasDht(f.data), label .. ": no DHT segment") + end + if s.name == "avi1_junk" then + t:eq(img.meta.source.avi1, 0, label .. ": AVI1 polarity") + t:eq(Jpeg.info(b).avi1, 0, label .. ": info.avi1") + end + frames += 1 + end + end + t:note("%d ffmpeg mjpeg frames bit-exact (yuv420p: TurboJPEG, rgba8: djpeg); worst PSNR against ffmpeg: luma %.1f, chroma %.1f, rgba %.1f dB", frames, worstY, worstC, worstRgb) +end + +-- 2. an interlaced frame: two fields (AVI1 polarity 1) woven, field 1 on the even rows +do + local F = Fx.fields + local b = buffer.fromstring(F.data) + local img = Jpeg.decode(b, 0, nil, { yuv = true }) :: Types.Image + t:check(img and img.width == F.width and img.height == F.height and img.format == "yuv420p", "fields: one 320x240 yuv420p frame") + t:eq(img.meta.source.fields, 2, "fields: meta.source.fields") + t:eq(Crc32.of(img.pixels), F.yuv, "fields: woven yuv420p planes = TurboJPEG's fields woven") + local src = z64(F.src) + local p = psnr(img.pixels, 0, src, 0, F.width * F.height) + t:check(p > 35, string.format("fields: luma PSNR %.1f dB against the source frame", p)) + local rgba = Jpeg.decode(b) :: Types.Image + t:check(rgba.height == F.height and Crc32.of(rgba.pixels) == F.rgba, "fields: woven rgba8 = djpeg's fields woven") + local one = Jpeg.decode(b, 0, nil, { yuv = true, fields = false }) :: Types.Image + t:check(one.height == F.height // 2 and one.meta.source.fields == 1, "fields = false: the first field only") + -- the first field alone (no second JPEG): a half-height frame, not an error + local first = string.find(F.data, "\255\217", 1, true) :: number + local half = Jpeg.decode(buffer.fromstring(string.sub(F.data, 1, first + 1)), 0, nil, { yuv = true }) :: Types.Image + t:check(half and half.height == F.height // 2 and half.meta.source.fields == 1, "a missing second field leaves the first") + t:check(Jpeg.info(b).avi1 == 1, "fields: info.avi1") +end + +-- 3. the yuv420p encoder: byte-identical with TurboJPEG, read back by djpeg (exact) and ffmpeg (PSNR) +do + local exact = 0 + for _, c in Enc do + local img = Types.Image.new(c.width, c.height, "yuv420p") + img.pixels = z64(c.yuv) + local out, err = Jpeg.encode(img, { quality = c.quality }) + t:check(out, c.name .. ": " .. tostring(err)) + local s = buffer.tostring(out :: buffer) + if s ~= c.want then + local at = 0 + for i = 1, math.min(#s, #c.want) do + if string.byte(s, i) ~= string.byte(c.want, i) then + at = i + break + end + end + t:check(false, string.format("%s: differs from tj3CompressFromYUV8 at byte %d (ours %d bytes, TurboJPEG %d)", c.name, at, #s, #c.want)) + end + exact += 1 + local back = Jpeg.decode(out :: buffer) :: Types.Image + t:eq(Crc32.of(back.pixels), c.rgba, c.name .. ": our decode of it = djpeg's") + local floor = if c.quality >= 75 then 30 else 26 + if c.width * c.height >= 1000 then + t:check(c.ffpsnr > floor, string.format("%s: ffmpeg reads it at %.1f dB luma PSNR", c.name, c.ffpsnr)) + local y = Jpeg.decode(out :: buffer, 0, nil, { yuv = true }) :: Types.Image + local p = psnr(y.pixels, 0, img.pixels, 0, c.width * c.height) + t:check(p > floor, string.format("%s: yuv round trip %.1f dB", c.name, p)) + end + end + t:note("%d yuv420p encodes byte-identical with tj3CompressFromYUV8", exact) + -- grey from yuv420p: the luma plane only + local c = Enc[1] + local img = Types.Image.new(c.width, c.height, "yuv420p") + img.pixels = z64(c.yuv) + local g = Jpeg.encode(img, { quality = 80, gray = true }) :: buffer + local gi = Jpeg.info(g) + t:check(gi and gi.components == 1, "yuv420p with gray = true: one component") + local gy = Jpeg.decode(g, 0, nil, { yuv = true }) :: Types.Image + t:check(gy.format == "yuv420p" and gy.meta.source.yuv == "gray" and buffer.readu8(gy.pixels, c.width * c.height) == 128, "grey decodes to yuv420p with chroma 128") + local p = Jpeg.encode(img, { quality = 80, progressive = true, restart = 2 }) :: buffer + local pi = Jpeg.info(p) + t:check(pi and pi.progressive and pi.sampling[1][1] == 2 and pi.sampling[1][2] == 2, "yuv420p progressive") + local pd = Jpeg.decode(p, 0, nil, { yuv = true }) :: Types.Image + t:check(psnr(pd.pixels, 0, img.pixels, 0, c.width * c.height) > 30, "yuv420p progressive round trip") + local s4 = Jpeg.encode(img, { subsampling = "444" }) :: buffer + t:eq(Jpeg.info(s4).sampling[1][1], 2, "yuv420p input is always 4:2:0") + -- extra segments and density + local seg = Jpeg.encode(img, { segments = { { marker = 0xFE, data = buffer.fromstring("hello") } }, density = { unit = 1, x = 72, y = 72 } }) :: buffer + local sd = Jpeg.decode(seg) :: Types.Image + t:check(sd.meta.text and sd.meta.text.comment == "hello" and sd.meta.dpi and sd.meta.dpi.x == 72, "segments and density") +end + +-- 4. the API: ranges, options, fallbacks, errors +do + local s = Fx.streams[1] + local data = s.frames[1].data + local big = buffer.create(#data + 30) + buffer.writestring(big, 17, data) + local a = Jpeg.decode(big, 17, #data, { yuv = true }) :: Types.Image + t:eq(Crc32.of(a.pixels), s.frames[1].yuv, "decode from a sub-range") + local i = Jpeg.info(big, 17, #data) + t:check(i and i.width == s.width and i.colorSpace == "ycbcr" and i.sampling[1][2] == 2, "info from a sub-range") + local sc = Jpeg.decode(buffer.fromstring(data), 0, nil, { yuv = true, scale = 2 }) :: Types.Image + t:check(sc.format == "rgba8" and sc.width == s.width // 2, "yuv with scale 2 falls back to rgba8") + local _, e1 = Jpeg.decode("nope" :: any) + t:check(e1 and e1.code == Err.ARG, "decode(string)") + local _, e2 = Jpeg.decode(buffer.fromstring("nope")) + t:check(e2 and e2.code == Err.CORRUPT, "junk") + local _, e3 = Jpeg.decode(buffer.fromstring(data), 0, nil, { maxPixels = 100, yuv = true }) + t:check(e3 and e3.code == Err.LIMIT, "maxPixels") + local _, e4 = Jpeg.decode(buffer.fromstring(data), 0, nil, 5 :: any) + t:check(e4 and e4.code == Err.ARG, "non-table options") + local _, e5 = Jpeg.encode(Types.Image.new(4, 4, "rgba16")) + t:check(e5 and e5.code == Err.ARG, "rgba16 is refused") + local short = Types.Image.new(8, 8, "yuv420p") + short.pixels = buffer.create(70) + local _, e6 = Jpeg.encode(short) + t:check(e6 and e6.code == Err.ARG, "a short yuv420p buffer") + local _, e7 = Jpeg.encode(Types.Image.new(8, 8), { segments = { { marker = 0xC4, data = buffer.create(1) } } }) + t:check(e7 and e7.code == Err.ARG, "a bad segment marker") + local _, e8 = Jpeg.info(buffer.create(0)) + t:check(e8 and Err.is(e8), "info of nothing") + -- truncated frames decode as far as they go or fail with an Err + local cuts, partial = 0, 0 + for cut = 0, #data - 1, #data // 37 do + local img, err = Jpeg.decode(buffer.fromstring(string.sub(data, 1, cut)), 0, nil, { yuv = true }) + t:check(img or Err.is(err), "cut at " .. cut .. ": no image and no Err") + if img then + partial += 1 + t:check(img.meta.truncated, "cut at " .. cut .. ": flagged truncated") + end + cuts += 1 + end + t:note("%d truncated frames, %d decoded partially", cuts, partial) +end + +-- 5. speed (a note; tools/bench.luau has the real numbers) +do + local s = Fx.streams[1] + local frames = {} + for _, f in s.frames do + table.insert(frames, buffer.fromstring(f.data)) + end + local t0, n = os.clock(), 0 + while os.clock() - t0 < 0.3 do + for _, b in frames do + Jpeg.decode(b, 0, nil, { yuv = true }) + n += 1 + end + end + t:note("%dx%d yuv420p decode: %.0f fps", s.width, s.height, n / (os.clock() - t0)) +end + +-- 6. fuzz +do + local samples = {} + for k, s in Fx.streams do + if k % 2 == 1 then + table.insert(samples, s.frames[1].data) + end + end + t:fuzz("decode yuv", function(b: buffer) + return Jpeg.decode(b, 0, nil, { yuv = true }) + end, samples, { mutations = 4, keepHeader = 2 }) + t:fuzz("decode fields", function(b: buffer) + return Jpeg.decode(b, 0, nil, { fields = true }) + end, { Fx.fields.data }, { mutations = 3, garbage = 10 }) +end + +t:done() diff --git a/tests/codecs/mdct.luau b/tests/codecs/mdct.luau new file mode 100644 index 0000000..82d0e25 --- /dev/null +++ b/tests/codecs/mdct.luau @@ -0,0 +1,134 @@ +-- codecs/Mdct tests: the FFT against a direct DFT for mixed-radix sizes, the forward / inverse MDCT and the DCT-IV +-- against their O(N^2) definitions (AAC, Vorbis and CELT sizes), perfect reconstruction (TDAC) with the sine, KBD and +-- Vorbis windows, window power complementarity, bad sizes. No fixtures (the definitions are the reference). +local T = require("@tests/T") +local Mdct = require("@formats/codecs/Mdct") + +local t = T.suite("mdct") +local rand = T.rng(7) +local cos, sin, pi = math.cos, math.sin, math.pi + +local function noise(n: number): { number } + local a = table.create(n, 0) + for i = 1, n do + a[i] = rand(20001) / 10000 - 1 + end + return a +end + +-- FFT vs DFT +for _, n in { 1, 2, 3, 4, 5, 6, 7, 8, 12, 15, 16, 30, 49, 60, 64, 120, 240, 480, 77 } do + local plan = Mdct.fft(n) + t:check(plan, "fft plan " .. n) + local re, im = noise(n), noise(n) + local wr, wi = table.create(n, 0), table.create(n, 0) + for k = 0, n - 1 do + local sr, si = 0, 0 + for j = 0, n - 1 do + local a = -2 * pi * j * k / n + sr += re[j + 1] * cos(a) - im[j + 1] * sin(a) + si += re[j + 1] * sin(a) + im[j + 1] * cos(a) + end + wr[k + 1], wi[k + 1] = sr, si + end + Mdct.Fft.forward(plan :: any, re, im) + local err = 0 + for k = 1, n do + err = math.max(err, math.abs(re[k] - wr[k]), math.abs(im[k] - wi[k])) + end + t:check(err < 1e-9 * n, string.format("fft %d: max error %g", n, err)) +end + +-- MDCT / IMDCT vs the definitions +local maxErr = 0 +for _, n in { 4, 8, 16, 64, 240, 256, 480, 1920, 2048 } do + local plan = Mdct.new(n) :: Mdct.Plan + t:check(plan, "mdct plan " .. n) + local m = n // 2 + local x = noise(n) + local X = table.create(m, 0) + Mdct.forward(plan, x, 1, X, 1) + local Y = noise(m) + local y = table.create(n, 0) + Mdct.inverse(plan, Y, 1, 1, y, 1) + local step = if n > 500 then 37 else 1 -- spot-check the big sizes + local ef, ei = 0, 0 + for k = 0, m - 1, step do + local s = 0 + for j = 0, n - 1 do + s += x[j + 1] * cos(2 * pi / n * (j + 0.5 + n / 4) * (k + 0.5)) + end + ef = math.max(ef, math.abs(s - X[k + 1])) + end + for j = 0, n - 1, step do + local s = 0 + for k = 0, m - 1 do + s += Y[k + 1] * cos(2 * pi / n * (j + 0.5 + n / 4) * (k + 0.5)) + end + ei = math.max(ei, math.abs(s - y[j + 1])) + end + t:check(ef < 1e-9 * n and ei < 1e-9 * n, string.format("mdct %d: forward error %g, inverse error %g", n, ef, ei)) + maxErr = math.max(maxErr, ef, ei) + -- strided coefficients + offsets + scale + local X2 = table.create(m * 3 + 5, 0) + Mdct.forward(plan, x, 1, X2, 3, 3, 0.5) + local ok = true + for k = 0, m - 1 do + ok = ok and math.abs(X2[3 + 3 * k] - 0.5 * X[k + 1]) < 1e-9 + end + t:check(ok, "mdct " .. n .. ": strided / scaled forward") +end +t:note("mdct vs definition: max error %.3g", maxErr) + +-- TDAC: windowed forward + inverse + overlap-add reproduces the signal +for _, kind in { "sine", "kbd", "vorbis" } do + for _, n in { 256, 2048, 240 } do + local w = Mdct.window(kind, n, if n == 256 then 6 else 4) :: { number } + local m = n // 2 + local plan = Mdct.new(n) :: Mdct.Plan + local pc = 0 + for i = 1, m do + pc = math.max(pc, math.abs(w[i] ^ 2 + w[i + m] ^ 2 - 1)) + end + t:check(pc < 1e-12, kind .. " " .. n .. ": power complementary") + local frames = 6 + local sig = noise(m * (frames + 1)) + local out = table.create(m * (frames + 1), 0) + local buf, X, y = table.create(n, 0), table.create(m, 0), table.create(n, 0) + for f = 0, frames - 1 do + for i = 1, n do + buf[i] = sig[f * m + i] * w[i] + end + Mdct.forward(plan, buf, 1, X, 1) + Mdct.inverse(plan, X, 1, 1, y, 1, 4 / n) + for i = 1, n do + out[f * m + i] += y[i] * w[i] + end + end + local e = 0 + for i = m + 1, m * frames do + e = math.max(e, math.abs(out[i] - sig[i])) + end + t:check(e < 1e-9, string.format("%s %d: reconstruction error %g", kind, n, e)) + end +end + +-- DCT-IV is its own inverse (times 2 / M) +do + local plan = Mdct.new(512) :: Mdct.Plan + local u = noise(256) + local c, back = table.create(256, 0), table.create(256, 0) + Mdct.dct4(plan, u, 1, 1, c, 1, 1) + Mdct.dct4(plan, c, 1, 1, back, 1, 1, 2 / 256) + local e = 0 + for i = 1, 256 do + e = math.max(e, math.abs(back[i] - u[i])) + end + t:check(e < 1e-10, "dct4 involution: " .. e) +end + +-- bad sizes +t:check(Mdct.new(6) == nil and Mdct.new(0) == nil and Mdct.new(-8) == nil and Mdct.new(8.5) == nil and Mdct.new("x" :: any) == nil, "bad mdct sizes") +t:check(Mdct.fft(0) == nil and Mdct.window("nope", 8) == nil and Mdct.window("sine", 7) == nil, "bad fft sizes / windows") + +t:done() diff --git a/tests/codecs/mpeg1.luau b/tests/codecs/mpeg1.luau new file mode 100644 index 0000000..98b57e8 --- /dev/null +++ b/tests/codecs/mpeg1.luau @@ -0,0 +1,413 @@ +-- codecs/Mpeg1 tests, ported from mpeg1-luau tests/decode.luau and tests/robust.luau. Against ffmpeg +-- (tools/fixtures/mpeg1.py): every stream decodes, one access unit at a time, to as many frames as ffmpeg's decode, +-- in display order; each frame's RGBA channel means within 1.5 of ffmpeg's; whole sampled frames within 2 MAE per +-- channel (IDCT and colour rounding) and, as yuv420p (frameImage), within a PSNR floor of ffmpeg -pix_fmt yuv420p; +-- the same stream written in random pieces through write() / decodeFrame() gives identical frames; a size change. +-- Robustness / API: bad arguments, pictures before the first sequence header, reset(), rgba = false, tags through +-- B-frame reordering, string input, truncated units, bit flips and garbage (never throws, recovers at an +-- I-picture), an oversized sequence header; frameImage; the fuzz no-throw pass. +local T = require("@tests/T") +local Mpeg1 = require("@formats/codecs/Mpeg1") +local Base64 = require("@formats/core/Base64") +local Deflate = require("@formats/codecs/Deflate") +local Types = require("@formats/Types") + +local STREAMS = { + require("@tests/gen/mpeg1_qcif_200k"), + require("@tests/gen/mpeg1_main_450k"), + require("@tests/gen/mpeg1_zoom_150k"), + require("@tests/gen/mpeg1_zoom_1500k"), + require("@tests/gen/mpeg1_big_1000k"), + require("@tests/gen/mpeg1_odd_173x95"), + require("@tests/gen/mpeg1_matrix"), + require("@tests/gen/mpeg1_q1"), + require("@tests/gen/mpeg1_q31"), + require("@tests/gen/mpeg1_zeromv"), + require("@tests/gen/mpeg1_bframes"), + require("@tests/gen/mpeg1_bframes_zoom"), +} +local SizeChange = require("@tests/gen/mpeg1_sizechange") + +local t = T.suite("codecs/mpeg1") +local rand = T.rng(7) +local function between(a: number, b: number): number + return a + rand(b - a + 1) +end + +local function b64(s: string): buffer + return Base64.decode(s) :: buffer +end +local function z64(s: string): buffer + return Deflate.zlib(b64(s)) :: buffer +end + +-- mean absolute error per channel (r, g, b) between two RGBA8 buffers of n pixels, and the largest difference +local function mae(a: buffer, b: buffer, n: number): (number, number, number, number) + local sr, sg, sb, mx = 0, 0, 0, 0 + for i = 0, n - 1 do + local o = i * 4 + local dr = math.abs(buffer.readu8(a, o) - buffer.readu8(b, o)) + local dg = math.abs(buffer.readu8(a, o + 1) - buffer.readu8(b, o + 1)) + local db = math.abs(buffer.readu8(a, o + 2) - buffer.readu8(b, o + 2)) + sr += dr + sg += dg + sb += db + mx = math.max(mx, dr, dg, db) + end + return sr / n, sg / n, sb / n, mx +end + +local function means(a: buffer, n: number): (number, number, number) + local r, g, b = 0, 0, 0 + for i = 0, n - 1 do + local o = i * 4 + r += buffer.readu8(a, o) + g += buffer.readu8(a, o + 1) + b += buffer.readu8(a, o + 2) + end + return r / n, g / n, b / n +end + +local function psnr(a: buffer, ao: number, b: buffer, bo: number, n: number): number + local se = 0 + for i = 0, n - 1 do + local d = buffer.readu8(a, ao + i) - buffer.readu8(b, bo + i) + se += d * d + end + if se == 0 then + return 99 + end + return 10 * math.log10(255 * 255 * n / se) +end + +local MAE_LIMIT = 2 +local MEAN_LIMIT = 1.5 + +-- 1. every stream against ffmpeg +local worst, worstY, worstC = 0, 99, 99 +for _, fx in STREAMS do + local name = fx.name + local file = b64(fx.file) + local w, h = fx.width, fx.height + local n = w * h + local cw, ch = (w + 1) // 2, (h + 1) // 2 + local rgbaRef, yuvRef = {}, {} + for _, s in fx.rgba do + rgbaRef[s.index] = z64(s.pixels) + end + for _, s in fx.yuv do + yuvRef[s.index] = z64(s.planes) + end + local hasB = string.find(name, "bframes") ~= nil + local dec = Mpeg1.new({ reorder = hasB }) + local frames = 0 + local maxMae, maxMeanErr = 0, 0 + local sums = {} + local function onFrame(f: any) + frames += 1 + t:check(f.width == w and f.height == h, string.format("%s: size %dx%d", name, f.width, f.height)) + t:eq(f.index, frames, name .. ": frame index") + local px = f.pixels :: buffer + t:eq(buffer.len(px), n * 4, name .. ": pixels size") + local ref = fx.means[frames] + t:check(ref ~= nil, string.format("%s: more frames than ffmpeg (%d)", name, frames)) + local r, g, b = means(px, n) + local me = math.max(math.abs(r - ref[1]), math.abs(g - ref[2]), math.abs(b - ref[3])) + maxMeanErr = math.max(maxMeanErr, me) + t:check(me <= MEAN_LIMIT, string.format("%s frame %d: channel means off by %.2f", name, frames, me)) + local s = rgbaRef[frames] + if s then + local mr, mg, mb = mae(px, s, n) + local m = math.max(mr, mg, mb) + maxMae = math.max(maxMae, m) + t:check(m <= MAE_LIMIT, string.format("%s frame %d: MAE %.3f %.3f %.3f", name, frames, mr, mg, mb)) + local again = Mpeg1.frameImage(f, true) :: Types.Image + t:check(again.format == "rgba8" and buffer.tostring(again.pixels) == buffer.tostring(px), name .. ": frameImage(f, true) = frame.pixels") + end + local y = yuvRef[frames] + if y then + local img = Mpeg1.frameImage(f) :: Types.Image + t:check(img.format == "yuv420p" and img.width == w and img.height == h and buffer.len(img.pixels) == n + 2 * cw * ch, name .. ": frameImage yuv420p") + t:check(img.meta.source.range == "limited" and img.meta.source.pictureType == f.pictureType, name .. ": frameImage meta") + local py = psnr(img.pixels, 0, y, 0, n) + local pc = psnr(img.pixels, n, y, n, 2 * cw * ch) + worstY, worstC = math.min(worstY, py), math.min(worstC, pc) + t:check(py > 50 and pc > 50, string.format("%s frame %d: yuv420p PSNR %.1f / %.1f dB against ffmpeg", name, frames, py, pc)) + end + t:check(buffer.readu8(px, 3) == 255 and buffer.readu8(px, n * 4 - 1) == 255, "alpha 255") + sums[frames] = buffer.tostring(px) + end + local t0 = os.clock() + for _, u in fx.units do + local f = dec:decode(file, u[1], u[2]) + if f then + onFrame(f) + end + end + while true do + local f = dec:flush() + if f == nil then + break + end + onFrame(f) + end + local dt = os.clock() - t0 + t:eq(frames, fx.frames, name .. ": frames (ffmpeg's count)") + t:eq(dec.stats.errors, 0, name .. ": no bitstream errors") + worst = math.max(worst, maxMae) + t:note("%-13s %4dx%-4d %3d frames worst MAE %.3f means err %.3f %6.1f fps (with the checks)", name, w, h, frames, maxMae, maxMeanErr, frames / dt) + + -- streamed: random pieces through write / decodeFrame, then flush + local d2 = Mpeg1.new({ reorder = hasB }) + local got = 0 + local p, total = 0, buffer.len(file) + local function take(f: any) + got += 1 + t:check(sums[got] == buffer.tostring(f.pixels :: buffer), string.format("%s streamed frame %d identical", name, got)) + end + while p < total do + local k = math.min(total - p, between(1, 6000)) + t:check(d2:write(file, p, k), "write") + p += k + while true do + local f = d2:decodeFrame() + if f == nil then + break + end + take(f) + end + end + while true do + local f = d2:flush() + if f == nil then + break + end + take(f) + end + t:eq(got, frames, name .. ": streamed frame count") +end +t:note("worst sampled-frame MAE %.3f (limit %d); worst yuv420p PSNR luma %.1f, chroma %.1f dB", worst, MAE_LIMIT, worstY, worstC) + +-- 2. a size change mid-stream +do + local file = b64(SizeChange.file) + local dec = Mpeg1.new() + dec:write(file) + local list = {} + while true do + local f = dec:decodeFrame() or dec:flush() + if f == nil then + break + end + table.insert(list, { w = f.width, h = f.height, px = buffer.tostring(f.pixels :: buffer) }) + end + local a, b = SizeChange.parts[1], SizeChange.parts[2] + t:eq(#list, a.frames + b.frames, "sizechange: frame count") + t:check(list[1].w == a.width and list[1].h == a.height, "sizechange: first size") + t:check(list[a.frames].w == a.width and list[a.frames + 1].w == b.width and list[#list].h == b.height, "sizechange: second size") + for k, part in { a, b } do + local last = list[if k == 1 then a.frames else #list] + local mr, mg, mb = mae(buffer.fromstring(last.px), z64(part.last), part.width * part.height) + t:check(math.max(mr, mg, mb) <= MAE_LIMIT, string.format("sizechange part %d MAE %.3f %.3f %.3f", k, mr, mg, mb)) + end +end + +-- 3. robustness and the API +local function slice(b: buffer, from: number, n: number): buffer + local out = buffer.create(n) + buffer.copy(out, 0, b, from, n) + return out +end +local main = STREAMS[2] +local mainFile = b64(main.file) +local W, H = main.width, main.height +local ref = {} +do + local dec = Mpeg1.new() + for _, u in main.units do + local f = dec:decode(mainFile, u[1], u[2]) + table.insert(ref, buffer.tostring((f :: any).pixels)) + end + t:eq(#ref, #main.units, "reference decode") +end + +do -- bad arguments + local dec = Mpeg1.new() + t:check(dec:decode((nil :: any)) == nil, "decode(nil)") + t:check(dec:decode((42 :: any)) == nil, "decode(number)") + t:check(dec:write(buffer.create(4), 10) == false, "write offset past the end") + t:check(dec:write(buffer.create(4), 0, 9) == false, "write length past the end") + t:check(dec:write(buffer.create(4), -1) == false, "write negative offset") + t:check(dec:decodeFrame() == nil, "decodeFrame with no data") + t:check(dec:flush() == nil, "flush with no data") + t:check(Mpeg1.new((5 :: any)) ~= nil, "new(non-table)") + t:check(dec:decode(buffer.create(0)) == nil, "empty unit") + t:check(Mpeg1.frameImage(nil :: any) == nil and Mpeg1.frameImage({} :: any) == nil, "frameImage of a non-frame") +end + +do -- string input; pictures before the first sequence header are skipped + local dec = Mpeg1.new() + local u2 = main.units[2] + t:check(dec:decode(buffer.tostring(slice(mainFile, u2[1], u2[2]))) == nil, "P picture before any sequence header") + local u1 = main.units[1] + local f = dec:decode(buffer.tostring(slice(mainFile, u1[1], u1[2]))) + t:check(f ~= nil and buffer.tostring((f :: any).pixels) == ref[1], "string unit decodes") + t:check(dec.width == W and dec.height == H and math.abs(dec.frameRate - 24) < 0.01, "sequence fields") + t:check(f.pictureType == Mpeg1.PICTURE_I and f.codedWidth == 320 and buffer.len(f.y) == 320 * 192, "frame fields") + t:eq(dec.stats.skipped, 1, "stats.skipped") +end + +do -- rgba = false: planes only, frameImage still gives both + local dec = Mpeg1.new({ rgba = false }) + local u1 = main.units[1] + local f = dec:decode(mainFile, u1[1], u1[2]) :: any + t:check(f ~= nil and f.pixels == nil and buffer.len(f.y) > 0 and buffer.len(f.cb) == buffer.len(f.y) // 4, "rgba = false") + local img = Mpeg1.frameImage(f, true) :: Types.Image + t:check(img and buffer.tostring(img.pixels) == ref[1], "frameImage(f, true) after rgba = false") + local y = Mpeg1.frameImage(f) :: Types.Image + t:check(y.format == "yuv420p" and buffer.readu8(y.pixels, W) == buffer.readu8(f.y, f.codedWidth), "frameImage crops the coded width") +end + +do -- reset (seek): the next picture must be an I-picture again + local dec = Mpeg1.new() + for i = 1, 5 do + local u = main.units[i] + dec:decode(mainFile, u[1], u[2]) + end + dec:reset() + local u = main.units[10] + t:check(dec:decode(mainFile, u[1], u[2]) == nil, "P after reset has no reference") + u = main.units[1] + local f = dec:decode(mainFile, u[1], u[2]) + t:check(f ~= nil and buffer.tostring((f :: any).pixels) == ref[1], "I after reset") +end + +do -- tags (pts) follow pictures through reordering + local fx = STREAMS[11] + local b = b64(fx.file) + local dec = Mpeg1.new({ reorder = true, rgba = false }) + local order = {} + for i, u in fx.units do + local f = dec:decode(b, u[1], u[2], i) + if f then + table.insert(order, f) + end + end + while true do + local f = dec:flush() + if f == nil then + break + end + table.insert(order, f) + end + t:eq(#order, #fx.units, "bframes: every picture out") + local sawB = false + for i = 2, #order do + local a, c = order[i - 1], order[i] + if c.temporalReference ~= 0 then + t:check(c.temporalReference == a.temporalReference + 1, "display order at " .. i) + end + if c.pictureType == Mpeg1.PICTURE_B then + sawB = true + t:check(c.tag == a.tag + 1 or a.pictureType ~= Mpeg1.PICTURE_B, "B tag order") + end + end + t:check(sawB, "the stream has B-frames") + local d2 = Mpeg1.new() + for i, u in fx.units do + local f = d2:decode(b, u[1], u[2], i) + t:check(f ~= nil and f.tag == i, "decode order tag " .. i) + end +end + +do -- truncated units: every prefix length of a picture, then recovery + local dec = Mpeg1.new() + local u1 = main.units[1] + for k = 0, u1[2], 97 do + Mpeg1.new():decode(mainFile, u1[1], k) + end + for i = 1, 6 do + local u = main.units[i] + dec:decode(mainFile, u[1], u[2] // 2) + end + local f = dec:decode(mainFile, main.units[1][1], main.units[1][2]) + t:check(f ~= nil and buffer.tostring((f :: any).pixels) == ref[1], "recovers at an I-picture after truncation") +end + +-- bit flips and byte garbage in every unit: no throw, sane frames +local rounds = 0 +for _, k in { 2, 11, 8, 6 } do + local fx = STREAMS[k] + local b = b64(fx.file) + for round = 1, 6 do + local dec = Mpeg1.new({ reorder = round % 2 == 0 }) + for _, u in fx.units do + local unit = slice(b, u[1], u[2]) + local nflip = if round <= 3 then round * 3 else 40 + for _ = 1, nflip do + local at = between(0, u[2] - 1) + if round == 6 then + buffer.writeu8(unit, at, between(0, 255)) + else + buffer.writeu8(unit, at, bit32.bxor(buffer.readu8(unit, at), bit32.lshift(1, between(0, 7)))) + end + end + local ok, f = pcall(dec.decode, dec, unit) + t:check(ok, fx.name .. ": corrupt unit threw " .. tostring(f)) + if f then + t:check(buffer.len((f :: any).pixels) == f.width * f.height * 4, "frame size") + end + end + while dec:flush() do + end + rounds += 1 + end +end +t:note("%d corrupted-stream rounds", rounds) + +do -- streamed garbage and random units + local dec = Mpeg1.new() + for _ = 1, 300 do + local n = between(0, 3000) + local g = buffer.create(n) + for i = 0, n - 1 do + local r = between(0, 9) + buffer.writeu8(g, i, if r < 3 then 0 elseif r == 3 then 1 elseif r == 4 then 0xB3 else between(0, 255)) + end + dec:write(g) + while dec:decodeFrame() do + end + dec:decode(g) + end + dec:reset() + local f = dec:decode(mainFile, main.units[1][1], main.units[1][2]) + t:check(f ~= nil and buffer.tostring((f :: any).pixels) == ref[1], "clean after garbage") +end + +do -- a hostile sequence header: a huge size is rejected + local b = buffer.create(16) + buffer.writestring(b, 0, "\0\0\1\xB3\xFF\xFF\xFF\x13\xFF\xFF\xE0\x18\0\0\1\xB8") + local dec = Mpeg1.new({ maxPixels = 1000 * 1000 }) + dec:decode(b) + t:eq(dec.width, 0, "oversized sequence header rejected") +end + +-- 4. the fuzz pass: whole elementary streams (cut, mutated, garbage) through one decoder each +do + local samples = {} + for _, k in { 1, 9 } do + local fx = STREAMS[k] + local b = b64(fx.file) + local u = fx.units + table.insert(samples, buffer.tostring(slice(b, 0, u[4][1] + u[4][2]))) + end + t:fuzz("decode", function(b: buffer) + local dec = Mpeg1.new({ reorder = true }) + local out = { dec:decode(b) } + while dec:flush() do + end + return table.unpack(out) + end, samples, { mutations = 12, keepHeader = 4 }) +end + +t:done() diff --git a/tests/codecs/vp8.luau b/tests/codecs/vp8.luau index 484c3f1..8b24ae9 100644 --- a/tests/codecs/vp8.luau +++ b/tests/codecs/vp8.luau @@ -56,7 +56,7 @@ do local inter = buffer.fromstring(frames[1]) buffer.writeu8(inter, 0, bit32.bor(buffer.readu8(inter, 0), 1)) local _, e1 = Vp8.decodeFrame(inter) - t:check(e1 and e1.code == Err.UNSUPPORTED, "inter frame: " .. tostring(e1)) + t:check(e1 and e1.code == Err.CORRUPT, "inter frame without a key frame: " .. tostring(e1)) local bad = buffer.fromstring(frames[1]) buffer.writeu8(bad, 3, 0) local _, e2 = Vp8.decodeFrame(bad) diff --git a/tests/codecs/vp8video.luau b/tests/codecs/vp8video.luau new file mode 100644 index 0000000..3cc2e36 --- /dev/null +++ b/tests/codecs/vp8video.luau @@ -0,0 +1,163 @@ +-- codecs/Vp8 video tests: whole IVF streams through one decoder object, every shown frame bit-exact against ffmpeg's +-- native vp8 decoder (yuv420p CRC32): the official VP8 test vectors (vp80-00-comprehensive-001..018 and others) and +-- libvpx clips at many settings (alt-ref / hidden frames, golden, token partitions, error resilience, profiles 1-3, +-- sharpness, segmentation, q extremes, short key frame intervals, motion off the frame, odd sizes). Also hidden +-- frames, reset() and inter frames without a key frame, and the fuzz no-throw pass over damaged streams. +-- Fixtures: tools/fixtures/vp8video.py. +local T = require("@tests/T") +local Vp8 = require("@formats/codecs/Vp8") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Cases = require("@tests/gen/vp8video_cases") + +local t = T.suite("vp8video") + +-- the frames of an IVF file: { offset, length } +local function ivfFrames(b: buffer): { { number } } + local out = {} + local p = buffer.readu16(b, 6) -- header length (32) + while p + 12 <= buffer.len(b) do + local n = buffer.readu32(b, p) + if p + 12 + n > buffer.len(b) then + break + end + table.insert(out, { p + 12, n }) + p += 12 + n + end + return out +end + +local total, hidden, vectors = 0, 0, 0 +local samples: { buffer } = {} +for _, c in Cases do + local b = buffer.fromstring(c.ivf) + local fr = ivfFrames(b) + local dec = Vp8.newDecoder() + local shown, bad, firstBad = 0, 0, "" + local ok = true + for i, f in fr do + local img, err = dec:decodeFrame(b, f[1], f[2]) + if not img then + ok = false + firstBad = "frame " .. i .. ": " .. tostring(err) + break + end + local src = img.meta.source + if src.show then + shown += 1 + if buffer.len(img.pixels) ~= c.sizes[shown] or Crc32.of(img.pixels) ~= c.crcs[shown] then + bad += 1 + if bad == 1 then + firstBad = string.format("frame %d (shown %d, %s)", i, shown, if src.keyFrame then "key" else "inter") + end + end + else + hidden += 1 + end + end + t:check(ok and bad == 0 and shown == #c.crcs, string.format("%s: %d / %d frames bit-exact, %d shown of %d; first bad: %s", c.name, shown - bad, #c.crcs, shown, #fr, firstBad)) + total += shown + if string.sub(c.name, 1, 5) == "vp80-" then + vectors += 1 + end + if #samples < 6 and #c.ivf < 20000 then + table.insert(samples, b) + end +end +t:note("%d streams (%d official test vectors), %d shown frames bit-exact with ffmpeg, %d hidden frames", #Cases, vectors, total, hidden) + +-- hidden frames, reset(), inter frames without a key frame +do + local c + for _, x in Cases do + if x.name == "altref_352x288" then + c = x + end + end + local b = buffer.fromstring(c.ivf) + local fr = ivfFrames(b) + local dec = Vp8.newDecoder() + local _, e0 = dec:decodeFrame(b, fr[2][1], fr[2][2]) + t:check(e0 and e0.code == Err.CORRUPT, "inter frame first: " .. tostring(e0)) + local key = dec:decodeFrame(b, fr[1][1], fr[1][2]) :: any + t:check(key and key.meta.source.keyFrame and key.meta.source.show and key.meta.source.format == "vp8", "key frame meta") + local sawHidden = false + for i = 2, #fr do + local img = dec:decodeFrame(b, fr[i][1], fr[i][2]) :: any + if img and not img.meta.source.show then + sawHidden = true + t:check(not img.meta.source.keyFrame and img.width == c.width, "hidden frame is an Image") + end + end + t:check(sawHidden, "the alt-ref stream has a hidden frame") + -- the returned planes are a copy: decoding more frames leaves an earlier image alone + local d2 = Vp8.newDecoder() + local first = d2:decodeFrame(b, fr[1][1], fr[1][2]) :: any + local crc = Crc32.of(first.pixels) + d2:decodeFrame(b, fr[2][1], fr[2][2]) + d2:decodeFrame(b, fr[3][1], fr[3][2]) + t:eq(Crc32.of(first.pixels), crc, "images are fresh buffers") + dec:reset() + local _, e1 = dec:decodeFrame(b, fr[3][1], fr[3][2]) + t:check(e1 and e1.code == Err.CORRUPT, "inter frame after reset: " .. tostring(e1)) + local again = dec:decodeFrame(b, fr[1][1], fr[1][2]) :: any + t:eq(again and Crc32.of(again.pixels), c.crcs[1], "key frame after reset") + local nxt = dec:decodeFrame(b, fr[2][1], fr[2][2]) :: any + t:check(nxt ~= nil, "inter frame after the key frame") + local _, e2 = Vp8.decodeFrame(b, fr[2][1], fr[2][2]) + t:check(e2 and e2.code == Err.CORRUPT, "one-shot decodeFrame of an inter frame") + local _, e3 = dec:decodeFrame(b, fr[2][1], 2) + t:check(e3 and e3.code == Err.TRUNCATED, "truncated frame tag: " .. tostring(e3)) +end + +-- fuzz: whole damaged streams through one decoder (truncated / mutated frames after valid ones) +local function feed(b: buffer) + local dec = Vp8.newDecoder() + local any = false + local p, n = 32, buffer.len(b) + while p + 12 <= n do + local len = math.min(buffer.readu32(b, p), n - p - 12) + local img = dec:decodeFrame(b, p + 12, len, { maxPixels = 2 ^ 20 }) + any = any or img ~= nil + p += 12 + len + end + return any, nil +end +-- damage aimed at inter frames: one frame truncated, or bytes changed in its headers / modes (first 48 bytes) +local damaged: { buffer } = {} +local rand = T.rng(8) +for _, b in samples do + local fr = ivfFrames(b) + for _ = 1, 12 do + local k = 2 + rand(#fr - 1) + local parts = {} + for i, f in fr do + local data = buffer.readstring(b, f[1], f[2]) + if i == k then + if rand(2) == 0 then + data = string.sub(data, 1, rand(#data)) + else + for _ = 1, 1 + rand(3) do + local at = 1 + rand(math.min(48, #data)) + data = string.sub(data, 1, at - 1) .. string.char(rand(256)) .. string.sub(data, at + 1) + end + end + end + local hdr = buffer.create(12) + buffer.writeu32(hdr, 0, #data) + table.insert(parts, buffer.tostring(hdr) .. data) + end + table.insert(damaged, buffer.fromstring(buffer.readstring(b, 0, 32) .. table.concat(parts))) + end +end +local throws = 0 +for _, b in damaged do + if not pcall(feed, b) then + throws += 1 + end +end +t:eq(throws, 0, #damaged .. " streams with one damaged inter frame: no throw") +t:fuzz("stream", feed, samples, { mutations = 5, keepHeader = 32 }) +t:fuzz("stream (more damage)", feed, samples, { mutations = 15, keepHeader = 32, garbage = 20 }) + +t:done() diff --git a/tests/containers/isobmff.luau b/tests/containers/isobmff.luau new file mode 100644 index 0000000..f05280e --- /dev/null +++ b/tests/containers/isobmff.luau @@ -0,0 +1,241 @@ +-- containers/IsoBmff tests: ffmpeg / MP4Box files (H.264 + AAC with B-frames, fast start, QuickTime MJPEG + PCM, HEVC, +-- fragmented by ffmpeg and MP4Box, stz2 + co64, ALAC) demuxed packet for packet against ffprobe (-ignore_editlist); +-- track facts and codec configurations; iTunes tags and cover art; AVIF items (libavif, plain and with alpha); the +-- muxer round-trips through the demuxer (sizes, times, cts, sync, tags, 64-bit sizes); a sub-range reader; the fuzz +-- no-throw pass. Fixtures: tools/fixtures/isobmff.py. +local T = require("@tests/T") +local IsoBmff = require("@formats/containers/IsoBmff") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Fx = require("@tests/gen/isobmff") + +local t = T.suite("isobmff") + +local CODEC = { h264 = "h264", aac = "aac", mjpeg = "mjpeg", pcm_s16be = "pcm", hevc = "hevc", alac = "alac" } + +local function reader(s: string, pad: number?): Bytes.Reader + if pad then + local b = buffer.create(#s + pad * 2) + buffer.writestring(b, pad, s) + return Bytes.reader(b, pad, #s) + end + return Bytes.reader(buffer.fromstring(s)) +end + +-- every fixture against ffprobe +for _, c in Fx.cases do + for _, pad in { 0, 5 } do + local r = reader(c.data, if pad > 0 then pad else nil) + local label = c.name .. (if pad > 0 then " (sub-range)" else "") + t:check(IsoBmff.sniff(r) ~= nil, label .. ": sniff") + local dmx, err = IsoBmff.demux(r) + t:check(dmx, label .. ": " .. tostring(err)) + t:eq(#dmx.tracks, #c.streams, label .. ": track count") + for i, s in c.streams do + local tr = dmx.tracks[i] + t:eq(tr.kind, s.kind, label .. ": track " .. i .. " kind") + t:eq(tr.codec, CODEC[s.codec] or s.codec, label .. ": track " .. i .. " codec") + t:eq(tr.timescale, s.timescale, label .. ": timescale") + if s.width then + t:check(tr.width == s.width and tr.height == s.height, label .. ": video size") + end + if s.sampleRate then + t:check(tr.sampleRate == s.sampleRate and tr.channels == s.channels, label .. ": audio format") + end + if s.extradata > 0 and s.codec ~= "alac" then + t:eq(if tr.config then buffer.len(tr.config) else 0, s.extradata, label .. ": codec config size") + end + end + -- packets in file order + local n, bad = 0, nil + local base = r.base + for p in dmx:packets() do + n += 1 + local want = c.packets[n] + if not want then + bad = bad or ("extra packet " .. n) + break + end + local tr = dmx.tracks[want.stream] + if p.track ~= tr.id then + bad = bad or ("packet " .. n .. " track") + end + local off = tr.offsets[p.index] + if off - base ~= want.pos or buffer.len(p.data) ~= want.size or p.dts ~= want.dts or p.pts ~= want.pts or p.keyframe ~= want.key then + bad = bad or string.format("packet %d: pos %d/%d size %d/%d dts %d/%d pts %d/%d key %s/%s", n, off - base, want.pos, buffer.len(p.data), want.size, p.dts, want.dts, p.pts, want.pts, tostring(p.keyframe), tostring(want.key)) + end + end + t:check(bad == nil, label .. ": " .. tostring(bad)) + t:eq(n, #c.packets, label .. ": packet count") + if pad == 0 then + t:note("%s: %d tracks, %d packets match ffprobe", c.name, #c.streams, n) + end + end +end + +-- per-track packets, seek +do + local c = Fx.cases[1] + local dmx = IsoBmff.demux(reader(c.data)) + local v = dmx.tracks[1] + local count = 0 + for p in dmx:packets(v.id) do + count += 1 + t:eq(p.track, v.id, "per-track packets") + end + t:eq(count, v.sampleCount, "per-track packet count") + dmx:seek(0.75) + local p = dmx:packets(v.id)() + t:check(p and p.keyframe and p.dts / v.timescale <= 0.75, "seek lands on a keyframe before the time") + t:check(v.skip >= 0 and v.edits ~= nil, "edit list parsed") +end + +-- tags and cover +do + local r = reader(Fx.tagged.data) + local movie = IsoBmff.parse(r) :: IsoBmff.Movie + local tags, pics = IsoBmff.tags(r, movie) + for k, v in Fx.tagged.tags do + t:eq(tags[k], v, "tag " .. k) + end + t:check(tags.encoder ~= nil, "encoder tag") + t:eq(#pics, 1, "one cover") + t:eq(pics[1] and buffer.len(pics[1].data), Fx.tagged.cover, "cover bytes") + t:eq(pics[1] and pics[1].mime, "image/png", "cover mime") +end + +-- AVIF items +for _, c in Fx.avif do + local r = reader(c.data) + t:check(IsoBmff.sniff(r) == "avif", c.name .. ": brand") + local movie = IsoBmff.parse(r) :: IsoBmff.Movie + t:check(movie and #movie.tracks == 0, c.name .. ": no tracks") + local items, err = IsoBmff.items(r, movie) + t:check(items, c.name .. ": items: " .. tostring(err)) + local prim = items.items[items.primary] + t:check(prim and prim.type == "av01", c.name .. ": primary item is av01") + local ispe, av1C + for _, p in prim.properties do + if p.type == "ispe" then + ispe = p + elseif p.type == "av1C" then + av1C = p + end + end + t:check(ispe and ispe.width == c.width and ispe.height == c.height, c.name .. ": ispe") + t:check(av1C and av1C.config and buffer.readu8(av1C.config, 0) == 0x81, c.name .. ": av1C marker / version") + local data = IsoBmff.itemData(r, items, items.primary :: number) + t:check(data and buffer.len(data) > 10, c.name .. ": item data") + -- an AV1 OBU stream: the first OBU is a sequence header (type 1) or a temporal delimiter (2) + local obu = data and bit32.band(bit32.rshift(buffer.readu8(data, 0), 3), 15) + t:check(obu == 1 or obu == 2, c.name .. ": AV1 OBU stream") + local auxl = nil + for _, id in items.order do + local it = items.items[id] + if it.refs.auxl then + auxl = it + end + end + t:eq(auxl ~= nil, c.alpha, c.name .. ": alpha auxiliary item") +end + +-- the muxer: round trip through the demuxer +do + local rand = T.rng(5) + local function sample(n: number): buffer + local b = buffer.create(n) + for i = 0, n - 1 do + buffer.writeu8(b, i, rand(256)) + end + return b + end + local aud, vid = {}, {} + for i = 1, 90 do + aud[i] = sample(50 + rand(200)) + end + for i = 1, 30 do + vid[i] = sample(100 + rand(900)) + end + local cts = {} + local sync = {} + for i = 1, 30 do + cts[i] = (i % 3) * 512 + sync[i] = i % 10 == 1 + end + local cfg = buffer.fromstring("\x12\x10") + local file, err = IsoBmff.mux({ + brand = "mp42", + compatible = { "mp42", "isom" }, + tracks = { + { kind = "video", entry = "avc1", timescale = 15360, samples = vid, durations = 512, cts = cts, sync = sync, width = 64, height = 48, config = buffer.fromstring("\1\100\0\10\255") }, + { kind = "audio", entry = "mp4a", timescale = 44100, samples = aud, durations = 1024, sampleRate = 44100, channels = 2, config = cfg, skip = 1024, playDuration = 44100 * 2 }, + }, + tags = { title = "Mux Test", artist = "Me", track = "2", tracktotal = "9", custom = "free form", bpm = "120" }, + pictures = { { mime = "image/jpeg", data = buffer.fromstring("\255\216\255\217") } }, + chunkDuration = 0.25, + }) + t:check(file, "mux: " .. tostring(err)) + local r = Bytes.reader(file :: buffer) + local dmx = IsoBmff.demux(r) + t:check(dmx and #dmx.tracks == 2, "mux: demux our file") + local v, a = dmx.tracks[1], dmx.tracks[2] + t:check(v.codec == "h264" and v.width == 64 and v.height == 48 and v.config and buffer.len(v.config) == 5, "mux: video track") + t:check(a.codec == "aac" and a.sampleRate == 44100 and a.channels == 2 and a.config and buffer.tostring(a.config) == "\x12\x10", "mux: audio track + esds") + t:check(a.skip == 1024 and a.playDuration == 88200, "mux: edit list") + local ok = true + for i = 1, 30 do + local s = IsoBmff.sample(r, v, i) :: buffer + ok = ok and buffer.tostring(s) == buffer.tostring(vid[i]) and v.dts[i] == (i - 1) * 512 and (v.cts :: any)[i] == cts[i] and ((v.sync :: any)[i] == true) == sync[i] + end + t:check(ok, "mux: video samples, times, cts, sync") + ok = true + for i = 1, 90 do + ok = ok and buffer.tostring(IsoBmff.sample(r, a, i) :: buffer) == buffer.tostring(aud[i]) and a.durations[i] == 1024 + end + t:check(ok, "mux: audio samples") + -- interleaved: offsets alternate between the tracks + t:check(v.offsets[30] > a.offsets[1] and a.offsets[90] > v.offsets[1], "mux: interleaved chunks") + local tags, pics = IsoBmff.tags(r, dmx.movie) + t:check(tags.title == "Mux Test" and tags.artist == "Me" and tags.track == "2" and tags.tracktotal == "9" and tags.custom == "free form" and tags.bpm == "120", "mux: tags round trip") + t:check(#pics == 1 and buffer.len(pics[1].data) == 4, "mux: cover round trip") + t:note("mux: %d bytes, crc %08x", buffer.len(file :: buffer), Crc32.of(file :: buffer)) + -- data + sizes form, bad specs + local f2 = IsoBmff.mux({ tracks = { { kind = "audio", entry = "alac", timescale = 8000, data = buffer.create(30), sizes = { 10, 10, 10 }, durations = { 4096, 4096, 100 }, config = buffer.create(24) } } }) + local d2 = IsoBmff.demux(Bytes.reader(f2 :: buffer)) + t:check(d2 and d2.tracks[1].codec == "alac" and d2.tracks[1].sampleCount == 3 and d2.tracks[1].durations[3] == 100 and buffer.len(d2.tracks[1].config) == 24, "mux: data + sizes, alac cookie") + for _, bad in { {}, { tracks = {} }, { tracks = { { kind = "audio", entry = "toolong", timescale = 1, samples = {}, durations = 1 } } }, { tracks = { { kind = "x", entry = "abcd", timescale = 1, samples = {}, durations = 1 } } }, { tracks = { { kind = "audio", entry = "abcd", timescale = 1 } } } } do + local f, e = IsoBmff.mux(bad :: any) + t:check(f == nil and e and e.code == "ARG", "mux: bad spec -> ARG") + end +end + +-- fuzz +do + local samples = {} + for _, c in Fx.cases do + table.insert(samples, string.sub(c.data, 1, 6000)) + table.insert(samples, c.data) + end + for _, c in Fx.avif do + table.insert(samples, c.data) + end + t:fuzz("demux", function(b: buffer) + local r = Bytes.reader(b) + local dmx = IsoBmff.demux(r) + if dmx then + for p in dmx:packets() do + local _ = p + end + IsoBmff.tags(r, dmx.movie) + local items = IsoBmff.items(r, dmx.movie) + if items then + for _, id in items.order do + IsoBmff.itemData(r, items, id) + end + end + end + return dmx + end, samples, { mutations = 12 }) +end + +t:done() diff --git a/tests/core/md5.luau b/tests/core/md5.luau new file mode 100644 index 0000000..a40b8c8 --- /dev/null +++ b/tests/core/md5.luau @@ -0,0 +1,30 @@ +-- core/Md5 tests: the RFC 1321 test suite, incremental updates at every split, sub-ranges, a long input. +local T = require("@tests/T") +local Md5 = require("@formats/core/Md5") + +local t = T.suite("md5") +local VECTORS = { + { "", "d41d8cd98f00b204e9800998ecf8427e" }, + { "a", "0cc175b9c0f1b6a831c399e269772661" }, + { "abc", "900150983cd24fb0d6963f7d28e17f72" }, + { "message digest", "f96b697d7cb7938d525a2f31aaf161d0" }, + { "abcdefghijklmnopqrstuvwxyz", "c3fcd3d76192e4007dfb496cca67e13b" }, + { "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "d174ab98d277d9f5a5611c2c9f419d9f" }, + { string.rep("1234567890", 8), "57edf4a22be3c955ac49da2e2107b67a" }, +} +for _, v in VECTORS do + t:eq(Md5.of(buffer.fromstring(v[1])), v[2], "md5 of " .. string.format("%q", v[1])) +end +-- incremental: every split point of a 130-byte message, three pieces +local msg = string.rep("The quick brown fox jumps over the lazy dog. ", 3) +local want = Md5.of(buffer.fromstring(msg)) +for cut = 0, #msg, 7 do + local h = Md5.new() + h:update(buffer.fromstring(string.sub(msg, 1, cut))) + h:update(buffer.fromstring(string.sub(msg, cut + 1, cut + 20))) + h:update(buffer.fromstring(string.sub(msg, cut + 21))) + t:eq(Md5.hex(h:digest()), want, "split at " .. cut) +end +t:eq(Md5.of(buffer.fromstring("xxabcyy"), 2, 3), "900150983cd24fb0d6963f7d28e17f72", "sub-range") +t:eq(Md5.of(buffer.fromstring(string.rep("a", 1000000))), "7707d6ae4e027c70eea2a935c2296f21", "a million a's") +t:done() diff --git a/tests/fixtures/vp8video/vp80-00-comprehensive-001.ivf b/tests/fixtures/vp8video/vp80-00-comprehensive-001.ivf new file mode 100644 index 0000000..d7a7cd5 Binary files /dev/null and b/tests/fixtures/vp8video/vp80-00-comprehensive-001.ivf differ diff --git a/tests/fixtures/vp8video/vp80-00-comprehensive-002.ivf b/tests/fixtures/vp8video/vp80-00-comprehensive-002.ivf new file mode 100644 index 0000000..06e208d Binary files /dev/null and b/tests/fixtures/vp8video/vp80-00-comprehensive-002.ivf differ diff --git a/tests/fixtures/vp8video/vp80-00-comprehensive-003.ivf b/tests/fixtures/vp8video/vp80-00-comprehensive-003.ivf new file mode 100644 index 0000000..1009450 Binary files /dev/null and b/tests/fixtures/vp8video/vp80-00-comprehensive-003.ivf differ diff --git a/tests/fixtures/vp8video/vp80-00-comprehensive-004.ivf b/tests/fixtures/vp8video/vp80-00-comprehensive-004.ivf new file mode 100644 index 0000000..70b49fe Binary files /dev/null and b/tests/fixtures/vp8video/vp80-00-comprehensive-004.ivf differ diff --git a/tests/fixtures/vp8video/vp80-00-comprehensive-005.ivf b/tests/fixtures/vp8video/vp80-00-comprehensive-005.ivf new file mode 100644 index 0000000..5388a61 Binary files /dev/null and b/tests/fixtures/vp8video/vp80-00-comprehensive-005.ivf differ diff --git a/tests/fixtures/vp8video/vp80-00-comprehensive-006.ivf b/tests/fixtures/vp8video/vp80-00-comprehensive-006.ivf new file mode 100644 index 0000000..5a78d4f Binary files /dev/null and b/tests/fixtures/vp8video/vp80-00-comprehensive-006.ivf differ diff --git a/tests/fixtures/vp8video/vp80-00-comprehensive-007.ivf b/tests/fixtures/vp8video/vp80-00-comprehensive-007.ivf new file mode 100644 index 0000000..3aafdeb Binary files /dev/null and b/tests/fixtures/vp8video/vp80-00-comprehensive-007.ivf differ diff --git a/tests/fixtures/vp8video/vp80-00-comprehensive-008.ivf b/tests/fixtures/vp8video/vp80-00-comprehensive-008.ivf new file mode 100644 index 0000000..d31941a Binary files /dev/null and b/tests/fixtures/vp8video/vp80-00-comprehensive-008.ivf differ diff --git a/tests/fixtures/vp8video/vp80-00-comprehensive-009.ivf b/tests/fixtures/vp8video/vp80-00-comprehensive-009.ivf new file mode 100644 index 0000000..1e7cf89 Binary files /dev/null and b/tests/fixtures/vp8video/vp80-00-comprehensive-009.ivf differ diff --git a/tests/fixtures/vp8video/vp80-00-comprehensive-010.ivf b/tests/fixtures/vp8video/vp80-00-comprehensive-010.ivf new file mode 100644 index 0000000..b5f8285 Binary files /dev/null and b/tests/fixtures/vp8video/vp80-00-comprehensive-010.ivf differ diff --git a/tests/fixtures/vp8video/vp80-00-comprehensive-011.ivf b/tests/fixtures/vp8video/vp80-00-comprehensive-011.ivf new file mode 100644 index 0000000..8a347eb Binary files /dev/null and b/tests/fixtures/vp8video/vp80-00-comprehensive-011.ivf differ diff --git a/tests/fixtures/vp8video/vp80-00-comprehensive-012.ivf b/tests/fixtures/vp8video/vp80-00-comprehensive-012.ivf new file mode 100644 index 0000000..9182f48 Binary files /dev/null and b/tests/fixtures/vp8video/vp80-00-comprehensive-012.ivf differ diff --git a/tests/fixtures/vp8video/vp80-00-comprehensive-013.ivf b/tests/fixtures/vp8video/vp80-00-comprehensive-013.ivf new file mode 100644 index 0000000..6873b35 Binary files /dev/null and b/tests/fixtures/vp8video/vp80-00-comprehensive-013.ivf differ diff --git a/tests/fixtures/vp8video/vp80-00-comprehensive-014.ivf b/tests/fixtures/vp8video/vp80-00-comprehensive-014.ivf new file mode 100644 index 0000000..366fd54 Binary files /dev/null and b/tests/fixtures/vp8video/vp80-00-comprehensive-014.ivf differ diff --git a/tests/fixtures/vp8video/vp80-00-comprehensive-015.ivf b/tests/fixtures/vp8video/vp80-00-comprehensive-015.ivf new file mode 100644 index 0000000..31c0e76 Binary files /dev/null and b/tests/fixtures/vp8video/vp80-00-comprehensive-015.ivf differ diff --git a/tests/fixtures/vp8video/vp80-00-comprehensive-016.ivf b/tests/fixtures/vp8video/vp80-00-comprehensive-016.ivf new file mode 100644 index 0000000..74bdc9d Binary files /dev/null and b/tests/fixtures/vp8video/vp80-00-comprehensive-016.ivf differ diff --git a/tests/fixtures/vp8video/vp80-00-comprehensive-017.ivf b/tests/fixtures/vp8video/vp80-00-comprehensive-017.ivf new file mode 100644 index 0000000..b6820c1 Binary files /dev/null and b/tests/fixtures/vp8video/vp80-00-comprehensive-017.ivf differ diff --git a/tests/fixtures/vp8video/vp80-00-comprehensive-018.ivf b/tests/fixtures/vp8video/vp80-00-comprehensive-018.ivf new file mode 100644 index 0000000..7da25e8 Binary files /dev/null and b/tests/fixtures/vp8video/vp80-00-comprehensive-018.ivf differ diff --git a/tests/fixtures/vp8video/vp80-02-inter-1418.ivf b/tests/fixtures/vp8video/vp80-02-inter-1418.ivf new file mode 100644 index 0000000..cd5b6f4 Binary files /dev/null and b/tests/fixtures/vp8video/vp80-02-inter-1418.ivf differ diff --git a/tests/fixtures/vp8video/vp80-03-segmentation-03.ivf b/tests/fixtures/vp8video/vp80-03-segmentation-03.ivf new file mode 100644 index 0000000..447e0b6 Binary files /dev/null and b/tests/fixtures/vp8video/vp80-03-segmentation-03.ivf differ diff --git a/tests/fixtures/vp8video/vp80-03-segmentation-1407.ivf b/tests/fixtures/vp8video/vp80-03-segmentation-1407.ivf new file mode 100644 index 0000000..ec9d645 Binary files /dev/null and b/tests/fixtures/vp8video/vp80-03-segmentation-1407.ivf differ diff --git a/tests/fixtures/vp8video/vp80-03-segmentation-1436.ivf b/tests/fixtures/vp8video/vp80-03-segmentation-1436.ivf new file mode 100644 index 0000000..55c9219 Binary files /dev/null and b/tests/fixtures/vp8video/vp80-03-segmentation-1436.ivf differ diff --git a/tests/fixtures/vp8video/vp80-03-segmentation-1437.ivf b/tests/fixtures/vp8video/vp80-03-segmentation-1437.ivf new file mode 100644 index 0000000..a1484bb Binary files /dev/null and b/tests/fixtures/vp8video/vp80-03-segmentation-1437.ivf differ diff --git a/tests/fixtures/vp8video/vp80-03-segmentation-1441.ivf b/tests/fixtures/vp8video/vp80-03-segmentation-1441.ivf new file mode 100644 index 0000000..83bf2d0 Binary files /dev/null and b/tests/fixtures/vp8video/vp80-03-segmentation-1441.ivf differ diff --git a/tests/fixtures/vp8video/vp80-04-partitions-1405.ivf b/tests/fixtures/vp8video/vp80-04-partitions-1405.ivf new file mode 100644 index 0000000..4578736 Binary files /dev/null and b/tests/fixtures/vp8video/vp80-04-partitions-1405.ivf differ diff --git a/tests/fixtures/vp8video/vp80-05-sharpness-1438.ivf b/tests/fixtures/vp8video/vp80-05-sharpness-1438.ivf new file mode 100644 index 0000000..5a5eb41 Binary files /dev/null and b/tests/fixtures/vp8video/vp80-05-sharpness-1438.ivf differ diff --git a/tests/fixtures/vp8video/vp80-06-smallsize.ivf b/tests/fixtures/vp8video/vp80-06-smallsize.ivf new file mode 100644 index 0000000..3f24bb3 Binary files /dev/null and b/tests/fixtures/vp8video/vp80-06-smallsize.ivf differ diff --git a/tests/music/_similar.luau b/tests/music/_similar.luau new file mode 100644 index 0000000..e97f7eb --- /dev/null +++ b/tests/music/_similar.luau @@ -0,0 +1,209 @@ +-- tests/music/_similar: shared helper of the tracker tests (not a test itself): renders a module through a Decoder and +-- compares it with a reference render's features (tools/fixtures/_tracker.py: per 2048-frame block the RMS of left, +-- right and mid, and 40 log-spaced band magnitudes of mid from a Hann-windowed FFT). Same definitions on both sides. +local S = {} + +local SR, HOP, BANDS = 44100, 2048, 40 +local F_LO, F_HI = 150, 16000 +S.SR = SR + +local WINDOW = table.create(HOP, 0) +for i = 0, HOP - 1 do + WINDOW[i + 1] = 0.5 - 0.5 * math.cos(2 * math.pi * i / HOP) +end +local BAND_OF = table.create(HOP // 2, -1) +for b = 1, HOP // 2 - 1 do + local f = b * SR / HOP + if f >= F_LO and f < F_HI then + BAND_OF[b + 1] = math.min(BANDS - 1, math.floor(math.log(f / F_LO) / math.log(F_HI / F_LO) * BANDS)) + end +end + +local function fft(re: { number }, im: { number }, n: number) + local j = 0 + for i = 1, n - 1 do + local bit = n // 2 + while bit > 0 and j >= bit and (j // bit) % 2 == 1 do + j -= bit + bit //= 2 + end + j += bit + if i < j then + re[i + 1], re[j + 1] = re[j + 1], re[i + 1] + im[i + 1], im[j + 1] = im[j + 1], im[i + 1] + end + end + local size = 2 + while size <= n do + local ang = -2 * math.pi / size + local wr, wi = math.cos(ang), math.sin(ang) + local half = size // 2 + for start = 0, n - 1, size do + local cr, ci = 1, 0 + for k = 0, half - 1 do + local a, b = start + k + 1, start + k + half + 1 + local tr = re[b] * cr - im[b] * ci + local ti = re[b] * ci + im[b] * cr + re[b], im[b] = re[a] - tr, im[a] - ti + re[a], im[a] = re[a] + tr, im[a] + ti + cr, ci = cr * wr - ci * wi, cr * wi + ci * wr + end + end + size *= 2 + end +end + +-- features(samples (interleaved stereo f32 buffer), frames) -> { frames, rmsL, rmsR, rmsM, bands } +function S.features(buf: buffer, frames: number): any + local n = frames // HOP + local out = { frames = n, rmsL = {}, rmsR = {}, rmsM = {}, bands = {} } + local re, im = table.create(HOP, 0), table.create(HOP, 0) + for k = 0, n - 1 do + local sl, sr, sm = 0, 0, 0 + for i = 0, HOP - 1 do + local o = ((k * HOP + i) * 2) * 4 + local l, r = buffer.readf32(buf, o), buffer.readf32(buf, o + 4) + local m = (l + r) / 2 + sl += l * l + sr += r * r + sm += m * m + re[i + 1] = m * WINDOW[i + 1] + im[i + 1] = 0 + end + table.insert(out.rmsL, math.sqrt(sl / HOP)) + table.insert(out.rmsR, math.sqrt(sr / HOP)) + table.insert(out.rmsM, math.sqrt(sm / HOP)) + fft(re, im, HOP) + local e = table.create(BANDS, 0) + for b = 1, HOP // 2 - 1 do + local j = BAND_OF[b + 1] + if j >= 0 then + e[j + 1] += re[b + 1] * re[b + 1] + im[b + 1] * im[b + 1] + end + end + for j = 1, BANDS do + table.insert(out.bands, math.sqrt(e[j])) + end + end + return out +end + +-- renderAll(decoder, maxFrames) -> interleaved buffer, frames +function S.renderAll(dec: any, maxFrames: number): (buffer, number) + local total = math.min(dec.frames, maxFrames) + local out = buffer.create(math.max(1, total) * 8) + local pos = 0 + local chunk = buffer.create(4096 * 8) + while pos < total do + local _, n = dec:read(math.min(4096, total - pos), chunk) + if n == 0 then + break + end + buffer.copy(out, pos * 8, chunk, 0, n * 8) + pos += n + end + return out, pos +end + +local function db(x: number): number + return 20 * math.log10(x + 1e-6) +end + +-- compare(ours, ref) -> { gainDb, envCorr, spectral, balance } over the common frames: +-- gainDb total mid energy ratio in dB (ours / ref) +-- envCorr Pearson correlation of the per-block mid loudness in dB (blocks above -60 dB in either) +-- envErr mean absolute difference of the per-block mid loudness in dB, after removing gainDb (same blocks) +-- spectral mean cosine similarity of the band magnitude vectors (blocks where ref is above -50 dB) +-- balance mean absolute difference of the per-block left / right balance (L - R) / (L + R) (loud blocks) +function S.compare(a: any, b: any): any + local n = math.min(a.frames, b.frames) + local ea, eb = 0, 0 + for k = 1, n do + ea += a.rmsM[k] ^ 2 + eb += b.rmsM[k] ^ 2 + end + local gainDb = 10 * math.log10((ea + 1e-12) / (eb + 1e-12)) + local xs, ys = {}, {} + for k = 1, n do + local x, y = db(a.rmsM[k]), db(b.rmsM[k]) + if x > -60 or y > -60 then + table.insert(xs, x) + table.insert(ys, y) + end + end + local mx, my = 0, 0 + for i = 1, #xs do + mx += xs[i] + my += ys[i] + end + mx /= math.max(1, #xs) + my /= math.max(1, #ys) + local sxy, sxx, syy = 0, 0, 0 + for i = 1, #xs do + sxy += (xs[i] - mx) * (ys[i] - my) + sxx += (xs[i] - mx) ^ 2 + syy += (ys[i] - my) ^ 2 + end + local envCorr = if sxx > 0 and syy > 0 then sxy / math.sqrt(sxx * syy) else 1 + -- the mean loudness difference per block once the overall gain is taken out (dB, each side clamped at -60) + local envErr = 0 + for i = 1, #xs do + envErr += math.abs(math.max(xs[i], -60) - math.max(ys[i], -60) - gainDb) + end + envErr /= math.max(1, #xs) + local cs, cn = 0, 0 + local bal, bn = 0, 0 + for k = 1, n do + if db(b.rmsM[k]) > -50 then + local dot, na, nb = 0, 0, 0 + for j = 1, BANDS do + local x, y = a.bands[(k - 1) * BANDS + j], b.bands[(k - 1) * BANDS + j] + dot += x * y + na += x * x + nb += y * y + end + cs += if na > 0 and nb > 0 then dot / math.sqrt(na * nb) else 0 + cn += 1 + end + local la, ra, lb, rb = a.rmsL[k], a.rmsR[k], b.rmsL[k], b.rmsR[k] + if lb + rb > 0.01 then + bal += math.abs((la - ra) / (la + ra + 1e-9) - (lb - rb) / (lb + rb)) + bn += 1 + end + end + return { + gainDb = gainDb, + envCorr = envCorr, + envErr = envErr, + spectral = if cn > 0 then cs / cn else 1, + balance = if bn > 0 then bal / bn else 0, + frames = n, + } +end + +-- worst(ours, ref, count) -> the blocks with the lowest spectral similarity (for debugging): { {block, sim} } +function S.worst(a: any, b: any, count: number): { { number } } + local list = {} + for k = 1, math.min(a.frames, b.frames) do + if db(b.rmsM[k]) > -50 then + local dot, na, nb = 0, 0, 0 + for j = 1, BANDS do + local x, y = a.bands[(k - 1) * BANDS + j], b.bands[(k - 1) * BANDS + j] + dot += x * y + na += x * x + nb += y * y + end + table.insert(list, { k, if na > 0 and nb > 0 then dot / math.sqrt(na * nb) else 0, db(a.rmsM[k]), db(b.rmsM[k]) }) + end + end + table.sort(list, function(x, y) + return x[2] < y[2] + end) + local out = {} + for i = 1, math.min(count, #list) do + out[i] = list[i] + end + return out +end + +return S diff --git a/tests/music/it.luau b/tests/music/it.luau new file mode 100644 index 0000000..b06ac8b --- /dev/null +++ b/tests/music/it.luau @@ -0,0 +1,84 @@ +-- music/it tests: generated Impulse Tracker modules (tools/fixtures/it.py) parsed, rendered through codecs/Tracker and +-- compared with openmpt123's render (loudness envelope, band spectrum, stereo balance, song length), the contract, +-- and the fuzz no-throw pass. +local T = require("@tests/T") +local S = require("@tests/music/_similar") +local It = require("@formats/music/it") +local Tracker = require("@formats/codecs/Tracker") +local Bytes = require("@formats/core/Bytes") +local Cases = require("@tests/gen/it_cases") + +local t = T.suite("it") + +t:eq(It.name, "it", "name") +t:eq(It.category, "music", "category") +t:check(It.caps.decode and not It.caps.encode, "caps") + +local function load(data: string): any + return It.decode(Bytes.reader(buffer.fromstring(data))) +end + +local THRESH = { gainDb = 0.5, envErr = 1.0, spectral = 0.95, balance = 0.04, duration = 0.01 } + +for _, c in Cases do + local m, err = load(c.data) + t:check(m, c.name .. ": " .. tostring(err)) + t:check(It.sniff(Bytes.reader(buffer.fromstring(c.data))) > 0, c.name .. ": sniff") + local dec = m:render({ sampleRate = S.SR }) + t:check(dec, c.name .. ": render") + t:check(math.abs(dec.duration - c.duration) < THRESH.duration, string.format("%s: duration %.3f s, openmpt %.3f s", c.name, dec.duration, c.duration)) + local buf, frames = S.renderAll(dec, math.floor(c.duration * S.SR)) + local r = S.compare(S.features(buf, frames), c.ref) + t:note("%-7s gain %+.2f dB, loudness error %.2f dB, spectrum %.3f, balance %.3f, %.2f s", c.name, r.gainDb, r.envErr, r.spectral, r.balance, dec.duration) + if r.spectral < THRESH.spectral or r.envErr > THRESH.envErr then + for _, w in S.worst(S.features(buf, frames), c.ref, 6) do + t:note(" block %d (%.2f s): spectrum %.3f, ours %.1f dB, ref %.1f dB", w[1], (w[1] - 1) * 2048 / S.SR, w[2], w[3], w[4]) + end + end + t:check(math.abs(r.gainDb) < THRESH.gainDb, c.name .. ": loudness") + t:check(r.envErr < THRESH.envErr, c.name .. ": loudness envelope") + t:check(r.spectral > THRESH.spectral, c.name .. ": spectrum") + t:check(r.balance < THRESH.balance, c.name .. ": stereo balance") +end + +-- compressed samples (IT 2.14 / 2.15, 8 and 16-bit, mono and stereo) decode to exactly the uncompressed data +for _, c in Cases do + if c.plain then + local a, b = load(c.data), load(c.plain) + local same = #a.samples == #b.samples + for i, s in a.samples do + local o = b.samples[i] + same = same and s.length == o.length and s.channels == o.channels and buffer.tostring(s.data) == buffer.tostring(o.data) + end + t:check(same, c.name .. ": samples equal the uncompressed ones") + end +end + +-- seek: the position after a seek and the output continuing +do + local m = load(Cases[1].data) + local dec = m:render() + dec:seek(2) + t:check(math.abs(dec:position() - 2) < 0.001, "seek position") + local _, n = dec:read(1000) + t:eq(n, 1000, "read after seek") + t:check(Tracker.duration(m) == dec.duration, "duration()") +end + +-- the fuzz pass: decode, and a short render of whatever decodes +local samples = {} +for _, c in Cases do + table.insert(samples, c.data) +end +t:fuzz("decode", function(b: buffer) + local m = It.decode(Bytes.reader(b)) + if m then + local dec = Tracker.render(m, { maxDuration = 0.5, sampleRate = 8000 }) + if dec then + dec:read(4000) + end + end + return m +end, samples, { mutations = 30 }) + +t:done() diff --git a/tests/music/midi.luau b/tests/music/midi.luau new file mode 100644 index 0000000..a906337 --- /dev/null +++ b/tests/music/midi.luau @@ -0,0 +1,272 @@ +-- music/midi tests: SMF formats 0 / 1 / 2 + SMPTE + RMID parsed exactly as python mido parses them, mido's own files +-- re-encoded byte for byte, round trips without running status, the tempo map against mido's message times and +-- lengths, meta summaries, crafted bad files, truncation (lenient / strict), the fallback-synth render (duration, +-- level, seek), and the fuzz no-throw pass (decode, and decode + a short render). Fixtures: tools/fixtures/midi.py. +local T = require("@tests/T") +local Midi = require("@formats/music/midi") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Cases = require("@tests/gen/midi_cases") +local Bad = require("@tests/gen/midi_bad") +local Trunc = require("@tests/gen/midi_trunc") + +local t = T.suite("midi") + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return Midi.decode(Bytes.reader(b), opts) +end + +-- the contract +t:eq(Midi.name, "midi", "name") +t:eq(Midi.category, "music", "category") +t:check(table.find(Midi.extensions, "mid") ~= nil, "extensions") +t:check(Midi.caps.decode and Midi.caps.encode, "caps") +t:eq(Midi.sniff(Bytes.reader(buffer.fromstring("MThd\0\0\0\6"))), 1, "sniff MThd") +t:eq(Midi.sniff(Bytes.reader(buffer.fromstring("RIFF\0\0\0\0RMID"))), 1, "sniff RMID") +t:eq(Midi.sniff(Bytes.reader(buffer.fromstring("RIFF\0\0\0\0WAVE"))), 0, "sniff WAVE") + +local function sameEvents(got: { any }, want: { any }, label: string) + t:eq(#got, #want, label .. ": event count") + for i, w in want do + local g = got[i] + local l = label .. " event " .. i + t:eq(g.tick, w[1], l .. " tick") + t:eq(g.type, w[2], l .. " type") + t:eq(g.channel or -1, w[3], l .. " channel") + t:eq(if g.type == "meta" then g.meta else -1, w[5], l .. " meta type") + local d = g.data or {} + t:eq(#d, #w[4], l .. " data length") + for k, v in w[4] do + if d[k] ~= v then + t:eq(d[k], v, l .. " data byte " .. k) + end + end + end +end + +local function trackEvents(m: any): { { any } } + local out = {} + for ti, tr in m.tracks do + local evs = {} + for _, ev in tr.events do + table.insert(evs, { ev.tick, ev.type, ev.channel or -1, ev.data or {}, if ev.type == "meta" then ev.meta else -1 }) + end + out[ti] = evs + end + return out +end + +local byName = {} +for _, c in Cases do + byName[c.name] = c + local m, err = decode(c.data) + t:check(m, c.name .. ": " .. tostring(err)) + t:eq(m.kind, "midi", c.name .. ": kind") + t:eq(m.format, c.type, c.name .. ": format") + t:eq(m.division, c.division, c.name .. ": division") + t:eq(#m.tracks, #c.tracks, c.name .. ": tracks") + for ti, want in c.tracks do + sameEvents(m.tracks[ti].events, want, c.name .. " track " .. ti) + end + -- mido's own bytes come back exactly (running status as mido writes it) + if c.exact then + local out, eerr = Midi.encode(m) + t:check(out, c.name .. ": encode " .. tostring(eerr)) + t:eq(buffer.tostring(out :: buffer) == c.data, true, c.name .. ": re-encoded bytes equal mido's") + end + -- without running status: longer (or equal), and the same events + local plain = Midi.encode(m, { runningStatus = false }) :: buffer + local withRs = Midi.encode(m) :: buffer + t:check(buffer.len(plain) >= buffer.len(withRs), c.name .. ": running status saves bytes") + local back = decode(plain) + t:check(back, c.name .. ": re-decode") + for ti, want in trackEvents(m) do + sameEvents(back.tracks[ti].events, want, c.name .. " round trip track " .. ti) + end + -- tempo map: every event's time against mido's merged message times + if c.times then + local secs = {} + for _, tr in m.tracks do + for _, ev in tr.events do + if not (ev.type == "meta" and ev.meta == 0x2F) then -- mido merges the end-of-track events into one + table.insert(secs, Midi.tickToSeconds(m, ev.tick)) + end + end + end + table.sort(secs) + t:eq(#secs, #c.times - 1, c.name .. ": event count vs mido") + local worst = 0 + for i, s in secs do + worst = math.max(worst, math.abs(s - c.times[i])) + end + t:check(worst < 1e-6, c.name .. ": event times match mido (worst " .. worst .. " s)") + t:check(math.abs(Midi.length(m) - c.length) < 1e-6, c.name .. ": length " .. Midi.length(m) .. " vs mido " .. c.length) + t:check(math.abs(m.meta.length - c.length) < 1e-6, c.name .. ": meta.length") + end +end +t:note("%d files parse as mido parses them; mido's files re-encode byte for byte", #Cases) + +-- meta summaries +do + local m = decode(byName.format0.data) + t:eq(m.tracks[1].name, "format zero", "track name") + t:eq(#m.meta.tempos, 3, "tempo changes") + t:eq(m.meta.tempos[1].usPerQuarter, 500000, "first tempo") + t:eq(m.meta.tempos[1].bpm, 120, "bpm") + t:eq(#m.meta.timeSignatures, 2, "time signatures") + t:eq(m.meta.timeSignatures[1].numerator, 3, "3/4 numerator") + t:eq(m.meta.timeSignatures[1].denominator, 4, "3/4 denominator") + t:eq(m.meta.timeSignatures[2].denominator, 8, "6/8 denominator") + t:eq(m.meta.keySignatures[1].sharps, -3, "Eb: 3 flats") + t:eq(m.meta.keySignatures[1].minor, false, "Eb major") + local s = decode(byName.smpte.data) + t:eq(s.meta.smpte.fps, 25, "smpte fps") + t:eq(s.meta.smpte.ticksPerFrame, 40, "smpte ticks per frame") + t:check(math.abs(Midi.tickToSeconds(s, 1000) - 1) < 1e-12, "smpte: 1000 ticks at 25 x 40 = 1 s") + t:eq(decode(byName.rmid.data).meta.rmid, true, "rmid flag") + -- format 2: per-track tempo maps, the tracks one after another + local f2 = decode(byName.format2.data) + local total = 0 + for ti, tr in f2.tracks do + local last = tr.events[#tr.events].tick + total += Midi.tickToSeconds(f2, last, ti) + end + t:check(math.abs(Midi.length(f2) - total) < 1e-9, "format 2 length = the tracks in sequence") +end + +-- a value built by hand: unsorted events are written in tick order, end of track added, bad values refused +do + local m = Types.Midi.new(96) + m.format = 0 + m.tracks[1] = { events = { + { tick = 50, type = "noteOff", channel = 2, data = { 60, 0 } }, + { tick = 0, type = "noteOn", channel = 2, data = { 60, 100 } }, + { tick = 50, type = "meta", meta = 0x2F, data = {} }, + { tick = 20, type = "controller", channel = 2, data = { 64, 127 } }, + } } + local b = Midi.encode(m) :: buffer + local back = decode(b) + sameEvents(back.tracks[1].events, { + { 0, "noteOn", 2, { 60, 100 }, -1 }, { 20, "controller", 2, { 64, 127 }, -1 }, { 50, "noteOff", 2, { 60, 0 }, -1 }, + { 50, "meta", -1, {}, 0x2F }, + }, "sorted on write") + local function refuses(mut: (any) -> (), label: string) + local x = Types.Midi.new(96) + x.tracks[1] = { events = { { tick = 0, type = "noteOn", channel = 0, data = { 60, 100 } } } } + mut(x) + local out, err = Midi.encode(x) + t:check(out == nil and Err.is(err) and err.code == Err.ARG, "encode refuses " .. label) + end + refuses(function(x) x.tracks[1].events[1].channel = 16 end, "channel 16") + refuses(function(x) x.tracks[1].events[1].data = { 60, 128 } end, "data byte 128") + refuses(function(x) x.tracks[1].events[1].tick = -1 end, "negative tick") + refuses(function(x) x.tracks[1].events[1].type = "wobble" end, "unknown type") + refuses(function(x) x.division = 0 end, "zero division") + refuses(function(x) x.format = 0; x.tracks[2] = { events = {} } end, "format 0 with two tracks") + local nope, nerr = Midi.encode(nil :: any) + t:check(nope == nil and nerr.code == Err.ARG, "encode refuses nil") +end + +-- crafted bad files +for _, c in Bad do + local ok, m, err = pcall(decode, c.data) + t:check(ok, c.name .. ": threw " .. tostring(m)) + t:check(m == nil and Err.is(err), c.name .. ": decoded") + t:eq(err.code, c.code, c.name .. ": error code (" .. tostring(err) .. ")") +end + +-- truncation: lenient keeps what it read, strict fails +do + local m = decode(Trunc.data) + t:check(m and m.meta.truncated, "truncated file decodes leniently, flagged") + local n = 0 + for _, tr in m.tracks do + n += #tr.events + end + t:check(n > 50, "truncated file keeps its events (" .. n .. ")") + local s, err = decode(Trunc.data, { strict = true }) + t:check(s == nil and err.code == Err.TRUNCATED, "strict: TRUNCATED") + t:eq(decode(byName.format1.data, { strict = true }).meta.truncated, false, "strict: a whole file passes") + local l, lerr = decode(byName.random.data, { maxEvents = 100 }) + t:check(l == nil and lerr.code == Err.LIMIT, "maxEvents: LIMIT") +end + +-- render through the built-in waveform set +do + local song = decode(byName.song.data) + local dec = song:render({ tail = 0.5 }) + local want = math.ceil((byName.song.length + 0.5) * 44100) + t:eq(dec.frames, want, "render: frames = (length + tail) * rate") + t:eq(dec.channels, 2, "render: stereo") + t:eq(dec.sampleRate, 44100, "render: rate") + local total, sumsq, peak = 0, 0, 0 + local out = buffer.create(4096 * 8) + while true do + local b, n = dec:read(4096, out) + if n == 0 then + break + end + for i = 0, n * 2 - 1 do + local v = buffer.readf32(b, i * 4) + sumsq += v * v + peak = math.max(peak, math.abs(v)) + end + total += n + end + t:eq(total, want, "render: reads every frame") + local rms = math.sqrt(sumsq / (total * 2)) + t:check(rms > 0.01 and peak < 4 and peak == peak, string.format("render: audible and sane (rms %.3f, peak %.3f)", rms, peak)) + t:note("fallback render: %.2f s, rms %.3f, peak %.3f", total / 44100, rms, peak) + -- seek: the same samples as playing through + local a = song:render({ tail = 0.5 }) + a:seek(1.5) + t:check(math.abs(a:position() - 1.5) < 1e-4, "seek position") + local x = buffer.create(1024 * 8) + a:read(1024, x) + local c = song:render({ tail = 0.5 }) + c:read(66150) + local y = c:read(1024) + local same = true + for i = 0, 2047 do + if buffer.readf32(x, i * 4) ~= buffer.readf32(y, i * 4) then + same = false + break + end + end + t:check(same, "seek renders the same samples as reading through") + a:seek(0.25) -- backwards + t:check(math.abs(a:position() - 0.25) < 1e-4, "seek backwards") + -- open = decode + render + local o = Midi.open(Bytes.reader(buffer.fromstring(byName.song.data)), { sampleRate = 22050, tail = 0 }) + t:check(o and o.sampleRate == 22050, "open: a Decoder at the asked rate") + local bad, berr = Midi.render(song, { sampleRate = 5 }) + t:check(bad == nil and berr.code == Err.ARG, "render: bad sampleRate") + local bs, bserr = Midi.render(song, { soundfont = "not a soundfont" }) + t:check(bs == nil and Err.is(bserr), "render: bad soundfont bytes") +end + +-- the fuzz no-throw pass +local samples = {} +for _, c in Cases do + if #c.data < 20000 then + table.insert(samples, c.data) + end +end +t:fuzz("decode", function(b: buffer) + return decode(b) +end, samples, { mutations = 40 }) +t:fuzz("decode + render", function(b: buffer) + local m = decode(b) + if m then + local dec = Midi.render(m, { tail = 0.1 }) + if dec then + dec:read(2048) + dec:read(2048) + end + Midi.encode(m) + end +end, samples, { mutations = 20, garbage = 50 }) + +t:done() diff --git a/tests/music/mod.luau b/tests/music/mod.luau new file mode 100644 index 0000000..79e8941 --- /dev/null +++ b/tests/music/mod.luau @@ -0,0 +1,127 @@ +-- music/mod tests: generated ProTracker modules (tools/fixtures/mod.py) parsed, rendered through codecs/Tracker and +-- compared with openmpt123's render (loudness envelope, band spectrum, stereo balance, song length), the MOD writer's +-- round trip, the contract, and the fuzz no-throw pass. +local T = require("@tests/T") +local S = require("@tests/music/_similar") +local Mod = require("@formats/music/mod") +local Tracker = require("@formats/codecs/Tracker") +local Bytes = require("@formats/core/Bytes") +local Cases = require("@tests/gen/mod_cases") + +local t = T.suite("mod") + +t:eq(Mod.name, "mod", "name") +t:eq(Mod.category, "music", "category") +t:check(Mod.caps.decode and Mod.caps.encode, "caps") + +local function load(data: string): any + return Mod.decode(Bytes.reader(buffer.fromstring(data))) +end + +local THRESH = { gainDb = 0.5, envErr = 1.0, spectral = 0.95, balance = 0.04, duration = 0.01 } + +for _, c in Cases do + local m, err = load(c.data) + t:check(m, c.name .. ": " .. tostring(err)) + t:check(Mod.sniff(Bytes.reader(buffer.fromstring(c.data))) > 0, c.name .. ": sniff") + local dec = m:render({ sampleRate = S.SR }) + t:check(dec, c.name .. ": render") + t:check(math.abs(dec.duration - c.duration) < THRESH.duration, string.format("%s: duration %.3f s, openmpt %.3f s", c.name, dec.duration, c.duration)) + local buf, frames = S.renderAll(dec, math.floor(c.duration * S.SR)) + local r = S.compare(S.features(buf, frames), c.ref) + t:note("%-7s gain %+.2f dB, loudness error %.2f dB, spectrum %.3f, balance %.3f, %.2f s", c.name, r.gainDb, r.envErr, r.spectral, r.balance, dec.duration) + if r.spectral < THRESH.spectral or r.envErr > THRESH.envErr then + for _, w in S.worst(S.features(buf, frames), c.ref, 6) do + t:note(" block %d (%.2f s): spectrum %.3f, ours %.1f dB, ref %.1f dB", w[1], (w[1] - 1) * 2048 / S.SR, w[2], w[3], w[4]) + end + end + t:check(math.abs(r.gainDb) < THRESH.gainDb, c.name .. ": loudness") + t:check(r.envErr < THRESH.envErr, c.name .. ": loudness envelope") + t:check(r.spectral > THRESH.spectral, c.name .. ": spectrum") + t:check(r.balance < THRESH.balance, c.name .. ": stereo balance") + -- the writer: MOD -> MOD gives the same bytes back (the fixtures are canonical ProTracker files) + local out, werr = Mod.encode(m) + t:check(out, c.name .. ": encode " .. tostring(werr)) + local m2 = Mod.decode(Bytes.reader(out :: buffer)) + t:check(m2, c.name .. ": re-decode") + t:eq(buffer.tostring(out :: buffer), c.data, c.name .. ": round trip bytes") +end + +-- MOD -> XM: the converted module plays as long, and sounds alike (XM has no channel panning and uses FT2's NTSC +-- Amiga clock, so only the duration and the band spectrum are compared) +local Xm = require("@formats/music/xm") +for _, c in Cases do + local m = load(c.data) + local xb, xerr = Xm.encode(m) + t:check(xb, c.name .. ": mod -> xm " .. tostring(xerr)) + local x = Xm.decode(Bytes.reader(xb :: buffer)) + t:check(x and x.format == "xm" and #x.instruments == #m.samples, c.name .. ": the xm decodes") + local dec = x:render() + t:check(math.abs(dec.duration - c.duration) < THRESH.duration, c.name .. ": xm duration") + local buf, frames = S.renderAll(dec, math.floor(c.duration * S.SR)) + local r = S.compare(S.features(buf, frames), c.ref) + t:check(r.spectral > 0.9, string.format("%s: xm spectrum %.3f", c.name, r.spectral)) +end + +-- through the API: load sniffs the MOD, open gives a Decoder, save converts to XM, load(as audio) renders +do + local F = require("@formats") + local m, err = F.load(Cases[1].data) + t:check(m and m.kind == "music" and m.format == "mod", "F.load: " .. tostring(err)) + local dec = F.open(Cases[1].data) + t:check(dec and dec.channels == 2 and dec.sampleRate == 44100, "F.open: a Decoder") + local xb = F.save(m, nil, { format = "xm" }) + t:check(xb and F.load(xb).format == "xm", "F.save as xm") + t:eq(F.saveString(m, { format = "mod" }), Cases[1].data, "F.saveString keeps the MOD bytes") +end + +-- seek: the position after a seek and the output continuing +do + local m = load(Cases[1].data) + local dec = m:render() + dec:seek(2) + t:check(math.abs(dec:position() - 2) < 0.001, "seek position") + local _, n = dec:read(1000) + t:eq(n, 1000, "read after seek") + t:check(Tracker.duration(m) == dec.duration, "duration()") + -- the same samples as playing up to that point (after the short fade-in that follows a seek) + local a, b = m:render(), m:render() + a:seek(3.5) + local at = math.floor(3.5 * S.SR) + while at > 0 do + local _, n = b:read(math.min(at, 8192)) + at -= n + end + local x, y = a:read(4096), b:read(4096) + local worst = 0 + for i = 256, 4095 * 2 do + worst = math.max(worst, math.abs(buffer.readf32(x, i * 4) - buffer.readf32(y, i * 4))) + end + t:check(worst < 1e-4, "seek then read matches reading through (" .. worst .. ")") + -- loop = true keeps playing past the end (frames / duration still give one pass) + local l = m:render({ loop = true, sampleRate = 8000 }) + local total = 0 + for _ = 1, 30 do + local _, n = l:read(8000) + total += n + end + t:check(total == 240000 and math.abs(l.duration - dec.duration) < 0.01, "loop plays past the end") +end + +-- the fuzz pass: decode, and a short render of whatever decodes +local samples = {} +for _, c in Cases do + table.insert(samples, c.data) +end +t:fuzz("decode", function(b: buffer) + local m = Mod.decode(Bytes.reader(b)) + if m then + local dec = Tracker.render(m, { maxDuration = 0.5, sampleRate = 8000 }) + if dec then + dec:read(4000) + end + end + return m +end, samples, { mutations = 30 }) + +t:done() diff --git a/tests/music/s3m.luau b/tests/music/s3m.luau new file mode 100644 index 0000000..ddff1a5 --- /dev/null +++ b/tests/music/s3m.luau @@ -0,0 +1,71 @@ +-- music/s3m tests: generated Scream Tracker 3 modules (tools/fixtures/s3m.py) parsed, rendered through codecs/Tracker and +-- compared with openmpt123's render (loudness envelope, band spectrum, stereo balance, song length), the contract, +-- and the fuzz no-throw pass. +local T = require("@tests/T") +local S = require("@tests/music/_similar") +local S3m = require("@formats/music/s3m") +local Tracker = require("@formats/codecs/Tracker") +local Bytes = require("@formats/core/Bytes") +local Cases = require("@tests/gen/s3m_cases") + +local t = T.suite("s3m") + +t:eq(S3m.name, "s3m", "name") +t:eq(S3m.category, "music", "category") +t:check(S3m.caps.decode and not S3m.caps.encode, "caps") + +local function load(data: string): any + return S3m.decode(Bytes.reader(buffer.fromstring(data))) +end + +local THRESH = { gainDb = 0.5, envErr = 1.0, spectral = 0.95, balance = 0.04, duration = 0.01 } + +for _, c in Cases do + local m, err = load(c.data) + t:check(m, c.name .. ": " .. tostring(err)) + t:check(S3m.sniff(Bytes.reader(buffer.fromstring(c.data))) > 0, c.name .. ": sniff") + local dec = m:render({ sampleRate = S.SR }) + t:check(dec, c.name .. ": render") + t:check(math.abs(dec.duration - c.duration) < THRESH.duration, string.format("%s: duration %.3f s, openmpt %.3f s", c.name, dec.duration, c.duration)) + local buf, frames = S.renderAll(dec, math.floor(c.duration * S.SR)) + local r = S.compare(S.features(buf, frames), c.ref) + t:note("%-7s gain %+.2f dB, loudness error %.2f dB, spectrum %.3f, balance %.3f, %.2f s", c.name, r.gainDb, r.envErr, r.spectral, r.balance, dec.duration) + if r.spectral < THRESH.spectral or r.envErr > THRESH.envErr then + for _, w in S.worst(S.features(buf, frames), c.ref, 6) do + t:note(" block %d (%.2f s): spectrum %.3f, ours %.1f dB, ref %.1f dB", w[1], (w[1] - 1) * 2048 / S.SR, w[2], w[3], w[4]) + end + end + t:check(math.abs(r.gainDb) < THRESH.gainDb, c.name .. ": loudness") + t:check(r.envErr < THRESH.envErr, c.name .. ": loudness envelope") + t:check(r.spectral > THRESH.spectral, c.name .. ": spectrum") + t:check(r.balance < THRESH.balance, c.name .. ": stereo balance") +end + +-- seek: the position after a seek and the output continuing +do + local m = load(Cases[1].data) + local dec = m:render() + dec:seek(2) + t:check(math.abs(dec:position() - 2) < 0.001, "seek position") + local _, n = dec:read(1000) + t:eq(n, 1000, "read after seek") + t:check(Tracker.duration(m) == dec.duration, "duration()") +end + +-- the fuzz pass: decode, and a short render of whatever decodes +local samples = {} +for _, c in Cases do + table.insert(samples, c.data) +end +t:fuzz("decode", function(b: buffer) + local m = S3m.decode(Bytes.reader(b)) + if m then + local dec = Tracker.render(m, { maxDuration = 0.5, sampleRate = 8000 }) + if dec then + dec:read(4000) + end + end + return m +end, samples, { mutations = 30 }) + +t:done() diff --git a/tests/music/sf2.luau b/tests/music/sf2.luau new file mode 100644 index 0000000..057b30e --- /dev/null +++ b/tests/music/sf2.luau @@ -0,0 +1,338 @@ +-- music/sf2 + codecs/SoundFont tests: a self-made SF2 parsed (INFO, presets, sample headers, instruments, generator +-- merging with preset / instrument global zones, 16-bit and sm24 samples), a test song rendered through it compared +-- with FluidSynth's render (loudness envelope and per-segment band spectra by correlation, pitch peaks), bad files, +-- the built-in fallback waveform set, and the fuzz no-throw pass. Fixtures: tools/fixtures/sf2.py. +local T = require("@tests/T") +local Sf2 = require("@formats/music/sf2") +local Midi = require("@formats/music/midi") +local SoundFont = require("@formats/codecs/SoundFont") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/sf2_cases") + +local t = T.suite("sf2") + +local function reader(s: string): Bytes.Reader + return Bytes.reader(buffer.fromstring(s)) +end + +-- the contract +t:eq(Sf2.name, "sf2", "name") +t:eq(Sf2.category, "music", "category") +t:check(Sf2.caps.decode and not Sf2.caps.encode, "caps") +t:eq(Sf2.sniff(reader(Fx.sf2)), 1, "sniff") +t:eq(Sf2.sniff(reader("RIFF\0\0\0\0WAVE")), 0, "sniff WAVE") + +-- parse +local sf, err = Sf2.decode(reader(Fx.sf2)) +t:check(sf, "decode: " .. tostring(err)) +local E = Fx.expect +t:eq(sf.kind, "soundfont", "kind") +t:eq(sf.info.name, E.info.name, "INAM") +t:eq(sf.info.engine, E.info.engine, "isng") +t:eq(sf.meta.source.version, E.info.version, "ifil") +t:eq(#sf.presets, #E.presets, "preset count") +for i, p in E.presets do + t:eq(sf.presets[i].name, p.name, "preset " .. i .. " name") + t:eq(sf.presets[i].bank, p.bank, "preset " .. i .. " bank") + t:eq(sf.presets[i].preset, p.preset, "preset " .. i .. " number") +end +t:eq(#sf.sampleHeaders, #E.samples, "sample headers") +for i, s in E.samples do + for k, v in s do + t:eq(sf.sampleHeaders[i][k], v, "sample " .. i .. " " .. k) + end +end +for i, n in E.instruments do + t:eq(sf.instruments[i].name, n, "instrument " .. i) +end +local function preset(name: string): any + for _, p in sf.presets do + if p.name == name then + return p + end + end + return nil +end +do + local sine, saw, drums = preset("Sine"), preset("Saw"), preset("Drums") + t:eq(#sine.regions, 1, "Sine: the preset global zone is not a region") + t:check(math.abs(sine.regions[1].attenuation - 30 * 0.04) < 1e-9, "Sine: the preset global zone's attenuation applies") + t:check(math.abs(sine.regions[1].aRelease - 0.2) < 0.001, "Sine: release in seconds") + t:check(math.abs(sine.regions[1].aSustain - 10 ^ (-6 / 20)) < 1e-6, "Sine: sustain 60 cB = -6 dB") + t:eq(sine.regions[1].loopMode, 1, "Sine: looped") + t:eq(sine.regions[1].keycenter, 69, "Sine: root key from the sample header") + t:eq(sine.regions[1].tune, -4, "Sine: pitch correction") + t:eq(#saw.regions, 1, "Saw: the instrument global zone is not a region") + t:check(math.abs(saw.regions[1].filterFc - math.floor(1200 * math.log(2500 / 8.176, 2) + 0.5)) <= 1, "Saw: the instrument global zone's filter applies") + t:eq(saw.regions[1].modEnvToFilterFc, 2400, "Saw: mod env to filter") + t:eq(#drums.regions, 4, "Drums: four key zones") + local groups = 0 + for _, r in drums.regions do + t:check(math.abs(r.aRelease - 0.05) < 0.001, "Drums: release from the instrument global zone") + if r.group == 1 then + groups += 1 + end + end + t:eq(groups, 2, "Drums: two hats in exclusive class 1") + t:eq(drums.regions[1].lokey, 35, "Drums: key range lo") + t:eq(drums.regions[1].hikey, 36, "Drums: key range hi") +end +-- samples: 16-bit, and 24-bit with sm24 +do + local sf24 = Sf2.decode(reader(Fx.sf2_24)) + t:check(sf24 and sf24.meta.source.sm24, "sm24 read") + t:eq(sf.meta.source.sm24, false, "no sm24") + for _, v in E.values do + local i, hi, lo = v[1], v[2], v[3] + local a = buffer.readf32(sf.samples, i * 4) + local b = buffer.readf32(sf24.samples, i * 4) + t:check(math.abs(a - hi / 32767) < 1e-6, "16-bit sample " .. i) + t:check(math.abs(b - (hi * 256 + lo) / 8388607) < 1e-6, "24-bit sample " .. i) + end + t:eq(buffer.len(sf.samples), (sf.sampleCount + 1) * 4, "samples: one pad sample") +end + +-- ------------------------------------------------------------------------------------------------ vs FluidSynth +local F = Fx.fluid +local song = Midi.decode(reader(Fx.song)) +t:check(song, "song decodes") +local dec = assert(Midi.render(song, { soundfont = sf, tail = 2 })) +local frames = math.min(dec.frames, F.frames) +local mono = table.create(frames, 0) +do + local got = 0 + while got < frames do + local b, n = dec:read(math.min(8192, frames - got)) + if n == 0 then + break + end + for i = 0, n - 1 do + mono[got + i + 1] = (buffer.readf32(b, i * 8) + buffer.readf32(b, i * 8 + 4)) * 0.5 + end + got += n + end + t:eq(got, frames, "rendered the compared length") +end + +local function pearson(a: { number }, b: { number }): number + local n = math.min(#a, #b) + local ma, mb = 0, 0 + for i = 1, n do + ma += a[i] + mb += b[i] + end + ma /= n + mb /= n + local sab, saa, sbb = 0, 0, 0 + for i = 1, n do + local x, y = a[i] - ma, b[i] - mb + sab += x * y + saa += x * x + sbb += y * y + end + return sab / math.sqrt(saa * sbb + 1e-30) +end + +-- in-place radix-2 FFT of re / im (1-based arrays of length n, a power of two) +local function fft(re: { number }, im: { number }, n: number) + local j = 0 + for i = 0, n - 2 do + if i < j then + re[i + 1], re[j + 1] = re[j + 1], re[i + 1] + im[i + 1], im[j + 1] = im[j + 1], im[i + 1] + end + local m = n // 2 + while m >= 1 and j >= m do + j -= m + m //= 2 + end + j += m + end + local len = 2 + while len <= n do + local ang = -2 * math.pi / len + local wr, wi = math.cos(ang), math.sin(ang) + for s = 0, n - 1, len do + local cr, ci = 1, 0 + for k = 0, len // 2 - 1 do + local a, b = s + k + 1, s + k + len // 2 + 1 + local xr = re[b] * cr - im[b] * ci + local xi = re[b] * ci + im[b] * cr + re[b], im[b] = re[a] - xr, im[a] - xi + re[a], im[a] = re[a] + xr, im[a] + xi + cr, ci = cr * wr - ci * wi, cr * wi + ci * wr + end + end + len *= 2 + end +end + +local function power(start: number, n: number): { number } + local re, im = table.create(n, 0), table.create(n, 0) + for i = 0, n - 1 do + re[i + 1] = (mono[start + i + 1] or 0) * (0.5 - 0.5 * math.cos(2 * math.pi * i / n)) + end + fft(re, im, n) + local p = table.create(n // 2 + 1, 0) + for k = 0, n // 2 do + p[k + 1] = re[k + 1] ^ 2 + im[k + 1] ^ 2 + end + return p +end + +local rate = F.rate +-- the loudness envelope (50 ms RMS) +local env = {} +for i = 0, frames - 2205, 2205 do + local s = 0 + for k = 1, 2205 do + local v = mono[i + k] + s += v * v + end + table.insert(env, math.sqrt(s / 2205)) +end +local envCorr = pearson(env, F.env) +local ENV_MIN = 0.95 +t:check(envCorr > ENV_MIN, string.format("loudness envelope correlation %.3f > %.2f", envCorr, ENV_MIN)) +t:note("loudness envelope vs FluidSynth: r = %.3f (%d windows)", envCorr, #env) + +-- per-segment band spectra +local BAND_MIN = 0.93 +local worstBand = 1 +for si, seg in F.segments do + local acc = table.create(24, 0) + local count = 0 + for s = math.floor(seg[1] * rate), math.floor(seg[2] * rate) - 2048, 1024 do + local p = power(s, 2048) + for k = 0, 1024 do + local f = k * rate / 2048 + for b = 1, 24 do + if f >= F.edges[b] and f < F.edges[b + 1] then + acc[b] += p[k + 1] + break + end + end + end + count += 1 + end + local db = table.create(24, 0) + for b = 1, 24 do + db[b] = 10 * math.log10(acc[b] / math.max(count, 1) + 1e-12) + end + local r = pearson(db, F.bands[si]) + worstBand = math.min(worstBand, r) + t:check(r > BAND_MIN, string.format("segment %d band spectrum correlation %.3f > %.2f", si, r, BAND_MIN)) + t:note("segment %d (%g-%g s) band spectrum vs FluidSynth: r = %.3f", si, seg[1], seg[2], r) +end + +-- pitch peaks (vibrato square, a note bent an octave with an RPN 0 range of 12, the saw melody's first note) +for wi, w in F.windows do + local acc = table.create(4097, 0) + for s = math.floor(w[1] * rate), math.floor(w[2] * rate) - 8192, 2048 do + local p = power(s, 8192) + for k = 1, 4097 do + acc[k] += p[k] + end + end + local best, bk = -1, 2 + for k = 2, 4096 do + if acc[k] > best then + best, bk = acc[k], k + end + end + local y0, y1, y2 = math.log(acc[bk - 1] + 1e-30), math.log(acc[bk] + 1e-30), math.log(acc[bk + 1] + 1e-30) + local hz = ((bk - 1) + 0.5 * (y0 - y2) / (y0 - 2 * y1 + y2)) * rate / 8192 + local ratio = hz / F.peaks[wi] + t:check(math.abs(ratio - 1) < 0.015, string.format("window %d peak %.1f Hz vs FluidSynth %.1f Hz", wi, hz, F.peaks[wi])) + t:note("window %g-%g s: peak %.1f Hz (FluidSynth %.1f Hz)", w[1], w[2], hz, F.peaks[wi]) +end + +-- ------------------------------------------------------------------------------------------------ bad files +local function bad(data: string, code: string, label: string) + local ok, v, e = pcall(Sf2.decode, reader(data)) + t:check(ok, label .. ": threw " .. tostring(v)) + t:check(v == nil and Err.is(e) and e.code == code, label .. ": " .. tostring(e)) +end +bad("RIFX\0\0\0\0sfbk", Err.CORRUPT, "not RIFF") +bad("RIFF\4\0\0\0WAVE", Err.CORRUPT, "not sfbk") +bad("RIFF\4\0\0\0sfbk", Err.CORRUPT, "no chunks") +bad(string.sub(Fx.sf2, 1, 40), Err.CORRUPT, "truncated in INFO") +local lim, lerr = Sf2.decode(reader(Fx.sf2), { maxSamples = 100 }) +t:check(lim == nil and lerr.code == Err.LIMIT, "maxSamples: LIMIT") +local lim2, lerr2 = Sf2.decode(reader(Fx.sf2), { maxRegions = 3 }) +t:check(lim2 == nil and lerr2.code == Err.LIMIT, "maxRegions: LIMIT") +local p, perr = SoundFont.parse(42 :: any) +t:check(p == nil and perr.code == Err.ARG, "parse: bad argument") + +-- ------------------------------------------------------------------------------------------------ fallback +do + local fb = SoundFont.fallback() + t:eq(#fb.presets, 129, "fallback: 128 programs + a drum kit") + local s = SoundFont.synth(nil, 22050) + local Synth = SoundFont.Synth + local out = buffer.create(2205 * 8) + for program = 0, 127, 8 do + Synth.reset(s) + Synth.midi(s, 0xC0, program, 0) + Synth.midi(s, 0x90, 60, 100) + buffer.fill(out, 0, 0) + Synth.render(s, out, 0, 2205) + local e = 0 + for i = 0, 2205 * 2 - 1 do + local v = buffer.readf32(out, i * 4) + t:check(v == v and math.abs(v) < 4, "fallback: finite samples") + e += v * v + end + t:check(e > 0.01, "fallback program " .. program .. " sounds") + end + for _, key in { 35, 36, 38, 42, 46, 49, 51, 60 } do + Synth.reset(s) + Synth.midi(s, 0x99, key, 120) + buffer.fill(out, 0, 0) + Synth.render(s, out, 0, 2205) + local e = 0 + for i = 0, 2205 * 2 - 1 do + e += buffer.readf32(out, i * 4) ^ 2 + end + t:check(e > 0.01, "fallback drum " .. key .. " sounds") + end + -- exclusive class: a closed hat cuts the open hat + Synth.reset(s) + Synth.midi(s, 0x99, 46, 120) + t:eq(Synth.active(s), 1, "open hat") + Synth.midi(s, 0x99, 42, 120) + Synth.render(s, out, 0, 2205) + t:eq(Synth.active(s), 1, "closed hat ends the open hat (exclusive class)") + -- render range clipping: never writes past the buffer + Synth.render(s, out, 2200, 100000) + Synth.render(s, out, -5, 10) + t:check(true, "out-of-range render requests are clipped") +end + +-- the fuzz no-throw pass (parse, then a few notes through whatever parsed) +t:fuzz("decode", function(b: buffer) + local f = Sf2.decode(Bytes.reader(b)) + if f then + local s = SoundFont.synth(f, 22050) + for ch = 0, 15 do + SoundFont.Synth.midi(s, 0xC0 + ch, ch * 8, 0) + SoundFont.Synth.midi(s, 0x90 + ch, 30 + ch * 5, 100) + end + local out = buffer.create(512 * 8) + SoundFont.Synth.render(s, out, 0, 512) + end +end, { Fx.sf2 }, { mutations = 60, garbage = 100 }) +-- mutations inside the hydra (the last ~1 KB) exercise the zone / index clamping +t:fuzz("hydra", function(b: buffer) + local f = Sf2.decode(Bytes.reader(b)) + if f then + local s = SoundFont.synth(f, 22050) + SoundFont.Synth.midi(s, 0x90, 60, 100) + SoundFont.Synth.midi(s, 0x99, 36, 100) + local out = buffer.create(256 * 8) + SoundFont.Synth.render(s, out, 0, 256) + end +end, { Fx.sf2 }, { mutations = 200, garbage = 0, keepHeader = #Fx.sf2 - 1200 }) + +t:done() diff --git a/tests/music/xm.luau b/tests/music/xm.luau new file mode 100644 index 0000000..b117848 --- /dev/null +++ b/tests/music/xm.luau @@ -0,0 +1,77 @@ +-- music/xm tests: generated FastTracker 2 modules (tools/fixtures/xm.py) parsed, rendered through codecs/Tracker and +-- compared with openmpt123's render (loudness envelope, band spectrum, stereo balance, song length), the XM writer's +-- round trip, the contract, and the fuzz no-throw pass. +local T = require("@tests/T") +local S = require("@tests/music/_similar") +local Xm = require("@formats/music/xm") +local Tracker = require("@formats/codecs/Tracker") +local Bytes = require("@formats/core/Bytes") +local Cases = require("@tests/gen/xm_cases") + +local t = T.suite("xm") + +t:eq(Xm.name, "xm", "name") +t:eq(Xm.category, "music", "category") +t:check(Xm.caps.decode and Xm.caps.encode, "caps") + +local function load(data: string): any + return Xm.decode(Bytes.reader(buffer.fromstring(data))) +end + +local THRESH = { gainDb = 0.5, envErr = 1.0, spectral = 0.95, balance = 0.04, duration = 0.01 } + +for _, c in Cases do + local m, err = load(c.data) + t:check(m, c.name .. ": " .. tostring(err)) + t:check(Xm.sniff(Bytes.reader(buffer.fromstring(c.data))) > 0, c.name .. ": sniff") + local dec = m:render({ sampleRate = S.SR }) + t:check(dec, c.name .. ": render") + t:check(math.abs(dec.duration - c.duration) < THRESH.duration, string.format("%s: duration %.3f s, openmpt %.3f s", c.name, dec.duration, c.duration)) + local buf, frames = S.renderAll(dec, math.floor(c.duration * S.SR)) + local r = S.compare(S.features(buf, frames), c.ref) + t:note("%-7s gain %+.2f dB, loudness error %.2f dB, spectrum %.3f, balance %.3f, %.2f s", c.name, r.gainDb, r.envErr, r.spectral, r.balance, dec.duration) + if r.spectral < THRESH.spectral or r.envErr > THRESH.envErr then + for _, w in S.worst(S.features(buf, frames), c.ref, 6) do + t:note(" block %d (%.2f s): spectrum %.3f, ours %.1f dB, ref %.1f dB", w[1], (w[1] - 1) * 2048 / S.SR, w[2], w[3], w[4]) + end + end + t:check(math.abs(r.gainDb) < THRESH.gainDb, c.name .. ": loudness") + t:check(r.envErr < THRESH.envErr, c.name .. ": loudness envelope") + t:check(r.spectral > THRESH.spectral, c.name .. ": spectrum") + t:check(r.balance < THRESH.balance, c.name .. ": stereo balance") + -- the writer: XM -> XM gives the same bytes back (the fixtures use the FT2 layout) + local out, werr = Xm.encode(m) + t:check(out, c.name .. ": encode " .. tostring(werr)) + local m2 = Xm.decode(Bytes.reader(out :: buffer)) + t:check(m2, c.name .. ": re-decode") + t:eq(buffer.tostring(out :: buffer), c.data, c.name .. ": round trip bytes") +end + +-- seek: the position after a seek and the output continuing +do + local m = load(Cases[1].data) + local dec = m:render() + dec:seek(2) + t:check(math.abs(dec:position() - 2) < 0.001, "seek position") + local _, n = dec:read(1000) + t:eq(n, 1000, "read after seek") + t:check(Tracker.duration(m) == dec.duration, "duration()") +end + +-- the fuzz pass: decode, and a short render of whatever decodes +local samples = {} +for _, c in Cases do + table.insert(samples, c.data) +end +t:fuzz("decode", function(b: buffer) + local m = Xm.decode(Bytes.reader(b)) + if m then + local dec = Tracker.render(m, { maxDuration = 0.5, sampleRate = 8000 }) + if dec then + dec:read(4000) + end + end + return m +end, samples, { mutations = 30 }) + +t:done() diff --git a/tests/video/_common.luau b/tests/video/_common.luau new file mode 100644 index 0000000..e8aaae7 --- /dev/null +++ b/tests/video/_common.luau @@ -0,0 +1,221 @@ +-- tests/video/_common: shared checks for the video container tests (mkv, avi, y4m, mpegts, mpegps, mp4): a demuxer's +-- tracks and packets against ffprobe's, decoded frames against ffmpeg's (CRC-32 for bit-exact codecs, PSNR for the +-- others), audio through the api's hook against ffmpeg's f32 decode, seeking. Not a test by itself. +local F = require("@formats") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Video = require("@formats/codecs/Video") + +local C = {} + +-- the codecs whose decode must equal ffmpeg's bit for bit +C.EXACT = { vp8 = true, rawvideo = true } + +-- psnr(a, b, off?, n?) -> dB between two byte strings / buffers (math.huge when equal) +function C.psnr(a: buffer, b: buffer, n: number?): number + local len = n or math.min(buffer.len(a), buffer.len(b)) + local se = 0 + for i = 0, len - 1 do + local d = buffer.readu8(a, i) - buffer.readu8(b, i) + se += d * d + end + if se == 0 then + return math.huge + end + return 10 * math.log10(255 * 255 * len / se) +end + +-- snr(ours f32 buffer, reference f32 string, n samples) -> dB +function C.snr(ours: buffer, ref: string, n: number): number + local rb = buffer.fromstring(ref) + local sig, err = 0, 0 + for i = 0, n - 1 do + local r = buffer.readf32(rb, i * 4) + local d = buffer.readf32(ours, i * 4) - r + sig += r * r + err += d * d + end + if err == 0 then + return math.huge + end + return 10 * math.log10(sig / err) +end + +-- packets(t, dmx, c, label, opts?): every track's packets against ffprobe's (in order): size, CRC, time, keyframe. +-- opts.skipStream(ffprobePacket, track) -> true skips a stream (ffmpeg's parsers re-split some, e.g. MPEG audio in TS) +function C.packets(t: any, dmx: any, c: any, label: string, opts: any?) + local o = opts or {} + local trackOf = {} -- ffprobe stream index -> our track + for i, s in c.streams do + trackOf[s.index] = o.trackFor and o.trackFor(dmx, s) or dmx.tracks[i] + end + local k: { [number]: number } = {} + local total, bad = 0, 0 + local first = nil + for _, want in c.packets do + local tr = trackOf[want.stream] + if not (o.skipStream and o.skipStream(want, tr)) then + total += 1 + local id = if tr then tr.id else -1 + k[id] = (k[id] or 0) + 1 + local p = if tr then dmx:get(id, k[id]) else nil + local ok = p ~= nil and buffer.len(p.data) == want.size and Crc32.of(p.data) == want.crc + local s = c.streams[want.stream + 1] + if ok and p and want.pts and s and not o.noPts then + local ours = p.pts / tr.timescale - (tr.codecDelay or 0) -- ffmpeg shifts by Matroska's CodecDelay + local theirs = want.pts * s.tbn / s.tbd + ok = math.abs(ours - theirs) < 0.0015 + end + if ok and p and not o.noKey and tr and tr.kind == "video" then + ok = p.keyframe == want.key + end + if not ok then + bad += 1 + if not first then + first = string.format("track %s packet %d: size %s/%d pts %s/%s key %s/%s crc %s", tostring(id), k[id], tostring(p and buffer.len(p.data)), want.size, tostring(p and p.pts), tostring(want.pts), tostring(p and p.keyframe), tostring(want.key), tostring(p and Crc32.of(p.data) == want.crc)) + end + end + end + end + local extra = 0 + for id, n in k do + extra += math.max(0, dmx:count(id) - n) + end + t:check(bad == 0, label .. ": " .. total .. " packets equal ffprobe's (" .. bad .. " differ" .. (if first then "; first: " .. first else "") .. ")") + t:check(extra == 0, label .. ": no extra packets (" .. extra .. ")") +end + +-- frames(t, v, c, label): every decoded frame against ffmpeg's (CRC for EXACT codecs, else PSNR of the raw ones) +function C.frames(t: any, v: any, c: any, label: string, minPsnr: number?) + if not c.frames then + return + end + if not Video.canDecode(v.codec) then + t:note("%s: no %s decoder, frames not checked", label, v.codec) + return + end + v:reset() + local n, bad, worst = 0, 0, math.huge + local firstBad = nil + while true do + local f, err = v:nextFrame() + if not f then + t:check(err == nil, label .. ": decode error " .. tostring(err)) + break + end + n += 1 + local img = f.image + if img.format ~= "yuv420p" then + t:check(false, label .. ": frame " .. n .. " is " .. img.format) + break + end + if C.EXACT[v.codec] then + if Crc32.of(img.pixels) ~= c.frames[n] then + bad += 1 + firstBad = firstBad or n + end + elseif c.yuv and c.yuv[n] then + local p = C.psnr(img.pixels, buffer.fromstring(c.yuv[n])) + worst = math.min(worst, p) + end + end + t:eq(n, #c.frames, label .. ": frame count") + if C.EXACT[v.codec] then + t:check(bad == 0, label .. ": every frame bit-exact with ffmpeg (" .. bad .. " differ, first " .. tostring(firstBad) .. ")") + elseif c.yuv then + t:check(worst >= (minPsnr or 38), string.format("%s: PSNR vs ffmpeg %.1f dB", label, worst)) + end +end + +-- audio(t, v, c, label, exact?): the audio decoder (through the api hook) against ffmpeg's f32 +function C.audio(t: any, v: any, c: any, label: string, exact: boolean?, minSnr: number?) + if not c.pcm then + return + end + if not v.audio then + local code = v.audioError and v.audioError.code + t:check(code == F.Err.UNKNOWN_FORMAT or code == F.Err.UNSUPPORTED, label .. ": audio missing only for a missing audio format (" .. tostring(v.audioError) .. ")") + return + end + local a = v.audio + a:seek(0) + local want = #c.pcm // 4 + local out = buffer.create(want * 4) + local got = 0 + while got * a.channels < want do + local chunk, k = a:read(want // a.channels - got) + if not chunk or k <= 0 then + break + end + buffer.copy(out, got * a.channels * 4, chunk, 0, k * a.channels * 4) + got += k + end + local n = got * a.channels + t:check(n == want or n * 4 == c.pcmBytes, label .. ": " .. n .. " samples read of " .. want) + n = math.min(n, want) + if exact then + local same = true + local rb = buffer.fromstring(c.pcm) + for i = 0, n - 1 do + if math.abs(buffer.readf32(out, i * 4) - buffer.readf32(rb, i * 4)) > 1e-6 then + same = false + break + end + end + t:check(same, label .. ": PCM equal to ffmpeg's") + else + local s = C.snr(out, c.pcm, n) + t:check(s >= (minSnr or 30), string.format("%s: audio SNR vs ffmpeg %.1f dB", label, s)) + end +end + +-- seek(t, v, c, label, at): after seek(at) the next frame is the first at or after `at` +function C.seek(t: any, v: any, c: any, label: string, at: number) + if not (c.frames or c.rgba) or not Video.canDecode(v.codec) then + return + end + if v.duration > 0 and at > v.duration * 0.6 then + at = math.floor(v.duration * 50) / 100 + end + v:seek(at) + local f = v:nextFrame() + t:check(f ~= nil and f.pts >= at - 1e-6 and f.pts < at + 0.2, label .. ": seek to " .. at .. " lands at " .. tostring(f and f.pts)) + if f and C.EXACT[v.codec] and c.frames then + local idx = math.floor(f.pts * v.frameRate + 0.5) + 1 + t:eq(Crc32.of(f.image.pixels), c.frames[idx], label .. ": the frame after seeking equals ffmpeg's frame " .. idx) + end + v:reset() +end + +-- fuzzOpen(Fmt) -> a fuzz function: open, read every packet, decode up to 8 frames, read some audio +function C.fuzzOpen(Fmt: any): (buffer) -> any + return function(b: buffer): any + local v = Fmt.open(Bytes.reader(b), { openAudio = function(d: any, tr: any): any + local AudioWrap = require("@formats/containers/AudioWrap") + AudioWrap.wrap(d, tr) + return nil + end }) + if not v then + return nil + end + for _ = 1, 8 do + local f = v:nextFrame() + if not f then + break + end + end + if v.demuxer then + v.demuxer:rewind() + while v.demuxer:read() do + end + end + return v + end +end + +-- open(data, opts?) -> VideoDecoder through the api (category video) +function C.open(data: string, opts: any?): (any, any) + return F.video.open(buffer.fromstring(data), opts) +end + +return C diff --git a/tests/video/avi.luau b/tests/video/avi.luau new file mode 100644 index 0000000..8bf192e --- /dev/null +++ b/tests/video/avi.luau @@ -0,0 +1,97 @@ +-- video/avi tests: AVI files from ffmpeg (MJPEG + PCM s16 / u8 / IMA ADPCM, MPEG-1 + MP2, uncompressed BGR24 / BGRA / +-- I420) read through the OpenDML indexes, idx1 alone, and a movi scan: tracks and every packet against ffprobe, +-- frames against ffmpeg, audio through the api hook, seeking; our muxer (MJPEG + PCM) read back; a GIF converted to +-- AVI. Fixtures: tools/fixtures/avi.py. +local T = require("@tests/T") +local C = require("@tests/video/_common") +local F = require("@formats") +local AviFormat = require("@formats/video/avi") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Fx = require("@tests/gen/avi_cases") + +local t = T.suite("avi") + +t:eq(AviFormat.name, "avi", "name") +t:eq(AviFormat.category, "video", "category") + +local EXACT_AUDIO = { pcm_s16le = true, pcm_u8 = true, adpcm_ima_wav = true } +local byName = {} +for _, c in Fx do + byName[c.name] = c +end + +for _, c in Fx do + local label = c.name + t:check(AviFormat.sniff(Bytes.reader(buffer.fromstring(c.data))) > 0, label .. ": sniff") + local v, err = C.open(c.data) + if c.truncated then + t:check(v ~= nil or err ~= nil, label .. ": opens or fails cleanly") + else + t:check(v ~= nil, label .. ": open: " .. tostring(err)) + if v then + local dmx = v.demuxer + t:eq(#dmx.tracks, #c.streams, label .. ": track count") + C.packets(t, dmx, c, label) + if c.rgba then + v:reset() + local n, bad = 0, 0 + while true do + local f = v:nextFrame() + if not f then + break + end + n += 1 + if f.image.format ~= "rgba8" or Crc32.of(f.image.pixels) ~= c.rgba[n] then + bad += 1 + end + end + t:check(n == #c.rgba and bad == 0, label .. ": " .. n .. " rgba frames equal ffmpeg's (" .. bad .. " differ)") + else + C.frames(t, v, c, label) + end + local at = dmx:track("audio") + if at then + C.audio(t, v, c, label, EXACT_AUDIO[at.codec], 30) + end + C.seek(t, v, c, label, 0.5) + end + end +end +t:eq(C.open(byName["mjpeg_pcm.avi"].data).demuxer.meta.index, "idx1", "ffmpeg's AVI: idx1 used") +t:eq(C.open(byName["odml.avi"].data).demuxer.meta.index, "odml", "OpenDML indexes used") +t:eq(C.open(byName["idx1_only.avi"].data).demuxer.meta.index, "idx1", "idx1 used without OpenDML indexes") +t:eq(C.open(byName["no_index.avi"].data).demuxer.meta.index, "scan", "movi scanned without indexes") + +-- our muxer: MJPEG copied + PCM, read back packet for packet +do + local v = C.open(byName["mjpeg_pcm.avi"].data) + local out, err = F.save(v, nil, { format = "avi" }) + t:check(out ~= nil, "mux avi: " .. tostring(err)) + if out then + local v2 = F.video.open(out) + t:check(v2 ~= nil, "mux avi: reads back") + if v2 then + local a, b = v.demuxer, v2.demuxer + local same = a:count(1) == b:count(1) + for k = 1, a:count(1) do + local p, q = a:get(1, k), b:get(1, k) + if not q or buffer.tostring(p.data) ~= buffer.tostring(q.data) then + same = false + end + end + t:check(same, "mux avi: identical MJPEG packets") + t:eq(v2.frameRate, 10, "mux avi: frame rate") + C.audio(t, v2, byName["mjpeg_pcm.avi"], "mux avi", true) + end + end +end + +-- fuzz +local samples = {} +for _, n in { "mjpeg_pcm.avi", "mjpeg_ima.avi", "idx1_only.avi", "i420.avi" } do + local d = byName[n].data + table.insert(samples, string.sub(d, 1, math.min(#d, 40000))) +end +t:fuzz("open", C.fuzzOpen(AviFormat), samples, { mutations = 6, garbage = 100 }) +t:done() diff --git a/tests/video/encode.luau b/tests/video/encode.luau new file mode 100644 index 0000000..ef009a7 --- /dev/null +++ b/tests/video/encode.luau @@ -0,0 +1,116 @@ +-- video writer tests: files our muxers wrote (tools/fixtures/_video_encode.luau: WebM remux, MJPEG Matroska / AVI +-- copied and re-encoded from VP8 / MPEG-1, an animated GIF with uneven delays to AVI / Matroska / Y4M, WebM to Y4M) +-- were probed by ffprobe and decoded by ffmpeg at fixture time; here our demuxers must see the same packets, our +-- decoders the same frames (CRC for VP8 / raw, PSNR for MJPEG) and audio; the writers are rerun and must give the same +-- bytes. Fixtures: tools/fixtures/videoenc.py. +local T = require("@tests/T") +local C = require("@tests/video/_common") +local F = require("@formats") +local Fx = require("@tests/gen/videoenc_cases") +local Src = require("@tests/gen/videoenc_src") + +local t = T.suite("video encode") + +local byName = {} +for _, c in Fx do + byName[c.name] = c +end + +for _, c in Fx do + local label = c.name + if c.err then + t:note("%s: not written at fixture time: %s", label, c.err) + else + local v, err = C.open(c.data) + t:check(v ~= nil, label .. ": opens: " .. tostring(err)) + if v then + t:eq(#v.demuxer.tracks, #c.streams, label .. ": track count (ffprobe)") + -- (ffmpeg's AVI demuxer cuts PCM chunks into 1024-sample packets: AVI audio is compared decoded) + local avi = string.sub(label, -4) == ".avi" + C.packets(t, v.demuxer, c, label, { skipStream = function(_: any, tr: any): boolean + return avi and tr ~= nil and tr.kind == "audio" + end }) + C.frames(t, v, c, label, 40) + local at = v.demuxer:track("audio") + if at then + C.audio(t, v, c, label, string.sub(at.codec, 1, 4) == "pcm_", 30) + end + end + end +end + +-- the GIF (100 / 50 / 200 / 100 ms) at a constant 20 fps: 2 + 1 + 4 + 2 frames +do + local c = byName["gif.avi"] + if c and c.frames then + t:eq(#c.frames, 9, "gif.avi: 9 frames at 20 fps (ffmpeg)") + local v = C.open(c.data) + t:eq(v.frameRate, 20, "gif.avi: 20 fps") + end + local y = byName["gif.y4m"] + if y and y.frames then + t:eq(#y.frames, 9, "gif.y4m: 9 frames (ffmpeg)") + end + -- F.video.open on the GIF itself: a frames-backed video + local g = F.video.open(buffer.fromstring(Src.gif)) + t:check(g ~= nil and g.codec == "frames" and g.frames == 4, "F.video.open(gif): 4 frames") + if g then + local f1 = g:nextFrame() + local f2 = g:nextFrame() + t:check(f1 and f1.image.format == "rgba8" and f1.duration == 0.1 and f2 and f2.pts == 0.1 and f2.duration == 0.05, "gif frames: rgba8 with the GIF's times") + g:seek(0.2) + local f3 = g:nextFrame() + t:check(f3 ~= nil and f3.index == 3, "gif seek: frame 3 at 0.15 s holds 0.2 s") + end +end + +-- animated WebP through F.video.open: frames-backed, the canvases equal Pillow's (libwebp's WebPAnimDecoder) +do + local Crc32 = require("@formats/core/Crc32") + local Anims = require("@tests/gen/webp_anim") + for _, a in Anims do + local v = F.video.open(buffer.fromstring(a.data)) + t:check(v ~= nil and v.codec == "frames" and v.frames == #a.frames, a.name .. ": opens as a " .. #a.frames .. "-frame video") + if v then + local bad, n, t0 = 0, 0, 0 + while true do + local f = v:nextFrame() + if not f then + break + end + n += 1 + local px = f.image.pixels + if a.rgba == false then + px = buffer.create(buffer.len(f.image.pixels)) + buffer.copy(px, 0, f.image.pixels) + for i = 3, buffer.len(px) - 1, 4 do + buffer.writeu8(px, i, 255) + end + end + if Crc32.of(px) ~= a.frames[n].crc or math.abs(f.pts - t0) > 1e-6 then + bad += 1 + end + t0 += a.frames[n].ms / 1000 + end + t:check(n == #a.frames and bad == 0, a.name .. ": video frames equal Pillow's canvases and times (" .. bad .. " differ)") + end + end +end + +-- the writers are deterministic: the same bytes again +do + local Mkv = require("@tests/gen/mkv_cases") + local remux = byName["remux.webm"] + for _, m in Mkv do + if m.name == "vp8_opus.webm" and remux and remux.data then + local out = F.convert(buffer.fromstring(m.data), "webm") + t:check(out ~= nil and buffer.tostring(out) == remux.data, "remux.webm: written again byte for byte") + end + end + local gifAvi = byName["gif.avi"] + if gifAvi and gifAvi.data then + local out = F.convert(buffer.fromstring(Src.gif), "avi", { quality = 95 }) + t:check(out ~= nil and buffer.tostring(out) == gifAvi.data, "gif.avi: F.convert(gif, 'avi') again byte for byte") + end +end +t:done() diff --git a/tests/video/mkv.luau b/tests/video/mkv.luau new file mode 100644 index 0000000..560eb66 --- /dev/null +++ b/tests/video/mkv.luau @@ -0,0 +1,128 @@ +-- video/mkv tests: Matroska / WebM files from ffmpeg and mkvmerge (VP8 + Opus / Vorbis, MJPEG + PCM, MPEG-1 + MP2, +-- VP8 + FLAC, srt subtitles, Xiph / EBML / fixed lacing, zlib compression, unknown-size clusters, a truncated file): +-- tracks and every packet against ffprobe, frames against ffmpeg (bit-exact VP8, PSNR for MJPEG / MPEG-1), audio +-- through the api hook against ffmpeg, seeking, subtitles; our muxer's output (remux and MJPEG) read back. Fixtures: +-- tools/fixtures/mkv.py. +local T = require("@tests/T") +local C = require("@tests/video/_common") +local F = require("@formats") +local Mkv = require("@formats/video/mkv") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/mkv_cases") + +local t = T.suite("mkv") + +-- 1. contract +t:eq(Mkv.name, "mkv", "name") +t:eq(Mkv.category, "video", "category") +t:check(table.find(Mkv.extensions, "webm") ~= nil, "webm extension") + +local EXACT_AUDIO = { pcm_s16le = true, flac = true } +local byName = {} +for _, c in Fx do + byName[c.name] = c +end + +-- 2. every fixture +for _, c in Fx do + local label = c.name + t:check(Mkv.sniff(Bytes.reader(buffer.fromstring(c.data))) > 0, label .. ": sniff") + if c.truncated then + local v, err = C.open(c.data) + t:check(v ~= nil or err ~= nil, label .. ": opens or fails cleanly") + if v then + local n = 0 + while v:nextFrame() do + n += 1 + end + t:note("%s: %d frames before the cut", label, n) + end + else + local v, err = C.open(c.data) + t:check(v ~= nil, label .. ": open: " .. tostring(err)) + if v then + local dmx = v.demuxer + t:eq(#dmx.tracks, #c.streams, label .. ": track count") + for i, s in c.streams do + local tr = dmx.tracks[i] + if tr then + t:eq(tr.kind, s.kind, label .. ": track " .. i .. " kind") + if s.width then + t:check(tr.width == s.width and tr.height == s.height, label .. ": track " .. i .. " size") + end + if s.rate then + t:check(tr.sampleRate == s.rate and tr.channels == s.channels, label .. ": track " .. i .. " rate / channels") + end + end + end + -- Vorbis frames inside a lace carry no time of their own (ffmpeg derives them from the Vorbis block sizes) + C.packets(t, dmx, c, label, { noPts = c.name == "laced_vorbis.mkv" or c.name == "zlib_vorbis.mka" }) + C.frames(t, v, c, label) + local at = dmx:track("audio") + if at then + C.audio(t, v, c, label, EXACT_AUDIO[at.codec], if at.codec == "vorbis" then 20 else 30) + end + C.seek(t, v, c, label, 0.6) + end + end +end + +-- 3. specific files +do + local v = C.open(byName["vp8_opus.webm"].data) + t:eq(v.format, "webm", "webm: format") + t:eq(v.codec, "vp8", "webm: codec") + t:eq(v.width, 160, "webm: width") + t:check(math.abs(v.duration - 1) < 0.1, "webm: duration " .. v.duration) + t:check(#v.demuxer.meta.cues > 0, "webm: cues read") + local subs = Mkv.subtitles(C.open(byName["subs.mkv"].data).demuxer) + t:check(subs ~= nil and #subs.cues == 2, "subtitles: two cues") + if subs then + t:eq(subs.cues[1].text, "Hello", "subtitles: text") + t:check(math.abs(subs.cues[1].start - 0.1) < 0.002 and math.abs(subs.cues[1].stop - 0.5) < 0.002, "subtitles: times") + end + local lv = C.open(byName["lacing.mka"].data) + t:eq(lv.demuxer:count(1), 10, "lacing: 10 frames from three laced blocks") + local _, _, _, _, len = lv.demuxer:info(1, 4) + t:eq(len, 160, "lacing: EBML-laced frame size") +end + +-- 4. our muxer: remux WebM (VP8 + Opus copied) and read it back packet for packet +do + local src = byName["vp8_opus.webm"] + local v = C.open(src.data) + local out, err = F.save(v, nil, { format = "webm" }) + t:check(out ~= nil, "remux webm: " .. tostring(err)) + if out then + local v2 = F.video.open(out) + t:check(v2 ~= nil and v2.format == "webm", "remux webm: reads back as webm") + if v2 then + local a, b = v.demuxer, v2.demuxer + t:eq(#b.tracks, 2, "remux webm: two tracks") + local same = a:count(1) == b:count(1) and a:count(2) == b:count(2) + for k = 1, a:count(1) do + local p, q = a:get(1, k), b:get(1, k) + if not q or p.pts ~= q.pts or buffer.tostring(p.data) ~= buffer.tostring(q.data) or p.keyframe ~= q.keyframe then + same = false + end + end + t:check(same, "remux webm: identical video packets") + C.frames(t, v2, src, "remux webm") + C.audio(t, v2, src, "remux webm", false, 30) + end + end + local bad, berr = F.save(C.open(byName["mjpeg_pcm.mkv"].data), nil, { format = "webm" }) + t:check(bad == nil and berr ~= nil and berr.code == Err.UNSUPPORTED, "webm refuses MJPEG: " .. tostring(berr)) +end + +-- 5. errors and the fuzz pass +local e1 = select(2, Mkv.open(Bytes.reader(buffer.fromstring("\26\69\223\163\128")))) +t:check(e1 ~= nil, "empty EBML header fails") +local samples = {} +for _, n in { "vp8_opus.webm", "mjpeg_pcm.mkv", "lacing.mka", "zlib_vorbis.mka", "subs.mkv" } do + local d = byName[n].data + table.insert(samples, string.sub(d, 1, math.min(#d, 60000))) +end +t:fuzz("open", C.fuzzOpen(Mkv), samples, { mutations = 6, garbage = 100 }) +t:done() diff --git a/tests/video/mp4.luau b/tests/video/mp4.luau new file mode 100644 index 0000000..9ff4d7a --- /dev/null +++ b/tests/video/mp4.luau @@ -0,0 +1,74 @@ +-- video/mp4 tests: MP4 / MOV files from ffmpeg (MJPEG + AAC / PCM / FLAC / MP2, H.264 with B-frames and edit lists + +-- AAC, fragmented MP4, MPEG-1 + Opus): tracks and every packet against ffprobe (pts moved by the edit lists, as ffmpeg), +-- frames against ffmpeg (PSNR), audio through the api hook (AAC priming dropped), seeking, our MP4 / MOV writer read +-- back, fuzz. Fixtures: tools/fixtures/mp4.py. +local T = require("@tests/T") +local C = require("@tests/video/_common") +local F = require("@formats") +local Mp4 = require("@formats/video/mp4") +local Bytes = require("@formats/core/Bytes") +local Fx = require("@tests/gen/mp4_cases") + +local t = T.suite("mp4") +t:eq(Mp4.name, "mp4", "name") + +local EXACT_AUDIO = { pcm_s16le = true, flac = true } +local byName = {} +for _, c in Fx do + byName[c.name] = c +end + +for _, c in Fx do + local label = c.name + t:check(Mp4.sniff(Bytes.reader(buffer.fromstring(c.data))) >= 0.6, label .. ": sniff") + local v, err = C.open(c.data) + t:check(v ~= nil, label .. ": open " .. tostring(err)) + if v then + local dmx = v.demuxer + t:eq(#dmx.tracks, #c.streams, label .. ": track count") + C.packets(t, dmx, c, label) + C.frames(t, v, c, label, 38) + local at = dmx:track("audio") + if at then + C.audio(t, v, c, label, EXACT_AUDIO[at.codec], 30) + end + C.seek(t, v, c, label, 0.5) + end +end + +-- our writer: MP4 (MJPEG + AAC copied) and MOV (MJPEG + PCM) read back packet for packet +for _, job in { { "mjpeg_aac.mp4", "mp4" }, { "mjpeg_pcm.mov", "mov" }, { "h264_aac.mp4", "mp4" } } do + local src = byName[job[1]] + local v = C.open(src.data) + local out, err = F.save(v, nil, { format = job[2] }) + t:check(out ~= nil, "write " .. job[2] .. " from " .. job[1] .. ": " .. tostring(err)) + if out then + local v2 = F.video.open(out) + t:check(v2 ~= nil, "write " .. job[1] .. ": reads back") + if v2 then + local a, b = v.demuxer, v2.demuxer + local same = #a.tracks == #b.tracks + for i, tr in a.tracks do + local tr2 = b.tracks[i] + if not tr2 or a:count(tr.id) ~= b:count(tr2.id) then + same = false + else + for k = 1, a:count(tr.id) do + local p, q = a:get(tr.id, k), b:get(tr2.id, k) + if not q or buffer.tostring(p.data) ~= buffer.tostring(q.data) or math.abs(p.pts / tr.timescale - q.pts / tr2.timescale) > 0.002 then + same = false + end + end + end + end + t:check(same, "write " .. job[1] .. ": same packets and times") + end + end +end + +local samples = {} +for _, n in { "mjpeg_aac.mp4", "fragmented.mp4", "h264_aac.mp4" } do + table.insert(samples, string.sub(byName[n].data, 1, 30000)) +end +t:fuzz("open", C.fuzzOpen(Mp4), samples, { mutations = 6, garbage = 100 }) +t:done() diff --git a/tests/video/mpegps.luau b/tests/video/mpegps.luau new file mode 100644 index 0000000..2a4317b --- /dev/null +++ b/tests/video/mpegps.luau @@ -0,0 +1,48 @@ +-- video/mpegps tests: program streams from ffmpeg (MPEG-1 system stream, B-frames, MPEG-2 PS / VOB packs, a raw .m1v +-- elementary stream): tracks, picture packets (count and timestamps against ffmpeg's frames), frames against ffmpeg +-- (PSNR) once an MPEG-1 decoder is registered, audio through the api hook (SNR), seeking, fuzz. Fixtures: +-- tools/fixtures/mpegts.py. +local T = require("@tests/T") +local C = require("@tests/video/_common") +local Ps = require("@formats/video/mpegps") +local Bytes = require("@formats/core/Bytes") +local Fx = require("@tests/gen/mpegps_cases") + +local t = T.suite("mpegps") +t:eq(Ps.name, "mpegps", "name") + +for _, c in Fx do + local label = c.name + t:check(Ps.sniff(Bytes.reader(buffer.fromstring(c.data))) > 0, label .. ": sniff") + local v, err = C.open(c.data) + t:check(v ~= nil, label .. ": open " .. tostring(err)) + if v then + local dmx = v.demuxer + local vt = dmx:track("video") + t:check(vt ~= nil and vt.codec == "mpeg1", label .. ": an MPEG-1 video track") + t:eq(dmx:count(vt.id), #c.frames, label .. ": one packet per picture") + -- presentation times: one per frame slot + local seen, ok = {}, true + for k = 1, dmx:count(vt.id) do + local pts = dmx:info(vt.id, k) + local slot = math.floor((pts - dmx:info(vt.id, 1)) / 3600 + 0.5) + if seen[slot] then + ok = false + end + seen[slot] = true + end + t:check(ok, label .. ": distinct presentation times") + C.frames(t, v, c, label, 36) + if dmx:track("audio") then + C.audio(t, v, c, label, false, 30) + end + C.seek(t, v, c, label, 0.5) + end +end + +local samples = {} +for _, c in Fx do + table.insert(samples, string.sub(c.data, 1, 30000)) +end +t:fuzz("open", C.fuzzOpen(Ps), samples, { mutations = 6, garbage = 100 }) +t:done() diff --git a/tests/video/mpegts.luau b/tests/video/mpegts.luau new file mode 100644 index 0000000..534f154 --- /dev/null +++ b/tests/video/mpegts.luau @@ -0,0 +1,64 @@ +-- video/mpegts tests: transport streams from ffmpeg (MPEG-1 + MP2, B-frames, H.264 + AAC, M2TS, garbage before the +-- first packet, a truncated file): tracks and the video packets against ffprobe (time, size, CRC, keyframe), frames +-- against ffmpeg (PSNR) once an MPEG-1 decoder is registered, audio through the api hook (SNR), seeking, fuzz. +-- Fixtures: tools/fixtures/mpegts.py. +local T = require("@tests/T") +local C = require("@tests/video/_common") +local Ts = require("@formats/video/mpegts") +local Bytes = require("@formats/core/Bytes") +local Fx = require("@tests/gen/mpegts_cases") + +local t = T.suite("mpegts") +t:eq(Ts.name, "mpegts", "name") + +local byName = {} +for _, c in Fx do + byName[c.name] = c +end + +local function audioStream(want: any, tr: any): boolean + return tr == nil or tr.kind ~= "video" -- ffmpeg's parser re-splits PES audio into frames +end + +for _, c in Fx do + local label = c.name + local v, err = C.open(c.data) + if c.truncated then + t:check(v ~= nil or err ~= nil, label .. ": opens or fails cleanly") + else + t:check(Ts.sniff(Bytes.reader(buffer.fromstring(c.data))) > 0 or label == "garbage.ts", label .. ": sniff") + t:check(v ~= nil, label .. ": open " .. tostring(err)) + if v then + local dmx = v.demuxer + t:eq(#dmx.tracks, #c.streams, label .. ": track count") + for i, s in c.streams do + local tr = dmx.tracks[i] + t:check(tr ~= nil and tr.kind == s.kind, label .. ": track " .. i .. " kind") + if tr and s.width and tr.width then -- (H.264 sizes come from its SPS, read by the codec) + t:check(tr.width == s.width and tr.height == s.height, label .. ": track " .. i .. " size") + end + end + if c.packets then + C.packets(t, dmx, c, label, { skipStream = audioStream }) + end + C.frames(t, v, c, label, 36) + if dmx:track("audio") then + C.audio(t, v, c, label, false, 30) + end + C.seek(t, v, c, label, 0.5) + end + end +end +do + local v = C.open(byName["mpeg1_mp2.ts"].data) + t:eq(v.codec, "mpeg1", "stream type 0x02 without a sequence extension is MPEG-1") + t:eq(v.demuxer.tracks[2].codec, "mp2", "MPEG audio layer II") + t:eq(C.open(byName["h264_aac.ts"].data).codec, "h264", "H.264 track") +end + +local samples = {} +for _, n in { "mpeg1_mp2.ts", "bframes.ts", "h264_aac.ts" } do + table.insert(samples, string.sub(byName[n].data, 1, 188 * 120)) +end +t:fuzz("open", C.fuzzOpen(Ts), samples, { mutations = 6, garbage = 100 }) +t:done() diff --git a/tests/video/y4m.luau b/tests/video/y4m.luau new file mode 100644 index 0000000..712c56d --- /dev/null +++ b/tests/video/y4m.luau @@ -0,0 +1,103 @@ +-- video/y4m tests: YUV4MPEG2 streams from ffmpeg (C420jpeg at an odd size, C420mpeg2, C422, C444, Cmono, C420p10) +-- against ffmpeg's yuv420p decode (bit-exact for 4:2:0 8-bit, PSNR for the converted layouts), the header fields, +-- our writer round trip (and from an rgba frames-backed video), errors and the fuzz pass. Fixtures: +-- tools/fixtures/y4m.py. +local T = require("@tests/T") +local C = require("@tests/video/_common") +local F = require("@formats") +local Y4m = require("@formats/video/y4m") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Fx = require("@tests/gen/y4m_cases") + +local t = T.suite("y4m") +t:eq(Y4m.name, "y4m", "name") + +for _, c in Fx do + local label = c.name + t:check(Y4m.sniff(Bytes.reader(buffer.fromstring(c.data))) == 1, label .. ": sniff") + local v, err = Y4m.open(Bytes.reader(buffer.fromstring(c.data))) + t:check(v ~= nil, label .. ": open " .. tostring(err)) + if v then + t:check(v.width == c.width and v.height == c.height, label .. ": size") + t:check(math.abs(v.frameRate - c.rate[1] / c.rate[2]) < 1e-9, label .. ": frame rate") + local n, bad, worst = 0, 0, math.huge + while true do + local f = v:nextFrame() + if not f then + break + end + n += 1 + if c.exact then + if Crc32.of(f.image.pixels) ~= c.frames[n] then + bad += 1 + end + elseif c.yuv[n] then + worst = math.min(worst, C.psnr(f.image.pixels, buffer.fromstring(c.yuv[n]))) + end + end + t:eq(n, #c.frames, label .. ": frame count") + if c.exact then + t:check(bad == 0, label .. ": frames bit-exact with ffmpeg") + else + t:check(worst > 30, string.format("%s: PSNR vs ffmpeg %.1f dB", label, worst)) + end + end +end + +-- writer: a y4m stream back to y4m is byte-identical in its frames; header as ffmpeg writes it +do + local c = Fx[1] + local v = F.video.open(buffer.fromstring(c.data)) + local out, err = F.save(v, nil, { format = "y4m" }) + t:check(out ~= nil, "write: " .. tostring(err)) + if out then + local s = buffer.tostring(out) + t:check(string.find(s, "YUV4MPEG2 W173 H95 F30000:1001 Ip A1:1 C420jpeg XYSCSS=420JPEG\n", 1, true) == 1, "write: header " .. string.sub(s, 1, 60)) + local v2 = Y4m.open(Bytes.reader(out)) + local n, same = 0, true + while true do + local f = v2:nextFrame() + if not f then + break + end + n += 1 + same = same and Crc32.of(f.image.pixels) == c.frames[n] + end + t:check(n == #c.frames and same, "write: frames round trip") + end + -- an rgba frames-backed video (a 2-frame animation) to y4m + local a = Types.Image.new(4, 2) + buffer.fill(a.pixels, 0, 255) + local b = Types.Image.new(4, 2) + a.frames = { { image = a, delay = 0.5, x = 0, y = 0, dispose = "none", blend = "source" }, { image = b, delay = 0.5, x = 0, y = 0, dispose = "none", blend = "source" } } + local y, yerr = F.save(a, nil, { format = "y4m" }) + t:check(y ~= nil, "write from frames: " .. tostring(yerr)) + if y then + local v3 = Y4m.open(Bytes.reader(y)) + local f1 = v3:nextFrame() + local f2 = v3:nextFrame() + t:check(f1 ~= nil and f2 ~= nil and v3:nextFrame() == nil, "write from frames: 2 frames") + t:eq(v3.frameRate, 2, "write from frames: frame rate from the delays") + t:eq(buffer.readu8(f1.image.pixels, 0), 235, "write from frames: white -> Y 235 (limited range)") + t:eq(buffer.readu8(f2.image.pixels, 0), 16, "write from frames: black -> Y 16") + end +end + +-- errors +local function code(s: string): string? + local _, e = Y4m.open(Bytes.reader(buffer.fromstring(s))) + return e and e.code +end +t:eq(code("YUV4MPEG2 W0 H0\n"), Err.CORRUPT, "zero size") +t:eq(code("YUV4MPEG2 W16 H16 Cfoo\n"), Err.UNSUPPORTED, "unknown colour space") +t:eq(code("YUV4MPEG2 W99999999 H99999 C420\n"), Err.CORRUPT, "huge size") +t:eq(code("YUV4MPEG2 W16 H16"), Err.TRUNCATED, "no header end") +local samples = {} +for _, c in Fx do + table.insert(samples, string.sub(c.data, 1, 30000)) +end +t:fuzz("open", C.fuzzOpen(Y4m), samples, { mutations = 6, garbage = 100 }) +t:done() diff --git a/tools/bench.luau b/tools/bench.luau index 237989e..827e4a8 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -90,6 +90,16 @@ for _, c in { { "celt 128k", OpusCelt }, { "silk wb", OpusSilk }, { "hybrid", Op Opus.decode(Bytes.reader(b)) end) end +-- vorbis (ws-audio): 10 s of 44.1 kHz stereo music at oggenc -q 5 (tools/fixtures/vorbis.py) +do + local Vorbis = require("@formats/audio/vorbis") + local VB = require("@tests/gen/vorbis_bench") + local b = buffer.fromstring(VB.data) + local dt = bench("vorbis decode q5 (10 s st)", 3, VB.frames * VB.channels * 4, function() + Vorbis.decode(Bytes.reader(b)) + end) + print(string.format("%-8s %-30s %8.0fx real time", runtime, "", VB.frames / VB.rate / dt)) +end for _, name in { "s16_long", "s24_96k" } do for _, c in FC do if c.name == name then @@ -116,6 +126,55 @@ do Wav.decode(Bytes.reader(file)) end) end +-- flac encode (ws-audio): 10 s of 44.1 kHz stereo 16-bit (a synthetic two-tone signal with noise) +do + local Fl = require("@formats/audio/flac") + local n = 441000 + local a = Types.Audio.new(44100, 2, n) + local seed = 1 + for i = 0, n - 1 do + seed = (seed * 1103515245 + 12345) % 2147483648 + local noise = (seed / 2147483648 - 0.5) * 0.01 + buffer.writef32(a.samples, i * 8, math.floor((math.sin(i * 0.031) * 0.4 + math.sin(i * 0.21) * 0.1 + noise) * 32768) / 32768) + buffer.writef32(a.samples, i * 8 + 4, math.floor((math.sin(i * 0.017) * 0.3 + noise) * 32768) / 32768) + end + for _, level in { 0, 5, 8 } do + local dt = bench("flac encode -" .. level .. " (10 s st 16)", 2, n * 4, function() + Fl.encode(a, { level = level }) + end) + print(string.format("%-8s %-30s %8.0fx real time", runtime, "", 10 / dt)) + end +end +-- mp3 / mp2 encode (ws-audio): 10 s of 44.1 kHz stereo tones +do + local M3 = require("@formats/audio/mp3") + local n = 441000 + local a = Types.Audio.new(44100, 2, n) + for i = 0, n - 1 do + buffer.writef32(a.samples, i * 8, math.sin(i * 0.031) * 0.4 + math.sin(i * 0.21) * 0.1) + buffer.writef32(a.samples, i * 8 + 4, math.sin(i * 0.017) * 0.3) + end + for _, cfg in { { layer = 3, bitrate = 128 }, { layer = 2, bitrate = 192 } } do + local dt = bench(string.format("mp%d encode %d kbps (10 s st)", cfg.layer, cfg.bitrate), 2, n * 8, function() + M3.encode(a, cfg) + end) + print(string.format("%-8s %-30s %8.1fx real time", runtime, "", 10 / dt)) + end +end +-- vorbis encode (ws-audio): 10 s of 44.1 kHz stereo tones at quality 3 +do + local Vb = require("@formats/audio/vorbis") + local n = 441000 + local a = Types.Audio.new(44100, 2, n) + for i = 0, n - 1 do + buffer.writef32(a.samples, i * 8, math.sin(i * 0.031) * 0.4 + math.sin(i * 0.21) * 0.1) + buffer.writef32(a.samples, i * 8 + 4, math.sin(i * 0.017) * 0.3) + end + local dt = bench("vorbis encode q3 (10 s st)", 2, n * 8, function() + Vb.encode(a, { quality = 3 }) + end) + print(string.format("%-8s %-30s %8.1fx real time", runtime, "", 10 / dt)) +end do local Json = require("@formats/codecs/Json") local JB = require("@tests/gen/json_bench") @@ -536,14 +595,335 @@ do end) end do - -- H.264: frames per second over whole streams (decode + output copies); MB/s of yuv420p output + local Xml = require("@formats/codecs/Xml") + local XB = require("@tests/gen/xml_bench") + local doc = assert(Xml.decode(XB.text)) + bench("xml decode (DOM)", 5, #XB.text, function() + Xml.decode(XB.text) + end) + bench("xml events", 5, #XB.text, function() + for _ in Xml.events(XB.text) do + end + end) + bench("xml encode", 5, #XB.text, function() + Xml.encode(doc) + end) +end + +-- ws-m4a: AAC-LC / ALAC decode and ALAC encode (MB/s of 16-bit PCM equivalent: frames * channels * 2), MDCT +do + local M4a = require("@formats/audio/m4a") + local Alac = require("@formats/codecs/Alac") + local Mdct = require("@formats/codecs/Mdct") + local MA = require("@tests/gen/m4a_aac") + local ML = require("@tests/gen/m4a_alac") + local aac = buffer.fromstring(MA[1].data) + local a = assert(M4a.decode(Bytes.reader(aac))) + bench("aac-lc decode (m4a, stereo)", 3, a.frames * a.channels * 2, function() + M4a.decode(Bytes.reader(aac)) + end) + local alac = buffer.fromstring(ML[1].data) + local l = assert(M4a.decode(Bytes.reader(alac))) + bench("alac decode (m4a, stereo 16)", 3, l.frames * l.channels * 2, function() + M4a.decode(Bytes.reader(alac)) + end) + local enc = assert(Alac.encoder({ sampleRate = 44100, channels = 2, bitDepth = 16 })) + local ints = table.create(a.frames * 2, 0) + for i = 1, a.frames * 2 do + ints[i] = math.floor(buffer.readf32(a.samples, (i - 1) * 4) * 32767) + end + bench("alac encode (stereo 16)", 2, a.frames * 2 * 2, function() + local f = 0 + while f < a.frames do + local n = math.min(4096, a.frames - f) + enc:encode(ints, f * 2 + 1, n) + f += n + end + end) + local plan = assert(Mdct.new(2048)) + local x, X = table.create(2048, 0.5), table.create(1024, 0) + bench("mdct 2048 x 1000 (forward)", 3, 1000 * 2048 * 4, function() + for _ = 1, 1000 do + Mdct.forward(plan, x, 1, X, 1) + end + end) +end +do + local Opus = require("@formats/audio/opus") + local Cases = require("@tests/audio/_opus_cases") + local c = Cases.list[2] + local a = Cases.signal(c) + local dt = bench("opus celt encode 128k (1.5 s st)", 2, a.frames * a.channels * 2, function() + Opus.encode(a, { bitrate = 128000 }) + end) + local _ = dt +end + +-- MIDI through the SoundFont synth (tools/fixtures/sf2.py's test song; tools/fixtures/midi.py's "song" through the +-- built-in waveform set): seconds of stereo 44.1 kHz audio rendered per second of CPU +do + local Midi = require("@formats/music/midi") + local Sf2 = require("@formats/music/sf2") + local SF = require("@tests/gen/sf2_cases") + local MC = require("@tests/gen/midi_cases") + local sf = assert(Sf2.decode(Bytes.reader(buffer.fromstring(SF.sf2)))) + local function realtime(label: string, data: string, font: any) + local song = assert(Midi.decode(Bytes.reader(buffer.fromstring(data)))) + local best = math.huge + local frames = 0 + for _ = 1, 3 do + local dec = assert(Midi.render(song, { soundfont = font, tail = 0 })) + local out = buffer.create(4096 * 8) + local t0 = os.clock() + frames = 0 + while true do + local _, n = dec:read(4096, out) + if n == 0 then + break + end + frames += n + end + best = math.min(best, os.clock() - t0) + end + print(string.format("%-8s %-30s %8.2f ms %7.1f x realtime", runtime, label, best * 1000, frames / 44100 / best)) + end + realtime("midi render sf2 (test song)", SF.song, sf) + for _, c in MC do + if c.name == "song" then + realtime("midi render fallback", c.data, nil) + end + end +end +-- the synth's per-voice cost: 32 sustained, filtered, looped voices (sf2 saw preset with a mod env) for 2 s +do + local SoundFont = require("@formats/codecs/SoundFont") + local Sf2 = require("@formats/music/sf2") + local SF = require("@tests/gen/sf2_cases") + local sf = assert(Sf2.decode(Bytes.reader(buffer.fromstring(SF.sf2)))) + local frames = 88200 + local out = buffer.create(frames * 8) + local best = math.huge + for _ = 1, 3 do + local s = SoundFont.synth(sf, 44100) + SoundFont.Synth.midi(s, 0xC0, 1, 0) + for k = 0, 31 do + SoundFont.Synth.midi(s, 0x90, 40 + k, 100) + end + buffer.fill(out, 0, 0) + local t0 = os.clock() + for f = 0, frames - 1, 1024 do + SoundFont.Synth.render(s, out, f, 1024) + end + best = math.min(best, os.clock() - t0) + end + print(string.format("%-8s %-30s %8.2f ms %7.1f M voice-samples/s", runtime, "synth 32 voices x 2 s", best * 1000, 32 * frames / best / 1e6)) +end +-- the tracker engine: 32 channels of looped samples (one note each, linear interpolation, volume ramps), and an +-- IT-style module with background voices (NNA continue) and resonant filters on every channel +do + local Tracker = require("@formats/codecs/Tracker") + local function song(format: string, filter: boolean): any + local m = Tracker.newModule(format, 32) + m.order = { 0 } + m.patterns[1] = Tracker.newPattern(64, 32) + local s = Tracker.newSample("saw") + s.length = 1000 + s.data = buffer.create(4000) + for i = 0, 999 do + buffer.writef32(s.data, i * 4, (i % 100) / 50 - 1) + end + s.loopStart, s.loopEnd, s.loopType = 0, 1000, 1 + m.samples[1] = s + if format == "it" then + local ins = Tracker.newInstrument("nna") + for n = 1, 120 do + ins.sampleMap[n] = 1 + end + ins.nna = 1 + ins.fadeout = 64 + if filter then + ins.cutoff, ins.resonance = 60, 40 + end + m.instruments[1] = ins + end + for ch = 1, 32 do + for row = 0, 63, 16 do + Tracker.setCell(m, 0, row, ch, 37 + ch + row // 16, 1, 0, 0, 0) + end + end + return m + end + local function realtime(label: string, m: any, voices: number) + local best, frames = math.huge, 0 + local out = buffer.create(4096 * 8) + for _ = 1, 3 do + local dec = Tracker.render(m) :: any + frames = 0 + local t0 = os.clock() + while true do + local _, n = dec:read(4096, out) + if n == 0 then + break + end + frames += n + end + best = math.min(best, os.clock() - t0) + end + print(string.format("%-8s %-30s %8.2f ms %7.1f x realtime %5.1f M voice-samples/s", runtime, label, best * 1000, frames / 44100 / best, voices * frames / best / 1e6)) + end + realtime("tracker 32 ch (mod)", song("mod", false), 32) + realtime("tracker 32 ch + NNA, filters", song("it", true), 64) +end +-- ------------------------------------------------------------------------------------------- ws-video-codecs: fps +do + local Jpeg = require("@formats/codecs/Jpeg") + local Mpeg1 = require("@formats/codecs/Mpeg1") + local Base64 = require("@formats/core/Base64") + local Types = require("@formats/Types") + local MB = require("@tests/gen/mjpeg_bench") + local M1 = require("@tests/gen/mpeg1_bench") + -- best of n runs of f (which handles `frames` frames): ms per frame and frames per second + local function fps(label: string, n: number, frames: number, f: () -> ()) + f() + local dt = math.huge + for _ = 1, n do + local t0 = os.clock() + f() + dt = math.min(dt, os.clock() - t0) + end + print(string.format("%-8s %-30s %8.2f ms %7.1f fps", runtime, label, dt * 1000 / frames, frames / dt)) + end + for _, c in MB.frames do + local b = Base64.decode(c.data) :: buffer + local img = assert(Jpeg.decode(b, 0, nil, { yuv = true })) + assert(Crc32.of(img.pixels) == c.yuv, "mjpeg bench: " .. c.name .. " does not match TurboJPEG") + fps("mjpeg decode yuv " .. c.name, 10, 1, function() + Jpeg.decode(b, 0, nil, { yuv = true }) + end) + fps("mjpeg decode rgba " .. c.name, 10, 1, function() + Jpeg.decode(b) + end) + end + for _, s in MB.sources do + local img = Types.Image.new(s.width, s.height, "yuv420p") + img.pixels = assert(Deflate.zlib(Base64.decode(s.yuv) :: buffer)) + fps(string.format("mjpeg encode yuv %dx%d q85", s.width, s.height), 5, 1, function() + Jpeg.encode(img, { quality = 85 }) + end) + end + for _, s in M1 do + local file = Base64.decode(s.file) :: buffer + for _, rgba in { false, true } do + fps(string.format("mpeg1 decode %s %dx%d", if rgba then "rgba" else "yuv", s.width, s.height), 3, #s.units, function() + local dec = Mpeg1.new({ reorder = true, rgba = rgba }) + for i, u in s.units do + dec:decode(file, u[1], u[2], i) + end + while dec:flush() do + end + end) + end + end +end +-- ------------------------------------------------------------------------------------------- ws-video: containers +do + local F = require("@formats") + local VB = require("@tests/gen/videobench") + local function clock(n: number, f: () -> number): (number, number) + local frames = f() + local dt = math.huge + for _ = 1, n do + local t0 = os.clock() + frames = f() + dt = math.min(dt, os.clock() - t0) + end + return dt, frames + end + for _, c in VB do + local data = buffer.fromstring(c.data) + local dtOpen = clock(3, function(): number + F.video.open(data, { audio = false }) + return 1 + end) + for _, rgba in { false, true } do + local ok, dt, frames = pcall(clock, 2, function(): number + local v = assert(F.video.open(data, { audio = false, rgba = rgba })) + local n = 0 + while true do + local f, err = v:nextFrame() + if not f then + assert(err == nil, tostring(err)) + break + end + n += 1 + end + return n + end) + if ok then + print(string.format("%-8s %-30s %8.2f ms %7.1f fps (open %.1f ms)", runtime, string.format("video %s %s %s", c.size, c.name, if rgba then "rgba" else "yuv"), dt * 1000 / frames, frames / dt, dtOpen * 1000)) + else + print(string.format("%-8s %-30s %s", runtime, "video " .. c.size .. " " .. c.name, tostring(dt))) + end + end + if c.name == "raw.y4m" then + local dt, frames = clock(2, function(): number + assert(F.convert(data, "avi", { quality = 85 })) + return 8 + end) + print(string.format("%-8s %-30s %8.2f ms %7.1f fps", runtime, "video " .. c.size .. " y4m -> mjpeg avi", dt * 1000 / frames, frames / dt)) + end + end +end +-- ------------------------------------------------------------------------------------------- ws-video-vp8: fps +do + -- VP8 video (codecs/Vp8, tools/fixtures/vp8video.py): whole IVF streams (libvpx, panning testsrc2) through one + -- decoder object; frames per second. On LuaJIT the library's host module raises the trace limits (maxtrace=8000, + -- see src/Formats/host/init.luau): the second pair of lines runs with them, as the api does. + local Vp8 = require("@formats/codecs/Vp8") + local VB = require("@tests/gen/vp8video_bench") + local function run(tag: string) + for _, c in VB do + local b = buffer.fromstring(c.ivf) + local frames = {} + local p = 32 + while p + 12 <= buffer.len(b) do + local n = buffer.readu32(b, p) + table.insert(frames, { p + 12, n }) + p += 12 + n + end + local dt = bench(string.format("vp8 decode %dx%d%s", c.width, c.height, tag), 3, c.width * c.height * 1.5 * #frames, function() + local dec = Vp8.newDecoder() + for _, f in frames do + dec:decodeFrame(b, f[1], f[2]) + end + end) + print(string.format("%-8s %-30s %8.1f fps", runtime, " (" .. #frames .. " frames)", #frames / dt)) + end + end + run("") + if runtime == "luajit" then + require("@formats/host") + run(" (jit tuned)") + end +end +do + -- H.264 (codecs/H264): whole Annex B streams, frames per second (decode + the cropped yuv420p output copies). The + -- testsrc2 clips are easy (mostly static); the mandelbrot zooms move everywhere. LuaJIT runs twice: with its default + -- trace limits and with the ones host/init.luau sets (maxtrace=8000, maxmcode=65536). local H264 = require("@formats/codecs/H264") local HB = require("@tests/gen/h264_bench") - for _, c in HB do - local n = c.width * c.height * 3 // 2 * #c.frames - local dt = bench("h264 " .. c.name .. " " .. #c.frames .. "f", 2, n, function() - H264.decodeAll(c.data) - end) - print(string.format("%-8s h264 %s: %.1f fps at %dx%d", runtime, c.name, #c.frames / dt, c.width, c.height)) + local function run(tag: string) + for _, c in HB do + local n = c.width * c.height * 3 // 2 * #c.frames + local dt = bench(string.format("h264 %s %dx%d%s", c.name, c.width, c.height, tag), 3, n, function() + H264.decodeAll(c.data) + end) + print(string.format("%-8s %-30s %8.1f fps", runtime, " (" .. #c.frames .. " frames)", #c.frames / dt)) + end + end + run("") + if runtime == "luajit" then + require("@formats/host") + run(" (jit tuned)") end end diff --git a/tools/fixtures/_audio.py b/tools/fixtures/_audio.py new file mode 100644 index 0000000..566ce86 --- /dev/null +++ b/tools/fixtures/_audio.py @@ -0,0 +1,334 @@ +# Shared helpers for the audio fixture generators (aiff, au, voc, vorbis, flac encoder, mp3 / mp2 encoders): +# A = _audio.load() in a generator: import this file (generators are loaded by path, not as a package) +# A.signal(kind, rate, ch, frames) deterministic test signals -> list of float frames-interleaved samples +# A.f32le(samples) / A.from_f32le(b) float list <-> raw little-endian f32 bytes +# A.wav(samples, rate, ch, bits=16) a WAV file (PCM 8/16/24/32 or float 32) for reference tools to read +# A.ffdecode(ctx, data, fmt=None) decode any file with ffmpeg -> (rate, ch, floats) +# A.tool(ctx, pkg, argv, data, ext) run a nix reference tool on a temp input file, return its stdout +# A.snr(ref, test, ch, max_lag=0) SNR in dB of test against ref (searching an alignment lag up to max_lag frames, +# either direction), and the lag found +# A.luau(ctx, code) run Luau code (luau --codegen -O2 from the repo root, the .luaurc aliases +# apply) and return its stdout bytes. Encoder fixtures use it to encode with our +# encoder in the fixture step, then decode the output with the reference tool: +# print(buffer.tostring(buf)) writes the raw bytes (plus one newline, stripped). +import array, math, os, random, shutil, struct, subprocess, sys, tempfile, importlib.util + +ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + + +def load(): + return sys.modules[__name__] + + +def signal(kind, rate, ch, frames, seed=1): + """kinds: sine (440 Hz + 1 kHz per channel), sweep (50 Hz .. rate/2.2 log sweep), noise (white, -12 dBFS), + music (a few harmonic notes with an envelope + a little noise), silence, square (aliased square, a stress test), + loud (a full-scale sine near clipping).""" + rng = random.Random(seed) + out = [0.0] * (frames * ch) + for c in range(ch): + ph = 0.0 + notes = [(220.0 * 2 ** (rng.randrange(0, 24) / 12.0), rng.random() * 0.25 + 0.05) for _ in range(4)] + for i in range(frames): + t = i / rate + if kind == "sine": + v = 0.5 * math.sin(2 * math.pi * (440 + 110 * c) * t) + 0.2 * math.sin(2 * math.pi * 1000 * t + c) + elif kind == "sweep": + f0, f1 = 50.0, rate / 2.2 + dur = frames / rate + f = f0 * (f1 / f0) ** (t / dur) + ph += 2 * math.pi * f / rate + v = 0.6 * math.sin(ph + c) + elif kind == "noise": + v = (rng.random() * 2 - 1) * 0.25 + elif kind == "music": + v = 0.0 + for k, (f, a) in enumerate(notes): + seg = (i // max(1, rate // 4) + k) % 4 + env = math.exp(-3.0 * ((i % max(1, rate // 4)) / rate)) + if seg != 3: + v += a * env * (math.sin(2 * math.pi * f * t) + 0.3 * math.sin(4 * math.pi * f * t) + 0.1 * math.sin(6 * math.pi * f * t)) + v += (rng.random() * 2 - 1) * 0.01 + elif kind == "silence": + v = 0.0 + elif kind == "square": + v = 0.4 if math.sin(2 * math.pi * (300 + 50 * c) * t) >= 0 else -0.4 + elif kind == "loud": + v = 0.98 * math.sin(2 * math.pi * 330 * t + c) + else: + raise ValueError(kind) + out[i * ch + c] = v + return out + + +def quantize(samples, bits): + s = 2 ** (bits - 1) + return [max(-s, min(s - 1, int(math.floor(v * s + 0.5)))) / s for v in samples] + + +def f32le(samples): + a = array.array("f", samples) + if sys.byteorder != "little": + a.byteswap() + return a.tobytes() + + +def from_f32le(b): + a = array.array("f") + a.frombytes(b[: len(b) // 4 * 4]) + if sys.byteorder != "little": + a.byteswap() + return a.tolist() + + +def wav(samples, rate, ch, bits=16, float_=False): + n = len(samples) // ch + if float_: + data = f32le(samples) + fmt = struct.pack("= 10: + return got + best = (-1e9, 0) + nref, ntest = len(ref) // ch, len(test) // ch + lags = range(-max_lag, max_lag + 1) if max_lag else [0] + if max_lag > 64: + # coarse cross-correlation on the first channel to find candidate lags, then refine + cands = [] + m = min(nref, 1 << 15) + seg = [ref[i * ch] for i in range(skip, min(nref, skip + m))] + for lag in range(-max_lag, max_lag + 1): + acc = 0.0 + for i in range(0, len(seg), 7): + j = skip + i + lag + if 0 <= j < ntest: + acc += seg[i] * test[j * ch] + cands.append((acc, lag)) + cands.sort(reverse=True) + lags = sorted(set(l for _, l in cands[:3])) + for lag in lags: + sig = err = 0.0 + for i in range(skip, nref): + j = i + lag + if j < 0 or j >= ntest: + continue + for c in range(ch): + a = ref[i * ch + c] + e = a - test[j * ch + c] + sig += a * a + err += e * e + s = 200.0 if err == 0 else (10 * math.log10(sig / err) if sig > 0 else -200.0) + if s > best[0]: + best = (s, lag) + return best + + +def _snr_at(ref, test, ch, lag, skip): + sig = err = 0.0 + nref, ntest = len(ref) // ch, len(test) // ch + for i in range(skip, nref): + j = i + lag + if 0 <= j < ntest: + for c in range(ch): + a = ref[i * ch + c] + e = a - test[j * ch + c] + sig += a * a + err += e * e + return (200.0 if err == 0 else (10 * math.log10(sig / err) if sig > 0 else -200.0), lag) + + +def luau_bin(): + p = shutil.which("luau") + if p: + return p + return subprocess.run(["nix", "shell", "nixpkgs#luau", "-c", "sh", "-c", "command -v luau"], capture_output=True, check=True, + text=True).stdout.strip() + + +def luau(ctx, code): + d = os.path.join(ROOT, "tests", "gen") + os.makedirs(d, exist_ok=True) + fd, path = tempfile.mkstemp(prefix="_run_", suffix=".luau", dir=d) + try: + with os.fdopen(fd, "w") as f: + f.write(code) + r = subprocess.run([luau_bin(), "--codegen", "-O2", path], cwd=ROOT, capture_output=True) + if r.returncode != 0: + raise RuntimeError("luau failed:\n" + r.stderr.decode(errors="replace") + r.stdout.decode(errors="replace")[-2000:]) + out = r.stdout + return out[:-1] if out.endswith(b"\n") else out + finally: + os.unlink(path) + + +def emit_signal(ctx, name, samples, rate, ch): + """emit tests/gen/.luau = { rate, channels, frames, data = f32le bytes } (the input encoders are tested on)""" + ctx.emit(name, {"rate": rate, "channels": ch, "frames": len(samples) // ch, "data": f32le(samples)}) + + +def encode_luau(ctx, module, sigmod, opts_lua="nil", source="audio"): + """encode the emitted signal module `sigmod` with require("@formats/").encode(audio, opts) in Luau; returns + the encoded bytes. source = "decoder" feeds a streaming Decoder (codecs/Pcm.audioDecoder) instead of the Audio.""" + code = """ +local S = require("@tests/gen/%s") +local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/Pcm") +local M = require("@formats/%s") +local a = Types.Audio.new(S.rate, S.channels, S.frames) +buffer.writestring(a.samples, 0, S.data) +local src: any = a +if "%s" == "decoder" then src = Pcm.audioDecoder(a) end +local out, err = M.encode(src, %s) +if not out then error("encode failed: " .. tostring(err)) end +print(buffer.tostring(out)) +""" % (sigmod, module, source, opts_lua) + return luau(ctx, code) + + +def max_diff(a, b): + if len(a) != len(b): + return float("inf") + return max((abs(x - y) for x, y in zip(a, b)), default=0.0) + + +def pcm_fixtures(ctx, fmt, made, encodes, sig_rate=22050, sig_frames=3000): + """The fixtures of an uncompressed container (aiff, au, voc): + made = [(name, packages, argv)]: reference tools write files from {in} (a stereo / mono 16-bit or float WAV of + the test signal; argv may use {in_mono}, {in_float}) into {out}; each file is decoded by ffmpeg as the + reference (f32le) + encodes = [(name, opts_lua, channels)]: our encoder's output (in the fixture step) decoded by ffmpeg, compared + against the f32 input (max abs difference, which the test bounds by the format's quantization step) + Emits _cases (files + references), _sig / _sig1 (the inputs, stereo / mono) and _enc.""" + stereo = signal("music", sig_rate, 2, sig_frames, seed=3) + mono = signal("sweep", sig_rate, 1, sig_frames, seed=4) + emit_signal(ctx, fmt + "_sig", stereo, sig_rate, 2) + emit_signal(ctx, fmt + "_sig1", mono, sig_rate, 1) + inputs = {"{in}": wav(stereo, sig_rate, 2, 16), "{in_mono}": wav(mono, sig_rate, 1, 16), + "{in_float}": wav(stereo, sig_rate, 2, float_=True)} + cases = [] + for name, packages, argv in made: + d = tempfile.mkdtemp(prefix="fmt-audio-") + try: + paths = {} + for key, data in inputs.items(): + paths[key] = os.path.join(d, key.strip("{}") + ".wav") + with open(paths[key], "wb") as f: + f.write(data) + out = os.path.join(d, "out." + fmt) + args = [] + for a in argv: + for key, p in paths.items(): + a = a.replace(key, p) + args.append(a.replace("{out}", out)) + ctx.nix(packages, args) + with open(out, "rb") as f: + data = f.read() + finally: + shutil.rmtree(d, ignore_errors=True) + rate, ch, ref = ffdecode(ctx, data, ext=fmt) + cases.append({"name": name, "data": data, "rate": rate, "channels": ch, "frames": len(ref) // ch, "ref": f32le(ref)}) + ctx.emit(fmt + "_cases", cases) + results = [] + for name, opts_lua, ch in encodes: + sig = stereo if ch == 2 else mono + out = encode_luau(ctx, "audio/" + fmt, fmt + ("_sig" if ch == 2 else "_sig1"), opts_lua) + streamed = encode_luau(ctx, "audio/" + fmt, fmt + ("_sig" if ch == 2 else "_sig1"), opts_lua, source="decoder") + rate, dch, dec = ffdecode(ctx, out, ext=fmt) + errs = tool(ctx, "ffmpeg", ["ffmpeg", "-v", "error", "-i", "{in}", "-f", "null", "-"], out, fmt) + results.append({"name": name, "opts": opts_lua, "channels": dch, "rate": rate, "frames": len(dec) // max(1, dch), + "maxDiff": max_diff(sig, dec) if dch == ch else 99.0, "ffmpegErrors": errs.decode(errors="replace"), + "bytes": len(out), "sameStreamed": out == streamed, "data": out}) + ctx.emit(fmt + "_enc", results) + + +def encode_luau_many(ctx, module, jobs, sigmod): + """jobs = [(signal name, opts_lua)] over the emitted module sigmod = { [name] = { rate, channels, frames, data } } + -> [bytes]: one Luau run encodes them all (length-prefixed on stdout)""" + body = ['job("%s", %s)' % (name, opts) for name, opts in jobs] + code = """ +local Types = require("@formats/Types") +local M = require("@formats/%s") +local S = require("@tests/gen/%s") +local outs = {} +local function job(name, opts) + local s = S[name] + local a = Types.Audio.new(s.rate, s.channels, s.frames) + buffer.writestring(a.samples, 0, s.data) + local out, err = M.encode(a, opts) + if not out then error("encode failed: " .. tostring(err)) end + local n = buffer.len(out) + table.insert(outs, string.format("%%012d", n) .. buffer.tostring(out)) +end +%s +print(table.concat(outs)) +""" % (module, sigmod, "\n".join(body)) + raw = luau(ctx, code) + res, p = [], 0 + while p < len(raw): + n = int(raw[p:p + 12]) + res.append(raw[p + 12:p + 12 + n]) + p += 12 + n + return res + + +def shell_many(ctx, packages, files, script): + """write files {name: bytes} into a temp dir and run `sh -c script` there under nix; returns stdout""" + d = tempfile.mkdtemp(prefix="fmt-audio-") + try: + for name, data in files.items(): + with open(os.path.join(d, name), "wb") as f: + f.write(data) + return ctx.nix(packages, ["sh", "-c", "cd '%s' && %s" % (d, script)]) + finally: + shutil.rmtree(d, ignore_errors=True) diff --git a/tools/fixtures/_m4a_encode.luau b/tools/fixtures/_m4a_encode.luau new file mode 100644 index 0000000..8a42eb5 --- /dev/null +++ b/tools/fixtures/_m4a_encode.luau @@ -0,0 +1,31 @@ +-- tools/fixtures/_m4a_encode: run by tools/fixtures/m4a.py (luau, from the repo root) so the reference tools can check +-- our writers: encodes the test signal (tests/audio/_signal) to ALAC M4A (audio/m4a) and ALAC / PCM CAF (audio/caf) +-- and prints " " lines. The tests re-encode and compare the CRC with the file ffmpeg validated. +local Signal = require("@tests/audio/_signal") +local M4a = require("@formats/audio/m4a") +local Caf = require("@formats/audio/caf") + +local function hex(b: buffer): string + local t = table.create(buffer.len(b)) + for i = 0, buffer.len(b) - 1 do + t[i + 1] = string.format("%02x", buffer.readu8(b, i)) + end + return table.concat(t) +end + +local Cases = require("@tests/audio/_encode_cases") +for _, c in Cases do + local a = Signal.audio(c.rate, c.frames, c.channels, c.bits, c.seed) + a.tags = c.tags or {} + local out, err + if c.container == "caf" then + out, err = Caf.encode(a, { codec = c.codec, bitDepth = c.bits }) + else + out, err = M4a.encode(a, { bitDepth = c.bits }) + end + if not out then + print(c.name .. " ERROR " .. tostring(err)) + else + print(c.name .. " " .. hex(out)) + end +end diff --git a/tools/fixtures/_m4a_signal.py b/tools/fixtures/_m4a_signal.py new file mode 100644 index 0000000..7eb72ed --- /dev/null +++ b/tools/fixtures/_m4a_signal.py @@ -0,0 +1,41 @@ +# The deterministic integer test signal shared by tools/fixtures/m4a.py, tools/fixtures/caf.py and the Luau side +# (tests/audio/_signal.luau computes the same numbers): triangle + square + MINSTD noise (exact in doubles) + clicks, per channel. +import struct + + +def signal(frames, channels, bits, seed): + s = seed + peak = 2 ** (bits - 1) - 1 + out = [] + for i in range(frames): + for c in range(channels): + s = (s * 48271) % 2147483647 + p1 = 97 + 31 * c + tri = abs((i % p1) * 2 - p1) * 2 - p1 + v = tri * (peak // (4 * p1)) + p2 = 1500 + 200 * c + v += (peak // 6) if (i // p2) % 2 == 0 else -(peak // 6) + v += ((s // 65536) % 4096 - 2048) * (peak // 65536 + 1) + if i % 7001 < 3: + v += peak // 2 + out.append(max(-peak - 1, min(peak, v))) + return out + + +def pack(samples, bits, big=False): + e = ">" if big else "<" + if bits == 16: + return struct.pack(e + "%dh" % len(samples), *samples) + if bits == 24: + b = bytearray() + for v in samples: + x = struct.pack(" [type, channel, data, meta] in formats-luau's shape (data = raw bytes)""" + t = msg.type + if msg.is_meta: + b = msg.bytes() + i = 2 + while b[i] & 0x80: + i += 1 + return ["meta", -1, list(b[i + 1:]), b[1]] + if t == "sysex": + return ["sysex", -1, list(msg.data) + [0xF7], -1] + if t == "note_on": + return ["noteOn", msg.channel, [msg.note, msg.velocity], -1] + if t == "note_off": + return ["noteOff", msg.channel, [msg.note, msg.velocity], -1] + if t == "polytouch": + return ["aftertouch", msg.channel, [msg.note, msg.value], -1] + if t == "control_change": + return ["controller", msg.channel, [msg.control, msg.value], -1] + if t == "program_change": + return ["program", msg.channel, [msg.program], -1] + if t == "aftertouch": + return ["channelPressure", msg.channel, [msg.value], -1] + if t == "pitchwheel": + v = msg.pitch + 8192 + return ["pitchBend", msg.channel, [v & 127, v >> 7], -1] + raise ValueError(t) + + +def describe(name, mid): + buf = io.BytesIO() + mid.save(file=buf) + data = buf.getvalue() + back = MidiFile(file=io.BytesIO(data)) + tracks = [] + for tr in back.tracks: + tick, evs = 0, [] + for msg in tr: + tick += msg.time + evs.append([tick] + ours(msg)) + tracks.append(evs) + case = {"name": name, "hex": data.hex(), "type": back.type, "division": back.ticks_per_beat, "tracks": tracks} + if back.type != 2 and back.ticks_per_beat > 0: + case["length"] = back.length + t, times = 0.0, [] + for msg in back: + t += msg.time + times.append(t) + case["times"] = times + return case + + +def notes(track, ch, rng, n, prog=None, start=0): + if prog is not None: + track.append(Message("program_change", channel=ch, program=prog, time=start)) + start = 0 + for i in range(n): + note = rng.randint(30, 90) + track.append(Message("note_on", channel=ch, note=note, velocity=rng.randint(1, 127), time=start if i == 0 else rng.randint(0, 120))) + track.append(Message("note_off", channel=ch, note=note, velocity=rng.randint(0, 127), time=rng.randint(1, 480))) + + +cases = [] +rng = random.Random(7) + +# format 0: one track with everything +mid = MidiFile(type=0, ticks_per_beat=480) +t = MidiTrack() +mid.tracks.append(t) +t.append(MetaMessage("track_name", name="format zero")) +t.append(MetaMessage("set_tempo", tempo=500000)) +t.append(MetaMessage("time_signature", numerator=3, denominator=4, clocks_per_click=24, notated_32nd_notes_per_beat=8)) +t.append(MetaMessage("key_signature", key="Eb")) +t.append(MetaMessage("text", text="hello")) +t.append(Message("program_change", channel=0, program=5)) +t.append(Message("control_change", channel=0, control=7, value=100)) +t.append(Message("control_change", channel=0, control=10, value=20)) +t.append(Message("note_on", channel=0, note=60, velocity=100, time=0)) +t.append(Message("note_on", channel=0, note=64, velocity=90, time=10)) # running status +t.append(Message("note_on", channel=0, note=67, velocity=80, time=10)) +t.append(Message("pitchwheel", channel=0, pitch=-8192, time=100)) +t.append(Message("pitchwheel", channel=0, pitch=8191, time=100)) +t.append(Message("pitchwheel", channel=0, pitch=0, time=100)) +t.append(Message("polytouch", channel=0, note=60, value=33, time=5)) +t.append(Message("aftertouch", channel=0, value=44, time=5)) +t.append(Message("sysex", data=[0x7E, 0x7F, 0x09, 0x01], time=0)) +t.append(MetaMessage("set_tempo", tempo=300000, time=240)) +t.append(Message("note_off", channel=0, note=60, velocity=0, time=480)) +t.append(Message("note_on", channel=0, note=64, velocity=0, time=0)) # note on, velocity 0 +t.append(Message("note_off", channel=0, note=67, velocity=64, time=0)) +t.append(Message("note_on", channel=9, note=36, velocity=127, time=100)) +t.append(Message("note_off", channel=9, note=36, velocity=0, time=100)) +t.append(MetaMessage("time_signature", numerator=6, denominator=8, time=0)) +t.append(MetaMessage("set_tempo", tempo=1000000, time=10)) +t.append(Message("note_on", channel=1, note=72, velocity=50, time=0)) +t.append(Message("note_off", channel=1, note=72, velocity=50, time=960)) +cases.append(describe("format0", mid)) + +# format 1: a conductor track + 3 instrument tracks, tempo changes in the conductor +mid = MidiFile(type=1, ticks_per_beat=96) +cond = MidiTrack() +mid.tracks.append(cond) +cond.append(MetaMessage("track_name", name="conductor")) +cond.append(MetaMessage("time_signature", numerator=4, denominator=4)) +for i, tempo in enumerate([500000, 400000, 600000, 250000, 750000]): + cond.append(MetaMessage("set_tempo", tempo=tempo, time=0 if i == 0 else 384)) +for ch in range(3): + tr = MidiTrack() + mid.tracks.append(tr) + tr.append(MetaMessage("track_name", name="part %d" % ch)) + notes(tr, ch, rng, 40, prog=ch * 10) +cases.append(describe("format1", mid)) + +# format 2: independent patterns, each with its own tempo +mid = MidiFile(type=2, ticks_per_beat=240) +for k in range(3): + tr = MidiTrack() + mid.tracks.append(tr) + tr.append(MetaMessage("set_tempo", tempo=400000 + 100000 * k)) + notes(tr, k, rng, 10) +cases.append(describe("format2", mid)) + +# a random stress file: many tracks / channels / controller streams (long running-status runs) +mid = MidiFile(type=1, ticks_per_beat=480) +for k in range(6): + tr = MidiTrack() + mid.tracks.append(tr) + if k == 0: + for j in range(20): + tr.append(MetaMessage("set_tempo", tempo=rng.randint(200000, 1500000), time=rng.randint(0, 2000))) + continue + ch = rng.randint(0, 15) + for j in range(400): + r = rng.random() + dt = rng.choice([0, 0, 1, 7, 120, 480, 20000]) + if r < 0.4: + tr.append(Message("note_on", channel=ch, note=rng.randint(0, 127), velocity=rng.randint(0, 127), time=dt)) + elif r < 0.6: + tr.append(Message("note_off", channel=ch, note=rng.randint(0, 127), velocity=rng.randint(0, 127), time=dt)) + elif r < 0.8: + tr.append(Message("control_change", channel=ch, control=rng.randint(0, 127), value=rng.randint(0, 127), time=dt)) + elif r < 0.9: + tr.append(Message("pitchwheel", channel=ch, pitch=rng.randint(-8192, 8191), time=dt)) + elif r < 0.95: + tr.append(Message("program_change", channel=ch, program=rng.randint(0, 127), time=dt)) + else: + tr.append(Message("sysex", data=[rng.randint(0, 127) for _ in range(rng.randint(0, 200))], time=dt)) +cases.append(describe("random", mid)) + +# SMPTE time (25 fps, 40 ticks per frame): division = -(25 << 8) + 40 as a signed 16-bit value +mid = MidiFile(type=0, ticks_per_beat=-6360) +t = MidiTrack() +mid.tracks.append(t) +t.append(Message("note_on", note=60, velocity=64, time=0)) +t.append(Message("note_off", note=60, velocity=64, time=1000)) +cases.append(describe("smpte", mid)) + +# the song the fallback / SoundFont render tests play (tools/fixtures/sf2.py has its own); its mido length +mid = MidiFile(type=1, ticks_per_beat=480) +cond = MidiTrack() +mid.tracks.append(cond) +cond.append(MetaMessage("set_tempo", tempo=500000)) +cond.append(MetaMessage("set_tempo", tempo=250000, time=1920)) +tr = MidiTrack() +mid.tracks.append(tr) +notes(tr, 0, rng, 12, prog=0) +dr = MidiTrack() +mid.tracks.append(dr) +for k in range(16): + dr.append(Message("note_on", channel=9, note=[36, 38, 42, 46][k % 4], velocity=110, time=0 if k == 0 else 120)) + dr.append(Message("note_off", channel=9, note=[36, 38, 42, 46][k % 4], velocity=0, time=120)) +cases.append(describe("song", mid)) + +json.dump(cases, sys.stdout) diff --git a/tools/fixtures/_opus_encode.luau b/tools/fixtures/_opus_encode.luau new file mode 100644 index 0000000..a974148 --- /dev/null +++ b/tools/fixtures/_opus_encode.luau @@ -0,0 +1,17 @@ +-- tools/fixtures/_opus_encode: run by tools/fixtures/opus_celt.py (luau, from the repo root): encodes +-- tests/audio/_opus_cases with audio/opus's CELT encoder and prints " " lines for opusdec / ffmpeg. +local Opus = require("@formats/audio/opus") +local Cases = require("@tests/audio/_opus_cases") + +for _, c in Cases.list do + local out, err = Opus.encode(Cases.signal(c), { bitrate = c.bitrate }) + if not out then + print(c.name .. " ERROR " .. tostring(err)) + else + local t = table.create(buffer.len(out)) + for i = 0, buffer.len(out) - 1 do + t[i + 1] = string.format("%02x", buffer.readu8(out, i)) + end + print(c.name .. " " .. table.concat(t)) + end +end diff --git a/tools/fixtures/_sf2_features.py b/tools/fixtures/_sf2_features.py new file mode 100644 index 0000000..09f39fb --- /dev/null +++ b/tools/fixtures/_sf2_features.py @@ -0,0 +1,61 @@ +# Audio features of a WAV on stdin (run by tools/fixtures/sf2.py through ctx.python(["numpy"], ...); not a generator). +# tests/music/sf2.luau computes the same features from formats-luau's render and compares them: +# env RMS of the mono mix per 50 ms window (2205 frames) +# bands per 2 s segment: mean power in 24 log-spaced bands (60 Hz .. 16 kHz) of 2048-point Hann frames (hop 1024), +# in dB +# peaks the strongest frequency (parabolic interpolation) of the mean 8192-point Hann spectrum in a few windows +import io, json, sys, wave +import numpy as np + +w = wave.open(io.BytesIO(sys.stdin.buffer.read())) +rate, ch, width, n = w.getframerate(), w.getnchannels(), w.getsampwidth(), w.getnframes() +raw = w.readframes(n) +assert width == 2, width +x = np.frombuffer(raw, dtype="= edges[k]) & (freqs < edges[k + 1])].sum() + frames += 1 + return [float(10 * np.log10(v / max(frames, 1) + 1e-12)) for v in acc] + + +PN = 8192 +phan = 0.5 - 0.5 * np.cos(2 * np.pi * np.arange(PN) / PN) +WINDOWS = [(4.2, 5.4), (8.05, 8.45), (8.55, 8.95), (2.02, 2.33)] + + +def peak(a, b): + acc = np.zeros(PN // 2 + 1) + for s in range(int(a * rate), int(b * rate) - PN + 1, PN // 4): + acc += np.abs(np.fft.rfft(mono[s:s + PN] * phan)) ** 2 + k = int(np.argmax(acc[1:-1])) + 1 + y0, y1, y2 = np.log(acc[k - 1] + 1e-30), np.log(acc[k] + 1e-30), np.log(acc[k + 1] + 1e-30) + d = 0.5 * (y0 - y2) / (y0 - 2 * y1 + y2) + return float((k + d) * rate / PN) + + +json.dump({ + "rate": rate, + "frames": len(mono), + "env": env, + "edges": edges, + "segments": [list(s) for s in SEGMENTS], + "bands": [bands(a, b) for a, b in SEGMENTS], + "windows": [list(wd) for wd in WINDOWS], + "peaks": [peak(a, b) for a, b in WINDOWS], +}, sys.stdout) diff --git a/tools/fixtures/_tracker.py b/tools/fixtures/_tracker.py new file mode 100644 index 0000000..eeef247 --- /dev/null +++ b/tools/fixtures/_tracker.py @@ -0,0 +1,495 @@ +# Tracker fixture helpers (used by tools/fixtures/{mod,s3m,xm,it}.py): small writers for MOD, S3M, XM and IT +# (including IT 2.14 / 2.15 sample compression), synthesized samples, reference renders through openmpt123 (nix +# libopenmpt) and the comparison features (per 2048-frame block: RMS of left / right / mid and 40 log-spaced band +# magnitudes of the mid signal), computed the same way in tests/music/_similar.luau. Every module is generated here +# (no third-party files), so the fixtures carry no licence. +import json, math, os, struct, subprocess, tempfile + +SR = 44100 +HOP = 2048 +BANDS = 40 +F_LO, F_HI = 150.0, 16000.0 + + +# ---------------------------------------------------------------------------------------------- samples +def synth(kind, n, period, amp=0.9, seed=1, decay=None): + """float samples in [-1, 1]: sine / square / saw / tri / noise / pluck""" + out = [] + s = seed + for i in range(n): + ph = (i % period) / period + if kind == "sine": + v = math.sin(2 * math.pi * ph) + elif kind == "square": + v = 1.0 if ph < 0.5 else -1.0 + elif kind == "saw": + v = 2 * ph - 1 + elif kind == "tri": + v = 4 * ph - 1 if ph < 0.5 else 3 - 4 * ph + else: # noise + s = (s * 1103515245 + 12345) % 2147483648 + v = (s / 2147483648) * 2 - 1 + if decay: + v *= math.exp(-i / decay) + out.append(v * amp) + return out + + +def s8(xs): + return bytes((max(-128, min(127, int(round(x * 127)))) & 255) for x in xs) + + +def u8(xs): + return bytes(max(0, min(255, int(round(x * 127)) + 128)) for x in xs) + + +def s16(xs): + return b"".join(struct.pack("= 128 else b + out.append((v - prev) & 255) + prev = v + return bytes(out) + + +def delta16(raw): + out, prev = bytearray(), 0 + for i in range(0, len(raw), 2): + v = struct.unpack_from("HBBHH", len(s["data"]) // 2, s.get("finetune", 0) & 15, + s.get("volume", 64), ls // 2, ll // 2) + else: + out += b"\0" * 22 + struct.pack(">HBBHH", 0, 0, 0, 0, 1) + out += bytes([len(orders), restart]) + bytes(orders) + b"\0" * (128 - len(orders)) + out += b"M.K." if channels == 4 else (b"%dCHN" % channels if channels < 10 else b"%dCH" % channels) + for pat in patterns: + for row in pat: + for (note, ins, fx, param) in row: + p = mod_period(note) + out += bytes([(ins & 0xF0) | (p >> 8), p & 255, ((ins & 15) << 4) | fx, param]) + for s in samples: + out += s["data"] + return bytes(out) + + +# ---------------------------------------------------------------------------------------------- S3M +def write_s3m(title, samples, orders, patterns, channels, speed=6, tempo=125, gvol=64, mvol=48 | 128, pans=None, + flags=0, cwt=0x1320, chanset=None): + """samples: [{name, data (u8 bytes), volume, c2spd, loop: (start, end) | None}]; + patterns: [[row: [(note, ins, vol, cmd, info)] * channels] * 64] with note 0 = none, 254 = cut, else S3M byte + (octave << 4 | semitone); vol None = none; cmd 0 = none (A = 1).""" + ordn = list(orders) + [255] + if len(ordn) % 2: + ordn.append(255) + nins, npat = len(samples), len(patterns) + head = bytearray(name(title, 28) + bytes([0x1A, 16, 0, 0])) + head += struct.pack("> 16 + struct.pack_into(" the S3M note byte""" + n = note - 13 + return (n // 12) << 4 | (n % 12) + + +# ---------------------------------------------------------------------------------------------- XM +def env_bytes(points): + b = bytearray() + for (x, y) in points[:12]: + b += struct.pack("= 128 else b for b in raw] + else: + vals = [struct.unpack_from("= 8: + data.append(acc & 255) + acc >>= 8 + nbits -= 8 + if nbits: + data.append(acc & 255) + out += struct.pack("> 1 + while j & bit: + j ^= bit + bit >>= 1 + j |= bit + if i < j: + re[i], re[j] = re[j], re[i] + im[i], im[j] = im[j], im[i] + size = 2 + while size <= n: + ang = -2 * math.pi / size + wr, wi = math.cos(ang), math.sin(ang) + for start in range(0, n, size): + cr, ci = 1.0, 0.0 + half = size // 2 + for k in range(half): + a, b = start + k, start + k + half + tr = re[b] * cr - im[b] * ci + ti = re[b] * ci + im[b] * cr + re[b], im[b] = re[a] - tr, im[a] - ti + re[a], im[a] = re[a] + tr, im[a] + ti + cr, ci = cr * wr - ci * wi, cr * wi + ci * wr + size *= 2 + + +EDGES = [F_LO * (F_HI / F_LO) ** (j / BANDS) for j in range(BANDS + 1)] +WINDOW = [0.5 - 0.5 * math.cos(2 * math.pi * i / HOP) for i in range(HOP)] + + +def features(left, right): + """{frames, rmsL, rmsR, rmsM, bands (frames * BANDS magnitudes)} of a stereo signal""" + n = len(left) // HOP + out = {"frames": n, "rmsL": [], "rmsR": [], "rmsM": [], "bands": []} + for k in range(n): + o = k * HOP + L, R = left[o:o + HOP], right[o:o + HOP] + M = [(a + b) / 2 for a, b in zip(L, R)] + out["rmsL"].append(math.sqrt(sum(x * x for x in L) / HOP)) + out["rmsR"].append(math.sqrt(sum(x * x for x in R) / HOP)) + out["rmsM"].append(math.sqrt(sum(x * x for x in M) / HOP)) + re = [M[i] * WINDOW[i] for i in range(HOP)] + im = [0.0] * HOP + fft(re, im) + e = [0.0] * BANDS + for b in range(1, HOP // 2): + f = b * SR / HOP + if f < F_LO or f >= F_HI: + continue + j = min(BANDS - 1, int(math.log(f / F_LO) / math.log(F_HI / F_LO) * BANDS)) + e[j] += re[b] * re[b] + im[b] * im[b] + out["bands"] += [math.sqrt(x) for x in e] + return out + + +def duration(ctx, data, ext): + """openmpt123 --info's song length in seconds""" + with tempfile.TemporaryDirectory() as d: + p = os.path.join(d, "song." + ext) + with open(p, "wb") as f: + f.write(data) + info = ctx.nix("libopenmpt", ["openmpt123", "--info", p]).decode(errors="replace") + for line in info.splitlines(): + if line.startswith("Duration"): + secs = 0.0 + for part in line.split(":", 1)[1].strip().split(":"): + secs = secs * 60 + float(part) + return secs + raise RuntimeError("openmpt123 --info: no duration") + + +def reference(ctx, data, ext, extra=()): + left, right = openmpt(ctx, data, ext, extra) + f = features(left, right) + f["duration"] = duration(ctx, data, ext) + return f diff --git a/tools/fixtures/_video.py b/tools/fixtures/_video.py new file mode 100644 index 0000000..60430fe --- /dev/null +++ b/tools/fixtures/_video.py @@ -0,0 +1,122 @@ +# Shared helpers for the video fixture generators (mkv.py, avi.py, y4m.py, mpegts.py, videoapi.py), loaded by path. +# ffmpeg / ffprobe come from PATH when present (a build with libvpx / libopus / libvorbis), else nix (ffmpeg-full). +import json, os, shutil, subprocess, zlib + +_FF = None + + +def ff_prefix(): + global _FF + if _FF is None: + if shutil.which("ffmpeg") and shutil.which("ffprobe"): + _FF = [] + else: + _FF = ["nix", "shell", "nixpkgs#ffmpeg-full", "-c"] + return _FF + + +def ffmpeg(args, cwd=None, input=None): + return subprocess.run(ff_prefix() + ["ffmpeg", "-v", "error", "-y"] + args, cwd=cwd, input=input, + capture_output=True, check=True).stdout + + +def ffprobe_json(path, extra): + out = subprocess.run(ff_prefix() + ["ffprobe", "-v", "error", "-of", "json"] + extra + [path], + capture_output=True, check=True).stdout + return json.loads(out) + + +def streams(path): + """ffprobe streams: [{index, kind, codec, width, height, rate, channels, time_base}]""" + d = ffprobe_json(path, ["-show_streams"]) + out = [] + for s in d.get("streams", []): + e = {"index": s["index"], "kind": s.get("codec_type", ""), "codec": s.get("codec_name", "")} + if "width" in s: + e["width"], e["height"] = s["width"], s["height"] + if "sample_rate" in s: + e["rate"] = int(s["sample_rate"]) + e["channels"] = s.get("channels", 0) + tb = s.get("time_base", "1/1").split("/") + e["tbn"], e["tbd"] = int(tb[0]), int(tb[1]) + out.append(e) + return out + + +def packets(path): + """ffprobe packets in file order: [{stream, pts, dur, key, size, crc}] (pts / dur in the stream time base)""" + d = ffprobe_json(path, ["-show_packets", "-show_data_hash", "crc32"]) + out = [] + for p in d.get("packets", []): + e = {"stream": p["stream_index"], "key": "K" in p.get("flags", ""), "size": int(p["size"]), + "crc": int(p["data_hash"].split(":")[1], 16)} + if p.get("pts") not in (None, "N/A"): + e["pts"] = int(p["pts"]) + if p.get("duration") not in (None, "N/A"): + e["dur"] = int(p["duration"]) + out.append(e) + return out + + +def yuv_frames(path, w, h, extra=None, codec=None): + """the first video stream decoded by ffmpeg to yuv420p (yuvj420p for MJPEG: full range, no conversion): a list of + frame bytes""" + pix = "yuvj420p" if codec == "mjpeg" else "yuv420p" + raw = ffmpeg(["-i", path] + (extra or []) + ["-map", "0:v:0", "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", pix, "-"]) + n = w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2) + return [raw[i:i + n] for i in range(0, len(raw) - n + 1, n)] + + +def pcm_f32(path, extra=None): + """the first audio stream decoded by ffmpeg to interleaved f32le""" + return ffmpeg(["-i", path] + (extra or []) + ["-map", "0:a:0", "-f", "f32le", "-"]) + + +def crc(b): + return zlib.crc32(b) & 0xffffffff + + +def ebml_vint(b, p): + """(value, length) of an EBML vint (marker removed; all ones -> -1)""" + first = b[p] + n = 1 + mask = 0x80 + while n <= 8 and not first & mask: + n += 1 + mask >>= 1 + v = first & (mask - 1) + ones = v == mask - 1 + for i in range(1, n): + v = (v << 8) | b[p + i] + ones = ones and b[p + i] == 255 + return (-1 if ones else v), n + + +def ebml_id(b, p): + first = b[p] + n = 1 if first >= 0x80 else 2 if first >= 0x40 else 3 if first >= 0x20 else 4 + return int.from_bytes(b[p:p + n], "big"), n + + +def mkv_unknown_clusters(data): + """the same Matroska file with every Cluster's size field rewritten to 'unknown' (same length)""" + b = bytearray(data) + p = 0 + # EBML header + i, n = ebml_id(b, p) + s, m = ebml_vint(b, p + n) + p += n + m + s + i, n = ebml_id(b, p) # Segment + s, m = ebml_vint(b, p + n) + p += n + m + while p < len(b): + i, n = ebml_id(b, p) + s, m = ebml_vint(b, p + n) + if i == 0x1F43B675: + b[p + n] = (0xFF >> (m - 1)) if m < 8 else 0x01 + for k in range(1, m): + b[p + n + k] = 0xFF + if m == 1: + b[p + n] = 0xFF + p += n + m + s + return bytes(b) diff --git a/tools/fixtures/_video_encode.luau b/tools/fixtures/_video_encode.luau new file mode 100644 index 0000000..5fa13b8 --- /dev/null +++ b/tools/fixtures/_video_encode.luau @@ -0,0 +1,53 @@ +-- tools/fixtures/_video_encode: run by tools/fixtures/videoenc.py (luau, from the repo root) so ffprobe / ffmpeg can +-- check our video writers: remuxes and re-encodes the container fixtures (tests/gen/mkv_cases, avi_cases, mp4_cases) and the +-- animated GIF of tests/gen/videoenc_src, and prints " " lines (or " ERR "). +local F = require("@formats") +local Mkv = require("@tests/gen/mkv_cases") +local Avi = require("@tests/gen/avi_cases") +local Mp4 = require("@tests/gen/mp4_cases") +local Src = require("@tests/gen/videoenc_src") + +local function hex(b: buffer): string + local t = table.create(buffer.len(b)) + for i = 0, buffer.len(b) - 1 do + t[i + 1] = string.format("%02x", buffer.readu8(b, i)) + end + return table.concat(t) +end + +local function find(list: any, name: string): string + for _, c in list do + if c.name == name then + return c.data + end + end + error("no fixture " .. name) +end + +local JOBS = { + { "remux.webm", find(Mkv, "vp8_opus.webm"), "webm", {} }, + { "copy.mkv", find(Mkv, "mjpeg_pcm.mkv"), "mkv", {} }, + { "vp8_mjpeg.mkv", find(Mkv, "vp8_opus.webm"), "mkv", { reencode = true, quality = 92 } }, + { "copy.avi", find(Avi, "mjpeg_pcm.avi"), "avi", {} }, + { "vp8_mjpeg.avi", find(Mkv, "vp8_opus.webm"), "avi", { quality = 92 } }, + { "mpeg1_mjpeg.avi", find(Mkv, "mpeg1_mp2.mkv"), "avi", { quality = 92 } }, + { "gif.avi", Src.gif, "avi", { quality = 95 } }, + { "gif.mkv", Src.gif, "mkv", { quality = 95 } }, + { "gif.y4m", Src.gif, "y4m", {} }, + { "webm.y4m", find(Mkv, "vp8_opus.webm"), "y4m", {} }, + { "gif.mp4", Src.gif, "mp4", { quality = 95 } }, + { "pcm.mov", find(Mkv, "mjpeg_pcm.mkv"), "mov", {} }, + { "h264_aac.mov", find(Mp4, "h264_aac.mp4"), "mov", {} }, + { "h264_aac.mkv", find(Mp4, "h264_aac.mp4"), "mkv", {} }, + { "vp8_mjpeg.mp4", find(Mkv, "vp8_opus.webm"), "mp4", { quality = 92 } }, + { "flac.mp4", find(Mp4, "mjpeg_flac.mp4"), "mp4", {} }, +} +for _, j in JOBS do + local name, data, fmt, opts = j[1], j[2], j[3], j[4] + local out, err = F.convert(buffer.fromstring(data), fmt, opts) + if out then + print(name .. " " .. hex(out)) + else + print(name .. " ERR " .. string.gsub(tostring(err), "%s", "_")) + end +end diff --git a/tools/fixtures/aiff.py b/tools/fixtures/aiff.py new file mode 100644 index 0000000..15fbdb2 --- /dev/null +++ b/tools/fixtures/aiff.py @@ -0,0 +1,51 @@ +# AIFF / AIFF-C fixtures (tools/fixtures.py): files written by ffmpeg and sox in every sample format we read, each +# with ffmpeg's f32 decode as the reference; our encoder's output for every sample format, decoded by ffmpeg in the +# fixture step (tools/fixtures/_audio.py pcm_fixtures). +# tests/gen/aiff_cases.luau { name, data, rate, channels, frames, ref (f32le) } +# tests/gen/aiff_enc.luau { name, opts, channels, rate, frames, maxDiff, ffmpegErrors, bytes, sameStreamed, data } +# tests/gen/aiff_sig*.luau the encoder inputs +import importlib.util, os + +_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 = ["src/Formats/audio/aiff", "src/Formats/codecs/Pcm"] + + +def ff(codec, src="{in}", extra=()): + return ["ffmpeg", "-v", "error", "-i", src] + list(extra) + ["-c:a", codec, "-f", "aiff", "-y", "{out}"] + + +def generate(ctx): + made = [ + ("ffmpeg-s16be", "ffmpeg", ff("pcm_s16be")), + ("ffmpeg-s16be-mono", "ffmpeg", ff("pcm_s16be", "{in_mono}")), + ("ffmpeg-s8", "ffmpeg", ff("pcm_s8")), + ("ffmpeg-s24be", "ffmpeg", ff("pcm_s24be", "{in_float}")), + ("ffmpeg-s32be", "ffmpeg", ff("pcm_s32be", "{in_float}")), + ("ffmpeg-sowt", "ffmpeg", ff("pcm_s16le")), + ("ffmpeg-fl32", "ffmpeg", ff("pcm_f32be", "{in_float}")), + ("ffmpeg-fl64", "ffmpeg", ff("pcm_f64be", "{in_float}")), + ("ffmpeg-ulaw", "ffmpeg", ff("pcm_mulaw")), + ("ffmpeg-alaw", "ffmpeg", ff("pcm_alaw")), + ("ffmpeg-48k-6ch", "ffmpeg", ["ffmpeg", "-v", "error", "-i", "{in}", "-af", "aresample=48000,pan=5.1|c0=c0|c1=c1|c2=c0|c3=c1|c4=c0|c5=c1", "-c:a", "pcm_s16be", "-f", "aiff", "-y", "{out}"]), + ("ffmpeg-tags", "ffmpeg", ff("pcm_s16be", extra=("-metadata", "title=Song Name", "-metadata", "author=Some One", "-metadata", "comment=hello"))), + ("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}"]), + ] + encodes = [ + ("s16", "nil", 2), + ("s16-mono", "nil", 1), + ("s8", '{ sampleFormat = "s8" }', 2), + ("s24", '{ sampleFormat = "s24" }', 2), + ("s32", '{ sampleFormat = "s32" }', 1), + ("f32", '{ sampleFormat = "f32" }', 2), + ("f64", '{ sampleFormat = "f64" }', 2), + ("ulaw", '{ sampleFormat = "ulaw" }', 2), + ("alaw", '{ sampleFormat = "alaw" }', 1), + ("sowt16", '{ littleEndian = true }', 2), + ("aifc-s16", '{ aifc = true }', 2), + ] + A.pcm_fixtures(ctx, "aiff", made, encodes) diff --git a/tools/fixtures/au.py b/tools/fixtures/au.py new file mode 100644 index 0000000..eb34539 --- /dev/null +++ b/tools/fixtures/au.py @@ -0,0 +1,47 @@ +# Sun AU fixtures (tools/fixtures.py): files written by ffmpeg and sox in every encoding we read, each with ffmpeg's +# f32 decode as the reference; our encoder's output for every encoding, decoded by ffmpeg in the fixture step +# (tools/fixtures/_audio.py pcm_fixtures). +# tests/gen/au_cases.luau { name, data, rate, channels, frames, ref (f32le) } +# tests/gen/au_enc.luau { name, opts, channels, rate, frames, maxDiff, ffmpegErrors, bytes, sameStreamed, data } +# tests/gen/au_sig*.luau the encoder inputs +import importlib.util, os + +_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 = ["src/Formats/audio/au", "src/Formats/codecs/Pcm"] + + +def ff(codec, src="{in}", extra=()): + return ["ffmpeg", "-v", "error", "-i", src] + list(extra) + ["-c:a", codec, "-f", "au", "-y", "{out}"] + + +def generate(ctx): + made = [ + ("ffmpeg-s16be", "ffmpeg", ff("pcm_s16be")), + ("ffmpeg-s16be-mono", "ffmpeg", ff("pcm_s16be", "{in_mono}")), + ("ffmpeg-s8", "ffmpeg", ff("pcm_s8")), + ("ffmpeg-s24be", "ffmpeg", ff("pcm_s24be", "{in_float}")), + ("ffmpeg-s32be", "ffmpeg", ff("pcm_s32be", "{in_float}")), + ("ffmpeg-f32be", "ffmpeg", ff("pcm_f32be", "{in_float}")), + ("ffmpeg-f64be", "ffmpeg", ff("pcm_f64be", "{in_float}")), + ("ffmpeg-ulaw", "ffmpeg", ff("pcm_mulaw")), + ("ffmpeg-alaw", "ffmpeg", ff("pcm_alaw")), + ("sox-comment", "sox", ["sox", "{in}", "--comment", "hello sun", "-t", "au", "{out}"]), + ("sox-ulaw-8k", "sox", ["sox", "{in_mono}", "-r", "8000", "-e", "mu-law", "-t", "au", "{out}"]), + ("sox-s16", "sox", ["sox", "{in}", "-t", "au", "{out}"]), + ("sox-f32", "sox", ["sox", "{in_float}", "-e", "floating-point", "-b", "32", "-t", "au", "{out}"]), + ] + encodes = [ + ("s16", "nil", 2), + ("s16-mono", "nil", 1), + ("s8", '{ sampleFormat = "s8" }', 2), + ("s24", '{ sampleFormat = "s24" }', 2), + ("s32", '{ sampleFormat = "s32" }', 1), + ("f32", '{ sampleFormat = "f32" }', 2), + ("f64", '{ sampleFormat = "f64" }', 2), + ("ulaw", '{ sampleFormat = "ulaw" }', 2), + ("alaw", '{ sampleFormat = "alaw" }', 1), + ] + A.pcm_fixtures(ctx, "au", made, encodes) diff --git a/tools/fixtures/avi.py b/tools/fixtures/avi.py new file mode 100644 index 0000000..393ddd5 --- /dev/null +++ b/tools/fixtures/avi.py @@ -0,0 +1,152 @@ +# AVI fixtures (tools/fixtures.py): files made by ffmpeg (MJPEG + PCM with idx1, the same with OpenDML indexes added +# here, MJPEG + IMA +# ADPCM, MPEG-1 + MP2, uncompressed BGR24 / BGRA / I420 video) and edits made here (the OpenDML indexes renamed to +# JUNK so idx1 is used; idx1 renamed too so the movi list is scanned; a truncated file). For each file: ffprobe's +# streams and packets, ffmpeg's frames (CRC-32 of yuv420p, or of rgba for uncompressed RGB; the first frames raw for +# PSNR checks) and ffmpeg's decoded audio (f32). +# tests/gen/avi_cases.luau { { name, data, streams, packets, frames, yuv, rgba, pcm, ... } } +import importlib.util, os, tempfile + +_spec = importlib.util.spec_from_file_location("_video_helpers", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_video.py")) +V = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(V) + +INPUTS = ["tools/fixtures/_video.py"] + +W, H = 160, 120 +SRC = ["-f", "lavfi", "-i", "testsrc2=size=%dx%d:rate=10" % (W, H)] + + +def sine(rate, ch=1): + return ["-f", "lavfi", "-i", "sine=frequency=330:sample_rate=%d" % rate, "-ac", str(ch)] + + +def rename(data, old, new): + """every chunk id `old` renamed to `new` (same length), found by walking the RIFF lists""" + b = bytearray(data) + + def walk(p, end): + while p + 8 <= end: + cid = bytes(b[p:p + 4]) + size = int.from_bytes(b[p + 4:p + 8], "little") + if cid in (b"RIFF", b"LIST"): + walk(p + 12, min(end, p + 8 + size)) + elif cid == old: + b[p:p + 4] = new + p += 8 + size + (size & 1) + walk(0, len(b)) + return bytes(b) + + +def chunks(b, p, end): + out = [] + while p + 8 <= end: + cid = b[p:p + 4] + size = int.from_bytes(b[p + 4:p + 8], "little") + out.append((cid, p, size)) + p += 8 + size + (size & 1) + return out + + +def ck(cid, body): + return cid + len(body).to_bytes(4, "little") + body + (b"\0" if len(body) & 1 else b"") + + +def add_odml(data): + """the same AVI with OpenDML indexes: an indx super index in every strl pointing at an ix## standard index + appended to the movi list (built from idx1, which is kept)""" + b = data + top = chunks(b, 12, len(b)) + hdrl = next(c for c in top if c[0] == b"LIST" and b[c[1] + 8:c[1] + 12] == b"hdrl") + movi = next(c for c in top if c[0] == b"LIST" and b[c[1] + 8:c[1] + 12] == b"movi") + idx1 = next(c for c in top if c[0] == b"idx1") + movi_base = movi[1] + 8 # the 'movi' fourcc + streams = {} + for k in range(idx1[2] // 16): + e = idx1[1] + 8 + k * 16 + cid = b[e:e + 4] + flags, off, size = (int.from_bytes(b[e + 4 + 4 * i:e + 8 + 4 * i], "little") for i in range(3)) + sn = int(cid[:2]) + streams.setdefault(sn, (cid, []))[1].append((movi_base + off + 8, size, bool(flags & 0x10))) + n = len([c for c in chunks(b, hdrl[1] + 12, hdrl[1] + 8 + hdrl[2]) if c[0] == b"LIST" and b[c[1] + 8:c[1] + 12] == b"strl"]) + INDX = 8 + 24 + 16 # one super index entry + delta = n * INDX + # the ix## chunks at the end of the movi list + ixs = [] + pos = movi[1] + 8 + movi[2] + delta # where the first ix chunk starts (movi grows by them) + for sn in range(n): + cid, ents = streams.get(sn, (b"%02dwb" % sn, [])) + body = (2).to_bytes(2, "little") + bytes([0, 1]) + len(ents).to_bytes(4, "little") + cid + \ + (0).to_bytes(8, "little") + bytes(4) + for off, size, key in ents: + body += (off + delta).to_bytes(4, "little") + (size | (0 if key else 0x80000000)).to_bytes(4, "little") + chunk = ck(b"ix%02d" % sn, body) + ixs.append((pos, len(chunk), len(ents), cid, chunk)) + pos += len(chunk) + # hdrl with an indx in every strl + out_h = b"" + si = 0 + for c in chunks(b, hdrl[1] + 12, hdrl[1] + 8 + hdrl[2]): + raw = b[c[1]:c[1] + 8 + c[2] + (c[2] & 1)] + if c[0] == b"LIST" and b[c[1] + 8:c[1] + 12] == b"strl": + p, ln, cnt, cid, _ = ixs[si] + indx = (4).to_bytes(2, "little") + bytes([0, 0]) + (1).to_bytes(4, "little") + cid + bytes(12) + \ + p.to_bytes(8, "little") + ln.to_bytes(4, "little") + cnt.to_bytes(4, "little") + raw = ck(b"LIST", b[c[1] + 8:c[1] + 8 + c[2]] + ck(b"indx", indx)) + si += 1 + out_h += raw + out = b"" + for c in top: + if c is hdrl: + out += ck(b"LIST", b"hdrl" + out_h) + elif c is movi: + out += ck(b"LIST", b[c[1] + 8:c[1] + 8 + c[2]] + b"".join(x[4] for x in ixs)) + else: + out += b[c[1]:c[1] + 8 + c[2] + (c[2] & 1)] + res = b"RIFF" + (len(out) + 4).to_bytes(4, "little") + b"AVI " + out + assert res[ixs[0][0]:ixs[0][0] + 2] == b"ix", "odml layout" + return res + + +def case(tmp, name, rgba=False, raw_frames=2, pcm_frames=8192): + path = os.path.join(tmp, name) + c = {"name": name, "data": open(path, "rb").read(), "streams": V.streams(path), "packets": V.packets(path)} + vs = [s for s in c["streams"] if s["kind"] == "video"] + if vs: + w, h = vs[0]["width"], vs[0]["height"] + if rgba: + raw = V.ffmpeg(["-i", path, "-map", "0:v:0", "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", "rgba", "-"]) + n = w * h * 4 + c["rgba"] = [V.crc(raw[i:i + n]) for i in range(0, len(raw) - n + 1, n)] + else: + frames = V.yuv_frames(path, w, h, codec=vs[0]["codec"]) + c["frames"] = [V.crc(f) for f in frames] + c["yuv"] = frames[:raw_frames] + if any(s["kind"] == "audio" for s in c["streams"]): + pcm = V.pcm_f32(path) + c["pcm"] = pcm[:pcm_frames * 4] + c["pcmBytes"] = len(pcm) + return c + + +def generate(ctx): + tmp = tempfile.mkdtemp(prefix="avifx_") + ff = lambda *a: V.ffmpeg(list(a), cwd=tmp) + ff(*SRC, *sine(44100, 2), "-t", "1", "-c:v", "mjpeg", "-q:v", "3", "-c:a", "pcm_s16le", "mjpeg_pcm.avi") + ff(*SRC, *sine(22050), "-t", "1", "-c:v", "mjpeg", "-q:v", "5", "-c:a", "adpcm_ima_wav", "mjpeg_ima.avi") + ff(*SRC, *sine(44100), "-t", "1", "-r", "25", "-c:v", "mpeg1video", "-b:v", "500k", "-c:a", "mp2", "mpeg1_mp2.avi") + ff(*SRC, "-t", "0.5", "-c:v", "rawvideo", "-pix_fmt", "bgr24", "bgr24.avi") + ff(*SRC, "-t", "0.5", "-c:v", "rawvideo", "-pix_fmt", "bgra", "bgra.avi") + ff(*SRC, "-t", "0.5", "-c:v", "rawvideo", "-pix_fmt", "yuv420p", "i420.avi") + ff(*SRC, *sine(8000), "-t", "1", "-c:v", "mjpeg", "-c:a", "pcm_u8", "pcm_u8.avi") + full = open(os.path.join(tmp, "mjpeg_pcm.avi"), "rb").read() + idx1 = rename(full, b"indx", b"JUNK") + open(os.path.join(tmp, "idx1_only.avi"), "wb").write(idx1) + open(os.path.join(tmp, "no_index.avi"), "wb").write(rename(idx1, b"idx1", b"JUNK")) + open(os.path.join(tmp, "odml.avi"), "wb").write(add_odml(full)) + cases = [case(tmp, "mjpeg_pcm.avi"), case(tmp, "mjpeg_ima.avi"), case(tmp, "mpeg1_mp2.avi"), + case(tmp, "bgr24.avi", rgba=True), case(tmp, "bgra.avi", rgba=True), case(tmp, "i420.avi"), + case(tmp, "pcm_u8.avi"), case(tmp, "idx1_only.avi"), case(tmp, "no_index.avi"), + case(tmp, "odml.avi")] + cases.append({"name": "truncated.avi", "data": full[: len(full) * 6 // 10], "truncated": True}) + ctx.emit("avi_cases", cases) diff --git a/tools/fixtures/flac_enc.py b/tools/fixtures/flac_enc.py new file mode 100644 index 0000000..19cf672 --- /dev/null +++ b/tools/fixtures/flac_enc.py @@ -0,0 +1,89 @@ +# FLAC encoder fixtures (tools/fixtures.py): our encoder runs in the fixture step (tools/fixtures/_audio.py +# encode_luau_many) on test signals; every output must pass `flac -t` (which also checks the decoded PCM against the +# STREAMINFO MD5), and that MD5 must equal the MD5 of the input quantized here, so the stream is bit-exact. The level +# sweep is compared in size with `flac -` (libFLAC 1.5, --no-padding --no-seektable). +# tests/gen/flac_enc.luau { name, sig, opts, bits, channels, frames, flacTest, md5, wantMd5, size, refSize?, data } +# tests/gen/flac_enc_sigs.luau { [sig] = { rate, channels, frames, data (f32le) } }: the inputs +import hashlib, importlib.util, os + +_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 = ["src/Formats/audio/flac", "src/Formats/codecs/Pcm", "src/Formats/core/Md5.luau"] + + +def pcm_bytes(samples, bits): + s = 2 ** (bits - 1) + nb = (bits + 7) // 8 + out = bytearray() + for v in samples: + q = max(-s, min(s - 1, int(__import__("math").floor(v * s + 0.5)))) + out += (q & ((1 << (8 * nb)) - 1)).to_bytes(nb, "little") + return bytes(out) + + +def generate(ctx): + sigs = {} + + def sig(kind, ch, frames, rate=44100): + name = "flacsig_%s_%d_%d_%d" % (kind, ch, frames, rate) + if name not in sigs: + samples = A.from_f32le(A.f32le(A.signal(kind, rate, ch, frames, seed=frames + ch))) # f32-rounded + sigs[name] = (samples, rate, ch) + return name + + cases = [] # (name, sigmod, bits, opts_lua, ref_level) + for level in range(9): + cases.append(("L%d-music-st16" % level, sig("music", 2, 20000), 16, "{ level = %d, bits = 16 }" % level, level)) + cases.append(("L%d-noise-mono24" % level, sig("noise", 1, 9000), 24, "{ level = %d, bits = 24 }" % level, level)) + cases.append(("L%d-sweep-6ch8" % level, sig("sweep", 6, 5000, 48000), 8, "{ level = %d, bits = 8 }" % level, level)) + for kind in ("sine", "silence", "loud", "square"): + for ch in (1, 2): + for bits in (8, 16, 24): + cases.append(("%s-%dch-%d" % (kind, ch, bits), sig(kind, ch, 4500), bits, "{ bits = %d }" % bits, None)) + for level in (0, 5, 8): + for n in (1, 15, 100, 1153, 4097): + cases.append(("L%d-len%d" % (level, n), sig("music", 2, n), 16, "{ level = %d }" % level, None)) + for bs in (192, 576, 1000, 4608, 16): + cases.append(("bs%d" % bs, sig("music", 2, 7000), 16, "{ blockSize = %d }" % bs, None)) + cases.append(("bits12-22k", sig("music", 1, 6000, 22050), 12, "{ bits = 12 }", None)) + cases.append(("bits20-96k", sig("sweep", 2, 6000, 96000), 20, "{ bits = 20, level = 8 }", None)) + cases.append(("rate-11111", sig("sine", 2, 3000, 11111), 16, "nil", None)) + cases.append(("seek-1s", sig("music", 2, 30000), 16, "{ seekInterval = 0.25 }", None)) + cases.append(("padding", sig("sine", 1, 1000), 16, "{ padding = 100 }", None)) + + ctx.emit("flac_enc_sigs", {n: {"rate": r, "channels": c, "frames": len(x) // c, "data": A.f32le(x)} for n, (x, r, c) in sigs.items()}) + outs = A.encode_luau_many(ctx, "audio/flac", [(c[1], c[3]) for c in cases], "flac_enc_sigs") + files = {"c%03d.flac" % i: o for i, o in enumerate(outs)} + script = 'for f in c*.flac; do r=$(flac -s -t "$f" 2>&1); echo "$f|$?|$(metaflac --show-md5sum "$f")|$(echo $r | tr "\\n" " ")"; done' + report = A.shell_many(ctx, "flac", files, script).decode(errors="replace") + rows = {} + for line in report.strip().split("\n"): + f, rc, md5, msg = line.split("|", 3) + rows[f] = (int(rc), md5.strip(), msg.strip()) + # libFLAC reference sizes for the level sweep + refs = {} + wavs = {} + for i, c in enumerate(cases): + if c[4] is not None: + samples, rate, ch = sigs[c[1]] + wavs["r%03d.raw" % i] = pcm_bytes(samples, c[2]) + wavs["r%03d.arg" % i] = ("-%d --channels=%d --bps=%d --sample-rate=%d" % (c[4], ch, c[2], rate)).encode() + script = ('for i in r*.raw; do rm -f out.flac; flac -s $(cat "${i%.raw}.arg") --force-raw-format --endian=little --sign=signed ' + '--no-padding --no-seektable -f -o out.flac "$i"; echo "$i $(stat -c %s out.flac)"; done') + for line in A.shell_many(ctx, "flac", wavs, script).decode().strip().split("\n"): + f, size = line.split() + refs[int(f[1:4])] = int(size) + emitted = [] + for i, (name, sigmod, bits, opts, lvl) in enumerate(cases): + samples, rate, ch = sigs[sigmod] + rc, md5, msg = rows["c%03d.flac" % i] + want = hashlib.md5(pcm_bytes(samples, bits)).hexdigest() + e = {"name": name, "sig": sigmod, "opts": opts, "bits": bits, "channels": ch, "frames": len(samples) // ch, + "flacTest": "" if rc == 0 else (msg or "rc %d" % rc), "md5": md5, "wantMd5": want, "size": len(outs[i]), + "data": outs[i]} + if i in refs: + e["refSize"] = refs[i] + emitted.append(e) + ctx.emit("flac_enc", emitted) diff --git a/tools/fixtures/isobmff.py b/tools/fixtures/isobmff.py new file mode 100644 index 0000000..4239ca6 --- /dev/null +++ b/tools/fixtures/isobmff.py @@ -0,0 +1,89 @@ +# containers/IsoBmff fixtures (tools/fixtures.py): small files from ffmpeg / MP4Box / avifenc (nix) with ffprobe's +# packet lists as the reference. +# tests/gen/isobmff.luau { cases = { { name, data, streams = { { codec, kind, timescale, width?, height?, +# sampleRate?, channels?, extradata }, ... }, packets = { { stream, pos, size, dts, pts, key }, +# ... } } }, tagged = { data, tags, cover }, avif = { { name, data, width, height, alpha } } } +import json, os, shutil, subprocess, tempfile + +PKGS = ["ffmpeg", "gpac", "libavif"] + + +def sh(ctx, script, cwd): + return ctx.nix(PKGS, ["sh", "-c", "cd '%s' && %s" % (cwd, script)]) + + +def probe(ctx, path, cwd): + out = sh(ctx, "ffprobe -v error -ignore_editlist 1 -show_streams -show_packets -of json '%s'" % path, cwd) + j = json.loads(out) + streams = [] + for s in j["streams"]: + kind = s["codec_type"] + if kind == "video" and s.get("disposition", {}).get("attached_pic"): + continue + tb = s["time_base"].split("/") + e = {"codec": s["codec_name"], "kind": kind, "timescale": int(tb[1]), "index": s["index"], + "extradata": int(s.get("extradata_size", 0))} + if kind == "video": + e["width"], e["height"] = s["width"], s["height"] + if kind == "audio": + e["sampleRate"], e["channels"] = int(s["sample_rate"]), s["channels"] + streams.append(e) + index = {s["index"]: i + 1 for i, s in enumerate(streams)} + packets = [] + for p in j["packets"]: + if p["stream_index"] not in index: + continue + packets.append({"stream": index[p["stream_index"]], "pos": int(p["pos"]), "size": int(p["size"]), + "dts": int(p["dts"]), "pts": int(p["pts"]), "key": "K" in p["flags"]}) + for s in streams: + del s["index"] + return streams, packets + + +def generate(ctx): + d = tempfile.mkdtemp(prefix="isobmff-fx-") + try: + src_v = "-f lavfi -i testsrc=size=64x48:rate=10 -t 1.2" + src_a = "-f lavfi -i sine=frequency=440:sample_rate=44100 -t 1.0" + steps = [ + ("h264_aac.mp4", "ffmpeg -v error %s %s -c:v libx264 -bf 2 -g 5 -pix_fmt yuv420p -c:a aac -b:a 64k -ac 2 h264_aac.mp4" % (src_v, src_a)), + ("faststart.mp4", "ffmpeg -v error -i h264_aac.mp4 -c copy -movflags +faststart faststart.mp4"), + ("mjpeg_pcm.mov", "ffmpeg -v error %s %s -c:v mjpeg -c:a pcm_s16be mjpeg_pcm.mov" % (src_v, src_a)), + ("hevc.mp4", "ffmpeg -v error %s -c:v libx265 -x265-params log-level=none -tag:v hvc1 hevc.mp4" % src_v), + ("frag.mp4", "ffmpeg -v error -i h264_aac.mp4 -c copy -movflags frag_keyframe+empty_moov+default_base_moof frag.mp4"), + ("mp4box_frag.mp4", "MP4Box -quiet -frag 300 -out mp4box_frag.mp4 h264_aac.mp4 >/dev/null 2>&1"), + ("stz2_co64.mp4", "MP4Box -quiet -add h264_aac.mp4#video -add h264_aac.mp4#audio:stz2 -co64 -new stz2_co64.mp4 >/dev/null 2>&1"), + ("alac.m4a", "ffmpeg -v error %s -c:a alac alac.m4a" % src_a), + ] + cases = [] + for name, cmd in steps: + sh(ctx, cmd, d) + streams, packets = probe(ctx, name, d) + with open(os.path.join(d, name), "rb") as f: + data = f.read() + cases.append({"name": name, "data": data, "streams": streams, "packets": packets}) + # tags + cover + sh(ctx, "ffmpeg -v error -f lavfi -i color=red:size=8x8 -frames:v 1 -update 1 cover.png", d) + tags = {"title": "Test Title", "artist": "Some Artist", "album": "An Album", "date": "2024", + "genre": "Electronic", "comment": "a comment", "composer": "Composer X", "album_artist": "AA"} + meta = " ".join("-metadata %s='%s'" % (k, v) for k, v in tags.items()) + sh(ctx, "ffmpeg -v error %s -i cover.png -map 0 -map 1 -c:a aac -b:a 48k -c:v png -disposition:v attached_pic -t 1 %s -metadata track=3/12 -metadata disc=1/2 tagged.m4a" % (src_a, meta), d) + with open(os.path.join(d, "tagged.m4a"), "rb") as f: + tagged = f.read() + with open(os.path.join(d, "cover.png"), "rb") as f: + cover = f.read() + want = {"title": "Test Title", "artist": "Some Artist", "album": "An Album", "date": "2024", + "genre": "Electronic", "comment": "a comment", "composer": "Composer X", "albumartist": "AA", + "track": "3", "tracktotal": "12", "disc": "1", "disctotal": "2"} + # AVIF stills (libavif): plain and with alpha + avif = [] + sh(ctx, "ffmpeg -v error -f lavfi -i testsrc=size=40x24 -frames:v 1 still.png && " + "ffmpeg -v error -f lavfi -i 'testsrc=size=40x24,format=rgba,geq=r=r(X\\,Y):a=X*6' -frames:v 1 alpha.png", d) + for name, png, alpha in (("still.avif", "still.png", False), ("alpha.avif", "alpha.png", True)): + sh(ctx, "avifenc -q 60 -s 10 %s %s >/dev/null" % (png, name), d) + with open(os.path.join(d, name), "rb") as f: + avif.append({"name": name, "data": f.read(), "width": 40, "height": 24, "alpha": alpha}) + ctx.emit("isobmff", {"cases": cases, "tagged": {"data": tagged, "tags": want, "cover": len(cover)}, + "avif": avif}) + finally: + shutil.rmtree(d, ignore_errors=True) diff --git a/tools/fixtures/it.py b/tools/fixtures/it.py new file mode 100644 index 0000000..493d525 --- /dev/null +++ b/tools/fixtures/it.py @@ -0,0 +1,192 @@ +# IT fixtures (tools/fixtures.py): generated Impulse Tracker modules exercising instruments (new note actions, +# duplicate checks, envelopes, filters, sustain loops, auto-vibrato, keymaps), sample mode with the IT effects, Amiga +# slides with old effects, and IT 2.14 / 2.15 compressed, 16-bit and stereo samples, rendered by openmpt123. +# tests/gen/it_cases.luau { name, data (the module), ref (features of openmpt's render, tools/fixtures/_tracker.py), +# duration (openmpt's song length), plain (for "compressed": the same song uncompressed) } +import os, sys + +# 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, K, L, M, N, O, P, Q, R, S, Tt, U, V, W, X, Y, Z = range(1, 27) +OFF, CUT, FADE = 255, 254, 253 + + +def empty(ch, rows=64): + return [[(0, 0, None, 0, 0) for _ in range(ch)] for _ in range(rows)] + + +def put(p, row, ch, note=0, ins=0, vol=None, cmd=0, param=0): + p[row][ch] = (note, ins, vol, cmd, param) + + +def samples(compress=None): + return [ + {"name": "sine", "data": T.s8(T.synth("sine", 64, 64)), "volume": 64, "c5": 8363, "loop": (0, 64, False), "compress": compress}, + {"name": "square", "data": T.s8(T.synth("square", 64, 64, 0.5)), "volume": 48, "c5": 16726, "loop": (0, 64, False), "gv": 48}, + {"name": "saw16", "data": T.s16(T.synth("saw", 128, 64, 0.6)), "bits": 16, "volume": 64, "c5": 11025, "loop": (0, 128, False), + "compress": compress}, + {"name": "noise", "data": T.s8(T.synth("noise", 6000, 1, 0.7, decay=1500)), "volume": 60, "c5": 8363, "pan": 16}, + {"name": "ping sus", "data": T.s8(T.synth("tri", 400, 50, 0.8)), "volume": 64, "c5": 9000, "sus": (100, 300, True), + "loop": (0, 400, False), "vib": (8, 16, 4, 0)}, + {"name": "stereo", "data": T.s16(T.synth("sine", 256, 32, 0.6) + T.synth("saw", 256, 64, 0.5)), "bits": 16, "stereo": True, + "volume": 56, "c5": 8363, "loop": (0, 256, True), "compress": compress}, + {"name": "pluck", "data": T.s8(T.synth("saw", 3000, 40, 0.8, decay=900)), "volume": 64, "c5": 8363}, + ] + + +def keymap(sample, transpose=0, split=None): + km = [] + for n in range(120): + smp = sample if split is None or n < split[0] else split[1] + km.append((max(0, min(119, n + transpose)), smp)) + return km + + +def instruments(): + return [ + {"name": "nna cont", "nna": 1, "fadeout": 256, "keymap": keymap(7), + "volenv": {"points": [(0, 64), (10, 48), (40, 0)]}}, + {"name": "nna off", "nna": 2, "fadeout": 128, "keymap": keymap(1), + "volenv": {"points": [(0, 0), (3, 64), (8, 40), (20, 30)], "sustain": (2, 3)}}, + {"name": "nna fade dct", "nna": 3, "dct": 1, "dca": 0, "fadeout": 64, "keymap": keymap(2)}, + {"name": "pan pitch", "fadeout": 512, "keymap": keymap(3, 12), "pan": 48, "pps": 16, "ppc": 60, + "panenv": {"points": [(0, -32), (16, 32), (32, -32)], "loop": (0, 2)}, + "pitchenv": {"points": [(0, 0), (10, 12), (20, -12), (30, 0)], "loop": (1, 2)}}, + {"name": "filter", "keymap": keymap(3), "ifc": 128 + 40, "ifr": 128 + 64, "fadeout": 300, + "pitchenv": {"points": [(0, -32), (30, 32), (60, -32)], "loop": (0, 2), "filter": True}}, + {"name": "sus loop", "keymap": keymap(5), "fadeout": 400, "gbv": 96}, + {"name": "split stereo", "keymap": keymap(6, 0, (60, 1)), "fadeout": 200, + "volenv": {"points": [(0, 64), (5, 32), (10, 64), (15, 32)], "sustain": (0, 3), "loop": (1, 2)}}, + ] + + +def song_instruments(compress=None): + a, b = empty(5), empty(5) + # new note actions: continue / note off / fade, with the duplicate check cutting same-note repeats + for i, n in enumerate((61, 64, 68, 73)): + put(a, i * 4, 0, n, 1) + put(a, i * 4, 1, n - 12, 2) + put(a, 16, 1, 0, 0, None, S, 0x71) + put(a, 20, 1, 49, 2) + put(a, 22, 1, 0, 0, None, S, 0x73) + put(a, 24, 1, 56, 2) + put(a, 28, 1, OFF) + for r in (0, 4, 8, 9, 12, 16): + put(a, r, 2, 61 if r != 12 else 64, 3) + put(a, 20, 2, 0, 0, None, S, 0x70) + put(a, 24, 2, 61, 3, None, S, 0x75) + put(a, 26, 2, 66, 3) + put(a, 30, 2, FADE) + # panning / pitch envelopes, pitch-pan separation, instrument pan + put(a, 32, 0, 37, 4) + put(a, 32, 1, 61, 4) + put(a, 40, 1, 73, 4, None, S, 0x7B) + put(a, 44, 1, 0, 0, None, S, 0x7C) + put(a, 48, 0, OFF) + put(a, 56, 1, CUT) + # filters: instrument cutoff + resonance, filter envelope, Zxx + put(a, 36, 3, 49, 5) + put(a, 44, 3, 0, 0, None, Z, 0x20) + put(a, 48, 3, 0, 0, None, Z, 0x60) + put(a, 52, 3, 0, 0, None, Z, 0x88) + put(a, 60, 3, OFF) + # sustain loop + ping-pong, auto-vibrato, instrument global volume, a stereo / mono key split + put(b, 0, 0, 61, 6) + put(b, 16, 0, OFF) + put(b, 0, 1, 49, 7) + put(b, 8, 1, 73, 7) + put(b, 16, 1, 49, 7, 32) + put(b, 24, 1, OFF) + put(b, 32, 1, 85, 7) + put(b, 8, 4, 61, 1, None, H, 0x44) + put(b, 12, 4, 61, 1, None, S, 0x77) + put(b, 20, 4, 0, 0, None, S, 0x78) + put(b, 40, 4, 61, 3, 0, M, 0x20) + put(b, 44, 4, 0, 0, None, N, 0x04) + put(b, 48, 4, 0, 0, None, N, 0x30) + return T.write_it("instruments", samples(compress), instruments(), [0, 1], [a, b], 5, speed=5, tempo=135, + pans=[16, 48, 32, 32, 40], mv=64) + + +def song_effects(linear=True, old=False, compat=False): + a, b = empty(4), empty(4) + put(a, 0, 0, 61, 1, 48, D, 0x00) + put(a, 4, 0, 0, 0, 70) + put(a, 5, 0, 0, 0, 80) + put(a, 8, 0, 0, 0, 88) + put(a, 12, 0, 0, 0, 99) + put(a, 16, 0, 0, 0, 110) + put(a, 20, 0, 0, 0, 120) + put(a, 24, 0, 49, 0, 196) + put(a, 28, 0, 0, 0, 205, H, 0x46) + put(a, 32, 0, 0, 0, 160) + put(a, 36, 0, 0, 0, None, Y, 0x48) + put(a, 44, 0, 0, 0, None, P, 0x08) + put(a, 48, 0, 0, 0, None, P, 0x30) + put(a, 52, 0, 0, 0, None, P, 0xF4) + put(a, 56, 0, 0, 0, None, X, 0xC0) + put(a, 0, 1, 49, 2, None, E, 0x04) + put(a, 4, 1, 0, 0, None, F, 0x10) + put(a, 8, 1, 0, 0, None, E, 0xF8) + put(a, 9, 1, 0, 0, None, F, 0xE8) + put(a, 12, 1, 49, 2, None, G, 0x08) + put(a, 13, 1, 61, 0, None, G, 0x00) + put(a, 16, 1, 0, 0, None, E, 0x00) + put(a, 20, 1, 56, 2, None, J, 0x37) + put(a, 24, 1, 0, 0, None, U, 0x88) + put(a, 28, 1, 0, 0, None, R, 0x46) + put(a, 32, 1, 0, 0, None, I, 0x31) + put(a, 36, 1, 0, 0, None, Q, 0x84) + put(a, 40, 1, 0, 0, None, K, 0x02) + put(a, 44, 1, 49, 2, None, L, 0x20) + put(a, 48, 1, 0, 0, None, O, 0x00) + put(a, 52, 1, 61, 4, None, O, 0x04) + put(a, 56, 1, 61, 4, None, S, 0xD3) + put(a, 60, 1, 61, 4, None, S, 0xC2) + put(a, 0, 2, 37, 3, None, V, 0x60) + put(a, 8, 2, 0, 0, None, W, 0x04) + put(a, 16, 2, 0, 0, None, W, 0x60) + put(a, 24, 2, 0, 0, None, Tt, 0x10 + 0x06) + put(a, 28, 2, 0, 0, None, Tt, 0x04) + put(a, 32, 2, 0, 0, None, Tt, 0x90) + put(a, 36, 2, 0, 0, None, S, 0xB0) + put(a, 38, 2, 0, 0, None, S, 0xB1) + put(a, 40, 2, 0, 0, None, S, 0xE2) + put(a, 44, 2, 0, 0, None, S, 0x63) + put(a, 48, 2, 0, 0, None, A, 0x04) + put(a, 52, 2, 0, 0, None, M, 0x30) + put(a, 56, 2, 0, 0, None, N, 0x02) + put(a, 0, 3, 73, 7, None, S, 0x91) + put(a, 16, 3, 73, 7, None, X, 0x40) + put(a, 32, 3, 61, 3, None, S, 0x8C) + put(b, 0, 0, 61, 1) + put(b, 0, 1, 64, 2) + put(b, 0, 2, 68, 3) + put(b, 8, 0, CUT) + put(b, 12, 1, OFF) + put(b, 16, 2, FADE) + put(b, 20, 3, 61, 7, None, B, 0x01) + return T.write_it("effects", samples(), None, [0, 1], [a, b], 4, speed=4, tempo=140, linear=linear, old=old, + compat=compat, pans=[0, 64, 20, 44], vols=[64, 48, 64, 56], gv=112, mv=80) + + +def generate(ctx): + cases = [] + plain = song_instruments() + for nm, data in (("instruments", plain), ("effects", song_effects()), ("amiga old", song_effects(False, True, True)), + ("compressed 2.14", song_instruments(214)), ("compressed 2.15", song_instruments(215))): + ref = T.reference(ctx, data, "it") + c = {"name": nm, "data": data, "ref": ref, "duration": ref["duration"]} + if nm.startswith("compressed"): + c["plain"] = plain + cases.append(c) + ctx.emit("it_cases", cases) diff --git a/tools/fixtures/m4a.py b/tools/fixtures/m4a.py new file mode 100644 index 0000000..8ffe43e --- /dev/null +++ b/tools/fixtures/m4a.py @@ -0,0 +1,198 @@ +# M4A / AAC / ALAC / CAF fixtures (tools/fixtures.py). Reference tools through nix: ffmpeg (AAC + ALAC encoders and +# decoders, the CAF muxer), fdkaac (Fraunhofer's encoder: plain and HE-AAC), MP4Box (-info on our files). +# tests/gen/m4a_alac.luau ALAC in M4A / CAF from ffmpeg: { name, data, container, channels, rate, bits, frames, +# crc } where crc is the CRC-32 of the source integers as little-endian int32 +# tests/gen/m4a_aac.luau AAC from ffmpeg / faac (M4A, ADTS, CAF): { name, data, container, channels, rate, frames, +# ref } with ref = ffmpeg's float decode (f32le) of the file +# tests/gen/m4a_he.luau HE-AAC / HE-AACv2 from fdkaac: { name, data, rate (the SBR output rate), ps } +# tests/gen/m4a_ours.luau our writers' files (tools/fixtures/_m4a_encode.luau over tests/audio/_encode_cases.luau) +# checked by ffmpeg: { name, crc (of our bytes), ffmpeg (decodes bit-exactly), frames, +# tags (ffprobe's view), mp4box (MP4Box -info exit status 0) } +import importlib.util, json, math, os, shutil, struct, subprocess, tempfile, zlib + +# the shared signal module, loaded by path (tools/fixtures/ must not go on sys.path: xml.py there would shadow xml) +_spec = importlib.util.spec_from_file_location("_m4a_signal", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_m4a_signal.py")) +_sig = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(_sig) +signal, pack, wav = _sig.signal, _sig.pack, _sig.wav + +INPUTS = ["src/Formats/audio/m4a", "src/Formats/audio/caf", "src/Formats/codecs/Alac", "src/Formats/containers/IsoBmff", + "tests/audio/_signal.luau", "tests/audio/_encode_cases.luau", "tools/fixtures/_m4a_encode.luau", + "tools/fixtures/_m4a_signal.py"] +PKGS = ["ffmpeg", "fdk-aac-encoder", "gpac"] + + +def run(ctx, cmd, cwd): + return ctx.nix(PKGS, ["sh", "-c", "cd '%s' && %s" % (cwd, cmd)]) + + +def crc_ints(ints): + return zlib.crc32(struct.pack("<%di" % len(ints), *ints)) + + +def music(frames, channels, rate, seed): + """a float test signal for the lossy codecs: tones with vibrato, a chord, noise bursts and clicks (transients)""" + rng = __import__("random").Random(seed) + out = [] + for i in range(frames): + t = i / rate + for c in range(channels): + v = 0.25 * math.sin(2 * math.pi * (220 * (c + 1)) * t + 3 * math.sin(2 * math.pi * 5 * t)) + v += 0.12 * math.sin(2 * math.pi * 660 * t) + 0.08 * math.sin(2 * math.pi * 1320.5 * t + c) + v += 0.05 * math.sin(2 * math.pi * (5000 + 300 * c) * t) + if (i // (rate // 8)) % 3 == 1: + v += 0.15 * (rng.random() * 2 - 1) + if i % (rate // 3) < 40: + v += 0.6 * (1 - (i % (rate // 3)) / 40) * (1 if (i // 7) % 2 else -1) + out.append(max(-32768, min(32767, int(round(v * 20000))))) + return out + + +def adts_to_caf(adts): + frames, p = [], 0 + while p + 7 <= len(adts): + b1, b2, b3, b4, b5 = adts[p + 1], adts[p + 2], adts[p + 3], adts[p + 4], adts[p + 5] + hs = 7 if b1 & 1 else 9 + size = ((b3 & 3) << 11) | (b4 << 3) | (b5 >> 5) + frames.append(adts[p + hs:p + size]) + sfi, ch, aot = (b2 >> 2) & 15, ((b2 & 1) << 2) | (b3 >> 6), (b2 >> 6) + 1 + p += size + rate = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350][sfi] + asc = struct.pack(">H", (aot << 11) | (sfi << 7) | (ch << 3)) + dsi = b"\x05" + bytes([len(asc)]) + asc + dcd = b"\x04" + bytes([13 + len(dsi)]) + bytes([0x40, 0x15, 0, 0, 0]) + struct.pack(">II", 0, 0) + dsi + esd = b"\x03" + bytes([3 + len(dcd) + 3]) + b"\x00\x00\x00" + dcd + b"\x06\x01\x02" + + def ber(n): + out = [n & 127] + n >>= 7 + while n: + out.insert(0, 128 | (n & 127)) + n >>= 7 + return bytes(out) + + def chunk(t, body): + return t + struct.pack(">q", len(body)) + body + + desc = struct.pack(">d4sIIIII", rate, b"aac ", 2, 0, 1024, ch, 0) + pakt = struct.pack(">qqii", len(frames), len(frames) * 1024, 0, 0) + b"".join(ber(len(f)) for f in frames) + data = b"\x00\x00\x00\x00" + b"".join(frames) + return b"caff\x00\x01\x00\x00" + chunk(b"desc", desc) + chunk(b"kuki", b"\x00\x00\x00\x00" + esd) + chunk(b"pakt", pakt) + chunk(b"data", data) + + +def generate(ctx): + d = tempfile.mkdtemp(prefix="m4a-fx-") + try: + # --- ALAC from ffmpeg: lossless, the decode must equal the source integers + alac = [] + for name, frames, ch, rate, bits, container in ( + ("alac16_stereo.m4a", 10000, 2, 44100, 16, "m4a"), + ("alac16_mono.m4a", 4097, 1, 8000, 16, "m4a"), + ("alac24_stereo.m4a", 6000, 2, 96000, 24, "m4a"), + ("alac16_6ch.m4a", 5000, 6, 48000, 16, "m4a"), + ("alac16_stereo.caf", 9000, 2, 44100, 16, "caf"), + ): + ints = signal(frames, ch, bits, 11 + frames) + with open(os.path.join(d, "in.wav"), "wb") as f: + f.write(wav(ints, ch, rate, bits)) + fmt = "-sample_fmt s32p" if bits == 24 else "" + run(ctx, "ffmpeg -v error -y -i in.wav -c:a alac %s %s" % (fmt, name), d) + with open(os.path.join(d, name), "rb") as f: + data = f.read() + alac.append({"name": name, "data": data, "container": container, "channels": ch, "rate": rate, + "bits": bits, "frames": frames, "crc": crc_ints(ints)}) + ctx.emit("m4a_alac", alac) + + # --- AAC from ffmpeg / faac: our decode against ffmpeg's float decode + aac = [] + specs = ( + # name, frames, channels, rate, encoder command (in.wav -> name) + ("aac_stereo_128k.m4a", 60000, 2, 44100, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 128k -aac_pns 0 %s"), + ("aac_mono_22k.m4a", 30000, 1, 22050, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 48k %s"), + ("aac_51_48k.m4a", 30000, 6, 48000, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 256k %s"), + ("aac_tools_40k.m4a", 50000, 2, 44100, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 40k -aac_pns 1 -aac_is 1 -aac_ms 1 -aac_tns 1 %s"), + ("aac_8k_mono.m4a", 12000, 1, 8000, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 16k %s"), + ("aac_96k.m4a", 30000, 2, 96000, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 192k %s"), + ("aac_stereo.aac", 40000, 2, 44100, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 96k -aac_pns 0 -f adts %s"), + ("fdk_stereo.aac", 40000, 2, 44100, "fdkaac -S -b 96000 -f 2 -o %s in.wav"), + ("fdk_mono_32k.aac", 20000, 1, 32000, "fdkaac -S -b 48000 -f 2 -o %s in.wav"), + ("fdk_stereo.m4a", 40000, 2, 48000, "fdkaac -S -b 128000 -o %s in.wav"), + ("aac_stereo.caf", 30000, 2, 44100, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 96k -f adts %s.adts"), + ) + for name, frames, ch, rate, cmd in specs: + ints = music(frames, ch, rate, frames + ch) + with open(os.path.join(d, "in.wav"), "wb") as f: + f.write(wav(ints, ch, rate, 16)) + run(ctx, cmd % name, d) + if name.endswith(".caf"): + # ffmpeg cannot write AAC in CAF: wrap its ADTS frames ourselves (desc, kuki esds, pakt, data) + with open(os.path.join(d, name + ".adts"), "rb") as f: + adts = f.read() + with open(os.path.join(d, name), "wb") as f: + f.write(adts_to_caf(adts)) + with open(os.path.join(d, name), "rb") as f: + data = f.read() + ref = run(ctx, "ffmpeg -v error -i %s -f f32le -c:a pcm_f32le -" % name, d) + container = "caf" if name.endswith(".caf") else ("adts" if name.endswith(".aac") else "m4a") + aac.append({"name": name, "data": data, "container": container, "channels": ch, "rate": rate, + "frames": len(ref) // (4 * ch), "ref": ref}) + ctx.emit("m4a_aac", aac) + # HE-AAC (SBR) and HE-AACv2 (SBR + PS) from fdkaac: we decode the AAC-LC core at the core rate + he = [] + for name, frames, ch, rate, prof, br in (("he_aac.m4a", 48000, 2, 44100, 5, 48000), ("he_aac_v2.m4a", 48000, 2, 44100, 29, 32000), ("he_aac.aac", 48000, 2, 44100, 5, 48000)): + ints = music(frames, ch, rate, 99) + with open(os.path.join(d, "in.wav"), "wb") as f: + f.write(wav(ints, ch, rate, 16)) + run(ctx, "fdkaac -S -p %d -b %d %s -o %s in.wav" % (prof, br, "-f 2" if name.endswith(".aac") else "", name), d) + with open(os.path.join(d, name), "rb") as f: + he.append({"name": name, "data": f.read(), "rate": rate, "ps": prof == 29}) + ctx.emit("m4a_he", he) + + # --- our writers, checked by ffmpeg / ffprobe / MP4Box + luau = os.environ.get("LUAU") or shutil.which("luau") + if luau: + out = subprocess.run([luau, "tools/fixtures/_m4a_encode.luau"], capture_output=True, check=True, cwd=ctx.root).stdout + else: + out = ctx.nix("luau", ["luau", os.path.join(ctx.root, "tools/fixtures/_m4a_encode.luau")]) + ours = [] + meta = { + # name -> frames, channels, bits, seed (tests/audio/_encode_cases.luau) + "ours_alac16_stereo": (4096 * 3 + 1234, 2, 16, 1), "ours_alac16_mono": (5000, 1, 16, 2), + "ours_alac24_stereo": (9000, 2, 24, 3), "ours_alac16_6ch": (4500, 6, 16, 4), + "ours_alac20_stereo": (3000, 2, 20, 5), "ours_caf_alac16": (7000, 2, 16, 6), + "ours_caf_pcm16": (3000, 2, 16, 7), "ours_caf_pcm24": (2000, 1, 24, 8), + } + for line in out.decode().split("\n"): + if not line.strip(): + continue + name, hx = line.split(" ", 1) + if hx.startswith("ERROR"): + raise RuntimeError("m4a fixtures: our encoder failed on %s: %s" % (name, hx)) + data = bytes.fromhex(hx) + ext = "caf" if "caf" in name else "m4a" + path = name + "." + ext + with open(os.path.join(d, path), "wb") as f: + f.write(data) + frames, ch, bits, seed = meta[name] + ints = signal(frames, ch, bits, seed) + wide = bits > 16 + want = pack([v << (32 - bits) for v in ints] if wide else ints, 32 if wide else 16) + got = run(ctx, "ffmpeg -v error -i %s -f %s -" % (path, "s32le" if wide else "s16le"), d) + fbytes = (4 if wide else 2) * ch + # ffmpeg's CAF reader drops the pakt remainder from a partial last ALAC packet (also on its own files): + # accept its output when it is an exact prefix of ours + ok = got == want or (ext == "caf" and len(got) > 0 and want.startswith(got)) + probe = json.loads(run(ctx, "ffprobe -v error -show_format -show_streams -of json %s" % path, d)) + tags = {k.lower(): v for k, v in probe["format"].get("tags", {}).items()} + mp4box = True + if ext == "m4a": + try: + run(ctx, "MP4Box -info %s >/dev/null 2>&1" % path, d) + except subprocess.CalledProcessError: + mp4box = False + ours.append({"name": name, "crc": zlib.crc32(data), "ffmpeg": ok, "frames": len(got) // fbytes, + "tags": tags, "mp4box": mp4box, + "codec": probe["streams"][0]["codec_name"]}) + ctx.emit("m4a_ours", ours) + finally: + shutil.rmtree(d, ignore_errors=True) diff --git a/tools/fixtures/midi.py b/tools/fixtures/midi.py new file mode 100644 index 0000000..d1f47c5 --- /dev/null +++ b/tools/fixtures/midi.py @@ -0,0 +1,72 @@ +# MIDI fixtures (tools/fixtures.py). Reference parses from python mido (tools/fixtures/_midi_ref.py, run in a nix +# python with mido) plus hand-made byte strings for what mido does not write. +# tests/gen/midi_cases.luau { { name, data, type, division, tracks = { { {tick, type, channel, data, meta} } }, +# length?, times?, exact? } }: channel / meta = -1 when absent; exact = the bytes are +# what an encoder with running status writes (mido's own output) +# tests/gen/midi_bad.luau { { name, data, code } }: crafted bad files and the Err code expected +# tests/gen/midi_trunc.luau { name, data }: a mido file cut short (lenient decode keeps the events, strict fails) +import json, struct + +INPUTS = ["tools/fixtures/_midi_ref.py"] + + +def vlq(v): + out = [v & 127] + v >>= 7 + while v: + out.insert(0, (v & 127) | 128) + v >>= 7 + return bytes(out) + + +def smf(tracks, fmt=0, division=96, extra=b""): + out = b"MThd" + struct.pack(">IHHh", 6, fmt, len(tracks), division) + extra + for body in tracks: + out += b"MTrk" + struct.pack(">I", len(body)) + body + return out + + +def generate(ctx): + ref = json.loads(ctx.python(["mido"], ctx.read("tools/fixtures/_midi_ref.py").decode())) + cases = [] + by_name = {} + for c in ref: + case = {"name": c["name"], "data": bytes.fromhex(c["hex"]), "type": c["type"], "division": c["division"], + "tracks": c["tracks"], "exact": True} + if "length" in c: + case["length"] = c["length"] + case["times"] = c["times"] + cases.append(case) + by_name[c["name"]] = case + + # running status across meta and escape events (mido's writer never relies on it), and an F7 escape + body = (b"\x00\x90\x3c\x40" + b"\x00\xff\x01\x01\x41" + b"\x10\x3c\x00" + b"\x00\xf7\x02\xf3\x01" + b"\x05\x3e\x7f" + + b"\x00\xff\x2f\x00") + cases.append({"name": "running-after-meta", "data": smf([body]), "type": 0, "division": 96, "exact": False, "tracks": [[ + [0, "noteOn", 0, [60, 64], -1], [0, "meta", -1, [0x41], 1], [16, "noteOn", 0, [60, 0], -1], + [16, "escape", -1, [0xF3, 0x01], -1], [21, "noteOn", 0, [62, 127], -1], [21, "meta", -1, [], 0x2F]]]}) + # an unknown chunk between MThd and MTrk, a longer MThd, and an RMID wrapper + f0 = by_name["format0"] + raw = f0["data"] + hdr, rest = raw[:14], raw[14:] + cases.append(dict(f0, name="unknown-chunk", exact=False, data=hdr + b"XFIH" + struct.pack(">I", 5) + b"abcde" + rest)) + long_hdr = b"MThd" + struct.pack(">I", 8) + raw[8:14] + b"\x00\x00" + rest + cases.append(dict(f0, name="long-mthd", exact=False, data=long_hdr)) + riff = b"RMID" + b"data" + struct.pack("IHHh", 6, 3, 0, 96), "code": "UNSUPPORTED"}, + {"name": "zero-division", "data": b"MThd" + struct.pack(">IHHh", 6, 0, 0, 0), "code": "CORRUPT"}, + {"name": "short-header", "data": b"MThd\x00\x00\x00\x06\x00", "code": "TRUNCATED"}, + {"name": "system-common", "data": smf([b"\x00\xf2\x01\x02"]), "code": "CORRUPT"}, + {"name": "rmid-without-data", "data": b"RIFF\x0c\x00\x00\x00RMIDLIST\x00\x00\x00\x00", "code": "CORRUPT"}, + ] + ctx.emit("midi_bad", bad) + f1 = by_name["format1"]["data"] + ctx.emit("midi_trunc", {"name": "format1-cut", "data": f1[: len(f1) * 3 // 5]}) diff --git a/tools/fixtures/mjpeg.py b/tools/fixtures/mjpeg.py new file mode 100644 index 0000000..258ca8a --- /dev/null +++ b/tools/fixtures/mjpeg.py @@ -0,0 +1,317 @@ +# Motion-JPEG fixtures for codecs/Jpeg (tools/fixtures.py): ffmpeg's mjpeg encoder (testsrc2 / mandelbrot sources, +# yuvj420p / yuvj422p / yuvj444p, odd sizes) split into its JPEG frames, and references for each frame: +# yuv CRC-32 of the yuv420p planes codecs/Jpeg must produce with { yuv = true }: libjpeg-turbo's own IDCT planes +# (TurboJPEG tj3DecompressToYUV8 through ctypes, the islow IDCT), cropped, 4:2:2 chroma row pairs averaged +# ((a + b + 1) >> 1), 4:4:4 chroma 2 x 2 averaged ((a + b + c + d + 2) >> 2): bit-exact +# rgba CRC-32 of djpeg -dct int (bit-exact) +# ff for the first frame of each stream: ffmpeg's own decode as yuvj420p and rgba (PSNR thresholds: ffmpeg's +# IDCT and its swscale conversions differ from libjpeg's; rgba for the small streams and one 320x240) +# Variants: frames written with ffmpeg's default (annex K) Huffman tables and their DHT segments stripped, as +# Motion-JPEG in AVI leaves them out; an AVI1 APP0 segment and junk after EOI; an interlaced frame (two fields, +# each its own half-height JPEG with an AVI1 segment of polarity 1, back to back). +# tests/gen/mjpeg_cases.luau { streams = { { name, width, height, sampling, frames = { { data, yuv, rgba } }, +# ff = { yuv, rgba? } } }, fields = { data, width, height, yuv, rgba, src } } +# tests/gen/mjpeg_enc.luau yuv420p sources and what tj3CompressFromYUV8 writes for them at a quality (our +# encoder must write the same bytes), with djpeg's CRC and ffmpeg's PSNR of that file +# tests/gen/mjpeg_bench.luau 320x240 and 640x480 frames (4:2:0, 4:2:2) and yuv420p sources +# Binary fields are base64 (JPEG data) or base64 of zlib data (raw planes / pixels, inflated with codecs/Deflate): +# Luau string literals of binary data cost ~3.7 bytes per byte, base64 1.33. +import base64, ctypes, math, os, shutil, subprocess, tempfile, zlib + +FF = ["-hide_banner", "-loglevel", "error", "-y"] + + +def b64(b): + return base64.b64encode(b).decode() + + +def z64(b): + return base64.b64encode(zlib.compress(b, 9)).decode() + + +def tool(ctx, pkg, name): + p = shutil.which(name) + if p: + return p + return ctx.nix(pkg, ["sh", "-c", "command -v " + name]).decode().strip() + + +def store(attr): + return subprocess.run(["nix", "build", "nixpkgs#" + attr, "--no-link", "--print-out-paths"], check=True, + capture_output=True, text=True).stdout.strip().split("\n")[0] + + +class TurboJpeg: + """the TurboJPEG 3 API (libjpeg-turbo) through ctypes: raw YUV planes in and out""" + + def __init__(self): + lib = ctypes.CDLL(os.path.join(store("libjpeg_turbo.out"), "lib", "libturbojpeg.so")) + lib.tj3Init.restype = ctypes.c_void_p + lib.tj3Init.argtypes = [ctypes.c_int] + lib.tj3Set.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int] + lib.tj3Get.argtypes = [ctypes.c_void_p, ctypes.c_int] + lib.tj3DecompressHeader.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_size_t] + lib.tj3DecompressToYUV8.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_size_t, ctypes.c_char_p, ctypes.c_int] + lib.tj3CompressFromYUV8.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int, ctypes.c_int, ctypes.c_int, + ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(ctypes.c_size_t)] + lib.tj3Free.argtypes = [ctypes.c_void_p] + self.lib = lib + self.dec = lib.tj3Init(1) + self.enc = lib.tj3Init(0) + + def planes(self, jpeg): + """-> w, h, subsamp (0 444, 1 422, 2 420), Y, Cb, Cr (TurboJPEG's unpadded-alignment plane layout)""" + L = self.lib + assert L.tj3DecompressHeader(self.dec, jpeg, len(jpeg)) == 0 + w, h, ss = L.tj3Get(self.dec, 5), L.tj3Get(self.dec, 6), L.tj3Get(self.dec, 4) + mw, mh = {0: (1, 1), 1: (2, 1), 2: (2, 2)}[ss] + pw, ph = -(-w // mw) * mw, -(-h // mh) * mh + cw, ch = pw // mw, ph // mh + out = ctypes.create_string_buffer(pw * ph + 2 * cw * ch) + assert L.tj3DecompressToYUV8(self.dec, jpeg, len(jpeg), out, 1) == 0 + raw = out.raw + return w, h, ss, (raw[:pw * ph], pw), (raw[pw * ph:pw * ph + cw * ch], cw, ch), (raw[pw * ph + cw * ch:], cw, ch) + + def yuv420(self, jpeg): + """what codecs/Jpeg { yuv = true } must produce for this frame""" + w, h, ss, (Y, pw), cb, cr = self.planes(jpeg) + out = bytearray() + for y in range(h): + out += Y[y * pw:y * pw + w] + ow, oh = (w + 1) // 2, (h + 1) // 2 + for P, cw, ch in (cb, cr): + for y in range(oh): + if ss == 2: + out += P[y * cw:y * cw + ow] + elif ss == 1: + a = P[2 * y * cw:2 * y * cw + ow] + b = P[(2 * y + 1) * cw:(2 * y + 1) * cw + ow] if 2 * y + 1 < ch else a + out += bytes((p + q + 1) >> 1 for p, q in zip(a, b)) + else: + r0 = P[2 * y * cw:2 * y * cw + cw] + r1 = P[(2 * y + 1) * cw:(2 * y + 1) * cw + cw] if 2 * y + 1 < ch else r0 + row = bytearray() + for x in range(ow): + x1 = min(2 * x + 1, w - 1) + row.append((r0[2 * x] + r0[x1] + r1[2 * x] + r1[x1] + 2) >> 2) + out += row + return bytes(out) + + def compress420(self, yuv, w, h, quality): + """yuv420p (w x h luma) -> tj3CompressFromYUV8's JPEG; TurboJPEG wants the luma plane padded to even sizes""" + pw, ph = w + (w & 1), h + (h & 1) + Y = yuv[:w * h] + buf = bytearray() + for y in range(ph): + r = Y[min(y, h - 1) * w:min(y, h - 1) * w + w] + buf += r + r[-1:] * (pw - w) + buf += yuv[w * h:] + L = self.lib + L.tj3Set(self.enc, 3, quality) + L.tj3Set(self.enc, 4, 2) + p, n = ctypes.c_void_p(), ctypes.c_size_t(0) + assert L.tj3CompressFromYUV8(self.enc, bytes(buf), w, 1, h, ctypes.byref(p), ctypes.byref(n)) == 0 + data = ctypes.string_at(p, n.value) + L.tj3Free(p) + return data + + +def split(stream): + """a Motion-JPEG elementary stream -> its JPEG frames (SOI .. EOI)""" + frames, pos = [], 0 + while True: + s = stream.find(b"\xff\xd8", pos) + if s < 0: + return frames + p = s + 2 + while True: + m = stream[p + 1] + if m == 0xD9: + p += 2 + break + ln = (stream[p + 2] << 8) | stream[p + 3] + p += 2 + ln + if m == 0xDA: + while not (stream[p] == 0xFF and stream[p + 1] not in (0,) and not 0xD0 <= stream[p + 1] <= 0xD7): + p += 1 + frames.append(stream[s:p]) + pos = p + + +def strip_dht(jpeg): + out, pos = bytearray(jpeg[:2]), 2 + while pos < len(jpeg): + m = jpeg[pos + 1] + if m == 0xDA: + out += jpeg[pos:] + break + ln = (jpeg[pos + 2] << 8) | jpeg[pos + 3] + if m != 0xC4: + out += jpeg[pos:pos + 2 + ln] + pos += 2 + ln + return bytes(out) + + +def avi1(jpeg, polarity): + """an AVI1 APP0 segment right after SOI (polarity, 0, field size, field size less padding)""" + n = len(jpeg) + 18 + body = b"AVI1" + bytes([polarity, 0]) + n.to_bytes(4, "big") + n.to_bytes(4, "big") + return jpeg[:2] + b"\xff\xe0" + (len(body) + 2).to_bytes(2, "big") + body + jpeg[2:] + + +def generate(ctx): + work = tempfile.mkdtemp(prefix="formats-mjpeg-") + try: + _generate(ctx, work) + finally: + shutil.rmtree(work, ignore_errors=True) + + +def _generate(ctx, work): + ffmpeg = tool(ctx, "ffmpeg", "ffmpeg") + djpeg = os.path.join(os.path.dirname(ctx.nix("libjpeg_turbo", ["sh", "-c", "command -v djpeg"]).decode().strip()), "djpeg") + tj = TurboJpeg() + W = lambda n: os.path.join(work, n) + + def ff(*args): + subprocess.run([ffmpeg] + FF + list(args), check=True, capture_output=True) + + def source(src, w, h, frames, extra=()): + # a raw yuv420p / yuv444p source scaled to w x h (ffmpeg's lavfi sources only make even sizes) + sw, sh = w + (w & 1), h + (h & 1) + return ["-f", "lavfi", "-i", "%s=size=%dx%d:rate=25" % (src, sw, sh), "-frames:v", str(frames), + "-vf", "scale=%d:%d" % (w, h)] + list(extra) + + def rgba_crc(jpeg): + p = W("f.jpg") + open(p, "wb").write(jpeg) + r = subprocess.run([djpeg, "-dct", "int", "-pnm", p], check=True, capture_output=True).stdout + return zlib.crc32(rgba_of_pnm(r)) + + def rgba_of_pnm(d): + # djpeg's "P6\n \n255\n" + RGB -> RGBA + parts = d.split(maxsplit=3) + w, h = int(parts[1]), int(parts[2]) + rgb = d[len(d) - w * h * 3:] + out = bytearray(w * h * 4) + out[0::4], out[1::4], out[2::4] = rgb[0::3], rgb[1::3], rgb[2::3] + out[3::4] = b"\xff" * (w * h) + return bytes(out) + + def ffdecode(jpeg, fmt): + p = W("ff.jpg") + open(p, "wb").write(jpeg) + o = W("ff.raw") + ff("-f", "mjpeg", "-i", p, "-f", "rawvideo", "-pix_fmt", fmt, o) + return open(o, "rb").read() + + streams = [] + + def stream(name, src, w, h, pix, nframes, encargs=(), mutate=None): + out = W(name + ".mjpeg") + ff(*source(src, w, h, nframes), "-pix_fmt", pix, "-c:v", "mjpeg", *encargs, "-f", "mjpeg", out) + frames = split(open(out, "rb").read()) + assert len(frames) == nframes, (name, len(frames)) + entries = [] + for fr in frames: + ref = fr + data = mutate(fr) if mutate else fr + entries.append({"data": b64(data), "yuv": zlib.crc32(tj.yuv420(ref)), "rgba": rgba_crc(ref)}) + ref = {"yuv": z64(ffdecode(frames[0], "yuvj420p"))} + if w * h <= 30000 or name == "testsrc_420": # keep tests/gen small: rgba for the small ones and one 320x240 + ref["rgba"] = z64(ffdecode(frames[0], "rgba")) + streams.append({"name": name, "width": w, "height": h, "sampling": pix[4:7], "frames": entries, "ff": ref}) + + stream("testsrc_420", "testsrc2", 320, 240, "yuvj420p", 4, ("-q:v", "3")) + stream("testsrc_422", "testsrc2", 320, 240, "yuvj422p", 4, ("-q:v", "3")) + stream("mandel_444", "mandelbrot", 176, 144, "yuvj444p", 2, ("-q:v", "4")) + stream("odd_420", "mandelbrot", 173, 97, "yuvj420p", 3, ("-q:v", "6")) + stream("odd_422", "testsrc2", 97, 61, "yuvj422p", 3, ("-q:v", "2")) + stream("odd_444", "testsrc2", 33, 17, "yuvj444p", 2, ("-q:v", "2")) + stream("q31_420", "testsrc2", 160, 120, "yuvj420p", 2, ("-q:v", "31")) + # Motion-JPEG as AVI stores it: the annex K tables left out + stream("nodht_420", "mandelbrot", 320, 240, "yuvj420p", 3, ("-q:v", "4", "-huffman", "default"), strip_dht) + stream("nodht_422", "testsrc2", 176, 144, "yuvj422p", 3, ("-q:v", "4", "-huffman", "default"), strip_dht) + # an AVI1 segment (progressive, polarity 0) and padding / junk after EOI + stream("avi1_junk", "testsrc2", 160, 120, "yuvj420p", 2, ("-q:v", "5"), + lambda f: avi1(f, 0) + b"\0\0\0\0\xff\xd9junk after the image\xff\xd8") + + # an interlaced frame: two fields of 320 x 120, each its own JPEG with AVI1 polarity 1, back to back + full = W("full.yuv") + ff(*source("testsrc2", 320, 240, 1), "-pix_fmt", "yuv420p", "-f", "rawvideo", full) + fy = open(full, "rb").read() + fw, fh = 320, 240 + fields, fsrc = [], [] + for k in range(2): + rows = b"".join(fy[y * fw:(y + 1) * fw] for y in range(k, fh, 2)) + cw = fw // 2 + chroma = b"" + for pl in range(2): + base = fw * fh + pl * cw * (fh // 2) + chroma += b"".join(fy[base + y * cw:base + (y + 1) * cw] for y in range(k, fh // 2, 2)) + p = W("field%d.yuv" % k) + open(p, "wb").write(rows + chroma) + o = W("field%d.jpg" % k) + ff("-f", "rawvideo", "-pix_fmt", "yuvj420p", "-s", "%dx%d" % (fw, fh // 2), "-i", p, "-pix_fmt", "yuvj420p", + "-c:v", "mjpeg", "-q:v", "3", "-f", "mjpeg", o) + fields.append(open(o, "rb").read()) + data = avi1(fields[0], 1) + b"\0" * 7 + avi1(fields[1], 1) + + def weave(a, b, w, hf, bpp): + out = bytearray() + for y in range(2 * hf): + src, k = (a, y // 2) if y % 2 == 0 else (b, y // 2) + out += src[k * w * bpp:(k + 1) * w * bpp] + return bytes(out) + + ya, yb = tj.yuv420(fields[0]), tj.yuv420(fields[1]) + hf, cw, chf = fh // 2, fw // 2, fh // 4 + wy = weave(ya[:fw * hf], yb[:fw * hf], fw, hf, 1) + for pl in range(2): + o = fw * hf + pl * cw * chf + wy += weave(ya[o:o + cw * chf], yb[o:o + cw * chf], cw, chf, 1) + + def rgba_raw(jpeg): + p = W("f.jpg") + open(p, "wb").write(jpeg) + return rgba_of_pnm(subprocess.run([djpeg, "-dct", "int", "-pnm", p], check=True, capture_output=True).stdout) + + wr = weave(rgba_raw(fields[0]), rgba_raw(fields[1]), fw, hf, 4) + ctx.emit("mjpeg_cases", {"streams": streams, "fields": {"data": b64(data), "width": fw, "height": fh, + "yuv": zlib.crc32(wy), "rgba": zlib.crc32(wr), "src": z64(fy)}}) + + # the encoder: yuv420p sources, byte-identical with tj3CompressFromYUV8 + enc = [] + for name, src, w, h, qs in (("testsrc_320x240", "testsrc2", 320, 240, (50, 75, 90)), + ("mandel_176x144", "mandelbrot", 176, 144, (30, 95)), + ("odd_97x61", "testsrc2", 97, 61, (75,)), ("tiny_7x5", "mandelbrot", 7, 5, (90,)), + ("one_1x1", "testsrc2", 1, 1, (90,))): + p = W(name + ".yuv") + ff(*source(src, max(w, 2), max(h, 2), 1), "-pix_fmt", "yuv420p", "-f", "rawvideo", W("s.yuv")) + raw = open(W("s.yuv"), "rb").read() + if (w, h) == (1, 1): + raw = raw[:1] + raw[4:5] + raw[5:6] # the top-left luma and chroma samples of a 2x2 source + open(p, "wb").write(raw) + for q in qs: + want = tj.compress420(raw, w, h, q) + got = ffdecode(want, "yuvj420p") if w > 1 else None + psnr = 99.0 + if got: + se = sum((a - b) ** 2 for a, b in zip(got[:w * h], raw[:w * h])) + psnr = 99.0 if se == 0 else 10 * math.log10(255 * 255 * w * h / se) + enc.append({"name": "%s_q%d" % (name, q), "width": w, "height": h, "quality": q, "yuv": z64(raw), + "want": b64(want), "rgba": rgba_crc(want), "ffpsnr": round(psnr, 3)}) + ctx.emit("mjpeg_enc", enc) + + bench = [] + for name, w, h, pix in (("320x240 4:2:0", 320, 240, "yuvj420p"), ("640x480 4:2:0", 640, 480, "yuvj420p"), + ("640x480 4:2:2", 640, 480, "yuvj422p")): + o = W("bench.mjpeg") + ff(*source("testsrc2", w, h, 1), "-pix_fmt", pix, "-c:v", "mjpeg", "-q:v", "3", "-f", "mjpeg", o) + fr = split(open(o, "rb").read())[0] + bench.append({"name": name, "width": w, "height": h, "data": b64(fr), "yuv": zlib.crc32(tj.yuv420(fr))}) + srcs = [] + for w, h in ((320, 240), (640, 480)): + ff(*source("testsrc2", w, h, 1), "-pix_fmt", "yuv420p", "-f", "rawvideo", W("b.yuv")) + srcs.append({"width": w, "height": h, "yuv": z64(open(W("b.yuv"), "rb").read())}) + ctx.emit("mjpeg_bench", {"frames": bench, "sources": srcs}) diff --git a/tools/fixtures/mkv.py b/tools/fixtures/mkv.py new file mode 100644 index 0000000..8fe6122 --- /dev/null +++ b/tools/fixtures/mkv.py @@ -0,0 +1,131 @@ +# Matroska / WebM fixtures (tools/fixtures.py): files made by ffmpeg (libvpx VP8 + Opus / Vorbis WebM, MJPEG + PCM, +# MPEG-1 + MP3, srt subtitles) and mkvmerge (Xiph / EBML / fixed lacing, header-removal compression), plus edits made +# here (every cluster rewritten to an unknown size, a truncated file). For each file: ffprobe's streams and packets +# (pts, duration, keyframe flag, size, CRC-32 of the data), ffmpeg's yuv420p frames (CRC-32 each; the first frames +# raw for PSNR checks) and ffmpeg's decoded audio (f32). +# tests/gen/mkv_cases.luau { { name, data, streams, packets, frames = { crc }, yuv = { raw frame }, pcm, ... } } +import importlib.util, os, subprocess, tempfile + +_spec = importlib.util.spec_from_file_location("_video_helpers", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_video.py")) +V = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(V) + +INPUTS = ["tools/fixtures/_video.py"] + +W, H = 160, 120 +SRC = ["-f", "lavfi", "-i", "testsrc2=size=%dx%d:rate=15" % (W, H)] +MOVE = ["-f", "lavfi", "-i", "mandelbrot=size=%dx%d:rate=15" % (W, H)] + + +def sine(rate, ch=1): + if ch == 1: + return ["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=%d" % rate] + return ["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=%d" % rate, "-ac", str(ch)] + + +def case(ctx, tmp, name, raw_frames=2, audio=True, video=True, pcm_frames=8192): + path = os.path.join(tmp, name) + data = open(path, "rb").read() + c = {"name": name, "data": data, "streams": V.streams(path), "packets": V.packets(path)} + vs = [s for s in c["streams"] if s["kind"] == "video"] + if video and vs: + frames = V.yuv_frames(path, vs[0]["width"], vs[0]["height"], codec=vs[0]["codec"]) + c["frames"] = [V.crc(f) for f in frames] + c["yuv"] = frames[:raw_frames] + if audio and any(s["kind"] == "audio" for s in c["streams"]): + pcm = V.pcm_f32(path) + c["pcm"] = pcm if pcm_frames is None else pcm[:pcm_frames * 4] + c["pcmBytes"] = len(pcm) + return c + + +def el(i, payload): + """an EBML element: id (int), payload bytes""" + n = len(payload) + size = bytes([0x01]) + n.to_bytes(7, "big") + return i.to_bytes((i.bit_length() + 7) // 8, "big") + size + payload + + +def uint(v): + return v.to_bytes(max(1, (v.bit_length() + 7) // 8), "big") + + +def lacing_file(ctx): + """A_PCM/INT/LIT mono 8 kHz s16 in three SimpleBlocks, Xiph-, EBML- and fixed-laced (DefaultDuration 10 ms)""" + rng = ctx.rng(7) + frames = [bytes(rng.randrange(256) for _ in range(2 * n)) for n in (80, 40, 120, 80, 80, 80, 80, 80, 80, 80)] + head = el(0x1A45DFA3, el(0x4282, b"matroska") + el(0x4287, uint(4)) + el(0x4285, uint(2))) + info = el(0x1549A966, el(0x2AD7B1, uint(1000000)) + el(0x4D80, b"fixture") + el(0x5741, b"fixture")) + track = el(0xAE, el(0xD7, uint(1)) + el(0x73C5, uint(1)) + el(0x83, uint(2)) + el(0x86, b"A_PCM/INT/LIT") + + el(0x23E383, uint(10000000)) + el(0xE1, el(0xB5, __import__("struct").pack(">d", 8000.0)) + + el(0x9F, uint(1)) + el(0x6264, uint(16)))) + tracks = el(0x1654AE6B, track) + + def xiph(sizes): + out = b"" + for s in sizes: + out += b"\xff" * (s // 255) + bytes([s % 255]) + return out + + def ebmlnum(v): + n = 1 + while v >= (1 << (7 * n)) - 1: + n += 1 + return ((1 << (7 * n)) | v).to_bytes(n, "big") + + def sebml(v, n=2): + return ((1 << (7 * n)) | (v + (1 << (7 * n - 1)) - 1)).to_bytes(n, "big") + + def block(rel, flags, body): + return el(0xA3, b"\x81" + rel.to_bytes(2, "big") + bytes([flags]) + body) + + f = frames + b1 = block(0, 0x80 | 0x02, bytes([2]) + xiph([len(f[0]), len(f[1])]) + f[0] + f[1] + f[2]) + sizes = [len(f[3]), len(f[4]), len(f[5])] + b2 = block(40, 0x80 | 0x06, bytes([2]) + ebmlnum(sizes[0]) + sebml(sizes[1] - sizes[0]) + f[3] + f[4] + f[5]) + b3 = block(70, 0x80 | 0x04, bytes([3]) + f[6] + f[7] + f[8] + f[9]) + cluster = el(0x1F43B675, el(0xE7, uint(0)) + b1 + b2 + b3) + return head + el(0x18538067, info + tracks + cluster) + + +def generate(ctx): + tmp = tempfile.mkdtemp(prefix="mkvfx_") + ff = lambda *a: V.ffmpeg(list(a), cwd=tmp) + ff(*SRC, *sine(48000), "-t", "1", "-c:v", "libvpx", "-g", "8", "-auto-alt-ref", "1", "-lag-in-frames", "8", + "-b:v", "300k", "-c:a", "libopus", "-b:a", "48k", "vp8_opus.webm") + ff(*MOVE, *sine(44100, 2), "-t", "1", "-c:v", "libvpx", "-g", "30", "-b:v", "200k", "-c:a", "libvorbis", + "vp8_vorbis.webm") + ff(*SRC, *sine(44100, 2), "-t", "1", "-c:v", "mjpeg", "-q:v", "3", "-c:a", "pcm_s16le", "mjpeg_pcm.mkv") + ff(*MOVE, *sine(44100), "-t", "1", "-r", "25", "-c:v", "mpeg1video", "-b:v", "400k", "-c:a", "mp2", "-b:a", "64k", + "mpeg1_mp2.mkv") + ff(*SRC, *sine(48000, 2), "-t", "1", "-c:v", "libvpx", "-g", "15", "-c:a", "flac", "vp8_flac.mkv") + open(os.path.join(tmp, "subs.srt"), "w").write( + "1\n00:00:00,100 --> 00:00:00,500\nHello\n\n2\n00:00:00,600 --> 00:00:00,900\nWorld bold\n\n") + ff(*SRC, "-i", "subs.srt", "-t", "1", "-c:v", "mjpeg", "-c:s", "srt", "subs.mkv") + # mkvmerge: Xiph lacing (Vorbis) and zlib content compression; a file crafted here with all three lacings + mk = lambda *a: subprocess.run(["nix", "shell", "nixpkgs#mkvtoolnix-cli", "-c", "mkvmerge", "-q"] + list(a), + cwd=tmp, check=False, capture_output=True) + mk("-o", "laced_vorbis.mkv", "vp8_vorbis.webm") + ff(*sine(44100), "-t", "1", "-c:a", "libvorbis", "v.ogg") + mk("-o", "zlib_vorbis.mka", "--compression", "0:zlib", "v.ogg") + open(os.path.join(tmp, "lacing.mka"), "wb").write(lacing_file(ctx)) + # unknown-size clusters, a truncated file + open(os.path.join(tmp, "unknown_clusters.webm"), "wb").write( + V.mkv_unknown_clusters(open(os.path.join(tmp, "vp8_opus.webm"), "rb").read())) + full = open(os.path.join(tmp, "mjpeg_pcm.mkv"), "rb").read() + + cases = [ + case(ctx, tmp, "vp8_opus.webm"), + case(ctx, tmp, "vp8_vorbis.webm"), + case(ctx, tmp, "mjpeg_pcm.mkv"), + case(ctx, tmp, "mpeg1_mp2.mkv"), + case(ctx, tmp, "vp8_flac.mkv"), + case(ctx, tmp, "subs.mkv", audio=False), + case(ctx, tmp, "unknown_clusters.webm"), + ] + for name in ("laced_vorbis.mkv", "zlib_vorbis.mka", "lacing.mka"): + if os.path.exists(os.path.join(tmp, name)): + cases.append(case(ctx, tmp, name)) + cut = full[: len(full) * 7 // 10] + cases.append({"name": "truncated.mkv", "data": cut, "truncated": True}) + ctx.emit("mkv_cases", cases) diff --git a/tools/fixtures/mod.py b/tools/fixtures/mod.py new file mode 100644 index 0000000..25b9b67 --- /dev/null +++ b/tools/fixtures/mod.py @@ -0,0 +1,110 @@ +# MOD fixtures (tools/fixtures.py): generated ProTracker modules exercising the effects, rendered by openmpt123. +# tests/gen/mod_cases.luau { name, data (the module), ref (features of openmpt's render, tools/fixtures/_tracker.py), +# duration (openmpt's song length) } +import os, sys + +# 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, 0, 0) for _ in range(ch)] for _ in range(64)] + + +def put(p, row, ch, note=0, ins=0, fx=0, param=0): + p[row][ch] = (note, ins, fx, param) + + +def samples(): + return [ + {"name": "sine", "data": T.s8(T.synth("sine", 64, 64)), "volume": 64, "loop": (0, 64)}, + {"name": "square", "data": T.s8(T.synth("square", 64, 64, 0.5)), "volume": 48, "loop": (0, 64)}, + {"name": "saw", "data": T.s8(T.synth("saw", 128, 64, 0.6)), "volume": 64, "loop": (64, 64)}, + {"name": "noise", "data": T.s8(T.synth("noise", 4000, 1, 0.7, decay=1200)), "volume": 64}, + {"name": "tri ft", "data": T.s8(T.synth("tri", 32, 32, 0.8)), "volume": 56, "finetune": 3, "loop": (0, 32)}, + ] + + +def song_basic(): + a, b = empty(4), empty(4) + mel = [49, 53, 56, 61, 56, 53, 51, 49] + for i in range(16): + put(a, i * 4, 0, mel[i % 8], 1) + put(a, i * 4, 1, 37 + (i % 4) * 2, 2, 0x0, 0x37 if i % 2 else 0) + put(a, 0, 2, 49, 3, 0x1, 0x02) + put(a, 16, 2, 0, 0, 0x2, 0x03) + put(a, 32, 2, 61, 3, 0xC, 0x30) + put(a, 33, 2, 0, 0, 0xA, 0x02) + put(a, 48, 2, 0, 0, 0xA, 0x40) + for r in range(0, 64, 8): + put(a, r, 3, 61, 4, 0xC, 0x40 - r // 2) + put(a, 60, 3, 61, 4, 0xE, 0xC2) + # pattern b: portamento, vibrato, tremolo, offsets, retrig, delay, fine slides, speed change, break + put(b, 0, 0, 49, 1) + put(b, 4, 0, 61, 0, 0x3, 0x08) + put(b, 8, 0, 0, 0, 0x3, 0x00) + put(b, 12, 0, 49, 0, 0x5, 0x02) + put(b, 16, 0, 56, 5, 0x4, 0x46) + put(b, 20, 0, 0, 0, 0x6, 0x01) + put(b, 24, 0, 0, 0, 0x4, 0x8F) + put(b, 0, 1, 37, 2, 0x7, 0x48) + put(b, 8, 1, 0, 0, 0x7, 0x00) + put(b, 16, 1, 44, 2, 0xE, 0x12) + put(b, 17, 1, 0, 0, 0xE, 0x12) + put(b, 20, 1, 0, 0, 0xE, 0x24) + put(b, 24, 1, 0, 0, 0xE, 0xB8) + put(b, 28, 1, 0, 0, 0xE, 0xA4) + put(b, 0, 3, 49, 4, 0x9, 0x08) + put(b, 8, 3, 49, 4, 0xE, 0x93) + put(b, 16, 3, 56, 4, 0xE, 0xD3) + put(b, 24, 2, 49, 3, 0xF, 0x03) + put(b, 32, 2, 51, 3, 0xF, 0x90) + put(b, 40, 2, 53, 3, 0xF, 0x06) + put(b, 40, 3, 61, 4, 0x9, 0x04) + put(b, 44, 0, 49, 5, 0xE, 0x53) + put(b, 48, 0, 0, 0, 0xD, 0x00) + return T.write_mod("basic", samples(), [0, 1], [a, b]) + + +def song_loops(): + a, b, c = empty(4), empty(4), empty(4) + put(a, 0, 0, 49, 1, 0xF, 0x04) + put(a, 4, 0, 0, 0, 0xE, 0x60) + put(a, 5, 1, 61, 2) + put(a, 8, 0, 53, 1, 0xE, 0x62) + put(a, 16, 0, 56, 1, 0xE, 0xE3) + put(a, 17, 2, 37, 3, 0xA, 0x01) + put(a, 32, 0, 0, 0, 0xD, 0x16) + put(b, 16, 0, 61, 1) + put(b, 20, 3, 49, 4, 0xF, 0x70) + put(b, 24, 0, 0, 0, 0xB, 0x02) + put(c, 0, 1, 50, 5) + put(c, 4, 1, 0, 0, 0xB, 0x01) + return T.write_mod("loops", samples(), [0, 1, 2], [a, b, c]) + + +def song_8ch(): + a = empty(8) + for ch in range(8): + put(a, ch * 2, ch, 37 + ch * 5, 1 + ch % 3, 0x8, ch * 32) + put(a, 32, 0, 61, 5, 0xE, 0x84) + put(a, 32, 7, 49, 4, 0x8, 0xFF) + put(a, 63, 0, 0, 0, 0xF, 0x00) + return T.write_mod("eight", samples(), [0], [a], channels=8) + + +def generate(ctx): + cases = [] + for nm, data in (("basic", song_basic()), ("loops", song_loops()), ("8ch", song_8ch())): + ref = T.reference(ctx, data, "mod") + cases.append({"name": nm, "data": data, "ref": ref, "duration": ref["duration"]}) + ctx.emit("mod_cases", cases) + diff --git a/tools/fixtures/mp3_enc.py b/tools/fixtures/mp3_enc.py new file mode 100644 index 0000000..5b95717 --- /dev/null +++ b/tools/fixtures/mp3_enc.py @@ -0,0 +1,80 @@ +# MP3 / MP2 encoder fixtures (tools/fixtures.py): our layer III and layer II encoders run in the fixture step +# (tools/fixtures/_audio.py encode_luau_many) on test signals at every MPEG sample rate group, several bit rates and +# modes; ffmpeg (mp3float / mp2float) and LAME (`lame --decode`, layer III) decode the files. Recorded per file: ffmpeg's +# error output (must be empty), the decoded frame counts, and the SNR against the input after aligning the decoder delay. +# tests/gen/mp3_enc.luau { name, sig, layer, bitrate, mode, rate, channels, frames, ffErrors, ffFrames, ffSnr, +# ffLag, lameFrames?, lameSnr?, size, data } +# tests/gen/mp3_enc_sigs.luau { [sig] = { rate, channels, frames, data (f32le) } } +import importlib.util, io, os, wave + +_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 = ["src/Formats/audio/mp3", "src/Formats/codecs/Pcm"] + + +def generate(ctx): + sigs = {} + + def sig(kind, ch, secs, rate): + name = "%s_%d_%d" % (kind, ch, rate) + if name not in sigs: + frames = int(secs * rate) + sigs[name] = (A.from_f32le(A.f32le(A.signal(kind, rate, ch, frames, seed=ch * 7 + rate % 97))), rate, ch) + return name + + cases = [] # name, sig, layer, bitrate, mode + for kind in ("music", "sine", "sweep"): + for br in (64, 128, 192, 320): + cases.append(("l3-%s-44k-%d-joint" % (kind, br), sig(kind, 2, 1.0, 44100), 3, br, "joint")) + cases.append(("l3-music-44k-128-stereo", sig("music", 2, 1.0, 44100), 3, 128, "stereo")) + cases.append(("l3-music-48k-160-joint", sig("music", 2, 1.0, 48000), 3, 160, "joint")) + cases.append(("l3-music-32k-96-mono", sig("music", 1, 1.0, 32000), 3, 96, "mono")) + cases.append(("l3-noise-44k-128-mono", sig("noise", 1, 0.6, 44100), 3, 128, "mono")) + cases.append(("l3-music-22k-64-joint", sig("music", 2, 1.0, 22050), 3, 64, "joint")) + cases.append(("l3-music-24k-96-stereo", sig("music", 2, 1.0, 24000), 3, 96, "stereo")) + cases.append(("l3-sweep-16k-48-mono", sig("sweep", 1, 1.0, 16000), 3, 48, "mono")) + cases.append(("l3-music-11k-32-mono", sig("music", 1, 1.0, 11025), 3, 32, "mono")) + cases.append(("l3-music-8k-24-joint", sig("music", 2, 1.0, 8000), 3, 24, "joint")) + cases.append(("l3-music-12k-64-stereo", sig("music", 2, 1.0, 12000), 3, 64, "stereo")) + cases.append(("l3-silence-44k-128", sig("silence", 2, 0.3, 44100), 3, 128, "joint")) + cases.append(("l3-loud-44k-128", sig("loud", 2, 0.5, 44100), 3, 128, "joint")) + for kind in ("music", "sine", "sweep"): + for br in (128, 192, 256, 384): + cases.append(("l2-%s-44k-%d" % (kind, br), sig(kind, 2, 1.0, 44100), 2, br, "stereo")) + cases.append(("l2-music-48k-192", sig("music", 2, 1.0, 48000), 2, 192, "stereo")) + cases.append(("l2-music-32k-mono-96", sig("music", 1, 1.0, 32000), 2, 96, "mono")) + cases.append(("l2-music-44k-mono-64", sig("music", 1, 1.0, 44100), 2, 64, "mono")) + cases.append(("l2-music-24k-96", sig("music", 2, 1.0, 24000), 2, 96, "stereo")) + cases.append(("l2-sweep-16k-mono-48", sig("sweep", 1, 1.0, 16000), 2, 48, "mono")) + cases.append(("l2-loud-44k-192", sig("loud", 2, 0.5, 44100), 2, 192, "stereo")) + + ctx.emit("mp3_enc_sigs", {n: {"rate": r, "channels": c, "frames": len(x) // c, "data": A.f32le(x)} for n, (x, r, c) in sigs.items()}) + jobs = [(c[1], '{ layer = %d, bitrate = %d, mode = "%s" }' % (c[2], c[3], c[4])) for c in cases] + outs = A.encode_luau_many(ctx, "audio/mp3", jobs, "mp3_enc_sigs") + emitted = [] + for (name, sigmod, layer, br, mode), data in zip(cases, outs): + samples, rate, ch = sigs[sigmod] + ext = "mp3" if layer == 3 else "mp2" + errs = A.tool(ctx, "ffmpeg", ["ffmpeg", "-v", "error", "-i", "{in}", "-f", "null", "-"], data, ext).decode(errors="replace") + frate, fch, dec = A.ffdecode(ctx, data, ext=ext) + dch = fch + ref = samples if dch == ch else [samples[i // dch] for i in range(len(samples) // ch * dch)] + snr, lag = A.snr(ref, dec, dch, max_lag=1600, skip=200, hints=[1057 if layer == 3 else 481]) if dch == ch else (-99.0, 0) + e = {"name": name, "sig": sigmod, "layer": layer, "bitrate": br, "mode": mode, "rate": rate, "channels": ch, + "frames": len(samples) // ch, "ffErrors": errs, "ffFrames": len(dec) // max(1, fch), "ffRate": frate, + "ffChannels": fch, "ffSnr": snr, "ffLag": lag, "size": len(data), "data": data} + if layer == 3: + wavb = A.tool(ctx, "lame", ["lame", "--quiet", "--decode", "{in}", "{out}"], data, "mp3", "wav") + with wave.open(io.BytesIO(wavb)) as wf: + lch, raw = wf.getnchannels(), wf.readframes(wf.getnframes()) + lame = [int.from_bytes(raw[i:i + 2], "little", signed=True) / 32768 for i in range(0, len(raw), 2)] + if lch == ch: + ls, ll = A.snr(samples, lame, ch, max_lag=1600, skip=200, hints=[1057, 528, 529]) + e["lameSnr"], e["lameLag"] = ls, ll + e["lameFrames"] = len(lame) // lch + emitted.append(e) + print(" mp3_enc: %-28s %5d bytes ffmpeg %.1f dB (lag %d)%s%s" % (name, len(data), snr, lag, + (" lame %.1f dB" % e["lameSnr"]) if "lameSnr" in e else "", (" ERR " + errs.strip()[:60]) if errs.strip() else "")) + ctx.emit("mp3_enc", emitted) diff --git a/tools/fixtures/mp4.py b/tools/fixtures/mp4.py new file mode 100644 index 0000000..cf4164a --- /dev/null +++ b/tools/fixtures/mp4.py @@ -0,0 +1,50 @@ +# MP4 / MOV fixtures (tools/fixtures.py): files made by ffmpeg (MJPEG + AAC MP4, MJPEG + PCM MOV, H.264 with B-frames +# + AAC (edit lists), fragmented MP4, MPEG-1 + Opus, MJPEG + FLAC, MJPEG + MP2 MOV) with ffprobe's streams and packets, +# ffmpeg's frames (CRC-32; the first raw) and audio (f32). Our MP4 / MOV writer's files are checked in +# tools/fixtures/videoenc.py. +# tests/gen/mp4_cases.luau { { name, data, streams, packets, frames, yuv, pcm, pcmBytes } } +import importlib.util, os, tempfile + +_spec = importlib.util.spec_from_file_location("_video_helpers", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_video.py")) +V = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(V) + +INPUTS = ["tools/fixtures/_video.py"] + +SRC = ["-f", "lavfi", "-i", "testsrc2=size=160x120:rate=12"] + + +def aud(rate, ch=1): + return ["-f", "lavfi", "-i", "sine=frequency=550:sample_rate=%d" % rate, "-ac", str(ch)] + + +def case(tmp, name): + path = os.path.join(tmp, name) + c = {"name": name, "data": open(path, "rb").read(), "streams": V.streams(path), "packets": V.packets(path)} + vs = [s for s in c["streams"] if s["kind"] == "video"] + if vs: + frames = V.yuv_frames(path, vs[0]["width"], vs[0]["height"], codec=vs[0]["codec"]) + c["frames"] = [V.crc(f) for f in frames] + c["yuv"] = frames[:2] + if any(s["kind"] == "audio" for s in c["streams"]): + pcm = V.pcm_f32(path) + c["pcm"] = pcm[:8192 * 4] + c["pcmBytes"] = len(pcm) + return c + + +def generate(ctx): + tmp = tempfile.mkdtemp(prefix="mp4fx_") + ff = lambda *a: V.ffmpeg(list(a), cwd=tmp) + ff(*SRC, *aud(44100), "-t", "1", "-c:v", "mjpeg", "-q:v", "4", "-c:a", "aac", "-b:a", "96k", "mjpeg_aac.mp4") + ff(*SRC, *aud(48000, 2), "-t", "1", "-c:v", "mjpeg", "-c:a", "pcm_s16le", "mjpeg_pcm.mov") + ff(*SRC, *aud(44100), "-t", "1", "-c:v", "libx264", "-preset", "veryfast", "-bf", "2", "-g", "6", "-c:a", "aac", + "h264_aac.mp4") + ff(*SRC, *aud(48000), "-t", "1", "-c:v", "mjpeg", "-c:a", "aac", "-movflags", "frag_keyframe+empty_moov", + "fragmented.mp4") + ff(*SRC, *aud(48000), "-t", "1", "-r", "25", "-c:v", "mpeg1video", "-c:a", "libopus", "mpeg1_opus.mp4") + ff(*SRC, *aud(44100, 2), "-t", "1", "-c:v", "mjpeg", "-c:a", "flac", "mjpeg_flac.mp4") + ff(*SRC, *aud(44100), "-t", "1", "-c:v", "mjpeg", "-c:a", "mp2", "mjpeg_mp2.mov") + cases = [case(tmp, n) for n in ("mjpeg_aac.mp4", "mjpeg_pcm.mov", "h264_aac.mp4", "fragmented.mp4", + "mpeg1_opus.mp4", "mjpeg_flac.mp4", "mjpeg_mp2.mov")] + ctx.emit("mp4_cases", cases) diff --git a/tools/fixtures/mpeg1.py b/tools/fixtures/mpeg1.py new file mode 100644 index 0000000..bf54b0a --- /dev/null +++ b/tools/fixtures/mpeg1.py @@ -0,0 +1,170 @@ +# MPEG-1 video fixtures for codecs/Mpeg1 (tools/fixtures.py), ported from mpeg1-luau tools/fixtures.py: elementary +# streams made by ffmpeg's mpeg1video encoder (testsrc2 / mandelbrot, several bit rates, odd sizes, custom matrices, +# B-frames, a size change), their access units, and ffmpeg's own decode of each as references: +# tests/gen/mpeg1_.luau { name, width, height, frames, file (base64), units = { { offset, length } }, +# means = { { r, g, b } } (every frame, display order, ffmpeg's RGBA), +# rgba = { { index, pixels } } (two whole RGBA frames, base64 zlib), +# yuv = { { index, planes } } (three whole frames as ffmpeg -pix_fmt yuv420p, base64 zlib) } +# tests/gen/mpeg1_sizechange.luau { file (base64), parts = { { width, height, frames, last (RGBA, base64 zlib) } } } +# tests/gen/mpeg1_bench.luau { { width, height, file (base64), units } }: 320x240 and 640x480 streams (with +# B-frames) for tools/bench.luau +# Binary fields are base64 (file, units' data) or base64 of zlib data (frames: the test inflates them with +# codecs/Deflate): Luau string literals of binary data cost ~3.7 bytes per byte, base64 1.33. With short streams and +# few whole frames the set stays near 10 MB. +import base64, os, shutil, subprocess, tempfile, zlib + +def b64(b): + return base64.b64encode(b).decode() + + +def z64(b): + return base64.b64encode(zlib.compress(b, 9)).decode() + + +FF = ["-hide_banner", "-loglevel", "error", "-y"] +ENC = ["-c:v", "mpeg1video", "-f", "mpeg1video"] +# a non-default intra matrix (steeper) and inter matrix (rising), 64 values in natural order +INTRA = ",".join(str(8 + (i // 8 + i % 8) * 3) for i in range(64)) +INTER = ",".join(str(16 + (i // 8 + i % 8)) for i in range(64)) + + +def src(kind, w, h, rate, t): + return ["-f", "lavfi", "-i", "%s=size=%dx%d:rate=%s" % (kind, w, h, rate), "-t", str(t)] + + +# name: (ffmpeg input + encoder args, size patched into the sequence headers or None, rgba sample picks, yuv picks) +CASES = { + "qcif_200k": (src("testsrc2", 176, 144, 25, 1.2) + ["-b:v", "200k", "-bf", "0", "-g", "50"], None), + "main_450k": (src("testsrc2", 320, 180, 24, 1.5) + ["-b:v", "450k", "-bf", "0", "-g", "48"], None), + "zoom_150k": (src("mandelbrot", 320, 180, 24, 1.5) + ["-b:v", "150k", "-bf", "0", "-g", "48"], None), + "zoom_1500k": (src("mandelbrot", 320, 180, 24, 1) + ["-b:v", "1500k", "-bf", "0", "-g", "48"], None), + "big_1000k": (src("testsrc2", 640, 360, 24, 0.5) + ["-b:v", "1000k", "-bf", "0", "-g", "36"], None), + # odd sizes: ffmpeg's encoder only writes even ones, so the size in the sequence headers is patched; the + # reference is ffmpeg's decode of the unpatched stream, cropped (swscale's odd-size RGBA path interpolates + # chroma differently from its even-size one, which is what the decoder matches) + "odd_173x95": (src("mandelbrot", 174, 96, 24, 1) + ["-b:v", "300k", "-bf", "0", "-g", "24"], (173, 95)), + "bframes": (src("testsrc2", 320, 180, 24, 1) + ["-b:v", "600k", "-bf", "2", "-g", "24"], None), + "bframes_zoom": (src("mandelbrot", 176, 144, 24, 1.5) + ["-b:v", "250k", "-bf", "3", "-g", "16"], None), + "matrix": (src("testsrc2", 176, 144, 25, 1) + ["-b:v", "300k", "-bf", "0", "-g", "12", + "-intra_matrix", INTRA, "-inter_matrix", INTER], None), + "q1": (src("mandelbrot", 176, 144, 25, 0.6) + ["-q:v", "1", "-bf", "0", "-g", "8"], None), + "q31": (src("testsrc2", 176, 144, 25, 1) + ["-q:v", "31", "-bf", "0", "-g", "25"], None), + "zeromv": (src("mandelbrot", 176, 144, 25, 1) + ["-b:v", "300k", "-bf", "0", "-g", "25", "-me_method", "zero"], None), +} + + +def patch_size(es, w, h): + # every sequence header (00 00 01 B3): 12-bit width, 12-bit height + b = bytearray(es) + i = 0 + while True: + i = b.find(b"\x00\x00\x01\xb3", i) + if i < 0: + return bytes(b) + b[i + 4] = w >> 4 + b[i + 5] = ((w & 15) << 4) | (h >> 8) + b[i + 6] = h & 255 + i += 4 + + +def access_units(es): + # one unit per picture: from the first header byte before it (sequence / GOP) to the next unit start + starts = [] + i = 0 + pending = None + while True: + i = es.find(b"\x00\x00\x01", i) + if i < 0 or i + 3 >= len(es): + break + code = es[i + 3] + if code in (0xB3, 0xB8) and pending is None: + pending = i + elif code == 0x00: + starts.append(pending if pending is not None else i) + pending = None + i += 3 + return [[s, (starts[k + 1] if k + 1 < len(starts) else len(es)) - s] for k, s in enumerate(starts)] + + +def crop(frames, w, h, cw, ch, bpp): + fs = w * h * bpp + out = bytearray() + for k in range(len(frames) // fs): + for y in range(ch): + o = k * fs + y * w * bpp + out += frames[o:o + cw * bpp] + return bytes(out) + + +def crop_yuv(frames, w, h, cw, ch): + fs = w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2) + out = bytearray() + for k in range(len(frames) // fs): + f = frames[k * fs:(k + 1) * fs] + out += crop(f[:w * h], w, h, cw, ch, 1) + c = ((w + 1) // 2) * ((h + 1) // 2) + for pl in range(2): + out += crop(f[w * h + pl * c:w * h + (pl + 1) * c], (w + 1) // 2, (h + 1) // 2, (cw + 1) // 2, (ch + 1) // 2, 1) + return bytes(out) + + +def generate(ctx): + ffmpeg = shutil.which("ffmpeg") or ctx.nix("ffmpeg", ["sh", "-c", "command -v ffmpeg"]).decode().strip() + ffprobe = shutil.which("ffprobe") or os.path.join(os.path.dirname(ffmpeg), "ffprobe") + + def ff(args): + subprocess.run([ffmpeg] + FF + args, check=True, capture_output=True) + + with tempfile.TemporaryDirectory(prefix="formats-mpeg1-") as tmp: + def encode(name, args, size): + path = os.path.join(tmp, name + ".m1v") + ff(args + ENC + [path]) + es = open(path, "rb").read() + return (patch_size(es, *size) if size else es), path + + def reference(path, fmt): + out = path + "." + fmt + ff(["-i", path, "-f", "rawvideo", "-pix_fmt", fmt, out]) + r = subprocess.run([ffprobe, "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height", + "-of", "csv=p=0", path], check=True, capture_output=True) + w, h = (int(x) for x in r.stdout.decode().strip().split(",")[:2]) + return open(out, "rb").read(), w, h + + for name, (args, size) in CASES.items(): + es, path = encode(name, args, size) + rgba, w, h = reference(path, "rgba") + yuv, _, _ = reference(path, "yuv420p") + if size: + rgba, yuv = crop(rgba, w, h, size[0], size[1], 4), crop_yuv(yuv, w, h, size[0], size[1]) + w, h = size + fs, ys = w * h * 4, w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2) + n = len(rgba) // fs + means = [] + for k in range(n): + fr = rgba[k * fs:(k + 1) * fs] + means.append([round(sum(fr[c::4]) / (w * h), 4) for c in range(3)]) + # whole frames: the first P-picture and the last one (the most drift) as RGBA, three as yuv420p + picks = sorted({1, n - 1}) if n > 2 else list(range(n)) + ypicks = sorted({0, n // 2, n - 1}) + ctx.emit("mpeg1_" + name, { + "name": name, "width": w, "height": h, "frames": n, "file": b64(es), "units": access_units(es), + "means": means, + "rgba": [{"index": k + 1, "pixels": z64(rgba[k * fs:(k + 1) * fs])} for k in picks], + "yuv": [{"index": k + 1, "planes": z64(yuv[k * ys:(k + 1) * ys])} for k in ypicks], + }) + + # a size change mid-stream: 176x144 then 320x180 (each part decoded by ffmpeg on its own) + a, pa = encode("sc_a", src("testsrc2", 176, 144, 24, 0.5) + ["-b:v", "200k", "-bf", "0", "-g", "6"], None) + b, pb = encode("sc_b", src("mandelbrot", 320, 180, 24, 0.5) + ["-b:v", "400k", "-bf", "0", "-g", "6"], None) + parts = [] + for path in (pa, pb): + rg, w, h = reference(path, "rgba") + n = len(rg) // (w * h * 4) + parts.append({"width": w, "height": h, "frames": n, "last": z64(rg[(n - 1) * w * h * 4:])}) + ctx.emit("mpeg1_sizechange", {"file": b64(a + b), "parts": parts}) + + bench = [] + for w, h, rate in ((320, 240, "600k"), (640, 480, "1500k")): + es, _ = encode("bench", src("testsrc2", w, h, 25, 2) + ["-b:v", rate, "-bf", "2", "-g", "25"], None) + bench.append({"width": w, "height": h, "file": b64(es), "units": access_units(es)}) + ctx.emit("mpeg1_bench", bench) diff --git a/tools/fixtures/mpegts.py b/tools/fixtures/mpegts.py new file mode 100644 index 0000000..ad3841e --- /dev/null +++ b/tools/fixtures/mpegts.py @@ -0,0 +1,59 @@ +# MPEG-TS / PS fixtures (tools/fixtures.py): transport streams (MPEG-1 + MP2 as bugtv plays them, with B-frames, +# H.264 + AAC, M2TS 192-byte packets, garbage before the first packet) and program streams (MPEG-1 system stream, +# MPEG-2 PS / VOB layout, B-frames, a raw .m1v elementary stream), made by ffmpeg. For each file: ffprobe's streams +# and packets, ffmpeg's frames (CRC-32 of yuv420p; the first frames raw) and audio (f32). +# tests/gen/mpegts_cases.luau, tests/gen/mpegps_cases.luau +import importlib.util, os, tempfile + +_spec = importlib.util.spec_from_file_location("_video_helpers", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_video.py")) +V = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(V) + +INPUTS = ["tools/fixtures/_video.py"] + +SRC = ["-f", "lavfi", "-i", "testsrc2=size=160x120:rate=25"] +AUD = ["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=44100"] + + +def case(tmp, name, raw_frames=3, pcm_frames=8192, packets=True): + path = os.path.join(tmp, name) + c = {"name": name, "data": open(path, "rb").read(), "streams": V.streams(path)} + if packets: + c["packets"] = V.packets(path) + vs = [s for s in c["streams"] if s["kind"] == "video"] + if vs: + frames = V.yuv_frames(path, vs[0]["width"], vs[0]["height"]) + c["frames"] = [V.crc(f) for f in frames] + c["yuv"] = frames[:raw_frames] + if any(s["kind"] == "audio" for s in c["streams"]): + pcm = V.pcm_f32(path) + c["pcm"] = pcm[:pcm_frames * 4] + c["pcmBytes"] = len(pcm) + return c + + +def generate(ctx): + tmp = tempfile.mkdtemp(prefix="mpegfx_") + ff = lambda *a: V.ffmpeg(list(a), cwd=tmp) + ff(*SRC, *AUD, "-t", "1", "-c:v", "mpeg1video", "-b:v", "600k", "-bf", "0", "-c:a", "mp2", "-b:a", "128k", + "-f", "mpegts", "mpeg1_mp2.ts") + ff(*SRC, *AUD, "-t", "1", "-c:v", "mpeg1video", "-b:v", "600k", "-bf", "2", "-c:a", "mp2", "-f", "mpegts", + "bframes.ts") + ff(*SRC, *AUD, "-t", "1", "-c:v", "libx264", "-preset", "veryfast", "-g", "10", "-c:a", "aac", "-b:a", "96k", + "-f", "mpegts", "h264_aac.ts") + ff(*SRC, "-t", "1", "-c:v", "mpeg1video", "-b:v", "600k", "-f", "mpegts", "-mpegts_m2ts_mode", "1", "m2ts.m2ts") + open(os.path.join(tmp, "garbage.ts"), "wb").write(bytes(ctx.rng(3).randrange(256) for _ in range(333)).replace(b"G", b"g") + + open(os.path.join(tmp, "mpeg1_mp2.ts"), "rb").read()) + ts = [case(tmp, "mpeg1_mp2.ts"), case(tmp, "bframes.ts"), case(tmp, "h264_aac.ts"), case(tmp, "m2ts.m2ts"), + case(tmp, "garbage.ts", packets=False)] + full = ts[0]["data"] + ts.append({"name": "truncated.ts", "data": full[: len(full) // 2 + 77], "truncated": True}) + ctx.emit("mpegts_cases", ts) + + ff(*SRC, *AUD, "-t", "1", "-c:v", "mpeg1video", "-b:v", "600k", "-bf", "0", "-c:a", "mp2", "-f", "mpeg", "system.mpg") + ff(*SRC, *AUD, "-t", "1", "-c:v", "mpeg1video", "-b:v", "600k", "-bf", "2", "-c:a", "mp2", "-f", "mpeg", + "bframes.mpg") + ff(*SRC, *AUD, "-t", "1", "-c:v", "mpeg1video", "-b:v", "600k", "-c:a", "mp2", "-f", "vob", "mpeg2ps.vob") + ff(*SRC, "-t", "1", "-c:v", "mpeg1video", "-b:v", "600k", "-bf", "2", "-f", "mpeg1video", "es.m1v") + ps = [case(tmp, n, packets=False) for n in ("system.mpg", "bframes.mpg", "mpeg2ps.vob", "es.m1v")] + ctx.emit("mpegps_cases", ps) diff --git a/tools/fixtures/opus_celt.py b/tools/fixtures/opus_celt.py new file mode 100644 index 0000000..5db280b --- /dev/null +++ b/tools/fixtures/opus_celt.py @@ -0,0 +1,48 @@ +# The CELT encoder reference check (tools/fixtures.py): runs tools/fixtures/_opus_encode.luau (our encoder over +# tests/audio/_opus_cases.luau), then the reference tools through nix: opusdec --float (libopus), opusinfo (stream +# structure), ffmpeg (an independent Ogg / Opus reader). +# tests/gen/opus_celt.luau { { name, crc (of our bytes), opusdec (f32le 48 kHz decode), opusinfo (exit 0), +# ffmpeg (decoded), ffmpegFrames, comments (opusinfo's user comments) } } +import os, re, shutil, subprocess, tempfile, zlib + +INPUTS = ["src/Formats/audio/opus", "src/Formats/codecs/Mdct", "src/Formats/containers/Ogg", + "tests/audio/_opus_cases.luau", "tools/fixtures/_opus_encode.luau"] + + +def generate(ctx): + luau = os.environ.get("LUAU") or shutil.which("luau") + script = os.path.join(ctx.root, "tools/fixtures/_opus_encode.luau") + if luau: + out = subprocess.run([luau, script], capture_output=True, check=True, cwd=ctx.root).stdout + else: + out = ctx.nix("luau", ["luau", script]) + d = tempfile.mkdtemp(prefix="opus-celt-fx-") + try: + cases = [] + for line in out.decode().split("\n"): + if not line.strip(): + continue + name, hx = line.split(" ", 1) + if hx.startswith("ERROR"): + raise RuntimeError("opus_celt fixtures: our encoder failed on %s: %s" % (name, hx)) + data = bytes.fromhex(hx) + path = os.path.join(d, name + ".opus") + with open(path, "wb") as f: + f.write(data) + raw = os.path.join(d, name + ".f32") + ctx.nix("opus-tools", ["opusdec", "--quiet", "--float", "--rate", "48000", path, raw]) + with open(raw, "rb") as f: + pcm = f.read() + info = subprocess.run(["nix", "shell", "nixpkgs#opus-tools", "-c", "opusinfo", path], capture_output=True) + text = info.stdout.decode(errors="replace") + comments = {} + for m in re.finditer(r"^\s*([A-Za-z]+)=(.*)$", text, re.M): + comments[m.group(1).lower()] = m.group(2) + ok = info.returncode == 0 and "WARNING" not in text and "ERROR" not in text.upper().replace("ERRORS", "") + ff = subprocess.run(["nix", "shell", "nixpkgs#ffmpeg", "-c", "ffmpeg", "-v", "error", "-i", path, "-f", "f32le", "-ac", "1", "-"], capture_output=True) + cases.append({"name": name, "crc": zlib.crc32(data), "opusdec": pcm, "opusinfo": ok, + "ffmpeg": ff.returncode == 0 and len(ff.stderr) == 0, "ffmpegFrames": len(ff.stdout) // 4, + "comments": comments}) + ctx.emit("opus_celt", cases) + finally: + shutil.rmtree(d, ignore_errors=True) diff --git a/tools/fixtures/s3m.py b/tools/fixtures/s3m.py new file mode 100644 index 0000000..d8a983e --- /dev/null +++ b/tools/fixtures/s3m.py @@ -0,0 +1,130 @@ +# S3M fixtures (tools/fixtures.py): generated Scream Tracker 3 modules exercising the effects, rendered by openmpt123. +# tests/gen/s3m_cases.luau { name, data (the module), ref (features of openmpt's render, tools/fixtures/_tracker.py), +# duration (openmpt's song length) } +import os, sys + +# 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, K, L, M, N, O, P, Q, R, S, Tt, U, V, W, X, Y, Z = range(1, 27) + + +def empty(ch, rows=64): + return [[(0, 0, None, 0, 0) for _ in range(ch)] for _ in range(rows)] + + +def put(p, row, ch, note=0, ins=0, vol=None, cmd=0, info=0): + p[row][ch] = (T.s3m_note(note) if 0 < note < 254 else note, ins, vol, cmd, info) + + +def samples(): + return [ + {"name": "sine", "data": T.u8(T.synth("sine", 64, 64)), "volume": 64, "c2spd": 8363, "loop": (0, 64)}, + {"name": "square", "data": T.u8(T.synth("square", 64, 64, 0.5)), "volume": 40, "c2spd": 16726, "loop": (0, 64)}, + {"name": "saw", "data": T.u8(T.synth("saw", 100, 100, 0.6)), "volume": 64, "c2spd": 13000, "loop": (0, 100)}, + {"name": "noise", "data": T.u8(T.synth("noise", 6000, 1, 0.7, decay=1500)), "volume": 60, "c2spd": 8363}, + {"name": "tri", "data": T.u8(T.synth("tri", 50, 50, 0.8)), "volume": 50, "c2spd": 10000, "loop": (0, 50)}, + ] + + +def song_effects(keep=None): + """keep: debugging aid, a set of channels to keep (the others keep only their global effects)""" + a, b, c = empty(4), empty(4), empty(4) + mel = [61, 65, 68, 73, 68, 65, 63, 61] + for i in range(16): + put(a, i * 4, 0, mel[i % 8], 1, None, J if i % 4 == 1 else 0, 0x47 if i % 4 == 1 else 0) + put(a, 0, 1, 49, 2, 48) + put(a, 4, 1, 0, 0, None, D, 0x04) + put(a, 8, 1, 0, 0, None, D, 0x20) + put(a, 12, 1, 0, 0, None, D, 0xF2) + put(a, 13, 1, 0, 0, None, D, 0x3F) + put(a, 14, 1, 0, 0, None, D, 0x00) + put(a, 16, 1, 51, 2, None, E, 0x03) + put(a, 20, 1, 0, 0, None, F, 0x06) + put(a, 24, 1, 0, 0, None, E, 0xF4) + put(a, 25, 1, 0, 0, None, F, 0xE8) + put(a, 28, 1, 56, 2, None, H, 0x46) + put(a, 32, 1, 0, 0, None, U, 0x48) + put(a, 36, 1, 0, 0, None, K, 0x02) + put(a, 40, 1, 49, 2, None, G, 0x00) + put(a, 41, 1, 61, 0, None, G, 0x10) + put(a, 44, 1, 0, 0, None, L, 0x01) + put(a, 48, 1, 54, 2, None, R, 0x58) + put(a, 52, 1, 0, 0, None, I, 0x21) + put(a, 56, 1, 0, 0, None, X, 0x20) + put(a, 60, 1, 0, 0, None, S, 0x8C) + for r in range(0, 64, 8): + put(a, r, 3, 61, 4, 64 - r // 2) + put(a, 20, 3, 0, 0, None, O, 0x08) + put(a, 24, 3, 61, 4, None, Q, 0x83) + put(a, 32, 3, 61, 4, None, S, 0xC3) + put(a, 40, 3, 61, 4, None, S, 0xD2) + put(a, 48, 2, 37, 3, None, V, 0x30) + put(a, 56, 2, 0, 0, None, V, 0x40) + put(b, 0, 2, 49, 3, None, A, 0x04) + put(b, 4, 2, 0, 0, None, Tt, 0x90) + put(b, 8, 2, 52, 5, None, S, 0xB0) + put(b, 10, 0, 64, 1) + put(b, 12, 2, 0, 0, None, S, 0xB2) + put(b, 16, 2, 56, 5, None, S, 0xE2) + put(b, 20, 0, 61, 1, None, O, 0x00) + put(b, 24, 0, 254) + put(b, 28, 2, 0, 0, None, C, 0x08) + put(c, 8, 0, 49, 1, 32) + put(c, 12, 1, 61, 2, None, X, 0x80) + put(c, 16, 1, 0, 0, None, S, 0x82) + put(c, 20, 0, 0, 0, None, B, 0x05) + if keep is not None: # debugging: only some channels + for p in (a, b, c): + for row in p: + for ch in range(4): + if ch not in keep and row[ch][3] not in (A, B, C, Tt, V): + row[ch] = (0, 0, None, 0, 0) + return T.write_s3m("effects", samples(), [0, 1, 254, 2], [a, b, c], 4) + + +def song_memory(): + """ST3's shared effect memory, fast slides (ST3.00), the panning table, global volume, an order loop""" + a = empty(6) + put(a, 0, 0, 61, 1, None, D, 0x08) + put(a, 4, 0, 0, 0, None, E, 0x02) + put(a, 8, 0, 0, 0, None, D, 0x00) + put(a, 12, 0, 0, 0, None, F, 0x00) + put(a, 0, 1, 49, 3, None, D, 0x80) + put(a, 2, 1, 0, 0, None, D, 0x00) + put(a, 16, 2, 73, 5) + put(a, 20, 2, 0, 0, None, Q, 0x02) + put(a, 24, 2, 0, 0, None, Q, 0x00) + put(a, 28, 3, 56, 2, 20) + put(a, 28, 4, 63, 1, 30) + put(a, 32, 5, 37, 3, None, X, 0x00) + put(a, 40, 5, 0, 0, None, S, 0xE3) + put(a, 48, 0, 0, 0, None, V, 0x20) + put(a, 63, 0, 0, 0, None, B, 0x00) + return T.write_s3m("memory", samples(), [0], [a], 6, speed=5, tempo=140, cwt=0x1300, + pans=[2, 13, 5, 10, 7, 15], mvol=64 | 128, gvol=48) + + +def song_mono(): + a = empty(2) + put(a, 0, 0, 61, 1) + put(a, 8, 1, 68, 2) + put(a, 16, 0, 0, 0, None, H, 0x28) + put(a, 32, 1, 0, 0, None, F, 0x10) + return T.write_s3m("mono", samples(), [0], [a], 2, mvol=32) + + +def generate(ctx): + cases = [] + for nm, data in (("effects", song_effects()), ("memory", song_memory()), ("mono", song_mono())): + ref = T.reference(ctx, data, "s3m") + cases.append({"name": nm, "data": data, "ref": ref, "duration": ref["duration"]}) + ctx.emit("s3m_cases", cases) diff --git a/tools/fixtures/sf2.py b/tools/fixtures/sf2.py new file mode 100644 index 0000000..638d874 --- /dev/null +++ b/tools/fixtures/sf2.py @@ -0,0 +1,227 @@ +# SoundFont fixtures (tools/fixtures.py): a small self-made SF2 (band-limited sine / saw / square loops + a noise +# burst; melodic presets with envelopes, a filter + mod envelope, vibrato, a preset global zone, an instrument global +# zone, a drum kit on bank 128 with exclusive classes), a 12.5 s test song (SMF written here) that plays each preset in +# its own 2 s segment (chords, pitch bend with an RPN 0 range of 12, sustain pedal, CC7 / CC11), the song rendered by +# FluidSynth (nixpkgs#fluidsynth, reverb and chorus off) and analysed with numpy (tools/fixtures/_sf2_features.py): +# tests/gen/sf2_cases.luau { sf2, sf2_24 (the same with an sm24 chunk), song, fluid = { env, bands, peaks }, +# expect = { presets, samples, instruments, info, values } } +import json, math, os, random, struct, subprocess, tempfile + +INPUTS = ["tools/fixtures/_sf2_features.py"] +RATE = 44100 +PERIOD = 100 # 441 Hz loops +CYCLES = 50 + + +def tc(sec): + return int(round(1200 * math.log2(sec))) + + +def hz_cents(hz): + return int(round(1200 * math.log2(hz / 8.176))) + + +def wave(kind, rng): + n = PERIOD * CYCLES + out = [] + for i in range(n): + ph = 2 * math.pi * i / PERIOD + if kind == "sine": + v = math.sin(ph) * 0.8 + elif kind == "saw": + v = sum(math.sin(k * ph) / k for k in range(1, 50)) * 0.45 + else: + v = sum(math.sin(k * ph) / k for k in range(1, 50, 2)) * 0.6 + out.append(v) + return out + + +def chunk(cid, data): + pad = b"\x00" if len(data) % 2 else b"" + return cid + struct.pack("> 8, x & 255 + pcm += struct.pack(" root 69, correction -4 makes it play 440 Hz-ish at key 69 + headers.append((name, start, end, start, end, RATE, 69, -4, 0, 1)) + if len(pcm24) % 2: + pcm24 += b"\x00" + info = lst(b"INFO", [chunk(b"ifil", struct.pack(">= 7 + while v: + out.insert(0, (v & 127) | 128) + v >>= 7 + return bytes(out) + + +def song(): + tpq, us = 480, 500000 # 1 beat = 0.5 s + ev = [] # (seconds, bytes) + + def at(sec, *b): + ev.append((sec, bytes(b))) + at(0, 0xC0, 0) + at(0, 0xC1, 1) + at(0, 0xC2, 2) + # seg 0: a sine chord + for n in (60, 64, 67): + at(0.0, 0x90, n, 127) + at(1.5, 0x80, n, 0) + # seg 1: a saw melody (filter + mod env) + for k, n in enumerate((48, 52, 55, 60)): + at(2.0 + 0.4 * k, 0x91, n, 127) + at(2.35 + 0.4 * k, 0x81, n, 0) + # seg 2: a square with vibrato + at(4.0, 0x92, 69, 127) + at(5.5, 0x82, 69, 0) + # seg 3: drums (hats cut each other: exclusive class) + for sec, n in ((6.0, 36), (6.25, 42), (6.5, 38), (6.75, 42), (7.0, 46), (7.25, 42), (7.5, 36)): + at(sec, 0x99, n, 127) + at(sec + 0.1, 0x89, n, 0) + # seg 4: sine with a pitch-bend range of 12 (RPN 0), a bend up an octave, the sustain pedal + at(7.9, 0xB0, 101, 0) + at(7.9, 0xB0, 100, 0) + at(7.9, 0xB0, 6, 12) + at(8.0, 0x90, 72, 127) + at(8.5, 0xE0, 0x7F, 0x7F) + at(9.0, 0xE0, 0x00, 0x40) + at(9.1, 0xB0, 64, 127) + at(9.2, 0x80, 72, 0) + at(9.6, 0xB0, 64, 0) + # seg 5: saw with volume and expression changes + at(10.0, 0x91, 57, 127) + at(10.75, 0xB1, 7, 60) + at(11.25, 0xB1, 11, 64) + at(11.6, 0x81, 57, 0) + ev.sort(key=lambda e: e[0]) + body, last = bytearray(), 0 + body += b"\x00\xff\x51\x03" + struct.pack(">I", us)[1:] + for sec, b in ev: + tick = int(round(sec * tpq * 1e6 / us)) + body += vlq(tick - last) + b + last = tick + end = int(round(12.5 * tpq * 1e6 / us)) + body += vlq(end - last) + b"\xff\x2f\x00" + return b"MThd" + struct.pack(">IHHH", 6, 0, 1, tpq) + b"MTrk" + struct.pack(">I", len(body)) + bytes(body) + + +def generate(ctx): + sf2, expect = build_sf2(False) + sf2_24, _ = build_sf2(True) + mid = song() + with tempfile.TemporaryDirectory() as d: + fp, mp, wp = os.path.join(d, "t.sf2"), os.path.join(d, "t.mid"), os.path.join(d, "t.wav") + with open(fp, "wb") as f: + f.write(sf2) + with open(mp, "wb") as f: + f.write(mid) + ctx.nix("fluidsynth", ["fluidsynth", "-ni", "-q", "-R", "0", "-C", "0", "-g", "0.5", "-r", "44100", "-F", wp, fp, mp]) + with open(wp, "rb") as f: + wav = f.read() + fluid = json.loads(ctx.python(["numpy"], ctx.read("tools/fixtures/_sf2_features.py").decode(), input=wav)) + ctx.emit("sf2_cases", {"sf2": sf2, "sf2_24": sf2_24, "song": mid, "fluid": fluid, "expect": expect}) diff --git a/tools/fixtures/videobench.py b/tools/fixtures/videobench.py new file mode 100644 index 0000000..d2c3eba --- /dev/null +++ b/tools/fixtures/videobench.py @@ -0,0 +1,27 @@ +# Video bench inputs (tools/fixtures.py, for tools/bench.luau): 1 s of testsrc2 at 320x240 and 640x480, 25 fps, as +# MJPEG AVI, MPEG-1 TS, VP8 WebM (libvpx) and 8 frames of 320x240 Y4M. +# tests/gen/videobench.luau { { name, size, data } } +import importlib.util, os, tempfile + +_spec = importlib.util.spec_from_file_location("_video_helpers", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_video.py")) +V = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(V) + +INPUTS = ["tools/fixtures/_video.py"] + + +def generate(ctx): + tmp = tempfile.mkdtemp(prefix="videobench_") + out = [] + for size in ("320x240", "640x480"): + src = ["-f", "lavfi", "-i", "testsrc2=size=%s:rate=25" % size, "-t", "1"] + for name, args in (("mjpeg.avi", ["-c:v", "mjpeg", "-q:v", "4"]), + ("mpeg1.ts", ["-c:v", "mpeg1video", "-b:v", "2M", "-bf", "2", "-f", "mpegts"]), + ("vp8.webm", ["-c:v", "libvpx", "-b:v", "1M", "-g", "50"]), + ("raw.y4m", ["-pix_fmt", "yuv420p", "-frames:v", "8"])): + if name == "raw.y4m" and size == "640x480": + continue + path = os.path.join(tmp, size + "_" + name) + V.ffmpeg(src + args + [path]) + out.append({"name": name, "size": size, "data": open(path, "rb").read()}) + ctx.emit("videobench", out) diff --git a/tools/fixtures/videoenc.py b/tools/fixtures/videoenc.py new file mode 100644 index 0000000..20f2411 --- /dev/null +++ b/tools/fixtures/videoenc.py @@ -0,0 +1,63 @@ +# Our video writers checked by ffprobe / ffmpeg (tools/fixtures.py): tools/fixtures/_video_encode.luau remuxes / +# re-encodes the container fixtures (WebM remux, MJPEG Matroska / AVI / MP4 from VP8 and MPEG-1, MJPEG copies, H.264 + +# AAC MP4 to MOV / Matroska, PCM MOV, FLAC MP4, an animated GIF with uneven delays to AVI / Matroska / Y4M / MP4, WebM +# to Y4M); each output must probe in ffprobe and decode in +# ffmpeg. Emitted per file: our bytes, ffprobe's streams and packets, ffmpeg's frames (CRC-32; the first raw) and +# audio, so the test can decode our file with our decoders and compare. +# tests/gen/videoenc_src.luau { gif = } +# tests/gen/videoenc_cases.luau { { name, data, streams, packets, frames, yuv, pcm, pcmBytes } | { name, err } } +import importlib.util, os, shutil, subprocess, tempfile + +_spec = importlib.util.spec_from_file_location("_video_helpers", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_video.py")) +V = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(V) + +INPUTS = ["tools/fixtures/_video.py", "tools/fixtures/_video_encode.luau", "tools/fixtures/mkv.py", "tools/fixtures/avi.py", "tools/fixtures/mp4.py", + "src/Formats/video", "src/Formats/codecs/Video", "src/Formats/containers/Ebml", "src/Formats/containers/Avi", "src/Formats/containers/IsoBmff", + "src/Formats/codecs/Jpeg", "src/Formats/codecs/Vp8"] + +GIF = r""" +import io, sys +from PIL import Image, ImageDraw +frames = [] +for i, c in enumerate([(255, 0, 0), (0, 160, 0), (0, 0, 255), (240, 200, 0)]): + im = Image.new("RGB", (64, 48), (20, 20, 20)) + d = ImageDraw.Draw(im) + d.rectangle([4 + i * 10, 8, 24 + i * 10, 40], fill=c) + d.ellipse([40, 4 + i * 6, 60, 20 + i * 6], fill=(255, 255, 255)) + frames.append(im) +b = io.BytesIO() +frames[0].save(b, "GIF", save_all=True, append_images=frames[1:], duration=[100, 50, 200, 100], loop=0) +sys.stdout.buffer.write(b.getvalue()) +""" + + +def generate(ctx): + tmp = tempfile.mkdtemp(prefix="videoenc_") + gif = ctx.python(["pillow"], GIF) + ctx.emit("videoenc_src", {"gif": gif}) + luau = os.environ.get("LUAU") or shutil.which("luau") + cmd = [luau, "tools/fixtures/_video_encode.luau"] if luau else ["nix", "shell", "nixpkgs#luau", "-c", "luau", "tools/fixtures/_video_encode.luau"] + out = subprocess.run(cmd, capture_output=True, check=True, cwd=ctx.root).stdout.decode() + cases = [] + for line in out.split("\n"): + if not line.strip(): + continue + name, rest = line.split(" ", 1) + if rest.startswith("ERR "): + cases.append({"name": name, "err": rest[4:]}) + continue + path = os.path.join(tmp, name) + open(path, "wb").write(bytes.fromhex(rest)) + c = {"name": name, "data": open(path, "rb").read(), "streams": V.streams(path), "packets": V.packets(path)} + vs = [s for s in c["streams"] if s["kind"] == "video"] + if vs: + frames = V.yuv_frames(path, vs[0]["width"], vs[0]["height"], codec=vs[0]["codec"]) + c["frames"] = [V.crc(f) for f in frames] + c["yuv"] = frames[:3] + if any(s["kind"] == "audio" for s in c["streams"]): + pcm = V.pcm_f32(path) + c["pcm"] = pcm[:8192 * 4] + c["pcmBytes"] = len(pcm) + cases.append(c) + ctx.emit("videoenc_cases", cases) diff --git a/tools/fixtures/voc.py b/tools/fixtures/voc.py new file mode 100644 index 0000000..b207bd8 --- /dev/null +++ b/tools/fixtures/voc.py @@ -0,0 +1,39 @@ +# Creative VOC fixtures (tools/fixtures.py): files written by ffmpeg (type 1 + type 8 blocks for 8-bit, type 9 for the +# rest) and sox, each with ffmpeg's f32 decode as the reference; our encoder's output for every sample format, decoded +# by ffmpeg in the fixture step (tools/fixtures/_audio.py pcm_fixtures). +# tests/gen/voc_cases.luau { name, data, rate, channels, frames, ref (f32le) } +# tests/gen/voc_enc.luau { name, opts, channels, rate, frames, maxDiff, ffmpegErrors, bytes, sameStreamed, data } +# tests/gen/voc_sig*.luau the encoder inputs +import importlib.util, os + +_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 = ["src/Formats/audio/voc", "src/Formats/codecs/Pcm"] + + +def ff(codec, src="{in}", extra=()): + return ["ffmpeg", "-v", "error", "-i", src] + list(extra) + ["-c:a", codec, "-f", "voc", "-y", "{out}"] + + +def generate(ctx): + made = [ + ("ffmpeg-u8-stereo", "ffmpeg", ff("pcm_u8")), + ("ffmpeg-u8-mono", "ffmpeg", ff("pcm_u8", "{in_mono}")), + ("ffmpeg-s16", "ffmpeg", ff("pcm_s16le")), + ("ffmpeg-s16-mono-44k", "ffmpeg", ff("pcm_s16le", "{in_mono}", ("-ar", "44100"))), + ("ffmpeg-alaw", "ffmpeg", ff("pcm_alaw")), + ("ffmpeg-ulaw", "ffmpeg", ff("pcm_mulaw", "{in_mono}")), + ("sox-u8-mono-11k", "sox", ["sox", "{in_mono}", "-r", "11025", "-b", "8", "-t", "voc", "{out}"]), + ("sox-u8-stereo", "sox", ["sox", "{in}", "-b", "8", "-t", "voc", "{out}"]), + ("sox-s16-stereo", "sox", ["sox", "{in}", "-b", "16", "-t", "voc", "{out}"]), + ] + encodes = [ + ("s16", "nil", 2), + ("s16-mono", "nil", 1), + ("u8", '{ sampleFormat = "u8" }', 2), + ("alaw", '{ sampleFormat = "alaw" }', 2), + ("ulaw", '{ sampleFormat = "ulaw" }', 1), + ] + A.pcm_fixtures(ctx, "voc", made, encodes) diff --git a/tools/fixtures/vorbis.py b/tools/fixtures/vorbis.py new file mode 100644 index 0000000..e4994ee --- /dev/null +++ b/tools/fixtures/vorbis.py @@ -0,0 +1,57 @@ +# Ogg Vorbis fixtures (tools/fixtures.py): files made by oggenc (libvorbis, vorbis-tools) and ffmpeg (libvorbis) from +# the test signals in tools/fixtures/_audio.py: qualities -1 .. 10, managed bitrate, 8 .. 96 kHz, mono / stereo / 5.1, +# transients (block switching), silence, tags, a stream shorter than one block. References: oggdec (libvorbisfile: +# the authority on start / end trimming) as 16-bit samples, and ffmpeg's f32 decode (more precise, but its Ogg demuxer +# trims some streams differently: the test uses it only when its frame count agrees with oggdec). +# tests/gen/vorbis_cases.luau { name, data, rate, channels, frames (oggdec), ref16 (s16le, oggdec), ffFrames, +# ffRef (f32le, ffmpeg), inputFrames } +import importlib.util, os + +_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) + +CASES = [ + # name, signal, rate, channels, seconds, tool, args + ("q5-stereo-44k-music", "music", 44100, 2, 1.5, "oggenc", ["-q", "5"]), + ("q-1-mono-8k-music", "music", 8000, 1, 1.0, "oggenc", ["-q", "-1"]), + ("q10-stereo-48k-sweep", "sweep", 48000, 2, 1.0, "oggenc", ["-q", "10"]), + ("q3-mono-22k-noise", "noise", 22050, 1, 0.7, "oggenc", ["-q", "3"]), + ("q0-stereo-44k-square", "square", 44100, 2, 1.0, "oggenc", ["-q", "0"]), + ("q2-stereo-32k-tags", "sine", 32000, 2, 0.6, "oggenc", ["-q", "2", "-t", "A Title", "-a", "An Artist", "-l", "The Album", "-N", "7", "-c", "comment=hello vorbis"]), + ("managed-64k-stereo", "music", 44100, 2, 1.0, "oggenc", ["--managed", "-b", "64"]), + ("silence-stereo", "silence", 44100, 2, 0.5, "oggenc", ["-q", "4"]), + ("short-100", "sine", 44100, 2, 100 / 44100, "oggenc", ["-q", "4"]), + ("short-3000-mono", "music", 44100, 1, 3000 / 44100, "oggenc", ["-q", "4"]), + ("q6-stereo-96k", "music", 96000, 2, 0.4, "oggenc", ["-q", "6"]), + ("ffmpeg-5.1-48k", "music", 48000, 6, 0.6, "ffmpeg", ["-c:a", "libvorbis", "-q:a", "4"]), + ("ffmpeg-mono-16k", "sweep", 16000, 1, 0.8, "ffmpeg", ["-c:a", "libvorbis", "-q:a", "1"]), + ("loud-stereo", "loud", 44100, 2, 0.5, "oggenc", ["-q", "8"]), +] + +INPUTS = [] + + +def generate(ctx): + cases = [] + bench = None + for name, kind, rate, ch, secs, tool, args in CASES: + frames = max(1, int(round(secs * rate))) + sig = A.signal(kind, rate, ch, frames, seed=len(name)) + wav = A.wav(sig, rate, ch, float_=True) if tool == "ffmpeg" else A.wav(sig, rate, ch, 16) + if tool == "oggenc": + data = A.tool(ctx, "vorbis-tools", ["oggenc", "-Q", "--serial", "1234"] + args + ["-o", "{out}", "{in}"], wav, "wav", "ogg") + else: + data = A.tool(ctx, "ffmpeg", ["ffmpeg", "-v", "error", "-i", "{in}"] + args + ["-f", "ogg", "-y", "{out}"], wav, "wav", "ogg") + rrate, rch, ref = A.ffdecode(ctx, data, ext="ogg") + raw = A.tool(ctx, "vorbis-tools", ["oggdec", "-Q", "-R", "-o", "{out}", "{in}"], data, "ogg", "raw") + case = {"name": name, "data": data, "rate": rrate, "channels": rch, "frames": len(raw) // (2 * rch), "ref16": raw, + "ffFrames": len(ref) // rch, "inputFrames": frames} + if len(ref) // rch == len(raw) // (2 * rch): + case["ffRef"] = A.f32le(ref) + cases.append(case) + ctx.emit("vorbis_cases", cases) + # bench: 10 s of stereo music at q5 + sig = A.signal("music", 44100, 2, 441000, seed=9) + data = A.tool(ctx, "vorbis-tools", ["oggenc", "-Q", "-q", "5", "-o", "{out}", "{in}"], A.wav(sig, 44100, 2, 16), "wav", "ogg") + ctx.emit("vorbis_bench", {"data": data, "frames": 441000, "rate": 44100, "channels": 2}) diff --git a/tools/fixtures/vorbis_enc.py b/tools/fixtures/vorbis_enc.py new file mode 100644 index 0000000..8cfc69c --- /dev/null +++ b/tools/fixtures/vorbis_enc.py @@ -0,0 +1,74 @@ +# Vorbis encoder fixtures (tools/fixtures.py): our encoder runs in the fixture step (tools/fixtures/_audio.py +# encode_luau_many) on test signals (qualities -1 .. 10, mono / stereo / 5.1, 8 .. 96 kHz, odd lengths, silence); +# oggdec (libvorbisfile) and ffmpeg decode every file, ogginfo checks the stream. Recorded per file: ogginfo's warnings +# and errors, oggdec's frame count, the SNR of oggdec's and ffmpeg's decodes against the input (no delay: the +# granules are exact). +# tests/gen/vorbis_enc.luau { name, sig, quality, rate, channels, frames, ogginfo, oggdecFrames, oggdecSnr, +# ffFrames, ffSnr, ffErrors, kbps, data } +# tests/gen/vorbis_enc_sigs.luau { [sig] = { rate, channels, frames, data (f32le) } } +import importlib.util, os, re + +_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 = ["src/Formats/audio/vorbis", "src/Formats/codecs", "src/Formats/containers/Ogg"] + + +WAVE_FROM_VORBIS6 = [0, 2, 1, 4, 5, 3] # vorbis channel k is WAVE channel WAVE_FROM_VORBIS6[k] + + +def reorder(x): + out = [0.0] * len(x) + for i in range(0, len(x) - 5, 6): + for k in range(6): + out[i + k] = x[i + WAVE_FROM_VORBIS6[k]] + return out + + +def generate(ctx): + sigs = {} + + def sig(kind, ch, frames, rate): + name = "%s_%d_%d_%d" % (kind, ch, frames, rate) + if name not in sigs: + sigs[name] = (A.from_f32le(A.f32le(A.signal(kind, rate, ch, frames, seed=frames % 1000 + ch))), rate, ch) + return name + + cases = [] + for q in (-1, 0, 3, 6, 10): + cases.append(("music-st-44k-q%d" % q, sig("music", 2, 44100, 44100), q)) + cases.append(("sine-st-44k-q3", sig("sine", 2, 30000, 44100), 3)) + cases.append(("sweep-mono-48k-q3", sig("sweep", 1, 40000, 48000), 3)) + cases.append(("noise-mono-22k-q5", sig("noise", 1, 15000, 22050), 5)) + cases.append(("music-mono-8k-q2", sig("music", 1, 9000, 8000), 2)) + cases.append(("music-st-96k-q4", sig("music", 2, 30000, 96000), 4)) + cases.append(("music-6ch-48k-q3", sig("music", 6, 20000, 48000), 3)) + cases.append(("square-st-32k-q5", sig("square", 2, 20000, 32000), 5)) + cases.append(("loud-st-44k-q8", sig("loud", 2, 20000, 44100), 8)) + cases.append(("silence-st-44k", sig("silence", 2, 10000, 44100), 3)) + for n in (1, 100, 1024, 1025, 3000): + cases.append(("len-%d" % n, sig("music", 2, n, 44100), 3)) + ctx.emit("vorbis_enc_sigs", {n: {"rate": r, "channels": c, "frames": len(x) // c, "data": A.f32le(x)} for n, (x, r, c) in sigs.items()}) + outs = A.encode_luau_many(ctx, "audio/vorbis", [(c[1], "{ quality = %d }" % c[2]) for c in cases], "vorbis_enc_sigs") + emitted = [] + for (name, sigmod, q), data in zip(cases, outs): + samples, rate, ch = sigs[sigmod] + frames = len(samples) // ch + info = A.tool(ctx, "vorbis-tools", ["sh", "-c", "ogginfo {in} 2>&1; true"], data, "ogg").decode(errors="replace") + problems = "\n".join(l for l in info.split("\n") if re.search(r"(?i)warning|error", l)) + raw = A.tool(ctx, "vorbis-tools", ["oggdec", "-Q", "-R", "-o", "{out}", "{in}"], data, "ogg", "raw") + od = [int.from_bytes(raw[i:i + 2], "little", signed=True) / 32768 for i in range(0, len(raw) - 1, 2)] + osnr, _ = A.snr(samples, od, ch) # (oggdec -R keeps the Vorbis channel order) + ffe = A.tool(ctx, "ffmpeg", ["ffmpeg", "-v", "error", "-i", "{in}", "-f", "null", "-"], data, "ogg").decode(errors="replace") + _, fch, ff = A.ffdecode(ctx, data, ext="ogg") + if ch == 6: # ffmpeg reorders to WAVE order (FL FR FC LFE RL RR); Vorbis order is FL FC FR RL RR LFE + ff = reorder(ff) + fsnr, _ = A.snr(samples, ff, ch) if fch == ch else (-99.0, 0) + e = {"name": name, "sig": sigmod, "quality": q, "rate": rate, "channels": ch, "frames": frames, "ogginfo": problems, + "oggdecFrames": len(od) // ch, "oggdecSnr": osnr, "ffFrames": len(ff) // max(1, fch), "ffSnr": fsnr, + "ffErrors": ffe, "kbps": len(data) * 8 / (frames / rate) / 1000, "data": data} + emitted.append(e) + print(" vorbis_enc: %-22s %7.1f kbps oggdec %d/%d frames %.1f dB ffmpeg %.1f dB%s" % (name, e["kbps"], e["oggdecFrames"], frames, + osnr, fsnr, (" OGGINFO " + problems[:80]) if problems else "")) + ctx.emit("vorbis_enc", emitted) diff --git a/tools/fixtures/vp8video.py b/tools/fixtures/vp8video.py new file mode 100644 index 0000000..1a01039 --- /dev/null +++ b/tools/fixtures/vp8video.py @@ -0,0 +1,133 @@ +# VP8 video fixtures (tools/fixtures.py) for tests/codecs/vp8video.luau and tools/bench.luau. Clips are encoded by +# ffmpeg's libvpx into IVF (many encoder settings: alt-ref / hidden frames, golden refreshes, token partitions, error +# resilience, profiles 1-3, sharpness, segmentation, q extremes, short key frame intervals, motion off the frame edges), +# plus the official VP8 test vectors (tests/fixtures/vp8video/vp80-*.ivf, from the libvpx test data, BSD: +# licenses/libvpx-LICENSE.txt). The reference output is ffmpeg's native vp8 decoder (bit-exact with libvpx): +# `ffmpeg -c:v vp8 -i x.ivf -noautoscale -fps_mode passthrough -f framehash -hash crc32 -`: the CRC32 of every +# shown yuv420p frame (and its size: key frames may change it). +# tests/gen/vp8video_cases.luau { name, ivf, width, height (of the first frame), crcs, sizes (bytes) } +# tests/gen/vp8video_bench.luau { { name, ivf, width, height, frames, crcs, sizes } } for tools/bench.luau +import os, shutil, subprocess, tempfile, zlib + +INPUTS = ["tests/fixtures/vp8video"] + +VECTORS = "tests/fixtures/vp8video" + + +def ffmpeg(ctx, args): + """runs ffmpeg (the one on PATH when it has libvpx, else nixpkgs#ffmpeg) and returns stdout""" + exe = shutil.which("ffmpeg") + if exe: + enc = subprocess.run([exe, "-hide_banner", "-encoders"], capture_output=True).stdout + if b"libvpx " in enc: + return subprocess.run([exe, "-hide_banner", "-loglevel", "error"] + args, capture_output=True, check=True).stdout + return ctx.nix("ffmpeg", ["ffmpeg", "-hide_banner", "-loglevel", "error"] + args) + + +def ivf_size(data): + return data[12] | data[13] << 8, data[14] | data[15] << 8 + + +def reference(ctx, path): + """ffmpeg's decode: (crc32, byte size) of each shown yuv420p frame (sizes may change at key frames)""" + out = ffmpeg(ctx, ["-c:v", "vp8", "-i", path, "-noautoscale", "-fps_mode", "passthrough", "-f", "framehash", + "-hash", "crc32", "-"]) + frames = [] + for line in out.decode().splitlines(): + if line and not line.startswith("#"): + f = [x.strip() for x in line.split(",")] + frames.append((int(f[5], 16), int(f[4]))) + return frames + + +# (name, lavfi source, frames, encoder options) +SRC_320 = "testsrc2=s=320x240:r=25" +PAN = "testsrc2=s=480x360:r=25,crop=w=320:h=240:x='80+70*sin(t*3)':y='60+50*cos(t*2)'" +CLIPS = [ + ("default_320x240", SRC_320, 20, ["-b:v", "400k"]), + ("odd_173x95", "mandelbrot=s=173x95:r=25", 16, ["-b:v", "200k"]), + ("pan_320x240", PAN, 24, ["-b:v", "300k", "-g", "100"]), + ("altref_352x288", "testsrc2=s=352x288:r=25", 30, + ["-b:v", "300k", "-auto-alt-ref", "1", "-lag-in-frames", "16", "-arnr-maxframes", "7", "-arnr-strength", "5", + "-arnr-type", "3", "2pass"]), + ("altref_pan", PAN, 30, ["-b:v", "250k", "-auto-alt-ref", "1", "-lag-in-frames", "25", "-g", "200", "2pass"]), + ("tokenparts3", SRC_320, 12, ["-b:v", "500k", "-slices", "8"]), + ("tokenparts1_odd", "mandelbrot=s=201x77:r=25", 12, ["-b:v", "300k", "-slices", "2"]), + ("error_resilient", PAN, 16, ["-b:v", "300k", "-error-resilient", "1"]), + ("profile1", PAN, 16, ["-b:v", "300k", "-profile:v", "1"]), + ("profile2", PAN, 16, ["-b:v", "300k", "-profile:v", "2"]), + ("profile3", PAN, 16, ["-b:v", "300k", "-profile:v", "3"]), + ("sharpness7", PAN, 12, ["-b:v", "200k", "-sharpness", "7"]), + ("sharpness3", "mandelbrot=s=160x120:r=25", 12, ["-b:v", "150k", "-sharpness", "3"]), + ("realtime_cyclic", PAN, 24, + ["-deadline", "realtime", "-cpu-used", "8", "-b:v", "200k", "-static-thresh", "100", "-screen-content-mode", "1"]), + ("realtime_noise", "testsrc2=s=320x240:r=25,noise=alls=30:allf=t", 16, + ["-deadline", "realtime", "-cpu-used", "4", "-b:v", "400k"]), + ("best_split", "testsrc2=s=176x144:r=25,rotate=a='t*0.4':c=black", 16, ["-deadline", "best", "-b:v", "250k"]), + ("cellauto_split", "cellauto=s=176x144:rule=110:r=25,scale=176:144", 16, ["-b:v", "300k", "-cpu-used", "0"]), + ("q_high", PAN, 10, ["-qmin", "0", "-qmax", "2", "-b:v", "20M"]), + ("q_low", PAN, 16, ["-qmin", "60", "-qmax", "63", "-b:v", "20k"]), + ("keyint5", PAN, 16, ["-b:v", "300k", "-g", "5"]), + ("golden", "testsrc2=s=240x160:r=25", 40, ["-b:v", "150k", "-g", "300", "-auto-alt-ref", "0"]), + ("big_motion", "testsrc2=s=640x480:r=25,crop=w=192:h=144:x='224+200*sin(t*9)':y='168+150*cos(t*7)'", 16, + ["-b:v", "300k"]), + ("tiny_24x18", "testsrc2=s=24x18:r=25", 12, ["-b:v", "50k"]), + ("temporal_layers", PAN, 16, + ["-deadline", "realtime", "-b:v", "300k", "-ts-parameters", + "ts_number_layers=2:ts_target_bitrate=150,300:ts_rate_decimator=2,1:ts_periodicity=2:ts_layer_id=0,1"]), +] + +BENCH = [ + ("bench_320x240", "testsrc2=s=480x360:r=25,crop=w=320:h=240:x='80+70*sin(t*3)':y='60+50*cos(t*2)'", 40, + ["-b:v", "500k"]), + ("bench_640x480", "testsrc2=s=960x720:r=25,crop=w=640:h=480:x='160+150*sin(t*3)':y='120+100*cos(t*2)'", 30, + ["-b:v", "1200k"]), +] + + +def encode(ctx, tmp, name, src, frames, opts): + path = os.path.join(tmp, name + ".ivf") + base = ["-f", "lavfi", "-i", src, "-frames:v", str(frames), "-pix_fmt", "yuv420p", "-c:v", "libvpx"] + try: + if "2pass" in opts: # alt-ref frames need the two-pass encoder + opts = [o for o in opts if o != "2pass"] + log = os.path.join(tmp, name + "-pass") + ffmpeg(ctx, base + opts + ["-pass", "1", "-passlogfile", log, "-f", "null", "-"]) + opts = opts + ["-pass", "2", "-passlogfile", log] + ffmpeg(ctx, base + opts + ["-f", "ivf", "-y", path]) + except subprocess.CalledProcessError as e: + if name == "temporal_layers": # optional: depends on the libvpx wrapper's options + return None + raise RuntimeError("vp8video: %s: %s" % (name, e.stderr.decode(errors="replace"))) + return path + + +def case(ctx, name, path): + with open(path, "rb") as f: + data = f.read() + w, h = ivf_size(data) + ref = reference(ctx, path) + return {"name": name, "ivf": data, "width": w, "height": h, "crcs": [r[0] for r in ref], "sizes": [r[1] for r in ref]} + + +def generate(ctx): + tmp = tempfile.mkdtemp(prefix="vp8video") + try: + cases = [] + vec = os.path.join(ctx.root, VECTORS) + for f in sorted(os.listdir(vec)): + if f.endswith(".ivf"): + cases.append(case(ctx, f[:-4], os.path.join(vec, f))) + for name, src, frames, opts in CLIPS: + path = encode(ctx, tmp, name, src, frames, opts) + if path: + cases.append(case(ctx, name, path)) + ctx.emit("vp8video_cases", cases) + bench = [] + for name, src, frames, opts in BENCH: + c = case(ctx, name, encode(ctx, tmp, name, src, frames, opts)) + c["frames"] = len(c["crcs"]) + bench.append(c) + ctx.emit("vp8video_bench", bench) + finally: + shutil.rmtree(tmp) diff --git a/tools/fixtures/xm.py b/tools/fixtures/xm.py new file mode 100644 index 0000000..812302e --- /dev/null +++ b/tools/fixtures/xm.py @@ -0,0 +1,167 @@ +# XM fixtures (tools/fixtures.py): generated FastTracker 2 modules exercising instruments (envelopes, fadeout, +# auto-vibrato, keymaps, 16-bit and ping-pong samples) and the effects, rendered by openmpt123. +# tests/gen/xm_cases.luau { name, data (the module), ref (features of openmpt's render, tools/fixtures/_tracker.py), +# duration (openmpt's song length) } +import os, sys + +# 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"] + +OFF = 97 +Gx, Hx, Kx, Lx, Px, Rx, Tx, Xx = 16, 17, 20, 21, 25, 27, 29, 33 + + +def empty(ch, rows=64): + return [[(0, 0, 0, 0, 0) for _ in range(ch)] for _ in range(rows)] + + +def put(p, row, ch, note=0, ins=0, vol=0, fx=0, param=0): + p[row][ch] = (note, ins, vol, fx, param) + + +def instruments(): + sine = {"name": "sine", "data": T.s8(T.synth("sine", 64, 64)), "volume": 64, "pan": 128, "loop": (0, 64, 1)} + tri = {"name": "tri", "data": T.s8(T.synth("tri", 32, 32, 0.8)), "volume": 48, "pan": 96, "relnote": 12, "finetune": -20, + "loop": (0, 32, 1)} + saw16 = {"name": "saw16", "data": T.s16(T.synth("saw", 128, 64, 0.6)), "bits": 16, "volume": 56, "pan": 160, + "loop": (0, 128, 1)} + ping = {"name": "ping", "data": T.s8(T.synth("saw", 200, 200, 0.7)), "volume": 64, "pan": 128, "finetune": 30, + "loop": (20, 150, 2)} + noise = {"name": "noise", "data": T.s8(T.synth("noise", 5000, 1, 0.7, decay=1500)), "volume": 60, "pan": 128} + square = {"name": "square", "data": T.s8(T.synth("square", 64, 64, 0.5)), "volume": 64, "pan": 128, "loop": (0, 64, 1)} + return [ + {"name": "env", "samples": [sine], "volenv": {"points": [(0, 0), (4, 64), (10, 40), (30, 20), (40, 0)], "sustain": 2}, + "fadeout": 1024}, + {"name": "panloop", "samples": [square], "panenv": {"points": [(0, 0), (8, 64), (16, 0)], "loop": (0, 2)}, + "volenv": {"points": [(0, 64), (20, 48), (60, 32)], "loop": (1, 2)}, "fadeout": 512}, + {"name": "autovib", "samples": [saw16], "vib": (0, 10, 8, 6)}, + {"name": "multi", "samples": [sine, tri], "keymap": [0] * 48 + [1] * 48}, + {"name": "ping", "samples": [ping]}, + {"name": "noise", "samples": [noise]}, + {"name": "sq vib", "samples": [square], "vib": (1, 0, 4, 20)}, + {"name": "empty"}, + ] + + +def song_instruments(): + a, b = empty(4), empty(4) + put(a, 0, 0, 49, 1) + put(a, 12, 0, OFF) + put(a, 20, 0, 56, 1) + put(a, 24, 0, 0, 0, 0, Kx, 3) + put(a, 32, 0, 61, 1) + put(a, 33, 0, 0, 0, 0, Lx, 20) + put(a, 40, 0, 63) + put(a, 44, 0, OFF) + put(a, 48, 0, 0, 1) + put(a, 0, 1, 37, 2) + put(a, 30, 1, OFF) + put(a, 40, 1, 44, 2) + put(a, 0, 2, 49, 3) + put(a, 32, 2, 56, 3) + put(a, 8, 3, 37, 4) + put(a, 16, 3, 61, 4) + put(a, 24, 3, 73, 4) + put(a, 32, 3, 85, 4) + put(a, 40, 3, 49, 5) + put(a, 52, 3, 61, 5) + put(a, 60, 3, 61, 8) + put(b, 0, 0, 49, 7) + put(b, 0, 1, 56, 3, 0x30) + put(b, 8, 1, 0, 3) + put(b, 16, 2, 61, 6, 0x40) + put(b, 20, 2, 61, 6, 0, 0x9, 0x08) + put(b, 24, 2, 61, 6, 0, 0xE, 0x93) + put(b, 32, 3, 49, 1) + put(b, 36, 3, 61) + put(b, 40, 3, OFF) + put(b, 44, 3, 63) + put(b, 48, 0, 0, 0, 0, 0xD, 0x00) + return T.write_xm("instruments", instruments(), [0, 1], [a, b], 4) + + +def song_effects(linear=True): + a, b = empty(6), empty(6, 48) + put(a, 0, 0, 49, 7, 0, 0x1, 0x04) + put(a, 4, 0, 0, 0, 0, 0x1, 0x00) + put(a, 8, 0, 0, 0, 0, 0x2, 0x08) + put(a, 12, 0, 0, 0, 0, 0xE, 0x18) + put(a, 13, 0, 0, 0, 0, 0xE, 0x10) + put(a, 14, 0, 0, 0, 0, 0xE, 0x2F) + put(a, 16, 0, 0, 0, 0, Xx, 0x1F) + put(a, 17, 0, 0, 0, 0, Xx, 0x10) + put(a, 18, 0, 0, 0, 0, Xx, 0x28) + put(a, 20, 0, 49, 7, 0, 0x3, 0x10) + put(a, 21, 0, 61, 0, 0, 0x3, 0x00) + put(a, 24, 0, 0, 0, 0, 0x5, 0x02) + put(a, 28, 0, 56, 0, 0, 0x4, 0x48) + put(a, 32, 0, 0, 0, 0, 0x6, 0x20) + put(a, 36, 0, 0, 0, 0, 0x7, 0x6F) + put(a, 40, 0, 0, 0, 0, Tx, 0x21) + put(a, 44, 0, 0, 0, 0, 0xA, 0x0F) + put(a, 46, 0, 0, 0, 0, 0xE, 0xA8) + put(a, 48, 0, 61, 7, 0, 0x0, 0x37) + put(a, 52, 0, 0, 0, 0, 0xE, 0xC3) + # channel 1: the volume column + put(a, 0, 1, 56, 6, 0x30) + put(a, 4, 1, 0, 0, 0x64) + put(a, 8, 1, 0, 0, 0x73) + put(a, 12, 1, 0, 0, 0x85) + put(a, 13, 1, 0, 0, 0x9A) + put(a, 16, 1, 0, 0, 0xA6) + put(a, 17, 1, 0, 0, 0xB8) + put(a, 24, 1, 0, 0, 0xC2) + put(a, 28, 1, 0, 0, 0xE4) + put(a, 32, 1, 0, 0, 0xD6) + put(a, 36, 1, 61, 0, 0xF8) + put(a, 40, 1, 49, 0, 0xF0) + # channel 2: panning, retrig, offset, delay + put(a, 0, 2, 61, 2, 0, 0x8, 0x20) + put(a, 8, 2, 0, 0, 0, Px, 0x30) + put(a, 16, 2, 0, 0, 0, Px, 0x06) + put(a, 24, 2, 61, 6, 0, Rx, 0x83) + put(a, 32, 2, 61, 6, 0, Rx, 0x32) + put(a, 40, 2, 61, 6, 0, 0x9, 0x06) + put(a, 48, 2, 61, 6, 0, 0xE, 0xD3) + put(a, 56, 2, 61, 6, 0x20, 0xE, 0xC2) + # channel 3: global volume, pattern loop, pattern delay, speed / tempo + put(a, 0, 3, 37, 3, 0, Gx, 0x30) + put(a, 8, 3, 0, 0, 0, Hx, 0x02) + put(a, 16, 3, 0, 0, 0, Hx, 0x40) + put(a, 24, 3, 0, 0, 0, 0xE, 0x60) + put(a, 26, 3, 0, 0, 0, 0xE, 0x62) + put(a, 32, 3, 0, 0, 0, 0xE, 0xE2) + put(a, 40, 3, 0, 0, 0, 0xF, 0x05) + put(a, 48, 3, 0, 0, 0, 0xF, 0x96) + # channel 4 / 5: an instrument change without a note, an empty instrument, a note after key off + put(a, 0, 4, 49, 1) + put(a, 8, 4, 0, 2) + put(a, 16, 4, OFF) + put(a, 24, 4, 51) + put(a, 32, 4, 51, 8) + put(a, 40, 4, 53, 1) + put(a, 4, 5, 73, 5, 0, 0xE, 0x80) + put(a, 20, 5, 0, 0, 0, 0x8, 0xC0) + # pattern b (48 rows): portamento in the other direction, arpeggio, a break and a jump back (song loop) + put(b, 0, 0, 73, 7, 0, 0x4, 0x00) + put(b, 0, 1, 61, 4) + put(b, 4, 1, 0, 0, 0, 0x0, 0x47) + put(b, 16, 1, 25, 4, 0, 0x2, 0x10) + put(b, 32, 0, 0, 0, 0, 0xB, 0x01) + return T.write_xm("effects", instruments(), [0, 1], [a, b], 6, speed=5, tempo=130, linear=linear, restart=1) + + +def generate(ctx): + cases = [] + for nm, data in (("instruments", song_instruments()), ("effects", song_effects()), ("amiga", song_effects(False))): + ref = T.reference(ctx, data, "xm") + cases.append({"name": nm, "data": data, "ref": ref, "duration": ref["duration"]}) + ctx.emit("xm_cases", cases) diff --git a/tools/fixtures/y4m.py b/tools/fixtures/y4m.py new file mode 100644 index 0000000..782f9b9 --- /dev/null +++ b/tools/fixtures/y4m.py @@ -0,0 +1,34 @@ +# YUV4MPEG2 fixtures (tools/fixtures.py): streams written by ffmpeg in C420jpeg (odd size 173x95), C420mpeg2, C422, +# C444, Cmono and C420p10 (10-bit) with ffmpeg's yuv420p decode of each (CRC-32 per frame; the first frames raw for +# the converted layouts, which are compared by PSNR). +# tests/gen/y4m_cases.luau { { name, data, width, height, rate = { num, den }, frames = { crc }, yuv = { raw } } } +import importlib.util, os, tempfile + +_spec = importlib.util.spec_from_file_location("_video_helpers", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_video.py")) +V = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(V) + +INPUTS = ["tools/fixtures/_video.py"] + + +def generate(ctx): + tmp = tempfile.mkdtemp(prefix="y4mfx_") + cases = [] + for name, size, rate, pix, extra in [ + ("c420jpeg.y4m", "173x95", "30000/1001", "yuv420p", []), + ("c420mpeg2.y4m", "160x120", "25", "yuv420p", ["-chroma_sample_location", "left"]), + ("c422.y4m", "160x120", "24", "yuv422p", []), + ("c444.y4m", "160x120", "10", "yuv444p", []), + ("cmono.y4m", "160x120", "10", "gray", []), + ("c420p10.y4m", "96x64", "10", "yuv420p10le", ["-strict", "-1"]), + ]: + path = os.path.join(tmp, name) + w, h = (int(x) for x in size.split("x")) + V.ffmpeg(["-f", "lavfi", "-i", "testsrc2=size=%s:rate=%s" % (size, rate), "-frames:v", "6", "-vf", + "pad=%d:%d" % (w + 1, h + 1) if w % 2 else "null", "-s", size, "-pix_fmt", pix] + extra + [path]) + frames = V.yuv_frames(path, w, h) + num, den = (rate.split("/") + ["1"])[:2] + cases.append({"name": name, "data": open(path, "rb").read(), "width": w, "height": h, + "rate": [int(num), int(den)], "frames": [V.crc(f) for f in frames], "yuv": frames[:2], + "exact": pix == "yuv420p"}) + ctx.emit("y4m_cases", cases) diff --git a/tools/test.sh b/tools/test.sh index 5e80063..30868d2 100644 --- a/tools/test.sh +++ b/tools/test.sh @@ -14,7 +14,7 @@ python3 -I tools/fixtures.py $1 || { echo "FAILED: fixtures"; exit 1; } python3 -I tools/gen_registry.py > /dev/null || { echo "FAILED: gen_registry"; exit 1; } python3 -I tools/build.py || { echo "FAILED: build"; exit 1; } passed=0 -for t in $(find tests -name '*.luau' -not -path 'tests/gen/*' -not -path 'tests/fixtures/*' -not -name 'T.luau' | sort); do +for t in $(find tests -name '*.luau' -not -path 'tests/gen/*' -not -path 'tests/fixtures/*' -not -name 'T.luau' -not -name '_*' | sort); do [ -n "$1" ] && [[ "$t" != *$1* ]] && continue for rt in $RUNTIMES; do echo "== $t ($rt)"