diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 28c79e5..f2a9a60 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -183,89 +183,89 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build Codecs (layer 3, shared by formats; not loadable on their own), by domain: - **audio** - - codecs/audio/Aac: AAC-LC decoder (ISO/IEC 14496-3 subpart 4, ISO/IEC 13818-7): the AudioSpecificConfig (with a program - - codecs/audio/Ac3: AC-3 (Dolby Digital, ATSC A/52) syncframes: the syncinfo / BSI header, the CRC check, and the - - codecs/audio/Adpcm: the 4-bit ADPCM family, decode (and encode where it is cheap). New in rosetta; the IMA and - - codecs/audio/Alac: Apple Lossless (ALAC) decoder and encoder, the codec inside m4a / mov / caf. A codec (layer 1). - - codecs/audio/Ape: the Monkey's Audio codec (.ape). A codec (layer 3). Ported from the Monkey's Audio SDK 13.28 - - codecs/audio/ApeTag: APEv1 / APEv2 tags (the tag block of Monkey's Audio, WavPack, Musepack, TTA, OptimFROG and - - codecs/audio/Flac: FLAC frames without the container: frame header parsing, subframe decoding (constant, verbatim, - - codecs/audio/Hively: the AHX / HivelyTracker engine behind music/ahx and music/hvl: the loader for both file formats - - codecs/audio/Mdct: the MDCT / IMDCT of any window length N divisible by 4 (N / 2 coefficients), through an N / 4-point - - codecs/audio/MidiRender: the tempo map (ticks -> seconds, as python mido computes lengths), the time-ordered event list, - - codecs/audio/Mpa: MPEG audio layers I / II / III (ISO/IEC 11172-3, 13818-3, MPEG-2.5) without the file around it: - - codecs/audio/Musepack: Musepack (MPC) stream versions 7 and 8: the stream headers (SV7's 32-bit word-swapped - - codecs/audio/Opus: the Opus codec (RFC 6716) without its container: TOC / packet framing (Packet), the SILK and CELT + - codecs/audio/Aac: AAC-LC decoder (ISO/IEC 14496-3 subpart 4, ISO/IEC 13818-7): AudioSpecificConfig, ADTS, raw_data_block. + - codecs/audio/Ac3: AC-3 (Dolby Digital, ATSC A/52) syncframes: syncinfo / BSI, CRC check and decoder. + - codecs/audio/Adpcm: the 4-bit ADPCM family, decode (and encode where it is cheap). + - codecs/audio/Alac: Apple Lossless (ALAC) decoder and encoder. + - codecs/audio/Ape: the Monkey's Audio codec (.ape), file versions 3.95 and later. + - codecs/audio/ApeTag: APEv1 / APEv2 tags -> Types.Tags. + - codecs/audio/Flac: FLAC frames without the container (frame header, subframes, CRC-8 / CRC-16) and the frame encoder. + - codecs/audio/Hively: the AHX / HivelyTracker engine (loader, replayer, waveform tables, render glue). + - codecs/audio/Mdct: MDCT / IMDCT for any N divisible by 4, DCT-IV, and the sine / KBD / Vorbis windows. + - codecs/audio/MidiRender: the MIDI tempo map, event timeline and the Decoder that plays a Midi through SoundFont. + - codecs/audio/Mpa: MPEG audio layers I / II / III (ISO/IEC 11172-3, 13818-3, MPEG-2.5) without the file around it. + - codecs/audio/Musepack: Musepack (MPC) stream versions 7 and 8. + - codecs/audio/Opus: the Opus codec (RFC 6716) without its container. - codecs/audio/Pcm: PCM plumbing shared by audio formats: raw sample formats, streaming Decoders, encoder input sources. - - codecs/audio/Qoa: the "Quite OK Audio" codec (QOA): frames of up to 256 slices per channel, each slice a 4-bit scale - - codecs/audio/Resample: audio sample-rate conversion by band-limited (Kaiser-windowed sinc) interpolation, streaming or - - codecs/audio/SoundFont: SoundFont 2 banks and the sample synth that plays MIDI through them. A codec (layer 1) shared by - - codecs/audio/Stream: the streaming Decoder (Types.Decoder: read / seek / position) over a packetised codec, the part - - codecs/audio/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it, and the loaders - - codecs/audio/Tta: the TTA1 (True Audio) lossless codec. A codec (layer 3). Written from the TTA1 format description - - codecs/audio/Vorbis: the Vorbis I decoder without its container: identification / comment / setup headers (Setup), - - codecs/audio/VorbisComment: Vorbis comment fields ("KEY=value", the tag block of Vorbis, Opus and FLAC) <-> Types.Tags. - - codecs/audio/WavPack: the WavPack 4 / 5 audio codec (the blocks of .wv files, and of WavPack in Matroska). A codec + - codecs/audio/Qoa: the "Quite OK Audio" codec (QOA). + - codecs/audio/Resample: sample-rate conversion by band-limited (Kaiser-windowed sinc) polyphase interpolation. + - codecs/audio/SoundFont: SoundFont 2 banks and the sample synth that plays MIDI through them. + - codecs/audio/Stream: the streaming Types.Decoder over a packetised codec (gapless trim, seeking with pre-roll). + - codecs/audio/Tracker: the shared tracker engine behind music/mod, s3m, xm and it, and the formats mapped onto them. + - codecs/audio/Tta: the TTA1 (True Audio) lossless codec. + - codecs/audio/Vorbis: the Vorbis I decoder without its container. + - codecs/audio/VorbisComment: Vorbis comment fields ("KEY=value"; Vorbis, Opus, FLAC) <-> Types.Tags. + - codecs/audio/WavPack: the WavPack 4 / 5 audio codec (the blocks of .wv files, and of WavPack in Matroska). - **compress** - - codecs/compress/Brotli: Brotli (RFC 7932) decompression. A codec (layer 3): archive/br and font/woff2 build on it. Written - - codecs/compress/Bzip2: bzip2 decompressor (BWT + MTF + Huffman, the .bz2 stream format of bzip2 0.9.5 / 1.0.x). A codec - - codecs/compress/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers. - - codecs/compress/Explode: decompressor for the PKWARE Data Compression Library "implode" format (DCL, 1987: MPQ - - codecs/compress/Lz4: the LZ4 block format (lz4 doc/lz4_Block_format.md): decode and a greedy hash-chain-free encoder - - codecs/compress/Lzh: the LHA family of LZSS decoders, used by archive/lha, archive/arj and archive/zoo: - - codecs/compress/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. A codec (layer 3): - - codecs/compress/Lzw: LZW decoder and encoder in the two variants file formats use. A codec (layer 1): image/gif and - - codecs/compress/Lzx: the LZX decoder as Microsoft Cabinet folders use it: windows of 2^15 .. 2^21 bytes, - - codecs/compress/PackBits: the Apple PackBits run-length code (TIFF compression 32773, PSD / PSB RLE channels, IFF - - codecs/compress/Quantum: the Quantum decoder (David Stafford's LZ77 with an adaptive arithmetic coder) as Microsoft - - codecs/compress/UnixCompress: the LZW of Unix compress (.Z files: magic 1F 9D, a flags byte with the maximum code - - codecs/compress/Xxh32: XXH32 of a buffer range (any seed), for the LZ4 frame format's header, block and content - - codecs/compress/Zstd: Zstandard decompression (RFC 8878). A codec (layer 3): archive/zst and anything else carrying zstd + - codecs/compress/Brotli: Brotli (RFC 7932) decompression, with the large-window extension. + - codecs/compress/Bzip2: bzip2 decompressor (BWT + MTF + Huffman, the .bz2 stream format of bzip2 0.9.5 / 1.0.x). + - codecs/compress/Deflate: DEFLATE (RFC 1951) decoder and compressor, with zlib (RFC 1950) and gzip (RFC 1952). + - codecs/compress/Explode: decompressor for the PKWARE Data Compression Library "implode" format (DCL, 1987). + - codecs/compress/Lz4: the LZ4 block format (lz4 doc/lz4_Block_format.md), decode and the reference "fast" encoder. + - codecs/compress/Lzh: the LHA family of LZSS decoders (lh1, lh4-lh7, lhx, lzs, lz5, ARJ 1-4, Zoo 2). + - codecs/compress/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. + - codecs/compress/Lzw: LZW decoder and encoder, from the GIF89a spec (appendix F) and TIFF 6.0 section 13 (new code). + - codecs/compress/Lzx: the LZX decoder for Microsoft Cabinet folders (windows of 2^15 .. 2^21 bytes). + - codecs/compress/PackBits: the Apple PackBits run-length code (TIFF compression 32773, PSD RLE, IFF ByteRun1). + - codecs/compress/Quantum: the Quantum decoder (David Stafford's LZ77 + adaptive arithmetic coder) for Cabinet folders. + - codecs/compress/UnixCompress: the LZW of Unix compress (.Z: magic 1F 9D, a flags byte: max width 9..16, block mode). + - codecs/compress/Xxh32: XXH32 for the LZ4 frame checksums, from the xxHash specification (Yann Collet, BSD-2). + - codecs/compress/Zstd: Zstandard decompression (RFC 8878), written from the specification; no dictionaries. - **entropy** - - codecs/entropy/Huffman: canonical Huffman codes (RFC 1951 3.2.2 / JPEG Annex C order) for decoders and encoders. - - codecs/entropy/RangeCoder: the RFC 6716 range coder (libopus celt/entdec.c + entenc.c, BSD: licenses/libopus-BSD.txt): + - codecs/entropy/Huffman: canonical Huffman codes (RFC 1951 3.2.2 / JPEG Annex C order). + - codecs/entropy/RangeCoder: the RFC 6716 range coder used by Opus, a port of libopus celt/entdec.c + entenc.c. - **font** - - codecs/font/Bitmap: the standard Font value for bitmap fonts (BDF, PCF, PSF, Windows FON / FNT): a Types.BitmapStrike - - codecs/font/Cff: Compact Font Format (Adobe TN #5176) and Type 2 charstrings (TN #5177): the outlines of OpenType fonts - - codecs/font/GlyphNames: PostScript glyph names -> Unicode for fonts that name their glyphs (Type 1, CFF without a - - codecs/font/TrueType: the sfnt font container (TrueType .ttf, OpenType .otf with CFF outlines, collections .ttc) parsed + - codecs/font/Bitmap: the standard Font value for bitmap fonts (BDF, PCF, PSF, Windows FON / FNT) and their 1-bit rows. + - codecs/font/Cff: Compact Font Format (Adobe TN #5176) and Type 2 charstrings (TN #5177), the outlines of .otf fonts. + - codecs/font/GlyphNames: PostScript glyph names -> Unicode (AGL specification) and Adobe StandardEncoding. + - codecs/font/TrueType: the sfnt container (.ttf, .otf with CFF outlines, .ttc collections) as the standard Font value. - **image** - - codecs/image/Bcn: the BCn block-compressed texture codecs, shared by the texture formats (DDS, KTX, VTF, BLP, ...): - - codecs/image/Blend: layer compositing on rgba8 buffers (straight alpha): source-over with the separable and non-separable + - codecs/image/Bcn: BC1-BC7 block-compressed textures with the D3D11 rules. + - codecs/image/Blend: rgba8 layer compositing (straight alpha) with the W3C Compositing and Blending Level 1 modes. - codecs/image/Dct: the 8x8 DCTs JPEG, Motion-JPEG and MPEG-1 share (native; never throws). - - codecs/image/Etc: the Ericsson / Khronos block texture codecs, decode only: ETC1, ETC2 RGB (with the T, H and planar - - codecs/image/Half: IEEE 754 binary16 ("half") <-> number, for the float texel formats (DDS / KTX R16F..., BC6H, - - codecs/image/Jpeg: the JPEG codec (ITU T.81) on byte ranges: image/jpeg is a thin format over it, and the Motion-JPEG - - codecs/image/Pixels: row loops between packed pixel layouts and rgba8 (native), shared by the bitmap formats (BMP, - - codecs/image/Quantize: palette quantization of rgba8 pixels. A codec (layer 1): image/gif (and later any palette - - codecs/image/Raster: an antialiased scanline rasterizer for paths of lines, quadratic and cubic Béziers, under an affine - - codecs/image/Texel: uncompressed GPU texel formats -> the standard pixel formats, shared by the texture containers - - codecs/image/Texture: one entry point over the texture pixel codecs for the texture containers (DDS, KTX, VTF, ...): - - codecs/image/Vp8: the VP8 video codec (RFC 6386), decode only. A codec (layer 1): image/webp uses it for lossy frames, the - - codecs/image/Vp8L: WebP lossless (VP8L, "WebP Lossless Bitstream Specification", RFC 9649 section 3). A codec (layer 1): - - codecs/image/Yuv: planar 4:2:0 Y'CbCr <-> rgba8 for the video codecs and writers (native; never throws). BT.601 or + - codecs/image/Etc: ETC1 / ETC2 / EAC block texture decoding (Khronos Data Format Specification 1.3, section 21). + - codecs/image/Half: IEEE 754 binary16 <-> number (round to nearest even, overflow to infinity). New in rosetta. + - codecs/image/Jpeg: the JPEG codec (ITU T.81), bit-exact with libjpeg-turbo's djpeg and byte-identical with cjpeg. + - codecs/image/Pixels: row loops between packed pixel layouts and rgba8 for BMP / DIB. + - codecs/image/Quantize: palette quantization of rgba8 pixels (median cut or octree, Floyd-Steinberg dithering). + - codecs/image/Raster: an antialiased scanline rasterizer (nonzero / even-odd) for line and Bézier paths, plus a stroker. + - codecs/image/Texel: uncompressed GPU texel formats -> the standard pixel formats. New in rosetta. + - codecs/image/Texture: one entry point over the texture pixel codecs (Bcn, Etc, Texel). New in rosetta. + - codecs/image/Vp8: the VP8 video codec (RFC 6386), decode only. + - codecs/image/Vp8L: WebP lossless (VP8L, RFC 9649 section 3). + - codecs/image/Yuv: planar 4:2:0 Y'CbCr <-> rgba8, BT.601 / BT.709, limited or full range. - **model** - codecs/model/Draco: Google Draco geometry decompression (.drc; glTF KHR_draco_mesh_compression; Roblox mesh v6 / v7). - - codecs/model/Mat4: 4x4 matrix and quaternion helpers for the model formats: column-major flat arrays of 16 - - codecs/model/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). Walks + - codecs/model/Mat4: 4x4 matrix (column-major, glTF / Types.Scene layout) and quaternion { x, y, z, w } helpers. + - codecs/model/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). - codecs/model/Minecraft: what Minecraft's voxel formats share (model/schematic, model/mca). New code. - - codecs/model/Polygon: 2D polygons with holes to triangles, for formats that store regions as outlines (Doom map - - codecs/model/Rbx: the Roblox instance tree every Roblox file format maps to (model/rbxm binary rbxm / rbxl, - - codecs/model/Rig: the Scene mapping shared by game model formats (MD2 / MD3 / MDL / MD5 / SMD / ...), so each - - codecs/model/Sampler: evaluates Scene animation channels at any time (STEP, LINEAR with quaternion slerp for - - codecs/model/Vrml: the VRML97 / X3D scene-graph engine shared by model/vrml (.wrl) and model/x3d (.x3d XML, + - codecs/model/Polygon: 2D polygons with holes to triangles by hole bridging and ear clipping. New code. + - codecs/model/Rbx: the Roblox instance tree and property values shared by model/rbxm and model/rbxmx. + - codecs/model/Rig: the Scene mapping shared by game model formats (MD2 / MD3 / MDL / MD5 / SMD / ...). New code. + - codecs/model/Sampler: Scene animation sampling, STEP / LINEAR (slerp) / CUBICSPLINE as in glTF 2.0 animations. New code. + - codecs/model/Vrml: VRML97 / X3D scene-graph engine (classic and XML encodings) for model/vrml and model/x3d. - **text** - codecs/text/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code. - - codecs/text/Nbt: Minecraft's Named Binary Tag format and its text form SNBT, the engine data/nbt, data/snbt, - - codecs/text/Text: text decoding helpers for the text formats: a UTF-8 BOM is stripped, text that is not valid UTF-8 is - - codecs/text/Url: RFC 3986 reference resolution (section 5.2), the classification of a playlist / manifest location (URL, - - codecs/text/Xml: XML 1.0 parse (DOM and pull events) and serialize, the engine data/xml, SVG, DAE, 3MF, TMX, plist, ... + - codecs/text/Nbt: Minecraft's Named Binary Tag format and SNBT (Minecraft wiki "NBT format", wiki.vg "NBT"). + - codecs/text/Text: text decoding helpers: BOM stripping, Windows-1252 for text that is not UTF-8, line splitting. + - codecs/text/Url: RFC 3986 reference resolution (section 5.2), local-path classification and percent-encoding. + - codecs/text/Xml: XML 1.0 parse (DOM and pull events) and serialize. New code. - **video** - codecs/video/Dsp: the 8x8 IDCT (bit-exact with ffmpeg -idct int) and half-pel motion compensation of MPEG codecs. - codecs/video/H263: an H.263 / H.263+ and Sorenson Spark (FLV1) video decoder, bit-exact with ffmpeg -idct int. - - codecs/video/H264: an H.264 / AVC (ITU-T H.264 | ISO/IEC 14496-10) video decoder in pure Luau. A codec (layer 1): the + - codecs/video/H264: an H.264 / AVC (ITU-T H.264 | ISO/IEC 14496-10) video decoder in pure Luau, bit-exact with ffmpeg. - codecs/video/Legacy: FLI / FLC, Cinepak, Microsoft Video 1, QuickTime RLE / SMC and Smacker video decoders. - - codecs/video/Mpeg1: the MPEG-1 video decoder (ISO/IEC 11172-2), which is codecs/video/Mpeg2 (an MPEG-2 decoder + - codecs/video/Mpeg1: the MPEG-1 video decoder (ISO/IEC 11172-2), the old name and API over codecs/video/Mpeg2. - codecs/video/Mpeg2: an MPEG-1 / MPEG-2 video decoder (ISO/IEC 11172-2, ISO/IEC 13818-2 Main profile). - - codecs/video/Theora: a Theora video decoder (the Theora I specification, Xiph.Org), for Ogg (video/ogv) and Matroska + - codecs/video/Theora: a Theora video decoder (the Theora I specification, Xiph.Org), for Ogg and Matroska (V_THEORA). - codecs/video/Video: the video codec registry and the generic VideoDecoder. New in rosetta. diff --git a/src/Rosetta/codecs/audio/Aac/Decode.luau b/src/Rosetta/codecs/audio/Aac/Decode.luau index a22a53a..818c573 100644 --- a/src/Rosetta/codecs/audio/Aac/Decode.luau +++ b/src/Rosetta/codecs/audio/Aac/Decode.luau @@ -1,12 +1,8 @@ --!strict --!native --!optimize 2 --- codecs/audio/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/audio/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. +-- codecs/audio/Aac/Decode: the AAC-LC raw_data_block decoder (ISO/IEC 14496-3 subpart 4). +-- Written from the standard; no third-party code. PNS uses FFmpeg's LCG so the noise matches it. local Mdct = require("@rosetta/codecs/audio/Mdct") local Tables = require("@rosetta/codecs/audio/Aac/Tables") @@ -18,14 +14,13 @@ 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 BP = 0 +local BL = 0 local OVER = false -local function getBits(n: number): number -- 1 .. 25 +local function getBits(n: number): number local p = BP BP = p + n if p > BL then @@ -49,7 +44,6 @@ local function getLong(n: number): number return getBits(n) end --- ------------------------------------------------------------------------------------------------ Huffman local PEEK = 10 type Book = { tab: { number }, map: { [number]: number }, maxLen: number } @@ -78,14 +72,12 @@ 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 @@ -98,7 +90,6 @@ local function huff(bk: Book): number 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 } @@ -110,7 +101,6 @@ 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 } @@ -118,37 +108,34 @@ 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 + spec: { number }, + overlap: { number }, prevShape: number, - -- this frame's ics windowSequence: number, windowShape: number, maxSfb: number, numGroups: number, groupLen: { number }, - bandType: { number }, -- [g * maxSfb + sfb + 1] + bandType: { number }, sf: { number }, - -- tns - tnsFilters: { { { number } } }, -- per window: { length, order, direction, coefs ... } flattened per filter + tnsFilters: { { { number } } }, } export type State = { sfIndex: number, - channels: number, -- configured channels (0: as found) + channels: number, 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 + pcm: { number }, + random: number, + time: { number }, + frame: { number }, + short: { number }, 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) + extensions: number, + sbr: boolean, + map: { number }?, } local function newChannel(): Channel @@ -168,7 +155,6 @@ local function newChannel(): Channel end Decode.newChannel = newChannel --- ------------------------------------------------------------------------------------------------ ics local function icsInfo(st: State, c: Channel): string? if getBits(1) ~= 0 then return "reserved ics bit set" @@ -394,7 +380,6 @@ local function applyTns(st: State, c: Channel) 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] @@ -530,7 +515,6 @@ local function spectralData(st: State, c: Channel, pulses: { number }?): string? 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 @@ -609,7 +593,6 @@ local function ics(st: State, c: Channel, commonWindow: boolean): string? 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] @@ -663,7 +646,6 @@ local function intensity(st: State, l: Channel, r: Channel, mask: { number }, ms 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 @@ -688,7 +670,6 @@ local function filterbank(st: State, c: Channel, out: { number }, stride: number 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 @@ -706,7 +687,6 @@ local function filterbank(st: State, c: Channel, out: { number }, stride: number 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 @@ -734,8 +714,6 @@ local function filterbank(st: State, c: Channel, out: { number }, stride: number 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) diff --git a/src/Rosetta/codecs/audio/Aac/Tables.luau b/src/Rosetta/codecs/audio/Aac/Tables.luau index 71bf6bc..7b92871 100644 --- a/src/Rosetta/codecs/audio/Aac/Tables.luau +++ b/src/Rosetta/codecs/audio/Aac/Tables.luau @@ -1,8 +1,7 @@ --!strict --- codecs/audio/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. +-- codecs/audio/Aac/Tables: the AAC-LC tables of ISO/IEC 14496-3 (subpart 4, Annex 4.A): Huffman codebooks, scalefactor +-- band offsets, 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 = { diff --git a/src/Rosetta/codecs/audio/Aac/init.luau b/src/Rosetta/codecs/audio/Aac/init.luau index 73755b4..e6b3853 100644 --- a/src/Rosetta/codecs/audio/Aac/init.luau +++ b/src/Rosetta/codecs/audio/Aac/init.luau @@ -1,20 +1,7 @@ --!strict --- codecs/audio/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/audio/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/audio/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("@rosetta/codecs/audio/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. +-- codecs/audio/Aac: AAC-LC decoder (ISO/IEC 14496-3 subpart 4, ISO/IEC 13818-7): AudioSpecificConfig, ADTS, raw_data_block. +-- Written from the standard; no third-party code. HE-AAC decodes its AAC-LC core at the core rate. Not supported: Main +-- prediction, LTP, SSR, coupling channels, 960-sample frames, ER / USAC (UNSUPPORTED). local Err = require("@rosetta/core/Err") local Bits = require("@rosetta/core/Bits") local Decode = require("@rosetta/codecs/audio/Aac/Decode") @@ -35,12 +22,12 @@ local CONFIG_MAP: { [number]: { number } } = { export type Config = { objectType: number, -- 2 = AAC-LC (the core object type when SBR / PS is signalled) sfIndex: number, - sampleRate: number, -- the core rate + sampleRate: number, channelConfig: number, channels: number, - sbr: boolean, -- SBR signalled (explicitly or backward-compatibly) + sbr: boolean, ps: boolean, - extensionRate: number?, -- the SBR output rate + extensionRate: number?, frameLength: number, } @@ -72,7 +59,7 @@ local function frequency(br: Bits.BitReader): (number, number) return i, Aac.RATES[i + 1] or 0 end --- pce(br) -> channels (program_config_element) +-- 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) @@ -98,7 +85,6 @@ local function pce(br: Bits.BitReader): number 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") @@ -182,7 +168,6 @@ function Aac.config(asc: buffer): (Config?, Err.Err?) }, 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 @@ -193,7 +178,7 @@ end export type Adts = { headerSize: number, -- 7, or 9 with a CRC - frameSize: number, -- the whole frame, header included + frameSize: number, objectType: number, sfIndex: number, sampleRate: number, @@ -202,7 +187,6 @@ export type Adts = { 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 @@ -233,14 +217,13 @@ function Aac.adts(b: buffer, o: number, limit: number): Adts? } 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 + pcm: { number }, + sbr: boolean, 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) -> (), @@ -263,7 +246,6 @@ local function decode(self: Decoder, buf: buffer, offset: number?, length: numbe 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 @@ -284,7 +266,6 @@ local function reset(self: Decoder) 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 diff --git a/src/Rosetta/codecs/audio/Ac3/Decode.luau b/src/Rosetta/codecs/audio/Ac3/Decode.luau index 72b18b1..71ba575 100644 --- a/src/Rosetta/codecs/audio/Ac3/Decode.luau +++ b/src/Rosetta/codecs/audio/Ac3/Decode.luau @@ -1,12 +1,9 @@ --!strict --!native --!optimize 2 --- codecs/audio/Ac3/Decode: one AC-3 syncframe (6 audio blocks of 256 samples) -> PCM. Written from ATSC A/52:2018 --- (section 5.3 syntax, 7.1 exponents, 7.2 parametric bit allocation with delta bit allocation, 7.3 mantissas with --- grouping and dither, 7.4 coupling with phase flags, 7.5 rematrixing, 7.7.1 dynamic range, 7.9 the 512 / 2 x 256 --- inverse transforms with block switching) on codecs/audio/Mdct; no third-party code. The bit reader is module state --- over a frame the caller pads by PAD bytes; every section stops when the position passes the frame. No error / --- assert: failures return nil, "message". +-- codecs/audio/Ac3/Decode: one AC-3 syncframe (6 audio blocks of 256 samples) -> PCM. +-- Written from ATSC A/52:2018 (5.3 syntax, 7.1 exponents, 7.2 bit allocation, 7.3 mantissas, 7.4 coupling, 7.5 +-- rematrixing, 7.7.1 dynamic range, 7.9 transforms); no third-party code. The caller pads the frame by PAD bytes. local T = require("@rosetta/codecs/audio/Ac3/Tables") local Mdct = require("@rosetta/codecs/audio/Mdct") @@ -22,7 +19,6 @@ local NFCHANS = { [0] = 2, 1, 2, 3, 3, 4, 4, 5 } local SLOWDEC, FASTDEC, SLOWGAIN, DBPBTAB, FLOORTAB, FASTGAIN = T.SLOWDEC, T.FASTDEC, T.SLOWGAIN, T.DBPBTAB, T.FLOORTAB, T.FASTGAIN local BNDTAB, BNDSZ, MASKTAB, LATAB, HTH, BAPTAB = T.BNDTAB, T.BNDSZ, T.MASKTAB, T.LATAB, T.HTH, T.BAPTAB --- 2^-e for the exponents 0 .. 24 local POW2 = table.create(32, 0) for e = 0, 31 do POW2[e + 1] = 2 ^ -e @@ -43,7 +39,6 @@ local WINDOW = Mdct.window("kbd", 512, 5) :: { number } local PLAN512 = Mdct.new(512) :: Mdct.Plan local PLAN256 = Mdct.new(256) :: Mdct.Plan --- ------------------------------------------------------------------------------------------------ bit reader local B: buffer = buffer.create(0) local P = 0 @@ -61,17 +56,14 @@ local function bits(n: number): number return v end --- ------------------------------------------------------------------------------------------------ state export type State = { - -- the frame header fscod: number, acmod: number, lfeon: boolean, nfchans: number, - channels: number, -- output channels - map: { number }, -- output index of slots 1 .. 6 - drc: number, -- the dynamic range scale (0 = off) - -- per channel slot (1 .. 7) + channels: number, + map: { number }, + drc: number, exp: { { number } }, bap: { { number } }, coef: { { number } }, @@ -86,19 +78,17 @@ export type State = { dbaOffst: { { number } }, dbaLen: { { number } }, dbaBa: { { number } }, - -- coupling cplinu: boolean, chincpl: { boolean }, phsflginu: boolean, cplbegf: number, cplendf: number, cplbndstrc: { boolean }, -- [sbnd + 1], sbnd = 0 .. 17 (absolute sub-band) - cplco: { { number } }, -- [ch][sbnd + 1] - phsflg: { boolean }, -- [sbnd + 1] + cplco: { { number } }, + phsflg: { boolean }, cplfleak: number, cplsleak: number, rematflg: { boolean }, - -- bit allocation parameters sdcycod: number, fdcycod: number, sgaincod: number, @@ -106,15 +96,14 @@ export type State = { floorcod: number, csnroffst: number, dynrng: { number }, -- gain for Ch1 / Ch2 - seed: number, -- dither generator - -- scratch + seed: number, psd: { number }, bndpsd: { number }, excite: { number }, mask: { number }, y: { number }, pcm: { number }, - blocks: { number }, -- the bit offset of each audio block in the last frame (for tools) + blocks: { number }, } local function arrays(n: number, size: number, v: any): { any } @@ -177,7 +166,6 @@ function Decode.state(): State } end --- reset(st): forget the overlap (before a seek) function Decode.reset(st: State) for _, d in st.delay do for i = 1, 256 do @@ -186,9 +174,7 @@ function Decode.reset(st: State) end end --- ------------------------------------------------------------------------------------------------ exponents --- read ngrps grouped exponents (7 bits = 3 deltas each) after absexp into e[first + 1 ..] (bins first ..), grpsize --- bins per delta; false when an exponent leaves 0 .. 24 +-- grouped exponents: 7 bits = 3 deltas each after absexp, grpsize bins per delta; each exponent stays in 0 .. 24 local function exponents(e: { number }, absexp: number, ngrps: number, grpsize: number, first: number): boolean local prev = absexp local k = first + 1 @@ -215,7 +201,6 @@ local function exponents(e: { number }, absexp: number, ngrps: number, grpsize: return true end --- ------------------------------------------------------------------------------------------------ bit allocation local function logadd(a: number, b: number): number local c = a - b local adr = min(rshift(if c >= 0 then c else -c, 1), 255) @@ -357,7 +342,6 @@ local function allocate(st: State, ch: number, start: number, stop: number, fgai until stop <= lastbin end --- ------------------------------------------------------------------------------------------------ mantissas -- grouped mantissa state (bap 1, 2, 4 share groups across channels within a block) local G1, G2, G4 = table.create(3, 0), table.create(3, 0), table.create(2, 0) local n1, n2, n4 = 0, 0, 0 @@ -368,7 +352,6 @@ local function dither(st: State): number return (s / 2147483648 - 1) * 0.707 end --- the mantissas of bins [start, stop) of slot ch into out[], scaled by their exponents (bap 0: dither when asked) local function mantissas(st: State, ch: number, start: number, stop: number, out: { number }, dith: boolean) local e, bap = st.exp[ch], st.bap[ch] for bin = start, stop - 1 do @@ -426,7 +409,6 @@ local function mantissas(st: State, ch: number, start: number, stop: number, out end end --- ------------------------------------------------------------------------------------------------ audio block local function readDba(st: State, ch: number) local nseg = bits(3) + 1 local offs, lens, bas = st.dbaOffst[ch], st.dbaLen[ch], st.dbaBa[ch] @@ -463,7 +445,6 @@ local function audblk(st: State, blk: number, limit: number): (boolean?, string? st.dynrng[i] = 1 end end - -- coupling strategy if bits(1) == 1 then st.cplinu = bits(1) == 1 if st.cplinu then @@ -527,7 +508,6 @@ local function audblk(st: State, blk: number, limit: number): (boolean?, string? end end end - -- rematrixing if acmod == 2 then if bits(1) == 1 then local n = if not cplinu or cplbegf > 2 then 4 elseif cplbegf > 0 then 3 else 2 @@ -540,7 +520,6 @@ local function audblk(st: State, blk: number, limit: number): (boolean?, string? end end end - -- exponent strategies local chexpstr = st.chexpstr chexpstr[CPL] = if cplinu then bits(2) else 0 for ch = 1, nf do @@ -572,7 +551,6 @@ local function audblk(st: State, blk: number, limit: number): (boolean?, string? end end endmant[LFE] = 7 - -- exponents if cplinu and chexpstr[CPL] ~= 0 then local abs = bits(4) * 2 local grp = EXPGRP[chexpstr[CPL]] @@ -610,7 +588,6 @@ local function audblk(st: State, blk: number, limit: number): (boolean?, string? if P > limit then return nil, "truncated block" end - -- bit allocation parameters if bits(1) == 1 then st.sdcycod, st.fdcycod, st.sgaincod, st.dbpbcod, st.floorcod = bits(2), bits(2), bits(2), bits(2), bits(3) elseif blk == 0 then @@ -635,7 +612,6 @@ local function audblk(st: State, blk: number, limit: number): (boolean?, string? st.cplfleak, st.cplsleak = bits(3), bits(3) end end - -- delta bit allocation if bits(1) == 1 then local modes = table.create(7, 0) if cplinu then @@ -664,14 +640,12 @@ local function audblk(st: State, blk: number, limit: number): (boolean?, string? st.dbaOn[ch] = false end end - -- skip field if bits(1) == 1 then P += bits(9) * 8 end if P > limit then return nil, "truncated block" end - -- bit allocation local zero = st.csnroffst == 0 if zero then for ch = 1, nf do @@ -702,7 +676,6 @@ local function audblk(st: State, blk: number, limit: number): (boolean?, string? if st.lfeon then alloc(LFE, 0, 7, true) end - -- mantissas n1, n2, n4 = 0, 0, 0 local gotCpl = false local coef = st.coef @@ -774,13 +747,11 @@ local function audblk(st: State, blk: number, limit: number): (boolean?, string? return true, nil end --- ------------------------------------------------------------------------------------------------ transform --- the inverse transform of slot ch (long or two short), windowed, overlap-added into out[base + i * step] local function synth(st: State, ch: number, short: boolean, gain: number, out: { number }, base: number, step: number) local x, y, d, w = st.coef[ch], st.y, st.delay[ch], WINDOW if short then -- two 256-point transforms of the interleaved coefficients, phases alpha = -1 (n0 = 0) and +1 (n0 = N / 2) - local z = st.psd -- 256 scratch + local z = st.psd Mdct.inverse(PLAN256, x, 1, 2, z, 1, -2 * gain) for n = 0, 63 do y[n + 1] = -z[n + 193] @@ -806,7 +777,6 @@ local function synth(st: State, ch: number, short: boolean, gain: number, out: { end end --- ------------------------------------------------------------------------------------------------ frame -- the output index of each slot (1 .. 5 full bandwidth, 6 LFE) in WAVE order: L R C LFE surrounds local ORDER: { [number]: { number } } = { [0] = { 1, 2 }, @@ -820,8 +790,6 @@ local ORDER: { [number]: { number } } = { } local HAS_C = { [0] = false, true, false, true, false, true, false, true } --- frame(st, buf, len, drc) -> 1536 | nil, message: decodes the syncframe at buf[0 .. len) (padded by PAD bytes) --- into st.pcm (1536 * st.channels interleaved floats, WAVE order). drc: the dynamic range scale (0 = off, 1 = full). function Decode.frame(st: State, buf: buffer, len: number, drc: number): (number?, string?) if len < 8 or buffer.len(buf) < len + Decode.PAD then return nil, "truncated frame" @@ -875,7 +843,6 @@ function Decode.frame(st: State, buf: buffer, len: number, drc: number): (number local nf = NFCHANS[acmod] local channels = nf + (if lfeon then 1 else 0) if st.acmod ~= acmod or st.lfeon ~= lfeon then - -- a new channel layout: build the output map and forget the overlap local order = ORDER[acmod] local map = table.create(6, 0) local nfront = if HAS_C[acmod] then 3 elseif acmod == 1 then 1 else 2 diff --git a/src/Rosetta/codecs/audio/Ac3/Tables.luau b/src/Rosetta/codecs/audio/Ac3/Tables.luau index 3eec9e3..1435e87 100644 --- a/src/Rosetta/codecs/audio/Ac3/Tables.luau +++ b/src/Rosetta/codecs/audio/Ac3/Tables.luau @@ -1,9 +1,6 @@ --!strict --- codecs/audio/Ac3/Tables: the AC-3 constant tables, transcribed from ATSC A/52:2018 (Digital Audio Compression --- Standard) section 7.2.3 (bit allocation: slowdec, fastdec, slowgain, dbpbtab, floortab, fastgain, bndtab / bndsz, --- latab, hth, baptab) and section 5.4 (frame sizes). masktab is derived from bndtab / bndsz, the transform window --- (Table 7.33) is the Kaiser-Bessel-derived window with alpha 5 (codecs/audio/Mdct), which Table 7.33 rounds to five --- decimals. No third-party code. +-- codecs/audio/Ac3/Tables: transcribed from ATSC A/52:2018 section 7.2.3 (bit allocation tables) and section 5.4 (frame +-- sizes); masktab is derived from bndtab / bndsz. No third-party code. local T = {} T.SLOWDEC = { 0x0f, 0x11, 0x13, 0x15 } @@ -13,7 +10,7 @@ T.DBPBTAB = { 0x000, 0x700, 0x900, 0xb00 } T.FLOORTAB = { 0x2f0, 0x2b0, 0x270, 0x230, 0x1f0, 0x170, 0x0f0, 0xf800 } T.FASTGAIN = { 0x080, 0x100, 0x180, 0x200, 0x280, 0x300, 0x380, 0x400 } --- the 50 bit allocation bands: first bin and width (Table 7.12) +-- bit allocation bands: first bin and width (Table 7.12) T.BNDTAB = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 31, 34, 37, 40, 43, 46, 49, 55, 61, 67, 73, 79, 85, 97, 109, 121, 133, 157, 181, 205, 229, @@ -22,7 +19,7 @@ T.BNDSZ = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 6, 6, 6, 6, 6, 6, 12, 12, 12, 12, 24, 24, 24, 24, 24, } --- masktab[bin + 1]: the band of each bin (Table 7.13; bins 253 .. 255 map to 0) +-- masktab (Table 7.13; bins 253 .. 255 map to 0) T.MASKTAB = table.create(256, 0) for b = 1, 50 do for k = T.BNDTAB[b], T.BNDTAB[b] + T.BNDSZ[b] - 1 do @@ -50,7 +47,7 @@ T.LATAB = { 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, } --- hearing threshold per band (Table 7.15): HTH[fscod + 1][band + 1] +-- hearing threshold (Table 7.15): HTH[fscod + 1][band + 1] T.HTH = { { 0x04d0, 0x04d0, 0x0440, 0x0400, 0x03e0, 0x03c0, 0x03b0, 0x03b0, 0x03a0, 0x03a0, diff --git a/src/Rosetta/codecs/audio/Ac3/init.luau b/src/Rosetta/codecs/audio/Ac3/init.luau index 04bc5b3..6afdb3f 100644 --- a/src/Rosetta/codecs/audio/Ac3/init.luau +++ b/src/Rosetta/codecs/audio/Ac3/init.luau @@ -1,17 +1,6 @@ --!strict --- codecs/audio/Ac3: AC-3 (Dolby Digital, ATSC A/52) syncframes: the syncinfo / BSI header, the CRC check, and the --- decoder (codecs/audio/Ac3/Decode). Written from ATSC A/52:2018; no third-party code. A codec (layer 3): audio/ac3 --- (raw .ac3 files) builds on it, and the AC-3 tracks of MKV / MP4 / MPEG-TS / AVI reach it through --- containers/AudioWrap. --- Supports: every acmod (1+1, 1/0 .. 3/2) with or without LFE, 32 / 44.1 / 48 kHz, all bit rates, coupling with phase --- flags, rematrixing, block switching, delta bit allocation, dither, dynamic range control (off by default, --- `drc` = 0 .. 1 scales it). Output: every channel in WAVE order (L R C LFE surrounds), no downmix. Not supported: --- E-AC-3 (bsid 11 .. 16) and the reduced-rate bsid 9 / 10 streams (UNSUPPORTED). --- --- local h = Ac3.header(buf, offset, limit) -- { sampleRate, frameSize, channels, acmod, lfeon, bsid, bitrate } --- local dec = Ac3.decoder({ drc = 0 }) -- dec:decode(buf, offset, length) -> 1536, dec.pcm (interleaved) --- --- Never throws: bad data returns nil, Err. +-- codecs/audio/Ac3: AC-3 (Dolby Digital, ATSC A/52) syncframes: syncinfo / BSI, CRC check and decoder. +-- Written from ATSC A/52:2018; no third-party code. E-AC-3 (bsid 11 .. 16) and bsid 9 / 10 are UNSUPPORTED. local Err = require("@rosetta/core/Err") local T = require("@rosetta/codecs/audio/Ac3/Tables") local Decode = require("@rosetta/codecs/audio/Ac3/Decode") @@ -23,16 +12,14 @@ local NFCHANS = { [0] = 2, 1, 2, 3, 3, 4, 4, 5 } export type Header = { sampleRate: number, - frameSize: number, -- bytes - bitrate: number, -- bits per second + frameSize: number, + bitrate: number, channels: number, acmod: number, lfeon: boolean, bsid: number, } --- header(buf, o, limit) -> Header | nil (not an AC-3 / E-AC-3 syncframe header at o). E-AC-3 headers (bsid > 10) --- come back with frameSize from their own frmsiz field so a scanner can step over them. function Ac3.header(b: buffer, o: number, limit: number): Header? if o < 0 or o + 8 > limit or o + 8 > buffer.len(b) then return nil @@ -90,8 +77,7 @@ function Ac3.header(b: buffer, o: number, limit: number): Header? } end --- the CRC-16 of A/52 section 7.10.1 (x^16 + x^15 + x^2 + 1, MSB first, zero start): a syncframe checks when the CRC of --- everything after the sync word is 0 +-- CRC-16 of A/52 section 7.10.1 (x^16 + x^15 + x^2 + 1, MSB first, zero start): 0 over everything after the sync word local CRC = table.create(256, 0) for i = 0, 255 do local c = i * 256 @@ -109,17 +95,16 @@ function Ac3.crc(b: buffer, o: number, n: number): number return c end --- ------------------------------------------------------------------------------------------------ decoder export type Options = { - drc: number?, -- dynamic range control: 0 = off (default, like ffmpeg -drc_scale 0), 1 = as the stream says - crc: boolean?, -- check crc2 (default true): a mismatch is Err.CHECKSUM + drc: number?, -- 0 = off (default, as ffmpeg -drc_scale 0), 1 = as the stream says + crc: boolean?, } export type Decoder = { - pcm: { number }, -- the last frame: 1536 * channels interleaved floats, WAVE order + pcm: { number }, channels: number, sampleRate: number, - blocks: { number }, -- the bit offset of each audio block in the last frame (tools: stream editing, analysis) + blocks: { number }, decode: (self: Decoder, buf: buffer, offset: number?, length: number?) -> (number?, Err.Err?), reset: (self: Decoder) -> (), } diff --git a/src/Rosetta/codecs/audio/Adpcm/Decoder.luau b/src/Rosetta/codecs/audio/Adpcm/Decoder.luau index 4a513e6..648406d 100644 --- a/src/Rosetta/codecs/audio/Adpcm/Decoder.luau +++ b/src/Rosetta/codecs/audio/Adpcm/Decoder.luau @@ -1,26 +1,6 @@ --!strict --- codecs/audio/Adpcm/Decoder: the streaming Decoder (Types.Decoder) over an ADPCM stream cut into packets, for the --- formats whose state carries from packet to packet (ADX, VAG, BRSTM, raw IMA): codecs/audio/Stream.packets plus --- exact seeking. The codec state (one buffer the packet decoder advances) is snapshotted at every packet start it --- passes; a seek restores the snapshot, else the format's own state for that packet (BRSTM's ADPC history), else --- decodes forward from the nearest earlier snapshot. New in rosetta. --- --- local dec, err = Decoder.packets(dec, { -- dec: the Decoder table (sampleRate, channels, frames, ...) --- count = n, packetFrames = 4096, -- packets of packetFrames frames (the last may be shorter) --- frames = total, -- output frames --- state = st, -- the codec state buffer decode advances --- decode = function(i, out) return frames end, -- packet i (1-based) as interleaved f32 into out from 0 --- restore = function(i) return false end, -- optional: set st for packet i, true if it could --- }) --- --- The layouts the formats share, each returning the Decoder (dec gets read / seek / position) | nil, Err: --- Decoder.interleaved(dec, spec) psx / adx / dsp frames (or s16 / s8 PCM), channels interleaved every --- spec.interleave bytes (VAG, ADX, BRSTM / BCSTM / BFSTM, raw PS-ADPCM) --- Decoder.nibbles(dec, spec) an IMA nibble stream, channels interleaved by nibble (raw IMA, KVAG) --- Decoder.blocks(dec, spec) self-contained blocks: "ms" / "ima_wav" (blockAlign bytes), "ima_qt" (34 bytes --- per channel), raw or inside AIFF-C / CAF --- --- Never throws (decode failures end the stream and land in dec.error, see codecs/audio/Stream). +-- codecs/audio/Adpcm/Decoder: the streaming Types.Decoder over packetised ADPCM (ADX, VAG, BRSTM, raw IMA) with exact seeking. +-- New in rosetta. local Err = require("@rosetta/core/Err") local Stream = require("@rosetta/codecs/audio/Stream") local Adpcm = require("@rosetta/codecs/audio/Adpcm") @@ -58,7 +38,6 @@ function Decoder.packets(dec: any, spec: Spec): (any, Err.Err?) if snaps[i] then buffer.copy(st, 0, snaps[i]) elseif restore and restore(i) then - -- the format set the state (BRSTM's seek table) else local j = i - 1 while j > 1 and not snaps[j] do @@ -95,11 +74,9 @@ function Decoder.packets(dec: any, spec: Spec): (any, Err.Err?) }) end --- ------------------------------------------------------------------------------------------------ layouts local FRAME: { [string]: number } = { psx = 16, adx = 18, dsp = 8, s16be = 2, s16le = 2, s8 = 1 } -- bytes per frame local SPF: { [string]: number } = { psx = 28, adx = 32, dsp = 14, s16be = 1, s16le = 1, s8 = 1 } -- samples per frame --- PCM samples of one channel into every ds-th float of dst from float d local function pcm(kind: string, src: buffer, p: number, n: number, dst: buffer, d: number, ds: number) if kind == "s8" then for k = 0, n - 1 do @@ -118,22 +95,21 @@ local function pcm(kind: string, src: buffer, p: number, n: number, dst: buffer, end export type InterleavedSpec = { - kind: "psx" | "adx" | "dsp" | "s16be" | "s16le" | "s8", -- ADPCM frames, or PCM samples laid out the same way + kind: "psx" | "adx" | "dsp" | "s16be" | "s16le" | "s8", buf: buffer, - offset: number, -- the first row - size: number, -- data bytes (rows past it are cut; a truncated file decodes its whole frames) - interleave: number, -- bytes per channel per row (a multiple of the frame size; mono: any multiple) + offset: number, + size: number, + interleave: number, lastInterleave: number?, -- bytes per channel in the last row (BRSTM's padded last block), default interleave - frames: number?, -- frames to output (default: what the data holds) - c1: number?, -- adx: the predictor (Adpcm.adxCoefs) + frames: number?, + c1: number?, c2: number?, - v3: boolean?, -- adx: version 3 rounding + v3: boolean?, coefs: buffer?, -- dsp: 16 i32 per channel - hist: { number }?, -- initial history, h1 / h2 per channel (default 0) + hist: { number }?, restore: ((row: number, st: buffer) -> boolean)?, -- the exact history at the start of a row (BRSTM ADPC) } --- interleaved(dec, spec) -> Decoder | nil, Err function Decoder.interleaved(dec: any, spec: InterleavedSpec): (any, Err.Err?) local ch = dec.channels local kind = spec.kind @@ -145,9 +121,8 @@ function Decoder.interleaved(dec: any, spec: InterleavedSpec): (any, Err.Err?) end local buf, base, size = spec.buf, spec.offset, spec.size local rowBytes = il * ch - -- rows: the full ones, then the last (which may be shorter, and may be cut by a truncated file) local rows = math.max(1, math.ceil(size / rowBytes)) - local function rowFrames(r: number): number -- the frames row r (0-based) holds whole in every channel + local function rowFrames(r: number): number local width = if r == rows - 1 then last else il -- channel c sits at c * width in the row: the last channel is the one a cut file shortens local per = math.clamp(size - r * rowBytes - (ch - 1) * width, 0, width) @@ -211,12 +186,12 @@ end export type NibbleSpec = { buf: buffer, offset: number, - size: number, -- bytes + size: number, hi: boolean?, -- the high nibble first (DVI / KVAG); default low first - frames: number?, -- default: every whole frame of nibbles + frames: number?, } --- nibbles(dec, spec): an IMA stream starting from predictor 0, step index 0, channel c in nibbles c, c + ch, ... +-- IMA from predictor 0, step index 0; channel c in nibbles c, c + ch, ... function Decoder.nibbles(dec: any, spec: NibbleSpec): (any, Err.Err?) local ch = dec.channels local buf, base = spec.buf, spec.offset @@ -246,12 +221,11 @@ export type BlockSpec = { buf: buffer, offset: number, size: number, - blockAlign: number?, -- ms / ima_wav: bytes per block - frames: number?, -- default: what the blocks hold + blockAlign: number?, + frames: number?, coefs: { number }?, -- ms: coefficient pairs, flat (default the 7 standard pairs) } --- blockFrames(kind, blockAlign, ch) -> frames per block, or nil when the block cannot hold the headers function Decoder.blockFrames(kind: string, ba: number, ch: number): number? if kind == "ima_qt" then return 64 @@ -261,7 +235,6 @@ function Decoder.blockFrames(kind: string, ba: number, ch: number): number? return if ba >= 4 * ch then (ba - 4 * ch) * 2 // ch + 1 else nil end --- blocks(dec, spec): self-contained ADPCM blocks (no state across blocks); a truncated last block decodes what it has function Decoder.blocks(dec: any, spec: BlockSpec): (any, Err.Err?) local ch = dec.channels local kind = spec.kind @@ -278,7 +251,6 @@ function Decoder.blocks(dec: any, spec: BlockSpec): (any, Err.Err?) local rest = size - full * ba local total = full * spb if kind ~= "ima_qt" and rest > 0 then - -- a partial last block: the frames it holds whole if kind == "ms" then total += if rest >= 7 * ch then math.min(spb, 2 + ((rest - 7 * ch) * 2) // ch) else 0 elseif rest >= 4 * ch then diff --git a/src/Rosetta/codecs/audio/Adpcm/init.luau b/src/Rosetta/codecs/audio/Adpcm/init.luau index 466a6f8..4446798 100644 --- a/src/Rosetta/codecs/audio/Adpcm/init.luau +++ b/src/Rosetta/codecs/audio/Adpcm/init.luau @@ -1,31 +1,9 @@ --!strict --!native --!optimize 2 --- codecs/audio/Adpcm: the 4-bit ADPCM family, decode (and encode where it is cheap). New in rosetta; the IMA and --- MS block decoders moved here from audio/wav/Codecs (wav-luau, same author). ADX coefficients, PS-ADPCM and Nintendo --- DSP decoding follow vgmstream r2117 (ISC licence, licenses/vgmstream-LICENSE.txt) so the output is bit-exact with it: --- the ADX scale + 1 and the version 3 rounding, PS-ADPCM's float filter (exact in integers below 2^17), DSP's 1024 --- rounding. Codec kernels only: the formats (wav, aiff, caf, adx, vag, brstm, adpcm, ...) walk the layouts. --- --- Decoders write f32 (sample / 32768) to dst at float index d, every ds floats (interleaving), and keep their running --- state in a caller-owned buffer `st` at byte offset `so` (i32 pairs: IMA pred / step index, the others hist1 / hist2), --- so a decoder can stop between calls and snapshot the state for seeking (codecs/audio/Adpcm/Decoder). --- --- Adpcm.ima(src, p, q0, qs, count, hi, st, so, dst, d, ds) -- IMA nibbles: count samples, nibble q0, q0+qs, ... --- Adpcm.imaQt(src, p, st, so, dst, d, ds) -- Apple ima4: one 34-byte packet -> 64 samples --- Adpcm.imaWav(src, off, avail, ch, spb, dst, d) -> frames -- Microsoft IMA block (WAV / AVI) --- Adpcm.msBlock(src, off, avail, ch, spb, dst, d, coefs, ncoef, st) -> frames -- MS ADPCM block --- Adpcm.adx(src, p, pstride, nframes, c1, c2, v3, st, so, dst, d, ds) -- CRI ADX: 18-byte frames, 32 samples --- Adpcm.adxCoefs(cutoff, rate) -> c1, c2 --- Adpcm.psx(src, p, pstride, nframes, st, so, dst, d, ds) -- Sony PS-ADPCM (VAG): 16-byte frames, 28 samples --- Adpcm.dsp(src, p, count, coefs, co, st, so, dst, d, ds) -- Nintendo DSP: 8-byte frames, 14 samples --- Adpcm.modplug(src, p, count, dst, d) -- ModPlug ADPCM (XM / MOD samples) --- Adpcm.swfFrames(src, p, n, ch) -> frames -- Flash (SWF / FLV) ADPCM: one packet's length --- Adpcm.swf(src, p, n, ch, dst, d) -> frames -- Flash ADPCM: one packet of n bytes --- encoders: imaEncode, imaWavEncode, msEncode, adxEncode, psxEncode, dspEncode (see each) --- --- Every function reads only the bytes its arguments describe: the caller checks the ranges (byte counts per call are --- documented on each). Never throws. +-- codecs/audio/Adpcm: the 4-bit ADPCM family, decode (and encode where it is cheap). +-- ADX, PS-ADPCM and Nintendo DSP decoding follow vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt) bit-exactly: the +-- ADX scale + 1 and version 3 rounding, PS-ADPCM's float filter (exact in integers below 2^17), DSP's 1024 rounding. local readu8, readi16, readu16, readi32 = buffer.readu8, buffer.readi16, buffer.readu16, buffer.readi32 local writef32, readf32, writei32, writeu8, writeu16 = buffer.writef32, buffer.readf32, buffer.writei32, buffer.writeu8, buffer.writeu16 local band, rshift, bor, lshift = bit32.band, bit32.rshift, bit32.bor, bit32.lshift @@ -33,7 +11,6 @@ local floor = math.floor local Adpcm = {} --- ------------------------------------------------------------------------------------------------ IMA local IMA_STEP = { 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, 130, 143, 157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, 876, 963, 1060, @@ -67,9 +44,7 @@ for i = 0, 88 do end Adpcm.IMA_STEP = IMA_STEP --- ima: `count` samples of one channel from a nibble stream at byte p: nibble q0, q0 + qs, q0 + 2 qs, ... (nibble q is --- in byte p + q // 2, the low half first unless hi). State: st[so] predictor, st[so + 4] step index. Reads bytes --- p .. p + (q0 + (count - 1) * qs) // 2. +-- IMA nibble q is in byte p + q // 2, the low half first unless hi function Adpcm.ima(src: buffer, p: number, q0: number, qs: number, count: number, hi: boolean, st: buffer, so: number, dst: buffer, d: number, ds: number) local pred = readi32(st, so) @@ -106,10 +81,8 @@ function Adpcm.ima(src: buffer, p: number, q0: number, qs: number, count: number writei32(st, so + 4, index) end --- imaQt: one Apple ima4 packet (34 bytes at p: a big-endian header, the predictor's top 9 bits and the 7-bit step --- index, then 64 nibbles low first) -> 64 samples. Apple's decoders keep the running full-precision predictor while --- the header agrees with it (the same step index, the predictor within 127): st carries it from packet to packet --- (zeros before the first). +-- Apple ima4: 34 bytes: a big-endian header (the predictor's top 9 bits, 7-bit step index), 64 nibbles low first; +-- Apple's decoders keep the full-precision predictor while the header agrees (same step index, within 127) function Adpcm.imaQt(src: buffer, p: number, st: buffer, so: number, dst: buffer, d: number, ds: number) local h = readu8(src, p) * 256 + readu8(src, p + 1) local pred = band(h, 0xFF80) @@ -124,10 +97,8 @@ function Adpcm.imaQt(src: buffer, p: number, st: buffer, so: number, dst: buffer Adpcm.ima(src, p + 2, 0, 1, 64, false, st, so, dst, d, ds) end --- imaWav: one Microsoft IMA ADPCM block (WAV / AVI) at src[off]: per channel a 4-byte header (s16 predictor = the --- first sample, u8 step index, pad), then groups of 4 bytes (8 nibbles, low first) per channel in turn. avail: the --- bytes present (a truncated last block decodes the whole groups it has). Writes interleaved frames to dst from float --- index d; returns the frame count (<= spb). +-- Microsoft IMA block: per channel s16 predictor (= the first sample), u8 step index, pad; then 4-byte groups +-- (8 nibbles, low first) per channel in turn function Adpcm.imaWav(src: buffer, off: number, avail: number, ch: number, spb: number, dst: buffer, d: number): number if avail < 4 * ch then return 0 @@ -170,15 +141,12 @@ function Adpcm.imaWav(src: buffer, off: number, avail: number, ch: number, spb: return frames end --- ------------------------------------------------------------------------------------------------ MS ADPCM local MS_ADAPT = { 230, 230, 230, 230, 307, 409, 512, 614, 768, 614, 512, 409, 307, 230, 230, 230 } Adpcm.MS_COEF1 = { 256, 512, 0, 192, 240, 460, 392 } Adpcm.MS_COEF2 = { 0, -256, 0, 64, 0, -208, -232 } --- msBlock: one MS ADPCM block: per channel u8 predictor index, s16 delta, s16 sample 1, s16 sample 2 (each field for --- every channel in turn), then nibbles high first, channels interleaved per nibble. coefs: i32 pairs (coef1, coef2) x --- ncoef (256 = 1.0). state: 20 * ch bytes of scratch. avail: the bytes present. Writes interleaved frames to dst from --- float index d; returns the frame count (<= spb). +-- MS ADPCM block: per channel u8 predictor index, s16 delta, s16 sample 1, s16 sample 2 (each field for every channel +-- in turn), then nibbles high first, channels interleaved per nibble; coefficients 256 = 1.0 function Adpcm.msBlock(src: buffer, off: number, avail: number, ch: number, spb: number, dst: buffer, d: number, coefs: buffer, ncoef: number, state: buffer): number local hdr = 7 * ch @@ -233,15 +201,14 @@ function Adpcm.msBlock(src: buffer, off: number, avail: number, ch: number, spb: return frames end --- ------------------------------------------------------------------------------------------------ CRI ADX local F32 = buffer.create(4) local function f32(x: number): number writef32(F32, 0, x) return readf32(F32, 0) end --- adxCoefs(cutoff, rate) -> coef1, coef2 (fixed point, 12 fractional bits): the 2-pole high-pass predictor from the --- header's cutoff frequency, in single precision as CRI's decoders (and vgmstream) compute it +-- coef1, coef2 (12 fractional bits): the 2-pole high-pass predictor from the header's cutoff, in single precision as +-- CRI's decoders (and vgmstream) compute it function Adpcm.adxCoefs(cutoff: number, rate: number): (number, number) if rate <= 0 then return 0, 0 @@ -257,9 +224,8 @@ function Adpcm.adxCoefs(cutoff: number, rate: number): (number, number) return c1, c2 end --- adx: nframes 18-byte frames of one channel (s16 big-endian scale, 32 nibbles high first), pstride bytes apart from --- p. v3: the version 3 rounding (each product shifted on its own). A scale of 0x8001 (CRI's end marker) decodes as --- silence. Reads p .. p + (nframes - 1) * pstride + 17; writes 32 * nframes samples. +-- ADX frame: s16 big-endian scale, 32 nibbles high first. v3 shifts each product on its own; scale 0x8001 (CRI's end +-- marker) decodes as silence function Adpcm.adx(src: buffer, p: number, pstride: number, nframes: number, c1: number, c2: number, v3: boolean, st: buffer, so: number, dst: buffer, d: number, ds: number) local h1, h2 = readi32(st, so), readi32(st, so + 4) @@ -302,7 +268,6 @@ function Adpcm.adx(src: buffer, p: number, pstride: number, nframes: number, c1: writei32(st, so + 4, h2) end --- ------------------------------------------------------------------------------------------------ PS-ADPCM local PSX1 = { 0, 60, 115, 98, 122 } local PSX2 = { 0, 0, -52, -55, -60 } @@ -317,9 +282,8 @@ local function psxPred(f: number, h1: number, h2: number): number return if v >= 0 then floor(v) else -floor(-v) end --- psx: nframes 16-byte frames of one channel (filter << 4 | shift, flags, 28 nibbles low first), pstride bytes apart --- from p. Filters past 4 decode as 0 and shifts past 12 as 9 (as vgmstream); a frame with flags 7 is silence. The --- history keeps the unclipped value. Reads p .. p + (nframes - 1) * pstride + 15; writes 28 * nframes samples. +-- PS-ADPCM frame: filter << 4 | shift, flags, 28 nibbles low first. Filters past 4 decode as 0 and shifts past 12 as 9 +-- (as vgmstream); flags 7 is silence; the history keeps the unclipped value function Adpcm.psx(src: buffer, p: number, pstride: number, nframes: number, st: buffer, so: number, dst: buffer, d: number, ds: number) local h1, h2 = readi32(st, so), readi32(st, so + 4) @@ -364,10 +328,8 @@ function Adpcm.psx(src: buffer, p: number, pstride: number, nframes: number, st: writei32(st, so + 4, h2) end --- ------------------------------------------------------------------------------------------------ Nintendo DSP --- dsp: count samples of one channel from 8-byte frames at p (predictor << 4 | scale shift, 14 nibbles high first). --- coefs: 16 i32 at byte co (8 pairs, 11 fractional bits); a predictor index past 7 uses pair 7. Reads p .. --- p + ceil(count / 14) * 8 - 1. +-- DSP frame: predictor << 4 | scale shift, 14 nibbles high first; coefs 8 pairs, 11 fractional bits; a predictor +-- index past 7 uses pair 7 function Adpcm.dsp(src: buffer, p: number, count: number, coefs: buffer, co: number, st: buffer, so: number, dst: buffer, d: number, ds: number) local h1, h2 = readi32(st, so), readi32(st, so + 4) @@ -405,8 +367,6 @@ function Adpcm.dsp(src: buffer, p: number, count: number, coefs: buffer, co: num writei32(st, so + 4, h2) end --- ------------------------------------------------------------------------------------------------ encoders --- the nearest s16 to x * 32768 (NaN -> 0) local function toS16(x: number): number local v = floor(x * 32768 + 0.5) if v ~= v then @@ -420,7 +380,6 @@ local function toS16(x: number): number end Adpcm.toS16 = toS16 --- the IMA nibble for x from (pred, index): the one whose decoded value lands nearest (greedy, all 16 tried) local function imaNibble(x: number, pred: number, index: number): number local base = index * 8 + 1 local best, bestErr = 0, math.huge @@ -440,9 +399,6 @@ local function imaNibble(x: number, pred: number, index: number): number return best end --- imaEncode: count samples of one channel, f32 at float index xi every xs floats of x, into nibbles q0, q0 + qs, ... --- of out at byte p (the other half of each byte is kept). State as Adpcm.ima. Writes bytes p .. --- p + (q0 + (count - 1) * qs) // 2. function Adpcm.imaEncode(x: buffer, xi: number, xs: number, count: number, st: buffer, so: number, out: buffer, p: number, q0: number, qs: number, hi: boolean) local pred = readi32(st, so) @@ -468,9 +424,7 @@ function Adpcm.imaEncode(x: buffer, xi: number, xs: number, count: number, st: b writei32(st, so + 4, index) end --- imaWavEncode: one Microsoft IMA block of spb frames (spb = 1 + 8k) from interleaved f32 x at frame xf (frames --- available: n; the rest is padded with the last sample) to out[off] (4 * ch + (spb - 1) / 2 * ch bytes). st: 8 * ch --- bytes carrying the step index from block to block. +-- Microsoft IMA block: spb = 1 + 8k frames, 4 * ch + (spb - 1) / 2 * ch bytes function Adpcm.imaWavEncode(x: buffer, xf: number, n: number, ch: number, spb: number, st: buffer, out: buffer, off: number) local groups = (spb - 1) // 8 for c = 0, ch - 1 do @@ -504,8 +458,6 @@ function Adpcm.imaWavEncode(x: buffer, xf: number, n: number, ch: number, spb: n end end --- one MS ADPCM channel run for the encoder: the nibbles for samples 2 .. n - 1 with predictor (c1, c2) and the first --- delta; returns the squared error and the nibbles in nibs (when given) local function msTrial(xs: { number }, n: number, c1: number, c2: number, delta0: number, nibs: { number }?): number local s1, s2 = xs[2], xs[1] local idelta = delta0 @@ -528,9 +480,7 @@ local function msTrial(xs: { number }, n: number, c1: number, c2: number, delta0 return err end --- msEncode: one MS ADPCM block of spb frames (standard 7 coefficient pairs) from interleaved f32 x at frame xf --- (frames available: n; the rest is padded with silence) to out[off] (7 * ch + (spb - 2) * ch / 2 bytes). Each channel --- takes the predictor with the least error. +-- MS ADPCM block (standard 7 coefficient pairs): 7 * ch + (spb - 2) * ch / 2 bytes function Adpcm.msEncode(x: buffer, xf: number, n: number, ch: number, spb: number, out: buffer, off: number) local C1, C2 = Adpcm.MS_COEF1, Adpcm.MS_COEF2 local xs = table.create(spb, 0) @@ -540,7 +490,6 @@ function Adpcm.msEncode(x: buffer, xf: number, n: number, ch: number, spb: numbe for i = 1, spb do xs[i] = if i <= n then toS16(readf32(x, ((xf + i - 1) * ch + c) * 4)) else 0 end - -- the first delta from the first steps local sum = 0 for i = 3, math.min(spb, 10) do sum += math.abs(xs[i] - xs[i - 1]) @@ -568,8 +517,6 @@ function Adpcm.msEncode(x: buffer, xf: number, n: number, ch: number, spb: numbe end end --- one ADX frame for the encoder: the squared error of encoding xs[1..32] with scale from (h1, h2) (v4 rounding), and --- the nibbles in nibs when given; returns the error and the new history local function adxTrial(xs: { number }, scale: number, c1: number, c2: number, h1: number, h2: number, nibs: { number }?): (number, number, number) local err = 0 for k = 1, 32 do @@ -588,9 +535,8 @@ local function adxTrial(xs: { number }, scale: number, c1: number, c2: number, h return err, h1, h2 end --- adxEncode: count samples of one channel (f32 at float index xi every xs floats of x) as ceil(count / 32) ADX frames +-- ADX v4 rounding; the scale is stored minus one as CRI's decoders add it back -- (v4 rounding, the scale stored minus one as CRI's decoders add it back) at out[p], pstride bytes apart; the frame --- past count is padded with silence. State as Adpcm.adx. function Adpcm.adxEncode(x: buffer, xi: number, xs: number, count: number, c1: number, c2: number, st: buffer, so: number, out: buffer, p: number, pstride: number) local h1, h2 = readi32(st, so), readi32(st, so + 4) @@ -607,7 +553,6 @@ function Adpcm.adxEncode(x: buffer, xi: number, xs: number, count: number, c1: n b = a a = s end - -- the scale that covers the open-loop residual peak, and a few around it, closed loop local base = math.max(1, (peak + 6) // 7) local best, bestErr = base, math.huge for _, m in { 1, 0.75, 1.25, 0.5, 1.6 } do @@ -630,9 +575,6 @@ function Adpcm.adxEncode(x: buffer, xi: number, xs: number, count: number, c1: n writei32(st, so + 4, h2) end --- psxEncode: count samples of one channel (f32 at float index xi every xs floats of x) as ceil(count / 28) PS-ADPCM --- frames at out[p], pstride bytes apart, flags byte 0 (the caller sets loop / end flags); every filter and shift is --- tried per frame against Adpcm.psx's decoding, the least squared error wins. State as Adpcm.psx. function Adpcm.psxEncode(x: buffer, xi: number, xs: number, count: number, st: buffer, so: number, out: buffer, p: number, pstride: number) local h1, h2 = readi32(st, so), readi32(st, so + 4) @@ -667,7 +609,6 @@ function Adpcm.psxEncode(x: buffer, xi: number, xs: number, count: number, st: b end end end - -- the winner again, for its nibbles and history local fi, shift = rshift(bestHead, 4) + 1, band(bestHead, 15) local mul = 2 ^ (20 - shift) for k = 1, 28 do @@ -688,10 +629,8 @@ function Adpcm.psxEncode(x: buffer, xi: number, xs: number, count: number, st: b writei32(st, so + 4, h2) end --- ------------------------------------------------------------------------------------------------ ModPlug --- modplug: ModPlug / OpenMPT ADPCM samples (XM / MOD sample data marked 0xAD): a table of 16 signed byte deltas at --- p, then count nibbles (low first) at p + 16, each adding its table delta to a running signed byte (wrapping). --- Writes count f32 (value / 128) to dst from float index d. Reads p .. p + 16 + ceil(count / 2) - 1. +-- ModPlug / OpenMPT ADPCM (sample data marked 0xAD): 16 signed byte deltas, then nibbles low first, each adding its +-- delta to a wrapping signed byte; value / 128 function Adpcm.modplug(src: buffer, p: number, count: number, dst: buffer, d: number) local tab = table.create(16, 0) for k = 0, 15 do @@ -706,7 +645,6 @@ function Adpcm.modplug(src: buffer, p: number, count: number, dst: buffer, d: nu end end --- ------------------------------------------------------------------------------------------------ Flash ADPCM -- The SWF / FLV ADPCM (SoundFormat 1, Adobe's SWF specification, "ADPCM compression"): an MSB-first bit stream of -- 2 bits (code size - 2), then blocks of 4096 frames: per channel a signed 16-bit first sample and a 6-bit step -- index, then 4095 frames of `bits`-bit codes, channels interleaved. A code is IMA generalised to 2..5 bits: sign in @@ -719,7 +657,6 @@ local SWF_INDEX: { { number } } = { { -1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 4, 6, 8, 10, 13, 16 }, } --- swfFrames: the frame count of one Flash ADPCM packet (n bytes at p, n >= 1) function Adpcm.swfFrames(src: buffer, p: number, n: number, ch: number): number if n < 1 or ch < 1 then return 0 @@ -737,7 +674,6 @@ function Adpcm.swfFrames(src: buffer, p: number, n: number, ch: number): number return frames end --- the k-bit (k <= 16) MSB-first value at bit position pos of src[p ..]; bytes at or past e read as 0 local function msb(src: buffer, p: number, e: number, pos: number, k: number): number local q = p + rshift(pos, 3) local v = readu8(src, q) * 65536 @@ -750,8 +686,6 @@ local function msb(src: buffer, p: number, e: number, pos: number, k: number): n return band(rshift(v, 24 - band(pos, 7) - k), lshift(1, k) - 1) end --- swf: one Flash ADPCM packet (n bytes at p, ch channels) -> interleaved f32 frames to dst from float index d; returns --- the frame count (Adpcm.swfFrames). Reads p .. p + n - 1 only. function Adpcm.swf(src: buffer, p: number, n: number, ch: number, dst: buffer, d: number): number local frames = Adpcm.swfFrames(src, p, n, ch) if frames == 0 then diff --git a/src/Rosetta/codecs/audio/Alac/Decode.luau b/src/Rosetta/codecs/audio/Alac/Decode.luau index 031613a..70c3e59 100644 --- a/src/Rosetta/codecs/audio/Alac/Decode.luau +++ b/src/Rosetta/codecs/audio/Alac/Decode.luau @@ -1,10 +1,8 @@ --!strict --!native --!optimize 2 --- codecs/audio/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. +-- codecs/audio/Alac/Decode: the ALAC frame decoder (SCE / CPE / LFE / DSE / FIL / END elements). +-- Written from the ALAC format as published by Apple (ALACDecoder / ag_dec / dp_dec, Apache 2.0; behaviour, not code). 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 @@ -20,10 +18,10 @@ export type State = { 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 + pred: { { number } }, mix: { { number } }, shift: { number }, - out: { number }, -- interleaved output samples (integers), frames * channels + out: { number }, } local POW = table.create(64, 0) @@ -31,7 +29,6 @@ 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) @@ -72,7 +69,6 @@ local function scalar(b: buffer, pos: number, k: number, m: number, bps: number) 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 @@ -126,7 +122,6 @@ local function rice(b: buffer, pos: number, limit: number, out: { number }, n: n 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 @@ -180,8 +175,6 @@ local function predict(err: { number }, out: { number }, n: number, bps: number, 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" @@ -196,7 +189,7 @@ function Decode.frame(st: State, buf: buffer, off: number, len: number): (number local limit = len * 8 local pos = 0 local channels = st.channels - local ch = 0 -- next output channel + local ch = 0 local frames = -1 local out = st.out while true do @@ -331,7 +324,6 @@ function Decode.frame(st: State, buf: buffer, off: number, len: number): (number end shift = 0 end - -- unmix + shifted bytes -> interleaved output local sm = POW[shift + 1] if nch == 2 then local den = POW[mixBits + 1] @@ -394,7 +386,6 @@ function Decode.frame(st: State, buf: buffer, off: number, len: number): (number 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 @@ -404,7 +395,6 @@ function Decode.frame(st: State, buf: buffer, off: number, len: number): (number return frames, nil end --- the scratch state for a configuration function Decode.state(cfg: any): State local n = cfg.frameLength return { diff --git a/src/Rosetta/codecs/audio/Alac/Encode.luau b/src/Rosetta/codecs/audio/Alac/Encode.luau index 2543e77..117792d 100644 --- a/src/Rosetta/codecs/audio/Alac/Encode.luau +++ b/src/Rosetta/codecs/audio/Alac/Encode.luau @@ -1,11 +1,8 @@ --!strict --!native --!optimize 2 --- codecs/audio/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. +-- codecs/audio/Alac/Encode: an ALAC frame encoder (mixBits 2, LPC orders 4 / 8 with denShift 9, escape frames). +-- Written from the ALAC format; no third-party code. 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 @@ -27,16 +24,15 @@ export type State = { mb: number, kb: number, channels: number, - out: buffer, -- packet scratch - pos: number, -- bit position in out - cap: number, -- bits available + out: buffer, + pos: number, + cap: number, 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 @@ -66,7 +62,6 @@ local function putBig(st: State, v: number, n: number) end end --- ------------------------------------------------------------------------------------------------ rice code local function signExtend(v: number, bits: number): number local m = POW[bits + 1] v = v % m @@ -76,7 +71,6 @@ local function signExtend(v: number, bits: number): number 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 @@ -96,7 +90,6 @@ local function scalar(st: State, x: number, k: number, m: number, bps: number) 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 @@ -108,7 +101,6 @@ local function scalar(st: State, x: number, k: number, m: number, bps: number) 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 @@ -162,7 +154,6 @@ local function rice(st: State, e: { number }, n: number, bps: number, mult: numb 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] @@ -201,7 +192,6 @@ local function residuals(x: { number }, e: { number }, n: number, bps: number, c 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 @@ -248,7 +238,6 @@ local function lpc(x: { number }, n: number, order: number, work: { number }): { 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 @@ -274,9 +263,6 @@ local function analyse(st: State, x: { number }, n: number, bps: number): (numbe 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 @@ -299,7 +285,6 @@ function Encode.frame(st: State, samples: { number }, first: number, frames: num 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 @@ -334,7 +319,6 @@ function Encode.frame(st: State, samples: { number }, first: number, frames: num 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) @@ -376,7 +360,6 @@ function Encode.frame(st: State, samples: { number }, first: number, frames: num end end if not compressed then - -- uncompressed frame buffer.fill(st.out, 0, 0) st.pos = 0 ch = 1 diff --git a/src/Rosetta/codecs/audio/Alac/init.luau b/src/Rosetta/codecs/audio/Alac/init.luau index 90f73ca..1358c4f 100644 --- a/src/Rosetta/codecs/audio/Alac/init.luau +++ b/src/Rosetta/codecs/audio/Alac/init.luau @@ -1,18 +1,7 @@ --!strict --- codecs/audio/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("@rosetta/codecs/audio/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. +-- codecs/audio/Alac: Apple Lossless (ALAC) decoder and encoder. +-- Written from the ALAC format as Apple published it; no third-party code. ALAC stores C L R ... for 3+ channels; the +-- API uses WAV order. local Err = require("@rosetta/core/Err") local Bytes = require("@rosetta/core/Bytes") local Decode = require("@rosetta/codecs/audio/Alac/Decode") @@ -21,20 +10,19 @@ local Encode = require("@rosetta/codecs/audio/Alac/Encode") local Alac = {} export type Config = { - frameLength: number, -- samples per packet (4096) + frameLength: number, compatibleVersion: number, bitDepth: number, - pb: number, -- 40 - mb: number, -- 10 - kb: number, -- 14 + pb: number, + mb: number, + kb: number, channels: number, - maxRun: number, -- 255 + maxRun: number, 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 }, @@ -45,7 +33,6 @@ local TO_WAV: { { number } } = { { 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 }, @@ -58,7 +45,6 @@ local ELEMENTS: { { number } } = { } 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 @@ -104,7 +90,6 @@ function Alac.config(buf: buffer, offset: number?, length: number?): (Config?, E 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) @@ -121,10 +106,9 @@ function Alac.cookie(c: Config): buffer 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) + pcm: { number }, decode: (self: Decoder, buf: buffer, offset: number?, length: number?) -> (number?, Err.Err?), state: Decode.State, } @@ -157,7 +141,6 @@ local function decode(self: Decoder, buf: buffer, offset: number?, length: numbe return frames, nil end --- decoder(cfg) -> Decoder function Alac.decoder(cfg: Config): Decoder return { config = cfg, @@ -167,7 +150,6 @@ function Alac.decoder(cfg: Config): Decoder } end --- ------------------------------------------------------------------------------------------------ encoder export type Encoder = { config: Config, encode: (self: Encoder, samples: { number }, first: number, frames: number) -> (buffer?, Err.Err?), @@ -200,12 +182,11 @@ end export type EncoderOptions = { sampleRate: number, - channels: number, -- 1 .. 8 - bitDepth: number?, -- 16 (default), 20 or 24 - frameLength: number?, -- default 4096 + channels: number, + bitDepth: number?, + frameLength: number?, } --- 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") diff --git a/src/Rosetta/codecs/audio/Ape/Decode.luau b/src/Rosetta/codecs/audio/Ape/Decode.luau index 9a39f1f..15c638a 100644 --- a/src/Rosetta/codecs/audio/Ape/Decode.luau +++ b/src/Rosetta/codecs/audio/Ape/Decode.luau @@ -1,12 +1,9 @@ --!strict --!native --!optimize 2 --- codecs/audio/Ape/Decode: one Monkey's Audio frame -> samples. Ported from the Monkey's Audio SDK 13.28 (Matthew T. --- Ashland, BSD 3-clause, licenses/monkeys-audio-LICENSE.txt): UnBitArray.cpp (the range coder and its value model, --- 3.99+) and Old/UnBitArrayOld.cpp (CUnBitArray3891To3989, the 3.95 - 3.98 model), NNFilter / NNFilterCommon.h (the --- neural-net filters of the normal .. insane levels), NewPredictor.cpp (CPredictorDecompress3950toCurrent, its int32 --- and int64 flavours), ScaledFirstOrderFilter.h, Prepare.cpp (Unprepare: X / Y -> channels), APEDecompressCore.cpp --- (special frames, the frame CRC) and FloatTransform.cpp. Never throws: returns nil, message. +-- codecs/audio/Ape/Decode: one Monkey's Audio frame -> samples. +-- Ported from the Monkey's Audio SDK 13.28 (Matthew T. Ashland, BSD 3-clause, licenses/monkeys-audio-LICENSE.txt): +-- UnBitArray.cpp, Old/UnBitArrayOld.cpp, NNFilter.h, NewPredictor.cpp, Prepare.cpp, APEDecompressCore.cpp, FloatTransform.cpp. local Crc32 = require("@rosetta/core/Crc32") local readu8, readu32, writeu32, byteswap = buffer.readu8, buffer.readu32, buffer.writeu32, bit32.byteswap @@ -62,8 +59,8 @@ export type State = { bits: number, channels: number, filters: { Filter }, -- per level, applied last to first on decode (as m_spNNFilter2, 1, 0) - V: { { number } }, -- per channel: the frame's values through the stages - S: buffer, -- the frame bytes, word-swapped (+ PAD zeros) + V: { { number } }, + S: buffer, crcbuf: buffer, scratch: buffer, lastX: number, @@ -78,7 +75,6 @@ local FILTERS: { [number]: { number } } = { -- level -> { order, shift, ... } in [5000] = { 1280, 15, 256, 13, 16, 11 }, } --- state(version, level, bits, channels) -> State | nil, message function Decode.state(version: number, level: number, bits: number, channels: number): (State?, string?) local spec = FILTERS[level] if not spec then @@ -114,7 +110,6 @@ function Decode.state(version: number, level: number, bits: number, channels: nu }, nil end --- ------------------------------------------------------------------------------------------------ entropy -- the range coder as a record (the 3.95 - 3.98 model's RangeDecodeFastWithUpdate) type Rc = { q: number, low: number, range: number, prev: number } local function rcBits(rc: Rc, S: buffer, nb: number): number @@ -136,8 +131,6 @@ local function rcBits(rc: Rc, S: buffer, nb: number): number return r end --- values(st, q, n, order, old) -> q | nil, message: n blocks of range-coded values into st.V[c] for the channels of --- `order` (decode order), from byte q of st.S (the range coder starts there) local function values(st: State, q: number, lim: number, n: number, order: { number }, old: boolean): (number?, string?) local S = st.S local V = st.V @@ -298,13 +291,11 @@ local function values(st: State, q: number, lim: number, n: number, order: { num return q, nil end --- ------------------------------------------------------------------------------------------------ NN filters -- ((v >> s) & m) ~= 0 for an int64 v (s given as 2^s) local function negBit(v: number, p2: number, m: number): boolean return band((v // p2) % TWO32, m) ~= 0 end --- the int16 dot product of the weights and the inputs from byte b (span bytes) local function dot16(M: buffer, I: buffer, b: number, span: number): number local dot = 0 for k = 0, span - 16, 16 do @@ -332,8 +323,7 @@ local function dotAdapt16(M: buffer, I: buffer, D: buffer, b: number, span: numb return dot end --- one CNNFilter over n values of v, in place (DecompressGeneric). The weights, inputs and deltas live in buffers of --- the C types (int16 for 8 - 24-bit files, int32 for 32-bit ones: `wide`), so the weights wrap as the C shorts do +-- one CNNFilter (DecompressGeneric); weights in the C types (int16 up to 24-bit files, int32 for 32-bit) wrap as C does local function nnFilter(f: Filter, v: { number }, n: number, newDelta: boolean, wide: boolean) local order, M, I, D = f.order, f.M, f.I, f.D local es = if wide then 4 else 2 @@ -342,7 +332,7 @@ local function nnFilter(f: Filter, v: { number }, n: number, newDelta: boolean, buffer.fill(M, 0, 0, order * es) buffer.fill(I, 0, 0, (order + 1) * es) buffer.fill(D, 0, 0, (order + 1) * es) - local p = order -- the current element (0-based); its history is p - order .. p - 1 + local p = order local total = 512 + order local avg = 0 local span = order * 2 @@ -421,7 +411,6 @@ local function nnFilter(f: Filter, v: { number }, n: number, newDelta: boolean, end end --- ------------------------------------------------------------------------------------------------ predictor -- the adapt sign of a 32-bit file's int64 prediction value: ((v >> 30) & 2) - 1, or 0 local function adaptWide(v: number): number if v == 0 then @@ -430,8 +419,7 @@ local function adaptWide(v: number): number return if (v // 1073741824) % 4 >= 2 then 1 else -1 end --- predict(st, a, b?, n) : CPredictorDecompress3950toCurrent over channel a's values (nB = channel b's outputs of the --- block, or 0), single-channel form; stereo uses predictStereo +-- CPredictorDecompress3950toCurrent, single-channel form local function predictOne(st: State, v: { number }, n: number) local wide = st.bits >= 32 local lastA, prevA0, A1, A2, A3 = 0, 0, 0, 0, 0 @@ -489,7 +477,6 @@ local function predictStereo(st: State, X: { number }, Y: { number }, n: number) local xStage = 0 local lastX = 0 for t = 1, n do - -- Y local nA = Y[t] local A0 = yLast yA3 = yA2 @@ -539,7 +526,6 @@ local function predictStereo(st: State, X: { number }, Y: { number }, n: number) yStage = wrap32(cur + (yStage * 31) // 32) yLast = cur local yv = yStage - -- X nA = X[t] A0 = xLast xA3 = xA2 @@ -592,10 +578,6 @@ local function predictStereo(st: State, X: { number }, Y: { number }, n: number) end end --- ------------------------------------------------------------------------------------------------ frame --- frame(st, buf, at, rem, stop, n, P, float) -> n | nil, message: the frame whose words start at byte `at` (its first --- byte at at + rem), reading at most up to `stop`; n blocks into P (interleaved integers, or floats when float); cut: --- the data ends at `stop` before the frame does (a running-over decode is then "truncated", else corrupt) function Decode.frame(st: State, buf: buffer, at: number, rem: number, stop: number, n: number, P: { number }, float: boolean, cut: boolean): (number?, string?) local C, bits = st.channels, st.bits local len = math.max(0, stop - at) @@ -636,10 +618,9 @@ function Decode.frame(st: State, buf: buffer, at: number, rem: number, stop: num end stored %= TWO31 end - -- the values local V = st.V local order: { number } - local mode -- "silence", "pseudo", "stereo", "mono", "multi" + local mode if C == 1 then if band(special, 1) ~= 0 then mode = "silence" @@ -694,7 +675,7 @@ function Decode.frame(st: State, buf: buffer, at: number, rem: number, stop: num cb = buffer.create(n * C * bps + 1024) st.crcbuf = cb end - local paired: { [number]: boolean } = {} -- first channel (0-based) of an X / Y pair + local paired: { [number]: boolean } = {} if C == 2 and mode == "stereo" then paired[0] = true elseif C == 4 and (bits == 16 or bits == 24) then diff --git a/src/Rosetta/codecs/audio/Ape/init.luau b/src/Rosetta/codecs/audio/Ape/init.luau index 1a039e8..b0378b2 100644 --- a/src/Rosetta/codecs/audio/Ape/init.luau +++ b/src/Rosetta/codecs/audio/Ape/init.luau @@ -1,19 +1,7 @@ --!strict --- codecs/audio/Ape: the Monkey's Audio codec (.ape). A codec (layer 3). Ported from the Monkey's Audio SDK 13.28 --- (Matthew T. Ashland, BSD 3-clause since v10, licenses/monkeys-audio-LICENSE.txt): APEHeader.cpp (the descriptor / --- header / seek table, and the pre-3.98 header), APEInfo / APEDecompress.cpp (frame bytes and alignment); the frame --- decoder is codecs/audio/Ape/Decode. Supports file versions 3.95 and later (3.99+ as the current encoder writes; the --- 3.95 - 3.98 range coder model is ported but has no reference fixture), every compression level (fast, normal, high, --- extra high, insane), 8 / 16 / 24 / 32-bit integer and 32-bit float, 1 - 32 channels, special frames (silence, --- pseudo stereo) and the frame CRC. Not supported: versions before 3.95 (UNSUPPORTED), the "interim" 24-bit --- re-decode for files of the 32-bit era before 8.50, big-endian / signed 8-bit source flags (the samples are returned --- as numbers either way). --- --- local info, err = Ape.info(buf, base, limit) -- header facts + the frame table --- local dec = Ape.decoder(info) --- local n, err = dec:frame(buf, i) -- frame i (1-based) -> dec.pcm (interleaved; integers, or floats) --- --- Never throws: bad data returns nil, Err. +-- codecs/audio/Ape: the Monkey's Audio codec (.ape), file versions 3.95 and later. +-- Ported from the Monkey's Audio SDK 13.28 (Matthew T. Ashland, BSD 3-clause since v10, licenses/monkeys-audio-LICENSE.txt): +-- APEHeader.cpp, APEInfo / APEDecompress.cpp. Not supported: pre-3.95 (UNSUPPORTED), the pre-8.50 "interim" 24-bit re-decode. local Err = require("@rosetta/core/Err") local Bytes = require("@rosetta/core/Bytes") local Decode = require("@rosetta/codecs/audio/Ape/Decode") @@ -22,7 +10,7 @@ local Ape = {} export type Info = { version: number, -- file version * 1000 (3990) - programVersion: number, -- 13280 (0 when not stored) + programVersion: number, level: number, -- 1000 (fast) .. 5000 (insane) flags: number, channels: number, @@ -33,16 +21,15 @@ export type Info = { finalFrameBlocks: number, totalFrames: number, totalBlocks: number, - frameStart: { number }, -- byte offset of each frame + frameStart: { number }, firstFrame: number, -- byte offset of frame 1 (the word alignment origin) - dataEnd: number, -- the end of the frame data - limit: number, -- the end of the file data (frames past it are truncated) + dataEnd: number, + limit: number, md5: string?, } local FLAG_8, FLAG_24, FLAG_PEAK, FLAG_SEEKN, FLAG_WAVHDR, FLAG_FLOAT = 1, 8, 4, 16, 32, 4096 --- find(buf, base, limit) -> the offset of "MAC " / "MACF" (after an ID3v2 tag) | nil function Ape.find(buf: buffer, base: number, limit: number): number? local at = base if limit - at >= 10 and buffer.readstring(buf, at, 3) == "ID3" then @@ -70,7 +57,6 @@ function Ape.find(buf: buffer, base: number, limit: number): number? return if k then at + k - 1 else nil end --- info(buf, base, limit) -> Info | nil, Err function Ape.info(buf: buffer, base: number, limit: number): (Info?, Err.Err?) local at = Ape.find(buf, base, limit) if not at then @@ -184,7 +170,6 @@ function Ape.info(buf: buffer, base: number, limit: number): (Info?, Err.Err?) return info :: Info, nil end --- ------------------------------------------------------------------------------------------------ decoder export type Decoder = { info: Info, pcm: { number }, @@ -212,7 +197,6 @@ local function frame(self: Decoder, buf: buffer, i: number): (number?, Err.Err?) return n2, nil end --- decoder(info) -> Decoder | nil, Err function Ape.decoder(info: Info): (Decoder?, Err.Err?) local st, msg = Decode.state(info.version, info.level, info.bitsPerSample, info.channels) if not st then diff --git a/src/Rosetta/codecs/audio/ApeTag.luau b/src/Rosetta/codecs/audio/ApeTag.luau index 259bdcf..2caa8c2 100644 --- a/src/Rosetta/codecs/audio/ApeTag.luau +++ b/src/Rosetta/codecs/audio/ApeTag.luau @@ -1,17 +1,7 @@ --!strict --- codecs/audio/ApeTag: APEv1 / APEv2 tags (the tag block of Monkey's Audio, WavPack, Musepack, TTA, OptimFROG and --- some MP3s) -> Types.Tags. Written from the APEv2 specification (wiki.hydrogenaud.io "APEv2 specification"); no --- third-party code. A tag sits at the end of the file (before an optional ID3v1 tag) as items + a 32-byte footer --- "APETAGEX", with an optional 32-byte header in front (APEv2). Item keys become lower case tag keys (Year -> date, --- Track -> track, Album Artist -> albumartist, Disc -> disc, Comment -> comment); text values holding several --- values (NUL separated) are joined with "; "; binary items (cover art) and external links stay in info.items. --- Never throws. --- --- local tags, info = ApeTag.find(buf, start, limit) -- the tag ending at limit (or before an ID3v1 tag there) --- -- tags: { title = ..., artist = ... } | nil (no tag / malformed) --- -- info: { start = first byte (the header when present), stop = past the footer, version = 1000 | 2000, --- -- items = { { key = "Title", value = "...", kind = "text" | "binary" | "link" } } } --- local tags, info = ApeTag.parse(buf, footer, start) -- the tag whose footer is at byte `footer` (>= start) +-- codecs/audio/ApeTag: APEv1 / APEv2 tags -> Types.Tags. +-- From the APEv2 specification (wiki.hydrogenaud.io); no third-party code. Items + a 32-byte "APETAGEX" footer, optional +-- 32-byte header (APEv2), before an optional ID3v1 tag. local ApeTag = {} export type Item = { key: string, value: string, kind: string } @@ -27,14 +17,11 @@ local TO_TAG: { [string]: string } = { } local KINDS = { [0] = "text", "binary", "link", "text" } --- tagKey(itemKey) -> the Types.Tags key function ApeTag.tagKey(key: string): string local k = string.lower(key) return TO_TAG[k] or k end --- parse(buf, footer, start?) -> tags, info | nil: the tag whose 32-byte footer starts at byte `footer`; the items --- must lie at or after `start` (default 0) function ApeTag.parse(buf: buffer, footer: number, start: number?): ({ [string]: string }?, Info?) local lo = start or 0 local n = buffer.len(buf) @@ -89,8 +76,6 @@ function ApeTag.parse(buf: buffer, footer: number, start: number?): ({ [string]: return tags, { start = first, stop = footer + 32, version = version, items = items } end --- find(buf, start, limit) -> tags, info | nil: the tag at the end of [start, limit), or just before a 128-byte --- ID3v1 tag ("TAG") there function ApeTag.find(buf: buffer, start: number, limit: number): ({ [string]: string }?, Info?) if limit > buffer.len(buf) then limit = buffer.len(buf) diff --git a/src/Rosetta/codecs/audio/Flac/Encode.luau b/src/Rosetta/codecs/audio/Flac/Encode.luau index c2178b1..4cc0a1d 100644 --- a/src/Rosetta/codecs/audio/Flac/Encode.luau +++ b/src/Rosetta/codecs/audio/Flac/Encode.luau @@ -1,15 +1,8 @@ --!strict --!native --!optimize 2 --- codecs/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/audio/Pcm Source, so a Decoder is encoded without decoding it --- whole. Never throws: bad options are rejected by audio/flac before calling in. +-- codecs/audio/Flac/Encode: the FLAC encoder (RFC 9639), written from the RFC. +-- The presets mirror libFLAC's -0 .. -8; QLP precision follows libFLAC's table. local Bits = require("@rosetta/core/Bits") local Md5 = require("@rosetta/core/Md5") local VorbisComment = require("@rosetta/codecs/audio/VorbisComment") @@ -25,8 +18,6 @@ for i = 0, 63 do POW[i + 1] = 2 ^ i end --- ------------------------------------------------------------------------------------------------ CRCs --- (the decoder's tables: codecs/audio/Flac/Frame; (b, offset, count) here) local function crc8(b: buffer, o: number, n: number): number return Frame.crc8(b, o, o + n) end @@ -35,7 +26,6 @@ local function crc16(b: buffer, o: number, n: number): number end Encode.crc8, Encode.crc16 = crc8, crc16 --- ------------------------------------------------------------------------------------------------ bit writer (MSB first) type W = Bits.RawWriter local function ensure(w: W, n: number) @@ -74,12 +64,11 @@ local function putUtf8(w: W, v: number) end end --- ------------------------------------------------------------------------------------------------ presets export type Config = { blockSize: number, maxLpcOrder: number, maxPartitionOrder: number, - stereo: string, -- "independent" | "adaptive" | "exhaustive" + stereo: string, exhaustiveOrder: boolean, } local PRESETS: { Config } = { @@ -95,22 +84,20 @@ local PRESETS: { Config } = { } 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) + kind: number, + bits: number, order: number, wasted: number, - bps: number, -- sample size after removing wasted bits - res: { number }, -- residual (fixed / lpc), indices 1..n + bps: number, + res: { number }, 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 + x: { number }, } local function newPlan(n: number): Plan @@ -131,7 +118,6 @@ local function newPlan(n: number): Plan } end --- scratch per encoder type Scratch = { sums: { number }, counts: { number }, @@ -147,9 +133,7 @@ type Scratch = { 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 @@ -157,7 +141,6 @@ local function rice(sc: Scratch, res: { number }, n: number, order: number, maxP 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 @@ -206,7 +189,6 @@ local function rice(sc: Scratch, res: { number }, n: number, order: number, maxP 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] @@ -224,7 +206,6 @@ local function keepRice(sc: Scratch, plan: Plan, porder: number, method: number) end end --- fixed predictor residuals local function fixedResidual(x: { number }, n: number, order: number, res: { number }) for i = 1, order do res[i] = 0 @@ -310,7 +291,6 @@ local function qlpPrecision(bps: number, n: number): number 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 @@ -372,7 +352,6 @@ local function lpcResidual(x: { number }, n: number, order: number, qlp: { numbe 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] @@ -407,10 +386,8 @@ local function levinson(sc: Scratch, maxOrder: number): number 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 @@ -424,7 +401,6 @@ local function analyze(sc: Scratch, cfg: Config, src: { number }, n: number, bps plan.res[1] = first return end - -- wasted bits: the common trailing zeros local wasted = 0 do local w = 0 @@ -451,9 +427,7 @@ local function analyze(sc: Scratch, cfg: Config, src: { number }, n: number, bps 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 @@ -466,10 +440,8 @@ local function analyze(sc: Scratch, cfg: Config, src: { number }, n: number, bps 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) @@ -542,7 +514,6 @@ local function analyze(sc: Scratch, cfg: Config, src: { number }, n: number, bps end end --- ------------------------------------------------------------------------------------------------ writing local function writeResidual(w: W, plan: Plan, n: number) local method = plan.method put(w, method, 2) @@ -649,7 +620,6 @@ local function blockCode(n: number): (number, number) -- code, extra bits (0, 8, return 7, 16 end --- ------------------------------------------------------------------------------------------------ encoder export type Source = { sampleRate: number, channels: number, @@ -662,18 +632,16 @@ export type Options = { level: number, bits: number, blockSize: number?, - seekInterval: number, -- seconds between seek points (0 = no SEEKTABLE) - padding: number, -- bytes of PADDING + seekInterval: number, + padding: number, vendor: string, } --- 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) @@ -682,7 +650,6 @@ function Encode.encode(src: Source, opts: Options): (buffer?, string?) 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) @@ -692,14 +659,12 @@ function Encode.encode(src: Source, opts: Options): (buffer?, string?) seekPoints = 0 end end - -- vorbis comment local comments = VorbisComment.fields(src.tags) 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) @@ -747,7 +712,6 @@ function Encode.encode(src: Source, opts: Options): (buffer?, string?) end end local audioStart = w.pos - -- frames local md5 = Md5.new() local mbytes = (bps + 7) // 8 local mbuf = buffer.create(bs * ch * mbytes) @@ -794,7 +758,6 @@ function Encode.encode(src: Source, opts: Options): (buffer?, string?) 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 @@ -841,7 +804,6 @@ function Encode.encode(src: Source, opts: Options): (buffer?, string?) end end md5:update(mbuf, 0, mo) - -- channel decorrelation local assign = ch - 1 local chosen: { Plan } = {} if ch == 2 and cfg.stereo ~= "independent" then @@ -900,14 +862,12 @@ function Encode.encode(src: Source, opts: Options): (buffer?, string?) 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 @@ -957,7 +917,6 @@ function Encode.encode(src: Source, opts: Options): (buffer?, string?) 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()) @@ -965,7 +924,7 @@ function Encode.encode(src: Source, opts: Options): (buffer?, string?) return out, nil end --- streaminfo(...) -> the 34-byte STREAMINFO body +-- STREAMINFO: 34 bytes 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) diff --git a/src/Rosetta/codecs/audio/Flac/Frame.luau b/src/Rosetta/codecs/audio/Flac/Frame.luau index e723473..5627c4a 100644 --- a/src/Rosetta/codecs/audio/Flac/Frame.luau +++ b/src/Rosetta/codecs/audio/Flac/Frame.luau @@ -1,13 +1,9 @@ --!strict --!native --!optimize 2 --- codecs/audio/Flac/Frame: FLAC frames: header parsing (CRC-8), the sync search, subframes (constant, verbatim, fixed, LPC, wasted bits), --- residuals (Rice / Rice2 partitions, escapes), stereo decorrelation and the CRC-16 check. --- --- The input buffer must have at least PAD zero bytes after the data end (`len`): the bit reader reads 32-bit --- words without bounds checks and instead compares its position with the data end once per sample. Nothing here --- throws: bad data gives nil, err. --- Absorbed from flac-luau 7083d0d (same author, no third-party code). +-- codecs/audio/Flac/Frame: FLAC frames: header (CRC-8), sync search, subframes, residuals, decorrelation, CRC-16. +-- Absorbed from flac-luau 7083d0d (no third-party code). The input needs PAD zero bytes after `len`: the bit reader +-- reads 32-bit words unchecked and compares its position with the data end once per sample. local readu8, readu32 = buffer.readu8, buffer.readu32 local band, bxor, lshift, rshift, countlz, byteswap = bit32.band, bit32.bxor, bit32.lshift, bit32.rshift, bit32.countlz, bit32.byteswap @@ -62,7 +58,7 @@ local RATE = { [1] = 88200, [2] = 176400, [3] = 192000, [4] = 8000, [5] = 16000, local BITS = { [1] = 8, [2] = 12, [4] = 16, [5] = 20, [6] = 24, [7] = 32 } export type Header = { - offset: number, -- byte offset of the sync code + offset: number, size: number, -- header bytes, CRC-8 included blockSize: number, sampleRate: number, @@ -73,8 +69,6 @@ export type Header = { number: number, } --- Parse the frame header at pos (data ends at len; the buffer is padded). si gives the STREAMINFO defaults --- (sampleRate, bitsPerSample) for the "from STREAMINFO" codes. Returns nil when it is not a valid header. function Frame.header(b: buffer, pos: number, len: number, si: any): Header? if pos < 0 or pos + 6 > len then return nil @@ -155,7 +149,6 @@ function Frame.header(b: buffer, pos: number, len: number, si: any): Header? if not bs or not bps or bps < 4 or bps > 32 or p + 1 > len then return nil end - -- CRC-8 over the header if crc8(b, pos, p) ~= readu8(b, p) then return nil end @@ -172,7 +165,6 @@ function Frame.header(b: buffer, pos: number, len: number, si: any): Header? } end --- The first valid header at an offset in [pos, limit) function Frame.find(b: buffer, pos: number, limit: number, len: number, si: any): Header? local lim = math.min(limit, len - 6) if pos < 0 then @@ -193,7 +185,6 @@ function Frame.find(b: buffer, pos: number, limit: number, len: number, si: any) return nil end --- Bit reading for the header parts of subframes: n <= 32 bits at bit position p (unsigned) local function bits(b: buffer, p: number, n: number): number if n == 0 then return 0 @@ -213,7 +204,6 @@ local function sbits(b: buffer, p: number, n: number): number return v end --- Residual coding: fills s[order + 1 .. n] with residuals. Returns the new bit position, or -1. local function residual(b: buffer, p: number, lim: number, s: { number }, n: number, order: number): number local method = bits(b, p, 2) if method > 1 then @@ -258,7 +248,6 @@ local function residual(b: buffer, p: number, lim: number, s: { number }, n: num end end elseif k <= 24 then - -- the hot loop: unary quotient + k-bit remainder, zigzag local pk = POW2[k + 1] local rk = 32 - k for j = i, stop do @@ -280,7 +269,6 @@ local function residual(b: buffer, p: number, lim: number, s: { number }, n: num p += k end else - -- a long run of zeros q = 32 - sh p += q while true do @@ -448,7 +436,6 @@ local function lpc(s: { number }, n: number, cf: { number }, order: number, shif end end --- One subframe into s[1..n]. Returns the new bit position, or -1. local function subframe(b: buffer, p: number, lim: number, s: { number }, n: number, bps: number, cf: { number }): number if p > lim then return -1 @@ -558,8 +545,6 @@ local function subframe(b: buffer, p: number, lim: number, s: { number }, n: num return p end --- Decode the frame whose header h was parsed (data ends at len). chans[c] are tables of at least h.blockSize --- numbers; they receive the samples. Returns the byte offset after the frame, or nil, err. function Frame.decode(b: buffer, len: number, h: Header, chans: { { number } }, cf: { number }, checkCrc: boolean): (number?, string?) local n = h.blockSize local lim = len * 8 @@ -575,7 +560,7 @@ function Frame.decode(b: buffer, len: number, h: Header, chans: { { number } }, return nil, "bad subframe" end end - local e = rshift(p + 7, 3) -- byte align + local e = rshift(p + 7, 3) if e + 2 > len then return nil, "truncated frame" end diff --git a/src/Rosetta/codecs/audio/Flac/init.luau b/src/Rosetta/codecs/audio/Flac/init.luau index 2209965..cd70bbd 100644 --- a/src/Rosetta/codecs/audio/Flac/init.luau +++ b/src/Rosetta/codecs/audio/Flac/init.luau @@ -1,8 +1,6 @@ --!strict --- codecs/audio/Flac: FLAC frames without the container: frame header parsing, subframe decoding (constant, verbatim, --- fixed, LPC, Rice residuals, stereo decorrelation) with CRC-8 / CRC-16 (Frame), and the frame encoder (Encode). --- Absorbed from flac-luau 7083d0d (same author); the encoder is new. Native FLAC / Ogg FLAC streams, metadata and --- seeking are audio/flac. +-- codecs/audio/Flac: FLAC frames without the container (frame header, subframes, CRC-8 / CRC-16) and the frame encoder. +-- Absorbed from flac-luau 7083d0d; the encoder is new. local Flac = { Frame = require("@rosetta/codecs/audio/Flac/Frame"), Encode = require("@rosetta/codecs/audio/Flac/Encode"), diff --git a/src/Rosetta/codecs/audio/Hively/Load.luau b/src/Rosetta/codecs/audio/Hively/Load.luau index 342fb09..40f5936 100644 --- a/src/Rosetta/codecs/audio/Hively/Load.luau +++ b/src/Rosetta/codecs/audio/Hively/Load.luau @@ -1,8 +1,7 @@ --!strict --- codecs/audio/Hively/Load: AHX ("THX\0".."THX\2") and HivelyTracker ("HVL\0", "HVL\1") module files -> the replayer's --- Tune. Ported from hvl2wav's replay.c 1.9 loaders (hvl_load_ahx / hvl_reset; BSD-3-Clause, (c) 2006-2018 Pete Gordon; --- licenses/hivelytracker-LICENSE.txt), with bounds checks the C code does not have. Errors are returned as --- (nil, message, kind) for core/Err.from. +-- codecs/audio/Hively/Load: AHX ("THX\0".."THX\2") and HivelyTracker ("HVL\0", "HVL\1") module files -> Tune. +-- Ported from hvl2wav replay.c 1.9 (hvl_load_ahx / hvl_reset; BSD-3-Clause, (c) 2006-2018 Pete Gordon; +-- licenses/hivelytracker-LICENSE.txt), with bounds checks the C code does not have. local Load = {} local readu8, readi8 = buffer.readu8, buffer.readi8 @@ -27,23 +26,23 @@ export type Instrument = { plist: { speed: number, length: number, entries: { PlistEntry } }, } export type Tune = { - format: string, -- "ahx" | "hvl" - version: number, -- the 4th byte: AHX 0..2, HVL 0..1 + format: string, + version: number, title: string, - channels: number, -- 4 (AHX), 4..16 (HVL) + channels: number, positionNr: number, restart: number, - speedMultiplier: number, -- 1..4 player calls per 50 Hz frame - trackLength: number, -- rows per track, 1..64 - trackNr: number, -- the highest track number stored + speedMultiplier: number, + trackLength: number, + trackNr: number, instrumentNr: number, - subsongs: { number }, -- first positions of subsongs 1..n + subsongs: { number }, positions: buffer, -- positionNr * 16 * 2 bytes: per channel track (u8), transpose (i8) tracks: buffer, -- 257 * 64 * 6 bytes: per track row note, instrument, fx, param, fxb, paramb - instruments: { Instrument }, -- 1-based, as numbered in the file + instruments: { Instrument }, mixgain: number, -- (percent * 256) / 100, HVL only (AHX: set by the stereo separation at render time) - stereo: number, -- HVL: the default stereo separation 0..4 - emptyTrack0: boolean, -- track 0 is not stored (always empty) + stereo: number, + emptyTrack0: boolean, } local function cstring(b: buffer, p: number, limit: number, max: number): (string, number) @@ -54,7 +53,6 @@ local function cstring(b: buffer, p: number, limit: number, max: number): (strin return buffer.readstring(b, p, e - p), e end --- parse(b, base, limit) -> Tune | nil, message, kind function Load.parse(b: buffer, base: number, limit: number): (Tune?, string?, string?) local size = limit - base if size < 14 then diff --git a/src/Rosetta/codecs/audio/Hively/Player.luau b/src/Rosetta/codecs/audio/Hively/Player.luau index 71b666d..b88d83e 100644 --- a/src/Rosetta/codecs/audio/Hively/Player.luau +++ b/src/Rosetta/codecs/audio/Hively/Player.luau @@ -1,10 +1,8 @@ --!strict --!native --- codecs/audio/Hively/Player: the AHX / HivelyTracker replayer: positions and tracks (two effect columns in HVL), the --- instrument engine (ADSR, vibrato, the PList performance list, square modulation, the resonant filter sweep, hard cut, --- ring modulation and panning for HVL) and the integer mixer, all as hvl2wav's replay.c 1.9 computes them so the output --- matches hvl2wav sample for sample. Ported from HivelyTracker (BSD-3-Clause, (c) 2006-2018 Pete Gordon; --- licenses/hivelytracker-LICENSE.txt). Where the C code reads outside its arrays on bad data this port clamps instead. +-- codecs/audio/Hively/Player: the AHX / HivelyTracker replayer and integer mixer, as hvl2wav's replay.c 1.9 computes them. +-- Ported from HivelyTracker (BSD-3-Clause, (c) 2006-2018 Pete Gordon; licenses/hivelytracker-LICENSE.txt). Where the C +-- code reads outside its arrays on bad data this port clamps instead. local Tables = require("@rosetta/codecs/audio/Hively/Tables") local Load = require("@rosetta/codecs/audio/Hively/Load") @@ -102,7 +100,6 @@ local function newVoice(i: number): Voice } end --- new(tune, freq, stereo, subsong) -> State | nil (subsong out of range). stereo: AHX separation 0..4 (HVL: the file's) function Player.new(tune: Load.Tune, freq: number, stereo: number, subsong: number): State? if subsong < 0 or subsong > #tune.subsongs then return nil @@ -130,7 +127,6 @@ function Player.new(tune: Load.Tune, freq: number, stereo: number, subsong: numb return st end --- ------------------------------------------------------------------------------------------------ steps local function setPan(st: State, v: Voice, p: number) v.pan = p v.panMultLeft, v.panMultRight = st.panL[p], st.panR[p] @@ -370,7 +366,6 @@ local function processStep(st: State, v: Voice) stepfx3(st, v, fxb, fxbp) end --- ------------------------------------------------------------------------------------------------ frames local function plistCommand(st: State, v: Voice, fx: number, param: number) if fx == 0 then if param > 0 and param < 0x40 then @@ -537,7 +532,6 @@ local function processFrame(st: State, v: Voice) end end - -- ADSR envelope if v.aFrames ~= 0 then v.adsrVolume += v.aVolume v.aFrames -= 1 @@ -560,10 +554,8 @@ local function processFrame(st: State, v: Voice) end end - -- volume slide v.noteMaxVolume = math.clamp(v.noteMaxVolume + v.volumeSlideUp - v.volumeSlideDown, 0, 0x40) - -- portamento if v.periodSlideOn then if v.periodSlideWithLimit then local d0 = v.periodSlidePeriod - v.periodSlideLimit @@ -588,7 +580,6 @@ local function processFrame(st: State, v: Voice) end end - -- vibrato if v.vibratoDepth ~= 0 then if v.vibratoDelay <= 0 then v.vibratoPeriod = (VIB[v.vibratoCurrent] * v.vibratoDepth) // 128 @@ -599,7 +590,6 @@ local function processFrame(st: State, v: Voice) end end - -- PList local pl = v.perfList if pl then if v.instrument and v.perfCurrent < v.instrument.plist.length then @@ -636,7 +626,6 @@ local function processFrame(st: State, v: Voice) end end - -- perf portamento if v.periodPerfSlideOn then v.periodPerfSlidePeriod = s16(v.periodPerfSlidePeriod - v.periodPerfSlideSpeed) if v.periodPerfSlidePeriod ~= 0 then @@ -754,7 +743,6 @@ local function processFrame(st: State, v: Voice) end end - -- ring modulation period if v.ringAudioOff >= 0 then local rp = v.ringBasePeriod if v.ringFixedPeriod == 0 then @@ -772,7 +760,6 @@ local function processFrame(st: State, v: Voice) v.ringAudioPeriod = math.clamp(rp, 0x71, 0xd60) end - -- the period local ap = v.instrPeriod if v.fixedNote == 0 then if v.overrideTranspose ~= 1000 then @@ -794,7 +781,6 @@ local function processFrame(st: State, v: Voice) v.audioVolume = s16(vol) end --- fill the 0x280-byte voice buffer with repeats of the 4 << waveLength cycle at (src, off) local function fillCycles(dst: buffer, src: buffer, off: number, len: number) if off < 0 or off + len > buffer.len(src) then buffer.fill(dst, 0, 0, 0x281) @@ -830,7 +816,7 @@ local function setAudio(st: State, v: Voice) end end --- irq(st, audio): one player call (hvl_play_irq); audio = false skips the audio side (duration scans) +-- hvl_play_irq (audio = false skips the audio side) function Player.irq(st: State, audio: boolean) local tune = st.tune local nch = st.channels @@ -888,7 +874,7 @@ function Player.irq(st: State, audio: boolean) end end --- mix(st, out, at, n): n stereo frames of f32 into out at frame `at` (hvl_mixchunk: integer mixing, s16 clipping, / 32768) +-- hvl_mixchunk: integer mixing, s16 clipping, / 32768 function Player.mix(st: State, out: buffer, at: number, n: number) local nch = st.channels local voices = st.voices diff --git a/src/Rosetta/codecs/audio/Hively/Tables.luau b/src/Rosetta/codecs/audio/Hively/Tables.luau index 8d76e0e..cb558db 100644 --- a/src/Rosetta/codecs/audio/Hively/Tables.luau +++ b/src/Rosetta/codecs/audio/Hively/Tables.luau @@ -1,15 +1,12 @@ --!strict --!native --- codecs/audio/Hively/Tables: the AHX / HivelyTracker replayer's tables: the waveform block (triangle and sawtooth at --- six lengths, 32 square pulse widths, white noise, and the 31 low-pass and 31 high-pass filtered copies of all of --- them, generated as hvl_replay.c does), the sine panning tables, the vibrato sine and the Amiga period table. Ported --- from HivelyTracker's hvl2wav replay.c 1.9 (BSD-3-Clause, (c) 2006-2018 Pete Gordon; licenses/hivelytracker-LICENSE.txt) --- as hvl2wav builds on 64-bit Linux (`long` is 64-bit there: the noise generator's shifts do not wrap at 32 bits). +-- codecs/audio/Hively/Tables: the AHX / HivelyTracker replayer's waveform, panning, vibrato and period tables. +-- Ported from hvl2wav replay.c 1.9 (BSD-3-Clause, (c) 2006-2018 Pete Gordon; licenses/hivelytracker-LICENSE.txt) as +-- built on 64-bit Linux (`long` is 64-bit: the noise generator's shifts do not wrap at 32 bits). local Tables = {} local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift --- the offsets inside `waves` (bytes) local FILTER_SET = 0xfc + 0xfc + 0x80 * 0x1f + 0x80 + 3 * 0x280 -- 6520: one filtered copy of every waveform local WHITENOISELEN = 0x280 * 3 local WO_LOWPASSES = 0 @@ -184,7 +181,6 @@ end local cache: { waves: buffer, panL: { number }, panR: { number } }? = nil --- get() -> { waves (int8 buffer), panL, panR (0-based, 256 entries) }: built once, shared read only function Tables.get(): { waves: buffer, panL: { number }, panR: { number } } if cache then return cache diff --git a/src/Rosetta/codecs/audio/Hively/init.luau b/src/Rosetta/codecs/audio/Hively/init.luau index bfdb4d8..93e0363 100644 --- a/src/Rosetta/codecs/audio/Hively/init.luau +++ b/src/Rosetta/codecs/audio/Hively/init.luau @@ -1,17 +1,8 @@ --!strict --- codecs/audio/Hively: the AHX / HivelyTracker engine behind music/ahx and music/hvl: the loader for both file formats --- (Load), the replayer with its waveform generator (Tables: triangle / sawtooth / square / noise and the 31 + 31 --- filtered copies) and integer mixer (Player), and the render glue to a Types.Decoder (stereo f32). A port of --- HivelyTracker's hvl2wav replay.c 1.9 (BSD-3-Clause, (c) 2006-2018 Pete Gordon; licenses/hivelytracker-LICENSE.txt): --- at hvl2wav's settings the output equals hvl2wav's 16-bit samples / 32768, sample for sample. --- --- local Hively = require("@rosetta/codecs/audio/Hively") --- local tune, err = Hively.parse(buf, 0, buffer.len(buf)) -- the replayer's Tune --- local song = Hively.module(tune) -- a Types.Module-shaped value with render() --- local dec = Hively.decoder(tune, { sampleRate = 44100 }) -- a Types.Decoder --- --- Not supported: hvl2wav's -a auto gain; a speed multiplier of 4 at 44.1 kHz renders 880 samples per 50 Hz frame --- (hvl2wav pads each frame to 882 with stale samples). +-- codecs/audio/Hively: the AHX / HivelyTracker engine (loader, replayer, waveform tables, render glue). +-- A port of hvl2wav replay.c 1.9 (BSD-3-Clause, (c) 2006-2018 Pete Gordon; licenses/hivelytracker-LICENSE.txt); at +-- hvl2wav's settings the output equals its 16-bit samples / 32768. hvl2wav pads a 44.1 kHz speed-multiplier-4 frame to +-- 882 samples with stale data; this renders 880. local Err = require("@rosetta/core/Err") local Types = require("@rosetta/Types") local Load = require("@rosetta/codecs/audio/Hively/Load") @@ -22,14 +13,13 @@ local Hively = {} export type Tune = Load.Tune export type RenderOptions = { - sampleRate: number?, -- default 44100 (the replayer runs at any rate: 8000..192000) - subsong: number?, -- 0 = the main song (default), 1..n the subsongs - stereo: number?, -- AHX stereo separation 0..4 (0 mono, 4 = 100 % Amiga L R R L); default 0 as hvl2wav. HVL: the file's - loop: boolean?, -- keep playing past the song end (frames / duration still give one pass) + sampleRate: number?, + subsong: number?, + stereo: number?, -- AHX stereo separation 0..4 (4 = 100 % Amiga L R R L); default 0 as hvl2wav + loop: boolean?, maxDuration: number?, -- seconds, default 600 (hvl2wav's 10 minute limit) } --- parse(b, base?, limit?) -> Tune | nil, Err function Hively.parse(b: buffer, base: number?, limit: number?): (Tune?, Err.Err?) local tune, msg, kind = Load.parse(b, base or 0, limit or buffer.len(b)) if not tune then @@ -51,7 +41,6 @@ local function settings(tune: Tune, opts: RenderOptions?): (number?, number, num return rate, sub, tonumber(o.stereo) or 0, nil end --- frameCount(tune, opts?) -> 50 Hz frames until the song end (as hvl2wav stops), capped by maxDuration function Hively.frameCount(tune: Tune, opts: RenderOptions?): number local rate, sub, stereo = settings(tune, opts) local st = rate and Player.new(tune, rate :: number, stereo, sub) @@ -69,7 +58,6 @@ function Hively.frameCount(tune: Tune, opts: RenderOptions?): number return n end --- decoder(tune, opts?) -> Types.Decoder | nil, Err function Hively.decoder(tune: Tune, opts: RenderOptions?): (Types.Decoder?, Err.Err?) local rate, sub, stereo, err = settings(tune, opts) if not rate then @@ -84,7 +72,7 @@ function Hively.decoder(tune: Tune, opts: RenderOptions?): (Types.Decoder?, Err. local loop = opts ~= nil and opts.loop == true local st = Player.new(tune, sr, stereo, sub) :: Player.State local fbuf = buffer.create(perFrame * 8) - local fpos, ffill = 0, 0 -- read position / filled frames inside fbuf + local fpos, ffill = 0, 0 local pos = 0 local function nextFrame() @@ -147,8 +135,6 @@ function Hively.decoder(tune: Tune, opts: RenderOptions?): (Types.Decoder?, Err. return (dec :: any) :: Types.Decoder, nil end --- module(tune) -> a Types.Module-shaped value (kind "music"): tracks as patterns (rows * 6 bytes: note, instrument, --- fx, param, fxb, paramb), positions, instruments with their play lists, and render(opts) -> Decoder function Hively.module(tune: Tune): Types.Module local patterns = {} for t = 0, tune.trackNr do @@ -198,7 +184,6 @@ function Hively.module(tune: Tune): Types.Module if dec then return dec end - -- the Types contract returns a Decoder: a failed render is an empty one carrying the Err local empty: any = Pcm.audioDecoder(Types.Audio.new(44100, 2, 0)) empty.err = derr return empty diff --git a/src/Rosetta/codecs/audio/Mdct/Fft.luau b/src/Rosetta/codecs/audio/Mdct/Fft.luau index a995706..093edc6 100644 --- a/src/Rosetta/codecs/audio/Mdct/Fft.luau +++ b/src/Rosetta/codecs/audio/Mdct/Fft.luau @@ -1,10 +1,8 @@ --!strict --!native --!optimize 2 --- codecs/audio/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. +-- codecs/audio/Mdct/Fft: mixed-radix complex FFT (radix 4, 2, 3, 5, generic odd), self-sorting Stockham passes (the +-- FFTPACK / pocketfft pass structure, written from the textbook derivation; no third-party code). local Fft = {} export type Plan = { @@ -16,13 +14,12 @@ export type Plan = { -- per pass, generic odd radix: exp(-2 pi i k / p) for k = 0 .. p - 1 rr: { { number } }, ri: { { number } }, - sre: { number }, -- scratch + sre: { number }, 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 @@ -189,8 +186,7 @@ local function pass(p: number, ido: number, l1: number, ar: { number }, ai: { nu 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). +-- X[k] = sum x[j] exp(-2 pi i j k / n), in place; the inverse (without 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 diff --git a/src/Rosetta/codecs/audio/Mdct/init.luau b/src/Rosetta/codecs/audio/Mdct/init.luau index e58a7c1..f223231 100644 --- a/src/Rosetta/codecs/audio/Mdct/init.luau +++ b/src/Rosetta/codecs/audio/Mdct/init.luau @@ -1,28 +1,14 @@ --!strict --!native --!optimize 2 --- codecs/audio/Mdct: the MDCT / IMDCT of any window length N divisible by 4 (N / 2 coefficients), through an N / 4-point --- complex FFT (codecs/audio/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. +-- codecs/audio/Mdct: MDCT / IMDCT for any N divisible by 4, DCT-IV, and the sine / KBD / Vorbis windows. +-- Through an N / 4-point complex FFT; written from the textbook definitions, 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("@rosetta/codecs/audio/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). +-- Unnormalised: forward + inverse + overlap-add with a Princen-Bradley window gives the input times N / 4 (the AAC spec +-- IMDCT is inverse(..., 2 / N)). local Fft = require("@rosetta/codecs/audio/Mdct/Fft") local cos, sin, pi, sqrt = math.cos, math.sin, math.pi, math.sqrt @@ -31,17 +17,16 @@ local Mdct = {} Mdct.Fft = Fft export type Plan = { - n: number, -- window length N - m: number, -- coefficients N / 2 - fft: Fft.Plan, -- N / 4 points + n: number, + m: number, + fft: Fft.Plan, twc: { number }, -- cos / sin (pi (p + 1/8) / M), p = 0 .. N/4 - 1 tws: { number }, - re: { number }, -- scratch + re: { number }, im: { number }, - c: { number }, -- DCT-IV output scratch (M) + c: { number }, } --- 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 @@ -69,7 +54,6 @@ function Mdct.new(n: number): Plan? } 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 @@ -82,8 +66,7 @@ local function dct4Post(plan: Plan, out: { number }, oi: number, os: number, sca 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) +-- C[k] = sum_{n=0}^{M-1} u[n] cos(pi / M (n + 1/2) (k + 1/2)), 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 @@ -96,10 +79,9 @@ function Mdct.dct4(plan: Plan, u: { number }, ui: number, us: number, out: { num 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 h = m // 2 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 @@ -125,7 +107,6 @@ function Mdct.forward(plan: Plan, x: { number }, xi: number, out: { number }, oi 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 @@ -140,7 +121,6 @@ function Mdct.inverse(plan: Plan, inp: { number }, ii: number, is: number?, y: { end end --- ------------------------------------------------------------------------------------------------ windows local function besselI0(x: number): number local sum, term = 1, 1 local k = 1 @@ -156,8 +136,8 @@ local function besselI0(x: number): number 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. +-- "sine" sin(pi (n + 1/2) / N); "kbd" Kaiser-Bessel-derived (AAC: alpha 4 long, 6 short); "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 @@ -195,7 +175,6 @@ function Mdct.window(kind: string, n: number, alpha: number?): { number }? 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 diff --git a/src/Rosetta/codecs/audio/MidiRender.luau b/src/Rosetta/codecs/audio/MidiRender.luau index eb29f54..b4b1aa2 100644 --- a/src/Rosetta/codecs/audio/MidiRender.luau +++ b/src/Rosetta/codecs/audio/MidiRender.luau @@ -1,9 +1,7 @@ --!strict --- codecs/audio/MidiRender: the tempo map (ticks -> seconds, as python mido computes lengths), the time-ordered event list, --- and the audio Decoder that plays a Midi through codecs/audio/SoundFont's synth (a SoundFont bank, or the built-in --- waveform set). Format 0 / 1: one tempo map from every track's tempo events, tracks merged (ties keep track order). --- Format 2: each track is its own song with its own tempo map, played one after another. Shared by every format that --- decodes to a Types.Midi (music/midi, mus, xmi, hmp): attach() adds the meta summary and the render method. +-- codecs/audio/MidiRender: the MIDI tempo map, event timeline and the Decoder that plays a Midi through SoundFont. +-- Lengths as python mido computes them. Format 0 / 1: one tempo map from every track, tracks merged (ties keep track +-- order); format 2: each track is its own song, played one after another. local Err = require("@rosetta/core/Err") local Types = require("@rosetta/Types") local SoundFont = require("@rosetta/codecs/audio/SoundFont") @@ -23,7 +21,6 @@ local function tempoOf(ev: any): number? 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 @@ -62,7 +59,6 @@ function Render.tempoMap(midi: Types.Midi, track: number?): TempoMap 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 @@ -74,7 +70,6 @@ function Render.seconds(map: TempoMap, tick: number): number 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 @@ -87,7 +82,6 @@ function Render.seconds(map: TempoMap, tick: number): number 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 @@ -116,7 +110,6 @@ 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 @@ -162,14 +155,13 @@ function Render.timeline(midi: Types.Midi): Timeline end export type RenderOptions = { - sampleRate: number?, -- default 44100 - soundfont: any?, -- a SoundFont (music/sf2 decode, codecs/audio/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 + sampleRate: number?, + soundfont: any?, + gain: number?, + tail: number?, + maxVoices: number?, } --- 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") @@ -267,19 +259,16 @@ function Render.decoder(midi: Types.Midi, opts: RenderOptions?): (Types.Decoder? return (dec :: any) :: Types.Decoder, nil end --- tempoBytes(division, ticksPerSecond) -> the 3 data bytes of a tempo meta event making each tick last --- 1 / ticksPerSecond seconds at that division (for formats with a fixed tick rate: MUS, XMIDI, HMP / HMI) +-- tempo meta making each tick last 1 / ticksPerSecond s at that division (MUS, XMIDI, HMP / HMI) function Render.tempoBytes(division: number, ticksPerSecond: number): { number } local us = math.clamp(math.floor(division * 1e6 / ticksPerSecond + 0.5), 1, 0xFFFFFF) return { us // 65536, (us // 256) % 256, us % 256 } end --- ------------------------------------------------------------------------------------------------ durations export type PendingOff = { tick: number, onTick: number, ev: Types.MidiEvent } --- merge(events, offs) -> one tick-ordered event list: for formats that store a duration with each note (XMIDI, HMI). --- events are in file order (ticks never decrease); offs are the generated note-offs. At equal ticks an off whose note --- started earlier goes before the file's events, an off of a zero-length note after them. +-- XMIDI / HMI note durations: at equal ticks an off whose note started earlier goes before the file's events, +-- an off of a zero-length note after them function Render.merge(events: { Types.MidiEvent }, offs: { PendingOff }): { Types.MidiEvent } for i, o in offs do (o :: any).seq = i @@ -305,11 +294,9 @@ function Render.merge(events: { Types.MidiEvent }, offs: { PendingOff }): { Type return out end --- ------------------------------------------------------------------------------------------------ attach local function render(self: Types.Midi, opts: RenderOptions?): Types.Decoder local dec, err = Render.decoder(self, opts) if not dec then - -- the Types contract returns a Decoder; a failed render is an empty one (Midi.render returns the Err) local empty: any = { sampleRate = 44100, channels = 2, frames = 0, duration = 0, bitrate = 0, tags = {}, err = err, read = function(_self: any, _n: number, out: buffer?): (buffer, number) @@ -325,7 +312,6 @@ local function render(self: Types.Midi, opts: RenderOptions?): Types.Decoder return dec end --- summarize(midi): meta.tempos / timeSignatures / keySignatures / length from the events function Render.summarize(midi: Types.Midi) local tempos, sigs, keys = {}, {}, {} local map = Render.tempoMap(midi) @@ -349,7 +335,6 @@ function Render.summarize(midi: Types.Midi) midi.meta.length = Render.length(midi) end --- attach(midi, source): what every MIDI-like decoder does last: the meta summary, meta.source and the render method function Render.attach(midi: Types.Midi, source: { [string]: any }) Render.summarize(midi) midi.meta.source = source diff --git a/src/Rosetta/codecs/audio/Mpa/Analysis.luau b/src/Rosetta/codecs/audio/Mpa/Analysis.luau index c73ba30..19adca8 100644 --- a/src/Rosetta/codecs/audio/Mpa/Analysis.luau +++ b/src/Rosetta/codecs/audio/Mpa/Analysis.luau @@ -1,13 +1,8 @@ --!strict --!native --!optimize 2 --- codecs/audio/Mpa/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 --- codecs/audio/Mpa/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] +-- codecs/audio/Mpa/Analysis: the polyphase analysis filterbank (ISO/IEC 11172-3 C.1.3, figure C.4): window C = D / 32, +-- matrixing M[k][i] = cos((2k + 1)(i - 16) pi / 64). local E = require("@rosetta/codecs/audio/Mpa/EncTables") local Analysis = {} @@ -16,7 +11,7 @@ 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] +local M = table.create(32 * 64, 0) 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) @@ -29,7 +24,6 @@ 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 diff --git a/src/Rosetta/codecs/audio/Mpa/Core.luau b/src/Rosetta/codecs/audio/Mpa/Core.luau index 385c40a..795f166 100644 --- a/src/Rosetta/codecs/audio/Mpa/Core.luau +++ b/src/Rosetta/codecs/audio/Mpa/Core.luau @@ -1,11 +1,8 @@ --!strict --!native --!optimize 2 --- codecs/audio/Mpa/Core: a line-by-line port of minimp3's mp3dec_decode_frame (https://github.com/lieff/minimp3, --- CC0) for layers I, II and III, using its scalar (non-SIMD) code paths and float output. --- State that must survive between frames (MDCT overlap, polyphase history, bit reservoir) lives in a per-stream --- state from Core.newState(); everything else is module scratch, so decoding is synchronous and allocation free. --- All buffer accesses stay in bounds by construction (padded scratch, bounded loops): native code must not throw. +-- codecs/audio/Mpa/Core: a line-by-line port of minimp3's mp3dec_decode_frame (https://github.com/lieff/minimp3, CC0) +-- for layers I, II and III, using its scalar (non-SIMD) code paths and float output. local T = require("@rosetta/codecs/audio/Mpa/Tables") local band, bor, lshift, rshift, arshift, bswap = bit32.band, bit32.bor, bit32.lshift, bit32.rshift, bit32.arshift, bit32.byteswap @@ -18,7 +15,6 @@ local MAX_BITRESERVOIR_BYTES = 511 local MAX_FRAME = 2304 + 8 -- largest frame (free format) incl. padding, rounded up local SCALE = 1 / 32768 ----------------------------------------------------------------------------------------------------------------- -- tables (floats rounded to f32 like the C arrays) local F32 = bcreate(4) @@ -111,19 +107,16 @@ for i = 0, 239 do WINT[i + 1] = f32(T.g_win[i]) end ----------------------------------------------------------------------------------------------------------------- --- scratch - local FRAME = bcreate(MAX_FRAME + 64) -- the current frame, copied (bit reader reads up to 4 bytes ahead) -local MAIN = bcreate(MAX_BITRESERVOIR_BYTES + MAX_FRAME + 4096) -- layer III main data (reservoir + frame) +local MAIN = bcreate(MAX_BITRESERVOIR_BYTES + MAX_FRAME + 4096) local GRBUF = bcreate(576 * 2 * 4) -- [ch][576] f32 -local SCF = bcreate(40 * 4) -- layer III scalefactor gains, f32 -local SYN = bcreate((18 + 15) * 64 * 4) -- synthesis lines / reorder scratch, f32 +local SCF = bcreate(40 * 4) +local SYN = bcreate((18 + 15) * 64 * 4) local IST = bcreate(2 * 39 + 8) -- ist_pos[2][39], u8 -local ISCF = bcreate(48) -- integer scalefactors, u8 +local ISCF = bcreate(48) local TMP = bcreate(18 * 4 * 2) -- imdct scratch: co[9] si[9] / short block copy[18] local L12SCF = bcreate(192 * 4) -- L12 scalefactors [band*2 + ch][3], f32 -local BA = bcreate(64) -- L12 bit allocation +local BA = bcreate(64) local SCFCOD = bcreate(64) -- layer III side info, per granule x channel (0..3) @@ -140,19 +133,16 @@ end local MAXB = { [0] = -1, -1, -1 } local SCFSIZE = { [0] = 0, 0, 0, 0 } --- per-stream state of the frame being decoded (set by decodeFrame) local OVL: buffer = bcreate(4) -- mdct_overlap[2][9*32] local QMF: buffer = bcreate(4) -- qmf_state[15*2*32] local PCM: buffer = bcreate(4) ----------------------------------------------------------------------------------------------------------------- --- bit reader (bs_t): position and limit in bits +-- bit reader (bs_t) local bsBuf: buffer = FRAME local bsPos = 0 local bsLimit = 0 --- n <= 25 local function getBits(n: number): number local pos = bsPos bsPos = pos + n @@ -163,7 +153,6 @@ local function getBits(n: number): number return rshift(w, 32 - n) end ----------------------------------------------------------------------------------------------------------------- -- layer III side info (L3_read_side_info): fills GR_*, returns main_data_begin or -1 local function readSideInfo(h1: number, h2: number, h3: number): number @@ -254,9 +243,6 @@ local function readSideInfo(h1: number, h2: number, h3: number): number return mdb end ----------------------------------------------------------------------------------------------------------------- --- layer III scalefactors - local function ldexpQ2(y: number, e: number): number repeat local s = if e < 120 then e else 120 @@ -346,7 +332,6 @@ local function decodeScalefactors(h1: number, h3: number, istOff: number, gr: nu end end ----------------------------------------------------------------------------------------------------------------- -- layer III Huffman decoding (L3_huffman) into GRBUF[dst ..], reads MAIN through a 32-bit cache local function huffman(dst: number, gr: number, limit: number) @@ -495,9 +480,6 @@ local function huffman(dst: number, gr: number, limit: number) bsPos = limit end ----------------------------------------------------------------------------------------------------------------- --- layer III stereo - -- L3_midside_stereo on GRBUF[left .. left + n) and its right channel at + 576 local function midside(left: number, n: number) for i = left * 4, (left + n - 1) * 4, 4 do @@ -576,9 +558,6 @@ local function intensityStereo(h1: number, h3: number, gr: number) end end ----------------------------------------------------------------------------------------------------------------- --- layer III reorder, antialias, IMDCT - local function reorder(g: number, sfb: number) local src, dst = g, 0 while true do @@ -842,7 +821,7 @@ local function dctII(g: number, n: number) t2_7 = d + c t3_7 = (d - c) * 5.10114861 end - do -- row 0 + do local x0, x1, x2, x3, x4, x5, x6, x7 = t0_0, t0_1, t0_2, t0_3, t0_4, t0_5, t0_6, t0_7 local xt = x0 - x7 x0 += x7 @@ -874,7 +853,7 @@ local function dctII(g: number, n: number) t0_6 = (x4 - x3) * 1.30656302 t0_7 = (xt - x7) * 2.56291556 end - do -- row 1 + do local x0, x1, x2, x3, x4, x5, x6, x7 = t1_0, t1_1, t1_2, t1_3, t1_4, t1_5, t1_6, t1_7 local xt = x0 - x7 x0 += x7 @@ -906,7 +885,7 @@ local function dctII(g: number, n: number) t1_6 = (x4 - x3) * 1.30656302 t1_7 = (xt - x7) * 2.56291556 end - do -- row 2 + do local x0, x1, x2, x3, x4, x5, x6, x7 = t2_0, t2_1, t2_2, t2_3, t2_4, t2_5, t2_6, t2_7 local xt = x0 - x7 x0 += x7 @@ -938,7 +917,7 @@ local function dctII(g: number, n: number) t2_6 = (x4 - x3) * 1.30656302 t2_7 = (xt - x7) * 2.56291556 end - do -- row 3 + do local x0, x1, x2, x3, x4, x5, x6, x7 = t3_0, t3_1, t3_2, t3_3, t3_4, t3_5, t3_6, t3_7 local xt = x0 - x7 x0 += x7 @@ -1101,7 +1080,6 @@ local function l3Decode(h1: number, h2: number, h3: number, grBase: number, nch: end end ----------------------------------------------------------------------------------------------------------------- -- polyphase synthesis (mp3d_DCT_II, mp3d_synth, mp3d_synth_granule) @@ -1129,8 +1107,7 @@ local function synthPair(dst: number, nch: number, z: number) wf(PCM, (dst + 16 * nch) * 4, a * SCALE) end --- mp3d_synth: two time slots of 32 subbands -> 64 samples per channel. xl = GRBUF float index of the left --- channel's slot, dstl = PCM float index, lins = SYN float index +-- mp3d_synth: two time slots of 32 subbands -> 64 samples per channel local function synth(xl: number, dstl: number, nch: number, lins: number) local xr = xl + 576 * (nch - 1) local dstr = dstl + (nch - 1) @@ -1256,9 +1233,6 @@ local function synthGranule(nbands: number, nch: number, pcm: number) end end ----------------------------------------------------------------------------------------------------------------- --- layers I and II - local ALLOC_L1 = { 76, 4, 32 } local ALLOC_L2M2 = { 60, 4, 4, 44, 3, 7, 44, 2, 19 } local ALLOC_L2M1 = { 0, 4, 3, 16, 4, 8, 32, 3, 12, 40, 2, 7 } @@ -1371,9 +1345,6 @@ local function l12ApplyScf(scfOff: number) end end ----------------------------------------------------------------------------------------------------------------- --- API - local Core = {} Core.MAX_FRAME = MAX_FRAME @@ -1406,7 +1377,6 @@ end Core.lastChannels = 0 --- pcm holds n mono samples: spread them to n interleaved stereo pairs (in place) function Core.upmix(pcm: buffer, n: number) if buffer.len(pcm) < n * 8 then return @@ -1418,9 +1388,6 @@ function Core.upmix(pcm: buffer, n: number) end end --- Decodes the frame b[off, off + size) (a whole frame found by the index, header included) into pcm --- (interleaved f32, frame samples x channels) and returns the samples per channel (0 = no output: an --- unfilled bit reservoir, or corrupt data). Core.lastChannels = the frame's channel count. function Core.decodeFrame(st: State, b: buffer, off: number, size: number, pcm: buffer): number if size < 4 or size > MAX_FRAME or off < 0 or off + size > buffer.len(b) then st.needReset = true @@ -1485,7 +1452,6 @@ function Core.decodeFrame(st: State, b: buffer, off: number, size: number, pcm: bsBuf = FRAME return if success then spf else 0 end - -- layers I / II local kbps = 2 * HALFRATE[(if band(h1, 8) ~= 0 then 45 else 0) + (band(rshift(h1, 1), 3) - 1) * 15 + rshift(h2, 4)] l12ReadScaleInfo(h1, h2, h3, kbps) bfill(GRBUF, 0, 0) @@ -1509,8 +1475,6 @@ function Core.decodeFrame(st: State, b: buffer, off: number, size: number, pcm: return spf end --- Layer III side info of the frame b[off, off + size): main_data_begin (-1 = corrupt), the sum of its --- part2_3 lengths in bits, and the main data bytes in the frame. Used by the stream index. function Core.probeL3(b: buffer, off: number, size: number): (number, number, number) local n = min(size, 64) if size < 4 or off + n > buffer.len(b) then @@ -1534,7 +1498,7 @@ function Core.probeL3(b: buffer, off: number, size: number): (number, number, nu return mdb, sum, (bsLimit - bsPos) // 8 end --- Layer I / II: false when the frame b[off, off + size) needs more bits than it has (minimp3 then drops it). +-- Layer I / II: minimp3 drops a frame that needs more bits than it has function Core.probeL12(b: buffer, off: number, size: number): boolean if size < 4 or size > MAX_FRAME or off + size > buffer.len(b) then return false diff --git a/src/Rosetta/codecs/audio/Mpa/EncTables.luau b/src/Rosetta/codecs/audio/Mpa/EncTables.luau index 02d6461..f1bf09f 100644 --- a/src/Rosetta/codecs/audio/Mpa/EncTables.luau +++ b/src/Rosetta/codecs/audio/Mpa/EncTables.luau @@ -1,9 +1,7 @@ --!strict --- codecs/audio/Mpa/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). +-- codecs/audio/Mpa/EncTables: the synthesis window D and the layer III Huffman trees of ISO/IEC 11172-3, from PDMP3 +-- (public domain / unlicense, Krister Lagerstrom and contributors: licenses/PDMP3-UNLICENSE.txt). Tree entries with a +-- high byte are nodes (high byte: left offset, low byte: right offset), else leaves (x << 4 | y; count1: 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, diff --git a/src/Rosetta/codecs/audio/Mpa/Encode2.luau b/src/Rosetta/codecs/audio/Mpa/Encode2.luau index e369463..b9459e2 100644 --- a/src/Rosetta/codecs/audio/Mpa/Encode2.luau +++ b/src/Rosetta/codecs/audio/Mpa/Encode2.luau @@ -1,13 +1,9 @@ --!strict --!native --!optimize 2 --- codecs/audio/Mpa/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 (codecs/audio/Mpa/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. +-- codecs/audio/Mpa/Encode2: an MPEG audio layer II CBR encoder, written from ISO/IEC 11172-3 (2.4.2.3, C.1.5.2). +-- Bit allocation tables in minimp3's compact form (CC0, licenses/minimp3-CC0.txt); greedy allocation by noise (signal +-- level minus the quantizer's SNR), no psychoacoustic model. local Bits = require("@rosetta/core/Bits") local T = require("@rosetta/codecs/audio/Mpa/Tables") local Analysis = require("@rosetta/codecs/audio/Mpa/Analysis") @@ -35,7 +31,6 @@ local function levels(ba: number): number 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 @@ -100,7 +95,6 @@ export type Source = { } 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] @@ -117,7 +111,6 @@ function Encode2.encode(src: Source, opts: Options): (buffer?, string?) 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 @@ -168,8 +161,8 @@ function Encode2.encode(src: Source, opts: Options): (buffer?, string?) -- 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 scf = { table.create(32 * 3, 0), table.create(32 * 3, 0) } + local bal = { table.create(32, 0), table.create(32, 0) } local slot = 144000 * kbps local rest = 0 local tmp: buffer? = nil @@ -249,7 +242,6 @@ function Encode2.encode(src: Source, opts: Options): (buffer?, string?) end end end - -- the frame size and the bits left for scalefactors and samples local frameBytes = slot // rate rest += slot % rate local padding = 0 @@ -262,8 +254,7 @@ function Encode2.encode(src: Source, opts: Options): (buffer?, string?) 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 + local level = { table.create(nbands, 0), table.create(nbands, 0) } for c = 1, nch do local sc = scf[c] for b = 1, nbands do @@ -298,7 +289,6 @@ function Encode2.encode(src: Source, opts: Options): (buffer?, string?) 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) @@ -318,7 +308,6 @@ function Encode2.encode(src: Source, opts: Options): (buffer?, string?) 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] diff --git a/src/Rosetta/codecs/audio/Mpa/Encode3.luau b/src/Rosetta/codecs/audio/Mpa/Encode3.luau index f8112bd..ef8dee4 100644 --- a/src/Rosetta/codecs/audio/Mpa/Encode3.luau +++ b/src/Rosetta/codecs/audio/Mpa/Encode3.luau @@ -1,13 +1,9 @@ --!strict --!native --!optimize 2 --- codecs/audio/Mpa/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 (codecs/audio/Mpa/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 (codecs/audio/Mpa/EncTables, from PDMP3, public domain). Never throws. +-- codecs/audio/Mpa/Encode3: an MPEG audio layer III CBR encoder in the spirit of shine (long blocks, global-gain rate +-- control, no bit reservoir). Written from ISO/IEC 11172-3 / 13818-3 (no shine / LAME code); Huffman codes derived +-- from the standard's decoder trees (codecs/audio/Mpa/EncTables, from PDMP3, public domain). local Bits = require("@rosetta/core/Bits") local E = require("@rosetta/codecs/audio/Mpa/EncTables") local T = require("@rosetta/codecs/audio/Mpa/Tables") @@ -23,7 +19,6 @@ 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 } } = {} @@ -75,7 +70,6 @@ for t = 1, 33 do 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 = {} @@ -87,13 +81,11 @@ for m = 0, 15 do SMALL[m] = list end --- ------------------------------------------------------------------------------------------------ bit writer type W = Bits.RawWriter local put = Bits.msbPut 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 }, @@ -118,7 +110,6 @@ for k = 0, 17 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 @@ -126,16 +117,15 @@ for i = 1, 8 do 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 + bigValues: number, + count1: number, + tables: { number }, region0: number, region1: number, c1table: number, -- 0 = A (table 32), 1 = B (33) - addr1: number, -- coefficient index where region 1 starts + addr1: number, addr2: number, } @@ -143,7 +133,6 @@ 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 @@ -173,7 +162,6 @@ local function pairBits(ix: { number }, a: number, b: number, t: number): number 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 @@ -214,7 +202,6 @@ local function chooseTable(ix: { number }, a: number, b: number): (number, numbe 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 @@ -228,7 +215,6 @@ local function plan(ix: { number }, bounds: { number }, p: Plan) 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 @@ -309,9 +295,8 @@ local function writeHuffman(w: W, ix: { number }, sign: { boolean }, p: Plan) end end --- ------------------------------------------------------------------------------------------------ quantization type Unit = { - xr: { number }, -- 576 MDCT coefficients + xr: { number }, xa: { number }, -- |xr|^(3/4) ix: { number }, sign: { boolean }, @@ -344,7 +329,6 @@ local function quantize(u: Unit, g: number): boolean 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 @@ -366,7 +350,6 @@ local function rateLoop(u: Unit, budget: number, bounds: { number }) 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 @@ -397,7 +380,6 @@ local function rateLoop(u: Unit, budget: number, bounds: { number }) u.gain = best end --- ------------------------------------------------------------------------------------------------ encoder export type Source = { sampleRate: number, channels: number, @@ -406,12 +388,11 @@ export type Source = { 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) + bitrate: number, + mode: string, + prefix: buffer?, } --- encode(src, opts) -> buffer | nil, message function Encode3.encode(src: Source, opts: Options): (buffer?, string?) local rate = src.sampleRate local info = RATES[rate] @@ -433,7 +414,6 @@ function Encode3.encode(src: Source, opts: Options): (buffer?, string?) 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 @@ -453,7 +433,7 @@ function Encode3.encode(src: Source, opts: Options): (buffer?, string?) 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 prev = { table.create(576, 0), table.create(576, 0) } local cur = { table.create(576, 0), table.create(576, 0) } local units = {} for g = 1, 2 do @@ -469,7 +449,6 @@ function Encode3.encode(src: Source, opts: Options): (buffer?, string?) 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 @@ -513,7 +492,6 @@ function Encode3.encode(src: Source, opts: Options): (buffer?, string?) 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] @@ -564,7 +542,6 @@ function Encode3.encode(src: Source, opts: Options): (buffer?, string?) end end end - -- the frame size local frameBytes = slotNum // rate rest += slotNum % rate local padding = 0 @@ -586,7 +563,6 @@ function Encode3.encode(src: Source, opts: Options): (buffer?, string?) 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) @@ -606,7 +582,6 @@ function Encode3.encode(src: Source, opts: Options): (buffer?, string?) 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) @@ -638,7 +613,6 @@ function Encode3.encode(src: Source, opts: Options): (buffer?, string?) put(w, p.c1table, 1) end end - -- main data for g = 1, granules do for c = 1, nch do local u = units[g][c] diff --git a/src/Rosetta/codecs/audio/Mpa/Header.luau b/src/Rosetta/codecs/audio/Mpa/Header.luau index f30cf12..a867c89 100644 --- a/src/Rosetta/codecs/audio/Mpa/Header.luau +++ b/src/Rosetta/codecs/audio/Mpa/Header.luau @@ -1,9 +1,8 @@ --!strict --!native --!optimize 2 --- codecs/audio/Mpa/Header: MPEG audio frame headers (minimp3's hdr_* macros and functions), frame sync (mp3d_find_frame / --- mp3d_match_frame). Every function reads 4 header bytes at a byte offset of a buffer; callers keep offset + 4 --- inside the buffer. Never throws. +-- codecs/audio/Mpa/Header: MPEG audio frame headers and frame sync, after minimp3's hdr_* and mp3d_find_frame / +-- mp3d_match_frame (CC0, licenses/minimp3-CC0.txt). local T = require("@rosetta/codecs/audio/Mpa/Tables") local band, bxor, rshift = bit32.band, bit32.bxor, bit32.rshift @@ -30,7 +29,7 @@ function H.valid(b: buffer, o: number): boolean end local valid = H.valid --- hdr_compare: h2 is a valid header of the same version / layer / sample rate / free-format-ness as h1 +-- hdr_compare function H.compare(b: buffer, o1: number, o2: number): boolean if not valid(b, o2) then return false @@ -73,7 +72,7 @@ function H.frameSamples(h1: number): number end local frameSamples = H.frameSamples --- hdr_frame_bytes (without padding); free format = 0 -> freeSize +-- hdr_frame_bytes (without padding) function H.frameBytes(b: buffer, o: number, freeSize: number): number local h1, h2 = ru8(b, o + 1), ru8(b, o + 2) local hz = sampleRate(h1, h2) @@ -108,7 +107,7 @@ local function matchFrame(b: buffer, o: number, n: number, fb: number): boolean return true end --- mp3d_find_frame over b[base, base + n): returns (skip, frame bytes incl. padding or 0, free format size) +-- mp3d_find_frame function H.findFrame(b: buffer, base: number, n: number, ffb: number): (number, number, number) for i = 0, n - 5 do local o = base + i diff --git a/src/Rosetta/codecs/audio/Mpa/init.luau b/src/Rosetta/codecs/audio/Mpa/init.luau index b50e118..4b84bb4 100644 --- a/src/Rosetta/codecs/audio/Mpa/init.luau +++ b/src/Rosetta/codecs/audio/Mpa/init.luau @@ -1,8 +1,7 @@ --!strict --- codecs/audio/Mpa: MPEG audio layers I / II / III (ISO/IEC 11172-3, 13818-3, MPEG-2.5) without the file around it: --- frame headers (Header), the decoder core (Core: a port of minimp3 by lieff, CC0: licenses/minimp3-CC0.txt, --- absorbed from mp3-luau c755bbf) with its tables, and the layer III / layer II encoders (Encode3, Encode2: shine-style --- CBR, new) with their analysis tables. ID3 tags, Xing / LAME gapless info, the frame index and seeking are audio/mp3. +-- codecs/audio/Mpa: MPEG audio layers I / II / III (ISO/IEC 11172-3, 13818-3, MPEG-2.5) without the file around it. +-- Core is a port of minimp3 by lieff (CC0, licenses/minimp3-CC0.txt), absorbed from mp3-luau c755bbf; the layer II / III +-- encoders are new. local Mpa = { Header = require("@rosetta/codecs/audio/Mpa/Header"), Core = require("@rosetta/codecs/audio/Mpa/Core"), diff --git a/src/Rosetta/codecs/audio/Musepack/Decode.luau b/src/Rosetta/codecs/audio/Musepack/Decode.luau index fcd4009..f38be58 100644 --- a/src/Rosetta/codecs/audio/Musepack/Decode.luau +++ b/src/Rosetta/codecs/audio/Musepack/Decode.luau @@ -1,13 +1,9 @@ --!strict --!native --!optimize 2 --- codecs/audio/Musepack/Decode: one Musepack SV7 / SV8 frame (1152 samples per channel): the bitstream (band --- resolutions, scalefactor indices, quantised subband samples, with SV8's canonical Huffman / enumerative codes), --- requantisation (M/S or L/R) and the 32-band polyphase synthesis. A line-by-line port of libmpcdec's mpc_decoder.c, --- requant.c and synth_filter.c (musepack_src_r475, BSD-3-Clause, (c) The Musepack Development Team, --- licenses/libmpcdec-BSD.txt) in double precision float. The bit reader is module state (decoding is synchronous) over --- a buffer the caller pads by at least PAD bytes past `limit`: the band loops stop as soon as the position passes the --- limit, so every read stays inside the buffer. No error / assert: failures return nil, "message". +-- codecs/audio/Musepack/Decode: one Musepack SV7 / SV8 frame (1152 samples per channel). +-- A line-by-line port of libmpcdec's mpc_decoder.c, requant.c and synth_filter.c (musepack_src_r475, BSD-3-Clause, (c) The +-- Musepack Development Team, licenses/libmpcdec-BSD.txt). The caller pads the buffer by PAD bytes past `limit`. local T = require("@rosetta/codecs/audio/Musepack/Tables") local readu32, bswap, extract, band, bor, rshift, lshift, bnot, bxor = @@ -19,7 +15,6 @@ Decode.PAD = 8192 Decode.DELAY = 481 -- MPC_DECODER_SYNTH_DELAY Decode.FRAME = 1152 --- ------------------------------------------------------------------------------------------------ tables local L = T.lut local HDR, SCFI7, DSCF7 = L(T.HuffHdr), L(T.HuffSCFI), L(T.HuffDSCF) local Q7: { { T.Lut } } = { @@ -83,9 +78,8 @@ for i, v in T.DI do DW[i] = f32(v / 65536) end --- ------------------------------------------------------------------------------------------------ bit reader local B: buffer = buffer.create(0) -local P = 0 -- bit position +local P = 0 local function bits(n: number): number if n <= 0 then @@ -106,7 +100,6 @@ local function peek16(): number return extract(w, 16 - band(P, 7), 16) end --- a table-driven Huffman symbol (plain or canonical) local function huff(t: T.Lut): number local code = peek16() local k = rshift(code, 8) + 1 @@ -176,7 +169,6 @@ for i = 0, 255 do PARITY[i + 1] = p end --- ------------------------------------------------------------------------------------------------ synthesis -- mpc_compute_new_V: 32 subband samples Y[y .. y + 31] -> 64 V values at V[o .. o + 63] (the ISO 11172-3 matrixing -- through Byeong Gi Lee's fast DCT) local function newV(Y: { number }, y: number, V: { number }, o: number) @@ -392,26 +384,25 @@ local function newV(Y: { number }, y: number, V: { number }, o: number) V[o + 96 - i] = V[o + i] end end --- ------------------------------------------------------------------------------------------------ state export type State = { - version: number, -- 7 | 8 - maxBand: number, -- the highest band index (0 .. 31) + version: number, + maxBand: number, ms: boolean, channels: number, - resL: { number }, -- [band + 1] + resL: { number }, resR: { number }, - scfL: { number }, -- [band * 3 + m + 1] + scfL: { number }, scfR: { number }, scfiL: { number }, scfiR: { number }, dscfL: { boolean }, dscfR: { boolean }, msf: { boolean }, - qL: { number }, -- [band * 36 + k + 1] + qL: { number }, qR: { number }, - yL: { number }, -- [n * 32 + band + 1], n = 0 .. 35 + yL: { number }, yR: { number }, - vL: { number }, -- synthesis history, 2304 + 960 + vL: { number }, vR: { number }, r1: number, r2: number, @@ -446,9 +437,7 @@ function Decode.state(version: number, maxBand: number, ms: boolean, channels: n return st end --- reset(st, scf): forget the history (before a seek); scf = the scalefactor indices to assume (libmpcdec: 0 at the --- start of the stream, 0x01010101 in the middle of an SV7 stream). The noise generator restarts too, so a seek --- decodes like libmpcdec seeking in a freshly opened stream. +-- libmpcdec assumes scf 0 at the stream start, 0x01010101 mid-SV7; the noise generator restarts, as in a fresh stream function Decode.reset(st: State, scf: number) for i = 1, 99 do st.scfL[i] = scf @@ -479,8 +468,7 @@ local function noise(st: State, q: { number }, o: number) st.r1, st.r2 = r1, r2 end --- ------------------------------------------------------------------------------------------------ SV7 --- mpc_decoder_read_bitstream_sv7 -> true | nil, message +-- mpc_decoder_read_bitstream_sv7 local function readSv7(st: State, limit: number): (boolean?, string?) local resL, resR, msf = st.resL, st.resR, st.msf local maxUsed = 0 @@ -607,7 +595,6 @@ local function readSv7(st: State, limit: number): (boolean?, string?) return true, nil end --- ------------------------------------------------------------------------------------------------ SV8 local function readSv8(st: State, key: boolean, limit: number): (boolean?, string?) local resL, resR, msf = st.resL, st.resR, st.msf local maxBand = st.maxBand @@ -802,7 +789,6 @@ local function readSv8(st: State, key: boolean, limit: number): (boolean?, strin return true, nil end --- ------------------------------------------------------------------------------------------------ requantisation local function requant(st: State) local resL, resR, msf = st.resL, st.resR, st.msf local scfL, scfR, qL, qR, yL, yR = st.scfL, st.scfR, st.qL, st.qR, st.yL, st.yR @@ -833,7 +819,7 @@ local function requant(st: State) end --- mpc_synthese_filter_float for one channel: 36 x 32 subband samples -> 1152 samples at out[base + i * step] +-- mpc_synthese_filter_float local function synth(V: { number }, Y: { number }, out: { number }, base: number, step: number) table.move(V, 1, 960, 2305) local o = 2304 + 1 @@ -854,10 +840,6 @@ local function synth(V: { number }, Y: { number }, out: { number }, base: number end end --- ------------------------------------------------------------------------------------------------ frames --- frame(st, buf, bitPos, limitBits, key, out, base) -> the bit position after the frame | nil, message: decodes one --- frame from buf (padded by PAD bytes past limitBits / 8) into out[base ..] (1152 * channels interleaved floats). --- key: an SV8 key frame (the first of a block). bitPos < 0 decodes a silent frame (the synthesis tail). function Decode.frame(st: State, buf: buffer, bitPos: number, limitBits: number, key: boolean, out: { number }, base: number): (number?, string?) if bitPos >= 0 then if rshift(limitBits, 3) + Decode.PAD > buffer.len(buf) or bitPos > limitBits then @@ -889,8 +871,6 @@ function Decode.frame(st: State, buf: buffer, bitPos: number, limitBits: number, return if bitPos >= 0 then pos else bitPos, nil end --- bitsAt(buf, bitPos, n) -> n (1 .. 24) bits at bitPos (frame headers: the SV7 frame size); the caller keeps --- bitPos / 8 + 4 inside buf function Decode.bitsAt(buf: buffer, bitPos: number, n: number): number local w = bswap(readu32(buf, rshift(bitPos, 3))) return extract(w, 32 - band(bitPos, 7) - n, n) diff --git a/src/Rosetta/codecs/audio/Musepack/Tables.luau b/src/Rosetta/codecs/audio/Musepack/Tables.luau index 448ea85..821b6a3 100644 --- a/src/Rosetta/codecs/audio/Musepack/Tables.luau +++ b/src/Rosetta/codecs/audio/Musepack/Tables.luau @@ -1,10 +1,8 @@ --!strict --- codecs/audio/Musepack/Tables: the Musepack SV7 / SV8 Huffman tables, the synthesis window and the requantisation --- constants. Ported from libmpcdec (musepack_src_r475: huffman.c, synth_filter.c, requant.c, mpc_bits_reader.c; --- BSD-3-Clause, (c) The Musepack Development Team, licenses/libmpcdec-BSD.txt); the tables are transcribed by script. --- Each Huffman table is a flat { code, length, value, ... } list sorted by descending left-aligned 16-bit code; --- canonical (SV8) tables map value - (code >> (16 - length)) through their symbol list. lut(table, sym?) builds the --- 8-bit first-level lookup the decoder uses. +-- codecs/audio/Musepack/Tables: the Musepack SV7 / SV8 Huffman tables, synthesis window and requantisation constants. +-- Ported from libmpcdec (musepack_src_r475: huffman.c, synth_filter.c, requant.c, mpc_bits_reader.c; BSD-3-Clause, +-- (c) The Musepack Development Team, licenses/libmpcdec-BSD.txt). Huffman tables: flat { code, length, value, ... } +-- sorted by descending left-aligned 16-bit code; canonical (SV8) tables map value - (code >> (16 - length)). local T = {} T.HuffHdr = { @@ -332,15 +330,14 @@ do end export type Lut = { - len: { number }, -- 256 entries: code length when the 8-bit prefix decides the symbol, else 0 - val: { number }, -- the symbol, or the 1-based table entry to scan from + len: { number }, + val: { number }, codes: { number }, lens: { number }, vals: { number }, sym: { number }?, } --- lut(table, sym?) -> Lut function T.lut(tab: { number }, sym: { number }?): Lut local codes, lens, vals = {}, {}, {} for i = 1, #tab, 3 do diff --git a/src/Rosetta/codecs/audio/Musepack/init.luau b/src/Rosetta/codecs/audio/Musepack/init.luau index ae64a40..5093f92 100644 --- a/src/Rosetta/codecs/audio/Musepack/init.luau +++ b/src/Rosetta/codecs/audio/Musepack/init.luau @@ -1,17 +1,7 @@ --!strict --- codecs/audio/Musepack: Musepack (MPC) stream versions 7 and 8: the stream headers (SV7's 32-bit word-swapped --- header, SV8's key / size packets: SH with its CRC, RG, EI, AP, SE), the frame / audio packet index, and the --- decoder (codecs/audio/Musepack/Decode: subband bitstream, requantisation, polyphase synthesis). A port of libmpcdec --- (musepack_src_r475: mpc_demux.c, streaminfo.c, mpc_decoder.c; BSD-3-Clause, (c) The Musepack Development Team, --- licenses/libmpcdec-BSD.txt), gapless like libmpcdec (the 481-sample synthesis delay and SV8's leading silence are --- dropped, the length is exact). Not supported: SV4 - SV6 (UNSUPPORTED), the SV8 seek table (the packets are indexed --- instead), chapters. --- --- local s, err = Musepack.open(buf, start, limit) -- start: the "MP+" / "MPCK" magic (after an ID3v2 tag) --- -- s: { version, sampleRate, channels, frames, maxBand, ms, profile, encoder, gapless, gain, ... } plus the --- -- codecs/audio/Stream spec: count, start(i), decode(i), pcm(), reset(), skip, stop, preroll --- --- Never throws: bad data returns nil, Err. +-- codecs/audio/Musepack: Musepack (MPC) stream versions 7 and 8. +-- A port of libmpcdec (musepack_src_r475: mpc_demux.c, streaminfo.c, mpc_decoder.c; BSD-3-Clause, (c) The Musepack +-- Development Team, licenses/libmpcdec-BSD.txt), gapless like libmpcdec. SV4 - SV6 are UNSUPPORTED. local Err = require("@rosetta/core/Err") local Crc32 = require("@rosetta/core/Crc32") local Decode = require("@rosetta/codecs/audio/Musepack/Decode") @@ -26,7 +16,7 @@ export type Stream = { version: number, sampleRate: number, channels: number, - frames: number, -- output sample frames (gapless) + frames: number, maxBand: number, ms: boolean, profile: number, -- SV7: the profile index (7 telephone .. 13 braindead); SV8: the quality (0 .. 15.875) @@ -35,8 +25,7 @@ export type Stream = { pns: boolean?, gain: { titleGain: number, titlePeak: number, albumGain: number, albumPeak: number }?, blockFrames: number, -- frames per packet (SV7: 1; SV8: 2^block_pwr) - bytes: number, -- the stream's size in bytes (for the bitrate) - -- the codecs/audio/Stream spec + bytes: number, count: number, start: (i: number) -> number, decode: (i: number) -> (number?, Err.Err?), @@ -47,7 +36,6 @@ export type Stream = { preroll: number, } --- ------------------------------------------------------------------------------------------------ SV7 -- SV7 reads the stream as little-endian 32-bit words, most significant bit first: swap them into a padded copy local function swapped(buf: buffer, p: number, limit: number): buffer local n = limit - p @@ -106,7 +94,7 @@ local function sv7(buf: buffer, start: number, limit: number): (Stream?, Err.Err local size = at(s, pos, 20) local stop = pos + 20 + size + (if i == frames then 11 else 0) if stop > totalBits then - break -- a truncated last frame + break end offs[i], sizes[i] = pos + 20, size pos = stop @@ -170,7 +158,6 @@ local function sv7(buf: buffer, start: number, limit: number): (Stream?, Err.Err return out, nil end --- ------------------------------------------------------------------------------------------------ SV8 -- a packet size: 7 bits per byte, most significant first, bit 7 = more local function varint(buf: buffer, p: number, limit: number): (number, number) local v = 0 @@ -205,7 +192,7 @@ local function sv8(buf: buffer, start: number, limit: number): (Stream?, Err.Err local stop = p + size if stop > limit then if key == "AP" then - break -- a truncated last packet + break end return nil, Err.new(Err.TRUNCATED, key .. " packet", p) end @@ -329,8 +316,6 @@ local function sv8(buf: buffer, start: number, limit: number): (Stream?, Err.Err return out, nil end --- ------------------------------------------------------------------------------------------------ open --- magic(buf, p, limit) -> 7 | 8 | 0 (other: "MP+" with another version is 7's family, reported by open) function Musepack.magic(buf: buffer, p: number, limit: number): number if p + 4 > limit then return 0 @@ -345,7 +330,6 @@ function Musepack.magic(buf: buffer, p: number, limit: number): number return 0 end --- open(buf, start, limit) -> Stream | nil, Err function Musepack.open(buf: buffer, start: number, limit: number): (Stream?, Err.Err?) local v = Musepack.magic(buf, start, limit) if v == 8 then diff --git a/src/Rosetta/codecs/audio/Opus/Celt.luau b/src/Rosetta/codecs/audio/Opus/Celt.luau index 53e11cc..fbe62cc 100644 --- a/src/Rosetta/codecs/audio/Opus/Celt.luau +++ b/src/Rosetta/codecs/audio/Opus/Celt.luau @@ -1,12 +1,9 @@ --!strict --!native --!optimize 2 --- codecs/audio/Opus/Celt: CELT decoder (RFC 6716 section 4.3), a port of the libopus float decoder: celt/celt_decoder.c, bands.c, vq.c, --- cwrs.c, rate.c, quant_bands.c, laplace.c, celt.c (comb filter). Only the standard 48 kHz / 960-sample mode is --- needed by Opus. Packet loss concealment is the noise-based variant only (no pitch PLC). --- --- Arrays are Luau tables of numbers. All normalised-band data (X, Y, the folding memory `norm` and the scratch --- copies) lives in one table W, and the "pointers" of the C code are 0-based offsets into it. +-- codecs/audio/Opus/Celt: CELT decoder (RFC 6716 section 4.3), 48 kHz / 960-sample mode, noise-based PLC only. +-- A port of the libopus float decoder (celt_decoder.c, bands.c, vq.c, cwrs.c, rate.c, quant_bands.c, laplace.c, celt.c; +-- BSD, licenses/libopus-BSD.txt). The C code's band pointers are 0-based offsets into one table W. local RD = require("@rosetta/codecs/entropy/RangeCoder/Decoder") local Mdct = require("@rosetta/codecs/audio/Opus/Mdct") local T = require("@rosetta/codecs/audio/Opus/CeltTables") @@ -102,7 +99,6 @@ for n = 1, UK - 1 do end end --- shared workspace (decoding is not re-entrant) local NORM_BASE = 1920 local W = table.create(4096, 0) local TMP = table.create(256, 0) @@ -164,7 +160,6 @@ local function bitexactLog2tan(isin: number, icos: number): number return (ls - lc) * 2048 + fracMul16(isin, fracMul16(isin, -2597) + 7932) - fracMul16(icos, fracMul16(icos, -2597) + 7932) end --- --------------------------------------------------------------------------------------------------------------- -- energy (quant_bands.c, laplace.c) local function laplaceDecode(dec: RD.Dec, fs: number, decay: number): number @@ -278,7 +273,6 @@ local function unquantEnergyFinalise(st: any, start: number, endb: number, fineQ end end --- --------------------------------------------------------------------------------------------------------------- -- bit allocation (rate.c) local function bits2pulses(bandI: number, LM: number, bits: number): number @@ -315,7 +309,7 @@ local function getPulses(i: number): number return lshift(8 + band(i, 7), rshift(i, 3) - 1) end --- clt_compute_allocation + interp_bits2pulses (decoder side). Returns codedBands, balance, intensity, dualStereo. +-- clt_compute_allocation + interp_bits2pulses (decoder side) local function computeAllocation(start: number, endb: number, offsets: { number }, cap: { number }, allocTrim: number, total: number, pulses: { number }, ebits: { number }, finePriority: { number }, C: number, LM: number, ec: RD.Dec) total = imax(total, 0) @@ -544,7 +538,6 @@ local function computeAllocation(start: number, endb: number, offsets: { number return codedBands, balance, intensity, dualStereo end --- --------------------------------------------------------------------------------------------------------------- -- PVQ (cwrs.c, vq.c) local function cwrsi(n: number, k: number, i: number, iy: { number }): number @@ -605,7 +598,6 @@ local function cwrsi(n: number, k: number, i: number, iy: { number }): number end n -= 1 end - -- n == 2 p = 2 * k + 1 local neg = i >= p if neg then @@ -619,7 +611,6 @@ local function cwrsi(n: number, k: number, i: number, iy: { number }): number val = if neg then k - k0 else k0 - k iy[idx] = val yy += val * val - -- n == 1 val = if i ~= 0 then -k else k iy[idx + 1] = val yy += val * val @@ -717,7 +708,6 @@ local function algUnquant(X: number, N: number, K: number, spread: number, B: nu return mask end --- --------------------------------------------------------------------------------------------------------------- -- bands (bands.c) type Ctx = { @@ -819,7 +809,6 @@ local function computeQn(N: number, b: number, offset: number, pulseCap: number, return lshift(rshift(qn + 1, 1), 1) end --- returns b, fill, inv, imid, iside, delta, itheta, qalloc local function computeTheta(N: number, b: number, B: number, B0: number, LM: number, stereo: boolean, fill: number) local i = ctx.i local ec = ctx.ec @@ -1328,9 +1317,6 @@ local function antiCollapse(st: any, C: number, size: number, LM: number, start: end end --- --------------------------------------------------------------------------------------------------------------- --- synthesis - local function denormaliseBands(X: number, freq: { number }, logE: { number }, eoff: number, start: number, endb: number, M: number, silence: boolean) local N = M * SHORT_MDCT local bound = M * EB[endb + 1] @@ -1486,9 +1472,6 @@ local function deemphasis(st: any, CC: number, N: number, pcm: { number }, pbase end end --- --------------------------------------------------------------------------------------------------------------- --- decoder state - local function resetState(st: any) st.rng = 0 st.error = 0 @@ -1596,8 +1579,7 @@ local function decodeLost(st: any, N: number, LM: number) st.last_frame_type = FRAME_PLC_NOISE end --- celt_decode_with_ec. pcm[pbase + j * channels + c]; frameSize at 48 kHz. dec may be nil (a new range decoder over --- buf[off, off + len)). buf == nil or len <= 1 conceals. Returns the samples per channel, or < 0 on error. +-- celt_decode_with_ec (buf nil or len <= 1 conceals) function Celt.decode(st: any, buf: buffer?, off: number, len: number, pcm: { number }, pbase: number, frameSize: number, dec: RD.Dec?, accum: boolean): number local CC = st.channels @@ -1766,7 +1748,6 @@ function Celt.decode(st: any, buf: buffer?, off: number, len: number, pcm: { num pulses, fineQuant, finePriority, C, LM, ec) unquantFineEnergy(st, start, endb, fineQuant, ec, C) - -- shift the decoder memory by one frame for c = 1, CC do table.move(st.mem[c], N + 1, DECODE_BUFFER_SIZE + OVERLAP, 1) end diff --git a/src/Rosetta/codecs/audio/Opus/CeltEncoder.luau b/src/Rosetta/codecs/audio/Opus/CeltEncoder.luau index da21695..55936d4 100644 --- a/src/Rosetta/codecs/audio/Opus/CeltEncoder.luau +++ b/src/Rosetta/codecs/audio/Opus/CeltEncoder.luau @@ -1,12 +1,9 @@ --!strict --!native --!optimize 2 --- codecs/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 codecs/audio/Opus/Celt's decoder step for step; the analysis is simplified. The MDCT is codecs/audio/Mdct. --- Never throws. +-- codecs/audio/Opus/CeltEncoder: a fixed-frame CELT encoder (RFC 6716 section 5.3): 20 ms, full band, CBR, long MDCTs only. +-- 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); the analysis is simplified. local RE = require("@rosetta/codecs/entropy/RangeCoder/Encoder") local T = require("@rosetta/codecs/audio/Opus/CeltTables") local Mdct = require("@rosetta/codecs/audio/Mdct") @@ -67,7 +64,6 @@ 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) @@ -116,7 +112,6 @@ local function bitexactLog2tan(isin: number, icos: number): number 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 @@ -153,23 +148,22 @@ end export type State = { channels: number, - oldBandE: { number }, -- the decoder's view (2 * 21) + oldBandE: { number }, preMem: { number }, - inMem: { { number } }, -- the last OVERLAP pre-emphasised samples per channel + inMem: { { number } }, frames: number, - X: { { number } }, -- per channel 960 normalised coefficients + X: { { number } }, bandLogE: { number }, - bandE: { number }, -- linear band amplitudes (intensity stereo weights) + bandE: { number }, error: { number }, work: { number }, tmp: { number }, iy: { number }, remaining: number, spread: number, - dual: boolean, -- stereo: L / R coded independently (default false: mid / side) + dual: boolean, } --- new(channels) -> State function CeltEncoder.new(channels: number): State local inMem = {} local X = {} @@ -302,7 +296,6 @@ local function quantEnergyFinalise(st: State, fineQuant: { number }, finePriorit 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] @@ -566,7 +559,6 @@ local function computeAllocation(offsets: { number }, cap: { number }, allocTrim 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] @@ -700,7 +692,6 @@ 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 @@ -710,7 +701,6 @@ local function algQuant(st: State, X: { number }, xo: number, n: number, K: numb 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) @@ -929,14 +919,10 @@ local function quantAllBands(st: State, C: number, pulses: { number }, dualStere 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] @@ -988,7 +974,6 @@ function CeltEncoder.encodeFrame(st: State, pcm: { number }, base: number, strid 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) diff --git a/src/Rosetta/codecs/audio/Opus/CeltTables.luau b/src/Rosetta/codecs/audio/Opus/CeltTables.luau index 1685c78..536cdcc 100644 --- a/src/Rosetta/codecs/audio/Opus/CeltTables.luau +++ b/src/Rosetta/codecs/audio/Opus/CeltTables.luau @@ -1,5 +1,5 @@ --!strict --- codecs/audio/Opus/CeltTables: Generated from libopus celt/static_modes_float.h and celt/quant_bands.c (BSD, see licenses/). 1-based arrays. +-- codecs/audio/Opus/CeltTables: from libopus celt/static_modes_float.h and celt/quant_bands.c (BSD, licenses/). return { logN400 = { 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 16, 16, 16, 21, 21, 24, 29, 34, 36, diff --git a/src/Rosetta/codecs/audio/Opus/Decoder.luau b/src/Rosetta/codecs/audio/Opus/Decoder.luau index 8314fdd..d255a11 100644 --- a/src/Rosetta/codecs/audio/Opus/Decoder.luau +++ b/src/Rosetta/codecs/audio/Opus/Decoder.luau @@ -1,9 +1,8 @@ --!strict --!native --!optimize 2 --- codecs/audio/Opus/Decoder: The Opus decoder proper (libopus src/opus_decoder.c and opus_multistream_decoder.c): per-frame mode switching --- between SILK, hybrid and CELT, the redundant CELT frames of mode transitions, cross-fades, PLC fallbacks, the --- multi-frame packet loop and multistream (channel mapping) decoding. Output is 48 kHz float in Luau arrays. +-- codecs/audio/Opus/Decoder: the Opus decoder proper (libopus src/opus_decoder.c and opus_multistream_decoder.c). +-- SILK / hybrid / CELT mode switching, redundant CELT frames of mode transitions, cross-fades, PLC, multistream. local RD = require("@rosetta/codecs/entropy/RangeCoder/Decoder") local Packet = require("@rosetta/codecs/audio/Opus/Packet") local Celt = require("@rosetta/codecs/audio/Opus/Celt") @@ -153,7 +152,6 @@ local function decodeFrame(st: State, buf: buffer?, off: number, len: number, pc end frameSize = audiosize - -- SILK if mode ~= MODE_CELT then local tooSmall = frameSize < F10 local sarr, sbase = pcm, pbase @@ -289,8 +287,7 @@ local function decodeFrame(st: State, buf: buffer?, off: number, len: number, pc return audiosize end --- opus_decode_native: decodes one packet (buf == nil or len == 0: conceal frameSize samples). pcm[pbase + i * ch + c]. --- Returns the samples per channel (or < 0 on error) and the packet's size (self-delimited packets). +-- opus_decode_native (buf nil or len 0: conceal frameSize samples) function Decoder.decode(st: State, buf: buffer?, off: number, len: number, pcm: { number }, pbase: number, frameSize: number, selfDelimited: boolean?): (number, number) local ch = st.channels if buf == nil or len == 0 then @@ -337,7 +334,6 @@ function Decoder.decode(st: State, buf: buffer?, off: number, len: number, pcm: return nb, packetOffset end --- --------------------------------------------------------------------------------------------------------------- -- multistream (channel mapping families 0 / 1 / 255) export type MS = { @@ -370,7 +366,6 @@ function Decoder.resetMultistream(ms: MS) end end --- copies channel `sc` of src (stride sstride) into every output channel mapped to stream channel index `id` local function copyOut(ms: MS, id: number, src: { number }, sc: number, sstride: number, pcm: { number }, pbase: number, n: number) local nch = ms.channels for c = 0, nch - 1 do @@ -386,7 +381,7 @@ local function copyOut(ms: MS, id: number, src: { number }, sc: number, sstride: end end --- opus_multistream_decode_native (float). Returns the samples per channel, or < 0 on error. +-- opus_multistream_decode_native function Decoder.decodeMultistream(ms: MS, buf: buffer?, off: number, len: number, pcm: { number }, pbase: number, frameSize: number): number local doPlc = buf == nil or len == 0 frameSize = min(frameSize, 5760) @@ -428,7 +423,6 @@ function Decoder.decodeMultistream(ms: MS, buf: buffer?, off: number, len: numbe return frameSize end --- writes src[base + 1 .. base + count] * gain to out as f32 from byte offset o function Decoder.writeF32(src: { number }, base: number, count: number, gain: number, out: buffer, o: number) local writef32 = buffer.writef32 if gain == 1 then @@ -444,8 +438,6 @@ function Decoder.writeF32(src: { number }, base: number, count: number, gain: nu end end --- Stereo downmix of n frames of srcCh-channel audio (src[base + 1 ..], interleaved): matrix[c * 2 + 1 / + 2] are the --- left / right weights of channel c. Writes f32 to out from byte offset o. function Decoder.writeDownmix(src: { number }, base: number, n: number, srcCh: number, matrix: { number }, gain: number, out: buffer, o: number) local writef32 = buffer.writef32 local p = base diff --git a/src/Rosetta/codecs/audio/Opus/Mdct.luau b/src/Rosetta/codecs/audio/Opus/Mdct.luau index 30bb34a..729a0f1 100644 --- a/src/Rosetta/codecs/audio/Opus/Mdct.luau +++ b/src/Rosetta/codecs/audio/Opus/Mdct.luau @@ -1,19 +1,15 @@ --!strict --!native --!optimize 2 --- codecs/audio/Opus/Mdct: CELT inverse MDCT (libopus celt/mdct.c clt_mdct_backward) over a mixed-radix complex FFT (a port of the --- kiss_fft stages used by libopus: radix 5, 3, 4 and 2). The 48 kHz mode uses N = 1920 >> shift for --- shift = 0..3 (FFT sizes 480, 240, 120, 60). Arrays are Luau tables of numbers, 1-based. --- Why not codecs/audio/Mdct (measured by the cleanup pass): the shared transform computes the full N-sample IMDCT through a --- DCT-IV, of which CELT keeps the middle N / 2, so routing the decoder through it made CELT decoding 2-3x slower --- (luau: 25 -> 54-76 ms for 3 s of 32 kbps stereo) and changed the output bits (same SNR against opusdec). This --- fused libopus port (pre-rotation, a kiss_fft with fixed factors, post-rotation, TDAC) stays private. +-- codecs/audio/Opus/Mdct: CELT inverse MDCT (libopus celt/mdct.c clt_mdct_backward) over the kiss_fft radix 5 / 3 / 4 / 2 stages. +-- N = 1920 >> shift (FFT sizes 480 .. 60). Kept apart from codecs/audio/Mdct: CELT keeps only the middle N / 2 of the +-- full IMDCT, so the shared transform was 2-3x slower and changed the output bits. local Mdct = {} local sin, cos, pi = math.sin, math.cos, math.pi type Plan = { - n: number, -- FFT size (N / 4) + n: number, factors: { number }, bitrev: { number }, twr: { number }, @@ -82,13 +78,11 @@ local function bfly2(fr: { number }, fi: { number }, N: number) local tw = 0.7071067812 local p = 1 for _ = 1, N do - -- k = 0 local tr, ti = fr[p + 4], fi[p + 4] fr[p + 4] = fr[p] - tr fi[p + 4] = fi[p] - ti fr[p] += tr fi[p] += ti - -- k = 1 local a, b = fr[p + 5], fi[p + 5] tr = (a + b) * tw ti = (b - a) * tw @@ -96,14 +90,12 @@ local function bfly2(fr: { number }, fi: { number }, N: number) fi[p + 5] = fi[p + 1] - ti fr[p + 1] += tr fi[p + 1] += ti - -- k = 2 tr = fi[p + 6] ti = -fr[p + 6] fr[p + 6] = fr[p + 2] - tr fi[p + 6] = fi[p + 2] - ti fr[p + 2] += tr fi[p + 2] += ti - -- k = 3 a, b = fr[p + 7], fi[p + 7] tr = (b - a) * tw ti = -(b + a) * tw @@ -265,7 +257,7 @@ local function bfly5(fr: { number }, fi: { number }, fstride: number, twr: { num end end --- in-place forward FFT of bit-reversed input (opus_fft_impl) +-- opus_fft_impl (bit-reversed input) local function fftImpl(pl: Plan) local factors = pl.factors local fr, fi, twr, twi = pl.fr, pl.fi, pl.twr, pl.twi @@ -295,9 +287,7 @@ local function fftImpl(pl: Plan) end end --- clt_mdct_backward: input coefficients inp[inBase + k*stride] (k = 0 .. N/2-1, inBase is the 1-based index of --- coefficient 0), output written to out[outBase .. outBase + N/2 + overlap/2) with TDAC windowing of the first --- `overlap` samples (out[outBase] is sample 0). +-- clt_mdct_backward function Mdct.backward(inp: { number }, inBase: number, out: { number }, outBase: number, window: { number }, overlap: number, shift: number, stride: number) local pl = plans[shift + 1] local N4 = pl.n @@ -319,7 +309,6 @@ function Mdct.backward(inp: { number }, inBase: number, out: { number }, outBase xp2 -= 2 * stride end fftImpl(pl) - -- post-rotate local h = outBase + (overlap // 2) for k = 0, N4 - 1 do local re = fi[k + 1] diff --git a/src/Rosetta/codecs/audio/Opus/Packet.luau b/src/Rosetta/codecs/audio/Opus/Packet.luau index ae38311..f723cf4 100644 --- a/src/Rosetta/codecs/audio/Opus/Packet.luau +++ b/src/Rosetta/codecs/audio/Opus/Packet.luau @@ -46,7 +46,6 @@ function Packet.channels(toc: number): number return if band(toc, 4) ~= 0 then 2 else 1 end --- samples per frame at rate Fs function Packet.samplesPerFrame(toc: number, Fs: number): number if band(toc, 0x80) ~= 0 then local a = band(rshift(toc, 3), 3) @@ -62,7 +61,6 @@ function Packet.samplesPerFrame(toc: number, Fs: number): number end end --- total samples of a packet at 48 kHz, or -1 if invalid function Packet.samples(buf: buffer, off: number, len: number): number if len < 1 then return -1 @@ -100,9 +98,7 @@ local function parseSize(buf: buffer, p: number, len: number): (number, number) return 2, 4 * readu8(buf, p + 1) + b0 end --- Splits a packet (opus_packet_parse_impl). Fills offsets[i] / sizes[i] (1-based, absolute buffer offsets) and --- returns the frame count, the TOC byte and the packet's total size including padding (self-delimited packets, as in --- multistream, carry an explicit size for the last frame). The count is -1 for an invalid packet. +-- opus_packet_parse_impl; self-delimited packets (multistream) carry an explicit size for the last frame function Packet.parse(buf: buffer, off: number, len: number, offsets: { number }, sizes: { number }, selfDelimited: boolean?): (number, number, number) if len < 1 then return -1, 0, 0 diff --git a/src/Rosetta/codecs/audio/Opus/Silk.luau b/src/Rosetta/codecs/audio/Opus/Silk.luau index 0ffcf54..6f0698e 100644 --- a/src/Rosetta/codecs/audio/Opus/Silk.luau +++ b/src/Rosetta/codecs/audio/Opus/Silk.luau @@ -1,19 +1,8 @@ --!strict --!native --!optimize 2 --- codecs/audio/Opus/Silk: SILK decoder: a bit-exact port of the libopus fixed-point SILK decoder (silk/dec_API.c and what it calls: --- decode_frame, decode_indices, decode_pulses, shell_coder, code_signs, decode_parameters, gain_quant, NLSF_*, --- LPC_fit, LPC_inv_pred_gain, decode_core, stereo_*, CNG, PLC, resampler_private_up2_HQ / IIR_FIR). BSD, see --- licenses/. --- --- local st = Silk.new(apiChannels) --- local ret, n = Silk.decode(st, ctrl, lostFlag, firstFrame, ec, out, outBase) --- ctrl = { nChannelsAPI, nChannelsInternal, API_sampleRate, internalSampleRate, payloadSize_ms } --- decodes one 10 / 20 ms SILK frame and writes n samples per channel (at API_sampleRate) to the Luau array --- `out`, interleaved by nChannelsAPI: out[outBase + i * nChannelsAPI + c], scaled int16 / 32768. --- --- Fixed-point emulation: all values are Luau numbers holding C int32 / int16 values. Products of two int32 values --- (64-bit in C) are split so that every intermediate stays below 2^53 and therefore exact. +-- codecs/audio/Opus/Silk: SILK decoder, a bit-exact port of the libopus fixed-point SILK decoder (silk/dec_API.c and what +-- it calls; BSD, licenses/). C int32 / int16 values are Luau numbers; int32 x int32 products are split to stay below 2^53. local RD = require("@rosetta/codecs/entropy/RangeCoder/Decoder") local T = require("@rosetta/codecs/audio/Opus/SilkTables") @@ -24,7 +13,7 @@ local floor = math.floor local Silk = {} -local P2 = table.create(64, 0) -- P2[s] = 2^s (1-based by s: P2[s] for s >= 1, P2_0 = 1) +local P2 = table.create(64, 0) for s = 1, 63 do P2[s] = 2 ^ s end @@ -35,8 +24,6 @@ local function p2(s: number): number return P2[s] end --- C helpers ----------------------------------------------------------------------------------------------------- - local function s16(x: number): number x = x % 65536 if x >= 32768 then @@ -252,8 +239,6 @@ local function sumSqrShift(x: { number }, xo: number, len: number): (number, num return nrg, shft end --- LPC helpers --------------------------------------------------------------------------------------------------- - -- silk_bwexpander (int16 coefficients), ar 1-based local function bwexpander(ar: { number }, d: number, chirp_Q16: number) local chirp_minus_one_Q16 = chirp_Q16 - 65536 @@ -451,8 +436,6 @@ local function lpcAnalysisFilter(out: { number }, oo: number, inp: { number }, i end end --- NLSF ---------------------------------------------------------------------------------------------------------- - local CB_NB_MB = { nVectors = 32, order = 10, @@ -604,8 +587,6 @@ local function nlsfDecode(pNLSF_Q15: { number }, NLSFIndices: { number }, CB: an nlsfStabilize(pNLSF_Q15, CB.deltaMin_Q15, order) end --- Resampler (decoder side: 8 / 12 / 16 kHz up to the API rate) ---------------------------------------------------- - local RES_COPY, RES_UP2, RES_IIR_FIR = 0, 1, 2 local up2_hq_0 = { 1746, 14986, 39083 - 65536 } local up2_hq_1 = { 6854, 25769, 55542 - 65536 } @@ -733,7 +714,6 @@ local function up2HQ(S: { number }, out: { number }, oo: number, inp: { number } S[1], S[2], S[3], S[4], S[5], S[6] = s0, s1, s2, s3, s4, s5 end --- returns the next output index local function iirFirInterpol(out: { number }, oo: number, buf: { number }, max_index_Q16: number, incr: number): number local index_Q16 = 0 while index_Q16 < max_index_Q16 do @@ -814,8 +794,6 @@ local function resampler(S: any, out: { number }, inp: { number }, io: number, i end end --- Decoder state ------------------------------------------------------------------------------------------------- - local function newChannel(): any return { prev_gain_Q16 = 65536, @@ -943,8 +921,6 @@ local function decoderSetFs(ch: any, fs_kHz: number, fs_API_Hz: number): number return ret end --- Bitstream: indices and pulses --------------------------------------------------------------------------------- - local LTP_gain_iCDF = { T.LTP_gain_iCDF_0, T.LTP_gain_iCDF_1, T.LTP_gain_iCDF_2 } local LTP_vq_Q7 = { T.LTP_gain_vq_0, T.LTP_gain_vq_1, T.LTP_gain_vq_2 } local LBRR_flags_iCDF = { T.LBRR_flags_2_iCDF, T.LBRR_flags_3_iCDF } @@ -1115,8 +1091,6 @@ local function decodePulses(d: any, pulses: { number }, signalType: number, quan end end --- Parameters ---------------------------------------------------------------------------------------------------- - local pNLSF_Q15 = table.create(16, 0) local pNLSF0_Q15 = table.create(16, 0) @@ -1214,8 +1188,6 @@ local function decodeParameters(ch: any, ctrl: any, condCoding: number) end end --- Core synthesis ------------------------------------------------------------------------------------------------ - local sLTP = table.create(320, 0) local sLTP_Q15 = table.create(640, 0) local res_Q14 = table.create(80, 0) @@ -1381,8 +1353,6 @@ local function decodeCore(ch: any, ctrl: any, xq: { number }, xo: number, pulses end end --- PLC / CNG ----------------------------------------------------------------------------------------------------- - local HARM_ATT_Q15 = { 32440, 31130 } local PLC_RAND_ATTENUATE_V_Q15 = { 31130, 26214 } local PLC_RAND_ATTENUATE_UV_Q15 = { 32440, 29491 } @@ -1708,8 +1678,6 @@ local function cng(ch: any, ctrl: any, frame: { number }, fo: number, length: nu end end --- Frame decode -------------------------------------------------------------------------------------------------- - -- silk_decode_frame: writes frame_length samples to out[fo ..] local function decodeFrame(ch: any, d: any, out: { number }, fo: number, lostFlag: number, condCoding: number): number local L = ch.frame_length @@ -1760,8 +1728,6 @@ local function decodeFrame(ch: any, d: any, out: { number }, fo: number, lostFla return L end --- Stereo -------------------------------------------------------------------------------------------------------- - local function stereoDecodePred(d: any, pred_Q13: { number }) local n = icdf(d, T.stereo_pred_joint_iCDF, 1, 8) local ix02 = n // 5 @@ -1818,8 +1784,6 @@ local function stereoMSToLR(state: any, x1: { number }, x2: { number }, pred_Q13 end end --- API ----------------------------------------------------------------------------------------------------------- - export type State = any function Silk.new(apiChannels: number): State diff --git a/src/Rosetta/codecs/audio/Opus/init.luau b/src/Rosetta/codecs/audio/Opus/init.luau index ec61ba5..31ca9cb 100644 --- a/src/Rosetta/codecs/audio/Opus/init.luau +++ b/src/Rosetta/codecs/audio/Opus/init.luau @@ -1,9 +1,6 @@ --!strict --- codecs/audio/Opus: the Opus codec (RFC 6716) without its container: TOC / packet framing (Packet), the SILK and CELT --- decoders and the multistream / hybrid decoder that drives them (Decoder), the CELT encoder (CeltEncoder) and the --- CELT inverse MDCT (Mdct, a fused libopus port: see its header for why it is not codecs/audio/Mdct). A port of the --- libopus 1.6 decoder (BSD: licenses/libopus-BSD.txt), absorbed from opus-luau dd2b4e5; the encoder is new. Ogg Opus --- (OpusHead, OpusTags, granules, seeking) is audio/opus. +-- codecs/audio/Opus: the Opus codec (RFC 6716) without its container. +-- A port of the libopus 1.6 decoder (BSD, licenses/libopus-BSD.txt), absorbed from opus-luau dd2b4e5; the CELT encoder is new. local Opus = { Packet = require("@rosetta/codecs/audio/Opus/Packet"), Decoder = require("@rosetta/codecs/audio/Opus/Decoder"), diff --git a/src/Rosetta/codecs/audio/Pcm/Convert.luau b/src/Rosetta/codecs/audio/Pcm/Convert.luau index 3d15128..9dd0079 100644 --- a/src/Rosetta/codecs/audio/Pcm/Convert.luau +++ b/src/Rosetta/codecs/audio/Pcm/Convert.luau @@ -1,12 +1,9 @@ --!strict --!native --!optimize 2 --- codecs/audio/Pcm/Convert: raw sample formats <-> interleaved f32 (the hot loops of codecs/audio/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. +-- codecs/audio/Pcm/Convert: raw sample formats <-> interleaved f32. +-- Integers map to v / 2^(bits-1) (as ffmpeg does). G.711 A-law / mu-law per ITU-T G.711 (the classic Sun g711.c +-- algorithm, written from the spec). local Convert = {} local readu8, readi8, readi16, readi32, readu32 = buffer.readu8, buffer.readi8, buffer.readi16, buffer.readi32, buffer.readu32 @@ -32,7 +29,6 @@ local SIZE: { [string]: number } = { 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, @@ -50,11 +46,9 @@ Convert.BITS = { ulaw = 16, } --- ------------------------------------------------------------------------------------------------ G.711 -local ALAW = table.create(256, 0) -- code -> linear s16 +local ALAW = table.create(256, 0) 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) @@ -66,7 +60,6 @@ for code = 0, 255 do 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 @@ -83,7 +76,6 @@ local function segment(v: number, ends: { number }): number 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 @@ -108,7 +100,6 @@ local function alawEncode(pcm: number): number 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 @@ -136,8 +127,6 @@ 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 @@ -216,7 +205,6 @@ function Convert.decode(src: buffer, so: number, fmt: string, count: number, dst return true end --- ------------------------------------------------------------------------------------------------ encode local function q(x: number, s: number): number local v = floor(x * s + 0.5) if v ~= v then @@ -230,7 +218,6 @@ local function q(x: number, s: number): number 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 diff --git a/src/Rosetta/codecs/audio/Pcm/init.luau b/src/Rosetta/codecs/audio/Pcm/init.luau index 56d6046..18e9097 100644 --- a/src/Rosetta/codecs/audio/Pcm/init.luau +++ b/src/Rosetta/codecs/audio/Pcm/init.luau @@ -1,21 +1,5 @@ --!strict -- codecs/audio/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/audio/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("@rosetta/core/Err") local Bytes = require("@rosetta/core/Bytes") local Types = require("@rosetta/Types") @@ -41,11 +25,10 @@ Pcm.WAVE_FROM_VORBIS = { export type Source = { sampleRate: number, channels: number, - frames: number, -- total frames, 0 = unknown (a streaming decoder without an index) + frames: number, 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 + err: Err.Err?, } local function audioRead(self: any, n: number, out: buffer?): (buffer, number) @@ -86,7 +69,6 @@ local function decoderRead(self: any, n: number, out: buffer?): (buffer, number) 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") @@ -109,7 +91,6 @@ function Pcm.source(v: any): (Source?, Err.Err?) 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) @@ -117,7 +98,6 @@ function Pcm.collect(src: Source, maxFrames: number?): (Types.Audio?, Err.Err?) local total = 0 local limit = maxFrames or 2 ^ 31 local tmp: buffer? = nil - -- a known length: one read straight into the result (decoders write into a big enough out buffer: no copy) if src.frames > 0 and src.frames <= limit then local b, n = src:read(src.frames, data) if n > 0 then @@ -160,9 +140,6 @@ function Pcm.collect(src: Source, maxFrames: number?): (Types.Audio?, Err.Err?) return a, nil end --- drain(dec, source?, maxFrames?) -> Types.Audio | nil, Err: a format's decode() through its open(): every frame of --- the Decoder (dec.frames is only a hint: short or long streams keep what decodes), dec.tags, meta.source = source --- (default dec.source). A decoder that recorded a failure in dec.error (an Err) fails the drain. function Pcm.drain(dec: any, source: { [string]: any }?, maxFrames: number?): (Types.Audio?, Err.Err?) local src, err = Pcm.source(dec) if not src then @@ -180,9 +157,6 @@ function Pcm.drain(dec: any, source: { [string]: any }?, maxFrames: number?): (T 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 @@ -221,14 +195,12 @@ function Pcm.rawDecoder(buf: buffer, offset: number, frames: number, channels: n 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 @@ -254,9 +226,6 @@ function Pcm.encode(src: Source, fmt: string, w: Bytes.Writer): (number?, Err.Er return total, nil end --- ------------------------------------------------------------------------------------------------ conversions --- reorder(buf, offset, frames, channels, map): in place, frame by frame, channel i of the result = channel map[i] --- (1-based) of the input; for converting between channel orders (Pcm.WAVE_FROM_VORBIS) function Pcm.reorder(buf: buffer, offset: number, frames: number, channels: number, map: { number }) local tmp = table.create(channels, 0) local readf32, writef32 = buffer.readf32, buffer.writef32 @@ -271,7 +240,6 @@ function Pcm.reorder(buf: buffer, offset: number, frames: number, channels: numb end end --- 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) @@ -286,7 +254,6 @@ function Pcm.toInt(x: number, bits: number): number return v end --- fromInt(v, bits) -> v / 2^(bits-1) function Pcm.fromInt(v: number, bits: number): number return v / 2 ^ (bits - 1) end diff --git a/src/Rosetta/codecs/audio/Qoa/init.luau b/src/Rosetta/codecs/audio/Qoa/init.luau index 0e7560a..881979f 100644 --- a/src/Rosetta/codecs/audio/Qoa/init.luau +++ b/src/Rosetta/codecs/audio/Qoa/init.luau @@ -1,18 +1,9 @@ --!strict --!native --!optimize 2 --- codecs/audio/Qoa: the "Quite OK Audio" codec (QOA): frames of up to 256 slices per channel, each slice a 4-bit scale --- factor and 20 3-bit residuals over a 4-tap sign-sign LMS predictor. Ported from qoa.h (phoboslab/qoa, Dominic --- Szablewski, MIT: licenses/qoa-LICENSE.txt): the tables, the predictor, the decoder and the encoder's brute-force --- scale factor search, so encoding is byte-for-byte qoa.h's (including its 32-bit wrap in the reciprocal division). --- The 64-bit slices are handled as two 32-bit halves. --- --- local info = Qoa.frameInfo(buf, p, avail) -- { channels, rate, samples, size } | nil, message --- local n, msg = Qoa.decodeFrame(buf, p, avail, dst, d) -- one frame -> interleaved f32 at float index d --- local size = Qoa.encodeFrame(x, xf, n, ch, rate, lms, out, p) -- n frames of f32 at frame xf -> bytes at out[p] --- local lms = Qoa.newLms(ch) -- the encoder state (history 0, weights 0, 0, -1, 2) --- --- Never throws: decodeFrame checks the frame against avail before reading; encodeFrame needs Qoa.frameSize bytes. +-- codecs/audio/Qoa: the "Quite OK Audio" codec (QOA). +-- Ported from qoa.h (phoboslab/qoa, Dominic Szablewski, MIT: licenses/qoa-LICENSE.txt); encoding is byte-for-byte +-- qoa.h's, including its 32-bit wrap in the reciprocal division. local readu8, readu32, readf32, writef32, writeu32 = buffer.readu8, buffer.readu32, buffer.readf32, buffer.writef32, buffer.writeu32 local readi32, writei32 = buffer.readi32, buffer.writei32 local band, rshift, bor, lshift, byteswap = bit32.band, bit32.rshift, bit32.bor, bit32.lshift, bit32.byteswap @@ -55,14 +46,12 @@ local function s16(v: number): number return if v >= 32768 then v - 65536 else v end --- frameSize(channels, slices) -> bytes function Qoa.frameSize(ch: number, slices: number): number return 8 + 16 * ch + 8 * slices * ch end export type FrameInfo = { channels: number, rate: number, samples: number, size: number } --- frameInfo(buf, p, avail) -> the frame header's facts, checked against avail and the slice count | nil, message function Qoa.frameInfo(b: buffer, p: number, avail: number): (FrameInfo?, string?) if avail < 8 then return nil, "truncated frame header" @@ -86,8 +75,6 @@ function Qoa.frameInfo(b: buffer, p: number, avail: number): (FrameInfo?, string return { channels = ch, rate = rate, samples = samples, size = size }, nil end --- decodeFrame(buf, p, avail, dst, d) -> samples per channel, frame bytes | nil, message: one frame (its own LMS state --- in the header) as interleaved f32 into dst from float index d (dst holds samples * channels floats there) function Qoa.decodeFrame(b: buffer, p: number, avail: number, dst: buffer, d: number): (number?, number | string) local info, msg = Qoa.frameInfo(b, p, avail) if not info then @@ -140,8 +127,7 @@ function Qoa.decodeFrame(b: buffer, p: number, avail: number, dst: buffer, d: nu return samples, info.size end --- ------------------------------------------------------------------------------------------------ encoder --- newLms(ch) -> the encoder's LMS state: 8 i32 per channel (history 0..3, weights 0..3), weights 0, 0, -1, 2 (<< 13) +-- LMS state: 8 i32 per channel (history 0..3, weights 0..3); initial weights 0, 0, -1, 2 (<< 13) function Qoa.newLms(ch: number): buffer local st = buffer.create(32 * ch) for c = 0, ch - 1 do @@ -151,7 +137,6 @@ function Qoa.newLms(ch: number): buffer return st end --- the nearest s16 to x * 32768 (NaN -> 0) local function toS16(x: number): number local v = floor(x * 32768 + 0.5) if v ~= v then @@ -177,8 +162,6 @@ local function qdiv(v: number, sf: number): number return n + sv - sn end --- encodeFrame(x, xf, n, ch, rate, lms, out, p) -> bytes written: frames xf .. xf + n - 1 (n <= 5120) of interleaved f32 x --- as one QOA frame at out[p] (Qoa.frameSize(ch, ceil(n / 20)) bytes); lms carries the encoder state between frames function Qoa.encodeFrame(x: buffer, xf: number, n: number, ch: number, rate: number, lms: buffer, out: buffer, p: number): number local slices = (n + 19) // 20 local size = Qoa.frameSize(ch, slices) diff --git a/src/Rosetta/codecs/audio/Resample/init.luau b/src/Rosetta/codecs/audio/Resample/init.luau index aab61be..18c768c 100644 --- a/src/Rosetta/codecs/audio/Resample/init.luau +++ b/src/Rosetta/codecs/audio/Resample/init.luau @@ -1,44 +1,32 @@ --!strict --!native --!optimize 2 --- codecs/audio/Resample: audio sample-rate conversion by band-limited (Kaiser-windowed sinc) interpolation, streaming or --- whole-buffer, any channel count, interleaved f32 (the Types.Audio / Decoder layout). Used by the Opus, MP3 and MP2 --- encoders (their input rates are fixed) and ops/AudioOps.resample. New in rosetta (the textbook polyphase --- filter; the kernel is the one the Opus encoder carried). +-- codecs/audio/Resample: sample-rate conversion by band-limited (Kaiser-windowed sinc) polyphase interpolation. +-- New in rosetta. -- -- The filter is a polyphase table: exact phases when to / gcd(from, to) <= 4096 (44100 <-> 48000: 160 phases), -- else 4096 phases with linear interpolation between them. Each phase is normalised to unit DC gain. The cutoff is a --- fraction (opts.cutoff, default 0.97) of the lower Nyquist frequency; quality picks the taps per side at the cutoff: +-- fraction (default 0.97) of the lower Nyquist frequency. -- -- quality zero crossings per side Kaiser beta stop band -- "low" 8 6 ~ -60 dB -- "medium" 16 (default) 8 ~ -80 dB -- "high" 32 10 ~ -100 dB -- --- Output frame j sits at input time j * from / to (no delay: the filter is centred, the input is zero outside its --- range); a stream of n input frames gives floor(n * to / from + 0.5) output frames. --- --- local out, frames = Resample.buffer(samples, frames, channels, 44100, 48000, { quality = "high" }) --- local rs = Resample.new(44100, 48000, 2) -- nil, message for bad rates --- local b, n = rs:process(chunk, chunkFrames) -- the output frames this input completes --- local b2, n2 = rs:flush() -- the rest (the input end padded with zeros) --- local src2 = Resample.source(pcmSource, 48000) -- a codecs/audio/Pcm Source at the new rate --- --- Never throws: bad arguments return nil, message (the api turns them into Err.ARG). +-- Output frame j sits at input time j * from / to (centred filter, zero outside the input); n input frames give +-- floor(n * to / from + 0.5) output frames. local Resample = {} export type Options = { - quality: ("low" | "medium" | "high")?, -- default "medium" - cutoff: number?, -- pass band edge as a fraction of the lower Nyquist frequency, 0.5 .. 1 (default 0.97) + quality: ("low" | "medium" | "high")?, + cutoff: number?, } export type Resampler = { from: number, to: number, channels: number, - -- process(src, frames, out?) -> interleaved f32 buffer, output frames (out is reused when big enough) process: (self: Resampler, src: buffer, frames: number, out: buffer?) -> (buffer, number), - -- flush(out?) -> the remaining output frames; the resampler is finished afterwards flush: (self: Resampler, out: buffer?) -> (buffer, number), } @@ -69,15 +57,14 @@ local function gcd(a: number, b: number): number end type Filter = { - taps: number, -- per phase - half: number, -- taps on the left of the centre (taps = 2 * half) + taps: number, + half: number, phases: number, exact: boolean, h: { number }, -- phase p, tap k: h[p * taps + k + 1] } --- filter(ratio, phases, exact, opts) -> the polyphase table. Phase p is the kernel for an output at fraction --- p / phases past an input sample; tap k multiplies input (floor(t) - half + 1 + k). +-- phase p: an output p / phases past an input sample; tap k multiplies input floor(t) - half + 1 + k local function makeFilter(ratio: number, phases: number, exact: boolean, zc: number, beta: number, cut: number): Filter local cutoff = cut * min(1, ratio) local width = zc / cutoff -- in input samples, each side @@ -111,7 +98,6 @@ local function makeFilter(ratio: number, phases: number, exact: boolean, zc: num return { taps = taps, half = half, phases = phases, exact = exact, h = h } end --- the stream state: the input history as an interleaved Lua array; hist[1] is frame `base` (absolute) type State = { from: number, to: number, @@ -121,15 +107,14 @@ type State = { L: number, -- to / g hist: { number }, histFrames: number, - base: number, -- the absolute input frame of hist[1] - inFrames: number, -- absolute input frames received - outPos: number, -- next output frame (absolute) + base: number, + inFrames: number, + outPos: number, done: boolean, process: any, flush: any, } --- run(st, lastInput) -> buffer, frames: every output frame whose taps end at or before lastInput (absolute, exclusive) local function run(st: State, limitOut: number, out: buffer?): (buffer, number) local f = st.f local taps, half, h = f.taps, f.half, f.h @@ -159,8 +144,8 @@ local function run(st: State, limitOut: number, out: buffer?): (buffer, number) for j = j0, jmax - 1 do local num = j * M local ip = num // L -- floor(t) - local first = ip - half + 1 -- absolute input frame of tap 0 - local rel = first - base -- frame index in hist + local first = ip - half + 1 + local rel = first - base local kLo = if rel < 0 then -rel else 0 local kHi = taps - 1 if rel + kHi >= histFrames then @@ -199,7 +184,6 @@ local function run(st: State, limitOut: number, out: buffer?): (buffer, number) end end st.outPos = jmax - -- drop history no future output needs (keep from the next output's first tap) local keepFrom = (jmax * M) // L - half + 1 local drop = keepFrom - base if drop > 0 then @@ -243,7 +227,6 @@ local function flush(self: State, out: buffer?): (buffer, number) return run(self, total, out) end --- new(from, to, channels, opts?) -> Resampler | nil, message function Resample.new(from: number, to: number, channels: number, opts: Options?): (Resampler?, string?) if type(from) ~= "number" or type(to) ~= "number" or from ~= from or to ~= to or from <= 0 or to <= 0 or from > 2 ^ 24 or to > 2 ^ 24 then return nil, "bad sample rates" @@ -287,7 +270,6 @@ function Resample.new(from: number, to: number, channels: number, opts: Options? return st :: any, nil end --- buffer(src, frames, channels, from, to, opts?) -> interleaved f32 buffer, frames | nil, message function Resample.buffer(src: buffer, frames: number, channels: number, from: number, to: number, opts: Options?): (buffer?, number | string) local rs, err = Resample.new(from, to, channels, opts) if not rs then @@ -322,8 +304,6 @@ function Resample.buffer(src: buffer, frames: number, channels: number, from: nu return out, got end --- source(src, to, opts?) -> a pull source ({ sampleRate, channels, frames, tags, read, err }, the codecs/audio/Pcm Source --- shape) reading src (any such source: Pcm.source(audioOrDecoder)) at the rate `to` | nil, message function Resample.source(src: any, to: number, opts: Options?): (any, string?) if type(src) ~= "table" or type(src.read) ~= "function" then return nil, "needs a source" @@ -333,7 +313,7 @@ function Resample.source(src: any, to: number, opts: Options?): (any, string?) return nil, err end local ch = src.channels - local pending = buffer.create(0) -- produced but not yet returned + local pending = buffer.create(0) local pendingFrames, pendingPos = 0, 0 local ended = false local out = { diff --git a/src/Rosetta/codecs/audio/SoundFont/Fallback.luau b/src/Rosetta/codecs/audio/SoundFont/Fallback.luau index e32c646..c532ca6 100644 --- a/src/Rosetta/codecs/audio/SoundFont/Fallback.luau +++ b/src/Rosetta/codecs/audio/SoundFont/Fallback.luau @@ -1,10 +1,6 @@ --!strict --- codecs/audio/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). +-- codecs/audio/SoundFont/Fallback: the built-in General MIDI set (generated waveforms per GM family, drum kit on bank 128). +-- No third-party code. local Parse = require("@rosetta/codecs/audio/SoundFont/Parse") local Fallback = {} @@ -19,7 +15,6 @@ 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 @@ -72,7 +67,6 @@ function Fallback.build(): any 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 } }, @@ -97,9 +91,7 @@ function Fallback.build(): any 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 diff --git a/src/Rosetta/codecs/audio/SoundFont/Parse.luau b/src/Rosetta/codecs/audio/SoundFont/Parse.luau index a4ab970..4a93fee 100644 --- a/src/Rosetta/codecs/audio/SoundFont/Parse.luau +++ b/src/Rosetta/codecs/audio/SoundFont/Parse.luau @@ -1,19 +1,13 @@ --!strict --- codecs/audio/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. +-- codecs/audio/SoundFont/Parse: SoundFont 2.0x (sfbk RIFF) reader, zones merged into regions as TinySoundFont does. +-- After tsf.h v0.9 (MIT, (c) Bernhard Schelling; licenses/TinySoundFont-LICENSE.txt) tsf_load_presets / +-- tsf_region_operator / tsf_region_envtosecs. Unlike tsf.h, initialAttenuation is cB * 0.04 dB (FluidSynth's +-- EMU-compatible scale; tsf uses 0.01). local Err = require("@rosetta/core/Err") local Bytes = require("@rosetta/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 } } @@ -23,7 +17,7 @@ export type 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 + presets: { Preset }, sampleHeaders: { { [string]: any } }, instruments: { { name: string, zones: number } }, meta: { [string]: any }, @@ -84,7 +78,6 @@ local GEN: { [number]: { any } } = { [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 } = {} @@ -106,7 +99,7 @@ local FIELDS = { "sampleIndex", } --- clear(relative): tsf_region_clear. relative = a preset zone (all zero: values add to the instrument's) +-- tsf_region_clear (relative: a preset zone, all zero so values add to the instrument's) local function clear(relative: boolean): Region local r: Region = {} for _, f in FIELDS do @@ -136,7 +129,6 @@ local function copy(r: Region): Region 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 @@ -220,7 +212,6 @@ local function envToSecs(r: Region, p: string, sustainIsGain: boolean) 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) @@ -244,7 +235,6 @@ local INFO_NAMES = { 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 @@ -301,7 +291,7 @@ function Parse.parse(r: Bytes.Reader, opts: Options?): (SoundFont?, Err.Err?) local rec = {} for _, w in layout do if w == 20 then - table.insert(rec, 0) -- the name is read separately + table.insert(rec, 0) sub:skip(20) elseif w == 4 then table.insert(rec, sub:u32le()) @@ -338,7 +328,6 @@ function Parse.parse(r: Bytes.Reader, opts: Options?): (SoundFont?, Err.Err?) 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 @@ -363,14 +352,13 @@ function Parse.parse(r: Bytes.Reader, opts: Options?): (SoundFont?, Err.Err?) end sm24 = s24 end - -- presets (tsf_load_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) diff --git a/src/Rosetta/codecs/audio/SoundFont/Synth.luau b/src/Rosetta/codecs/audio/SoundFont/Synth.luau index d868f0c..de9f280 100644 --- a/src/Rosetta/codecs/audio/SoundFont/Synth.luau +++ b/src/Rosetta/codecs/audio/SoundFont/Synth.luau @@ -1,16 +1,8 @@ --!strict --!native --- codecs/audio/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). +-- codecs/audio/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). Unlike tsf.h, the envelope gain is ramped across each 64-sample block. local Synth = {} local readf32, writef32, blen = buffer.readf32, buffer.writef32, buffer.len @@ -39,12 +31,12 @@ type Env = { } type Lfo = { untilStart: number, level: number, delta: number } export type Voice = { - preset: number, -- 1-based preset index, -1 = idle + preset: number, key: number, channel: number, - held: boolean, -- note off while sustain was down + held: boolean, region: { [string]: number }, - pitchIn: number, -- timecents + pitchIn: number, pitchOut: number, pos: number, gainDB: number, @@ -83,14 +75,14 @@ export type Channel = { } export type State = { presets: { { regions: { { [string]: number } }, preset: number, bank: number } }, - lookup: { [number]: number }, -- bank * 128 + preset -> preset index + lookup: { [number]: number }, samples: buffer, rate: number, gainDB: number, voices: { Voice }, maxVoices: number, playIndex: number, - channels: { Channel }, -- [1..16] = MIDI channels 0..15 + channels: { Channel }, } local function tc2s(tc: number): number @@ -106,7 +98,6 @@ 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 @@ -216,7 +207,6 @@ 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) @@ -249,7 +239,6 @@ local function lfoProcess(l: Lfo, n: number) 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 @@ -276,7 +265,7 @@ 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 + v.loopEnd = v.loopStart end end @@ -303,8 +292,6 @@ local function newChannel(): Channel } 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 @@ -337,7 +324,6 @@ 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 @@ -427,7 +413,6 @@ function Synth.noteOn(s: State, ch: number, key: number, velocity: number) 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 @@ -518,7 +503,7 @@ local function setSustain(s: State, ch: number, c: Channel, on: boolean) end end --- program(s, channel, program): bank select + program change (channel 9: drums, bank 128) +-- channel 9: drums (bank 128) function Synth.program(s: State, ch: number, program: number) local c = s.channels[ch + 1] if not c then @@ -548,7 +533,6 @@ function Synth.program(s: State, ch: number, program: number) 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 @@ -558,7 +542,6 @@ function Synth.pitchBend(s: State, ch: number, value: number) 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 @@ -640,7 +623,6 @@ function Synth.control(s: State, ch: number, cc: number, value: number) 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 @@ -656,7 +638,6 @@ function Synth.midi(s: State, status: number, d1: number, d2: number) 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 @@ -669,7 +650,6 @@ function Synth.reset(s: State) end end --- active(s) -> the number of sounding voices function Synth.active(s: State): number local n = 0 for _, v in s.voices do @@ -680,7 +660,6 @@ function Synth.active(s: State): number 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 @@ -772,8 +751,6 @@ local function voiceRender(s: State, v: Voice, out: buffer, frame: number, numSa 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 @@ -785,8 +762,7 @@ function Synth.render(s: State, out: buffer, frame: number, n: number) 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) + -- the sample buffer must hold every region's range + the pad sample (checked once against hand-made SoundFonts) local count = blen(s.samples) // 4 - 1 for _, v in s.voices do if v.preset ~= -1 then diff --git a/src/Rosetta/codecs/audio/SoundFont/init.luau b/src/Rosetta/codecs/audio/SoundFont/init.luau index ce36495..dc75823 100644 --- a/src/Rosetta/codecs/audio/SoundFont/init.luau +++ b/src/Rosetta/codecs/audio/SoundFont/init.luau @@ -1,17 +1,6 @@ --!strict --- codecs/audio/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("@rosetta/codecs/audio/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. +-- codecs/audio/SoundFont: SoundFont 2 banks and the sample synth that plays MIDI through them. +-- The synth is a port of TinySoundFont (tsf.h v0.9, MIT, (c) 2017-2025 Bernhard Schelling; licenses/TinySoundFont-LICENSE.txt). local Err = require("@rosetta/core/Err") local Bytes = require("@rosetta/core/Bytes") local Parse = require("@rosetta/codecs/audio/SoundFont/Parse") @@ -26,13 +15,10 @@ 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 @@ -51,17 +37,14 @@ function SoundFont.parse(src: any, opts: Parse.Options?): (SoundFont?, Err.Err?) 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 diff --git a/src/Rosetta/codecs/audio/Stream.luau b/src/Rosetta/codecs/audio/Stream.luau index 467828e..56ebcd6 100644 --- a/src/Rosetta/codecs/audio/Stream.luau +++ b/src/Rosetta/codecs/audio/Stream.luau @@ -1,25 +1,6 @@ --!strict --- codecs/audio/Stream: the streaming Decoder (Types.Decoder: read / seek / position) over a packetised codec, the part --- every packet-based audio format repeated: decode packets in order into a pending float block, return frames in --- read()-sized pieces, drop the encoder priming at the start and the padding at the end (gapless), and seek by --- finding the packet holding the target (with codec pre-roll) and dropping up to it. AAC (ADTS), CAF and M4A use it; --- formats with their own seeking (Opus granule bisection, FLAC, MP3, Vorbis) keep their streams. New in rosetta --- (the loop the three formats carried). --- --- local dec, err = Stream.packets(dec, { -- dec: the Decoder table with its fields (sampleRate, channels, --- count = n, -- frames, duration, bitrate, tags, ...); read / seek / position --- start = function(i) return ... end, -- are added. start(i): packet i's first frame (absolute, before --- decode = function(i) return n, err end,-- trimming); decode(i) -> frames | nil, Err, the samples in pcm() --- pcm = function() return floats end, -- (interleaved, 1-based; or a buffer of f32) until the next decode --- reset = function() end, -- forget codec state (before a seek) --- skip = priming, stop = lastFrame, -- output = absolute frames [skip, stop) --- preroll = 1, -- packets decoded before the one holding a seek target (AAC: 1) --- scale = 1 / 32768, -- optional: read() writes pcm() values * scale (default 1) --- ints = true, -- optional: pcm() holds integers; adds dec:readInt(n, out?), the --- }) -- same frames as read() as i32 (bit-exact checks) --- --- A decode failure ends the stream and is kept in dec.error (Pcm.drain reports it); a failing first packet is --- returned by packets() as the open error. Never throws. +-- codecs/audio/Stream: the streaming Types.Decoder over a packetised codec (gapless trim, seeking with pre-roll). +-- New in rosetta. local Err = require("@rosetta/core/Err") local Stream = {} @@ -28,17 +9,16 @@ export type Spec = { count: number, start: (i: number) -> number, decode: (i: number) -> (number?, Err.Err?), - pcm: () -> { number } | buffer, -- a buffer: interleaved f32 from byte 0 + pcm: () -> { number } | buffer, reset: () -> (), - skip: number?, -- default 0 - stop: number?, -- default start(count + 1) - preroll: number?, -- default 0 + skip: number?, + stop: number?, + preroll: number?, cumulative: boolean?, -- frames after a packet = frames before + its output (default: start(i) + its output) - scale: number?, -- read() writes pcm() values times this (default 1) - ints: boolean?, -- pcm() values are integers: dec:readInt(n, out?) returns them as i32 + scale: number?, + ints: boolean?, } --- packets(dec, spec) -> dec (with read / seek / position) | nil, Err (the first packet failed) function Stream.packets(dec: any, spec: Spec): (any, Err.Err?) local sr, ch = dec.sampleRate, dec.channels local count = spec.count @@ -48,7 +28,7 @@ function Stream.packets(dec: any, spec: Spec): (any, Err.Err?) local preroll = spec.preroll or 0 local decodeP, pcmOf, startOf = spec.decode, spec.pcm, spec.start local nextPacket = 1 - local decoded = 0 -- absolute frame after the packets decoded so far + local decoded = 0 local pendPos, pendN = 0, 0 local dropUntil = skip local pos = 0 @@ -144,8 +124,7 @@ function Stream.packets(dec: any, spec: Spec): (any, Err.Err?) function dec.seek(_self: any, seconds: number) local sec = if type(seconds) == "number" and seconds == seconds then seconds else 0 - local target = math.clamp(math.floor(sec * sr + 0.5), 0, frames) + skip -- absolute frame - -- the last packet starting at or before the target, minus the codec's pre-roll + local target = math.clamp(math.floor(sec * sr + 0.5), 0, frames) + skip local lo, hi, found = 1, count, 1 while lo <= hi do local mid = (lo + hi) // 2 @@ -171,7 +150,6 @@ function Stream.packets(dec: any, spec: Spec): (any, Err.Err?) return pos / sr end - -- prime: surface a broken first packet as an open error if count > 0 and frames > 0 and not fill() and failed then return nil, failed end diff --git a/src/Rosetta/codecs/audio/Tracker/Load.luau b/src/Rosetta/codecs/audio/Tracker/Load.luau index c192c0d..1cc9cef 100644 --- a/src/Rosetta/codecs/audio/Tracker/Load.luau +++ b/src/Rosetta/codecs/audio/Tracker/Load.luau @@ -1,10 +1,7 @@ --!strict --- codecs/audio/Tracker/Load: helpers shared by the tracker loaders that map another format's effects onto one of the --- engine's families (music/mtm, 669, stm, ult, okt, med, ptm, far). Effects are first named the way OpenMPT's loaders --- name them ("portaup", "volslide", "modex", ...), then written in the family's own cell coding: S3M / IT letter --- codes (A = 1) with the IT volume column, or MOD / XM numbers. Ported from OpenMPT's ModCommand helpers --- (ConvertModCommand, ConvertToVolCommand, FillInTwoCommands, GetEffectWeight, CPattern::WriteEffect; BSD licence, --- licenses/openmpt-LICENSE.txt), reduced to what the engine plays. +-- codecs/audio/Tracker/Load: helpers mapping other tracker formats' effects onto the engine's S3M / IT or MOD / XM families. +-- Ported from OpenMPT's ModCommand helpers (ConvertModCommand, ConvertToVolCommand, FillInTwoCommands, GetEffectWeight, +-- CPattern::WriteEffect; BSD licence, licenses/openmpt-LICENSE.txt). local Err = require("@rosetta/core/Err") local Player = require("@rosetta/codecs/audio/Tracker/Player") local Pcm = require("@rosetta/codecs/audio/Tracker/Pcm") @@ -14,7 +11,6 @@ local Load = {} local EXT = Player.EXT --- the S3M / IT letter code of each effect name (engine extension effects included) local IT: { [string]: number } = { speed = 1, jump = 2, @@ -67,7 +63,7 @@ end local GLOBAL = { jump = true, ["break"] = true, speed = true, tempo = true, globalvol = true, globalvolslide = true } --- isGlobal(name, param) -> the effect acts on the whole song (OpenMPT's IsGlobalCommand) +-- OpenMPT's IsGlobalCommand function Load.isGlobal(name: string?, param: number): boolean if name == nil then return false @@ -84,7 +80,7 @@ function Load.isGlobal(name: string?, param: number): boolean return false end --- modCommand(cmd, param) -> name?, param: a MOD / XM effect number (0..F, XM letters 16..) by name (ConvertModCommand) +-- OpenMPT's ConvertModCommand local MODFX: { [number]: string } = { [0] = "arpeggio", [1] = "portaup", [2] = "portadown", [3] = "toneporta", [4] = "vibrato", [5] = "toneportavol", [6] = "vibratovol", [7] = "tremolo", [8] = "panning8", [9] = "offset", [10] = "volslide", [11] = "jump", @@ -104,8 +100,7 @@ function Load.modCommand(cmd: number, param: number): (string?, number) return n, param end --- itVolume(name, param, force) -> the IT volume-column byte + 1 (the engine's coding) for an effect that fits there, --- or nil (OpenMPT's ConvertToVolCommand; force: fit it with some loss of precision) +-- OpenMPT's ConvertToVolCommand (force: fit with some loss of precision) function Load.itVolume(name: string?, param: number, force: boolean): number? if name == "volume" then return math.min(param, 64) + 1 @@ -159,8 +154,6 @@ function Load.itVolume(name: string?, param: number, force: boolean): number? return nil end --- itEffect(name, param) -> effect code, param in S3M / IT coding (0, 0 for none or an effect the family lacks; MOD's --- extended E commands become their S3M equivalents) function Load.itEffect(name: string?, param: number): (number, number) if name == nil then return 0, 0 @@ -191,9 +184,7 @@ function Load.itEffect(name: string?, param: number): (number, number) return code, param end --- fillTwo(name1, param1, name2, param2, lowResOffset?) -> volume byte (engine IT coding, 0 none), effect name, param, --- lost name?, lost param: two effects of one cell into the IT volume column and the effect column, keeping the --- heavier one when both cannot fit (OpenMPT's FillInTwoCommands) +-- OpenMPT's FillInTwoCommands function Load.fillTwo(e1: string?, p1: number, e2: string?, p2: number): (number, string?, number, string?, number) if e1 ~= nil and e1 == e2 then e2 = nil -- the same effect twice: keep one (most are absolute; slides are kept once too, a simplification) @@ -215,10 +206,7 @@ function Load.fillTwo(e1: string?, p1: number, e2: string?, p2: number): (number return 0, e2, p2, e1, p1 end --- writeEffect(m, pattern (0-based), row, fx, param, retry?, channel?, multiple?) -> true when written: puts an effect --- into a free effect slot of the row (any channel, or the given 1-based one); none free: the next row (retry "next") or --- the previous one ("prev"). The same effect already on the row counts as written unless multiple (OpenMPT's --- CPattern::WriteEffect). +-- OpenMPT's CPattern::WriteEffect function Load.writeEffect(m: any, pattern: number, row: number, fx: number, param: number, retry: string?, channel: number?, multiple: boolean?): boolean local p = m.patterns[pattern + 1] if not p then @@ -261,9 +249,6 @@ function Load.writeEffect(m: any, pattern: number, row: number, fx: number, para return false end --- readSample(buf, offset, frames, spec, sample, budget) -> true | nil, Err: decodes raw PCM (codecs/audio/Tracker/Pcm --- spec) at the absolute buffer offset into the sample (data, length, bits, channels). A short file keeps the frames --- that are there (end = the buffer's length, or spec.limit). budget = { left = f32 bytes still allowed } (maxBytes). function Load.readSample(buf: buffer, offset: number, frames: number, spec: any, s: any, budget: { left: number }): (boolean?, Err.Err?) local nch = spec.channels or 1 local bps = spec.bits // 8 @@ -282,7 +267,7 @@ function Load.readSample(buf: buffer, offset: number, frames: number, spec: any, return true, nil end --- bcd(n) -> n as the two decimal digits S3M / MOD pattern breaks store (0..99) +-- S3M / MOD pattern breaks store the row as two decimal digits function Load.bcd(n: number): number n = math.clamp(math.floor(n), 0, 99) return (n // 10) * 16 + n % 10 diff --git a/src/Rosetta/codecs/audio/Tracker/Mixer.luau b/src/Rosetta/codecs/audio/Tracker/Mixer.luau index 9cedf6b..47af9b6 100644 --- a/src/Rosetta/codecs/audio/Tracker/Mixer.luau +++ b/src/Rosetta/codecs/audio/Tracker/Mixer.luau @@ -1,17 +1,12 @@ --!strict --!native --- codecs/audio/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/audio/Tracker) --- validates the sample buffers' sizes. +-- codecs/audio/Tracker/Mixer: tracker voice mixing (loops, IT sustain loops, IT two-pole resonant filter, click ramps). +-- No third-party code. 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 @@ -161,7 +156,6 @@ local function mixVoice(v: any, out: buffer?, off: number, n: number, linear: bo 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 diff --git a/src/Rosetta/codecs/audio/Tracker/Pcm.luau b/src/Rosetta/codecs/audio/Tracker/Pcm.luau index cdbc496..8dfc69e 100644 --- a/src/Rosetta/codecs/audio/Tracker/Pcm.luau +++ b/src/Rosetta/codecs/audio/Tracker/Pcm.luau @@ -1,9 +1,7 @@ --!strict --!native --- codecs/audio/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). +-- codecs/audio/Tracker/Pcm: raw 8 / 16-bit tracker sample data (signed / unsigned, XM / IT 2.15 delta coding, +-- interleaved or planar stereo) <-> f32. 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 @@ -11,20 +9,18 @@ local floor = math.floor local Pcm = {} export type Spec = { - bits: number, -- 8 | 16 + bits: number, signed: boolean, delta: boolean?, -- each value is the difference to the previous one (XM, IT 2.15 "delta" flag) - channels: number?, -- 1 (default) | 2 + channels: number?, 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 @@ -76,7 +72,6 @@ function Pcm.decode(buf: buffer, off: number, frames: number, spec: Spec): buffe 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 @@ -118,7 +113,6 @@ function Pcm.encode(samples: buffer, frames: number, spec: Spec): buffer 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 diff --git a/src/Rosetta/codecs/audio/Tracker/Player.luau b/src/Rosetta/codecs/audio/Tracker/Player.luau index 1c8e568..c71e948 100644 --- a/src/Rosetta/codecs/audio/Tracker/Player.luau +++ b/src/Rosetta/codecs/audio/Tracker/Player.luau @@ -1,14 +1,8 @@ --!strict --!native --- codecs/audio/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/audio/Tracker/Mixer. --- --- Never throws: the module is validated by codecs/audio/Tracker before a player is made, and every table lookup here is --- guarded. +-- codecs/audio/Tracker/Player: the tracker sequencer for the MOD, S3M, XM and IT effect families. +-- 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. local Tables = require("@rosetta/codecs/audio/Tracker/Tables") local wave64, autoWave = Tables.wave64, Tables.autoWave @@ -23,8 +17,6 @@ local MOD, S3M, XM, IT = 1, 2, 3, 4 Player.MOD, Player.S3M, Player.XM, Player.IT = MOD, S3M, XM, IT local FAMILY = { mod = MOD, s3m = S3M, xm = XM, it = IT } --- engine extension effects: format-specific commands of the other tracker formats, in any family (see --- codecs/audio/Tracker) local EXT = { NOTE_SLIDE_UP = 0x40, NOTE_SLIDE_DOWN = 0x41, @@ -37,9 +29,8 @@ local EXT = { } Player.EXT = EXT -local BG_VOICES = 64 -- voices beyond one per channel, for IT new note actions +local BG_VOICES = 64 --- ------------------------------------------------------------------------------------------------ state local function newVoice(): any return { active = false, @@ -100,8 +91,8 @@ local function newVoice(): any tremorMute = false, surround = false, rampN = 0, - owner = 0, -- the channel whose foreground voice this is (0: free or background) - order = 0, -- allocation age + owner = 0, + order = 0, } end @@ -126,7 +117,6 @@ local function newChannel(i: number, pan: number, vol: number): any fx = 0, param = 0, vcmd = 0, - -- memories mPortaUp = 0, mPortaDn = 0, mFineUp = 0, @@ -186,15 +176,14 @@ local function newChannel(i: number, pan: number, vol: number): any muted = false, triggered = false, autoPorta = 0, -- auto portamento (EXT 0x44 / 0x45): period units per tick, + down - autoTone = false, -- flags.autoTonePorta: the tone portamento keeps running + autoTone = false, hzAdd = 0, -- EXT 0x46: Hz added to the frequency (669) - slideCount = 0, -- note slides: ticks to the next step + slideCount = 0, mNoteSlide = 0, tonePortaRow = false, } end --- new(module, opts) -> player state (module validated by the caller) function Player.new(m: any, sampleRate: number, opts: any): any local fmt = FAMILY[m.engine or m.format] or MOD local flags = m.flags @@ -213,8 +202,8 @@ function Player.new(m: any, sampleRate: number, opts: any): any compatG = m.flags.compatGxx or false, fastSlides = flags.fastSlides or false, amigaLimits = flags.amigaLimits or false, - ptPeriods = ptPeriods, -- ProTracker periods (integer table periods, PAL clock) - hz = flags.periods == "hz", -- periods are frequencies in Hz + ptPeriods = ptPeriods, + hz = flags.periods == "hz", hzScale = if type(flags.hzSlide) == "number" then flags.hzSlide else 1, hzTone = if type(flags.hzTonePorta) == "number" then flags.hzTonePorta else 1, fastPortas = flags.fastPortas or false, @@ -286,8 +275,6 @@ function Player.masterGain(m: any, fmt: number): number 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 @@ -357,8 +344,6 @@ local function advanceRow(st: any) end end --- ------------------------------------------------------------------------------------------------ pitch --- the period of a note for a sample (see codecs/audio/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 @@ -412,8 +397,7 @@ local function clampPeriod(st: any, c: any) end end --- slide(st, c, units): a pitch slide in period units (positive: down; 4 per effect unit); in Hz mode the frequency --- moves units * hzSlide Hz the other way +-- pitch slides in period units (positive: down; 4 per effect unit); in Hz mode the frequency moves units * hzSlide Hz the other way local function slide(st: any, c: any, units: number) if st.hz then c.period -= units * st.hzScale @@ -423,7 +407,6 @@ local function slide(st: any, c: any, units: number) clampPeriod(st, c) end --- ------------------------------------------------------------------------------------------------ voices local function allocVoice(st: any): any local best, bestScore = nil, math.huge for _, v in st.voices do @@ -441,7 +424,6 @@ local function allocVoice(st: any): any 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] @@ -451,7 +433,7 @@ local function allocVoice(st: any): any return v end end - return st.voices[1] -- unreachable: there are more voices than channels + return st.voices[1] end local function keyOff(st: any, v: any) @@ -492,7 +474,6 @@ local function cutVoice(v: any) 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 @@ -541,7 +522,6 @@ 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 @@ -582,7 +562,6 @@ local function newNoteAction(st: any, c: any, ins: any, insIdx: number, note: nu end end --- ------------------------------------------------------------------------------------------------ triggering local function isPorta(st: any, fx: number, vcmd: number): boolean local f = st.fmt if f == MOD then @@ -594,7 +573,6 @@ local function isPorta(st: any, fx: number, vcmd: number): boolean 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 @@ -668,7 +646,6 @@ local function sampleOffset(st: any, c: any, v: any) 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 @@ -802,7 +779,6 @@ local function trigger(st: any, c: any, note: number, insIdx: number, vcmd: numb end end --- ------------------------------------------------------------------------------------------------ effect helpers local function volSlideMod(c: any, param: number) local x, y = param // 16, param % 16 if x > 0 then @@ -858,8 +834,7 @@ local function retrigVolume(c: any, x: number) 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) +-- S3M / IT D-style slide: 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 @@ -884,7 +859,6 @@ local function dSlide(value: number, param: number, tick: number, fast: boolean, 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 @@ -1198,7 +1172,6 @@ local function volColXm(st: any, c: any, tick: number) 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 @@ -1606,8 +1579,6 @@ local function volColIt(st: any, c: any, tick: number) end end --- ------------------------------------------------------------------------------------------------ extension effects --- the engine extension effects (EXT, codes 0x40..) and the auto slides, in any family local function fxExt(st: any, c: any, tick: number) local fx, param = c.fx, c.param if fx >= EXT.NOTE_SLIDE_UP and fx <= EXT.NOTE_SLIDE_DOWN_RETRIG then @@ -1666,7 +1637,6 @@ local function fxExt(st: any, c: any, tick: number) 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 @@ -1764,7 +1734,6 @@ local function processRow(st: any) 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 @@ -1805,7 +1774,6 @@ local function updateEnvelope(env: any, pos: number, keyOn: boolean, it: boolean 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 @@ -1876,7 +1844,6 @@ local function updateVoice(st: any, v: any) end v.avPos = (v.avPos + (avSrc.vibRate or 0)) % 256 end - -- frequency local P = v.periodOut + avDelta local freq if st.hz then @@ -1890,7 +1857,6 @@ local function updateVoice(st: any, v: any) 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 -- channel, sample and instrument global volumes (64 / 64 / 128 unless an IT file, or another format's loader, @@ -1899,7 +1865,6 @@ local function updateVoice(st: any, v: any) 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) @@ -1921,7 +1886,6 @@ local function updateVoice(st: any, v: any) 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 @@ -1946,7 +1910,6 @@ local function updateVoice(st: any, v: any) 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 @@ -1959,7 +1922,6 @@ function Player.tick(st: any): number 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 @@ -1983,7 +1945,6 @@ function Player.tick(st: any): number 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 @@ -2009,7 +1970,6 @@ function Player.tick(st: any): number 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 diff --git a/src/Rosetta/codecs/audio/Tracker/Tables.luau b/src/Rosetta/codecs/audio/Tracker/Tables.luau index 2378fee..877f9eb 100644 --- a/src/Rosetta/codecs/audio/Tracker/Tables.luau +++ b/src/Rosetta/codecs/audio/Tracker/Tables.luau @@ -1,15 +1,12 @@ --!strict --!native --- codecs/audio/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). +-- codecs/audio/Tracker/Tables: tracker lookup tables, 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 @@ -31,8 +28,6 @@ function Tables.wave64(kind: number, pos: number): number 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) @@ -59,9 +54,7 @@ function Tables.autoWave(kind: number, pos: number, it: boolean): number 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). +-- ProTracker periods, finetune 0, C-0 .. B-4; note 1 = C-0 (FT2 numbering), C-2 (428) = note 49 plays at 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, @@ -73,12 +66,10 @@ local PERIODS = { 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 @@ -88,7 +79,6 @@ function Tables.periodToNote(period: number): number 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 @@ -104,14 +94,12 @@ Tables.IT_VOLPORTA = { 0, 1, 4, 8, 16, 32, 64, 96, 128, 255 } 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) +-- frequency = AMIGA / period; period 1712 plays an 8363 Hz sample at its base rate (FT2 / ST3 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 --- st2Tempo(byte) -> speed, tempo: a Scream Tracker 2 tempo byte (high nibble ticks per row, low nibble a fine factor) --- as OpenMPT plays it (ConvertST2Tempo: ST2's tick length at its 23863 Hz mixing rate, as a fractional BPM) +-- Scream Tracker 2 tempo byte as OpenMPT plays it (ConvertST2Tempo: ST2's tick length at 23863 Hz, as a fractional BPM) local ST2_FACTOR = { 140, 50, 25, 15, 10, 7, 6, 4, 3, 3, 2, 2, 2, 2, 1, 1 } function Tables.st2Tempo(byte: number): (number, number) local hi, lo = byte // 16, byte % 16 diff --git a/src/Rosetta/codecs/audio/Tracker/init.luau b/src/Rosetta/codecs/audio/Tracker/init.luau index 355a7a8..5f36569 100644 --- a/src/Rosetta/codecs/audio/Tracker/init.luau +++ b/src/Rosetta/codecs/audio/Tracker/init.luau @@ -1,67 +1,18 @@ --!strict --- codecs/audio/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it, and the loaders --- that map other trackers onto those four effect families (music/mtm, 669, stm, ult, okt, med, ptm, far; helpers in --- codecs/audio/Tracker/Load). The loaders read their files into one Module structure (below); render(module, opts) plays any of them through the standard audio --- Decoder (Types.Decoder: stereo f32). Written for this library from the format documents (ProTracker 2.3, the XM --- spec + FT2 behaviour, ST3 TECH.DOC, ITTECH.TXT); libxmp / OpenMPT were used only as reference players for tests. +-- codecs/audio/Tracker: the shared tracker engine behind music/mod, s3m, xm and it, and the formats mapped onto them. +-- Written 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("@rosetta/codecs/audio/Tracker") --- local dec, err = Tracker.render(module, { sampleRate = 44100 }) -- a Types.Decoder --- local seconds = Tracker.duration(module) -- one pass, song loops detected +-- Pattern cells are 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. 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). Extension effects (Tracker.EXT): 0x40 / 0x41 note +-- slide up / down, 0x42 / 0x43 with retrigger (param = ticks per step << 4 | semitones), 0x44 / 0x45 auto portamento +-- up / down (669), 0x46 frequency adjust (+ param * 80 Hz, 669), 0x47 / 0x48 / 0x49 tempo 256 / 512 / 768 + param (MED). -- --- Module (Types.Module plus the engine fields; pattern / instrument / sample numbers are as in the file): --- format the file format ("mod", "s3m", "xm", "it", "mtm", "669", ...): what the module was read from --- engine "mod" | "s3m" | "xm" | "it": the effect family the engine plays (default: format, so the four --- families need no engine field). Other formats map their effects onto one family (music/mtm: "xm", --- music/669: "s3m", ...) and set the quirks they need in flags. --- preamp optional 0..256: the output gain as OpenMPT's sample pre-amp (gain = preamp / 128); default per family --- title, channels, speed (ticks per row), tempo (BPM: a tick lasts 2.5 / tempo s) --- globalVolume 0..128 (S3M / XM 0..64 are stored doubled), mixVolume 0..128 (IT mix volume, S3M master volume) --- order { pattern number (0-based) | 254 skip ("+++") | 255 end ("---") }, restart (0-based order index) --- linear linear frequency slides (XM / IT flag) or Amiga periods --- instrumentMode XM, IT with instruments: notes go through Instrument keymaps; otherwise the instrument column --- is a sample number (MOD, S3M, IT sample mode) --- flags { oldEffects, compatGxx (IT), fastSlides (ST3.00 volume slides: also on tick 0; any family), --- amigaLimits (MOD), and the quirks of the other formats (any family): --- periods = "amiga" (ProTracker period table + PAL clock, as MOD) | "hz" (periods are frequencies in --- Hz: 669, FAR; slides move hzSlide Hz per unit, tone portamento hzSlide * hzTonePorta), --- fastPortas (slides on tick 0 too), autoTonePorta (a tone portamento keeps running on later rows), --- autoReset (669: any effect stops the auto slides), st2Tempo (S3M family A: Scream Tracker 2 tempo), --- oktSlides (Oktalyzer note slides), panLaw = "ft2" (square-root panning, OpenMPT's FT2 mix levels), --- envRowHold (MED: envelopes do not advance on a row's first tick) } --- channelPan { 0..256 per channel (128 centre; 512 = surround); MOD: 64 / 192 (Amiga L R R L at half width, --- as OpenMPT plays it; set 0 / 256 or render with stereoSeparation = 200 for hard panning) }, channelVolume { 0..64 }, channelMute { bool } --- patterns { Pattern } (pattern n at patterns[n + 1]); Pattern = { rows, data }: data holds rows * channels --- 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). Engine extension effects (any family, for the other formats): Tracker.EXT (0x40 note --- slide up, 0x41 down, 0x42 / 0x43 the same with retrigger: param = ticks per step << 4 | semitones; --- 0x44 / 0x45 auto portamento up / down (669: every tick until another effect), 0x46 frequency --- adjust (+ param * 80 Hz, 669), 0x47 / 0x48 / 0x49 tempo 256 / 512 / 768 + param (MED)). --- Tracker.cell / Tracker.setCell read and write cells. --- samples { Sample }: { name, data (f32, interleaved when stereo), length (frames), channels, bits (8 | 16, --- for writers), loopStart, loopEnd (frames, end exclusive), loopType (0 none, 1 forward, 2 ping-pong), --- susStart, susEnd, susType (IT sustain loop), volume 0..64, globalVolume 0..64, pan (0..256 or nil), --- 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. +-- Pitch: linear P = (ref - note) * 64 - transpose, 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. local Err = require("@rosetta/core/Err") local Types = require("@rosetta/Types") local Player = require("@rosetta/codecs/audio/Tracker/Player") @@ -86,38 +37,32 @@ export type Envelope = { susEnd: number, carry: boolean?, filter: boolean?, - raw: any?, -- format-specific fields kept for a faithful re-save (XM) + raw: any?, } 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) + sampleRate: number?, + interpolation: ("linear" | "none")?, + stereoSeparation: number?, + loop: boolean?, + maxDuration: number?, } local CELL = 5 --- engine extension effects (see the Module notes above) Tracker.EXT = Player.EXT --- st2Tempo(byte) -> speed, tempo (BPM): a Scream Tracker 2 tempo byte Tracker.st2Tempo = Tables.st2Tempo local FAMILIES = { mod = true, s3m = true, xm = true, it = true } --- family(module) -> "mod" | "s3m" | "xm" | "it" | nil: the effect family a module plays as function Tracker.family(m: any): string? local f = m.engine or m.format return if type(f) == "string" and FAMILIES[f] then f else nil end --- ------------------------------------------------------------------------------------------------ constructors --- newModule(format, channels, engine?) -> an empty Module (no patterns / samples) with the defaults of the effect family --- (engine, default format) function Tracker.newModule(format: string, channels: number, engine: string?): any local fam = engine or format local m = { @@ -156,12 +101,10 @@ function Tracker.newModule(format: string, channels: number, engine: string?): a 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 "", @@ -192,7 +135,6 @@ 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 @@ -222,8 +164,6 @@ function Tracker.newInstrument(name: string?): any } 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 @@ -234,7 +174,6 @@ function Tracker.cell(m: any, pattern: number, row: number, channel: number): (n 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 @@ -250,7 +189,6 @@ function Tracker.setCell(m: any, pattern: number, row: number, channel: number, 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 @@ -312,8 +250,6 @@ local function fixLoop(s0: any, e0: any, t0: any, len: number): (number, number, 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") @@ -420,11 +356,9 @@ function Tracker.validate(m: any): (boolean?, Err.Err?) 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 @@ -451,7 +385,6 @@ local function newPlayer(self: any) 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 @@ -482,13 +415,11 @@ function Tracker.render(m: any, opts: RenderOptions?): (Types.Decoder?, Err.Err? 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 @@ -515,7 +446,6 @@ local function run(self: any, out: buffer?, n: number): number 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 @@ -528,7 +458,6 @@ function Decoder.read(self: any, n: number, out: buffer?): (buffer, number) 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) @@ -539,7 +468,6 @@ function Decoder.seek(self: any, seconds: number) 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 diff --git a/src/Rosetta/codecs/audio/Tta/Decode.luau b/src/Rosetta/codecs/audio/Tta/Decode.luau index 2f76b84..dc8c696 100644 --- a/src/Rosetta/codecs/audio/Tta/Decode.luau +++ b/src/Rosetta/codecs/audio/Tta/Decode.luau @@ -1,10 +1,8 @@ --!strict --!native --!optimize 2 --- codecs/audio/Tta/Decode: one TTA1 frame -> samples. Written from the TTA1 format description (the True Audio --- format notes: adaptive Rice codes with two running sums per channel, the order-8 sign-LMS "hybrid" filter, the --- first-order fixed predictor, inter-channel decorrelation, a CRC-32 per frame); no libtta / ffmpeg code. Checked --- bit-exact against the ttaenc 3.4.1 decoder (tools/fixtures/tta.py). Never throws: returns nil, message. +-- codecs/audio/Tta/Decode: one TTA1 frame -> samples, from the TTA1 format description; no libtta / ffmpeg code. +-- Bit-exact against the ttaenc 3.4.1 decoder (tools/fixtures/tta.py). local Crc32 = require("@rosetta/core/Crc32") local readu8, readu32 = buffer.readu8, buffer.readu32 @@ -16,11 +14,10 @@ local Decode = {} local TWO31, TWO32 = 2147483648, 4294967296 local INV31 = 1 / TWO31 local PAD = 16 -local P2: { number } = table.create(40, 0) -- P2[k + 1] = 2^k +local P2: { number } = table.create(40, 0) for i = 0, 39 do P2[i + 1] = 2 ^ i end --- ONES[b + 1]: the trailing 1 bits of the byte b local ONES: { number } = table.create(256, 0) for b = 0, 255 do local n, v = 0, b @@ -31,7 +28,6 @@ for b = 0, 255 do ONES[b + 1] = n end --- longUnary(S, pos, lim) -> the count of 1 bits from pos, the position after the 0 | nil (past lim) local function longUnary(S: buffer, pos: number, lim: number): (number?, number) local unary = 0 while pos <= lim do @@ -48,9 +44,8 @@ end export type State = { channels: number, - bytes: number, -- 1 .. 3 - S: buffer, -- the frame's bits (+ PAD zeros) - -- per channel: rice k0, k1, sum0, sum1; filter error, Q (weights), X (steps), L (delay line) x 8; the last value + bytes: number, + S: buffer, R: { number }, Q: { number }, X: { number }, @@ -75,8 +70,6 @@ function Decode.state(channels: number, bytes: number): State } end --- frame(st, buf, o, len, n, P) -> n | nil, message: the frame of len bytes at o (its CRC-32 last) holding n samples per --- channel, into P (interleaved integers) function Decode.frame(st: State, buf: buffer, o: number, len: number, n: number, P: { number }): (number?, string?) if len < 4 then return nil, "truncated frame" @@ -105,15 +98,14 @@ function Decode.frame(st: State, buf: buffer, o: number, len: number, n: number, Q[c * 8 + i], X[c * 8 + i], L[c * 8 + i] = 0, 0, 0 end end - local pos = 0 -- bit position + local pos = 0 local lim = dlen * 8 - local c = 0 -- the channel of the sample at idx + local c = 0 for idx = 1, n * C do do if pos > lim then return nil, "truncated frame" end - -- the unary prefix: 1 bits up to a 0 (a run past one byte goes to longUnary) local unary local w = rshift(readu32(S, rshift(pos, 3)), band(pos, 7)) local ones = ONES[band(w, 255) + 1] @@ -222,7 +214,6 @@ function Decode.frame(st: State, buf: buffer, o: number, len: number, n: number, L[fb + 6] = n6 L[fb + 7] = n7 L[fb + 8] = value - -- the fixed predictor value += (last[c + 1] * (pk - 1)) // pk last[c + 1] = value cur[c + 1] = value diff --git a/src/Rosetta/codecs/audio/Tta/init.luau b/src/Rosetta/codecs/audio/Tta/init.luau index bb3ba33..43b230e 100644 --- a/src/Rosetta/codecs/audio/Tta/init.luau +++ b/src/Rosetta/codecs/audio/Tta/init.luau @@ -1,15 +1,7 @@ --!strict --- codecs/audio/Tta: the TTA1 (True Audio) lossless codec. A codec (layer 3). Written from the TTA1 format description --- (the 22-byte header with its CRC-32, the seek table of frame sizes with its CRC-32, frames of 256 / 245 seconds); --- no libtta / ffmpeg code (those are LGPL). The frame decoder is codecs/audio/Tta/Decode. Supports format 1 (plain --- PCM), 8 / 16 / 24 bits, any channel count, the header / seek table / frame CRCs. Not supported: format 2 --- (password-protected: UNSUPPORTED), TTA2. --- --- local info, err = Tta.info(buf, at, limit) -- the header at `at` (after any ID3v2 tag) + the frame table --- local dec = Tta.decoder(info) --- local n, err = dec:frame(buf, i) -- frame i (1-based) -> dec.pcm (interleaved integers) --- --- Never throws: bad data returns nil, Err. +-- codecs/audio/Tta: the TTA1 (True Audio) lossless codec. +-- From the TTA1 format description (22-byte header and seek table with CRC-32s, frames of 256 / 245 seconds); no libtta / +-- ffmpeg code (LGPL). Format 2 (password) is UNSUPPORTED. local Err = require("@rosetta/core/Err") local Crc32 = require("@rosetta/core/Crc32") local Decode = require("@rosetta/codecs/audio/Tta/Decode") @@ -21,14 +13,13 @@ export type Info = { channels: number, bitsPerSample: number, sampleRate: number, - samples: number, -- per channel + samples: number, frameLength: number, -- samples per frame (256 * rate / 245) frames: number, - offsets: { number }, -- each frame's byte offset + offsets: { number }, sizes: { number }, } --- info(buf, at, limit) -> Info | nil, Err: the TTA1 header at byte `at` function Tta.info(buf: buffer, at: number, limit: number): (Info?, Err.Err?) if at + 22 > limit then return nil, Err.new(Err.TRUNCATED, "truncated header") @@ -86,7 +77,6 @@ function Tta.info(buf: buffer, at: number, limit: number): (Info?, Err.Err?) return info, nil end --- ------------------------------------------------------------------------------------------------ decoder export type Decoder = { info: Info, pcm: { number }, @@ -112,7 +102,6 @@ local function frame(self: Decoder, buf: buffer, i: number): (number?, Err.Err?) return got, nil end --- decoder(info, limit) -> Decoder (limit: the end of the file data) function Tta.decoder(info: Info, limit: number): Decoder return { info = info, diff --git a/src/Rosetta/codecs/audio/Vorbis/Codebook.luau b/src/Rosetta/codecs/audio/Vorbis/Codebook.luau index 73af31c..a3cada1 100644 --- a/src/Rosetta/codecs/audio/Vorbis/Codebook.luau +++ b/src/Rosetta/codecs/audio/Vorbis/Codebook.luau @@ -1,14 +1,9 @@ --!strict --!native --!optimize 2 --- codecs/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. +-- codecs/audio/Vorbis/Codebook: the Vorbis LSB-first bit reader and codebooks (Vorbis I spec sections 2 and 3). +-- Ported from stb_vorbis 1.22 (public domain / MIT, licenses/stb_vorbis-LICENSE.txt). Reading past the packet end gives +-- zero bits and sets eop (the spec's end-of-packet condition); an invalid codeword also sets eop and decodes to -1. local Codebook = {} local readu8 = buffer.readu8 @@ -19,22 +14,20 @@ for i = 0, 40 do POW[i + 1] = 2 ^ i end --- ------------------------------------------------------------------------------------------------ bit reader export type Br = { buf: buffer, - pos: number, -- next byte to load + pos: number, limit: number, - acc: number, -- loaded, unread bits (LSB first) + acc: number, 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 + pad: number, + eop: boolean, } 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 @@ -66,7 +59,7 @@ local function bits(br: Br, n: number): number end Codebook.bits = bits --- ilog(x): the number of bits needed to hold x (0 for x <= 0) +-- ilog (spec 9.2.1) local function ilog(x: number): number local n = 0 while x > 0 do @@ -86,7 +79,6 @@ local function float32Unpack(x: number): number return if sign then -v else v end --- ------------------------------------------------------------------------------------------------ codebooks export type Book = { dims: number, entries: number, @@ -95,9 +87,9 @@ export type Book = { 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 + lookup: number, + vq: { number }?, + used: number, } local MAX_ENTRIES = 2 ^ 20 @@ -152,7 +144,6 @@ local function build(book: Book, lengths: { number }): string? 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 @@ -189,7 +180,6 @@ local function build(book: Book, lengths: { number }): string? 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] @@ -205,7 +195,7 @@ local function build(book: Book, lengths: { number }): string? fl[idx + 1], fs[idx + 1] = d, -child - 1 break elseif child == 0 then - break -- invalid (-1) + break end node = child if d == fb then @@ -217,7 +207,6 @@ local function build(book: Book, lengths: { number }): string? 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" @@ -337,7 +326,6 @@ function Codebook.read(br: Br): (Book?, string?) 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 diff --git a/src/Rosetta/codecs/audio/Vorbis/Packet.luau b/src/Rosetta/codecs/audio/Vorbis/Packet.luau index d98ae09..babf116 100644 --- a/src/Rosetta/codecs/audio/Vorbis/Packet.luau +++ b/src/Rosetta/codecs/audio/Vorbis/Packet.luau @@ -1,18 +1,10 @@ --!strict --!native --!optimize 2 --- codecs/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/audio/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. +-- codecs/audio/Vorbis/Packet: Vorbis audio packet decoding (Vorbis I spec sections 4.3, 7, 8). +-- Floors, residues and coupling ported from stb_vorbis 1.22 (public domain / MIT, 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 two window +-- centres, so granule positions count exactly the samples returned (the first packet returns none). local Codebook = require("@rosetta/codecs/audio/Vorbis/Codebook") local Setup = require("@rosetta/codecs/audio/Vorbis/Setup") local Tables = require("@rosetta/codecs/audio/Vorbis/Tables") @@ -31,16 +23,16 @@ export type State = { 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 + slopes: { [number]: { number } }, + spec: { { number } }, + frame: { { number } }, + tail: { { number } }, tailLen: number, - prevN: number, -- the previous block size, 0 = no previous frame - out: { { number } }, -- per channel: the returned samples + prevN: number, + out: { { number } }, finalY: { { number } }, step2: { number }, - inter: { number }, -- residue type 2 interleaved scratch + inter: { number }, zero: { boolean }, reallyZero: { boolean }, partClass: { { { number } } }, @@ -101,7 +93,6 @@ function Packet.reset(st: State) 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 @@ -118,7 +109,6 @@ function Packet.blocksize(st: State, b: buffer, off: number, size: number): numb 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 @@ -155,7 +145,6 @@ local function drawLine(out: { number }, x0: number, y0: number, x1: number, y1: 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 @@ -259,8 +248,6 @@ local function floorCurve(g: Setup.Floor1, finalY: { number }, target: { number 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 @@ -304,7 +291,6 @@ local function partition(br: Codebook.Br, book: Codebook.Book, target: { number 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 @@ -374,7 +360,6 @@ local function residue(st: State, br: Codebook.Br, r: Setup.Residue, targets: { classSet += 1 end end - -- de-interleave into the channels that are decoded for j = 1, ch do local t = targets[j] if t then @@ -428,8 +413,6 @@ local function residue(st: State, br: Codebook.Br, r: Setup.Residue, targets: { 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 @@ -471,7 +454,6 @@ function Packet.decode(st: State, b: buffer, off: number, size: number): number 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] @@ -486,7 +468,6 @@ function Packet.decode(st: State, b: buffer, off: number, size: number): number zero[m], zero[a] = false, false end end - -- residues, per submap for i = 1, map.submaps do local targets: { { number } | false } = {} local k = 0 @@ -498,7 +479,6 @@ function Packet.decode(st: State, b: buffer, off: number, size: number): number 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 @@ -520,7 +500,6 @@ function Packet.decode(st: State, b: buffer, off: number, size: number): number 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] @@ -570,7 +549,6 @@ function Packet.decode(st: State, b: buffer, off: number, size: number): number 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] diff --git a/src/Rosetta/codecs/audio/Vorbis/Setup.luau b/src/Rosetta/codecs/audio/Vorbis/Setup.luau index 11d6108..a371005 100644 --- a/src/Rosetta/codecs/audio/Vorbis/Setup.luau +++ b/src/Rosetta/codecs/audio/Vorbis/Setup.luau @@ -1,10 +1,8 @@ --!strict --!native --- codecs/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. +-- codecs/audio/Vorbis/Setup: the three Vorbis header packets (Vorbis I spec section 4.2). +-- Ported from stb_vorbis 1.22 start_decoder (public domain / MIT, licenses/stb_vorbis-LICENSE.txt). Floor 0 is +-- rejected as unsupported, as stb_vorbis does. local Codebook = require("@rosetta/codecs/audio/Vorbis/Codebook") local Setup = {} @@ -24,16 +22,16 @@ export type Ident = { export type Floor1 = { partitions: number, - partitionClass: { number }, -- 1-based list of class numbers (0-based values) - classDims: { number }, -- [class + 1] + partitionClass: { number }, + classDims: { number }, classSubs: { number }, classMaster: { number }, - subBooks: { { number } }, -- [class + 1][sub + 1] = book (0-based) or -1 + subBooks: { { number } }, multiplier: number, - xlist: { number }, -- [j + 1] + xlist: { number }, values: number, - sorted: { number }, -- point indices (0-based) by increasing x - low: { number }, -- neighbours, [j + 1] (0-based indices) + sorted: { number }, + low: { number }, high: { number }, } @@ -44,16 +42,16 @@ export type Residue = { partSize: number, classifications: number, classbook: number, - books: { { number } }, -- [class + 1][pass + 1] = book or -1 - classdata: { { number } }, -- [classbook entry + 1][k + 1] = class + books: { { number } }, + classdata: { { number } }, } export type Mapping = { submaps: number, couplingSteps: number, - magnitude: { number }, -- [step + 1] channel (0-based) + magnitude: { number }, angle: { number }, - mux: { number }, -- [channel + 1] submap (0-based) + mux: { number }, submapFloor: { number }, submapResidue: { number }, } @@ -75,7 +73,6 @@ local function isVorbis(b: buffer, o: number, n: number, kind: number): boolean 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" @@ -111,7 +108,6 @@ function Setup.ident(b: buffer, o: number, n: number): (Ident?, string?) 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 @@ -148,14 +144,12 @@ function Setup.comment(b: buffer, o: number, n: number): (string?, { string }?) 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 @@ -172,7 +166,6 @@ function Setup.setup(b: buffer, o: number, n: number, id: Ident): (Setup?, strin return nil, "bad time domain transform" end end - -- floors local floors: { Floor1 } = {} local maxValues = 0 local nfloors = bits(br, 6) + 1 @@ -272,7 +265,6 @@ function Setup.setup(b: buffer, o: number, n: number, id: Ident): (Setup?, strin maxValues = values end end - -- residues local residues: { Residue } = {} local nres = bits(br, 6) + 1 for i = 1, nres do @@ -341,7 +333,6 @@ function Setup.setup(b: buffer, o: number, n: number, id: Ident): (Setup?, strin classdata = classdata, } end - -- mappings local mappings: { Mapping } = {} local nmaps = bits(br, 6) + 1 local chBits = ilog(channels - 1) @@ -396,7 +387,6 @@ function Setup.setup(b: buffer, o: number, n: number, id: Ident): (Setup?, strin submapResidue = sr, } end - -- modes local modes: { Mode } = {} local nmodes = bits(br, 6) + 1 for i = 1, nmodes do diff --git a/src/Rosetta/codecs/audio/Vorbis/Tables.luau b/src/Rosetta/codecs/audio/Vorbis/Tables.luau index 55e3ec9..8ad2bad 100644 --- a/src/Rosetta/codecs/audio/Vorbis/Tables.luau +++ b/src/Rosetta/codecs/audio/Vorbis/Tables.luau @@ -1,6 +1,6 @@ --!strict --- codecs/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). +-- codecs/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). 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, diff --git a/src/Rosetta/codecs/audio/Vorbis/init.luau b/src/Rosetta/codecs/audio/Vorbis/init.luau index 6087ba0..af5104b 100644 --- a/src/Rosetta/codecs/audio/Vorbis/init.luau +++ b/src/Rosetta/codecs/audio/Vorbis/init.luau @@ -1,8 +1,6 @@ --!strict --- codecs/audio/Vorbis: the Vorbis I decoder without its container: identification / comment / setup headers (Setup), --- codebooks (Codebook), audio packets to PCM (Packet: floors 0 / 1, residues 0 / 1 / 2, coupling, the IMDCT through --- codecs/audio/Mdct) and the shared tables. A Luau port of stb_vorbis 1.22 (public domain / MIT, --- licenses/stb_vorbis-LICENSE.txt). Ogg Vorbis (pages, granules, seeking) and the encoder are audio/vorbis. +-- codecs/audio/Vorbis: the Vorbis I decoder without its container. +-- A Luau port of stb_vorbis 1.22 (public domain / MIT, licenses/stb_vorbis-LICENSE.txt). local Vorbis = { Setup = require("@rosetta/codecs/audio/Vorbis/Setup"), Codebook = require("@rosetta/codecs/audio/Vorbis/Codebook"), diff --git a/src/Rosetta/codecs/audio/VorbisComment.luau b/src/Rosetta/codecs/audio/VorbisComment.luau index fa1b6cc..cac6f5a 100644 --- a/src/Rosetta/codecs/audio/VorbisComment.luau +++ b/src/Rosetta/codecs/audio/VorbisComment.luau @@ -1,32 +1,21 @@ --!strict --- codecs/audio/VorbisComment: Vorbis comment fields ("KEY=value", the tag block of Vorbis, Opus and FLAC) <-> Types.Tags. --- Tag keys are lower case everywhere in rosetta (the same names ID3 / MP4 / RIFF INFO map to): title, artist, --- album, albumartist, date, genre, track, tracktotal, disc, disctotal, comment, composer, ...; TRACKNUMBER becomes --- track, DISCNUMBER disc, DESCRIPTION comment, other fields their lower-cased name. Repeated fields are joined with --- "; " in tags; the raw fields stay available (decoders put them in meta.source.comments). Shared so the three --- formats read and write tags the same way. Never throws. --- --- local tags, raw = VorbisComment.tags({ "TITLE=x", "TRACKNUMBER=3" }) -- { title = "x", track = "3" }, raw list --- local fields = VorbisComment.fields(tags) -- sorted { "TITLE=x", "TRACKNUMBER=3" } +-- codecs/audio/VorbisComment: Vorbis comment fields ("KEY=value"; Vorbis, Opus, FLAC) <-> Types.Tags. local VorbisComment = {} -export type Field = { key: string, value: string } -- key as written (upper-cased), value +export type Field = { key: string, value: string } local TO_TAG: { [string]: string } = { tracknumber = "track", discnumber = "disc", description = "comment" } local TO_FIELD: { [string]: string } = { track = "TRACKNUMBER", disc = "DISCNUMBER" } --- tagKey(fieldName) -> the Types.Tags key function VorbisComment.tagKey(name: string): string local k = string.lower(name) return TO_TAG[k] or k end --- fieldName(tagKey) -> the Vorbis comment field name function VorbisComment.fieldName(key: string): string return TO_FIELD[key] or string.upper(key) end --- tags(list of "KEY=value") -> Types.Tags, { Field } (entries without "=" are skipped) function VorbisComment.tags(comments: { string }): ({ [string]: string }, { Field }) local tags: { [string]: string } = {} local raw: { Field } = {} @@ -43,7 +32,6 @@ function VorbisComment.tags(comments: { string }): ({ [string]: string }, { Fiel return tags, raw end --- fields(tags) -> "KEY=value" strings in key order (string keys and values only) function VorbisComment.fields(tags: { [any]: any }): { string } local keys = {} for k, v in tags do diff --git a/src/Rosetta/codecs/audio/WavPack/Block.luau b/src/Rosetta/codecs/audio/WavPack/Block.luau index 7383e3f..c619f2e 100644 --- a/src/Rosetta/codecs/audio/WavPack/Block.luau +++ b/src/Rosetta/codecs/audio/WavPack/Block.luau @@ -1,13 +1,9 @@ --!strict --!native --!optimize 2 --- codecs/audio/WavPack/Block: one WavPack 4 / 5 block (one mono or stereo stream of a frame) -> samples. Ported from --- WavPack 5.9.0 (David Bryant, BSD 3-clause, licenses/wavpack-LICENSE.txt): unpack.c (the decorrelation passes, joint --- stereo, the hybrid lossy and hybrid lossless (+ wvc) paths with noise shaping and cross decorrelation, fixup_samples), --- read_words.c (the median-adaptive entropy decoder: get_words_lossless, get_word, read_code), unpack_floats.c, --- decorr_utils.c / entropy_utils.c (the metadata) and open_utils.c (metadata parsing, the block checksum). The block --- CRC (and the wvx CRC) is checked. Not ported: DSD blocks (UNSUPPORTED), pre-4.0 streams, the lossy "mute" heuristics. --- Never throws: returns nil, message. +-- codecs/audio/WavPack/Block: one WavPack 4 / 5 block (one mono or stereo stream of a frame) -> samples. +-- Ported from WavPack 5.9.0 (David Bryant, BSD 3-clause, licenses/wavpack-LICENSE.txt): unpack.c, read_words.c, +-- unpack_floats.c, decorr_utils.c / entropy_utils.c, open_utils.c. DSD blocks are UNSUPPORTED. local Tables = require("@rosetta/codecs/audio/WavPack/Tables") local readu8, readi8, readu16, readi16, readu32 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32 @@ -19,11 +15,10 @@ local sign, clamp = math.sign, math.clamp local Block = {} local TWO32 = 4294967296 -local P2: { number } = table.create(34, 0) -- P2[k + 1] = 2^k +local P2: { number } = table.create(34, 0) for i = 0, 33 do P2[i + 1] = 2 ^ i end --- ONES[b + 1]: the number of trailing 1 bits of the byte b local ONES: { number } = table.create(256, 0) for b = 0, 255 do local n, v = 0, b @@ -34,18 +29,15 @@ for b = 0, 255 do ONES[b + 1] = n end --- header flags local MONO_FLAG, HYBRID, JOINT, CROSS, SHAPE, FLOAT, INT32 = 4, 8, 0x10, 0x20, 0x40, 0x80, 0x100 local HBITRATE, HBALANCE, NEW_SHAPING, FALSE_STEREO, DSD = 0x200, 0x400, 0x20000000, 0x40000000, 0x80000000 local FLOAT_SHIFT_ONES, FLOAT_SHIFT_SAME, FLOAT_SHIFT_SENT, FLOAT_ZEROS_SENT, FLOAT_NEG_ZEROS = 1, 2, 4, 8, 0x10 local PAD = 64 -- zero bytes after each copied bitstream: reads past the end stay in the buffer -local MAX_SAMPLES = 2 ^ 20 -- per block +local MAX_SAMPLES = 2 ^ 20 local D2, D1 = 17, 9 -- the first data index of the work table (stereo / mono): 8 frames of history in front --- ------------------------------------------------------------------------------------------------ metadata export type Meta = { [number]: number } -- id -> offset; id + 256 -> byte length --- meta(buf, p, size) -> Meta | nil, message: the metadata sub-blocks of the block at p (header included in size) function Block.meta(buf: buffer, p: number, size: number): (Meta?, string?) local m: Meta = {} local q, stop = p + 32, p + size @@ -80,7 +72,6 @@ function Block.meta(buf: buffer, p: number, size: number): (Meta?, string?) return m, nil end --- checksum(buf, p, size, m) -> true | false: the ID_BLOCK_CHECKSUM (when there is one) matches function Block.checksum(buf: buffer, p: number, m: Meta): boolean local o = m[0x2F] if not o then @@ -102,7 +93,6 @@ function Block.checksum(buf: buffer, p: number, m: Meta): boolean return readu16(buf, o) == band(csum, 0xFFFF) end --- ------------------------------------------------------------------------------------------------ state export type Reader = { b: buffer, p: number, e: number, n: number } export type State = { [string]: any } @@ -130,7 +120,6 @@ function Block.state(): State } end --- open a bitstream: the bytes [o, o + len) copied with PAD zero bytes after them local function openReader(R: Reader, buf: buffer, o: number, len: number) if buffer.len(R.b) < len + PAD then R.b = buffer.create(len + PAD + 1024) @@ -143,8 +132,6 @@ local function openReader(R: Reader, buf: buffer, o: number, len: number) R.n = len + PAD end --- ------------------------------------------------------------------------------------------------ bit reading --- bits(R, n) -> the next n (<= 32) bits, LSB first local function bits(R: Reader, n: number): number if n <= 0 then return 0 @@ -152,7 +139,7 @@ local function bits(R: Reader, n: number): number local p = R.p local byte = rshift(p, 3) if byte + 8 > R.n then - R.p = R.e + 1 -- overrun: the caller's end check fails + R.p = R.e + 1 return 0 end local b = R.b @@ -170,8 +157,6 @@ local function bit(R: Reader): number return bits(R, 1) end --- trailing(R, max) -> the number of 1 bits from the read position (up to max; a byte at a time), consumed with the 0 --- after them when fewer than max local function trailing(R: Reader, max: number): number local c = 0 while c < max do @@ -193,7 +178,6 @@ local function trailing(R: Reader, max: number): number c += 8 R.p = p + 8 end - -- (max reached inside a run of 8: give back the extra ones) R.p -= c - max return max end @@ -210,7 +194,7 @@ local function gamma(R: Reader): number? return bits(R, c - 1) + P2[c] end --- readCode(R, maxcode) -> 0 .. maxcode (read_code) +-- read_code local function readCode(R: Reader, maxcode: number): number if maxcode < 2 then return if maxcode == 1 then bits(R, 1) else 0 @@ -240,16 +224,13 @@ local function onesCount(R: Reader): number? return c end --- ------------------------------------------------------------------------------------------------ lossless entropy --- wordsLossless(st, n, stereo) -> true | nil: n samples (n * 2 when stereo) into st.W from the data index (the hot --- loop of get_words_lossless, with the bit reader in locals) +-- get_words_lossless local function wordsLossless(st: State, count: number, d: number): boolean local R: Reader = st.R1 local b, pos, lim = R.b, R.p, R.e local W = st.W local med = st.med local stereo = d == D2 - -- (a0, a1, a2): the current channel's medians, (c0, c1, c2) the other's; swapped every sample when stereo local a0, a1, a2, c0, c1, c2 = med[4], med[5], med[6], med[1], med[2], med[3] if not stereo then a0, a1, a2, c0, c1, c2 = med[1], med[2], med[3], 0, 0, 0 @@ -408,7 +389,6 @@ local function wordsLossless(st: State, count: number, d: number): boolean return pos <= lim end --- ------------------------------------------------------------------------------------------------ hybrid entropy local function updateErrorLimit(st: State, flags: number, mono: boolean) local bacc, bdelta, slow, limit = st.bacc, st.bdelta, st.slow, st.limit bacc[1] = (bacc[1] + bdelta[1]) % TWO32 @@ -448,7 +428,7 @@ local function updateErrorLimit(st: State, flags: number, mono: boolean) end end --- getWord(st, chan, flags, mono) -> value, correction | nil (get_word; chan 0 / 1) +-- get_word local function getWord(st: State, chan: number, flags: number, mono: boolean): (number?, number) local R: Reader = st.R1 local med = st.med @@ -564,7 +544,6 @@ local function getWord(st: State, chan: number, flags: number, mono: boolean): ( return if sign == 1 then -mid - 1 else mid, correction end --- ------------------------------------------------------------------------------------------------ decorrelation -- the decorrelation passes over the whole block (stereo, from W[D2]): unpack.c decorr_stereo_pass local function passesStereo(st: State, n: number) local W = st.W @@ -679,7 +658,6 @@ local function passesMono(st: State, n: number) end end --- ------------------------------------------------------------------------------------------------ hybrid lossless local function shaped(st: State, c: number, flags: number, correction: number): number -- returns the value to subtract (temp) and updates the error state (noise shaping, unpack.c) local sacc, sdelta, err = st.sacc, st.sdelta, st.err @@ -872,7 +850,6 @@ local function hybridStereo(st: State, n: number, flags: number): boolean return true end --- ------------------------------------------------------------------------------------------------ metadata -> state local function readMeta(st: State, buf: buffer, m: Meta, flags: number, version: number): string? local mono = band(flags, MONO_FLAG + FALSE_STEREO) ~= 0 local o = m[2] @@ -1058,8 +1035,7 @@ local function readMeta(st: State, buf: buffer, m: Meta, flags: number, version: return nil end --- ------------------------------------------------------------------------------------------------ fixup + output --- the float conversion of one value (float_values; R = the wvx stream or nil) +-- float_values (R = the wvx stream or nil) local function floatValue(st: State, v: number, R: Reader?): number local fflags, exp = st.fflags, st.fmaxexp local mant, e, sign = 0, 0, 0 @@ -1160,7 +1136,7 @@ local function floatValue(st: State, v: number, R: Reader?): number return readf32(sc, 0) end --- emit: fixup_samples + false stereo + interleave into P (stride C, first channel c0 0-based) +-- fixup_samples + false stereo + interleave local function emit(st: State, flags: number, n: number, d: number, P: { number }, c0: number, C: number, lossy: boolean) local W = st.W local s = if d == D2 then 2 else 1 @@ -1263,7 +1239,6 @@ local function emit(st: State, flags: number, n: number, d: number, P: { number end end end - -- interleave if s == 2 then if c0 == 0 and C == 2 then for k = 0, count - 1 do @@ -1296,9 +1271,6 @@ local function emit(st: State, flags: number, n: number, d: number, P: { number end end --- ------------------------------------------------------------------------------------------------ decode --- decode(st, buf, p, size, P, c0, C, cbuf?, cp?, csize?) -> channels written (1 / 2) | nil, message: the block at p --- (header included in size) into P (interleaved, stride C, from channel c0), with its correction block if given function Block.decode(st: State, buf: buffer, p: number, size: number, P: { number }, c0: number, C: number, cbuf: buffer?, cp: number?, csize: number?): (number?, string?) local version = readu16(buf, p + 8) local n = readu32(buf, p + 20) @@ -1332,7 +1304,6 @@ function Block.decode(st: State, buf: buffer, p: number, size: number, P: { numb cm, cb, hasC = cmeta, cbuf, true crcWant = readu32(cbuf, cp + 28) end - -- reset st.nterms = 0 local sA, sB, wA, wB = st.sA, st.sB, st.wA, st.wB for k = 1, 128 do @@ -1368,7 +1339,6 @@ function Block.decode(st: State, buf: buffer, p: number, size: number, P: { numb if n == 0 then return out, nil end - -- bitstreams local o = m[0xA] if not o or m[0xA + 256] == 0 or m[0xA + 256] % 2 == 1 then return nil, "no audio bitstream" diff --git a/src/Rosetta/codecs/audio/WavPack/Tables.luau b/src/Rosetta/codecs/audio/WavPack/Tables.luau index e06596d..bac9a15 100644 --- a/src/Rosetta/codecs/audio/WavPack/Tables.luau +++ b/src/Rosetta/codecs/audio/WavPack/Tables.luau @@ -1,13 +1,12 @@ --!strict --!native --!optimize 2 --- codecs/audio/WavPack/Tables: the WavPack log2 / exp2 tables and the conversions built on them (wp_log2, wp_exp2s, --- restore_weight). Ported from WavPack 5.9.0 entropy_utils.c (David Bryant, BSD 3-clause, licenses/wavpack-LICENSE.txt). +-- codecs/audio/WavPack/Tables: the log2 / exp2 tables, wp_log2, wp_exp2s, restore_weight. Ported from WavPack 5.9.0 +-- entropy_utils.c (David Bryant, BSD 3-clause, licenses/wavpack-LICENSE.txt). local band, rshift, lshift, countlz = bit32.band, bit32.rshift, bit32.lshift, bit32.countlz local Tables = {} --- LOG2[x + 1], EXP2[x + 1] for x = 0 .. 255 local LOG2: { number } = { 0, 1, 3, 4, 6, 7, 9, 10, 11, 13, 14, 16, 17, 18, 20, 21, 22, 24, 25, 26, 28, 29, 30, 32, 33, 34, 36, 37, 38, 40, 41, 42, 44, 45, 46, 47, 49, 50, 51, 52, 54, 55, 56, 57, 59, 60, 61, 62, 63, 65, 66, 67, 68, 69, 71, 72, 73, 74, 75, 77, 78, 79, 80, 81, @@ -29,7 +28,6 @@ local EXP2: { number } = { 214, 215, 216, 217, 219, 220, 221, 222, 224, 225, 226, 228, 229, 230, 232, 233, 234, 236, 237, 238, 240, 241, 242, 244, 245, 246, 248, 249, 250, 252, 253, 255, } --- exp2s(log) -> the int32 the signed log stands for (wp_exp2s) function Tables.exp2s(lg: number): number if lg < 0 then local v = Tables.exp2s(-lg) @@ -42,7 +40,6 @@ function Tables.exp2s(lg: number): number return if r >= 2147483648 then r - 4294967296 else r end --- log2(v) -> wp_log2 of the uint32 v function Tables.log2(v: number): number v = (v + rshift(v, 9)) % 4294967296 if v < 256 then @@ -53,7 +50,6 @@ function Tables.log2(v: number): number return dbits * 256 + LOG2[band(rshift(v, dbits - 9), 255) + 1] end --- restoreWeight(signed byte) -> the decorrelation weight (restore_weight) function Tables.restoreWeight(w: number): number local r = w * 8 if r > 0 then diff --git a/src/Rosetta/codecs/audio/WavPack/init.luau b/src/Rosetta/codecs/audio/WavPack/init.luau index a9e7a7c..d1ce0f8 100644 --- a/src/Rosetta/codecs/audio/WavPack/init.luau +++ b/src/Rosetta/codecs/audio/WavPack/init.luau @@ -1,18 +1,7 @@ --!strict --- codecs/audio/WavPack: the WavPack 4 / 5 audio codec (the blocks of .wv files, and of WavPack in Matroska). A codec --- (layer 3). Ported from WavPack 5.9.0 (David Bryant, BSD 3-clause, licenses/wavpack-LICENSE.txt); the hot code is in --- codecs/audio/WavPack/Block. Lossless and hybrid (lossy, and lossless with the .wvc correction blocks), integer 8 - 32 --- bit (with the extended int32 modes) and 32-bit float, mono / stereo / multichannel (one block per mono or stereo --- stream, INITIAL .. FINAL), every decorrelation pass (terms 1 - 8, 17, 18, -1 .. -3), joint stereo, cross --- decorrelation, noise shaping, block CRCs and block checksums. Not supported: DSD, pre-4.0 streams (version < 0x402). --- --- local h, err = WavPack.header(buf, at, limit) -- the 32-byte block header at `at` (nil, message if none) --- local info, err = WavPack.info(buf, at, limit) -- stream facts from the first audio block (channels, rate, ...) --- local dec = WavPack.decoder(info.channels) --- local frames, err = dec:frame(buf, blocks, cbuf?, cblocks?) -- blocks = { offset, ... } of one frame (+ wvc) --- -- dec.pcm: interleaved samples (integers in the container range, or float values), WAV channel order --- --- Never throws: bad data returns nil, Err. +-- codecs/audio/WavPack: the WavPack 4 / 5 audio codec (the blocks of .wv files, and of WavPack in Matroska). +-- Ported from WavPack 5.9.0 (David Bryant, BSD 3-clause, licenses/wavpack-LICENSE.txt). Not supported: DSD, pre-4.0 +-- streams (version < 0x402). local Err = require("@rosetta/core/Err") local Block = require("@rosetta/codecs/audio/WavPack/Block") @@ -32,7 +21,6 @@ local RATES = { 6000, 8000, 9600, 11025, 12000, 16000, 22050, 24000, 32000, 4410 WavPack.MONO, WavPack.HYBRID, WavPack.FLOAT, WavPack.INITIAL, WavPack.FINAL = 4, 8, 0x80, 0x800, 0x1000 WavPack.DSD = 0x80000000 --- header(buf, at, limit?) -> Header | nil, message: a valid "wvpk" block header at byte `at` whose block ends by limit function WavPack.header(buf: buffer, at: number, limit: number?): (Header?, string?) local lim = math.min(limit or buffer.len(buf), buffer.len(buf)) if at < 0 or at + 32 > lim then @@ -70,15 +58,14 @@ export type Info = { channels: number, channelMask: number, sampleRate: number, - bitsPerSample: number, -- the source depth (container bytes * 8 - shift) - bytesPerSample: number, -- the container: 1 .. 4 + bitsPerSample: number, + bytesPerSample: number, float: boolean, hybrid: boolean, - md5: string?, -- 32 hex digits when stored + md5: string?, version: number, } --- info(buf, at, limit?) -> Info | nil, Err: the facts of the stream whose first audio block is at `at` function WavPack.info(buf: buffer, at: number, limit: number?): (Info?, Err.Err?) local h, herr = WavPack.header(buf, at, limit) if not h then @@ -146,7 +133,6 @@ function WavPack.info(buf: buffer, at: number, limit: number?): (Info?, Err.Err? return info, nil end --- md5(buf, at, limit?) -> 32 hex digits | nil: an ID_MD5_CHECKSUM in the block at `at` function WavPack.md5(buf: buffer, at: number, limit: number?): string? local h = WavPack.header(buf, at, limit) if not h then @@ -167,16 +153,13 @@ function WavPack.md5(buf: buffer, at: number, limit: number?): string? return table.concat(hex) end --- ------------------------------------------------------------------------------------------------ decoder export type Decoder = { channels: number, - pcm: { number }, -- the last frame's samples, interleaved (integers in the container range, or floats) + pcm: { number }, frame: (self: Decoder, buf: buffer, blocks: { number }, cbuf: buffer?, cblocks: { number }?) -> (number?, Err.Err?), state: Block.State, } --- frame(buf, blocks, cbuf?, cblocks?) -> frames | nil, Err: decode one frame (the blocks of one sample range, one per --- mono / stereo stream, in channel order) into dec.pcm; cblocks are the matching .wvc blocks (hybrid lossless) local function frame(self: Decoder, buf: buffer, blocks: { number }, cbuf: buffer?, cblocks: { number }?): (number?, Err.Err?) local C = self.channels local n = -1 @@ -222,7 +205,6 @@ local function frame(self: Decoder, buf: buffer, blocks: { number }, cbuf: buffe return n, nil end --- decoder(channels) -> Decoder function WavPack.decoder(channels: number): Decoder return { channels = channels, diff --git a/src/Rosetta/codecs/compress/Brotli/Decode.luau b/src/Rosetta/codecs/compress/Brotli/Decode.luau index 08f7705..6afe00e 100644 --- a/src/Rosetta/codecs/compress/Brotli/Decode.luau +++ b/src/Rosetta/codecs/compress/Brotli/Decode.luau @@ -1,18 +1,9 @@ --!strict --!native --!optimize 2 --- codecs/compress/Brotli/Decode: a Brotli (RFC 7932) decoder over a whole in-memory stream. Written from the RFC, with the --- reference decoder (google/brotli c/dec/decode.c, MIT) as the authority on edge cases (simple prefix code alphabet --- widths, repeat codes, padding checks, the large-window extension). Supports every meta-block kind (compressed, --- uncompressed, metadata), block types / counts, the four literal context modes, context maps with RLE and inverse --- move-to-front, NPOSTFIX / NDIRECT distances, the static dictionary with all 121 transforms, window sizes 10..24 and --- large windows (10..30). The whole output is kept, so the window is only used to tell copies from dictionary words. --- --- Bits are read LSB first into a bit buffer of up to 32 bits. Prefix codes decode through tables indexed by the next --- 8 bits; entries are symbol * 32 + length (length < 16), or a link offset * 32 + 16 + subtable bits. --- --- Nothing here throws: every buffer access is checked or in range by construction (the output buffer is sized for each --- meta-block before it is decoded); bad data returns nil, message. +-- codecs/compress/Brotli/Decode: a Brotli (RFC 7932) decoder, with the large-window extension (windows 10..30). +-- Written from the RFC, with google/brotli c/dec/decode.c (MIT) as the authority on edge cases. +-- Prefix table entry: symbol * 32 + length (length < 16), or a link offset * 32 + 16 + subtable bits (8-bit primary). local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift local readu8, readu16, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32 local bcreate, bcopy, blen, bfill = buffer.create, buffer.copy, buffer.len, buffer.fill @@ -27,7 +18,6 @@ export type Static = { transforms: { number }, -- 121 x (prefix id, type, suffix id) } --- ------------------------------------------------------------------------------------------------ constants local CL_ORDER = { 1, 2, 3, 4, 0, 5, 17, 6, 16, 7, 8, 9, 10, 11, 12, 13, 14, 15 } local CLP_LEN = { 2, 2, 2, 3, 2, 2, 2, 4, 2, 2, 2, 3, 2, 2, 2, 4 } local CLP_VAL = { 0, 4, 3, 2, 0, 4, 3, 1, 0, 4, 3, 2, 0, 4, 3, 5 } @@ -54,7 +44,6 @@ end local NTRANSFORMS = 121 local MAX_ALLOWED_DISTANCE = 0x7FFFFFFC --- 8-bit reversal local REV8 = bcreate(256) for i = 0, 255 do local r, v = 0, i @@ -65,19 +54,15 @@ for i = 0, 255 do writeu8(REV8, i, r) end local function reverse(code: number, len: number): number - -- len <= 15 local r = readu8(REV8, band(code, 255)) * 256 + readu8(REV8, band(rshift(code, 8), 255)) return rshift(r, 16 - len) end --- ------------------------------------------------------------------------------------------------ prefix tables local count = table.create(16, 0) local nextc = table.create(16, 0) local subBits = table.create(256, 0) local subOff = table.create(256, 0) --- tableSize(lens, n) -> the entries build() will write (256 + subtables), or -1 for an over-subscribed set. --- Also leaves count / nextc / subBits ready for build(). local function prepare(lens: buffer, n: number): number for l = 1, 16 do count[l] = 0 @@ -135,7 +120,6 @@ local function prepare(lens: buffer, n: number): number return size end --- build(lens, n, T, at): the table prepared by prepare() at entry offset `at` of T (T must have room) local function build(lens: buffer, n: number, T: buffer, at: number) local single = -1 local used = 0 @@ -188,8 +172,7 @@ local function build(lens: buffer, n: number, T: buffer, at: number) end end --- the largest distance alphabet whose distances stay under MAX_ALLOWED_DISTANCE (large windows); after the reference --- decoder's BrotliCalculateDistanceCodeLimit +-- largest distance alphabet under MAX_ALLOWED_DISTANCE, as the reference's BrotliCalculateDistanceCodeLimit local function distanceLimit(maxDistance: number, npostfix: number, ndirect: number): number if maxDistance <= ndirect then return maxDistance + 16 @@ -213,8 +196,6 @@ local function distanceLimit(maxDistance: number, npostfix: number, ndirect: num return bor(lshift(group, npostfix), postfix) + ndirect + 16 + 1 end --- ------------------------------------------------------------------------------------------------ decoder --- decompress(src, off, len, maxBytes, S, largeWindow) -> out, n, consumedEnd | nil, message function Decode.decompress(src: buffer, off: number, len: number, maxBytes: number, S: Static, largeWindow: boolean): (buffer?, any, number?) local lim = off + len local ip = off @@ -251,7 +232,6 @@ function Decode.decompress(src: buffer, off: number, len: number, maxBytes: numb return (ip - lim) * 8 > bc end - -- prefix tables of the current meta-block: T (u32 entries), tpos entries used local T = bcreate(4096 * 4) local tpos = 0 local LENS = bcreate(1128) @@ -273,7 +253,6 @@ function Decode.decompress(src: buffer, off: number, len: number, maxBytes: numb return rshift(e, 5) end - -- install(n) -> base: the table for LENS[0 .. n - 1] appended to T, or -1 local function install(n: number): number local size = prepare(LENS, n) if size < 0 then @@ -291,7 +270,6 @@ function Decode.decompress(src: buffer, off: number, len: number, maxBytes: numb return base end - -- readCode(alphabetMax, limit) -> table base | -1 (corrupt) local function readCode(alphabetMax: number, limit: number): number bfill(LENS, 0, 0, limit) local hskip = bits(2) @@ -447,7 +425,6 @@ function Decode.decompress(src: buffer, off: number, len: number, maxBytes: numb return BL_OFF[code + 1] + bits(BL_BITS[code + 1]) end - -- readContextMap(size) -> ntrees, map buffer | -1 local function readContextMap(size: number): (number, buffer) local ntrees = varLen8() + 1 local map = bcreate(size) @@ -475,7 +452,7 @@ function Decode.decompress(src: buffer, off: number, len: number, maxBytes: numb if i + reps > size then return -1, map end - i += reps -- zeros (map is zero-filled) + i += reps end if overrun() then return -1, map @@ -499,7 +476,7 @@ function Decode.decompress(src: buffer, off: number, len: number, maxBytes: numb return ntrees, map end - -- ------------------------------------------------------------------ stream header + -- RFC 7932 9.1: stream header fill() local wbits local large = false @@ -545,7 +522,7 @@ function Decode.decompress(src: buffer, off: number, len: number, maxBytes: numb local d0, d1, d2, d3 = 4, 11, 15, 16 while true do - -- ---------------------------------------------------------------- meta-block header + -- RFC 7932 9.2: meta-block header if overrun() then return nil, "truncated stream" end @@ -626,7 +603,7 @@ function Decode.decompress(src: buffer, off: number, len: number, maxBytes: numb continue end - -- ---------------------------------------------------------------- compressed meta-block + -- RFC 7932 9.3: compressed meta-block data tpos = 0 -- block types / counts: 1 = literals, 2 = commands, 3 = distances local nbtL, nbtI, nbtD = 1, 1, 1 @@ -673,7 +650,6 @@ function Decode.decompress(src: buffer, off: number, len: number, maxBytes: numb if ntreesD < 0 then return nil, "bad distance context map" end - -- the tree groups local litBase = table.create(ntreesL, 0) for i = 1, ntreesL do local b = readCode(256, 256) @@ -703,7 +679,6 @@ function Decode.decompress(src: buffer, off: number, len: number, maxBytes: numb if overrun() then return nil, "truncated meta-block header" end - -- context map slices resolved to table bases local litMap = table.create(64 * nbtL, 0) for i = 0, 64 * nbtL - 1 do litMap[i + 1] = litBase[readu8(cmapL, i) + 1] @@ -713,7 +688,6 @@ function Decode.decompress(src: buffer, off: number, len: number, maxBytes: numb distMap[i + 1] = distBase[readu8(cmapD, i) + 1] end - -- block state: current type, previous type local typeL, prevL = 0, 1 local typeI, prevI = 0, 1 local typeD, prevD = 0, 1 @@ -727,7 +701,6 @@ function Decode.decompress(src: buffer, off: number, len: number, maxBytes: numb if ip > lim + 4 then return nil, "truncated stream" end - -- command block switch if cntI == 0 then local t = decodeSym(btTreeI) if t == 1 then @@ -759,7 +732,6 @@ function Decode.decompress(src: buffer, off: number, len: number, maxBytes: numb if ce > 0 then cpyLen += bits(ce) end - -- literals if insLen > remaining then return nil, "insert past the meta-block end" end @@ -815,7 +787,6 @@ function Decode.decompress(src: buffer, off: number, len: number, maxBytes: numb break end end - -- distance local dist local push = true if cell < 2 then diff --git a/src/Rosetta/codecs/compress/Brotli/init.luau b/src/Rosetta/codecs/compress/Brotli/init.luau index aa0b98b..698ea50 100644 --- a/src/Rosetta/codecs/compress/Brotli/init.luau +++ b/src/Rosetta/codecs/compress/Brotli/init.luau @@ -1,16 +1,7 @@ --!strict --- codecs/compress/Brotli: Brotli (RFC 7932) decompression. A codec (layer 3): archive/br and font/woff2 build on it. Written --- from the RFC (decoder in codecs/compress/Brotli/Decode); the static dictionary, context table and word transforms come from --- google/brotli (MIT, licenses/brotli-LICENSE.txt) through codecs/compress/Brotli/Static (tools/brotli_static.py). --- Supports every RFC 7932 stream (window sizes 10..24, metadata / uncompressed / compressed meta-blocks, the static --- dictionary with all 121 transforms) and the large-window extension (opts.largeWindow). Not supported: compression, --- shared / compound dictionaries (draft "shared brotli"). --- --- local Brotli = require("@rosetta/codecs/compress/Brotli") --- local out, consumedEnd = Brotli.decompress(buf) -- buffer | string --- local out, err = Brotli.decompress(buf, offset, length, { maxBytes = 2^24 }) --- --- Never throws: bad data and bad arguments return nil, Err (TRUNCATED / CORRUPT / LIMIT / UNSUPPORTED / ARG). +-- codecs/compress/Brotli: Brotli (RFC 7932) decompression, with the large-window extension. +-- The static dictionary, context table and word transforms come from google/brotli (MIT, licenses/brotli-LICENSE.txt) +-- through codecs/compress/Brotli/Static (tools/brotli_static.py). local Err = require("@rosetta/core/Err") local Bytes = require("@rosetta/core/Bytes") local Crc32 = require("@rosetta/core/Crc32") @@ -22,11 +13,10 @@ local StaticData = require("@rosetta/codecs/compress/Brotli/Static") local Brotli = {} export type Options = { - maxBytes: number?, -- refuse output larger than this (default 2^30) - largeWindow: boolean?, -- accept the large-window extension (windows up to 2^30; default true) + maxBytes: number?, + largeWindow: boolean?, } --- ------------------------------------------------------------------------------------------------ static data -- the tables are base64 text (trusted, generated by tools/brotli_static.py) local function unbase64(s: string): buffer return Base64.decode(s) or buffer.create(0) @@ -34,7 +24,6 @@ end local static: Decode.Static? = nil --- tables() -> the decoded static data (inflated once, on first use) local function tables(): (Decode.Static?, Err.Err?) if static then return static, nil @@ -57,16 +46,11 @@ local function tables(): (Decode.Static?, Err.Err?) return static, nil end --- dictionary() -> the 122784-byte RFC 7932 static dictionary (for tests and encoders) function Brotli.dictionary(): buffer? local s = tables() return if s then s.dictionary else nil end --- ------------------------------------------------------------------------------------------------ decompress - --- decompress(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err. consumedEnd: the input offset just past --- the stream (trailing bytes are ignored). function Brotli.decompress(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any) local b, o, l, aerr = Bytes.span("Brotli.decompress", buf, offset, length) if not b then diff --git a/src/Rosetta/codecs/compress/Bzip2/Decode.luau b/src/Rosetta/codecs/compress/Bzip2/Decode.luau index e281116..0ad4ab1 100644 --- a/src/Rosetta/codecs/compress/Bzip2/Decode.luau +++ b/src/Rosetta/codecs/compress/Bzip2/Decode.luau @@ -1,16 +1,9 @@ --!strict --!native --!optimize 2 --- codecs/compress/Bzip2/Decode: bzip2 stream decoder (Julian Seward's format, as documented by the bzip2 1.0.x sources and --- Joe Tsai's "bzip2 format specification"). Written from the format description; no third-party code. --- Per block: MSB-first bit reader on a local 32-bit bit buffer, Huffman groups (10-bit lookup + canonical fallback for --- codes up to 20 bits), MTF + RUNA/RUNB, inverse BWT through one u32 vector (byte in the low 8 bits, next index --- above), RLE1 undo with the block CRC (CRC-32/BZIP2, MSB first) computed on the way out; the combined stream CRC is --- checked at the end-of-stream marker. Concatenated streams are decoded one after the other. --- Not supported: randomised blocks (written only by bzip2 0.9.0 and older). --- --- Never throws: every buffer access is in range by construction; failures return nil, message, kind --- ("truncated" | "corrupt" | "checksum" | "limit" | "unsupported"). +-- codecs/compress/Bzip2/Decode: bzip2 stream decoder (bzip2 1.0.x sources, Joe Tsai's "bzip2 format specification"). +-- Huffman groups, MTF + RUNA/RUNB, inverse BWT, RLE1; block CRC-32/BZIP2 (MSB first) and the combined stream CRC. +-- Written from the format description; no third-party code. local Crc32 = require("@rosetta/core/Crc32") local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift local readu8, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu8, buffer.writeu32 @@ -27,25 +20,23 @@ for i = 0, 32 do MASK[i + 1] = if i == 32 then 0xFFFFFFFF else 2 ^ i - 1 end -local PBITS = 10 -- primary lookup width +local PBITS = 10 local PSIZE = 1024 local MAXGROUPS = 6 local MAXALPHA = 258 local MAXLEN = 20 --- scratch tables, reused across calls (single-threaded) -local LOOK = bcreate(MAXGROUPS * PSIZE * 4) -- per group: sym * 32 + len (len <= PBITS), 0 = longer code / none +local LOOK = bcreate(MAXGROUPS * PSIZE * 4) local LENS = bcreate(MAXGROUPS * MAXALPHA) -local PERM = table.create(MAXGROUPS * MAXALPHA, 0) -- per group: symbols in canonical order -local FIRST = table.create(MAXGROUPS * (MAXLEN + 1), 0) -- first code of each length +local PERM = table.create(MAXGROUPS * MAXALPHA, 0) +local FIRST = table.create(MAXGROUPS * (MAXLEN + 1), 0) local COUNT = table.create(MAXGROUPS * (MAXLEN + 1), 0) -local OFFS = table.create(MAXGROUPS * (MAXLEN + 1), 0) -- index into PERM of the first symbol of each length +local OFFS = table.create(MAXGROUPS * (MAXLEN + 1), 0) local MAXL = table.create(MAXGROUPS, 0) local CFTAB = table.create(257, 0) local MTF = table.create(256, 0) local SEQ = table.create(256, 0) --- build group g's tables from LENS[g*MAXALPHA .. + n): false when over-subscribed local function buildGroup(g: number, n: number): boolean local lbase = g * MAXALPHA local cbase = g * (MAXLEN + 1) @@ -74,7 +65,6 @@ local function buildGroup(g: number, n: number): boolean end code *= 2 end - -- perm + lookup local pbase = g * MAXALPHA local tbase = g * PSIZE * 4 bfill(LOOK, tbase, 0, PSIZE * 4) @@ -106,11 +96,10 @@ local function grow(out: buffer, op: number, need: number): buffer return nb end --- decode(b, o, e, maxBytes) -> out, n, consumedEnd | nil, message, kind function Decode.decode(b: buffer, o: number, e: number, maxBytes: number): (buffer?, any, any) local out = bcreate(math.min(math.max(65536, (e - o) * 4), maxBytes + 1)) local op = 0 - local p = o -- next input byte (may run past e: zeros are fed, and the overrun is detected) + local p = o local bb, bc = 0, 0 local tt: buffer? = nil local ttSize = 0 @@ -377,7 +366,6 @@ function Decode.decode(b: buffer, o: number, e: number, maxBytes: number): (buff bc -= band(ent, 31) sym = rshift(ent, 5) else - -- a code longer than PBITS: canonical search local v = band(rshift(bb, bc - gmax), MASK[gmax + 1]) sym = -1 for l = PBITS + 1, gmax do @@ -442,7 +430,6 @@ function Decode.decode(b: buffer, o: number, e: number, maxBytes: number): (buff return nil, "bad BWT origin pointer", "corrupt" end - -- inverse BWT: T[pos] |= i << 8 at each byte's sorted position local sum = 0 for i = 0, 255 do local c = CFTAB[i + 1] @@ -456,7 +443,6 @@ function Decode.decode(b: buffer, o: number, e: number, maxBytes: number): (buff writeu32(T, k * 4, bor(readu32(T, k * 4), lshift(i, 8))) end - -- walk, undo RLE1, CRC if op + nblock + 4096 > blen(out) then out = grow(out, op, op + nblock + 4096) end diff --git a/src/Rosetta/codecs/compress/Bzip2/init.luau b/src/Rosetta/codecs/compress/Bzip2/init.luau index e7e29f7..99b2728 100644 --- a/src/Rosetta/codecs/compress/Bzip2/init.luau +++ b/src/Rosetta/codecs/compress/Bzip2/init.luau @@ -1,14 +1,6 @@ --!strict --- codecs/compress/Bzip2: bzip2 decompressor (BWT + MTF + Huffman, the .bz2 stream format of bzip2 0.9.5 / 1.0.x). A codec --- (layer 3): archive/bz2 and tar.bz2 build on it. Written from the format description (no third-party code). --- Supports: block sizes 1..9, every Huffman group layout, block and stream CRCs, concatenated streams (as bzip2 -d). --- Not supported: randomised blocks (bzip2 0.9.0 and older; Err.UNSUPPORTED), compression. --- --- local Bzip2 = require("@rosetta/codecs/compress/Bzip2") --- local out, consumedEnd = Bzip2.decompress(buf) -- | nil, Err --- local out = Bzip2.decompress(buf, offset, length, { maxBytes = 2^24 }) --- --- Never throws: bad data and bad arguments return nil, Err (TRUNCATED / CORRUPT / CHECKSUM / LIMIT / ARG). +-- codecs/compress/Bzip2: bzip2 decompressor (BWT + MTF + Huffman, the .bz2 stream format of bzip2 0.9.5 / 1.0.x). +-- Written from the format description (no third-party code); randomised blocks (bzip2 0.9.0 and older) are unsupported. local Err = require("@rosetta/core/Err") local Bytes = require("@rosetta/core/Bytes") local Decode = require("@rosetta/codecs/compress/Bzip2/Decode") @@ -16,10 +8,9 @@ local Decode = require("@rosetta/codecs/compress/Bzip2/Decode") local Bzip2 = {} export type Options = { - maxBytes: number?, -- refuse output larger than this (default 2^30) + maxBytes: number?, } --- decompress(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err function Bzip2.decompress(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any) local b, o, l, aerr = Bytes.span("Bzip2.decompress", buf, offset, length) if not b then @@ -41,7 +32,6 @@ function Bzip2.decompress(buf: buffer | string, offset: number?, length: number? return res, consumed end --- crc(buf, offset?, length?) -> the CRC-32/BZIP2 of a range (the block CRC bzip2 stores) function Bzip2.crc(buf: buffer, offset: number?, length: number?): number local CT = Decode.crcTable local o = offset or 0 diff --git a/src/Rosetta/codecs/compress/Deflate/Compress.luau b/src/Rosetta/codecs/compress/Deflate/Compress.luau index 4c38448..84f7047 100644 --- a/src/Rosetta/codecs/compress/Deflate/Compress.luau +++ b/src/Rosetta/codecs/compress/Deflate/Compress.luau @@ -1,11 +1,8 @@ --!strict --!native --!optimize 2 --- codecs/compress/Deflate/Compress: a DEFLATE (RFC 1951) compressor. LZ77 over a 32 KB window with hash chains (chain depth --- and lazy matching by level), then per block the cheapest of stored / fixed-Huffman / dynamic-Huffman (codecs/entropy/Huffman --- length-limited codes). Level 0 = stored blocks only. --- --- raw(buf, off, len, level) -> buffer. Never throws (the caller validated the arguments). +-- codecs/compress/Deflate/Compress: a DEFLATE (RFC 1951) compressor: hash-chain LZ77 over a 32 KB window, then per +-- block the cheapest of stored / fixed / dynamic Huffman, as zlib's levels. local Huffman = require("@rosetta/codecs/entropy/Huffman") local readu8, writeu8, writeu16 = buffer.readu8, buffer.writeu8, buffer.writeu16 @@ -15,11 +12,10 @@ local floor = math.floor local WSIZE = 32768 local HSIZE = 65536 local MAXMATCH = 258 -local BLOCKSYMS = 16384 -- symbols per block +local BLOCKSYMS = 16384 --- per level (zlib's configuration_table): GOOD = a match this long quarters the chain for the lazy search, LAZY = no --- lazy search after a match this long, NICE = stop searching at this length, CHAIN = max chain steps. Levels 1-3 are --- greedy (no lazy matching). +-- zlib's configuration_table: GOOD quarters the chain for the lazy search, LAZY = no lazy search after a match this +-- long, NICE = stop searching at this length, CHAIN = max chain steps; levels 1-3 are greedy. local GOOD = { 4, 4, 4, 4, 8, 8, 8, 32, 32 } local LAZY = { 0, 0, 0, 4, 16, 16, 32, 128, 258 } local NICE = { 8, 16, 32, 16, 32, 128, 128, 258, 258 } @@ -66,14 +62,12 @@ end local CLORDER = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 } --- fixed codes local FIXLEN = table.create(288, 0) for i = 1, 288 do FIXLEN[i] = if i <= 144 then 8 elseif i <= 256 then 9 elseif i <= 280 then 7 else 8 end local FIXDLEN = table.create(30, 5) --- reversed (LSB-first) canonical codes for lengths local function revCodes(lens: { number }): { number } local codes = Huffman.codes(lens) for i, l in lens do @@ -91,7 +85,6 @@ for i = 0, 32 do POW[i + 1] = 2 ^ i end --- ------------------------------------------------------------------------------------------------ bit output type Out = { buf: buffer, op: number, acc: number, cnt: number } local function ensure(o: Out, n: number) @@ -102,7 +95,6 @@ local function ensure(o: Out, n: number) end end --- put(v, n): n <= 24 bits, LSB first local function put(o: Out, v: number, n: number) local acc = o.acc + v * POW[o.cnt + 1] local cnt = o.cnt + n @@ -127,8 +119,6 @@ local function alignOut(o: Out) end end --- ------------------------------------------------------------------------------------------------ blocks --- syms: L[i] = literal 0..255 or 256 + match length; D[i] = distance (0 for literals) local function storedBlock(o: Out, src: buffer, s: number, e: number, final: boolean) local p = s repeat @@ -209,7 +199,7 @@ local function block(o: Out, src: buffer, s: number, e: number, L: { number }, D for i = 1, hdist do all[hlit + i] = dlen[i] end - local cs, cx = {}, {} -- symbol, extra value + local cs, cx = {}, {} local cf = table.create(19, 0) local i = 1 local total = hlit + hdist @@ -252,7 +242,6 @@ local function block(o: Out, src: buffer, s: number, e: number, L: { number }, D while hclen > 4 and clen[CLORDER[hclen] + 1] == 0 do hclen -= 1 end - -- costs in bits local dyn = 17 + 3 * hclen + extra for k = 1, 19 do dyn += cf[k] * clen[k] @@ -299,7 +288,6 @@ local function block(o: Out, src: buffer, s: number, e: number, L: { number }, D emitSymbols(o, L, D, nsym, revCodes(llen), llen, revCodes(dlen), dlen) end --- ------------------------------------------------------------------------------------------------ LZ77 local Compress = {} function Compress.raw(src: buffer, off: number, len: number, level: number): buffer @@ -336,7 +324,6 @@ function Compress.raw(src: buffer, off: number, len: number, level: number): buf prev[p % WSIZE + 1] = head[h] head[h] = p end - -- longest match at p among earlier positions: len (0 if < 3), dist local function find(p: number, steps: number): (number, number) local maxLen = math.min(MAXMATCH, e - p) if maxLen < 3 then @@ -360,7 +347,7 @@ function Compress.raw(src: buffer, off: number, len: number, level: number): buf end local nc = prev[c % WSIZE + 1] if nc >= c then - break -- the slot was reused by a newer position: the chain ends here + break end c = nc steps -= 1 @@ -377,7 +364,7 @@ function Compress.raw(src: buffer, off: number, len: number, level: number): buf end local p = off - local stop3 = e - 3 -- positions with 3 bytes ahead can be hashed + local stop3 = e - 3 while p < e do local mlen, mdist = 0, 0 if p <= stop3 then @@ -386,7 +373,6 @@ function Compress.raw(src: buffer, off: number, len: number, level: number): buf if mlen >= 3 and mlen < lazyMax and p + 1 <= stop3 then local l2, d2 = find(p + 1, if mlen >= good then maxChain // 4 else maxChain) if l2 > mlen then - -- a literal now, the longer match from p + 1 nsym += 1 L[nsym] = readu8(src, p) D[nsym] = 0 diff --git a/src/Rosetta/codecs/compress/Deflate/Inflate.luau b/src/Rosetta/codecs/compress/Deflate/Inflate.luau index 7867436..eee66ed 100644 --- a/src/Rosetta/codecs/compress/Deflate/Inflate.luau +++ b/src/Rosetta/codecs/compress/Deflate/Inflate.luau @@ -2,15 +2,7 @@ --!native --!optimize 2 -- codecs/compress/Deflate/Inflate: raw DEFLATE (RFC 1951) decoder: stored, fixed-Huffman and dynamic-Huffman blocks. --- Absorbed from deflate-luau src/Deflate/Inflate.luau (same author); the table builder moved to codecs/entropy/Huffman, whose --- entries are symbol * 32 + length (5 length bits instead of 4). --- --- Bits are read LSB first into a 32-bit bit buffer (refilled 4 bytes at a time with one readu32 while the input --- lasts). Huffman codes decode through a codecs/entropy/Huffman LSB table indexed by the next LITBITS / DISTBITS bits; a longer --- code's primary slot links to a subtable, so a symbol is one or two table reads. --- --- Nothing in this module throws on any input: every buffer read and write is bounds-checked, and corrupt data --- returns nil, message. (Native code must never throw: it crashes Roblox Studio.) +-- Absorbed from deflate-luau src/Deflate/Inflate.luau (same author). local Huffman = require("@rosetta/codecs/entropy/Huffman") local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift @@ -20,7 +12,7 @@ local bcreate, bcopy, bfill, blen = buffer.create, buffer.copy, buffer.fill, buf local LITBITS, DISTBITS, CLBITS = 10, 8, 7 local LITMASK, DISTMASK, CLMASK = 1023, 255, 127 --- length codes 257..285 and distance codes 0..29: base value, extra bits +-- RFC 1951 3.2.5: length codes 257..285 and distance codes 0..29: base value, extra bits local LBASE = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258 } local LEXT = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 } local DBASE = { @@ -28,15 +20,13 @@ local DBASE = { 6145, 8193, 12289, 16385, 24577, } local DEXT = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 } --- the order code-length code lengths are sent in +-- RFC 1951 3.2.7: the order the code-length code lengths are sent in local CLORDER = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 } --- table capacities (entries): primary + one subtable per code longer than the primary width, worst case local LITCAP = Huffman.capacity(288, LITBITS, 15) local DISTCAP = Huffman.capacity(32, DISTBITS, 15) local CLCAP = Huffman.capacity(19, CLBITS, 7) --- fixed Huffman tables local FLIT, FDIST = bcreate(LITCAP * 4), bcreate(DISTCAP * 4) local FLITS: number, FDISTS: number do @@ -53,7 +43,6 @@ end local Inflate = {} --- Grow out (capacity cap) to hold at least need bytes. Returns the new buffer and capacity. local function grow(out: buffer, op: number, need: number): (buffer, number) local cap = math.max(blen(out) * 2, need, 1024) local nb = bcreate(cap) @@ -61,12 +50,6 @@ local function grow(out: buffer, op: number, need: number): (buffer, number) return nb, cap end --- Inflate src[start, endpos) into a buffer. cap: initial output capacity; exact: true = the output must fit in --- cap bytes (an error otherwise), false = grow as needed. prefix (with exact): stop at cap instead of failing and --- return what was inflated so far (at most cap bytes; Deflate.peek, for sniffing). --- dict: a preset dictionary (the data before the stream, e.g. MSZIP's previous block): out starts with a copy of it, --- distances may reach into it, and outLen includes it (cap does not). --- Returns out, outLen, consumedEnd (the input offset just past the final block) or nil, message. function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, exact: boolean, prefix: boolean?, dict: buffer?): (buffer?, any, number?) local op = 0 if dict then @@ -267,7 +250,6 @@ function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, ex end local lsmask = lshift(1, lsub) - 1 local dsmask = lshift(1, dsub) - 1 - -- the symbol loop while true do if bitcnt < 15 then if pos + 4 <= endpos then @@ -324,7 +306,6 @@ function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, ex if sym > 29 then return nil, "invalid literal/length code" end - -- up to 5 length extra bits + a 15-bit distance code if bitcnt < 20 then if pos + 4 <= endpos then bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt)) @@ -414,8 +395,7 @@ function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, ex local s = op - dist if dist >= len then if len <= 16 and op + 16 <= cap then - -- straight-line 16-byte copy (the bytes past len are rewritten later): no inner loop, which - -- keeps LuaJIT's traces simple; chunks read only bytes before op or already copied ones + -- straight-line 16-byte copy for simple LuaJIT traces; it reads only bytes before op or already copied ones writeu32(out, op, readu32(out, s)) writeu32(out, op + 4, readu32(out, s + 4)) writeu32(out, op + 8, readu32(out, s + 8)) @@ -432,7 +412,6 @@ function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, ex bfill(out, op, readu8(out, s), len) op += len else - -- overlapping: the pattern of period dist, copied in growing non-overlapping chunks local rem = len while rem > 0 do local k = math.min(op - s, rem) diff --git a/src/Rosetta/codecs/compress/Deflate/init.luau b/src/Rosetta/codecs/compress/Deflate/init.luau index 541fe96..7f315e0 100644 --- a/src/Rosetta/codecs/compress/Deflate/init.luau +++ b/src/Rosetta/codecs/compress/Deflate/init.luau @@ -1,19 +1,6 @@ --!strict --- codecs/compress/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers. --- A codec (layer 1), not a format: png, zip, gzip, woff, tiff, ... build on it. Absorbed from deflate-luau 1.0.0 --- (same author; no third-party code); the compressor is new. --- --- local Deflate = require("@rosetta/codecs/compress/Deflate") --- local out, err = Deflate.inflate(buf) -- raw deflate -> buffer, consumedEnd | nil, Err --- local out, err = Deflate.inflate(buf, off, len, size) -- a range, with the exact output size if known --- local out, err = Deflate.inflate(buf, off, len, size, dict) -- with a preset dictionary --- local out, err = Deflate.mszip(buf, { { offset, length, size }, ... }) -- MSZIP blocks ("CK" + deflate, chained) --- local out, err = Deflate.zlib(buf) -- checks the Adler-32 --- local out, err = Deflate.gunzip(buf) -- checks CRC-32 + ISIZE, concatenates members --- local z = Deflate.compress(buf, { level = 6 }) -- raw deflate; also zlibCompress / gzip --- local head = Deflate.peek(buf, nil, nil, 512) -- the first 512 inflated bytes of gzip / zlib / raw --- --- Never throws: bad data and bad arguments return nil, Err (core/Err codes TRUNCATED / CORRUPT / CHECKSUM / ARG). +-- codecs/compress/Deflate: DEFLATE (RFC 1951) decoder and compressor, with zlib (RFC 1950) and gzip (RFC 1952). +-- Absorbed from deflate-luau 1.0.0 (same author; no third-party code); the compressor is new. local Err = require("@rosetta/core/Err") local Bytes = require("@rosetta/core/Bytes") local Crc32 = require("@rosetta/core/Crc32") @@ -42,11 +29,6 @@ local function inflateErr(msg: string, at: number?): Err.Err return Err.new(code, "inflate: " .. msg, at) end --- inflate(buf, offset?, length?, expectedSize?) -> buffer, consumedEnd | nil, Err. Raw deflate. --- expectedSize: the exact uncompressed size when known (a zip entry): the output is allocated once, and a stream --- that inflates to a different size is an error. consumedEnd is the input offset just past the final block. --- dict: a preset dictionary (up to 32 KB of data before the stream, as MSZIP's previous block): back references may --- reach into it; the result holds only the new bytes. function Deflate.inflate(buf: buffer | string, offset: number?, length: number?, expectedSize: number?, dict: buffer?): (buffer?, any) local b, o, l, aerr = args("Deflate.inflate", buf, offset, length) if not b then @@ -82,7 +64,6 @@ function Deflate.inflate(buf: buffer | string, offset: number?, length: number?, return shrink(out, n), consumed end --- zlib(buf, offset?, length?, expectedSize?) -> buffer, consumedEnd | nil, Err function Deflate.zlib(buf: buffer | string, offset: number?, length: number?, expectedSize: number?): (buffer?, any) local b, o, l, aerr = args("Deflate.zlib", buf, offset, length) if not b then @@ -116,7 +97,6 @@ function Deflate.zlib(buf: buffer | string, offset: number?, length: number?, ex return out, consumed + 4 end --- gzipBody(b, p, e) -> the offset of a gzip member's deflate data (past FEXTRA / FNAME / FCOMMENT / FHCRC) | nil, Err local function gzipBody(b: buffer, p: number, e: number): (number?, Err.Err?) local flg = buffer.readu8(b, p + 3) if flg >= 0x20 then @@ -146,8 +126,6 @@ local function gzipBody(b: buffer, p: number, e: number): (number?, Err.Err?) return q, nil end --- gunzip(buf, offset?, length?) -> buffer | nil, Err. Members are concatenated; trailing data after a member that is --- not another gzip member (zero padding, garbage) is ignored, as gzip -d does. function Deflate.gunzip(buf: buffer | string, offset: number?, length: number?): (buffer?, Err.Err?) local b, o, l, aerr = args("Deflate.gunzip", buf, offset, length) if not b then @@ -194,7 +172,6 @@ function Deflate.gunzip(buf: buffer | string, offset: number?, length: number?): table.insert(parts, out) total += buffer.len(out) p = consumed + 8 - -- skip zero padding local z = p while z < e and buffer.readu8(b, z) == 0 do z += 1 @@ -215,9 +192,6 @@ function Deflate.gunzip(buf: buffer | string, offset: number?, length: number?): return res, nil end --- peek(buf, offset?, length?, n) -> buffer | nil, Err: the first n bytes (fewer when the stream is shorter, or up to --- 258 fewer at a match boundary) a gzip member, zlib stream or raw deflate stream inflates to, without inflating --- the rest or checking checksums: for sniffing compressed files cheaply. function Deflate.peek(buf: buffer | string, offset: number?, length: number?, n: number): (buffer?, Err.Err?) local b, o, l, aerr = args("Deflate.peek", buf, offset, length) if not b then @@ -248,7 +222,7 @@ function Deflate.peek(buf: buffer | string, offset: number?, length: number?, n: end export type CompressOptions = { - level: number?, -- 0 (stored) .. 9 (best); default 6 + level: number?, } local function level(opts: CompressOptions?): number? @@ -259,7 +233,6 @@ local function level(opts: CompressOptions?): number? return lv end --- compress(buf, opts?) -> raw deflate buffer | nil, Err function Deflate.compress(buf: buffer | string, opts: CompressOptions?): (buffer?, Err.Err?) local b = toBuffer(buf) local lv = level(opts) @@ -269,7 +242,6 @@ function Deflate.compress(buf: buffer | string, opts: CompressOptions?): (buffer return Compress.raw(b, 0, buffer.len(b), lv), nil end --- zlibCompress(buf, opts?) -> zlib stream | nil, Err function Deflate.zlibCompress(buf: buffer | string, opts: CompressOptions?): (buffer?, Err.Err?) local b = toBuffer(buf) local lv = level(opts) @@ -290,7 +262,6 @@ function Deflate.zlibCompress(buf: buffer | string, opts: CompressOptions?): (bu return out, nil end --- gzip(buf, opts?) -> gzip member (no name, mtime 0) | nil, Err function Deflate.gzip(buf: buffer | string, opts: CompressOptions?): (buffer?, Err.Err?) local b = toBuffer(buf) local lv = level(opts) @@ -309,10 +280,8 @@ function Deflate.gzip(buf: buffer | string, opts: CompressOptions?): (buffer?, E return out, nil end --- mszip(buf, blocks) -> buffer | nil, Err: MSZIP data (Microsoft's blocked deflate, as in CAB folders and DirectX .x --- files): blocks = { { offset, length, size } }, each buf[offset, offset + length) = "CK" + a raw deflate stream that --- inflates to exactly size bytes using the previous block's output (up to 32 KB) as its dictionary. Returns the --- blocks' output concatenated. +-- MSZIP (CAB folders, DirectX .x): each block is "CK" + a raw deflate stream using the previous block's output (up to +-- 32 KB) as its dictionary. function Deflate.mszip(buf: buffer, blocks: { { offset: number, length: number, size: number } }): (buffer?, Err.Err?) local total = 0 for _, b in blocks do @@ -343,7 +312,6 @@ function Deflate.mszip(buf: buffer, blocks: { { offset: number, length: number, return out, nil end --- crc32 / adler32 (kept from deflate-luau's API; the same as core/Crc32.of / core/Adler32.of) Deflate.crc32 = function(buf: buffer | string, offset: number?, length: number?, crc: number?): number local b = toBuffer(buf) or buffer.create(0) return Crc32.of(b, offset, length, crc) diff --git a/src/Rosetta/codecs/compress/Explode.luau b/src/Rosetta/codecs/compress/Explode.luau index 42b6aef..875cd79 100644 --- a/src/Rosetta/codecs/compress/Explode.luau +++ b/src/Rosetta/codecs/compress/Explode.luau @@ -1,17 +1,9 @@ --!strict --!native --!optimize 2 --- codecs/compress/Explode: decompressor for the PKWARE Data Compression Library "implode" format (DCL, 1987: MPQ --- archive sectors, old installers, some game data files). A codec (layer 3). Written after the format as documented --- by Mark Adler's blast.c (zlib licence, licenses/blast-LICENSE.txt): the same constant code tables (run-length --- coded Huffman code lengths, length bases / extra bits), the bit order (LSB first, Huffman codes inverted); the --- decoder itself is new code. --- Supports: literal coding off (raw bytes) and on (Huffman coded), 1 / 2 / 4 KB dictionaries, the end code; stops --- early at maxOut bytes (MPQ sectors whose stream has no end code). --- --- local out, err = Explode.decompress(buf, offset?, length?, maxOut?) -- buffer | nil, Err --- --- Never throws: bad data returns nil, Err (TRUNCATED / CORRUPT / ARG / LIMIT). +-- codecs/compress/Explode: decompressor for the PKWARE Data Compression Library "implode" format (DCL, 1987). +-- Code tables and bit order (LSB first, Huffman codes inverted) after Mark Adler's blast.c (zlib licence: +-- licenses/blast-LICENSE.txt); the decoder is new code. local Err = require("@rosetta/core/Err") local Bytes = require("@rosetta/core/Bytes") @@ -33,7 +25,6 @@ local EXTRA = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8 } type Code = { count: { number }, symbol: { number } } --- canonical code from run-length coded lengths local function construct(rep: { number }): Code local lengths: { number } = {} for _, b in rep do @@ -64,7 +55,6 @@ local LIT = construct(LITLEN) local LEN = construct(LENLEN) local DIST = construct(DISTLEN) --- decompress(buf, offset?, length?, maxOut?) -> buffer | nil, Err function Explode.decompress(buf: buffer | string, offset: number?, length: number?, maxOut: number?): (buffer?, Err.Err?) local b, o, l, aerr = Bytes.span("Explode.decompress", buf, offset, length) if not b then diff --git a/src/Rosetta/codecs/compress/Lz4.luau b/src/Rosetta/codecs/compress/Lz4.luau index 8303367..5445a38 100644 --- a/src/Rosetta/codecs/compress/Lz4.luau +++ b/src/Rosetta/codecs/compress/Lz4.luau @@ -1,26 +1,14 @@ --!strict --!native --!optimize 2 --- codecs/compress/Lz4: the LZ4 block format (lz4 doc/lz4_Block_format.md): decode and a greedy hash-chain-free encoder --- (the reference "fast" strategy: one 4-byte hash table, 64 KB window). A codec (layer 3): model/rbxm chunk bodies, --- and the LZ4 frame format (archive) builds on it. New code, written from the specification. Never throws. --- --- local out, err = Lz4.decompress(src, offset?, length?, outSize?, opts?) -- a block -> buffer | nil, Err --- local packed = Lz4.compress(src, offset?, length?) -- -> buffer (a block) | nil, Err --- local dEnd, msg = Lz4.decodeInto(src, p, limit, dst, d, dstLimit, histStart?) -- low level (linked blocks) --- local n = Lz4.encodeInto(src, p, n, dst, d) -- low level; dst has bound(n) room --- Lz4.bound(n) -- worst-case block size for n bytes --- --- decodeInto decodes one block from src[p, limit) to dst[d, dstLimit): matches may reach back to histStart (default --- d), so a frame decoder with linked blocks keeps the previous output in front of d. It returns the output end, or --- nil and a message ("truncated", "corrupt: ...", "limit: output ...") for the caller's Err.from. +-- codecs/compress/Lz4: the LZ4 block format (lz4 doc/lz4_Block_format.md), decode and the reference "fast" encoder. local Err = require("@rosetta/core/Err") local Bytes = require("@rosetta/core/Bytes") local Lz4 = {} export type Options = { - maxBytes: number?, -- refuse output larger than this when outSize is not given (default 2^28) + maxBytes: number?, } local readu8, writeu8, readu16, writeu16, readu32 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16, buffer.readu32 @@ -34,7 +22,6 @@ local MAX_OFFSET = 65535 local HASH_BITS = 13 local HASH_SIZE = 2 ^ HASH_BITS --- ------------------------------------------------------------------------------------------------ decode function Lz4.decodeInto(src: buffer, p: number, limit: number, dst: buffer, d: number, dstLimit: number, histStart: number?): (number?, string?) local lo = histStart or d if limit > blen(src) or dstLimit > blen(dst) or p < 0 or d < 0 or lo < 0 or lo > d then @@ -107,7 +94,6 @@ function Lz4.decodeInto(src: buffer, p: number, limit: number, dst: buffer, d: n buffer.fill(dst, d, readu8(dst, s), ml) d += ml else - -- an overlapping match repeats the off-byte pattern: copy what is already there, doubling each time local n = ml while n > 0 do local c = d - s @@ -122,8 +108,6 @@ function Lz4.decodeInto(src: buffer, p: number, limit: number, dst: buffer, d: n end end --- decompress(src, offset?, length?, outSize?, opts?) -> buffer | nil, Err: one block. With outSize the output must be --- exactly that long (CORRUPT otherwise); without it the output grows up to opts.maxBytes. function Lz4.decompress(src: buffer | string, offset: number?, length: number?, outSize: number?, opts: Options?): (buffer?, Err.Err?) local b, o, l, aerr = Bytes.span("Lz4.decompress", src, offset, length) if not b then @@ -163,13 +147,10 @@ function Lz4.decompress(src: buffer | string, offset: number?, length: number?, end end --- ------------------------------------------------------------------------------------------------ encode --- bound(n) -> the largest block n input bytes can produce function Lz4.bound(n: number): number return n + n // 255 + 16 end --- writes a length's 255-run extension at o; returns the next offset local function extend(dst: buffer, o: number, n: number): number while n >= 255 do writeu8(dst, o, 255) @@ -180,7 +161,7 @@ local function extend(dst: buffer, o: number, n: number): number return o + 1 end --- hash(v) -> 1 .. HASH_SIZE: Knuth's multiplicative hash (v * 2654435761 mod 2^32, top bits), exact in doubles +-- Knuth's multiplicative hash (v * 2654435761 mod 2^32, top bits), exact in doubles local function hash(v: number): number local vl, vh = band(v, 0xFFFF), rshift(v, 16) local mid = (vh * 0x79B1 + vl * 0x9E37) % 65536 @@ -189,7 +170,6 @@ end local hashTable: { number } = table.create(HASH_SIZE, -1e9) --- encodeInto(src, p, n, dst, d) -> the block's length: src[p, p + n) compressed to dst[d ..] (room for bound(n)) function Lz4.encodeInto(src: buffer, p: number, n: number, dst: buffer, d: number): number local op = d local anchor = p @@ -209,7 +189,6 @@ function Lz4.encodeInto(src: buffer, p: number, n: number, dst: buffer, d: numbe local ref = ht[h] ht[h] = ip if ref >= p and ip - ref <= MAX_OFFSET and readu32(src, ref) == v then - -- back over equal bytes before the match (into the pending literals) while ip > anchor and ref > p and readu8(src, ip - 1) == readu8(src, ref - 1) do ip -= 1 ref -= 1 @@ -247,7 +226,6 @@ function Lz4.encodeInto(src: buffer, p: number, n: number, dst: buffer, d: numbe ip = a anchor = ip skip = 64 - -- index the position just before the next one (better ratio at no cost) if ip - 2 >= p and ip - 2 < mflimit then local w = readu32(src, ip - 2) ht[hash(w)] = ip - 2 @@ -258,7 +236,6 @@ function Lz4.encodeInto(src: buffer, p: number, n: number, dst: buffer, d: numbe end end end - -- the last literals local lit = iend - anchor local tok = op op += 1 @@ -275,7 +252,6 @@ function Lz4.encodeInto(src: buffer, p: number, n: number, dst: buffer, d: numbe return op - d end --- compress(src, offset?, length?) -> buffer (one block) | nil, Err function Lz4.compress(src: buffer | string, offset: number?, length: number?): (buffer?, Err.Err?) local b, o, l, aerr = Bytes.span("Lz4.compress", src, offset, length) if not b then diff --git a/src/Rosetta/codecs/compress/Lzh/init.luau b/src/Rosetta/codecs/compress/Lzh/init.luau index cdf6fe9..18656c6 100644 --- a/src/Rosetta/codecs/compress/Lzh/init.luau +++ b/src/Rosetta/codecs/compress/Lzh/init.luau @@ -1,23 +1,9 @@ --!strict --!native --!optimize 2 --- codecs/compress/Lzh: the LHA family of LZSS decoders, used by archive/lha, archive/arj and archive/zoo: --- lh4 / lh5 / lh6 / lh7 / lhx static Huffman blocks (code-length "temp" table, 510 literal / length codes, offset --- bit-length codes); also ARJ methods 1..3 (= "lh6") and Zoo method 2 (= "lh5") --- lh1 adaptive Huffman (LHarc 1.x: 314 codes, grouped frequency tree) with fixed-length --- offset prefixes, 4 KB window --- lzs / lz5 LArc's plain LZSS (2 KB / 4 KB windows, flag bits / flag bytes) --- arj4 ARJ method 4 (unary-prefixed lengths and offsets, no Huffman) --- Every method decodes into a buffer of the known output size; the windows start filled as the original tools fill --- them (spaces; lz5's pattern), and offsets before the start of the output read that fill. --- Ported from lhasa 0.6.0 (Simon Howard, ISC licence: licenses/lhasa-LICENSE.txt): lh_new_decoder.c, lh1_decoder.c, --- lzs_decoder.c, lz5_decoder.c; the static Huffman tables are canonical codes built with codecs/entropy/Huffman instead --- of lhasa's trees. ARJ method 4 is written from the ARJ technical notes (unarj's decode_f description). --- --- local out, err = Lzh.decode(src, off, len, outSize, "lh5") -- buffer | nil, message --- --- Never throws: bad codes / truncated input return nil, message (truncated input: "truncated ..." after the bytes --- decoded so far would be useless, so nothing partial is returned). Not supported: pm0 / pm1 / pm2 (PMarc), lk7. +-- codecs/compress/Lzh: the LHA family of LZSS decoders (lh1, lh4-lh7, lhx, lzs, lz5, ARJ 1-4, Zoo 2). +-- Ported from lhasa 0.6.0 (Simon Howard, ISC: licenses/lhasa-LICENSE.txt); ARJ method 4 from the ARJ technical notes. +-- Windows start filled as the original tools fill them (spaces; lz5's pattern); offsets before the output read it. local Huffman = require("@rosetta/codecs/entropy/Huffman") local Lzh = {} @@ -26,9 +12,6 @@ local readu8, writeu8, readu32 = buffer.readu8, buffer.writeu8, buffer.readu32 local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift local floor = math.floor --- ------------------------------------------------------------------------------------------------ bit reader --- an MSB-first bit reader over src[pos, limit): acc holds cnt bits (cnt <= 32); past the end, zero bits are read and --- over counts them type Reader = { src: buffer, pos: number, limit: number, acc: number, cnt: number, over: number } local function reader(src: buffer, off: number, len: number): Reader @@ -73,7 +56,6 @@ local function bits(r: Reader, n: number): number return v end --- ------------------------------------------------------------------------------------------------ static Huffman type Table = { tab: buffer, P: number, S: number, single: number } local function newTable(nsym: number, P: number): Table @@ -145,7 +127,7 @@ local function readLengths(r: Reader, t: Table, nbits: number, maxN: number, spe writeu8(lens, i, l) if i == special then local z = bits(r, 2) - i += z -- zeros (already zero) + i += z end i += 1 end @@ -235,7 +217,6 @@ local function decodeNew(src: buffer, off: number, len: number, out: buffer, n: return nil end --- ------------------------------------------------------------------------------------------------ lh1 local NUM_CODES = 314 local NUM_NODES = NUM_CODES * 2 - 1 local REORDER = 32 * 1024 @@ -261,7 +242,6 @@ end local function decodeLh1(src: buffer, off: number, len: number, out: buffer, n: number): string? local r = reader(src, off, len) - -- node arrays (0-based indexes stored at [i + 1]) local leaf = table.create(NUM_NODES, false) local child = table.create(NUM_NODES, 0) local parent = table.create(NUM_NODES, 0) @@ -401,7 +381,7 @@ local function decodeLh1(src: buffer, off: number, len: number, out: buffer, n: end end local code = child[ni + 1] - -- increment_for_code + -- lhasa's increment_for_code if freq[1] >= REORDER then reconstruct() end @@ -438,8 +418,7 @@ local function decodeLh1(src: buffer, off: number, len: number, out: buffer, n: return nil end --- ------------------------------------------------------------------------------------------------ LArc lzs / lz5 --- the ring of a 2 KB / 4 KB window (positions are absolute ring positions, not distances) +-- LArc lzs / lz5: a 2 KB / 4 KB ring (absolute ring positions, not distances) local function decodeLzs(src: buffer, off: number, len: number, out: buffer, n: number): string? local r = reader(src, off, len) local ring = buffer.create(2048) @@ -549,7 +528,6 @@ local function decodeLz5(src: buffer, off: number, len: number, out: buffer, n: return nil end --- ------------------------------------------------------------------------------------------------ ARJ method 4 local function decodeArj4(src: buffer, off: number, len: number, out: buffer, n: number): string? local r = reader(src, off, len) local function prefixed(start: number, stop: number): number @@ -591,10 +569,8 @@ local function decodeArj4(src: buffer, off: number, len: number, out: buffer, n: return nil end --- ------------------------------------------------------------------------------------------------ api Lzh.METHODS = { "lh1", "lh4", "lh5", "lh6", "lh7", "lhx", "lzs", "lz5", "arj4" } --- decode(src, off, len, outSize, method) -> buffer | nil, message function Lzh.decode(src: buffer, off: number, len: number, outSize: number, method: string): (buffer?, string?) if off < 0 or len < 0 or off > buffer.len(src) or outSize < 0 or outSize ~= outSize then return nil, "bad arguments" diff --git a/src/Rosetta/codecs/compress/Lzma/Crc64.luau b/src/Rosetta/codecs/compress/Lzma/Crc64.luau index bd39f30..286989c 100644 --- a/src/Rosetta/codecs/compress/Lzma/Crc64.luau +++ b/src/Rosetta/codecs/compress/Lzma/Crc64.luau @@ -1,8 +1,8 @@ --!strict --!native --!optimize 2 --- codecs/compress/Lzma/Crc64: CRC-64/XZ (ECMA-182 polynomial, reflected: 0xC96C5795D7870F42), the xz check type 4. The 64-bit --- value is kept as two u32 halves (hi, lo). Written from the xz file format specification. Never throws. +-- codecs/compress/Lzma/Crc64: CRC-64/XZ (ECMA-182 polynomial, reflected: 0xC96C5795D7870F42), xz check type 4. +-- Written from the xz file format specification; the 64-bit value is kept as two u32 halves (hi, lo). local band, bxor, rshift, lshift, bor = bit32.band, bit32.bxor, bit32.rshift, bit32.lshift, bit32.bor local readu8 = buffer.readu8 @@ -23,7 +23,6 @@ end local Crc64 = {} --- of(buf, offset, length) -> hi, lo function Crc64.of(b: buffer, o: number, n: number): (number, number) local hi, lo = 0xFFFFFFFF, 0xFFFFFFFF for i = o, o + n - 1 do diff --git a/src/Rosetta/codecs/compress/Lzma/Decode.luau b/src/Rosetta/codecs/compress/Lzma/Decode.luau index dfbb956..2026ffc 100644 --- a/src/Rosetta/codecs/compress/Lzma/Decode.luau +++ b/src/Rosetta/codecs/compress/Lzma/Decode.luau @@ -1,17 +1,9 @@ --!strict --!native --!optimize 2 --- codecs/compress/Lzma/Decode: the LZMA range decoder and LZ state machine, shared by raw LZMA (.lzma, 7z) and LZMA2 (xz, 7z). --- Written from the LZMA specification and its reference decoder (LzmaSpec.cpp, Igor Pavlov, public domain); the --- structure (probability model layout, state transitions, distance / length decoding) follows that document. --- --- The output buffer is also the dictionary: everything decoded stays in memory, so a match may reach back to the last --- dictionary reset (st.dictStart). A decoder state (new) carries the probabilities, the LZ state, the four rep --- distances, a pending match remainder (st.remLen) and the range coder across calls, so LZMA2 can feed it chunk by --- chunk. run() decodes until st.op reaches outEnd, an end marker, or an error. --- --- Never throws: every input read is bounds-checked (a read past the end counts in `over` and fails the call as --- "truncated"), every output write is preceded by a capacity check, and errors return nil, message. +-- codecs/compress/Lzma/Decode: the LZMA range decoder and LZ state machine, shared by LZMA (.lzma, 7z) and LZMA2. +-- Follows the LZMA specification's reference decoder (LzmaSpec.cpp, Igor Pavlov, public domain): probability layout, +-- state transitions, distance / length decoding. local readu8, readu16, writeu8, writeu16 = buffer.readu8, buffer.readu16, buffer.writeu8, buffer.writeu16 local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len local rshift, band = bit32.rshift, bit32.band @@ -37,8 +29,8 @@ local Decode = {} export type State = { out: buffer, cap: number, - op: number, -- bytes decoded so far (the next write offset) - dictStart: number, -- the last dictionary reset: matches may not reach before it + op: number, + dictStart: number, maxBytes: number, probs: buffer, nprobs: number, @@ -50,12 +42,11 @@ export type State = { rep1: number, rep2: number, rep3: number, - remLen: number, -- a match cut by outEnd, finished by the next run + remLen: number, range: number, code: number, } --- new(cap, maxBytes) -> a decoder state with an empty output buffer of capacity cap function Decode.new(cap: number, maxBytes: number): State local c = math.max(64, math.min(cap, maxBytes)) return { @@ -80,7 +71,6 @@ function Decode.new(cap: number, maxBytes: number): State } end --- setProps(st, lc, lp, pb) -> ok, message?: new literal / position parameters (resets the probabilities) function Decode.setProps(st: State, lc: number, lp: number, pb: number): (boolean, string?) if lc > 8 or lp > 4 or pb > 4 or lc < 0 or lp < 0 or pb < 0 then return false, "bad lc / lp / pb" @@ -95,7 +85,6 @@ function Decode.setProps(st: State, lc: number, lp: number, pb: number): (boolea return true, nil end --- resetState(st): probabilities to 1/2, LZ state and reps to 0 function Decode.resetState(st: State) local p = st.probs for i = 0, st.nprobs - 1 do @@ -106,13 +95,11 @@ function Decode.resetState(st: State) st.remLen = 0 end --- resetDict(st): matches may no longer reach before the current position function Decode.resetDict(st: State) st.dictStart = st.op st.remLen = 0 end --- rcInit(st, buf, ip, iend) -> next ip | nil, message: the 5 range coder init bytes function Decode.rcInit(st: State, b: buffer, ip: number, iend: number): (number?, string?) if ip + 5 > iend then return nil, "truncated range coder init" @@ -128,7 +115,6 @@ function Decode.rcInit(st: State, b: buffer, ip: number, iend: number): (number? return ip + 5, nil end --- ensure(st, need) -> ok: grow the output to hold need bytes (bounded by maxBytes) local function ensure(st: State, need: number): boolean if need <= st.cap then return true @@ -145,7 +131,6 @@ local function ensure(st: State, need: number): boolean end Decode.ensure = ensure --- copy(st, n, b, ip): append n stored bytes (LZMA2 uncompressed chunks); the caller checked the input range function Decode.copy(st: State, n: number, b: buffer, ip: number): (boolean, string?) if not ensure(st, st.op + n) then return false, "limit: output over maxBytes" @@ -155,14 +140,12 @@ function Decode.copy(st: State, n: number, b: buffer, ip: number): (boolean, str return true, nil end --- the range decoder state while run() executes (module upvalues: the helpers below are created once, so LuaJIT --- traces stay valid across calls; run() is not re-entrant, and never yields) +-- module upvalues, so LuaJIT traces stay valid across calls (run() is not re-entrant) local EMPTY = bcreate(2) local probs: buffer = EMPTY local inb: buffer = EMPTY local range, code, ip, iend, over = 0, 0, 0, 0, 0 --- decode one bit with the probability at index i local function bit(i: number): number local p = i * 2 local prob = readu16(probs, p) @@ -244,8 +227,6 @@ local function length(base: number, posState: number): number return 16 + tree(base + 258, 8) end --- run(st, buf, ip, iend, outEnd) -> status, ip | nil, message. status: "full" (st.op reached outEnd) or "eos" (end --- marker). The range coder must have been initialised (rcInit). function Decode.run(st: State, inb0: buffer, ip0: number, iend0: number, outEnd: number): (string?, any) probs = st.probs inb = inb0 @@ -268,7 +249,6 @@ function Decode.run(st: State, inb0: buffer, ip0: number, iend0: number, outEnd: local status: string? = nil local msg: string? = nil - -- a pending match from the previous call local remLen = st.remLen if remLen > 0 then local n = math.min(remLen, outEnd - op) @@ -469,7 +449,7 @@ function Decode.run(st: State, inb0: buffer, ip0: number, iend0: number, outEnd: st.state = state st.rep0, st.rep1, st.rep2, st.rep3 = rep0, rep1, rep2, rep3 st.remLen = remLen - probs, inb = EMPTY, EMPTY -- do not keep the caller's buffers alive + probs, inb = EMPTY, EMPTY if msg then return nil, msg end @@ -479,7 +459,6 @@ function Decode.run(st: State, inb0: buffer, ip0: number, iend0: number, outEnd: return status, ip end --- finish(st) -> a buffer of exactly the decoded bytes function Decode.finish(st: State): buffer if st.cap == st.op then return st.out diff --git a/src/Rosetta/codecs/compress/Lzma/Filters.luau b/src/Rosetta/codecs/compress/Lzma/Filters.luau index 5cc2e2f..7484122 100644 --- a/src/Rosetta/codecs/compress/Lzma/Filters.luau +++ b/src/Rosetta/codecs/compress/Lzma/Filters.luau @@ -1,10 +1,8 @@ --!strict --!native --!optimize 2 --- codecs/compress/Lzma/Filters: the branch-call-jump (BCJ) and delta decoding filters of xz and 7z, run in place over a whole --- decoded buffer range. Written from the xz file format specification and xz-embedded's xz_dec_bcj.c (Lasse Collin, --- public domain): x86, ARM, ARM-Thumb, PowerPC, SPARC, ARM64 and delta. Not supported: IA-64, RISC-V. --- Never throws: every access is inside [o, o + n). +-- codecs/compress/Lzma/Filters: the xz / 7z branch-call-jump (BCJ) and delta decoding filters, in place. +-- From the xz file format specification and xz-embedded's xz_dec_bcj.c (Lasse Collin, public domain). local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32 local band, bor, bxor, rshift, lshift, byteswap = bit32.band, bit32.bor, bit32.bxor, bit32.rshift, bit32.lshift, bit32.byteswap @@ -19,7 +17,6 @@ local function msbyte(b: number): boolean return b == 0 or b == 0xFF end --- x86(b, o, n, start): BCJ x86 decode; start = the stream position of b[o] (the filter's start offset) function Filters.x86(b: buffer, o: number, n: number, start: number) if n <= 4 then return @@ -167,7 +164,7 @@ function Filters.arm64(b: buffer, o: number, n: number, start: number) end end --- delta(b, o, n, dist): b[i] += b[i - dist] (1 <= dist <= 256) +-- delta filter: b[i] += b[i - dist] (1 <= dist <= 256) function Filters.delta(b: buffer, o: number, n: number, dist: number) for i = dist, n - 1 do writeu8(b, o + i, band(readu8(b, o + i) + readu8(b, o + i - dist), 255)) diff --git a/src/Rosetta/codecs/compress/Lzma/init.luau b/src/Rosetta/codecs/compress/Lzma/init.luau index 03fd9ee..89f09c6 100644 --- a/src/Rosetta/codecs/compress/Lzma/init.luau +++ b/src/Rosetta/codecs/compress/Lzma/init.luau @@ -1,21 +1,7 @@ --!strict --- codecs/compress/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. A codec (layer 3): --- archive/xz, archive/7z (and anything else holding LZMA data) build on it. Decode only. --- Written from the LZMA specification (LzmaSpec.cpp, Igor Pavlov, public domain) and the xz file format specification --- 1.2 (Lasse Collin / Igor Pavlov, public domain); the BCJ filters follow xz-embedded (public domain). --- --- local Lzma = require("@rosetta/codecs/compress/Lzma") --- local out, e = Lzma.lzma(buf, off, len, props, unpackSize?, opts?) -- raw LZMA; props = 5-byte buffer / string --- -- or { lc, lp, pb, dictSize } --- local out, e = Lzma.lzma2(buf, off, len, dictSize?, unpackSize?, opts?) -- raw LZMA2 chunks --- local out, e = Lzma.alone(buf, off?, len?, opts?) -- a .lzma file (13-byte header) --- local out, e = Lzma.xz(buf, off?, len?, opts?) -- a .xz file (all streams concatenated) --- Lzma.filter(id, buf, off, len, props?) -- BCJ / delta decode in place (7z) --- --- Each returns buffer, consumedEnd (the input offset just past what was decoded) | nil, Err. opts.maxBytes (default --- 2^30) bounds the output (Err.LIMIT). xz: every stream, block, index and footer is parsed and checked; check types --- none / CRC-32 / CRC-64 are verified, SHA-256 is skipped (not verified). xz filters: LZMA2, delta, x86, PowerPC, --- ARM, ARM-Thumb, SPARC, ARM64; IA-64 and RISC-V are Err.UNSUPPORTED. Never throws. +-- codecs/compress/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. +-- From LzmaSpec.cpp (Igor Pavlov) and the xz file format specification 1.2 (Lasse Collin / Igor Pavlov), both public +-- domain; the BCJ filters follow xz-embedded (public domain). local Err = require("@rosetta/core/Err") local Bytes = require("@rosetta/core/Bytes") local Crc32 = require("@rosetta/core/Crc32") @@ -30,7 +16,7 @@ local Lzma = {} local DEFAULT_MAX = 2 ^ 30 export type Options = { - maxBytes: number?, -- refuse output larger than this (default 2^30) + maxBytes: number?, } export type Props = { lc: number, lp: number, pb: number, dictSize: number? } @@ -42,7 +28,6 @@ local function maxOf(opts: Options?): number return if type(m) == "number" and m >= 0 then m else DEFAULT_MAX end --- a decoder message -> Err local function fail(msg: any, at: number?): Err.Err local s = tostring(msg) local code = Err.CORRUPT @@ -54,7 +39,6 @@ local function fail(msg: any, at: number?): Err.Err return Err.new(code, s, at) end --- props byte -> lc, lp, pb | nil local function propsByte(d: number): (number?, number, number) if d >= 225 then return nil, 0, 0 @@ -63,8 +47,6 @@ local function propsByte(d: number): (number?, number, number) end Lzma.propsByte = propsByte --- ------------------------------------------------------------------------------------------------ LZMA --- decodeLzma(st, b, o, e, unpackSize?) -> consumedEnd | nil, Err: one raw LZMA stream into st (props set) local function decodeLzma(st: Decode.State, b: buffer, o: number, e: number, unpackSize: number?): (number?, Err.Err?) local ip, ierr = Decode.rcInit(st, b, o, e) if not ip then @@ -87,7 +69,6 @@ local function decodeLzma(st: Decode.State, b: buffer, o: number, e: number, unp return res :: number, nil end --- lzma(buf, offset, length, props, unpackSize?, opts?) -> buffer, consumedEnd | nil, Err function Lzma.lzma(buf: buffer | string, offset: number?, length: number?, props: any, unpackSize: number?, opts: Options?): (buffer?, any) local b, o, l, aerr = args("Lzma.lzma", buf, offset, length) if not b then @@ -125,7 +106,7 @@ function Lzma.lzma(buf: buffer | string, offset: number?, length: number?, props return Decode.finish(st), consumed end --- alone(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err: a .lzma file (props, dict size, u64 size) +-- .lzma file: props byte, dict size, u64 unpacked size function Lzma.alone(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any) local b, o, l, aerr = args("Lzma.alone", buf, offset, length) if not b then @@ -145,8 +126,6 @@ function Lzma.alone(buf: buffer | string, offset: number?, length: number?, opts return Lzma.lzma(b, o + 13, l - 13, buffer.fromstring(buffer.readstring(b, o, 1)), size, opts) end --- ------------------------------------------------------------------------------------------------ LZMA2 --- decodeLzma2(st, b, o, e) -> consumedEnd | nil, Err: LZMA2 chunks up to the end-of-stream byte local function decodeLzma2(st: Decode.State, b: buffer, o: number, e: number): (number?, Err.Err?) local p = o local needDict, needProps = true, true @@ -234,7 +213,6 @@ local function decodeLzma2(st: Decode.State, b: buffer, o: number, e: number): ( end end --- lzma2(buf, offset?, length?, dictSize?, unpackSize?, opts?) -> buffer, consumedEnd | nil, Err function Lzma.lzma2(buf: buffer | string, offset: number?, length: number?, _dictSize: number?, unpackSize: number?, opts: Options?): (buffer?, any) local b, o, l, aerr = args("Lzma.lzma2", buf, offset, length) if not b then @@ -252,7 +230,6 @@ function Lzma.lzma2(buf: buffer | string, offset: number?, length: number?, _dic return Decode.finish(st), consumed end --- ------------------------------------------------------------------------------------------------ filters -- filter ids (xz numbering; 7z's method ids map onto these in archive/7z) Lzma.FILTER = table.freeze({ delta = 0x03, @@ -275,8 +252,7 @@ local BCJ: { [number]: (buffer, number, number, number) -> () } = { [0x0A] = Filters.arm64, } --- filter(id, buf, offset, length, props?) -> true | nil, Err: decode a BCJ / delta filter in place. props: the --- filter's property bytes (a string or buffer: BCJ start offset u32le, delta distance - 1) +-- filter properties: BCJ start offset u32le, delta distance - 1 function Lzma.filter(id: number, b: buffer, o: number, n: number, props: any?): (boolean?, Err.Err?) local pb = toBuffer(props) local plen = if pb then buffer.len(pb) else 0 @@ -301,11 +277,9 @@ function Lzma.filter(id: number, b: buffer, o: number, n: number, props: any?): return true, nil end --- ------------------------------------------------------------------------------------------------ xz local XZ_MAGIC = "\253" .. "7zXZ\0" local CHECK_SIZE = { [0] = 0, 4, 4, 4, 8, 8, 8, 16, 16, 16, 32, 32, 32, 64, 64, 64 } --- vli(b, p, e) -> value, next | nil local function vli(b: buffer, p: number, e: number): (number?, number) local v, mul = 0, 1 for i = 0, 8 do @@ -330,7 +304,6 @@ local function crc(b: buffer, o: number, n: number): number return Crc32.raw(b, o, n) end --- one xz stream at o -> next offset | nil, Err (blocks appended to st) local function xzStream(st: Decode.State, b: buffer, o: number, e: number): (number?, Err.Err?) if o + 12 > e then return nil, Err.new(Err.TRUNCATED, "truncated xz stream header", o) @@ -521,7 +494,6 @@ local function xzStream(st: Decode.State, b: buffer, o: number, e: number): (num return q + 12, nil end --- xz(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err: every stream (and stream padding) in the range function Lzma.xz(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any) local b, o, l, aerr = args("Lzma.xz", buf, offset, length) if not b then @@ -558,7 +530,6 @@ function Lzma.xz(buf: buffer | string, offset: number?, length: number?, opts: O return Decode.finish(st), p end --- isXz(buf, offset?) -> true when the bytes start an xz stream function Lzma.isXz(b: buffer, o: number?): boolean local off = o or 0 return off + 6 <= buffer.len(b) and buffer.readstring(b, off, 6) == XZ_MAGIC diff --git a/src/Rosetta/codecs/compress/Lzw/init.luau b/src/Rosetta/codecs/compress/Lzw/init.luau index a4584f4..88e5b11 100644 --- a/src/Rosetta/codecs/compress/Lzw/init.luau +++ b/src/Rosetta/codecs/compress/Lzw/init.luau @@ -1,25 +1,9 @@ --!strict --!native --!optimize 2 --- codecs/compress/Lzw: LZW decoder and encoder in the two variants file formats use. A codec (layer 1): image/gif and --- image/tiff build on it. New code (no port), written from the GIF89a spec (appendix F) and TIFF 6.0 section 13. --- gif LSB-first codes, a minimum code size 1..11 (2..8 in GIF), clear = 2^min, EOI = clear + 1, the code width --- grows when the next free code reaches 2^width (max 12 bits; a full table stays frozen until a clear). --- tiff MSB-first codes, 8-bit symbols, clear = 256, EOI = 257, "early change": the width grows one code --- earlier (next free code = 2^width - 1). Old-style (pre-6.0, LSB-first, no early change) TIFF LZW is --- detected by its first bytes (0x00 then an odd byte) and decoded too. --- zoo the gif layout with 8-bit symbols and codes up to 13 bits (Zoo archives' method 1; decode only). --- --- local n, err = Lzw.decode(src, off, len, out, outOff, maxOut, "gif", minCodeSize) -- bytes written --- local n, err = Lzw.decode(src, off, len, out, outOff, maxOut, "tiff") --- local n, err = Lzw.decode(src, off, len, out, outOff, maxOut, "zoo") --- local codes = Lzw.encode(data, off, len, "gif", minCodeSize) -- buffer --- local codes = Lzw.encode(data, off, len, "tiff") --- --- decode writes at most maxOut bytes at out[outOff ..] and returns how many it wrote; it stops at EOI, at the end of --- the input or when out is full. err is nil for a clean stream, "truncated" when the input ended without EOI, or --- "corrupt" for an impossible code (everything decoded up to it is kept). Never throws; the caller checks that --- [outOff, outOff + maxOut) lies inside out and [off, off + len) inside src (decode clamps both anyway). +-- codecs/compress/Lzw: LZW decoder and encoder, from the GIF89a spec (appendix F) and TIFF 6.0 section 13 (new code). +-- gif: LSB-first, clear = 2^min, EOI = clear + 1, width grows when the next code reaches 2^width (max 12, then frozen). +-- tiff: MSB-first, clear = 256, EOI = 257, early change (at 2^width - 1). zoo (method 1): gif layout, up to 13 bits. local readu8, writeu8, readu16, writeu16 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16 local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift local blen = buffer.len @@ -29,14 +13,11 @@ local Lzw = {} local MAX_CODES = 4096 -- 12-bit codes (GIF, TIFF) local TABLE = 8192 -- the tables hold 13-bit codes (Zoo) --- per-call tables (allocated once: decode / encode are not re-entrant across coroutines, but never yield) -local prefix = buffer.create(TABLE * 2) -- u16: the code this entry extends -local suffix = buffer.create(TABLE) -- u8: its last byte -local first = buffer.create(TABLE) -- u8: its first byte -local length = buffer.create(TABLE * 2) -- u16: its length +local prefix = buffer.create(TABLE * 2) +local suffix = buffer.create(TABLE) +local first = buffer.create(TABLE) +local length = buffer.create(TABLE * 2) --- ------------------------------------------------------------------------------------------------ decode --- writes the string of code c (length l) ending at out[o + l - 1]; clipped to [o, lim) local function emit(out: buffer, o: number, c: number, l: number, lim: number) local p = o + l - 1 if p < lim then @@ -67,7 +48,7 @@ function Lzw.decode(src: buffer, off: number, len: number, out: buffer, outOff: return 0, "corrupt" end local msb = variant == "tiff" - local early = 0 -- 1 for TIFF's early change + local early = 0 local min = minCodeSize or 8 local maxCodes, maxBits = MAX_CODES, 12 if variant == "zoo" then @@ -101,7 +82,6 @@ function Lzw.decode(src: buffer, off: number, len: number, out: buffer, outOff: local p = off local acc, nb = 0, 0 while true do - -- refill (at most 13 + 7 bits held: below 2^21) while nb < size do if p >= e then return o - outOff, "truncated" @@ -133,7 +113,7 @@ function Lzw.decode(src: buffer, off: number, len: number, out: buffer, outOff: return o - outOff, nil else if o >= lim then - return o - outOff, nil -- full: the rest (normally just EOI) is ignored + return o - outOff, nil end if prev < 0 then if c >= clear then @@ -178,13 +158,10 @@ function Lzw.decode(src: buffer, off: number, len: number, out: buffer, outOff: end end --- ------------------------------------------------------------------------------------------------ encode -local HASH = 8192 -- open addressing over (prefix << 8 | byte) keys: a power of two above 4096 entries -local hkey = buffer.create(HASH * 4) -- i32 key + 1 (0 = empty) -local hval = buffer.create(HASH * 2) -- u16 code +local HASH = 8192 +local hkey = buffer.create(HASH * 4) +local hval = buffer.create(HASH * 2) --- encode(data, off, len, variant, minCodeSize?) -> the code stream (GIF: without the sub-block framing). Symbols in --- data must be below 2^minCodeSize (GIF; larger ones are masked) or bytes (TIFF). function Lzw.encode(data: buffer, off: number, len: number, variant: string, minCodeSize: number?): buffer local msb = variant == "tiff" local min = if msb then 8 else math.clamp(minCodeSize or 8, 1, 11) diff --git a/src/Rosetta/codecs/compress/Lzx.luau b/src/Rosetta/codecs/compress/Lzx.luau index 422979d..648d5db 100644 --- a/src/Rosetta/codecs/compress/Lzx.luau +++ b/src/Rosetta/codecs/compress/Lzx.luau @@ -1,19 +1,9 @@ --!strict --!native --!optimize 2 --- codecs/compress/Lzx: the LZX decoder as Microsoft Cabinet folders use it: windows of 2^15 .. 2^21 bytes, --- verbatim, aligned offset and uncompressed blocks (block sizes of 24 bits, blocks spanning frames), the main and --- length trees sent as deltas of the previous block's code lengths through a 20-symbol pre-tree (runs 17 / 18 / 19), --- the three repeated offsets R0..R2, the Intel E8 call translation header (applied to the first 32768 frames, on the --- output only), and the stream cut into frames of 32768 output bytes, each 16-bit aligned at its end; trees, offsets --- and the window persist across the frames (the CFDATA blocks) of a folder. Written from the specification --- (Microsoft's LZX data format documentation in the Cabinet SDK and the LZX sections of [MS-PATCH]); no code from --- libmspack. Not supported: LZX DELTA reference data and reset intervals (CHM / WIM variants). --- --- local out, err = Lzx.decode(src, offset, length, outSize, windowBits) -- buffer | nil, message --- --- src[offset, offset + length) is the folder's compressed data (the CFDATA payloads concatenated), outSize its exact --- uncompressed size. Never throws: bad or truncated data returns nil, message. +-- codecs/compress/Lzx: the LZX decoder for Microsoft Cabinet folders (windows of 2^15 .. 2^21 bytes). +-- Written from Microsoft's LZX data format documentation (Cabinet SDK) and [MS-PATCH]; no code from libmspack. +-- Frames of 32768 output bytes, 16-bit aligned at their ends; trees, R0..R2 and the window persist across a folder. local Huffman = require("@rosetta/codecs/entropy/Huffman") local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift @@ -43,9 +33,7 @@ do end local SLOTS: { [number]: number } = { [15] = 30, [16] = 32, [17] = 34, [18] = 36, [19] = 38, [20] = 42, [21] = 50 } --- ------------------------------------------------------------------------------------------------ bit reader --- 16-bit little-endian words read most significant bit first; bb holds cnt bits left aligned (cnt <= 32). Past the --- end, zero words are read and over counts their bits. +-- 16-bit little-endian words, read most significant bit first type State = { src: buffer, pos: number, stop: number, bb: number, cnt: number, over: number } local function refill(s: State) @@ -67,7 +55,6 @@ local function refill(s: State) end end --- bits(s, n) -> the next n (1..17) bits local function bits(s: State, n: number): number if s.cnt < n then refill(s) @@ -78,7 +65,6 @@ local function bits(s: State, n: number): number return v end --- sym(s, tab, P, S) -> the next symbol of an MSB Huffman table, -1 for an invalid code local function sym(s: State, tab: buffer, P: number, S: number): number if s.cnt < 16 then refill(s) @@ -100,7 +86,7 @@ local function sym(s: State, tab: buffer, P: number, S: number): number return rshift(e, 5) end --- readLens: the code lengths lens[first, last) as deltas of their previous values, through a fresh pre-tree +-- code lengths as deltas of their previous values, through a fresh 20-symbol pre-tree (runs 17 / 18 / 19) local function readLens(s: State, lens: buffer, first: number, last: number, pre: buffer, preLens: buffer): boolean for i = 0, 19 do writeu8(preLens, i, bits(s, 4)) @@ -145,8 +131,7 @@ local function readLens(s: State, lens: buffer, first: number, last: number, pre return true end --- ------------------------------------------------------------------------------------------------ decode --- E8 translation of the decoded output, frame by frame (absolute call targets back to relative) +-- E8 translation, frame by frame: absolute call targets back to relative local function translate(out: buffer, n: number, size: number) local base = 0 local frame = 0 @@ -199,7 +184,6 @@ function Lzx.decode(src: buffer, offset: number, length: number, outSize: number local frameEnd = math.min(op + FRAME, outSize) while op < frameEnd do if bremain == 0 then - -- a new block if btype == 3 and band(bsize, 1) == 1 then s.pos += 1 end @@ -283,7 +267,6 @@ function Lzx.decode(src: buffer, offset: number, length: number, outSize: number local aligned = btype == 2 local start = op while op < runEnd do - -- refill to at least 17 bits while cnt <= 16 do local w = 0 if pos + 2 <= stop then diff --git a/src/Rosetta/codecs/compress/PackBits.luau b/src/Rosetta/codecs/compress/PackBits.luau index e3fd12f..53b9943 100644 --- a/src/Rosetta/codecs/compress/PackBits.luau +++ b/src/Rosetta/codecs/compress/PackBits.luau @@ -1,18 +1,12 @@ --!strict --!native --!optimize 2 --- codecs/compress/PackBits: the Apple PackBits run-length code (TIFF compression 32773, PSD / PSB RLE channels, IFF --- ByteRun1, ...): a header byte n < 128 copies n + 1 literal bytes, n > 128 repeats the next byte 257 - n times, --- 128 is a no-op. Decode and encode; moved here from image/tiff (TIFF and PSD both carried a decoder). Never throws. --- --- local written, srcEnd, clean = PackBits.decode(src, p, limit, dst, d, n) -- up to n bytes into dst at d --- local packed = PackBits.encode(src, offset, length) -- a buffer (one row at a time) +-- codecs/compress/PackBits: the Apple PackBits run-length code (TIFF compression 32773, PSD RLE, IFF ByteRun1). +-- Header byte n < 128 copies n + 1 literal bytes, n > 128 repeats the next byte 257 - n times, 128 is a no-op. local PackBits = {} local readu8, writeu8 = buffer.readu8, buffer.writeu8 --- decode(src, p, limit, dst, d, n) -> bytes written (<= n), the source offset after the codes used, clean (false when --- the source ran out before n bytes or a run overflowed n: lenient callers keep what was written, strict ones fail) function PackBits.decode(src: buffer, p: number, limit: number, dst: buffer, d: number, n: number): (number, number, boolean) local o, lim = d, d + n local clean = true @@ -56,7 +50,6 @@ function PackBits.decode(src: buffer, p: number, limit: number, dst: buffer, d: return o - d, p, clean end --- encode(src, offset, length) -> buffer: runs of 3+ equal bytes as repeats, the rest as literals (at most 128 each) function PackBits.encode(src: buffer, off: number, len: number): buffer local out = buffer.create(len + (len + 127) // 128 + 8) local o = 0 diff --git a/src/Rosetta/codecs/compress/Quantum.luau b/src/Rosetta/codecs/compress/Quantum.luau index ec833ce..c53e3a6 100644 --- a/src/Rosetta/codecs/compress/Quantum.luau +++ b/src/Rosetta/codecs/compress/Quantum.luau @@ -1,20 +1,9 @@ --!strict --!native --!optimize 2 --- codecs/compress/Quantum: the Quantum decoder (David Stafford's LZ77 with an adaptive arithmetic coder) as Microsoft --- Cabinet folders use it: windows of 2^10 .. 2^21 bytes; a 16-bit arithmetic decoder (H / L / C registers with --- underflow handling) over a most-significant-bit-first byte stream; eight adaptive frequency models (the --- 7-symbol selector, four 64-symbol literal models, the offset models for matches of 3, 4 and 5..259 bytes and the --- 27-symbol length model) whose cumulative frequencies grow by 8 per symbol and are rescaled above 3800 (halved, and --- every 50th time rebuilt from the frequencies and re-sorted); position and length footers read as raw bits from the --- same stream. Each CFDATA block is one frame (at most 32768 output bytes) that restarts the arithmetic coder; the --- models and the window persist across the frames of a folder. Written from the public descriptions of the format --- (the Quantum notes by Matthew Russotto and the cabinet documentation); no code from libmspack. --- --- local out, err = Quantum.decode(src, blocks, outSize, windowBits) -- buffer | nil, message --- --- blocks = { { at, len, size } }: each block's compressed bytes src[at, at + len) and its output size; outSize is --- their total. Never throws: bad or truncated data returns nil, message. +-- codecs/compress/Quantum: the Quantum decoder (David Stafford's LZ77 + adaptive arithmetic coder) for Cabinet folders. +-- Written from Matthew Russotto's Quantum notes and the cabinet documentation; no code from libmspack. Frequencies grow +-- by 8 and rescale above 3800 (halved; every 50th time rebuilt and re-sorted); each CFDATA frame restarts the coder. local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift local readu8, writeu8 = buffer.readu8, buffer.writeu8 @@ -45,8 +34,7 @@ do end end --- ------------------------------------------------------------------------------------------------ models --- an adaptive model: symbols sym[1..n] in their current order, cumulative frequencies cum[1..n + 1] (cum[n + 1] = 0) +-- model: sym[1..n] in their current order, cumulative frequencies cum[1..n + 1] (cum[n + 1] = 0) type Model = { n: number, sym: { number }, cum: { number }, shifts: number } local function model(first: number, n: number): Model @@ -92,8 +80,6 @@ local function rescale(m: Model) end end --- ------------------------------------------------------------------------------------------------ decode --- the coder and bit reader of one frame type Coder = { src: buffer, pos: number, stop: number, acc: number, cnt: number, over: number, H: number, L: number, C: number, bad: boolean } local function bit(c: Coder): number @@ -112,7 +98,6 @@ local function bit(c: Coder): number return band(rshift(c.acc, c.cnt), 1) end --- raw(c, n) -> the next n (0..19) bits, most significant first local function raw(c: Coder, n: number): number local v = 0 for _ = 1, n do @@ -127,7 +112,6 @@ local function symbol(c: Coder, m: Model): number local range = H - L + 1 local total = cum[1] if range <= 0 or C < L or C > H then - -- only corrupt registers get here (the decoder keeps L <= C <= H) c.bad = true return 0 end diff --git a/src/Rosetta/codecs/compress/UnixCompress.luau b/src/Rosetta/codecs/compress/UnixCompress.luau index 03cbee7..1084140 100644 --- a/src/Rosetta/codecs/compress/UnixCompress.luau +++ b/src/Rosetta/codecs/compress/UnixCompress.luau @@ -1,24 +1,16 @@ --!strict --!native --!optimize 2 --- codecs/compress/UnixCompress: the LZW of Unix compress (.Z files: magic 1F 9D, a flags byte with the maximum code --- width 9..16 and the block mode bit), decode and encode. A codec (layer 3): archive/z builds on it. Codes are --- LSB-first, 9 bits wide at the start; the width grows when the next free code passes 2^width - 1 (up to the --- maximum), and in block mode code 256 clears the table. compress writes codes in groups of eight: when the width --- changes or a CLEAR is read, the rest of the current group (counted from the previous change) is skipped. The encoder --- reproduces ncompress 5.0 bit for bit: greedy longest match, a full table frozen until the compression ratio checked --- every 10000 input bytes drops, then a CLEAR. Written from the ncompress sources (public domain, The Unlicense: read --- for the format and the encoder's ratio check; licenses/ncompress-UNLICENSE.txt). Never throws. --- --- local out, err = UnixCompress.decompress(buf, offset?, length?, { maxBytes = 2^28 }) -- a whole .Z file --- local z = UnixCompress.compress(buf, offset?, length?, { maxBits = 16 }) -- -> a .Z file +-- codecs/compress/UnixCompress: the LZW of Unix compress (.Z: magic 1F 9D, a flags byte: max width 9..16, block mode). +-- From the ncompress sources (public domain: licenses/ncompress-UNLICENSE.txt); the encoder matches ncompress 5.0. +-- LSB-first codes from 9 bits; block mode code 256 clears; a width change or CLEAR skips the rest of the 8-code group. local Err = require("@rosetta/core/Err") local Bytes = require("@rosetta/core/Bytes") local UnixCompress = {} -export type DecodeOptions = { maxBytes: number? } -- refuse output larger than this (default 2^30) -export type EncodeOptions = { maxBits: number? } -- 9..16, default 16 +export type DecodeOptions = { maxBytes: number? } +export type EncodeOptions = { maxBits: number? } local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32 local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift @@ -27,14 +19,11 @@ local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len local MAXCODES = 65536 local CHECK_GAP = 10000 --- decoder tables (per call state lives in locals; the tables are reused: decode never yields) -local prefix = bcreate(MAXCODES * 4) -- u32: the code an entry extends -local suffix = bcreate(MAXCODES) -- u8: its last byte -local first = bcreate(MAXCODES) -- u8: its first byte -local length = bcreate(MAXCODES * 4) -- u32: its length +local prefix = bcreate(MAXCODES * 4) +local suffix = bcreate(MAXCODES) +local first = bcreate(MAXCODES) +local length = bcreate(MAXCODES * 4) --- ------------------------------------------------------------------------------------------------ decode --- decompress(buf, offset?, length?, opts?) -> buffer | nil, Err function UnixCompress.decompress(buf: buffer | string, offset: number?, len: number?, opts: DecodeOptions?): (buffer?, Err.Err?) local b, o, n, aerr = Bytes.span("UnixCompress.decompress", buf, offset, len) if not b then @@ -68,8 +57,8 @@ function UnixCompress.decompress(buf: buffer | string, offset: number?, len: num local op = 0 local totalBits = (n - 3) * 8 local base = o + 3 - local pos = 0 -- bit position from the first code - local gbase = 0 -- where the current group sequence starts + local pos = 0 + local gbase = 0 local nbits = 9 local mask = 511 local maxcode = 511 @@ -85,7 +74,6 @@ function UnixCompress.decompress(buf: buffer | string, offset: number?, len: num mask = lshift(1, nbits) - 1 continue end - -- the code: up to 23 bits from three bytes local q = base + rshift(pos, 3) local acc = readu8(b, q) if q + 1 < o + n then @@ -157,12 +145,10 @@ function UnixCompress.decompress(buf: buffer | string, offset: number?, len: num return res, nil end --- ------------------------------------------------------------------------------------------------ encode -local HSIZE = 1 * 131072 -- open addressing over (prefix << 8 | byte) + 1 keys: twice the 65536 entries +local HSIZE = 1 * 131072 local hkey = bcreate(HSIZE * 4) local hval = bcreate(HSIZE * 4) --- compress(buf, offset?, length?, opts?) -> a .Z file (block mode) | nil, Err function UnixCompress.compress(buf: buffer | string, offset: number?, len: number?, opts: EncodeOptions?): (buffer?, Err.Err?) local b, o, n, aerr = Bytes.span("UnixCompress.compress", buf, offset, len) if not b then @@ -172,7 +158,6 @@ function UnixCompress.compress(buf: buffer | string, offset: number?, len: numbe if type(maxbits) ~= "number" or maxbits < 9 or maxbits > 16 or maxbits % 1 ~= 0 then return nil, Err.new(Err.ARG, "maxBits must be 9..16") end - -- at most 17 bits per input byte, plus group padding (< one group per width change / clear) local cap = 3 + n * 2 + 64 local out = bcreate(cap) writeu8(out, 0, 0x1F) @@ -180,7 +165,7 @@ function UnixCompress.compress(buf: buffer | string, offset: number?, len: numbe writeu8(out, 2, bor(maxbits, 0x80)) local outbits = 24 local boff = 24 - local acc, nb = 0, 0 -- pending bits not yet written (below 2^24) + local acc, nb = 0, 0 local nbits = 9 local extcode = 513 local maxmax = lshift(1, maxbits) @@ -290,7 +275,6 @@ function UnixCompress.compress(buf: buffer | string, offset: number?, len: numbe checks(i - o) end if rshift(outbits, 3) + 8 > cap then - -- grow (rare: only incompressible input passes 2 bytes per byte) local ncap = cap * 2 local nbuf = bcreate(ncap) bcopy(nbuf, 0, out, 0, cap) @@ -310,7 +294,6 @@ function UnixCompress.compress(buf: buffer | string, offset: number?, len: numbe return res, nil end --- isCompress(buf, offset?) -> true when the bytes at offset start a .Z file function UnixCompress.isCompress(b: buffer, o: number?): boolean local p = o or 0 return p + 3 <= blen(b) and readu8(b, p) == 0x1F and readu8(b, p + 1) == 0x9D diff --git a/src/Rosetta/codecs/compress/Xxh32.luau b/src/Rosetta/codecs/compress/Xxh32.luau index 121a6f8..86b4267 100644 --- a/src/Rosetta/codecs/compress/Xxh32.luau +++ b/src/Rosetta/codecs/compress/Xxh32.luau @@ -1,11 +1,8 @@ --!strict --!native --!optimize 2 --- codecs/compress/Xxh32: XXH32 of a buffer range (any seed), for the LZ4 frame format's header, block and content --- checksums. 32 x 32 -> 32 products split one operand into 16-bit limbs so every partial product is exact in a double. --- From the xxHash specification (Yann Collet, BSD-2); no code copied. Never throws (the range is clamped to the buffer). --- --- local h = Xxh32.hash(buf, offset?, length?, seed?) -- a number in 0 .. 2^32 - 1 +-- codecs/compress/Xxh32: XXH32 for the LZ4 frame checksums, from the xxHash specification (Yann Collet, BSD-2). +-- 32 x 32 -> 32 products split one operand into 16-bit limbs so every partial product is exact in a double. local Xxh32 = {} local bxor, bor, lshift, rshift = bit32.bxor, bit32.bor, bit32.lshift, bit32.rshift @@ -14,7 +11,6 @@ local readu8, readu32 = buffer.readu8, buffer.readu32 local T32 = 4294967296 local P1, P2, P3, P4, P5 = 0x9E3779B1, 0x85EBCA77, 0xC2B2AE3D, 0x27D4EB2F, 0x165667B1 --- a * b mod 2^32 (a, b below 2^32) local function mul(a: number, b: number): number local a0 = a % 65536 local a1 = (a - a0) / 65536 @@ -29,7 +25,6 @@ local function round(acc: number, lane: number): number return mul(rotl((acc + mul(lane, P2)) % T32, 13), P1) end --- hash(buf, offset?, length?, seed?) -> XXH32 function Xxh32.hash(b: buffer, offset: number?, length: number?, seed: number?): number local n0 = buffer.len(b) local o = math.clamp(offset or 0, 0, n0) diff --git a/src/Rosetta/codecs/compress/Zstd/Decode.luau b/src/Rosetta/codecs/compress/Zstd/Decode.luau index e20b344..4c334d7 100644 --- a/src/Rosetta/codecs/compress/Zstd/Decode.luau +++ b/src/Rosetta/codecs/compress/Zstd/Decode.luau @@ -1,16 +1,8 @@ --!strict --!native --!optimize 2 --- codecs/compress/Zstd/Decode: Zstandard frame decoder (RFC 8878), written from the specification (no code copied from the --- BSD reference implementation). Frames (any number, concatenated), skippable frames, raw / RLE / compressed blocks, --- Huffman literals (1 or 4 streams, new or repeated table), FSE sequence tables (predefined / RLE / compressed / --- repeat), repeat offsets, the XXH64 content checksum. Not supported: dictionaries (a non-zero dictionary ID). --- --- The whole output lives in one buffer, so the window is the output itself (offsets are checked against the frame's --- start). Backward bitstreams are read through bit offsets: bits [o - n, o) of a stream come from one readu32 at --- byte (o - n) / 8, bits before the stream start read as zeros. --- --- Nothing here throws on any input: every read is bounds-checked; failures return nil, code, message, offset. +-- codecs/compress/Zstd/Decode: Zstandard frame decoder (RFC 8878), written from the specification (no reference code). +-- Backward bitstreams: bits [o - n, o) come from one readu32 at byte (o - n) / 8; bits before the stream read as zeros. local Xxh64 = require("@rosetta/codecs/compress/Zstd/Xxh64") local band, lshift, rshift = bit32.band, bit32.lshift, bit32.rshift @@ -22,7 +14,6 @@ local BLOCK_MAX = 131072 local Decode = {} --- ------------------------------------------------------------------------------------------------ tables -- literal length / match length codes: baseline, extra bits (index = code + 1) local LL_BASE = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 20, 22, 24, 28, 32, 40, 48, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536 } local LL_BITS = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 3, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 } @@ -41,7 +32,6 @@ local ML_DEFAULT = { } local OF_DEFAULT = { 1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1 } --- highest set bit of 1..2048 local HB = table.create(2048, 0) do local v = 0 @@ -53,8 +43,6 @@ do end end --- ------------------------------------------------------------------------------------------------ bit readers --- backward stream starting at byte s: bits [o - n, o) (n <= 25), bits below 0 are zeros local function peek(b: buffer, s: number, o: number, n: number): number if n <= 0 then return 0 @@ -82,7 +70,6 @@ local function peek(b: buffer, s: number, o: number, n: number): number return lshift(peek(b, s, o, o), -lo) end --- the bit length of a backward stream [s, e) (up to its end marker), or -1 when the last byte is 0 / it is empty local function streamBits(b: buffer, s: number, e: number): number if e <= s then return -1 @@ -94,7 +81,6 @@ local function streamBits(b: buffer, s: number, e: number): number return (e - 1 - s) * 8 + HB[last] end --- forward stream: n (<= 24) bits at bit position bp from byte p; bytes at or past e read as zeros local function getF(b: buffer, p: number, e: number, bp: number, n: number): number local byte = p + rshift(bp, 3) local v = 0 @@ -108,11 +94,10 @@ local function getF(b: buffer, p: number, e: number, bp: number, n: number): num return band(rshift(v, band(bp, 7)), lshift(1, n) - 1) end --- ------------------------------------------------------------------------------------------------ FSE -- FSE decoding table entries (u32): symbol | nbBits << 8 | newStateBase << 16 local symTmp = bcreate(512) --- build(norm, nsym, al, t) -> true | nil, message. norm: { [symbol + 1] = normalized count (-1 = "less than 1") } +-- normalized counts: { [symbol + 1] = count }, -1 = "less than 1" probability local function buildFse(norm: { number }, nsym: number, al: number, t: buffer): (boolean?, string?) local size = lshift(1, al) local high = size - 1 @@ -166,7 +151,6 @@ local function buildFse(norm: { number }, nsym: number, al: number, t: buffer): return true, nil end --- ncount(b, p, e, maxSym, maxAL, norm) -> al, bytesUsed, nsym | nil, message: an FSE table description local function ncount(b: buffer, p: number, e: number, maxSym: number, maxAL: number, norm: { number }): (number?, any, number?) if p >= e then return nil, "truncated FSE table" @@ -251,8 +235,7 @@ local function predefined(dist: { number }, al: number): buffer end local LL_PRE, ML_PRE, OF_PRE = predefined(LL_DEFAULT, 6), predefined(ML_DEFAULT, 6), predefined(OF_DEFAULT, 5) --- ------------------------------------------------------------------------------------------------ Huffman --- hufTable(b, p, e, st) -> bytesUsed | nil, message: a Huffman tree description into st.huf (u16: sym | nbBits << 8) +-- Huffman table entry (u16): sym | nbBits << 8 local weights = bcreate(256) local wfse = bcreate(64 * 4) local function hufTable(b: buffer, p: number, e: number, st: any): (number?, string?) @@ -380,7 +363,6 @@ local function hufTable(b: buffer, p: number, e: number, st: any): (number?, str return used, nil end --- one Huffman stream [s, e) -> cnt literals at lit[dp] | nil, message local function hufStream(b: buffer, s: number, e: number, t: buffer, mb: number, lit: buffer, dp: number, cnt: number): string? local off = streamBits(b, s, e) if off < 0 then @@ -411,8 +393,6 @@ local function hufStream(b: buffer, s: number, e: number, t: buffer, mb: number, return nil end --- ------------------------------------------------------------------------------------------------ frames --- grow st.out to hold need bytes (doubling, capped at st.maxBytes): true | false (over the limit) local function grow(st: any, need: number): boolean if need > st.maxBytes then return false @@ -424,7 +404,6 @@ local function grow(st: any, need: number): boolean return true end --- a compressed block [p, e): nil (ok) | code, message local function block(b: buffer, p: number, e: number, st: any): (string?, string?) -- literals section local b0 = readu8(b, p) @@ -759,7 +738,6 @@ local function block(b: buffer, p: number, e: number, st: any): (string?, string bfill(out, op, readu8(out, from), ml) op += ml else - -- overlapping: copy in chunks of `offset` bytes (each chunk's source precedes its destination) local left = ml while left > 0 do local n = if left < offset then left else offset @@ -790,7 +768,6 @@ local function block(b: buffer, p: number, e: number, st: any): (string?, string return nil, nil end --- decompress(b, start, stop, maxBytes, verify) -> out, length, consumedEnd | nil, code, message, offset function Decode.decompress(b: buffer, start: number, stop: number, maxBytes: number, verify: boolean): (buffer?, any, any, any) local st: any = { out = bcreate(math.min(maxBytes, math.max(4096, (stop - start) * 3))), @@ -903,7 +880,6 @@ function Decode.decompress(b: buffer, start: number, stop: number, maxBytes: num st.rep1, st.rep2, st.rep3 = 1, 4, 8 st.hufBits = nil table.clear(st.tabs) - -- blocks local last = false repeat if pos + 3 > stop then diff --git a/src/Rosetta/codecs/compress/Zstd/Xxh64.luau b/src/Rosetta/codecs/compress/Zstd/Xxh64.luau index 7e29fec..1119b11 100644 --- a/src/Rosetta/codecs/compress/Zstd/Xxh64.luau +++ b/src/Rosetta/codecs/compress/Zstd/Xxh64.luau @@ -1,10 +1,8 @@ --!strict --!native --!optimize 2 --- codecs/compress/Zstd/Xxh64: XXH64 (seed 0) of a buffer range, computed on 32-bit halves held in doubles (Luau and LuaJIT have --- no 64-bit integers). 64 x 64 -> 64 products split the low operand into 16-bit limbs so every partial product is --- exact below 2^53. From the xxHash specification (Yann Collet, BSD-2); no code copied. zstd stores the low 32 bits --- of the hash as the frame content checksum. Never throws (the caller passes an in-range buffer slice). +-- codecs/compress/Zstd/Xxh64: XXH64 (seed 0) on 32-bit halves, from the xxHash specification (Yann Collet, BSD-2). +-- 64 x 64 -> 64 products split the low operand into 16-bit limbs so every partial product is exact below 2^53. local bor, bxor, lshift, rshift = bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift local readu8, readu32 = buffer.readu8, buffer.readu32 @@ -16,7 +14,6 @@ local P3H, P3L = 0x165667B1, 0x9E3779F9 local P4H, P4L = 0x85EBCA77, 0xC2B2AE63 local P5H, P5L = 0x27D4EB2F, 0x165667C5 --- (ah, al) * (bh, bl) mod 2^64 local function mul(ah: number, al: number, bh: number, bl: number): (number, number) local a0 = al % 65536 local a1 = (al - a0) / 65536 @@ -41,7 +38,6 @@ local function add(ah: number, al: number, bh: number, bl: number): (number, num return h % T32, l end --- rotl by r in 1..31 local function rotl(h: number, l: number, r: number): (number, number) return bor(lshift(h, r), rshift(l, 32 - r)), bor(lshift(l, r), rshift(h, 32 - r)) end @@ -49,7 +45,7 @@ end local P1L0, P1L1 = P1L % 65536, P1L // 65536 local P2L0, P2L1 = P2L % 65536, P2L // 65536 --- acc = rotl(acc + input * P2, 31) * P1, with both products written out (the hot path: 4 per 32 input bytes) +-- round: acc = rotl(acc + input * P2, 31) * P1 local function round(ah: number, al: number, ih: number, il: number): (number, number) local a0 = il % 65536 local a1 = (il - a0) / 65536 @@ -87,7 +83,6 @@ end local Xxh64 = {} --- hash(b, offset, length) -> hi, lo (the 64-bit hash as two unsigned 32-bit halves) function Xxh64.hash(b: buffer, offset: number, length: number): (number, number) local p = offset local e = offset + length diff --git a/src/Rosetta/codecs/compress/Zstd/init.luau b/src/Rosetta/codecs/compress/Zstd/init.luau index 6a67b1d..0510282 100644 --- a/src/Rosetta/codecs/compress/Zstd/init.luau +++ b/src/Rosetta/codecs/compress/Zstd/init.luau @@ -1,15 +1,5 @@ --!strict --- codecs/compress/Zstd: Zstandard decompression (RFC 8878). A codec (layer 3): archive/zst and anything else carrying zstd --- data build on it. Written from the specification. Supports every frame feature a dictionary-less stream uses: --- concatenated and skippable frames, raw / RLE / compressed blocks, Huffman literals (1 / 4 streams, repeated tables), --- predefined / RLE / compressed / repeated FSE tables, repeat offsets, the XXH64 content checksum (verified). --- Not supported: dictionaries (Err.UNSUPPORTED), compression. --- --- local Zstd = require("@rosetta/codecs/compress/Zstd") --- local out, err = Zstd.decompress(buf) -- -> buffer, consumedEnd | nil, Err --- local out, err = Zstd.decompress(buf, off, len, { maxBytes = 2^24, verify = false }) --- --- Never throws: bad data and bad arguments return nil, Err (TRUNCATED / CORRUPT / CHECKSUM / UNSUPPORTED / LIMIT / ARG). +-- codecs/compress/Zstd: Zstandard decompression (RFC 8878), written from the specification; no dictionaries. local Err = require("@rosetta/core/Err") local Bytes = require("@rosetta/core/Bytes") local Decode = require("@rosetta/codecs/compress/Zstd/Decode") @@ -17,14 +7,13 @@ local Decode = require("@rosetta/codecs/compress/Zstd/Decode") local Zstd = {} export type Options = { - maxBytes: number?, -- refuse output larger than this (default 2^30) - verify: boolean?, -- check the content checksum when a frame has one (default true) + maxBytes: number?, + verify: boolean?, } -- magic numbers: a zstd frame, and skippable frames (0x184D2A50 .. 0x184D2A5F) Zstd.MAGIC = "\40\181\47\253" --- isFrame(buf, offset?) -> true when a zstd (or skippable) frame starts there function Zstd.isFrame(buf: buffer, offset: number?): boolean local o = offset or 0 if type(buf) ~= "buffer" or o < 0 or o + 4 > buffer.len(buf) then @@ -34,8 +23,7 @@ function Zstd.isFrame(buf: buffer, offset: number?): boolean return m == 0xFD2FB528 or bit32.band(m, 0xFFFFFFF0) == 0x184D2A50 end --- decompress(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err. Every frame in the range is decoded --- and the outputs concatenated; data after the last frame that is not a frame is an error (as zstd -d does). +-- data after the last frame that is not a frame is an error, as zstd -d does function Zstd.decompress(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any) local b, o, l, aerr = Bytes.span("Zstd.decompress", buf, offset, length) if not b then @@ -58,7 +46,6 @@ function Zstd.decompress(buf: buffer | string, offset: number?, length: number?, return out, consumed end --- xxh64(buf, offset?, length?) -> hi, lo: the XXH64 hash (seed 0) as two unsigned 32-bit halves function Zstd.xxh64(buf: buffer, offset: number?, length: number?): (number, number) local o = math.clamp(offset or 0, 0, buffer.len(buf)) local l = math.clamp(length or (buffer.len(buf) - o), 0, buffer.len(buf) - o) diff --git a/src/Rosetta/codecs/entropy/Huffman.luau b/src/Rosetta/codecs/entropy/Huffman.luau index 3f43dd2..35ca2ec 100644 --- a/src/Rosetta/codecs/entropy/Huffman.luau +++ b/src/Rosetta/codecs/entropy/Huffman.luau @@ -1,18 +1,10 @@ --!strict --!native --- codecs/entropy/Huffman: canonical Huffman codes (RFC 1951 3.2.2 / JPEG Annex C order) for decoders and encoders. --- --- Decoding tables (built by buildLsb / buildMsb) are u32 buffers, indexed by the next P bits of the stream: --- entry = symbol * 32 + length a code of `length` <= P bits --- entry = offset * 32 (length 0) a link: index offset + the following S bits (subtable of 2^S entries) --- entry = 0 no code (incomplete code set): the stream is corrupt --- so a symbol is one or two table reads. LSB tables (DEFLATE, VP8L) are indexed by bit-reversed codes, MSB tables --- (JPEG, MPEG) by the code itself. Code lengths are 1..MAXLEN (16), symbols < 2^27. --- The hot loops (codecs/compress/Deflate/Inflate) inline the lookup on their own bit buffer; decodeLsb / decodeMsb do it on a --- core/Bits reader. --- --- Encoding: lengths(freqs, maxLen) -> length-limited code lengths; codes(lengths) -> canonical code values. --- Never throws: bad code sets return -1 / nil. +-- codecs/entropy/Huffman: canonical Huffman codes (RFC 1951 3.2.2 / JPEG Annex C order). +-- Decoding table entry (u32, indexed by the next P bits; LSB tables by bit-reversed codes, MSB tables by the code): +-- symbol * 32 + length a code of length <= P bits +-- offset * 32 a link: index offset + the following S bits (subtable of 2^S entries) +-- 0 no code (incomplete code set) local Bits = require("@rosetta/core/Bits") local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift @@ -24,7 +16,6 @@ local MAXLEN = 16 local Huffman = {} Huffman.MAXLEN = MAXLEN --- 8-bit reversal local REV = table.create(256, 0) for i = 0, 255 do local r, v = 0, i @@ -35,13 +26,11 @@ for i = 0, 255 do REV[i + 1] = r end --- reverse(code, len) -> the low len bits of code reversed (len <= 16) local function reverse(code: number, len: number): number return rshift(bor(lshift(REV[band(code, 255) + 1], 8), REV[band(rshift(code, 8), 255) + 1]), 16 - len) end Huffman.reverse = reverse --- capacity(nsym, P, maxLen) -> the table entries (u32) needed for nsym symbols, primary width P, codes up to maxLen function Huffman.capacity(nsym: number, P: number, maxLen: number): number return 2 ^ P + (if maxLen > P then nsym * 2 ^ (maxLen - P) else 0) end @@ -90,7 +79,6 @@ local function build(lens: buffer, off: number, n: number, tab: buffer, P: numbe local entry = s * 32 + l if l <= P then if msb then - -- the code is the top l bits of the P-bit index: fill every completion of the low bits local first = lshift(c, P - l) local last = first + lshift(1, P - l) - 1 for i = first, last do @@ -124,7 +112,7 @@ local function build(lens: buffer, off: number, n: number, tab: buffer, P: numbe else sub = rshift(e, 5) end - local k = l - P -- bits of the code in the subtable index + local k = l - P if msb then local first = lshift(rest, S - k) for i = first, first + lshift(1, S - k) - 1 do @@ -144,19 +132,14 @@ local function build(lens: buffer, off: number, n: number, tab: buffer, P: numbe return S end --- buildLsb(lens, off, n, tab, P) -> S: a table for the code lengths lens[off .. off + n - 1] (u8), indexed by the next --- P bits LSB-first (bit-reversed codes). S = the subtable width (0 when no code is longer than P), -1 = an --- over-subscribed or invalid code set. tab must hold capacity(n, P, maxLen) u32 entries. function Huffman.buildLsb(lens: buffer, off: number, n: number, tab: buffer, P: number): number return build(lens, off, n, tab, P, false) end --- buildMsb(lens, off, n, tab, P) -> S: the same, indexed by the next P bits MSB-first function Huffman.buildMsb(lens: buffer, off: number, n: number, tab: buffer, P: number): number return build(lens, off, n, tab, P, true) end --- decodeLsb(br, tab, P, S) -> symbol, or -1 for an invalid code (br: a core/Bits LSB reader) function Huffman.decodeLsb(br: Bits.BitReader, tab: buffer, P: number, S: number): number local e = readu32(tab, br:peek(P) * 4) local l = band(e, 31) @@ -175,7 +158,6 @@ function Huffman.decodeLsb(br: Bits.BitReader, tab: buffer, P: number, S: number return rshift(e, 5) end --- decodeMsb(br, tab, P, S) -> symbol, or -1 (br: a core/Bits MSB reader) function Huffman.decodeMsb(br: Bits.BitReader, tab: buffer, P: number, S: number): number local e = readu32(tab, br:peek(P) * 4) local l = band(e, 31) @@ -194,8 +176,6 @@ function Huffman.decodeMsb(br: Bits.BitReader, tab: buffer, P: number, S: number return rshift(e, 5) end --- codes(lengths) -> canonical code values (MSB-first, as written by an MSB writer; reverse() them for LSB streams). --- lengths: { number } indexed 1..n (symbol + 1), 0 = unused. function Huffman.codes(lengths: { number }): { number } local cnt = table.create(MAXLEN + 1, 0) for _, l in lengths do @@ -219,12 +199,9 @@ function Huffman.codes(lengths: { number }): { number } return out end --- lengths(freqs, maxLen) -> code lengths ({ number }, same indexing as freqs), at most maxLen bits, optimal without --- the limit; over the limit, the JPEG Annex K.3 adjustment. A single used symbol gets length 1. function Huffman.lengths(freqs: { number }, maxLen: number): { number } local n = #freqs local out = table.create(n, 0) - -- leaves sorted by frequency (ties by symbol, for determinism) local syms = {} for i = 1, n do if freqs[i] > 0 then @@ -244,14 +221,13 @@ function Huffman.lengths(freqs: { number }, maxLen: number): { number } end return a < b end) - -- two-queue Huffman: leaves (sorted) and internal nodes (created in increasing weight order) local m = #syms local weight = table.create(2 * m, 0) local parent = table.create(2 * m, 0) for i = 1, m do weight[i] = freqs[syms[i]] end - local li, ni, nn = 1, m + 1, m + 1 -- next leaf, next internal node to take, next free node + local li, ni, nn = 1, m + 1, m + 1 local function take(): number if li <= m and (ni >= nn or weight[li] <= weight[ni]) then li += 1 @@ -268,12 +244,11 @@ function Huffman.lengths(freqs: { number }, maxLen: number): { number } parent[b] = nn nn += 1 end - -- depths: the root is nn - 1 local depth = table.create(2 * m, 0) for i = nn - 2, 1, -1 do depth[i] = depth[parent[i]] + 1 end - -- count codes per length; limit (JPEG K.3: move pairs from the deepest level up) + -- length limiting: JPEG Annex K.3 (move pairs from the deepest level up) local bl = table.create(m + maxLen + 2, 0) local deepest = 0 for i = 1, m do @@ -292,7 +267,6 @@ function Huffman.lengths(freqs: { number }, maxLen: number): { number } bl[j] -= 1 end end - -- the longest codes go to the least frequent symbols (syms is sorted ascending) local k = 1 for l = math.min(deepest, maxLen), 1, -1 do for _ = 1, bl[l] do diff --git a/src/Rosetta/codecs/entropy/RangeCoder/Decoder.luau b/src/Rosetta/codecs/entropy/RangeCoder/Decoder.luau index 6073941..3df1b9e 100644 --- a/src/Rosetta/codecs/entropy/RangeCoder/Decoder.luau +++ b/src/Rosetta/codecs/entropy/RangeCoder/Decoder.luau @@ -1,10 +1,9 @@ --!strict --!native --!optimize 2 --- codecs/entropy/RangeCoder/Decoder: the Opus range decoder (RFC 6716 section 4.1, libopus celt/entdec.c). Reads one Opus --- frame from a `buffer` slice [base, base + storage). Raw bits (ec_dec_bits) are read from the end of the slice --- backwards. --- All values stay below 2^32, so plain Luau numbers hold them exactly; floor division is exact below 2^52. +-- codecs/entropy/RangeCoder/Decoder: the Opus range decoder (RFC 6716 4.1), a port of libopus celt/entdec.c (BSD: +-- licenses/libopus-BSD.txt). Raw bits (ec_dec_bits) are read from the end of the frame backwards. +-- All values stay below 2^32, so floor division on plain numbers is exact. local RangeDecoder = {} export type Dec = { @@ -54,7 +53,7 @@ local function normalize(d: Dec) else rem = 0 end - sym = rshift(bor(lshift(sym, 8), rem), SYM_BITS - CODE_EXTRA) -- (sym << 8 | rem) >> 1 + sym = rshift(bor(lshift(sym, 8), rem), SYM_BITS - CODE_EXTRA) val = band(val * 256 + band(SYM_MAX, bit32.bnot(sym)), CODE_TOP - 1) end d.rng, d.val, d.rem = rng, val, rem @@ -87,7 +86,6 @@ function RangeDecoder.new(buf: buffer, base: number, storage: number): Dec return d end --- ec_decode: the cumulative frequency of the next symbol, for a total of ft function RangeDecoder.decode(d: Dec, ft: number): number local ext = d.rng // ft d.ext = ext @@ -129,7 +127,6 @@ function RangeDecoder.bitLogp(d: Dec, logp: number): boolean return ret end --- ec_dec_icdf over a Luau array (1-based) starting at index `off` (icdf[off] is entry 0) function RangeDecoder.icdf(d: Dec, icdf: { number }, off: number, ftb: number): number local s = d.rng local v = d.val diff --git a/src/Rosetta/codecs/entropy/RangeCoder/Encoder.luau b/src/Rosetta/codecs/entropy/RangeCoder/Encoder.luau index 0ddb202..49ac2c0 100644 --- a/src/Rosetta/codecs/entropy/RangeCoder/Encoder.luau +++ b/src/Rosetta/codecs/entropy/RangeCoder/Encoder.luau @@ -1,10 +1,8 @@ --!strict --!native --!optimize 2 --- codecs/entropy/RangeCoder/Encoder: the Opus range encoder (RFC 6716 section 5.1), a port of libopus celt/entenc.c (BSD: --- licenses/libopus-BSD.txt), the mirror of codecs/entropy/RangeCoder/Decoder. 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`. +-- codecs/entropy/RangeCoder/Encoder: the Opus range encoder (RFC 6716 5.1), a port of libopus celt/entenc.c (BSD: +-- licenses/libopus-BSD.txt). Range-coded symbols from the front of the frame, raw bits (ec_enc_bits) from the back. local RangeEncoder = {} export type Enc = { @@ -37,7 +35,6 @@ local function ilog(x: number): number 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)), @@ -101,7 +98,6 @@ local function normalize(e: Enc) 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 @@ -113,7 +109,6 @@ function RangeEncoder.encode(e: Enc, fl: number, fh: number, ft: number) 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) @@ -126,7 +121,6 @@ function RangeEncoder.encodeBin(e: Enc, fl: number, fh: number, bits: number) 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) @@ -140,7 +134,6 @@ function RangeEncoder.bitLogp(e: Enc, v: boolean, logp: number) 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 @@ -152,7 +145,6 @@ function RangeEncoder.icdf(e: Enc, s: number, icdf: { number }, ftb: number) 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 @@ -170,7 +162,6 @@ function RangeEncoder.bits(e: Enc, fl: number, n: number) 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) @@ -202,7 +193,6 @@ function RangeEncoder.tellFrac(e: Enc): number 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) diff --git a/src/Rosetta/codecs/entropy/RangeCoder/init.luau b/src/Rosetta/codecs/entropy/RangeCoder/init.luau index b652e93..78ae5ff 100644 --- a/src/Rosetta/codecs/entropy/RangeCoder/init.luau +++ b/src/Rosetta/codecs/entropy/RangeCoder/init.luau @@ -1,10 +1,6 @@ --!strict --- codecs/entropy/RangeCoder: the RFC 6716 range coder (libopus celt/entdec.c + entenc.c, BSD: licenses/libopus-BSD.txt): --- symbols range-coded from the front of a frame, raw bits from its back. Opus (CELT and SILK) uses it; LZMA, VP8 and --- CABAC have their own (different) binary coders. Moved here from audio/opus by the cleanup pass (same code). --- --- local RD = require("@rosetta/codecs/entropy/RangeCoder/Decoder") -- RD.new(buf, base, size), RD.icdf / bits / uint ... --- local RE = require("@rosetta/codecs/entropy/RangeCoder/Encoder") -- RE.new(size), RE.icdf / bits / uint, RE.done +-- codecs/entropy/RangeCoder: the RFC 6716 range coder used by Opus, a port of libopus celt/entdec.c + entenc.c. +-- BSD: licenses/libopus-BSD.txt. local RangeCoder = { Decoder = require("@rosetta/codecs/entropy/RangeCoder/Decoder"), Encoder = require("@rosetta/codecs/entropy/RangeCoder/Encoder"), diff --git a/src/Rosetta/codecs/font/Bitmap.luau b/src/Rosetta/codecs/font/Bitmap.luau index a6aa021..f32efe1 100644 --- a/src/Rosetta/codecs/font/Bitmap.luau +++ b/src/Rosetta/codecs/font/Bitmap.luau @@ -1,18 +1,6 @@ --!strict --- codecs/font/Bitmap: the standard Font value for bitmap fonts (BDF, PCF, PSF, Windows FON / FNT): a Types.BitmapStrike --- (one pixel size, glyphs as u8 bitmaps, 0 = off / 255 = on) wrapped as a Types.Font whose units are pixels --- (unitsPerEm = the pixel size), glyphIndex / advance / kern work, outline is nil, and rasterize(g) returns the glyph's --- bitmap as an alpha8 Image (img.meta.left / top / advance, as codecs/font/TrueType does; the px argument is ignored, --- img.meta.scale = px / size tells the caller how much to scale). Also: the strike of any Font (its own bitmap, or an --- outline font rasterized at a pixel size and thresholded), which the bitmap font encoders write, and the bit-row --- packing every bitmap font format shares. New code. --- --- local font = Bitmap.font(strike, { family = "Fixed" }, { source = { format = "bdf" } }) --- local strike, err = Bitmap.strike(anyFont, { px = 16, chars = "abc" }) -- font.bitmap, or rasterized --- local pixels = Bitmap.unpack(buf, off, w, h, stride) -- MSB-first 1-bit rows -> u8 0 / 255 --- local bytes = Bitmap.pack(pixels, w, h, stride) -- u8 -> MSB-first rows (buffer) --- --- Never throws: rasterize of a bad glyph index returns nil; unpack reads only inside the buffer (missing bits are 0). +-- codecs/font/Bitmap: the standard Font value for bitmap fonts (BDF, PCF, PSF, Windows FON / FNT) and their 1-bit rows. +-- Bit rows are MSB = left pixel unless lsbFirst; a pixel >= 128 is on. local Err = require("@rosetta/core/Err") local Types = require("@rosetta/Types") @@ -20,9 +8,6 @@ local Bitmap = {} local readu8, writeu8 = buffer.readu8, buffer.writeu8 --- ------------------------------------------------------------------------------------------------ bits --- unpack(buf, off, w, h, stride, lsbFirst?) -> u8 pixels (w * h, 0 / 255) from 1-bit rows of stride bytes (MSB = left --- pixel unless lsbFirst); bytes past the end of buf read as 0 function Bitmap.unpack(b: buffer, off: number, w: number, h: number, stride: number, lsbFirst: boolean?): buffer local out = buffer.create(math.max(0, w * h)) local n = buffer.len(b) @@ -42,7 +27,6 @@ function Bitmap.unpack(b: buffer, off: number, w: number, h: number, stride: num return out end --- pack(pixels, w, h, stride?, lsbFirst?) -> 1-bit rows (stride bytes each, default ceil(w / 8)); a pixel >= 128 is on function Bitmap.pack(px: buffer, w: number, h: number, stride: number?, lsbFirst: boolean?): buffer local s = stride or math.ceil(w / 8) local out = buffer.create(math.max(0, s * h)) @@ -60,7 +44,6 @@ function Bitmap.pack(px: buffer, w: number, h: number, stride: number?, lsbFirst return out end --- ------------------------------------------------------------------------------------------------ font local Face = {} Face.__index = Face @@ -81,7 +64,6 @@ function Face.outline(_self: any, _g: number): { any }? return nil end --- rasterize(g, px?) -> the glyph as an alpha8 Image (px is ignored: meta.scale = px / size) function Face.rasterize(self: any, g: number, px: number?): Types.Image? local gl: Types.BitmapGlyph? = self.bitmap.glyphs[g + 1] if not gl or gl.width < 0 or gl.height < 0 then @@ -100,7 +82,6 @@ function Face.rasterize(self: any, g: number, px: number?): Types.Image? return img end --- font(strike, info?, meta?) -> a Types.Font over the strike (font.bitmap = strike) function Bitmap.font(strike: Types.BitmapStrike, info: { [string]: any }?, meta: { [string]: any }?): any local index: { [number]: number } = {} for i, gl in strike.glyphs do @@ -136,11 +117,10 @@ function Bitmap.font(strike: Types.BitmapStrike, info: { [string]: any }?, meta: return f end --- ------------------------------------------------------------------------------------------------ strike export type StrikeOptions = { - px: number?, -- pixel size for outline fonts (default 16) - chars: (string | { number })?, -- code points for outline fonts (default 32..126) - threshold: number?, -- coverage 0..255 at or above which a pixel is on (default 128) + px: number?, + chars: (string | { number })?, + threshold: number?, } local function codepoints(chars: (string | { number })?): { number } @@ -160,7 +140,6 @@ local function codepoints(chars: (string | { number })?): { number } return out end --- strike(font, opts?) -> the font's BitmapStrike: font.bitmap, else the outline font rasterized at opts.px function Bitmap.strike(font: any, opts: StrikeOptions?): (Types.BitmapStrike?, Err.Err?) if type(font) ~= "table" or font.kind ~= "font" then return nil, Err.new(Err.ARG, "expected a Font") diff --git a/src/Rosetta/codecs/font/Cff/init.luau b/src/Rosetta/codecs/font/Cff/init.luau index a4cebb6..892c09f 100644 --- a/src/Rosetta/codecs/font/Cff/init.luau +++ b/src/Rosetta/codecs/font/Cff/init.luau @@ -1,17 +1,7 @@ --!strict --- codecs/font/Cff: Compact Font Format (Adobe TN #5176) and Type 2 charstrings (TN #5177): the outlines of OpenType fonts --- with a "CFF " table (.otf). Parses the header, the INDEXes, the Top / Private DICTs (name-keyed and CID-keyed --- fonts with FDArray / FDSelect formats 0 and 3), local and global subroutines, and runs charstrings to path commands --- (moveTo / lineTo / cubicTo / close, font units, y up). The charstring interpreter is ported from stb_truetype 1.26 --- (public domain / MIT; Dougall Johnson's Type 2 support) through imgui-luau's imstb_truetype.lua, bounds-checked, --- with fixes: flex1's last delta, an operation budget against subroutine bombs, and the arithmetic / storage --- operators (TN #5177 4.4: and or not abs add sub div neg eq drop put get ifelse random mul sqrt dup exch index roll). --- Not supported: CFF2 (variable fonts), seac accented glyphs in endchar (deprecated in OpenType), hinting. --- --- local cff, err = Cff.parse(buf, offset, length) --- local cmds, err = Cff.outline(cff, glyphIndex) --- --- Never throws: malformed data returns nil, message. +-- codecs/font/Cff: Compact Font Format (Adobe TN #5176) and Type 2 charstrings (TN #5177), the outlines of .otf fonts. +-- Charstrings ported from stb_truetype 1.26 (public domain / MIT) via imgui-luau's imstb_truetype.lua, plus +-- flex1's last delta, an operation budget, and the TN #5177 4.4 arithmetic / storage operators. local Cff = {} local readu8 = buffer.readu8 @@ -38,15 +28,14 @@ export type Font = { limit: number, charStrings: Index, gsubrs: Index, - subrs: Index?, -- name-keyed fonts - fdSubrs: { Index? }?, -- CID-keyed fonts: per font dict - fdSelect: number?, -- absolute offset of FDSelect + subrs: Index?, + fdSubrs: { Index? }?, + fdSelect: number?, numGlyphs: number, cid: boolean, fontMatrix: { number }?, } --- INDEX at absolute offset p (within [base, limit)) -> Index | nil local function index(b: buffer, p: number, limit: number): Index? if p + 2 > limit then return nil @@ -71,7 +60,6 @@ local function index(b: buffer, p: number, limit: number): Index? return { count = count, offSize = offSize, offsets = offsets, data = data, next = data + last } end --- item(idx, i) -> absolute start, length (nil when out of range / corrupt) local function item(b: buffer, idx: Index, i: number): (number?, number) if i < 0 or i >= idx.count then return nil, 0 @@ -85,7 +73,7 @@ local function item(b: buffer, idx: Index, i: number): (number?, number) end Cff.item = item --- DICT at [p, p + n) -> { [op] = { operands } } (two-byte ops are 1200 + second byte) +-- DICT operators: two-byte ops (12 x) are keyed 1200 + x local function dict(b: buffer, p: number, n: number): { [number]: { number } } local out: { [number]: { number } } = {} local ops: { number } = {} @@ -171,7 +159,6 @@ local function privateSubrs(b: buffer, base: number, limit: number, d: { [number return index(b, ps + s[1], limit) end --- parse(buf, offset, length) -> Font | nil, message function Cff.parse(b: buffer, offset: number, length: number): (Font?, string?) local base, limit = offset, math.min(offset + length, blen(b)) if limit - base < 4 then @@ -256,7 +243,6 @@ local function bias(count: number): number return if count < 1240 then 107 elseif count < 33900 then 1131 else 32768 end --- the local subrs of glyph g (CID fonts: through FDSelect) local function localSubrs(f: Font, g: number): Index? if not f.cid then return f.subrs @@ -286,7 +272,6 @@ end local BUDGET = 200000 -- operators per glyph (subroutine bombs) --- outline(f, g) -> path commands | nil, message function Cff.outline(f: Font, g: number): ({ any }?, string?) local b = f.buf local p, len = item(b, f.charStrings, g) @@ -295,14 +280,14 @@ function Cff.outline(f: Font, g: number): ({ any }?, string?) end local e = p + len local cmds: { any } = {} - local s: { number } = table.create(48, 0) -- operand stack, 1-based; sp = count + local s: { number } = table.create(48, 0) local sp = 0 local trans = table.create(32, 0) :: { number } local x, y = 0, 0 local open = false local maskbits = 0 local inHeader = true - local stack: { { number } } = {} -- return addresses { p, e } + local stack: { { number } } = {} local subrs: Index? = nil local haveSubrs = false local ops = 0 @@ -334,13 +319,12 @@ function Cff.outline(f: Font, g: number): ({ any }?, string?) x, y = x2 + dx3, y2 + dy3 table.insert(cmds, { op = "cubicTo", x1, y1, x2, y2, x, y }) end - local function S(i: number): number -- operand i (0-based), 0 past the stack + local function S(i: number): number return s[i + 1] or 0 end while true do if p >= e then - -- the end of a subroutine without return, or of the charstring without endchar if #stack > 0 then local r = table.remove(stack) :: { number } p, e = r[1], r[2] @@ -535,12 +519,10 @@ function Cff.outline(f: Font, g: number): ({ any }?, string?) curveTo(S(0), S(1), S(2), S(3), S(4), S(5)) curveTo(S(6), S(7), S(8), S(9), dx6, dy6) else - -- arithmetic and storage operators: they leave results on the stack clear = false local top = sp local a, c = S(top - 2), S(top - 1) local function set(n: number, v: number) - -- pop n operands, push v sp = math.max(0, sp - n) sp += 1 s[sp] = v diff --git a/src/Rosetta/codecs/font/GlyphNames.luau b/src/Rosetta/codecs/font/GlyphNames.luau index 4130e91..5a9d862 100644 --- a/src/Rosetta/codecs/font/GlyphNames.luau +++ b/src/Rosetta/codecs/font/GlyphNames.luau @@ -1,12 +1,7 @@ --!strict --- codecs/font/GlyphNames: PostScript glyph names -> Unicode for fonts that name their glyphs (Type 1, CFF without a --- cmap, PCF / BDF glyph names): the Adobe Glyph List For New Fonts (AGLFN 1.7, Adobe, BSD-3-Clause: --- licenses/agl-LICENSE.txt; the f-ligatures and dotlessj added), the uniXXXX / uXXXX[XX] conventions and --- name.suffix variants ("a.sc" -> a) per the AGL specification; and Adobe StandardEncoding (code -> glyph name). --- Generated once from fontTools.agl / fontTools.encodings.StandardEncoding. --- --- GlyphNames.unicode("Aacute") -> 0xC1 GlyphNames.unicode("uni20AC") -> 0x20AC (nil when unknown) --- GlyphNames.STANDARD[65] -> "A" (StandardEncoding, codes 0..255; nil for .notdef) +-- codecs/font/GlyphNames: PostScript glyph names -> Unicode (AGL specification) and Adobe StandardEncoding. +-- Data: the Adobe Glyph List For New Fonts (AGLFN 1.7, BSD-3-Clause: licenses/agl-LICENSE.txt; the f-ligatures and +-- dotlessj added) and StandardEncoding, generated from fontTools.agl / fontTools.encodings.StandardEncoding. local GlyphNames = {} -- AGLFN: "name hex" pairs @@ -126,7 +121,6 @@ do end GlyphNames.STANDARD = STANDARD --- unicode(name) -> the code point of a glyph name (the first one for ligature names like "f_i"), or nil function GlyphNames.unicode(name: string): number? local base = string.match(name, "^([^%.]+)") or name local t = byName or load() diff --git a/src/Rosetta/codecs/font/TrueType/Glyf.luau b/src/Rosetta/codecs/font/TrueType/Glyf.luau index ce08e9f..7e99dab 100644 --- a/src/Rosetta/codecs/font/TrueType/Glyf.luau +++ b/src/Rosetta/codecs/font/TrueType/Glyf.luau @@ -1,12 +1,7 @@ --!strict --- codecs/font/TrueType/Glyf: TrueType glyph outlines (the glyf / loca tables): simple glyphs (contours of on- and --- off-curve points, with the implied on-curve midpoints) and composite glyphs (offsets or point matching, scale / --- x-y scale / 2x2 transforms, SCALED_COMPONENT_OFFSET, nesting up to 8 levels). Ported from stb_truetype 1.26 --- (public domain / MIT, Sean Barrett) through imgui-luau's imstb_truetype.lua, made bounds-checked, with point --- matching and the FreeType component transform (stb scales the offsets of transformed components; FreeType and the --- spec do not). No hinting. --- --- Never throws: every read is range-checked (out of range reads as 0) and malformed glyphs return nil, message. +-- codecs/font/TrueType/Glyf: TrueType glyph outlines from the glyf / loca tables, simple and composite. +-- Ported from stb_truetype 1.26 (public domain / MIT, Sean Barrett) via imgui-luau's imstb_truetype.lua; component +-- offsets follow FreeType and the spec (stb also scales the offsets of transformed components). local Glyf = {} local readu8, readi8 = buffer.readu8, buffer.readi8 @@ -35,7 +30,7 @@ end export type Face = { buf: buffer, - glyf: number, -- absolute offset of the glyf table + glyf: number, glyfLen: number, loca: number, locaLen: number, @@ -44,7 +39,6 @@ export type Face = { [string]: any, } --- (start, length) of glyph g in the glyf table, or nil for an empty glyph / bad index function Glyf.range(f: Face, g: number): (number?, number) if g < 0 or g >= f.numGlyphs or g % 1 ~= 0 then return nil, 0 @@ -67,7 +61,6 @@ function Glyf.range(f: Face, g: number): (number?, number) return f.glyf + a, z - a end --- bounds(f, g) -> xMin, yMin, xMax, yMax from the glyph header (nil for empty glyphs) function Glyf.bounds(f: Face, g: number): (number?, number, number, number) local o, n = Glyf.range(f, g) if not o or n < 10 then @@ -77,7 +70,6 @@ function Glyf.bounds(f: Face, g: number): (number?, number, number, number) return i16(b, o + 2), i16(b, o + 4), i16(b, o + 6), i16(b, o + 8) end --- contours: { { xs, ys, on } } point lists in font units type Contour = { x: { number }, y: { number }, on: { boolean } } local MAX_POINTS = 65536 @@ -108,7 +100,6 @@ local function simple(b: buffer, o: number, len: number, nc: number): ({ Contour if p > e then return nil, "instructions past the end" end - -- flags local flags = table.create(n, 0) local i = 1 while i <= n do @@ -134,7 +125,6 @@ local function simple(b: buffer, o: number, len: number, nc: number): ({ Contour end end end - -- coordinates local xs = table.create(n, 0) local x = 0 for k = 1, n do @@ -247,7 +237,6 @@ local function composite(f: Face, o: number, len: number, depth: number): ({ Con if not child then return nil, err end - -- transform the child's points local tc = table.create(#child) :: { Contour } for i, c in child do local nx, ny = table.create(#c.x) :: { number }, table.create(#c.x) :: { number } @@ -308,7 +297,7 @@ contours = function(f: Face, g: number, depth: number): ({ Contour }?, string?) end local o, len = Glyf.range(f, g) if not o then - return {}, nil -- empty glyph (space) + return {}, nil end if len < 10 then return nil, "glyph header past the end" @@ -320,7 +309,6 @@ contours = function(f: Face, g: number, depth: number): ({ Contour }?, string?) return composite(f, o, len, depth) end --- outline(f, g) -> path commands (codecs/image/Raster format, font units, y up) | nil, message function Glyf.outline(f: Face, g: number): ({ any }?, string?) local cs, err = contours(f, g, 0) if not cs then @@ -365,7 +353,7 @@ function Glyf.outline(f: Face, g: number): ({ any }?, string?) local k = (s + i - 1) % n + 1 local x, y, isOn = xs[k], ys[k], on[k] if i == n then - x, y, isOn = sx, sy, true -- back to the start + x, y, isOn = sx, sy, true end if isOn then if off then @@ -387,7 +375,6 @@ function Glyf.outline(f: Face, g: number): ({ any }?, string?) return cmds, nil end --- points(f, g) -> the number of points and contours (for tests) function Glyf.counts(f: Face, g: number): (number, number) local cs = contours(f, g, 0) if not cs then diff --git a/src/Rosetta/codecs/font/TrueType/Tables.luau b/src/Rosetta/codecs/font/TrueType/Tables.luau index 18b468c..081f01e 100644 --- a/src/Rosetta/codecs/font/TrueType/Tables.luau +++ b/src/Rosetta/codecs/font/TrueType/Tables.luau @@ -1,11 +1,6 @@ --!strict --- codecs/font/TrueType/Tables: the sfnt tables besides the outlines: cmap (formats 0, 4, 6, 10, 12, 13; the best Unicode --- subtable, symbol fonts through U+F000), kern (Microsoft version 0 and Apple version 1, format 0 pairs), GPOS pair --- kerning (lookup type 2 formats 1 and 2, reached through the 'kern' feature, including extension lookups, type 9), --- name (UTF-16BE and Mac Roman strings) and OS/2. Written from the OpenType spec, with stb_truetype 1.26 (public --- domain / MIT) as a reference for cmap 4 and the GPOS walk. --- --- Never throws: every read is range-checked (out of range reads as 0). +-- codecs/font/TrueType/Tables: the sfnt cmap (0, 4, 6, 10, 12, 13), kern, GPOS pair kerning, name and OS/2 tables. +-- Written from the OpenType spec; stb_truetype 1.26 (public domain / MIT) was the reference for cmap 4 and GPOS. local Text = require("@rosetta/codecs/text/Text") local Tables = {} @@ -34,10 +29,9 @@ local function u32(b: buffer, o: number): number end Tables.u8, Tables.u16, Tables.i16, Tables.u32 = u8, u16, i16, u32 --- ------------------------------------------------------------------------------------------------ cmap export type Cmap = { buf: buffer, at: number, format: number, symbol: boolean } --- pick the best subtable of the cmap table at [o, o + n): Unicode full repertoire, then BMP, then symbol, then Mac +-- cmap subtable preference: Unicode full repertoire, then BMP, then symbol, then Mac function Tables.cmap(b: buffer, o: number, n: number): Cmap? local count = u16(b, o + 2) local best, bestRank, symbol = -1, 0, false @@ -102,7 +96,6 @@ local function lookup(c: Cmap, cp: number): number local segX2 = u16(b, t + 6) local segs = segX2 // 2 local ends = t + 14 - -- binary search for the first segment whose end >= cp local lo, hi = 0, segs - 1 while lo < hi do local mid = (lo + hi) // 2 @@ -153,7 +146,6 @@ local function lookup(c: Cmap, cp: number): number return 0 end --- glyph(cmap, codepoint) -> glyph index (0 = .notdef) function Tables.glyph(c: Cmap?, cp: number): number if not c or type(cp) ~= "number" or cp < 0 or cp > 0x10FFFF or cp % 1 ~= 0 then return 0 @@ -165,8 +157,6 @@ function Tables.glyph(c: Cmap?, cp: number): number return g end --- ------------------------------------------------------------------------------------------------ kern --- the 'kern' table's horizontal format 0 pairs -> { [left * 65536 + right] = value } function Tables.kern(b: buffer, o: number, n: number): { [number]: number } local pairs: { [number]: number } = {} local e = o + n @@ -219,7 +209,6 @@ function Tables.kern(b: buffer, o: number, n: number): { [number]: number } return pairs end --- ------------------------------------------------------------------------------------------------ GPOS local function popcount(v: number): number local c = 0 while v ~= 0 do @@ -229,7 +218,6 @@ local function popcount(v: number): number return c end --- coverage index of glyph g in the Coverage table at t, or -1 local function coverage(b: buffer, t: number, g: number): number local fmt = u16(b, t) if fmt == 1 then @@ -291,7 +279,6 @@ local function classOf(b: buffer, t: number, g: number): number return 0 end --- the x advance adjustment in a value record with format vf at r local function xAdvance(b: buffer, r: number, vf: number): number if band(vf, 4) == 0 then return 0 @@ -299,7 +286,6 @@ local function xAdvance(b: buffer, r: number, vf: number): number return i16(b, r + 2 * popcount(band(vf, 3))) end --- one PairPos subtable: (applies, value) local function pairPos(b: buffer, t: number, l: number, r: number): (boolean, number) local fmt = u16(b, t) local ci = coverage(b, t + u16(b, t + 2), l) @@ -343,9 +329,8 @@ local function pairPos(b: buffer, t: number, l: number, r: number): (boolean, nu return false, 0 end -export type Gpos = { buf: buffer, subtables: { { number } } } -- per lookup: PairPos subtable offsets +export type Gpos = { buf: buffer, subtables: { { number } } } --- the pair-adjustment lookups of the 'kern' feature (any script / language) of the GPOS table at [o, o + n) function Tables.gpos(b: buffer, o: number, n: number): Gpos? if n < 10 or u16(b, o) ~= 1 then return nil @@ -396,7 +381,6 @@ function Tables.gpos(b: buffer, o: number, n: number): Gpos? return { buf = b, subtables = lookups } end --- gposKern(gpos, left, right) -> the summed x advance adjustment of the first glyph (font units) function Tables.gposKern(g: Gpos, l: number, r: number): number local total = 0 for _, subs in g.subtables do @@ -411,7 +395,6 @@ function Tables.gposKern(g: Gpos, l: number, r: number): number return total end --- ------------------------------------------------------------------------------------------------ name, OS/2 local MAC_ROMAN_HIGH = { 0xC4, 0xC5, 0xC7, 0xC9, 0xD1, 0xD6, 0xDC, 0xE1, 0xE0, 0xE2, 0xE4, 0xE3, 0xE5, 0xE7, 0xE9, 0xE8, 0xEA, 0xEB, 0xED, 0xEC, 0xEE, 0xEF, 0xF1, 0xF3, 0xF2, 0xF4, 0xF6, 0xF5, 0xFA, 0xF9, 0xFB, 0xFC, @@ -456,7 +439,6 @@ local NAME_IDS: { [number]: string } = { [17] = "typographicStyle", } --- names(name table) -> { family, style, fullName, ... } (English Windows names first, then Unicode, then Mac Roman) function Tables.names(b: buffer, o: number, n: number): { [string]: string } local out: { [string]: string } = {} local rank: { [string]: number } = {} @@ -490,7 +472,6 @@ function Tables.names(b: buffer, o: number, n: number): { [string]: string } return out end --- os2(OS/2 table) -> the commonly used fields function Tables.os2(b: buffer, o: number, n: number): { [string]: number } local t: { [string]: number } = { version = u16(b, o), diff --git a/src/Rosetta/codecs/font/TrueType/init.luau b/src/Rosetta/codecs/font/TrueType/init.luau index 56b0eb5..ed66c70 100644 --- a/src/Rosetta/codecs/font/TrueType/init.luau +++ b/src/Rosetta/codecs/font/TrueType/init.luau @@ -1,20 +1,6 @@ --!strict --- codecs/font/TrueType: the sfnt font container (TrueType .ttf, OpenType .otf with CFF outlines, collections .ttc) parsed --- into the standard Font value (Types.Font): metrics (head / hhea / hmtx / OS/2 / post), cmap lookups, glyph outlines --- (codecs/font/TrueType/Glyf for glyf, codecs/font/Cff for "CFF "), kerning ('kern' table and GPOS 'kern' pair adjustments), --- names, and rasterize(glyph, px) through codecs/image/Raster. A codec, not a format: font/ttf, font/woff and font/woff2 all --- build an sfnt and call TrueType.font(). Ported and modernised from stb_truetype 1.26 (public domain / MIT, Sean --- Barrett and contributors) through imgui-luau's imstb_truetype.lua; the rasterizer is codecs/image/Raster instead of stb's. --- Not supported: hinting, variable fonts (fvar / gvar / CFF2), vertical metrics, bitmap strikes (EBDT / CBDT / sbix), --- colour layers (COLR), GSUB substitutions. --- --- local font, err = TrueType.font(buf, offset?, length?, { index = 0 }) -- Types.Font | nil, Err --- local g = font:glyphIndex(0x41) local adv = font:advance(g) -- font units --- local k = font:kern(g1, g2) local cmds = font:outline(g) -- moveTo / lineTo / quadTo / cubicTo --- local img = font:rasterize(g, 32) -- alpha8 Image, 32 px per em; img.meta.left / top / advance (px) --- local n = TrueType.count(buf) -- fonts in a collection (1 for a plain sfnt) --- --- Never throws: malformed fonts return nil, Err from font(), and nil from the per-glyph methods. +-- codecs/font/TrueType: the sfnt container (.ttf, .otf with CFF outlines, .ttc collections) as the standard Font value. +-- Ported from stb_truetype 1.26 (public domain / MIT, Sean Barrett et al.) via imgui-luau's imstb_truetype.lua. local Err = require("@rosetta/core/Err") local Types = require("@rosetta/Types") local Raster = require("@rosetta/codecs/image/Raster") @@ -33,7 +19,6 @@ local function tag(b: buffer, o: number): string return buffer.readstring(b, o, 4) end --- count(buf, offset?) -> the number of fonts (a collection's count, 1 for an sfnt, 0 for neither) function TrueType.count(b: buffer, offset: number?): number local o = offset or 0 local t = tag(b, o) @@ -46,7 +31,6 @@ function TrueType.count(b: buffer, offset: number?): number return 0 end --- tables(buf, file, dir) -> { [tag] = { offset (absolute), length } } of the table directory at dir function TrueType.tables(b: buffer, file: number, dir: number, limit: number): ({ [string]: { number } }?, string?) local n = u16(b, dir + 4) if dir + 12 + n * 16 > limit then @@ -64,7 +48,6 @@ function TrueType.tables(b: buffer, file: number, dir: number, limit: number): ( return out, nil end --- ------------------------------------------------------------------------------------------------ the Font value local Face = {} Face.__index = Face @@ -116,7 +99,6 @@ function Face.kern(self: any, a: number, b: number): number return v end --- kernCodepoints(a, b) -> kern between two code points function Face.kernCodepoints(self: any, a: number, b: number): number return self:kern(self:glyphIndex(a), self:glyphIndex(b)) end @@ -141,7 +123,6 @@ function Face.outline(self: any, g: number): { any }? return cmds end --- bounds(g) -> xMin, yMin, xMax, yMax of the outline's points (font units), nil for an empty / bad glyph function Face.bounds(self: any, g: number): (number?, number, number, number) local cmds = self:outline(g) if not cmds then @@ -160,21 +141,18 @@ function Face.bounds(self: any, g: number): (number?, number, number, number) return x0, y0, x1, y1 end --- scale(px) -> pixels per font unit for an em of px pixels function Face.scale(self: any, px: number): number return px / self.unitsPerEm end export type RasterOptions = { - scaleX: number?, -- pixels per font unit (default px / unitsPerEm); scaleY likewise + scaleX: number?, scaleY: number?, - shiftX: number?, -- subpixel shift (pixels) + shiftX: number?, shiftY: number?, } --- rasterize(g, px, opts?) -> alpha8 Image (meta.left / meta.top: the bitmap's offset from the pen position, pixels; --- top counts up from the baseline as FreeType's bitmap_top; meta.advance in pixels) | nil for a bad glyph. Empty --- glyphs give a 0 x 0 image. +-- meta.top counts up from the baseline, as FreeType's bitmap_top function Face.rasterize(self: any, g: number, px: number, opts: RasterOptions?): Types.Image? if type(px) ~= "number" or not (px > 0) or px > 4096 then return nil @@ -204,10 +182,8 @@ function Face.rasterize(self: any, g: number, px: number, opts: RasterOptions?): return img end --- ------------------------------------------------------------------------------------------------ parsing -export type Options = { index: number? } -- the font in a collection (default 0) +export type Options = { index: number? } --- font(buf, offset?, length?, opts?) -> Types.Font | nil, Err function TrueType.font(buf: buffer, offset: number?, length: number?, opts: Options?): (any, Err.Err?) local b = buf local file = offset or 0 @@ -271,7 +247,6 @@ function TrueType.font(buf: buffer, offset: number?, length: number?, opts: Opti _numHMetrics = nh, _kernCache = {}, }, Face) - -- outlines if t.glyf and t.loca then font._glyf = { buf = b, @@ -296,7 +271,6 @@ function TrueType.font(buf: buffer, offset: number?, length: number?, opts: Opti else return nil, Err.new(Err.UNSUPPORTED, "no glyf or CFF outlines (bitmap-only font?)", dir) end - -- cmap, kerning, names, OS/2, post if t.cmap then font._cmap = Tables.cmap(b, t.cmap[1], t.cmap[2]) end diff --git a/src/Rosetta/codecs/image/Bcn/Decode.luau b/src/Rosetta/codecs/image/Bcn/Decode.luau index 2503a9d..21e6ab7 100644 --- a/src/Rosetta/codecs/image/Bcn/Decode.luau +++ b/src/Rosetta/codecs/image/Bcn/Decode.luau @@ -1,12 +1,9 @@ --!strict --!native --!optimize 2 --- codecs/image/Bcn/Decode: the BC1..BC7 block decoders (S3TC / DXT1-5, RGTC, BPTC). Ported from Pillow's --- src/libImaging/BcnDecode.c (CC0, licenses/pillow-bcn-CC0.txt) and changed to follow the D3D11 functional spec where --- Pillow does not: BC6H interpolation rounds ((a * (64 - w) + b * w + 32) >> 6), BC6H keeps its float values (no 8-bit --- clamp), BC7's reserved mode 8 and BC6H's reserved modes decode to transparent / zero, BC4 / BC5 SNORM interpolate --- the signed values (-128 reads as -127). Each decoder writes one 4x4 block into a 64-byte (rgba8) or 256-byte --- (rgbaf32) scratch block; the caller clips it into the image. Never throws: the caller checks the source size. +-- codecs/image/Bcn/Decode: BC1..BC7 block decoders (S3TC / DXT1-5, RGTC, BPTC), ported from Pillow's BcnDecode.c +-- (CC0, licenses/pillow-bcn-CC0.txt). Follows the D3D11 functional spec where Pillow does not: BC6H rounds +-- (a * (64 - w) + b * w + 32) >> 6 and keeps floats, reserved modes decode to zero, SNORM -128 reads as -127. local Half = require("@rosetta/codecs/image/Half") local Decode = {} @@ -15,8 +12,7 @@ local readu8, readu16, readu32, writeu8, writeu32, writef32 = buffer.readu8, buf local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift local HALF = Half.TABLE --- ------------------------------------------------------------------------------------------------ BC1 / BC2 / BC3 -local pal = buffer.create(16) -- 4 rgba8 colours +local pal = buffer.create(16) local function c565(c: number): (number, number, number) local r = rshift(band(c, 0xF800), 8) @@ -25,7 +21,7 @@ local function c565(c: number): (number, number, number) return bor(r, rshift(r, 5)), bor(g, rshift(g, 6)), bor(b, rshift(b, 5)) end --- the BC1 colour block at p into blk (64 bytes); fourColour = BC2 / BC3 (always the 4-colour palette) +-- BC2 / BC3 colour blocks always use the 4-colour palette local function colour(src: buffer, p: number, blk: buffer, fourColour: boolean) local c0, c1 = readu16(src, p), readu16(src, p + 2) local r0, g0, b0 = c565(c0) @@ -45,7 +41,6 @@ local function colour(src: buffer, p: number, blk: buffer, fourColour: boolean) end end --- the 8 values of a BC3 alpha / BC4 block (unsigned) into vals local vals = table.create(8, 0) local function ramp8(a0: number, a1: number) vals[1], vals[2] = a0, a1 @@ -78,7 +73,6 @@ local function ramp8s(u0: number, u1: number) end end --- one 8-byte BC3 alpha / BC4 block at p into byte `channel` of every blk pixel (and the next ones when spread) local function single(src: buffer, p: number, blk: buffer, channel: number, signed: boolean, spread: boolean) if signed then ramp8s(readu8(src, p), readu8(src, p + 1)) @@ -138,7 +132,6 @@ function Decode.bc5s(src: buffer, p: number, blk: buffer) bc5(src, p, blk, true) end --- ------------------------------------------------------------------------------------------------ BPTC tables -- partition tables (BC7 Table.P2 1 bit per pixel, Table.P3 2 bits per pixel) and the anchor indices local SI2 = { 0xcccc, 0x8888, 0xeeee, 0xecc8, 0xc880, 0xfeec, 0xfec8, 0xec80, 0xc800, 0xffec, 0xfe80, 0xe800, 0xffe8, 0xff00, 0xfff0, 0xf000, @@ -182,7 +175,6 @@ local function subset(ns: number, part: number, i: number): number return 0 end --- the 128-bit block as four u32 words: bits(at, n) for n <= 16 local w0, w1, w2, w3 = 0, 0, 0, 0 local function load(src: buffer, p: number) w0, w1, w2, w3 = readu32(src, p), readu32(src, p + 4), readu32(src, p + 8), readu32(src, p + 12) @@ -202,7 +194,6 @@ local function bits(at: number, n: number): number return band(v, lshift(1, n) - 1) end --- ------------------------------------------------------------------------------------------------ BC7 -- ns, pb, rb, isb, cb, ab, epb, spb, ib, ib2 local MODES7 = { { 3, 4, 0, 0, 4, 0, 1, 0, 3, 0 }, @@ -341,7 +332,6 @@ function Decode.bc7(src: buffer, p: number, blk: buffer) end end --- ------------------------------------------------------------------------------------------------ BC6H -- ns, transformed, pb, epb, rb, gb, bb local MODES6 = { { 2, 1, 5, 10, 5, 5, 5 }, @@ -420,7 +410,6 @@ local function finish(v: number, signed: boolean): number return HALF[(v * 31) // 64] end --- one BC6H block into blk as rgbaf32 (256 bytes, alpha 1) function Decode.bc6h(src: buffer, p: number, blk: buffer, signed: boolean) load(src, p) local m = band(w0, 31) diff --git a/src/Rosetta/codecs/image/Bcn/Encode.luau b/src/Rosetta/codecs/image/Bcn/Encode.luau index 06160c1..24d179b 100644 --- a/src/Rosetta/codecs/image/Bcn/Encode.luau +++ b/src/Rosetta/codecs/image/Bcn/Encode.luau @@ -1,11 +1,8 @@ --!strict --!native --!optimize 2 --- codecs/image/Bcn/Encode: BC1 / BC3 / BC4 / BC5 block encoders (new in rosetta; the approach follows stb_dxt by --- Fabian Giesen / Sean Barrett, public domain: the principal axis of the block's colours by power iteration, the --- extreme pixels along it as endpoints, then least-squares refinement of the endpoints for the chosen indices, keeping --- the best; single-colour blocks use exact endpoint tables). Indices are chosen against the palette exactly as --- Bcn/Decode rebuilds it. BC4 / BC5 channels try both the 8-value and the 6-value (+ 0 / 255) ramps. Never throws. +-- codecs/image/Bcn/Encode: BC1 / BC3 / BC4 / BC5 block encoders, new in rosetta; the approach follows stb_dxt (Fabian +-- Giesen / Sean Barrett, public domain): principal axis endpoints, least-squares refinement, exact single-colour tables. local Encode = {} local readu8, writeu8, writeu16, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu16, buffer.writeu32 @@ -18,7 +15,6 @@ local function exp6(v: number): number return bor(lshift(v, 2), rshift(v, 4)) end --- ------------------------------------------------------------------------------------------------ single colours -- OM[k][v + 1] = e0 * 256 + e1 (quantized) whose colour-2 value (4-colour: (2 e0 + e1) // 3; 3-colour: (e0 + e1) -- // 2) is closest to v; k = 1 / 2 for 5-bit (4 / 3 colour), 3 / 4 for 6-bit local OM: { { number } }? = nil @@ -56,7 +52,6 @@ local function singleTables(): { { number } } return t end --- ------------------------------------------------------------------------------------------------ BC1 colour local R, G, B, A = table.create(16, 0), table.create(16, 0), table.create(16, 0), table.create(16, 0) local USE = table.create(16, true) local PR, PG, PB = table.create(4, 0), table.create(4, 0), table.create(4, 0) @@ -77,7 +72,6 @@ local function palette(c0: number, c1: number, four: boolean) end end --- indices for the palette into IDX (0-based); returns the squared error of the used pixels local function assign(four: boolean): number local n = if four then 4 else 3 local total = 0 @@ -108,11 +102,9 @@ local function q565(r: number, g: number, b: number): number return qr * 2048 + qg * 32 + qb end --- the endpoint weights of index k (the e0 share) local W4 = { 1, 0, 2 / 3, 1 / 3 } local W3 = { 1, 0, 0.5, 0 } --- least squares endpoints for the current IDX: c0, c1 or nil when degenerate local function refine(four: boolean): (number?, number?) local W = if four then W4 else W3 local aa, bb, ab = 0, 0, 0 @@ -142,8 +134,6 @@ local function refine(four: boolean): (number?, number?) return q565(r0, g0, b0), q565(r1, g1, b1) end --- encodes R / G / B (USE marks the pixels that count) as a BC1 colour block at out[o]; four = 4-colour mode --- (opaque), else the 3-colour mode with index 3 for the unused (transparent) pixels local function colourBlock(out: buffer, o: number, four: boolean) local n, mr, mg, mb = 0, 0, 0, 0 for i = 1, 16 do @@ -276,7 +266,6 @@ local function colourBlock(out: buffer, o: number, four: boolean) writeu32(out, o + 4, bitsv) end --- ------------------------------------------------------------------------------------------------ BC4 channel local V = table.create(16, 0) local RAMP = table.create(8, 0) local SEL = table.create(16, 0) @@ -314,7 +303,6 @@ local function pick(): number return total end --- encodes V[1..16] (0..255) as an 8-byte BC4 block at out[o] local function channelBlock(out: buffer, o: number) local lo, hi = 255, 0 local lo2, hi2 = 255, 0 @@ -380,8 +368,6 @@ local function channelBlock(out: buffer, o: number) writeu8(out, o + 7, rshift(hi24, 16)) end --- ------------------------------------------------------------------------------------------------ whole images --- the 4x4 block at bx, by of an rgba8 image into R / G / B / A (edge pixels repeat) local function gather(px: buffer, w: number, h: number, bx: number, by: number) for y = 0, 3 do local sy = math.min(by * 4 + y, h - 1) @@ -394,7 +380,6 @@ local function gather(px: buffer, w: number, h: number, bx: number, by: number) end end --- encode(kind, rgba8 pixels, w, h, alphaThreshold) -> the block data (kind = bc1 / bc3 / bc4 / bc5) function Encode.run(kind: string, px: buffer, w: number, h: number, threshold: number): buffer local bw, bh = (w + 3) // 4, (h + 3) // 4 local bytes = if kind == "bc1" or kind == "bc4" then 8 else 16 diff --git a/src/Rosetta/codecs/image/Bcn/init.luau b/src/Rosetta/codecs/image/Bcn/init.luau index f980e7b..9b55535 100644 --- a/src/Rosetta/codecs/image/Bcn/init.luau +++ b/src/Rosetta/codecs/image/Bcn/init.luau @@ -1,26 +1,14 @@ --!strict --!native --!optimize 2 --- codecs/image/Bcn: the BCn block-compressed texture codecs, shared by the texture formats (DDS, KTX, VTF, BLP, ...): --- decode of BC1 (DXT1, with the 3-colour + transparent mode), BC2 (DXT3), BC3 (DXT5), BC4 / BC5 (RGTC / ATI1 / ATI2, --- UNORM and SNORM), BC6H (UF16 / SF16, to rgbaf32) and BC7 (all 8 modes); encode of BC1 / BC3 / BC4 / BC5 (UNORM). --- Decoders ported from Pillow's BcnDecode.c (CC0) with the D3D11 rules; encoders new (stb_dxt-style). Never throws. --- --- local px, err = Bcn.decode("bc7", buf, offset, w, h) -- rgba8 pixels (rgbaf32 for bc6h / bc6hs) --- local blocks = Bcn.encode("bc1", rgba8Pixels, w, h) -- the block data (row-major blocks) --- Bcn.size("bc3", w, h) -- bytes of a w x h image (whole 4x4 blocks) --- --- Channels: BC4 decodes to grey (r = g = b, opaque), BC5 to red + green (blue 0, opaque); SNORM values are biased by --- 128 into rgba8 (-127 -> 1, 0 -> 128, 127 -> 255). BC1 / BC3 / BC5 encode reads R / G (BC4: R), BC1 alpha below --- opts.alphaThreshold (default 128) selects the transparent 3-colour mode. +-- codecs/image/Bcn: BC1-BC7 block-compressed textures with the D3D11 rules. +-- Decoders ported from Pillow's BcnDecode.c (CC0); encoders new (stb_dxt-style). SNORM is biased by 128 into rgba8. local Decode = require("@rosetta/codecs/image/Bcn/Decode") local Encode = require("@rosetta/codecs/image/Bcn/Encode") local Bcn = {} --- kind -> bytes per 4x4 block Bcn.BLOCK = table.freeze({ bc1 = 8, bc2 = 16, bc3 = 16, bc4 = 8, bc4s = 8, bc5 = 16, bc5s = 16, bc6h = 16, bc6hs = 16, bc7 = 16 }) :: { [string]: number } --- kinds that decode to rgbaf32 Bcn.FLOAT = table.freeze({ bc6h = true, bc6hs = true }) :: { [string]: boolean } local readu32, writeu32 = buffer.readu32, buffer.writeu32 @@ -42,7 +30,6 @@ local BLOCKS: { [string]: (buffer, number, buffer) -> () } = { end, } --- size(kind, w, h) -> bytes of the block data (nil for an unknown kind) function Bcn.size(kind: string, w: number, h: number): number? local b = Bcn.BLOCK[kind] if not b then @@ -51,8 +38,6 @@ function Bcn.size(kind: string, w: number, h: number): number? return ((w + 3) // 4) * ((h + 3) // 4) * b end --- decode(kind, src, offset, w, h, out?, outOffset?) -> pixels (rgba8, or rgbaf32 for BC6H) | nil, message. --- out (optional) receives the pixels at outOffset (default 0) instead of a new buffer. function Bcn.decode(kind: string, src: buffer, offset: number, w: number, h: number, out: buffer?, outOffset: number?): (buffer?, string?) local fn = BLOCKS[kind] if not fn then @@ -103,10 +88,9 @@ function Bcn.decode(kind: string, src: buffer, offset: number, w: number, h: num end export type EncodeOptions = { - alphaThreshold: number?, -- BC1: alpha below this is transparent (default 128; 0 = always opaque) + alphaThreshold: number?, } --- encode(kind, pixels, w, h, opts?) -> block data | nil, message. pixels: rgba8, w x h; kind = bc1 / bc3 / bc4 / bc5. function Bcn.encode(kind: string, px: buffer, w: number, h: number, opts: EncodeOptions?): (buffer?, string?) if kind ~= "bc1" and kind ~= "bc3" and kind ~= "bc4" and kind ~= "bc5" then return nil, "unsupported: no encoder for " .. tostring(kind) diff --git a/src/Rosetta/codecs/image/Blend.luau b/src/Rosetta/codecs/image/Blend.luau index 68c4405..cf23b84 100644 --- a/src/Rosetta/codecs/image/Blend.luau +++ b/src/Rosetta/codecs/image/Blend.luau @@ -1,16 +1,7 @@ --!strict --!native --- codecs/image/Blend: layer compositing on rgba8 buffers (straight alpha): source-over with the separable and non-separable --- blend modes of the W3C Compositing and Blending Level 1 spec (the Photoshop / Aseprite set), opacity, a grey layer --- mask, clipping (source-atop: the backdrop keeps its alpha) and dissolve. Shared by ops/LayerOps (flatten) and the --- layered formats that must write a composite (layered/psd). Never throws: rectangles are clipped to both buffers. --- --- Blend.composite(dst, dw, dh, src, sw, sh, x, y, opacity, "multiply", { clip = false, mask = m }) --- Blend.MODES.multiply -> true --- --- Mode names: normal dissolve darken multiply colorBurn linearBurn darkerColor lighten screen colorDodge linearDodge --- (= add) lighterColor overlay softLight hardLight vividLight linearLight pinLight hardMix difference exclusion --- subtract divide hue saturation color luminosity. Unknown names composite as normal. +-- codecs/image/Blend: rgba8 layer compositing (straight alpha) with the W3C Compositing and Blending Level 1 modes. +-- Clipping is source-atop (the backdrop keeps its alpha); unknown mode names composite as normal. local Blend = {} local readu8, writeu8, readu32, writeu32, blen = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32, buffer.len @@ -164,9 +155,6 @@ local function setSat(r: number, g: number, b: number, s: number): (number, numb return (r - mn) * k, (g - mn) * k, (b - mn) * k end --- composite(dst, dw, dh, src, sw, sh, x, y, opacity, mode, opts?): blends the sw x sh rgba8 src onto the dw x dh rgba8 --- dst with its top-left at (x, y). opacity 0..1. opts.clip: keep the backdrop's alpha (clipping masks). opts.mask: --- { pixels: buffer (1 byte per pixel), width, height, x, y, default: 0..255 } in dst coordinates (outside it: default). local function composite(dst: buffer, dw: number, dh: number, src: buffer, sw: number, sh: number, x: number, y: number, opacity: number, mode: string?, opts: { clip: boolean?, mask: any? }?) x, y = floor(x), floor(y) if opacity <= 0 or dw <= 0 or dh <= 0 or sw <= 0 or sh <= 0 then @@ -216,7 +204,6 @@ local function composite(dst: buffer, dw: number, dh: number, src: buffer, sw: n if sa > 0 and not (clip and ba8 == 0) then local sr, sg, sb = readu8(src, so) / 255, readu8(src, so + 1) / 255, readu8(src, so + 2) / 255 if ba8 == 0 then - -- empty backdrop: the source as it is (alpha scaled) writeu32(dst, do_, readu32(src, so)) writeu8(dst, do_ + 3, floor(sa * 255 + 0.5)) else @@ -273,9 +260,6 @@ local function composite(dst: buffer, dw: number, dh: number, src: buffer, sw: n end end --- lerp(dst, from, t, n, w?, mask?): dst = from + (dst - from) * t per byte over n pixels (pass-through group opacity); --- with a mask ({ pixels, width, height, x, y, default } as for composite, in the coordinates of a w-wide canvas) t is --- also scaled by the mask value of each pixel local function lerp(dst: buffer, from: buffer, t: number, n: number, w: number?, mask: any?) if blen(dst) < n * 4 or blen(from) < n * 4 then return @@ -312,7 +296,6 @@ end Blend.composite = composite Blend.lerp = lerp --- ------------------------------------------------------------------------------------------------ layer trees local function isImage(v: any): boolean return type(v) == "table" and v.format == "rgba8" and type(v.pixels) == "buffer" and type(v.width) == "number" and type(v.height) == "number" and buffer.len(v.pixels) >= v.width * v.height * 4 end @@ -324,7 +307,7 @@ local function maskOf(l: any): any end local img = m.image local px = img.pixels - if img.format == "rgba8" then -- use the red channel + if img.format == "rgba8" then local n = img.width * img.height local g = buffer.create(n) for i = 0, n - 1 do @@ -349,7 +332,6 @@ local function compose(layers: { any }, canvas: buffer, w: number, h: number, hi end local opacity = (tonumber(l.opacity) or 1) * (tonumber(l.fillOpacity) or 1) local mode = if type(l.blend) == "string" then l.blend else "normal" - -- the layer's own pixels, as an isolated w x h buffer local src: buffer? = nil if type(l.children) == "table" then if mode == "passThrough" then @@ -386,10 +368,6 @@ local function compose(layers: { any }, canvas: buffer, w: number, h: number, hi end end --- flatten(layers, canvas, w, h, hidden): composites a Types.Layer tree (bottom to top) onto the w x h rgba8 canvas: --- blend modes, opacity x fillOpacity, groups (isolated, or "passThrough": blended straight onto the canvas, the group --- opacity and mask then mixing before / after), clipping layers (clip = true: source-atop onto the layer below), grey masks. --- hidden = true includes invisible layers. function Blend.flatten(layers: { any }, canvas: buffer, w: number, h: number, hidden: boolean) if blen(canvas) >= w * h * 4 then compose(layers, canvas, w, h, hidden) diff --git a/src/Rosetta/codecs/image/Dct/init.luau b/src/Rosetta/codecs/image/Dct/init.luau index 9b9dfe4..db19b7f 100644 --- a/src/Rosetta/codecs/image/Dct/init.luau +++ b/src/Rosetta/codecs/image/Dct/init.luau @@ -2,16 +2,8 @@ --!native --!optimize 2 -- codecs/image/Dct: the 8x8 DCTs JPEG, Motion-JPEG and MPEG-1 share (native; never throws). --- Inverse: libjpeg's islow (jidctint.c: the Loeffler-Ligtenberg-Moschytz algorithm, 13-bit constants, two passes with --- PASS1_BITS of scaling between them), plus the reduced 4x4 / 2x2 / 1x1 IDCTs for scaled decodes (jidctred.c); the --- results match libjpeg-turbo's djpeg bit for bit. Absorbed from jpeg-luau 1.0 src/Jpeg/Idct.luau (same author). --- Forward: libjpeg's islow (jfdctint.c) with jcdctmgr.c's rounding quantiser, so an encoder built on it produces --- the same coefficients as cjpeg. Both are Luau translations of IJG code (licenses/libjpeg-turbo-LICENSE.md). --- Values are exact integers in doubles: no overflow even on corrupt coefficients; outputs are clamped to 0..maxv. --- --- Dct.idctComponent(coef, q, bpl, bpc, size, plane, p1, center, maxv) -- every block of a component --- Dct.idctBlock(coef, off, q, plane, out, stride, p1, center, maxv) -- one 8x8 block (u16 samples) --- Dct.fdctQuantize(src, stride, x, y, w, h, div, coef, off) -- one block from u8 samples +-- libjpeg's islow (jidctint.c / jfdctint.c), the reduced IDCTs (jidctred.c) and jcdctmgr.c's rounding quantiser, bit-exact +-- with libjpeg-turbo. From jpeg-luau 1.0 (same author); IJG code: licenses/libjpeg-turbo-LICENSE.md. local readi16, readu16, writeu16, readu8, writei16 = buffer.readi16, buffer.readu16, buffer.writeu16, buffer.readu8, buffer.writei16 local clamp = math.clamp @@ -243,10 +235,7 @@ local function idct2(coef: buffer, off: number, q: buffer, plane: buffer, out: n end end --- Inverse-transforms every block of a component: coef (i16, 64 per block, natural order) on a bpl x bpc block --- grid, quantisation table q (64 u16, natural order), into plane (u16 samples, (bpl * size) per row) at size x --- size samples per block. p1 is PASS1_BITS (2 for 8-bit, 1 for 12-bit), center the level shift, maxv the top. --- hook (optional): a cooperative yield point after every block row (pcall'ed: it can't throw through here). +-- p1 = PASS1_BITS (2 for 8-bit, 1 for 12-bit) function Dct.idctComponent(coef: buffer, q: buffer, bpl: number, bpc: number, size: number, plane: buffer, p1: number, center: number, maxv: number, hook: (() -> ())?) local stride = bpl * size for by = 0, bpc - 1 do @@ -270,13 +259,10 @@ function Dct.idctComponent(coef: buffer, q: buffer, bpl: number, bpc: number, si end end --- idctBlock(coef, off, q, plane, out, stride, p1, center, maxv): one 8x8 block, coef (i16, natural order) at byte --- offset off, dequantised by q (64 u16), into the u16 plane at sample index out with stride samples per row function Dct.idctBlock(coef: buffer, off: number, q: buffer, plane: buffer, out: number, stride: number, p1: number, center: number, maxv: number) idct8(coef, off, q, plane, out, stride, p1, center, maxv) end --- ------------------------------------------------------------------------------------------------ forward local fw = table.create(64, 0) local function quant(coef: buffer, off: number, div: buffer, v: number, i: number) @@ -289,10 +275,7 @@ local function quant(coef: buffer, off: number, div: buffer, v: number, i: numbe end end --- fdctQuantize(src, stride, x, y, w, h, div, coef, off): the 8x8 block of u8 samples at (x, y) in src (stride bytes --- per row; samples past w - 1 / h - 1 repeat the edge), level-shifted by 128, forward DCT (jfdctint.c islow), then --- quantised as jcdctmgr.c: (|v| + q * 4) // (q * 8) with the sign restored, q = div (64 u16, natural order). Writes --- 64 i16 at coef[off] (natural order). The caller keeps x < w, y < h and the src range valid. +-- quantised as jcdctmgr.c: (|v| + q * 4) // (q * 8) with the sign restored function Dct.fdctQuantize(src: buffer, stride: number, x: number, y: number, w: number, h: number, div: buffer, coef: buffer, off: number) local lastX, lastY = w - 1, h - 1 for r = 0, 7 do diff --git a/src/Rosetta/codecs/image/Etc.luau b/src/Rosetta/codecs/image/Etc.luau index 3fb2d56..25f638e 100644 --- a/src/Rosetta/codecs/image/Etc.luau +++ b/src/Rosetta/codecs/image/Etc.luau @@ -1,17 +1,8 @@ --!strict --!native --!optimize 2 --- codecs/image/Etc: the Ericsson / Khronos block texture codecs, decode only: ETC1, ETC2 RGB (with the T, H and planar --- modes), ETC2 RGBA (an EAC alpha block + ETC2 colour), ETC2 RGB A1 (punch-through alpha) and EAC R11 / RG11 --- (unsigned and signed). Written from the Khronos Data Format Specification 1.3, section 21 (ETC1 / ETC2 / EAC); new --- in rosetta. Shared by the texture formats (KTX, PVR, ...). Never throws: the caller gets a message instead. --- --- local px, err = Etc.decode("etc2_rgba", buf, offset, w, h) -- rgba8 pixels --- local px16 = Etc.decode("eac_rg11", buf, offset, w, h, nil, 0, true) -- rgba16 (EAC keeps its 11 bits) --- Etc.size("etc1", w, h) -- bytes of the block data --- --- Kinds: etc1, etc2_rgb, etc2_rgba, etc2_rgba1, eac_r11, eac_r11s, eac_rg11, eac_rg11s. R11 decodes to grey (r = g = b), --- RG11 to red + green (blue 0); signed values are biased (-1 -> 1, 0 -> 128, +1 -> 255; rgba16: 0 / 32768 / 65535). +-- codecs/image/Etc: ETC1 / ETC2 / EAC block texture decoding (Khronos Data Format Specification 1.3, section 21). +-- New in rosetta. Signed EAC values are biased into rgba8 (-1 -> 1, 0 -> 128, +1 -> 255). local Etc = {} Etc.BLOCK = table.freeze({ etc1 = 8, etc2_rgb = 8, etc2_rgba = 16, etc2_rgba1 = 8, eac_r11 = 8, eac_r11s = 8, eac_rg11 = 16, eac_rg11s = 16 }) :: { [string]: number } @@ -19,7 +10,6 @@ Etc.BLOCK = table.freeze({ etc1 = 8, etc2_rgb = 8, etc2_rgba = 16, etc2_rgba1 = local readu8, readu32, writeu8, writeu16, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu8, buffer.writeu16, buffer.writeu32 local band, rshift, byteswap = bit32.band, bit32.rshift, bit32.byteswap --- ------------------------------------------------------------------------------------------------ tables local MOD = { -- the ETC1 intensity modifiers per table: index (msb * 2 + lsb) -> a, b, -a, -b { 2, 8, -2, -8 }, { 5, 17, -5, -17 }, @@ -57,9 +47,8 @@ local function rgb(r: number, g: number, b: number): number return clamp8(r) + clamp8(g) * 256 + clamp8(b) * 65536 + 0xFF000000 end --- ------------------------------------------------------------------------------------------------ colour blocks -- blk: 16 u32 rgba8 pixels in raster order (y * 4 + x) -local P = table.create(4, 0) -- T / H paint colours (rgba8 u32) +local P = table.create(4, 0) local function be32(src: buffer, p: number): number return byteswap(readu32(src, p)) @@ -70,7 +59,7 @@ local function pix(lo: number, i: number): number return band(rshift(lo, i + 15), 2) + band(rshift(lo, i), 1) end --- ETC1 / ETC2 colour block at p into blk. etc2: T / H / planar modes; punch: the RGB A1 variant (bit 33 = opaque). +-- ETC1 / ETC2 colour block; the RGB A1 variant: bit 33 = opaque local function colour(src: buffer, p: number, blk: buffer, etc2: boolean, punch: boolean) local hi, lo = be32(src, p), be32(src, p + 4) local diffBit = band(rshift(hi, 1), 1) @@ -142,7 +131,6 @@ local function colour(src: buffer, p: number, blk: buffer, etc2: boolean, punch: r2, g2, b2 = R2 * 8 + rshift(R2, 2), G2 * 8 + rshift(G2, 2), B2 * 8 + rshift(B2, 2) end if not r1 then - -- T / H: the paint colours by index for i = 0, 15 do local x, y = rshift(i, 2), band(i, 3) local idx = pix(lo, i) @@ -175,10 +163,8 @@ local function colour(src: buffer, p: number, blk: buffer, etc2: boolean, punch: end end --- ------------------------------------------------------------------------------------------------ EAC local VALS = table.create(16, 0) --- the 16 values of the EAC block at p into VALS (raster order): mode "alpha" (8-bit), "u11" / "s11" (11-bit) local function eac(src: buffer, p: number, mode: string) local base = readu8(src, p) local b1 = readu8(src, p + 1) @@ -211,7 +197,6 @@ local function eac(src: buffer, p: number, mode: string) end end --- 11-bit values -> 8 / 16 bits local function to8(v: number, signed: boolean): number if signed then return math.floor(v * 127 / 1023 + 0.5) + 128 @@ -225,15 +210,11 @@ local function to16(v: number, signed: boolean): number return v * 32 + rshift(v, 6) end --- ------------------------------------------------------------------------------------------------ decode --- size(kind, w, h) -> bytes of the block data | nil for an unknown kind function Etc.size(kind: string, w: number, h: number): number? local b = Etc.BLOCK[kind] return if b then ((w + 3) // 4) * ((h + 3) // 4) * b else nil end --- decode(kind, src, offset, w, h, out?, outOffset?, wide?) -> pixels | nil, message. rgba8, or rgba16 for the EAC --- kinds when wide is true. function Etc.decode(kind: string, src: buffer, offset: number, w: number, h: number, out: buffer?, outOffset: number?, wide: boolean?): (buffer?, string?) local bytes = Etc.BLOCK[kind] if not bytes then diff --git a/src/Rosetta/codecs/image/Half.luau b/src/Rosetta/codecs/image/Half.luau index 8bbe1c1..16a2793 100644 --- a/src/Rosetta/codecs/image/Half.luau +++ b/src/Rosetta/codecs/image/Half.luau @@ -1,17 +1,11 @@ --!strict --!native --!optimize 2 --- codecs/image/Half: IEEE 754 binary16 ("half") <-> number, for the float texel formats (DDS / KTX R16F..., BC6H, --- OpenEXR HALF channels). New in rosetta. Never throws. --- --- local f = Half.TABLE[h] -- the number of every half bit pattern 0..65535 (a 65536-entry table) --- local f = Half.toFloat(h) -- the same, computed --- local h = Half.fromFloat(f) -- round to nearest even; overflow -> infinity, NaN -> a quiet NaN +-- codecs/image/Half: IEEE 754 binary16 <-> number (round to nearest even, overflow to infinity). New in rosetta. local Half = {} local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift --- toFloat(h) -> number (h a 16-bit pattern) local function toFloat(h: number): number local s = if h >= 32768 then -1 else 1 local e = band(rshift(h, 10), 31) @@ -33,7 +27,6 @@ Half.TABLE = TABLE local scratch = buffer.create(4) --- fromFloat(f) -> the nearest half bit pattern (ties to even) function Half.fromFloat(f: number): number if f ~= f then return 0x7E00 diff --git a/src/Rosetta/codecs/image/Jpeg/Arith.luau b/src/Rosetta/codecs/image/Jpeg/Arith.luau index 4dcf84f..2db3930 100644 --- a/src/Rosetta/codecs/image/Jpeg/Arith.luau +++ b/src/Rosetta/codecs/image/Jpeg/Arith.luau @@ -1,15 +1,9 @@ --!strict --!native --!optimize 2 --- codecs/image/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. --- --- It reads the destuffed scan data that Scan.destuff produces (0xFF 0x00 already removed, RSTn positions recorded); --- past the end of a restart segment it reads zero bytes, the convention libjpeg follows when the decoder runs into a --- marker (libjpeg's encoder also drops trailing zero bytes, so reading past the end is normal and not a sign of --- truncation: the caller flags a scan that runs into the end of the file instead). Statistics bins live in one buffer: DC tables at [t * 64], AC tables at [256 + t * 256], the fixed 0.5 --- bin at [1280]. +-- codecs/image/Jpeg/Arith: arithmetic-coded scans (ITU T.81 annex D / F.1.4, sequential and progressive). +-- A Luau translation of libjpeg-turbo's jdarith.c / jaricom.c (IJG licence: licenses/libjpeg-turbo-LICENSE.md); past the +-- end of a restart segment it reads zero bytes, as libjpeg does. Bins: DC [t * 64], AC [256 + t * 256], fixed 0.5 [1280]. local readu8, writeu8, readi16, writei16 = buffer.readu8, buffer.writeu8, buffer.readi16, buffer.writei16 local band, bxor = bit32.band, bit32.bxor @@ -50,7 +44,7 @@ do end end -local ZZ: buffer = buffer.create(80) -- set by Arith.init (Scan.ZIGZAG) +local ZZ: buffer = buffer.create(80) local STATS = 1281 local POW2 = buffer.create(8) @@ -59,11 +53,10 @@ for i = 0, 7 do end local FIXED = 1280 --- decoder state (one scan at a time; never yields) local D: buffer = buffer.create(0) -local P = 0 -- next byte -local SEGEND = 0 -- reads at or past this return 0 -local OVER = 0 -- zero bytes supplied past the end +local P = 0 +local SEGEND = 0 +local OVER = 0 local C, A, CT = 0, 0, -16 local st: buffer = buffer.create(STATS) @@ -130,7 +123,7 @@ export type ArithComp = { v: number, bw: number, bh: number, - dcTbl: number, -- 0..3 + dcTbl: number, acTbl: number, pred: number, ctx: number, @@ -141,16 +134,16 @@ export type ArithParams = { mcusX: number, mcusY: number, ri: number, - mode: number, -- 0 sequential, 1 DC first, 2 DC refine, 3 AC first, 4 AC refine + mode: number, ss: number, se: number, al: number, - dcL: { number }, -- conditioning per table (DAC), 1-based by table + 1 + dcL: { number }, dcU: { number }, acK: { number }, } --- DC difference (F.1.4.4.1 / figures F.19, F.21 - F.24); returns the new predictor or nil on a bad code +-- DC difference (F.1.4.4.1 / figures F.19, F.21 - F.24) local function dcDiff(c: ArithComp, L: number, U: number): number? local base = c.dcTbl * 64 local s = base + c.ctx @@ -194,7 +187,7 @@ local function dcDiff(c: ArithComp, L: number, U: number): number? return band(c.pred + v, 0xFFFF) end --- AC coefficients k = ss..se of one block (figure F.20); false on a bad code +-- AC coefficients k = ss..se of one block (figure F.20) local function acFirst(coef: buffer, off: number, tbl: number, ss: number, se: number, K: number, mul: number): boolean local base = 256 + tbl * 256 local k = ss @@ -292,7 +285,6 @@ function Arith.init(zigzag: buffer) ZZ = zigzag end --- run(d, cleanLen, rst, nrst, P) -> truncated: decodes one scan (see Scan.run for the data layout) function Arith.run(d: buffer, cleanLen: number, rst: { number }, nrst: number, Pm: ArithParams): boolean local comps = Pm.comps local nc = #comps diff --git a/src/Rosetta/codecs/image/Jpeg/Color.luau b/src/Rosetta/codecs/image/Jpeg/Color.luau index 41468c2..a950a24 100644 --- a/src/Rosetta/codecs/image/Jpeg/Color.luau +++ b/src/Rosetta/codecs/image/Jpeg/Color.luau @@ -1,19 +1,9 @@ --!strict --!native --!optimize 2 --- codecs/image/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). --- --- Upsampling follows libjpeg-turbo's jdsample.c, so the output matches djpeg's defaults: --- FULL the component is at output resolution --- H2V1 "fancy" triangle filter, 3/4 nearer + 1/4 further sample, alternating rounding (1, 2) / 4 --- H2V2 fancy in both directions: vertical 3:1 column sums, then horizontal 3:1, rounding (8, 7) / 16 --- H1V2 fancy vertical only, rounding 1 (upper row) / 2 (lower row) --- REPLICATE any other ratio (or no fancy upsampling): nearest sample, as int_upsample --- Edges replicate the last real sample (downW x downH), as libjpeg does with its context rows. --- Colour conversion is jdcolor.c's table-driven YCbCr -> RGB (16-bit fixed point), plus grey, RGB, CMYK and --- YCCK (Adobe inverted CMYK: R = C * K / 255). +-- codecs/image/Jpeg/Color: chroma upsampling (libjpeg-turbo jdsample.c: fancy H2V1 / H2V2 / H1V2, else replicate) and +-- colour conversion (jdcolor.c; YCCK = Adobe inverted CMYK), matching djpeg's defaults. From jpeg-luau 1.0, a Luau +-- translation of libjpeg-turbo (IJG licence: licenses/libjpeg-turbo-LICENSE.md). local readu16, readi32, readu8, writeu16, writeu32 = buffer.readu16, buffer.readi32, buffer.readu8, buffer.writeu16, buffer.writeu32 local clamp, min, max = math.clamp, math.min, math.max @@ -31,20 +21,20 @@ Color.RGB = 2 Color.CMYK = 3 Color.YCCK = 4 Color.CMYK_PLAIN = 5 -- CMYK without an Adobe marker: not inverted -Color.RAW = 6 -- no conversion: components 1..4 as R, G, B, A (opts.raw: BLP1's BGRA JPEGs, ...) +Color.RAW = 6 export type Comp = { - plane: buffer, -- u16 samples, stride per row + plane: buffer, stride: number, - rows: number, -- plane height - downW: number, -- real samples across / down (the rest is block padding) + rows: number, + downW: number, downH: number, method: number, hIn: number, hOut: number, vIn: number, vOut: number, - row: buffer, -- scratch row (u16, at least max(outW, 2 * downW) + 8 samples) + row: buffer, } export type Params = { @@ -54,13 +44,12 @@ export type Params = { outH: number, maxv: number, pixels: buffer, - -- YCbCr tables (maxv + 1 i32 entries) crr: buffer, cbb: buffer, crg: buffer, cbg: buffer, - toByte: buffer?, -- maxv + 1 u8 entries (12-bit), nil for 8-bit - hook: (() -> ())?, -- a cooperative yield point every 8 rows (pcall'ed: it can't throw through here) + toByte: buffer?, + hook: (() -> ())?, } -- jdcolor.c build_ycc_rgb_table @@ -81,7 +70,6 @@ function Color.tables(maxv: number): (buffer, buffer, buffer, buffer) return crr, cbb, crg, cbg end --- fills c.row with output row y; returns the buffer and byte offset of the row's samples local function fetch(c: Comp, y: number, outW: number): (buffer, number) local method = c.method local plane, stride, row = c.plane, c.stride, c.row @@ -197,7 +185,6 @@ function Color.run(P: Params) continue end if space == 1 and not toByte then - -- the common case: 8-bit YCbCr for x = 0, outW - 1 do local i = x * 2 local yv, cb, cr = readu16(s0, b0 + i), readu16(s1, b1 + i), readu16(s2, b2 + i) diff --git a/src/Rosetta/codecs/image/Jpeg/Decode.luau b/src/Rosetta/codecs/image/Jpeg/Decode.luau index 650ff53..655dcca 100644 --- a/src/Rosetta/codecs/image/Jpeg/Decode.luau +++ b/src/Rosetta/codecs/image/Jpeg/Decode.luau @@ -1,10 +1,7 @@ --!strict --- codecs/image/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/image/Jpeg/Decode for the video formats. +-- codecs/image/Jpeg/Decode: the JPEG marker parser and output stage (it validates everything the native loops index). +-- From jpeg-luau 1.0 (same author), extended with SOF9 / SOF10 / DAC, EXIF / ICC / AVI1 segments and yuv420p output; +-- the IDCT size choice for scaled decodes follows libjpeg-turbo's jdmaster.c. local Scan = require("@rosetta/codecs/image/Jpeg/Scan") local Arith = require("@rosetta/codecs/image/Jpeg/Arith") local Color = require("@rosetta/codecs/image/Jpeg/Color") @@ -36,7 +33,7 @@ local function stdTable(class: string, slot: number): buffer? return stdBuilt[key] end --- the EXIF TIFF block (after "Exif\0\0") and its orientation tag, from an APP1 segment at [p, e) +-- the EXIF TIFF block (after "Exif\0\0") and its orientation tag local function exif(b: buffer, p: number, e: number): (number?, number?) if e - p < 14 or buffer.readstring(b, p, 6) ~= "Exif\0\0" then return nil, nil @@ -91,7 +88,7 @@ type Comp = { bw: number, bh: number, coef: buffer?, - quant: buffer?, -- latched at the component's first scan + quant: buffer?, dct: buffer?, act: buffer?, dcTbl: number, @@ -124,7 +121,6 @@ local SOF_REFUSED = { [0xCF] = "hierarchical arithmetic-coded", } --- failures carry a code: "corrupt" | "unsupported" | "limit" | "truncated" local function parseSof(b: buffer, p: number, e: number, m: number): (Frame?, string?, string?) if e - p < 6 then return nil, "corrupt", "short SOF" @@ -228,15 +224,13 @@ export type State = { icc: buffer?, comments: { string }, truncated: boolean, - raw: boolean, -- opts.raw: no colour conversion + raw: 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) - hook: (() -> ())?, -- opts.yield: the cooperative yield point (scans, IDCT, colour conversion) + endPos: number, + hook: (() -> ())?, } --- parse(b, base, limit, opts, headerOnly) -> State | nil, code, message. Walks the markers in b[base, limit); with --- headerOnly it stops at the frame header, otherwise it decodes every scan into the components' coefficients. function Decode.parse(b: buffer, base: number, n: number, opts: any, headerOnly: boolean): (State?, string?, string?) if n - base < 4 or readu8(b, base) ~= 0xFF or readu8(b, base + 1) ~= 0xD8 then return nil, "corrupt", "not a JPEG file (no SOI marker)" @@ -587,7 +581,6 @@ end local toByte12: buffer? = nil --- output(st) -> width, height, rgba8 pixels, colour space | nil, code, message function Decode.output(st: State): (number?, any, any, string?) local f: Frame = st.frame local scale = st.scale @@ -642,7 +635,7 @@ function Decode.output(st: State): (number?, any, any, string?) vOut = vOut, row = buffer.create((math.max(outW, 2 * stride) + 8) * 2), }) - c.coef = nil -- free the coefficients early + c.coef = nil end local space = colorSpaceOf(f, st.adobe, st.jfif) local spaceId = SPACE_IDS[space] @@ -682,14 +675,8 @@ 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 +-- outputYuv: 4:2:0, 4:2:2 (chroma row pairs averaged, rounding up), 4:4:4 (2 x 2 averaged, rounding to nearest) or grey +-- (chroma 128) straight from the IDCT planes; full scale only local scratch: buffer? = nil local function scratchPlane(n: number): buffer local sc = scratch @@ -734,7 +721,7 @@ function Decode.outputYuv(st: State): (number?, number?, buffer?, string?) end for _, c in comps do if c.coef and not c.quant then - return nil, nil, nil, nil -- output() reports the missing table + return nil, nil, nil, nil end end local w, h = f.width, f.height diff --git a/src/Rosetta/codecs/image/Jpeg/Encode.luau b/src/Rosetta/codecs/image/Jpeg/Encode.luau index f0c0f8e..c72711d 100644 --- a/src/Rosetta/codecs/image/Jpeg/Encode.luau +++ b/src/Rosetta/codecs/image/Jpeg/Encode.luau @@ -1,14 +1,9 @@ --!strict --!native --!optimize 2 --- codecs/image/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, 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/image/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/image/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. +-- codecs/image/Jpeg/Encode: the JPEG encoder, baseline (SOF0) and progressive (SOF2, jpeg_simple_progression). +-- Follows libjpeg-turbo step for step (jccolor.c, jcsample.c, jccoefct.c, jfdctint.c / jcdctmgr.c, jchuff.c, jcphuff.c) +-- so its output is byte-identical to cjpeg's; Luau translation of IJG code: licenses/libjpeg-turbo-LICENSE.md. local Dct = require("@rosetta/codecs/image/Dct") local Tables = require("@rosetta/codecs/image/Jpeg/Tables") @@ -38,7 +33,6 @@ do end Encode.ZIGZAG = ZZ --- ------------------------------------------------------------------------------------------------ output local OUT = buffer.create(0) local OP = 0 local CAP = 0 @@ -100,7 +94,6 @@ local function nbits(v: number): number return if v == 0 then 0 else 32 - countlz(v) end --- ------------------------------------------------------------------------------------------------ Huffman tables -- a derived table: u16 code + u8 size per symbol (jpeg_make_c_derived_tbl) export type Derived = { code: buffer, size: buffer } @@ -222,7 +215,6 @@ local function optimal(freqIn: { number }): ({ number }, { number }) end Encode.optimal = optimal --- ------------------------------------------------------------------------------------------------ entropy coding state local dcTab: { Derived } = {} local acTab: { Derived } = {} local dcFreq: { { number } } = {} @@ -241,14 +233,14 @@ export type Comp = { h: number, v: number, tq: number, - td: number, -- DC table slot - ta: number, -- AC table slot - bw: number, -- real blocks across / down + td: number, + ta: number, + bw: number, bh: number, - bpl: number, -- MCU-padded block grid + bpl: number, bpc: number, - coef: buffer, -- i16, 64 per block, natural order - last: number, -- DC predictor + coef: buffer, + last: number, } local function dcDiff(c: Comp, diff: number) @@ -379,7 +371,7 @@ local function blockAcRefine(c: Comp, off: number, ss: number, se: number, al: n end end local r = 0 - local br = 0 -- correction bits added in this block, at CORR[brStart + 1 ..] + local br = 0 local brStart = BE for k = ss, se do local t = absv[k + 1] @@ -425,10 +417,8 @@ local function blockAcRefine(c: Comp, off: number, ss: number, se: number, al: n end end --- ------------------------------------------------------------------------------------------------ scans export type ScanSpec = { comps: { number }, ss: number, se: number, ah: number, al: number } --- iterate the scan's MCUs (or blocks, for one component), calling fn(c, off) per block; restart markers when ri > 0 local function walk(comps: { Comp }, mcusX: number, mcusY: number, ri: number, onRestart: (number) -> (), fn: (Comp, number) -> ()) local nc = #comps local units, ux @@ -490,7 +480,6 @@ local function sos(comps: { Comp }, ss: number, se: number, ah: number, al: numb byte(ah * 16 + al) end --- ------------------------------------------------------------------------------------------------ planes -- jccolor.c rgb_ycc_start tables (16-bit fixed point) local function fix(x: number): number return math.floor(x * 65536 + 0.5) @@ -500,7 +489,6 @@ local CBR, CBG, HALF = fix(0.16874), fix(0.33126), fix(0.5) local CRG, CRB = fix(0.41869), fix(0.08131) local OFF = 128 * 65536 + 32768 - 1 --- pixels (rgba8 / rgb8 / gray8) -> Y, Cb, Cr planes (w * h bytes each; Cb / Cr nil for grey output) local function planes(px: buffer, w: number, h: number, bpp: number, gray: boolean): (buffer, buffer?, buffer?) local n = w * h local Y = buffer.create(n) @@ -534,8 +522,7 @@ local function planes(px: buffer, w: number, h: number, bpp: number, gray: boole return Y, Cb, Cr end --- jcsample.c: a full-resolution plane (w x h) -> the component's samples, (bw * 8) x ch, for factors hf x vf --- (1 or 2 each); full-resolution columns past w - 1 repeat the last one, rows past h - 1 the last row +-- jcsample.c downsampling: columns past w - 1 repeat the last one, rows past h - 1 the last row local function downsample(src: buffer, w: number, h: number, hf: number, vf: number, outW: number, outH: number): buffer local out = buffer.create(outW * outH) for oy = 0, outH - 1 do @@ -562,22 +549,18 @@ local function downsample(src: buffer, w: number, h: number, hf: number, vf: num return out end --- ------------------------------------------------------------------------------------------------ encode export type Options = { - quality: number, -- 1..100 - sampling: string, -- "444" | "422" | "420" + quality: number, + sampling: string, progressive: boolean, - optimize: boolean, -- baseline: optimised Huffman tables (progressive always optimises) + optimize: boolean, gray: boolean, - restart: number, -- MCUs per restart interval (0 = none) - segments: { { marker: number, data: buffer } }, -- APPn / COM segments after the JFIF header + restart: number, + segments: { { marker: number, data: buffer } }, jfif: boolean, 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), 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) @@ -619,7 +602,6 @@ function Encode.run(px: buffer, w: number, h: number, bpp: number, o: Options): qdiv[t] = b end - -- components and their quantised coefficients local comps: { Comp } = {} local srcs = if o.gray then { Y } else { Y, Cb :: buffer, Cr :: buffer } for i, src in srcs do @@ -668,7 +650,6 @@ function Encode.run(px: buffer, w: number, h: number, bpp: number, o: Options): comps[i] = c end - -- headers byte(0xFF) byte(0xD8) if o.jfif then @@ -845,7 +826,6 @@ function Encode.run(px: buffer, w: number, h: number, bpp: number, o: Options): walk(sComps, mcusX, mcusY, o.restart, onRestart, blockFn) emitEobrun() end - -- gather statistics, then emit the optimal tables this scan uses if not (isDc and ah > 0) then GATHER = true for t = 1, ntab do diff --git a/src/Rosetta/codecs/image/Jpeg/Scan.luau b/src/Rosetta/codecs/image/Jpeg/Scan.luau index 5b6faab..fb18936 100644 --- a/src/Rosetta/codecs/image/Jpeg/Scan.luau +++ b/src/Rosetta/codecs/image/Jpeg/Scan.luau @@ -1,16 +1,8 @@ --!strict --!native --!optimize 2 --- codecs/image/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, --- records where each RSTn marker fell, and stops at any other marker. The clean buffer is followed by at least --- PAD zero bytes, so the bit reader can read 32 bits at any position up to PAD bytes past the end without a --- bounds check. `run` checks the position once per MCU, and no MCU (at most 10 blocks, enforced by the parser) --- can consume PAD bytes. So every buffer index stays in range, even on garbage data. --- --- The bit reader keeps no state but a bit position: `peek` reads the big-endian 32-bit word that holds it. +-- codecs/image/Jpeg/Scan: Huffman-coded scan decoding into quantised DCT coefficients. From jpeg-luau 1.0 (same author). +-- The clean scan data is followed by PAD zero bytes, so the 32-bit big-endian bit reader needs no bounds check. -- Huffman tables (built by `buildTable`) are buffers: -- [0, 1024) fast lookup by the next 9 bits: u16 (length << 8) | symbol, 0 = longer code -- [1024, 1096) maxcode[l], l = 0..17: u32, one past the last code of length l, left-aligned to 16 bits @@ -58,8 +50,7 @@ do end Scan.ZIGZAG = ZZ --- Builds a Huffman table from the 16 code-length counts and the symbols (Luau arrays, 1-based). An --- over-subscribed table keeps the codes that fit; the rest decode as invalid. +-- an over-subscribed table keeps the codes that fit; the rest decode as invalid function Scan.buildTable(counts: { number }, symbols: { number }): buffer local t = buffer.create(Scan.TABLE_SIZE) local code, k = 0, 0 @@ -87,7 +78,6 @@ function Scan.buildTable(counts: { number }, symbols: { number }): buffer writeu8(t, T_VAL + i - 1, symbols[i]) end writeu16(t, T_COUNT, k) - -- fast lookups for i = 1, k do local l = sizes[i] if l <= 9 then @@ -110,9 +100,6 @@ function Scan.buildTable(counts: { number }, symbols: { number }): buffer return t end --- Copies the entropy-coded data at src[pos..n) into dst (at least n - pos + PAD bytes): byte stuffing removed, --- RSTn offsets (in dst) stored in rst[1..]. Returns the source position of the marker that ended the scan (or n), --- the clean length, and the RST count. The PAD bytes after the clean data are zeroed. function Scan.destuff(src: buffer, pos: number, n: number, dst: buffer, rst: { number }): (number, number, number) local o, nr = 0, 0 while pos < n do @@ -170,7 +157,6 @@ local function huff(d: buffer, pos: number, t: buffer): (number, number) return readu8(t, T_VAL + idx), pos + l end --- the next s bits (1 <= s <= 16) as an unsigned number local function bits(d: buffer, pos: number, s: number): number return rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 32 - s) end @@ -182,7 +168,6 @@ local function extend(v: number, s: number): number return v end --- sequential (baseline / extended) block: returns pos, DC predictor local function blockSeq(d: buffer, pos: number, coef: buffer, off: number, dct: buffer, act: buffer, pred: number): (number, number) local s s, pos = huff(d, pos, dct) @@ -354,11 +339,11 @@ local function blockAcRefine(d: buffer, pos: number, coef: buffer, off: number, end export type ScanComp = { - coef: buffer, -- i16 coefficients, 64 per block in natural order, blocks row-major on a bpl-wide grid + coef: buffer, bpl: number, h: number, v: number, - bw: number, -- blocks across / down the component itself (non-interleaved scans) + bw: number, bh: number, dct: buffer?, act: buffer?, @@ -369,16 +354,14 @@ export type ScanParams = { comps: { ScanComp }, mcusX: number, mcusY: number, - ri: number, -- restart interval in MCUs (0 = none) - mode: number, -- 0 sequential, 1 DC first, 2 DC refine, 3 AC first, 4 AC refine + ri: number, + mode: number, ss: number, se: number, al: number, - hook: (() -> ())?, -- a cooperative yield point after every MCU row (pcall'ed: it can't throw through here) + hook: (() -> ())?, } --- Decodes one scan from the clean data d (cleanLen bytes, then PAD zeros). Returns the final bit position and --- whether the data ran out (or overran) before the last MCU. function Scan.run(d: buffer, cleanLen: number, rst: { number }, nrst: number, P: ScanParams): (number, boolean) local comps = P.comps local nc = #comps diff --git a/src/Rosetta/codecs/image/Jpeg/Tables.luau b/src/Rosetta/codecs/image/Jpeg/Tables.luau index 35c5af6..3c5e16a 100644 --- a/src/Rosetta/codecs/image/Jpeg/Tables.luau +++ b/src/Rosetta/codecs/image/Jpeg/Tables.luau @@ -63,7 +63,6 @@ Tables.CHROMA = { 99, 99, 99, 99, 99, 99, 99, 99, } --- quant(base, quality) -> 64 values (natural order) for quality 1..100, clamped to 1..255 (baseline) function Tables.quant(base: { number }, quality: number): { number } local q = math.clamp(math.floor(quality), 1, 100) local scale = if q < 50 then 5000 // q else 200 - q * 2 diff --git a/src/Rosetta/codecs/image/Jpeg/Yuv.luau b/src/Rosetta/codecs/image/Jpeg/Yuv.luau index b9b0925..cd6938d 100644 --- a/src/Rosetta/codecs/image/Jpeg/Yuv.luau +++ b/src/Rosetta/codecs/image/Jpeg/Yuv.luau @@ -1,23 +1,18 @@ --!strict --!native --!optimize 2 --- codecs/image/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/image/Jpeg/Decode, codecs/image/Jpeg) size every buffer; each loop reads and writes inside those sizes. +-- codecs/image/Jpeg/Yuv: the JPEG decoder's u16 IDCT planes -> u8 yuv420p; 4:2:2 / 4:4:4 chroma averaged to 4:2:0, +-- the two fields of AVI1 interlaced Motion-JPEG woven. 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) @@ -30,8 +25,6 @@ function Yuv.crop(src: buffer, stride: number, w: number, h: number, dst: buffer 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 @@ -44,8 +37,6 @@ function Yuv.rows(src: buffer, stride: number, w: number, h: number, dst: buffer 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 @@ -60,8 +51,6 @@ function Yuv.box(src: buffer, stride: number, w: number, h: number, dst: buffer, 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 diff --git a/src/Rosetta/codecs/image/Jpeg/init.luau b/src/Rosetta/codecs/image/Jpeg/init.luau index a5e3086..1ea768c 100644 --- a/src/Rosetta/codecs/image/Jpeg/init.luau +++ b/src/Rosetta/codecs/image/Jpeg/init.luau @@ -1,34 +1,7 @@ --!strict --- codecs/image/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/image/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. +-- codecs/image/Jpeg: the JPEG codec (ITU T.81), bit-exact with libjpeg-turbo's djpeg and byte-identical with cjpeg. +-- From jpeg-luau 1.0 (same author); IJG-derived parts: licenses/libjpeg-turbo-LICENSE.md. Motion-JPEG: frames without +-- DHT use the T.81 annex K tables; AVI1 fields are woven top field first, as ffmpeg does (it ignores the polarity). local Err = require("@rosetta/core/Err") local Types = require("@rosetta/Types") local Decode = require("@rosetta/codecs/image/Jpeg/Decode") @@ -38,28 +11,25 @@ local Yuv = require("@rosetta/codecs/image/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) - raw: boolean?, -- no colour conversion: 3 / 4 components as R, G, B (, A) bytes (default false; BLP1 BGRA JPEGs) - maxPixels: number?, -- refuse larger images (default 2^26) - -- a cooperative yield point, run after every MCU row of a scan, every block row of the IDCT and every 8 output - -- rows: e.g. a function that calls coroutine.yield() when a time budget is spent, so one image is decoded over - -- several frames (decode then runs inside a coroutine). Errors in it are ignored. + scale: number?, + orient: boolean?, + native: boolean?, + yuv: boolean?, + fields: boolean?, + raw: boolean?, + maxPixels: number?, yield: (() -> ())?, } 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 + quality: number?, + subsampling: ("420" | "422" | "444")?, + progressive: boolean?, + optimize: boolean?, + gray: boolean?, + restart: number?, + jfif: boolean?, + density: { unit: number, x: number, y: number }?, + segments: { { marker: number, data: buffer } }?, } export type Info = { @@ -70,11 +40,11 @@ export type Info = { arithmetic: boolean, precision: number, colorSpace: string, - sampling: { { number } }, -- { h, v } per component + sampling: { { number } }, orientation: number, adobe: number?, jfif: boolean, - avi1: number?, -- the AVI1 field polarity, when the segment comes before the frame header + avi1: number?, } local function range(buf: buffer, off: number?, len: number?): (number, number) @@ -83,7 +53,6 @@ local function range(buf: buffer, off: number?, len: number?): (number, number) 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 @@ -103,7 +72,6 @@ local function samplingOf(f: any): { { number } } 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") @@ -131,7 +99,6 @@ function Jpeg.info(buf: buffer, off: number?, len: number?): (Info?, Err.Err?) 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 @@ -164,7 +131,6 @@ local function orient(px: buffer, w: number, h: number, o: number): (buffer, num 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 @@ -231,14 +197,14 @@ local function decodeOne(buf: buffer, o: number, l: number, opts: DecodeOptions? adobe = s.adobe, jfif = s.jfif, avi1 = s.avi1, - yuv = mode, -- "420" | "422" | "444" | "gray": how the yuv420p planes were made (opts.yuv) + yuv = mode, 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 +-- the start of a second JPEG: FF D8 FF local function nextSoi(buf: buffer, p: number, e: number): number local readu8 = buffer.readu8 while p + 3 <= e do @@ -250,7 +216,6 @@ local function nextSoi(buf: buffer, p: number, e: number): number 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 @@ -258,7 +223,7 @@ local function weave(a: Types.Image, b: Types.Image): Types.Image local dst = out.pixels if a.format == "yuv420p" then local cw, chf = (w + 1) // 2, (hf + 1) // 2 - local ch = (h + 1) // 2 -- = hf + local ch = (h + 1) // 2 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) @@ -271,7 +236,6 @@ local function weave(a: Types.Image, b: Types.Image): Types.Image 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") @@ -307,10 +271,8 @@ function Jpeg.decode(buf: buffer, off: number?, len: number?, opts: DecodeOption 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") diff --git a/src/Rosetta/codecs/image/Pixels.luau b/src/Rosetta/codecs/image/Pixels.luau index d8ae224..30a15a8 100644 --- a/src/Rosetta/codecs/image/Pixels.luau +++ b/src/Rosetta/codecs/image/Pixels.luau @@ -1,21 +1,13 @@ --!strict --!native --!optimize 2 --- codecs/image/Pixels: row loops between packed pixel layouts and rgba8 (native), shared by the bitmap formats (BMP, --- the DIBs inside ICO / CUR, ...): 1 / 2 / 4 / 8-bit indexes through a palette, BGR / BGRA, 5-5-5, bit-masked 16 / --- 24 / 32-bit pixels, RLE4 / RLE8, rows bottom-up or top-down; and the encoder direction (rgba8 -> BGR / BGRA / --- 8-bit indexes, bottom-up). Absorbed from bmp-luau b86aed6 (same author, no third-party code); the encoder loops --- are new. They never throw: the caller validates every size first and hands in a source buffer that holds every --- byte an uncompressed loop can read (a truncated file is copied into a zero-padded buffer); the RLE loop checks each --- read against its end offset. Output: rgba8, top-down rows, one u32 per pixel (bytes R, G, B, A). +-- codecs/image/Pixels: row loops between packed pixel layouts and rgba8 for BMP / DIB. +-- Indexed, BGR(A), 5-5-5, bit masks, RLE4 / RLE8. From bmp-luau b86aed6 (same author); the encoder loops are new. local readu8, readu16, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu32, buffer.writeu8 local band, rshift, bor, lshift = bit32.band, bit32.rshift, bit32.bor, bit32.lshift local Pixels = {} --- palette(src, base, n, bgr?) -> a 256-entry u32 palette for indexed(): n RGB triples (BGR when bgr) at src[base..], --- opaque; entries past n (or past the end of src) are opaque black. The game formats' 768-byte palettes (PLAYPAL, --- Quake palette.lmp, Half-Life MDL / WAD3 / BSP 30 textures). function Pixels.palette(src: buffer, base: number, n: number, bgr: boolean?): buffer local pal = buffer.create(1024) local m = if base >= 0 then math.clamp(math.min(n, (buffer.len(src) - base) // 3), 0, 256) else 0 @@ -34,7 +26,6 @@ function Pixels.palette(src: buffer, base: number, n: number, bgr: boolean?): bu return pal end --- 1, 2, 4 and 8 bpp through a 256-entry u32 palette (pal) function Pixels.indexed(src: buffer, base: number, stride: number, bpp: number, dst: buffer, w: number, h: number, topDown: boolean, pal: buffer) local mask = lshift(1, bpp) - 1 @@ -88,7 +79,7 @@ function Pixels.bgr24(src: buffer, base: number, stride: number, dst: buffer, w: end end --- 32 bpp B, G, R, A (BI_RGB, or BITFIELDS with the standard masks). Returns the OR of every alpha byte. +-- 32 bpp B, G, R, A (BI_RGB, or BITFIELDS with the standard masks) function Pixels.bgra32(src: buffer, base: number, stride: number, dst: buffer, w: number, h: number, topDown: boolean): number local aor = 0 @@ -97,7 +88,6 @@ function Pixels.bgra32(src: buffer, base: number, stride: number, dst: buffer, w local d = (if topDown then r else h - 1 - r) * w * 4 for x = 0, w - 1 do local p = readu32(src, so + x * 4) - -- swap R and B: B G R A -> R G B A writeu32(dst, d + x * 4, bor(band(p, 0xFF00FF00), band(rshift(p, 16), 0xFF), lshift(band(p, 0xFF), 16))) aor = bor(aor, p) end @@ -105,9 +95,6 @@ function Pixels.bgra32(src: buffer, base: number, stride: number, dst: buffer, w return rshift(aor, 24) end --- 16 / 24 / 32 bpp through bit masks. sh* = shift of each mask, m* = mask >> shift, t* = scale tables (u8, one entry --- per masked value). A channel without a mask has m = 0 and a 1-entry table (0 for colour, 255 for alpha). --- Returns the OR of every masked alpha value (before scaling). function Pixels.masked(src: buffer, base: number, stride: number, bpp: number, dst: buffer, w: number, h: number, topDown: boolean, shr: number, mr: number, tr: buffer, shg: number, mg: number, tg: buffer, shb: number, mb: number, tb: buffer, sha: number, ma: number, ta: buffer): number @@ -138,16 +125,14 @@ function Pixels.masked(src: buffer, base: number, stride: number, bpp: number, d return aor end --- Sets every alpha byte to 255 (32-bit images whose alpha channel is all zero are opaque). +-- 32-bit images whose alpha channel is all zero are opaque function Pixels.opaque(dst: buffer, n: number) for i = 0, n - 1 do writeu8(dst, i * 4 + 3, 255) end end --- RLE8 / RLE4 from src[pos, stop) into dst (pre-filled with transparent black; pixels the stream skips with a --- delta, an early end of line or an early end of bitmap stay transparent). Malformed or truncated data stops the --- decode and keeps what was drawn. Returns the number of pixels written. +-- RLE8 / RLE4: pixels skipped by a delta or an early end of line / bitmap stay transparent function Pixels.rle(src: buffer, pos: number, stop: number, rle4: boolean, dst: buffer, w: number, h: number, topDown: boolean, pal: buffer): number local x, y = 0, 0 @@ -221,7 +206,6 @@ function Pixels.rle(src: buffer, pos: number, stop: number, rle4: boolean, dst: return written end --- Encoder: rgba8 (top-down) -> 24 bpp BGR rows, bottom-up, each padded to stride (dst is zero-filled) function Pixels.encode24(src: buffer, w: number, h: number, dst: buffer, base: number, stride: number) for y = 0, h - 1 do local s = y * w * 4 @@ -236,20 +220,17 @@ function Pixels.encode24(src: buffer, w: number, h: number, dst: buffer, base: n end end --- rgba8 -> 32 bpp BGRA, bottom-up function Pixels.encode32(src: buffer, w: number, h: number, dst: buffer, base: number) for y = 0, h - 1 do local s = y * w * 4 local d = base + (h - 1 - y) * w * 4 for x = 0, w - 1 do local v = readu32(src, s + x * 4) - -- R G B A (little-endian u32: R | G << 8 | B << 16 | A << 24) -> B G R A writeu32(dst, d + x * 4, bor(band(v, 0xFF00FF00), band(rshift(v, 16), 255), lshift(band(v, 255), 16))) end end end --- rgba8 -> 8 bpp indexes through idx (a table colour -> index, colours as R | G << 8 | B << 16), bottom-up function Pixels.encode8(src: buffer, w: number, h: number, dst: buffer, base: number, stride: number, idx: { [number]: number }) for y = 0, h - 1 do local s = y * w * 4 @@ -260,8 +241,6 @@ function Pixels.encode8(src: buffer, w: number, h: number, dst: buffer, base: nu end end --- colours(src, n, max) -> the distinct RGB colours in first-appearance order (R | G << 8 | B << 16), whether any --- alpha is below 255; stops counting at max + 1 colours function Pixels.colours(src: buffer, n: number, max: number): ({ number }, boolean) local seen: { [number]: boolean } = {} local list: { number } = {} diff --git a/src/Rosetta/codecs/image/Quantize/init.luau b/src/Rosetta/codecs/image/Quantize/init.luau index b9edac5..e132edb 100644 --- a/src/Rosetta/codecs/image/Quantize/init.luau +++ b/src/Rosetta/codecs/image/Quantize/init.luau @@ -1,20 +1,9 @@ --!strict --!native --!optimize 2 --- codecs/image/Quantize: palette quantization of rgba8 pixels. A codec (layer 1): image/gif (and later any palette --- writer) builds on it. New code: Heckbert's median cut and Gervautz-Purgathofer octree, both over a 5-bit-per-channel --- weighted histogram (palette colours are the exact means of the pixels they cover), nearest-colour mapping with --- optional Floyd-Steinberg error diffusion. Deterministic: the same palette and indexes on every runtime (no table --- iteration order is ever relied on). --- --- local pal, exact = Quantize.palette(pixels, w, h, 256, { method = "mediancut" }) -- { {r, g, b, 255} }, boolean --- local idx = Quantize.map(pixels, w, h, pal, { dither = true, transparentIndex = 255 }) -- buffer of w * h u8 --- --- Pixels with alpha < 128 are "transparent": palette() ignores them, map() gives them opts.transparentIndex (0-based) --- when set (otherwise they map like opaque pixels). When the opaque pixels have at most maxColors distinct colours, --- palette() returns exactly those (in first-seen order) and exact = true, and map() is then lossless. The octree --- folds whole nodes, so it may return fewer than maxColors entries; below 8 colours median cut is used instead. --- Never throws: bad arguments give an empty palette / a zero-filled index buffer. +-- codecs/image/Quantize: palette quantization of rgba8 pixels (median cut or octree, Floyd-Steinberg dithering). +-- New in rosetta: Heckbert's median cut and the Gervautz-Purgathofer octree over a 5-bit-per-channel histogram; +-- deterministic on every runtime (no table iteration order is relied on). local readu8, writeu8 = buffer.readu8, buffer.writeu8 local readu32, writeu32, readf64, writef64 = buffer.readu32, buffer.writeu32, buffer.readf64, buffer.writef64 local floor = math.floor @@ -22,18 +11,17 @@ local blen = buffer.len local Quantize = {} -export type Color = { number } -- { r, g, b, a } 0..255 +export type Color = { number } export type PaletteOptions = { - method: ("mediancut" | "octree")?, -- default "mediancut" + method: ("mediancut" | "octree")?, } export type MapOptions = { - dither: boolean?, -- Floyd-Steinberg error diffusion (default false) - transparentIndex: number?, -- 0-based index for pixels with alpha < 128 (default: none) + dither: boolean?, + transparentIndex: number?, } local BINS = 32768 -- 5 bits per channel --- ------------------------------------------------------------------------------------------------ helpers local function count(pixels: buffer, n: number): (buffer, buffer) -- per bin: u32 count; f64 sums of r, g, b local cnt = buffer.create(BINS * 4) @@ -68,7 +56,6 @@ local function mean(cnt: buffer, sums: buffer, bins: { number }, lo: number, hi: return { floor(r / n + 0.5), floor(g / n + 0.5), floor(b / n + 0.5), 255 } end --- ------------------------------------------------------------------------------------------------ median cut local function medianCut(cnt: buffer, sums: buffer, maxColors: number): { Color } local bins: { number } = {} for bin = 0, BINS - 1 do @@ -79,7 +66,6 @@ local function medianCut(cnt: buffer, sums: buffer, maxColors: number): { Color if #bins == 0 then return {} end - -- boxes: { lo, hi } ranges of the bins array local boxes: { { number } } = {} local function channel(bin: number, c: number): number if c == 0 then @@ -90,7 +76,6 @@ local function medianCut(cnt: buffer, sums: buffer, maxColors: number): { Color return bin % 32 end local function stats(box: { number }): (number, number, number) - -- returns the widest channel, its range, the pixel count local mins, maxs = { 31, 31, 31 }, { 0, 0, 0 } local n = 0 for i = box[1], box[2] do @@ -164,11 +149,10 @@ local function medianCut(cnt: buffer, sums: buffer, maxColors: number): { Color return pal end --- ------------------------------------------------------------------------------------------------ octree --- over the histogram bins: 5 levels (one bit of each channel per level). Nodes are array slots. +-- octree over the histogram bins: 5 levels, one bit of each channel per level local function octree(cnt: buffer, sums: buffer, maxColors: number): { Color } local child: { number } = {} -- node * 8 + k -> node (0 = none) - local n: { number } = {} -- pixel count + local n: { number } = {} local sr: { number }, sg: { number }, sb: { number } = {}, {}, {} local leaf: { boolean } = {} local level: { number } = {} @@ -177,7 +161,7 @@ local function octree(cnt: buffer, sums: buffer, maxColors: number): { Color } for k = 1, 8 do child[k] = 0 end - local byLevel: { { number } } = { {}, {}, {}, {}, {} } -- inner nodes per level 0..4, creation order + local byLevel: { { number } } = { {}, {}, {}, {}, {} } table.insert(byLevel[1], 1) local leaves = 0 for bin = 0, BINS - 1 do @@ -215,7 +199,6 @@ local function octree(cnt: buffer, sums: buffer, maxColors: number): { Color } end -- fold the deepest inner nodes (fewest pixels first, ties by creation order) until few enough leaves remain local function fold(node: number): number - -- merges the children (all leaves) into node; returns how many leaves disappeared local merged = 0 for k = 1, 8 do local slot = (node - 1) * 8 + k @@ -264,7 +247,6 @@ local function octree(cnt: buffer, sums: buffer, maxColors: number): { Color } leaves -= fold(e[1]) end end - -- collect leaves depth first in child order local pal: { Color } = {} local function walk(node: number) if leaf[node] then @@ -289,15 +271,12 @@ local function octree(cnt: buffer, sums: buffer, maxColors: number): { Color } return pal end --- ------------------------------------------------------------------------------------------------ palette --- palette(pixels, w, h, maxColors, opts?) -> palette, exact function Quantize.palette(pixels: buffer, w: number, h: number, maxColors: number, opts: PaletteOptions?): ({ Color }, boolean) if type(pixels) ~= "buffer" or type(w) ~= "number" or type(h) ~= "number" or w < 0 or h < 0 or blen(pixels) < w * h * 4 then return {}, false end local maxc = math.clamp(floor(tonumber(maxColors) or 256), 1, 65536) local npx = w * h - -- exact colours, in first-seen order (stops counting past maxColors) local seen: { [number]: boolean } = {} local exact: { Color } = {} local over = false @@ -327,8 +306,6 @@ function Quantize.palette(pixels: buffer, w: number, h: number, maxColors: numbe return medianCut(cnt, sums, maxc), false end --- ------------------------------------------------------------------------------------------------ map --- map(pixels, w, h, palette, opts?) -> buffer of w * h palette indexes (0-based) function Quantize.map(pixels: buffer, w: number, h: number, palette: { Color }, opts: MapOptions?): buffer if type(pixels) ~= "buffer" or type(w) ~= "number" or type(h) ~= "number" or w < 0 or h < 0 or blen(pixels) < w * h * 4 or type(palette) ~= "table" then return buffer.create(0) @@ -337,7 +314,6 @@ function Quantize.map(pixels: buffer, w: number, h: number, palette: { Color }, local out = buffer.create(npx) local dither = opts and opts.dither or false local tidx = opts and opts.transparentIndex - -- the searchable entries (the transparent slot is excluded) local pr: { number }, pg: { number }, pb: { number }, pi: { number } = {}, {}, {}, {} for i, c in palette do if tidx == nil or i - 1 ~= tidx then @@ -362,7 +338,7 @@ function Quantize.map(pixels: buffer, w: number, h: number, palette: { Color }, end pr, pg, pb, pi = r2, g2, b2, i2 end - local startAt = table.create(256, np) -- the first entry with green >= g (1-based), np + 1 past the end + local startAt = table.create(256, np) do local k = 1 for g = 0, 255 do @@ -431,7 +407,6 @@ function Quantize.map(pixels: buffer, w: number, h: number, palette: { Color }, end return out end - -- Floyd-Steinberg: error rows (f64 r, g, b per pixel, one extra pixel each side) local rowLen = (w + 2) * 24 local cur, nxt = buffer.create(rowLen), buffer.create(rowLen) for y = 0, h - 1 do @@ -469,13 +444,12 @@ function Quantize.map(pixels: buffer, w: number, h: number, palette: { Color }, return out end --- quantize(pixels, w, h, maxColors, opts?) -> indexes, palette, exact: palette() then map() (opts of both) function Quantize.quantize(pixels: buffer, w: number, h: number, maxColors: number, opts: any?): (buffer, { Color }, boolean) local pal, exact = Quantize.palette(pixels, w, h, maxColors, opts) local mo = opts if exact and opts and opts.dither then mo = table.clone(opts) - mo.dither = false -- nothing to diffuse + mo.dither = false end return Quantize.map(pixels, w, h, pal, mo), pal, exact end diff --git a/src/Rosetta/codecs/image/Raster.luau b/src/Rosetta/codecs/image/Raster.luau index 8a1732d..69ceb34 100644 --- a/src/Rosetta/codecs/image/Raster.luau +++ b/src/Rosetta/codecs/image/Raster.luau @@ -1,29 +1,9 @@ --!strict --!native --!optimize 2 --- codecs/image/Raster: an antialiased scanline rasterizer for paths of lines, quadratic and cubic Béziers, under an affine --- transform, with the nonzero and even-odd fill rules, plus a polygon stroker. Used by the fonts (glyph outlines) and --- by vector/svg. New code; the coverage accumulation is the signed-area method of font-rs (Raph Levien, Apache-2.0 / --- MIT, an algorithm description, no code copied) and of stb_truetype v2: every edge adds its exact signed area to an --- accumulation row; a running sum along the row gives the winding coverage of each pixel. The rules map the summed --- coverage a as FreeType does: nonzero = min(1, |a|), even-odd = |a| folded modulo 2. --- --- local R = require("@rosetta/codecs/image/Raster") --- local p = R.path():moveTo(0, 0):lineTo(10, 0):quadTo(10, 10, 0, 10):close() -- or a plain command list: --- local cmds = { { op = "moveTo", 0, 0 }, { op = "lineTo", 10, 0 }, { op = "cubicTo", 12, 2, 12, 8, 10, 10 }, --- { op = "close" } } -- (the Font:outline() format) --- local m = R.mask(cmds, { transform = { 2, 0, 0, 2, 5, 5 }, rule = "evenodd", clip = { 0, 0, 64, 64 } }) --- -- m = { x, y, width, height, coverage: buffer (u8, width * height) } in device pixels, or nil when empty --- R.fill(img, cmds, { 255, 0, 0, 255 }, { transform = t }) -- composite onto an rgba8 Image (source over) --- R.fill(img, cmds, function(x, y) return r, g, b, a end) -- a paint function per covered pixel (gradients) --- local outline = R.stroke(cmds, { width = 2, join = "round", cap = "butt" }) -- a path to fill (nonzero) --- --- Transforms are { a, b, c, d, e, f } (SVG matrix order): x' = a x + c y + e, y' = b x + d y + f. Coordinates are --- pixels with y down; a pixel (i, j) covers [i, i+1) x [j, j+1). Curves are flattened in device space to --- opts.tolerance (default 0.1 px). Subpaths are implicitly closed for filling. --- --- Never throws: malformed commands (missing or non-number operands) are skipped, non-finite coordinates drop the --- edge, sizes are bounded by opts.maxPixels (default 2^26), so it is safe for native code and untrusted paths. +-- codecs/image/Raster: an antialiased scanline rasterizer (nonzero / even-odd) for line and Bézier paths, plus a stroker. +-- New code; the signed-area accumulation follows font-rs (Raph Levien, Apache-2.0 / MIT; algorithm only) and stb_truetype +-- v2, and the summed coverage a maps as FreeType does: nonzero = min(1, |a|), even-odd = |a| folded modulo 2. local Raster = {} local floor, ceil, min, max, abs, sqrt = math.floor, math.ceil, math.min, math.max, math.abs, math.sqrt @@ -35,20 +15,19 @@ export type Path = { Cmd } export type Transform = { number } export type Mask = { x: number, y: number, width: number, height: number, coverage: buffer } export type Options = { - transform: Transform?, -- default identity - rule: ("nonzero" | "evenodd")?, -- default "nonzero" - clip: { number }?, -- { x0, y0, x1, y1 } device pixel bounds (integers); default: the path's bounds (fill: the image) - tolerance: number?, -- curve flattening tolerance in device pixels (default 0.1) - maxPixels: number?, -- largest mask (default 2^26) - opacity: number?, -- fill: multiplies the coverage (0..1, default 1) + transform: Transform?, + rule: ("nonzero" | "evenodd")?, + clip: { number }?, + tolerance: number?, + maxPixels: number?, + opacity: number?, } local LIMIT = 1e7 -- coordinates beyond this (device pixels) are treated as broken --- ------------------------------------------------------------------------------------------------ transforms +-- transforms { a, b, c, d, e, f } in SVG matrix order: x' = a x + c y + e, y' = b x + d y + f Raster.IDENTITY = table.freeze({ 1, 0, 0, 1, 0, 0 }) --- multiply(m, n) -> m * n (apply n first, then m) function Raster.multiply(m: Transform, n: Transform): Transform return { m[1] * n[1] + m[3] * n[2], @@ -69,7 +48,6 @@ function Raster.rotate(radians: number): Transform local c, s = math.cos(radians), math.sin(radians) return { c, s, -s, c, 0, 0 } end --- invert(m) -> m^-1 | nil (singular) function Raster.invert(m: Transform): Transform? local det = m[1] * m[4] - m[2] * m[3] if det == 0 or det ~= det then @@ -79,18 +57,14 @@ function Raster.invert(m: Transform): Transform? local a, b, c, d = m[4] * id, -m[2] * id, -m[3] * id, m[1] * id return { a, b, c, d, -(a * m[5] + c * m[6]), -(b * m[5] + d * m[6]) } end --- apply(m, x, y) -> x', y' function Raster.apply(m: Transform, x: number, y: number): (number, number) return m[1] * x + m[3] * y + m[5], m[2] * x + m[4] * y + m[6] end --- ------------------------------------------------------------------------------------------------ path builder local Builder = {} Builder.__index = Builder export type Builder = typeof(setmetatable({} :: { cmds: Path }, Builder)) --- path() -> a Builder; every method returns the builder; builder.cmds is the command list (any API taking a path --- takes a builder too) function Raster.path(): Builder return setmetatable({ cmds = {} :: Path }, Builder) end @@ -114,7 +88,6 @@ function Builder.close(self: Builder): Builder table.insert(self.cmds, { op = "close" } :: Cmd) return self end --- rect(x, y, w, h), ellipse(cx, cy, rx, ry): closed subpaths function Builder.rect(self: Builder, x: number, y: number, w: number, h: number): Builder return self:moveTo(x, y):lineTo(x + w, y):lineTo(x + w, y + h):lineTo(x, y + h):close() end @@ -138,7 +111,6 @@ local function commands(path: any): Path? return path end --- n numeric operands of a command, or nil local function operands(c: any, n: number): boolean if type(c) ~= "table" then return false @@ -152,9 +124,6 @@ local function operands(c: any, n: number): boolean return true end --- ------------------------------------------------------------------------------------------------ flattening --- flatten(path, transform?, tolerance?) -> polylines: { { x1, y1, x2, y2, ... } } in device space, one per subpath --- (closed implicitly; the closing point is not repeated), and the bounds x0, y0, x1, y1 (nil when empty) local function flatten(path: any, transform: Transform?, tolerance: number?, minLen: number): ({ { number } }, number?, number?, number?, number?) local cmds = commands(path) local polys: { { number } } = {} @@ -171,8 +140,8 @@ local function flatten(path: any, transform: Transform?, tolerance: number?, min tol = 0.1 end local cur: { number }? = nil - local px, py = 0, 0 -- current point (device) - local sx, sy = 0, 0 -- subpath start (device) + local px, py = 0, 0 + local sx, sy = 0, 0 local bx0, by0, bx1, by1 = math.huge, math.huge, -math.huge, -math.huge local function point(x: number, y: number) local poly = cur :: { number } @@ -280,9 +249,7 @@ function Raster.flatten(path: any, transform: Transform?, tolerance: number?): ( return flatten(path, transform, tolerance, 6) end --- ------------------------------------------------------------------------------------------------ accumulation --- one edge (x0, y0) -> (x1, y1), already inside [0, W] horizontally, into acc (stride S, H rows): the signed area --- each pixel gains (font-rs's draw_line) +-- the signed area each pixel gains from one edge (font-rs draw_line) local function line(acc: buffer, S: number, H: number, x0: number, y0: number, x1: number, y1: number) if y0 == y1 then return @@ -362,9 +329,7 @@ local function line(acc: buffer, S: number, H: number, x0: number, y0: number, x end end --- an edge in mask coordinates, split where it crosses x = 0 and x = W (in its own order: the direction is the --- winding sign); the parts outside are pushed onto the border (their area lies outside the mask, their cover still --- applies to the row) +-- edges split at x = 0 / x = W: the parts outside go onto the border, whose cover still applies to the row local function clampx(x: number, W: number): number return if x < 0 then 0 elseif x > W then W else x end @@ -376,7 +341,7 @@ local function edge(acc: buffer, S: number, W: number, H: number, x0: number, y0 return end local dx = x1 - x0 - local ta, tb = 2, 2 -- parameters of the crossings with x = 0 and x = W (2 = none) + local ta, tb = 2, 2 if dx ~= 0 then local t0 = (0 - x0) / dx local tw = (W - x0) / dx @@ -405,8 +370,6 @@ local function edge(acc: buffer, S: number, W: number, H: number, x0: number, y0 line(acc, S, H, clampx(px, W), py, clampx(x1, W), y1) end --- ------------------------------------------------------------------------------------------------ masks --- mask(path, opts?) -> Mask | nil (empty, or over the size limit: then the second result is "limit") function Raster.mask(path: any, opts: Options?): (Mask?, string?) local o: Options = opts or {} local polys, bx0, by0, bx1, by1 = Raster.flatten(path, o.transform, o.tolerance) @@ -467,11 +430,6 @@ function Raster.mask(path: any, opts: Options?): (Mask?, string?) return { x = X0, y = Y0, width = W, height = H, coverage = cov }, nil end --- ------------------------------------------------------------------------------------------------ filling --- fill(img, path, paint, opts?) -> true | false, message. img: an rgba8 Image ({ width, height, pixels }); paint: an --- { r, g, b, a } colour (0..255) or a function(x, y) -> r, g, b, a called per covered pixel (pixel centres in --- device space: x + 0.5, y + 0.5). Composites source-over onto the straight-alpha pixels. opts.clip defaults to the --- image; opts.opacity scales the coverage. function Raster.fill(img: any, path: any, paint: any, opts: Options?): (boolean, string?) if type(img) ~= "table" or type(img.pixels) ~= "buffer" or type(img.width) ~= "number" or type(img.height) ~= "number" then return false, "fill: expected an rgba8 image" @@ -536,14 +494,13 @@ function Raster.fill(img: any, path: any, paint: any, opts: Options?): (boolean, return true, nil end --- ------------------------------------------------------------------------------------------------ stroking export type StrokeOptions = { - width: number?, -- default 1 - join: ("miter" | "round" | "bevel")?, -- default "miter" - cap: ("butt" | "round" | "square")?, -- default "butt" - miterLimit: number?, -- default 4 (SVG) - tolerance: number?, -- flattening tolerance in path units (default 0.1); scale it down for magnified strokes - closed: boolean?, -- treat every subpath as closed (default: only subpaths ending with "close") + width: number?, + join: ("miter" | "round" | "bevel")?, + cap: ("butt" | "round" | "square")?, + miterLimit: number?, + tolerance: number?, + closed: boolean?, } -- push a polygon (flat x, y list) as a closed subpath with positive orientation, so overlapping pieces add up @@ -586,8 +543,6 @@ local function arcPoints(cx: number, cy: number, r: number, a0: number, a1: numb end end --- stroke(path, opts?) -> Path: the outline of the stroke as pieces to fill with the nonzero rule (in the path's own --- coordinate space: transform it like the path). Dashes are the caller's job (split the path first). function Raster.stroke(path: any, opts: StrokeOptions?): Path local o: StrokeOptions = opts or {} local hw = (if type(o.width) == "number" and o.width > 0 then o.width else 1) / 2 @@ -640,7 +595,6 @@ function Raster.stroke(path: any, opts: StrokeOptions?): Path end continue end - -- drop repeated points local p: { number } = { pts[1], pts[2] } for i = 3, #pts - 1, 2 do if abs(pts[i] - p[#p - 1]) > 1e-9 or abs(pts[i + 1] - p[#p]) > 1e-9 then @@ -658,7 +612,6 @@ function Raster.stroke(path: any, opts: StrokeOptions?): Path continue end local segs = if closed then n else n - 1 - -- segment bodies local dirs: { number } = {} for s = 0, segs - 1 do local i, j = s, (s + 1) % n @@ -670,7 +623,6 @@ function Raster.stroke(path: any, opts: StrokeOptions?): Path local nx, ny = -uy * hw, ux * hw polygon(out, { x0 + nx, y0 + ny, x1 + nx, y1 + ny, x1 - nx, y1 - ny, x0 - nx, y0 - ny }) end - -- joins local function joinAt(k: number, s0: number, s1: number) local x, y = p[2 * k + 1], p[2 * k + 2] local ax, ay = dirs[2 * s0 + 1], dirs[2 * s0 + 2] @@ -697,7 +649,7 @@ function Raster.stroke(path: any, opts: StrokeOptions?): Path arcPoints(x, y, hw, a0, a0 + da, tol, d) polygon(out, d) else - local cosT = ax * bx + ay * by -- angle between directions + local cosT = ax * bx + ay * by local miter = if join == "miter" then 1 / sqrt(max(1e-12, (1 + cosT) / 2)) else math.huge if join == "miter" and miter <= miterLimit then local mx, my = n0x + n1x, n0y + n1y @@ -719,12 +671,11 @@ function Raster.stroke(path: any, opts: StrokeOptions?): Path for k = 1, n - 2 do joinAt(k, k - 1, k) end - -- caps if cap ~= "butt" then for _, endInfo in { { 0, 0, -1 }, { n - 1, segs - 1, 1 } } do local k, s, sgn = endInfo[1], endInfo[2], endInfo[3] local x, y = p[2 * k + 1], p[2 * k + 2] - local ux, uy = dirs[2 * s + 1] * sgn, dirs[2 * s + 2] * sgn -- pointing outwards + local ux, uy = dirs[2 * s + 1] * sgn, dirs[2 * s + 2] * sgn local nx, ny = -uy * hw, ux * hw if cap == "square" then polygon(out, { x + nx, y + ny, x + nx + ux * hw, y + ny + uy * hw, x - nx + ux * hw, y - ny + uy * hw, x - nx, y - ny }) diff --git a/src/Rosetta/codecs/image/Texel.luau b/src/Rosetta/codecs/image/Texel.luau index 96e313e..a4faa1f 100644 --- a/src/Rosetta/codecs/image/Texel.luau +++ b/src/Rosetta/codecs/image/Texel.luau @@ -1,33 +1,20 @@ --!strict --!native --!optimize 2 --- codecs/image/Texel: uncompressed GPU texel formats -> the standard pixel formats, shared by the texture containers --- (DDS's DXGI and legacy bit-mask formats, KTX's Vulkan / OpenGL formats, ...). New in rosetta. Formats are named --- lower case, channels from the lowest address / bit up (DXGI order): r8, rg8, rgb8, bgr8, rgba8, bgra8, bgrx8, a8, --- l8, la8, r16, rgba16, *s (snorm), *ui / *i (integers), *f (half / float: r16f ... rgba32f), and the packed ones: --- b5g6r5, r5g6b5, b5g5r5a1, a1b5g5r5, b4g4r4a4, a4b4g4r4, a4r4g4b4, rgb10a2, bgr10a2, r11g11b10f, rgb9e5; any other --- bit-mask layout through Texel.masked(bytes, rMask, gMask, bMask, aMask, luminance?). Never throws. --- --- local px, fmt = Texel.decode("bgra8", buf, offset, w, h) -- rgba8 pixels --- local px, fmt = Texel.decode("rgba16f", buf, offset, w, h, true) -- native: rgbaf32 (float) / rgba16 (16-bit) --- local desc = Texel.masked(2, 0xF800, 0x07E0, 0x001F, 0) -- a descriptor, accepted by decode --- --- Channels: one-channel formats (r*, l*) are grey (r = g = b), two-channel ones red + green; missing alpha is opaque. --- rgba8 output: unorm rescaled with rounding, snorm biased (8-bit: s + 128), floats clamped to 0..1, integers clamped --- to 0..255. Native output: rgba8 when every channel fits 8 bits unsigned, rgba16 for 9..16-bit unorm, else rgbaf32 --- (snorm -> -1..1, integers as their values). +-- codecs/image/Texel: uncompressed GPU texel formats -> the standard pixel formats. New in rosetta. +-- Names list channels from the lowest address / bit up (DXGI order); snorm -> rgba8 is biased (8-bit: s + 128). local Half = require("@rosetta/codecs/image/Half") local Texel = {} -export type Channel = { c: string, shift: number, bits: number } -- packed channels (c = r g b a l) +export type Channel = { c: string, shift: number, bits: number } export type Desc = { - bytes: number, -- per texel + bytes: number, kind: "array" | "packed" | "r11g11b10f" | "rgb9e5" | "pair" | "ayuv", - size: number?, -- array: bytes per component (1, 2, 4) - type: string?, -- array: unorm / snorm / uint / sint / float - order: string?, -- array: the components in memory (r g b a l x); pair: the 4 bytes of 2 pixels (yuyv, uyvy, rgbg, grgb) - channels: { Channel }?, -- packed: unorm fields of a little-endian 16 / 32-bit word + size: number?, + type: string?, + order: string?, + channels: { Channel }?, } local readu8, readu16, readu32, readi8, readi16, readi32, readf32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi8, buffer.readi16, buffer.readi32, buffer.readf32 @@ -35,7 +22,6 @@ local writeu8, writeu16, writeu32, writef32 = buffer.writeu8, buffer.writeu16, b local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift local HALF = Half.TABLE --- ------------------------------------------------------------------------------------------------ formats local FORMATS: { [string]: Desc } = {} local function array(name: string, size: number, typ: string, order: string) FORMATS[name] = { bytes = size * #order, kind = "array", size = size, type = typ, order = order } @@ -95,8 +81,6 @@ FORMATS.grgb = { bytes = 2, kind = "pair", order = "grgb" } FORMATS.ayuv = { bytes = 4, kind = "ayuv" } Texel.FORMATS = FORMATS --- masked(bytes, r, g, b, a, luminance?) -> a packed descriptor from bit masks (DDS legacy pixel formats); luminance: --- the r mask is a luminance channel function Texel.masked(bytes: number, r: number, g: number, b: number, a: number, luminance: boolean?): Desc? if bytes < 1 or bytes > 4 then return nil @@ -122,7 +106,6 @@ function Texel.masked(bytes: number, r: number, g: number, b: number, a: number, return { bytes = bytes, kind = "packed", channels = ch } end --- size(fmt, w, h) -> bytes (rows tightly packed) | nil function Texel.size(fmt: string | Desc, w: number, h: number): number? local d = if type(fmt) == "string" then FORMATS[fmt] else fmt if not d then @@ -131,8 +114,6 @@ function Texel.size(fmt: string | Desc, w: number, h: number): number? return if d.kind == "pair" then ((w + 1) // 2) * 4 * h else d.bytes * w * h end --- ------------------------------------------------------------------------------------------------ helpers --- the native output of a descriptor: rgba8 / rgba16 / rgbaf32 local function nativeOf(d: Desc): string if d.kind == "array" then local t, s = d.type, d.size :: number @@ -170,7 +151,6 @@ local function uf10(v: number): number return (1 + m / 32) * 2 ^ (e - 15) end --- one component at q of an array format -> a float (native meaning) and its rgba8 byte local function component(src: buffer, q: number, size: number, typ: string): (number, number) if typ == "unorm" then if size == 1 then @@ -204,7 +184,6 @@ local function component(src: buffer, q: number, size: number, typ: string): (nu return v, math.clamp(v, 0, 255) end --- BT.601 limited-range Y'CbCr -> an rgba8 u32 local function ycc(y: number, u: number, v: number, a: number): number local c, d, e = 1.164 * (y - 16), u - 128, v - 128 local r = math.clamp(math.floor(c + 1.596 * e + 0.5), 0, 255) @@ -213,7 +192,6 @@ local function ycc(y: number, u: number, v: number, a: number): number return r + g * 256 + b * 65536 + a * 16777216 end --- the 4:2:2 pair formats and AYUV -> rgba8 (out is always rgba8: 8-bit sources) local function yuv(d: Desc, src: buffer, offset: number, w: number, h: number, pitch: number, dst: buffer): buffer local n = 0 local order = d.order or "" @@ -243,9 +221,6 @@ local function yuv(d: Desc, src: buffer, offset: number, w: number, h: number, p return dst end --- ------------------------------------------------------------------------------------------------ decode --- decode(fmt, src, offset, w, h, native?, rowPitch?) -> pixels, pixel format ("rgba8" / "rgba16" / "rgbaf32") | nil, --- message. rowPitch: bytes per source row (default tight). function Texel.decode(fmt: string | Desc, src: buffer, offset: number, w: number, h: number, native: boolean?, rowPitch: number?): (buffer?, string) local d = if type(fmt) == "string" then FORMATS[fmt] else fmt if not d then @@ -266,7 +241,6 @@ function Texel.decode(fmt: string | Desc, src: buffer, offset: number, w: number local n = 0 if d.kind == "array" then local order, size, typ = d.order :: string, d.size :: number, d.type :: string - -- fast paths if size == 1 and typ == "unorm" and out == "rgba8" and (order == "rgba" or order == "bgra" or order == "bgrx" or order == "rgbx") then local swap = order == "bgra" or order == "bgrx" local opaque = order == "bgrx" or order == "rgbx" @@ -287,7 +261,7 @@ function Texel.decode(fmt: string | Desc, src: buffer, offset: number, w: number return dst, out end local nc = #order - local map = table.create(nc, 0) -- component -> output channel 0..3, 4 = grey, -1 = skip + local map = table.create(nc, 0) for i = 1, nc do local c = string.sub(order, i, i) map[i] = if c == "r" then (if nc == 1 then 4 else 0) elseif c == "g" then 1 elseif c == "b" then 2 elseif c == "a" then 3 elseif c == "l" then 4 else -1 @@ -367,7 +341,6 @@ function Texel.decode(fmt: string | Desc, src: buffer, offset: number, w: number if d.kind == "pair" or d.kind == "ayuv" then return yuv(d, src, offset, w, h, pitch, dst), out end - -- shared-exponent / packed floats local nine = d.kind == "rgb9e5" for y = 0, h - 1 do local s = offset + y * pitch diff --git a/src/Rosetta/codecs/image/Texture.luau b/src/Rosetta/codecs/image/Texture.luau index 6b2b24b..77a1a92 100644 --- a/src/Rosetta/codecs/image/Texture.luau +++ b/src/Rosetta/codecs/image/Texture.luau @@ -1,13 +1,5 @@ --!strict --- codecs/image/Texture: one entry point over the texture pixel codecs for the texture containers (DDS, KTX, VTF, ...): --- a format name is a BCn kind (codecs/image/Bcn), an ETC / EAC kind (codecs/image/Etc) or a texel format --- (codecs/image/Texel); decode / size dispatch on it, surfaces() assembles mip levels / faces / layers into one --- Types.Image, halve() makes the next mip level of an image for writers. New in rosetta. Never throws. --- --- local px, pf = Texture.decode("bc7", buf, offset, w, h, native) -- pixels + their pixel format --- Texture.size("etc2_rgb", w, h) -- bytes of one surface --- local img = Texture.image(px, pf, w, h) -- a Types.Image around them --- local smaller = Texture.halve(img) -- box-filtered next mip level +-- codecs/image/Texture: one entry point over the texture pixel codecs (Bcn, Etc, Texel). New in rosetta. local Types = require("@rosetta/Types") local Bcn = require("@rosetta/codecs/image/Bcn") local Etc = require("@rosetta/codecs/image/Etc") @@ -16,7 +8,6 @@ local Half = require("@rosetta/codecs/image/Half") local Texture = {} --- known(name) -> "bcn" | "etc" | "texel" | nil function Texture.known(name: string): string? if Bcn.BLOCK[name] then return "bcn" @@ -28,12 +19,10 @@ function Texture.known(name: string): string? return nil end --- size(name, w, h) -> bytes of a w x h surface | nil function Texture.size(name: string, w: number, h: number): number? return Bcn.size(name, w, h) or Etc.size(name, w, h) or Texel.size(name, w, h) end --- block(name) -> block width, height, bytes (1, 1, texel bytes for texel formats) | nil function Texture.block(name: string): (number?, number?, number?) local b = Bcn.BLOCK[name] or Etc.BLOCK[name] if b then @@ -46,8 +35,6 @@ function Texture.block(name: string): (number?, number?, number?) return nil, nil, nil end --- decode(name, src, offset, w, h, native?) -> pixels, pixel format | nil, message. Without native the result is --- rgba8 (BC6H and float texels clamped to 0..1); native keeps rgbaf32 (BC6H, floats) / rgba16 (EAC, 16-bit unorm). function Texture.decode(name: string, src: buffer, offset: number, w: number, h: number, native: boolean?): (buffer?, string) if Bcn.BLOCK[name] then local px, err = Bcn.decode(name, src, offset, w, h) @@ -79,7 +66,6 @@ function Texture.decode(name: string, src: buffer, offset: number, w: number, h: return Texel.decode(name, src, offset, w, h, native) end --- image(pixels, pixel format, w, h) -> Types.Image function Texture.image(px: buffer, pf: string, w: number, h: number): Types.Image local img = Types.Image.new(0, 0, pf :: any) img.width, img.height, img.pixels = w, h, px @@ -88,8 +74,6 @@ end export type Surface = { level: number, layer: number, face: number, slice: number, image: Types.Image } --- assemble(surfaces, layout) -> the Image of the first surface with img.frames = every level-0 surface (faces / --- layers / depth slices in order, when more than one) and img.meta.mipmaps = the smaller levels of the first surface function Texture.assemble(list: { Surface }, layout: string): Types.Image? local first: Types.Image? = nil local frames: { Types.Frame } = {} @@ -117,8 +101,6 @@ function Texture.assemble(list: { Surface }, layout: string): Types.Image? return img end --- halve(img) -> the next mip level (each dimension halved, at least 1; 2 x 2 box filter), same pixel format --- (rgba8 / rgba16 / rgbaf32) function Texture.halve(img: Types.Image): Types.Image local w, h = img.width, img.height local nw, nh = math.max(1, w // 2), math.max(1, h // 2) @@ -149,7 +131,6 @@ function Texture.halve(img: Types.Image): Types.Image return out end --- toHalf(rgbaf32 pixels, n) -> rgba16f texels (for writers) function Texture.toHalf(px: buffer, n: number): buffer local out = buffer.create(n * 8) local from = Half.fromFloat diff --git a/src/Rosetta/codecs/image/Vp8/Decode.luau b/src/Rosetta/codecs/image/Vp8/Decode.luau index b2752d3..50917ae 100644 --- a/src/Rosetta/codecs/image/Vp8/Decode.luau +++ b/src/Rosetta/codecs/image/Vp8/Decode.luau @@ -1,21 +1,9 @@ --!strict --!native --!optimize 2 --- codecs/image/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, --- 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). 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/image/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: 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). +-- codecs/image/Vp8/Decode: the VP8 frame decoder (RFC 6386), key frames a port of libwebp 1.6 src/dec + src/dsp/dec.c +-- (BSD-3-Clause, licenses/libwebp-LICENSE.txt), inter frames after libvpx 1.17 vp8/decoder + vp8/common (BSD-3-Clause, +-- licenses/libvpx-LICENSE.txt). Where libvpx and ffmpeg disagree on streams no encoder writes, this follows ffmpeg. local Tables = require("@rosetta/codecs/image/Vp8/Tables") local Predict = require("@rosetta/codecs/image/Vp8/Predict") @@ -34,7 +22,6 @@ local CAT = { Tables.CAT3, Tables.CAT4, Tables.CAT5, Tables.CAT6 } local Decode = {} --- ------------------------------------------------------------------------------------------------ boolean decoder -- libwebp's VP8BitReader: `range` is the range minus one (127..254), `value` holds the unread bits, `bits` is the -- position of the 8-bit window in `value` (< 0: load more). Bytes past the end read as zero once and set eof. type Br = { buf: buffer, pos: number, limit: number, value: number, bits: number, range: number, eof: boolean } @@ -76,8 +63,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 +-- branchless getBit: bit = value >> bits > split; 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) @@ -107,10 +94,8 @@ local function getSignedValue(br: Br, n: number): number return if getBit(br, 0x80) == 1 then -v else v 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 = { @@ -129,12 +114,12 @@ export type State = { 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 + segMap: { number }, width: number, height: number, mbw: number, mbh: number, - hasKey: boolean, -- a key frame was decoded (inter frames need one) + hasKey: boolean, last: Ref?, golden: Ref?, alt: Ref?, @@ -146,8 +131,8 @@ export type State = { 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 + miN: number, + pred: buffer?, } function Decode.new(): State @@ -186,13 +171,11 @@ function Decode.new(): State } 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 return nil, "truncated: frame tag" @@ -226,7 +209,6 @@ function Decode.header(buf: buffer, off: number, len: number): (any, string?) return h, nil end --- ------------------------------------------------------------------------------------------------ residuals local function getLargeValue(br: Br, P: { number }, p: number): number local v if getBit(br, P[p + 4]) == 0 then @@ -257,9 +239,7 @@ local function getLargeValue(br: Br, P: { number }, p: number): number return v end --- getCoeffs(br, P, t, ctx, dqDc, dqAc, n, out, o) -> the position of the last non-zero coefficient + 1. Writes the --- dequantized coefficients (int16, as libwebp stores them) into out at byte offset o, in raster order. The boolean --- decoder is inlined (the hot loop of lossy decoding); getLargeValue goes through br. +-- coefficients are dequantized to int16 as libwebp stores them, in raster order local function getCoeffs(br: Br, P: { number }, t: number, ctx: number, dqDc: number, dqAc: number, n: number, out: buffer, o: number): number local tb = t * 8 local p = ((tb + BANDS[n + 1]) * 3 + ctx) * 11 @@ -432,7 +412,6 @@ local function transformWHT(inp: buffer, out: buffer, o: number) end end --- ------------------------------------------------------------------------------------------------ reconstruction -- the work buffer of libwebp (yuv_b): BPS = 32, Y at row 1 column 8, U and V below it side by side local BPS = 32 local Y_OFF = BPS + 8 @@ -772,13 +751,11 @@ local function checkMode(mbx: number, mby: number, mode: number): number return mode end --- ------------------------------------------------------------------------------------------------ loop filter -- 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). +-- SimpleVFilter16 / SimpleHFilter16; a position whose filter value a is 0 changes nothing (skipped before the mask) local function simpleFilter(b: buffer, p: number, step: number, along: number, thresh: number) local t2 = 2 * thresh + 1 for _ = 1, 16 do @@ -807,7 +784,7 @@ local function simpleFilter(b: buffer, p: number, step: number, along: number, t end end --- filterEdge(b, p, hs, vs, size, thresh, it, hevT): the macroblock edge filter (FilterLoop26) +-- 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 @@ -866,8 +843,7 @@ local function filterEdge(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 +-- 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 @@ -914,7 +890,6 @@ local function filterInner(b: buffer, p: number, hs: number, vs: number, size: n 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 @@ -976,17 +951,16 @@ 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 + modes: { number }, uv: { number }, ref: { number }, -- 0 intra, 1 last, 2 golden, 3 altref - mode: { number }, -- 0..9 (see MODE_LF) + mode: { number }, 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 +-- libvpx read_mb_modes_mv with vp8_find_near_mvs 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 @@ -1187,11 +1161,10 @@ local function readInterMb(st: State, br: Br, probIntra: number, probLast: numbe miRef[mi], miMode[mi], miMvR[mi], miMvC[mi] = ref, mode, mvr, mvc end --- ------------------------------------------------------------------------------------------------ frame export type Frame = { width: number, height: number, - ref: Ref, -- the decoded planes (the decoder keeps them as a reference: copy them out, see cropTo) + ref: Ref, header: any, } @@ -1213,7 +1186,6 @@ local function newRef(mbw: number, mbh: number): Ref } 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 @@ -1225,7 +1197,6 @@ local function freeRef(st: State): Ref 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 @@ -1240,7 +1211,6 @@ function Decode.cropTo(f: Frame, dy: buffer, oy: number, du: buffer, ou: number, 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 @@ -1502,7 +1472,6 @@ function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, ma end end - -- 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 @@ -1536,7 +1505,6 @@ function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, ma end local coeffs = bcreate(mbw * 768) local dcb = bcreate(32) - -- per macroblock column / row state local intraT = table.create(mbw * 4, 0) local intraL = table.create(4, 0) local topNz = table.create(mbw, 0) @@ -1554,7 +1522,6 @@ function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, ma local mbSkip = table.create(mbw, 0) local mbNzY = table.create(mbw, 0) local mbNzUv = table.create(mbw, 0) - -- filter info for the whole frame: limit, ilevel, inner, hev per macroblock local fLimit = table.create(mbw * mbh, 0) local fIlevel = table.create(mbw * mbh, 0) local fInner = table.create(mbw * mbh, 0) diff --git a/src/Rosetta/codecs/image/Vp8/Predict.luau b/src/Rosetta/codecs/image/Vp8/Predict.luau index f3c4d13..ad0b439 100644 --- a/src/Rosetta/codecs/image/Vp8/Predict.luau +++ b/src/Rosetta/codecs/image/Vp8/Predict.luau @@ -1,13 +1,9 @@ --!strict --!native --!optimize 2 --- codecs/image/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. +-- codecs/image/Vp8/Predict: VP8 inter prediction (RFC 6386 section 18), after libvpx 1.17 vp8/common/reconinter.c and +-- filter.c (BSD-3-Clause, licenses/libvpx-LICENSE.txt). Out-of-frame motion reads the edge pixels extended forever, +-- which equals libvpx's 32 pixel border plus its motion vector clamping. local Tables = require("@rosetta/codecs/image/Vp8/Tables") local readu8, writeu8, bcopy, bcreate, bfill = buffer.readu8, buffer.writeu8, buffer.copy, buffer.create, buffer.fill @@ -20,14 +16,12 @@ local Predict = {} local BORDER = 32 Predict.BORDER = BORDER --- the work buffer stride (codecs/image/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 +local emu = bcreate(32 * 32) +local tmp = bcreate(32 * 32) --- 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). +-- six-tap along rows: dst[i] = clamp((sum of src[i - 2 .. i + 3] * taps + 64) >> 7) 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] @@ -42,7 +36,6 @@ local function sixH(src: buffer, so: number, ss: number, dst: buffer, d: number, 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] @@ -83,9 +76,6 @@ local function bilV(src: buffer, so: number, ss: number, dst: buffer, d: number, 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 @@ -163,17 +153,14 @@ 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) + ys: number, + uvs: number, + yb: number, 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 @@ -236,9 +223,6 @@ function Predict.mb(ref: Planes, mbx: number, mby: number, mvr: number, mvc: num 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] @@ -250,7 +234,6 @@ function Predict.row(refs: { Planes }, mby: number, mbw: number, ref: { number } 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 diff --git a/src/Rosetta/codecs/image/Vp8/Tables.luau b/src/Rosetta/codecs/image/Vp8/Tables.luau index 7bbdb4a..db86a0a 100644 --- a/src/Rosetta/codecs/image/Vp8/Tables.luau +++ b/src/Rosetta/codecs/image/Vp8/Tables.luau @@ -1,9 +1,7 @@ --!strict --- codecs/image/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); 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. +-- codecs/image/Vp8/Tables: the VP8 tables of RFC 6386 (sections 11.5, 13.4, 13.5, 14.1, 16-18), from libwebp 1.6 src/dec +-- (BSD-3-Clause, licenses/libwebp-LICENSE.txt) and libvpx 1.17 vp8/common (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 diff --git a/src/Rosetta/codecs/image/Vp8/Yuv.luau b/src/Rosetta/codecs/image/Vp8/Yuv.luau index 720fe65..089a87c 100644 --- a/src/Rosetta/codecs/image/Vp8/Yuv.luau +++ b/src/Rosetta/codecs/image/Vp8/Yuv.luau @@ -1,9 +1,8 @@ --!strict --!native --!optimize 2 --- codecs/image/Vp8/Yuv: 4:2:0 Y'CbCr (BT.601, limited range) to rgba8 the way libwebp's decoder does it, bit-exact: the --- 14-bit fixed-point VP8YuvToRgb of src/dsp/yuv.h, with either the "fancy" upsampler (src/dsp/upsampling.c: a 9-3-3-1 --- bilinear filter on the chroma, libwebp's default) or point sampling (dwebp -nofancy). A port of libwebp 1.6 +-- codecs/image/Vp8/Yuv: 4:2:0 BT.601 limited-range Y'CbCr -> rgba8, bit-exact with libwebp (src/dsp/yuv.h VP8YuvToRgb; +-- src/dsp/upsampling.c "fancy" 9-3-3-1 upsampler, or point sampling as dwebp -nofancy). A port of libwebp 1.6 -- (BSD-3-Clause, licenses/libwebp-LICENSE.txt). local rshift = bit32.rshift local readu8, writeu8, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu32 @@ -19,12 +18,10 @@ local function clip(v: number): number return if v < 0 then 0 else 255 end --- (v * coeff) >> 8 for non-negative v local function mulHi(v: number, c: number): number return rshift(v * c, 8) end --- rgba(y, u, v) -> the pixel as a little-endian u32 (bytes R G B 255) local function rgba(y: number, u: number, v: number): number local yy = mulHi(y, 19077) local r = clip(yy + mulHi(v, 26149) - 14234) @@ -34,8 +31,7 @@ local function rgba(y: number, u: number, v: number): number end Yuv.rgba = rgba --- upsamplePair: libwebp UPSAMPLE_FUNC for one or two output rows. ty / by: offsets of the top / bottom luma rows --- (by < 0: no bottom row), tu / cu: offsets of the top / current chroma rows; dt / db: output row offsets. +-- libwebp UPSAMPLE_FUNC for one or two output rows (by < 0: no bottom row) local function upsamplePair(Y: buffer, U: buffer, V: buffer, ty: number, by: number, tu: number, cu: number, out: buffer, dt: number, db: number, len: number) local last = rshift(len - 1, 1) local tlu, tlv = readu8(U, tu), readu8(V, tu) @@ -80,7 +76,6 @@ local function upsamplePair(Y: buffer, U: buffer, V: buffer, ty: number, by: num end end --- toRgba(y, u, v, w, h, fancy, out?) -> rgba8 (alpha 255). Planes are tightly packed (chroma ceil(w / 2) wide). function Yuv.toRgba(Y: buffer, U: buffer, V: buffer, w: number, h: number, fancy: boolean, out: buffer?): buffer local o = out or bcreate(w * h * 4) local cw = (w + 1) // 2 @@ -113,7 +108,6 @@ function Yuv.toRgba(Y: buffer, U: buffer, V: buffer, w: number, h: number, fancy return o end --- setAlpha(rgba, a8, n): copy an alpha plane into the A bytes function Yuv.setAlpha(o: buffer, a: buffer, n: number) for i = 0, n - 1 do writeu8(o, i * 4 + 3, readu8(a, i)) diff --git a/src/Rosetta/codecs/image/Vp8/init.luau b/src/Rosetta/codecs/image/Vp8/init.luau index a14fab3..7db4f2d 100644 --- a/src/Rosetta/codecs/image/Vp8/init.luau +++ b/src/Rosetta/codecs/image/Vp8/init.luau @@ -1,25 +1,7 @@ --!strict --- codecs/image/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 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`. 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("@rosetta/codecs/image/Vp8") --- 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() -- 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). +-- codecs/image/Vp8: the VP8 video codec (RFC 6386), decode only. +-- Key frames ported from libwebp 1.6 (BSD-3-Clause, licenses/libwebp-LICENSE.txt), inter frames after libvpx 1.17 +-- (BSD-3-Clause, licenses/libvpx-LICENSE.txt); bit-exact with both. Scale bits are ignored, as libwebp and ffmpeg do. local Err = require("@rosetta/core/Err") local Types = require("@rosetta/Types") local Decode = require("@rosetta/codecs/image/Vp8/Decode") @@ -30,7 +12,7 @@ local Vp8 = {} local DEFAULT_MAX_PIXELS = 2 ^ 28 export type Options = { - maxPixels: number?, -- default 2^28 + maxPixels: number?, } local function fail(msg: string?, offset: number?): Err.Err @@ -51,7 +33,6 @@ local function range(buf: buffer, off: number?, len: number?): (number, number) return o, math.clamp(len or (n - o), 0, n - o) end --- info(buf, off?, len?) -> { keyFrame, profile, show, partitionLength, width, height, xscale, yscale } | nil, Err function Vp8.info(buf: buffer, off: number?, len: number?): (any, Err.Err?) if type(buf) ~= "buffer" then return nil, Err.new(Err.ARG, "info: expected a buffer") @@ -69,14 +50,10 @@ DecoderMeta.__index = DecoderMeta export type Decoder = typeof(setmetatable({} :: { state: Decode.State }, DecoderMeta)) --- newDecoder() -> Decoder: decodes successive frames of one stream function Vp8.newDecoder(): Decoder return setmetatable({ state = Decode.new() }, DecoderMeta) end --- 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") @@ -95,17 +72,14 @@ function DecoderMeta.decodeFrame(self: Decoder, buf: buffer, off: number?, len: 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) end --- decodePlanes(buf, off?, len?, opts?) -> y, u, v, width, height | nil, Err: one key frame as separate planes function Vp8.decodePlanes(buf: buffer, off: number?, len: number?, opts: Options?): (buffer?, any, buffer?, number?, number?) if type(buf) ~= "buffer" then return nil, Err.new(Err.ARG, "decodePlanes: expected a buffer") @@ -121,15 +95,12 @@ function Vp8.decodePlanes(buf: buffer, off: number?, len: number?, opts: Options return y, u, v, f.width, f.height end --- planes(img) -> y, u, v offsets in img.pixels and the chroma width / height function Vp8.planes(img: Types.Image): (number, number, number, number, number) local cw, ch = (img.width + 1) // 2, (img.height + 1) // 2 local ny = img.width * img.height return 0, ny, ny + cw * ch, cw, ch end --- toRgba(yuvImage, fancy?) -> rgba8 Image. fancy (default true): libwebp's bilinear chroma upsampling; false: point --- sampling (dwebp -nofancy) function Vp8.toRgba(img: Types.Image, fancy: boolean?): (Types.Image?, Err.Err?) if type(img) ~= "table" or img.format ~= "yuv420p" then return nil, Err.new(Err.ARG, "toRgba: needs a yuv420p Image") @@ -148,7 +119,6 @@ function Vp8.toRgba(img: Types.Image, fancy: boolean?): (Types.Image?, Err.Err?) return out, nil end --- yuvToRgba(y, u, v, w, h, fancy?) -> rgba8 pixels from separate planes (alpha 255) function Vp8.yuvToRgba(y: buffer, u: buffer, v: buffer, w: number, h: number, fancy: boolean?): buffer return Yuv.toRgba(y, u, v, w, h, fancy ~= false) end diff --git a/src/Rosetta/codecs/image/Vp8L/Decode.luau b/src/Rosetta/codecs/image/Vp8L/Decode.luau index a8b202c..93a5216 100644 --- a/src/Rosetta/codecs/image/Vp8L/Decode.luau +++ b/src/Rosetta/codecs/image/Vp8L/Decode.luau @@ -1,13 +1,9 @@ --!strict --!native --!optimize 2 --- codecs/image/Vp8L/Decode: the WebP lossless (VP8L) bitstream decoder: prefix codes (two-level tables), meta prefix codes, --- LZ77 backward references with the 2-D distance map, the colour cache, and the four inverse transforms (predictor, --- cross colour, subtract green, colour indexing with pixel bundling). A port of libwebp 1.6 src/dec/vp8l_dec.c, +-- codecs/image/Vp8L/Decode: the WebP lossless (VP8L) bitstream decoder, a port of libwebp 1.6 src/dec/vp8l_dec.c, -- src/utils/huffman_utils.c and src/dsp/lossless.c (BSD-3-Clause, licenses/libwebp-LICENSE.txt); bit-exact with it. --- --- Pixels are ARGB u32 values (0xAARRGGBB) in a buffer, 4 bytes each, rows top to bottom. Never throws: every --- function returns nil, "message" (prefixed "truncated: " when the data ends early) on bad data. +-- Pixels are ARGB u32 values (0xAARRGGBB). local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift local readu8, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu32, buffer.writeu32, buffer.writeu8 local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len @@ -35,9 +31,7 @@ local CODE_TO_PLANE = { -- distance map (x offset 8 - (v & 15), y offset v >> 4) as a plain distance for a row width: done per image Decode.CODE_TO_PLANE = CODE_TO_PLANE --- ------------------------------------------------------------------------------------------------ bit reader --- LSB-first; bytes past the end read as zero and are counted in `over`: the stream is overrun when fewer bits are --- left in the buffer than phantom bits were added (bitcnt < over * 8). +-- LSB-first; bytes past the end read as zero and count in `over`: the stream is overrun when bitcnt < over * 8 export type State = { buf: buffer, pos: number, @@ -68,7 +62,6 @@ local function fill(d: State) d.bitbuf, d.bitcnt = bitbuf, bitcnt end --- readBits(d, n) n <= 24 local function readBits(d: State, n: number): number if d.bitcnt < n then fill(d) @@ -83,7 +76,6 @@ local function eos(d: State): boolean return d.bitcnt < d.over * 8 end --- ------------------------------------------------------------------------------------------------ prefix codes local count = table.create(MAX_LEN + 1, 0) local offset = table.create(MAX_LEN + 2, 0) @@ -112,8 +104,7 @@ local function nextKey(key: number, len: number): number return if step ~= 0 then band(key, step - 1) + step else key end --- build(d, lens (0-based Lua array), n) -> table offset in d.tab, or -1 for an invalid code set (libwebp --- BuildHuffmanTable: complete codes only, except a single used symbol, which reads 0 bits) +-- libwebp BuildHuffmanTable: complete codes only, except a single used symbol, which reads 0 bits; -1 when invalid local sorted = table.create(2400, 0) local function build(d: State, lens: { number }, n: number): number for l = 0, MAX_LEN do @@ -222,7 +213,6 @@ local function build(d: State, lens: { number }, n: number): number return root end --- readSymbol(d, at) -> symbol (the reader is refilled to >= 15 bits first) local function readSymbol(d: State, at: number): number if d.bitcnt < MAX_LEN then fill(d) @@ -246,7 +236,6 @@ end local codeLengths = table.create(2400, 0) local clLens = table.create(19, 0) --- readCode(d, alphabetSize) -> table offset, or -1 local function readCode(d: State, size: number): number for i = 1, size do codeLengths[i] = 0 @@ -325,7 +314,6 @@ local function readCode(d: State, size: number): number return build(d, codeLengths, size) end --- ------------------------------------------------------------------------------------------------ pixel data local function subSample(size: number, bits: number): number return rshift(size + lshift(1, bits) - 1, bits) end @@ -340,7 +328,6 @@ local function cacheKey(argb: number, shift: number): number end Decode.cacheKey = cacheKey --- decodeData: the entropy-coded pixels of one level into `data` (w * h u32) local function decodeData(d: State, data: buffer, w: number, h: number, cacheBits: number, groups: { number }, himg: buffer?, hbits: number, hxs: number): (boolean, string?) local total = w * h local cache: buffer? = if cacheBits > 0 then bcreate(lshift(1, cacheBits) * 4) else nil @@ -457,7 +444,6 @@ local function decodeData(d: State, data: buffer, w: number, h: number, cacheBit return true, nil end --- ------------------------------------------------------------------------------------------------ transforms local function addPixels(a: number, b: number): number return band(band(a, 0xff00ff00) + band(b, 0xff00ff00), 0xff00ff00) + band(band(a, 0x00ff00ff) + band(b, 0x00ff00ff), 0x00ff00ff) end @@ -510,7 +496,7 @@ local function clampedHalf(c0: number, c1: number, c2: number): number return a * 16777216 + r * 65536 + g * 256 + b end --- predict(mode, L, T, TR, TL) -> the predicted pixel (libwebp VP8LPredictors; 14 and 15 are black) +-- libwebp VP8LPredictors; modes 14 and 15 are black local function predict(mode: number, L: number, T: number, TR: number, TL: number): number if mode == 0 then return ARGB_BLACK @@ -618,7 +604,6 @@ local function inverseSubtractGreen(data: buffer, n: number) end end --- inverseColorIndexing(src (sw x h), w, h, bits, map (2^(8 >> bits) u32)) -> w x h local function inverseColorIndexing(src: buffer, sw: number, w: number, h: number, bits: number, map: buffer): buffer local out = bcreate(w * h * 4) if bits == 0 then @@ -646,12 +631,10 @@ local function inverseColorIndexing(src: buffer, sw: number, w: number, h: numbe return out end --- ------------------------------------------------------------------------------------------------ image stream type Transform = { kind: number, xsize: number, bits: number, data: buffer? } local decodeStream: (d: State, xs: number, ys: number, level0: boolean) -> (buffer?, string?) --- readCodes(d, xs, ys, cacheBits, level0) -> groups (5 table offsets each), huffman image, bits, image width local function readCodes(d: State, xs: number, ys: number, cacheBits: number, level0: boolean): ({ number }?, buffer?, number, number, string?) local himg: buffer? = nil local hbits, hxs = 0, 0 @@ -808,7 +791,6 @@ local function newState(buf: buffer, off: number, len: number, maxPixels: number } end --- header(buf, off, len) -> width, height, alphaHint | nil, message function Decode.header(buf: buffer, off: number, len: number): (number?, number, boolean, string?) if len < 5 then return nil, 0, false, "truncated: header" @@ -826,7 +808,6 @@ function Decode.header(buf: buffer, off: number, len: number): (number?, number, return w, h, alpha, nil end --- argb(buf, off, len, maxPixels) -> ARGB pixels, width, height, alphaHint | nil, message function Decode.argb(buf: buffer, off: number, len: number, maxPixels: number): (buffer?, number, number, boolean, string?) local w, h, alpha, err = Decode.header(buf, off, len) if not w then @@ -843,13 +824,11 @@ function Decode.argb(buf: buffer, off: number, len: number, maxPixels: number): return data, w, h, alpha, nil end --- stream(buf, off, len, w, h) -> ARGB pixels | nil, message: a headerless image stream (the ALPH chunk's payload) function Decode.stream(buf: buffer, off: number, len: number, w: number, h: number): (buffer?, string?) local d = newState(buf, off, len, w * h) return decodeStream(d, w, h, true) end --- toRgba(argb, n, out?, outOff?) -> rgba8 bytes function Decode.toRgba(argb: buffer, n: number, out: buffer?, outOff: number?): buffer local o = out or bcreate(n * 4) local base = outOff or 0 @@ -861,7 +840,6 @@ function Decode.toRgba(argb: buffer, n: number, out: buffer?, outOff: number?): return o end --- green(argb, n) -> the green channel as bytes (alpha planes) function Decode.green(argb: buffer, n: number): buffer local o = bcreate(n) for k = 0, n - 1 do diff --git a/src/Rosetta/codecs/image/Vp8L/Encode.luau b/src/Rosetta/codecs/image/Vp8L/Encode.luau index 7aa219a..7e8cb0e 100644 --- a/src/Rosetta/codecs/image/Vp8L/Encode.luau +++ b/src/Rosetta/codecs/image/Vp8L/Encode.luau @@ -1,12 +1,7 @@ --!strict --!native --!optimize 2 --- codecs/image/Vp8L/Encode: a WebP lossless (VP8L) encoder, new code written from the specification (RFC 9649 section 3). --- Transforms: colour indexing with pixel bundling (<= 256 colours), else subtract green + predictor (per-tile mode --- chosen from a residual cost) + cross colour (per-tile least-squares multipliers). Entropy coding: LZ77 with hash --- chains, the left / up run candidates and the 2-D distance codes, a colour cache whose size is chosen by an entropy --- estimate, one prefix code group per image, code lengths limited to 15 bits (codecs/entropy/Huffman) and run-length coded. --- Never throws (the init module validates the arguments). +-- codecs/image/Vp8L/Encode: a WebP lossless (VP8L) encoder, new code written from RFC 9649 section 3. local Huffman = require("@rosetta/codecs/entropy/Huffman") local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift @@ -39,14 +34,13 @@ for i, v in CODE_TO_PLANE do PLANE_TO_CODE[v + 1] = i end --- ------------------------------------------------------------------------------------------------ bit writer type W = { buf: buffer, pos: number, acc: number, cnt: number } local function newWriter(cap: number): W return { buf = bcreate(math.max(64, cap)), pos = 0, acc = 0, cnt = 0 } end --- put(w, v, n): the n <= 24 low bits of v, LSB first +-- the n <= 24 low bits of v, LSB first local function put(w: W, v: number, n: number) local acc = w.acc + v * 2 ^ w.cnt local cnt = w.cnt + n @@ -80,7 +74,6 @@ local function finish(w: W): buffer return out end --- ------------------------------------------------------------------------------------------------ helpers local function subSample(size: number, bits: number): number return rshift(size + lshift(1, bits) - 1, bits) end @@ -92,7 +85,6 @@ local function mulHash(v: number): number return (lo * 0xa7bd + ((lo * 0x1e35 + hi * 0xa7bd) % 65536) * 65536) % 4294967296 end --- prefix(v) -> code, extra bits, extra value of a length or distance code value v >= 1 local function prefix(v: number): (number, number, number) local d = v - 1 if d < 4 then @@ -109,7 +101,7 @@ local function prefix(v: number): (number, number, number) return 2 * hb + second, eb, band(d, lshift(1, eb) - 1) end --- distCode(xs, dist) -> the distance code value (1..120 for the 2-D plane offsets, else dist + 120) +-- distance code value: 1..120 for the 2-D plane offsets, else dist + 120 local function distCode(xs: number, dist: number): number local yo = dist // xs local xo = dist - yo * xs @@ -143,7 +135,6 @@ local function half(x: number, y: number): number return clip255(x + (if dd >= 0 then rshift(dd, 1) else -rshift(-dd, 1))) end --- predict(mode, L, T, TR, TL): the decoder's predictors (codecs/image/Vp8L/Decode) local function predict(mode: number, L: number, T: number, TR: number, TL: number): number if mode == 1 then return L @@ -188,7 +179,6 @@ local function predict(mode: number, L: number, T: number, TR: number, TL: numbe return ARGB_BLACK end --- COST[v + 1]: an estimate of the bits of a residual byte v (small magnitudes, mod 256, are cheap) local COST = table.create(256, 0) for v = 0, 255 do local m = math.min(v, 256 - v) @@ -199,12 +189,10 @@ local function residualCost(r: number): number return COST[band(r, 255) + 1] + COST[band(rshift(r, 8), 255) + 1] + COST[band(rshift(r, 16), 255) + 1] + COST[rshift(r, 24) + 1] end --- ------------------------------------------------------------------------------------------------ transforms local MODES_FAST = { 1, 2, 11 } local MODES_MID = { 0, 1, 2, 4, 5, 7, 10, 11, 12, 13 } local MODES_ALL = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 } --- predictorTransform(px, w, h, bits, effort) -> the modes sub-image; px becomes the residuals local function predictorTransform(px: buffer, w: number, h: number, bits: number, effort: number): buffer local tw, th = subSample(w, bits), subSample(h, bits) local modesImg = bcreate(tw * th * 4) @@ -267,8 +255,7 @@ local function clampM(v: number): number return if m < -128 then -128 elseif m > 127 then 127 else m end --- crossColorTransform(px, w, h, bits) -> the multipliers sub-image; px is transformed in place. Per tile: the --- least-squares multipliers (r ~ g2r * g / 32, b ~ g2b * g / 32 + r2b * r / 32), kept when they lower the cost +-- cross colour per tile: least-squares r ~ g2r * g / 32, b ~ g2b * g / 32 + r2b * r / 32, kept when they lower the cost local function crossColorTransform(px: buffer, w: number, h: number, bits: number): buffer local tw, th = subSample(w, bits), subSample(h, bits) local img = bcreate(tw * th * 4) @@ -342,7 +329,6 @@ local function crossColorTransform(px: buffer, w: number, h: number, bits: numbe return img end --- ------------------------------------------------------------------------------------------------ LZ77 -- tokens: L[i] >= 0 is a literal ARGB pixel; L[i] < 0 is a copy of -L[i] pixels with the distance code value D[i] local HASH_BITS = 16 @@ -378,7 +364,6 @@ local function lz77(px: buffer, xs: number, n: number, effort: number): ({ numbe head[h] = i end end - -- best(i) -> length, distance (0, 0 when no useful match) local function best(i: number): (number, number) local max = math.min(MAX_LENGTH, n - i) if max < 2 then @@ -482,7 +467,6 @@ local function lz77(px: buffer, xs: number, n: number, effort: number): ({ numbe return L, D end --- ------------------------------------------------------------------------------------------------ prefix codes local function entropy(h: { number }): number local total = 0 for _, c in h do @@ -501,7 +485,6 @@ local function entropy(h: { number }): number return bits / log(2) end --- chooseCache(px, L, effort) -> the colour cache bits (0..10) with the smallest estimated literal cost local function chooseCache(px: buffer, L: { number }, effort: number): number if effort < 2 then return 0 @@ -565,7 +548,6 @@ end type Code = { lens: { number }, codes: { number }, single: boolean } --- buildCode(freqs, maxLen) -> code lengths, reversed (LSB-first) codes, single (<= 1 used symbol: 0 bits each) local function buildCode(freqs: { number }, maxLen: number): Code local lens = Huffman.lengths(freqs, maxLen) local used = 0 @@ -609,7 +591,6 @@ local function zeroRun(tok: { number }, ext: { number }, run: number) end end --- writeCode(w, code, alphabetSize): the code lengths (a simple code when possible, else run-length coded) local function writeCode(w: W, c: Code, size: number) local syms: { number } = {} for s = 0, size - 1 do @@ -647,7 +628,7 @@ local function writeCode(w: W, c: Code, size: number) -- decoder's "previous" starts at 8), 17 zeros (3..10), 18 zeros (11..138) local tok: { number } = {} local ext: { number } = {} - local keep = 0 -- tokens up to the last non-zero length + local keep = 0 local prev = 8 local s = 1 while s <= size do @@ -727,8 +708,7 @@ local function writeCode(w: W, c: Code, size: number) end end --- ------------------------------------------------------------------------------------------------ image data --- writeImage(w, px, xs, n, effort, level0): colour cache bits, [the meta-code bit], the five codes, the pixels +-- colour cache bits, [the meta-code bit], the five codes, the pixels local function writeImage(w: W, px: buffer, xs: number, n: number, effort: number, level0: boolean) local L, D = lz77(px, xs, n, effort) local cacheBits = if level0 then chooseCache(px, L, effort) else 0 @@ -815,8 +795,6 @@ local function writeImage(w: W, px: buffer, xs: number, n: number, effort: numbe end end --- ------------------------------------------------------------------------------------------------ encode --- toArgb(rgba, n, exact) -> ARGB pixels, any alpha < 255. Without exact, fully transparent pixels become 0. local function toArgb(rgba: buffer, n: number, exact: boolean): (buffer, boolean) local px = bcreate(n * 4) local alpha = false @@ -835,7 +813,6 @@ local function toArgb(rgba: buffer, n: number, exact: boolean): (buffer, boolean return px, alpha end --- palette(px, n) -> the sorted colours when there are at most 256, else nil local function palette(px: buffer, n: number): { number }? local seen: { [number]: boolean } = {} local list: { number } = {} @@ -855,7 +832,6 @@ end type Config = { palette: { number }?, pbits: number, cc: boolean, ccbits: number } --- stream(px, w, h, effort, cfg, bw): the transforms and the main image of one configuration (px is consumed) local function stream(px: buffer, w: number, h: number, effort: number, cfg: Config, bw: W) local n = w * h local xs = w @@ -923,8 +899,6 @@ local function stream(px: buffer, w: number, h: number, effort: number, cfg: Con writeImage(bw, px, xs, xs * h, effort, true) end --- encode(rgba, w, h, effort, exact, alphaHint?, headerless) -> the VP8L bitstream (headerless: the image stream only, --- as an ALPH chunk stores it). Efforts 6+ try several transform configurations and keep the smallest. function Encode.encode(rgba: buffer, w: number, h: number, effort: number, exact: boolean, alphaHint: boolean?, headerless: boolean): buffer local n = w * h local px, usesAlpha = toArgb(rgba, n, exact) diff --git a/src/Rosetta/codecs/image/Vp8L/init.luau b/src/Rosetta/codecs/image/Vp8L/init.luau index 156090e..0fdb50f 100644 --- a/src/Rosetta/codecs/image/Vp8L/init.luau +++ b/src/Rosetta/codecs/image/Vp8L/init.luau @@ -1,17 +1,6 @@ --!strict --- codecs/image/Vp8L: WebP lossless (VP8L, "WebP Lossless Bitstream Specification", RFC 9649 section 3). A codec (layer 1): --- image/webp uses it for VP8L frames and for compressed ALPH planes; other containers may carry it too. --- Decoder: a port of libwebp 1.6 (BSD-3-Clause, licenses/libwebp-LICENSE.txt), bit-exact with it. Encoder: new --- (subtract green, predictor and cross-colour transforms with per-tile mode search, colour indexing with pixel --- bundling for <= 256 colours, LZ77 with hash chains and the 2-D distance codes, a colour cache chosen by entropy, --- one prefix code group per image or meta codes for big images). --- --- local Vp8L = require("@rosetta/codecs/image/Vp8L") --- local rgba, w, h, alpha = Vp8L.decode(buf, off, len) -- a VP8L bitstream (0x2f signature) -> rgba8 --- local a8 = Vp8L.decodeAlpha(buf, off, len, w, h) -- a headerless stream's green channel (ALPH) --- local bits = Vp8L.encode(rgba, w, h, { effort = 4 }) -- rgba8 -> a VP8L bitstream --- --- Never throws: bad data returns nil, Err (core/Err codes TRUNCATED / CORRUPT / LIMIT / ARG). +-- codecs/image/Vp8L: WebP lossless (VP8L, RFC 9649 section 3). +-- Decoder ported from libwebp 1.6 (BSD-3-Clause, licenses/libwebp-LICENSE.txt), bit-exact with it; encoder new. local Err = require("@rosetta/core/Err") local Decode = require("@rosetta/codecs/image/Vp8L/Decode") local Encode = require("@rosetta/codecs/image/Vp8L/Encode") @@ -37,7 +26,6 @@ local function range(buf: buffer, off: number?, len: number?): (number, number) return o, math.clamp(len or (n - o), 0, n - o) end --- info(buf, off?, len?) -> { width, height, alpha } | nil, Err: the 5-byte header function Vp8L.info(buf: buffer, off: number?, len: number?): ({ width: number, height: number, alpha: boolean }?, Err.Err?) local o, l = range(buf, off, len) local w, h, alpha, err = Decode.header(buf, o, l) @@ -47,7 +35,6 @@ function Vp8L.info(buf: buffer, off: number?, len: number?): ({ width: number, h return { width = w, height = h, alpha = alpha }, nil end --- decodeArgb(buf, off?, len?, maxPixels?) -> ARGB u32 pixels (0xAARRGGBB), width, height, alphaHint | nil, Err function Vp8L.decodeArgb(buf: buffer, off: number?, len: number?, maxPixels: number?): (buffer?, any, number?, boolean?) local o, l = range(buf, off, len) local px, w, h, alpha, err = Decode.argb(buf, o, l, maxPixels or DEFAULT_MAX_PIXELS) @@ -57,7 +44,6 @@ function Vp8L.decodeArgb(buf: buffer, off: number?, len: number?, maxPixels: num return px, w, h, alpha end --- decode(buf, off?, len?, maxPixels?) -> rgba8 pixels, width, height, alphaHint | nil, Err function Vp8L.decode(buf: buffer, off: number?, len: number?, maxPixels: number?): (buffer?, any, number?, boolean?) local px, w, h, alpha = Vp8L.decodeArgb(buf, off, len, maxPixels) if not px then @@ -66,7 +52,6 @@ function Vp8L.decode(buf: buffer, off: number?, len: number?, maxPixels: number? return Decode.toRgba(px, w * (h :: number)), w, h, alpha end --- decodeAlpha(buf, off, len, width, height) -> width * height bytes (the green channel) | nil, Err function Vp8L.decodeAlpha(buf: buffer, off: number?, len: number?, width: number, height: number): (buffer?, Err.Err?) local o, l = range(buf, off, len) local px, err = Decode.stream(buf, o, l, width, height) @@ -76,16 +61,14 @@ function Vp8L.decodeAlpha(buf: buffer, off: number?, len: number?, width: number return Decode.green(px, width * height), nil end --- toRgba(argb, n) -> rgba8 bytes of n ARGB pixels Vp8L.toRgba = Decode.toRgba export type EncodeOptions = { - effort: number?, -- 0..9, default 5: more = smaller and slower (0: no transforms, no LZ77 search) - exact: boolean?, -- default false: keep the RGB of fully transparent pixels (otherwise they may be zeroed) - alphaHint: boolean?, -- the header's "alpha is used" bit; default: any alpha < 255 + effort: number?, + exact: boolean?, + alphaHint: boolean?, } --- encode(rgba, width, height, opts?) -> a VP8L bitstream (signature + header + image stream) | nil, Err function Vp8L.encode(rgba: buffer, width: number, height: number, opts: EncodeOptions?): (buffer?, Err.Err?) if type(rgba) ~= "buffer" or type(width) ~= "number" or type(height) ~= "number" then return nil, Err.new(Err.ARG, "encode: needs rgba8 pixels, width, height") @@ -104,7 +87,6 @@ function Vp8L.encode(rgba: buffer, width: number, height: number, opts: EncodeOp return Encode.encode(rgba, width, height, effort, o.exact == true, o.alphaHint, false), nil end --- encodeAlpha(a8, width, height, opts?) -> a headerless stream of the plane in green (an ALPH payload) function Vp8L.encodeAlpha(a8: buffer, width: number, height: number, opts: EncodeOptions?): (buffer?, Err.Err?) if type(a8) ~= "buffer" or buffer.len(a8) < width * height then return nil, Err.new(Err.ARG, "encodeAlpha: plane too small") diff --git a/src/Rosetta/codecs/image/Yuv.luau b/src/Rosetta/codecs/image/Yuv.luau index 7fbc944..1c21eea 100644 --- a/src/Rosetta/codecs/image/Yuv.luau +++ b/src/Rosetta/codecs/image/Yuv.luau @@ -1,17 +1,9 @@ --!strict --!native --!optimize 2 --- codecs/image/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 --- Yuv.scale(src, w, h, dw, dh, out?) -> yuv420p buffer of dw x dh (each plane bilinear; for shrinking by up to 2x per --- axis, larger factors skip source samples); Yuv.imageScale(img, dw, dh) -> Types.Image (yuv420p in and out) +-- codecs/image/Yuv: planar 4:2:0 Y'CbCr <-> rgba8, BT.601 / BT.709, limited or full range. +-- yuv -> rgb: nearest chroma, swscale's default 16-bit coefficients (within about one level of ffmpeg -pix_fmt rgba); +-- rgb -> yuv: each 2x2 block averaged for the chroma. local Types = require("@rosetta/Types") local readu8, writeu8, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu32 @@ -55,14 +47,11 @@ local function coeffs(range: string?, matrix: string?): Coeffs 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) @@ -94,7 +83,6 @@ function Yuv.toRgba(src: buffer, w: number, h: number, uo: number, vo: number, c 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 @@ -109,7 +97,6 @@ function Yuv.fromRgba(src: buffer, w: number, h: number, range: string?, matrix: 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) @@ -142,7 +129,6 @@ function Yuv.fromRgba(src: buffer, w: number, h: number, range: string?, matrix: 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 @@ -157,13 +143,11 @@ local function info(img: Types.Image): (string, string) 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 @@ -171,7 +155,6 @@ for v = 0, 255 do 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 @@ -192,7 +175,6 @@ function Yuv.toFullRange(img: Types.Image): Types.Image 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 @@ -209,7 +191,6 @@ function Yuv.imageToRgba(img: Types.Image): Types.Image? 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 @@ -224,7 +205,6 @@ function Yuv.imageFromRgba(img: Types.Image, range: string?, matrix: string?): T return out end --- one plane (sw x sh bytes at so) -> (dw x dh at do), bilinear in 8-bit fixed point (source sample centres) local function scalePlane(src: buffer, so: number, sw: number, sh: number, dst: buffer, d0: number, dw: number, dh: number) local fx, fy = sw / dw, sh / dh for y = 0, dh - 1 do @@ -258,8 +238,6 @@ local function scalePlane(src: buffer, so: number, sw: number, sh: number, dst: end end --- scale(src, w, h, dw, dh, out?) -> a yuv420p buffer of dw x dh (planes Y, U, V; chroma ceil(dw / 2) x ceil(dh / 2)). --- src must hold w x h yuv420p (checked: a short buffer or bad sizes return a zero-filled result of the right size). function Yuv.scale(src: buffer, w: number, h: number, width: number, height: number, out: buffer?): buffer local dw: number = math.max(1, floor(width)) local dh: number = math.max(1, floor(height)) diff --git a/src/Rosetta/codecs/model/Draco/Attributes.luau b/src/Rosetta/codecs/model/Draco/Attributes.luau index 53b4f52..0b98907 100644 --- a/src/Rosetta/codecs/model/Draco/Attributes.luau +++ b/src/Rosetta/codecs/model/Draco/Attributes.luau @@ -1,11 +1,7 @@ --!strict --- codecs/model/Draco/Attributes: Draco attribute decoding. The attributes decoders (one per connectivity: linear --- sequencer for sequential meshes and point clouds, traversal sequencers for Edgebreaker), their attribute --- descriptors, and the sequential attribute decoders: generic (raw values), integer, quantization (dequantized to --- f32 exactly like the C++) and octahedral normals; prediction through codecs/model/Draco/Predict. Bitstream --- versions 1.0 - 2.2. Ported from Google's Draco 1.5.7 (compression/attributes/*, compression/point_cloud/ --- point_cloud_decoder.cc, attributes/attribute_quantization_transform.cc, attribute_octahedron_transform.cc; --- Apache-2.0, licenses/draco-LICENSE.txt). +-- codecs/model/Draco/Attributes: Draco attribute decoders and sequential attribute decoding (bitstreams 1.0 - 2.2). +-- Port of Draco 1.5.7 compression/attributes/*, point_cloud_decoder.cc, attribute_quantization_transform.cc and +-- attribute_octahedron_transform.cc (Apache-2.0, licenses/draco-LICENSE.txt). local Reader = require("@rosetta/codecs/model/Draco/Reader") local Connectivity = require("@rosetta/codecs/model/Draco/Connectivity") local Predict = require("@rosetta/codecs/model/Draco/Predict") @@ -20,18 +16,18 @@ local DT_LENGTH = { [1] = 1, [2] = 1, [3] = 2, [4] = 2, [5] = 4, [6] = 4, [7] = Attributes.DT_LENGTH = DT_LENGTH export type Attr = { - id: number, -- 0-based attribute id + id: number, type: number, -- GeometryAttribute::Type (0 POSITION, 1 NORMAL, 2 COLOR, 3 TEX_COORD, 4 GENERIC, 5.. transcoder types) dataType: number, comps: number, normalized: boolean, uniqueId: number, seqType: number, -- 0 generic, 1 integer, 2 quantization, 3 normals - map: { number }?, -- point -> value (0-based values at [point + 1]); nil = identity + map: { number }?, numValues: number, - portable: { number }?, -- the integer (portable) values - values: { number }?, -- the final values (numbers), flat - raw: buffer?, -- generic attributes: the raw values + portable: { number }?, + values: { number }?, + raw: buffer?, quant: { min: { number }, range: number, bits: number }?, octBits: number?, scheme: Predict.Scheme?, @@ -44,7 +40,6 @@ type Decoder = { points: { number }?, } --- the geometry the attributes decode against export type Geom = { numPoints: number, mesh: Connectivity.Mesh?, edgebreaker: boolean, kdTree: boolean } local function zigzag(v: number): number @@ -54,8 +49,7 @@ local function zigzag(v: number): number return v // 2 end --- the parent (position) getter for a scheme: portable integers from 2.0 on, the final values before (truncated to --- integers unless the scheme works in floats) +-- parent getter: portable integers from 2.0 on, the final values before (truncated unless the scheme uses floats) local function parentGetter(ver: number, pos: Attr, floats: boolean): Predict.Parent? local old = ver < 0x0200 local vals = if old then pos.values else pos.portable @@ -228,7 +222,6 @@ local function storeValues(a: Attr): (boolean, string?) return true, nil end --- decodes every attribute; returns them in attribute id order function Attributes.decode(d: D, g: Geom): ({ Attr }?, string?) local ver = d.ver local numDecoders = Reader.u8(d) @@ -283,13 +276,11 @@ function Attributes.decode(d: D, g: Geom): ({ Attr }?, string?) enc = cad.enc dec.traversal = { ct = cad.ct :: Connectivity.CT, enc = enc, method = 0 } end - -- prediction data: the attribute's own corner table when its seams are in use local pct = if ad and ad.used then ad.ct :: Connectivity.CT else ct dec.md = { ct = pct, e2c = enc.e2c, v2e = enc.v2e } end decoders[i + 1] = dec end - -- the attribute descriptors local all: { Attr } = {} for _, dec in decoders do local n = Reader.count(d, 0x0200) @@ -350,7 +341,6 @@ function Attributes.decode(d: D, g: Geom): ({ Attr }?, string?) end return nil end - -- decode for _, dec in decoders do if g.kdTree then local ok, err = KdTree.decode(d, dec.attrs, g.numPoints) @@ -383,7 +373,6 @@ function Attributes.decode(d: D, g: Geom): ({ Attr }?, string?) end end dec.points = points - -- portable values for _, a in dec.attrs do if a.seqType == 0 then local stride = DT_LENGTH[a.dataType] * a.comps @@ -449,7 +438,6 @@ function Attributes.decode(d: D, g: Geom): ({ Attr }?, string?) end end end - -- data needed by the transforms if ver >= 0x0200 then for _, a in dec.attrs do if a.seqType == 2 then diff --git a/src/Rosetta/codecs/model/Draco/Connectivity.luau b/src/Rosetta/codecs/model/Draco/Connectivity.luau index 29e9142..0824f8f 100644 --- a/src/Rosetta/codecs/model/Draco/Connectivity.luau +++ b/src/Rosetta/codecs/model/Draco/Connectivity.luau @@ -1,27 +1,21 @@ --!strict --- codecs/model/Draco/Connectivity: Draco mesh connectivity. The sequential decoder (raw or rANS delta-coded indices) --- and the Edgebreaker decoder (standard, predictive and valence traversals, topology splits, start faces, attribute --- seams), the corner tables they build (the mesh's and one per attribute seam set), and the traversal sequencers --- (depth first and max prediction degree) that order attribute values. Ported from Google's Draco 1.5.7 --- (compression/mesh/mesh_sequential_decoder.cc, mesh_edgebreaker_decoder_impl.cc, mesh_edgebreaker_traversal_*, --- mesh/corner_table, mesh/mesh_attribute_corner_table, compression/mesh/traverser/*; Apache-2.0, --- licenses/draco-LICENSE.txt). Corners, vertices and faces are 0-based values stored at [i + 1]; -1 is invalid. +-- codecs/model/Draco/Connectivity: Draco mesh connectivity (sequential and Edgebreaker) and traversal sequencers. +-- Port of Draco 1.5.7 mesh_sequential_decoder.cc, mesh_edgebreaker_decoder_impl.cc, mesh_edgebreaker_traversal_*, +-- corner_table, mesh_attribute_corner_table, traverser/* (Apache-2.0, licenses/draco-LICENSE.txt). local Reader = require("@rosetta/codecs/model/Draco/Reader") local Connectivity = {} type D = Reader.D --- a corner table: corner -> vertex, corner -> opposite corner, vertex -> left-most corner export type CT = { c2v: { number }, opp: { number }, lmc: { number }, nv: number, nf: number } --- encoding data of one attribute connectivity: vertex -> value index, value index -> corner export type Enc = { v2e: { number }, e2c: { number }, numValues: number } export type AttrData = { decoderId: number, used: boolean, seams: { number }, ct: CT?, enc: Enc } export type Mesh = { - faces: { number }, -- corner -> point + faces: { number }, numFaces: number, numPoints: number, - ct: CT?, -- Edgebreaker only + ct: CT?, attrData: { AttrData }, posEnc: Enc?, posDecoderId: number, @@ -49,7 +43,6 @@ local function newEnc(nv: number): Enc return { v2e = table.create(nv, 0), e2c = {}, numValues = 0 } end --- ------------------------------------------------------------------------------------------------ sequential function Connectivity.sequential(d: D): (Mesh?, string?) local numFaces, numPoints if d.ver < 0x0202 then @@ -124,8 +117,6 @@ function Connectivity.sequential(d: D): (Mesh?, string?) return { faces = faces, numFaces = numFaces, numPoints = numPoints, ct = nil, attrData = {}, posEnc = nil, posDecoderId = -1 }, nil end --- ------------------------------------------------------------------------------------------------ edgebreaker --- the traversal decoders: symbols, start face configurations, attribute seam bits type Trav = { decodeSymbol: () -> number, newActiveCorner: (corner: number) -> (), @@ -134,8 +125,7 @@ type Trav = { seam: (i: number) -> boolean, } --- MeshEdgebreakerTraversalDecoder::Start (the standard parts): symbols (bits), start faces, seam decoders. --- Returns the decoder state and the buffer after them. +-- MeshEdgebreakerTraversalDecoder::Start local function standardStart(buf: D, numAttributeData: number, withSymbols: boolean): (any?, D) local st: any = {} if withSymbols then @@ -195,7 +185,7 @@ local function standardSymbol(sym: D): number return s + Reader.bits(sym, 2) * 2 end --- builds the traversal decoder for `kind` (0 standard, 1 predictive, 2 valence); returns it and the buffer after its data +-- traversal decoder kind: 0 standard, 1 predictive, 2 valence local function makeTraversal(kind: number, buf: D, numAttributeData: number, numVertices: number, numFaces: number, ct: CT): (Trav?, D) local ver = buf.ver local st, out = standardStart(buf, numAttributeData, kind ~= 2 or ver < 0x0202) @@ -372,7 +362,6 @@ local function makeTraversal(kind: number, buf: D, numAttributeData: number, num }, out end --- hole and topology split events; returns the split stack (source / split symbol ids, edges) or nil local function splitEvents(eb: D, numFaces: number): { any }? local ver = eb.ver local n = Reader.count(eb, 0x0200) @@ -559,7 +548,6 @@ function Connectivity.edgebreaker(d: D, traversalKind: number): (Mesh?, string?) end local maxVertices = numEncodedVertices + numSplitSymbols - -- the corner table (filled lazily: nil = invalid) local c2v: { number } = {} local opp: { number } = {} local lmc: { number } = {} @@ -630,7 +618,6 @@ function Connectivity.edgebreaker(d: D, traversalKind: number): (Mesh?, string?) return prevC(O(prevC(c))) end - -- the symbols local stack: { number } = {} local sp = 0 local splitActive: { [number]: number } = {} @@ -869,7 +856,6 @@ function Connectivity.edgebreaker(d: D, traversalKind: number): (Mesh?, string?) d.pos += splitBytes end - -- attribute seams local attrData: { AttrData } = {} for i = 1, numAttributeData do attrData[i] = { decoderId = -1, used = true, seams = {}, ct = nil, enc = newEnc(0) } @@ -990,9 +976,7 @@ function Connectivity.edgebreaker(d: D, traversalKind: number): (Mesh?, string?) }, nil end --- ------------------------------------------------------------------------------------------------ traversal --- MeshTraversalSequencer::GenerateSequence: the point ids in value order; fills enc (v2e, e2c, numValues). --- method 0 = depth first, 1 = max prediction degree. +-- MeshTraversalSequencer::GenerateSequence: method 0 depth first, 1 max prediction degree function Connectivity.traverse(ct: CT, faces: { number }, enc: Enc, method: number): { number }? local c2v, opp, lmc = ct.c2v, ct.opp, ct.lmc local nf, nvt = ct.nf, ct.nv @@ -1093,7 +1077,6 @@ function Connectivity.traverse(ct: CT, faces: { number }, enc: Enc, method: numb end return points end - -- max prediction degree if nvt == 0 then return points end @@ -1182,7 +1165,7 @@ function Connectivity.traverse(ct: CT, faces: { number }, enc: Enc, method: numb return points end --- MeshTraversalSequencer::UpdatePointToAttributeIndexMapping: point -> value index (1-based table of 0-based values) +-- MeshTraversalSequencer::UpdatePointToAttributeIndexMapping function Connectivity.mapping(ct: CT, faces: { number }, enc: Enc, numPoints: number): { number }? local map = table.create(numPoints, 0) local c2v, v2e = ct.c2v, enc.v2e diff --git a/src/Rosetta/codecs/model/Draco/Int64.luau b/src/Rosetta/codecs/model/Draco/Int64.luau index 4365b8b..a695fe3 100644 --- a/src/Rosetta/codecs/model/Draco/Int64.luau +++ b/src/Rosetta/codecs/model/Draco/Int64.luau @@ -1,7 +1,6 @@ --!strict --- codecs/model/Draco/Int64: the 64-bit integer arithmetic Draco's portable tex coord predictor relies on (int64 / --- uint64 with wrap-around, truncating division, IntSqrt), on (hi, lo) pairs of 32-bit halves held in numbers (both --- runtimes: no native 64-bit integers). Two's complement: hi >= 2^31 is negative when read as signed. +-- codecs/model/Draco/Int64: wrap-around int64 / uint64 for Draco's portable tex coord predictor. +-- Values are (hi, lo) 32-bit halves, two's complement (hi >= 2^31 is negative). local Int64 = {} local P32 = 4294967296 @@ -37,7 +36,6 @@ function Int64.sub(ah: number, al: number, bh: number, bl: number): (number, num return Int64.add(ah, al, nh, nl) end --- the product mod 2^64 (the same bits for signed and unsigned operands) function Int64.mul(ah: number, al: number, bh: number, bl: number): (number, number) local a0, a1, a2, a3 = al % 65536, al // 65536, ah % 65536, ah // 65536 local b0, b1, b2, b3 = bl % 65536, bl // 65536, bh % 65536, bh // 65536 @@ -56,7 +54,6 @@ function Int64.isNeg(h: number): boolean return h >= P31 end --- the signed value as a number (exact below 2^53 in magnitude) function Int64.signed(h: number, l: number): number if h >= P31 then return (h - P32) * P32 + l @@ -64,12 +61,10 @@ function Int64.signed(h: number, l: number): number return h * P32 + l end --- the unsigned value as a number (rounded past 2^53) function Int64.unsigned(h: number, l: number): number return h * P32 + l end --- unsigned compare: -1, 0, 1 function Int64.ucmp(ah: number, al: number, bh: number, bl: number): number if ah ~= bh then return if ah < bh then -1 else 1 @@ -80,7 +75,6 @@ function Int64.ucmp(ah: number, al: number, bh: number, bl: number): number return 0 end --- signed compare: -1, 0, 1 function Int64.cmp(ah: number, al: number, bh: number, bl: number): number local sa = if ah >= P31 then ah - P32 else ah local sb = if bh >= P31 then bh - P32 else bh @@ -90,14 +84,12 @@ function Int64.cmp(ah: number, al: number, bh: number, bl: number): number return Int64.ucmp(0, al, 0, bl) end --- unsigned division (b ~= 0): quotient, remainder function Int64.udivmod(ah: number, al: number, bh: number, bl: number): (number, number, number, number) if ah == 0 and bh == 0 then return 0, al // bl, 0, al % bl end local qh, ql, rh, rl = 0, 0, 0, 0 for i = 63, 0, -1 do - -- r = r * 2 + bit i of a local bit = if i >= 32 then (ah // 2 ^ (i - 32)) % 2 else (al // 2 ^ i) % 2 local over = rh >= P31 rh = (rh * 2 + rl // P31) % P32 @@ -114,7 +106,6 @@ function Int64.udivmod(ah: number, al: number, bh: number, bl: number): (number, return qh, ql, rh, rl end --- signed division truncating toward zero (b ~= 0) function Int64.div(ah: number, al: number, bh: number, bl: number): (number, number) local na, nb = ah >= P31, bh >= P31 if na then diff --git a/src/Rosetta/codecs/model/Draco/KdTree.luau b/src/Rosetta/codecs/model/Draco/KdTree.luau index a272afc..818b545 100644 --- a/src/Rosetta/codecs/model/Draco/KdTree.luau +++ b/src/Rosetta/codecs/model/Draco/KdTree.luau @@ -1,10 +1,7 @@ --!strict --- codecs/model/Draco/KdTree: kd-tree coded point cloud attributes (bitstream 2.3): DynamicIntegerPointsKdTreeDecoder --- at compression levels 0 - 6 (direct bits, rANS bits, folded 32-bit rANS numbers, selected axes) over all the --- attributes of a decoder at once, then the signed offsets and the dequantization of f32 attributes. Ported from --- Google's Draco 1.5.7 (compression/attributes/kd_tree_attributes_decoder.cc, compression/point_cloud/algorithms/ --- dynamic_integer_points_kd_tree_decoder.h, compression/bit_coders/{direct,folded_integer}_bit_decoder; Apache-2.0, --- licenses/draco-LICENSE.txt). The pre-2.3 kd-tree layouts are not supported. +-- codecs/model/Draco/KdTree: kd-tree coded point cloud attributes (bitstream 2.3, compression levels 0 - 6). +-- Port of Draco 1.5.7 kd_tree_attributes_decoder.cc, dynamic_integer_points_kd_tree_decoder.h and the direct / +-- folded_integer bit decoders (Apache-2.0, licenses/draco-LICENSE.txt). Pre-2.3 kd-tree layouts are not supported. local Reader = require("@rosetta/codecs/model/Draco/Reader") local Predict = require("@rosetta/codecs/model/Draco/Predict") @@ -12,7 +9,7 @@ local KdTree = {} type D = Reader.D --- a bit source: next() -> 0 / 1, bits(n) -> value (MSB first); bits returns nil when a direct decoder runs out +-- bits(n) reads MSB first type Src = { next: () -> number, bits: (n: number) -> number? } local function direct(d: D): Src? @@ -122,7 +119,7 @@ local function msb(n: number): number return k end --- DynamicIntegerPointsKdTreeDecoder::DecodePoints -> points (each a table of `dim` u32 values), or nil +-- DynamicIntegerPointsKdTreeDecoder::DecodePoints local function decodePoints(d: D, level: number, dim: number, expected: number): ({ { number } }?, string?) local bitLength = Reader.u32(d) local numPoints = Reader.u32(d) @@ -250,7 +247,6 @@ end local SIGNED = { [1] = 8, [3] = 16, [5] = 32 } --- decodes the attributes of one kd-tree decoder (Attributes.Attr records: dataType, comps; sets values / numValues) function KdTree.decode(d: D, attrs: { any }, numPoints: number): (boolean, string?) if d.ver < 0x0203 then return false, "unsupported: kd-tree point clouds before bitstream 2.3" @@ -293,7 +289,6 @@ function KdTree.decode(d: D, attrs: { any }, numPoints: number): (boolean, strin a.map = nil off += comps end - -- the data needed by the transforms: f32 quantization, then the signed minima for _, a in attrs do if a.dataType == 9 then local mins = table.create(a.comps, 0) @@ -321,7 +316,6 @@ function KdTree.decode(d: D, attrs: { any }, numPoints: number): (boolean, strin a.signedMin = mins end end - -- back to the original values local fround = Predict.fround for _, a in attrs do local vals = a.portable :: { number } diff --git a/src/Rosetta/codecs/model/Draco/Predict.luau b/src/Rosetta/codecs/model/Draco/Predict.luau index 1e47715..1e6c1ae 100644 --- a/src/Rosetta/codecs/model/Draco/Predict.luau +++ b/src/Rosetta/codecs/model/Draco/Predict.luau @@ -1,11 +1,7 @@ --!strict --- codecs/model/Draco/Predict: Draco attribute prediction schemes and their decoding transforms. Schemes: difference --- (delta), parallelogram, multi-parallelogram, constrained multi-parallelogram, tex coords (deprecated, float) and --- portable tex coords, geometric normal; transforms: wrap, normal octahedron and canonicalized normal octahedron. --- Integer semantics follow the C++ (int32 wrap, truncating division, exact 64-bit products where they can pass 2^53; --- float math rounded to f32 at every step). Ported from Google's Draco 1.5.7 --- (compression/attributes/prediction_schemes/*, compression/attributes/normal_compression_utils.h; Apache-2.0, --- licenses/draco-LICENSE.txt). +-- codecs/model/Draco/Predict: Draco attribute prediction schemes and their decoding transforms. +-- C++ integer semantics (int32 wrap, truncating division, exact 64-bit products) and f32 rounding at every step. +-- Port of Draco 1.5.7 prediction_schemes/*, normal_compression_utils.h (Apache-2.0, licenses/draco-LICENSE.txt). local Reader = require("@rosetta/codecs/model/Draco/Reader") local Connectivity = require("@rosetta/codecs/model/Draco/Connectivity") local Int64 = require("@rosetta/codecs/model/Draco/Int64") @@ -87,7 +83,7 @@ local function isqrtProd(a: number, b: number): number end local s = math.floor(math.sqrt(a) * math.sqrt(b)) local ph, pl = twoProd(a, b) - local function le(x: number): boolean -- x * x <= a * b + local function le(x: number): boolean local xh, xl = twoProd(x, x) if xh ~= ph then return xh < ph @@ -103,7 +99,6 @@ local function isqrtProd(a: number, b: number): number return s end --- ------------------------------------------------------------------------------------------------ octahedron toolbox export type Oct = { bits: number, maxQ: number, maxV: number, center: number, scale: number } function Predict.octahedron(bits: number): Oct? @@ -207,8 +202,6 @@ function Predict.octToVector(o: Oct, s: number, t: number): (number, number, num return fround(x * dd), fround(y * dd), fround(z * dd) end --- ------------------------------------------------------------------------------------------------ transforms --- tr.apply(pred, data, off): data[off + 1 ..] holds the corrections and receives the original values export type Transform = { kind: number, -- 1 wrap, 2 octahedron, 3 octahedron canonicalized positive: boolean, -- corrections are stored without the zig-zag sign mapping @@ -254,7 +247,6 @@ function Predict.decodeTransform(tr: Transform, d: D): boolean return true end --- the original values from a prediction (pred[1 .. comps]) and the corrections at data[off + 1 ..] local function apply(tr: Transform, pred: { number }, data: { number }, off: number, comps: number) if tr.kind == 1 then local mn, mx, dif = tr.min, tr.max, tr.maxDif @@ -324,10 +316,7 @@ local function apply(tr: Transform, pred: { number }, data: { number }, off: num end Predict.apply = apply --- ------------------------------------------------------------------------------------------------ schemes --- the mesh data of a scheme: corner table, value -> corner, vertex -> value export type MeshData = { ct: CT, e2c: { number }, v2e: { number } } --- the parent position attribute: pos(point) -> x, y, z (portable integers, or floats before 2.0) export type Parent = (point: number) -> (number, number, number) export type Scheme = { @@ -335,7 +324,6 @@ export type Scheme = { tr: Transform, md: MeshData?, parent: Parent?, - -- per-scheme decoded data crease: { { boolean } }?, orient: { boolean }?, flips: Reader.Bits?, @@ -346,7 +334,6 @@ export type Scheme = { local DELTA, PARALLELOGRAM, MULTI, TEXDEP, CONSTRAINED, TEXPORT, GEONORMAL = 0, 1, 2, 3, 4, 5, 6 Predict.GEOMETRIC_NORMAL = GEONORMAL --- whether the scheme needs the position attribute function Predict.needsParent(s: Scheme): boolean return s.md ~= nil and (s.method == TEXDEP or s.method == TEXPORT or s.method == GEONORMAL) end @@ -489,9 +476,7 @@ local function swingLeft(ct: CT, c: number): number return nextC(o) end --- the portable tex coord prediction when both neighbours are decoded (MeshPredictionSchemeTexCoordsPortablePredictor --- ::ComputePredictedValue), in int64 / uint64 arithmetic like the C++. Returns "ok", u, v; "fallback" (degenerate --- edge: predict from a neighbour); or "fail", message. +-- MeshPredictionSchemeTexCoordsPortablePredictor::ComputePredictedValue in int64 / uint64 like the C++ local function texPortable(nu: number, nv: number, pu: number, pv: number, tx: number, ty: number, tz: number, nx: number, ny: number, nz: number, qx: number, qy: number, qz: number, pop: () -> boolean?): (string, any, any) local pnx, pny, pnz = qx - nx, qy - ny, qz - nz local cnx, cny, cnz = tx - nx, ty - ny, tz - nz @@ -524,7 +509,6 @@ local function texPortable(nu: number, nv: number, pu: number, pv: number, tx: n end end end - -- the general case: int64 local from, add, sub, mul, div = Int64.from, Int64.add, Int64.sub, Int64.mul, Int64.div local function dot3(ax: number, ay: number, az: number, bx: number, by: number, bz: number): (number, number) local xh, xl = from(ax) @@ -636,7 +620,7 @@ local function texPortable(nu: number, nv: number, pu: number, pv: number, tx: n return "ok", i32(ul), i32(vl) end --- ComputeOriginalValues over data (corrections in, values out, in place); points = the entry -> point map +-- ComputeOriginalValues (in place); points = the entry -> point map function Predict.compute(s: Scheme, data: { number }, numEntries: number, comps: number, points: { number }): (boolean, string?) local tr = s.tr local m = s.method @@ -912,7 +896,6 @@ function Predict.compute(s: Scheme, data: { number }, numEntries: number, comps: end return true, nil end - -- geometric normal local o = tr.oct local flips = s.flips if not o or not flips or comps ~= 2 then diff --git a/src/Rosetta/codecs/model/Draco/Reader.luau b/src/Rosetta/codecs/model/Draco/Reader.luau index 1fb3b5c..a90353b 100644 --- a/src/Rosetta/codecs/model/Draco/Reader.luau +++ b/src/Rosetta/codecs/model/Draco/Reader.luau @@ -1,10 +1,7 @@ --!strict --- codecs/model/Draco/Reader: the Draco decoder buffer (little-endian fields, LEB128 varints, LSB-first bit runs) and --- its entropy decoders: rANS symbol coding (tagged and raw schemes, DecodeSymbols) and the binary rANS / rABS bit --- decoder. Ported from Google's Draco 1.5.7 (core/decoder_buffer, core/varint_decoding, compression/entropy/ans.h, --- rans_symbol_decoder.h, symbol_decoding.cc, compression/bit_coders/rans_bit_decoder.cc; Apache-2.0, --- licenses/draco-LICENSE.txt). Bitstream versions 1.0 - 2.2 (fixed-width counts before 2.0 / 2.2). --- A failed read sets the sticky d.bad message and returns 0; callers check d.bad at their boundaries. +-- codecs/model/Draco/Reader: Draco's decoder buffer (LE fields, LEB128, LSB-first bit runs) and rANS / rABS decoders. +-- Port of Draco 1.5.7 core/decoder_buffer, core/varint_decoding, entropy/ans.h, rans_symbol_decoder.h, symbol_decoding.cc +-- and rans_bit_decoder.cc (Apache-2.0, licenses/draco-LICENSE.txt). local Reader = {} local readu8, readu16, readu32, readi32, readf32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi32, buffer.readf32 @@ -12,13 +9,13 @@ local band, rshift = bit32.band, bit32.rshift export type D = { b: buffer, - pos: number, -- absolute offset in b - limit: number, -- absolute end + pos: number, + limit: number, ver: number, -- major * 256 + minor bad: string?, bitMode: boolean, - bitStart: number, -- absolute byte where the bit run starts - bitOff: number, -- bits consumed + bitStart: number, + bitOff: number, } function Reader.new(b: buffer, pos: number, limit: number, ver: number): D @@ -82,7 +79,6 @@ function Reader.i32(d: D): number return readi32(d.b, p) end --- u64 as a number (exact below 2^53; sizes beyond that fail the bounds checks anyway) function Reader.u64(d: D): number local p = d.pos if p + 8 > d.limit then @@ -132,7 +128,6 @@ function Reader.count(d: D, fixedBefore: number): number return Reader.varint(d) end --- ------------------------------------------------------------------------------------------------ bit runs -- StartBitDecoding(decodeSize): an optional size (u64 before 2.2, varint64 after), then LSB-first bits up to the end -- of the buffer; EndBitDecoding moves pos past the whole bytes consumed. function Reader.startBits(d: D, decodeSize: boolean): number @@ -179,7 +174,6 @@ function Reader.endBits(d: D) d.pos = d.bitStart + (d.bitOff + 7) // 8 end --- ------------------------------------------------------------------------------------------------ rANS symbols -- the precision for a symbol alphabet of `bitLength`-bit symbols: (3 * bits) / 2 clamped to 12..20 local function precisionBits(bitLength: number): number local p = (3 * bitLength) // 2 @@ -188,12 +182,12 @@ end export type Rans = { b: buffer, - base: number, -- absolute start of the coded bytes - off: number, -- bytes left (read backwards from base + off) + base: number, + off: number, state: number, lBase: number, precBits: number, - lut: { number }, -- rem + 1 -> symbol + 1 + lut: { number }, prob: { number }, cum: { number }, numSymbols: number, @@ -337,7 +331,6 @@ local function ransStart(d: D, r: Rans): boolean return true end --- decodes n symbols into out[first .. first + n - 1] (0-based symbol values) local function ransRead(r: Rans, n: number, out: { number }, first: number) local b, base, off, state = r.b, r.base, r.off, r.state local lBase, bits = r.lBase, r.precBits @@ -412,7 +405,7 @@ local function decodeRaw(d: D, n: number, out: { number }): boolean return true end --- DecodeSymbols(n, components) -> { u32 } (1-based) | nil (d.bad set) +-- DecodeSymbols function Reader.symbols(d: D, n: number, comps: number): { number }? local out = table.create(n, 0) if n == 0 then @@ -434,7 +427,6 @@ function Reader.symbols(d: D, n: number, comps: number): { number }? return if ok then out else nil end --- ------------------------------------------------------------------------------------------------ binary rANS export type Bits = { b: buffer, base: number, off: number, state: number, p0: number, p: number } -- RAnsBitDecoder::StartDecoding: prob_zero, the size (u32 before 2.2), the bytes diff --git a/src/Rosetta/codecs/model/Draco/init.luau b/src/Rosetta/codecs/model/Draco/init.luau index 9b747be..1e642b9 100644 --- a/src/Rosetta/codecs/model/Draco/init.luau +++ b/src/Rosetta/codecs/model/Draco/init.luau @@ -1,25 +1,7 @@ --!strict -- codecs/model/Draco: Google Draco geometry decompression (.drc; glTF KHR_draco_mesh_compression; Roblox mesh v6 / v7). --- A codec, not a format: model/gltf (and any format carrying Draco data) calls it on a byte range. --- Ported from Google's Draco 1.5.7 (Apache-2.0, licenses/draco-LICENSE.txt): the decoder only, bitstream versions --- 1.0 - 2.2 for meshes (sequential and Edgebreaker connectivity: standard, predictive and valence traversals; topology --- splits, attribute seams), sequential point clouds and kd-tree point clouds (2.3); attribute decoders generic / --- integer / quantization / octahedral normals; prediction schemes difference, parallelogram, multi-parallelogram, --- constrained multi-parallelogram, tex coords (deprecated and portable), geometric normal, with the wrap and normal --- octahedron transforms; metadata. Values match draco_decoder bit for bit (f32 rounding at every step of the --- dequantization). --- Not supported: the pre-2.3 kd-tree point cloud layouts (Err.UNSUPPORTED). --- --- local Draco = require("@rosetta/codecs/model/Draco") --- local g, err = Draco.decode(buf, off?, len?, opts?) -- buffer | string --- g.kind ("mesh" | "points"), g.numPoints, g.numFaces, g.indices (u32 x 3 per face, or nil for points) --- g.attributes[i] = { name = "POSITION" | "NORMAL" | "COLOR" | "TEX_COORD" | "GENERIC" | ..., uniqueId, --- components, type = "f32" | "u8" | "i16" | ..., normalized, data (per point, packed) } --- Draco.attribute(g, uniqueId) -> the attribute with that unique id (glTF's attribute map) --- g.metadata = { entries = { [name] = buffer }, children = { [name] = Metadata }, attributes = { [uniqueId] = Metadata } } --- --- Options: maxPoints (default 2^24), maxFaces (default 2^24): larger geometry returns Err.LIMIT. --- Never throws: bad data returns nil, Err (TRUNCATED / CORRUPT / UNSUPPORTED / LIMIT). +-- Port of Draco 1.5.7's decoder (Apache-2.0, licenses/draco-LICENSE.txt): bitstreams 1.0 - 2.2 meshes, 2.3 kd-tree +-- point clouds; values match draco_decoder bit for bit (f32 rounding at every dequantization step). local Err = require("@rosetta/core/Err") local Bytes = require("@rosetta/core/Bytes") local Reader = require("@rosetta/codecs/model/Draco/Reader") @@ -55,7 +37,6 @@ export type Geometry = { } export type Header = { major: number, minor: number, kind: "mesh" | "points", method: number, flags: number } --- sniff(buf, off?) -> whether the bytes start with "DRACO" function Draco.sniff(buf: buffer, off: number?): boolean local o = off or 0 return buffer.len(buf) >= o + 5 and buffer.readstring(buf, o, 5) == "DRACO" @@ -77,7 +58,6 @@ local function header(d: Reader.D): (Header?, string?) return { major = major, minor = minor, kind = if kind == 0 then "points" else "mesh", method = method, flags = flags }, nil end --- info(buf, off?, len?) -> the header function Draco.info(src: buffer | string, off: number?, len: number?): (Header?, Err.Err?) local buf, o, l, aerr = Bytes.span("draco", src, off, len) if not buf then @@ -169,7 +149,6 @@ local WRITE: { [number]: (buffer, number, number) -> () } = { [11] = buffer.writeu8, } --- per point output buffer of an attribute local function expand(a: Attributes.Attr, numPoints: number): (buffer?, string?) local size = Attributes.DT_LENGTH[a.dataType] local comps = a.comps @@ -324,7 +303,6 @@ local function decode(buf: buffer, o: number, l: number, opts: any): (Geometry?, return g, nil, nil end --- decode(src, off?, len?, opts?) -> Geometry | nil, Err function Draco.decode(src: buffer | string, off: number?, len: number?, opts: any?): (Geometry?, Err.Err?) local buf, o, l, aerr = Bytes.span("draco", src, off, len) if not buf then @@ -340,7 +318,6 @@ function Draco.decode(src: buffer | string, off: number?, len: number?, opts: an return g, nil end --- attribute(g, uniqueId) -> the attribute with that unique id function Draco.attribute(g: Geometry, uniqueId: number): Attribute? for _, a in g.attributes do if a.uniqueId == uniqueId then diff --git a/src/Rosetta/codecs/model/Mat4.luau b/src/Rosetta/codecs/model/Mat4.luau index 4095644..43547cd 100644 --- a/src/Rosetta/codecs/model/Mat4.luau +++ b/src/Rosetta/codecs/model/Mat4.luau @@ -1,14 +1,5 @@ --!strict --- codecs/model/Mat4: 4x4 matrix and quaternion helpers for the model formats: column-major flat arrays of 16 --- (glTF / FBX / Types.Scene layout: translation at 13..15), quaternions { x, y, z, w }, angles in degrees where a --- format stores degrees. Shared by FBX, Collada, USD and MeshOps instead of a copy in each. New in rosetta (the --- functions come from the former model/fbx/Xform, model/dae/Math and model/usda/Build helpers). --- --- local m = Mat4.compose({ 1, 2, 3 }, quat, { 2, 2, 2 }) -- T * R * S --- local t, r, s = Mat4.decompose(m) -- (decomposeStrict: nil for shear / projective / singular) --- local w = Mat4.mul(parent, m) -- = Types.Scene.mul --- local inv = Mat4.inverse(m) -- affine inverse | nil --- local x, y, z = Mat4.point(m, px, py, pz) +-- codecs/model/Mat4: 4x4 matrix (column-major, glTF / Types.Scene layout) and quaternion { x, y, z, w } helpers. local Types = require("@rosetta/Types") local Mat4 = {} @@ -21,7 +12,6 @@ function Mat4.identity(): M4 return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 } end --- mul(a, b) -> a * b Mat4.mul = Types.Scene.mul function Mat4.translation(x: number, y: number, z: number): M4 @@ -32,7 +22,6 @@ function Mat4.scaling(x: number, y: number, z: number): M4 return { x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1 } end --- rotation(axis, degrees) -> the rotation about axis 1 (X), 2 (Y) or 3 (Z) function Mat4.rotation(axis: number, degrees: number): M4 local a = rad(degrees) local c, s = cos(a), sin(a) @@ -45,7 +34,6 @@ function Mat4.rotation(axis: number, degrees: number): M4 end local AXIS = { x = 1, y = 2, z = 3 } --- euler(x, y, z, order?) -> the rotation applying the axes in order (default "xyz": R = Rz * Ry * Rx), degrees function Mat4.euler(x: number, y: number, z: number, order: string?): M4 local o = order or "xyz" local deg = { x = x, y = y, z = z } @@ -57,7 +45,6 @@ function Mat4.euler(x: number, y: number, z: number, order: string?): M4 return m end --- axisAngle(x, y, z, degrees) -> quaternion function Mat4.axisAngle(x: number, y: number, z: number, degrees: number): { number } local l = sqrt(x * x + y * y + z * z) if l < 1e-12 then @@ -68,7 +55,6 @@ function Mat4.axisAngle(x: number, y: number, z: number, degrees: number): { num return { x * s, y * s, z * s, cos(h) } end --- fromQuat(q) -> the rotation matrix of a quaternion function Mat4.fromQuat(q: { number }): M4 local x, y, z, w = q[1], q[2], q[3], q[4] local xx, yy, zz, xy, xz, yz, wx, wy, wz = x * x, y * y, z * z, x * y, x * z, y * z, w * x, w * y, w * z @@ -80,7 +66,6 @@ function Mat4.fromQuat(q: { number }): M4 } end --- quat(m) -> the unit quaternion of the rotation in m's upper 3x3 (columns assumed orthonormal) function Mat4.quat(m: M4): { number } local m00, m01, m02 = m[1], m[5], m[9] local m10, m11, m12 = m[2], m[6], m[10] @@ -107,7 +92,6 @@ function Mat4.quat(m: M4): { number } return { x / n, y / n, z / n, w / n } end --- eulerXYZ(q) -> Euler XYZ degrees (R = Rz * Ry * Rx) of a quaternion function Mat4.eulerXYZ(q: { number }): { number } local m = Mat4.fromQuat(q) local sy = math.clamp(-m[3], -1, 1) -- m[3] = r20 = -sin(y) @@ -123,7 +107,7 @@ function Mat4.eulerXYZ(q: { number }): { number } return { math.deg(x), math.deg(y), math.deg(z) } end --- compose(t?, r?, s?) -> T * R * S (glTF node semantics) +-- T * R * S (glTF 2.0 node transform) function Mat4.compose(t: { number }?, r: { number }?, s: { number }?): M4 local m = if r then Mat4.fromQuat(r) else Mat4.identity() if s then @@ -171,19 +155,16 @@ local function split(m: M4, strict: boolean): ({ number }?, { number }?, { numbe return { m[13], m[14], m[15] }, Mat4.quat(r), { sx, sy, sz } end --- decompose(m) -> translation, rotation (quaternion), scale (a negative determinant flips the x scale; shear is lost) +-- a negative determinant flips the x scale; shear is lost function Mat4.decompose(m: M4): ({ number }, { number }, { number }) local t, r, s = split(m, false) return t :: { number }, r :: { number }, s :: { number } end --- decomposeStrict(m) -> translation, rotation, scale | nil for matrices TRS cannot express (a projective row, shear, --- a zero scale) function Mat4.decomposeStrict(m: M4): ({ number }?, { number }?, { number }?) return split(m, true) end --- inverse(m) -> the inverse of an affine matrix (general upper 3x3) | nil when singular function Mat4.inverse(m: M4): M4? local a, b, c = m[1], m[5], m[9] local d, e, f = m[2], m[6], m[10] @@ -207,7 +188,6 @@ function Mat4.inverse(m: M4): M4? return r end --- inverseFull(m) -> the inverse of any invertible 4x4 (projective rows too) | nil when singular function Mat4.inverseFull(m: M4): M4? local a = m local inv = table.create(16, 0) @@ -237,12 +217,10 @@ function Mat4.inverseFull(m: M4): M4? return inv end --- transpose3(m) -> m with its upper 3x3 transposed and no translation (the inverse of a pure rotation) function Mat4.transpose3(m: M4): M4 return { m[1], m[5], m[9], 0, m[2], m[6], m[10], 0, m[3], m[7], m[11], 0, 0, 0, 0, 1 } end --- fromRows(v, at?) -> column-major from 16 row-major values at v[at] (default 1; missing values: identity) function Mat4.fromRows(v: { number }, at: number?): M4 local o = (at or 1) - 1 local m = table.create(16, 0) @@ -254,7 +232,6 @@ function Mat4.fromRows(v: { number }, at: number?): M4 return m end --- toRows(m) -> the 16 values row-major function Mat4.toRows(m: M4): { number } local v = table.create(16, 0) for r = 0, 3 do @@ -265,12 +242,10 @@ function Mat4.toRows(m: M4): { number } return v end --- point(m, x, y, z) -> m * (x, y, z, 1) function Mat4.point(m: M4, x: number, y: number, z: number): (number, number, number) return m[1] * x + m[5] * y + m[9] * z + m[13], m[2] * x + m[6] * y + m[10] * z + m[14], m[3] * x + m[7] * y + m[11] * z + m[15] end --- normalMatrix(m) -> the inverse transpose of the upper 3x3 (for normals) as a 4x4 (identity when singular) function Mat4.normalMatrix(m: M4): M4 local inv = Mat4.inverse({ m[1], m[2], m[3], 0, m[5], m[6], m[7], 0, m[9], m[10], m[11], 0, 0, 0, 0, 1 }) if not inv then diff --git a/src/Rosetta/codecs/model/MeshFlatten.luau b/src/Rosetta/codecs/model/MeshFlatten.luau index f9c2e16..01a76c2 100644 --- a/src/Rosetta/codecs/model/MeshFlatten.luau +++ b/src/Rosetta/codecs/model/MeshFlatten.luau @@ -1,11 +1,5 @@ --!strict --- codecs/model/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). Walks --- scene.roots recursively (TRS or column-major `matrix` per node; a scene without nodes uses its meshes as they are), --- applies the transforms to POSITION (and the inverse transpose to NORMAL), reverses the winding under mirroring --- transforms, reads every accessor type to numbers and concatenates all primitives (triangles with or without indices, --- polygons, strips, fans, points; lines are skipped). Shared here because a format cannot require another one --- (ops/MeshOps.merge is the editing-side equivalent). --- Never throws: bad input returns nil, message. +-- codecs/model/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). local Types = require("@rosetta/Types") local Flatten = {} @@ -19,31 +13,29 @@ local SIZE = Types.COMPONENT_SIZE local NORM: { [string]: number } = { unorm8 = 255, unorm16 = 65535, snorm8 = 127, snorm16 = 32767 } export type Attr = { - type: string, -- the accessor type shared by every part ("f32" when the parts disagree) + type: string, components: number, - raw: boolean, -- values are raw integers of a normalized type (unorm8: 0..255), else plain numbers - values: { number }, -- count * components + raw: boolean, + values: { number }, } export type PartInfo = { prim: Types.Primitive, mesh: Types.Mesh?, node: Types.Node?, - firstVertex: number, -- 0-based offset of the part's vertices in the merged mesh + firstVertex: number, vertexCount: number, - firstFace: number, -- 0-based offset of the part's faces + firstFace: number, faceCount: number, - identity: boolean, -- no transform was applied + identity: boolean, } export type Merged = { - count: number, -- vertices - attrs: { [string]: Attr }, -- POSITION and NORMAL in world space (f32 values), the others as read - sizes: { number }?, -- vertices per face (nil: no part has faces, a point cloud) - corners: { number }, -- 0-based vertex indices, face after face + count: number, + attrs: { [string]: Attr }, + sizes: { number }?, + corners: { number }, parts: { PartInfo }, } --- ------------------------------------------------------------------------------------------------ accessors --- numbers(acc, raw) -> the accessor's count * components values (normalized types divided out unless raw), or nil, msg function Flatten.numbers(acc: any, raw: boolean?): ({ number }?, string?) if type(acc) ~= "table" or type(acc.data) ~= "buffer" then return nil, "accessor without a data buffer" @@ -106,10 +98,9 @@ function Flatten.numbers(acc: any, raw: boolean?): ({ number }?, string?) return out, nil end --- ------------------------------------------------------------------------------------------------ transforms local IDENTITY = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 } -local mul = Types.Scene.mul -- column-major 4x4 product a * b +local mul = Types.Scene.mul local function numList(v: any, n: number): boolean if type(v) ~= "table" then @@ -123,7 +114,6 @@ local function numList(v: any, n: number): boolean return true end --- a node's local matrix (nil: none), or nil, message local function localMatrix(node: any): ({ number }?, string?) if node.matrix ~= nil then if not numList(node.matrix, 16) then @@ -186,7 +176,6 @@ end type Instance = { prim: Types.Primitive, mesh: Types.Mesh?, node: Types.Node?, matrix: { number }? } --- the primitive instances of a scene in traversal order, or nil, message local function instances(scene: any): ({ Instance }?, string?) local out: { Instance } = {} local nodes, meshes = scene.nodes, scene.meshes @@ -274,8 +263,6 @@ local function instances(scene: any): ({ Instance }?, string?) return out, nil end --- ------------------------------------------------------------------------------------------------ faces --- the faces of a primitive: sizes (nil = all triangles), corners (0-based), or "points" / "skip", or nil, message local function faces(prim: any, nv: number): (any, any, string?) local mode = prim.mode or "triangles" if mode == "points" then @@ -352,7 +339,6 @@ local function faces(prim: any, nv: number): (any, any, string?) return nil, nil, "unknown primitive mode " .. tostring(mode) end --- ------------------------------------------------------------------------------------------------ merge -- the fill value of a missing attribute component: colours default to opaque white, everything else to 0 local function fill(name: string, t: string, raw: boolean): number if string.sub(name, 1, 6) ~= "COLOR_" then @@ -367,8 +353,6 @@ local function f32(v: number): number return buffer.readf32(b, 0) end --- merge(scene, keep, opts) -> Merged | nil, message. keep(name) says which attributes to carry (POSITION always). --- opts.triangulate fan-triangulates polygons (faces of fewer than 3 vertices are dropped then). function Flatten.merge(scene: any, keep: (string) -> boolean, opts: { triangulate: boolean? }?): (Merged?, string?) if type(scene) ~= "table" then return nil, "not a scene" @@ -378,7 +362,6 @@ function Flatten.merge(scene: any, keep: (string) -> boolean, opts: { triangulat return nil, lerr end local triangulate = opts and opts.triangulate or false - -- the attribute set: union over parts, a type every part agrees on (else f32), the widest component count local types: { [string]: string } = {} local comps: { [string]: number } = {} local used: { Instance } = {} diff --git a/src/Rosetta/codecs/model/Minecraft/Colors.luau b/src/Rosetta/codecs/model/Minecraft/Colors.luau index 1d66576..fbb19f2 100644 --- a/src/Rosetta/codecs/model/Minecraft/Colors.luau +++ b/src/Rosetta/codecs/model/Minecraft/Colors.luau @@ -1,8 +1,6 @@ --!strict --- codecs/model/Minecraft/Colors: the built-in default colour of Minecraft blocks, for showing block grids as coloured --- voxels. Hand-made for this library (approximate average colours picked by eye; no game assets or wiki tables were --- copied): exact block names, then families by dye colour and wood type; codecs/model/Minecraft resolves stairs / --- slabs / walls / ... to their base block and falls back to keywords. Format: name=rrggbb or name=rrggbbaa. +-- codecs/model/Minecraft/Colors: default Minecraft block colours as name=rrggbb or name=rrggbbaa. +-- Hand-picked approximations; no game assets or wiki tables copied. local Colors = {} Colors.BLOCKS = [[ @@ -66,13 +64,11 @@ muddy_mangrove_roots=46413a ochre_froglight=f6e8a6 verdant_froglight=dcf0d6 pear creaking_heart=5a4a3c resin_block=d9661c resin_bricks=ce5a1a ]] --- wool-like colour of each dye, then concrete and terracotta (same order as Colors.DYES) Colors.DYES = { "white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray", "light_gray", "cyan", "purple", "blue", "brown", "green", "red", "black" } Colors.WOOL = "e9ecec f07613 bd44b3 3aafd9 f8c527 70b919 ed8dac 3e4447 8e8e86 158991 792aac 35399d 724728 546d1b a12722 141519" Colors.CONCRETE = "cfd5d6 e06100 a9309f 2389c6 f0af15 5ea818 d5658e 36393d 7d7d73 157788 64209c 2c2e8f 603b1f 495b24 8e2020 080a0f" Colors.TERRACOTTA = "d1b2a1 a15325 95576c 716c89 ba8523 677534 a14e4e 392a23 876a61 575b5b 764656 4a3b5b 4d3323 4c532a 8f3d2e 251610" --- wood types: planks, bark (log / wood), leaves Colors.WOODS = { "oak", "spruce", "birch", "jungle", "acacia", "dark_oak", "mangrove", "cherry", "pale_oak", "bamboo", "crimson", "warped" } Colors.PLANKS = "a2834f 735531 c0af79 a07351 a85a32 432b14 763631 e3b3ad e4d9d3 c1ad50 653147 2b6963" Colors.BARK = "6d5533 3a2510 d8d7d2 55441a 676157 3e2f17 543a26 371b22 524a46 7f9030 5c1919 3a3a4d" diff --git a/src/Rosetta/codecs/model/Minecraft/Legacy.luau b/src/Rosetta/codecs/model/Minecraft/Legacy.luau index 51f834d..6c66bb1 100644 --- a/src/Rosetta/codecs/model/Minecraft/Legacy.luau +++ b/src/Rosetta/codecs/model/Minecraft/Legacy.luau @@ -1,8 +1,6 @@ --!strict --- codecs/model/Minecraft/Legacy: numeric block ids of Minecraft before 1.13 (the .schematic format, Anvil chunks with --- Blocks / Data arrays), from the Minecraft wiki "Java Edition data values/Pre-flattening" page (facts, not code): --- the 1.12 name of every id, and how the data value picks a variant for the blocks whose colour or wood depends on it --- (the modern name of that variant: wool 14 -> red_wool, planks 2 -> birch_planks). +-- codecs/model/Minecraft/Legacy: pre-1.13 numeric block ids and their data-value variants. +-- From the Minecraft wiki "Java Edition data values/Pre-flattening" (facts, not code). local Legacy = {} local function words(s: string): { string } @@ -46,8 +44,7 @@ gray_glazed_terracotta silver_glazed_terracotta cyan_glazed_terracotta purple_gl blue_glazed_terracotta brown_glazed_terracotta green_glazed_terracotta red_glazed_terracotta black_glazed_terracotta concrete concrete_powder - - structure_block]]) --- legacy names whose modern name differs (data value not involved; only one-to-one renames, so the way back is exact: --- lit_furnace, powered_repeater, ... keep their legacy names) +-- one-to-one renames only, so the way back is exact (lit_furnace, powered_repeater, ... keep their legacy names) Legacy.RENAMED = { grass = "grass_block", brick_block = "bricks", stonebrick = "stone_bricks", hardened_clay = "terracotta", melon_block = "melon", lit_pumpkin = "jack_o_lantern", slime = "slime_block", magma = "magma_block", diff --git a/src/Rosetta/codecs/model/Minecraft/Packed.luau b/src/Rosetta/codecs/model/Minecraft/Packed.luau index 75cbf83..143b6a3 100644 --- a/src/Rosetta/codecs/model/Minecraft/Packed.luau +++ b/src/Rosetta/codecs/model/Minecraft/Packed.luau @@ -1,18 +1,15 @@ --!strict --!native --!optimize 2 --- codecs/model/Minecraft/Packed: Minecraft's packed index arrays. New code, from the Minecraft wiki "Chunk format" and --- the Sponge / Litematica schematic specs: long arrays (little-endian int64s as codecs/text/Nbt keeps them) holding --- bits-wide indices either spanning long boundaries (Litematica, chunks before 1.16) or not (chunks since 1.16: --- floor(64 / bits) per long, the rest padding), and the varint byte arrays of Sponge schematics. Indices are written --- to / read from u16 little-endian buffers. Every access is bounds-checked first; never throws. +-- codecs/model/Minecraft/Packed: Minecraft's packed index arrays. New code. +-- Minecraft wiki "Chunk format", Sponge / Litematica schematic specs: little-endian int64 longs of bits-wide indices, +-- spanning long boundaries (Litematica, chunks before 1.16) or floor(64 / bits) per long plus padding (since 1.16). local Packed = {} local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32 local writeu8, writeu16 = buffer.writeu8, buffer.writeu16 local extract, band, rshift, lshift, bor = bit32.extract, bit32.band, bit32.rshift, bit32.lshift, bit32.bor --- longsNeeded(count, bits, spanning) -> the number of longs a packed array of count indices takes function Packed.longsNeeded(count: number, bits: number, spanning: boolean): number if spanning then return (count * bits + 63) // 64 @@ -21,8 +18,6 @@ function Packed.longsNeeded(count: number, bits: number, spanning: boolean): num return (count + per - 1) // per end --- unpack(longs, bits, count, spanning, out, max) -> true | false, message: count indices into out (u16 LE, from byte --- 0); an index >= max is an error. bits 1 .. 16. function Packed.unpack(longs: buffer, bits: number, count: number, spanning: boolean, out: buffer, max: number): (boolean, string?) if bits < 1 or bits > 16 then return false, "unsupported: " .. bits .. "-bit packed indices" @@ -34,7 +29,6 @@ function Packed.unpack(longs: buffer, bits: number, count: number, spanning: boo if buffer.len(out) < count * 2 then return false, "output too small" end - -- a copy with 4 bytes of padding, so every 32-bit read stays in range local n = need * 8 local src = buffer.create(n + 4) buffer.copy(src, 0, longs, 0, n) @@ -72,7 +66,6 @@ function Packed.unpack(longs: buffer, bits: number, count: number, spanning: boo return true, nil end --- pack(indices, count, bits, spanning) -> longs buffer (little-endian int64s): the inverse of unpack function Packed.pack(indices: buffer, count: number, bits: number, spanning: boolean): buffer local need = Packed.longsNeeded(count, bits, spanning) local out = buffer.create(need * 8 + 4) @@ -82,7 +75,6 @@ function Packed.pack(indices: buffer, count: number, bits: number, spanning: boo local p = if spanning then i * bits else (i // per) * 64 + (i % per) * bits local at = rshift(p, 3) local sh = band(p, 7) - -- OR the value in byte by byte (up to 3 bytes for 16 bits at a shift of 7) local x = lshift(v, sh) for k = 0, 2 do local bits8 = band(rshift(x, k * 8), 0xff) @@ -96,7 +88,6 @@ function Packed.pack(indices: buffer, count: number, bits: number, spanning: boo return res end --- bitsFor(n, min) -> bits for indices 0 .. n - 1 (at least min) function Packed.bitsFor(n: number, min: number): number local b = min while lshift(1, b) < n and b < 31 do @@ -105,8 +96,7 @@ function Packed.bitsFor(n: number, min: number): number return b end --- varints(src, offset, length, count, out, max) -> true | false, message: count unsigned LEB128 varints (Sponge --- BlockData) into out (u16 LE) +-- Sponge BlockData: unsigned LEB128 varints function Packed.varints(src: buffer, offset: number, length: number, count: number, out: buffer, max: number): (boolean, string?) if buffer.len(out) < count * 2 or offset + length > buffer.len(src) then return false, "bad varint array arguments" @@ -137,7 +127,6 @@ function Packed.varints(src: buffer, offset: number, length: number, count: numb return true, nil end --- toVarints(indices, count) -> buffer: count u16 indices as unsigned LEB128 varints function Packed.toVarints(indices: buffer, count: number): buffer local out = buffer.create(count * 3) local p = 0 @@ -156,8 +145,7 @@ function Packed.toVarints(indices: buffer, count: number): buffer return res end --- nibble(src, offset, i, highFirst) -> the 4-bit value i of a nibble array (Minecraft: low nibble first; WorldEdit's --- AddBlocks: high nibble first) +-- nibble arrays: Minecraft low nibble first; WorldEdit AddBlocks high nibble first function Packed.nibble(src: buffer, offset: number, i: number, highFirst: boolean): number local b = readu8(src, offset + rshift(i, 1)) local odd = band(i, 1) == 1 @@ -167,7 +155,6 @@ function Packed.nibble(src: buffer, offset: number, i: number, highFirst: boolea return rshift(b, 4) end --- setNibble(dst, offset, i, v, highFirst) function Packed.setNibble(dst: buffer, offset: number, i: number, v: number, highFirst: boolean) local at = offset + rshift(i, 1) local b = readu8(dst, at) @@ -179,9 +166,7 @@ function Packed.setNibble(dst: buffer, offset: number, i: number, v: number, hig end end --- fromYzx(src, sx, sy, sz, dst?, ox?, oy?, oz?, dsx?, dsy?) -> dst: u16 cells in Minecraft's order (x fastest, then --- z, then y: schematics, chunk sections) to Types.Voxels order (x, then y, then z), into dst (default a new --- sx * sy * sz grid) at cell offset (ox, oy, oz) of a dsx * dsy * ... grid. The caller checks the ranges. +-- Minecraft order: x fastest, then z, then y (schematics, chunk sections) function Packed.fromYzx(src: buffer, sx: number, sy: number, sz: number, dst: buffer?, ox: number?, oy: number?, oz: number?, dsx: number?, dsy: number?): buffer local out = dst or buffer.create(sx * sy * sz * 2) local bx, by, bz = ox or 0, oy or 0, oz or 0 @@ -200,7 +185,6 @@ function Packed.fromYzx(src: buffer, sx: number, sy: number, sz: number, dst: bu return out end --- toYzx(src, sx, sy, sz) -> buffer: Types.Voxels order to Minecraft's (the inverse of fromYzx) function Packed.toYzx(src: buffer, sx: number, sy: number, sz: number): buffer local out = buffer.create(sx * sy * sz * 2) local i = 0 diff --git a/src/Rosetta/codecs/model/Minecraft/init.luau b/src/Rosetta/codecs/model/Minecraft/init.luau index 06d1924..4182d8f 100644 --- a/src/Rosetta/codecs/model/Minecraft/init.luau +++ b/src/Rosetta/codecs/model/Minecraft/init.luau @@ -1,16 +1,5 @@ --!strict -- codecs/model/Minecraft: what Minecraft's voxel formats share (model/schematic, model/mca). New code. --- Block states ("minecraft:oak_stairs[facing=east,half=bottom]": parse / format / NBT compound form), the default --- block colour table (codecs/model/Minecraft/Colors, hand-made) with fallbacks by family, the pre-1.13 numeric ids --- (codecs/model/Minecraft/Legacy), packed index arrays (codecs/model/Minecraft/Packed), and the bridge between block --- grids and Types.Voxels: voxels.blocks holds the exact states (u16 indices into a state palette), voxels.data / --- palette their colours; writing a grid without blocks picks the block nearest in colour for each palette colour. --- --- local Mc = require("@rosetta/codecs/model/Minecraft") --- local name, props = Mc.parseState("minecraft:oak_log[axis=y]") -- "minecraft:oak_log", { { "axis", "y" } } --- local rgba = Mc.color("minecraft:red_wool") -- { r, g, b, a } | nil for air --- local v = Mc.voxels(sx, sy, sz, states, indices) -- a Types.Voxels with .blocks --- local states, indices = Mc.blocksOf(v) -- back (or chosen by colour) local Types = require("@rosetta/Types") local Nbt = require("@rosetta/codecs/text/Nbt") local Colors = require("@rosetta/codecs/model/Minecraft/Colors") @@ -22,8 +11,6 @@ local Minecraft = {} Minecraft.Packed = Packed Minecraft.Legacy = Legacy --- ------------------------------------------------------------------------------------------------ block states --- parseState(s) -> name (namespace added when missing), props { { key, value } } in their order function Minecraft.parseState(s: string): (string, { { string } }) local name, rest = string.match(s, "^%s*([^%[%s]*)%s*(.*)$") local n = name or "" @@ -43,7 +30,6 @@ function Minecraft.parseState(s: string): (string, { { string } }) return n, props end --- stateString(name, props?) -> "name[k=v,...]" (props { { k, v } } in order, or a map: keys sorted) function Minecraft.stateString(name: string, props: { any }?): string if not props or next(props) == nil then return name @@ -61,7 +47,6 @@ function Minecraft.stateString(name: string, props: { any }?): string return name .. "[" .. table.concat(parts, ",") .. "]" end --- stateFromNbt(compound) -> the state string of a palette entry { Name, Properties? } (litematic, chunk sections) function Minecraft.stateFromNbt(c: any): string? if type(c) ~= "table" or type(c.Name) ~= "string" then return nil @@ -76,7 +61,6 @@ function Minecraft.stateFromNbt(c: any): string? return Minecraft.stateString(c.Name, props) end --- stateToNbt(state) -> { Name, Properties? } (a Types.object; Properties in the state's order) function Minecraft.stateToNbt(s: string): { [string]: any } local name, props = Minecraft.parseState(s) local c = Types.object({ Name = name }, { "Name" }) @@ -91,19 +75,16 @@ function Minecraft.stateToNbt(s: string): { [string]: any } return c end --- baseName(state) -> the name without namespace and properties ("minecraft:oak_log[axis=y]" -> "oak_log") function Minecraft.baseName(s: string): string local name = string.match(s, "^%s*([^%[%s]*)") or "" return string.match(name, ":(.*)$") or name end local AIR = { air = true, cave_air = true, void_air = true, structure_void = true, light = true, barrier = true, moving_piston = true } --- isAir(state) -> true for blocks that are not drawn (air, cave_air, void_air, structure_void, light, barrier) function Minecraft.isAir(s: string): boolean return AIR[Minecraft.baseName(s)] == true end --- ------------------------------------------------------------------------------------------------ colours local function hex(h: string): { number } local c = { tonumber(string.sub(h, 1, 2), 16) or 0, tonumber(string.sub(h, 3, 4), 16) or 0, tonumber(string.sub(h, 5, 6), 16) or 0, 255 } if #h >= 8 then @@ -259,7 +240,6 @@ resolve = function(n: string, depth: number): { number }? end local cache: { [string]: { number } | false } = {} --- color(state) -> { r, g, b, a } (0..255) | nil for air-like blocks: the default colour table, families, keywords function Minecraft.color(s: string): { number }? local hit = cache[s] if hit ~= nil then @@ -269,7 +249,6 @@ function Minecraft.color(s: string): { number }? local n = string.match(name, ":(.*)$") or name local res: { number }? = nil if not AIR[n] then - -- pre-1.13 names whose data value picks the variant local variants = Legacy.VARIANTS[n] or (if n == "double_wooden_slab" then Legacy.VARIANTS.planks else nil) if variants then local data = 0 @@ -287,7 +266,6 @@ function Minecraft.color(s: string): { number }? return res end --- ------------------------------------------------------------------------------------------------ legacy ids local REVERSE: { [string]: { number } }? = nil local function reverse(): { [string]: { number } } if REVERSE then @@ -319,8 +297,7 @@ local function reverse(): { [string]: { number } } return r end --- legacyState(id, data) -> the state string for a pre-1.13 block (variant names where the data value picks one, the --- rest of the data value kept as [data=N] so legacyId gives it back exactly) +-- the rest of the data value stays as [data=N], so legacyId gives it back exactly function Minecraft.legacyState(id: number, data: number): string local n = Legacy.NAMES[id + 1] if n == nil or n == "-" then @@ -337,8 +314,6 @@ function Minecraft.legacyState(id: number, data: number): string return "minecraft:" .. (Legacy.RENAMED[n] or n) .. (if data ~= 0 then "[data=" .. data .. "]" else "") end --- legacyId(state) -> id, data | nil: the inverse of legacyState (modern names that exist before 1.13 too; their --- properties are not converted to data values) function Minecraft.legacyId(s: string): (number?, number?) local name, props = Minecraft.parseState(s) local n = string.match(name, ":(.*)$") or name @@ -363,10 +338,6 @@ function Minecraft.legacyId(s: string): (number?, number?) return id, data end --- ------------------------------------------------------------------------------------------------ voxels --- voxels(sx, sy, sz, states, indices, opts?) -> Types.Voxels: indices (u16 LE per cell in Voxels order: x fastest, --- then y, then z) into states; data / palette from the block colours (air -> 0; up to 255 colours, more merge into --- the nearest one) function Minecraft.voxels(sx: number, sy: number, sz: number, states: { string }, indices: buffer): Types.Voxels local v = Types.Voxels.new(sx, sy, sz) local lut = buffer.create(#states) @@ -409,7 +380,6 @@ function Minecraft.voxels(sx: number, sy: number, sz: number, states: { string } return v end --- the blocks a colour grid is written with: full blocks of distinct colours (and stained glass for translucent ones) local CANDIDATES: { { any } }? = nil local function candidates(): { { any } } if CANDIDATES then @@ -434,7 +404,6 @@ local function candidates(): { { any } } return out end --- nearestBlock(rgba) -> the block state whose default colour is nearest (translucent colours -> stained glass) function Minecraft.nearestBlock(c: { number }): string local a = c[4] or 255 if a < 200 then @@ -459,8 +428,6 @@ function Minecraft.nearestBlock(c: { number }): string return best end --- blocksOf(voxels) -> states, indices (u16 LE per cell): voxels.blocks when present (checked), else a block per --- palette colour (nearestBlock; cell 0 -> "minecraft:air" at index 0) | nil, message function Minecraft.blocksOf(v: Types.Voxels): ({ string }?, any) local n = v.size[1] * v.size[2] * v.size[3] local b = v.blocks @@ -497,9 +464,8 @@ function Minecraft.blocksOf(v: Types.Voxels): ({ string }?, any) return states, out end --- ------------------------------------------------------------------------------------------------ block entities --- Block entity records in one shape, { pos = { x, y, z }, id, data } (Sponge v3's), from / to the flat --- { x, y, z, id, ... } of MCEdit, Litematica and chunks, and Sponge v1 / v2's { Pos, Id, ... }. +-- block entities: Sponge v3 { pos = { x, y, z }, id, data } <-> flat { x, y, z, id, ... } (MCEdit, Litematica, +-- chunks) / Sponge v1 / v2 { Pos, Id, ... } local function int(v: any): number? local n = Nbt.number(v) if n == nil or n ~= n or n % 1 ~= 0 then @@ -519,8 +485,8 @@ local function ints(v: any): { number }? end return nil end -Minecraft.int = int -- the integer value of an NBT number | nil -Minecraft.ints = ints -- the numbers of an intArray or a list | nil +Minecraft.int = int +Minecraft.ints = ints local function rest(c: any, skip: { [string]: boolean }): { [string]: any } local out, keys = {}, {} @@ -536,8 +502,6 @@ end local FLAT_SKIP = { x = true, y = true, z = true, id = true } local POS_SKIP = { Pos = true, Id = true } --- blockEntity(c, style) -> the common shape of one record: style "flat" (MCEdit, Litematica), "pos" (Sponge v1 / v2), --- "data" (Sponge v3) function Minecraft.blockEntity(c: any, style: string): any if type(c) ~= "table" or Nbt.isTag(c) then return nil @@ -550,7 +514,6 @@ function Minecraft.blockEntity(c: any, style: string): any return { pos = { p[1] or 0, p[2] or 0, p[3] or 0 }, id = if type(c.Id) == "string" then c.Id else nil, data = data } end --- flatBlockEntity(be, style) -> the record in a flavour's shape (the inverse of blockEntity) function Minecraft.flatBlockEntity(be: any, style: string): any local o = Types.object() local data = if type(be.data) == "table" then be.data else Types.object() diff --git a/src/Rosetta/codecs/model/Polygon.luau b/src/Rosetta/codecs/model/Polygon.luau index 7fc317e..c9a1221 100644 --- a/src/Rosetta/codecs/model/Polygon.luau +++ b/src/Rosetta/codecs/model/Polygon.luau @@ -1,16 +1,6 @@ --!strict --- codecs/model/Polygon: 2D polygons with holes to triangles, for formats that store regions as outlines (Doom map --- sectors, ...). Loops are classified by nesting (a loop inside an odd number of other loops is a hole of the --- smallest loop around it), oriented, each hole bridged to its outer loop at a mutually visible vertex, then the --- result is ear-clipped (reflex-vertex test; a polygon that never yields a clean ear clips its least bad corner so --- every input terminates). New in rosetta, after the classic "ear clipping with hole bridging" method --- (D. Eberly, Triangulation by Ear Clipping); no code taken. --- --- local tris = Polygon.triangulate({ { 0, 0, 10, 0, 10, 10, 0, 10 }, { 2, 2, 4, 2, 4, 4, 2, 4 } }) --- -- tris = { loop, index, loop, index, loop, index, ... }: three corners per triangle, each a (loop, vertex) pair --- -- (1-based), counter-clockwise --- --- Never throws; degenerate loops (fewer than 3 points, zero area) are ignored. +-- codecs/model/Polygon: 2D polygons with holes to triangles by hole bridging and ear clipping. New code. +-- After D. Eberly, "Triangulation by Ear Clipping" (no code taken). local Polygon = {} type Pt = { x: number, y: number, loop: number, index: number } @@ -43,7 +33,6 @@ local function cross(o: Pt, a: Pt, b: Pt): number return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x) end --- segments p1-p2 and q1-q2 cross properly (touching at an endpoint does not count) local function crosses(p1: Pt, p2: Pt, q1: Pt, q2: Pt): boolean if (p1.x == q1.x and p1.y == q1.y) or (p1.x == q2.x and p1.y == q2.y) or (p2.x == q1.x and p2.y == q1.y) or (p2.x == q2.x and p2.y == q2.y) then return false @@ -65,8 +54,6 @@ local function visible(m: Pt, v: Pt, rings: { { Pt } }): boolean return true end --- splice hole h into ring outer (both oriented: outer counter-clockwise, hole clockwise) at mutually visible --- vertices; others = every ring the bridge must not cross local function bridge(outer: { Pt }, h: { Pt }, others: { { Pt } }): { Pt } local mi = 1 for i, p in h do @@ -110,7 +97,6 @@ local function inTri(a: Pt, b: Pt, c: Pt, p: Pt): boolean return cross(a, b, p) >= 0 and cross(b, c, p) >= 0 and cross(c, a, p) >= 0 end --- ear clipping of one counter-clockwise ring local function clip(ring: { Pt }, out: { number }) local pts = table.clone(ring) local guard = #pts * #pts + 16 @@ -159,7 +145,6 @@ local function clip(ring: { Pt }, out: { number }) end end --- triangulate(loops) -> { loop, index, ... }: loops[i] = { x1, y1, x2, y2, ... } (closed implicitly) function Polygon.triangulate(loops: { { number } }): { number } local rings: { { Pt } } = {} local areas: { number } = {} @@ -184,7 +169,6 @@ function Polygon.triangulate(loops: { { number } }): { number } end end end - -- nesting: the parent of a ring is the smallest ring containing its first point local n = #rings local depth, parent = table.create(n, 0), table.create(n, 0) for i = 1, n do diff --git a/src/Rosetta/codecs/model/Rbx/Binary.luau b/src/Rosetta/codecs/model/Rbx/Binary.luau index b90951b..391be6c 100644 --- a/src/Rosetta/codecs/model/Rbx/Binary.luau +++ b/src/Rosetta/codecs/model/Rbx/Binary.luau @@ -1,19 +1,8 @@ --!strict --!native --!optimize 2 --- codecs/model/Rbx/Binary: the property columns of the Roblox binary format (rbx-dom docs/binary.md): one PROP chunk --- holds a property's values for every instance of a class, by type id, with the format's array transforms: byte --- interleaving (all first bytes, then all second bytes, ...), big-endian integers, zigzag signed integers, "rotated" --- floats (sign bit moved to bit 0), delta-coded referents, and CFrame rotation ids (codecs/model/Rbx). Never throws. --- --- local values, pEnd = Binary.decode(typeId, buf, p, limit, n, ctx) -- n plain values (codecs/model/Rbx forms) --- local err = Binary.encode(typeId, values, n, writer, ctx) -- nil, or a message --- Binary.readRefs(buf, p, limit, n) / Binary.writeRefs(writer, refs) -- referent arrays (INST, PRNT) --- --- ctx: { ref = function(referent) -> Instance? (decode), refOf = function(Instance?) -> referent (-1 = none), --- shared = { string } (SSTR entries, 1-based, decode), sharedIndex = function(string) -> 0-based index (encode) }. --- decode returns nil, message on bad data ("truncated", "corrupt: ...", "unknown" for a type id it does not know / --- a layout it cannot read, which the format keeps raw). +-- codecs/model/Rbx/Binary: the property column codecs of the Roblox binary format (rbx-dom docs/binary.md). +-- PROP columns: byte-interleaved big-endian values, zigzag signed integers, rotated floats, delta-coded referents. local Rbx = require("@rosetta/codecs/model/Rbx") local Bytes = require("@rosetta/core/Bytes") @@ -28,7 +17,6 @@ local floor = math.floor local scratch = buffer.create(8) local TWO32 = 4294967296 --- ------------------------------------------------------------------------------------------------ transforms -- the rotated float encoding: bits rotated left by one (sign in bit 0) local function unrotate(x: number): number writeu32(scratch, 0, x // 2 + (x % 2) * 2147483648) @@ -47,7 +35,6 @@ local function zigzag32(v: number): number return (if v >= 0 then v * 2 else -v * 2 - 1) % TWO32 end --- n big-endian u32 values interleaved at p (4n bytes) local function u32s(b: buffer, p: number, n: number): { number } local out = table.create(n, 0) local n2, n3 = n * 2, n * 3 @@ -70,7 +57,6 @@ local function f32s(b: buffer, p: number, n: number): { number } end return out end --- n zigzag i64 values (8n interleaved bytes), as doubles local function i64s(b: buffer, p: number, n: number): { number } local out = table.create(n, 0) for i = 0, n - 1 do @@ -82,7 +68,6 @@ local function i64s(b: buffer, p: number, n: number): { number } return out end --- writers: n values interleaved as big-endian u32 / zigzag i32 / rotated f32 / zigzag i64 local function putU32s(w: Bytes.Writer, vals: { number }) local n = #vals local p = w:reserve(4 * n) @@ -153,7 +138,6 @@ function Binary.writeRefs(w: Bytes.Writer, refs: { number }) putI32s(w, d) end --- ------------------------------------------------------------------------------------------------ decode export type Ctx = { ref: ((number) -> any)?, refOf: ((any) -> number)?, @@ -161,7 +145,6 @@ export type Ctx = { sharedIndex: ((string) -> number)?, } --- a length-prefixed string at p: string, next p (nil when it runs past limit) local function str(b: buffer, p: number, limit: number): (string?, number) if p + 4 > limit then return nil, p @@ -211,7 +194,7 @@ local function cframes(b: buffer, p: number, limit: number, n: number): ({ any } return out, p + 12 * n end -local FIXED: { [number]: number } = { -- bytes per value of the fixed-size types +local FIXED: { [number]: number } = { [0x02] = 1, [0x03] = 4, [0x04] = 4, @@ -238,7 +221,6 @@ local FIXED: { [number]: number } = { -- bytes per value of the fixed-size types [0x21] = 8, } --- decode(typeId, b, p, limit, n, ctx) -> n values, the end offset | nil, message function Binary.decode(t: number, b: buffer, p: number, limit: number, n: number, ctx: Ctx): ({ any }?, any) if limit > buffer.len(b) or p < 0 or n < 0 then return nil, "corrupt: bad ranges" @@ -531,11 +513,9 @@ function Binary.decode(t: number, b: buffer, p: number, limit: number, n: number return nil, "unknown" end --- ------------------------------------------------------------------------------------------------ encode local function num(v: any): number return if type(v) == "number" and v == v then v else 0 end --- column c of n array values (missing components 0) local function column(vals: { any }, n: number, c: number): { number } local out = table.create(n, 0) for i = 1, n do @@ -571,8 +551,6 @@ local function hexByte(s: string, i: number): number return tonumber(string.sub(s, 2 * i - 1, 2 * i), 16) or 0 end --- encode(typeId, values, n, w, ctx) -> nil | message: values[1 .. n] in the codecs/model/Rbx forms (nil entries are --- the type's none / default) function Binary.encode(t: number, vals: { any }, n: number, w: Bytes.Writer, ctx: Ctx): string? if t == 0x01 or t == 0x1D then for i = 1, n do diff --git a/src/Rosetta/codecs/model/Rbx/init.luau b/src/Rosetta/codecs/model/Rbx/init.luau index ac3142c..4180477 100644 --- a/src/Rosetta/codecs/model/Rbx/init.luau +++ b/src/Rosetta/codecs/model/Rbx/init.luau @@ -1,40 +1,9 @@ --!strict --- codecs/model/Rbx: the Roblox instance tree every Roblox file format maps to (model/rbxm binary rbxm / rbxl, --- model/rbxmx XML rbxmx / rbxlx), the typed property values, the CFrame rotation IDs, and (codecs/model/Rbx/Binary) the --- binary format's property column codecs. Shared here because a format cannot require another one. Written from the --- rbx-dom format notes (docs/binary.md, docs/xml.md) and checked against rbx-dom through rojo / lune. A file library, --- not a Roblox runtime: nothing here creates Instances; a Roblox game reads the tree itself. --- --- local tree = Rbx.tree() -- { kind = "rbxtree", roots = {}, place = false, ... } --- local part = Rbx.instance("Part", "Floor") -- { className, name, properties = {}, children = {} } --- Rbx.set(part, "Size", "Vector3", { 64, 1, 64 }) -- properties.Size = { type = "Vector3", value = {...} } --- Rbx.add(tree, part) -- a root; Rbx.add(parentInstance, child) nests --- for inst, depth in Rbx.descendants(tree) do ... end --- --- Property values are { type = , value = } with these value forms (arrays follow the Roblox constructor --- argument order, so Vector3.new(table.unpack(v.value)) / CFrame.new(table.unpack(v.value)) rebuild them in Roblox): --- String, BinaryString, ProtectedString, ContentId, Bytecode string (bytes) --- SharedString string (the content; writers deduplicate) --- Bool boolean --- Int32, Int64, Float32, Float64 number (Int64 exact to 2^53) --- Enum, BrickColor, SecurityCapabilities number --- Faces number: bits Right 1, Top 2, Back 4, Left 8, Bottom 16, Front 32 --- Axes number: bits X 1, Y 2, Z 4 --- UDim { scale, offset } UDim2 { xScale, xOffset, yScale, yOffset } NumberRange { min, max } --- Vector2 / Vector2int16 { x, y } Vector3 / Vector3int16 { x, y, z } Color3 { r, g, b } (0..1) --- Color3uint8 { r, g, b } (0..255) Rect { minX, minY, maxX, maxY } Ray { ox, oy, oz, dx, dy, dz } --- CFrame { x, y, z, r00, r01, r02, r10, r11, r12, r20, r21, r22 } OptionalCFrame: the same, or nil (none) --- NumberSequence { { time, value, envelope } ... } ColorSequence { { time, r, g, b, envelope } ... } --- PhysicalProperties nil (default) | { density, friction, elasticity, frictionWeight, elasticityWeight, --- acousticAbsorption } (decoders fill acousticAbsorption = 1 when the file leaves it out) --- Ref an Instance of the tree, or nil --- UniqueId 32 hex digits: random (16), time (8), index (8) --- Font { family, weight (100..900), style ("Normal" | "Italic"), cachedFaceId? } --- Content nil (none) | string (a URI) | an Instance (object) --- Raw a binary property of a type this library does not know: { typeId, data (the class's whole column), --- index, count }; written back verbatim while the class keeps the same instances in the same order --- XmlRaw an XML property of an unknown type: value = the element (codecs/text/Xml node), written back as it is --- Name is not a property here: it is inst.name. Never throws. +-- codecs/model/Rbx: the Roblox instance tree and property values shared by model/rbxm and model/rbxmx. +-- Written from the rbx-dom format notes (docs/binary.md, docs/xml.md); checked against rbx-dom through rojo / lune. +-- Faces: bits Right 1, Top 2, Back 4, Left 8, Bottom 16, Front 32 +-- Axes: bits X 1, Y 2, Z 4 +-- UniqueId: 32 hex digits: random (16), time (8), index (8) local Rbx = {} @@ -44,20 +13,19 @@ export type Instance = { name: string, properties: { [string]: Value }, children: { Instance }, - parent: Instance?, -- nil for roots - referent: string?, -- the file's referent (XML "RBX..." id, binary index) when read; writers make their own + parent: Instance?, + referent: string?, service: boolean?, -- a service (binary INST object format 1; rbxl roots) } export type Tree = { kind: "rbxtree", roots: { Instance }, - place: boolean, -- a place (rbxl / rbxlx: the roots are services under the DataModel) or a model + place: boolean, metadata: { [string]: string }, -- binary META / XML entries (ExplicitAutoJoints, ...) - extra: { any }, -- unknown binary chunks { name, data } / unknown top-level XML elements, written back + extra: { any }, meta: { source: { format: string, [string]: any }?, [string]: any }, } --- ------------------------------------------------------------------------------------------------ tree function Rbx.tree(place: boolean?): Tree return { kind = "rbxtree", roots = {}, place = place == true, metadata = {}, extra = {}, meta = {} } end @@ -66,7 +34,6 @@ function Rbx.instance(className: string, name: string?): Instance return { className = className, name = name or className, properties = {}, children = {} } end --- add(parent, child) -> child: parent is a Tree (child becomes a root) or an Instance function Rbx.add(parent: any, child: Instance): Instance if parent.kind == "rbxtree" then child.parent = nil @@ -78,19 +45,15 @@ function Rbx.add(parent: any, child: Instance): Instance return child end --- set(inst, name, type, value): a property (value nil = the type's nil form: Ref none, OptionalCFrame none, ...) function Rbx.set(inst: Instance, name: string, typ: string, value: any) inst.properties[name] = { type = typ, value = value } end --- get(inst, name) -> the property's value (not the Value table), nil when absent function Rbx.get(inst: Instance, name: string): any local v = inst.properties[name] return if v then v.value else nil end --- descendants(treeOrInstance) -> iterator over (instance, depth) in depth-first order (roots / the instance's children --- at depth 1) function Rbx.descendants(root: any): () -> (Instance?, number?) local stack: { any } = {} local list = if root.kind == "rbxtree" then root.roots else root.children @@ -110,7 +73,6 @@ function Rbx.descendants(root: any): () -> (Instance?, number?) end end --- list(tree) -> every instance, depth first function Rbx.list(tree: any): { Instance } local out = {} for inst in Rbx.descendants(tree) do @@ -119,7 +81,6 @@ function Rbx.list(tree: any): { Instance } return out end --- find(treeOrInstance, path) -> the instance at a "/"-separated path of names ("Workspace/Baseplate"), or nil function Rbx.find(root: any, path: string): Instance? local cur: any = root for part in string.gmatch(path, "[^/]+") do @@ -139,7 +100,6 @@ function Rbx.find(root: any, path: string): Instance? return if cur.kind == "rbxtree" then nil else cur end --- fullName(inst) -> "Workspace.Model.Part" (names joined up to the root) function Rbx.fullName(inst: Instance): string local parts = {} local cur: Instance? = inst @@ -150,12 +110,10 @@ function Rbx.fullName(inst: Instance): string return table.concat(parts, ".") end --- ------------------------------------------------------------------------------------------------ CFrame rotation ids -- The binary format stores axis-aligned rotations as one byte: id = 6 * n(RightVector) + n(UpVector) + 1, where n is -- the NormalId of a unit axis (+X 0, +Y 1, +Z 2, -X 3, -Y 4, -Z 5) and the third column is their cross product. local AXES = { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 }, { -1, 0, 0 }, { 0, -1, 0 }, { 0, 0, -1 } } --- the rotation of an id as { r00 .. r22 } (row major), or nil for an id that is not a rotation local ROTATIONS: { [number]: { number } } = {} for a = 0, 5 do for b = 0, 5 do @@ -178,7 +136,6 @@ local function axisIndex(x: number, y: number, z: number): number? return nil end --- rotationId(cf) -> the id of the CFrame's rotation (cf = { x, y, z, r00 .. r22 }), or 0 when it is not axis aligned function Rbx.rotationId(cf: { number }): number local a = axisIndex(cf[4], cf[7], cf[10]) local b = axisIndex(cf[5], cf[8], cf[11]) @@ -193,7 +150,6 @@ function Rbx.rotationId(cf: { number }): number return id end --- ------------------------------------------------------------------------------------------------ values -- binary type ids (rbx-dom docs/binary.md) by type name, and back Rbx.TYPE_IDS = table.freeze({ String = 0x01, @@ -241,8 +197,7 @@ for name, id in Rbx.TYPE_IDS do end Rbx.TYPE_NAMES = table.freeze(NAMES) --- the value a binary writer uses for an instance without the property (zero / empty / identity; BrickColor 194, the --- Medium stone grey Roblox defaults to; sequences of two keypoints at times 0 and 1) +-- BrickColor 194 (Medium stone grey) is Roblox's default local IDENTITY_CF = { 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1 } function Rbx.default(typ: string): any if typ == "String" or typ == "BinaryString" or typ == "ProtectedString" or typ == "ContentId" or typ == "Bytecode" or typ == "SharedString" then @@ -275,7 +230,6 @@ function Rbx.default(typ: string): any return 0 end --- STRINGS: the string-valued types (one binary type, several XML tags) Rbx.STRINGS = table.freeze({ String = true, BinaryString = true, ProtectedString = true, ContentId = true, Bytecode = true } :: { [string]: boolean }) return Rbx diff --git a/src/Rosetta/codecs/model/Rig.luau b/src/Rosetta/codecs/model/Rig.luau index a05c87c..811f307 100644 --- a/src/Rosetta/codecs/model/Rig.luau +++ b/src/Rosetta/codecs/model/Rig.luau @@ -1,16 +1,5 @@ --!strict --- codecs/model/Rig: the Scene mapping shared by game model formats (MD2 / MD3 / MDL / MD5 / SMD / ...), so each --- format only parses its file: vertex-animation frames as morph targets plus "weights" animations, joint hierarchies --- as Scene nodes plus a Skin (inverse bind matrices), per-vertex joint influences as JOINTS_0 / WEIGHTS_0, and --- keyframed joint TRS tracks as animation channels. New in rosetta. --- --- Rig.morph(prim, frames) -- frames[k] = f32 x3 positions: targets[k] = frame k - base --- Rig.morphAnimation(scene, node, #frames, { { name = "run", first = 41, last = 46, fps = 10 } }, "LINEAR") --- local nodes, skin = Rig.skeleton(scene, joints, "world") -- joints = { { name, parent (0 = root), t, r, s? } } --- prim.attributes.JOINTS_0, prim.attributes.WEIGHTS_0 = Rig.influences(lists) -- lists[v] = { j1, w1, j2, w2, ... } --- Rig.animation(scene, "idle", nodes, times, tracks) -- tracks[j] = { translation = {...}, rotation = {...} } --- --- Frames, joints and tracks come from parsed files: the helpers check every count they rely on and never throw. +-- codecs/model/Rig: the Scene mapping shared by game model formats (MD2 / MD3 / MDL / MD5 / SMD / ...). New code. local Types = require("@rosetta/Types") local Mat4 = require("@rosetta/codecs/model/Mat4") @@ -21,18 +10,14 @@ local readf32, writef32, writeu16 = buffer.readf32, buffer.writef32, buffer.writ export type Joint = { name: string?, - parent: number, -- 1-based index into the joint list, 0 for a root (parents come before their children) + parent: number, translation: { number }, rotation: { number }, -- quaternion x, y, z, w scale: { number }?, } -export type Range = { name: string?, first: number, last: number, fps: number? } -- frames first..last (1-based) -export type Track = { translation: { number }?, rotation: { number }?, scale: { number }? } -- flat, one key per time +export type Range = { name: string?, first: number, last: number, fps: number? } +export type Track = { translation: { number }?, rotation: { number }?, scale: { number }? } --- ------------------------------------------------------------------------------------------------ morph targets --- morph(prim, frames, normals?, base?) -> (): prim.targets[k] = { POSITION = frames[k] - base positions } (and NORMAL --- deltas when normals[k] is given), base = prim.attributes.POSITION (and NORMAL). Every frame buffer must hold as --- many f32 x3 as the base; shorter ones are skipped (false is returned). function Rig.morph(prim: Types.Primitive, frames: { buffer }, normals: { buffer }?): boolean local pos = prim.attributes.POSITION if not pos or pos.type ~= "f32" or pos.components ~= 3 then @@ -70,9 +55,6 @@ function Rig.morph(prim: Types.Primitive, frames: { buffer }, normals: { buffer return ok end --- morphAnimation(scene, node, targets, ranges, interpolation?) -> (): one animation per range, a "weights" channel on --- scene.nodes[node] whose key k (at (k - first) / fps seconds) sets target k to 1 and the others to 0 (LINEAR --- blends neighbouring frames, as the games do; default "LINEAR"). Ranges out of 1..targets are clamped / skipped. function Rig.morphAnimation(scene: Types.Scene, node: number, targets: number, ranges: { Range }, interpolation: string?) for _, rg in ranges do local first, last = math.max(1, math.floor(rg.first)), math.min(targets, math.floor(rg.last)) @@ -101,9 +83,7 @@ function Rig.morphAnimation(scene: Types.Scene, node: number, targets: number, r end end --- normals(pos, count, indices) -> f32 x3 buffer: smooth vertex normals (area-weighted face normals, normalised) of a --- triangle list (indices: 0-based, three per triangle; out-of-range triangles are skipped). For formats whose stored --- normals cannot be used (Quake's precomputed normal table is not redistributable here). +-- Quake's precomputed normal table is not redistributable here function Rig.normals(pos: buffer, count: number, indices: { number }): buffer local out = buffer.create(count * 12) local acc = table.create(count * 3, 0) @@ -134,13 +114,11 @@ function Rig.normals(pos: buffer, count: number, indices: { number }): buffer return out end --- ------------------------------------------------------------------------------------------------ skeletons local function trs(j: Joint): { number } return Mat4.compose(j.translation, j.rotation, j.scale) end --- angles(x, y, z) -> quaternion { x, y, z, w } of the Euler angles in radians applied x first, then y, then z --- (R = Rz * Ry * Rx: the Quake / Half-Life "AngleQuaternion" convention of MDL bones and SMD skeletons) +-- R = Rz * Ry * Rx: the Quake / Half-Life AngleQuaternion convention of MDL bones and SMD skeletons function Rig.angles(x: number, y: number, z: number): { number } local sy, cy = math.sin(z / 2), math.cos(z / 2) local sp, cp = math.sin(y / 2), math.cos(y / 2) @@ -148,10 +126,6 @@ function Rig.angles(x: number, y: number, z: number): { number } return { sr * cp * cy - cr * sp * sy, cr * sp * cy + sr * cp * sy, cr * cp * sy - sr * sp * cy, cr * cp * cy + sr * sp * sy } end --- skeleton(scene, joints, space, root?) -> (joint node indices, skin index, world matrices): one node per joint (TRS relative to its --- parent), parented as listed, roots added to scene.roots (or as children of node `root`); a Skin with the inverse --- bind matrices. space "local": joint TRS are relative to the parent (SMD, MDL); "world": in model space (MD5's --- bind pose), converted to local here. A parent index that does not come earlier makes the joint a root. function Rig.skeleton(scene: Types.Scene, joints: { Joint }, space: "local" | "world", root: number?): ({ number }, number, { { number } }) local n = #joints local world: { { number } } = {} @@ -197,9 +171,6 @@ function Rig.skeleton(scene: Types.Scene, joints: { Joint }, space: "local" | "w return nodes, #scene.skins, world end --- influences(lists) -> JOINTS_0 (u16 x4), WEIGHTS_0 (f32 x4): lists[v] = { joint, weight, joint, weight, ... } with --- 0-based joint indices (into the skin's joints; a joint listed twice adds up); the four largest weights are kept --- and normalised to sum 1. function Rig.influences(lists: { { number } }): (Types.Accessor, Types.Accessor) local n = #lists local jb, wb = buffer.create(n * 8), buffer.create(n * 16) @@ -210,7 +181,7 @@ function Rig.influences(lists: { { number } }): (Types.Accessor, Types.Accessor) if l[k + 1] > 0 then local same = at[l[k]] if same then - same[2] += l[k + 1] -- the same joint twice: one influence + same[2] += l[k + 1] else local e = { l[k], l[k + 1] } at[l[k]] = e @@ -233,7 +204,6 @@ function Rig.influences(lists: { { number } }): (Types.Accessor, Types.Accessor) return Scene.accessor(jb, "u16", 4, n), Scene.accessor(wb, "f32", 4, n) end --- ------------------------------------------------------------------------------------------------ animations local function floats(t: { number }, count: number, comps: number): Types.Accessor? if #t < count * comps then return nil @@ -245,9 +215,6 @@ local function floats(t: { number }, count: number, comps: number): Types.Access return Scene.accessor(b, "f32", comps, count) end --- animation(scene, name, nodes, times, tracks, interpolation?) -> the animation index: tracks[j] (j = index into --- nodes) holds flat translation (x3) / rotation (quaternion x4) / scale (x3) keys, one per time (seconds); tracks --- with too few keys are skipped. Default interpolation "LINEAR". function Rig.animation(scene: Types.Scene, name: string?, nodes: { number }, times: { number }, tracks: { [number]: Track }, interpolation: string?): number local count = #times local input = floats(times, count, 1) diff --git a/src/Rosetta/codecs/model/Sampler.luau b/src/Rosetta/codecs/model/Sampler.luau index 23b8393..4564d5c 100644 --- a/src/Rosetta/codecs/model/Sampler.luau +++ b/src/Rosetta/codecs/model/Sampler.luau @@ -1,15 +1,5 @@ --!strict --- codecs/model/Sampler: evaluates Scene animation channels at any time (STEP, LINEAR with quaternion slerp for --- rotations, CUBICSPLINE Hermite splines as glTF 2.0 defines them; times before the first / after the last key hold --- the end values), and the node poses of an animation at a time, for writers of formats that store sampled frames --- (IQM, MD5, BVH, ...). New in rosetta. --- --- local sample = Sampler.channel(ch) -- nil for an unreadable channel --- local v = sample(0.5) -- { x, y, z } / { x, y, z, w } / the morph weights --- local times = Sampler.times(anim) -- every key time of the animation, sorted, unique --- local pose = Sampler.pose(scene, anim, 0.5) -- pose[node] = { translation?, rotation?, scale?, weights? } --- --- Never throws on bad data: unreadable channels are skipped. +-- codecs/model/Sampler: Scene animation sampling, STEP / LINEAR (slerp) / CUBICSPLINE as in glTF 2.0 animations. New code. local Types = require("@rosetta/Types") local Sampler = {} @@ -42,7 +32,6 @@ local function slerp(a: { number }, b: { number }, s: number): { number } return normalize({ a[1] * wa + bx * wb, a[2] * wa + by * wb, a[3] * wa + bz * wb, a[4] * wa + bw * wb }) end --- channel(ch) -> sample(t) | nil function Sampler.channel(ch: Types.Channel): Sample? local inp, out = ch.input, ch.output if type(inp) ~= "table" or type(out) ~= "table" then @@ -69,7 +58,6 @@ function Sampler.channel(ch: Types.Channel): Sample? times[k] = IN(k - 1, 0) end local oc = out.components - -- element e (0-based, of comps values) of the flat output local function get(e: number): { number } local v = table.create(comps) :: { number } for c = 0, comps - 1 do @@ -78,7 +66,7 @@ function Sampler.channel(ch: Types.Channel): Sample? end return v end - local function value(k: number): { number } -- key k (1-based) + local function value(k: number): { number } return get(if cubic then (k - 1) * 3 + 1 else k - 1) end local rot = ch.path == "rotation" @@ -127,7 +115,6 @@ function Sampler.channel(ch: Types.Channel): Sample? end end --- times(anim) -> every key time, sorted and unique function Sampler.times(anim: Types.Animation): { number } local seen: { [number]: boolean } = {} local out: { number } = {} @@ -148,8 +135,6 @@ function Sampler.times(anim: Types.Animation): { number } return out end --- pose(scene, anim, t, samplers?) -> pose[node] = { [path] = values } for the animated nodes. samplers: a cache table --- (reuse it across calls for the same animation) function Sampler.pose(_scene: Types.Scene, anim: Types.Animation, t: number, samplers: { [any]: any }?): Pose local cache: { [any]: any } = samplers or {} local pose: Pose = {} diff --git a/src/Rosetta/codecs/model/Vrml/Build.luau b/src/Rosetta/codecs/model/Vrml/Build.luau index ed2702c..2180723 100644 --- a/src/Rosetta/codecs/model/Vrml/Build.luau +++ b/src/Rosetta/codecs/model/Vrml/Build.luau @@ -1,16 +1,7 @@ --!strict --- codecs/model/Vrml/Build: the VRML97 / X3D node graph (codecs/model/Vrml/Parse, codecs/model/Vrml/Xml) to a Scene. --- Written from the specifications; no third-party code. Grouping nodes (Group, Transform with center / scaleOrientation, --- Anchor, Billboard, Collision, StaticGroup, Switch whichChoice, LOD first level, CAD and HAnim groups, Inline through --- the fetch callback) become nodes; a Transform is one TRS node (translation T + C, rotation R * SR, scale S) and, when --- it has a center or scale orientation, an inner node (rotation SR^-1, translation SR^-1 * -C) holding the children. --- Shapes become meshes (shared by USE), Appearance / Material / PhysicalMaterial / UnlitMaterial / TwoSidedMaterial --- materials (Phong terms in material.extras.vrml; solid FALSE -> doubleSided), ImageTexture / MovieTexture --- (uri, data through fetch, repeatS / repeatT), PixelTexture (texture.image), TextureTransform (KHR transform: --- translation / scale / rotation; the center in extras); Viewpoint / OrthoViewpoint -> cameras, DirectionalLight / --- PointLight / SpotLight -> lights; ROUTEs from a TimeSensor through Position- / OrientationInterpolators to a --- Transform's translation / rotation / scale -> animations (key times x cycleInterval). Other nodes are counted in --- meta.source.skipped. Never throws: bad data returns nil, message. +-- codecs/model/Vrml/Build: the VRML97 / X3D node graph to a Scene. Written from the specifications; no third-party code. +-- A Transform is one TRS node (translation T + C, rotation R * SR, scale S) plus, when it has a center or scale +-- orientation, an inner node (rotation SR^-1, translation SR^-1 * -C) holding the children. local Types = require("@rosetta/Types") local Mat4 = require("@rosetta/codecs/model/Mat4") local Fields = require("@rosetta/codecs/model/Vrml/Fields") @@ -23,16 +14,15 @@ local nums, num, vec, bool, str, strs, node, nodes = Fields.nums, Fields.num, Fi local deg = math.deg export type Options = Geometry.Options & { - fetch: ((uri: string) -> buffer?)?, -- reads textures and Inline files - load: ((data: buffer) -> (any, string?))?, -- an Inline file's bytes -> its graph - format: string?, -- meta.source.format - maxInline: number?, -- Inline nesting (default 8) + fetch: ((uri: string) -> buffer?)?, + load: ((data: buffer) -> (any, string?))?, + format: string?, + maxInline: number?, } local GROUP = { Group = true, Anchor = true, Billboard = true, Collision = true, StaticGroup = true, CADAssembly = true, CADLayer = true, LayerSet = true, Layer = true, HAnimSegment = true, HAnimSite = true, LOD = true, Switch = true } local TRANSFORM = { Transform = true, CADPart = true, HAnimHumanoid = true, HAnimJoint = true } local CHILDREN = { "children", "skeleton", "segments", "sites", "layers" } --- nodes with nothing to show (not counted as skipped) local QUIET = { WorldInfo = true, NavigationInfo = true, Background = true, TextureBackground = true, Fog = true, TimeSensor = true, PositionInterpolator = true, OrientationInterpolator = true, ScalarInterpolator = true, ColorInterpolator = true, @@ -67,7 +57,6 @@ end local function isIdentityQ(q: { number }): boolean return q[1] == 0 and q[2] == 0 and q[3] == 0 end --- the rotation taking unit vector a onto b local function between(a: { number }, b: { number }): { number } local l = math.sqrt(b[1] * b[1] + b[2] * b[2] + b[3] * b[3]) if l < 1e-12 then @@ -76,7 +65,6 @@ local function between(a: { number }, b: { number }): { number } local bx, by, bz = b[1] / l, b[2] / l, b[3] / l local d = a[1] * bx + a[2] * by + a[3] * bz if d < -0.999999 then - -- opposite: half a turn about any perpendicular axis return if math.abs(a[1]) < 0.9 then { 0, a[3], -a[2], 0 } else { -a[3], 0, a[1], 0 } end local cx, cy, cz = a[2] * bz - a[3] * by, a[3] * bx - a[1] * bz, a[1] * by - a[2] * bx @@ -110,7 +98,6 @@ local function addNode(ctx: Ctx, n: Types.Node, parent: number?): number return i end --- ------------------------------------------------------------------------------------------------ materials local function texture(ctx: Ctx, t: any): number? if not t then return nil @@ -282,7 +269,6 @@ local function material(ctx: Ctx, app: any, solid: boolean): number? return idx end --- ------------------------------------------------------------------------------------------------ nodes local walk: (ctx: Ctx, n: any, parent: number?) -> () local function shape(ctx: Ctx, n: any, parent: number?) @@ -304,7 +290,6 @@ local function shape(ctx: Ctx, n: any, parent: number?) end local count = if prim.indices then prim.indices.count else prim.attributes.POSITION.count if count == 0 then - -- nothing to draw (no valid faces / points) ctx.meshes[n] = false return end @@ -491,11 +476,9 @@ function walk(ctx: Ctx, n: any, parent: number?) ctx.depth -= 1 end --- ------------------------------------------------------------------------------------------------ animation local TARGET = { set_translation = "translation", translation = "translation", set_rotation = "rotation", rotation = "rotation", set_scale = "scale", scale = "scale" } local function animations(ctx: Ctx, routes: { any }) - -- interpolator -> its TimeSensor local timer: { [any]: any } = {} for _, r in routes do if (r.toField == "set_fraction" or r.toField == "fraction") and r.from.type == "TimeSensor" then @@ -564,7 +547,6 @@ local function animations(ctx: Ctx, routes: { any }) end end --- ------------------------------------------------------------------------------------------------ scene function Build.scene(graph: any, opts: Options): (Types.Scene?, string?) local scene = S.new() scene.meta.up = "y" diff --git a/src/Rosetta/codecs/model/Vrml/Fields.luau b/src/Rosetta/codecs/model/Vrml/Fields.luau index c9ec1e2..067c88f 100644 --- a/src/Rosetta/codecs/model/Vrml/Fields.luau +++ b/src/Rosetta/codecs/model/Vrml/Fields.luau @@ -1,13 +1,9 @@ --!strict --- codecs/model/Vrml/Fields: typed reads of node fields for codecs/model/Vrml/Build and Geometry. A classic-encoding --- value is a flat array (numbers, strings, booleans, nodes); an X3D XML value is the raw attribute string, parsed here --- on first use (numbers split on blanks / commas, MFString as quoted strings or one unquoted string, booleans --- true / false). Never throws. +-- codecs/model/Vrml/Fields: typed reads of VRML / X3D node fields (classic arrays or X3D XML attribute strings). local Fields = {} local gmatch, find, sub, byte = string.gmatch, string.find, string.sub, string.byte --- quoted strings of an MFString attribute ("a" "b \"c\""), or the text itself when it is not quoted local function mfString(s: string): { string } local out = {} local p = find(s, "[^%s,]") @@ -43,7 +39,6 @@ local function mfString(s: string): { string } return out end --- nums(node, name) -> the numbers of a field (booleans as 1 / 0), or nil when absent function Fields.nums(node: any, name: string): { number }? local v = node.fields[name] if v == nil then @@ -93,7 +88,6 @@ function Fields.num(node: any, name: string, default: number): number return if v and type(v[1]) == "number" then v[1] else default end --- vec(node, name, default) -> the first #default numbers of a field (the default when the field is shorter) function Fields.vec(node: any, name: string, default: { number }): { number } local v = Fields.nums(node, name) if not v or #v < #default then @@ -147,7 +141,6 @@ function Fields.str(node: any, name: string, default: string?): string? return default end --- nodes(node, name) -> the nodes of an SFNode / MFNode field function Fields.nodes(node: any, name: string): { any } local v = node.fields[name] local out = {} diff --git a/src/Rosetta/codecs/model/Vrml/Geometry.luau b/src/Rosetta/codecs/model/Vrml/Geometry.luau index b87db7e..eb82c34 100644 --- a/src/Rosetta/codecs/model/Vrml/Geometry.luau +++ b/src/Rosetta/codecs/model/Vrml/Geometry.luau @@ -1,12 +1,6 @@ --!strict --- codecs/model/Vrml/Geometry: VRML97 / X3D geometry nodes to Scene primitives. Written from the specifications; no --- third-party code. IndexedFaceSet (coord / normal / color / texCoord with their own indices, per-vertex or per-face --- normals and colours, ccw, convex polygons fan-triangulated or kept as "polygons"), the X3D triangle / quad sets --- (IndexedTriangleSet, TriangleSet, IndexedTriangleFanSet, TriangleFanSet, IndexedTriangleStripSet, --- TriangleStripSet, IndexedQuadSet, QuadSet), ElevationGrid, Extrusion (spine-aligned cross sections, scale, --- orientation, caps), IndexedLineSet / LineSet ("lines"), PointSet ("points"), and the primitives Box, Sphere, Cone, --- Cylinder tessellated with normals and the specification's texture mapping. Texture coordinates get t flipped to --- glTF's top-left origin unless flipV = false. Never throws: returns nil, message for bad data. +-- codecs/model/Vrml/Geometry: VRML97 / X3D geometry nodes to Scene primitives. New code, from the specifications. +-- Texture t is flipped to glTF's top-left origin unless flipV = false. local Types = require("@rosetta/Types") local Fields = require("@rosetta/codecs/model/Vrml/Fields") @@ -35,7 +29,6 @@ local function u32(list: { number }): Types.Accessor return a end --- the colour node's values and component count (Color: 3, ColorRGBA: 4) local function colors(n: any): ({ number }?, number) local c = node(n, "color") if not c then @@ -50,14 +43,11 @@ local function points(n: any, field: string, sub: string): { number }? return if c then nums(c, sub) or {} else nil end --- ------------------------------------------------------------------------------------------------ polygon meshes --- Mesh input: faces as corner lists of coordinate indices (0-based) plus, per attribute, a per-corner index list (nil: --- the coordinate index) or per-face indices. type PolyIn = { - P: { number }, -- coordinates, 3 per point - corners: { number }, -- coordinate index per corner, face after face - sizes: { number }, -- corners per face - N: { number }?, nIdx: { number }?, nFace: boolean?, -- normals; per-corner or per-face indices (nil: identity) + P: { number }, + corners: { number }, + sizes: { number }, + N: { number }?, nIdx: { number }?, nFace: boolean?, C: { number }?, cComps: number?, cIdx: { number }?, cFace: boolean?, T: { number }?, tIdx: { number }?, ccw: boolean, @@ -68,7 +58,6 @@ local function polyMesh(m: PolyIn, o: Options, maxV: number): (any, string?) local np = #P // 3 local N, C, T = m.N, m.C, m.T local cc = m.cComps or 3 - -- the attribute index of corner k (1-based) in face f (1-based) local function idx(list: { number }?, perFace: boolean?, f: number, k: number, c: number): number if perFace then return if list and #list > 0 then (list[f] or 0) else f - 1 @@ -77,7 +66,7 @@ local function polyMesh(m: PolyIn, o: Options, maxV: number): (any, string?) end local simple = (N == nil or (not m.nFace and (m.nIdx == nil or #m.nIdx == 0))) and (C == nil or (not m.cFace and (m.cIdx == nil or #m.cIdx == 0))) and (T == nil or m.tIdx == nil or #m.tIdx == 0) local vkey: { [string]: number } = {} - local vsrc: { { number } } = {} -- per output vertex: coord, normal, colour, texcoord indices + local vsrc: { { number } } = {} local out: { number } = {} local outSizes: { number } = {} local k = 0 @@ -179,7 +168,6 @@ local function polyMesh(m: PolyIn, o: Options, maxV: number): (any, string?) return prim end --- split a -1 separated index list into corners + sizes local function split(list: { number }): ({ number }, { number }) local corners, sizes = {}, {} local run = 0 @@ -230,7 +218,6 @@ local function faceSet(n: any, o: Options, maxV: number): (Types.Primitive?, str return polyMesh(m, o, maxV) end --- the X3D triangle / quad sets: faces from index (or vertex order) and fan / strip counts local function triSet(n: any, o: Options, maxV: number): (Types.Primitive?, string?) local t = n.type local P = points(n, "coord", "point") or {} @@ -359,7 +346,6 @@ local function elevationGrid(n: any, o: Options, maxV: number): (Types.Primitive return polyMesh(m, o, maxV) end --- ------------------------------------------------------------------------------------------------ Extrusion local function cross(a: { number }, b: { number }): { number } return { a[2] * b[3] - a[3] * b[2], a[3] * b[1] - a[1] * b[3], a[1] * b[2] - a[2] * b[1] } end @@ -489,7 +475,6 @@ local function extrusion(n: any, o: Options, maxV: number): (Types.Primitive?, s return polyMesh({ P = P, corners = corners, sizes = sizes, ccw = bool(n, "ccw", true) }, o, maxV) end --- ------------------------------------------------------------------------------------------------ lines, points local function lines(n: any, maxV: number): (any, string?) local P = points(n, "coord", "point") or {} local np = #P // 3 @@ -583,8 +568,6 @@ local function pointSet(n: any, maxV: number): (any, string?) return { attributes = attrs, mode = "points" } end --- ------------------------------------------------------------------------------------------------ primitives --- a primitive from flat arrays (positions, normals, uvs with the specification's bottom-left origin, triangles) local function direct(P: { number }, N: { number }, T: { number }, I: { number }, o: Options): Types.Primitive local nv = #P // 3 if o.flipV ~= false then @@ -628,8 +611,7 @@ local function box(n: any, o: Options): Types.Primitive return direct(P, N, T, I, o) end --- a ring of segs + 1 vertices (the seam doubled for the texture) at height y, radius r; s starts at the back (-z) --- and runs counter-clockwise seen from +y +-- a ring of segs + 1 vertices (seam doubled); s starts at the back (-z) and runs counter-clockwise seen from +y local function ring(P: { number }, N: { number }?, T: { number }?, segs: number, y: number, r: number, t: number, ny: number?, nr: number?) for i = 0, segs do local a = 2 * pi * i / segs @@ -649,7 +631,6 @@ local function ring(P: { number }, N: { number }?, T: { number }?, segs: number, end end --- a cap disc at height y facing ny (+1 / -1) local function cap(P: { number }, N: { number }, T: { number }, I: { number }, segs: number, y: number, r: number, ny: number) local b = #P // 3 for i = 0, segs - 1 do @@ -679,7 +660,6 @@ local function cap(P: { number }, N: { number }, T: { number }, I: { number }, s end end --- quads between two rings of segs + 1 vertices starting at a (lower) and b (upper) local function band(I: { number }, a: number, b: number, segs: number) for i = 0, segs - 1 do table.insert(I, a + i) @@ -727,9 +707,6 @@ local function cylinder(n: any, o: Options, segs: number, cone: boolean): Types. return direct(P, N, T, I, o) end --- ------------------------------------------------------------------------------------------------ dispatch --- primitive(geometryNode, opts) -> Primitive | nil, message | nil, nil (a node type without geometry here); --- the second value of a success is the node's solid flag function Geometry.primitive(n: any, o: Options): (Types.Primitive?, any) local t = n.type local maxV = o.maxVertices or 2 ^ 24 diff --git a/src/Rosetta/codecs/model/Vrml/Parse.luau b/src/Rosetta/codecs/model/Vrml/Parse.luau index 8dd2ac5..8ca23bc 100644 --- a/src/Rosetta/codecs/model/Vrml/Parse.luau +++ b/src/Rosetta/codecs/model/Vrml/Parse.luau @@ -1,12 +1,6 @@ --!strict --- codecs/model/Vrml/Parse: the VRML97 (ISO/IEC 14772-1) / X3D classic VRML encoding (ISO/IEC 19776-2) parser, into --- the node graph codecs/model/Vrml/Build reads. Written from the specifications; no third-party code. Field types are --- not known without the node schemas, so a field value is kept as a flat array of what the file wrote (numbers, --- strings, booleans, nodes) and the builder reads it as the type it expects. Handles comments, DEF / USE, PROTO --- (instances are expanded: IS fields take the instance's values or the declared defaults; nested PROTOs, ROUTEs inside --- bodies), EXTERNPROTO (instances stay nodes of that type, without a body), Script / shader interface declarations, --- ROUTE, and the X3D header statements (PROFILE, COMPONENT, META, UNIT, IMPORT, EXPORT). Never throws: errors are --- returned as nil, message ("line N: ..."). +-- codecs/model/Vrml/Parse: the VRML97 (ISO/IEC 14772-1) / X3D classic (ISO/IEC 19776-2) encoding parser. +-- Written from the specifications; no third-party code. local Parse = {} export type Node = { type: string, def: string?, fields: { [string]: any } } @@ -15,13 +9,12 @@ export type Proto = { name: string, fields: { [string]: any }, body: { Node }, r export type Graph = { roots: { Node }, routes: { Route }, - header: { [string]: any }, -- version ("2.0" / "3.3" ...), encoding, x3d (boolean), profile - meta: { [string]: string }, -- META / WorldInfo statements + header: { [string]: any }, + meta: { [string]: string }, components: { string }, units: { [string]: { name: string, factor: number } }, protos: { [string]: Proto }, } --- an IS reference in a PROTO body: fields[name] = { is = "protoField" } export type IsRef = { is: string } local find, sub, byte, match, gmatch = string.find, string.sub, string.byte, string.match, string.gmatch @@ -31,7 +24,6 @@ local MAX_DEPTH = 200 local DECL = { field = true, exposedField = true, eventIn = true, eventOut = true, initializeOnly = true, inputOutput = true, inputOnly = true, outputOnly = true } local HAS_VALUE = { field = true, exposedField = true, initializeOnly = true, inputOutput = true } --- copy(node, values, defaults, memo) -> a PROTO body node with its IS fields replaced (shared nodes stay shared) local function copy(node: Node, values: { [string]: any }, defaults: { [string]: any }, memo: { [any]: any }): Node local done = memo[node] if done then @@ -60,7 +52,6 @@ local function copy(node: Node, values: { [string]: any }, defaults: { [string]: return out end --- expand(proto, values, def, routes) -> the instance's node (the body's first node), or nil for an EXTERNPROTO function Parse.expand(proto: Proto, values: { [string]: any }, def: string?, routes: { Route }?): Node? if proto.extern or #proto.body == 0 then return nil @@ -125,8 +116,6 @@ function Parse.parse(text: string): (Graph?, string?) end end - -- the lexer: skip blanks, commas and comments; returns the next token kind and value - -- kinds: "num", "str", "id", "{", "}", "[", "]", ".", "eof" local function skip() while true do local q = find(text, "[^%s,]", p) @@ -189,7 +178,6 @@ function Parse.parse(text: string): (Graph?, string?) p += 1 return ".", nil end - -- +inf / -nan style words: read the word local _, we = find(text, "^[^%s,%[%]{}#\"]+", p) local w = sub(text, p, we) p = (we :: number) + 1 @@ -221,12 +209,10 @@ function Parse.parse(text: string): (Graph?, string?) local parseProto: (extern: boolean) -> () local parseRoute: () -> () - -- a field value (after its name): an array of numbers / strings / booleans / nodes local function value(): any local k, val = token() if k == "[" then local out = {} - -- fast path: a bracket of plain numbers (big coordinate arrays) local close = find(text, "]", p, true) if close then local seg = sub(text, p, close - 1) @@ -298,7 +284,6 @@ function Parse.parse(text: string): (Graph?, string?) return {} end - -- the fields of a node body, up to its "}" local function body(node: Node) while not failure do local k, name = token() @@ -445,7 +430,7 @@ function Parse.parse(text: string): (Graph?, string?) end end if extern then - value() -- the url list + value() protos[name] = proto return end @@ -478,7 +463,6 @@ function Parse.parse(text: string): (Graph?, string?) protos[name] = proto end - -- statements while not failure do local k, w = token() if k == "eof" then diff --git a/src/Rosetta/codecs/model/Vrml/Write.luau b/src/Rosetta/codecs/model/Vrml/Write.luau index 1400df2..7e247b5 100644 --- a/src/Rosetta/codecs/model/Vrml/Write.luau +++ b/src/Rosetta/codecs/model/Vrml/Write.luau @@ -1,15 +1,5 @@ --!strict --- codecs/model/Vrml/Write: a Scene to VRML97 (`#VRML V2.0 utf8`), X3D classic (`#X3D V3.3 utf8`) or X3D XML text, --- for model/vrml and model/x3d. New code. Every node becomes a DEF'd Transform (a matrix is decomposed into TRS; --- shear is lost), each primitive a Shape: triangles / polygons / strips / fans -> IndexedFaceSet (coord, normal, --- texCoord with t flipped back unless flipV = false, color; per-vertex, ccw, solid = not doubleSided), lines -> --- IndexedLineSet, points -> PointSet; a mesh used twice is written once and USE'd. Materials -> Appearance / Material --- (diffuse = baseColor, transparency = 1 - alpha, emissive, shininess from roughness, the Phong terms of --- material.extras.vrml when present) with an ImageTexture (the texture bytes go into opts.files named after the uri or --- opts.name, else url = texture.uri). Cameras -> Viewpoint (X3D: OrthoViewpoint for orthographic ones), lights -> --- Directional / Point / SpotLight, animations (translation / rotation / scale channels) -> a TimeSensor and --- Position / OrientationInterpolators with ROUTEs (cubic splines keep their values, weights channels are dropped). --- Never throws: returns nil, message. +-- codecs/model/Vrml/Write: a Scene to VRML97 (`#VRML V2.0 utf8`), X3D classic (`#X3D V3.3 utf8`) or X3D XML. New code. local Types = require("@rosetta/Types") local Mat4 = require("@rosetta/codecs/model/Mat4") local Flatten = require("@rosetta/codecs/model/MeshFlatten") @@ -19,8 +9,6 @@ local Write = {} export type Options = { encoding: ("vrml97" | "x3dv" | "xml")?, files: { [string]: any }?, name: string?, flipV: boolean? } --- a written node: fields in order, each { name, kind, value }; kinds: "sf" / "mf" (numbers; mf groups `per` numbers --- per line), "bool", "str", "mstr" (MFString), "node", "nodes" type WNode = { type: string, def: string?, use: string?, fields: { { any } } } local format, concat = string.format, table.concat @@ -45,7 +33,6 @@ local function F(n: WNode, name: string, kind: string, value: any, per: number?) table.insert(n.fields, { name, kind, value, per }) end --- names: valid, unique DEF names local function namer(): (string?, string) -> string local used: { [string]: boolean } = {} return function(name: string?, fallback: string): string @@ -63,7 +50,6 @@ local function namer(): (string?, string) -> string end end --- axis-angle of a quaternion (x, y, z, w) local function axisAngle(q: { number }): { number } local x, y, z, w = q[1], q[2], q[3], q[4] local l = math.sqrt(x * x + y * y + z * z + w * w) @@ -77,7 +63,6 @@ local function axisAngle(q: { number }): { number } return { x / s, y / s, z / s, 2 * math.acos(math.clamp(w, -1, 1)) } end --- ------------------------------------------------------------------------------------------------ geometry local function values(acc: any): { number }? return (Flatten.numbers(acc)) end @@ -145,7 +130,6 @@ local function faceSet(prim: any, doubleSided: boolean, o: Options, x3d: boolean return g, nil end --- Coordinate from POSITION, Color / ColorRGBA from COLOR_0 (lines and points) local function coordNode(prim: any): (WNode?, number) local pos = values(prim.attributes.POSITION) if not pos then @@ -241,7 +225,6 @@ local function pointSet(prim: any, x3d: boolean): (WNode?, string?) return g, nil end --- ------------------------------------------------------------------------------------------------ materials local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/gif"] = "gif", ["image/bmp"] = "bmp", ["image/webp"] = "webp", ["image/ktx2"] = "ktx2" } local function textureUrl(scene: any, i: number, o: Options, written: { [number]: string }): string? @@ -347,7 +330,6 @@ local function appearance(scene: any, mi: number, o: Options, written: { [number return app end --- ------------------------------------------------------------------------------------------------ the tree function Write.graph(scene: any, o: Options): ({ WNode }?, { { string } }?, string?) local x3d = o.encoding == "x3dv" or o.encoding == "xml" local name = namer() @@ -360,7 +342,6 @@ function Write.graph(scene: any, o: Options): ({ WNode }?, { { string } }?, stri local function shapes(mi: number): { WNode } local done = meshShapes[mi] if done then - -- USE the shapes written before local out = {} for _, s in done do table.insert(out, { type = "Shape", use = s.def, fields = {} }) @@ -489,7 +470,6 @@ function Write.graph(scene: any, o: Options): ({ WNode }?, { { string } }?, stri local roots: { WNode } = {} local list = scene.roots if type(list) ~= "table" or #list == 0 then - -- no roots: every node without a parent local child = {} for _, n in scene.nodes do for _, c in n.children or {} do @@ -517,7 +497,6 @@ function Write.graph(scene: any, o: Options): ({ WNode }?, { { string } }?, stri end end - -- animations: a TimeSensor per animation, an interpolator per channel local routes: { { string } } = {} for ai, anim in scene.animations or {} do local tmax = 0 @@ -577,14 +556,12 @@ function Write.graph(scene: any, o: Options): ({ WNode }?, { { string } }?, stri return roots, routes, nil end --- ------------------------------------------------------------------------------------------------ serializers local function numbers(vals: { number }, per: number?, indent: string): string local out = table.create(#vals) for i, v in vals do out[i] = fmt(v) end if per == 0 then - -- index lists: one face per line local lines, cur = {}, {} for i, v in vals do table.insert(cur, out[i]) @@ -665,7 +642,6 @@ local function classic(roots: { WNode }, routes: { { string } }, x3d: boolean): return concat(out, "\n") .. "\n" end --- the containerField a child element needs when it is not its type's default local DEFAULT = { Appearance = "appearance", Material = "material", ImageTexture = "texture", TextureTransform = "textureTransform", Coordinate = "coord", Normal = "normal", Color = "color", ColorRGBA = "color", TextureCoordinate = "texCoord", IndexedFaceSet = "geometry", IndexedLineSet = "geometry", PointSet = "geometry" } local function xml(roots: { WNode }, routes: { { string } }): (string?, string?) @@ -735,7 +711,6 @@ local function xml(roots: { WNode }, routes: { { string } }): (string?, string?) return s, nil end --- text(scene, opts) -> the file text function Write.text(scene: any, o: Options): (string?, string?) local roots, routes, err = Write.graph(scene, o) if not roots or not routes then diff --git a/src/Rosetta/codecs/model/Vrml/Xml.luau b/src/Rosetta/codecs/model/Vrml/Xml.luau index ceb60d7..7b35a36 100644 --- a/src/Rosetta/codecs/model/Vrml/Xml.luau +++ b/src/Rosetta/codecs/model/Vrml/Xml.luau @@ -1,11 +1,5 @@ --!strict --- codecs/model/Vrml/Xml: the X3D XML encoding (ISO/IEC 19776-1) to the node graph of codecs/model/Vrml/Parse, so one --- builder serves .wrl, .x3dv and .x3d. Written from the specification; no third-party code. Elements are nodes; --- attributes stay raw strings (the builder parses them as the type it expects); child nodes go into their --- containerField (or the default field of their type: geometry, appearance, material, coord, ...); DEF / USE; ROUTE; --- ProtoDeclare (ProtoInterface fields with value attributes or child nodes, ProtoBody, IS / connect) and --- ProtoInstance (fieldValue) are expanded through Parse.expand; ExternProtoDeclare instances stay plain nodes; head / --- meta, UNIT, component and the profile go into the graph header. Never throws. +-- codecs/model/Vrml/Xml: the X3D XML encoding (ISO/IEC 19776-1) to the Vrml/Parse node graph. New code. local Xml = require("@rosetta/codecs/text/Xml") local Parse = require("@rosetta/codecs/model/Vrml/Parse") @@ -65,7 +59,6 @@ function VXml.graph(doc: Xml.Node): (Parse.Graph?, string?) end local declare: (el: Xml.Node, extern: boolean) -> () - -- the child elements of a node into its fields local function children(el: Xml.Node, node: Parse.Node) for _, ch in el.children do if type(ch) ~= "table" or string.sub(ch.name, 1, 1) == "#" then @@ -100,7 +93,6 @@ function VXml.graph(doc: Xml.Node): (Parse.Graph?, string?) end end - -- a field value of ProtoInterface / fieldValue: the value attribute, or the child nodes local function fieldValue(el: Xml.Node): any if el.attrs.value ~= nil then return el.attrs.value diff --git a/src/Rosetta/codecs/model/Vrml/init.luau b/src/Rosetta/codecs/model/Vrml/init.luau index feabeda..122ca1d 100644 --- a/src/Rosetta/codecs/model/Vrml/init.luau +++ b/src/Rosetta/codecs/model/Vrml/init.luau @@ -1,12 +1,6 @@ --!strict --- codecs/model/Vrml: the VRML97 / X3D scene-graph engine shared by model/vrml (.wrl) and model/x3d (.x3d XML, --- .x3dv classic): one parser for the classic encoding (codecs/model/Vrml/Parse), one for the XML encoding --- (codecs/model/Vrml/Xml over codecs/text/Xml), both into the same node graph, and one builder from the graph to a --- Scene (codecs/model/Vrml/Build, codecs/model/Vrml/Geometry). Gzipped files (.wrz / .x3dz / .x3dvz) are inflated --- first. New code, written from ISO/IEC 14772-1 (VRML97), ISO/IEC 19775-1 (X3D) and its encodings 19776-1 / -2. --- --- local graph, err = Vrml.graph(bytes) -- classic or XML, by content --- local scene, err2 = Vrml.decode(bytes, { format = "vrml", files = { ["tex.png"] = png } }) +-- codecs/model/Vrml: VRML97 / X3D scene-graph engine (classic and XML encodings) for model/vrml and model/x3d. +-- VRML97 ISO/IEC 14772-1, X3D ISO/IEC 19775-1, encodings ISO/IEC 19776-1 (XML) / -2 (classic). New code. local Err = require("@rosetta/core/Err") local Types = require("@rosetta/Types") local Deflate = require("@rosetta/codecs/compress/Deflate") @@ -21,12 +15,11 @@ local Vrml = {} export type Graph = Parse.Graph export type Node = Parse.Node export type Options = Build.Options & { - files: { [string]: any }?, -- textures / Inline files by uri or base name (buffer or string) - resolve: ((uri: string) -> any)?, -- or: reads them (the api sets it for paths) - maxBytes: number?, -- the inflated size of a gzipped file (default 2^28) + files: { [string]: any }?, + resolve: ((uri: string) -> any)?, + maxBytes: number?, } --- the bytes as text: gzip inflated, UTF-8 BOM dropped local function text(data: buffer | string, maxBytes: number?): (string?, Err.Err?) local b = if type(data) == "string" then buffer.fromstring(data) else data if buffer.len(b) >= 2 and buffer.readu8(b, 0) == 0x1F and buffer.readu8(b, 1) == 0x8B then @@ -57,7 +50,6 @@ local function code(msg: string): string return Err.CORRUPT end --- parse(text) -> the graph of a classic-encoding file (VRML97 / .x3dv) function Vrml.parse(s: string): (Graph?, Err.Err?) local g, msg = Parse.parse(s) if not g then @@ -66,7 +58,6 @@ function Vrml.parse(s: string): (Graph?, Err.Err?) return g, nil end --- parseXml(text | XML document) -> the graph of an X3D XML file function Vrml.parseXml(src: any): (Graph?, Err.Err?) local doc = src if type(src) == "string" then @@ -87,7 +78,6 @@ function Vrml.parseXml(src: any): (Graph?, Err.Err?) return g, nil end --- graph(bytes, opts?) -> the graph of either encoding (XML when the text starts with "<"); binary X3D is UNSUPPORTED function Vrml.graph(data: buffer | string, opts: Options?): (Graph?, Err.Err?) local s, err = text(data, opts and opts.maxBytes) if not s then @@ -103,7 +93,6 @@ function Vrml.graph(data: buffer | string, opts: Options?): (Graph?, Err.Err?) return Vrml.parse(s) end --- fetcher(opts) -> fetch(uri) -> buffer?: opts.files (uri or base name) / opts.resolve function Vrml.fetcher(opts: Options?): (uri: string) -> buffer? return function(uri: string): buffer? if not opts then @@ -121,7 +110,6 @@ function Vrml.fetcher(opts: Options?): (uri: string) -> buffer? end end --- build(graph, opts?) -> Scene function Vrml.build(graph: Graph, opts: Options?): (Types.Scene?, Err.Err?) local o: any = table.clone(opts or {}) o.fetch = o.fetch or Vrml.fetcher(opts) @@ -136,7 +124,6 @@ function Vrml.build(graph: Graph, opts: Options?): (Types.Scene?, Err.Err?) return scene, nil end --- decode(bytes, opts?) -> Scene: graph + build function Vrml.decode(data: buffer | string, opts: Options?): (Types.Scene?, Err.Err?) local g, err = Vrml.graph(data, opts) if not g then @@ -145,7 +132,6 @@ function Vrml.decode(data: buffer | string, opts: Options?): (Types.Scene?, Err. return Vrml.build(g, opts) end --- encode(scene, opts?) -> text: opts.encoding "vrml97" (default) / "x3dv" / "xml"; texture bytes go into opts.files function Vrml.encode(scene: Types.Scene, opts: Write.Options?): (string?, Err.Err?) if type(scene) ~= "table" or scene.kind ~= "scene" or type(scene.nodes) ~= "table" or type(scene.meshes) ~= "table" then return nil, Err.new(Err.ARG, "needs a Scene") diff --git a/src/Rosetta/codecs/text/Json/Decode.luau b/src/Rosetta/codecs/text/Json/Decode.luau index f161130..4a7ceb1 100644 --- a/src/Rosetta/codecs/text/Json/Decode.luau +++ b/src/Rosetta/codecs/text/Json/Decode.luau @@ -1,9 +1,7 @@ --!strict --!native --- codecs/text/Json/Decode: the RFC 8259 parser behind codecs/text/Json. Iterative (an explicit container stack, so deep nesting --- is a LIMIT error, never a stack overflow), strict grammar (no comments, trailing commas, leading zeros, NaN, single --- quotes or raw control characters), \u escapes with surrogate pairs (lone surrogates become WTF-8 bytes). Also the --- pull tokenizer behind Json.events. Never throws: failures return nil, message, offset (0-based byte offset). +-- codecs/text/Json/Decode: the RFC 8259 parser behind codecs/text/Json: iterative, strict grammar. +-- \u escapes with surrogate pairs; lone surrogates become WTF-8 bytes. local Text = require("@rosetta/codecs/text/Text") local Types = require("@rosetta/Types") @@ -14,10 +12,10 @@ local tonumber = tonumber local concat = table.concat export type Options = { - ordered: boolean?, -- every object is a Types.object with its key order (default false: only empty objects are) - bigInts: ("number" | "string")?, -- integers beyond +-2^53: "string" keeps their exact text (default "number") - null: any?, -- the value for null (default Types.null) - maxDepth: number?, -- nesting limit (default 1000) + ordered: boolean?, + bigInts: ("number" | "string")?, + null: any?, + maxDepth: number?, } local ESC: { [number]: string } = { @@ -31,7 +29,6 @@ local ESC: { [number]: string } = { [116] = "\t", } --- utf8 bytes of a code point (surrogates too: WTF-8) local utf8char = Text.utf8char Decode.utf8char = utf8char @@ -43,7 +40,6 @@ local function hex4(s: string, i: number): number? return tonumber(h, 16) end --- string(s, i) -> value, next | nil, message, offset. i is at the opening quote. local function str(s: string, i: number): (string?, any, number?) local j = find(s, '[%z\1-\31"\\]', i + 1) if not j then @@ -102,7 +98,6 @@ local function str(s: string, i: number): (string?, any, number?) end Decode.string = str --- number(s, i) -> value, next | nil, message, offset local function num(s: string, i: number, bigStrings: boolean): (any, any, number?) local p = i if byte(s, p) == 45 then @@ -153,8 +148,6 @@ local function num(s: string, i: number, bigStrings: boolean): (any, any, number end Decode.number = num --- decode(s, i, opts) -> value, next | nil, message, offset. Parses one value starting at i (leading whitespace --- skipped); next is the position after the value (trailing whitespace not skipped). function Decode.value(s: string, i: number, opts: Options?): (any, any, number?) local o: Options = opts or {} local ordered = o.ordered == true @@ -163,9 +156,9 @@ function Decode.value(s: string, i: number, opts: Options?): (any, any, number?) local maxDepth = o.maxDepth or 1000 local object = Types.object - local stackT: { any } = {} -- containers - local stackK: { any } = {} -- object: the pending key; array: the count - local stackO: { any } = {} -- object: its key order (or true); array: false + local stackT: { any } = {} + local stackK: { any } = {} + local stackO: { any } = {} local depth = 0 local n = #s local value: any @@ -246,7 +239,6 @@ function Decode.value(s: string, i: number, opts: Options?): (any, any, number?) end value, i = v, ni end - -- attach the value to the open containers, closing them as their ends come while haveValue do if depth == 0 then return value, i @@ -303,17 +295,13 @@ function Decode.value(s: string, i: number, opts: Options?): (any, any, number?) end end --- events: a pull tokenizer. next() -> event, value | nil at the end | "error", message, offset. Events: "object", --- "endObject", "array", "endArray", "key" (string), "value" (scalar). The grammar is checked as it goes. function Decode.events(s: string, i: number, opts: Options?): () -> (string?, any, number?) local o: Options = opts or {} local bigStrings = o.bigInts == "string" local nullv = if o.null ~= nil then o.null else Types.null local maxDepth = o.maxDepth or 1000 - local stack: { boolean } = {} -- true = object + local stack: { boolean } = {} local depth = 0 - -- state: "value" (a value expected), "first" (after { or [: value / key or close), "after" (after a value), - -- "key" (a key expected), "done", "dead" local state = "value" local n = #s local function fail(msg: string, at: number): (string, any, number) @@ -378,7 +366,6 @@ function Decode.events(s: string, i: number, opts: Options?): () -> (string?, an state = "value" return "key", k end - -- a value local after = if depth == 0 then "done" else "after" if c == 123 or c == 91 then depth += 1 diff --git a/src/Rosetta/codecs/text/Json/Encode.luau b/src/Rosetta/codecs/text/Json/Encode.luau index 8fff546..e8946ea 100644 --- a/src/Rosetta/codecs/text/Json/Encode.luau +++ b/src/Rosetta/codecs/text/Json/Encode.luau @@ -1,9 +1,6 @@ --!strict --!native --- codecs/text/Json/Encode: the serializer behind codecs/text/Json. Compact or pretty (indent), objects in their Types.object key --- order (plain tables: sorted keys), arrays for tables with keys 1..n, shortest round-trip number text, optional --- ASCII-only output. Never throws: bad values (cycles, NaN / inf, functions, non-string keys that are not numbers) --- return nil, message. +-- codecs/text/Json/Encode: the RFC 8259 serializer behind codecs/text/Json. local Types = require("@rosetta/Types") local Encode = {} @@ -13,13 +10,13 @@ local floor, huge = math.floor, math.huge local concat = table.concat export type Options = { - indent: (number | string)?, -- pretty print: spaces per level (or the indent string); default compact - sortKeys: boolean?, -- plain tables' keys sorted (default true; false = next() order, faster) - ascii: boolean?, -- escape every non-ASCII character as \uXXXX (default false: UTF-8 as is) - nan: ("error" | "null")?, -- NaN / inf: an error (default) or null - emptyTable: ("array" | "object")?, -- what a plain empty table is (default "array"; Types.object() is "{}") - maxDepth: number?, -- nesting limit (default 1000; also catches cycles) - escapeSlash: boolean?, -- write / as \/ (default false) + indent: (number | string)?, + sortKeys: boolean?, + ascii: boolean?, + nan: ("error" | "null")?, + emptyTable: ("array" | "object")?, + maxDepth: number?, + escapeSlash: boolean?, } local ESCAPES: { [string]: string } = { @@ -47,7 +44,6 @@ local function utf16(cp: number): string return format("\\u%04x\\u%04x", 0xD800 + cp // 1024, 0xDC00 + cp % 1024) end --- asciify a UTF-8 string's non-ASCII sequences (invalid bytes become \u00XX of the byte: lossy but never throws) local function asciiSeq(seq: string): string local out = {} local i, n = 1, #seq @@ -69,7 +65,7 @@ local function asciiSeq(seq: string): string return concat(out) end --- string(s, ascii, slash) -> the quoted JSON string (ascii: DEL too, like Python's ensure_ascii) +-- ascii escapes DEL too, like Python's ensure_ascii local function quote(s: string, ascii: boolean?, slash: boolean?): string local pat = if slash then '[%z\1-\31"\\/]' else '[%z\1-\31"\\]' if string.find(s, pat) then @@ -85,7 +81,6 @@ end Encode.quote = quote local FLOAT_FORMATS = { "%.15g", "%.16g", "%.17g" } --- number(x) -> the shortest text that reads back as x | nil for NaN / inf local function number(x: number): string? if x ~= x or x == huge or x == -huge then return nil @@ -114,7 +109,6 @@ local function keyLess(a: any, b: any): boolean return a < b end --- kind(t, emptyObject) -> "array" (keys exactly 1..n) | "object" local function kind(t: { [any]: any }, emptyObject: boolean): string if Types.isObject(t) then return "object" @@ -295,7 +289,6 @@ end Encode.state = state Encode.write = value --- encode(v, opts) -> text | nil, message function Encode.encode(v: any, opts: Options?, nullv: any?): (string?, string?) local st = state(opts, nullv) if not value(st, v, 0) then diff --git a/src/Rosetta/codecs/text/Json/init.luau b/src/Rosetta/codecs/text/Json/init.luau index 528635e..11663e0 100644 --- a/src/Rosetta/codecs/text/Json/init.luau +++ b/src/Rosetta/codecs/text/Json/init.luau @@ -1,18 +1,5 @@ --!strict -- codecs/text/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code. --- Values are plain Luau: objects -> tables (string keys), arrays -> arrays, null -> Types.null (opts.null), numbers --- -> doubles (opts.bigInts = "string" keeps integers past 2^53 as their text). Empty objects are Types.object() so --- they write back as {}; opts.ordered makes every object a Types.object with its key order. --- --- local Json = require("@rosetta/codecs/text/Json") --- local v, err = Json.decode('{"a": [1, 2, null]}') -- string | buffer; nil, Err on bad input --- local s = Json.encode(v, { indent = 2 }) -- string | nil, Err --- for ev, x in Json.events(text) do ... end -- pull events without building the tree --- for i, v, err in Json.lines(ndjson) do ... end -- JSON Lines / concatenated JSON values --- local w = Json.writer({ indent = 2 }); w:beginObject(); w:key("a"); w:value(1); w:endObject(); w:tostring() --- --- Streaming: decodeAt(src, pos) parses one value and returns where the next begins; events() is a pull tokenizer; --- writer() builds output incrementally and flush() hands back the text so far. Never throws. local Err = require("@rosetta/core/Err") local Types = require("@rosetta/Types") local Decode = require("@rosetta/codecs/text/Json/Decode") @@ -46,8 +33,6 @@ local function fail(msg: any, at: any, n: number): Err.Err return Err.new(code, m, at) end --- decode(src, opts?) -> value | nil, Err. One JSON text: a value with optional whitespace around it (a UTF-8 BOM is --- skipped). Note a JSON null top-level value decodes to opts.null (Types.null by default), never nil. function Json.decode(src: string | buffer, opts: DecodeOptions?): (any, Err.Err?) local s, terr = text(src) if not s then @@ -65,8 +50,6 @@ function Json.decode(src: string | buffer, opts: DecodeOptions?): (any, Err.Err? return v, nil end --- decodeAt(src, pos?, opts?) -> value, nextPos | nil, Err. One value starting at pos (1-based, default 1; leading --- whitespace skipped); nextPos is just past it. nil, nil when only whitespace is left. function Json.decodeAt(src: string | buffer, pos: number?, opts: DecodeOptions?): (any, any) local s, terr = text(src) if not s then @@ -83,8 +66,6 @@ function Json.decodeAt(src: string | buffer, pos: number?, opts: DecodeOptions?) return v, ni end --- lines(src, opts?) -> iterator: index, value (JSON Lines, or any whitespace-separated sequence of JSON values). A --- bad value gives a last index, nil, Err: for i, v, err in Json.lines(s) do if err then ... end end function Json.lines(src: string | buffer, opts: DecodeOptions?): () -> (number?, any, Err.Err?) local s, terr = text(src) local pos = 1 @@ -112,8 +93,6 @@ function Json.lines(src: string | buffer, opts: DecodeOptions?): () -> (number?, end end --- events(src, opts?) -> iterator: event, value. Events: "object", "endObject", "array", "endArray", "key" (the key), --- "value" (a scalar), and on bad input one final "error", Err. function Json.events(src: string | buffer, opts: DecodeOptions?): () -> (string?, any) local s, terr = text(src) if not s then @@ -138,7 +117,6 @@ function Json.events(src: string | buffer, opts: DecodeOptions?): () -> (string? end end --- encode(value, opts?) -> string | nil, Err function Json.encode(value: any, opts: EncodeOptions?): (string?, Err.Err?) local s, msg = Encode.encode(value, opts) if not s then @@ -147,13 +125,9 @@ function Json.encode(value: any, opts: EncodeOptions?): (string?, Err.Err?) return s, nil end -Json.quote = Encode.quote -- quote(s) -> '"..."' with JSON escapes -Json.number = Encode.number -- number(x) -> the shortest round-trip text (nil for NaN / inf) +Json.quote = Encode.quote +Json.number = Encode.number --- ------------------------------------------------------------------------------------------------ writer --- writer(opts?) -> a streaming Writer: beginObject / endObject / beginArray / endArray / key(k) / value(v) (any --- value, encoded whole), then tostring() for everything or flush() for the text since the last flush. Misuse (a key --- outside an object, a value where a key is due, unbalanced ends) is recorded in w.err and later calls do nothing. export type Writer = { err: Err.Err?, beginObject: (self: Writer) -> Writer, @@ -169,10 +143,10 @@ export type Writer = { function Json.writer(opts: EncodeOptions?): Writer local st = Encode.state(opts) local ind = st.indent - local kinds: { boolean } = {} -- true = object + local kinds: { boolean } = {} local counts: { number } = {} local depth = 0 - local keyDone = false -- an object's key written, its value due + local keyDone = false local flushed: { string } = {} local w: any = { err = nil } local function bad(msg: string) @@ -180,7 +154,6 @@ function Json.writer(opts: EncodeOptions?): Writer w.err = Err.new(Err.ARG, msg) end end - -- before an element: a comma / newline as needed; false when the position is wrong local function slot(isKey: boolean): boolean if w.err then return false diff --git a/src/Rosetta/codecs/text/Nbt/Binary.luau b/src/Rosetta/codecs/text/Nbt/Binary.luau index a22b579..1ecab9a 100644 --- a/src/Rosetta/codecs/text/Nbt/Binary.luau +++ b/src/Rosetta/codecs/text/Nbt/Binary.luau @@ -1,9 +1,7 @@ --!strict -- codecs/text/Nbt/Binary: binary NBT read and write, from the Minecraft wiki "NBT format" page and wiki.vg "NBT". --- New code. Three encodings: big-endian (Java Edition files; strings in Java's modified UTF-8, converted to and from --- UTF-8), little-endian (Bedrock files; UTF-8) and Bedrock's network form (little-endian with zigzag varints for int / --- long and varint lengths). All thirteen tag types; values per codecs/text/Nbt/Value. Lengths are checked against --- the bytes left before anything is allocated, and nesting is limited (opts.maxDepth, default 512 like Minecraft). +-- Java big-endian (modified UTF-8 strings), Bedrock little-endian (UTF-8), and Bedrock network NBT (little-endian, +-- zigzag varint int / long, varint lengths). local Bytes = require("@rosetta/core/Bytes") local Types = require("@rosetta/Types") local Value = require("@rosetta/codecs/text/Nbt/Value") @@ -11,11 +9,11 @@ local Value = require("@rosetta/codecs/text/Nbt/Value") local Binary = {} export type Options = { - endian: ("big" | "little")?, -- default "big" (Java) - varint: boolean?, -- Bedrock network NBT (little-endian, varint ints / lengths); implies endian = "little" - nameless: boolean?, -- the root tag has no name (Java network NBT since 1.20.2) - maxDepth: number?, -- nesting limit (default 512) - name: string?, -- write: the root name (default "") + endian: ("big" | "little")?, + varint: boolean?, + nameless: boolean?, + maxDepth: number?, + name: string?, } local readu8, readi8, readu32, readi16 = buffer.readu8, buffer.readi8, buffer.readu32, buffer.readi16 @@ -27,7 +25,6 @@ local newTag = Value.TagMeta type State = { b: buffer, p: number, e: number, le: boolean, net: boolean, java: boolean, depth: number, maxDepth: number, err: string?, scratch: buffer } --- ------------------------------------------------------------------------------------------------ modified UTF-8 -- Java's DataOutput strings: U+0000 as C0 80, supplementary characters as two 3-byte surrogates (CESU-8) local function fromModified(s: string): string if not string.find(s, "[\192\237]") then @@ -89,7 +86,6 @@ end Binary.fromModified = fromModified Binary.toModified = toModified --- ------------------------------------------------------------------------------------------------ read local function fail(s: State, msg: string): nil if not s.err then s.err = msg @@ -170,7 +166,7 @@ local function len(s: State): number return i32(s) end -local function i64(s: State): (number, number) -- hi, lo +local function i64(s: State): (number, number) if s.net then local lo, hi, sh = 0, 0, 0 while true do @@ -248,7 +244,6 @@ local function tag(name: string, v: any): any return setmetatable({ type = name, value = v }, newTag) end --- the smallest encoded size of one element, to bound list lengths before allocating local MIN = { [0] = 0, 1, 2, 4, 8, 4, 8, 4, 2, 5, 1, 4, 4 } local MIN_NET = { [0] = 0, 1, 2, 1, 1, 4, 8, 1, 1, 2, 1, 1, 1 } @@ -393,7 +388,6 @@ payload = function(s: State, id: number): any return fail(s, "bad tag type " .. id) end --- read(buf, pos, limit, opts?) -> value, rootName, endPos | nil, message, at function Binary.read(b: buffer, pos: number, limit: number, opts: Options?): (any, any, number?) local o: Options = opts or {} local net = o.varint == true @@ -425,7 +419,6 @@ function Binary.read(b: buffer, pos: number, limit: number, opts: Options?): (an return v, name, s.p end --- ------------------------------------------------------------------------------------------------ write type WState = { w: Bytes.Writer, le: boolean, net: boolean, java: boolean, depth: number, maxDepth: number } local function wvaruint(w: Bytes.Writer, v: number) @@ -438,7 +431,7 @@ local function wvaruint(w: Bytes.Writer, v: number) end local function wi32(ws: WState, v: number) - v %= TWO32 -- two's complement + v %= TWO32 if ws.net then local sv = if v >= 0x80000000 then v - TWO32 else v wvaruint(ws.w, if sv >= 0 then sv * 2 else -sv * 2 - 1) @@ -671,7 +664,6 @@ wpayload = function(ws: WState, t: string, v: any): string? return nil end --- write(value, opts?) -> buffer | nil, message function Binary.write(v: any, opts: Options?): (buffer?, string?) local o: Options = opts or {} local net = o.varint == true diff --git a/src/Rosetta/codecs/text/Nbt/Snbt.luau b/src/Rosetta/codecs/text/Nbt/Snbt.luau index 39456d9..ef865de 100644 --- a/src/Rosetta/codecs/text/Nbt/Snbt.luau +++ b/src/Rosetta/codecs/text/Nbt/Snbt.luau @@ -1,11 +1,6 @@ --!strict --- codecs/text/Nbt/Snbt: stringified NBT (the text form of /data and /give), parse and print. New code, from the --- Minecraft wiki "NBT format" SNBT section (Java 1.21.5 grammar). Parses: compounds, lists, [B; ...] [I; ...] [L; ...] --- arrays, quoted strings ('...' / "..." with \\ \' \" \n \t \r \b \f \s \xNN \uNNNN \UNNNNNNNN escapes) and unquoted --- strings, numbers with b / s / i / l / f / d suffixes (any case, signed / unsigned s / u prefix), underscores, hex --- 0x and binary 0b integers, exponents, true / false (bytes 1 / 0), NaN / Infinity with a float suffix, trailing --- commas. Not supported: the 1.21.5 operations bool(...) / uuid(...) and \N{name} escapes. Prints Minecraft's --- compact form (or indented); floats print as the shortest text that reads back to the same value. +-- codecs/text/Nbt/Snbt: stringified NBT, parse and print, from the Minecraft wiki "NBT format" SNBT section (1.21.5). +-- Not supported: the 1.21.5 operations bool(...) / uuid(...) and \N{name} escapes. local Types = require("@rosetta/Types") local Value = require("@rosetta/codecs/text/Nbt/Value") @@ -13,8 +8,8 @@ local Snbt = {} export type ParseOptions = { maxDepth: number? } export type PrintOptions = { - indent: (number | string)?, -- pretty print: spaces per level or the indent string (default: compact) - quote: string?, -- the string quote, '"' (default) or "'"; the other one is used when it needs fewer escapes + indent: (number | string)?, + quote: string?, } local byte, sub, find = string.byte, string.sub, string.find @@ -24,7 +19,6 @@ local function tag(name: string, v: any): any return setmetatable({ type = name, value = v }, Value.TagMeta) end --- ------------------------------------------------------------------------------------------------ parse type P = { s: string, i: number, n: number, err: string?, at: number, depth: number, maxDepth: number } local function fail(p: P, msg: string): nil @@ -85,7 +79,6 @@ local function quoted(p: P): string? end end --- number text -> a value, or nil when it is not a number (then it is an unquoted string) local INT_RANGE: { [string]: { number } } = { b = { -128, 127, 255 }, s = { -32768, 32767, 65535 }, @@ -135,7 +128,6 @@ local function integer(t: string): any if unsigned and sign == "-" then return nil end - -- the magnitude as (hi, lo) local hi, lo = 0, 0 for k = 1, #digits do local c = byte(digits, k) @@ -437,7 +429,6 @@ parseValue = function(p: P): any return v end --- parse(text, opts?) -> value | nil, message, position (1-based) function Snbt.parse(s: string, opts: ParseOptions?): (any, string?, number?) local p: P = { s = s, i = 1, n = #s, err = nil, at = 1, depth = 0, maxDepth = (opts and opts.maxDepth) or 512 } local v = parseValue(p) @@ -451,7 +442,6 @@ function Snbt.parse(s: string, opts: ParseOptions?): (any, string?, number?) return v, nil, nil end --- ------------------------------------------------------------------------------------------------ print local function shortest(v: number, single: boolean): string if v ~= v then return "NaN" @@ -625,7 +615,6 @@ printValue = function(pr: Pr, v: any, depth: number): string? return nil end --- print(value, opts?) -> text | nil, message function Snbt.print(v: any, opts: PrintOptions?): (string?, string?) local o: PrintOptions = opts or {} local ind = o.indent diff --git a/src/Rosetta/codecs/text/Nbt/Value.luau b/src/Rosetta/codecs/text/Nbt/Value.luau index c178e79..d01f348 100644 --- a/src/Rosetta/codecs/text/Nbt/Value.luau +++ b/src/Rosetta/codecs/text/Nbt/Value.luau @@ -1,13 +1,7 @@ --!strict -- codecs/text/Nbt/Value: the NBT value model shared by the binary and SNBT codecs. New code. --- Plain Luau values with typed numbers, so a decode / encode round trip is exact: --- int -> number string -> string byteArray -> buffer --- compound -> Types.object (key order kept) list -> array (element type in Value.listType) --- byte / short / long / float / double / intArray / longArray -> a tag { type = "", value = ... } with a --- metatable (tostring gives SNBT): long values are numbers when exact (|v| <= 2^53), else their exact decimal --- text; intArray value = { numbers }; longArray value = a buffer of little-endian two's complement int64s. --- Inputs are lenient: a plain number writes as int when integral and in int range, else double; true / false as --- byte 1 / 0; a plain table with string keys as a compound. +-- long values are numbers when |v| <= 2^53, else their exact decimal text; longArray values are buffers of +-- little-endian two's complement int64s. local Types = require("@rosetta/Types") local Value = {} @@ -37,7 +31,6 @@ export type Tag = { type: string, value: any } local TagMeta: { [string]: any } = {} Value.TagMeta = TagMeta --- the SNBT printer, filled in by codecs/text/Nbt (Value is below the printer) Value.print = function(v: any): string return tostring(v.value) end @@ -67,11 +60,8 @@ end local listTypes: { [any]: string } = setmetatable({}, { __mode = "k" }) :: any --- ------------------------------------------------------------------------------------------------ 64-bit integers local TWO32 = 4294967296 --- fromHiLo(hi, lo) -> a long value: a number when exact, else the exact decimal text (hi, lo: u32 halves of the --- two's complement int64) function Value.fromHiLo(hi: number, lo: number): number | string local s = if hi >= 0x80000000 then hi - TWO32 else hi if s >= -0x200000 and s < 0x200000 then @@ -94,7 +84,6 @@ function Value.fromHiLo(hi: number, lo: number): number | string return (if neg then "-" else "") .. table.concat(parts) end --- toHiLo(v) -> hi, lo (u32 halves) | nil: v a whole number in int64 range or its decimal text function Value.toHiLo(v: any): (number?, number?) if type(v) == "number" then if v % 1 ~= 0 or v < -9223372036854775808 or v >= 9223372036854775808 then @@ -127,7 +116,6 @@ function Value.toHiLo(v: any): (number?, number?) return nil, nil end --- ------------------------------------------------------------------------------------------------ constructors local function tag(name: string, v: any): Tag return setmetatable({ type = name, value = v }, TagMeta) :: any end @@ -140,7 +128,6 @@ end function Value.int(n: number): number return n end --- long(n | "decimal") -> a long tag (decimal text within 2^53 becomes a number) function Value.long(v: number | string): Tag if type(v) == "string" then local hi, lo = Value.toHiLo(v) @@ -151,7 +138,6 @@ function Value.long(v: number | string): Tag return tag("long", v) end local f32 = buffer.create(4) --- float(n) -> a float tag holding n rounded to single precision function Value.float(n: number): Tag buffer.writef32(f32, 0, n) return tag("float", buffer.readf32(f32, 0)) @@ -162,7 +148,6 @@ end function Value.intArray(t: { number }?): Tag return tag("intArray", t or {}) end --- longArray(values | buffer) -> a longArray tag (values: numbers / decimal texts; a buffer: 8 bytes each, LE) function Value.longArray(t: { any } | buffer | nil): Tag if type(t) == "buffer" then return tag("longArray", t) @@ -176,7 +161,6 @@ function Value.longArray(t: { any } | buffer | nil): Tag end return tag("longArray", b) end --- longs(longArray) -> { number | string }: the elements as long values function Value.longs(a: Tag): { number | string } local b: buffer = a.value local out = table.create(buffer.len(b) // 8) :: { number | string } @@ -185,7 +169,6 @@ function Value.longs(a: Tag): { number | string } end return out end --- list(typeName, items?) -> items marked as a list of that element type (an empty list keeps its type) function Value.list(name: string, items: { any }?): { any } local t = items or {} listTypes[t] = name @@ -194,7 +177,6 @@ end function Value.compound(t: { [string]: any }?, keys: { string }?): { [string]: any } return Types.object(t, keys) end --- listType(t) -> the element type name recorded for a list (decoded, or made by Value.list) function Value.listType(t: any): string? return listTypes[t] end @@ -205,7 +187,6 @@ function Value.isTag(v: any): boolean return type(v) == "table" and getmetatable(v) == TagMeta end --- typeOf(v) -> the tag name v writes as, or nil + why function Value.typeOf(v: any): (string?, string?) local tv = type(v) if tv == "number" then @@ -236,7 +217,6 @@ function Value.typeOf(v: any): (string?, string?) return nil, "cannot write a " .. tv .. " as NBT" end --- number(v) -> the numeric value of a number or numeric tag (long texts through tonumber: approximate) function Value.number(v: any): number? if type(v) == "number" then return v diff --git a/src/Rosetta/codecs/text/Nbt/init.luau b/src/Rosetta/codecs/text/Nbt/init.luau index 3e2bbb5..086f948 100644 --- a/src/Rosetta/codecs/text/Nbt/init.luau +++ b/src/Rosetta/codecs/text/Nbt/init.luau @@ -1,22 +1,6 @@ --!strict --- codecs/text/Nbt: Minecraft's Named Binary Tag format and its text form SNBT, the engine data/nbt, data/snbt, --- model/schematic and model/mca use. New code (Minecraft wiki "NBT format", wiki.vg "NBT"). --- Binary: Java big-endian (modified UTF-8 strings), Bedrock little-endian (with or without the 8-byte level.dat --- header) and Bedrock network NBT (varints), every tag type; files may be gzip or zlib compressed (codecs/compress/ --- Deflate). SNBT: parse and print (codecs/text/Nbt/Snbt). Values are plain Luau with typed numbers --- (codecs/text/Nbt/Value): int -> number, string -> string, byteArray -> buffer, compound -> Types.object (key order --- kept), list -> array, the other numeric and array tags -> { type, value } tags, so round trips are exact. --- --- local Nbt = require("@rosetta/codecs/text/Nbt") --- local v, info = Nbt.decode(buf) -- a file: compression and edition detected; info = how it was stored --- print(v.Data.LevelName, v.Data.Time.value) -- int / string plain; long / byte / ... tags have .value --- v.Data.Difficulty = Nbt.byte(2) --- local out = Nbt.encode(v) -- written the way it was read (Nbt.info(v)), or opts --- local text = Nbt.print(v) -- SNBT: {Data:{Difficulty:2b,...}} --- local w = Nbt.parse('{pos:[I;1,2,3],name:"x"}') --- local raw, name, endPos = Nbt.read(buf, 0, nil, { endian = "little" }) -- one uncompressed tag --- --- Never throws: bad data and bad values return nil, Err. +-- codecs/text/Nbt: Minecraft's Named Binary Tag format and SNBT (Minecraft wiki "NBT format", wiki.vg "NBT"). +-- Files may be gzip or zlib compressed; a Bedrock level.dat has an 8-byte header. local Err = require("@rosetta/core/Err") local Bytes = require("@rosetta/core/Bytes") local Types = require("@rosetta/Types") @@ -29,31 +13,31 @@ local Nbt = {} export type Tag = Value.Tag export type Info = { - name: string, -- the root tag's name + name: string, endian: "big" | "little", - varint: boolean?, -- Bedrock network NBT + varint: boolean?, compression: "gzip" | "zlib" | "none", - header: number?, -- Bedrock level.dat: the storage version from the 8-byte header + header: number?, } export type DecodeOptions = { - endian: ("big" | "little")?, -- default: detected (Java big-endian first) - varint: boolean?, -- Bedrock network NBT - nameless: boolean?, -- no root name (Java network NBT since 1.20.2) - maxDepth: number?, -- nesting limit (default 512) - maxBytes: number?, -- refuse compressed data that inflates past this (default 2^28) -} -export type EncodeOptions = { - endian: ("big" | "little")?, -- default: Nbt.info(value).endian, else "big" + endian: ("big" | "little")?, varint: boolean?, nameless: boolean?, - name: string?, -- the root name (default: Nbt.info(value).name, else "") - compression: ("gzip" | "zlib" | "none")?, -- default: Nbt.info(value).compression, else gzip for big-endian - header: number?, -- write the Bedrock level.dat header with this version - level: number?, -- deflate level 0..9 (default 6) + maxDepth: number?, + maxBytes: number?, +} +export type EncodeOptions = { + endian: ("big" | "little")?, + varint: boolean?, + nameless: boolean?, + name: string?, + compression: ("gzip" | "zlib" | "none")?, + header: number?, + level: number?, } -Nbt.TAG = Value.IDS -- name -> id -Nbt.TAG_NAMES = Value.NAMES -- id -> name +Nbt.TAG = Value.IDS +Nbt.TAG_NAMES = Value.NAMES Nbt.byte = Value.byte Nbt.short = Value.short Nbt.int = Value.int @@ -74,18 +58,15 @@ Nbt.toHiLo = Value.toHiLo local infos: { [any]: Info } = setmetatable({}, { __mode = "k" }) :: any --- info(value) -> how a decoded root was stored (nil for values not from decode) function Nbt.info(v: any): Info? return if type(v) == "table" then infos[v] else nil end --- setInfo(value, info): what encode uses as defaults function Nbt.setInfo(v: any, info: Info) if type(v) == "table" then infos[v] = info end end --- read(buf, offset?, length?, opts?) -> value, rootName, endOffset | nil, Err: one uncompressed root tag function Nbt.read(buf: buffer | string, offset: number?, length: number?, opts: DecodeOptions?): (any, any, number?) local b, o, l, aerr = Bytes.span("Nbt.read", buf, offset, length) if not b then @@ -98,7 +79,6 @@ function Nbt.read(buf: buffer | string, offset: number?, length: number?, opts: return v, name, at end --- write(value, opts?) -> buffer | nil, Err: one uncompressed root tag function Nbt.write(v: any, opts: EncodeOptions?): (buffer?, Err.Err?) local out, e = Binary.write(v, opts :: any) if not out then @@ -107,7 +87,6 @@ function Nbt.write(v: any, opts: EncodeOptions?): (buffer?, Err.Err?) return out, nil end --- unwrap(buf, offset?, length?, maxBytes?) -> data, start, end, compression | nil, Err: gzip / zlib detected by magic function Nbt.unwrap(buf: buffer | string, offset: number?, length: number?, maxBytes: number?): (buffer?, any, number?, string?) local b, o, l, aerr = Bytes.span("Nbt.unwrap", buf, offset, length) if not b then @@ -135,14 +114,14 @@ function Nbt.unwrap(buf: buffer | string, offset: number?, length: number?, maxB end export type Peek = { - compression: string, -- "gzip" | "zlib" | "none" + compression: string, endian: "big" | "little", - header: boolean, -- a Bedrock level.dat header - rootType: string, -- "compound" (or "list") - name: string, -- the root name - firstType: string?, -- the first child of a root compound (type and name; "end" when empty), when peeked + header: boolean, + rootType: string, + name: string, + firstType: string?, firstName: string?, - head: buffer, -- the first (up to 1024) uncompressed bytes + head: buffer, } local function plausibleName(b: buffer, p: number, n: number): string? @@ -156,8 +135,6 @@ local function plausibleName(b: buffer, p: number, n: number): string? return s end --- peek(buf, offset?, length?) -> Peek | nil: whether the bytes look like an NBT file (inflating at most 1 KiB of a --- gzip / zlib stream), and its root's name and first child: what format sniffs look at. Never fails loudly. function Nbt.peek(buf: buffer, offset: number?, length: number?): Peek? local o = offset or 0 local l = length or (buffer.len(buf) - o) @@ -204,7 +181,7 @@ function Nbt.peek(buf: buffer, offset: number?, length: number?): Peek? return nil end if ft == 0 then - res.firstType = "end" -- an empty root compound + res.firstType = "end" elseif q + 3 <= hn then local fname = plausibleName(head, q + 3, u16(q + 1)) if fname == nil and q + 3 + u16(q + 1) <= hn then @@ -224,8 +201,6 @@ function Nbt.peek(buf: buffer, offset: number?, length: number?): Peek? return at(0, "big", false) or at(0, "little", false) end --- decode(buf | string, opts?, offset?, length?) -> value, Info | nil, Err: a whole NBT file (gzip / zlib / raw; Java --- or Bedrock) function Nbt.decode(buf: buffer | string, opts: DecodeOptions?, offset: number?, length: number?): (any, any) local o: DecodeOptions = opts or {} local b, s, e, comp = Nbt.unwrap(buf, offset, length, o.maxBytes) @@ -291,7 +266,6 @@ function Nbt.decode(buf: buffer | string, opts: DecodeOptions?, offset: number?, return v, info end --- encode(value, opts?) -> buffer | nil, Err: a whole NBT file function Nbt.encode(v: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: EncodeOptions = opts or {} local info = Nbt.info(v) @@ -325,7 +299,6 @@ function Nbt.encode(v: any, opts: EncodeOptions?): (buffer?, Err.Err?) return raw, nil end --- parse(text, opts?) -> value | nil, Err: SNBT function Nbt.parse(text: string | buffer, opts: Snbt.ParseOptions?): (any, Err.Err?) local s = if type(text) == "buffer" then buffer.tostring(text) else text if type(s) ~= "string" then @@ -338,7 +311,6 @@ function Nbt.parse(text: string | buffer, opts: Snbt.ParseOptions?): (any, Err.E return v, nil end --- print(value, opts?) -> text | nil, Err: SNBT (compact, or opts.indent) function Nbt.print(v: any, opts: Snbt.PrintOptions?): (string?, Err.Err?) local s, e = Snbt.print(v, opts) if not s then @@ -347,7 +319,6 @@ function Nbt.print(v: any, opts: Snbt.PrintOptions?): (string?, Err.Err?) return s, nil end --- get(value, path) -> the value at a dotted path ("Data.Player.Pos[1]"; list indices 0-based like Minecraft's) function Nbt.get(v: any, path: string): any local cur = v for part in string.gmatch(path, "[^%.]+") do diff --git a/src/Rosetta/codecs/text/Text/init.luau b/src/Rosetta/codecs/text/Text/init.luau index fe1e2d5..ee88261 100644 --- a/src/Rosetta/codecs/text/Text/init.luau +++ b/src/Rosetta/codecs/text/Text/init.luau @@ -1,11 +1,9 @@ --!strict --!optimize 2 --- codecs/text/Text: text decoding helpers for the text formats: a UTF-8 BOM is stripped, text that is not valid UTF-8 is --- read as Windows-1252 (classic .m3u / .pls / .ini / .srt files), lines split on CRLF / CR / LF, trim. Absorbed from --- playlist-luau 3fc7fd3 (same author, no third-party code). Never throws. +-- codecs/text/Text: text decoding helpers: BOM stripping, Windows-1252 for text that is not UTF-8, line splitting. +-- Absorbed from playlist-luau 3fc7fd3 (same author, no third-party code). local Text = {} --- utf8char(codepoint) -> its UTF-8 bytes (no validation: the parsers check ranges first; utf8.char would throw) function Text.utf8char(c: number): string local char = string.char if c < 0x80 then @@ -31,8 +29,6 @@ function Text.trim(s: string): string return (string.match(s, "^%s*(.-)%s*$") :: string) end --- utf16(buf, offset, length, bigEndian?) -> UTF-8 text of UTF-16 code units (surrogate pairs joined, lone surrogates --- become U+FFFD; an odd last byte is ignored). Font names, 7z / PSD / Windows strings, XML in UTF-16. function Text.utf16(b: buffer, o: number, n: number, bigEndian: boolean?): string local out = {} local k = 0 @@ -59,7 +55,6 @@ function Text.utf16(b: buffer, o: number, n: number, bigEndian: boolean?): strin return table.concat(out) end --- toUtf8(text, warnings?) -> text as UTF-8: strips a BOM; text that is not valid UTF-8 is read as Windows-1252 function Text.toUtf8(text: string, warnings: { string }?): string if string.sub(text, 1, 3) == "\239\187\191" then text = string.sub(text, 4) diff --git a/src/Rosetta/codecs/text/Url/init.luau b/src/Rosetta/codecs/text/Url/init.luau index 19b359b..04f7147 100644 --- a/src/Rosetta/codecs/text/Url/init.luau +++ b/src/Rosetta/codecs/text/Url/init.luau @@ -1,10 +1,7 @@ --!strict --!optimize 2 --- codecs/text/Url: RFC 3986 reference resolution (section 5.2), the classification of a playlist / manifest location (URL, --- Windows / UNC / POSIX local path, relative reference) and percent-encoding of bytes that may not appear in a URI --- (raw spaces and UTF-8 in playlists). Shared by the playlist formats (m3u / HLS, pls, xspf); later DASH / glTF URIs. --- Absorbed from playlist-luau 3fc7fd3 (same author, no third-party code): Url.luau, plus locate / base from its --- init.luau. Never throws. +-- codecs/text/Url: RFC 3986 reference resolution (section 5.2), local-path classification and percent-encoding. +-- Absorbed from playlist-luau 3fc7fd3 (same author, no third-party code). local Url = {} export type Location = { url: string, playable: boolean, reason: string?, [string]: any } @@ -17,7 +14,7 @@ export type Parts = { fragment: string?, } --- Splits a URI reference into its five components (RFC 3986 appendix B). +-- RFC 3986 appendix B: the five components of a URI reference function Url.split(ref: string): Parts local scheme, rest = string.match(ref, "^([%a][%w+%.%-]*):(.*)$") if not scheme then @@ -48,7 +45,7 @@ function Url.split(ref: string): Parts return { scheme = scheme, authority = authority, path = s, query = query, fragment = fragment } end --- Recomposes components (RFC 3986 section 5.3). +-- RFC 3986 section 5.3 function Url.join(p: Parts): string local out = {} if p.scheme then @@ -99,7 +96,7 @@ function Url.removeDotSegments(path: string): string return table.concat(output) end --- Resolves a reference against an absolute base URI (RFC 3986 section 5.2.2, strict). +-- RFC 3986 section 5.2.2 (strict) function Url.resolve(ref: string, base: string): string local r, b = Url.split(ref), Url.split(base) local t: Parts = { path = "" } @@ -136,15 +133,13 @@ function Url.resolve(ref: string, base: string): string return Url.join(t) end --- Percent-encodes the bytes that may not appear in a URI (controls, space, non-ASCII, "<>\"^`{|}" and "\\"), --- leaving existing %XX escapes and the reserved delimiters alone. +-- percent-encoded: controls, space, non-ASCII, "<>\"^`{|}" and "\\"; existing %XX escapes and reserved delimiters stay function Url.encodeUnsafe(s: string): string return (string.gsub(s, "[%z\1-\32\127-\255<>\"%^`{|}\\]", function(c: string): string return string.format("%%%02X", string.byte(c)) end)) end --- Is a location a local Windows path ("C:\x", "C:/x", "\\server\share", "\x")? function Url.isWindowsPath(s: string): boolean return string.match(s, "^%a:[\\/]") ~= nil or string.match(s, "^%a:$") ~= nil @@ -152,7 +147,6 @@ function Url.isWindowsPath(s: string): boolean or string.sub(s, 1, 1) == "\\" end --- The scheme of an absolute URI (lower case), or nil. Windows drive letters are not schemes. function Url.scheme(s: string): string? if Url.isWindowsPath(s) then return nil @@ -161,9 +155,6 @@ function Url.scheme(s: string): string? return if scheme then string.lower(scheme) else nil end --- locate(raw, base?, baseScheme?) -> { url, playable, reason? }: an entry location resolved against the playlist's --- base (from Url.base). Windows paths stay as they are and are local; relative paths without a base, file: URLs and --- schemes other than http(s) are not playable (reason says why). function Url.locate(raw: string, base: string?, baseScheme: string?): Location local loc = (string.match(raw, "^%s*(.-)%s*$") :: string) if Url.isWindowsPath(loc) then @@ -172,7 +163,6 @@ function Url.locate(raw: string, base: string?, baseScheme: string?): Location local scheme = Url.scheme(loc) local url = loc if not scheme and baseScheme == "windows" and base then - -- a playlist on a Windows disk: relative entries are paths next to it local dir = string.match(base, "^(.*[\\/])") or "" return { url = dir .. loc, playable = false, reason = "local path" } end @@ -181,7 +171,6 @@ function Url.locate(raw: string, base: string?, baseScheme: string?): Location url = Url.encodeUnsafe(Url.resolve(loc, loc)) end elseif base and baseScheme then - -- a relative reference: Windows separators become URL ones url = Url.resolve(Url.encodeUnsafe((string.gsub(loc, "\\", "/"))), base) scheme = baseScheme else @@ -195,8 +184,6 @@ function Url.locate(raw: string, base: string?, baseScheme: string?): Location return { url = url, playable = false, reason = "scheme " .. tostring(scheme) } end --- base(baseUrl?, warnings?) -> base, baseScheme: the base for Url.locate from the playlist's own URL or path ("windows" --- for a Windows path); a non-absolute base is ignored (with a warning) function Url.base(baseUrl: string?, warnings: { string }?): (string?, string?) if type(baseUrl) ~= "string" or baseUrl == "" then return nil, nil diff --git a/src/Rosetta/codecs/text/Xml/Parse.luau b/src/Rosetta/codecs/text/Xml/Parse.luau index 2a47422..61de16c 100644 --- a/src/Rosetta/codecs/text/Xml/Parse.luau +++ b/src/Rosetta/codecs/text/Xml/Parse.luau @@ -1,12 +1,7 @@ --!strict --!native --- codecs/text/Xml/Parse: the XML 1.0 pull parser behind codecs/text/Xml. Input decoding (UTF-8, UTF-16 LE / BE by BOM or --- by the first bytes, ISO-8859-1 / US-ASCII / Windows-1252 by the declaration), line-ending normalization, the --- well-formedness rules that matter (one root, matched tags, unique attributes, quoted values, no '<' in values, --- legal names, character references in range, no "--" in comments, no "]]>" in text), the five predefined entities, --- character references and internal general entities from the DOCTYPE (with an expansion limit). Not supported: --- external entities / DTDs (references to them are errors), entity values containing markup (taken as text), --- validation. Never throws: errors are events. +-- codecs/text/Xml/Parse: the XML 1.0 pull parser behind codecs/text/Xml: input decoding, line-ending normalization, +-- well-formedness checks, predefined entities, character references, internal DOCTYPE entities (expansion-limited). local Text = require("@rosetta/codecs/text/Text") local Types = require("@rosetta/Types") @@ -15,11 +10,11 @@ local Parse = {} local byte, sub, find, match, char, gsub, lower = string.byte, string.sub, string.find, string.match, string.char, string.gsub, string.lower export type Options = { - whitespace: boolean?, -- keep whitespace-only text (default false: dropped, except inside xml:space="preserve") - namespaces: boolean?, -- resolve namespace prefixes: "start" events carry the element's URI (default false) - entities: { [string]: string }?, -- extra general entities (name -> replacement text) - maxExpansion: number?, -- total characters produced by entity expansion (default 1e7; the billion laughs guard) - maxDepth: number?, -- element nesting limit (default 10000) + whitespace: boolean?, + namespaces: boolean?, + entities: { [string]: string }?, + maxExpansion: number?, + maxDepth: number?, } local NAME = "^[%a_:\128-\255][%w_:%.%-\128-\255]*" @@ -68,7 +63,6 @@ local function utf16(s: string, start: number, le: boolean): (string?, string?) return table.concat(out), nil end --- toUtf8(s) -> UTF-8 text (BOM removed), the encoding name | nil, message function Parse.toUtf8(s: string): (string?, string) local b1, b2, b3 = byte(s, 1, 3) if b1 == 0xEF and b2 == 0xBB and b3 == 0xBF then @@ -121,7 +115,7 @@ local function xmlDecl(data: string): { [string]: string }? local q, v, e = match(data, "^" .. key .. "[ \t\n]*=[ \t\n]*([\"'])(.-)%1()", ws) if q then if k > 1 and ws == p then - return nil -- no whitespace before + return nil end if (key == "version" and not match(v, "^1%.%d+$")) or (key == "encoding" and not match(v, "^%a[%w%._%-]*$")) @@ -141,17 +135,6 @@ local function xmlDecl(data: string): { [string]: string }? return out end --- the events iterator: next() -> event, a, b, c --- "decl", { version, encoding, standalone } the declaration --- "doctype", raw, info raw = the text between ""; info = { name, --- publicId, systemId, entities } --- "start", name, attrs (Types.object), ns ns: the element's namespace URI (opts.namespaces) or nil --- "end", name --- "text", s character data, entities decoded (whitespace-only dropped --- unless opts.whitespace) --- "cdata", s "comment", s "pi", target, data --- "error", message, offset then the iterator ends --- nil at the end of the document. function Parse.events(s: string, opts: Options?): () -> (string?, any, any, any) local o: Options = opts or {} local keepWs = o.whitespace == true @@ -178,7 +161,7 @@ function Parse.events(s: string, opts: Options?): () -> (string?, any, any, any) local rootSeen = false local rootDone = false local dead = false - local pending: { any }? = nil -- an "end" queued after a self-closing start + local pending: { any }? = nil local errMsg: string? = nil local errAt = 0 @@ -187,7 +170,6 @@ function Parse.events(s: string, opts: Options?): () -> (string?, any, any, any) return "error", msg, at - 1 end - -- decode entity / character references in raw text; nil on error (errMsg set) local decode: (raw: string, at: number, level: number) -> string? function decode(raw: string, at: number, level: number): string? if not find(raw, "&", 1, true) then @@ -265,7 +247,6 @@ function Parse.events(s: string, opts: Options?): () -> (string?, any, any, any) return nil end - -- a quoted literal at p -> its content, the position after it | nil local function literal(p: number): (string?, number) local q = byte(s, p) if q ~= 34 and q ~= 39 then @@ -277,7 +258,7 @@ function Parse.events(s: string, opts: Options?): () -> (string?, any, any, any) end return sub(s, p + 1, e - 1), e + 1 end - -- an ExternalID (SYSTEM "sys" | PUBLIC "pub" "sys") at p -> publicId, systemId, next | nil + -- ExternalID: SYSTEM "sys" | PUBLIC "pub" "sys" local function externalId(p: number): (string?, string?, number?) local kw = sub(s, p, p + 5) if kw == "SYSTEM" then @@ -311,7 +292,6 @@ function Parse.events(s: string, opts: Options?): () -> (string?, any, any, any) end return nil, nil, nil end - -- check an entity value's references and expand its character references (the rest expand when used) local function entityValue(v: string): string? if find(v, "%", 1, true) then return nil -- parameter-entity references are not allowed in the internal subset's markup @@ -345,8 +325,6 @@ function Parse.events(s: string, opts: Options?): () -> (string?, any, any, any) end return table.concat(parts) end - -- the DOCTYPE at i (just past " (string?, any, any, any) if not r or not match(s, NAME, r) then return nil, "bad " .. kw .. " declaration" end - -- skip to the closing '>' outside quotes while true do local c2 = byte(s, r) if c2 == nil then @@ -631,7 +608,6 @@ function Parse.events(s: string, opts: Options?): () -> (string?, any, any, any) end return "pi", target, data end - -- a start tag local name = match(s, NAME, i + 1) if not name then return fail(if i + 1 > n then "truncated tag" else "bad tag name", i + 1) @@ -692,7 +668,7 @@ function Parse.events(s: string, opts: Options?): () -> (string?, any, any, any) return fail(errMsg :: string, errAt) end if find(raw, "[\t\n]") then - -- attribute-value normalization: literal tab / newline become spaces (references stay) + -- XML 1.0 3.3.3 attribute-value normalization: literal tab / newline become spaces (references stay) v = decode((gsub(raw, "[\t\n]", " ")), r + 1, 0) :: string end if attrs[an] ~= nil then @@ -735,14 +711,13 @@ function Parse.events(s: string, opts: Options?): () -> (string?, any, any, any) stack[depth] = nil nsStack[depth] = nil preserve[depth] = nil - pending = { name } -- depth goes down when the queued "end" is returned + pending = { name } end return "start", name, attrs, uri end end end --- lookup(nsMaps...) helper for the DOM: the namespace URI of prefix, walking an element's ancestors function Parse.resolve(node: any, prefix: string): string? local p = node local key = if prefix == "" then "xmlns" else "xmlns:" .. prefix diff --git a/src/Rosetta/codecs/text/Xml/init.luau b/src/Rosetta/codecs/text/Xml/init.luau index 67f96ba..0377bb4 100644 --- a/src/Rosetta/codecs/text/Xml/init.luau +++ b/src/Rosetta/codecs/text/Xml/init.luau @@ -1,21 +1,6 @@ --!strict --- codecs/text/Xml: XML 1.0 parse (DOM and pull events) and serialize, the engine data/xml, SVG, DAE, 3MF, TMX, plist, ... --- use. New code. Supports: UTF-8 / UTF-16 / Latin-1 input, the predefined entities, character references, internal --- DOCTYPE entities (expansion limited), CDATA, comments, processing instructions, the XML declaration, namespaces --- (names stay qualified "prefix:local"; opts.namespaces adds each element's URI as node.ns; Xml.clark gives --- "{uri}local"), xml:space. Not supported: external entities / DTDs, validation, entity values containing markup. --- --- local Xml = require("@rosetta/codecs/text/Xml") --- local doc, err = Xml.decode(text) -- a "#document" node; doc.root is the root element --- for _, item in Xml.children(doc.root, "item") do print(item.attrs.id, Xml.text(item)) end --- for ev, a, b in Xml.events(text) do ... end -- "start" name attrs / "end" name / "text" s / ... (SAX-like) --- local s = Xml.encode(doc, { indent = 2 }) --- local e = Xml.element("svg", { width = "10" }, { Xml.element("rect") }) -- build trees --- --- Nodes (Types.XmlNode): { name, attrs (a Types.object: attribute order kept), children = { node | string }, --- parent }. Text children are strings. With opts.comments / opts.cdata / opts.pi, comments, CDATA sections and --- processing instructions are kept as "#comment" / "#cdata" / "#pi" nodes (text = the content, target = the PI --- target); otherwise CDATA merges into the text and the others are dropped. Never throws. +-- codecs/text/Xml: XML 1.0 parse (DOM and pull events) and serialize. New code. +-- Not supported: external entities / DTDs, validation, entity values containing markup. local Err = require("@rosetta/core/Err") local Types = require("@rosetta/Types") local Parse = require("@rosetta/codecs/text/Xml/Parse") @@ -24,15 +9,15 @@ local Xml = {} export type Node = Types.XmlNode export type DecodeOptions = Parse.Options & { - comments: boolean?, -- keep comments as "#comment" nodes (default false) - cdata: boolean?, -- keep CDATA sections as "#cdata" nodes (default false: merged into the text) - pi: boolean?, -- keep processing instructions as "#pi" nodes (default false) - parents: boolean?, -- set node.parent (default true) + comments: boolean?, + cdata: boolean?, + pi: boolean?, + parents: boolean?, } export type EncodeOptions = { - indent: (number | string)?, -- pretty print elements that hold only elements (default none) - declaration: boolean?, -- write (default: true for a "#document") - selfClose: boolean?, -- for empty elements (default true) + indent: (number | string)?, + declaration: boolean?, + selfClose: boolean?, } local find, gsub, sub, match = string.find, string.gsub, string.sub, string.match @@ -57,8 +42,6 @@ local function errCode(msg: string, at: number, n: number): string return Err.CORRUPT end --- events(src, opts?) -> iterator: event, a, b, c (see codecs/text/Xml/Parse: "decl", "doctype", "start" name attrs ns, --- "end" name, "text" s, "cdata" s, "comment" s, "pi" target data, and on bad input "error" Err as the last event) function Xml.events(src: string | buffer, opts: Parse.Options?): () -> (string?, any, any, any) local s, terr = text(src) local u, enc = nil, "" @@ -87,9 +70,6 @@ function Xml.events(src: string | buffer, opts: Parse.Options?): () -> (string?, end end --- decode(src, opts?) -> the "#document" node | nil, Err. doc.root = the root element; doc.declaration = { version, --- encoding, standalone }?; doc.doctype = { raw, name, publicId, systemId, entities }?; doc.children = the root plus --- any kept comments / PIs around it. function Xml.decode(src: string | buffer, opts: DecodeOptions?): (Node?, Err.Err?) local o: DecodeOptions = opts or {} local keepComments, keepCdata, keepPi = o.comments == true, o.cdata == true, o.pi == true @@ -144,9 +124,6 @@ function Xml.decode(src: string | buffer, opts: DecodeOptions?): (Node?, Err.Err return doc, nil end --- ------------------------------------------------------------------------------------------------ tree helpers --- element(name, attrs?, children?) -> a new element (attrs: a plain table (written sorted) or a Types.object; --- children: nodes or strings; their parent is set) function Xml.element(name: string, attrs: { [string]: string }?, children: { any }?): Node local a = attrs or Types.object() if not Types.isObject(a) then @@ -166,14 +143,12 @@ function Xml.element(name: string, attrs: { [string]: string }?, children: { any return node end --- document(root, declaration?) -> a "#document" node around root function Xml.document(root: Node, declaration: { [string]: string }?): Node local doc: any = { name = "#document", attrs = Types.object(), children = { root }, root = root, declaration = declaration } root.parent = doc return doc end --- append(parent, child) -> child (a node or a string), parent link set function Xml.append(parent: Node, child: any): any table.insert(parent.children, child) if type(child) == "table" then @@ -182,13 +157,10 @@ function Xml.append(parent: Node, child: any): any return child end --- setAttr(node, name, value): set (or with nil remove) an attribute, keeping the order function Xml.setAttr(node: Node, name: string, value: string?) Types.set(node.attrs, name, value) end --- children(node, name?) -> the element children (with that qualified name, or local name when name has no prefix and --- the child's does), in order function Xml.children(node: Node, name: string?): { Node } local out = {} for _, ch in node.children do @@ -201,7 +173,6 @@ function Xml.children(node: Node, name: string?): { Node } return out end --- child(node, name?) -> the first matching element child, or nil function Xml.child(node: Node, name: string?): Node? for _, ch in node.children do if type(ch) == "table" and string.byte(ch.name) ~= 35 then @@ -213,7 +184,6 @@ function Xml.child(node: Node, name: string?): Node? return nil end --- descendants(node, name?) -> every element below node (document order), optionally filtered as children() does function Xml.descendants(node: Node, name: string?): { Node } local out = {} local function walk(n: Node) @@ -230,7 +200,6 @@ function Xml.descendants(node: Node, name: string?): { Node } return out end --- text(node) -> all the character data below node, concatenated (CDATA included, comments / PIs not) function Xml.text(node: any): string if type(node) == "string" then return node @@ -254,7 +223,6 @@ function Xml.text(node: any): string return table.concat(parts) end --- prefix(name) / localName(name): the parts of a qualified name ("svg:rect" -> "svg", "rect"; "rect" -> "", "rect") function Xml.prefix(name: string): string return match(name, "^([^:]*):") or "" end @@ -262,14 +230,10 @@ function Xml.localName(name: string): string return match(name, ":(.*)$") or name end --- namespace(node, prefix?) -> the URI bound to prefix (default: the node's own prefix) at node, through its --- ancestors' xmlns attributes (needs parent links) function Xml.namespace(node: Node, prefix: string?): string? return Parse.resolve(node, prefix or Xml.prefix(node.name)) end --- clark(node, attrName?) -> "{uri}local" (ElementTree's notation) for the element, or for one of its attributes --- (unprefixed attributes have no namespace) function Xml.clark(node: Node, attrName: string?): string local name = attrName or node.name local prefix = Xml.prefix(name) @@ -283,11 +247,9 @@ function Xml.clark(node: Node, attrName: string?): string return name end --- ------------------------------------------------------------------------------------------------ encode local TEXT_ESC = { ["&"] = "&", ["<"] = "<", [">"] = ">", ["\r"] = " " } local ATTR_ESC = { ["&"] = "&", ["<"] = "<", [">"] = ">", ['"'] = """, ["\t"] = " ", ["\n"] = " ", ["\r"] = " " } --- escape(s) / escapeAttr(s): text / attribute-value escaping function Xml.escape(s: string): string return (gsub(s, "[&<>\r]", TEXT_ESC)) end @@ -299,7 +261,6 @@ local function badName(name: any): boolean return type(name) ~= "string" or not match(name, "^[%a_:\128-\255][%w_:%.%-\128-\255]*$") end --- encode(node, opts?) -> string | nil, Err. node: a "#document" or any node (an element, a comment, ...) function Xml.encode(node: Node, opts: EncodeOptions?): (string?, Err.Err?) local o: EncodeOptions = opts or {} local ind: string? = nil diff --git a/src/Rosetta/codecs/video/Dsp.luau b/src/Rosetta/codecs/video/Dsp.luau index f632ed7..e1cf87f 100644 --- a/src/Rosetta/codecs/video/Dsp.luau +++ b/src/Rosetta/codecs/video/Dsp.luau @@ -2,23 +2,9 @@ --!native --!optimize 2 -- codecs/video/Dsp: the 8x8 IDCT (bit-exact with ffmpeg -idct int) and half-pel motion compensation of MPEG codecs. --- Block DSP shared by the MPEG-style video codecs (MPEG-1 / MPEG-2, H.263 / Sorenson Spark): the IDCT put or added --- into 8-bit planes, constant (DC-only) blocks, half-pel motion compensation four samples at a time. Native, never --- throws (the caller keeps offsets in range). --- --- The IDCT is the Independent JPEG Group's jrevdct.c (the LL&M integer IDCT, CONST_BITS 13, PASS1_BITS 2) as ffmpeg --- ships it (libavcodec/jrevdct.c, IJG licence: licenses/libjpeg-README.ijg), translated mechanically: rows first, then --- columns, with every sparse-input special case of the original kept, because several of them use merged constants --- (FIX_1_306562965 for FIX_0_541196100 - FIX_1_847759065, ...) that round differently from the general case; that --- is what makes ffmpeg's `-idct int` output reproducible here. Changes: Luau, i32 coefficients in natural order --- (ffmpeg's LIBMPEG2 permutation is only a storage order), no int16 wrap of the intermediate values (identical for --- coefficients in the MPEG range), and the put / add clamping fused into the last pass. --- --- Dsp.idct(blk, dst, off, stride, add) -- blk: 64 i32 (256 bytes, row-major), left holding garbage: clear it --- Dsp.fill(dst, off, stride, v, add) -- an 8x8 block of constant v (a DC-only block: v = (dc + 4) >> 3) --- Dsp.mc(src, sStride, sOff, dst, dStride, dOff, w, h, hx, hy, avg) -- half-pel prediction of a w x h block --- Dsp.mcNoRound(src, sStride, sOff, dst, dStride, dOff, w, h, hx, hy) -- the same, averages rounded down (H.263+) --- Dsp.edge(src, stride, base, x, y, w, h, pw, ph, out) -- a block with edge samples repeated (EDGE_STRIDE) +-- The IDCT is IJG's jrevdct.c (LL&M, CONST_BITS 13, PASS1_BITS 2) as ffmpeg ships it (libavcodec/jrevdct.c, IJG +-- licence: licenses/libjpeg-README.ijg), translated mechanically: its sparse-input special cases stay because their +-- merged constants round differently. Natural-order i32 coefficients, no int16 wrap, put / add clamping in pass 2. local Dsp = {} local readu8 = buffer.readu8 @@ -42,7 +28,6 @@ end Dsp.CLAMP = CLAMP Dsp.COFF = COFF --- ------------------------------------------------------------------------------------------------ IDCT function Dsp.idct(blk: buffer, dst: buffer, off: number, stride: number, add: boolean) local tmp0, tmp1, tmp2, tmp3 = 0, 0, 0, 0 local tmp10, tmp11, tmp12, tmp13 = 0, 0, 0, 0 @@ -634,9 +619,7 @@ function Dsp.idct(blk: buffer, dst: buffer, off: number, stride: number, add: bo end end --- ------------------------------------------------------------------------------------------------ blocks --- an 8x8 block of the constant v put into dst (add = false) or added to it, clamped (a DC-only block: the IDCT --- of a lone DC coefficient dc is (dc + 4) >> 3 everywhere) +-- the IDCT of a lone DC coefficient dc is (dc + 4) >> 3 everywhere function Dsp.fill(dst: buffer, off: number, stride: number, v: number, add: boolean) if not add then local c = readu8(CLAMP, v + COFF) * 0x01010101 @@ -655,12 +638,9 @@ function Dsp.fill(dst: buffer, off: number, stride: number, v: number, add: bool end end --- ------------------------------------------------------------------------------------------------ motion --- Motion-compensated prediction of a w x h block (w a multiple of 4) from src (rows sStride apart, from sOff) to dst --- (dStride, dOff): half-pel flags hx / hy, rounding up (MPEG-1 / 2, H.263 rounding_type 0); avg averages into what --- dst holds (the second prediction of a bidirectional block, rounding up). Strides are twice the plane width for --- field prediction. Four bytes at a time: avg(a, b) = (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. +-- rounding up (MPEG-1 / 2, H.263 rounding_type 0); strides are twice the plane width for field prediction. +-- Four bytes at a time: avg(a, b) = (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. function Dsp.mc(src: buffer, sStride: number, sOff: number, dst: buffer, dStride: number, dOff: number, w: number, h: number, hx: number, hy: number, avg: boolean) for _ = 1, h do for i = 0, w - 4, 4 do @@ -693,8 +673,7 @@ function Dsp.mc(src: buffer, sStride: number, sOff: number, dst: buffer, dStride end end --- Dsp.mc with the half-sample averages rounded down, (a + b) >> 1 and (a + b + c + d + 1) >> 2 (H.263 rounding type 1: --- RTYPE of an H.263+ picture header, MPEG-4 rounding_control). No averaging into dst. +-- averages rounded down, (a + b) >> 1 and (a + b + c + d + 1) >> 2 (H.263 rounding type 1, MPEG-4 rounding_control) function Dsp.mcNoRound(src: buffer, sStride: number, sOff: number, dst: buffer, dStride: number, dOff: number, w: number, h: number, hx: number, hy: number) if hx == 0 and hy == 0 then Dsp.mc(src, sStride, sOff, dst, dStride, dOff, w, h, 0, 0, false) @@ -721,9 +700,8 @@ function Dsp.mcNoRound(src: buffer, sStride: number, sOff: number, dst: buffer, end end --- Edge emulation: the (w + 1) x (h + 1) samples at (x, y) of a pw x ph plane (row r at base + r * stride) copied to --- out (rows EDGE_STRIDE apart), coordinates clamped into the plane, so a vector pointing outside the picture --- predicts from repeated edge samples (w + 1 <= EDGE_STRIDE, h + 1 <= 33; out holds EDGE_SIZE bytes). +-- edge emulation: coordinates clamped into the plane, so a vector pointing outside the picture predicts from repeated +-- edge samples (w + 1 <= EDGE_STRIDE, h + 1 <= 33) Dsp.EDGE_STRIDE = 32 Dsp.EDGE_SIZE = 32 * 34 + 4 function Dsp.edge(src: buffer, stride: number, base: number, x: number, y: number, w: number, h: number, pw: number, ph: number, out: buffer) diff --git a/src/Rosetta/codecs/video/H263/Decoder.luau b/src/Rosetta/codecs/video/H263/Decoder.luau index 8cd147f..3cf5f8c 100644 --- a/src/Rosetta/codecs/video/H263/Decoder.luau +++ b/src/Rosetta/codecs/video/H263/Decoder.luau @@ -1,30 +1,9 @@ --!strict --!native --!optimize 2 --- codecs/video/H263/Decoder: the H.263 / Sorenson Spark decoding core (native, never throws). Written from ITU-T --- H.263 (01/2005) and Adobe's Video File Format Specification v10 (the H.263VIDEOPACKET of Sorenson Spark). --- --- H.263: picture headers with PTYPE (sub-QCIF .. 16CIF) and PLUSPTYPE (H.263+: standard and custom picture formats, --- custom pixel aspect ratios and picture clock frequencies, the rounding type RTYPE), I and P pictures, GOB headers --- (with or without stuffing), MCBPC / CBPY / MVD / TCOEF VLCs, DQUANT, the H.263 dequantiser, half-sample motion --- compensation with the H.263 chroma vector rounding, unrestricted motion vectors (Annex D in both header forms, the --- PLUSPTYPE form with its reversible MVD codes and unlimited range), slice structure (Annex K, without rectangular --- slices) and the extended escape of Annex T. Sorenson Spark --- (FLV1): its picture header (sizes, disposable inter pictures, which never become the reference), its 7 / 11-bit --- escape codes (version 1), unrestricted vectors. Not supported (the picture is refused with an "unsupported:" message): --- syntax-based arithmetic coding, advanced prediction (Annex F: four vectors and OBMC), PB / B / EI / EP pictures, --- advanced intra coding, the deblocking filter, rectangular slices, reference picture selection / resampling, reduced --- resolution update, independent segments, the alternative inter VLC, modified quantisation (other than the escape). --- --- The IDCT and motion compensation are codecs/video/Dsp, the dequantiser is the H.263 one (|REC| = QUANT * (2 |LEVEL| --- + 1), minus 1 for an even QUANT, as ffmpeg without the -2048..2047 saturation), and vectors pointing outside the reference read --- repeated edge samples of the macroblock-aligned picture, so valid streams decode exactly as `ffmpeg -idct int` --- (tests/codecs/h263.luau). Corrupt data ends the picture: the rest is copied from the reference (state.errors). --- --- local core = D.new(flv, maxPixels) --- local hdr, msg = D.header(buf, off, len, flv, core.state.opp) -- the picture header (no decoding) --- local store, msg = core.decode(buf, off, len) -- one picture -> the Store decoded into (decoder-owned) --- core.reset() -- forget the reference (after a seek) +-- codecs/video/H263/Decoder: the H.263 / Sorenson Spark decoding core, from ITU-T H.263 (01/2005) and Adobe's Video +-- File Format Specification v10 (H.263VIDEOPACKET). Dequantiser |REC| = QUANT * (2 |LEVEL| + 1), minus 1 for an even +-- QUANT; vectors outside the reference read repeated edge samples of the macroblock-aligned picture, as ffmpeg. local Tb = require("@rosetta/codecs/video/H263/Tables") local Dsp = require("@rosetta/codecs/video/Dsp") @@ -67,7 +46,7 @@ export type Opp = { customPcf: boolean, umv: boolean, ss: boolean, -- slice structured (Annex K) - options: string?, -- the unsupported options set, or nil + options: string?, width: number, height: number, } @@ -84,15 +63,15 @@ export type Header = { umv: boolean, -- unrestricted vectors, baseline form (long vectors) umvPlus: boolean, -- unrestricted vectors, PLUSPTYPE form rounding: number, -- RTYPE (0: half-sample averages round up) - plus: boolean, -- PLUSPTYPE + plus: boolean, ss: boolean, -- slice structured (Annex K) cpm: boolean, deblock: boolean, -- Sorenson's deblocking hint (not applied, as ffmpeg) aspect: number?, -- PLUSPTYPE pixel aspect ratio code (15: aspectNum / aspectDen) aspectNum: number?, aspectDen: number?, - opp: Opp?, -- the PLUSPTYPE options in force - bitPos: number, -- absolute bit position of the first macroblock + opp: Opp?, + bitPos: number, } export type Store = { @@ -107,13 +86,11 @@ export type Store = { disposable: boolean, } --- ------------------------------------------------------------------------------------------------ header -- the length of a slice's MBA field for a picture of n macroblocks (table K.2) function D.mbaBits(n: number): number return if n <= 48 then 6 elseif n <= 99 then 7 elseif n <= 396 then 9 elseif n <= 1584 then 11 elseif n <= 6336 then 13 else 14 end --- n (<= 24) bits at bit position p of buf, zeros past endByte local function bitsAt(buf: buffer, endByte: number, p: number, n: number): number local v = 0 for k = p, p + n - 1 do @@ -124,8 +101,7 @@ local function bitsAt(buf: buffer, endByte: number, p: number, n: number): numbe return v end --- the byte offset of the first picture start code in buf[off, off + len) (H.263: 22 bits 0..01 00000; Sorenson: --- 17 bits 0..01 and version 0 / 1), or -1 +-- picture start code: H.263 22 bits 0..01 00000; Sorenson 17 bits 0..01, then version 0 / 1 local function findStart(buf: buffer, off: number, len: number, flv: boolean): number local mask = if flv then 0xF8 else 0xFC for i = off, off + len - 3 do @@ -136,8 +112,7 @@ local function findStart(buf: buffer, off: number, len: number, flv: boolean): n return -1 end --- header(buf, off, len, flv, opp?) -> Header | nil, message: the picture header of the first picture in --- buf[off, off + len); opp: the PLUSPTYPE options of the previous picture (pictures with UFEP = 0 keep them) +-- pictures with UFEP = 0 keep the previous picture's PLUSPTYPE options (opp) function D.header(buf: buffer, off: number, len: number, flv: boolean, opp: Opp?): (Header?, string?) if off < 0 or len < 0 or off + len > buffer.len(buf) then return nil, "bad range" @@ -340,7 +315,6 @@ function D.header(buf: buffer, off: number, len: number, flv: boolean, opp: Opp? return h, nil end --- ------------------------------------------------------------------------------------------------ decoder export type Core = { decode: (buf: buffer, off: number, len: number) -> (Store?, string?), reset: () -> (), @@ -365,12 +339,10 @@ function D.new(flv: boolean, maxPixels: number?): Core opp = nil :: Opp?, maxPixels = maxPixels or 4096 * 2304, } - -- bitstream local data = buffer.create(64 * 1024 + PAD) local endBits = 0 local pos = 0 local err = false - -- picture local W, H = 0, 0 local mbW, mbH = 0, 0 local ls, cs, lh, chh = 0, 0, 0, 0 -- luma / chroma strides, plane heights @@ -438,8 +410,7 @@ function D.new(flv: boolean, maxPixels: number?): Core state.width, state.height = w, h end - -- one 8x8 block: intra (INTRADC, then the coded coefficients from position 1) put into dst, or an inter block's - -- coefficients added to the prediction already in dst + -- intra blocks: INTRADC, then the coded coefficients from position 1 local function block(intra: boolean, coded: boolean, dst: buffer, off: number, stride: number): boolean local i = 0 local dcOnly = true @@ -551,7 +522,6 @@ function D.new(flv: boolean, maxPixels: number?): Core return true end - -- one motion vector component from its prediction (half samples) local function motion(pred: number): number if umvPlus then -- reversible codes (Annex D.2): "1" = 0, else 0 x0 (1 x)* 0, the last x the sign @@ -591,7 +561,6 @@ function D.new(flv: boolean, maxPixels: number?): Core return (v + 32) % 64 - 32 -- the code pair's value in -16 .. 15.5 end - -- the prediction of macroblock (col, row) from the reference, vector (mx, my) in half samples local function predict(col: number, row: number, mx: number, my: number) local hx, hy = mx % 2, my % 2 local sx, sy = col * 16 + (mx - hx) // 2, row * 16 + (my - hy) // 2 @@ -619,7 +588,6 @@ function D.new(flv: boolean, maxPixels: number?): Core end end - -- a macroblock copied from the reference (not coded, or concealed); mid-grey without one local function copyMb(col: number, row: number) local yo, co = row * 16 * ls + col * 16, row * 8 * cs + col * 8 if ref then @@ -636,9 +604,6 @@ function D.new(flv: boolean, maxPixels: number?): Core end end - -- macroblock (col, row) of a picture (P: an inter picture; top: within the first macroblock columns' worth of - -- the picture / a GOB or slice with a header, whose vector predictions do not look up; first: the first - -- macroblock of a slice, whose left neighbour is outside). false on bad data. local function macroblock(col: number, row: number, P: boolean, top: boolean, first: boolean): boolean if pos > endBits then return false @@ -732,7 +697,6 @@ function D.new(flv: boolean, maxPixels: number?): Core return true end - -- an optional GOB header at a GOB boundary: its GN and GQUANT, or nil local function gobHeader(cpm: boolean): (number?, number?) if not startCode() then return nil, nil @@ -745,7 +709,6 @@ function D.new(flv: boolean, maxPixels: number?): Core return gn, read(5) end - -- an optional slice header (Annex K, no rectangular slices): its MBA and SQUANT, or nil local function sliceHeader(cpm: boolean, mbaBits: number, sepb2: boolean): (number?, number?) if not startCode() then return nil, nil @@ -869,7 +832,6 @@ function D.new(flv: boolean, maxPixels: number?): Core if hdr.opp then state.opp = hdr.opp end - -- the data from the header on, with zero padding local need = len + PAD if buffer.len(data) < need then data = buffer.create(need) diff --git a/src/Rosetta/codecs/video/H263/Tables.luau b/src/Rosetta/codecs/video/H263/Tables.luau index 0f427db..97d2179 100644 --- a/src/Rosetta/codecs/video/H263/Tables.luau +++ b/src/Rosetta/codecs/video/H263/Tables.luau @@ -1,20 +1,15 @@ --!strict --- codecs/video/H263/Tables: the H.263 variable-length codes (ITU-T H.263 (01/2005): table 7 MCBPC for I-pictures, --- table 8 MCBPC for P-pictures, table 12 DQUANT, table 13 CBPY, table 14 MVD, table 16 TCOEF, the zigzag scan of --- figure 14), written from the specification as bit strings and turned into flat lookup tables at load time. --- --- A flat table is indexed by the next K bits of the stream and holds len * 65536 + value (len 0: not a code). --- MCBPC_I / MCBPC_P (K = 9): value = macroblock type * 4 + CBPC (types 0 INTER, 1 INTER+Q, 2 INTER4V, 3 INTRA, --- 4 INTRA+Q), STUFFING for the stuffing code --- CBPY (K = 6): the intra CBPY (Y1 the most significant bit; inter macroblocks use 15 - value) --- MVD (K = 12): the magnitude 0..32 in half samples (a sign bit follows every code but "1", which is 0) --- TCOEF (K = 12): last * 1024 + run * 16 + level (a sign bit follows), ESCAPE for the escape code +-- codecs/video/H263/Tables: the H.263 variable-length codes (ITU-T H.263 (01/2005) tables 7 / 8 MCBPC, 12 DQUANT, +-- 13 CBPY, 14 MVD, 16 TCOEF, figure 14 zigzag). Flat tables indexed by the next K bits: len * 65536 + value (len 0: none). +-- MCBPC_I / MCBPC_P (K = 9): type * 4 + CBPC (0 INTER, 1 INTER+Q, 2 INTER4V, 3 INTRA, 4 INTRA+Q), STUFFING +-- CBPY (K = 6): the intra CBPY, Y1 the MSB (inter macroblocks use 15 - value) +-- MVD (K = 12): magnitude 0..32 in half samples (a sign bit follows every code but "1") +-- TCOEF (K = 12): last * 1024 + run * 16 + level (a sign bit follows), ESCAPE local T = {} T.STUFFING = 255 T.ESCAPE = 0xFFFF --- builds a K-bit flat table from { bits, value } pairs local function flat(codes: { { any } }, k: number): buffer local lut = buffer.create(4 * 2 ^ k) for _, c in codes do diff --git a/src/Rosetta/codecs/video/H263/init.luau b/src/Rosetta/codecs/video/H263/init.luau index b8de4e1..38a7ed2 100644 --- a/src/Rosetta/codecs/video/H263/init.luau +++ b/src/Rosetta/codecs/video/H263/init.luau @@ -1,20 +1,7 @@ --!strict -- codecs/video/H263: an H.263 / H.263+ and Sorenson Spark (FLV1) video decoder, bit-exact with ffmpeg -idct int. --- ITU-T H.263 baseline and the H.263+ picture header. Written from ITU-T H.263 (01/2005) and Adobe's Video File Format Specification v10; the decoding core is --- H263/Decoder.luau (native), the IDCT and motion compensation codecs/video/Dsp, so the output planes equal --- `ffmpeg -idct int` (tests/codecs/h263.luau). Supports sub-QCIF .. 16CIF and H.263+ custom sizes, I and P pictures, --- GOB headers, the rounding type, unrestricted motion vectors (Annex D), Sorenson's escape codes and disposable inter --- pictures. Not supported (UNSUPPORTED): arithmetic coding, advanced prediction / four vectors, PB / B / EI / EP --- pictures and the other H.263+ coding options (advanced intra coding, deblocking filter, slices, ...). --- --- local dec = H263.new({ flv = false }) -- flv = true: Sorenson Spark (FLV1) --- local frame, err = dec:decode(packetData, off?, len?) -- one picture -> Frame (planes decoder-owned) --- local img = H263.frameImage(frame) -- a fresh yuv420p Types.Image (limited range, BT.601) --- local img, err = dec:image(packetData) -- both at once --- local info = H263.header(data, off?, len?, flv?) -- the picture header: width, height, ptype, ... --- dec:reset() -- after a seek: wait for the next I picture --- --- Nothing here throws: bad arguments and bad data come back as nil, Err. +-- From ITU-T H.263 (01/2005) and Adobe's Video File Format Specification v10. Annex D UMV, GOB headers and Sorenson +-- escapes are supported; arithmetic coding, advanced prediction, PB / B / EI / EP and other H.263+ options are not. local Err = require("@rosetta/core/Err") local Types = require("@rosetta/Types") local D = require("@rosetta/codecs/video/H263/Decoder") @@ -29,22 +16,21 @@ export type Header = D.Header export type Frame = { width: number, height: number, - -- decoder-owned planes, valid until the next decode: luma stride `stride`, chroma stride stride / 2 y: buffer, cb: buffer, cr: buffer, stride: number, pictureType: number, -- 1 I, 2 P keyframe: boolean, - disposable: boolean, -- a Sorenson disposable inter picture (not used as a reference) + disposable: boolean, temporalReference: number, - index: number, -- pictures returned so far + index: number, flv: boolean, } export type Options = { - flv: boolean?, -- Sorenson Spark (FLV1) bitstreams (default false: H.263) - maxPixels: number?, -- larger pictures are refused (LIMIT; default 4096 * 2304) + flv: boolean?, + maxPixels: number?, } local Decoder = {} @@ -80,8 +66,6 @@ local function span(data: any, off: number?, len: number?): (buffer?, number, nu return b, o, n end --- Decodes one picture (a container packet or one picture of an elementary stream). A picture with damaged --- macroblock data still comes back (the damaged part copied from the reference; stats.errors counts them). function Decoder.decode(self: Decoder, data: buffer | string, off: number?, len: number?): (Frame?, Err.Err?) local b, o, n = span(data, off, len) if not b then @@ -111,7 +95,6 @@ function Decoder.decode(self: Decoder, data: buffer | string, off: number?, len: }, nil end --- decode + frameImage function Decoder.image(self: Decoder, data: buffer | string, off: number?, len: number?): (Types.Image?, Err.Err?) local f, err = self:decode(data, off, len) if not f then @@ -120,13 +103,10 @@ function Decoder.image(self: Decoder, data: buffer | string, off: number?, len: return H263.frameImage(f), nil end --- Forgets the reference picture (after a seek: P pictures fail until the next I picture). function Decoder.reset(self: Decoder) self._core.reset() end --- frameImage(frame) -> a fresh yuv420p Types.Image of the frame, cropped to width x height (chroma ceil(w / 2) x --- ceil(h / 2)), meta.yuv = limited range BT.601; nil for a value that is not a Frame function H263.frameImage(frame: Frame): Types.Image? if type(frame) ~= "table" or type(frame.y) ~= "buffer" or type(frame.cb) ~= "buffer" or type(frame.cr) ~= "buffer" then return nil @@ -159,8 +139,6 @@ function H263.frameImage(frame: Frame): Types.Image? return img end --- header(data, off?, len?, flv?) -> Header (width, height, ptype 1 I / 2 P, quant, tr, plus, umv, ...) | nil, Err: --- the first picture header in the data, without decoding (containers use it for the track size) function H263.header(data: buffer | string, off: number?, len: number?, flv: boolean?): (Header?, Err.Err?) local b, o, n = span(data, off, len) if not b then diff --git a/src/Rosetta/codecs/video/H264/Bitstream.luau b/src/Rosetta/codecs/video/H264/Bitstream.luau index 9750fde..de143f8 100644 --- a/src/Rosetta/codecs/video/H264/Bitstream.luau +++ b/src/Rosetta/codecs/video/H264/Bitstream.luau @@ -1,11 +1,8 @@ --!strict --!native --!optimize 2 --- codecs/video/H264/Bitstream: NAL unit framing and the RBSP bit reader of ITU-T H.264 (7.3 / 7.4 / 9.1): Annex B start --- code splitting, AVCC length-prefixed samples, avcC (AVCDecoderConfigurationRecord, ISO/IEC 14496-15 5.3.3) --- parsing, emulation-prevention removal, and the u(n) / ue(v) / se(v) / te(v) readers. Written from the spec. --- Never throws: reads past the end of an RBSP return zero bits (the buffer carries 8 zero bytes of padding and every --- read is range-checked), and callers check `r.pos > r.size` once per syntax structure. +-- codecs/video/H264/Bitstream: NAL unit framing and the RBSP bit reader of ITU-T H.264 (7.3 / 7.4 / 9.1): Annex B, +-- AVCC, avcC (AVCDecoderConfigurationRecord, ISO/IEC 14496-15 5.3.3), emulation prevention, u(n) / ue(v) / se(v) / te(v). local Bitstream = {} local readu8 = buffer.readu8 @@ -13,15 +10,13 @@ local band, lshift = bit32.band, bit32.lshift export type Reader = { buf: buffer, -- the RBSP (emulation prevention removed) followed by 8 zero bytes - pos: number, -- bit position + pos: number, size: number, -- RBSP length in bits (up to the end of the data, trailing bits included) stop: number, -- bit position of the rbsp_stop_one_bit (size when there is none) - n: number, -- buffer length in bytes + n: number, } --- ------------------------------------------------------------------------------------------------ framing --- splitAnnexB(buf, off, len) -> { off1, len1, off2, len2, ... }: NAL unit payload ranges between start codes --- (00 00 01, with any leading zero bytes); trailing zero bytes of a NAL are dropped. +-- start codes are 00 00 01 with any leading zero bytes; trailing zero bytes of a NAL are dropped function Bitstream.splitAnnexB(buf: buffer, off: number, len: number): { number } local out = {} local e = off + len @@ -63,7 +58,6 @@ function Bitstream.splitAnnexB(buf: buffer, off: number, len: number): { number return out end --- isAnnexB(buf, off, len) -> true when the data starts with a start code (00 00 01 or 00 00 00 01) function Bitstream.isAnnexB(buf: buffer, off: number, len: number): boolean if len >= 3 and readu8(buf, off) == 0 and readu8(buf, off + 1) == 0 then local b2 = readu8(buf, off + 2) @@ -75,8 +69,6 @@ function Bitstream.isAnnexB(buf: buffer, off: number, len: number): boolean return false end --- splitLength(buf, off, len, size) -> NAL ranges of a length-prefixed (AVCC / MP4 sample) buffer, or nil when a --- length runs past the end (the NALs before it are kept in the second result) function Bitstream.splitLength(buf: buffer, off: number, len: number, size: number): ({ number }?, { number }) local out = {} local e = off + len @@ -99,8 +91,6 @@ function Bitstream.splitLength(buf: buffer, off: number, len: number, size: numb return out, out end --- parseAvcC(buf, off, len) -> { lengthSize, profile, level, nals = { off, len, ... } (SPS then PPS, + SPS ext) } | --- nil, message function Bitstream.parseAvcC(buf: buffer, off: number, len: number): (any, string?) if len < 7 then return nil, "truncated: avcC shorter than 7 bytes" @@ -140,9 +130,7 @@ function Bitstream.parseAvcC(buf: buffer, off: number, len: number): (any, strin return cfg, nil end --- ------------------------------------------------------------------------------------------------ rbsp --- reader(buf, off, len, skip) -> Reader over the RBSP of a NAL unit's bytes [off, off + len), the first `skip` --- bytes (the NAL header) left out; emulation_prevention_three_byte (00 00 03) removed. +-- emulation_prevention_three_byte (00 00 03) is removed function Bitstream.reader(buf: buffer, off: number, len: number, skip: number): Reader local out = buffer.create(len + 8) local o = 0 @@ -178,7 +166,6 @@ function Bitstream.reader(buf: buffer, off: number, len: number, skip: number): return { buf = out, pos = 0, size = o * 8, stop = stop, n = o + 8 } end --- ------------------------------------------------------------------------------------------------ bits -- Plain arithmetic instead of bit32 (LuaJIT runs bit32 through compat wrappers whose sign fix-ups split traces). local P2 = table.create(33, 1) -- P2[k + 1] = 2^k for k = 0, 32 do @@ -196,7 +183,6 @@ for x = 0, 255 do end Bitstream.LZ8 = LZ8 --- clz32(v) -> leading zero bits of a 32-bit value local function clz32(v: number): number if v >= 16777216 then return LZ8[v // 16777216 + 1] @@ -209,7 +195,6 @@ local function clz32(v: number): number end Bitstream.clz32 = clz32 --- peekAt(b, n, pos) -> the 32 bits at bit position pos of buffer b (n bytes), zeros past the end local function peekAt(b: buffer, n: number, pos: number): number local p = pos // 8 if p + 5 > n then @@ -224,20 +209,17 @@ local function peekAt(b: buffer, n: number, pos: number): number end Bitstream.peekAt = peekAt --- peek32(r) -> the next 32 bits (zeros past the end) local function peek32(r: Reader): number return peekAt(r.buf, r.n, r.pos) end Bitstream.peek32 = peek32 --- u(r, n) -> n bits (n 1..32) as an unsigned number function Bitstream.u(r: Reader, n: number): number local v = peekAt(r.buf, r.n, r.pos) r.pos += n return v // P2[33 - n] end --- u1(r) -> one bit function Bitstream.u1(r: Reader): number local pos = r.pos r.pos = pos + 1 @@ -248,7 +230,7 @@ function Bitstream.u1(r: Reader): number return (readu8(r.buf, p) // P2[8 - (pos - p * 8)]) % 2 end --- ue(r) -> ue(v); a code with more than 31 leading zeros returns 2^32 (out of range for every syntax element) +-- more than 31 leading zeros returns 2^32 (out of range for every syntax element) local function ue(r: Reader): number local v = peekAt(r.buf, r.n, r.pos) if v == 0 then @@ -268,7 +250,6 @@ local function ue(r: Reader): number end Bitstream.ue = ue --- se(r) -> se(v) function Bitstream.se(r: Reader): number local k = ue(r) if k % 2 == 1 then @@ -277,7 +258,6 @@ function Bitstream.se(r: Reader): number return -(k // 2) end --- te(r, range) -> te(v) with the given range (max value) function Bitstream.te(r: Reader, range: number): number if range == 1 then return 1 - Bitstream.u1(r) @@ -285,7 +265,7 @@ function Bitstream.te(r: Reader, range: number): number return ue(r) end --- moreData(r) -> more_rbsp_data() +-- more_rbsp_data() function Bitstream.moreData(r: Reader): boolean return r.pos < r.stop end diff --git a/src/Rosetta/codecs/video/H264/Cabac.luau b/src/Rosetta/codecs/video/H264/Cabac.luau index 9ab2343..93e64be 100644 --- a/src/Rosetta/codecs/video/H264/Cabac.luau +++ b/src/Rosetta/codecs/video/H264/Cabac.luau @@ -1,12 +1,9 @@ --!strict --!native --!optimize 2 --- codecs/video/H264/Cabac: slice data and macroblock layer with CABAC entropy coding (ITU-T H.264 7.3.4, 7.3.5, 9.3): the --- arithmetic decoding engine (9.3.1.2 / 9.3.3.2), context initialisation (9.3.1.1), the binarizations and context --- index increments of every syntax element (9.3.2 / 9.3.3.1) and residual_block_cabac for 4x4, 8x8 and DC blocks. --- Coefficients are dequantised as they are placed. Written from the spec; tables from Tables. --- The engine keeps codIOffset with `nb` look-ahead bits (low = offset * 2^nb + next bits), so renormalisation is one --- multiply and bytes are fetched one at a time. Never throws: returns false, "message" on bad data. +-- codecs/video/H264/Cabac: slice data and macroblock layer with CABAC entropy coding (ITU-T H.264 7.3.4, 7.3.5, 9.3): +-- engine (9.3.1.2 / 9.3.3.2), context init (9.3.1.1), binarizations and ctxIdxInc (9.3.2 / 9.3.3.1), residual_block_cabac. +-- codIOffset is kept with `nb` look-ahead bits (low = offset * 2^nb + next bits), so renormalisation is one multiply. local Bitstream = require("@rosetta/codecs/video/H264/Bitstream") local Tables = require("@rosetta/codecs/video/H264/Tables") local Mb = require("@rosetta/codecs/video/H264/Mb") @@ -19,7 +16,6 @@ local BLK_X, BLK_Y = Mb.BLK_X, Mb.BLK_Y local Cabac = {} --- ------------------------------------------------------------------------------------------------ engine local RANGE_LPS = Tables.RANGE_LPS local TRANS = Tables.TRANS local POW2 = table.create(40, 1) @@ -51,7 +47,6 @@ for st = 0, 127 do end end --- the engine (one slice at a time) local ebuf: buffer = buffer.create(1) local epos, elimit = 0, 0 local erange, elow, enb = 510, 0, 0 @@ -66,8 +61,7 @@ local function refill() enb += 8 end --- decision(ctx) -> bin (9.3.3.2.1), branch-free apart from the byte refill: the LPS test is min(1, low // scaled) --- (low < 2.5 * scaled always), the state step and the bin come from tables +-- decision (9.3.3.2.1): the LPS test is min(1, low // scaled) (low < 2.5 * scaled always) local function decision(ctx: number): number local s = ST[ctx + 1] local range = erange @@ -117,7 +111,6 @@ local function terminate(): number return 0 end --- start the engine at byte p of the rbsp local function engineInit(b: buffer, p: number, limit: number) ebuf, epos, elimit = b, p, limit elow, enb = 0, -9 @@ -147,7 +140,6 @@ local function initContexts(sliceQp: number, model: number) end end --- ------------------------------------------------------------------------------------------------ residual local ZZ4, ZZ8 = Tables.ZIGZAG4, Tables.ZIGZAG8 local SIG8, LAST8 = Tables.SIG8, Tables.LAST8 local CAT_CBF = { 0, 4, 8, 12, 16 } @@ -156,8 +148,7 @@ local CAT_ABS = { 0, 10, 20, 30, 39 } local MAXC = { 16, 15, 16, 4, 15, 64 } local SIGPOS = table.create(64, 0) --- block(cat, out, base, mul, div) -> number of coefficients (cat 0..5); coded_block_flag is decoded by the caller. --- Positions: cat 0 / 2 zig-zag, 1 / 4 zig-zag from 1, 3 raster 0..3, 5 the 8x8 zig-zag +-- positions: cat 0 / 2 zig-zag, 1 / 4 zig-zag from 1, 3 raster 0..3, 5 the 8x8 zig-zag local SCAN = {} do local ac = table.create(15, 0) @@ -266,7 +257,6 @@ local function block(cat: number, out: { number }, base: number, mul: { number } return n end --- ------------------------------------------------------------------------------------------------ syntax elements -- condition helpers on neighbouring macroblocks (addresses are 1-based here) local function leftAddr(S: any, M: any): number return ((M.aL) and (M.addr) or (0)) @@ -405,7 +395,6 @@ local function bSubType(): number return t end --- ref_idx for the partition whose top-left 4x4 is (x, y); rgt: the ref > 0 grid of the list local function refIdx(S: any, M: any, rgt: { number }, x: number, y: number): number local g = M.g0 + y * S.w4 + x local inc = 0 @@ -430,7 +419,7 @@ local function refIdx(S: any, M: any, rgt: { number }, x: number, y: number): nu return v end --- mvd component (comp 0 x, 1 y) for the partition at (x, y); grid holds |mvd| (2 per 4x4) +-- the mvd grid holds |mvd| (2 per 4x4) local function mvd(S: any, M: any, grid: { number }, x: number, y: number, comp: number): number local g = M.g0 + y * S.w4 + x local sum = 0 @@ -651,7 +640,6 @@ local function dcCond(S: any, M: any, bit: number, intra: boolean): (number, num return ca, cb end --- ------------------------------------------------------------------------------------------------ residual local function residuals(S: any, M: any): boolean local kind = M.kind local cbp = M.cbp @@ -776,7 +764,6 @@ local function clearCounts(M: any) end end --- ------------------------------------------------------------------------------------------------ macroblock local SUBB_PF = { 0, 1, 2, 3, 1, 1, 2, 2, 3, 3, 1, 2, 3 } local SUBB_SHAPE = { 0, 0, 0, 0, 1, 2, 1, 2, 1, 2, 3, 3, 3 } local SUB_N = { 1, 2, 2, 4 } @@ -1096,7 +1083,6 @@ local function macroblock(S: any, M: any, r: Bitstream.Reader): (boolean, string return interMb(S, M, r, t, true) end --- slice(S, M, r) -> true | false, message function Cabac.slice(S: any, M: any, r: Bitstream.Reader): (boolean, string?) local p = (r.pos + 7) // 8 local limit = r.size // 8 diff --git a/src/Rosetta/codecs/video/H264/Cavlc.luau b/src/Rosetta/codecs/video/H264/Cavlc.luau index 5abcd7f..73df77e 100644 --- a/src/Rosetta/codecs/video/H264/Cavlc.luau +++ b/src/Rosetta/codecs/video/H264/Cavlc.luau @@ -1,11 +1,8 @@ --!strict --!native --!optimize 2 --- codecs/video/H264/Cavlc: slice data and macroblock layer with CAVLC entropy coding (ITU-T H.264 7.3.4, 7.3.5, 9.2): --- mb_skip_run, mb_type / sub_mb_type, intra modes, ref_idx (te), mvd, coded_block_pattern (me), mb_qp_delta and --- residual_block_cavlc (coeff_token, level_prefix / suffix, total_zeros, run_before) with the 8x8 interleaving. --- Coefficients are dequantised as they are placed. Written from the spec; VLC tables from Tables. --- Never throws: returns false, "message" on bad data. +-- codecs/video/H264/Cavlc: slice data and macroblock layer with CAVLC entropy coding (ITU-T H.264 7.3.4, 7.3.5, 9.2), +-- residual_block_cavlc with the 8x8 interleaving; coefficients are dequantised as they are placed. local Bitstream = require("@rosetta/codecs/video/H264/Bitstream") local Tables = require("@rosetta/codecs/video/H264/Tables") local Mb = require("@rosetta/codecs/video/H264/Mb") @@ -17,7 +14,6 @@ local BLK_X, BLK_Y = Mb.BLK_X, Mb.BLK_Y local Cavlc = {} --- ------------------------------------------------------------------------------------------------ vlc tables -- build(entries) -> l1, l2: a two-level lookup on 16 peeked bits. l1[(v >> 8) + 1] = value * 32 + length, or -- -(base) of a second-level block l2[base + (v & 255)]; 0 = no code local function build(entries: { { number } }): ({ number }, { number }) @@ -100,7 +96,6 @@ local IDENT = { 0, 1, 2, 3 } local INTRA_CBP, INTER_CBP = Tables.INTRA_CBP, Tables.INTER_CBP --- ------------------------------------------------------------------------------------------------ residual local LEVEL = table.create(16, 0) local RUN = table.create(16, 0) @@ -108,8 +103,7 @@ local peek = Bitstream.peekAt local clz32 = Bitstream.clz32 local P2 = Bitstream.P2 --- residual(r, nC, maxCoeff, out, base, scan, mul, div) -> TotalCoeff, or -1 on a bad code. Levels go to --- out[base + scan[i] + 1] dequantised as (level * mul[pos + 1] + div / 2) // div (mul nil: raw levels) +-- levels go to out[base + scan[i] + 1] as (level * mul[pos + 1] + div / 2) // div (mul nil: raw levels) local function residual(r: Bitstream.Reader, nC: number, maxCoeff: number, out: { number }, base: number, scan: { number }, mul: { number }?, div: number): number local b, n = r.buf, r.n local pos = r.pos @@ -256,7 +250,6 @@ local function residual(r: Bitstream.Reader, nC: number, maxCoeff: number, out: end Cavlc.residual = residual --- ------------------------------------------------------------------------------------------------ macroblock local SUBB_PF = { 0, 1, 2, 3, 1, 1, 2, 2, 3, 3, 1, 2, 3 } local SUBB_SHAPE = { 0, 0, 0, 0, 1, 2, 1, 2, 1, 2, 3, 3, 3 } local SUB_N = { 1, 2, 2, 4 } @@ -279,7 +272,6 @@ local function refIdx(r: Bitstream.Reader, n: number): number return v end --- the residual of the parsed macroblock local function residuals(S: any, M: any, r: Bitstream.Reader): (boolean, string?) local kind = M.kind local cbp = M.cbp @@ -404,7 +396,7 @@ local function clearLumaGrids(S: any, M: any, intra: boolean) end end --- intra(S, M, r, t): the intra macroblock types 0..25 (table 7-11) +-- intra macroblock types 0..25 (table 7-11) local function intraMb(S: any, M: any, r: Bitstream.Reader, t: number): (boolean, string?) local addr = M.addr + 1 if t == 25 then @@ -515,7 +507,7 @@ local function intraMb(S: any, M: any, r: Bitstream.Reader, t: number): (boolean return true end --- inter(S, M, r, t, isB): the P (0..4) and B (0..22) inter macroblock types +-- the P (0..4) and B (0..22) inter macroblock types local function interMb(S: any, M: any, r: Bitstream.Reader, t: number, isB: boolean): (boolean, string?) clearLumaGrids(S, M, false) local n0, n1 = S.n0, S.n1 @@ -709,7 +701,6 @@ local function interMb(S: any, M: any, r: Bitstream.Reader, t: number, isB: bool return true end --- macroblock(S, M, r) -> true | false, message local function macroblock(S: any, M: any, r: Bitstream.Reader): (boolean, string?) local t = ue(r) local st = S.type @@ -727,8 +718,6 @@ local function macroblock(S: any, M: any, r: Bitstream.Reader): (boolean, string return interMb(S, M, r, t, true) end --- ------------------------------------------------------------------------------------------------ slice data --- slice(S, M, r) -> true | false, message: decodes macroblocks from S.firstMb until the end of the slice data function Cavlc.slice(S: any, M: any, r: Bitstream.Reader): (boolean, string?) local addr = S.firstMb local total = S.mbW * S.mbH diff --git a/src/Rosetta/codecs/video/H264/Deblock.luau b/src/Rosetta/codecs/video/H264/Deblock.luau index 172722c..3226ea7 100644 --- a/src/Rosetta/codecs/video/H264/Deblock.luau +++ b/src/Rosetta/codecs/video/H264/Deblock.luau @@ -1,12 +1,9 @@ --!strict --!native --!optimize 2 --- codecs/video/H264/Deblock: the in-loop deblocking filter of ITU-T H.264 8.7 for frame macroblocks, 8-bit 4:2:0: --- boundary strengths (8.7.2.1, from the per-4x4 intra / coefficient / reference / motion grids), alpha / beta / tC0 --- (tables 8-16 / 8-17), the bS < 4 and bS = 4 luma and chroma filters, disable_deblocking_filter_idc 0 / 1 / 2 and the --- slice alpha / beta offsets. Written from the spec. Runs over the whole picture in macroblock order once all its --- slices are decoded (the result equals filtering each macroblock as it is decoded). --- Never throws. +-- codecs/video/H264/Deblock: the in-loop deblocking filter of ITU-T H.264 8.7 for frame macroblocks, 8-bit 4:2:0 +-- (bS 8.7.2.1, alpha / beta / tC0 tables 8-16 / 8-17). Runs over the whole picture once its slices are decoded, which +-- equals filtering each macroblock as it is decoded. local Tables = require("@rosetta/codecs/video/H264/Tables") local readu8, writeu8 = buffer.readu8, buffer.writeu8 @@ -23,9 +20,6 @@ end local abs = math.abs --- luma(b, o, across, along, qp, aOff, bOff): filters the 16 samples of one luma edge; `across` steps from q0 to q1 --- (1 for vertical edges, the stride for horizontal ones), `along` to the next sample of the edge; BS holds the four --- strengths local function luma(b: buffer, o: number, across: number, along: number, qp: number, aOff: number, bOff: number) local indexA = clip3(0, 51, qp + aOff) local alpha = ALPHA[indexA + 13] @@ -84,7 +78,7 @@ local function luma(b: buffer, o: number, across: number, along: number, qp: num end end --- chroma(b, o, across, along, qp, aOff, bOff): the 8 samples of one chroma edge (bS of luma segment i // 2) +-- chroma: bS of luma segment i // 2 local function chroma(b: buffer, o: number, across: number, along: number, qp: number, aOff: number, bOff: number) local indexA = clip3(0, 51, qp + aOff) local alpha = ALPHA[indexA + 13] @@ -115,7 +109,7 @@ local function chroma(b: buffer, o: number, across: number, along: number, qp: n end end --- motionDiffers(pic, p, q) -> true when the 4x4 blocks p and q (grid indices) need bS 1 (8.7.2.1) +-- the bS 1 motion test of 8.7.2.1 local function mvDiff(mvA: { number }, a: number, mvB: { number }, b: number): boolean return abs(mvA[2 * a - 1] - mvB[2 * b - 1]) >= 4 or abs(mvA[2 * a] - mvB[2 * b]) >= 4 end @@ -156,7 +150,6 @@ local function motionDiffers(pic: any, p: number, q: number): boolean return (mvDiff(mv0, p, mv0, q) or mvDiff(mv1, p, mv1, q)) and (mvDiff(mv0, p, mv1, q) or mvDiff(mv1, p, mv0, q)) end --- picture(S, pic, params): deblocks the whole picture. params[sliceNum] = { idc, alphaOffset, betaOffset } function Deblock.picture(S: any, pic: any, params: { any }) local mbW, mbH = S.mbW, S.mbH local w4 = S.w4 @@ -203,7 +196,6 @@ function Deblock.picture(S: any, pic: any, params: { any }) if t8 and (e == 1 or e == 3) then continue end - -- strengths of the four segments local intraP = intraQ local qpP, qpcP, qpc2P = qpQ, qpcQ, qpc2Q if e == 0 then diff --git a/src/Rosetta/codecs/video/H264/Decoder.luau b/src/Rosetta/codecs/video/H264/Decoder.luau index 7590582..e0c4b07 100644 --- a/src/Rosetta/codecs/video/H264/Decoder.luau +++ b/src/Rosetta/codecs/video/H264/Decoder.luau @@ -1,10 +1,7 @@ --!strict --- codecs/video/H264/Decoder: the decoding process above the macroblock layer (ITU-T H.264 8.1, 8.2, C.4): NAL unit --- dispatch, picture boundaries (7.4.1.2.4), picture order count types 0 / 1 / 2 (8.2.1), frame_num gaps (8.2.5.2), --- reference picture lists with modification (8.2.4), sliding window and adaptive (MMCO 1-6) marking (8.2.5), output --- in POC order through a reorder buffer (num_reorder_frames, else the DPB size), concealment of lost macroblocks, --- deblocking and border extension. Written from the spec. --- Never throws: errors are returned (a corrupt slice is skipped and its macroblocks concealed). +-- codecs/video/H264/Decoder: the decoding process above the macroblock layer (ITU-T H.264 8.1, 8.2, C.4): picture +-- boundaries (7.4.1.2.4), POC types 0 / 1 / 2 (8.2.1), frame_num gaps (8.2.5.2), list modification (8.2.4), marking +-- (8.2.5), output in POC order (num_reorder_frames, else the DPB size). local Bitstream = require("@rosetta/codecs/video/H264/Bitstream") local Params = require("@rosetta/codecs/video/H264/Params") local Slice = require("@rosetta/codecs/video/H264/Slice") @@ -23,17 +20,14 @@ local Decoder = {} Decoder.__index = Decoder export type Options = { - maxPixels: number?, -- largest picture accepted (default 2^22: 4096 x 1024) - lowDelay: boolean?, -- output pictures in decoding order without reordering (only right for streams without B frames) - deblock: boolean?, -- false skips the loop filter (not conformant: faster, for previews); default true - -- a cooperative yield point, called (pcall'ed: it can't throw through the native code) every YIELD_MBS macroblocks - -- of slice data and every macroblock row of the loop filter: e.g. a function that calls coroutine.yield() once a time - -- budget is spent, to spread one picture over several frames. While a decode is suspended, no other H.264 decode may - -- run in the same Luau VM (the entropy decoders keep their state in module locals); default nil (no calls) + maxPixels: number?, + lowDelay: boolean?, + deblock: boolean?, + -- yield is pcall'ed (it can't throw through native code); the entropy decoders keep state in module locals, so no + -- other H.264 decode may run in the VM while one is suspended yield: (() -> ())?, } --- new(opts) -> decoder state function Decoder.new(opts: Options?): any local o = opts or {} return setmetatable({ @@ -58,7 +52,7 @@ function Decoder.new(opts: Options?): any maxLongTermIdx = -1, pool = {}, gray = nil, - frames = 0, -- pictures decoded + frames = 0, errors = 0, lastError = nil, fatal = nil, @@ -67,7 +61,6 @@ function Decoder.new(opts: Options?): any }, Decoder) end --- ------------------------------------------------------------------------------------------------ pictures local function newPicture(self: any, sps: any): any local mbW, mbH = sps.mbWidth, sps.mbHeight local pool = self.pool @@ -136,7 +129,6 @@ local function grayPicture(self: any, sps: any): any return g end --- ------------------------------------------------------------------------------------------------ output local function emit(self: any, p: any) p.waiting = false local sps = p.sps @@ -189,7 +181,6 @@ local function reorderDepth(self: any, sps: any): number return sps.maxDecFrameBuffering or sps.maxDpbFrames end --- ------------------------------------------------------------------------------------------------ reference lists local function shortRefs(self: any): { any } local t = {} for _, p in self.refs do @@ -288,7 +279,6 @@ local function modify(self: any, list: { any }, ops: { number }, n: number, sh: return true end --- buildLists(self, sh, cur) -> list0, list1 (arrays of pictures, truncated to num_ref_idx_active) local function buildLists(self: any, sh: any, cur: any): ({ any }, { any }, boolean) picNums(self, sh) local list0, list1 = {}, {} @@ -368,7 +358,6 @@ local function buildLists(self: any, sh: any, cur: any): ({ any }, { any }, bool return list0, list1, ok end --- ------------------------------------------------------------------------------------------------ marking local function unmark(self: any, p: any) p.short = false p.long = false @@ -411,7 +400,7 @@ local function addRef(self: any, p: any) table.insert(self.refs, p) end --- mark(self, cur, sh): 8.2.5 after decoding the current (reference) picture; returns true when MMCO 5 was present +-- 8.2.5 marking after a reference picture; true when MMCO 5 was present local function mark(self: any, cur: any, sh: any): boolean local sps = sh.sps if sh.idr then @@ -511,7 +500,6 @@ local function mark(self: any, cur: any, sh: any): boolean return mmco5 end --- ------------------------------------------------------------------------------------------------ poc local function computePoc(self: any, sh: any): (number, number) local sps = sh.sps local maxFrameNum = 2 ^ sps.log2MaxFrameNum @@ -577,7 +565,6 @@ local function computePoc(self: any, sh: any): (number, number) return t, t end --- ------------------------------------------------------------------------------------------------ picture decode local function setupGrids(self: any, sps: any) local mbW, mbH = sps.mbWidth, sps.mbHeight if self.S and self.S.mbW == mbW and self.S.mbH == mbH then @@ -760,7 +747,6 @@ local function finishPicture(self: any) p.poc = 0 p.frameNum = 0 end - -- POC / frame_num state for the next pictures if sh.nalRefIdc ~= 0 then if mmco5 then self.prevPocMsb = 0 @@ -917,7 +903,6 @@ local function decodeSlice(self: any, sh: any, r: Bitstream.Reader) end end --- nal(self, buf, off, len, pts): one NAL unit (no start code) function Decoder.nal(self: any, buf: buffer, off: number, len: number, pts: number?) if len < 1 then return @@ -1008,13 +993,11 @@ function Decoder.nal(self: any, buf: buffer, off: number, len: number, pts: numb -- SEI (6), filler (12), SPS extension (13), prefix / SVC / MVC (14, 15, 20) and reserved types are ignored end --- flush(self): finish the current picture and output every waiting picture function Decoder.flush(self: any) finishPicture(self) bump(self, 0) end --- take(self) -> the frames output since the last call function Decoder.take(self: any): { any } local out = self.out self.out = {} diff --git a/src/Rosetta/codecs/video/H264/Inter.luau b/src/Rosetta/codecs/video/H264/Inter.luau index 6dc0a8e..d8e144a 100644 --- a/src/Rosetta/codecs/video/H264/Inter.luau +++ b/src/Rosetta/codecs/video/H264/Inter.luau @@ -1,12 +1,8 @@ --!strict --!native --!optimize 2 --- codecs/video/H264/Inter: inter prediction sample interpolation and weighting (ITU-T H.264 8.4.2.2 / 8.4.2.3): the 6-tap --- quarter-sample luma filter, eighth-sample bilinear chroma, default / explicit / implicit weighted sample --- prediction, and the picture border extension that makes out-of-picture reference reads equal to the clamped --- sample positions of 8.4.2.2.1. Written from the spec. --- Reference planes carry a border of PAD (luma) / PADC (chroma) replicated samples; callers clamp block positions --- with Inter.clampLuma / clampChroma so every read is inside the buffer. Never throws. +-- codecs/video/H264/Inter: inter prediction sample interpolation and weighting (ITU-T H.264 8.4.2.2 / 8.4.2.3). +-- Reference planes carry a border of PAD / PADC replicated samples, so reads equal the clamped positions of 8.4.2.2.1. local readu8, writeu8 = buffer.readu8, buffer.writeu8 local Inter = {} @@ -19,11 +15,9 @@ local function clip(v: number): number return min(max(v, 0), 255) end --- scratch rows of horizontal 6-tap intermediates (unrounded), 21 rows x 16 (+1) columns local B1 = table.create(24 * 17, 0) --- the six-tap filter cases, each a small function (LuaJIT keeps small loops in one trace); sliding windows read each --- sample once per row / column +-- one small function per six-tap case: LuaJIT keeps each loop in one trace local function lumaCopy(ref: buffer, s: number, base: number, w: number, h: number, P: { number }) for r = 0, h - 1 do local o = base + r * s @@ -141,8 +135,6 @@ local function lumaDiag(ref: buffer, s: number, base: number, w: number, h: numb end end --- luma(ref, s, base, fx, fy, w, h, P): the w x h luma prediction for a block whose integer sample (0, 0) is at --- ref[base] and whose fractional offset is (fx, fy) quarter samples; P[r * 16 + c + 1] receives the samples function Inter.luma(ref: buffer, s: number, base: number, fx: number, fy: number, w: number, h: number, P: { number }) if fy == 0 then if fx == 0 then @@ -161,7 +153,6 @@ function Inter.luma(ref: buffer, s: number, base: number, fx: number, fy: number end end --- chroma(ref, s, base, fx, fy, w, h, P): eighth-sample bilinear chroma prediction function Inter.chroma(ref: buffer, s: number, base: number, fx: number, fy: number, w: number, h: number, P: { number }) if fx == 0 and fy == 0 then for r = 0, h - 1 do @@ -187,8 +178,6 @@ function Inter.chroma(ref: buffer, s: number, base: number, fx: number, fy: numb end end --- ------------------------------------------------------------------------------------------------ weighting --- put(P, w, h, b, o, s): P into the picture function Inter.put(P: { number }, w: number, h: number, b: buffer, o: number, s: number) for r = 0, h - 1 do local d = r * 16 + 1 @@ -199,7 +188,7 @@ function Inter.put(P: { number }, w: number, h: number, b: buffer, o: number, s: end end --- avg(P0, P1, w, h, b, o, s): default bi-prediction (P0 + P1 + 1) >> 1 +-- default bi-prediction (P0 + P1 + 1) >> 1 function Inter.avg(P0: { number }, P1: { number }, w: number, h: number, b: buffer, o: number, s: number) for r = 0, h - 1 do local d = r * 16 + 1 @@ -210,7 +199,7 @@ function Inter.avg(P0: { number }, P1: { number }, w: number, h: number, b: buff end end --- weight1(P, w, h, b, o, s, logWD, wt, off): explicit single-list weighting (8-270 / 8-271) +-- explicit single-list weighting (8-270 / 8-271) function Inter.weight1(P: { number }, w: number, h: number, b: buffer, o: number, s: number, logWD: number, wt: number, off: number) if logWD >= 1 then local rnd = 2 ^ (logWD - 1) @@ -233,8 +222,7 @@ function Inter.weight1(P: { number }, w: number, h: number, b: buffer, o: number end end --- weight2(P0, P1, w, h, b, o, s, logWD, w0, w1, off): explicit / implicit bi-prediction weighting (8-272); --- off = (o0 + o1 + 1) >> 1 +-- explicit / implicit bi-prediction weighting (8-272); off = (o0 + o1 + 1) >> 1 function Inter.weight2(P0: { number }, P1: { number }, w: number, h: number, b: buffer, o: number, s: number, logWD: number, w0: number, w1: number, off: number) local rnd = 2 ^ logWD local div = 2 ^ (logWD + 1) @@ -247,8 +235,6 @@ function Inter.weight2(P0: { number }, P1: { number }, w: number, h: number, b: end end --- ------------------------------------------------------------------------------------------------ borders --- extend(b, o, s, w, h, pad): replicate the edge samples of the w x h plane at b[o] (stride s) into its border function Inter.extend(b: buffer, o: number, s: number, w: number, h: number, pad: number) for y = 0, h - 1 do local r = o + y * s diff --git a/src/Rosetta/codecs/video/H264/Intra.luau b/src/Rosetta/codecs/video/H264/Intra.luau index f63dead..d68f8e3 100644 --- a/src/Rosetta/codecs/video/H264/Intra.luau +++ b/src/Rosetta/codecs/video/H264/Intra.luau @@ -1,10 +1,8 @@ --!strict --!native --!optimize 2 --- codecs/video/H264/Intra: intra prediction (ITU-T H.264 8.3): Intra_4x4 and Intra_8x8 (nine directional modes, with the --- 8x8 reference sample filter of 8.3.2.2.1), Intra_16x16 and chroma (DC / horizontal / vertical / plane), 8-bit. --- Written from the spec. Predictions are written straight into the picture plane (row stride `s`, block origin `o`). --- Never throws: every sample read is inside the padded plane (callers pass availability for the edges). +-- codecs/video/H264/Intra: intra prediction (ITU-T H.264 8.3): Intra_4x4 and Intra_8x8 (with the 8x8 reference sample +-- filter of 8.3.2.2.1), Intra_16x16 and chroma, 8-bit. local readu8, writeu8 = buffer.readu8, buffer.writeu8 local Intra = {} @@ -94,8 +92,7 @@ local function directional(R: { number }, N: number, mode: number, b: buffer, o: end end --- pred4x4(b, o, s, mode, left, top, topRight, topLeft): Intra_4x4 at plane offset o. Unavailable top-right samples --- repeat p[3, -1]. +-- unavailable top-right samples repeat p[3, -1] function Intra.pred4x4(b: buffer, o: number, s: number, mode: number, left: boolean, top: boolean, topRight: boolean, topLeft: boolean) if mode == 0 then local t = o - s @@ -170,7 +167,6 @@ function Intra.pred4x4(b: buffer, o: number, s: number, mode: number, left: bool directional(E, 4, mode, b, o, s) end --- pred8x8(b, o, s, mode, left, top, topRight, topLeft): Intra_8x8 with the reference sample filter function Intra.pred8x8(b: buffer, o: number, s: number, mode: number, left: boolean, top: boolean, topRight: boolean, topLeft: boolean) -- unfiltered edges into E: E[1..8] = p[-1, 7..0], E[9] = p[-1, -1], E[10..25] = p[0..15, -1] if left then @@ -277,7 +273,6 @@ function Intra.pred8x8(b: buffer, o: number, s: number, mode: number, left: bool end end --- pred16x16(b, o, s, mode, left, top, topLeft) function Intra.pred16x16(b: buffer, o: number, s: number, mode: number, left: boolean, top: boolean, topLeft: boolean) if mode == 0 then local t = o - s @@ -343,7 +338,7 @@ local function fill4(b: buffer, o: number, s: number, v: number) end end --- predChroma(b, o, s, mode, left, top, topLeft): 8x8 chroma (4:2:0); mode 0 DC, 1 horizontal, 2 vertical, 3 plane +-- 8x8 chroma (4:2:0): mode 0 DC, 1 horizontal, 2 vertical, 3 plane function Intra.predChroma(b: buffer, o: number, s: number, mode: number, left: boolean, top: boolean, topLeft: boolean) if mode == 0 then local t = o - s diff --git a/src/Rosetta/codecs/video/H264/Mb.luau b/src/Rosetta/codecs/video/H264/Mb.luau index d32e344..8992e0a 100644 --- a/src/Rosetta/codecs/video/H264/Mb.luau +++ b/src/Rosetta/codecs/video/H264/Mb.luau @@ -2,11 +2,8 @@ --!native --!optimize 2 -- codecs/video/H264/Mb: macroblock reconstruction shared by the CAVLC and CABAC parsers (ITU-T H.264 8.3 - 8.5): --- neighbour availability (6.4.11), Intra4x4 / Intra8x8 mode prediction (8.3.1.1 / 8.3.2.1), motion vector prediction --- (8.4.1.3), P_Skip (8.4.1.1), B direct spatial and temporal (8.4.1.2), motion compensation with weighting, intra --- prediction and the residual. Written from the spec; the per-4x4 motion / mode grids follow the usual decoder layout --- (picture-wide arrays, one entry per 4x4 luma block, 1-based). --- Never throws: every index is in range by construction; reference indices past the list use the first entry. +-- neighbour availability (6.4.11), intra mode prediction (8.3.1.1 / 8.3.2.1), motion vector prediction (8.4.1.3), +-- P_Skip (8.4.1.1), B direct (8.4.1.2). Reference indices past the list use the first entry. local Intra = require("@rosetta/codecs/video/H264/Intra") local Transform = require("@rosetta/codecs/video/H264/Transform") local Inter = require("@rosetta/codecs/video/H264/Inter") @@ -29,7 +26,6 @@ local BLK_X = { 0, 1, 0, 1, 2, 3, 2, 3, 0, 1, 0, 1, 2, 3, 2, 3 } local BLK_Y = { 0, 0, 1, 1, 0, 0, 1, 1, 2, 2, 3, 3, 2, 2, 3, 3 } Mb.BLK_X, Mb.BLK_Y = BLK_X, BLK_Y --- new() -> M, the per-macroblock scratch state function Mb.new(): any return { addr = 0, @@ -79,7 +75,6 @@ function Mb.new(): any } end --- grids(mbW, mbH) -> the per-picture decoding grids (shared by the slices of one picture) function Mb.grids(mbW: number, mbH: number): any local n = mbW * mbH local n4 = n * 16 @@ -107,8 +102,6 @@ function Mb.grids(mbW: number, mbH: number): any } end --- ------------------------------------------------------------------------------------------------ neighbours --- start(S, M, addr): position and neighbour availability of macroblock addr function Mb.start(S: any, M: any, addr: number) local mbW = S.mbW local x, y = addr % mbW, addr // mbW @@ -141,7 +134,7 @@ function Mb.start(S: any, M: any, addr: number) M.qpd = 0 end --- nC(S, M, bx, by) -> nC of luma block (bx, by) (9.2.1) +-- nC of luma block (bx, by) (9.2.1) function Mb.nC(S: any, M: any, bx: number, by: number): number local g = M.g0 + by * S.w4 + bx local nzc = S.nzc @@ -157,7 +150,6 @@ function Mb.nC(S: any, M: any, bx: number, by: number): number return 0 end --- nCc(S, M, tab, bx, by) -> nC of chroma AC block (bx, by) of the plane whose counts are in tab function Mb.nCc(S: any, M: any, tab: { number }, bx: number, by: number): number local cw = S.cw4 local g = M.c0 + by * cw + bx @@ -173,7 +165,7 @@ function Mb.nCc(S: any, M: any, tab: { number }, bx: number, by: number): number return 0 end --- predMode(S, M, bx, by) -> predIntra4x4PredMode / predIntra8x8PredMode of the block whose top-left 4x4 is (bx, by) +-- predIntra4x4PredMode / predIntra8x8PredMode (8.3.1.1 / 8.3.2.1) function Mb.predMode(S: any, M: any, bx: number, by: number): number local la = bx > 0 or M.iL local ta = by > 0 or M.iT @@ -186,9 +178,6 @@ function Mb.predMode(S: any, M: any, bx: number, by: number): number return ((a < b) and (a) or (b)) end --- ------------------------------------------------------------------------------------------------ motion vectors --- neighbour(S, M, list, nx, ny) -> ref (UNAVAIL when not available), mvx, mvy of the 4x4 at (nx, ny) relative to the --- macroblock (nx, ny in -1 .. 4) local function neighbour(S: any, M: any, refs: { number }, mvs: { number }, nx: number, ny: number): (number, number, number) local ok if ny < 0 then @@ -221,8 +210,7 @@ local function median(a: number, b: number, c: number): number return max(min(a, b), min(max(a, b), c)) end --- mvp(S, M, list, x, y, w, ref, shape) -> mvpLX for the partition at (x, y) (4x4 units) of width w with reference --- index ref. shape: 0 generic, 1 = 16x8 upper, 2 = 16x8 lower, 3 = 8x16 left, 4 = 8x16 right +-- shape: 0 generic, 1 = 16x8 upper, 2 = 16x8 lower, 3 = 8x16 left, 4 = 8x16 right (8.4.1.3) local function mvp(S: any, M: any, list: number, x: number, y: number, w: number, ref: number, shape: number): (number, number) local pic = S.pic local refs = ((list == 0) and (pic.ref0) or (pic.ref1)) @@ -275,7 +263,6 @@ local function mvp(S: any, M: any, list: number, x: number, y: number, w: number end Mb.mvp = mvp --- set(S, M, x, y, w, h, r0, m0x, m0y, r1, m1x, m1y): motion data of a region into the picture grids local function set(S: any, M: any, x: number, y: number, w: number, h: number, r0: number, m0x: number, m0y: number, r1: number, m1x: number, m1y: number) local pic = S.pic local ref0, ref1, mv0, mv1, uid0, uid1 = pic.ref0, pic.ref1, pic.mv0, pic.mv1, pic.uid0, pic.uid1 @@ -302,7 +289,6 @@ local function set(S: any, M: any, x: number, y: number, w: number, h: number, r M.nreg += 1 end --- clipping helpers local function clip3(lo: number, hi: number, v: number): number return min(max(v, lo), hi) end @@ -315,7 +301,7 @@ local function tdiv(a: number, b: number): number return -math.floor(-q) end --- distScale(cur, poc0, poc1) -> DistScaleFactor (8-195 .. 8-198), or nil when td is 0 +-- DistScaleFactor (8-195 .. 8-198), nil when td is 0 function Mb.distScale(cur: number, poc0: number, poc1: number): number? local tb = clip3(-128, 127, cur - poc0) local td = clip3(-128, 127, poc1 - poc0) @@ -326,7 +312,7 @@ function Mb.distScale(cur: number, poc0: number, poc1: number): number? return clip3(-1024, 1023, (tb * tx + 32) // 64) end --- pskip(S, M): P_Skip motion (8.4.1.1) +-- P_Skip motion (8.4.1.1) local function pskip(S: any, M: any) local mx, my = 0, 0 if M.aL and M.aT then @@ -340,7 +326,7 @@ local function pskip(S: any, M: any) set(S, M, 0, 0, 4, 4, 0, mx, my, -1, 0, 0) end --- colocated(S, M, bx, by) -> refIdxCol (-1: intra / none), mvCol x, y, uid of the referenced picture (8.4.1.2.1) +-- refIdxCol (-1: intra / none), mvCol (8.4.1.2.1) local function colocated(S: any, M: any, bx: number, by: number): (number, number, number, number) local col = S.colPic if S.direct8x8 then @@ -369,7 +355,7 @@ local function minPositive(a: number, b: number): number return ((a > b) and (a) or (b)) end --- spatialRefs(S, M): the macroblock-level references and predictors of spatial direct (8.4.1.2.2), cached in M +-- spatial direct references and predictors (8.4.1.2.2) local function spatialRefs(S: any, M: any) local pic = S.pic local r0, r1 = -1, -1 @@ -410,7 +396,6 @@ local function spatialRefs(S: any, M: any) M.dReady = true end --- direct8(S, M, i8): direct motion of 8x8 quadrant i8 (B_Skip, B_Direct_16x16, B_Direct_8x8) local function direct8(S: any, M: any, i8: number) local x0, y0 = (i8 % 2) * 2, (i8 // 2) * 2 local step = ((S.direct8x8) and (2) or (1)) @@ -459,12 +444,10 @@ local function direct8(S: any, M: any, i8: number) end end --- partition geometry (4x4 units) of the sub-macroblock shapes local SUB_N = { 1, 2, 2, 4 } local SUB_W = { 2, 2, 1, 1 } local SUB_H = { 2, 1, 2, 1 } --- motion(S, M): motion vectors of an inter macroblock into the grids, and its MC regions local function motion(S: any, M: any) local kind = M.kind M.dReady = false @@ -551,8 +534,6 @@ local function motion(S: any, M: any) end Mb.motion = motion --- ------------------------------------------------------------------------------------------------ motion compensation --- predict(S, M, pic, P, list, x, y, w, h, mvx, mvy, plane): one list's prediction samples of a region into P local function predLuma(S: any, ref: any, P: { number }, px: number, py: number, w: number, h: number, mvx: number, mvy: number) local W, H = S.mbW * 16, S.mbH * 16 local ix = px + mvx // 4 @@ -577,7 +558,6 @@ local function refPic(list: { any }, r: number): any return list[r + 1] or list[1] end --- mc(S, M): inter prediction of every region of the macroblock into the current picture local function mc(S: any, M: any) local pic = S.pic local reg = M.reg @@ -604,7 +584,6 @@ local function mc(S: any, M: any) local lo = pic.yo + py * ys + px local cx, cy, cw, ch = M.x * 8 + x * 2, M.y * 8 + y * 2, w * 2, h * 2 local co = pic.co + cy * cs + cx - -- weights for this pair local bi = ref0 ~= nil and ref1 ~= nil local explicit = wm == 1 local implicitW0, implicitW1 = 32, 32 @@ -664,7 +643,6 @@ local function mc(S: any, M: any) end end --- ------------------------------------------------------------------------------------------------ residual local function lumaResidual(S: any, M: any) local pic = S.pic local b, s = pic.y, pic.ys @@ -716,7 +694,6 @@ local function chromaResidual(S: any, M: any) end end --- ------------------------------------------------------------------------------------------------ intra local function intraLuma(S: any, M: any) local pic = S.pic local b, s = pic.y, pic.ys @@ -821,8 +798,6 @@ local function pcm(S: any, M: any) end end --- ------------------------------------------------------------------------------------------------ macroblock --- recon(S, M): reconstruct the parsed macroblock and store what later macroblocks / deblocking need function Mb.recon(S: any, M: any) local kind = M.kind local addr = M.addr + 1 @@ -838,7 +813,6 @@ function Mb.recon(S: any, M: any) local nzDb = S.nzDb local g0 = M.g0 if kind <= K_PCM then - -- intra: no motion local ref0, ref1, uid0, uid1 = pic.ref0, pic.ref1, pic.uid0, pic.uid1 for j = 0, 3 do local g = g0 + j * w4 @@ -888,7 +862,6 @@ function Mb.recon(S: any, M: any) chromaResidual(S, M) end --- skip(S, M, kind): a P_Skip / B_Skip macroblock (no residual) function Mb.skip(S: any, M: any, kind: number) M.kind = kind M.cbp = 0 diff --git a/src/Rosetta/codecs/video/H264/Params.luau b/src/Rosetta/codecs/video/H264/Params.luau index ad954bc..5121040 100644 --- a/src/Rosetta/codecs/video/H264/Params.luau +++ b/src/Rosetta/codecs/video/H264/Params.luau @@ -1,9 +1,8 @@ --!strict --!native --- codecs/video/H264/Params: sequence and picture parameter sets (ITU-T H.264 7.3.2.1 / 7.3.2.2 / E.1), scaling lists with --- the fall-back rules A and B (7.4.2.1.1 / table 7-2), and the dequantisation tables built from them (8.5.9: the --- LevelScale4x4 / LevelScale8x8 functions, premultiplied by 2^(qP / 6)). Written from the spec. --- Never throws: parse functions return nil, "message". +-- codecs/video/H264/Params: sequence and picture parameter sets (ITU-T H.264 7.3.2.1 / 7.3.2.2 / E.1), scaling lists +-- with the fall-back rules A and B (7.4.2.1.1 / table 7-2), and the dequantisation tables built from them (8.5.9: the +-- LevelScale4x4 / LevelScale8x8 functions, premultiplied by 2^(qP / 6)). local Bitstream = require("@rosetta/codecs/video/H264/Bitstream") local Tables = require("@rosetta/codecs/video/H264/Tables") @@ -18,7 +17,7 @@ local MAX_DPB_MBS = { [9] = 396, [10] = 396, [11] = 900, [12] = 2376, [13] = 237 local ZIGZAG4, ZIGZAG8 = Tables.ZIGZAG4, Tables.ZIGZAG8 --- scaling_list(): returns the list in raster order, or "default" (useDefaultScalingMatrixFlag) +-- scaling_list(): raster order, or "default" (useDefaultScalingMatrixFlag) local function scalingList(r: Bitstream.Reader, size: number): any local list = table.create(size, 0) local last, nxt = 8, 8 @@ -74,7 +73,7 @@ end local FLAT16, FLAT64 = table.create(16, 16), table.create(64, 16) --- resolve(lists, fallback) -> 12 raster lists. fallback: nil = rule A (defaults), else the 12 lists of the SPS (rule B) +-- fallback nil = rule A (defaults), else the SPS's 12 lists (rule B) local function resolve(lists: { any }, fallback: { { number } }?): { { number } } local out = {} for i = 1, 12 do @@ -94,7 +93,6 @@ local function resolve(lists: { any }, fallback: { { number } }?): { { number } return out end --- ------------------------------------------------------------------------------------------------ vui local function hrd(r: Bitstream.Reader) local cnt = ue(r) if cnt > 31 then @@ -167,8 +165,6 @@ local function vui(r: Bitstream.Reader, sps: any) end end --- ------------------------------------------------------------------------------------------------ sps --- sps(r) -> the SPS table | nil, message. r is positioned after the NAL header. function Params.sps(r: Bitstream.Reader): (any, string?) local sps: any = {} sps.profile = u(r, 8) @@ -289,8 +285,6 @@ function Params.sps(r: Bitstream.Reader): (any, string?) return sps, nil end --- ------------------------------------------------------------------------------------------------ pps --- pps(r, spsTable) -> the PPS | nil, message. spsTable: id -> SPS (needed for the scaling list count) function Params.pps(r: Bitstream.Reader, spsTable: { [number]: any }): (any, string?) local pps: any = {} pps.id = ue(r) @@ -351,7 +345,6 @@ function Params.pps(r: Bitstream.Reader, spsTable: { [number]: any }): (any, str return pps, nil end --- ------------------------------------------------------------------------------------------------ dequantisation local V4 = { { 10, 16, 13 }, { 11, 18, 14 }, { 13, 20, 16 }, { 14, 23, 18 }, { 16, 25, 20 }, { 18, 29, 23 } } local V8 = { { 20, 18, 32, 19, 25, 24 }, @@ -424,7 +417,6 @@ local function build(lists: { { number } }): any return { d4 = d4, d8 = d8 } end --- dequant(sps, pps, cache) -> the dequant tables for this pair (cache: a table kept by the decoder, by content) function Params.dequant(sps: any, pps: any, cache: { [string]: any }): any local lists: { { number } } if pps.scalingLists then diff --git a/src/Rosetta/codecs/video/H264/Slice.luau b/src/Rosetta/codecs/video/H264/Slice.luau index fda2757..d4e4b23 100644 --- a/src/Rosetta/codecs/video/H264/Slice.luau +++ b/src/Rosetta/codecs/video/H264/Slice.luau @@ -1,9 +1,8 @@ --!strict --!native -- codecs/video/H264/Slice: the slice header (ITU-T H.264 7.3.3): ref_pic_list_modification, pred_weight_table and --- dec_ref_pic_marking. Written from the spec. Frame coding only: field pictures (field_pic_flag = 1), MBAFF, --- SP / SI slices, separate colour planes and redundant pictures return "unsupported: ...". --- Never throws: header() returns nil, "message". +-- dec_ref_pic_marking. Frame coding only: field pictures, MBAFF, SP / SI, separate colour planes and redundant +-- pictures return "unsupported: ...". local Bitstream = require("@rosetta/codecs/video/H264/Bitstream") local u, u1, ue, se = Bitstream.u, Bitstream.u1, Bitstream.ue, Bitstream.se @@ -62,7 +61,6 @@ local function weights(r: Bitstream.Reader, n: number, lw: number, cw: number, c return t end --- header(r, nalType, nalRefIdc, spsTable, ppsTable) -> sh | nil, message function Slice.header(r: Bitstream.Reader, nalType: number, nalRefIdc: number, spsTable: { [number]: any }, ppsTable: { [number]: any }): (any, string?) local sh: any = {} sh.nalType = nalType diff --git a/src/Rosetta/codecs/video/H264/Tables.luau b/src/Rosetta/codecs/video/H264/Tables.luau index d2b1679..f57b899 100644 --- a/src/Rosetta/codecs/video/H264/Tables.luau +++ b/src/Rosetta/codecs/video/H264/Tables.luau @@ -1,11 +1,8 @@ --!strict --!native --- codecs/video/H264/Tables: the constant tables of ITU-T H.264 (CAVLC code tables 9-5, 9-7, 9-8, 9-9, 9-10; CABAC context --- initialisation tables 9-12..9-24, rangeTabLPS 9-44 and the state transitions 9-45; the chroma QP table 8-15; the --- me(v) coded_block_pattern mapping 9-4; default scaling lists 7-3 / 7-4; zig-zag scans 8-12 / 8-13; table 9-43; the --- deblocking alpha / beta / tC0 tables 8-16 / 8-17). Values extracted from openh264 2.x (BSD-2-Clause, --- licenses/openh264-LICENSE.txt): encoder_data_tables.cpp, common_tables.cpp, decoder_data_tables.cpp, --- wels_common_basis.h, deblocking.cpp. Flat 1-based arrays; the layouts are noted at each table. +-- codecs/video/H264/Tables: the constant tables of ITU-T H.264 (CAVLC 9-5, 9-7..9-10; CABAC init 9-12..9-24, +-- rangeTabLPS 9-44, transitions 9-45; chroma QP 8-15; me(v) CBP 9-4; scaling lists 7-3 / 7-4; zig-zag 8-12 / 8-13; +-- 9-43; deblocking 8-16 / 8-17). Values from openh264 2.x (BSD-2-Clause, licenses/openh264-LICENSE.txt). local T = {} -- coeff_token per nC class (0: 0<=nC<2, 1: 2<=nC<4, 2: 4<=nC<8, 3: 8<=nC, 4: nC=-1 chroma DC): { code, len, TotalCoeff, diff --git a/src/Rosetta/codecs/video/H264/Transform.luau b/src/Rosetta/codecs/video/H264/Transform.luau index b631624..3548031 100644 --- a/src/Rosetta/codecs/video/H264/Transform.luau +++ b/src/Rosetta/codecs/video/H264/Transform.luau @@ -1,11 +1,8 @@ --!strict --!native --!optimize 2 --- codecs/video/H264/Transform: the inverse transforms of ITU-T H.264 8.5: the 4x4 and 8x8 integer IDCTs with the residual --- added to the prediction in the plane (8.5.12.2 / 8.5.13.2 / 8.5.14), the 4x4 luma DC and 2x2 chroma DC Hadamard --- transforms with their scaling (8.5.10 / 8.5.11.2). Written from the spec. Coefficients are dequantised already --- (Params.dequant), raster order, in a 1-based table at `base + 1 ...`; the functions zero what they read. --- Never throws. +-- codecs/video/H264/Transform: the inverse transforms of ITU-T H.264 8.5 (4x4 / 8x8 IDCT 8.5.12.2 / 8.5.13.2 / 8.5.14, +-- luma DC / chroma DC Hadamard 8.5.10 / 8.5.11.2). Coefficients come dequantised, raster order, at base + 1; zeroed after use. local readu8, writeu8 = buffer.readu8, buffer.writeu8 local Transform = {} @@ -15,9 +12,7 @@ local function clip(v: number): number return min(max(v, 0), 255) end --- add4(c, base, b, o, s): inverse 4x4 transform of c[base + 1 .. base + 16], added to the 4x4 block at b[o] (stride s) function Transform.add4(c: { number }, base: number, b: buffer, o: number, s: number) - -- rows for i = 0, 3 do local k = base + i * 4 local d0, d1, d2, d3 = c[k + 1], c[k + 2], c[k + 3], c[k + 4] @@ -30,7 +25,6 @@ function Transform.add4(c: { number }, base: number, b: buffer, o: number, s: nu c[k + 3] = f - g c[k + 4] = e - h end - -- columns for j = 0, 3 do local k = base + j local d0, d1, d2, d3 = c[k + 1], c[k + 5], c[k + 9], c[k + 13] @@ -50,7 +44,6 @@ function Transform.add4(c: { number }, base: number, b: buffer, o: number, s: nu end end --- addDc4(dc, b, o, s): a 4x4 block whose only coefficient is the (dequantised) DC function Transform.addDc4(dc: number, b: buffer, o: number, s: number) local v = (dc + 32) // 64 if v == 0 then @@ -67,11 +60,9 @@ end local T8 = table.create(64, 0) --- add8(c, base, b, o, s): inverse 8x8 transform of c[base + 1 .. base + 64] added to the 8x8 block at b[o] function Transform.add8(c: { number }, base: number, b: buffer, o: number, s: number) for pass = 0, 1 do for i = 0, 7 do - -- pass 0: rows of c into T8; pass 1: columns of T8 local d0, d1, d2, d3, d4, d5, d6, d7 if pass == 0 then local k = base + i * 8 @@ -128,8 +119,7 @@ function Transform.add8(c: { number }, base: number, b: buffer, o: number, s: nu end end --- lumaDc(dc, m, c): the Intra_16x16 DC levels dc[1..16] (raster 4x4 matrix) -> inverse Hadamard, scaled with the --- DC multiplier m (LevelScale4x4(qP % 6, 0, 0) * 2^(qP / 6)), stored at c[blk * 16 + 1] (blk = raster block index) +-- m = LevelScale4x4(qP % 6, 0, 0) * 2^(qP / 6) function Transform.lumaDc(dc: { number }, m: number, c: { number }) for i = 0, 3 do local k = i * 4 @@ -157,7 +147,6 @@ function Transform.lumaDc(dc: { number }, m: number, c: { number }) end end --- chromaDc(dc, base, m, c, cbase): the 2x2 chroma DC levels dc[base + 1 .. base + 4] -> c[cbase + blk * 16 + 1] function Transform.chromaDc(dc: { number }, base: number, m: number, c: { number }, cbase: number) local c0, c1, c2, c3 = dc[base + 1], dc[base + 2], dc[base + 3], dc[base + 4] dc[base + 1], dc[base + 2], dc[base + 3], dc[base + 4] = 0, 0, 0, 0 diff --git a/src/Rosetta/codecs/video/H264/init.luau b/src/Rosetta/codecs/video/H264/init.luau index 278659e..645c01f 100644 --- a/src/Rosetta/codecs/video/H264/init.luau +++ b/src/Rosetta/codecs/video/H264/init.luau @@ -1,32 +1,8 @@ --!strict --- codecs/video/H264: an H.264 / AVC (ITU-T H.264 | ISO/IEC 14496-10) video decoder in pure Luau. A codec (layer 1): the --- video/h264 format (raw Annex B streams) and the MP4 / MKV / AVI / TS video tracks use it. Clean-room, written from the --- spec; constant tables taken from openh264 (BSD-2-Clause, licenses/openh264-LICENSE.txt). Bit-exact with the --- reference decoder (checked against ffmpeg per frame). --- Supports: Annex B and AVCC (length-prefixed, with avcC extradata) input; SPS / PPS / slices; CAVLC and CABAC; I, P and --- B slices; every intra mode (4x4, 8x8, 16x16, chroma), quarter-sample luma / eighth-sample chroma motion --- compensation, explicit and implicit weighted prediction, direct spatial and temporal prediction; the 4x4 and 8x8 --- transforms with scaling matrices; the deblocking filter; multiple reference frames, long-term references, MMCO and --- the sliding window, frame_num gaps; POC types 0 / 1 / 2 and output reordering; 8-bit 4:2:0 Constrained Baseline, --- Main, Extended-without-SP/data-partitioning and High profiles; cropping. Corrupt slices are skipped and their --- macroblocks concealed (copied from the latest reference picture). --- Not supported (UNSUPPORTED): interlaced coding (field pictures, MBAFF), 4:0:0 / 4:2:2 / 4:4:4, bit depths above 8, --- lossless (transform bypass), FMO / ASO slice groups, SP / SI slices, data partitioning, SVC / MVC enhancement layers --- (their NAL units are ignored). --- --- local H264 = require("@rosetta/codecs/video/H264") --- local dec = H264.newDecoder() -- or { avcC = buffer } for MP4 samples (length-prefixed) --- for _, au in accessUnits do --- local frames, err = dec:decode(au, pts) -- frames: { { image (yuv420p Types.Image), pts, poc, keyframe } } --- end --- local rest = dec:flush() -- the frames still held for reordering --- --- Speed (one Zen 5 core, tools/bench.luau, libx264 crf 23 clips): Luau --codegen ~220-425 fps at 320x240 and ~75-135 --- fps at 640x360; LuaJIT with the api's trace limits (host/init.luau) about the same or faster, but with LuaJIT's default --- limits (maxtrace=1000) the trace cache thrashes and it drops to ~30-190 fps. Real-time is comfortable at 320x240 and --- feasible at 640x360 for typical bitrates; high-bitrate CIF conformance streams run ~100-150 fps (Luau). --- Never throws: bad data returns nil, Err (core/Err codes ARG / UNSUPPORTED / LIMIT), or frames with the bad slices --- concealed (dec.errors counts them, dec.lastError says why). +-- codecs/video/H264: an H.264 / AVC (ITU-T H.264 | ISO/IEC 14496-10) video decoder in pure Luau, bit-exact with ffmpeg. +-- Clean-room from the spec; constant tables from openh264 (BSD-2-Clause, licenses/openh264-LICENSE.txt). 8-bit 4:2:0 +-- Constrained Baseline, Main and High. UNSUPPORTED: interlaced coding (field pictures, MBAFF), 4:0:0 / 4:2:2 / 4:4:4, +-- bit depths above 8, lossless, FMO / ASO, SP / SI slices, data partitioning, SVC / MVC (their NAL units are ignored). local Err = require("@rosetta/core/Err") local Types = require("@rosetta/Types") local Bitstream = require("@rosetta/codecs/video/H264/Bitstream") @@ -38,15 +14,15 @@ local H264 = {} export type Options = { avcC: buffer?, -- AVCDecoderConfigurationRecord (MP4 'avcC', Matroska CodecPrivate): samples are length-prefixed lengthSize: number?, -- NAL length field size for length-prefixed input without avcC (1, 2 or 4) - maxPixels: number?, -- largest picture (default 2^22 luma samples) - lowDelay: boolean?, -- output in decoding order, no reordering delay (streams without B frames / reordering) - deblock: boolean?, -- false skips the deblocking filter (faster, not conformant); default true - yield: (() -> ())?, -- a cooperative yield point (see Decoder Options.yield): pcall'ed every 16 macroblocks + maxPixels: number?, + lowDelay: boolean?, + deblock: boolean?, + yield: (() -> ())?, } export type Frame = { - image: Types.Image, -- yuv420p, cropped to the display size; image.meta.source = { format = "h264", poc, ... } - pts: number, -- the pts passed with the access unit holding the picture (default: its decoding index) + image: Types.Image, + pts: number, duration: number, poc: number, keyframe: boolean, @@ -83,7 +59,6 @@ local function status(self: H264Decoder): Err.Err? return nil end --- newDecoder(opts?) -> H264Decoder | nil, Err function H264.newDecoder(opts: Options?): (H264Decoder?, Err.Err?) local o = opts or {} if type(o) ~= "table" then @@ -100,8 +75,6 @@ function H264.newDecoder(opts: Options?): (H264Decoder?, Err.Err?) return self, nil end --- decoder:configure(avcC) -> true | nil, Err: reads an AVCDecoderConfigurationRecord (its SPS / PPS) and switches to --- length-prefixed input function DecoderMeta.configure(self: H264Decoder, avcC: any): (boolean?, Err.Err?) local b = toBuffer(avcC) if not b then @@ -127,8 +100,6 @@ function DecoderMeta.configure(self: H264Decoder, avcC: any): (boolean?, Err.Err return true, nil end --- decoder:decode(data, pts?, off?, len?) -> { Frame } | nil, Err. data: an access unit or any run of NAL units: --- length-prefixed (after configure / with opts.lengthSize), else Annex B (start codes) or one bare NAL unit. function DecoderMeta.decode(self: H264Decoder, data: any, pts: number?, off: number?, len: number?): ({ Frame }?, Err.Err?) local b = toBuffer(data) if not b then @@ -165,14 +136,12 @@ function DecoderMeta.decode(self: H264Decoder, data: any, pts: number?, off: num return frames, nil end --- decoder:flush() -> { Frame }: ends the stream (the current picture and every picture held for reordering) function DecoderMeta.flush(self: H264Decoder): { Frame } Decoder.flush(self.state) status(self) return Decoder.take(self.state) end --- decodeAll(data, opts?) -> { Frame } | nil, Err: a whole Annex B (or length-prefixed with opts.avcC) stream function H264.decodeAll(data: any, opts: Options?): ({ Frame }?, Err.Err?) local dec, err = H264.newDecoder(opts) if not dec then @@ -188,7 +157,6 @@ function H264.decodeAll(data: any, opts: Options?): ({ Frame }?, Err.Err?) return frames, nil end --- parseAvcC(buf) -> { lengthSize, profile, level, nals } | nil, Err function H264.parseAvcC(data: any): (any, Err.Err?) local b = toBuffer(data) if not b then @@ -201,11 +169,6 @@ function H264.parseAvcC(data: any): (any, Err.Err?) return cfg, nil end --- ------------------------------------------------------------------------------------------------ video layer --- newVideoDecoder(track, opts?) -> a Types.VideoCodecDecoder (the codecs/video/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 packet timestamps sorted (display order); 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, yield = opts and opts.yield } @@ -234,8 +197,7 @@ function H264.newVideoDecoder(track: Types.Track, opts: any?): (Types.VideoCodec pts = outIndex or 0 outIndex = pts + 1 elseif #pool > 0 then - -- pictures leave in display order: they take the packet timestamps in increasing order (right for - -- MP4 / MKV / TS pts, and for AVI whose packets only carry decode-order times) + -- pictures take the packet timestamps in increasing order (right for MP4 / MKV / TS pts and AVI's decode-order times) pts = table.remove(pool, 1) end table.insert(queue, { f.image, pts, f.keyframe }) @@ -285,9 +247,8 @@ function H264.newVideoDecoder(track: Types.Track, opts: any?): (Types.VideoCodec 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. +-- 7.4.1.2.3: a new access 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 function H264.accessUnits(data: any, off: number?, len: number?): { any } local b = toBuffer(data) local out = {} @@ -312,7 +273,6 @@ function H264.accessUnits(data: any, off: number?, len: number?): { any } 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 @@ -341,8 +301,6 @@ function H264.accessUnits(data: any, off: number?, len: number?): { any } 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 @@ -366,7 +324,6 @@ function H264.toAnnexB(config: buffer?, sample: buffer): (buffer?, Err.Err?) 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 @@ -405,7 +362,6 @@ function H264.info(data: any): any 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 local ny = img.width * img.height diff --git a/src/Rosetta/codecs/video/Legacy/Cinepak.luau b/src/Rosetta/codecs/video/Legacy/Cinepak.luau index 75e111d..9327fdf 100644 --- a/src/Rosetta/codecs/video/Legacy/Cinepak.luau +++ b/src/Rosetta/codecs/video/Legacy/Cinepak.luau @@ -1,14 +1,10 @@ --!strict --!native --!optimize 2 --- codecs/video/Legacy/Cinepak: Cinepak ('cvid') frames: 24-bit colour (codebook entries of 4 luma + 2 chroma, or 4 --- luma for grey), and 8-bit palettised streams (entries are palette indexes). Written from the format description --- (MultimediaWiki "Cinepak"): a frame header (flags, size, width, height, strip count), strips with their own V1 / V4 --- codebooks (full or partial updates, kept per strip between frames, inherited from the strip above unless the frame --- flags say otherwise) and the vector chunks (intra, inter with skip flags, V1-only). Colour codebook entries are --- converted once with the Cinepak YUV formula (r = y + 2v, g = y - u/2 - v, b = y + 2u, clamped). Sega FILM's extra --- header bytes are detected on the first frame. Paints over the previous picture. Bit-exact with ffmpeg's cinepak --- decoder. Never throws: every read is range-checked against its chunk. +-- codecs/video/Legacy/Cinepak: Cinepak ('cvid') frames, 24-bit colour and 8-bit palettised. +-- From MultimediaWiki "Cinepak", bit-exact with ffmpeg: a frame header (flags, size, width, height, strip count), strips +-- with V1 / V4 codebooks (inherited from the strip above unless the flags say otherwise) and vector chunks. +-- Colour entries: r = y + 2v, g = y - u/2 - v, b = y + 2u, clamped. local Picture = require("@rosetta/codecs/video/Legacy/Picture") local readu8, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu32, buffer.writeu32, buffer.writeu8 @@ -93,7 +89,7 @@ local function codebook(books: buffer, book: number, id: number, d: buffer, p: n end end --- the vectors of a strip (ids 0x30 intra, 0x31 inter with skip flags, 0x32 V1 only); false on truncated data +-- the vectors of a strip (ids 0x30 intra, 0x31 inter with skip flags, 0x32 V1 only) local function vectors(pic: Picture.Picture, books: buffer, v4: number, v1: number, id: number, d: buffer, p: number, stop: number, x1: number, y1: number, x2: number, y2: number): boolean local stride = pic.stride @@ -194,8 +190,6 @@ local function vectors(pic: Picture.Picture, books: buffer, v4: number, v1: numb return true end --- decode(pic, data, state, hasPalette) -> picture?, message: true = a picture; false + nil = no picture for this --- packet (an empty frame); false + message = an error function Cinepak.decode(pic: Picture.Picture, d: buffer, st: State, newPalette: boolean): (boolean, string?) local n = buffer.len(d) if n < 10 then @@ -238,7 +232,6 @@ function Cinepak.decode(pic: Picture.Picture, d: buffer, st: State, newPalette: local p = 10 + skip strips = math.min(strips, MAX_STRIPS) local books = st.books - -- the coded area: the size rounded up to whole blocks (the picture's plane) local cw, ch = pic.stride, pic.rows local y0 = 0 for i = 0, strips - 1 do @@ -263,7 +256,6 @@ function Cinepak.decode(pic: Picture.Picture, d: buffer, st: State, newPalette: if i > 0 and band(flags, 1) == 0 then buffer.copy(books, v4, books, v4 - 2 * BOOK, 2 * BOOK) end - -- the strip's chunks: codebooks, then one vector chunk -- (strips start on block boundaries in every known stream: the plane holds whole blocks only) if sx2 > cw or sy2 > ch or sx1 >= sx2 or sy1 >= sy2 or band(sx1, 3) ~= 0 or band(sy1, 3) ~= 0 then return true, nil diff --git a/src/Rosetta/codecs/video/Legacy/Flic.luau b/src/Rosetta/codecs/video/Legacy/Flic.luau index 70760ed..9ec898b 100644 --- a/src/Rosetta/codecs/video/Legacy/Flic.luau +++ b/src/Rosetta/codecs/video/Legacy/Flic.luau @@ -1,15 +1,12 @@ --!strict --!native --!optimize 2 --- codecs/video/Legacy/Flic: Autodesk Animator FLI / FLC frames (the F1FA frame chunks; the file format is --- video/fli). Written from the FLIC file format description (Jim Kent's "FLC - Animator Pro Flic Files", Dr. Dobb's --- 1993; MultimediaWiki "Flic Video"). 8-bit palettised: COLOR_256 (4), COLOR_64 (11, 6-bit entries widened by bit --- replication), DELTA_FLC / SS2 (7: word runs, line skips, last-byte opcode), DELTA_FLI / LC (12: byte runs), BLACK --- (13), BYTE_RUN / BRUN (15), FLI_COPY (16, rows padded to 4), PSTAMP (18, skipped). 15 / 16 / 24-bit FLC and FLX --- (DTA): DELTA / DTA_LC (pixel runs), BLACK, BRUN (byte runs), DTA_BRUN (25, pixel runs), COPY / DTA_COPY (16 / 26); --- pixels are 5-5-5 / 5-6-5 little-endian words or B, G, R bytes. Not supported: 1-bit FLICs, the Magic Carpet --- 6-bit COLOR_256 variant. Paints over the previous picture. Bit-exact with ffmpeg's flic decoder on valid frames. --- Never throws: reads past the frame give zeros, every write is range-checked (a damaged frame gives no picture). +-- codecs/video/Legacy/Flic: Autodesk Animator FLI / FLC frames (the F1FA frame chunks; the file format is video/fli). +-- From Jim Kent's "FLC - Animator Pro Flic Files" (Dr. Dobb's 1993) and MultimediaWiki "Flic Video", bit-exact with +-- ffmpeg. 8-bit: COLOR_256 (4), COLOR_64 (11), DELTA_FLC / SS2 (7), DELTA_FLI / LC (12), BLACK (13), BYTE_RUN / BRUN +-- (15), FLI_COPY (16, rows padded to 4), PSTAMP (18). 15 / 16 / 24-bit FLC and FLX (DTA): DELTA / DTA_LC, BLACK, BRUN, +-- DTA_BRUN (25), COPY / DTA_COPY (16 / 26); 5-5-5 / 5-6-5 little-endian words or B, G, R bytes. +-- Not supported: 1-bit FLICs, the Magic Carpet 6-bit COLOR_256 variant. local Types = require("@rosetta/Types") local Picture = require("@rosetta/codecs/video/Legacy/Picture") @@ -18,14 +15,12 @@ local bfill = buffer.fill local Flic = {} --- the decoding state of one stream: a byte plane (stride = width * bytes per pixel) and the palette export type State = { pic: Picture.Picture, depth: number, -- 8, 15, 16, 24 - bpp: number, -- bytes per pixel + bpp: number, } --- state(w, h, depth) -> State | nil, message function Flic.state(w: number, h: number, depth: number): (State?, string?) local bpp = if depth == 8 then 1 elseif depth == 15 or depth == 16 then 2 elseif depth == 24 then 3 else 0 if bpp == 0 then @@ -40,7 +35,6 @@ local function s8(v: number): number return if v >= 128 then v - 256 else v end --- decode(st, data) -> true | false, message function Flic.decode(st: State, d: buffer): (boolean, string?) local pic = st.pic local px = pic.idx :: buffer @@ -336,7 +330,6 @@ function Flic.decode(st: State, d: buffer): (boolean, string?) return true, nil end --- image(st) -> a fresh rgba8 Image function Flic.image(st: State): Types.Image local pic = st.pic if st.bpp == 1 then diff --git a/src/Rosetta/codecs/video/Legacy/Msvideo1.luau b/src/Rosetta/codecs/video/Legacy/Msvideo1.luau index a124449..aaf4950 100644 --- a/src/Rosetta/codecs/video/Legacy/Msvideo1.luau +++ b/src/Rosetta/codecs/video/Legacy/Msvideo1.luau @@ -1,12 +1,10 @@ --!strict --!native --!optimize 2 --- codecs/video/Legacy/Msvideo1: Microsoft Video 1 (CRAM / MSVC / WHAM) frames, 8-bit palettised and 16-bit --- X-R-G-B 1-5-5-5. Written from the format description (MultimediaWiki "Microsoft Video 1"): 4x4 blocks, block rows --- bottom-up (rows of a block bottom-up too), each block a 16-bit code: a skip count (0x84xx - 0x87xx), a 2-colour --- block (16 flag bits + 2 colours; at 16 bits a first colour with bit 15 set makes it an 8-colour block, one colour --- pair per quadrant; at 8 bits codes >= 0x9000 are 8-colour), or a 1-colour block. Paints over the previous picture. --- Bit-exact with ffmpeg's msvideo1 decoder. Never throws: every read is range-checked (a damaged frame stops there). +-- codecs/video/Legacy/Msvideo1: Microsoft Video 1 (CRAM / MSVC / WHAM), 8-bit palettised and 16-bit X-R-G-B 1-5-5-5. +-- From MultimediaWiki "Microsoft Video 1", bit-exact with ffmpeg: 4x4 blocks, block rows (and rows in a block) bottom-up; +-- a 16-bit code per block: skip (0x84xx - 0x87xx), 2-colour (16 flag bits + 2 colours; at 16 bits c0 bit 15 set = 8-colour, +-- a pair per quadrant; at 8 bits codes >= 0x9000 are 8-colour), else 1-colour. local Picture = require("@rosetta/codecs/video/Legacy/Picture") local readu8, readu16, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32 @@ -14,13 +12,11 @@ local band = bit32.band local Msvideo1 = {} --- the colour of pixel (x, y) of a block (y = 0 is the block's bottom row) for flag bit f: 2-colour c0 / c1 --- (bit set = c0), 8-colour: colours[quadrant * 2 + (bit clear)] +-- 2-colour: bit set = c0; 8-colour: colours[quadrant * 2 + (bit clear)] local function quadrant(x: number, y: number): number return (if y >= 2 then 4 else 0) + (if x >= 2 then 2 else 0) end --- decode(pic, data, bits) -> true | false, message (bits = 8: palettised, else 16-bit) function Msvideo1.decode(pic: Picture.Picture, d: buffer, bits: number): (boolean, string?) local n = buffer.len(d) local bw, bh = pic.w // 4, pic.h // 4 @@ -50,7 +46,6 @@ function Msvideo1.decode(pic: Picture.Picture, d: buffer, bits: number): (boolea if a == 0 and b == 0 and total == 0 then return true, nil end - -- the block's bottom-left pixel; its rows go up local o = (by * 4 + 3) * stride + bx * 4 if band(b, 0xFC) == 0x84 then skip = (b - 0x84) * 256 + a - 1 diff --git a/src/Rosetta/codecs/video/Legacy/Picture.luau b/src/Rosetta/codecs/video/Legacy/Picture.luau index 6c8c11a..ea26478 100644 --- a/src/Rosetta/codecs/video/Legacy/Picture.luau +++ b/src/Rosetta/codecs/video/Legacy/Picture.luau @@ -1,11 +1,8 @@ --!strict --!native --!optimize 2 --- codecs/video/Legacy/Picture: the picture every legacy decoder keeps between frames (they are all inter-frame --- codecs: a packet paints over the previous picture). Palettised codecs keep a u8 index plane and a 256-entry palette, --- direct-colour ones an rgba8 plane; both planes are padded (stride / rows) so the codecs' block and run writes past --- the visible edge land in range. Also the 5-5-5 / 5-6-5 to 8-bit tables: channels are widened by bit replication --- (c << 3 | c >> 2), as ffmpeg's swscale does, so the output equals ffmpeg's rgba conversion. New in rosetta. +-- codecs/video/Legacy/Picture: the picture the legacy inter-frame decoders paint over (u8 index plane + palette or rgba8). +-- 5-5-5 / 5-6-5 widen by bit replication (c << 3 | c >> 2), as ffmpeg's swscale does. local Types = require("@rosetta/Types") local Pixels = require("@rosetta/codecs/image/Pixels") @@ -23,7 +20,6 @@ export type Picture = { pal: buffer, -- 256 u32 entries, bytes R, G, B, A } --- new(w, h, palettised, padW?, padH?, palette?) -> a black picture; padW / padH round the plane up (blocks of 4, ...) function Picture.new(w: number, h: number, palettised: boolean, padW: number?, padH: number?, palette: buffer?): Picture local pw, ph = padW or 1, padH or 1 local stride = ((w + pw - 1) // pw) * pw @@ -41,7 +37,6 @@ function Picture.new(w: number, h: number, palettised: boolean, padW: number?, p return p end --- image(p) -> a fresh rgba8 Image of the visible w x h function Picture.image(p: Picture): Types.Image local w, h = p.w, p.h local img = Types.Image.new(w, h, "rgba8") @@ -60,7 +55,6 @@ function Picture.image(p: Picture): Types.Image return img end --- setPalette(p, src): a 1024-byte palette (u32 R, G, B, A entries) from a packet or the track function Picture.setPalette(p: Picture, src: buffer) if buffer.len(src) >= 1024 then buffer.copy(p.pal, 0, src, 0, 1024) @@ -70,7 +64,6 @@ end local lut555: buffer? = nil local lut565: buffer? = nil --- rgb555() -> u32 table: X-R-G-B 1-5-5-5 value -> rgba8 pixel (opaque); 32768 entries function Picture.rgb555(): buffer local t = lut555 if t then @@ -86,7 +79,6 @@ function Picture.rgb555(): buffer return b end --- rgb565() -> u32 table: R-G-B 5-6-5 value -> rgba8 pixel; 65536 entries function Picture.rgb565(): buffer local t = lut565 if t then @@ -102,7 +94,6 @@ function Picture.rgb565(): buffer return b end --- copy of a picture's plane (for decoders that read the previous picture while writing the next) function Picture.clonePlane(p: Picture): buffer local src = (p.idx or p.rgba) :: buffer local c = buffer.create(buffer.len(src)) diff --git a/src/Rosetta/codecs/video/Legacy/QtRle.luau b/src/Rosetta/codecs/video/Legacy/QtRle.luau index 9244245..d86a92e 100644 --- a/src/Rosetta/codecs/video/Legacy/QtRle.luau +++ b/src/Rosetta/codecs/video/Legacy/QtRle.luau @@ -1,14 +1,11 @@ --!strict --!native --!optimize 2 --- codecs/video/Legacy/QtRle: QuickTime Animation ('rle ') frames, depths 1, 2, 4, 8 (palettised; 33..40 = grey) and --- 16 (X-R-G-B 1-5-5-5), 24 (R, G, B), 32 (A, R, G, B). Written from the format description (Apple QuickTime File --- Format; MultimediaWiki "Apple QuickTime RLE"): a chunk size, a header (0x0008: start line + line count), then per --- line a skip byte and run codes until -1 (0: another skip; < 0: one pixel group repeated; > 0: literal groups). --- Groups are 4 pixels at 8 bits, 8 at 4 bits, 16 at 2 bits, 1 pixel at 16 / 24 / 32 bits; the 1-bit layout has its --- own (skip, code) pairs where a skip with bit 7 set moves to the next line. Paints over the previous picture; frames --- shorter than 8 bytes repeat it. Bit-exact with ffmpeg's qtrle decoder on valid streams. Never throws: every read --- and write is range-checked (a damaged frame stops where the damage is). +-- codecs/video/Legacy/QtRle: QuickTime Animation ('rle ') frames, depths 1, 2, 4, 8 (palettised; 33..40 = grey), +-- 16 (X-R-G-B 1-5-5-5), 24 (R, G, B), 32 (A, R, G, B). From Apple QuickTime File Format and MultimediaWiki "Apple +-- QuickTime RLE", bit-exact with ffmpeg on valid streams: chunk size, header (0x0008: start line + line count), per line +-- a skip byte and codes until -1 (0: another skip; < 0: one group repeated; > 0: literal groups). Groups are 4 pixels at +-- 8 bits, 8 at 4, 16 at 2, 1 at 16 / 24 / 32. Frames shorter than 8 bytes repeat the picture. local Picture = require("@rosetta/codecs/video/Legacy/Picture") local readu8, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu8, buffer.writeu32 @@ -83,8 +80,8 @@ end -- 2 / 4 / 8-bit: groups of 16 / 8 / 4 indexes (4 bytes); skips count groups local function decodeIdx(px: buffer, stride: number, limit: number, d: buffer, p: number, n: number, row: number, lines: number, bpp: number) - local group = 32 // bpp -- pixels per 4 bytes - local per = 8 // bpp -- pixels per byte + local group = 32 // bpp + local per = 8 // bpp local mask = 2 ^ bpp - 1 for _ = 1, lines do if p >= n then @@ -224,11 +221,10 @@ local function decodeRgb(px: buffer, stride: number, limit: number, d: buffer, p end end --- decode(pic, data, depth) -> true (a picture, possibly the previous one again) | false, message function QtRle.decode(pic: Picture.Picture, d: buffer, depth: number): (boolean, string?) local n = buffer.len(d) if n < 8 then - return true, nil -- no change + return true, nil end local p = 4 local header = readu8(d, p) * 256 + readu8(d, p + 1) @@ -264,7 +260,6 @@ function QtRle.decode(pic: Picture.Picture, d: buffer, depth: number): (boolean, return true, nil end --- palettised(depth) -> whether the depth uses a palette; pad(depth) -> the row padding the plane needs function QtRle.palettised(depth: number): boolean return depth <= 8 or depth > 32 end diff --git a/src/Rosetta/codecs/video/Legacy/Smacker.luau b/src/Rosetta/codecs/video/Legacy/Smacker.luau index ce7e395..3e565a7 100644 --- a/src/Rosetta/codecs/video/Legacy/Smacker.luau +++ b/src/Rosetta/codecs/video/Legacy/Smacker.luau @@ -2,17 +2,12 @@ --!native --!optimize 2 -- codecs/video/Legacy/Smacker: RAD Game Tools' Smacker video (SMK2 / SMK4 frames; the file format is video/smk) and --- the Huffman trees Smacker audio shares. Written from the format description (MultimediaWiki "Smacker"). Bits are --- read LSB first. A tree is a pre-order bit string (1 = node: left subtree then right; 0 = leaf with its value); --- an 8-bit tree's leaves hold bytes, a "big" tree's leaves hold 16-bit values made of a low-byte and a high-byte --- 8-bit tree, three of them being escape leaves that return the three most recently decoded values instead (a --- per-frame cache, reset to 0 at each frame). The four big trees (MMAP, MCLR, FULL, TYPE) come from the file header; --- a frame is 4x4 blocks in raster order, each TYPE code giving a block type and a run length: MONO (two colours and a --- 16-bit mask), FULL (16 pixels as 8 codes; SMK4 adds a 2x2-doubled and a 2x1-doubled mode), SKIP, FILL (one colour). --- Trees are flat arrays (a node stores the size of its left subtree, as a negative number); the frame decoder reads --- 10 bits at a time through a lookup table into them. --- Bit-exact with ffmpeg's smackvid decoder. Never throws: trees are bounded (depth, entries), reads past the data give --- zero bits, a frame whose codes run out of bits gives no picture. +-- the Huffman trees Smacker audio shares. From MultimediaWiki "Smacker", bit-exact with ffmpeg's smackvid. +-- Bits LSB first. A tree is a pre-order bit string (1 = node: left subtree then right; 0 = leaf). A big tree's 16-bit +-- leaves pair a low-byte and a high-byte 8-bit tree; three escape leaves return the three most recently decoded values +-- (reset each frame). The header holds the MMAP, MCLR, FULL and TYPE big trees; a frame is 4x4 blocks in raster order, +-- each TYPE code a block type and run length: MONO (two colours + 16-bit mask), FULL (16 pixels as 8 codes; SMK4 adds +-- 2x2- and 2x1-doubled modes), SKIP, FILL. local Picture = require("@rosetta/codecs/video/Legacy/Picture") local readu8, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu8, buffer.writeu32 @@ -30,7 +25,6 @@ for i = 1, 59 do end RUNS[60], RUNS[61], RUNS[62], RUNS[63], RUNS[64] = 128, 256, 512, 1024, 2048 --- a bit position over buf[0, nbits / 8) export type Bits = { buf: buffer, pos: number, nbits: number } function Smacker.bits(buf: buffer, offset: number, length: number): Bits @@ -47,7 +41,6 @@ local function bit(br: Bits): number end Smacker.bit = bit --- read(br, n) -> n bits (LSB first; zeros past the end) function Smacker.read(br: Bits, n: number): number local v, m = 0, 1 for _ = 1, n do @@ -58,7 +51,7 @@ function Smacker.read(br: Bits, n: number): number end local readBits = Smacker.read --- walk(tree, br) -> the leaf value (no end-of-data check: 8-bit trees, as the reference's table lookups) +-- no end-of-data check for 8-bit trees, as the reference's table lookups local function walk(tree: { number }, br: Bits): number local i = 1 local e = tree[1] @@ -73,7 +66,6 @@ local function walk(tree: { number }, br: Bits): number end Smacker.walk = walk --- the pre-order tree reader: leaf(index) -> value | nil, message; returns the flat tree (1-based) local function build(br: Bits, maxDepth: number, maxEntries: number, leaf: (number) -> (number?, string?), bigChecks: boolean): ({ number }?, string?) local vals: { number } = {} local n = 0 @@ -120,7 +112,6 @@ local function build(br: Bits, maxDepth: number, maxEntries: number, leaf: (numb end end --- tree8(br) -> an 8-bit tree (leaves are bytes) | nil, message function Smacker.tree8(br: Bits): ({ number }?, string?) local leaves = 0 return build(br, MAX_DEPTH8, 511, function(_: number): (number?, string?) @@ -138,7 +129,6 @@ local tree8 = Smacker.tree8 export type BigTree = { vals: { number }, last: { number }, lut: buffer? } -- last: the escape leaves' indexes (1-based) --- bigTree(br, size) -> one of the header's trees | nil, message (size = its byte size from the header: bounds entries) local function bigTree(br: Bits, size: number): (BigTree?, string?) if bit(br) == 0 then return { vals = { 0, 0 }, last = { 2, 2, 2 } }, nil -- no tree: every code is 0 @@ -184,7 +174,7 @@ end export type Trees = { mmap: BigTree, mclr: BigTree, full: BigTree, type: BigTree } --- trees(config) -> the four header trees | nil, message. config = the four u32 tree sizes then the tree bits +-- config = the four u32 tree sizes, then the tree bits function Smacker.trees(config: buffer): (Trees?, string?) local n = buffer.len(config) if n <= 16 then @@ -241,7 +231,6 @@ local function reset(t: BigTree) vals[last[1]], vals[last[2]], vals[last[3]] = 0, 0, 0 end --- decode(pic, data, trees, v4) -> true | false, message. pic: palettised, padded to blocks of 4 function Smacker.decode(pic: Picture.Picture, d: buffer, trees: Trees, v4: boolean): (boolean, string?) local px = pic.idx :: buffer local stride = pic.stride @@ -255,7 +244,6 @@ function Smacker.decode(pic: Picture.Picture, d: buffer, trees: Trees, v4: boole local n = buffer.len(d) local nbits = n * 8 local pos = 0 - -- the next value of a tree (updating its recent-value cache) | -1 when the bits run out inside the tree local function code(t: BigTree): number local vals = t.vals local i, p diff --git a/src/Rosetta/codecs/video/Legacy/Smc.luau b/src/Rosetta/codecs/video/Legacy/Smc.luau index 23afbc5..4d27fd7 100644 --- a/src/Rosetta/codecs/video/Legacy/Smc.luau +++ b/src/Rosetta/codecs/video/Legacy/Smc.luau @@ -1,13 +1,9 @@ --!strict --!native --!optimize 2 --- codecs/video/Legacy/Smc: QuickTime Graphics ('smc ') frames, 8-bit palettised. Written from the format description --- (MultimediaWiki "Apple SMC"): 4x4 blocks in raster order, opcodes in the high nibble with a block count (low nibble --- + 1, or the next byte + 1 when bit 4 is set): skip, repeat the last block, repeat the last pair of blocks, 1-colour --- fill, 2 / 4 / 8-colour blocks (the colour groups go into 256-entry rotating tables, or come from them by index: --- the tables restart every frame) and 16-colour blocks. Paints over the previous picture. Bit-exact with ffmpeg's smc --- decoder (for widths whose rows are not padded: the previous block of a row start is the last block of the row --- above). Never throws: reads past the data give zeros, the block count bounds every write. +-- codecs/video/Legacy/Smc: QuickTime Graphics ('smc ') frames, 8-bit palettised; from MultimediaWiki "Apple SMC", +-- bit-exact with ffmpeg. 4x4 blocks in raster order; opcode in the high nibble, count = low nibble + 1 (bit 4: next +-- byte + 1); the colour-group tables restart every frame. As ffmpeg: a row start's previous block ends the row above. local Picture = require("@rosetta/codecs/video/Legacy/Picture") local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32 @@ -15,7 +11,6 @@ local band, rshift = bit32.band, bit32.rshift local Smc = {} --- decode(pic, data, tables) -> true | false, message. tables = Smc.tables() (scratch, reused between frames) function Smc.decode(pic: Picture.Picture, d: buffer, tables: buffer): (boolean, string?) local px = pic.idx :: buffer local n = buffer.len(d) @@ -27,7 +22,6 @@ function Smc.decode(pic: Picture.Picture, d: buffer, tables: buffer): (boolean, end local blocksWide = (pic.w + 3) // 4 local p = 4 -- flags byte + 24-bit chunk size - -- block position: bx, by (blocks) local bx, by = 0, 0 local pairI, quadI, octI = 0, 0, 0 -- tables: pairs at 0 (256 * 2), quads at 512 (256 * 4), octets at 1536 (256 * 8) @@ -159,7 +153,6 @@ function Smc.decode(pic: Picture.Picture, d: buffer, tables: buffer): (boolean, advance() end else - -- 16-colour blocks for _ = 1, count do if total <= 0 or by >= bh then break @@ -175,7 +168,6 @@ function Smc.decode(pic: Picture.Picture, d: buffer, tables: buffer): (boolean, return true, nil end --- tables() -> the colour group scratch (pairs, quads, octets) function Smc.tables(): buffer return buffer.create(512 + 1024 + 2048) end diff --git a/src/Rosetta/codecs/video/Legacy/init.luau b/src/Rosetta/codecs/video/Legacy/init.luau index 8a0ddc2..259569b 100644 --- a/src/Rosetta/codecs/video/Legacy/init.luau +++ b/src/Rosetta/codecs/video/Legacy/init.luau @@ -1,22 +1,7 @@ --!strict -- codecs/video/Legacy: FLI / FLC, Cinepak, Microsoft Video 1, QuickTime RLE / SMC and Smacker video decoders. --- The 1990s inter-frame codecs as codecs/video/Video registry decoders (rgba8 pictures, one per packet): Autodesk --- FLI / FLC ("flic", the frames of video/fli), Cinepak ("cinepak", --- 'cvid'), Microsoft Video 1 ("msvideo1": CRAM / MSVC / WHAM, 8-bit palettised and 16-bit), QuickTime Animation --- ("qtrle", 'rle ': depths 1 / 2 / 4 / 8 / 16 / 24 / 32 and grey), QuickTime Graphics ("smc", 'smc ') and Smacker --- video ("smackvid", the frames of video/smk: track.config = the header's tree sizes and trees, codecTag SMK2 / SMK4). --- New in rosetta, written from the format descriptions (see each submodule); decoding is bit-exact with ffmpeg's --- decoders (tests/codecs/legacy.luau). Every decoder keeps the previous picture (a packet paints over it) and returns --- a fresh copy. --- --- Palettes come from the Track: track.palette (256 u32 entries, bytes R, G, B, A: the AVI BITMAPINFO palette, the --- QuickTime sample description's colour table, ...) and a packet's own `palette` (same layout) replaces it from that --- packet on. Depths come from track.bitsPerPixel (AVI biBitCount, the QuickTime depth). --- --- local dec, err = Legacy.newDecoder("cinepak", track, { maxPixels = 2^22 }) -- a Types.VideoCodecDecoder --- Legacy.CODECS --> { "flic", "cinepak", "msvideo1", "qtrle", "smc", "smackvid" } --- --- Never throws: bad tracks return nil, Err; bad packets return Err from decode(). +-- From the format descriptions (see each submodule), bit-exact with ffmpeg. Palette: track.palette, replaced by a +-- packet's palette (256 u32 entries R, G, B, A); depth: track.bitsPerPixel (AVI biBitCount, QuickTime depth). local Err = require("@rosetta/core/Err") local Types = require("@rosetta/Types") local Picture = require("@rosetta/codecs/video/Legacy/Picture") @@ -39,11 +24,10 @@ Legacy.Smacker = Smacker Legacy.CODECS = { "flic", "cinepak", "msvideo1", "qtrle", "smc", "smackvid" } export type Options = { - maxPixels: number?, -- refuse bigger pictures (LIMIT; default 2^26) + maxPixels: number?, [string]: any, } --- the per-codec pieces: make(track) -> state, step(state, data, packet) -> image? | nil, Err? type Codec = { make: (track: Types.Track) -> (any, string?), step: (st: any, data: buffer, packet: Types.Packet) -> (Types.Image?, Err.Err?), @@ -165,7 +149,6 @@ local CODECS: { [string]: Codec } = { }, } --- newDecoder(id, track, opts?) -> a Types.VideoCodecDecoder | nil, Err function Legacy.newDecoder(id: string, track: Types.Track, opts: Options?): (Types.VideoCodecDecoder?, Err.Err?) local codec = CODECS[id] if not codec then @@ -183,7 +166,6 @@ function Legacy.newDecoder(id: string, track: Types.Track, opts: Options?): (Typ if not st then return nil, fail(msg) end - -- Video.simpleDecoder, without requiring the registry (which requires this module) local queue: { any } = {} local self = {} function self.decode(_: any, packet: Types.Packet): Err.Err? @@ -206,7 +188,7 @@ function Legacy.newDecoder(id: string, track: Types.Track, opts: Options?): (Typ function self.flush(_: any) end function self.reset(_: any) table.clear(queue) - st = codec.make(track) or st -- back to a black picture with the track's palette (decoding restarts at a keyframe) + st = codec.make(track) or st end return self :: any, nil end diff --git a/src/Rosetta/codecs/video/Mpeg1/init.luau b/src/Rosetta/codecs/video/Mpeg1/init.luau index 265c771..20a8c68 100644 --- a/src/Rosetta/codecs/video/Mpeg1/init.luau +++ b/src/Rosetta/codecs/video/Mpeg1/init.luau @@ -1,7 +1,6 @@ --!strict --- codecs/video/Mpeg1: the MPEG-1 video decoder (ISO/IEC 11172-2), which is codecs/video/Mpeg2 (an MPEG-2 decoder --- decodes MPEG-1 streams): this module keeps the old name and API (Mpeg1.new, frameImage, PICTURE_*, the Frame / --- Options / Decoder types). Absorbed from mpeg1-luau e2e2898 (same author); see codecs/video/Mpeg2. +-- codecs/video/Mpeg1: the MPEG-1 video decoder (ISO/IEC 11172-2), the old name and API over codecs/video/Mpeg2. +-- From mpeg1-luau e2e2898 (same author). local Mpeg2 = require("@rosetta/codecs/video/Mpeg2") export type Frame = Mpeg2.Frame diff --git a/src/Rosetta/codecs/video/Mpeg2/Decoder.luau b/src/Rosetta/codecs/video/Mpeg2/Decoder.luau index 8e9b64f..93f53e7 100644 --- a/src/Rosetta/codecs/video/Mpeg2/Decoder.luau +++ b/src/Rosetta/codecs/video/Mpeg2/Decoder.luau @@ -1,24 +1,9 @@ --!strict --!native --- codecs/video/Mpeg2/Decoder: the MPEG-1 / MPEG-2 video decoding core (native, never throws). --- ISO/IEC 11172-2 and ISO/IEC 13818-2 Main profile: I, P and B pictures; progressive and interlaced sequences; frame --- pictures (frame / field motion compensation, frame / field DCT) and field pictures (field and 16x8 motion --- compensation, the second field predicted from the first); dual-prime; 4:2:0 and 4:2:2; intra DC precision 8..11; --- linear and non-linear quantiser scales; Table B-15 intra VLCs; the alternate scan; custom (and chroma) quantiser --- matrices; mismatch control; concealment motion vectors; sequence headers anywhere (size changes). Not supported: --- 4:4:4, the scalable / multiview extensions, D-pictures (skipped). --- --- Grown from the MPEG-1 core absorbed from mpeg1-luau e2e2898 (same author; a port of jsmpeg's decoder, src/mpeg1.js --- by Dominic Szablewski, MIT, licenses/jsmpeg-MIT.txt, with table-driven VLCs, B-pictures and SWAR motion --- compensation). The IDCT and motion compensation are codecs/video/Dsp (the IDCT bit-exact with ffmpeg's -idct int), --- and dequantisation follows ffmpeg's arithmetic, so the output planes equal `ffmpeg -idct int` decoding for valid --- streams (tests/codecs/mpeg2.luau, tests/codecs/mpeg1.luau). Coefficients are saturated to -2048..2047 (13818-2 --- 7.4.3; ffmpeg omits it, valid streams never reach it) and motion vectors pointing outside the reference are --- clamped (ffmpeg skips the prediction): both only matter for corrupt data. --- --- Everything works on flat buffers allocated per sequence size: no allocation per block, macroblock or picture. --- 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. +-- codecs/video/Mpeg2/Decoder: the MPEG-1 / MPEG-2 video decoding core (ISO/IEC 11172-2, 13818-2 Main profile). +-- From mpeg1-luau e2e2898 (same author; a port of jsmpeg's src/mpeg1.js by Dominic Szablewski, MIT, +-- licenses/jsmpeg-MIT.txt). Dequantisation follows ffmpeg's arithmetic; coefficients are saturated to -2048..2047 +-- (13818-2 7.4.3; ffmpeg omits it) and vectors outside the reference are clamped (ffmpeg skips the prediction). local V = require("@rosetta/codecs/video/Mpeg2/Vlc") local T = require("@rosetta/codecs/video/Mpeg2/Tables") local Dsp = require("@rosetta/codecs/video/Dsp") @@ -83,17 +68,13 @@ 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 --- clamp to 0..255 by lookup: RGB_CLAMP[v + COFF] = clamp(v, 0, 255) for v in [-COFF, COFF + 255] (the colour biases --- include COFF * 256, so the shifted sums below are indices): the same values as math.clamp, 2-3x faster natively +-- clamp by lookup: RGB_CLAMP[v + COFF] for v in [-COFF, COFF + 255]; the colour biases include COFF * 256 local RGB_CLAMP = buffer.create(2 * COFF + 256) for i = 0, 2 * COFF + 255 do buffer.writeu8(RGB_CLAMP, i, math.clamp(i - COFF, 0, 255)) end --- YCbCr 4:2:0 planes (coded strides) -> RGBA8 (alpha 255), w x h, nearest chroma like ffmpeg's default swscale path. --- Rows row0 .. row1 - 1 of the planes (row0 even; default 0 .. h) into out from byte oo (default 0). hook (optional) --- runs every 16 rows (a cooperative yield point; it is pcall'ed, so it can't throw through here). (From mpeg1-luau's --- later banded conversion.) +-- 4:2:0 -> RGBA8 with nearest chroma, like ffmpeg's default swscale path; hook is pcall'ed (can't throw through here) local function toRgba(Y: buffer, Cb: buffer, Cr: buffer, cw: number, w: number, h: number, out: buffer, row0: number?, row1: number?, oo: number?, hook: (() -> ())?) -- 2 x 2 pixels per chroma sample: the chroma terms are computed once per block of four local r0: number = row0 or 0 @@ -187,16 +168,10 @@ export type Store = { } 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. A frame coded as two field - -- pictures comes back once, after its second field. nextPicture: (atEnd: boolean, tag: any) -> (Store?, boolean), toRgba: (s: Store, out: buffer) -> (), reset: () -> (), - -- a cooperative yield point (e.g. coroutine.yield when over a time budget), run after every slice and every 16 - -- rows of colour conversion; nil = none. pcall'ed: it can't throw through the native code. setYield: (hook: (() -> ())?) -> (), state: { width: number, @@ -244,7 +219,6 @@ function D.new(maxPixels: number?): Core 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 @@ -252,7 +226,6 @@ function D.new(maxPixels: number?): Core local pos = 0 -- bit position inside data local err = false - -- sequence local hasSeq = false local mpeg2 = false local chroma = 1 -- 1 = 4:2:0, 2 = 4:2:2 @@ -273,7 +246,6 @@ function D.new(maxPixels: number?): Core -- the sequence header's values, applied (and the stores allocated) once its extension has been seen local seqW, seqH = 0, 0 - -- picture local ptype = 0 local fc00, fc01, fc10, fc11 = 1, 1, 1, 1 -- f_code[s][t] local fullPelFw, fullPelBw = false, false @@ -299,7 +271,6 @@ function D.new(maxPixels: number?): Core local pendingFw: Store? = nil local pendingBw: Store? = nil - -- slice / macroblock local qscale = 2 local mbAddr, mbRow, mbCol = 0, 0, 0 local dcY, dcCb, dcCr = 128, 128, 128 @@ -342,7 +313,6 @@ function D.new(maxPixels: number?): Core 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 @@ -396,7 +366,6 @@ function D.new(maxPixels: number?): Core end end - -- the sequence (header + extension) takes effect: sizes and stores local function applySequence(): boolean local w, h = seqW, seqH if w == 0 or h == 0 or w * h > state.maxPixels then @@ -428,7 +397,6 @@ function D.new(maxPixels: number?): Core return true end - -- sequence header at byte p (after the start code); false when invalid local function sequenceHeader(p: number): boolean pos = p * 8 local w = read(12) @@ -545,11 +513,6 @@ function D.new(maxPixels: number?): Core return (pred + d + range) % (2 * range) - range end - -- ------------------------------------------------------------------------------------------------ prediction - -- One prediction of the current macroblock part from the reference planes rY / rCb / rCr: field-based (sp >= 0: - -- source field sp, destination field dp of the frame, line stride 2 * cw) or frame-based (sp < 0); rowY / h: the - -- first luma line of the part in those lines and its height; (mvx, mvy) in half samples; avg averages into the - -- first prediction. local EDGE = buffer.create(Dsp.EDGE_SIZE) local function mcPart(rY: buffer, rCb: buffer, rCr: buffer, sp: number, dp: number, rowY: number, h: number, mvx: number, mvy: number, avg: boolean) local stride, sb, db, ph = cw, 0, 0, lumaH @@ -558,7 +521,6 @@ function D.new(maxPixels: number?): Core stride, sb, db, ph = 2 * cw, sp * cw, dp * cw, lumaH // 2 cs, csb, cdb = 2 * chw, sp * chw, dp * chw end - -- luma local hx, hy = band(mvx, 1), band(mvy, 1) local sx = mbCol * 16 + (mvx - hx) // 2 local sy = rowY + (mvy - hy) // 2 @@ -623,7 +585,6 @@ function D.new(maxPixels: number?): Core return (bwS or cur) :: Store end - -- the prediction of direction d (0 forward, 1 backward); avg: the second one of a bidirectional macroblock local function predictDir(d: number, avg: boolean) local o = d * 8 if not fieldPic then @@ -667,7 +628,6 @@ function D.new(maxPixels: number?): Core end end - -- the prediction of a non-intra macroblock from the current motion state local function predictMb() if ptype == 2 then predictDir(0, false) @@ -701,10 +661,8 @@ function D.new(maxPixels: number?): Core 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. + -- macroblocks no slice covers: ffmpeg's encoder skips a row's last macroblock at an MPEG-1 slice end and its decoder + -- conceals it as skipped; so do we (P / damaged I: zero-vector copy, B: the prediction before the gap) local covered = 0 local gapFw, gapBw = false, false local GAP = table.create(16, 0) @@ -761,9 +719,7 @@ function D.new(maxPixels: number?): Core FSEL[1], FSEL[2], FSEL[3], FSEL[4] = f1, f2, f3, f4 end - -- ------------------------------------------------------------------------------------------------ blocks - -- one 8x8 block b (0..3 luma, then Cb / Cr alternating): coefficients, dequantisation, IDCT into the picture. - -- False on a bitstream error. + -- block b: 0..3 luma, then Cb / Cr alternating local function decodeBlock(b: number): boolean local n = 0 local q: buffer @@ -828,7 +784,6 @@ function D.new(maxPixels: number?): Core local qs = qscale local m2 = mpeg2 while true do - -- inline peek local bp = rshift(pos, 3) local w = bswap(readu32(data, bp)) local s = band(pos, 7) @@ -911,7 +866,7 @@ function D.new(maxPixels: number?): Core if m2 then parityOdd = bxor(parityOdd, band(m, 1)) end - -- saturate + -- saturation (13818-2 7.4.3) if m > 2047 then m = 2047 elseif m < -2048 then @@ -929,7 +884,6 @@ function D.new(maxPixels: number?): Core writei32(blk, 252, if v % 2 ~= 0 then v - 1 else v + 1) onlyDc = false end - -- reconstruction local dst, off, stride if luma then dst = curY @@ -973,7 +927,6 @@ function D.new(maxPixels: number?): Core return true end - -- ------------------------------------------------------------------------------------------------ macroblocks local function getQscale(code: number): number if qScaleType == 1 then return readu8(NON_LINEAR, code) @@ -1051,7 +1004,6 @@ function D.new(maxPixels: number?): Core end 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) @@ -1253,7 +1205,6 @@ function D.new(maxPixels: number?): Core end end - -- ------------------------------------------------------------------------------------------------ pictures -- the frame a picture completes becomes the newest reference (I / P) local function finishFrame(s: Store) if s.ptype ~= 3 then @@ -1262,8 +1213,7 @@ function D.new(maxPixels: number?): Core end end - -- The picture header at byte p (after 00 00 01 00) and its extensions, up to stop: the byte of the first slice - -- start code (-1: none) and the temporal reference, or nil when the picture is skipped + -- the picture header (after 00 00 01 00) and its extensions local function pictureHeader(p: number, stop: number): (number?, number) pos = p * 8 local tref = read(10) @@ -1316,7 +1266,6 @@ function D.new(maxPixels: number?): Core return at, tref end - -- the frame the picture decodes into (the pending one for a second field) and its references; false: skipped local function selectTarget(tref: number, tag: any): boolean fieldPic = picStruct ~= 3 parity = if picStruct == 2 then 1 else 0 @@ -1370,7 +1319,6 @@ function D.new(maxPixels: number?): Core return true end - -- plane addressing of the current picture local function setAddressing() local target = cur :: Store curY, curCb, curCr = target.y, target.cb, target.cr @@ -1390,15 +1338,12 @@ function D.new(maxPixels: number?): Core mbIntra = false end - -- The picture whose header starts at byte p (after 00 00 01 00) and ends at byte stop: the decoded frame, or nil - -- (skipped, or the first field of a frame). local function decodePicture(p: number, stop: number, tag: any): Store? local first, tref = pictureHeader(p, stop) if first == nil or not selectTarget(tref, tag) then return nil end setAddressing() - -- slices local at = first :: number while at >= 0 do local code = readu8(data, at + 3) @@ -1443,7 +1388,6 @@ function D.new(maxPixels: number?): Core 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 @@ -1468,7 +1412,6 @@ function D.new(maxPixels: number?): Core buffer.fill(data, dataLen, 0, PAD) end - -- the sequence header unit at byte at (up to stop): the header, then its extensions local function sequenceUnit(at: number, stop: number) local ok = sequenceHeader(at + 4) local s = findStart(at + 4, stop) diff --git a/src/Rosetta/codecs/video/Mpeg2/Tables.luau b/src/Rosetta/codecs/video/Mpeg2/Tables.luau index 86960c9..047344a 100644 --- a/src/Rosetta/codecs/video/Mpeg2/Tables.luau +++ b/src/Rosetta/codecs/video/Mpeg2/Tables.luau @@ -1,8 +1,7 @@ --!strict --- codecs/video/Mpeg2/Tables: MPEG-1 / MPEG-2 video constant tables. Those 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 0-based like the JS arrays; the MPEG-2 ones (DC sizes up to 11, Table B-15, the --- non-linear quantiser scale, the alternate scan) are the tables of ISO/IEC 13818-2 annex B / section 7. +-- codecs/video/Mpeg2/Tables: MPEG-1 / MPEG-2 video constant tables. +-- MPEG-1: jsmpeg's (https://github.com/phoboslab/jsmpeg, Dominic Szablewski, MIT, licenses/jsmpeg-MIT.txt), 0-based, via +-- mpeg1-luau e2e2898. MPEG-2 (DC sizes to 11, B-15, non-linear quantiser scale, alternate scan): ISO/IEC 13818-2 annex B / 7. 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, diff --git a/src/Rosetta/codecs/video/Mpeg2/Vlc.luau b/src/Rosetta/codecs/video/Mpeg2/Vlc.luau index 534bd0b..e9710a1 100644 --- a/src/Rosetta/codecs/video/Mpeg2/Vlc.luau +++ b/src/Rosetta/codecs/video/Mpeg2/Vlc.luau @@ -1,14 +1,8 @@ --!strict -- codecs/video/Mpeg2/Vlc: lookup tables for the MPEG-1 / MPEG-2 variable-length codes, built at load time (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. DCT_B15 is MPEG-2's Table B-15 (intra_vlc_format = 1), DC_LUMA / --- DC_CHROMA cover sizes up to 11. Absorbed from mpeg1-luau e2e2898 (same author, built from jsmpeg's binary trees); --- the MPEG-2 tables are built from code lists. +-- Flat: indexed by the next K bits, len * 65536 + (value + 32768), len 0 = invalid. DCT: two-level (8 + 8 bits), +-- len * 65536 + run * 256 + level, ESC = 0xFFFF, EOB = 0xFFFE, or SUB + subtable for a long-code prefix. +-- DCT_NEXT: "10" = end_of_block, "11" = run 0 / level 1 (jsmpeg reads "1" + one bit); DCT_FIRST: "1" = run 0 / level 1. local T = require("@rosetta/codecs/video/Mpeg2/Tables") local V = {} @@ -53,7 +47,6 @@ local function flat(tree: { [number]: number }): (buffer, number) return flatLeaves(leaves(tree)) end --- { { code, length } } indexed from 1 -> leaves with value = index - 1 local function codeLeaves(codes: { { number } }): { Leaf } local out: { Leaf } = {} for i, c in codes do @@ -66,7 +59,6 @@ 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 diff --git a/src/Rosetta/codecs/video/Mpeg2/init.luau b/src/Rosetta/codecs/video/Mpeg2/init.luau index 3013986..e464994 100644 --- a/src/Rosetta/codecs/video/Mpeg2/init.luau +++ b/src/Rosetta/codecs/video/Mpeg2/init.luau @@ -1,23 +1,8 @@ --!strict -- codecs/video/Mpeg2: an MPEG-1 / MPEG-2 video decoder (ISO/IEC 11172-2, ISO/IEC 13818-2 Main profile). --- Progressive and interlaced (frame and field pictures, field / dual-prime prediction, field DCT), 4:2:0 and 4:2:2, I / --- P / B pictures with display reordering, every MPEG-2 coding tool of Main profile (Mpeg2/Decoder.luau). Output planes --- are bit-exact with `ffmpeg -idct int` (codecs/video/Dsp; tests/codecs/mpeg2.luau, tests/codecs/mpeg1.luau). Grown from --- the MPEG-1 decoder absorbed from mpeg1-luau e2e2898 (same author), a port of jsmpeg's decoder --- (https://github.com/phoboslab/jsmpeg, Dominic Szablewski, MIT: licenses/jsmpeg-MIT.txt). codecs/video/Mpeg1 is this --- module under its old name. Frames come out woven (both fields of an interlaced frame, top field on even lines); --- frame.fields / topFieldFirst / repeatFirstField / progressive say how they were coded. --- Not supported: 4:4:4, the scalable / multiview extensions, D-pictures (skipped). --- --- local dec = Mpeg2.new({ reorder = true, rgba = false }) --- local frame = dec:decode(packetData, 0, len, pts) -- one picture (+ sequence / GOP headers) -> Frame?, tag = pts --- local img = Mpeg2.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, chroma, ... } --- local vdec = Mpeg2.newVideoDecoder(track, opts) -- a Types.VideoCodecDecoder (codecs/video/Video: mpeg1, mpeg2) --- --- Nothing here throws: bad arguments return nil / false, bad data is skipped (see Decoder.luau). +-- Bit-exact with `ffmpeg -idct int`. Grown from mpeg1-luau e2e2898 (same author), a port of jsmpeg's decoder +-- (https://github.com/phoboslab/jsmpeg, Dominic Szablewski, MIT: licenses/jsmpeg-MIT.txt). Frames come out woven (top +-- field on even lines). Not supported: 4:4:4, the scalable / multiview extensions, D-pictures (skipped). local Types = require("@rosetta/Types") local Err = require("@rosetta/core/Err") local D = require("@rosetta/codecs/video/Mpeg2/Decoder") @@ -34,10 +19,9 @@ export type Frame = { 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 planes (decoder-owned, valid until the next decode): luma stride codedWidth, chroma stride - -- codedWidth / 2, chroma rows half the luma rows (4:2:0) or as many (4:2:2) + index: number, + tag: any, + -- luma stride codedWidth, chroma stride codedWidth / 2; chroma rows half the luma rows (4:2:0) or as many (4:2:2) y: buffer, cb: buffer, cr: buffer, @@ -45,23 +29,17 @@ export type Frame = { chroma: number, -- 1 = 4:2:0, 2 = 4:2:2 mpeg2: boolean, progressive: boolean, -- progressive_frame (MPEG-1 and progressive MPEG-2: true) - fields: boolean, -- coded as two field pictures + fields: boolean, topFieldFirst: boolean, repeatFirstField: boolean, - clamped: number, -- predictions from outside the reference picture (an invalid stream; edge samples repeated) - concealed: { [number]: boolean }, -- 16-line bands with macroblocks no slice covered (concealed) + clamped: number, + concealed: { [number]: boolean }, } 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) - -- a cooperative yield point, run after every slice and every 16 rows of colour conversion: e.g. a function that - -- calls coroutine.yield() when a time budget is spent, to spread a picture over several frames (the decode call - -- then runs inside a coroutine). Don't call this decoder again while a decode is suspended. Errors in it are - -- ignored. See dec:setYield. + reorder: boolean?, + rgba: boolean?, + maxPixels: number?, yield: (() -> ())?, } @@ -154,7 +132,6 @@ local function sync(self: Decoder) 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) @@ -205,19 +182,14 @@ local function append(self: Decoder, data: any, offset: number?, len: number?): 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 @@ -225,8 +197,6 @@ function Decoder.decode(self: Decoder, data: buffer | string, offset: number?, l 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 @@ -240,24 +210,15 @@ function Decoder.flush(self: Decoder): Frame? return nil end --- Sets (or clears, nil) the cooperative yield hook (Options.yield). function Decoder.setYield(self: Decoder, hook: (() -> ())?) self._core.setYield(if type(hook) == "function" then hook else 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 --- YCbCr 4:2:0 planes (a frame's y / cb / cr / codedWidth, or copies of them) -> RGBA8 rows row0 .. row1 - 1 of a --- width x height picture, written to out from byte outOffset (default 0) as (row1 - row0) rows of width * 4 bytes. --- row0 is rounded down to even (rows share chroma in pairs); defaults 0 and height. Lets the conversion run in --- bands (on several threads) or only for the frames that are shown. The planes may hold only rows planeRow0 .. --- (planeRow0 even, default 0; their row 0 is picture row planeRow0). hook: a cooperative yield point every 16 rows. --- Returns false (writing nothing) when an argument is out of range. (4:2:0 only: a 4:2:2 frame's chroma has as many --- rows as its luma; use frameImage(frame, true) for those.) function Mpeg2.toRgba(y: buffer, cb: buffer, cr: buffer, codedWidth: number, width: number, height: number, out: buffer, row0: number?, row1: number?, outOffset: number?, planeRow0: number?, hook: (() -> ())?): boolean if type(y) ~= "buffer" or type(cb) ~= "buffer" or type(cr) ~= "buffer" or type(out) ~= "buffer" then return false @@ -274,7 +235,6 @@ function Mpeg2.toRgba(y: buffer, cb: buffer, cr: buffer, codedWidth: number, wid if r0 < 0 or r1 > h or r1 <= r0 or pr < 0 or pr % 2 ~= 0 or pr > r0 or oo < 0 or oo % 4 ~= 0 then return false end - -- the planes must cover rows pr .. r1 - 1 (luma) and their chroma rows; out the band local lumaRows = r1 - pr local chromaRows = (r1 + 1) // 2 - pr // 2 if buffer.len(y) < lumaRows * cw or buffer.len(cb) < chromaRows * (cw // 2) or buffer.len(cr) < chromaRows * (cw // 2) then @@ -283,15 +243,10 @@ function Mpeg2.toRgba(y: buffer, cb: buffer, cr: buffer, codedWidth: number, wid if buffer.len(out) < oo + (r1 - r0) * w * 4 then return false end - -- rows relative to the planes' first row D.toRgba(y, cb, cr, cw, w, h, out, r0 - pr, r1 - pr, oo, if type(hook) == "function" then hook else nil) return true 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"; 4:2:2 chroma --- averaged over line pairs of the same field), or rgba8 (the decoder's BT.601 conversion) when rgba is true. nil for --- a value that is not a Frame. function Mpeg2.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 @@ -360,10 +315,6 @@ function Mpeg2.frameImage(frame: Frame, rgba: boolean?): Types.Image? return img end --- ------------------------------------------------------------------------------------------------ VideoCodecDecoder --- newVideoDecoder(track, opts) -> a Types.VideoCodecDecoder (codecs/video/Video's mpeg1 and mpeg2 entries): pictures in --- decode order, reordered for display; the packet's pts travels with its picture. A packet may hold any number of --- pictures (MPEG-PS / TS units, AVI chunks) or part of one (written as a stream). function Mpeg2.newVideoDecoder(_track: any, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) local dec = Mpeg2.new({ reorder = true, rgba = false, maxPixels = opts and opts.maxPixels }) local queue: { any } = {} @@ -382,7 +333,7 @@ function Mpeg2.newVideoDecoder(_track: any, opts: any?): (Types.VideoCodecDecode if not ok then return Err.new(Err.CORRUPT, "decoder threw: " .. tostring(f)) end - while f do -- more pictures in the packet + while f do push(f) f = dec:decode(packet.data, 0, 0, tag) end diff --git a/src/Rosetta/codecs/video/Theora/Decoder.luau b/src/Rosetta/codecs/video/Theora/Decoder.luau index c641a36..ff328d9 100644 --- a/src/Rosetta/codecs/video/Theora/Decoder.luau +++ b/src/Rosetta/codecs/video/Theora/Decoder.luau @@ -1,22 +1,10 @@ --!strict --!native --!optimize 2 --- codecs/video/Theora/Decoder: the Theora frame decoder (Theora I specification, section 7; native, never throws). A --- Luau port of libtheora 1.2.0's decoder (Xiph.Org, BSD 3-clause: licenses/libtheora-BSD.txt; decode.c, state.c, --- idct.c, fragment.c) with the bit-exact reconstruction of the specification: --- * frame header, coded super block / block flags (the run-length codes), macro block modes (the 8 mode --- alphabets), motion vectors (VLC / fixed length, last / prior vectors, 4MV with the chroma averages of each pixel --- format), per-block qi indices, DC / AC tokens with EOB runs across blocks, planes and coefficients; --- * DC prediction, dequantisation, the spec's 16-bit integer IDCT (DC-only blocks as libtheora: (dc * q + 15) >> 5), --- half-pel motion compensation (two-reference average toward zero), the loop filter, border extension for --- unrestricted motion vectors, golden / previous reference frames; --- * 4:2:0, 4:2:2 and 4:4:4; empty packets repeat the previous frame. --- Differences from libtheora: coefficients are kept per fragment (64 i16 each) instead of libtheora's token lists, --- the frame is reconstructed whole (no MCU pipelining, same result), there is no post-processing (libtheora's default), --- and intermediate IDCT sums are not wrapped to 16 bits (only out-of-range streams differ). --- --- Planes are stored in Theora's own orientation (row 0 is the bottom of the picture) with 16 (luma) / 8 (subsampled --- chroma) pixels of edge padding; output() turns the picture region into top-down planes. +-- codecs/video/Theora/Decoder: the Theora frame decoder (Theora I specification, section 7). A Luau port of libtheora +-- 1.2.0's decoder (Xiph.Org, BSD 3-clause: licenses/libtheora-BSD.txt; decode.c, state.c, idct.c, fragment.c). +-- DC-only blocks as libtheora: (dc * q + 15) >> 5; IDCT sums are not wrapped to 16 bits (only out-of-range streams differ). +-- Planes are in Theora's orientation (row 0 = bottom) with 16 (luma) / 8 (subsampled chroma) pixels of edge padding. local Header = require("@rosetta/codecs/video/Theora/Header") local readu8 = buffer.readu8 @@ -211,7 +199,6 @@ export type State = { keyframes: number, } --- new(info, setup) -> State function D.new(info: Header.Info, setup: Header.Setup): State local pf = info.pixelFormat local hdec = if pf % 2 == 0 then 1 else 0 @@ -382,7 +369,6 @@ function D.new(info: Header.Info, setup: Header.Setup): State return st :: State end --- ------------------------------------------------------------------------------------------------ reconstruction -- the 8-point IDCT of libtheora's idct8 (the spec's), on 8 values; returns the 8 outputs local function idct8(x0: number, x1: number, x2: number, x3: number, x4: number, x5: number, x6: number, x7: number): (number, number, number, number, number, number, number, number) local t0 = (C4 * (x0 + x4)) // 65536 @@ -522,7 +508,6 @@ local function reconFrag(st: State, fi: number, qis: { number }, dstPlanes: { bu st.last[fi] = 0 idctRows(blk, st.tmp) end - -- the prediction if ri == SELF then for y = 0, 7 do bfill(dst, pos + y * stride, 128, 8) @@ -552,7 +537,6 @@ local function reconFrag(st: State, fi: number, qis: { number }, dstPlanes: { bu end end end - -- the residual if last ~= 0 then idctAdd(st.tmp, dst, pos, stride) elseif fv ~= 0 then @@ -565,7 +549,6 @@ local function reconFrag(st: State, fi: number, qis: { number }, dstPlanes: { bu end end --- ------------------------------------------------------------------------------------------------ loop filter local function filterH(b: buffer, p: number, stride: number, bv: { number }) p -= 2 for _ = 0, 7 do @@ -735,14 +718,10 @@ local function dcPredict(st: State) end end --- ------------------------------------------------------------------------------------------------ frame decode --- decode(st, data, off, len) -> kind ("key" | "inter" | "dup") | nil, message. The picture is then in --- st.refs[st.shown]. function D.decode(st: State, data: buffer, off: number, len: number): (string?, string?) if len <= 0 then return "dup", nil end - -- a zero-padded copy: reads past the end give zero bits, every read site clamps pos to the end first local bb = buffer.create(len + 24) bcopy(bb, 0, data, off, len) local maxp = len * 8 @@ -1216,7 +1195,6 @@ function D.decode(st: State, data: buffer, off: number, len: number): (string?, dcPredict(st) - -- reconstruction into a free reference buffer local self = 1 while self == st.gold or self == st.prev do self += 1 @@ -1249,9 +1227,6 @@ function D.decode(st: State, data: buffer, off: number, len: number): (string?, return if intra then "key" else "inter", nil end --- ------------------------------------------------------------------------------------------------ output --- the picture region of the shown frame as top-down planes: plane(st, pli, x0, y0, w, h) copies a w x h window whose --- top-left corner is (x0, y0) counted from the top of the plane function D.plane(st: State, pli: number, x0: number, y0: number, w: number, h: number): buffer local src = st.refs[st.shown][pli + 1] local stride, origin, ph = st.stride[pli + 1], st.origin[pli + 1], st.ph[pli + 1] @@ -1263,8 +1238,7 @@ function D.plane(st: State, pli: number, x0: number, y0: number, w: number, h: n return out end --- downsample(src, cw, ch, hdec, dst, off, ow, oh): 4:2:2 (hdec 1: rows averaged in pairs) or 4:4:4 (hdec 0: 2x2 --- averages) chroma of cw x ch into ow x oh 4:2:0 chroma at dst[off] +-- 4:2:2 (rows averaged in pairs) or 4:4:4 (2x2 averages) chroma down to 4:2:0 function D.downsample(src: buffer, cw: number, ch: number, hdec: number, dst: buffer, off: number, ow: number, oh: number) for r = 0, oh - 1 do local r0 = math.min(2 * r, ch - 1) diff --git a/src/Rosetta/codecs/video/Theora/Header.luau b/src/Rosetta/codecs/video/Theora/Header.luau index 61d4ce5..27f2892 100644 --- a/src/Rosetta/codecs/video/Theora/Header.luau +++ b/src/Rosetta/codecs/video/Theora/Header.luau @@ -1,11 +1,7 @@ --!strict --- codecs/video/Theora/Header: the three Theora headers (Theora I specification, section 6): identification (frame / --- picture size and offsets, frame rate, aspect, colour space, pixel format, keyframe granule shift), comment (Vorbis --- comment layout) and setup (loop-filter limits, quantisation parameters, the 80 DCT token Huffman trees), and the --- tables derived from them: the dequantisation matrices of every qi / plane / intra-inter and the collapsed Huffman --- lookup tables the frame decoder walks. A Luau port of libtheora 1.2.0 (Xiph.Org, BSD 3-clause: --- licenses/libtheora-BSD.txt): decinfo.c, dequant.c, quant.c (oc_dequant_tables_init), huffdec.c (the tree unpacking; --- the table layout here is simpler). Never throws: bad headers return nil, message. +-- codecs/video/Theora/Header: the three Theora headers (Theora I specification, section 6) and the dequantisation and +-- Huffman lookup tables derived from them. A Luau port of libtheora 1.2.0 (Xiph.Org, BSD 3-clause, +-- licenses/libtheora-BSD.txt): decinfo.c, dequant.c, quant.c (oc_dequant_tables_init), huffdec.c. local Bits = require("@rosetta/core/Bits") local H = {} @@ -18,7 +14,7 @@ export type Info = { frameHeight: number, picWidth: number, -- the picture region (the displayed part) picHeight: number, - picX: number, -- from the left + picX: number, picY: number, -- from the bottom, as stored fpsNum: number, fpsDen: number, @@ -53,8 +49,7 @@ local function ilog(v: number): number return n end --- ------------------------------------------------------------------------------------------------ identification --- info(buf, off, len) -> Info | nil, message: the packet starting with 0x80 "theora" +-- identification header: 0x80 "theora" function H.info(b: buffer, off: number, len: number): (Info?, string?) if len < 42 or buffer.readu8(b, off) ~= 0x80 or buffer.readstring(b, off + 1, 6) ~= "theora" then return nil, "not a Theora identification header" @@ -99,8 +94,7 @@ function H.info(b: buffer, off: number, len: number): (Info?, string?) return info, nil end --- ------------------------------------------------------------------------------------------------ comment --- comment(buf, off, len) -> vendor, { "KEY=value" } | nil, message: the packet starting with 0x81 "theora" +-- comment header: 0x81 "theora" function H.comment(b: buffer, off: number, len: number): (string?, { string }?, string?) if len < 7 or buffer.readu8(b, off) ~= 0x81 or buffer.readstring(b, off + 1, 6) ~= "theora" then return nil, nil, "not a Theora comment header" @@ -139,7 +133,6 @@ function H.comment(b: buffer, off: number, len: number): (string?, { string }?, return vendor, list, nil end --- ------------------------------------------------------------------------------------------------ Huffman trees -- A tree is read depth first (0: an internal node, 1 then 5 bits: a leaf with that token). It becomes lookup tables in -- one flat array: a node is huff[o] = n (bits to peek) followed by 2^n entries, entry = length * 64 + token (a leaf -- reached after `length` <= n of the peeked bits) or -offset (another node, after all n bits). @@ -166,7 +159,6 @@ local function readTree(br: any): ({ number }?, { number }?, { number }?) return nil, nil, nil end local t = br:read(5) - -- insert the leaf local n = 1 for d = 1, len do local k = (code // 2 ^ (32 - d)) % 2 @@ -247,11 +239,10 @@ local function buildTable(out: { number }, kid0: { number }, kid1: { number }, t return node(1) end --- ------------------------------------------------------------------------------------------------ setup local DC_MIN = { 16, 32 } local AC_MIN = { 8, 16 } --- setup(buf, off, len) -> Setup | nil, message: the packet starting with 0x82 "theora" +-- setup header: 0x82 "theora" function H.setup(b: buffer, off: number, len: number): (Setup?, string?) if len < 7 or buffer.readu8(b, off) ~= 0x82 or buffer.readstring(b, off + 1, 6) ~= "theora" then return nil, "not a Theora setup header" diff --git a/src/Rosetta/codecs/video/Theora/init.luau b/src/Rosetta/codecs/video/Theora/init.luau index eaee634..1c29955 100644 --- a/src/Rosetta/codecs/video/Theora/init.luau +++ b/src/Rosetta/codecs/video/Theora/init.luau @@ -1,20 +1,7 @@ --!strict --- codecs/video/Theora: a Theora video decoder (the Theora I specification, Xiph.Org), for Ogg (video/ogv) and Matroska --- (V_THEORA). A Luau port of the libtheora 1.2.0 decoder (BSD 3-clause, licenses/libtheora-BSD.txt): Header.luau --- (identification / comment / setup headers, dequantisation tables, Huffman trees) and Decoder.luau (native frames). --- Supports: every Theora I stream (bitstream 3.2.x and older 3.x): intra and inter frames, golden frames, 4MV --- macro blocks, all three pixel formats (4:2:0, 4:2:2, 4:4:4), picture regions smaller than the coded frame (odd sizes, --- offsets), empty packets (a repeated frame). Output is bit-exact with libtheora / ffmpeg (tests/codecs/theora.luau); --- yuv420p images average 4:2:2 / 4:4:4 chroma down (planes() keeps the native layout). --- Not supported: libtheora's optional post-processing (deblocking / deringing, off by default there too). --- --- local dec = Theora.new({ idHeader, commentHeader, setupHeader }) -- or the Xiph-laced Matroska CodecPrivate --- local kind = dec:decode(packet) -- "key" | "inter" | "dup" (empty packet / no coded blocks) | nil, Err --- local img = dec:image() -- a fresh yuv420p Types.Image of the picture region --- local y, u, v, cw, ch = dec:planes() -- native planes (chroma cw x ch), top-down --- Theora.granuleFrame(dec.info, granulepos) -- the 0-based frame index of an Ogg granule position --- --- Never throws: bad headers / packets come back as nil, Err (a corrupt frame still updates the picture). +-- codecs/video/Theora: a Theora video decoder (the Theora I specification, Xiph.Org), for Ogg and Matroska (V_THEORA). +-- A Luau port of the libtheora 1.2.0 decoder (BSD 3-clause, licenses/libtheora-BSD.txt), bit-exact with libtheora / +-- ffmpeg; libtheora's optional post-processing is not supported. local Err = require("@rosetta/core/Err") local Types = require("@rosetta/Types") local VorbisComment = require("@rosetta/codecs/audio/VorbisComment") @@ -26,12 +13,11 @@ local Theora = {} export type Info = Header.Info export type Options = { - maxPixels: number?, -- larger coded frames are refused (default 4096 * 2304) + maxPixels: number?, } local PIXEL_FORMATS = { [0] = "yuv420p", "reserved", "yuv422p", "yuv444p" } --- isHeader(buf, off?, len?) -> 1 / 2 / 3 for the identification / comment / setup header, else nil function Theora.isHeader(b: buffer, off: number?, len: number?): number? local o = off or 0 local n = len or (buffer.len(b) - o) @@ -45,7 +31,6 @@ function Theora.isHeader(b: buffer, off: number?, len: number?): number? return nil end --- splitConfig(config) -> the three header packets from Matroska's Xiph-laced CodecPrivate (or nil) function Theora.splitConfig(c: buffer): { buffer }? local n = buffer.len(c) if n < 3 or buffer.readu8(c, 0) ~= 2 then @@ -77,7 +62,6 @@ function Theora.splitConfig(c: buffer): { buffer }? return out end --- info(idHeader) -> Header.Info (frame / picture size, frame rate, granule shift, pixel format, ...) | nil, Err function Theora.info(h: buffer): (Header.Info?, Err.Err?) local ok, info, err = pcall(Header.info, h, 0, buffer.len(h)) if not ok or not info then @@ -86,7 +70,6 @@ function Theora.info(h: buffer): (Header.Info?, Err.Err?) return info, nil end --- comment(commentHeader) -> vendor, { "KEY=value" }, tags (lower-case keys) | nil, nil, nil, Err function Theora.comment(h: buffer): (string?, { string }?, { [string]: string }?, Err.Err?) local ok, vendor, list, err = pcall(Header.comment, h, 0, buffer.len(h)) if not ok or not vendor or not list then @@ -95,7 +78,6 @@ function Theora.comment(h: buffer): (string?, { string }?, { [string]: string }? return vendor, list, (VorbisComment.tags(list)), nil end --- granuleFrame(info, granulepos) -> the 0-based index of the frame a granule position ends on (-1 for none) function Theora.granuleFrame(info: Header.Info, g: number): number if g < 0 then return -1 @@ -111,7 +93,6 @@ function Theora.granuleFrame(info: Header.Info, g: number): number return f end --- ------------------------------------------------------------------------------------------------ decoder local Dec = {} Dec.__index = Dec @@ -126,14 +107,13 @@ export type TheoraDecoder = typeof(setmetatable( frameRate: number, pixelFormat: string, -- "yuv420p" | "yuv422p" | "yuv444p" aspect: number, -- pixel aspect ratio (1 when unknown) - frames: number, -- packets decoded (dupes included) + frames: number, _st: Decoder.State, - _any: boolean, -- a frame was decoded + _any: boolean, }, Dec )) --- new(headers, opts?) -> TheoraDecoder | nil, Err: headers = the three header packets, or the Xiph-laced config function Theora.new(headers: { buffer } | buffer, opts: Options?): (TheoraDecoder?, Err.Err?) local list: { buffer }? = nil if type(headers) == "buffer" then @@ -177,7 +157,6 @@ function Theora.new(headers: { buffer } | buffer, opts: Options?): (TheoraDecode }, Dec), nil end --- decode(data, off?, len?) -> "key" | "inter" | "dup" | nil, Err. Header packets are skipped (nil, nil). function Dec.decode(self: TheoraDecoder, data: buffer, off: number?, len: number?): (string?, Err.Err?) local o = off or 0 local n = len or (buffer.len(data) - o) @@ -198,7 +177,6 @@ function Dec.decode(self: TheoraDecoder, data: buffer, off: number?, len: number return kind, nil end --- reset(): after a seek (the next frame should be a keyframe; until then inter frames predict from grey / old data) function Dec.reset(self: TheoraDecoder) local st = self._st st.shown = st.prev @@ -210,8 +188,6 @@ local function window(self: TheoraDecoder): (number, number, number, number) return info.picX, info.frameHeight - info.picHeight - info.picY, info.picWidth, info.picHeight end --- planes() -> y, u, v (fresh top-down buffers of the picture region, chroma in the native layout), chroma width, --- chroma height function Dec.planes(self: TheoraDecoder): (buffer, buffer, buffer, number, number) local st = self._st local x0, y0, w, h = window(self) @@ -223,7 +199,6 @@ function Dec.planes(self: TheoraDecoder): (buffer, buffer, buffer, number, numbe return Decoder.plane(st, 0, x0, y0, w, h), Decoder.plane(st, 1, cx0, cy0, cw, ch), Decoder.plane(st, 2, cx0, cy0, cw, ch), cw, ch end --- image() -> a fresh yuv420p Types.Image of the picture (4:2:2 / 4:4:4 chroma averaged down) function Dec.image(self: TheoraDecoder): Types.Image local y, u, v, cw, ch = self:planes() local w, h = self.width, self.height @@ -247,9 +222,6 @@ function Dec.image(self: TheoraDecoder): Types.Image return img end --- ------------------------------------------------------------------------------------------------ registry --- newVideoDecoder(track, opts?) -> a Types.VideoCodecDecoder (the codecs/video/Video entry "theora"): track.config --- holds the three headers (Xiph-laced, as Matroska's CodecPrivate); one picture per packet, empty packets repeat function Theora.newVideoDecoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) if not track.config then return nil, Err.new(Err.CORRUPT, "Theora track without its headers") diff --git a/src/Rosetta/codecs/video/Video/Source.luau b/src/Rosetta/codecs/video/Video/Source.luau index 993375d..a9ce806 100644 --- a/src/Rosetta/codecs/video/Video/Source.luau +++ b/src/Rosetta/codecs/video/Video/Source.luau @@ -1,16 +1,6 @@ --!strict --- codecs/video/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 rosetta. --- --- 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 } } } +-- codecs/video/Video/Source: what a video writer (Matroska / WebM, AVI, Y4M, MP4) gets to write, from a VideoDecoder +-- or a Demuxer: each stream is copied (remuxed) or produced (decoded frames re-encoded, PCM audio). local Err = require("@rosetta/core/Err") local Types = require("@rosetta/Types") local Yuv = require("@rosetta/codecs/image/Yuv") @@ -41,7 +31,6 @@ 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 @@ -72,8 +61,6 @@ local function trackStream(track: Types.Track, packets: { OutPacket }): Stream } 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 @@ -140,7 +127,6 @@ local function encodeFrames(v: any, codec: string, opts: any): (Stream?, Err.Err } :: 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 @@ -184,7 +170,6 @@ local function pcmFrom(dec: any, opts: any): (Stream?, Err.Err?) } :: 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 @@ -192,7 +177,6 @@ function Source.streams(value: any, opts: any?, want: Want): ({ Stream }?, Err.E 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 @@ -208,7 +192,6 @@ function Source.streams(value: any, opts: any?, want: Want): ({ Stream }?, Err.E 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") @@ -232,7 +215,7 @@ function Source.streams(value: any, opts: any?, want: Want): ({ Stream }?, Err.E return out, nil end --- rational(fps) -> num, den: integer rates as n / 1, NTSC rates as n * 1000 / 1001, else to a millisecond +-- 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 @@ -247,9 +230,6 @@ function Source.rational(fps: number): (number, number) 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 @@ -277,8 +257,6 @@ function Source.constantRate(s: Stream, maxFps: number?): (number, number, { Out 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) diff --git a/src/Rosetta/codecs/video/Video/init.luau b/src/Rosetta/codecs/video/Video/init.luau index 942f3bc..2b71ad1 100644 --- a/src/Rosetta/codecs/video/Video/init.luau +++ b/src/Rosetta/codecs/video/Video/init.luau @@ -1,19 +1,5 @@ --!strict -- codecs/video/Video: the video codec registry and the generic VideoDecoder. New in rosetta. --- --- 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("@rosetta/codecs/video/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("@rosetta/core/Err") local Types = require("@rosetta/Types") local Yuv = require("@rosetta/codecs/image/Yuv") @@ -21,18 +7,15 @@ local Yuv = require("@rosetta/codecs/image/Yuv") local Video = {} export type Entry = { - id: string, -- our codec id - name: string, -- a human name + id: string, + name: string, 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) +-- decodeOne -> nil, nil: a packet with no picture to show (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 = {} @@ -213,8 +196,7 @@ local function vp8Decoder(_track: Types.Track, opts: any?): (Types.VideoCodecDec end), nil end --- Motion JPEG: every packet one JPEG (or two fields), yuv420p straight from the planes (full range) when the layout --- allows, else rgba8 +-- Motion JPEG: 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("@rosetta/codecs/image/Jpeg") local o: Jpeg.DecodeOptions = { yuv = true, maxPixels = opts and opts.maxPixels } @@ -240,20 +222,16 @@ local function mjpegEncode(img: Types.Image, opts: any?): (buffer?, Err.Err?) return Jpeg.encode(src, { quality = opts and opts.quality or 90 }) end --- MPEG-1 / MPEG-2 video (codecs/video/Mpeg2): pictures in decode order, reordered for display local function mpeg2Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) local Mpeg2 = require("@rosetta/codecs/video/Mpeg2") return Mpeg2.newVideoDecoder(track, opts) end --- H.264 / AVC (codecs/video/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("@rosetta/codecs/video/H264") return H264.newVideoDecoder(track, opts) end --- H.263 / Sorenson Spark (codecs/video/H263): one picture per packet, no reordering local function h263Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) local H263 = require("@rosetta/codecs/video/H263") local dec = H263.new({ flv = track.codec == "flv1", maxPixels = opts and opts.maxPixels }) @@ -264,22 +242,18 @@ local function h263Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDec end), nil end --- Theora (codecs/video/Theora): track.config = the three headers, Xiph-laced (Matroska's CodecPrivate; video/ogv --- builds the same); one picture per packet, empty packets repeat the previous one local function theoraDecoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) local Theora = require("@rosetta/codecs/video/Theora") return Theora.newVideoDecoder(track, opts) end --- FLI / FLC, Cinepak, Microsoft Video 1, QuickTime RLE / SMC, Smacker (codecs/video/Legacy) local function legacyDecoder(id: string): (track: Types.Track, opts: any?) -> (Types.VideoCodecDecoder?, Err.Err?) return function(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) return require("@rosetta/codecs/video/Legacy").newDecoder(id, track, opts) end end --- ------------------------------------------------------------------------------------------------ registry --- the codecs known by name (decoders where `new` is set). FourCCs compare case-sensitively first, then upper-cased. +-- 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 }, @@ -299,7 +273,6 @@ local BUILTIN: { Entry } = { { id = "flashsv", name = "Flash Screen Video", fourcc = { "FSV1" } }, { id = "flashsv2", name = "Flash Screen Video 2" }, { id = "png", name = "PNG", fourcc = { "png ", "MPNG" }, matroska = { "V_PNG" } }, - -- legacy inter-frame codecs (codecs/video/Legacy; rgba8 pictures, palettes from track.palette) { id = "cinepak", name = "Cinepak", fourcc = { "cvid" }, new = legacyDecoder("cinepak") }, { id = "msvideo1", name = "Microsoft Video 1", fourcc = { "CRAM", "MSVC", "WHAM" }, new = legacyDecoder("msvideo1") }, { id = "qtrle", name = "QuickTime Animation (RLE)", fourcc = { "rle " }, new = legacyDecoder("qtrle") }, @@ -312,7 +285,6 @@ 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") @@ -334,31 +306,25 @@ 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 @@ -371,7 +337,6 @@ function Video.decoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder 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) @@ -379,22 +344,16 @@ local function toRGBA(_self: any, f: any): Types.Image 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) + rgba: boolean?, + track: number?, 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 - -- shrink yuv420p frames so the longer side is at most this many pixels (aspect kept; bilinear, Yuv.scale), before - -- any rgba conversion. v.width / v.height stay the source size; frame.image has the output size. Default: none + openAudio: ((demuxer: Types.Demuxer, track: Types.Track) -> (Types.Decoder?, Err.Err?))?, + audio: boolean?, maxSide: number?, - -- passed to codecs that support a cooperative yield point (H.264: codecs/video/H264 Options.yield) yield: (() -> ())?, [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 @@ -435,7 +394,6 @@ function Video.open(demuxer: Types.Demuxer, opts: OpenOptions?): (Types.VideoDec 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 @@ -469,8 +427,7 @@ function Video.open(demuxer: Types.Demuxer, opts: OpenOptions?): (Types.VideoDec local t = (pts or 0) / scale - start if t + 1e-9 >= skipUntil then if index < 0 then - -- the first frame after a seek: its position in the stream (constant-rate: round(pts * fps); - -- without a frame rate, counted from the seek) + -- after a seek: constant-rate index = round(pts * fps), else counted from the seek index = if v.frameRate > 0 then math.max(0, math.floor(t * v.frameRate + 0.5)) else 0 end index += 1 @@ -531,9 +488,6 @@ function Video.open(demuxer: Types.Demuxer, opts: OpenOptions?): (Types.VideoDec 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")