diff --git a/compat/luajit.lua b/compat/luajit.lua
index 3b7a194..c5b1813 100644
--- a/compat/luajit.lua
+++ b/compat/luajit.lua
@@ -267,12 +267,19 @@ do
if o < 0 or o + 4 > b.n then oob() end
return cast(i32p, b.p + o)[0]
end
+ -- NaNs are checked through their bits before the float is loaded: a NaN with an arbitrary payload, handed back by
+ -- the FFI, can alias LuaJIT's NaN-tagged object values (read as a table / userdata). Return the canonical NaN.
+ local NAN = 0 / 0
function Buf.readf32(b, o)
if o < 0 or o + 4 > b.n then oob() end
+ local bits = cast(u32p, b.p + o)[0]
+ if bits % 0x80000000 > 0x7f800000 then return NAN end
return cast(f32p, b.p + o)[0]
end
function Buf.readf64(b, o)
if o < 0 or o + 8 > b.n then oob() end
+ local hi = cast(u32p, b.p + o + 4)[0] % 0x80000000 -- little-endian: sign / exponent / top mantissa bits
+ if hi >= 0x7ff00000 and (hi > 0x7ff00000 or cast(u32p, b.p + o)[0] ~= 0) then return NAN end
return cast(f64p, b.p + o)[0]
end
-- integer writes wrap like Luau (300 -> 44, -1 -> 255); the double -> int conversion goes through int32 for
@@ -403,7 +410,7 @@ function M.__iter(t, s, c)
local mt = getmetatable(t)
if rawtype(mt) == "table" and mt.__iter then return mt.__iter(t) end
local n = #t
- if n > 0 and next(t, n) == nil then return ipairs(t) end
+ if n > 0 and t[0] == nil and next(t, n) == nil then return ipairs(t) end -- LuaJIT keeps t[0] in the array part
return next, t, nil
end
diff --git a/docs/FORMATS.md b/docs/FORMATS.md
index 278fe8e..aaab390 100644
--- a/docs/FORMATS.md
+++ b/docs/FORMATS.md
@@ -6,19 +6,88 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| Category | Format | Extensions | Read | Write | Capabilities | Test |
|---|---|---|---|---|---|---|
| image | bmp | .bmp .dib | yes | yes | alpha: true, depths: 1, 2, 4, 8, 16, 24, 32, rle: true | `tests/image/bmp.luau` |
+| image | gif | .gif | yes | yes | animation: true, alpha: true, palette: true, depths: 1, 2, 4, 8 | `tests/image/gif.luau` |
+| image | hdr | .hdr .pic .rgbe | yes | yes | alpha: false, float: true, depths: 32 | `tests/image/hdr.luau` |
+| image | ico | .ico .cur | yes | yes | alpha: true, frames: true, depths: 1, 4, 8, 16, 24, 32 | `tests/image/ico.luau` |
+| image | jpeg | .jpg .jpeg .jpe .jfif | yes | yes | lossy: true, alpha: false, depths: 8, 12, progressive: true, arithmetic: true | `tests/image/jpeg.luau` |
| image | png | .png .apng | yes | yes | animation: true, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` |
+| image | pnm | .pnm .pbm .pgm .ppm .pam .pfm | yes | yes | alpha: true, depths: 1, 8, 16, 32, float: true | `tests/image/pnm.luau` |
+| image | qoi | .qoi | yes | yes | alpha: true, depths: 8 | `tests/image/qoi.luau` |
+| image | tga | .tga .icb .vda .vst .tpic | yes | yes | alpha: true, palette: true, depths: 8, 15, 16, 24, 32 | `tests/image/tga.luau` |
+| image | tiff | .tif .tiff | yes | yes | alpha: true, pages: true, depths: 1, 2, 4, 8, 16, 32, float: true | `tests/image/tiff.luau` |
+| image | webp | .webp | yes | yes | animation: true, alpha: true, lossy: true, lossless: true, depths: 8 | `tests/image/webp.luau` |
+| audio | aac | .aac .adts | yes | - | codecs: "aac", streaming: true | `tests/audio/aac.luau` |
| audio | aiff | .aiff .aif .aifc .afc | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, lossy: false | `tests/audio/aiff.luau` |
| audio | au | .au .snd | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, lossy: false | `tests/audio/au.luau` |
+| audio | caf | .caf .caff | yes | yes | codecs: "pcm", "alac", "aac", "ulaw", "alaw", encodeCodecs: "pcm", "alac", tags: true, streaming: true | `tests/audio/caf.luau` |
| audio | flac | .flac .oga | yes | yes | streaming: true, depths: 4, 8, 12, 16, 20, 24, 32, ogg: true, seek: true | `tests/audio/flac.luau` |
+| audio | m4a | .m4a .m4b .m4r | yes | yes | codecs: "aac", "alac", encodeCodecs: "alac", tags: true, streaming: true | `tests/audio/m4a.luau` |
| audio | mp3 | .mp3 .mp2 .mp1 .mpga | yes | yes | streaming: true, seek: true, layers: 1, 2, 3, channels: 2 | `tests/audio/mp3.luau` |
-| audio | opus | .opus | yes | - | streaming: true, seek: true, lossy: true, channels: 255, rates: 48000 | `tests/audio/opus.luau` |
+| audio | opus | .opus | yes | yes | streaming: true, seek: true, lossy: true, channels: 255, rates: 48000, encodeModes: "celt" | `tests/audio/opus.luau` |
| audio | voc | .voc | yes | yes | streaming: true, depths: 8, 16, lossy: false | `tests/audio/voc.luau` |
| audio | vorbis | .ogg .oga | yes | yes | streaming: true, seek: true, lossy: true, channels: 255 | `tests/audio/vorbis.luau` |
| audio | wav | .wav .wave .rf64 .bw64 | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, rf64: true | `tests/audio/wav.luau` |
+| model | gltf | .gltf .glb | yes | yes | binary: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true | `tests/model/gltf.luau` |
+| model | obj | .obj | yes | yes | materials: true, polygons: true, vertexColors: true | `tests/model/obj.luau` |
+| model | off | .off | yes | yes | polygons: true, points: true, colors: true, binary: false | `tests/model/off.luau` |
+| model | ply | .ply | yes | yes | ascii: true, binary: true, polygons: true, points: true, colors: true | `tests/model/ply.luau` |
+| model | stl | .stl | yes | yes | ascii: true, binary: true, colors: true, indexed: false | `tests/model/stl.luau` |
+| model | vox | .vox | yes | yes | voxels: true, sceneGraph: true, materials: true | `tests/model/vox.luau` |
+| font | bmfont | .fnt | yes | yes | bitmap: true, variants: "text", "xml", "binary" | `tests/font/bmfont.luau` |
+| font | ttf | .ttf .otf .ttc .otc | yes | - | outlines: "truetype", "cff", collection: true, kerning: true | `tests/font/ttf.luau` |
+| font | woff | .woff | yes | - | outlines: "truetype", "cff" | `tests/font/woff.luau` |
+| font | woff2 | .woff2 | yes | - | outlines: "truetype", "cff", transforms: "glyf", "loca", "hmtx" | `tests/font/woff2.luau` |
+| archive | 7z | .7z | yes | - | methods: "copy", "lzma", "lzma2", "deflate", "bcj", "delta", encrypted: false | `tests/archive/7z.luau` |
+| archive | br | .br | yes | - | stream: true | `tests/archive/br.luau` |
+| archive | bz2 | .bz2 .tbz2 .tbz | yes | - | stream: true | `tests/archive/bz2.luau` |
+| archive | gzip | .gz .tgz .gzip | yes | yes | stream: true | `tests/archive/gzip.luau` |
+| archive | tar | .tar | yes | yes | variants: "ustar", "pax", "gnu" | `tests/archive/tar.luau` |
+| archive | xz | .xz .txz .lzma | yes | - | stream: true, filters: "lzma2", "lzma", "delta", "x86", "powerpc", "arm", "armthumb", "sparc", "arm64" | `tests/archive/xz.luau` |
| archive | zip | .zip .wsz | yes | yes | methods: "store", "deflate", zip64: true | `tests/archive/zip.luau` |
+| archive | zst | .zst .tzst | yes | - | stream: true | `tests/archive/zst.luau` |
+| data | cbor | .cbor | yes | yes | binary: true, ordered: true, tags: true | `tests/data/cbor.luau` |
+| data | csv | .csv .tsv | yes | yes | header: true | `tests/data/csv.luau` |
+| data | ini | .ini .cfg .conf .inf .desktop | yes | yes | ordered: true | `tests/data/ini.luau` |
+| data | json | .json .jsonl .ndjson .geojson | yes | yes | ordered: true, streaming: true | `tests/data/json.luau` |
+| data | msgpack | .msgpack .mpk | yes | yes | binary: true, ordered: true | `tests/data/msgpack.luau` |
+| data | plist | .plist | yes | yes | binary: "read", ordered: true | `tests/data/plist.luau` |
+| data | toml | .toml | yes | yes | ordered: true, dates: true | `tests/data/toml.luau` |
+| data | xml | .xml .xsd .xsl .xslt .rss .atom .xhtml | yes | yes | namespaces: true, streaming: true | `tests/data/xml.luau` |
+| data | yaml | .yaml .yml | yes | yes | ordered: true, multiDocument: true, anchors: true | `tests/data/yaml.luau` |
+| vector | svg | .svg | yes | yes | rasterize: true, text: false | `tests/vector/svg.luau` |
+| vector | tiled | .tmx .tmj .tsx .tsj | yes | yes | tilesets: true, infinite: true | `tests/vector/tiled.luau` |
+| layered | aseprite | .aseprite .ase | yes | yes | layers: true, groups: true, animation: true, depths: 8, 16, 32 | `tests/layered/aseprite.luau` |
+| layered | psd | .psd .psb | yes | yes | layers: true, groups: true, depths: 1, 8, 16, 32 | `tests/layered/psd.luau` |
+| subtitle | ass | .ass .ssa | yes | yes | styles: true | `tests/subtitle/ass.luau` |
+| subtitle | srt | .srt | yes | yes | styles: false | `tests/subtitle/srt.luau` |
+| subtitle | vtt | .vtt .webvtt | yes | yes | styles: true | `tests/subtitle/vtt.luau` |
+| playlist | m3u | .m3u .m3u8 | yes | yes | hls: true | `tests/playlist/m3u.luau` |
+| playlist | pls | .pls | yes | yes | | `tests/playlist/pls.luau` |
+| playlist | xspf | .xspf | yes | yes | | `tests/playlist/xspf.luau` |
Codecs (layer 1, shared by formats; not loadable on their own):
+- codecs/Aac: AAC-LC decoder (ISO/IEC 14496-3 subpart 4, ISO/IEC 13818-7): the AudioSpecificConfig (with a program
+- codecs/Alac: Apple Lossless (ALAC) decoder and encoder, the codec inside m4a / mov / caf. A codec (layer 1).
+- codecs/Base64: RFC 4648 base64 (standard alphabet, and base64url with opts.url) encode / decode, for data: URIs
+- codecs/Blend: layer compositing on rgba8 buffers (straight alpha): source-over with the separable and non-separable
+- codecs/Brotli: Brotli (RFC 7932) decompression. A codec (layer 3): archive/br and font/woff2 build on it. Written
+- codecs/Bzip2: bzip2 decompressor (BWT + MTF + Huffman, the .bz2 stream format of bzip2 0.9.5 / 1.0.x). A codec
+- codecs/Cff: Compact Font Format (Adobe TN #5176) and Type 2 charstrings (TN #5177): the outlines of OpenType fonts
+- codecs/Dct: the 8x8 DCTs JPEG, Motion-JPEG and MPEG-1 share (native; never throws).
- codecs/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers.
+- codecs/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code.
+- codecs/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. A codec (layer 3):
+- codecs/Lzw: LZW decoder and encoder in the two variants file formats use. A codec (layer 1): image/gif and
- codecs/Mdct: the MDCT / IMDCT of any window length N divisible by 4 (N / 2 coefficients), through an N / 4-point
+- codecs/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). Walks
- codecs/Pcm: PCM plumbing shared by audio formats: raw sample formats, streaming Decoders, encoder input sources.
+- codecs/Quantize: palette quantization of rgba8 pixels. A codec (layer 1): image/gif (and later any palette
+- codecs/Raster: an antialiased scanline rasterizer for paths of lines, quadratic and cubic Béziers, under an affine
+- codecs/Text: text decoding helpers for the text formats: a UTF-8 BOM is stripped, text that is not valid UTF-8 is
+- codecs/TrueType: the sfnt font container (TrueType .ttf, OpenType .otf with CFF outlines, collections .ttc) parsed
+- codecs/Url: RFC 3986 reference resolution (section 5.2), the classification of a playlist / manifest location (URL,
+- codecs/Vp8: the VP8 video codec (RFC 6386), decode only. A codec (layer 1): image/webp uses it for lossy frames, the
+- codecs/Vp8L: WebP lossless (VP8L, "WebP Lossless Bitstream Specification", RFC 9649 section 3). A codec (layer 1):
+- codecs/Xml: XML 1.0 parse (DOM and pull events) and serialize, the engine data/xml, SVG, DAE, 3MF, TMX, plist, ...
+- codecs/Zstd: Zstandard decompression (RFC 8878). A codec (layer 3): archive/zst and anything else carrying zstd
diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md
index d380919..7ac7bf9 100644
--- a/licenses/NOTICE.md
+++ b/licenses/NOTICE.md
@@ -4,6 +4,9 @@
|---|---|---|
| `src/Formats/codecs/Deflate/` (Inflate, init), `src/Formats/core/Crc32.luau`, `src/Formats/core/Adler32.luau`, `src/Formats/core/Huffman.luau` (table builder) | deflate-luau 1.0.0 (same author), written from RFC 1950-1952 | no licence chosen yet; no third-party code: [deflate-luau-NOTICE.txt](deflate-luau-NOTICE.txt) |
| `src/Formats/image/png/` (init, Decode) | png-luau 1.0.0 (same author), written from the PNG specification | no licence chosen yet; no third-party code |
+| `src/Formats/codecs/Brotli/Static.luau` (static dictionary, context lookup table, word transforms; generated by `tools/brotli_static.py`), `src/Formats/codecs/Brotli/Decode.luau` (written from RFC 7932, structure after the reference decoder) | google/brotli | MIT: [brotli-LICENSE.txt](brotli-LICENSE.txt) |
+| `src/Formats/codecs/Lzma/`, `src/Formats/archive/xz/`, `src/Formats/archive/7z/` | written from the LZMA specification / LzmaSpec.cpp and 7zFormat.txt (LZMA SDK, Igor Pavlov), the xz file format specification and xz-embedded's BCJ filters (Lasse Collin) | all public domain: [lzma-xz-PUBLIC-DOMAIN.txt](lzma-xz-PUBLIC-DOMAIN.txt) |
+| `src/Formats/codecs/TrueType/`, `src/Formats/codecs/Cff/` | stb_truetype 1.26 (Sean Barrett), via imgui-luau's `imstb_truetype.lua`; fixed and extended | MIT or public domain: [stb_truetype-LICENSE.txt](stb_truetype-LICENSE.txt) |
| `src/Formats/containers/Ogg/` (init, Page) | ogg-luau be9f604 (same author), written from RFC 3533 | no licence chosen yet; no third-party code |
| `src/Formats/audio/wav/`, `src/Formats/containers/Riff/` (the chunk walker) | wav-luau fd9a909 (same author), written from the RIFF / WAVE / RF64 (EBU Tech 3306) specifications | no licence chosen yet; no third-party code |
| `src/Formats/audio/mp3/` | mp3-luau c755bbf (same author), a port of minimp3 by lieff (https://github.com/lieff/minimp3) | minimp3: CC0 1.0, [minimp3-CC0.txt](minimp3-CC0.txt) |
@@ -15,7 +18,17 @@
| `tests/fixtures/bmpsuite/` | BMP Suite 2.8 by Jason Summers (generated images) | public domain: [bmpsuite-NOTICE.txt](bmpsuite-NOTICE.txt) |
| `src/Formats/containers/Zip/` (the reader), `src/Formats/archive/zip/` | zip-luau 121d4b0 (same author), written from PKWARE's APPNOTE.TXT 6.3 | no licence chosen yet; no third-party code |
| `src/Formats/audio/mp3/EncTables.luau` (ws-audio encoders) | PDMP3 by Krister Lagerström et al. (https://github.com/technosaurus/PDMP3): the ISO/IEC 11172-3 synthesis window and layer III Huffman trees | public domain (unlicense): [PDMP3-UNLICENSE.txt](PDMP3-UNLICENSE.txt) |
+| `src/Formats/playlist/` (m3u, pls; xspf is new), `src/Formats/codecs/Url/`, `src/Formats/codecs/Text/` | playlist-luau 3fc7fd3 (same author), written from RFC 3986 / RFC 8216 | no licence chosen yet; no third-party code |
+| `src/Formats/image/jpeg/` (Decode, Scan, Color), `src/Formats/codecs/Dct/` (inverse DCTs) | jpeg-luau 1.0 (same author); the IDCTs, upsampling, colour conversion and IDCT-size choice are Luau translations of libjpeg / libjpeg-turbo (jidctint.c, jidctred.c, jdsample.c, jdcolor.c, jdmaster.c) | IJG licence + libjpeg-turbo BSD: [libjpeg-turbo-LICENSE.md](libjpeg-turbo-LICENSE.md), [libjpeg-README.ijg](libjpeg-README.ijg). This software is based in part on the work of the Independent JPEG Group. |
+| `src/Formats/image/jpeg/Arith.luau`, `src/Formats/image/jpeg/Encode.luau`, `src/Formats/codecs/Dct/` (forward DCT) | new; Luau translations of libjpeg-turbo 3.2 jdarith.c / jaricom.c (Guido Vollbeding), jccolor.c, jcsample.c, jccoefct.c, jfdctint.c, jcdctmgr.c, jchuff.c, jcphuff.c, jcparam.c | as above |
+| `src/Formats/codecs/Aac/Tables.luau` | the Huffman codebooks, scalefactor band offsets and TNS limits of ISO/IEC 14496-3 (Annex 4.A), transcribed mechanically from FFmpeg's `libavcodec/aactab.c` (tables of the standard only; no FFmpeg code) | FFmpeg is LGPL-2.1-or-later; the tables are the standard's data |
+| `src/Formats/codecs/Aac/`, `codecs/Alac/`, `codecs/Mdct/`, `containers/IsoBmff/`, `audio/m4a`, `audio/aac`, `audio/caf` | written for this library from ISO/IEC 14496-3 / 14496-12 / 23008-12, Apple's ALAC and CAF specifications | no third-party code |
+| `src/Formats/audio/opus/CeltEncoder.luau`, `src/Formats/audio/opus/RangeEncoder.luau` | the encoder side of libopus 1.6 (celt_encoder.c, entenc.c, quant_bands.c, laplace.c, rate.c, bands.c, vq.c, cwrs.c), ported to mirror the absorbed decoder; analysis simplified (ws-m4a) | libopus BSD 3-clause: [libopus-BSD.txt](libopus-BSD.txt) |
| `tests/fixtures/pngsuite/` | PngSuite by Willem van Schaik | [PngSuite-LICENSE.txt](PngSuite-LICENSE.txt) |
+| `tests/fixtures/vox/{chr_knight,chr_sword,deer,maze}.vox`, `tests/fixtures/vox/MagicaVoxel-file-format-vox*.txt` (the format spec) | ephtracy/voxel-model (MagicaVoxel sample models) | MIT: [voxel-model-LICENSE.txt](voxel-model-LICENSE.txt) |
+| `tests/fixtures/vox/ogt_*.vox` | jpaver/opengametools `demo/vox/` (files saved by MagicaVoxel 0.99.x) | MIT: [opengametools-LICENSE.txt](opengametools-LICENSE.txt) |
+| `tests/fixtures/gltf/` | KhronosGroup/glTF-Sample-Assets `Models/` (one LICENSE.md per model folder; `UnicodeTest` is `Unicode❤♻Test` renamed) | CC-BY-4.0 or CC0-1.0 per model, see each folder's LICENSE.md |
+| `src/Formats/codecs/Vp8/` (Decode, Yuv, Tables), `src/Formats/codecs/Vp8L/Decode.luau`, `src/Formats/image/webp/` (Alpha unfilters, Anim.coalesce) | ports of libwebp 1.6.0 (Google): src/dec, src/dsp, src/utils, src/demux/anim_decode.c | BSD-3-Clause + patent grant: [libwebp-LICENSE.txt](libwebp-LICENSE.txt) |
Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this
folder (see docs/STYLE.md, "Absorbing an existing repo").
diff --git a/licenses/brotli-LICENSE.txt b/licenses/brotli-LICENSE.txt
new file mode 100644
index 0000000..33b7cdd
--- /dev/null
+++ b/licenses/brotli-LICENSE.txt
@@ -0,0 +1,19 @@
+Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/licenses/libjpeg-README.ijg b/licenses/libjpeg-README.ijg
new file mode 100644
index 0000000..dbf8070
--- /dev/null
+++ b/licenses/libjpeg-README.ijg
@@ -0,0 +1,260 @@
+libjpeg-turbo note: This file has been modified by The libjpeg-turbo Project
+to include only information relevant to libjpeg-turbo, to wordsmith certain
+sections, and to remove impolitic language that existed in the libjpeg v8
+README. It is included only for reference. Please see README.md for
+information specific to libjpeg-turbo.
+
+
+The Independent JPEG Group's JPEG software
+==========================================
+
+This distribution contains a release of the Independent JPEG Group's free JPEG
+software. You are welcome to redistribute this software and to use it for any
+purpose, subject to the conditions under LEGAL ISSUES, below.
+
+This software is the work of Tom Lane, Guido Vollbeding, Philip Gladstone,
+Bill Allombert, Jim Boucher, Lee Crocker, Bob Friesenhahn, Ben Jackson,
+Julian Minguillon, Luis Ortiz, George Phillips, Davide Rossi, Ge' Weijers,
+and other members of the Independent JPEG Group.
+
+IJG is not affiliated with the ISO/IEC JTC1/SC29/WG1 standards committee
+(also known as JPEG, together with ITU-T SG16).
+
+
+DOCUMENTATION ROADMAP
+=====================
+
+This file contains the following sections:
+
+OVERVIEW General description of JPEG and the IJG software.
+LEGAL ISSUES Copyright, lack of warranty, terms of distribution.
+REFERENCES Where to learn more about JPEG.
+ARCHIVE LOCATIONS Where to find newer versions of this software.
+FILE FORMAT WARS Software *not* to get.
+TO DO Plans for future IJG releases.
+
+Other documentation files in the distribution are:
+
+User documentation:
+ doc/usage.txt Usage instructions for cjpeg, djpeg, jpegtran,
+ rdjpgcom, and wrjpgcom.
+ doc/*.1 Unix-style man pages for programs (same info as
+ usage.txt).
+ doc/wizard.txt Advanced usage instructions for JPEG wizards only.
+ doc/change.log Version-to-version change highlights.
+Programmer and internal documentation:
+ doc/libjpeg.txt How to use the JPEG library in your own programs.
+ src/example.c Sample code for calling the JPEG library.
+ doc/structure.txt Overview of the JPEG library's internal structure.
+ doc/coderules.txt Coding style rules --- please read if you contribute
+ code.
+
+Please read at least usage.txt. Some information can also be found in the JPEG
+FAQ (Frequently Asked Questions) article. See ARCHIVE LOCATIONS below to find
+out where to obtain the FAQ article.
+
+If you want to understand how the JPEG code works, we suggest reading one or
+more of the REFERENCES, then looking at the documentation files (in roughly
+the order listed) before diving into the code.
+
+
+OVERVIEW
+========
+
+This package contains C software to implement JPEG image encoding, decoding,
+and transcoding. JPEG (pronounced "jay-peg") is a standardized compression
+method for full-color and grayscale images. JPEG's strong suit is compressing
+photographic images or other types of images that have smooth color and
+brightness transitions between neighboring pixels. Images with sharp lines or
+other abrupt features may not compress well with JPEG, and a higher JPEG
+quality may have to be used to avoid visible compression artifacts with such
+images.
+
+JPEG is normally lossy, meaning that the output pixels are not necessarily
+identical to the input pixels. However, on photographic content and other
+"smooth" images, very good compression ratios can be obtained with no visible
+compression artifacts, and extremely high compression ratios are possible if
+you are willing to sacrifice image quality (by reducing the "quality" setting
+in the compressor.)
+
+This software implements JPEG baseline, extended-sequential, progressive, and
+lossless compression processes. Provision is made for supporting all variants
+of these processes, although some uncommon parameter settings aren't
+implemented yet. We have made no provision for supporting the hierarchical
+processes defined in the standard.
+
+We provide a set of library routines for reading and writing JPEG image files,
+plus two sample applications "cjpeg" and "djpeg", which use the library to
+perform conversion between JPEG and some other popular image file formats.
+The library is intended to be reused in other applications.
+
+In order to support file conversion and viewing software, we have included
+considerable functionality beyond the bare JPEG coding/decoding capability;
+for example, the color quantization modules are not strictly part of JPEG
+decoding, but they are essential for output to colormapped file formats. These
+extra functions can be compiled out of the library if not required for a
+particular application.
+
+We have also included "jpegtran", a utility for lossless transcoding between
+different JPEG processes, and "rdjpgcom" and "wrjpgcom", two simple
+applications for inserting and extracting textual comments in JFIF files.
+
+The emphasis in designing this software has been on achieving portability and
+flexibility, while also making it fast enough to be useful. In particular,
+the software is not intended to be read as a tutorial on JPEG. (See the
+REFERENCES section for introductory material.) Rather, it is intended to
+be reliable, portable, industrial-strength code. We do not claim to have
+achieved that goal in every aspect of the software, but we strive for it.
+
+We welcome the use of this software as a component of commercial products.
+No royalty is required, but we do ask for an acknowledgement in product
+documentation, as described under LEGAL ISSUES.
+
+
+LEGAL ISSUES
+============
+
+In plain English:
+
+1. We don't promise that this software works. (But if you find any bugs,
+ please let us know!)
+2. You can use this software for whatever you want. You don't have to pay us.
+3. You may not pretend that you wrote this software. If you use it in a
+ program, you must acknowledge somewhere in your documentation that
+ you've used the IJG code.
+
+In legalese:
+
+The authors make NO WARRANTY or representation, either express or implied,
+with respect to this software, its quality, accuracy, merchantability, or
+fitness for a particular purpose. This software is provided "AS IS", and you,
+its user, assume the entire risk as to its quality and accuracy.
+
+This software is copyright (C) 1991-2020, Thomas G. Lane, Guido Vollbeding.
+All Rights Reserved except as specified below.
+
+Permission is hereby granted to use, copy, modify, and distribute this
+software (or portions thereof) for any purpose, without fee, subject to these
+conditions:
+(1) If any part of the source code for this software is distributed, then this
+README file must be included, with this copyright and no-warranty notice
+unaltered; and any additions, deletions, or changes to the original files
+must be clearly indicated in accompanying documentation.
+(2) If only executable code is distributed, then the accompanying
+documentation must state that "this software is based in part on the work of
+the Independent JPEG Group".
+(3) Permission for use of this software is granted only if the user accepts
+full responsibility for any undesirable consequences; the authors accept
+NO LIABILITY for damages of any kind.
+
+These conditions apply to any software derived from or based on the IJG code,
+not just to the unmodified library. If you use our work, you ought to
+acknowledge us.
+
+Permission is NOT granted for the use of any IJG author's name or company name
+in advertising or publicity relating to this software or products derived from
+it. This software may be referred to only as "the Independent JPEG Group's
+software".
+
+We specifically permit and encourage the use of this software as the basis of
+commercial products, provided that all warranty or liability claims are
+assumed by the product vendor.
+
+
+REFERENCES
+==========
+
+We recommend reading one or more of these references before trying to
+understand the innards of the JPEG software.
+
+The best short technical introduction to the JPEG compression algorithm is
+ Wallace, Gregory K. "The JPEG Still Picture Compression Standard",
+ Communications of the ACM, April 1991 (vol. 34 no. 4), pp. 30-44.
+(Adjacent articles in that issue discuss MPEG motion picture compression,
+applications of JPEG, and related topics.) If you don't have the CACM issue
+handy, a PDF file containing a revised version of Wallace's article is
+available at http://www.ijg.org/files/Wallace.JPEG.pdf. The file (actually
+a preprint for an article that appeared in IEEE Trans. Consumer Electronics)
+omits the sample images that appeared in CACM, but it includes corrections
+and some added material. Note: the Wallace article is copyright ACM and IEEE,
+and it may not be used for commercial purposes.
+
+A somewhat less technical, more leisurely introduction to JPEG can be found in
+"The Data Compression Book" by Mark Nelson and Jean-loup Gailly, published by
+M&T Books (New York), 2nd ed. 1996, ISBN 1-55851-434-1. This book provides
+good explanations and example C code for a multitude of compression methods
+including JPEG. It is an excellent source if you are comfortable reading C
+code but don't know much about data compression in general. The book's JPEG
+sample code is far from industrial-strength, but when you are ready to look
+at a full implementation, you've got one here...
+
+The best currently available description of JPEG is the textbook "JPEG Still
+Image Data Compression Standard" by William B. Pennebaker and Joan L.
+Mitchell, published by Van Nostrand Reinhold, 1993, ISBN 0-442-01272-1.
+Price US$59.95, 638 pp. The book includes the complete text of the ISO JPEG
+standards (DIS 10918-1 and draft DIS 10918-2).
+
+The original JPEG standard is divided into two parts, Part 1 being the actual
+specification, while Part 2 covers compliance testing methods. Part 1 is
+titled "Digital Compression and Coding of Continuous-tone Still Images,
+Part 1: Requirements and guidelines" and has document numbers ISO/IEC IS
+10918-1, ITU-T T.81. Part 2 is titled "Digital Compression and Coding of
+Continuous-tone Still Images, Part 2: Compliance testing" and has document
+numbers ISO/IEC IS 10918-2, ITU-T T.83.
+
+The JPEG standard does not specify all details of an interchangeable file
+format. For the omitted details, we follow the "JFIF" conventions, revision
+1.02. JFIF version 1 has been adopted as ISO/IEC 10918-5 (05/2013) and
+Recommendation ITU-T T.871 (05/2011): Information technology - Digital
+compression and coding of continuous-tone still images: JPEG File Interchange
+Format (JFIF). It is available as a free download in PDF file format from
+https://www.iso.org/standard/54989.html and http://www.itu.int/rec/T-REC-T.871.
+A PDF file of the older JFIF 1.02 specification is available at
+http://www.w3.org/Graphics/JPEG/jfif3.pdf.
+
+The TIFF 6.0 file format specification can be obtained from
+http://mirrors.ctan.org/graphics/tiff/TIFF6.ps.gz. The JPEG incorporation
+scheme found in the TIFF 6.0 spec of 3-June-92 has a number of serious
+problems. IJG does not recommend use of the TIFF 6.0 design (TIFF Compression
+tag 6). Instead, we recommend the JPEG design proposed by TIFF Technical Note
+#2 (Compression tag 7). Copies of this Note can be obtained from
+http://www.ijg.org/files/. It is expected that the next revision
+of the TIFF spec will replace the 6.0 JPEG design with the Note's design.
+Although IJG's own code does not support TIFF/JPEG, the free libtiff library
+uses our library to implement TIFF/JPEG per the Note.
+
+
+ARCHIVE LOCATIONS
+=================
+
+The "official" archive site for this software is www.ijg.org.
+The most recent released version can always be found there in
+directory "files".
+
+The JPEG FAQ (Frequently Asked Questions) article is a source of some
+general information about JPEG. It is available at
+http://www.faqs.org/faqs/jpeg-faq.
+
+
+FILE FORMAT COMPATIBILITY
+=========================
+
+This software implements ITU T.81 | ISO/IEC 10918 with some extensions from
+ITU T.871 | ISO/IEC 10918-5 (JPEG File Interchange Format-- see REFERENCES).
+Informally, the term "JPEG image" or "JPEG file" most often refers to JFIF or
+a subset thereof, but there are other formats containing the name "JPEG" that
+are incompatible with the original JPEG standard or with JFIF (for instance,
+JPEG 2000 and JPEG XR). This software therefore does not support these
+formats. Indeed, one of the original reasons for developing this free software
+was to help force convergence on a common, interoperable format standard for
+JPEG files.
+
+JFIF is a minimal or "low end" representation. TIFF/JPEG (TIFF revision 6.0 as
+modified by TIFF Technical Note #2) can be used for "high end" applications
+that need to record a lot of additional data about an image.
+
+
+TO DO
+=====
+
+Please send bug reports, offers of help, etc. to jpeg-info@jpegclub.org.
diff --git a/licenses/libjpeg-turbo-LICENSE.md b/licenses/libjpeg-turbo-LICENSE.md
new file mode 100644
index 0000000..37a489b
--- /dev/null
+++ b/licenses/libjpeg-turbo-LICENSE.md
@@ -0,0 +1,147 @@
+libjpeg-turbo Licenses
+======================
+
+libjpeg-turbo is covered by two compatible BSD-style open source licenses:
+
+- The IJG (Independent JPEG Group) License, which is listed in
+ [README.ijg](README.ijg)
+
+ This license applies to the libjpeg API library and associated programs,
+ including any code inherited from libjpeg and any modifications to that
+ code.
+
+- The Modified (3-clause) BSD License, which is listed below
+
+ This license applies to the TurboJPEG API library and associated programs,
+ [libspng](https://libspng.org) (which is used by cjpeg and djpeg), and the
+ build/test system.
+
+ * The TurboJPEG API library wraps the libjpeg API library, so in the context
+ of the overall TurboJPEG API library, both the terms of the IJG License and
+ the terms of the Modified (3-clause) BSD License apply.
+ * cjpeg and djpeg use libspng, so in the context of those programs, both the
+ terms of the IJG License and the terms of the Modified (3-clause) BSD
+ License apply.
+
+
+Component Licenses
+==================
+
+Some of libjpeg-turbo's modules and internal dependencies are covered by less
+restrictive licenses, but in the context of libjpeg-turbo as a whole, the terms
+of the less restrictive licenses are subsumed by either the IJG License or the
+Modified BSD License. (In other words, the terms of the less restrictive
+licenses are satisfied if the terms of the IJG and Modified BSD Licenses are
+satisfied.)
+
+- The libjpeg-turbo SIMD source code and zlib are covered by the
+ [zlib License](https://spdx.org/licenses/Zlib.html), which is subsumed by the
+ IJG License in the context of the cjpeg and djpeg programs and the libjpeg
+ API library.
+
+- Some of the libspng source code is covered by the
+ [PNG Reference Library License v2](https://spdx.org/licenses/libpng-2.0.html),
+ which is subsumed by the IJG License in the context of the cjpeg and djpeg
+ programs and the TurboJPEG API library.
+
+- Most of the libspng source code is covered by the
+ [Simplified (2-clause) BSD License](https://spdx.org/licenses/BSD-2-Clause.html),
+ which is subsumed by the Modified BSD License in the context of the cjpeg and
+ djpeg programs and the TurboJPEG API library.
+
+
+Complying with the libjpeg-turbo Licenses
+=========================================
+
+This section provides a roll-up of the libjpeg-turbo licensing terms, to the
+best of our understanding. This is not a license in and of itself. It is
+intended solely for clarification.
+
+1. If you are distributing a modified version of the libjpeg-turbo source,
+ then:
+
+ 1. You cannot alter or remove any existing copyright or license notices
+ from the source.
+
+ **Origin**
+ - Clause 1 of the IJG License
+ - Clause 1 of the Modified BSD License
+
+ 2. You must add your own copyright notice to the header of each source
+ file you modified, so others can tell that you modified that file. (If
+ there is not an existing copyright header in that file, then you can
+ simply add a notice stating that you modified the file.)
+
+ **Origin**
+ - Clause 1 of the IJG License
+
+ 3. You must include the IJG README file, and you must not alter any of the
+ copyright or license text in that file.
+
+ **Origin**
+ - Clause 1 of the IJG License
+
+2. If you are distributing only libjpeg-turbo binaries without the source, or
+ if you are distributing an application that statically links with
+ libjpeg-turbo, then:
+
+ 1. Your product documentation must include a message stating:
+
+ This software is based in part on the work of the Independent JPEG
+ Group.
+
+ **Origin**
+ - Clause 2 of the IJG license
+
+ 2. If your binary distribution includes or uses the TurboJPEG API or
+ associated programs, cjpeg, or djpeg, then your product documentation
+ must include the text of the Modified BSD License (see below.)
+
+ **Origin**
+ - Clause 2 of the Modified BSD License
+
+3. You cannot use the name of the IJG or The libjpeg-turbo Project or the
+ contributors thereof in advertising, publicity, etc.
+
+ **Origin**
+ - IJG License
+ - Clause 3 of the Modified BSD License
+
+4. The authors and distributors do not warrant libjpeg-turbo to be free of
+ defects, nor do we accept any liability for undesirable consequences
+ resulting from your use of the software.
+
+ **Origin**
+ - IJG License
+ - Modified BSD License
+
+
+The Modified (3-clause) BSD License
+===================================
+
+Copyright (C) 2009-2026 D. R. Commander
+Copyright (C) 2018-2023 Randy
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+- Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+- Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+- Neither the name of the libjpeg-turbo Project nor the names of its
+ contributors may be used to endorse or promote products derived from this
+ software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS",
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGE.
diff --git a/licenses/libwebp-LICENSE.txt b/licenses/libwebp-LICENSE.txt
new file mode 100644
index 0000000..b6de3f0
--- /dev/null
+++ b/licenses/libwebp-LICENSE.txt
@@ -0,0 +1,55 @@
+Copyright (c) 2010, Google Inc. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+ * Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in
+ the documentation and/or other materials provided with the
+ distribution.
+
+ * Neither the name of Google nor the names of its contributors may
+ be used to endorse or promote products derived from this software
+ without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+
+Additional IP Rights Grant (Patents):
+Additional IP Rights Grant (Patents)
+------------------------------------
+
+"These implementations" means the copyrightable works that implement the WebM
+codecs distributed by Google as part of the WebM Project.
+
+Google hereby grants to you a perpetual, worldwide, non-exclusive, no-charge,
+royalty-free, irrevocable (except as stated in this section) patent license to
+make, have made, use, offer to sell, sell, import, transfer, and otherwise
+run, modify and propagate the contents of these implementations of WebM, where
+such license applies only to those patent claims, both currently owned by
+Google and acquired in the future, licensable by Google that are necessarily
+infringed by these implementations of WebM. This grant does not include claims
+that would be infringed only as a consequence of further modification of these
+implementations. If you or your agent or exclusive licensee institute or order
+or agree to the institution of patent litigation or any other patent
+enforcement activity against any entity (including a cross-claim or
+counterclaim in a lawsuit) alleging that any of these implementations of WebM
+or any code incorporated within any of these implementations of WebM
+constitute direct or contributory patent infringement, or inducement of
+patent infringement, then any patent rights granted to you under this License
+for these implementations of WebM shall terminate as of the date such
+litigation is filed.
diff --git a/licenses/lzma-xz-PUBLIC-DOMAIN.txt b/licenses/lzma-xz-PUBLIC-DOMAIN.txt
new file mode 100644
index 0000000..eb3afbd
--- /dev/null
+++ b/licenses/lzma-xz-PUBLIC-DOMAIN.txt
@@ -0,0 +1,9 @@
+LZMA SDK (Igor Pavlov): "LZMA SDK is placed in the public domain. Anyone is free to copy, modify, publish, use,
+compile, sell, or distribute the original LZMA SDK code, either in source code form or as a compiled binary, for any
+purpose, commercial or non-commercial, and by any means." (https://www.7-zip.org/sdk.html). This covers the LZMA
+specification (lzma-specification.txt, LzmaSpec.cpp) and 7zFormat.txt that codecs/Lzma and archive/7z follow.
+
+XZ Utils / xz-embedded (Lasse Collin): the xz file format specification and xz-embedded (including xz_dec_bcj.c, whose
+BCJ filters codecs/Lzma/Filters follows) were released into the public domain ("This file has been put into the public
+domain. You can do whatever you want with this file."); newer releases use the 0BSD licence, which imposes no
+conditions either.
diff --git a/licenses/opengametools-LICENSE.txt b/licenses/opengametools-LICENSE.txt
new file mode 100644
index 0000000..eadf720
--- /dev/null
+++ b/licenses/opengametools-LICENSE.txt
@@ -0,0 +1,9 @@
+MIT License
+
+Copyright (c) 2019 Justin Paver
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/licenses/stb_truetype-LICENSE.txt b/licenses/stb_truetype-LICENSE.txt
new file mode 100644
index 0000000..b43e1af
--- /dev/null
+++ b/licenses/stb_truetype-LICENSE.txt
@@ -0,0 +1,28 @@
+stb_truetype.h v1.26 by Sean Barrett (https://github.com/nothings/stb), via the imgui-luau port (imstb_truetype.lua).
+Upstream offers two licences; choose whichever you prefer.
+
+ALTERNATIVE A - MIT License
+Copyright (c) 2017 Sean Barrett
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
+rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
+persons to whom the Software is furnished to do so, subject to the following conditions:
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
+Software.
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+ALTERNATIVE B - Public Domain (www.unlicense.org)
+This is free and unencumbered software released into the public domain.
+Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or
+as a compiled binary, for any purpose, commercial or non-commercial, and by any means.
+In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright
+interest in the software to the public domain. We make this dedication for the benefit of the public at large and to
+the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in
+perpetuity of all present and future rights to this software under copyright law.
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/licenses/voxel-model-LICENSE.txt b/licenses/voxel-model-LICENSE.txt
new file mode 100644
index 0000000..d6af977
--- /dev/null
+++ b/licenses/voxel-model-LICENSE.txt
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 ephtracy
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau
index 8f9252f..dd4f16b 100644
--- a/src/Formats/Registry.luau
+++ b/src/Formats/Registry.luau
@@ -26,6 +26,54 @@ local list: { Entry } = {
return require("@formats/image/bmp")
end,
},
+ {
+ name = "gif",
+ category = "image",
+ path = "image/gif",
+ extensions = { "gif" },
+ mime = { "image/gif" },
+ deps = { "core/Err", "core/Bytes", "codecs/Lzw", "codecs/Quantize", "Types" },
+ caps = { decode = true, encode = true, animation = true, alpha = true, palette = true, depths = { 1, 2, 4, 8 } },
+ load = function()
+ return require("@formats/image/gif")
+ end,
+ },
+ {
+ name = "hdr",
+ category = "image",
+ path = "image/hdr",
+ extensions = { "hdr", "pic", "rgbe" },
+ mime = { "image/vnd.radiance", "image/x-hdr" },
+ deps = { "core/Err", "core/Bytes", "Types" },
+ caps = { decode = true, encode = true, alpha = false, float = true, depths = { 32 } },
+ load = function()
+ return require("@formats/image/hdr")
+ end,
+ },
+ {
+ name = "ico",
+ category = "image",
+ path = "image/ico",
+ extensions = { "ico", "cur" },
+ mime = { "image/vnd.microsoft.icon", "image/x-icon" },
+ deps = { "core/Err", "core/Bytes", "Types" },
+ caps = { decode = true, encode = true, alpha = true, frames = true, depths = { 1, 4, 8, 16, 24, 32 } },
+ load = function()
+ return require("@formats/image/ico")
+ end,
+ },
+ {
+ name = "jpeg",
+ category = "image",
+ path = "image/jpeg",
+ extensions = { "jpg", "jpeg", "jpe", "jfif" },
+ mime = { "image/jpeg" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/Dct" },
+ caps = { decode = true, encode = true, lossy = true, alpha = false, depths = { 8, 12 }, progressive = true, arithmetic = true },
+ load = function()
+ return require("@formats/image/jpeg")
+ end,
+ },
{
name = "png",
category = "image",
@@ -38,6 +86,78 @@ local list: { Entry } = {
return require("@formats/image/png")
end,
},
+ {
+ name = "pnm",
+ category = "image",
+ path = "image/pnm",
+ extensions = { "pnm", "pbm", "pgm", "ppm", "pam", "pfm" },
+ mime = { "image/x-portable-anymap", "image/x-portable-bitmap", "image/x-portable-graymap", "image/x-portable-pixmap", "image/x-portable-arbitrarymap", "image/x-portable-floatmap" },
+ deps = { "core/Err", "core/Bytes", "Types" },
+ caps = { decode = true, encode = true, alpha = true, depths = { 1, 8, 16, 32 }, float = true },
+ load = function()
+ return require("@formats/image/pnm")
+ end,
+ },
+ {
+ name = "qoi",
+ category = "image",
+ path = "image/qoi",
+ extensions = { "qoi" },
+ mime = { "image/qoi", "image/x-qoi" },
+ deps = { "core/Err", "core/Bytes", "Types" },
+ caps = { decode = true, encode = true, alpha = true, depths = { 8 } },
+ load = function()
+ return require("@formats/image/qoi")
+ end,
+ },
+ {
+ name = "tga",
+ category = "image",
+ path = "image/tga",
+ extensions = { "tga", "icb", "vda", "vst", "tpic" },
+ mime = { "image/x-tga", "image/x-targa" },
+ deps = { "core/Err", "core/Bytes", "Types" },
+ caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 8, 15, 16, 24, 32 } },
+ load = function()
+ return require("@formats/image/tga")
+ end,
+ },
+ {
+ name = "tiff",
+ category = "image",
+ path = "image/tiff",
+ extensions = { "tif", "tiff" },
+ mime = { "image/tiff" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/Deflate", "codecs/Lzw" },
+ caps = { decode = true, encode = true, alpha = true, pages = true, depths = { 1, 2, 4, 8, 16, 32 }, float = true },
+ load = function()
+ return require("@formats/image/tiff")
+ end,
+ },
+ {
+ name = "webp",
+ category = "image",
+ path = "image/webp",
+ extensions = { "webp" },
+ mime = { "image/webp" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/Vp8", "codecs/Vp8L", "containers/Riff" },
+ caps = { decode = true, encode = true, animation = true, alpha = true, lossy = true, lossless = true, depths = { 8 } },
+ load = function()
+ return require("@formats/image/webp")
+ end,
+ },
+ {
+ name = "aac",
+ category = "audio",
+ path = "audio/aac",
+ extensions = { "aac", "adts" },
+ mime = { "audio/aac", "audio/aacp", "audio/x-aac" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac" },
+ caps = { decode = true, encode = false, codecs = { "aac" }, streaming = true },
+ load = function()
+ return require("@formats/audio/aac")
+ end,
+ },
{
name = "aiff",
category = "audio",
@@ -62,6 +182,18 @@ local list: { Entry } = {
return require("@formats/audio/au")
end,
},
+ {
+ name = "caf",
+ category = "audio",
+ path = "audio/caf",
+ extensions = { "caf", "caff" },
+ mime = { "audio/x-caf" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac", "codecs/Alac" },
+ caps = { decode = true, encode = true, codecs = { "pcm", "alac", "aac", "ulaw", "alaw" }, encodeCodecs = { "pcm", "alac" }, tags = true, streaming = true },
+ load = function()
+ return require("@formats/audio/caf")
+ end,
+ },
{
name = "flac",
category = "audio",
@@ -74,6 +206,18 @@ local list: { Entry } = {
return require("@formats/audio/flac")
end,
},
+ {
+ name = "m4a",
+ category = "audio",
+ path = "audio/m4a",
+ extensions = { "m4a", "m4b", "m4r" },
+ mime = { "audio/mp4", "audio/x-m4a", "audio/m4a" },
+ deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "codecs/Aac", "codecs/Alac" },
+ caps = { decode = true, encode = true, codecs = { "aac", "alac" }, encodeCodecs = { "alac" }, tags = true, streaming = true },
+ load = function()
+ return require("@formats/audio/m4a")
+ end,
+ },
{
name = "mp3",
category = "audio",
@@ -92,8 +236,8 @@ local list: { Entry } = {
path = "audio/opus",
extensions = { "opus" },
mime = { "audio/opus", "audio/ogg" },
- deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg" },
- caps = { decode = true, encode = false, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 } },
+ deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct" },
+ caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 }, encodeModes = { "celt" } },
load = function()
return require("@formats/audio/opus")
end,
@@ -134,6 +278,198 @@ local list: { Entry } = {
return require("@formats/audio/wav")
end,
},
+ {
+ name = "gltf",
+ category = "model",
+ path = "model/gltf",
+ extensions = { "gltf", "glb" },
+ mime = { "model/gltf+json", "model/gltf-binary" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/Json", "codecs/Base64" },
+ caps = { decode = true, encode = true, binary = true, materials = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true },
+ load = function()
+ return require("@formats/model/gltf")
+ end,
+ },
+ {
+ name = "obj",
+ category = "model",
+ path = "model/obj",
+ extensions = { "obj" },
+ mime = { "model/obj" },
+ deps = { "core/Err", "core/Bytes", "Types" },
+ caps = { decode = true, encode = true, materials = true, polygons = true, vertexColors = true },
+ load = function()
+ return require("@formats/model/obj")
+ end,
+ },
+ {
+ name = "off",
+ category = "model",
+ path = "model/off",
+ extensions = { "off" },
+ mime = { "model/off", "text/plain" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/MeshFlatten" },
+ caps = { decode = true, encode = true, polygons = true, points = true, colors = true, binary = false },
+ load = function()
+ return require("@formats/model/off")
+ end,
+ },
+ {
+ name = "ply",
+ category = "model",
+ path = "model/ply",
+ extensions = { "ply" },
+ mime = { "model/ply", "application/ply" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/MeshFlatten" },
+ caps = { decode = true, encode = true, ascii = true, binary = true, polygons = true, points = true, colors = true },
+ load = function()
+ return require("@formats/model/ply")
+ end,
+ },
+ {
+ name = "stl",
+ category = "model",
+ path = "model/stl",
+ extensions = { "stl" },
+ mime = { "model/stl", "application/sla" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/MeshFlatten" },
+ caps = { decode = true, encode = true, ascii = true, binary = true, colors = true, indexed = false },
+ load = function()
+ return require("@formats/model/stl")
+ end,
+ },
+ {
+ name = "vox",
+ category = "model",
+ path = "model/vox",
+ extensions = { "vox" },
+ mime = { "model/x-vox" },
+ deps = { "core/Err", "core/Bytes", "Types" },
+ caps = { decode = true, encode = true, voxels = true, sceneGraph = true, materials = true },
+ load = function()
+ return require("@formats/model/vox")
+ end,
+ },
+ {
+ name = "bmfont",
+ category = "font",
+ path = "font/bmfont",
+ extensions = { "fnt" },
+ mime = { "application/x-bmfont" },
+ deps = { "core/Err", "core/Bytes", "Types" },
+ caps = { decode = true, encode = true, bitmap = true, variants = { "text", "xml", "binary" } },
+ load = function()
+ return require("@formats/font/bmfont")
+ end,
+ },
+ {
+ name = "ttf",
+ category = "font",
+ path = "font/ttf",
+ extensions = { "ttf", "otf", "ttc", "otc" },
+ mime = { "font/ttf", "font/otf", "font/collection" },
+ deps = { "core/Err", "core/Bytes", "codecs/TrueType" },
+ caps = { decode = true, encode = false, outlines = { "truetype", "cff" }, collection = true, kerning = true },
+ load = function()
+ return require("@formats/font/ttf")
+ end,
+ },
+ {
+ name = "woff",
+ category = "font",
+ path = "font/woff",
+ extensions = { "woff" },
+ mime = { "font/woff" },
+ deps = { "core/Err", "core/Bytes", "codecs/Deflate", "codecs/TrueType" },
+ caps = { decode = true, encode = false, outlines = { "truetype", "cff" } },
+ load = function()
+ return require("@formats/font/woff")
+ end,
+ },
+ {
+ name = "woff2",
+ category = "font",
+ path = "font/woff2",
+ extensions = { "woff2" },
+ mime = { "font/woff2" },
+ deps = { "core/Err", "core/Bytes", "codecs/TrueType", "codecs/Brotli" },
+ caps = { decode = true, encode = false, outlines = { "truetype", "cff" }, transforms = { "glyf", "loca", "hmtx" } },
+ load = function()
+ return require("@formats/font/woff2")
+ end,
+ },
+ {
+ name = "7z",
+ category = "archive",
+ path = "archive/7z",
+ extensions = { "7z" },
+ mime = { "application/x-7z-compressed" },
+ deps = { "core/Err", "core/Bytes", "core/Crc32", "Types", "codecs/Lzma", "codecs/Deflate", "codecs/Bzip2", "codecs/Zstd", "containers/Archive" },
+ caps = { decode = true, encode = false, methods = { "copy", "lzma", "lzma2", "deflate", "bcj", "delta" }, encrypted = false },
+ load = function()
+ return require("@formats/archive/7z")
+ end,
+ },
+ {
+ name = "br",
+ category = "archive",
+ path = "archive/br",
+ extensions = { "br" },
+ mime = { "application/x-brotli" },
+ deps = { "core/Err", "core/Bytes", "codecs/Brotli", "containers/Archive" },
+ caps = { decode = true, encode = false, stream = true },
+ load = function()
+ return require("@formats/archive/br")
+ end,
+ },
+ {
+ name = "bz2",
+ category = "archive",
+ path = "archive/bz2",
+ extensions = { "bz2", "tbz2", "tbz" },
+ mime = { "application/x-bzip2" },
+ deps = { "core/Err", "core/Bytes", "containers/Archive", "codecs/Bzip2" },
+ caps = { decode = true, encode = false, stream = true },
+ load = function()
+ return require("@formats/archive/bz2")
+ end,
+ },
+ {
+ name = "gzip",
+ category = "archive",
+ path = "archive/gzip",
+ extensions = { "gz", "tgz", "gzip" },
+ mime = { "application/gzip" },
+ deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/Deflate", "containers/Archive", "containers/Tar" },
+ caps = { decode = true, encode = true, stream = true },
+ load = function()
+ return require("@formats/archive/gzip")
+ end,
+ },
+ {
+ name = "tar",
+ category = "archive",
+ path = "archive/tar",
+ extensions = { "tar" },
+ mime = { "application/x-tar" },
+ deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Tar" },
+ caps = { decode = true, encode = true, variants = { "ustar", "pax", "gnu" } },
+ load = function()
+ return require("@formats/archive/tar")
+ end,
+ },
+ {
+ name = "xz",
+ category = "archive",
+ path = "archive/xz",
+ extensions = { "xz", "txz", "lzma" },
+ mime = { "application/x-xz", "application/x-lzma" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/Lzma", "containers/Archive" },
+ caps = { decode = true, encode = false, stream = true, filters = { "lzma2", "lzma", "delta", "x86", "powerpc", "arm", "armthumb", "sparc", "arm64" } },
+ load = function()
+ return require("@formats/archive/xz")
+ end,
+ },
{
name = "zip",
category = "archive",
@@ -146,6 +482,246 @@ local list: { Entry } = {
return require("@formats/archive/zip")
end,
},
+ {
+ name = "zst",
+ category = "archive",
+ path = "archive/zst",
+ extensions = { "zst", "tzst" },
+ mime = { "application/zstd" },
+ deps = { "core/Err", "core/Bytes", "codecs/Zstd", "containers/Archive" },
+ caps = { decode = true, encode = false, stream = true },
+ load = function()
+ return require("@formats/archive/zst")
+ end,
+ },
+ {
+ name = "cbor",
+ category = "data",
+ path = "data/cbor",
+ extensions = { "cbor" },
+ mime = { "application/cbor", "application/cbor-seq" },
+ deps = { "core/Err", "core/Bytes", "Types" },
+ caps = { decode = true, encode = true, binary = true, ordered = true, tags = true },
+ load = function()
+ return require("@formats/data/cbor")
+ end,
+ },
+ {
+ name = "csv",
+ category = "data",
+ path = "data/csv",
+ extensions = { "csv", "tsv" },
+ mime = { "text/csv", "text/tab-separated-values" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/Json" },
+ caps = { decode = true, encode = true, header = true },
+ load = function()
+ return require("@formats/data/csv")
+ end,
+ },
+ {
+ name = "ini",
+ category = "data",
+ path = "data/ini",
+ extensions = { "ini", "cfg", "conf", "inf", "desktop" },
+ mime = { "text/plain" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/Json" },
+ caps = { decode = true, encode = true, ordered = true },
+ load = function()
+ return require("@formats/data/ini")
+ end,
+ },
+ {
+ name = "json",
+ category = "data",
+ path = "data/json",
+ extensions = { "json", "jsonl", "ndjson", "geojson" },
+ mime = { "application/json", "application/x-ndjson" },
+ deps = { "core/Err", "core/Bytes", "codecs/Json" },
+ caps = { decode = true, encode = true, ordered = true, streaming = true },
+ load = function()
+ return require("@formats/data/json")
+ end,
+ },
+ {
+ name = "msgpack",
+ category = "data",
+ path = "data/msgpack",
+ extensions = { "msgpack", "mpk" },
+ mime = { "application/msgpack", "application/x-msgpack" },
+ deps = { "core/Err", "core/Bytes", "Types" },
+ caps = { decode = true, encode = true, binary = true, ordered = true },
+ load = function()
+ return require("@formats/data/msgpack")
+ end,
+ },
+ {
+ name = "plist",
+ category = "data",
+ path = "data/plist",
+ extensions = { "plist" },
+ mime = { "application/x-plist", "application/x-bplist" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "codecs/Json" },
+ caps = { decode = true, encode = true, binary = "read", ordered = true },
+ load = function()
+ return require("@formats/data/plist")
+ end,
+ },
+ {
+ name = "toml",
+ category = "data",
+ path = "data/toml",
+ extensions = { "toml" },
+ mime = { "application/toml" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/Json" },
+ caps = { decode = true, encode = true, ordered = true, dates = true },
+ load = function()
+ return require("@formats/data/toml")
+ end,
+ },
+ {
+ name = "xml",
+ category = "data",
+ path = "data/xml",
+ extensions = { "xml", "xsd", "xsl", "xslt", "rss", "atom", "xhtml" },
+ mime = { "application/xml", "text/xml" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml" },
+ caps = { decode = true, encode = true, namespaces = true, streaming = true },
+ load = function()
+ return require("@formats/data/xml")
+ end,
+ },
+ {
+ name = "yaml",
+ category = "data",
+ path = "data/yaml",
+ extensions = { "yaml", "yml" },
+ mime = { "application/yaml", "application/x-yaml", "text/yaml" },
+ deps = { "core/Err", "core/Bytes", "Types" },
+ caps = { decode = true, encode = true, ordered = true, multiDocument = true, anchors = true },
+ load = function()
+ return require("@formats/data/yaml")
+ end,
+ },
+ {
+ name = "svg",
+ category = "vector",
+ path = "vector/svg",
+ extensions = { "svg" },
+ mime = { "image/svg+xml" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "codecs/Raster", "codecs/Blend" },
+ caps = { decode = true, encode = true, rasterize = true, text = false },
+ load = function()
+ return require("@formats/vector/svg")
+ end,
+ },
+ {
+ name = "tiled",
+ category = "vector",
+ path = "vector/tiled",
+ extensions = { "tmx", "tmj", "tsx", "tsj" },
+ mime = { "application/x-tiled-tmx", "application/x-tiled-tmj" },
+ deps = { "core/Err", "core/Bytes", "core/Base64", "Types", "codecs/Xml", "codecs/Json", "codecs/Deflate" },
+ caps = { decode = true, encode = true, tilesets = true, infinite = true },
+ load = function()
+ return require("@formats/vector/tiled")
+ end,
+ },
+ {
+ name = "aseprite",
+ category = "layered",
+ path = "layered/aseprite",
+ extensions = { "aseprite", "ase" },
+ mime = { "image/x-aseprite" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/Deflate" },
+ caps = { decode = true, encode = true, layers = true, groups = true, animation = true, depths = { 8, 16, 32 } },
+ load = function()
+ return require("@formats/layered/aseprite")
+ end,
+ },
+ {
+ name = "psd",
+ category = "layered",
+ path = "layered/psd",
+ extensions = { "psd", "psb" },
+ mime = { "image/vnd.adobe.photoshop" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/Blend", "codecs/Deflate" },
+ caps = { decode = true, encode = true, layers = true, groups = true, depths = { 1, 8, 16, 32 } },
+ load = function()
+ return require("@formats/layered/psd")
+ end,
+ },
+ {
+ name = "ass",
+ category = "subtitle",
+ path = "subtitle/ass",
+ extensions = { "ass", "ssa" },
+ mime = { "text/x-ssa", "text/x-ass" },
+ deps = { "core/Err", "core/Bytes", "Types" },
+ caps = { decode = true, encode = true, styles = true },
+ load = function()
+ return require("@formats/subtitle/ass")
+ end,
+ },
+ {
+ name = "srt",
+ category = "subtitle",
+ path = "subtitle/srt",
+ extensions = { "srt" },
+ mime = { "application/x-subrip", "text/srt" },
+ deps = { "core/Err", "core/Bytes", "Types" },
+ caps = { decode = true, encode = true, styles = false },
+ load = function()
+ return require("@formats/subtitle/srt")
+ end,
+ },
+ {
+ name = "vtt",
+ category = "subtitle",
+ path = "subtitle/vtt",
+ extensions = { "vtt", "webvtt" },
+ mime = { "text/vtt" },
+ deps = { "core/Err", "core/Bytes", "Types" },
+ caps = { decode = true, encode = true, styles = true },
+ load = function()
+ return require("@formats/subtitle/vtt")
+ end,
+ },
+ {
+ name = "m3u",
+ category = "playlist",
+ path = "playlist/m3u",
+ extensions = { "m3u", "m3u8" },
+ mime = { "audio/x-mpegurl", "audio/mpegurl", "application/vnd.apple.mpegurl", "application/x-mpegurl" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/Url", "codecs/Text" },
+ caps = { decode = true, encode = true, hls = true },
+ load = function()
+ return require("@formats/playlist/m3u")
+ end,
+ },
+ {
+ name = "pls",
+ category = "playlist",
+ path = "playlist/pls",
+ extensions = { "pls" },
+ mime = { "audio/x-scpls", "audio/scpls" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/Url", "codecs/Text" },
+ caps = { decode = true, encode = true },
+ load = function()
+ return require("@formats/playlist/pls")
+ end,
+ },
+ {
+ name = "xspf",
+ category = "playlist",
+ path = "playlist/xspf",
+ extensions = { "xspf" },
+ mime = { "application/xspf+xml" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/Url", "codecs/Xml" },
+ caps = { decode = true, encode = true },
+ load = function()
+ return require("@formats/playlist/xspf")
+ end,
+ },
}
return list
diff --git a/src/Formats/Types.luau b/src/Formats/Types.luau
index 9f37bd1..6464e98 100644
--- a/src/Formats/Types.luau
+++ b/src/Formats/Types.luau
@@ -197,21 +197,66 @@ export type VideoDecoder = {
}
-- ------------------------------------------------------------------------------------------------ Scene (3D, glTF-shaped)
+-- Indices are 1-based everywhere (node, mesh, material, texture, ...). Accessor data is tightly packed (no stride, no
+-- padding, sparse accessors already applied). unorm / snorm types are glTF's normalized integers (value / 255,
+-- max(value / 127, -1), ...). Positions are in scene units (meta.unit = metres per unit when known), meta.up is the
+-- source's up axis ("y" for glTF / OBJ, "z" for STL / VOX / most CAD) - no format rotates the data on load.
+--
+-- Textures keep the encoded image (texture.data + texture.mime, PNG / JPEG / ... bytes) or an external reference
+-- (texture.uri): a model format never decodes images (a format does not require another format). Decode them at the
+-- api layer, lazily: `F.model.loadTextures(scene)` sets texture.image = F.image.load(texture.data) for each texture
+-- whose image format is available (or do it yourself when needed). Writers embed texture.data when set, else write
+-- texture.uri; a texture with only a decoded image must be encoded first (texture.data = F.save(texture.image, nil,
+-- { format = "png" }), texture.mime = "image/png"), which `F.model.save` does for you.
+--
+-- Other files (OBJ's .mtl, glTF's .bin / images): decoders ask `opts.resolve(uri) -> buffer | string | nil`, or look
+-- up `opts.files[uri]` (a table of buffers / strings); the api sets opts.resolve to read files next to a path it
+-- loaded. Encoders that write more than one file return the main file and put the others into `opts.files` (when the
+-- caller passes a table there; the api does, and writes them next to the destination), named after `opts.name`.
export type Accessor = {
- data: buffer, -- tightly packed
- type: "f32" | "u8" | "u16" | "u32" | "i8" | "i16" | "unorm8" | "unorm16" | "snorm8" | "snorm16",
- components: number, -- 1 (SCALAR) .. 4 (VEC4), 16 (MAT4)
+ data: buffer, -- tightly packed, little endian
+ type: "f32" | "f64" | "u8" | "u16" | "u32" | "i8" | "i16" | "i32" | "unorm8" | "unorm16" | "snorm8" | "snorm16",
+ components: number, -- 1 (SCALAR) .. 4 (VEC4), 4 (MAT2), 9 (MAT3), 16 (MAT4)
count: number,
+ matrix: boolean?, -- components 4 / 9 / 16 are MAT2 / MAT3 / MAT4 (glTF), not VEC4
+ name: string?,
}
export type Primitive = {
- attributes: { [string]: Accessor }, -- POSITION, NORMAL, TANGENT, TEXCOORD_0, COLOR_0, JOINTS_0, WEIGHTS_0
+ attributes: { [string]: Accessor }, -- POSITION, NORMAL, TANGENT, TEXCOORD_n, COLOR_n, JOINTS_n, WEIGHTS_n; custom
+ -- attributes start with "_" (glTF convention: PLY extra vertex properties, ...)
indices: Accessor?,
- mode: "triangles" | "lines" | "points" | "triangle_strip" | "triangle_fan" | "line_strip",
+ -- "polygons": faces (u32, one size per face) splits indices into n-gons (OBJ / PLY / OFF with triangulate = false;
+ -- MeshOps.triangulate turns them into triangles)
+ mode: "triangles" | "lines" | "points" | "triangle_strip" | "triangle_fan" | "line_strip" | "line_loop" | "polygons",
+ faces: Accessor?,
material: number?, -- index into scene.materials (1-based)
+ targets: { { [string]: Accessor } }?, -- morph targets (POSITION / NORMAL / TANGENT deltas)
+ extras: { [string]: any }?,
+}
+export type Mesh = { name: string?, primitives: { Primitive }, weights: { number }?, extras: { [string]: any }? }
+export type Sampler = {
+ wrapS: ("repeat" | "clamp" | "mirror")?, -- default "repeat"
+ wrapT: ("repeat" | "clamp" | "mirror")?,
+ filter: ("linear" | "nearest")?, -- magnification
+ minFilter: string?, -- "nearest" | "linear" | "nearest_mipmap_nearest" | ... (glTF names, lower case)
+}
+export type Texture = {
+ name: string?,
+ image: Image?, -- decoded (F.model.loadTextures or the caller), never by a model format
+ data: buffer?, -- the encoded image bytes (embedded / GLB / data: URI / resolved external file)
+ mime: string?, -- "image/png", "image/jpeg", "image/webp", "image/ktx2", ...
+ uri: string?, -- the external file name (relative to the model) when the data was not available or not embedded
+ sampler: Sampler?,
+ extras: { [string]: any }?,
+}
+export type TextureRef = {
+ texture: number, -- index into scene.textures (1-based)
+ texCoord: number?, -- TEXCOORD_n set (default 0)
+ scale: number?, -- normalTexture scale
+ strength: number?, -- occlusionTexture strength
+ -- KHR_texture_transform (texCoord overrides the ref's texCoord)
+ transform: { offset: { number }?, scale: { number }?, rotation: number?, texCoord: number? }?,
}
-export type Mesh = { name: string?, primitives: { Primitive } }
-export type Texture = { image: Image?, uri: string?, sampler: { wrapS: string?, wrapT: string?, filter: string? }? }
-export type TextureRef = { texture: number, texCoord: number?, transform: { offset: { number }?, scale: { number }?, rotation: number? }? }
export type Material = {
name: string?,
baseColor: { number }, -- r, g, b, a linear 0..1
@@ -226,6 +271,9 @@ export type Material = {
alphaMode: "opaque" | "mask" | "blend",
alphaCutoff: number,
doubleSided: boolean,
+ -- glTF material extensions by name (KHR_materials_emissive_strength = { emissiveStrength = 5 }, KHR_materials_unlit
+ -- = {}, ...), their fields as in glTF except textureInfo objects, which are TextureRefs
+ extensions: { [string]: any }?,
extras: { [string]: any }?, -- classic Phong (OBJ / FBX): ambient, diffuse, specular, shininess, ...
}
export type Node = {
@@ -235,17 +283,52 @@ export type Node = {
camera: number?,
light: number?,
skin: number?,
+ voxels: number?, -- index into scene.voxels (MagicaVoxel shapes; MeshOps.meshVoxels gives them meshes)
translation: { number }?, -- TRS, or matrix (column-major 4x4), not both
rotation: { number }?, -- quaternion x, y, z, w
scale: { number }?,
matrix: { number }?,
+ weights: { number }?, -- morph target weights
extras: { [string]: any }?,
}
-export type Camera = { type: "perspective" | "orthographic", yfov: number?, aspect: number?, xmag: number?, ymag: number?, znear: number, zfar: number? }
-export type Light = { type: "directional" | "point" | "spot", color: { number }, intensity: number, range: number?, innerCone: number?, outerCone: number? }
-export type Skin = { joints: { number }, inverseBindMatrices: Accessor?, skeleton: number? }
+export type Camera = { name: string?, type: "perspective" | "orthographic", yfov: number?, aspect: number?, xmag: number?, ymag: number?, znear: number, zfar: number? }
+export type Light = { name: string?, type: "directional" | "point" | "spot", color: { number }, intensity: number, range: number?, innerCone: number?, outerCone: number? }
+export type Skin = { name: string?, joints: { number }, inverseBindMatrices: Accessor?, skeleton: number? }
export type Channel = { node: number, path: "translation" | "rotation" | "scale" | "weights", input: Accessor, output: Accessor, interpolation: "LINEAR" | "STEP" | "CUBICSPLINE" }
export type Animation = { name: string?, channels: { Channel } }
+
+-- a voxel grid (MagicaVoxel): one byte per cell, 0 = empty, 1..255 = palette index
+export type VoxelMaterial = { type: string, [string]: any } -- "diffuse" | "metal" | "glass" | "emit" | "blend" | "media" | ..., MATL properties (numbers when numeric)
+export type Voxels = {
+ kind: "voxels",
+ name: string?,
+ size: { number }, -- x, y, z cells
+ data: buffer, -- size x * y * z bytes, cell (x, y, z) at x + sx * (y + sy * z)
+ palette: { { number } }, -- palette[i] = { r, g, b, a } 0..255 (sRGB) for i = 1 .. 255 (shared between a file's models)
+ materials: { [number]: VoxelMaterial }?, -- by palette index
+}
+local Voxels = {}
+-- new(sx, sy, sz, palette?) -> an empty grid (the palette defaults to grey ramps: callers set their own)
+function Voxels.new(sx: number, sy: number, sz: number, palette: { { number } }?): Voxels
+ local pal = palette
+ if not pal then
+ local p = table.create(255)
+ for i = 1, 255 do
+ p[i] = { i, i, i, 255 }
+ end
+ pal = p
+ end
+ return { kind = "voxels", size = { sx, sy, sz }, data = buffer.create(sx * sy * sz), palette = pal :: { { number } }, materials = nil }
+end
+-- get / set(v, x, y, z [, index]): 0-based cell coordinates, no bounds check
+function Voxels.get(v: Voxels, x: number, y: number, z: number): number
+ return buffer.readu8(v.data, x + v.size[1] * (y + v.size[2] * z))
+end
+function Voxels.set(v: Voxels, x: number, y: number, z: number, index: number)
+ buffer.writeu8(v.data, x + v.size[1] * (y + v.size[2] * z), index)
+end
+Types.Voxels = Voxels
+
export type Scene = {
kind: "scene",
nodes: { Node },
@@ -257,6 +340,7 @@ export type Scene = {
lights: { Light },
skins: { Skin },
animations: { Animation },
+ voxels: { Voxels }?, -- voxel grids (VOX), referenced by node.voxels
meta: { up: "y" | "z"?, unit: number?, source: { format: string, [string]: any }?, [string]: any },
}
@@ -273,11 +357,30 @@ function Scene.new(): Scene
lights = {},
skins = {},
animations = {},
+ voxels = nil,
meta = {},
}
end
-function Scene.accessor(data: buffer, type: any, components: number, count: number): Accessor
- return { data = data, type = type, components = components, count = count }
+-- the byte size of one component of an accessor type
+local COMPONENT_SIZE: { [string]: number } = {
+ f32 = 4,
+ f64 = 8,
+ u8 = 1,
+ u16 = 2,
+ u32 = 4,
+ i8 = 1,
+ i16 = 2,
+ i32 = 4,
+ unorm8 = 1,
+ unorm16 = 2,
+ snorm8 = 1,
+ snorm16 = 2,
+}
+Types.COMPONENT_SIZE = table.freeze(COMPONENT_SIZE)
+-- accessor(data, type, components, count) -> Accessor (data = nil allocates a zero-filled buffer)
+function Scene.accessor(data: buffer?, type: any, components: number, count: number): Accessor
+ local d = data or buffer.create(count * components * (COMPONENT_SIZE[type] or 4))
+ return { data = d, type = type, components = components, count = count }
end
function Scene.material(name: string?): Material
return {
@@ -301,6 +404,161 @@ function Scene.fromPrimitive(prim: Primitive, name: string?): Scene
end
Types.Scene = Scene
+-- reader(acc) -> get(i, c): element i (0-based), component c (0-based) as a number; normalized types are converted
+-- to floats (unorm8 255 -> 1, snorm16 -32767 -> -1, glTF rules). Nil for an unknown type.
+function Scene.reader(acc: Accessor): ((i: number, c: number) -> number)?
+ local d, n, t = acc.data, acc.components, acc.type
+ local size = COMPONENT_SIZE[t]
+ if not size or type(d) ~= "buffer" then
+ return nil
+ end
+ local stride = n * size
+ local rb = buffer
+ if t == "f32" then
+ local f = rb.readf32
+ return function(i: number, c: number): number
+ return f(d, i * stride + c * 4)
+ end
+ elseif t == "f64" then
+ local f = rb.readf64
+ return function(i: number, c: number): number
+ return f(d, i * stride + c * 8)
+ end
+ elseif t == "u8" or t == "unorm8" then
+ local f, k = rb.readu8, if t == "unorm8" then 1 / 255 else 1
+ return function(i: number, c: number): number
+ return f(d, i * stride + c) * k
+ end
+ elseif t == "u16" or t == "unorm16" then
+ local f, k = rb.readu16, if t == "unorm16" then 1 / 65535 else 1
+ return function(i: number, c: number): number
+ return f(d, i * stride + c * 2) * k
+ end
+ elseif t == "u32" then
+ local f = rb.readu32
+ return function(i: number, c: number): number
+ return f(d, i * stride + c * 4)
+ end
+ elseif t == "i8" then
+ local f = rb.readi8
+ return function(i: number, c: number): number
+ return f(d, i * stride + c)
+ end
+ elseif t == "snorm8" then
+ local f = rb.readi8
+ return function(i: number, c: number): number
+ return math.max(f(d, i * stride + c) / 127, -1)
+ end
+ elseif t == "i16" then
+ local f = rb.readi16
+ return function(i: number, c: number): number
+ return f(d, i * stride + c * 2)
+ end
+ elseif t == "snorm16" then
+ local f = rb.readi16
+ return function(i: number, c: number): number
+ return math.max(f(d, i * stride + c * 2) / 32767, -1)
+ end
+ elseif t == "i32" then
+ local f = rb.readi32
+ return function(i: number, c: number): number
+ return f(d, i * stride + c * 4)
+ end
+ end
+ return nil
+end
+
+-- the identity and products of column-major 4x4 matrices (flat arrays of 16)
+local IDENTITY = table.freeze({ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 })
+Scene.IDENTITY = IDENTITY
+function Scene.mul(a: { number }, b: { number }): { number }
+ local m = table.create(16, 0)
+ for col = 0, 3 do
+ for row = 0, 3 do
+ local s = 0
+ for k = 0, 3 do
+ s += a[k * 4 + row + 1] * b[col * 4 + k + 1]
+ end
+ m[col * 4 + row + 1] = s
+ end
+ end
+ return m
+end
+-- nodeMatrix(node) -> the node's local matrix (node.matrix, or T * R * S)
+function Scene.nodeMatrix(node: Node): { number }
+ if node.matrix and #node.matrix == 16 then
+ return node.matrix
+ end
+ local t, r, sc = node.translation, node.rotation, node.scale
+ if not t and not r and not sc then
+ return IDENTITY
+ end
+ local tx, ty, tz = 0, 0, 0
+ if t then
+ tx, ty, tz = t[1] or 0, t[2] or 0, t[3] or 0
+ end
+ local x, y, z, w = 0, 0, 0, 1
+ if r then
+ x, y, z, w = r[1] or 0, r[2] or 0, r[3] or 0, r[4] or 1
+ end
+ local sx, sy, sz = 1, 1, 1
+ if sc then
+ sx, sy, sz = sc[1] or 1, sc[2] or 1, sc[3] or 1
+ end
+ 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
+ return {
+ (1 - 2 * (yy + zz)) * sx, (2 * (xy + wz)) * sx, (2 * (xz - wy)) * sx, 0,
+ (2 * (xy - wz)) * sy, (1 - 2 * (xx + zz)) * sy, (2 * (yz + wx)) * sy, 0,
+ (2 * (xz + wy)) * sz, (2 * (yz - wx)) * sz, (1 - 2 * (xx + yy)) * sz, 0,
+ tx, ty, tz, 1,
+ }
+end
+export type Placed = { primitive: Primitive, matrix: { number }, node: number, mesh: number }
+-- flatten(scene) -> { { primitive, matrix (world), node, mesh } } for every mesh primitive reachable from the roots
+-- (depth first, in order; cycles and repeated visits are cut). Scenes without roots use every node without a parent.
+function Scene.flatten(scene: Scene): { Placed }
+ local out: { Placed } = {}
+ local nodes = scene.nodes or {}
+ local roots = scene.roots
+ if not roots or #roots == 0 then
+ local child = {}
+ for _, n in nodes do
+ for _, c in n.children or {} do
+ child[c] = true
+ end
+ end
+ roots = {}
+ for i in nodes do
+ if not child[i] then
+ table.insert(roots, i)
+ end
+ end
+ end
+ local seen: { [number]: boolean } = {}
+ local function visit(i: number, parent: { number })
+ local node = nodes[i]
+ if not node or seen[i] then
+ return
+ end
+ seen[i] = true
+ local m = Scene.nodeMatrix(node)
+ local world = if parent == IDENTITY then m elseif m == IDENTITY then parent else Scene.mul(parent, m)
+ local mesh = node.mesh and scene.meshes[node.mesh]
+ if mesh then
+ for _, p in mesh.primitives do
+ table.insert(out, { primitive = p, matrix = world, node = i, mesh = node.mesh :: number })
+ end
+ end
+ for _, c in node.children or {} do
+ visit(c, world)
+ end
+ end
+ for _, r in roots do
+ visit(r, IDENTITY)
+ end
+ return out
+end
+
-- ------------------------------------------------------------------------------------------------ Cad
-- the STEP entity graph; B-rep bodies and tessellation come from the injected brep plug-in (Formats.plugins.brep)
export type StepEntity = { id: number, type: string, args: { any } }
@@ -343,12 +601,289 @@ export type Archive = {
-- ------------------------------------------------------------------------------------------------ Data
-- data formats decode to plain Luau values; JSON null / YAML ~ / CBOR null is this sentinel (nil cannot sit in a
--- table). XML decodes to XmlNode trees.
+-- table). XML decodes to XmlNode trees. Byte strings (msgpack bin, CBOR bytes, plist data) are buffers.
local nullMeta = { __tostring = function()
return "null"
end }
Types.null = table.freeze(setmetatable({}, nullMeta))
-export type XmlNode = { name: string, attrs: { [string]: string }, children: { XmlNode | string }, parent: XmlNode? }
+
+-- Objects (maps) whose key order matters, and empty objects (which would otherwise read back as empty arrays), carry
+-- an "object" metatable with their key order. Decoders mark empty objects always and every object when asked
+-- (opts.ordered); encoders write an object's keys in that order (keys added later, or plain tables: sorted).
+-- local o = Types.object() o.b = 1; o.a = 2 -- or Types.object({ a = 2, b = 1 }, { "b", "a" })
+-- Types.set(o, "c", 3) -- assigns and appends "c" to the order
+-- for _, k in Types.keys(o) do ... end
+local OBJECT = { __object = true }
+local objectMeta: { [any]: { any } } = setmetatable({}, { __mode = "k" }) :: any -- object -> its key order
+-- object(t?, keys?) -> t marked as an object, keys = its key order (default: none recorded; Types.set appends)
+function Types.object(t: { [any]: any }?, keys: { any }?): { [any]: any }
+ local o = t or {}
+ if getmetatable(o) == nil then
+ setmetatable(o, OBJECT)
+ end
+ objectMeta[o] = keys or {}
+ return o
+end
+-- isObject(v) -> true for tables made by Types.object
+function Types.isObject(v: any): boolean
+ return type(v) == "table" and objectMeta[v] ~= nil
+end
+-- set(o, k, v): o[k] = v, appending k to o's key order when new (o must be an object; a plain table just assigns)
+function Types.set(o: { [any]: any }, k: any, v: any)
+ local order = objectMeta[o]
+ if order and o[k] == nil and v ~= nil then
+ table.insert(order, k)
+ end
+ o[k] = v
+end
+local function keyLess(a: any, b: any): boolean
+ local ta, tb = type(a), type(b)
+ if ta ~= tb then
+ return ta < tb
+ end
+ if ta == "number" or ta == "string" then
+ return a < b
+ end
+ return tostring(a) < tostring(b)
+end
+-- keys(t) -> the keys in order: an object's recorded order (keys since removed are skipped), then any other keys
+-- sorted (numbers before strings)
+function Types.keys(t: { [any]: any }): { any }
+ local order = objectMeta[t]
+ local out, seen = {}, {}
+ if order then
+ for _, k in order do
+ if t[k] ~= nil and not seen[k] then
+ seen[k] = true
+ table.insert(out, k)
+ end
+ end
+ end
+ local rest = {}
+ for k in next, t do
+ if not seen[k] then
+ table.insert(rest, k)
+ end
+ end
+ if #rest > 0 then
+ table.sort(rest, keyLess)
+ table.move(rest, 1, #rest, #out + 1, out)
+ end
+ return out
+end
+
+-- Dates and times (TOML datetimes, plist , CBOR tags 0 / 1, msgpack timestamps). Fields present depend on the
+-- kind: "datetime" (with offset: an instant), "datetime-local", "date-local", "time-local". offset is in minutes
+-- east of UTC (nil = local time). tostring gives RFC 3339 ("1979-05-27T07:32:00.5-07:00", "07:32:00", ...).
+export type Date = {
+ kind: "datetime" | "datetime-local" | "date-local" | "time-local",
+ year: number?,
+ month: number?,
+ day: number?,
+ hour: number?,
+ minute: number?,
+ second: number?,
+ nanosecond: number?, -- 0 .. 999999999
+ offset: number?, -- minutes east of UTC
+}
+local DateMeta = {}
+local function p2(n: number): string
+ return string.format("%02d", n)
+end
+local function fmtDate(d: any): string
+ local s = ""
+ if d.year then
+ s = string.format("%04d-%02d-%02d", d.year, d.month or 1, d.day or 1)
+ end
+ if d.hour then
+ if s ~= "" then
+ s ..= "T"
+ end
+ s ..= p2(d.hour) .. ":" .. p2(d.minute or 0) .. ":" .. p2(d.second or 0)
+ local ns = d.nanosecond or 0
+ if ns > 0 then
+ local f = string.format("%09d", ns)
+ s ..= "." .. (string.gsub(f, "0+$", ""))
+ end
+ if d.offset then
+ if d.offset == 0 then
+ s ..= "Z"
+ else
+ local o = math.abs(d.offset)
+ s ..= (if d.offset < 0 then "-" else "+") .. p2(o // 60) .. ":" .. p2(o % 60)
+ end
+ end
+ end
+ return s
+end
+DateMeta.__tostring = fmtDate
+DateMeta.__eq = function(a: any, b: any): boolean
+ return fmtDate(a) == fmtDate(b) and a.kind == b.kind
+end
+local DateLib = {}
+-- days since 1970-01-01 of a civil date (proleptic Gregorian; Howard Hinnant's algorithm)
+local function daysFromCivil(y: number, m: number, d: number): number
+ y = if m <= 2 then y - 1 else y
+ local era = (if y >= 0 then y else y - 399) // 400
+ local yoe = y - era * 400
+ local mp = (m + 9) % 12
+ local doy = (153 * mp + 2) // 5 + d - 1
+ local doe = yoe * 365 + yoe // 4 - yoe // 100 + doy
+ return era * 146097 + doe - 719468
+end
+local function civilFromDays(z: number): (number, number, number)
+ z += 719468
+ local era = (if z >= 0 then z else z - 146096) // 146097
+ local doe = z - era * 146097
+ local yoe = (doe - doe // 1460 + doe // 36524 - doe // 146096) // 365
+ local y = yoe + era * 400
+ local doy = doe - (365 * yoe + yoe // 4 - yoe // 100)
+ local mp = (5 * doy + 2) // 153
+ local d = doy - (153 * mp + 2) // 5 + 1
+ local m = if mp < 10 then mp + 3 else mp - 9
+ return (if m <= 2 then y + 1 else y), m, d
+end
+local MDAYS = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
+-- new(fields) -> Date (kind inferred from the fields present when not given)
+function DateLib.new(f: { [string]: any }): Date
+ local d: any = {}
+ for k, v in f do
+ d[k] = v
+ end
+ if d.kind == nil then
+ d.kind = if d.year and d.hour then (if d.offset then "datetime" else "datetime-local")
+ elseif d.year then "date-local"
+ else "time-local"
+ end
+ return setmetatable(d, DateMeta) :: any
+end
+-- is(v) -> true for Dates
+function DateLib.is(v: any): boolean
+ return type(v) == "table" and getmetatable(v) == DateMeta
+end
+-- valid(d) -> true when the fields are in range (month 1..12, the day exists in that month, hour < 24, ...)
+function DateLib.valid(d: Date): boolean
+ if d.year then
+ local y, m, dd = d.year, d.month or 0, d.day or 0
+ if y < 0 or y > 9999 or m < 1 or m > 12 or dd < 1 or dd > MDAYS[m] then
+ return false
+ end
+ if m == 2 and dd == 29 and not (y % 4 == 0 and (y % 100 ~= 0 or y % 400 == 0)) then
+ return false
+ end
+ end
+ if d.hour then
+ if d.hour > 23 or (d.minute or 0) > 59 or (d.second or 0) > 60 then
+ return false
+ end
+ end
+ if d.offset and math.abs(d.offset) >= 24 * 60 then
+ return false
+ end
+ return true
+end
+-- parse(s) -> Date | nil: RFC 3339 / ISO 8601 date-times and their TOML partial forms ("1979-05-27",
+-- "07:32:00.999", "1979-05-27 07:32:00Z", lower-case t / z accepted); out-of-range fields return nil
+function DateLib.parse(s: string): Date?
+ local d: any = {}
+ local rest = s
+ local y, mo, dd, r1 = string.match(rest, "^(%d%d%d%d)%-(%d%d)%-(%d%d)(.*)$")
+ if y then
+ d.year, d.month, d.day = tonumber(y), tonumber(mo), tonumber(dd)
+ rest = r1
+ if rest == "" then
+ return if DateLib.valid(d) then DateLib.new(d) else nil
+ end
+ local sep = string.sub(rest, 1, 1)
+ if sep ~= "T" and sep ~= "t" and sep ~= " " then
+ return nil
+ end
+ rest = string.sub(rest, 2)
+ end
+ local h, mi, r2 = string.match(rest, "^(%d%d):(%d%d)(.*)$")
+ if not h then
+ return nil
+ end
+ d.hour, d.minute = tonumber(h), tonumber(mi)
+ rest = r2
+ local sec, r3 = string.match(rest, "^:(%d%d)(.*)$")
+ if not sec then
+ return nil
+ end
+ d.second = tonumber(sec)
+ rest = r3
+ local frac, r4 = string.match(rest, "^%.(%d+)(.*)$")
+ if frac then
+ d.nanosecond = tonumber(string.sub(frac .. "000000000", 1, 9))
+ rest = r4
+ else
+ d.nanosecond = 0
+ end
+ if rest ~= "" then
+ if not d.year then
+ return nil
+ end
+ if rest == "Z" or rest == "z" then
+ d.offset = 0
+ else
+ local sign, oh, om = string.match(rest, "^([%+%-])(%d%d):(%d%d)$")
+ if not sign then
+ return nil
+ end
+ local oh_n, om_n = tonumber(oh) :: number, tonumber(om) :: number
+ if oh_n > 23 or om_n > 59 then
+ return nil
+ end
+ d.offset = (oh_n * 60 + om_n) * (if sign == "-" then -1 else 1)
+ end
+ end
+ return if DateLib.valid(d) then DateLib.new(d) else nil
+end
+-- toUnix(d) -> seconds since 1970-01-01T00:00:00Z (fractional; local times are taken as UTC)
+function DateLib.toUnix(d: Date): number
+ local days = if d.year then daysFromCivil(d.year, d.month or 1, d.day or 1) else 0
+ local s = days * 86400 + (d.hour or 0) * 3600 + (d.minute or 0) * 60 + (d.second or 0) - (d.offset or 0) * 60
+ return s + (d.nanosecond or 0) / 1e9
+end
+-- fromUnix(seconds, offset?) -> a "datetime" Date (offset in minutes, default 0 = UTC)
+function DateLib.fromUnix(t: number, offset: number?): Date
+ local off = offset or 0
+ local whole = math.floor(t)
+ local ns = math.floor((t - whole) * 1e9 + 0.5)
+ if ns >= 1e9 then
+ whole += 1
+ ns -= 1e9
+ end
+ local lt = whole + off * 60
+ local days = lt // 86400
+ local secs = lt - days * 86400
+ local y, m, dd = civilFromDays(days)
+ return DateLib.new({
+ kind = "datetime",
+ year = y,
+ month = m,
+ day = dd,
+ hour = secs // 3600,
+ minute = (secs // 60) % 60,
+ second = secs % 60,
+ nanosecond = ns,
+ offset = off,
+ })
+end
+Types.Date = table.freeze(DateLib)
+
+-- XML: an element, or (name starting with "#") a "#document" / "#comment" / "#cdata" / "#pi" / "#doctype" node with
+-- its content in text. attrs is a Types.object (attribute order kept). Text children are plain strings.
+export type XmlNode = {
+ name: string,
+ attrs: { [string]: string },
+ children: { XmlNode | string },
+ parent: XmlNode?,
+ text: string?, -- "#comment" / "#cdata" / "#pi" (the data after the target) / "#doctype" content
+ target: string?, -- "#pi": the target
+ ns: string?, -- the namespace URI (opts.namespaces)
+ [string]: any,
+}
-- ------------------------------------------------------------------------------------------------ Vector
export type Paint = { type: "color", color: { number } } | { type: "linear" | "radial", stops: { { number } }, [string]: any }
@@ -376,24 +911,40 @@ end
Types.Vector = Vector
-- ------------------------------------------------------------------------------------------------ Layered (PSD, Aseprite)
-export type Layer = { name: string, image: Image, x: number, y: number, opacity: number, blend: string, visible: boolean }
+-- blend: a codecs/Blend mode name ("normal", "multiply", ...; groups also "passThrough"). Optional: children (a group:
+-- its layers bottom to top; its image is 0 x 0), clip (clipped to the alpha of the layer below), mask (a grey mask in
+-- canvas coordinates; outside its rectangle the mask is `default`).
+export type LayerMask = { image: Image, x: number, y: number, default: number, disabled: boolean? }
+export type Layer = { name: string, image: Image, x: number, y: number, opacity: number, blend: string, visible: boolean, children: { Layer }?, clip: boolean?, mask: LayerMask? }
export type Layered = {
kind: "layered",
width: number,
height: number,
- layers: { Layer }, -- bottom to top
- frames: { { layers: { Layer }, delay: number } }?,
+ layers: { Layer }, -- bottom to top (a tree: groups have children); animations: frame 1's layers
+ frames: { { layers: { Layer }, delay: number } }?, -- animations (Aseprite): every frame's layers, delay in seconds
meta: { [string]: any },
}
local Layered = {}
function Layered.new(width: number, height: number): Layered
return { kind = "layered", width = width, height = height, layers = {}, frames = nil, meta = {} }
end
+-- layer(name, image, x?, y?) -> a visible normal layer at full opacity
+function Layered.layer(name: string, image: Image, x: number?, y: number?): Layer
+ return { name = name, image = image, x = x or 0, y = y or 0, opacity = 1, blend = "normal", visible = true }
+end
+-- group(name, children) -> a pass-through group layer
+function Layered.group(name: string, children: { Layer }): Layer
+ return { name = name, image = Image.new(0, 0), x = 0, y = 0, opacity = 1, blend = "passThrough", visible = true, children = children }
+end
Types.Layered = Layered
-- ------------------------------------------------------------------------------------------------ TileMap (Tiled)
-export type Tileset = { name: string, firstGid: number, tileWidth: number, tileHeight: number, columns: number, count: number, image: Image?, source: string? }
-export type TileLayer = { name: string, type: "tiles" | "objects" | "image" | "group", width: number?, height: number?, data: { number }?, objects: { any }?, visible: boolean, opacity: number, properties: { [string]: any } }
+-- gids are Tiled's: 0 = empty, the tile's firstGid-relative index, flip / rotation flags in the top bits (kept).
+-- Tilesets keep their image as a reference (imageSource: the path as written; image: an Image only if a caller
+-- loads it). Extra Tiled fields sit next to these (offsetX / offsetY, parallax, tintColor, class, chunks of infinite
+-- maps, objects' shapes, per-tile data, ...: see vector/tiled).
+export type Tileset = { name: string, firstGid: number, tileWidth: number, tileHeight: number, columns: number, count: number, image: Image?, source: string?, [string]: any }
+export type TileLayer = { name: string, type: "tiles" | "objects" | "image" | "group", width: number?, height: number?, data: { number }?, objects: { any }?, visible: boolean, opacity: number, properties: { [string]: any }, [string]: any }
export type TileMap = {
kind: "tilemap",
width: number,
@@ -405,7 +956,13 @@ export type TileMap = {
layers: { TileLayer },
properties: { [string]: any },
meta: { [string]: any },
+ [string]: any,
}
+local TileMap = {}
+function TileMap.new(width: number, height: number, tileWidth: number, tileHeight: number): TileMap
+ return { kind = "tilemap", width = width, height = height, tileWidth = tileWidth, tileHeight = tileHeight, orientation = "orthogonal", tilesets = {}, layers = {}, properties = {}, meta = {} }
+end
+Types.TileMap = TileMap
-- ------------------------------------------------------------------------------------------------ Subtitles
export type Cue = { start: number, stop: number, text: string, style: string?, id: string?, [string]: any } -- seconds
diff --git a/src/Formats/archive/7z/Header.luau b/src/Formats/archive/7z/Header.luau
new file mode 100644
index 0000000..c85accc
--- /dev/null
+++ b/src/Formats/archive/7z/Header.luau
@@ -0,0 +1,542 @@
+--!strict
+-- archive/7z/Header: the 7z header parser (7zFormat.txt from the LZMA SDK / 7-Zip, Igor Pavlov, public domain):
+-- streams info (pack info, folders with their coders and bind pairs, substreams), files info (names, empty streams /
+-- files, anti items, times, attributes). Not --!native: a parse failure raises an Err value that parse() catches and
+-- returns; any other error is a bug and propagates (the tests' fuzz pass sees it).
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+
+local Header = {}
+
+export type Coder = { id: string, numIn: number, numOut: number, props: buffer }
+export type Folder = {
+ coders: { Coder },
+ bindPairs: { { inIndex: number, outIndex: number } },
+ packed: { number }, -- in-stream index of each packed stream
+ unpackSizes: { number }, -- per out stream
+ crc: number?,
+ firstPack: number, -- index of the folder's first pack stream (0-based)
+ numSub: number, -- substreams (files) in the folder
+}
+export type Streams = {
+ packPos: number,
+ packSizes: { number },
+ folders: { Folder },
+ subSizes: { number }, -- every substream, folder by folder
+ subCrcs: { [number]: number }, -- 1-based substream index -> CRC
+}
+export type File = {
+ name: string,
+ emptyStream: boolean,
+ emptyFile: boolean,
+ anti: boolean,
+ mtime: number?,
+ attributes: number?,
+}
+export type Parsed = { streams: Streams?, files: { File }, encoded: Streams? }
+
+local K = {
+ End = 0x00,
+ Header = 0x01,
+ ArchiveProperties = 0x02,
+ AdditionalStreamsInfo = 0x03,
+ MainStreamsInfo = 0x04,
+ FilesInfo = 0x05,
+ PackInfo = 0x06,
+ UnPackInfo = 0x07,
+ SubStreamsInfo = 0x08,
+ Size = 0x09,
+ CRC = 0x0A,
+ Folder = 0x0B,
+ CodersUnPackSize = 0x0C,
+ NumUnPackStream = 0x0D,
+ EmptyStream = 0x0E,
+ EmptyFile = 0x0F,
+ Anti = 0x10,
+ Name = 0x11,
+ MTime = 0x14,
+ WinAttributes = 0x15,
+ EncodedHeader = 0x17,
+ Dummy = 0x19,
+}
+Header.K = K
+
+local Fail = {}
+
+local function bad(r: Bytes.Reader, msg: string, code: string?): never
+ error(setmetatable({ err = Err.new(code or Err.CORRUPT, msg, r.pos) }, Fail), 0)
+end
+
+local function check(r: Bytes.Reader)
+ if r.err then
+ error(setmetatable({ err = r.err }, Fail), 0)
+ end
+end
+
+local function byte(r: Bytes.Reader): number
+ local v = r:u8()
+ check(r)
+ return v
+end
+
+-- NUMBER: the first byte's leading 1 bits count the extra (little-endian) bytes
+local function number(r: Bytes.Reader): number
+ local first = byte(r)
+ local mask = 0x80
+ local value = 0
+ for i = 0, 7 do
+ if bit32.band(first, mask) == 0 then
+ local high = bit32.band(first, mask - 1)
+ return value + high * 2 ^ (8 * i)
+ end
+ value += byte(r) * 2 ^ (8 * i)
+ mask = bit32.rshift(mask, 1)
+ end
+ return value
+end
+
+-- a count bounded by the bytes left (every counted item takes at least `min` bytes)
+local function count(r: Bytes.Reader, min: number?): number
+ local n = number(r)
+ if n * (min or 1) > r:remaining() + 1 then
+ bad(r, "count " .. n .. " is larger than the header")
+ end
+ return n
+end
+
+local function bits(r: Bytes.Reader, n: number): { boolean }
+ local out = table.create(n, false)
+ local cur, mask = 0, 0
+ for i = 1, n do
+ if mask == 0 then
+ cur = byte(r)
+ mask = 0x80
+ end
+ out[i] = bit32.band(cur, mask) ~= 0
+ mask = bit32.rshift(mask, 1)
+ end
+ return out
+end
+
+-- bits preceded by an "all defined" byte
+local function defined(r: Bytes.Reader, n: number): { boolean }
+ if byte(r) ~= 0 then
+ return table.create(n, true)
+ end
+ return bits(r, n)
+end
+
+local function digests(r: Bytes.Reader, n: number): { [number]: number }
+ local def = defined(r, n)
+ local out = {}
+ for i = 1, n do
+ if def[i] then
+ out[i] = r:u32le()
+ end
+ end
+ check(r)
+ return out
+end
+
+local function packInfo(r: Bytes.Reader, s: Streams)
+ s.packPos = number(r)
+ local n = count(r)
+ while true do
+ local t = byte(r)
+ if t == K.End then
+ break
+ elseif t == K.Size then
+ for i = 1, n do
+ s.packSizes[i] = number(r)
+ end
+ elseif t == K.CRC then
+ digests(r, n)
+ else
+ bad(r, "unexpected property " .. t .. " in pack info")
+ end
+ end
+ if #s.packSizes ~= n then
+ bad(r, "missing pack sizes")
+ end
+end
+
+local function folder(r: Bytes.Reader): Folder
+ local ncoders = count(r)
+ if ncoders == 0 or ncoders > 64 then
+ bad(r, "bad coder count " .. ncoders)
+ end
+ local f: Folder = { coders = {}, bindPairs = {}, packed = {}, unpackSizes = {}, crc = nil, firstPack = 0, numSub = 1 }
+ local totalIn, totalOut = 0, 0
+ for _ = 1, ncoders do
+ local flags = byte(r)
+ if bit32.band(flags, 0x80) ~= 0 then
+ bad(r, "alternative coder methods", Err.UNSUPPORTED)
+ end
+ local idSize = bit32.band(flags, 0x0F)
+ local id = r:string(idSize)
+ check(r)
+ local nin, nout = 1, 1
+ if bit32.band(flags, 0x10) ~= 0 then
+ nin, nout = number(r), number(r)
+ if nin > 64 or nout > 64 then
+ bad(r, "bad coder stream count")
+ end
+ end
+ local props = buffer.create(0)
+ if bit32.band(flags, 0x20) ~= 0 then
+ local n = count(r)
+ props = r:bytes(n)
+ check(r)
+ end
+ table.insert(f.coders, { id = id, numIn = nin, numOut = nout, props = props })
+ totalIn += nin
+ totalOut += nout
+ end
+ if totalOut == 0 then
+ bad(r, "a folder without output")
+ end
+ for _ = 1, totalOut - 1 do
+ local i, o = number(r), number(r)
+ table.insert(f.bindPairs, { inIndex = i, outIndex = o })
+ end
+ local npacked = totalIn - (totalOut - 1)
+ if npacked < 1 then
+ bad(r, "bad bind pairs")
+ end
+ if npacked == 1 then
+ for i = 0, totalIn - 1 do
+ local bound = false
+ for _, bp in f.bindPairs do
+ if bp.inIndex == i then
+ bound = true
+ end
+ end
+ if not bound then
+ table.insert(f.packed, i)
+ break
+ end
+ end
+ if #f.packed ~= 1 then
+ bad(r, "no packed stream")
+ end
+ else
+ for _ = 1, npacked do
+ table.insert(f.packed, number(r))
+ end
+ end
+ return f
+end
+
+-- the folder's main out stream: the one no bind pair consumes
+function Header.mainOut(f: Folder): number?
+ local total = 0
+ for _, c in f.coders do
+ total += c.numOut
+ end
+ for o = 0, total - 1 do
+ local bound = false
+ for _, bp in f.bindPairs do
+ if bp.outIndex == o then
+ bound = true
+ end
+ end
+ if not bound then
+ return o
+ end
+ end
+ return nil
+end
+
+function Header.unpackSize(f: Folder): number
+ local m = Header.mainOut(f)
+ return if m then f.unpackSizes[m + 1] or 0 else 0
+end
+
+local function unpackInfo(r: Bytes.Reader, s: Streams)
+ if byte(r) ~= K.Folder then
+ bad(r, "expected the folder list")
+ end
+ local n = count(r)
+ if byte(r) ~= 0 then
+ bad(r, "external folders", Err.UNSUPPORTED)
+ end
+ for i = 1, n do
+ s.folders[i] = folder(r)
+ end
+ if byte(r) ~= K.CodersUnPackSize then
+ bad(r, "expected the coder unpack sizes")
+ end
+ for _, f in s.folders do
+ local total = 0
+ for _, c in f.coders do
+ total += c.numOut
+ end
+ for k = 1, total do
+ f.unpackSizes[k] = number(r)
+ end
+ end
+ while true do
+ local t = byte(r)
+ if t == K.End then
+ break
+ elseif t == K.CRC then
+ local d = digests(r, n)
+ for i = 1, n do
+ s.folders[i].crc = d[i]
+ end
+ else
+ bad(r, "unexpected property " .. t .. " in unpack info")
+ end
+ end
+end
+
+local function subStreamsInfo(r: Bytes.Reader, s: Streams)
+ local t = byte(r)
+ if t == K.NumUnPackStream then
+ for _, f in s.folders do
+ f.numSub = count(r, 0)
+ end
+ t = byte(r)
+ end
+ local sizes = s.subSizes
+ if t == K.Size then
+ for _, f in s.folders do
+ if f.numSub > 0 then
+ local sum = 0
+ for _ = 1, f.numSub - 1 do
+ local v = number(r)
+ sum += v
+ table.insert(sizes, v)
+ end
+ local total = Header.unpackSize(f)
+ if sum > total then
+ bad(r, "substream sizes exceed the folder")
+ end
+ table.insert(sizes, total - sum)
+ end
+ end
+ t = byte(r)
+ else
+ for _, f in s.folders do
+ if f.numSub > 1 then
+ bad(r, "missing substream sizes")
+ elseif f.numSub == 1 then
+ table.insert(sizes, Header.unpackSize(f))
+ end
+ end
+ end
+ -- CRCs for the streams whose folder CRC does not already cover them
+ local unknown = 0
+ for _, f in s.folders do
+ if not (f.numSub == 1 and f.crc) then
+ unknown += f.numSub
+ end
+ end
+ while t ~= K.End do
+ if t == K.CRC then
+ local d = digests(r, unknown)
+ local k, si = 1, 1
+ for _, f in s.folders do
+ if f.numSub == 1 and f.crc then
+ s.subCrcs[si] = f.crc
+ si += 1
+ else
+ for _ = 1, f.numSub do
+ s.subCrcs[si] = d[k]
+ k += 1
+ si += 1
+ end
+ end
+ end
+ else
+ bad(r, "unexpected property " .. t .. " in substreams info")
+ end
+ t = byte(r)
+ end
+end
+
+local function streamsInfo(r: Bytes.Reader): Streams
+ local s: Streams = { packPos = 0, packSizes = {}, folders = {}, subSizes = {}, subCrcs = {} }
+ local sawSub = false
+ while true do
+ local t = byte(r)
+ if t == K.End then
+ break
+ elseif t == K.PackInfo then
+ packInfo(r, s)
+ elseif t == K.UnPackInfo then
+ unpackInfo(r, s)
+ elseif t == K.SubStreamsInfo then
+ subStreamsInfo(r, s)
+ sawSub = true
+ else
+ bad(r, "unexpected property " .. t .. " in streams info")
+ end
+ end
+ if not sawSub then
+ for i, f in s.folders do
+ f.numSub = 1
+ table.insert(s.subSizes, Header.unpackSize(f))
+ if f.crc then
+ s.subCrcs[i] = f.crc
+ end
+ end
+ end
+ local p = 0
+ for _, f in s.folders do
+ f.firstPack = p
+ p += #f.packed
+ end
+ if p > #s.packSizes then
+ bad(r, "folders use more pack streams than exist")
+ end
+ return s
+end
+
+local function utf16(b: buffer, o: number, n: number): string
+ local out = {}
+ local i = 0
+ while i + 1 < n do
+ local u = buffer.readu16(b, o + i)
+ i += 2
+ if u >= 0xD800 and u < 0xDC00 and i + 1 < n then
+ local lo = buffer.readu16(b, o + i)
+ if lo >= 0xDC00 and lo < 0xE000 then
+ u = 0x10000 + (u - 0xD800) * 1024 + (lo - 0xDC00)
+ i += 2
+ end
+ end
+ table.insert(out, utf8.char(u))
+ end
+ return table.concat(out)
+end
+
+local function filesInfo(r: Bytes.Reader): { File }
+ local n = count(r, 0)
+ if n > 1000000 then
+ bad(r, "too many files", Err.LIMIT)
+ end
+ local files: { File } = table.create(n)
+ for i = 1, n do
+ files[i] = { name = "", emptyStream = false, emptyFile = false, anti = false }
+ end
+ local empties = {}
+ while true do
+ local t = byte(r)
+ if t == K.End then
+ break
+ end
+ local size = number(r)
+ if size > r:remaining() then
+ bad(r, "file property past the header")
+ end
+ local pr = r:slice(size)
+ check(r)
+ if t == K.EmptyStream then
+ local v = bits(pr, n)
+ empties = {}
+ for i = 1, n do
+ files[i].emptyStream = v[i]
+ if v[i] then
+ table.insert(empties, i)
+ end
+ end
+ elseif t == K.EmptyFile or t == K.Anti then
+ local v = bits(pr, #empties)
+ for k, i in empties do
+ if t == K.EmptyFile then
+ files[i].emptyFile = v[k]
+ else
+ files[i].anti = v[k]
+ end
+ end
+ elseif t == K.Name then
+ if byte(pr) ~= 0 then
+ bad(pr, "external names", Err.UNSUPPORTED)
+ end
+ local b = pr.buf
+ local p = pr.pos
+ for i = 1, n do
+ local q = p
+ while q + 1 < pr.limit and buffer.readu16(b, q) ~= 0 do
+ q += 2
+ end
+ if q + 1 >= pr.limit then
+ bad(pr, "unterminated name")
+ end
+ files[i].name = utf16(b, p, q - p)
+ p = q + 2
+ end
+ elseif t == K.MTime or t == K.WinAttributes then
+ local def = defined(pr, n)
+ if byte(pr) ~= 0 then
+ bad(pr, "external file properties", Err.UNSUPPORTED)
+ end
+ for i = 1, n do
+ if def[i] then
+ if t == K.MTime then
+ local ft = pr:u64le()
+ files[i].mtime = math.floor(ft / 1e7 - 11644473600)
+ else
+ files[i].attributes = pr:u32le()
+ end
+ end
+ end
+ check(pr)
+ end
+ -- other properties (CTime, ATime, StartPos, Dummy, ...) are skipped
+ end
+ return files
+end
+
+local function header(r: Bytes.Reader): Parsed
+ local p: Parsed = { streams = nil, files = {}, encoded = nil }
+ while true do
+ local t = byte(r)
+ if t == K.End then
+ break
+ elseif t == K.ArchiveProperties then
+ while true do
+ local pt = byte(r)
+ if pt == 0 then
+ break
+ end
+ r:skip(number(r))
+ check(r)
+ end
+ elseif t == K.AdditionalStreamsInfo then
+ streamsInfo(r)
+ elseif t == K.MainStreamsInfo then
+ p.streams = streamsInfo(r)
+ elseif t == K.FilesInfo then
+ p.files = filesInfo(r)
+ else
+ bad(r, "unexpected property " .. t .. " in the header")
+ end
+ end
+ return p
+end
+
+-- parse(buf, offset, length) -> Parsed | nil, Err. An encoded header returns { encoded = streams } for the caller to
+-- decode and parse again.
+function Header.parse(b: buffer, o: number, n: number): (Parsed?, Err.Err?)
+ local r = Bytes.reader(b, o, n)
+ local ok, res = pcall(function(): Parsed
+ local t = byte(r)
+ if t == K.Header then
+ return header(r)
+ elseif t == K.EncodedHeader then
+ return { streams = nil, files = {}, encoded = streamsInfo(r) }
+ end
+ return bad(r, "bad header type " .. t)
+ end)
+ if ok then
+ return res, nil
+ end
+ if type(res) == "table" and getmetatable(res :: any) == Fail then
+ return nil, (res :: any).err
+ end
+ error(res, 0)
+end
+
+return Header
diff --git a/src/Formats/archive/7z/init.luau b/src/Formats/archive/7z/init.luau
new file mode 100644
index 0000000..39097fd
--- /dev/null
+++ b/src/Formats/archive/7z/init.luau
@@ -0,0 +1,387 @@
+--!strict
+-- archive/7z: 7z archives (7zFormat.txt from the LZMA SDK, Igor Pavlov, public domain), read as an Archive whose
+-- entries decode lazily (a folder is decoded once on first read, then sliced). Supports: plain and encoded (compressed)
+-- headers, solid and non-solid folders, coder chains of copy / LZMA / LZMA2 / Deflate / BZip2 /
+-- Zstd (7-Zip-zstd's plain frames; untested: stock 7-Zip cannot write it) with BCJ (x86, PowerPC, ARM,
+-- ARM-Thumb, SPARC, ARM64) and delta filters, empty files and directories, anti items (skipped), UTF-16 names, mtimes,
+-- Windows / Unix attributes, folder and file CRC-32s (verified on read).
+-- Not supported (Err.UNSUPPORTED naming the method, on read of the affected entries): PPMd, BCJ2, Deflate64, other
+-- plug-in codecs (Brotli, LZ4, ...), AES encryption, multi-volume archives, external header references; writing.
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Crc32 = require("@formats/core/Crc32")
+local Types = require("@formats/Types")
+local Lzma = require("@formats/codecs/Lzma")
+local Deflate = require("@formats/codecs/Deflate")
+local Bzip2 = require("@formats/codecs/Bzip2")
+local Zstd = require("@formats/codecs/Zstd")
+local Archive = require("@formats/containers/Archive")
+local Header = require("@formats/archive/7z/Header")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local SevenZip = {
+ name = "7z",
+ category = "archive",
+ extensions = { "7z" },
+ mime = { "application/x-7z-compressed" },
+ deps = { "core/Err", "core/Bytes", "core/Crc32", "Types", "codecs/Lzma", "codecs/Deflate", "codecs/Bzip2", "codecs/Zstd", "containers/Archive" },
+ caps = { decode = true, encode = false, methods = { "copy", "lzma", "lzma2", "deflate", "bcj", "delta" }, encrypted = false },
+}
+
+export type DecodeOptions = {
+ maxBytes: number?, -- refuse a folder (solid block) or header that decodes to more than this (default 2^30)
+ checkCrc: boolean?, -- verify CRC-32s on read (default true)
+}
+
+-- ------------------------------------------------------------------------------------------------ constants
+local MAGIC = "7z\188\175\39\28"
+
+-- method id -> xz filter id (BCJ / delta)
+local FILTERS: { [string]: number } = {
+ ["\3\3\1\3"] = 0x04, -- x86
+ ["\3\3\2\5"] = 0x05, -- PowerPC
+ ["\3\3\5\1"] = 0x07, -- ARM
+ ["\3\3\7\1"] = 0x08, -- ARM-Thumb
+ ["\3\3\8\5"] = 0x09, -- SPARC
+ ["\10"] = 0x0A, -- ARM64
+ ["\3"] = 0x03, -- delta
+}
+local NAMES: { [string]: string } = {
+ ["\0"] = "copy",
+ ["\3\1\1"] = "lzma",
+ ["\33"] = "lzma2",
+ ["\4\1\8"] = "deflate",
+ ["\4\1\9"] = "deflate64",
+ ["\4\2\2"] = "bzip2",
+ ["\3\4\1"] = "ppmd",
+ ["\3\3\1\27"] = "bcj2",
+ ["\6\241\7\1"] = "aes",
+ ["\4\247\17\1"] = "zstd",
+ ["\4\247\17\2"] = "brotli",
+ ["\3\3\1\3"] = "bcj",
+ ["\3\3\2\5"] = "ppc",
+ ["\3\3\5\1"] = "arm",
+ ["\3\3\7\1"] = "armt",
+ ["\3\3\8\5"] = "sparc",
+ ["\10"] = "arm64",
+ ["\3"] = "delta",
+}
+
+local function methodName(id: string): string
+ local n = NAMES[id]
+ if n then
+ return n
+ end
+ local hex = {}
+ for i = 1, #id do
+ table.insert(hex, string.format("%02x", string.byte(id, i)))
+ end
+ return "method " .. table.concat(hex)
+end
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function SevenZip.sniff(r: Bytes.Reader): number
+ return if r:peek(6) == MAGIC then 1 else 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+-- folder decoding: evaluate the coder graph from the main out stream; every coder here has one in and one out stream
+type Ctx = { buf: buffer, base: number, limit: number, maxBytes: number }
+
+local function packStart(ctx: Ctx, s: Header.Streams, index: number): number
+ local p = ctx.base + 32 + s.packPos
+ for i = 1, index do
+ p += s.packSizes[i]
+ end
+ return p
+end
+
+local function decodeFolder(ctx: Ctx, s: Header.Streams, f: Header.Folder): (buffer?, Err.Err?)
+ -- coder -> first in / out stream index
+ local inBase, outBase = {}, {}
+ local ni, no = 0, 0
+ for i, c in f.coders do
+ inBase[i], outBase[i] = ni, no
+ ni += c.numIn
+ no += c.numOut
+ end
+ local depth = 0
+ local function out(outIdx: number): (buffer?, Err.Err?)
+ depth += 1
+ if depth > 32 then
+ return nil, Err.new(Err.CORRUPT, "coder graph too deep")
+ end
+ local ci
+ for i, c in f.coders do
+ if outIdx >= outBase[i] and outIdx < outBase[i] + c.numOut then
+ ci = i
+ end
+ end
+ if not ci then
+ return nil, Err.new(Err.CORRUPT, "bad bind pair")
+ end
+ local c = f.coders[ci]
+ if c.numIn ~= 1 or c.numOut ~= 1 then
+ return nil, Err.new(Err.UNSUPPORTED, methodName(c.id) .. " (multi-stream coder)")
+ end
+ local size = f.unpackSizes[outIdx + 1] or 0
+ if size > ctx.maxBytes then
+ return nil, Err.new(Err.LIMIT, string.format("folder of %d bytes is over maxBytes", size))
+ end
+ -- the coder's input: another coder's output, or a packed stream
+ local inIdx = inBase[ci]
+ local src: buffer, so: number, sl: number
+ local bound = nil
+ for _, bp in f.bindPairs do
+ if bp.inIndex == inIdx then
+ bound = bp.outIndex
+ end
+ end
+ if bound then
+ local b, e = out(bound)
+ if not b then
+ return nil, e
+ end
+ src, so, sl = b, 0, buffer.len(b)
+ else
+ local k = table.find(f.packed, inIdx)
+ if not k then
+ return nil, Err.new(Err.CORRUPT, "unbound coder input")
+ end
+ local pi = f.firstPack + k - 1
+ if pi >= #s.packSizes then
+ return nil, Err.new(Err.CORRUPT, "missing pack stream")
+ end
+ so = packStart(ctx, s, pi)
+ sl = s.packSizes[pi + 1]
+ if so + sl > ctx.limit or so < ctx.base then
+ return nil, Err.new(Err.TRUNCATED, "pack stream past the end of the archive", so)
+ end
+ src = ctx.buf
+ end
+ local id = c.id
+ local opts = { maxBytes = ctx.maxBytes }
+ if id == "\0" then
+ if sl < size then
+ return nil, Err.new(Err.TRUNCATED, "short stored stream")
+ end
+ local b = buffer.create(size)
+ buffer.copy(b, 0, src, so, size)
+ return b
+ elseif id == "\3\1\1" then
+ if buffer.len(c.props) < 5 then
+ return nil, Err.new(Err.CORRUPT, "bad LZMA properties")
+ end
+ local b, e = Lzma.lzma(src, so, sl, c.props, size, opts)
+ return b, if b then nil else e
+ elseif id == "\33" then
+ local b, e = Lzma.lzma2(src, so, sl, nil, size, opts)
+ return b, if b then nil else e
+ elseif id == "\4\1\8" then
+ local b, e = Deflate.inflate(src, so, sl, size)
+ return b, if b then nil else e
+ elseif id == "\4\2\2" or id == "\4\247\17\1" then -- BZip2, Zstd (7-Zip-zstd: plain zstd frames)
+ local b, e
+ if id == "\4\2\2" then
+ b, e = Bzip2.decompress(src, so, sl, opts)
+ else
+ b, e = Zstd.decompress(src, so, sl, opts)
+ end
+ if not b then
+ return nil, e
+ end
+ if buffer.len(b) ~= size then
+ return nil, Err.new(Err.CORRUPT, methodName(id) .. " stream decodes to the wrong size")
+ end
+ return b
+ elseif FILTERS[id] then
+ if sl ~= size then
+ return nil, Err.new(Err.CORRUPT, "filter size mismatch")
+ end
+ local b = buffer.create(size)
+ buffer.copy(b, 0, src, so, size)
+ local ok, e = Lzma.filter(FILTERS[id], b, 0, size, c.props)
+ if not ok then
+ return nil, e
+ end
+ return b
+ end
+ return nil, Err.new(Err.UNSUPPORTED, methodName(id) .. " is not supported")
+ end
+ local main = Header.mainOut(f)
+ if not main then
+ return nil, Err.new(Err.CORRUPT, "folder without a main output")
+ end
+ return out(main)
+end
+
+local function folderMethod(f: Header.Folder): string
+ local names = {}
+ for _, c in f.coders do
+ table.insert(names, methodName(c.id))
+ end
+ return table.concat(names, "+")
+end
+
+function SevenZip.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive?, Err.Err?)
+ local o = opts or {}
+ local maxBytes = if type(o.maxBytes) == "number" then o.maxBytes else 2 ^ 30
+ local checkCrc = o.checkCrc ~= false
+ local b, base, limit = r.buf, r.base, r.limit
+ if limit - base < 32 then
+ return nil, Err.new(Err.TRUNCATED, "truncated signature header", base)
+ end
+ if buffer.readstring(b, base, 6) ~= MAGIC then
+ return nil, Err.new(Err.CORRUPT, "bad 7z signature", base)
+ end
+ if buffer.readu8(b, base + 6) ~= 0 then
+ return nil, Err.new(Err.UNSUPPORTED, "7z major version " .. buffer.readu8(b, base + 6), base + 6)
+ end
+ if Crc32.raw(b, base + 12, 20) ~= buffer.readu32(b, base + 8) then
+ return nil, Err.new(Err.CHECKSUM, "start header CRC-32 mismatch", base + 8)
+ end
+ local hr = Bytes.reader(b, base + 12, 20)
+ local nextOff, nextSize, nextCrc = hr:u64le(), hr:u64le(), hr:u32le()
+ local ctx: Ctx = { buf = b, base = base, limit = limit, maxBytes = maxBytes }
+ local a = Archive.new("7z")
+ if nextSize == 0 then
+ return a, nil -- an empty archive
+ end
+ local ho = base + 32 + nextOff
+ if nextOff < 0 or ho + nextSize > limit then
+ return nil, Err.new(Err.TRUNCATED, "header past the end of the archive", base + 12)
+ end
+ if Crc32.raw(b, ho, nextSize) ~= nextCrc then
+ return nil, Err.new(Err.CHECKSUM, "header CRC-32 mismatch", ho)
+ end
+ local hbuf, hoff, hlen = b, ho, nextSize
+ local parsed
+ for _ = 1, 4 do
+ local p, perr = Header.parse(hbuf, hoff, hlen)
+ if not p then
+ return nil, perr
+ end
+ if not p.encoded then
+ parsed = p
+ break
+ end
+ -- an encoded header: decode folder 1 of its streams, then parse again
+ local es = p.encoded
+ local f = es.folders[1]
+ if not f then
+ return nil, Err.new(Err.CORRUPT, "encoded header without a folder")
+ end
+ local hb, herr = decodeFolder(ctx, es, f)
+ if not hb then
+ return nil, herr
+ end
+ if f.crc and Crc32.raw(hb, 0, buffer.len(hb)) ~= f.crc then
+ return nil, Err.new(Err.CHECKSUM, "encoded header CRC-32 mismatch")
+ end
+ hbuf, hoff, hlen = hb, 0, buffer.len(hb)
+ end
+ if not parsed then
+ return nil, Err.new(Err.CORRUPT, "nested encoded headers")
+ end
+ local s = parsed.streams or { packPos = 0, packSizes = {}, folders = {}, subSizes = {}, subCrcs = {} }
+ a.meta.folders = #s.folders
+ a.meta.solid = false
+ -- folder caches and the substream -> folder map
+ local cache: { [number]: buffer } = {}
+ local subFolder, subOffset = {}, {}
+ do
+ local si = 1
+ for fi, f in s.folders do
+ if f.numSub > 1 then
+ a.meta.solid = true
+ end
+ local off = 0
+ for _ = 1, f.numSub do
+ subFolder[si], subOffset[si] = fi, off
+ off += s.subSizes[si] or 0
+ si += 1
+ end
+ if off > Header.unpackSize(f) then
+ return nil, Err.new(Err.CORRUPT, "substreams exceed their folder")
+ end
+ end
+ end
+ local function folderData(fi: number): (buffer?, Err.Err?)
+ local c = cache[fi]
+ if c then
+ return c
+ end
+ local f = s.folders[fi]
+ local d, e = decodeFolder(ctx, s, f)
+ if not d then
+ return nil, e
+ end
+ if checkCrc and f.crc and Crc32.raw(d, 0, buffer.len(d)) ~= f.crc then
+ return nil, Err.new(Err.CHECKSUM, "folder CRC-32 mismatch")
+ end
+ cache[fi] = d
+ return d
+ end
+ local si = 0
+ for _, file in parsed.files do
+ if file.anti then
+ continue
+ end
+ local attr = file.attributes
+ local isDir = file.emptyStream and not file.emptyFile
+ if attr and bit32.band(attr, 0x10) ~= 0 then
+ isDir = true
+ end
+ local mode = if attr and bit32.band(attr, 0x8000) ~= 0 then bit32.rshift(attr, 16) else nil
+ local e: Archive.Entry = {
+ name = file.name,
+ size = 0,
+ dir = isDir,
+ mtime = file.mtime,
+ attributes = attr,
+ mode = mode,
+ }
+ if not file.emptyStream then
+ si += 1
+ local idx = si
+ local fi = subFolder[idx]
+ if not fi then
+ return nil, Err.new(Err.CORRUPT, "more files than streams")
+ end
+ local size = s.subSizes[idx]
+ e.size = size
+ e.method = folderMethod(s.folders[fi])
+ if s.folders[fi].numSub == 1 then
+ local pk = 0
+ for k = 1, #s.folders[fi].packed do
+ pk += s.packSizes[s.folders[fi].firstPack + k] or 0
+ end
+ e.compressedSize = pk
+ end
+ e.crc = s.subCrcs[idx]
+ e.load = function(): (buffer?, Err.Err?)
+ local d, derr = folderData(fi)
+ if not d then
+ return nil, derr
+ end
+ local off = subOffset[idx]
+ if off + size > buffer.len(d) then
+ return nil, Err.new(Err.CORRUPT, "substream past its folder")
+ end
+ local out = buffer.create(size)
+ buffer.copy(out, 0, d, off, size)
+ local want = s.subCrcs[idx]
+ if checkCrc and want and Crc32.raw(out, 0, size) ~= want then
+ return nil, Err.new(Err.CHECKSUM, "CRC-32 mismatch in " .. file.name)
+ end
+ return out
+ end
+ end
+ Archive.put(a, e)
+ end
+ return a, nil
+end
+
+return SevenZip
diff --git a/src/Formats/archive/br/init.luau b/src/Formats/archive/br/init.luau
new file mode 100644
index 0000000..6949a02
--- /dev/null
+++ b/src/Formats/archive/br/init.luau
@@ -0,0 +1,76 @@
+--!strict
+-- archive/br: a Brotli (RFC 7932) stream as a single-entry archive (meta.stream: the api unwraps a .tar.br to the tar
+-- inside). Decoding through codecs/Brotli. The entry is named after opts.name without ".br" (else "data").
+-- Supports: read (eager decompression). Not supported: write (no Brotli compressor). Brotli has no magic number:
+-- sniff accepts only data that decodes cleanly (the whole stream for small files, a 64 KB prefix for big ones), at a
+-- low confidence, so the extension decides between candidates.
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Brotli = require("@formats/codecs/Brotli")
+local Archive = require("@formats/containers/Archive")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Br = {
+ name = "br",
+ category = "archive",
+ extensions = { "br" },
+ mime = { "application/x-brotli" },
+ deps = { "core/Err", "core/Bytes", "codecs/Brotli", "containers/Archive" },
+ caps = { decode = true, encode = false, stream = true },
+}
+
+export type DecodeOptions = {
+ name: string?, -- the file name (the api passes it): the entry is named after it
+ maxBytes: number?, -- refuse output larger than this (default 2^30)
+}
+
+-- ------------------------------------------------------------------------------------------------ constants
+local SNIFF_WHOLE = 262144 -- streams up to this size are decoded whole by sniff
+local SNIFF_PREFIX = 65536
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Br.sniff(r: Bytes.Reader): number
+ local n = r:remaining()
+ if n == 0 then
+ return 0
+ end
+ if n <= SNIFF_WHOLE then
+ local out, consumed = Brotli.decompress(r.buf, r.pos, n, { maxBytes = 2 ^ 26 })
+ if out and consumed == r.limit then
+ return if buffer.len(out) > 0 then 0.3 else 0.05
+ end
+ return 0
+ end
+ local _, err = Brotli.decompress(r.buf, r.pos, SNIFF_PREFIX, { maxBytes = 2 ^ 22 })
+ if err and (err.code == Err.TRUNCATED or err.code == Err.LIMIT) then
+ return 0.05
+ end
+ return 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+function Br.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
+ local n = r:remaining()
+ local out, consumed = Brotli.decompress(r.buf, r.pos, n, { maxBytes = opts and opts.maxBytes })
+ if not out then
+ local e: Err.Err = consumed
+ e.message = string.gsub(e.message, "^brotli: ", "")
+ return nil, e
+ end
+ local a = Archive.new("br")
+ a.meta.stream = true
+ a.meta.compressedSize = consumed - r.pos
+ Archive.put(a, {
+ name = Archive.streamName(opts, Br.extensions),
+ size = buffer.len(out),
+ compressedSize = consumed - r.pos,
+ method = "brotli",
+ dir = false,
+ data = out,
+ })
+ return a, nil
+end
+
+return Br
diff --git a/src/Formats/archive/bz2/init.luau b/src/Formats/archive/bz2/init.luau
new file mode 100644
index 0000000..7483ab0
--- /dev/null
+++ b/src/Formats/archive/bz2/init.luau
@@ -0,0 +1,63 @@
+--!strict
+-- archive/bz2: a .bz2 file as a single-stream archive: one entry, the decompressed data (codecs/Bzip2; concatenated
+-- streams are joined, as bzip2 -d does). The entry is named after the file without its .bz2 (".tbz2" -> ".tar"),
+-- else "data"; the api unwraps a .tar.bz2 into the tar inside (meta.stream). Read only.
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Archive = require("@formats/containers/Archive")
+local Bzip2 = require("@formats/codecs/Bzip2")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Bz2 = {
+ name = "bz2",
+ category = "archive",
+ extensions = { "bz2", "tbz2", "tbz" },
+ mime = { "application/x-bzip2" },
+ deps = { "core/Err", "core/Bytes", "containers/Archive", "codecs/Bzip2" },
+ caps = { decode = true, encode = false, stream = true },
+}
+
+export type DecodeOptions = {
+ maxBytes: number?, -- refuse larger output (default 2^30)
+ name: string?, -- the file name (the api passes it): names the entry
+}
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Bz2.sniff(r: Bytes.Reader): number
+ local h = r:peek(10)
+ if #h < 10 or string.sub(h, 1, 3) ~= "BZh" then
+ return 0
+ end
+ local lv = string.byte(h, 4)
+ if lv < 0x31 or lv > 0x39 then
+ return 0
+ end
+ local magic = string.sub(h, 5, 10)
+ if magic == "\x31\x41\x59\x26\x53\x59" or magic == "\x17\x72\x45\x38\x50\x90" then
+ return 1
+ end
+ return 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+function Bz2.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
+ local out, consumed = Bzip2.decompress(r.buf, r.base, r.limit - r.base, { maxBytes = opts and opts.maxBytes })
+ if not out then
+ return nil, consumed
+ end
+ local a = Archive.new("bz2")
+ a.meta.stream = true
+ Archive.put(a, {
+ name = Archive.streamName(opts, Bz2.extensions),
+ size = buffer.len(out),
+ compressedSize = consumed - r.base,
+ method = "bzip2",
+ dir = false,
+ data = out,
+ })
+ return a, nil
+end
+
+return Bz2
diff --git a/src/Formats/archive/gzip/init.luau b/src/Formats/archive/gzip/init.luau
new file mode 100644
index 0000000..38ddeca
--- /dev/null
+++ b/src/Formats/archive/gzip/init.luau
@@ -0,0 +1,187 @@
+--!strict
+-- archive/gzip: gzip files (RFC 1952) as a single-stream Archive: one entry, named after the header's FNAME (else the
+-- file name without .gz, else "data"), with the header's MTIME; concatenated members decode as one stream, as gzip -d
+-- does. Writing: an Archive with one entry (or a buffer / string) becomes one member with FNAME and MTIME; an Archive
+-- with several entries is written as a tar inside the gzip (a .tar.gz). The api unwraps a .tar.gz / .tgz on load (the
+-- inner tar, meta.compression = "gzip"). Deflate is codecs/Deflate. Not supported: FHCRC verification.
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Crc32 = require("@formats/core/Crc32")
+local Deflate = require("@formats/codecs/Deflate")
+local Archive = require("@formats/containers/Archive")
+local Tar = require("@formats/containers/Tar")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Gzip = {
+ name = "gzip",
+ category = "archive",
+ extensions = { "gz", "tgz", "gzip" },
+ mime = { "application/gzip" },
+ deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/Deflate", "containers/Archive", "containers/Tar" },
+ caps = { decode = true, encode = true, stream = true },
+}
+
+export type DecodeOptions = { name: string? } -- the file name (the api passes it): names the entry without FNAME
+export type EncodeOptions = {
+ level: number?, -- 0..9, default 6
+ name: string?, -- FNAME (default: the entry's name; none for a buffer)
+ mtime: number?, -- MTIME (default: the entry's mtime, else 0)
+}
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Gzip.sniff(r: Bytes.Reader): number
+ return if r:peek(3) == "\31\139\8" then 1 else 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+-- header(r) -> { name, comment, mtime, os } of the first member (nil fields when absent)
+local function header(b: buffer, o: number, e: number): { [string]: any }
+ local h: { [string]: any } = {}
+ if o + 10 > e then
+ return h
+ end
+ local flg = buffer.readu8(b, o + 3)
+ h.mtime = buffer.readu32(b, o + 4)
+ h.os = buffer.readu8(b, o + 9)
+ local q = o + 10
+ if bit32.band(flg, 4) ~= 0 and q + 2 <= e then
+ q += 2 + buffer.readu16(b, q)
+ end
+ for _, f in { { 8, "name" }, { 16, "comment" } } do
+ if bit32.band(flg, f[1]) ~= 0 then
+ local s = q
+ while q < e and buffer.readu8(b, q) ~= 0 do
+ q += 1
+ end
+ if q < e then
+ h[f[2]] = buffer.readstring(b, s, q - s)
+ end
+ q += 1
+ end
+ end
+ return h
+end
+
+function Gzip.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
+ local out, err = Deflate.gunzip(r.buf, r.base, r.limit - r.base)
+ if not out then
+ return nil, err
+ end
+ local h = header(r.buf, r.base, r.limit)
+ local a = Archive.new("gzip", function(arc: any, o: any?): (buffer?, Err.Err?)
+ return Gzip.encode(arc, o)
+ end)
+ a.meta.stream = true
+ a.meta.source = { format = "gzip", os = h.os }
+ a.meta.comment = h.comment
+ local name = h.name
+ if not name or name == "" or string.find(name, "[/\\]") then
+ name = Archive.streamName(opts, Gzip.extensions)
+ end
+ Archive.put(a, {
+ name = name,
+ size = buffer.len(out),
+ compressedSize = r.limit - r.base,
+ method = "deflate",
+ mtime = if h.mtime and h.mtime > 0 then h.mtime else nil,
+ dir = false,
+ data = out,
+ })
+ return a, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+function Gzip.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
+ local o = opts or {}
+ local level = if o.level == nil then 6 else o.level
+ if type(level) ~= "number" or level < 0 or level > 9 or level % 1 ~= 0 then
+ return nil, Err.new(Err.ARG, "level must be 0..9")
+ end
+ local data: buffer
+ local name: string? = o.name
+ local mtime: number = o.mtime or 0
+ if type(value) == "buffer" then
+ data = value
+ elseif type(value) == "string" then
+ data = buffer.fromstring(value)
+ else
+ local items = Archive.entries(value)
+ if not items then
+ return nil, Err.new(Err.ARG, "expected an Archive, a buffer or a string")
+ end
+ local files = {}
+ for _, it in items do
+ if not it.entry.dir then
+ table.insert(files, it)
+ end
+ end
+ if #files == 1 and #items == 1 then
+ local b, err = files[1].read()
+ if not b then
+ return nil, err
+ end
+ data = b
+ name = name or files[1].entry.name
+ mtime = o.mtime or files[1].entry.mtime or 0
+ else
+ -- several entries: a tar inside
+ local list = {}
+ for _, it in items do
+ local e: any = it.entry
+ local b = nil
+ if not e.dir then
+ local rb, err = it.read()
+ if not rb then
+ return nil, err
+ end
+ b = rb
+ end
+ table.insert(list, { name = e.name, data = b, dir = e.dir, mtime = e.mtime, mode = e.mode })
+ end
+ local t, terr = Tar.write(list)
+ if not t then
+ return nil, terr
+ end
+ data = t
+ end
+ end
+ if type(mtime) ~= "number" or mtime < 0 or mtime >= 2 ^ 32 then
+ mtime = 0
+ end
+ local raw, cerr = Deflate.compress(data, { level = level })
+ if not raw then
+ return nil, cerr
+ end
+ local w = Bytes.writer(buffer.len(raw) + 32 + (if name then #name else 0))
+ w:string("\31\139\8")
+ w:u8(if name then 8 else 0)
+ w:u32le(math.floor(mtime))
+ w:u8(if level >= 9 then 2 elseif level <= 1 then 4 else 0)
+ w:u8(255)
+ if name then
+ local z = string.find(name, "\0", 1, true)
+ w:cstring(if z then string.sub(name, 1, z - 1) else name)
+ end
+ w:bytes(raw)
+ w:u32le(Crc32.raw(data, 0, buffer.len(data)))
+ w:u32le(buffer.len(data) % 4294967296)
+ return w:finish(), nil
+end
+
+-- ------------------------------------------------------------------------------------------------ extras
+-- new(data?, name?) -> a gzip Archive holding one entry (add() replaces / adds; several entries write a .tar.gz)
+function Gzip.new(data: (buffer | string)?, name: string?): any
+ local a = Archive.new("gzip", function(arc: any, o: any?): (buffer?, Err.Err?)
+ return Gzip.encode(arc, o)
+ end)
+ a.meta.stream = true
+ a.meta.source = { format = "gzip" }
+ if data then
+ a:add(name or "data", data)
+ end
+ return a
+end
+
+return Gzip
diff --git a/src/Formats/archive/tar/init.luau b/src/Formats/archive/tar/init.luau
new file mode 100644
index 0000000..ea1e304
--- /dev/null
+++ b/src/Formats/archive/tar/init.luau
@@ -0,0 +1,120 @@
+--!strict
+-- archive/tar: tar archives (ustar, pax, GNU long names; see containers/Tar), read into the standard Archive value
+-- (entries read lazily: a copy of the stored bytes) and written from any Archive value (a tar, a zip, a 7z: list() +
+-- read()). Compressed tars (.tar.gz / .tgz / .tar.zst / .tar.xz / .tar.bz2 / .tar.br) load through the api, which
+-- unwraps the single-stream archive and sniffs again (meta.compression names the outer format).
+-- Not supported: sparse files, multi-volume archives.
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Archive = require("@formats/containers/Archive")
+local Tar = require("@formats/containers/Tar")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local TarFormat = {
+ name = "tar",
+ category = "archive",
+ extensions = { "tar" },
+ mime = { "application/x-tar" },
+ deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Tar" },
+ caps = { decode = true, encode = true, variants = { "ustar", "pax", "gnu" } },
+}
+
+export type DecodeOptions = { maxEntries: number? } -- default 1e6
+export type EncodeOptions = { format: ("pax" | "gnu" | "ustar")? } -- default "pax": ustar + pax records when needed
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function TarFormat.sniff(r: Bytes.Reader): number
+ if r:remaining() < 512 then
+ return 0
+ end
+ if not Tar.valid(r.buf, r.pos) then
+ return 0
+ end
+ return if r:peek(5, 257) == "ustar" then 0.95 else 0.6
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+local function lazy(b: buffer, at: number, n: number): () -> (buffer?, Err.Err?)
+ return function(): (buffer?, Err.Err?)
+ local out = buffer.create(n)
+ buffer.copy(out, 0, b, at, n)
+ return out, nil
+ end
+end
+
+local function encode(archive: any, opts: any?): (buffer?, Err.Err?)
+ return TarFormat.encode(archive, opts)
+end
+
+function TarFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
+ local list, err = Tar.read(r.buf, r.base, r.limit - r.base, opts)
+ if not list then
+ return nil, err
+ end
+ local a = Archive.new("tar", encode)
+ for _, e in list do
+ Archive.put(a, {
+ name = e.name,
+ size = e.size,
+ dir = e.dir,
+ mtime = e.mtime,
+ mode = e.mode,
+ uid = e.uid,
+ gid = e.gid,
+ uname = e.uname,
+ gname = e.gname,
+ type = e.type,
+ link = e.link,
+ method = "store",
+ load = if e.dir or e.size == 0 then nil else lazy(r.buf, e.offset, e.size),
+ })
+ end
+ a.meta.source = { format = "tar" }
+ return a, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+function TarFormat.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?)
+ local items = Archive.entries(archive)
+ if not items then
+ return nil, Err.new(Err.ARG, "expected an Archive")
+ end
+ local list: { Tar.WriteEntry } = {}
+ for _, it in items do
+ local e: any = it.entry
+ local data: buffer? = nil
+ if not e.dir and e.type ~= "1" and e.type ~= "2" then
+ local b, err = it.read()
+ if not b then
+ return nil, err
+ end
+ data = b
+ end
+ table.insert(list, {
+ name = e.name,
+ data = data,
+ dir = e.dir,
+ type = if type(e.type) == "string" and #e.type == 1 then e.type else nil,
+ link = if type(e.link) == "string" then e.link else nil,
+ mode = if type(e.mode) == "number" then e.mode else nil,
+ uid = if type(e.uid) == "number" then e.uid else nil,
+ gid = if type(e.gid) == "number" then e.gid else nil,
+ uname = if type(e.uname) == "string" then e.uname else nil,
+ gname = if type(e.gname) == "string" then e.gname else nil,
+ mtime = if type(e.mtime) == "number" then e.mtime else nil,
+ })
+ end
+ return Tar.write(list, opts)
+end
+
+-- ------------------------------------------------------------------------------------------------ extras
+-- new() -> an empty tar Archive: a:add(name, data, { mtime, mode, dir }); a:write()
+function TarFormat.new(): any
+ local a = Archive.new("tar", encode)
+ a.meta.source = { format = "tar" }
+ return a
+end
+
+return TarFormat
diff --git a/src/Formats/archive/xz/init.luau b/src/Formats/archive/xz/init.luau
new file mode 100644
index 0000000..9225302
--- /dev/null
+++ b/src/Formats/archive/xz/init.luau
@@ -0,0 +1,101 @@
+--!strict
+-- archive/xz: .xz (xz file format 1.2) and .lzma ("LZMA alone") files, read as single-stream archives holding one
+-- entry (the decompressed data). Built on codecs/Lzma. Supports: concatenated streams, stream padding, every block
+-- layout, checks none / CRC-32 / CRC-64 (verified; SHA-256 is not verified), filters LZMA2, delta and the BCJ filters
+-- x86 / PowerPC / ARM / ARM-Thumb / SPARC / ARM64. Not supported: writing, IA-64 / RISC-V filters.
+-- The entry is named after the file (opts.name without .xz / .lzma; .txz -> .tar), else "data". meta.stream = true:
+-- the api unwraps an inner archive (a .tar.xz loads as the tar).
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Types = require("@formats/Types")
+local Lzma = require("@formats/codecs/Lzma")
+local Archive = require("@formats/containers/Archive")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Xz = {
+ name = "xz",
+ category = "archive",
+ extensions = { "xz", "txz", "lzma" },
+ mime = { "application/x-xz", "application/x-lzma" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/Lzma", "containers/Archive" },
+ caps = { decode = true, encode = false, stream = true, filters = { "lzma2", "lzma", "delta", "x86", "powerpc", "arm", "armthumb", "sparc", "arm64" } },
+}
+
+export type DecodeOptions = {
+ maxBytes: number?, -- refuse output larger than this (default 2^30)
+ name: string?, -- the file name (the api passes it): names the entry
+}
+
+-- ------------------------------------------------------------------------------------------------ constants
+local XZ_MAGIC = "\253" .. "7zXZ\0"
+
+-- ------------------------------------------------------------------------------------------------ sniff
+-- .lzma files have no magic: props byte < 225 (0x5D for every preset), a dictionary size of 2^n or 2^n + 2^(n-1),
+-- a size of -1 or under 2^40, and a 0 range coder byte
+local function aloneScore(r: Bytes.Reader): number
+ local h = r:peek(14)
+ if #h < 14 then
+ return 0
+ end
+ local d = string.byte(h, 1)
+ if d >= 225 or string.byte(h, 14) ~= 0 then
+ return 0
+ end
+ local dict = string.byte(h, 2) + string.byte(h, 3) * 256 + string.byte(h, 4) * 65536 + string.byte(h, 5) * 16777216
+ local okDict = false
+ for n = 12, 31 do
+ if dict == 2 ^ n or (n < 31 and dict == 2 ^ n + 2 ^ (n - 1)) then
+ okDict = true
+ break
+ end
+ end
+ if not okDict then
+ return 0
+ end
+ local s = string.sub(h, 6, 13)
+ if s ~= string.rep("\255", 8) and (string.byte(h, 11) ~= 0 or string.byte(h, 12) ~= 0 or string.byte(h, 13) ~= 0) then
+ return 0
+ end
+ return if d == 0x5D then 0.4 else 0.2
+end
+
+function Xz.sniff(r: Bytes.Reader): number
+ if r:peek(6) == XZ_MAGIC then
+ return 1
+ end
+ return aloneScore(r)
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+function Xz.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive?, Err.Err?)
+ local o = opts or {}
+ local n = r.limit - r.base
+ local out, res
+ local method
+ if r:peek(6) == XZ_MAGIC then
+ out, res = Lzma.xz(r.buf, r.base, n, o)
+ method = "lzma2"
+ else
+ out, res = Lzma.alone(r.buf, r.base, n, o)
+ method = "lzma"
+ end
+ if not out then
+ return nil, res
+ end
+ local a = Archive.new("xz")
+ a.meta.stream = true
+ a.meta.container = if method == "lzma" then "lzma" else "xz"
+ Archive.put(a, {
+ name = Archive.streamName(o, Xz.extensions),
+ size = buffer.len(out),
+ compressedSize = n,
+ method = method,
+ dir = false,
+ data = out,
+ })
+ return a, nil
+end
+
+return Xz
diff --git a/src/Formats/archive/zst/init.luau b/src/Formats/archive/zst/init.luau
new file mode 100644
index 0000000..af5eef6
--- /dev/null
+++ b/src/Formats/archive/zst/init.luau
@@ -0,0 +1,63 @@
+--!strict
+-- archive/zst: a Zstandard-compressed file (.zst, RFC 8878) as a single-stream archive holding one entry, decoded
+-- through codecs/Zstd. The entry is named after the file without its extension (opts.name; ".tzst" -> ".tar"), else
+-- "data". The api unwraps it when the entry is itself an archive (.tar.zst loads as the tar). Read-only.
+-- Not supported: dictionaries, writing.
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Zstd = require("@formats/codecs/Zstd")
+local Archive = require("@formats/containers/Archive")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Zst = {
+ name = "zst",
+ category = "archive",
+ extensions = { "zst", "tzst" },
+ mime = { "application/zstd" },
+ deps = { "core/Err", "core/Bytes", "codecs/Zstd", "containers/Archive" },
+ caps = { decode = true, encode = false, stream = true },
+}
+
+export type DecodeOptions = {
+ maxBytes: number?, -- refuse a decompressed size over this (default 2^30)
+ verify: boolean?, -- check the content checksum (default true)
+ name: string?, -- the file name, for the entry name (the api passes it)
+}
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Zst.sniff(r: Bytes.Reader): number
+ local m = r:peek(4)
+ if m == Zstd.MAGIC then
+ return 1
+ end
+ -- a skippable frame (0x184D2A50 .. 0x184D2A5F) is usually followed by a zstd frame
+ if #m == 4 and string.sub(m, 2, 4) == "\42\77\24" and bit32.band(string.byte(m, 1), 0xF0) == 0x50 then
+ return 0.5
+ end
+ return 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+function Zst.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
+ local o: DecodeOptions = opts or {}
+ local len = r.limit - r.base
+ local out, err = Zstd.decompress(r.buf, r.base, len, { maxBytes = o.maxBytes, verify = o.verify })
+ if not out then
+ return nil, err
+ end
+ local a = Archive.new("zst")
+ a.meta.stream = true
+ Archive.put(a, {
+ name = Archive.streamName(o, Zst.extensions),
+ size = buffer.len(out),
+ compressedSize = len,
+ method = "zstd",
+ dir = false,
+ data = out,
+ })
+ return a, nil
+end
+
+return Zst
diff --git a/src/Formats/audio/aac/init.luau b/src/Formats/audio/aac/init.luau
new file mode 100644
index 0000000..6c3e45d
--- /dev/null
+++ b/src/Formats/audio/aac/init.luau
@@ -0,0 +1,277 @@
+--!strict
+-- audio/aac: raw AAC in ADTS framing (ISO/IEC 13818-7 / 14496-3 1.A.3), the .aac files encoders and radio streams
+-- write. Supports: reading AAC-LC through codecs/Aac (1 - 8 channels, every rate, multi-block frames, CRC-protected
+-- headers skipped), a leading ID3v2 tag (skipped; its text frames become tags), resync after garbage, seeking (by
+-- frame), HE-AAC streams play their AAC-LC core. Not supported: writing (AAC encoding is out of scope), ADIF, LATM.
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Types = require("@formats/Types")
+local Aac = require("@formats/codecs/Aac")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local AacFormat = {
+ name = "aac",
+ category = "audio",
+ extensions = { "aac", "adts" },
+ mime = { "audio/aac", "audio/aacp", "audio/x-aac" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac" },
+ caps = { decode = true, encode = false, codecs = { "aac" }, streaming = true },
+}
+
+-- ------------------------------------------------------------------------------------------------ types
+export type DecodeOptions = {
+ maxFrames: number?, -- refuse streams with more ADTS frames (default 2^22)
+}
+
+-- ------------------------------------------------------------------------------------------------ constants
+local readu8 = buffer.readu8
+
+-- the size of an ID3v2 tag at p (0 if none)
+local function id3Size(b: buffer, p: number, limit: number): number
+ if p + 10 > limit or buffer.readstring(b, p, 3) ~= "ID3" then
+ return 0
+ end
+ local s = 0
+ for i = 6, 9 do
+ s = s * 128 + bit32.band(readu8(b, p + i), 127)
+ end
+ local footer = if bit32.band(readu8(b, p + 5), 0x10) ~= 0 then 10 else 0
+ return 10 + s + footer
+end
+
+-- a few ID3v2.3 / 2.4 text frames -> tags
+local ID3_TAGS: { [string]: string } = {
+ TIT2 = "title", TPE1 = "artist", TALB = "album", TYER = "date", TDRC = "date", TCON = "genre", TRCK = "track",
+ COMM = "comment", TCOM = "composer", TPE2 = "albumartist",
+}
+local function id3Tags(b: buffer, p: number, size: number): Types.Tags
+ local tags: Types.Tags = {}
+ local ver = readu8(b, p + 3)
+ if ver < 3 then
+ return tags
+ end
+ local q, stop = p + 10, p + size
+ while q + 10 <= stop do
+ local id = buffer.readstring(b, q, 4)
+ if not string.match(id, "^[A-Z0-9][A-Z0-9][A-Z0-9][A-Z0-9]$") then
+ break
+ end
+ local n = 0
+ for i = 4, 7 do
+ n = if ver == 4 then n * 128 + bit32.band(readu8(b, q + i), 127) else n * 256 + readu8(b, q + i)
+ end
+ if n < 1 or q + 10 + n > stop then
+ break
+ end
+ local key = ID3_TAGS[id]
+ local enc = readu8(b, q + 10)
+ if key and (enc == 0 or enc == 3) then
+ local s = buffer.readstring(b, q + 11, n - 1)
+ if id == "COMM" and #s > 3 then
+ s = string.sub(s, 4)
+ local z = string.find(s, "\0", 1, true)
+ if z then
+ s = string.sub(s, z + 1)
+ end
+ end
+ s = (string.gsub(s, "%z+$", ""))
+ tags[key] = s
+ end
+ q += 10 + n
+ end
+ return tags
+end
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function AacFormat.sniff(r: Bytes.Reader): number
+ local b, p, limit = r.buf, r.pos, r.limit
+ p += id3Size(b, p, limit)
+ local h = Aac.adts(b, p, limit)
+ if not h then
+ return 0
+ end
+ -- a second header right after the first makes it certain
+ local h2 = Aac.adts(b, p + h.frameSize, limit)
+ if h2 and h2.sfIndex == h.sfIndex and h2.channelConfig == h.channelConfig then
+ return 0.9
+ end
+ return if p + h.frameSize >= limit then 0.7 else 0.4
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+-- the frame index: offsets of every ADTS frame (resyncing over garbage)
+local function index(r: Bytes.Reader, maxFrames: number): ({ number }, { number }, Aac.Adts?, Err.Err?)
+ local b, limit = r.buf, r.limit
+ local p = r.base + id3Size(b, r.base, limit)
+ local offs, sizes = {}, {}
+ local first: Aac.Adts? = nil
+ while p + 7 <= limit do
+ local h = Aac.adts(b, p, limit)
+ if h and first and (h.sfIndex ~= first.sfIndex or h.channelConfig ~= first.channelConfig) then
+ h = nil -- a false sync inside the data
+ end
+ if not h then
+ p += 1
+ continue
+ end
+ if p + h.frameSize > limit then
+ break -- a truncated last frame
+ end
+ if not first then
+ first = h
+ end
+ if h.blocks ~= 1 then
+ return offs, sizes, first, Err.new(Err.UNSUPPORTED, "ADTS frames with " .. h.blocks .. " raw data blocks", p)
+ end
+ table.insert(offs, p + h.headerSize)
+ table.insert(sizes, h.frameSize - h.headerSize)
+ if #offs > maxFrames then
+ return offs, sizes, first, Err.new(Err.LIMIT, "more than " .. maxFrames .. " frames")
+ end
+ p += h.frameSize
+ end
+ return offs, sizes, first, nil
+end
+
+function AacFormat.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?)
+ local o = opts or {}
+ local offs, sizes, first, ierr = index(r, o.maxFrames or 2 ^ 22)
+ if ierr then
+ return nil, ierr
+ end
+ if not first then
+ return nil, Err.new(Err.CORRUPT, "no ADTS frame", r.base)
+ end
+ local h = first :: Aac.Adts
+ if h.objectType ~= 2 then
+ return nil, Err.new(Err.UNSUPPORTED, "ADTS profile " .. h.objectType .. " (only AAC-LC)")
+ end
+ if h.channelConfig == 0 then
+ return nil, Err.new(Err.UNSUPPORTED, "ADTS with a program config element (channel configuration 0)")
+ end
+ local channels = ({ 1, 2, 3, 4, 5, 6, 8 })[h.channelConfig] :: number
+ local dec, derr = Aac.decoder({ sfIndex = h.sfIndex, channels = channels, channelConfig = h.channelConfig })
+ if not dec then
+ return nil, derr
+ end
+ local d = dec :: Aac.Decoder
+ local sr = d.sampleRate
+ local nframes = #offs
+ local total = nframes * 1024
+ local bytes = 0
+ for _, s in sizes do
+ bytes += s
+ end
+ local id3 = id3Size(r.buf, r.base, r.limit)
+ local tags = if id3 > 0 then id3Tags(r.buf, r.base, id3) else {}
+ local buf = r.buf
+ local nextFrame = 1
+ local pendPos, pendN = 0, 0
+ local drop = 0
+ local pos = 0
+ local failed: Err.Err? = nil
+ local out: any = {
+ sampleRate = sr,
+ channels = channels,
+ frames = total,
+ duration = total / sr,
+ bitrate = if total > 0 then math.floor(bytes * 8 * sr / total) else 0,
+ tags = tags,
+ codec = "aac",
+ error = nil,
+ }
+ local function fill(): boolean
+ while true do
+ if nextFrame > nframes then
+ return false
+ end
+ local i = nextFrame
+ nextFrame += 1
+ local n, e = d:decode(buf, offs[i], sizes[i])
+ if not n then
+ failed = e
+ out.error = e
+ return false
+ end
+ if drop >= n then
+ drop -= n
+ else
+ pendPos, pendN = drop, n
+ drop = 0
+ return true
+ end
+ end
+ end
+ function out.read(_self: any, n: number, ob: buffer?): (buffer, number)
+ local want = math.max(0, math.floor(n))
+ local need = want * channels * 4
+ local res = if ob and buffer.len(ob) >= need then ob else buffer.create(need)
+ local got = 0
+ local writef32 = buffer.writef32
+ while got < want do
+ if pendPos >= pendN then
+ if failed or not fill() then
+ break
+ end
+ end
+ local take = math.min(want - got, pendN - pendPos)
+ local src = d.pcm
+ local q = got * channels * 4
+ local s = pendPos * channels
+ for k = 1, take * channels do
+ writef32(res, q, src[s + k])
+ q += 4
+ end
+ pendPos += take
+ got += take
+ end
+ pos += got
+ return res, got
+ end
+ function out.seek(_self: any, seconds: number)
+ local target = math.clamp(math.floor(seconds * sr + 0.5), 0, total)
+ local f = target // 1024 -- frame holding the target (0-based)
+ local start = math.max(0, f - 1) -- one frame of pre-roll for the overlap
+ d:reset()
+ nextFrame = start + 1
+ drop = target - start * 1024
+ pendPos, pendN = 0, 0
+ failed = nil
+ pos = target
+ end
+ function out.position(_self: any): number
+ return pos / sr
+ end
+ if nframes > 0 and not fill() and failed then
+ return nil, failed
+ end
+ return out, nil
+end
+
+function AacFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?)
+ local dec, err = AacFormat.open(r, opts)
+ if not dec then
+ return nil, err
+ end
+ local d: any = dec
+ local audio = Types.Audio.new(d.sampleRate, d.channels, d.frames)
+ local done = 0
+ while done < d.frames do
+ local b, n = d:read(math.min(65536, d.frames - done))
+ if n == 0 then
+ break
+ end
+ buffer.copy(audio.samples, done * d.channels * 4, b, 0, n * d.channels * 4)
+ done += n
+ end
+ if d.error then
+ return nil, d.error
+ end
+ audio.tags = d.tags
+ audio.meta.source = { format = "aac", codec = "aac", bitrate = d.bitrate }
+ return audio, nil
+end
+
+return AacFormat
diff --git a/src/Formats/audio/caf/init.luau b/src/Formats/audio/caf/init.luau
new file mode 100644
index 0000000..f602434
--- /dev/null
+++ b/src/Formats/audio/caf/init.luau
@@ -0,0 +1,746 @@
+--!strict
+-- audio/caf: Apple Core Audio Format (CAF 1.0, Apple's "Core Audio Format Specification"). Supports reading linear
+-- PCM (8 / 16 / 24 / 32-bit integer, 32 / 64-bit float, big / little endian), ALAC (codecs/Alac), AAC-LC (codecs/Aac,
+-- kuki esds), mu-law and A-law; the packet table (pakt) with priming / remainder trimming, a data chunk of unknown
+-- size (-1), info chunk tags; seeking. Writing linear PCM (16 / 24-bit big endian, 32-bit float) and ALAC (16 / 20 /
+-- 24-bit) with info tags. Not supported: IMA4, other compressed formats (UNSUPPORTED).
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Types = require("@formats/Types")
+local Aac = require("@formats/codecs/Aac")
+local Alac = require("@formats/codecs/Alac")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Caf = {
+ name = "caf",
+ category = "audio",
+ extensions = { "caf", "caff" },
+ mime = { "audio/x-caf" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac", "codecs/Alac" },
+ caps = { decode = true, encode = true, codecs = { "pcm", "alac", "aac", "ulaw", "alaw" }, encodeCodecs = { "pcm", "alac" }, tags = true, streaming = true },
+}
+
+-- ------------------------------------------------------------------------------------------------ types
+export type DecodeOptions = {
+ maxPackets: number?, -- packet table limit (default 2^24)
+}
+export type EncodeOptions = {
+ codec: ("pcm" | "alac")?, -- default "alac"
+ bitDepth: number?, -- pcm: 16 (default), 24, 32 (float); alac: 16 (default), 20, 24
+ tags: Types.Tags?, -- default: the audio's tags
+}
+
+-- ------------------------------------------------------------------------------------------------ constants
+local INFO_TAGS: { [string]: string } = {
+ title = "title", artist = "artist", album = "album", year = "date", genre = "genre", ["track number"] = "track",
+ comments = "comment", composer = "composer", copyright = "copyright", lyricist = "lyricist",
+ ["encoding application"] = "encoder", ["recorded date"] = "recorded", tempo = "bpm",
+}
+local TAG_INFO: { [string]: string } = {}
+for k, v in INFO_TAGS do
+ TAG_INFO[v] = k
+end
+
+-- mu-law / A-law -> linear 16-bit
+local ULAW, ALAW = table.create(256, 0), table.create(256, 0)
+for i = 0, 255 do
+ local u = 255 - i
+ local t = (bit32.band(u, 15) * 8 + 132) * 2 ^ bit32.band(bit32.rshift(u, 4), 7)
+ ULAW[i + 1] = if bit32.band(u, 128) ~= 0 then 132 - t else t - 132
+ local a = bit32.bxor(i, 0x55)
+ local seg = bit32.band(bit32.rshift(a, 4), 7)
+ local m = bit32.band(a, 15) * 16 + 8
+ if seg > 0 then
+ m = (m + 256) * 2 ^ (seg - 1)
+ end
+ ALAW[i + 1] = if bit32.band(a, 128) ~= 0 then m else -m
+end
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Caf.sniff(r: Bytes.Reader): number
+ local h = r:peek(8)
+ if #h == 8 and string.sub(h, 1, 4) == "caff" and string.byte(h, 5) == 0 and string.byte(h, 6) == 1 then
+ return 1
+ end
+ return 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+type Desc = { rate: number, format: string, flags: number, bytesPerPacket: number, framesPerPacket: number, channels: number, bits: number }
+type Parsed = {
+ desc: Desc,
+ dataStart: number, -- absolute offset of the audio data
+ dataEnd: number,
+ cookie: buffer?,
+ packets: { number }?, -- sizes (pakt)
+ packetFrames: { number }?,
+ priming: number,
+ remainder: number,
+ validFrames: number?,
+ tags: Types.Tags,
+}
+
+-- the esds payload in a kuki (version / flags, then the ES_Descriptor) -> the DecoderSpecificInfo
+local function esdsConfig(b: buffer): buffer?
+ local r = Bytes.reader(b)
+ if r:peekU8() ~= 3 then
+ r:skip(4) -- the esds atom's version / flags
+ end
+ local function len(): number
+ local n = 0
+ for _ = 1, 4 do
+ local c = r:u8()
+ n = n * 128 + bit32.band(c, 127)
+ if c < 128 then
+ break
+ end
+ end
+ return n
+ end
+ while not r:eof() and not r.err do
+ local tag = r:u8()
+ local n = len()
+ if tag == 3 then
+ r:skip(2)
+ local f = r:u8()
+ if bit32.band(f, 0x80) ~= 0 then
+ r:skip(2)
+ end
+ if bit32.band(f, 0x40) ~= 0 then
+ r:skip(r:u8())
+ end
+ if bit32.band(f, 0x20) ~= 0 then
+ r:skip(2)
+ end
+ elseif tag == 4 then
+ r:skip(13)
+ elseif tag == 5 then
+ if n > 0 and r:need(n) then
+ return r:bytes(n)
+ end
+ return nil
+ else
+ r:skip(n)
+ end
+ end
+ return nil
+end
+
+local function vlq(r: Bytes.Reader): number
+ local v = 0
+ for _ = 1, 8 do
+ local c = r:u8()
+ v = v * 128 + bit32.band(c, 127)
+ if c < 128 then
+ return v
+ end
+ end
+ r:fail(Err.CORRUPT, "bad packet table entry")
+ return 0
+end
+
+local function parse(r: Bytes.Reader, o: DecodeOptions): (Parsed?, Err.Err?)
+ if Caf.sniff(r) == 0 then
+ return nil, Err.new(Err.CORRUPT, "not a CAF file", r.base)
+ end
+ r:seek(8)
+ local p: Parsed = { desc = nil :: any, dataStart = 0, dataEnd = 0, priming = 0, remainder = 0, tags = {} }
+ local haveData = false
+ while r:remaining() >= 12 do
+ local typ = r:string(4)
+ local size = r:i64be()
+ local start = r.pos
+ if size == -1 and typ == "data" then
+ size = r.limit - start
+ end
+ if size < 0 then
+ return nil, Err.new(Err.CORRUPT, "bad chunk size", start - 12)
+ end
+ local stop = start + size
+ if stop > r.limit then
+ if typ ~= "data" then
+ return nil, Err.new(Err.TRUNCATED, "chunk '" .. typ .. "' runs past the end", start - 12)
+ end
+ stop = r.limit -- a truncated data chunk: play what is there
+ end
+ local c = Bytes.reader(r.buf, start, stop - start)
+ if typ == "desc" then
+ p.desc = {
+ rate = c:f64be(),
+ format = c:string(4),
+ flags = c:u32be(),
+ bytesPerPacket = c:u32be(),
+ framesPerPacket = c:u32be(),
+ channels = c:u32be(),
+ bits = c:u32be(),
+ }
+ if c.err then
+ return nil, c.err
+ end
+ elseif typ == "data" then
+ p.dataStart = start + 4 -- edit count
+ p.dataEnd = stop
+ haveData = true
+ elseif typ == "kuki" then
+ p.cookie = c:bytes(stop - start)
+ elseif typ == "pakt" then
+ local n = c:i64be()
+ p.validFrames = c:i64be()
+ p.priming = c:i32be()
+ p.remainder = c:i32be()
+ if c.err then
+ return nil, c.err
+ end
+ if n < 0 or n > (o.maxPackets or 2 ^ 24) or n > c:remaining() then
+ return nil, Err.new(Err.LIMIT, "packet table of " .. n .. " entries", start)
+ end
+ local d = p.desc
+ if not d then
+ return nil, Err.new(Err.CORRUPT, "pakt before desc", start)
+ end
+ local sizes, frames = table.create(n, 0), nil
+ if d.framesPerPacket == 0 then
+ frames = table.create(n, 0)
+ end
+ for i = 1, n do
+ sizes[i] = if d.bytesPerPacket == 0 then vlq(c) else d.bytesPerPacket
+ if frames then
+ frames[i] = vlq(c)
+ end
+ end
+ if c.err then
+ return nil, c.err
+ end
+ p.packets, p.packetFrames = sizes, frames
+ elseif typ == "info" then
+ local n = c:u32be()
+ for _ = 1, math.min(n, 1000) do
+ local k = c:cstring()
+ local v = c:cstring()
+ if c.err then
+ break
+ end
+ p.tags[INFO_TAGS[string.lower(k)] or k] = v
+ end
+ end
+ r.pos = stop
+ if typ == "data" and stop >= r.limit then
+ break
+ end
+ end
+ if not p.desc then
+ return nil, Err.new(Err.CORRUPT, "no desc chunk", r.base)
+ end
+ if not haveData then
+ return nil, Err.new(Err.CORRUPT, "no data chunk", r.base)
+ end
+ local d = p.desc
+ if d.channels < 1 or d.channels > 64 or d.rate <= 0 or d.rate ~= d.rate or d.rate > 1e7 then
+ return nil, Err.new(Err.CORRUPT, "bad stream description")
+ end
+ return p, nil
+end
+
+-- the packet decoder: decode(i) -> frames into pcm (interleaved floats) | nil, Err
+type Source = {
+ channels: number,
+ rate: number,
+ packetCount: number,
+ packetFrames: (number) -> number,
+ decode: (number) -> (number?, Err.Err?),
+ pcm: { number },
+ reset: () -> (),
+ codec: string,
+ bits: number?,
+}
+
+local function source(r: Bytes.Reader, p: Parsed): (Source?, Err.Err?)
+ local d = p.desc
+ local b = r.buf
+ local ch = d.channels
+ local fmt = d.format
+ if fmt == "lpcm" or fmt == "ulaw" or fmt == "alaw" then
+ local bits = if fmt == "lpcm" then d.bits else 8
+ local float = fmt == "lpcm" and bit32.band(d.flags, 1) ~= 0
+ local little = fmt == "lpcm" and bit32.band(d.flags, 2) ~= 0
+ local bpf = d.bytesPerPacket
+ if bpf == 0 then
+ bpf = ch * (bits // 8)
+ end
+ if not (bits == 8 or bits == 16 or bits == 24 or bits == 32 or (bits == 64 and float)) or (float and bits < 32) then
+ return nil, Err.new(Err.UNSUPPORTED, "linear PCM with " .. bits .. " bits")
+ end
+ local bps = bits // 8
+ if bpf < ch * bps then
+ return nil, Err.new(Err.CORRUPT, "bytes per packet smaller than a frame")
+ end
+ local total = (p.dataEnd - p.dataStart) // bpf
+ local per = 1024
+ local pcm = table.create(per * ch, 0)
+ local scale = 1 / 2 ^ (bits - 1)
+ local readu8, readi8 = buffer.readu8, buffer.readi8
+ local src: Source = {
+ channels = ch,
+ rate = d.rate,
+ packetCount = (total + per - 1) // per,
+ packetFrames = function(i: number): number
+ return math.min(per, total - (i - 1) * per)
+ end,
+ pcm = pcm,
+ reset = function() end,
+ codec = if fmt == "lpcm" then "pcm" else fmt,
+ bits = bits,
+ decode = function(i: number): (number?, Err.Err?)
+ local f0 = (i - 1) * per
+ local n = math.min(per, total - f0)
+ local k = 1
+ for f = f0, f0 + n - 1 do
+ local q = p.dataStart + f * bpf
+ for _ = 1, ch do
+ local v
+ if fmt == "ulaw" then
+ v = ULAW[readu8(b, q) + 1] / 32768
+ elseif fmt == "alaw" then
+ v = ALAW[readu8(b, q) + 1] / 32768
+ elseif float then
+ if bits == 32 then
+ v = if little then buffer.readf32(b, q) else Bytes.reader(b, q, 4):f32be()
+ else
+ v = if little then buffer.readf64(b, q) else Bytes.reader(b, q, 8):f64be()
+ end
+ elseif bits == 8 then
+ v = readi8(b, q) * scale
+ elseif bits == 16 then
+ v = if little then buffer.readi16(b, q) else readi8(b, q) * 256 + readu8(b, q + 1)
+ v *= scale
+ elseif bits == 24 then
+ if little then
+ v = readi8(b, q + 2) * 65536 + readu8(b, q + 1) * 256 + readu8(b, q)
+ else
+ v = readi8(b, q) * 65536 + readu8(b, q + 1) * 256 + readu8(b, q + 2)
+ end
+ v *= scale
+ else
+ if little then
+ v = buffer.readi32(b, q)
+ else
+ v = readi8(b, q) * 16777216 + readu8(b, q + 1) * 65536 + readu8(b, q + 2) * 256 + readu8(b, q + 3)
+ end
+ v *= scale
+ end
+ pcm[k] = v
+ k += 1
+ q += bps
+ end
+ end
+ return n, nil
+ end,
+ }
+ return src, nil
+ end
+ -- packetised codecs
+ local sizes = p.packets
+ if not sizes then
+ if d.bytesPerPacket > 0 then
+ local n = (p.dataEnd - p.dataStart) // d.bytesPerPacket
+ sizes = table.create(n, d.bytesPerPacket)
+ else
+ return nil, Err.new(Err.CORRUPT, "compressed CAF without a packet table")
+ end
+ end
+ local offsets = table.create(#sizes, 0)
+ local o = p.dataStart
+ for i, s in sizes :: { number } do
+ offsets[i] = o
+ o += s
+ if o > p.dataEnd then
+ -- a truncated file: keep the whole packets
+ offsets[i] = nil :: any
+ sizes = table.move(sizes :: { number }, 1, i - 1, 1, {})
+ break
+ end
+ end
+ local count = #(sizes :: { number })
+ local fpp = d.framesPerPacket
+ local pf = p.packetFrames
+ local function framesOf(i: number): number
+ return if pf then pf[i] else fpp
+ end
+ local cookie = p.cookie
+ if fmt == "alac" then
+ if not cookie then
+ return nil, Err.new(Err.CORRUPT, "ALAC without a magic cookie")
+ end
+ local cfg, err = Alac.config(cookie :: buffer)
+ if not cfg then
+ return nil, err
+ end
+ local dec = Alac.decoder(cfg)
+ local pcm = table.create(cfg.frameLength * cfg.channels, 0)
+ local scale = 1 / 2 ^ (cfg.bitDepth - 1)
+ return {
+ channels = cfg.channels,
+ rate = d.rate,
+ packetCount = count,
+ packetFrames = framesOf,
+ pcm = pcm,
+ reset = function() end,
+ codec = "alac",
+ bits = cfg.bitDepth,
+ decode = function(i: number): (number?, Err.Err?)
+ local n, e = dec:decode(b, offsets[i], (sizes :: { number })[i])
+ if not n then
+ return nil, e
+ end
+ local src = dec.pcm
+ for k = 1, n * cfg.channels do
+ pcm[k] = src[k] * scale
+ end
+ return n, nil
+ end,
+ }, nil
+ elseif fmt == "aac " then
+ local asc = if cookie then esdsConfig(cookie :: buffer) else nil
+ if not asc then
+ return nil, Err.new(Err.CORRUPT, "AAC without an esds magic cookie")
+ end
+ local dec, err = Aac.decoder(asc :: buffer)
+ if not dec then
+ return nil, err
+ end
+ local ad = dec :: Aac.Decoder
+ return {
+ channels = ad.channels,
+ rate = d.rate,
+ packetCount = count,
+ packetFrames = framesOf,
+ pcm = ad.pcm,
+ reset = function()
+ ad:reset()
+ end,
+ codec = "aac",
+ decode = function(i: number): (number?, Err.Err?)
+ return ad:decode(b, offsets[i], (sizes :: { number })[i])
+ end,
+ }, nil
+ end
+ return nil, Err.new(Err.UNSUPPORTED, "CAF format '" .. fmt .. "'")
+end
+
+function Caf.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?)
+ local p, err = parse(r, opts or {})
+ if not p then
+ return nil, err
+ end
+ local s, serr = source(r, p :: Parsed)
+ if not s then
+ return nil, serr
+ end
+ local src = s :: Source
+ local ch, rate = src.channels, src.rate
+ local starts = table.create(src.packetCount + 1, 0)
+ local total = 0
+ for i = 1, src.packetCount do
+ starts[i] = total
+ total += src.packetFrames(i)
+ end
+ starts[src.packetCount + 1] = total
+ local skip = math.max(0, p.priming)
+ local stopAt = total
+ if p.validFrames and p.validFrames >= 0 then
+ stopAt = math.min(total, skip + p.validFrames)
+ elseif p.remainder > 0 then
+ stopAt = math.max(skip, total - p.remainder)
+ end
+ local frames = math.max(0, stopAt - skip)
+ local nextPacket = 1
+ local decoded = 0
+ local pendPos, pendN = 0, 0
+ local dropUntil = skip
+ local pos = 0
+ local failed: Err.Err? = nil
+ local dec: any = {
+ sampleRate = rate,
+ channels = ch,
+ frames = frames,
+ duration = frames / rate,
+ bitrate = if frames > 0 then math.floor((p.dataEnd - p.dataStart) * 8 * rate / frames) else 0,
+ tags = p.tags,
+ codec = src.codec,
+ bitsPerSample = src.bits,
+ error = nil,
+ }
+ local function fill(): boolean
+ while true do
+ if nextPacket > src.packetCount or decoded >= stopAt then
+ return false
+ end
+ local i = nextPacket
+ nextPacket += 1
+ local start = starts[i]
+ local n, e = src.decode(i)
+ if not n then
+ failed = e
+ dec.error = e
+ return false
+ end
+ decoded = start + n
+ local a = math.max(start, dropUntil)
+ local b = math.min(decoded, stopAt)
+ if b > a then
+ pendPos, pendN = a - start, b - start
+ return true
+ end
+ end
+ end
+ function dec.read(_self: any, n: number, out: buffer?): (buffer, number)
+ local want = math.max(0, math.floor(n))
+ local need = want * ch * 4
+ local ob = if out and buffer.len(out) >= need then out else buffer.create(need)
+ local got = 0
+ local writef32 = buffer.writef32
+ while got < want do
+ if pendPos >= pendN then
+ if failed or not fill() then
+ break
+ end
+ end
+ local take = math.min(want - got, pendN - pendPos)
+ local q = got * ch * 4
+ local sidx = pendPos * ch
+ local pcm = src.pcm
+ for k = 1, take * ch do
+ writef32(ob, q, pcm[sidx + k])
+ q += 4
+ end
+ pendPos += take
+ got += take
+ end
+ pos += got
+ return ob, got
+ end
+ function dec.seek(_self: any, seconds: number)
+ local target = math.clamp(math.floor(seconds * rate + 0.5), 0, frames) + skip
+ local lo, hi, found = 1, src.packetCount, 1
+ while lo <= hi do
+ local mid = (lo + hi) // 2
+ if starts[mid] <= target then
+ found = mid
+ lo = mid + 1
+ else
+ hi = mid - 1
+ end
+ end
+ if src.codec == "aac" then
+ found = math.max(1, found - 1)
+ end
+ src.reset()
+ nextPacket = found
+ decoded = starts[found]
+ dropUntil = target
+ pendPos, pendN = 0, 0
+ failed = nil
+ pos = target - skip
+ end
+ function dec.position(_self: any): number
+ return pos / rate
+ end
+ if src.packetCount > 0 and frames > 0 and not fill() and failed then
+ return nil, failed
+ end
+ return dec, nil
+end
+
+function Caf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?)
+ local dec, err = Caf.open(r, opts)
+ if not dec then
+ return nil, err
+ end
+ local d: any = dec
+ local audio = Types.Audio.new(d.sampleRate, d.channels, d.frames)
+ local done = 0
+ while done < d.frames do
+ local b, n = d:read(math.min(65536, d.frames - done))
+ if n == 0 then
+ break
+ end
+ buffer.copy(audio.samples, done * d.channels * 4, b, 0, n * d.channels * 4)
+ done += n
+ end
+ if d.error then
+ return nil, d.error
+ end
+ audio.tags = d.tags
+ audio.meta.source = { format = "caf", codec = d.codec, bitsPerSample = d.bitsPerSample }
+ return audio, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+local function chunk(w: Bytes.Writer, typ: string, size: number)
+ w:string(typ)
+ w:i64be(size)
+end
+
+-- encode(audio | decoder, opts?) -> buffer | nil, Err
+function Caf.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
+ local o = opts or {}
+ if type(value) ~= "table" or type(value.sampleRate) ~= "number" or type(value.channels) ~= "number" then
+ return nil, Err.new(Err.ARG, "expected an Audio or a Decoder")
+ end
+ local codec = o.codec or "alac"
+ if codec ~= "alac" and codec ~= "pcm" then
+ return nil, Err.new(Err.ARG, "codec must be 'alac' or 'pcm'")
+ end
+ local sr, ch = value.sampleRate, value.channels
+ local depth = o.bitDepth or 16
+ if codec == "pcm" and depth ~= 16 and depth ~= 24 and depth ~= 32 then
+ return nil, Err.new(Err.ARG, "pcm bitDepth 16, 24 or 32 (float)")
+ end
+ if ch < 1 or ch > 64 or sr <= 0 then
+ return nil, Err.new(Err.ARG, "bad sample rate / channels")
+ end
+ -- the source frames
+ local isAudio = value.kind == "audio" and type(value.samples) == "buffer"
+ if not isAudio and type(value.read) ~= "function" then
+ return nil, Err.new(Err.ARG, "expected an Audio or a Decoder")
+ end
+ if isAudio and buffer.len(value.samples) < value.frames * ch * 4 then
+ return nil, Err.new(Err.ARG, "audio.samples is shorter than frames * channels")
+ end
+ local done = 0
+ local chunkBuf: buffer? = nil
+ local function nextBlock(n: number): (buffer?, number, number)
+ if isAudio then
+ local k = math.min(n, value.frames - done)
+ local base = done * ch * 4
+ done += k
+ return value.samples, base, k
+ end
+ local b, got = value:read(n, chunkBuf)
+ chunkBuf = b
+ done += got
+ return b, 0, got
+ end
+ local readf32 = buffer.readf32
+ local data = Bytes.writer(65536)
+ local sizes: { number } = {}
+ local enc: Alac.Encoder? = nil
+ if codec == "alac" then
+ local e, err = Alac.encoder({ sampleRate = math.floor(sr), channels = ch, bitDepth = depth })
+ if not e then
+ return nil, err
+ end
+ enc = e
+ local ints = table.create(4096 * ch, 0)
+ local peak = 2 ^ (depth - 1)
+ while true do
+ local b, base, n = nextBlock(4096)
+ if not b or n <= 0 then
+ break
+ end
+ for i = 0, n * ch - 1 do
+ local v = math.floor(readf32(b, base + i * 4) * peak + 0.5)
+ ints[i + 1] = math.clamp(v, -peak, peak - 1)
+ end
+ local pkt, perr = (e :: Alac.Encoder):encode(ints, 1, n)
+ if not pkt then
+ return nil, perr
+ end
+ data:bytes(pkt)
+ table.insert(sizes, buffer.len(pkt))
+ end
+ else
+ local peak = 2 ^ (depth - 1)
+ while true do
+ local b, base, n = nextBlock(4096)
+ if not b or n <= 0 then
+ break
+ end
+ for i = 0, n * ch - 1 do
+ local f = readf32(b, base + i * 4)
+ if depth == 32 then
+ data:f32be(f)
+ else
+ local v = math.clamp(math.floor(f * peak + 0.5), -peak, peak - 1)
+ if depth == 16 then
+ data:u16be(v % 65536)
+ else
+ data:u24be(v % 16777216)
+ end
+ end
+ end
+ end
+ end
+ local frames = done
+ local w = Bytes.writer(data:tell() + 1024)
+ w:string("caff")
+ w:u16be(1)
+ w:u16be(0)
+ chunk(w, "desc", 32)
+ w:f64be(sr)
+ if codec == "alac" then
+ w:string("alac")
+ w:u32be(({ [16] = 1, [20] = 2, [24] = 3, [32] = 4 })[depth] or 1)
+ w:u32be(0)
+ w:u32be(4096)
+ w:u32be(ch)
+ w:u32be(0)
+ else
+ w:string("lpcm")
+ w:u32be(if depth == 32 then 1 else 0) -- float / big-endian integer
+ w:u32be(ch * depth // 8)
+ w:u32be(1)
+ w:u32be(ch)
+ w:u32be(depth)
+ end
+ local tags = o.tags or value.tags or {}
+ local keys = {}
+ for k, v in tags do
+ if type(v) == "string" then
+ table.insert(keys, k)
+ end
+ end
+ table.sort(keys)
+ if #keys > 0 then
+ local info = Bytes.writer(256)
+ info:u32be(#keys)
+ for _, k in keys do
+ info:cstring(TAG_INFO[k] or k)
+ info:cstring(tags[k])
+ end
+ chunk(w, "info", info:tell())
+ w:bytes(info.buf, 0, info:tell())
+ end
+ if enc then
+ local cookie = Alac.cookie(enc.config)
+ chunk(w, "kuki", buffer.len(cookie))
+ w:bytes(cookie)
+ local pk = Bytes.writer(64 + #sizes * 2)
+ pk:i64be(#sizes)
+ pk:i64be(frames)
+ pk:u32be(0)
+ pk:u32be(#sizes * 4096 - frames)
+ for _, s in sizes do
+ -- BER variable-length integer
+ local bytes = { s % 128 }
+ local v = s // 128
+ while v > 0 do
+ table.insert(bytes, 1, 128 + v % 128)
+ v //= 128
+ end
+ for _, x in bytes do
+ pk:u8(x)
+ end
+ end
+ chunk(w, "pakt", pk:tell())
+ w:bytes(pk.buf, 0, pk:tell())
+ end
+ chunk(w, "data", data:tell() + 4)
+ w:u32be(0) -- edit count
+ w:bytes(data.buf, 0, data:tell())
+ return w:finish(), nil
+end
+
+return Caf
diff --git a/src/Formats/audio/m4a/init.luau b/src/Formats/audio/m4a/init.luau
new file mode 100644
index 0000000..bf64abb
--- /dev/null
+++ b/src/Formats/audio/m4a/init.luau
@@ -0,0 +1,441 @@
+--!strict
+-- audio/m4a: MPEG-4 audio files (M4A / M4B / MP4 / MOV audio tracks) through containers/IsoBmff. Supports: reading
+-- AAC-LC (codecs/Aac; HE-AAC files play their AAC-LC core at the core rate) and ALAC (codecs/Alac) tracks, gapless
+-- trimming through the edit list (encoder priming / padding), seeking, iTunes tags and cover art (dec.pictures);
+-- writing ALAC (16 / 20 / 24-bit, 1 - 8 channels) with tags and cover art. Not supported: writing AAC, other codecs
+-- inside MP4 (MP3 / Opus / FLAC / AC-3: UNSUPPORTED), encrypted files.
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Types = require("@formats/Types")
+local IsoBmff = require("@formats/containers/IsoBmff")
+local Aac = require("@formats/codecs/Aac")
+local Alac = require("@formats/codecs/Alac")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local M4a = {
+ name = "m4a",
+ category = "audio",
+ extensions = { "m4a", "m4b", "m4r" },
+ mime = { "audio/mp4", "audio/x-m4a", "audio/m4a" },
+ deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "codecs/Aac", "codecs/Alac" },
+ caps = { decode = true, encode = true, codecs = { "aac", "alac" }, encodeCodecs = { "alac" }, tags = true, streaming = true },
+}
+
+-- ------------------------------------------------------------------------------------------------ types
+export type DecodeOptions = {
+ track: number?, -- the track id to play (default: the first AAC / ALAC track)
+ gapless: boolean?, -- apply the edit list (default true)
+ maxSamples: number?, -- sample table limit (default 2^25)
+}
+export type EncodeOptions = {
+ bitDepth: number?, -- 16 (default), 20 or 24
+ frameLength: number?, -- samples per packet, default 4096
+ tags: Types.Tags?, -- default: the audio's tags
+ pictures: { { mime: string, data: buffer } }?, -- cover art (default: audio.meta.pictures)
+}
+
+-- ------------------------------------------------------------------------------------------------ constants
+local AUDIO_BRANDS: { [string]: number } = { ["M4A "] = 1, ["M4B "] = 1, ["M4P "] = 1, ["M4V "] = 0.3 }
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function M4a.sniff(r: Bytes.Reader): number
+ local brand = IsoBmff.sniff(r)
+ if brand == nil then
+ return 0
+ end
+ if AUDIO_BRANDS[brand] then
+ return AUDIO_BRANDS[brand]
+ end
+ if brand == "avif" or brand == "avis" or brand == "heic" or brand == "heix" or brand == "mif1" or brand == "msf1" or brand == "crx " then
+ return 0
+ end
+ return 0.4 -- an MP4 / MOV that may hold audio; a video format claims it more strongly
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+-- the packet decoder of a track: decode(buf, off, len) -> frames | nil, Err; pcm: interleaved floats
+type PacketDecoder = {
+ channels: number,
+ sampleRate: number,
+ frameSize: number,
+ pcm: { number },
+ decode: (buf: buffer, off: number, len: number) -> (number?, Err.Err?),
+ reset: () -> (),
+}
+
+local function packetDecoder(t: IsoBmff.Track): (PacketDecoder?, Err.Err?)
+ if not t.config then
+ return nil, Err.new(Err.CORRUPT, "track " .. t.id .. " (" .. t.codec .. ") has no codec configuration")
+ end
+ if t.codec == "alac" then
+ local cfg, err = Alac.config(t.config :: buffer)
+ if not cfg then
+ return nil, err
+ end
+ local dec = Alac.decoder(cfg)
+ local pcm = table.create(cfg.frameLength * cfg.channels, 0)
+ local scale = 1 / 2 ^ (cfg.bitDepth - 1)
+ local pd: PacketDecoder = {
+ channels = cfg.channels,
+ sampleRate = if cfg.sampleRate > 0 then cfg.sampleRate else (t.sampleRate or 44100),
+ frameSize = cfg.frameLength,
+ pcm = pcm,
+ decode = function(buf: buffer, off: number, len: number): (number?, Err.Err?)
+ local n, e = dec:decode(buf, off, len)
+ if not n then
+ return nil, e
+ end
+ local src = dec.pcm
+ for i = 1, n * cfg.channels do
+ pcm[i] = src[i] * scale
+ end
+ return n, nil
+ end,
+ reset = function() end,
+ }
+ return pd, nil
+ elseif t.codec == "aac" then
+ local dec, err = Aac.decoder(t.config :: buffer)
+ if not dec then
+ return nil, err
+ end
+ local d = dec :: Aac.Decoder
+ local pd: PacketDecoder = {
+ channels = d.channels,
+ sampleRate = d.sampleRate,
+ frameSize = d.frameLength,
+ pcm = d.pcm,
+ decode = function(buf: buffer, off: number, len: number): (number?, Err.Err?)
+ return d:decode(buf, off, len)
+ end,
+ reset = function()
+ d:reset()
+ end,
+ }
+ return pd, nil
+ end
+ return nil, Err.new(Err.UNSUPPORTED, "audio codec " .. t.codec .. " in MP4")
+end
+
+-- open(r, opts?) -> Types.Decoder | nil, Err
+function M4a.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?)
+ local o = opts or {}
+ local movie, err = IsoBmff.parse(r, { maxSamples = o.maxSamples })
+ if not movie then
+ return nil, err
+ end
+ local track: IsoBmff.Track? = nil
+ local other: IsoBmff.Track? = nil
+ for _, t in movie.tracks do
+ if t.kind == "audio" then
+ if o.track and t.id ~= o.track then
+ continue
+ end
+ if t.codec == "aac" or t.codec == "alac" then
+ track = t
+ break
+ end
+ other = other or t
+ end
+ end
+ if not track then
+ if other then
+ return nil, Err.new(Err.UNSUPPORTED, "audio codec " .. other.codec .. " in MP4")
+ end
+ return nil, Err.new(Err.CORRUPT, "no audio track")
+ end
+ local t = track :: IsoBmff.Track
+ local pd, perr = packetDecoder(t)
+ if not pd then
+ return nil, perr
+ end
+ local p = pd :: PacketDecoder
+ local channels, sr = p.channels, p.sampleRate
+ -- media ticks -> sample frames
+ local tickScale = sr / t.timescale
+ local gapless = o.gapless ~= false
+ local skip = if gapless then math.floor(t.skip * tickScale + 0.5) else 0
+ local total = 0
+ for i = 1, t.sampleCount do
+ total += t.durations[i]
+ end
+ total = math.floor(total * tickScale + 0.5)
+ if gapless and t.playDuration then
+ total = math.min(total, skip + math.floor(t.playDuration * tickScale + 0.5))
+ end
+ local tags, pictures = IsoBmff.tags(r, movie)
+ -- iTunes gapless info (fdkaac, iTunes) when there is no edit list: " 0 ..." (hex)
+ local smpb = tags.iTunSMPB
+ if gapless and not t.edits and smpb then
+ local f = {}
+ for w in string.gmatch(smpb, "%x+") do
+ table.insert(f, tonumber(w, 16))
+ end
+ if #f >= 4 and f[2] and f[4] and f[4] > 0 and f[2] + f[4] <= total then
+ skip = f[2]
+ total = f[2] + f[4]
+ end
+ end
+ local frames = math.max(0, total - skip)
+ local buf = r.buf
+ -- streaming state
+ local nextPacket = 1
+ local decoded = 0 -- frames produced by the packets decoded so far (before trimming)
+ local pend, pendPos, pendN = p.pcm, 0, 0 -- the current packet: frames pendPos .. pendN - 1 not yet returned
+ local dropUntil = skip -- absolute frame index of the first frame to return
+ local stopAt = total
+ local pos = 0 -- frames returned
+ local failed: Err.Err? = nil
+
+ local dec: any = {
+ sampleRate = sr,
+ channels = channels,
+ frames = frames,
+ duration = frames / sr,
+ bitrate = 0,
+ tags = tags,
+ pictures = pictures,
+ codec = t.codec,
+ track = t,
+ movie = movie,
+ error = nil,
+ }
+ local bytes = 0
+ for i = 1, t.sampleCount do
+ bytes += t.sizes[i]
+ end
+ dec.bitrate = if frames > 0 then math.floor(bytes * 8 * sr / frames) else (t.bitrate or 0)
+
+ -- decode the next packet into pend; false at the end / on an error
+ local function fill(): boolean
+ while true do
+ if nextPacket > t.sampleCount or decoded >= stopAt then
+ return false
+ end
+ local i = nextPacket
+ nextPacket += 1
+ local start = decoded
+ local n, e = p.decode(buf, t.offsets[i], t.sizes[i])
+ if not n then
+ failed = e
+ dec.error = e
+ return false
+ end
+ decoded += n
+ -- the part of this packet inside [dropUntil, stopAt)
+ local a = math.max(start, dropUntil)
+ local b = math.min(decoded, stopAt)
+ if b > a then
+ pendPos = a - start
+ pendN = b - start
+ return true
+ end
+ end
+ end
+
+ function dec.read(_self: any, n: number, out: buffer?): (buffer, number)
+ local want = math.max(0, math.floor(n))
+ local need = want * channels * 4
+ local ob = if out and buffer.len(out) >= need then out else buffer.create(need)
+ local got = 0
+ local writef32 = buffer.writef32
+ while got < want do
+ if pendPos >= pendN then
+ if failed or not fill() then
+ break
+ end
+ end
+ local take = math.min(want - got, pendN - pendPos)
+ local src = pend
+ local o = got * channels * 4
+ local s = pendPos * channels
+ for k = 1, take * channels do
+ writef32(ob, o, src[s + k])
+ o += 4
+ end
+ pendPos += take
+ got += take
+ end
+ pos += got
+ return ob, got
+ end
+
+ function dec.seek(_self: any, seconds: number)
+ local target = math.clamp(math.floor(seconds * sr + 0.5), 0, frames) + skip -- absolute frame
+ -- the last packet starting at or before the target, minus one for the codec's overlap (AAC)
+ local ticks = target / tickScale
+ local lo, hi, found = 1, t.sampleCount, 1
+ while lo <= hi do
+ local mid = (lo + hi) // 2
+ if t.dts[mid] <= ticks then
+ found = mid
+ lo = mid + 1
+ else
+ hi = mid - 1
+ end
+ end
+ local startPacket = if t.codec == "aac" then math.max(1, found - 1) else found
+ p.reset()
+ nextPacket = startPacket
+ decoded = math.floor((t.dts[startPacket] or 0) * tickScale + 0.5)
+ dropUntil = math.max(target, skip)
+ pendPos, pendN = 0, 0
+ failed = nil
+ pos = target - skip
+ end
+
+ function dec.position(_self: any): number
+ return pos / sr
+ end
+
+ -- prime: surface a broken first packet as an open error
+ if t.sampleCount > 0 and frames > 0 then
+ if not fill() and failed then
+ return nil, failed
+ end
+ end
+ return dec, nil
+end
+
+-- decode(r, opts?) -> Types.Audio | nil, Err (the whole stream, tags, cover pictures in meta.pictures)
+function M4a.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?)
+ local dec, err = M4a.open(r, opts)
+ if not dec then
+ return nil, err
+ end
+ local d: any = dec
+ local audio = Types.Audio.new(d.sampleRate, d.channels, d.frames)
+ local done = 0
+ local chunk = buffer.create(65536 * d.channels * 4)
+ while done < d.frames do
+ local b, n = d:read(math.min(65536, d.frames - done), chunk)
+ if n == 0 then
+ break
+ end
+ buffer.copy(audio.samples, done * d.channels * 4, b, 0, n * d.channels * 4)
+ done += n
+ end
+ if d.error then
+ return nil, d.error
+ end
+ if done < d.frames then
+ local short = buffer.create(done * d.channels * 4)
+ buffer.copy(short, 0, audio.samples, 0, buffer.len(short))
+ audio.samples = short
+ audio.frames = done
+ end
+ audio.tags = d.tags
+ audio.meta.source = { format = "m4a", codec = d.codec, bitsPerSample = d.track.bitsPerSample, brand = d.movie.brand }
+ if #d.pictures > 0 then
+ audio.meta.pictures = d.pictures
+ end
+ return audio, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+-- encode(audio | decoder, opts?) -> buffer | nil, Err: an ALAC M4A
+function M4a.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
+ local o = opts or {}
+ if type(value) ~= "table" or type(value.sampleRate) ~= "number" or type(value.channels) ~= "number" then
+ return nil, Err.new(Err.ARG, "expected an Audio or a Decoder")
+ end
+ local sr, ch = value.sampleRate, value.channels
+ local enc, eerr = Alac.encoder({ sampleRate = sr, channels = ch, bitDepth = o.bitDepth or 16, frameLength = o.frameLength })
+ if not enc then
+ return nil, eerr
+ end
+ local e = enc :: Alac.Encoder
+ local depth = e.config.bitDepth
+ local fl = e.config.frameLength
+ local peak = 2 ^ (depth - 1)
+ local packets: { buffer } = {}
+ local durations: { number } = {}
+ local ints = table.create(fl * ch, 0)
+ local floor = math.floor
+ local readf32 = buffer.readf32
+ -- frames from an Audio buffer or a streaming Decoder
+ local src: buffer, srcFrames = nil :: any, 0
+ local isAudio = value.kind == "audio" and type(value.samples) == "buffer"
+ if isAudio then
+ src, srcFrames = value.samples, value.frames
+ if buffer.len(src) < srcFrames * ch * 4 then
+ return nil, Err.new(Err.ARG, "audio.samples is shorter than frames * channels")
+ end
+ elseif type(value.read) ~= "function" then
+ return nil, Err.new(Err.ARG, "expected an Audio or a Decoder")
+ end
+ local done = 0
+ local chunk: buffer? = nil
+ while true do
+ local n, b, base
+ if isAudio then
+ n = math.min(fl, srcFrames - done)
+ b, base = src, done * ch * 4
+ else
+ local got
+ b, got = value:read(fl, chunk)
+ chunk = b
+ n, base = got, 0
+ end
+ if n <= 0 then
+ break
+ end
+ for i = 0, n * ch - 1 do
+ local v = floor(readf32(b, base + i * 4) * peak + 0.5)
+ if v >= peak then
+ v = peak - 1
+ elseif v < -peak then
+ v = -peak
+ end
+ ints[i + 1] = v
+ end
+ local pkt, perr = e:encode(ints, 1, n)
+ if not pkt then
+ return nil, perr
+ end
+ table.insert(packets, pkt)
+ table.insert(durations, n)
+ done += n
+ if isAudio and done >= srcFrames then
+ break
+ end
+ end
+ local tags = o.tags or value.tags or {}
+ local pictures = o.pictures or (value.meta and value.meta.pictures) or nil
+ local timescale = if sr < 65536 then sr else 0
+ local file, merr = IsoBmff.mux({
+ brand = "M4A ",
+ minor = 0,
+ compatible = { "M4A ", "mp42", "isom" },
+ timescale = 1000,
+ tracks = {
+ {
+ kind = "audio",
+ entry = "alac",
+ timescale = if timescale > 0 then timescale else 48000,
+ samples = packets,
+ durations = if timescale > 0 then durations else (function()
+ local d = {}
+ for i, v in durations do
+ d[i] = math.floor(v * 48000 / sr + 0.5)
+ end
+ return d
+ end)(),
+ sampleRate = sr,
+ channels = ch,
+ bitsPerSample = depth,
+ config = Alac.cookie(e.config),
+ },
+ },
+ tags = tags,
+ pictures = pictures,
+ })
+ if not file then
+ return nil, merr
+ end
+ return file, nil
+end
+
+return M4a
diff --git a/src/Formats/audio/opus/CeltEncoder.luau b/src/Formats/audio/opus/CeltEncoder.luau
new file mode 100644
index 0000000..7c8225a
--- /dev/null
+++ b/src/Formats/audio/opus/CeltEncoder.luau
@@ -0,0 +1,1078 @@
+--!strict
+--!native
+--!optimize 2
+-- audio/opus/CeltEncoder: a fixed-frame CELT encoder (RFC 6716 section 5.3): 20 ms frames (LM 3), full band, constant
+-- bit rate, long MDCTs only (no transient detection), no pitch pre-filter, normal spreading, default allocation trim,
+-- mono, or stereo as mid / side per band (the angle, intensity when it has no bits; dual L / R stereo on request). The bitstream side is a port of the libopus 1.6 encoder paths
+-- (celt_encoder.c, quant_bands.c, laplace.c, rate.c, bands.c, vq.c, cwrs.c; BSD: licenses/libopus-BSD.txt) that
+-- mirror audio/opus/Celt's decoder step for step; the analysis is simplified. The MDCT is codecs/Mdct.
+-- Never throws.
+local RE = require("@formats/audio/opus/RangeEncoder")
+local T = require("@formats/audio/opus/CeltTables")
+local Mdct = require("@formats/codecs/Mdct")
+
+local CeltEncoder = {}
+
+local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift
+local min, max, sqrt, floor, cos, log, atan2 = math.min, math.max, math.sqrt, math.floor, math.cos, math.log, math.atan2
+local encBitLogp, encIcdf, encBits, encUint, encEncode, encEncodeBin = RE.bitLogp, RE.icdf, RE.bits, RE.uint, RE.encode, RE.encodeBin
+local tell, tellFrac = RE.tell, RE.tellFrac
+
+local NB_EBANDS = 21
+local OVERLAP = 120
+local SHORT_MDCT = 120
+local BITRES = 3
+local MAX_FINE_BITS = 8
+local FINE_OFFSET = 21
+local QTHETA_OFFSET = 4
+local PREEMPH = 0.85000610
+local LM = 3 -- 20 ms frames
+local M = 8
+local N = 960
+
+local EB = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 34, 40, 48, 60, 78, 100 }
+local ALLOC = {
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 90, 80, 75, 69, 63, 56, 49, 40, 34, 29, 20, 18, 10, 0, 0, 0, 0, 0, 0, 0, 0,
+ 110, 100, 90, 84, 78, 71, 65, 58, 51, 45, 39, 32, 26, 20, 12, 0, 0, 0, 0, 0, 0,
+ 118, 110, 103, 93, 86, 80, 75, 70, 65, 59, 53, 47, 40, 31, 23, 15, 4, 0, 0, 0, 0,
+ 126, 119, 112, 104, 95, 89, 83, 78, 72, 66, 60, 54, 47, 39, 32, 25, 17, 12, 1, 0, 0,
+ 134, 127, 120, 114, 103, 97, 91, 85, 78, 72, 66, 60, 54, 47, 41, 35, 29, 23, 16, 10, 1,
+ 144, 137, 130, 124, 113, 107, 101, 95, 88, 82, 76, 70, 64, 57, 51, 45, 39, 33, 26, 15, 1,
+ 152, 145, 138, 132, 123, 117, 111, 105, 98, 92, 86, 80, 74, 67, 61, 55, 49, 43, 36, 20, 1,
+ 162, 155, 148, 142, 133, 127, 121, 115, 108, 102, 96, 90, 84, 77, 71, 65, 59, 53, 46, 30, 1,
+ 172, 165, 158, 152, 143, 137, 131, 125, 118, 112, 106, 100, 94, 87, 81, 75, 69, 63, 56, 45, 20,
+ 200, 200, 200, 200, 200, 200, 200, 200, 198, 193, 188, 183, 178, 173, 168, 163, 158, 153, 148, 129, 104,
+}
+local NB_ALLOC_VECTORS = 11
+local LOG2_FRAC_TABLE = { 0, 8, 13, 16, 19, 21, 23, 24, 26, 27, 28, 29, 30, 31, 32, 32, 33, 34, 34, 35, 36, 36, 37, 37 }
+local LOGN = T.logN400
+local CACHE_INDEX = T.cache_index50
+local CACHE_BITS = T.cache_bits50
+local CACHE_CAPS = T.cache_caps50
+local E_PROB = T.e_prob_model
+local E_MEANS = {
+ 6.437500, 6.250000, 5.750000, 5.312500, 5.062500, 4.812500, 4.500000, 4.375000, 4.875000, 4.687500,
+ 4.562500, 4.437500, 4.875000, 4.625000, 4.312500, 4.500000, 4.375000, 4.625000, 4.750000, 4.437500,
+ 3.750000,
+}
+local PRED_COEF = { 29440 / 32768, 26112 / 32768, 21248 / 32768, 16384 / 32768 }
+local BETA_COEF = { 30147 / 32768, 22282 / 32768, 12124 / 32768, 6554 / 32768 }
+local BETA_INTRA = 4915 / 32768
+local TF_SELECT = { 0, -2, 0, -3, 3, 0, 1, -1 } -- LM 3
+local TRIM_ICDF = { 126, 124, 119, 109, 87, 41, 19, 9, 4, 2, 0 }
+local SPREAD_ICDF = { 25, 23, 2, 0 }
+local SMALL_ENERGY_ICDF = { 2, 1, 0 }
+local EXP2_TABLE8 = { 16384, 17866, 19483, 21247, 23170, 25267, 27554, 30048 }
+local SPREAD_NORMAL = 2
+local SPREAD_FACTOR = { 15, 10, 5 }
+
+-- the MDCT window (the decoder's) and plan
+local WINDOW = table.create(OVERLAP, 0)
+for i = 0, OVERLAP - 1 do
+ local s = math.sin(0.5 * math.pi * (i + 0.5) / OVERLAP)
+ WINDOW[i + 1] = math.sin(0.5 * math.pi * s * s)
+end
+local PLAN = Mdct.new(2 * N) :: Mdct.Plan
+-- forward scale matching the decoder's backward MDCT (calibrated against audio/opus/Mdct: tests/audio/opus_encode)
+local MDCT_SCALE = 2 / N
+
+-- PVQ codebook sizes U(n, k), flat: U[n * UK + k + 1]
+local UK = 177
+local U = table.create(UK * UK, 0)
+U[1] = 1
+for n = 1, UK - 1 do
+ for k = 1, UK - 1 do
+ U[n * UK + k + 1] = U[(n - 1) * UK + k + 1] + U[n * UK + k] + U[(n - 1) * UK + k]
+ end
+end
+local function pvqU(n: number, k: number): number
+ return U[n * UK + k + 1]
+end
+
+local function imin(a: number, b: number): number
+ return if a < b then a else b
+end
+local function imax(a: number, b: number): number
+ return if a > b then a else b
+end
+local function tdiv(a: number, b: number): number
+ local q = a / b
+ return if q >= 0 then floor(q) else -floor(-q)
+end
+local function fracMul16(a: number, b: number): number
+ return (16384 + a * b) // 32768
+end
+local function bitexactCos(x: number): number
+ local x2 = (4096 + x * x) // 8192
+ x2 = (32767 - x2) + fracMul16(x2, (-7651 + fracMul16(x2, (8277 + fracMul16(-626, x2)))))
+ return 1 + x2
+end
+local function bitexactLog2tan(isin: number, icos: number): number
+ local lc = RE.ilog(icos)
+ local ls = RE.ilog(isin)
+ icos = icos * 2 ^ (15 - lc)
+ isin = isin * 2 ^ (15 - ls)
+ return (ls - lc) * 2048 + fracMul16(isin, fracMul16(isin, -2597) + 7932) - fracMul16(icos, fracMul16(icos, -2597) + 7932)
+end
+
+-- ------------------------------------------------------------------------------------------------ energy
+-- ec_laplace_encode: returns the value actually coded (clamped in the flat tail)
+local function laplaceEncode(enc: RE.Enc, value: number, fs: number, decay: number): number
+ local fl = 0
+ local val = value
+ if val ~= 0 then
+ local s = if val < 0 then -1 else 0
+ val = if val < 0 then -val else val
+ fl = fs
+ fs = ((32768 - 32 - fs) * (16384 - decay)) // 32768 -- ec_laplace_get_freq1
+ local i = 1
+ while fs > 0 and i < val do
+ fs *= 2
+ fl += fs + 2
+ fs = (fs * decay) // 32768
+ i += 1
+ end
+ if fs == 0 then
+ local ndiMax = 32768 - fl + 1 - 1
+ ndiMax = rshift(ndiMax - s, 1)
+ local di = imin(val - i, ndiMax - 1)
+ fl += (2 * di + 1 + s)
+ fs = imin(1, 32768 - fl)
+ value = if s ~= 0 then -(i + di) else i + di
+ else
+ fs += 1
+ if s == 0 then
+ fl += fs
+ end
+ end
+ end
+ encEncodeBin(enc, fl, fl + fs, 15)
+ return value
+end
+
+export type State = {
+ channels: number,
+ oldBandE: { number }, -- the decoder's view (2 * 21)
+ preMem: { number },
+ inMem: { { number } }, -- the last OVERLAP pre-emphasised samples per channel
+ frames: number,
+ X: { { number } }, -- per channel 960 normalised coefficients
+ bandLogE: { number },
+ bandE: { number }, -- linear band amplitudes (intensity stereo weights)
+ error: { number },
+ work: { number },
+ tmp: { number },
+ iy: { number },
+ remaining: number,
+ spread: number,
+ dual: boolean, -- stereo: L / R coded independently (default false: mid / side)
+}
+
+-- new(channels) -> State
+function CeltEncoder.new(channels: number): State
+ local inMem = {}
+ local X = {}
+ for c = 1, channels do
+ inMem[c] = table.create(OVERLAP, 0)
+ X[c] = table.create(N, 0)
+ end
+ return {
+ channels = channels,
+ oldBandE = table.create(2 * NB_EBANDS, 0),
+ preMem = table.create(channels, 0),
+ inMem = inMem,
+ frames = 0,
+ X = X,
+ bandLogE = table.create(2 * NB_EBANDS, 0),
+ bandE = table.create(2 * NB_EBANDS, 0),
+ error = table.create(2 * NB_EBANDS, 0),
+ work = table.create(2 * N, 0),
+ tmp = table.create(2 * N, 0),
+ iy = table.create(256, 0),
+ remaining = 0,
+ spread = SPREAD_NORMAL,
+ dual = false,
+ }
+end
+
+local function quantCoarseEnergy(st: State, intra: boolean, enc: RE.Enc, C: number, budget: number, nbBytes: number)
+ local oldE, bandLogE, err = st.oldBandE, st.bandLogE, st.error
+ local probBase = LM * 84 + (if intra then 42 else 0)
+ local coef, beta
+ if intra then
+ coef, beta = 0, BETA_INTRA
+ else
+ coef, beta = PRED_COEF[LM + 1], BETA_COEF[LM + 1]
+ end
+ local maxDecay = min(16, nbBytes / 8)
+ local prev0, prev1 = 0, 0
+ for i = 0, NB_EBANDS - 1 do
+ for c = 0, C - 1 do
+ local k = c * NB_EBANDS + i + 1
+ local x = bandLogE[k]
+ local e = max(-9, oldE[k])
+ local prev = if c == 0 then prev0 else prev1
+ local f = x - coef * e - prev
+ local qi = floor(0.5 + f)
+ local decayBound = max(-28, oldE[k]) - maxDecay
+ if qi < 0 and x < decayBound then
+ qi += tdiv(decayBound - x, 1)
+ if qi > 0 then
+ qi = 0
+ end
+ end
+ local t = tell(enc)
+ local bitsLeft = budget - t - 3 * C * (NB_EBANDS - i)
+ if i ~= 0 and bitsLeft < 30 then
+ if bitsLeft < 24 then
+ qi = imin(1, qi)
+ end
+ if bitsLeft < 16 then
+ qi = imax(-1, qi)
+ end
+ end
+ if budget - t >= 15 then
+ local pi = 2 * imin(i, 20)
+ qi = laplaceEncode(enc, qi, E_PROB[probBase + pi + 1] * 128, E_PROB[probBase + pi + 2] * 64)
+ elseif budget - t >= 2 then
+ qi = imax(-1, imin(qi, 1))
+ encIcdf(enc, if qi < 0 then 1 else 2 * qi, SMALL_ENERGY_ICDF, 2)
+ elseif budget - t >= 1 then
+ qi = imin(0, qi)
+ encBitLogp(enc, qi ~= 0, 1)
+ else
+ qi = -1
+ end
+ err[k] = f - qi
+ oldE[k] = coef * e + prev + qi
+ prev = prev + qi - beta * qi
+ if c == 0 then
+ prev0 = prev
+ else
+ prev1 = prev
+ end
+ end
+ end
+end
+
+local function quantFineEnergy(st: State, fineQuant: { number }, enc: RE.Enc, C: number)
+ local oldE, err = st.oldBandE, st.error
+ for i = 0, NB_EBANDS - 1 do
+ local extra = fineQuant[i + 1]
+ if extra <= 0 then
+ continue
+ end
+ if tell(enc) + C * extra > enc.storage * 8 then
+ continue
+ end
+ local frac = 2 ^ extra
+ for c = 0, C - 1 do
+ local k = c * NB_EBANDS + i + 1
+ local q2 = floor((err[k] + 0.5) * frac)
+ q2 = math.clamp(q2, 0, frac - 1)
+ encBits(enc, q2, extra)
+ local offset = (q2 + 0.5) * 2 ^ (14 - extra) * (1 / 16384) - 0.5
+ oldE[k] += offset
+ err[k] -= offset
+ end
+ end
+end
+
+local function quantEnergyFinalise(st: State, fineQuant: { number }, finePriority: { number }, bitsLeft: number, enc: RE.Enc, C: number)
+ local oldE, err = st.oldBandE, st.error
+ for prio = 0, 1 do
+ local i = 0
+ while i < NB_EBANDS and bitsLeft >= C do
+ if fineQuant[i + 1] >= MAX_FINE_BITS or finePriority[i + 1] ~= prio then
+ i += 1
+ continue
+ end
+ for c = 0, C - 1 do
+ local k = c * NB_EBANDS + i + 1
+ local q2 = if err[k] < 0 then 0 else 1
+ encBits(enc, q2, 1)
+ local offset = (q2 - 0.5) * 2 ^ (14 - fineQuant[i + 1] - 1) * (1 / 16384)
+ oldE[k] += offset
+ err[k] -= offset
+ bitsLeft -= 1
+ end
+ i += 1
+ end
+ end
+end
+
+-- ------------------------------------------------------------------------------------------------ allocation
+local function bits2pulses(bandI: number, lm: number, bits: number): number
+ local base = CACHE_INDEX[(lm + 1) * NB_EBANDS + bandI + 1]
+ local lo, hi = 0, CACHE_BITS[base + 1]
+ bits -= 1
+ for _ = 1, 6 do
+ local mid = rshift(lo + hi + 1, 1)
+ if CACHE_BITS[base + mid + 1] >= bits then
+ hi = mid
+ else
+ lo = mid
+ end
+ end
+ local loBits = if lo == 0 then -1 else CACHE_BITS[base + lo + 1]
+ if bits - loBits <= CACHE_BITS[base + hi + 1] - bits then
+ return lo
+ end
+ return hi
+end
+
+local function pulses2bits(bandI: number, lm: number, pulses: number): number
+ if pulses == 0 then
+ return 0
+ end
+ local base = CACHE_INDEX[(lm + 1) * NB_EBANDS + bandI + 1]
+ return CACHE_BITS[base + pulses + 1] + 1
+end
+
+local function getPulses(i: number): number
+ if i < 8 then
+ return i
+ end
+ return lshift(8 + band(i, 7), rshift(i, 3) - 1)
+end
+
+-- clt_compute_allocation (encoder side): keeps every band it can, no intensity stereo, dual stereo for C == 2
+local function computeAllocation(offsets: { number }, cap: { number }, allocTrim: number, total: number,
+ pulses: { number }, ebits: { number }, finePriority: { number }, C: number, enc: RE.Enc, wantDual: boolean)
+ local start, endb = 0, NB_EBANDS
+ total = imax(total, 0)
+ local len = NB_EBANDS
+ local skipStart = start
+ local skipRsv = if total >= 8 then 8 else 0
+ total -= skipRsv
+ local intensityRsv, dualStereoRsv = 0, 0
+ if C == 2 then
+ intensityRsv = LOG2_FRAC_TABLE[endb - start + 1]
+ if intensityRsv > total then
+ intensityRsv = 0
+ else
+ total -= intensityRsv
+ dualStereoRsv = if total >= 8 then 8 else 0
+ total -= dualStereoRsv
+ end
+ end
+ local bits1, bits2, thresh, trimOffset = {}, {}, {}, {}
+ for j = start, endb - 1 do
+ local w = EB[j + 2] - EB[j + 1]
+ thresh[j + 1] = imax(C * 8, (3 * w * 2 ^ LM * 8) // 16)
+ trimOffset[j + 1] = (C * w * (allocTrim - 5 - LM) * (endb - j - 1) * 2 ^ (LM + BITRES)) // 64
+ if w * 2 ^ LM == 1 then
+ trimOffset[j + 1] -= C * 8
+ end
+ end
+ local lo, hi = 1, NB_ALLOC_VECTORS - 1
+ repeat
+ local done = false
+ local psum = 0
+ local mid = rshift(lo + hi, 1)
+ for j = endb - 1, start, -1 do
+ local Nw = EB[j + 2] - EB[j + 1]
+ local bitsj = (C * Nw * ALLOC[mid * len + j + 1] * 2 ^ LM) // 4
+ if bitsj > 0 then
+ bitsj = imax(0, bitsj + trimOffset[j + 1])
+ end
+ bitsj += offsets[j + 1]
+ if bitsj >= thresh[j + 1] or done then
+ done = true
+ psum += imin(bitsj, cap[j + 1])
+ elseif bitsj >= C * 8 then
+ psum += C * 8
+ end
+ end
+ if psum > total then
+ hi = mid - 1
+ else
+ lo = mid + 1
+ end
+ until lo > hi
+ hi = lo
+ lo -= 1
+ for j = start, endb - 1 do
+ local Nw = EB[j + 2] - EB[j + 1]
+ local bits1j = (C * Nw * ALLOC[lo * len + j + 1] * 2 ^ LM) // 4
+ local bits2j = if hi >= NB_ALLOC_VECTORS then cap[j + 1] else (C * Nw * ALLOC[hi * len + j + 1] * 2 ^ LM) // 4
+ if bits1j > 0 then
+ bits1j = imax(0, bits1j + trimOffset[j + 1])
+ end
+ if bits2j > 0 then
+ bits2j = imax(0, bits2j + trimOffset[j + 1])
+ end
+ if lo > 0 then
+ bits1j += offsets[j + 1]
+ end
+ bits2j += offsets[j + 1]
+ if offsets[j + 1] > 0 then
+ skipStart = j
+ end
+ bits2j = imax(0, bits2j - bits1j)
+ bits1[j + 1] = bits1j
+ bits2[j + 1] = bits2j
+ end
+ -- interp_bits2pulses
+ local bits = pulses
+ local allocFloor = C * 8
+ local stereo = if C > 1 then 1 else 0
+ local logM = LM * 8
+ lo, hi = 0, 64
+ for _ = 1, 6 do
+ local mid = rshift(lo + hi, 1)
+ local psum = 0
+ local done = false
+ for j = endb - 1, start, -1 do
+ local tmp = bits1[j + 1] + (mid * bits2[j + 1]) // 64
+ if tmp >= thresh[j + 1] or done then
+ done = true
+ psum += imin(tmp, cap[j + 1])
+ elseif tmp >= allocFloor then
+ psum += allocFloor
+ end
+ end
+ if psum > total then
+ hi = mid
+ else
+ lo = mid
+ end
+ end
+ local psum = 0
+ local done = false
+ for j = endb - 1, start, -1 do
+ local tmp = bits1[j + 1] + (lo * bits2[j + 1]) // 64
+ if tmp < thresh[j + 1] and not done then
+ if tmp >= allocFloor then
+ tmp = allocFloor
+ else
+ tmp = 0
+ end
+ else
+ done = true
+ end
+ tmp = imin(tmp, cap[j + 1])
+ bits[j + 1] = tmp
+ psum += tmp
+ end
+ local codedBands = endb
+ while true do
+ local j = codedBands - 1
+ if j <= skipStart then
+ total += skipRsv
+ break
+ end
+ local left = total - psum
+ local percoeff = left // (EB[codedBands + 1] - EB[start + 1])
+ left -= (EB[codedBands + 1] - EB[start + 1]) * percoeff
+ local rem = imax(left - (EB[j + 1] - EB[start + 1]), 0)
+ local bandWidth = EB[codedBands + 1] - EB[j + 1]
+ local bandBits = bits[j + 1] + percoeff * bandWidth + rem
+ if bandBits >= imax(thresh[j + 1], allocFloor + 8) then
+ -- keep every band that can be coded: signal "no more skipping"
+ encBitLogp(enc, true, 1)
+ break
+ end
+ psum -= bits[j + 1] + intensityRsv
+ if intensityRsv > 0 then
+ intensityRsv = LOG2_FRAC_TABLE[j - start + 1]
+ end
+ psum += intensityRsv
+ if bandBits >= allocFloor then
+ psum += allocFloor
+ bits[j + 1] = allocFloor
+ else
+ bits[j + 1] = 0
+ end
+ codedBands -= 1
+ end
+ local intensity, dualStereo = 0, false
+ if intensityRsv > 0 then
+ intensity = codedBands -- no intensity stereo
+ encUint(enc, intensity - start, codedBands + 1 - start)
+ end
+ if intensity <= start then
+ total += dualStereoRsv
+ dualStereoRsv = 0
+ end
+ if dualStereoRsv > 0 then
+ dualStereo = wantDual
+ encBitLogp(enc, dualStereo, 1)
+ end
+ local left = total - psum
+ local percoeff = left // (EB[codedBands + 1] - EB[start + 1])
+ left -= (EB[codedBands + 1] - EB[start + 1]) * percoeff
+ for j = start, codedBands - 1 do
+ bits[j + 1] += percoeff * (EB[j + 2] - EB[j + 1])
+ end
+ for j = start, codedBands - 1 do
+ local tmp = imin(left, EB[j + 2] - EB[j + 1])
+ bits[j + 1] += tmp
+ left -= tmp
+ end
+ local balance = 0
+ local j = start
+ while j < codedBands do
+ local N0 = EB[j + 2] - EB[j + 1]
+ local Nw = N0 * 2 ^ LM
+ local bit = bits[j + 1] + balance
+ local excess
+ if Nw > 1 then
+ excess = imax(bit - cap[j + 1], 0)
+ bits[j + 1] = bit - excess
+ local den = C * Nw + (if C == 2 and Nw > 2 and not dualStereo and j < intensity then 1 else 0)
+ local NClogN = den * (LOGN[j + 1] + logM)
+ local offset = (NClogN // 2) - den * FINE_OFFSET
+ if Nw == 2 then
+ offset += (den * 8) // 4
+ end
+ if bits[j + 1] + offset < den * 2 * 8 then
+ offset += NClogN // 4
+ elseif bits[j + 1] + offset < den * 3 * 8 then
+ offset += NClogN // 8
+ end
+ local eb = imax(0, bits[j + 1] + offset + den * 4)
+ eb = (eb // den) // 8
+ if C * eb > (bits[j + 1] // 8) then
+ eb = (bits[j + 1] // 2 ^ stereo) // 8
+ end
+ eb = imin(eb, MAX_FINE_BITS)
+ finePriority[j + 1] = if eb * (den * 8) >= bits[j + 1] + offset then 1 else 0
+ bits[j + 1] -= C * eb * 8
+ ebits[j + 1] = eb
+ else
+ excess = imax(0, bit - C * 8)
+ bits[j + 1] = bit - excess
+ ebits[j + 1] = 0
+ finePriority[j + 1] = 1
+ end
+ if excess > 0 then
+ local extraFine = imin(excess // 2 ^ (stereo + BITRES), MAX_FINE_BITS - ebits[j + 1])
+ ebits[j + 1] += extraFine
+ local extraBits = extraFine * C * 8
+ finePriority[j + 1] = if extraBits >= excess - balance then 1 else 0
+ excess -= extraBits
+ end
+ balance = excess
+ j += 1
+ end
+ while j < endb do
+ ebits[j + 1] = (bits[j + 1] // 2 ^ stereo) // 8
+ bits[j + 1] = 0
+ finePriority[j + 1] = if ebits[j + 1] < 1 then 1 else 0
+ j += 1
+ end
+ return codedBands, balance, intensity, dualStereo
+end
+
+-- ------------------------------------------------------------------------------------------------ PVQ
+-- icwrs: the index of the pulse vector iy[1..n]
+local function icwrs(n: number, iy: { number }): number
+ local j = n -- 1-based position of _y[n - 1]
+ local i = if iy[j] < 0 then 1 else 0
+ local k = math.abs(iy[j])
+ repeat
+ j -= 1
+ local nn = n - (j - 1) -- _n - j with 0-based j
+ i += pvqU(nn, k)
+ k += math.abs(iy[j])
+ if iy[j] < 0 then
+ i += pvqU(nn, k + 1)
+ end
+ until j <= 1
+ return i
+end
+
+local function expRotation1(X: { number }, xo: number, len: number, stride: number, c: number, s: number)
+ local ms = -s
+ local p = xo + 1
+ for _ = 0, len - stride - 1 do
+ local x1 = X[p]
+ local x2 = X[p + stride]
+ X[p + stride] = c * x2 + s * x1
+ X[p] = c * x1 + ms * x2
+ p += 1
+ end
+ p = xo + len - 2 * stride
+ for _ = len - 2 * stride - 1, 0, -1 do
+ local x1 = X[p]
+ local x2 = X[p + stride]
+ X[p + stride] = c * x2 + s * x1
+ X[p] = c * x1 + ms * x2
+ p -= 1
+ end
+end
+
+-- exp_rotation(X, len, dir = 1, stride, K, spread): the encoder's spreading rotation
+local function expRotation(X: { number }, xo: number, len: number, stride: number, K: number, spread: number)
+ if 2 * K >= len or spread == 0 then
+ return
+ end
+ local factor = SPREAD_FACTOR[spread]
+ local gain = len / (len + factor * K)
+ local theta = 0.5 * (gain * gain)
+ local c = cos(0.5 * math.pi * theta)
+ local s = cos(0.5 * math.pi * (1 - theta))
+ local stride2 = 0
+ if len >= 8 * stride then
+ stride2 = 1
+ while (stride2 * stride2 + stride2) * stride + rshift(stride, 2) < len do
+ stride2 += 1
+ end
+ end
+ len = len // stride
+ for i = 0, stride - 1 do
+ local x = xo + i * len
+ expRotation1(X, x, len, 1, c, -s)
+ if stride2 ~= 0 then
+ expRotation1(X, x, len, stride2, s, -c)
+ end
+ end
+end
+
+-- op_pvq_search: the K-pulse vector closest to X[xo + 1 .. xo + n] into iy[1..n]
+local function pvqSearch(X: { number }, xo: number, n: number, K: number, iy: { number }, y: { number }, absx: { number })
+ local sign = y -- reuse: y holds 2 * |pulses| during the search, signs kept in absx's sign
+ local xy, yy = 0, 0
+ local pulsesLeft = K
+ for j = 1, n do
+ local v = X[xo + j]
+ absx[j] = if v < 0 then -v else v
+ sign[j] = 0
+ iy[j] = 0
+ end
+ if K > rshift(n, 1) then
+ local sum = 0
+ for j = 1, n do
+ sum += absx[j]
+ end
+ if not (sum > 1e-15 and sum < 64) then
+ absx[1] = 1
+ for j = 2, n do
+ absx[j] = 0
+ end
+ sum = 1
+ end
+ local rcp = (K + 0.8) / sum
+ for j = 1, n do
+ local p = floor(rcp * absx[j])
+ iy[j] = p
+ yy += p * p
+ xy += absx[j] * p
+ sign[j] = 2 * p
+ pulsesLeft -= p
+ end
+ end
+ if pulsesLeft > n + 3 then
+ yy += pulsesLeft * pulsesLeft + pulsesLeft * sign[1]
+ iy[1] += pulsesLeft
+ pulsesLeft = 0
+ end
+ for _ = 1, pulsesLeft do
+ yy += 1
+ local best = 1
+ local rxy = xy + absx[1]
+ local bestNum = rxy * rxy
+ local bestDen = yy + sign[1]
+ for j = 2, n do
+ rxy = xy + absx[j]
+ local num = rxy * rxy
+ local den = yy + sign[j]
+ if bestDen * num > den * bestNum then
+ bestDen, bestNum, best = den, num, j
+ end
+ end
+ xy += absx[best]
+ yy += sign[best]
+ sign[best] += 2
+ iy[best] += 1
+ end
+ for j = 1, n do
+ if X[xo + j] < 0 then
+ iy[j] = -iy[j]
+ end
+ end
+end
+
+local SCRATCH_Y = table.create(256, 0)
+local SCRATCH_A = table.create(256, 0)
+local ROT = table.create(256, 0)
+
+local function algQuant(st: State, X: { number }, xo: number, n: number, K: number, enc: RE.Enc)
+ -- rotate a copy (the original band stays for nothing else, but keep it intact)
+ for j = 1, n do
+ ROT[j] = X[xo + j]
+ end
+ expRotation(ROT, 0, n, 1, K, st.spread)
+ local iy = st.iy
+ pvqSearch(ROT, 0, n, K, iy, SCRATCH_Y, SCRATCH_A)
+ encUint(enc, icwrs(n, iy), pvqU(n, K) + pvqU(n, K + 1))
+end
+
+-- ------------------------------------------------------------------------------------------------ bands
+local function computeQn(n: number, b: number, offset: number, pulseCap: number): number
+ local N2 = 2 * n - 1
+ local qb = tdiv(b + N2 * offset, N2)
+ qb = imin(b - pulseCap - 32, qb)
+ qb = imin(64, qb)
+ if qb < 4 then
+ return 1
+ end
+ local qn = rshift(EXP2_TABLE8[band(qb, 7) + 1], 14 - rshift(qb, 3))
+ return lshift(rshift(qn + 1, 1), 1)
+end
+
+-- quant_partition (encoder, B = 1, mono): returns nothing (no resynthesis)
+local function quantPartition(st: State, bandI: number, X: { number }, xo: number, n: number, b: number, lm: number, enc: RE.Enc)
+ local split = false
+ if lm ~= -1 and n > 2 then
+ local base = CACHE_INDEX[(lm + 1) * NB_EBANDS + bandI + 1]
+ split = b > CACHE_BITS[base + CACHE_BITS[base + 1] + 1] + 12
+ end
+ if split then
+ n = rshift(n, 1)
+ local yo = xo + n
+ lm -= 1
+ -- compute_theta (mono split, B0 = 1: triangular pdf)
+ local pulseCap = LOGN[bandI + 1] + lm * 8
+ local offset = (pulseCap // 2) - QTHETA_OFFSET
+ local qn = computeQn(n, b, offset, pulseCap)
+ local t0 = tellFrac(enc)
+ local itheta = 0
+ if qn ~= 1 then
+ local emid, eside = 1e-15, 1e-15
+ for j = 1, n do
+ emid += X[xo + j] * X[xo + j]
+ eside += X[yo + j] * X[yo + j]
+ end
+ local it = floor(0.5 + 16384 * 0.63662 * atan2(sqrt(eside), sqrt(emid)))
+ itheta = (it * qn + 8192) // 16384
+ local h = rshift(qn, 1)
+ local ft = (h + 1) * (h + 1)
+ local fs = if itheta <= h then itheta + 1 else qn + 1 - itheta
+ local fl = if itheta <= h then rshift(itheta * (itheta + 1), 1) else ft - rshift((qn + 1 - itheta) * (qn + 2 - itheta), 1)
+ encEncode(enc, fl, fl + fs, ft)
+ itheta = (itheta * 16384) // qn
+ end
+ local qalloc = tellFrac(enc) - t0
+ b -= qalloc
+ local delta
+ if itheta == 0 then
+ delta = -16384
+ elseif itheta == 16384 then
+ delta = 16384
+ else
+ local imid = bitexactCos(itheta)
+ local iside = bitexactCos(16384 - itheta)
+ delta = fracMul16((n - 1) * 128, bitexactLog2tan(iside, imid))
+ end
+ local mbits = imax(0, imin(b, tdiv(b - delta, 2)))
+ local sbits = b - mbits
+ st.remaining -= qalloc
+ local rebalance = st.remaining
+ if mbits >= sbits then
+ quantPartition(st, bandI, X, xo, n, mbits, lm, enc)
+ rebalance = mbits - (rebalance - st.remaining)
+ if rebalance > 24 and itheta ~= 0 then
+ sbits += rebalance - 24
+ end
+ quantPartition(st, bandI, X, yo, n, sbits, lm, enc)
+ else
+ quantPartition(st, bandI, X, yo, n, sbits, lm, enc)
+ rebalance = sbits - (rebalance - st.remaining)
+ if rebalance > 24 and itheta ~= 16384 then
+ mbits += rebalance - 24
+ end
+ quantPartition(st, bandI, X, xo, n, mbits, lm, enc)
+ end
+ else
+ local q = bits2pulses(bandI, lm, b)
+ local currBits = pulses2bits(bandI, lm, q)
+ st.remaining -= currBits
+ while st.remaining < 0 and q > 0 do
+ st.remaining += currBits
+ q -= 1
+ currBits = pulses2bits(bandI, lm, q)
+ st.remaining -= currBits
+ end
+ if q ~= 0 then
+ algQuant(st, X, xo, n, getPulses(q), enc)
+ end
+ end
+end
+
+-- quant_band_stereo (encoder, N > 2, B = 1): the mid / side angle (step pdf), then mid and side as mono bands;
+-- qn == 1 falls back to intensity stereo (with the inversion bit when there is room)
+local function quantBandStereo(st: State, i: number, n: number, xo: number, b: number, enc: RE.Enc)
+ local L, R = st.X[1], st.X[2]
+ local pulseCap = LOGN[i + 1] + LM * 8
+ local offset = (pulseCap // 2) - QTHETA_OFFSET
+ local qn = computeQn(n, b, offset, pulseCap)
+ -- stereo_itheta: the angle between mid and side energies
+ local emid, eside = 1e-15, 1e-15
+ for j = 1, n do
+ local m = 0.5 * L[xo + j] + 0.5 * R[xo + j]
+ local sd = 0.5 * L[xo + j] - 0.5 * R[xo + j]
+ emid += m * m
+ eside += sd * sd
+ end
+ local itheta = floor(0.5 + 16384 * 0.63662 * atan2(sqrt(eside), sqrt(emid)))
+ local t0 = tellFrac(enc)
+ local function intensityStereo()
+ local left, right = st.bandE[i + 1], st.bandE[NB_EBANDS + i + 1]
+ local norm = 1e-15 + sqrt(1e-15 + left * left + right * right)
+ local a1, a2 = left / norm, right / norm
+ for j = 1, n do
+ L[xo + j] = a1 * L[xo + j] + a2 * R[xo + j]
+ end
+ end
+ if qn ~= 1 then
+ itheta = (itheta * qn + 8192) // 16384
+ local p0 = 3
+ local x0 = qn // 2
+ local ft = p0 * (x0 + 1) + x0
+ if itheta <= x0 then
+ encEncode(enc, p0 * itheta, p0 * (itheta + 1), ft)
+ else
+ encEncode(enc, (itheta - 1 - x0) + (x0 + 1) * p0, (itheta - x0) + (x0 + 1) * p0, ft)
+ end
+ itheta = (itheta * 16384) // qn
+ if itheta == 0 then
+ intensityStereo()
+ else
+ -- stereo_split: mid / side
+ for j = 1, n do
+ local l = 0.70710678 * L[xo + j]
+ local r = 0.70710678 * R[xo + j]
+ L[xo + j] = l + r
+ R[xo + j] = r - l
+ end
+ end
+ else
+ local inv = itheta > 8192
+ if inv then
+ for j = 1, n do
+ R[xo + j] = -R[xo + j]
+ end
+ end
+ intensityStereo()
+ if b > 16 and st.remaining > 16 then
+ encBitLogp(enc, inv, 2)
+ end
+ itheta = 0
+ end
+ local qalloc = tellFrac(enc) - t0
+ b -= qalloc
+ local delta
+ if itheta == 0 then
+ delta = -16384
+ elseif itheta == 16384 then
+ delta = 16384
+ else
+ local imid = bitexactCos(itheta)
+ local iside = bitexactCos(16384 - itheta)
+ delta = fracMul16((n - 1) * 128, bitexactLog2tan(iside, imid))
+ end
+ local mbits = imax(0, imin(b, tdiv(b - delta, 2)))
+ local sbits = b - mbits
+ st.remaining -= qalloc
+ local rebalance = st.remaining
+ if mbits >= sbits then
+ quantPartition(st, i, L, xo, n, mbits, LM, enc)
+ rebalance = mbits - (rebalance - st.remaining)
+ if rebalance > 24 and itheta ~= 0 then
+ sbits += rebalance - 24
+ end
+ quantPartition(st, i, R, xo, n, sbits, LM, enc)
+ else
+ quantPartition(st, i, R, xo, n, sbits, LM, enc)
+ rebalance = sbits - (rebalance - st.remaining)
+ if rebalance > 24 and itheta ~= 16384 then
+ mbits += rebalance - 24
+ end
+ quantPartition(st, i, L, xo, n, mbits, LM, enc)
+ end
+end
+
+-- quant_all_bands (encoder): mono, dual stereo or mid / side stereo
+local function quantAllBands(st: State, C: number, pulses: { number }, dualStereo: boolean, totalBits: number,
+ balance: number, enc: RE.Enc, codedBands: number, intensity: number)
+ for i = 0, NB_EBANDS - 1 do
+ local xo = M * EB[i + 1]
+ local nb = M * EB[i + 2] - M * EB[i + 1]
+ local t = tellFrac(enc)
+ if i ~= 0 then
+ balance -= t
+ end
+ local remainingBits = totalBits - t - 1
+ st.remaining = remainingBits
+ local b
+ if i <= codedBands - 1 then
+ local currBalance = tdiv(balance, imin(3, codedBands - i))
+ b = imax(0, imin(16383, imin(remainingBits + 1, pulses[i + 1] + currBalance)))
+ else
+ b = 0
+ end
+ if dualStereo and i == intensity then
+ dualStereo = false
+ end
+ if C == 2 and dualStereo then
+ quantPartition(st, i, st.X[1], xo, nb, b // 2, LM, enc)
+ quantPartition(st, i, st.X[2], xo, nb, b // 2, LM, enc)
+ elseif C == 2 then
+ quantBandStereo(st, i, nb, xo, b, enc)
+ else
+ quantPartition(st, i, st.X[1], xo, nb, b, LM, enc)
+ end
+ balance += pulses[i + 1] + t
+ end
+end
+
+-- ------------------------------------------------------------------------------------------------ frame
+-- encodeFrame(st, pcm, base, stride, nbBytes) -> buffer: one CELT frame of nbBytes from 960 samples per channel
+-- (pcm[base + k * stride + c], floats -1 .. 1, interleaved)
+function CeltEncoder.encodeFrame(st: State, pcm: { number }, base: number, stride: number, nbBytes: number): buffer
+ local C = st.channels
+ local work, tmp = st.work, st.tmp
+ local silent = true
+ -- pre-emphasis, the windowed 1920-sample MDCT input, band energies, normalisation
+ for c = 1, C do
+ local inMem = st.inMem[c]
+ local m = st.preMem[c]
+ -- tmp[1..1080] = the last 120 pre-emphasised samples + this frame's 960
+ for k = 1, OVERLAP do
+ tmp[k] = inMem[k]
+ end
+ for k = 0, N - 1 do
+ local x = pcm[base + k * stride + c - 1] * 32768
+ if x ~= 0 then
+ silent = false
+ end
+ tmp[OVERLAP + k + 1] = x - m
+ m = PREEMPH * x
+ end
+ st.preMem[c] = m
+ for k = 1, OVERLAP do
+ inMem[k] = tmp[N + k]
+ end
+ local q = 420 -- (2N - (N + OVERLAP)) / 2 zeros at each end
+ for k = 1, q do
+ work[k] = 0
+ work[2 * N - k + 1] = 0
+ end
+ for k = 1, OVERLAP do
+ work[q + k] = tmp[k] * WINDOW[k]
+ work[q + N + k] = tmp[N + k] * WINDOW[OVERLAP - k + 1]
+ end
+ for k = OVERLAP + 1, N do
+ work[q + k] = tmp[k]
+ end
+ local X = st.X[c]
+ Mdct.forward(PLAN, work, 1, X, 1, 1, MDCT_SCALE)
+ for i = 0, NB_EBANDS - 1 do
+ local a, z = M * EB[i + 1] + 1, M * EB[i + 2]
+ local s = 1e-27
+ for k = a, z do
+ s += X[k] * X[k]
+ end
+ local E = sqrt(s)
+ st.bandE[(c - 1) * NB_EBANDS + i + 1] = E
+ st.bandLogE[(c - 1) * NB_EBANDS + i + 1] = log(E) / log(2) - E_MEANS[i + 1]
+ local g = 1 / (1e-27 + E)
+ for k = a, z do
+ X[k] *= g
+ end
+ end
+ end
+ local enc = RE.new(nbBytes)
+ local totalBits = nbBytes * 8
+ local oldE = st.oldBandE
+ -- silence
+ if silent then
+ encBitLogp(enc, true, 15)
+ enc.nbits_total += totalBits - tell(enc)
+ RE.done(enc)
+ for i = 1, 2 * NB_EBANDS do
+ oldE[i] = -28
+ end
+ st.frames += 1
+ return enc.buf
+ end
+ encBitLogp(enc, false, 15)
+ if tell(enc) + 16 <= totalBits then
+ encBitLogp(enc, false, 1) -- no post-filter
+ end
+ if tell(enc) + 3 <= totalBits then
+ encBitLogp(enc, false, 3) -- not transient
+ end
+ local intra = st.frames == 0
+ if tell(enc) + 3 <= totalBits then
+ encBitLogp(enc, intra, 3)
+ else
+ intra = false
+ end
+ if C == 1 then
+ for i = 1, NB_EBANDS do
+ oldE[i] = max(oldE[i], oldE[NB_EBANDS + i])
+ end
+ end
+ quantCoarseEnergy(st, intra, enc, C, totalBits, nbBytes)
+ -- tf_encode: no changes
+ do
+ local budget = totalBits
+ local tt = tell(enc)
+ local logp = 4
+ if tt + logp + 1 <= budget then
+ budget -= 1
+ end
+ for _ = 0, NB_EBANDS - 1 do
+ if tt + logp <= budget then
+ encBitLogp(enc, false, logp)
+ tt = tell(enc)
+ end
+ logp = 5
+ end
+ -- tf_select is only coded when it changes something: not for LM 3 without changes
+ local _ = TF_SELECT
+ end
+ if tell(enc) + 4 <= totalBits then
+ encIcdf(enc, st.spread, SPREAD_ICDF, 5)
+ end
+ local cap = {}
+ for i = 0, NB_EBANDS - 1 do
+ local Nw = (EB[i + 2] - EB[i + 1]) * 2 ^ LM
+ cap[i + 1] = rshift((CACHE_CAPS[NB_EBANDS * (2 * LM + C - 1) + i + 1] + 64) * C * Nw, 2)
+ end
+ local offsets = table.create(NB_EBANDS, 0)
+ local total8 = totalBits * 8
+ local t = tellFrac(enc)
+ for i = 0, NB_EBANDS - 1 do
+ if t + 6 * 8 < total8 and 0 < cap[i + 1] then
+ encBitLogp(enc, false, 6) -- no dynamic allocation boost
+ t = tellFrac(enc)
+ end
+ end
+ if t + 48 <= total8 then
+ encIcdf(enc, 5, TRIM_ICDF, 7)
+ end
+ local bits = nbBytes * 64 - tellFrac(enc) - 1
+ local pulses, fineQuant, finePriority = table.create(NB_EBANDS, 0), table.create(NB_EBANDS, 0), table.create(NB_EBANDS, 0)
+ local codedBands, balance, intensity, dualStereo = computeAllocation(offsets, cap, 5, bits, pulses, fineQuant, finePriority, C, enc, st.dual)
+ quantFineEnergy(st, fineQuant, enc, C)
+ quantAllBands(st, C, pulses, dualStereo, nbBytes * 64, balance, enc, codedBands, intensity)
+ quantEnergyFinalise(st, fineQuant, finePriority, totalBits - tell(enc), enc, C)
+ RE.done(enc)
+ if C == 1 then
+ for i = 1, NB_EBANDS do
+ oldE[NB_EBANDS + i] = oldE[i]
+ end
+ end
+ st.frames += 1
+ st.lastError = enc.error
+ return enc.buf
+end
+
+CeltEncoder.FRAME = N
+CeltEncoder.DELAY = OVERLAP -- the decoder's output lags the input by the MDCT overlap
+return CeltEncoder
diff --git a/src/Formats/audio/opus/Encode.luau b/src/Formats/audio/opus/Encode.luau
new file mode 100644
index 0000000..13e4c05
--- /dev/null
+++ b/src/Formats/audio/opus/Encode.luau
@@ -0,0 +1,181 @@
+--!strict
+-- audio/opus/Encode: Ogg Opus writing (RFC 7845) around audio/opus/CeltEncoder: CELT-only packets (TOC config 31:
+-- full band, 20 ms, code 0), OpusHead (mapping family 0, the pre-skip = the encoder's delay), OpusTags (vendor +
+-- the tags as Vorbis comments), granule positions with end trimming, pages through containers/Ogg's muxer. Input at
+-- other rates is resampled to 48 kHz (a Kaiser-windowed sinc; quality enough for a codec input). New in formats-luau.
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Ogg = require("@formats/containers/Ogg")
+local CeltEncoder = require("@formats/audio/opus/CeltEncoder")
+
+local Encode = {}
+
+export type Options = {
+ bitrate: number?, -- bits per second (default 64000 per channel; 6000 .. 510000, constant)
+ tags: { [string]: string }?, -- default: the audio's tags
+ vendor: string?, -- OpusTags vendor (default "formats-luau")
+ serial: number?, -- Ogg stream serial (default 0x4f707573)
+}
+
+local floor, sin, pi, sqrt = math.floor, math.sin, math.pi, math.sqrt
+
+local function besselI0(x: number): number
+ local sum, term = 1, 1
+ for k = 1, 60 do
+ term *= (x / (2 * k)) ^ 2
+ sum += term
+ if term < sum * 1e-15 then
+ break
+ end
+ end
+ return sum
+end
+
+-- resample(src (interleaved f32 buffer), frames, channels, from, to) -> { number } interleaved, frames out
+local function resample(src: buffer, frames: number, channels: number, from: number, to: number): ({ number }, number)
+ local outFrames = floor(frames * to / from + 0.5)
+ local out = table.create(outFrames * channels, 0)
+ local ratio = to / from
+ local cutoff = 0.97 * math.min(1, ratio) -- of the input Nyquist
+ local half = 16 -- zero crossings each side (at the cutoff)
+ local width = half / cutoff
+ local beta = 8
+ local i0b = besselI0(beta)
+ local readf32 = buffer.readf32
+ for j = 0, outFrames - 1 do
+ local t = j / ratio -- the input position
+ local first = math.max(0, floor(t - width) + 1)
+ local last = math.min(frames - 1, floor(t + width))
+ for c = 0, channels - 1 do
+ local acc, wsum = 0, 0
+ for i = first, last do
+ local d = i - t
+ local x = d * cutoff
+ local s = if x == 0 then 1 else sin(pi * x) / (pi * x)
+ local r = d / width
+ local w = besselI0(beta * sqrt(math.max(0, 1 - r * r))) / i0b
+ local h = s * w
+ acc += readf32(src, (i * channels + c) * 4) * h
+ wsum += h
+ end
+ out[j * channels + c + 1] = if wsum ~= 0 then acc / wsum else 0
+ end
+ end
+ return out, outFrames
+end
+
+local TAG_NAMES: { [string]: string } = {
+ title = "TITLE", artist = "ARTIST", album = "ALBUM", albumartist = "ALBUMARTIST", date = "DATE", genre = "GENRE",
+ track = "TRACKNUMBER", tracktotal = "TRACKTOTAL", disc = "DISCNUMBER", comment = "COMMENT", composer = "COMPOSER",
+}
+
+-- encode(audio | decoder, opts) -> buffer | nil, Err
+function Encode.encode(value: any, opts: Options?): (buffer?, Err.Err?)
+ local o = opts or {}
+ if type(value) ~= "table" or type(value.sampleRate) ~= "number" or type(value.channels) ~= "number" then
+ return nil, Err.new(Err.ARG, "expected an Audio or a Decoder")
+ end
+ local ch = value.channels
+ if ch ~= 1 and ch ~= 2 then
+ return nil, Err.new(Err.UNSUPPORTED, "the CELT encoder writes mono or stereo (got " .. ch .. " channels)")
+ end
+ local rate = value.sampleRate
+ if rate < 1000 or rate > 768000 then
+ return nil, Err.new(Err.ARG, "bad sample rate " .. tostring(rate))
+ end
+ local bitrate = o.bitrate or 64000 * ch
+ if type(bitrate) ~= "number" or bitrate < 6000 or bitrate > 510000 then
+ return nil, Err.new(Err.ARG, "bitrate 6000 .. 510000")
+ end
+ -- the whole input as an interleaved f32 buffer
+ local samples: buffer, frames: number
+ if value.kind == "audio" and type(value.samples) == "buffer" then
+ samples, frames = value.samples, value.frames
+ if buffer.len(samples) < frames * ch * 4 then
+ return nil, Err.new(Err.ARG, "audio.samples is shorter than frames * channels")
+ end
+ elseif type(value.read) == "function" then
+ local w = Bytes.writer(65536)
+ frames = 0
+ local chunk: buffer? = nil
+ while true do
+ local b, n = value:read(16384, chunk)
+ chunk = b
+ if n <= 0 then
+ break
+ end
+ w:bytes(b, 0, n * ch * 4)
+ frames += n
+ end
+ samples = w:finish()
+ else
+ return nil, Err.new(Err.ARG, "expected an Audio or a Decoder")
+ end
+ -- 48 kHz floats
+ local pcm: { number }, n48: number
+ if rate == 48000 then
+ n48 = frames
+ pcm = table.create(frames * ch, 0)
+ for i = 1, frames * ch do
+ pcm[i] = buffer.readf32(samples, (i - 1) * 4)
+ end
+ else
+ pcm, n48 = resample(samples, frames, ch, rate, 48000)
+ end
+ local FRAME = CeltEncoder.FRAME
+ local preSkip = CeltEncoder.DELAY
+ local packets = (n48 + preSkip + FRAME - 1) // FRAME
+ -- zero padding to whole frames
+ for i = n48 * ch + 1, packets * FRAME * ch do
+ pcm[i] = 0
+ end
+ local bytes = math.clamp(floor(bitrate * FRAME / 48000 / 8), if ch == 2 then 40 else 20, 1275 - 1)
+ local st = CeltEncoder.new(ch)
+ local mux = Ogg.muxer({ pageSize = 4096 })
+ local s = mux:stream(o.serial or 0x4f707573)
+ -- OpusHead
+ local head = Bytes.writer(19)
+ head:string("OpusHead")
+ head:u8(1)
+ head:u8(ch)
+ head:u16le(preSkip)
+ head:u32le(floor(rate))
+ head:u16le(0)
+ head:u8(0)
+ s:packet(head:finish(), 0, { flush = true })
+ -- OpusTags
+ local tags = o.tags or value.tags or {}
+ local tw = Bytes.writer(256)
+ tw:string("OpusTags")
+ local vendor = o.vendor or "formats-luau"
+ tw:u32le(#vendor)
+ tw:string(vendor)
+ local keys = {}
+ for k, v in tags do
+ if type(k) == "string" and type(v) == "string" then
+ table.insert(keys, k)
+ end
+ end
+ table.sort(keys)
+ tw:u32le(#keys)
+ for _, k in keys do
+ local field = (TAG_NAMES[k] or string.upper(k)) .. "=" .. tags[k]
+ tw:u32le(#field)
+ tw:string(field)
+ end
+ s:packet(tw:finish(), 0, { flush = true })
+ -- audio
+ local toc = 31 * 8 + (if ch == 2 then 4 else 0)
+ for p = 0, packets - 1 do
+ local frame = CeltEncoder.encodeFrame(st, pcm, p * FRAME * ch + 1, ch, bytes)
+ local pkt = buffer.create(bytes + 1)
+ buffer.writeu8(pkt, 0, toc)
+ buffer.copy(pkt, 1, frame, 0, bytes)
+ local last = p == packets - 1
+ local granule = if last then preSkip + n48 else (p + 1) * FRAME
+ s:packet(pkt, granule, { eos = last })
+ end
+ return mux:finish(), nil
+end
+
+return Encode
diff --git a/src/Formats/audio/opus/RangeEncoder.luau b/src/Formats/audio/opus/RangeEncoder.luau
new file mode 100644
index 0000000..13bf3c6
--- /dev/null
+++ b/src/Formats/audio/opus/RangeEncoder.luau
@@ -0,0 +1,252 @@
+--!strict
+--!native
+--!optimize 2
+-- audio/opus/RangeEncoder: the range encoder (RFC 6716 section 5.1), a port of libopus celt/entenc.c (BSD:
+-- licenses/libopus-BSD.txt), the mirror of audio/opus/RangeDecoder. Writes one fixed-size frame: the range-coded
+-- symbols from the front, the raw bits (ec_enc_bits) from the back, zeros between. Values stay below 2^32 as plain
+-- numbers. Never throws: running out of room sets `error`.
+local RangeEncoder = {}
+
+export type Enc = {
+ buf: buffer,
+ storage: number,
+ offs: number,
+ end_offs: number,
+ end_window: number,
+ nend_bits: number,
+ nbits_total: number,
+ rng: number,
+ val: number,
+ rem: number,
+ ext: number,
+ error: number,
+}
+
+local CODE_TOP = 2147483648 -- 1 << 31
+local CODE_BOT = 8388608 -- CODE_TOP >> 8
+local CODE_SHIFT = 23
+local SYM_MAX = 255
+
+local countlz = bit32.countlz
+local band = bit32.band
+local readu8, writeu8 = buffer.readu8, buffer.writeu8
+local floor = math.floor
+
+local function ilog(x: number): number
+ return 32 - countlz(x)
+end
+RangeEncoder.ilog = ilog
+
+-- new(storage) -> Enc over a fresh zeroed buffer of storage bytes
+function RangeEncoder.new(storage: number): Enc
+ return {
+ buf = buffer.create(math.max(storage, 1)),
+ storage = storage,
+ offs = 0,
+ end_offs = 0,
+ end_window = 0,
+ nend_bits = 0,
+ nbits_total = 33, -- EC_CODE_BITS + 1
+ rng = CODE_TOP,
+ val = 0,
+ rem = -1,
+ ext = 0,
+ error = 0,
+ }
+end
+
+local function writeByte(e: Enc, v: number)
+ if e.offs + e.end_offs >= e.storage then
+ e.error = -1
+ return
+ end
+ writeu8(e.buf, e.offs, band(v, 255))
+ e.offs += 1
+end
+
+local function writeByteAtEnd(e: Enc, v: number)
+ if e.offs + e.end_offs >= e.storage then
+ e.error = -1
+ return
+ end
+ e.end_offs += 1
+ writeu8(e.buf, e.storage - e.end_offs, band(v, 255))
+end
+
+local function carryOut(e: Enc, c: number)
+ if c ~= SYM_MAX then
+ local carry = if c >= 256 then 1 else 0
+ if e.rem >= 0 then
+ writeByte(e, e.rem + carry)
+ end
+ if e.ext > 0 then
+ local sym = band(SYM_MAX + carry, 255)
+ repeat
+ writeByte(e, sym)
+ e.ext -= 1
+ until e.ext <= 0
+ end
+ e.rem = band(c, 255)
+ else
+ e.ext += 1
+ end
+end
+
+local function normalize(e: Enc)
+ while e.rng <= CODE_BOT do
+ carryOut(e, floor(e.val / 8388608))
+ e.val = (e.val * 256) % CODE_TOP
+ e.rng *= 256
+ e.nbits_total += 8
+ end
+end
+
+-- encode(fl, fh, ft): the symbol [fl, fh) of ft
+function RangeEncoder.encode(e: Enc, fl: number, fh: number, ft: number)
+ local r = floor(e.rng / ft)
+ if fl > 0 then
+ e.val += e.rng - r * (ft - fl)
+ e.rng = r * (fh - fl)
+ else
+ e.rng -= r * (ft - fh)
+ end
+ normalize(e)
+end
+
+-- encodeBin(fl, fh, bits): ft = 2^bits
+function RangeEncoder.encodeBin(e: Enc, fl: number, fh: number, bits: number)
+ local ft = 2 ^ bits
+ local r = floor(e.rng / ft)
+ if fl > 0 then
+ e.val += e.rng - r * (ft - fl)
+ e.rng = r * (fh - fl)
+ else
+ e.rng -= r * (ft - fh)
+ end
+ normalize(e)
+end
+
+-- bitLogp(v, logp): a bit whose probability of being 1 is 2^-logp
+function RangeEncoder.bitLogp(e: Enc, v: boolean, logp: number)
+ local r = e.rng
+ local s = floor(r / 2 ^ logp)
+ r -= s
+ if v then
+ e.val += r
+ e.rng = s
+ else
+ e.rng = r
+ end
+ normalize(e)
+end
+
+-- icdf(s, icdf, ftb): symbol s (0-based) of an inverse CDF table (1-based Luau array) with 2^ftb total
+function RangeEncoder.icdf(e: Enc, s: number, icdf: { number }, ftb: number)
+ local r = floor(e.rng / 2 ^ ftb)
+ if s > 0 then
+ e.val += e.rng - r * icdf[s]
+ e.rng = r * (icdf[s] - icdf[s + 1])
+ else
+ e.rng -= r * icdf[s + 1]
+ end
+ normalize(e)
+end
+
+-- bits(fl, n): n raw bits (n <= 25), written from the end of the frame
+function RangeEncoder.bits(e: Enc, fl: number, n: number)
+ local window = e.end_window
+ local used = e.nend_bits
+ if used + n > 32 then
+ repeat
+ writeByteAtEnd(e, window % 256)
+ window = floor(window / 256)
+ used -= 8
+ until used < 8
+ end
+ window += fl * 2 ^ used
+ used += n
+ e.end_window = window
+ e.nend_bits = used
+ e.nbits_total += n
+end
+
+-- uint(fl, ft): fl uniformly in [0, ft), ft up to 2^32
+function RangeEncoder.uint(e: Enc, fl: number, ft: number)
+ ft -= 1
+ local ftb = ilog(ft)
+ if ftb > 8 then
+ ftb -= 8
+ local sh = 2 ^ ftb
+ local ft1 = floor(ft / sh) + 1
+ local hi = floor(fl / sh)
+ RangeEncoder.encode(e, hi, hi + 1, ft1)
+ RangeEncoder.bits(e, fl - hi * sh, ftb)
+ else
+ RangeEncoder.encode(e, fl, fl + 1, ft + 1)
+ end
+end
+
+function RangeEncoder.tell(e: Enc): number
+ return e.nbits_total - ilog(e.rng)
+end
+
+local CORRECTION = { 35733, 38967, 42495, 46340, 50535, 55109, 60097, 65535 }
+function RangeEncoder.tellFrac(e: Enc): number
+ local nbits = e.nbits_total * 8
+ local l = ilog(e.rng)
+ local r = floor(e.rng / 2 ^ (l - 16))
+ local b = floor(r / 4096) - 8
+ if r > CORRECTION[b + 1] then
+ b += 1
+ end
+ return nbits - (l * 8 + b)
+end
+
+-- done(): flush; the frame is e.buf (storage bytes)
+function RangeEncoder.done(e: Enc)
+ local l = 32 - ilog(e.rng)
+ local msk = floor((CODE_TOP - 1) / 2 ^ l)
+ local stop = floor((e.val + msk) / (msk + 1)) * (msk + 1)
+ if stop + msk >= e.val + e.rng then
+ l += 1
+ msk = floor(msk / 2)
+ stop = floor((e.val + msk) / (msk + 1)) * (msk + 1)
+ end
+ while l > 0 do
+ carryOut(e, floor(stop / 8388608))
+ stop = (stop * 256) % CODE_TOP
+ l -= 8
+ end
+ if e.rem >= 0 or e.ext > 0 then
+ carryOut(e, 0)
+ end
+ local window = e.end_window
+ local used = e.nend_bits
+ while used >= 8 do
+ writeByteAtEnd(e, window % 256)
+ window = floor(window / 256)
+ used -= 8
+ end
+ if e.error == 0 then
+ local a, b = e.offs, e.storage - e.end_offs
+ if b > a then
+ buffer.fill(e.buf, a, 0, b - a)
+ end
+ if used > 0 then
+ if e.end_offs >= e.storage then
+ e.error = -1
+ else
+ l = -l
+ if e.offs + e.end_offs >= e.storage and l < used then
+ window = window % 2 ^ l
+ e.error = -1
+ end
+ local p = e.storage - e.end_offs - 1
+ writeu8(e.buf, p, bit32.bor(readu8(e.buf, p), window))
+ end
+ end
+ end
+end
+
+local _ = CODE_SHIFT
+return RangeEncoder
diff --git a/src/Formats/audio/opus/init.luau b/src/Formats/audio/opus/init.luau
index 08852eb..2d80432 100644
--- a/src/Formats/audio/opus/init.luau
+++ b/src/Formats/audio/opus/init.luau
@@ -5,14 +5,17 @@
-- Supports: decode of every Opus mode / bandwidth / frame size, mono, stereo and surround (optional stereo downmix,
-- opts.stereo), pre-skip, end trimming, output gain, OpusTags, sample-accurate seeking (granule bisection + 80 ms
-- pre-roll), damaged files (concealment). Output is always 48 kHz f32.
--- Not supported: encoding, mapping family 3 (ambisonics projection), chained streams (the first Opus stream is
--- decoded), CELT pitch PLC (noise PLC only).
+-- Encoding (audio/opus/Encode + CeltEncoder, ws-m4a): a CELT-only fixed-frame encoder (20 ms, full band, constant
+-- bit rate, mono or dual stereo; other input rates resampled to 48 kHz) writing Ogg Opus with OpusTags.
+-- Not supported: SILK / hybrid encoding, transients / pitch pre-filter in the encoder, mapping family 3 (ambisonics
+-- projection), chained streams (the first Opus stream is decoded), CELT pitch PLC (noise PLC only).
-- Changes from opus-luau: the injected Ogg demuxer is containers/Ogg; errors are core/Err values; read() takes an
-- optional output buffer; decode() fully decodes to an Audio.
--
-- local dec, err = Opus.open(Bytes.reader(buf)) -- the Types.Decoder: dec:read(n, out?), dec:seek(s), ...
-- local audio = Opus.decode(Bytes.reader(buf)) -- a Types.Audio
-- Opus.Decoder.new(channels) + Opus.Decoder.decode(st, buf, off, len, pcm, base, maxFrames) -- raw packets
+-- local file = Opus.encode(audio, { bitrate = 96000 }) -- Ogg Opus (CELT only)
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
@@ -24,6 +27,7 @@ local Packet = require("@formats/audio/opus/Packet")
local RangeDecoder = require("@formats/audio/opus/RangeDecoder")
local Celt = require("@formats/audio/opus/Celt")
local Silk = require("@formats/audio/opus/Silk")
+local Encode = require("@formats/audio/opus/Encode")
-- ------------------------------------------------------------------------------------------------ contract
local Opus = {
@@ -31,8 +35,8 @@ local Opus = {
category = "audio",
extensions = { "opus" },
mime = { "audio/opus", "audio/ogg" },
- deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg" },
- caps = { decode = true, encode = false, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 } },
+ deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct" },
+ caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 }, encodeModes = { "celt" } },
}
-- ------------------------------------------------------------------------------------------------ types
@@ -213,6 +217,12 @@ function Opus.decode(r: any, opts: OpenOptions?): (Types.Audio?, Err.Err?)
return a, nil
end
+-- ------------------------------------------------------------------------------------------------ encode
+-- encode(audio | decoder, opts?) -> Ogg Opus buffer | nil, Err (CELT only; see audio/opus/Encode)
+function Opus.encode(value: any, opts: Encode.Options?): (buffer?, Err.Err?)
+ return Encode.encode(value, opts)
+end
+
-- ------------------------------------------------------------------------------------------------ open
local Stream = {}
Stream.__index = Stream
diff --git a/src/Formats/codecs/Aac/Decode.luau b/src/Formats/codecs/Aac/Decode.luau
new file mode 100644
index 0000000..ce4a88b
--- /dev/null
+++ b/src/Formats/codecs/Aac/Decode.luau
@@ -0,0 +1,903 @@
+--!strict
+--!native
+--!optimize 2
+-- codecs/Aac/Decode: the AAC-LC raw_data_block decoder (ISO/IEC 14496-3 subpart 4): SCE / CPE / LFE / DSE / PCE /
+-- FIL / END elements, ics_info with window grouping, section data, scalefactors (with noise energies and intensity
+-- positions), pulse data, TNS, the eleven spectral codebooks with escapes, dequantisation, M/S and intensity stereo,
+-- perceptual noise substitution (FFmpeg's LCG so the noise matches it), the filterbank (sine / KBD windows, the four
+-- window sequences, IMDCT through codecs/Mdct, overlap-add). FIL extension payloads (SBR / PS) are reported to a hook
+-- and otherwise skipped. Written from the standard; no third-party code. Never throws: returns nil, message.
+local Mdct = require("@formats/codecs/Mdct")
+local Tables = require("@formats/codecs/Aac/Tables")
+
+local readu32, byteswap, lshift, rshift, band = buffer.readu32, bit32.byteswap, bit32.lshift, bit32.rshift, bit32.band
+local floor, sqrt, abs = math.floor, math.sqrt, math.abs
+
+local Decode = {}
+
+local ONLY_LONG, LONG_START, EIGHT_SHORT, LONG_STOP = 0, 1, 2, 3
+local ZERO_HCB, ESC_HCB, NOISE_HCB, INTENSITY_HCB2, INTENSITY_HCB = 0, 11, 13, 14, 15
+
+-- ------------------------------------------------------------------------------------------------ bit reader
+-- one packet at a time: module-level cursor over a zero-padded copy (a frame decode never yields)
+local B: buffer = buffer.create(16)
+local BP = 0 -- bit position
+local BL = 0 -- bit limit
+local OVER = false
+
+local function getBits(n: number): number -- 1 .. 25
+ local p = BP
+ BP = p + n
+ if p > BL then
+ OVER = true
+ return 0
+ end
+ return rshift(lshift(byteswap(readu32(B, rshift(p, 3))), band(p, 7)), 32 - n)
+end
+local function peekBits(n: number): number
+ local p = BP
+ if p > BL then
+ return 0
+ end
+ return rshift(lshift(byteswap(readu32(B, rshift(p, 3))), band(p, 7)), 32 - n)
+end
+local function getLong(n: number): number
+ if n > 24 then
+ local hi = getBits(n - 16)
+ return hi * 65536 + getBits(16)
+ end
+ return getBits(n)
+end
+
+-- ------------------------------------------------------------------------------------------------ Huffman
+local PEEK = 10
+type Book = { tab: { number }, map: { [number]: number }, maxLen: number }
+
+local function book(codes: { number }, bits: { number }): Book
+ local tab = table.create(2 ^ PEEK, 0)
+ local map = {}
+ local maxLen = 0
+ for s = 1, #codes do
+ local c, l = codes[s], bits[s]
+ maxLen = math.max(maxLen, l)
+ if l <= PEEK then
+ local shift = 2 ^ (PEEK - l)
+ for k = 0, shift - 1 do
+ tab[c * shift + k + 1] = (s - 1) * 32 + l
+ end
+ else
+ map[l * 2 ^ 20 + c] = s - 1
+ end
+ end
+ return { tab = tab, map = map, maxLen = maxLen }
+end
+
+local SF_BOOK = book(Tables.SF_CODES, Tables.SF_BITS)
+local SPEC_BOOK: { Book } = {}
+for i = 1, 11 do
+ SPEC_BOOK[i] = book(Tables.SPEC_CODES[i], Tables.SPEC_BITS[i])
+end
+
+-- the next symbol of a book, -1 for an invalid code
+local function huff(bk: Book): number
+ local e = bk.tab[peekBits(PEEK) + 1]
+ if e > 0 then
+ BP += band(e, 31)
+ return rshift(e, 5)
+ end
+ -- a code longer than PEEK bits
+ local code = getBits(PEEK)
+ local map = bk.map
+ for l = PEEK + 1, bk.maxLen do
+ code = code * 2 + getBits(1)
+ local s = map[l * 1048576 + code]
+ if s then
+ return s
+ end
+ end
+ return -1
+end
+
+-- per codebook: dimension, unsigned, modulus, offset
+local DIM = { 4, 4, 4, 4, 2, 2, 2, 2, 2, 2, 2 }
+local UNSIGNED = { false, false, true, true, false, false, true, true, true, true, true }
+local MOD = { 3, 3, 3, 3, 9, 9, 8, 8, 13, 13, 17 }
+local OFF = { 1, 1, 0, 0, 4, 4, 0, 0, 0, 0, 0 }
+
+-- |q|^(4/3)
+local POW43 = table.create(8192, 0)
+for i = 0, 8191 do
+ POW43[i + 1] = i ^ (4 / 3)
+end
+
+-- ------------------------------------------------------------------------------------------------ windows
+local SINE_LONG = Mdct.window("sine", 2048) :: { number }
+local KBD_LONG = Mdct.window("kbd", 2048, 4) :: { number }
+local SINE_SHORT = Mdct.window("sine", 256) :: { number }
+local KBD_SHORT = Mdct.window("kbd", 256, 6) :: { number }
+local PLAN_LONG = Mdct.new(2048) :: Mdct.Plan
+local PLAN_SHORT = Mdct.new(256) :: Mdct.Plan
+
+-- ------------------------------------------------------------------------------------------------ state
+export type Channel = {
+ spec: { number }, -- 1024 dequantised coefficients (8 x 128 for short windows)
+ overlap: { number }, -- 1024 samples carried to the next frame
+ prevShape: number,
+ -- this frame's ics
+ windowSequence: number,
+ windowShape: number,
+ maxSfb: number,
+ numGroups: number,
+ groupLen: { number },
+ bandType: { number }, -- [g * maxSfb + sfb + 1]
+ sf: { number },
+ -- tns
+ tnsFilters: { { number } }, -- per window: { length, order, direction, coefs ... } flattened per filter
+}
+
+export type State = {
+ sfIndex: number,
+ channels: number, -- configured channels (0: as found)
+ frameLength: number,
+ ch: { Channel },
+ pcm: { number }, -- interleaved output floats
+ random: number, -- PNS generator state
+ time: { number }, -- 2048 IMDCT scratch
+ frame: { number }, -- 2048 windowed frame scratch
+ short: { number }, -- 256 scratch
+ onExtension: ((kind: number, element: number, buf: buffer, bitPos: number, bits: number) -> ())?,
+ extensions: number, -- extension payloads seen (SBR / PS / ...)
+ sbr: boolean, -- an SBR payload was seen
+ map: { number }?, -- element channel order -> output channel (1-based)
+}
+
+local function newChannel(): Channel
+ return {
+ spec = table.create(1024, 0),
+ overlap = table.create(1024, 0),
+ prevShape = 0,
+ windowSequence = 0,
+ windowShape = 0,
+ maxSfb = 0,
+ numGroups = 1,
+ groupLen = { 1, 0, 0, 0, 0, 0, 0, 0 },
+ bandType = table.create(8 * 64, 0),
+ sf = table.create(8 * 64, 0),
+ tnsFilters = {},
+ }
+end
+Decode.newChannel = newChannel
+
+-- ------------------------------------------------------------------------------------------------ ics
+local function icsInfo(st: State, c: Channel): string?
+ if getBits(1) ~= 0 then
+ return "reserved ics bit set"
+ end
+ c.windowSequence = getBits(2)
+ c.windowShape = getBits(1)
+ if c.windowSequence == EIGHT_SHORT then
+ c.maxSfb = getBits(4)
+ local grouping = getBits(7)
+ local ng = 1
+ local gl = c.groupLen
+ gl[1] = 1
+ for w = 1, 7 do
+ if band(grouping, 2 ^ (6 - (w - 1))) ~= 0 then
+ gl[ng] += 1
+ else
+ ng += 1
+ gl[ng] = 1
+ end
+ end
+ c.numGroups = ng
+ if c.maxSfb > Tables.NUM_SWB_SHORT[st.sfIndex + 1] then
+ return "max_sfb over the short band count"
+ end
+ else
+ c.maxSfb = getBits(6)
+ c.numGroups = 1
+ c.groupLen[1] = 1
+ if getBits(1) ~= 0 then
+ return "prediction (AAC Main / LTP) is not supported"
+ end
+ if c.maxSfb > Tables.NUM_SWB_LONG[st.sfIndex + 1] then
+ return "max_sfb over the long band count"
+ end
+ end
+ return nil
+end
+
+local function sectionData(c: Channel): string?
+ local long = c.windowSequence ~= EIGHT_SHORT
+ local bits = if long then 5 else 3
+ local esc = 2 ^ bits - 1
+ local maxSfb = c.maxSfb
+ local bt = c.bandType
+ for g = 0, c.numGroups - 1 do
+ local k = 0
+ while k < maxSfb do
+ local cb = getBits(4)
+ if cb == 12 then
+ return "reserved codebook 12"
+ end
+ local len = 0
+ while true do
+ local inc = getBits(bits)
+ len += inc
+ if inc ~= esc then
+ break
+ end
+ if OVER then
+ return "section data runs past the end"
+ end
+ end
+ if k + len > maxSfb then
+ return "section runs past max_sfb"
+ end
+ for s = k, k + len - 1 do
+ bt[g * maxSfb + s + 1] = cb
+ end
+ k += len
+ if OVER then
+ return "section data runs past the end"
+ end
+ end
+ end
+ return nil
+end
+
+local function scaleFactors(c: Channel, globalGain: number): string?
+ local sfv = globalGain
+ local noise = globalGain - 90
+ local is = 0
+ local firstNoise = true
+ local maxSfb = c.maxSfb
+ local bt, sf = c.bandType, c.sf
+ for g = 0, c.numGroups - 1 do
+ for s = 0, maxSfb - 1 do
+ local i = g * maxSfb + s + 1
+ local cb = bt[i]
+ if cb == ZERO_HCB then
+ sf[i] = 0
+ elseif cb == INTENSITY_HCB or cb == INTENSITY_HCB2 then
+ local d = huff(SF_BOOK)
+ if d < 0 then
+ return "bad scalefactor code"
+ end
+ is += d - 60
+ sf[i] = math.clamp(is, -155, 100)
+ elseif cb == NOISE_HCB then
+ if firstNoise then
+ noise += getBits(9) - 256
+ firstNoise = false
+ else
+ local d = huff(SF_BOOK)
+ if d < 0 then
+ return "bad scalefactor code"
+ end
+ noise += d - 60
+ end
+ sf[i] = math.clamp(noise, -100, 155)
+ else
+ local d = huff(SF_BOOK)
+ if d < 0 then
+ return "bad scalefactor code"
+ end
+ sfv += d - 60
+ if sfv < 0 or sfv > 255 then
+ return "scalefactor out of range"
+ end
+ sf[i] = sfv
+ end
+ end
+ end
+ return nil
+end
+
+local function tnsData(st: State, c: Channel): string?
+ local short = c.windowSequence == EIGHT_SHORT
+ local nw = if short then 8 else 1
+ local filters = {}
+ for w = 1, nw do
+ local list = {}
+ local nFilt = getBits(if short then 1 else 2)
+ if nFilt > 0 then
+ local coefRes = getBits(1)
+ for _ = 1, nFilt do
+ local length = getBits(if short then 4 else 6)
+ local order = getBits(if short then 3 else 5)
+ local f = { length, order, 0 }
+ if order > (if short then 7 else 12) then
+ return "TNS order too high"
+ end
+ if order > 0 then
+ f[3] = getBits(1)
+ local compress = getBits(1)
+ local resBits = coefRes + 3
+ local nb = resBits - compress
+ local iq = ((2 ^ (resBits - 1)) - 0.5) / (math.pi / 2)
+ local iqm = ((2 ^ (resBits - 1)) + 0.5) / (math.pi / 2)
+ local tmp = table.create(order, 0)
+ for k = 1, order do
+ local v = getBits(nb)
+ if v >= 2 ^ (nb - 1) then
+ v -= 2 ^ nb
+ end
+ tmp[k] = math.sin(v / (if v >= 0 then iq else iqm))
+ end
+ -- parcor -> LPC
+ local a = table.create(order + 1, 0)
+ local b = table.create(order + 1, 0)
+ a[1] = 1
+ for m = 1, order do
+ for i = 1, m - 1 do
+ b[i + 1] = a[i + 1] + tmp[m] * a[m - i + 1]
+ end
+ for i = 1, m - 1 do
+ a[i + 1] = b[i + 1]
+ end
+ a[m + 1] = tmp[m]
+ end
+ for k = 1, order do
+ f[3 + k] = a[k + 1]
+ end
+ end
+ table.insert(list, f)
+ end
+ end
+ filters[w] = list
+ end
+ c.tnsFilters = filters
+ local _ = st
+ return nil
+end
+
+local function applyTns(st: State, c: Channel)
+ local short = c.windowSequence == EIGHT_SHORT
+ local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1]
+ local numSwb = if short then Tables.NUM_SWB_SHORT[st.sfIndex + 1] else Tables.NUM_SWB_LONG[st.sfIndex + 1]
+ local maxBands = if short then Tables.TNS_MAX_BANDS_SHORT[st.sfIndex + 1] else Tables.TNS_MAX_BANDS_LONG[st.sfIndex + 1]
+ local mmm = math.min(maxBands, c.maxSfb)
+ if mmm == 0 then
+ return
+ end
+ local spec = c.spec
+ for w, list in c.tnsFilters do
+ local bottom = numSwb
+ for _, f in list do
+ local top = bottom
+ bottom = math.max(0, top - f[1])
+ local order = f[2]
+ if order > 0 then
+ local start = swb[math.min(bottom, mmm) + 1]
+ local stop = swb[math.min(top, mmm) + 1]
+ local size = stop - start
+ if size > 0 then
+ local inc = 1
+ local p = (w - 1) * 128 + start + 1
+ if f[3] == 1 then
+ inc = -1
+ p = (w - 1) * 128 + stop
+ end
+ for m = 0, size - 1 do
+ local y = spec[p]
+ local lim = if m < order then m else order
+ for i = 1, lim do
+ y -= spec[p - i * inc] * f[3 + i]
+ end
+ spec[p] = y
+ p += inc
+ end
+ end
+ end
+ end
+ end
+end
+
+-- the spectral data of one channel, dequantised into c.spec (also pulses, noise, intensity zeros)
+local function spectralData(st: State, c: Channel, pulses: { number }?): string?
+ local short = c.windowSequence == EIGHT_SHORT
+ local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1]
+ local spec = c.spec
+ for i = 1, 1024 do
+ spec[i] = 0
+ end
+ local maxSfb = c.maxSfb
+ local bt, sf = c.bandType, c.sf
+ local win = 0
+ for g = 0, c.numGroups - 1 do
+ local glen = c.groupLen[g + 1]
+ for s = 0, maxSfb - 1 do
+ local idx = g * maxSfb + s + 1
+ local cb = bt[idx]
+ local lo, hi = swb[s + 1], swb[s + 2]
+ local width = hi - lo
+ if cb == ZERO_HCB or cb == INTENSITY_HCB or cb == INTENSITY_HCB2 then
+ -- zeros (intensity bands are filled from the other channel later)
+ continue
+ elseif cb == NOISE_HCB then
+ local scale = 2 ^ (0.25 * sf[idx])
+ for w = 0, glen - 1 do
+ local base = (win + w) * 128 + lo
+ local energy = 0
+ local r = st.random
+ for k = 1, width do
+ r = (r * 1664525 + 1013904223) % 4294967296
+ local v = if r >= 2147483648 then r - 4294967296 else r
+ spec[base + k] = v
+ energy += v * v
+ end
+ st.random = r
+ local m = if energy > 0 then scale / sqrt(energy) else 0
+ for k = 1, width do
+ spec[base + k] *= m
+ end
+ end
+ continue
+ end
+ local bk = SPEC_BOOK[cb]
+ local dim, uns, mod, off = DIM[cb], UNSIGNED[cb], MOD[cb], OFF[cb]
+ local gain = 2 ^ (0.25 * (sf[idx] - 100))
+ for w = 0, glen - 1 do
+ local base = (win + w) * 128 + lo
+ local k = 0
+ while k < width do
+ local sym = huff(bk)
+ if sym < 0 then
+ return "bad spectral code"
+ end
+ -- unpack the symbol into dim values (first value most significant)
+ local vals1, vals2, vals3, vals4
+ if dim == 4 then
+ vals4 = sym % mod - off
+ sym = (sym - (sym % mod)) / mod
+ vals3 = sym % mod - off
+ sym = (sym - (sym % mod)) / mod
+ vals2 = sym % mod - off
+ sym = (sym - (sym % mod)) / mod
+ vals1 = sym % mod - off
+ else
+ vals2 = sym % mod - off
+ vals1 = (sym - (sym % mod)) / mod - off
+ end
+ if uns then
+ if vals1 ~= 0 and getBits(1) == 1 then
+ vals1 = -vals1
+ end
+ if vals2 ~= 0 and getBits(1) == 1 then
+ vals2 = -vals2
+ end
+ if dim == 4 then
+ if vals3 ~= 0 and getBits(1) == 1 then
+ vals3 = -vals3
+ end
+ if vals4 ~= 0 and getBits(1) == 1 then
+ vals4 = -vals4
+ end
+ end
+ if cb == ESC_HCB then
+ for e = 1, 2 do
+ local v = if e == 1 then vals1 else vals2
+ if v == 16 or v == -16 then
+ local n = 0
+ while getBits(1) == 1 do
+ n += 1
+ if n > 8 or OVER then
+ return "bad escape"
+ end
+ end
+ local esc = 2 ^ (n + 4) + getBits(n + 4)
+ if v < 0 then
+ esc = -esc
+ end
+ if e == 1 then
+ vals1 = esc
+ else
+ vals2 = esc
+ end
+ end
+ end
+ end
+ end
+ local p = base + k + 1
+ spec[p] = vals1
+ spec[p + 1] = vals2
+ if dim == 4 then
+ spec[p + 2] = vals3
+ spec[p + 3] = vals4
+ end
+ k += dim
+ end
+ if OVER then
+ return "spectral data runs past the end"
+ end
+ end
+ -- dequantise (pulses are added to the quantised values first: long windows only, applied below)
+ if not pulses then
+ for w = 0, glen - 1 do
+ local base = (win + w) * 128 + lo
+ for k = 1, width do
+ local q = spec[base + k]
+ if q ~= 0 then
+ local aq = if q < 0 then -q else q
+ local v = (POW43[aq + 1] or aq ^ (4 / 3)) * gain
+ spec[base + k] = if q < 0 then -v else v
+ end
+ end
+ end
+ end
+ end
+ win += glen
+ end
+ if pulses then
+ -- long window: add the pulses to the quantised values, then dequantise every band
+ for i = 1, #pulses, 2 do
+ local pos = pulses[i] + 1
+ if pos <= 1024 then
+ local q = spec[pos]
+ spec[pos] = if q > 0 then q + pulses[i + 1] else q - pulses[i + 1]
+ end
+ end
+ for s = 0, maxSfb - 1 do
+ local idx = s + 1
+ local cb = bt[idx]
+ if cb ~= ZERO_HCB and cb < NOISE_HCB then
+ local gain = 2 ^ (0.25 * (sf[idx] - 100))
+ for k = swb[s + 1] + 1, swb[s + 2] do
+ local q = spec[k]
+ if q ~= 0 then
+ local aq = if q < 0 then -q else q
+ local v = (POW43[aq + 1] or aq ^ (4 / 3)) * gain
+ spec[k] = if q < 0 then -v else v
+ end
+ end
+ end
+ end
+ end
+ return nil
+end
+
+-- individual_channel_stream
+local function ics(st: State, c: Channel, commonWindow: boolean): string?
+ local globalGain = getBits(8)
+ if not commonWindow then
+ local e = icsInfo(st, c)
+ if e then
+ return e
+ end
+ end
+ local e = sectionData(c)
+ if e then
+ return e
+ end
+ e = scaleFactors(c, globalGain)
+ if e then
+ return e
+ end
+ local pulses: { number }? = nil
+ if getBits(1) == 1 then
+ if c.windowSequence == EIGHT_SHORT then
+ return "pulse data in a short window"
+ end
+ local n = getBits(2) + 1
+ local startSfb = getBits(6)
+ if startSfb >= Tables.NUM_SWB_LONG[st.sfIndex + 1] then
+ return "bad pulse start band"
+ end
+ local pos = Tables.SWB_LONG[st.sfIndex + 1][startSfb + 1]
+ local list = {}
+ for _ = 1, n do
+ pos += getBits(5)
+ table.insert(list, pos)
+ table.insert(list, getBits(4))
+ end
+ pulses = list
+ end
+ c.tnsFilters = {}
+ if getBits(1) == 1 then
+ e = tnsData(st, c)
+ if e then
+ return e
+ end
+ end
+ if getBits(1) == 1 then
+ return "gain control (AAC SSR) is not supported"
+ end
+ if OVER then
+ return "channel stream runs past the end"
+ end
+ return spectralData(st, c, pulses)
+end
+
+-- ------------------------------------------------------------------------------------------------ stereo
+local function msStereo(st: State, l: Channel, r: Channel, mask: { number })
+ local short = l.windowSequence == EIGHT_SHORT
+ local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1]
+ local maxSfb = l.maxSfb
+ local a, b = l.spec, r.spec
+ local win = 0
+ for g = 0, l.numGroups - 1 do
+ local glen = l.groupLen[g + 1]
+ for s = 0, maxSfb - 1 do
+ local idx = g * maxSfb + s + 1
+ if mask[idx] == 1 and l.bandType[idx] < NOISE_HCB and r.bandType[idx] < NOISE_HCB then
+ for w = 0, glen - 1 do
+ local base = (win + w) * 128
+ for k = base + swb[s + 1] + 1, base + swb[s + 2] do
+ local m, sd = a[k], b[k]
+ a[k], b[k] = m + sd, m - sd
+ end
+ end
+ end
+ end
+ win += glen
+ end
+end
+
+local function intensity(st: State, l: Channel, r: Channel, mask: { number }, msPresent: number)
+ local short = r.windowSequence == EIGHT_SHORT
+ local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1]
+ local maxSfb = r.maxSfb
+ local a, b = l.spec, r.spec
+ local win = 0
+ for g = 0, r.numGroups - 1 do
+ local glen = r.groupLen[g + 1]
+ for s = 0, maxSfb - 1 do
+ local idx = g * maxSfb + s + 1
+ local cb = r.bandType[idx]
+ if cb == INTENSITY_HCB or cb == INTENSITY_HCB2 then
+ local sign = if cb == INTENSITY_HCB then 1 else -1
+ if msPresent ~= 0 and mask[idx] == 1 then
+ sign = -sign
+ end
+ local scale = sign * 0.5 ^ (0.25 * r.sf[idx])
+ for w = 0, glen - 1 do
+ local base = (win + w) * 128
+ for k = base + swb[s + 1] + 1, base + swb[s + 2] do
+ b[k] = a[k] * scale
+ end
+ end
+ end
+ end
+ win += glen
+ end
+end
+
+-- ------------------------------------------------------------------------------------------------ filterbank
+local function filterbank(st: State, c: Channel, out: { number }, stride: number, offset: number)
+ local seq, shape, prev = c.windowSequence, c.windowShape, c.prevShape
+ local spec, overlap = c.spec, c.overlap
+ local frame = st.frame
+ local scale = 1 / 32768
+ if seq == EIGHT_SHORT then
+ for i = 1, 2048 do
+ frame[i] = 0
+ end
+ local tmp = st.short
+ local rise0 = if prev == 1 then KBD_SHORT else SINE_SHORT
+ local wcur = if shape == 1 then KBD_SHORT else SINE_SHORT
+ for w = 0, 7 do
+ Mdct.inverse(PLAN_SHORT, spec, w * 128 + 1, 1, tmp, 1, 2 / 256)
+ local rise = if w == 0 then rise0 else wcur
+ local base = 448 + w * 128
+ for n = 1, 128 do
+ frame[base + n] += tmp[n] * rise[n]
+ frame[base + 128 + n] += tmp[128 + n] * wcur[128 + n]
+ end
+ end
+ else
+ local t = st.time
+ Mdct.inverse(PLAN_LONG, spec, 1, 1, t, 1, 2 / 2048)
+ -- left half
+ if seq == LONG_STOP then
+ local rise = if prev == 1 then KBD_SHORT else SINE_SHORT
+ for n = 1, 448 do
+ frame[n] = 0
+ end
+ for n = 1, 128 do
+ frame[448 + n] = t[448 + n] * rise[n]
+ end
+ for n = 577, 1024 do
+ frame[n] = t[n]
+ end
+ else
+ local rise = if prev == 1 then KBD_LONG else SINE_LONG
+ for n = 1, 1024 do
+ frame[n] = t[n] * rise[n]
+ end
+ end
+ -- right half
+ if seq == LONG_START then
+ local fall = if shape == 1 then KBD_SHORT else SINE_SHORT
+ for n = 1025, 1472 do
+ frame[n] = t[n]
+ end
+ for n = 1, 128 do
+ frame[1472 + n] = t[1472 + n] * fall[128 + n]
+ end
+ for n = 1601, 2048 do
+ frame[n] = 0
+ end
+ else
+ local fall = if shape == 1 then KBD_LONG else SINE_LONG
+ for n = 1025, 2048 do
+ frame[n] = t[n] * fall[n]
+ end
+ end
+ end
+ local p = offset
+ for n = 1, 1024 do
+ out[p] = (frame[n] + overlap[n]) * scale
+ overlap[n] = frame[1024 + n]
+ p += stride
+ end
+ c.prevShape = shape
+end
+
+-- ------------------------------------------------------------------------------------------------ frame
+-- frame(st, buf, off, len) -> channels decoded | nil, message. Output: st.pcm, 1024 frames interleaved.
+function Decode.frame(st: State, buf: buffer, off: number, len: number): (number?, string?)
+ if buffer.len(B) < len + 16 then
+ B = buffer.create(len + 256)
+ end
+ buffer.copy(B, 0, buf, off, len)
+ buffer.fill(B, len, 0, 16)
+ BP, BL, OVER = 0, len * 8, false
+ local chans = st.ch
+ local nextCh = 1
+ local order: { Channel } = {}
+ local lastElement = -1
+ while true do
+ if BP + 3 > BL then
+ break -- tolerate a missing END
+ end
+ local id = getBits(3)
+ if id == 7 then
+ break
+ end
+ if id == 0 or id == 3 then -- SCE / LFE
+ getBits(4)
+ local c = chans[nextCh]
+ if not c then
+ c = newChannel()
+ chans[nextCh] = c
+ end
+ local e = ics(st, c, false)
+ if e then
+ return nil, e
+ end
+ applyTns(st, c)
+ table.insert(order, c)
+ nextCh += 1
+ lastElement = id
+ elseif id == 1 then -- CPE
+ getBits(4)
+ local l, r = chans[nextCh], chans[nextCh + 1]
+ if not l then
+ l = newChannel()
+ chans[nextCh] = l
+ end
+ if not r then
+ r = newChannel()
+ chans[nextCh + 1] = r
+ end
+ local common = getBits(1) == 1
+ local msPresent = 0
+ local mask = table.create(8 * 64, 0)
+ if common then
+ local e = icsInfo(st, l)
+ if e then
+ return nil, e
+ end
+ r.windowSequence, r.windowShape, r.maxSfb, r.numGroups = l.windowSequence, l.windowShape, l.maxSfb, l.numGroups
+ for i = 1, 8 do
+ r.groupLen[i] = l.groupLen[i]
+ end
+ msPresent = getBits(2)
+ if msPresent == 1 then
+ for i = 1, l.numGroups * l.maxSfb do
+ mask[i] = getBits(1)
+ end
+ elseif msPresent == 2 then
+ for i = 1, l.numGroups * l.maxSfb do
+ mask[i] = 1
+ end
+ elseif msPresent == 3 then
+ return nil, "reserved ms_mask_present"
+ end
+ end
+ local e = ics(st, l, common)
+ if e then
+ return nil, e
+ end
+ e = ics(st, r, common)
+ if e then
+ return nil, e
+ end
+ if common and msPresent ~= 0 then
+ msStereo(st, l, r, mask)
+ end
+ if common then
+ intensity(st, l, r, mask, msPresent)
+ end
+ applyTns(st, l)
+ applyTns(st, r)
+ table.insert(order, l)
+ table.insert(order, r)
+ nextCh += 2
+ lastElement = id
+ elseif id == 2 then
+ return nil, "coupling channel elements are not supported"
+ elseif id == 4 then -- DSE
+ getBits(4)
+ local align = getBits(1)
+ local count = getBits(8)
+ if count == 255 then
+ count += getBits(8)
+ end
+ if align == 1 then
+ BP = (BP + 7) // 8 * 8
+ end
+ BP += count * 8
+ elseif id == 5 then -- PCE: skipped here (parsed from the configuration)
+ return nil, "program config element inside the stream is not supported"
+ elseif id == 6 then -- FIL
+ local count = getBits(4)
+ if count == 15 then
+ count += getBits(8) - 1
+ end
+ if count > 0 then
+ local start = BP
+ local kind = getBits(4)
+ if kind == 13 or kind == 14 then -- EXT_SBR_DATA / EXT_SBR_DATA_CRC
+ st.sbr = true
+ end
+ st.extensions += 1
+ local hook = st.onExtension
+ if hook then
+ hook(kind, lastElement, B, start, count * 8)
+ end
+ BP = start + count * 8
+ end
+ end
+ if OVER or BP > BL then
+ return nil, "frame runs past the end"
+ end
+ if nextCh > 9 then
+ return nil, "more than 8 channels"
+ end
+ end
+ local n = #order
+ if n == 0 then
+ return 0, nil
+ end
+ local pcm = st.pcm
+ local map = st.map
+ for i, c in order do
+ local o = if map and map[i] then map[i] else i
+ filterbank(st, c, pcm, n, o)
+ end
+ return n, nil
+end
+
+function Decode.state(sfIndex: number): State
+ return {
+ sfIndex = sfIndex,
+ channels = 0,
+ frameLength = 1024,
+ ch = {},
+ pcm = table.create(1024 * 8, 0),
+ random = 0x1f2e3d4c,
+ time = table.create(2048, 0),
+ frame = table.create(2048, 0),
+ short = table.create(256, 0),
+ onExtension = nil,
+ extensions = 0,
+ sbr = false,
+ map = nil,
+ }
+end
+
+local _ = abs
+local _2 = floor
+return Decode
diff --git a/src/Formats/codecs/Aac/Tables.luau b/src/Formats/codecs/Aac/Tables.luau
new file mode 100644
index 0000000..65305fb
--- /dev/null
+++ b/src/Formats/codecs/Aac/Tables.luau
@@ -0,0 +1,335 @@
+--!strict
+-- codecs/Aac/Tables: the AAC-LC tables of ISO/IEC 14496-3 (subpart 4, Annex 4.A): the scalefactor and the eleven
+-- spectral Huffman codebooks (code, length per symbol), the scalefactor band offsets per sampling rate (1024 and 128
+-- lines) and the TNS band limits. Transcribed from FFmpeg libavcodec/aactab.c (tables of the standard, no code;
+-- see licenses/NOTICE.md). Generated; do not edit.
+local Tables = {}
+
+Tables.SF_CODES = {
+ 262120, 262118, 262119, 262117, 524277, 524273, 524269, 524278, 524270, 524271, 524272, 524284, 524285, 524287, 524286, 524279,
+ 524280, 524283, 524281, 262116, 524282, 262115, 131055, 131056, 65525, 131054, 65522, 65523, 65524, 65521, 32758, 32759,
+ 16377, 16373, 16375, 16371, 16374, 16370, 8183, 8181, 4089, 4087, 4086, 2041, 4084, 2040, 1017, 1015,
+ 1013, 504, 503, 250, 248, 246, 121, 58, 56, 26, 11, 4, 0, 10, 12, 27,
+ 57, 59, 120, 122, 247, 249, 502, 505, 1012, 1014, 1016, 2037, 2036, 2038, 2039, 4085,
+ 4088, 8180, 8182, 8184, 16376, 16372, 65520, 32756, 65526, 32757, 262114, 524249, 524250, 524251, 524252, 524253,
+ 524254, 524248, 524242, 524243, 524244, 524245, 524246, 524274, 524255, 524263, 524264, 524265, 524266, 524267, 524262, 524256,
+ 524257, 524258, 524259, 524260, 524261, 524247, 524268, 524276, 524275,
+}
+
+Tables.SF_BITS = {
+ 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 18, 19, 18, 17, 17, 16, 17, 16, 16, 16, 16,
+ 15, 15, 14, 14, 14, 14, 14, 14, 13, 13, 12, 12, 12, 11, 12, 11, 10, 10, 10, 9, 9, 8, 8, 8, 7, 6, 6, 5, 4, 3,
+ 1, 4, 4, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 10, 11, 11, 11, 11, 12, 12, 13, 13, 13, 14, 14, 16, 15, 16, 15,
+ 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19,
+}
+
+Tables.SPEC_CODES = {
+ {
+ 2040, 497, 2045, 1013, 104, 1008, 2039, 492, 2037, 1009, 114, 1012, 116, 17, 118, 491,
+ 108, 1014, 2044, 481, 2033, 496, 97, 502, 2034, 490, 2043, 498, 105, 493, 119, 23,
+ 111, 486, 100, 485, 103, 21, 98, 18, 0, 20, 101, 22, 109, 489, 99, 484,
+ 107, 19, 113, 483, 112, 499, 2046, 487, 2035, 495, 96, 494, 2032, 482, 2042, 1011,
+ 106, 488, 117, 16, 115, 500, 110, 1015, 2038, 480, 2041, 1010, 102, 501, 2047, 503,
+ 2036,
+ },
+ {
+ 499, 111, 509, 235, 35, 234, 503, 232, 506, 242, 45, 112, 32, 6, 43, 110,
+ 40, 233, 505, 102, 248, 231, 27, 241, 500, 107, 501, 236, 42, 108, 44, 10,
+ 39, 103, 26, 245, 36, 8, 31, 9, 0, 7, 29, 11, 48, 239, 28, 100,
+ 30, 12, 41, 243, 47, 240, 508, 113, 498, 244, 33, 230, 247, 104, 504, 238,
+ 34, 101, 49, 2, 38, 237, 37, 106, 507, 114, 510, 105, 46, 246, 511, 109,
+ 502,
+ },
+ {
+ 0, 9, 239, 11, 25, 240, 491, 486, 1010, 10, 53, 495, 52, 55, 489, 493,
+ 487, 1011, 494, 1005, 8186, 492, 498, 2041, 2040, 1016, 4088, 8, 56, 1014, 54, 117,
+ 1009, 1003, 1004, 4084, 24, 118, 2036, 57, 116, 1007, 499, 500, 2038, 488, 1002, 8188,
+ 242, 497, 4091, 1013, 2035, 4092, 238, 1015, 32766, 496, 2037, 32765, 8187, 16378, 65535, 241,
+ 1008, 16380, 490, 1006, 16379, 4086, 4090, 32764, 2034, 4085, 65534, 1012, 2039, 32763, 4087, 4089,
+ 32762,
+ },
+ {
+ 7, 22, 246, 24, 8, 239, 495, 243, 2040, 25, 23, 237, 21, 1, 226, 240,
+ 112, 1008, 494, 241, 2042, 238, 228, 1010, 2038, 1007, 2045, 5, 20, 242, 9, 4,
+ 229, 244, 232, 1012, 6, 2, 231, 3, 0, 107, 227, 105, 499, 235, 230, 1014,
+ 110, 106, 500, 1004, 496, 1017, 245, 236, 2043, 234, 111, 1015, 2041, 1011, 4095, 233,
+ 109, 1016, 108, 104, 501, 1006, 498, 2036, 2039, 1009, 4094, 1005, 497, 2037, 2046, 1013,
+ 2044,
+ },
+ {
+ 8191, 4087, 2036, 2024, 1009, 2030, 2041, 4088, 8189, 4093, 2033, 1000, 488, 240, 492, 1006,
+ 2034, 4090, 4084, 1007, 498, 232, 112, 236, 496, 1002, 2035, 2027, 491, 234, 26, 8,
+ 25, 238, 495, 2029, 1008, 242, 115, 11, 0, 10, 113, 243, 2025, 2031, 494, 239,
+ 24, 9, 27, 235, 489, 2028, 2038, 1003, 499, 237, 114, 233, 497, 1005, 2039, 4086,
+ 2032, 1001, 493, 241, 490, 1004, 2040, 4089, 8188, 4092, 4085, 2026, 1011, 1010, 2037, 4091,
+ 8190,
+ },
+ {
+ 2046, 1021, 497, 491, 500, 490, 496, 1020, 2045, 1014, 485, 234, 108, 113, 104, 240,
+ 486, 1015, 499, 239, 50, 39, 40, 38, 49, 235, 503, 488, 111, 46, 8, 4,
+ 6, 41, 107, 494, 495, 114, 45, 2, 0, 3, 47, 115, 506, 487, 110, 43,
+ 7, 1, 5, 44, 109, 492, 505, 238, 48, 36, 42, 37, 51, 236, 498, 1016,
+ 484, 237, 106, 112, 105, 116, 241, 1018, 2047, 1017, 502, 493, 504, 489, 501, 1019,
+ 2044,
+ },
+ {
+ 0, 5, 55, 116, 242, 491, 1005, 2039, 4, 12, 53, 113, 236, 238, 494, 501,
+ 54, 52, 114, 234, 241, 489, 499, 1013, 115, 112, 235, 240, 497, 496, 1004, 1018,
+ 243, 237, 488, 495, 1007, 1009, 1017, 2043, 493, 239, 490, 498, 1011, 1016, 2041, 2044,
+ 1006, 492, 500, 1012, 1015, 2040, 4093, 4094, 2038, 1008, 1010, 1014, 2042, 2045, 4092, 4095,
+ },
+ {
+ 14, 5, 16, 48, 111, 241, 506, 1022, 3, 0, 4, 18, 44, 106, 117, 248,
+ 15, 2, 6, 20, 46, 105, 114, 245, 47, 17, 19, 42, 50, 108, 236, 250,
+ 113, 43, 45, 49, 109, 112, 242, 505, 239, 104, 51, 107, 110, 238, 249, 1020,
+ 504, 116, 115, 237, 240, 246, 502, 509, 1021, 243, 244, 247, 503, 507, 508, 1023,
+ },
+ {
+ 0, 5, 55, 231, 478, 974, 985, 1992, 1997, 4040, 4061, 8164, 8172, 4, 12, 53,
+ 114, 234, 237, 482, 977, 979, 992, 2008, 4047, 4053, 54, 52, 113, 232, 236, 481,
+ 975, 989, 987, 2000, 4039, 4052, 4068, 230, 112, 233, 477, 483, 978, 988, 1996, 1994,
+ 2014, 4056, 4074, 8155, 479, 235, 476, 486, 981, 990, 1995, 2013, 2012, 4045, 4066, 4071,
+ 8161, 976, 480, 484, 982, 1989, 2001, 2011, 4050, 2016, 4057, 4075, 8163, 8169, 1988, 485,
+ 983, 1990, 1999, 2010, 4043, 4058, 4067, 4073, 8166, 8179, 8183, 2003, 984, 993, 2004, 2009,
+ 4051, 4062, 8157, 8153, 8162, 8170, 8177, 8182, 2002, 980, 986, 1991, 2007, 2018, 4046, 4059,
+ 8152, 8174, 16368, 8180, 16370, 2017, 991, 1993, 2006, 4042, 4048, 4069, 4070, 8171, 8175, 16371,
+ 16372, 16373, 4064, 1998, 2005, 4038, 4049, 4065, 8160, 8168, 8176, 16369, 16376, 16374, 32764, 4072,
+ 2015, 4041, 4055, 4060, 8156, 8159, 8173, 8181, 16377, 16379, 32765, 32766, 8167, 4044, 4054, 4063,
+ 8158, 8154, 8165, 8178, 16378, 16375, 16380, 16381, 32767,
+ },
+ {
+ 34, 8, 29, 38, 95, 211, 463, 976, 983, 1005, 2032, 2038, 4093, 7, 0, 1,
+ 9, 32, 84, 96, 213, 220, 468, 973, 990, 2023, 28, 2, 6, 12, 30, 40,
+ 91, 205, 217, 462, 476, 985, 1009, 37, 11, 10, 13, 36, 87, 97, 204, 221,
+ 460, 478, 979, 999, 93, 33, 31, 35, 39, 89, 100, 216, 223, 466, 482, 989,
+ 1006, 209, 85, 41, 86, 88, 98, 206, 224, 226, 474, 980, 995, 2027, 457, 94,
+ 90, 92, 99, 202, 218, 455, 458, 480, 987, 1000, 2028, 483, 210, 203, 208, 215,
+ 219, 454, 469, 472, 970, 986, 2026, 2033, 481, 212, 207, 214, 222, 225, 464, 470,
+ 977, 981, 1010, 2030, 2043, 1001, 461, 456, 459, 465, 471, 479, 975, 992, 1007, 2022,
+ 2040, 4090, 1003, 477, 467, 473, 475, 978, 972, 988, 1002, 2029, 2035, 2041, 4089, 2034,
+ 974, 484, 971, 984, 982, 994, 997, 2024, 2036, 2037, 2039, 4091, 2042, 1004, 991, 993,
+ 996, 998, 1008, 2025, 2031, 4088, 4094, 4092, 4095,
+ },
+ {
+ 0, 6, 25, 61, 156, 198, 423, 912, 962, 991, 2022, 2035, 4091, 2028, 4090, 4094,
+ 910, 5, 1, 8, 20, 55, 66, 146, 175, 401, 421, 437, 926, 960, 930, 973,
+ 2006, 174, 23, 7, 9, 24, 57, 64, 142, 163, 184, 409, 428, 449, 945, 918,
+ 958, 970, 157, 60, 21, 22, 26, 59, 68, 145, 165, 190, 406, 430, 441, 929,
+ 913, 933, 981, 148, 154, 54, 56, 58, 65, 140, 155, 176, 195, 414, 427, 444,
+ 927, 911, 937, 975, 147, 191, 62, 63, 67, 69, 158, 167, 185, 404, 418, 442,
+ 451, 934, 935, 955, 980, 159, 416, 143, 141, 144, 152, 166, 182, 196, 415, 431,
+ 447, 921, 959, 948, 969, 999, 168, 438, 171, 164, 170, 178, 194, 197, 408, 420,
+ 440, 908, 932, 964, 966, 989, 1000, 173, 943, 402, 189, 188, 398, 407, 410, 419,
+ 433, 909, 920, 951, 979, 977, 987, 2013, 180, 990, 425, 411, 412, 417, 426, 429,
+ 435, 907, 946, 952, 974, 993, 992, 2002, 2021, 183, 2019, 443, 424, 422, 432, 434,
+ 439, 923, 922, 954, 949, 982, 2007, 996, 2008, 2026, 186, 2024, 928, 445, 436, 906,
+ 452, 914, 938, 944, 956, 983, 2004, 2012, 2011, 2005, 2032, 193, 2043, 968, 931, 917,
+ 925, 940, 942, 965, 984, 994, 998, 2020, 2023, 2016, 2025, 2039, 400, 2034, 915, 446,
+ 448, 916, 919, 941, 963, 961, 978, 2010, 2009, 2015, 2027, 2036, 2042, 405, 2040, 957,
+ 924, 939, 936, 947, 953, 976, 995, 997, 2018, 2014, 2029, 2033, 2041, 2044, 403, 4093,
+ 988, 950, 967, 972, 971, 985, 986, 2003, 2017, 2030, 2031, 2037, 2038, 4092, 4095, 413,
+ 450, 181, 161, 150, 151, 149, 153, 160, 162, 172, 169, 177, 179, 187, 192, 399,
+ 4,
+ },
+}
+
+Tables.SPEC_BITS = {
+ {
+ 11, 9, 11, 10, 7, 10, 11, 9, 11, 10, 7, 10, 7, 5, 7, 9, 7, 10, 11, 9, 11, 9, 7, 9, 11, 9, 11, 9, 7, 9,
+ 7, 5, 7, 9, 7, 9, 7, 5, 7, 5, 1, 5, 7, 5, 7, 9, 7, 9, 7, 5, 7, 9, 7, 9, 11, 9, 11, 9, 7, 9,
+ 11, 9, 11, 10, 7, 9, 7, 5, 7, 9, 7, 10, 11, 9, 11, 10, 7, 9, 11, 9, 11,
+ },
+ {
+ 9, 7, 9, 8, 6, 8, 9, 8, 9, 8, 6, 7, 6, 5, 6, 7, 6, 8, 9, 7, 8, 8, 6, 8, 9, 7, 9, 8, 6, 7,
+ 6, 5, 6, 7, 6, 8, 6, 5, 6, 5, 3, 5, 6, 5, 6, 8, 6, 7, 6, 5, 6, 8, 6, 8, 9, 7, 9, 8, 6, 8,
+ 8, 7, 9, 8, 6, 7, 6, 4, 6, 8, 6, 7, 9, 7, 9, 7, 6, 8, 9, 7, 9,
+ },
+ {
+ 1, 4, 8, 4, 5, 8, 9, 9, 10, 4, 6, 9, 6, 6, 9, 9, 9, 10, 9, 10, 13, 9, 9, 11, 11, 10, 12, 4, 6, 10,
+ 6, 7, 10, 10, 10, 12, 5, 7, 11, 6, 7, 10, 9, 9, 11, 9, 10, 13, 8, 9, 12, 10, 11, 12, 8, 10, 15, 9, 11, 15,
+ 13, 14, 16, 8, 10, 14, 9, 10, 14, 12, 12, 15, 11, 12, 16, 10, 11, 15, 12, 12, 15,
+ },
+ {
+ 4, 5, 8, 5, 4, 8, 9, 8, 11, 5, 5, 8, 5, 4, 8, 8, 7, 10, 9, 8, 11, 8, 8, 10, 11, 10, 11, 4, 5, 8,
+ 4, 4, 8, 8, 8, 10, 4, 4, 8, 4, 4, 7, 8, 7, 9, 8, 8, 10, 7, 7, 9, 10, 9, 10, 8, 8, 11, 8, 7, 10,
+ 11, 10, 12, 8, 7, 10, 7, 7, 9, 10, 9, 11, 11, 10, 12, 10, 9, 11, 11, 10, 11,
+ },
+ {
+ 13, 12, 11, 11, 10, 11, 11, 12, 13, 12, 11, 10, 9, 8, 9, 10, 11, 12, 12, 10, 9, 8, 7, 8, 9, 10, 11, 11, 9, 8,
+ 5, 4, 5, 8, 9, 11, 10, 8, 7, 4, 1, 4, 7, 8, 11, 11, 9, 8, 5, 4, 5, 8, 9, 11, 11, 10, 9, 8, 7, 8,
+ 9, 10, 11, 12, 11, 10, 9, 8, 9, 10, 11, 12, 13, 12, 12, 11, 10, 10, 11, 12, 13,
+ },
+ {
+ 11, 10, 9, 9, 9, 9, 9, 10, 11, 10, 9, 8, 7, 7, 7, 8, 9, 10, 9, 8, 6, 6, 6, 6, 6, 8, 9, 9, 7, 6,
+ 4, 4, 4, 6, 7, 9, 9, 7, 6, 4, 4, 4, 6, 7, 9, 9, 7, 6, 4, 4, 4, 6, 7, 9, 9, 8, 6, 6, 6, 6,
+ 6, 8, 9, 10, 9, 8, 7, 7, 7, 7, 8, 10, 11, 10, 9, 9, 9, 9, 9, 10, 11,
+ },
+ {
+ 1, 3, 6, 7, 8, 9, 10, 11, 3, 4, 6, 7, 8, 8, 9, 9, 6, 6, 7, 8, 8, 9, 9, 10, 7, 7, 8, 8, 9, 9,
+ 10, 10, 8, 8, 9, 9, 10, 10, 10, 11, 9, 8, 9, 9, 10, 10, 11, 11, 10, 9, 9, 10, 10, 11, 12, 12, 11, 10, 10, 10,
+ 11, 11, 12, 12,
+ },
+ {
+ 5, 4, 5, 6, 7, 8, 9, 10, 4, 3, 4, 5, 6, 7, 7, 8, 5, 4, 4, 5, 6, 7, 7, 8, 6, 5, 5, 6, 6, 7,
+ 8, 8, 7, 6, 6, 6, 7, 7, 8, 9, 8, 7, 6, 7, 7, 8, 8, 10, 9, 7, 7, 8, 8, 8, 9, 9, 10, 8, 8, 8,
+ 9, 9, 9, 10,
+ },
+ {
+ 1, 3, 6, 8, 9, 10, 10, 11, 11, 12, 12, 13, 13, 3, 4, 6, 7, 8, 8, 9, 10, 10, 10, 11, 12, 12, 6, 6, 7, 8,
+ 8, 9, 10, 10, 10, 11, 12, 12, 12, 8, 7, 8, 9, 9, 10, 10, 11, 11, 11, 12, 12, 13, 9, 8, 9, 9, 10, 10, 11, 11,
+ 11, 12, 12, 12, 13, 10, 9, 9, 10, 11, 11, 11, 12, 11, 12, 12, 13, 13, 11, 9, 10, 11, 11, 11, 12, 12, 12, 12, 13, 13,
+ 13, 11, 10, 10, 11, 11, 12, 12, 13, 13, 13, 13, 13, 13, 11, 10, 10, 11, 11, 11, 12, 12, 13, 13, 14, 13, 14, 11, 10, 11,
+ 11, 12, 12, 12, 12, 13, 13, 14, 14, 14, 12, 11, 11, 12, 12, 12, 13, 13, 13, 14, 14, 14, 15, 12, 11, 12, 12, 12, 13, 13,
+ 13, 13, 14, 14, 15, 15, 13, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15,
+ },
+ {
+ 6, 5, 6, 6, 7, 8, 9, 10, 10, 10, 11, 11, 12, 5, 4, 4, 5, 6, 7, 7, 8, 8, 9, 10, 10, 11, 6, 4, 5, 5,
+ 6, 6, 7, 8, 8, 9, 9, 10, 10, 6, 5, 5, 5, 6, 7, 7, 8, 8, 9, 9, 10, 10, 7, 6, 6, 6, 6, 7, 7, 8,
+ 8, 9, 9, 10, 10, 8, 7, 6, 7, 7, 7, 8, 8, 8, 9, 10, 10, 11, 9, 7, 7, 7, 7, 8, 8, 9, 9, 9, 10, 10,
+ 11, 9, 8, 8, 8, 8, 8, 9, 9, 9, 10, 10, 11, 11, 9, 8, 8, 8, 8, 8, 9, 9, 10, 10, 10, 11, 11, 10, 9, 9,
+ 9, 9, 9, 9, 10, 10, 10, 11, 11, 12, 10, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 12, 11, 10, 9, 10, 10, 10, 10,
+ 10, 11, 11, 11, 11, 12, 11, 10, 10, 10, 10, 10, 10, 11, 11, 12, 12, 12, 12,
+ },
+ {
+ 4, 5, 6, 7, 8, 8, 9, 10, 10, 10, 11, 11, 12, 11, 12, 12, 10, 5, 4, 5, 6, 7, 7, 8, 8, 9, 9, 9, 10, 10,
+ 10, 10, 11, 8, 6, 5, 5, 6, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 8, 7, 6, 6, 6, 7, 7, 8, 8, 8,
+ 9, 9, 9, 10, 10, 10, 10, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 8, 8, 7, 7, 7, 7,
+ 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 8, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 10, 8, 9,
+ 8, 8, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 10, 10, 8, 10, 9, 8, 8, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10,
+ 10, 11, 8, 10, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 11, 11, 8, 11, 9, 9, 9, 9, 9, 9, 10, 10, 10,
+ 10, 10, 11, 10, 11, 11, 8, 11, 10, 9, 9, 10, 9, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 8, 11, 10, 10, 10, 10, 10,
+ 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 9, 11, 10, 9, 9, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 9, 11, 10,
+ 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 9, 12, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 12,
+ 12, 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 5,
+ },
+}
+
+Tables.SWB_LONG = {
+ {
+ 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 96,
+ 108, 120, 132, 144, 156, 172, 188, 212, 240, 276, 320, 384, 448, 512, 576, 640, 704, 768, 832, 896,
+ 960, 1024,
+ },
+ {
+ 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 96,
+ 108, 120, 132, 144, 156, 172, 188, 212, 240, 276, 320, 384, 448, 512, 576, 640, 704, 768, 832, 896,
+ 960, 1024,
+ },
+ {
+ 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 100,
+ 112, 124, 140, 156, 172, 192, 216, 240, 268, 304, 344, 384, 424, 464, 504, 544, 584, 624, 664, 704,
+ 744, 784, 824, 864, 904, 944, 984, 1024,
+ },
+ {
+ 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120,
+ 132, 144, 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640,
+ 672, 704, 736, 768, 800, 832, 864, 896, 928, 1024,
+ },
+ {
+ 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120,
+ 132, 144, 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640,
+ 672, 704, 736, 768, 800, 832, 864, 896, 928, 1024,
+ },
+ {
+ 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120,
+ 132, 144, 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640,
+ 672, 704, 736, 768, 800, 832, 864, 896, 928, 960, 992, 1024,
+ },
+ {
+ 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 52, 60, 68, 76, 84, 92, 100, 108,
+ 116, 124, 136, 148, 160, 172, 188, 204, 220, 240, 260, 284, 308, 336, 364, 396, 432, 468, 508, 552,
+ 600, 652, 704, 768, 832, 896, 960, 1024,
+ },
+ {
+ 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 52, 60, 68, 76, 84, 92, 100, 108,
+ 116, 124, 136, 148, 160, 172, 188, 204, 220, 240, 260, 284, 308, 336, 364, 396, 432, 468, 508, 552,
+ 600, 652, 704, 768, 832, 896, 960, 1024,
+ },
+ {
+ 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124, 136, 148, 160, 172, 184,
+ 196, 212, 228, 244, 260, 280, 300, 320, 344, 368, 396, 424, 456, 492, 532, 572, 616, 664, 716, 772,
+ 832, 896, 960, 1024,
+ },
+ {
+ 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124, 136, 148, 160, 172, 184,
+ 196, 212, 228, 244, 260, 280, 300, 320, 344, 368, 396, 424, 456, 492, 532, 572, 616, 664, 716, 772,
+ 832, 896, 960, 1024,
+ },
+ {
+ 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124, 136, 148, 160, 172, 184,
+ 196, 212, 228, 244, 260, 280, 300, 320, 344, 368, 396, 424, 456, 492, 532, 572, 616, 664, 716, 772,
+ 832, 896, 960, 1024,
+ },
+ {
+ 0, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156, 172, 188, 204, 220, 236, 252,
+ 268, 288, 308, 328, 348, 372, 396, 420, 448, 476, 508, 544, 580, 620, 664, 712, 764, 820, 880, 944,
+ 1024,
+ },
+ {
+ 0, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156, 172, 188, 204, 220, 236, 252,
+ 268, 288, 308, 328, 348, 372, 396, 420, 448, 476, 508, 544, 580, 620, 664, 712, 764, 820, 880, 944,
+ 1024,
+ },
+}
+
+Tables.SWB_SHORT = {
+ {
+ 0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128,
+ },
+ {
+ 0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128,
+ },
+ {
+ 0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128,
+ },
+ {
+ 0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128,
+ },
+ {
+ 0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128,
+ },
+ {
+ 0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128,
+ },
+ {
+ 0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 64, 76, 92, 108, 128,
+ },
+ {
+ 0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 64, 76, 92, 108, 128,
+ },
+ {
+ 0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 60, 72, 88, 108, 128,
+ },
+ {
+ 0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 60, 72, 88, 108, 128,
+ },
+ {
+ 0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 60, 72, 88, 108, 128,
+ },
+ {
+ 0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 60, 72, 88, 108, 128,
+ },
+ {
+ 0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 60, 72, 88, 108, 128,
+ },
+}
+
+Tables.NUM_SWB_LONG = {
+ 41, 41, 47, 49, 49, 51, 47, 47, 43, 43, 43, 40, 40,
+}
+
+Tables.NUM_SWB_SHORT = {
+ 12, 12, 12, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15,
+}
+
+Tables.TNS_MAX_BANDS_LONG = {
+ 31, 31, 34, 40, 42, 51, 46, 46, 42, 42, 42, 39, 39,
+}
+
+Tables.TNS_MAX_BANDS_SHORT = {
+ 9, 9, 10, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+}
+
+return Tables
+
diff --git a/src/Formats/codecs/Aac/init.luau b/src/Formats/codecs/Aac/init.luau
new file mode 100644
index 0000000..c7e5e0b
--- /dev/null
+++ b/src/Formats/codecs/Aac/init.luau
@@ -0,0 +1,336 @@
+--!strict
+-- codecs/Aac: AAC-LC decoder (ISO/IEC 14496-3 subpart 4, ISO/IEC 13818-7): the AudioSpecificConfig (with a program
+-- config element, explicit and backward-compatible SBR signalling), ADTS headers, and raw_data_block decoding
+-- (codecs/Aac/Decode). A codec (layer 1): audio/m4a, audio/aac (ADTS), and later MP4 / MKV / MPEG-TS video build on it.
+-- Written from the standard (tables: codecs/Aac/Tables); no third-party code.
+-- Supports: AAC-LC (object type 2) 1 - 8 channels, all sampling rates, long / short / start / stop windows, sine and KBD
+-- windows, M/S, intensity stereo, PNS, TNS, pulses. HE-AAC (SBR, PS: object types 5 / 29, or implicit SBR payloads)
+-- decodes its AAC-LC core at the core rate; `decoder.onExtension` receives every FIL extension payload (the hook for a
+-- later SBR / PS module), `decoder.sbr` says whether one was seen. Not supported: AAC Main prediction, LTP, SSR gain
+-- control, coupling channels, 960-sample frames, ER / USAC object types (UNSUPPORTED).
+--
+-- local Aac = require("@formats/codecs/Aac")
+-- local dec, err = Aac.decoder(asc) -- an AudioSpecificConfig (buffer) or { objectType, sfIndex, channels }
+-- local frames, err = dec:decode(buf, offset, length) -- one raw_data_block -> dec.pcm (frames * channels floats)
+-- local h = Aac.adts(buf, offset, limit) -- an ADTS header: { headerSize, frameSize, objectType, sfIndex, ... }
+--
+-- Never throws: bad data returns nil, Err.
+local Err = require("@formats/core/Err")
+local Bits = require("@formats/core/Bits")
+local Decode = require("@formats/codecs/Aac/Decode")
+
+local Aac = {}
+
+Aac.RATES = { 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350 }
+local CONFIG_CHANNELS = { 1, 2, 3, 4, 5, 6, 8 }
+-- element order (AAC: C, L, R, ...) -> WAV order (L, R, C, LFE, ...) for channel configurations 3 .. 7
+local CONFIG_MAP: { [number]: { number } } = {
+ [3] = { 3, 1, 2 },
+ [4] = { 3, 1, 2, 4 },
+ [5] = { 3, 1, 2, 4, 5 },
+ [6] = { 3, 1, 2, 5, 6, 4 },
+ [7] = { 3, 7, 8, 1, 2, 5, 6, 4 },
+}
+
+export type Config = {
+ objectType: number, -- 2 = AAC-LC (the core object type when SBR / PS is signalled)
+ sfIndex: number,
+ sampleRate: number, -- the core rate
+ channelConfig: number,
+ channels: number,
+ sbr: boolean, -- SBR signalled (explicitly or backward-compatibly)
+ ps: boolean,
+ extensionRate: number?, -- the SBR output rate
+ frameLength: number,
+}
+
+local function rateIndex(rate: number): number
+ -- the nearest standard rate (ISO 14496-3 table 4.82 mapping for explicit frequencies)
+ local best, bi = math.huge, 4
+ for i, r in Aac.RATES do
+ if math.abs(r - rate) < best then
+ best, bi = math.abs(r - rate), i - 1
+ end
+ end
+ return bi
+end
+
+local function objectType(br: Bits.BitReader): number
+ local t = br:read(5)
+ if t == 31 then
+ t = 32 + br:read(6)
+ end
+ return t
+end
+
+local function frequency(br: Bits.BitReader): (number, number)
+ local i = br:read(4)
+ if i == 15 then
+ local f = br:read(24)
+ return rateIndex(f), f
+ end
+ return i, Aac.RATES[i + 1] or 0
+end
+
+-- pce(br) -> channels (program_config_element)
+local function pce(br: Bits.BitReader): number
+ br:read(4 + 2 + 4)
+ local front, side, back = br:read(4), br:read(4), br:read(4)
+ local lfe, assoc, cc = br:read(2), br:read(3), br:read(4)
+ if br:read(1) == 1 then
+ br:read(4)
+ end
+ if br:read(1) == 1 then
+ br:read(4)
+ end
+ if br:read(1) == 1 then
+ br:read(3)
+ end
+ local channels = 0
+ for _ = 1, front + side + back do
+ channels += if br:read(1) == 1 then 2 else 1
+ br:read(4)
+ end
+ channels += lfe
+ br:skip(lfe * 4 + assoc * 4 + cc * 5)
+ br:align()
+ br:skip(br:read(8) * 8)
+ return channels
+end
+
+-- config(asc) -> Config | nil, Err: parse an AudioSpecificConfig
+function Aac.config(asc: buffer): (Config?, Err.Err?)
+ if type(asc) ~= "buffer" or buffer.len(asc) < 2 then
+ return nil, Err.new(Err.TRUNCATED, "AudioSpecificConfig is shorter than 2 bytes")
+ end
+ local br = Bits.msbReader(asc)
+ local aot = objectType(br)
+ local sfi, rate = frequency(br)
+ local chcfg = br:read(4)
+ local sbr, ps = false, false
+ local extRate: number? = nil
+ if aot == 5 or aot == 29 then
+ sbr = true
+ ps = aot == 29
+ local _, er = frequency(br)
+ extRate = er
+ aot = objectType(br)
+ if aot == 22 then
+ br:read(4)
+ end
+ end
+ if aot ~= 2 and aot ~= 1 and aot ~= 4 then
+ if aot == 0 or br.err then
+ return nil, Err.new(Err.CORRUPT, "bad AudioSpecificConfig")
+ end
+ return nil, Err.new(Err.UNSUPPORTED, "AAC object type " .. aot .. " (only AAC-LC)")
+ end
+ if aot ~= 2 then
+ return nil, Err.new(Err.UNSUPPORTED, if aot == 1 then "AAC Main" else "AAC LTP")
+ end
+ -- GASpecificConfig
+ local frameLengthFlag = br:read(1)
+ if br:read(1) == 1 then
+ br:read(14)
+ end
+ local ext = br:read(1)
+ local channels = CONFIG_CHANNELS[chcfg] or 0
+ if chcfg == 0 then
+ channels = pce(br)
+ elseif chcfg > 7 then
+ return nil, Err.new(Err.UNSUPPORTED, "channel configuration " .. chcfg)
+ end
+ if ext == 1 then
+ br:read(1) -- extensionFlag3
+ end
+ -- backward-compatible SBR signalling
+ if not sbr and br:bitsLeft() >= 16 then
+ if br:read(11) == 0x2b7 then
+ local et = objectType(br)
+ if et == 5 and br:read(1) == 1 then
+ sbr = true
+ local _, er = frequency(br)
+ extRate = er
+ if br:bitsLeft() >= 12 and br:read(11) == 0x548 then
+ ps = br:read(1) == 1
+ end
+ end
+ end
+ end
+ if br.err and channels == 0 then
+ return nil, br.err
+ end
+ if sfi > 12 or rate <= 0 then
+ return nil, Err.new(Err.CORRUPT, "bad sampling frequency index " .. sfi)
+ end
+ if frameLengthFlag == 1 then
+ return nil, Err.new(Err.UNSUPPORTED, "960-sample AAC frames")
+ end
+ if channels < 1 or channels > 8 then
+ return nil, Err.new(Err.UNSUPPORTED, channels .. " channels")
+ end
+ return {
+ objectType = aot,
+ sfIndex = sfi,
+ sampleRate = rate,
+ channelConfig = chcfg,
+ channels = channels,
+ sbr = sbr,
+ ps = ps,
+ extensionRate = extRate,
+ frameLength = 1024,
+ }, nil
+end
+
+-- asc(objectType, sfIndex, channelConfig) -> a 2-byte AudioSpecificConfig
+function Aac.asc(aot: number, sfIndex: number, channelConfig: number): buffer
+ local b = buffer.create(2)
+ local v = aot * 2048 + sfIndex * 128 + channelConfig * 8
+ buffer.writeu8(b, 0, bit32.rshift(v, 8))
+ buffer.writeu8(b, 1, bit32.band(v, 255))
+ return b
+end
+
+export type Adts = {
+ headerSize: number, -- 7, or 9 with a CRC
+ frameSize: number, -- the whole frame, header included
+ objectType: number,
+ sfIndex: number,
+ sampleRate: number,
+ channelConfig: number,
+ blocks: number, -- raw_data_blocks in the frame (1 .. 4)
+ protected: boolean,
+}
+
+-- adts(buf, offset, limit) -> Adts | nil (not a valid header at offset)
+function Aac.adts(b: buffer, o: number, limit: number): Adts?
+ if o < 0 or o + 7 > limit or o + 7 > buffer.len(b) then
+ return nil
+ end
+ local b0, b1, b2, b3, b4, b5, b6 = buffer.readu8(b, o), buffer.readu8(b, o + 1), buffer.readu8(b, o + 2), buffer.readu8(b, o + 3), buffer.readu8(b, o + 4), buffer.readu8(b, o + 5), buffer.readu8(b, o + 6)
+ if b0 ~= 0xFF or bit32.band(b1, 0xF6) ~= 0xF0 then -- sync, layer 0
+ return nil
+ end
+ local protected = bit32.band(b1, 1) == 0
+ local profile = bit32.rshift(b2, 6)
+ local sfi = bit32.band(bit32.rshift(b2, 2), 15)
+ local ch = bit32.band(b2, 1) * 4 + bit32.rshift(b3, 6)
+ local size = bit32.band(b3, 3) * 2048 + b4 * 8 + bit32.rshift(b5, 5)
+ local blocks = bit32.band(b6, 3) + 1
+ local hs = if protected then 9 else 7
+ if sfi > 12 or size < hs then
+ return nil
+ end
+ return {
+ headerSize = hs,
+ frameSize = size,
+ objectType = profile + 1,
+ sfIndex = sfi,
+ sampleRate = Aac.RATES[sfi + 1],
+ channelConfig = ch,
+ blocks = blocks,
+ protected = protected,
+ }
+end
+
+-- ------------------------------------------------------------------------------------------------ decoder
+export type Decoder = {
+ config: Config,
+ channels: number,
+ sampleRate: number,
+ frameLength: number,
+ pcm: { number }, -- the last frame: 1024 * channels interleaved floats (-1 .. 1), WAV channel order
+ sbr: boolean, -- SBR payloads seen in the stream (implicit signalling) or signalled
+ onExtension: ((kind: number, element: number, buf: buffer, bitPos: number, bits: number) -> ())?,
+ decode: (self: Decoder, buf: buffer, offset: number?, length: number?) -> (number?, Err.Err?),
+ reset: (self: Decoder) -> (),
+ state: Decode.State,
+}
+
+local function decode(self: Decoder, buf: buffer, offset: number?, length: number?): (number?, Err.Err?)
+ local o = offset or 0
+ local n = length or (buffer.len(buf) - o)
+ if type(buf) ~= "buffer" or o < 0 or n < 0 or o + n > buffer.len(buf) then
+ return nil, Err.new(Err.ARG, "packet range out of the buffer")
+ end
+ local st = self.state
+ st.onExtension = self.onExtension
+ local chans, msg = Decode.frame(st, buf, o, n)
+ if not chans then
+ return nil, Err.new(Err.CORRUPT, msg or "bad frame", o)
+ end
+ if st.sbr then
+ self.sbr = true
+ end
+ if chans == 0 then
+ -- an empty frame (only fill elements): silence
+ for i = 1, 1024 * self.channels do
+ st.pcm[i] = 0
+ end
+ return 1024, nil
+ end
+ if chans ~= self.channels then
+ return nil, Err.new(Err.CORRUPT, string.format("frame has %d channels, the configuration %d", chans, self.channels), o)
+ end
+ return 1024, nil
+end
+
+local function reset(self: Decoder)
+ for _, c in self.state.ch do
+ for i = 1, 1024 do
+ c.overlap[i] = 0
+ end
+ c.prevShape = 0
+ end
+end
+
+-- decoder(asc | { objectType?, sfIndex, channels }) -> Decoder | nil, Err
+function Aac.decoder(asc: any): (Decoder?, Err.Err?)
+ local cfg: Config
+ if type(asc) == "buffer" then
+ local c, err = Aac.config(asc)
+ if not c then
+ return nil, err
+ end
+ cfg = c
+ elseif type(asc) == "table" and type(asc.sfIndex) == "number" and type(asc.channels) == "number" then
+ local sfi = asc.sfIndex
+ if sfi < 0 or sfi > 12 or asc.channels < 1 or asc.channels > 8 then
+ return nil, Err.new(Err.ARG, "bad sampling index / channels")
+ end
+ if (asc.objectType or 2) ~= 2 then
+ return nil, Err.new(Err.UNSUPPORTED, "AAC object type " .. asc.objectType .. " (only AAC-LC)")
+ end
+ cfg = {
+ objectType = 2,
+ sfIndex = sfi,
+ sampleRate = Aac.RATES[sfi + 1],
+ channelConfig = asc.channelConfig or asc.channels,
+ channels = asc.channels,
+ sbr = false,
+ ps = false,
+ frameLength = 1024,
+ }
+ else
+ return nil, Err.new(Err.ARG, "decoder: expected an AudioSpecificConfig buffer")
+ end
+ local st = Decode.state(cfg.sfIndex)
+ st.channels = cfg.channels
+ if cfg.channelConfig >= 3 then
+ st.map = CONFIG_MAP[cfg.channelConfig]
+ end
+ return {
+ config = cfg,
+ channels = cfg.channels,
+ sampleRate = cfg.sampleRate,
+ frameLength = 1024,
+ pcm = st.pcm,
+ sbr = cfg.sbr,
+ onExtension = nil,
+ decode = decode,
+ reset = reset,
+ state = st,
+ }, nil
+end
+
+return Aac
diff --git a/src/Formats/codecs/Alac/Decode.luau b/src/Formats/codecs/Alac/Decode.luau
new file mode 100644
index 0000000..932d7e7
--- /dev/null
+++ b/src/Formats/codecs/Alac/Decode.luau
@@ -0,0 +1,427 @@
+--!strict
+--!native
+--!optimize 2
+-- codecs/Alac/Decode: the ALAC frame decoder: elements SCE / CPE / LFE / DSE / FIL / END, the adaptive Golomb-Rice
+-- residuals with zero runs, the adaptive FIR predictor (orders 0, 31 and 1 .. 30), stereo unmixing, shifted low bytes,
+-- uncompressed (escape) frames, 16 / 20 / 24 / 32-bit samples. Written from the ALAC format as published by Apple
+-- (ALACDecoder / ag_dec / dp_dec, Apache 2.0; behaviour, not code). Never throws: returns nil, message.
+local readu32, readu8 = buffer.readu32, buffer.readu8
+local byteswap, lshift, rshift, band, countlz, bnot = bit32.byteswap, bit32.lshift, bit32.rshift, bit32.band, bit32.countlz, bit32.bnot
+local floor = math.floor
+
+local Decode = {}
+
+export type State = {
+ frameLength: number,
+ bitDepth: number,
+ pb: number,
+ mb: number,
+ kb: number,
+ channels: number,
+ maxRun: number,
+ scratch: buffer, -- the packet + 16 zero bytes (reads past the end are safe; the overrun is checked)
+ pred: { { number } }, -- per element channel (0, 1): residuals / predictor output
+ mix: { { number } },
+ shift: { number },
+ out: { number }, -- interleaved output samples (integers), frames * channels
+}
+
+local POW = table.create(64, 0)
+for i = 0, 63 do
+ POW[i + 1] = 2 ^ i
+end
+
+-- bit reader over st.scratch: pos = bit position. bits(n) for n <= 25.
+local function bitsAt(b: buffer, pos: number, n: number): number
+ local w = byteswap(readu32(b, rshift(pos, 3)))
+ return rshift(lshift(w, band(pos, 7)), 32 - n)
+end
+
+local function signExtend(v: number, bits: number): number
+ local m = POW[bits + 1]
+ v = v % m
+ if v >= m / 2 then
+ v -= m
+ end
+ return v
+end
+
+-- the adaptive Golomb-Rice value: unary prefix (escape after 9 ones: `bps` raw bits), then k bits
+local function scalar(b: buffer, pos: number, k: number, m: number, bps: number): (number, number)
+ local w = lshift(byteswap(readu32(b, rshift(pos, 3))), band(pos, 7))
+ local pre = countlz(bnot(w))
+ if pre >= 9 then
+ pos += 9
+ local v
+ if bps > 25 then
+ v = bitsAt(b, pos, bps - 16) * 65536 + bitsAt(b, pos + bps - 16, 16)
+ else
+ v = bitsAt(b, pos, bps)
+ end
+ return v, pos + bps
+ end
+ pos += pre + 1
+ if k == 1 then
+ return pre, pos
+ end
+ local v = bitsAt(b, pos, k)
+ local x = pre * m
+ if v > 1 then
+ return x + v - 1, pos + k
+ end
+ return x, pos + k - 1
+end
+
+-- residuals: n values into out[1..n]; returns the new bit position or -1
+local function rice(b: buffer, pos: number, limit: number, out: { number }, n: number, bps: number, mult: number, st: State): number
+ local history = st.mb
+ local kb = st.kb
+ local signMod = 0
+ local i = 1
+ while i <= n do
+ if pos > limit then
+ return -1 -- each value reads at most 41 bits past here: inside the 16 padding bytes
+ end
+ local k = 31 - countlz(floor(history / 512) + 3)
+ if k > kb then
+ k = kb
+ end
+ local x
+ x, pos = scalar(b, pos, k, POW[k + 1] - 1, bps)
+ x += signMod
+ signMod = 0
+ out[i] = if x % 2 == 0 then x / 2 else -(x + 1) / 2
+ if x > 0xFFFF then
+ history = 0xFFFF
+ else
+ history += x * mult - floor(history * mult / 512)
+ end
+ if history < 128 and i < n then
+ if pos > limit then
+ return -1
+ end
+ local lg = if history > 0 then 31 - countlz(history) else 0
+ k = 7 - lg + floor((history + 16) / 64)
+ if k > kb then
+ k = kb
+ end
+ local run
+ run, pos = scalar(b, pos, k, POW[k + 1] - 1, 16)
+ if run > 0 then
+ if run > n - i then
+ return -1
+ end
+ for j = i + 1, i + run do
+ out[j] = 0
+ end
+ i += run
+ end
+ if run < 0xFFFF then
+ signMod = 1 -- the next value is not 0 (unless the run hit its maximum)
+ end
+ history = 0
+ end
+ i += 1
+ end
+ return pos
+end
+
+-- the adaptive FIR predictor: err[1..n] -> out[1..n] (may be the same array); coefs adapt in place
+local function predict(err: { number }, out: { number }, n: number, bps: number, coefs: { number }, order: number, quant: number)
+ out[1] = err[1]
+ if n <= 1 then
+ return
+ end
+ if order == 0 then
+ if out ~= err then
+ for i = 2, n do
+ out[i] = err[i]
+ end
+ end
+ return
+ end
+ if order == 31 then
+ for i = 2, n do
+ out[i] = signExtend(out[i - 1] + err[i], bps)
+ end
+ return
+ end
+ local i = 2
+ while i <= order + 1 and i <= n do
+ out[i] = signExtend(out[i - 1] + err[i], bps)
+ i += 1
+ end
+ local half = if quant > 0 then POW[quant] else 0
+ local qd = POW[quant + 1]
+ -- coefs[1] multiplies the most recent sample
+ while i <= n do
+ local d = out[i - order - 1]
+ local val = 0
+ for j = 1, order do
+ val += (out[i - j] - d) * coefs[j]
+ end
+ val = floor((val + half) / qd)
+ local e = err[i]
+ out[i] = signExtend(val + d + e, bps)
+ if e ~= 0 then
+ local es = if e > 0 then 1 else -1
+ -- adapt from the oldest sample to the newest while the error keeps its sign
+ for j = order, 1, -1 do
+ if e * es <= 0 then
+ break
+ end
+ local v = d - out[i - j]
+ local sgn = if v > 0 then es elseif v < 0 then -es else 0
+ coefs[j] -= sgn
+ e -= floor(v * sgn / qd) * (order - j + 1)
+ end
+ end
+ i += 1
+ end
+end
+
+-- decode(st, buf, off, len) -> frames | nil, message. Samples land interleaved in st.out (integers), channels in the
+-- ALAC element order.
+function Decode.frame(st: State, buf: buffer, off: number, len: number): (number?, string?)
+ if len <= 0 then
+ return nil, "empty packet"
+ end
+ local b = st.scratch
+ if buffer.len(b) < len + 16 then
+ b = buffer.create(len + 64)
+ st.scratch = b
+ end
+ buffer.copy(b, 0, buf, off, len)
+ buffer.fill(b, len, 0, 16)
+ local limit = len * 8
+ local pos = 0
+ local channels = st.channels
+ local ch = 0 -- next output channel
+ local frames = -1
+ local out = st.out
+ while true do
+ if pos + 3 > limit then
+ return nil, "frame runs past the end"
+ end
+ local tag = bitsAt(b, pos, 3)
+ pos += 3
+ if tag == 7 then -- END
+ break
+ elseif tag == 0 or tag == 1 or tag == 3 then -- SCE / CPE / LFE
+ local nch = if tag == 1 then 2 else 1
+ if ch + nch > channels then
+ return nil, "more channels than the configuration"
+ end
+ pos += 4 -- element instance tag
+ if bitsAt(b, pos, 12) ~= 0 then
+ return nil, "bad element header"
+ end
+ pos += 12
+ local h = bitsAt(b, pos, 4)
+ pos += 4
+ local partial = rshift(h, 3)
+ local shiftBytes = band(rshift(h, 1), 3)
+ local escape = band(h, 1)
+ if shiftBytes == 3 then
+ return nil, "bad shift"
+ end
+ local n = st.frameLength
+ if partial == 1 then
+ n = bitsAt(b, pos, 16) * 65536 + bitsAt(b, pos + 16, 16)
+ pos += 32
+ end
+ if n < 1 or n > st.frameLength then
+ return nil, "bad frame length " .. n
+ end
+ if frames >= 0 and n ~= frames then
+ return nil, "elements of different lengths"
+ end
+ frames = n
+ if #out < n * channels then
+ for k = #out + 1, n * channels do
+ out[k] = 0
+ end
+ end
+ local shift = shiftBytes * 8
+ local bps = st.bitDepth - shift + nch - 1
+ if bps > 32 or bps < 1 then
+ return nil, "bad sample size"
+ end
+ if pos > limit then
+ return nil, "frame runs past the end"
+ end
+ local mixBits, mixRes = 0, 0
+ local p0, p1 = st.pred[1], st.pred[2]
+ local m0, m1 = st.mix[1], st.mix[2]
+ local shiftBuf = st.shift
+ if escape == 0 then
+ mixBits = bitsAt(b, pos, 8)
+ mixRes = bitsAt(b, pos + 8, 8)
+ pos += 16
+ if mixRes >= 128 then
+ mixRes -= 256
+ end
+ local mode, denShift, pbFactor, order = {}, {}, {}, {}
+ local coefs = { {}, {} }
+ for c = 1, nch do
+ local x = bitsAt(b, pos, 8)
+ local y = bitsAt(b, pos + 8, 8)
+ pos += 16
+ mode[c], denShift[c] = rshift(x, 4), band(x, 15)
+ pbFactor[c], order[c] = rshift(y, 5), band(y, 31)
+ if pos + order[c] * 16 > limit then
+ return nil, "frame runs past the end"
+ end
+ for j = 1, order[c] do
+ local v = bitsAt(b, pos, 16)
+ pos += 16
+ coefs[c][j] = if v >= 32768 then v - 65536 else v
+ end
+ end
+ if pos > limit then
+ return nil, "frame runs past the end"
+ end
+ local shiftPos = pos
+ if shift > 0 then
+ pos += shift * n * nch
+ end
+ for c = 1, nch do
+ local p = if c == 1 then p0 else p1
+ local mb = if c == 1 then m0 else m1
+ pos = rice(b, pos, limit, p, n, bps, floor(st.pb * pbFactor[c] / 4), st)
+ if pos < 0 or pos > limit then
+ return nil, "bad residuals"
+ end
+ if mode[c] == 15 then
+ predict(p, p, n, bps, {}, 31, 0)
+ elseif mode[c] ~= 0 then
+ return nil, "unknown prediction mode " .. mode[c]
+ end
+ predict(p, mb, n, bps, coefs[c], order[c], denShift[c])
+ end
+ if shift > 0 then
+ local sp = shiftPos
+ for i = 1, n * nch do
+ shiftBuf[i] = bitsAt(b, sp, shift)
+ sp += shift
+ end
+ end
+ else
+ -- uncompressed: interleaved samples of bitDepth bits
+ local bits = st.bitDepth
+ if pos + n * nch * bits > limit then
+ return nil, "frame runs past the end"
+ end
+ for i = 1, n do
+ for c = 1, nch do
+ local v
+ if bits > 25 then
+ v = bitsAt(b, pos, bits - 16) * 65536 + bitsAt(b, pos + bits - 16, 16)
+ else
+ v = bitsAt(b, pos, bits)
+ end
+ pos += bits
+ v = signExtend(v, bits)
+ if c == 1 then
+ m0[i] = v
+ else
+ m1[i] = v
+ end
+ end
+ end
+ shift = 0
+ end
+ -- unmix + shifted bytes -> interleaved output
+ local sm = POW[shift + 1]
+ if nch == 2 then
+ local den = POW[mixBits + 1]
+ for i = 1, n do
+ local u, v = m0[i], m1[i]
+ local l, r
+ if mixRes ~= 0 then
+ l = u + v - floor(mixRes * v / den)
+ r = l - v
+ else
+ l, r = u, v
+ end
+ if shift > 0 then
+ l = l * sm + shiftBuf[2 * i - 1]
+ r = r * sm + shiftBuf[2 * i]
+ end
+ local o = (i - 1) * channels + ch + 1
+ out[o] = l
+ out[o + 1] = r
+ end
+ else
+ for i = 1, n do
+ local v = m0[i]
+ if shift > 0 then
+ v = v * sm + shiftBuf[i]
+ end
+ out[(i - 1) * channels + ch + 1] = v
+ end
+ end
+ ch += nch
+ elseif tag == 4 then -- DSE
+ pos += 4
+ local align = bitsAt(b, pos, 1)
+ local count = bitsAt(b, pos + 1, 8)
+ pos += 9
+ if count == 255 then
+ count += bitsAt(b, pos, 8)
+ pos += 8
+ end
+ if align == 1 then
+ pos = (pos + 7) // 8 * 8
+ end
+ pos += count * 8
+ elseif tag == 6 then -- FIL
+ local count = bitsAt(b, pos, 4)
+ pos += 4
+ if count == 15 then
+ count += bitsAt(b, pos, 8) - 1
+ pos += 8
+ end
+ pos += count * 8
+ else
+ return nil, "unsupported element " .. tag
+ end
+ if pos > limit then
+ return nil, "frame runs past the end"
+ end
+ end
+ if frames < 0 then
+ return 0, nil
+ end
+ if ch < channels then
+ -- missing channels: silence
+ for i = 1, frames do
+ for c = ch + 1, channels do
+ out[(i - 1) * channels + c] = 0
+ end
+ end
+ end
+ return frames, nil
+end
+
+-- the scratch state for a configuration
+function Decode.state(cfg: any): State
+ local n = cfg.frameLength
+ return {
+ frameLength = n,
+ bitDepth = cfg.bitDepth,
+ pb = cfg.pb,
+ mb = cfg.mb,
+ kb = cfg.kb,
+ channels = cfg.channels,
+ maxRun = cfg.maxRun,
+ scratch = buffer.create(math.max(64, cfg.maxFrameBytes or 0) + 64),
+ pred = { table.create(n, 0), table.create(n, 0) },
+ mix = { table.create(n, 0), table.create(n, 0) },
+ shift = table.create(n * 2, 0),
+ out = table.create(n * cfg.channels, 0),
+ }
+end
+
+local _ = readu8
+return Decode
diff --git a/src/Formats/codecs/Alac/Encode.luau b/src/Formats/codecs/Alac/Encode.luau
new file mode 100644
index 0000000..4309bd5
--- /dev/null
+++ b/src/Formats/codecs/Alac/Encode.luau
@@ -0,0 +1,427 @@
+--!strict
+--!native
+--!optimize 2
+-- codecs/Alac/Encode: an ALAC frame encoder: per element (SCE / CPE) the stereo mix (mixBits 2, the best mixRes of
+-- 0 .. 4 by first-difference energy), per channel LPC coefficients (Levinson-Durbin on a windowed autocorrelation,
+-- orders 4 and 8 tried, quantised with denShift 9), residuals through the same adaptive FIR the decoder runs, the
+-- adaptive Golomb-Rice code with zero runs; an uncompressed (escape) frame when that is smaller. 16 / 20 / 24-bit
+-- input. Written for this library from the ALAC format; no third-party code. Never throws.
+local band, rshift, bor, lshift, countlz = bit32.band, bit32.rshift, bit32.bor, bit32.lshift, bit32.countlz
+local readu8, writeu8 = buffer.readu8, buffer.writeu8
+local floor, abs = math.floor, math.abs
+
+local Encode = {}
+
+local POW = table.create(64, 0)
+for i = 0, 63 do
+ POW[i + 1] = 2 ^ i
+end
+
+local DENSHIFT = 9
+local PB_FACTOR = 4
+
+export type State = {
+ frameLength: number,
+ bitDepth: number,
+ pb: number,
+ mb: number,
+ kb: number,
+ channels: number,
+ out: buffer, -- packet scratch
+ pos: number, -- bit position in out
+ cap: number, -- bits available
+ u: { number },
+ v: { number },
+ err: { number },
+ work: { number },
+}
+
+-- ------------------------------------------------------------------------------------------------ bit writer
+local function put(st: State, v: number, n: number)
+ local pos = st.pos
+ if pos + n > st.cap then
+ st.pos = st.cap + 1 -- overflow: the caller falls back to an uncompressed frame
+ return
+ end
+ local b = st.out
+ while n > 0 do
+ local byte = rshift(pos, 3)
+ local free = 8 - band(pos, 7)
+ local take = if n < free then n else free
+ local bits = band(rshift(v, n - take), POW[take + 1] - 1)
+ writeu8(b, byte, bor(readu8(b, byte), lshift(bits, free - take)))
+ pos += take
+ n -= take
+ end
+ st.pos = pos
+end
+
+local function putBig(st: State, v: number, n: number)
+ if n > 24 then
+ local lo = v % 65536
+ put(st, (v - lo) / 65536, n - 16)
+ put(st, lo, 16)
+ else
+ put(st, v, n)
+ end
+end
+
+-- ------------------------------------------------------------------------------------------------ rice code
+local function signExtend(v: number, bits: number): number
+ local m = POW[bits + 1]
+ v = v % m
+ if v >= m / 2 then
+ v -= m
+ end
+ return v
+end
+
+-- the bits of one scalar (no writing)
+local function scalarBits(x: number, k: number, m: number, bps: number): number
+ local pre = if k == 1 then x else floor(x / m)
+ if pre >= 9 then
+ return 9 + bps
+ end
+ if k == 1 then
+ return pre + 1
+ end
+ local r = x - pre * m
+ return pre + 1 + (if r == 0 then k - 1 else k)
+end
+
+local function scalar(st: State, x: number, k: number, m: number, bps: number)
+ local pre = if k == 1 then x else floor(x / m)
+ if pre >= 9 then
+ put(st, 511, 9)
+ putBig(st, x, bps)
+ return
+ end
+ -- pre ones and a zero
+ put(st, POW[pre + 2] - 2, pre + 1)
+ if k ~= 1 then
+ local r = x - pre * m
+ if r == 0 then
+ put(st, 0, k - 1)
+ else
+ put(st, r + 1, k)
+ end
+ end
+end
+
+-- code the residuals e[1..n] (write = false: just count the bits)
+local function rice(st: State, e: { number }, n: number, bps: number, mult: number, write: boolean): number
+ local history = st.mb
+ local kb = st.kb
+ local signMod = 0
+ local bits = 0
+ local i = 1
+ while i <= n do
+ local k = 31 - countlz(floor(history / 512) + 3)
+ if k > kb then
+ k = kb
+ end
+ local v = e[i]
+ local zz = if v >= 0 then 2 * v else -2 * v - 1
+ local x = zz - signMod
+ signMod = 0
+ local m = POW[k + 1] - 1
+ if write then
+ scalar(st, x, k, m, bps)
+ else
+ bits += scalarBits(x, k, m, bps)
+ end
+ if zz > 0xFFFF then -- the decoder adapts on the value with its sign modifier added back
+ history = 0xFFFF
+ else
+ history += zz * mult - floor(history * mult / 512)
+ end
+ if history < 128 and i < n then
+ local lg = if history > 0 then 31 - countlz(history) else 0
+ k = 7 - lg + floor((history + 16) / 64)
+ if k > kb then
+ k = kb
+ end
+ local run = 0
+ while i + run < n and e[i + run + 1] == 0 and run < 0xFFFF do
+ run += 1
+ end
+ m = POW[k + 1] - 1
+ if write then
+ scalar(st, run, k, m, 16)
+ else
+ bits += scalarBits(run, k, m, 16)
+ end
+ i += run
+ if run < 0xFFFF then
+ signMod = 1
+ end
+ history = 0
+ end
+ i += 1
+ end
+ return bits
+end
+
+-- ------------------------------------------------------------------------------------------------ prediction
+-- residuals of x[1..n] under the decoder's adaptive FIR starting from coefs (adapted in place, like the decoder)
+local function residuals(x: { number }, e: { number }, n: number, bps: number, coefs: { number }, order: number, quant: number)
+ e[1] = x[1]
+ if n <= 1 then
+ return
+ end
+ local i = 2
+ while i <= order + 1 and i <= n do
+ e[i] = signExtend(x[i] - x[i - 1], bps)
+ i += 1
+ end
+ local half = POW[quant]
+ local qd = POW[quant + 1]
+ while i <= n do
+ local d = x[i - order - 1]
+ local val = 0
+ for j = 1, order do
+ val += (x[i - j] - d) * coefs[j]
+ end
+ val = floor((val + half) / qd)
+ local r = signExtend(x[i] - val - d, bps)
+ e[i] = r
+ if r ~= 0 then
+ local es = if r > 0 then 1 else -1
+ for j = order, 1, -1 do
+ if r * es <= 0 then
+ break
+ end
+ local v = d - x[i - j]
+ local sgn = if v > 0 then es elseif v < 0 then -es else 0
+ coefs[j] -= sgn
+ r -= floor(v * sgn / qd) * (order - j + 1)
+ end
+ end
+ i += 1
+ end
+end
+
+-- LPC coefficients of x[1..n] for the given order (Levinson-Durbin on a Welch-windowed autocorrelation), quantised
+local function lpc(x: { number }, n: number, order: number, work: { number }): { number }
+ local ac = table.create(order + 1, 0)
+ for i = 1, n do
+ local t = (2 * (i - 1) - (n - 1)) / (n + 1)
+ work[i] = x[i] * (1 - t * t)
+ end
+ for lag = 0, order do
+ local s = 0
+ for i = lag + 1, n do
+ s += work[i] * work[i - lag]
+ end
+ ac[lag + 1] = s
+ end
+ local coefs = table.create(order, 0)
+ if ac[1] <= 0 then
+ return coefs
+ end
+ ac[1] *= 1.0001 -- a little white noise: keeps the recursion stable
+ local a = table.create(order + 1, 0)
+ local tmp = table.create(order + 1, 0)
+ local errv = ac[1]
+ for i = 1, order do
+ local acc = ac[i + 1]
+ for j = 1, i - 1 do
+ acc -= a[j] * ac[i - j + 1]
+ end
+ local kc = acc / errv
+ for j = 1, i - 1 do
+ tmp[j] = a[j] - kc * a[i - j]
+ end
+ for j = 1, i - 1 do
+ a[j] = tmp[j]
+ end
+ a[i] = kc
+ errv *= (1 - kc * kc)
+ if errv <= 0 then
+ break
+ end
+ end
+ local scale = POW[DENSHIFT + 1]
+ for j = 1, order do
+ coefs[j] = math.clamp(floor(a[j] * scale + 0.5), -32768, 32767)
+ end
+ return coefs
+end
+
+-- choose order / coefficients for one channel: returns order, coefs (as transmitted), bits
+local function analyse(st: State, x: { number }, n: number, bps: number): (number, { number }, number)
+ local mult = floor(st.pb * PB_FACTOR / 4)
+ local bestOrder, bestCoefs, bestBits = 0, {}, math.huge
+ for _, order in { 4, 8 } do
+ if order >= n then
+ continue
+ end
+ local coefs = lpc(x, n, order, st.work)
+ local trial = table.clone(coefs)
+ residuals(x, st.err, n, bps, trial, order, DENSHIFT)
+ local bits = rice(st, st.err, n, bps, mult, false) + order * 16
+ if bits < bestBits then
+ bestOrder, bestCoefs, bestBits = order, coefs, bits
+ end
+ end
+ if bestBits == math.huge then
+ -- tiny frames: first-order prediction (order 31 is only a decoder mode; order 0 = no prediction)
+ for i = 1, n do
+ st.err[i] = x[i]
+ end
+ return 0, {}, rice(st, st.err, n, bps, mult, false)
+ end
+ return bestOrder, bestCoefs, bestBits
+end
+
+-- ------------------------------------------------------------------------------------------------ frame
+-- frame(st, samples, first, frames, map) -> buffer: samples interleaved (integers, WAV channel order) from index
+-- `first`; map[k] = the input channel (1-based) of ALAC channel k; elements: list of 1 / 2 channel counts
+function Encode.frame(st: State, samples: { number }, first: number, frames: number, map: { number }, elements: { number }): buffer
+ local channels, depth = st.channels, st.bitDepth
+ local n = frames
+ local partial = n ~= st.frameLength
+ local rawBits = n * channels * depth
+ local need = rawBits + 64 * #elements + 64
+ if st.cap < need + 8 * 32 * 2 * #elements * 16 then
+ local bytes = (need + 8 * 32 * 2 * #elements * 16) // 8 + 16
+ st.out = buffer.create(bytes)
+ st.cap = bytes * 8
+ end
+ buffer.fill(st.out, 0, 0)
+ st.pos = 0
+ local u, v = st.u, st.v
+ local mult = floor(st.pb * PB_FACTOR / 4)
+ local compressed = true
+ local ch = 1
+ for _, nch in elements do
+ local a, b = map[ch], map[ch + 1]
+ local bps = depth + nch - 1
+ local mixRes = 0
+ if nch == 2 then
+ -- the mix with the smallest first-difference energy
+ local best = math.huge
+ for res = 0, 4 do
+ local cost = 0
+ local pu, pv = 0, 0
+ for i = 0, n - 1 do
+ local l = samples[first + i * channels + a - 1]
+ local r = samples[first + i * channels + b - 1]
+ local uu, vv
+ if res == 0 then
+ uu, vv = l, r
+ else
+ uu, vv = floor((res * l + (4 - res) * r) / 4), l - r
+ end
+ cost += abs(uu - pu) + abs(vv - pv)
+ pu, pv = uu, vv
+ end
+ if cost < best then
+ best, mixRes = cost, res
+ end
+ end
+ for i = 1, n do
+ local l = samples[first + (i - 1) * channels + a - 1]
+ local r = samples[first + (i - 1) * channels + b - 1]
+ if mixRes == 0 then
+ u[i], v[i] = l, r
+ else
+ u[i], v[i] = floor((mixRes * l + (4 - mixRes) * r) / 4), l - r
+ end
+ end
+ else
+ for i = 1, n do
+ u[i] = samples[first + (i - 1) * channels + a - 1]
+ end
+ end
+ -- header
+ put(st, if nch == 2 then 1 else 0, 3)
+ put(st, 0, 4)
+ put(st, 0, 12)
+ put(st, if partial then 1 else 0, 1)
+ put(st, 0, 2)
+ put(st, 0, 1)
+ if partial then
+ putBig(st, n, 32)
+ end
+ put(st, if mixRes == 0 then 0 else 2, 8)
+ put(st, mixRes, 8)
+ local orders, coefsList = {}, {}
+ for c = 1, nch do
+ local x = if c == 1 then u else v
+ local order, coefs = analyse(st, x, n, bps)
+ orders[c], coefsList[c] = order, coefs
+ put(st, 0 * 16 + DENSHIFT, 8) -- mode 0, denShift
+ put(st, PB_FACTOR * 32 + order, 8)
+ for j = 1, order do
+ put(st, coefs[j] % 65536, 16)
+ end
+ end
+ for c = 1, nch do
+ local x = if c == 1 then u else v
+ local order = orders[c]
+ if order == 0 then
+ for i = 1, n do
+ st.err[i] = x[i]
+ end
+ else
+ residuals(x, st.err, n, bps, table.clone(coefsList[c]), order, DENSHIFT)
+ end
+ rice(st, st.err, n, bps, mult, true)
+ end
+ ch += nch
+ if st.pos > rawBits + 64 * #elements then
+ compressed = false
+ break
+ end
+ end
+ if not compressed then
+ -- uncompressed frame
+ buffer.fill(st.out, 0, 0)
+ st.pos = 0
+ ch = 1
+ for _, nch in elements do
+ put(st, if nch == 2 then 1 else 0, 3)
+ put(st, 0, 4)
+ put(st, 0, 12)
+ put(st, if partial then 1 else 0, 1)
+ put(st, 0, 2)
+ put(st, 1, 1)
+ if partial then
+ putBig(st, n, 32)
+ end
+ for i = 0, n - 1 do
+ for c = 0, nch - 1 do
+ putBig(st, samples[first + i * channels + map[ch + c] - 1] % POW[depth + 1], depth)
+ end
+ end
+ ch += nch
+ end
+ end
+ put(st, 7, 3) -- END
+ local bytes = (st.pos + 7) // 8
+ local pkt = buffer.create(bytes)
+ buffer.copy(pkt, 0, st.out, 0, bytes)
+ return pkt
+end
+
+function Encode.state(cfg: any): State
+ local n = cfg.frameLength
+ return {
+ frameLength = n,
+ bitDepth = cfg.bitDepth,
+ pb = cfg.pb,
+ mb = cfg.mb,
+ kb = cfg.kb,
+ channels = cfg.channels,
+ out = buffer.create(16),
+ pos = 0,
+ cap = 0,
+ u = table.create(n, 0),
+ v = table.create(n, 0),
+ err = table.create(n, 0),
+ work = table.create(n, 0),
+ }
+end
+
+return Encode
diff --git a/src/Formats/codecs/Alac/init.luau b/src/Formats/codecs/Alac/init.luau
new file mode 100644
index 0000000..7af082b
--- /dev/null
+++ b/src/Formats/codecs/Alac/init.luau
@@ -0,0 +1,251 @@
+--!strict
+-- codecs/Alac: Apple Lossless (ALAC) decoder and encoder, the codec inside m4a / mov / caf. A codec (layer 1).
+-- Written from the ALAC format as Apple published it (ALACSpecificConfig, the element syntax, adaptive Golomb-Rice
+-- residuals, the adaptive FIR predictor); no third-party code. 1 - 8 channels, 16 / 20 / 24 / 32-bit decode, 16 / 20 /
+-- 24-bit encode. Channels come out (and go in) in WAV order (ALAC stores C L R ... for 3+ channels).
+--
+-- local Alac = require("@formats/codecs/Alac")
+-- local cfg, err = Alac.config(cookie) -- the 24-byte ALACSpecificConfig (frma / alac atoms skipped)
+-- local dec = Alac.decoder(cfg)
+-- local frames, err = dec:decode(buf, offset, length) -- one packet -> dec.pcm (interleaved integers, WAV order)
+-- local enc = Alac.encoder({ sampleRate = 44100, channels = 2, bitDepth = 16 })
+-- local packet = enc:encode(samples, first, frames) -- interleaved integers -> one packet (frames <= 4096)
+-- local cookie = Alac.cookie(enc.config) -- after encoding: maxFrameBytes / avgBitRate filled
+--
+-- Never throws: bad data returns nil, Err (CORRUPT / TRUNCATED / UNSUPPORTED), bad arguments Err.ARG.
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Decode = require("@formats/codecs/Alac/Decode")
+local Encode = require("@formats/codecs/Alac/Encode")
+
+local Alac = {}
+
+export type Config = {
+ frameLength: number, -- samples per packet (4096)
+ compatibleVersion: number,
+ bitDepth: number,
+ pb: number, -- 40
+ mb: number, -- 10
+ kb: number, -- 14
+ channels: number,
+ maxRun: number, -- 255
+ maxFrameBytes: number,
+ avgBitRate: number,
+ sampleRate: number,
+}
+
+-- ALAC channel k (1-based) -> WAV channel (1-based), per channel count
+local TO_WAV: { { number } } = {
+ { 1 },
+ { 1, 2 },
+ { 3, 1, 2 },
+ { 3, 1, 2, 4 },
+ { 3, 1, 2, 4, 5 },
+ { 3, 1, 2, 5, 6, 4 },
+ { 3, 1, 2, 5, 6, 7, 4 },
+ { 3, 7, 8, 1, 2, 5, 6, 4 },
+}
+-- the element layout (channels per element) the encoder writes
+local ELEMENTS: { { number } } = {
+ { 1 },
+ { 2 },
+ { 1, 2 },
+ { 1, 2, 1 },
+ { 1, 2, 2 },
+ { 1, 2, 2, 1 },
+ { 1, 2, 2, 1, 1 },
+ { 1, 2, 2, 2, 1 },
+}
+Alac.TO_WAV = TO_WAV
+
+-- config(buf, offset?, length?) -> Config | nil, Err
+function Alac.config(buf: buffer, offset: number?, length: number?): (Config?, Err.Err?)
+ local r = Bytes.reader(buf, offset, length)
+ -- a QuickTime 'wave' payload may hold frma + alac atoms ahead of the cookie
+ for _ = 1, 2 do
+ local typ = r:peek(4, 4)
+ if typ == "frma" then
+ r:skip(12)
+ elseif typ == "alac" then
+ r:skip(12)
+ end
+ end
+ if r:remaining() < 24 then
+ return nil, Err.new(Err.TRUNCATED, "ALAC configuration is shorter than 24 bytes")
+ end
+ local c: Config = {
+ frameLength = r:u32be(),
+ compatibleVersion = r:u8(),
+ bitDepth = r:u8(),
+ pb = r:u8(),
+ mb = r:u8(),
+ kb = r:u8(),
+ channels = r:u8(),
+ maxRun = r:u16be(),
+ maxFrameBytes = r:u32be(),
+ avgBitRate = r:u32be(),
+ sampleRate = r:u32be(),
+ }
+ if c.compatibleVersion ~= 0 then
+ return nil, Err.new(Err.UNSUPPORTED, "ALAC version " .. c.compatibleVersion)
+ end
+ if c.frameLength < 1 or c.frameLength > 65536 then
+ return nil, Err.new(Err.CORRUPT, "bad ALAC frame length " .. c.frameLength)
+ end
+ if c.bitDepth ~= 16 and c.bitDepth ~= 20 and c.bitDepth ~= 24 and c.bitDepth ~= 32 then
+ return nil, Err.new(Err.UNSUPPORTED, "ALAC bit depth " .. c.bitDepth)
+ end
+ if c.channels < 1 or c.channels > 8 then
+ return nil, Err.new(Err.UNSUPPORTED, "ALAC with " .. c.channels .. " channels")
+ end
+ if c.kb < 1 or c.kb > 24 then
+ return nil, Err.new(Err.CORRUPT, "bad ALAC rice limit " .. c.kb)
+ end
+ return c, nil
+end
+
+-- cookie(cfg) -> the 24-byte ALACSpecificConfig
+function Alac.cookie(c: Config): buffer
+ local w = Bytes.writer(24)
+ w:u32be(c.frameLength)
+ w:u8(0)
+ w:u8(c.bitDepth)
+ w:u8(c.pb)
+ w:u8(c.mb)
+ w:u8(c.kb)
+ w:u8(c.channels)
+ w:u16be(c.maxRun)
+ w:u32be(c.maxFrameBytes)
+ w:u32be(c.avgBitRate)
+ w:u32be(c.sampleRate)
+ return w:finish()
+end
+
+-- ------------------------------------------------------------------------------------------------ decoder
+export type Decoder = {
+ config: Config,
+ pcm: { number }, -- the last packet's samples, interleaved, WAV order (integers of config.bitDepth bits)
+ decode: (self: Decoder, buf: buffer, offset: number?, length: number?) -> (number?, Err.Err?),
+ state: Decode.State,
+}
+
+local function decode(self: Decoder, buf: buffer, offset: number?, length: number?): (number?, Err.Err?)
+ local o = offset or 0
+ local n = length or (buffer.len(buf) - o)
+ if o < 0 or n < 0 or o + n > buffer.len(buf) then
+ return nil, Err.new(Err.ARG, "packet range out of the buffer")
+ end
+ local frames, msg = Decode.frame(self.state, buf, o, n)
+ if not frames then
+ return nil, Err.new(Err.CORRUPT, msg or "bad packet", o)
+ end
+ local ch = self.config.channels
+ local src, dst = self.state.out, self.pcm
+ if ch <= 2 then
+ for i = 1, frames * ch do
+ dst[i] = src[i]
+ end
+ else
+ local map = TO_WAV[ch]
+ for f = 0, frames - 1 do
+ local base = f * ch
+ for k = 1, ch do
+ dst[base + map[k]] = src[base + k]
+ end
+ end
+ end
+ return frames, nil
+end
+
+-- decoder(cfg) -> Decoder
+function Alac.decoder(cfg: Config): Decoder
+ return {
+ config = cfg,
+ pcm = table.create(cfg.frameLength * cfg.channels, 0),
+ decode = decode,
+ state = Decode.state(cfg),
+ }
+end
+
+-- ------------------------------------------------------------------------------------------------ encoder
+export type Encoder = {
+ config: Config,
+ encode: (self: Encoder, samples: { number }, first: number, frames: number) -> (buffer?, Err.Err?),
+ state: Encode.State,
+ bytes: number,
+ frames: number,
+}
+
+local function encode(self: Encoder, samples: { number }, first: number, frames: number): (buffer?, Err.Err?)
+ local cfg = self.config
+ if type(samples) ~= "table" or frames < 1 or frames > cfg.frameLength or frames % 1 ~= 0 then
+ return nil, Err.new(Err.ARG, "encode: 1 .. " .. cfg.frameLength .. " frames of interleaved integer samples")
+ end
+ if first < 1 or first + frames * cfg.channels - 1 > #samples then
+ return nil, Err.new(Err.ARG, "encode: the samples end early")
+ end
+ local ch = cfg.channels
+ local pkt = Encode.frame(self.state, samples, first, frames, TO_WAV[ch], ELEMENTS[ch])
+ local n = buffer.len(pkt)
+ self.bytes += n
+ self.frames += frames
+ if n > cfg.maxFrameBytes then
+ cfg.maxFrameBytes = n
+ end
+ if self.frames > 0 then
+ cfg.avgBitRate = math.floor(self.bytes * 8 * cfg.sampleRate / self.frames)
+ end
+ return pkt, nil
+end
+
+export type EncoderOptions = {
+ sampleRate: number,
+ channels: number, -- 1 .. 8
+ bitDepth: number?, -- 16 (default), 20 or 24
+ frameLength: number?, -- default 4096
+}
+
+-- encoder(opts) -> Encoder | nil, Err
+function Alac.encoder(opts: EncoderOptions): (Encoder?, Err.Err?)
+ if type(opts) ~= "table" then
+ return nil, Err.new(Err.ARG, "encoder: expected options")
+ end
+ local depth = opts.bitDepth or 16
+ local ch = opts.channels
+ if depth ~= 16 and depth ~= 20 and depth ~= 24 then
+ return nil, Err.new(Err.ARG, "encoder: bitDepth 16, 20 or 24")
+ end
+ if type(ch) ~= "number" or ch < 1 or ch > 8 or ch % 1 ~= 0 then
+ return nil, Err.new(Err.ARG, "encoder: 1 .. 8 channels")
+ end
+ local sr = opts.sampleRate
+ if type(sr) ~= "number" or sr < 1 or sr % 1 ~= 0 then
+ return nil, Err.new(Err.ARG, "encoder: bad sampleRate")
+ end
+ local fl = opts.frameLength or 4096
+ if fl < 16 or fl > 16384 or fl % 1 ~= 0 then
+ return nil, Err.new(Err.ARG, "encoder: frameLength 16 .. 16384")
+ end
+ local cfg: Config = {
+ frameLength = fl,
+ compatibleVersion = 0,
+ bitDepth = depth,
+ pb = 40,
+ mb = 10,
+ kb = 14,
+ channels = ch,
+ maxRun = 255,
+ maxFrameBytes = 0,
+ avgBitRate = 0,
+ sampleRate = sr,
+ }
+ return {
+ config = cfg,
+ encode = encode,
+ state = Encode.state(cfg),
+ bytes = 0,
+ frames = 0,
+ }, nil
+end
+
+return Alac
diff --git a/src/Formats/codecs/Base64/init.luau b/src/Formats/codecs/Base64/init.luau
new file mode 100644
index 0000000..3d3030f
--- /dev/null
+++ b/src/Formats/codecs/Base64/init.luau
@@ -0,0 +1,140 @@
+--!strict
+--!native
+-- codecs/Base64: RFC 4648 base64 (standard alphabet, and base64url with opts.url) encode / decode, for data: URIs
+-- (glTF, SVG, CSS), PEM-like text, YAML !!binary, ... New code. decode skips whitespace, accepts missing padding and
+-- both alphabets; any other character is an error. Never throws.
+--
+-- local Base64 = require("@formats/codecs/Base64")
+-- local s = Base64.encode(buf) -- string ("" for an empty buffer)
+-- local b, err = Base64.decode(s) -- buffer | nil, "message"
+-- local b2 = Base64.decodeDataUri("data:application/octet-stream;base64,AAEC") -- buffer, mime | nil, message
+local Base64 = {}
+
+local ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
+local ALPHA_URL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
+local ENC = buffer.fromstring(ALPHA)
+local ENC_URL = buffer.fromstring(ALPHA_URL)
+-- the decode table: 0..63, 64 = skip (whitespace), 65 = padding, 255 = bad
+local DEC = buffer.create(256)
+buffer.fill(DEC, 0, 255)
+for i = 1, 64 do
+ buffer.writeu8(DEC, string.byte(ALPHA, i), i - 1)
+end
+buffer.writeu8(DEC, string.byte("-"), 62)
+buffer.writeu8(DEC, string.byte("_"), 63)
+for _, c in { 9, 10, 13, 32 } do
+ buffer.writeu8(DEC, c, 64)
+end
+buffer.writeu8(DEC, string.byte("="), 65)
+
+local readu8, writeu8 = buffer.readu8, buffer.writeu8
+
+-- encode(buf, opts?, offset?, length?) -> string. opts.url: the URL-safe alphabet; opts.pad = false: no "=" padding.
+function Base64.encode(buf: buffer, opts: { url: boolean?, pad: boolean? }?, offset: number?, length: number?): string
+ local o = math.clamp(offset or 0, 0, buffer.len(buf))
+ local n = math.clamp(length or (buffer.len(buf) - o), 0, buffer.len(buf) - o)
+ local enc = if opts and opts.url then ENC_URL else ENC
+ local pad = not (opts and opts.pad == false)
+ local full = n // 3
+ local rest = n - full * 3
+ local outLen = full * 4 + (if rest == 0 then 0 elseif pad then 4 else rest + 1)
+ local out = buffer.create(outLen)
+ local p = 0
+ for i = 0, full - 1 do
+ local q = o + i * 3
+ local v = readu8(buf, q) * 65536 + readu8(buf, q + 1) * 256 + readu8(buf, q + 2)
+ writeu8(out, p, readu8(enc, v // 262144))
+ writeu8(out, p + 1, readu8(enc, (v // 4096) % 64))
+ writeu8(out, p + 2, readu8(enc, (v // 64) % 64))
+ writeu8(out, p + 3, readu8(enc, v % 64))
+ p += 4
+ end
+ if rest > 0 then
+ local q = o + full * 3
+ local v = readu8(buf, q) * 65536 + (if rest == 2 then readu8(buf, q + 1) * 256 else 0)
+ writeu8(out, p, readu8(enc, v // 262144))
+ writeu8(out, p + 1, readu8(enc, (v // 4096) % 64))
+ if rest == 2 then
+ writeu8(out, p + 2, readu8(enc, (v // 64) % 64))
+ elseif pad then
+ writeu8(out, p + 2, 61)
+ end
+ if pad then
+ writeu8(out, p + 3, 61)
+ end
+ end
+ return buffer.tostring(out)
+end
+
+-- decode(s) -> buffer | nil, message
+function Base64.decode(s: string | buffer): (buffer?, string?)
+ local src = if type(s) == "string" then buffer.fromstring(s) else s
+ local n = buffer.len(src)
+ local out = buffer.create((n // 4 + 1) * 3)
+ local acc, bits, p = 0, 0, 0
+ local padded = false
+ for i = 0, n - 1 do
+ local d = readu8(DEC, readu8(src, i))
+ if d < 64 then
+ if padded then
+ return nil, "data after padding"
+ end
+ acc = acc * 64 + d
+ bits += 6
+ if bits >= 8 then
+ bits -= 8
+ local byte = acc // (2 ^ bits)
+ writeu8(out, p, byte % 256)
+ p += 1
+ acc = acc % (2 ^ bits)
+ end
+ elseif d == 65 then
+ padded = true
+ elseif d ~= 64 then
+ return nil, string.format("bad base64 character 0x%02x at %d", readu8(src, i), i)
+ end
+ end
+ if bits >= 6 then
+ return nil, "truncated base64 (a single character in the last group)"
+ end
+ local res = buffer.create(p)
+ buffer.copy(res, 0, out, 0, p)
+ return res, nil
+end
+
+-- decodeDataUri(uri) -> buffer, mime | nil, message: "data:[][;params][;base64]," (percent-encoded data
+-- when not base64)
+function Base64.decodeDataUri(uri: string): (buffer?, string?)
+ if string.sub(uri, 1, 5) ~= "data:" then
+ return nil, "not a data: URI"
+ end
+ local comma = string.find(uri, ",", 6, true)
+ if not comma then
+ return nil, "data: URI without a comma"
+ end
+ local head = string.sub(uri, 6, comma - 1)
+ local isB64 = string.sub(head, -7) == ";base64"
+ local mime = string.match(head, "^([^;]*)") or ""
+ if mime == "" then
+ mime = "text/plain"
+ end
+ local body = string.sub(uri, comma + 1)
+ if isB64 then
+ local b, err = Base64.decode(body)
+ if not b then
+ return nil, err
+ end
+ return b, mime
+ end
+ local decoded = string.gsub(body, "%%(%x%x)", function(h: string): string
+ return string.char(tonumber(h, 16) :: number)
+ end)
+ return buffer.fromstring(decoded), mime
+end
+
+-- dataUri(buf, mime) -> "data:;base64,..."
+function Base64.dataUri(buf: buffer, mime: string?): string
+ return "data:" .. (mime or "application/octet-stream") .. ";base64," .. Base64.encode(buf)
+end
+
+return Base64
diff --git a/src/Formats/codecs/Blend.luau b/src/Formats/codecs/Blend.luau
new file mode 100644
index 0000000..a3db2a9
--- /dev/null
+++ b/src/Formats/codecs/Blend.luau
@@ -0,0 +1,371 @@
+--!strict
+--!native
+-- codecs/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.
+local Blend = {}
+
+local readu8, writeu8, readu32, writeu32, blen = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32, buffer.len
+local min, max, floor, sqrt, abs = math.min, math.max, math.floor, math.sqrt, math.abs
+
+local IDS: { [string]: number } = {
+ normal = 0,
+ dissolve = 1,
+ darken = 2,
+ multiply = 3,
+ colorBurn = 4,
+ linearBurn = 5,
+ darkerColor = 6,
+ lighten = 7,
+ screen = 8,
+ colorDodge = 9,
+ linearDodge = 10,
+ add = 10,
+ lighterColor = 11,
+ overlay = 12,
+ softLight = 13,
+ hardLight = 14,
+ vividLight = 15,
+ linearLight = 16,
+ pinLight = 17,
+ hardMix = 18,
+ difference = 19,
+ exclusion = 20,
+ subtract = 21,
+ divide = 22,
+ hue = 23,
+ saturation = 24,
+ color = 25,
+ luminosity = 26,
+}
+local MODES: { [string]: boolean } = {}
+for k in IDS do
+ MODES[k] = true
+end
+Blend.MODES = table.freeze(MODES)
+
+local function burn(cb: number, cs: number): number
+ if cb >= 1 then
+ return 1
+ elseif cs <= 0 then
+ return 0
+ end
+ return 1 - min(1, (1 - cb) / cs)
+end
+local function dodge(cb: number, cs: number): number
+ if cb <= 0 then
+ return 0
+ elseif cs >= 1 then
+ return 1
+ end
+ return min(1, cb / (1 - cs))
+end
+
+-- B(cb, cs) of a separable mode
+local function sep(m: number, cb: number, cs: number): number
+ if m == 3 then
+ return cb * cs
+ elseif m == 8 then
+ return cb + cs - cb * cs
+ elseif m == 2 then
+ return min(cb, cs)
+ elseif m == 7 then
+ return max(cb, cs)
+ elseif m == 12 then -- overlay = hardLight(cs, cb)
+ if cb <= 0.5 then
+ return 2 * cb * cs
+ end
+ local c = 2 * cb - 1
+ return cs + c - cs * c
+ elseif m == 14 then
+ if cs <= 0.5 then
+ return 2 * cb * cs
+ end
+ local c = 2 * cs - 1
+ return cb + c - cb * c
+ elseif m == 13 then
+ if cs <= 0.5 then
+ return cb - (1 - 2 * cs) * cb * (1 - cb)
+ end
+ local d = if cb <= 0.25 then ((16 * cb - 12) * cb + 4) * cb else sqrt(cb)
+ return cb + (2 * cs - 1) * (d - cb)
+ elseif m == 9 then
+ return dodge(cb, cs)
+ elseif m == 4 then
+ return burn(cb, cs)
+ elseif m == 5 then
+ return max(0, cb + cs - 1)
+ elseif m == 10 then
+ return min(1, cb + cs)
+ elseif m == 15 then
+ if cs <= 0.5 then
+ return burn(cb, 2 * cs)
+ end
+ return dodge(cb, 2 * cs - 1)
+ elseif m == 16 then
+ return max(0, min(1, cb + 2 * cs - 1))
+ elseif m == 17 then
+ if cs <= 0.5 then
+ return min(cb, 2 * cs)
+ end
+ return max(cb, 2 * cs - 1)
+ elseif m == 18 then
+ return if cb + cs >= 1 then 1 else 0
+ elseif m == 19 then
+ return abs(cb - cs)
+ elseif m == 20 then
+ return cb + cs - 2 * cb * cs
+ elseif m == 21 then
+ return max(0, cb - cs)
+ elseif m == 22 then
+ if cs <= 0 then
+ return if cb <= 0 then 0 else 1
+ end
+ return min(1, cb / cs)
+ end
+ return cs
+end
+
+-- non-separable helpers (W3C): lum, clip, setLum, sat, setSat
+local function lum(r: number, g: number, b: number): number
+ return 0.3 * r + 0.59 * g + 0.11 * b
+end
+local function clipColor(r: number, g: number, b: number): (number, number, number)
+ local l = lum(r, g, b)
+ local n = min(r, g, b)
+ local x = max(r, g, b)
+ if n < 0 and l - n > 1e-12 then
+ r, g, b = l + (r - l) * l / (l - n), l + (g - l) * l / (l - n), l + (b - l) * l / (l - n)
+ end
+ if x > 1 and x - l > 1e-12 then
+ r, g, b = l + (r - l) * (1 - l) / (x - l), l + (g - l) * (1 - l) / (x - l), l + (b - l) * (1 - l) / (x - l)
+ end
+ return r, g, b
+end
+local function setLum(r: number, g: number, b: number, l: number): (number, number, number)
+ local d = l - lum(r, g, b)
+ return clipColor(r + d, g + d, b + d)
+end
+local function setSat(r: number, g: number, b: number, s: number): (number, number, number)
+ local mx = max(r, g, b)
+ local mn = min(r, g, b)
+ if mx - mn <= 1e-12 then
+ return 0, 0, 0
+ end
+ local k = s / (mx - mn)
+ 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
+ return
+ end
+ if blen(dst) < dw * dh * 4 or blen(src) < sw * sh * 4 then
+ return
+ end
+ local op = min(1, opacity)
+ local m = IDS[mode or "normal"] or 0
+ local clip = opts ~= nil and opts.clip == true
+ local mask = if opts ~= nil then opts.mask else nil
+ local mbuf: buffer? = nil
+ local mx0, my0, mw, mh, mdef = 0, 0, 0, 0, 1
+ if type(mask) == "table" and type(mask.pixels) == "buffer" and type(mask.width) == "number" and type(mask.height) == "number" then
+ mw, mh = floor(mask.width), floor(mask.height)
+ if mw > 0 and mh > 0 and blen(mask.pixels) >= mw * mh then
+ mbuf = mask.pixels
+ end
+ mx0, my0 = floor(tonumber(mask.x) or 0), floor(tonumber(mask.y) or 0)
+ mdef = (tonumber(mask.default) or 255) / 255
+ elseif type(mask) == "table" then
+ mdef = (tonumber(mask.default) or 255) / 255
+ end
+ local x0, y0 = max(0, x), max(0, y)
+ local x1, y1 = min(dw, x + sw), min(dh, y + sh)
+ for py = y0, y1 - 1 do
+ local so = ((py - y) * sw + (x0 - x)) * 4
+ local do_ = (py * dw + x0) * 4
+ for px = x0, x1 - 1 do
+ local sa8 = readu8(src, so + 3)
+ if sa8 ~= 0 then
+ local sa = sa8 / 255 * op
+ if mbuf ~= nil or mdef ~= 1 then
+ local mv = mdef
+ local mxx, myy = px - mx0, py - my0
+ if mbuf ~= nil and mxx >= 0 and myy >= 0 and mxx < mw and myy < mh then
+ mv = readu8(mbuf, myy * mw + mxx) / 255
+ end
+ sa *= mv
+ end
+ if m == 1 then -- dissolve: a hash threshold per pixel, full alpha where it shows
+ local h = (px * 73856093 + py * 19349663) % 65536 / 65536
+ sa = if h < sa then 1 else 0
+ end
+ local ba8 = readu8(dst, do_ + 3)
+ 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
+ local ba = ba8 / 255
+ local br, bg, bb = readu8(dst, do_) / 255, readu8(dst, do_ + 1) / 255, readu8(dst, do_ + 2) / 255
+ local mr, mg, mb = sr, sg, sb
+ if m >= 2 and m ~= 6 and m ~= 11 and m < 23 then
+ mr, mg, mb = sep(m, br, sr), sep(m, bg, sg), sep(m, bb, sb)
+ elseif m == 6 then
+ if lum(sr, sg, sb) >= lum(br, bg, bb) then
+ mr, mg, mb = br, bg, bb
+ end
+ elseif m == 11 then
+ if lum(sr, sg, sb) < lum(br, bg, bb) then
+ mr, mg, mb = br, bg, bb
+ end
+ elseif m == 23 then
+ local s = max(br, bg, bb) - min(br, bg, bb)
+ local r1, g1, b1 = setSat(sr, sg, sb, s)
+ mr, mg, mb = setLum(r1, g1, b1, lum(br, bg, bb))
+ elseif m == 24 then
+ local s = max(sr, sg, sb) - min(sr, sg, sb)
+ local r1, g1, b1 = setSat(br, bg, bb, s)
+ mr, mg, mb = setLum(r1, g1, b1, lum(br, bg, bb))
+ elseif m == 25 then
+ mr, mg, mb = setLum(sr, sg, sb, lum(br, bg, bb))
+ elseif m == 26 then
+ mr, mg, mb = setLum(br, bg, bb, lum(sr, sg, sb))
+ end
+ local orr, og, ob, oa
+ if clip then
+ -- source-atop: the backdrop's alpha; the mixed colour where the backdrop is opaque
+ orr = sa * mr + (1 - sa) * br
+ og = sa * mg + (1 - sa) * bg
+ ob = sa * mb + (1 - sa) * bb
+ oa = ba
+ else
+ oa = sa + ba * (1 - sa)
+ local ws, wm, wb = sa * (1 - ba), sa * ba, (1 - sa) * ba
+ orr = (ws * sr + wm * mr + wb * br) / oa
+ og = (ws * sg + wm * mg + wb * bg) / oa
+ ob = (ws * sb + wm * mb + wb * bb) / oa
+ end
+ writeu8(dst, do_, floor(max(0, min(1, orr)) * 255 + 0.5))
+ writeu8(dst, do_ + 1, floor(max(0, min(1, og)) * 255 + 0.5))
+ writeu8(dst, do_ + 2, floor(max(0, min(1, ob)) * 255 + 0.5))
+ writeu8(dst, do_ + 3, floor(max(0, min(1, oa)) * 255 + 0.5))
+ end
+ end
+ end
+ so += 4
+ do_ += 4
+ end
+ end
+end
+
+-- lerp(dst, from, t, n): dst = from + (dst - from) * t per byte over n pixels (pass-through group opacity)
+local function lerp(dst: buffer, from: buffer, t: number, n: number)
+ if blen(dst) < n * 4 or blen(from) < n * 4 then
+ return
+ end
+ for i = 0, n * 4 - 1 do
+ local a = readu8(from, i)
+ writeu8(dst, i, floor(a + (readu8(dst, i) - a) * t + 0.5))
+ end
+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
+
+local function maskOf(l: any): any
+ local m = l.mask
+ if type(m) ~= "table" or m.disabled or type(m.image) ~= "table" or type(m.image.pixels) ~= "buffer" then
+ return nil
+ end
+ local img = m.image
+ local px = img.pixels
+ if img.format == "rgba8" then -- use the red channel
+ local n = img.width * img.height
+ local g = buffer.create(n)
+ for i = 0, n - 1 do
+ buffer.writeu8(g, i, buffer.readu8(px, i * 4))
+ end
+ px = g
+ end
+ return { pixels = px, width = img.width, height = img.height, x = m.x or 0, y = m.y or 0, default = m.default or 255 }
+end
+
+local function compose(layers: { any }, canvas: buffer, w: number, h: number, hidden: boolean)
+ local i = 1
+ while i <= #layers do
+ local l = layers[i]
+ i += 1
+ if type(l) ~= "table" or (l.visible == false and not hidden) then
+ -- clipped layers above a hidden base are hidden too
+ while i <= #layers and type(layers[i]) == "table" and layers[i].clip do
+ i += 1
+ end
+ continue
+ 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
+ local before = buffer.create(w * h * 4)
+ buffer.copy(before, 0, canvas, 0, w * h * 4)
+ compose(l.children, canvas, w, h, hidden)
+ if opacity < 1 then
+ lerp(canvas, before, opacity, w * h)
+ end
+ continue
+ end
+ src = buffer.create(w * h * 4)
+ compose(l.children, src :: buffer, w, h, hidden)
+ elseif isImage(l.image) then
+ if l.image.width > 0 and l.image.height > 0 then
+ local b = buffer.create(w * h * 4)
+ composite(b, w, h, l.image.pixels, l.image.width, l.image.height, tonumber(l.x) or 0, tonumber(l.y) or 0, 1, "normal")
+ src = b
+ end
+ end
+ -- clipping layers above this one: composited onto it with their alpha limited to it
+ while i <= #layers and type(layers[i]) == "table" and layers[i].clip do
+ local c = layers[i]
+ i += 1
+ if src and (c.visible ~= false or hidden) and isImage(c.image) then
+ composite(src :: buffer, w, h, c.image.pixels, c.image.width, c.image.height, tonumber(c.x) or 0, tonumber(c.y) or 0, (tonumber(c.opacity) or 1) * (tonumber(c.fillOpacity) or 1), c.blend, { clip = true, mask = maskOf(c) })
+ end
+ end
+ if src then
+ composite(canvas, w, h, src :: buffer, w, h, 0, 0, opacity, mode, { mask = maskOf(l) })
+ end
+ 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 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)
+ end
+end
+
+return Blend
diff --git a/src/Formats/codecs/Brotli/Decode.luau b/src/Formats/codecs/Brotli/Decode.luau
new file mode 100644
index 0000000..e17e7d8
--- /dev/null
+++ b/src/Formats/codecs/Brotli/Decode.luau
@@ -0,0 +1,996 @@
+--!strict
+--!native
+--!optimize 2
+-- codecs/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.
+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
+
+local Decode = {}
+
+export type Static = {
+ dictionary: buffer, -- 122784 bytes
+ context: buffer, -- 2048 bytes: 4 modes x (256 for p1, 256 for p2)
+ prefixSuffix: buffer, -- length-prefixed strings
+ prefixSuffixMap: { number },
+ 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 }
+local BL_OFF = {
+ 1, 5, 9, 13, 17, 25, 33, 41, 49, 65, 81, 97, 113, 145, 177, 209, 241, 305, 369, 497, 753, 1265, 2289, 4337, 8433, 16625,
+}
+local BL_BITS = { 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 7, 8, 9, 10, 11, 12, 13, 24 }
+local INS_BASE = { 0, 1, 2, 3, 4, 5, 6, 8, 10, 14, 18, 26, 34, 50, 66, 98, 130, 194, 322, 578, 1090, 2114, 6210, 22594 }
+local INS_EXTRA = { 0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7, 8, 9, 10, 12, 14, 24 }
+local CPY_BASE = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 18, 22, 30, 38, 54, 70, 102, 134, 198, 326, 582, 1094, 2118 }
+local CPY_EXTRA = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7, 8, 9, 10, 24 }
+local CELL_INS = { 0, 0, 0, 0, 8, 8, 0, 16, 8, 16, 16 }
+local CELL_CPY = { 0, 8, 0, 8, 0, 8, 16, 0, 16, 8, 16 }
+-- static dictionary: bits of the word index per word length 0..24 (index + 1), and the offsets
+local NDBITS = { 0, 0, 0, 0, 10, 10, 11, 11, 10, 10, 10, 10, 10, 9, 9, 8, 7, 7, 8, 7, 7, 6, 6, 5, 5 }
+local DOFF = table.create(25, 0)
+do
+ local o = 0
+ for l = 4, 24 do
+ DOFF[l + 1] = o
+ o += l * 2 ^ NDBITS[l + 1]
+ end
+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
+ for _ = 1, 8 do
+ r = r * 2 + v % 2
+ v = v // 2
+ end
+ 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
+ end
+ local used = 0
+ for s = 0, n - 1 do
+ local l = readu8(lens, s)
+ if l > 0 then
+ count[l] += 1
+ used += 1
+ end
+ end
+ if used <= 1 then
+ return 256
+ end
+ local left = 1
+ for l = 1, 15 do
+ left = left * 2 - count[l]
+ if left < 0 then
+ return -1
+ end
+ end
+ -- canonical codes: the first code of length l is (first(l - 1) + count(l - 1)) * 2
+ local code = 0
+ for l = 1, 15 do
+ nextc[l] = code
+ code = (code + count[l]) * 2
+ end
+ for i = 1, 256 do
+ subBits[i] = 0
+ end
+ local nc = table.clone(nextc)
+ for s = 0, n - 1 do
+ local l = readu8(lens, s)
+ if l > 8 then
+ local c = nc[l]
+ nc[l] = c + 1
+ local pre = band(reverse(c, l), 255)
+ local k = l - 8
+ if k > subBits[pre + 1] then
+ subBits[pre + 1] = k
+ end
+ elseif l > 0 then
+ nc[l] += 1
+ end
+ end
+ local size = 256
+ for i = 1, 256 do
+ local k = subBits[i]
+ if k > 0 then
+ subOff[i] = size
+ size += lshift(1, k)
+ end
+ end
+ 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
+ for s = 0, n - 1 do
+ if readu8(lens, s) > 0 then
+ used += 1
+ single = s
+ end
+ end
+ if used <= 1 then
+ local e = (if single < 0 then 0 else single) * 32
+ for i = 0, 255 do
+ writeu32(T, (at + i) * 4, e)
+ end
+ return
+ end
+ for i = 1, 256 do
+ local k = subBits[i]
+ if k > 0 then
+ writeu32(T, (at + i - 1) * 4, subOff[i] * 32 + 16 + k)
+ end
+ end
+ for s = 0, n - 1 do
+ local l = readu8(lens, s)
+ if l > 0 then
+ local c = nextc[l]
+ nextc[l] = c + 1
+ local rev = reverse(c, l)
+ local e = s * 32 + l
+ if l <= 8 then
+ local step = lshift(1, l)
+ local i = rev
+ while i < 256 do
+ writeu32(T, (at + i) * 4, e)
+ i += step
+ end
+ else
+ local pre = band(rev, 255)
+ local sb = subBits[pre + 1]
+ local base = at + subOff[pre + 1]
+ local step = lshift(1, l - 8)
+ local i = rshift(rev, 8)
+ local lim = lshift(1, sb)
+ while i < lim do
+ writeu32(T, (base + i) * 4, e)
+ i += step
+ end
+ end
+ end
+ end
+end
+
+-- the largest distance alphabet whose distances stay under MAX_ALLOWED_DISTANCE (large windows); after the reference
+-- decoder's BrotliCalculateDistanceCodeLimit
+local function distanceLimit(maxDistance: number, npostfix: number, ndirect: number): number
+ if maxDistance <= ndirect then
+ return maxDistance + 16
+ end
+ local offset = maxDistance + 1 - ndirect - 1
+ offset = rshift(offset, npostfix) + 4
+ local ndistbits = 0
+ local tmp = offset // 2
+ while tmp ~= 0 do
+ ndistbits += 1
+ tmp = rshift(tmp, 1)
+ end
+ ndistbits -= 1
+ local half = band(rshift(offset, ndistbits), 1)
+ local group = bor(lshift(ndistbits - 1, 1), half)
+ if group == 0 then
+ return ndirect + 16
+ end
+ group -= 1
+ local postfix = lshift(1, npostfix) - 1
+ 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
+ local bb, bc = 0, 0
+
+ local function fill()
+ while bc <= 24 do
+ local byte = 0
+ if ip < lim then
+ byte = readu8(src, ip)
+ end
+ ip += 1
+ bb = bor(bb, lshift(byte, bc))
+ bc += 8
+ end
+ end
+ local function bits(n: number): number
+ if bc < n then
+ fill()
+ end
+ local v = band(bb, lshift(1, n) - 1)
+ bb = rshift(bb, n)
+ bc -= n
+ return v
+ end
+ local function bitsLong(n: number): number
+ if n <= 24 then
+ return bits(n)
+ end
+ local lo = bits(16)
+ return lo + bits(n - 16) * 65536
+ end
+ local function overrun(): boolean
+ 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)
+ local CLL = bcreate(18)
+ local CLT = bcreate(256 * 4)
+
+ local function decodeSym(base: number): number
+ if bc < 15 then
+ fill()
+ end
+ local e = readu32(T, (base + band(bb, 255)) * 4)
+ local l = band(e, 31)
+ if l >= 16 then
+ e = readu32(T, (base + rshift(e, 5) + band(rshift(bb, 8), lshift(1, l - 16) - 1)) * 4)
+ l = band(e, 31)
+ end
+ bb = rshift(bb, l)
+ bc -= l
+ 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
+ return -1
+ end
+ local need = (tpos + size) * 4
+ if need > blen(T) then
+ local nt = bcreate(math.max(blen(T) * 2, need))
+ bcopy(nt, 0, T, 0, tpos * 4)
+ T = nt
+ end
+ build(LENS, n, T, tpos)
+ local base = tpos
+ tpos += size
+ 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)
+ if hskip == 1 then
+ local nsym = bits(2) + 1
+ local maxBits = 0
+ local x = alphabetMax - 1
+ while x > 0 do
+ maxBits += 1
+ x = rshift(x, 1)
+ end
+ local s1, s2, s3, s4 = -1, -1, -1, -1
+ for i = 1, nsym do
+ local v = bits(maxBits)
+ if v >= limit then
+ return -1
+ end
+ if i == 1 then
+ s1 = v
+ elseif i == 2 then
+ s2 = v
+ elseif i == 3 then
+ s3 = v
+ else
+ s4 = v
+ end
+ end
+ if nsym >= 2 and (s1 == s2 or s1 == s3 or s1 == s4 or (nsym >= 3 and (s2 == s3 or s2 == s4)) or (nsym == 4 and s3 == s4)) then
+ return -1
+ end
+ if nsym == 1 then
+ writeu8(LENS, s1, 1)
+ elseif nsym == 2 then
+ writeu8(LENS, s1, 1)
+ writeu8(LENS, s2, 1)
+ elseif nsym == 3 then
+ writeu8(LENS, s1, 1)
+ writeu8(LENS, s2, 2)
+ writeu8(LENS, s3, 2)
+ else
+ if bits(1) == 0 then
+ writeu8(LENS, s1, 2)
+ writeu8(LENS, s2, 2)
+ writeu8(LENS, s3, 2)
+ writeu8(LENS, s4, 2)
+ else
+ writeu8(LENS, s1, 1)
+ writeu8(LENS, s2, 2)
+ writeu8(LENS, s3, 3)
+ writeu8(LENS, s4, 3)
+ end
+ end
+ return install(limit)
+ end
+ -- complex: the code length code
+ bfill(CLL, 0, 0, 18)
+ local space, num = 32, 0
+ for i = hskip + 1, 18 do
+ if bc < 4 then
+ fill()
+ end
+ local ix = band(bb, 15)
+ local v = CLP_VAL[ix + 1]
+ local dl = CLP_LEN[ix + 1]
+ bb = rshift(bb, dl)
+ bc -= dl
+ writeu8(CLL, CL_ORDER[i], v)
+ if v ~= 0 then
+ space -= rshift(32, v)
+ num += 1
+ if space <= 0 then
+ break
+ end
+ end
+ end
+ if not (num == 1 or space == 0) then
+ return -1
+ end
+ -- its table (lengths <= 5)
+ do
+ local size = prepare(CLL, 18)
+ if size ~= 256 then
+ return -1
+ end
+ build(CLL, 18, CLT, 0)
+ end
+ -- the symbol code lengths
+ local sym, prev, rep, repLen = 0, 8, 0, 0
+ space = 32768
+ while sym < limit and space > 0 do
+ if bc < 15 then
+ fill()
+ end
+ local e = readu32(CLT, band(bb, 255) * 4)
+ local l = band(e, 31)
+ bb = rshift(bb, l)
+ bc -= l
+ local cl = rshift(e, 5)
+ if cl < 16 then
+ rep = 0
+ writeu8(LENS, sym, cl)
+ if cl ~= 0 then
+ prev = cl
+ space -= rshift(32768, cl)
+ end
+ sym += 1
+ else
+ local extra = if cl == 16 then 2 else 3
+ local d = bits(extra)
+ local newLen = if cl == 16 then prev else 0
+ if repLen ~= newLen then
+ rep = 0
+ repLen = newLen
+ end
+ local old = rep
+ if rep > 0 then
+ rep = (rep - 2) * lshift(1, extra)
+ end
+ rep += d + 3
+ local delta = rep - old
+ if sym + delta > limit then
+ return -1
+ end
+ if repLen ~= 0 then
+ bfill(LENS, sym, repLen, delta)
+ space -= delta * rshift(32768, repLen)
+ end
+ sym += delta
+ end
+ if overrun() then
+ return -1
+ end
+ end
+ if space ~= 0 then
+ return -1
+ end
+ return install(limit)
+ end
+
+ local function varLen8(): number
+ if bits(1) == 0 then
+ return 0
+ end
+ local n = bits(3)
+ if n == 0 then
+ return 1
+ end
+ return bits(n) + lshift(1, n)
+ end
+
+ local function blockLen(base: number): number
+ local code = decodeSym(base)
+ 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)
+ if ntrees < 2 then
+ return ntrees, map
+ end
+ local rleMax = 0
+ if bits(1) == 1 then
+ rleMax = bits(4) + 1
+ end
+ local base = readCode(ntrees + rleMax, ntrees + rleMax)
+ if base < 0 then
+ return -1, map
+ end
+ local i = 0
+ while i < size do
+ local code = decodeSym(base)
+ if code == 0 then
+ i += 1
+ elseif code > rleMax then
+ writeu8(map, i, code - rleMax)
+ i += 1
+ else
+ local reps = lshift(1, code) + bits(code)
+ if i + reps > size then
+ return -1, map
+ end
+ i += reps -- zeros (map is zero-filled)
+ end
+ if overrun() then
+ return -1, map
+ end
+ end
+ if bits(1) == 1 then -- inverse move-to-front
+ local mtf = table.create(256, 0)
+ for k = 1, 256 do
+ mtf[k] = k - 1
+ end
+ for k = 0, size - 1 do
+ local idx = readu8(map, k)
+ local v = mtf[idx + 1]
+ writeu8(map, k, v)
+ if idx > 0 then
+ table.move(mtf, 1, idx, 2)
+ mtf[1] = v
+ end
+ end
+ end
+ return ntrees, map
+ end
+
+ -- ------------------------------------------------------------------ stream header
+ fill()
+ local wbits
+ local large = false
+ if bits(1) == 0 then
+ wbits = 16
+ else
+ local n = bits(3)
+ if n ~= 0 then
+ wbits = 17 + n
+ else
+ local m = bits(3)
+ if m == 1 then
+ if not largeWindow then
+ return nil, "unsupported: large-window brotli (pass opts.largeWindow = true)"
+ end
+ if bits(1) == 1 then
+ return nil, "bad window bits"
+ end
+ large = true
+ wbits = bits(6)
+ if wbits < 10 or wbits > 30 then
+ return nil, "bad large window bits"
+ end
+ elseif m ~= 0 then
+ wbits = 8 + m
+ else
+ wbits = 17
+ end
+ end
+ end
+ local maxBackward = 2 ^ wbits - 16
+
+ local dict = S.dictionary
+ local LUT = S.context
+ local PS = S.prefixSuffix
+ local PSMAP = S.prefixSuffixMap
+ local TRANS = S.transforms
+ local WORD = bcreate(64)
+
+ local out = bcreate(math.max(256, math.min(len * 4, maxBytes)))
+ local op = 0
+ -- distance ring buffer: last, second, third, fourth
+ local d0, d1, d2, d3 = 4, 11, 15, 16
+
+ while true do
+ -- ---------------------------------------------------------------- meta-block header
+ if overrun() then
+ return nil, "truncated stream"
+ end
+ local isLast = bits(1) == 1
+ if isLast and bits(1) == 1 then
+ break -- ISLASTEMPTY
+ end
+ local mn = bits(2)
+ local mlen = 0
+ if mn == 3 then
+ -- metadata
+ if bits(1) ~= 0 then
+ return nil, "reserved bit set"
+ end
+ local nbytes = bits(2)
+ for i = 0, nbytes - 1 do
+ local b = bits(8)
+ if i + 1 == nbytes and nbytes > 1 and b == 0 then
+ return nil, "exuberant metadata length byte"
+ end
+ mlen += b * 2 ^ (8 * i)
+ end
+ if nbytes > 0 then
+ mlen += 1
+ end
+ local pad = band(bc, 7)
+ if pad > 0 and bits(pad) ~= 0 then
+ return nil, "nonzero padding"
+ end
+ ip -= rshift(bc, 3)
+ bb, bc = 0, 0
+ if ip + mlen > lim then
+ return nil, "truncated metadata"
+ end
+ ip += mlen
+ if isLast then
+ break
+ end
+ continue
+ end
+ local nib = mn + 4
+ for i = 0, nib - 1 do
+ local v = bits(4)
+ if i + 1 == nib and nib > 4 and v == 0 then
+ return nil, "exuberant nibble"
+ end
+ mlen += v * 2 ^ (4 * i)
+ end
+ mlen += 1
+ local uncompressed = false
+ if not isLast then
+ uncompressed = bits(1) == 1
+ end
+ if op + mlen > maxBytes then
+ return nil, "limit: output over " .. maxBytes .. " bytes"
+ end
+ if op + mlen + 8 > blen(out) then
+ local nb = bcreate(math.min(math.max(blen(out) * 2, op + mlen + 8), maxBytes + 8))
+ bcopy(nb, 0, out, 0, op)
+ out = nb
+ end
+ if uncompressed then
+ local pad = band(bc, 7)
+ if pad > 0 and bits(pad) ~= 0 then
+ return nil, "nonzero padding"
+ end
+ ip -= rshift(bc, 3)
+ bb, bc = 0, 0
+ if ip + mlen > lim then
+ return nil, "truncated uncompressed block"
+ end
+ bcopy(out, op, src, ip, mlen)
+ ip += mlen
+ op += mlen
+ if isLast then
+ break
+ end
+ continue
+ end
+
+ -- ---------------------------------------------------------------- compressed meta-block
+ tpos = 0
+ -- block types / counts: 1 = literals, 2 = commands, 3 = distances
+ local nbtL, nbtI, nbtD = 1, 1, 1
+ local btTreeL, btTreeI, btTreeD = 0, 0, 0
+ local blTreeL, blTreeI, blTreeD = 0, 0, 0
+ local cntL, cntI, cntD = 1073741824, 1073741824, 1073741824
+ for c = 1, 3 do
+ local nbt = varLen8() + 1
+ local btt, blt, cnt = 0, 0, 1073741824
+ if nbt >= 2 then
+ btt = readCode(nbt + 2, nbt + 2)
+ if btt < 0 then
+ return nil, "bad block type code"
+ end
+ blt = readCode(26, 26)
+ if blt < 0 then
+ return nil, "bad block count code"
+ end
+ cnt = blockLen(blt)
+ end
+ if c == 1 then
+ nbtL, btTreeL, blTreeL, cntL = nbt, btt, blt, cnt
+ elseif c == 2 then
+ nbtI, btTreeI, blTreeI, cntI = nbt, btt, blt, cnt
+ else
+ nbtD, btTreeD, blTreeD, cntD = nbt, btt, blt, cnt
+ end
+ end
+ if overrun() then
+ return nil, "truncated meta-block header"
+ end
+ local npostfix = bits(2)
+ local ndirect = lshift(bits(4), npostfix)
+ local postMask = lshift(1, npostfix) - 1
+ local modes = table.create(nbtL, 0)
+ for i = 1, nbtL do
+ modes[i] = bits(2)
+ end
+ local ntreesL, cmapL = readContextMap(64 * nbtL)
+ if ntreesL < 0 then
+ return nil, "bad literal context map"
+ end
+ local ntreesD, cmapD = readContextMap(4 * nbtD)
+ 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)
+ if b < 0 then
+ return nil, "bad literal code"
+ end
+ litBase[i] = b
+ end
+ local cmdBase = table.create(nbtI, 0)
+ for i = 1, nbtI do
+ local b = readCode(704, 704)
+ if b < 0 then
+ return nil, "bad insert-and-copy code"
+ end
+ cmdBase[i] = b
+ end
+ local distMax = 16 + ndirect + lshift(if large then 62 else 24, npostfix + 1)
+ local distLimit = if large then distanceLimit(MAX_ALLOWED_DISTANCE, npostfix, ndirect) else distMax
+ local distBase = table.create(ntreesD, 0)
+ for i = 1, ntreesD do
+ local b = readCode(distMax, distLimit)
+ if b < 0 then
+ return nil, "bad distance code"
+ end
+ distBase[i] = b
+ end
+ 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]
+ end
+ local distMap = table.create(4 * nbtD, 0)
+ for i = 0, 4 * nbtD - 1 do
+ 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
+ local lutBase = modes[1] * 512
+ local litSlice = 0
+ local cmdTree = cmdBase[1]
+ local distSlice = 0
+
+ local remaining = mlen
+ while remaining > 0 do
+ 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
+ t = typeI + 1
+ elseif t == 0 then
+ t = prevI
+ else
+ t -= 2
+ end
+ if t >= nbtI then
+ t -= nbtI
+ end
+ prevI, typeI = typeI, t
+ cntI = blockLen(blTreeI)
+ cmdTree = cmdBase[t + 1]
+ end
+ cntI -= 1
+ local cmd = decodeSym(cmdTree)
+ local cell = rshift(cmd, 6)
+ local insCode = CELL_INS[cell + 1] + band(rshift(cmd, 3), 7)
+ local cpyCode = CELL_CPY[cell + 1] + band(cmd, 7)
+ local insLen = INS_BASE[insCode + 1]
+ local ie = INS_EXTRA[insCode + 1]
+ if ie > 0 then
+ insLen += bits(ie)
+ end
+ local cpyLen = CPY_BASE[cpyCode + 1]
+ local ce = CPY_EXTRA[cpyCode + 1]
+ if ce > 0 then
+ cpyLen += bits(ce)
+ end
+ -- literals
+ if insLen > remaining then
+ return nil, "insert past the meta-block end"
+ end
+ if insLen > 0 then
+ local p1 = if op > 0 then readu8(out, op - 1) else 0
+ local p2 = if op > 1 then readu8(out, op - 2) else 0
+ for _ = 1, insLen do
+ if cntL == 0 then
+ local t = decodeSym(btTreeL)
+ if t == 1 then
+ t = typeL + 1
+ elseif t == 0 then
+ t = prevL
+ else
+ t -= 2
+ end
+ if t >= nbtL then
+ t -= nbtL
+ end
+ prevL, typeL = typeL, t
+ cntL = blockLen(blTreeL)
+ lutBase = modes[t + 1] * 512
+ litSlice = t * 64
+ end
+ cntL -= 1
+ local ctx = bor(readu8(LUT, lutBase + p1), readu8(LUT, lutBase + 256 + p2))
+ local base = litMap[litSlice + ctx + 1]
+ if bc < 16 then
+ if ip + 2 <= lim then
+ bb = bor(bb, lshift(readu16(src, ip), bc))
+ ip += 2
+ bc += 16
+ else
+ fill()
+ end
+ end
+ local e = readu32(T, (base + band(bb, 255)) * 4)
+ local l = band(e, 31)
+ if l >= 16 then
+ e = readu32(T, (base + rshift(e, 5) + band(rshift(bb, 8), lshift(1, l - 16) - 1)) * 4)
+ l = band(e, 31)
+ end
+ bb = rshift(bb, l)
+ bc -= l
+ local lit = rshift(e, 5)
+ writeu8(out, op, lit)
+ op += 1
+ p2 = p1
+ p1 = lit
+ end
+ remaining -= insLen
+ if remaining == 0 then
+ break
+ end
+ end
+ -- distance
+ local dist
+ local push = true
+ if cell < 2 then
+ dist = d0
+ push = false
+ else
+ if cntD == 0 then
+ local t = decodeSym(btTreeD)
+ if t == 1 then
+ t = typeD + 1
+ elseif t == 0 then
+ t = prevD
+ else
+ t -= 2
+ end
+ if t >= nbtD then
+ t -= nbtD
+ end
+ prevD, typeD = typeD, t
+ cntD = blockLen(blTreeD)
+ distSlice = t * 4
+ end
+ cntD -= 1
+ local dctx = if cpyLen > 4 then 3 else cpyLen - 2
+ local dcode = decodeSym(distMap[distSlice + dctx + 1])
+ if dcode < 16 then
+ if dcode == 0 then
+ dist = d0
+ push = false
+ elseif dcode == 1 then
+ dist = d1
+ elseif dcode == 2 then
+ dist = d2
+ elseif dcode == 3 then
+ dist = d3
+ elseif dcode < 10 then
+ local k = (dcode - 2) // 2 -- 4,5 -> 1; 6,7 -> 2; 8,9 -> 3
+ dist = if dcode % 2 == 0 then d0 - k else d0 + k
+ else
+ local k = (dcode - 8) // 2 -- 10,11 -> 1; ...
+ dist = if dcode % 2 == 0 then d1 - k else d1 + k
+ end
+ if dist <= 0 then
+ return nil, "bad distance"
+ end
+ elseif dcode < 16 + ndirect then
+ dist = dcode - 15
+ else
+ local x = dcode - ndirect - 16
+ local ndistbits = 1 + rshift(x, npostfix + 1)
+ local hcode = rshift(x, npostfix)
+ local lcode = band(x, postMask)
+ local offset = (2 + band(hcode, 1)) * 2 ^ ndistbits - 4
+ dist = (offset + bitsLong(ndistbits)) * 2 ^ npostfix + lcode + ndirect + 1
+ end
+ end
+ local maxDist = if op < maxBackward then op else maxBackward
+ if dist > maxDist then
+ -- a static dictionary word
+ if dist > MAX_ALLOWED_DISTANCE or cpyLen < 4 or cpyLen > 24 then
+ return nil, "bad dictionary reference"
+ end
+ local nb = NDBITS[cpyLen + 1]
+ local addr = dist - maxDist - 1
+ local widx = band(addr, lshift(1, nb) - 1)
+ local tidx = rshift(addr, nb)
+ if tidx >= NTRANSFORMS then
+ return nil, "bad dictionary transform"
+ end
+ local woff = DOFF[cpyLen + 1] + widx * cpyLen
+ -- transform into WORD
+ local pfx = PSMAP[TRANS[tidx * 3 + 1] + 1]
+ local ttype = TRANS[tidx * 3 + 2]
+ local sfx = PSMAP[TRANS[tidx * 3 + 3] + 1]
+ local w = 0
+ local pl = readu8(PS, pfx)
+ for k = 1, pl do
+ writeu8(WORD, w, readu8(PS, pfx + k))
+ w += 1
+ end
+ local wl = cpyLen
+ local wo = woff
+ if ttype <= 9 then
+ wl -= ttype
+ elseif ttype >= 12 and ttype <= 20 then
+ local skip = ttype - 11
+ wo += skip
+ wl -= skip
+ end
+ local ws = w
+ if wl > 0 then
+ bcopy(WORD, w, dict, wo, wl)
+ w += wl
+ end
+ if ttype == 10 then
+ -- uppercase the first character
+ local c = readu8(WORD, ws)
+ if c < 0xC0 then
+ if c >= 97 and c <= 122 then
+ writeu8(WORD, ws, c - 32)
+ end
+ elseif c < 0xE0 then
+ writeu8(WORD, ws + 1, bit32.bxor(readu8(WORD, ws + 1), 32))
+ else
+ writeu8(WORD, ws + 2, bit32.bxor(readu8(WORD, ws + 2), 5))
+ end
+ elseif ttype == 11 then
+ local p = ws
+ local left = wl
+ while left > 0 do
+ local c = readu8(WORD, p)
+ local step
+ if c < 0xC0 then
+ if c >= 97 and c <= 122 then
+ writeu8(WORD, p, c - 32)
+ end
+ step = 1
+ elseif c < 0xE0 then
+ writeu8(WORD, p + 1, bit32.bxor(readu8(WORD, p + 1), 32))
+ step = 2
+ else
+ writeu8(WORD, p + 2, bit32.bxor(readu8(WORD, p + 2), 5))
+ step = 3
+ end
+ p += step
+ left -= step
+ end
+ end
+ local sl = readu8(PS, sfx)
+ for k = 1, sl do
+ writeu8(WORD, w, readu8(PS, sfx + k))
+ w += 1
+ end
+ if w == 0 and dist <= 120 then
+ return nil, "empty dictionary word"
+ end
+ if w > remaining then
+ return nil, "dictionary word past the meta-block end"
+ end
+ bcopy(out, op, WORD, 0, w)
+ op += w
+ remaining -= w
+ else
+ if cpyLen > remaining then
+ return nil, "copy past the meta-block end"
+ end
+ if push then
+ d3, d2, d1, d0 = d2, d1, d0, dist
+ end
+ local from = op - dist
+ if dist >= cpyLen then
+ bcopy(out, op, out, from, cpyLen)
+ else
+ for k = 0, cpyLen - 1 do
+ writeu8(out, op + k, readu8(out, from + k))
+ end
+ end
+ op += cpyLen
+ remaining -= cpyLen
+ end
+ end
+ if isLast then
+ break
+ end
+ end
+ -- the final byte's padding bits must be zero
+ local pad = band(bc, 7)
+ if pad > 0 and bits(pad) ~= 0 then
+ return nil, "nonzero padding at the end"
+ end
+ ip -= rshift(bc, 3)
+ if ip > lim then
+ return nil, "truncated stream"
+ end
+ return out, op, ip
+end
+
+return Decode
diff --git a/src/Formats/codecs/Brotli/Static.luau b/src/Formats/codecs/Brotli/Static.luau
new file mode 100644
index 0000000..d9170fa
--- /dev/null
+++ b/src/Formats/codecs/Brotli/Static.luau
@@ -0,0 +1,866 @@
+--!strict
+-- codecs/Brotli/Static: GENERATED by tools/brotli_static.py from the brotli C sources (MIT, Google; see
+-- licenses/brotli-LICENSE.txt) - do not edit. The RFC 7932 static dictionary (122784 bytes, deflated, base64),
+-- the context lookup table (Appendix B, 4 modes x 512) and the 121 word transforms (Appendix B).
+return {
+ dictionarySize = 122784,
+ dictionaryCrc = 1362545412,
+ dictionary = {
+ "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",
+ "/wTNVhYWVhbuZqcPNEd/zp7Prrw4sDL3U/3q7calo9nz2ysvLzUPnGk8Xqw/ul6/dKTx8lTjl4v1I0P4vTlzGN3yvcuHOKRf",
+ "rjXO3KuPPV+9c271+lM+ODRcH0fLmdXz06s3LjQm57LhxytzR5svX9ZPXmo8ubHychmPNF9iVM+yS/caC8src4to2Xx6uH7u",
+ "YvPuyOqNU9nklezW8frje9nIMb598VL9zLPm+YlsZDibnq+fuNc8fjKbO5hdWqg/G8M6NO4vYF7ZxKls7tDK4tDK/Fh2+2U2",
+ "cbRx5mr9yWI2udQ4MspvZ89mdw7Wr1yqHzlax7PnHq6eX6xfGsIv9XPz2YuJ7Nj5lYUH9YmTK0uTHPbCifrkk+zWT83li1g0",
+ "LEhj8Wrj6u3VA6frc3P1sYlsfjk7NZ4NP1tZPIf+m9fvZdNHsuF7jQeyHS9+yk5daC5PNq8faxycz0YXG0fG6pcPNc48zaZO",
+ "rsyda5w91pxeak5fz4aPN5/M189ebB58lI1fy4Zvc9jj99AtdjY7O4Kdyo7/lE3faJx4iEVbmRuvP32Ouay8PJs9f9RYnGjg",
+ "2XtDzZk7jcWRxq2l7NhC4+Ji9vJs/dID7N3qpaHmnQMri8/r117Uz8zUjx0A2axeHF49vVQ/cRu/Z9PPssUFDKYOApg4unph",
+ "uDmzWH98Nls6uvLyeOPlNF5Rf3pidehI/eh9rEb92vPs5ensyPFsbKQxu1g/8SPmmE1eW5kDXd2qXziNVc1Onli9+nhlHjM9",
+ "3jz0cnUIyziKZqC0xt1TIBJQJj7HS7Nbo9nJMRBPdusuRoLxY+ka18407j9bmTuN9ljS1UP3Vq/PNyan8fbV0WPN5Qv1CzPZ",
+ "i6Hs7tH6oeFs5ClWtXn4FGiSdHX6QOPIsWxuOhu/j0+yY+dIXQsn2f/UHfx/Zf5adulhdnmo/nSieXesPn4WDUD5jXtHsVD1",
+ "2YP1oROgIvBLNnQxG7+KcYJK8RUGgFmjcXN6Jrt6AkQIysFCcU9fztaPTjYPXMhuPqxfOLGyuMjdOXA7W3heP/uwfny6sXSC",
+ "3Dr7svnyzsri0cbi8ZWXI5gFV+zpAdAqWBJcBm7lXGYu1y8sNW4tkJAWJrPjZ7ERYFtQFNa8fuUkxz+5VD8/DFLEyLPh55gX",
+ "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",
+ "Lqe9fa/pfbITg8eYPL3k30Wfn5RVaKP1svfv6+Rsfs3H9DE8D/mbz3BkTpJ/+Dx+07h8zv/zS/7fX/b//qr/93O/9Mu/8qu/",
+ "9uu/8Ru//mu/+iu//Euf+80dM3/n7+78e3//7/+9nX/378zs+M1/8A//0T/+J//0n/3zf/7P/uk/+cf/6B/+g3/xL//Vv/43",
+ "//bf/ft//+/+7b/51//qX/6L/9f+E/fA779kP3/Z//9L/v9f4Xvxp//2m/7fz7FRv2JN+bXP/frnfiPiWoqyogIlMuSST1Cs",
+ "eHMTFUATO3zqHqIsJFeC4X7HkTsWjpGDiZAycxRQpol6TygdVKONtjq7GirmRWKpFR7j5sm5W4/gNUCyw044zOZnMOa8TGoO",
+ "GPGdwqt17LweKy3DpCUgegMPaylsUfcm8ufE2dtDTKhyEgrQ5qNCEJxgnmMu4pdGvMJggx0Nx0z0A/TCDH4nMlFbqNRHmRBA",
+ "5GqG55CdWc08QFQvMVKY4BPVMQA6wPCLmDYzafJcds4QnY3vI6VB4q3b6wHzRpNvBfAy0m8NMW1woA+4Y9kEkqLpwpFFLLsp",
+ "yRIzapOjzjRgFgxxVmZMELcASL85tj1GZJ0Na2lBXJ+gLlTs0W7DpKa11kbMmoH0L17BpQSdeqjqxi26pKzro27MnoWYutGG",
+ "+cx9mzr3eTKtmF+zljWzuxZhv/NxNut1jVfZh1GzGhR95jKKMYWkrg2raUDNB/dzuxKSDe4/gilIPCJ1gMTgRPHEOkXKwTtp",
+ "swexaeWo62aTXDX4TEWVdTPXDvSqYwzdl1uKvHUDiNIQt43QlLOj2URaW0OsEskthdmXWcGK9wUutl8WItCI8h4mHxxtu7+z",
+ "EqPMzN1R0PyxbsY+AyjnjdfKurnbJvbk6GCA/F0pj9uBOI0tEBL8zLCaAbe/w2xZ+N4okSOKoXvQ3A8W04AzDhdubnecDwJ/",
+ "a2NccHnGQ+zhWgbfEUAGFWnFCkaFUPZON29NqvaOBa4Qc9hCuaoyFTMBeWhYZYPB9fxC2RP5LWkDHQfg5RadBQflV907Y1lt",
+ "oQLqUH80CzkVBpXHfa8ntXuxyTNKU1oz7rPJQuxgxcQr6KvFpFd1R0cHBRgbGhXFjIQVZOW6Ux13lllD3i9RlqM8Z/d2IpZZ",
+ "FT1Uin7EhCDK5OEzIEhMHlLUFsbTNHfCmVqxGyw5WHI5EuX23WZMhG7Uoy6qINyu88XKZwJcIaZ/zU2yizPvvsnCqyaAUfN1",
+ "n1gC0p8JA3Qw9mcHL42bQNmQzgXkf1XgnRoWRmA4+wKUo2B2XUSbnDWi3WWp/ArgzUzXTJwSrjdBdSfHNBLEi0IKOERJ6TXR",
+ "Zdu+Yfs6eVPwBc7ymhkru7J4OEHJgNWGEC25nvCoABRubQxARVltWudtVQEOaohqAoxiV8SbQcnHKyshRz6pzcEqUnEs+uf0",
+ "OzbSdtGMPSvo0XWk8ZWGbNIZ4PdC+WDd5YyyNqO6YyV4ym3jti1OUUzPUncDXtVE/nymGTfKuHsGo9jTbNVDnFy9yIXPbNag",
+ "7TBPTVly6zFn10A8GVWzNoFEYWaN94DXA2Rrq0A77jTM2HsFcupi0+eO7aRaZK/VgBEAgQcUOTVS+mCPiaKVMY7+L3mwsCDS",
+ "npQOHn7tlr11nLQbmwFwaoBJIbmzsOH9irmR8VBgLSyDyL4ojS48jJekEdinzNNsQEUETZPBIPL8XYxKrm4UgRbp7o686F3V",
+ "yhCshkUkcIvIJO4j5AGbnS1A5rpx+KKCDpZMD5GK/R3NzFUwuZY6gA44YK6QPQR2g2Neanw3OuMP8E9kjQNlU2wSoGBHCeE7",
+ "JGddW9Nki8jkDg+xk8eDx/G8zVknS2OBbYkixYF1+9GNQeAUPTDUqE6lhpOuVCVzkUJBYgJsY0/riu23BiTAA7LzTtAy61R2",
+ "QIIgc2EtxDoj5WLCPOETDD9FFq4LUmAaHLtji6z6GCMA4Xs+NxziBozCskinImleOLds1b3Pw8FFnFZLawA3wLI65AjAohj0",
+ "V3rjodl1Y2aX+YD1lrhAGnKRFfda/7GKplwZyMxwdl+vLwRsvUIXwLwQpbTtWn2QHxDl190mG2WzdcyB/6u+MXbNKN3fMXum",
+ "4wg7SlSI1LYIcKSrXAyGgRZrPN1XdQ8DvYcnLLtdJqRmY44UHqKvWNpCLiQ3SsEdbc+B7f1wbO/gLrJuoWjWiOxuwerWdWjX",
+ "sPkSwup4PPAesFBF2xe4tTyd6jVx1loAnhFYskdZqUEeQijIOmy1o2SkBg/HsUUnctyoQH4PBibCRcfDyL5VkeDr2jFR9sXb",
+ "4FsTcnc1cKBUIUB7VIlsK+IOh/VMfO+lsAIIj8wwE4GlmeiEpBHzJGxWo8IuVOc7inc+ttOlNaLxQJWB1Q1CKNCPNySWIkF+",
+ "jcJ71AfZEVQEaoaoHBCe8MSCQQ6LrxSwVF1YjPvOAWjr9EESbXQKp6+LZFclehZySm9WZJ4K3NJkBTsnUh1l4dznHB3MSuwA",
+ "/dHy0sJ9g+FRO2RhMhNdxGGyLc5xtfBOhrOBpIA9D2T2xDmAQc40kpVM6BbRDX7czLtaAjZ8eTdDm1jbHDggKDTK5jKwllG1",
+ "lKCrF2EnKphXBNMppaxgi5enln3mQHsEECkEeT6HAh6ohzh3bZKxzg11mWKl2K5QcI4OrpysoR6R68UzWzjBRBoL2oset7gu",
+ "lDiGg6Nkh+LujrIsUUzYfAv8bbM56IEypWqIwbc9jLYoLXHQa7LCkuDzDbOWWS5HvoXKNzRSo29hFybbKPAILCBi1ZYgvKog",
+ "AwMIk/oYZe4tuE4/zEvhNe1id8a5TAI1THzK+zWaopt0Iu4XuLzskSQd4489cxUWmjmqIB0ewqQRPkLUVoDL/NYfHSQHZGfZ",
+ "URiHHVxWOMuCbZUVzmv71nxxiBxKyLWp01TwMEIKVlDCeWGgBIoiKLFxUuzeZHc4qLLZaPyPnBjHxn+3YDZrbmQjV4hOWK9G",
+ "B1lNSq8f47W0oMTiMkugNr3YuRYlpyzqRkwDNB2BBaapxv2+PyLLIdJ7giXV1dGv1W68mf2nJxUfg50ReFqyffyhbXoPjW0v",
+ "nRWBQ29CmwzutNJ38OuExwR7z7ZtawUY9bY1bb5WP1hvYbbKuiC4RJRqE1kdR1EoYs3HSR95aAeQwT4UV3M5YgKNpwzZkYYo",
+ "6eyJ3ser3WnXkZq3q5or2GOV8wUuR0r0EO0xPMIR0Z6y2JWblBcobTYs5sKBcRd2HTtsSUzB05w2NvYphOzZMPSKKHIxazGm",
+ "R8LsUXkDcorYhDF7+rbvrwMx5Al12xy2UAMGTCTZ3EkJ3FPlp5jBQfQf5zpa3AV5n6Yi9o3SSyydVQX07kqCF+L1BJ2GfZqb",
+ "flk4B3gP+1hDuiSGZgZrX/ZJWzj1ka1l+ne1dJw2cXCYmdvjOid8paFZ4moo5MMgpz2FA2wufSOwmCqlJkvfuu7lkk5I3DIh",
+ "af7g5roANeSaA2UX7G9wT1bSn+HXI0mOk3xUbm5BYIN7Lwbli0PS8q6X9JJQ2Cz1DRCSdIsSVYMYsUGfFLgYOHzra/DRvAKc",
+ "tqjwyEc2aJ8PQykKCCQUJgMq7xDaRjxs9q2DYfvFc3WdtLrCWqxI2b8UyEZHtu2ccTduFQg5HSUBSlguWahvvxdFSDw4zhQ4",
+ "kDXaSLsDwu6Ui6CSmogFhdw7A+s6mqY4NMU5jJ1R1eZgARiy1LH5angK7gHZPr/OCrRRRR4ALFFUKOqQxKaOiztX+lwAQDrL",
+ "fi9CxxXWq0T6aEuYghbcE4A2ECcjvEqzcpEHhg17cAMUYDVYO1Q5YDOVCD9wtDU1FjOS9nr2mYApKIZGAgkP05FApjQDg3Em",
+ "RiFIMbENBxy86XZBsDA+CDUDrGkUh4TggFm5oDcDyL0M6MyS2RE9cDyohZvg0UMA1zaZmRmnLnYuvdFAZTkIXnndRLMcFURh",
+ "CTu0W1JR4y2OBVJ/GCYq2sLuLh2412PJr287YMI66hpbNHedpeqgjezKSoUu8H0jqkSao4iKmF3Yj0hFlNLuI5feCuIboka3",
+ "bziBfbEXBhWCgstuafUm4rDFnMTOj2M7ANxFVLSxyphNjbhLIa4qcNlUtq+gV5sIDdmeNTywLoC0wj5ikN/aMEstaklszq4D",
+ "ZRRFGHNrZrsxxESDAdZH4JSWQELFbRBrhxp2IiyAxUiD4cEKxQBmRCOiCLsFG35Ee+bEc2QPeJgSXzoHETQ3m4SVXLCA4xAP",
+ "8LRZMhqB5ZEzOKEMWgsiALhN+ETdI2GvglSPW2UMyn6xWQBSjKMfRo5TpoJtpSHUP1Ua2C08ShQx6kkC5a5yywSJoYeIrKO6",
+ "fda3Y+DInlVEqV8M9xdYY4/rlEWrQqY4m3vHg6FopICOAbmhTfAi0g1gMyFEa0Z23ai7LHujIPU1UbIzZlusunUB5lPUlUcQ",
+ "bASSO8gsyBjAwRZndoCklpacuWFZ9dnWhsDp9ANovRynzR4SXHB79xq9OQa+UcHMQ5xejRnkpMuVehd2LS+onGM8WjSNgk4X",
+ "EYPd57TXvclBHp92UuCCot9FdTv6CNOPRy3eovktiKAY2MWMAR6eJg03wu3h0UOzRG6Ik01vVPfaUhlvkiwYVFe2ymcjLrYJ",
+ "4YJmMCq3ogyzLHzE7kByAFcUfTRPT5ekkGCLNRGsyt/EccRidBlUdjNsT52C5obZJLDy0BuOZ61TRVHj5A+rg4h5FlEcVJIb",
+ "QaVGYAKySVmyGp66EQ65dE7TesTFCmxcEeD7WBeF2Ghshgge77hGmruMhWPf5QRAC3dGgH2/E2XOdyvZ1VWgzgsFE7BL2HWo",
+ "hbO04BUn3qma4SAmqViDhzbY0tf3KRRx95F77yEtBHzXyT7n7j64geCg75A8TMhEhgxeuAPF7kCv+kFvrm/U76HkhqU1ZZxN",
+ "xMahuHotkhQ9lG1Vf/3S2I6x0Xi7/utLf/W0/QnB7L96xn/522uP/u3V7//t1R9/+v1XPn3h7Gdn/lKAvU/OfV+IPfvl/3nu",
+ "hf/r8rn/+/k3P756/eO3j3987YnPzr/08/Pfh1b92e99dv4Cvnj6O5/99PlPnjn+6QvPfPLUS5/82emPr//JZw9/7+fv/vGn",
+ "T7z/yQsXPr7+2sfvv/Hxte/+4pHTnzx+/edPPvHzU+99+p0/+eylpz999QV78bPvvvvpj9757P0///jq8U/PvfLp917/+O0f",
+ "fHL+L35x5unPXn/45z96+JPXvvfJH//g43d++OlzFz595vwn1//00ytPfPbmtc+On/zkqb/85OTZT86f+uz86c/OX//k6euf",
+ "vvXGJy9c+uTqiU//5Nyn33vP2vPJ09//+PpZe+WTU699cu7Vn3/vxc+uPPXpX7xi//7cHue7j+Hi77/06cOvW5sDTtjY3Ltx",
+ "znyGAUw3TORypQRsGxmSMUFw1dAxYN0EEjT7qieYE2wt5G1thrtTY0t6TITXyo3ryOmy+lxoISq1kyVA3g2CsUIPOvy07g7C",
+ "eBtuh5OVkIQAXgHUR5oUgqH6MGZZm65zuYUzJlxkU3uAa6DKaELvVseE36nW+ca5st688RLsi0DJlsOAVw2ZcwHSEuX2vKmZ",
+ "cTd+soYqfUhkOSZLIDIV0+oWxMlhpr7Ug1a915/bpusAqsYjZnVp2z9SFWXjNduDxkFZoVprPW+NufHS6kh1JQRGeh/WjiSz",
+ "V9DL7FUsHDY1nsJR3oSrEcZX9rzuhcwL9gK4EMhaCS+9BItTH3qG/Yes+dVDEUA2L7/H2VIGjK9xswxTYAhkZR9IvJeYyQAk",
+ "lxgxtJmTZKv0bwVasAmYZPT8oAlR7ROUxH7fJbchOn6CwtgSBb/Kf1/hu5f51gV+7PFQIpdI+cN/e+rP/S18/iz/fZWK3dfi",
+ "OlIlv8YPPxvXOc5m6Kavshmn4+unujWYKgarjUuAo0kX/vaVE9QvP83PnOfvp/j7T/n1CxRHv8oXT0WTLoZsue7+WNziQqiG",
+ "X4m3rCXP85WLvJ2a9FzcSyLlZ6mnftybil9+yKd4mndUj10MhfLnKXD+ZOiUv8r/nZLOOq+gTrgSeucn+d3v86bn4i7fD7l3",
+ "9eSFTK9dA/dkiMRz4LyfraMedplzvPWi9zYe8NsUYn8uOuFk3Ov7Idx+ir2R1NZfjI46wQ+rPd+Nm56PHlPL34tBtz+fCpX6",
+ "H8a9vhtdpAtKEv59vqjevsi+0nw4GwOtx9FcfS969Tg74Sybd5qt1dcfj4Y9htddV17zWXNVo/MkW3suZOwvxFO84FPF+/m8",
+ "PxfePcN/X4gHfCXudZztvxaq9mrkj+JPffhhPrJW0Cm+mGbLqWjeq2yzfj/jDUabn+YjXIn2vBpT6/W4qZr6OgeXN/I2H3f+",
+ "Dgh8QT6GxS6RXd85czBwLMUD5XapksUEYKEym9gslrYCm8PEGiXXYANJu2GpjHfFKIktzHVpvrBnL658WFcOEFADtoju6nC8",
+ "uQJr0jZks66B9HkIu1NPjiquchCSLlDILJ1voyYS2kM/9ymkVfMI6MtW9mi2/dZP7yo+WmZPvrQZdRadIiWxQzFR3ygFKnGV",
+ "CTMTxyCaL2776oHdw1Qtn1BIDYIOimSzLXSUv1aSg3g0aINv80UyEmtWEOAbCCqsDJHRUH6XPJrytuvEvLu/8/nA3JPnzQ05",
+ "NxXwvNXRRrLIzhmCvkLitha2RupU9daRNIL3Q8y6dATYVsmI9bgXYzlPx/jLa7MduMo9Ykk8fc1+9iRsIwU++IVfSVnFrydM",
+ "GNP/5jINuv2Bl8QuMYLNq6A4Ti4pSaG26M2CdtPusr+zlAU46VxQerJu5ml6e0rMrnJw0Hefju4V/N8RBm03LfyUGIemxVjl",
+ "nJEy0RPZOWNNBWOGqq5n4xyeI29m6atnGAriAI7g7dvTCnCFSaRw+hyAuqlmKdQC+uqUgeoEy0qncBSDnd/JpF9IaJWZ0B5n",
+ "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",
+ "IPjp0Cg/Ec9+JsbouGvEe1/FOOL1s7z+j3jZ1OdqyQW2860Y8RN8MX3m2yHdfnFqPni/XWPXnfJffF2kOXA8nlrC7q/GvV7g",
+ "k56AXry3/2powV9tHznNW78C+x+ffyHrq8uxgq7ysqejP0+7wH3bZvXVD0JC/WL7XN6rx9mex+PzbB6ufIptvsCePMFeutiO",
+ "na+j90JK/rFs37gcr59u57D6DXPsbHzlWnxen7ka6/Qam3eKn9R80/x/MfrkVAzKlZgDavMVb7DGvZ2rqQ8fj/X+BK92Jfrk",
+ "1Wx/OJ49Y7bn+BNFl+K+qT0XqFaf9hneF1c7n82fND+Pxyy9zLcoZO/j9Xw2x07GnHmFN01rTWvh+en98zi/pbV2ns/+flxH",
+ "81+b/HPTe/61+Myr2ZzRxL6Y7QM/jT45Gzv5Kd+j8JXz0bDv84nS9S/ECnqn7Qe89Vi8dSZG/HSMAluibmnX+/NTe0U7uLHW",
+ "fJ5f9odN+4P/qbHQ3Hua1+e08V36QnvG+fOmfj7JP6/yM2ejkc/6M/pnrsYAXcye8fH493le4TJffys7Ky/4d7Fv6Lx7JY07",
+ "2aLBi/0UGZLfJJ/0I4n1+dLNt4Kx+aOHwS790Um+foWMyC1Xs5iUT968SDbvxAOeGJZfyziWX7crvA5ecPBpBzM4Xp3iEH9U",
+ "zNi430cn/F7hAZNVmrzXev0s2uRs0xecdRy/n8Nn/ZrnPjrBK6k9b5D3Oq75mr13EozUdp2r/nkwdD/GT4Hf+vHgKCeL9MuJ",
+ "m/yNmz/mU4Br/HR23yfIz822OcO5GKkvkbVbjN/g5j6J52efBjP2G+Q3f0x84+KuJo/4JfJP6/VHyGJ+xvvtMT7laTFW3zyD",
+ "58d1+OoV8qU/xdfBYn4GfZC+S45u5+s+zW+87tcXb7nag2u/5c943ubBUzcv8YpvJL7un2b/XiaDtvd5y3VuM6Ptk/PgQ/dx",
+ "P+vs2i13/OPxehpT8Htfw9yLsYhnvPkqWqN+sKs647j112NkLg927xgXzLw3fP68br89wStj/l+3v8CTfpktiLlxmozvZ7xt",
+ "V/E644qI/MFtb+VEEfnfn8HMxA3u2FNSaqyPhx697LfvkG46wsokH0Y13mBzdheTIeJrmQDFg8ieRLRW6+HqeNMjjvM5NjjH",
+ "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",
+ },
+ context = {
+ "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+PwABAgMEBQYH",
+ "CAkKCwwNDg8QERITFBUWFxgZGhscHR4fICEiIyQlJicoKSorLC0uLzAxMjM0NTY3ODk6Ozw9Pj8AAQIDBAUGBwgJCgsMDQ4P",
+ "EBESExQVFhcYGRobHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4/AAECAwQFBgcICQoLDA0ODxAREhMUFRYX",
+ "GBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+PwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
+ "AAAAAAAAAAAAAAAAAQEBAQICAgIDAwMDBAQEBAUFBQUGBgYGBwcHBwgICAgJCQkJCgoKCgsLCwsMDAwMDQ0NDQ4ODg4PDw8P",
+ "EBAQEBERERESEhISExMTExQUFBQVFRUVFhYWFhcXFxcYGBgYGRkZGRoaGhobGxsbHBwcHB0dHR0eHh4eHx8fHyAgICAhISEh",
+ "IiIiIiMjIyMkJCQkJSUlJSYmJiYnJycnKCgoKCkpKSkqKioqKysrKywsLCwtLS0tLi4uLi8vLy8wMDAwMTExMTIyMjIzMzMz",
+ "NDQ0NDU1NTU2NjY2Nzc3Nzg4ODg5OTk5Ojo6Ojs7Ozs8PDw8PT09PT4+Pj4/Pz8/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQEAAAEAAAAAAAAAAAAAAAAAAAAAAAACAwQDAwUDBAYHAwMIAwkDCwsLCwsLCws",
+ "LCwgIBgoHAwMMDQ0NDA0NDQwNDQ0NDQwNDQ0NDQwNDQ0NDQYDBwMDAw4PDw8ODw8PDg8PDw8PDg8PDw8PDg8PDw8PBgMHAwA",
+ "AAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQIDAgMCAwID",
+ "AgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMAAAAAAAAAAAAAAAAAAAAA",
+ "AAAAAAAAAAAAAAAAAAAAAAABAQEBAQEBAQEBAQEBAQECAgICAgICAgICAQEBAQEBAQICAgICAgICAgICAgICAgICAgICAgIC",
+ "AgICAQEBAQEBAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMBAQEBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAICAgICAgIC",
+ "AgICAgICAgICAgICAgICAgICAgICAgICAAgICAgICAgICAgICAgICBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ",
+ "EBAQEBAQEBAQEBAQEBAQEBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgY",
+ "GBgYGBgYGBggICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg",
+ "KCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoMDAwMDAwMDAwMDAwMDAwOAABAQEBAQEB",
+ "AQEBAQEBAQECAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIDAwMDAwMDAwMDAwMDAwMD",
+ "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE",
+ "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUF",
+ "BQUFBQUFBQUFBQUFBQUFBQYGBgYGBgYGBgYGBgYGBgc=",
+ },
+ prefixSuffix = "ASACLCAIIG9mIHRoZSAEIG9mIAJzIAEuBSBhbmQgBCBpbiABIgQgdG8gAiI+AQoCLiABXQUgZm9yIAMgYSAGIHRoYXQgAScGIHdpdGggBiBmcm9tIAQgYnkgASgGLiBUaGUgBCBvbiAEIGFzIAQgaXMgBGluZyACCgkBOgNlZCACPSIEIGF0IANseSABLAI9JwUuY29tLwcuIFRoaXMgBSBub3QgA2VyIANhbCAEZnVsIARpdmUgBWxlc3MgBGVzdCAEaXplIALCoARvdXMgBSB0aGUgAmUgAA==",
+ prefixSuffixMap = { 0, 2, 5, 14, 19, 22, 24, 30, 35, 37, 42, 45, 47, 50, 52, 58, 62, 69, 71, 78, 85, 90, 92, 99, 104, 109, 114, 119, 122, 124, 128, 131, 136, 140, 142, 145, 151, 159, 165, 169, 173, 178, 183, 189, 194, 199, 202, 207, 213, 216 },
+ transforms = {
+ 49, 0, 49, 49, 0, 0, 0, 0, 0, 49, 12, 49, 49, 10, 0, 49, 0, 47, 0, 0, 49, 4, 0, 0, 49, 0, 3, 49, 10, 49,
+ 49, 0, 6, 49, 13, 49, 49, 1, 49, 1, 0, 0, 49, 0, 1, 0, 10, 0, 49, 0, 7, 49, 0, 9, 48, 0, 0, 49, 0, 8,
+ 49, 0, 5, 49, 0, 10, 49, 0, 11, 49, 3, 49, 49, 0, 13, 49, 0, 14, 49, 14, 49, 49, 2, 49, 49, 0, 15, 49, 0, 16,
+ 0, 10, 49, 49, 0, 12, 5, 0, 49, 0, 0, 1, 49, 15, 49, 49, 0, 18, 49, 0, 17, 49, 0, 19, 49, 0, 20, 49, 16, 49,
+ 49, 17, 49, 47, 0, 49, 49, 4, 49, 49, 0, 22, 49, 11, 49, 49, 0, 23, 49, 0, 24, 49, 0, 25, 49, 7, 49, 49, 1, 26,
+ 49, 0, 27, 49, 0, 28, 0, 0, 12, 49, 0, 29, 49, 20, 49, 49, 18, 49, 49, 6, 49, 49, 0, 21, 49, 10, 1, 49, 8, 49,
+ 49, 0, 31, 49, 0, 32, 47, 0, 3, 49, 5, 49, 49, 9, 49, 0, 10, 1, 49, 10, 8, 5, 0, 21, 49, 11, 0, 49, 10, 10,
+ 49, 0, 30, 0, 0, 5, 35, 0, 49, 47, 0, 2, 49, 10, 17, 49, 0, 36, 49, 0, 33, 5, 0, 0, 49, 10, 21, 49, 10, 5,
+ 49, 0, 37, 0, 0, 30, 49, 0, 38, 0, 11, 0, 49, 0, 39, 0, 11, 49, 49, 0, 34, 49, 11, 8, 49, 10, 12, 0, 0, 21,
+ 49, 0, 40, 0, 10, 12, 49, 0, 41, 49, 0, 42, 49, 11, 17, 49, 0, 43, 0, 10, 5, 49, 11, 10, 0, 0, 34, 49, 10, 33,
+ 49, 0, 44, 49, 11, 5, 45, 0, 49, 0, 0, 33, 49, 10, 30, 49, 11, 30, 49, 0, 46, 49, 11, 1, 49, 10, 34, 0, 10, 33,
+ 0, 11, 30, 0, 11, 1, 49, 11, 33, 49, 11, 21, 49, 11, 12, 0, 11, 5, 49, 11, 34, 0, 11, 12, 0, 10, 30, 0, 11, 34,
+ 0, 10, 34,
+ },
+}
diff --git a/src/Formats/codecs/Brotli/init.luau b/src/Formats/codecs/Brotli/init.luau
new file mode 100644
index 0000000..391ec29
--- /dev/null
+++ b/src/Formats/codecs/Brotli/init.luau
@@ -0,0 +1,150 @@
+--!strict
+-- codecs/Brotli: Brotli (RFC 7932) decompression. A codec (layer 3): archive/br and font/woff2 build on it. Written
+-- from the RFC (decoder in codecs/Brotli/Decode); the static dictionary, context table and word transforms come from
+-- google/brotli (MIT, licenses/brotli-LICENSE.txt) through codecs/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("@formats/codecs/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).
+local Err = require("@formats/core/Err")
+local Crc32 = require("@formats/core/Crc32")
+local Deflate = require("@formats/codecs/Deflate")
+local Decode = require("@formats/codecs/Brotli/Decode")
+local StaticData = require("@formats/codecs/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)
+}
+
+-- ------------------------------------------------------------------------------------------------ static data
+local B64 = {}
+do
+ local alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
+ for i = 1, 64 do
+ B64[string.byte(alphabet, i)] = i - 1
+ end
+end
+
+local function unbase64(s: string): buffer
+ local n = #s
+ local pad = 0
+ if string.sub(s, -2) == "==" then
+ pad = 2
+ elseif string.sub(s, -1) == "=" then
+ pad = 1
+ end
+ local out = buffer.create(n // 4 * 3 - pad)
+ local o = 0
+ for i = 1, n, 4 do
+ local a, b, c, d = string.byte(s, i, i + 3)
+ local v = B64[a] * 262144 + B64[b] * 4096 + (B64[c] or 0) * 64 + (B64[d] or 0)
+ buffer.writeu8(out, o, v // 65536)
+ if o + 1 < buffer.len(out) then
+ buffer.writeu8(out, o + 1, (v // 256) % 256)
+ end
+ if o + 2 < buffer.len(out) then
+ buffer.writeu8(out, o + 2, v % 256)
+ end
+ o += 3
+ end
+ return out
+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
+ end
+ local z = unbase64(table.concat(StaticData.dictionary))
+ local dict, err = Deflate.zlib(z, 0, nil, StaticData.dictionarySize)
+ if not dict then
+ return nil, err
+ end
+ if Crc32.of(dict) ~= StaticData.dictionaryCrc then
+ return nil, Err.new(Err.CHECKSUM, "brotli: static dictionary damaged")
+ end
+ static = {
+ dictionary = dict,
+ context = unbase64(table.concat(StaticData.context)),
+ prefixSuffix = unbase64(StaticData.prefixSuffix),
+ prefixSuffixMap = StaticData.prefixSuffixMap,
+ transforms = StaticData.transforms,
+ }
+ 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
+local function toBuffer(b: any): buffer?
+ if type(b) == "string" then
+ return buffer.fromstring(b)
+ end
+ return if type(b) == "buffer" then b else nil
+end
+
+-- 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 = toBuffer(buf)
+ if not b then
+ return nil, Err.new(Err.ARG, "Brotli.decompress: expected a buffer or a string, got " .. typeof(buf))
+ end
+ local n = buffer.len(b)
+ local o = offset or 0
+ if type(o) ~= "number" or o < 0 or o > n or o % 1 ~= 0 then
+ return nil, Err.new(Err.ARG, "Brotli.decompress: bad offset " .. tostring(offset))
+ end
+ local l = length or (n - o)
+ if type(l) ~= "number" or l < 0 or l % 1 ~= 0 then
+ return nil, Err.new(Err.ARG, "Brotli.decompress: bad length " .. tostring(length))
+ end
+ l = math.min(l, n - o)
+ local maxBytes = if opts and opts.maxBytes then opts.maxBytes else 2 ^ 30
+ if type(maxBytes) ~= "number" or maxBytes < 0 then
+ return nil, Err.new(Err.ARG, "Brotli.decompress: bad maxBytes")
+ end
+ local large = not (opts and opts.largeWindow == false)
+ if l == 0 then
+ return nil, Err.new(Err.TRUNCATED, "brotli: empty input", o)
+ end
+ local S, serr = tables()
+ if not S then
+ return nil, serr
+ end
+ local out, size, consumed = Decode.decompress(b, o, l, maxBytes, S, large)
+ if not out then
+ local msg = tostring(size)
+ local code = Err.CORRUPT
+ if string.find(msg, "truncated", 1, true) then
+ code = Err.TRUNCATED
+ elseif string.sub(msg, 1, 6) == "limit:" then
+ code = Err.LIMIT
+ elseif string.sub(msg, 1, 12) == "unsupported:" then
+ code = Err.UNSUPPORTED
+ end
+ return nil, Err.new(code, "brotli: " .. msg, o)
+ end
+ local res = out
+ if buffer.len(out) ~= size then
+ res = buffer.create(size)
+ buffer.copy(res, 0, out, 0, size)
+ end
+ return res, consumed
+end
+
+return Brotli
diff --git a/src/Formats/codecs/Bzip2/Decode.luau b/src/Formats/codecs/Bzip2/Decode.luau
new file mode 100644
index 0000000..66df42e
--- /dev/null
+++ b/src/Formats/codecs/Bzip2/Decode.luau
@@ -0,0 +1,538 @@
+--!strict
+--!native
+--!optimize 2
+-- codecs/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").
+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
+local bcreate, bcopy, bfill, blen = buffer.create, buffer.copy, buffer.fill, buffer.len
+
+local Decode = {}
+
+-- CRC-32/BZIP2 table (polynomial 0x04C11DB7, not reflected)
+local CT = table.create(256, 0)
+for i = 0, 255 do
+ local c = lshift(i, 24)
+ for _ = 1, 8 do
+ if band(c, 0x80000000) ~= 0 then
+ c = bxor(lshift(c, 1), 0x04C11DB7)
+ else
+ c = lshift(c, 1)
+ end
+ end
+ CT[i + 1] = c
+end
+Decode.crcTable = CT
+
+local MASK = table.create(33, 0)
+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 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 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 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 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)
+ for l = 0, MAXLEN do
+ COUNT[cbase + l + 1] = 0
+ end
+ local maxLen = 0
+ for s = 0, n - 1 do
+ local l = readu8(LENS, lbase + s)
+ COUNT[cbase + l + 1] += 1
+ if l > maxLen then
+ maxLen = l
+ end
+ end
+ MAXL[g + 1] = maxLen
+ -- canonical codes: by length, then symbol
+ local code, idx = 0, 0
+ for l = 1, MAXLEN do
+ FIRST[cbase + l + 1] = code
+ OFFS[cbase + l + 1] = idx
+ local c = COUNT[cbase + l + 1]
+ code += c
+ idx += c
+ if code > 2 ^ l then
+ return false
+ end
+ code *= 2
+ end
+ -- perm + lookup
+ local pbase = g * MAXALPHA
+ local tbase = g * PSIZE * 4
+ bfill(LOOK, tbase, 0, PSIZE * 4)
+ local next = table.create(MAXLEN + 1, 0)
+ for l = 1, MAXLEN do
+ next[l + 1] = OFFS[cbase + l + 1]
+ end
+ for s = 0, n - 1 do
+ local l = readu8(LENS, lbase + s)
+ local k = next[l + 1]
+ next[l + 1] = k + 1
+ PERM[pbase + k + 1] = s
+ if l <= PBITS then
+ local c = FIRST[cbase + l + 1] + (k - OFFS[cbase + l + 1])
+ local shift = PBITS - l
+ local from = lshift(c, shift)
+ local entry = s * 32 + l
+ for j = from, from + lshift(1, shift) - 1 do
+ writeu32(LOOK, tbase + j * 4, entry)
+ end
+ end
+ end
+ return true
+end
+
+local function grow(out: buffer, op: number, need: number): buffer
+ local nb = bcreate(math.max(blen(out) * 2, need, 65536))
+ bcopy(nb, 0, out, 0, op)
+ 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 bb, bc = 0, 0
+ local tt: buffer? = nil
+ local ttSize = 0
+ local streams = 0
+ local consumedEnd = o
+
+ while true do
+ -- stream header (byte aligned)
+ if streams > 0 then
+ if p + 4 > e or readu8(b, p) ~= 0x42 or readu8(b, p + 1) ~= 0x5A or readu8(b, p + 2) ~= 0x68 then
+ break -- trailing data after a stream is ignored, as bzip2 -d does
+ end
+ end
+ if p + 4 > e then
+ return nil, "truncated stream header", "truncated"
+ end
+ if readu8(b, p) ~= 0x42 or readu8(b, p + 1) ~= 0x5A or readu8(b, p + 2) ~= 0x68 then
+ return nil, "bad magic", "corrupt"
+ end
+ local level = readu8(b, p + 3) - 0x30
+ if level < 1 or level > 9 then
+ return nil, "bad block size", "corrupt"
+ end
+ local maxBlock = level * 100000
+ if ttSize < maxBlock then
+ tt = bcreate(maxBlock * 4)
+ ttSize = maxBlock
+ end
+ local T = tt :: buffer
+ p += 4
+ bb, bc = 0, 0
+ local combined = 0
+
+ while true do
+ -- 48-bit magic + 32-bit CRC
+ while bc <= 24 do
+ bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0)
+ p += 1
+ bc += 8
+ end
+ local m1 = band(rshift(bb, bc - 24), 0xFFFFFF)
+ bc -= 24
+ while bc <= 24 do
+ bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0)
+ p += 1
+ bc += 8
+ end
+ local m2 = band(rshift(bb, bc - 24), 0xFFFFFF)
+ bc -= 24
+ while bc <= 24 do
+ bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0)
+ p += 1
+ bc += 8
+ end
+ local c1 = band(rshift(bb, bc - 16), 0xFFFF)
+ bc -= 16
+ while bc <= 24 do
+ bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0)
+ p += 1
+ bc += 8
+ end
+ local storedCrc = band(rshift(bb, bc - 16), 0xFFFF) + c1 * 65536
+ bc -= 16
+ if (p - o) * 8 - bc > (e - o) * 8 then
+ return nil, "truncated block header", "truncated"
+ end
+ if m1 == 0x177245 and m2 == 0x385090 then
+ if storedCrc ~= combined then
+ return nil, string.format("stream CRC mismatch (%08x, expected %08x)", combined, storedCrc), "checksum"
+ end
+ -- align to the byte after the stream
+ p -= bc // 8
+ bb, bc = 0, 0
+ break
+ end
+ if m1 ~= 0x314159 or m2 ~= 0x265359 then
+ return nil, "bad block magic", "corrupt"
+ end
+
+ -- randomised bit, origPtr, symbol map
+ while bc <= 24 do
+ bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0)
+ p += 1
+ bc += 8
+ end
+ local rnd = band(rshift(bb, bc - 1), 1)
+ bc -= 1
+ while bc <= 24 do
+ bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0)
+ p += 1
+ bc += 8
+ end
+ local origPtr = band(rshift(bb, bc - 24), 0xFFFFFF)
+ bc -= 24
+ if rnd ~= 0 then
+ return nil, "randomised blocks (bzip2 0.9.0 and older) are not supported", "unsupported"
+ end
+ while bc <= 24 do
+ bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0)
+ p += 1
+ bc += 8
+ end
+ local used = band(rshift(bb, bc - 16), 0xFFFF)
+ bc -= 16
+ local nInUse = 0
+ for i = 0, 15 do
+ if band(used, lshift(1, 15 - i)) ~= 0 then
+ while bc <= 24 do
+ bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0)
+ p += 1
+ bc += 8
+ end
+ local bits = band(rshift(bb, bc - 16), 0xFFFF)
+ bc -= 16
+ for j = 0, 15 do
+ if band(bits, lshift(1, 15 - j)) ~= 0 then
+ SEQ[nInUse + 1] = i * 16 + j
+ nInUse += 1
+ end
+ end
+ end
+ end
+ if nInUse == 0 then
+ return nil, "no symbols in use", "corrupt"
+ end
+ local alphaSize = nInUse + 2
+
+ -- groups and selectors
+ while bc <= 24 do
+ bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0)
+ p += 1
+ bc += 8
+ end
+ local nGroups = band(rshift(bb, bc - 3), 7)
+ bc -= 3
+ local nSelectors = band(rshift(bb, bc - 15), 0x7FFF)
+ bc -= 15
+ if nGroups < 2 or nGroups > 6 then
+ return nil, "bad number of Huffman groups", "corrupt"
+ end
+ if nSelectors < 1 then
+ return nil, "no selectors", "corrupt"
+ end
+ local selectors = buffer.create(nSelectors)
+ local mtfg0, mtfg1, mtfg2, mtfg3, mtfg4, mtfg5 = 0, 1, 2, 3, 4, 5
+ for i = 0, nSelectors - 1 do
+ local j = 0
+ while true do
+ if bc <= 24 then
+ bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0)
+ p += 1
+ bc += 8
+ end
+ bc -= 1
+ if band(rshift(bb, bc), 1) == 0 then
+ break
+ end
+ j += 1
+ if j >= nGroups then
+ return nil, "bad selector", "corrupt"
+ end
+ end
+ -- move-to-front over the group list
+ local v
+ if j == 0 then
+ v = mtfg0
+ elseif j == 1 then
+ v = mtfg1
+ mtfg1 = mtfg0
+ elseif j == 2 then
+ v = mtfg2
+ mtfg2, mtfg1 = mtfg1, mtfg0
+ elseif j == 3 then
+ v = mtfg3
+ mtfg3, mtfg2, mtfg1 = mtfg2, mtfg1, mtfg0
+ elseif j == 4 then
+ v = mtfg4
+ mtfg4, mtfg3, mtfg2, mtfg1 = mtfg3, mtfg2, mtfg1, mtfg0
+ else
+ v = mtfg5
+ mtfg5, mtfg4, mtfg3, mtfg2, mtfg1 = mtfg4, mtfg3, mtfg2, mtfg1, mtfg0
+ end
+ mtfg0 = v
+ writeu8(selectors, i, v)
+ end
+ if (p - o) * 8 - bc > (e - o) * 8 then
+ return nil, "truncated selectors", "truncated"
+ end
+
+ -- code lengths (delta coded)
+ for g = 0, nGroups - 1 do
+ while bc <= 24 do
+ bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0)
+ p += 1
+ bc += 8
+ end
+ local len = band(rshift(bb, bc - 5), 31)
+ bc -= 5
+ for s = 0, alphaSize - 1 do
+ while true do
+ if len < 1 or len > MAXLEN then
+ return nil, "bad code length", "corrupt"
+ end
+ if bc <= 24 then
+ bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0)
+ p += 1
+ bc += 8
+ end
+ bc -= 1
+ if band(rshift(bb, bc), 1) == 0 then
+ break
+ end
+ bc -= 1
+ if band(rshift(bb, bc), 1) == 0 then
+ len += 1
+ else
+ len -= 1
+ end
+ end
+ writeu8(LENS, g * MAXALPHA + s, len)
+ end
+ if not buildGroup(g, alphaSize) then
+ return nil, "over-subscribed Huffman code", "corrupt"
+ end
+ end
+ if (p - o) * 8 - bc > (e - o) * 8 then
+ return nil, "truncated code lengths", "truncated"
+ end
+
+ -- MTF / RUNA / RUNB symbols -> T low bytes
+ for i = 0, 255 do
+ CFTAB[i + 1] = 0
+ MTF[i + 1] = i
+ end
+ local eob = alphaSize - 1
+ local nblock = 0
+ local selIdx = 0
+ local left = 0
+ local g = 0
+ local tbase, pbase, cbase, gmax = 0, 0, 0, 0
+ local runLen, runBit = 0, 1
+ while true do
+ if left == 0 then
+ if selIdx >= nSelectors then
+ return nil, "ran out of selectors", "corrupt"
+ end
+ g = readu8(selectors, selIdx)
+ selIdx += 1
+ left = 50
+ tbase = g * PSIZE * 4
+ pbase = g * MAXALPHA
+ cbase = g * (MAXLEN + 1)
+ gmax = MAXL[g + 1]
+ end
+ left -= 1
+ while bc <= 24 do
+ bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0)
+ p += 1
+ bc += 8
+ end
+ local ent = readu32(LOOK, tbase + band(rshift(bb, bc - PBITS), PSIZE - 1) * 4)
+ local sym
+ if ent ~= 0 then
+ 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
+ local c = rshift(v, gmax - l)
+ local f = FIRST[cbase + l + 1]
+ local k = c - f
+ if k >= 0 and k < COUNT[cbase + l + 1] then
+ sym = PERM[pbase + OFFS[cbase + l + 1] + k + 1]
+ bc -= l
+ break
+ end
+ end
+ if sym < 0 then
+ return nil, "bad Huffman code", "corrupt"
+ end
+ end
+ if sym <= 1 then
+ -- RUNA / RUNB: bijective base-2 run length of the front symbol
+ runLen += runBit * (sym + 1)
+ runBit *= 2
+ if runLen > maxBlock then
+ return nil, "run past the block size", "corrupt"
+ end
+ else
+ if runLen > 0 then
+ if nblock + runLen > maxBlock then
+ return nil, "block larger than its declared size", "corrupt"
+ end
+ local ch = SEQ[MTF[1] + 1]
+ CFTAB[ch + 1] += runLen
+ for k = nblock, nblock + runLen - 1 do
+ writeu32(T, k * 4, ch)
+ end
+ nblock += runLen
+ runLen, runBit = 0, 1
+ end
+ if sym == eob then
+ break
+ end
+ local idx = sym - 1
+ if idx >= nInUse then
+ return nil, "bad MTF index", "corrupt"
+ end
+ if nblock >= maxBlock then
+ return nil, "block larger than its declared size", "corrupt"
+ end
+ local v = MTF[idx + 1]
+ for k = idx, 1, -1 do
+ MTF[k + 1] = MTF[k]
+ end
+ MTF[1] = v
+ local ch = SEQ[v + 1]
+ CFTAB[ch + 1] += 1
+ writeu32(T, nblock * 4, ch)
+ nblock += 1
+ end
+ if (p - o) * 8 - bc > (e - o) * 8 then
+ return nil, "truncated block data", "truncated"
+ end
+ end
+ if origPtr >= nblock then
+ 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]
+ CFTAB[i + 1] = sum
+ sum += c
+ end
+ for i = 0, nblock - 1 do
+ local ch = band(readu32(T, i * 4), 255)
+ local k = CFTAB[ch + 1]
+ CFTAB[ch + 1] = k + 1
+ 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
+ local cap = blen(out)
+ local crc = 0xFFFFFFFF
+ local tPos = rshift(readu32(T, origPtr * 4), 8)
+ local last, run = -1, 0
+ local i = 0
+ while i < nblock do
+ local v = readu32(T, tPos * 4)
+ local ch = band(v, 255)
+ tPos = rshift(v, 8)
+ i += 1
+ if run == 4 then
+ -- ch is a repeat count for the previous byte
+ if ch > 0 then
+ if op + ch > maxBytes then
+ return nil, "output larger than maxBytes", "limit"
+ end
+ if op + ch + 256 > cap then
+ out = grow(out, op, op + ch + nblock - i + 4096)
+ cap = blen(out)
+ end
+ bfill(out, op, last, ch)
+ op += ch
+ for _ = 1, ch do
+ crc = bxor(lshift(crc, 8), CT[bxor(rshift(crc, 24), last) + 1])
+ end
+ end
+ run = 0
+ last = -1
+ else
+ if ch == last then
+ run += 1
+ else
+ run = 1
+ last = ch
+ end
+ if op + 256 > cap then
+ if op >= maxBytes then
+ return nil, "output larger than maxBytes", "limit"
+ end
+ out = grow(out, op, op + nblock - i + 4096)
+ cap = blen(out)
+ end
+ writeu8(out, op, ch)
+ op += 1
+ crc = bxor(lshift(crc, 8), CT[bxor(rshift(crc, 24), ch) + 1])
+ end
+ end
+ if op > maxBytes then
+ return nil, "output larger than maxBytes", "limit"
+ end
+ crc = bxor(crc, 0xFFFFFFFF)
+ if crc ~= storedCrc then
+ return nil, string.format("block CRC mismatch (%08x, expected %08x)", crc, storedCrc), "checksum"
+ end
+ combined = bxor(bor(lshift(combined, 1), rshift(combined, 31)), crc)
+ end
+ streams += 1
+ consumedEnd = p
+ if p >= e then
+ break
+ end
+ end
+ return out, op, consumedEnd
+end
+
+return Decode
diff --git a/src/Formats/codecs/Bzip2/init.luau b/src/Formats/codecs/Bzip2/init.luau
new file mode 100644
index 0000000..e492aee
--- /dev/null
+++ b/src/Formats/codecs/Bzip2/init.luau
@@ -0,0 +1,77 @@
+--!strict
+-- codecs/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("@formats/codecs/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).
+local Err = require("@formats/core/Err")
+local Decode = require("@formats/codecs/Bzip2/Decode")
+
+local Bzip2 = {}
+
+export type Options = {
+ maxBytes: number?, -- refuse output larger than this (default 2^30)
+}
+
+local KINDS = {
+ truncated = Err.TRUNCATED,
+ corrupt = Err.CORRUPT,
+ checksum = Err.CHECKSUM,
+ limit = Err.LIMIT,
+ unsupported = Err.UNSUPPORTED,
+}
+
+-- 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: buffer
+ if type(buf) == "string" then
+ b = buffer.fromstring(buf)
+ elseif type(buf) == "buffer" then
+ b = buf
+ else
+ return nil, Err.new(Err.ARG, "Bzip2.decompress: expected a buffer or a string, got " .. typeof(buf))
+ end
+ local n = buffer.len(b)
+ local o = offset or 0
+ if type(o) ~= "number" or o < 0 or o > n or o % 1 ~= 0 then
+ return nil, Err.new(Err.ARG, "Bzip2.decompress: bad offset " .. tostring(offset))
+ end
+ local l = length or (n - o)
+ if type(l) ~= "number" or l < 0 or l % 1 ~= 0 then
+ return nil, Err.new(Err.ARG, "Bzip2.decompress: bad length " .. tostring(length))
+ end
+ l = math.min(l, n - o)
+ local maxBytes = if opts and opts.maxBytes ~= nil then opts.maxBytes else 2 ^ 30
+ if type(maxBytes) ~= "number" or maxBytes < 0 then
+ return nil, Err.new(Err.ARG, "Bzip2.decompress: bad maxBytes")
+ end
+ local out, nOut, consumed = Decode.decode(b, o, o + l, maxBytes)
+ if not out then
+ return nil, Err.new(KINDS[consumed] or Err.CORRUPT, "bzip2: " .. tostring(nOut), o)
+ end
+ local res = out
+ if buffer.len(out) ~= nOut then
+ res = buffer.create(nOut)
+ buffer.copy(res, 0, out, 0, nOut)
+ end
+ 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
+ local e = o + (length or (buffer.len(buf) - o))
+ local c = 0xFFFFFFFF
+ for i = o, e - 1 do
+ c = bit32.bxor(bit32.lshift(c, 8), CT[bit32.bxor(bit32.rshift(c, 24), buffer.readu8(buf, i)) + 1])
+ end
+ return bit32.bxor(c, 0xFFFFFFFF)
+end
+
+return Bzip2
diff --git a/src/Formats/codecs/Cff/init.luau b/src/Formats/codecs/Cff/init.luau
new file mode 100644
index 0000000..bdec1dc
--- /dev/null
+++ b/src/Formats/codecs/Cff/init.luau
@@ -0,0 +1,657 @@
+--!strict
+-- codecs/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.
+local Cff = {}
+
+local readu8 = buffer.readu8
+local blen = buffer.len
+
+local function u8(b: buffer, o: number): number
+ if o < 0 or o + 1 > blen(b) then
+ return 0
+ end
+ return readu8(b, o)
+end
+local function uN(b: buffer, o: number, n: number): number
+ local v = 0
+ for i = 0, n - 1 do
+ v = v * 256 + u8(b, o + i)
+ end
+ return v
+end
+
+export type Index = { count: number, offSize: number, offsets: number, data: number, next: number }
+export type Font = {
+ buf: buffer,
+ base: number,
+ 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
+ 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
+ end
+ local count = uN(b, p, 2)
+ if count == 0 then
+ return { count = 0, offSize = 1, offsets = p + 2, data = p + 2, next = p + 2 }
+ end
+ local offSize = u8(b, p + 2)
+ if offSize < 1 or offSize > 4 then
+ return nil
+ end
+ local offsets = p + 3
+ local data = offsets + (count + 1) * offSize - 1 -- offsets are 1-based
+ if data + 1 > limit then
+ return nil
+ end
+ local last = uN(b, offsets + count * offSize, offSize)
+ if data + last > limit then
+ return nil
+ end
+ 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
+ end
+ local s = uN(b, idx.offsets + i * idx.offSize, idx.offSize)
+ local e = uN(b, idx.offsets + (i + 1) * idx.offSize, idx.offSize)
+ if s < 1 or e < s or idx.data + e > idx.next then
+ return nil, 0
+ end
+ return idx.data + s, e - s
+end
+Cff.item = item
+
+-- DICT at [p, p + n) -> { [op] = { operands } } (two-byte ops are 1200 + second byte)
+local function dict(b: buffer, p: number, n: number): { [number]: { number } }
+ local out: { [number]: { number } } = {}
+ local ops: { number } = {}
+ local e = p + n
+ while p < e do
+ local b0 = u8(b, p)
+ if b0 <= 21 then
+ local op = b0
+ p += 1
+ if b0 == 12 then
+ op = 1200 + u8(b, p)
+ p += 1
+ end
+ out[op] = ops
+ ops = {}
+ elseif b0 == 28 then
+ local v = uN(b, p + 1, 2)
+ table.insert(ops, if v >= 32768 then v - 65536 else v)
+ p += 3
+ elseif b0 == 29 then
+ local v = uN(b, p + 1, 4)
+ table.insert(ops, if v >= 2147483648 then v - 4294967296 else v)
+ p += 5
+ elseif b0 == 30 then -- real number: BCD nibbles
+ local s = {}
+ p += 1
+ local done = false
+ while p < e and not done do
+ local byte = u8(b, p)
+ p += 1
+ for _, nib in { byte // 16, byte % 16 } do
+ if nib <= 9 then
+ table.insert(s, tostring(nib))
+ elseif nib == 10 then
+ table.insert(s, ".")
+ elseif nib == 11 then
+ table.insert(s, "E")
+ elseif nib == 12 then
+ table.insert(s, "E-")
+ elseif nib == 14 then
+ table.insert(s, "-")
+ elseif nib == 15 then
+ done = true
+ break
+ end
+ end
+ end
+ table.insert(ops, tonumber(table.concat(s)) or 0)
+ elseif b0 >= 32 and b0 <= 246 then
+ table.insert(ops, b0 - 139)
+ p += 1
+ elseif b0 >= 247 and b0 <= 250 then
+ table.insert(ops, (b0 - 247) * 256 + u8(b, p + 1) + 108)
+ p += 2
+ elseif b0 >= 251 and b0 <= 254 then
+ table.insert(ops, -(b0 - 251) * 256 - u8(b, p + 1) - 108)
+ p += 2
+ else
+ p += 1 -- reserved
+ end
+ if #ops > 48 then
+ return out
+ end
+ end
+ return out
+end
+
+local function privateSubrs(b: buffer, base: number, limit: number, d: { [number]: { number } }): Index?
+ local pr = d[18]
+ if not pr or #pr < 2 then
+ return nil
+ end
+ local size, off = pr[1], pr[2]
+ local ps = base + off
+ if size < 0 or off < 0 or ps + size > limit then
+ return nil
+ end
+ local pd = dict(b, ps, size)
+ local s = pd[19]
+ if not s or #s < 1 then
+ return nil
+ end
+ 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
+ return nil, "truncated CFF header"
+ end
+ local major, hdrSize = u8(b, base), u8(b, base + 2)
+ if major == 2 then
+ return nil, "unsupported: CFF2 (variable font outlines)"
+ end
+ if major ~= 1 then
+ return nil, "bad CFF version " .. major
+ end
+ local names = index(b, base + hdrSize, limit)
+ if not names then
+ return nil, "bad name INDEX"
+ end
+ local tops = index(b, names.next, limit)
+ if not tops or tops.count < 1 then
+ return nil, "bad Top DICT INDEX"
+ end
+ local strings = index(b, tops.next, limit)
+ if not strings then
+ return nil, "bad String INDEX"
+ end
+ local gsubrs = index(b, strings.next, limit)
+ if not gsubrs then
+ return nil, "bad global subrs INDEX"
+ end
+ local ts, tl = item(b, tops, 0)
+ if not ts then
+ return nil, "bad Top DICT"
+ end
+ local top = dict(b, ts, tl)
+ local cso = top[17]
+ if not cso or #cso < 1 then
+ return nil, "no CharStrings"
+ end
+ local cst = top[1206]
+ if cst and cst[1] ~= 2 then
+ return nil, "unsupported: charstring type " .. tostring(cst[1])
+ end
+ local charStrings = index(b, base + cso[1], limit)
+ if not charStrings then
+ return nil, "bad CharStrings INDEX"
+ end
+ local f: Font = {
+ buf = b,
+ base = base,
+ limit = limit,
+ charStrings = charStrings,
+ gsubrs = gsubrs,
+ subrs = nil,
+ fdSubrs = nil,
+ fdSelect = nil,
+ numGlyphs = charStrings.count,
+ cid = top[1230] ~= nil,
+ fontMatrix = top[1207],
+ }
+ if f.cid then
+ local fda, fds = top[1236], top[1237]
+ if not fda or not fds then
+ return nil, "CID font without FDArray / FDSelect"
+ end
+ local fdArray = index(b, base + fda[1], limit)
+ if not fdArray then
+ return nil, "bad FDArray"
+ end
+ local list: { Index? } = {}
+ for i = 0, math.min(fdArray.count, 256) - 1 do
+ local s, l = item(b, fdArray, i)
+ list[i + 1] = if s then privateSubrs(b, base, limit, dict(b, s, l)) else nil
+ end
+ f.fdSubrs = list
+ f.fdSelect = base + fds[1]
+ else
+ f.subrs = privateSubrs(b, base, limit, top)
+ end
+ return f, nil
+end
+
+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
+ end
+ local b, p = f.buf, f.fdSelect :: number
+ local fmt = u8(b, p)
+ local fd = -1
+ if fmt == 0 then
+ fd = u8(b, p + 1 + g)
+ elseif fmt == 3 then
+ local n = uN(b, p + 1, 2)
+ local first = uN(b, p + 3, 2)
+ for i = 0, n - 1 do
+ local q = p + 5 + i * 3
+ local v = u8(b, q)
+ local nxt = uN(b, q + 1, 2)
+ if g >= first and g < nxt then
+ fd = v
+ break
+ end
+ first = nxt
+ end
+ end
+ local list = f.fdSubrs :: { Index? }
+ return list[fd + 1]
+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)
+ if not p then
+ return nil, "bad glyph index " .. tostring(g)
+ end
+ local e = p + len
+ local cmds: { any } = {}
+ local s: { number } = table.create(48, 0) -- operand stack, 1-based; sp = count
+ local sp = 0
+ local trans: { number } = table.create(32, 0)
+ local x, y = 0, 0
+ local open = false
+ local maskbits = 0
+ local inHeader = true
+ local stack: { { number } } = {} -- return addresses { p, e }
+ local subrs: Index? = nil
+ local haveSubrs = false
+ local ops = 0
+ local seed = 12345
+
+ local function moveTo(dx: number, dy: number)
+ if open then
+ table.insert(cmds, { op = "close" })
+ end
+ x += dx
+ y += dy
+ table.insert(cmds, { op = "moveTo", x, y })
+ open = true
+ end
+ local function lineTo(dx: number, dy: number)
+ if not open then
+ moveTo(0, 0)
+ end
+ x += dx
+ y += dy
+ table.insert(cmds, { op = "lineTo", x, y })
+ end
+ local function curveTo(dx1: number, dy1: number, dx2: number, dy2: number, dx3: number, dy3: number)
+ if not open then
+ moveTo(0, 0)
+ end
+ local x1, y1 = x + dx1, y + dy1
+ local x2, y2 = x1 + dx2, y1 + dy2
+ 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
+ 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]
+ continue
+ end
+ break
+ end
+ ops += 1
+ if ops > BUDGET then
+ return nil, "charstring too long (subroutine loop?)"
+ end
+ local b0 = u8(b, p)
+ p += 1
+ local clear = true
+ local i = 0
+ if b0 == 19 or b0 == 20 then -- hintmask, cntrmask
+ if inHeader then
+ maskbits += sp // 2
+ end
+ inHeader = false
+ p += (maskbits + 7) // 8
+ elseif b0 == 1 or b0 == 3 or b0 == 18 or b0 == 23 then -- hstem vstem hstemhm vstemhm
+ maskbits += sp // 2
+ elseif b0 == 21 then -- rmoveto
+ inHeader = false
+ if sp < 2 then
+ return nil, "rmoveto stack"
+ end
+ moveTo(S(sp - 2), S(sp - 1))
+ elseif b0 == 4 then -- vmoveto
+ inHeader = false
+ if sp < 1 then
+ return nil, "vmoveto stack"
+ end
+ moveTo(0, S(sp - 1))
+ elseif b0 == 22 then -- hmoveto
+ inHeader = false
+ if sp < 1 then
+ return nil, "hmoveto stack"
+ end
+ moveTo(S(sp - 1), 0)
+ elseif b0 == 5 then -- rlineto
+ if sp < 2 then
+ return nil, "rlineto stack"
+ end
+ while i + 1 < sp do
+ lineTo(S(i), S(i + 1))
+ i += 2
+ end
+ elseif b0 == 6 or b0 == 7 then -- hlineto / vlineto: alternate
+ if sp < 1 then
+ return nil, "hlineto stack"
+ end
+ local horiz = b0 == 6
+ while i < sp do
+ if horiz then
+ lineTo(S(i), 0)
+ else
+ lineTo(0, S(i))
+ end
+ horiz = not horiz
+ i += 1
+ end
+ elseif b0 == 31 or b0 == 30 then -- hvcurveto / vhcurveto: alternate
+ if sp < 4 then
+ return nil, "hvcurveto stack"
+ end
+ local horiz = b0 == 31
+ while i + 3 < sp do
+ local last = if sp - i == 5 then S(i + 4) else 0
+ if horiz then
+ curveTo(S(i), 0, S(i + 1), S(i + 2), last, S(i + 3))
+ else
+ curveTo(0, S(i), S(i + 1), S(i + 2), S(i + 3), last)
+ end
+ horiz = not horiz
+ i += 4
+ end
+ elseif b0 == 8 then -- rrcurveto
+ if sp < 6 then
+ return nil, "rrcurveto stack"
+ end
+ while i + 5 < sp do
+ curveTo(S(i), S(i + 1), S(i + 2), S(i + 3), S(i + 4), S(i + 5))
+ i += 6
+ end
+ elseif b0 == 24 then -- rcurveline
+ if sp < 8 then
+ return nil, "rcurveline stack"
+ end
+ while i + 5 < sp - 2 do
+ curveTo(S(i), S(i + 1), S(i + 2), S(i + 3), S(i + 4), S(i + 5))
+ i += 6
+ end
+ lineTo(S(i), S(i + 1))
+ elseif b0 == 25 then -- rlinecurve
+ if sp < 8 then
+ return nil, "rlinecurve stack"
+ end
+ while i + 1 < sp - 6 do
+ lineTo(S(i), S(i + 1))
+ i += 2
+ end
+ curveTo(S(i), S(i + 1), S(i + 2), S(i + 3), S(i + 4), S(i + 5))
+ elseif b0 == 26 or b0 == 27 then -- vvcurveto / hhcurveto
+ if sp < 4 then
+ return nil, "vv/hhcurveto stack"
+ end
+ local f0 = 0
+ if sp % 2 == 1 then
+ f0 = S(0)
+ i = 1
+ end
+ while i + 3 < sp do
+ if b0 == 27 then
+ curveTo(S(i), f0, S(i + 1), S(i + 2), S(i + 3), 0)
+ else
+ curveTo(f0, S(i), S(i + 1), S(i + 2), 0, S(i + 3))
+ end
+ f0 = 0
+ i += 4
+ end
+ elseif b0 == 10 or b0 == 29 then -- callsubr / callgsubr
+ if b0 == 10 and not haveSubrs then
+ subrs = localSubrs(f, g)
+ haveSubrs = true
+ end
+ if sp < 1 then
+ return nil, "callsubr stack"
+ end
+ local idx = if b0 == 10 then subrs else f.gsubrs
+ if not idx then
+ return nil, "no subroutines"
+ end
+ local n = math.floor(S(sp - 1)) + bias(idx.count)
+ sp -= 1
+ if #stack >= 10 then
+ return nil, "subroutine recursion limit"
+ end
+ local sp0, sl = item(b, idx, n)
+ if not sp0 then
+ return nil, "subroutine " .. n .. " not found"
+ end
+ table.insert(stack, { p, e })
+ p, e = sp0, sp0 + sl
+ clear = false
+ elseif b0 == 11 then -- return
+ if #stack == 0 then
+ return nil, "return outside a subroutine"
+ end
+ local r = table.remove(stack) :: { number }
+ p, e = r[1], r[2]
+ clear = false
+ elseif b0 == 14 then -- endchar
+ if open then
+ table.insert(cmds, { op = "close" })
+ end
+ return cmds, nil
+ elseif b0 == 12 then -- escape
+ local b1 = u8(b, p)
+ p += 1
+ if b1 == 34 then -- hflex
+ if sp < 7 then
+ return nil, "hflex stack"
+ end
+ curveTo(S(0), 0, S(1), S(2), S(3), 0)
+ curveTo(S(4), 0, S(5), -S(2), S(6), 0)
+ elseif b1 == 35 then -- flex
+ if sp < 13 then
+ return nil, "flex stack"
+ end
+ curveTo(S(0), S(1), S(2), S(3), S(4), S(5))
+ curveTo(S(6), S(7), S(8), S(9), S(10), S(11))
+ elseif b1 == 36 then -- hflex1
+ if sp < 9 then
+ return nil, "hflex1 stack"
+ end
+ curveTo(S(0), S(1), S(2), S(3), S(4), 0)
+ curveTo(S(5), 0, S(6), S(7), S(8), -(S(1) + S(3) + S(7)))
+ elseif b1 == 37 then -- flex1
+ if sp < 11 then
+ return nil, "flex1 stack"
+ end
+ local dx = S(0) + S(2) + S(4) + S(6) + S(8)
+ local dy = S(1) + S(3) + S(5) + S(7) + S(9)
+ local dx6, dy6 = S(10), S(10)
+ if math.abs(dx) > math.abs(dy) then
+ dy6 = -dy
+ else
+ dx6 = -dx
+ end
+ 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
+ end
+ if b1 == 3 then
+ set(2, if a ~= 0 and c ~= 0 then 1 else 0) -- and
+ elseif b1 == 4 then
+ set(2, if a ~= 0 or c ~= 0 then 1 else 0) -- or
+ elseif b1 == 5 then
+ set(1, if c == 0 then 1 else 0) -- not
+ elseif b1 == 9 then
+ set(1, math.abs(c))
+ elseif b1 == 10 then
+ set(2, a + c)
+ elseif b1 == 11 then
+ set(2, a - c)
+ elseif b1 == 12 then
+ set(2, if c ~= 0 then a / c else 0)
+ elseif b1 == 14 then
+ set(1, -c)
+ elseif b1 == 15 then
+ set(2, if a == c then 1 else 0)
+ elseif b1 == 18 then
+ sp = math.max(0, sp - 1) -- drop
+ elseif b1 == 20 then -- put: val i
+ local k = math.floor(c)
+ if k >= 0 and k < 32 then
+ trans[k + 1] = a
+ end
+ sp = math.max(0, sp - 2)
+ elseif b1 == 21 then -- get
+ local k = math.floor(c)
+ set(1, if k >= 0 and k < 32 then trans[k + 1] else 0)
+ elseif b1 == 22 then -- ifelse: s1 s2 v1 v2 -> v1 <= v2 ? s1 : s2
+ local s1, s2, v1, v2 = S(top - 4), S(top - 3), S(top - 2), S(top - 1)
+ set(4, if v1 <= v2 then s1 else s2)
+ elseif b1 == 23 then -- random (deterministic)
+ seed = (seed * 1103515245 + 12345) % 2147483648
+ set(0, (seed % 65535 + 1) / 65536)
+ elseif b1 == 24 then
+ set(2, a * c)
+ elseif b1 == 26 then
+ set(1, math.sqrt(math.max(0, c)))
+ elseif b1 == 27 then
+ set(0, c) -- dup
+ elseif b1 == 28 then -- exch
+ if sp >= 2 then
+ s[sp - 1], s[sp] = s[sp], s[sp - 1]
+ end
+ elseif b1 == 29 then -- index
+ local k = math.floor(c)
+ local v = if k < 0 then S(top - 2) else S(top - 2 - k)
+ set(1, v)
+ elseif b1 == 30 then -- roll: n j
+ local n, j = math.floor(a), math.floor(c)
+ sp = math.max(0, sp - 2)
+ if n > 0 and n <= sp then
+ local base = sp - n
+ local tmp = table.create(n, 0)
+ for k = 0, n - 1 do
+ tmp[((k + j) % n) + 1] = s[base + k + 1]
+ end
+ for k = 0, n - 1 do
+ s[base + k + 1] = tmp[k + 1]
+ end
+ end
+ else
+ return nil, "unknown operator 12 " .. b1
+ end
+ if sp > 48 then
+ return nil, "stack overflow"
+ end
+ end
+ elseif b0 >= 32 or b0 == 28 then -- operands
+ local v
+ if b0 == 28 then
+ v = uN(b, p, 2)
+ if v >= 32768 then
+ v -= 65536
+ end
+ p += 2
+ elseif b0 <= 246 then
+ v = b0 - 139
+ elseif b0 <= 250 then
+ v = (b0 - 247) * 256 + u8(b, p) + 108
+ p += 1
+ elseif b0 <= 254 then
+ v = -(b0 - 251) * 256 - u8(b, p) - 108
+ p += 1
+ else -- 255: 16.16 fixed
+ v = uN(b, p, 4)
+ if v >= 2147483648 then
+ v -= 4294967296
+ end
+ v /= 65536
+ p += 4
+ end
+ if sp >= 48 then
+ return nil, "operand stack overflow"
+ end
+ sp += 1
+ s[sp] = v
+ clear = false
+ else
+ return nil, "reserved operator " .. b0
+ end
+ if clear then
+ sp = 0
+ end
+ end
+ return nil, "no endchar"
+end
+
+return Cff
diff --git a/src/Formats/codecs/Dct/init.luau b/src/Formats/codecs/Dct/init.luau
new file mode 100644
index 0000000..c46923c
--- /dev/null
+++ b/src/Formats/codecs/Dct/init.luau
@@ -0,0 +1,392 @@
+--!strict
+--!native
+--!optimize 2
+-- codecs/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
+local readi16, readu16, writeu16, readu8, writei16 = buffer.readi16, buffer.readu16, buffer.writeu16, buffer.readu8, buffer.writei16
+local clamp = math.clamp
+
+local Dct = {}
+
+local ws = table.create(64, 0)
+
+local function idct8(coef: buffer, off: number, q: buffer, plane: buffer, out: number, stride: number, p1: number, center: number, maxv: number)
+ local s1 = 2 ^ (13 - p1)
+ local h1 = s1 / 2
+ local s2 = 2 ^ (16 + p1)
+ local h2 = s2 / 2 + center * s2
+ local dcm = 2 ^ p1
+ for c = 0, 7 do
+ local o = off + c * 2
+ local qo = c * 2
+ local c1, c2, c3 = readi16(coef, o + 16), readi16(coef, o + 32), readi16(coef, o + 48)
+ local c4, c5, c6, c7 = readi16(coef, o + 64), readi16(coef, o + 80), readi16(coef, o + 96), readi16(coef, o + 112)
+ if c1 == 0 and c2 == 0 and c3 == 0 and c4 == 0 and c5 == 0 and c6 == 0 and c7 == 0 then
+ local dc = readi16(coef, o) * readu16(q, qo) * dcm
+ ws[c + 1] = dc
+ ws[c + 9] = dc
+ ws[c + 17] = dc
+ ws[c + 25] = dc
+ ws[c + 33] = dc
+ ws[c + 41] = dc
+ ws[c + 49] = dc
+ ws[c + 57] = dc
+ else
+ -- even part
+ local z2 = c2 * readu16(q, qo + 32)
+ local z3 = c6 * readu16(q, qo + 96)
+ local z1 = (z2 + z3) * 4433
+ local tmp2 = z1 - z3 * 15137
+ local tmp3 = z1 + z2 * 6270
+ z2 = readi16(coef, o) * readu16(q, qo)
+ z3 = c4 * readu16(q, qo + 64)
+ local tmp0 = (z2 + z3) * 8192
+ local tmp1 = (z2 - z3) * 8192
+ local tmp10, tmp13 = tmp0 + tmp3, tmp0 - tmp3
+ local tmp11, tmp12 = tmp1 + tmp2, tmp1 - tmp2
+ -- odd part
+ local t0 = c7 * readu16(q, qo + 112)
+ local t1 = c5 * readu16(q, qo + 80)
+ local t2 = c3 * readu16(q, qo + 48)
+ local t3 = c1 * readu16(q, qo + 16)
+ z1 = t0 + t3
+ z2 = t1 + t2
+ z3 = t0 + t2
+ local z4 = t1 + t3
+ local z5 = (z3 + z4) * 9633
+ t0 *= 2446
+ t1 *= 16819
+ t2 *= 25172
+ t3 *= 12299
+ z1 *= -7373
+ z2 *= -20995
+ z3 = z3 * -16069 + z5
+ z4 = z4 * -3196 + z5
+ t0 += z1 + z3
+ t1 += z2 + z4
+ t2 += z2 + z3
+ t3 += z1 + z4
+ ws[c + 1] = (tmp10 + t3 + h1) // s1
+ ws[c + 57] = (tmp10 - t3 + h1) // s1
+ ws[c + 9] = (tmp11 + t2 + h1) // s1
+ ws[c + 49] = (tmp11 - t2 + h1) // s1
+ ws[c + 17] = (tmp12 + t1 + h1) // s1
+ ws[c + 41] = (tmp12 - t1 + h1) // s1
+ ws[c + 25] = (tmp13 + t0 + h1) // s1
+ ws[c + 33] = (tmp13 - t0 + h1) // s1
+ end
+ end
+ local sd = 2 ^ (p1 + 3)
+ local hd = sd / 2 + center * sd
+ for r = 0, 7 do
+ local b = r * 8
+ local w0, w1, w2, w3 = ws[b + 1], ws[b + 2], ws[b + 3], ws[b + 4]
+ local w4, w5, w6, w7 = ws[b + 5], ws[b + 6], ws[b + 7], ws[b + 8]
+ local o = (out + r * stride) * 2
+ if w1 == 0 and w2 == 0 and w3 == 0 and w4 == 0 and w5 == 0 and w6 == 0 and w7 == 0 then
+ local v = clamp((w0 + hd) // sd, 0, maxv)
+ for i = 0, 14, 2 do
+ writeu16(plane, o + i, v)
+ end
+ else
+ local z1 = (w2 + w6) * 4433
+ local tmp2 = z1 - w6 * 15137
+ local tmp3 = z1 + w2 * 6270
+ local tmp0 = (w0 + w4) * 8192
+ local tmp1 = (w0 - w4) * 8192
+ local tmp10, tmp13 = tmp0 + tmp3, tmp0 - tmp3
+ local tmp11, tmp12 = tmp1 + tmp2, tmp1 - tmp2
+ local t0, t1, t2, t3 = w7, w5, w3, w1
+ z1 = t0 + t3
+ local z2 = t1 + t2
+ local z3 = t0 + t2
+ local z4 = t1 + t3
+ local z5 = (z3 + z4) * 9633
+ t0 *= 2446
+ t1 *= 16819
+ t2 *= 25172
+ t3 *= 12299
+ z1 *= -7373
+ z2 *= -20995
+ z3 = z3 * -16069 + z5
+ z4 = z4 * -3196 + z5
+ t0 += z1 + z3
+ t1 += z2 + z4
+ t2 += z2 + z3
+ t3 += z1 + z4
+ writeu16(plane, o, clamp((tmp10 + t3 + h2) // s2, 0, maxv))
+ writeu16(plane, o + 14, clamp((tmp10 - t3 + h2) // s2, 0, maxv))
+ writeu16(plane, o + 2, clamp((tmp11 + t2 + h2) // s2, 0, maxv))
+ writeu16(plane, o + 12, clamp((tmp11 - t2 + h2) // s2, 0, maxv))
+ writeu16(plane, o + 4, clamp((tmp12 + t1 + h2) // s2, 0, maxv))
+ writeu16(plane, o + 10, clamp((tmp12 - t1 + h2) // s2, 0, maxv))
+ writeu16(plane, o + 6, clamp((tmp13 + t0 + h2) // s2, 0, maxv))
+ writeu16(plane, o + 8, clamp((tmp13 - t0 + h2) // s2, 0, maxv))
+ end
+ end
+end
+
+local function idct4(coef: buffer, off: number, q: buffer, plane: buffer, out: number, stride: number, p1: number, center: number, maxv: number)
+ local s1 = 2 ^ (14 - p1)
+ local h1 = s1 / 2
+ local dcm = 2 ^ p1
+ for c = 0, 7 do
+ if c ~= 4 then
+ local o = off + c * 2
+ local qo = c * 2
+ local c1, c2, c3 = readi16(coef, o + 16), readi16(coef, o + 32), readi16(coef, o + 48)
+ local c5, c6, c7 = readi16(coef, o + 80), readi16(coef, o + 96), readi16(coef, o + 112)
+ if c1 == 0 and c2 == 0 and c3 == 0 and c5 == 0 and c6 == 0 and c7 == 0 then
+ local dc = readi16(coef, o) * readu16(q, qo) * dcm
+ ws[c + 1] = dc
+ ws[c + 9] = dc
+ ws[c + 17] = dc
+ ws[c + 25] = dc
+ else
+ local tmp0 = readi16(coef, o) * readu16(q, qo) * 16384
+ local tmp2 = c2 * readu16(q, qo + 32) * 15137 - c6 * readu16(q, qo + 96) * 6270
+ local tmp10, tmp12 = tmp0 + tmp2, tmp0 - tmp2
+ local z1 = c7 * readu16(q, qo + 112)
+ local z2 = c5 * readu16(q, qo + 80)
+ local z3 = c3 * readu16(q, qo + 48)
+ local z4 = c1 * readu16(q, qo + 16)
+ tmp0 = z1 * -1730 + z2 * 11893 + z3 * -17799 + z4 * 8697
+ tmp2 = z1 * -4176 + z2 * -4926 + z3 * 7373 + z4 * 20995
+ ws[c + 1] = (tmp10 + tmp2 + h1) // s1
+ ws[c + 25] = (tmp10 - tmp2 + h1) // s1
+ ws[c + 9] = (tmp12 + tmp0 + h1) // s1
+ ws[c + 17] = (tmp12 - tmp0 + h1) // s1
+ end
+ end
+ end
+ local s2 = 2 ^ (17 + p1)
+ local h2 = s2 / 2 + center * s2
+ local sd = 2 ^ (p1 + 3)
+ local hd = sd / 2 + center * sd
+ for r = 0, 3 do
+ local b = r * 8
+ local w0, w1, w2, w3 = ws[b + 1], ws[b + 2], ws[b + 3], ws[b + 4]
+ local w5, w6, w7 = ws[b + 6], ws[b + 7], ws[b + 8]
+ local o = (out + r * stride) * 2
+ if w1 == 0 and w2 == 0 and w3 == 0 and w5 == 0 and w6 == 0 and w7 == 0 then
+ local v = clamp((w0 + hd) // sd, 0, maxv)
+ writeu16(plane, o, v)
+ writeu16(plane, o + 2, v)
+ writeu16(plane, o + 4, v)
+ writeu16(plane, o + 6, v)
+ else
+ local tmp0 = w0 * 16384
+ local tmp2 = w2 * 15137 - w6 * 6270
+ local tmp10, tmp12 = tmp0 + tmp2, tmp0 - tmp2
+ tmp0 = w7 * -1730 + w5 * 11893 + w3 * -17799 + w1 * 8697
+ tmp2 = w7 * -4176 + w5 * -4926 + w3 * 7373 + w1 * 20995
+ writeu16(plane, o, clamp((tmp10 + tmp2 + h2) // s2, 0, maxv))
+ writeu16(plane, o + 6, clamp((tmp10 - tmp2 + h2) // s2, 0, maxv))
+ writeu16(plane, o + 2, clamp((tmp12 + tmp0 + h2) // s2, 0, maxv))
+ writeu16(plane, o + 4, clamp((tmp12 - tmp0 + h2) // s2, 0, maxv))
+ end
+ end
+end
+
+local function idct2(coef: buffer, off: number, q: buffer, plane: buffer, out: number, stride: number, p1: number, center: number, maxv: number)
+ local s1 = 2 ^ (15 - p1)
+ local h1 = s1 / 2
+ local dcm = 2 ^ p1
+ for c = 0, 7 do
+ if c ~= 2 and c ~= 4 and c ~= 6 then
+ local o = off + c * 2
+ local qo = c * 2
+ local c1, c3 = readi16(coef, o + 16), readi16(coef, o + 48)
+ local c5, c7 = readi16(coef, o + 80), readi16(coef, o + 112)
+ if c1 == 0 and c3 == 0 and c5 == 0 and c7 == 0 then
+ local dc = readi16(coef, o) * readu16(q, qo) * dcm
+ ws[c + 1] = dc
+ ws[c + 9] = dc
+ else
+ local tmp10 = readi16(coef, o) * readu16(q, qo) * 32768
+ local tmp0 = c7 * readu16(q, qo + 112) * -5906
+ + c5 * readu16(q, qo + 80) * 6967
+ + c3 * readu16(q, qo + 48) * -10426
+ + c1 * readu16(q, qo + 16) * 29692
+ ws[c + 1] = (tmp10 + tmp0 + h1) // s1
+ ws[c + 9] = (tmp10 - tmp0 + h1) // s1
+ end
+ end
+ end
+ local s2 = 2 ^ (18 + p1)
+ local h2 = s2 / 2 + center * s2
+ local sd = 2 ^ (p1 + 3)
+ local hd = sd / 2 + center * sd
+ for r = 0, 1 do
+ local b = r * 8
+ local w0, w1, w3, w5, w7 = ws[b + 1], ws[b + 2], ws[b + 4], ws[b + 6], ws[b + 8]
+ local o = (out + r * stride) * 2
+ if w1 == 0 and w3 == 0 and w5 == 0 and w7 == 0 then
+ local v = clamp((w0 + hd) // sd, 0, maxv)
+ writeu16(plane, o, v)
+ writeu16(plane, o + 2, v)
+ else
+ local tmp10 = w0 * 32768
+ local tmp0 = w7 * -5906 + w5 * 6967 + w3 * -10426 + w1 * 29692
+ writeu16(plane, o, clamp((tmp10 + tmp0 + h2) // s2, 0, maxv))
+ writeu16(plane, o + 2, clamp((tmp10 - tmp0 + h2) // s2, 0, maxv))
+ end
+ 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.
+function Dct.idctComponent(coef: buffer, q: buffer, bpl: number, bpc: number, size: number, plane: buffer, p1: number, center: number, maxv: number)
+ local stride = bpl * size
+ for by = 0, bpc - 1 do
+ for bx = 0, bpl - 1 do
+ local off = (by * bpl + bx) * 128
+ local out = by * size * stride + bx * size
+ if size == 8 then
+ idct8(coef, off, q, plane, out, stride, p1, center, maxv)
+ elseif size == 4 then
+ idct4(coef, off, q, plane, out, stride, p1, center, maxv)
+ elseif size == 2 then
+ idct2(coef, off, q, plane, out, stride, p1, center, maxv)
+ else
+ local v = (readi16(coef, off) * readu16(q, 0) + 4) // 8 + center
+ writeu16(plane, out * 2, clamp(v, 0, maxv))
+ end
+ end
+ 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)
+ local qv = readu16(div, i * 2) * 8
+ local h = qv // 2
+ if v < 0 then
+ writei16(coef, off + i * 2, -((h - v) // qv))
+ else
+ writei16(coef, off + i * 2, (v + h) // qv)
+ 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.
+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
+ local row = math.min(y + r, lastY) * stride
+ local d0: number, d1: number, d2: number, d3: number, d4: number, d5: number, d6: number, d7: number
+ if x + 7 <= lastX then
+ local p = row + x
+ d0, d1, d2, d3 = readu8(src, p), readu8(src, p + 1), readu8(src, p + 2), readu8(src, p + 3)
+ d4, d5, d6, d7 = readu8(src, p + 4), readu8(src, p + 5), readu8(src, p + 6), readu8(src, p + 7)
+ else
+ d0 = readu8(src, row + math.min(x, lastX))
+ d1 = readu8(src, row + math.min(x + 1, lastX))
+ d2 = readu8(src, row + math.min(x + 2, lastX))
+ d3 = readu8(src, row + math.min(x + 3, lastX))
+ d4 = readu8(src, row + math.min(x + 4, lastX))
+ d5 = readu8(src, row + math.min(x + 5, lastX))
+ d6 = readu8(src, row + math.min(x + 6, lastX))
+ d7 = readu8(src, row + math.min(x + 7, lastX))
+ end
+ d0 -= 128
+ d1 -= 128
+ d2 -= 128
+ d3 -= 128
+ d4 -= 128
+ d5 -= 128
+ d6 -= 128
+ d7 -= 128
+ local tmp0, tmp7 = d0 + d7, d0 - d7
+ local tmp1, tmp6 = d1 + d6, d1 - d6
+ local tmp2, tmp5 = d2 + d5, d2 - d5
+ local tmp3, tmp4 = d3 + d4, d3 - d4
+ local tmp10, tmp13 = tmp0 + tmp3, tmp0 - tmp3
+ local tmp11, tmp12 = tmp1 + tmp2, tmp1 - tmp2
+ local b = r * 8 + 1
+ fw[b] = (tmp10 + tmp11) * 4
+ fw[b + 4] = (tmp10 - tmp11) * 4
+ local z1 = (tmp12 + tmp13) * 4433
+ fw[b + 2] = (z1 + tmp13 * 6270 + 1024) // 2048
+ fw[b + 6] = (z1 - tmp12 * 15137 + 1024) // 2048
+ z1 = tmp4 + tmp7
+ local z2 = tmp5 + tmp6
+ local z3 = tmp4 + tmp6
+ local z4 = tmp5 + tmp7
+ local z5 = (z3 + z4) * 9633
+ tmp4 *= 2446
+ tmp5 *= 16819
+ tmp6 *= 25172
+ tmp7 *= 12299
+ z1 *= -7373
+ z2 *= -20995
+ z3 = z3 * -16069 + z5
+ z4 = z4 * -3196 + z5
+ fw[b + 7] = (tmp4 + z1 + z3 + 1024) // 2048
+ fw[b + 5] = (tmp5 + z2 + z4 + 1024) // 2048
+ fw[b + 3] = (tmp6 + z2 + z3 + 1024) // 2048
+ fw[b + 1] = (tmp7 + z1 + z4 + 1024) // 2048
+ end
+ for c = 1, 8 do
+ local d0, d1, d2, d3 = fw[c], fw[c + 8], fw[c + 16], fw[c + 24]
+ local d4, d5, d6, d7 = fw[c + 32], fw[c + 40], fw[c + 48], fw[c + 56]
+ local tmp0, tmp7 = d0 + d7, d0 - d7
+ local tmp1, tmp6 = d1 + d6, d1 - d6
+ local tmp2, tmp5 = d2 + d5, d2 - d5
+ local tmp3, tmp4 = d3 + d4, d3 - d4
+ local tmp10, tmp13 = tmp0 + tmp3, tmp0 - tmp3
+ local tmp11, tmp12 = tmp1 + tmp2, tmp1 - tmp2
+ local o0 = (tmp10 + tmp11 + 2) // 4
+ local o4 = (tmp10 - tmp11 + 2) // 4
+ local z1 = (tmp12 + tmp13) * 4433
+ local o2 = (z1 + tmp13 * 6270 + 16384) // 32768
+ local o6 = (z1 - tmp12 * 15137 + 16384) // 32768
+ z1 = tmp4 + tmp7
+ local z2 = tmp5 + tmp6
+ local z3 = tmp4 + tmp6
+ local z4 = tmp5 + tmp7
+ local z5 = (z3 + z4) * 9633
+ tmp4 *= 2446
+ tmp5 *= 16819
+ tmp6 *= 25172
+ tmp7 *= 12299
+ z1 *= -7373
+ z2 *= -20995
+ z3 = z3 * -16069 + z5
+ z4 = z4 * -3196 + z5
+ local o7 = (tmp4 + z1 + z3 + 16384) // 32768
+ local o5 = (tmp5 + z2 + z4 + 16384) // 32768
+ local o3 = (tmp6 + z2 + z3 + 16384) // 32768
+ local o1 = (tmp7 + z1 + z4 + 16384) // 32768
+ local cc = c - 1
+ quant(coef, off, div, o0, cc)
+ quant(coef, off, div, o1, cc + 8)
+ quant(coef, off, div, o2, cc + 16)
+ quant(coef, off, div, o3, cc + 24)
+ quant(coef, off, div, o4, cc + 32)
+ quant(coef, off, div, o5, cc + 40)
+ quant(coef, off, div, o6, cc + 48)
+ quant(coef, off, div, o7, cc + 56)
+ end
+end
+
+return Dct
diff --git a/src/Formats/codecs/Json/Decode.luau b/src/Formats/codecs/Json/Decode.luau
new file mode 100644
index 0000000..46b9fd2
--- /dev/null
+++ b/src/Formats/codecs/Json/Decode.luau
@@ -0,0 +1,433 @@
+--!strict
+--!native
+-- codecs/Json/Decode: the RFC 8259 parser behind codecs/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).
+local Types = require("@formats/Types")
+
+local Decode = {}
+
+local byte, sub, find, match, char = string.byte, string.sub, string.find, string.match, string.char
+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)
+}
+
+local ESC: { [number]: string } = {
+ [34] = '"',
+ [92] = "\\",
+ [47] = "/",
+ [98] = "\b",
+ [102] = "\f",
+ [110] = "\n",
+ [114] = "\r",
+ [116] = "\t",
+}
+
+-- utf8 bytes of a code point (surrogates too: WTF-8)
+local function utf8char(c: number): string
+ if c < 0x80 then
+ return char(c)
+ elseif c < 0x800 then
+ return char(0xC0 + c // 64, 0x80 + c % 64)
+ elseif c < 0x10000 then
+ return char(0xE0 + c // 4096, 0x80 + (c // 64) % 64, 0x80 + c % 64)
+ end
+ return char(0xF0 + c // 262144, 0x80 + (c // 4096) % 64, 0x80 + (c // 64) % 64, 0x80 + c % 64)
+end
+Decode.utf8char = utf8char
+
+local function hex4(s: string, i: number): number?
+ local h = match(s, "^%x%x%x%x", i)
+ if not h then
+ return nil
+ end
+ 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
+ return nil, "unterminated string", #s
+ end
+ local c = byte(s, j)
+ if c == 34 then
+ return sub(s, i + 1, j - 1), j + 1
+ end
+ local parts = {}
+ local np = 0
+ local start = i + 1
+ while true do
+ if c == 34 then
+ np += 1
+ parts[np] = sub(s, start, j - 1)
+ return concat(parts), j + 1
+ elseif c ~= 92 then
+ return nil, "control character in string", j - 1
+ end
+ np += 1
+ parts[np] = sub(s, start, j - 1)
+ local e = byte(s, j + 1)
+ if e == nil then
+ return nil, "unterminated string", #s
+ end
+ local simple = ESC[e]
+ if simple then
+ np += 1
+ parts[np] = simple
+ start = j + 2
+ elseif e == 117 then -- \u
+ local cp = hex4(s, j + 2)
+ if not cp then
+ return nil, "bad \\u escape", j - 1
+ end
+ start = j + 6
+ if cp >= 0xD800 and cp <= 0xDBFF and byte(s, start) == 92 and byte(s, start + 1) == 117 then
+ local lo = hex4(s, start + 2)
+ if lo and lo >= 0xDC00 and lo <= 0xDFFF then
+ cp = 0x10000 + (cp - 0xD800) * 1024 + (lo - 0xDC00)
+ start += 6
+ end
+ end
+ np += 1
+ parts[np] = utf8char(cp)
+ else
+ return nil, "bad escape", j - 1
+ end
+ j = find(s, '[%z\1-\31"\\]', start)
+ if not j then
+ return nil, "unterminated string", #s
+ end
+ c = byte(s, j)
+ end
+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
+ p += 1
+ end
+ local c = byte(s, p)
+ if c == 48 then
+ p += 1
+ elseif c and c >= 49 and c <= 57 then
+ p = match(s, "^%d*()", p + 1) :: any
+ else
+ return nil, if c == nil then "truncated: expected a value" elseif p == i then "unexpected character" else "bad number", p - 1
+ end
+ local int = true
+ if byte(s, p) == 46 then
+ local q = match(s, "^%d+()", p + 1)
+ if not q then
+ return nil, "bad fraction", p
+ end
+ p = q :: any
+ int = false
+ end
+ c = byte(s, p)
+ if c == 101 or c == 69 then
+ p += 1
+ c = byte(s, p)
+ if c == 43 or c == 45 then
+ p += 1
+ end
+ local q = match(s, "^%d+()", p)
+ if not q then
+ return nil, "bad exponent", p - 1
+ end
+ p = q :: any
+ int = false
+ end
+ local text = sub(s, i, p - 1)
+ local n = tonumber(text) :: number
+ if n == nil then -- LuaJIT: absurd exponents (1e0066999...) -> nil; they overflow / underflow
+ local m, es = match(text, "^([^eE]*)[eE]([%+%-]?)")
+ local mv = tonumber(m) or 0
+ n = if mv == 0 then mv elseif es == "-" then mv * 0 else mv * math.huge
+ end
+ if int and bigStrings and p - i > 15 and (n >= 9007199254740992 or n <= -9007199254740992) then
+ return text, p
+ end
+ return n, p
+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
+ local bigStrings = o.bigInts == "string"
+ local nullv = if o.null ~= nil then o.null else Types.null
+ 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 depth = 0
+ local n = #s
+ local value: any
+
+ while true do
+ i = match(s, "^[ \t\n\r]*()", i) :: any
+ local c = byte(s, i)
+ local haveValue = true
+ if c == 123 then -- {
+ depth += 1
+ if depth > maxDepth then
+ return nil, "nested deeper than " .. maxDepth, i - 1
+ end
+ i = match(s, "^[ \t\n\r]*()", i + 1) :: any
+ local t = {}
+ c = byte(s, i)
+ if c == 125 then
+ i += 1
+ depth -= 1
+ value = object(t, {})
+ elseif c == 34 then
+ local k, ni, at = str(s, i)
+ if k == nil then
+ return nil, ni, at
+ end
+ i = match(s, "^[ \t\n\r]*()", ni) :: any
+ if byte(s, i) ~= 58 then
+ return nil, if i > n then "truncated object" else "expected ':'", i - 1
+ end
+ i += 1
+ stackT[depth], stackK[depth] = t, k
+ stackO[depth] = if ordered then {} else true
+ haveValue = false
+ else
+ return nil, if c == nil then "truncated object" else "expected a key", i - 1
+ end
+ elseif c == 91 then -- [
+ depth += 1
+ if depth > maxDepth then
+ return nil, "nested deeper than " .. maxDepth, i - 1
+ end
+ i = match(s, "^[ \t\n\r]*()", i + 1) :: any
+ if byte(s, i) == 93 then
+ i += 1
+ depth -= 1
+ value = {}
+ else
+ stackT[depth], stackK[depth], stackO[depth] = {}, 0, false
+ haveValue = false
+ end
+ elseif c == 34 then
+ local v, ni, at = str(s, i)
+ if v == nil then
+ return nil, ni, at
+ end
+ value, i = v, ni
+ elseif c == 116 then
+ if sub(s, i, i + 3) ~= "true" then
+ return nil, "bad literal", i - 1
+ end
+ value, i = true, i + 4
+ elseif c == 102 then
+ if sub(s, i, i + 4) ~= "false" then
+ return nil, "bad literal", i - 1
+ end
+ value, i = false, i + 5
+ elseif c == 110 then
+ if sub(s, i, i + 3) ~= "null" then
+ return nil, "bad literal", i - 1
+ end
+ value, i = nullv, i + 4
+ elseif c == nil then
+ return nil, "truncated: expected a value", n
+ else
+ local v, ni, at = num(s, i, bigStrings)
+ if v == nil then
+ return nil, ni, at
+ 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
+ end
+ local t = stackT[depth]
+ local ord = stackO[depth]
+ if ord then
+ local k = stackK[depth]
+ if ord ~= true and t[k] == nil then
+ table.insert(ord, k)
+ end
+ t[k] = value
+ else
+ local cnt = stackK[depth] + 1
+ t[cnt] = value
+ stackK[depth] = cnt
+ end
+ i = match(s, "^[ \t\n\r]*()", i) :: any
+ c = byte(s, i)
+ if c == 44 then -- ,
+ i = match(s, "^[ \t\n\r]*()", i + 1) :: any
+ if ord then
+ if byte(s, i) ~= 34 then
+ return nil, if i > n then "truncated object" else "expected a key", i - 1
+ end
+ local k, ni, at = str(s, i)
+ if k == nil then
+ return nil, ni, at
+ end
+ i = match(s, "^[ \t\n\r]*()", ni) :: any
+ if byte(s, i) ~= 58 then
+ return nil, if i > n then "truncated object" else "expected ':'", i - 1
+ end
+ i += 1
+ stackK[depth] = k
+ end
+ haveValue = false
+ elseif ord and c == 125 then
+ i += 1
+ value = if ord ~= true then object(t, ord) elseif next(t) == nil then object(t, {}) else t
+ stackT[depth] = nil
+ depth -= 1
+ elseif not ord and c == 93 then
+ i += 1
+ value = t
+ stackT[depth] = nil
+ depth -= 1
+ elseif c == nil then
+ return nil, if ord then "truncated object" else "truncated array", n
+ else
+ return nil, if ord then "expected ',' or '}'" else "expected ',' or ']'", i - 1
+ end
+ end
+ 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 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)
+ state = "dead"
+ return "error", msg, at
+ end
+ return function(): (string?, any, number?)
+ if state == "dead" then
+ return nil
+ end
+ i = match(s, "^[ \t\n\r]*()", i) :: any
+ local c = byte(s, i)
+ if state == "done" then
+ state = "dead"
+ if c ~= nil then
+ return "error", "trailing data", i - 1
+ end
+ return nil
+ end
+ if state == "after" then
+ local obj = stack[depth]
+ if c == 44 then
+ i = match(s, "^[ \t\n\r]*()", i + 1) :: any
+ c = byte(s, i)
+ state = if obj then "key" else "value"
+ elseif c == (if obj then 125 else 93) then
+ i += 1
+ stack[depth] = nil
+ depth -= 1
+ state = if depth == 0 then "done" else "after"
+ return if obj then "endObject" else "endArray", nil
+ elseif c == nil then
+ return fail("truncated", n)
+ else
+ return fail("expected ',' or a close", i - 1)
+ end
+ end
+ if state == "first" then
+ local obj = stack[depth]
+ if c == (if obj then 125 else 93) then
+ i += 1
+ stack[depth] = nil
+ depth -= 1
+ state = if depth == 0 then "done" else "after"
+ return if obj then "endObject" else "endArray", nil
+ end
+ state = if obj then "key" else "value"
+ end
+ if state == "key" then
+ if c ~= 34 then
+ return fail(if c == nil then "truncated" else "expected a key", i - 1)
+ end
+ local k, ni, at = str(s, i)
+ if k == nil then
+ return fail(ni, at :: number)
+ end
+ i = match(s, "^[ \t\n\r]*()", ni) :: any
+ if byte(s, i) ~= 58 then
+ return fail("expected ':'", i - 1)
+ end
+ i += 1
+ 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
+ if depth > maxDepth then
+ return fail("nested deeper than " .. maxDepth, i - 1)
+ end
+ stack[depth] = c == 123
+ i += 1
+ state = "first"
+ return if c == 123 then "object" else "array", nil
+ elseif c == 34 then
+ local v, ni, at = str(s, i)
+ if v == nil then
+ return fail(ni, at :: number)
+ end
+ i = ni
+ state = after
+ return "value", v
+ elseif c == 116 and sub(s, i, i + 3) == "true" then
+ i += 4
+ state = after
+ return "value", true
+ elseif c == 102 and sub(s, i, i + 4) == "false" then
+ i += 5
+ state = after
+ return "value", false
+ elseif c == 110 and sub(s, i, i + 3) == "null" then
+ i += 4
+ state = after
+ return "value", nullv
+ elseif c == nil then
+ return fail("truncated: expected a value", n)
+ end
+ local v, ni, at = num(s, i, bigStrings)
+ if v == nil then
+ return fail(ni, at :: number)
+ end
+ i = ni
+ state = after
+ return "value", v
+ end
+end
+
+return Decode
diff --git a/src/Formats/codecs/Json/Encode.luau b/src/Formats/codecs/Json/Encode.luau
new file mode 100644
index 0000000..78d0ac5
--- /dev/null
+++ b/src/Formats/codecs/Json/Encode.luau
@@ -0,0 +1,307 @@
+--!strict
+--!native
+-- codecs/Json/Encode: the serializer behind codecs/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.
+local Types = require("@formats/Types")
+
+local Encode = {}
+
+local byte, format, gsub = string.byte, string.format, string.gsub
+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)
+}
+
+local ESCAPES: { [string]: string } = {
+ ['"'] = '\\"',
+ ["\\"] = "\\\\",
+ ["\b"] = "\\b",
+ ["\f"] = "\\f",
+ ["\n"] = "\\n",
+ ["\r"] = "\\r",
+ ["\t"] = "\\t",
+ ["/"] = "\\/",
+}
+for c = 0, 31 do
+ local ch = string.char(c)
+ if not ESCAPES[ch] then
+ ESCAPES[ch] = format("\\u%04x", c)
+ end
+end
+
+local function utf16(cp: number): string
+ if cp < 0x10000 then
+ return format("\\u%04x", cp)
+ end
+ cp -= 0x10000
+ 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
+ while i <= n do
+ local c = byte(seq, i)
+ local cp, len
+ if c < 0xC0 then
+ cp, len = c, 1
+ elseif c < 0xE0 then
+ cp, len = (c % 32) * 64 + (byte(seq, i + 1) or 128) % 64, 2
+ elseif c < 0xF0 then
+ cp, len = (c % 16) * 4096 + ((byte(seq, i + 1) or 128) % 64) * 64 + (byte(seq, i + 2) or 128) % 64, 3
+ else
+ cp, len = (c % 8) * 262144 + ((byte(seq, i + 1) or 128) % 64) * 4096 + ((byte(seq, i + 2) or 128) % 64) * 64 + (byte(seq, i + 3) or 128) % 64, 4
+ end
+ table.insert(out, utf16(cp))
+ i += len
+ end
+ return concat(out)
+end
+
+-- string(s, ascii, slash) -> the quoted JSON string (ascii: 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
+ s = gsub(s, pat, ESCAPES)
+ end
+ if ascii and string.find(s, "[\127-\255]") then
+ s = gsub(s, "\127", "\\u007f")
+ s = gsub(s, "[\192-\255][\128-\191]*", asciiSeq)
+ s = gsub(s, "[\128-\191]", asciiSeq)
+ end
+ return '"' .. s .. '"'
+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
+ end
+ if x == floor(x) and x > -1e15 and x < 1e15 then
+ if x == 0 and 1 / x < 0 then
+ return "-0"
+ end
+ return format("%d", x)
+ end
+ for _, f in FLOAT_FORMATS do
+ local t = format(f, x)
+ if tonumber(t) == x then
+ return t
+ end
+ end
+ return format("%.17g", x)
+end
+Encode.number = number
+
+local function keyLess(a: any, b: any): boolean
+ local ta, tb = type(a), type(b)
+ if ta ~= tb then
+ return ta == "number"
+ end
+ 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"
+ end
+ local n = #t
+ if n == 0 then
+ if next(t) == nil then
+ return if emptyObject then "object" else "array"
+ end
+ return "object"
+ end
+ local count = 0
+ for _ in next, t do
+ count += 1
+ end
+ return if count == n then "array" else "object"
+end
+Encode.kind = kind
+
+type State = {
+ out: { string },
+ n: number,
+ indent: string?,
+ sort: boolean,
+ ascii: boolean,
+ slash: boolean,
+ nanNull: boolean,
+ emptyObject: boolean,
+ maxDepth: number,
+ null: any,
+ err: string?,
+}
+
+local function put(st: State, s: string)
+ local n = st.n + 1
+ st.out[n] = s
+ st.n = n
+end
+
+local function value(st: State, v: any, depth: number): boolean
+ local tv = type(v)
+ if tv == "string" then
+ put(st, quote(v, st.ascii, st.slash))
+ elseif tv == "number" then
+ local s = number(v)
+ if not s then
+ if not st.nanNull then
+ st.err = "cannot encode " .. tostring(v)
+ return false
+ end
+ s = "null"
+ end
+ put(st, s)
+ elseif tv == "boolean" then
+ put(st, if v then "true" else "false")
+ elseif v == nil or v == st.null or v == Types.null then
+ put(st, "null")
+ elseif tv == "table" then
+ if Types.Date.is(v) then
+ put(st, '"' .. tostring(v) .. '"')
+ return true
+ end
+ if depth >= st.maxDepth then
+ st.err = "nested deeper than " .. st.maxDepth .. " (a cycle?)"
+ return false
+ end
+ local ind = st.indent
+ local nl, nl2 = "", ""
+ if ind then
+ nl = "\n" .. string.rep(ind, depth + 1)
+ nl2 = "\n" .. string.rep(ind, depth)
+ end
+ if kind(v, st.emptyObject) == "array" then
+ local n = #v
+ if n == 0 then
+ put(st, "[]")
+ return true
+ end
+ put(st, "[")
+ for i = 1, n do
+ if i > 1 then
+ put(st, ",")
+ end
+ if ind then
+ put(st, nl)
+ end
+ if not value(st, v[i], depth + 1) then
+ return false
+ end
+ end
+ if ind then
+ put(st, nl2)
+ end
+ put(st, "]")
+ else
+ local keys: { any }
+ if Types.isObject(v) then
+ keys = Types.keys(v)
+ else
+ keys = {}
+ for k in next, v do
+ local tk = type(k)
+ if tk ~= "string" and tk ~= "number" then
+ st.err = "object key of type " .. tk
+ return false
+ end
+ table.insert(keys, k)
+ end
+ if st.sort then
+ table.sort(keys, keyLess)
+ end
+ end
+ if #keys == 0 then
+ put(st, "{}")
+ return true
+ end
+ put(st, "{")
+ local sep = if ind then ": " else ":"
+ for i, k in keys do
+ if i > 1 then
+ put(st, ",")
+ end
+ if ind then
+ put(st, nl)
+ end
+ local ks: string
+ if type(k) == "string" then
+ ks = k
+ elseif type(k) == "number" then
+ ks = number(k) or tostring(k)
+ else
+ st.err = "object key of type " .. type(k)
+ return false
+ end
+ put(st, quote(ks, st.ascii, st.slash))
+ put(st, sep)
+ if not value(st, v[k], depth + 1) then
+ return false
+ end
+ end
+ if ind then
+ put(st, nl2)
+ end
+ put(st, "}")
+ end
+ elseif tv == "buffer" then
+ st.err = "cannot encode a buffer (encode it as base64 or an array first)"
+ return false
+ else
+ st.err = "cannot encode a " .. tv
+ return false
+ end
+ return true
+end
+
+local function state(opts: Options?, nullv: any?): State
+ local o: Options = opts or {}
+ local ind: string? = nil
+ if type(o.indent) == "number" then
+ ind = if o.indent > 0 then string.rep(" ", o.indent) else nil
+ elseif type(o.indent) == "string" then
+ ind = o.indent
+ end
+ return {
+ out = {},
+ n = 0,
+ indent = ind,
+ sort = o.sortKeys ~= false,
+ ascii = o.ascii == true,
+ slash = o.escapeSlash == true,
+ nanNull = o.nan == "null",
+ emptyObject = o.emptyTable == "object",
+ maxDepth = o.maxDepth or 1000,
+ null = nullv,
+ err = nil,
+ }
+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
+ return nil, st.err
+ end
+ return concat(st.out), nil
+end
+
+return Encode
diff --git a/src/Formats/codecs/Json/init.luau b/src/Formats/codecs/Json/init.luau
new file mode 100644
index 0000000..f9b6204
--- /dev/null
+++ b/src/Formats/codecs/Json/init.luau
@@ -0,0 +1,294 @@
+--!strict
+-- codecs/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("@formats/codecs/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("@formats/core/Err")
+local Types = require("@formats/Types")
+local Decode = require("@formats/codecs/Json/Decode")
+local Encode = require("@formats/codecs/Json/Encode")
+
+local Json = {}
+
+export type DecodeOptions = Decode.Options
+export type EncodeOptions = Encode.Options
+
+Json.null = Types.null
+Json.object = Types.object
+Json.keys = Types.keys
+Json.set = Types.set
+
+local function text(src: any): (string?, Err.Err?)
+ if type(src) == "string" then
+ return src, nil
+ elseif type(src) == "buffer" then
+ return buffer.tostring(src), nil
+ end
+ return nil, Err.new(Err.ARG, "expected a string or a buffer, got " .. typeof(src))
+end
+
+local function fail(msg: any, at: any, n: number): Err.Err
+ local m = tostring(msg)
+ local code = if string.find(m, "truncated", 1, true) or string.find(m, "unterminated", 1, true) or (at or 0) >= n
+ then Err.TRUNCATED
+ elseif string.find(m, "nested deeper", 1, true) then Err.LIMIT
+ else Err.CORRUPT
+ 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
+ return nil, terr
+ end
+ local i = if string.sub(s, 1, 3) == "\239\187\191" then 4 else 1
+ local v, ni, at = Decode.value(s, i, opts)
+ if v == nil then
+ return nil, fail(ni, at, #s)
+ end
+ local e = string.match(s, "^[ \t\n\r]*()", ni) :: any
+ if e <= #s then
+ return nil, Err.new(Err.CORRUPT, "trailing data after the value", e - 1)
+ end
+ 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
+ return nil, terr
+ end
+ local i = string.match(s, "^[ \t\n\r]*()", pos or 1) :: any
+ if i > #s then
+ return nil, nil
+ end
+ local v, ni, at = Decode.value(s, i, opts)
+ if v == nil then
+ return nil, fail(ni, at, #s)
+ end
+ 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
+ local index = 0
+ local dead = false
+ return function(): (number?, any, Err.Err?)
+ if dead then
+ return nil
+ end
+ index += 1
+ if not s then
+ dead = true
+ return index, nil, terr
+ end
+ local v, ni = Json.decodeAt(s, pos, opts)
+ if v == nil then
+ dead = true
+ if ni == nil then
+ return nil
+ end
+ return index, nil, ni
+ end
+ pos = ni
+ return index, v, nil
+ 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
+ local done = false
+ return function(): (string?, any)
+ if done then
+ return nil, nil
+ end
+ done = true
+ return "error", terr
+ end
+ end
+ local str: string = s
+ local i = if string.sub(str, 1, 3) == "\239\187\191" then 4 else 1
+ local nextEv = Decode.events(str, i, opts)
+ return function(): (string?, any)
+ local ev, v, at = nextEv()
+ if ev == "error" then
+ return ev, fail(v, at, #str)
+ end
+ return ev, v
+ 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
+ return nil, Err.new(Err.ARG, msg or "cannot encode")
+ end
+ 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)
+
+-- ------------------------------------------------------------------------------------------------ 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,
+ endObject: (self: Writer) -> Writer,
+ beginArray: (self: Writer) -> Writer,
+ endArray: (self: Writer) -> Writer,
+ key: (self: Writer, k: string) -> Writer,
+ value: (self: Writer, v: any) -> Writer,
+ flush: (self: Writer) -> string,
+ tostring: (self: Writer) -> (string?, Err.Err?),
+}
+
+function Json.writer(opts: EncodeOptions?): Writer
+ local st = Encode.state(opts)
+ local ind = st.indent
+ local kinds: { boolean } = {} -- true = object
+ local counts: { number } = {}
+ local depth = 0
+ local keyDone = false -- an object's key written, its value due
+ local flushed: { string } = {}
+ local w: any = { err = nil }
+ local function bad(msg: string)
+ if not w.err then
+ 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
+ end
+ if depth == 0 then
+ if counts[0] and counts[0] > 0 then
+ bad("one top-level value only")
+ return false
+ end
+ counts[0] = 1
+ return true
+ end
+ local obj = kinds[depth]
+ if obj and not isKey then
+ if not keyDone then
+ bad("an object member needs a key first")
+ return false
+ end
+ keyDone = false
+ return true
+ end
+ if isKey and not obj then
+ bad("key outside an object")
+ return false
+ end
+ if isKey and keyDone then
+ bad("two keys in a row")
+ return false
+ end
+ if counts[depth] > 0 then
+ table.insert(st.out, ",")
+ end
+ counts[depth] += 1
+ if ind then
+ table.insert(st.out, "\n" .. string.rep(ind, depth))
+ end
+ return true
+ end
+ local function open(obj: boolean)
+ if slot(false) then
+ table.insert(st.out, if obj then "{" else "[")
+ depth += 1
+ kinds[depth], counts[depth] = obj, 0
+ end
+ return w
+ end
+ local function close(obj: boolean)
+ if w.err then
+ return w
+ end
+ if depth == 0 or kinds[depth] ~= obj or (obj and keyDone) then
+ bad(if obj then "unbalanced endObject" else "unbalanced endArray")
+ return w
+ end
+ if ind and counts[depth] > 0 then
+ table.insert(st.out, "\n" .. string.rep(ind, depth - 1))
+ end
+ table.insert(st.out, if obj then "}" else "]")
+ depth -= 1
+ return w
+ end
+ function w.beginObject(_self: Writer): Writer
+ return open(true)
+ end
+ function w.beginArray(_self: Writer): Writer
+ return open(false)
+ end
+ function w.endObject(_self: Writer): Writer
+ return close(true)
+ end
+ function w.endArray(_self: Writer): Writer
+ return close(false)
+ end
+ function w.key(_self: Writer, k: string): Writer
+ if type(k) ~= "string" then
+ bad("key must be a string")
+ elseif slot(true) then
+ table.insert(st.out, Encode.quote(k, st.ascii, st.slash) .. (if ind then ": " else ":"))
+ keyDone = true
+ end
+ return w
+ end
+ function w.value(_self: Writer, v: any): Writer
+ if slot(false) then
+ st.n = #st.out
+ if not Encode.write(st, v, depth) then
+ bad(st.err or "cannot encode")
+ end
+ end
+ return w
+ end
+ function w.flush(_self: Writer): string
+ local s = table.concat(st.out)
+ table.clear(st.out)
+ st.n = 0
+ table.insert(flushed, s)
+ return s
+ end
+ function w.tostring(_self: Writer): (string?, Err.Err?)
+ if w.err then
+ return nil, w.err
+ end
+ if depth ~= 0 then
+ return nil, Err.new(Err.ARG, "unclosed object / array")
+ end
+ return table.concat(flushed) .. table.concat(st.out), nil
+ end
+ return w :: Writer
+end
+
+return Json
diff --git a/src/Formats/codecs/Lzma/Crc64.luau b/src/Formats/codecs/Lzma/Crc64.luau
new file mode 100644
index 0000000..19f682f
--- /dev/null
+++ b/src/Formats/codecs/Lzma/Crc64.luau
@@ -0,0 +1,37 @@
+--!strict
+--!native
+--!optimize 2
+-- codecs/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.
+local band, bxor, rshift, lshift, bor = bit32.band, bit32.bxor, bit32.rshift, bit32.lshift, bit32.bor
+local readu8 = buffer.readu8
+
+local THI, TLO = table.create(256, 0), table.create(256, 0)
+for n = 0, 255 do
+ local hi, lo = 0, n
+ for _ = 1, 8 do
+ local low = band(lo, 1)
+ lo = bor(rshift(lo, 1), lshift(band(hi, 1), 31))
+ hi = rshift(hi, 1)
+ if low ~= 0 then
+ hi = bxor(hi, 0xC96C5795)
+ lo = bxor(lo, 0xD7870F42)
+ end
+ end
+ THI[n + 1], TLO[n + 1] = hi, lo
+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
+ local idx = band(bxor(lo, readu8(b, i)), 255) + 1
+ lo = bxor(TLO[idx], bor(rshift(lo, 8), lshift(band(hi, 255), 24)))
+ hi = bxor(THI[idx], rshift(hi, 8))
+ end
+ return bxor(hi, 0xFFFFFFFF), bxor(lo, 0xFFFFFFFF)
+end
+
+return Crc64
diff --git a/src/Formats/codecs/Lzma/Decode.luau b/src/Formats/codecs/Lzma/Decode.luau
new file mode 100644
index 0000000..51be654
--- /dev/null
+++ b/src/Formats/codecs/Lzma/Decode.luau
@@ -0,0 +1,492 @@
+--!strict
+--!native
+--!optimize 2
+-- codecs/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.
+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
+
+-- probability offsets (u16 entries)
+local IS_MATCH = 0 -- 12 states x 16 pos states
+local IS_REP = 192
+local IS_REP_G0 = 204
+local IS_REP_G1 = 216
+local IS_REP_G2 = 228
+local IS_REP0_LONG = 240 -- 12 x 16
+local POS_SLOT = 432 -- 4 x 64
+local SPEC_POS = 688 -- 115
+local ALIGN = 803 -- 16
+local LEN = 819 -- choice, choice2, low 16 x 8, mid 16 x 8, high 256
+local REP_LEN = 1333
+local LITERAL = 1847 -- 0x300 << (lc + lp)
+
+local TOP = 16777216 -- 2^24
+
+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
+ maxBytes: number,
+ probs: buffer,
+ nprobs: number,
+ lc: number,
+ lp: number,
+ pb: number,
+ state: number,
+ rep0: number,
+ rep1: number,
+ rep2: number,
+ rep3: number,
+ remLen: number, -- a match cut by outEnd, finished by the next run
+ 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 {
+ out = bcreate(c),
+ cap = c,
+ op = 0,
+ dictStart = 0,
+ maxBytes = maxBytes,
+ probs = bcreate(2),
+ nprobs = 0,
+ lc = 0,
+ lp = 0,
+ pb = 0,
+ state = 0,
+ rep0 = 0,
+ rep1 = 0,
+ rep2 = 0,
+ rep3 = 0,
+ remLen = 0,
+ range = 0xFFFFFFFF,
+ code = 0,
+ }
+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"
+ end
+ st.lc, st.lp, st.pb = lc, lp, pb
+ local n = LITERAL + 0x300 * 2 ^ (lc + lp)
+ if blen(st.probs) < n * 2 then
+ st.probs = bcreate(n * 2)
+ end
+ st.nprobs = n
+ Decode.resetState(st)
+ 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
+ writeu16(p, i * 2, 1024)
+ end
+ st.state = 0
+ st.rep0, st.rep1, st.rep2, st.rep3 = 0, 0, 0, 0
+ 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"
+ end
+ if readu8(b, ip) ~= 0 then
+ return nil, "bad range coder init byte"
+ end
+ st.code = readu8(b, ip + 1) * 16777216 + readu8(b, ip + 2) * 65536 + readu8(b, ip + 3) * 256 + readu8(b, ip + 4)
+ st.range = 0xFFFFFFFF
+ if st.code == st.range then
+ return nil, "bad range coder init"
+ end
+ 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
+ end
+ if need > st.maxBytes then
+ return false
+ end
+ local c = math.min(math.max(st.cap * 2, need, 65536), st.maxBytes)
+ local nb = bcreate(c)
+ bcopy(nb, 0, st.out, 0, st.op)
+ st.out = nb
+ st.cap = c
+ return true
+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"
+ end
+ bcopy(st.out, st.op, b, ip, n)
+ st.op += n
+ 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)
+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)
+ local bound = rshift(range, 11) * prob
+ local r
+ if code < bound then
+ range = bound
+ writeu16(probs, p, prob + rshift(2048 - prob, 5))
+ r = 0
+ else
+ range -= bound
+ code -= bound
+ writeu16(probs, p, prob - rshift(prob, 5))
+ r = 1
+ end
+ if range < TOP then
+ range *= 256
+ if ip < iend then
+ code = code * 256 + readu8(inb, ip)
+ else
+ code *= 256
+ over += 1
+ end
+ ip += 1
+ end
+ return r
+end
+
+local function tree(base: number, nbits: number): number
+ local m = 1
+ for _ = 1, nbits do
+ m = m * 2 + bit(base + m)
+ end
+ return m - 2 ^ nbits
+end
+
+local function reverse(base: number, nbits: number): number
+ local m = 1
+ local sym = 0
+ for i = 0, nbits - 1 do
+ local b = bit(base + m)
+ m = m * 2 + b
+ sym += b * 2 ^ i
+ end
+ return sym
+end
+
+local function direct(nbits: number): number
+ local res = 0
+ for _ = 1, nbits do
+ range = rshift(range, 1)
+ local b = 0
+ if code >= range then
+ code -= range
+ b = 1
+ end
+ res = res * 2 + b
+ if range < TOP then
+ range *= 256
+ if ip < iend then
+ code = code * 256 + readu8(inb, ip)
+ else
+ code *= 256
+ over += 1
+ end
+ ip += 1
+ end
+ end
+ return res
+end
+
+local function length(base: number, posState: number): number
+ if bit(base) == 0 then
+ return tree(base + 2 + posState * 8, 3)
+ end
+ if bit(base + 1) == 0 then
+ return 8 + tree(base + 130 + posState * 8, 3)
+ end
+ 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
+ iend = iend0
+ local out = st.out
+ local cap = st.cap
+ local op = st.op
+ local dictStart = st.dictStart
+ range, code = st.range, st.code
+ ip = ip0
+ over = 0
+ local state = st.state
+ local rep0, rep1, rep2, rep3 = st.rep0, st.rep1, st.rep2, st.rep3
+ local lc = st.lc
+ local lcShift = 2 ^ (8 - lc)
+ local lpMask = 2 ^ st.lp - 1
+ local pbMask = 2 ^ st.pb - 1
+ local lcMul = 2 ^ lc
+
+ 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)
+ if n > 0 then
+ if op + n > cap then
+ st.op = op
+ if not ensure(st, op + n) then
+ probs, inb = EMPTY, EMPTY
+ return nil, "limit: output over maxBytes"
+ end
+ out, cap = st.out, st.cap
+ end
+ local src = op - rep0 - 1
+ for k = 0, n - 1 do
+ writeu8(out, op + k, readu8(out, src + k))
+ end
+ op += n
+ remLen -= n
+ end
+ end
+
+ while true do
+ if op >= outEnd then
+ status = "full"
+ break
+ end
+ if over > 0 then
+ msg = "truncated"
+ break
+ end
+ if op + 273 > cap then
+ st.op = op
+ if not ensure(st, math.min(op + 273, outEnd)) then
+ msg = "limit: output over maxBytes"
+ break
+ end
+ out, cap = st.out, st.cap
+ end
+ local pos = op - dictStart
+ local posState = band(pos, pbMask)
+ -- is match? (inlined bit)
+ local pidx = (IS_MATCH + state * 16 + posState) * 2
+ local prob = readu16(probs, pidx)
+ local bound = rshift(range, 11) * prob
+ if code < bound then
+ range = bound
+ writeu16(probs, pidx, prob + rshift(2048 - prob, 5))
+ if range < TOP then
+ range *= 256
+ if ip < iend then
+ code = code * 256 + readu8(inb, ip)
+ else
+ code *= 256
+ over += 1
+ end
+ ip += 1
+ end
+ -- literal
+ local prev = if op > dictStart then readu8(out, op - 1) else 0
+ local base = LITERAL + 0x300 * (band(pos, lpMask) * lcMul + prev // lcShift)
+ local sym = 1
+ if state >= 7 then
+ local mpos = op - rep0 - 1
+ local matchByte = if mpos >= dictStart then readu8(out, mpos) else 0
+ repeat
+ local matchBit = band(rshift(matchByte, 7), 1)
+ matchByte *= 2
+ local b = bit(base + (1 + matchBit) * 256 + sym)
+ sym = sym * 2 + b
+ if matchBit ~= b then
+ break
+ end
+ until sym >= 256
+ end
+ while sym < 256 do
+ local p2 = (base + sym) * 2
+ local pr = readu16(probs, p2)
+ local bd = rshift(range, 11) * pr
+ if code < bd then
+ range = bd
+ writeu16(probs, p2, pr + rshift(2048 - pr, 5))
+ sym = sym * 2
+ else
+ range -= bd
+ code -= bd
+ writeu16(probs, p2, pr - rshift(pr, 5))
+ sym = sym * 2 + 1
+ end
+ if range < TOP then
+ range *= 256
+ if ip < iend then
+ code = code * 256 + readu8(inb, ip)
+ else
+ code *= 256
+ over += 1
+ end
+ ip += 1
+ end
+ end
+ writeu8(out, op, sym - 256)
+ op += 1
+ state = if state < 4 then 0 elseif state < 10 then state - 3 else state - 6
+ else
+ range -= bound
+ code -= bound
+ writeu16(probs, pidx, prob - rshift(prob, 5))
+ if range < TOP then
+ range *= 256
+ if ip < iend then
+ code = code * 256 + readu8(inb, ip)
+ else
+ code *= 256
+ over += 1
+ end
+ ip += 1
+ end
+ local len
+ if bit(IS_REP + state) == 0 then
+ -- simple match
+ len = length(LEN, posState)
+ state = if state < 7 then 7 else 10
+ rep3, rep2, rep1 = rep2, rep1, rep0
+ local lenState = if len < 3 then len else 3
+ local slot = tree(POS_SLOT + lenState * 64, 6)
+ if slot < 4 then
+ rep0 = slot
+ else
+ local nd = slot // 2 - 1
+ local dist = (2 + slot % 2) * 2 ^ nd
+ if slot < 14 then
+ dist += reverse(SPEC_POS + dist - slot, nd)
+ else
+ dist += direct(nd - 4) * 16
+ dist += reverse(ALIGN, 4)
+ end
+ rep0 = dist
+ end
+ if rep0 == 0xFFFFFFFF then
+ status = "eos"
+ break
+ end
+ else
+ if bit(IS_REP_G0 + state) == 0 then
+ if bit(IS_REP0_LONG + state * 16 + posState) == 0 then
+ -- short rep: one byte at rep0
+ if op == dictStart or rep0 >= op - dictStart then
+ msg = "distance past the dictionary start"
+ break
+ end
+ state = if state < 7 then 9 else 11
+ writeu8(out, op, readu8(out, op - rep0 - 1))
+ op += 1
+ continue
+ end
+ else
+ local dist
+ if bit(IS_REP_G1 + state) == 0 then
+ dist = rep1
+ else
+ if bit(IS_REP_G2 + state) == 0 then
+ dist = rep2
+ else
+ dist = rep3
+ rep3 = rep2
+ end
+ rep2 = rep1
+ end
+ rep1 = rep0
+ rep0 = dist
+ end
+ len = length(REP_LEN, posState)
+ state = if state < 7 then 8 else 11
+ end
+ -- copy len + 2 bytes from rep0 + 1 back
+ if rep0 >= op - dictStart then
+ msg = "distance past the dictionary start"
+ break
+ end
+ local n = len + 2
+ local room = outEnd - op
+ if n > room then
+ remLen = n - room
+ n = room
+ end
+ local src = op - rep0 - 1
+ if rep0 + 1 >= n then
+ bcopy(out, op, out, src, n)
+ else
+ for k = 0, n - 1 do
+ writeu8(out, op + k, readu8(out, src + k))
+ end
+ end
+ op += n
+ end
+ end
+ st.op = op
+ st.range, st.code = range, code
+ 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
+ if msg then
+ return nil, msg
+ end
+ if over > 0 then
+ return nil, "truncated"
+ end
+ 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
+ end
+ local b = bcreate(st.op)
+ bcopy(b, 0, st.out, 0, st.op)
+ return b
+end
+
+return Decode
diff --git a/src/Formats/codecs/Lzma/Filters.luau b/src/Formats/codecs/Lzma/Filters.luau
new file mode 100644
index 0000000..60a5d59
--- /dev/null
+++ b/src/Formats/codecs/Lzma/Filters.luau
@@ -0,0 +1,177 @@
+--!strict
+--!native
+--!optimize 2
+-- codecs/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).
+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
+
+local TWO32 = 4294967296
+
+local Filters = {}
+
+local MASK_ALLOWED = { [0] = true, true, true, false, true, false, false, false }
+local MASK_BITNUM = { [0] = 0, 1, 2, 2, 3, 3, 3, 3 }
+
+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
+ end
+ local size = n - 4
+ local prevPos = -1
+ local prevMask = 0
+ local i = 0
+ while i < size do
+ local c = readu8(b, o + i)
+ if band(c, 0xFE) ~= 0xE8 then
+ i += 1
+ continue
+ end
+ local d = i - prevPos
+ if d > 3 then
+ prevMask = 0
+ else
+ prevMask = band(lshift(prevMask, d - 1), 7)
+ if prevMask ~= 0 then
+ local bb = readu8(b, o + i + 4 - MASK_BITNUM[prevMask])
+ if not MASK_ALLOWED[prevMask] or msbyte(bb) then
+ prevPos = i
+ prevMask = bor(lshift(prevMask, 1), 1)
+ i += 1
+ continue
+ end
+ end
+ end
+ prevPos = i
+ if msbyte(readu8(b, o + i + 4)) then
+ local src = readu32(b, o + i + 1)
+ local dest
+ while true do
+ dest = (src - (start + i + 5)) % TWO32
+ if prevMask == 0 then
+ break
+ end
+ local j = MASK_BITNUM[prevMask] * 8
+ local bb = band(rshift(dest, 24 - j), 0xFF)
+ if not msbyte(bb) then
+ break
+ end
+ src = bxor(dest, 2 ^ (32 - j) - 1)
+ end
+ dest = band(dest, 0x01FFFFFF)
+ if band(dest, 0x01000000) ~= 0 then
+ dest = bor(dest, 0xFF000000)
+ end
+ writeu32(b, o + i + 1, dest)
+ i += 5
+ else
+ prevMask = bor(lshift(prevMask, 1), 1)
+ i += 1
+ end
+ end
+end
+
+function Filters.arm(b: buffer, o: number, n: number, start: number)
+ local i = 0
+ while i + 4 <= n do
+ if readu8(b, o + i + 3) == 0xEB then
+ local addr = readu8(b, o + i) + readu8(b, o + i + 1) * 256 + readu8(b, o + i + 2) * 65536
+ addr = (addr * 4 - (start + i + 8)) % TWO32
+ addr = rshift(addr, 2)
+ writeu8(b, o + i, band(addr, 255))
+ writeu8(b, o + i + 1, band(rshift(addr, 8), 255))
+ writeu8(b, o + i + 2, band(rshift(addr, 16), 255))
+ end
+ i += 4
+ end
+end
+
+function Filters.armthumb(b: buffer, o: number, n: number, start: number)
+ local i = 0
+ while i + 4 <= n do
+ local b1, b3 = readu8(b, o + i + 1), readu8(b, o + i + 3)
+ if band(b1, 0xF8) == 0xF0 and band(b3, 0xF8) == 0xF8 then
+ local addr = band(b1, 7) * 524288 + readu8(b, o + i) * 2048 + band(b3, 7) * 256 + readu8(b, o + i + 2)
+ addr = (addr * 2 - (start + i + 4)) % TWO32
+ addr = rshift(addr, 1)
+ writeu8(b, o + i + 1, bor(0xF0, band(rshift(addr, 19), 7)))
+ writeu8(b, o + i, band(rshift(addr, 11), 255))
+ writeu8(b, o + i + 3, bor(0xF8, band(rshift(addr, 8), 7)))
+ writeu8(b, o + i + 2, band(addr, 255))
+ i += 4
+ else
+ i += 2
+ end
+ end
+end
+
+function Filters.powerpc(b: buffer, o: number, n: number, start: number)
+ local i = 0
+ while i + 4 <= n do
+ local instr = byteswap(readu32(b, o + i))
+ if band(instr, 0xFC000003) == 0x48000001 then
+ instr = band(instr, 0x03FFFFFC)
+ instr = band((instr - (start + i)) % TWO32, 0x03FFFFFC)
+ instr = bor(instr, 0x48000001)
+ writeu32(b, o + i, byteswap(instr))
+ end
+ i += 4
+ end
+end
+
+function Filters.sparc(b: buffer, o: number, n: number, start: number)
+ local i = 0
+ while i + 4 <= n do
+ local instr = byteswap(readu32(b, o + i))
+ local top = rshift(instr, 22)
+ if top == 0x100 or top == 0x1FF then
+ instr = (instr * 4) % TWO32
+ instr = (instr - (start + i)) % TWO32
+ instr = rshift(instr, 2)
+ instr = bor((0x40000000 - band(instr, 0x400000)) % TWO32, 0x40000000, band(instr, 0x3FFFFF))
+ writeu32(b, o + i, byteswap(instr))
+ end
+ i += 4
+ end
+end
+
+function Filters.arm64(b: buffer, o: number, n: number, start: number)
+ local i = 0
+ while i + 4 <= n do
+ local pc = (start + i) % TWO32
+ local instr = readu32(b, o + i)
+ if rshift(instr, 26) == 0x25 then
+ local src = instr
+ local p = (TWO32 - rshift(pc, 2)) % TWO32
+ writeu32(b, o + i, bor(0x94000000, band((src + p) % TWO32, 0x03FFFFFF)))
+ elseif band(instr, 0x9F000000) == 0x90000000 then
+ local src = bor(band(rshift(instr, 29), 3), band(rshift(instr, 3), 0x001FFFFC))
+ if band(src + 0x00020000, 0x001C0000) == 0 then
+ local p = (TWO32 - rshift(pc, 12)) % TWO32
+ local dest = (src + p) % TWO32
+ local v = band(instr, 0x9000001F)
+ v = bor(v, lshift(band(dest, 3), 29))
+ v = bor(v, lshift(band(dest, 0x0003FFFC), 3))
+ v = bor(v, band((TWO32 - band(dest, 0x00020000)) % TWO32, 0x00E00000))
+ writeu32(b, o + i, v)
+ end
+ end
+ i += 4
+ end
+end
+
+-- delta(b, o, n, dist): 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))
+ end
+end
+
+return Filters
diff --git a/src/Formats/codecs/Lzma/init.luau b/src/Formats/codecs/Lzma/init.luau
new file mode 100644
index 0000000..f6f2825
--- /dev/null
+++ b/src/Formats/codecs/Lzma/init.luau
@@ -0,0 +1,601 @@
+--!strict
+-- codecs/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("@formats/codecs/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.
+local Err = require("@formats/core/Err")
+local Crc32 = require("@formats/core/Crc32")
+local Decode = require("@formats/codecs/Lzma/Decode")
+local Filters = require("@formats/codecs/Lzma/Filters")
+local Crc64 = require("@formats/codecs/Lzma/Crc64")
+
+local readu8, readu32 = buffer.readu8, buffer.readu32
+
+local Lzma = {}
+
+local DEFAULT_MAX = 2 ^ 30
+
+export type Options = {
+ maxBytes: number?, -- refuse output larger than this (default 2^30)
+}
+export type Props = { lc: number, lp: number, pb: number, dictSize: number? }
+
+local function toBuffer(b: any): buffer?
+ if type(b) == "string" then
+ return buffer.fromstring(b)
+ end
+ if type(b) ~= "buffer" then
+ return nil
+ end
+ return b
+end
+
+local function range(b: buffer, off: number?, len: number?): (number?, number)
+ local n = buffer.len(b)
+ local o = off or 0
+ if type(o) ~= "number" or o < 0 or o > n or o % 1 ~= 0 then
+ return nil, 0
+ end
+ local l = len or (n - o)
+ if type(l) ~= "number" or l < 0 or l % 1 ~= 0 then
+ return nil, 0
+ end
+ if o + l > n then
+ l = n - o
+ end
+ return o, l
+end
+
+local function args(what: string, buf: any, offset: number?, length: number?): (buffer?, number, number, Err.Err?)
+ local b = toBuffer(buf)
+ if not b then
+ return nil, 0, 0, Err.new(Err.ARG, what .. ": expected a buffer or a string, got " .. typeof(buf))
+ end
+ local o, l = range(b, offset, length)
+ if not o then
+ return nil, 0, 0, Err.new(Err.ARG, what .. ": bad offset / length " .. tostring(offset) .. ", " .. tostring(length))
+ end
+ return b, o, l, nil
+end
+
+local function maxOf(opts: Options?): number
+ local m = opts and opts.maxBytes
+ 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
+ if string.sub(s, 1, 5) == "limit" then
+ code = Err.LIMIT
+ elseif string.find(s, "truncated", 1, true) then
+ code = Err.TRUNCATED
+ end
+ 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
+ end
+ return d % 9, (d // 9) % 5, d // 45
+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
+ return nil, fail(ierr, o)
+ end
+ local target = if unpackSize then st.op + unpackSize else math.huge
+ if unpackSize and target > st.maxBytes then
+ return nil, Err.new(Err.LIMIT, string.format("output of %d bytes is over maxBytes", unpackSize))
+ end
+ if unpackSize and not Decode.ensure(st, target) then
+ return nil, Err.new(Err.LIMIT, "output over maxBytes")
+ end
+ local status, res = Decode.run(st, b, ip, e, target)
+ if not status then
+ return nil, fail(res, o)
+ end
+ if unpackSize and st.op ~= target then
+ return nil, Err.new(Err.CORRUPT, "end marker before the declared size", o)
+ end
+ 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
+ return nil, aerr
+ end
+ local lc, lp, pb
+ if type(props) == "table" then
+ lc, lp, pb = props.lc, props.lp, props.pb
+ else
+ local pbuf = toBuffer(props)
+ if not pbuf or buffer.len(pbuf) < 1 then
+ return nil, Err.new(Err.ARG, "Lzma.lzma: props must be the 5-byte properties or { lc, lp, pb }")
+ end
+ lc, lp, pb = propsByte(readu8(pbuf, 0))
+ if not lc then
+ return nil, Err.new(Err.CORRUPT, "bad LZMA properties byte")
+ end
+ end
+ if type(lc) ~= "number" or type(lp) ~= "number" or type(pb) ~= "number" then
+ return nil, Err.new(Err.ARG, "Lzma.lzma: bad props")
+ end
+ if unpackSize ~= nil and (type(unpackSize) ~= "number" or unpackSize < 0 or unpackSize % 1 ~= 0) then
+ return nil, Err.new(Err.ARG, "Lzma.lzma: bad unpackSize")
+ end
+ local max = maxOf(opts)
+ local st = Decode.new(if unpackSize then unpackSize else l * 4, max)
+ local ok, perr = Decode.setProps(st, lc, lp, pb)
+ if not ok then
+ return nil, Err.new(Err.CORRUPT, tostring(perr))
+ end
+ local consumed, err = decodeLzma(st, b, o, o + l, unpackSize)
+ if not consumed then
+ return nil, err
+ end
+ return Decode.finish(st), consumed
+end
+
+-- alone(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err: a .lzma file (props, dict size, u64 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
+ return nil, aerr
+ end
+ if l < 13 then
+ return nil, Err.new(Err.TRUNCATED, "truncated .lzma header", o)
+ end
+ local lo, hi = readu32(b, o + 5), readu32(b, o + 9)
+ local size: number? = nil
+ if not (lo == 0xFFFFFFFF and hi == 0xFFFFFFFF) then
+ if hi >= 2 ^ 21 then
+ return nil, Err.new(Err.CORRUPT, "bad .lzma size", o + 5)
+ end
+ size = hi * 4294967296 + lo
+ end
+ 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
+ while true do
+ if p >= e then
+ return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 stream", p)
+ end
+ local c = readu8(b, p)
+ if c == 0 then
+ return p + 1, nil
+ end
+ if c == 1 or c == 2 then
+ if p + 3 > e then
+ return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 chunk header", p)
+ end
+ local n = readu8(b, p + 1) * 256 + readu8(b, p + 2) + 1
+ if c == 1 then
+ Decode.resetDict(st)
+ needDict = false
+ elseif needDict then
+ return nil, Err.new(Err.CORRUPT, "LZMA2 chunk without a dictionary reset", p)
+ end
+ if p + 3 + n > e then
+ return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 stored chunk", p)
+ end
+ local ok, cerr = Decode.copy(st, n, b, p + 3)
+ if not ok then
+ return nil, fail(cerr, p)
+ end
+ st.remLen = 0
+ p += 3 + n
+ elseif c >= 0x80 then
+ if p + 5 > e then
+ return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 chunk header", p)
+ end
+ local usize = (c % 32) * 65536 + readu8(b, p + 1) * 256 + readu8(b, p + 2) + 1
+ local psize = readu8(b, p + 3) * 256 + readu8(b, p + 4) + 1
+ local mode = (c // 32) % 4
+ local q = p + 5
+ if mode == 3 then
+ Decode.resetDict(st)
+ needDict = false
+ elseif needDict then
+ return nil, Err.new(Err.CORRUPT, "LZMA2 chunk without a dictionary reset", p)
+ end
+ if mode >= 2 then
+ if q >= e then
+ return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 properties", q)
+ end
+ local lc, lp, pb = propsByte(readu8(b, q))
+ if not lc or lc + lp > 4 then
+ return nil, Err.new(Err.CORRUPT, "bad LZMA2 properties", q)
+ end
+ Decode.setProps(st, lc, lp, pb)
+ needProps = false
+ q += 1
+ elseif needProps then
+ return nil, Err.new(Err.CORRUPT, "LZMA2 chunk without properties", p)
+ elseif mode == 1 then
+ Decode.resetState(st)
+ end
+ if q + psize > e then
+ return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 chunk", q)
+ end
+ local target = st.op + usize
+ if target > st.maxBytes then
+ return nil, Err.new(Err.LIMIT, "output over maxBytes")
+ end
+ Decode.ensure(st, target)
+ local ip, ierr = Decode.rcInit(st, b, q, q + psize)
+ if not ip then
+ return nil, fail(ierr, q)
+ end
+ local status, res = Decode.run(st, b, ip, q + psize, target)
+ if not status then
+ return nil, fail(res, q)
+ end
+ if status ~= "full" or st.op ~= target then
+ return nil, Err.new(Err.CORRUPT, "LZMA2 chunk size mismatch", p)
+ end
+ p = q + psize
+ else
+ return nil, Err.new(Err.CORRUPT, "bad LZMA2 control byte " .. c, p)
+ end
+ 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
+ return nil, aerr
+ end
+ local max = maxOf(opts)
+ local st = Decode.new(if type(unpackSize) == "number" and unpackSize >= 0 then unpackSize else l * 4, max)
+ local consumed, err = decodeLzma2(st, b, o, o + l)
+ if not consumed then
+ return nil, err
+ end
+ if type(unpackSize) == "number" and st.op ~= unpackSize then
+ return nil, Err.new(Err.CORRUPT, string.format("LZMA2 output is %d bytes, expected %d", st.op, unpackSize))
+ end
+ 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,
+ x86 = 0x04,
+ powerpc = 0x05,
+ ia64 = 0x06,
+ arm = 0x07,
+ armthumb = 0x08,
+ sparc = 0x09,
+ arm64 = 0x0A,
+ riscv = 0x0B,
+ lzma2 = 0x21,
+})
+local BCJ: { [number]: (buffer, number, number, number) -> () } = {
+ [0x04] = Filters.x86,
+ [0x05] = Filters.powerpc,
+ [0x07] = Filters.arm,
+ [0x08] = Filters.armthumb,
+ [0x09] = Filters.sparc,
+ [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)
+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
+ if id == 0x03 then
+ if plen ~= 1 then
+ return nil, Err.new(Err.CORRUPT, "bad delta filter properties")
+ end
+ Filters.delta(b, o, n, readu8(pb :: buffer, 0) + 1)
+ return true
+ end
+ local f = BCJ[id]
+ if not f then
+ return nil, Err.new(Err.UNSUPPORTED, string.format("filter 0x%x is not supported", id))
+ end
+ local start = 0
+ if plen == 4 then
+ start = readu32(pb :: buffer, 0)
+ elseif plen ~= 0 then
+ return nil, Err.new(Err.CORRUPT, "bad BCJ filter properties")
+ end
+ f(b, o, n, start)
+ return true
+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
+ if p + i >= e then
+ return nil, p
+ end
+ local c = readu8(b, p + i)
+ v += (c % 128) * mul
+ if c < 128 then
+ if c == 0 and i > 0 then
+ return nil, p -- non-minimal encoding
+ end
+ return v, p + i + 1
+ end
+ mul *= 128
+ end
+ return nil, p
+end
+Lzma.vli = vli
+
+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)
+ end
+ if buffer.readstring(b, o, 6) ~= XZ_MAGIC then
+ return nil, Err.new(Err.CORRUPT, "bad xz magic", o)
+ end
+ if readu8(b, o + 6) ~= 0 or readu8(b, o + 7) > 15 then
+ return nil, Err.new(Err.UNSUPPORTED, "unknown xz stream flags", o + 6)
+ end
+ if crc(b, o + 6, 2) ~= readu32(b, o + 8) then
+ return nil, Err.new(Err.CHECKSUM, "xz stream header CRC-32 mismatch", o + 8)
+ end
+ local check = readu8(b, o + 7)
+ local csize = CHECK_SIZE[check]
+ local p = o + 12
+ local records: { { number } } = {}
+ while true do
+ if p >= e then
+ return nil, Err.new(Err.TRUNCATED, "truncated xz block", p)
+ end
+ local hs = readu8(b, p)
+ if hs == 0 then
+ break -- the index
+ end
+ local hsize = (hs + 1) * 4
+ if p + hsize > e then
+ return nil, Err.new(Err.TRUNCATED, "truncated xz block header", p)
+ end
+ if crc(b, p, hsize - 4) ~= readu32(b, p + hsize - 4) then
+ return nil, Err.new(Err.CHECKSUM, "xz block header CRC-32 mismatch", p)
+ end
+ local flags = readu8(b, p + 1)
+ if flags % 64 >= 4 then
+ return nil, Err.new(Err.UNSUPPORTED, "reserved xz block flags", p + 1)
+ end
+ local nfilters = flags % 4 + 1
+ local q = p + 2
+ local he = p + hsize - 4
+ local csz, usz: number? = nil, nil
+ if flags >= 128 or (flags // 64) % 2 == 1 then
+ if (flags // 64) % 2 == 1 then
+ local v
+ v, q = vli(b, q, he)
+ if not v or v == 0 then
+ return nil, Err.new(Err.CORRUPT, "bad xz compressed size", q)
+ end
+ csz = v
+ end
+ if flags >= 128 then
+ local v
+ v, q = vli(b, q, he)
+ if not v then
+ return nil, Err.new(Err.CORRUPT, "bad xz uncompressed size", q)
+ end
+ usz = v
+ end
+ end
+ local filters: { { id: number, props: buffer } } = {}
+ for _ = 1, nfilters do
+ local id, psz
+ id, q = vli(b, q, he)
+ if not id then
+ return nil, Err.new(Err.CORRUPT, "bad xz filter flags", q)
+ end
+ psz, q = vli(b, q, he)
+ if not psz or q + psz > he then
+ return nil, Err.new(Err.CORRUPT, "bad xz filter properties", q)
+ end
+ local pr = buffer.create(psz)
+ buffer.copy(pr, 0, b, q, psz)
+ q += psz
+ table.insert(filters, { id = id, props = pr })
+ end
+ for k = q, he - 1 do
+ if readu8(b, k) ~= 0 then
+ return nil, Err.new(Err.CORRUPT, "nonzero xz block header padding", k)
+ end
+ end
+ local last = filters[nfilters]
+ if last.id ~= 0x21 or buffer.len(last.props) ~= 1 or readu8(last.props, 0) > 40 then
+ return nil, Err.new(Err.UNSUPPORTED, string.format("xz filter chain must end in LZMA2 (got 0x%x)", last.id), p)
+ end
+ for k = 1, nfilters - 1 do
+ local id = filters[k].id
+ if id ~= 0x03 and not BCJ[id] then
+ return nil, Err.new(Err.UNSUPPORTED, string.format("xz filter 0x%x is not supported", id), p)
+ end
+ end
+ -- data
+ local dstart = p + hsize
+ local ostart = st.op
+ local dend = if csz then dstart + csz else e
+ if dend > e then
+ return nil, Err.new(Err.TRUNCATED, "truncated xz block data", dstart)
+ end
+ local cend, derr = decodeLzma2(st, b, dstart, dend)
+ if not cend then
+ return nil, derr
+ end
+ if csz and cend ~= dend then
+ return nil, Err.new(Err.CORRUPT, "xz compressed size mismatch", dstart)
+ end
+ local un = st.op - ostart
+ if usz and un ~= usz then
+ return nil, Err.new(Err.CORRUPT, "xz uncompressed size mismatch", dstart)
+ end
+ for k = nfilters - 1, 1, -1 do
+ local ok, ferr = Lzma.filter(filters[k].id, st.out, ostart, un, filters[k].props)
+ if not ok then
+ return nil, ferr
+ end
+ end
+ local unpadded = hsize + (cend - dstart) + csize
+ local pe = cend
+ while (pe - p) % 4 ~= 0 do
+ if pe >= e then
+ return nil, Err.new(Err.TRUNCATED, "truncated xz block padding", pe)
+ end
+ if readu8(b, pe) ~= 0 then
+ return nil, Err.new(Err.CORRUPT, "nonzero xz block padding", pe)
+ end
+ pe += 1
+ end
+ if pe + csize > e then
+ return nil, Err.new(Err.TRUNCATED, "truncated xz check", pe)
+ end
+ if check == 1 then
+ if crc(st.out, ostart, un) ~= readu32(b, pe) then
+ return nil, Err.new(Err.CHECKSUM, "xz block CRC-32 mismatch", pe)
+ end
+ elseif check == 4 then
+ local hi, lo = Crc64.of(st.out, ostart, un)
+ if lo ~= readu32(b, pe) or hi ~= readu32(b, pe + 4) then
+ return nil, Err.new(Err.CHECKSUM, "xz block CRC-64 mismatch", pe)
+ end
+ end
+ table.insert(records, { unpadded, un })
+ p = pe + csize
+ end
+ -- index
+ local ip = p
+ local count, q = vli(b, p + 1, e)
+ if not count or count ~= #records then
+ return nil, Err.new(Err.CORRUPT, "xz index record count mismatch", p)
+ end
+ for i = 1, count do
+ local a, u
+ a, q = vli(b, q, e)
+ if not a then
+ return nil, Err.new(Err.TRUNCATED, "truncated xz index", q)
+ end
+ u, q = vli(b, q, e)
+ if not u then
+ return nil, Err.new(Err.TRUNCATED, "truncated xz index", q)
+ end
+ if a ~= records[i][1] or u ~= records[i][2] then
+ return nil, Err.new(Err.CORRUPT, "xz index does not match the blocks", q)
+ end
+ end
+ while (q - ip) % 4 ~= 0 do
+ if q >= e or readu8(b, q) ~= 0 then
+ return nil, Err.new(Err.CORRUPT, "bad xz index padding", q)
+ end
+ q += 1
+ end
+ if q + 4 > e then
+ return nil, Err.new(Err.TRUNCATED, "truncated xz index", q)
+ end
+ if crc(b, ip, q - ip) ~= readu32(b, q) then
+ return nil, Err.new(Err.CHECKSUM, "xz index CRC-32 mismatch", q)
+ end
+ q += 4
+ local isize = q - ip
+ -- footer
+ if q + 12 > e then
+ return nil, Err.new(Err.TRUNCATED, "truncated xz stream footer", q)
+ end
+ if crc(b, q + 4, 6) ~= readu32(b, q) then
+ return nil, Err.new(Err.CHECKSUM, "xz stream footer CRC-32 mismatch", q)
+ end
+ if (readu32(b, q + 4) + 1) * 4 ~= isize then
+ return nil, Err.new(Err.CORRUPT, "xz backward size mismatch", q + 4)
+ end
+ if readu8(b, q + 8) ~= 0 or readu8(b, q + 9) ~= check or buffer.readstring(b, q + 10, 2) ~= "YZ" then
+ return nil, Err.new(Err.CORRUPT, "bad xz stream footer", q + 8)
+ end
+ 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
+ return nil, aerr
+ end
+ local e = o + l
+ local st = Decode.new(l * 4, maxOf(opts))
+ local p = o
+ local nstreams = 0
+ while true do
+ local nxt, err = xzStream(st, b, p, e)
+ if not nxt then
+ return nil, err
+ end
+ nstreams += 1
+ p = nxt
+ -- stream padding: zero bytes in multiples of 4
+ local z = p
+ while z < e and readu8(b, z) == 0 do
+ z += 1
+ end
+ if z == e then
+ if (z - p) % 4 ~= 0 then
+ return nil, Err.new(Err.CORRUPT, "xz stream padding is not a multiple of 4", p)
+ end
+ p = z
+ break
+ end
+ if (z - p) % 4 ~= 0 then
+ return nil, Err.new(Err.CORRUPT, "xz stream padding is not a multiple of 4", p)
+ end
+ p = z
+ end
+ 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
+end
+
+return Lzma
diff --git a/src/Formats/codecs/Lzw/init.luau b/src/Formats/codecs/Lzw/init.luau
new file mode 100644
index 0000000..168ded4
--- /dev/null
+++ b/src/Formats/codecs/Lzw/init.luau
@@ -0,0 +1,282 @@
+--!strict
+--!native
+--!optimize 2
+-- codecs/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.
+--
+-- 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 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).
+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
+
+local Lzw = {}
+
+local MAX_CODES = 4096
+
+-- per-call tables (allocated once: decode / encode are not re-entrant across coroutines, but never yield)
+local prefix = buffer.create(MAX_CODES * 2) -- u16: the code this entry extends
+local suffix = buffer.create(MAX_CODES) -- u8: its last byte
+local first = buffer.create(MAX_CODES) -- u8: its first byte
+local length = buffer.create(MAX_CODES * 2) -- u16: its length
+
+-- ------------------------------------------------------------------------------------------------ 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
+ while p >= o do
+ writeu8(out, p, readu8(suffix, c))
+ c = readu16(prefix, c * 2)
+ p -= 1
+ end
+ else
+ while p >= o do
+ if p < lim then
+ writeu8(out, p, readu8(suffix, c))
+ end
+ c = readu16(prefix, c * 2)
+ p -= 1
+ end
+ end
+end
+
+function Lzw.decode(src: buffer, off: number, len: number, out: buffer, outOff: number, maxOut: number, variant: string, minCodeSize: number?): (number, string?)
+ local n = blen(src)
+ if off < 0 or off > n then
+ return 0, "corrupt"
+ end
+ local e = math.min(off + math.max(0, len), n)
+ local lim = math.min(outOff + math.max(0, maxOut), blen(out))
+ if outOff < 0 then
+ return 0, "corrupt"
+ end
+ local msb = variant == "tiff"
+ local early = 0 -- 1 for TIFF's early change
+ local min = minCodeSize or 8
+ if msb then
+ min = 8
+ early = 1
+ -- old-style TIFF LZW: LSB-first, no early change (libtiff LZWPreDecode's check)
+ if e - off >= 2 and readu8(src, off) == 0 and band(readu8(src, off + 1), 1) == 1 then
+ msb = false
+ early = 0
+ end
+ end
+ if min < 1 or min > 11 then
+ return 0, "corrupt"
+ end
+ local clear = lshift(1, min)
+ local eoi = clear + 1
+ for i = 0, clear - 1 do
+ writeu16(prefix, i * 2, 0)
+ writeu8(suffix, i, band(i, 255))
+ writeu8(first, i, band(i, 255))
+ writeu16(length, i * 2, 1)
+ end
+ local size = min + 1
+ local mask = lshift(1, size) - 1
+ local nextc = clear + 2
+ local prev = -1
+ local o = outOff
+ local p = off
+ local acc, nb = 0, 0
+ while true do
+ -- refill (at most 12 + 7 bits held: below 2^20)
+ while nb < size do
+ if p >= e then
+ return o - outOff, "truncated"
+ end
+ if msb then
+ acc = acc * 256 + readu8(src, p)
+ else
+ acc += lshift(readu8(src, p), nb)
+ end
+ p += 1
+ nb += 8
+ end
+ local c
+ if msb then
+ nb -= size
+ c = band(rshift(acc, nb), mask)
+ acc = band(acc, lshift(1, nb) - 1)
+ else
+ c = band(acc, mask)
+ acc = rshift(acc, size)
+ nb -= size
+ end
+ if c == clear then
+ size = min + 1
+ mask = lshift(1, size) - 1
+ nextc = clear + 2
+ prev = -1
+ elseif c == eoi then
+ return o - outOff, nil
+ else
+ if o >= lim then
+ return o - outOff, nil -- full: the rest (normally just EOI) is ignored
+ end
+ if prev < 0 then
+ if c >= clear then
+ return o - outOff, "corrupt"
+ end
+ writeu8(out, o, readu8(suffix, c))
+ o += 1
+ prev = c
+ else
+ local l
+ if c < nextc then
+ l = readu16(length, c * 2)
+ emit(out, o, c, l, lim)
+ if nextc < MAX_CODES then
+ writeu16(prefix, nextc * 2, prev)
+ writeu8(suffix, nextc, readu8(first, c))
+ writeu8(first, nextc, readu8(first, prev))
+ writeu16(length, nextc * 2, readu16(length, prev * 2) + 1)
+ nextc += 1
+ end
+ elseif c == nextc and nextc < MAX_CODES then
+ -- KwKwK: the new entry is prev + first(prev)
+ local f = readu8(first, prev)
+ writeu16(prefix, nextc * 2, prev)
+ writeu8(suffix, nextc, f)
+ writeu8(first, nextc, f)
+ l = readu16(length, prev * 2) + 1
+ writeu16(length, nextc * 2, l)
+ nextc += 1
+ emit(out, o, c, l, lim)
+ else
+ return o - outOff, "corrupt"
+ end
+ o = math.min(o + l, lim)
+ prev = c
+ end
+ if nextc + early >= lshift(1, size) and size < 12 then
+ size += 1
+ mask = lshift(1, size) - 1
+ end
+ end
+ 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
+
+-- 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)
+ local early = if msb then 1 else 0
+ local symMask = lshift(1, min) - 1
+ local clear = lshift(1, min)
+ local eoi = clear + 1
+ local n = blen(data)
+ off = math.clamp(off, 0, n)
+ local e = math.clamp(off + len, off, n)
+ local cap = (e - off) * 2 + 64
+ local out = buffer.create(cap)
+ local op = 0
+ local acc, nb = 0, 0
+ local size = min + 1
+ local function put(code: number)
+ if op + 4 > cap then
+ cap *= 2
+ local nbuf = buffer.create(cap)
+ buffer.copy(nbuf, 0, out, 0, op)
+ out = nbuf
+ end
+ if msb then
+ acc = acc * lshift(1, size) + code
+ nb += size
+ while nb >= 8 do
+ nb -= 8
+ writeu8(out, op, rshift(acc, nb))
+ op += 1
+ acc = band(acc, lshift(1, nb) - 1)
+ end
+ else
+ acc += lshift(code, nb)
+ nb += size
+ while nb >= 8 do
+ writeu8(out, op, band(acc, 255))
+ op += 1
+ acc = rshift(acc, 8)
+ nb -= 8
+ end
+ end
+ end
+ buffer.fill(hkey, 0, 0, HASH * 4)
+ local nextc = clear + 2
+ put(clear)
+ if e > off then
+ local cur = band(readu8(data, off), symMask)
+ for i = off + 1, e - 1 do
+ local b = band(readu8(data, i), symMask)
+ local key = cur * 256 + b + 1
+ local h = band(cur * 31 + b * 4099, HASH - 1)
+ local found = -1
+ while true do
+ local k = buffer.readi32(hkey, h * 4)
+ if k == 0 then
+ break
+ elseif k == key then
+ found = readu16(hval, h * 2)
+ break
+ end
+ h = band(h + 1, HASH - 1)
+ end
+ if found >= 0 then
+ cur = found
+ else
+ put(cur)
+ if nextc >= MAX_CODES - 2 then
+ put(clear)
+ size = min + 1
+ nextc = clear + 2
+ buffer.fill(hkey, 0, 0, HASH * 4)
+ else
+ buffer.writei32(hkey, h * 4, key)
+ writeu16(hval, h * 2, nextc)
+ nextc += 1
+ if nextc + early > lshift(1, size) and size < 12 then
+ size += 1
+ end
+ end
+ cur = b
+ end
+ end
+ put(cur)
+ -- the decoder adds an entry for this last code too: its width may grow before EOI
+ if nextc < MAX_CODES then
+ nextc += 1
+ if nextc + early > lshift(1, size) and size < 12 then
+ size += 1
+ end
+ end
+ end
+ put(eoi)
+ if nb > 0 then
+ writeu8(out, op, if msb then band(lshift(acc, 8 - nb), 255) else band(acc, 255))
+ op += 1
+ end
+ local res = buffer.create(op)
+ buffer.copy(res, 0, out, 0, op)
+ return res
+end
+
+return Lzw
diff --git a/src/Formats/codecs/MeshFlatten.luau b/src/Formats/codecs/MeshFlatten.luau
new file mode 100644
index 0000000..298a577
--- /dev/null
+++ b/src/Formats/codecs/MeshFlatten.luau
@@ -0,0 +1,556 @@
+--!strict
+-- codecs/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.
+local Types = require("@formats/Types")
+
+local Flatten = {}
+
+local readf32, readf64 = buffer.readf32, buffer.readf64
+local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32
+local readi8, readi16, readi32 = buffer.readi8, buffer.readi16, buffer.readi32
+
+local SIZE = Types.COMPONENT_SIZE
+-- normalized integer types: their scale (raw / scale = the normalized value)
+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)
+ components: number,
+ raw: boolean, -- values are raw integers of a normalized type (unorm8: 0..255), else plain numbers
+ values: { number }, -- count * components
+}
+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
+ vertexCount: number,
+ firstFace: number, -- 0-based offset of the part's faces
+ faceCount: number,
+ identity: boolean, -- no transform was applied
+}
+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
+ 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"
+ end
+ local t, comps, count = acc.type, acc.components, acc.count
+ local size = SIZE[t]
+ if size == nil then
+ return nil, "unknown accessor type " .. tostring(t)
+ end
+ if type(comps) ~= "number" or type(count) ~= "number" or comps < 1 or comps > 16 or count < 0 or comps % 1 ~= 0 or count % 1 ~= 0 then
+ return nil, "bad accessor components / count"
+ end
+ local n = count * comps
+ local d: buffer = acc.data
+ if buffer.len(d) < n * size then
+ return nil, "accessor data shorter than count * components"
+ end
+ local out = table.create(n)
+ if t == "f32" then
+ for i = 0, n - 1 do
+ out[i + 1] = readf32(d, i * 4)
+ end
+ elseif t == "f64" then
+ for i = 0, n - 1 do
+ out[i + 1] = readf64(d, i * 8)
+ end
+ elseif t == "u8" or t == "unorm8" then
+ for i = 0, n - 1 do
+ out[i + 1] = readu8(d, i)
+ end
+ elseif t == "u16" or t == "unorm16" then
+ for i = 0, n - 1 do
+ out[i + 1] = readu16(d, i * 2)
+ end
+ elseif t == "u32" then
+ for i = 0, n - 1 do
+ out[i + 1] = readu32(d, i * 4)
+ end
+ elseif t == "i8" or t == "snorm8" then
+ for i = 0, n - 1 do
+ out[i + 1] = readi8(d, i)
+ end
+ elseif t == "i16" or t == "snorm16" then
+ for i = 0, n - 1 do
+ out[i + 1] = readi16(d, i * 2)
+ end
+ else -- i32
+ for i = 0, n - 1 do
+ out[i + 1] = readi32(d, i * 4)
+ end
+ end
+ local scale = NORM[t]
+ if scale and not raw then
+ local signed = t == "snorm8" or t == "snorm16"
+ for i = 1, n do
+ local v = out[i] / scale
+ out[i] = if signed and v < -1 then -1 else v
+ end
+ end
+ return out, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ transforms
+local IDENTITY = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }
+
+-- column-major 4x4 product a * b
+local function mul(a: { number }, b: { number }): { number }
+ local m = table.create(16, 0)
+ for c = 0, 3 do
+ for r = 0, 3 do
+ local s = 0
+ for k = 0, 3 do
+ s += a[k * 4 + r + 1] * b[c * 4 + k + 1]
+ end
+ m[c * 4 + r + 1] = s
+ end
+ end
+ return m
+end
+
+local function numList(v: any, n: number): boolean
+ if type(v) ~= "table" then
+ return false
+ end
+ for i = 1, n do
+ if type(v[i]) ~= "number" then
+ return false
+ end
+ end
+ 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
+ return nil, "node matrix is not 16 numbers"
+ end
+ local m = table.create(16)
+ for i = 1, 16 do
+ m[i] = node.matrix[i]
+ end
+ return m, nil
+ end
+ local t, q, s = node.translation, node.rotation, node.scale
+ if t == nil and q == nil and s == nil then
+ return nil, nil
+ end
+ if (t ~= nil and not numList(t, 3)) or (q ~= nil and not numList(q, 4)) or (s ~= nil and not numList(s, 3)) then
+ return nil, "bad node translation / rotation / scale"
+ end
+ local x, y, z, w = 0, 0, 0, 1
+ if q then
+ x, y, z, w = q[1], q[2], q[3], q[4]
+ end
+ local sx, sy, sz = 1, 1, 1
+ if s then
+ sx, sy, sz = s[1], s[2], s[3]
+ end
+ local tx, ty, tz = 0, 0, 0
+ if t then
+ tx, ty, tz = t[1], t[2], t[3]
+ end
+ return {
+ (1 - 2 * (y * y + z * z)) * sx,
+ (2 * (x * y + z * w)) * sx,
+ (2 * (x * z - y * w)) * sx,
+ 0,
+ (2 * (x * y - z * w)) * sy,
+ (1 - 2 * (x * x + z * z)) * sy,
+ (2 * (y * z + x * w)) * sy,
+ 0,
+ (2 * (x * z + y * w)) * sz,
+ (2 * (y * z - x * w)) * sz,
+ (1 - 2 * (x * x + y * y)) * sz,
+ 0,
+ tx,
+ ty,
+ tz,
+ 1,
+ },
+ nil
+end
+
+local function isIdentity(m: { number }): boolean
+ for i = 1, 16 do
+ if m[i] ~= IDENTITY[i] then
+ return false
+ end
+ end
+ return true
+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
+ if type(nodes) ~= "table" or type(meshes) ~= "table" then
+ return nil, "scene without nodes / meshes tables"
+ end
+ local function addMesh(mi: any, node: Types.Node?, m: { number }?): string?
+ local mesh = meshes[mi]
+ if type(mesh) ~= "table" or type(mesh.primitives) ~= "table" then
+ return "node refers to a missing mesh " .. tostring(mi)
+ end
+ for _, prim in mesh.primitives do
+ if type(prim) ~= "table" or type(prim.attributes) ~= "table" then
+ return "bad primitive"
+ end
+ table.insert(out, { prim = prim, mesh = mesh, node = node, matrix = m })
+ end
+ return nil
+ end
+ local visiting: { [number]: boolean } = {}
+ local function visit(ni: any, parent: { number }?, depth: number): string?
+ local node = nodes[ni]
+ if type(node) ~= "table" then
+ return "missing node " .. tostring(ni)
+ end
+ if depth > 256 or visiting[ni] then
+ return "node hierarchy is cyclic or too deep"
+ end
+ visiting[ni] = true
+ local m, merr = localMatrix(node)
+ if merr then
+ return merr
+ end
+ local world = if m and parent then mul(parent, m) elseif m then m else parent
+ if node.mesh ~= nil then
+ local e = addMesh(node.mesh, node, world)
+ if e then
+ return e
+ end
+ end
+ if type(node.children) == "table" then
+ for _, c in node.children do
+ local e = visit(c, world, depth + 1)
+ if e then
+ return e
+ end
+ end
+ end
+ visiting[ni] = nil
+ return nil
+ end
+ local roots = scene.roots
+ if type(roots) == "table" and #roots > 0 then
+ for _, ri in roots do
+ local e = visit(ri, nil, 0)
+ if e then
+ return nil, e
+ end
+ end
+ elseif #nodes > 0 then
+ local isChild: { [number]: boolean } = {}
+ for _, n in nodes do
+ if type(n) == "table" and type(n.children) == "table" then
+ for _, c in n.children do
+ isChild[c] = true
+ end
+ end
+ end
+ for i = 1, #nodes do
+ if not isChild[i] then
+ local e = visit(i, nil, 0)
+ if e then
+ return nil, e
+ end
+ end
+ end
+ else
+ for i = 1, #meshes do
+ local e = addMesh(i, nil, nil)
+ if e then
+ return nil, e
+ end
+ end
+ end
+ 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
+ return "points", nil, nil
+ elseif mode == "lines" or mode == "line_strip" or mode == "line_loop" then
+ return "skip", nil, nil
+ end
+ local idx: { number }
+ if prim.indices ~= nil then
+ local v, err = Flatten.numbers(prim.indices, true)
+ if not v then
+ return nil, nil, "indices: " .. tostring(err)
+ end
+ idx = v
+ else
+ idx = table.create(nv)
+ for i = 1, nv do
+ idx[i] = i - 1
+ end
+ end
+ for i = 1, #idx do
+ local v = idx[i]
+ if v < 0 or v >= nv or v % 1 ~= 0 then
+ return nil, nil, string.format("index %s out of range (%d vertices)", tostring(v), nv)
+ end
+ end
+ if mode == "triangles" then
+ local n = #idx - #idx % 3
+ if n ~= #idx then
+ local c = table.create(n)
+ table.move(idx, 1, n, 1, c)
+ idx = c
+ end
+ return false, idx, nil
+ elseif mode == "polygons" then
+ if prim.faces == nil then
+ return nil, nil, "polygons primitive without faces"
+ end
+ local sizes, err = Flatten.numbers(prim.faces, true)
+ if not sizes then
+ return nil, nil, "faces: " .. tostring(err)
+ end
+ local total = 0
+ for i = 1, #sizes do
+ local s = sizes[i]
+ if s < 0 or s % 1 ~= 0 then
+ return nil, nil, "bad face size"
+ end
+ total += s
+ end
+ if total ~= #idx then
+ return nil, nil, "face sizes do not add up to the index count"
+ end
+ return sizes, idx, nil
+ elseif mode == "triangle_strip" or mode == "triangle_fan" then
+ local c = {}
+ for i = 3, #idx do
+ if mode == "triangle_fan" then
+ table.insert(c, idx[1])
+ table.insert(c, idx[i - 1])
+ table.insert(c, idx[i])
+ elseif i % 2 == 1 then
+ table.insert(c, idx[i - 2])
+ table.insert(c, idx[i - 1])
+ table.insert(c, idx[i])
+ else
+ table.insert(c, idx[i - 1])
+ table.insert(c, idx[i - 2])
+ table.insert(c, idx[i])
+ end
+ end
+ return false, c, nil
+ end
+ 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
+ return 0
+ end
+ return if raw and NORM[t] then NORM[t] else 1
+end
+
+local function f32(v: number): number
+ local b = buffer.create(4)
+ buffer.writef32(b, 0, v)
+ 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"
+ end
+ local list, lerr = instances(scene)
+ if not list then
+ 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 } = {}
+ for _, inst in list do
+ local mode = inst.prim.mode or "triangles"
+ if mode ~= "lines" and mode ~= "line_strip" and mode ~= "line_loop" then
+ local pos = inst.prim.attributes.POSITION
+ if type(pos) ~= "table" then
+ return nil, "primitive without POSITION"
+ end
+ table.insert(used, inst)
+ for name, acc in inst.prim.attributes do
+ if type(name) == "string" and (name == "POSITION" or keep(name)) and type(acc) == "table" then
+ local t = acc.type
+ if types[name] == nil then
+ types[name] = t
+ elseif types[name] ~= t then
+ types[name] = "f32"
+ end
+ comps[name] = math.max(comps[name] or 0, tonumber(acc.components) or 0)
+ end
+ end
+ end
+ end
+ if (comps.POSITION or 3) < 3 then
+ return nil, "POSITION needs 3 components"
+ end
+ local attrs: { [string]: Attr } = {}
+ for name, t in types do
+ local raw = NORM[t] ~= nil
+ if name == "POSITION" or name == "NORMAL" then
+ raw = false
+ end
+ attrs[name] = { type = if name == "POSITION" or name == "NORMAL" then "f32" else t, components = if name == "POSITION" or name == "NORMAL" then 3 else comps[name], raw = raw, values = {} }
+ end
+ local merged: Merged = { count = 0, attrs = attrs, sizes = nil, corners = {}, parts = {} }
+ local sizes: { number } = {}
+ local anyFaces = false
+ local corners = merged.corners
+ for _, inst in used do
+ local prim: any = inst.prim
+ local posAcc = prim.attributes.POSITION
+ local nv = tonumber(posAcc.count) or 0
+ local m = inst.matrix
+ local identity = m == nil or isIdentity(m :: { number })
+ local info: PartInfo = { prim = prim, mesh = inst.mesh, node = inst.node, firstVertex = merged.count, vertexCount = nv, firstFace = #sizes, faceCount = 0, identity = identity }
+ for name, a in attrs do
+ local acc = prim.attributes[name]
+ local dst = a.values
+ local n0 = #dst
+ local ac = a.components
+ if acc == nil then
+ local f = fill(name, a.type, a.raw)
+ for i = 1, nv * ac do
+ dst[n0 + i] = f
+ end
+ else
+ if acc.count ~= nv then
+ return nil, name .. " count differs from POSITION"
+ end
+ local vals, err = Flatten.numbers(acc, a.raw and acc.type == a.type)
+ if not vals then
+ return nil, name .. ": " .. tostring(err)
+ end
+ local sc = acc.components
+ if a.raw and acc.type ~= a.type then
+ return nil, name .. ": mixed accessor types"
+ end
+ local f = fill(name, a.type, a.raw)
+ if name == "POSITION" and not identity then
+ local mm = m :: { number }
+ for i = 0, nv - 1 do
+ local x, y, z = vals[i * sc + 1], vals[i * sc + 2], vals[i * sc + 3]
+ dst[n0 + i * 3 + 1] = f32(mm[1] * x + mm[5] * y + mm[9] * z + mm[13])
+ dst[n0 + i * 3 + 2] = f32(mm[2] * x + mm[6] * y + mm[10] * z + mm[14])
+ dst[n0 + i * 3 + 3] = f32(mm[3] * x + mm[7] * y + mm[11] * z + mm[15])
+ end
+ elseif name == "NORMAL" and not identity and sc >= 3 then
+ local mm = m :: { number }
+ -- the cofactor matrix of the upper 3x3 = det * inverse transpose; the sign of det keeps the direction
+ local a1, a2, a3, b1, b2, b3, c1, c2, c3 = mm[1], mm[2], mm[3], mm[5], mm[6], mm[7], mm[9], mm[10], mm[11]
+ local n11, n12, n13 = b2 * c3 - b3 * c2, b3 * c1 - b1 * c3, b1 * c2 - b2 * c1
+ local n21, n22, n23 = c2 * a3 - c3 * a2, c3 * a1 - c1 * a3, c1 * a2 - c2 * a1
+ local n31, n32, n33 = a2 * b3 - a3 * b2, a3 * b1 - a1 * b3, a1 * b2 - a2 * b1
+ local sgn = if a1 * n11 + a2 * n12 + a3 * n13 < 0 then -1 else 1
+ for i = 0, nv - 1 do
+ local x, y, z = vals[i * sc + 1], vals[i * sc + 2], vals[i * sc + 3]
+ -- column j of the cofactor matrix multiplies component j: (inverse transpose) * n
+ local nx = n11 * x + n21 * y + n31 * z
+ local ny = n12 * x + n22 * y + n32 * z
+ local nz = n13 * x + n23 * y + n33 * z
+ local l = math.sqrt(nx * nx + ny * ny + nz * nz)
+ if l > 0 then
+ nx, ny, nz = sgn * nx / l, sgn * ny / l, sgn * nz / l
+ end
+ dst[n0 + i * 3 + 1] = f32(nx)
+ dst[n0 + i * 3 + 2] = f32(ny)
+ dst[n0 + i * 3 + 3] = f32(nz)
+ end
+ else
+ for i = 0, nv - 1 do
+ for c = 1, ac do
+ dst[n0 + i * ac + c] = if c <= sc then vals[i * sc + c] else f
+ end
+ end
+ end
+ end
+ end
+ local fs, cs, ferr = faces(prim, nv)
+ if ferr then
+ return nil, ferr
+ end
+ local flip = false
+ if not identity then
+ local mm = m :: { number }
+ local det = mm[1] * (mm[6] * mm[11] - mm[7] * mm[10]) - mm[5] * (mm[2] * mm[11] - mm[3] * mm[10]) + mm[9] * (mm[2] * mm[7] - mm[3] * mm[6])
+ flip = det < 0
+ end
+ if fs ~= "points" and fs ~= "skip" then
+ anyFaces = true
+ local base = merged.count
+ local cl: { number } = cs
+ local p = 0
+ local nf = if fs then #fs else #cl // 3
+ for f = 1, nf do
+ local s = if fs then fs[f] else 3
+ if triangulate then
+ for k = 2, s - 1 do
+ table.insert(sizes, 3)
+ local a, b, c = cl[p + 1], cl[p + k], cl[p + k + 1]
+ if flip then
+ b, c = c, b
+ end
+ table.insert(corners, base + a)
+ table.insert(corners, base + b)
+ table.insert(corners, base + c)
+ end
+ else
+ table.insert(sizes, s)
+ if flip then
+ table.insert(corners, base + cl[p + 1])
+ for k = s, 2, -1 do
+ table.insert(corners, base + cl[p + k])
+ end
+ else
+ for k = 1, s do
+ table.insert(corners, base + cl[p + k])
+ end
+ end
+ end
+ p += s
+ end
+ end
+ info.faceCount = #sizes - info.firstFace
+ merged.count += nv
+ table.insert(merged.parts, info)
+ end
+ merged.sizes = if anyFaces then sizes else nil
+ return merged, nil
+end
+
+return Flatten
diff --git a/src/Formats/codecs/Quantize/init.luau b/src/Formats/codecs/Quantize/init.luau
new file mode 100644
index 0000000..df4dd53
--- /dev/null
+++ b/src/Formats/codecs/Quantize/init.luau
@@ -0,0 +1,483 @@
+--!strict
+--!native
+--!optimize 2
+-- codecs/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.
+local readu8, writeu8 = buffer.readu8, buffer.writeu8
+local readu32, writeu32, readf64, writef64 = buffer.readu32, buffer.writeu32, buffer.readf64, buffer.writef64
+local floor = math.floor
+local blen = buffer.len
+
+local Quantize = {}
+
+export type Color = { number } -- { r, g, b, a } 0..255
+export type PaletteOptions = {
+ method: ("mediancut" | "octree")?, -- default "mediancut"
+}
+export type MapOptions = {
+ dither: boolean?, -- Floyd-Steinberg error diffusion (default false)
+ transparentIndex: number?, -- 0-based index for pixels with alpha < 128 (default: none)
+}
+
+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)
+ local sums = buffer.create(BINS * 24)
+ for i = 0, n - 1 do
+ local o = i * 4
+ if readu8(pixels, o + 3) >= 128 then
+ local r, g, b = readu8(pixels, o), readu8(pixels, o + 1), readu8(pixels, o + 2)
+ local bin = (r // 8) * 1024 + (g // 8) * 32 + b // 8
+ writeu32(cnt, bin * 4, readu32(cnt, bin * 4) + 1)
+ local s = bin * 24
+ writef64(sums, s, readf64(sums, s) + r)
+ writef64(sums, s + 8, readf64(sums, s + 8) + g)
+ writef64(sums, s + 16, readf64(sums, s + 16) + b)
+ end
+ end
+ return cnt, sums
+end
+
+local function mean(cnt: buffer, sums: buffer, bins: { number }, lo: number, hi: number): Color
+ local n, r, g, b = 0, 0, 0, 0
+ for i = lo, hi do
+ local bin = bins[i]
+ n += readu32(cnt, bin * 4)
+ r += readf64(sums, bin * 24)
+ g += readf64(sums, bin * 24 + 8)
+ b += readf64(sums, bin * 24 + 16)
+ end
+ if n == 0 then
+ return { 0, 0, 0, 255 }
+ end
+ 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
+ if readu32(cnt, bin * 4) > 0 then
+ table.insert(bins, bin)
+ end
+ end
+ 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
+ return bin // 1024
+ elseif c == 1 then
+ return (bin // 32) % 32
+ end
+ 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
+ local bin = bins[i]
+ n += readu32(cnt, bin * 4)
+ for c = 0, 2 do
+ local v = channel(bin, c)
+ if v < mins[c + 1] then
+ mins[c + 1] = v
+ end
+ if v > maxs[c + 1] then
+ maxs[c + 1] = v
+ end
+ end
+ end
+ local best, range = 0, -1
+ for c = 0, 2 do
+ local rg = maxs[c + 1] - mins[c + 1]
+ if rg > range then
+ best, range = c, rg
+ end
+ end
+ return best, range, n
+ end
+ local function scored(lo: number, hi: number): { number }
+ local c, range, n = stats({ lo, hi })
+ return { lo, hi, c, if hi > lo then range * math.sqrt(n) else 0 }
+ end
+ boxes[1] = scored(1, #bins)
+ while #boxes < maxColors do
+ -- split the box with the largest range * sqrt(count) score (ties: the first)
+ local pick, pickScore = 0, 0
+ for i, box in boxes do
+ if box[4] > pickScore then
+ pick, pickScore = i, box[4]
+ end
+ end
+ if pick == 0 then
+ break
+ end
+ local box = boxes[pick]
+ local lo, hi, c = box[1], box[2], box[3]
+ -- sort the range by the channel, ties by bin number: unique numeric keys, no comparator
+ local keys = table.create(hi - lo + 1)
+ for i = lo, hi do
+ keys[i - lo + 1] = channel(bins[i], c) * BINS + bins[i]
+ end
+ table.sort(keys)
+ local total = 0
+ for i = 1, #keys do
+ local bin = keys[i] % BINS
+ bins[lo + i - 1] = bin
+ total += readu32(cnt, bin * 4)
+ end
+ -- the weighted median, keeping both halves non-empty
+ local acc, cut = 0, lo
+ for i = lo, hi - 1 do
+ acc += readu32(cnt, bins[i] * 4)
+ cut = i
+ if acc * 2 >= total then
+ break
+ end
+ end
+ boxes[pick] = scored(lo, cut)
+ table.insert(boxes, scored(cut + 1, hi))
+ end
+ local pal = table.create(#boxes)
+ for i, box in boxes do
+ pal[i] = mean(cnt, sums, bins, box[1], box[2])
+ end
+ return pal
+end
+
+-- ------------------------------------------------------------------------------------------------ octree
+-- over the histogram bins: 5 levels (one bit of each channel per level). Nodes are array slots.
+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 sr: { number }, sg: { number }, sb: { number } = {}, {}, {}
+ local leaf: { boolean } = {}
+ local level: { number } = {}
+ local nodes = 1
+ n[1], sr[1], sg[1], sb[1], leaf[1], level[1] = 0, 0, 0, 0, false, 0
+ for k = 1, 8 do
+ child[k] = 0
+ end
+ local byLevel: { { number } } = { {}, {}, {}, {}, {} } -- inner nodes per level 0..4, creation order
+ table.insert(byLevel[1], 1)
+ local leaves = 0
+ for bin = 0, BINS - 1 do
+ local c = readu32(cnt, bin * 4)
+ if c > 0 then
+ local r5, g5, b5 = bin // 1024, (bin // 32) % 32, bin % 32
+ local node = 1
+ for lv = 0, 4 do
+ local sh = 4 - lv
+ local k = ((r5 // 2 ^ sh) % 2) * 4 + ((g5 // 2 ^ sh) % 2) * 2 + (b5 // 2 ^ sh) % 2
+ local slot = (node - 1) * 8 + k + 1
+ local nx = child[slot]
+ if nx == 0 then
+ nodes += 1
+ nx = nodes
+ child[slot] = nx
+ for j = 1, 8 do
+ child[(nx - 1) * 8 + j] = 0
+ end
+ n[nx], sr[nx], sg[nx], sb[nx], level[nx] = 0, 0, 0, 0, lv + 1
+ leaf[nx] = lv == 4
+ if lv == 4 then
+ leaves += 1
+ else
+ table.insert(byLevel[lv + 2], nx)
+ end
+ end
+ node = nx
+ end
+ n[node] += c
+ sr[node] += readf64(sums, bin * 24)
+ sg[node] += readf64(sums, bin * 24 + 8)
+ sb[node] += readf64(sums, bin * 24 + 16)
+ end
+ 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
+ local ch = child[slot]
+ if ch ~= 0 then
+ n[node] += n[ch]
+ sr[node] += sr[ch]
+ sg[node] += sg[ch]
+ sb[node] += sb[ch]
+ child[slot] = 0
+ merged += 1
+ end
+ end
+ leaf[node] = true
+ return merged - 1
+ end
+ local function subtotal(node: number): number
+ local s = 0
+ for k = 1, 8 do
+ local ch = child[(node - 1) * 8 + k]
+ if ch ~= 0 then
+ s += n[ch]
+ end
+ end
+ return s
+ end
+ for lv = 5, 1, -1 do
+ if leaves <= maxColors then
+ break
+ end
+ local list = byLevel[lv]
+ local order = table.create(#list)
+ for i, node in list do
+ order[i] = { node, subtotal(node), i }
+ end
+ table.sort(order, function(a: { number }, b: { number }): boolean
+ if a[2] ~= b[2] then
+ return a[2] < b[2]
+ end
+ return a[3] < b[3]
+ end)
+ for _, e in order do
+ if leaves <= maxColors then
+ break
+ end
+ 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
+ local c = n[node]
+ if c > 0 then
+ table.insert(pal, { floor(sr[node] / c + 0.5), floor(sg[node] / c + 0.5), floor(sb[node] / c + 0.5), 255 })
+ end
+ return
+ end
+ for k = 1, 8 do
+ local ch = child[(node - 1) * 8 + k]
+ if ch ~= 0 then
+ walk(ch)
+ end
+ end
+ end
+ walk(1)
+ -- the root itself can end up a leaf with everything (maxColors 1)
+ while #pal > maxColors do
+ table.remove(pal)
+ end
+ 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
+ for i = 0, npx - 1 do
+ local o = i * 4
+ if readu8(pixels, o + 3) >= 128 then
+ local r, g, b = readu8(pixels, o), readu8(pixels, o + 1), readu8(pixels, o + 2)
+ local key = r * 65536 + g * 256 + b
+ if not seen[key] then
+ if #exact >= maxc then
+ over = true
+ break
+ end
+ seen[key] = true
+ table.insert(exact, { r, g, b, 255 })
+ end
+ end
+ end
+ if not over then
+ return exact, true
+ end
+ local cnt, sums = count(pixels, npx)
+ local method = opts and opts.method or "mediancut"
+ if method == "octree" and maxc >= 8 then -- below 8 the octree can only fold to a single colour
+ return octree(cnt, sums, maxc), false
+ end
+ 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)
+ end
+ local npx = w * h
+ 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, pg, pb, pi = {}, {}, {}, {}
+ for i, c in palette do
+ if tidx == nil or i - 1 ~= tidx then
+ table.insert(pr, c[1] or 0)
+ table.insert(pg, c[2] or 0)
+ table.insert(pb, c[3] or 0)
+ table.insert(pi, i - 1)
+ end
+ end
+ local np = #pr
+ -- sorted by green (the heaviest weight), so the search can stop once 4 * dg^2 alone is worse than the best
+ do
+ local order = table.create(np)
+ for k = 1, np do
+ order[k] = pg[k] * 65536 + k
+ end
+ table.sort(order)
+ local r2, g2, b2, i2 = table.create(np), table.create(np), table.create(np), table.create(np)
+ for k = 1, np do
+ local j = order[k] % 65536
+ r2[k], g2[k], b2[k], i2[k] = pr[j], pg[j], pb[j], pi[j]
+ 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
+ do
+ local k = 1
+ for g = 0, 255 do
+ while k <= np and pg[k] < g do
+ k += 1
+ end
+ startAt[g + 1] = k
+ end
+ end
+ if np == 0 then
+ if tidx then
+ buffer.fill(out, 0, math.clamp(tidx, 0, 255), npx)
+ end
+ return out
+ end
+ local cache: { [number]: number } = {}
+ local function nearest(r: number, g: number, b: number): number
+ local key = r * 65536 + g * 256 + b
+ local hit = cache[key]
+ if hit then
+ return hit
+ end
+ local best, bd = 1, math.huge
+ local up = startAt[math.clamp(g, 0, 255) + 1]
+ local down = up - 1
+ while up <= np or down >= 1 do
+ if up <= np then
+ local dg = pg[up] - g
+ if dg * dg * 4 >= bd then
+ up = np + 1
+ else
+ local dr, db = r - pr[up], b - pb[up]
+ local d = dr * dr * 2 + dg * dg * 4 + db * db * 3
+ if d < bd then
+ best, bd = up, d
+ end
+ up += 1
+ end
+ end
+ if down >= 1 then
+ local dg = g - pg[down]
+ if dg * dg * 4 >= bd then
+ down = 0
+ else
+ local dr, db = r - pr[down], b - pb[down]
+ local d = dr * dr * 2 + dg * dg * 4 + db * db * 3
+ if d < bd then
+ best, bd = down, d
+ end
+ down -= 1
+ end
+ end
+ end
+ cache[key] = best
+ return best
+ end
+ local tbyte = if tidx then math.clamp(tidx, 0, 255) else 0
+ if not dither then
+ for i = 0, npx - 1 do
+ local o = i * 4
+ if tidx and readu8(pixels, o + 3) < 128 then
+ writeu8(out, i, tbyte)
+ else
+ writeu8(out, i, pi[nearest(readu8(pixels, o), readu8(pixels, o + 1), readu8(pixels, o + 2))])
+ end
+ 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
+ buffer.fill(nxt, 0, 0, rowLen)
+ for x = 0, w - 1 do
+ local i = y * w + x
+ local o = i * 4
+ if tidx and readu8(pixels, o + 3) < 128 then
+ writeu8(out, i, tbyte)
+ else
+ local e = (x + 1) * 24
+ local r = math.clamp(floor(readu8(pixels, o) + readf64(cur, e) + 0.5), 0, 255)
+ local g = math.clamp(floor(readu8(pixels, o + 1) + readf64(cur, e + 8) + 0.5), 0, 255)
+ local b = math.clamp(floor(readu8(pixels, o + 2) + readf64(cur, e + 16) + 0.5), 0, 255)
+ local k = nearest(r, g, b)
+ writeu8(out, i, pi[k])
+ local er, eg, eb = r - pr[k], g - pg[k], b - pb[k]
+ -- 7/16 right, 3/16 down-left, 5/16 down, 1/16 down-right
+ writef64(cur, e + 24, readf64(cur, e + 24) + er * 0.4375)
+ writef64(cur, e + 32, readf64(cur, e + 32) + eg * 0.4375)
+ writef64(cur, e + 40, readf64(cur, e + 40) + eb * 0.4375)
+ writef64(nxt, e - 24, readf64(nxt, e - 24) + er * 0.1875)
+ writef64(nxt, e - 16, readf64(nxt, e - 16) + eg * 0.1875)
+ writef64(nxt, e - 8, readf64(nxt, e - 8) + eb * 0.1875)
+ writef64(nxt, e, readf64(nxt, e) + er * 0.3125)
+ writef64(nxt, e + 8, readf64(nxt, e + 8) + eg * 0.3125)
+ writef64(nxt, e + 16, readf64(nxt, e + 16) + eb * 0.3125)
+ writef64(nxt, e + 24, readf64(nxt, e + 24) + er * 0.0625)
+ writef64(nxt, e + 32, readf64(nxt, e + 32) + eg * 0.0625)
+ writef64(nxt, e + 40, readf64(nxt, e + 40) + eb * 0.0625)
+ end
+ end
+ cur, nxt = nxt, cur
+ end
+ 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
+ end
+ return Quantize.map(pixels, w, h, pal, mo), pal, exact
+end
+
+return Quantize
diff --git a/src/Formats/codecs/Raster.luau b/src/Formats/codecs/Raster.luau
new file mode 100644
index 0000000..953336e
--- /dev/null
+++ b/src/Formats/codecs/Raster.luau
@@ -0,0 +1,744 @@
+--!strict
+--!native
+--!optimize 2
+-- codecs/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("@formats/codecs/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.
+local Raster = {}
+
+local floor, ceil, min, max, abs, sqrt = math.floor, math.ceil, math.min, math.max, math.abs, math.sqrt
+local readf32, writef32, readu8, writeu8 = buffer.readf32, buffer.writef32, buffer.readu8, buffer.writeu8
+local bcreate = buffer.create
+
+export type Cmd = { op: string, [number]: number }
+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)
+}
+
+local LIMIT = 1e7 -- coordinates beyond this (device pixels) are treated as broken
+
+-- ------------------------------------------------------------------------------------------------ transforms
+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],
+ m[2] * n[1] + m[4] * n[2],
+ m[1] * n[3] + m[3] * n[4],
+ m[2] * n[3] + m[4] * n[4],
+ m[1] * n[5] + m[3] * n[6] + m[5],
+ m[2] * n[5] + m[4] * n[6] + m[6],
+ }
+end
+function Raster.translate(tx: number, ty: number): Transform
+ return { 1, 0, 0, 1, tx, ty }
+end
+function Raster.scale(sx: number, sy: number?): Transform
+ return { sx, 0, 0, sy or sx, 0, 0 }
+end
+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
+ return nil
+ end
+ local id = 1 / det
+ 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
+function Builder.moveTo(self: Builder, x: number, y: number): Builder
+ table.insert(self.cmds, { op = "moveTo", x, y })
+ return self
+end
+function Builder.lineTo(self: Builder, x: number, y: number): Builder
+ table.insert(self.cmds, { op = "lineTo", x, y })
+ return self
+end
+function Builder.quadTo(self: Builder, cx: number, cy: number, x: number, y: number): Builder
+ table.insert(self.cmds, { op = "quadTo", cx, cy, x, y })
+ return self
+end
+function Builder.cubicTo(self: Builder, c1x: number, c1y: number, c2x: number, c2y: number, x: number, y: number): Builder
+ table.insert(self.cmds, { op = "cubicTo", c1x, c1y, c2x, c2y, x, y })
+ return self
+end
+function Builder.close(self: Builder): Builder
+ table.insert(self.cmds, { op = "close" })
+ 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
+function Builder.ellipse(self: Builder, cx: number, cy: number, rx: number, ry: number): Builder
+ local k = 0.5522847498307936 -- 4/3 (sqrt 2 - 1): cubic quarter circle
+ self:moveTo(cx + rx, cy)
+ self:cubicTo(cx + rx, cy + ry * k, cx + rx * k, cy + ry, cx, cy + ry)
+ self:cubicTo(cx - rx * k, cy + ry, cx - rx, cy + ry * k, cx - rx, cy)
+ self:cubicTo(cx - rx, cy - ry * k, cx - rx * k, cy - ry, cx, cy - ry)
+ self:cubicTo(cx + rx * k, cy - ry, cx + rx, cy - ry * k, cx + rx, cy)
+ return self:close()
+end
+
+local function commands(path: any): Path?
+ if type(path) ~= "table" then
+ return nil
+ end
+ if type(path.cmds) == "table" then
+ return path.cmds
+ end
+ 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
+ end
+ for i = 1, n do
+ local v = c[i]
+ if type(v) ~= "number" or v ~= v or abs(v) > 1e15 then
+ return false
+ end
+ end
+ 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 } } = {}
+ if not cmds then
+ return polys
+ end
+ local m = transform or Raster.IDENTITY
+ local a, b, c, d, e, f = m[1], m[2], m[3], m[4], m[5], m[6]
+ if type(a) ~= "number" or type(b) ~= "number" or type(c) ~= "number" or type(d) ~= "number" or type(e) ~= "number" or type(f) ~= "number" then
+ return polys
+ end
+ local tol = tolerance or 0.1
+ if type(tol) ~= "number" or not (tol > 0.001) then
+ 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 bx0, by0, bx1, by1 = math.huge, math.huge, -math.huge, -math.huge
+ local function point(x: number, y: number)
+ local poly = cur :: { number }
+ local n = #poly
+ poly[n + 1] = x
+ poly[n + 2] = y
+ if x < bx0 then
+ bx0 = x
+ end
+ if x > bx1 then
+ bx1 = x
+ end
+ if y < by0 then
+ by0 = y
+ end
+ if y > by1 then
+ by1 = y
+ end
+ end
+ local function start(x: number, y: number)
+ if cur and #cur >= minLen then
+ table.insert(polys, cur)
+ end
+ cur = {}
+ point(x, y)
+ sx, sy = x, y
+ px, py = x, y
+ end
+ for _, cmd in cmds do
+ local op = if type(cmd) == "table" then cmd.op else nil
+ if op == "moveTo" then
+ if operands(cmd, 2) then
+ start(a * cmd[1] + c * cmd[2] + e, b * cmd[1] + d * cmd[2] + f)
+ end
+ elseif op == "lineTo" then
+ if operands(cmd, 2) then
+ if not cur then
+ start(px, py)
+ end
+ px, py = a * cmd[1] + c * cmd[2] + e, b * cmd[1] + d * cmd[2] + f
+ point(px, py)
+ end
+ elseif op == "quadTo" then
+ if operands(cmd, 4) then
+ if not cur then
+ start(px, py)
+ end
+ local x1, y1 = a * cmd[1] + c * cmd[2] + e, b * cmd[1] + d * cmd[2] + f
+ local x2, y2 = a * cmd[3] + c * cmd[4] + e, b * cmd[3] + d * cmd[4] + f
+ local ddx, ddy = px - 2 * x1 + x2, py - 2 * y1 + y2
+ local n = ceil(sqrt(sqrt(ddx * ddx + ddy * ddy) * 0.25 / tol))
+ n = if n ~= n then 1 else max(1, min(n, 500))
+ local x0, y0 = px, py
+ for i = 1, n - 1 do
+ local t = i / n
+ local u = 1 - t
+ point(u * u * x0 + 2 * u * t * x1 + t * t * x2, u * u * y0 + 2 * u * t * y1 + t * t * y2)
+ end
+ point(x2, y2)
+ px, py = x2, y2
+ end
+ elseif op == "cubicTo" then
+ if operands(cmd, 6) then
+ if not cur then
+ start(px, py)
+ end
+ local x1, y1 = a * cmd[1] + c * cmd[2] + e, b * cmd[1] + d * cmd[2] + f
+ local x2, y2 = a * cmd[3] + c * cmd[4] + e, b * cmd[3] + d * cmd[4] + f
+ local x3, y3 = a * cmd[5] + c * cmd[6] + e, b * cmd[5] + d * cmd[6] + f
+ local ax, ay = px - 2 * x1 + x2, py - 2 * y1 + y2
+ local bxx, byy = x1 - 2 * x2 + x3, y1 - 2 * y2 + y3
+ local dd = max(sqrt(ax * ax + ay * ay), sqrt(bxx * bxx + byy * byy))
+ local n = ceil(sqrt(dd * 0.75 / tol))
+ n = if n ~= n then 1 else max(1, min(n, 500))
+ local x0, y0 = px, py
+ for i = 1, n - 1 do
+ local t = i / n
+ local u = 1 - t
+ local w0, w1, w2, w3 = u * u * u, 3 * u * u * t, 3 * u * t * t, t * t * t
+ point(w0 * x0 + w1 * x1 + w2 * x2 + w3 * x3, w0 * y0 + w1 * y1 + w2 * y2 + w3 * y3)
+ end
+ point(x3, y3)
+ px, py = x3, y3
+ end
+ elseif op == "close" then
+ if cur then
+ if #cur >= minLen then
+ table.insert(polys, cur)
+ end
+ cur = nil
+ px, py = sx, sy
+ end
+ end
+ end
+ if cur and #cur >= minLen then
+ table.insert(polys, cur)
+ end
+ if #polys == 0 or bx0 ~= bx0 or by0 ~= by0 or bx1 ~= bx1 or by1 ~= by1 then
+ return polys
+ end
+ return polys, bx0, by0, bx1, by1
+end
+
+function Raster.flatten(path: any, transform: Transform?, tolerance: number?): ({ { number } }, number?, number?, number?, 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)
+local function line(acc: buffer, S: number, H: number, x0: number, y0: number, x1: number, y1: number)
+ if y0 == y1 then
+ return
+ end
+ local W = S - 2
+ local xl, xr = 0, W -- x stays in [0, W] (rounding in the splits and in x + dxdy * dy must never index outside)
+ local dir = 1
+ if y0 > y1 then
+ dir = -1
+ x0, x1 = x1, x0
+ y0, y1 = y1, y0
+ end
+ if y1 <= 0 or y0 >= H then
+ return
+ end
+ local dxdy = (x1 - x0) / (y1 - y0)
+ local x = x0
+ if y0 < 0 then
+ x -= y0 * dxdy
+ end
+ local ystart = max(0, floor(y0))
+ local yend = min(H, ceil(y1)) - 1
+ for y = ystart, yend do
+ local ls = y * S
+ local dy = min(y + 1, y1) - max(y, y0)
+ local xnext = x + dxdy * dy
+ if xnext < xl then
+ xnext = xl
+ elseif xnext > xr then
+ xnext = xr
+ end
+ if x < xl then
+ x = xl
+ elseif x > xr then
+ x = xr
+ end
+ local dd = dy * dir
+ local xa, xb = x, xnext
+ if xa > xb then
+ xa, xb = xb, xa
+ end
+ local xaf = floor(xa)
+ local xai = xaf
+ local xbc = ceil(xb)
+ local xbi = xbc
+ if xbi <= xai + 1 then
+ local xmf = 0.5 * (x + xnext) - xaf
+ local o = (ls + xai) * 4
+ writef32(acc, o, readf32(acc, o) + dd - dd * xmf)
+ writef32(acc, o + 4, readf32(acc, o + 4) + dd * xmf)
+ else
+ local s = 1 / (xb - xa)
+ local x0f = xa - xaf
+ local a0 = 0.5 * s * (1 - x0f) * (1 - x0f)
+ local x1f = xb - xbc + 1
+ local am = 0.5 * s * x1f * x1f
+ local o = (ls + xai) * 4
+ writef32(acc, o, readf32(acc, o) + dd * a0)
+ if xbi == xai + 2 then
+ writef32(acc, o + 4, readf32(acc, o + 4) + dd * (1 - a0 - am))
+ else
+ local a1 = s * (1.5 - x0f)
+ writef32(acc, o + 4, readf32(acc, o + 4) + dd * (a1 - a0))
+ local ds = dd * s
+ for xi = xai + 2, xbi - 2 do
+ local q = (ls + xi) * 4
+ writef32(acc, q, readf32(acc, q) + ds)
+ end
+ local a2 = a1 + (xbi - xai - 3) * s
+ local q = (ls + xbi - 1) * 4
+ writef32(acc, q, readf32(acc, q) + dd * (1 - a2 - am))
+ end
+ local q = (ls + xbi) * 4
+ writef32(acc, q, readf32(acc, q) + dd * am)
+ end
+ x = xnext
+ 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)
+local function clampx(x: number, W: number): number
+ return if x < 0 then 0 elseif x > W then W else x
+end
+local function edge(acc: buffer, S: number, W: number, H: number, x0: number, y0: number, x1: number, y1: number)
+ if y0 == y1 or not (abs(x0) < LIMIT and abs(y0) < LIMIT and abs(x1) < LIMIT and abs(y1) < LIMIT) then
+ return -- horizontal, or non-finite (NaN fails every comparison)
+ end
+ if (y0 <= 0 and y1 <= 0) or (y0 >= H and y1 >= H) then
+ return
+ end
+ local dx = x1 - x0
+ local ta, tb = 2, 2 -- parameters of the crossings with x = 0 and x = W (2 = none)
+ if dx ~= 0 then
+ local t0 = (0 - x0) / dx
+ local tw = (W - x0) / dx
+ if t0 > 0 and t0 < 1 then
+ ta = t0
+ end
+ if tw > 0 and tw < 1 then
+ tb = tw
+ end
+ if ta > tb then
+ ta, tb = tb, ta
+ end
+ end
+ local dy = y1 - y0
+ local px, py = x0, y0
+ if ta < 1 then
+ local qx, qy = x0 + dx * ta, y0 + dy * ta
+ line(acc, S, H, clampx(px, W), py, clampx(qx, W), qy)
+ px, py = qx, qy
+ end
+ if tb < 1 then
+ local qx, qy = x0 + dx * tb, y0 + dy * tb
+ line(acc, S, H, clampx(px, W), py, clampx(qx, W), qy)
+ px, py = qx, qy
+ end
+ 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)
+ if not bx0 then
+ return nil
+ end
+ if abs(bx0 :: number) > LIMIT or abs(by0 :: number) > LIMIT or abs(bx1 :: number) > LIMIT or abs(by1 :: number) > LIMIT then
+ return nil, "coordinates out of range"
+ end
+ local X0, Y0, X1, Y1 = floor(bx0 :: number), floor(by0 :: number), ceil(bx1 :: number), ceil(by1 :: number)
+ local clip = o.clip
+ if type(clip) == "table" and type(clip[1]) == "number" and type(clip[2]) == "number" and type(clip[3]) == "number" and type(clip[4]) == "number" then
+ Y0 = max(Y0, floor(clip[2]))
+ Y1 = min(Y1, ceil(clip[4]))
+ X1 = min(X1, ceil(clip[3]))
+ local cx0 = floor(clip[1])
+ X0 = max(X0, cx0)
+ end
+ local W, H = X1 - X0, Y1 - Y0
+ if W <= 0 or H <= 0 then
+ return nil
+ end
+ local maxPixels = if type(o.maxPixels) == "number" then o.maxPixels else 2 ^ 26
+ if W * H > maxPixels then
+ return nil, "limit"
+ end
+ local S = W + 2
+ local acc = bcreate(S * H * 4)
+ for _, poly in polys do
+ local n = #poly
+ local lx, ly = poly[n - 1] - X0, poly[n] - Y0
+ for i = 1, n - 1, 2 do
+ local x, y = poly[i] - X0, poly[i + 1] - Y0
+ edge(acc, S, W, H, lx, ly, x, y)
+ lx, ly = x, y
+ end
+ end
+ local cov = bcreate(W * H)
+ local evenodd = o.rule == "evenodd"
+ for y = 0, H - 1 do
+ local sum = 0
+ local ls = y * S
+ local os = y * W
+ for x = 0, W - 1 do
+ sum += readf32(acc, (ls + x) * 4)
+ local v = abs(sum)
+ if evenodd then
+ v = v % 2
+ if v > 1 then
+ v = 2 - v
+ end
+ elseif v > 1 then
+ v = 1
+ end
+ writeu8(cov, os + x, floor(v * 255 + 0.5))
+ end
+ end
+ return { x = X0, y = Y0, width = W, height = H, coverage = cov }
+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"
+ end
+ local iw, ih = img.width, img.height
+ local px = img.pixels
+ if buffer.len(px) < iw * ih * 4 then
+ return false, "fill: image pixels too short"
+ end
+ local o: Options = table.clone(opts or {})
+ local clip = o.clip
+ if type(clip) == "table" and type(clip[1]) == "number" and type(clip[2]) == "number" and type(clip[3]) == "number" and type(clip[4]) == "number" then
+ o.clip = { max(0, clip[1]), max(0, clip[2]), min(iw, clip[3]), min(ih, clip[4]) }
+ else
+ o.clip = { 0, 0, iw, ih }
+ end
+ local m, why = Raster.mask(path, o)
+ if not m then
+ return why == nil, why
+ end
+ local opacity = if type(o.opacity) == "number" then math.clamp(o.opacity, 0, 1) else 1
+ local fn: any = nil
+ local cr, cg, cb, ca = 0, 0, 0, 255
+ if type(paint) == "function" then
+ fn = paint
+ elseif type(paint) == "table" then
+ cr, cg, cb = tonumber(paint[1]) or 0, tonumber(paint[2]) or 0, tonumber(paint[3]) or 0
+ ca = tonumber(paint[4]) or 255
+ else
+ return false, "fill: paint must be a colour or a function"
+ end
+ local cov = m.coverage
+ local mw = m.width
+ for y = 0, m.height - 1 do
+ local iy = m.y + y
+ for x = 0, mw - 1 do
+ local cv = readu8(cov, y * mw + x)
+ if cv > 0 then
+ local ix = m.x + x
+ local r, g, b, a = cr, cg, cb, ca
+ if fn then
+ local ok, r2, g2, b2, a2 = pcall(fn, ix + 0.5, iy + 0.5)
+ if not ok then
+ return false, "fill: paint function failed"
+ end
+ r, g, b, a = tonumber(r2) or 0, tonumber(g2) or 0, tonumber(b2) or 0, tonumber(a2) or 255
+ end
+ local sa = math.clamp(a, 0, 255) / 255 * cv / 255 * opacity
+ if sa > 0 then
+ local p = (iy * iw + ix) * 4
+ local da = readu8(px, p + 3) / 255
+ local oa = sa + da * (1 - sa)
+ local k = da * (1 - sa)
+ writeu8(px, p, floor((math.clamp(r, 0, 255) * sa + readu8(px, p) * k) / oa + 0.5))
+ writeu8(px, p + 1, floor((math.clamp(g, 0, 255) * sa + readu8(px, p + 1) * k) / oa + 0.5))
+ writeu8(px, p + 2, floor((math.clamp(b, 0, 255) * sa + readu8(px, p + 2) * k) / oa + 0.5))
+ writeu8(px, p + 3, floor(oa * 255 + 0.5))
+ end
+ end
+ end
+ end
+ return true
+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")
+}
+
+-- push a polygon (flat x, y list) as a closed subpath with positive orientation, so overlapping pieces add up
+-- under the nonzero rule
+local function polygon(out: Path, pts: { number })
+ local n = #pts
+ if n < 6 then
+ return
+ end
+ local area = 0
+ for i = 1, n - 1, 2 do
+ local j = if i + 2 > n then 1 else i + 2
+ area += pts[i] * pts[j + 1] - pts[j] * pts[i + 1]
+ end
+ if area == 0 then
+ return
+ end
+ if area > 0 then
+ table.insert(out, { op = "moveTo", pts[1], pts[2] })
+ for i = 3, n - 1, 2 do
+ table.insert(out, { op = "lineTo", pts[i], pts[i + 1] })
+ end
+ else
+ table.insert(out, { op = "moveTo", pts[n - 1], pts[n] })
+ for i = n - 3, 1, -2 do
+ table.insert(out, { op = "lineTo", pts[i], pts[i + 1] })
+ end
+ end
+ table.insert(out, { op = "close" })
+end
+
+local function arcPoints(cx: number, cy: number, r: number, a0: number, a1: number, tol: number, pts: { number })
+ local da = a1 - a0
+ local step = 2 * math.acos(math.clamp(1 - tol / max(r, 1e-9), -1, 1))
+ local n = max(1, min(256, ceil(abs(da) / max(step, 0.01))))
+ for i = 0, n do
+ local t = a0 + da * i / n
+ table.insert(pts, cx + r * math.cos(t))
+ table.insert(pts, cy + r * math.sin(t))
+ 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
+ local join = o.join or "miter"
+ local cap = o.cap or "butt"
+ local miterLimit = if type(o.miterLimit) == "number" and o.miterLimit >= 1 then o.miterLimit else 4
+ local tol = if type(o.tolerance) == "number" and o.tolerance > 0.0005 then o.tolerance else 0.1
+ local out: Path = {}
+ local cmds = commands(path)
+ if not cmds then
+ return out
+ end
+ -- subpaths with their closed flag (flatten loses it, so split here)
+ local subs: { { cmds: Path, closed: boolean } } = {}
+ local cur: Path? = nil
+ local lx, ly = 0, 0
+ for _, c in cmds do
+ local op = if type(c) == "table" then c.op else nil
+ if op == "moveTo" and operands(c, 2) then
+ cur = { c }
+ table.insert(subs, { cmds = cur :: Path, closed = o.closed == true })
+ lx, ly = c[1], c[2]
+ elseif op == "close" then
+ if cur then
+ subs[#subs].closed = true
+ cur = nil
+ end
+ elseif op == "lineTo" or op == "quadTo" or op == "cubicTo" then
+ if not cur then
+ cur = { { op = "moveTo", lx, ly } }
+ table.insert(subs, { cmds = cur :: Path, closed = o.closed == true })
+ end
+ table.insert(cur :: Path, c)
+ end
+ end
+ for _, sub in subs do
+ local polys = flatten(sub.cmds, nil, tol, 4)
+ local pts = polys[1]
+ if not pts then
+ -- a degenerate subpath (a single point): round / square caps draw a dot
+ local m = sub.cmds[1]
+ if #sub.cmds >= 1 and operands(m, 2) and cap ~= "butt" then
+ local d = {}
+ if cap == "round" then
+ arcPoints(m[1], m[2], hw, 0, 2 * math.pi, tol, d)
+ else
+ d = { m[1] - hw, m[2] - hw, m[1] + hw, m[2] - hw, m[1] + hw, m[2] + hw, m[1] - hw, m[2] + hw }
+ end
+ polygon(out, d)
+ 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
+ table.insert(p, pts[i])
+ table.insert(p, pts[i + 1])
+ end
+ end
+ local closed = sub.closed
+ if closed and #p >= 4 and abs(p[1] - p[#p - 1]) < 1e-9 and abs(p[2] - p[#p]) < 1e-9 then
+ table.remove(p)
+ table.remove(p)
+ end
+ local n = #p // 2
+ if n < 2 then
+ 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
+ local x0, y0, x1, y1 = p[2 * i + 1], p[2 * i + 2], p[2 * j + 1], p[2 * j + 2]
+ local dx, dy = x1 - x0, y1 - y0
+ local len = sqrt(dx * dx + dy * dy)
+ local ux, uy = dx / len, dy / len
+ dirs[2 * s + 1], dirs[2 * s + 2] = ux, uy
+ 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]
+ local bx, by = dirs[2 * s1 + 1], dirs[2 * s1 + 2]
+ local cross = ax * by - ay * bx
+ if abs(cross) < 1e-12 and ax * bx + ay * by > 0 then
+ return
+ end
+ -- the outer side: left normals when turning right (cross < 0)
+ local sgn = if cross < 0 then 1 else -1
+ local n0x, n0y = -ay * hw * sgn, ax * hw * sgn
+ local n1x, n1y = -by * hw * sgn, bx * hw * sgn
+ if join == "round" then
+ local d = { x, y }
+ local a0 = math.atan2(n0y, n0x)
+ local a1 = math.atan2(n1y, n1x)
+ local da = a1 - a0
+ while da > math.pi do
+ da -= 2 * math.pi
+ end
+ while da < -math.pi do
+ da += 2 * math.pi
+ end
+ arcPoints(x, y, hw, a0, a0 + da, tol, d)
+ polygon(out, d)
+ else
+ local cosT = ax * bx + ay * by -- angle between directions
+ 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
+ local ml = sqrt(mx * mx + my * my)
+ if ml > 1e-12 then
+ local scale = hw * miter / ml
+ polygon(out, { x, y, x + n0x, y + n0y, x + mx * scale, y + my * scale, x + n1x, y + n1y })
+ return
+ end
+ end
+ polygon(out, { x, y, x + n0x, y + n0y, x + n1x, y + n1y })
+ end
+ end
+ if closed then
+ for k = 0, n - 1 do
+ joinAt(k, (k - 1) % n, k)
+ end
+ else
+ 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 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 })
+ else
+ local d = {}
+ local a0 = math.atan2(ny, nx)
+ arcPoints(x, y, hw, a0, a0 - math.pi, tol, d)
+ polygon(out, d)
+ end
+ end
+ end
+ end
+ end
+ return out
+end
+
+return Raster
diff --git a/src/Formats/codecs/Text/init.luau b/src/Formats/codecs/Text/init.luau
new file mode 100644
index 0000000..11d9da4
--- /dev/null
+++ b/src/Formats/codecs/Text/init.luau
@@ -0,0 +1,53 @@
+--!strict
+--!optimize 2
+-- codecs/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.
+local Text = {}
+
+-- CP1252 bytes 0x80..0x9F (undefined ones map to U+FFFD)
+Text.CP1252 = {
+ [0x80] = 0x20AC, [0x82] = 0x201A, [0x83] = 0x0192, [0x84] = 0x201E, [0x85] = 0x2026, [0x86] = 0x2020,
+ [0x87] = 0x2021, [0x88] = 0x02C6, [0x89] = 0x2030, [0x8A] = 0x0160, [0x8B] = 0x2039, [0x8C] = 0x0152,
+ [0x8E] = 0x017D, [0x91] = 0x2018, [0x92] = 0x2019, [0x93] = 0x201C, [0x94] = 0x201D, [0x95] = 0x2022,
+ [0x96] = 0x2013, [0x97] = 0x2014, [0x98] = 0x02DC, [0x99] = 0x2122, [0x9A] = 0x0161, [0x9B] = 0x203A,
+ [0x9C] = 0x0153, [0x9E] = 0x017E, [0x9F] = 0x0178,
+}
+
+function Text.trim(s: string): string
+ return (string.match(s, "^%s*(.-)%s*$") :: string)
+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)
+ end
+ if utf8.len(text) then
+ return text
+ end
+ if warnings then
+ table.insert(warnings, "text is not UTF-8: read as Windows-1252")
+ end
+ local out = table.create(#text)
+ for i = 1, #text do
+ local b = string.byte(text, i)
+ if b < 0x80 then
+ out[i] = string.char(b)
+ else
+ out[i] = utf8.char(if b < 0xA0 then Text.CP1252[b] or 0xFFFD else b)
+ end
+ end
+ return table.concat(out)
+end
+
+function Text.lines(text: string): { string }
+ text = string.gsub(text, "\r\n?", "\n")
+ local out = {}
+ for line in string.gmatch(text .. "\n", "([^\n]*)\n") do
+ table.insert(out, line)
+ end
+ return out
+end
+
+return Text
diff --git a/src/Formats/codecs/TrueType/Glyf.luau b/src/Formats/codecs/TrueType/Glyf.luau
new file mode 100644
index 0000000..65392f6
--- /dev/null
+++ b/src/Formats/codecs/TrueType/Glyf.luau
@@ -0,0 +1,403 @@
+--!strict
+-- codecs/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.
+local Glyf = {}
+
+local readu8, readi8 = buffer.readu8, buffer.readi8
+local blen = buffer.len
+local band = bit32.band
+
+local function u8(b: buffer, o: number): number
+ if o < 0 or o + 1 > blen(b) then
+ return 0
+ end
+ return readu8(b, o)
+end
+local function u16(b: buffer, o: number): number
+ if o < 0 or o + 2 > blen(b) then
+ return 0
+ end
+ return readu8(b, o) * 256 + readu8(b, o + 1)
+end
+local function i16(b: buffer, o: number): number
+ local v = u16(b, o)
+ return if v >= 32768 then v - 65536 else v
+end
+local function u32(b: buffer, o: number): number
+ return u16(b, o) * 65536 + u16(b, o + 2)
+end
+
+export type Face = {
+ buf: buffer,
+ glyf: number, -- absolute offset of the glyf table
+ glyfLen: number,
+ loca: number,
+ locaLen: number,
+ longLoca: boolean,
+ numGlyphs: number,
+ [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
+ end
+ local a, z
+ if f.longLoca then
+ if (g + 2) * 4 > f.locaLen then
+ return nil, 0
+ end
+ a, z = u32(f.buf, f.loca + g * 4), u32(f.buf, f.loca + g * 4 + 4)
+ else
+ if (g + 2) * 2 > f.locaLen then
+ return nil, 0
+ end
+ a, z = u16(f.buf, f.loca + g * 2) * 2, u16(f.buf, f.loca + g * 2 + 2) * 2
+ end
+ if z <= a or z > f.glyfLen then
+ return nil, 0
+ end
+ 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
+ return nil, 0, 0, 0
+ end
+ local b = f.buf
+ 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
+
+local function simple(b: buffer, o: number, len: number, nc: number): ({ Contour }?, string?)
+ local e = o + len
+ local ends = table.create(nc)
+ local p = o + 10
+ if p + nc * 2 + 2 > e then
+ return nil, "glyph header past the end"
+ end
+ local last = -1
+ for i = 1, nc do
+ local v = u16(b, p)
+ if v < last then
+ return nil, "contour end points out of order"
+ end
+ ends[i] = v
+ last = v
+ p += 2
+ end
+ local n = last + 1
+ if n > MAX_POINTS then
+ return nil, "too many points"
+ end
+ local ins = u16(b, p)
+ p += 2 + ins
+ 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
+ if p >= e then
+ return nil, "flags past the end"
+ end
+ local fl = readu8(b, p)
+ p += 1
+ flags[i] = fl
+ i += 1
+ if band(fl, 8) ~= 0 then
+ if p >= e then
+ return nil, "flags past the end"
+ end
+ local rep = readu8(b, p)
+ p += 1
+ for _ = 1, rep do
+ if i > n then
+ break
+ end
+ flags[i] = fl
+ i += 1
+ end
+ end
+ end
+ -- coordinates
+ local xs = table.create(n, 0)
+ local x = 0
+ for k = 1, n do
+ local fl = flags[k]
+ if band(fl, 2) ~= 0 then
+ if p >= e then
+ return nil, "x coordinates past the end"
+ end
+ local d = readu8(b, p)
+ p += 1
+ x += if band(fl, 16) ~= 0 then d else -d
+ elseif band(fl, 16) == 0 then
+ if p + 2 > e then
+ return nil, "x coordinates past the end"
+ end
+ x += i16(b, p)
+ p += 2
+ end
+ xs[k] = x
+ end
+ local ys = table.create(n, 0)
+ local y = 0
+ for k = 1, n do
+ local fl = flags[k]
+ if band(fl, 4) ~= 0 then
+ if p >= e then
+ return nil, "y coordinates past the end"
+ end
+ local d = readu8(b, p)
+ p += 1
+ y += if band(fl, 32) ~= 0 then d else -d
+ elseif band(fl, 32) == 0 then
+ if p + 2 > e then
+ return nil, "y coordinates past the end"
+ end
+ y += i16(b, p)
+ p += 2
+ end
+ ys[k] = y
+ end
+ local out: { Contour } = table.create(nc)
+ local s = 1
+ for c = 1, nc do
+ local z = ends[c] + 1
+ local cx, cy, con = {}, {}, {}
+ for k = s, z do
+ table.insert(cx, xs[k])
+ table.insert(cy, ys[k])
+ table.insert(con, band(flags[k], 1) ~= 0)
+ end
+ out[c] = { x = cx, y = cy, on = con }
+ s = z + 1
+ end
+ return out, nil
+end
+
+local contours: (f: Face, g: number, depth: number) -> ({ Contour }?, string?)
+
+local function composite(f: Face, o: number, len: number, depth: number): ({ Contour }?, string?)
+ local b = f.buf
+ local e = o + len
+ local p = o + 10
+ local out: { Contour } = {}
+ local total = 0
+ while true do
+ if p + 4 > e then
+ return nil, "component past the end"
+ end
+ local flags = u16(b, p)
+ local gi = u16(b, p + 2)
+ p += 4
+ local a1, a2
+ if band(flags, 1) ~= 0 then -- ARG_1_AND_2_ARE_WORDS
+ if p + 4 > e then
+ return nil, "component past the end"
+ end
+ if band(flags, 2) ~= 0 then
+ a1, a2 = i16(b, p), i16(b, p + 2)
+ else
+ a1, a2 = u16(b, p), u16(b, p + 2)
+ end
+ p += 4
+ else
+ if p + 2 > e then
+ return nil, "component past the end"
+ end
+ if band(flags, 2) ~= 0 then
+ a1, a2 = readi8(b, p), readi8(b, p + 1)
+ else
+ a1, a2 = readu8(b, p), readu8(b, p + 1)
+ end
+ p += 2
+ end
+ local m1, m2, m3, m4 = 1, 0, 0, 1
+ if band(flags, 8) ~= 0 then -- WE_HAVE_A_SCALE
+ m1 = i16(b, p) / 16384
+ m4 = m1
+ p += 2
+ elseif band(flags, 0x40) ~= 0 then -- WE_HAVE_AN_X_AND_Y_SCALE
+ m1, m4 = i16(b, p) / 16384, i16(b, p + 2) / 16384
+ p += 4
+ elseif band(flags, 0x80) ~= 0 then -- WE_HAVE_A_TWO_BY_TWO
+ m1, m2, m3, m4 = i16(b, p) / 16384, i16(b, p + 2) / 16384, i16(b, p + 4) / 16384, i16(b, p + 6) / 16384
+ p += 8
+ end
+ if p > e then
+ return nil, "component past the end"
+ end
+ local child, err = contours(f, gi, depth + 1)
+ if not child then
+ return nil, err
+ end
+ -- transform the child's points
+ local tc: { Contour } = table.create(#child)
+ for i, c in child do
+ local nx, ny = table.create(#c.x), table.create(#c.x)
+ for k = 1, #c.x do
+ local x, y = c.x[k], c.y[k]
+ nx[k] = m1 * x + m3 * y
+ ny[k] = m2 * x + m4 * y
+ end
+ tc[i] = { x = nx, y = ny, on = c.on }
+ end
+ local dx, dy
+ if band(flags, 2) ~= 0 then -- ARGS_ARE_XY_VALUES
+ dx, dy = a1, a2
+ if band(flags, 0x800) ~= 0 and band(flags, 0x1000) == 0 then -- SCALED_COMPONENT_OFFSET
+ dx, dy = m1 * a1 + m3 * a2, m2 * a1 + m4 * a2
+ end
+ else
+ -- point matching: parent point a1 (in what is composed so far) meets child point a2
+ local function pt(list: { Contour }, idx: number): (number?, number)
+ local k = idx
+ for _, c in list do
+ local n = #c.x
+ if k < n then
+ return c.x[k + 1], c.y[k + 1]
+ end
+ k -= n
+ end
+ return nil, 0
+ end
+ local px, py = pt(out, a1)
+ local cx, cy = pt(tc, a2)
+ if not px or not cx then
+ return nil, "component point index out of range"
+ end
+ dx, dy = px - cx, py - (cy :: number)
+ end
+ for _, c in tc do
+ for k = 1, #c.x do
+ c.x[k] += dx
+ c.y[k] += dy
+ end
+ total += #c.x
+ table.insert(out, c)
+ end
+ if total > MAX_POINTS then
+ return nil, "too many points"
+ end
+ if band(flags, 0x20) == 0 then -- MORE_COMPONENTS
+ break
+ end
+ end
+ return out, nil
+end
+
+contours = function(f: Face, g: number, depth: number): ({ Contour }?, string?)
+ if depth > 8 then
+ return nil, "composite glyphs nested too deep"
+ end
+ local o, len = Glyf.range(f, g)
+ if not o then
+ return {}, nil -- empty glyph (space)
+ end
+ if len < 10 then
+ return nil, "glyph header past the end"
+ end
+ local nc = i16(f.buf, o)
+ if nc >= 0 then
+ return simple(f.buf, o, len, nc)
+ end
+ return composite(f, o, len, depth)
+end
+
+-- outline(f, g) -> path commands (codecs/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
+ return nil, err
+ end
+ local cmds = {}
+ for _, c in cs do
+ local n = #c.x
+ if n < 2 then
+ continue
+ end
+ local xs, ys, on = c.x, c.y, c.on
+ -- the start: the first on-curve point, or the midpoint of the first two off-curve points
+ local s = 0
+ for k = 1, n do
+ if on[k] then
+ s = k
+ break
+ end
+ end
+ local sx, sy
+ if s == 0 then
+ sx, sy = (xs[1] + xs[n]) / 2, (ys[1] + ys[n]) / 2
+ s = 1
+ -- all off-curve: start at the implied midpoint between the last and the first, then walk from 1
+ table.insert(cmds, { op = "moveTo", sx, sy })
+ local cx, cy = xs[1], ys[1]
+ for k = 2, n do
+ local x, y = xs[k], ys[k]
+ table.insert(cmds, { op = "quadTo", cx, cy, (cx + x) / 2, (cy + y) / 2 })
+ cx, cy = x, y
+ end
+ table.insert(cmds, { op = "quadTo", cx, cy, sx, sy })
+ table.insert(cmds, { op = "close" })
+ continue
+ end
+ sx, sy = xs[s], ys[s]
+ table.insert(cmds, { op = "moveTo", sx, sy })
+ local off = false
+ local cx, cy = 0, 0
+ for i = 1, n do
+ 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
+ end
+ if isOn then
+ if off then
+ table.insert(cmds, { op = "quadTo", cx, cy, x, y })
+ elseif i < n then
+ table.insert(cmds, { op = "lineTo", x, y })
+ end
+ off = false
+ else
+ if off then
+ table.insert(cmds, { op = "quadTo", cx, cy, (cx + x) / 2, (cy + y) / 2 })
+ end
+ cx, cy = x, y
+ off = true
+ end
+ end
+ table.insert(cmds, { op = "close" })
+ end
+ 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
+ return 0, 0
+ end
+ local n = 0
+ for _, c in cs do
+ n += #c.x
+ end
+ return n, #cs
+end
+
+return Glyf
diff --git a/src/Formats/codecs/TrueType/Tables.luau b/src/Formats/codecs/TrueType/Tables.luau
new file mode 100644
index 0000000..87e5833
--- /dev/null
+++ b/src/Formats/codecs/TrueType/Tables.luau
@@ -0,0 +1,535 @@
+--!strict
+-- codecs/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).
+local Tables = {}
+
+local readu8 = buffer.readu8
+local blen = buffer.len
+local band = bit32.band
+
+local function u8(b: buffer, o: number): number
+ if o < 0 or o + 1 > blen(b) then
+ return 0
+ end
+ return readu8(b, o)
+end
+local function u16(b: buffer, o: number): number
+ if o < 0 or o + 2 > blen(b) then
+ return 0
+ end
+ return readu8(b, o) * 256 + readu8(b, o + 1)
+end
+local function i16(b: buffer, o: number): number
+ local v = u16(b, o)
+ return if v >= 32768 then v - 65536 else v
+end
+local function u32(b: buffer, o: number): number
+ return u16(b, o) * 65536 + u16(b, o + 2)
+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
+function Tables.cmap(b: buffer, o: number, n: number): Cmap?
+ local count = u16(b, o + 2)
+ local best, bestRank, symbol = -1, 0, false
+ for i = 0, count - 1 do
+ local r = o + 4 + i * 8
+ if r + 8 > o + n then
+ break
+ end
+ local pid, eid, off = u16(b, r), u16(b, r + 2), u32(b, r + 4)
+ local at = o + off
+ if off >= n then
+ continue
+ end
+ local fmt = u16(b, at)
+ local rank = 0
+ if pid == 3 and eid == 10 then
+ rank = 6
+ elseif pid == 0 and (eid == 4 or eid == 6) then
+ rank = 5
+ elseif pid == 3 and eid == 1 then
+ rank = 4
+ elseif pid == 0 and fmt ~= 14 then
+ rank = 3
+ elseif pid == 3 and eid == 0 then
+ rank = 2
+ elseif pid == 1 and eid == 0 then
+ rank = 1
+ end
+ if fmt ~= 0 and fmt ~= 4 and fmt ~= 6 and fmt ~= 10 and fmt ~= 12 and fmt ~= 13 then
+ rank = 0
+ end
+ if rank > bestRank then
+ best, bestRank, symbol = at, rank, pid == 3 and eid == 0
+ end
+ end
+ if best < 0 then
+ return nil
+ end
+ return { buf = b, at = best, format = u16(b, best), symbol = symbol }
+end
+
+local function lookup(c: Cmap, cp: number): number
+ local b, t, fmt = c.buf, c.at, c.format
+ if fmt == 0 then
+ return if cp < 256 then u8(b, t + 6 + cp) else 0
+ elseif fmt == 6 then
+ local first, count = u16(b, t + 6), u16(b, t + 8)
+ if cp >= first and cp < first + count then
+ return u16(b, t + 10 + (cp - first) * 2)
+ end
+ return 0
+ elseif fmt == 10 then
+ local first, count = u32(b, t + 12), u32(b, t + 16)
+ if cp >= first and cp < first + count then
+ return u16(b, t + 20 + (cp - first) * 2)
+ end
+ return 0
+ elseif fmt == 4 then
+ if cp > 0xFFFF then
+ return 0
+ end
+ 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
+ if u16(b, ends + mid * 2) < cp then
+ lo = mid + 1
+ else
+ hi = mid
+ end
+ end
+ if segs == 0 or u16(b, ends + lo * 2) < cp then
+ return 0
+ end
+ local starts = ends + segX2 + 2
+ local start = u16(b, starts + lo * 2)
+ if cp < start then
+ return 0
+ end
+ local deltaAt = starts + segX2 + lo * 2
+ local delta = u16(b, deltaAt)
+ local rangeAt = deltaAt + segX2
+ local ro = u16(b, rangeAt)
+ if ro == 0 then
+ return (cp + delta) % 65536
+ end
+ local g = u16(b, rangeAt + ro + (cp - start) * 2)
+ if g == 0 then
+ return 0
+ end
+ return (g + delta) % 65536
+ elseif fmt == 12 or fmt == 13 then
+ local n = u32(b, t + 12)
+ local lo, hi = 0, n - 1
+ while lo <= hi do
+ local mid = (lo + hi) // 2
+ local g = t + 16 + mid * 12
+ local s, e = u32(b, g), u32(b, g + 4)
+ if cp < s then
+ hi = mid - 1
+ elseif cp > e then
+ lo = mid + 1
+ else
+ local gid = u32(b, g + 8)
+ return if fmt == 12 then gid + cp - s else gid
+ end
+ end
+ return 0
+ end
+ 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
+ end
+ local g = lookup(c, cp)
+ if g == 0 and c.symbol and cp < 256 then
+ g = lookup(c, 0xF000 + cp) -- symbol fonts map U+F020.. to the 8-bit codes
+ end
+ 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
+ local apple = u32(b, o) == 0x00010000
+ local count = if apple then u32(b, o + 4) else u16(b, o + 2)
+ local p = if apple then o + 8 else o + 4
+ for _ = 1, math.min(count, 64) do
+ if p + 6 > e then
+ break
+ end
+ local len, fmt, horizontal, cross, minimum, hdr
+ if apple then
+ len = u32(b, p)
+ local cov = u16(b, p + 4)
+ fmt = band(cov, 0xFF)
+ horizontal = band(cov, 0x8000) == 0
+ cross = band(cov, 0x4000) ~= 0
+ minimum = band(cov, 0x2000) ~= 0 -- (variation) treated as not applicable
+ hdr = 8
+ else
+ len = u16(b, p + 2)
+ local cov = u16(b, p + 4)
+ fmt = cov // 256
+ horizontal = band(cov, 1) ~= 0
+ minimum = band(cov, 2) ~= 0
+ cross = band(cov, 4) ~= 0
+ hdr = 6
+ end
+ if fmt == 0 and horizontal and not cross and not minimum then
+ local np = u16(b, p + hdr)
+ local q = p + hdr + 8
+ for k = 0, np - 1 do
+ local r = q + k * 6
+ if r + 6 > e then
+ break
+ end
+ local key = u16(b, r) * 65536 + u16(b, r + 2)
+ pairs[key] = (pairs[key] or 0) + i16(b, r + 4)
+ end
+ end
+ if len < hdr then
+ break
+ end
+ -- Microsoft subtables often have a wrong 16-bit length for big tables: only the first is reliable then
+ if not apple and len < hdr + 8 then
+ break
+ end
+ p += len
+ end
+ return pairs
+end
+
+-- ------------------------------------------------------------------------------------------------ GPOS
+local function popcount(v: number): number
+ local c = 0
+ while v ~= 0 do
+ c += band(v, 1)
+ v = bit32.rshift(v, 1)
+ end
+ 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
+ local n = u16(b, t + 2)
+ local lo, hi = 0, n - 1
+ while lo <= hi do
+ local mid = (lo + hi) // 2
+ local v = u16(b, t + 4 + mid * 2)
+ if g < v then
+ hi = mid - 1
+ elseif g > v then
+ lo = mid + 1
+ else
+ return mid
+ end
+ end
+ elseif fmt == 2 then
+ local n = u16(b, t + 2)
+ local lo, hi = 0, n - 1
+ while lo <= hi do
+ local mid = (lo + hi) // 2
+ local r = t + 4 + mid * 6
+ local s, e = u16(b, r), u16(b, r + 2)
+ if g < s then
+ hi = mid - 1
+ elseif g > e then
+ lo = mid + 1
+ else
+ return u16(b, r + 4) + g - s
+ end
+ end
+ end
+ return -1
+end
+
+local function classOf(b: buffer, t: number, g: number): number
+ local fmt = u16(b, t)
+ if fmt == 1 then
+ local s, n = u16(b, t + 2), u16(b, t + 4)
+ if g >= s and g < s + n then
+ return u16(b, t + 6 + (g - s) * 2)
+ end
+ elseif fmt == 2 then
+ local n = u16(b, t + 2)
+ local lo, hi = 0, n - 1
+ while lo <= hi do
+ local mid = (lo + hi) // 2
+ local r = t + 4 + mid * 6
+ local s, e = u16(b, r), u16(b, r + 2)
+ if g < s then
+ hi = mid - 1
+ elseif g > e then
+ lo = mid + 1
+ else
+ return u16(b, r + 4)
+ end
+ end
+ end
+ 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
+ end
+ 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)
+ if ci < 0 then
+ return false, 0
+ end
+ local vf1, vf2 = u16(b, t + 4), u16(b, t + 6)
+ local s1, s2 = 2 * popcount(band(vf1, 0xFF)), 2 * popcount(band(vf2, 0xFF))
+ if fmt == 1 then
+ local count = u16(b, t + 8)
+ if ci >= count then
+ return false, 0
+ end
+ local ps = t + u16(b, t + 10 + ci * 2)
+ local n = u16(b, ps)
+ local rec = 2 + s1 + s2
+ local lo, hi = 0, n - 1
+ while lo <= hi do
+ local mid = (lo + hi) // 2
+ local q = ps + 2 + mid * rec
+ local g = u16(b, q)
+ if r < g then
+ hi = mid - 1
+ elseif r > g then
+ lo = mid + 1
+ else
+ return true, xAdvance(b, q + 2, vf1)
+ end
+ end
+ return false, 0
+ elseif fmt == 2 then
+ local cd1, cd2 = t + u16(b, t + 8), t + u16(b, t + 10)
+ local n1, n2 = u16(b, t + 12), u16(b, t + 14)
+ local c1, c2 = classOf(b, cd1, l), classOf(b, cd2, r)
+ if c1 >= n1 or c2 >= n2 then
+ return false, 0
+ end
+ local q = t + 16 + (c1 * n2 + c2) * (s1 + s2)
+ return true, xAdvance(b, q, vf1)
+ end
+ return false, 0
+end
+
+export type Gpos = { buf: buffer, subtables: { { number } } } -- per lookup: PairPos subtable offsets
+
+-- 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
+ end
+ local fl, ll = o + u16(b, o + 6), o + u16(b, o + 8)
+ local want: { [number]: boolean } = {}
+ local any = false
+ local nf = u16(b, fl)
+ for i = 0, nf - 1 do
+ local r = fl + 2 + i * 6
+ if u32(b, r) == 0x6B65726E then -- "kern"
+ local f = fl + u16(b, r + 4)
+ for k = 0, u16(b, f + 2) - 1 do
+ want[u16(b, f + 4 + k * 2)] = true
+ any = true
+ end
+ end
+ end
+ if not any then
+ return nil
+ end
+ local lookups: { { number } } = {}
+ local nl = u16(b, ll)
+ for i = 0, nl - 1 do
+ if want[i] then
+ local lt = ll + u16(b, ll + 2 + i * 2)
+ local ty = u16(b, lt)
+ local subs: { number } = {}
+ for k = 0, math.min(u16(b, lt + 4), 4096) - 1 do
+ local st = lt + u16(b, lt + 6 + k * 2)
+ local sty = ty
+ if ty == 9 and u16(b, st) == 1 then -- extension
+ sty = u16(b, st + 2)
+ st += u32(b, st + 4)
+ end
+ if sty == 2 then
+ table.insert(subs, st)
+ end
+ end
+ if #subs > 0 then
+ table.insert(lookups, subs)
+ end
+ end
+ end
+ if #lookups == 0 then
+ return nil
+ end
+ 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
+ for _, st in subs do
+ local applies, v = pairPos(g.buf, st, l, r)
+ if applies then
+ total += v
+ break
+ end
+ end
+ end
+ 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,
+ 0x2020, 0xB0, 0xA2, 0xA3, 0xA7, 0x2022, 0xB6, 0xDF, 0xAE, 0xA9, 0x2122, 0xB4, 0xA8, 0x2260, 0xC6, 0xD8,
+ 0x221E, 0xB1, 0x2264, 0x2265, 0xA5, 0xB5, 0x2202, 0x2211, 0x220F, 0x3C0, 0x222B, 0xAA, 0xBA, 0x3A9, 0xE6, 0xF8,
+ 0xBF, 0xA1, 0xAC, 0x221A, 0x192, 0x2248, 0x2206, 0xAB, 0xBB, 0x2026, 0xA0, 0xC0, 0xC3, 0xD5, 0x152, 0x153,
+ 0x2013, 0x2014, 0x201C, 0x201D, 0x2018, 0x2019, 0xF7, 0x25CA, 0xFF, 0x178, 0x2044, 0x20AC, 0x2039, 0x203A, 0xFB01, 0xFB02,
+ 0x2021, 0xB7, 0x201A, 0x201E, 0x2030, 0xC2, 0xCA, 0xC1, 0xCB, 0xC8, 0xCD, 0xCE, 0xCF, 0xCC, 0xD3, 0xD4,
+ 0xF8FF, 0xD2, 0xDA, 0xDB, 0xD9, 0x131, 0x2C6, 0x2DC, 0xAF, 0x2D8, 0x2D9, 0x2DA, 0xB8, 0x2DD, 0x2DB, 0x2C7,
+}
+
+local function utf16be(b: buffer, o: number, n: number): string
+ local out = {}
+ local k = 0
+ while k + 1 < n do
+ local c = u16(b, o + k)
+ k += 2
+ if c >= 0xD800 and c < 0xDC00 and k + 1 < n then
+ local lo = u16(b, o + k)
+ if lo >= 0xDC00 and lo < 0xE000 then
+ c = 0x10000 + (c - 0xD800) * 1024 + (lo - 0xDC00)
+ k += 2
+ end
+ end
+ if c >= 0xD800 and c < 0xE000 then
+ c = 0xFFFD
+ end
+ table.insert(out, utf8.char(c))
+ end
+ return table.concat(out)
+end
+
+local function macRoman(b: buffer, o: number, n: number): string
+ local out = {}
+ for k = 0, n - 1 do
+ local c = u8(b, o + k)
+ table.insert(out, utf8.char(if c < 128 then c else MAC_ROMAN_HIGH[c - 127]))
+ end
+ return table.concat(out)
+end
+
+local NAME_IDS = {
+ [0] = "copyright",
+ [1] = "family",
+ [2] = "style",
+ [3] = "uniqueId",
+ [4] = "fullName",
+ [5] = "version",
+ [6] = "postScriptName",
+ [7] = "trademark",
+ [8] = "manufacturer",
+ [9] = "designer",
+ [10] = "description",
+ [11] = "vendorUrl",
+ [12] = "designerUrl",
+ [13] = "license",
+ [14] = "licenseUrl",
+ [16] = "typographicFamily",
+ [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 } = {}
+ local count, strings = u16(b, o + 2), o + u16(b, o + 4)
+ for i = 0, math.min(count, 4096) - 1 do
+ local r = o + 6 + i * 12
+ if r + 12 > o + n then
+ break
+ end
+ local pid, eid, lang, nid = u16(b, r), u16(b, r + 2), u16(b, r + 4), u16(b, r + 6)
+ local len, off = u16(b, r + 8), u16(b, r + 10)
+ local key = NAME_IDS[nid]
+ if key and strings + off + len <= o + n then
+ local rk, s = 0, nil
+ if pid == 3 and (eid == 1 or eid == 10 or eid == 0) then
+ rk = if lang == 0x409 then 4 else 2
+ s = utf16be(b, strings + off, len)
+ elseif pid == 0 then
+ rk = 3
+ s = utf16be(b, strings + off, len)
+ elseif pid == 1 and eid == 0 then
+ rk = if lang == 0 then 1 else 0.5
+ s = macRoman(b, strings + off, len)
+ end
+ if s and rk > (rank[key] or 0) then
+ out[key] = s
+ rank[key] = rk
+ end
+ end
+ end
+ 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),
+ xAvgCharWidth = i16(b, o + 2),
+ weightClass = u16(b, o + 4),
+ widthClass = u16(b, o + 6),
+ fsType = u16(b, o + 8),
+ }
+ if n >= 78 then
+ t.fsSelection = u16(b, o + 62)
+ t.firstChar = u16(b, o + 64)
+ t.lastChar = u16(b, o + 66)
+ t.typoAscender = i16(b, o + 68)
+ t.typoDescender = i16(b, o + 70)
+ t.typoLineGap = i16(b, o + 72)
+ t.winAscent = u16(b, o + 74)
+ t.winDescent = u16(b, o + 76)
+ end
+ if n >= 96 and t.version >= 2 then
+ t.xHeight = i16(b, o + 86)
+ t.capHeight = i16(b, o + 88)
+ end
+ return t
+end
+
+return Tables
diff --git a/src/Formats/codecs/TrueType/init.luau b/src/Formats/codecs/TrueType/init.luau
new file mode 100644
index 0000000..4e7948d
--- /dev/null
+++ b/src/Formats/codecs/TrueType/init.luau
@@ -0,0 +1,338 @@
+--!strict
+-- codecs/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/TrueType/Glyf for glyf, codecs/Cff for "CFF "), kerning ('kern' table and GPOS 'kern' pair adjustments),
+-- names, and rasterize(glyph, px) through codecs/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/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.
+local Err = require("@formats/core/Err")
+local Types = require("@formats/Types")
+local Raster = require("@formats/codecs/Raster")
+local Cff = require("@formats/codecs/Cff")
+local Glyf = require("@formats/codecs/TrueType/Glyf")
+local Tables = require("@formats/codecs/TrueType/Tables")
+
+local TrueType = {}
+
+local u16, i16, u32 = Tables.u16, Tables.i16, Tables.u32
+
+local function tag(b: buffer, o: number): string
+ if o < 0 or o + 4 > buffer.len(b) then
+ return ""
+ end
+ 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)
+ if t == "ttcf" then
+ return u32(b, o + 8)
+ end
+ if t == "\0\1\0\0" or t == "OTTO" or t == "true" or t == "typ1" then
+ return 1
+ end
+ 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
+ return nil, "table directory past the end"
+ end
+ local out: { [string]: { number } } = {}
+ for i = 0, n - 1 do
+ local r = dir + 12 + i * 16
+ local t = tag(b, r)
+ local off, len = u32(b, r + 8), u32(b, r + 12)
+ if file + off + len <= limit then
+ out[t] = { file + off, len }
+ end
+ end
+ return out, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ the Font value
+local Face = {}
+Face.__index = Face
+
+function Face.glyphIndex(self: any, cp: number): number
+ return Tables.glyph(self._cmap, cp)
+end
+
+function Face.advance(self: any, g: number): number
+ if type(g) ~= "number" or g < 0 or g >= self.numGlyphs then
+ return 0
+ end
+ local nh = self._numHMetrics
+ if nh == 0 then
+ return 0
+ end
+ local h = self._hmtx
+ return u16(self._buf, h + 4 * math.min(g, nh - 1))
+end
+
+function Face.leftSideBearing(self: any, g: number): number
+ if type(g) ~= "number" or g < 0 or g >= self.numGlyphs then
+ return 0
+ end
+ local nh, h = self._numHMetrics, self._hmtx
+ if g < nh then
+ return i16(self._buf, h + 4 * g + 2)
+ end
+ return i16(self._buf, h + 4 * nh + 2 * (g - nh))
+end
+
+function Face.kern(self: any, a: number, b: number): number
+ if type(a) ~= "number" or type(b) ~= "number" then
+ return 0
+ end
+ local key = a * 65536 + b
+ local cache = self._kernCache
+ local v = cache[key]
+ if v then
+ return v
+ end
+ v = 0
+ if self._gpos then
+ v = Tables.gposKern(self._gpos, a, b)
+ end
+ if v == 0 and self._kern then
+ v = self._kern[key] or 0
+ end
+ cache[key] = v
+ 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
+
+function Face.outline(self: any, g: number): { any }?
+ if type(g) ~= "number" or g < 0 or g >= self.numGlyphs or g % 1 ~= 0 then
+ return nil
+ end
+ local ok, cmds, err = pcall(function()
+ if self._cff then
+ return Cff.outline(self._cff, g)
+ end
+ return Glyf.outline(self._glyf, g)
+ end)
+ if not ok then
+ self.meta.lastError = tostring(cmds)
+ return nil
+ end
+ if not cmds then
+ self.meta.lastError = err
+ end
+ 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
+ return nil, 0, 0, 0
+ end
+ local x0, y0, x1, y1 = math.huge, math.huge, -math.huge, -math.huge
+ for _, c in cmds do
+ for i = 1, #c - 1, 2 do
+ local x, y = c[i], c[i + 1]
+ x0, y0, x1, y1 = math.min(x0, x), math.min(y0, y), math.max(x1, x), math.max(y1, y)
+ end
+ end
+ if x0 > x1 then
+ return nil, 0, 0, 0
+ end
+ 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
+ scaleY: number?,
+ shiftX: number?, -- subpixel shift (pixels)
+ 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.
+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
+ end
+ local cmds = self:outline(g)
+ if not cmds then
+ return nil
+ end
+ local o = opts or {}
+ local sx = if type(o.scaleX) == "number" then o.scaleX else px / self.unitsPerEm
+ local sy = if type(o.scaleY) == "number" then o.scaleY else sx
+ local tx, ty = o.shiftX or 0, o.shiftY or 0
+ local m = Raster.mask(cmds, { transform = { sx, 0, 0, -sy, tx, ty }, maxPixels = 2 ^ 24 })
+ local img
+ if m then
+ img = Types.Image.new(m.width, m.height, "alpha8")
+ buffer.copy(img.pixels, 0, m.coverage)
+ img.meta.left = m.x
+ img.meta.top = -m.y
+ else
+ img = Types.Image.new(0, 0, "alpha8")
+ img.meta.left = 0
+ img.meta.top = 0
+ end
+ img.meta.advance = self:advance(g) * sx
+ img.meta.glyph = g
+ return img
+end
+
+-- ------------------------------------------------------------------------------------------------ parsing
+export type Options = { index: number? } -- the font in a collection (default 0)
+
+-- 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
+ local limit = math.min(buffer.len(b), file + (length or (buffer.len(b) - file)))
+ if limit - file < 12 then
+ return nil, Err.new(Err.TRUNCATED, "too short for an sfnt header", file)
+ end
+ local dir = file
+ local index = (opts and opts.index) or 0
+ local count = TrueType.count(b, file)
+ if tag(b, file) == "ttcf" then
+ if type(index) ~= "number" or index < 0 or index >= count or index % 1 ~= 0 then
+ return nil, Err.new(Err.ARG, string.format("font index %s out of range (collection of %d)", tostring(index), count))
+ end
+ dir = file + u32(b, file + 12 + index * 4)
+ if dir + 12 > limit then
+ return nil, Err.new(Err.TRUNCATED, "collection font directory past the end", file)
+ end
+ elseif count == 0 then
+ return nil, Err.new(Err.CORRUPT, "not an sfnt font", file)
+ end
+ local sfntTag = tag(b, dir)
+ if sfntTag == "typ1" then
+ return nil, Err.new(Err.UNSUPPORTED, "PostScript Type 1 sfnt", dir)
+ end
+ local t, terr = TrueType.tables(b, file, dir, limit)
+ if not t then
+ return nil, Err.new(Err.TRUNCATED, terr or "bad table directory", dir)
+ end
+ for _, need in { "head", "hhea", "maxp", "hmtx" } do
+ if not t[need] then
+ return nil, Err.new(Err.CORRUPT, "missing the " .. need .. " table", dir)
+ end
+ end
+ local head, hhea, maxp, hmtx = t.head[1], t.hhea[1], t.maxp[1], t.hmtx[1]
+ if t.head[2] < 54 or t.hhea[2] < 36 or t.maxp[2] < 6 then
+ return nil, Err.new(Err.TRUNCATED, "short head / hhea / maxp table", dir)
+ end
+ local upem = u16(b, head + 18)
+ if upem < 16 or upem > 16384 then
+ return nil, Err.new(Err.CORRUPT, "bad unitsPerEm " .. upem, head + 18)
+ end
+ local numGlyphs = u16(b, maxp + 4)
+ local nh = math.min(u16(b, hhea + 34), numGlyphs)
+ if nh * 4 > t.hmtx[2] then
+ nh = t.hmtx[2] // 4
+ end
+ local font: any = setmetatable({
+ kind = "font",
+ info = {},
+ unitsPerEm = upem,
+ ascent = i16(b, hhea + 4),
+ descent = i16(b, hhea + 6),
+ lineGap = i16(b, hhea + 8),
+ numGlyphs = numGlyphs,
+ bbox = { i16(b, head + 36), i16(b, head + 38), i16(b, head + 40), i16(b, head + 42) },
+ pages = nil,
+ meta = {},
+ _buf = b,
+ _hmtx = hmtx,
+ _numHMetrics = nh,
+ _kernCache = {},
+ }, Face)
+ -- outlines
+ if t.glyf and t.loca then
+ font._glyf = {
+ buf = b,
+ glyf = t.glyf[1],
+ glyfLen = t.glyf[2],
+ loca = t.loca[1],
+ locaLen = t.loca[2],
+ longLoca = i16(b, head + 50) ~= 0,
+ numGlyphs = numGlyphs,
+ }
+ font.meta.outlines = "truetype"
+ elseif t["CFF "] then
+ local cff, cerr = Cff.parse(b, t["CFF "][1], t["CFF "][2])
+ if not cff then
+ local code = if cerr and string.find(cerr, "unsupported", 1, true) then Err.UNSUPPORTED else Err.CORRUPT
+ return nil, Err.new(code, "CFF: " .. tostring(cerr), t["CFF "][1])
+ end
+ font._cff = cff
+ font.meta.outlines = "cff"
+ elseif t.CFF2 then
+ return nil, Err.new(Err.UNSUPPORTED, "CFF2 outlines (variable OpenType)", dir)
+ 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
+ if t.kern then
+ font._kern = Tables.kern(b, t.kern[1], t.kern[2])
+ end
+ if t.GPOS then
+ font._gpos = Tables.gpos(b, t.GPOS[1], t.GPOS[2])
+ end
+ if t.name then
+ local names = Tables.names(b, t.name[1], t.name[2])
+ for k, v in names do
+ font.info[k] = v
+ end
+ font.info.family = names.typographicFamily or names.family
+ font.info.style = names.typographicStyle or names.style
+ end
+ if t["OS/2"] and t["OS/2"][2] >= 10 then
+ font.meta.os2 = Tables.os2(b, t["OS/2"][1], t["OS/2"][2])
+ end
+ if t.post and t.post[2] >= 16 then
+ local p = t.post[1]
+ font.meta.italicAngle = i16(b, p + 4) + u16(b, p + 6) / 65536
+ font.meta.underlinePosition = i16(b, p + 8)
+ font.meta.underlineThickness = i16(b, p + 10)
+ font.meta.fixedPitch = u32(b, p + 12) ~= 0
+ end
+ local tags = {}
+ for k in t do
+ table.insert(tags, k)
+ end
+ table.sort(tags)
+ font.meta.tables = tags
+ font.meta.sfnt = if sfntTag == "OTTO" then "OTTO" else "TrueType"
+ font.meta.collection = if count > 1 or tag(b, file) == "ttcf" then { index = index, count = count } else nil
+ return font, nil
+end
+
+return TrueType
diff --git a/src/Formats/codecs/Url/init.luau b/src/Formats/codecs/Url/init.luau
new file mode 100644
index 0000000..026ecb5
--- /dev/null
+++ b/src/Formats/codecs/Url/init.luau
@@ -0,0 +1,216 @@
+--!strict
+--!optimize 2
+-- codecs/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.
+local Url = {}
+
+export type Location = { url: string, playable: boolean, reason: string?, [string]: any }
+
+export type Parts = {
+ scheme: string?,
+ authority: string?,
+ path: string,
+ query: string?,
+ fragment: string?,
+}
+
+-- Splits a URI reference into its five components (RFC 3986 appendix B).
+function Url.split(ref: string): Parts
+ local scheme, rest = string.match(ref, "^([%a][%w+%.%-]*):(.*)$")
+ if not scheme then
+ rest = ref
+ end
+ local s = rest :: string
+ local fragment, query, authority
+ local i = string.find(s, "#", 1, true)
+ if i then
+ fragment = string.sub(s, i + 1)
+ s = string.sub(s, 1, i - 1)
+ end
+ i = string.find(s, "?", 1, true)
+ if i then
+ query = string.sub(s, i + 1)
+ s = string.sub(s, 1, i - 1)
+ end
+ if string.sub(s, 1, 2) == "//" then
+ local j = string.find(s, "/", 3, true)
+ if j then
+ authority = string.sub(s, 3, j - 1)
+ s = string.sub(s, j)
+ else
+ authority = string.sub(s, 3)
+ s = ""
+ end
+ end
+ return { scheme = scheme, authority = authority, path = s, query = query, fragment = fragment }
+end
+
+-- Recomposes components (RFC 3986 section 5.3).
+function Url.join(p: Parts): string
+ local out = {}
+ if p.scheme then
+ table.insert(out, p.scheme .. ":")
+ end
+ if p.authority then
+ table.insert(out, "//" .. p.authority)
+ end
+ table.insert(out, p.path)
+ if p.query then
+ table.insert(out, "?" .. p.query)
+ end
+ if p.fragment then
+ table.insert(out, "#" .. p.fragment)
+ end
+ return table.concat(out)
+end
+
+-- RFC 3986 section 5.2.4
+function Url.removeDotSegments(path: string): string
+ local input = path
+ local output = {}
+ while input ~= "" do
+ if string.sub(input, 1, 3) == "../" then
+ input = string.sub(input, 4)
+ elseif string.sub(input, 1, 2) == "./" then
+ input = string.sub(input, 3)
+ elseif string.sub(input, 1, 3) == "/./" then
+ input = string.sub(input, 3)
+ elseif input == "/." then
+ input = "/"
+ elseif string.sub(input, 1, 4) == "/../" then
+ input = string.sub(input, 4)
+ table.remove(output)
+ elseif input == "/.." then
+ input = "/"
+ table.remove(output)
+ elseif input == "." or input == ".." then
+ input = ""
+ else
+ -- move the first segment (with its leading "/", up to the next "/") to the output
+ local j = string.find(input, "/", 2, true)
+ local seg = if j then string.sub(input, 1, j - 1) else input
+ table.insert(output, seg)
+ input = string.sub(input, #seg + 1)
+ end
+ end
+ return table.concat(output)
+end
+
+-- Resolves a reference against an absolute base URI (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 = "" }
+ if r.scheme then
+ t.scheme, t.authority, t.path, t.query = r.scheme, r.authority, Url.removeDotSegments(r.path), r.query
+ else
+ if r.authority then
+ t.authority, t.path, t.query = r.authority, Url.removeDotSegments(r.path), r.query
+ else
+ if r.path == "" then
+ t.path = b.path
+ t.query = if r.query then r.query else b.query
+ else
+ if string.sub(r.path, 1, 1) == "/" then
+ t.path = Url.removeDotSegments(r.path)
+ else
+ -- merge (5.2.3)
+ local merged
+ if b.authority and b.path == "" then
+ merged = "/" .. r.path
+ else
+ local k = string.match(b.path, "^.*()/")
+ merged = (if k then string.sub(b.path, 1, k) else "") .. r.path
+ end
+ t.path = Url.removeDotSegments(merged)
+ end
+ t.query = r.query
+ end
+ t.authority = b.authority
+ end
+ t.scheme = b.scheme
+ end
+ t.fragment = r.fragment
+ 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.
+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
+ or string.sub(s, 1, 2) == "\\\\"
+ 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
+ end
+ local scheme = string.match(s, "^([%a][%w+%.%-]*):")
+ 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
+ return { url = loc, playable = false, reason = "local path" }
+ end
+ 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
+ if scheme then
+ if scheme == "http" or scheme == "https" then
+ 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
+ return { url = loc, playable = false, reason = "relative path without a base URL" }
+ end
+ if scheme == "http" or scheme == "https" then
+ return { url = url, playable = true }
+ elseif scheme == "file" then
+ return { url = url, playable = false, reason = "local path" }
+ end
+ 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
+ end
+ local s = Url.scheme(baseUrl)
+ if s and Url.split(baseUrl).authority ~= nil or s == "file" then
+ return Url.encodeUnsafe(baseUrl), s
+ elseif Url.isWindowsPath(baseUrl) then
+ return baseUrl, "windows"
+ end
+ if warnings then
+ table.insert(warnings, "base URL is not absolute: " .. baseUrl)
+ end
+ return nil, nil
+end
+
+return Url
diff --git a/src/Formats/codecs/Vp8/Decode.luau b/src/Formats/codecs/Vp8/Decode.luau
new file mode 100644
index 0000000..eacff53
--- /dev/null
+++ b/src/Formats/codecs/Vp8/Decode.luau
@@ -0,0 +1,1353 @@
+--!strict
+--!native
+--!optimize 2
+-- codecs/Vp8/Decode: the VP8 key 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), bit-exact with it (libwebp is deterministic; so is this).
+--
+-- The decoder state (Decode.new) keeps what persists between frames (token probabilities, segment and filter
+-- headers) so inter frames can be added later for WebM: decodeFrame() returns UNSUPPORTED for them today.
+-- Never throws: bad data returns nil, "message" ("truncated: ..." when the data ends early).
+local Tables = require("@formats/codecs/Vp8/Tables")
+
+local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift
+local readu8, writeu8, readi16, writei16 = buffer.readu8, buffer.writeu8, buffer.readi16, buffer.writei16
+local bfill, bcopy, bcreate = buffer.fill, buffer.copy, buffer.create
+local abs = math.abs
+
+local COEFF_PROBA0 = Tables.COEFF_PROBA0
+local COEFF_UPDATE_PROBA = Tables.COEFF_UPDATE_PROBA
+local BMODES_PROBA = Tables.BMODES_PROBA
+local DC_TABLE, AC_TABLE = Tables.DC_TABLE, Tables.AC_TABLE
+local BANDS, ZIGZAG = Tables.BANDS, Tables.ZIGZAG
+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 }
+
+-- SHIFT[r + 1]: the normalisation shift of a range r (1..255) = 7 - floor(log2 r)
+local SHIFT = table.create(256, 0)
+for r = 1, 255 do
+ local s, v = 0, r
+ while v < 128 do
+ v *= 2
+ s += 1
+ end
+ SHIFT[r + 1] = s
+end
+
+local function load(br: Br)
+ local p = br.pos
+ if p + 3 <= br.limit then
+ local b = br.buf
+ br.value = br.value * 16777216 + readu8(b, p) * 65536 + readu8(b, p + 1) * 256 + readu8(b, p + 2)
+ br.pos = p + 3
+ br.bits += 24
+ elseif p < br.limit then
+ br.value = br.value * 256 + readu8(br.buf, p)
+ br.pos = p + 1
+ br.bits += 8
+ elseif not br.eof then
+ br.value *= 256
+ br.bits += 8
+ br.eof = true
+ else
+ br.bits = 0
+ end
+end
+
+local function newBr(buf: buffer, off: number, len: number): Br
+ local br = { buf = buf, pos = off, limit = off + len, value = 0, bits = -8, range = 254, eof = false }
+ load(br)
+ return br
+end
+
+local function getBit(br: Br, prob: number): number
+ if br.bits < 0 then
+ load(br)
+ end
+ local range = br.range
+ local pos = br.bits
+ local split = rshift(range * prob, 8)
+ local bit = 0
+ if rshift(br.value, pos) > split then
+ range -= split
+ br.value -= (split + 1) * 2 ^ pos
+ bit = 1
+ else
+ range = split + 1
+ end
+ local shift = SHIFT[range + 1]
+ br.range = lshift(range, shift) - 1
+ br.bits = pos - shift
+ return bit
+end
+
+local function getValue(br: Br, n: number): number
+ local v = 0
+ for i = n - 1, 0, -1 do
+ v += getBit(br, 0x80) * 2 ^ i
+ end
+ return v
+end
+
+local function getSignedValue(br: Br, n: number): number
+ local v = getValue(br, n)
+ 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 }
+
+export type State = {
+ -- persistent between frames (inter frames: TODO)
+ proba: { number }, -- 4 * 8 * 3 * 11 token probabilities
+ segProba: { number }, -- 3
+ useSegment: boolean,
+ updateMap: boolean,
+ absoluteDelta: boolean,
+ segQuant: { number }, -- 4
+ segFilter: { number }, -- 4
+ refLfDelta: { number }, -- 4
+ modeLfDelta: { number }, -- 4
+ width: number,
+ height: number,
+}
+
+function Decode.new(): State
+ return {
+ proba = table.clone(COEFF_PROBA0),
+ segProba = { 255, 255, 255 },
+ useSegment = false,
+ updateMap = false,
+ absoluteDelta = true,
+ segQuant = { 0, 0, 0, 0 },
+ segFilter = { 0, 0, 0, 0 },
+ refLfDelta = { 0, 0, 0, 0 },
+ modeLfDelta = { 0, 0, 0, 0 },
+ width = 0,
+ height = 0,
+ }
+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"
+ end
+ local bits = readu8(buf, off) + readu8(buf, off + 1) * 256 + readu8(buf, off + 2) * 65536
+ local h = {
+ keyFrame = band(bits, 1) == 0,
+ profile = band(rshift(bits, 1), 7),
+ show = band(rshift(bits, 4), 1) == 1,
+ partitionLength = rshift(bits, 5),
+ width = 0,
+ height = 0,
+ xscale = 0,
+ yscale = 0,
+ }
+ if h.profile > 3 then
+ return nil, "bad profile " .. h.profile
+ end
+ if h.keyFrame then
+ if len < 10 then
+ return nil, "truncated: key frame header"
+ end
+ if readu8(buf, off + 3) ~= 0x9d or readu8(buf, off + 4) ~= 0x01 or readu8(buf, off + 5) ~= 0x2a then
+ return nil, "bad VP8 start code"
+ end
+ local w = readu8(buf, off + 6) + readu8(buf, off + 7) * 256
+ local ht = readu8(buf, off + 8) + readu8(buf, off + 9) * 256
+ h.width, h.xscale = band(w, 0x3fff), rshift(w, 14)
+ h.height, h.yscale = band(ht, 0x3fff), rshift(ht, 14)
+ end
+ 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
+ if getBit(br, P[p + 5]) == 0 then
+ v = 2
+ else
+ v = 3 + getBit(br, P[p + 6])
+ end
+ else
+ if getBit(br, P[p + 7]) == 0 then
+ if getBit(br, P[p + 8]) == 0 then
+ v = 5 + getBit(br, 159)
+ else
+ v = 7 + 2 * getBit(br, 165)
+ v += getBit(br, 145)
+ end
+ else
+ local bit1 = getBit(br, P[p + 9])
+ local bit0 = getBit(br, P[p + 10 + bit1])
+ local cat = 2 * bit1 + bit0
+ v = 0
+ for _, pr in CAT[cat + 1] do
+ v = v + v + getBit(br, pr)
+ end
+ v += 3 + lshift(8, cat)
+ end
+ end
+ 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.
+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
+ local buf, limit = br.buf, br.limit
+ local value, bits, range, pos = br.value, br.bits, br.range, br.pos
+ while n < 16 do
+ do
+ if bits < 0 then
+ if pos + 3 <= limit then
+ value = value * 16777216 + readu8(buf, pos) * 65536 + readu8(buf, pos + 1) * 256 + readu8(buf, pos + 2)
+ pos += 3
+ bits += 24
+ else
+ br.value, br.bits, br.pos = value, bits, pos
+ load(br)
+ value, bits, pos = br.value, br.bits, br.pos
+ end
+ end
+ local split = rshift(range * P[p + 1], 8)
+ local more = rshift(value, bits) > split
+ if more then
+ range -= split
+ value -= lshift(split + 1, bits)
+ else
+ range = split + 1
+ end
+ local sh = SHIFT[range + 1]
+ range = lshift(range, sh) - 1
+ bits -= sh
+ if not more then
+ br.value, br.bits, br.range, br.pos = value, bits, range, pos
+ return n
+ end
+ end
+ while true do
+ if bits < 0 then
+ if pos + 3 <= limit then
+ value = value * 16777216 + readu8(buf, pos) * 65536 + readu8(buf, pos + 1) * 256 + readu8(buf, pos + 2)
+ pos += 3
+ bits += 24
+ else
+ br.value, br.bits, br.pos = value, bits, pos
+ load(br)
+ value, bits, pos = br.value, br.bits, br.pos
+ end
+ end
+ local split = rshift(range * P[p + 2], 8)
+ local nonzero = rshift(value, bits) > split
+ if nonzero then
+ range -= split
+ value -= lshift(split + 1, bits)
+ else
+ range = split + 1
+ end
+ local sh = SHIFT[range + 1]
+ range = lshift(range, sh) - 1
+ bits -= sh
+ if nonzero then
+ break
+ end
+ n += 1
+ if n == 16 then
+ br.value, br.bits, br.range, br.pos = value, bits, range, pos
+ return 16
+ end
+ p = (tb + BANDS[n + 1]) * 33
+ end
+ local nb = (tb + BANDS[n + 2]) * 3
+ local v
+ do
+ if bits < 0 then
+ if pos + 3 <= limit then
+ value = value * 16777216 + readu8(buf, pos) * 65536 + readu8(buf, pos + 1) * 256 + readu8(buf, pos + 2)
+ pos += 3
+ bits += 24
+ else
+ br.value, br.bits, br.pos = value, bits, pos
+ load(br)
+ value, bits, pos = br.value, br.bits, br.pos
+ end
+ end
+ local split = rshift(range * P[p + 3], 8)
+ local large = rshift(value, bits) > split
+ if large then
+ range -= split
+ value -= lshift(split + 1, bits)
+ else
+ range = split + 1
+ end
+ local sh = SHIFT[range + 1]
+ range = lshift(range, sh) - 1
+ bits -= sh
+ if not large then
+ v = 1
+ p = (nb + 1) * 11
+ else
+ br.value, br.bits, br.range, br.pos = value, bits, range, pos
+ v = getLargeValue(br, P, p)
+ value, bits, range, pos = br.value, br.bits, br.range, br.pos
+ p = (nb + 2) * 11
+ end
+ end
+ do
+ if bits < 0 then
+ if pos + 3 <= limit then
+ value = value * 16777216 + readu8(buf, pos) * 65536 + readu8(buf, pos + 1) * 256 + readu8(buf, pos + 2)
+ pos += 3
+ bits += 24
+ else
+ br.value, br.bits, br.pos = value, bits, pos
+ load(br)
+ value, bits, pos = br.value, br.bits, br.pos
+ end
+ end
+ local split = rshift(range * 0x80, 8)
+ local neg = rshift(value, bits) > split
+ if neg then
+ range -= split
+ value -= lshift(split + 1, bits)
+ else
+ range = split + 1
+ end
+ local sh = SHIFT[range + 1]
+ range = lshift(range, sh) - 1
+ bits -= sh
+ if neg then
+ v = -v
+ end
+ end
+ writei16(out, o + ZIGZAG[n + 1] * 2, v * (if n > 0 then dqAc else dqDc))
+ n += 1
+ end
+ br.value, br.bits, br.range, br.pos = value, bits, range, pos
+ return 16
+end
+
+local function nzCode(acc: number, nz: number, dcNz: number): number
+ return acc * 4 + (if nz > 3 then 3 elseif nz > 1 then 2 else dcNz)
+end
+
+-- the inverse Walsh-Hadamard transform of the 16 Y2 coefficients into the DC of the 16 luma blocks
+local whtTmp = table.create(16, 0)
+local function transformWHT(inp: buffer, out: buffer, o: number)
+ for i = 0, 3 do
+ local i0, i4, i8, i12 = readi16(inp, i * 2), readi16(inp, (4 + i) * 2), readi16(inp, (8 + i) * 2), readi16(inp, (12 + i) * 2)
+ local a0 = i0 + i12
+ local a1 = i4 + i8
+ local a2 = i4 - i8
+ local a3 = i0 - i12
+ whtTmp[1 + i] = a0 + a1
+ whtTmp[9 + i] = a0 - a1
+ whtTmp[5 + i] = a3 + a2
+ whtTmp[13 + i] = a3 - a2
+ end
+ for i = 0, 3 do
+ local dc = whtTmp[1 + i * 4] + 3
+ local a0 = dc + whtTmp[4 + i * 4]
+ local a1 = whtTmp[2 + i * 4] + whtTmp[3 + i * 4]
+ local a2 = whtTmp[2 + i * 4] - whtTmp[3 + i * 4]
+ local a3 = dc - whtTmp[4 + i * 4]
+ local base = o + i * 128
+ writei16(out, base, (a0 + a1) // 8)
+ writei16(out, base + 32, (a3 + a2) // 8)
+ writei16(out, base + 64, (a0 - a1) // 8)
+ writei16(out, base + 96, (a3 - a2) // 8)
+ 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
+local U_OFF = Y_OFF + BPS * 16 + BPS
+local V_OFF = U_OFF + 16
+local YUV_SIZE = BPS * 17 + BPS * 9
+
+local function clip8(v: number): number
+ return if v < 0 then 0 elseif v > 255 then 255 else v
+end
+
+-- the inverse DCT of one block (libwebp TransformOne) added to dst
+local C1, C2 = 20091, 35468
+local idctTmp = table.create(16, 0)
+local function mul1(a: number): number
+ return ((a * C1) // 65536) + a
+end
+local function mul2(a: number): number
+ return (a * C2) // 65536
+end
+local function transformOne(c: buffer, o: number, b: buffer, dst: number)
+ for i = 0, 3 do
+ local i0, i4, i8, i12 = readi16(c, o + i * 2), readi16(c, o + (4 + i) * 2), readi16(c, o + (8 + i) * 2), readi16(c, o + (12 + i) * 2)
+ local a = i0 + i8
+ local bb = i0 - i8
+ local cc = mul2(i4) - mul1(i12)
+ local d = mul1(i4) + mul2(i12)
+ idctTmp[i * 4 + 1] = a + d
+ idctTmp[i * 4 + 2] = bb + cc
+ idctTmp[i * 4 + 3] = bb - cc
+ idctTmp[i * 4 + 4] = a - d
+ end
+ for i = 0, 3 do
+ local dc = idctTmp[i + 1] + 4
+ local a = dc + idctTmp[i + 9]
+ local bb = dc - idctTmp[i + 9]
+ local cc = mul2(idctTmp[i + 5]) - mul1(idctTmp[i + 13])
+ local d = mul1(idctTmp[i + 5]) + mul2(idctTmp[i + 13])
+ local row = dst + i * BPS
+ writeu8(b, row, clip8(readu8(b, row) + (a + d) // 8))
+ writeu8(b, row + 1, clip8(readu8(b, row + 1) + (bb + cc) // 8))
+ writeu8(b, row + 2, clip8(readu8(b, row + 2) + (bb - cc) // 8))
+ writeu8(b, row + 3, clip8(readu8(b, row + 3) + (a - d) // 8))
+ end
+end
+
+local function transformDC(c: buffer, o: number, b: buffer, dst: number)
+ local dc = (readi16(c, o) + 4) // 8
+ for j = 0, 3 do
+ local row = dst + j * BPS
+ for i = row, row + 3 do
+ writeu8(b, i, clip8(readu8(b, i) + dc))
+ end
+ end
+end
+
+-- code: 3 = full transform, 2 = only the first three coefficients (the same result as the full one), 1 = DC only
+local function doTransform(code: number, c: buffer, o: number, b: buffer, dst: number)
+ if code >= 2 then
+ transformOne(c, o, b, dst)
+ elseif code == 1 then
+ transformDC(c, o, b, dst)
+ end
+end
+
+local function doUVTransform(bits: number, c: buffer, o: number, b: buffer, dst: number)
+ if band(bits, 0xff) ~= 0 then
+ if band(bits, 0xaa) ~= 0 then
+ transformOne(c, o, b, dst)
+ transformOne(c, o + 32, b, dst + 4)
+ transformOne(c, o + 64, b, dst + 4 * BPS)
+ transformOne(c, o + 96, b, dst + 4 * BPS + 4)
+ else
+ if readi16(c, o) ~= 0 then
+ transformDC(c, o, b, dst)
+ end
+ if readi16(c, o + 32) ~= 0 then
+ transformDC(c, o + 32, b, dst + 4)
+ end
+ if readi16(c, o + 64) ~= 0 then
+ transformDC(c, o + 64, b, dst + 4 * BPS)
+ end
+ if readi16(c, o + 96) ~= 0 then
+ transformDC(c, o + 96, b, dst + 4 * BPS + 4)
+ end
+ end
+ end
+end
+
+-- prediction: modes 0 DC, 1 TM, 2 VE, 3 HE; 4 DC no top, 5 DC no left, 6 DC no top-left (16x16 and chroma)
+local function fill(b: buffer, dst: number, size: number, v: number)
+ for j = 0, size - 1 do
+ bfill(b, dst + j * BPS, v, size)
+ end
+end
+
+local function trueMotion(b: buffer, dst: number, size: number)
+ local tl = readu8(b, dst - BPS - 1)
+ for y = 0, size - 1 do
+ local row = dst + y * BPS
+ local l = readu8(b, row - 1) - tl
+ for x = 0, size - 1 do
+ writeu8(b, row + x, clip8(readu8(b, dst - BPS + x) + l))
+ end
+ end
+end
+
+local function predictBlock(b: buffer, dst: number, size: number, mode: number)
+ local shift = if size == 16 then 5 else 4
+ if mode == 0 then
+ local dc = size
+ for j = 0, size - 1 do
+ dc += readu8(b, dst - 1 + j * BPS) + readu8(b, dst + j - BPS)
+ end
+ fill(b, dst, size, rshift(dc, shift))
+ elseif mode == 1 then
+ trueMotion(b, dst, size)
+ elseif mode == 2 then
+ for j = 0, size - 1 do
+ bcopy(b, dst + j * BPS, b, dst - BPS, size)
+ end
+ elseif mode == 3 then
+ for j = 0, size - 1 do
+ bfill(b, dst + j * BPS, readu8(b, dst + j * BPS - 1), size)
+ end
+ elseif mode == 4 then -- no top: left samples
+ local dc = size // 2
+ for j = 0, size - 1 do
+ dc += readu8(b, dst - 1 + j * BPS)
+ end
+ fill(b, dst, size, rshift(dc, shift - 1))
+ elseif mode == 5 then -- no left: top samples
+ local dc = size // 2
+ for j = 0, size - 1 do
+ dc += readu8(b, dst + j - BPS)
+ end
+ fill(b, dst, size, rshift(dc, shift - 1))
+ else
+ fill(b, dst, size, 0x80)
+ end
+end
+
+local function avg3(a: number, b: number, c: number): number
+ return rshift(a + 2 * b + c + 2, 2)
+end
+local function avg2(a: number, b: number): number
+ return rshift(a + b + 1, 1)
+end
+
+-- 4x4 prediction (libwebp VP8PredLuma4): 0 DC, 1 TM, 2 VE, 3 HE, 4 RD, 5 VR, 6 LD, 7 VL, 8 HD, 9 HU
+local function predict4(b: buffer, dst: number, mode: number)
+ if mode == 0 then
+ local dc = 4
+ for i = 0, 3 do
+ dc += readu8(b, dst + i - BPS) + readu8(b, dst - 1 + i * BPS)
+ end
+ fill(b, dst, 4, rshift(dc, 3))
+ elseif mode == 1 then
+ trueMotion(b, dst, 4)
+ elseif mode == 2 then
+ local t = dst - BPS
+ local x, a, bb, c, d, e = readu8(b, t - 1), readu8(b, t), readu8(b, t + 1), readu8(b, t + 2), readu8(b, t + 3), readu8(b, t + 4)
+ local v0, v1, v2, v3 = avg3(x, a, bb), avg3(a, bb, c), avg3(bb, c, d), avg3(c, d, e)
+ for j = 0, 3 do
+ writeu8(b, dst + j * BPS + 0, v0)
+ writeu8(b, dst + j * BPS + 1, v1)
+ writeu8(b, dst + j * BPS + 2, v2)
+ writeu8(b, dst + j * BPS + 3, v3)
+ end
+ elseif mode == 3 then
+ local A, B, C, D = readu8(b, dst - 1 - BPS), readu8(b, dst - 1), readu8(b, dst - 1 + BPS), readu8(b, dst - 1 + 2 * BPS)
+ local E = readu8(b, dst - 1 + 3 * BPS)
+ bfill(b, dst, avg3(A, B, C), 4)
+ bfill(b, dst + BPS, avg3(B, C, D), 4)
+ bfill(b, dst + 2 * BPS, avg3(C, D, E), 4)
+ bfill(b, dst + 3 * BPS, avg3(D, E, E), 4)
+ else
+ local I, J, K, L = readu8(b, dst - 1), readu8(b, dst - 1 + BPS), readu8(b, dst - 1 + 2 * BPS), readu8(b, dst - 1 + 3 * BPS)
+ local t = dst - BPS
+ local X, A, B, C, D = readu8(b, t - 1), readu8(b, t), readu8(b, t + 1), readu8(b, t + 2), readu8(b, t + 3)
+ local E, F, G, H = readu8(b, t + 4), readu8(b, t + 5), readu8(b, t + 6), readu8(b, t + 7)
+ if mode == 4 then -- RD
+ writeu8(b, dst + 96, avg3(J, K, L))
+ local v = avg3(I, J, K)
+ writeu8(b, dst + 97, v)
+ writeu8(b, dst + 64, v)
+ v = avg3(X, I, J)
+ writeu8(b, dst + 98, v)
+ writeu8(b, dst + 65, v)
+ writeu8(b, dst + 32, v)
+ v = avg3(A, X, I)
+ writeu8(b, dst + 99, v)
+ writeu8(b, dst + 66, v)
+ writeu8(b, dst + 33, v)
+ writeu8(b, dst + 0, v)
+ v = avg3(B, A, X)
+ writeu8(b, dst + 67, v)
+ writeu8(b, dst + 34, v)
+ writeu8(b, dst + 1, v)
+ v = avg3(C, B, A)
+ writeu8(b, dst + 35, v)
+ writeu8(b, dst + 2, v)
+ writeu8(b, dst + 3, avg3(D, C, B))
+ elseif mode == 5 then -- VR
+ local v = avg2(X, A)
+ writeu8(b, dst + 0, v)
+ writeu8(b, dst + 65, v)
+ v = avg2(A, B)
+ writeu8(b, dst + 1, v)
+ writeu8(b, dst + 66, v)
+ v = avg2(B, C)
+ writeu8(b, dst + 2, v)
+ writeu8(b, dst + 67, v)
+ writeu8(b, dst + 3, avg2(C, D))
+ writeu8(b, dst + 96, avg3(K, J, I))
+ writeu8(b, dst + 64, avg3(J, I, X))
+ v = avg3(I, X, A)
+ writeu8(b, dst + 32, v)
+ writeu8(b, dst + 97, v)
+ v = avg3(X, A, B)
+ writeu8(b, dst + 33, v)
+ writeu8(b, dst + 98, v)
+ v = avg3(A, B, C)
+ writeu8(b, dst + 34, v)
+ writeu8(b, dst + 99, v)
+ writeu8(b, dst + 35, avg3(B, C, D))
+ elseif mode == 6 then -- LD
+ writeu8(b, dst + 0, avg3(A, B, C))
+ local v = avg3(B, C, D)
+ writeu8(b, dst + 1, v)
+ writeu8(b, dst + 32, v)
+ v = avg3(C, D, E)
+ writeu8(b, dst + 2, v)
+ writeu8(b, dst + 33, v)
+ writeu8(b, dst + 64, v)
+ v = avg3(D, E, F)
+ writeu8(b, dst + 3, v)
+ writeu8(b, dst + 34, v)
+ writeu8(b, dst + 65, v)
+ writeu8(b, dst + 96, v)
+ v = avg3(E, F, G)
+ writeu8(b, dst + 35, v)
+ writeu8(b, dst + 66, v)
+ writeu8(b, dst + 97, v)
+ v = avg3(F, G, H)
+ writeu8(b, dst + 67, v)
+ writeu8(b, dst + 98, v)
+ writeu8(b, dst + 99, avg3(G, H, H))
+ elseif mode == 7 then -- VL
+ writeu8(b, dst + 0, avg2(A, B))
+ local v = avg2(B, C)
+ writeu8(b, dst + 1, v)
+ writeu8(b, dst + 64, v)
+ v = avg2(C, D)
+ writeu8(b, dst + 2, v)
+ writeu8(b, dst + 65, v)
+ v = avg2(D, E)
+ writeu8(b, dst + 3, v)
+ writeu8(b, dst + 66, v)
+ writeu8(b, dst + 32, avg3(A, B, C))
+ v = avg3(B, C, D)
+ writeu8(b, dst + 33, v)
+ writeu8(b, dst + 96, v)
+ v = avg3(C, D, E)
+ writeu8(b, dst + 34, v)
+ writeu8(b, dst + 97, v)
+ v = avg3(D, E, F)
+ writeu8(b, dst + 35, v)
+ writeu8(b, dst + 98, v)
+ writeu8(b, dst + 67, avg3(E, F, G))
+ writeu8(b, dst + 99, avg3(F, G, H))
+ elseif mode == 8 then -- HD
+ local v = avg2(I, X)
+ writeu8(b, dst + 0, v)
+ writeu8(b, dst + 34, v)
+ v = avg2(J, I)
+ writeu8(b, dst + 32, v)
+ writeu8(b, dst + 66, v)
+ v = avg2(K, J)
+ writeu8(b, dst + 64, v)
+ writeu8(b, dst + 98, v)
+ writeu8(b, dst + 96, avg2(L, K))
+ writeu8(b, dst + 3, avg3(A, B, C))
+ writeu8(b, dst + 2, avg3(X, A, B))
+ v = avg3(I, X, A)
+ writeu8(b, dst + 1, v)
+ writeu8(b, dst + 35, v)
+ v = avg3(J, I, X)
+ writeu8(b, dst + 33, v)
+ writeu8(b, dst + 67, v)
+ v = avg3(K, J, I)
+ writeu8(b, dst + 65, v)
+ writeu8(b, dst + 99, v)
+ writeu8(b, dst + 97, avg3(L, K, J))
+ else -- HU
+ writeu8(b, dst + 0, avg2(I, J))
+ local v = avg2(J, K)
+ writeu8(b, dst + 2, v)
+ writeu8(b, dst + 32, v)
+ v = avg2(K, L)
+ writeu8(b, dst + 34, v)
+ writeu8(b, dst + 64, v)
+ writeu8(b, dst + 1, avg3(I, J, K))
+ v = avg3(J, K, L)
+ writeu8(b, dst + 3, v)
+ writeu8(b, dst + 33, v)
+ v = avg3(K, L, L)
+ writeu8(b, dst + 35, v)
+ writeu8(b, dst + 65, v)
+ writeu8(b, dst + 67, L)
+ writeu8(b, dst + 66, L)
+ writeu8(b, dst + 96, L)
+ writeu8(b, dst + 97, L)
+ writeu8(b, dst + 98, L)
+ writeu8(b, dst + 99, L)
+ end
+ end
+end
+
+local function checkMode(mbx: number, mby: number, mode: number): number
+ if mode == 0 then
+ if mbx == 0 then
+ return if mby == 0 then 6 else 5
+ end
+ return if mby == 0 then 4 else 0
+ end
+ return mode
+end
+
+-- ------------------------------------------------------------------------------------------------ loop filter
+local function sclip1(v: number): number
+ return if v < -128 then -128 elseif v > 127 then 127 else v
+end
+local function sclip2(v: number): number
+ return if v < -16 then -16 elseif v > 15 then 15 else v
+end
+
+local function doFilter2(b: buffer, p: number, step: number)
+ local p1, p0, q0, q1 = readu8(b, p - 2 * step), readu8(b, p - step), readu8(b, p), readu8(b, p + step)
+ local a = 3 * (q0 - p0) + sclip1(p1 - q1)
+ local a1 = sclip2((a + 4) // 8)
+ local a2 = sclip2((a + 3) // 8)
+ writeu8(b, p - step, clip8(p0 + a2))
+ writeu8(b, p, clip8(q0 - a1))
+end
+
+local function doFilter4(b: buffer, p: number, step: number)
+ local p1, p0, q0, q1 = readu8(b, p - 2 * step), readu8(b, p - step), readu8(b, p), readu8(b, p + step)
+ local a = 3 * (q0 - p0)
+ local a1 = sclip2((a + 4) // 8)
+ local a2 = sclip2((a + 3) // 8)
+ local a3 = (a1 + 1) // 2
+ writeu8(b, p - 2 * step, clip8(p1 + a3))
+ writeu8(b, p - step, clip8(p0 + a2))
+ writeu8(b, p, clip8(q0 - a1))
+ writeu8(b, p + step, clip8(q1 - a3))
+end
+
+local function doFilter6(b: buffer, p: number, step: number)
+ local p2, p1, p0 = readu8(b, p - 3 * step), readu8(b, p - 2 * step), readu8(b, p - step)
+ local q0, q1, q2 = readu8(b, p), readu8(b, p + step), readu8(b, p + 2 * step)
+ local a = sclip1(3 * (q0 - p0) + sclip1(p1 - q1))
+ local a1 = (27 * a + 63) // 128
+ local a2 = (18 * a + 63) // 128
+ local a3 = (9 * a + 63) // 128
+ writeu8(b, p - 3 * step, clip8(p2 + a3))
+ writeu8(b, p - 2 * step, clip8(p1 + a2))
+ writeu8(b, p - step, clip8(p0 + a1))
+ writeu8(b, p, clip8(q0 - a1))
+ writeu8(b, p + step, clip8(q1 - a2))
+ writeu8(b, p + 2 * step, clip8(q2 - a3))
+end
+
+local function simpleFilter(b: buffer, p: number, step: number, along: number, thresh: number)
+ local t2 = 2 * thresh + 1
+ for i = 0, 15 do
+ local q = p + i * along
+ local p1, p0, q0, q1 = readu8(b, q - 2 * step), readu8(b, q - step), readu8(b, q), readu8(b, q + step)
+ if 4 * abs(p0 - q0) + abs(p1 - q1) <= t2 then
+ doFilter2(b, q, step)
+ end
+ end
+end
+
+-- filterLoop(b, p, hstride, vstride, size, thresh, ithresh, hevThresh, six): FilterLoop26 (six) / FilterLoop24
+local function filterLoop(b: buffer, p: number, hs: number, vs: number, size: number, thresh: number, it: number, hevT: number, six: boolean)
+ local t2 = 2 * thresh + 1
+ for _ = 1, size do
+ local p1, p0, q0, q1 = readu8(b, p - 2 * hs), readu8(b, p - hs), readu8(b, p), readu8(b, p + hs)
+ if 4 * abs(p0 - q0) + abs(p1 - q1) <= t2 and abs(p1 - p0) <= it and abs(q1 - q0) <= it then
+ local p3, p2 = readu8(b, p - 4 * hs), readu8(b, p - 3 * hs)
+ local q2, q3 = readu8(b, p + 2 * hs), readu8(b, p + 3 * hs)
+ if abs(p3 - p2) <= it and abs(p2 - p1) <= it and abs(q3 - q2) <= it and abs(q2 - q1) <= it then
+ if abs(p1 - p0) > hevT or abs(q1 - q0) > hevT then
+ doFilter2(b, p, hs)
+ elseif six then
+ doFilter6(b, p, hs)
+ else
+ doFilter4(b, p, hs)
+ end
+ end
+ end
+ p += vs
+ end
+end
+
+-- ------------------------------------------------------------------------------------------------ frame
+export type Frame = {
+ width: number,
+ height: number,
+ y: buffer, -- width * height
+ u: buffer, -- ceil(w / 2) * ceil(h / 2)
+ v: buffer,
+ header: any,
+}
+
+-- decodeFrame(state, buf, off, len, maxPixels) -> Frame | nil, message
+function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, maxPixels: number): (Frame?, string?)
+ local hdr, herr = Decode.header(buf, off, len)
+ if not hdr then
+ return nil, herr
+ end
+ if not hdr.keyFrame then
+ return nil, "unsupported: inter frames"
+ end
+ if not hdr.show then
+ return nil, "unsupported: invisible frame"
+ end
+ local width, height = hdr.width, hdr.height
+ if width == 0 or height == 0 then
+ return nil, "zero frame size"
+ end
+ if width * height > maxPixels then
+ return nil, "limit: " .. width .. " x " .. height .. " is over maxPixels"
+ end
+ st.width, st.height = width, height
+ local p = off + 10
+ local left = len - 10
+ if hdr.partitionLength > left then
+ return nil, "truncated: first partition"
+ end
+ -- key frame: reset the probabilities and the segment header
+ st.segProba = { 255, 255, 255 }
+ st.useSegment, st.updateMap, st.absoluteDelta = false, false, true
+ st.segQuant = { 0, 0, 0, 0 }
+ st.segFilter = { 0, 0, 0, 0 }
+ local br = newBr(buf, p, hdr.partitionLength)
+ p += hdr.partitionLength
+ left -= hdr.partitionLength
+ getValue(br, 1) -- colour space
+ getValue(br, 1) -- clamping type
+ -- segment header
+ st.useSegment = getValue(br, 1) == 1
+ if st.useSegment then
+ st.updateMap = getValue(br, 1) == 1
+ if getValue(br, 1) == 1 then
+ st.absoluteDelta = getValue(br, 1) == 1
+ for s = 1, 4 do
+ st.segQuant[s] = if getValue(br, 1) == 1 then getSignedValue(br, 7) else 0
+ end
+ for s = 1, 4 do
+ st.segFilter[s] = if getValue(br, 1) == 1 then getSignedValue(br, 6) else 0
+ end
+ end
+ if st.updateMap then
+ for s = 1, 3 do
+ st.segProba[s] = if getValue(br, 1) == 1 then getValue(br, 8) else 255
+ end
+ end
+ else
+ st.updateMap = false
+ end
+ if br.eof then
+ return nil, "truncated: segment header"
+ end
+ -- filter header
+ local simple = getValue(br, 1) == 1
+ local level = getValue(br, 6)
+ local sharpness = getValue(br, 3)
+ local useLfDelta = getValue(br, 1) == 1
+ if useLfDelta then
+ if getValue(br, 1) == 1 then
+ for i = 1, 4 do
+ if getValue(br, 1) == 1 then
+ st.refLfDelta[i] = getSignedValue(br, 6)
+ end
+ end
+ for i = 1, 4 do
+ if getValue(br, 1) == 1 then
+ st.modeLfDelta[i] = getSignedValue(br, 6)
+ end
+ end
+ end
+ end
+ local filterType = if level == 0 then 0 elseif simple then 1 else 2
+ if br.eof then
+ return nil, "truncated: filter header"
+ end
+ -- partitions
+ local numParts = lshift(1, getValue(br, 2))
+ local lastPart = numParts - 1
+ if left < 3 * lastPart then
+ return nil, "truncated: partition sizes"
+ end
+ local parts: { Br } = {}
+ local partStart = p + lastPart * 3
+ local sizeLeft = left - lastPart * 3
+ for k = 0, lastPart - 1 do
+ local q = p + k * 3
+ local psize = readu8(buf, q) + readu8(buf, q + 1) * 256 + readu8(buf, q + 2) * 65536
+ if psize > sizeLeft then
+ psize = sizeLeft
+ end
+ parts[k + 1] = newBr(buf, partStart, psize)
+ partStart += psize
+ sizeLeft -= psize
+ end
+ parts[numParts] = newBr(buf, partStart, sizeLeft)
+ if partStart >= off + len then
+ return nil, "truncated: partitions"
+ end
+ -- quantizers
+ local baseQ = getValue(br, 7)
+ local dqy1dc = if getValue(br, 1) == 1 then getSignedValue(br, 4) else 0
+ local dqy2dc = if getValue(br, 1) == 1 then getSignedValue(br, 4) else 0
+ local dqy2ac = if getValue(br, 1) == 1 then getSignedValue(br, 4) else 0
+ local dquvdc = if getValue(br, 1) == 1 then getSignedValue(br, 4) else 0
+ local dquvac = if getValue(br, 1) == 1 then getSignedValue(br, 4) else 0
+ local quants: { Quant } = {}
+ for s = 1, 4 do
+ local q
+ if st.useSegment then
+ q = st.segQuant[s]
+ if not st.absoluteDelta then
+ q += baseQ
+ end
+ else
+ q = baseQ
+ end
+ local function cq(v: number, m: number): number
+ return if v < 0 then 0 elseif v > m then m else v
+ end
+ local y2ac = (AC_TABLE[cq(q + dqy2ac, 127) + 1] * 101581) // 65536
+ if y2ac < 8 then
+ y2ac = 8
+ end
+ quants[s] = {
+ y1dc = DC_TABLE[cq(q + dqy1dc, 127) + 1],
+ y1ac = AC_TABLE[cq(q, 127) + 1],
+ y2dc = DC_TABLE[cq(q + dqy2dc, 127) + 1] * 2,
+ y2ac = y2ac,
+ uvdc = DC_TABLE[cq(q + dquvdc, 117) + 1],
+ uvac = AC_TABLE[cq(q + dquvac, 127) + 1],
+ }
+ end
+ getValue(br, 1) -- refresh entropy probabilities (ignored, as libwebp does)
+ -- token probabilities
+ local P = st.proba
+ for i = 1, 1056 do
+ P[i] = if getBit(br, COEFF_UPDATE_PROBA[i]) == 1 then getValue(br, 8) else COEFF_PROBA0[i]
+ end
+ local useSkip = getValue(br, 1) == 1
+ local skipP = if useSkip then getValue(br, 8) else 0
+ if br.eof then
+ return nil, "truncated: frame header"
+ end
+
+ -- filter strengths per segment and i4x4: { limit, ilevel, hevThresh }
+ local fstr: { { number } } = {}
+ for s = 1, 4 do
+ local base
+ if st.useSegment then
+ base = st.segFilter[s]
+ if not st.absoluteDelta then
+ base += level
+ end
+ else
+ base = level
+ end
+ for i4 = 0, 1 do
+ local lv = base
+ if useLfDelta then
+ lv += st.refLfDelta[1]
+ if i4 == 1 then
+ lv += st.modeLfDelta[1]
+ end
+ end
+ lv = if lv < 0 then 0 elseif lv > 63 then 63 else lv
+ local e = { 0, 0, 0 }
+ if lv > 0 then
+ local il = lv
+ if sharpness > 0 then
+ if sharpness > 4 then
+ il = rshift(il, 2)
+ else
+ il = rshift(il, 1)
+ end
+ if il > 9 - sharpness then
+ il = 9 - sharpness
+ end
+ end
+ if il < 1 then
+ il = 1
+ end
+ e[1] = 2 * lv + il
+ e[2] = il
+ e[3] = if lv >= 40 then 2 elseif lv >= 15 then 1 else 0
+ end
+ fstr[(s - 1) * 2 + i4 + 1] = e
+ end
+ end
+
+ -- the frame, macroblock aligned
+ local mbw, mbh = (width + 15) // 16, (height + 15) // 16
+ local ys, uvs = mbw * 16, mbw * 8
+ local Y = bcreate(ys * mbh * 16)
+ local U = bcreate(uvs * mbh * 8)
+ local V = bcreate(uvs * mbh * 8)
+ local topY, topU, topV = bcreate(ys), bcreate(uvs), bcreate(uvs)
+ local yuv = bcreate(YUV_SIZE)
+ 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)
+ local topNzDc = table.create(mbw, 0)
+ local mbI4 = table.create(mbw, false)
+ local mbModes = table.create(mbw * 16, 0)
+ local mbUv = table.create(mbw, 0)
+ local mbSeg = table.create(mbw, 0)
+ 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)
+ local fHev = table.create(mbw * mbh, 0)
+ local segProba = st.segProba
+
+ for mby = 0, mbh - 1 do
+ local tbr = parts[band(mby, lastPart) + 1]
+ -- intra modes of the row (first partition)
+ for k = 1, 4 do
+ intraL[k] = 0
+ end
+ for mbx = 0, mbw - 1 do
+ local seg = 0
+ if st.updateMap then
+ if getBit(br, segProba[1]) == 0 then
+ seg = getBit(br, segProba[2])
+ else
+ seg = getBit(br, segProba[3]) + 2
+ end
+ end
+ mbSeg[mbx + 1] = seg
+ mbSkip[mbx + 1] = if useSkip then getBit(br, skipP) else 0
+ local i4 = getBit(br, 145) == 0
+ mbI4[mbx + 1] = i4
+ local t0 = mbx * 4
+ if not i4 then
+ local ymode
+ if getBit(br, 156) == 1 then
+ ymode = if getBit(br, 128) == 1 then 1 else 3
+ else
+ ymode = if getBit(br, 163) == 1 then 2 else 0
+ end
+ mbModes[mbx * 16 + 1] = ymode
+ for k = 1, 4 do
+ intraT[t0 + k] = ymode
+ intraL[k] = ymode
+ end
+ else
+ for y = 0, 3 do
+ local ymode = intraL[y + 1]
+ for x = 0, 3 do
+ local pr = (intraT[t0 + x + 1] * 10 + ymode) * 9
+ if getBit(br, BMODES_PROBA[pr + 1]) == 0 then
+ ymode = 0
+ elseif getBit(br, BMODES_PROBA[pr + 2]) == 0 then
+ ymode = 1
+ elseif getBit(br, BMODES_PROBA[pr + 3]) == 0 then
+ ymode = 2
+ elseif getBit(br, BMODES_PROBA[pr + 4]) == 0 then
+ if getBit(br, BMODES_PROBA[pr + 5]) == 0 then
+ ymode = 3
+ elseif getBit(br, BMODES_PROBA[pr + 6]) == 0 then
+ ymode = 4
+ else
+ ymode = 5
+ end
+ elseif getBit(br, BMODES_PROBA[pr + 7]) == 0 then
+ ymode = 6
+ elseif getBit(br, BMODES_PROBA[pr + 8]) == 0 then
+ ymode = 7
+ elseif getBit(br, BMODES_PROBA[pr + 9]) == 0 then
+ ymode = 8
+ else
+ ymode = 9
+ end
+ intraT[t0 + x + 1] = ymode
+ mbModes[mbx * 16 + y * 4 + x + 1] = ymode
+ end
+ intraL[y + 1] = ymode
+ end
+ end
+ if getBit(br, 142) == 0 then
+ mbUv[mbx + 1] = 0
+ elseif getBit(br, 114) == 0 then
+ mbUv[mbx + 1] = 2
+ else
+ mbUv[mbx + 1] = if getBit(br, 183) == 1 then 1 else 3
+ end
+ end
+ if br.eof then
+ return nil, "truncated: first partition (intra modes)"
+ end
+
+ -- residuals (token partition)
+ local leftNz, leftNzDc = 0, 0
+ for mbx = 0, mbw - 1 do
+ local x1 = mbx + 1
+ local q = quants[mbSeg[x1] + 1]
+ local skip = mbSkip[x1]
+ local i4 = mbI4[x1]
+ if skip == 0 then
+ local co = mbx * 768
+ bfill(coeffs, co, 0, 768)
+ local first, acType
+ if not i4 then
+ bfill(dcb, 0, 0, 32)
+ local ctx = topNzDc[x1] + leftNzDc
+ local nz = getCoeffs(tbr, P, 1, ctx, q.y2dc, q.y2ac, 0, dcb, 0)
+ local f = if nz > 0 then 1 else 0
+ topNzDc[x1] = f
+ leftNzDc = f
+ if nz > 1 then
+ transformWHT(dcb, coeffs, co)
+ else
+ local dc0 = (readi16(dcb, 0) + 3) // 8
+ for i = 0, 15 do
+ writei16(coeffs, co + i * 32, dc0)
+ end
+ end
+ first, acType = 1, 0
+ else
+ first, acType = 0, 3
+ end
+ local tnz = band(topNz[x1], 0x0f)
+ local lnz = band(leftNz, 0x0f)
+ local nzY = 0
+ local dst = co
+ for _ = 0, 3 do
+ local l = band(lnz, 1)
+ local acc = 0
+ for _ = 0, 3 do
+ local ctx = l + band(tnz, 1)
+ local nz = getCoeffs(tbr, P, acType, ctx, q.y1dc, q.y1ac, first, coeffs, dst)
+ l = if nz > first then 1 else 0
+ tnz = bor(rshift(tnz, 1), l * 128)
+ acc = nzCode(acc, nz, if readi16(coeffs, dst) ~= 0 then 1 else 0)
+ dst += 32
+ end
+ tnz = rshift(tnz, 4)
+ lnz = bor(rshift(lnz, 1), l * 128)
+ nzY = nzY * 256 + acc
+ end
+ local outT = tnz
+ local outL = rshift(lnz, 4)
+ local nzUv = 0
+ for ch = 0, 2, 2 do
+ local acc = 0
+ tnz = band(rshift(topNz[x1], 4 + ch), 255)
+ lnz = band(rshift(leftNz, 4 + ch), 255)
+ for _ = 0, 1 do
+ local l = band(lnz, 1)
+ for _ = 0, 1 do
+ local ctx = l + band(tnz, 1)
+ local nz = getCoeffs(tbr, P, 2, ctx, q.uvdc, q.uvac, 0, coeffs, dst)
+ l = if nz > 0 then 1 else 0
+ tnz = bor(rshift(tnz, 1), l * 8)
+ acc = nzCode(acc, nz, if readi16(coeffs, dst) ~= 0 then 1 else 0)
+ dst += 32
+ end
+ tnz = rshift(tnz, 2)
+ lnz = bor(rshift(lnz, 1), l * 32)
+ end
+ nzUv = bor(nzUv, lshift(acc, 4 * ch))
+ outT = bor(outT, lshift(lshift(tnz, 4), ch))
+ outL = bor(outL, lshift(band(lnz, 0xf0), ch))
+ end
+ topNz[x1] = band(outT, 255)
+ leftNz = band(outL, 255)
+ mbNzY[x1] = nzY
+ mbNzUv[x1] = nzUv
+ skip = if nzY == 0 and nzUv == 0 then 1 else 0
+ else
+ topNz[x1] = 0
+ leftNz = 0
+ if not i4 then
+ topNzDc[x1] = 0
+ leftNzDc = 0
+ end
+ mbNzY[x1] = 0
+ mbNzUv[x1] = 0
+ end
+ if filterType > 0 then
+ local e = fstr[mbSeg[x1] * 2 + (if i4 then 1 else 0) + 1]
+ local fi = mby * mbw + x1
+ fLimit[fi] = e[1]
+ fIlevel[fi] = e[2]
+ fHev[fi] = e[3]
+ fInner[fi] = if i4 or skip == 0 then 1 else 0
+ end
+ if tbr.eof then
+ return nil, "truncated: token partition"
+ end
+ end
+
+ -- reconstruct the row (libwebp ReconstructRow)
+ for j = 0, 15 do
+ writeu8(yuv, Y_OFF + j * BPS - 1, 129)
+ end
+ for j = 0, 7 do
+ writeu8(yuv, U_OFF + j * BPS - 1, 129)
+ writeu8(yuv, V_OFF + j * BPS - 1, 129)
+ end
+ if mby > 0 then
+ writeu8(yuv, Y_OFF - 1 - BPS, 129)
+ writeu8(yuv, U_OFF - 1 - BPS, 129)
+ writeu8(yuv, V_OFF - 1 - BPS, 129)
+ else
+ bfill(yuv, Y_OFF - BPS - 1, 127, 16 + 4 + 1)
+ bfill(yuv, U_OFF - BPS - 1, 127, 8 + 1)
+ bfill(yuv, V_OFF - BPS - 1, 127, 8 + 1)
+ end
+ for mbx = 0, mbw - 1 do
+ local x1 = mbx + 1
+ if mbx > 0 then
+ for j = -1, 15 do
+ bcopy(yuv, Y_OFF + j * BPS - 4, yuv, Y_OFF + j * BPS + 12, 4)
+ end
+ for j = -1, 7 do
+ bcopy(yuv, U_OFF + j * BPS - 4, yuv, U_OFF + j * BPS + 4, 4)
+ bcopy(yuv, V_OFF + j * BPS - 4, yuv, V_OFF + j * BPS + 4, 4)
+ end
+ end
+ if mby > 0 then
+ bcopy(yuv, Y_OFF - BPS, topY, mbx * 16, 16)
+ bcopy(yuv, U_OFF - BPS, topU, mbx * 8, 8)
+ bcopy(yuv, V_OFF - BPS, topV, mbx * 8, 8)
+ end
+ local co = mbx * 768
+ local bits = mbNzY[x1]
+ if mbI4[x1] then
+ local tr = Y_OFF - BPS + 16
+ if mby > 0 then
+ if mbx >= mbw - 1 then
+ bfill(yuv, tr, readu8(topY, mbx * 16 + 15), 4)
+ else
+ bcopy(yuv, tr, topY, mbx * 16 + 16, 4)
+ end
+ end
+ bcopy(yuv, tr + 4 * BPS, yuv, tr, 4)
+ bcopy(yuv, tr + 8 * BPS, yuv, tr, 4)
+ bcopy(yuv, tr + 12 * BPS, yuv, tr, 4)
+ for n = 0, 15 do
+ local dst = Y_OFF + (n % 4) * 4 + (n // 4) * 4 * BPS
+ predict4(yuv, dst, mbModes[mbx * 16 + n + 1])
+ doTransform(band(rshift(bits, 30 - 2 * n), 3), coeffs, co + n * 32, yuv, dst)
+ end
+ else
+ predictBlock(yuv, Y_OFF, 16, checkMode(mbx, mby, mbModes[mbx * 16 + 1]))
+ if bits ~= 0 then
+ for n = 0, 15 do
+ local dst = Y_OFF + (n % 4) * 4 + (n // 4) * 4 * BPS
+ doTransform(band(rshift(bits, 30 - 2 * n), 3), coeffs, co + n * 32, yuv, dst)
+ end
+ end
+ end
+ local uvm = checkMode(mbx, mby, mbUv[x1])
+ predictBlock(yuv, U_OFF, 8, uvm)
+ predictBlock(yuv, V_OFF, 8, uvm)
+ local buv = mbNzUv[x1]
+ doUVTransform(buv, coeffs, co + 16 * 32, yuv, U_OFF)
+ doUVTransform(rshift(buv, 8), coeffs, co + 20 * 32, yuv, V_OFF)
+ if mby < mbh - 1 then
+ bcopy(topY, mbx * 16, yuv, Y_OFF + 15 * BPS, 16)
+ bcopy(topU, mbx * 8, yuv, U_OFF + 7 * BPS, 8)
+ bcopy(topV, mbx * 8, yuv, V_OFF + 7 * BPS, 8)
+ end
+ local yo = mby * 16 * ys + mbx * 16
+ for j = 0, 15 do
+ bcopy(Y, yo + j * ys, yuv, Y_OFF + j * BPS, 16)
+ end
+ local uo = mby * 8 * uvs + mbx * 8
+ for j = 0, 7 do
+ bcopy(U, uo + j * uvs, yuv, U_OFF + j * BPS, 8)
+ bcopy(V, uo + j * uvs, yuv, V_OFF + j * BPS, 8)
+ end
+ end
+ end
+
+ -- loop filter over the whole frame, macroblocks in raster order (libwebp DoFilter)
+ if filterType > 0 then
+ for mby = 0, mbh - 1 do
+ for mbx = 0, mbw - 1 do
+ local fi = mby * mbw + mbx + 1
+ local limit = fLimit[fi]
+ if limit ~= 0 then
+ local inner = fInner[fi] == 1
+ local yp = mby * 16 * ys + mbx * 16
+ if filterType == 1 then
+ if mbx > 0 then
+ simpleFilter(Y, yp, 1, ys, limit + 4)
+ end
+ if inner then
+ for k = 1, 3 do
+ simpleFilter(Y, yp + 4 * k, 1, ys, limit)
+ end
+ end
+ if mby > 0 then
+ simpleFilter(Y, yp, ys, 1, limit + 4)
+ end
+ if inner then
+ for k = 1, 3 do
+ simpleFilter(Y, yp + 4 * k * ys, ys, 1, limit)
+ end
+ end
+ else
+ local il, hev = fIlevel[fi], fHev[fi]
+ local up = mby * 8 * uvs + mbx * 8
+ if mbx > 0 then
+ filterLoop(Y, yp, 1, ys, 16, limit + 4, il, hev, true)
+ filterLoop(U, up, 1, uvs, 8, limit + 4, il, hev, true)
+ filterLoop(V, up, 1, uvs, 8, limit + 4, il, hev, true)
+ end
+ if inner then
+ for k = 1, 3 do
+ filterLoop(Y, yp + 4 * k, 1, ys, 16, limit, il, hev, false)
+ end
+ filterLoop(U, up + 4, 1, uvs, 8, limit, il, hev, false)
+ filterLoop(V, up + 4, 1, uvs, 8, limit, il, hev, false)
+ end
+ if mby > 0 then
+ filterLoop(Y, yp, ys, 1, 16, limit + 4, il, hev, true)
+ filterLoop(U, up, uvs, 1, 8, limit + 4, il, hev, true)
+ filterLoop(V, up, uvs, 1, 8, limit + 4, il, hev, true)
+ end
+ if inner then
+ for k = 1, 3 do
+ filterLoop(Y, yp + 4 * k * ys, ys, 1, 16, limit, il, hev, false)
+ end
+ filterLoop(U, up + 4 * uvs, uvs, 1, 8, limit, il, hev, false)
+ filterLoop(V, up + 4 * uvs, uvs, 1, 8, limit, il, hev, false)
+ end
+ end
+ end
+ end
+ end
+ end
+
+ -- crop to the frame size
+ local cw, chh = (width + 1) // 2, (height + 1) // 2
+ local oy = bcreate(width * height)
+ for j = 0, height - 1 do
+ bcopy(oy, j * width, Y, j * ys, width)
+ end
+ local ou, ov = bcreate(cw * chh), bcreate(cw * chh)
+ for j = 0, chh - 1 do
+ bcopy(ou, j * cw, U, j * uvs, cw)
+ bcopy(ov, j * cw, V, j * uvs, cw)
+ end
+ return { width = width, height = height, y = oy, u = ou, v = ov, header = hdr }, nil
+end
+
+return Decode
diff --git a/src/Formats/codecs/Vp8/Tables.luau b/src/Formats/codecs/Vp8/Tables.luau
new file mode 100644
index 0000000..e8a9320
--- /dev/null
+++ b/src/Formats/codecs/Vp8/Tables.luau
@@ -0,0 +1,180 @@
+--!strict
+-- codecs/Vp8/Tables: the constant VP8 tables of RFC 6386 (sections 13.5, 13.4, 11.5, 14.1), copied from libwebp 1.6
+-- src/dec/tree_dec.c and src/dec/quant_dec.c (BSD-3-Clause, licenses/libwebp-LICENSE.txt). Flat 1-based arrays.
+local Tables = {}
+
+-- default token probabilities [type 4][band 8][ctx 3][proba 11]: index ((t * 8 + b) * 3 + c) * 11 + p + 1
+Tables.COEFF_PROBA0 = {
+ 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
+ 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 253, 136, 254, 255, 228, 219, 128, 128, 128, 128, 128,
+ 189, 129, 242, 255, 227, 213, 255, 219, 128, 128, 128, 106, 126, 227, 252, 214, 209, 255, 255, 128, 128, 128,
+ 1, 98, 248, 255, 236, 226, 255, 255, 128, 128, 128, 181, 133, 238, 254, 221, 234, 255, 154, 128, 128, 128,
+ 78, 134, 202, 247, 198, 180, 255, 219, 128, 128, 128, 1, 185, 249, 255, 243, 255, 128, 128, 128, 128, 128,
+ 184, 150, 247, 255, 236, 224, 128, 128, 128, 128, 128, 77, 110, 216, 255, 236, 230, 128, 128, 128, 128, 128,
+ 1, 101, 251, 255, 241, 255, 128, 128, 128, 128, 128, 170, 139, 241, 252, 236, 209, 255, 255, 128, 128, 128,
+ 37, 116, 196, 243, 228, 255, 255, 255, 128, 128, 128, 1, 204, 254, 255, 245, 255, 128, 128, 128, 128, 128,
+ 207, 160, 250, 255, 238, 128, 128, 128, 128, 128, 128, 102, 103, 231, 255, 211, 171, 128, 128, 128, 128, 128,
+ 1, 152, 252, 255, 240, 255, 128, 128, 128, 128, 128, 177, 135, 243, 255, 234, 225, 128, 128, 128, 128, 128,
+ 80, 129, 211, 255, 194, 224, 128, 128, 128, 128, 128, 1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128,
+ 246, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128, 255, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
+ 198, 35, 237, 223, 193, 187, 162, 160, 145, 155, 62, 131, 45, 198, 221, 172, 176, 220, 157, 252, 221, 1,
+ 68, 47, 146, 208, 149, 167, 221, 162, 255, 223, 128, 1, 149, 241, 255, 221, 224, 255, 255, 128, 128, 128,
+ 184, 141, 234, 253, 222, 220, 255, 199, 128, 128, 128, 81, 99, 181, 242, 176, 190, 249, 202, 255, 255, 128,
+ 1, 129, 232, 253, 214, 197, 242, 196, 255, 255, 128, 99, 121, 210, 250, 201, 198, 255, 202, 128, 128, 128,
+ 23, 91, 163, 242, 170, 187, 247, 210, 255, 255, 128, 1, 200, 246, 255, 234, 255, 128, 128, 128, 128, 128,
+ 109, 178, 241, 255, 231, 245, 255, 255, 128, 128, 128, 44, 130, 201, 253, 205, 192, 255, 255, 128, 128, 128,
+ 1, 132, 239, 251, 219, 209, 255, 165, 128, 128, 128, 94, 136, 225, 251, 218, 190, 255, 255, 128, 128, 128,
+ 22, 100, 174, 245, 186, 161, 255, 199, 128, 128, 128, 1, 182, 249, 255, 232, 235, 128, 128, 128, 128, 128,
+ 124, 143, 241, 255, 227, 234, 128, 128, 128, 128, 128, 35, 77, 181, 251, 193, 211, 255, 205, 128, 128, 128,
+ 1, 157, 247, 255, 236, 231, 255, 255, 128, 128, 128, 121, 141, 235, 255, 225, 227, 255, 255, 128, 128, 128,
+ 45, 99, 188, 251, 195, 217, 255, 224, 128, 128, 128, 1, 1, 251, 255, 213, 255, 128, 128, 128, 128, 128,
+ 203, 1, 248, 255, 255, 128, 128, 128, 128, 128, 128, 137, 1, 177, 255, 224, 255, 128, 128, 128, 128, 128,
+ 253, 9, 248, 251, 207, 208, 255, 192, 128, 128, 128, 175, 13, 224, 243, 193, 185, 249, 198, 255, 255, 128,
+ 73, 17, 171, 221, 161, 179, 236, 167, 255, 234, 128, 1, 95, 247, 253, 212, 183, 255, 255, 128, 128, 128,
+ 239, 90, 244, 250, 211, 209, 255, 255, 128, 128, 128, 155, 77, 195, 248, 188, 195, 255, 255, 128, 128, 128,
+ 1, 24, 239, 251, 218, 219, 255, 205, 128, 128, 128, 201, 51, 219, 255, 196, 186, 128, 128, 128, 128, 128,
+ 69, 46, 190, 239, 201, 218, 255, 228, 128, 128, 128, 1, 191, 251, 255, 255, 128, 128, 128, 128, 128, 128,
+ 223, 165, 249, 255, 213, 255, 128, 128, 128, 128, 128, 141, 124, 248, 255, 255, 128, 128, 128, 128, 128, 128,
+ 1, 16, 248, 255, 255, 128, 128, 128, 128, 128, 128, 190, 36, 230, 255, 236, 255, 128, 128, 128, 128, 128,
+ 149, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128, 1, 226, 255, 128, 128, 128, 128, 128, 128, 128, 128,
+ 247, 192, 255, 128, 128, 128, 128, 128, 128, 128, 128, 240, 128, 255, 128, 128, 128, 128, 128, 128, 128, 128,
+ 1, 134, 252, 255, 255, 128, 128, 128, 128, 128, 128, 213, 62, 250, 255, 255, 128, 128, 128, 128, 128, 128,
+ 55, 93, 255, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
+ 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
+ 202, 24, 213, 235, 186, 191, 220, 160, 240, 175, 255, 126, 38, 182, 232, 169, 184, 228, 174, 255, 187, 128,
+ 61, 46, 138, 219, 151, 178, 240, 170, 255, 216, 128, 1, 112, 230, 250, 199, 191, 247, 159, 255, 255, 128,
+ 166, 109, 228, 252, 211, 215, 255, 174, 128, 128, 128, 39, 77, 162, 232, 172, 180, 245, 178, 255, 255, 128,
+ 1, 52, 220, 246, 198, 199, 249, 220, 255, 255, 128, 124, 74, 191, 243, 183, 193, 250, 221, 255, 255, 128,
+ 24, 71, 130, 219, 154, 170, 243, 182, 255, 255, 128, 1, 182, 225, 249, 219, 240, 255, 224, 128, 128, 128,
+ 149, 150, 226, 252, 216, 205, 255, 171, 128, 128, 128, 28, 108, 170, 242, 183, 194, 254, 223, 255, 255, 128,
+ 1, 81, 230, 252, 204, 203, 255, 192, 128, 128, 128, 123, 102, 209, 247, 188, 196, 255, 233, 128, 128, 128,
+ 20, 95, 153, 243, 164, 173, 255, 203, 128, 128, 128, 1, 222, 248, 255, 216, 213, 128, 128, 128, 128, 128,
+ 168, 175, 246, 252, 235, 205, 255, 255, 128, 128, 128, 47, 116, 215, 255, 211, 212, 255, 255, 128, 128, 128,
+ 1, 121, 236, 253, 212, 214, 255, 255, 128, 128, 128, 141, 84, 213, 252, 201, 202, 255, 219, 128, 128, 128,
+ 42, 80, 160, 240, 162, 185, 255, 205, 128, 128, 128, 1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128,
+ 244, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128, 238, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128,
+}
+-- token probability update probabilities, same layout
+Tables.COEFF_UPDATE_PROBA = {
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 176, 246, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 223, 241, 252, 255, 255, 255, 255, 255, 255, 255, 255, 249, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 244, 252, 255, 255, 255, 255, 255, 255, 255, 255, 234, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255,
+ 253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 246, 254, 255, 255, 255, 255, 255, 255, 255, 255,
+ 239, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255, 251, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255,
+ 251, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 254, 253, 255, 254, 255, 255, 255, 255, 255, 255, 250, 255, 254, 255, 254, 255, 255, 255, 255, 255, 255,
+ 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 217, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 225, 252, 241, 253, 255, 255, 254, 255, 255, 255, 255,
+ 234, 250, 241, 250, 253, 255, 253, 254, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 223, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 238, 253, 254, 254, 255, 255, 255, 255, 255, 255, 255,
+ 255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255, 249, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 253, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 247, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255, 252, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255,
+ 253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255, 250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 186, 251, 250, 255, 255, 255, 255, 255, 255, 255, 255, 234, 251, 244, 254, 255, 255, 255, 255, 255, 255, 255,
+ 251, 251, 243, 253, 254, 255, 254, 255, 255, 255, 255, 255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255,
+ 236, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255, 251, 253, 253, 254, 254, 255, 255, 255, 255, 255, 255,
+ 255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 248, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 250, 254, 252, 254, 255, 255, 255, 255, 255, 255, 255,
+ 248, 254, 249, 253, 255, 255, 255, 255, 255, 255, 255, 255, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255,
+ 246, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255, 252, 254, 251, 254, 254, 255, 255, 255, 255, 255, 255,
+ 255, 254, 252, 255, 255, 255, 255, 255, 255, 255, 255, 248, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255,
+ 253, 255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255,
+ 245, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255, 253, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 251, 253, 255, 255, 255, 255, 255, 255, 255, 255, 252, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 252, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 249, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 253, 255, 255, 255, 255, 255, 255, 255, 255, 250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+}
+-- 4x4 intra mode probabilities [top 10][left 10][9]: index (top * 10 + left) * 9 + i + 1
+Tables.BMODES_PROBA = {
+ 231, 120, 48, 89, 115, 113, 120, 152, 112, 152, 179, 64, 126, 170, 118, 46, 70, 95, 175, 69, 143, 80,
+ 85, 82, 72, 155, 103, 56, 58, 10, 171, 218, 189, 17, 13, 152, 114, 26, 17, 163, 44, 195, 21, 10,
+ 173, 121, 24, 80, 195, 26, 62, 44, 64, 85, 144, 71, 10, 38, 171, 213, 144, 34, 26, 170, 46, 55,
+ 19, 136, 160, 33, 206, 71, 63, 20, 8, 114, 114, 208, 12, 9, 226, 81, 40, 11, 96, 182, 84, 29,
+ 16, 36, 134, 183, 89, 137, 98, 101, 106, 165, 148, 72, 187, 100, 130, 157, 111, 32, 75, 80, 66, 102,
+ 167, 99, 74, 62, 40, 234, 128, 41, 53, 9, 178, 241, 141, 26, 8, 107, 74, 43, 26, 146, 73, 166,
+ 49, 23, 157, 65, 38, 105, 160, 51, 52, 31, 115, 128, 104, 79, 12, 27, 217, 255, 87, 17, 7, 87,
+ 68, 71, 44, 114, 51, 15, 186, 23, 47, 41, 14, 110, 182, 183, 21, 17, 194, 66, 45, 25, 102, 197,
+ 189, 23, 18, 22, 88, 88, 147, 150, 42, 46, 45, 196, 205, 43, 97, 183, 117, 85, 38, 35, 179, 61,
+ 39, 53, 200, 87, 26, 21, 43, 232, 171, 56, 34, 51, 104, 114, 102, 29, 93, 77, 39, 28, 85, 171,
+ 58, 165, 90, 98, 64, 34, 22, 116, 206, 23, 34, 43, 166, 73, 107, 54, 32, 26, 51, 1, 81, 43,
+ 31, 68, 25, 106, 22, 64, 171, 36, 225, 114, 34, 19, 21, 102, 132, 188, 16, 76, 124, 62, 18, 78,
+ 95, 85, 57, 50, 48, 51, 193, 101, 35, 159, 215, 111, 89, 46, 111, 60, 148, 31, 172, 219, 228, 21,
+ 18, 111, 112, 113, 77, 85, 179, 255, 38, 120, 114, 40, 42, 1, 196, 245, 209, 10, 25, 109, 88, 43,
+ 29, 140, 166, 213, 37, 43, 154, 61, 63, 30, 155, 67, 45, 68, 1, 209, 100, 80, 8, 43, 154, 1,
+ 51, 26, 71, 142, 78, 78, 16, 255, 128, 34, 197, 171, 41, 40, 5, 102, 211, 183, 4, 1, 221, 51,
+ 50, 17, 168, 209, 192, 23, 25, 82, 138, 31, 36, 171, 27, 166, 38, 44, 229, 67, 87, 58, 169, 82,
+ 115, 26, 59, 179, 63, 59, 90, 180, 59, 166, 93, 73, 154, 40, 40, 21, 116, 143, 209, 34, 39, 175,
+ 47, 15, 16, 183, 34, 223, 49, 45, 183, 46, 17, 33, 183, 6, 98, 15, 32, 183, 57, 46, 22, 24,
+ 128, 1, 54, 17, 37, 65, 32, 73, 115, 28, 128, 23, 128, 205, 40, 3, 9, 115, 51, 192, 18, 6,
+ 223, 87, 37, 9, 115, 59, 77, 64, 21, 47, 104, 55, 44, 218, 9, 54, 53, 130, 226, 64, 90, 70,
+ 205, 40, 41, 23, 26, 57, 54, 57, 112, 184, 5, 41, 38, 166, 213, 30, 34, 26, 133, 152, 116, 10,
+ 32, 134, 39, 19, 53, 221, 26, 114, 32, 73, 255, 31, 9, 65, 234, 2, 15, 1, 118, 73, 75, 32,
+ 12, 51, 192, 255, 160, 43, 51, 88, 31, 35, 67, 102, 85, 55, 186, 85, 56, 21, 23, 111, 59, 205,
+ 45, 37, 192, 55, 38, 70, 124, 73, 102, 1, 34, 98, 125, 98, 42, 88, 104, 85, 117, 175, 82, 95,
+ 84, 53, 89, 128, 100, 113, 101, 45, 75, 79, 123, 47, 51, 128, 81, 171, 1, 57, 17, 5, 71, 102,
+ 57, 53, 41, 49, 38, 33, 13, 121, 57, 73, 26, 1, 85, 41, 10, 67, 138, 77, 110, 90, 47, 114,
+ 115, 21, 2, 10, 102, 255, 166, 23, 6, 101, 29, 16, 10, 85, 128, 101, 196, 26, 57, 18, 10, 102,
+ 102, 213, 34, 20, 43, 117, 20, 15, 36, 163, 128, 68, 1, 26, 102, 61, 71, 37, 34, 53, 31, 243,
+ 192, 69, 60, 71, 38, 73, 119, 28, 222, 37, 68, 45, 128, 34, 1, 47, 11, 245, 171, 62, 17, 19,
+ 70, 146, 85, 55, 62, 70, 37, 43, 37, 154, 100, 163, 85, 160, 1, 63, 9, 92, 136, 28, 64, 32,
+ 201, 85, 75, 15, 9, 9, 64, 255, 184, 119, 16, 86, 6, 28, 5, 64, 255, 25, 248, 1, 56, 8,
+ 17, 132, 137, 255, 55, 116, 128, 58, 15, 20, 82, 135, 57, 26, 121, 40, 164, 50, 31, 137, 154, 133,
+ 25, 35, 218, 51, 103, 44, 131, 131, 123, 31, 6, 158, 86, 40, 64, 135, 148, 224, 45, 183, 128, 22,
+ 26, 17, 131, 240, 154, 14, 1, 209, 45, 16, 21, 91, 64, 222, 7, 1, 197, 56, 21, 39, 155, 60,
+ 138, 23, 102, 213, 83, 12, 13, 54, 192, 255, 68, 47, 28, 85, 26, 85, 85, 128, 128, 32, 146, 171,
+ 18, 11, 7, 63, 144, 171, 4, 4, 246, 35, 27, 10, 146, 174, 171, 12, 26, 128, 190, 80, 35, 99,
+ 180, 80, 126, 54, 45, 85, 126, 47, 87, 176, 51, 41, 20, 32, 101, 75, 128, 139, 118, 146, 116, 128,
+ 85, 56, 41, 15, 176, 236, 85, 37, 9, 62, 71, 30, 17, 119, 118, 255, 17, 18, 138, 101, 38, 60,
+ 138, 55, 70, 43, 26, 142, 146, 36, 19, 30, 171, 255, 97, 27, 20, 138, 45, 61, 62, 219, 1, 81,
+ 188, 64, 32, 41, 20, 117, 151, 142, 20, 21, 163, 112, 19, 12, 61, 195, 128, 48, 4, 24,
+}
+-- DC dequantization factors, index q + 1 (q 0..127)
+Tables.DC_TABLE = {
+ 4, 5, 6, 7, 8, 9, 10, 10, 11, 12, 13, 14, 15, 16, 17, 17, 18, 19, 20, 20, 21, 21,
+ 22, 22, 23, 23, 24, 25, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 37, 38, 39,
+ 40, 41, 42, 43, 44, 45, 46, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60,
+ 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 76, 77, 78, 79, 80, 81,
+ 82, 83, 84, 85, 86, 87, 88, 89, 91, 93, 95, 96, 98, 100, 101, 102, 104, 106, 108, 110, 112, 114,
+ 116, 118, 122, 124, 126, 128, 130, 132, 134, 136, 138, 140, 143, 145, 148, 151, 154, 157,
+}
+-- AC dequantization factors, index q + 1
+Tables.AC_TABLE = {
+ 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, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
+ 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80,
+ 82, 84, 86, 88, 90, 92, 94, 96, 98, 100, 102, 104, 106, 108, 110, 112, 114, 116, 119, 122, 125, 128,
+ 131, 134, 137, 140, 143, 146, 149, 152, 155, 158, 161, 164, 167, 170, 173, 177, 181, 185, 189, 193, 197, 201,
+ 205, 209, 213, 217, 221, 225, 229, 234, 239, 245, 249, 254, 259, 264, 269, 274, 279, 284,
+}
+-- coefficient band of each position (with a sentinel for position 16)
+Tables.BANDS = { 0, 1, 2, 3, 6, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 0 }
+-- zigzag scan: coefficient n goes to position ZIGZAG[n + 1]
+Tables.ZIGZAG = { 0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15 }
+-- extra bits probabilities for the DCT_CAT3..6 tokens
+Tables.CAT3 = { 173, 148, 140 }
+Tables.CAT4 = { 176, 155, 140, 135 }
+Tables.CAT5 = { 180, 157, 141, 134, 130 }
+Tables.CAT6 = { 254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129 }
+
+return Tables
diff --git a/src/Formats/codecs/Vp8/Yuv.luau b/src/Formats/codecs/Vp8/Yuv.luau
new file mode 100644
index 0000000..5668738
--- /dev/null
+++ b/src/Formats/codecs/Vp8/Yuv.luau
@@ -0,0 +1,123 @@
+--!strict
+--!native
+--!optimize 2
+-- codecs/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
+-- (BSD-3-Clause, licenses/libwebp-LICENSE.txt).
+local rshift = bit32.rshift
+local readu8, writeu8, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu32
+local bcreate = buffer.create
+
+local Yuv = {}
+
+local function clip(v: number): number
+ -- VP8Clip8: v in 14-bit fixed point
+ if v >= 0 and v < 16384 then
+ return rshift(v, 6)
+ end
+ 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)
+ local g = clip(yy - mulHi(u, 6419) - mulHi(v, 13320) + 8708)
+ local b = clip(yy + mulHi(u, 33050) - 17685)
+ return r + g * 256 + b * 65536 + 0xff000000
+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.
+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)
+ local lu, lv = readu8(U, cu), readu8(V, cu)
+ do
+ local u0 = rshift(3 * tlu + lu + 2, 2)
+ local v0 = rshift(3 * tlv + lv + 2, 2)
+ writeu32(out, dt, rgba(readu8(Y, ty), u0, v0))
+ end
+ if by >= 0 then
+ local u0 = rshift(3 * lu + tlu + 2, 2)
+ local v0 = rshift(3 * lv + tlv + 2, 2)
+ writeu32(out, db, rgba(readu8(Y, by), u0, v0))
+ end
+ for x = 1, last do
+ local tu1, tv1 = readu8(U, tu + x), readu8(V, tu + x)
+ local u1, v1 = readu8(U, cu + x), readu8(V, cu + x)
+ local avgU = tlu + tu1 + lu + u1 + 8
+ local avgV = tlv + tv1 + lv + v1 + 8
+ local d12u = rshift(avgU + 2 * (tu1 + lu), 3)
+ local d03u = rshift(avgU + 2 * (tlu + u1), 3)
+ local d12v = rshift(avgV + 2 * (tv1 + lv), 3)
+ local d03v = rshift(avgV + 2 * (tlv + v1), 3)
+ local px = 2 * x
+ writeu32(out, dt + (px - 1) * 4, rgba(readu8(Y, ty + px - 1), rshift(d12u + tlu, 1), rshift(d12v + tlv, 1)))
+ writeu32(out, dt + px * 4, rgba(readu8(Y, ty + px), rshift(d03u + tu1, 1), rshift(d03v + tv1, 1)))
+ if by >= 0 then
+ writeu32(out, db + (px - 1) * 4, rgba(readu8(Y, by + px - 1), rshift(d03u + lu, 1), rshift(d03v + lv, 1)))
+ writeu32(out, db + px * 4, rgba(readu8(Y, by + px), rshift(d12u + u1, 1), rshift(d12v + v1, 1)))
+ end
+ tlu, tlv, lu, lv = tu1, tv1, u1, v1
+ end
+ if len % 2 == 0 then
+ local u0 = rshift(3 * tlu + lu + 2, 2)
+ local v0 = rshift(3 * tlv + lv + 2, 2)
+ writeu32(out, dt + (len - 1) * 4, rgba(readu8(Y, ty + len - 1), u0, v0))
+ if by >= 0 then
+ u0 = rshift(3 * lu + tlu + 2, 2)
+ v0 = rshift(3 * lv + tlv + 2, 2)
+ writeu32(out, db + (len - 1) * 4, rgba(readu8(Y, by + len - 1), u0, v0))
+ end
+ 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
+ local stride = w * 4
+ if fancy then
+ -- libwebp EmitFancyRGB over the whole picture: row 0 alone (chroma mirrored), then pairs of rows between two
+ -- chroma rows, then the last row of an even height alone
+ upsamplePair(Y, U, V, 0, -1, 0, 0, o, 0, -1, w)
+ local y = 1
+ local cu = 0
+ while y + 1 < h do
+ upsamplePair(Y, U, V, y * w, (y + 1) * w, cu, cu + cw, o, y * stride, (y + 1) * stride, w)
+ cu += cw
+ y += 2
+ end
+ if h % 2 == 0 and h > 1 then
+ upsamplePair(Y, U, V, (h - 1) * w, -1, cu, cu, o, (h - 1) * stride, -1, w)
+ end
+ else
+ for y = 0, h - 1 do
+ local cu = (y // 2) * cw
+ local yo = y * w
+ local oo = y * stride
+ for x = 0, w - 1 do
+ local c = cu + x // 2
+ writeu32(o, oo + x * 4, rgba(readu8(Y, yo + x), readu8(U, c), readu8(V, c)))
+ end
+ end
+ end
+ 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))
+ end
+end
+
+return Yuv
diff --git a/src/Formats/codecs/Vp8/init.luau b/src/Formats/codecs/Vp8/init.luau
new file mode 100644
index 0000000..05f56f1
--- /dev/null
+++ b/src/Formats/codecs/Vp8/init.luau
@@ -0,0 +1,142 @@
+--!strict
+-- codecs/Vp8: the VP8 video codec (RFC 6386), decode only. A codec (layer 1): image/webp uses it for lossy frames, the
+-- WebM / Matroska and IVF video tracks can use it too. A port of libwebp 1.6 (BSD-3-Clause,
+-- licenses/libwebp-LICENSE.txt), bit-exact with libwebp: the yuv420p planes equal `dwebp -yuv`, and toRgba equals
+-- `dwebp -pam` (fancy upsampling) or `dwebp -nofancy -pam`.
+-- Supports: key frames (intra 16x16 / 4x4 / chroma prediction, segments, both loop filters, token partitions,
+-- probability updates, skip). Not supported yet: inter frames (decodeFrame returns UNSUPPORTED; the decoder object
+-- keeps the cross-frame state so they can be added), the horizontal / vertical scale bits (ignored, as libwebp does).
+--
+-- local Vp8 = require("@formats/codecs/Vp8")
+-- local frame, err = Vp8.decodeFrame(buf, off, len) -- a yuv420p Types.Image (+ frame.meta.source.vp8 header)
+-- local rgba = Vp8.toRgba(frame) -- rgba8 Image (libwebp's fancy upsampling)
+-- local dec = Vp8.newDecoder(); dec:decodeFrame(...) -- a stream of frames (WebM)
+--
+-- Never throws: bad data returns nil, Err (core/Err codes TRUNCATED / CORRUPT / UNSUPPORTED / LIMIT / ARG).
+local Err = require("@formats/core/Err")
+local Types = require("@formats/Types")
+local Decode = require("@formats/codecs/Vp8/Decode")
+local Yuv = require("@formats/codecs/Vp8/Yuv")
+
+local Vp8 = {}
+
+local DEFAULT_MAX_PIXELS = 2 ^ 28
+
+export type Options = {
+ maxPixels: number?, -- default 2^28
+}
+
+local function fail(msg: string?, offset: number?): Err.Err
+ local m = msg or "bad data"
+ if string.sub(m, 1, 11) == "truncated: " then
+ return Err.new(Err.TRUNCATED, string.sub(m, 12), offset)
+ elseif string.sub(m, 1, 7) == "limit: " then
+ return Err.new(Err.LIMIT, string.sub(m, 8), offset)
+ elseif string.sub(m, 1, 13) == "unsupported: " then
+ return Err.new(Err.UNSUPPORTED, string.sub(m, 14), offset)
+ end
+ return Err.new(Err.CORRUPT, m, offset)
+end
+
+local function range(buf: buffer, off: number?, len: number?): (number, number)
+ local n = buffer.len(buf)
+ local o = math.clamp(off or 0, 0, n)
+ 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")
+ end
+ local o, l = range(buf, off, len)
+ local h, err = Decode.header(buf, o, l)
+ if not h then
+ return nil, fail(err, o)
+ end
+ return h, nil
+end
+
+local DecoderMeta = {}
+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 | nil, Err
+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")
+ end
+ local o, l = range(buf, off, len)
+ local f, err = Decode.decodeFrame(self.state, buf, o, l, opts and opts.maxPixels or DEFAULT_MAX_PIXELS)
+ if not f then
+ return nil, fail(err, o)
+ end
+ local img = Types.Image.new(f.width, f.height, "yuv420p")
+ local ny = f.width * f.height
+ local nc = buffer.len(f.u)
+ buffer.copy(img.pixels, 0, f.y, 0, ny)
+ buffer.copy(img.pixels, ny, f.u, 0, nc)
+ buffer.copy(img.pixels, ny + nc, f.v, 0, nc)
+ img.meta.source = { format = "vp8", keyFrame = f.header.keyFrame, profile = f.header.profile }
+ return img, nil
+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")
+ end
+ local o, l = range(buf, off, len)
+ local f, err = Decode.decodeFrame(Decode.new(), buf, o, l, opts and opts.maxPixels or DEFAULT_MAX_PIXELS)
+ if not f then
+ return nil, fail(err, o)
+ end
+ return f.y, f.u, f.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")
+ end
+ local w, h = img.width, img.height
+ local _, uo, vo, cw, ch = Vp8.planes(img)
+ local y = buffer.create(w * h)
+ local u = buffer.create(cw * ch)
+ local v = buffer.create(cw * ch)
+ buffer.copy(y, 0, img.pixels, 0, w * h)
+ buffer.copy(u, 0, img.pixels, uo, cw * ch)
+ buffer.copy(v, 0, img.pixels, vo, cw * ch)
+ local out = Types.Image.new(w, h, "rgba8")
+ Yuv.toRgba(y, u, v, w, h, fancy ~= false, out.pixels)
+ out.meta.source = img.meta.source
+ 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
+
+Vp8.setAlpha = Yuv.setAlpha
+
+return Vp8
diff --git a/src/Formats/codecs/Vp8L/Decode.luau b/src/Formats/codecs/Vp8L/Decode.luau
new file mode 100644
index 0000000..6f88783
--- /dev/null
+++ b/src/Formats/codecs/Vp8L/Decode.luau
@@ -0,0 +1,873 @@
+--!strict
+--!native
+--!optimize 2
+-- codecs/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,
+-- 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.
+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
+
+local Decode = {}
+
+local ROOT_BITS = 8
+local MAX_LEN = 15
+local NUM_LITERAL = 256
+local NUM_LENGTH = 24
+local NUM_DISTANCE = 40
+local MAX_CACHE_BITS = 11
+local ARGB_BLACK = 0xff000000
+
+local CODE_LENGTH_ORDER = { 17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }
+local CODE_TO_PLANE = {
+ 0x18, 0x07, 0x17, 0x19, 0x28, 0x06, 0x27, 0x29, 0x16, 0x1a, 0x26, 0x2a, 0x38, 0x05, 0x37, 0x39, 0x15, 0x1b, 0x36,
+ 0x3a, 0x25, 0x2b, 0x48, 0x04, 0x47, 0x49, 0x14, 0x1c, 0x35, 0x3b, 0x46, 0x4a, 0x24, 0x2c, 0x58, 0x45, 0x4b, 0x34,
+ 0x3c, 0x03, 0x57, 0x59, 0x13, 0x1d, 0x56, 0x5a, 0x23, 0x2d, 0x44, 0x4c, 0x55, 0x5b, 0x33, 0x3d, 0x68, 0x02, 0x67,
+ 0x69, 0x12, 0x1e, 0x66, 0x6a, 0x22, 0x2e, 0x54, 0x5c, 0x43, 0x4d, 0x65, 0x6b, 0x32, 0x3e, 0x78, 0x01, 0x77, 0x79,
+ 0x53, 0x5d, 0x11, 0x1f, 0x64, 0x6c, 0x42, 0x4e, 0x76, 0x7a, 0x21, 0x2f, 0x75, 0x7b, 0x31, 0x3f, 0x63, 0x6d, 0x52,
+ 0x5e, 0x00, 0x74, 0x7c, 0x41, 0x4f, 0x10, 0x20, 0x62, 0x6e, 0x30, 0x73, 0x7d, 0x51, 0x5f, 0x40, 0x72, 0x7e, 0x61,
+ 0x6f, 0x50, 0x71, 0x7f, 0x60, 0x70,
+}
+-- 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).
+export type State = {
+ buf: buffer,
+ pos: number,
+ limit: number,
+ bitbuf: number,
+ bitcnt: number,
+ over: number,
+ -- prefix code tables (u32 entries value * 32 + bits), shared by every group of every level
+ tab: buffer,
+ tabUsed: number,
+ maxPixels: number,
+}
+
+local function fill(d: State)
+ local bitbuf, bitcnt = d.bitbuf, d.bitcnt
+ while bitcnt <= 24 do
+ local p = d.pos
+ local b = 0
+ if p < d.limit then
+ b = readu8(d.buf, p)
+ d.pos = p + 1
+ else
+ d.over += 1
+ end
+ bitbuf += lshift(b, bitcnt)
+ bitcnt += 8
+ end
+ 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)
+ end
+ local v = band(d.bitbuf, lshift(1, n) - 1)
+ d.bitbuf = rshift(d.bitbuf, n)
+ d.bitcnt -= n
+ return v
+end
+
+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)
+
+local function ensure(d: State, n: number)
+ local cap = blen(d.tab) // 4
+ if d.tabUsed + n > cap then
+ local nb = bcreate(math.max(cap * 2, d.tabUsed + n) * 4)
+ bcopy(nb, 0, d.tab, 0, d.tabUsed * 4)
+ d.tab = nb
+ end
+end
+
+local function replicate(tab: buffer, at: number, step: number, size: number, entry: number)
+ local e = size
+ repeat
+ e -= step
+ writeu32(tab, (at + e) * 4, entry)
+ until e <= 0
+end
+
+local function nextKey(key: number, len: number): number
+ local step = lshift(1, len - 1)
+ while band(key, step) ~= 0 do
+ step = rshift(step, 1)
+ end
+ 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)
+local sorted = table.create(2400, 0)
+local function build(d: State, lens: { number }, n: number): number
+ for l = 0, MAX_LEN do
+ count[l + 1] = 0
+ end
+ for s = 0, n - 1 do
+ local l = lens[s + 1]
+ if l > MAX_LEN then
+ return -1
+ end
+ count[l + 1] += 1
+ end
+ if count[1] == n then
+ return -1
+ end
+ offset[2] = 0
+ for len = 1, MAX_LEN - 1 do
+ if count[len + 1] > lshift(1, len) then
+ return -1
+ end
+ offset[len + 2] = offset[len + 1] + count[len + 1]
+ end
+ for s = 0, n - 1 do
+ local l = lens[s + 1]
+ if l > 0 then
+ sorted[offset[l + 1] + 1] = s
+ offset[l + 1] += 1
+ end
+ end
+ local long = 0
+ for len = ROOT_BITS + 1, MAX_LEN do
+ long += count[len + 1]
+ end
+ ensure(d, lshift(1, ROOT_BITS) + long * lshift(1, MAX_LEN - ROOT_BITS))
+ local tab = d.tab
+ local root = d.tabUsed
+ local totalSize = lshift(1, ROOT_BITS)
+ if offset[MAX_LEN + 1] == 1 then
+ replicate(tab, root, 1, totalSize, sorted[1] * 32)
+ d.tabUsed = root + totalSize
+ return root
+ end
+ local key = 0
+ local numNodes, numOpen = 1, 1
+ local tableBits = ROOT_BITS
+ local tableSize = lshift(1, tableBits)
+ local tableAt = root
+ local low = -1
+ local mask = totalSize - 1
+ local symbol = 1
+ local step = 2
+ for len = 1, ROOT_BITS do
+ numOpen *= 2
+ numNodes += numOpen
+ numOpen -= count[len + 1]
+ if numOpen < 0 then
+ return -1
+ end
+ while count[len + 1] > 0 do
+ replicate(tab, root + key, step, tableSize, sorted[symbol] * 32 + len)
+ symbol += 1
+ key = nextKey(key, len)
+ count[len + 1] -= 1
+ end
+ step *= 2
+ end
+ step = 2
+ for len = ROOT_BITS + 1, MAX_LEN do
+ numOpen *= 2
+ numNodes += numOpen
+ numOpen -= count[len + 1]
+ if numOpen < 0 then
+ return -1
+ end
+ while count[len + 1] > 0 do
+ if band(key, mask) ~= low then
+ tableAt += tableSize
+ -- NextTableBitSize
+ local l2 = len
+ local left = lshift(1, l2 - ROOT_BITS)
+ while l2 < MAX_LEN do
+ left -= count[l2 + 1]
+ if left <= 0 then
+ break
+ end
+ l2 += 1
+ left *= 2
+ end
+ tableBits = l2 - ROOT_BITS
+ tableSize = lshift(1, tableBits)
+ totalSize += tableSize
+ low = band(key, mask)
+ writeu32(tab, (root + low) * 4, (tableAt - root - low) * 32 + tableBits + ROOT_BITS)
+ end
+ replicate(tab, tableAt + rshift(key, ROOT_BITS), step, tableSize, sorted[symbol] * 32 + len - ROOT_BITS)
+ symbol += 1
+ key = nextKey(key, len)
+ count[len + 1] -= 1
+ end
+ step *= 2
+ end
+ if numNodes ~= 2 * offset[MAX_LEN + 1] - 1 then
+ return -1
+ end
+ d.tabUsed = root + totalSize
+ 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)
+ end
+ local tab = d.tab
+ local bitbuf = d.bitbuf
+ local idx = at + band(bitbuf, 255)
+ local e = readu32(tab, idx * 4)
+ local nb = band(e, 31)
+ if nb > ROOT_BITS then
+ bitbuf = rshift(bitbuf, ROOT_BITS)
+ d.bitcnt -= ROOT_BITS
+ e = readu32(tab, (idx + rshift(e, 5) + band(bitbuf, lshift(1, nb - ROOT_BITS) - 1)) * 4)
+ nb = band(e, 31)
+ end
+ d.bitbuf = rshift(bitbuf, nb)
+ d.bitcnt -= nb
+ return rshift(e, 5)
+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
+ end
+ if readBits(d, 1) == 1 then
+ local numSymbols = readBits(d, 1) + 1
+ local first = readBits(d, 1)
+ local s = readBits(d, if first == 0 then 1 else 8)
+ if s < size then
+ codeLengths[s + 1] = 1
+ end
+ if numSymbols == 2 then
+ s = readBits(d, 8)
+ if s < size then
+ codeLengths[s + 1] = 1
+ end
+ end
+ else
+ for i = 1, 19 do
+ clLens[i] = 0
+ end
+ local numCodes = readBits(d, 4) + 4
+ for i = 1, numCodes do
+ clLens[CODE_LENGTH_ORDER[i] + 1] = readBits(d, 3)
+ end
+ local mark = d.tabUsed
+ local clt = build(d, clLens, 19)
+ if clt < 0 then
+ return -1
+ end
+ local maxSymbol = size
+ if readBits(d, 1) == 1 then
+ local nbits = 2 + 2 * readBits(d, 3)
+ maxSymbol = 2 + readBits(d, nbits)
+ if maxSymbol > size then
+ return -1
+ end
+ end
+ local prev = 8
+ local s = 0
+ while s < size do
+ if maxSymbol == 0 then
+ break
+ end
+ maxSymbol -= 1
+ local cl = readSymbol(d, clt)
+ if cl < 16 then
+ codeLengths[s + 1] = cl
+ s += 1
+ if cl ~= 0 then
+ prev = cl
+ end
+ else
+ local rep, len
+ if cl == 16 then
+ rep, len = readBits(d, 2) + 3, prev
+ elseif cl == 17 then
+ rep, len = readBits(d, 3) + 3, 0
+ else
+ rep, len = readBits(d, 7) + 11, 0
+ end
+ if s + rep > size then
+ return -1
+ end
+ for k = s + 1, s + rep do
+ codeLengths[k] = len
+ end
+ s += rep
+ end
+ end
+ d.tabUsed = mark -- the code length table is temporary
+ end
+ if eos(d) then
+ return -1
+ end
+ 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
+Decode.subSample = subSample
+
+local function cacheKey(argb: number, shift: number): number
+ -- (0x1e35a7bd * argb) mod 2^32 >> shift, exact in doubles
+ local lo = argb % 65536
+ local hi = (argb - lo) / 65536
+ local m = (lo * 0xa7bd + ((lo * 0x1e35 + hi * 0xa7bd) % 65536) * 65536) % 4294967296
+ return rshift(m, shift)
+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
+ local cshift = 32 - cacheBits
+ local lenLimit = NUM_LITERAL + NUM_LENGTH
+ local cacheLimit = lenLimit + (if cacheBits > 0 then lshift(1, cacheBits) else 0)
+ local hmask = if himg then lshift(1, hbits) - 1 else -1
+ local i, col, row = 0, 0, 0
+ local gG, gR, gB, gA, gD = groups[1], groups[2], groups[3], groups[4], groups[5]
+ local function setGroup()
+ if himg then
+ local g = readu32(himg, (hxs * rshift(row, hbits) + rshift(col, hbits)) * 4) * 5
+ gG, gR, gB, gA, gD = groups[g + 1], groups[g + 2], groups[g + 3], groups[g + 4], groups[g + 5]
+ end
+ end
+ while i < total do
+ if band(col, hmask) == 0 then
+ setGroup()
+ end
+ local code = readSymbol(d, gG)
+ if code < NUM_LITERAL then
+ local r = readSymbol(d, gR)
+ local b = readSymbol(d, gB)
+ local a = readSymbol(d, gA)
+ if d.bitcnt < d.over * 8 then
+ break
+ end
+ local argb = a * 16777216 + r * 65536 + code * 256 + b
+ writeu32(data, i * 4, argb)
+ if cache then
+ writeu32(cache, cacheKey(argb, cshift) * 4, argb)
+ end
+ i += 1
+ col += 1
+ if col >= w then
+ col = 0
+ row += 1
+ end
+ elseif code < lenLimit then
+ local ls = code - NUM_LITERAL
+ local length
+ if ls < 4 then
+ length = ls + 1
+ else
+ local eb = rshift(ls - 2, 1)
+ length = lshift(2 + band(ls, 1), eb) + readBits(d, eb) + 1
+ end
+ local ds = readSymbol(d, gD)
+ local dc
+ if ds < 4 then
+ dc = ds + 1
+ else
+ local eb = rshift(ds - 2, 1)
+ dc = lshift(2 + band(ds, 1), eb) + readBits(d, eb) + 1
+ end
+ local dist
+ if dc > 120 then
+ dist = dc - 120
+ else
+ local v = CODE_TO_PLANE[dc]
+ dist = rshift(v, 4) * w + 8 - band(v, 15)
+ if dist < 1 then
+ dist = 1
+ end
+ end
+ if d.bitcnt < d.over * 8 then
+ break
+ end
+ if i < dist or total - i < length then
+ return false, "bad backward reference"
+ end
+ if dist >= length then
+ bcopy(data, i * 4, data, (i - dist) * 4, length * 4)
+ else
+ for k = i, i + length - 1 do
+ writeu32(data, k * 4, readu32(data, (k - dist) * 4))
+ end
+ end
+ if cache then
+ for k = i, i + length - 1 do
+ local argb = readu32(data, k * 4)
+ writeu32(cache, cacheKey(argb, cshift) * 4, argb)
+ end
+ end
+ i += length
+ col += length
+ while col >= w do
+ col -= w
+ row += 1
+ end
+ if band(col, hmask) ~= 0 then
+ setGroup()
+ end
+ elseif code < cacheLimit and cache then
+ if d.bitcnt < d.over * 8 then
+ break
+ end
+ local argb = readu32(cache, (code - lenLimit) * 4)
+ writeu32(data, i * 4, argb)
+ writeu32(cache, cacheKey(argb, cshift) * 4, argb)
+ i += 1
+ col += 1
+ if col >= w then
+ col = 0
+ row += 1
+ end
+ else
+ return false, "bad symbol"
+ end
+ end
+ if eos(d) then
+ return false, "truncated: pixel data"
+ end
+ 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
+Decode.addPixels = addPixels
+
+local function average2(a: number, b: number): number
+ return rshift(band(bxor(a, b), 0xfefefefe), 1) + band(a, b)
+end
+Decode.average2 = average2
+
+local function clip255(v: number): number
+ return if v < 0 then 0 elseif v > 255 then 255 else v
+end
+
+local function sub3(a: number, b: number, c: number): number
+ local pb, pa = b - c, a - c
+ return (if pb < 0 then -pb else pb) - (if pa < 0 then -pa else pa)
+end
+
+-- select(T, L, TL)
+local function select3(a: number, b: number, c: number): number
+ local s = sub3(rshift(a, 24), rshift(b, 24), rshift(c, 24))
+ + sub3(band(rshift(a, 16), 255), band(rshift(b, 16), 255), band(rshift(c, 16), 255))
+ + sub3(band(rshift(a, 8), 255), band(rshift(b, 8), 255), band(rshift(c, 8), 255))
+ + sub3(band(a, 255), band(b, 255), band(c, 255))
+ return if s <= 0 then a else b
+end
+
+local function clampedFull(c0: number, c1: number, c2: number): number
+ local a = clip255(rshift(c0, 24) + rshift(c1, 24) - rshift(c2, 24))
+ local r = clip255(band(rshift(c0, 16), 255) + band(rshift(c1, 16), 255) - band(rshift(c2, 16), 255))
+ local g = clip255(band(rshift(c0, 8), 255) + band(rshift(c1, 8), 255) - band(rshift(c2, 8), 255))
+ local b = clip255(band(c0, 255) + band(c1, 255) - band(c2, 255))
+ return a * 16777216 + r * 65536 + g * 256 + b
+end
+
+local function half(a: number, b: number): number
+ local dd = a - b
+ -- C division truncates toward zero
+ local q = if dd >= 0 then rshift(dd, 1) else -rshift(-dd, 1)
+ return clip255(a + q)
+end
+
+local function clampedHalf(c0: number, c1: number, c2: number): number
+ local ave = average2(c0, c1)
+ local a = half(rshift(ave, 24), rshift(c2, 24))
+ local r = half(band(rshift(ave, 16), 255), band(rshift(c2, 16), 255))
+ local g = half(band(rshift(ave, 8), 255), band(rshift(c2, 8), 255))
+ local b = half(band(ave, 255), band(c2, 255))
+ 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)
+local function predict(mode: number, L: number, T: number, TR: number, TL: number): number
+ if mode == 0 then
+ return ARGB_BLACK
+ elseif mode == 1 then
+ return L
+ elseif mode == 2 then
+ return T
+ elseif mode == 3 then
+ return TR
+ elseif mode == 4 then
+ return TL
+ elseif mode == 5 then
+ return average2(average2(L, TR), T)
+ elseif mode == 6 then
+ return average2(L, TL)
+ elseif mode == 7 then
+ return average2(L, T)
+ elseif mode == 8 then
+ return average2(TL, T)
+ elseif mode == 9 then
+ return average2(T, TR)
+ elseif mode == 10 then
+ return average2(average2(L, TL), average2(T, TR))
+ elseif mode == 11 then
+ return select3(T, L, TL)
+ elseif mode == 12 then
+ return clampedFull(L, T, TL)
+ elseif mode == 13 then
+ return clampedHalf(L, T, TL)
+ end
+ return ARGB_BLACK
+end
+Decode.predict = predict
+
+local function inversePredictor(data: buffer, w: number, h: number, bits: number, sub: buffer)
+ local tw = subSample(w, bits)
+ -- first row: black, then L
+ writeu32(data, 0, addPixels(readu32(data, 0), ARGB_BLACK))
+ for x = 1, w - 1 do
+ writeu32(data, x * 4, addPixels(readu32(data, x * 4), readu32(data, (x - 1) * 4)))
+ end
+ for y = 1, h - 1 do
+ local row = y * w
+ local up = row - w
+ writeu32(data, row * 4, addPixels(readu32(data, row * 4), readu32(data, up * 4)))
+ local trow = rshift(y, bits) * tw
+ local x = 1
+ while x < w do
+ local mode = band(rshift(readu32(sub, (trow + rshift(x, bits)) * 4), 8), 15)
+ local xe = math.min(w, lshift(rshift(x, bits) + 1, bits))
+ local L = readu32(data, (row + x - 1) * 4)
+ if mode == 1 then
+ for k = x, xe - 1 do
+ L = addPixels(readu32(data, (row + k) * 4), L)
+ writeu32(data, (row + k) * 4, L)
+ end
+ elseif mode == 2 then
+ for k = x, xe - 1 do
+ writeu32(data, (row + k) * 4, addPixels(readu32(data, (row + k) * 4), readu32(data, (up + k) * 4)))
+ end
+ else
+ for k = x, xe - 1 do
+ local p = predict(mode, L, readu32(data, (up + k) * 4), readu32(data, (up + k + 1) * 4), readu32(data, (up + k - 1) * 4))
+ L = addPixels(readu32(data, (row + k) * 4), p)
+ writeu32(data, (row + k) * 4, L)
+ end
+ end
+ x = xe
+ end
+ end
+end
+
+local function sint8(v: number): number
+ return if v >= 128 then v - 256 else v
+end
+
+local function inverseCrossColor(data: buffer, w: number, h: number, bits: number, sub: buffer)
+ local tw = subSample(w, bits)
+ for y = 0, h - 1 do
+ local trow = rshift(y, bits) * tw
+ local x = 0
+ while x < w do
+ local m = readu32(sub, (trow + rshift(x, bits)) * 4)
+ local g2r = sint8(band(m, 255))
+ local g2b = sint8(band(rshift(m, 8), 255))
+ local r2b = sint8(band(rshift(m, 16), 255))
+ local xe = math.min(w, lshift(rshift(x, bits) + 1, bits))
+ for k = y * w + x, y * w + xe - 1 do
+ local argb = readu32(data, k * 4)
+ local g = sint8(band(rshift(argb, 8), 255))
+ local r = band(band(rshift(argb, 16), 255) + ((g2r * g) // 32), 255)
+ local b = band(band(argb, 255) + ((g2b * g) // 32) + ((r2b * sint8(r)) // 32), 255)
+ writeu32(data, k * 4, band(argb, 0xff00ff00) + r * 65536 + b)
+ end
+ x = xe
+ end
+ end
+end
+
+local function inverseSubtractGreen(data: buffer, n: number)
+ for k = 0, n - 1 do
+ local argb = readu32(data, k * 4)
+ local g = band(rshift(argb, 8), 255)
+ writeu32(data, k * 4, band(argb, 0xff00ff00) + band(band(argb, 0x00ff00ff) + g * 65537, 0x00ff00ff))
+ 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
+ for k = 0, w * h - 1 do
+ writeu32(out, k * 4, readu32(map, band(rshift(readu32(src, k * 4), 8), 255) * 4))
+ end
+ return out
+ end
+ local bpp = rshift(8, bits)
+ local cmask = lshift(1, bits) - 1
+ local vmask = lshift(1, bpp) - 1
+ for y = 0, h - 1 do
+ local packed = 0
+ local s = y * sw
+ local o = y * w
+ for x = 0, w - 1 do
+ if band(x, cmask) == 0 then
+ packed = band(rshift(readu32(src, s * 4), 8), 255)
+ s += 1
+ end
+ writeu32(out, (o + x) * 4, readu32(map, band(packed, vmask) * 4))
+ packed = rshift(packed, bpp)
+ end
+ end
+ 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
+ local numGroups = 1
+ local mapping: { number }? = nil
+ local numMax = 1
+ if level0 and readBits(d, 1) == 1 then
+ hbits = readBits(d, 3) + 2
+ hxs = subSample(xs, hbits)
+ local hys = subSample(ys, hbits)
+ local img, err = decodeStream(d, hxs, hys, false)
+ if not img then
+ return nil, nil, 0, 0, err
+ end
+ local n = hxs * hys
+ for k = 0, n - 1 do
+ local g = band(rshift(readu32(img, k * 4), 8), 0xffff)
+ writeu32(img, k * 4, g)
+ if g >= numMax then
+ numMax = g + 1
+ end
+ end
+ if numMax > 1000 or numMax > xs * ys then
+ -- remap the used groups to [0, numGroups); unused ones are read and checked but not kept
+ local map: { number } = table.create(numMax, -1)
+ numGroups = 0
+ for k = 0, n - 1 do
+ local g = readu32(img, k * 4)
+ if map[g + 1] == -1 then
+ map[g + 1] = numGroups
+ numGroups += 1
+ end
+ writeu32(img, k * 4, map[g + 1])
+ end
+ mapping = map
+ else
+ numGroups = numMax
+ end
+ himg = img
+ end
+ if eos(d) then
+ return nil, nil, 0, 0, "truncated: meta codes"
+ end
+ local groups: { number } = table.create(numGroups * 5, 0)
+ local cacheSize = if cacheBits > 0 then lshift(1, cacheBits) else 0
+ for i = 0, numMax - 1 do
+ local slot = if mapping then mapping[i + 1] else i
+ local mark = d.tabUsed
+ for j = 0, 4 do
+ local size = if j == 0 then NUM_LITERAL + NUM_LENGTH + cacheSize elseif j == 4 then NUM_DISTANCE else NUM_LITERAL
+ local at = readCode(d, size)
+ if at < 0 then
+ return nil, nil, 0, 0, if eos(d) then "truncated: prefix code" else "bad prefix code"
+ end
+ if slot >= 0 then
+ groups[slot * 5 + j + 1] = at
+ end
+ end
+ if slot < 0 then
+ d.tabUsed = mark
+ end
+ end
+ return groups, himg, hbits, hxs, nil
+end
+
+decodeStream = function(d: State, xs: number, ys: number, level0: boolean): (buffer?, string?)
+ local transforms: { Transform } = {}
+ local seen = 0
+ local txs = xs
+ if level0 then
+ while readBits(d, 1) == 1 do
+ local kind = readBits(d, 2)
+ if band(seen, lshift(1, kind)) ~= 0 then
+ return nil, "repeated transform"
+ end
+ seen = bor(seen, lshift(1, kind))
+ local t: Transform = { kind = kind, xsize = txs, bits = 0, data = nil }
+ if kind == 0 or kind == 1 then
+ t.bits = readBits(d, 3) + 2
+ local sub, err = decodeStream(d, subSample(txs, t.bits), subSample(ys, t.bits), false)
+ if not sub then
+ return nil, err
+ end
+ t.data = sub
+ elseif kind == 3 then
+ local num = readBits(d, 8) + 1
+ local bits = if num > 16 then 0 elseif num > 4 then 1 elseif num > 2 then 2 else 3
+ t.bits = bits
+ local pal, err = decodeStream(d, num, 1, false)
+ if not pal then
+ return nil, err
+ end
+ local final = lshift(1, rshift(8, bits))
+ local map = bcreate(final * 4)
+ local prev = 0
+ for k = 0, num - 1 do
+ prev = addPixels(readu32(pal, k * 4), prev)
+ writeu32(map, k * 4, prev)
+ end
+ t.data = map
+ txs = subSample(txs, bits)
+ end
+ table.insert(transforms, t)
+ if eos(d) then
+ return nil, "truncated: transforms"
+ end
+ end
+ end
+ local cacheBits = 0
+ if readBits(d, 1) == 1 then
+ cacheBits = readBits(d, 4)
+ if cacheBits < 1 or cacheBits > MAX_CACHE_BITS then
+ return nil, "bad colour cache size"
+ end
+ end
+ local mark = d.tabUsed
+ local groups, himg, hbits, hxs, err = readCodes(d, txs, ys, cacheBits, level0)
+ if not groups then
+ return nil, err
+ end
+ local data = bcreate(txs * ys * 4)
+ local ok, derr = decodeData(d, data, txs, ys, cacheBits, groups, himg, hbits, hxs)
+ if not ok then
+ return nil, derr
+ end
+ d.tabUsed = mark
+ -- inverse transforms, last read first
+ for k = #transforms, 1, -1 do
+ local t = transforms[k]
+ if t.kind == 0 then
+ inversePredictor(data, t.xsize, ys, t.bits, t.data :: buffer)
+ elseif t.kind == 1 then
+ inverseCrossColor(data, t.xsize, ys, t.bits, t.data :: buffer)
+ elseif t.kind == 2 then
+ inverseSubtractGreen(data, t.xsize * ys)
+ else
+ data = inverseColorIndexing(data, subSample(t.xsize, t.bits), t.xsize, ys, t.bits, t.data :: buffer)
+ end
+ end
+ return data, nil
+end
+
+local function newState(buf: buffer, off: number, len: number, maxPixels: number): State
+ return {
+ buf = buf,
+ pos = off,
+ limit = off + len,
+ bitbuf = 0,
+ bitcnt = 0,
+ over = 0,
+ tab = bcreate(4096 * 4),
+ tabUsed = 0,
+ maxPixels = maxPixels,
+ }
+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"
+ end
+ if readu8(buf, off) ~= 0x2f then
+ return nil, 0, false, "bad VP8L signature"
+ end
+ local v = readu32(buf, off + 1)
+ local w = band(v, 0x3fff) + 1
+ local h = band(rshift(v, 14), 0x3fff) + 1
+ local alpha = band(rshift(v, 28), 1) == 1
+ if rshift(v, 29) ~= 0 then
+ return nil, 0, false, "bad VP8L version"
+ end
+ 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
+ return nil, 0, 0, false, err
+ end
+ if w * h > maxPixels then
+ return nil, w, h, alpha, "limit: " .. w .. " x " .. h .. " is over maxPixels"
+ end
+ local d = newState(buf, off + 5, len - 5, maxPixels)
+ local data, derr = decodeStream(d, w, h, true)
+ if not data then
+ return nil, w, h, alpha, derr
+ end
+ 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
+ for k = 0, n - 1 do
+ local v = readu32(argb, k * 4)
+ -- 0xAARRGGBB (bytes B G R A) -> bytes R G B A
+ writeu32(o, base + k * 4, band(v, 0xff00ff00) + band(rshift(v, 16), 255) + band(v, 255) * 65536)
+ end
+ 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
+ writeu8(o, k, band(rshift(readu32(argb, k * 4), 8), 255))
+ end
+ return o
+end
+
+return Decode
diff --git a/src/Formats/codecs/Vp8L/Encode.luau b/src/Formats/codecs/Vp8L/Encode.luau
new file mode 100644
index 0000000..1eff41a
--- /dev/null
+++ b/src/Formats/codecs/Vp8L/Encode.luau
@@ -0,0 +1,976 @@
+--!strict
+--!native
+--!optimize 2
+-- codecs/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 (core/Huffman) and run-length coded.
+-- Never throws (the init module validates the arguments).
+local Huffman = require("@formats/core/Huffman")
+
+local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift
+local readu32, writeu8, writeu32 = buffer.readu32, buffer.writeu8, buffer.writeu32
+local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len
+local log = math.log
+
+local Encode = {}
+
+local NUM_LITERAL = 256
+local NUM_LENGTH = 24
+local NUM_DISTANCE = 40
+local MAX_LENGTH = 4096
+local WINDOW = 1048576 - 120
+local ARGB_BLACK = 0xff000000
+
+local CODE_LENGTH_ORDER = { 17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }
+local CODE_TO_PLANE = {
+ 0x18, 0x07, 0x17, 0x19, 0x28, 0x06, 0x27, 0x29, 0x16, 0x1a, 0x26, 0x2a, 0x38, 0x05, 0x37, 0x39, 0x15, 0x1b, 0x36,
+ 0x3a, 0x25, 0x2b, 0x48, 0x04, 0x47, 0x49, 0x14, 0x1c, 0x35, 0x3b, 0x46, 0x4a, 0x24, 0x2c, 0x58, 0x45, 0x4b, 0x34,
+ 0x3c, 0x03, 0x57, 0x59, 0x13, 0x1d, 0x56, 0x5a, 0x23, 0x2d, 0x44, 0x4c, 0x55, 0x5b, 0x33, 0x3d, 0x68, 0x02, 0x67,
+ 0x69, 0x12, 0x1e, 0x66, 0x6a, 0x22, 0x2e, 0x54, 0x5c, 0x43, 0x4d, 0x65, 0x6b, 0x32, 0x3e, 0x78, 0x01, 0x77, 0x79,
+ 0x53, 0x5d, 0x11, 0x1f, 0x64, 0x6c, 0x42, 0x4e, 0x76, 0x7a, 0x21, 0x2f, 0x75, 0x7b, 0x31, 0x3f, 0x63, 0x6d, 0x52,
+ 0x5e, 0x00, 0x74, 0x7c, 0x41, 0x4f, 0x10, 0x20, 0x62, 0x6e, 0x30, 0x73, 0x7d, 0x51, 0x5f, 0x40, 0x72, 0x7e, 0x61,
+ 0x6f, 0x50, 0x71, 0x7f, 0x60, 0x70,
+}
+-- PLANE_TO_CODE[v + 1] = the distance code (1..120) of the plane offset v = yoffset * 16 + 8 - xoffset
+local PLANE_TO_CODE = table.create(128, 0)
+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
+local function put(w: W, v: number, n: number)
+ local acc = w.acc + v * 2 ^ w.cnt
+ local cnt = w.cnt + n
+ if cnt >= 8 then
+ local pos = w.pos
+ local buf = w.buf
+ if pos + 8 > blen(buf) then
+ local nb = bcreate(blen(buf) * 2)
+ bcopy(nb, 0, buf, 0, pos)
+ buf = nb
+ w.buf = nb
+ end
+ repeat
+ local byte = acc % 256
+ writeu8(buf, pos, byte)
+ pos += 1
+ acc = (acc - byte) / 256
+ cnt -= 8
+ until cnt < 8
+ w.pos = pos
+ end
+ w.acc, w.cnt = acc, cnt
+end
+
+local function finish(w: W): buffer
+ if w.cnt > 0 then
+ put(w, 0, 8 - w.cnt)
+ end
+ local out = bcreate(w.pos)
+ bcopy(out, 0, w.buf, 0, w.pos)
+ return out
+end
+
+-- ------------------------------------------------------------------------------------------------ helpers
+local function subSample(size: number, bits: number): number
+ return rshift(size + lshift(1, bits) - 1, bits)
+end
+
+-- (0x1e35a7bd * v) mod 2^32: the colour cache hash before its shift
+local function mulHash(v: number): number
+ local lo = v % 65536
+ local hi = (v - lo) / 65536
+ 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
+ return d, 0, 0
+ end
+ local hb = 0
+ local t = d
+ while t >= 2 do
+ t = rshift(t, 1)
+ hb += 1
+ end
+ local second = band(rshift(d, hb - 1), 1)
+ local eb = hb - 1
+ 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)
+local function distCode(xs: number, dist: number): number
+ local yo = dist // xs
+ local xo = dist - yo * xs
+ if xo <= 8 and yo < 8 then
+ return PLANE_TO_CODE[yo * 16 + 8 - xo + 1]
+ elseif xo > xs - 8 and yo < 7 then
+ return PLANE_TO_CODE[(yo + 1) * 16 + 8 + (xs - xo) + 1]
+ end
+ return dist + 120
+end
+
+local function subPixels(a: number, b: number): number
+ return band(bor(a, 0x00ff00ff) - band(b, 0xff00ff00), 0xff00ff00) + band(bor(a, 0xff00ff00) - band(b, 0x00ff00ff), 0x00ff00ff)
+end
+
+local function average2(a: number, b: number): number
+ return rshift(band(bxor(a, b), 0xfefefefe), 1) + band(a, b)
+end
+
+local function clip255(v: number): number
+ return if v < 0 then 0 elseif v > 255 then 255 else v
+end
+
+local function sub3(a: number, b: number, c: number): number
+ local pb, pa = b - c, a - c
+ return (if pb < 0 then -pb else pb) - (if pa < 0 then -pa else pa)
+end
+
+local function half(x: number, y: number): number
+ local dd = x - y
+ 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/Vp8L/Decode)
+local function predict(mode: number, L: number, T: number, TR: number, TL: number): number
+ if mode == 1 then
+ return L
+ elseif mode == 2 then
+ return T
+ elseif mode == 3 then
+ return TR
+ elseif mode == 4 then
+ return TL
+ elseif mode == 5 then
+ return average2(average2(L, TR), T)
+ elseif mode == 6 then
+ return average2(L, TL)
+ elseif mode == 7 then
+ return average2(L, T)
+ elseif mode == 8 then
+ return average2(TL, T)
+ elseif mode == 9 then
+ return average2(T, TR)
+ elseif mode == 10 then
+ return average2(average2(L, TL), average2(T, TR))
+ elseif mode == 11 then
+ local s = sub3(rshift(T, 24), rshift(L, 24), rshift(TL, 24))
+ + sub3(band(rshift(T, 16), 255), band(rshift(L, 16), 255), band(rshift(TL, 16), 255))
+ + sub3(band(rshift(T, 8), 255), band(rshift(L, 8), 255), band(rshift(TL, 8), 255))
+ + sub3(band(T, 255), band(L, 255), band(TL, 255))
+ return if s <= 0 then T else L
+ elseif mode == 12 then
+ local a = clip255(rshift(L, 24) + rshift(T, 24) - rshift(TL, 24))
+ local r = clip255(band(rshift(L, 16), 255) + band(rshift(T, 16), 255) - band(rshift(TL, 16), 255))
+ local g = clip255(band(rshift(L, 8), 255) + band(rshift(T, 8), 255) - band(rshift(TL, 8), 255))
+ local b = clip255(band(L, 255) + band(T, 255) - band(TL, 255))
+ return a * 16777216 + r * 65536 + g * 256 + b
+ elseif mode == 13 then
+ local ave = average2(L, T)
+ local a = half(rshift(ave, 24), rshift(TL, 24))
+ local r = half(band(rshift(ave, 16), 255), band(rshift(TL, 16), 255))
+ local g = half(band(rshift(ave, 8), 255), band(rshift(TL, 8), 255))
+ local b = half(band(ave, 255), band(TL, 255))
+ return a * 16777216 + r * 65536 + g * 256 + b
+ end
+ 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)
+ COST[v + 1] = log(1 + m) / log(2)
+end
+
+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)
+ local modes = if effort <= 2 then MODES_FAST elseif effort <= 6 then MODES_MID else MODES_ALL
+ local ts = lshift(1, bits)
+ for ty = 0, th - 1 do
+ for tx = 0, tw - 1 do
+ local x0, y0 = tx * ts, ty * ts
+ local x1, y1 = math.min(w, x0 + ts), math.min(h, y0 + ts)
+ local best, bestCost = 1, math.huge
+ for _, m in modes do
+ local cost = 0
+ for y = math.max(y0, 1), y1 - 1 do
+ local row = y * w
+ for x = math.max(x0, 1), x1 - 1 do
+ local i = row + x
+ local up = i - w
+ local p = predict(m, readu32(px, (i - 1) * 4), readu32(px, up * 4), readu32(px, (up + 1) * 4), readu32(px, (up - 1) * 4))
+ cost += residualCost(subPixels(readu32(px, i * 4), p))
+ end
+ if cost >= bestCost then
+ break
+ end
+ end
+ if cost < bestCost then
+ best, bestCost = m, cost
+ end
+ end
+ writeu32(modesImg, (ty * tw + tx) * 4, ARGB_BLACK + best * 256)
+ end
+ end
+ -- residuals with the chosen modes (and the decoder's fixed first row and column)
+ local res = bcreate(w * h * 4)
+ writeu32(res, 0, subPixels(readu32(px, 0), ARGB_BLACK))
+ for x = 1, w - 1 do
+ writeu32(res, x * 4, subPixels(readu32(px, x * 4), readu32(px, (x - 1) * 4)))
+ end
+ for y = 1, h - 1 do
+ local row = y * w
+ writeu32(res, row * 4, subPixels(readu32(px, row * 4), readu32(px, (row - w) * 4)))
+ local trow = rshift(y, bits) * tw
+ for x = 1, w - 1 do
+ local m = band(rshift(readu32(modesImg, (trow + rshift(x, bits)) * 4), 8), 15)
+ local i = row + x
+ local up = i - w
+ local p = predict(m, readu32(px, (i - 1) * 4), readu32(px, up * 4), readu32(px, (up + 1) * 4), readu32(px, (up - 1) * 4))
+ writeu32(res, i * 4, subPixels(readu32(px, i * 4), p))
+ end
+ end
+ bcopy(px, 0, res, 0, w * h * 4)
+ return modesImg
+end
+
+local function sint8(v: number): number
+ return if v >= 128 then v - 256 else v
+end
+
+local function clampM(v: number): number
+ local m = math.floor(v + 0.5)
+ 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
+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)
+ local ts = lshift(1, bits)
+ local function tileCost(x0: number, y0: number, x1: number, y1: number, g2r: number, g2b: number, r2b: number): number
+ local c = 0
+ for y = y0, y1 - 1 do
+ for x = x0, x1 - 1 do
+ local argb = readu32(px, (y * w + x) * 4)
+ local g = sint8(band(rshift(argb, 8), 255))
+ local r = band(rshift(argb, 16), 255)
+ local b = band(argb, 255)
+ local nr = band(r - ((g2r * g) // 32), 255)
+ local nb = band(b - ((g2b * g) // 32) - ((r2b * sint8(r)) // 32), 255)
+ c += COST[nr + 1] + COST[nb + 1]
+ end
+ end
+ return c
+ end
+ for ty = 0, th - 1 do
+ for tx = 0, tw - 1 do
+ local x0, y0 = tx * ts, ty * ts
+ local x1, y1 = math.min(w, x0 + ts), math.min(h, y0 + ts)
+ local sgg, sgr, sgb, srr, srb = 0, 0, 0, 0, 0
+ for y = y0, y1 - 1 do
+ for x = x0, x1 - 1 do
+ local argb = readu32(px, (y * w + x) * 4)
+ local g = sint8(band(rshift(argb, 8), 255))
+ local r = sint8(band(rshift(argb, 16), 255))
+ local b = sint8(band(argb, 255))
+ sgg += g * g
+ sgr += g * r
+ sgb += g * b
+ srr += r * r
+ srb += r * b
+ end
+ end
+ local g2r, g2b, r2b = 0, 0, 0
+ if sgg > 0 then
+ g2r = clampM(32 * sgr / sgg)
+ local det = sgg * srr - sgr * sgr
+ if det > 0 then
+ g2b = clampM(32 * (sgb * srr - srb * sgr) / det)
+ r2b = clampM(32 * (srb * sgg - sgb * sgr) / det)
+ else
+ g2b = clampM(32 * sgb / sgg)
+ end
+ end
+ if g2r ~= 0 or g2b ~= 0 or r2b ~= 0 then
+ if tileCost(x0, y0, x1, y1, g2r, g2b, r2b) >= tileCost(x0, y0, x1, y1, 0, 0, 0) then
+ g2r, g2b, r2b = 0, 0, 0
+ end
+ end
+ writeu32(img, (ty * tw + tx) * 4, ARGB_BLACK + band(r2b, 255) * 65536 + band(g2b, 255) * 256 + band(g2r, 255))
+ if g2r ~= 0 or g2b ~= 0 or r2b ~= 0 then
+ for y = y0, y1 - 1 do
+ for x = x0, x1 - 1 do
+ local k = (y * w + x) * 4
+ local argb = readu32(px, k)
+ local g = sint8(band(rshift(argb, 8), 255))
+ local r = band(rshift(argb, 16), 255)
+ local b = band(argb, 255)
+ local nr = band(r - ((g2r * g) // 32), 255)
+ local nb = band(b - ((g2b * g) // 32) - ((r2b * sint8(r)) // 32), 255)
+ writeu32(px, k, band(argb, 0xff00ff00) + nr * 65536 + nb)
+ end
+ end
+ end
+ end
+ end
+ 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
+
+local function hash2(a: number, b: number): number
+ return rshift(mulHash(bxor(a, (b * 31) % 4294967296)), 32 - HASH_BITS)
+end
+
+local function matchLen(px: buffer, i: number, j: number, max: number): number
+ local n = 0
+ while n < max and readu32(px, (i + n) * 4) == readu32(px, (j + n) * 4) do
+ n += 1
+ end
+ return n
+end
+
+local function lz77(px: buffer, xs: number, n: number, effort: number): ({ number }, { number })
+ local L: { number } = {}
+ local D: { number } = {}
+ if effort == 0 then
+ for i = 0, n - 1 do
+ L[i + 1] = readu32(px, i * 4)
+ D[i + 1] = 0
+ end
+ return L, D
+ end
+ local head = table.create(lshift(1, HASH_BITS), -1)
+ local prev = table.create(n, -1)
+ local maxIter = if effort <= 2 then 4 elseif effort <= 5 then 16 elseif effort <= 7 then 48 else 128
+ local function insert(i: number)
+ if i + 1 < n then
+ local h = hash2(readu32(px, i * 4), readu32(px, (i + 1) * 4)) + 1
+ prev[i + 1] = head[h]
+ 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
+ return 0, 0
+ end
+ local bl, bd, bc = 0, 0, math.huge
+ local function try(j: number)
+ local d = i - j
+ if d < 1 or d > WINDOW then
+ return
+ end
+ local l = matchLen(px, i, j, max)
+ if l >= 2 then
+ local c = distCode(xs, d)
+ if l > bl or (l == bl and c < bc) then
+ bl, bd, bc = l, d, c
+ end
+ end
+ end
+ if i >= 1 then
+ try(i - 1)
+ end
+ if i >= xs then
+ try(i - xs)
+ end
+ if bl < max then
+ local h = hash2(readu32(px, i * 4), readu32(px, (i + 1) * 4)) + 1
+ local j = head[h]
+ local it = 0
+ while j >= 0 and it < maxIter and i - j <= WINDOW do
+ if j ~= i - 1 and j ~= i - xs then
+ try(j)
+ if bl >= max then
+ break
+ end
+ end
+ j = prev[j + 1]
+ it += 1
+ end
+ end
+ -- a 2-pixel copy only pays with a short 2-D distance code
+ if bl == 2 and bc > 120 then
+ return 0, 0
+ end
+ return bl, bd
+ end
+ local i = 0
+ local k = 0
+ local lazy = effort >= 4
+ local nl, nd = 0, 0
+ local haveNext = false
+ while i < n do
+ local l, d
+ if haveNext then
+ l, d = nl, nd
+ haveNext = false
+ else
+ l, d = best(i)
+ end
+ if l >= 2 and lazy and l < 64 and i + 1 < n then
+ insert(i)
+ nl, nd = best(i + 1)
+ if nl > l + 1 then
+ -- a literal now, the longer match next
+ k += 1
+ L[k] = readu32(px, i * 4)
+ D[k] = 0
+ i += 1
+ haveNext = true
+ else
+ k += 1
+ L[k] = -l
+ D[k] = distCode(xs, d)
+ for t = i + 1, i + l - 1 do
+ insert(t)
+ end
+ i += l
+ end
+ elseif l >= 2 then
+ k += 1
+ L[k] = -l
+ D[k] = distCode(xs, d)
+ local stop = i + l
+ if effort <= 2 and l > 16 then
+ insert(i)
+ insert(stop - 1)
+ else
+ for t = i, stop - 1 do
+ insert(t)
+ end
+ end
+ i = stop
+ else
+ insert(i)
+ k += 1
+ L[k] = readu32(px, i * 4)
+ D[k] = 0
+ i += 1
+ end
+ end
+ return L, D
+end
+
+-- ------------------------------------------------------------------------------------------------ prefix codes
+local function entropy(h: { number }): number
+ local total = 0
+ for _, c in h do
+ total += c
+ end
+ if total == 0 then
+ return 0
+ end
+ local bits = 0
+ local lt = log(total)
+ for _, c in h do
+ if c > 0 then
+ bits += c * (lt - log(c))
+ end
+ end
+ 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
+ end
+ local cands = if effort < 5 then { 0, 4, 7, 10 } else { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
+ local caches: { { number } } = {}
+ local hg: { { number } } = {}
+ local hr: { { number } } = {}
+ local hb: { { number } } = {}
+ local ha: { { number } } = {}
+ for c, bits in cands do
+ caches[c] = table.create(lshift(1, bits), -1)
+ hg[c] = table.create(256 + lshift(1, bits), 0)
+ hr[c] = table.create(256, 0)
+ hb[c] = table.create(256, 0)
+ ha[c] = table.create(256, 0)
+ end
+ local pos = 0
+ for _, t in L do
+ if t >= 0 then
+ local hsh = mulHash(t)
+ for c, bits in cands do
+ local cache = caches[c]
+ local key = if bits > 0 then rshift(hsh, 32 - bits) else 0
+ if bits > 0 and cache[key + 1] == t then
+ hg[c][257 + key] += 1
+ else
+ hg[c][band(rshift(t, 8), 255) + 1] += 1
+ hr[c][band(rshift(t, 16), 255) + 1] += 1
+ hb[c][band(t, 255) + 1] += 1
+ ha[c][rshift(t, 24) + 1] += 1
+ end
+ if bits > 0 then
+ cache[key + 1] = t
+ end
+ end
+ pos += 1
+ else
+ for p = pos, pos - t - 1 do
+ local v = readu32(px, p * 4)
+ local hsh = mulHash(v)
+ for c, bits in cands do
+ if bits > 0 then
+ caches[c][rshift(hsh, 32 - bits) + 1] = v
+ end
+ end
+ end
+ pos -= t
+ end
+ end
+ local bestBits, bestCost = 0, math.huge
+ for c, bits in cands do
+ -- + a rough price for the longer green code lengths
+ local cost = entropy(hg[c]) + entropy(hr[c]) + entropy(hb[c]) + entropy(ha[c]) + lshift(1, bits) * 0.5
+ if cost < bestCost then
+ bestBits, bestCost = bits, cost
+ end
+ end
+ return bestBits
+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
+ for _, l in lens do
+ if l > 0 then
+ used += 1
+ end
+ end
+ local codes = Huffman.codes(lens)
+ for i, l in lens do
+ if l > 0 then
+ codes[i] = Huffman.reverse(codes[i], l)
+ end
+ end
+ return { lens = lens, codes = codes, single = used <= 1 }
+end
+
+local function emit(w: W, c: Code, sym: number)
+ if not c.single then
+ put(w, c.codes[sym + 1], c.lens[sym + 1])
+ end
+end
+
+local function zeroRun(tok: { number }, ext: { number }, run: number)
+ local r = run
+ while r > 0 do
+ if r >= 11 then
+ local k = math.min(r, 138)
+ table.insert(tok, 18)
+ table.insert(ext, k - 11)
+ r -= k
+ elseif r >= 3 then
+ table.insert(tok, 17)
+ table.insert(ext, r - 3)
+ r = 0
+ else
+ table.insert(tok, 0)
+ table.insert(ext, 0)
+ r -= 1
+ end
+ 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
+ if (c.lens[s + 1] or 0) > 0 then
+ table.insert(syms, s)
+ if #syms > 2 then
+ break
+ end
+ end
+ end
+ if #syms == 0 then
+ -- an unused alphabet: the simple code of symbol 0
+ put(w, 1, 1)
+ put(w, 0, 1)
+ put(w, 0, 1)
+ put(w, 0, 1)
+ return
+ end
+ if #syms <= 2 and syms[#syms] < 256 then
+ put(w, 1, 1)
+ put(w, #syms - 1, 1)
+ if syms[1] <= 1 then
+ put(w, 0, 1)
+ put(w, syms[1], 1)
+ else
+ put(w, 1, 1)
+ put(w, syms[1], 8)
+ end
+ if #syms == 2 then
+ put(w, syms[2], 8)
+ end
+ return
+ end
+ -- run-length tokens of every length: 0..15 literal, 16 repeats the previous non-zero length (3..6 times; the
+ -- 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 prev = 8
+ local s = 1
+ while s <= size do
+ local l = c.lens[s] or 0
+ local run = 1
+ while s + run <= size and (c.lens[s + run] or 0) == l do
+ run += 1
+ end
+ if l == 0 then
+ zeroRun(tok, ext, run)
+ else
+ local r = run
+ if l ~= prev then
+ table.insert(tok, l)
+ table.insert(ext, 0)
+ r -= 1
+ prev = l
+ end
+ while r > 0 do
+ if r >= 3 then
+ local k = math.min(r, 6)
+ table.insert(tok, 16)
+ table.insert(ext, k - 3)
+ r -= k
+ else
+ table.insert(tok, l)
+ table.insert(ext, 0)
+ r -= 1
+ end
+ end
+ keep = #tok
+ end
+ s += run
+ end
+ local ntok = #tok
+ local trim = keep < ntok and keep >= 2
+ if trim then
+ ntok = keep
+ end
+ local hist = table.create(19, 0)
+ for i = 1, ntok do
+ hist[tok[i] + 1] += 1
+ end
+ local cl = buildCode(hist, 7)
+ local nc = 19
+ while nc > 4 and (cl.lens[CODE_LENGTH_ORDER[nc] + 1] or 0) == 0 do
+ nc -= 1
+ end
+ put(w, 0, 1)
+ put(w, nc - 4, 4)
+ for i = 1, nc do
+ put(w, cl.lens[CODE_LENGTH_ORDER[i] + 1] or 0, 3)
+ end
+ if trim then
+ put(w, 1, 1)
+ local v = ntok - 2
+ local nbits = 0
+ while lshift(1, nbits) <= v do
+ nbits += 1
+ end
+ local pairs = math.max(1, (nbits + 1) // 2)
+ put(w, pairs - 1, 3)
+ put(w, v, pairs * 2)
+ else
+ put(w, 0, 1)
+ end
+ for i = 1, ntok do
+ local t = tok[i]
+ emit(w, cl, t)
+ if t == 16 then
+ put(w, ext[i], 2)
+ elseif t == 17 then
+ put(w, ext[i], 3)
+ elseif t == 18 then
+ put(w, ext[i], 7)
+ end
+ end
+end
+
+-- ------------------------------------------------------------------------------------------------ image data
+-- writeImage(w, px, xs, n, effort, level0): 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
+ if cacheBits > 0 then
+ put(w, 1, 1)
+ put(w, cacheBits, 4)
+ else
+ put(w, 0, 1)
+ end
+ if level0 then
+ put(w, 0, 1) -- no meta prefix codes
+ end
+ local cacheSize = if cacheBits > 0 then lshift(1, cacheBits) else 0
+ local cshift = 32 - cacheBits
+ local hg = table.create(NUM_LITERAL + NUM_LENGTH + cacheSize, 0)
+ local hr = table.create(256, 0)
+ local hb = table.create(256, 0)
+ local ha = table.create(256, 0)
+ local hd = table.create(NUM_DISTANCE, 0)
+ -- token kinds after the cache: 0 literal, 1 cache hit, 2 copy
+ local cache: { number }? = if cacheBits > 0 then table.create(cacheSize, -1) else nil
+ local K = table.create(#L, 0)
+ local pos = 0
+ for i, t in L do
+ if t >= 0 then
+ local hit = false
+ if cache then
+ local key = rshift(mulHash(t), cshift)
+ if cache[key + 1] == t then
+ hit = true
+ hg[NUM_LITERAL + NUM_LENGTH + key + 1] += 1
+ end
+ cache[key + 1] = t
+ end
+ if hit then
+ K[i] = 1
+ else
+ hg[band(rshift(t, 8), 255) + 1] += 1
+ hr[band(rshift(t, 16), 255) + 1] += 1
+ hb[band(t, 255) + 1] += 1
+ ha[rshift(t, 24) + 1] += 1
+ end
+ pos += 1
+ else
+ K[i] = 2
+ hg[NUM_LITERAL + prefix(-t) + 1] += 1
+ hd[prefix(D[i]) + 1] += 1
+ if cache then
+ for p = pos, pos - t - 1 do
+ local v = readu32(px, p * 4)
+ cache[rshift(mulHash(v), cshift) + 1] = v
+ end
+ end
+ pos -= t
+ end
+ end
+ local cg, cr, cb, ca, cd = buildCode(hg, 15), buildCode(hr, 15), buildCode(hb, 15), buildCode(ha, 15), buildCode(hd, 15)
+ writeCode(w, cg, NUM_LITERAL + NUM_LENGTH + cacheSize)
+ writeCode(w, cr, 256)
+ writeCode(w, cb, 256)
+ writeCode(w, ca, 256)
+ writeCode(w, cd, NUM_DISTANCE)
+ for i, t in L do
+ local k = K[i]
+ if k == 0 then
+ emit(w, cg, band(rshift(t, 8), 255))
+ emit(w, cr, band(rshift(t, 16), 255))
+ emit(w, cb, band(t, 255))
+ emit(w, ca, rshift(t, 24))
+ elseif k == 1 then
+ emit(w, cg, NUM_LITERAL + NUM_LENGTH + rshift(mulHash(t), cshift))
+ else
+ local lc, leb, lev = prefix(-t)
+ emit(w, cg, NUM_LITERAL + lc)
+ if leb > 0 then
+ put(w, lev, leb)
+ end
+ local dc, deb, dev = prefix(D[i])
+ emit(w, cd, dc)
+ if deb > 0 then
+ put(w, dev, deb)
+ end
+ end
+ 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
+ for i = 0, n - 1 do
+ local v = readu32(rgba, i * 4)
+ local a = rshift(v, 24)
+ if a ~= 255 then
+ alpha = true
+ end
+ if a == 0 and not exact then
+ v = 0
+ end
+ -- bytes R G B A (0xAABBGGRR) -> 0xAARRGGBB
+ writeu32(px, i * 4, band(v, 0xff00ff00) + band(rshift(v, 16), 255) + band(v, 255) * 65536)
+ end
+ 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 } = {}
+ for i = 0, n - 1 do
+ local v = readu32(px, i * 4)
+ if not seen[v] then
+ if #list == 256 then
+ return nil
+ end
+ seen[v] = true
+ table.insert(list, v)
+ end
+ end
+ table.sort(list)
+ return list
+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
+ local sub = math.min(effort, 3)
+ local pal = cfg.palette
+ if pal then
+ local num = #pal
+ local bits = if num > 16 then 0 elseif num > 4 then 1 elseif num > 2 then 2 else 3
+ put(bw, 1, 1)
+ put(bw, 3, 2)
+ put(bw, num - 1, 8)
+ local pimg = bcreate(num * 4)
+ local prevc = 0
+ local index: { [number]: number } = {}
+ for i, c in pal do
+ writeu32(pimg, (i - 1) * 4, subPixels(c, prevc))
+ prevc = c
+ index[c] = i - 1
+ end
+ writeImage(bw, pimg, num, num, sub, false)
+ xs = subSample(w, bits)
+ local packed = bcreate(xs * h * 4)
+ local bpp = rshift(8, bits)
+ local cmask = lshift(1, bits) - 1
+ for y = 0, h - 1 do
+ local acc = 0
+ local o = y * xs
+ for x = 0, w - 1 do
+ local sh = band(x, cmask)
+ acc += index[readu32(px, (y * w + x) * 4)] * 2 ^ (bpp * sh)
+ if sh == cmask or x == w - 1 then
+ writeu32(packed, (o + rshift(x, bits)) * 4, ARGB_BLACK + acc * 256)
+ acc = 0
+ end
+ end
+ end
+ px = packed
+ elseif cfg.pbits > 0 then
+ -- subtract green
+ put(bw, 1, 1)
+ put(bw, 2, 2)
+ for i = 0, n - 1 do
+ local v = readu32(px, i * 4)
+ local g = band(rshift(v, 8), 255)
+ writeu32(px, i * 4, band(v, 0xff00ff00) + band(band(v, 0x00ff00ff) + 0x01000100 - g * 65537, 0x00ff00ff))
+ end
+ -- predictor
+ local pbits = cfg.pbits
+ local modes = predictorTransform(px, w, h, pbits, effort)
+ put(bw, 1, 1)
+ put(bw, 0, 2)
+ put(bw, pbits - 2, 3)
+ writeImage(bw, modes, subSample(w, pbits), subSample(w, pbits) * subSample(h, pbits), sub, false)
+ -- cross colour
+ if cfg.cc then
+ local cbits = cfg.ccbits
+ local cimg = crossColorTransform(px, w, h, cbits)
+ put(bw, 1, 1)
+ put(bw, 1, 2)
+ put(bw, cbits - 2, 3)
+ writeImage(bw, cimg, subSample(w, cbits), subSample(w, cbits) * subSample(h, cbits), sub, false)
+ end
+ end
+ put(bw, 0, 1) -- no more transforms
+ 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)
+ local pal = if effort > 0 then palette(px, n) else nil
+ local configs: { Config } = {}
+ if effort == 0 then
+ table.insert(configs, { palette = nil, pbits = 0, cc = false, ccbits = 0 })
+ else
+ local pbits = if effort >= 5 then 4 else 5
+ local plain: Config = { palette = nil, pbits = pbits, cc = effort >= 3, ccbits = if effort >= 6 then 4 else 5 }
+ if pal then
+ table.insert(configs, { palette = pal, pbits = 0, cc = false, ccbits = 0 })
+ if effort >= 6 then
+ table.insert(configs, plain)
+ end
+ else
+ table.insert(configs, plain)
+ end
+ if effort >= 9 then
+ table.insert(configs, { palette = nil, pbits = 3, cc = true, ccbits = 3 })
+ table.insert(configs, { palette = nil, pbits = 5, cc = false, ccbits = 0 })
+ end
+ end
+ local best: buffer? = nil
+ for k, cfg in configs do
+ local bw = newWriter(n + 256)
+ if not headerless then
+ put(bw, 0x2f, 8)
+ put(bw, w - 1, 14)
+ put(bw, h - 1, 14)
+ local hint = if alphaHint == nil then usesAlpha else alphaHint
+ put(bw, if hint then 1 else 0, 1)
+ put(bw, 0, 3)
+ end
+ local work = px
+ if k < #configs then
+ work = bcreate(n * 4)
+ bcopy(work, 0, px, 0, n * 4)
+ end
+ stream(work, w, h, effort, cfg, bw)
+ local out = finish(bw)
+ if not best or blen(out) < blen(best) then
+ best = out
+ end
+ end
+ return best :: buffer
+end
+
+return Encode
diff --git a/src/Formats/codecs/Vp8L/init.luau b/src/Formats/codecs/Vp8L/init.luau
new file mode 100644
index 0000000..d35d7e1
--- /dev/null
+++ b/src/Formats/codecs/Vp8L/init.luau
@@ -0,0 +1,120 @@
+--!strict
+-- codecs/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("@formats/codecs/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).
+local Err = require("@formats/core/Err")
+local Decode = require("@formats/codecs/Vp8L/Decode")
+local Encode = require("@formats/codecs/Vp8L/Encode")
+
+local Vp8L = {}
+
+local DEFAULT_MAX_PIXELS = 2 ^ 28
+
+local function fail(msg: string?, offset: number?): Err.Err
+ local m = msg or "bad data"
+ if string.sub(m, 1, 11) == "truncated: " then
+ return Err.new(Err.TRUNCATED, string.sub(m, 12), offset)
+ elseif string.sub(m, 1, 7) == "limit: " then
+ return Err.new(Err.LIMIT, string.sub(m, 8), offset)
+ end
+ return Err.new(Err.CORRUPT, m, offset)
+end
+Vp8L.fail = fail
+
+local function range(buf: buffer, off: number?, len: number?): (number, number)
+ local n = buffer.len(buf)
+ local o = math.clamp(off or 0, 0, n)
+ 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)
+ if not w then
+ return nil, fail(err, o)
+ end
+ 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)
+ if not px then
+ return nil, fail(err, o)
+ end
+ 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
+ return nil, w
+ end
+ 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)
+ if not px then
+ return nil, fail(err, o)
+ end
+ 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
+}
+
+-- 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")
+ end
+ if width < 1 or height < 1 or width > 16384 or height > 16384 or width % 1 ~= 0 or height % 1 ~= 0 then
+ return nil, Err.new(Err.ARG, "encode: size must be 1..16384")
+ end
+ if buffer.len(rgba) < width * height * 4 then
+ return nil, Err.new(Err.ARG, "encode: pixel buffer too small")
+ end
+ local o: EncodeOptions = opts or {} :: EncodeOptions
+ local effort = o.effort or 5
+ if type(effort) ~= "number" or effort < 0 or effort > 9 then
+ return nil, Err.new(Err.ARG, "encode: effort must be 0..9")
+ end
+ 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")
+ end
+ local rgba = buffer.create(width * height * 4)
+ for i = 0, width * height - 1 do
+ buffer.writeu32(rgba, i * 4, 0xff000000 + buffer.readu8(a8, i) * 256)
+ end
+ local effort = opts and opts.effort or 5
+ return Encode.encode(rgba, width, height, effort, true, false, true), nil
+end
+
+return Vp8L
diff --git a/src/Formats/codecs/Xml/Parse.luau b/src/Formats/codecs/Xml/Parse.luau
new file mode 100644
index 0000000..4a04ff3
--- /dev/null
+++ b/src/Formats/codecs/Xml/Parse.luau
@@ -0,0 +1,771 @@
+--!strict
+--!native
+-- codecs/Xml/Parse: the XML 1.0 pull parser behind codecs/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.
+local Types = require("@formats/Types")
+
+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)
+}
+
+local NAME = "^[%a_:\128-\255][%w_:%.%-\128-\255]*"
+local PREDEF: { [string]: string } = { lt = "<", gt = ">", amp = "&", quot = '"', apos = "'" }
+
+local function utf8char(c: number): string
+ if c < 0x80 then
+ return char(c)
+ elseif c < 0x800 then
+ return char(0xC0 + c // 64, 0x80 + c % 64)
+ elseif c < 0x10000 then
+ return char(0xE0 + c // 4096, 0x80 + (c // 64) % 64, 0x80 + c % 64)
+ end
+ return char(0xF0 + c // 262144, 0x80 + (c // 4096) % 64, 0x80 + (c // 64) % 64, 0x80 + c % 64)
+end
+Parse.utf8char = utf8char
+
+local CP1252: { [number]: number } = {
+ [0x80] = 0x20AC, [0x82] = 0x201A, [0x83] = 0x0192, [0x84] = 0x201E, [0x85] = 0x2026, [0x86] = 0x2020,
+ [0x87] = 0x2021, [0x88] = 0x02C6, [0x89] = 0x2030, [0x8A] = 0x0160, [0x8B] = 0x2039, [0x8C] = 0x0152,
+ [0x8E] = 0x017D, [0x91] = 0x2018, [0x92] = 0x2019, [0x93] = 0x201C, [0x94] = 0x201D, [0x95] = 0x2022,
+ [0x96] = 0x2013, [0x97] = 0x2014, [0x98] = 0x02DC, [0x99] = 0x2122, [0x9A] = 0x0161, [0x9B] = 0x203A,
+ [0x9C] = 0x0153, [0x9E] = 0x017E, [0x9F] = 0x0178,
+}
+
+local function utf16(s: string, start: number, le: boolean): (string?, string?)
+ local out = table.create(#s // 2)
+ local n = 0
+ local i = start
+ local len = #s
+ while i + 1 <= len do
+ local a, b = byte(s, i, i + 1)
+ local u = if le then a + b * 256 else a * 256 + b
+ i += 2
+ if u >= 0xD800 and u <= 0xDBFF then
+ if i + 1 > len then
+ return nil, "truncated UTF-16 surrogate pair"
+ end
+ local c, d = byte(s, i, i + 1)
+ local lo = if le then c + d * 256 else c * 256 + d
+ if lo < 0xDC00 or lo > 0xDFFF then
+ return nil, "bad UTF-16 surrogate pair"
+ end
+ i += 2
+ u = 0x10000 + (u - 0xD800) * 1024 + (lo - 0xDC00)
+ elseif u >= 0xDC00 and u <= 0xDFFF then
+ return nil, "bad UTF-16 surrogate pair"
+ end
+ n += 1
+ out[n] = utf8char(u)
+ end
+ if i <= len then
+ return nil, "odd number of bytes in UTF-16 text"
+ end
+ 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
+ return sub(s, 4), "utf-8"
+ elseif b1 == 0xFF and b2 == 0xFE then
+ local t, e = utf16(s, 3, true)
+ return t, e or "utf-16le"
+ elseif b1 == 0xFE and b2 == 0xFF then
+ local t, e = utf16(s, 3, false)
+ return t, e or "utf-16be"
+ elseif b1 == 0x3C and b2 == 0 then
+ local t, e = utf16(s, 1, true)
+ return t, e or "utf-16le"
+ elseif b1 == 0 and b2 == 0x3C then
+ local t, e = utf16(s, 1, false)
+ return t, e or "utf-16be"
+ end
+ local decl = match(s, "^<%?xml[^>]-%?>")
+ local enc = if decl then match(decl, "encoding%s*=%s*[\"']([%w%._%-]+)[\"']") else nil
+ if enc then
+ local e = lower(enc)
+ if e == "utf-8" or e == "utf8" or e == "us-ascii" or e == "ascii" then
+ if find(s, "[\128-\255]") and not utf8.len(s) then
+ return nil, "invalid UTF-8"
+ end
+ return s, e
+ elseif e == "iso-8859-1" or e == "latin1" or e == "latin-1" or e == "iso8859-1" or e == "windows-1252" or e == "cp1252" then
+ local w = e == "windows-1252" or e == "cp1252"
+ return (gsub(s, "[\128-\255]", function(c: string): string
+ local v = byte(c)
+ return utf8char(if w then CP1252[v] or v else v)
+ end)), e
+ elseif e == "utf-16" or e == "utf-16le" or e == "utf-16be" then
+ return s, "utf-8" -- declared UTF-16 but read as 8-bit text: trust the bytes
+ end
+ return nil, "unsupported encoding " .. enc
+ end
+ if find(s, "[\128-\255]") and not utf8.len(s) then
+ return nil, "invalid UTF-8"
+ end
+ return s, "utf-8"
+end
+
+-- the pseudo-attributes, strictly: version, then encoding?, then standalone?, each after whitespace
+local function xmlDecl(data: string): { [string]: string }?
+ local p = 1
+ local out: { [string]: string } = {}
+ for k, key in { "version", "encoding", "standalone" } do
+ local ws = match(data, "^[ \t\n]*()", p) :: any
+ 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
+ end
+ if (key == "version" and not match(v, "^1%.%d+$"))
+ or (key == "encoding" and not match(v, "^%a[%w%._%-]*$"))
+ or (key == "standalone" and v ~= "yes" and v ~= "no")
+ then
+ return nil
+ end
+ out[key] = v
+ p = e
+ elseif key == "version" then
+ return nil
+ end
+ end
+ if match(data, "^[ \t\n]*()", p) ~= #data + 1 then
+ return nil
+ end
+ 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
+ local nsOn = o.namespaces == true
+ local maxExp = o.maxExpansion or 1e7
+ local maxDepth = o.maxDepth or 10000
+ local entities: { [string]: string } = {}
+ if o.entities then
+ for k, v in o.entities do
+ entities[k] = v
+ end
+ end
+ local external: { [string]: boolean } = {}
+ local expanded = 0
+ if find(s, "\r", 1, true) then
+ s = gsub(gsub(s, "\r\n", "\n"), "\r", "\n")
+ end
+ local n = #s
+ local i = 1
+ local stack: { string } = {}
+ local nsStack: { { [string]: string } } = {}
+ local preserve: { boolean } = {}
+ local depth = 0
+ local rootSeen = false
+ local rootDone = false
+ local dead = false
+ local pending: { any }? = nil -- an "end" queued after a self-closing start
+ local errMsg: string? = nil
+ local errAt = 0
+
+ local function fail(msg: string, at: number): (string, string, number)
+ dead = true
+ 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
+ return raw
+ end
+ local parts = {}
+ local np = 0
+ local p = 1
+ while true do
+ local a = find(raw, "&", p, true)
+ if not a then
+ break
+ end
+ np += 1
+ parts[np] = sub(raw, p, a - 1)
+ local ref, e = match(raw, "^&([^;&%s<]*);()", a)
+ if not ref then
+ errMsg, errAt = "bad reference (no ';')", at + a - 1
+ return nil
+ end
+ local rep: string
+ if byte(ref) == 35 then -- #
+ local cp = if byte(ref, 2) == 120 then tonumber(match(ref, "^#x(%x+)$") or "", 16) else tonumber(match(ref, "^#(%d+)$") or "")
+ if not cp or cp > 0x10FFFF or (cp < 0x20 and cp ~= 9 and cp ~= 10 and cp ~= 13) or (cp >= 0xD800 and cp <= 0xDFFF) or cp == 0xFFFE or cp == 0xFFFF then
+ errMsg, errAt = "bad character reference &" .. ref .. ";", at + a - 1
+ return nil
+ end
+ rep = utf8char(cp)
+ else
+ local pre = PREDEF[ref]
+ if pre then
+ rep = pre
+ else
+ local ent = entities[ref]
+ if not ent then
+ errMsg = if external[ref] then "external entity &" .. ref .. "; not supported" else "undefined entity &" .. ref .. ";"
+ errAt = at + a - 1
+ return nil
+ end
+ if level > 40 then
+ errMsg, errAt = "entity references nested too deeply (recursive?)", at + a - 1
+ return nil
+ end
+ local r = decode(ent, at + a - 1, level + 1)
+ if not r then
+ return nil
+ end
+ rep = r
+ end
+ end
+ expanded += #rep
+ if expanded > maxExp then
+ errMsg, errAt = "entity expansion over the limit", at + a - 1
+ return nil
+ end
+ np += 1
+ parts[np] = rep
+ p = e :: any
+ end
+ np += 1
+ parts[np] = sub(raw, p)
+ return table.concat(parts)
+ end
+
+ local function lookupNs(prefix: string): string?
+ for d = depth, 1, -1 do
+ local m = nsStack[d]
+ if m and m[prefix] ~= nil then
+ return m[prefix]
+ end
+ end
+ if prefix == "xml" then
+ return "http://www.w3.org/XML/1998/namespace"
+ end
+ 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
+ return nil, p
+ end
+ local e = find(s, if q == 34 then '"' else "'", p + 1, true)
+ if not e then
+ return nil, p
+ end
+ return sub(s, p + 1, e - 1), e + 1
+ end
+ -- an ExternalID (SYSTEM "sys" | PUBLIC "pub" "sys") at p -> publicId, systemId, next | nil
+ local function externalId(p: number): (string?, string?, number?)
+ local kw = sub(s, p, p + 5)
+ if kw == "SYSTEM" then
+ local q = match(s, "^[ \t\n]+()", p + 6) :: any
+ if not q then
+ return nil
+ end
+ local sys, e = literal(q)
+ if not sys then
+ return nil
+ end
+ return "", sys, e
+ elseif kw == "PUBLIC" then
+ local q = match(s, "^[ \t\n]+()", p + 6) :: any
+ if not q then
+ return nil
+ end
+ local pub, e = literal(q)
+ if not pub or find(pub, "[^ \r\n%w%-'()+,./:=?;!*#@$_%%]") then
+ return nil
+ end
+ local r = match(s, "^[ \t\n]+()", e) :: any
+ if not r then
+ return nil
+ end
+ local sys, e2 = literal(r)
+ if not sys then
+ return nil
+ end
+ return pub, sys, e2
+ end
+ return 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
+ end
+ local p = 1
+ local parts = {}
+ while true do
+ local a = find(v, "&", p, true)
+ if not a then
+ table.insert(parts, sub(v, p))
+ break
+ end
+ table.insert(parts, sub(v, p, a - 1))
+ local hex = match(v, "^(%x+);", a)
+ local dec = match(v, "^(%d+);", a)
+ if hex or dec then
+ local cp = tonumber(hex or dec, if hex then 16 else 10) :: number
+ if cp > 0x10FFFF or (cp < 0x20 and cp ~= 9 and cp ~= 10 and cp ~= 13) or (cp >= 0xD800 and cp <= 0xDFFF) then
+ return nil
+ end
+ table.insert(parts, utf8char(cp))
+ p = (find(v, ";", a, true) :: number) + 1
+ else
+ local name = match(v, "^&([%a_:\128-\255][%w_:%.%-\128-\255]*);", a)
+ if not name then
+ return nil
+ end
+ table.insert(parts, "&" .. name .. ";")
+ p = a + #name + 2
+ end
+ end
+ return table.concat(parts)
+ end
+ -- the DOCTYPE at i (just past " p and (sub(s, q, q + 5) == "SYSTEM" or sub(s, q, q + 5) == "PUBLIC") then
+ local pub, sys, e = externalId(q)
+ if not pub then
+ return nil, "bad DOCTYPE external id"
+ end
+ info.publicId = if pub ~= "" then pub else nil
+ info.systemId = sys
+ q = match(s, "^[ \t\n]*()", e) :: any
+ end
+ if byte(s, q) == 91 then -- the internal subset
+ q += 1
+ while true do
+ q = match(s, "^[ \t\n]*()", q) :: any
+ local c = byte(s, q)
+ if c == 93 then
+ q += 1
+ break
+ elseif c == 37 then -- %name;
+ local pe = match(s, "^%%[%a_:\128-\255][%w_:%.%-\128-\255]*;()", q)
+ if not pe then
+ return nil, "bad parameter-entity reference"
+ end
+ q = pe :: any
+ elseif sub(s, q, q + 3) == "")
+ elseif name == "#cdata" then
+ table.insert(out, "", "]]]]>") .. "]]>")
+ elseif name == "#pi" then
+ if badName(n.target) or find(n.text or "", "?>", 1, true) then
+ err = "bad processing instruction"
+ return
+ end
+ table.insert(out, "" .. n.target .. (if n.text and n.text ~= "" then " " .. n.text else "") .. "?>")
+ elseif name == "#doctype" then
+ table.insert(out, "")
+ elseif name == "#document" then
+ for i, ch in n.children do
+ if i > 1 and ind then
+ table.insert(out, "\n")
+ end
+ write(ch, 0)
+ end
+ else
+ if badName(name) then
+ err = "bad element name " .. tostring(name)
+ return
+ end
+ table.insert(out, "<" .. name)
+ local attrs = n.attrs or {}
+ for _, k in Types.keys(attrs) do
+ local v = attrs[k]
+ if badName(k) then
+ err = "bad attribute name " .. tostring(k)
+ return
+ end
+ if type(v) == "number" or type(v) == "boolean" then
+ v = tostring(v)
+ elseif type(v) ~= "string" then
+ err = "attribute " .. k .. " is not a string"
+ return
+ end
+ table.insert(out, " " .. k .. '="' .. Xml.escapeAttr(v) .. '"')
+ end
+ local ch = n.children or {}
+ if #ch == 0 then
+ table.insert(out, if selfClose then "/>" else ">" .. name .. ">")
+ return
+ end
+ table.insert(out, ">")
+ local pretty = ind ~= nil
+ if pretty then
+ for _, c in ch do
+ if type(c) == "string" or c.name == "#cdata" then
+ pretty = false
+ break
+ end
+ end
+ end
+ for _, c in ch do
+ if pretty then
+ table.insert(out, "\n" .. string.rep(ind :: string, depth + 1))
+ end
+ write(c, depth + 1)
+ end
+ if pretty then
+ table.insert(out, "\n" .. string.rep(ind :: string, depth))
+ end
+ table.insert(out, "" .. name .. ">")
+ end
+ end
+
+ local decl = o.declaration
+ if decl == nil then
+ decl = node.name == "#document"
+ end
+ if decl then
+ local d: any = node.declaration or {}
+ table.insert(out, '")
+ table.insert(out, "\n")
+ end
+ if node.name == "#document" and node.doctype then
+ local dt: any = node.doctype
+ local raw = dt.raw
+ if raw == nil then
+ raw = " " .. (dt.name or (if node.root then node.root.name else "root"))
+ if dt.publicId then
+ raw ..= ' PUBLIC "' .. dt.publicId .. '" "' .. (dt.systemId or "") .. '"'
+ elseif dt.systemId then
+ raw ..= ' SYSTEM "' .. dt.systemId .. '"'
+ end
+ end
+ table.insert(out, "\n")
+ end
+ write(node, 0)
+ if err then
+ return nil, Err.new(Err.ARG, err)
+ end
+ if ind and node.name == "#document" then
+ table.insert(out, "\n")
+ end
+ return table.concat(out), nil
+end
+
+return Xml
diff --git a/src/Formats/codecs/Zstd/Decode.luau b/src/Formats/codecs/Zstd/Decode.luau
new file mode 100644
index 0000000..7ad77d5
--- /dev/null
+++ b/src/Formats/codecs/Zstd/Decode.luau
@@ -0,0 +1,980 @@
+--!strict
+--!native
+--!optimize 2
+-- codecs/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.
+local Xxh64 = require("@formats/codecs/Zstd/Xxh64")
+
+local band, lshift, rshift = bit32.band, bit32.lshift, bit32.rshift
+local readu8, readu16, readu32, writeu8, writeu16, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu16, buffer.writeu32
+local bcreate, bcopy, bfill, blen = buffer.create, buffer.copy, buffer.fill, buffer.len
+
+local MAGIC = 0xFD2FB528
+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 }
+local ML_BASE = {
+ 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, 29, 30, 31, 32, 33, 34,
+ 35, 37, 39, 41, 43, 47, 51, 59, 67, 83, 99, 131, 259, 515, 1027, 2051, 4099, 8195, 16387, 32771, 65539,
+}
+local ML_BITS = {
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
+}
+local LL_DEFAULT = { 4, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 2, 1, 1, 1, 1, 1, -1, -1, -1, -1 }
+local ML_DEFAULT = {
+ 1, 4, 3, 2, 2, 2, 2, 2, 2, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1,
+}
+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
+ for i = 1, 2048 do
+ if i >= lshift(2, v) then
+ v += 1
+ end
+ HB[i] = v
+ 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
+ end
+ local lo = o - n
+ if lo >= 0 then
+ local byte = s + rshift(lo, 3)
+ local bl = blen(b)
+ if byte + 4 <= bl then
+ return band(rshift(readu32(b, byte), band(lo, 7)), lshift(1, n) - 1)
+ end
+ local v = 0
+ local m = 1
+ for k = 0, 3 do
+ if byte + k < bl then
+ v += readu8(b, byte + k) * m
+ end
+ m *= 256
+ end
+ return band(rshift(v, band(lo, 7)), lshift(1, n) - 1)
+ end
+ if o <= 0 then
+ return 0
+ end
+ 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
+ end
+ local last = readu8(b, e - 1)
+ if last == 0 then
+ return -1
+ end
+ 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
+ local m = 1
+ for k = 0, 3 do
+ if byte + k < e then
+ v += readu8(b, byte + k) * m
+ end
+ m *= 256
+ end
+ 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") }
+local function buildFse(norm: { number }, nsym: number, al: number, t: buffer): (boolean?, string?)
+ local size = lshift(1, al)
+ local high = size - 1
+ local next = table.create(nsym, 0)
+ for s = 0, nsym - 1 do
+ local c = norm[s + 1]
+ if c == -1 then
+ if high < 0 then
+ return nil, "bad FSE distribution"
+ end
+ writeu8(symTmp, high, s)
+ high -= 1
+ next[s + 1] = 1
+ else
+ next[s + 1] = c
+ end
+ end
+ local pos = 0
+ local step = rshift(size, 1) + rshift(size, 3) + 3
+ local mask = size - 1
+ for s = 0, nsym - 1 do
+ local c = norm[s + 1]
+ for _ = 1, c do
+ writeu8(symTmp, pos, s)
+ local guard = 0
+ repeat
+ pos = band(pos + step, mask)
+ guard += 1
+ until pos <= high or guard > size
+ if guard > size then
+ return nil, "bad FSE distribution"
+ end
+ end
+ end
+ if pos ~= 0 then
+ return nil, "bad FSE distribution"
+ end
+ for u = 0, size - 1 do
+ local s = readu8(symTmp, u)
+ local ns = next[s + 1]
+ if ns < 1 or ns > 2048 then
+ return nil, "bad FSE distribution"
+ end
+ next[s + 1] = ns + 1
+ local nb = al - HB[ns]
+ if nb < 0 then
+ return nil, "bad FSE distribution"
+ end
+ writeu32(t, u * 4, s + nb * 256 + (lshift(ns, nb) - size) * 65536)
+ end
+ 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"
+ end
+ local al = getF(b, p, e, 0, 4) + 5
+ if al > maxAL then
+ return nil, "FSE accuracy log too large"
+ end
+ local bp = 4
+ local remaining = lshift(1, al) + 1
+ local threshold = lshift(1, al)
+ local nbBits = al + 1
+ local sym = 0
+ local prev0 = false
+ while remaining > 1 and sym <= maxSym do
+ if prev0 then
+ local n0 = sym
+ while true do
+ local v = getF(b, p, e, bp, 2)
+ bp += 2
+ if v == 3 then
+ n0 += 3
+ if n0 > maxSym or bp > (e - p) * 8 then
+ return nil, "bad FSE table"
+ end
+ else
+ n0 += v
+ break
+ end
+ end
+ if n0 > maxSym then
+ return nil, "bad FSE table"
+ end
+ while sym < n0 do
+ norm[sym + 1] = 0
+ sym += 1
+ end
+ end
+ local max = 2 * threshold - 1 - remaining
+ local count
+ local low = getF(b, p, e, bp, nbBits - 1)
+ if low < max then
+ count = low
+ bp += nbBits - 1
+ else
+ count = getF(b, p, e, bp, nbBits)
+ if count >= threshold then
+ count -= max
+ end
+ bp += nbBits
+ end
+ count -= 1
+ remaining -= if count < 0 then -count else count
+ if remaining < 1 then
+ return nil, "bad FSE table"
+ end
+ norm[sym + 1] = count
+ sym += 1
+ prev0 = count == 0
+ while remaining < threshold do
+ nbBits -= 1
+ threshold = rshift(threshold, 1)
+ end
+ end
+ if remaining ~= 1 then
+ return nil, "bad FSE table"
+ end
+ local used = rshift(bp + 7, 3)
+ if p + used > e then
+ return nil, "truncated FSE table"
+ end
+ for s = sym, maxSym do
+ norm[s + 1] = 0
+ end
+ return al, used, sym
+end
+
+local function predefined(dist: { number }, al: number): buffer
+ local t = bcreate(lshift(1, al) * 4)
+ buildFse(dist, #dist, al, t)
+ return t
+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)
+local weights = bcreate(256)
+local wfse = bcreate(64 * 4)
+local function hufTable(b: buffer, p: number, e: number, st: any): (number?, string?)
+ if p >= e then
+ return nil, "truncated Huffman table"
+ end
+ local hdr = readu8(b, p)
+ local n = 0
+ local used
+ if hdr >= 128 then
+ n = hdr - 127
+ used = 1 + rshift(n + 1, 1)
+ if p + used > e then
+ return nil, "truncated Huffman table"
+ end
+ for i = 0, n - 1 do
+ local byte = readu8(b, p + 1 + rshift(i, 1))
+ writeu8(weights, i, if band(i, 1) == 0 then rshift(byte, 4) else band(byte, 15))
+ end
+ else
+ used = 1 + hdr
+ if p + used > e then
+ return nil, "truncated Huffman table"
+ end
+ local q, qe = p + 1, p + 1 + hdr
+ local norm = st.norm
+ local al, nb = ncount(b, q, qe, 255, 6, norm)
+ if not al then
+ return nil, nb
+ end
+ local ok, msg = buildFse(norm, 256, al, wfse)
+ if not ok then
+ return nil, msg
+ end
+ local ss = q + nb
+ local off = streamBits(b, ss, qe)
+ if off < 0 then
+ return nil, "bad Huffman weight stream"
+ end
+ local s1 = peek(b, ss, off, al)
+ off -= al
+ local s2 = peek(b, ss, off, al)
+ off -= al
+ while true do
+ if n > 254 then
+ return nil, "too many Huffman weights"
+ end
+ local e1 = readu32(wfse, s1 * 4)
+ writeu8(weights, n, band(e1, 255))
+ n += 1
+ local k = band(rshift(e1, 8), 255)
+ s1 = rshift(e1, 16) + peek(b, ss, off, k)
+ off -= k
+ if off < 0 then
+ writeu8(weights, n, band(readu32(wfse, s2 * 4), 255))
+ n += 1
+ break
+ end
+ local e2 = readu32(wfse, s2 * 4)
+ writeu8(weights, n, band(e2, 255))
+ n += 1
+ k = band(rshift(e2, 8), 255)
+ s2 = rshift(e2, 16) + peek(b, ss, off, k)
+ off -= k
+ if off < 0 then
+ writeu8(weights, n, band(readu32(wfse, s1 * 4), 255))
+ n += 1
+ break
+ end
+ end
+ end
+ -- the last weight is implied: the total must reach the next power of two
+ local total = 0
+ for i = 0, n - 1 do
+ local w = readu8(weights, i)
+ if w > 11 then
+ return nil, "bad Huffman weight"
+ end
+ if w > 0 then
+ total += lshift(1, w - 1)
+ end
+ end
+ if total == 0 or total >= 2048 then
+ return nil, "bad Huffman weights"
+ end
+ local maxBits = HB[total] + 1
+ local rest = lshift(1, maxBits) - total
+ if band(rest, rest - 1) ~= 0 then
+ return nil, "bad Huffman weights"
+ end
+ writeu8(weights, n, HB[rest] + 1)
+ local nsym = n + 1
+ -- codes: the longest first, in symbol order within a length
+ local rankCount = table.create(13, 0)
+ for i = 0, nsym - 1 do
+ local w = readu8(weights, i)
+ if w > 0 then
+ local bits = maxBits + 1 - w
+ rankCount[bits + 1] += 1
+ end
+ end
+ local rankIdx = table.create(13, 0)
+ rankIdx[maxBits + 1] = 0
+ for i = maxBits, 1, -1 do
+ rankIdx[i] = rankIdx[i + 1] + rankCount[i + 1] * lshift(1, maxBits - i)
+ end
+ if rankIdx[1] ~= lshift(1, maxBits) then
+ return nil, "bad Huffman weights"
+ end
+ local t = st.huf
+ for i = 0, nsym - 1 do
+ local w = readu8(weights, i)
+ if w > 0 then
+ local bits = maxBits + 1 - w
+ local code = rankIdx[bits + 1]
+ local len = lshift(1, maxBits - bits)
+ local v = i + bits * 256
+ for k = code, code + len - 1 do
+ writeu16(t, k * 2, v)
+ end
+ rankIdx[bits + 1] = code + len
+ end
+ end
+ st.hufBits = maxBits
+ 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
+ return "bad Huffman stream"
+ end
+ local mmask = lshift(1, mb) - 1
+ local fastEnd = blen(b) - 4
+ for k = dp, dp + cnt - 1 do
+ local lo = off - mb
+ local idx
+ if lo >= 0 then
+ local byte = s + rshift(lo, 3)
+ if byte <= fastEnd then
+ idx = band(rshift(readu32(b, byte), band(lo, 7)), mmask)
+ else
+ idx = peek(b, s, off, mb)
+ end
+ else
+ idx = peek(b, s, off, mb)
+ end
+ local v = readu16(t, idx * 2)
+ writeu8(lit, k, v)
+ off -= rshift(v, 8)
+ end
+ if off ~= 0 then
+ return "Huffman stream size mismatch"
+ end
+ 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
+ end
+ local cap = math.min(st.maxBytes, math.max(blen(st.out) * 2, need, 65536))
+ local nb = bcreate(cap)
+ bcopy(nb, 0, st.out, 0, st.op)
+ st.out = nb
+ 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)
+ local ltype = band(b0, 3)
+ local sf = band(rshift(b0, 2), 3)
+ local regen
+ local litSrc, litPos
+ local lit = st.lit
+ if ltype <= 1 then
+ if sf == 0 or sf == 2 then
+ regen = rshift(b0, 3)
+ p += 1
+ elseif sf == 1 then
+ if p + 2 > e then
+ return "TRUNCATED", "truncated literals header"
+ end
+ regen = rshift(b0, 4) + readu8(b, p + 1) * 16
+ p += 2
+ else
+ if p + 3 > e then
+ return "TRUNCATED", "truncated literals header"
+ end
+ regen = rshift(b0, 4) + readu8(b, p + 1) * 16 + readu8(b, p + 2) * 4096
+ p += 3
+ end
+ if regen > BLOCK_MAX then
+ return "CORRUPT", "literals too large"
+ end
+ if ltype == 0 then
+ if p + regen > e then
+ return "TRUNCATED", "truncated raw literals"
+ end
+ litSrc, litPos = b, p
+ p += regen
+ else
+ if p + 1 > e then
+ return "TRUNCATED", "truncated RLE literals"
+ end
+ bfill(lit, 0, readu8(b, p), regen)
+ litSrc, litPos = lit, 0
+ p += 1
+ end
+ else
+ local csize
+ if sf <= 1 then
+ if p + 3 > e then
+ return "TRUNCATED", "truncated literals header"
+ end
+ local v = b0 + readu8(b, p + 1) * 256 + readu8(b, p + 2) * 65536
+ regen = band(rshift(v, 4), 0x3FF)
+ csize = band(rshift(v, 14), 0x3FF)
+ p += 3
+ elseif sf == 2 then
+ if p + 4 > e then
+ return "TRUNCATED", "truncated literals header"
+ end
+ local v = readu32(b, p)
+ regen = band(rshift(v, 4), 0x3FFF)
+ csize = rshift(v, 18)
+ p += 4
+ else
+ if p + 5 > e then
+ return "TRUNCATED", "truncated literals header"
+ end
+ local v = readu32(b, p)
+ regen = band(rshift(v, 4), 0x3FFFF)
+ csize = rshift(v, 22) + readu8(b, p + 4) * 1024
+ p += 5
+ end
+ if regen > BLOCK_MAX then
+ return "CORRUPT", "literals too large"
+ end
+ if p + csize > e then
+ return "TRUNCATED", "truncated compressed literals"
+ end
+ local hs, he = p, p + csize
+ p = he
+ if ltype == 2 then
+ local used, herr = hufTable(b, hs, he, st)
+ if not used then
+ return "CORRUPT", herr
+ end
+ hs += used
+ elseif not st.hufBits then
+ return "CORRUPT", "treeless literals without a previous Huffman table"
+ end
+ local t, mb = st.huf, st.hufBits
+ if sf == 0 then
+ local herr = hufStream(b, hs, he, t, mb, lit, 0, regen)
+ if herr then
+ return "CORRUPT", herr
+ end
+ else
+ if hs + 6 > he then
+ return "CORRUPT", "truncated jump table"
+ end
+ local l1, l2, l3 = readu16(b, hs), readu16(b, hs + 2), readu16(b, hs + 4)
+ local s1 = hs + 6
+ local s2 = s1 + l1
+ local s3 = s2 + l2
+ local s4 = s3 + l3
+ if s4 > he then
+ return "CORRUPT", "bad jump table"
+ end
+ local seg = rshift(regen + 3, 2)
+ local last = regen - 3 * seg
+ if last < 0 then
+ return "CORRUPT", "bad 4-stream literals size"
+ end
+ local herr = hufStream(b, s1, s2, t, mb, lit, 0, seg)
+ or hufStream(b, s2, s3, t, mb, lit, seg, seg)
+ or hufStream(b, s3, s4, t, mb, lit, 2 * seg, seg)
+ or hufStream(b, s4, he, t, mb, lit, 3 * seg, last)
+ if herr then
+ return "CORRUPT", herr
+ end
+ end
+ litSrc, litPos = lit, 0
+ end
+
+ -- sequences section header
+ if p >= e then
+ return "TRUNCATED", "missing sequences header"
+ end
+ local nbSeq = readu8(b, p)
+ p += 1
+ if nbSeq >= 128 then
+ if nbSeq == 255 then
+ if p + 2 > e then
+ return "TRUNCATED", "truncated sequences header"
+ end
+ nbSeq = readu16(b, p) + 0x7F00
+ p += 2
+ else
+ if p + 1 > e then
+ return "TRUNCATED", "truncated sequences header"
+ end
+ nbSeq = (nbSeq - 128) * 256 + readu8(b, p)
+ p += 1
+ end
+ end
+ local op = st.op
+ if nbSeq == 0 then
+ if p ~= e then
+ return "CORRUPT", "data after an empty sequences section"
+ end
+ if op + regen > blen(st.out) then
+ if not grow(st, op + regen) then
+ return "LIMIT", "output over the size limit"
+ end
+ end
+ bcopy(st.out, op, litSrc, litPos, regen)
+ st.op = op + regen
+ return nil, nil
+ end
+ if p >= e then
+ return "TRUNCATED", "missing compression modes"
+ end
+ local modes = readu8(b, p)
+ p += 1
+ if band(modes, 3) ~= 0 then
+ return "CORRUPT", "reserved bits set in compression modes"
+ end
+ -- the three tables, in the order LL, OF, ML
+ local tabs = st.tabs
+ for k = 1, 3 do
+ local mode = band(rshift(modes, 8 - 2 * k), 3)
+ local maxSym = if k == 1 then 35 elseif k == 2 then 31 else 52
+ local maxAL = if k == 1 then 9 elseif k == 2 then 8 else 9
+ if mode == 0 then
+ tabs[k] = if k == 1 then LL_PRE elseif k == 2 then OF_PRE else ML_PRE
+ tabs[k + 3] = if k == 2 then 5 else 6
+ elseif mode == 1 then
+ if p >= e then
+ return "TRUNCATED", "truncated RLE table"
+ end
+ local sym = readu8(b, p)
+ p += 1
+ if sym > maxSym then
+ return "CORRUPT", "bad RLE symbol"
+ end
+ local t = st.rle[k]
+ writeu32(t, 0, sym)
+ tabs[k] = t
+ tabs[k + 3] = 0
+ elseif mode == 2 then
+ local norm = st.norm
+ local al, used, nsym = ncount(b, p, e, maxSym, maxAL, norm)
+ if not al then
+ return "CORRUPT", used
+ end
+ p += used
+ local t = st.dyn[k]
+ local ok, msg = buildFse(norm, nsym :: number, al, t)
+ if not ok then
+ return "CORRUPT", msg
+ end
+ tabs[k] = t
+ tabs[k + 3] = al
+ else
+ if not tabs[k] then
+ return "CORRUPT", "repeated table without a previous one"
+ end
+ end
+ end
+ local llT, ofT, mlT = tabs[1] :: buffer, tabs[2] :: buffer, tabs[3] :: buffer
+ local llAL, ofAL, mlAL = tabs[4] :: number, tabs[5] :: number, tabs[6] :: number
+
+ -- the sequences bitstream
+ local s = p
+ local off = streamBits(b, s, e)
+ if off < 0 then
+ return "CORRUPT", "bad sequences bitstream"
+ end
+ local llS = peek(b, s, off, llAL)
+ off -= llAL
+ local ofS = peek(b, s, off, ofAL)
+ off -= ofAL
+ local mlS = peek(b, s, off, mlAL)
+ off -= mlAL
+ local rep1, rep2, rep3 = st.rep1, st.rep2, st.rep3
+ local out = st.out
+ local cap = blen(out)
+ local frameStart = st.frameStart
+ local lp, litEnd = litPos, litPos + regen
+ local fastEnd = blen(b) - 4
+ for i = 1, nbSeq do
+ local ofE, llE, mlE = readu32(ofT, ofS * 4), readu32(llT, llS * 4), readu32(mlT, mlS * 4)
+ local ofCode = band(ofE, 255)
+ local mlCode = band(mlE, 255) + 1
+ local llCode = band(llE, 255) + 1
+ -- offset bits, then match length bits, then literal length bits
+ local ofv
+ if ofCode > 24 then
+ local hiN = ofCode - 24
+ local hi = peek(b, s, off, hiN)
+ off -= hiN
+ ofv = lshift(1, ofCode) + hi * 16777216 + peek(b, s, off, 24)
+ off -= 24
+ elseif ofCode > 0 then
+ local lo = off - ofCode
+ local v
+ if lo >= 0 and s + rshift(lo, 3) <= fastEnd then
+ v = band(rshift(readu32(b, s + rshift(lo, 3)), band(lo, 7)), lshift(1, ofCode) - 1)
+ else
+ v = peek(b, s, off, ofCode)
+ end
+ off = lo
+ ofv = lshift(1, ofCode) + v
+ else
+ ofv = 1
+ end
+ local ml = ML_BASE[mlCode]
+ local nb = ML_BITS[mlCode]
+ if nb > 0 then
+ ml += peek(b, s, off, nb)
+ off -= nb
+ end
+ local ll = LL_BASE[llCode]
+ nb = LL_BITS[llCode]
+ if nb > 0 then
+ ll += peek(b, s, off, nb)
+ off -= nb
+ end
+ -- repeat offsets
+ local offset
+ if ofv > 3 then
+ offset = ofv - 3
+ rep3 = rep2
+ rep2 = rep1
+ rep1 = offset
+ else
+ local idx = ofv - 1
+ if ll == 0 then
+ idx += 1
+ end
+ if idx == 0 then
+ offset = rep1
+ else
+ if idx == 1 then
+ offset = rep2
+ elseif idx == 2 then
+ offset = rep3
+ else
+ offset = rep1 - 1
+ end
+ if idx > 1 then
+ rep3 = rep2
+ end
+ rep2 = rep1
+ rep1 = offset
+ end
+ end
+ -- state updates (not after the last sequence): LL, ML, OF
+ if i < nbSeq then
+ nb = band(rshift(llE, 8), 255)
+ llS = rshift(llE, 16) + peek(b, s, off, nb)
+ off -= nb
+ nb = band(rshift(mlE, 8), 255)
+ mlS = rshift(mlE, 16) + peek(b, s, off, nb)
+ off -= nb
+ nb = band(rshift(ofE, 8), 255)
+ ofS = rshift(ofE, 16) + peek(b, s, off, nb)
+ off -= nb
+ end
+ -- execute
+ if lp + ll > litEnd then
+ return "CORRUPT", "literal length past the literals"
+ end
+ local need = op + ll + ml
+ if need > cap then
+ st.op = op
+ if not grow(st, need) then
+ return "LIMIT", "output over the size limit"
+ end
+ out = st.out
+ cap = blen(out)
+ end
+ if ll > 0 then
+ bcopy(out, op, litSrc, lp, ll)
+ op += ll
+ lp += ll
+ end
+ if offset > op - frameStart or offset < 1 then
+ return "CORRUPT", "match offset before the frame start"
+ end
+ local from = op - offset
+ if offset >= ml then
+ bcopy(out, op, out, from, ml)
+ op += ml
+ elseif offset == 1 then
+ 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
+ bcopy(out, op, out, from, n)
+ op += n
+ from += n
+ left -= n
+ end
+ end
+ end
+ if off ~= 0 then
+ return "CORRUPT", "sequences bitstream size mismatch"
+ end
+ local rest = litEnd - lp
+ if rest > 0 then
+ if op + rest > cap then
+ st.op = op
+ if not grow(st, op + rest) then
+ return "LIMIT", "output over the size limit"
+ end
+ out = st.out
+ end
+ bcopy(out, op, litSrc, lp, rest)
+ op += rest
+ end
+ st.op = op
+ st.rep1, st.rep2, st.rep3 = rep1, rep2, rep3
+ 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))),
+ op = 0,
+ maxBytes = maxBytes,
+ lit = bcreate(BLOCK_MAX + 64),
+ huf = bcreate(2048 * 2),
+ hufBits = nil,
+ norm = table.create(256, 0),
+ tabs = {},
+ rle = { bcreate(4), bcreate(4), bcreate(4) },
+ dyn = { bcreate(512 * 4), bcreate(256 * 4), bcreate(512 * 4) },
+ frameStart = 0,
+ rep1 = 1,
+ rep2 = 4,
+ rep3 = 8,
+ }
+ local pos = start
+ local frames = 0
+ if stop - start < 4 then
+ return nil, "TRUNCATED", "not a zstd stream (too short)", start
+ end
+ while pos < stop do
+ if pos + 4 > stop then
+ return nil, "TRUNCATED", "truncated frame magic", pos
+ end
+ local magic = readu32(b, pos)
+ if band(magic, 0xFFFFFFF0) == 0x184D2A50 then
+ if pos + 8 > stop then
+ return nil, "TRUNCATED", "truncated skippable frame", pos
+ end
+ local size = readu32(b, pos + 4)
+ if pos + 8 + size > stop then
+ return nil, "TRUNCATED", "truncated skippable frame", pos
+ end
+ pos += 8 + size
+ frames += 1
+ continue
+ end
+ if magic ~= MAGIC then
+ return nil, "CORRUPT", if frames == 0 then "bad magic" else "unknown data after frame " .. frames, pos
+ end
+ pos += 4
+ if pos + 1 > stop then
+ return nil, "TRUNCATED", "truncated frame header", pos
+ end
+ local fhd = readu8(b, pos)
+ pos += 1
+ local fcsFlag = rshift(fhd, 6)
+ local single = band(fhd, 0x20) ~= 0
+ if band(fhd, 8) ~= 0 then
+ return nil, "CORRUPT", "reserved frame header bit set", pos - 1
+ end
+ local checksum = band(fhd, 4) ~= 0
+ local didFlag = band(fhd, 3)
+ local didSize = if didFlag == 3 then 4 else didFlag
+ local fcsSize = if fcsFlag == 0 then (if single then 1 else 0) else lshift(1, fcsFlag)
+ local hsize = (if single then 0 else 1) + didSize + fcsSize
+ if pos + hsize > stop then
+ return nil, "TRUNCATED", "truncated frame header", pos
+ end
+ local windowSize = 0
+ if not single then
+ local wd = readu8(b, pos)
+ pos += 1
+ local wlog = 10 + rshift(wd, 3)
+ if wlog > 41 then
+ return nil, "CORRUPT", "bad window size", pos - 1
+ end
+ local base = 2 ^ wlog
+ windowSize = base + base / 8 * band(wd, 7)
+ end
+ local did = 0
+ if didSize == 1 then
+ did = readu8(b, pos)
+ elseif didSize == 2 then
+ did = readu16(b, pos)
+ elseif didSize == 4 then
+ did = readu32(b, pos)
+ end
+ pos += didSize
+ if did ~= 0 then
+ return nil, "UNSUPPORTED", "dictionaries are not supported (dictionary " .. did .. ")", pos - didSize
+ end
+ local fcs = -1
+ if fcsSize == 1 then
+ fcs = readu8(b, pos)
+ elseif fcsSize == 2 then
+ fcs = readu16(b, pos) + 256
+ elseif fcsSize == 4 then
+ fcs = readu32(b, pos)
+ elseif fcsSize == 8 then
+ fcs = readu32(b, pos) + readu32(b, pos + 4) * 4294967296
+ end
+ pos += fcsSize
+ if single then
+ windowSize = fcs
+ end
+ local blockMax = math.min(windowSize, BLOCK_MAX)
+ local frameStart = st.op
+ if fcs >= 0 then
+ if frameStart + fcs > st.maxBytes then
+ return nil, "LIMIT", string.format("frame content size %d is over the %d byte limit", fcs, st.maxBytes), pos
+ end
+ if frameStart + fcs > blen(st.out) then
+ grow(st, frameStart + fcs)
+ end
+ end
+ st.frameStart = frameStart
+ 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
+ return nil, "TRUNCATED", "truncated block header", pos
+ end
+ local bh = readu16(b, pos) + readu8(b, pos + 2) * 65536
+ last = band(bh, 1) ~= 0
+ local btype = band(rshift(bh, 1), 3)
+ local bsize = rshift(bh, 3)
+ pos += 3
+ if bsize > blockMax then
+ return nil, "CORRUPT", "block larger than the maximum block size", pos - 3
+ end
+ if btype == 0 then
+ if pos + bsize > stop then
+ return nil, "TRUNCATED", "truncated raw block", pos
+ end
+ if st.op + bsize > blen(st.out) and not grow(st, st.op + bsize) then
+ return nil, "LIMIT", "output over the size limit", pos
+ end
+ bcopy(st.out, st.op, b, pos, bsize)
+ st.op += bsize
+ pos += bsize
+ elseif btype == 1 then
+ if pos + 1 > stop then
+ return nil, "TRUNCATED", "truncated RLE block", pos
+ end
+ if st.op + bsize > blen(st.out) and not grow(st, st.op + bsize) then
+ return nil, "LIMIT", "output over the size limit", pos
+ end
+ bfill(st.out, st.op, readu8(b, pos), bsize)
+ st.op += bsize
+ pos += 1
+ elseif btype == 2 then
+ if pos + bsize > stop then
+ return nil, "TRUNCATED", "truncated compressed block", pos
+ end
+ if bsize == 0 then
+ return nil, "CORRUPT", "empty compressed block", pos
+ end
+ local code, msg = block(b, pos, pos + bsize, st)
+ if code then
+ return nil, code, msg, pos
+ end
+ pos += bsize
+ else
+ return nil, "CORRUPT", "reserved block type", pos - 3
+ end
+ until last
+ local size = st.op - frameStart
+ if fcs >= 0 and size ~= fcs then
+ return nil, "CORRUPT", string.format("frame decoded to %d bytes, header says %d", size, fcs), pos
+ end
+ if checksum then
+ if pos + 4 > stop then
+ return nil, "TRUNCATED", "missing content checksum", pos
+ end
+ if verify then
+ local _, lo = Xxh64.hash(st.out, frameStart, size)
+ local want = readu32(b, pos)
+ if lo ~= want then
+ return nil, "CHECKSUM", string.format("content checksum mismatch (%08x, expected %08x)", lo, want), pos
+ end
+ end
+ pos += 4
+ end
+ frames += 1
+ end
+ return st.out, st.op, pos
+end
+
+Decode.hash = Xxh64.hash
+
+return Decode
diff --git a/src/Formats/codecs/Zstd/Xxh64.luau b/src/Formats/codecs/Zstd/Xxh64.luau
new file mode 100644
index 0000000..5aa48e8
--- /dev/null
+++ b/src/Formats/codecs/Zstd/Xxh64.luau
@@ -0,0 +1,155 @@
+--!strict
+--!native
+--!optimize 2
+-- codecs/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).
+local bor, bxor, lshift, rshift = bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift
+local readu8, readu32 = buffer.readu8, buffer.readu32
+
+local T32 = 4294967296
+
+local P1H, P1L = 0x9E3779B1, 0x85EBCA87
+local P2H, P2L = 0xC2B2AE3D, 0x27D4EB4F
+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
+ local b0 = bl % 65536
+ local b1 = (bl - b0) / 65536
+ local mid = a1 * b0 + a0 * b1
+ local mid0 = mid % 65536
+ local lo = a0 * b0 + mid0 * 65536
+ local lo32 = lo % T32
+ local hi = a1 * b1 + (mid - mid0) / 65536 + (lo - lo32) / T32
+ hi += (a0 * bh + ((a1 * bh) % 65536) * 65536) + (b0 * ah + ((b1 * ah) % 65536) * 65536)
+ return hi % T32, lo32
+end
+
+local function add(ah: number, al: number, bh: number, bl: number): (number, number)
+ local l = al + bl
+ local h = ah + bh
+ if l >= T32 then
+ l -= T32
+ h += 1
+ end
+ 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
+
+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)
+local function round(ah: number, al: number, ih: number, il: number): (number, number)
+ local a0 = il % 65536
+ local a1 = (il - a0) / 65536
+ local mid = a1 * P2L0 + a0 * P2L1
+ local mid0 = mid % 65536
+ local lo = a0 * P2L0 + mid0 * 65536
+ local ml = lo % T32
+ local mh = a1 * P2L1 + (mid - mid0) / 65536 + (lo - ml) / T32 + a0 * P2H + ((a1 * P2H) % 65536) * 65536 + P2L0 * ih + ((P2L1 * ih) % 65536) * 65536
+ local l = al + ml
+ local h = ah + mh
+ if l >= T32 then
+ l -= T32
+ h += 1
+ end
+ h %= T32
+ -- rotl 31 = rotr 1, in arithmetic (cheaper than bit32 calls on LuaJIT)
+ local hb, lb = h % 2, l % 2
+ local rh, rl = hb * 2147483648 + (l - lb) / 2, lb * 2147483648 + (h - hb) / 2
+ a0 = rl % 65536
+ a1 = (rl - a0) / 65536
+ mid = a1 * P1L0 + a0 * P1L1
+ mid0 = mid % 65536
+ lo = a0 * P1L0 + mid0 * 65536
+ ml = lo % T32
+ mh = a1 * P1L1 + (mid - mid0) / 65536 + (lo - ml) / T32 + a0 * P1H + ((a1 * P1H) % 65536) * 65536 + P1L0 * rh + ((P1L1 * rh) % 65536) * 65536
+ return mh % T32, ml
+end
+
+local function merge(hh: number, hl: number, vh: number, vl: number): (number, number)
+ local rh, rl = round(0, 0, vh, vl)
+ hh, hl = bxor(hh, rh), bxor(hl, rl)
+ hh, hl = mul(hh, hl, P1H, P1L)
+ return add(hh, hl, P4H, P4L)
+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
+ local hh, hl = 0, 0
+ if length >= 32 then
+ local v1h, v1l = add(P1H, P1L, P2H, P2L)
+ local v2h, v2l = P2H, P2L
+ local v3h, v3l = 0, 0
+ local v4h, v4l = add(0, 0, (T32 - P1H - 1) % T32, (T32 - P1L) % T32) -- -P1 (two's complement)
+ local limit = e - 32
+ while p <= limit do
+ v1h, v1l = round(v1h, v1l, readu32(b, p + 4), readu32(b, p))
+ v2h, v2l = round(v2h, v2l, readu32(b, p + 12), readu32(b, p + 8))
+ v3h, v3l = round(v3h, v3l, readu32(b, p + 20), readu32(b, p + 16))
+ v4h, v4l = round(v4h, v4l, readu32(b, p + 28), readu32(b, p + 24))
+ p += 32
+ end
+ local ah, al = rotl(v1h, v1l, 1)
+ local bh, bl = rotl(v2h, v2l, 7)
+ hh, hl = add(ah, al, bh, bl)
+ bh, bl = rotl(v3h, v3l, 12)
+ hh, hl = add(hh, hl, bh, bl)
+ bh, bl = rotl(v4h, v4l, 18)
+ hh, hl = add(hh, hl, bh, bl)
+ hh, hl = merge(hh, hl, v1h, v1l)
+ hh, hl = merge(hh, hl, v2h, v2l)
+ hh, hl = merge(hh, hl, v3h, v3l)
+ hh, hl = merge(hh, hl, v4h, v4l)
+ else
+ hh, hl = P5H, P5L
+ end
+ hh, hl = add(hh, hl, math.floor(length / T32) % T32, length % T32)
+ while p + 8 <= e do
+ local kh, kl = round(0, 0, readu32(b, p + 4), readu32(b, p))
+ hh, hl = bxor(hh, kh), bxor(hl, kl)
+ hh, hl = rotl(hh, hl, 27)
+ hh, hl = mul(hh, hl, P1H, P1L)
+ hh, hl = add(hh, hl, P4H, P4L)
+ p += 8
+ end
+ if p + 4 <= e then
+ local kh, kl = mul(0, readu32(b, p), P1H, P1L)
+ hh, hl = bxor(hh, kh), bxor(hl, kl)
+ hh, hl = rotl(hh, hl, 23)
+ hh, hl = mul(hh, hl, P2H, P2L)
+ hh, hl = add(hh, hl, P3H, P3L)
+ p += 4
+ end
+ while p < e do
+ local kh, kl = mul(0, readu8(b, p), P5H, P5L)
+ hh, hl = bxor(hh, kh), bxor(hl, kl)
+ hh, hl = rotl(hh, hl, 11)
+ hh, hl = mul(hh, hl, P1H, P1L)
+ p += 1
+ end
+ -- avalanche
+ hl = bxor(hl, rshift(hh, 1)) -- h ^= h >> 33
+ hh, hl = mul(hh, hl, P2H, P2L)
+ hh, hl = bxor(hh, rshift(hh, 29)), bxor(hl, bor(rshift(hl, 29), lshift(hh, 3))) -- h ^= h >> 29
+ hh, hl = mul(hh, hl, P3H, P3L)
+ hl = bxor(hl, hh) -- h ^= h >> 32
+ return hh, hl
+end
+
+return Xxh64
diff --git a/src/Formats/codecs/Zstd/init.luau b/src/Formats/codecs/Zstd/init.luau
new file mode 100644
index 0000000..c48de03
--- /dev/null
+++ b/src/Formats/codecs/Zstd/init.luau
@@ -0,0 +1,89 @@
+--!strict
+-- codecs/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("@formats/codecs/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).
+local Err = require("@formats/core/Err")
+local Decode = require("@formats/codecs/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)
+}
+
+local CODES: { [string]: string } = {
+ TRUNCATED = Err.TRUNCATED,
+ CORRUPT = Err.CORRUPT,
+ CHECKSUM = Err.CHECKSUM,
+ UNSUPPORTED = Err.UNSUPPORTED,
+ LIMIT = Err.LIMIT,
+}
+
+-- 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
+ return false
+ end
+ local m = buffer.readu32(buf, o)
+ 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).
+function Zstd.decompress(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any)
+ local b: buffer
+ if type(buf) == "string" then
+ b = buffer.fromstring(buf)
+ elseif type(buf) == "buffer" then
+ b = buf
+ else
+ return nil, Err.new(Err.ARG, "Zstd.decompress: expected a buffer or a string, got " .. typeof(buf))
+ end
+ local n = buffer.len(b)
+ local o = offset or 0
+ if type(o) ~= "number" or o < 0 or o > n or o % 1 ~= 0 then
+ return nil, Err.new(Err.ARG, "Zstd.decompress: bad offset " .. tostring(offset))
+ end
+ local l = length or (n - o)
+ if type(l) ~= "number" or l < 0 or l % 1 ~= 0 then
+ return nil, Err.new(Err.ARG, "Zstd.decompress: bad length " .. tostring(length))
+ end
+ l = math.min(l, n - o)
+ local maxBytes = if opts and opts.maxBytes ~= nil then opts.maxBytes else 2 ^ 30
+ if type(maxBytes) ~= "number" or maxBytes < 0 then
+ return nil, Err.new(Err.ARG, "Zstd.decompress: bad maxBytes " .. tostring(maxBytes))
+ end
+ local verify = not (opts and opts.verify == false)
+ local out, len, consumed, at = Decode.decompress(b, o, o + l, maxBytes, verify)
+ if not out then
+ return nil, Err.new(CODES[len] or Err.CORRUPT, tostring(consumed), at)
+ end
+ if buffer.len(out) ~= len then
+ local r = buffer.create(len)
+ buffer.copy(r, 0, out, 0, len)
+ out = r
+ end
+ 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)
+ return Decode.hash(buf, o, l)
+end
+
+return Zstd
diff --git a/src/Formats/containers/Archive.luau b/src/Formats/containers/Archive.luau
new file mode 100644
index 0000000..1cdd84c
--- /dev/null
+++ b/src/Formats/containers/Archive.luau
@@ -0,0 +1,176 @@
+--!strict
+-- containers/Archive: the in-memory Archive value (Types.Archive) that archive formats return. Entries hold their data
+-- or a lazy loader (decompressed on read); add() appends or replaces an entry; write() calls the format's encoder
+-- (attached by the format), so an archive read from a .tar writes back as a .tar, and any Archive (a zip, a 7z) can be
+-- encoded by any writable archive format through its list() / read().
+--
+-- local a = Archive.new("tar", Tar.encode) -- encode(archive, opts) -> buffer | nil, Err
+-- Archive.put(a, { name = "a.txt", size = 3, data = buf, mtime = 0 })
+-- Archive.put(a, { name = "b.bin", size = n, load = function() return inflate(...) end })
+-- a:list() a:read("a.txt") a:add("c.txt", "text") a:write()
+--
+-- Single-stream archives (gzip, zst, xz, bz2, br) set meta.stream = true and hold one entry; the api unwraps them
+-- (a .tar.gz loads as the tar inside). Never throws: read of a missing entry or a failed loader returns nil, Err.
+local Err = require("@formats/core/Err")
+local Types = require("@formats/Types")
+
+local Archive = {}
+
+-- an entry: the Types.ArchiveEntry fields plus format extras (mode, uid, gid, link, type, ...) and its data source
+export type Entry = {
+ name: string,
+ size: number,
+ compressedSize: number?,
+ method: string?,
+ mtime: number?,
+ dir: boolean,
+ data: buffer?,
+ load: (() -> (buffer?, Err.Err?))?,
+ [string]: any,
+}
+export type Encoder = (archive: any, opts: any?) -> (buffer?, Err.Err?)
+
+local Methods = {}
+Methods.__index = Methods
+
+-- the public fields of an entry (no data / loader)
+local function public(e: Entry): Types.ArchiveEntry
+ local out: any = {}
+ for k, v in e :: any do
+ if k ~= "data" and k ~= "load" then
+ out[k] = v
+ end
+ end
+ return out
+end
+
+function Methods.list(self: any): { Types.ArchiveEntry }
+ local out = table.create(#self._entries)
+ for i, e in self._entries do
+ out[i] = public(e)
+ end
+ return out
+end
+
+-- read(name) -> buffer | nil, Err (directories read as an empty buffer)
+function Methods.read(self: any, name: string): (buffer?, Err.Err?)
+ local e: Entry? = self._byName[name]
+ if not e then
+ return nil, Err.new(Err.ARG, "no entry named " .. tostring(name))
+ end
+ if e.data then
+ return e.data
+ end
+ if e.load then
+ local ok, b, err = pcall(e.load)
+ if not ok then
+ return nil, Err.new(Err.CORRUPT, "entry " .. name .. ": " .. tostring(b))
+ end
+ if not b then
+ return nil, err or Err.new(Err.CORRUPT, "entry " .. name .. ": decode failed")
+ end
+ return b
+ end
+ return buffer.create(0)
+end
+
+-- add(name, data, opts?) -> (): opts.mtime (unix seconds), opts.dir, opts.mode; replaces an entry of the same name
+function Methods.add(self: any, name: string, data: buffer | string, opts: any?)
+ local b: buffer = if type(data) == "string" then buffer.fromstring(data) elseif type(data) == "buffer" then data else buffer.create(0)
+ local o = opts or {}
+ local e: Entry = {
+ name = name,
+ size = buffer.len(b),
+ dir = o.dir == true,
+ mtime = o.mtime,
+ mode = o.mode,
+ data = b,
+ }
+ Archive.put(self, e)
+end
+
+-- write(opts?) -> buffer | nil, Err: the archive's own format (opts.format is handled by the api)
+function Methods.write(self: any, opts: any?): (buffer?, Err.Err?)
+ local enc = self._encode
+ if not enc then
+ return nil, Err.new(Err.UNSUPPORTED, self.format .. " archives are read-only")
+ end
+ return enc(self, opts)
+end
+
+-- new(format, encode?) -> an empty Archive
+function Archive.new(format: string, encode: Encoder?): any
+ return setmetatable({
+ kind = "archive",
+ format = format,
+ meta = {},
+ _entries = {} :: { Entry },
+ _byName = {} :: { [string]: Entry },
+ _encode = encode,
+ }, Methods)
+end
+
+-- put(archive, entry): append (or replace by name) an entry
+function Archive.put(a: any, e: Entry)
+ local old = a._byName[e.name]
+ if old then
+ local i = table.find(a._entries, old)
+ if i then
+ a._entries[i] = e
+ end
+ else
+ table.insert(a._entries, e)
+ end
+ a._byName[e.name] = e
+end
+
+-- entries(value) -> { { entry, read: () -> (buffer?, Err?) } } for any Archive-shaped value (ours or another
+-- format's): what encoders iterate. nil when the value is not an archive.
+function Archive.entries(value: any): { { entry: Types.ArchiveEntry, read: () -> (buffer?, Err.Err?) } }?
+ if type(value) ~= "table" or value.kind ~= "archive" or type(value.list) ~= "function" or type(value.read) ~= "function" then
+ return nil
+ end
+ local ok, list = pcall(value.list, value)
+ if not ok or type(list) ~= "table" then
+ return nil
+ end
+ local out = {}
+ for _, e in list do
+ if type(e) == "table" and type(e.name) == "string" then
+ table.insert(out, {
+ entry = e,
+ read = function(): (buffer?, Err.Err?)
+ local rok, b, err = pcall(value.read, value, e.name)
+ if not rok then
+ return nil, Err.new(Err.CORRUPT, tostring(b))
+ end
+ return b, err
+ end,
+ })
+ end
+ end
+ return out
+end
+
+-- streamName(opts, ext) -> the entry name for a single-stream archive: opts.name without its compression extension
+-- (".tgz" -> ".tar"), else "data"
+function Archive.streamName(opts: any?, exts: { string }): string
+ local name = if type(opts) == "table" and type(opts.name) == "string" then opts.name else nil
+ if not name then
+ return "data"
+ end
+ local base = string.match(name, "([^/\\]+)$") or name
+ local stem, ext = string.match(base, "^(.+)%.([%w]+)$")
+ if stem and ext then
+ local e = string.lower(ext)
+ if e == "tgz" or e == "tbz2" or e == "tbz" or e == "txz" or e == "tzst" then
+ return stem .. ".tar"
+ end
+ if table.find(exts, e) then
+ return stem
+ end
+ end
+ return base
+end
+
+return Archive
diff --git a/src/Formats/containers/IsoBmff/Box.luau b/src/Formats/containers/IsoBmff/Box.luau
new file mode 100644
index 0000000..769d22e
--- /dev/null
+++ b/src/Formats/containers/IsoBmff/Box.luau
@@ -0,0 +1,193 @@
+--!strict
+-- containers/IsoBmff/Box: the box tree of an ISO BMFF / QuickTime file (ISO/IEC 14496-12 4.2): 32-bit, 64-bit
+-- (size 1) and to-the-end (size 0) sizes, uuid boxes, full-box version / flags, and the recursion into the container
+-- boxes (moov / trak / mdia / minf / stbl / udta / meta / ilst items / moof / traf / iprp / ipco / iref / dinf / ...).
+-- Sample descriptions (stsd) are left to the demuxer, which knows the sample entry layouts. Never throws.
+local Err = require("@formats/core/Err")
+
+local readu8, readu32, readstring = buffer.readu8, buffer.readu32, buffer.readstring
+local byteswap = bit32.byteswap
+
+local Box = {}
+
+export type Box = {
+ type: string, -- four characters ("moov", "\169nam", ...); "uuid" boxes also have `uuid`
+ start: number, -- absolute offset of the box in the buffer
+ size: number, -- the whole box, header included
+ data: number, -- absolute offset of the payload (after size / type / largesize / uuid)
+ stop: number, -- absolute offset just past the box (start + size, clamped to the parent)
+ uuid: string?,
+ children: { Box }?, -- container boxes
+ truncated: boolean?, -- the box claims more bytes than its parent has (clamped)
+}
+
+-- plain container boxes: their payload is a list of boxes
+local CONTAINERS = {
+ moov = true, trak = true, mdia = true, minf = true, stbl = true, dinf = true, edts = true, udta = true,
+ mvex = true, moof = true, traf = true, mfra = true, tref = true, iprp = true, ipco = true, sinf = true,
+ schi = true, wave = true, gmhd = true, tapt = true, ilst = true, clip = true, matt = true, rinf = true,
+ strk = true, strd = true, grpl = true, meco = true, mere = true,
+}
+-- full boxes (version + flags) whose payload is then a list of boxes, after `skip` more bytes
+local FULL_CONTAINERS: { [string]: number } = { meta = 0, iref = 0, dref = 4 }
+Box.CONTAINERS = CONTAINERS
+
+local function be32(b: buffer, o: number): number
+ return byteswap(readu32(b, o))
+end
+Box.be32 = be32
+
+-- the ilst item boxes ("\169nam", "trkn", "----", ...) contain data / mean / name boxes
+local function isIlstItem(parentType: string?): boolean
+ return parentType == "ilst"
+end
+
+-- header(buf, p, limit) -> Box (without children) | nil, Err
+function Box.header(b: buffer, p: number, limit: number): (Box?, Err.Err?)
+ if p + 8 > limit then
+ return nil, Err.new(Err.TRUNCATED, "box header runs past the end", p)
+ end
+ local size = be32(b, p)
+ local typ = readstring(b, p + 4, 4)
+ local data = p + 8
+ if size == 1 then
+ if p + 16 > limit then
+ return nil, Err.new(Err.TRUNCATED, "64-bit box size runs past the end", p)
+ end
+ size = be32(b, p + 8) * 4294967296 + be32(b, p + 12)
+ data = p + 16
+ elseif size == 0 then
+ size = limit - p
+ end
+ local uuid: string? = nil
+ if typ == "uuid" then
+ if data + 16 > limit then
+ return nil, Err.new(Err.TRUNCATED, "uuid runs past the end", p)
+ end
+ uuid = readstring(b, data, 16)
+ data += 16
+ end
+ if size < data - p then
+ return nil, Err.new(Err.CORRUPT, string.format("box '%s' size %d is smaller than its header", typ, size), p)
+ end
+ local stop = p + size
+ local truncated: boolean? = nil
+ if stop > limit then
+ stop = limit
+ truncated = true
+ end
+ return { type = typ, start = p, size = size, data = data, stop = stop, uuid = uuid, children = nil, truncated = truncated }, nil
+end
+
+-- list(buf, p, limit, parentType?, depth?) -> { Box } (a run of sibling boxes, containers parsed recursively). A
+-- broken box ends the list (its siblings so far are kept); the second value is the first error met, if any.
+function Box.list(b: buffer, p: number, limit: number, parentType: string?, depth: number?): ({ Box }, Err.Err?)
+ local d = depth or 0
+ local out: { Box } = {}
+ local firstErr: Err.Err? = nil
+ if d > 32 then
+ return out, Err.new(Err.CORRUPT, "boxes nested too deep", p)
+ end
+ while p + 8 <= limit do
+ local box, err = Box.header(b, p, limit)
+ if not box then
+ firstErr = firstErr or err
+ break
+ end
+ if box.truncated then
+ firstErr = firstErr or Err.new(Err.TRUNCATED, "box '" .. box.type .. "' runs past the end", p)
+ end
+ local t = box.type
+ local kids: { Box }? = nil
+ local kerr: Err.Err? = nil
+ if CONTAINERS[t] or isIlstItem(parentType) then
+ kids, kerr = Box.list(b, box.data, box.stop, t, d + 1)
+ elseif FULL_CONTAINERS[t] then
+ local q = box.data + 4 + FULL_CONTAINERS[t]
+ -- QuickTime writes udta/meta as a plain container: its first child box follows directly
+ if t == "meta" and box.data + 8 <= box.stop and readstring(b, box.data + 4, 4) == "hdlr" then
+ q = box.data
+ end
+ if q <= box.stop then
+ kids, kerr = Box.list(b, q, box.stop, t, d + 1)
+ end
+ elseif t == "iinf" then
+ if box.data + 4 <= box.stop then
+ local v = readu8(b, box.data)
+ local q = box.data + 4 + (if v == 0 then 2 else 4)
+ if q <= box.stop then
+ kids, kerr = Box.list(b, q, box.stop, t, d + 1)
+ end
+ end
+ end
+ box.children = kids
+ if kerr then
+ firstErr = firstErr or kerr
+ end
+ table.insert(out, box)
+ if box.stop <= p then
+ break
+ end
+ p = box.stop
+ end
+ return out, firstErr
+end
+
+-- child(box, type) -> the first child of that type
+function Box.child(box: Box?, typ: string): Box?
+ if not box or not box.children then
+ return nil
+ end
+ for _, c in box.children :: { Box } do
+ if c.type == typ then
+ return c
+ end
+ end
+ return nil
+end
+
+-- children(box, type) -> every child of that type
+function Box.childrenOf(box: Box?, typ: string): { Box }
+ local out = {}
+ if box and box.children then
+ for _, c in box.children :: { Box } do
+ if c.type == typ then
+ table.insert(out, c)
+ end
+ end
+ end
+ return out
+end
+
+-- path(boxes or box, "moov/trak/mdia") -> the first box along the path
+function Box.path(root: any, path: string): Box?
+ local cur: any = root
+ for part in string.gmatch(path, "[^/]+") do
+ if cur == nil then
+ return nil
+ end
+ local list = if cur.children ~= nil or cur.type ~= nil then cur.children else cur
+ local found = nil
+ if list then
+ for _, c in list do
+ if c.type == part then
+ found = c
+ break
+ end
+ end
+ end
+ cur = found
+ end
+ return cur
+end
+
+-- version / flags of a full box
+function Box.fullHeader(b: buffer, box: Box): (number, number)
+ if box.data + 4 > box.stop then
+ return -1, 0
+ end
+ local v = be32(b, box.data)
+ return bit32.rshift(v, 24), bit32.band(v, 0xFFFFFF)
+end
+
+return Box
diff --git a/src/Formats/containers/IsoBmff/Demux.luau b/src/Formats/containers/IsoBmff/Demux.luau
new file mode 100644
index 0000000..6a5a4cb
--- /dev/null
+++ b/src/Formats/containers/IsoBmff/Demux.luau
@@ -0,0 +1,848 @@
+--!strict
+-- containers/IsoBmff/Demux: tracks and sample tables of an ISO BMFF / QuickTime file (ISO/IEC 14496-12 8.3 - 8.8):
+-- tkhd / mdhd / hdlr, sample descriptions (audio v0 / QuickTime v1 / v2, video, other) with the codec configuration
+-- (esds DecoderSpecificInfo, alac, dOps, dfLa, avcC, hvcC, av1C, vpcC, dac3, ...), stts / ctts / stsc / stsz / stz2 /
+-- stco / co64 / stss, edit lists (elst), and fragmented files (mvex / trex, moof / traf / tfhd / tfdt / trun).
+-- The per-sample tables are columnar arrays (offsets / sizes / dts / durations / cts / sync), offsets absolute in the
+-- reader's buffer. Never throws.
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Box = require("@formats/containers/IsoBmff/Box")
+
+local readstring = buffer.readstring
+
+local Demux = {}
+
+export type Edit = { duration: number, mediaTime: number, rate: number } -- duration in movie ticks, mediaTime in media ticks (-1 = empty)
+
+-- a track: Types.Track (id, kind, codec, timescale, duration, width, height, sampleRate, channels, config) plus the
+-- sample tables and the ISO facts
+export type Track = {
+ id: number,
+ kind: "video" | "audio" | "subtitle" | "data",
+ codec: string, -- "aac", "alac", "mp3", "opus", "flac", "pcm", "h264", "hevc", "av1", "vp8", "vp9", "mpeg4", "mjpeg", "ac3", "eac3", "tx3g", ... or the entry fourcc
+ entry: string, -- the sample entry fourcc ("mp4a", "alac", "avc1", ...)
+ handler: string, -- hdlr type ("soun", "vide", "subt", "text", "pict", ...)
+ timescale: number,
+ duration: number, -- seconds (media duration; the edit list may shorten it)
+ mediaDuration: number, -- ticks
+ language: string?, -- ISO 639-2 ("und", "eng", ...)
+ width: number?,
+ height: number?,
+ sampleRate: number?,
+ channels: number?,
+ bitsPerSample: number?,
+ config: buffer?, -- codec configuration (AudioSpecificConfig, ALAC cookie, dOps, avcC, ...)
+ objectType: number?, -- esds objectTypeIndication
+ pcm: { bits: number, float: boolean, little: boolean }?,
+ entryBoxes: { Box.Box }, -- the sample entry's child boxes (esds, btrt, colr, pasp, ...)
+ edits: { Edit }?,
+ skip: number, -- media ticks to drop at the start (the first edit's media time: AAC priming)
+ delay: number, -- movie ticks of an initial empty edit
+ playDuration: number?, -- media ticks the edit list plays (nil: all)
+ -- samples
+ sampleCount: number,
+ offsets: { number }, -- absolute offsets in the buffer
+ sizes: { number },
+ dts: { number }, -- decode times in ticks
+ durations: { number },
+ cts: { number }?, -- composition offsets (pts = dts + cts) when the track has ctts / trun offsets
+ sync: { [number]: boolean }?, -- sync samples (nil: every sample is a sync sample)
+ sampleDescription: { number }?, -- stsd index per sample when there are several entries
+ [string]: any,
+}
+
+export type Options = { maxSamples: number? }
+
+local HANDLER_KIND: { [string]: "video" | "audio" | "subtitle" | "data" } = {
+ soun = "audio", vide = "video", pict = "video", auxv = "video", subt = "subtitle", text = "subtitle",
+ sbtl = "subtitle", clcp = "subtitle",
+}
+local CODEC: { [string]: string } = {
+ mp4a = "aac", alac = "alac", Opus = "opus", fLaC = "flac", [".mp3"] = "mp3", ["ac-3"] = "ac3", ["ec-3"] = "eac3",
+ lpcm = "pcm", sowt = "pcm", twos = "pcm", ["raw "] = "pcm", in24 = "pcm", in32 = "pcm", fl32 = "pcm", fl64 = "pcm",
+ ipcm = "pcm", fpcm = "pcm", ulaw = "ulaw", alaw = "alaw", samr = "amr", sawb = "amrwb",
+ avc1 = "h264", avc3 = "h264", hvc1 = "hevc", hev1 = "hevc", av01 = "av1", vp08 = "vp8", vp09 = "vp9",
+ mp4v = "mpeg4", jpeg = "mjpeg", mjpa = "mjpeg", mjpb = "mjpeg", png = "png", ["s263"] = "h263", ["mp1v"] = "mpeg1",
+ ["mp2v"] = "mpeg2", tx3g = "tx3g", wvtt = "webvtt", stpp = "ttml", c608 = "cea608", text = "text",
+}
+-- esds objectTypeIndication -> codec
+local OTI: { [number]: string } = {
+ [0x40] = "aac", [0x66] = "aac", [0x67] = "aac", [0x68] = "aac", [0x69] = "mp3", [0x6B] = "mp3", [0x6A] = "mpeg1",
+ [0x60] = "mpeg2", [0x61] = "mpeg2", [0x20] = "mpeg4", [0x21] = "h264", [0x6C] = "mjpeg", [0xA5] = "ac3",
+ [0xA6] = "eac3", [0xAD] = "opus", [0xDD] = "vorbis",
+}
+-- the box holding each video / audio codec's configuration
+local CONFIG_BOX = { "avcC", "hvcC", "av1C", "vpcC", "dOps", "dfLa", "dac3", "dec3", "d263", "glbl" }
+local FULL_CONFIG: { [string]: boolean } = { vpcC = true, dfLa = true, alac = true }
+
+local function payload(b: buffer, box: Box.Box, skip: number?): buffer
+ local o = box.data + (skip or 0)
+ local n = math.max(0, box.stop - o)
+ local out = buffer.create(n)
+ if n > 0 then
+ buffer.copy(out, 0, b, o, n)
+ end
+ return out
+end
+
+local function reader(b: buffer, box: Box.Box): Bytes.Reader
+ return Bytes.reader(b, box.data, box.stop - box.data)
+end
+
+-- expandable descriptor length (ISO 14496-1 8.3.3)
+local function descLen(r: Bytes.Reader): number
+ local n = 0
+ for _ = 1, 4 do
+ local c = r:u8()
+ n = n * 128 + bit32.band(c, 127)
+ if c < 128 then
+ break
+ end
+ end
+ return n
+end
+
+-- esds -> objectTypeIndication, DecoderSpecificInfo, avg bitrate
+function Demux.esds(b: buffer, box: Box.Box): (number?, buffer?, number?)
+ local r = reader(b, box)
+ r:skip(4) -- version / flags
+ if r:u8() ~= 3 then
+ return nil, nil, nil
+ end
+ descLen(r)
+ r:skip(2) -- ES_ID
+ local flags = r:u8()
+ if bit32.band(flags, 0x80) ~= 0 then
+ r:skip(2)
+ end
+ if bit32.band(flags, 0x40) ~= 0 then
+ r:skip(r:u8())
+ end
+ if bit32.band(flags, 0x20) ~= 0 then
+ r:skip(2)
+ end
+ if r:u8() ~= 4 then
+ return nil, nil, nil
+ end
+ local dlen = descLen(r)
+ local dstart = r.pos
+ local oti = r:u8()
+ r:skip(1 + 3 + 4) -- streamType, bufferSize, maxBitrate
+ local avg = r:u32be()
+ local dsi: buffer? = nil
+ if r.pos < dstart + dlen and r:u8() == 5 then
+ local n = descLen(r)
+ if n > 0 and r:need(n) then
+ dsi = r:bytes(n)
+ end
+ end
+ if r.err then
+ return oti, nil, nil
+ end
+ return oti, dsi, avg
+end
+
+-- the sample entry `e` of a track with handler `handler`: fills the codec facts into t
+local function sampleEntry(b: buffer, e: Box.Box, handler: string, t: Track)
+ local r = reader(b, e)
+ r:skip(6)
+ r:skip(2) -- data reference index
+ local typ = e.type
+ t.entry = typ
+ t.codec = CODEC[typ] or typ
+ local kind = t.kind
+ local childStart
+ if kind == "audio" then
+ local version = r:u16be()
+ r:skip(2 + 4) -- revision, vendor
+ local channels = r:u16be()
+ local bits = r:u16be()
+ r:skip(4) -- compression id, packet size
+ local rate = r:u32be() / 65536
+ if version == 1 then
+ r:skip(16)
+ elseif version == 2 then
+ r:skip(4)
+ rate = r:f64be()
+ channels = r:u32be()
+ r:skip(4)
+ bits = r:u32be()
+ local lpcmFlags = r:u32be()
+ r:skip(8)
+ if typ == "lpcm" then
+ t.pcm = {
+ bits = bits,
+ float = bit32.band(lpcmFlags, 1) ~= 0,
+ little = bit32.band(lpcmFlags, 2) == 0,
+ }
+ end
+ end
+ t.channels, t.sampleRate, t.bitsPerSample = channels, rate, bits
+ if not t.pcm and t.codec == "pcm" then
+ local B: { [string]: number } = { sowt = 16, twos = 16, ["raw "] = 8, in24 = 24, in32 = 32, fl32 = 32, fl64 = 64 }
+ t.pcm = {
+ bits = B[typ] or bits,
+ float = typ == "fl32" or typ == "fl64",
+ little = typ == "sowt",
+ }
+ end
+ childStart = r.pos
+ elseif kind == "video" then
+ r:skip(16)
+ t.width = r:u16be()
+ t.height = r:u16be()
+ r:skip(4 + 4 + 4 + 2 + 32 + 2 + 2)
+ childStart = r.pos
+ else
+ childStart = r.pos
+ end
+ if r.err then
+ t.entryBoxes = {}
+ return
+ end
+ local kids = Box.list(b, childStart, e.stop, typ)
+ t.entryBoxes = kids
+ -- QuickTime puts the codec boxes inside 'wave'
+ local all = table.clone(kids)
+ local wave = Box.child({ type = "", start = 0, size = 0, data = 0, stop = 0, children = kids } :: any, "wave")
+ if wave and wave.children then
+ for _, c in wave.children :: { Box.Box } do
+ table.insert(all, c)
+ end
+ end
+ local holder = { type = "", start = 0, size = 0, data = 0, stop = 0, children = all } :: any
+ local esds = Box.child(holder, "esds")
+ if esds then
+ local oti, dsi, avg = Demux.esds(b, esds)
+ t.objectType = oti
+ if oti and OTI[oti] then
+ t.codec = OTI[oti]
+ end
+ t.config = dsi
+ if avg and avg > 0 then
+ t.bitrate = avg
+ end
+ end
+ if typ == "alac" then
+ local a = Box.child(holder, "alac")
+ if a then
+ t.config = payload(b, a, 4)
+ end
+ end
+ for _, name in CONFIG_BOX do
+ local c = Box.child(holder, name)
+ if c then
+ t.config = payload(b, c, if FULL_CONFIG[name] then 4 else 0)
+ break
+ end
+ end
+end
+
+-- media handler / header / sample tables of one trak -> Track | nil, Err
+local function track(b: buffer, trak: Box.Box, movieTimescale: number, trex: { [number]: any }, o: Options): (Track?, Err.Err?)
+ local tkhd = Box.child(trak, "tkhd")
+ local mdia = Box.child(trak, "mdia")
+ if not tkhd or not mdia then
+ return nil, Err.new(Err.CORRUPT, "trak without tkhd / mdia", trak.start)
+ end
+ local t: Track = {
+ id = 0, kind = "data", codec = "", entry = "", handler = "", timescale = 1, duration = 0, mediaDuration = 0,
+ entryBoxes = {}, skip = 0, delay = 0, sampleCount = 0, offsets = {}, sizes = {}, dts = {}, durations = {},
+ }
+ do
+ local r = reader(b, tkhd)
+ local v = r:u8()
+ r:skip(3)
+ if v == 1 then
+ r:skip(16)
+ t.id = r:u32be()
+ r:skip(4 + 8)
+ else
+ r:skip(8)
+ t.id = r:u32be()
+ r:skip(4 + 4)
+ end
+ r:skip(8 + 2 + 2 + 2 + 2 + 36)
+ local w, h = r:u32be() / 65536, r:u32be() / 65536
+ if r.err then
+ return nil, r.err
+ end
+ if w > 0 and h > 0 then
+ t.width, t.height = math.floor(w), math.floor(h)
+ end
+ end
+ local mdhd = Box.child(mdia, "mdhd")
+ if mdhd then
+ local r = reader(b, mdhd)
+ local v = r:u8()
+ r:skip(3)
+ if v == 1 then
+ r:skip(16)
+ t.timescale = r:u32be()
+ t.mediaDuration = r:u64be()
+ else
+ r:skip(8)
+ t.timescale = r:u32be()
+ t.mediaDuration = r:u32be()
+ end
+ local lang = r:u16be()
+ if not r.err and lang ~= 0 and lang ~= 0x7FFF then
+ t.language = string.char(
+ 96 + bit32.band(bit32.rshift(lang, 10), 31),
+ 96 + bit32.band(bit32.rshift(lang, 5), 31),
+ 96 + bit32.band(lang, 31)
+ )
+ end
+ if t.timescale == 0 then
+ t.timescale = 1
+ end
+ end
+ local hdlr = Box.child(mdia, "hdlr")
+ if hdlr and hdlr.data + 12 <= hdlr.stop then
+ t.handler = readstring(b, hdlr.data + 8, 4)
+ end
+ t.kind = HANDLER_KIND[t.handler] or "data"
+ local stbl = Box.path(mdia, "minf/stbl")
+ if not stbl then
+ return nil, Err.new(Err.CORRUPT, "track " .. t.id .. " has no sample table", mdia.start)
+ end
+ -- sample descriptions
+ local stsd = Box.child(stbl, "stsd")
+ if stsd and stsd.data + 8 <= stsd.stop then
+ local entries = Box.list(b, stsd.data + 8, stsd.stop, "stsd")
+ if entries[1] then
+ sampleEntry(b, entries[1], t.handler, t)
+ end
+ t.sampleEntries = entries
+ end
+ -- edit list
+ local elst = Box.path(trak, "edts/elst")
+ if elst then
+ local r = reader(b, elst)
+ local v = r:u8()
+ r:skip(3)
+ local n = r:u32be()
+ if n <= (elst.stop - elst.data) // 12 then
+ local edits = {}
+ for _ = 1, n do
+ local dur, mt
+ if v == 1 then
+ dur, mt = r:u64be(), r:i64be()
+ else
+ dur, mt = r:u32be(), r:i32be()
+ end
+ local rate = r:i32be() / 65536
+ if r.err then
+ break
+ end
+ table.insert(edits, { duration = dur, mediaTime = mt, rate = rate })
+ end
+ t.edits = edits
+ local play = 0
+ local started = false
+ for _, ed in edits do
+ if ed.mediaTime == -1 then
+ if not started then
+ t.delay += ed.duration
+ end
+ else
+ if not started then
+ t.skip = ed.mediaTime
+ started = true
+ end
+ play += ed.duration * t.timescale / math.max(1, movieTimescale)
+ end
+ end
+ if started and play > 0 then
+ t.playDuration = math.floor(play + 0.5)
+ end
+ end
+ end
+ -- sample sizes
+ local maxSamples = o.maxSamples or 2 ^ 25
+ local sizes = t.sizes
+ local count = 0
+ local stsz = Box.child(stbl, "stsz")
+ local stz2 = Box.child(stbl, "stz2")
+ if stsz then
+ local r = reader(b, stsz)
+ r:skip(4)
+ local fixed = r:u32be()
+ count = r:u32be()
+ if r.err then
+ return nil, r.err
+ end
+ if count > maxSamples then
+ return nil, Err.new(Err.LIMIT, string.format("track %d has %d samples (limit %d)", t.id, count, maxSamples), stsz.start)
+ end
+ if fixed ~= 0 then
+ for i = 1, count do
+ sizes[i] = fixed
+ end
+ else
+ if count * 4 > r:remaining() then
+ return nil, Err.new(Err.TRUNCATED, "stsz table runs past its box", stsz.start)
+ end
+ for i = 1, count do
+ sizes[i] = r:u32be()
+ end
+ end
+ elseif stz2 then
+ local r = reader(b, stz2)
+ r:skip(4 + 3)
+ local fieldSize = r:u8()
+ count = r:u32be()
+ if r.err then
+ return nil, r.err
+ end
+ if fieldSize ~= 4 and fieldSize ~= 8 and fieldSize ~= 16 then
+ return nil, Err.new(Err.CORRUPT, "bad stz2 field size " .. fieldSize, stz2.start)
+ end
+ if count * fieldSize / 8 > r:remaining() + 1 then
+ return nil, Err.new(Err.TRUNCATED, "stz2 table runs past its box", stz2.start)
+ end
+ for i = 1, count do
+ if fieldSize == 16 then
+ sizes[i] = r:u16be()
+ elseif fieldSize == 8 then
+ sizes[i] = r:u8()
+ else
+ local byte = r:peekU8()
+ if i % 2 == 1 then
+ sizes[i] = bit32.rshift(math.max(byte, 0), 4)
+ else
+ sizes[i] = bit32.band(math.max(byte, 0), 15)
+ r:skip(1)
+ end
+ end
+ end
+ end
+ -- decode times
+ local dts, durs = t.dts, t.durations
+ local stts = Box.child(stbl, "stts")
+ if stts and count > 0 then
+ local r = reader(b, stts)
+ r:skip(4)
+ local n = r:u32be()
+ if n * 8 > r:remaining() then
+ return nil, Err.new(Err.TRUNCATED, "stts table runs past its box", stts.start)
+ end
+ local i, time = 1, 0
+ for _ = 1, n do
+ local c, d = r:u32be(), r:u32be()
+ for _ = 1, c do
+ if i > count then
+ break
+ end
+ dts[i], durs[i] = time, d
+ time += d
+ i += 1
+ end
+ end
+ -- fewer stts entries than samples: repeat the last duration
+ local last = if i > 1 then durs[i - 1] else 0
+ while i <= count do
+ dts[i], durs[i] = time, last
+ time += last
+ i += 1
+ end
+ else
+ for i = 1, count do
+ dts[i], durs[i] = 0, 0
+ end
+ end
+ -- composition offsets
+ local ctts = Box.child(stbl, "ctts")
+ if ctts and count > 0 then
+ local r = reader(b, ctts)
+ local v = r:u8()
+ r:skip(3)
+ local n = r:u32be()
+ if n * 8 <= r:remaining() then
+ local cts = table.create(count, 0)
+ local i = 1
+ for _ = 1, n do
+ local c = r:u32be()
+ local off = if v == 1 then r:i32be() else r:u32be()
+ if v == 0 and off >= 2147483648 then
+ off -= 4294967296 -- writers put negative offsets in version 0 too
+ end
+ for _ = 1, c do
+ if i > count then
+ break
+ end
+ cts[i] = off
+ i += 1
+ end
+ end
+ t.cts = cts
+ end
+ end
+ -- sync samples
+ local stss = Box.child(stbl, "stss")
+ if stss then
+ local r = reader(b, stss)
+ r:skip(4)
+ local n = r:u32be()
+ if n * 4 <= r:remaining() then
+ local sync = {}
+ for _ = 1, n do
+ sync[r:u32be()] = true
+ end
+ t.sync = sync
+ end
+ end
+ -- chunk offsets + sample-to-chunk -> sample offsets
+ local stco = Box.child(stbl, "stco")
+ local co64 = Box.child(stbl, "co64")
+ local chunks: { number } = {}
+ if stco or co64 then
+ local box = (stco or co64) :: Box.Box
+ local r = reader(b, box)
+ r:skip(4)
+ local n = r:u32be()
+ local w = if co64 then 8 else 4
+ if n * w > r:remaining() then
+ return nil, Err.new(Err.TRUNCATED, "chunk offset table runs past its box", box.start)
+ end
+ for i = 1, n do
+ chunks[i] = if co64 then r:u64be() else r:u32be()
+ end
+ end
+ local stsc = Box.child(stbl, "stsc")
+ local offsets = t.offsets
+ if count > 0 then
+ if not stsc or #chunks == 0 then
+ return nil, Err.new(Err.CORRUPT, "track " .. t.id .. " has samples but no stsc / stco", stbl.start)
+ end
+ local r = reader(b, stsc)
+ r:skip(4)
+ local n = r:u32be()
+ if n * 12 > r:remaining() then
+ return nil, Err.new(Err.TRUNCATED, "stsc table runs past its box", stsc.start)
+ end
+ local first, per, desc = {}, {}, {}
+ for k = 1, n do
+ first[k], per[k], desc[k] = r:u32be(), r:u32be(), r:u32be()
+ end
+ local sdi: { number }? = nil
+ if n > 0 then
+ for k = 1, n do
+ if desc[k] ~= desc[1] then
+ sdi = table.create(count, 1)
+ end
+ end
+ end
+ local i = 1
+ local base = 0 -- added by the caller (the file's offset in the buffer)
+ for k = 1, n do
+ local c0 = first[k]
+ local c1 = if k < n then first[k + 1] - 1 else #chunks
+ if c0 < 1 then
+ return nil, Err.new(Err.CORRUPT, "stsc first chunk 0", stsc.start)
+ end
+ for c = c0, math.min(c1, #chunks) do
+ local off = chunks[c] + base
+ for _ = 1, per[k] do
+ if i > count then
+ break
+ end
+ offsets[i] = off
+ if sdi then
+ sdi[i] = desc[k]
+ end
+ off += sizes[i]
+ i += 1
+ end
+ if i > count then
+ break
+ end
+ end
+ if i > count then
+ break
+ end
+ end
+ if i <= count then
+ return nil, Err.new(Err.CORRUPT, string.format("track %d: the chunks hold %d of %d samples", t.id, i - 1, count), stsc.start)
+ end
+ t.sampleDescription = sdi
+ end
+ t.sampleCount = count
+ -- QuickTime PCM: one "sample" per sample frame (constant size, duration 1). Regroup into packets of up to 1024
+ -- frames within each chunk (as ffmpeg does), so a packet is a useful amount of audio.
+ if t.kind == "audio" and count > 1 and not t.cts and not t.sync then
+ local fixed = sizes[1]
+ local uniform = fixed > 0
+ for i = 1, count do
+ if sizes[i] ~= fixed or durs[i] ~= 1 then
+ uniform = false
+ break
+ end
+ end
+ if uniform then
+ local no, ns, nd, nu = {}, {}, {}, {}
+ local i = 1
+ while i <= count do
+ local k = 1
+ while k < 1024 and i + k <= count and offsets[i + k] == offsets[i] + k * fixed do
+ k += 1
+ end
+ table.insert(no, offsets[i])
+ table.insert(ns, k * fixed)
+ table.insert(nd, dts[i])
+ table.insert(nu, k)
+ i += k
+ end
+ t.offsets, t.sizes, t.dts, t.durations = no, ns, nd, nu
+ t.sampleCount = #no
+ t.frameSize = fixed
+ t.sampleDescription = nil
+ end
+ end
+ -- fragment defaults
+ t.trex = trex[t.id]
+ return t, nil
+end
+
+-- the movie fragments (moof) after the moov: appends their samples to the tracks
+local function fragments(b: buffer, fileBase: number, top: { Box.Box }, byId: { [number]: Track }, o: Options): Err.Err?
+ local maxSamples = o.maxSamples or 2 ^ 25
+ for _, moof in top do
+ if moof.type ~= "moof" then
+ continue
+ end
+ local moofStart = moof.start - fileBase -- file offsets (r.base is added at the end)
+ local prevEnd = moofStart
+ for _, traf in Box.childrenOf(moof, "traf") do
+ local tfhd = Box.child(traf, "tfhd")
+ if not tfhd then
+ continue
+ end
+ local r = reader(b, tfhd)
+ r:skip(1)
+ local flags = r:u24be()
+ local id = r:u32be()
+ local t = byId[id]
+ if r.err or not t then
+ continue
+ end
+ local trex = t.trex or {}
+ local base
+ if bit32.band(flags, 0x1) ~= 0 then
+ base = r:u64be()
+ elseif bit32.band(flags, 0x20000) ~= 0 then
+ base = moofStart
+ else
+ base = prevEnd
+ end
+ if bit32.band(flags, 0x2) ~= 0 then
+ r:skip(4)
+ end
+ local defDur = if bit32.band(flags, 0x8) ~= 0 then r:u32be() else (trex.duration or 0)
+ local defSize = if bit32.band(flags, 0x10) ~= 0 then r:u32be() else (trex.size or 0)
+ local defFlags = if bit32.band(flags, 0x20) ~= 0 then r:u32be() else (trex.flags or 0)
+ if r.err then
+ return r.err
+ end
+ local n0 = t.sampleCount
+ local time = if n0 > 0 then t.dts[n0] + t.durations[n0] else 0
+ local tfdt = Box.child(traf, "tfdt")
+ if tfdt then
+ local q = reader(b, tfdt)
+ local v = q:u8()
+ q:skip(3)
+ local bt = if v == 1 then q:u64be() else q:u32be()
+ if not q.err then
+ time = bt
+ end
+ end
+ local dataPos = base
+ for _, trun in Box.childrenOf(traf, "trun") do
+ local q = reader(b, trun)
+ local v = q:u8()
+ local tf = q:u24be()
+ local n = q:u32be()
+ if q.err then
+ return q.err
+ end
+ if t.sampleCount + n > maxSamples then
+ return Err.new(Err.LIMIT, "too many fragment samples", trun.start)
+ end
+ if bit32.band(tf, 0x1) ~= 0 then
+ dataPos = base + q:i32be()
+ end
+ local firstFlags = if bit32.band(tf, 0x4) ~= 0 then q:u32be() else nil
+ local per = 0
+ for _, bit in { 0x100, 0x200, 0x400, 0x800 } do
+ if bit32.band(tf, bit) ~= 0 then
+ per += 4
+ end
+ end
+ if n * per > q:remaining() then
+ return Err.new(Err.TRUNCATED, "trun table runs past its box", trun.start)
+ end
+ for k = 1, n do
+ local dur = if bit32.band(tf, 0x100) ~= 0 then q:u32be() else defDur
+ local size = if bit32.band(tf, 0x200) ~= 0 then q:u32be() else defSize
+ local sf = if bit32.band(tf, 0x400) ~= 0 then q:u32be() else (if k == 1 and firstFlags then firstFlags else defFlags)
+ local cto = 0
+ if bit32.band(tf, 0x800) ~= 0 then
+ cto = if v == 1 then q:i32be() else q:u32be()
+ end
+ local i = t.sampleCount + 1
+ t.sampleCount = i
+ t.offsets[i] = dataPos
+ t.sizes[i] = size
+ t.dts[i] = time
+ t.durations[i] = dur
+ if cto ~= 0 or t.cts then
+ if not t.cts then
+ t.cts = table.create(i - 1, 0)
+ end
+ (t.cts :: { number })[i] = cto
+ end
+ -- sample_is_non_sync_sample (bit 16)
+ local nonSync = bit32.band(sf, 0x10000) ~= 0
+ if nonSync then
+ if not t.sync then
+ local s = {}
+ for j = 1, i - 1 do
+ s[j] = true
+ end
+ t.sync = s
+ end
+ elseif t.sync then
+ (t.sync :: any)[i] = true
+ end
+ time += dur
+ dataPos += size
+ end
+ prevEnd = dataPos
+ end
+ end
+ end
+ return nil
+end
+
+export type Movie = {
+ brand: string?,
+ minor: number?,
+ compatible: { string },
+ timescale: number,
+ duration: number, -- seconds
+ tracks: { Track },
+ boxes: { Box.Box },
+ moov: Box.Box?,
+ fragmented: boolean,
+}
+
+-- parse(r, opts) -> Movie | nil, Err: the box tree, ftyp, mvhd and every track (fragments included)
+function Demux.parse(r: Bytes.Reader, opts: Options?): (Movie?, Err.Err?)
+ local o = opts or {}
+ local b = r.buf
+ local top, terr = Box.list(b, r.base, r.limit)
+ if #top == 0 then
+ return nil, terr or Err.new(Err.CORRUPT, "no boxes", r.base)
+ end
+ local m: Movie = { compatible = {}, timescale = 1000, duration = 0, tracks = {}, boxes = top, fragmented = false }
+ local ftyp = Box.child({ children = top } :: any, "ftyp")
+ if ftyp and ftyp.data + 8 <= ftyp.stop then
+ m.brand = readstring(b, ftyp.data, 4)
+ m.minor = Box.be32(b, ftyp.data + 4)
+ local p = ftyp.data + 8
+ while p + 4 <= ftyp.stop do
+ table.insert(m.compatible, readstring(b, p, 4))
+ p += 4
+ end
+ end
+ local moov = Box.child({ children = top } :: any, "moov")
+ m.moov = moov
+ if not moov then
+ return m, nil -- an image file (HEIF / AVIF) or a fragment: no tracks
+ end
+ local mvhd = Box.child(moov, "mvhd")
+ local movieDuration = 0
+ if mvhd then
+ local q = reader(b, mvhd)
+ local v = q:u8()
+ q:skip(3)
+ if v == 1 then
+ q:skip(16)
+ m.timescale = q:u32be()
+ movieDuration = q:u64be()
+ else
+ q:skip(8)
+ m.timescale = q:u32be()
+ movieDuration = q:u32be()
+ end
+ if q.err or m.timescale == 0 then
+ m.timescale = 1000
+ end
+ end
+ local trex = {}
+ local mvex = Box.child(moov, "mvex")
+ if mvex then
+ m.fragmented = true
+ for _, x in Box.childrenOf(mvex, "trex") do
+ local q = reader(b, x)
+ q:skip(4)
+ local id = q:u32be()
+ q:skip(4)
+ local d = { duration = q:u32be(), size = q:u32be(), flags = q:u32be() }
+ if not q.err then
+ trex[id] = d
+ end
+ end
+ end
+ local byId = {}
+ for _, trak in Box.childrenOf(moov, "trak") do
+ local t, err = track(b, trak, m.timescale, trex, o)
+ if not t then
+ return nil, err
+ end
+ table.insert(m.tracks, t)
+ byId[t.id] = t
+ end
+ if m.fragmented then
+ local ferr = fragments(b, r.base, top, byId, o)
+ if ferr then
+ return nil, ferr
+ end
+ end
+ -- durations; drop samples outside the buffer (a truncated file) but keep what is there
+ for _, t in m.tracks do
+ local n = t.sampleCount
+ local ticks = t.mediaDuration
+ if n > 0 then
+ ticks = math.max(ticks, t.dts[n] + t.durations[n])
+ end
+ t.mediaDuration = ticks
+ t.duration = ticks / t.timescale
+ for i = 1, n do
+ local off = t.offsets[i]
+ if off < 0 or off + t.sizes[i] > r.limit - r.base then
+ t.sampleCount = i - 1
+ t.truncated = true
+ break
+ end
+ end
+ -- the tables hold file offsets; make them buffer offsets
+ local base = r.base
+ if base ~= 0 then
+ local offs = t.offsets
+ for i = 1, t.sampleCount do
+ offs[i] += base
+ end
+ end
+ end
+ m.duration = movieDuration / m.timescale
+ if m.duration == 0 then
+ for _, t in m.tracks do
+ m.duration = math.max(m.duration, t.duration)
+ end
+ end
+ return m, nil
+end
+
+return Demux
diff --git a/src/Formats/containers/IsoBmff/Meta.luau b/src/Formats/containers/IsoBmff/Meta.luau
new file mode 100644
index 0000000..a7c44ca
--- /dev/null
+++ b/src/Formats/containers/IsoBmff/Meta.luau
@@ -0,0 +1,526 @@
+--!strict
+-- containers/IsoBmff/Meta: the metadata boxes. HEIF / AVIF items (ISO/IEC 23008-12: pitm, iinf / infe, iloc
+-- versions 0 - 2, iref, iprp / ipco / ipma, idat; the common properties ispe / pixi / colr / irot / imir / clap / auxC
+-- decoded, codec configurations av1C / hvcC / avcC kept raw) and the iTunes tags (udta / meta / ilst: text, trkn /
+-- disk, tmpo / cpil, gnre, covr pictures, '----' freeform), plus the ilst writer used by the muxer.
+-- Never throws.
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Box = require("@formats/containers/IsoBmff/Box")
+
+local readstring = buffer.readstring
+
+local Meta = {}
+
+local function reader(b: buffer, box: Box.Box): Bytes.Reader
+ return Bytes.reader(b, box.data, box.stop - box.data)
+end
+
+local function uint(r: Bytes.Reader, size: number): number
+ if size == 0 then
+ return 0
+ elseif size == 4 then
+ return r:u32be()
+ elseif size == 8 then
+ return r:u64be()
+ elseif size == 2 then
+ return r:u16be()
+ elseif size == 1 then
+ return r:u8()
+ end
+ r:fail(Err.CORRUPT, "bad iloc field size " .. size)
+ return 0
+end
+
+-- ------------------------------------------------------------------------------------------------ HEIF items
+export type Property = { type: string, box: Box.Box, [string]: any }
+export type Item = {
+ id: number,
+ type: string, -- "av01", "hvc1", "grid", "Exif", "mime", ...
+ name: string,
+ contentType: string?,
+ hidden: boolean,
+ construction: number, -- iloc construction method (0 file offset, 1 idat, 2 item)
+ baseOffset: number,
+ extents: { { offset: number, length: number } },
+ properties: { Property }, -- in ipma order
+ essential: { [number]: boolean }, -- by index into properties
+ refs: { [string]: { number } }, -- iref type -> item ids (dimg, thmb, auxl, cdsc, ...)
+}
+export type Items = {
+ primary: number?,
+ items: { [number]: Item },
+ order: { number }, -- item ids in iinf order
+ idat: Box.Box?,
+ properties: { Property }, -- ipco, in order
+}
+
+local function property(b: buffer, box: Box.Box): Property
+ local p: Property = { type = box.type, box = box }
+ local r = reader(b, box)
+ local t = box.type
+ if t == "ispe" then
+ r:skip(4)
+ p.width, p.height = r:u32be(), r:u32be()
+ elseif t == "pixi" then
+ r:skip(4)
+ local n = r:u8()
+ local bits = {}
+ for i = 1, math.min(n, 16) do
+ bits[i] = r:u8()
+ end
+ p.bits = bits
+ elseif t == "colr" then
+ local ct = r:string(4)
+ p.colourType = ct
+ if ct == "nclx" then
+ p.primaries, p.transfer, p.matrix = r:u16be(), r:u16be(), r:u16be()
+ p.fullRange = bit32.band(r:u8(), 0x80) ~= 0
+ elseif ct == "rICC" or ct == "prof" then
+ p.icc = r:bytes(r:remaining())
+ end
+ elseif t == "irot" then
+ p.angle = bit32.band(r:u8(), 3) * 90
+ elseif t == "imir" then
+ p.axis = bit32.band(r:u8(), 1)
+ elseif t == "clap" then
+ local function frac(): number
+ local n, d = r:i32be(), r:u32be()
+ return if d == 0 then 0 else n / d
+ end
+ p.width, p.height, p.horizOff, p.vertOff = frac(), frac(), frac(), frac()
+ elseif t == "auxC" then
+ r:skip(4)
+ p.auxType = r:cstring()
+ else
+ local n = box.stop - box.data
+ local cfg = buffer.create(math.max(0, n))
+ if n > 0 then
+ buffer.copy(cfg, 0, b, box.data, n)
+ end
+ p.config = cfg
+ end
+ return p
+end
+
+-- items(buf, meta) -> Items | nil, Err (meta: a top-level 'meta' box)
+function Meta.items(b: buffer, meta: Box.Box): (Items?, Err.Err?)
+ local out: Items = { items = {}, order = {}, properties = {} }
+ local pitm = Box.child(meta, "pitm")
+ if pitm then
+ local r = reader(b, pitm)
+ local v = r:u8()
+ r:skip(3)
+ out.primary = if v == 0 then r:u16be() else r:u32be()
+ end
+ local iinf = Box.child(meta, "iinf")
+ if iinf then
+ for _, infe in Box.childrenOf(iinf, "infe") do
+ local r = reader(b, infe)
+ local v = r:u8()
+ local flags = r:u24be()
+ local it: Item = {
+ id = 0, type = "", name = "", hidden = bit32.band(flags, 1) ~= 0, construction = 0, baseOffset = 0,
+ extents = {}, properties = {}, essential = {}, refs = {},
+ }
+ if v >= 2 then
+ it.id = if v == 2 then r:u16be() else r:u32be()
+ r:skip(2)
+ it.type = r:string(4)
+ it.name = r:cstring()
+ if it.type == "mime" and r:remaining() > 0 then
+ it.contentType = r:cstring()
+ end
+ else
+ it.id = r:u16be()
+ r:skip(2)
+ it.name = r:cstring()
+ it.contentType = r:cstring()
+ it.type = "mime"
+ end
+ if r.err and it.id == 0 then
+ return nil, r.err
+ end
+ out.items[it.id] = it
+ table.insert(out.order, it.id)
+ end
+ end
+ local iloc = Box.child(meta, "iloc")
+ if iloc then
+ local r = reader(b, iloc)
+ local v = r:u8()
+ r:skip(3)
+ local a, c = r:u8(), r:u8()
+ local offSize, lenSize, baseSize = bit32.rshift(a, 4), bit32.band(a, 15), bit32.rshift(c, 4)
+ local idxSize = if v >= 1 then bit32.band(c, 15) else 0
+ local n = if v < 2 then r:u16be() else r:u32be()
+ if r.err then
+ return nil, r.err
+ end
+ for _ = 1, n do
+ local id = if v < 2 then r:u16be() else r:u32be()
+ local method = 0
+ if v >= 1 then
+ method = bit32.band(r:u16be(), 15)
+ end
+ r:skip(2) -- data reference index
+ local base = uint(r, baseSize)
+ local ne = r:u16be()
+ if r.err then
+ return nil, r.err
+ end
+ if ne * (offSize + lenSize + idxSize) > r:remaining() then
+ return nil, Err.new(Err.TRUNCATED, "iloc extents run past the box", iloc.start)
+ end
+ local extents = {}
+ for k = 1, ne do
+ if idxSize > 0 then
+ uint(r, idxSize)
+ end
+ extents[k] = { offset = base + uint(r, offSize), length = uint(r, lenSize) }
+ end
+ if r.err then
+ return nil, r.err
+ end
+ local it = out.items[id]
+ if not it then
+ it = {
+ id = id, type = "", name = "", hidden = false, construction = 0, baseOffset = 0, extents = {},
+ properties = {}, essential = {}, refs = {},
+ }
+ out.items[id] = it
+ table.insert(out.order, id)
+ end
+ it.construction, it.baseOffset, it.extents = method, base, extents
+ end
+ end
+ local iref = Box.child(meta, "iref")
+ if iref then
+ local v = Box.fullHeader(b, iref)
+ for _, ref in (iref.children or {}) :: { Box.Box } do
+ local r = reader(b, ref)
+ local from = if v == 0 then r:u16be() else r:u32be()
+ local n = r:u16be()
+ local to = {}
+ for k = 1, n do
+ to[k] = if v == 0 then r:u16be() else r:u32be()
+ end
+ local it = out.items[from]
+ if it and not r.err then
+ it.refs[ref.type] = to
+ end
+ end
+ end
+ local ipco = Box.path(meta, "iprp/ipco")
+ if ipco and ipco.children then
+ for i, pb in ipco.children :: { Box.Box } do
+ out.properties[i] = property(b, pb)
+ end
+ end
+ local ipma = Box.path(meta, "iprp/ipma")
+ if ipma then
+ local r = reader(b, ipma)
+ local v = r:u8()
+ local flags = r:u24be()
+ local n = r:u32be()
+ for _ = 1, n do
+ if r.err then
+ break
+ end
+ local id = if v < 1 then r:u16be() else r:u32be()
+ local na = r:u8()
+ local it = out.items[id]
+ for _ = 1, na do
+ local idx, ess
+ if bit32.band(flags, 1) ~= 0 then
+ local x = r:u16be()
+ idx, ess = bit32.band(x, 0x7FFF), x >= 0x8000
+ else
+ local x = r:u8()
+ idx, ess = bit32.band(x, 0x7F), x >= 0x80
+ end
+ local p = out.properties[idx]
+ if it and p and not r.err then
+ table.insert(it.properties, p)
+ if ess then
+ it.essential[#it.properties] = true
+ end
+ end
+ end
+ end
+ end
+ out.idat = Box.child(meta, "idat")
+ return out, nil
+end
+
+-- itemData(buf, base, limit, items, id) -> buffer | nil, Err: the item's bytes (extents concatenated); base / limit
+-- bound the file in the buffer
+function Meta.itemData(b: buffer, base: number, limit: number, items: Items, id: number): (buffer?, Err.Err?)
+ local it = items.items[id]
+ if not it then
+ return nil, Err.new(Err.CORRUPT, "no item " .. id)
+ end
+ local origin, stop
+ if it.construction == 0 then
+ origin, stop = base, limit
+ elseif it.construction == 1 then
+ local idat = items.idat
+ if not idat then
+ return nil, Err.new(Err.CORRUPT, "item " .. id .. " is in a missing idat")
+ end
+ origin, stop = idat.data, idat.stop
+ else
+ return nil, Err.new(Err.UNSUPPORTED, "item construction method " .. it.construction)
+ end
+ local total = 0
+ for _, e in it.extents do
+ local len = e.length
+ if len == 0 then -- the whole rest of the file
+ len = stop - origin - e.offset
+ end
+ if e.offset < 0 or len < 0 or origin + e.offset + len > stop then
+ return nil, Err.new(Err.TRUNCATED, "item " .. id .. " runs past the end")
+ end
+ total += len
+ end
+ if total > 2 ^ 30 then
+ return nil, Err.new(Err.LIMIT, "item " .. id .. " is too big")
+ end
+ local out = buffer.create(total)
+ local p = 0
+ for _, e in it.extents do
+ local len = if e.length == 0 then stop - origin - e.offset else e.length
+ buffer.copy(out, p, b, origin + e.offset, len)
+ p += len
+ end
+ return out, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ iTunes tags
+-- ilst item -> standard tag name
+local TAG: { [string]: string } = {
+ ["\169nam"] = "title", ["\169ART"] = "artist", aART = "albumartist", ["\169alb"] = "album", ["\169day"] = "date",
+ ["\169gen"] = "genre", ["\169cmt"] = "comment", ["\169wrt"] = "composer", ["\169too"] = "encoder",
+ ["\169lyr"] = "lyrics", ["\169grp"] = "grouping", cprt = "copyright", desc = "description", ldes = "longdescription",
+ sonm = "titlesort", soar = "artistsort", soal = "albumsort", soaa = "albumartistsort", soco = "composersort",
+ tvsh = "show", ["\169st3"] = "subtitle", ["\169wrk"] = "work", ["\169mvn"] = "movement", purd = "purchasedate",
+ ["\169pub"] = "publisher", ["\169xyz"] = "location",
+}
+local TAG_ATOM: { [string]: string } = {}
+for atom, name in TAG do
+ TAG_ATOM[name] = atom
+end
+Meta.TAG = TAG
+Meta.TAG_ATOM = TAG_ATOM
+
+-- the ID3v1 genres gnre indexes (1-based in gnre)
+local GENRES = {
+ "Blues", "Classic Rock", "Country", "Dance", "Disco", "Funk", "Grunge", "Hip-Hop", "Jazz", "Metal", "New Age",
+ "Oldies", "Other", "Pop", "R&B", "Rap", "Reggae", "Rock", "Techno", "Industrial", "Alternative", "Ska",
+ "Death Metal", "Pranks", "Soundtrack", "Euro-Techno", "Ambient", "Trip-Hop", "Vocal", "Jazz+Funk", "Fusion",
+ "Trance", "Classical", "Instrumental", "Acid", "House", "Game", "Sound Clip", "Gospel", "Noise", "AlternRock",
+ "Bass", "Soul", "Punk", "Space", "Meditative", "Instrumental Pop", "Instrumental Rock", "Ethnic", "Gothic",
+ "Darkwave", "Techno-Industrial", "Electronic", "Pop-Folk", "Eurodance", "Dream", "Southern Rock", "Comedy", "Cult",
+ "Gangsta", "Top 40", "Christian Rap", "Pop/Funk", "Jungle", "Native American", "Cabaret", "New Wave",
+ "Psychadelic", "Rave", "Showtunes", "Trailer", "Lo-Fi", "Tribal", "Acid Punk", "Acid Jazz", "Polka", "Retro",
+ "Musical", "Rock & Roll", "Hard Rock",
+}
+
+export type Picture = { mime: string, data: buffer }
+
+-- tags(buf, ilst) -> Tags, { Picture }
+function Meta.tags(b: buffer, ilst: Box.Box?): ({ [string]: string }, { Picture })
+ local tags: { [string]: string } = {}
+ local pics: { Picture } = {}
+ if not ilst or not ilst.children then
+ return tags, pics
+ end
+ for _, item in ilst.children :: { Box.Box } do
+ local typ = item.type
+ local freeName: string? = nil
+ if typ == "----" then
+ local nm = Box.child(item, "name")
+ if nm and nm.data + 4 <= nm.stop then
+ freeName = readstring(b, nm.data + 4, nm.stop - nm.data - 4)
+ end
+ end
+ for _, d in Box.childrenOf(item, "data") do
+ if d.data + 8 > d.stop then
+ continue
+ end
+ local kind = bit32.band(Box.be32(b, d.data), 0xFFFFFF)
+ local p, n = d.data + 8, d.stop - d.data - 8
+ if typ == "trkn" or typ == "disk" then
+ if n >= 6 then
+ local num = Box.be32(b, p) % 65536
+ local total = Box.be32(b, p + 2) % 65536
+ local key = if typ == "trkn" then "track" else "disc"
+ if num > 0 then
+ tags[key] = tostring(num)
+ end
+ if total > 0 then
+ tags[key .. "total"] = tostring(total)
+ end
+ end
+ elseif typ == "gnre" then
+ if n >= 2 then
+ local g = GENRES[Box.be32(b, p - 2) % 65536]
+ if g and not tags.genre then
+ tags.genre = g
+ end
+ end
+ elseif typ == "tmpo" then
+ if n >= 2 then
+ tags.bpm = tostring(Box.be32(b, p - 2) % 65536)
+ end
+ elseif typ == "cpil" or typ == "pgap" then
+ if n >= 1 then
+ tags[if typ == "cpil" then "compilation" else "gapless"] = tostring(buffer.readu8(b, p))
+ end
+ elseif typ == "covr" then
+ local mime = if kind == 14 then "image/png" elseif kind == 27 then "image/bmp" else "image/jpeg"
+ local data = buffer.create(n)
+ buffer.copy(data, 0, b, p, n)
+ table.insert(pics, { mime = mime, data = data })
+ elseif kind == 1 or kind == 0 then
+ local s = readstring(b, p, n)
+ local key = freeName or TAG[typ] or typ
+ if typ == "\169gen" or not tags[key] then
+ tags[key] = s
+ end
+ end
+ end
+ end
+ return tags, pics
+end
+
+-- ------------------------------------------------------------------------------------------------ ilst writer
+local function box(w: Bytes.Writer, typ: string, body: (Bytes.Writer) -> ())
+ local start = w:tell()
+ w:u32be(0)
+ w:string(typ)
+ body(w)
+ w:setU32be(start, w:tell() - start)
+end
+Meta.box = box
+
+local function dataBox(w: Bytes.Writer, kind: number, value: string | buffer)
+ box(w, "data", function()
+ w:u32be(kind)
+ w:u32be(0)
+ if type(value) == "string" then
+ w:string(value)
+ else
+ w:bytes(value)
+ end
+ end)
+end
+
+local function num(s: string?): number
+ local v = tonumber(s or "")
+ if not v then
+ return 0
+ end
+ return math.clamp(math.floor(v), 0, 65535)
+end
+
+-- writeIlst(w, tags, pictures?): an ilst box with the tags (standard names -> iTunes atoms; unknown names -> '----'
+-- freeform com.apple.iTunes items) and cover pictures
+function Meta.writeIlst(w: Bytes.Writer, tags: { [string]: string }, pictures: { Picture }?)
+ box(w, "ilst", function()
+ local keys = {}
+ for k in tags do
+ table.insert(keys, k)
+ end
+ table.sort(keys)
+ local done: { [string]: boolean } = {}
+ for _, k in keys do
+ local v = tags[k]
+ if type(v) ~= "string" or done[k] then
+ continue
+ end
+ if k == "track" or k == "tracktotal" or k == "disc" or k == "disctotal" then
+ local base = if k == "track" or k == "tracktotal" then "track" else "disc"
+ if done[base] then
+ continue
+ end
+ done[base] = true
+ local atom = if base == "track" then "trkn" else "disk"
+ local n, total = num(tags[base]), num(tags[base .. "total"])
+ box(w, atom, function()
+ box(w, "data", function()
+ w:u32be(0)
+ w:u32be(0)
+ w:u16be(0)
+ w:u16be(n)
+ w:u16be(total)
+ if atom == "trkn" then
+ w:u16be(0)
+ end
+ end)
+ end)
+ elseif k == "bpm" then
+ box(w, "tmpo", function()
+ box(w, "data", function()
+ w:u32be(21)
+ w:u32be(0)
+ w:u16be(num(v))
+ end)
+ end)
+ elseif k == "compilation" or k == "gapless" then
+ box(w, if k == "compilation" then "cpil" else "pgap", function()
+ box(w, "data", function()
+ w:u32be(21)
+ w:u32be(0)
+ w:u8(if num(v) ~= 0 then 1 else 0)
+ end)
+ end)
+ elseif TAG_ATOM[k] then
+ box(w, TAG_ATOM[k], function()
+ dataBox(w, 1, v)
+ end)
+ else
+ box(w, "----", function()
+ box(w, "mean", function()
+ w:u32be(0)
+ w:string("com.apple.iTunes")
+ end)
+ box(w, "name", function()
+ w:u32be(0)
+ w:string(k)
+ end)
+ dataBox(w, 1, v)
+ end)
+ end
+ done[k] = true
+ end
+ if pictures and #pictures > 0 then
+ box(w, "covr", function()
+ for _, p in pictures do
+ dataBox(w, if p.mime == "image/png" then 14 elseif p.mime == "image/bmp" then 27 else 13, p.data)
+ end
+ end)
+ end
+ end)
+end
+
+-- writeUdta(w, tags, pictures?): udta / meta (hdlr mdir) / ilst
+function Meta.writeUdta(w: Bytes.Writer, tags: { [string]: string }, pictures: { Picture }?)
+ box(w, "udta", function()
+ box(w, "meta", function()
+ w:u32be(0)
+ box(w, "hdlr", function()
+ w:u32be(0)
+ w:u32be(0)
+ w:string("mdir")
+ w:string("appl")
+ w:u32be(0)
+ w:u32be(0)
+ w:u8(0)
+ end)
+ Meta.writeIlst(w, tags, pictures)
+ end)
+ end)
+end
+
+return Meta
diff --git a/src/Formats/containers/IsoBmff/Mux.luau b/src/Formats/containers/IsoBmff/Mux.luau
new file mode 100644
index 0000000..299cc44
--- /dev/null
+++ b/src/Formats/containers/IsoBmff/Mux.luau
@@ -0,0 +1,519 @@
+--!strict
+-- containers/IsoBmff/Mux: writes a progressive (non-fragmented) ISO BMFF / MP4 / M4A file: ftyp, moov (mvhd, one trak
+-- per track with tkhd / edts / mdia / mdhd / hdlr / minf / [sv]mhd / dinf / stbl), the samples interleaved in chunks
+-- in one mdat, and udta / meta / ilst tags. moov goes first ("fast start"); co64 replaces stco past 4 GB. Sample
+-- entries: audio (mp4a + esds, alac, Opus + dOps, fLaC + dfLa, ...) and video (avc1 / hvc1 / av01 / vp09 / ... +
+-- their configuration box), plus any raw child boxes. Never throws: bad specs return nil, Err.ARG.
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Meta = require("@formats/containers/IsoBmff/Meta")
+
+local Mux = {}
+
+export type MuxTrack = {
+ kind: "audio" | "video" | "subtitle" | "data",
+ entry: string, -- sample entry fourcc: "alac", "mp4a", "Opus", "fLaC", "avc1", "hvc1", "av01", "vp09", ...
+ timescale: number, -- ticks per second (audio: the sample rate)
+ samples: { buffer }?, -- one buffer per sample, or
+ data: buffer?, -- the samples back to back, with
+ sizes: { number }?, -- their sizes
+ durations: { number } | number, -- ticks per sample (or one constant)
+ cts: { number }?, -- composition offsets (video with B-frames)
+ sync: { [number]: boolean }?, -- sync samples (nil: all)
+ sampleRate: number?,
+ channels: number?,
+ bitsPerSample: number?, -- default 16
+ width: number?,
+ height: number?,
+ config: buffer?, -- the codec configuration, written as the entry's configuration box
+ configBox: string?, -- its box type (default by entry: esds, alac, dOps, dfLa, avcC, hvcC, av1C, vpcC)
+ objectType: number?, -- esds objectTypeIndication (default 0x40, AAC)
+ bitrate: number?, -- esds average bitrate
+ boxes: { { type: string, data: buffer } }?, -- extra sample entry child boxes (raw payloads)
+ language: string?, -- ISO 639-2, default "und"
+ name: string?, -- hdlr name
+ skip: number?, -- media ticks to skip at the start (edit list media time: AAC priming)
+ playDuration: number?, -- media ticks to play (edit list)
+}
+export type MuxSpec = {
+ brand: string?, -- default "isom"
+ minor: number?,
+ compatible: { string }?,
+ timescale: number?, -- movie timescale, default 1000
+ tracks: { MuxTrack },
+ tags: { [string]: string }?,
+ pictures: { Meta.Picture }?,
+ chunkDuration: number?, -- seconds of samples per chunk, default 1
+}
+
+local DEFAULT_CONFIG_BOX: { [string]: string } = {
+ mp4a = "esds", mp4v = "esds", alac = "alac", Opus = "dOps", fLaC = "dfLa", avc1 = "avcC", avc3 = "avcC",
+ hvc1 = "hvcC", hev1 = "hvcC", av01 = "av1C", vp08 = "vpcC", vp09 = "vpcC", ["ac-3"] = "dac3", ["ec-3"] = "dec3",
+}
+local FULL_BOX: { [string]: boolean } = { alac = true, dfLa = true, vpcC = true }
+local HANDLER = { audio = "soun", video = "vide", subtitle = "sbtl", data = "meta" }
+
+local box = Meta.box
+
+local function lang(s: string?): number
+ local l = s or "und"
+ if #l ~= 3 then
+ l = "und"
+ end
+ local v = 0
+ for i = 1, 3 do
+ v = v * 32 + bit32.band(string.byte(l, i) - 96, 31)
+ end
+ return v
+end
+
+local function descriptor(w: Bytes.Writer, tag: number, body: (Bytes.Writer) -> ())
+ local inner = Bytes.writer(64)
+ body(inner)
+ local n = inner:tell()
+ w:u8(tag)
+ -- 4-byte expandable length (the common iTunes / ffmpeg form)
+ w:u8(0x80 + bit32.band(bit32.rshift(n, 21), 127))
+ w:u8(0x80 + bit32.band(bit32.rshift(n, 14), 127))
+ w:u8(0x80 + bit32.band(bit32.rshift(n, 7), 127))
+ w:u8(bit32.band(n, 127))
+ w:bytes(inner.buf, 0, n)
+end
+
+local function esds(w: Bytes.Writer, t: MuxTrack)
+ box(w, "esds", function()
+ w:u32be(0)
+ descriptor(w, 3, function(d)
+ d:u16be(0) -- ES_ID
+ d:u8(0)
+ descriptor(d, 4, function(c)
+ c:u8(t.objectType or 0x40)
+ c:u8(if t.kind == "video" then 0x11 else 0x15) -- streamType << 2 | upStream 0 | reserved 1
+ c:u24be(0)
+ c:u32be(t.bitrate or 0)
+ c:u32be(t.bitrate or 0)
+ if t.config then
+ descriptor(c, 5, function(s)
+ s:bytes(t.config :: buffer)
+ end)
+ end
+ end)
+ descriptor(d, 6, function(s)
+ s:u8(2)
+ end)
+ end)
+ end)
+end
+
+local function sampleEntry(w: Bytes.Writer, t: MuxTrack)
+ box(w, t.entry, function()
+ w:fill(0, 6)
+ w:u16be(1) -- data reference index
+ if t.kind == "audio" then
+ w:u16be(0) -- version
+ w:u16be(0)
+ w:u32be(0)
+ w:u16be(t.channels or 2)
+ w:u16be(t.bitsPerSample or 16)
+ w:u16be(0)
+ w:u16be(0)
+ local sr = t.sampleRate or t.timescale
+ w:u32be(if sr < 65536 then sr * 65536 else 0)
+ elseif t.kind == "video" then
+ w:fill(0, 16)
+ w:u16be(t.width or 0)
+ w:u16be(t.height or 0)
+ w:u32be(0x00480000)
+ w:u32be(0x00480000)
+ w:u32be(0)
+ w:u16be(1) -- frame count
+ w:fill(0, 32) -- compressor name
+ w:u16be(0x18)
+ w:i16be(-1)
+ end
+ local cb = t.configBox or DEFAULT_CONFIG_BOX[t.entry]
+ if t.config and cb then
+ if cb == "esds" then
+ esds(w, t)
+ else
+ box(w, cb, function()
+ if FULL_BOX[cb] then
+ w:u32be(0)
+ end
+ w:bytes(t.config :: buffer)
+ end)
+ end
+ end
+ for _, x in t.boxes or {} do
+ box(w, x.type, function()
+ w:bytes(x.data)
+ end)
+ end
+ end)
+end
+
+type Chunk = { track: number, first: number, count: number, time: number, offset: number }
+
+-- runs of equal values: { { count, value } }
+local function runs(n: number, value: (number) -> number): { { number } }
+ local out = {}
+ for i = 1, n do
+ local v = value(i)
+ local last = out[#out]
+ if last and last[2] == v then
+ last[1] += 1
+ else
+ table.insert(out, { 1, v })
+ end
+ end
+ return out
+end
+
+type Prepared = {
+ t: MuxTrack,
+ n: number,
+ sizes: { number },
+ dur: (number) -> number,
+ total: number, -- media ticks
+ chunks: { Chunk },
+ sample: (number) -> (buffer, number), -- buffer, offset
+}
+
+local function moov(w: Bytes.Writer, spec: MuxSpec, prep: { Prepared }, co64: boolean)
+ local mts = spec.timescale or 1000
+ local function toMovie(p: Prepared, ticks: number): number
+ return math.floor(ticks * mts / p.t.timescale + 0.5)
+ end
+ local movieDur = 0
+ for _, p in prep do
+ local play = p.t.playDuration or (p.total - (p.t.skip or 0))
+ movieDur = math.max(movieDur, toMovie(p, play))
+ end
+ box(w, "moov", function()
+ box(w, "mvhd", function()
+ w:u32be(0)
+ w:u32be(0)
+ w:u32be(0)
+ w:u32be(mts)
+ w:u32be(movieDur)
+ w:u32be(0x00010000)
+ w:u16be(0x0100)
+ w:fill(0, 10)
+ for _, v in { 0x00010000, 0, 0, 0, 0x00010000, 0, 0, 0, 0x40000000 } do
+ w:u32be(v)
+ end
+ w:fill(0, 24)
+ w:u32be(#prep + 1)
+ end)
+ for id, p in prep do
+ local t = p.t
+ local play = t.playDuration or (p.total - (t.skip or 0))
+ box(w, "trak", function()
+ box(w, "tkhd", function()
+ w:u32be(3) -- enabled, in movie
+ w:u32be(0)
+ w:u32be(0)
+ w:u32be(id)
+ w:u32be(0)
+ w:u32be(toMovie(p, play))
+ w:fill(0, 8)
+ w:u16be(0)
+ w:u16be(0)
+ w:u16be(if t.kind == "audio" then 0x0100 else 0)
+ w:u16be(0)
+ for _, v in { 0x00010000, 0, 0, 0, 0x00010000, 0, 0, 0, 0x40000000 } do
+ w:u32be(v)
+ end
+ w:u32be((t.width or 0) * 65536)
+ w:u32be((t.height or 0) * 65536)
+ end)
+ if t.skip or t.playDuration then
+ box(w, "edts", function()
+ box(w, "elst", function()
+ w:u32be(0)
+ w:u32be(1)
+ w:u32be(toMovie(p, play))
+ w:u32be(t.skip or 0)
+ w:u32be(0x00010000)
+ end)
+ end)
+ end
+ box(w, "mdia", function()
+ box(w, "mdhd", function()
+ w:u32be(0)
+ w:u32be(0)
+ w:u32be(0)
+ w:u32be(t.timescale)
+ w:u32be(p.total)
+ w:u16be(lang(t.language))
+ w:u16be(0)
+ end)
+ box(w, "hdlr", function()
+ w:u32be(0)
+ w:u32be(0)
+ w:string(HANDLER[t.kind] or "meta")
+ w:fill(0, 12)
+ w:cstring(t.name or (if t.kind == "audio" then "SoundHandler" elseif t.kind == "video" then "VideoHandler" else "DataHandler"))
+ end)
+ box(w, "minf", function()
+ if t.kind == "audio" then
+ box(w, "smhd", function()
+ w:u32be(0)
+ w:u32be(0)
+ end)
+ elseif t.kind == "video" then
+ box(w, "vmhd", function()
+ w:u32be(1)
+ w:fill(0, 8)
+ end)
+ else
+ box(w, "nmhd", function()
+ w:u32be(0)
+ end)
+ end
+ box(w, "dinf", function()
+ box(w, "dref", function()
+ w:u32be(0)
+ w:u32be(1)
+ box(w, "url ", function()
+ w:u32be(1) -- self-contained
+ end)
+ end)
+ end)
+ box(w, "stbl", function()
+ box(w, "stsd", function()
+ w:u32be(0)
+ w:u32be(1)
+ sampleEntry(w, t)
+ end)
+ local stts = runs(p.n, p.dur)
+ box(w, "stts", function()
+ w:u32be(0)
+ w:u32be(#stts)
+ for _, r in stts do
+ w:u32be(r[1])
+ w:u32be(r[2])
+ end
+ end)
+ local cts = t.cts
+ if cts then
+ local cr = runs(p.n, function(i)
+ return cts[i] or 0
+ end)
+ box(w, "ctts", function()
+ w:u32be(0x01000000) -- version 1: signed offsets
+ w:u32be(#cr)
+ for _, r in cr do
+ w:u32be(r[1])
+ w:i32be(r[2])
+ end
+ end)
+ end
+ local sync = t.sync
+ if sync then
+ local list = {}
+ for i = 1, p.n do
+ if sync[i] then
+ table.insert(list, i)
+ end
+ end
+ box(w, "stss", function()
+ w:u32be(0)
+ w:u32be(#list)
+ for _, i in list do
+ w:u32be(i)
+ end
+ end)
+ end
+ local stsc = runs(#p.chunks, function(i)
+ return p.chunks[i].count
+ end)
+ box(w, "stsc", function()
+ w:u32be(0)
+ w:u32be(#stsc)
+ local c = 1
+ for _, r in stsc do
+ w:u32be(c)
+ w:u32be(r[2])
+ w:u32be(1)
+ c += r[1]
+ end
+ end)
+ box(w, "stsz", function()
+ w:u32be(0)
+ local fixed = p.sizes[1] or 0
+ for i = 2, p.n do
+ if p.sizes[i] ~= fixed then
+ fixed = -1
+ break
+ end
+ end
+ if fixed >= 0 and p.n > 0 then
+ w:u32be(fixed)
+ w:u32be(p.n)
+ else
+ w:u32be(0)
+ w:u32be(p.n)
+ for i = 1, p.n do
+ w:u32be(p.sizes[i])
+ end
+ end
+ end)
+ box(w, if co64 then "co64" else "stco", function()
+ w:u32be(0)
+ w:u32be(#p.chunks)
+ for _, c in p.chunks do
+ if co64 then
+ w:u64be(c.offset)
+ else
+ w:u32be(c.offset)
+ end
+ end
+ end)
+ end)
+ end)
+ end)
+ end)
+ end
+ if spec.tags and next(spec.tags) or spec.pictures and #spec.pictures > 0 then
+ Meta.writeUdta(w, spec.tags or {}, spec.pictures)
+ end
+ end)
+end
+
+-- mux(spec) -> buffer | nil, Err
+function Mux.mux(spec: MuxSpec): (buffer?, Err.Err?)
+ if type(spec) ~= "table" or type(spec.tracks) ~= "table" or #spec.tracks == 0 then
+ return nil, Err.new(Err.ARG, "mux: expected { tracks = { ... } }")
+ end
+ local prep: { Prepared } = {}
+ local all: { Chunk } = {}
+ for k, t in spec.tracks do
+ if type(t) ~= "table" or type(t.entry) ~= "string" or #t.entry ~= 4 or type(t.timescale) ~= "number" or t.timescale <= 0 then
+ return nil, Err.new(Err.ARG, "mux: track " .. k .. " needs a 4-character entry and a timescale")
+ end
+ if not HANDLER[t.kind] then
+ return nil, Err.new(Err.ARG, "mux: track " .. k .. ": bad kind " .. tostring(t.kind))
+ end
+ local n, sizes, sample
+ if t.samples then
+ local list = t.samples
+ n = #list
+ sizes = table.create(n, 0)
+ for i = 1, n do
+ if type(list[i]) ~= "buffer" then
+ return nil, Err.new(Err.ARG, "mux: track " .. k .. ": sample " .. i .. " is not a buffer")
+ end
+ sizes[i] = buffer.len(list[i])
+ end
+ sample = function(i: number): (buffer, number)
+ return list[i], 0
+ end
+ elseif t.data and t.sizes then
+ n = #t.sizes
+ sizes = t.sizes
+ local starts = table.create(n, 0)
+ local o = 0
+ for i = 1, n do
+ starts[i] = o
+ o += sizes[i]
+ end
+ if o > buffer.len(t.data) then
+ return nil, Err.new(Err.ARG, "mux: track " .. k .. ": sizes exceed the data")
+ end
+ local data = t.data
+ sample = function(i: number): (buffer, number)
+ return data, starts[i]
+ end
+ else
+ return nil, Err.new(Err.ARG, "mux: track " .. k .. " needs samples or data + sizes")
+ end
+ local durs = t.durations
+ local dur
+ if type(durs) == "number" then
+ dur = function(_: number): number
+ return durs
+ end
+ elseif type(durs) == "table" then
+ dur = function(i: number): number
+ return durs[i] or 0
+ end
+ else
+ return nil, Err.new(Err.ARG, "mux: track " .. k .. " needs durations")
+ end
+ local total = 0
+ local chunks: { Chunk } = {}
+ local per = (spec.chunkDuration or 1) * t.timescale
+ local cur: Chunk? = nil
+ for i = 1, n do
+ if not cur or total - cur.time >= per then
+ cur = { track = k, first = i, count = 0, time = total, offset = 0 }
+ table.insert(chunks, cur :: Chunk)
+ table.insert(all, cur :: Chunk)
+ end
+ (cur :: Chunk).count += 1
+ total += dur(i)
+ end
+ prep[k] = { t = t, n = n, sizes = sizes, dur = dur, total = total, chunks = chunks, sample = sample }
+ end
+ -- interleave the chunks by time
+ table.sort(all, function(a: Chunk, b: Chunk): boolean
+ local ta = a.time / prep[a.track].t.timescale
+ local tb = b.time / prep[b.track].t.timescale
+ if ta ~= tb then
+ return ta < tb
+ end
+ if a.track ~= b.track then
+ return a.track < b.track
+ end
+ return a.first < b.first
+ end)
+ local mdatSize = 0
+ for _, c in all do
+ local p = prep[c.track]
+ for i = c.first, c.first + c.count - 1 do
+ mdatSize += p.sizes[i]
+ end
+ end
+ local co64 = mdatSize > 4294967295 - 2 ^ 24
+ -- ftyp
+ local w = Bytes.writer(mdatSize + 4096)
+ box(w, "ftyp", function()
+ w:string(spec.brand or "isom")
+ w:u32be(spec.minor or 0x200)
+ for _, c in spec.compatible or { spec.brand or "isom", "iso2", "mp41" } do
+ w:string(string.sub(c .. " ", 1, 4))
+ end
+ end)
+ -- moov twice: the first pass measures it, the second has the real chunk offsets
+ local probe = Bytes.writer(4096)
+ moov(probe, spec, prep, co64)
+ local mdatHeader = if mdatSize + 8 > 4294967295 then 16 else 8
+ local o = w:tell() + probe:tell() + mdatHeader
+ for _, c in all do
+ c.offset = o
+ local p = prep[c.track]
+ for i = c.first, c.first + c.count - 1 do
+ o += p.sizes[i]
+ end
+ end
+ moov(w, spec, prep, co64)
+ if mdatHeader == 16 then
+ w:u32be(1)
+ w:string("mdat")
+ w:u64be(mdatSize + 16)
+ else
+ w:u32be(mdatSize + 8)
+ w:string("mdat")
+ end
+ for _, c in all do
+ local p = prep[c.track]
+ for i = c.first, c.first + c.count - 1 do
+ local b, off = p.sample(i)
+ w:bytes(b, off, p.sizes[i])
+ end
+ end
+ return w:finish(), nil
+end
+
+return Mux
diff --git a/src/Formats/containers/IsoBmff/init.luau b/src/Formats/containers/IsoBmff/init.luau
new file mode 100644
index 0000000..dab62b9
--- /dev/null
+++ b/src/Formats/containers/IsoBmff/init.luau
@@ -0,0 +1,188 @@
+--!strict
+-- containers/IsoBmff: ISO base media file format (ISO/IEC 14496-12) and its relatives: MP4 / M4A / M4V / MOV (QuickTime)
+-- / 3GP, fragmented MP4 (moof), HEIF / AVIF items (ISO/IEC 23008-12), iTunes tags. A container (layer 2): m4a, mp4,
+-- mov, heif, avif build on it. Written from the specifications; no third-party code.
+--
+-- local IsoBmff = require("@formats/containers/IsoBmff")
+-- local movie, err = IsoBmff.parse(r) -- ftyp brand, tracks (Demux.Track: codec, config, sample tables)
+-- local dmx = IsoBmff.demux(r) -- Types.Demuxer: tracks, duration, packets(trackId?), seek(s)
+-- local tags, pictures = IsoBmff.tags(r, movie) -- moov/udta/meta/ilst (or a top-level meta)
+-- local items = IsoBmff.items(r, movie) -- HEIF / AVIF: primary item, items, properties, refs
+-- local data = IsoBmff.itemData(r, items, id) -- an item's bytes
+-- local file = IsoBmff.mux({ brand = "M4A ", tracks = { { kind = "audio", entry = "alac", ... } }, tags = ... })
+--
+-- Sample offsets in tracks are absolute offsets into r.buf (r may cover part of a bigger buffer). Supports: 32 / 64-bit
+-- boxes, stsz / stz2, stco / co64, ctts v0 / v1, stss, elst v0 / v1, QuickTime sound descriptions v1 / v2 and 'wave',
+-- fragments with trex defaults / tfdt / data offsets. Not supported: external data references (dref urls),
+-- encrypted tracks (sinf / senc are left to the caller), fragmented writing. Never throws.
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Box = require("@formats/containers/IsoBmff/Box")
+local Demux = require("@formats/containers/IsoBmff/Demux")
+local Meta = require("@formats/containers/IsoBmff/Meta")
+local Mux = require("@formats/containers/IsoBmff/Mux")
+
+local IsoBmff = {}
+IsoBmff.Box = Box
+IsoBmff.Demux = Demux
+IsoBmff.Meta = Meta
+
+export type Track = Demux.Track
+export type Movie = Demux.Movie
+export type Items = Meta.Items
+export type Item = Meta.Item
+export type MuxSpec = Mux.MuxSpec
+export type MuxTrack = Mux.MuxTrack
+export type Picture = Meta.Picture
+
+local TOP: { [string]: boolean } = {
+ ftyp = true, moov = true, mdat = true, free = true, skip = true, wide = true, pnot = true, moof = true,
+ styp = true, sidx = true, meta = true, uuid = true, PICT = true,
+}
+
+-- sniff(r) -> brand ("M4A ", "isom", "qt ", "avif", "heic", ...) or "" when the file starts with another top-level box,
+-- nil when it is not an ISO BMFF file
+function IsoBmff.sniff(r: Bytes.Reader): string?
+ local head = r:peek(12)
+ if #head < 8 then
+ return nil
+ end
+ local typ = string.sub(head, 5, 8)
+ if typ == "ftyp" then
+ return if #head >= 12 then string.sub(head, 9, 12) else ""
+ end
+ if TOP[typ] then
+ local size = string.byte(head, 1) * 16777216 + string.byte(head, 2) * 65536 + string.byte(head, 3) * 256 + string.byte(head, 4)
+ if size == 1 or size == 0 or size >= 8 then
+ return ""
+ end
+ end
+ return nil
+end
+
+-- parse(r, opts?) -> Movie | nil, Err
+function IsoBmff.parse(r: Bytes.Reader, opts: Demux.Options?): (Movie?, Err.Err?)
+ return Demux.parse(r, opts)
+end
+
+-- tags(r, movie) -> Tags, { Picture }: iTunes tags from moov/udta/meta/ilst (or moov/meta/ilst, or a top-level meta)
+function IsoBmff.tags(r: Bytes.Reader, movie: Movie): ({ [string]: string }, { Picture })
+ local ilst = Box.path(movie.boxes, "moov/udta/meta/ilst") or Box.path(movie.boxes, "moov/meta/ilst") or Box.path(movie.boxes, "meta/ilst")
+ return Meta.tags(r.buf, ilst)
+end
+
+-- items(r, movie) -> Items | nil, Err (the top-level meta box of a HEIF / AVIF file)
+function IsoBmff.items(r: Bytes.Reader, movie: Movie): (Items?, Err.Err?)
+ local meta = Box.path(movie.boxes, "meta")
+ if not meta then
+ return nil, Err.new(Err.CORRUPT, "no top-level meta box")
+ end
+ return Meta.items(r.buf, meta)
+end
+
+-- itemData(r, items, id) -> buffer | nil, Err
+function IsoBmff.itemData(r: Bytes.Reader, items: Items, id: number): (buffer?, Err.Err?)
+ return Meta.itemData(r.buf, r.base, r.limit, items, id)
+end
+
+-- sample(r, track, i) -> a copy of sample i (1-based)
+function IsoBmff.sample(r: Bytes.Reader, t: Track, i: number): buffer?
+ if i < 1 or i > t.sampleCount then
+ return nil
+ end
+ local n = t.sizes[i]
+ local out = buffer.create(n)
+ buffer.copy(out, 0, r.buf, t.offsets[i], n)
+ return out
+end
+
+-- demux(r, opts?) -> Types.Demuxer (tracks, duration, packets(trackId?), seek(seconds)) | nil, Err. Packets carry pts /
+-- dts / duration in their track's timescale ticks and a copy of the sample bytes.
+function IsoBmff.demux(r: Bytes.Reader, opts: Demux.Options?): (any, Err.Err?)
+ local movie, err = Demux.parse(r, opts)
+ if not movie then
+ return nil, err
+ end
+ local cursor: { [number]: number } = {}
+ local byId: { [number]: Track } = {}
+ for _, t in movie.tracks do
+ cursor[t.id] = 1
+ byId[t.id] = t
+ end
+ local dmx = { tracks = movie.tracks, duration = movie.duration, movie = movie }
+ local function packet(t: Track, i: number): any
+ local dts = t.dts[i]
+ local cts = t.cts
+ return {
+ track = t.id,
+ dts = dts,
+ pts = dts + (if cts then cts[i] or 0 else 0),
+ duration = t.durations[i],
+ keyframe = t.sync == nil or (t.sync :: any)[i] == true,
+ data = IsoBmff.sample(r, t, i),
+ index = i,
+ }
+ end
+ function dmx.packets(_self: any, trackId: number?): () -> any
+ return function(): any
+ if trackId then
+ local t = byId[trackId]
+ if not t then
+ return nil
+ end
+ local i = cursor[trackId]
+ if i > t.sampleCount then
+ return nil
+ end
+ cursor[trackId] = i + 1
+ return packet(t, i)
+ end
+ -- all tracks in file order
+ local best: Track? = nil
+ local bestOff = math.huge
+ for _, t in movie.tracks do
+ local i = cursor[t.id]
+ if i <= t.sampleCount and t.offsets[i] < bestOff then
+ best, bestOff = t, t.offsets[i]
+ end
+ end
+ if not best then
+ return nil
+ end
+ local i = cursor[best.id]
+ cursor[best.id] = i + 1
+ return packet(best, i)
+ end
+ end
+ -- seek(seconds): every track to its last sync sample at or before the time
+ function dmx.seek(_self: any, seconds: number)
+ for _, t in movie.tracks do
+ local target = seconds * t.timescale
+ local lo, hi = 1, t.sampleCount
+ local found = 1
+ while lo <= hi do
+ local mid = (lo + hi) // 2
+ if t.dts[mid] <= target then
+ found = mid
+ lo = mid + 1
+ else
+ hi = mid - 1
+ end
+ end
+ if t.sync then
+ while found > 1 and not (t.sync :: any)[found] do
+ found -= 1
+ end
+ end
+ cursor[t.id] = found
+ end
+ end
+ return dmx, nil
+end
+
+-- mux(spec) -> buffer | nil, Err (see containers/IsoBmff/Mux)
+function IsoBmff.mux(spec: MuxSpec): (buffer?, Err.Err?)
+ return Mux.mux(spec)
+end
+
+return IsoBmff
diff --git a/src/Formats/containers/Tar.luau b/src/Formats/containers/Tar.luau
new file mode 100644
index 0000000..5627311
--- /dev/null
+++ b/src/Formats/containers/Tar.luau
@@ -0,0 +1,426 @@
+--!strict
+-- containers/Tar: tar archives (POSIX.1-1988 ustar, POSIX.1-2001 pax, GNU), read and written. Reading handles
+-- v7 / ustar / GNU / pax headers: the ustar name prefix, pax extended headers ('x' per file, 'g' global: path,
+-- linkpath, size, mtime, uid, gid, uname, gname), GNU long names and link names ('L' / 'K'), base-256 numeric fields,
+-- header checksums (unsigned and the historical signed sum) and the end-of-archive blocks. Writing produces ustar
+-- headers, with a pax extended header for what ustar cannot hold (long or non-ASCII names, sizes of 8 GiB and more,
+-- fractional / negative mtimes) or, with opts.format = "gnu", GNU 'L' / 'K' records. Written from POSIX
+-- (pax(1), IEEE Std 1003.1-2017) and the GNU tar manual. Not supported: sparse files (GNU 'S', pax GNU.sparse), multi-
+-- volume archives (they list, with type "S" / "M"; reading them returns their stored bytes).
+--
+-- local entries, err = Tar.read(buf, offset?, length?) -- { { name, size, type, mode, mtime, link, offset, ... } }
+-- local out, err = Tar.write({ { name = "a.txt", data = buf, mtime = 0 }, { name = "d/", dir = true } }, opts)
+--
+-- Never throws: bad data returns nil, Err.
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+
+local Tar = {}
+
+export type Entry = {
+ name: string,
+ size: number,
+ type: string, -- "0" file, "5" directory, "2" symlink, "1" hard link, "3" / "4" devices, "6" fifo, ...
+ dir: boolean,
+ mode: number,
+ uid: number,
+ gid: number,
+ mtime: number,
+ link: string?,
+ uname: string?,
+ gname: string?,
+ offset: number, -- absolute offset of the data in the buffer
+ pax: { [string]: string }?,
+}
+
+local BLOCK = 512
+
+local function zeros(b: buffer, o: number): boolean
+ for i = 0, BLOCK - 1, 4 do
+ if buffer.readu32(b, o + i) ~= 0 then
+ return false
+ end
+ end
+ return true
+end
+
+-- a numeric field: octal text (NUL / space terminated) or base-256 (high bit of the first byte)
+local function number(b: buffer, o: number, n: number): number?
+ local first = buffer.readu8(b, o)
+ if first >= 0x80 then
+ local v = first - (if first >= 0xC0 then 0x100 else 0x80) -- 0xFF.. = negative
+ for i = 1, n - 1 do
+ v = v * 256 + buffer.readu8(b, o + i)
+ end
+ return v
+ end
+ local s = buffer.readstring(b, o, n)
+ s = string.match(s, "^[ %z]*([0-7]*)") or ""
+ if s == "" then
+ return 0
+ end
+ return tonumber(s, 8)
+end
+
+local function str(b: buffer, o: number, n: number): string
+ local s = buffer.readstring(b, o, n)
+ local z = string.find(s, "\0", 1, true)
+ return if z then string.sub(s, 1, z - 1) else s
+end
+
+local function checksum(b: buffer, o: number): (number, number)
+ local u, s = 0, 0
+ for i = 0, BLOCK - 1 do
+ local v = if i >= 148 and i < 156 then 32 else buffer.readu8(b, o + i)
+ u += v
+ s += if v >= 128 then v - 256 else v
+ end
+ return u, s
+end
+
+-- valid(buf, offset) -> true when the block at offset is a tar header with a correct checksum
+function Tar.valid(b: buffer, o: number): boolean
+ if o + BLOCK > buffer.len(b) or zeros(b, o) then
+ return false
+ end
+ local want = number(b, o + 148, 8)
+ local u, s = checksum(b, o)
+ return want == u or want == s
+end
+
+-- pax records "len key=value\n" -> { key = value }
+local function pax(b: buffer, o: number, n: number, into: { [string]: string }): boolean
+ local s = buffer.readstring(b, o, n)
+ local p = 1
+ while p <= #s do
+ if string.byte(s, p) == 0 then
+ break
+ end
+ local len = string.match(s, "^(%d+) ", p)
+ if not len then
+ return false
+ end
+ local l = tonumber(len) :: number
+ if l < #len + 3 or p + l - 1 > #s then
+ return false
+ end
+ local rec = string.sub(s, p + #len + 1, p + l - 2) -- without the trailing newline
+ local eq = string.find(rec, "=", 1, true)
+ if not eq then
+ return false
+ end
+ into[string.sub(rec, 1, eq - 1)] = string.sub(rec, eq + 1)
+ p += l
+ end
+ return true
+end
+
+export type ReadOptions = { maxEntries: number? } -- default 1e6
+
+-- read(buf, offset?, length?, opts?) -> { Entry } | nil, Err
+function Tar.read(b: buffer, offset: number?, length: number?, opts: ReadOptions?): ({ Entry }?, Err.Err?)
+ local o = offset or 0
+ local e = math.min(buffer.len(b), o + (length or (buffer.len(b) - o)))
+ local maxEntries = (opts and opts.maxEntries) or 1e6
+ local out: { Entry } = {}
+ local global: { [string]: string } = {}
+ local nextPax: { [string]: string }? = nil
+ local longName: string? = nil
+ local longLink: string? = nil
+ local p = o
+ while true do
+ if p + BLOCK > e then
+ if p == e then
+ break -- no end-of-archive blocks: accepted, as GNU tar does (with a warning)
+ end
+ return nil, Err.new(Err.TRUNCATED, "header past the end", p)
+ end
+ if zeros(b, p) then
+ break -- end of archive (one or two zero blocks; what follows is padding)
+ end
+ local want = number(b, p + 148, 8)
+ local u, s = checksum(b, p)
+ if want ~= u and want ~= s then
+ return nil, Err.new(if #out == 0 then Err.CORRUPT else Err.CHECKSUM, "bad header checksum", p + 148)
+ end
+ local typ = buffer.readstring(b, p + 156, 1)
+ if typ == "\0" then
+ typ = "0"
+ end
+ local size = number(b, p + 124, 12)
+ if not size or size < 0 then
+ return nil, Err.new(Err.CORRUPT, "bad size field", p + 124)
+ end
+ local data = p + BLOCK
+ local nextHeader = data + (size + BLOCK - 1) // BLOCK * BLOCK
+ local ustar = buffer.readstring(b, p + 257, 5) == "ustar"
+ -- meta records: pax / GNU long names
+ if typ == "x" or typ == "g" or typ == "L" or typ == "K" then
+ if data + size > e then
+ return nil, Err.new(Err.TRUNCATED, "extended header past the end", data)
+ end
+ if typ == "x" or typ == "g" then
+ local into = if typ == "g" then global else (nextPax or {})
+ if not pax(b, data, size, into) then
+ return nil, Err.new(Err.CORRUPT, "bad pax record", data)
+ end
+ if typ == "x" then
+ nextPax = into
+ end
+ elseif typ == "L" then
+ longName = str(b, data, size)
+ else
+ longLink = str(b, data, size)
+ end
+ p = nextHeader
+ continue
+ end
+ local name = str(b, p, 100)
+ if ustar then
+ local prefix = str(b, p + 345, 155)
+ if prefix ~= "" and buffer.readstring(b, p + 257, 8) ~= "ustar \0" then -- (GNU uses the field for times)
+ name = prefix .. "/" .. name
+ end
+ end
+ local entry: Entry = {
+ name = name,
+ size = size,
+ type = typ,
+ dir = typ == "5",
+ mode = number(b, p + 100, 8) or 0,
+ uid = number(b, p + 108, 8) or 0,
+ gid = number(b, p + 116, 8) or 0,
+ mtime = number(b, p + 136, 12) or 0,
+ link = if typ == "1" or typ == "2" then str(b, p + 157, 100) else nil,
+ uname = if ustar then str(b, p + 265, 32) else nil,
+ gname = if ustar then str(b, p + 297, 32) else nil,
+ offset = data,
+ pax = nil,
+ }
+ if longName then
+ entry.name = longName
+ end
+ if longLink then
+ entry.link = longLink
+ end
+ local px = nextPax
+ for _, rec in { global, px } do
+ if rec then
+ if rec.path then
+ entry.name = rec.path
+ end
+ if rec.linkpath then
+ entry.link = rec.linkpath
+ end
+ if rec.size then
+ local sz = tonumber(rec.size)
+ if not sz or sz < 0 or sz % 1 ~= 0 then
+ return nil, Err.new(Err.CORRUPT, "bad pax size", p)
+ end
+ entry.size = sz
+ end
+ if rec.mtime then
+ entry.mtime = tonumber(rec.mtime) or entry.mtime
+ end
+ if rec.uid then
+ entry.uid = tonumber(rec.uid) or entry.uid
+ end
+ if rec.gid then
+ entry.gid = tonumber(rec.gid) or entry.gid
+ end
+ if rec.uname then
+ entry.uname = rec.uname
+ end
+ if rec.gname then
+ entry.gname = rec.gname
+ end
+ end
+ end
+ if px then
+ entry.pax = px
+ end
+ if typ == "5" or string.sub(entry.name, -1) == "/" and (typ == "0" and entry.size == 0) then
+ entry.dir = true
+ end
+ -- links, devices, fifos and directories carry no data (whatever the size field says, except GNU dumpdir)
+ local dataSize = if typ == "1" or typ == "2" or typ == "3" or typ == "4" or typ == "6" or typ == "5" then 0 else entry.size
+ if typ == "5" or typ == "1" or typ == "2" then
+ entry.size = 0
+ end
+ nextHeader = data + (dataSize + BLOCK - 1) // BLOCK * BLOCK
+ if typ ~= "5" and data + dataSize > e then
+ return nil, Err.new(Err.TRUNCATED, "entry " .. entry.name .. " data past the end", data)
+ end
+ table.insert(out, entry)
+ if #out > maxEntries then
+ return nil, Err.new(Err.LIMIT, "more than " .. maxEntries .. " entries")
+ end
+ nextPax, longName, longLink = nil, nil, nil
+ p = nextHeader
+ end
+ return out, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ writing
+export type WriteEntry = {
+ name: string,
+ data: buffer?,
+ dir: boolean?,
+ type: string?, -- default "0" ("5" for dir)
+ link: string?,
+ mode: number?, -- default 0o644 (0o755 for directories)
+ uid: number?,
+ gid: number?,
+ uname: string?,
+ gname: string?,
+ mtime: number?, -- unix seconds (default 0)
+}
+export type WriteOptions = { format: ("pax" | "gnu" | "ustar")? } -- default "pax" (ustar headers + pax when needed)
+
+local function octal(w: buffer, o: number, n: number, v: number): boolean
+ -- n - 1 octal digits and a NUL; false when it does not fit
+ local s = string.format("%o", v)
+ if v < 0 or v % 1 ~= 0 or #s > n - 1 then
+ return false
+ end
+ buffer.writestring(w, o, string.rep("0", n - 1 - #s) .. s)
+ buffer.writeu8(w, o + n - 1, 0)
+ return true
+end
+
+local function field(w: buffer, o: number, n: number, s: string)
+ buffer.writestring(w, o, string.sub(s, 1, n))
+end
+
+local function ascii(s: string): boolean
+ return not string.find(s, "[\128-\255]")
+end
+
+local function paxRecord(key: string, value: string): string
+ local body = " " .. key .. "=" .. value .. "\n"
+ local n = #body + 1
+ while #tostring(n) + #body ~= n do
+ n = #tostring(n) + #body
+ end
+ return tostring(n) .. body
+end
+
+-- one header block (the checksum filled in)
+local function header(name: string, typ: string, size: number, e: WriteEntry, prefix: string, link: string, gnu: boolean): buffer
+ local h = buffer.create(BLOCK)
+ field(h, 0, 100, name)
+ local mode = e.mode or (if typ == "5" then 0x1ED else 0x1A4)
+ octal(h, 100, 8, mode % 0x200000)
+ octal(h, 108, 8, math.clamp(math.floor(e.uid or 0), 0, 0x1FFFFF))
+ octal(h, 116, 8, math.clamp(math.floor(e.gid or 0), 0, 0x1FFFFF))
+ octal(h, 124, 12, size)
+ octal(h, 136, 12, math.clamp(math.floor(e.mtime or 0), 0, 8 ^ 11 - 1))
+ field(h, 148, 8, " ")
+ field(h, 156, 1, typ)
+ field(h, 157, 100, link)
+ field(h, 257, 8, if gnu then "ustar \0" else "ustar\00000")
+ field(h, 265, 32, e.uname or "")
+ field(h, 297, 32, e.gname or "")
+ field(h, 345, 155, prefix)
+ local u = checksum(h, 0)
+ field(h, 148, 8, string.format("%06o", u) .. "\0 ")
+ return h
+end
+
+-- split a long path into ustar prefix (<= 155) + name (<= 100) at a slash, or nil
+local function split(path: string): (string?, string?)
+ if #path <= 100 then
+ return "", path
+ end
+ for i = 2, math.min(#path - 1, 156) do -- the shortest prefix that works, as Python's tarfile
+ if string.sub(path, i, i) == "/" and i - 1 <= 155 and #path - i <= 100 then
+ return string.sub(path, 1, i - 1), string.sub(path, i + 1)
+ end
+ end
+ return nil, nil
+end
+
+-- write(entries, opts?) -> buffer | nil, Err
+function Tar.write(entries: { WriteEntry }, opts: WriteOptions?): (buffer?, Err.Err?)
+ local fmt = (opts and opts.format) or "pax"
+ local w = Bytes.writer(BLOCK * (2 * #entries + 2))
+ for i, e in entries do
+ if type(e) ~= "table" or type(e.name) ~= "string" or e.name == "" then
+ return nil, Err.new(Err.ARG, "entry " .. i .. ": needs a name")
+ end
+ local data = e.data or buffer.create(0)
+ local typ = e.type or (if e.dir then "5" else "0")
+ local name = e.name
+ if typ == "5" and string.sub(name, -1) ~= "/" then
+ name ..= "/"
+ end
+ local size = if typ == "0" or typ == "7" then buffer.len(data) else 0
+ local link = e.link or ""
+ -- ustar splits long names into prefix + name; pax and GNU (as Python's tarfile and GNU tar) record them whole
+ local prefix, short
+ if fmt == "ustar" then
+ prefix, short = split(name)
+ elseif #name <= 100 then
+ prefix, short = "", name
+ end
+ local paxRecs: { string } = {}
+ -- GNU headers hold any bytes (UTF-8 names stay raw); ustar / pax headers are ASCII
+ local needName = prefix == nil or (fmt ~= "gnu" and not ascii(name))
+ local needLink = #link > 100 or (fmt ~= "gnu" and not ascii(link))
+ if needName or needLink then
+ if fmt == "ustar" then
+ return nil, Err.new(Err.ARG, "entry " .. name .. ": name or link too long / not ASCII for ustar")
+ elseif fmt == "gnu" then
+ if needName then
+ local ln = buffer.fromstring(name .. "\0")
+ w:bytes(header("././@LongLink", "L", buffer.len(ln), { mode = 0 } :: any, "", "", true))
+ w:bytes(ln)
+ w:fill(0, (BLOCK - buffer.len(ln) % BLOCK) % BLOCK)
+ end
+ if needLink then
+ local ll = buffer.fromstring(link .. "\0")
+ w:bytes(header("././@LongLink", "K", buffer.len(ll), { mode = 0 } :: any, "", "", true))
+ w:bytes(ll)
+ w:fill(0, (BLOCK - buffer.len(ll) % BLOCK) % BLOCK)
+ end
+ else
+ if needName then
+ table.insert(paxRecs, paxRecord("path", name))
+ end
+ if needLink then
+ table.insert(paxRecs, paxRecord("linkpath", link))
+ end
+ end
+ end
+ if size >= 8 ^ 11 then
+ if fmt ~= "pax" then
+ return nil, Err.new(Err.ARG, "entry " .. name .. ": 8 GiB or more needs pax")
+ end
+ table.insert(paxRecs, paxRecord("size", tostring(size)))
+ end
+ local mt = e.mtime or 0
+ if fmt == "pax" and (mt < 0 or mt % 1 ~= 0 or mt >= 8 ^ 11) then
+ table.insert(paxRecs, paxRecord("mtime", string.format("%.9f", mt):gsub("0+$", ""):gsub("%.$", "")))
+ end
+ if #paxRecs > 0 then
+ local body = buffer.fromstring(table.concat(paxRecs))
+ w:bytes(header("././@PaxHeader", "x", buffer.len(body), { mode = 0 } :: any, "", "", false))
+ w:bytes(body)
+ w:fill(0, (BLOCK - buffer.len(body) % BLOCK) % BLOCK)
+ end
+ if prefix == nil or (fmt ~= "gnu" and not ascii(name)) then
+ -- the header keeps an ASCII stand-in (each non-ASCII character as "?", as Python's tarfile)
+ local stand = if fmt == "gnu" then name else string.gsub(name, "[\192-\255][\128-\191]*", "?")
+ prefix, short = "", string.sub(stand, 1, 100)
+ end
+ w:bytes(header(short :: string, typ, if size >= 8 ^ 11 then 0 else size, e, prefix :: string, string.sub(link, 1, 100), fmt == "gnu"))
+ if size > 0 then
+ w:bytes(data)
+ w:fill(0, (BLOCK - size % BLOCK) % BLOCK)
+ end
+ end
+ w:fill(0, BLOCK * 2)
+ return w:finish(), nil
+end
+
+return Tar
diff --git a/src/Formats/core/Base64.luau b/src/Formats/core/Base64.luau
new file mode 100644
index 0000000..7ffbb09
--- /dev/null
+++ b/src/Formats/core/Base64.luau
@@ -0,0 +1,89 @@
+--!strict
+--!native
+-- core/Base64: RFC 4648 base64 (standard alphabet, and the URL-safe one on decode). Tiled map data, data: URIs, ...
+-- decode skips whitespace and accepts missing padding; other bad characters fail. Never throws.
+--
+-- local s = Base64.encode(buf) -- buffer | string -> string
+-- local b, err = Base64.decode(s) -- string -> buffer | nil, "message"
+local Base64 = {}
+
+local ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
+local ENC = buffer.create(64)
+buffer.writestring(ENC, 0, ALPHABET)
+local DEC = buffer.create(256)
+buffer.fill(DEC, 0, 255)
+for i = 0, 63 do
+ buffer.writeu8(DEC, string.byte(ALPHABET, i + 1), i)
+end
+buffer.writeu8(DEC, string.byte("-"), 62)
+buffer.writeu8(DEC, string.byte("_"), 63)
+for _, c in { 9, 10, 13, 32 } do
+ buffer.writeu8(DEC, c, 254) -- whitespace: skipped
+end
+
+local readu8, writeu8 = buffer.readu8, buffer.writeu8
+
+-- encode(data) -> base64 text with padding
+function Base64.encode(data: buffer | string): string
+ local src: buffer = if type(data) == "string" then buffer.fromstring(data) else data
+ local n = buffer.len(src)
+ local out = buffer.create((n + 2) // 3 * 4)
+ local o = 0
+ local i = 0
+ while i + 2 < n do
+ local v = readu8(src, i) * 65536 + readu8(src, i + 1) * 256 + readu8(src, i + 2)
+ writeu8(out, o, readu8(ENC, v // 262144))
+ writeu8(out, o + 1, readu8(ENC, v // 4096 % 64))
+ writeu8(out, o + 2, readu8(ENC, v // 64 % 64))
+ writeu8(out, o + 3, readu8(ENC, v % 64))
+ i += 3
+ o += 4
+ end
+ local rest = n - i
+ if rest > 0 then
+ local v = readu8(src, i) * 65536 + (if rest == 2 then readu8(src, i + 1) * 256 else 0)
+ writeu8(out, o, readu8(ENC, v // 262144))
+ writeu8(out, o + 1, readu8(ENC, v // 4096 % 64))
+ writeu8(out, o + 2, if rest == 2 then readu8(ENC, v // 64 % 64) else 61)
+ writeu8(out, o + 3, 61)
+ end
+ return buffer.tostring(out)
+end
+
+-- decode(text) -> buffer | nil, message
+function Base64.decode(text: string | buffer): (buffer?, string?)
+ local src: buffer = if type(text) == "string" then buffer.fromstring(text) else text
+ local n = buffer.len(src)
+ local out = buffer.create(n // 4 * 3 + 3)
+ local o = 0
+ local acc, bits = 0, 0
+ local pad = false
+ for i = 0, n - 1 do
+ local c = readu8(src, i)
+ local v = readu8(DEC, c)
+ if v == 254 then
+ continue
+ end
+ if c == 61 then -- '='
+ pad = true
+ continue
+ end
+ if v == 255 or pad then
+ return nil, string.format("bad base64 character at %d", i)
+ end
+ acc = acc * 64 + v
+ bits += 6
+ if bits >= 8 then
+ bits -= 8
+ local p = 2 ^ bits
+ writeu8(out, o, acc // p)
+ acc %= p
+ o += 1
+ end
+ end
+ local res = buffer.create(o)
+ buffer.copy(res, 0, out, 0, o)
+ return res, nil
+end
+
+return Base64
diff --git a/src/Formats/data/cbor/Codec.luau b/src/Formats/data/cbor/Codec.luau
new file mode 100644
index 0000000..f588c59
--- /dev/null
+++ b/src/Formats/data/cbor/Codec.luau
@@ -0,0 +1,607 @@
+--!strict
+--!native
+-- data/cbor/Codec: the CBOR (RFC 8949) decoder and encoder behind data/cbor. Never throws: errors return nil,
+-- message, offset.
+local Bytes = require("@formats/core/Bytes")
+local Types = require("@formats/Types")
+
+local Codec = {}
+
+local TWO32 = 4294967296
+
+-- ------------------------------------------------------------------------------------------------ value types
+local TaggedMeta = { __tostring = function(t: any): string
+ return "cbor.tag(" .. t.tag .. ")"
+end }
+local SimpleMeta = { __tostring = function(s: any): string
+ return "cbor.simple(" .. s.value .. ")"
+end }
+-- tagged(tag, value) -> { tag, value }: a tag this library does not interpret
+function Codec.tagged(tag: number, value: any): { tag: number, value: any }
+ return setmetatable({ tag = tag, value = value }, TaggedMeta) :: any
+end
+function Codec.isTagged(v: any): boolean
+ return type(v) == "table" and getmetatable(v) == TaggedMeta
+end
+-- simple(n) -> an unassigned simple value (0..19, 32..255)
+function Codec.simple(n: number): { value: number }
+ return setmetatable({ value = n }, SimpleMeta) :: any
+end
+function Codec.isSimple(v: any): boolean
+ return type(v) == "table" and getmetatable(v) == SimpleMeta
+end
+Codec.undefined = table.freeze(setmetatable({}, { __tostring = function()
+ return "undefined"
+end }))
+
+-- decimal text of a big-endian unsigned byte string (any length)
+local function bigText(s: string): string
+ local limbs = {} -- base 1e7, little-endian
+ for i = 1, #s do
+ local carry = string.byte(s, i)
+ for k = 1, #limbs do
+ local v = limbs[k] * 256 + carry
+ limbs[k] = v % 10000000
+ carry = v // 10000000
+ end
+ while carry > 0 do
+ table.insert(limbs, carry % 10000000)
+ carry //= 10000000
+ end
+ end
+ if #limbs == 0 then
+ return "0"
+ end
+ local out = { string.format("%d", limbs[#limbs]) }
+ for k = #limbs - 1, 1, -1 do
+ table.insert(out, string.format("%07d", limbs[k]))
+ end
+ return table.concat(out)
+end
+-- text + 1 for a decimal string
+local function incText(s: string): string
+ local digits = table.create(#s)
+ for i = 1, #s do
+ digits[i] = string.byte(s, i) - 48
+ end
+ local i = #digits
+ while i >= 1 do
+ if digits[i] < 9 then
+ digits[i] += 1
+ break
+ end
+ digits[i] = 0
+ i -= 1
+ end
+ local out = table.create(#digits)
+ for k, d in digits do
+ out[k] = string.char(48 + d)
+ end
+ return (if i == 0 then "1" else "") .. table.concat(out)
+end
+
+export type DecodeOptions = {
+ bigInts: ("number" | "string")?, -- integers / bignums past 2^53: "string" keeps exact decimal text
+ null: any?, -- the value for null (default Types.null)
+ undefined: any?, -- the value for undefined (default Codec.undefined)
+ maxDepth: number?, -- default 512
+ dates: boolean?, -- tags 0 / 1 as Types.Date (default true)
+}
+
+type St = { r: Bytes.Reader, big: boolean, null: any, undef: any, maxDepth: number, dates: boolean }
+
+local BREAK = {} -- the 0xFF stop code, inside indefinite items
+
+-- the argument of a head: number (or nil, "text" for u64 past 2^53 when big), nil means indefinite (ai 31)
+local function arg(st: St, ai: number): (number?, string?, string?)
+ local r = st.r
+ if ai < 24 then
+ return ai, nil, nil
+ elseif ai == 24 then
+ return r:u8(), nil, nil
+ elseif ai == 25 then
+ return r:u16be(), nil, nil
+ elseif ai == 26 then
+ return r:u32be(), nil, nil
+ elseif ai == 27 then
+ local hi, lo = r:u32be(), r:u32be()
+ if st.big and hi >= 0x200000 then
+ return hi * TWO32 + lo, bigText(string.char(hi // 16777216, (hi // 65536) % 256, (hi // 256) % 256, hi % 256, lo // 16777216, (lo // 65536) % 256, (lo // 256) % 256, lo % 256)), nil
+ end
+ return hi * TWO32 + lo, nil, nil
+ elseif ai == 31 then
+ return nil, nil, nil
+ end
+ return nil, nil, "reserved additional information " .. ai
+end
+
+local item: (st: St, depth: number) -> (any, string?)
+
+local function chunks(st: St, major: number, depth: number): (string?, string?)
+ local parts = {}
+ while true do
+ local r = st.r
+ local ib = r:u8()
+ if r.err then
+ return nil, "truncated"
+ end
+ if ib == 0xFF then
+ return table.concat(parts), nil
+ end
+ if ib // 32 ~= major then
+ return nil, "bad chunk in an indefinite string"
+ end
+ local n, _, e = arg(st, ib % 32)
+ if e or n == nil then
+ return nil, e or "nested indefinite string"
+ end
+ if r.err or not r:need(n) then
+ return nil, "truncated string"
+ end
+ table.insert(parts, r:string(n))
+ end
+end
+
+local function half(h: number): number
+ local s = if h >= 32768 then -1 else 1
+ local e = (h // 1024) % 32
+ local m = h % 1024
+ if e == 0 then
+ return s * m * 2 ^ -24
+ elseif e == 31 then
+ return if m == 0 then s * math.huge else 0 / 0
+ end
+ return s * (1 + m / 1024) * 2 ^ (e - 15)
+end
+
+local function tag(st: St, t: number, v: any): (any, string?)
+ if t == 0 and st.dates then
+ if type(v) ~= "string" then
+ return nil, "tag 0 needs a text string"
+ end
+ local d = Types.Date.parse(v)
+ if not d or not d.offset then
+ return nil, "tag 0: bad date-time " .. v
+ end
+ return d, nil
+ elseif t == 1 and st.dates then
+ if type(v) ~= "number" or v ~= v or v == math.huge or v == -math.huge then
+ return nil, "tag 1 needs a number"
+ end
+ return Types.Date.fromUnix(v), nil
+ elseif t == 2 or t == 3 then
+ if type(v) ~= "string" then
+ return nil, "bignum tag needs a byte string"
+ end
+ local s = v :: string
+ local n = 0
+ for i = 1, #s do
+ n = n * 256 + string.byte(s, i)
+ end
+ if n >= 9007199254740992 then
+ -- exact text; as a number, read back from that text (correctly rounded, unlike the running sum)
+ local text = bigText(s)
+ if t == 3 then
+ text = incText(text)
+ end
+ if st.big then
+ return if t == 2 then text else "-" .. text, nil
+ end
+ local x = tonumber(text) :: number
+ return if t == 2 then x else -x, nil
+ end
+ return if t == 2 then n else -1 - n, nil
+ elseif t == 55799 then
+ return v, nil
+ end
+ return Codec.tagged(t, v), nil
+end
+
+function item(st: St, depth: number): (any, string?)
+ if depth > st.maxDepth then
+ return nil, "nested deeper than " .. st.maxDepth
+ end
+ local r = st.r
+ local ib = r:u8()
+ if r.err then
+ return nil, "truncated"
+ end
+ local major, ai = ib // 32, ib % 32
+ if major == 7 then
+ if ai < 20 then
+ return Codec.simple(ai), nil
+ elseif ai == 20 then
+ return false, nil
+ elseif ai == 21 then
+ return true, nil
+ elseif ai == 22 then
+ return st.null, nil
+ elseif ai == 23 then
+ return st.undef, nil
+ elseif ai == 24 then
+ local n = r:u8()
+ if r.err then
+ return nil, "truncated"
+ end
+ if n < 32 then
+ return nil, "bad two-byte simple value"
+ end
+ return Codec.simple(n), nil
+ elseif ai == 25 then
+ local h = r:u16be()
+ return if r.err then nil else half(h), if r.err then "truncated" else nil
+ elseif ai == 26 then
+ local f = r:f32be()
+ return if r.err then nil else f, if r.err then "truncated" else nil
+ elseif ai == 27 then
+ local f = r:f64be()
+ return if r.err then nil else f, if r.err then "truncated" else nil
+ elseif ai == 31 then
+ return BREAK, nil
+ end
+ return nil, "reserved simple value"
+ end
+ local n, text, e = arg(st, ai)
+ if e then
+ return nil, e
+ end
+ if r.err then
+ return nil, "truncated"
+ end
+ if major == 0 then
+ if n == nil then
+ return nil, "indefinite integer"
+ end
+ return text or n, nil
+ elseif major == 1 then
+ if n == nil then
+ return nil, "indefinite integer"
+ end
+ if text then
+ return "-" .. incText(text), nil
+ end
+ return -1 - n, nil
+ elseif major == 2 or major == 3 then
+ local s: string
+ if n == nil then
+ local c, ce = chunks(st, major, depth)
+ if not c then
+ return nil, ce
+ end
+ s = c
+ else
+ if not r:need(n) then
+ return nil, "truncated string"
+ end
+ s = r:string(n)
+ end
+ if major == 2 then
+ return buffer.fromstring(s), nil
+ end
+ if string.find(s, "[\128-\255]") and not utf8.len(s) then
+ return nil, "invalid UTF-8 in a text string"
+ end
+ return s, nil
+ elseif major == 4 then
+ if n == nil then
+ local t = {}
+ while true do
+ local v, ve = item(st, depth + 1)
+ if ve then
+ return nil, ve
+ end
+ if v == BREAK then
+ return t, nil
+ end
+ table.insert(t, v)
+ end
+ end
+ if n > r:remaining() then
+ return nil, "array count past the end"
+ end
+ local t = table.create(n)
+ for k = 1, n do
+ local v, ve = item(st, depth + 1)
+ if ve then
+ return nil, ve
+ end
+ if v == BREAK then
+ return nil, "unexpected break"
+ end
+ t[k] = v
+ end
+ return t, nil
+ elseif major == 5 then
+ if n ~= nil and n * 2 > r:remaining() then
+ return nil, "map count past the end"
+ end
+ local t = {}
+ local order = {}
+ local k = 0
+ while n == nil or k < n do
+ k += 1
+ local key, ke = item(st, depth + 1)
+ if ke then
+ return nil, ke
+ end
+ if key == BREAK then
+ if n == nil then
+ break
+ end
+ return nil, "unexpected break"
+ end
+ local v, ve = item(st, depth + 1)
+ if ve then
+ return nil, ve
+ end
+ if v == BREAK then
+ return nil, "unexpected break"
+ end
+ if key ~= key then
+ return nil, "NaN map key"
+ end
+ if t[key] == nil then
+ table.insert(order, key)
+ end
+ t[key] = v
+ end
+ return Types.object(t, order), nil
+ else -- 6: tag
+ if n == nil then
+ return nil, "indefinite tag"
+ end
+ local v, ve = item(st, depth + 1)
+ if ve then
+ return nil, ve
+ end
+ if v == BREAK then
+ return nil, "unexpected break"
+ end
+ -- bignum content arrives as a buffer: hand the tag its bytes
+ if (n == 2 or n == 3) and type(v) == "buffer" then
+ return tag(st, n, buffer.tostring(v))
+ end
+ return tag(st, n, v)
+ end
+end
+
+-- decode(r, opts) -> value | nil, message, offset (one item; r is left after it)
+function Codec.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, string?, number?)
+ local o: DecodeOptions = opts or {}
+ local st: St = {
+ r = r,
+ big = o.bigInts == "string",
+ null = if o.null ~= nil then o.null else Types.null,
+ undef = if o.undefined ~= nil then o.undefined else Codec.undefined,
+ maxDepth = o.maxDepth or 512,
+ dates = o.dates ~= false,
+ }
+ local v, e = item(st, 0)
+ if e then
+ return nil, e, r.pos - r.base
+ end
+ if v == BREAK then
+ return nil, "unexpected break", r.pos - r.base - 1
+ end
+ return v, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+export type EncodeOptions = {
+ compactFloats: boolean?, -- floats in the shortest of half / single / double that keeps the value (default false)
+ sortKeys: boolean?, -- plain tables' keys sorted (default true; Types.object keeps its order)
+ emptyTable: ("array" | "map")?, -- a plain empty table (default "array")
+ dates: ("string" | "epoch")?, -- Types.Date as tag 0 text (default) or tag 1 seconds
+ maxDepth: number?, -- default 512 (also catches cycles)
+}
+
+type ESt = { w: Bytes.Writer, compact: boolean, sort: boolean, emptyMap: boolean, epoch: boolean, maxDepth: number, err: string? }
+
+local function head(w: Bytes.Writer, major: number, n: number)
+ local m = major * 32
+ if n < 24 then
+ w:u8(m + n)
+ elseif n < 256 then
+ w:u8(m + 24)
+ w:u8(n)
+ elseif n < 65536 then
+ w:u8(m + 25)
+ w:u16be(n)
+ elseif n < TWO32 then
+ w:u8(m + 26)
+ w:u32be(n)
+ elseif n >= 18446744073709551616 then -- -1 - (-2^64) rounds up to 2^64: the exact argument is 2^64 - 1
+ w:u8(m + 27)
+ w:u32be(0xFFFFFFFF)
+ w:u32be(0xFFFFFFFF)
+ else
+ w:u8(m + 27)
+ w:u64be(n)
+ end
+end
+
+-- the half-float bits of x when x is exactly representable, else nil
+local function toHalf(x: number): number?
+ if x ~= x then
+ return 0x7E00
+ end
+ local sign = if x < 0 or (x == 0 and 1 / x < 0) then 0x8000 else 0
+ local a = math.abs(x)
+ if a == math.huge then
+ return sign + 0x7C00
+ end
+ if a == 0 then
+ return sign
+ end
+ local m, e = math.frexp(a) -- a = m * 2^e, 0.5 <= m < 1
+ local exp = e - 1 + 15
+ if exp >= 31 then
+ return nil
+ end
+ if exp <= 0 then -- subnormal: a = mant * 2^-24
+ local mant = a / 2 ^ -24
+ if mant ~= math.floor(mant) or mant >= 1024 then
+ return nil
+ end
+ return sign + mant
+ end
+ local frac = (m * 2 - 1) * 1024
+ if frac ~= math.floor(frac) then
+ return nil
+ end
+ return sign + exp * 1024 + frac
+end
+Codec.toHalf = toHalf
+
+local function keyLess(a: any, b: any): boolean
+ local ta, tb = type(a), type(b)
+ if ta ~= tb then
+ return ta < tb
+ end
+ if ta == "number" or ta == "string" then
+ return a < b
+ end
+ return tostring(a) < tostring(b)
+end
+
+local function isArray(t: any, emptyMap: boolean): boolean
+ if Types.isObject(t) then
+ return false
+ end
+ local n = #t
+ if n == 0 then
+ return next(t) == nil and not emptyMap
+ end
+ local c = 0
+ for _ in next, t do
+ c += 1
+ end
+ return c == n
+end
+
+local scratch = buffer.create(8)
+
+local function enc(st: ESt, v: any, depth: number): boolean
+ local w = st.w
+ local tv = type(v)
+ if v == nil or v == Types.null then
+ w:u8(0xF6)
+ elseif v == Codec.undefined then
+ w:u8(0xF7)
+ elseif tv == "boolean" then
+ w:u8(if v then 0xF5 else 0xF4)
+ elseif tv == "number" then
+ if v == math.floor(v) and v >= -18446744073709551616 and v < 18446744073709551616 and not (v == 0 and 1 / v < 0) then
+ if v >= 0 then
+ head(w, 0, v)
+ else
+ head(w, 1, -1 - v)
+ end
+ else
+ local h = if st.compact then toHalf(v) else nil
+ if h then
+ w:u8(0xF9)
+ w:u16be(h)
+ else
+ buffer.writef32(scratch, 0, v)
+ if st.compact and (buffer.readf32(scratch, 0) == v or v ~= v) then
+ w:u8(0xFA)
+ w:f32be(v)
+ else
+ w:u8(0xFB)
+ w:f64be(v)
+ end
+ end
+ end
+ elseif tv == "string" then
+ head(w, 3, #v)
+ w:string(v)
+ elseif tv == "buffer" then
+ head(w, 2, buffer.len(v))
+ w:bytes(v)
+ elseif tv == "table" then
+ if depth >= st.maxDepth then
+ st.err = "nested deeper than " .. st.maxDepth .. " (a cycle?)"
+ return false
+ end
+ if Codec.isTagged(v) then
+ if type(v.tag) ~= "number" or v.tag < 0 or v.tag ~= math.floor(v.tag) then
+ st.err = "bad tag number"
+ return false
+ end
+ head(w, 6, v.tag)
+ return enc(st, v.value, depth + 1)
+ elseif Codec.isSimple(v) then
+ local n = v.value
+ if n < 20 then
+ w:u8(0xE0 + n)
+ elseif n >= 32 and n < 256 then
+ w:u8(0xF8)
+ w:u8(n)
+ else
+ st.err = "bad simple value " .. tostring(n)
+ return false
+ end
+ elseif Types.Date.is(v) then
+ if st.epoch then
+ w:u8(0xC1)
+ return enc(st, Types.Date.toUnix(v), depth + 1)
+ end
+ w:u8(0xC0)
+ local s = tostring(v)
+ head(w, 3, #s)
+ w:string(s)
+ elseif isArray(v, st.emptyMap) then
+ local n = #v
+ head(w, 4, n)
+ for k = 1, n do
+ if not enc(st, v[k], depth + 1) then
+ return false
+ end
+ end
+ else
+ local keys: { any }
+ if Types.isObject(v) then
+ keys = Types.keys(v)
+ else
+ keys = {}
+ for k in next, v do
+ table.insert(keys, k)
+ end
+ if st.sort then
+ table.sort(keys, keyLess)
+ end
+ end
+ head(w, 5, #keys)
+ for _, k in keys do
+ if not enc(st, k, depth + 1) or not enc(st, v[k], depth + 1) then
+ return false
+ end
+ end
+ end
+ else
+ st.err = "cannot encode a " .. tv
+ return false
+ end
+ return true
+end
+
+-- encode(v, opts) -> buffer | nil, message
+function Codec.encode(v: any, opts: EncodeOptions?): (buffer?, string?)
+ local o: EncodeOptions = opts or {}
+ local st: ESt = {
+ w = Bytes.writer(256),
+ compact = o.compactFloats == true,
+ sort = o.sortKeys ~= false,
+ emptyMap = o.emptyTable == "map",
+ epoch = o.dates == "epoch",
+ maxDepth = o.maxDepth or 512,
+ err = nil,
+ }
+ if not enc(st, v, 0) then
+ return nil, st.err
+ end
+ return st.w:finish(), nil
+end
+
+return Codec
diff --git a/src/Formats/data/cbor/init.luau b/src/Formats/data/cbor/init.luau
new file mode 100644
index 0000000..c605750
--- /dev/null
+++ b/src/Formats/data/cbor/init.luau
@@ -0,0 +1,100 @@
+--!strict
+-- data/cbor: CBOR (RFC 8949). New code. Supports: every major type, indefinite-length strings / arrays / maps, half /
+-- single / double floats, tags (0 / 1 date-times as Types.Date, 2 / 3 bignums as numbers or exact decimal text,
+-- 55799 self-describe stripped, others kept as Cbor.tagged(tag, value)), simple values (Cbor.simple(n),
+-- Cbor.undefined), byte strings as buffers, maps as Types.object (key order kept; keys of any type), sequences
+-- (RFC 8742, opts.all). Encode: preferred (shortest) integer and length heads, float64 unless opts.compactFloats,
+-- definite lengths. Not supported: other semantic tags (decimal fractions, bigfloats, ...) stay tagged values.
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Codec = require("@formats/data/cbor/Codec")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Cbor = {
+ name = "cbor",
+ category = "data",
+ extensions = { "cbor" },
+ mime = { "application/cbor", "application/cbor-seq" },
+ deps = { "core/Err", "core/Bytes", "Types" },
+ caps = { decode = true, encode = true, binary = true, ordered = true, tags = true },
+}
+
+export type DecodeOptions = Codec.DecodeOptions & {
+ all: boolean?, -- a CBOR sequence: every item into an array (default false: exactly one item)
+}
+export type EncodeOptions = Codec.EncodeOptions & {
+ all: boolean?, -- the value is an array of items, written as a sequence
+ selfDescribe: boolean?, -- prefix the 55799 self-describe tag (d9 d9 f7)
+}
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Cbor.sniff(r: Bytes.Reader): number
+ return if r:peek(3) == "\217\217\247" then 1 else 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+local function codeOf(e: string): string
+ if string.find(e, "truncated", 1, true) or string.find(e, "past the end", 1, true) then
+ return Err.TRUNCATED
+ elseif string.find(e, "nested deeper", 1, true) then
+ return Err.LIMIT
+ end
+ return Err.CORRUPT
+end
+
+function Cbor.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
+ local o: DecodeOptions = opts or {}
+ if o.all then
+ local out = {}
+ while not r:eof() do
+ local v, e, at = Codec.decode(r, o)
+ if e then
+ return nil, Err.new(codeOf(e), e, at)
+ end
+ table.insert(out, v)
+ end
+ return out, nil
+ end
+ local v, e, at = Codec.decode(r, o)
+ if e then
+ return nil, Err.new(codeOf(e), e, at)
+ end
+ if not r:eof() then
+ return nil, Err.new(Err.CORRUPT, "trailing data after the item (opts.all reads a sequence)", r.pos - r.base)
+ end
+ return v, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+function Cbor.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
+ local w = Bytes.writer()
+ if opts and opts.selfDescribe then
+ w:string("\217\217\247")
+ end
+ local items = { value }
+ if opts and opts.all then
+ if type(value) ~= "table" then
+ return nil, Err.new(Err.ARG, "all: expected an array of items")
+ end
+ items = value
+ end
+ for _, v in items do
+ local b, e = Codec.encode(v, opts)
+ if not b then
+ return nil, Err.new(Err.ARG, e or "cannot encode")
+ end
+ w:bytes(b)
+ end
+ return w:finish(), nil
+end
+
+-- ------------------------------------------------------------------------------------------------ extras
+Cbor.tagged = Codec.tagged -- tagged(tag, value) -> a value written as that tag
+Cbor.isTagged = Codec.isTagged
+Cbor.simple = Codec.simple -- simple(n) -> a simple value
+Cbor.isSimple = Codec.isSimple
+Cbor.undefined = Codec.undefined
+
+return Cbor
diff --git a/src/Formats/data/csv/init.luau b/src/Formats/data/csv/init.luau
new file mode 100644
index 0000000..e5c7d6d
--- /dev/null
+++ b/src/Formats/data/csv/init.luau
@@ -0,0 +1,316 @@
+--!strict
+-- data/csv: comma-separated values (RFC 4180, read as leniently as Python's csv module). New code. Supports: any
+-- one-byte delimiter (opts.delimiter, or "auto" to pick , ; tab |), quoted fields with doubled quotes and embedded
+-- line breaks, CRLF / LF / CR line ends, a header row (opts.header: rows become Types.object keyed by the column
+-- names, in column order), number conversion by option; encode from arrays of arrays or of keyed rows, quoting only
+-- where needed (like Python's QUOTE_MINIMAL) or always. Blank lines are skipped. Not supported: escape characters
+-- other than the doubled quote, multi-byte delimiters.
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Types = require("@formats/Types")
+local Json = require("@formats/codecs/Json")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Csv = {
+ name = "csv",
+ category = "data",
+ extensions = { "csv", "tsv" },
+ mime = { "text/csv", "text/tab-separated-values" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/Json" },
+ caps = { decode = true, encode = true, header = true },
+}
+
+export type DecodeOptions = {
+ delimiter: string?, -- one byte (default ","; "auto" guesses from the first line among , ; tab |)
+ quote: string?, -- the quote byte (default '"')
+ header: boolean?, -- the first row names the columns: rows become Types.object (default false: arrays)
+ numbers: boolean?, -- fields that are numbers become numbers (default false: every field is a string)
+ maxRows: number?, -- refuse more rows (default unlimited)
+}
+export type EncodeOptions = {
+ delimiter: string?, -- default ","
+ quote: string?, -- default '"'
+ newline: string?, -- the row terminator (default "\r\n", as RFC 4180 and Python's csv)
+ quoteAll: boolean?, -- quote every field (default false: only those that need it)
+ columns: { string }?, -- keyed rows: the column order (default: the keys of the rows in first-seen order)
+ header: boolean?, -- keyed rows: write the header row (default true)
+}
+
+-- ------------------------------------------------------------------------------------------------ constants
+local find, sub, byte, gsub = string.find, string.sub, string.byte, string.gsub
+
+local function patEscape(c: string): string
+ return (gsub(c, "[%^%$%(%)%%%.%[%]%*%+%-%?]", "%%%0"))
+end
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Csv.sniff(r: Bytes.Reader): number
+ local head = r:peek(1024)
+ if find(head, "%z") then
+ return 0
+ end
+ local l1, l2 = string.match(head, "^([^\r\n]*)\r?\n([^\r\n]*)")
+ if not l1 or l1 == "" then
+ return 0
+ end
+ for _, d in { ",", "\t", ";" } do
+ local _, c1 = gsub(l1, d, "")
+ local _, c2 = gsub(l2, d, "")
+ if c1 > 0 and c1 == c2 then
+ return 0.15
+ end
+ end
+ return 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+local function guess(s: string, q: string): string
+ local line = string.match(s, "^[^\r\n]*") or ""
+ line = gsub(line, patEscape(q) .. "[^" .. patEscape(q) .. "]*" .. patEscape(q), "")
+ local best, bestN = ",", 0
+ for _, d in { ",", ";", "\t", "|" } do
+ local _, n = gsub(line, patEscape(d), "")
+ if n > bestN then
+ best, bestN = d, n
+ end
+ end
+ return best
+end
+
+-- rows(s, opts) -> { { string } } | nil, Err
+function Csv.parse(s: string, opts: DecodeOptions?): ({ { string } }?, Err.Err?)
+ local o: DecodeOptions = opts or {}
+ local q = o.quote or '"'
+ local d = o.delimiter or ","
+ if d == "auto" then
+ d = guess(s, q)
+ end
+ if #d ~= 1 or #q ~= 1 or d == q or d == "\n" or d == "\r" then
+ return nil, Err.new(Err.ARG, "delimiter and quote must be single, different bytes (not line ends)")
+ end
+ local qb, db = byte(q), byte(d)
+ local stop = "[" .. patEscape(d) .. "\r\n]"
+ local maxRows = o.maxRows or math.huge
+ local rows: { { string } } = {}
+ local row: { string } = {}
+ local n = #s
+ local i = 1
+ local rowEmpty = true -- the current line has no field text yet (blank lines are skipped)
+ while true do
+ local c = byte(s, i)
+ local field: string
+ if c == qb then
+ local k = i + 1
+ local parts = {}
+ while true do
+ local j = find(s, q, k, true)
+ if not j then
+ return nil, Err.new(Err.TRUNCATED, "unterminated quoted field", i - 1)
+ end
+ if byte(s, j + 1) == qb then
+ table.insert(parts, sub(s, k, j))
+ k = j + 2
+ else
+ table.insert(parts, sub(s, k, j - 1))
+ i = j + 1
+ break
+ end
+ end
+ -- text after the closing quote up to the delimiter is kept (Python's lenient reading)
+ local e = find(s, stop, i) or (n + 1)
+ if e > i then
+ table.insert(parts, sub(s, i, e - 1))
+ end
+ i = e
+ field = table.concat(parts)
+ rowEmpty = false
+ else
+ local e = find(s, stop, i) or (n + 1)
+ field = sub(s, i, e - 1)
+ if e > i then
+ rowEmpty = false
+ end
+ i = e
+ end
+ table.insert(row, field)
+ c = byte(s, i)
+ if c == db then
+ rowEmpty = false
+ i += 1
+ else
+ -- end of the row: CRLF / LF / CR / end of data
+ if c == 13 and byte(s, i + 1) == 10 then
+ i += 2
+ elseif c ~= nil then
+ i += 1
+ end
+ if not rowEmpty then
+ table.insert(rows, row)
+ if #rows > maxRows then
+ return nil, Err.new(Err.LIMIT, "more than " .. maxRows .. " rows")
+ end
+ end
+ row = {}
+ rowEmpty = true
+ if i > n then
+ break
+ end
+ end
+ end
+ return rows, nil
+end
+
+local NUMBER = "^%s*[%-%+]?%d+%.?%d*[eE]?[%-%+]?%d*%s*$"
+local function convert(v: string): any
+ if string.match(v, NUMBER) or string.match(v, "^%s*[%-%+]?%.%d+[eE]?[%-%+]?%d*%s*$") then
+ local x = tonumber(v)
+ if x then
+ return x
+ end
+ end
+ return v
+end
+
+function Csv.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
+ local s = buffer.readstring(r.buf, r.base, r.limit - r.base)
+ if sub(s, 1, 3) == "\239\187\191" then
+ s = sub(s, 4)
+ end
+ local rows, err = Csv.parse(s, opts)
+ if not rows then
+ return nil, err
+ end
+ local o: DecodeOptions = opts or {}
+ if o.numbers then
+ for _, row in rows do
+ for k, v in row do
+ row[k] = convert(v)
+ end
+ end
+ end
+ if not o.header then
+ return rows, nil
+ end
+ local names = rows[1] or {}
+ local out = table.create(math.max(#rows - 1, 0))
+ for k = 2, #rows do
+ local row = rows[k]
+ local obj = Types.object()
+ for c, name in names do
+ if row[c] ~= nil then
+ Types.set(obj, tostring(name), row[c])
+ end
+ end
+ out[k - 1] = obj
+ end
+ return out, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+local function text(v: any): (string?, string?)
+ local tv = type(v)
+ if tv == "string" then
+ return v, nil
+ elseif tv == "number" then
+ local s = Json.number(v)
+ if not s then
+ return if v ~= v then "nan" elseif v > 0 then "inf" else "-inf", nil
+ end
+ return s, nil
+ elseif tv == "boolean" then
+ return if v then "true" else "false", nil
+ elseif v == nil or v == Types.null then
+ return "", nil
+ elseif tv == "table" and Types.Date.is(v) then
+ return tostring(v), nil
+ end
+ return nil, "cannot write a " .. tv .. " as a field"
+end
+
+local function isArray(t: any): boolean
+ if type(t) ~= "table" or Types.isObject(t) then
+ return false
+ end
+ local n = #t
+ return n > 0 or next(t) == nil
+end
+
+function Csv.encode(rows: any, opts: EncodeOptions?): (buffer?, Err.Err?)
+ local o: EncodeOptions = opts or {}
+ local d, q, nl = o.delimiter or ",", o.quote or '"', o.newline or "\r\n"
+ if #d ~= 1 or #q ~= 1 or d == q then
+ return nil, Err.new(Err.ARG, "delimiter and quote must be single, different bytes")
+ end
+ if type(rows) ~= "table" then
+ return nil, Err.new(Err.ARG, "expected an array of rows")
+ end
+ local special = "[" .. patEscape(d) .. patEscape(q) .. "\r\n]"
+ local qq = q .. q
+ local out: { string } = {}
+ local function writeRow(fields: { any }, count: number): Err.Err?
+ local parts = table.create(count)
+ for k = 1, count do
+ local s, e = text(fields[k])
+ if not s then
+ return Err.new(Err.ARG, "row " .. (#out + 1) .. ", field " .. k .. ": " .. tostring(e))
+ end
+ if o.quoteAll or find(s, special) or (count == 1 and s == "") then
+ s = q .. gsub(s, patEscape(q), qq) .. q
+ end
+ parts[k] = s
+ end
+ table.insert(out, table.concat(parts, d) .. nl)
+ return nil
+ end
+ local keyed = rows[1] ~= nil and not isArray(rows[1])
+ if keyed then
+ local cols = o.columns
+ if not cols then
+ local seen, list = {}, {}
+ for _, row in rows do
+ if type(row) ~= "table" then
+ return nil, Err.new(Err.ARG, "rows must be tables")
+ end
+ for _, k in Types.keys(row) do
+ if not seen[k] then
+ seen[k] = true
+ table.insert(list, k)
+ end
+ end
+ end
+ cols = list
+ end
+ local cl = cols :: { any }
+ if o.header ~= false then
+ local e = writeRow(cl, #cl)
+ if e then
+ return nil, e
+ end
+ end
+ for _, row in rows do
+ local fields = table.create(#cl)
+ for k, name in cl do
+ fields[k] = row[name]
+ end
+ local e = writeRow(fields, #cl)
+ if e then
+ return nil, e
+ end
+ end
+ else
+ for _, row in rows do
+ if type(row) ~= "table" then
+ return nil, Err.new(Err.ARG, "rows must be arrays of fields")
+ end
+ local e = writeRow(row, #row)
+ if e then
+ return nil, e
+ end
+ end
+ end
+ return buffer.fromstring(table.concat(out)), nil
+end
+
+return Csv
diff --git a/src/Formats/data/ini/init.luau b/src/Formats/data/ini/init.luau
new file mode 100644
index 0000000..fe48955
--- /dev/null
+++ b/src/Formats/data/ini/init.luau
@@ -0,0 +1,250 @@
+--!strict
+-- data/ini: INI / config files, read the way Python's configparser does (interpolation off, key case kept). New code.
+-- Supports: [sections] (name = everything between the first '[' and the last ']'), key = value and key: value,
+-- ; and # comment lines (indented too), indented continuation lines (joined with "\n"), keys before any section (at
+-- the top level), duplicate keys / sections (the last value wins, sections merge), inline comments, keys without a
+-- value and typed values by option. Decodes to a Types.object of sections (each a Types.object of strings), top-level
+-- keys beside them. Encode writes configparser's layout ("key = value", a blank line after each section, nested
+-- tables as dotted section names). Not supported: interpolation, the DEFAULT section's inheritance, escapes.
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Types = require("@formats/Types")
+local Json = require("@formats/codecs/Json")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Ini = {
+ name = "ini",
+ category = "data",
+ extensions = { "ini", "cfg", "conf", "inf", "desktop" },
+ mime = { "text/plain" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/Json" },
+ caps = { decode = true, encode = true, ordered = true },
+}
+
+export type DecodeOptions = {
+ inlineComments: boolean?, -- strip " ;..." / " #..." after values (default false, like configparser)
+ allowNoValue: boolean?, -- a line with a key and no delimiter is the key with value true (default false: an error)
+ types: boolean?, -- values that are numbers / true / false / yes / no / on / off become numbers / booleans
+ strict: boolean?, -- a duplicate section or key is an error (default false: last wins / merge)
+}
+export type EncodeOptions = {
+ delimiter: string?, -- default " = "
+}
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Ini.sniff(r: Bytes.Reader): number
+ local head = r:peek(512)
+ if string.find(head, "%z") then
+ return 0
+ end
+ local first = string.match(head, "^[%s]*([^\r\n]*)")
+ while first and string.match(first, "^[;#]") do
+ head = string.match(head, "^[^\n]*\n(.*)$") or ""
+ first = string.match(head, "^[%s]*([^\r\n]*)")
+ end
+ if first and string.match(first, "^%[[^%]]+%]%s*$") then
+ return 0.2
+ end
+ return 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+local BOOLS: { [string]: boolean } = { ["true"] = true, ["false"] = false, yes = true, no = false, on = true, off = false }
+
+local function typed(v: any): any
+ if type(v) ~= "string" then
+ return v
+ end
+ local b = BOOLS[string.lower(v)]
+ if b ~= nil then
+ return b
+ end
+ if string.match(v, "^[%-%+]?%d+%.?%d*[eE]?[%-%+]?%d*$") or string.match(v, "^[%-%+]?%.%d+$") or string.match(v, "^0x%x+$") then
+ local n = tonumber(v)
+ if n then
+ return n
+ end
+ end
+ return v
+end
+
+function Ini.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
+ local o: DecodeOptions = opts or {}
+ local s = buffer.readstring(r.buf, r.base, r.limit - r.base)
+ if string.sub(s, 1, 3) == "\239\187\191" then
+ s = string.sub(s, 4)
+ end
+ local root = Types.object()
+ local cur = root
+ local lastKey: string? = nil
+ local lastIndent = 0
+ local lastTable: any = nil
+ local seenKeys: { [any]: { [string]: boolean } } = {}
+ local pos = 1
+ local lineStart = 0
+ for line in string.gmatch(s .. "\n", "([^\n]*)\n") do
+ lineStart = pos - 1
+ pos += #line + 1
+ line = string.gsub(line, "\r$", "")
+ local indent = #(string.match(line, "^[ \t]*") :: string)
+ local trimmed = string.match(line, "^%s*(.-)%s*$") :: string
+ if trimmed == "" then
+ lastKey = nil
+ elseif string.match(trimmed, "^[;#]") then
+ -- a comment line (configparser: also when indented); it does not end a continuation
+ elseif lastKey and indent > lastIndent then
+ -- continuation of the previous value
+ local v = trimmed
+ if o.inlineComments then
+ v = string.match(v, "^(.-)%s+[;#]") or v
+ end
+ local prev = lastTable[lastKey]
+ lastTable[lastKey] = (if type(prev) == "string" then prev else "") .. "\n" .. v
+ elseif string.sub(trimmed, 1, 1) == "[" and string.find(trimmed, "]", 2, true) then
+ local name = string.match(trimmed, "^%[(.*)%]") :: string
+ local existing = root[name]
+ if existing ~= nil and type(existing) ~= "table" then
+ return nil, Err.new(Err.CORRUPT, "section [" .. name .. "] has the name of a top-level key", lineStart)
+ end
+ if existing and o.strict then
+ return nil, Err.new(Err.CORRUPT, "duplicate section [" .. name .. "]", lineStart)
+ end
+ if not existing then
+ existing = Types.object()
+ Types.set(root, name, existing)
+ end
+ cur = existing
+ lastKey = nil
+ else
+ local key, value = string.match(trimmed, "^(.-)%s*[=:]%s*(.*)$")
+ if not key then
+ if not o.allowNoValue then
+ return nil, Err.new(Err.CORRUPT, "line without '=' or ':': " .. string.sub(trimmed, 1, 40), lineStart)
+ end
+ key, value = trimmed, true :: any
+ end
+ if key == "" then
+ return nil, Err.new(Err.CORRUPT, "empty key", lineStart)
+ end
+ if o.inlineComments and type(value) == "string" then
+ value = string.match(value, "^(.-)%s+[;#]") or (if string.match(value, "^[;#]") then "" else value)
+ end
+ local seen = seenKeys[cur]
+ if not seen then
+ seen = {}
+ seenKeys[cur] = seen
+ end
+ if seen[key :: string] and o.strict then
+ return nil, Err.new(Err.CORRUPT, "duplicate key " .. key, lineStart)
+ end
+ seen[key :: string] = true
+ if cur == root and type(root[key]) == "table" then
+ return nil, Err.new(Err.CORRUPT, "top-level key " .. key .. " has the name of a section", lineStart)
+ end
+ Types.set(cur, key, value)
+ lastKey, lastIndent, lastTable = key, indent, cur
+ end
+ end
+ if o.types then
+ for _, k in Types.keys(root) do
+ local v = root[k]
+ if type(v) == "table" then
+ for _, k2 in Types.keys(v) do
+ v[k2] = typed(v[k2])
+ end
+ else
+ root[k] = typed(v)
+ end
+ end
+ end
+ return root, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+local function text(v: any): string?
+ local tv = type(v)
+ if tv == "string" then
+ return (string.gsub(v, "\n", "\n\t"))
+ elseif tv == "number" then
+ return Json.number(v) or tostring(v)
+ elseif tv == "boolean" then
+ return if v then "true" else "false"
+ elseif v == Types.null then
+ return ""
+ elseif tv == "table" and Types.Date.is(v) then
+ return tostring(v)
+ end
+ return nil
+end
+
+function Ini.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
+ if type(value) ~= "table" then
+ return nil, Err.new(Err.ARG, "expected a table of sections")
+ end
+ local delim = (opts and opts.delimiter) or " = "
+ local out: { string } = {}
+ local err: string? = nil
+ local function keyOk(k: any): boolean
+ if type(k) ~= "string" and type(k) ~= "number" then
+ err = "keys must be strings"
+ return false
+ end
+ local ks = tostring(k)
+ if ks == "" or string.find(ks, "[=:\r\n]") or string.match(ks, "^[%s;#%[]") or string.match(ks, "%s$") then
+ err = "key " .. string.format("%q", ks) .. " cannot be written"
+ return false
+ end
+ return true
+ end
+ local function pairsOf(t: any, prefix: string, depth: number): boolean
+ if depth > 32 then
+ err = "sections nested too deeply (a cycle?)"
+ return false
+ end
+ local subs = {}
+ local lines = {}
+ for _, k in Types.keys(t) do
+ local v = t[k]
+ if type(v) == "table" and not Types.Date.is(v) and v ~= Types.null then
+ table.insert(subs, k)
+ else
+ if not keyOk(k) then
+ return false
+ end
+ local s = text(v)
+ if not s then
+ err = "cannot write a " .. type(v) .. " value"
+ return false
+ end
+ table.insert(lines, tostring(k) .. delim .. s .. "\n")
+ end
+ end
+ if prefix ~= "" then
+ table.insert(out, "[" .. prefix .. "]\n")
+ table.move(lines, 1, #lines, #out + 1, out)
+ table.insert(out, "\n")
+ elseif #lines > 0 then
+ table.move(lines, 1, #lines, #out + 1, out)
+ table.insert(out, "\n")
+ end
+ for _, k in subs do
+ local name = tostring(k)
+ if string.find(name, "[\r\n%]]") then
+ err = "section name " .. string.format("%q", name) .. " cannot be written"
+ return false
+ end
+ if not pairsOf(t[k], if prefix == "" then name else prefix .. "." .. name, depth + 1) then
+ return false
+ end
+ end
+ return true
+ end
+ if not pairsOf(value, "", 0) then
+ return nil, Err.new(Err.ARG, err or "cannot encode")
+ end
+ return buffer.fromstring(table.concat(out)), nil
+end
+
+return Ini
diff --git a/src/Formats/data/json/init.luau b/src/Formats/data/json/init.luau
new file mode 100644
index 0000000..bf75d5f
--- /dev/null
+++ b/src/Formats/data/json/init.luau
@@ -0,0 +1,93 @@
+--!strict
+-- data/json: JSON (RFC 8259) files, a thin wrapper over codecs/Json (which see for the value mapping and options).
+-- Supports: decode to plain Luau values (Types.null, ordered keys and bigInts as strings by option), encode compact or
+-- pretty. JSON Lines through codecs/Json.lines. Not supported: JSON5 / comments / trailing commas.
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Json = require("@formats/codecs/Json")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local JsonFormat = {
+ name = "json",
+ category = "data",
+ extensions = { "json", "jsonl", "ndjson", "geojson" },
+ mime = { "application/json", "application/x-ndjson" },
+ deps = { "core/Err", "core/Bytes", "codecs/Json" },
+ caps = { decode = true, encode = true, ordered = true, streaming = true },
+}
+
+export type DecodeOptions = Json.DecodeOptions & {
+ lines: boolean?, -- JSON Lines: decode every value into an array (default false: one value)
+}
+export type EncodeOptions = Json.EncodeOptions & {
+ lines: boolean?, -- JSON Lines: the value must be an array, written one compact value per line
+}
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function JsonFormat.sniff(r: Bytes.Reader): number
+ local head = r:peek(64)
+ if string.sub(head, 1, 3) == "\239\187\191" then
+ head = string.sub(head, 4)
+ end
+ local first = string.match(head, "^[ \t\r\n]*(.)")
+ if first == "{" then
+ local nxt = string.match(head, "^[^{]*{[ \t\r\n]*(.)")
+ return if nxt == nil or nxt == '"' or nxt == "}" then 0.6 else 0.1
+ elseif first == "[" then
+ -- past any nested '[': a JSON value must start (TOML / INI "[section]" and "[[table]]" do not)
+ local nxt = string.match(head, "^[ \t\r\n]*[%[ \t\r\n]*(.)")
+ if nxt == nil or string.find('{"-0123456789tfn]', nxt, 1, true) then
+ return 0.3
+ end
+ return 0
+ end
+ return 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+function JsonFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
+ local s = buffer.readstring(r.buf, r.base, r.limit - r.base)
+ if opts and opts.lines then
+ local out = {}
+ for _, v, err in Json.lines(s, opts) do
+ if err then
+ return nil, err
+ end
+ table.insert(out, v)
+ end
+ return out, nil
+ end
+ return Json.decode(s, opts)
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+function JsonFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
+ if opts and opts.lines then
+ if type(value) ~= "table" then
+ return nil, Err.new(Err.ARG, "lines: expected an array of values")
+ end
+ local o = table.clone(opts) :: any
+ o.indent = nil
+ local parts = {}
+ for i, v in value do
+ local s, err = Json.encode(v, o)
+ if not s then
+ return nil, err
+ end
+ parts[i] = s .. "\n"
+ end
+ return buffer.fromstring(table.concat(parts)), nil
+ end
+ local s, err = Json.encode(value, opts)
+ if not s then
+ return nil, err
+ end
+ if opts and opts.indent then
+ s ..= "\n"
+ end
+ return buffer.fromstring(s), nil
+end
+
+return JsonFormat
diff --git a/src/Formats/data/msgpack/Codec.luau b/src/Formats/data/msgpack/Codec.luau
new file mode 100644
index 0000000..fd42577
--- /dev/null
+++ b/src/Formats/data/msgpack/Codec.luau
@@ -0,0 +1,468 @@
+--!strict
+--!native
+-- data/msgpack/Codec: the MessagePack decoder and encoder behind data/msgpack (msgpack spec, 2017 revision with
+-- str8 / bin / ext and the timestamp extension). Never throws: errors return nil, message, offset.
+local Bytes = require("@formats/core/Bytes")
+local Types = require("@formats/Types")
+
+local Codec = {}
+
+local TWO32 = 4294967296
+
+-- an extension value: { type = -128..127, data = buffer }
+local ExtMeta = { __tostring = function(e: any): string
+ return "msgpack.ext(" .. e.type .. ", " .. buffer.len(e.data) .. " bytes)"
+end }
+function Codec.ext(t: number, data: buffer): { type: number, data: buffer }
+ return setmetatable({ type = t, data = data }, ExtMeta) :: any
+end
+function Codec.isExt(v: any): boolean
+ return type(v) == "table" and getmetatable(v) == ExtMeta
+end
+
+-- decimal text of hi * 2^32 + lo (hi, lo unsigned 32-bit), exact
+local function u64text(hi: number, lo: number): string
+ if hi == 0 then
+ return string.format("%d", lo)
+ end
+ local digits = {}
+ -- long division by 10 on four 16-bit limbs
+ local l = { hi // 65536, hi % 65536, lo // 65536, lo % 65536 }
+ while l[1] ~= 0 or l[2] ~= 0 or l[3] ~= 0 or l[4] ~= 0 do
+ local rem = 0
+ for k = 1, 4 do
+ local cur = rem * 65536 + l[k]
+ l[k] = cur // 10
+ rem = cur % 10
+ end
+ table.insert(digits, 1, string.char(48 + rem))
+ end
+ return table.concat(digits)
+end
+Codec.u64text = u64text
+
+export type DecodeOptions = {
+ bigInts: ("number" | "string")?, -- 64-bit integers past 2^53: "string" keeps the exact decimal text
+ null: any?, -- the value for nil (default Types.null)
+ maxDepth: number?, -- nesting limit (default 512)
+ timestamps: boolean?, -- ext -1 as a Types.Date (default true)
+ ordered: boolean?, -- maps as Types.object with key order (default true)
+}
+
+type St = { r: Bytes.Reader, big: boolean, null: any, maxDepth: number, ts: boolean, ordered: boolean }
+
+local function int64(st: St, signed: boolean): any
+ local r = st.r
+ local hi, lo = r:u32be(), r:u32be()
+ if signed and hi >= 0x80000000 then
+ -- negative: two's complement
+ local nhi, nlo = 0xFFFFFFFF - hi, TWO32 - lo
+ if nlo == TWO32 then
+ nlo = 0
+ nhi += 1
+ end
+ if st.big and nhi >= 0x200000 then
+ return "-" .. u64text(nhi, nlo)
+ end
+ return -(nhi * TWO32 + nlo)
+ end
+ if st.big and hi >= 0x200000 then
+ return u64text(hi, lo)
+ end
+ return hi * TWO32 + lo
+end
+
+local value: (st: St, depth: number) -> (any, string?)
+
+local function ext(st: St, n: number): (any, string?)
+ local r = st.r
+ local t = r:i8()
+ if r.err or not r:need(n) then
+ return nil, "truncated ext"
+ end
+ if t == -1 and st.ts then
+ local secs, ns = 0, 0
+ if n == 4 then
+ secs = r:u32be()
+ elseif n == 8 then
+ local hi, lo = r:u32be(), r:u32be()
+ ns = hi // 4
+ secs = (hi % 4) * TWO32 + lo
+ elseif n == 12 then
+ ns = r:u32be()
+ secs = r:i64be()
+ else
+ return nil, "bad timestamp length"
+ end
+ if ns > 999999999 then
+ return nil, "bad timestamp nanoseconds"
+ end
+ local d: any = Types.Date.fromUnix(secs)
+ d.nanosecond = ns
+ return d, nil
+ end
+ return Codec.ext(t, r:bytes(n)), nil
+end
+
+local function array(st: St, n: number, depth: number): (any, string?)
+ if n > st.r:remaining() then
+ return nil, "array count past the end"
+ end
+ local t = table.create(n)
+ for k = 1, n do
+ local v, e = value(st, depth + 1)
+ if e then
+ return nil, e
+ end
+ t[k] = v
+ end
+ return t, nil
+end
+
+local function map(st: St, n: number, depth: number): (any, string?)
+ if n * 2 > st.r:remaining() then
+ return nil, "map count past the end"
+ end
+ local t = {}
+ local order: { any }? = if st.ordered then table.create(n) else nil
+ for _ = 1, n do
+ local k, e = value(st, depth + 1)
+ if e then
+ return nil, e
+ end
+ local v, e2 = value(st, depth + 1)
+ if e2 then
+ return nil, e2
+ end
+ if k ~= k then
+ return nil, "NaN map key"
+ end
+ if order and t[k] == nil then
+ table.insert(order, k)
+ end
+ t[k] = v
+ end
+ return Types.object(t, order or {}), nil
+end
+
+function value(st: St, depth: number): (any, string?)
+ if depth > st.maxDepth then
+ return nil, "nested deeper than " .. st.maxDepth
+ end
+ local r = st.r
+ local b = r:u8()
+ if r.err then
+ return nil, "truncated"
+ end
+ if b < 0x80 then
+ return b, nil
+ elseif b >= 0xE0 then
+ return b - 256, nil
+ elseif b < 0x90 then
+ return map(st, b - 0x80, depth)
+ elseif b < 0xA0 then
+ return array(st, b - 0x90, depth)
+ elseif b < 0xC0 then
+ local n = b - 0xA0
+ if not r:need(n) then
+ return nil, "truncated string"
+ end
+ return r:string(n), nil
+ elseif b == 0xC0 then
+ return st.null, nil
+ elseif b == 0xC2 then
+ return false, nil
+ elseif b == 0xC3 then
+ return true, nil
+ elseif b == 0xC4 or b == 0xC5 or b == 0xC6 then
+ local n = if b == 0xC4 then r:u8() elseif b == 0xC5 then r:u16be() else r:u32be()
+ if r.err or not r:need(n) then
+ return nil, "truncated bin"
+ end
+ return r:bytes(n), nil
+ elseif b == 0xC7 or b == 0xC8 or b == 0xC9 then
+ local n = if b == 0xC7 then r:u8() elseif b == 0xC8 then r:u16be() else r:u32be()
+ if r.err then
+ return nil, "truncated ext"
+ end
+ return ext(st, n)
+ elseif b == 0xCA then
+ local v = r:f32be()
+ return if r.err then nil else v, if r.err then "truncated" else nil
+ elseif b == 0xCB then
+ local v = r:f64be()
+ return if r.err then nil else v, if r.err then "truncated" else nil
+ elseif b >= 0xCC and b <= 0xD3 then
+ local v: any
+ if b == 0xCC then
+ v = r:u8()
+ elseif b == 0xCD then
+ v = r:u16be()
+ elseif b == 0xCE then
+ v = r:u32be()
+ elseif b == 0xCF then
+ v = int64(st, false)
+ elseif b == 0xD0 then
+ v = r:i8()
+ elseif b == 0xD1 then
+ v = r:i16be()
+ elseif b == 0xD2 then
+ v = r:i32be()
+ else
+ v = int64(st, true)
+ end
+ if r.err then
+ return nil, "truncated"
+ end
+ return v, nil
+ elseif b >= 0xD4 and b <= 0xD8 then
+ return ext(st, 2 ^ (b - 0xD4))
+ elseif b >= 0xD9 and b <= 0xDB then
+ local n = if b == 0xD9 then r:u8() elseif b == 0xDA then r:u16be() else r:u32be()
+ if r.err or not r:need(n) then
+ return nil, "truncated string"
+ end
+ return r:string(n), nil
+ elseif b == 0xDC or b == 0xDD then
+ local n = if b == 0xDC then r:u16be() else r:u32be()
+ if r.err then
+ return nil, "truncated"
+ end
+ return array(st, n, depth)
+ elseif b == 0xDE or b == 0xDF then
+ local n = if b == 0xDE then r:u16be() else r:u32be()
+ if r.err then
+ return nil, "truncated"
+ end
+ return map(st, n, depth)
+ end
+ return nil, string.format("reserved type byte 0x%02x", b)
+end
+
+-- decode(r, opts) -> value, nil | nil, message, offset (one value; r is left after it)
+function Codec.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, string?, number?)
+ local o: DecodeOptions = opts or {}
+ local st: St = {
+ r = r,
+ big = o.bigInts == "string",
+ null = if o.null ~= nil then o.null else Types.null,
+ maxDepth = o.maxDepth or 512,
+ ts = o.timestamps ~= false,
+ ordered = o.ordered ~= false,
+ }
+ local v, e = value(st, 0)
+ if e then
+ return nil, e, r.pos - r.base
+ end
+ return v, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+export type EncodeOptions = {
+ float32: boolean?, -- non-integer numbers as float32 (default false: float64)
+ sortKeys: boolean?, -- plain tables' keys sorted (default true; Types.object keeps its order)
+ emptyTable: ("array" | "map")?, -- a plain empty table (default "array")
+ maxDepth: number?, -- default 512 (also catches cycles)
+ stringsAsBin: boolean?, -- strings as bin (default false: str)
+}
+
+type ESt = { w: Bytes.Writer, f32: boolean, sort: boolean, emptyMap: boolean, maxDepth: number, bin: boolean, err: string? }
+
+local function writeInt(w: Bytes.Writer, v: number)
+ if v >= 0 then
+ if v < 128 then
+ w:u8(v)
+ elseif v < 256 then
+ w:u8(0xCC)
+ w:u8(v)
+ elseif v < 65536 then
+ w:u8(0xCD)
+ w:u16be(v)
+ elseif v < TWO32 then
+ w:u8(0xCE)
+ w:u32be(v)
+ else
+ w:u8(0xCF)
+ w:u64be(v)
+ end
+ else
+ if v >= -32 then
+ w:u8(v + 256)
+ elseif v >= -128 then
+ w:u8(0xD0)
+ w:u8(v + 256)
+ elseif v >= -32768 then
+ w:u8(0xD1)
+ w:u16be(v + 65536)
+ elseif v >= -2147483648 then
+ w:u8(0xD2)
+ w:u32be(v + TWO32)
+ else
+ w:u8(0xD3)
+ local hi = math.floor(v / TWO32)
+ local lo = v - hi * TWO32
+ w:u32be(hi + TWO32)
+ w:u32be(lo)
+ end
+ end
+end
+
+local function lenHeader(w: Bytes.Writer, n: number, fix: number?, fixMax: number, b8: number?, b16: number, b32: number)
+ if fix and n <= fixMax then
+ w:u8(fix + n)
+ elseif b8 and n < 256 then
+ w:u8(b8)
+ w:u8(n)
+ elseif n < 65536 then
+ w:u8(b16)
+ w:u16be(n)
+ else
+ w:u8(b32)
+ w:u32be(n)
+ end
+end
+
+local function keyLess(a: any, b: any): boolean
+ local ta, tb = type(a), type(b)
+ if ta ~= tb then
+ return ta < tb
+ end
+ if ta == "number" or ta == "string" then
+ return a < b
+ end
+ return tostring(a) < tostring(b)
+end
+
+local function isArray(t: any, emptyMap: boolean): boolean
+ if Types.isObject(t) then
+ return false
+ end
+ local n = #t
+ if n == 0 then
+ return next(t) == nil and not emptyMap
+ end
+ local c = 0
+ for _ in next, t do
+ c += 1
+ end
+ return c == n
+end
+Codec.isArray = isArray
+
+local function enc(st: ESt, v: any, depth: number): boolean
+ local w = st.w
+ local tv = type(v)
+ if v == nil or v == Types.null then
+ w:u8(0xC0)
+ elseif tv == "boolean" then
+ w:u8(if v then 0xC3 else 0xC2)
+ elseif tv == "number" then
+ if v == math.floor(v) and v >= -9223372036854775808 and v < 18446744073709551616 then
+ writeInt(w, v)
+ elseif st.f32 then
+ w:u8(0xCA)
+ w:f32be(v)
+ else
+ w:u8(0xCB)
+ w:f64be(v)
+ end
+ elseif tv == "string" then
+ if st.bin then
+ lenHeader(w, #v, nil, 0, 0xC4, 0xC5, 0xC6)
+ else
+ lenHeader(w, #v, 0xA0, 31, 0xD9, 0xDA, 0xDB)
+ end
+ w:string(v)
+ elseif tv == "buffer" then
+ lenHeader(w, buffer.len(v), nil, 0, 0xC4, 0xC5, 0xC6)
+ w:bytes(v)
+ elseif tv == "table" then
+ if depth >= st.maxDepth then
+ st.err = "nested deeper than " .. st.maxDepth .. " (a cycle?)"
+ return false
+ end
+ if Codec.isExt(v) then
+ local n = buffer.len(v.data)
+ if n == 1 or n == 2 or n == 4 or n == 8 or n == 16 then
+ w:u8(({ [1] = 0xD4, [2] = 0xD5, [4] = 0xD6, [8] = 0xD7, [16] = 0xD8 })[n])
+ else
+ lenHeader(w, n, nil, 0, 0xC7, 0xC8, 0xC9)
+ end
+ w:u8(v.type % 256)
+ w:bytes(v.data)
+ elseif Types.Date.is(v) then
+ local t = Types.Date.toUnix(v)
+ local secs = math.floor(t)
+ local ns = (v :: any).nanosecond or 0
+ if ns == 0 and secs >= 0 and secs < TWO32 then
+ w:u8(0xD6)
+ w:u8(0xFF)
+ w:u32be(secs)
+ elseif secs >= 0 and secs < 2 ^ 34 then
+ w:u8(0xD7)
+ w:u8(0xFF)
+ w:u32be(ns * 4 + secs // TWO32)
+ w:u32be(secs % TWO32)
+ else
+ w:u8(0xC7)
+ w:u8(12)
+ w:u8(0xFF)
+ w:u32be(ns)
+ local hi = math.floor(secs / TWO32)
+ w:u32be(hi % TWO32)
+ w:u32be(secs - hi * TWO32)
+ end
+ elseif isArray(v, st.emptyMap) then
+ local n = #v
+ lenHeader(w, n, 0x90, 15, nil, 0xDC, 0xDD)
+ for k = 1, n do
+ if not enc(st, v[k], depth + 1) then
+ return false
+ end
+ end
+ else
+ local keys: { any }
+ if Types.isObject(v) then
+ keys = Types.keys(v)
+ else
+ keys = {}
+ for k in next, v do
+ table.insert(keys, k)
+ end
+ if st.sort then
+ table.sort(keys, keyLess)
+ end
+ end
+ lenHeader(w, #keys, 0x80, 15, nil, 0xDE, 0xDF)
+ for _, k in keys do
+ if not enc(st, k, depth + 1) or not enc(st, v[k], depth + 1) then
+ return false
+ end
+ end
+ end
+ else
+ st.err = "cannot encode a " .. tv
+ return false
+ end
+ return true
+end
+
+-- encode(v, opts) -> buffer | nil, message
+function Codec.encode(v: any, opts: EncodeOptions?): (buffer?, string?)
+ local o: EncodeOptions = opts or {}
+ local st: ESt = {
+ w = Bytes.writer(256),
+ f32 = o.float32 == true,
+ sort = o.sortKeys ~= false,
+ emptyMap = o.emptyTable == "map",
+ maxDepth = o.maxDepth or 512,
+ bin = o.stringsAsBin == true,
+ err = nil,
+ }
+ if not enc(st, v, 0) then
+ return nil, st.err
+ end
+ return st.w:finish(), nil
+end
+
+return Codec
diff --git a/src/Formats/data/msgpack/init.luau b/src/Formats/data/msgpack/init.luau
new file mode 100644
index 0000000..ecd96f9
--- /dev/null
+++ b/src/Formats/data/msgpack/init.luau
@@ -0,0 +1,90 @@
+--!strict
+-- data/msgpack: MessagePack (msgpack spec, str8 / bin / ext revision). New code. Supports: every type, the
+-- timestamp extension (-1) as Types.Date, other extensions as Msgpack.ext(type, data), bin as buffers, maps as
+-- Types.object (key order kept; keys of any type), 64-bit integers past 2^53 as exact decimal strings by option, a
+-- stream of concatenated values (opts.all). Encode picks the smallest integer / length forms (float64 for
+-- non-integers unless opts.float32). Not supported: nothing in the spec.
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Codec = require("@formats/data/msgpack/Codec")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Msgpack = {
+ name = "msgpack",
+ category = "data",
+ extensions = { "msgpack", "mpk" },
+ mime = { "application/msgpack", "application/x-msgpack" },
+ deps = { "core/Err", "core/Bytes", "Types" },
+ caps = { decode = true, encode = true, binary = true, ordered = true },
+}
+
+export type DecodeOptions = Codec.DecodeOptions & {
+ all: boolean?, -- decode every concatenated value into an array (default false: exactly one value)
+}
+export type EncodeOptions = Codec.EncodeOptions & {
+ all: boolean?, -- the value is an array of values, written one after another
+}
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Msgpack.sniff(_r: Bytes.Reader): number
+ return 0 -- no magic: by extension or opts.format only
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+function Msgpack.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
+ local o: DecodeOptions = opts or {}
+ if o.all then
+ local out = {}
+ while not r:eof() do
+ local v, e, at = Codec.decode(r, o)
+ if e then
+ return nil, Err.new(if string.find(e, "truncated", 1, true) or string.find(e, "past the end", 1, true) then Err.TRUNCATED else Err.CORRUPT, e, at)
+ end
+ table.insert(out, v)
+ end
+ return out, nil
+ end
+ local v, e, at = Codec.decode(r, o)
+ if e then
+ local code = if string.find(e, "truncated", 1, true) or string.find(e, "past the end", 1, true) then Err.TRUNCATED
+ elseif string.find(e, "nested deeper", 1, true) then Err.LIMIT
+ else Err.CORRUPT
+ return nil, Err.new(code, e, at)
+ end
+ if not r:eof() then
+ return nil, Err.new(Err.CORRUPT, "trailing data after the value (opts.all reads a stream)", r.pos - r.base)
+ end
+ return v, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+function Msgpack.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
+ if opts and opts.all then
+ if type(value) ~= "table" then
+ return nil, Err.new(Err.ARG, "all: expected an array of values")
+ end
+ local w = Bytes.writer()
+ for _, v in value do
+ local b, e = Codec.encode(v, opts)
+ if not b then
+ return nil, Err.new(Err.ARG, e or "cannot encode")
+ end
+ w:bytes(b)
+ end
+ return w:finish(), nil
+ end
+ local b, e = Codec.encode(value, opts)
+ if not b then
+ return nil, Err.new(Err.ARG, e or "cannot encode")
+ end
+ return b, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ extras
+-- ext(type, data) -> an extension value { type, data } that encodes as ext; isExt(v)
+Msgpack.ext = Codec.ext
+Msgpack.isExt = Codec.isExt
+
+return Msgpack
diff --git a/src/Formats/data/plist/Base64.luau b/src/Formats/data/plist/Base64.luau
new file mode 100644
index 0000000..115cf94
--- /dev/null
+++ b/src/Formats/data/plist/Base64.luau
@@ -0,0 +1,71 @@
+--!strict
+--!native
+-- data/plist/Base64: RFC 4648 base64 for plist (decode skips whitespace; encode wraps lines). Never throws.
+local Base64 = {}
+
+local ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
+local DEC: { [number]: number } = {}
+for i = 1, 64 do
+ DEC[string.byte(ALPHA, i)] = i - 1
+end
+local ENC: { string } = {}
+for i = 1, 64 do
+ ENC[i - 1] = string.sub(ALPHA, i, i)
+end
+
+-- decode(s) -> buffer | nil, message (whitespace ignored; padding optional)
+function Base64.decode(s: string): (buffer?, string?)
+ local clean = string.gsub(s, "[ \t\r\n]", "")
+ clean = string.gsub(clean, "=+$", "")
+ local n = #clean
+ if n % 4 == 1 then
+ return nil, "bad base64 length"
+ end
+ local out = buffer.create(n * 3 // 4)
+ local o = 0
+ local acc, bits = 0, 0
+ for i = 1, n do
+ local v = DEC[string.byte(clean, i)]
+ if v == nil then
+ return nil, "bad base64 character"
+ end
+ acc = acc * 64 + v
+ bits += 6
+ if bits >= 8 then
+ bits -= 8
+ local b = acc // (2 ^ bits)
+ buffer.writeu8(out, o, b)
+ o += 1
+ acc -= b * 2 ^ bits
+ end
+ end
+ return out, nil
+end
+
+-- encode(b, lineBytes?) -> base64 text; lineBytes > 0 puts "\n" after every lineBytes input bytes (and at the end)
+function Base64.encode(b: buffer, lineBytes: number?): string
+ local n = buffer.len(b)
+ local parts = table.create(n // 3 + 2)
+ local per = lineBytes or 0
+ local k = 0
+ local i = 0
+ while i < n do
+ local a = buffer.readu8(b, i)
+ local c1 = if i + 1 < n then buffer.readu8(b, i + 1) else 0
+ local c2 = if i + 2 < n then buffer.readu8(b, i + 2) else 0
+ local v = a * 65536 + c1 * 256 + c2
+ local q = ENC[v // 262144] .. ENC[(v // 4096) % 64]
+ q ..= if i + 1 < n then ENC[(v // 64) % 64] else "="
+ q ..= if i + 2 < n then ENC[v % 64] else "="
+ k += 1
+ parts[k] = q
+ i += 3
+ if per > 0 and (i % per == 0 or i >= n) then
+ k += 1
+ parts[k] = "\n"
+ end
+ end
+ return table.concat(parts)
+end
+
+return Base64
diff --git a/src/Formats/data/plist/Binary.luau b/src/Formats/data/plist/Binary.luau
new file mode 100644
index 0000000..544fe33
--- /dev/null
+++ b/src/Formats/data/plist/Binary.luau
@@ -0,0 +1,271 @@
+--!strict
+--!native
+-- data/plist/Binary: the binary property list reader ("bplist00", CoreFoundation's format as documented in
+-- CFBinaryPList.c and implemented by Python's plistlib). Objects: null / bool / fill, ints (1, 2, 4, 8 bytes; 16-byte
+-- ints are read from their low 8 bytes), reals (4 / 8 bytes), dates, data, ASCII / UTF-16BE / UTF-8 strings, UIDs,
+-- arrays, sets (as arrays), dicts (Types.object, key order kept). Shared references decode to the same table; cycles
+-- are errors. Never throws: errors return nil, message.
+local Types = require("@formats/Types")
+
+local Binary = {}
+
+local readu8 = buffer.readu8
+local TWO32 = 4294967296
+local EPOCH_2001 = 978307200
+
+local UidMeta = { __tostring = function(u: any): string
+ return "UID(" .. u.uid .. ")"
+end }
+function Binary.uid(n: number): { uid: number }
+ return setmetatable({ uid = n }, UidMeta) :: any
+end
+function Binary.isUid(v: any): boolean
+ return type(v) == "table" and getmetatable(v) == UidMeta
+end
+
+local function be(b: buffer, o: number, n: number): number
+ local v = 0
+ for k = 0, n - 1 do
+ v = v * 256 + readu8(b, o + k)
+ end
+ return v
+end
+
+local function utf8char(c: number): string
+ if c < 0x80 then
+ return string.char(c)
+ elseif c < 0x800 then
+ return string.char(0xC0 + c // 64, 0x80 + c % 64)
+ elseif c < 0x10000 then
+ return string.char(0xE0 + c // 4096, 0x80 + (c // 64) % 64, 0x80 + c % 64)
+ end
+ return string.char(0xF0 + c // 262144, 0x80 + (c // 4096) % 64, 0x80 + (c // 64) % 64, 0x80 + c % 64)
+end
+
+export type Options = { bigInts: ("number" | "string")?, maxDepth: number? }
+
+-- decode(buf, base, len, opts) -> value | nil, message
+function Binary.decode(b: buffer, base: number, len: number, opts: Options?): (any, string?)
+ if len < 40 then
+ return nil, "truncated: shorter than header + trailer"
+ end
+ local t = base + len - 32
+ local offSize, refSize = readu8(b, t + 6), readu8(b, t + 7)
+ local numObjects = be(b, t + 8, 8)
+ local top = be(b, t + 16, 8)
+ local tableOff = be(b, t + 24, 8)
+ if offSize < 1 or offSize > 8 or refSize < 1 or refSize > 8 then
+ return nil, "bad trailer sizes"
+ end
+ if numObjects < 1 or top >= numObjects or tableOff < 8 or tableOff + numObjects * offSize > len - 32 then
+ return nil, "bad trailer"
+ end
+ local maxDepth = (opts and opts.maxDepth) or 512
+ local cache: { [number]: any } = {}
+ local busy: { [number]: boolean } = {}
+
+ local object: (idx: number, depth: number) -> (any, string?)
+
+ -- a length nibble: 0..14, or 15 = an int object follows
+ local function count(o: number, nib: number): (number?, number)
+ if nib < 15 then
+ return nib, o + 1
+ end
+ if o + 2 > len - 32 then
+ return nil, 0
+ end
+ local m = readu8(b, base + o + 1)
+ if m // 16 ~= 1 then
+ return nil, 0
+ end
+ local w = 2 ^ (m % 16)
+ if w > 8 or o + 2 + w > len - 32 then
+ return nil, 0
+ end
+ return be(b, base + o + 2, w), o + 2 + w
+ end
+
+ local function ref(at: number): number
+ return be(b, base + at, refSize)
+ end
+
+ function object(idx: number, depth: number): (any, string?)
+ local cached = cache[idx]
+ if cached ~= nil then
+ return cached, nil
+ end
+ if busy[idx] then
+ return nil, "object references form a cycle"
+ end
+ if depth > maxDepth then
+ return nil, "nested deeper than " .. maxDepth
+ end
+ if idx >= numObjects then
+ return nil, "object reference out of range"
+ end
+ local o = be(b, base + tableOff + idx * offSize, offSize)
+ if o < 8 or o >= len - 32 then
+ return nil, "object offset out of range"
+ end
+ local marker = readu8(b, base + o)
+ local hi, nib = marker // 16, marker % 16
+ local v: any
+ if marker == 0x00 then
+ v = Types.null
+ elseif marker == 0x08 then
+ v = false
+ elseif marker == 0x09 then
+ v = true
+ elseif hi == 1 then
+ local w = 2 ^ nib
+ if w > 16 or o + 1 + w > len - 32 then
+ return nil, "bad integer"
+ end
+ if w == 16 then
+ o += 8
+ w = 8
+ end
+ if w == 8 then
+ local h, l = be(b, base + o + 1, 4), be(b, base + o + 5, 4)
+ if h >= 0x80000000 and nib == 3 then
+ v = (h - TWO32) * TWO32 + l
+ elseif opts and opts.bigInts == "string" and h >= 0x200000 then
+ -- exact decimal text of h * 2^32 + l
+ local digits = {}
+ local limbs = { h // 65536, h % 65536, l // 65536, l % 65536 }
+ while limbs[1] + limbs[2] + limbs[3] + limbs[4] > 0 do
+ local rem = 0
+ for k = 1, 4 do
+ local cur = rem * 65536 + limbs[k]
+ limbs[k] = cur // 10
+ rem = cur % 10
+ end
+ table.insert(digits, 1, string.char(48 + rem))
+ end
+ v = table.concat(digits)
+ else
+ v = h * TWO32 + l
+ end
+ else
+ v = be(b, base + o + 1, w)
+ end
+ elseif hi == 2 then
+ if nib == 2 and o + 5 <= len - 32 then
+ local s = buffer.create(4)
+ for k = 0, 3 do
+ buffer.writeu8(s, k, readu8(b, base + o + 4 - k))
+ end
+ v = buffer.readf32(s, 0)
+ elseif nib == 3 and o + 9 <= len - 32 then
+ local s = buffer.create(8)
+ for k = 0, 7 do
+ buffer.writeu8(s, k, readu8(b, base + o + 8 - k))
+ end
+ v = buffer.readf64(s, 0)
+ else
+ return nil, "bad real"
+ end
+ elseif marker == 0x33 then
+ if o + 9 > len - 32 then
+ return nil, "truncated date"
+ end
+ local s = buffer.create(8)
+ for k = 0, 7 do
+ buffer.writeu8(s, k, readu8(b, base + o + 8 - k))
+ end
+ local secs = buffer.readf64(s, 0)
+ if secs ~= secs or math.abs(secs) > 1e14 then
+ return nil, "bad date"
+ end
+ v = Types.Date.fromUnix(secs + EPOCH_2001)
+ elseif hi == 4 or hi == 5 or hi == 6 or hi == 7 then
+ local n, p = count(o, nib)
+ if not n then
+ return nil, "bad length"
+ end
+ local bytes = if hi == 6 then n * 2 else n
+ if p + bytes > len - 32 then
+ return nil, "string / data past the end"
+ end
+ if hi == 4 then
+ local d = buffer.create(bytes)
+ buffer.copy(d, 0, b, base + p, bytes)
+ v = d
+ elseif hi == 6 then
+ local parts = table.create(n)
+ local k = 0
+ while k < n do
+ local u = be(b, base + p + k * 2, 2)
+ k += 1
+ if u >= 0xD800 and u <= 0xDBFF and k < n then
+ local lo = be(b, base + p + k * 2, 2)
+ if lo >= 0xDC00 and lo <= 0xDFFF then
+ u = 0x10000 + (u - 0xD800) * 1024 + (lo - 0xDC00)
+ k += 1
+ end
+ end
+ table.insert(parts, utf8char(u))
+ end
+ v = table.concat(parts)
+ else
+ v = buffer.readstring(b, base + p, bytes)
+ end
+ elseif hi == 8 then
+ if o + 2 + nib > len - 32 then
+ return nil, "bad UID"
+ end
+ v = Binary.uid(be(b, base + o + 1, nib + 1))
+ elseif hi == 0xA or hi == 0xC or hi == 0xD then
+ local n, p = count(o, nib)
+ if not n then
+ return nil, "bad length"
+ end
+ local refs = if hi == 0xD then n * 2 else n
+ if p + refs * refSize > len - 32 then
+ return nil, "collection past the end"
+ end
+ busy[idx] = true
+ if hi == 0xD then
+ local t2 = {}
+ local order = table.create(n)
+ for k = 0, n - 1 do
+ local key, ke = object(ref(p + k * refSize), depth + 1)
+ if ke then
+ return nil, ke
+ end
+ if type(key) ~= "string" then
+ return nil, "dict key is not a string"
+ end
+ local val, ve = object(ref(p + (n + k) * refSize), depth + 1)
+ if ve then
+ return nil, ve
+ end
+ if t2[key] == nil then
+ table.insert(order, key)
+ end
+ t2[key] = val
+ end
+ v = Types.object(t2, order)
+ else
+ local arr = table.create(n)
+ for k = 0, n - 1 do
+ local item, ie = object(ref(p + k * refSize), depth + 1)
+ if ie then
+ return nil, ie
+ end
+ arr[k + 1] = item
+ end
+ v = arr
+ end
+ busy[idx] = nil
+ else
+ return nil, string.format("unknown object marker 0x%02x", marker)
+ end
+ cache[idx] = v
+ return v, nil
+ end
+
+ return object(top, 0)
+end
+
+return Binary
diff --git a/src/Formats/data/plist/init.luau b/src/Formats/data/plist/init.luau
new file mode 100644
index 0000000..e8bede1
--- /dev/null
+++ b/src/Formats/data/plist/init.luau
@@ -0,0 +1,306 @@
+--!strict
+-- data/plist: Apple property lists. New code. Supports: XML plists (read and write, through codecs/Xml; the write is
+-- byte-identical to Python's plistlib for the same key order) and binary plists ("bplist00", read). Values: dict ->
+-- Types.object (key order kept), array, string, integer / real -> number, true / false, date -> Types.Date, data ->
+-- buffer, UID (binary) -> Plist.uid(n). Not supported: binary write, the old OpenStep text format, integers past
+-- 2^63. Note: Luau has one number type, so a real with an integral value is written back as .
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Types = require("@formats/Types")
+local Xml = require("@formats/codecs/Xml")
+local Json = require("@formats/codecs/Json")
+local Base64 = require("@formats/data/plist/Base64")
+local Binary = require("@formats/data/plist/Binary")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Plist = {
+ name = "plist",
+ category = "data",
+ extensions = { "plist" },
+ mime = { "application/x-plist", "application/x-bplist" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "codecs/Json" },
+ caps = { decode = true, encode = true, binary = "read", ordered = true },
+}
+
+export type DecodeOptions = {
+ bigInts: ("number" | "string")?, -- integers past 2^53: "string" keeps exact decimal text
+ maxDepth: number?, -- default 512
+}
+export type EncodeOptions = {
+ sortKeys: boolean?, -- plain tables' keys sorted (default true; Types.object keeps its order)
+}
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Plist.sniff(r: Bytes.Reader): number
+ local head = r:peek(256)
+ if string.sub(head, 1, 6) == "bplist" then
+ return 1
+ end
+ if string.find(head, " ((opts and opts.maxDepth) or 512) then
+ return nil, "nested too deeply"
+ end
+ local name = node.name
+ if name == "dict" then
+ local out = Types.object()
+ local kids = Xml.children(node)
+ local i = 1
+ while i <= #kids do
+ local k = kids[i]
+ if k.name ~= "key" then
+ return nil, "dict: expected , got <" .. k.name .. ">"
+ end
+ local v = kids[i + 1]
+ if not v then
+ return nil, "dict: without a value"
+ end
+ local val, e = xmlValue(v, opts, depth + 1)
+ if e then
+ return nil, e
+ end
+ Types.set(out, Xml.text(k), val)
+ i += 2
+ end
+ return out, nil
+ elseif name == "array" then
+ local out = {}
+ for _, ch in Xml.children(node) do
+ local val, e = xmlValue(ch, opts, depth + 1)
+ if e then
+ return nil, e
+ end
+ table.insert(out, val)
+ end
+ return out, nil
+ elseif name == "string" then
+ return Xml.text(node), nil
+ elseif name == "integer" then
+ local t = string.match(Xml.text(node), "^%s*(.-)%s*$") :: string
+ local neg, hex = string.match(t, "^([%-%+]?)0[xX](%x+)$")
+ local n: number?
+ if hex then
+ n = tonumber(hex, 16)
+ if n and neg == "-" then
+ n = -n
+ end
+ elseif string.match(t, "^[%-%+]?%d+$") then
+ n = tonumber(t)
+ if n and math.abs(n) >= 2 ^ 53 and opts and opts.bigInts == "string" then
+ return (string.gsub(t, "^%+", "")), nil
+ end
+ end
+ if not n then
+ return nil, "bad integer " .. string.sub(t, 1, 30)
+ end
+ return n, nil
+ elseif name == "real" then
+ local t = string.lower(string.match(Xml.text(node), "^%s*(.-)%s*$") :: string)
+ local n = tonumber(t)
+ if not n then
+ if t == "nan" or t == "+nan" or t == "-nan" then
+ n = 0 / 0
+ elseif t == "inf" or t == "+inf" or t == "infinity" or t == "+infinity" then
+ n = math.huge
+ elseif t == "-inf" or t == "-infinity" then
+ n = -math.huge
+ end
+ end
+ if not n then
+ return nil, "bad real " .. string.sub(t, 1, 30)
+ end
+ return n, nil
+ elseif name == "true" then
+ return true, nil
+ elseif name == "false" then
+ return false, nil
+ elseif name == "date" then
+ local d = Types.Date.parse((string.match(Xml.text(node), "^%s*(.-)%s*$")))
+ if not d then
+ return nil, "bad date"
+ end
+ return d, nil
+ elseif name == "data" then
+ local b, e = Base64.decode(Xml.text(node))
+ if not b then
+ return nil, e
+ end
+ return b, nil
+ end
+ return nil, "unknown element <" .. tostring(name) .. ">"
+end
+
+function Plist.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
+ local len = r.limit - r.base
+ if len >= 8 and buffer.readstring(r.buf, r.base, 6) == "bplist" then
+ local v, e = Binary.decode(r.buf, r.base, len, opts)
+ if e then
+ return nil, Err.new(if string.find(e, "truncated", 1, true) or string.find(e, "past the end", 1, true) then Err.TRUNCATED else Err.CORRUPT, e)
+ end
+ return v, nil
+ end
+ local doc, err = Xml.decode(buffer.readstring(r.buf, r.base, len), { whitespace = true })
+ if not doc then
+ return nil, err
+ end
+ local root = (doc :: any).root
+ if root.name == "plist" then
+ local kids = Xml.children(root)
+ if #kids ~= 1 then
+ return nil, Err.new(Err.CORRUPT, " must hold exactly one value")
+ end
+ root = kids[1]
+ end
+ local v, e = xmlValue(root, opts, 0)
+ if e then
+ return nil, Err.new(Err.CORRUPT, e)
+ end
+ return v, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+local HEADER = '\n\n\n'
+
+local function esc(s: string): (string?, string?)
+ if string.find(s, "[%z\1-\8\11\12\14-\31]") then
+ return nil, "strings cannot contain control characters"
+ end
+ s = string.gsub(string.gsub(s, "\r\n", "\n"), "\r", "\n")
+ return (string.gsub(s, "[&<>]", { ["&"] = "&", ["<"] = "<", [">"] = ">" })), nil
+end
+
+local function keyLess(a: any, b: any): boolean
+ return a < b
+end
+
+function Plist.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
+ local sort = not (opts and opts.sortKeys == false)
+ local out: { string } = { HEADER }
+ local err: string? = nil
+ local function line(level: number, s: string)
+ table.insert(out, string.rep("\t", level) .. s .. "\n")
+ end
+ local write: (v: any, level: number, depth: number) -> boolean
+ function write(v: any, level: number, depth: number): boolean
+ if depth > 512 then
+ err = "nested deeper than 512 (a cycle?)"
+ return false
+ end
+ local tv = type(v)
+ if tv == "string" then
+ local s, e = esc(v)
+ if not s then
+ err = e
+ return false
+ end
+ line(level, "" .. s .. "")
+ elseif tv == "boolean" then
+ line(level, if v then "" else "")
+ elseif tv == "number" then
+ if v == math.floor(v) and math.abs(v) < 2 ^ 63 then
+ line(level, "" .. string.format("%d", v) .. "")
+ else
+ local s = Json.number(v)
+ if not s then
+ s = if v ~= v then "nan" elseif v > 0 then "inf" else "-inf"
+ end
+ line(level, "" .. s .. "")
+ end
+ elseif tv == "buffer" then
+ line(level, "")
+ local maxLine = math.max(16, 76 - 8 * level)
+ for l in string.gmatch(Base64.encode(v, maxLine // 4 * 3), "[^\n]+") do
+ line(level, l)
+ end
+ line(level, "")
+ elseif tv == "table" and Types.Date.is(v) then
+ local d = Types.Date.fromUnix(math.floor(Types.Date.toUnix(v)))
+ line(level, string.format("%04d-%02d-%02dT%02d:%02d:%02dZ", d.year :: number, d.month :: number, d.day :: number, d.hour :: number, d.minute :: number, d.second :: number))
+ elseif tv == "table" and Binary.isUid(v) then
+ err = "UIDs can only be written to binary plists"
+ return false
+ elseif tv == "table" and v ~= Types.null then
+ local n = #v
+ local isArray = false
+ if not Types.isObject(v) then
+ local c = 0
+ for _ in next, v do
+ c += 1
+ end
+ isArray = c == n
+ end
+ if isArray then
+ if n == 0 then
+ line(level, "")
+ return true
+ end
+ line(level, "")
+ for k = 1, n do
+ if not write(v[k], level + 1, depth + 1) then
+ return false
+ end
+ end
+ line(level, "")
+ else
+ local keys: { any }
+ if Types.isObject(v) then
+ keys = Types.keys(v)
+ else
+ keys = {}
+ for k in next, v do
+ table.insert(keys, k)
+ end
+ end
+ for _, k in keys do
+ if type(k) ~= "string" then
+ err = "dict keys must be strings"
+ return false
+ end
+ end
+ if sort and not Types.isObject(v) then
+ table.sort(keys, keyLess)
+ end
+ if #keys == 0 then
+ line(level, "")
+ return true
+ end
+ line(level, "")
+ for _, k in keys do
+ local ks, e = esc(k)
+ if not ks then
+ err = e
+ return false
+ end
+ line(level + 1, "" .. ks .. "")
+ if not write(v[k], level + 1, depth + 1) then
+ return false
+ end
+ end
+ line(level, "")
+ end
+ else
+ err = "cannot write " .. (if v == Types.null then "null" else "a " .. tv) .. " in a plist"
+ return false
+ end
+ return true
+ end
+ if not write(value, 0, 0) then
+ return nil, Err.new(Err.ARG, err or "cannot encode")
+ end
+ table.insert(out, "\n")
+ return buffer.fromstring(table.concat(out)), nil
+end
+
+-- ------------------------------------------------------------------------------------------------ extras
+Plist.uid = Binary.uid -- uid(n) -> a UID value (binary plists, NSKeyedArchiver)
+Plist.isUid = Binary.isUid
+
+return Plist
diff --git a/src/Formats/data/toml/Decode.luau b/src/Formats/data/toml/Decode.luau
new file mode 100644
index 0000000..b03b941
--- /dev/null
+++ b/src/Formats/data/toml/Decode.luau
@@ -0,0 +1,643 @@
+--!strict
+-- data/toml/Decode: the TOML 1.0.0 parser behind data/toml. Tables (and inline tables) are Types.object values with
+-- their key order; arrays are arrays; datetimes are Types.Date values. Checks the 1.0 validity rules: UTF-8, control
+-- characters, table / key redefinition (explicit, implicit, dotted, inline and array-of-tables), number grammar and
+-- 64-bit range, escapes, datetimes. Never throws: failures return nil, message, offset (0-based).
+local Types = require("@formats/Types")
+
+local Decode = {}
+
+local byte, sub, find, match, gsub, char = string.byte, string.sub, string.find, string.match, string.gsub, string.char
+
+export type Options = {
+ bigInts: ("number" | "string")?, -- integers beyond +-2^53: "string" keeps their digits (default "number")
+}
+
+local function utf8char(c: number): string
+ if c < 0x80 then
+ return char(c)
+ elseif c < 0x800 then
+ return char(0xC0 + c // 64, 0x80 + c % 64)
+ elseif c < 0x10000 then
+ return char(0xE0 + c // 4096, 0x80 + (c // 64) % 64, 0x80 + c % 64)
+ end
+ return char(0xF0 + c // 262144, 0x80 + (c // 4096) % 64, 0x80 + (c // 64) % 64, 0x80 + c % 64)
+end
+
+local ESC: { [number]: string } = { [98] = "\b", [116] = "\t", [110] = "\n", [102] = "\f", [114] = "\r", [34] = '"', [92] = "\\" }
+
+-- digits with single underscores between them
+local function digitsOk(d: string, class: string): boolean
+ return d ~= "" and not find(d, "__", 1, true) and byte(d, 1) ~= 95 and byte(d, #d) ~= 95 and find(d, "^[" .. class .. "_]+$") ~= nil
+end
+
+function Decode.decode(s: string, opts: Options?): (any, any, number?)
+ local bigStrings = opts ~= nil and opts.bigInts == "string"
+ local errMsg: string = ""
+ local errAt = 0
+ local function fail(msg: string, at: number): nil
+ errMsg, errAt = msg, at - 1
+ return nil
+ end
+
+ -- input checks: BOM, UTF-8, control characters, bare CR
+ if sub(s, 1, 3) == "\239\187\191" then
+ s = sub(s, 4)
+ end
+ do
+ local bad = find(s, "[%z\1-\8\11\12\14-\31\127]")
+ if bad then
+ return nil, "control character", bad - 1
+ end
+ local cr = find(s, "\r[^\n]") or (if byte(s, #s) == 13 then #s else nil)
+ if cr then
+ return nil, "carriage return without a line feed", cr - 1
+ end
+ if find(s, "[\128-\255]") then
+ if not utf8.len(s) then
+ return nil, "invalid UTF-8", 0
+ end
+ local sur = find(s, "\237[\160-\191]")
+ if sur then
+ return nil, "invalid UTF-8 (surrogate)", sur - 1
+ end
+ end
+ if find(s, "\r", 1, true) then
+ s = gsub(s, "\r\n", "\n")
+ end
+ end
+ local n = #s
+
+ -- table bookkeeping: kind = "explicit" | "implicit" | "dotted" | "inline"; section = where dotted tables were made
+ local kinds: { [any]: string } = {}
+ local sections: { [any]: number } = {}
+ local aot: { [any]: boolean } = {} -- arrays of tables ([[x]]); other arrays are static
+ local arrays: { [any]: boolean } = {}
+ local section = 0
+ local building: { any }? = nil -- tables created inside the inline table being parsed (frozen when it closes)
+
+ local function newTable(kind: string): any
+ local t = Types.object({}, {})
+ kinds[t] = kind
+ if building then
+ table.insert(building, t)
+ end
+ return t
+ end
+
+ local function ws(i: number): number
+ return match(s, "^[ \t]*()", i) :: any
+ end
+ -- whitespace, newlines and comments (inside arrays)
+ local function wsnl(i: number): number
+ while true do
+ i = match(s, "^[ \t\n]*()", i) :: any
+ if byte(s, i) == 35 then
+ i = find(s, "\n", i, true) or (n + 1)
+ else
+ return i
+ end
+ end
+ end
+
+ local function escape(p: number, parts: { string }): number?
+ local e = byte(s, p + 1)
+ local simple = if e then ESC[e] else nil
+ if simple then
+ table.insert(parts, simple)
+ return p + 2
+ elseif e == 117 or e == 85 then
+ local len = if e == 117 then 4 else 8
+ local h = match(s, "^" .. string.rep("%x", len), p + 2)
+ if not h then
+ return fail("bad unicode escape", p)
+ end
+ local cp = tonumber(h, 16) :: number
+ if cp > 0x10FFFF or (cp >= 0xD800 and cp <= 0xDFFF) then
+ return fail("unicode escape is not a scalar value", p)
+ end
+ table.insert(parts, utf8char(cp))
+ return p + 2 + len
+ end
+ return fail("bad escape", p)
+ end
+
+ -- strings: value, next | nil
+ local function basic(i: number): (string?, number)
+ local parts = {}
+ local j = i + 1
+ while true do
+ local p = find(s, '["\\\n]', j)
+ if not p or byte(s, p) == 10 then
+ return fail("unterminated string", p or n + 1), 0
+ end
+ table.insert(parts, sub(s, j, p - 1))
+ if byte(s, p) == 34 then
+ return table.concat(parts), p + 1
+ end
+ local nj = escape(p, parts)
+ if not nj then
+ return nil, 0
+ end
+ j = nj
+ end
+ end
+ local function multiBasic(i: number): (string?, number)
+ local j = i + 3
+ if byte(s, j) == 10 then
+ j += 1
+ end
+ local parts = {}
+ while true do
+ local p = find(s, '["\\]', j)
+ if not p then
+ return fail("unterminated multi-line string", i), 0
+ end
+ table.insert(parts, sub(s, j, p - 1))
+ if byte(s, p) == 34 then
+ if sub(s, p, p + 2) == '"""' then
+ local q = p + 3
+ local extra = 0
+ while byte(s, q) == 34 and extra < 2 do
+ extra += 1
+ q += 1
+ end
+ if byte(s, q) == 34 then
+ return fail("too many quotes", q), 0
+ end
+ table.insert(parts, string.rep('"', extra))
+ return table.concat(parts), q
+ end
+ table.insert(parts, '"')
+ j = p + 1
+ else
+ local k = match(s, "^\\[ \t]*\n[ \t\n]*()", p)
+ if k then
+ j = k :: any
+ else
+ local nj = escape(p, parts)
+ if not nj then
+ return nil, 0
+ end
+ j = nj
+ end
+ end
+ end
+ end
+ local function literal(i: number): (string?, number)
+ local e = find(s, "['\n]", i + 1)
+ if not e or byte(s, e) == 10 then
+ return fail("unterminated literal string", e or n + 1), 0
+ end
+ return sub(s, i + 1, e - 1), e + 1
+ end
+ local function multiLiteral(i: number): (string?, number)
+ local j = i + 3
+ if byte(s, j) == 10 then
+ j += 1
+ end
+ local e = find(s, "'''", j, true)
+ if not e then
+ return fail("unterminated multi-line literal string", i), 0
+ end
+ local q = e + 3
+ local extra = 0
+ while byte(s, q) == 39 and extra < 2 do
+ extra += 1
+ q += 1
+ end
+ if byte(s, q) == 39 then
+ return fail("too many quotes", q), 0
+ end
+ return sub(s, j, e - 1) .. string.rep("'", extra), q
+ end
+
+ -- a (dotted) key: { parts }, next | nil
+ local function key(i: number): ({ string }?, number)
+ local keys = {}
+ while true do
+ i = ws(i)
+ local c = byte(s, i)
+ local k: string?
+ if c == 34 then
+ if sub(s, i, i + 2) == '"""' then
+ return fail("multi-line string as a key", i), 0
+ end
+ k, i = basic(i)
+ elseif c == 39 then
+ if sub(s, i, i + 2) == "'''" then
+ return fail("multi-line string as a key", i), 0
+ end
+ k, i = literal(i)
+ else
+ k = match(s, "^[%w_%-]+", i)
+ if k then
+ i += #k
+ else
+ return fail("expected a key", i), 0
+ end
+ end
+ if k == nil then
+ return nil, 0
+ end
+ table.insert(keys, k)
+ i = ws(i)
+ if byte(s, i) == 46 then
+ i += 1
+ else
+ return keys, i
+ end
+ end
+ end
+
+ -- numbers and datetimes
+ local function number(i: number): (any, number)
+ local tok = match(s, "^[%+%-]?[%w_%.]+", i)
+ if not tok then
+ return fail("expected a value", i), 0
+ end
+ local last = byte(tok, #tok)
+ if (last == 101 or last == 69) and not find(tok, "^[%+%-]?0[xob]") then
+ local ext = match(s, "^[%+%-][%w_]*", i + #tok)
+ if ext then
+ tok ..= ext
+ end
+ end
+ local nexti = i + #tok
+ local sign, body = match(tok, "^([%+%-]?)(.*)$")
+ if body == "inf" or body == "nan" then
+ return (if body == "nan" then 0 / 0 elseif sign == "-" then -math.huge else math.huge), nexti
+ end
+ local prefix = sub(body :: string, 1, 2)
+ if prefix == "0x" or prefix == "0o" or prefix == "0b" then
+ if sign ~= "" then
+ return fail("sign on a non-decimal integer", i), 0
+ end
+ local d = sub(body :: string, 3)
+ local class = if prefix == "0x" then "%x" elseif prefix == "0o" then "0-7" else "01"
+ if not digitsOk(d, class) then
+ return fail("bad integer", i), 0
+ end
+ d = gsub(gsub(d, "_", ""), "^0+", "")
+ local over = if prefix == "0x" then #d > 16 or (#d == 16 and (tonumber(sub(d, 1, 1), 16) :: number) >= 8)
+ elseif prefix == "0o" then #d > 21
+ else #d > 63
+ if over then
+ return fail("integer out of 64-bit range", i), 0
+ end
+ if d == "" then
+ return 0, nexti
+ end
+ local v = tonumber(d, if prefix == "0x" then 16 elseif prefix == "0o" then 8 else 2) :: number
+ if bigStrings and v >= 9007199254740992 then
+ return prefix .. d, nexti
+ end
+ return v, nexti
+ end
+ local ip, rest = match(body :: string, "^([%d_]+)(.*)$")
+ if not ip or not digitsOk(ip, "%d") then
+ return fail("bad number", i), 0
+ end
+ local digits = gsub(ip, "_", "")
+ if #digits > 1 and byte(digits, 1) == 48 then
+ return fail("leading zero", i), 0
+ end
+ if rest == "" then
+ local limit = if sign == "-" then "9223372036854775808" else "9223372036854775807"
+ if #digits > 19 or (#digits == 19 and digits > limit) then
+ return fail("integer out of 64-bit range", i), 0
+ end
+ local v = tonumber(digits) :: number
+ if bigStrings and v >= 9007199254740992 then
+ return (if sign == "-" then "-" else "") .. digits, nexti
+ end
+ return if sign == "-" then -v else v, nexti
+ end
+ local text = sign .. digits
+ local frac, r2 = match(rest :: string, "^%.([%d_]*)(.*)$")
+ if frac then
+ if not digitsOk(frac, "%d") then
+ return fail("bad fraction", i), 0
+ end
+ text ..= "." .. gsub(frac, "_", "")
+ rest = r2
+ end
+ if rest ~= "" then
+ local es, ed = match(rest :: string, "^[eE]([%+%-]?)([%d_]*)$")
+ if not es or not digitsOk(ed, "%d") then
+ return fail("bad float", i), 0
+ end
+ text ..= "e" .. es .. gsub(ed, "_", "")
+ end
+ local v = tonumber(text)
+ if v == nil then
+ return fail("bad float", i), 0
+ end
+ return v, nexti
+ end
+
+ local function datetime(i: number): (any, number)
+ local j = i
+ if match(s, "^%d%d%d%d%-%d%d%-%d%d", i) then
+ j = i + 10
+ local c = byte(s, j)
+ if (c == 84 or c == 116 or c == 32) and match(s, "^%d%d:", j + 1) then
+ j += 1
+ elseif c == 84 or c == 116 then
+ return fail("bad datetime", i), 0
+ else
+ local d = Types.Date.parse(sub(s, i, j - 1))
+ if not d then
+ return fail("bad date", i), 0
+ end
+ return d, j
+ end
+ end
+ local t = match(s, "^%d%d:%d%d:%d%d", j)
+ if not t then
+ return fail("bad time (seconds are required)", j), 0
+ end
+ j += 8
+ local frac = match(s, "^%.%d+", j)
+ if frac then
+ j += #frac
+ elseif byte(s, j) == 46 then
+ return fail("bad fraction", j), 0
+ end
+ if j - i > 19 or match(s, "^%d%d%d%d%-", i) then
+ local off = match(s, "^[Zz]", j) or match(s, "^[%+%-]%d%d:%d%d", j)
+ if off then
+ j += #off
+ end
+ end
+ local d = Types.Date.parse(sub(s, i, j - 1))
+ if not d then
+ return fail("bad datetime", i), 0
+ end
+ return d, j
+ end
+
+ local value: (i: number) -> (any, number)
+ local assign: (tbl: any, keys: { string }, v: any, sid: number, at: number) -> boolean
+
+ local function array(i: number): (any, number)
+ local arr = {}
+ arrays[arr] = true
+ i += 1
+ while true do
+ i = wsnl(i)
+ local c = byte(s, i)
+ if c == 93 then
+ return arr, i + 1
+ elseif c == nil then
+ return fail("unterminated array", i), 0
+ end
+ local v, ni = value(i)
+ if v == nil then
+ return nil, 0
+ end
+ table.insert(arr, v)
+ i = wsnl(ni)
+ c = byte(s, i)
+ if c == 44 then
+ i += 1
+ elseif c == 93 then
+ return arr, i + 1
+ else
+ return fail(if c == nil then "unterminated array" else "expected ',' or ']'", i), 0
+ end
+ end
+ end
+
+ local function inline(i: number): (any, number)
+ local outer = building
+ local mine = {}
+ building = mine
+ local t = newTable("inline")
+ section += 1
+ local sid = section
+ i = ws(i + 1)
+ if byte(s, i) == 125 then
+ building = outer
+ return t, i + 1
+ end
+ while true do
+ local keys, ni = key(i)
+ if not keys then
+ return nil, 0
+ end
+ i = ws(ni)
+ if byte(s, i) ~= 61 then
+ return fail("expected '='", i), 0
+ end
+ local v, vi = value(ws(i + 1))
+ if v == nil then
+ return nil, 0
+ end
+ if not assign(t, keys, v, sid, i) then
+ return nil, 0
+ end
+ i = ws(vi)
+ local c = byte(s, i)
+ if c == 44 then
+ i = ws(i + 1)
+ if byte(s, i) == 125 then
+ return fail("trailing comma in an inline table", i), 0
+ end
+ elseif c == 125 then
+ break
+ else
+ return fail(if c == 10 then "newline in an inline table" else "expected ',' or '}'", i), 0
+ end
+ end
+ for _, x in mine do
+ kinds[x] = "inline"
+ end
+ building = outer
+ if outer then
+ for _, x in mine do
+ table.insert(outer, x)
+ end
+ end
+ return t, i + 1
+ end
+
+ function value(i: number): (any, number)
+ local c = byte(s, i)
+ if c == 34 then
+ if sub(s, i, i + 2) == '"""' then
+ return multiBasic(i)
+ end
+ return basic(i)
+ elseif c == 39 then
+ if sub(s, i, i + 2) == "'''" then
+ return multiLiteral(i)
+ end
+ return literal(i)
+ elseif c == 116 then
+ if match(s, "^true", i) and not match(s, "^[%w_%-]", i + 4) then
+ return true, i + 4
+ end
+ elseif c == 102 then
+ if match(s, "^false", i) and not match(s, "^[%w_%-]", i + 5) then
+ return false, i + 5
+ end
+ elseif c == 91 then
+ return array(i)
+ elseif c == 123 then
+ return inline(i)
+ elseif c and ((c >= 48 and c <= 57) or c == 43 or c == 45 or c == 105 or c == 110) then
+ if match(s, "^%d%d%d%d%-", i) or match(s, "^%d%d:", i) then
+ return datetime(i)
+ end
+ return number(i)
+ end
+ return fail(if c == nil or c == 10 then "expected a value" else "bad value", i), 0
+ end
+
+ function assign(tbl: any, keys: { string }, v: any, sid: number, at: number): boolean
+ local t = tbl
+ for j = 1, #keys - 1 do
+ local k = keys[j]
+ local x = t[k]
+ if x == nil then
+ local nt = newTable("dotted")
+ sections[nt] = sid
+ Types.set(t, k, nt)
+ t = nt
+ elseif kinds[x] == "implicit" or (kinds[x] == "dotted" and sections[x] == sid) then
+ t = x
+ else
+ fail("cannot add to " .. k .. " with a dotted key (already defined)", at)
+ return false
+ end
+ end
+ local k = keys[#keys]
+ if t[k] ~= nil then
+ fail("duplicate key " .. k, at)
+ return false
+ end
+ Types.set(t, k, v)
+ return true
+ end
+
+ -- after a key / value or a header: spaces, an optional comment, then a newline or the end
+ local function eol(i: number): number?
+ i = ws(i)
+ local c = byte(s, i)
+ if c == 35 then
+ return find(s, "\n", i, true) or (n + 1)
+ elseif c == 10 or c == nil then
+ return i
+ end
+ return fail("expected the end of the line", i)
+ end
+
+ local root = newTable("explicit")
+ local cur = root
+ local i = 1
+ while true do
+ i = ws(i)
+ local c = byte(s, i)
+ if c == nil then
+ break
+ elseif c == 10 then
+ i += 1
+ elseif c == 35 then
+ i = find(s, "\n", i, true) or (n + 1)
+ elseif c == 91 then
+ local at = i
+ local isAot = byte(s, i + 1) == 91
+ local keys, ni = key(i + (if isAot then 2 else 1))
+ if not keys then
+ return nil, errMsg, errAt
+ end
+ ni = ws(ni)
+ if isAot then
+ if sub(s, ni, ni + 1) ~= "]]" then
+ return nil, "expected ']]'", ni - 1
+ end
+ ni += 2
+ else
+ if byte(s, ni) ~= 93 then
+ return nil, "expected ']'", ni - 1
+ end
+ ni += 1
+ end
+ -- walk to the parent
+ local t = root
+ for j = 1, #keys - 1 do
+ local k = keys[j]
+ local x = t[k]
+ if x == nil then
+ local nt = newTable("implicit")
+ Types.set(t, k, nt)
+ t = nt
+ elseif kinds[x] and kinds[x] ~= "inline" then
+ t = x
+ elseif aot[x] then
+ t = x[#x]
+ else
+ return nil, "cannot define a table under " .. k .. " (already defined)", at - 1
+ end
+ end
+ local k = keys[#keys]
+ local x = t[k]
+ if isAot then
+ local arr = x
+ if arr == nil then
+ arr = {}
+ aot[arr] = true
+ Types.set(t, k, arr)
+ elseif not aot[arr] then
+ return nil, "cannot define an array of tables " .. k .. " (already defined)", at - 1
+ end
+ local nt = newTable("explicit")
+ table.insert(arr, nt)
+ cur = nt
+ else
+ if x == nil then
+ local nt = newTable("explicit")
+ Types.set(t, k, nt)
+ cur = nt
+ elseif kinds[x] == "implicit" then
+ kinds[x] = "explicit"
+ cur = x
+ else
+ return nil, "table " .. k .. " defined twice", at - 1
+ end
+ end
+ section += 1
+ local e = eol(ni)
+ if not e then
+ return nil, errMsg, errAt
+ end
+ i = e
+ else
+ local at = i
+ local keys, ni = key(i)
+ if not keys then
+ return nil, errMsg, errAt
+ end
+ ni = ws(ni)
+ if byte(s, ni) ~= 61 then
+ return nil, "expected '='", ni - 1
+ end
+ local v, vi = value(ws(ni + 1))
+ if v == nil then
+ return nil, errMsg, errAt
+ end
+ if not assign(cur, keys, v, section, at) then
+ return nil, errMsg, errAt
+ end
+ local e = eol(vi)
+ if not e then
+ return nil, errMsg, errAt
+ end
+ i = e
+ end
+ end
+ return root, nil, nil
+end
+
+return Decode
diff --git a/src/Formats/data/toml/Encode.luau b/src/Formats/data/toml/Encode.luau
new file mode 100644
index 0000000..664e467
--- /dev/null
+++ b/src/Formats/data/toml/Encode.luau
@@ -0,0 +1,214 @@
+--!strict
+-- data/toml/Encode: the TOML 1.0.0 writer behind data/toml. A table's plain values come first, then its sub-tables
+-- as [a.b] sections and arrays of tables as [[a.b]]; keys in Types.object order (plain tables: sorted); strings as
+-- basic strings with escapes; numbers as integers when integral (|x| < 2^63) else round-trip float text; Types.Date
+-- values as datetimes. Never throws: bad values (null, buffers, functions, cycles, non-string keys) return nil,
+-- message.
+local Types = require("@formats/Types")
+local Json = require("@formats/codecs/Json")
+
+local Encode = {}
+
+local format, gsub, find = string.format, string.gsub, string.find
+
+export type Options = {
+ inline: boolean?, -- write every sub-table as an inline table (default false: [sections])
+ indent: (number | string)?, -- indent keys of nested sections (default none)
+}
+
+local ESC: { [string]: string } = { ['"'] = '\\"', ["\\"] = "\\\\", ["\b"] = "\\b", ["\t"] = "\\t", ["\n"] = "\\n", ["\f"] = "\\f", ["\r"] = "\\r", ["\127"] = "\\u007F" }
+for c = 0, 31 do
+ local ch = string.char(c)
+ if not ESC[ch] then
+ ESC[ch] = format("\\u%04X", c)
+ end
+end
+
+local function quote(str: string): string
+ return '"' .. gsub(str, '[%z\1-\31"\\\127]', ESC) .. '"'
+end
+Encode.quote = quote
+
+local function keyText(k: string): string
+ if find(k, "^[%w_%-]+$") then
+ return k
+ end
+ return quote(k)
+end
+
+-- isMap(t): a table written as a TOML table (Types.object, or keys other than 1..n); empty plain tables are arrays
+local function isMap(t: { [any]: any }): boolean
+ if Types.isObject(t) then
+ return true
+ end
+ local n = #t
+ if n == 0 then
+ return next(t) ~= nil
+ end
+ local count = 0
+ for _ in next, t do
+ count += 1
+ end
+ return count ~= n
+end
+
+local function isDate(v: any): boolean
+ return Types.Date.is(v)
+end
+
+-- an array of tables: non-empty, every element a map
+local function isAot(v: any): boolean
+ if type(v) ~= "table" or isDate(v) or isMap(v) or #v == 0 then
+ return false
+ end
+ for _, x in v do
+ if type(x) ~= "table" or isDate(x) or not isMap(x) then
+ return false
+ end
+ end
+ return true
+end
+
+local function keysOf(t: { [any]: any }): ({ string }?, string?)
+ local keys = Types.keys(t)
+ for _, k in keys do
+ if type(k) ~= "string" then
+ return nil, "table key of type " .. type(k)
+ end
+ end
+ return keys :: any, nil
+end
+
+type State = { seen: { [any]: boolean }, err: string? }
+
+local inlineValue: (st: State, v: any) -> string?
+
+local function scalar(st: State, v: any): string?
+ local tv = type(v)
+ if v == Types.null then
+ st.err = "TOML has no null"
+ return nil
+ elseif tv == "string" then
+ return quote(v)
+ elseif tv == "boolean" then
+ return if v then "true" else "false"
+ elseif tv == "number" then
+ if v ~= v then
+ return "nan"
+ elseif v == math.huge then
+ return "inf"
+ elseif v == -math.huge then
+ return "-inf"
+ elseif v == math.floor(v) and math.abs(v) < 2 ^ 63 then
+ return format("%d", v)
+ end
+ local t = Json.number(v) :: string
+ if not find(t, "[%.eEn]") then
+ t ..= ".0"
+ end
+ return t
+ elseif tv == "table" and isDate(v) then
+ return tostring(v)
+ elseif tv == "table" then
+ return inlineValue(st, v)
+ end
+ st.err = "cannot encode a " .. tv
+ return nil
+end
+
+function inlineValue(st: State, v: any): string?
+ if st.seen[v] then
+ st.err = "a table contains itself"
+ return nil
+ end
+ st.seen[v] = true
+ local parts = {}
+ if isMap(v) then
+ local keys, kerr = keysOf(v)
+ if not keys then
+ st.err = kerr
+ return nil
+ end
+ for _, k in keys do
+ local s = scalar(st, v[k])
+ if not s then
+ return nil
+ end
+ table.insert(parts, keyText(k) .. " = " .. s)
+ end
+ st.seen[v] = nil
+ return if #parts == 0 then "{}" else "{ " .. table.concat(parts, ", ") .. " }"
+ end
+ for i = 1, #v do
+ local s = scalar(st, v[i])
+ if not s then
+ return nil
+ end
+ parts[i] = s
+ end
+ st.seen[v] = nil
+ return "[" .. table.concat(parts, ", ") .. "]"
+end
+
+local function section(st: State, t: any, path: string, out: { string }, inlineAll: boolean, ind: string, depth: number): boolean
+ if st.seen[t] then
+ st.err = "a table contains itself"
+ return false
+ end
+ st.seen[t] = true
+ local keys, kerr = keysOf(t)
+ if not keys then
+ st.err = kerr
+ return false
+ end
+ local pad = string.rep(ind, depth)
+ local subs = {}
+ for _, k in keys do
+ local v = t[k]
+ if not inlineAll and type(v) == "table" and not isDate(v) and (isMap(v) or isAot(v)) then
+ table.insert(subs, k)
+ else
+ local s = scalar(st, v)
+ if not s then
+ return false
+ end
+ table.insert(out, pad .. keyText(k) .. " = " .. s .. "\n")
+ end
+ end
+ for _, k in subs do
+ local v = t[k]
+ local p = (if path == "" then "" else path .. ".") .. keyText(k)
+ if isMap(v) then
+ table.insert(out, (if #out > 0 then "\n" else "") .. pad .. "[" .. p .. "]\n")
+ if not section(st, v, p, out, inlineAll, ind, depth + 1) then
+ return false
+ end
+ else
+ for _, el in v do
+ table.insert(out, (if #out > 0 then "\n" else "") .. pad .. "[[" .. p .. "]]\n")
+ if not section(st, el, p, out, inlineAll, ind, depth + 1) then
+ return false
+ end
+ end
+ end
+ end
+ st.seen[t] = nil
+ return true
+end
+
+-- encode(t, opts) -> text | nil, message
+function Encode.encode(t: any, opts: Options?): (string?, string?)
+ if type(t) ~= "table" or isDate(t) or (not isMap(t) and next(t) ~= nil) then
+ return nil, "the top level must be a table with string keys"
+ end
+ local o: Options = opts or {}
+ local ind = if type(o.indent) == "number" then string.rep(" ", o.indent) elseif type(o.indent) == "string" then o.indent else ""
+ local st: State = { seen = {}, err = nil }
+ local out = {}
+ if not section(st, t, "", out, o.inline == true, ind, 0) then
+ return nil, st.err
+ end
+ return table.concat(out), nil
+end
+
+return Encode
diff --git a/src/Formats/data/toml/init.luau b/src/Formats/data/toml/init.luau
new file mode 100644
index 0000000..093bca1
--- /dev/null
+++ b/src/Formats/data/toml/init.luau
@@ -0,0 +1,70 @@
+--!strict
+-- data/toml: TOML 1.0.0 (https://toml.io/en/v1.0.0). New code. Supports: decode of the whole 1.0 grammar (tables,
+-- inline tables, arrays of tables, dotted keys, every string kind, integers in every base with the 64-bit range
+-- check, floats incl. inf / nan, booleans, offset / local datetimes, local dates and times) with the validity rules
+-- (redefinitions, UTF-8, control characters, number grammar), tested against toml-test; encode from plain tables /
+-- Types.object (key order kept) / Types.Date. Tables decode to Types.object values (key order kept), datetimes to
+-- Types.Date. Not supported: TOML 1.1 additions; the integer / float distinction is lost (Luau numbers: integral
+-- values are written as integers).
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Decode = require("@formats/data/toml/Decode")
+local Encode = require("@formats/data/toml/Encode")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Toml = {
+ name = "toml",
+ category = "data",
+ extensions = { "toml" },
+ mime = { "application/toml" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/Json" },
+ caps = { decode = true, encode = true, ordered = true, dates = true },
+}
+
+export type DecodeOptions = Decode.Options
+export type EncodeOptions = Encode.Options
+
+-- ------------------------------------------------------------------------------------------------ sniff
+-- text that starts (after comments / blank lines) with a [table] header or a key = value line; INI looks the same,
+-- so this stays low and the extension decides
+function Toml.sniff(r: Bytes.Reader): number
+ local head = r:peek(512)
+ if string.find(head, "%z") then
+ return 0
+ end
+ for line in string.gmatch(head, "[^\n]+") do
+ local l = string.match(line, "^[ \t]*(.-)[ \t\r]*$") :: string
+ if l ~= "" and string.sub(l, 1, 1) ~= "#" then
+ if string.match(l, "^%[%[?[%w_%-%.\"' ]+%]%]?$") or string.match(l, "^[%w_%-%.\"']+[ \t]*=[ \t]*[\"'%[{%dtf%+%-in]") then
+ return 0.2
+ end
+ return 0
+ end
+ end
+ return 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+function Toml.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
+ local s = buffer.readstring(r.buf, r.base, r.limit - r.base)
+ local v, msg, at = Decode.decode(s, opts)
+ if v == nil then
+ local m = tostring(msg)
+ local code = if string.find(m, "unterminated", 1, true) then Err.TRUNCATED else Err.CORRUPT
+ return nil, Err.new(code, m, at)
+ end
+ return v, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+function Toml.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
+ local s, msg = Encode.encode(value, opts)
+ if not s then
+ return nil, Err.new(Err.ARG, msg or "cannot encode")
+ end
+ return buffer.fromstring(s), nil
+end
+
+return Toml
diff --git a/src/Formats/data/xml/init.luau b/src/Formats/data/xml/init.luau
new file mode 100644
index 0000000..c992418
--- /dev/null
+++ b/src/Formats/data/xml/init.luau
@@ -0,0 +1,57 @@
+--!strict
+-- data/xml: XML 1.0 files, a thin wrapper over codecs/Xml (which see for the node shape and options). Supports:
+-- decode to a "#document" XmlNode tree (doc.root = the root element), encode a document or an element. Not
+-- supported: external entities / DTDs, validation.
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Types = require("@formats/Types")
+local Xml = require("@formats/codecs/Xml")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local XmlFormat = {
+ name = "xml",
+ category = "data",
+ extensions = { "xml", "xsd", "xsl", "xslt", "rss", "atom", "xhtml" },
+ mime = { "application/xml", "text/xml" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml" },
+ caps = { decode = true, encode = true, namespaces = true, streaming = true },
+}
+
+export type DecodeOptions = Xml.DecodeOptions
+export type EncodeOptions = Xml.EncodeOptions
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function XmlFormat.sniff(r: Bytes.Reader): number
+ local head = r:peek(64)
+ if string.sub(head, 1, 3) == "\239\187\191" then
+ head = string.sub(head, 4)
+ end
+ if string.match(head, "^<%?xml[ \t\r\n]") or string.sub(head, 1, 4) == "\255\254<\0" or string.sub(head, 1, 4) == "\254\255\0<" then
+ return 0.5
+ end
+ if string.match(head, "^[ \t\r\n]*<[%a!]") then
+ return 0.3
+ end
+ return 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+function XmlFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.XmlNode?, Err.Err?)
+ return Xml.decode(buffer.readstring(r.buf, r.base, r.limit - r.base), opts)
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+function XmlFormat.encode(node: Types.XmlNode, opts: EncodeOptions?): (buffer?, Err.Err?)
+ if type(node) ~= "table" or type(node.name) ~= "string" then
+ return nil, Err.new(Err.ARG, "expected an XmlNode")
+ end
+ local s, err = Xml.encode(node, opts)
+ if not s then
+ return nil, err
+ end
+ return buffer.fromstring(s), nil
+end
+
+return XmlFormat
diff --git a/src/Formats/data/yaml/Emit.luau b/src/Formats/data/yaml/Emit.luau
new file mode 100644
index 0000000..6fbacac
--- /dev/null
+++ b/src/Formats/data/yaml/Emit.luau
@@ -0,0 +1,339 @@
+--!strict
+-- data/yaml/Emit: the YAML writer behind data/yaml. Block style; empty collections as [] / {}; strings plain when
+-- they read back as the same string (core schema, and not a YAML 1.1 boolean like "yes"), literal block scalars
+-- for multi-line text, double-quoted otherwise; numbers with the shortest round-trip text, .inf / .nan; buffers as
+-- !!binary; dates as their RFC 3339 text; tables referenced twice get an anchor and aliases. Never throws: bad
+-- values (cycles, functions, collection keys) return nil, message.
+local Types = require("@formats/Types")
+local Parse = require("@formats/data/yaml/Parse")
+
+local Emit = {}
+
+export type Options = {
+ indent: number?, -- spaces per level (default 2)
+ all: boolean?, -- the value is an array of documents, written with "---" separators
+ explicitStart: boolean?, -- start the (first) document with "---" (default false)
+ sortKeys: boolean?, -- plain tables' keys sorted (default true; Types.object keys keep their order)
+ null: any?, -- the value written as null besides Types.null
+}
+
+local format, byte, find, gsub = string.format, string.byte, string.find, string.gsub
+
+local YAML11 = {
+ y = true, Y = true, yes = true, Yes = true, YES = true, n = true, N = true, no = true, No = true, NO = true,
+ on = true, On = true, ON = true, off = true, Off = true, OFF = true,
+}
+
+local function number(x: number): string
+ if x ~= x then
+ return ".nan"
+ elseif x == math.huge then
+ return ".inf"
+ elseif x == -math.huge then
+ return "-.inf"
+ elseif x == math.floor(x) and math.abs(x) < 2 ^ 53 then
+ if x == 0 and 1 / x < 0 then
+ return "-0.0"
+ end
+ return format("%d", x)
+ end
+ for _, f in { "%.15g", "%.16g", "%.17g" } do
+ local t = format(f, x)
+ if tonumber(t) == x then
+ if not find(t, "[%.eEn]") then
+ t ..= ".0"
+ end
+ return t
+ end
+ end
+ return format("%.17g", x)
+end
+
+local DQ: { [string]: string } = {
+ ["\\"] = "\\\\",
+ ['"'] = '\\"',
+ ["\n"] = "\\n",
+ ["\t"] = "\\t",
+ ["\r"] = "\\r",
+ ["\0"] = "\\0",
+ ["\27"] = "\\e",
+}
+local function dquote(s: string): string
+ s = gsub(s, '[%z\1-\31\127\\"]', function(c: string): string
+ return DQ[c] or format("\\x%02x", byte(c))
+ end)
+ -- the Unicode line / paragraph separators and NEL would be folded as line breaks: escape them
+ s = gsub(s, "\226\128\168", "\\L")
+ s = gsub(s, "\226\128\169", "\\P")
+ s = gsub(s, "\194\133", "\\N")
+ return '"' .. s .. '"'
+end
+
+local function plainOk(s: string): boolean
+ if s == "" or YAML11[s] then
+ return false
+ end
+ if Parse.resolve(s, Types.null) ~= s then
+ return false
+ end
+ if find(s, "^[%s]") or find(s, "[%s]$") then
+ return false
+ end
+ if find(s, "^[%-%?:,%[%]{}#&%*!|>'\"%%@`]") or find(s, "^%.%.%.") then
+ return false
+ end
+ if find(s, ": ", 1, true) or find(s, " #", 1, true) or find(s, ":$") or find(s, "[%z\1-\31\127]") then
+ return false
+ end
+ if find(s, "\226\128\168") or find(s, "\226\128\169") or find(s, "\194\133") or find(s, "\239\187\191") then
+ return false
+ end
+ -- not invalid UTF-8 (the reader treats the text as bytes, but other tools will not)
+ if find(s, "[\128-\255]") and not utf8.len(s) then
+ return false
+ end
+ return true
+end
+
+-- a string as a scalar on a line at indentation ind (for block scalars)
+local function str(s: string, ind: string, key: boolean): string
+ if plainOk(s) then
+ return s
+ end
+ if not key and find(s, "\n", 1, true) and not find(s, "[%z\1-\9\11-\31\127]") and not find(s, "[ ]\n") and not find(s, " $")
+ and not find(s, "^[ \n]") and not find(s, "\226\128[\168\169]") and not find(s, "\194\133") and (not find(s, "[\128-\255]") or utf8.len(s))
+ then
+ local trailing = #(string.match(s, "\n*$") :: string)
+ local body = string.sub(s, 1, #s - trailing)
+ local chomp = if trailing == 0 then "-" elseif trailing == 1 then "" else "+"
+ local lines = string.split(body, "\n")
+ local out = { "|" .. chomp }
+ for _, l in lines do
+ table.insert(out, if l == "" then "" else ind .. l)
+ end
+ for _ = 2, trailing do
+ table.insert(out, "")
+ end
+ return table.concat(out, "\n")
+ end
+ return dquote(s)
+end
+
+local function b64(b: buffer): string
+ local A = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
+ local out = {}
+ local n = buffer.len(b)
+ for i = 0, n - 1, 3 do
+ local a1 = buffer.readu8(b, i)
+ local a2 = if i + 1 < n then buffer.readu8(b, i + 1) else 0
+ local a3 = if i + 2 < n then buffer.readu8(b, i + 2) else 0
+ local v = a1 * 65536 + a2 * 256 + a3
+ local c1, c2, c3, c4 = v // 262144, (v // 4096) % 64, (v // 64) % 64, v % 64
+ table.insert(out, string.sub(A, c1 + 1, c1 + 1) .. string.sub(A, c2 + 1, c2 + 1)
+ .. (if i + 1 < n then string.sub(A, c3 + 1, c3 + 1) else "=") .. (if i + 2 < n then string.sub(A, c4 + 1, c4 + 1) else "="))
+ end
+ return table.concat(out)
+end
+
+local function isArray(t: { [any]: any }): boolean
+ if Types.isObject(t) then
+ return false
+ end
+ local n = #t
+ if n == 0 then
+ return next(t) == nil
+ end
+ if next(t, n) ~= nil then
+ return false
+ end
+ local c = 0
+ for _ in next, t do
+ c += 1
+ end
+ return c == n
+end
+
+local function keyLess(a: any, b: any): boolean
+ local ta, tb = type(a), type(b)
+ if ta ~= tb then
+ return ta < tb
+ end
+ if ta == "number" or ta == "string" then
+ return a < b
+ end
+ return tostring(a) < tostring(b)
+end
+
+type St = { out: { string }, step: number, sort: boolean, null: any, refs: { [any]: number }, anchors: { [any]: string }, nextId: number, err: string? }
+
+-- count references to tables (anchors for those seen twice); false on a cycle
+local function count(st: St, v: any, onStack: { [any]: boolean }): boolean
+ if type(v) ~= "table" or v == Types.null or v == st.null or Types.Date.is(v) then
+ return true
+ end
+ if onStack[v] then
+ st.err = "a cycle (YAML aliases cannot point at their own ancestors here)"
+ return false
+ end
+ local r = st.refs[v]
+ st.refs[v] = (r or 0) + 1
+ if r then
+ return true
+ end
+ onStack[v] = true
+ for k, x in next, v do
+ if not count(st, k, onStack) or not count(st, x, onStack) then
+ return false
+ end
+ end
+ onStack[v] = nil
+ return true
+end
+
+-- scalar text for a non-collection value, or nil
+local function scalar(st: St, v: any, ind: string, key: boolean): string?
+ local tv = type(v)
+ if v == nil or v == Types.null or (st.null ~= nil and v == st.null) then
+ return "null"
+ elseif tv == "boolean" then
+ return if v then "true" else "false"
+ elseif tv == "number" then
+ return number(v)
+ elseif tv == "string" then
+ return str(v, ind, key)
+ elseif tv == "buffer" then
+ return "!!binary " .. b64(v)
+ elseif tv == "table" and Types.Date.is(v) then
+ return tostring(v)
+ end
+ return nil
+end
+
+local write: (st: St, v: any, depth: number) -> string?
+
+-- the text of v as a node whose first line follows "key:" / "- " (it starts with a space or a newline)
+function write(st: St, v: any, depth: number): string?
+ local ind = string.rep(" ", st.step * (depth + 1))
+ local s = scalar(st, v, ind, false)
+ if s then
+ return " " .. s
+ end
+ if type(v) ~= "table" then
+ st.err = "cannot write a " .. type(v)
+ return nil
+ end
+ local prefix = ""
+ if st.refs[v] and st.refs[v] > 1 then
+ local a = st.anchors[v]
+ if a then
+ return " *" .. a
+ end
+ st.nextId += 1
+ a = "id" .. format("%03d", st.nextId)
+ st.anchors[v] = a
+ prefix = " &" .. a
+ end
+ local pad = string.rep(" ", st.step * depth)
+ if isArray(v) and not Types.isObject(v) then
+ if #v == 0 then
+ return prefix .. " []"
+ end
+ local parts = {}
+ for _, x in v do
+ local t = write(st, x, depth + 1)
+ if not t then
+ return nil
+ end
+ table.insert(parts, pad .. "-" .. t)
+ end
+ return prefix .. "\n" .. table.concat(parts, "\n")
+ end
+ local keys
+ if Types.isObject(v) then
+ keys = Types.keys(v)
+ else
+ keys = {}
+ for k in next, v do
+ table.insert(keys, k)
+ end
+ if st.sort then
+ table.sort(keys, keyLess)
+ end
+ end
+ if #keys == 0 then
+ return prefix .. " {}"
+ end
+ local parts = {}
+ for _, k in keys do
+ local ks = scalar(st, k, "", true)
+ if not ks or (type(k) == "table" and not Types.Date.is(k) and k ~= Types.null) then
+ st.err = "mapping keys must be scalars"
+ return nil
+ end
+ local t = write(st, v[k], depth + 1)
+ if not t then
+ return nil
+ end
+ table.insert(parts, pad .. ks .. ":" .. t)
+ end
+ return prefix .. "\n" .. table.concat(parts, "\n")
+end
+
+local function document(st: St, v: any): string?
+ local t = write(st, v, 0)
+ if not t then
+ return nil
+ end
+ -- the top level: drop the separator write() put before the first line
+ if string.sub(t, 1, 1) == "\n" then
+ return string.sub(t, 2)
+ end
+ local body = string.sub(t, 2)
+ if string.sub(body, 1, 1) == "&" then
+ -- "&id001\n- a": an anchored top-level collection
+ return body
+ end
+ return body
+end
+
+-- encode(v, opts) -> text | nil, message
+function Emit.encode(v: any, opts: Options?): (string?, string?)
+ local o: Options = opts or {}
+ local st: St = {
+ out = {},
+ step = math.clamp(math.floor(o.indent or 2), 1, 10),
+ sort = o.sortKeys ~= false,
+ null = o.null,
+ refs = {},
+ anchors = {},
+ nextId = 0,
+ err = nil,
+ }
+ local docs = if o.all then v else { v }
+ if type(docs) ~= "table" then
+ return nil, "all: expected an array of documents"
+ end
+ local parts = {}
+ for i, d in docs do
+ st.refs, st.anchors = {}, {}
+ if not count(st, d, {}) then
+ return nil, st.err
+ end
+ local t = document(st, d)
+ if not t then
+ return nil, st.err
+ end
+ local start = i > 1 or o.explicitStart
+ if start then
+ -- a scalar / [] / {} can share the "---" line; a collection starts on the next one
+ local block = type(d) == "table" and d ~= Types.null and not Types.Date.is(d) and next(d) ~= nil
+ local sep = if block and not string.find(t, "^&") then "---\n" else "--- "
+ table.insert(parts, sep .. t .. "\n")
+ else
+ table.insert(parts, t .. "\n")
+ end
+ end
+ return table.concat(parts), nil
+end
+
+return Emit
diff --git a/src/Formats/data/yaml/Parse.luau b/src/Formats/data/yaml/Parse.luau
new file mode 100644
index 0000000..fc84c87
--- /dev/null
+++ b/src/Formats/data/yaml/Parse.luau
@@ -0,0 +1,1360 @@
+--!strict
+-- data/yaml/Parse: the YAML 1.2 parser behind data/yaml. Recursive descent over the text (line breaks normalized):
+-- block mappings / sequences (compact forms included), flow collections, plain / single / double-quoted scalars with
+-- line folding, literal / folded block scalars (indentation and chomping indicators), anchors and aliases (shared
+-- references, with an expansion-size limit), tags (core types + !!binary, !!timestamp; others UNSUPPORTED unless
+-- opts.tags = "ignore"), %YAML / %TAG directives, multi-document streams, comments. Scalars resolve with the core
+-- schema. Not supported: complex keys ("? "), collections as keys, recursive aliases, merge keys "<<" (kept as a
+-- normal key). Internally raises { yamlErr } tables caught by run(); never throws past it.
+local Types = require("@formats/Types")
+
+local Parse = {}
+
+local byte, sub, find, match, char = string.byte, string.sub, string.find, string.match, string.char
+
+export type Options = {
+ all: boolean?, -- every document as an array (default false: the first document; none -> Types.null)
+ tags: ("error" | "ignore")?, -- unknown tags: an UNSUPPORTED error (default) or resolved as if untagged
+ maxAliasNodes: number?, -- the total size of aliased nodes (default 1e6): the billion laughs guard
+ maxDepth: number?, -- nesting limit (default 500)
+ null: any?, -- the value for null (default Types.null)
+}
+
+type St = {
+ s: string,
+ n: number,
+ anchors: { [string]: any },
+ handles: { [string]: string },
+ depth: number,
+ maxDepth: number,
+ aliasNodes: number,
+ maxAlias: number,
+ sizes: { [any]: number },
+ ignoreTags: boolean,
+ null: any,
+}
+
+local CORE = "tag:yaml.org,2002:"
+
+local function raise(code: string, msg: string, p: number)
+ error({ yamlErr = true, code = code, msg = msg, at = p - 1 }, 0)
+end
+local function corrupt(msg: string, p: number)
+ raise("CORRUPT", msg, p)
+end
+
+-- ------------------------------------------------------------------------------------------------ helpers
+local function col(s: string, p: number): number
+ local q = p
+ while q > 1 and byte(s, q - 1) ~= 10 do
+ q -= 1
+ end
+ return p - q
+end
+
+local function isWsEnd(c: number?): boolean -- space, tab, newline or the end
+ return c == nil or c == 32 or c == 9 or c == 10
+end
+
+local function docMarker(s: string, p: number): boolean
+ if p ~= 1 and byte(s, p - 1) ~= 10 then
+ return false
+ end
+ local m = sub(s, p, p + 2)
+ return (m == "---" or m == "...") and isWsEnd(byte(s, p + 3))
+end
+
+-- skip spaces, tabs, comments and line breaks: the next content position (n + 1 at the end)
+local function skip(s: string, p: number): number
+ local n = #s
+ while p <= n do
+ local c = byte(s, p)
+ if c == 32 or c == 9 or c == 10 then
+ p += 1
+ elseif c == 35 and (p == 1 or isWsEnd(byte(s, p - 1))) then
+ local e = find(s, "\n", p, true)
+ if not e then
+ return n + 1
+ end
+ p = e + 1
+ else
+ return p
+ end
+ end
+ return p
+end
+
+-- the number of leading spaces on p's line, and whether a tab comes before p on it
+local function lineIndent(s: string, p: number): (number, boolean)
+ local q = p
+ while q > 1 and byte(s, q - 1) ~= 10 do
+ q -= 1
+ end
+ local sp = (match(s, "^ *()", q) :: number) - q
+ return sp, find(sub(s, q, p - 1), "\t", 1, true) ~= nil
+end
+
+-- block content at p on a new line must not be indented with tabs: a tab before p is an error when the spaces before
+-- it do not already indent the line past ind (siblings: pass ind = their column - 1... any tab is an error)
+local function noTabs(s: string, p: number, ind: number?)
+ local sp, tab = lineIndent(s, p)
+ if tab and (ind == nil or sp <= ind) then
+ error({ yamlErr = true, code = "CORRUPT", msg = "tab in indentation", at = p - 1 }, 0)
+ end
+end
+
+-- skip spaces / tabs on the line
+local function skipLine(s: string, p: number): number
+ return match(s, "^[ \t]*()", p) :: any
+end
+
+-- after a node on its line: only spaces and a comment may follow before the line break
+local function endOfLine(s: string, p: number): boolean
+ local q = skipLine(s, p)
+ local c = byte(s, q)
+ return c == nil or c == 10 or (c == 35 and q > p)
+end
+
+local function utf8char(c: number): string
+ if c < 0x80 then
+ return char(c)
+ elseif c < 0x800 then
+ return char(0xC0 + c // 64, 0x80 + c % 64)
+ elseif c < 0x10000 then
+ return char(0xE0 + c // 4096, 0x80 + (c // 64) % 64, 0x80 + c % 64)
+ end
+ return char(0xF0 + c // 262144, 0x80 + (c // 4096) % 64, 0x80 + (c // 64) % 64, 0x80 + c % 64)
+end
+
+-- ------------------------------------------------------------------------------------------------ resolution
+-- the core schema: a plain scalar's value
+function Parse.resolve(t: string, nullv: any): any
+ if t == "" or t == "~" or t == "null" or t == "Null" or t == "NULL" then
+ return nullv
+ end
+ local c = byte(t)
+ if c == 116 or c == 84 or c == 102 or c == 70 then
+ if t == "true" or t == "True" or t == "TRUE" then
+ return true
+ elseif t == "false" or t == "False" or t == "FALSE" then
+ return false
+ end
+ return t
+ end
+ if not ((c >= 48 and c <= 57) or c == 43 or c == 45 or c == 46) then
+ return t
+ end
+ if match(t, "^[-+]?%d+$") then
+ return tonumber(if c == 43 then sub(t, 2) else t)
+ end
+ local o = match(t, "^0o([0-7]+)$")
+ if o then
+ return tonumber(o, 8)
+ end
+ local x = match(t, "^0x(%x+)$")
+ if x then
+ return tonumber(x, 16)
+ end
+ if match(t, "^[-+]?%d+%.?%d*$") or match(t, "^[-+]?%.%d+$") or match(t, "^[-+]?%d+%.?%d*[eE][-+]?%d+$") or match(t, "^[-+]?%.%d+[eE][-+]?%d+$") then
+ local v = tonumber(if c == 43 then sub(t, 2) else t)
+ if v then
+ return v
+ end
+ end
+ local inf = match(t, "^([-+]?)%.[iI][nN][fF]$")
+ if inf and (t == inf .. ".inf" or t == inf .. ".Inf" or t == inf .. ".INF") then
+ return if inf == "-" then -math.huge else math.huge
+ end
+ if t == ".nan" or t == ".NaN" or t == ".NAN" then
+ return 0 / 0
+ end
+ return t
+end
+
+local B64: { [number]: number } = {}
+do
+ local alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
+ for i = 1, 64 do
+ B64[byte(alphabet, i)] = i - 1
+ end
+end
+local function base64(t: string): buffer?
+ t = string.gsub(t, "[%s]", "")
+ t = string.gsub(t, "=+$", "")
+ local n = #t
+ if n % 4 == 1 then
+ return nil
+ end
+ local out = buffer.create(n * 3 // 4)
+ local o = 0
+ local acc, bits = 0, 0
+ for i = 1, n do
+ local v = B64[byte(t, i)]
+ if v == nil then
+ return nil
+ end
+ acc = acc * 64 + v
+ bits += 6
+ if bits >= 8 then
+ bits -= 8
+ local b = acc // (2 ^ bits)
+ buffer.writeu8(out, o, b)
+ o += 1
+ acc -= b * 2 ^ bits
+ end
+ end
+ return out
+end
+
+-- a scalar's value given its tag (nil = untagged, "!" = non-specific)
+local function scalarValue(st: St, raw: string, plain: boolean, tag: string?, p: number): any
+ if tag == nil then
+ return if plain then Parse.resolve(raw, st.null) else raw
+ end
+ if tag == "!" or tag == CORE .. "str" then
+ return raw
+ end
+ if sub(tag, 1, #CORE) == CORE then
+ local kind = sub(tag, #CORE + 1)
+ local v = Parse.resolve(raw, st.null)
+ if kind == "null" then
+ if v ~= st.null then
+ corrupt("bad !!null " .. raw, p)
+ end
+ return v
+ elseif kind == "bool" then
+ if type(v) ~= "boolean" then
+ corrupt("bad !!bool " .. raw, p)
+ end
+ return v
+ elseif kind == "int" then
+ if type(v) ~= "number" or not (match(raw, "^[-+]?%d+$") or match(raw, "^0[ox]")) then
+ corrupt("bad !!int " .. raw, p)
+ end
+ return v
+ elseif kind == "float" then
+ if type(v) ~= "number" then
+ corrupt("bad !!float " .. raw, p)
+ end
+ return v
+ elseif kind == "binary" then
+ local b = base64(raw)
+ if not b then
+ corrupt("bad !!binary data", p)
+ end
+ return b
+ elseif kind == "timestamp" then
+ local d = Types.Date.parse(raw)
+ if not d then
+ corrupt("bad !!timestamp " .. raw, p)
+ end
+ return d
+ elseif kind == "map" or kind == "seq" then
+ corrupt("!!" .. kind .. " on a scalar", p)
+ end
+ end
+ if st.ignoreTags then
+ return if plain then Parse.resolve(raw, st.null) else raw
+ end
+ raise("UNSUPPORTED", "tag " .. tag, p)
+ return nil
+end
+
+local function collectionTag(st: St, tag: string?, kind: string, p: number)
+ if tag == nil or tag == "!" or tag == CORE .. kind then
+ return
+ end
+ if sub(tag, 1, #CORE) == CORE then
+ local k = sub(tag, #CORE + 1)
+ if k == "map" or k == "seq" or k == "str" or k == "int" or k == "float" or k == "bool" or k == "null" or k == "binary" then
+ corrupt("!!" .. k .. " on a " .. kind, p)
+ end
+ end
+ if not st.ignoreTags then
+ raise("UNSUPPORTED", "tag " .. tag, p)
+ end
+end
+
+-- expansion size of a value (nodes), memoized
+local function size(st: St, v: any): number
+ if type(v) ~= "table" or v == st.null then
+ return 1
+ end
+ local m = st.sizes[v]
+ if m then
+ return m
+ end
+ local total = 1
+ for k, x in next, v do
+ total += size(st, k) + size(st, x)
+ end
+ st.sizes[v] = total
+ return total
+end
+
+-- ------------------------------------------------------------------------------------------------ properties
+type Props = { anchor: string?, tag: string?, at: number }
+
+-- anchors / tags at p -> props?, the position after them (and the spaces after them)
+local function properties(st: St, p: number): (Props?, number)
+ local s = st.s
+ local props: Props? = nil
+ while true do
+ local c = byte(s, p)
+ if c == 38 then -- &
+ local name = match(s, "^&([^%s,%[%]{}]+)", p)
+ if not name then
+ corrupt("bad anchor", p)
+ end
+ local pr: Props = props or { at = p }
+ props = pr
+ if pr.anchor then
+ corrupt("two anchors on one node", p)
+ end
+ pr.anchor = name
+ p = skipLine(s, p + 1 + #(name :: string))
+ elseif c == 33 then -- !
+ local pr: Props = props or { at = p }
+ props = pr
+ if pr.tag then
+ corrupt("two tags on one node", p)
+ end
+ local tag: string
+ if byte(s, p + 1) == 60 then -- !
+ local v = match(s, "^!<([^>%s]+)>", p)
+ if not v then
+ corrupt("bad verbatim tag", p)
+ end
+ tag = v :: string
+ p += #tag + 3
+ else
+ local handle, suffix = match(s, "^(![%w%-]*!)([^%s,%[%]{}]*)", p)
+ if handle then
+ local prefix = st.handles[handle]
+ if not prefix then
+ corrupt("undefined tag handle " .. handle, p)
+ end
+ if suffix == "" then
+ corrupt("empty tag", p)
+ end
+ tag = prefix .. string.gsub(suffix :: string, "%%(%x%x)", function(h: string): string
+ return char(tonumber(h, 16) :: number)
+ end)
+ else
+ local sfx = match(s, "^!([^%s,%[%]{}]*)", p) :: string
+ if sfx == "" then
+ tag = "!"
+ else
+ tag = st.handles["!"] .. sfx
+ end
+ end
+ p += #(match(s, "^![^%s,%[%]{}]*", p) :: string)
+ end
+ pr.tag = tag
+ if not isWsEnd(byte(s, p)) and byte(s, p) ~= 44 and byte(s, p) ~= 93 and byte(s, p) ~= 125 then
+ corrupt("bad tag", p)
+ end
+ p = skipLine(s, p)
+ else
+ return props, p
+ end
+ end
+end
+
+local function finish(st: St, props: Props?, v: any): any
+ if props and props.anchor then
+ st.anchors[props.anchor] = v
+ end
+ return v
+end
+
+local function alias(st: St, p: number): (any, number)
+ local s = st.s
+ local name = match(s, "^%*([^%s,%[%]{}]+)", p)
+ if not name then
+ corrupt("bad alias", p)
+ end
+ local v = st.anchors[name :: string]
+ if v == nil then
+ corrupt("undefined alias *" .. (name :: string), p)
+ end
+ st.aliasNodes += size(st, v)
+ if st.aliasNodes > st.maxAlias then
+ raise("LIMIT", "alias expansion over " .. st.maxAlias .. " nodes", p)
+ end
+ return v, p + 1 + #(name :: string)
+end
+
+-- ------------------------------------------------------------------------------------------------ scalars
+-- fold the line break(s) at p (p at a '\n'): the text they become and the position of the next line's content.
+-- Lines holding only spaces / tabs count as empty.
+local function fold(s: string, p: number): (string, number)
+ local empties = 0
+ local q = p + 1
+ while true do
+ local r = skipLine(s, q)
+ if byte(s, r) == 10 then
+ empties += 1
+ q = r + 1
+ else
+ return (if empties == 0 then " " else string.rep("\n", empties)), q
+ end
+ end
+end
+
+local ESC: { [number]: string } = {
+ [48] = "\0",
+ [97] = "\a",
+ [98] = "\b",
+ [116] = "\t",
+ [9] = "\t",
+ [110] = "\n",
+ [118] = "\v",
+ [102] = "\f",
+ [114] = "\r",
+ [101] = "\27",
+ [32] = " ",
+ [34] = '"',
+ [47] = "/",
+ [92] = "\\",
+ [78] = "\194\133",
+ [95] = "\194\160",
+ [76] = "\226\128\168",
+ [80] = "\226\128\169",
+}
+
+-- a quoted scalar at p ('"' or "'") -> text, the position after the closing quote
+local function quoted(st: St, p: number, ind: number): (string, number)
+ local s = st.s
+ local dq = byte(s, p) == 34
+ local parts: { string } = {}
+ local i = p + 1
+ local stop = if dq then '[\\"\n]' else "['\n]"
+ while true do
+ local j = find(s, stop, i)
+ if not j then
+ raise("TRUNCATED", "unterminated quoted scalar", p)
+ end
+ local jj = j :: number
+ local seg = sub(s, i, jj - 1)
+ local c = byte(s, jj)
+ if c == 10 then
+ table.insert(parts, (string.gsub(seg, "[ \t]+$", "")))
+ local f, q = fold(s, jj)
+ if docMarker(s, q) then
+ corrupt("document marker inside a quoted scalar", q)
+ end
+ if ind >= 0 and (match(s, "^ *()", q) :: number) - q <= ind then
+ corrupt("a quoted scalar's continuation line is not indented", q)
+ end
+ table.insert(parts, f)
+ i = skipLine(s, q)
+ elseif dq and c == 92 then
+ table.insert(parts, seg)
+ local e = byte(s, jj + 1)
+ if e == 10 then -- escaped line break: joined without a space
+ local r = jj + 2
+ while true do
+ local q = skipLine(s, r)
+ if byte(s, q) == 10 then
+ table.insert(parts, "\n")
+ r = q + 1
+ else
+ i = q
+ break
+ end
+ end
+ elseif e == 120 or e == 117 or e == 85 then
+ local len = if e == 120 then 2 elseif e == 117 then 4 else 8
+ local h = sub(s, jj + 2, jj + 1 + len)
+ if #h ~= len or not match(h, "^%x+$") then
+ corrupt("bad escape", jj)
+ end
+ local cp = tonumber(h, 16) :: number
+ if cp > 0x10FFFF then
+ corrupt("bad escape", jj)
+ end
+ table.insert(parts, utf8char(cp))
+ i = jj + 2 + len
+ else
+ local r = if e then ESC[e] else nil
+ if not r then
+ corrupt("bad escape", jj)
+ end
+ table.insert(parts, r :: string)
+ i = jj + 2
+ end
+ elseif not dq and byte(s, jj + 1) == 39 then
+ table.insert(parts, seg .. "'")
+ i = jj + 2
+ else
+ table.insert(parts, seg)
+ return table.concat(parts), jj + 1
+ end
+ end
+end
+
+-- a plain scalar at p -> text, the position after it. ind: continuation lines must be indented deeper than ind
+-- (block context); flow: the flow-context rules (stops at , [ ] { }).
+local function plain(st: St, p: number, ind: number, flow: boolean): (string, number)
+ local s = st.s
+ local parts: { string } = {}
+ local i = p
+ local lastEnd = p
+ while true do
+ -- one line's worth
+ local j = i
+ local stopAt = nil
+ while true do
+ local c = byte(s, j)
+ if c == nil or c == 10 then
+ break
+ elseif c == 58 then -- :
+ local d = byte(s, j + 1)
+ if isWsEnd(d) or (flow and (d == 44 or d == 91 or d == 93 or d == 123 or d == 125)) then
+ stopAt = j
+ break
+ end
+ elseif c == 35 and (byte(s, j - 1) == 32 or byte(s, j - 1) == 9) then
+ stopAt = j
+ break
+ elseif flow and (c == 44 or c == 91 or c == 93 or c == 123 or c == 125) then
+ stopAt = j
+ break
+ end
+ j += 1
+ end
+ local seg = string.gsub(sub(s, i, j - 1), "[ \t]+$", "")
+ table.insert(parts, seg)
+ lastEnd = i + #seg
+ if stopAt or byte(s, j) == nil then
+ return table.concat(parts), lastEnd
+ end
+ -- a continuation line?
+ local f, q = fold(s, j)
+ local r = skipLine(s, q)
+ local c = byte(s, r)
+ if c == nil or docMarker(s, q) or c == 35 or (not flow and (match(s, "^ *()", q) :: number) - q <= ind) then
+ return table.concat(parts), lastEnd
+ end
+ if flow and (c == 44 or c == 93 or c == 125 or (c == 58 and isWsEnd(byte(s, r + 1)))) then
+ return table.concat(parts), lastEnd
+ end
+ table.insert(parts, f)
+ i = r
+ end
+end
+
+-- a block scalar at p ('|' or '>'); ind = the parent's indentation -> text, the position after it
+local function blockScalar(st: St, p: number, ind: number): (string, number)
+ local s = st.s
+ local folded = byte(s, p) == 62
+ local q = p + 1
+ local explicit: number? = nil
+ local chomp = "clip"
+ for _ = 1, 2 do
+ local c = byte(s, q)
+ if c and c >= 49 and c <= 57 and not explicit then
+ explicit = c - 48
+ q += 1
+ elseif (c == 43 or c == 45) and chomp == "clip" then
+ chomp = if c == 43 then "keep" else "strip"
+ q += 1
+ end
+ end
+ if not endOfLine(s, q) then
+ corrupt("bad block scalar header", q)
+ end
+ local nl = find(s, "\n", q, true)
+ local lines: { string } = {}
+ local trailing = 0 -- empty lines after the last content line
+ if not nl then
+ return "", #s + 1
+ end
+ local ls = (nl :: number) + 1
+ local indent: number
+ if explicit then
+ indent = math.max(ind + explicit, 0) -- n + the indicator (n = -1 at the top level)
+ else
+ -- auto-detect: the first non-empty line; leading empty lines may not be longer
+ local maxEmpty = 0
+ local r = ls
+ indent = -1
+ while true do
+ local sp = (match(s, "^ *()", r) :: number) - r
+ local c = byte(s, r + sp)
+ if c == 10 then
+ maxEmpty = math.max(maxEmpty, sp)
+ r = r + sp + 1
+ elseif c == nil then
+ maxEmpty = math.max(maxEmpty, sp)
+ indent = math.max(maxEmpty, ind + 1)
+ break
+ else
+ if docMarker(s, r) then
+ indent = math.max(maxEmpty, ind + 1)
+ break
+ end
+ indent = sp
+ if sp < maxEmpty then
+ corrupt("leading empty lines indented more than the block scalar", r)
+ end
+ break
+ end
+ end
+ if indent <= ind then
+ indent = ind + 1
+ end
+ end
+ -- the lines
+ local r = ls
+ local pendingEmpty = 0
+ local endPos = ls
+ while r <= #s do
+ if docMarker(s, r) then
+ break
+ end
+ local sp = (match(s, "^ *()", r) :: number) - r
+ local e = find(s, "\n", r, true) or (#s + 1)
+ if sp >= indent then
+ local text = sub(s, r + indent, e - 1)
+ for _ = 1, pendingEmpty do
+ table.insert(lines, "")
+ end
+ pendingEmpty = 0
+ table.insert(lines, text)
+ elseif r + sp == e then
+ pendingEmpty += 1
+ else
+ if byte(s, r + sp) == 9 then
+ corrupt("tab in block scalar indentation", r + sp)
+ end
+ break
+ end
+ r = e + 1
+ endPos = math.min(r, #s + 1)
+ end
+ trailing = pendingEmpty
+ local body: string
+ if #lines == 0 then
+ body = ""
+ elseif not folded then
+ body = table.concat(lines, "\n")
+ else
+ local out: { string } = {}
+ local prevMore = false
+ local empties = 0
+ local first = true
+ for _, l in lines do
+ if l == "" then
+ empties += 1
+ else
+ local more = byte(l) == 32 or byte(l) == 9
+ if first then
+ table.insert(out, string.rep("\n", empties))
+ elseif empties == 0 then
+ table.insert(out, if more or prevMore then "\n" else " ")
+ else
+ table.insert(out, string.rep("\n", if more or prevMore then empties + 1 else empties))
+ end
+ table.insert(out, l)
+ first = false
+ prevMore = more
+ empties = 0
+ end
+ end
+ trailing += empties -- empty lines after the last content line (or all of them)
+ body = table.concat(out)
+ end
+ if not folded then
+ -- literal: trailing "" lines inside `lines` are content-indented empty lines; count them as trailing
+ local k = #lines
+ while k > 0 and lines[k] == "" do
+ k -= 1
+ trailing += 1
+ end
+ body = table.concat(lines, "\n", 1, k)
+ if k == 0 then
+ body = ""
+ end
+ lines = table.move(lines, 1, k, 1, {})
+ end
+ local hasContent = false
+ for _, l in lines do
+ if l ~= "" then
+ hasContent = true
+ break
+ end
+ end
+ if chomp == "strip" then
+ return body, endPos
+ elseif chomp == "clip" then
+ return (if hasContent then body .. "\n" else ""), endPos
+ end
+ return (if hasContent then body .. "\n" else "") .. string.rep("\n", trailing), endPos
+end
+
+-- ------------------------------------------------------------------------------------------------ flow
+local parseFlow: (st: St, p: number, ind: number) -> (any, number)
+
+local function enter(st: St, p: number)
+ st.depth += 1
+ if st.depth > st.maxDepth then
+ raise("LIMIT", "nested deeper than " .. st.maxDepth, p)
+ end
+end
+
+-- a flow node at p (after skip) -> value, next, wasEmpty
+local function flowNode(st: St, p: number, ind: number): (any, number, boolean)
+ local s = st.s
+ local props, q = properties(st, p)
+ if props then
+ q = skip(s, q)
+ end
+ local c = byte(s, q)
+ local v: any
+ if c == 42 then -- *
+ if props then
+ corrupt("properties on an alias", q)
+ end
+ return alias(st, q)
+ elseif c == 91 or c == 123 then
+ v, q = parseFlow(st, q, ind)
+ collectionTag(st, props and props.tag, if c == 91 then "seq" else "map", q)
+ return finish(st, props, v), q, false
+ elseif c == 34 or c == 39 then
+ local t, r = quoted(st, q, ind)
+ return finish(st, props, scalarValue(st, t, false, props and props.tag, q)), r, false
+ elseif c == nil or c == 44 or c == 93 or c == 125 or (c == 58 and (isWsEnd(byte(s, q + 1)) or byte(s, q + 1) == 44 or byte(s, q + 1) == 93 or byte(s, q + 1) == 125)) then
+ -- an empty node
+ return finish(st, props, scalarValue(st, "", true, props and props.tag, q)), (if props then q else p), true
+ elseif c == 35 or c == 38 or c == 33 or c == 124 or c == 62 or c == 37 or c == 64 or c == 96 then
+ corrupt("unexpected character in a flow collection", q)
+ elseif (c == 45 or c == 63 or c == 58) and (isWsEnd(byte(s, q + 1)) or byte(s, q + 1) == 44 or byte(s, q + 1) == 93 or byte(s, q + 1) == 125) then
+ if c == 63 then
+ raise("UNSUPPORTED", "explicit keys (?) in flow collections", q)
+ end
+ corrupt("unexpected '" .. char(c :: number) .. "' in a flow collection", q)
+ end
+ local t, r = plain(st, q, ind, true)
+ return finish(st, props, scalarValue(st, t, true, props and props.tag, q)), r, false
+end
+
+local function checkKey(st: St, k: any, p: number): any
+ if type(k) == "table" and k ~= st.null and not Types.Date.is(k) then
+ raise("UNSUPPORTED", "collections as mapping keys", p)
+ end
+ if k ~= k then
+ corrupt("NaN as a mapping key", p)
+ end
+ return k
+end
+
+function parseFlow(st: St, p: number, ind: number): (any, number)
+ local s = st.s
+ enter(st, p)
+ local isMap = byte(s, p) == 123
+ local close = if isMap then 125 else 93
+ local t: { [any]: any } = {}
+ local order: { any } = {}
+ local count = 0
+ local q = p + 1
+ local function flowSkip(from: number): number
+ local r = skip(s, from)
+ if ind >= 0 and r <= #s and find(sub(s, from, r), "\n", 1, true) and (lineIndent(s, r)) <= ind then
+ corrupt("a flow collection's line is not indented", r)
+ end
+ return r
+ end
+ while true do
+ q = flowSkip(q)
+ local c = byte(s, q)
+ if c == nil then
+ raise("TRUNCATED", "unterminated flow collection", p)
+ end
+ if docMarker(s, q) then
+ corrupt("document marker inside a flow collection", q)
+ end
+ if c == close then
+ q += 1
+ break
+ end
+ local explicitKey = false
+ if c == 63 and isWsEnd(byte(s, q + 1)) then
+ explicitKey = true
+ q = flowSkip(q + 1)
+ end
+ local startLine = q
+ local k, r, empty = flowNode(st, q, ind)
+ r = flowSkip(r)
+ local hasColon = false
+ if byte(s, r) == 58 then
+ local d = byte(s, r + 1)
+ local jsonLike = byte(s, q) == 34 or byte(s, q) == 39 or byte(s, q) == 91 or byte(s, q) == 123
+ if isWsEnd(d) or d == 44 or d == 93 or d == 125 or jsonLike then
+ hasColon = true
+ -- an implicit key must sit on one line
+ if not isMap and not explicitKey and find(sub(s, startLine, r), "\n", 1, true) then
+ corrupt("multi-line implicit key", startLine)
+ end
+ r += 1
+ end
+ end
+ if isMap then
+ local v: any = st.null
+ if hasColon then
+ local r2 = flowSkip(r)
+ local cc = byte(s, r2)
+ if cc ~= 44 and cc ~= 125 then
+ v, r = flowNode(st, r2, ind)
+ end
+ end
+ if empty and not hasColon and not explicitKey then
+ corrupt("expected a mapping entry", q)
+ end
+ k = checkKey(st, k, q)
+ if t[k] == nil then
+ table.insert(order, k)
+ end
+ t[k] = v
+ else
+ local item = k
+ if hasColon or explicitKey then
+ local v: any = st.null
+ local r2 = if hasColon then flowSkip(r) else r
+ local cc = byte(s, r2)
+ if hasColon and cc ~= 44 and cc ~= 93 then
+ v, r = flowNode(st, r2, ind)
+ end
+ k = checkKey(st, k, q)
+ item = Types.object({ [k] = v }, { k })
+ elseif empty then
+ corrupt("empty sequence entry", q)
+ end
+ count += 1
+ t[count] = item
+ end
+ r = flowSkip(r)
+ local cc = byte(s, r)
+ if cc == 44 then
+ q = r + 1
+ elseif cc == close then
+ q = r + 1
+ break
+ elseif cc == nil then
+ raise("TRUNCATED", "unterminated flow collection", p)
+ else
+ corrupt(if isMap then "expected ',' or '}'" else "expected ',' or ']'", r)
+ end
+ end
+ st.depth -= 1
+ if isMap then
+ return Types.object(t, order), q
+ end
+ return t, q
+end
+
+-- ------------------------------------------------------------------------------------------------ block
+local blockNode: (st: St, ind: number, p: number, inline: boolean, mapParent: boolean) -> (any, number)
+
+-- an implicit key at p (on one line, followed by ':' and a space / the end of the line) -> key, position after ':'
+local function implicitKey(st: St, p: number): (any, number?)
+ local s = st.s
+ local c = byte(s, p)
+ if c == 34 or c == 39 then
+ local ok, t, q = pcall(quoted, st, p, -1)
+ if not ok then
+ return nil, nil
+ end
+ if find(sub(s, p, q - 1), "\n", 1, true) then
+ return nil, nil
+ end
+ local r = skipLine(s, q)
+ if byte(s, r) == 58 and isWsEnd(byte(s, r + 1)) then
+ return t, r + 1
+ end
+ return nil, nil
+ elseif c == 42 then
+ local name = match(s, "^%*([^%s,%[%]{}]+)", p)
+ if not name then
+ return nil, nil
+ end
+ local r = skipLine(s, p + 1 + #name)
+ if byte(s, r) == 58 and isWsEnd(byte(s, r + 1)) then
+ return true, r + 1
+ end
+ return nil, nil
+ elseif c == 91 or c == 123 then
+ -- a flow collection used as a key?
+ local e = find(s, "\n", p, true) or #s + 1
+ local line = sub(s, p, e - 1)
+ if match(line, "[%]}]%s*:%s") or match(line, "[%]}]%s*:$") then
+ local ok, _, q = pcall(parseFlow, st, p, -1)
+ if ok and byte(s, skipLine(s, q)) == 58 then
+ raise("UNSUPPORTED", "collections as mapping keys", p)
+ end
+ end
+ return nil, nil
+ end
+ if c == nil or c == 10 or c == 35 or c == 124 or c == 62 or c == 37 or c == 64 or c == 96 or c == 44 or c == 93 or c == 125 then
+ return nil, nil
+ end
+ if (c == 45 or c == 63 or c == 58) and isWsEnd(byte(s, p + 1)) then
+ return nil, nil
+ end
+ local j = p
+ while true do
+ local d = byte(s, j)
+ if d == nil or d == 10 then
+ return nil, nil
+ elseif d == 58 and isWsEnd(byte(s, j + 1)) then
+ break
+ elseif d == 35 and (byte(s, j - 1) == 32 or byte(s, j - 1) == 9) then
+ return nil, nil
+ end
+ j += 1
+ end
+ local t = string.gsub(sub(s, p, j - 1), "[ \t]+$", "")
+ return t, j + 1
+end
+
+local function readKey(st: St, p: number, props: Props?): (any, number)
+ local s = st.s
+ local c = byte(s, p)
+ local tag = props and props.tag
+ local k: any
+ local q: number
+ if c == 42 then
+ if props then
+ corrupt("properties on an alias", p)
+ end
+ k, q = alias(st, p)
+ q = skipLine(s, q)
+ q += 1 -- the ':'
+ elseif c == 34 or c == 39 then
+ local t, r = quoted(st, p, -1)
+ if find(sub(s, p, r - 1), "\n", 1, true) then
+ corrupt("multi-line implicit key", p)
+ end
+ k = scalarValue(st, t, false, tag, p)
+ q = skipLine(s, r) + 1
+ else
+ local t, after = implicitKey(st, p)
+ if t == nil then
+ corrupt("expected a mapping key", p)
+ end
+ k = scalarValue(st, t, true, tag, p)
+ q = after :: number
+ end
+ k = finish(st, props, k)
+ return checkKey(st, k, p), q
+end
+
+-- a node on the lines after p's line (content deeper than ind; or a sequence at ind when seqAt) -> value, next | null
+local function nextLineNode(st: St, ind: number, p: number, seqAt: boolean, mapParent: boolean): (any, number)
+ local s = st.s
+ local r = skip(s, p)
+ if r <= #s and not docMarker(s, r) then
+ local c = col(s, r)
+ if c > ind or (seqAt and c == ind and byte(s, r) == 45 and isWsEnd(byte(s, r + 1))) then
+ noTabs(s, r, ind)
+ return blockNode(st, ind, r, false, mapParent)
+ end
+ end
+ return st.null, p
+end
+
+-- the value after a ':' (at p, just past it) of a mapping at column mc
+local function mapValue(st: St, mc: number, p: number, explicit: boolean): (any, number)
+ local s = st.s
+ local r = skipLine(s, p)
+ local cc = byte(s, r)
+ if cc == nil or cc == 10 or (cc == 35 and r > p) then
+ return nextLineNode(st, mc, r, true, true)
+ end
+ return blockNode(st, mc, r, not explicit, true)
+end
+
+local function blockMap(st: St, mc: number, p: number, firstProps: Props?): (any, number)
+ local s = st.s
+ enter(st, p)
+ local t: { [any]: any } = {}
+ local order: { any } = {}
+ local q = p
+ local first = true
+ while true do
+ local props: Props? = nil
+ if first and firstProps then
+ props = firstProps
+ else
+ props, p = properties(st, p)
+ end
+ first = false
+ local c = byte(s, p)
+ local k: any
+ local v: any
+ if ((c == 63 and not props) or c == 58) and isWsEnd(byte(s, p + 1)) then
+ -- "? key" (explicit) and ": value" (an empty key)
+ k = st.null
+ q = p
+ if c == 63 then
+ local r = skipLine(s, p + 1)
+ local cc = byte(s, r)
+ if cc == nil or cc == 10 or (cc == 35 and r > p + 1) then
+ k, q = nextLineNode(st, mc, r, true, false)
+ else
+ k, q = blockNode(st, mc, r, false, false)
+ end
+ k = checkKey(st, k, p)
+ local r3 = skip(s, q)
+ if r3 <= #s and not docMarker(s, r3) and col(s, r3) == mc and byte(s, r3) == 58 and isWsEnd(byte(s, r3 + 1)) then
+ v, q = mapValue(st, mc, r3 + 1, true)
+ else
+ v = st.null
+ end
+ else
+ k = finish(st, props, scalarValue(st, "", true, props and props.tag, p))
+ v, q = mapValue(st, mc, p + 1, true)
+ end
+ else
+ local after
+ k, after = readKey(st, p, props)
+ v, q = mapValue(st, mc, after, false)
+ end
+ if t[k] == nil then
+ table.insert(order, k)
+ end
+ t[k] = v
+ local r3 = skip(s, q)
+ if r3 > #s or docMarker(s, r3) then
+ break
+ end
+ local cc3 = col(s, r3)
+ if cc3 == mc then
+ noTabs(s, r3)
+ if byte(s, r3) == 45 and isWsEnd(byte(s, r3 + 1)) then
+ corrupt("a sequence entry where a mapping key is expected", r3)
+ end
+ p = r3
+ elseif cc3 < mc then
+ break
+ else
+ corrupt("bad indentation of a mapping entry", r3)
+ end
+ end
+ st.depth -= 1
+ return Types.object(t, order), q
+end
+
+local function blockSeq(st: St, sc: number, p: number): (any, number)
+ local s = st.s
+ enter(st, p)
+ local t: { any } = {}
+ local q = p
+ while true do
+ local r = skipLine(s, p + 1)
+ local c = byte(s, r)
+ local v: any
+ if c == nil or c == 10 or (c == 35 and r > p + 1) then
+ v, q = nextLineNode(st, sc, r, false, false)
+ else
+ if find(sub(s, p + 1, r - 1), "\t", 1, true) and (((c == 45 or c == 63 or c == 58) and isWsEnd(byte(s, r + 1))) or implicitKey(st, r) ~= nil) then
+ corrupt("tab before a compact collection", r)
+ end
+ v, q = blockNode(st, sc, r, false, false)
+ end
+ table.insert(t, v)
+ local r3 = skip(s, q)
+ if r3 > #s or docMarker(s, r3) then
+ break
+ end
+ local cc = col(s, r3)
+ if cc == sc and byte(s, r3) == 45 and isWsEnd(byte(s, r3 + 1)) then
+ noTabs(s, r3)
+ p = r3
+ elseif cc <= sc then
+ break
+ else
+ corrupt("bad indentation of a sequence entry", r3)
+ end
+ end
+ st.depth -= 1
+ return t, q
+end
+
+-- the node at q after its properties (props may be nil); start = where the properties began
+local function afterProps(st: St, ind: number, start: number, q: number, props: Props?, inline: boolean, mapParent: boolean): (any, number)
+ local s = st.s
+ local tag = props and props.tag
+ local c = byte(s, q)
+ if c == 42 then
+ if props then
+ corrupt("properties on an alias", q)
+ end
+ if implicitKey(st, q) ~= nil then
+ if inline then
+ corrupt("a mapping cannot start on its key's line", q)
+ end
+ return blockMap(st, col(s, q), q, nil)
+ end
+ local v, e = alias(st, q)
+ if not endOfLine(s, e) then
+ corrupt("unexpected text after an alias", e)
+ end
+ return v, e
+ end
+ if c == 45 and isWsEnd(byte(s, q + 1)) then
+ if inline or props then
+ corrupt("a sequence cannot start here", q)
+ end
+ return blockSeq(st, col(s, q), q)
+ elseif (c == 63 or c == 58) and isWsEnd(byte(s, q + 1)) then
+ if inline or (props and c == 63) then
+ corrupt("a mapping cannot start here", q)
+ end
+ return blockMap(st, col(s, start), q, props)
+ elseif c == 124 or c == 62 then
+ local text, e = blockScalar(st, q, ind)
+ return finish(st, props, scalarValue(st, text, false, tag, q)), e
+ elseif c == 91 or c == 123 then
+ implicitKey(st, q) -- raises UNSUPPORTED for a flow collection used as a key
+ local v, e = parseFlow(st, q, ind)
+ collectionTag(st, tag, if c == 91 then "seq" else "map", q)
+ if not endOfLine(s, e) then
+ corrupt("unexpected text after a flow collection", e)
+ end
+ return finish(st, props, v), e
+ end
+ if implicitKey(st, q) ~= nil then
+ if inline then
+ corrupt("a mapping cannot start on its key's line", q)
+ end
+ -- properties on the key's line belong to the first key
+ return blockMap(st, col(s, start), q, props)
+ end
+ if c == 34 or c == 39 then
+ local text, e = quoted(st, q, ind)
+ if not endOfLine(s, e) then
+ corrupt("unexpected text after a quoted scalar", e)
+ end
+ return finish(st, props, scalarValue(st, text, false, tag, q)), e
+ end
+ if c == 35 or c == 37 or c == 64 or c == 96 or c == 44 or c == 93 or c == 125 or c == 38 or c == 33 then
+ corrupt("unexpected character '" .. char(c :: number) .. "'", q)
+ end
+ local text, e = plain(st, q, ind, false)
+ if not endOfLine(s, e) then
+ corrupt("unexpected ':' (mapping values are not allowed here)", e)
+ end
+ return finish(st, props, scalarValue(st, text, true, tag, q)), e
+end
+
+-- a block node at p (content; col(p) > ind, or == ind for a sequence that is a mapping's value). inline: on the
+-- same line as its mapping key (no new block collection may start). mapParent: a sequence at the parent's
+-- indentation may follow properties that end their line.
+function blockNode(st: St, ind: number, p: number, inline: boolean, mapParent: boolean): (any, number)
+ local s = st.s
+ local props, q = properties(st, p)
+ if not props then
+ return afterProps(st, ind, p, q, nil, inline, mapParent)
+ end
+ -- properties ending their line apply to the node on the next lines; more properties there merge in, unless
+ -- they start a mapping key
+ local c = byte(s, q)
+ if not (c == nil or c == 10 or (c == 35 and q > p)) then
+ return afterProps(st, ind, p, q, props, inline, mapParent)
+ end
+ while true do
+ local r = skip(s, q)
+ if r > #s or docMarker(s, r) then
+ break
+ end
+ local cr = col(s, r)
+ if not (cr > ind or (mapParent and cr == ind and byte(s, r) == 45 and isWsEnd(byte(s, r + 1)))) then
+ break
+ end
+ noTabs(s, r, ind)
+ local cc = byte(s, r)
+ if cc == 38 or cc == 33 then
+ local p2, q2 = properties(st, r)
+ local c2 = byte(s, q2)
+ if c2 == nil or c2 == 10 or (c2 == 35 and q2 > r) then
+ local pr = props :: Props
+ if (p2 :: Props).anchor then
+ if pr.anchor then
+ corrupt("two anchors on one node", r)
+ end
+ pr.anchor = (p2 :: Props).anchor
+ end
+ if (p2 :: Props).tag then
+ if pr.tag then
+ corrupt("two tags on one node", r)
+ end
+ pr.tag = (p2 :: Props).tag
+ end
+ q = q2
+ continue
+ end
+ if implicitKey(st, q2) ~= nil then
+ local v, e = blockMap(st, cr, r, nil)
+ collectionTag(st, (props :: Props).tag, "map", r)
+ return finish(st, props, v), e
+ end
+ -- properties then a scalar on the next line: merge
+ local pr = props :: Props
+ if (p2 :: Props).anchor and pr.anchor or (p2 :: Props).tag and pr.tag then
+ corrupt("two anchors or tags on one node", r)
+ end
+ pr.anchor = pr.anchor or (p2 :: Props).anchor
+ pr.tag = pr.tag or (p2 :: Props).tag
+ return afterProps(st, ind, r, q2, pr, false, mapParent)
+ end
+ local tag = (props :: Props).tag
+ if cc == 45 and isWsEnd(byte(s, r + 1)) then
+ local v, e = blockSeq(st, cr, r)
+ collectionTag(st, tag, "seq", r)
+ return finish(st, props, v), e
+ elseif ((cc == 63 or cc == 58) and isWsEnd(byte(s, r + 1))) or (cc ~= 91 and cc ~= 123 and implicitKey(st, r) ~= nil) then
+ local v, e = blockMap(st, cr, r, nil)
+ collectionTag(st, tag, "map", r)
+ return finish(st, props, v), e
+ elseif cc == 42 then
+ corrupt("properties on an alias", r)
+ end
+ return afterProps(st, ind, r, r, props, false, mapParent)
+ end
+ return finish(st, props, scalarValue(st, "", true, (props :: Props).tag, q)), q
+end
+
+-- ------------------------------------------------------------------------------------------------ stream
+local function stream(st: St): { any }
+ local s = st.s
+ local n = #s
+ local docs = {}
+ local p = 1
+ local needEnd = false -- a bare document after a document must follow "..." or "---"
+ while true do
+ p = skip(s, p)
+ if p > n then
+ break
+ end
+ local sawDirective = false
+ st.handles = { ["!"] = "!", ["!!"] = CORE }
+ local yamlSeen = false
+ while byte(s, p) == 37 and col(s, p) == 0 do -- %
+ if needEnd then
+ corrupt("a directive needs '...' after the previous document", p)
+ end
+ local e = find(s, "\n", p, true) or n + 1
+ local line = string.gsub(sub(s, p, e - 1), "%s+#.*$", "")
+ local name = match(line, "^%%(%S+)")
+ if name == "YAML" then
+ if yamlSeen then
+ corrupt("two %YAML directives", p)
+ end
+ yamlSeen = true
+ local v = match(line, "^%%YAML[ \t]+(%d+%.%d+)[ \t]*$")
+ if not v then
+ corrupt("bad %YAML directive", p)
+ end
+ elseif name == "TAG" then
+ local h, prefix = match(line, "^%%TAG[ \t]+(![%w%-]*!?)[ \t]+(%S+)[ \t]*$")
+ if not h then
+ corrupt("bad %TAG directive", p)
+ end
+ st.handles[h :: string] = prefix :: string
+ end
+ sawDirective = true
+ p = skip(s, e)
+ end
+ local explicit = false
+ if docMarker(s, p) and sub(s, p, p + 2) == "---" then
+ explicit = true
+ p += 3
+ elseif sawDirective then
+ corrupt("directives without '---'", p)
+ elseif docMarker(s, p) then -- "..."
+ if not endOfLine(s, p + 3) then
+ corrupt("text after '...'", p + 3)
+ end
+ p += 3
+ needEnd = false
+ continue
+ elseif needEnd then
+ corrupt("a second document needs '---'", p)
+ end
+ st.anchors = {}
+ local q = skip(s, p)
+ local value: any
+ if q > n or docMarker(s, q) then
+ value = st.null
+ p = q
+ else
+ if explicit and not find(sub(s, p, q), "\n", 1, true) then
+ -- content on the "---" line
+ local ok, _, q2 = pcall(properties, st, q)
+ local c = byte(s, q2)
+ if ok and c ~= 124 and c ~= 62 and not endOfLine(s, q2) and implicitKey(st, q2) ~= nil then
+ corrupt("a block mapping cannot start on the '---' line", q)
+ end
+ end
+ value, p = blockNode(st, -1, q, false, false)
+ local r = skip(s, p)
+ if r <= n and not docMarker(s, r) then
+ corrupt("unexpected content after the document", r)
+ end
+ p = r
+ end
+ table.insert(docs, value)
+ needEnd = true
+ if p <= n and docMarker(s, p) and sub(s, p, p + 2) == "..." then
+ if not endOfLine(s, p + 3) then
+ corrupt("text after '...'", p + 3)
+ end
+ p += 3
+ needEnd = false
+ elseif p <= n and docMarker(s, p) then
+ needEnd = false
+ end
+ end
+ return docs
+end
+
+-- run(text, opts) -> docs | nil, code, message, offset
+function Parse.run(text: string, opts: Options?): (any, any, any, any)
+ local o: Options = opts or {}
+ local s = text
+ if sub(s, 1, 3) == "\239\187\191" then
+ s = sub(s, 4)
+ end
+ if find(s, "\r", 1, true) then
+ s = string.gsub(string.gsub(s, "\r\n", "\n"), "\r", "\n")
+ end
+ local st: St = {
+ s = s,
+ n = #s,
+ anchors = {},
+ handles = {},
+ depth = 0,
+ maxDepth = o.maxDepth or 500,
+ aliasNodes = 0,
+ maxAlias = o.maxAliasNodes or 1e6,
+ sizes = setmetatable({}, { __mode = "k" }) :: any,
+ ignoreTags = o.tags == "ignore",
+ null = if o.null ~= nil then o.null else Types.null,
+ }
+ local ok, res = pcall(stream, st)
+ if ok then
+ return res, nil, nil, nil
+ end
+ if type(res) == "table" and res.yamlErr then
+ return nil, res.code, res.msg, res.at
+ end
+ local msg = tostring(res)
+ if string.find(msg, "stack overflow", 1, true) then
+ return nil, "LIMIT", "nested too deeply", 0
+ end
+ return nil, "CORRUPT", "internal error: " .. msg, 0
+end
+
+return Parse
diff --git a/src/Formats/data/yaml/init.luau b/src/Formats/data/yaml/init.luau
new file mode 100644
index 0000000..fd605b7
--- /dev/null
+++ b/src/Formats/data/yaml/init.luau
@@ -0,0 +1,77 @@
+--!strict
+-- data/yaml: YAML 1.2 (core schema), new code. Supports: block and flow styles, compact nested collections, plain /
+-- quoted / literal / folded scalars (indentation and chomping indicators), comments, anchors and aliases (decoded as
+-- shared references; an expansion-size limit guards against alias bombs), tags !!str !!int !!float !!bool !!null
+-- !!map !!seq !!binary (-> buffer) !!timestamp (-> Types.Date) and verbatim / %TAG forms, multi-document streams.
+-- Maps decode to Types.object (key order kept), null to Types.null. Writes block style (anchors for shared tables).
+-- Not supported (Err.UNSUPPORTED): complex keys "? ", collections as keys, other tags unless opts.tags = "ignore";
+-- merge keys "<<" stay ordinary keys; YAML 1.1 types (yes / no, sexagesimal, ...) are strings.
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Types = require("@formats/Types")
+local Parse = require("@formats/data/yaml/Parse")
+local Emit = require("@formats/data/yaml/Emit")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Yaml = {
+ name = "yaml",
+ category = "data",
+ extensions = { "yaml", "yml" },
+ mime = { "application/yaml", "application/x-yaml", "text/yaml" },
+ deps = { "core/Err", "core/Bytes", "Types" },
+ caps = { decode = true, encode = true, ordered = true, multiDocument = true, anchors = true },
+}
+
+export type DecodeOptions = Parse.Options
+export type EncodeOptions = Emit.Options
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Yaml.sniff(r: Bytes.Reader): number
+ local head = r:peek(256)
+ if string.find(head, "%z") then
+ return 0
+ end
+ if string.match(head, "^%%YAML ") then
+ return 0.9
+ end
+ if string.match(head, "^%-%-%-[ \r\n]") then
+ return 0.5
+ end
+ local line = string.match(head, "^[ \t\r\n]*([^\r\n]*)")
+ if line and (string.match(line, "^[%w_%-\"']+[%w_%- \"']*:[ ]") or string.match(line, "^[%w_%-]+:$") or string.match(line, "^%- ")) then
+ return 0.2
+ end
+ return 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+-- decode(r, opts?) -> the first document (Types.null when there is none) | every document (opts.all) | nil, Err
+function Yaml.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
+ local text = buffer.readstring(r.buf, r.base, r.limit - r.base)
+ local docs, code, msg, at = Parse.run(text, opts)
+ if not docs then
+ return nil, Err.new(code, msg, at)
+ end
+ if opts and opts.all then
+ return docs, nil
+ end
+ local first = docs[1]
+ if first == nil then
+ return if opts and opts.null ~= nil then opts.null else Types.null, nil
+ end
+ return first, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+-- encode(value, opts?) -> buffer | nil, Err (opts.all: value is an array of documents)
+function Yaml.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
+ local s, err = Emit.encode(value, opts)
+ if not s then
+ return nil, Err.new(Err.ARG, err or "cannot encode")
+ end
+ return buffer.fromstring(s), nil
+end
+
+return Yaml
diff --git a/src/Formats/font/bmfont/Parse.luau b/src/Formats/font/bmfont/Parse.luau
new file mode 100644
index 0000000..13c8314
--- /dev/null
+++ b/src/Formats/font/bmfont/Parse.luau
@@ -0,0 +1,457 @@
+--!strict
+-- font/bmfont/Parse: the three AngelCode BMFont descriptor encodings (text, XML, binary version 3) to and from one
+-- description table { info, common, pages, chars, kernings }. Written from the BMFont documentation
+-- (angelcode.com/products/bmfont/doc/file_format.html). The XML reader only scans elements and attributes (the
+-- descriptor has no nesting that matters, no text content).
+--
+-- Never throws on bad input: parse functions return nil, message.
+local Bytes = require("@formats/core/Bytes")
+
+local Parse = {}
+
+export type Char = {
+ id: number,
+ x: number,
+ y: number,
+ width: number,
+ height: number,
+ xoffset: number,
+ yoffset: number,
+ xadvance: number,
+ page: number,
+ chnl: number,
+}
+export type Desc = {
+ info: { [string]: any }, -- face, size, bold, italic, charset, unicode, stretchH, smooth, aa, padding {4}, spacing {2}, outline
+ common: { [string]: any }, -- lineHeight, base, scaleW, scaleH, pages, packed, alphaChnl, redChnl, greenChnl, blueChnl
+ pages: { string }, -- file names, by page id (1-based: page id 0 is pages[1])
+ chars: { Char },
+ kernings: { { number } }, -- { first, second, amount }
+}
+
+local LIMIT = 1000000 -- chars / kernings
+
+local INFO_NUM = { "size", "bold", "italic", "unicode", "stretchH", "smooth", "aa", "outline" }
+local COMMON_NUM = { "lineHeight", "base", "scaleW", "scaleH", "pages", "packed", "alphaChnl", "redChnl", "greenChnl", "blueChnl" }
+local CHAR_NUM = { "id", "x", "y", "width", "height", "xoffset", "yoffset", "xadvance", "page", "chnl" }
+
+local function list(s: string?, n: number): { number }
+ local out = table.create(n, 0)
+ if s then
+ local i = 1
+ for v in string.gmatch(s, "-?%d+") do
+ if i > n then
+ break
+ end
+ out[i] = tonumber(v) or 0
+ i += 1
+ end
+ end
+ return out
+end
+
+local function new(): Desc
+ return { info = {}, common = {}, pages = {}, chars = {}, kernings = {} }
+end
+
+-- one tag's attributes (already split into key -> string) into the description
+local function apply(d: Desc, tag: string, a: { [string]: string }): string?
+ if tag == "info" then
+ d.info.face = a.face or ""
+ d.info.charset = a.charset or ""
+ for _, k in INFO_NUM do
+ d.info[k] = tonumber(a[k]) or 0
+ end
+ d.info.padding = list(a.padding, 4)
+ d.info.spacing = list(a.spacing, 2)
+ elseif tag == "common" then
+ for _, k in COMMON_NUM do
+ d.common[k] = tonumber(a[k]) or 0
+ end
+ elseif tag == "page" then
+ local id = tonumber(a.id)
+ if not id or id < 0 or id > 4096 or id % 1 ~= 0 then
+ return "bad page id"
+ end
+ d.pages[id + 1] = a.file or ""
+ elseif tag == "char" then
+ if #d.chars >= LIMIT then
+ return "too many chars"
+ end
+ local c: any = {}
+ for _, k in CHAR_NUM do
+ c[k] = tonumber(a[k]) or 0
+ end
+ table.insert(d.chars, c)
+ elseif tag == "kerning" then
+ if #d.kernings >= LIMIT then
+ return "too many kerning pairs"
+ end
+ table.insert(d.kernings, { tonumber(a.first) or 0, tonumber(a.second) or 0, tonumber(a.amount) or 0 })
+ end
+ return nil
+end
+
+local function fill(d: Desc)
+ for i = 1, #d.pages do
+ d.pages[i] = d.pages[i] or ""
+ end
+end
+
+-- ------------------------------------------------------------------------------------------------ text
+function Parse.text(s: string): (Desc?, string?)
+ local d = new()
+ for line in string.gmatch(s, "[^\r\n]+") do
+ local tag, rest = string.match(line, "^%s*(%a+)(.*)$")
+ if tag then
+ local a: { [string]: string } = {}
+ -- key=value, key="quoted value"
+ local i = 1
+ while i <= #rest do
+ local k, q, e = string.match(rest, '^%s*([%w_]+)="([^"]*)"()', i)
+ if k then
+ a[k] = q
+ i = e
+ else
+ local k2, v2, e2 = string.match(rest, "^%s*([%w_]+)=(%S*)()", i)
+ if not k2 then
+ break
+ end
+ a[k2] = v2
+ i = e2
+ end
+ end
+ local err = apply(d, tag, a)
+ if err then
+ return nil, err
+ end
+ end
+ end
+ if not d.common.lineHeight then
+ return nil, "no common line"
+ end
+ fill(d)
+ return d, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ XML
+local ENTITIES = { quot = '"', amp = "&", lt = "<", gt = ">", apos = "'" }
+local function unescape(s: string): string
+ return (
+ string.gsub(s, "&(#?x?%w+);", function(e: string): string?
+ if ENTITIES[e] then
+ return ENTITIES[e]
+ end
+ local n = if string.sub(e, 1, 2) == "#x" then tonumber(string.sub(e, 3), 16) elseif string.sub(e, 1, 1) == "#" then tonumber(string.sub(e, 2)) else nil
+ if n and n >= 0 and n <= 0x10FFFF then
+ return utf8.char(n)
+ end
+ return nil
+ end)
+ )
+end
+
+function Parse.xml(s: string): (Desc?, string?)
+ local d = new()
+ local seenFont = false
+ for tag, attrs in string.gmatch(s, "<(%a+)([^>]*)>") do
+ if tag == "font" then
+ seenFont = true
+ end
+ local a: { [string]: string } = {}
+ for k, q, v in string.gmatch(attrs, "([%w_]+)%s*=%s*([\"'])(.-)%2") do
+ a[k] = unescape(v)
+ local _ = q
+ end
+ local err = apply(d, tag, a)
+ if err then
+ return nil, err
+ end
+ end
+ if not seenFont or not d.common.lineHeight then
+ return nil, "not a BMFont XML descriptor"
+ end
+ fill(d)
+ return d, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ binary
+function Parse.binary(r: Bytes.Reader): (Desc?, string?)
+ if not r:match("BMF") then
+ return nil, "bad signature"
+ end
+ local version = r:u8()
+ if version ~= 3 then
+ return nil, "unsupported binary version " .. version
+ end
+ local d = new()
+ while not r:eof() do
+ local kind = r:u8()
+ local size = r:u32le()
+ if r.err then
+ return nil, "truncated block header"
+ end
+ local b = r:slice(size)
+ if r.err then
+ return nil, "block past the end"
+ end
+ if kind == 1 then
+ d.info.size = b:i16le()
+ local bits = b:u8()
+ d.info.smooth = bit32.band(bits, 0x80) ~= 0 and 1 or 0
+ d.info.unicode = bit32.band(bits, 0x40) ~= 0 and 1 or 0
+ d.info.italic = bit32.band(bits, 0x20) ~= 0 and 1 or 0
+ d.info.bold = bit32.band(bits, 0x10) ~= 0 and 1 or 0
+ d.info.fixedHeight = bit32.band(bits, 0x08) ~= 0 and 1 or 0
+ d.info.charsetId = b:u8()
+ d.info.charset = ""
+ d.info.stretchH = b:u16le()
+ d.info.aa = b:u8()
+ d.info.padding = { b:u8(), b:u8(), b:u8(), b:u8() }
+ d.info.spacing = { b:u8(), b:u8() }
+ d.info.outline = b:u8()
+ d.info.face = b:cstring()
+ elseif kind == 2 then
+ d.common.lineHeight = b:u16le()
+ d.common.base = b:u16le()
+ d.common.scaleW = b:u16le()
+ d.common.scaleH = b:u16le()
+ d.common.pages = b:u16le()
+ d.common.packed = if bit32.band(b:u8(), 1) ~= 0 then 1 else 0
+ d.common.alphaChnl = b:u8()
+ d.common.redChnl = b:u8()
+ d.common.greenChnl = b:u8()
+ d.common.blueChnl = b:u8()
+ elseif kind == 3 then
+ while not b:eof() and #d.pages < 4096 do
+ table.insert(d.pages, b:cstring())
+ end
+ elseif kind == 4 then
+ local n = size // 20
+ if n > LIMIT then
+ return nil, "too many chars"
+ end
+ for _ = 1, n do
+ table.insert(d.chars, {
+ id = b:u32le(),
+ x = b:u16le(),
+ y = b:u16le(),
+ width = b:u16le(),
+ height = b:u16le(),
+ xoffset = b:i16le(),
+ yoffset = b:i16le(),
+ xadvance = b:i16le(),
+ page = b:u8(),
+ chnl = b:u8(),
+ })
+ end
+ elseif kind == 5 then
+ local n = size // 10
+ if n > LIMIT then
+ return nil, "too many kerning pairs"
+ end
+ for _ = 1, n do
+ table.insert(d.kernings, { b:u32le(), b:u32le(), b:i16le() })
+ end
+ end
+ if b.err then
+ return nil, "truncated block " .. kind
+ end
+ end
+ if not d.common.lineHeight then
+ return nil, "no common block"
+ end
+ return d, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ writers
+local function num(v: any): string
+ return string.format("%d", math.floor(tonumber(v) or 0))
+end
+
+local function textLines(d: Desc, quote: (string) -> string): { { any } }
+ local i, c = d.info, d.common
+ local pad, sp = i.padding or { 0, 0, 0, 0 }, i.spacing or { 0, 0 }
+ local lines: { { any } } = {
+ {
+ "info",
+ {
+ { "face", quote(i.face or "") },
+ { "size", num(i.size) },
+ { "bold", num(i.bold) },
+ { "italic", num(i.italic) },
+ { "charset", quote(i.charset or "") },
+ { "unicode", num(i.unicode) },
+ { "stretchH", num(i.stretchH or 100) },
+ { "smooth", num(i.smooth) },
+ { "aa", num(i.aa) },
+ { "padding", table.concat({ num(pad[1]), num(pad[2]), num(pad[3]), num(pad[4]) }, ",") },
+ { "spacing", num(sp[1]) .. "," .. num(sp[2]) },
+ { "outline", num(i.outline) },
+ },
+ },
+ }
+ local cf = {}
+ for _, k in COMMON_NUM do
+ table.insert(cf, { k, num(c[k]) })
+ end
+ table.insert(lines, { "common", cf })
+ return lines
+end
+
+function Parse.writeText(d: Desc): string
+ local out = {}
+ local function q(s: string): string
+ return '"' .. string.gsub(s, '"', "") .. '"'
+ end
+ for _, l in textLines(d, q) do
+ local parts = { l[1] }
+ for _, kv in l[2] do
+ table.insert(parts, kv[1] .. "=" .. kv[2])
+ end
+ table.insert(out, table.concat(parts, " "))
+ end
+ for id, file in d.pages do
+ table.insert(out, string.format('page id=%d file="%s"', id - 1, (string.gsub(file, '"', ""))))
+ end
+ table.insert(out, "chars count=" .. #d.chars)
+ for _, c in d.chars do
+ local parts = { "char" }
+ for _, k in CHAR_NUM do
+ table.insert(parts, k .. "=" .. num((c :: any)[k]))
+ end
+ table.insert(out, table.concat(parts, " "))
+ end
+ if #d.kernings > 0 then
+ table.insert(out, "kernings count=" .. #d.kernings)
+ for _, k in d.kernings do
+ table.insert(out, string.format("kerning first=%s second=%s amount=%s", num(k[1]), num(k[2]), num(k[3])))
+ end
+ end
+ return table.concat(out, "\n") .. "\n"
+end
+
+local function esc(s: string): string
+ return (string.gsub(s, '[&<>"]', { ["&"] = "&", ["<"] = "<", [">"] = ">", ['"'] = """ }))
+end
+
+function Parse.writeXml(d: Desc): string
+ local out = { '', "" }
+ for _, l in textLines(d, function(s: string): string
+ return s
+ end) do
+ local parts = { " <" .. l[1] }
+ for _, kv in l[2] do
+ table.insert(parts, kv[1] .. '="' .. esc(kv[2]) .. '"')
+ end
+ table.insert(out, table.concat(parts, " ") .. "/>")
+ end
+ table.insert(out, " ")
+ for id, file in d.pages do
+ table.insert(out, string.format(' ', id - 1, esc(file)))
+ end
+ table.insert(out, " ")
+ table.insert(out, string.format(' ', #d.chars))
+ for _, c in d.chars do
+ local parts = { " ")
+ end
+ table.insert(out, " ")
+ if #d.kernings > 0 then
+ table.insert(out, string.format(' ', #d.kernings))
+ for _, k in d.kernings do
+ table.insert(out, string.format(' ', num(k[1]), num(k[2]), num(k[3])))
+ end
+ table.insert(out, " ")
+ end
+ table.insert(out, "")
+ return table.concat(out, "\n") .. "\n"
+end
+
+function Parse.writeBinary(d: Desc): buffer
+ local w = Bytes.writer(64 + #d.chars * 20 + #d.kernings * 10)
+ w:string("BMF")
+ w:u8(3)
+ local i, c = d.info, d.common
+ local face = i.face or ""
+ w:u8(1)
+ w:u32le(14 + #face + 1)
+ w:u16le((tonumber(i.size) or 0) % 65536)
+ local bits = 0
+ if (tonumber(i.smooth) or 0) ~= 0 then
+ bits += 0x80
+ end
+ if (tonumber(i.unicode) or 0) ~= 0 then
+ bits += 0x40
+ end
+ if (tonumber(i.italic) or 0) ~= 0 then
+ bits += 0x20
+ end
+ if (tonumber(i.bold) or 0) ~= 0 then
+ bits += 0x10
+ end
+ if (tonumber(i.fixedHeight) or 0) ~= 0 then
+ bits += 0x08
+ end
+ w:u8(bits)
+ w:u8(tonumber(i.charsetId) or 0)
+ w:u16le(tonumber(i.stretchH) or 100)
+ w:u8(tonumber(i.aa) or 1)
+ local pad, sp = i.padding or { 0, 0, 0, 0 }, i.spacing or { 0, 0 }
+ for k = 1, 4 do
+ w:u8(pad[k] or 0)
+ end
+ w:u8(sp[1] or 0)
+ w:u8(sp[2] or 0)
+ w:u8(tonumber(i.outline) or 0)
+ w:cstring(face)
+ w:u8(2)
+ w:u32le(15)
+ for _, k in { "lineHeight", "base", "scaleW", "scaleH", "pages" } do
+ w:u16le((tonumber(c[k]) or 0) % 65536)
+ end
+ w:u8(if (tonumber(c.packed) or 0) ~= 0 then 1 else 0)
+ for _, k in { "alphaChnl", "redChnl", "greenChnl", "blueChnl" } do
+ w:u8(tonumber(c[k]) or 0)
+ end
+ if #d.pages > 0 then
+ local len = 0
+ for _, p in d.pages do
+ len += #p + 1
+ end
+ w:u8(3)
+ w:u32le(len)
+ for _, p in d.pages do
+ w:cstring(p)
+ end
+ end
+ w:u8(4)
+ w:u32le(#d.chars * 20)
+ for _, ch in d.chars do
+ w:u32le(ch.id)
+ w:u16le(ch.x)
+ w:u16le(ch.y)
+ w:u16le(ch.width)
+ w:u16le(ch.height)
+ w:u16le(ch.xoffset % 65536)
+ w:u16le(ch.yoffset % 65536)
+ w:u16le(ch.xadvance % 65536)
+ w:u8(ch.page)
+ w:u8(ch.chnl)
+ end
+ if #d.kernings > 0 then
+ w:u8(5)
+ w:u32le(#d.kernings * 10)
+ for _, k in d.kernings do
+ w:u32le(k[1])
+ w:u32le(k[2])
+ w:u16le(k[3] % 65536)
+ end
+ end
+ return w:finish()
+end
+
+return Parse
diff --git a/src/Formats/font/bmfont/init.luau b/src/Formats/font/bmfont/init.luau
new file mode 100644
index 0000000..e40aa7e
--- /dev/null
+++ b/src/Formats/font/bmfont/init.luau
@@ -0,0 +1,408 @@
+--!strict
+-- font/bmfont: AngelCode BMFont descriptors (.fnt) in all three encodings: text, XML and binary (version 3), read and
+-- written. Decodes to the standard Font (a bitmap font: glyphIndex / advance / kern work, outline is nil, rasterize
+-- crops the glyph from its page as alpha8). Pages are image files named by the descriptor (meta.pageFiles); they are
+-- loaded lazily through font:loadPages(loader) or the loader the api attaches (opts.loadPage(file) -> Image, or the
+-- files next to the .fnt on hosts with a file system). Bmfont.bake(font, opts) renders any outline Font (ttf / otf /
+-- woff) into a packed bitmap font with its pages. Written from the BMFont documentation.
+-- Not supported: packed multi-channel glyphs (chnl other than one channel or all: read as alpha).
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Types = require("@formats/Types")
+local Parse = require("@formats/font/bmfont/Parse")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Bmfont = {
+ name = "bmfont",
+ category = "font",
+ extensions = { "fnt" },
+ mime = { "application/x-bmfont" },
+ deps = { "core/Err", "core/Bytes", "Types" },
+ caps = { decode = true, encode = true, bitmap = true, variants = { "text", "xml", "binary" } },
+}
+
+export type DecodeOptions = {
+ pages: { Types.Image }?, -- the page images, if the caller has them already (page id 0 first)
+ loadPage: ((file: string, page: number) -> any)?, -- loader for lazy pages: file -> Image (the api passes one)
+}
+export type EncodeOptions = {
+ variant: ("text" | "xml" | "binary")?, -- default: the variant it was read from, else "text"
+ px: number?, -- fonts without a BMFont description are baked first (see bake)
+ chars: (string | { number })?,
+}
+export type BakeOptions = {
+ px: number?, -- pixels per em (default 32)
+ chars: (string | { number })?, -- code points to include (default printable ASCII 32..126)
+ pageSize: number?, -- page width = height (default: the smallest power of two that fits, up to 4096)
+ padding: number?, -- empty pixels around each glyph (default 1)
+ file: string?, -- page file name prefix (default "font"): pages are _.png
+}
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Bmfont.sniff(r: Bytes.Reader): number
+ local head = r:peek(64)
+ if string.sub(head, 1, 4) == "BMF\3" then
+ return 1
+ end
+ if string.match(head, "^info%s+face=") or string.match(head, "^info%s+") and string.find(head, "size=", 1, true) then
+ return 0.9
+ end
+ if string.find(head, "", 1, true) or (string.find(head, "", 1, true)) then
+ return if string.find(r:peek(512), " true | nil, Err: loader(file, pageIndex) -> Image (rgba8) | nil
+function Face.loadPages(self: any, loader: any?): (boolean?, Err.Err?)
+ local load = loader or self.meta.pageLoader
+ if type(load) ~= "function" then
+ return nil, Err.new(Err.ARG, "no page loader (pass font:loadPages(function(file) return image end))")
+ end
+ local pages = {}
+ for i, file in self.meta.pageFiles do
+ local ok, img, err = pcall(load, file, i - 1)
+ if not ok or type(img) ~= "table" or type(img.pixels) ~= "buffer" then
+ return nil, if Err.is(err) then err else Err.new(Err.IO, "page " .. file .. ": " .. tostring(if ok then err else img))
+ end
+ pages[i] = img
+ end
+ self.pages = pages
+ return true
+end
+
+local CHANNEL = { [1] = 2, [2] = 1, [4] = 0, [8] = 3 } -- chnl bit -> byte in rgba8
+
+-- rasterize(g, px?) -> alpha8 Image cropped from the glyph's page (px is ignored: bitmap fonts have one size;
+-- meta.scale = px / size tells the caller how much to scale). nil when the pages are not loaded / available.
+function Face.rasterize(self: any, g: number, px: number?): Types.Image?
+ local c = self._chars[g]
+ if not c then
+ return nil
+ end
+ if not self.pages and self.meta.pageLoader then
+ self:loadPages()
+ end
+ local page = self.pages and self.pages[c.page + 1]
+ local img = Types.Image.new(c.width, c.height, "alpha8")
+ img.meta.left = c.xoffset
+ img.meta.top = (self.meta.base or 0) - c.yoffset
+ img.meta.advance = c.xadvance
+ img.meta.glyph = g
+ img.meta.scale = if type(px) == "number" and self.unitsPerEm > 0 then px / self.unitsPerEm else 1
+ if not page then
+ return nil
+ end
+ local pw, ph = page.width, page.height
+ local bpp = Types.Image.bpp(page.format) or 4
+ local ch = if page.format == "rgba8" then CHANNEL[c.chnl] or 3 else 0
+ if page.format == "graya8" then
+ ch = 1
+ end
+ for y = 0, c.height - 1 do
+ local sy = c.y + y
+ for x = 0, c.width - 1 do
+ local sx = c.x + x
+ if sx >= 0 and sy >= 0 and sx < pw and sy < ph then
+ buffer.writeu8(img.pixels, y * c.width + x, buffer.readu8(page.pixels, (sy * pw + sx) * bpp + math.min(ch, bpp - 1)))
+ end
+ end
+ end
+ return img
+end
+
+-- the Font value of a description
+local function face(d: Parse.Desc, variant: string): any
+ local f: any = setmetatable({
+ kind = "font",
+ info = {
+ family = d.info.face,
+ style = if (d.info.bold or 0) ~= 0 and (d.info.italic or 0) ~= 0 then "Bold Italic" elseif (d.info.bold or 0) ~= 0 then "Bold" elseif (d.info.italic or 0) ~= 0 then "Italic" else "Regular",
+ fullName = d.info.face,
+ },
+ unitsPerEm = math.abs(d.info.size or 0),
+ ascent = d.common.base or 0,
+ descent = (d.common.base or 0) - (d.common.lineHeight or 0),
+ lineGap = 0,
+ numGlyphs = #d.chars + 1,
+ pages = nil,
+ meta = {
+ bmfont = d,
+ variant = variant,
+ pageFiles = d.pages,
+ lineHeight = d.common.lineHeight,
+ base = d.common.base,
+ source = { format = "bmfont", variant = variant },
+ },
+ _chars = {},
+ _index = {},
+ _kern = {},
+ }, Face)
+ for i, c in d.chars do
+ f._chars[i] = c
+ if f._index[c.id] == nil then
+ f._index[c.id] = i
+ end
+ end
+ for _, k in d.kernings do
+ f._kern[k[1] * 2097152 + k[2]] = k[3]
+ end
+ return f
+end
+
+function Bmfont.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
+ local d, err, variant
+ if r:peek(3) == "BMF" then
+ d, err = Parse.binary(r:sub(0))
+ variant = "binary"
+ else
+ local s = r:peek(r:size())
+ if string.find(string.sub(s, 1, 512), " 255 or c.chnl < 0 or c.chnl > 255 then
+ return false
+ end
+ end
+ for _, k in d.kernings do
+ if type(k) ~= "table" or type(k[1]) ~= "number" or type(k[2]) ~= "number" or type(k[3]) ~= "number" then
+ return false
+ end
+ end
+ for _, p in d.pages do
+ if type(p) ~= "string" then
+ return false
+ end
+ end
+ return true
+end
+
+function Bmfont.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?)
+ if type(font) ~= "table" or font.kind ~= "font" then
+ return nil, Err.new(Err.ARG, "expected a Font")
+ end
+ local d = type(font.meta) == "table" and font.meta.bmfont or nil
+ if d == nil then
+ local baked, err = Bmfont.bake(font, { px = opts and opts.px, chars = opts and opts.chars })
+ if not baked then
+ return nil, err
+ end
+ d = baked.meta.bmfont
+ end
+ if not validDesc(d) then
+ return nil, Err.new(Err.ARG, "bad BMFont description in font.meta.bmfont")
+ end
+ local variant = (opts and opts.variant) or (font.meta and font.meta.variant) or "text"
+ if variant == "text" then
+ return buffer.fromstring(Parse.writeText(d)), nil
+ elseif variant == "xml" then
+ return buffer.fromstring(Parse.writeXml(d)), nil
+ elseif variant == "binary" then
+ return Parse.writeBinary(d), nil
+ end
+ return nil, Err.new(Err.ARG, "variant must be text, xml or binary")
+end
+
+-- ------------------------------------------------------------------------------------------------ extras
+local function codepoints(chars: any): { number }
+ local out = {}
+ if type(chars) == "string" then
+ for _, c in utf8.codes(chars) do
+ table.insert(out, c)
+ end
+ elseif type(chars) == "table" then
+ for _, c in chars do
+ if type(c) == "number" then
+ table.insert(out, c)
+ end
+ end
+ else
+ for c = 32, 126 do
+ table.insert(out, c)
+ end
+ end
+ return out
+end
+
+-- bake(font, opts?) -> a BMFont Font (pages: rgba8 Images, white with the coverage as alpha) | nil, Err. Glyphs are
+-- rasterized with font:rasterize and packed in rows (tallest first); kerning pairs between the baked characters are
+-- kept (rounded to pixels).
+function Bmfont.bake(font: any, opts: BakeOptions?): (any, Err.Err?)
+ if type(font) ~= "table" or type(font.rasterize) ~= "function" or type(font.glyphIndex) ~= "function" then
+ return nil, Err.new(Err.ARG, "bake: expected an outline Font")
+ end
+ local o = opts or {}
+ local px = if type(o.px) == "number" and o.px > 0 and o.px <= 1024 then o.px else 32
+ local pad = if type(o.padding) == "number" and o.padding >= 0 then math.floor(o.padding) else 1
+ local scale = px / font.unitsPerEm
+ local glyphs = {}
+ local area = 0
+ local seen = {}
+ for _, cp in codepoints(o.chars) do
+ local g = font:glyphIndex(cp)
+ if (g ~= 0 or cp == 0) and not seen[cp] then
+ seen[cp] = true
+ local img = font:rasterize(g, px)
+ if img then
+ table.insert(glyphs, { cp = cp, g = g, img = img })
+ area += (img.width + pad) * (img.height + pad)
+ end
+ end
+ end
+ local size = o.pageSize
+ if type(size) ~= "number" then
+ size = 64
+ while size * size < area * 1.3 and size < 4096 do
+ size *= 2
+ end
+ end
+ local order = table.clone(glyphs)
+ table.sort(order, function(a: any, b: any): boolean
+ if a.img.height ~= b.img.height then
+ return a.img.height > b.img.height
+ end
+ return a.cp < b.cp
+ end)
+ local ascent = math.ceil(font.ascent * scale)
+ local lineHeight = math.ceil((font.ascent - font.descent + (font.lineGap or 0)) * scale)
+ local prefix = o.file or "font"
+ local d: Parse.Desc = {
+ info = {
+ face = font.info and font.info.family or "font",
+ size = px,
+ bold = 0,
+ italic = 0,
+ charset = "",
+ unicode = 1,
+ stretchH = 100,
+ smooth = 1,
+ aa = 1,
+ padding = { 0, 0, 0, 0 },
+ spacing = { pad, pad },
+ outline = 0,
+ },
+ common = { lineHeight = lineHeight, base = ascent, scaleW = size, scaleH = size, pages = 0, packed = 0, alphaChnl = 0, redChnl = 4, greenChnl = 4, blueChnl = 4 },
+ pages = {},
+ chars = {},
+ kernings = {},
+ }
+ local pages: { Types.Image } = {}
+ local page: Types.Image? = nil
+ local x, y, rowH = pad, pad, 0
+ local placed: { [number]: Parse.Char } = {}
+ for _, gl in order do
+ local w, h = gl.img.width, gl.img.height
+ if w + 2 * pad > size or h + 2 * pad > size then
+ return nil, Err.new(Err.LIMIT, "bake: glyph larger than the page")
+ end
+ if x + w + pad > size then
+ x, y, rowH = pad, y + rowH + pad, 0
+ end
+ if not page or y + h + pad > size then
+ page = Types.Image.new(size, size)
+ table.insert(pages, page :: Types.Image)
+ table.insert(d.pages, string.format("%s_%d.png", prefix, #pages - 1))
+ x, y, rowH = pad, pad, 0
+ end
+ local pg = page :: Types.Image
+ for yy = 0, h - 1 do
+ for xx = 0, w - 1 do
+ local a = buffer.readu8(gl.img.pixels, yy * w + xx)
+ buffer.writeu32(pg.pixels, ((y + yy) * size + x + xx) * 4, 0x00FFFFFF + a * 16777216)
+ end
+ end
+ local c: Parse.Char = {
+ id = gl.cp,
+ x = x,
+ y = y,
+ width = w,
+ height = h,
+ xoffset = gl.img.meta.left,
+ yoffset = ascent - gl.img.meta.top,
+ xadvance = math.floor(gl.img.meta.advance + 0.5),
+ page = #pages - 1,
+ chnl = 15,
+ }
+ placed[gl.cp] = c
+ x += w + pad
+ rowH = math.max(rowH, h)
+ end
+ for _, gl in glyphs do
+ table.insert(d.chars, placed[gl.cp])
+ end
+ d.common.pages = #pages
+ if type(font.kern) == "function" then
+ for _, a in glyphs do
+ for _, b in glyphs do
+ local k = font:kern(a.g, b.g)
+ if k ~= 0 then
+ local v = math.floor(k * scale + 0.5)
+ if v ~= 0 then
+ table.insert(d.kernings, { a.cp, b.cp, v })
+ end
+ end
+ end
+ end
+ end
+ local f = face(d, "text")
+ f.pages = pages
+ return f, nil
+end
+
+return Bmfont
diff --git a/src/Formats/font/ttf/init.luau b/src/Formats/font/ttf/init.luau
new file mode 100644
index 0000000..2e81f06
--- /dev/null
+++ b/src/Formats/font/ttf/init.luau
@@ -0,0 +1,52 @@
+--!strict
+-- font/ttf: TrueType and OpenType fonts (.ttf, .otf with CFF outlines) and collections (.ttc / .otc), read into the
+-- standard Font (Types.Font) by codecs/TrueType: metrics, names, cmap, outlines (glyf or CFF), kerning ('kern' table,
+-- GPOS pair kerning) and rasterize(glyph, px) through codecs/Raster. Ported from stb_truetype 1.26 (public domain /
+-- MIT) via imgui-luau's imstb_truetype.lua; see codecs/TrueType. opts.index picks the font of a collection.
+-- Not supported: hinting, variable fonts, bitmap / colour glyphs, GSUB, writing.
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local TrueType = require("@formats/codecs/TrueType")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Ttf = {
+ name = "ttf",
+ category = "font",
+ extensions = { "ttf", "otf", "ttc", "otc" },
+ mime = { "font/ttf", "font/otf", "font/collection" },
+ deps = { "core/Err", "core/Bytes", "codecs/TrueType" },
+ caps = { decode = true, encode = false, outlines = { "truetype", "cff" }, collection = true, kerning = true },
+}
+
+export type DecodeOptions = {
+ index: number?, -- the font of a collection (default 0)
+}
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Ttf.sniff(r: Bytes.Reader): number
+ local m = r:peek(4)
+ if m == "\0\1\0\0" or m == "OTTO" or m == "ttcf" or m == "true" then
+ return 0.9
+ end
+ return 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+function Ttf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
+ local font, err = TrueType.font(r.buf, r.base, r.limit - r.base, opts)
+ if not font then
+ return nil, err
+ end
+ font.meta.source = { format = "ttf", outlines = font.meta.outlines, sfnt = font.meta.sfnt }
+ return font, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ extras
+-- count(r) -> the number of fonts in the file (1 unless a collection)
+function Ttf.count(r: Bytes.Reader): number
+ return TrueType.count(r.buf, r.base)
+end
+
+return Ttf
diff --git a/src/Formats/font/woff/init.luau b/src/Formats/font/woff/init.luau
new file mode 100644
index 0000000..6b1bb91
--- /dev/null
+++ b/src/Formats/font/woff/init.luau
@@ -0,0 +1,132 @@
+--!strict
+-- font/woff: WOFF 1.0 (W3C Recommendation, 2012): an sfnt font whose tables are zlib-compressed one by one. Decoding
+-- rebuilds the sfnt and reads it through codecs/TrueType (TrueType or CFF outlines, see font/ttf); the extended
+-- metadata XML is kept in meta.woffMetadata. Written from the spec. Not supported: writing.
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Deflate = require("@formats/codecs/Deflate")
+local TrueType = require("@formats/codecs/TrueType")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Woff = {
+ name = "woff",
+ category = "font",
+ extensions = { "woff" },
+ mime = { "font/woff" },
+ deps = { "core/Err", "core/Bytes", "codecs/Deflate", "codecs/TrueType" },
+ caps = { decode = true, encode = false, outlines = { "truetype", "cff" } },
+}
+
+export type DecodeOptions = {
+ maxBytes: number?, -- refuse a font whose sfnt is bigger (default 2^28)
+}
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Woff.sniff(r: Bytes.Reader): number
+ return if r:peek(4) == "wOFF" then 1 else 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+-- sfnt(r, opts?) -> the rebuilt sfnt font file (a buffer) | nil, Err
+function Woff.sfnt(r: Bytes.Reader, opts: DecodeOptions?): (buffer?, Err.Err?, string?)
+ local maxBytes = (opts and opts.maxBytes) or 2 ^ 28
+ local base = r.base
+ if not r:match("wOFF") then
+ return nil, Err.new(Err.CORRUPT, "bad signature", base)
+ end
+ local flavor = r:string(4)
+ local length = r:u32be()
+ local numTables = r:u16be()
+ r:skip(2)
+ local total = r:u32be()
+ r:skip(4)
+ local metaOffset, metaLength, metaOrig = r:u32be(), r:u32be(), r:u32be()
+ r:skip(8)
+ if r.err then
+ return nil, r.err
+ end
+ if flavor == "ttcf" then
+ return nil, Err.new(Err.UNSUPPORTED, "font collections in WOFF", base + 4)
+ end
+ if length > r:size() then
+ return nil, Err.new(Err.TRUNCATED, string.format("file is %d bytes, header says %d", r:size(), length), base + 8)
+ end
+ if numTables == 0 or total > maxBytes or total < 12 + 16 * numTables then
+ return nil, Err.new(if total > maxBytes then Err.LIMIT else Err.CORRUPT, "bad table count or sfnt size", base + 12)
+ end
+ local dir = {}
+ for i = 1, numTables do
+ local e = { tag = r:string(4), offset = r:u32be(), comp = r:u32be(), orig = r:u32be(), sum = r:u32be() }
+ dir[i] = e
+ end
+ if r.err then
+ return nil, r.err
+ end
+ local out = buffer.create(total)
+ local w = Bytes.writer(12)
+ w:string(flavor)
+ w:u16be(numTables)
+ local es, sel = 1, 0
+ while es * 2 <= numTables do
+ es *= 2
+ sel += 1
+ end
+ w:u16be(es * 16)
+ w:u16be(sel)
+ w:u16be(numTables * 16 - es * 16)
+ buffer.copy(out, 0, w.buf, 0, 12)
+ local p = 12 + 16 * numTables
+ for i, e in dir do
+ if e.offset + e.comp > r:size() or e.comp > e.orig then
+ return nil, Err.new(Err.CORRUPT, "table " .. e.tag .. " out of range", base + 44 + (i - 1) * 20)
+ end
+ if p + e.orig > total then
+ return nil, Err.new(Err.CORRUPT, "tables larger than totalSfntSize", base + 16)
+ end
+ local d = 12 + (i - 1) * 16
+ buffer.writestring(out, d, e.tag)
+ buffer.writeu32(out, d + 4, bit32.byteswap(e.sum))
+ buffer.writeu32(out, d + 8, bit32.byteswap(p))
+ buffer.writeu32(out, d + 12, bit32.byteswap(e.orig))
+ if e.comp < e.orig then
+ local t, err = Deflate.zlib(r.buf, base + e.offset, e.comp, e.orig)
+ if not t then
+ return nil, Err.new((err :: any).code, "table " .. e.tag .. ": " .. (err :: any).message, base + e.offset)
+ end
+ buffer.copy(out, p, t, 0, e.orig)
+ else
+ buffer.copy(out, p, r.buf, base + e.offset, e.orig)
+ end
+ p += e.orig
+ p = (p + 3) // 4 * 4
+ if p > total then
+ p = total
+ end
+ end
+ local xml = nil
+ if metaLength > 0 and metaOffset + metaLength <= r:size() then
+ local m = Deflate.zlib(r.buf, base + metaOffset, metaLength, metaOrig)
+ if m then
+ xml = buffer.tostring(m)
+ end
+ end
+ return out, nil, xml
+end
+
+function Woff.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
+ local sfnt, err, xml = Woff.sfnt(r, opts)
+ if not sfnt then
+ return nil, err
+ end
+ local font, ferr = TrueType.font(sfnt)
+ if not font then
+ return nil, ferr
+ end
+ font.meta.woffMetadata = xml
+ font.meta.source = { format = "woff", outlines = font.meta.outlines }
+ return font, nil
+end
+
+return Woff
diff --git a/src/Formats/font/woff2/Rebuild.luau b/src/Formats/font/woff2/Rebuild.luau
new file mode 100644
index 0000000..7cbf3b3
--- /dev/null
+++ b/src/Formats/font/woff2/Rebuild.luau
@@ -0,0 +1,541 @@
+--!strict
+-- font/woff2/Rebuild: rebuilds the sfnt of a WOFF2 file (W3C WOFF2 Recommendation, 2024 edition): the table
+-- directory, the Brotli stream, the transformed glyf / loca tables (section 5: nContour, nPoints, flag, glyph,
+-- composite, bbox and instruction streams, triplet-encoded coordinates, the overlap bitmap) and the transformed hmtx
+-- (section 6: side bearings from the glyph bounds). Written from the spec. Not supported: collections (ttcf flavor).
+--
+-- Never throws: malformed data returns nil, message.
+local Bytes = require("@formats/core/Bytes")
+local Brotli = require("@formats/codecs/Brotli")
+
+local Rebuild = {}
+
+local readu8 = buffer.readu8
+local band, rshift = bit32.band, bit32.rshift
+
+local KNOWN = {
+ "cmap", "head", "hhea", "hmtx", "maxp", "name", "OS/2", "post", "cvt ", "fpgm", "glyf", "loca", "prep", "CFF ",
+ "VORG", "EBDT", "EBLC", "gasp", "hdmx", "kern", "LTSH", "PCLT", "VDMX", "vhea", "vmtx", "BASE", "GDEF", "GPOS",
+ "GSUB", "EBSC", "JSTF", "MATH", "CBDT", "CBLC", "COLR", "CPAL", "SVG ", "sbix", "acnt", "avar", "bdat", "bloc",
+ "bsln", "cvar", "fdsc", "feat", "fmtx", "fvar", "gvar", "hsty", "just", "lcar", "mort", "morx", "opbd", "prop",
+ "trak", "Zapf", "Silf", "Glat", "Gloc", "Feat", "Sill",
+}
+
+-- UIntBase128 from r
+local function base128(r: Bytes.Reader): number?
+ local v = 0
+ for i = 1, 5 do
+ local b = r:u8()
+ if r.err or (i == 1 and b == 0x80) then
+ return nil
+ end
+ if v >= 2 ^ 25 then
+ return nil
+ end
+ v = v * 128 + band(b, 0x7F)
+ if b < 0x80 then
+ return v
+ end
+ end
+ return nil
+end
+
+-- a cursor over a stream inside the decompressed block
+type Stream = { buf: buffer, p: number, e: number, bad: boolean }
+local function stream(b: buffer, p: number, n: number): Stream
+ return { buf = b, p = p, e = p + n, bad = false }
+end
+local function su8(s: Stream): number
+ if s.p >= s.e then
+ s.bad = true
+ return 0
+ end
+ local v = readu8(s.buf, s.p)
+ s.p += 1
+ return v
+end
+local function su16(s: Stream): number
+ return su8(s) * 256 + su8(s)
+end
+local function si16(s: Stream): number
+ local v = su16(s)
+ return if v >= 32768 then v - 65536 else v
+end
+local function s255(s: Stream): number
+ local c = su8(s)
+ if c == 253 then
+ return su16(s)
+ elseif c == 255 then
+ return su8(s) + 253
+ elseif c == 254 then
+ return su8(s) + 506
+ end
+ return c
+end
+
+local function withSign(flag: number, v: number): number
+ return if band(flag, 1) ~= 0 then v else -v
+end
+
+-- the glyf transform -> glyf bytes (a Writer), loca offsets, per-glyph xMin (for hmtx), numGlyphs, indexFormat
+local function glyf(b: buffer, p: number, n: number, maxBytes: number): (any?, string?)
+ local h = stream(b, p, n)
+ su16(h) -- reserved
+ local option = su16(h)
+ local numGlyphs = su16(h)
+ local indexFormat = su16(h)
+ local sizes = {}
+ for i = 1, 7 do
+ sizes[i] = su16(h) * 65536 + su16(h)
+ end
+ if h.bad then
+ return nil, "truncated glyf transform header"
+ end
+ local at = h.p
+ local streams: { Stream } = {}
+ for i = 1, 7 do
+ if at + sizes[i] > p + n then
+ return nil, "glyf transform stream past the end"
+ end
+ streams[i] = stream(b, at, sizes[i])
+ at += sizes[i]
+ end
+ local nContour, nPoints, flagS, glyphS, compS, bboxS, instrS = streams[1], streams[2], streams[3], streams[4], streams[5], streams[6], streams[7]
+ local overlap: Stream? = nil
+ if band(option, 1) ~= 0 then
+ overlap = stream(b, at, (numGlyphs + 7) // 8)
+ if at + (numGlyphs + 7) // 8 > p + n then
+ return nil, "overlap bitmap past the end"
+ end
+ end
+ -- the bbox bitmap leads the bbox stream
+ local bitmapLen = 4 * ((numGlyphs + 31) // 32)
+ if bitmapLen > sizes[6] then
+ return nil, "bbox bitmap past the end"
+ end
+ local bboxBits = bboxS.p
+ bboxS.p += bitmapLen
+ local function hasBox(g: number): boolean
+ return band(readu8(b, bboxBits + g // 8), rshift(0x80, g % 8)) ~= 0
+ end
+ local w = Bytes.writer(n * 2)
+ local loca = table.create(numGlyphs + 1, 0)
+ local xMins = table.create(numGlyphs, 0)
+ for g = 0, numGlyphs - 1 do
+ loca[g + 1] = w.pos
+ local nc = si16(nContour)
+ if nContour.bad then
+ return nil, "nContour stream truncated"
+ end
+ if nc == 0 then
+ if hasBox(g) then
+ return nil, "empty glyph with a bounding box"
+ end
+ elseif nc > 0 then
+ -- simple glyph
+ local ends = table.create(nc, 0)
+ local total = 0
+ for c = 1, nc do
+ total += s255(nPoints)
+ ends[c] = total - 1
+ end
+ if nPoints.bad or total > 65535 then
+ return nil, "bad point counts"
+ end
+ local xs, ys, on = table.create(total, 0), table.create(total, 0), table.create(total, false)
+ local x, y = 0, 0
+ for k = 1, total do
+ local fl = su8(flagS)
+ on[k] = rshift(fl, 7) == 0
+ fl = band(fl, 0x7F)
+ local dx, dy
+ if fl < 10 then
+ dx, dy = 0, withSign(fl, band(fl, 14) * 128 + su8(glyphS))
+ elseif fl < 20 then
+ dx, dy = withSign(fl, band(fl - 10, 14) * 128 + su8(glyphS)), 0
+ elseif fl < 84 then
+ local b0 = fl - 20
+ local b1 = su8(glyphS)
+ dx = withSign(fl, 1 + band(b0, 0x30) + rshift(b1, 4))
+ dy = withSign(rshift(fl, 1), 1 + band(b0, 0x0C) * 4 + band(b1, 0x0F))
+ elseif fl < 120 then
+ local b0 = fl - 84
+ dx = withSign(fl, 1 + (b0 // 12) * 256 + su8(glyphS))
+ dy = withSign(rshift(fl, 1), 1 + rshift(b0 % 12, 2) * 256 + su8(glyphS))
+ elseif fl < 124 then
+ local b1, b2, b3 = su8(glyphS), su8(glyphS), su8(glyphS)
+ dx = withSign(fl, b1 * 16 + rshift(b2, 4))
+ dy = withSign(rshift(fl, 1), band(b2, 0x0F) * 256 + b3)
+ else
+ local b1, b2, b3, b4 = su8(glyphS), su8(glyphS), su8(glyphS), su8(glyphS)
+ dx = withSign(fl, b1 * 256 + b2)
+ dy = withSign(rshift(fl, 1), b3 * 256 + b4)
+ end
+ x += dx
+ y += dy
+ xs[k], ys[k] = x, y
+ end
+ local ilen = s255(glyphS)
+ if flagS.bad or glyphS.bad then
+ return nil, "flag / glyph stream truncated"
+ end
+ local x0, y0, x1, y1
+ if hasBox(g) then
+ x0, y0, x1, y1 = si16(bboxS), si16(bboxS), si16(bboxS), si16(bboxS)
+ else
+ x0, y0, x1, y1 = 32767, 32767, -32768, -32768
+ for k = 1, total do
+ x0, y0 = math.min(x0, xs[k]), math.min(y0, ys[k])
+ x1, y1 = math.max(x1, xs[k]), math.max(y1, ys[k])
+ end
+ if total == 0 then
+ x0, y0, x1, y1 = 0, 0, 0, 0
+ end
+ end
+ xMins[g + 1] = x0
+ w:u16be(nc % 65536)
+ w:u16be(x0 % 65536)
+ w:u16be(y0 % 65536)
+ w:u16be(x1 % 65536)
+ w:u16be(y1 % 65536)
+ for c = 1, nc do
+ w:u16be(ends[c])
+ end
+ w:u16be(ilen)
+ if instrS.p + ilen > instrS.e then
+ return nil, "instruction stream truncated"
+ end
+ w:bytes(b, instrS.p, ilen)
+ instrS.p += ilen
+ local ov = overlap ~= nil and band(readu8(b, (overlap :: Stream).p + g // 8), rshift(0x80, g % 8)) ~= 0
+ -- flags (short vectors, same-as-previous, repeats) and the coordinate deltas, as compilers write them
+ local fls = table.create(total, 0)
+ for k = 1, total do
+ local fl = if on[k] then 1 else 0
+ if k == 1 and ov then
+ fl += 0x40
+ end
+ local dx = xs[k] - (if k > 1 then xs[k - 1] else 0)
+ local dy = ys[k] - (if k > 1 then ys[k - 1] else 0)
+ if dx == 0 then
+ fl += 0x10
+ elseif dx > -256 and dx < 256 then
+ fl += if dx > 0 then 0x12 else 0x02
+ end
+ if dy == 0 then
+ fl += 0x20
+ elseif dy > -256 and dy < 256 then
+ fl += if dy > 0 then 0x24 else 0x04
+ end
+ fls[k] = fl
+ end
+ local k = 1
+ while k <= total do
+ local fl = fls[k]
+ local run = 0
+ while k + run + 1 <= total and fls[k + run + 1] == fl and run < 255 do
+ run += 1
+ end
+ if run > 1 then
+ w:u8(fl + 8)
+ w:u8(run)
+ k += run + 1
+ else
+ w:u8(fl)
+ k += 1
+ end
+ end
+ for pass = 0, 1 do
+ local cs = if pass == 0 then xs else ys
+ local short, same = if pass == 0 then 0x02 else 0x04, if pass == 0 then 0x10 else 0x20
+ local prev = 0
+ for q = 1, total do
+ local d = cs[q] - prev
+ prev = cs[q]
+ local fl = fls[q]
+ if band(fl, short) ~= 0 then
+ w:u8(math.abs(d))
+ elseif band(fl, same) == 0 then
+ w:u16be(d % 65536)
+ end
+ end
+ end
+ elseif nc == -1 then
+ if not hasBox(g) then
+ return nil, "composite glyph without a bounding box"
+ end
+ local x0, y0, x1, y1 = si16(bboxS), si16(bboxS), si16(bboxS), si16(bboxS)
+ xMins[g + 1] = x0
+ w:u16be(0xFFFF)
+ w:u16be(x0 % 65536)
+ w:u16be(y0 % 65536)
+ w:u16be(x1 % 65536)
+ w:u16be(y1 % 65536)
+ -- copy the component records: their length follows from the flags
+ local start = compS.p
+ local instr = false
+ while true do
+ local fl = su16(compS)
+ su16(compS) -- glyph index
+ local len = if band(fl, 1) ~= 0 then 4 else 2
+ if band(fl, 8) ~= 0 then
+ len += 2
+ elseif band(fl, 0x40) ~= 0 then
+ len += 4
+ elseif band(fl, 0x80) ~= 0 then
+ len += 8
+ end
+ compS.p += len
+ if band(fl, 0x100) ~= 0 then
+ instr = true
+ end
+ if compS.bad or compS.p > compS.e then
+ return nil, "composite stream truncated"
+ end
+ if band(fl, 0x20) == 0 then
+ break
+ end
+ end
+ w:bytes(b, start, compS.p - start)
+ if instr then
+ local ilen = s255(glyphS)
+ if glyphS.bad or instrS.p + ilen > instrS.e then
+ return nil, "instruction stream truncated"
+ end
+ w:u16be(ilen)
+ w:bytes(b, instrS.p, ilen)
+ instrS.p += ilen
+ end
+ else
+ return nil, "bad contour count " .. nc
+ end
+ if bboxS.bad then
+ return nil, "bbox stream truncated"
+ end
+ -- 4-byte alignment
+ while w.pos % 4 ~= 0 do
+ w:u8(0)
+ end
+ if w.pos > maxBytes then
+ return nil, "limit"
+ end
+ end
+ loca[numGlyphs + 1] = w.pos
+ if indexFormat == 0 and w.pos > 0x1FFFE then
+ indexFormat = 1 -- (head.indexToLocFormat is patched to match)
+ end
+ return { glyf = w:finish(), loca = loca, xMins = xMins, numGlyphs = numGlyphs, indexFormat = indexFormat }, nil
+end
+
+-- hmtx transform (version 1): advances + the side bearings that were not dropped
+local function hmtx(b: buffer, p: number, n: number, numGlyphs: number, numH: number, xMins: { number }): (buffer?, string?)
+ local s = stream(b, p, n)
+ local flags = su8(s)
+ local out = Bytes.writer(numH * 4 + (numGlyphs - numH) * 2)
+ local adv = table.create(numH, 0)
+ for i = 1, numH do
+ adv[i] = su16(s)
+ end
+ local lsb = table.create(numGlyphs, 0)
+ for i = 1, numH do
+ lsb[i] = if band(flags, 1) == 0 then si16(s) else (xMins[i] or 0)
+ end
+ for i = numH + 1, numGlyphs do
+ lsb[i] = if band(flags, 2) == 0 then si16(s) else (xMins[i] or 0)
+ end
+ if s.bad then
+ return nil, "hmtx transform truncated"
+ end
+ for i = 1, numH do
+ out:u16be(adv[i])
+ out:u16be(lsb[i] % 65536)
+ end
+ for i = numH + 1, numGlyphs do
+ out:u16be(lsb[i] % 65536)
+ end
+ return out:finish(), nil
+end
+
+-- sfnt(r, maxBytes) -> sfnt buffer | nil, message, code ("truncated" / "corrupt" / "unsupported" / "limit")
+function Rebuild.sfnt(r: Bytes.Reader, maxBytes: number): (buffer?, string?, string?)
+ if not r:match("wOF2") then
+ return nil, "bad signature", "corrupt"
+ end
+ local flavor = r:string(4)
+ local length = r:u32be()
+ local numTables = r:u16be()
+ r:skip(2)
+ local totalSfnt = r:u32be()
+ local totalComp = r:u32be()
+ r:skip(24)
+ if r.err then
+ return nil, "truncated header", "truncated"
+ end
+ if flavor == "ttcf" then
+ return nil, "font collections in WOFF2", "unsupported"
+ end
+ if length > r:size() then
+ return nil, "file shorter than its header says", "truncated"
+ end
+ if numTables == 0 or numTables > 1024 then
+ return nil, "bad table count", "corrupt"
+ end
+ local dir = {}
+ local streamTotal = 0
+ for i = 1, numTables do
+ local flags = r:u8()
+ local tag = KNOWN[band(flags, 63) + 1]
+ if band(flags, 63) == 63 then
+ tag = r:string(4)
+ end
+ local version = rshift(flags, 6)
+ local orig = base128(r)
+ if not tag or not orig then
+ return nil, "bad table directory entry " .. i, if r.err then "truncated" else "corrupt"
+ end
+ local transformed = if tag == "glyf" or tag == "loca" then version == 0 else version ~= 0
+ local tlen = orig
+ if transformed then
+ local t = base128(r)
+ if not t then
+ return nil, "bad transformLength", "corrupt"
+ end
+ tlen = t
+ end
+ if (tag == "glyf" or tag == "loca") and not transformed and version ~= 3 then
+ return nil, "bad glyf / loca transform version", "corrupt"
+ end
+ if transformed and tag ~= "glyf" and tag ~= "loca" and tag ~= "hmtx" then
+ return nil, "unknown transform of " .. tag, "unsupported"
+ end
+ dir[i] = { tag = tag, orig = orig, len = tlen, transformed = transformed, at = streamTotal }
+ streamTotal += tlen
+ if streamTotal > maxBytes or orig > maxBytes then
+ return nil, "limit", "limit"
+ end
+ end
+ local compAt = r.pos
+ if compAt + totalComp > r.limit then
+ return nil, "compressed data past the end", "truncated"
+ end
+ local data, berr = Brotli.decompress(r.buf, compAt, totalComp, { maxBytes = math.max(streamTotal, 1) })
+ if not data then
+ local e = berr :: any
+ return nil, "brotli: " .. tostring(e.message), if e.code == "LIMIT" then "limit" else "corrupt"
+ end
+ if buffer.len(data) < streamTotal then
+ return nil, "decompressed stream shorter than the tables", "corrupt"
+ end
+ -- the tables, glyf / loca / hmtx rebuilt
+ local byTag: { [string]: any } = {}
+ for _, e in dir do
+ byTag[e.tag] = e
+ end
+ local tables: { [string]: buffer } = {}
+ local g = byTag.glyf
+ local xMins: { number } = {}
+ local locaLong: boolean? = nil
+ if g and g.transformed then
+ if not byTag.loca then
+ return nil, "glyf without loca", "corrupt"
+ end
+ local res, gerr = glyf(data, g.at, g.len, maxBytes)
+ if not res then
+ return nil, "glyf: " .. tostring(gerr), if gerr == "limit" then "limit" else "corrupt"
+ end
+ tables.glyf = res.glyf
+ xMins = res.xMins
+ local short = res.indexFormat == 0
+ local lw = Bytes.writer((res.numGlyphs + 1) * 4)
+ for _, o in res.loca do
+ if short then
+ lw:u16be(o // 2)
+ else
+ lw:u32be(o)
+ end
+ end
+ tables.loca = lw:finish()
+ locaLong = not short
+ end
+ for _, e in dir do
+ if e.tag == "glyf" or e.tag == "loca" then
+ if not e.transformed then
+ local t = buffer.create(e.len)
+ buffer.copy(t, 0, data, e.at, e.len)
+ tables[e.tag] = t
+ end
+ elseif e.tag == "hmtx" and e.transformed then
+ -- needs numGlyphs (maxp) and numberOfHMetrics (hhea)
+ local mp, hh = byTag.maxp, byTag.hhea
+ if not mp or not hh or mp.len < 6 or hh.len < 36 then
+ return nil, "hmtx transform without maxp / hhea", "corrupt"
+ end
+ local numGlyphs = readu8(data, mp.at + 4) * 256 + readu8(data, mp.at + 5)
+ local numH = readu8(data, hh.at + 34) * 256 + readu8(data, hh.at + 35)
+ if numH < 1 or numH > numGlyphs then
+ return nil, "bad numberOfHMetrics", "corrupt"
+ end
+ local t, herr = hmtx(data, e.at, e.len, numGlyphs, numH, xMins)
+ if not t then
+ return nil, herr, "corrupt"
+ end
+ tables.hmtx = t
+ else
+ local t = buffer.create(e.len)
+ buffer.copy(t, 0, data, e.at, e.len)
+ tables[e.tag] = t
+ end
+ end
+ -- head.indexToLocFormat must agree with the rebuilt loca
+ if locaLong ~= nil and tables.head and buffer.len(tables.head) >= 54 then
+ buffer.writeu8(tables.head, 50, 0)
+ buffer.writeu8(tables.head, 51, if locaLong then 1 else 0)
+ end
+ -- the sfnt: directory sorted by tag, tables 4-byte aligned
+ local tags = {}
+ for t in tables do
+ table.insert(tags, t)
+ end
+ table.sort(tags)
+ local n = #tags
+ local size = 12 + 16 * n
+ for _, t in tags do
+ size += (buffer.len(tables[t]) + 3) // 4 * 4
+ end
+ if size > maxBytes then
+ return nil, "limit", "limit"
+ end
+ local out = buffer.create(size)
+ buffer.writestring(out, 0, flavor)
+ local es, sel = 1, 0
+ while es * 2 <= n do
+ es *= 2
+ sel += 1
+ end
+ local function be16(o: number, v: number)
+ buffer.writeu8(out, o, rshift(v, 8))
+ buffer.writeu8(out, o + 1, band(v, 255))
+ end
+ local function be32(o: number, v: number)
+ buffer.writeu32(out, o, bit32.byteswap(v))
+ end
+ be16(4, n)
+ be16(6, es * 16)
+ be16(8, sel)
+ be16(10, n * 16 - es * 16)
+ local p = 12 + 16 * n
+ for i, t in tags do
+ local tb = tables[t]
+ local d = 12 + (i - 1) * 16
+ buffer.writestring(out, d, t)
+ be32(d + 4, 0) -- checksums are not recomputed
+ be32(d + 8, p)
+ be32(d + 12, buffer.len(tb))
+ buffer.copy(out, p, tb)
+ p += (buffer.len(tb) + 3) // 4 * 4
+ end
+ local _ = totalSfnt
+ return out, nil, nil
+end
+
+return Rebuild
diff --git a/src/Formats/font/woff2/init.luau b/src/Formats/font/woff2/init.luau
new file mode 100644
index 0000000..1d368b4
--- /dev/null
+++ b/src/Formats/font/woff2/init.luau
@@ -0,0 +1,59 @@
+--!strict
+-- font/woff2: WOFF 2.0 (W3C Recommendation): sfnt tables in one Brotli stream, with the glyf / loca and hmtx
+-- transforms. Decoding rebuilds the sfnt (font/woff2/Rebuild) and reads it through codecs/TrueType (TrueType or CFF
+-- outlines, see font/ttf). Written from the spec; Brotli is codecs/Brotli. Not supported: collections, writing.
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local TrueType = require("@formats/codecs/TrueType")
+local Rebuild = require("@formats/font/woff2/Rebuild")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Woff2 = {
+ name = "woff2",
+ category = "font",
+ extensions = { "woff2" },
+ mime = { "font/woff2" },
+ deps = { "core/Err", "core/Bytes", "codecs/TrueType", "codecs/Brotli" },
+ caps = { decode = true, encode = false, outlines = { "truetype", "cff" }, transforms = { "glyf", "loca", "hmtx" } },
+}
+
+export type DecodeOptions = {
+ maxBytes: number?, -- refuse a font whose sfnt is bigger (default 2^28)
+}
+
+-- ------------------------------------------------------------------------------------------------ constants
+local CODES = { truncated = Err.TRUNCATED, corrupt = Err.CORRUPT, unsupported = Err.UNSUPPORTED, limit = Err.LIMIT }
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Woff2.sniff(r: Bytes.Reader): number
+ return if r:peek(4) == "wOF2" then 1 else 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+-- sfnt(r, opts?) -> the rebuilt sfnt font file | nil, Err
+function Woff2.sfnt(r: Bytes.Reader, opts: DecodeOptions?): (buffer?, Err.Err?)
+ local maxBytes = (opts and opts.maxBytes) or 2 ^ 28
+ local at = r.base
+ local out, msg, code = Rebuild.sfnt(r, maxBytes)
+ if not out then
+ return nil, Err.new(CODES[code or "corrupt"] or Err.CORRUPT, msg or "rebuild failed", at)
+ end
+ return out, nil
+end
+
+function Woff2.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
+ local sfnt, err = Woff2.sfnt(r, opts)
+ if not sfnt then
+ return nil, err
+ end
+ local font, ferr = TrueType.font(sfnt)
+ if not font then
+ return nil, ferr
+ end
+ font.meta.source = { format = "woff2", outlines = font.meta.outlines }
+ return font, nil
+end
+
+return Woff2
diff --git a/src/Formats/host/init.luau b/src/Formats/host/init.luau
index ed78da2..3852922 100644
--- a/src/Formats/host/init.luau
+++ b/src/Formats/host/init.luau
@@ -39,5 +39,12 @@ elseif name == "luajit" then
else
host = require("@formats/host/Luau")
end
+-- LuaJIT (plain or LÖVE): the big decoders (Opus CELT, H.264, ...) outgrow the default 1000 traces / 8 MB of machine
+-- code and fall back to the interpreter (CELT runs about 2.5x faster with these limits). Raising the limits only
+-- allows more traces; set _G.FORMATS_NO_JIT_TUNE = true before requiring the library to leave them alone.
+if G.jit ~= nil and type(G.jit.opt) == "table" and not G.FORMATS_NO_JIT_TUNE then
+ pcall(G.jit.opt.start, "maxtrace=8000", "maxmcode=65536")
+end
+
local _ = Err
return host
diff --git a/src/Formats/image/gif/Decode.luau b/src/Formats/image/gif/Decode.luau
new file mode 100644
index 0000000..98a6c7c
--- /dev/null
+++ b/src/Formats/image/gif/Decode.luau
@@ -0,0 +1,68 @@
+--!strict
+--!native
+--!optimize 2
+-- image/gif/Decode: the per-frame pixel work (native; never throws): palette indexes (plain or interlaced rows) to
+-- rgba8, and drawing a frame onto the canvas (transparent pixels leave the canvas as it is). The caller sizes every
+-- buffer: indexes fw * fh bytes, the palette 256 u32 entries, the frame fw * fh * 4, the canvas cw * ch * 4.
+local readu8, readu32, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu32
+
+local Decode = {}
+
+-- the source row of output row y in an interlaced frame (passes: every 8th from 0, every 8th from 4, every 4th from
+-- 2, every 2nd from 1)
+local function interlacedRow(fh: number): { number }
+ local map = table.create(fh, 0)
+ local r = 0
+ for _, pass in { { 0, 8 }, { 4, 8 }, { 2, 4 }, { 1, 2 } } do
+ local y = pass[1]
+ while y < fh do
+ map[y + 1] = r
+ r += 1
+ y += pass[2]
+ end
+ end
+ return map
+end
+
+-- toRgba(indexes, fw, fh, interlaced, palette, out): out = the frame in rgba8 (palette: 256 u32 entries, the
+-- transparent one already alpha 0)
+function Decode.toRgba(indexes: buffer, fw: number, fh: number, interlaced: boolean, palette: buffer, out: buffer)
+ local rows = if interlaced then interlacedRow(fh) else nil
+ for y = 0, fh - 1 do
+ local src = (if rows then rows[y + 1] else y) * fw
+ local dst = y * fw * 4
+ for x = 0, fw - 1 do
+ writeu32(out, dst + x * 4, readu32(palette, readu8(indexes, src + x) * 4))
+ end
+ end
+end
+
+-- draw(canvas, cw, ch, frame, fx, fy, fw, fh): frame pixels with alpha > 0 replace the canvas (clipped)
+function Decode.draw(canvas: buffer, cw: number, ch: number, frame: buffer, fx: number, fy: number, fw: number, fh: number)
+ local x0, y0 = math.max(0, fx), math.max(0, fy)
+ local x1, y1 = math.min(cw, fx + fw), math.min(ch, fy + fh)
+ for y = y0, y1 - 1 do
+ local s = ((y - fy) * fw - fx) * 4
+ local d = y * cw * 4
+ for x = x0, x1 - 1 do
+ local v = readu32(frame, s + x * 4)
+ if v >= 0x01000000 then
+ writeu32(canvas, d + x * 4, v)
+ end
+ end
+ end
+end
+
+-- clear(canvas, cw, ch, fx, fy, fw, fh): the frame's rectangle to transparent black (dispose to background)
+function Decode.clear(canvas: buffer, cw: number, ch: number, fx: number, fy: number, fw: number, fh: number)
+ local x0, y0 = math.max(0, fx), math.max(0, fy)
+ local x1, y1 = math.min(cw, fx + fw), math.min(ch, fy + fh)
+ if x1 <= x0 then
+ return
+ end
+ for y = y0, y1 - 1 do
+ buffer.fill(canvas, (y * cw + x0) * 4, 0, (x1 - x0) * 4)
+ end
+end
+
+return Decode
diff --git a/src/Formats/image/gif/init.luau b/src/Formats/image/gif/init.luau
new file mode 100644
index 0000000..c2b84f4
--- /dev/null
+++ b/src/Formats/image/gif/init.luau
@@ -0,0 +1,534 @@
+--!strict
+-- image/gif: GIF87a / GIF89a. New code from the GIF89a spec (W3C / CompuServe 1990). Supports: decode of every image
+-- (global / local colour tables, interlaced rows, LZW minimum code sizes 2..8 and the odd 1, transparency, frames
+-- smaller than or outside the canvas), animation (Graphic Control Extension delays, disposal none / background /
+-- previous, NETSCAPE2.0 / ANIMEXTS1.0 loop counts), comments (meta.text.comment); truncated files keep the frames
+-- read so far (meta.truncated). Encode of rgba8 images and animations (Types.Frame lists) through codecs/Quantize
+-- (median cut or octree, optional Floyd-Steinberg dithering; exact palettes, so lossless, at <= 256 colours) with
+-- alpha < 128 as the transparent index.
+-- Not supported: the plain text extension (skipped), the aspect ratio (kept in meta.source.aspect), the "user input"
+-- flag, and blend = "source" frames that clear pixels to transparent (GIF can only draw over).
+--
+-- Decoded value: img.pixels = the first frame composited on a transparent canvas; for animations img.frames = every
+-- frame's own rectangle (rgba8; blend "over" when it has a transparent index, else "source") and img.loops, the
+-- number of plays (0 = forever; 1 when the file has no loop extension). The NETSCAPE2.0 value counts repeats, as
+-- browsers and ImageMagick read it: a stored n plays n + 1 times (n = 0: forever).
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Lzw = require("@formats/codecs/Lzw")
+local Quantize = require("@formats/codecs/Quantize")
+local Types = require("@formats/Types")
+local Decode = require("@formats/image/gif/Decode")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Gif = {
+ name = "gif",
+ category = "image",
+ extensions = { "gif" },
+ mime = { "image/gif" },
+ deps = { "core/Err", "core/Bytes", "codecs/Lzw", "codecs/Quantize", "Types" },
+ caps = { decode = true, encode = true, animation = true, alpha = true, palette = true, depths = { 1, 2, 4, 8 } },
+}
+
+-- ------------------------------------------------------------------------------------------------ types
+export type DecodeOptions = {
+ maxPixels: number?, -- refuse a canvas or frame larger than this (default 2^26)
+ maxTotalPixels: number?, -- refuse animations whose frames add up to more (default 2^28)
+ maxFrames: number?, -- stop after this many frames (default: all)
+}
+export type EncodeOptions = {
+ maxColors: number?, -- 2..256 per palette (default 256; one is taken by transparency when needed)
+ method: ("mediancut" | "octree")?, -- default "mediancut"
+ dither: boolean?, -- Floyd-Steinberg (default false)
+ loops: number?, -- animation plays override (0 = forever, 1..65536; default img.loops)
+ globalPalette: boolean?, -- one palette for every frame (default false: a single image uses the global table,
+ -- each animation frame gets its own local table)
+}
+
+-- ------------------------------------------------------------------------------------------------ constants
+local readu8 = buffer.readu8
+local DISPOSE = { [0] = "none", [1] = "none", [2] = "background", [3] = "previous" }
+local DISPOSE_CODE = { none = 1, background = 2, previous = 3 }
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Gif.sniff(r: Bytes.Reader): number
+ local s = r:peek(6)
+ return if s == "GIF89a" or s == "GIF87a" then 1 else 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+-- a colour table at p (n entries) -> 256 u32 rgba entries (missing ones opaque black) and the { r, g, b, a } list
+local function colorTable(b: buffer, p: number, n: number): (buffer, { { number } })
+ local t = buffer.create(1024)
+ local list = table.create(n)
+ for i = 0, 255 do
+ buffer.writeu32(t, i * 4, 0xFF000000)
+ end
+ for i = 0, n - 1 do
+ local q = p + i * 3
+ local r, g, bl = readu8(b, q), readu8(b, q + 1), readu8(b, q + 2)
+ buffer.writeu32(t, i * 4, r + g * 256 + bl * 65536 + 0xFF000000)
+ list[i + 1] = { r, g, bl, 255 }
+ end
+ return t, list
+end
+
+function Gif.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
+ local maxPixels = opts and opts.maxPixels or 2 ^ 26
+ local maxTotal = opts and opts.maxTotalPixels or 2 ^ 28
+ local maxFrames = opts and opts.maxFrames or math.huge
+ local sig = r:string(6)
+ local cw, ch = r:u16le(), r:u16le()
+ local flags, bg, aspect = r:u8(), r:u8(), r:u8()
+ if r.err then
+ return nil, r.err
+ end
+ if sig ~= "GIF89a" and sig ~= "GIF87a" then
+ return nil, Err.new(Err.CORRUPT, "bad signature", r.base)
+ end
+ if cw == 0 or ch == 0 then
+ return nil, Err.new(Err.CORRUPT, "zero canvas size", r.base + 6)
+ end
+ if cw * ch > maxPixels then
+ return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", cw, ch, maxPixels))
+ end
+ local b = r.buf
+ local gct: buffer? = nil
+ local gpal: { { number } }? = nil
+ if bit32.band(flags, 0x80) ~= 0 then
+ local n = bit32.lshift(1, bit32.band(flags, 7) + 1)
+ if not r:need(n * 3) then
+ return nil, r.err
+ end
+ gct, gpal = colorTable(b, r.pos, n)
+ r.pos += n * 3
+ end
+ local img = Types.Image.new(cw, ch, "rgba8")
+ local frames: { Types.Frame } = {}
+ local comments: { string } = {}
+ local loops: number? = nil
+ local total = 0
+ -- the pending Graphic Control Extension
+ local delay, dispose, trans = 0, 0, -1
+ local truncated = false
+ local interlacedAny = false
+ local localTables = 0
+ local minCode = 8
+ local limit = r.limit
+ -- the sub-blocks at r.pos: joined into one buffer (nil when they run past the end)
+ local function subBlocks(): (buffer?, number)
+ local p = r.pos
+ local n = 0
+ while true do
+ if p >= limit then
+ return nil, p
+ end
+ local len = readu8(b, p)
+ if len == 0 then
+ break
+ end
+ if p + 1 + len > limit then
+ -- keep what is there: a truncated last block
+ n += limit - p - 1
+ p = limit
+ local out = buffer.create(n)
+ local q, o = r.pos, 0
+ while q < limit do
+ local l = math.min(readu8(b, q), limit - q - 1)
+ buffer.copy(out, o, b, q + 1, l)
+ o += l
+ q += 1 + l
+ end
+ return out, -1
+ end
+ n += len
+ p += 1 + len
+ end
+ local out = buffer.create(n)
+ local q, o = r.pos, 0
+ while q < p do
+ local l = readu8(b, q)
+ buffer.copy(out, o, b, q + 1, l)
+ o += l
+ q += 1 + l
+ end
+ return out, p + 1
+ end
+ local function skipBlocks(): boolean
+ local p = r.pos
+ while p < limit do
+ local len = readu8(b, p)
+ if len == 0 then
+ r.pos = p + 1
+ return true
+ end
+ p += 1 + len
+ end
+ r.pos = limit
+ return false
+ end
+ while true do
+ if r.pos >= limit then
+ truncated = true
+ break
+ end
+ local intro = r:u8()
+ if intro == 0x3B then
+ break
+ elseif intro == 0x21 then
+ local label = r:u8()
+ if r.err then
+ truncated = true
+ break
+ end
+ local p = r.pos
+ if label == 0xF9 and p + 6 <= limit and readu8(b, p) >= 4 then
+ local f = readu8(b, p + 1)
+ dispose = bit32.band(bit32.rshift(f, 2), 7)
+ delay = readu8(b, p + 2) + readu8(b, p + 3) * 256
+ trans = if bit32.band(f, 1) ~= 0 then readu8(b, p + 4) else -1
+ elseif label == 0xFF and p + 15 <= limit and readu8(b, p) == 11 then
+ local id = buffer.readstring(b, p + 1, 11)
+ if (id == "NETSCAPE2.0" or id == "ANIMEXTS1.0") and readu8(b, p + 12) >= 3 and readu8(b, p + 13) == 1 then
+ local rep = readu8(b, p + 14) + readu8(b, p + 15) * 256
+ loops = if rep == 0 then 0 else rep + 1 -- the stored value repeats: plays = value + 1
+ end
+ elseif label == 0xFE then
+ local data = subBlocks()
+ if data then
+ table.insert(comments, buffer.tostring(data))
+ end
+ end
+ if not skipBlocks() then
+ truncated = true
+ break
+ end
+ elseif intro == 0x2C then
+ local fx, fy, fw, fh = r:u16le(), r:u16le(), r:u16le(), r:u16le()
+ local f = r:u8()
+ if r.err then
+ truncated = true
+ break
+ end
+ if fw * fh > maxPixels then
+ return nil, Err.new(Err.LIMIT, string.format("a %d x %d frame is over the %d pixel limit", fw, fh, maxPixels), r.pos)
+ end
+ total += fw * fh
+ if total > maxTotal then
+ return nil, Err.new(Err.LIMIT, string.format("the frames add up to over %d pixels", maxTotal), r.pos)
+ end
+ local pal = gct
+ if bit32.band(f, 0x80) ~= 0 then
+ local n = bit32.lshift(1, bit32.band(f, 7) + 1)
+ if not r:need(n * 3) then
+ truncated = true
+ break
+ end
+ pal = colorTable(b, r.pos, n)
+ r.pos += n * 3
+ localTables += 1
+ end
+ local interlaced = bit32.band(f, 0x40) ~= 0
+ interlacedAny = interlacedAny or interlaced
+ local mc = r:u8()
+ if r.err then
+ truncated = true
+ break
+ end
+ if mc < 1 or mc > 11 then
+ return nil, Err.new(Err.CORRUPT, "bad LZW minimum code size " .. mc, r.pos - 1)
+ end
+ minCode = mc
+ local data, nextPos = subBlocks()
+ if not data then
+ truncated = true
+ break
+ end
+ local n = fw * fh
+ local idx = buffer.create(n)
+ local got, lerr = Lzw.decode(data, 0, buffer.len(data), idx, 0, n, "gif", mc)
+ if got < n or nextPos < 0 then
+ truncated = true -- the missing pixels stay index 0, as most decoders show them
+ end
+ local _ = lerr -- a corrupt code ends the frame early (kept: what was decoded is shown)
+ local t = buffer.create(1024)
+ if pal then
+ buffer.copy(t, 0, pal)
+ else
+ -- no colour table at all: a grey ramp (what the spec leaves to the decoder)
+ for i = 0, 255 do
+ buffer.writeu32(t, i * 4, i + i * 256 + i * 65536 + 0xFF000000)
+ end
+ end
+ if trans >= 0 then
+ buffer.writeu32(t, trans * 4, 0)
+ end
+ local fimg = Types.Image.new(fw, fh, "rgba8")
+ Decode.toRgba(idx, fw, fh, interlaced, t, fimg.pixels)
+ if #frames == 0 then
+ Decode.draw(img.pixels, cw, ch, fimg.pixels, fx, fy, fw, fh)
+ end
+ table.insert(frames, {
+ image = fimg,
+ delay = delay / 100,
+ x = fx,
+ y = fy,
+ dispose = DISPOSE[dispose] or "none",
+ blend = if trans >= 0 then "over" else "source",
+ } :: Types.Frame)
+ delay, dispose, trans = 0, 0, -1
+ if nextPos < 0 then
+ break
+ end
+ r.pos = nextPos
+ if #frames >= maxFrames then
+ break
+ end
+ else
+ -- junk between blocks: stop here, keeping what was read
+ if #frames == 0 then
+ return nil, Err.new(Err.CORRUPT, string.format("bad block introducer 0x%02x", intro), r.pos - 1)
+ end
+ truncated = true
+ break
+ end
+ end
+ if #frames == 0 then
+ return nil, Err.new(Err.TRUNCATED, "no image data", r.pos)
+ end
+ if #frames > 1 then
+ img.frames = frames
+ img.loops = loops or 1
+ else
+ img.loops = loops or 0
+ end
+ img.meta.palette = gpal
+ img.meta.background = bg
+ if #comments > 0 then
+ img.meta.text = { comment = table.concat(comments, "\n") }
+ end
+ if truncated then
+ img.meta.truncated = true
+ end
+ img.meta.source = {
+ format = "gif",
+ version = string.sub(sig, 4),
+ bitDepth = minCode,
+ colorType = "palette",
+ frames = #frames,
+ interlaced = interlacedAny,
+ localPalettes = localTables,
+ aspect = aspect,
+ loopExtension = loops ~= nil,
+ }
+ return img, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+local function validImage(i: any): boolean
+ return type(i) == "table" and i.format == "rgba8" and type(i.pixels) == "buffer" and type(i.width) == "number" and type(i.height) == "number" and i.width >= 1 and i.height >= 1 and i.width <= 65535 and i.height <= 65535 and i.width % 1 == 0 and i.height % 1 == 0 and buffer.len(i.pixels) >= i.width * i.height * 4
+end
+
+local function hasTransparency(px: buffer, n: number): boolean
+ for i = 0, n - 1 do
+ if readu8(px, i * 4 + 3) < 128 then
+ return true
+ end
+ end
+ return false
+end
+
+-- palette list -> padded table bytes (power of two entries, >= 2) and its size code
+local function writeTable(w: Bytes.Writer, pal: { { number } }): number
+ local bits = 1
+ while bit32.lshift(1, bits) < #pal do
+ bits += 1
+ end
+ for i = 1, bit32.lshift(1, bits) do
+ local c = pal[i]
+ if c then
+ w:u8(c[1])
+ w:u8(c[2])
+ w:u8(c[3])
+ else
+ w:fill(0, 3)
+ end
+ end
+ return bits
+end
+
+local function tableBits(n: number): number
+ local bits = 1
+ while bit32.lshift(1, bits) < n do
+ bits += 1
+ end
+ return bits
+end
+
+function Gif.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
+ if not validImage(img) then
+ return nil, Err.new(Err.ARG, "needs an rgba8 Image of 1..65535 x 1..65535 pixels")
+ end
+ local maxColors = opts and opts.maxColors or 256
+ if type(maxColors) ~= "number" or maxColors < 2 or maxColors > 256 then
+ return nil, Err.new(Err.ARG, "maxColors must be 2..256")
+ end
+ maxColors = math.floor(maxColors)
+ local method = opts and opts.method or "mediancut"
+ if method ~= "mediancut" and method ~= "octree" then
+ return nil, Err.new(Err.ARG, "method must be mediancut or octree")
+ end
+ local dither = opts and opts.dither or false
+ -- the frames to write: { image, x, y, delay, dispose }
+ local list: { Types.Frame } = {}
+ if type(img.frames) == "table" and #(img.frames :: any) > 0 then
+ for i, f in img.frames :: { Types.Frame } do
+ if type(f) ~= "table" or not validImage(f.image) then
+ return nil, Err.new(Err.ARG, "frame " .. i .. ": needs an rgba8 image")
+ end
+ local x, y = f.x or 0, f.y or 0
+ if type(x) ~= "number" or type(y) ~= "number" or x < 0 or y < 0 or x + f.image.width > 65535 or y + f.image.height > 65535 then
+ return nil, Err.new(Err.ARG, "frame " .. i .. ": bad position")
+ end
+ table.insert(list, f)
+ end
+ else
+ list[1] = { image = img, x = 0, y = 0, delay = 0, dispose = "none", blend = "source" }
+ end
+ local animated = #list > 1
+ local loops = opts and opts.loops or img.loops or 0
+ if type(loops) ~= "number" or loops < 0 or loops > 65536 or loops % 1 ~= 0 then
+ return nil, Err.new(Err.ARG, "loops must be 0..65536")
+ end
+ -- palettes
+ local shared = (opts and opts.globalPalette) or not animated
+ local qopts = { method = method, dither = dither }
+ local globalPal: { { number } }? = nil
+ local globalTrans = false
+ if shared then
+ -- every frame's pixels together
+ local npx = 0
+ for _, f in list do
+ npx += f.image.width * f.image.height
+ end
+ local all = buffer.create(npx * 4)
+ local o = 0
+ for _, f in list do
+ local n = f.image.width * f.image.height * 4
+ buffer.copy(all, o, f.image.pixels, 0, n)
+ o += n
+ end
+ globalTrans = hasTransparency(all, npx)
+ local pal = Quantize.palette(all, npx, 1, if globalTrans then maxColors - 1 else maxColors, qopts)
+ if #pal == 0 then
+ pal = { { 0, 0, 0, 255 } }
+ end
+ if globalTrans then
+ table.insert(pal, { 0, 0, 0, 0 })
+ end
+ globalPal = pal
+ end
+ local w = Bytes.writer(img.width * img.height + 1024)
+ w:string("GIF89a")
+ w:u16le(img.width)
+ w:u16le(img.height)
+ if globalPal then
+ w:u8(0x80 + 0x70 + (tableBits(#globalPal) - 1))
+ w:u8(0)
+ w:u8(0)
+ writeTable(w, globalPal)
+ else
+ w:u8(0x70)
+ w:u8(0)
+ w:u8(0)
+ end
+ if animated and loops ~= 1 then
+ w:u8(0x21)
+ w:u8(0xFF)
+ w:u8(11)
+ w:string("NETSCAPE2.0")
+ w:u8(3)
+ w:u8(1)
+ w:u16le(if loops == 0 then 0 else loops - 1)
+ w:u8(0)
+ end
+ local text = img.meta and img.meta.text
+ local comment = text and (text.comment or text.Comment)
+ if type(comment) == "string" and #comment > 0 then
+ w:u8(0x21)
+ w:u8(0xFE)
+ for i = 1, #comment, 255 do
+ local part = string.sub(comment, i, i + 254)
+ w:u8(#part)
+ w:string(part)
+ end
+ w:u8(0)
+ end
+ for _, f in list do
+ local fi = f.image
+ local fw, fh = fi.width, fi.height
+ local n = fw * fh
+ local pal: { { number } }
+ local tidx: number? = nil
+ if globalPal then
+ pal = globalPal
+ if globalTrans then
+ tidx = #pal - 1
+ end
+ else
+ local tr = hasTransparency(fi.pixels, n)
+ pal = Quantize.palette(fi.pixels, fw, fh, if tr then maxColors - 1 else maxColors, qopts)
+ if #pal == 0 then
+ pal = { { 0, 0, 0, 255 } }
+ end
+ if tr then
+ table.insert(pal, { 0, 0, 0, 0 })
+ tidx = #pal - 1
+ end
+ end
+ local idx = Quantize.map(fi.pixels, fw, fh, pal, { dither = dither, transparentIndex = tidx })
+ -- the Graphic Control Extension: always for animations, else only for transparency
+ if animated or tidx then
+ local d = DISPOSE_CODE[f.dispose or "none"] or 1
+ w:u8(0x21)
+ w:u8(0xF9)
+ w:u8(4)
+ w:u8(d * 4 + (if tidx then 1 else 0))
+ w:u16le(math.clamp(math.floor((f.delay or 0) * 100 + 0.5), 0, 65535))
+ w:u8(tidx or 0)
+ w:u8(0)
+ end
+ w:u8(0x2C)
+ w:u16le(f.x or 0)
+ w:u16le(f.y or 0)
+ w:u16le(fw)
+ w:u16le(fh)
+ local bits
+ if globalPal then
+ w:u8(0)
+ bits = tableBits(#globalPal)
+ else
+ bits = tableBits(#pal)
+ w:u8(0x80 + bits - 1)
+ writeTable(w, pal)
+ end
+ local mc = math.max(2, bits)
+ w:u8(mc)
+ local codes = Lzw.encode(idx, 0, n, "gif", mc)
+ local cl = buffer.len(codes)
+ local p = 0
+ while p < cl do
+ local l = math.min(255, cl - p)
+ w:u8(l)
+ w:bytes(codes, p, l)
+ p += l
+ end
+ w:u8(0)
+ end
+ w:u8(0x3B)
+ return w:finish(), nil
+end
+
+return Gif
diff --git a/src/Formats/image/hdr/Codec.luau b/src/Formats/image/hdr/Codec.luau
new file mode 100644
index 0000000..7f97f5e
--- /dev/null
+++ b/src/Formats/image/hdr/Codec.luau
@@ -0,0 +1,219 @@
+--!strict
+--!native
+--!optimize 2
+-- image/hdr/Codec: Radiance RGBE scanlines (native; never throws). Written from the Radiance file format notes
+-- (Greg Ward, "Real Pixels", Graphics Gems II) and Bruce Walter's rgbe.c conventions: flat pixels, old-style RLE
+-- (1, 1, 1, n repeats the previous pixel, shifted by 8 for consecutive markers) and new-style RLE (2, 2, width, then
+-- four run-length coded channel planes). RGBE -> float is mantissa * 2^(e - 136), as rgbe.c, stb_image and
+-- ImageMagick (no +0.5 offset); float -> RGBE as rgbe.c float2rgbe (frexp). Every read is bounds-checked.
+local readu8, writeu8, writef32, readf32 = buffer.readu8, buffer.writeu8, buffer.writef32, buffer.readf32
+local frexp = math.frexp
+
+local Codec = {}
+
+-- readLine(b, p, limit, w, row) -> new position | nil, message: one scanline into row (w * 4 RGBE bytes)
+function Codec.readLine(b: buffer, p: number, limit: number, w: number, row: buffer): (number?, string?)
+ if w >= 8 and w <= 32767 and p + 4 <= limit and readu8(b, p) == 2 and readu8(b, p + 1) == 2 and readu8(b, p + 2) < 128 then
+ if readu8(b, p + 2) * 256 + readu8(b, p + 3) ~= w then
+ return nil, "scanline width mismatch"
+ end
+ p += 4
+ for c = 0, 3 do
+ local x = 0
+ while x < w do
+ if p >= limit then
+ return nil, "truncated"
+ end
+ local n = readu8(b, p)
+ p += 1
+ if n > 128 then
+ n -= 128
+ if x + n > w or p >= limit then
+ return nil, if p >= limit then "truncated" else "bad run"
+ end
+ local v = readu8(b, p)
+ p += 1
+ for i = x, x + n - 1 do
+ writeu8(row, i * 4 + c, v)
+ end
+ else
+ if n == 0 or x + n > w then
+ return nil, "bad count"
+ end
+ if p + n > limit then
+ return nil, "truncated"
+ end
+ for i = x, x + n - 1 do
+ writeu8(row, i * 4 + c, readu8(b, p))
+ p += 1
+ end
+ end
+ x += n
+ end
+ end
+ return p, nil
+ end
+ -- flat pixels, with old-style runs
+ local x = 0
+ local shift = 0
+ while x < w do
+ if p + 4 > limit then
+ return nil, "truncated"
+ end
+ local r, g, bl, e = readu8(b, p), readu8(b, p + 1), readu8(b, p + 2), readu8(b, p + 3)
+ p += 4
+ if r == 1 and g == 1 and bl == 1 then
+ if x == 0 then
+ return nil, "run at the start of a scanline"
+ end
+ local n = e * 2 ^ shift
+ if x + n > w then
+ return nil, "bad run"
+ end
+ local q = (x - 1) * 4
+ local pr, pg, pb, pe = readu8(row, q), readu8(row, q + 1), readu8(row, q + 2), readu8(row, q + 3)
+ for i = x, x + n - 1 do
+ writeu8(row, i * 4, pr)
+ writeu8(row, i * 4 + 1, pg)
+ writeu8(row, i * 4 + 2, pb)
+ writeu8(row, i * 4 + 3, pe)
+ end
+ x += n
+ shift += 8
+ if shift > 24 then
+ return nil, "bad run"
+ end
+ else
+ writeu8(row, x * 4, r)
+ writeu8(row, x * 4 + 1, g)
+ writeu8(row, x * 4 + 2, bl)
+ writeu8(row, x * 4 + 3, e)
+ x += 1
+ shift = 0
+ end
+ end
+ return p, nil
+end
+
+-- toFloat(row, n, out, offsets): n RGBE pixels -> rgbaf32 at out byte offsets dest(i) = base + i * step
+function Codec.toFloat(row: buffer, n: number, out: buffer, base: number, step: number)
+ for i = 0, n - 1 do
+ local q = i * 4
+ local e = readu8(row, q + 3)
+ local o = base + i * step
+ if e == 0 then
+ writef32(out, o, 0)
+ writef32(out, o + 4, 0)
+ writef32(out, o + 8, 0)
+ else
+ local f = 2 ^ (e - 136)
+ writef32(out, o, readu8(row, q) * f)
+ writef32(out, o + 4, readu8(row, q + 1) * f)
+ writef32(out, o + 8, readu8(row, q + 2) * f)
+ end
+ writef32(out, o + 12, 1)
+ end
+end
+
+-- fromFloat(px, y, w, row): row y of an rgbaf32 image -> w RGBE pixels (rgbe.c float2rgbe)
+function Codec.fromFloat(px: buffer, y: number, w: number, row: buffer)
+ for x = 0, w - 1 do
+ local q = (y * w + x) * 16
+ local r, g, b = readf32(px, q), readf32(px, q + 4), readf32(px, q + 8)
+ if r ~= r or r < 0 then
+ r = 0
+ end
+ if g ~= g or g < 0 then
+ g = 0
+ end
+ if b ~= b or b < 0 then
+ b = 0
+ end
+ local v = math.max(r, g, b)
+ local o = x * 4
+ if v < 1e-32 or v == math.huge then
+ if v == math.huge then
+ -- clamp infinities to the largest RGBE value
+ writeu8(row, o, if r == math.huge then 255 else 0)
+ writeu8(row, o + 1, if g == math.huge then 255 else 0)
+ writeu8(row, o + 2, if b == math.huge then 255 else 0)
+ writeu8(row, o + 3, 255)
+ else
+ writeu8(row, o, 0)
+ writeu8(row, o + 1, 0)
+ writeu8(row, o + 2, 0)
+ writeu8(row, o + 3, 0)
+ end
+ else
+ local m, e = frexp(v)
+ if e > 127 then
+ writeu8(row, o, 255)
+ writeu8(row, o + 1, 255)
+ writeu8(row, o + 2, 255)
+ writeu8(row, o + 3, 255)
+ else
+ local s = m * 256 / v
+ writeu8(row, o, math.min(255, math.floor(r * s)))
+ writeu8(row, o + 1, math.min(255, math.floor(g * s)))
+ writeu8(row, o + 2, math.min(255, math.floor(b * s)))
+ writeu8(row, o + 3, e + 128)
+ end
+ end
+ end
+end
+
+-- writeLine(row, w, out, o) -> new offset: new-style RLE (rgbe.c RGBE_WriteBytes_RLE); out needs w * 4 + w + 8
+function Codec.writeLine(row: buffer, w: number, out: buffer, o: number): number
+ writeu8(out, o, 2)
+ writeu8(out, o + 1, 2)
+ writeu8(out, o + 2, w // 256)
+ writeu8(out, o + 3, w % 256)
+ o += 4
+ for c = 0, 3 do
+ local cur = 0
+ while cur < w do
+ -- find the next run of at least 4
+ local begRun = cur
+ local runCount = 0
+ local oldRun = 0
+ while runCount < 4 and begRun < w do
+ begRun += runCount
+ oldRun = runCount
+ runCount = 1
+ if begRun < w then
+ local v = readu8(row, begRun * 4 + c)
+ while begRun + runCount < w and runCount < 127 and readu8(row, (begRun + runCount) * 4 + c) == v do
+ runCount += 1
+ end
+ end
+ end
+ -- a short run just before the long one
+ if oldRun > 1 and oldRun == begRun - cur then
+ writeu8(out, o, 128 + oldRun)
+ writeu8(out, o + 1, readu8(row, cur * 4 + c))
+ o += 2
+ cur = begRun
+ end
+ -- raw bytes up to the run
+ while cur < begRun do
+ local n = math.min(begRun - cur, 128)
+ writeu8(out, o, n)
+ o += 1
+ for i = cur, cur + n - 1 do
+ writeu8(out, o, readu8(row, i * 4 + c))
+ o += 1
+ end
+ cur += n
+ end
+ if runCount >= 4 then
+ writeu8(out, o, 128 + runCount)
+ writeu8(out, o + 1, readu8(row, begRun * 4 + c))
+ o += 2
+ cur += runCount
+ end
+ end
+ end
+ return o
+end
+
+return Codec
diff --git a/src/Formats/image/hdr/init.luau b/src/Formats/image/hdr/init.luau
new file mode 100644
index 0000000..ceb84a3
--- /dev/null
+++ b/src/Formats/image/hdr/init.luau
@@ -0,0 +1,234 @@
+--!strict
+-- image/hdr: Radiance HDR / RGBE (.hdr, .pic), written from the Radiance file format notes and rgbe.c conventions.
+-- Decode: "#?RADIANCE" / "#?RGBE" (any "#?" program name) headers, FORMAT=32-bit_rle_rgbe, EXPOSURE (the product of
+-- every EXPOSURE line, kept in meta.exposure, not applied), other header lines in meta.text, the eight resolution
+-- orientations (-Y +X standard, +Y, -X and the X-major ones), flat, old-style RLE and new-style RLE scanlines.
+-- opts.native gives the linear rgbaf32 values (alpha 1); the default rgba8 is a display conversion:
+-- round(clamp(v, 0, 1) ^ (1 / 2.2) * 255) per channel. Encode: rgbaf32 (or rgba8 through the inverse curve) to a
+-- -Y +X file with new-style RLE (flat scanlines for widths outside 8..32767).
+-- Not supported: FORMAT=32-bit_rle_xyze (CIE XYZ files: UNSUPPORTED), PRIMARIES / COLORCORR (ignored).
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Types = require("@formats/Types")
+local Codec = require("@formats/image/hdr/Codec")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Hdr = {
+ name = "hdr",
+ category = "image",
+ extensions = { "hdr", "pic", "rgbe" },
+ mime = { "image/vnd.radiance", "image/x-hdr" },
+ deps = { "core/Err", "core/Bytes", "Types" },
+ caps = { decode = true, encode = true, alpha = false, float = true, depths = { 32 } },
+}
+
+-- ------------------------------------------------------------------------------------------------ types
+export type DecodeOptions = {
+ native: boolean?, -- linear rgbaf32 (default false: rgba8 through a 1 / 2.2 display gamma)
+ maxPixels: number?, -- refuse larger images (default 2^26)
+}
+export type EncodeOptions = {
+ rle: boolean?, -- new-style RLE scanlines (default true)
+ exposure: number?, -- write an EXPOSURE line (default meta.exposure when not 1)
+}
+
+-- ------------------------------------------------------------------------------------------------ constants
+local GAMMA = 1 / 2.2
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Hdr.sniff(r: Bytes.Reader): number
+ local s = r:peek(10)
+ if s == "#?RADIANCE" then
+ return 1
+ end
+ if string.sub(s, 1, 6) == "#?RGBE" then
+ return 1
+ end
+ if string.sub(s, 1, 2) == "#?" and string.match(s, "^#%?%u") then
+ return 0.5
+ end
+ return 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+function Hdr.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
+ local maxPixels = opts and opts.maxPixels or 2 ^ 26
+ local b, limit = r.buf, r.limit
+ local p = r.base
+ -- header lines up to the first empty one
+ local function line(): string?
+ local s = p
+ while p < limit and buffer.readu8(b, p) ~= 10 do
+ p += 1
+ end
+ if p >= limit then
+ return nil
+ end
+ local l = buffer.readstring(b, s, p - s)
+ p += 1
+ return l
+ end
+ local first = line()
+ if not first or string.sub(first, 1, 2) ~= "#?" then
+ return nil, Err.new(Err.CORRUPT, "not a Radiance file (no #? line)", r.base)
+ end
+ local exposure = 1
+ local format = nil
+ local text: { [string]: string } = {}
+ while true do
+ local l = line()
+ if l == nil then
+ return nil, Err.new(Err.TRUNCATED, "header ends early", p)
+ end
+ l = string.gsub(l, "\r$", "")
+ if l == "" then
+ break
+ end
+ local k, v = string.match(l, "^%s*([%w_%-]+)%s*=%s*(.-)%s*$")
+ if k == "FORMAT" then
+ format = v
+ elseif k == "EXPOSURE" then
+ local e = tonumber(v)
+ if e and e > 0 then
+ exposure *= e
+ end
+ elseif k then
+ text[k] = v :: string
+ end
+ end
+ if format and format ~= "32-bit_rle_rgbe" then
+ return nil, Err.new(Err.UNSUPPORTED, "FORMAT=" .. format)
+ end
+ local res = line()
+ if not res then
+ return nil, Err.new(Err.TRUNCATED, "no resolution line", p)
+ end
+ local s1, a1, n1, s2, a2, n2 = string.match(res, "^%s*([%+%-])([XY])%s+(%d+)%s+([%+%-])([XY])%s+(%d+)%s*$")
+ if not s1 or a1 == a2 or #n1 > 9 or #n2 > 9 then
+ return nil, Err.new(Err.CORRUPT, "bad resolution line", p)
+ end
+ local outer, inner = tonumber(n1) :: number, tonumber(n2) :: number
+ local w, h = if a1 == "Y" then inner else outer, if a1 == "Y" then outer else inner
+ if w < 1 or h < 1 then
+ return nil, Err.new(Err.CORRUPT, "zero size")
+ end
+ if w * h > maxPixels then
+ return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
+ end
+ local img = Types.Image.new(w, h, "rgbaf32")
+ local px = img.pixels
+ local row = buffer.create(inner * 4)
+ local truncated = false
+ for i = 0, outer - 1 do
+ local np, err = Codec.readLine(b, p, limit, inner, row)
+ if not np then
+ if err == "truncated" then
+ truncated = true
+ break
+ end
+ return nil, Err.new(Err.CORRUPT, tostring(err), p)
+ end
+ p = np
+ -- where scanline i, pixel j lands: Y decreasing ("-Y") = top first, X increasing ("+X") = left first
+ local base, step
+ if a1 == "Y" then
+ local y = if s1 == "-" then i else h - 1 - i
+ if s2 == "+" then
+ base, step = y * w * 16, 16
+ else
+ base, step = (y * w + w - 1) * 16, -16
+ end
+ else
+ local x = if s1 == "+" then i else w - 1 - i
+ if s2 == "-" then
+ base, step = x * 16, w * 16
+ else
+ base, step = ((h - 1) * w + x) * 16, -w * 16
+ end
+ end
+ Codec.toFloat(row, inner, px, base, step)
+ end
+ if not (opts and opts.native) then
+ local o = Types.Image.new(w, h, "rgba8")
+ for i = 0, w * h - 1 do
+ for c = 0, 2 do
+ local v = buffer.readf32(px, i * 16 + c * 4)
+ buffer.writeu8(o.pixels, i * 4 + c, math.floor(math.clamp(v, 0, 1) ^ GAMMA * 255 + 0.5))
+ end
+ buffer.writeu8(o.pixels, i * 4 + 3, 255)
+ end
+ o.meta = img.meta
+ img = o
+ end
+ img.meta.exposure = exposure
+ img.meta.colorSpace = "linear"
+ if next(text) then
+ img.meta.text = text
+ end
+ if truncated then
+ img.meta.truncated = true
+ end
+ img.meta.source = { format = "hdr", bitDepth = 32, colorType = "rgbe", program = string.sub(first, 3), orientation = string.format("%s%s %s%s", s1, a1, s2, a2) }
+ return img, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+function Hdr.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
+ if type(img) ~= "table" or type(img.pixels) ~= "buffer" or (img.format ~= "rgbaf32" and img.format ~= "rgba8") then
+ return nil, Err.new(Err.ARG, "needs an rgbaf32 or rgba8 Image")
+ end
+ local w, h = img.width, img.height
+ local bpp = if img.format == "rgbaf32" then 16 else 4
+ if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < w * h * bpp then
+ return nil, Err.new(Err.ARG, "bad image size or pixel buffer")
+ end
+ local o: any = opts or {}
+ local px = img.pixels
+ if bpp == 4 then
+ -- rgba8 through the inverse of the decoder's display curve
+ local lut = table.create(256, 0)
+ for v = 0, 255 do
+ lut[v + 1] = (v / 255) ^ 2.2
+ end
+ px = buffer.create(w * h * 16)
+ for i = 0, w * h - 1 do
+ for c = 0, 2 do
+ buffer.writef32(px, i * 16 + c * 4, lut[buffer.readu8(img.pixels, i * 4 + c) + 1])
+ end
+ buffer.writef32(px, i * 16 + 12, 1)
+ end
+ end
+ local exposure = o.exposure or (img.meta and img.meta.exposure)
+ local head = "#?RADIANCE\n# written by formats-luau\nFORMAT=32-bit_rle_rgbe\n"
+ if type(exposure) == "number" and exposure > 0 and exposure ~= 1 then
+ head ..= string.format("EXPOSURE=%.9g\n", exposure)
+ end
+ head ..= string.format("\n-Y %d +X %d\n", h, w)
+ local rle = o.rle ~= false and w >= 8 and w <= 32767
+ local out = buffer.create(#head + h * (w * 5 + 8))
+ buffer.writestring(out, 0, head)
+ local op = #head
+ local row = buffer.create(w * 4)
+ for y = 0, h - 1 do
+ Codec.fromFloat(px, y, w, row)
+ if rle then
+ op = Codec.writeLine(row, w, out, op)
+ else
+ buffer.copy(out, op, row, 0, w * 4)
+ for x = 0, w - 1 do
+ -- 1, 1, 1 would read as an old-style run marker
+ if buffer.readu8(out, op + x * 4) == 1 and buffer.readu8(out, op + x * 4 + 1) == 1 and buffer.readu8(out, op + x * 4 + 2) == 1 then
+ buffer.writeu8(out, op + x * 4 + 2, 0)
+ end
+ end
+ op += w * 4
+ end
+ end
+ local res = buffer.create(op)
+ buffer.copy(res, 0, out, 0, op)
+ return res, nil
+end
+
+return Hdr
diff --git a/src/Formats/image/ico/Dib.luau b/src/Formats/image/ico/Dib.luau
new file mode 100644
index 0000000..447fa5e
--- /dev/null
+++ b/src/Formats/image/ico/Dib.luau
@@ -0,0 +1,106 @@
+--!strict
+--!native
+--!optimize 2
+-- image/ico/Dib: the BMP device-independent bitmaps inside ICO / CUR entries (native; never throws). Written from
+-- the Microsoft ICO / BITMAPINFOHEADER documentation: a colour (XOR) bitmap of 1 / 4 / 8 / 16 (5-5-5) / 24 / 32-bit
+-- pixels, bottom-up rows padded to 4 bytes, then a 1-bit AND mask (1 = transparent). 32-bit entries use their alpha
+-- channel unless it is all zero (old icons), in which case the AND mask decides.
+local readu8, readu16, readu32, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu32
+
+local Dib = {}
+
+-- decode(b, p, e, w, h, bpp, pal, palN, out) -> ok, message: the XOR + AND bitmaps at b[p, e) into rgba8 out
+function Dib.decode(b: buffer, p: number, e: number, w: number, h: number, bpp: number, pal: buffer, palN: number, out: buffer): (boolean, string?)
+ local stride = ((w * bpp + 31) // 32) * 4
+ local maskStride = ((w + 31) // 32) * 4
+ if p + stride * h > e then
+ return false, "colour bitmap runs past the entry"
+ end
+ local hasMask = p + stride * h + maskStride * h <= e
+ local anyAlpha = false
+ for y = 0, h - 1 do
+ local row = p + (h - 1 - y) * stride
+ for x = 0, w - 1 do
+ local v
+ if bpp == 32 then
+ v = readu8(b, row + x * 4 + 2) + readu8(b, row + x * 4 + 1) * 256 + readu8(b, row + x * 4) * 65536 + readu8(b, row + x * 4 + 3) * 16777216
+ if v >= 16777216 then
+ anyAlpha = true
+ end
+ elseif bpp == 24 then
+ v = readu8(b, row + x * 3 + 2) + readu8(b, row + x * 3 + 1) * 256 + readu8(b, row + x * 3) * 65536 + 0xFF000000
+ elseif bpp == 16 then
+ local s = readu16(b, row + x * 2)
+ local r, g, bl = (s // 1024) % 32, (s // 32) % 32, s % 32
+ v = (r * 255 + 15) // 31 + ((g * 255 + 15) // 31) * 256 + ((bl * 255 + 15) // 31) * 65536 + 0xFF000000
+ else
+ local bit = x * bpp
+ local byte = readu8(b, row + bit // 8)
+ local idx = (byte // 2 ^ (8 - bpp - bit % 8)) % 2 ^ bpp
+ v = if idx < palN then readu32(pal, idx * 4) else 0xFF000000
+ end
+ writeu32(out, (y * w + x) * 4, v)
+ end
+ end
+ if bpp == 32 and anyAlpha then
+ return true, nil
+ end
+ if hasMask then
+ local mp = p + stride * h
+ for y = 0, h - 1 do
+ local row = mp + (h - 1 - y) * maskStride
+ for x = 0, w - 1 do
+ local o = (y * w + x) * 4
+ local px = readu32(out, o) % 16777216
+ if (readu8(b, row + x // 8) // 2 ^ (7 - x % 8)) % 2 == 1 then
+ writeu32(out, o, px) -- transparent
+ else
+ writeu32(out, o, px + 0xFF000000)
+ end
+ end
+ end
+ elseif bpp == 32 then
+ -- no alpha and no mask: opaque
+ for i = 0, w * h - 1 do
+ writeu32(out, i * 4, readu32(out, i * 4) % 16777216 + 0xFF000000)
+ end
+ end
+ return true, nil
+end
+
+-- encode(px, w, h, out, o) -> new offset: rgba8 as a 32-bit BGRA bitmap (bottom-up) + an AND mask (alpha 0 = 1).
+-- out needs room for w * h * 4 + maskStride * h bytes.
+function Dib.encode(px: buffer, w: number, h: number, out: buffer, o: number): number
+ for y = h - 1, 0, -1 do
+ for x = 0, w - 1 do
+ local q = (y * w + x) * 4
+ buffer.writeu8(out, o, readu8(px, q + 2))
+ buffer.writeu8(out, o + 1, readu8(px, q + 1))
+ buffer.writeu8(out, o + 2, readu8(px, q))
+ buffer.writeu8(out, o + 3, readu8(px, q + 3))
+ o += 4
+ end
+ end
+ local maskStride = ((w + 31) // 32) * 4
+ for y = h - 1, 0, -1 do
+ local acc, nb, written = 0, 0, 0
+ for x = 0, w - 1 do
+ acc = acc * 2 + (if readu8(px, (y * w + x) * 4 + 3) == 0 then 1 else 0)
+ nb += 1
+ if nb == 8 then
+ buffer.writeu8(out, o + written, acc)
+ written += 1
+ acc, nb = 0, 0
+ end
+ end
+ if nb > 0 then
+ buffer.writeu8(out, o + written, acc * 2 ^ (8 - nb))
+ written += 1
+ end
+ buffer.fill(out, o + written, 0, maskStride - written)
+ o += maskStride
+ end
+ return o
+end
+
+return Dib
diff --git a/src/Formats/image/ico/init.luau b/src/Formats/image/ico/init.luau
new file mode 100644
index 0000000..9fc05a1
--- /dev/null
+++ b/src/Formats/image/ico/init.luau
@@ -0,0 +1,282 @@
+--!strict
+-- image/ico: Windows icons and cursors (ICO / CUR), written from Microsoft's ICO format documentation. Decode: every
+-- directory entry, as a BMP DIB (1 / 4 / 8 / 16 / 24 / 32-bit with a colour table and the AND mask; 32-bit alpha) or
+-- an embedded PNG, decoded through the api hook opts.decodeImage (F.load supplies it; without it PNG entries are
+-- skipped, and a file of PNG entries only returns UNSUPPORTED). The image is the largest entry (then the deepest);
+-- img.frames lists every decoded entry in file order (Types.Frame, each frame image with meta.source.bitDepth / png
+-- and, for cursors, meta.hotspot = { x, y }). Encode: the image, or every img.frames image (each up to 256 x 256), as
+-- 32-bit DIB entries with an AND mask; 256-pixel entries (or all with opts.png) as PNG through opts.encodeImage when it
+-- is there; a cursor (CUR) with opts.cursor or when the image has meta.hotspot.
+-- Not supported: resizing to a set of icon sizes (do that with ops/ImageOps first), DIB compression (BI_BITFIELDS
+-- 16 / 32-bit is read as 5-5-5 / BGRA), the obsolete 2-colour planes.
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Types = require("@formats/Types")
+local Dib = require("@formats/image/ico/Dib")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Ico = {
+ name = "ico",
+ category = "image",
+ extensions = { "ico", "cur" },
+ mime = { "image/vnd.microsoft.icon", "image/x-icon" },
+ deps = { "core/Err", "core/Bytes", "Types" },
+ caps = { decode = true, encode = true, alpha = true, frames = true, depths = { 1, 4, 8, 16, 24, 32 } },
+}
+
+-- ------------------------------------------------------------------------------------------------ types
+export type DecodeOptions = {
+ decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?, -- decodes PNG entries (the api passes one)
+ maxPixels: number?, -- refuse larger entries (default 2^26)
+}
+export type EncodeOptions = {
+ encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?, -- writes PNG entries (the api passes one)
+ png: boolean?, -- every entry as PNG (needs encodeImage; default: only 256-pixel entries, when it exists)
+ cursor: boolean?, -- write a CUR (default: when the image has meta.hotspot)
+}
+
+-- ------------------------------------------------------------------------------------------------ constants
+local PNG_SIG = "\137PNG\r\n\26\n"
+local readu8 = buffer.readu8
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Ico.sniff(r: Bytes.Reader): number
+ if r:remaining() < 22 then
+ return 0
+ end
+ local b, o = r.buf, r.pos
+ local typ = buffer.readu16(b, o + 2)
+ local count = buffer.readu16(b, o + 4)
+ if buffer.readu16(b, o) ~= 0 or (typ ~= 1 and typ ~= 2) or count == 0 then
+ return 0
+ end
+ -- the first entry: reserved byte 0, a size and offset inside the file
+ local size, off = buffer.readu32(b, o + 14), buffer.readu32(b, o + 18)
+ if readu8(b, o + 9) ~= 0 or size == 0 or off < 6 + count * 16 then
+ return 0
+ end
+ return 0.8
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+local function le16(b: buffer, p: number): number
+ return buffer.readu16(b, p)
+end
+local function le32(b: buffer, p: number): number
+ return buffer.readu32(b, p)
+end
+
+function Ico.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
+ local maxPixels = opts and opts.maxPixels or 2 ^ 26
+ local decodeImage = opts and opts.decodeImage
+ local b, base, limit = r.buf, r.base, r.limit
+ if limit - base < 6 then
+ return nil, Err.new(Err.TRUNCATED, "short header", base)
+ end
+ local typ, count = le16(b, base + 2), le16(b, base + 4)
+ if le16(b, base) ~= 0 or (typ ~= 1 and typ ~= 2) then
+ return nil, Err.new(Err.CORRUPT, "not an ICO / CUR file", base)
+ end
+ if count == 0 then
+ return nil, Err.new(Err.CORRUPT, "no images", base)
+ end
+ if base + 6 + count * 16 > limit then
+ return nil, Err.new(Err.TRUNCATED, "directory runs past the end", base)
+ end
+ local frames: { Types.Frame } = {}
+ local best: Types.Image? = nil
+ local bestScore = -1
+ local skipped, lastErr = 0, nil :: Err.Err?
+ for i = 0, count - 1 do
+ local d = base + 6 + i * 16
+ local dw, dh = readu8(b, d), readu8(b, d + 1)
+ dw = if dw == 0 then 256 else dw
+ dh = if dh == 0 then 256 else dh
+ local f1, f2 = le16(b, d + 4), le16(b, d + 6)
+ local size, off = le32(b, d + 8), le32(b, d + 12)
+ local p, e = base + off, base + off + size
+ local img: Types.Image? = nil
+ local depth = 0
+ local isPng = false
+ if off < 6 or p >= limit then
+ lastErr = Err.new(Err.TRUNCATED, "entry " .. (i + 1) .. " lies past the end", d)
+ else
+ e = math.min(e, limit)
+ if e - p >= 8 and buffer.readstring(b, p, 8) == PNG_SIG then
+ isPng = true
+ depth = 32
+ if decodeImage then
+ local sub = buffer.create(e - p)
+ buffer.copy(sub, 0, b, p, e - p)
+ local ok, pimg, perr = pcall(decodeImage, sub)
+ if ok and pimg and pimg.format == "rgba8" then
+ img = pimg
+ else
+ lastErr = if ok and perr then perr else Err.new(Err.CORRUPT, "entry " .. (i + 1) .. ": bad PNG")
+ end
+ else
+ lastErr = Err.new(Err.UNSUPPORTED, "PNG entries need opts.decodeImage (F.load passes it)")
+ end
+ elseif e - p >= 40 then
+ local hs = le32(b, p)
+ local bw = buffer.readi32(b, p + 4)
+ local bh = buffer.readi32(b, p + 8)
+ local bpp = le16(b, p + 14)
+ local clrUsed = le32(b, p + 32)
+ local w = if bw > 0 then bw else dw
+ local h = if bh ~= 0 then math.abs(bh) // 2 else dh
+ if hs < 12 or hs > e - p or w < 1 or h < 1 or w > 4096 or h > 4096 then
+ lastErr = Err.new(Err.CORRUPT, "entry " .. (i + 1) .. ": bad bitmap header", p)
+ elseif bpp ~= 1 and bpp ~= 4 and bpp ~= 8 and bpp ~= 16 and bpp ~= 24 and bpp ~= 32 then
+ lastErr = Err.new(Err.UNSUPPORTED, "entry " .. (i + 1) .. ": " .. bpp .. "-bit bitmap", p)
+ elseif w * h > maxPixels then
+ return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
+ else
+ depth = bpp
+ local q = p + hs
+ local palN = 0
+ local pal = buffer.create(4)
+ if bpp <= 8 then
+ palN = if clrUsed > 0 and clrUsed < 2 ^ bpp then clrUsed else 2 ^ bpp
+ if q + palN * 4 > e then
+ palN = 0
+ lastErr = Err.new(Err.TRUNCATED, "entry " .. (i + 1) .. ": colour table runs past the entry", q)
+ else
+ pal = buffer.create(palN * 4)
+ for k = 0, palN - 1 do
+ local c = q + k * 4
+ buffer.writeu32(pal, k * 4, readu8(b, c + 2) + readu8(b, c + 1) * 256 + readu8(b, c) * 65536 + 0xFF000000)
+ end
+ q += palN * 4
+ end
+ end
+ if bpp > 8 or palN > 0 then
+ if bpp == 16 and le32(b, p + 16) == 3 then
+ q += 12 -- BI_BITFIELDS masks (assumed 5-5-5)
+ end
+ local out = Types.Image.new(w, h, "rgba8")
+ local ok, msg = Dib.decode(b, q, e, w, h, bpp, pal, palN, out.pixels)
+ if ok then
+ img = out
+ else
+ lastErr = Err.new(Err.TRUNCATED, "entry " .. (i + 1) .. ": " .. tostring(msg), q)
+ end
+ end
+ end
+ else
+ lastErr = Err.new(Err.TRUNCATED, "entry " .. (i + 1) .. " is too short", p)
+ end
+ end
+ if img then
+ local im = img :: Types.Image
+ im.meta.source = { format = "ico", bitDepth = depth, png = isPng, colorCount = readu8(b, d + 2) }
+ if typ == 2 then
+ im.meta.hotspot = { x = f1, y = f2 }
+ end
+ table.insert(frames, { image = im, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" })
+ local score = im.width * im.height * 64 + depth
+ if score > bestScore then
+ best, bestScore = im, score
+ end
+ else
+ skipped += 1
+ end
+ end
+ if not best then
+ return nil, lastErr or Err.new(Err.CORRUPT, "no decodable entry")
+ end
+ local main = best :: Types.Image
+ local img = Types.Image.new(main.width, main.height, "rgba8")
+ buffer.copy(img.pixels, 0, main.pixels)
+ if #frames > 1 then
+ img.frames = frames
+ end
+ img.meta.source = { format = "ico", type = if typ == 2 then "cur" else "ico", bitDepth = main.meta.source and main.meta.source.bitDepth, entries = count, skipped = skipped, png = main.meta.source and main.meta.source.png }
+ img.meta.hotspot = main.meta.hotspot
+ return img, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+function Ico.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
+ if type(img) ~= "table" then
+ return nil, Err.new(Err.ARG, "needs an Image")
+ end
+ local o: any = opts or {}
+ local list: { Types.Image } = {}
+ if type(img.frames) == "table" and #img.frames > 0 then
+ for _, f in img.frames do
+ table.insert(list, f.image)
+ end
+ else
+ list[1] = img
+ end
+ local cursor = o.cursor
+ if cursor == nil then
+ cursor = type(img.meta) == "table" and img.meta.hotspot ~= nil
+ end
+ local blobs: { buffer } = {}
+ for i, im in list do
+ if type(im) ~= "table" or im.format ~= "rgba8" or type(im.pixels) ~= "buffer" then
+ return nil, Err.new(Err.ARG, "entry " .. i .. ": needs an rgba8 Image")
+ end
+ local w, h = im.width, im.height
+ if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w > 256 or h > 256 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(im.pixels) < w * h * 4 then
+ return nil, Err.new(Err.ARG, "entry " .. i .. ": icons are 1..256 pixels per side")
+ end
+ local png = nil
+ if o.encodeImage and (o.png or w == 256 or h == 256) then
+ local ok, res, err = pcall(o.encodeImage, im, "png")
+ if not ok or not res then
+ return nil, if ok and err then err else Err.new(Err.ARG, "entry " .. i .. ": PNG encode failed")
+ end
+ png = res
+ elseif o.png then
+ return nil, Err.new(Err.ARG, "opts.png needs opts.encodeImage (F.save passes it)")
+ end
+ if png then
+ blobs[i] = png
+ else
+ local maskStride = ((w + 31) // 32) * 4
+ local n = 40 + w * h * 4 + maskStride * h
+ local d = buffer.create(n)
+ buffer.writeu32(d, 0, 40)
+ buffer.writei32(d, 4, w)
+ buffer.writei32(d, 8, h * 2)
+ buffer.writeu16(d, 12, 1)
+ buffer.writeu16(d, 14, 32)
+ buffer.writeu32(d, 20, w * h * 4 + maskStride * h)
+ Dib.encode(im.pixels, w, h, d, 40)
+ blobs[i] = d
+ end
+ end
+ local total = 6 + #list * 16
+ for _, bl in blobs do
+ total += buffer.len(bl)
+ end
+ local out = buffer.create(total)
+ buffer.writeu16(out, 2, if cursor then 2 else 1)
+ buffer.writeu16(out, 4, #list)
+ local off = 6 + #list * 16
+ for i, im in list do
+ local d = 6 + (i - 1) * 16
+ buffer.writeu8(out, d, im.width % 256)
+ buffer.writeu8(out, d + 1, im.height % 256)
+ if cursor then
+ local hs = (type(im.meta) == "table" and im.meta.hotspot) or (img.meta and img.meta.hotspot) or { x = 0, y = 0 }
+ buffer.writeu16(out, d + 4, math.clamp(math.floor(tonumber(hs.x) or 0), 0, 65535))
+ buffer.writeu16(out, d + 6, math.clamp(math.floor(tonumber(hs.y) or 0), 0, 65535))
+ else
+ buffer.writeu16(out, d + 4, 1)
+ buffer.writeu16(out, d + 6, 32)
+ end
+ buffer.writeu32(out, d + 8, buffer.len(blobs[i]))
+ buffer.writeu32(out, d + 12, off)
+ buffer.copy(out, off, blobs[i])
+ off += buffer.len(blobs[i])
+ end
+ return out, nil
+end
+
+return Ico
diff --git a/src/Formats/image/jpeg/Arith.luau b/src/Formats/image/jpeg/Arith.luau
new file mode 100644
index 0000000..a1044e2
--- /dev/null
+++ b/src/Formats/image/jpeg/Arith.luau
@@ -0,0 +1,414 @@
+--!strict
+--!native
+--!optimize 2
+-- 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].
+local readu8, writeu8, readi16, writei16 = buffer.readu8, buffer.writeu8, buffer.readi16, buffer.writei16
+local band, bxor = bit32.band, bit32.bxor
+
+local Arith = {}
+
+-- jaricom.c: Qe << 16 | Next_Index_MPS << 8 | Switch_MPS << 7 | Next_Index_LPS
+local TAB = buffer.create(114 * 4)
+do
+ local raw = {
+ { 0x5a1d, 1, 1, 1 }, { 0x2586, 14, 2, 0 }, { 0x1114, 16, 3, 0 }, { 0x080b, 18, 4, 0 }, { 0x03d8, 20, 5, 0 },
+ { 0x01da, 23, 6, 0 }, { 0x00e5, 25, 7, 0 }, { 0x006f, 28, 8, 0 }, { 0x0036, 30, 9, 0 }, { 0x001a, 33, 10, 0 },
+ { 0x000d, 35, 11, 0 }, { 0x0006, 9, 12, 0 }, { 0x0003, 10, 13, 0 }, { 0x0001, 12, 13, 0 }, { 0x5a7f, 15, 15, 1 },
+ { 0x3f25, 36, 16, 0 }, { 0x2cf2, 38, 17, 0 }, { 0x207c, 39, 18, 0 }, { 0x17b9, 40, 19, 0 }, { 0x1182, 42, 20, 0 },
+ { 0x0cef, 43, 21, 0 }, { 0x09a1, 45, 22, 0 }, { 0x072f, 46, 23, 0 }, { 0x055c, 48, 24, 0 }, { 0x0406, 49, 25, 0 },
+ { 0x0303, 51, 26, 0 }, { 0x0240, 52, 27, 0 }, { 0x01b1, 54, 28, 0 }, { 0x0144, 56, 29, 0 }, { 0x00f5, 57, 30, 0 },
+ { 0x00b7, 59, 31, 0 }, { 0x008a, 60, 32, 0 }, { 0x0068, 62, 33, 0 }, { 0x004e, 63, 34, 0 }, { 0x003b, 32, 35, 0 },
+ { 0x002c, 33, 9, 0 }, { 0x5ae1, 37, 37, 1 }, { 0x484c, 64, 38, 0 }, { 0x3a0d, 65, 39, 0 }, { 0x2ef1, 67, 40, 0 },
+ { 0x261f, 68, 41, 0 }, { 0x1f33, 69, 42, 0 }, { 0x19a8, 70, 43, 0 }, { 0x1518, 72, 44, 0 }, { 0x1177, 73, 45, 0 },
+ { 0x0e74, 74, 46, 0 }, { 0x0bfb, 75, 47, 0 }, { 0x09f8, 77, 48, 0 }, { 0x0861, 78, 49, 0 }, { 0x0706, 79, 50, 0 },
+ { 0x05cd, 48, 51, 0 }, { 0x04de, 50, 52, 0 }, { 0x040f, 50, 53, 0 }, { 0x0363, 51, 54, 0 }, { 0x02d4, 52, 55, 0 },
+ { 0x025c, 53, 56, 0 }, { 0x01f8, 54, 57, 0 }, { 0x01a4, 55, 58, 0 }, { 0x0160, 56, 59, 0 }, { 0x0125, 57, 60, 0 },
+ { 0x00f6, 58, 61, 0 }, { 0x00cb, 59, 62, 0 }, { 0x00ab, 61, 63, 0 }, { 0x008f, 61, 32, 0 }, { 0x5b12, 65, 65, 1 },
+ { 0x4d04, 80, 66, 0 }, { 0x412c, 81, 67, 0 }, { 0x37d8, 82, 68, 0 }, { 0x2fe8, 83, 69, 0 }, { 0x293c, 84, 70, 0 },
+ { 0x2379, 86, 71, 0 }, { 0x1edf, 87, 72, 0 }, { 0x1aa9, 87, 73, 0 }, { 0x174e, 72, 74, 0 }, { 0x1424, 72, 75, 0 },
+ { 0x119c, 74, 76, 0 }, { 0x0f6b, 74, 77, 0 }, { 0x0d51, 75, 78, 0 }, { 0x0bb6, 77, 79, 0 }, { 0x0a40, 77, 48, 0 },
+ { 0x5832, 80, 81, 1 }, { 0x4d1c, 88, 82, 0 }, { 0x438e, 89, 83, 0 }, { 0x3bdd, 90, 84, 0 }, { 0x34ee, 91, 85, 0 },
+ { 0x2eae, 92, 86, 0 }, { 0x299a, 93, 87, 0 }, { 0x2516, 86, 71, 0 }, { 0x5570, 88, 89, 1 }, { 0x4ca9, 95, 90, 0 },
+ { 0x44d9, 96, 91, 0 }, { 0x3e22, 97, 92, 0 }, { 0x3824, 99, 93, 0 }, { 0x32b4, 99, 94, 0 }, { 0x2e17, 93, 86, 0 },
+ { 0x56a8, 95, 96, 1 }, { 0x4f46, 101, 97, 0 }, { 0x47e5, 102, 98, 0 }, { 0x41cf, 103, 99, 0 }, { 0x3c3d, 104, 100, 0 },
+ { 0x375e, 99, 93, 0 }, { 0x5231, 105, 102, 0 }, { 0x4c0f, 106, 103, 0 }, { 0x4639, 107, 104, 0 }, { 0x415e, 103, 99, 0 },
+ { 0x5627, 105, 106, 1 }, { 0x50e7, 108, 107, 0 }, { 0x4b85, 109, 103, 0 }, { 0x5597, 110, 109, 0 }, { 0x504f, 111, 107, 0 },
+ { 0x5a10, 110, 111, 1 }, { 0x5522, 112, 109, 0 }, { 0x59eb, 112, 111, 1 }, { 0x5a1d, 113, 113, 0 },
+ }
+ for i, e in raw do
+ buffer.writeu16(TAB, (i - 1) * 4, e[1]) -- Qe
+ writeu8(TAB, (i - 1) * 4 + 2, e[4] * 128 + e[2]) -- Switch_MPS << 7 | Next_Index_LPS
+ writeu8(TAB, (i - 1) * 4 + 3, e[3]) -- Next_Index_MPS
+ end
+end
+
+local ZZ: buffer = buffer.create(80) -- set by Arith.init (Scan.ZIGZAG)
+
+local STATS = 1281
+local POW2 = buffer.create(8)
+for i = 0, 7 do
+ writeu8(POW2, i, 2 ^ i)
+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 C, A, CT = 0, 0, -16
+local st: buffer = buffer.create(STATS)
+
+local function decode(s: number): number
+ while A < 0x8000 do
+ CT -= 1
+ if CT < 0 then
+ local data = 0
+ if P < SEGEND then
+ data = readu8(D, P)
+ P += 1
+ else
+ OVER += 1
+ end
+ C = C * 256 + data
+ CT += 8
+ if CT < 0 then
+ CT += 1
+ if CT == 0 then
+ A = 0x8000
+ end
+ end
+ end
+ A *= 2
+ end
+ local sv = readu8(st, s)
+ local t = band(sv, 0x7F) * 4
+ local qe = buffer.readu16(TAB, t)
+ local nl = readu8(TAB, t + 2)
+ local nm = readu8(TAB, t + 3)
+ local temp = A - qe
+ A = temp
+ temp *= readu8(POW2, CT)
+ if C >= temp then
+ C -= temp
+ if A < qe then
+ A = qe
+ writeu8(st, s, bxor(band(sv, 0x80), nm))
+ else
+ A = qe
+ writeu8(st, s, bxor(band(sv, 0x80), nl))
+ sv = bxor(sv, 0x80)
+ end
+ elseif A < 0x8000 then
+ if A < qe then
+ writeu8(st, s, bxor(band(sv, 0x80), nl))
+ sv = bxor(sv, 0x80)
+ else
+ writeu8(st, s, bxor(band(sv, 0x80), nm))
+ end
+ end
+ return if sv >= 0x80 then 1 else 0
+end
+
+local function i16(v: number): number
+ v = band(v, 0xFFFF)
+ return if v >= 0x8000 then v - 0x10000 else v
+end
+
+export type ArithComp = {
+ coef: buffer,
+ bpl: number,
+ h: number,
+ v: number,
+ bw: number,
+ bh: number,
+ dcTbl: number, -- 0..3
+ acTbl: number,
+ pred: number,
+ ctx: number,
+}
+
+export type ArithParams = {
+ comps: { ArithComp },
+ mcusX: number,
+ mcusY: number,
+ ri: number,
+ mode: number, -- 0 sequential, 1 DC first, 2 DC refine, 3 AC first, 4 AC refine
+ ss: number,
+ se: number,
+ al: number,
+ dcL: { number }, -- conditioning per table (DAC), 1-based by table + 1
+ 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
+local function dcDiff(c: ArithComp, L: number, U: number): number?
+ local base = c.dcTbl * 64
+ local s = base + c.ctx
+ if decode(s) == 0 then
+ c.ctx = 0
+ return c.pred
+ end
+ local sign = decode(s + 1)
+ s = s + 2 + sign
+ local m = decode(s)
+ if m ~= 0 then
+ s = base + 20
+ while decode(s) ~= 0 do
+ m *= 2
+ if m == 0x8000 then
+ return nil
+ end
+ s += 1
+ end
+ end
+ if m < 2 ^ L // 2 then
+ c.ctx = 0
+ elseif m > 2 ^ U // 2 then
+ c.ctx = 12 + sign * 4
+ else
+ c.ctx = 4 + sign * 4
+ end
+ local v = m
+ s += 14
+ m = m // 2
+ while m > 0 do
+ if decode(s) ~= 0 then
+ v += m
+ end
+ m = m // 2
+ end
+ v += 1
+ if sign ~= 0 then
+ v = -v
+ end
+ return band(c.pred + v, 0xFFFF)
+end
+
+-- AC coefficients k = ss..se of one block (figure F.20); false on a bad code
+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
+ while k <= se do
+ local s = base + 3 * (k - 1)
+ if decode(s) ~= 0 then
+ break -- EOB
+ end
+ while decode(s + 1) == 0 do
+ s += 3
+ k += 1
+ if k > se then
+ return false
+ end
+ end
+ local sign = decode(FIXED)
+ s += 2
+ local m = decode(s)
+ if m ~= 0 then
+ if decode(s) ~= 0 then
+ m *= 2
+ s = base + (if k <= K then 189 else 217)
+ while decode(s) ~= 0 do
+ m *= 2
+ if m == 0x8000 then
+ return false
+ end
+ s += 1
+ end
+ end
+ end
+ local v = m
+ s += 14
+ m = m // 2
+ while m > 0 do
+ if decode(s) ~= 0 then
+ v += m
+ end
+ m = m // 2
+ end
+ v += 1
+ if sign ~= 0 then
+ v = -v
+ end
+ writei16(coef, off + readu8(ZZ, k) * 2, i16(v * mul))
+ k += 1
+ end
+ return true
+end
+
+local function acRefine(coef: buffer, off: number, tbl: number, ss: number, se: number, al: number): boolean
+ local base = 256 + tbl * 256
+ local p1 = 2 ^ al
+ local m1 = -p1
+ local kex = se
+ while kex > 0 do
+ if readi16(coef, off + readu8(ZZ, kex) * 2) ~= 0 then
+ break
+ end
+ kex -= 1
+ end
+ local k = ss
+ while k <= se do
+ local s = base + 3 * (k - 1)
+ if k > kex then
+ if decode(s) ~= 0 then
+ break
+ end
+ end
+ while true do
+ local o = off + readu8(ZZ, k) * 2
+ local cv = readi16(coef, o)
+ if cv ~= 0 then
+ if decode(s + 2) ~= 0 then
+ writei16(coef, o, i16(if cv < 0 then cv + m1 else cv + p1))
+ end
+ break
+ end
+ if decode(s + 1) ~= 0 then
+ writei16(coef, o, i16(if decode(FIXED) ~= 0 then m1 else p1))
+ break
+ end
+ s += 3
+ k += 1
+ if k > se then
+ return false
+ end
+ end
+ k += 1
+ end
+ return true
+end
+
+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
+ local mode, ss, se, al, ri = Pm.mode, Pm.ss, Pm.se, Pm.al, Pm.ri
+ local units, ux
+ if nc == 1 then
+ ux = comps[1].bw
+ units = ux * comps[1].bh
+ else
+ ux = Pm.mcusX
+ units = ux * Pm.mcusY
+ end
+ local resetDc = mode == 0 or mode == 1
+ local resetAc = mode == 0 or mode == 3 or mode == 4
+ local function reset()
+ for i = 1, nc do
+ local c = comps[i]
+ if resetDc then
+ buffer.fill(st, c.dcTbl * 64, 0, 64)
+ c.pred = 0
+ c.ctx = 0
+ end
+ if resetAc then
+ buffer.fill(st, 256 + c.acTbl * 256, 0, 256)
+ end
+ end
+ C, A, CT = 0, 0, -16
+ end
+ D = d
+ P = 0
+ SEGEND = if nrst >= 1 then math.min(rst[1], cleanLen) else cleanLen
+ OVER = 0
+ writeu8(st, FIXED, 113)
+ reset()
+ local rstIdx = 0
+ local bad = false
+ local truncated = false
+ local mul = 2 ^ al
+ for u = 0, units - 1 do
+ if ri > 0 and u > 0 and u % ri == 0 then
+ rstIdx += 1
+ if rstIdx <= nrst then
+ P = math.min(rst[rstIdx], cleanLen)
+ SEGEND = if rstIdx + 1 <= nrst then math.min(rst[rstIdx + 1], cleanLen) else cleanLen
+ bad = false
+ else
+ truncated = true
+ break
+ end
+ reset()
+ end
+ if not bad then
+ local my, mx = u // ux, u % ux
+ for ci = 1, nc do
+ local c = comps[ci]
+ local bh, bw, by0, bx0
+ if nc == 1 then
+ bh, bw, by0, bx0 = 1, 1, my, mx
+ else
+ bh, bw, by0, bx0 = c.v, c.h, my * c.v, mx * c.h
+ end
+ local coef, bpl = c.coef, c.bpl
+ for by = by0, by0 + bh - 1 do
+ for bx = bx0, bx0 + bw - 1 do
+ local off = (by * bpl + bx) * 128
+ if mode == 0 then
+ local pred = dcDiff(c, Pm.dcL[c.dcTbl + 1], Pm.dcU[c.dcTbl + 1])
+ if not pred then
+ bad = true
+ else
+ c.pred = pred
+ writei16(coef, off, i16(pred))
+ if not acFirst(coef, off, c.acTbl, 1, 63, Pm.acK[c.acTbl + 1], 1) then
+ bad = true
+ end
+ end
+ elseif mode == 1 then
+ local pred = dcDiff(c, Pm.dcL[c.dcTbl + 1], Pm.dcU[c.dcTbl + 1])
+ if not pred then
+ bad = true
+ else
+ c.pred = pred
+ writei16(coef, off, i16(pred * mul))
+ end
+ elseif mode == 2 then
+ if decode(FIXED) ~= 0 then
+ local cv = readi16(coef, off)
+ if band(cv, mul) == 0 then
+ writei16(coef, off, i16(cv + mul))
+ end
+ end
+ elseif mode == 3 then
+ if not acFirst(coef, off, c.acTbl, ss, se, Pm.acK[c.acTbl + 1], mul) then
+ bad = true
+ end
+ else
+ if not acRefine(coef, off, c.acTbl, ss, se, al) then
+ bad = true
+ end
+ end
+ if bad then
+ break
+ end
+ end
+ if bad then
+ break
+ end
+ end
+ if bad then
+ break
+ end
+ end
+ end
+ end
+ D = buffer.create(0)
+ return truncated
+end
+
+return Arith
diff --git a/src/Formats/image/jpeg/Color.luau b/src/Formats/image/jpeg/Color.luau
new file mode 100644
index 0000000..af39c11
--- /dev/null
+++ b/src/Formats/image/jpeg/Color.luau
@@ -0,0 +1,229 @@
+--!strict
+--!native
+--!optimize 2
+-- 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).
+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
+
+local Color = {}
+
+Color.FULL = 0
+Color.REPLICATE = 1
+Color.H2V1 = 2
+Color.H2V2 = 3
+Color.H1V2 = 4
+
+Color.GRAY = 0
+Color.YCC = 1
+Color.RGB = 2
+Color.CMYK = 3
+Color.YCCK = 4
+Color.CMYK_PLAIN = 5 -- CMYK without an Adobe marker: not inverted
+
+export type Comp = {
+ plane: buffer, -- u16 samples, stride per row
+ stride: number,
+ rows: number, -- plane height
+ downW: number, -- real samples across / down (the rest is block padding)
+ 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)
+}
+
+export type Params = {
+ comps: { Comp },
+ space: number,
+ outW: number,
+ 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
+}
+
+-- jdcolor.c build_ycc_rgb_table
+function Color.tables(maxv: number): (buffer, buffer, buffer, buffer)
+ local n = maxv + 1
+ local center = n // 2
+ local crr, cbb, crg, cbg = buffer.create(n * 4), buffer.create(n * 4), buffer.create(n * 4), buffer.create(n * 4)
+ local function fix(x: number): number
+ return math.floor(x * 65536 + 0.5)
+ end
+ for i = 0, maxv do
+ local x = i - center
+ buffer.writei32(crr, i * 4, (fix(1.40200) * x + 32768) // 65536)
+ buffer.writei32(cbb, i * 4, (fix(1.77200) * x + 32768) // 65536)
+ buffer.writei32(crg, i * 4, -fix(0.71414) * x)
+ buffer.writei32(cbg, i * 4, -fix(0.34414) * x + 32768)
+ end
+ 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
+ if method == 0 then
+ return plane, min(y, c.rows - 1) * stride * 2
+ elseif method == 2 then
+ local w = c.downW
+ local b = min(y, c.rows - 1) * stride * 2
+ local cur = readu16(plane, b)
+ writeu16(row, 0, cur)
+ local nxt = readu16(plane, b + 2)
+ writeu16(row, 2, (cur * 3 + nxt + 2) // 4)
+ local prev = cur
+ cur = nxt
+ for i = 1, w - 2 do
+ nxt = readu16(plane, b + (i + 1) * 2)
+ local v3 = cur * 3
+ writeu16(row, i * 4, (v3 + prev + 1) // 4)
+ writeu16(row, i * 4 + 2, (v3 + nxt + 2) // 4)
+ prev = cur
+ cur = nxt
+ end
+ writeu16(row, (w - 1) * 4, (cur * 3 + prev + 1) // 4)
+ writeu16(row, (w - 1) * 4 + 2, cur)
+ return row, 0
+ elseif method == 3 then
+ local w = c.downW
+ local iy = min(y // 2, c.downH - 1)
+ local oy = if y % 2 == 0 then max(iy - 1, 0) else min(iy + 1, c.downH - 1)
+ local b0, b1 = iy * stride * 2, oy * stride * 2
+ local this = readu16(plane, b0) * 3 + readu16(plane, b1)
+ local nxt = readu16(plane, b0 + 2) * 3 + readu16(plane, b1 + 2)
+ writeu16(row, 0, (this * 4 + 8) // 16)
+ writeu16(row, 2, (this * 3 + nxt + 7) // 16)
+ local last = this
+ this = nxt
+ for i = 1, w - 2 do
+ nxt = readu16(plane, b0 + (i + 1) * 2) * 3 + readu16(plane, b1 + (i + 1) * 2)
+ local t3 = this * 3
+ writeu16(row, i * 4, (t3 + last + 8) // 16)
+ writeu16(row, i * 4 + 2, (t3 + nxt + 7) // 16)
+ last = this
+ this = nxt
+ end
+ writeu16(row, (w - 1) * 4, (this * 3 + last + 8) // 16)
+ writeu16(row, (w - 1) * 4 + 2, (this * 4 + 7) // 16)
+ return row, 0
+ elseif method == 4 then
+ local iy = min(y // 2, c.downH - 1)
+ local oy, bias
+ if y % 2 == 0 then
+ oy, bias = max(iy - 1, 0), 1
+ else
+ oy, bias = min(iy + 1, c.downH - 1), 2
+ end
+ local b0, b1 = iy * stride * 2, oy * stride * 2
+ for x = 0, outW - 1 do
+ writeu16(row, x * 2, (readu16(plane, b0 + x * 2) * 3 + readu16(plane, b1 + x * 2) + bias) // 4)
+ end
+ return row, 0
+ else
+ local hIn, hOut = c.hIn, c.hOut
+ local iy = min((y * c.vIn) // c.vOut, c.rows - 1)
+ local b = iy * stride * 2
+ local last = stride - 1
+ for x = 0, outW - 1 do
+ writeu16(row, x * 2, readu16(plane, b + min((x * hIn) // hOut, last) * 2))
+ end
+ return row, 0
+ end
+end
+
+function Color.run(P: Params)
+ local comps = P.comps
+ local nc = #comps
+ local space, outW, outH, maxv, out = P.space, P.outW, P.outH, P.maxv, P.pixels
+ local crr, cbb, crg, cbg = P.crr, P.cbb, P.crg, P.cbg
+ local toByte = P.toByte
+ local o = 0
+ for y = 0, outH - 1 do
+ local s0, b0 = fetch(comps[1], y, outW)
+ if space == 0 or nc < 3 then
+ for x = 0, outW - 1 do
+ local v = readu16(s0, b0 + x * 2)
+ if toByte then
+ v = readu8(toByte, v)
+ end
+ writeu32(out, o, 0xFF000000 + v * 0x10101)
+ o += 4
+ end
+ else
+ local s1, b1 = fetch(comps[2], y, outW)
+ local s2, b2 = fetch(comps[3], y, outW)
+ local s3, b3 = s0, b0
+ if nc >= 4 then
+ s3, b3 = fetch(comps[4], y, outW)
+ 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)
+ local r = clamp(yv + readi32(crr, cr * 4), 0, 255)
+ local g = clamp(yv + (readi32(cbg, cb * 4) + readi32(crg, cr * 4)) // 65536, 0, 255)
+ local b = clamp(yv + readi32(cbb, cb * 4), 0, 255)
+ writeu32(out, o, 0xFF000000 + r + g * 256 + b * 65536)
+ o += 4
+ end
+ continue
+ end
+ for x = 0, outW - 1 do
+ local i = x * 2
+ local c0, c1, c2 = readu16(s0, b0 + i), readu16(s1, b1 + i), readu16(s2, b2 + i)
+ local r, g, b
+ if space == 2 then
+ r, g, b = c0, c1, c2
+ elseif space == 3 or space == 5 then
+ local k = readu16(s3, b3 + i)
+ if space == 5 then
+ c0, c1, c2, k = maxv - c0, maxv - c1, maxv - c2, maxv - k
+ end
+ r = (c0 * k + maxv // 2) // maxv
+ g = (c1 * k + maxv // 2) // maxv
+ b = (c2 * k + maxv // 2) // maxv
+ else
+ r = clamp(c0 + readi32(crr, c2 * 4), 0, maxv)
+ g = clamp(c0 + (readi32(cbg, c1 * 4) + readi32(crg, c2 * 4)) // 65536, 0, maxv)
+ b = clamp(c0 + readi32(cbb, c1 * 4), 0, maxv)
+ if space == 4 then
+ -- YCCK: the YCC part decodes to inverted C, M, Y (libjpeg ycck_cmyk_convert), K as stored
+ local k = readu16(s3, b3 + i)
+ r = ((maxv - r) * k + maxv // 2) // maxv
+ g = ((maxv - g) * k + maxv // 2) // maxv
+ b = ((maxv - b) * k + maxv // 2) // maxv
+ end
+ end
+ if toByte then
+ r, g, b = readu8(toByte, r), readu8(toByte, g), readu8(toByte, b)
+ end
+ writeu32(out, o, 0xFF000000 + r + g * 256 + b * 65536)
+ o += 4
+ end
+ end
+ end
+end
+
+return Color
diff --git a/src/Formats/image/jpeg/Decode.luau b/src/Formats/image/jpeg/Decode.luau
new file mode 100644
index 0000000..11d2f64
--- /dev/null
+++ b/src/Formats/image/jpeg/Decode.luau
@@ -0,0 +1,666 @@
+--!strict
+-- image/jpeg/Decode: the JPEG marker parser and output stage (interpreted; it validates everything the native Scan /
+-- Arith / Dct / Color loops index). Absorbed from jpeg-luau 1.0 src/Jpeg/init.luau (same author) and extended:
+-- arithmetic-coded frames (SOF9 / SOF10, DAC), a reader range instead of a whole buffer, APP1 EXIF / APP2 ICC / COM
+-- / JFIF density collected for meta. The IDCT size choice for scaled decodes follows libjpeg-turbo's jdmaster.c.
+local Scan = require("@formats/image/jpeg/Scan")
+local Arith = require("@formats/image/jpeg/Arith")
+local Color = require("@formats/image/jpeg/Color")
+local Tables = require("@formats/image/jpeg/Tables")
+local Dct = require("@formats/codecs/Dct")
+
+local readu8 = buffer.readu8
+local band, rshift = bit32.band, bit32.rshift
+
+local Decode = {}
+
+Arith.init(Scan.ZIGZAG)
+
+local function be16(b: buffer, p: number): number
+ return readu8(b, p) * 256 + readu8(b, p + 1)
+end
+
+local stdBuilt: { [string]: buffer } = {}
+local function stdTable(class: string, slot: number): buffer?
+ local key = class .. slot
+ if not stdBuilt[key] then
+ local def = (if class == "dc" then Tables.DC else Tables.AC)[slot + 1]
+ if not def then
+ return nil
+ end
+ stdBuilt[key] = Scan.buildTable(def.counts, def.symbols)
+ end
+ return stdBuilt[key]
+end
+
+-- the EXIF TIFF block (after "Exif\0\0") and its orientation tag, from an APP1 segment at [p, e)
+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
+ end
+ local t = p + 6
+ local le
+ local bo = buffer.readstring(b, t, 2)
+ if bo == "II" then
+ le = true
+ elseif bo == "MM" then
+ le = false
+ else
+ return nil, nil
+ end
+ local function r16(at: number): number
+ if le then
+ return readu8(b, at) + readu8(b, at + 1) * 256
+ end
+ return readu8(b, at) * 256 + readu8(b, at + 1)
+ end
+ local function r32(at: number): number
+ if le then
+ return r16(at) + r16(at + 2) * 65536
+ end
+ return r16(at) * 65536 + r16(at + 2)
+ end
+ local ifd = t + r32(t + 4)
+ if ifd + 2 > e then
+ return t, nil
+ end
+ local count = r16(ifd)
+ for i = 0, count - 1 do
+ local en = ifd + 2 + i * 12
+ if en + 12 > e then
+ return t, nil
+ end
+ if r16(en) == 0x0112 then
+ local v = r16(en + 8)
+ return t, if v >= 1 and v <= 8 then v else nil
+ end
+ end
+ return t, nil
+end
+
+type Comp = {
+ id: number,
+ h: number,
+ v: number,
+ tq: number,
+ bpl: number,
+ bpc: number,
+ bw: number,
+ bh: number,
+ coef: buffer?,
+ quant: buffer?, -- latched at the component's first scan
+ dct: buffer?,
+ act: buffer?,
+ dcTbl: number,
+ acTbl: number,
+ pred: number,
+ ctx: number,
+}
+
+type Frame = {
+ width: number,
+ height: number,
+ precision: number,
+ progressive: boolean,
+ arithmetic: boolean,
+ comps: { Comp },
+ hmax: number,
+ vmax: number,
+ mcusX: number,
+ mcusY: number,
+}
+
+local SOF_REFUSED = {
+ [0xC3] = "lossless",
+ [0xC5] = "hierarchical",
+ [0xC6] = "hierarchical",
+ [0xC7] = "hierarchical",
+ [0xCB] = "lossless arithmetic-coded",
+ [0xCD] = "hierarchical arithmetic-coded",
+ [0xCE] = "hierarchical arithmetic-coded",
+ [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"
+ end
+ local prec = readu8(b, p)
+ local height, width, nf = be16(b, p + 1), be16(b, p + 3), readu8(b, p + 5)
+ if prec ~= 8 and prec ~= 12 then
+ return nil, "unsupported", "sample precision " .. prec
+ end
+ if width == 0 or height == 0 then
+ if height == 0 and width > 0 then
+ return nil, "unsupported", "DNL (height 0 in the frame header)"
+ end
+ return nil, "corrupt", "bad size " .. width .. "x" .. height
+ end
+ if nf ~= 1 and nf ~= 3 and nf ~= 4 then
+ return nil, "unsupported", "component count " .. nf
+ end
+ if e - p < 6 + nf * 3 then
+ return nil, "corrupt", "short SOF"
+ end
+ local comps = {}
+ local hmax, vmax = 1, 1
+ for i = 0, nf - 1 do
+ local q = p + 6 + i * 3
+ local hv = readu8(b, q + 1)
+ local h, v, tq = rshift(hv, 4), band(hv, 15), readu8(b, q + 2)
+ if h < 1 or h > 4 or v < 1 or v > 4 then
+ return nil, "corrupt", "bad sampling factors " .. h .. "x" .. v
+ end
+ if tq > 3 then
+ return nil, "corrupt", "bad quantisation table selector " .. tq
+ end
+ local id = readu8(b, q)
+ for _, c in comps do
+ if c.id == id then
+ return nil, "corrupt", "duplicate component id " .. id
+ end
+ end
+ hmax, vmax = math.max(hmax, h), math.max(vmax, v)
+ table.insert(comps, { id = id, h = h, v = v, tq = tq, bpl = 0, bpc = 0, bw = 0, bh = 0, dcTbl = 0, acTbl = 0, pred = 0, ctx = 0 } :: Comp)
+ end
+ local mcusX = math.ceil(width / (8 * hmax))
+ local mcusY = math.ceil(height / (8 * vmax))
+ for _, c in comps do
+ c.bpl = mcusX * c.h
+ c.bpc = mcusY * c.v
+ c.bw = math.ceil(math.ceil(width * c.h / hmax) / 8)
+ c.bh = math.ceil(math.ceil(height * c.v / vmax) / 8)
+ end
+ return {
+ width = width,
+ height = height,
+ precision = prec,
+ progressive = m == 0xC2 or m == 0xCA,
+ arithmetic = m == 0xC9 or m == 0xCA,
+ comps = comps,
+ hmax = hmax,
+ vmax = vmax,
+ mcusX = mcusX,
+ mcusY = mcusY,
+ }
+end
+
+local function colorSpaceOf(frame: Frame, adobe: number?, jfif: boolean): string
+ local n = #frame.comps
+ if n == 1 then
+ return "gray"
+ elseif n == 3 then
+ if adobe ~= nil then
+ return if adobe == 0 then "rgb" else "ycbcr"
+ end
+ local c = frame.comps
+ if not jfif and c[1].id == 82 and c[2].id == 71 and c[3].id == 66 then
+ return "rgb"
+ end
+ return "ycbcr"
+ end
+ return if adobe == 2 then "ycck" else "cmyk"
+end
+Decode.colorSpaceOf = colorSpaceOf
+
+-- The IDCT size (8, 4, 2 or 1) for a component at a scale. libjpeg-turbo scales chroma up through a bigger IDCT
+-- instead of upsampling it, when the sampling ratios allow (jdmaster.c jpeg_calc_output_dimensions).
+local function idctSize(f: Frame, c: Comp, scale: number): number
+ local minSize = 8 // scale
+ local ssize = minSize
+ while ssize < 8 and (f.hmax * minSize) % (c.h * ssize * 2) == 0 and (f.vmax * minSize) % (c.v * ssize * 2) == 0 do
+ ssize *= 2
+ end
+ return ssize
+end
+
+export type State = {
+ frame: any,
+ adobe: number?,
+ jfif: boolean,
+ density: { unit: number, x: number, y: number }?,
+ orientation: number,
+ exif: buffer?,
+ icc: buffer?,
+ comments: { string },
+ truncated: boolean,
+ scale: number,
+}
+
+-- 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)"
+ end
+ local scale = (opts and opts.scale) or 1
+ if scale ~= 1 and scale ~= 2 and scale ~= 4 and scale ~= 8 then
+ return nil, "arg", "scale must be 1, 2, 4 or 8"
+ end
+ local maxPixels = (opts and opts.maxPixels) or 2 ^ 26
+ local quant: { [number]: buffer } = {}
+ local dcT: { [number]: buffer } = {}
+ local acT: { [number]: buffer } = {}
+ local dcL, dcU, acK = { 0, 0, 0, 0 }, { 1, 1, 1, 1 }, { 5, 5, 5, 5 }
+ local frame: Frame? = nil
+ local st: State = {
+ frame = nil,
+ adobe = nil,
+ jfif = false,
+ density = nil,
+ orientation = 1,
+ exif = nil,
+ icc = nil,
+ comments = {},
+ truncated = false,
+ scale = scale,
+ }
+ local iccChunks: { buffer } = {}
+ local ri = 0
+ local scans = 0
+ local clean: buffer? = nil
+ local rst = {}
+ local pos = base + 2
+ while pos < n do
+ -- find the next marker (tolerate garbage and fill bytes)
+ if readu8(b, pos) ~= 0xFF then
+ pos += 1
+ continue
+ end
+ while pos < n and readu8(b, pos) == 0xFF do
+ pos += 1
+ end
+ if pos >= n then
+ break
+ end
+ local m = readu8(b, pos)
+ pos += 1
+ if m == 0xD9 then
+ break -- EOI
+ elseif m == 0 or m == 0x01 or m == 0xD8 or (m >= 0xD0 and m <= 0xD7) then
+ continue -- standalone markers (or stray stuffing)
+ end
+ if pos + 2 > n then
+ st.truncated = true
+ break
+ end
+ local len = be16(b, pos)
+ if len < 2 then
+ return nil, "corrupt", string.format("bad segment length for marker %02X", m)
+ end
+ local p, e = pos + 2, pos + len
+ if e > n then
+ if m == 0xDA and frame and not headerOnly then
+ e = n -- a truncated SOS header still fails below
+ else
+ st.truncated = true
+ break
+ end
+ end
+ pos = e
+ if m == 0xE0 then
+ if e - p >= 12 and buffer.readstring(b, p, 5) == "JFIF\0" then
+ st.jfif = true
+ st.density = { unit = readu8(b, p + 7), x = be16(b, p + 8), y = be16(b, p + 10) }
+ end
+ elseif m == 0xE1 then
+ local t, o = exif(b, p, e)
+ if t and not st.exif then
+ local x = buffer.create(e - t)
+ buffer.copy(x, 0, b, t, e - t)
+ st.exif = x
+ end
+ if o then
+ st.orientation = o
+ end
+ elseif m == 0xE2 then
+ -- ICC_PROFILE\0, sequence number, count, data
+ if e - p >= 14 and buffer.readstring(b, p, 12) == "ICC_PROFILE\0" then
+ local seq = readu8(b, p + 12)
+ local x = buffer.create(e - p - 14)
+ buffer.copy(x, 0, b, p + 14, e - p - 14)
+ if seq >= 1 then
+ iccChunks[seq] = x
+ end
+ end
+ elseif m == 0xEE then
+ if e - p >= 12 and buffer.readstring(b, p, 5) == "Adobe" then
+ st.adobe = readu8(b, p + 11)
+ end
+ elseif m == 0xFE then
+ table.insert(st.comments, buffer.readstring(b, p, e - p))
+ elseif m == 0xDB then
+ -- DQT
+ while p < e do
+ local pt = readu8(b, p)
+ local pq, tq = rshift(pt, 4), band(pt, 15)
+ local size = if pq == 0 then 64 else 128
+ if tq > 3 or pq > 1 or p + 1 + size > e then
+ return nil, "corrupt", "bad DQT segment"
+ end
+ local q = buffer.create(128)
+ for k = 0, 63 do
+ local v = if pq == 0 then readu8(b, p + 1 + k) else be16(b, p + 1 + k * 2)
+ buffer.writeu16(q, readu8(Scan.ZIGZAG, k) * 2, v)
+ end
+ quant[tq] = q
+ p += 1 + size
+ end
+ elseif m == 0xC4 then
+ -- DHT
+ while p < e do
+ if p + 17 > e then
+ return nil, "corrupt", "bad DHT segment"
+ end
+ local tc = readu8(b, p)
+ local class, slot = rshift(tc, 4), band(tc, 15)
+ if class > 1 or slot > 3 then
+ return nil, "corrupt", "bad DHT table class / slot"
+ end
+ local counts, total = {}, 0
+ for l = 1, 16 do
+ counts[l] = readu8(b, p + l)
+ total += counts[l]
+ end
+ if total > 256 or p + 17 + total > e then
+ return nil, "corrupt", "bad DHT segment"
+ end
+ local syms = {}
+ for i = 1, total do
+ syms[i] = readu8(b, p + 16 + i)
+ end
+ local t = Scan.buildTable(counts, syms)
+ if class == 0 then
+ dcT[slot] = t
+ else
+ acT[slot] = t
+ end
+ p += 17 + total
+ end
+ elseif m == 0xCC then
+ -- DAC: arithmetic conditioning
+ while p + 2 <= e do
+ local tc, v = readu8(b, p), readu8(b, p + 1)
+ local class, slot = rshift(tc, 4), band(tc, 15)
+ if class > 1 or slot > 3 then
+ return nil, "corrupt", "bad DAC segment"
+ end
+ if class == 0 then
+ local L, U = band(v, 15), rshift(v, 4)
+ if L > U then
+ return nil, "corrupt", "bad DAC value"
+ end
+ dcL[slot + 1], dcU[slot + 1] = L, U
+ else
+ if v < 1 or v > 63 then
+ return nil, "corrupt", "bad DAC value"
+ end
+ acK[slot + 1] = v
+ end
+ p += 2
+ end
+ elseif m == 0xDD then
+ if e - p < 2 then
+ return nil, "corrupt", "bad DRI segment"
+ end
+ ri = be16(b, p)
+ elseif m == 0xC0 or m == 0xC1 or m == 0xC2 or m == 0xC9 or m == 0xCA then
+ if frame then
+ return nil, "corrupt", "more than one frame header"
+ end
+ local f, code, err = parseSof(b, p, e, m)
+ if not f then
+ return nil, code, err
+ end
+ if f.width * f.height > maxPixels then
+ return nil, "limit", string.format("%d x %d is over the %d pixel limit", f.width, f.height, maxPixels)
+ end
+ frame = f
+ st.frame = f
+ if headerOnly then
+ return st
+ end
+ elseif SOF_REFUSED[m] then
+ return nil, "unsupported", SOF_REFUSED[m] .. " JPEG"
+ elseif m == 0xDA then
+ if headerOnly then
+ break
+ end
+ if not frame then
+ return nil, "corrupt", "scan before the frame header"
+ end
+ local f = frame :: Frame
+ local ns = if p < e then readu8(b, p) else 0
+ if ns < 1 or ns > 4 or e - p < 4 + ns * 2 then
+ return nil, "corrupt", "bad SOS segment"
+ end
+ local sc = {}
+ local blocks = 0
+ for i = 0, ns - 1 do
+ local id, t = readu8(b, p + 1 + i * 2), readu8(b, p + 2 + i * 2)
+ local comp = nil
+ for _, c in f.comps do
+ if c.id == id then
+ comp = c
+ end
+ end
+ if not comp or table.find(sc, comp) then
+ return nil, "corrupt", "scan names an unknown component " .. id
+ end
+ local td, ta = rshift(t, 4), band(t, 15)
+ if td > 3 or ta > 3 then
+ return nil, "corrupt", "bad entropy table selector"
+ end
+ comp.dcTbl, comp.acTbl = td, ta
+ if not f.arithmetic then
+ comp.dct = dcT[td] or stdTable("dc", td)
+ comp.act = acT[ta] or stdTable("ac", ta)
+ end
+ blocks += comp.h * comp.v
+ table.insert(sc, comp)
+ end
+ local q = p + 1 + ns * 2
+ local ss, se, a = readu8(b, q), readu8(b, q + 1), readu8(b, q + 2)
+ local ah, al = rshift(a, 4), band(a, 15)
+ if ns > 1 and blocks > 10 then
+ return nil, "corrupt", "more than 10 blocks per MCU"
+ end
+ local mode
+ if not f.progressive then
+ mode = 0
+ ss, se, ah, al = 0, 63, 0, 0
+ else
+ if se > 63 or ss > se or ah > 13 or al > 13 or (ss == 0 and se ~= 0) or (ss > 0 and ns ~= 1) then
+ return nil, "corrupt", "bad progressive scan parameters"
+ end
+ if ss == 0 then
+ mode = if ah == 0 then 1 else 2
+ else
+ mode = if ah == 0 then 3 else 4
+ end
+ end
+ for _, c in sc do
+ if not f.arithmetic then
+ if (mode == 0 or mode == 1) and not c.dct then
+ return nil, "corrupt", "missing DC Huffman table"
+ end
+ if (mode == 0 or mode == 3 or mode == 4) and not c.act then
+ return nil, "corrupt", "missing AC Huffman table"
+ end
+ end
+ if not c.coef then
+ c.coef = buffer.create(c.bpl * c.bpc * 128)
+ end
+ if not c.quant then
+ c.quant = quant[c.tq]
+ end
+ end
+ if not clean then
+ clean = buffer.create(n - base + Scan.PAD)
+ end
+ local cb = clean :: buffer
+ local nextPos, cleanLen, nrst = Scan.destuff(b, pos, n, cb, rst)
+ if nextPos >= n then
+ st.truncated = true -- no EOI
+ end
+ -- a component decoded through the 1x1 IDCT only needs its DC coefficient: skip its AC scans
+ if not (mode >= 3 and idctSize(f, sc[1], scale) == 1) then
+ local params = {
+ comps = sc :: any,
+ mcusX = f.mcusX,
+ mcusY = f.mcusY,
+ ri = ri,
+ mode = mode,
+ ss = ss,
+ se = se,
+ al = al,
+ dcL = dcL,
+ dcU = dcU,
+ acK = acK,
+ }
+ local short
+ if f.arithmetic then
+ short = Arith.run(cb, cleanLen, rst, nrst, params)
+ else
+ local _
+ _, short = Scan.run(cb, cleanLen, rst, nrst, params)
+ end
+ st.truncated = st.truncated or short
+ end
+ scans += 1
+ pos = nextPos
+ end
+ end
+ if not frame then
+ return nil, if st.truncated then "truncated" else "corrupt", "no frame header"
+ end
+ if #iccChunks > 0 then
+ local total = 0
+ for _, c in iccChunks do
+ total += buffer.len(c)
+ end
+ local icc = buffer.create(total)
+ local o = 0
+ for _, c in iccChunks do
+ buffer.copy(icc, o, c)
+ o += buffer.len(c)
+ end
+ st.icc = icc
+ end
+ if headerOnly then
+ return st
+ end
+ if scans == 0 then
+ return nil, "truncated", "no image data"
+ end
+ return st
+end
+
+local SPACE_IDS = { gray = Color.GRAY, ycbcr = Color.YCC, rgb = Color.RGB, cmyk = Color.CMYK, ycck = Color.YCCK }
+
+local tableCache: { [number]: { buffer } } = {}
+local function yccTables(maxv: number): { buffer }
+ local t = tableCache[maxv]
+ if not t then
+ local a, b, c, d = Color.tables(maxv)
+ t = { a, b, c, d }
+ tableCache[maxv] = t
+ end
+ return t
+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
+ local minSize = 8 // scale
+ local maxv = if f.precision == 12 then 4095 else 255
+ local center = (maxv + 1) // 2
+ local p1 = if f.precision == 12 then 1 else 2
+ local outW = math.ceil(f.width * minSize / 8)
+ local outH = math.ceil(f.height * minSize / 8)
+ local fancy = minSize > 1
+ local ccomps = {}
+ local zeroQ = buffer.create(128)
+ for _, c in f.comps do
+ local ssize = idctSize(f, c, scale)
+ local stride, rows = c.bpl * ssize, c.bpc * ssize
+ local plane = buffer.create(stride * rows * 2)
+ local coef = c.coef or buffer.create(c.bpl * c.bpc * 128)
+ local q = c.quant
+ if not q then
+ if c.coef then
+ return nil, "corrupt", "missing quantisation table " .. c.tq
+ end
+ q = zeroQ -- the component never appeared in a scan: mid grey
+ end
+ Dct.idctComponent(coef, q :: buffer, c.bpl, c.bpc, ssize, plane, p1, center, maxv)
+ local hIn, hOut = c.h * ssize // minSize, f.hmax
+ local vIn, vOut = c.v * ssize // minSize, f.vmax
+ local downW = math.ceil(f.width * c.h * ssize / (f.hmax * 8))
+ local downH = math.ceil(f.height * c.v * ssize / (f.vmax * 8))
+ local method
+ if hIn == hOut and vIn == vOut then
+ method = Color.FULL
+ elseif hIn * 2 == hOut and vIn * 2 == vOut and fancy and downW > 2 then
+ method = Color.H2V2
+ elseif hIn * 2 == hOut and vIn == vOut and fancy and downW > 2 then
+ method = Color.H2V1
+ elseif hIn == hOut and vIn * 2 == vOut and fancy then
+ method = Color.H1V2
+ else
+ method = Color.REPLICATE
+ end
+ table.insert(ccomps, {
+ plane = plane,
+ stride = stride,
+ rows = rows,
+ downW = downW,
+ downH = downH,
+ method = method,
+ hIn = hIn,
+ hOut = hOut,
+ vIn = vIn,
+ vOut = vOut,
+ row = buffer.create((math.max(outW, 2 * stride) + 8) * 2),
+ })
+ c.coef = nil -- free the coefficients early
+ end
+ local space = colorSpaceOf(f, st.adobe, st.jfif)
+ local spaceId = SPACE_IDS[space]
+ if space == "cmyk" and st.adobe == nil then
+ spaceId = Color.CMYK_PLAIN
+ end
+ local t = yccTables(maxv)
+ local tb = nil
+ if maxv == 4095 then
+ if not toByte12 then
+ local tbuf = buffer.create(4096)
+ for v = 0, 4095 do
+ buffer.writeu8(tbuf, v, (v * 255 + 2047) // 4095)
+ end
+ toByte12 = tbuf
+ end
+ tb = toByte12
+ end
+ local pixels = buffer.create(outW * outH * 4)
+ Color.run({
+ comps = ccomps,
+ space = spaceId,
+ outW = outW,
+ outH = outH,
+ maxv = maxv,
+ pixels = pixels,
+ crr = t[1],
+ cbb = t[2],
+ crg = t[3],
+ cbg = t[4],
+ toByte = tb,
+ })
+ return outW, outH, pixels, space
+end
+
+return Decode
diff --git a/src/Formats/image/jpeg/Encode.luau b/src/Formats/image/jpeg/Encode.luau
new file mode 100644
index 0000000..0ecf6eb
--- /dev/null
+++ b/src/Formats/image/jpeg/Encode.luau
@@ -0,0 +1,883 @@
+--!strict
+--!native
+--!optimize 2
+-- 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; restart intervals. It follows libjpeg-turbo's encoder step for step so that its output is
+-- byte-identical to cjpeg's for the same settings: jccolor.c (fixed-point RGB -> YCbCr), jcsample.c (box downsampling
+-- with alternating rounding bias, right-edge replication), jccoefct.c (dummy edge blocks), jfdctint.c + jcdctmgr.c
+-- (codecs/Dct), jchuff.c (sequential coding, jpeg_gen_optimal_table) and jcphuff.c (progressive coding: EOB runs,
+-- correction-bit buffering). Luau translation of IJG code: licenses/libjpeg-turbo-LICENSE.md.
+local Dct = require("@formats/codecs/Dct")
+local Tables = require("@formats/image/jpeg/Tables")
+
+local readu8, writeu8, readi16, writei16, readu16, writeu16 = buffer.readu8, buffer.writeu8, buffer.readi16, buffer.writei16, buffer.readu16, buffer.writeu16
+local band, countlz = bit32.band, bit32.countlz
+
+local Encode = {}
+
+-- natural order index of zigzag position k
+local ZZ = buffer.create(64)
+do
+ local i = 0
+ for s = 0, 14 do
+ local lo, hi = math.max(0, s - 7), math.min(s, 7)
+ if s % 2 == 0 then
+ for r = hi, lo, -1 do
+ writeu8(ZZ, i, r * 8 + (s - r))
+ i += 1
+ end
+ else
+ for r = lo, hi do
+ writeu8(ZZ, i, r * 8 + (s - r))
+ i += 1
+ end
+ end
+ end
+end
+Encode.ZIGZAG = ZZ
+
+-- ------------------------------------------------------------------------------------------------ output
+local OUT = buffer.create(0)
+local OP = 0
+local CAP = 0
+local ACC, NB = 0, 0
+local GATHER = false
+
+local function grow(n: number)
+ if OP + n > CAP then
+ local c = math.max(CAP * 2, OP + n + 1024)
+ local nb = buffer.create(c)
+ buffer.copy(nb, 0, OUT, 0, OP)
+ OUT = nb
+ CAP = c
+ end
+end
+
+local function byte(v: number)
+ grow(1)
+ writeu8(OUT, OP, v)
+ OP += 1
+end
+
+local function u16be(v: number)
+ byte(v // 256)
+ byte(v % 256)
+end
+
+-- n bits of v (n <= 16), MSB first, with 0xFF stuffing
+local function bits(v: number, n: number)
+ if GATHER or n == 0 then
+ return
+ end
+ local p = 2 ^ n
+ ACC = ACC * p + band(v, p - 1)
+ NB += n
+ while NB >= 8 do
+ NB -= 8
+ local d = 2 ^ NB
+ local b = ACC // d
+ ACC -= b * d
+ grow(2)
+ writeu8(OUT, OP, b)
+ OP += 1
+ if b == 0xFF then
+ writeu8(OUT, OP, 0)
+ OP += 1
+ end
+ end
+end
+
+local function flushBits()
+ if NB > 0 then
+ bits(0x7F, 8 - NB) -- pad with ones
+ end
+ ACC, NB = 0, 0
+end
+
+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 }
+
+local function derive(counts: { number }, symbols: { number }): Derived
+ local code, size = buffer.create(512), buffer.create(256)
+ local c, k = 0, 1
+ for l = 1, 16 do
+ for _ = 1, counts[l] or 0 do
+ local s = symbols[k]
+ if s then
+ writeu16(code, s * 2, c)
+ writeu8(size, s, l)
+ end
+ k += 1
+ c += 1
+ end
+ c *= 2
+ end
+ return { code = code, size = size }
+end
+
+-- jchuff.c jpeg_gen_optimal_table: freq (0..256, 1-based +1) -> counts, symbols
+local function optimal(freqIn: { number }): ({ number }, { number })
+ local freq = table.create(257, 0)
+ local bitsT = table.create(34, 0)
+ local codesize = table.create(257, 0)
+ local others = table.create(257, -1)
+ local nz = table.create(257, 0)
+ local n = 0
+ for i = 0, 256 do
+ local f = if i == 256 then 1 else freqIn[i + 1]
+ if f > 0 then
+ n += 1
+ nz[n] = i
+ freq[n] = f
+ end
+ end
+ while true do
+ local c1, c2 = -1, -1
+ local v, v2 = 1e9, 1e9
+ for i = 1, n do
+ local f = freq[i]
+ if f <= v2 then
+ if f <= v then
+ c2 = c1
+ v2 = v
+ v = f
+ c1 = i
+ else
+ v2 = f
+ c2 = i
+ end
+ end
+ end
+ if c2 < 0 then
+ break
+ end
+ freq[c1] += freq[c2]
+ freq[c2] = 1000000001
+ codesize[c1] += 1
+ while others[c1] >= 0 do
+ c1 = others[c1]
+ codesize[c1] += 1
+ end
+ others[c1] = c2
+ codesize[c2] += 1
+ while others[c2] >= 0 do
+ c2 = others[c2]
+ codesize[c2] += 1
+ end
+ end
+ for i = 1, n do
+ local cs = math.min(codesize[i], 32)
+ bitsT[cs + 1] += 1
+ end
+ local bitPos = table.create(34, 0)
+ local p = 0
+ for i = 1, 32 do
+ bitPos[i + 1] = p
+ p += bitsT[i + 1]
+ end
+ local i = 32
+ while i > 16 do
+ while bitsT[i + 1] > 0 do
+ local j = i - 2
+ while bitsT[j + 1] == 0 do
+ j -= 1
+ end
+ bitsT[i + 1] -= 2
+ bitsT[i] += 1
+ bitsT[j + 2] += 2
+ bitsT[j + 1] -= 1
+ end
+ i -= 1
+ end
+ while bitsT[i + 1] == 0 do
+ i -= 1
+ end
+ bitsT[i + 1] -= 1
+ local counts = table.create(16, 0)
+ for l = 1, 16 do
+ counts[l] = bitsT[l + 1]
+ end
+ local symbols = table.create(n, 0)
+ for k = 1, n - 1 do
+ local cs = math.min(codesize[k], 32)
+ symbols[bitPos[cs + 1] + 1] = nz[k]
+ bitPos[cs + 1] += 1
+ end
+ local total = 0
+ for l = 1, 16 do
+ total += counts[l]
+ end
+ local out = table.create(total, 0)
+ for k = 1, total do
+ out[k] = symbols[k]
+ end
+ return counts, out
+end
+Encode.optimal = optimal
+
+-- ------------------------------------------------------------------------------------------------ entropy coding state
+local dcTab: { Derived } = {}
+local acTab: { Derived } = {}
+local dcFreq: { { number } } = {}
+local acFreq: { { number } } = {}
+
+local function symbol(t: Derived, freq: { number }, s: number)
+ if GATHER then
+ freq[s + 1] += 1
+ else
+ bits(readu16(t.code, s * 2), readu8(t.size, s))
+ end
+end
+
+export type Comp = {
+ id: number,
+ h: number,
+ v: number,
+ tq: number,
+ td: number, -- DC table slot
+ ta: number, -- AC table slot
+ bw: number, -- real blocks across / down
+ bh: number,
+ bpl: number, -- MCU-padded block grid
+ bpc: number,
+ coef: buffer, -- i16, 64 per block, natural order
+ last: number, -- DC predictor
+}
+
+local function dcDiff(c: Comp, diff: number)
+ local t = diff
+ local t2 = diff
+ if t < 0 then
+ t = -t
+ t2 -= 1
+ end
+ local n = nbits(t)
+ symbol(dcTab[c.td + 1], dcFreq[c.td + 1], n)
+ if n > 0 then
+ bits(t2, n)
+ end
+end
+
+-- jchuff.c encode_one_block
+local function blockSeq(c: Comp, off: number)
+ local coef = c.coef
+ local dc = readi16(coef, off)
+ dcDiff(c, dc - c.last)
+ c.last = dc
+ local at, af = acTab[c.ta + 1], acFreq[c.ta + 1]
+ local r = 0
+ for k = 1, 63 do
+ local v = readi16(coef, off + readu8(ZZ, k) * 2)
+ if v == 0 then
+ r += 1
+ else
+ while r > 15 do
+ symbol(at, af, 0xF0)
+ r -= 16
+ end
+ local t, t2 = v, v
+ if t < 0 then
+ t = -t
+ t2 -= 1
+ end
+ local n = nbits(t)
+ symbol(at, af, r * 16 + n)
+ bits(t2, n)
+ r = 0
+ end
+ end
+ if r > 0 then
+ symbol(at, af, 0)
+ end
+end
+
+-- progressive state (jcphuff.c)
+local EOBRUN = 0
+local BE = 0
+local CORR: { number } = table.create(1000, 0)
+local curAc: Derived = { code = buffer.create(512), size = buffer.create(256) }
+local curAcFreq: { number } = {}
+
+local function emitEobrun()
+ if EOBRUN > 0 then
+ local n = nbits(EOBRUN) - 1
+ symbol(curAc, curAcFreq, n * 16)
+ if n > 0 then
+ bits(EOBRUN, n)
+ end
+ EOBRUN = 0
+ if not GATHER then
+ for i = 1, BE do
+ bits(CORR[i], 1)
+ end
+ end
+ BE = 0
+ end
+end
+
+local function blockDcFirst(c: Comp, off: number, al: number)
+ local t2 = readi16(c.coef, off) // 2 ^ al
+ dcDiff(c, t2 - c.last)
+ c.last = t2
+end
+
+local function blockAcFirst(c: Comp, off: number, ss: number, se: number, al: number)
+ local coef = c.coef
+ local d = 2 ^ al
+ local r = 0
+ for k = ss, se do
+ local v = readi16(coef, off + readu8(ZZ, k) * 2)
+ local t, t2
+ if v < 0 then
+ t = (-v) // d
+ t2 = -t - 1 -- ~t
+ else
+ t = v // d
+ t2 = t
+ end
+ if t == 0 then
+ r += 1
+ else
+ emitEobrun()
+ while r > 15 do
+ symbol(curAc, curAcFreq, 0xF0)
+ r -= 16
+ end
+ local n = nbits(t)
+ symbol(curAc, curAcFreq, r * 16 + n)
+ bits(t2, n)
+ r = 0
+ end
+ end
+ if r > 0 then
+ EOBRUN += 1
+ if EOBRUN == 0x7FFF then
+ emitEobrun()
+ end
+ end
+end
+
+local absv = table.create(64, 0)
+
+local function blockAcRefine(c: Comp, off: number, ss: number, se: number, al: number)
+ local coef = c.coef
+ local d = 2 ^ al
+ local eob = 0
+ for k = ss, se do
+ local v = readi16(coef, off + readu8(ZZ, k) * 2)
+ local t = (if v < 0 then -v else v) // d
+ absv[k + 1] = t
+ if t == 1 then
+ eob = k
+ end
+ end
+ local r = 0
+ local br = 0 -- correction bits added in this block, at CORR[brStart + 1 ..]
+ local brStart = BE
+ for k = ss, se do
+ local t = absv[k + 1]
+ if t == 0 then
+ r += 1
+ continue
+ end
+ while r > 15 and k <= eob do
+ emitEobrun()
+ symbol(curAc, curAcFreq, 0xF0)
+ r -= 16
+ if not GATHER then
+ for i = 1, br do
+ bits(CORR[brStart + i], 1)
+ end
+ end
+ brStart = 0
+ br = 0
+ end
+ if t > 1 then
+ br += 1
+ CORR[brStart + br] = t % 2
+ continue
+ end
+ emitEobrun()
+ symbol(curAc, curAcFreq, r * 16 + 1)
+ bits(if readi16(coef, off + readu8(ZZ, k) * 2) < 0 then 0 else 1, 1)
+ if not GATHER then
+ for i = 1, br do
+ bits(CORR[brStart + i], 1)
+ end
+ end
+ brStart = 0
+ br = 0
+ r = 0
+ end
+ if r > 0 or br > 0 then
+ EOBRUN += 1
+ BE += br
+ if EOBRUN == 0x7FFF or BE > 1000 - 64 + 1 then
+ emitEobrun()
+ end
+ 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
+ if nc == 1 then
+ ux = comps[1].bw
+ units = ux * comps[1].bh
+ else
+ ux = mcusX
+ units = ux * mcusY
+ end
+ local rn = 0
+ for u = 0, units - 1 do
+ if ri > 0 and u > 0 and u % ri == 0 then
+ onRestart(rn)
+ rn = (rn + 1) % 8
+ end
+ local my, mx = u // ux, u % ux
+ for ci = 1, nc do
+ local c = comps[ci]
+ if nc == 1 then
+ fn(c, (my * c.bpl + mx) * 128)
+ else
+ for by = my * c.v, my * c.v + c.v - 1 do
+ for bx = mx * c.h, mx * c.h + c.h - 1 do
+ fn(c, (by * c.bpl + bx) * 128)
+ end
+ end
+ end
+ end
+ end
+end
+
+local function dht(class: number, slot: number, counts: { number }, symbols: { number })
+ byte(0xFF)
+ byte(0xC4)
+ u16be(2 + 17 + #symbols)
+ byte(class * 16 + slot)
+ for l = 1, 16 do
+ byte(counts[l])
+ end
+ for _, s in symbols do
+ byte(s)
+ end
+end
+
+local function sos(comps: { Comp }, ss: number, se: number, ah: number, al: number, dcOnly: boolean, acOnly: boolean)
+ byte(0xFF)
+ byte(0xDA)
+ u16be(6 + 2 * #comps)
+ byte(#comps)
+ for _, c in comps do
+ byte(c.id)
+ local td = if acOnly then 0 else c.td
+ local ta = if dcOnly then 0 else c.ta
+ byte(td * 16 + ta)
+ end
+ byte(ss)
+ byte(se)
+ 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)
+end
+local YR, YG, YB = fix(0.29900), fix(0.58700), fix(0.11400)
+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)
+ if bpp == 1 then
+ buffer.copy(Y, 0, px, 0, n)
+ if gray then
+ return Y, nil, nil
+ end
+ local Cb = buffer.create(n)
+ buffer.fill(Cb, 0, 128, n)
+ local Cr = buffer.create(n)
+ buffer.fill(Cr, 0, 128, n)
+ return Y, Cb, Cr
+ end
+ if gray then
+ for i = 0, n - 1 do
+ local o = i * bpp
+ local r, g, b = readu8(px, o), readu8(px, o + 1), readu8(px, o + 2)
+ writeu8(Y, i, (YR * r + YG * g + YB * b + 32768) // 65536)
+ end
+ return Y, nil, nil
+ end
+ local Cb, Cr = buffer.create(n), buffer.create(n)
+ for i = 0, n - 1 do
+ local o = i * bpp
+ local r, g, b = readu8(px, o), readu8(px, o + 1), readu8(px, o + 2)
+ writeu8(Y, i, (YR * r + YG * g + YB * b + 32768) // 65536)
+ writeu8(Cb, i, (-CBR * r - CBG * g + HALF * b + OFF) // 65536)
+ writeu8(Cr, i, (HALF * r - CRG * g - CRB * b + OFF) // 65536)
+ end
+ 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
+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
+ local r0 = math.min(oy * vf, h - 1) * w
+ local r1 = math.min(oy * vf + vf - 1, h - 1) * w
+ local bias = if hf == 2 and vf == 2 then 1 elseif hf == 2 then 0 else (if vf == 2 then 1 else 0)
+ for ox = 0, outW - 1 do
+ local x0 = math.min(ox * hf, w - 1)
+ local x1 = math.min(ox * hf + hf - 1, w - 1)
+ local v
+ if hf == 2 and vf == 2 then
+ v = (readu8(src, r0 + x0) + readu8(src, r0 + x1) + readu8(src, r1 + x0) + readu8(src, r1 + x1) + bias) // 4
+ bias = 3 - bias
+ elseif hf == 2 then
+ v = (readu8(src, r0 + x0) + readu8(src, r0 + x1) + bias) // 2
+ bias = 1 - bias
+ else
+ v = (readu8(src, r0 + x0) + readu8(src, r1 + x0) + bias) // 2
+ bias = 1 - bias
+ end
+ writeu8(out, oy * outW + ox, v)
+ end
+ end
+ return out
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+export type Options = {
+ quality: number, -- 1..100
+ sampling: string, -- "444" | "422" | "420"
+ progressive: boolean,
+ optimize: boolean, -- baseline: optimised Huffman tables (progressive always optimises)
+ gray: boolean,
+ restart: number, -- MCUs per restart interval (0 = none)
+ segments: { { marker: number, data: buffer } }, -- APPn / COM segments after the JFIF header
+ 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); the caller
+-- validated sizes (1..65535) 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)
+ OP = 0
+ ACC, NB = 0, 0
+ GATHER = false
+ EOBRUN, BE = 0, 0
+
+ local Y, Cb, Cr = planes(px, w, h, bpp, o.gray)
+ local hs, vs = 1, 1
+ if not o.gray then
+ if o.sampling == "420" then
+ hs, vs = 2, 2
+ elseif o.sampling == "422" then
+ hs, vs = 2, 1
+ end
+ end
+ local mcusX = math.ceil(w / (8 * hs))
+ local mcusY = math.ceil(h / (8 * vs))
+ local qt = { Tables.quant(Tables.LUMA, o.quality), Tables.quant(Tables.CHROMA, o.quality) }
+ local qdiv = {}
+ for t = 1, 2 do
+ local b = buffer.create(128)
+ for i = 1, 64 do
+ writeu16(b, (i - 1) * 2, qt[t][i])
+ end
+ 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
+ local ch, cv = if i == 1 then hs else 1, if i == 1 then vs else 1
+ local cw = math.ceil(w * ch / hs)
+ local chh = math.ceil(h * cv / vs)
+ local bw, bh = math.ceil(cw / 8), math.ceil(chh / 8)
+ local bpl, bpc = mcusX * ch, mcusY * cv
+ local plane, pw, ph = src, w, h
+ if ch < hs or cv < vs then
+ pw, ph = bw * 8, chh
+ plane = downsample(src, w, h, hs // ch, vs // cv, pw, ph)
+ end
+ local coef = buffer.create(bpl * bpc * 128)
+ local c: Comp = {
+ id = i,
+ h = ch,
+ v = cv,
+ tq = if i == 1 then 0 else 1,
+ td = if i == 1 then 0 else 1,
+ ta = if i == 1 then 0 else 1,
+ bw = bw,
+ bh = bh,
+ bpl = bpl,
+ bpc = bpc,
+ coef = coef,
+ last = 0,
+ }
+ local div = qdiv[c.tq + 1]
+ for by = 0, bpc - 1 do
+ for bx = 0, bpl - 1 do
+ local off = (by * bpl + bx) * 128
+ if by < bh and bx < bw then
+ Dct.fdctQuantize(plane, pw, bx * 8, by * 8, pw, ph, div, coef, off)
+ elseif by < bh then
+ writei16(coef, off, readi16(coef, off - 128)) -- right edge: the previous block's DC
+ else
+ -- bottom: the DC of the MCU's last block in the row above
+ local lb = (bx // ch) * ch + ch - 1
+ writei16(coef, off, readi16(coef, ((by - 1) * bpl + lb) * 128))
+ end
+ end
+ end
+ comps[i] = c
+ end
+
+ -- headers
+ byte(0xFF)
+ byte(0xD8)
+ if o.jfif then
+ local d = o.density or { unit = 0, x = 1, y = 1 }
+ byte(0xFF)
+ byte(0xE0)
+ u16be(16)
+ for _, ch in { 0x4A, 0x46, 0x49, 0x46, 0 } do
+ byte(ch)
+ end
+ byte(1)
+ byte(1)
+ byte(d.unit)
+ u16be(d.x)
+ u16be(d.y)
+ byte(0)
+ byte(0)
+ end
+ for _, s in o.segments do
+ local n = buffer.len(s.data)
+ byte(0xFF)
+ byte(s.marker)
+ u16be(n + 2)
+ grow(n)
+ buffer.copy(OUT, OP, s.data, 0, n)
+ OP += n
+ end
+ for t = 1, (if o.gray then 1 else 2) do
+ byte(0xFF)
+ byte(0xDB)
+ u16be(67)
+ byte(t - 1)
+ for k = 0, 63 do
+ byte(qt[t][readu8(ZZ, k) + 1])
+ end
+ end
+ byte(0xFF)
+ byte(if o.progressive then 0xC2 else 0xC0)
+ u16be(8 + 3 * #comps)
+ byte(8)
+ u16be(h)
+ u16be(w)
+ byte(#comps)
+ for _, c in comps do
+ byte(c.id)
+ byte(c.h * 16 + c.v)
+ byte(c.tq)
+ end
+ local ntab = if o.gray then 1 else 2
+
+ local function restartMarker(n: number)
+ flushBits()
+ byte(0xFF)
+ byte(0xD0 + n)
+ end
+
+ if not o.progressive then
+ if o.optimize then
+ GATHER = true
+ for t = 1, ntab do
+ dcFreq[t] = table.create(257, 0)
+ acFreq[t] = table.create(257, 0)
+ end
+ for _, c in comps do
+ c.last = 0
+ end
+ walk(comps, mcusX, mcusY, o.restart, function()
+ for _, c in comps do
+ c.last = 0
+ end
+ end, blockSeq)
+ GATHER = false
+ end
+ for t = 1, ntab do
+ local dcC, dcS, acC, acS
+ if o.optimize then
+ dcC, dcS = optimal(dcFreq[t])
+ acC, acS = optimal(acFreq[t])
+ else
+ local d, a = Tables.DC[t], Tables.AC[t]
+ dcC, dcS, acC, acS = d.counts, d.symbols, a.counts, a.symbols
+ end
+ dcTab[t] = derive(dcC, dcS)
+ acTab[t] = derive(acC, acS)
+ dcFreq[t] = table.create(257, 0)
+ acFreq[t] = table.create(257, 0)
+ -- libjpeg emits each table before the scan in component order: DC0, AC0, DC1, AC1
+ dht(0, t - 1, dcC, dcS)
+ dht(1, t - 1, acC, acS)
+ end
+ if o.restart > 0 then
+ byte(0xFF)
+ byte(0xDD)
+ u16be(4)
+ u16be(o.restart)
+ end
+ sos(comps, 0, 63, 0, 0, false, false)
+ for _, c in comps do
+ c.last = 0
+ end
+ walk(comps, mcusX, mcusY, o.restart, function(n: number)
+ restartMarker(n)
+ for _, c in comps do
+ c.last = 0
+ end
+ end, blockSeq)
+ flushBits()
+ else
+ local script: { ScanSpec }
+ if o.gray then
+ script = {
+ { comps = { 1 }, ss = 0, se = 0, ah = 0, al = 1 },
+ { comps = { 1 }, ss = 1, se = 5, ah = 0, al = 2 },
+ { comps = { 1 }, ss = 6, se = 63, ah = 0, al = 2 },
+ { comps = { 1 }, ss = 1, se = 63, ah = 2, al = 1 },
+ { comps = { 1 }, ss = 0, se = 0, ah = 1, al = 0 },
+ { comps = { 1 }, ss = 1, se = 63, ah = 1, al = 0 },
+ }
+ else
+ script = {
+ { comps = { 1, 2, 3 }, ss = 0, se = 0, ah = 0, al = 1 },
+ { comps = { 1 }, ss = 1, se = 5, ah = 0, al = 2 },
+ { comps = { 3 }, ss = 1, se = 63, ah = 0, al = 1 },
+ { comps = { 2 }, ss = 1, se = 63, ah = 0, al = 1 },
+ { comps = { 1 }, ss = 6, se = 63, ah = 0, al = 2 },
+ { comps = { 1 }, ss = 1, se = 63, ah = 2, al = 1 },
+ { comps = { 1, 2, 3 }, ss = 0, se = 0, ah = 1, al = 0 },
+ { comps = { 3 }, ss = 1, se = 63, ah = 1, al = 0 },
+ { comps = { 2 }, ss = 1, se = 63, ah = 1, al = 0 },
+ { comps = { 1 }, ss = 1, se = 63, ah = 1, al = 0 },
+ }
+ end
+ local driSent = false
+ for _, sc in script do
+ local sComps = {}
+ for _, ci in sc.comps do
+ table.insert(sComps, comps[ci])
+ end
+ local ss, se, ah, al = sc.ss, sc.se, sc.ah, sc.al
+ local isDc = ss == 0
+ local blockFn: (Comp, number) -> ()
+ if isDc and ah == 0 then
+ blockFn = function(c: Comp, off: number)
+ blockDcFirst(c, off, al)
+ end
+ elseif isDc then
+ blockFn = function(c: Comp, off: number)
+ bits(band(readi16(c.coef, off) // 2 ^ al, 1), 1)
+ end
+ elseif ah == 0 then
+ blockFn = function(c: Comp, off: number)
+ blockAcFirst(c, off, ss, se, al)
+ end
+ else
+ blockFn = function(c: Comp, off: number)
+ blockAcRefine(c, off, ss, se, al)
+ end
+ end
+ local function onRestart(n: number)
+ emitEobrun()
+ if not GATHER then
+ restartMarker(n)
+ end
+ for _, c in sComps do
+ c.last = 0
+ end
+ EOBRUN, BE = 0, 0
+ end
+ local function pass()
+ for _, c in sComps do
+ c.last = 0
+ end
+ EOBRUN, BE = 0, 0
+ 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
+ dcFreq[t] = table.create(257, 0)
+ acFreq[t] = table.create(257, 0)
+ end
+ if not isDc then
+ curAcFreq = acFreq[sComps[1].ta + 1]
+ end
+ pass()
+ GATHER = false
+ local sent = {}
+ for _, c in sComps do
+ local slot = if isDc then c.td else c.ta
+ if not sent[slot] then
+ sent[slot] = true
+ local counts, syms = optimal(if isDc then dcFreq[slot + 1] else acFreq[slot + 1])
+ dht(if isDc then 0 else 1, slot, counts, syms)
+ if isDc then
+ dcTab[slot + 1] = derive(counts, syms)
+ else
+ acTab[slot + 1] = derive(counts, syms)
+ end
+ end
+ end
+ if not isDc then
+ curAc = acTab[sComps[1].ta + 1]
+ end
+ end
+ if o.restart > 0 and not driSent then
+ driSent = true
+ byte(0xFF)
+ byte(0xDD)
+ u16be(4)
+ u16be(o.restart)
+ end
+ sos(sComps, ss, se, ah, al, isDc, not isDc or ah > 0) -- DC refinement uses no table: td = 0 (as libjpeg)
+ pass()
+ flushBits()
+ end
+ end
+ byte(0xFF)
+ byte(0xD9)
+ local res = buffer.create(OP)
+ buffer.copy(res, 0, OUT, 0, OP)
+ OUT = buffer.create(0)
+ CAP = 0
+ return res
+end
+
+return Encode
diff --git a/src/Formats/image/jpeg/Scan.luau b/src/Formats/image/jpeg/Scan.luau
new file mode 100644
index 0000000..ec8f45f
--- /dev/null
+++ b/src/Formats/image/jpeg/Scan.luau
@@ -0,0 +1,456 @@
+--!strict
+--!native
+--!optimize 2
+-- 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.
+-- 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
+-- [1096, 1168) delta[l]: i32, symbol index = code + delta[l]
+-- [1168, 1424) symbols
+-- [1424, 1426) symbol count
+-- [1428, 3476) fast AC lookup by the next 9 bits: i32 value * 256 + run * 16 + total length, when the code
+-- and its extra bits fit in 9 bits (0 otherwise)
+local readu8, readu16, readu32, readi32, readi16 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi32, buffer.readi16
+local writeu8, writeu16, writeu32, writei32, writei16 = buffer.writeu8, buffer.writeu16, buffer.writeu32, buffer.writei32, buffer.writei16
+local band, bor, lshift, rshift, byteswap = bit32.band, bit32.bor, bit32.lshift, bit32.rshift, bit32.byteswap
+
+local Scan = {}
+
+Scan.PAD = 4096
+Scan.TABLE_SIZE = 3476
+
+local T_MAX = 1024
+local T_DELTA = 1096
+local T_VAL = 1168
+local T_COUNT = 1424
+local T_FASTAC = 1428
+
+-- zigzag index -> natural (row-major) index, padded with 63s so a run past the end stays in range
+local ZZ = buffer.create(80)
+do
+ local i = 0
+ for s = 0, 14 do
+ local lo, hi = math.max(0, s - 7), math.min(s, 7)
+ if s % 2 == 0 then
+ for r = hi, lo, -1 do
+ writeu8(ZZ, i, r * 8 + (s - r))
+ i += 1
+ end
+ else
+ for r = lo, hi do
+ writeu8(ZZ, i, r * 8 + (s - r))
+ i += 1
+ end
+ end
+ end
+ for j = 64, 79 do
+ writeu8(ZZ, j, 63)
+ end
+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.
+function Scan.buildTable(counts: { number }, symbols: { number }): buffer
+ local t = buffer.create(Scan.TABLE_SIZE)
+ local code, k = 0, 0
+ local nsym = #symbols
+ local codes, sizes = {}, {}
+ local broken = false
+ for l = 1, 16 do
+ writei32(t, T_DELTA + l * 4, k - code)
+ local n = counts[l] or 0
+ for _ = 1, n do
+ if broken or code >= lshift(1, l) or k >= nsym or k >= 256 then
+ broken = true
+ break
+ end
+ k += 1
+ codes[k] = code
+ sizes[k] = l
+ code += 1
+ end
+ writeu32(t, T_MAX + l * 4, if broken then 0 else lshift(code, 16 - l))
+ code *= 2
+ end
+ writeu32(t, T_MAX + 17 * 4, 0xFFFFFFFF)
+ for i = 1, k do
+ 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
+ local sym = symbols[i]
+ local base = lshift(codes[i], 9 - l)
+ for j = 0, lshift(1, 9 - l) - 1 do
+ local idx = base + j
+ writeu16(t, idx * 2, l * 256 + sym)
+ local r, s = rshift(sym, 4), band(sym, 15)
+ if s ~= 0 and l + s <= 9 then
+ local v = band(rshift(idx, 9 - l - s), lshift(1, s) - 1)
+ if v < lshift(1, s - 1) then
+ v = v - lshift(1, s) + 1
+ end
+ writei32(t, T_FASTAC + idx * 4, v * 256 + r * 16 + l + s)
+ end
+ end
+ end
+ end
+ 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
+ local b = readu8(src, pos)
+ if b ~= 0xFF then
+ writeu8(dst, o, b)
+ o += 1
+ pos += 1
+ else
+ local q = pos + 1
+ while q < n and readu8(src, q) == 0xFF do
+ q += 1
+ end
+ if q >= n then
+ pos = n
+ break
+ end
+ local m = readu8(src, q)
+ if m == 0 then
+ writeu8(dst, o, 0xFF)
+ o += 1
+ pos = q + 1
+ elseif m >= 0xD0 and m <= 0xD7 then
+ nr += 1
+ rst[nr] = o
+ pos = q + 1
+ else
+ pos = q - 1
+ break
+ end
+ end
+ end
+ buffer.fill(dst, o, 0, Scan.PAD)
+ return pos, o, nr
+end
+
+local function huff(d: buffer, pos: number, t: buffer): (number, number)
+ local w = lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7))
+ local f = readu16(t, rshift(w, 23) * 2)
+ if f ~= 0 then
+ return band(f, 255), pos + rshift(f, 8)
+ end
+ local c = rshift(w, 16)
+ local l = 10
+ while c >= readu32(t, T_MAX + l * 4) do
+ l += 1
+ end
+ if l > 16 then
+ return 0, pos + 16 -- invalid code
+ end
+ local idx = rshift(c, 16 - l) + readi32(t, T_DELTA + l * 4)
+ if idx < 0 or idx >= readu16(t, T_COUNT) then
+ return 0, pos + l
+ end
+ 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
+
+local function extend(v: number, s: number): number
+ if v < lshift(1, s - 1) then
+ return v - lshift(1, s) + 1
+ end
+ 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)
+ if s ~= 0 then
+ if s > 16 then
+ s = 16
+ end
+ pred += extend(bits(d, pos, s), s)
+ pos += s
+ end
+ writei16(coef, off, pred)
+ local k = 1
+ while k < 64 do
+ local w = lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7))
+ local fa = readi32(act, T_FASTAC + rshift(w, 23) * 4)
+ if fa ~= 0 then
+ local low = fa % 256
+ k += low // 16
+ pos += low % 16
+ if k > 63 then
+ break
+ end
+ writei16(coef, off + readu8(ZZ, k) * 2, fa // 256)
+ k += 1
+ else
+ local rs
+ rs, pos = huff(d, pos, act)
+ local r, sz = rshift(rs, 4), band(rs, 15)
+ if sz == 0 then
+ if r ~= 15 then
+ break
+ end
+ k += 16
+ else
+ k += r
+ if k > 63 then
+ break
+ end
+ writei16(coef, off + readu8(ZZ, k) * 2, extend(bits(d, pos, sz), sz))
+ pos += sz
+ k += 1
+ end
+ end
+ end
+ return pos, pred
+end
+
+local function blockDcFirst(d: buffer, pos: number, coef: buffer, off: number, dct: buffer, pred: number, al: number): (number, number)
+ local s
+ s, pos = huff(d, pos, dct)
+ if s ~= 0 then
+ if s > 16 then
+ s = 16
+ end
+ pred += extend(bits(d, pos, s), s)
+ pos += s
+ end
+ writei16(coef, off, pred * lshift(1, al))
+ return pos, pred
+end
+
+local function blockAcFirst(d: buffer, pos: number, coef: buffer, off: number, act: buffer, ss: number, se: number, al: number, eobrun: number): (number, number)
+ if eobrun > 0 then
+ return pos, eobrun - 1
+ end
+ local mul = lshift(1, al)
+ local k = ss
+ while k <= se do
+ local w = lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7))
+ local fa = readi32(act, T_FASTAC + rshift(w, 23) * 4)
+ if fa ~= 0 then
+ local low = fa % 256
+ k += low // 16
+ pos += low % 16
+ if k > se then
+ break
+ end
+ writei16(coef, off + readu8(ZZ, k) * 2, (fa // 256) * mul)
+ k += 1
+ else
+ local rs
+ rs, pos = huff(d, pos, act)
+ local r, s = rshift(rs, 4), band(rs, 15)
+ if s == 0 then
+ if r < 15 then
+ eobrun = lshift(1, r) - 1
+ if r > 0 then
+ eobrun += bits(d, pos, r)
+ pos += r
+ end
+ break
+ end
+ k += 16
+ else
+ k += r
+ if k > se then
+ break
+ end
+ writei16(coef, off + readu8(ZZ, k) * 2, extend(bits(d, pos, s), s) * mul)
+ pos += s
+ k += 1
+ end
+ end
+ end
+ return pos, eobrun
+end
+
+-- successive-approximation refinement of AC coefficients ss..se (as stb_image / libjpeg decode_mcu_AC_refine)
+local function blockAcRefine(d: buffer, pos: number, coef: buffer, off: number, act: buffer, ss: number, se: number, al: number, eobrun: number): (number, number)
+ local bit = lshift(1, al)
+ if eobrun > 0 then
+ for k = ss, se do
+ local o = off + readu8(ZZ, k) * 2
+ local p = readi16(coef, o)
+ if p ~= 0 then
+ local b = rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 31)
+ pos += 1
+ if b ~= 0 and band(p, bit) == 0 then
+ writei16(coef, o, if p > 0 then p + bit else p - bit)
+ end
+ end
+ end
+ return pos, eobrun - 1
+ end
+ local k = ss
+ while k <= se do
+ local rs
+ rs, pos = huff(d, pos, act)
+ local s, r = band(rs, 15), rshift(rs, 4)
+ local val = 0
+ if s == 0 then
+ if r < 15 then
+ eobrun = lshift(1, r) - 1
+ if r > 0 then
+ eobrun += bits(d, pos, r)
+ pos += r
+ end
+ r = 64 -- the rest of the block only refines
+ end
+ else
+ -- s must be 1; anything else is corrupt and treated as 1
+ local b = rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 31)
+ pos += 1
+ val = if b ~= 0 then bit else -bit
+ end
+ while k <= se do
+ local o = off + readu8(ZZ, k) * 2
+ k += 1
+ local p = readi16(coef, o)
+ if p ~= 0 then
+ local b = rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 31)
+ pos += 1
+ if b ~= 0 and band(p, bit) == 0 then
+ writei16(coef, o, if p > 0 then p + bit else p - bit)
+ end
+ else
+ if r == 0 then
+ if val ~= 0 then
+ writei16(coef, o, val)
+ end
+ break
+ end
+ r -= 1
+ end
+ end
+ end
+ -- an EOB run that started in this block counts it already (eobrun = run length - 1)
+ return pos, eobrun
+end
+
+export type ScanComp = {
+ coef: buffer, -- i16 coefficients, 64 per block in natural order, blocks row-major on a bpl-wide grid
+ bpl: number,
+ h: number,
+ v: number,
+ bw: number, -- blocks across / down the component itself (non-interleaved scans)
+ bh: number,
+ dct: buffer?,
+ act: buffer?,
+ pred: number,
+}
+
+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
+ ss: number,
+ se: number,
+ al: number,
+}
+
+-- 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
+ local mode, ss, se, al, ri = P.mode, P.ss, P.se, P.al, P.ri
+ local endBits = cleanLen * 8
+ local units, ux
+ if nc == 1 then
+ ux = comps[1].bw
+ units = ux * comps[1].bh
+ else
+ ux = P.mcusX
+ units = ux * P.mcusY
+ end
+ for i = 1, nc do
+ comps[i].pred = 0
+ end
+ local pos, eobrun, rstIdx = 0, 0, 0
+ local truncated, skipping = false, false
+ local bit = lshift(1, al)
+ for u = 0, units - 1 do
+ if ri > 0 and u > 0 and u % ri == 0 then
+ rstIdx += 1
+ if rstIdx <= nrst then
+ pos = rst[rstIdx] * 8
+ skipping = false
+ end
+ for i = 1, nc do
+ comps[i].pred = 0
+ end
+ eobrun = 0
+ end
+ if pos > endBits then
+ truncated = true
+ if ri == 0 or rstIdx >= nrst then
+ break
+ end
+ skipping = true
+ end
+ if not skipping then
+ local my, mx = u // ux, u % ux
+ for ci = 1, nc do
+ local c = comps[ci]
+ local bh, bw, by0, bx0
+ if nc == 1 then
+ bh, bw, by0, bx0 = 1, 1, my, mx
+ else
+ bh, bw, by0, bx0 = c.v, c.h, my * c.v, mx * c.h
+ end
+ local coef, bpl = c.coef, c.bpl
+ for by = by0, by0 + bh - 1 do
+ for bx = bx0, bx0 + bw - 1 do
+ local off = (by * bpl + bx) * 128
+ if mode == 0 then
+ pos, c.pred = blockSeq(d, pos, coef, off, c.dct :: buffer, c.act :: buffer, c.pred)
+ elseif mode == 1 then
+ pos, c.pred = blockDcFirst(d, pos, coef, off, c.dct :: buffer, c.pred, al)
+ elseif mode == 2 then
+ local b = rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 31)
+ pos += 1
+ if b ~= 0 then
+ writei16(coef, off, bor(readi16(coef, off), bit))
+ end
+ elseif mode == 3 then
+ pos, eobrun = blockAcFirst(d, pos, coef, off, c.act :: buffer, ss, se, al, eobrun)
+ else
+ pos, eobrun = blockAcRefine(d, pos, coef, off, c.act :: buffer, ss, se, al, eobrun)
+ end
+ end
+ end
+ end
+ end
+ end
+ return pos, truncated
+end
+
+return Scan
diff --git a/src/Formats/image/jpeg/Tables.luau b/src/Formats/image/jpeg/Tables.luau
new file mode 100644
index 0000000..e524d54
--- /dev/null
+++ b/src/Formats/image/jpeg/Tables.luau
@@ -0,0 +1,77 @@
+--!strict
+-- image/jpeg/Tables: the standard tables of ITU T.81 annex K: the example Huffman tables (K.3, which every baseline
+-- encoder without optimisation writes and Motion-JPEG frames leave out) and the luminance / chrominance quantisation
+-- tables (K.1) with libjpeg's quality scaling (jcparam.c jpeg_quality_scaling / jpeg_add_quant_table).
+local Tables = {}
+
+local function range(t: { number }, a: number, b: number)
+ for v = a, b do
+ table.insert(t, v)
+ end
+end
+
+-- { counts (16 code-length counts), symbols } per table: dc[1] luma, dc[2] chroma, ac[1], ac[2]
+local dcl = { 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 }
+local dcc = { 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 }
+local dcv = {}
+range(dcv, 0, 11)
+local acl = { 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d }
+local aclv = {
+ 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
+ 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
+ 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
+ 0x29, 0x2a,
+}
+range(aclv, 0x34, 0x3a)
+for hi = 4, 8 do
+ range(aclv, hi * 16 + 3, hi * 16 + 10)
+end
+for hi = 9, 13 do
+ range(aclv, hi * 16 + 2, hi * 16 + 10)
+end
+range(aclv, 0xe1, 0xea)
+range(aclv, 0xf1, 0xfa)
+local acc = { 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 }
+local accv = {
+ 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
+ 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
+ 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
+ 0x27, 0x28, 0x29, 0x2a,
+}
+range(accv, 0x35, 0x3a)
+for hi = 4, 7 do
+ range(accv, hi * 16 + 3, hi * 16 + 10)
+end
+for hi = 8, 14 do
+ range(accv, hi * 16 + 2, hi * 16 + 10)
+end
+range(accv, 0xf2, 0xfa)
+
+export type Spec = { counts: { number }, symbols: { number } }
+Tables.DC = { { counts = dcl, symbols = dcv }, { counts = dcc, symbols = dcv } } :: { Spec }
+Tables.AC = { { counts = acl, symbols = aclv }, { counts = acc, symbols = accv } } :: { Spec }
+
+-- K.1, natural (row-major) order
+Tables.LUMA = {
+ 16, 11, 10, 16, 24, 40, 51, 61, 12, 12, 14, 19, 26, 58, 60, 55, 14, 13, 16, 24, 40, 57, 69, 56, 14, 17, 22, 29,
+ 51, 87, 80, 62, 18, 22, 37, 56, 68, 109, 103, 77, 24, 35, 55, 64, 81, 104, 113, 92, 49, 64, 78, 87, 103, 121,
+ 120, 101, 72, 92, 95, 98, 112, 100, 103, 99,
+}
+Tables.CHROMA = {
+ 17, 18, 24, 47, 99, 99, 99, 99, 18, 21, 26, 66, 99, 99, 99, 99, 24, 26, 56, 99, 99, 99, 99, 99, 47, 66, 99, 99,
+ 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99,
+ 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
+ local out = table.create(64, 1)
+ for i = 1, 64 do
+ out[i] = math.clamp((base[i] * scale + 50) // 100, 1, 255)
+ end
+ return out
+end
+
+return Tables
diff --git a/src/Formats/image/jpeg/init.luau b/src/Formats/image/jpeg/init.luau
new file mode 100644
index 0000000..f6c3077
--- /dev/null
+++ b/src/Formats/image/jpeg/init.luau
@@ -0,0 +1,285 @@
+--!strict
+-- image/jpeg: JPEG / JFIF / EXIF (ITU T.81). Absorbed from jpeg-luau 1.0 (same author: the Huffman decoder, IDCTs,
+-- upsampling and colour conversion, bit-exact with libjpeg-turbo's djpeg) and extended with arithmetic coding, meta
+-- (EXIF, ICC, comments, density) and an encoder. IJG-derived parts: licenses/libjpeg-turbo-LICENSE.md.
+-- Decode: baseline, extended and progressive frames, Huffman or arithmetic coded (SOF0/1/2/9/10), 8 and 12-bit
+-- samples, 1, 3 or 4 components with any sampling factors 1..4, restart intervals (resynchronising after corrupt
+-- data), grey / YCbCr / RGB / CMYK / YCCK (Adobe APP14), scaled decodes (opts.scale = 2, 4, 8 through libjpeg's
+-- reduced IDCTs), EXIF orientation reported in meta.orientation and applied with opts.orient. Truncated or corrupt
+-- scans decode as far as they go (meta.truncated = true).
+-- 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, EXIF / ICC / comment segments from meta;
+-- byte-identical to cjpeg for the same settings.
+-- Not supported: lossless (SOF3) and hierarchical frames, DNL, 2-component images, ICC colour management, 12-bit
+-- or CMYK encoding.
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Types = require("@formats/Types")
+local Decode = require("@formats/image/jpeg/Decode")
+local Encode = require("@formats/image/jpeg/Encode")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Jpeg = {
+ name = "jpeg",
+ category = "image",
+ extensions = { "jpg", "jpeg", "jpe", "jfif" },
+ mime = { "image/jpeg" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/Dct" },
+ caps = { decode = true, encode = true, lossy = true, alpha = false, depths = { 8, 12 }, progressive = true, arithmetic = true },
+}
+
+-- ------------------------------------------------------------------------------------------------ types
+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)
+ native: boolean?, -- grey files decode to gray8 (default false: rgba8)
+ maxPixels: number?, -- refuse larger images (default 2^26)
+}
+export type EncodeOptions = {
+ quality: number?, -- 1..100 (default 90), libjpeg's scaling of the T.81 annex K tables
+ subsampling: ("420" | "422" | "444")?, -- chroma subsampling (default "420")
+ 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)
+ meta: boolean?, -- write meta.exif (APP1), meta.icc (APP2) and meta.text.comment (COM) (default true)
+}
+
+export type Info = {
+ width: number,
+ height: number,
+ components: number,
+ progressive: boolean,
+ arithmetic: boolean,
+ precision: number,
+ colorSpace: string,
+ sampling: { { number } }, -- { h, v } per component
+ orientation: number,
+ adobe: number?,
+ jfif: boolean,
+}
+
+-- ------------------------------------------------------------------------------------------------ constants
+local CODES = { corrupt = Err.CORRUPT, unsupported = Err.UNSUPPORTED, limit = Err.LIMIT, truncated = Err.TRUNCATED, arg = Err.ARG }
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Jpeg.sniff(r: Bytes.Reader): number
+ local s = r:peek(3)
+ return if s == "\255\216\255" then 1 else 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+local function parse(r: Bytes.Reader, opts: any, headerOnly: boolean): (Decode.State?, Err.Err?)
+ local ok, st, code, msg = pcall(Decode.parse, r.buf, r.base, r.limit, opts, headerOnly)
+ if not ok then
+ return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(st))
+ end
+ if not st then
+ return nil, Err.new(CODES[code :: string] or Err.CORRUPT, msg or "decode failed")
+ end
+ return st, nil
+end
+
+-- info(r) -> Info | nil, Err (reads the headers up to the frame header)
+function Jpeg.info(r: Bytes.Reader): (Info?, Err.Err?)
+ local st, err = parse(r, nil, true)
+ if not st then
+ return nil, err
+ end
+ local f = st.frame
+ local sampling = {}
+ for _, c in f.comps do
+ table.insert(sampling, { c.h, c.v })
+ end
+ return {
+ width = f.width,
+ height = f.height,
+ components = #f.comps,
+ progressive = f.progressive,
+ arithmetic = f.arithmetic,
+ precision = f.precision,
+ colorSpace = Decode.colorSpaceOf(f, st.adobe, st.jfif),
+ sampling = sampling,
+ orientation = st.orientation,
+ adobe = st.adobe,
+ jfif = st.jfif,
+ },
+ nil
+end
+
+-- the EXIF orientation applied to rgba8 pixels: buffer, width, height
+local function orient(px: buffer, w: number, h: number, o: number): (buffer, number, number)
+ if o <= 1 or o > 8 then
+ return px, w, h
+ end
+ local swap = o >= 5
+ local ow, oh = if swap then h else w, if swap then w else h
+ local out = buffer.create(ow * oh * 4)
+ local readu32, writeu32 = buffer.readu32, buffer.writeu32
+ for y = 0, oh - 1 do
+ for x = 0, ow - 1 do
+ local col, row
+ if o == 2 then
+ col, row = w - 1 - x, y
+ elseif o == 3 then
+ col, row = w - 1 - x, h - 1 - y
+ elseif o == 4 then
+ col, row = x, h - 1 - y
+ elseif o == 5 then
+ col, row = y, x
+ elseif o == 6 then
+ col, row = y, h - 1 - x
+ elseif o == 7 then
+ col, row = w - 1 - y, h - 1 - x
+ else
+ col, row = w - 1 - y, x
+ end
+ writeu32(out, (y * ow + x) * 4, readu32(px, (row * w + col) * 4))
+ end
+ end
+ return out, ow, oh
+end
+
+function Jpeg.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
+ local st, err = parse(r, opts, false)
+ if not st then
+ return nil, err
+ end
+ local ok, w, h, px, space = pcall(Decode.output, st :: Decode.State)
+ if not ok then
+ return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(w))
+ end
+ if not w then
+ return nil, Err.new(CODES[h :: string] or Err.CORRUPT, tostring(px))
+ end
+ local orientation = st.orientation
+ if opts and opts.orient then
+ px, w, h = orient(px, w, h, orientation)
+ end
+ local img = Types.Image.new(1, 1)
+ img.width, img.height, img.pixels = w, h, px
+ if opts and opts.native and space == "gray" then
+ local g = buffer.create(w * h)
+ for i = 0, w * h - 1 do
+ buffer.writeu8(g, i, buffer.readu8(px, i * 4))
+ end
+ img.pixels, img.format = g, "gray8"
+ end
+ local f = st.frame
+ local sampling = {}
+ for _, c in f.comps do
+ table.insert(sampling, { c.h, c.v })
+ end
+ img.meta.orientation = orientation
+ img.meta.oriented = (opts and opts.orient) or false
+ img.meta.exif = st.exif
+ img.meta.icc = st.icc
+ if #st.comments > 0 then
+ img.meta.text = { comment = table.concat(st.comments, "\n") }
+ end
+ if st.density and st.density.unit > 0 and st.density.x > 0 and st.density.y > 0 then
+ local k = if st.density.unit == 2 then 2.54 else 1
+ img.meta.dpi = { x = st.density.x * k, y = st.density.y * k }
+ end
+ img.meta.truncated = st.truncated
+ img.meta.source = {
+ format = "jpeg",
+ bitDepth = f.precision,
+ colorType = space,
+ components = #f.comps,
+ progressive = f.progressive,
+ arithmetic = f.arithmetic,
+ sampling = sampling,
+ scale = st.scale,
+ adobe = st.adobe,
+ jfif = st.jfif,
+ }
+ return img, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+local BPP = { rgba8 = 4, rgb8 = 3, gray8 = 1 }
+
+function Jpeg.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
+ if type(img) ~= "table" or type(img.pixels) ~= "buffer" or type(img.width) ~= "number" or type(img.height) ~= "number" then
+ return nil, Err.new(Err.ARG, "needs an Image")
+ end
+ local bpp = BPP[img.format]
+ if not bpp then
+ return nil, Err.new(Err.ARG, "needs an rgba8, rgb8 or gray8 Image (got " .. tostring(img.format) .. ")")
+ end
+ local w, h = img.width, img.height
+ if w < 1 or h < 1 or w > 65535 or h > 65535 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < w * h * bpp then
+ return nil, Err.new(Err.ARG, "bad image size or pixel buffer (1..65535 per side)")
+ end
+ local o: any = opts or {}
+ local quality = o.quality or 90
+ if type(quality) ~= "number" or quality < 1 or quality > 100 then
+ return nil, Err.new(Err.ARG, "quality must be 1..100")
+ end
+ local sub = o.subsampling or "420"
+ if sub ~= "420" and sub ~= "422" and sub ~= "444" then
+ return nil, Err.new(Err.ARG, "subsampling must be \"420\", \"422\" or \"444\"")
+ end
+ local restart = o.restart or 0
+ if type(restart) ~= "number" or restart < 0 or restart > 65535 or restart % 1 ~= 0 then
+ return nil, Err.new(Err.ARG, "restart must be 0..65535 MCUs")
+ end
+ local gray = o.gray
+ if gray == nil then
+ gray = img.format == "gray8"
+ end
+ local segments = {}
+ local meta = img.meta or {}
+ if o.meta ~= false then
+ if type(meta.exif) == "buffer" and buffer.len(meta.exif) <= 65527 then
+ local d = buffer.create(buffer.len(meta.exif) + 6)
+ buffer.writestring(d, 0, "Exif\0\0")
+ buffer.copy(d, 6, meta.exif)
+ table.insert(segments, { marker = 0xE1, data = d })
+ end
+ if type(meta.icc) == "buffer" then
+ local icc = meta.icc :: buffer
+ local n = buffer.len(icc)
+ local chunk = 65519
+ local count = math.max(1, math.ceil(n / chunk))
+ if count <= 255 then
+ for i = 1, count do
+ local a = (i - 1) * chunk
+ local l = math.min(chunk, n - a)
+ local d = buffer.create(l + 14)
+ buffer.writestring(d, 0, "ICC_PROFILE\0")
+ buffer.writeu8(d, 12, i)
+ buffer.writeu8(d, 13, count)
+ buffer.copy(d, 14, icc, a, l)
+ table.insert(segments, { marker = 0xE2, data = d })
+ end
+ end
+ end
+ local text = meta.text
+ if type(text) == "table" and type(text.comment) == "string" and #text.comment <= 65533 then
+ table.insert(segments, { marker = 0xFE, data = buffer.fromstring(text.comment) })
+ end
+ end
+ local density = nil
+ if type(meta.dpi) == "table" and type(meta.dpi.x) == "number" and type(meta.dpi.y) == "number" then
+ density = { unit = 1, x = math.clamp(math.floor(meta.dpi.x + 0.5), 1, 65535), y = math.clamp(math.floor(meta.dpi.y + 0.5), 1, 65535) }
+ end
+ local out = Encode.run(img.pixels, w, h, bpp, {
+ quality = quality,
+ sampling = sub,
+ progressive = o.progressive == true,
+ optimize = o.optimize == true,
+ gray = gray,
+ restart = restart,
+ segments = segments,
+ jfif = o.jfif ~= false,
+ density = density,
+ })
+ return out, nil
+end
+
+return Jpeg
diff --git a/src/Formats/image/pnm/Codec.luau b/src/Formats/image/pnm/Codec.luau
new file mode 100644
index 0000000..5bc6285
--- /dev/null
+++ b/src/Formats/image/pnm/Codec.luau
@@ -0,0 +1,289 @@
+--!strict
+--!native
+--!optimize 2
+-- image/pnm/Codec: the Netpbm sample loops (native; never throws). Written from the Netpbm format pages (pbm, pgm,
+-- ppm, pam, pfm). Reading: binary 8 / 16-bit samples, ASCII samples (P1 digits may run together), P4 bit rows, PFM
+-- floats (either byte order, bottom-to-top rows); packing samples into a Types pixel format with maxval scaling.
+-- Writing: samples of any pixel format extracted at 1..4 channels and 8 or 16 bits. Every read is bounds-checked.
+local readu8, writeu8, readu16, writeu16 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16
+local readf32, writef32, readu32, writeu32 = buffer.readf32, buffer.writef32, buffer.readu32, buffer.writeu32
+local byteswap = bit32.byteswap
+
+local Codec = {}
+
+-- readSamples(b, p, limit, count, mode, out) -> true | false, message: count raw values into out (u16 each).
+-- mode 1 = binary 8-bit, 2 = binary 16-bit big-endian, 3 = ASCII decimal, 4 = ASCII P1 (single digits)
+function Codec.readSamples(b: buffer, p: number, limit: number, count: number, mode: number, out: buffer): (boolean, string?)
+ if mode == 1 then
+ if p + count > limit then
+ return false, "truncated"
+ end
+ for i = 0, count - 1 do
+ writeu16(out, i * 2, readu8(b, p + i))
+ end
+ return true, nil
+ elseif mode == 2 then
+ if p + count * 2 > limit then
+ return false, "truncated"
+ end
+ for i = 0, count - 1 do
+ writeu16(out, i * 2, readu8(b, p + i * 2) * 256 + readu8(b, p + i * 2 + 1))
+ end
+ return true, nil
+ end
+ local i = 0
+ while i < count do
+ -- skip whitespace and comments
+ while p < limit do
+ local c = readu8(b, p)
+ if c == 35 then -- '#'
+ while p < limit and readu8(b, p) ~= 10 and readu8(b, p) ~= 13 do
+ p += 1
+ end
+ elseif c == 32 or (c >= 9 and c <= 13) then
+ p += 1
+ else
+ break
+ end
+ end
+ if p >= limit then
+ return false, "truncated"
+ end
+ local c = readu8(b, p)
+ if c < 48 or c > 57 then
+ return false, "bad ASCII sample"
+ end
+ if mode == 4 then
+ writeu16(out, i * 2, c - 48)
+ p += 1
+ else
+ local v = 0
+ while p < limit do
+ local d = readu8(b, p)
+ if d < 48 or d > 57 then
+ break
+ end
+ v = math.min(v * 10 + d - 48, 65535)
+ p += 1
+ end
+ writeu16(out, i * 2, v)
+ end
+ i += 1
+ end
+ return true, nil
+end
+
+-- readBits(b, p, limit, w, h, out) -> ok, message: P4 rows (MSB first, rows padded to bytes) as u16 0 / 1 values
+function Codec.readBits(b: buffer, p: number, limit: number, w: number, h: number, out: buffer): (boolean, string?)
+ local rowBytes = (w + 7) // 8
+ if p + rowBytes * h > limit then
+ return false, "truncated"
+ end
+ for y = 0, h - 1 do
+ local r = p + y * rowBytes
+ for x = 0, w - 1 do
+ local byte = readu8(b, r + x // 8)
+ writeu16(out, (y * w + x) * 2, (byte // 2 ^ (7 - x % 8)) % 2)
+ end
+ end
+ return true, nil
+end
+
+-- format codes for pack / extract
+Codec.RGBA8, Codec.RGB8, Codec.GRAY8, Codec.GRAYA8, Codec.RGBA16, Codec.GRAY16, Codec.RGBAF32 = 0, 1, 2, 3, 4, 5, 6
+
+-- pack(samples, n, ch, maxval, invert, fmt, dst): n pixels of ch raw samples (u16, 0..maxval; invert: 1 - v for
+-- PBM bits) into dst in pixel format fmt, scaled to the format's range (8-bit: round(v * 255 / maxval))
+function Codec.pack(s: buffer, n: number, ch: number, maxval: number, invert: boolean, fmt: number, dst: buffer)
+ local wide = fmt == 4 or fmt == 5
+ local top = if wide then 65535 else 255
+ local half = maxval // 2
+ local function get(i: number): number
+ local v = math.min(readu16(s, i * 2), maxval)
+ if invert then
+ v = maxval - v
+ end
+ if maxval == top then
+ return v
+ end
+ return (v * top + half) // maxval
+ end
+ for i = 0, n - 1 do
+ local q = i * ch
+ local r, g, b, a
+ if ch == 1 then
+ r = get(q)
+ g, b, a = r, r, top
+ elseif ch == 2 then
+ r = get(q)
+ g, b, a = r, r, get(q + 1)
+ elseif ch == 3 then
+ r, g, b, a = get(q), get(q + 1), get(q + 2), top
+ else
+ r, g, b, a = get(q), get(q + 1), get(q + 2), get(q + 3)
+ end
+ if fmt == 0 then
+ writeu32(dst, i * 4, r + g * 256 + b * 65536 + a * 16777216)
+ elseif fmt == 1 then
+ writeu8(dst, i * 3, r)
+ writeu8(dst, i * 3 + 1, g)
+ writeu8(dst, i * 3 + 2, b)
+ elseif fmt == 2 then
+ writeu8(dst, i, r)
+ elseif fmt == 3 then
+ writeu8(dst, i * 2, r)
+ writeu8(dst, i * 2 + 1, a)
+ elseif fmt == 4 then
+ writeu16(dst, i * 8, r)
+ writeu16(dst, i * 8 + 2, g)
+ writeu16(dst, i * 8 + 4, b)
+ writeu16(dst, i * 8 + 6, a)
+ elseif fmt == 5 then
+ writeu16(dst, i * 2, r)
+ end
+ end
+end
+
+-- readFloats(b, p, limit, w, h, ch, le, dst) -> ok, message: PFM rows (bottom-to-top) into rgbaf32 dst
+function Codec.readFloats(b: buffer, p: number, limit: number, w: number, h: number, ch: number, le: boolean, dst: buffer): (boolean, string?)
+ if p + w * h * ch * 4 > limit then
+ return false, "truncated"
+ end
+ local tmp = buffer.create(4)
+ for y = 0, h - 1 do
+ local row = p + (h - 1 - y) * w * ch * 4
+ for x = 0, w - 1 do
+ local o = (y * w + x) * 16
+ for c = 0, ch - 1 do
+ local v
+ if le then
+ v = readf32(b, row + (x * ch + c) * 4)
+ else
+ writeu32(tmp, 0, byteswap(readu32(b, row + (x * ch + c) * 4)))
+ v = readf32(tmp, 0)
+ end
+ writef32(dst, o + c * 4, v)
+ end
+ if ch == 1 then
+ local v = readf32(dst, o)
+ writef32(dst, o + 4, v)
+ writef32(dst, o + 8, v)
+ end
+ writef32(dst, o + 12, 1)
+ end
+ end
+ return true, nil
+end
+
+local function f(v: number): number
+ if v ~= v then
+ return 0
+ end
+ return math.floor(math.clamp(v, 0, 1) * 65535 + 0.5)
+end
+
+-- extract(px, fmt, n, ch, wide) -> u16 samples: n pixels of format fmt as ch channels (1 grey (Rec. 601 luma for
+-- colour sources, Pillow's L = (299 R + 587 G + 114 B) / 1000), 2 grey + alpha, 3 RGB, 4 RGBA), 16-bit if wide
+function Codec.extract(px: buffer, fmt: number, n: number, ch: number, wide: boolean): buffer
+ local out = buffer.create(n * ch * 2)
+ local srcWide = fmt == 4 or fmt == 5
+ local isGray = fmt == 2 or fmt == 3 or fmt == 5
+ for i = 0, n - 1 do
+ local r, g, b, a
+ if fmt == 0 then
+ r, g, b, a = readu8(px, i * 4), readu8(px, i * 4 + 1), readu8(px, i * 4 + 2), readu8(px, i * 4 + 3)
+ elseif fmt == 1 then
+ r, g, b, a = readu8(px, i * 3), readu8(px, i * 3 + 1), readu8(px, i * 3 + 2), 255
+ elseif fmt == 2 then
+ r = readu8(px, i)
+ g, b, a = r, r, 255
+ elseif fmt == 3 then
+ r, a = readu8(px, i * 2), readu8(px, i * 2 + 1)
+ g, b = r, r
+ elseif fmt == 4 then
+ r, g, b, a = readu16(px, i * 8), readu16(px, i * 8 + 2), readu16(px, i * 8 + 4), readu16(px, i * 8 + 6)
+ elseif fmt == 5 then
+ r = readu16(px, i * 2)
+ g, b, a = r, r, 65535
+ else
+ r, g, b, a = f(readf32(px, i * 16)), f(readf32(px, i * 16 + 4)), f(readf32(px, i * 16 + 8)), f(readf32(px, i * 16 + 12))
+ end
+ local w16 = srcWide or fmt == 6
+ local gray = r
+ if ch <= 2 and not isGray then
+ gray = (r * 299 + g * 587 + b * 114) // 1000
+ end
+ local vals = if ch == 1 then 1 elseif ch == 2 then 2 else ch
+ for c = 0, vals - 1 do
+ local v
+ if ch <= 2 then
+ v = if c == 0 then gray else a
+ else
+ v = if c == 0 then r elseif c == 1 then g elseif c == 2 then b else a
+ end
+ if wide and not w16 then
+ v *= 257
+ elseif w16 and not wide then
+ v = (v * 255 + 32767) // 65535
+ end
+ writeu16(out, (i * ch + c) * 2, v)
+ end
+ end
+ return out
+end
+
+-- writeSamples(s, count, wide, out, o) -> new offset: binary samples (8-bit or 16-bit big-endian)
+function Codec.writeSamples(s: buffer, count: number, wide: boolean, out: buffer, o: number): number
+ if wide then
+ for i = 0, count - 1 do
+ local v = readu16(s, i * 2)
+ writeu8(out, o, v // 256)
+ writeu8(out, o + 1, v % 256)
+ o += 2
+ end
+ else
+ for i = 0, count - 1 do
+ writeu8(out, o, readu16(s, i * 2))
+ o += 1
+ end
+ end
+ return o
+end
+
+-- writeBits(s, w, h, threshold, out, o) -> new offset: P4 rows from grey samples (below threshold = black = 1)
+function Codec.writeBits(s: buffer, w: number, h: number, threshold: number, out: buffer, o: number): number
+ for y = 0, h - 1 do
+ local acc, nb = 0, 0
+ for x = 0, w - 1 do
+ acc = acc * 2 + (if readu16(s, (y * w + x) * 2) < threshold then 1 else 0)
+ nb += 1
+ if nb == 8 then
+ writeu8(out, o, acc)
+ o += 1
+ acc, nb = 0, 0
+ end
+ end
+ if nb > 0 then
+ writeu8(out, o, acc * 2 ^ (8 - nb))
+ o += 1
+ end
+ end
+ return o
+end
+
+-- writeFloats(px, w, h, ch, out, o) -> new offset: rgbaf32 (ch 3) or its first channel (ch 1) as little-endian PFM
+-- rows, bottom-to-top
+function Codec.writeFloats(px: buffer, w: number, h: number, ch: number, out: buffer, o: number): number
+ for y = h - 1, 0, -1 do
+ for x = 0, w - 1 do
+ local q = (y * w + x) * 16
+ for c = 0, ch - 1 do
+ writef32(out, o, readf32(px, q + c * 4))
+ o += 4
+ end
+ end
+ end
+ return o
+end
+
+return Codec
diff --git a/src/Formats/image/pnm/init.luau b/src/Formats/image/pnm/init.luau
new file mode 100644
index 0000000..237e474
--- /dev/null
+++ b/src/Formats/image/pnm/init.luau
@@ -0,0 +1,383 @@
+--!strict
+-- image/pnm: the Netpbm family, written from the Netpbm format pages: PBM (P1 ASCII / P4 binary), PGM (P2 / P5),
+-- PPM (P3 / P6), PAM (P7: BLACKANDWHITE, GRAYSCALE, GRAYSCALE_ALPHA, RGB, RGB_ALPHA and their _ALPHA forms, any
+-- tuple type of depth 1..4) and PFM (PF colour / Pf grey 32-bit float, either byte order, bottom-to-top rows).
+-- maxval 1..65535 (scaled to 8 bits by round(v * 255 / maxval)). Decode: rgba8, or with opts.native the source layout
+-- (gray8, gray16, graya8, rgb8, rgba8, rgba16 for 16-bit colour or grey + alpha, rgbaf32 for PFM). PFM to rgba8 is
+-- clamp(v, 0, 1) * 255 rounded (linear, no gamma). Encode: any of the seven types, binary or ASCII, from every pixel
+-- format; the subtype comes from opts.format / the file extension (pbm, pgm, ppm, pam, pfm) or the image.
+-- Not supported: multi-image streams (the first image is read), PAM depths above 4.
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Types = require("@formats/Types")
+local Codec = require("@formats/image/pnm/Codec")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Pnm = {
+ name = "pnm",
+ category = "image",
+ extensions = { "pnm", "pbm", "pgm", "ppm", "pam", "pfm" },
+ mime = { "image/x-portable-anymap", "image/x-portable-bitmap", "image/x-portable-graymap", "image/x-portable-pixmap", "image/x-portable-arbitrarymap", "image/x-portable-floatmap" },
+ deps = { "core/Err", "core/Bytes", "Types" },
+ caps = { decode = true, encode = true, alpha = true, depths = { 1, 8, 16, 32 }, float = true },
+}
+
+-- ------------------------------------------------------------------------------------------------ types
+export type DecodeOptions = {
+ native: boolean?, -- keep the source layout (default false: rgba8)
+ maxPixels: number?, -- refuse larger images (default 2^26)
+}
+export type EncodeOptions = {
+ format: string?, -- "pbm" | "pgm" | "ppm" | "pam" | "pfm" (default: from the image: grey -> pgm, opaque colour
+ -- -> ppm, alpha -> pam, rgbaf32 -> pfm); "pnm" means the default
+ ascii: boolean?, -- P1 / P2 / P3 instead of P4 / P5 / P6 (default false)
+ maxval: number?, -- 1..65535 (default 255, or 65535 for 16-bit / float sources); pbm ignores it
+ threshold: number?, -- pbm: grey below this (0..255) is black (default 128)
+}
+
+-- ------------------------------------------------------------------------------------------------ constants
+local FMT_CODE = { rgba8 = 0, rgb8 = 1, gray8 = 2, graya8 = 3, rgba16 = 4, gray16 = 5, rgbaf32 = 6 }
+local BPP = { rgba8 = 4, rgb8 = 3, gray8 = 1, graya8 = 2, rgba16 = 8, gray16 = 2, rgbaf32 = 16 }
+local readu8 = buffer.readu8
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Pnm.sniff(r: Bytes.Reader): number
+ if r:remaining() < 3 then
+ return 0
+ end
+ local a, b, c = r:peekU8(0), r:peekU8(1), r:peekU8(2)
+ if a ~= 80 then -- 'P'
+ return 0
+ end
+ local ws = c == 32 or (c >= 9 and c <= 13)
+ if b >= 49 and b <= 55 and ws then -- P1..P7
+ return 0.9
+ end
+ if (b == 70 or b == 102) and ws then -- PF / Pf
+ return 0.9
+ end
+ return 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+local function isSpace(c: number): boolean
+ return c == 32 or (c >= 9 and c <= 13)
+end
+
+-- the next header token from p: token, position after it (nil at the end)
+local function token(b: buffer, p: number, limit: number): (string?, number)
+ while p < limit do
+ local c = readu8(b, p)
+ if c == 35 then
+ while p < limit and readu8(b, p) ~= 10 and readu8(b, p) ~= 13 do
+ p += 1
+ end
+ elseif isSpace(c) then
+ p += 1
+ else
+ break
+ end
+ end
+ local s = p
+ while p < limit and not isSpace(readu8(b, p)) and readu8(b, p) ~= 35 do
+ p += 1
+ end
+ if p == s then
+ return nil, p
+ end
+ return buffer.readstring(b, s, p - s), p
+end
+
+local function int(s: string?): number?
+ if s == nil or not string.match(s, "^%d+$") or #s > 9 then
+ return nil
+ end
+ return tonumber(s)
+end
+
+function Pnm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
+ local maxPixels = opts and opts.maxPixels or 2 ^ 26
+ local native = opts and opts.native or false
+ local b, limit = r.buf, r.limit
+ if r.limit - r.base < 3 or readu8(b, r.base) ~= 80 then
+ return nil, Err.new(Err.CORRUPT, "not a Netpbm file", r.base)
+ end
+ local kind = string.char(readu8(b, r.base + 1))
+ local p = r.base + 2
+ local w, h, maxval, ch, mode
+ local bits = false -- PBM: 1 = black
+ local bw = false -- PAM BLACKANDWHITE: 1 = white
+ local tupl: string? = nil
+ local scale: number? = nil
+ if kind == "1" or kind == "2" or kind == "3" or kind == "4" or kind == "5" or kind == "6" or kind == "F" or kind == "f" then
+ local t1, t2, t3
+ t1, p = token(b, p, limit)
+ t2, p = token(b, p, limit)
+ w, h = int(t1), int(t2)
+ if kind == "1" or kind == "4" then
+ maxval = 1
+ elseif kind == "F" or kind == "f" then
+ t3, p = token(b, p, limit)
+ scale = if t3 then tonumber(t3) else nil
+ if scale == nil or scale == 0 then
+ return nil, Err.new(Err.CORRUPT, "bad PFM scale", p)
+ end
+ maxval = 1
+ else
+ t3, p = token(b, p, limit)
+ maxval = int(t3)
+ end
+ if w == nil or h == nil or maxval == nil then
+ return nil, if p >= limit then Err.new(Err.TRUNCATED, "header ends early", p) else Err.new(Err.CORRUPT, "bad header", p)
+ end
+ if kind ~= "1" and kind ~= "2" and kind ~= "3" then
+ p += 1 -- exactly one whitespace byte before binary data
+ end
+ ch = if kind == "3" or kind == "6" or kind == "F" then 3 else 1
+ bits = kind == "1" or kind == "4"
+ mode = if kind == "1" then 4 elseif kind == "2" or kind == "3" then 3 elseif kind == "4" then 0 elseif maxval > 255 then 2 else 1
+ elseif kind == "7" then
+ local depth
+ while true do
+ local key
+ key, p = token(b, p, limit)
+ if key == nil then
+ return nil, Err.new(Err.TRUNCATED, "PAM header ends early", p)
+ end
+ if key == "ENDHDR" then
+ break
+ end
+ local v
+ v, p = token(b, p, limit)
+ if key == "WIDTH" then
+ w = int(v)
+ elseif key == "HEIGHT" then
+ h = int(v)
+ elseif key == "DEPTH" then
+ depth = int(v)
+ elseif key == "MAXVAL" then
+ maxval = int(v)
+ elseif key == "TUPLTYPE" then
+ tupl = v
+ -- the rest of the line belongs to the value
+ while p < limit and readu8(b, p) ~= 10 do
+ p += 1
+ end
+ end
+ end
+ -- ENDHDR ends with a newline
+ while p < limit and readu8(b, p) ~= 10 do
+ p += 1
+ end
+ p += 1
+ if w == nil or h == nil or depth == nil or maxval == nil then
+ return nil, Err.new(Err.CORRUPT, "PAM header misses WIDTH / HEIGHT / DEPTH / MAXVAL", p)
+ end
+ if depth < 1 or depth > 4 then
+ return nil, Err.new(Err.UNSUPPORTED, "PAM depth " .. depth)
+ end
+ ch = depth
+ bw = tupl ~= nil and string.sub(tupl, 1, 13) == "BLACKANDWHITE"
+ mode = if maxval > 255 then 2 else 1
+ else
+ return nil, Err.new(Err.CORRUPT, "not a Netpbm file", r.base)
+ end
+ if w < 1 or h < 1 or maxval < 1 or maxval > 65535 then
+ return nil, Err.new(Err.CORRUPT, string.format("bad size %d x %d or maxval %d", w, h, maxval))
+ end
+ if w * h > maxPixels then
+ return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
+ end
+ local n = w * h
+ local img: Types.Image
+ local colorType = if ch == 1 then "gray" elseif ch == 2 then "graya" elseif ch == 3 then "rgb" else "rgba"
+ if scale then
+ local f = Types.Image.new(w, h, "rgbaf32")
+ local ok, e = Codec.readFloats(b, p, limit, w, h, ch, (scale :: number) < 0, f.pixels)
+ if not ok then
+ return nil, Err.new(Err.TRUNCATED, tostring(e))
+ end
+ img = f
+ if not native then
+ local o = Types.Image.new(w, h, "rgba8")
+ for i = 0, n * 4 - 1 do
+ local v = buffer.readf32(f.pixels, i * 4)
+ buffer.writeu8(o.pixels, i, if v ~= v then 0 else math.floor(math.clamp(v, 0, 1) * 255 + 0.5))
+ end
+ img = o
+ end
+ img.meta.source = { format = "pnm", type = if ch == 3 then "pfm" else "pfm-gray", bitDepth = 32, colorType = colorType, scale = math.abs(scale :: number), byteOrder = if (scale :: number) < 0 then "little" else "big" }
+ return img, nil
+ end
+ local samples = buffer.create(n * ch * 2)
+ local ok, e
+ if mode == 0 then
+ ok, e = Codec.readBits(b, p, limit, w, h, samples)
+ else
+ ok, e = Codec.readSamples(b, p, limit, n * ch, mode, samples)
+ end
+ if not ok then
+ return nil, Err.new(if e == "truncated" then Err.TRUNCATED else Err.CORRUPT, tostring(e))
+ end
+ local fmt = "rgba8"
+ if native then
+ local wide = maxval > 255
+ if bits or bw or ch == 1 then
+ fmt = if wide then "gray16" else "gray8"
+ elseif ch == 2 then
+ fmt = if wide then "rgba16" else "graya8"
+ elseif ch == 3 then
+ fmt = if wide then "rgba16" else "rgb8"
+ else
+ fmt = if wide then "rgba16" else "rgba8"
+ end
+ end
+ img = Types.Image.new(w, h, fmt :: Types.PixelFormat)
+ Codec.pack(samples, n, ch, maxval, bits, FMT_CODE[fmt], img.pixels)
+ local typ = if kind == "7" then "pam" elseif bits then "pbm" elseif ch == 1 then "pgm" else "ppm"
+ img.meta.source = {
+ format = "pnm",
+ type = typ,
+ ascii = mode == 3 or mode == 4,
+ bitDepth = if bits or bw then 1 elseif maxval > 255 then 16 else 8,
+ maxval = maxval,
+ colorType = if bits or bw then "bilevel" else colorType,
+ tupltype = tupl,
+ }
+ return img, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+local SUBTYPES = { pbm = true, pgm = true, ppm = true, pam = true, pfm = true }
+
+function Pnm.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
+ if type(img) ~= "table" or type(img.pixels) ~= "buffer" then
+ return nil, Err.new(Err.ARG, "needs an Image")
+ end
+ local fc = FMT_CODE[img.format]
+ if fc == nil then
+ return nil, Err.new(Err.ARG, "unsupported pixel format " .. tostring(img.format))
+ end
+ local w, h = img.width, img.height
+ if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < w * h * BPP[img.format] then
+ return nil, Err.new(Err.ARG, "bad image size or pixel buffer")
+ end
+ local o: any = opts or {}
+ local n = w * h
+ local isGray = img.format == "gray8" or img.format == "gray16" or img.format == "graya8"
+ local hasAlpha = img.format == "graya8" or img.format == "rgba16" or img.format == "rgba8" or img.format == "rgbaf32"
+ if hasAlpha and img.format ~= "graya8" then
+ -- an alpha channel that is fully opaque does not count
+ local opaque = true
+ for i = 0, n - 1 do
+ local a
+ if img.format == "rgba8" then
+ a = buffer.readu8(img.pixels, i * 4 + 3) == 255
+ elseif img.format == "rgba16" then
+ a = buffer.readu16(img.pixels, i * 8 + 6) == 65535
+ else
+ a = buffer.readf32(img.pixels, i * 16 + 12) == 1
+ end
+ if not a then
+ opaque = false
+ break
+ end
+ end
+ hasAlpha = not opaque
+ end
+ local sub = if type(o.format) == "string" then string.lower(o.format) else nil
+ if not (sub and SUBTYPES[sub]) then
+ if img.format == "rgbaf32" and not hasAlpha then
+ sub = "pfm"
+ elseif hasAlpha then
+ sub = "pam"
+ elseif isGray then
+ sub = "pgm"
+ else
+ sub = "ppm"
+ end
+ end
+ local ascii = o.ascii == true
+ local wideSrc = img.format == "gray16" or img.format == "rgba16" or img.format == "rgbaf32"
+ local maxval = o.maxval or (if wideSrc then 65535 else 255)
+ if type(maxval) ~= "number" or maxval < 1 or maxval > 65535 or maxval % 1 ~= 0 then
+ return nil, Err.new(Err.ARG, "maxval must be 1..65535")
+ end
+ local out: buffer
+ local op = 0
+ local function header(s: string, extra: number)
+ out = buffer.create(#s + extra)
+ buffer.writestring(out, 0, s)
+ op = #s
+ end
+ if sub == "pfm" then
+ local ch = if isGray then 1 else 3
+ local src = img
+ if img.format ~= "rgbaf32" then
+ local s = Codec.extract(img.pixels, fc, n, 4, true)
+ src = Types.Image.new(w, h, "rgbaf32")
+ for i = 0, n * 4 - 1 do
+ buffer.writef32(src.pixels, i * 4, buffer.readu16(s, i * 2) / 65535)
+ end
+ end
+ header(string.format("%s\n%d %d\n-1.0\n", if ch == 3 then "PF" else "Pf", w, h), n * ch * 4)
+ op = Codec.writeFloats(src.pixels, w, h, ch, out, op)
+ return out, nil
+ end
+ local ch = if sub == "pbm" or sub == "pgm" then 1 elseif sub == "ppm" then 3 elseif isGray then (if hasAlpha then 2 else 1) else (if hasAlpha then 4 else 3)
+ if sub == "pbm" then
+ local thr = o.threshold or 128
+ local s = Codec.extract(img.pixels, fc, n, 1, false)
+ if ascii then
+ local parts = table.create(h + 1)
+ parts[1] = string.format("P1\n%d %d\n", w, h)
+ for y = 0, h - 1 do
+ local row = table.create(w)
+ for x = 0, w - 1 do
+ row[x + 1] = if buffer.readu16(s, (y * w + x) * 2) < thr then "1" else "0"
+ end
+ parts[y + 2] = table.concat(row, " ") .. "\n"
+ end
+ return buffer.fromstring(table.concat(parts)), nil
+ end
+ header(string.format("P4\n%d %d\n", w, h), ((w + 7) // 8) * h)
+ op = Codec.writeBits(s, w, h, thr, out, op)
+ return out, nil
+ end
+ local wide = maxval > 255
+ local s = Codec.extract(img.pixels, fc, n, ch, wide)
+ if maxval ~= 255 and maxval ~= 65535 then
+ local top = if wide then 65535 else 255
+ for i = 0, n * ch - 1 do
+ buffer.writeu16(s, i * 2, (buffer.readu16(s, i * 2) * maxval + top // 2) // top)
+ end
+ end
+ local magic
+ if sub == "pam" then
+ local tt = if ch == 1 then "GRAYSCALE" elseif ch == 2 then "GRAYSCALE_ALPHA" elseif ch == 3 then "RGB" else "RGB_ALPHA"
+ header(string.format("P7\nWIDTH %d\nHEIGHT %d\nDEPTH %d\nMAXVAL %d\nTUPLTYPE %s\nENDHDR\n", w, h, ch, maxval, tt), n * ch * (if wide then 2 else 1))
+ op = Codec.writeSamples(s, n * ch, wide, out, op)
+ return out, nil
+ end
+ magic = if sub == "pgm" then (if ascii then "P2" else "P5") else (if ascii then "P3" else "P6")
+ if ascii then
+ local parts = table.create(h + 1)
+ parts[1] = string.format("%s\n%d %d\n%d\n", magic, w, h, maxval)
+ local rowLen = w * ch
+ for y = 0, h - 1 do
+ local row = table.create(rowLen)
+ for i = 0, rowLen - 1 do
+ row[i + 1] = tostring(buffer.readu16(s, (y * rowLen + i) * 2))
+ end
+ parts[y + 2] = table.concat(row, " ") .. "\n"
+ end
+ return buffer.fromstring(table.concat(parts)), nil
+ end
+ header(string.format("%s\n%d %d\n%d\n", magic, w, h, maxval), n * ch * (if wide then 2 else 1))
+ op = Codec.writeSamples(s, n * ch, wide, out, op)
+ return out, nil
+end
+
+return Pnm
diff --git a/src/Formats/image/qoi/Codec.luau b/src/Formats/image/qoi/Codec.luau
new file mode 100644
index 0000000..2936f07
--- /dev/null
+++ b/src/Formats/image/qoi/Codec.luau
@@ -0,0 +1,144 @@
+--!strict
+--!native
+--!optimize 2
+-- image/qoi/Codec: the QOI op loops (native; never throws). Written from the QOI specification 1.0 (qoiformat.org).
+-- decode reads ops from b[p, limit) into an rgba8 buffer; encode writes ops for rgba8 / rgb8 pixels. Every input read
+-- is checked against limit; the output buffer has exactly w * h * 4 bytes and the loop stops when it is full.
+local readu8, writeu8, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu32
+
+local Codec = {}
+
+local index = buffer.create(256)
+
+-- decode(b, p, limit, out, n) -> true | false, "truncated" (n pixels into out)
+function Codec.decode(b: buffer, p: number, limit: number, out: buffer, n: number): (boolean, string?)
+ buffer.fill(index, 0, 0, 256)
+ local r, g, bl, a = 0, 0, 0, 255
+ local o = 0
+ local stop = n * 4
+ while o < stop do
+ if p >= limit then
+ return false, "truncated"
+ end
+ local op = readu8(b, p)
+ p += 1
+ if op == 0xFE then
+ if p + 3 > limit then
+ return false, "truncated"
+ end
+ r, g, bl = readu8(b, p), readu8(b, p + 1), readu8(b, p + 2)
+ p += 3
+ elseif op == 0xFF then
+ if p + 4 > limit then
+ return false, "truncated"
+ end
+ r, g, bl, a = readu8(b, p), readu8(b, p + 1), readu8(b, p + 2), readu8(b, p + 3)
+ p += 4
+ else
+ local tag = op // 64
+ if tag == 0 then
+ local q = op * 4
+ r, g, bl, a = readu8(index, q), readu8(index, q + 1), readu8(index, q + 2), readu8(index, q + 3)
+ elseif tag == 1 then
+ r = (r + (op // 16) % 4 - 2) % 256
+ g = (g + (op // 4) % 4 - 2) % 256
+ bl = (bl + op % 4 - 2) % 256
+ elseif tag == 2 then
+ if p >= limit then
+ return false, "truncated"
+ end
+ local d2 = readu8(b, p)
+ p += 1
+ local dg = op % 64 - 32
+ g = (g + dg) % 256
+ r = (r + dg + d2 // 16 - 8) % 256
+ bl = (bl + dg + d2 % 16 - 8) % 256
+ else
+ local run = op % 64 -- 1..62 more copies of the previous pixel (63 / 64 are RGB / RGBA)
+ local v = r + g * 256 + bl * 65536 + a * 16777216
+ local e = math.min(o + run * 4, stop - 4)
+ while o < e do
+ writeu32(out, o, v)
+ o += 4
+ end
+ end
+ end
+ writeu32(out, o, r + g * 256 + bl * 65536 + a * 16777216)
+ o += 4
+ local h = ((r * 3 + g * 5 + bl * 7 + a * 11) % 64) * 4
+ writeu8(index, h, r)
+ writeu8(index, h + 1, g)
+ writeu8(index, h + 2, bl)
+ writeu8(index, h + 3, a)
+ end
+ return true, nil
+end
+
+-- encode(px, n, bpp, out, o) -> new offset: n pixels of bpp (3 or 4) bytes; out has room for n * (bpp + 1) bytes
+function Codec.encode(px: buffer, n: number, bpp: number, out: buffer, o: number): number
+ buffer.fill(index, 0, 0, 256)
+ local pr, pg, pb, pa = 0, 0, 0, 255
+ local run = 0
+ local hasA = bpp == 4
+ for i = 0, n - 1 do
+ local q = i * bpp
+ local r, g, b = readu8(px, q), readu8(px, q + 1), readu8(px, q + 2)
+ local a = if hasA then readu8(px, q + 3) else 255
+ if r == pr and g == pg and b == pb and a == pa then
+ run += 1
+ if run == 62 or i == n - 1 then
+ writeu8(out, o, 0xC0 + run - 1)
+ o += 1
+ run = 0
+ end
+ else
+ if run > 0 then
+ writeu8(out, o, 0xC0 + run - 1)
+ o += 1
+ run = 0
+ end
+ local h = (r * 3 + g * 5 + b * 7 + a * 11) % 64
+ local hq = h * 4
+ if readu8(index, hq) == r and readu8(index, hq + 1) == g and readu8(index, hq + 2) == b and readu8(index, hq + 3) == a then
+ writeu8(out, o, h)
+ o += 1
+ else
+ writeu8(index, hq, r)
+ writeu8(index, hq + 1, g)
+ writeu8(index, hq + 2, b)
+ writeu8(index, hq + 3, a)
+ if a == pa then
+ local dr = (r - pr + 128) % 256 - 128
+ local dg = (g - pg + 128) % 256 - 128
+ local db = (b - pb + 128) % 256 - 128
+ local dgr, dgb = dr - dg, db - dg
+ if dr >= -2 and dr <= 1 and dg >= -2 and dg <= 1 and db >= -2 and db <= 1 then
+ writeu8(out, o, 0x40 + (dr + 2) * 16 + (dg + 2) * 4 + db + 2)
+ o += 1
+ elseif dg >= -32 and dg <= 31 and dgr >= -8 and dgr <= 7 and dgb >= -8 and dgb <= 7 then
+ writeu8(out, o, 0x80 + dg + 32)
+ writeu8(out, o + 1, (dgr + 8) * 16 + dgb + 8)
+ o += 2
+ else
+ writeu8(out, o, 0xFE)
+ writeu8(out, o + 1, r)
+ writeu8(out, o + 2, g)
+ writeu8(out, o + 3, b)
+ o += 4
+ end
+ else
+ writeu8(out, o, 0xFF)
+ writeu8(out, o + 1, r)
+ writeu8(out, o + 2, g)
+ writeu8(out, o + 3, b)
+ writeu8(out, o + 4, a)
+ o += 5
+ end
+ end
+ pr, pg, pb, pa = r, g, b, a
+ end
+ end
+ return o
+end
+
+return Codec
diff --git a/src/Formats/image/qoi/init.luau b/src/Formats/image/qoi/init.luau
new file mode 100644
index 0000000..ef11dc6
--- /dev/null
+++ b/src/Formats/image/qoi/init.luau
@@ -0,0 +1,122 @@
+--!strict
+-- image/qoi: QOI, the Quite OK Image format (specification 1.0, qoiformat.org). New code written from the spec.
+-- Supports: decode of RGB and RGBA files (either colour space tag) to rgba8 (opts.native: rgb8 for 3-channel files);
+-- encode of rgba8 (4 channels) and rgb8 (3 channels), lossless; meta.source.colorSpace keeps the sRGB / linear tag.
+-- Not supported: nothing in the spec is left out.
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Types = require("@formats/Types")
+local Codec = require("@formats/image/qoi/Codec")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Qoi = {
+ name = "qoi",
+ category = "image",
+ extensions = { "qoi" },
+ mime = { "image/qoi", "image/x-qoi" },
+ deps = { "core/Err", "core/Bytes", "Types" },
+ caps = { decode = true, encode = true, alpha = true, depths = { 8 } },
+}
+
+-- ------------------------------------------------------------------------------------------------ types
+export type DecodeOptions = {
+ native: boolean?, -- rgb8 for 3-channel files (default false: always rgba8)
+ maxPixels: number?, -- refuse larger images (default 2^26)
+}
+export type EncodeOptions = {
+ channels: number?, -- 3 or 4 (default: 3 for rgb8 images or opaque rgba8, else 4)
+ linear: boolean?, -- tag the file as linear instead of sRGB (default: meta.source.colorSpace == "linear")
+}
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Qoi.sniff(r: Bytes.Reader): number
+ return if r:peek(4) == "qoif" then 1 else 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+function Qoi.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
+ local maxPixels = opts and opts.maxPixels or 2 ^ 26
+ local magic = r:string(4)
+ local w, h = r:u32be(), r:u32be()
+ local channels, cs = r:u8(), r:u8()
+ if r.err then
+ return nil, r.err
+ end
+ if magic ~= "qoif" then
+ return nil, Err.new(Err.CORRUPT, "bad magic", r.base)
+ end
+ if w == 0 or h == 0 or (channels ~= 3 and channels ~= 4) or cs > 1 then
+ return nil, Err.new(Err.CORRUPT, "bad header", r.base + 4)
+ end
+ if w * h > maxPixels then
+ return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
+ end
+ local img = Types.Image.new(w, h, "rgba8")
+ local ok, e = Codec.decode(r.buf, r.pos, r.limit, img.pixels, w * h)
+ if not ok then
+ return nil, Err.new(Err.TRUNCATED, tostring(e))
+ end
+ if opts and opts.native and channels == 3 then
+ local rgb = Types.Image.new(w, h, "rgb8")
+ local src, dst = img.pixels, rgb.pixels
+ for i = 0, w * h - 1 do
+ buffer.writeu16(dst, i * 3, buffer.readu16(src, i * 4))
+ buffer.writeu8(dst, i * 3 + 2, buffer.readu8(src, i * 4 + 2))
+ end
+ img = rgb
+ end
+ img.meta.source = { format = "qoi", bitDepth = 8, colorType = if channels == 4 then "rgba" else "rgb", channels = channels, colorSpace = if cs == 1 then "linear" else "srgb" }
+ if cs == 1 then
+ img.meta.colorSpace = "linear"
+ end
+ return img, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+function Qoi.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
+ if type(img) ~= "table" or type(img.pixels) ~= "buffer" or (img.format ~= "rgba8" and img.format ~= "rgb8") then
+ return nil, Err.new(Err.ARG, "needs an rgba8 or rgb8 Image")
+ end
+ local w, h = img.width, img.height
+ local bpp = if img.format == "rgba8" then 4 else 3
+ if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < w * h * bpp then
+ return nil, Err.new(Err.ARG, "bad image size or pixel buffer")
+ end
+ local channels = opts and opts.channels
+ if channels == nil then
+ channels = 3
+ if bpp == 4 then
+ local px = img.pixels
+ for i = 0, w * h - 1 do
+ if buffer.readu8(px, i * 4 + 3) ~= 255 then
+ channels = 4
+ break
+ end
+ end
+ end
+ elseif channels ~= 3 and channels ~= 4 then
+ return nil, Err.new(Err.ARG, "channels must be 3 or 4")
+ end
+ local linear = opts and opts.linear
+ if linear == nil then
+ local src = img.meta and img.meta.source
+ linear = (type(src) == "table" and src.colorSpace == "linear") or (img.meta and img.meta.colorSpace == "linear") or false
+ end
+ local n = w * h
+ local out = buffer.create(14 + n * (bpp + 1) + 8)
+ buffer.writestring(out, 0, "qoif")
+ buffer.writeu32(out, 4, bit32.byteswap(w))
+ buffer.writeu32(out, 8, bit32.byteswap(h))
+ buffer.writeu8(out, 12, channels)
+ buffer.writeu8(out, 13, if linear then 1 else 0)
+ local o = Codec.encode(img.pixels, n, bpp, out, 14)
+ buffer.writestring(out, o, "\0\0\0\0\0\0\0\1")
+ o += 8
+ local res = buffer.create(o)
+ buffer.copy(res, 0, out, 0, o)
+ return res, nil
+end
+
+return Qoi
diff --git a/src/Formats/image/tga/Codec.luau b/src/Formats/image/tga/Codec.luau
new file mode 100644
index 0000000..1cbb0bd
--- /dev/null
+++ b/src/Formats/image/tga/Codec.luau
@@ -0,0 +1,157 @@
+--!strict
+--!native
+--!optimize 2
+-- image/tga/Codec: the Truevision TGA pixel loops (native; never throws). Written from the Truevision TGA 2.0
+-- specification. decode reads raw or RLE pixel data (packets may cross scanlines) into rgba8 at the oriented
+-- position; encode writes raw or RLE rows. Every read is bounds-checked; the output has exactly w * h * 4 bytes.
+local readu8, readu16, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32
+
+local Codec = {}
+
+-- one source pixel at b[p] -> rgba as a u32; kind: 0 grey 8, 1 grey + alpha 16, 2 = 15/16-bit ARGB1555,
+-- 3 = BGR 24, 4 = BGRA 32, 5 = index 8, 6 = index 16 (pal: u32 entries, palN of them)
+local function pixel(b: buffer, p: number, kind: number, alpha1: boolean, pal: buffer, palN: number): number
+ if kind == 0 then
+ return readu8(b, p) * 0x10101 + 0xFF000000
+ elseif kind == 1 then
+ return readu8(b, p) * 0x10101 + readu8(b, p + 1) * 0x1000000
+ elseif kind == 2 then
+ local v = readu16(b, p)
+ local r, g, bl = (v // 1024) % 32, (v // 32) % 32, v % 32
+ local a = if alpha1 and v < 32768 then 0 else 255
+ return (r * 255 + 15) // 31 + ((g * 255 + 15) // 31) * 256 + ((bl * 255 + 15) // 31) * 65536 + a * 16777216 -- round(v * 255 / 31), as ImageMagick
+ elseif kind == 3 then
+ return readu8(b, p + 2) + readu8(b, p + 1) * 256 + readu8(b, p) * 65536 + 0xFF000000
+ elseif kind == 4 then
+ return readu8(b, p + 2) + readu8(b, p + 1) * 256 + readu8(b, p) * 65536 + readu8(b, p + 3) * 16777216
+ end
+ local i = if kind == 5 then readu8(b, p) else readu16(b, p)
+ if i >= palN then
+ return 0xFF000000
+ end
+ return readu32(pal, i * 4)
+end
+Codec.pixel = pixel
+
+-- decode(b, p, limit, w, h, bpp, kind, alpha1, rle, bottomUp, rtl, pal, palN, out) -> pixels written, truncated?
+function Codec.decode(b: buffer, p: number, limit: number, w: number, h: number, bpp: number, kind: number, alpha1: boolean, rle: boolean, bottomUp: boolean, rtl: boolean, pal: buffer, palN: number, out: buffer): (number, boolean)
+ local n = w * h
+ local i = 0
+ local function put(v: number)
+ local row, col = i // w, i % w
+ if bottomUp then
+ row = h - 1 - row
+ end
+ if rtl then
+ col = w - 1 - col
+ end
+ writeu32(out, (row * w + col) * 4, v)
+ i += 1
+ end
+ if not rle then
+ local avail = math.min(n, (limit - p) // bpp)
+ for _ = 1, avail do
+ put(pixel(b, p, kind, alpha1, pal, palN))
+ p += bpp
+ end
+ return i, avail < n
+ end
+ while i < n do
+ if p >= limit then
+ return i, true
+ end
+ local hd = readu8(b, p)
+ p += 1
+ local count = hd % 128 + 1
+ if hd >= 128 then
+ if p + bpp > limit then
+ return i, true
+ end
+ local v = pixel(b, p, kind, alpha1, pal, palN)
+ p += bpp
+ for _ = 1, math.min(count, n - i) do
+ put(v)
+ end
+ else
+ for _ = 1, math.min(count, n - i) do
+ if p + bpp > limit then
+ return i, true
+ end
+ put(pixel(b, p, kind, alpha1, pal, palN))
+ p += bpp
+ end
+ end
+ end
+ return i, false
+end
+
+-- encode(px, w, h, srcBpp, outBpp, rle, topDown, out, o) -> new offset. px: rgba8 / rgb8 / gray8 (srcBpp 4 / 3 / 1);
+-- written as BGRA / BGR / grey (outBpp 4 / 3 / 1), rows top-down or bottom-up; RLE packets stay inside a row.
+-- out needs room for w * h * (outBpp + 1) bytes.
+function Codec.encode(px: buffer, w: number, h: number, srcBpp: number, outBpp: number, rle: boolean, topDown: boolean, out: buffer, o: number): number
+ local function get(q: number): number
+ if srcBpp == 1 then
+ return readu8(px, q)
+ elseif srcBpp == 3 then
+ return readu8(px, q) + readu8(px, q + 1) * 256 + readu8(px, q + 2) * 65536 + 0xFF000000
+ end
+ return readu32(px, q)
+ end
+ local function emit(v: number)
+ if outBpp == 1 then
+ writeu8(out, o, v % 256)
+ else
+ writeu8(out, o, (v // 65536) % 256)
+ writeu8(out, o + 1, (v // 256) % 256)
+ writeu8(out, o + 2, v % 256)
+ if outBpp == 4 then
+ writeu8(out, o + 3, v // 16777216)
+ end
+ end
+ o += outBpp
+ end
+ for y = 0, h - 1 do
+ local row = if topDown then y else h - 1 - y
+ local base = row * w * srcBpp
+ if not rle then
+ for x = 0, w - 1 do
+ emit(get(base + x * srcBpp))
+ end
+ else
+ local x = 0
+ while x < w do
+ local v = get(base + x * srcBpp)
+ local run = 1
+ while x + run < w and run < 128 and get(base + (x + run) * srcBpp) == v do
+ run += 1
+ end
+ if run >= 2 then
+ writeu8(out, o, 127 + run)
+ o += 1
+ emit(v)
+ x += run
+ else
+ -- a raw packet up to the next run of 2 or more
+ local s = x
+ local cnt = 0
+ while x < w and cnt < 128 do
+ local c = get(base + x * srcBpp)
+ if x + 1 < w and get(base + (x + 1) * srcBpp) == c then
+ break
+ end
+ cnt += 1
+ x += 1
+ end
+ writeu8(out, o, cnt - 1)
+ o += 1
+ for k = s, s + cnt - 1 do
+ emit(get(base + k * srcBpp))
+ end
+ end
+ end
+ end
+ end
+ return o
+end
+
+return Codec
diff --git a/src/Formats/image/tga/init.luau b/src/Formats/image/tga/init.luau
new file mode 100644
index 0000000..1b4400b
--- /dev/null
+++ b/src/Formats/image/tga/init.luau
@@ -0,0 +1,276 @@
+--!strict
+-- image/tga: Truevision TGA (TGA 2.0 specification; new code). Decode: colour-mapped (1), true-colour (2) and grey (3)
+-- images, raw or RLE (9, 10, 11; packets may cross scanlines), 8 / 15 / 16 / 24 / 32-bit pixels, 15 / 16 / 24 /
+-- 32-bit colour maps with a first index, 8 / 16-bit indexes, grey + alpha (16-bit type 3), every origin (bottom-left,
+-- top-left, right-to-left), the alpha bits of the descriptor (16-bit: alpha only when it declares 1 alpha bit; 32-bit:
+-- alpha always), the image ID (meta.text.id) and the TGA 2.0 footer (tolerated, not needed). Truncated pixel data
+-- leaves the rest transparent black (meta.truncated). opts.native: gray8 for grey files, rgb8 for 24-bit.
+-- Encode: rgba8 (32-bit BGRA when there is alpha, else 24-bit), rgb8 (24-bit), gray8 (type 3), raw or RLE, bottom-left
+-- (default) or top-left origin, with the TGA 2.0 footer. Not supported: the extension area's fields (gamma, postage
+-- stamp, ...), which are ignored.
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Types = require("@formats/Types")
+local Codec = require("@formats/image/tga/Codec")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Tga = {
+ name = "tga",
+ category = "image",
+ extensions = { "tga", "icb", "vda", "vst", "tpic" },
+ mime = { "image/x-tga", "image/x-targa" },
+ deps = { "core/Err", "core/Bytes", "Types" },
+ caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 8, 15, 16, 24, 32 } },
+}
+
+-- ------------------------------------------------------------------------------------------------ types
+export type DecodeOptions = {
+ native: boolean?, -- gray8 for grey files, rgb8 for 24-bit ones (default false: rgba8)
+ maxPixels: number?, -- refuse larger images (default 2^26)
+}
+export type EncodeOptions = {
+ rle: boolean?, -- run-length encode (default false)
+ origin: ("bottom-left" | "top-left")?, -- default "bottom-left" (the classic layout every reader understands)
+ alpha: boolean?, -- force 32-bit (true) or 24-bit (false) for rgba8 (default: 32-bit when any alpha < 255)
+ id: string?, -- the image ID field (up to 255 bytes; default meta.text.id)
+}
+
+-- ------------------------------------------------------------------------------------------------ constants
+local TYPES = { [1] = true, [2] = true, [3] = true, [9] = true, [10] = true, [11] = true }
+local FOOTER = "TRUEVISION-XFILE.\0"
+local readu8 = buffer.readu8
+
+-- ------------------------------------------------------------------------------------------------ sniff
+type Header = {
+ idLen: number,
+ cmapType: number,
+ imageType: number,
+ cmapFirst: number,
+ cmapLen: number,
+ cmapBits: number,
+ width: number,
+ height: number,
+ depth: number,
+ desc: number,
+}
+
+local function header(r: Bytes.Reader): Header?
+ if r.limit - r.base < 18 then
+ return nil
+ end
+ local b, o = r.buf, r.base
+ local function u16(q: number): number
+ return readu8(b, o + q) + readu8(b, o + q + 1) * 256
+ end
+ local h: Header = {
+ idLen = readu8(b, o),
+ cmapType = readu8(b, o + 1),
+ imageType = readu8(b, o + 2),
+ cmapFirst = u16(3),
+ cmapLen = u16(5),
+ cmapBits = readu8(b, o + 7),
+ width = u16(12),
+ height = u16(14),
+ depth = readu8(b, o + 16),
+ desc = readu8(b, o + 17),
+ }
+ return h
+end
+
+-- plausible(h) -> nil | why not
+local function implausible(h: Header): string?
+ local t = h.imageType
+ if not TYPES[t] then
+ return "image type " .. t
+ end
+ if h.cmapType > 1 then
+ return "colour map type " .. h.cmapType
+ end
+ local mapped = t == 1 or t == 9
+ if mapped and (h.cmapType ~= 1 or (h.depth ~= 8 and h.depth ~= 16)) then
+ return "colour-mapped image without a colour map"
+ end
+ if h.cmapType == 1 and h.cmapLen > 0 and h.cmapBits ~= 15 and h.cmapBits ~= 16 and h.cmapBits ~= 24 and h.cmapBits ~= 32 then
+ return "colour map entry size " .. h.cmapBits
+ end
+ if (t == 2 or t == 10) and h.depth ~= 15 and h.depth ~= 16 and h.depth ~= 24 and h.depth ~= 32 then
+ return "pixel depth " .. h.depth
+ end
+ if (t == 3 or t == 11) and h.depth ~= 8 and h.depth ~= 16 then
+ return "grey pixel depth " .. h.depth
+ end
+ if h.width == 0 or h.height == 0 then
+ return "zero size"
+ end
+ if h.desc >= 64 then
+ return "interleaving / reserved descriptor bits"
+ end
+ return nil
+end
+
+function Tga.sniff(r: Bytes.Reader): number
+ local h = header(r)
+ if not h or implausible(h) then
+ return 0
+ end
+ local n = r.limit - r.base
+ if n >= 44 and buffer.readstring(r.buf, r.limit - 18, 18) == FOOTER then
+ return 0.9
+ end
+ return 0.2
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+function Tga.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
+ local maxPixels = opts and opts.maxPixels or 2 ^ 26
+ local h = header(r)
+ if not h then
+ return nil, Err.new(Err.TRUNCATED, "short header", r.base)
+ end
+ local why = implausible(h)
+ if why then
+ return nil, Err.new(if h.imageType == 0 then Err.UNSUPPORTED else Err.CORRUPT, why, r.base)
+ end
+ local w, ht = h.width, h.height
+ if w * ht > maxPixels then
+ return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, ht, maxPixels))
+ end
+ local b = r.buf
+ local p = r.base + 18
+ local id = if h.idLen > 0 and p + h.idLen <= r.limit then buffer.readstring(b, p, h.idLen) else nil
+ p += h.idLen
+ -- colour map
+ local pal = buffer.create(4)
+ local palN = 0
+ if h.cmapType == 1 and h.cmapLen > 0 then
+ local eb = (h.cmapBits + 7) // 8
+ if p + h.cmapLen * eb > r.limit then
+ return nil, Err.new(Err.TRUNCATED, "colour map runs past the end", p)
+ end
+ local first = h.cmapFirst
+ palN = first + h.cmapLen
+ pal = buffer.create(palN * 4)
+ buffer.fill(pal, 0, 0, palN * 4)
+ local kind = if h.cmapBits == 24 then 3 elseif h.cmapBits == 32 then 4 else 2
+ for i = 0, h.cmapLen - 1 do
+ buffer.writeu32(pal, (first + i) * 4, Codec.pixel(b, p + i * eb, kind, false, pal, 0))
+ end
+ for i = 0, first - 1 do
+ buffer.writeu32(pal, i * 4, 0xFF000000)
+ end
+ p += h.cmapLen * eb
+ end
+ local t = h.imageType
+ local alphaBits = h.desc % 16
+ local kind
+ if t == 1 or t == 9 then
+ kind = if h.depth == 8 then 5 else 6
+ elseif t == 3 or t == 11 then
+ kind = if h.depth == 8 then 0 else 1
+ else
+ kind = if h.depth == 24 then 3 elseif h.depth == 32 then 4 else 2
+ end
+ local bpp = (h.depth + 7) // 8
+ local bottomUp = (h.desc // 32) % 2 == 0
+ local rtl = (h.desc // 16) % 2 == 1
+ local img = Types.Image.new(w, ht, "rgba8")
+ local _, truncated = Codec.decode(b, p, r.limit, w, ht, bpp, kind, h.depth == 16 and alphaBits >= 1, t >= 9, bottomUp, rtl, pal, palN, img.pixels)
+ local native = opts and opts.native
+ if native and kind == 0 then
+ local g = Types.Image.new(w, ht, "gray8")
+ for i = 0, w * ht - 1 do
+ buffer.writeu8(g.pixels, i, readu8(img.pixels, i * 4))
+ end
+ img = g
+ elseif native and kind == 3 then
+ local c = Types.Image.new(w, ht, "rgb8")
+ for i = 0, w * ht - 1 do
+ buffer.writeu16(c.pixels, i * 3, buffer.readu16(img.pixels, i * 4))
+ buffer.writeu8(c.pixels, i * 3 + 2, readu8(img.pixels, i * 4 + 2))
+ end
+ img = c
+ end
+ if palN > 0 then
+ local palette = {}
+ for i = 0, palN - 1 do
+ palette[i + 1] = { readu8(pal, i * 4), readu8(pal, i * 4 + 1), readu8(pal, i * 4 + 2), readu8(pal, i * 4 + 3) }
+ end
+ img.meta.palette = palette
+ end
+ if id then
+ img.meta.text = { id = id }
+ end
+ if truncated then
+ img.meta.truncated = true
+ end
+ img.meta.source = {
+ format = "tga",
+ bitDepth = h.depth,
+ colorType = if kind >= 5 then "palette" elseif kind <= 1 then (if kind == 1 then "graya" else "gray") else (if kind == 3 then "rgb" else "rgba"),
+ rle = t >= 9,
+ origin = (if bottomUp then "bottom" else "top") .. "-" .. (if rtl then "right" else "left"),
+ alphaBits = alphaBits,
+ }
+ return img, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+function Tga.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
+ if type(img) ~= "table" or type(img.pixels) ~= "buffer" then
+ return nil, Err.new(Err.ARG, "needs an Image")
+ end
+ local srcBpp = if img.format == "rgba8" then 4 elseif img.format == "rgb8" then 3 elseif img.format == "gray8" then 1 else nil
+ if not srcBpp then
+ return nil, Err.new(Err.ARG, "needs an rgba8, rgb8 or gray8 Image")
+ end
+ local w, h = img.width, img.height
+ if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w > 65535 or h > 65535 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < w * h * srcBpp then
+ return nil, Err.new(Err.ARG, "bad image size or pixel buffer (1..65535 per side)")
+ end
+ local o: any = opts or {}
+ local origin = o.origin or "bottom-left"
+ if origin ~= "bottom-left" and origin ~= "top-left" then
+ return nil, Err.new(Err.ARG, "origin must be \"bottom-left\" or \"top-left\"")
+ end
+ local outBpp = srcBpp
+ if srcBpp == 4 then
+ local alpha = o.alpha
+ if alpha == nil then
+ alpha = false
+ for i = 0, w * h - 1 do
+ if readu8(img.pixels, i * 4 + 3) ~= 255 then
+ alpha = true
+ break
+ end
+ end
+ end
+ outBpp = if alpha then 4 else 3
+ end
+ local id = o.id or (img.meta and img.meta.text and img.meta.text.id) or ""
+ if type(id) ~= "string" then
+ id = ""
+ end
+ id = string.sub(id, 1, 255)
+ local rle = o.rle == true
+ local out = buffer.create(18 + #id + w * h * (outBpp + 1) + 26)
+ buffer.writeu8(out, 0, #id)
+ buffer.writeu8(out, 2, (if outBpp == 1 then 3 else 2) + (if rle then 8 else 0))
+ buffer.writeu16(out, 12, w)
+ buffer.writeu16(out, 14, h)
+ buffer.writeu8(out, 16, outBpp * 8)
+ buffer.writeu8(out, 17, (if outBpp == 4 then 8 else 0) + (if origin == "top-left" then 32 else 0))
+ buffer.writestring(out, 18, id)
+ local op = Codec.encode(img.pixels, w, h, srcBpp, outBpp, rle, origin == "top-left", out, 18 + #id)
+ -- TGA 2.0 footer: no extension / developer areas
+ buffer.writeu32(out, op, 0)
+ buffer.writeu32(out, op + 4, 0)
+ buffer.writestring(out, op + 8, FOOTER)
+ op += 26
+ local res = buffer.create(op)
+ buffer.copy(res, 0, out, 0, op)
+ return res, nil
+end
+
+return Tga
diff --git a/src/Formats/image/tiff/Pixels.luau b/src/Formats/image/tiff/Pixels.luau
new file mode 100644
index 0000000..6ae16d4
--- /dev/null
+++ b/src/Formats/image/tiff/Pixels.luau
@@ -0,0 +1,469 @@
+--!strict
+--!native
+--!optimize 2
+-- image/tiff/Pixels: the hot loops of the TIFF codec (native; never throws): PackBits, the horizontal (2) and
+-- floating-point (3) predictors both ways (TIFF 6.0 section 14, Adobe TIFF technote 3; predictor 3 as libtiff's
+-- fpAcc / fpDiff), fill-order bit reversal, and the sample converter from decoded planes to a Types.Image layout.
+-- Callers (image/tiff/init) size every buffer before calling: planes hold h rows of rb bytes plus 8 bytes of slack.
+local readu8, writeu8, readu16, writeu16, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16, buffer.readu32, buffer.writeu32
+local readf32, writef32, readf64 = buffer.readf32, buffer.writef32, buffer.readf64
+local band, bor, rshift, lshift, byteswap = bit32.band, bit32.bor, bit32.rshift, bit32.lshift, bit32.byteswap
+local floor = math.floor
+
+local Pixels = {}
+
+local scratch = buffer.create(8)
+
+-- floats read through their bits: NaN / infinity never load from memory (LuaJIT's FFI would hand back a NaN with an
+-- arbitrary payload, which its NaN-tagged values misread as a table / userdata)
+local function f32(bits: number): number
+ if band(bits, 0x7F800000) == 0x7F800000 then
+ if band(bits, 0x7FFFFF) ~= 0 then
+ return 0 / 0
+ end
+ return if bits >= 0x80000000 then -math.huge else math.huge
+ end
+ writeu32(scratch, 0, bits)
+ return readf32(scratch, 0)
+end
+local function f64(lo: number, hi: number): number
+ if band(hi, 0x7FF00000) == 0x7FF00000 then
+ if band(hi, 0xFFFFF) ~= 0 or lo ~= 0 then
+ return 0 / 0
+ end
+ return if hi >= 0x80000000 then -math.huge else math.huge
+ end
+ writeu32(scratch, 0, lo)
+ writeu32(scratch, 4, hi)
+ return readf64(scratch, 0)
+end
+Pixels.f32 = f32
+Pixels.f64 = f64
+
+-- ------------------------------------------------------------------------------------------------ PackBits
+-- packbits(src, off, len, out, outOff, max) -> bytes written (stops when out or src is exhausted)
+function Pixels.packbits(src: buffer, off: number, len: number, out: buffer, outOff: number, max: number): number
+ local p, e = off, off + len
+ local o, lim = outOff, outOff + max
+ while p < e and o < lim do
+ local n = readu8(src, p)
+ p += 1
+ if n < 128 then
+ local cnt = math.min(n + 1, e - p, lim - o)
+ if cnt <= 0 then
+ break
+ end
+ buffer.copy(out, o, src, p, cnt)
+ p += n + 1
+ o += cnt
+ elseif n > 128 then
+ if p >= e then
+ break
+ end
+ local cnt = math.min(257 - n, lim - o)
+ buffer.fill(out, o, readu8(src, p), cnt)
+ p += 1
+ o += cnt
+ end
+ end
+ return o - outOff
+end
+
+-- packbitsEncode(src, off, len) -> buffer (one row at a time is the caller's business)
+function Pixels.packbitsEncode(src: buffer, off: number, len: number): buffer
+ local out = buffer.create(len + (len + 127) // 128 + 8)
+ local o = 0
+ local p, e = off, off + len
+ while p < e do
+ local run = 1
+ local v = readu8(src, p)
+ while p + run < e and run < 128 and readu8(src, p + run) == v do
+ run += 1
+ end
+ if run >= 3 then
+ writeu8(out, o, 257 - run)
+ writeu8(out, o + 1, v)
+ o += 2
+ p += run
+ else
+ local s = p
+ local n = 0
+ while p < e and n < 128 do
+ if p + 2 < e and readu8(src, p) == readu8(src, p + 1) and readu8(src, p) == readu8(src, p + 2) then
+ break
+ end
+ p += 1
+ n += 1
+ end
+ writeu8(out, o, n - 1)
+ buffer.copy(out, o + 1, src, s, n)
+ o += n + 1
+ end
+ end
+ local r = buffer.create(o)
+ buffer.copy(r, 0, out, 0, o)
+ return r
+end
+
+-- ------------------------------------------------------------------------------------------------ fill order
+local REV = buffer.create(256)
+for i = 0, 255 do
+ local r = 0
+ for k = 0, 7 do
+ if band(i, lshift(1, k)) ~= 0 then
+ r = bor(r, lshift(1, 7 - k))
+ end
+ end
+ writeu8(REV, i, r)
+end
+function Pixels.reverseBits(b: buffer, off: number, len: number)
+ for i = off, off + len - 1 do
+ writeu8(b, i, readu8(REV, readu8(b, i)))
+ end
+end
+
+-- ------------------------------------------------------------------------------------------------ predictors
+-- unpredict2(b, off, rows, rb, stride, bps, le): undo horizontal differencing (bps 8, 16 or 32; others untouched)
+function Pixels.unpredict2(b: buffer, off: number, rows: number, rb: number, stride: number, bps: number, le: boolean)
+ for r = 0, rows - 1 do
+ local base = off + r * rb
+ if bps == 8 then
+ for i = base + stride, base + rb - 1 do
+ writeu8(b, i, band(readu8(b, i) + readu8(b, i - stride), 255))
+ end
+ elseif bps == 16 then
+ local n = rb // 2
+ for k = stride, n - 1 do
+ local i = base + k * 2
+ local j = i - stride * 2
+ if le then
+ writeu16(b, i, band(readu16(b, i) + readu16(b, j), 0xFFFF))
+ else
+ local v = readu8(b, i) * 256 + readu8(b, i + 1) + readu8(b, j) * 256 + readu8(b, j + 1)
+ writeu8(b, i, band(rshift(v, 8), 255))
+ writeu8(b, i + 1, band(v, 255))
+ end
+ end
+ elseif bps == 32 then
+ local n = rb // 4
+ for k = stride, n - 1 do
+ local i = base + k * 4
+ local j = i - stride * 4
+ if le then
+ writeu32(b, i, (readu32(b, i) + readu32(b, j)) % 4294967296)
+ else
+ writeu32(b, i, byteswap((byteswap(readu32(b, i)) + byteswap(readu32(b, j))) % 4294967296))
+ end
+ end
+ end
+ end
+end
+
+-- predict2(b, off, rows, rb, stride, bps): apply horizontal differencing to little-endian samples (8 / 16 bit)
+function Pixels.predict2(b: buffer, off: number, rows: number, rb: number, stride: number, bps: number)
+ for r = 0, rows - 1 do
+ local base = off + r * rb
+ if bps == 8 then
+ for i = base + rb - 1, base + stride, -1 do
+ writeu8(b, i, band(readu8(b, i) - readu8(b, i - stride), 255))
+ end
+ elseif bps == 16 then
+ for k = rb // 2 - 1, stride, -1 do
+ local i = base + k * 2
+ writeu16(b, i, band(readu16(b, i) - readu16(b, i - stride * 2), 0xFFFF))
+ end
+ end
+ end
+end
+
+-- unpredict3(b, off, rows, rb, bytes, stride, tmp): undo the floating-point predictor; the samples come out little
+-- endian whatever the file's byte order (libtiff fpAcc). tmp holds at least rb bytes.
+function Pixels.unpredict3(b: buffer, off: number, rows: number, rb: number, bytes: number, stride: number, tmp: buffer)
+ local wc = rb // bytes
+ for r = 0, rows - 1 do
+ local base = off + r * rb
+ for i = base + stride, base + rb - 1 do
+ writeu8(b, i, band(readu8(b, i) + readu8(b, i - stride), 255))
+ end
+ buffer.copy(tmp, 0, b, base, rb)
+ for c = 0, wc - 1 do
+ for k = 0, bytes - 1 do
+ writeu8(b, base + c * bytes + k, readu8(tmp, (bytes - k - 1) * wc + c))
+ end
+ end
+ end
+end
+
+-- predict3(b, off, rows, rb, bytes, stride, tmp): the floating-point predictor on little-endian samples (fpDiff)
+function Pixels.predict3(b: buffer, off: number, rows: number, rb: number, bytes: number, stride: number, tmp: buffer)
+ local wc = rb // bytes
+ for r = 0, rows - 1 do
+ local base = off + r * rb
+ for c = 0, wc - 1 do
+ for k = 0, bytes - 1 do
+ writeu8(tmp, (bytes - k - 1) * wc + c, readu8(b, base + c * bytes + k))
+ end
+ end
+ buffer.copy(b, base, tmp, 0, rb)
+ for i = base + rb - 1, base + stride, -1 do
+ writeu8(b, i, band(readu8(b, i) - readu8(b, i - stride), 255))
+ end
+ end
+end
+
+-- ------------------------------------------------------------------------------------------------ samples
+local function half(h: number): number
+ local s = if h >= 0x8000 then -1 else 1
+ local e = band(rshift(h, 10), 31)
+ local m = band(h, 1023)
+ if e == 0 then
+ return s * m * 2 ^ -24
+ elseif e == 31 then
+ return if m == 0 then s * math.huge else 0 / 0
+ end
+ return s * (1 + m / 1024) * 2 ^ (e - 15)
+end
+
+export type Params = {
+ planes: { buffer },
+ rb: number, -- bytes per row in each plane
+ chunky: boolean,
+ w: number,
+ h: number,
+ spp: number,
+ bps: number,
+ sfmt: number, -- 1 uint, 2 int, 3 float
+ le: boolean,
+ photo: number, -- 0 min-is-white, 1 min-is-black, 2 RGB, 3 palette, 5 CMYK
+ alpha: number, -- sample index of the alpha channel, -1 = none
+ assoc: boolean, -- premultiplied alpha (undone)
+ cmap: buffer?, -- palette: 3 * 2^bps u16 (red block, green block, blue block)
+ kind: string, -- the output pixel format
+ out: buffer,
+}
+
+-- the common 8-bit chunky cases without per-sample dispatch; false when P is not one of them
+local function fast(P: Params): boolean
+ if not P.chunky or P.bps ~= 8 or P.sfmt ~= 1 or P.assoc then
+ return false
+ end
+ local b, rb, w, h, spp, alpha, kind, out = P.planes[1], P.rb, P.w, P.h, P.spp, P.alpha, P.kind, P.out
+ local o = 0
+ if P.photo == 2 and spp >= 3 and (kind == "rgba8" or kind == "rgb8") then
+ local four = kind == "rgba8"
+ for y = 0, h - 1 do
+ local p = y * rb
+ for _ = 0, w - 1 do
+ writeu8(out, o, readu8(b, p))
+ writeu8(out, o + 1, readu8(b, p + 1))
+ writeu8(out, o + 2, readu8(b, p + 2))
+ if four then
+ writeu8(out, o + 3, if alpha >= 0 then readu8(b, p + alpha) else 255)
+ o += 4
+ else
+ o += 3
+ end
+ p += spp
+ end
+ end
+ return true
+ elseif (P.photo == 1 or P.photo == 0) and (kind == "rgba8" or kind == "gray8" or kind == "graya8") then
+ local inv = if P.photo == 0 then 255 else 0
+ for y = 0, h - 1 do
+ local p = y * rb
+ for _ = 0, w - 1 do
+ local v = math.abs(inv - readu8(b, p))
+ if kind == "gray8" then
+ writeu8(out, o, v)
+ o += 1
+ elseif kind == "graya8" then
+ writeu8(out, o, v)
+ writeu8(out, o + 1, if alpha >= 0 then readu8(b, p + alpha) else 255)
+ o += 2
+ else
+ writeu32(out, o, v * 0x10101 + (if alpha >= 0 then readu8(b, p + alpha) else 255) * 0x1000000)
+ o += 4
+ end
+ p += spp
+ end
+ end
+ return true
+ end
+ return false
+end
+
+-- convert(P): every pixel into P.out in P.kind's layout
+function Pixels.convert(P: Params)
+ if fast(P) then
+ return
+ end
+ local planes, rb, chunky, w, h, spp, bps, sfmt, le = P.planes, P.rb, P.chunky, P.w, P.h, P.spp, P.bps, P.sfmt, P.le
+ local photo, alpha, assoc, cmap, kind, out = P.photo, P.alpha, P.assoc, P.cmap, P.kind, P.out
+ local maxv = 2 ^ math.min(bps, 32) - 1
+ local float = sfmt == 3
+ local signed = sfmt == 2
+ local cmapN = 2 ^ math.min(bps, 16)
+ -- raw sample s of pixel x in the row starting at byte ro of its plane
+ local function raw(s: number, x: number, row: number): number
+ local b, i
+ if chunky then
+ b, i = planes[1], x * spp + s
+ else
+ b, i = planes[s + 1], x
+ end
+ local ro = row * rb
+ if bps == 8 then
+ local v = readu8(b, ro + i)
+ return if signed then (v + 128) % 256 else v
+ elseif bps == 16 then
+ local p = ro + i * 2
+ local v = if le then readu16(b, p) else readu8(b, p) * 256 + readu8(b, p + 1)
+ if float then
+ return half(v)
+ end
+ return if signed then (v + 32768) % 65536 else v
+ elseif bps == 32 then
+ local p = ro + i * 4
+ if float then
+ return f32(if le then readu32(b, p) else byteswap(readu32(b, p)))
+ end
+ local v = if le then readu32(b, p) else byteswap(readu32(b, p))
+ return if signed then (v + 2147483648) % 4294967296 else v
+ elseif bps == 64 then
+ local p = ro + i * 8
+ if le then
+ return f64(readu32(b, p), readu32(b, p + 4))
+ end
+ return f64(byteswap(readu32(b, p + 4)), byteswap(readu32(b, p)))
+ else
+ -- any other depth (1..31): MSB-first bit fields
+ local bit = i * bps
+ local v = 0
+ local need = bps
+ local p = ro + rshift(bit, 3)
+ local sh = band(bit, 7)
+ local cur = band(readu8(b, p), rshift(255, sh))
+ local avail = 8 - sh
+ while need > 0 do
+ if need >= avail then
+ v = v * 2 ^ avail + cur
+ need -= avail
+ p += 1
+ cur = if need > 0 then readu8(b, p) else 0
+ avail = 8
+ else
+ v = v * 2 ^ need + rshift(cur, avail - need)
+ need = 0
+ end
+ end
+ return v
+ end
+ end
+ -- normalised 0..1 (floats as stored)
+ local function norm(s: number, x: number, row: number): number
+ local v = raw(s, x, row)
+ if float then
+ return v
+ end
+ return v / maxv
+ end
+ local o = 0
+ local is8 = kind == "rgba8" or kind == "rgb8" or kind == "gray8" or kind == "graya8"
+ local is16 = kind == "rgba16" or kind == "gray16"
+ local nch = if kind == "rgba8" or kind == "rgba16" or kind == "rgbaf32" then 4 elseif kind == "rgb8" then 3 elseif kind == "graya8" then 2 else 1
+ for y = 0, h - 1 do
+ for x = 0, w - 1 do
+ local r, g, bl, a
+ if photo == 3 then
+ local idx = raw(0, x, y)
+ if cmap and idx < cmapN then
+ r = readu16(cmap, idx * 2) / 65535
+ g = readu16(cmap, (cmapN + idx) * 2) / 65535
+ bl = readu16(cmap, (2 * cmapN + idx) * 2) / 65535
+ else
+ r, g, bl = 0, 0, 0
+ end
+ elseif photo == 2 then
+ r, g, bl = norm(0, x, y), norm(1, x, y), norm(2, x, y)
+ elseif photo == 5 then
+ local c, m, ye, k = norm(0, x, y), norm(1, x, y), norm(2, x, y), norm(3, x, y)
+ r, g, bl = (1 - c) * (1 - k), (1 - m) * (1 - k), (1 - ye) * (1 - k)
+ else
+ local v = norm(0, x, y)
+ if photo == 0 then
+ v = 1 - v
+ end
+ r, g, bl = v, v, v
+ end
+ if alpha >= 0 then
+ a = norm(alpha, x, y)
+ if assoc then
+ if a > 0 then
+ r, g, bl = math.min(r / a, 1), math.min(g / a, 1), math.min(bl / a, 1)
+ else
+ r, g, bl = 0, 0, 0
+ end
+ end
+ else
+ a = 1
+ end
+ if is8 then
+ if r ~= r then
+ r = 0
+ end
+ if g ~= g then
+ g = 0
+ end
+ if bl ~= bl then
+ bl = 0
+ end
+ if a ~= a then
+ a = 0
+ end
+ local R = floor(math.clamp(r, 0, 1) * 255 + 0.5)
+ if nch == 1 then
+ writeu8(out, o, R)
+ elseif nch == 2 then
+ writeu8(out, o, R)
+ writeu8(out, o + 1, floor(math.clamp(a, 0, 1) * 255 + 0.5))
+ else
+ writeu8(out, o, R)
+ writeu8(out, o + 1, floor(math.clamp(g, 0, 1) * 255 + 0.5))
+ writeu8(out, o + 2, floor(math.clamp(bl, 0, 1) * 255 + 0.5))
+ if nch == 4 then
+ writeu8(out, o + 3, floor(math.clamp(a, 0, 1) * 255 + 0.5))
+ end
+ end
+ o += nch
+ elseif is16 then
+ if r ~= r then
+ r = 0
+ end
+ if g ~= g then
+ g = 0
+ end
+ if bl ~= bl then
+ bl = 0
+ end
+ if a ~= a then
+ a = 0
+ end
+ writeu16(out, o, floor(math.clamp(r, 0, 1) * 65535 + 0.5))
+ if nch == 4 then
+ writeu16(out, o + 2, floor(math.clamp(g, 0, 1) * 65535 + 0.5))
+ writeu16(out, o + 4, floor(math.clamp(bl, 0, 1) * 65535 + 0.5))
+ writeu16(out, o + 6, floor(math.clamp(a, 0, 1) * 65535 + 0.5))
+ end
+ o += nch * 2
+ else
+ writef32(out, o, r)
+ writef32(out, o + 4, g)
+ writef32(out, o + 8, bl)
+ writef32(out, o + 12, a)
+ o += 16
+ end
+ end
+ end
+end
+
+return Pixels
diff --git a/src/Formats/image/tiff/init.luau b/src/Formats/image/tiff/init.luau
new file mode 100644
index 0000000..81dca4b
--- /dev/null
+++ b/src/Formats/image/tiff/init.luau
@@ -0,0 +1,841 @@
+--!strict
+-- image/tiff: TIFF 6.0 (+ Adobe technote 3 floating point, BigTIFF). New code from the TIFF 6.0 specification.
+-- Decode: both byte orders, classic and BigTIFF, strips and tiles, planar configuration 1 and 2, compression none /
+-- LZW (codecs/Lzw, also old-style) / Deflate (8 and 32946, codecs/Deflate) / PackBits, JPEG (7) through the api's
+-- opts.decodeImage hook (JPEGTables stitched to each strip / tile), predictors 2 (8 / 16 / 32-bit) and 3 (float),
+-- 1..32-bit unsigned / signed integer and 16 / 32 / 64-bit float samples, min-is-white / min-is-black, RGB, palette,
+-- CMYK (naive conversion), extra samples (associated alpha is un-premultiplied), fill order 2, every page as
+-- img.frames, resolution (meta.dpi), ICC (meta.icc). Decodes to rgba8, or with opts.native to the nearest standard
+-- layout (gray8, gray16, graya8, rgb8, rgba8, rgba16, rgbaf32).
+-- Encode: rgba8 / rgb8 / gray8 / graya8 / gray16 / rgba16 / rgbaf32 as the matching TIFF layout, compression none /
+-- deflate / lzw / packbits with predictor 2 (integers) or 3 (floats), strips, multi-page from img.frames.
+-- Not supported: old-style JPEG (6), CCITT fax (2, 3, 4), uncompressed YCbCr with subsampling, CIELab, JBIG.
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Types = require("@formats/Types")
+local Deflate = require("@formats/codecs/Deflate")
+local Lzw = require("@formats/codecs/Lzw")
+local Pixels = require("@formats/image/tiff/Pixels")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Tiff = {
+ name = "tiff",
+ category = "image",
+ extensions = { "tif", "tiff" },
+ mime = { "image/tiff" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/Deflate", "codecs/Lzw" },
+ caps = { decode = true, encode = true, alpha = true, pages = true, depths = { 1, 2, 4, 8, 16, 32 }, float = true },
+}
+
+-- ------------------------------------------------------------------------------------------------ types
+export type DecodeOptions = {
+ native: boolean?, -- keep the source layout (gray8 / gray16 / graya8 / rgb8 / rgba8 / rgba16 / rgbaf32); default rgba8
+ maxPixels: number?, -- per page (default 2^26)
+ maxPages: number?, -- pages decoded into img.frames (default 1024)
+ page: number?, -- decode only this page (1-based)
+ decodeImage: ((buffer) -> (any, any))?, -- the api's hook, for JPEG-compressed pages
+}
+export type EncodeOptions = {
+ compression: ("none" | "deflate" | "lzw" | "packbits")?, -- default "deflate"
+ predictor: boolean?, -- horizontal / float predictor with deflate and lzw (default true)
+ level: number?, -- deflate level 0..9 (default 6)
+ rowsPerStrip: number?, -- default: about 64 KB per strip
+}
+
+-- ------------------------------------------------------------------------------------------------ constants
+local TYPE_SIZE = { [1] = 1, [2] = 1, [3] = 2, [4] = 4, [5] = 8, [6] = 1, [7] = 1, [8] = 2, [9] = 4, [10] = 8, [11] = 4, [12] = 8, [13] = 4, [16] = 8, [17] = 8, [18] = 8 }
+local COMPRESSION = { [1] = "none", [5] = "lzw", [8] = "deflate", [32946] = "deflate", [32773] = "packbits", [7] = "jpeg" }
+local PHOTOMETRIC = { [0] = "miniswhite", [1] = "minisblack", [2] = "rgb", [3] = "palette", [5] = "cmyk", [6] = "ycbcr" }
+local TWO32 = 4294967296
+
+local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Tiff.sniff(r: Bytes.Reader): number
+ local s = r:peek(4)
+ if s == "II*\0" or s == "MM\0*" or s == "II+\0" or s == "MM\0+" then
+ return 1
+ end
+ return 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+type Entry = { tag: number, typ: number, count: number, at: number }
+type Ctx = { b: buffer, base: number, limit: number, le: boolean, big: boolean }
+
+local function u16(c: Ctx, at: number): number
+ if at < c.base or at + 2 > c.limit then
+ return 0
+ end
+ return if c.le then readu16(c.b, at) else readu8(c.b, at) * 256 + readu8(c.b, at + 1)
+end
+local function u32(c: Ctx, at: number): number
+ if at < c.base or at + 4 > c.limit then
+ return 0
+ end
+ local v = readu32(c.b, at)
+ return if c.le then v else bit32.byteswap(v)
+end
+local function u64(c: Ctx, at: number): number
+ local lo, hi = u32(c, at), u32(c, at + 4)
+ if not c.le then
+ lo, hi = hi, lo
+ end
+ return hi * TWO32 + lo
+end
+local function off(c: Ctx, at: number): number
+ return if c.big then u64(c, at) else u32(c, at)
+end
+
+-- values(c, e, max) -> the entry's numbers (rationals divided) | nil when out of range / too many
+local function values(c: Ctx, e: Entry?, max: number?): { number }?
+ if not e then
+ return nil
+ end
+ local size = TYPE_SIZE[e.typ]
+ if not size or e.count > (max or 1e7) or e.at < c.base or e.at + e.count * size > c.limit then
+ return nil
+ end
+ local out = table.create(e.count, 0)
+ local b = c.b
+ for i = 0, e.count - 1 do
+ local p = e.at + i * size
+ local t = e.typ
+ local v
+ if t == 1 or t == 2 or t == 7 then
+ v = readu8(b, p)
+ elseif t == 6 then
+ v = buffer.readi8(b, p)
+ elseif t == 3 then
+ v = u16(c, p)
+ elseif t == 8 then
+ v = u16(c, p)
+ if v >= 32768 then
+ v -= 65536
+ end
+ elseif t == 4 or t == 13 then
+ v = u32(c, p)
+ elseif t == 9 then
+ v = u32(c, p)
+ if v >= 2147483648 then
+ v -= TWO32
+ end
+ elseif t == 5 or t == 10 then
+ local n, d = u32(c, p), u32(c, p + 4)
+ if t == 10 then
+ if n >= 2147483648 then
+ n -= TWO32
+ end
+ if d >= 2147483648 then
+ d -= TWO32
+ end
+ end
+ v = if d ~= 0 then n / d else 0
+ elseif t == 11 then
+ v = Pixels.f32(u32(c, p))
+ elseif t == 12 then
+ local lo, hi = u32(c, p), u32(c, p + 4)
+ if not c.le then
+ lo, hi = hi, lo
+ end
+ v = Pixels.f64(lo, hi)
+ else
+ v = u64(c, p)
+ end
+ out[i + 1] = v
+ end
+ return out
+end
+
+local function one(c: Ctx, e: Entry?, default: number): number
+ local v = values(c, e, 64)
+ return if v and v[1] then v[1] else default
+end
+
+-- the IFD at absolute offset p: { [tag] = Entry }, next IFD offset (absolute, 0 = none) | nil, Err
+local function readIfd(c: Ctx, p: number): ({ [number]: Entry }?, number, Err.Err?)
+ local esize = if c.big then 20 else 12
+ local hsize = if c.big then 8 else 2
+ if p < c.base or p + hsize > c.limit then
+ return nil, 0, Err.new(Err.TRUNCATED, "IFD past the end", p)
+ end
+ local n = if c.big then u64(c, p) else u16(c, p)
+ if n == 0 or p + hsize + n * esize > c.limit then
+ return nil, 0, Err.new(if n == 0 then Err.CORRUPT else Err.TRUNCATED, "bad IFD entry count " .. n, p)
+ end
+ local entries: { [number]: Entry } = {}
+ for i = 0, n - 1 do
+ local q = p + hsize + i * esize
+ local tag, typ = u16(c, q), u16(c, q + 2)
+ local count = if c.big then u64(c, q + 4) else u32(c, q + 4)
+ local vat = q + (if c.big then 12 else 8)
+ local size = TYPE_SIZE[typ]
+ if size then
+ local at = vat
+ if count * size > (if c.big then 8 else 4) then
+ at = c.base + off(c, vat)
+ end
+ entries[tag] = { tag = tag, typ = typ, count = count, at = at }
+ end
+ end
+ local nq = p + hsize + n * esize
+ local nextOff = 0
+ if nq + (if c.big then 8 else 4) <= c.limit then
+ nextOff = off(c, nq)
+ end
+ return entries, if nextOff > 0 then c.base + nextOff else 0, nil
+end
+
+local function bytesOf(c: Ctx, e: Entry?, max: number): buffer?
+ if not e or e.at < c.base then
+ return nil
+ end
+ local size = TYPE_SIZE[e.typ] or 1
+ local n = e.count * size
+ if n > max or e.at + n > c.limit then
+ return nil
+ end
+ local x = buffer.create(n)
+ buffer.copy(x, 0, c.b, e.at, n)
+ return x
+end
+
+-- decompress one chunk at [p, p + len) into out[o, o + size): bytes produced | nil, Err
+local function inflateChunk(c: Ctx, comp: number, p: number, len: number, out: buffer, o: number, size: number, rev: boolean): (number?, Err.Err?)
+ if p < c.base or len < 0 or p + len > c.limit then
+ -- a chunk past the end: keep what exists (truncated files)
+ len = math.max(0, math.min(len, c.limit - p))
+ if p < c.base or p >= c.limit then
+ return 0
+ end
+ end
+ local src, sp = c.b, p
+ if rev then
+ src = buffer.create(len)
+ buffer.copy(src, 0, c.b, p, len)
+ Pixels.reverseBits(src, 0, len)
+ sp = 0
+ end
+ if comp == 1 then
+ local n = math.min(len, size)
+ buffer.copy(out, o, src, sp, n)
+ return n
+ elseif comp == 5 then
+ local n = Lzw.decode(src, sp, len, out, o, size, "tiff")
+ return n
+ elseif comp == 8 or comp == 32946 then
+ local raw = Deflate.zlib(src, sp, len, size)
+ if not raw then
+ raw = Deflate.zlib(src, sp, len) or Deflate.inflate(src, sp, len)
+ end
+ if not raw then
+ return nil, Err.new(Err.CORRUPT, "bad deflate data", p)
+ end
+ local n = math.min(buffer.len(raw :: buffer), size)
+ buffer.copy(out, o, raw :: buffer, 0, n)
+ return n
+ elseif comp == 32773 then
+ return Pixels.packbits(src, sp, len, out, o, size)
+ end
+ return nil, Err.new(Err.UNSUPPORTED, "compression " .. comp)
+end
+
+type Page = { image: Types.Image, info: { [string]: any } }
+
+local function decodePage(c: Ctx, t: { [number]: Entry }, opts: DecodeOptions?): (Types.Image?, Err.Err?)
+ local w, h = one(c, t[256], 0), one(c, t[257], 0)
+ if w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 then
+ return nil, Err.new(Err.CORRUPT, "bad image size")
+ end
+ local maxPixels = opts and opts.maxPixels or 2 ^ 26
+ if w * h > maxPixels then
+ return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
+ end
+ local spp = one(c, t[277], 1)
+ local bpsList = values(c, t[258], 64) or { 1 }
+ local bps = bpsList[1] or 1
+ for i = 2, math.min(#bpsList, spp) do
+ if bpsList[i] ~= bps then
+ return nil, Err.new(Err.UNSUPPORTED, "different bit depths per sample")
+ end
+ end
+ local comp = one(c, t[259], 1)
+ local photo = one(c, t[262], if spp >= 3 then 2 else 1)
+ local planar = one(c, t[284], 1)
+ local predictor = one(c, t[317], 1)
+ local sfmt = one(c, t[339], 1)
+ local fill = one(c, t[266], 1)
+ if spp < 1 or spp > 16 or bps < 1 or bps > 64 then
+ return nil, Err.new(Err.UNSUPPORTED, string.format("%d samples of %d bits", spp, bps))
+ end
+ if sfmt == 3 and bps ~= 16 and bps ~= 32 and bps ~= 64 then
+ return nil, Err.new(Err.UNSUPPORTED, bps .. "-bit floats")
+ end
+ if sfmt ~= 3 and bps > 32 then
+ return nil, Err.new(Err.UNSUPPORTED, bps .. "-bit integers")
+ end
+ if not COMPRESSION[comp] then
+ local names = { [2] = "CCITT RLE", [3] = "CCITT fax 3", [4] = "CCITT fax 4", [6] = "old-style JPEG", [34712] = "JPEG 2000", [34925] = "LZMA", [50000] = "Zstandard", [50001] = "WebP" }
+ return nil, Err.new(Err.UNSUPPORTED, (names[comp] or "compression") .. " (" .. comp .. ")")
+ end
+ if not PHOTOMETRIC[photo] then
+ return nil, Err.new(Err.UNSUPPORTED, "photometric interpretation " .. photo)
+ end
+ local cc = if photo == 2 or photo == 6 then 3 elseif photo == 5 then 4 else 1
+ if spp < cc then
+ return nil, Err.new(Err.CORRUPT, string.format("%d samples for photometric %d", spp, photo))
+ end
+ if photo == 5 and one(c, t[332], 1) ~= 1 then
+ return nil, Err.new(Err.UNSUPPORTED, "separated image that is not CMYK")
+ end
+ local extra = values(c, t[338], 16) or {}
+ local alpha, assoc = -1, false
+ if spp > cc then
+ local kind = extra[1] or 0
+ alpha = cc
+ assoc = kind == 1
+ end
+ local chunky = planar ~= 2 or spp == 1
+ local tiled = t[322] ~= nil
+ local cw = if tiled then one(c, t[322], 0) else w
+ local ch = if tiled then one(c, t[323], 0) else math.min(one(c, t[278], h), h)
+ if cw < 1 or ch < 1 or cw > 65536 or (tiled and ch > 65536) then
+ return nil, Err.new(Err.CORRUPT, "bad tile / strip size")
+ end
+ if ch > h and not tiled then
+ ch = h
+ end
+ local pspp = if chunky then spp else 1 -- samples per pixel in one plane
+ local nplanes = if chunky then 1 else spp
+ local rb = math.ceil(w * pspp * bps / 8) -- bytes per image row in a plane
+ local crb = math.ceil(cw * pspp * bps / 8) -- bytes per chunk row
+ if rb * h * nplanes > 2 ^ 30 or crb * ch > 2 ^ 30 then
+ return nil, Err.new(Err.LIMIT, "decoded data over 1 GB")
+ end
+ local across = if tiled then math.ceil(w / cw) else 1
+ local down = math.ceil(h / ch)
+ local perPlane = across * down
+ local offs = values(c, if tiled then t[324] else t[273], 2 ^ 24)
+ local lens = values(c, if tiled then t[325] else t[279], 2 ^ 24)
+ if not offs or #offs < perPlane * nplanes then
+ return nil, Err.new(Err.CORRUPT, "missing or short strip / tile offsets")
+ end
+ local planes = table.create(nplanes)
+ for i = 1, nplanes do
+ planes[i] = buffer.create(rb * h + 8)
+ end
+ local tmp = buffer.create(crb * ch + 8)
+ local ftmp = buffer.create(math.max(rb, crb) + 8)
+ local le = c.le
+ local bytesPer = bps // 8
+ local hook = opts and opts.decodeImage
+ local jpegTables = if comp == 7 then bytesOf(c, t[347], 1 * 2 ^ 20) else nil
+ local jpegPixels: buffer? = nil
+ if comp == 7 then
+ if type(hook) ~= "function" then
+ return nil, Err.new(Err.UNSUPPORTED, "JPEG-compressed TIFF needs opts.decodeImage (F.load supplies it)")
+ end
+ jpegPixels = buffer.create(w * h * 4)
+ end
+ for pl = 0, nplanes - 1 do
+ for ty = 0, down - 1 do
+ for tx = 0, across - 1 do
+ local idx = pl * perPlane + ty * across + tx
+ local p = c.base + offs[idx + 1]
+ local len = if lens and lens[idx + 1] then lens[idx + 1] else c.limit - p
+ local rows = if tiled then ch else math.min(ch, h - ty * ch)
+ local size = rows * crb
+ if comp == 7 then
+ -- JPEGTables (SOI .. EOI) + the chunk (SOI .. EOI): one stream without the inner EOI / SOI
+ if p < c.base or p + len > c.limit or len < 4 then
+ return nil, Err.new(Err.TRUNCATED, "JPEG chunk past the end", p)
+ end
+ local tl = if jpegTables and buffer.len(jpegTables) >= 4 then buffer.len(jpegTables) - 2 else 0
+ local s = buffer.create(tl + len - (if tl > 0 then 2 else 0))
+ if tl > 0 then
+ buffer.copy(s, 0, jpegTables :: buffer, 0, tl)
+ buffer.copy(s, tl, c.b, p + 2, len - 2)
+ else
+ buffer.copy(s, 0, c.b, p, len)
+ end
+ local ok, img, herr = pcall(hook :: any, s)
+ if not ok or type(img) ~= "table" or img.format ~= "rgba8" then
+ return nil, if ok and herr then herr else Err.new(Err.CORRUPT, "embedded JPEG: " .. tostring(if ok then herr else img))
+ end
+ local x0, y0 = tx * cw, ty * ch
+ local cwid = math.min(cw, w - x0, img.width)
+ for yy = 0, math.min(rows, h - y0, img.height) - 1 do
+ buffer.copy(jpegPixels :: buffer, ((y0 + yy) * w + x0) * 4, img.pixels, yy * img.width * 4, cwid * 4)
+ end
+ continue
+ end
+ buffer.fill(tmp, 0, 0, size)
+ local _, derr = inflateChunk(c, comp, p, len, tmp, 0, size, fill == 2)
+ if derr then
+ return nil, derr
+ end
+ if predictor == 2 then
+ Pixels.unpredict2(tmp, 0, rows, crb, pspp, bps, le)
+ elseif predictor == 3 and bytesPer >= 2 and crb % bytesPer == 0 then
+ Pixels.unpredict3(tmp, 0, rows, crb, bytesPer, pspp, ftmp)
+ end
+ -- into the plane
+ local plane = planes[pl + 1]
+ local x0b = math.floor(tx * cw * pspp * bps / 8)
+ local cols = math.min(cw, w - tx * cw)
+ local nb = math.min(math.ceil(cols * pspp * bps / 8), rb - x0b)
+ for yy = 0, rows - 1 do
+ local y = ty * ch + yy
+ if y >= h then
+ break
+ end
+ buffer.copy(plane, y * rb + x0b, tmp, yy * crb, nb)
+ end
+ end
+ end
+ end
+ local floatOut = sfmt == 3
+ if predictor == 3 and floatOut then
+ le = true -- fpAcc leaves the samples little endian
+ end
+ local colorType = PHOTOMETRIC[photo]
+ -- the output layout
+ local kind = "rgba8"
+ if opts and opts.native and comp ~= 7 then
+ if photo == 3 or photo == 5 then
+ kind = "rgba8"
+ elseif floatOut then
+ kind = "rgbaf32"
+ elseif cc == 1 then
+ if alpha >= 0 then
+ kind = if bps <= 8 then "graya8" else "rgba16"
+ else
+ kind = if bps <= 8 then "gray8" else "gray16"
+ end
+ else
+ if alpha >= 0 then
+ kind = if bps <= 8 then "rgba8" else "rgba16"
+ else
+ kind = if bps <= 8 then "rgb8" else "rgba16"
+ end
+ end
+ end
+ local img = Types.Image.new(w, h, kind :: any)
+ if comp == 7 then
+ img.pixels = jpegPixels :: buffer
+ else
+ if photo == 6 then
+ return nil, Err.new(Err.UNSUPPORTED, "uncompressed YCbCr")
+ end
+ local cmap = nil
+ if photo == 3 then
+ local n = 3 * 2 ^ math.min(bps, 16)
+ local cv = values(c, t[320], n)
+ if not cv or #cv < n then
+ return nil, Err.new(Err.CORRUPT, "palette image without a full ColorMap")
+ end
+ cmap = buffer.create(n * 2)
+ for i = 1, n do
+ buffer.writeu16(cmap, (i - 1) * 2, math.clamp(cv[i], 0, 65535))
+ end
+ end
+ Pixels.convert({
+ planes = planes,
+ rb = rb,
+ chunky = chunky,
+ w = w,
+ h = h,
+ spp = spp,
+ bps = bps,
+ sfmt = sfmt,
+ le = le,
+ photo = photo,
+ alpha = alpha,
+ assoc = assoc,
+ cmap = cmap,
+ kind = kind,
+ out = img.pixels,
+ })
+ end
+ local xr, yr = one(c, t[282], 0), one(c, t[283], 0)
+ if xr > 0 and yr > 0 then
+ local unit = one(c, t[296], 2)
+ local k = if unit == 3 then 2.54 else 1
+ if unit ~= 1 then
+ img.meta.dpi = { x = xr * k, y = yr * k }
+ end
+ end
+ img.meta.icc = bytesOf(c, t[34675], 2 ^ 26)
+ local function ascii(tag: number): string?
+ local v = bytesOf(c, t[tag], 65536)
+ if not v then
+ return nil
+ end
+ local s = buffer.tostring(v)
+ local z = string.find(s, "\0", 1, true)
+ return if z then string.sub(s, 1, z - 1) else s
+ end
+ local text = {}
+ for tag, key in { [270] = "description", [305] = "software", [306] = "datetime", [315] = "artist", [33432] = "copyright" } do
+ local s = ascii(tag)
+ if s and s ~= "" then
+ text[key] = s
+ end
+ end
+ if next(text) then
+ img.meta.text = text
+ end
+ img.meta.source = {
+ format = "tiff",
+ bitDepth = bps,
+ colorType = colorType,
+ photometric = photo,
+ samples = spp,
+ sampleFormat = if sfmt == 3 then "float" elseif sfmt == 2 then "int" else "uint",
+ compression = COMPRESSION[comp],
+ predictor = predictor,
+ planar = planar,
+ tiled = tiled,
+ alpha = if alpha >= 0 then (if assoc then "associated" else "unassociated") else nil,
+ bigtiff = c.big,
+ byteOrder = if c.le then "II" else "MM",
+ }
+ return img, nil
+end
+
+-- pages(r) -> the IFD tables of every page (and the context) | nil, Err
+local function pages(r: Bytes.Reader, maxPages: number): ({ { [number]: Entry } }?, Ctx?, Err.Err?)
+ local b, base, limit = r.buf, r.base, r.limit
+ if limit - base < 8 then
+ return nil, nil, Err.new(Err.TRUNCATED, "short header")
+ end
+ local bo = buffer.readstring(b, base, 2)
+ if bo ~= "II" and bo ~= "MM" then
+ return nil, nil, Err.new(Err.CORRUPT, "bad byte order mark")
+ end
+ local c: Ctx = { b = b, base = base, limit = limit, le = bo == "II", big = false }
+ local magic = u16(c, base + 2)
+ local first
+ if magic == 42 then
+ first = u32(c, base + 4)
+ elseif magic == 43 then
+ if limit - base < 16 or u16(c, base + 4) ~= 8 then
+ return nil, nil, Err.new(Err.CORRUPT, "bad BigTIFF header")
+ end
+ c.big = true
+ first = u64(c, base + 8)
+ else
+ return nil, nil, Err.new(Err.CORRUPT, "bad magic " .. magic)
+ end
+ local list = {}
+ local seen = {}
+ local p = base + first
+ while p > 0 and #list < maxPages do
+ if seen[p] then
+ break -- an IFD loop
+ end
+ seen[p] = true
+ local t, nextP, err = readIfd(c, p)
+ if not t then
+ if #list == 0 then
+ return nil, nil, err
+ end
+ break
+ end
+ table.insert(list, t)
+ p = nextP
+ end
+ return list, c, nil
+end
+
+-- info(r) -> { pages, width, height, bitDepth, samples, compression } of page 1 | nil, Err
+function Tiff.info(r: Bytes.Reader): ({ [string]: any }?, Err.Err?)
+ local list, c, err = pages(r, 1024)
+ if not list or not c then
+ return nil, err
+ end
+ local t = list[1]
+ return {
+ pages = #list,
+ width = one(c, t[256], 0),
+ height = one(c, t[257], 0),
+ bitDepth = one(c, t[258], 1),
+ samples = one(c, t[277], 1),
+ compression = COMPRESSION[one(c, t[259], 1)] or tostring(one(c, t[259], 1)),
+ photometric = PHOTOMETRIC[one(c, t[262], 1)],
+ bigtiff = c.big,
+ },
+ nil
+end
+
+function Tiff.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
+ local maxPages = opts and opts.maxPages or 1024
+ local list, c, err = pages(r, if opts and opts.page then math.max(1, opts.page) else maxPages)
+ if not list or not c then
+ return nil, err
+ end
+ if opts and opts.page then
+ local t = list[opts.page]
+ if not t then
+ return nil, Err.new(Err.ARG, "no page " .. tostring(opts.page))
+ end
+ local img, perr = decodePage(c, t, opts)
+ if img then
+ img.meta.source.pages = #list
+ end
+ return img, perr
+ end
+ local first: Types.Image? = nil
+ local frames = {}
+ for i, t in list do
+ -- reduced-resolution subfiles (thumbnails) after page 1 are skipped
+ local sub = one(c, t[254], 0)
+ if i > 1 and bit32.band(sub, 1) ~= 0 then
+ continue
+ end
+ local img, perr = decodePage(c, t, opts)
+ if not img then
+ if i == 1 then
+ return nil, perr
+ end
+ continue
+ end
+ if not first then
+ first = img
+ end
+ table.insert(frames, { image = img, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" })
+ end
+ local img = first :: Types.Image
+ img.meta.source.pages = #frames
+ if #frames > 1 then
+ img.frames = frames :: any
+ end
+ return img, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+-- layout per pixel format: samples, bits, sample format, photometric, extra samples
+local LAYOUT = {
+ gray8 = { 1, 8, 1, 1 },
+ graya8 = { 2, 8, 1, 1 },
+ gray16 = { 1, 16, 1, 1 },
+ rgb8 = { 3, 8, 1, 2 },
+ rgba8 = { 4, 8, 1, 2 },
+ rgba16 = { 4, 16, 1, 2 },
+ rgbaf32 = { 4, 32, 3, 2 },
+}
+local COMP_CODES = { none = 1, deflate = 8, lzw = 5, packbits = 32773 }
+
+type Tag = { tag: number, typ: number, vals: { number }?, data: buffer? }
+
+local function encodePage(img: Types.Image, o: EncodeOptions, comp: number): ({ Tag }?, { buffer }?, Err.Err?)
+ local L = LAYOUT[img.format]
+ if not L then
+ return nil, nil, Err.new(Err.ARG, "unsupported pixel format " .. tostring(img.format))
+ end
+ local w, h = img.width, img.height
+ local spp, bps, sfmt, photo = L[1], L[2], L[3], L[4]
+ local rb = w * spp * bps // 8
+ if type(w) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or w > 2 ^ 31 or buffer.len(img.pixels) < rb * h then
+ return nil, nil, Err.new(Err.ARG, "bad image size or pixel buffer")
+ end
+ local rps = o.rowsPerStrip or math.max(1, 65536 // rb)
+ if type(rps) ~= "number" or rps < 1 then
+ return nil, nil, Err.new(Err.ARG, "rowsPerStrip must be >= 1")
+ end
+ rps = math.min(math.floor(rps), h)
+ local predictor = 1
+ if (comp == 8 or comp == 5) and o.predictor ~= false then
+ predictor = if sfmt == 3 then 3 else 2
+ end
+ local strips = {}
+ local tmp = buffer.create(rb + 8)
+ for y0 = 0, h - 1, rps do
+ local rows = math.min(rps, h - y0)
+ local raw = buffer.create(rows * rb)
+ buffer.copy(raw, 0, img.pixels, y0 * rb, rows * rb)
+ if predictor == 2 then
+ Pixels.predict2(raw, 0, rows, rb, spp, bps)
+ elseif predictor == 3 then
+ Pixels.predict3(raw, 0, rows, rb, 4, spp, tmp)
+ end
+ local out
+ if comp == 1 then
+ out = raw
+ elseif comp == 8 then
+ out = Deflate.zlibCompress(raw, { level = o.level or 6 }) :: buffer
+ elseif comp == 5 then
+ out = Lzw.encode(raw, 0, rows * rb, "tiff")
+ else
+ local parts, total = {}, 0
+ for r = 0, rows - 1 do
+ local p = Pixels.packbitsEncode(raw, r * rb, rb)
+ table.insert(parts, p)
+ total += buffer.len(p)
+ end
+ out = buffer.create(total)
+ local q = 0
+ for _, p in parts do
+ buffer.copy(out, q, p)
+ q += buffer.len(p)
+ end
+ end
+ table.insert(strips, out)
+ end
+ local bpsv = table.create(spp, bps)
+ local tags: { Tag } = {
+ { tag = 254, typ = 4, vals = { 0 } },
+ { tag = 256, typ = 4, vals = { w } },
+ { tag = 257, typ = 4, vals = { h } },
+ { tag = 258, typ = 3, vals = bpsv },
+ { tag = 259, typ = 3, vals = { comp } },
+ { tag = 262, typ = 3, vals = { photo } },
+ { tag = 273, typ = 4, vals = table.create(#strips, 0) }, -- patched
+ { tag = 277, typ = 3, vals = { spp } },
+ { tag = 278, typ = 4, vals = { rps } },
+ { tag = 279, typ = 4, vals = table.create(#strips, 0) },
+ { tag = 284, typ = 3, vals = { 1 } },
+ }
+ for i, s in strips do
+ (tags[10].vals :: { number })[i] = buffer.len(s)
+ end
+ local dpi = img.meta and img.meta.dpi
+ if type(dpi) == "table" and type(dpi.x) == "number" and type(dpi.y) == "number" and dpi.x > 0 and dpi.y > 0 then
+ table.insert(tags, { tag = 282, typ = 5, vals = { dpi.x } })
+ table.insert(tags, { tag = 283, typ = 5, vals = { dpi.y } })
+ table.insert(tags, { tag = 296, typ = 3, vals = { 2 } })
+ end
+ if predictor > 1 then
+ table.insert(tags, { tag = 317, typ = 3, vals = { predictor } })
+ end
+ if spp == 2 or spp == 4 then
+ table.insert(tags, { tag = 338, typ = 3, vals = { 2 } })
+ end
+ if sfmt ~= 1 then
+ table.insert(tags, { tag = 339, typ = 3, vals = table.create(spp, sfmt) })
+ end
+ local icc = img.meta and img.meta.icc
+ if type(icc) == "buffer" then
+ table.insert(tags, { tag = 34675, typ = 7, data = icc })
+ end
+ local text = img.meta and img.meta.text
+ if type(text) == "table" then
+ for key, tag in { description = 270, software = 305, datetime = 306, artist = 315, copyright = 33432 } do
+ if type(text[key]) == "string" then
+ table.insert(tags, { tag = tag, typ = 2, data = buffer.fromstring(text[key] .. "\0") })
+ end
+ end
+ end
+ table.sort(tags, function(a: Tag, b: Tag): boolean
+ return a.tag < b.tag
+ end)
+ return tags, strips, nil
+end
+
+function Tiff.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
+ if type(img) ~= "table" or type(img.pixels) ~= "buffer" then
+ return nil, Err.new(Err.ARG, "needs an Image")
+ end
+ local o: EncodeOptions = opts or {}
+ local comp = COMP_CODES[o.compression or "deflate"]
+ if not comp then
+ return nil, Err.new(Err.ARG, "compression must be none, deflate, lzw or packbits")
+ end
+ local list = { img }
+ if type(img.frames) == "table" and #img.frames > 1 then
+ list = {}
+ for _, f in img.frames :: any do
+ if type(f) ~= "table" or type(f.image) ~= "table" then
+ return nil, Err.new(Err.ARG, "bad frame")
+ end
+ table.insert(list, f.image)
+ end
+ end
+ local w = Bytes.writer(1024)
+ w:string("II")
+ w:u16le(42)
+ w:u32le(0) -- first IFD, patched
+ local prevNext = 4
+ for _, page in list do
+ local tags, strips, err = encodePage(page, o, comp)
+ if not tags or not strips then
+ return nil, err
+ end
+ -- strip data first
+ local soffs = {}
+ for i, s in strips do
+ if w:tell() % 2 == 1 then
+ w:u8(0)
+ end
+ soffs[i] = w:tell()
+ w:bytes(s)
+ end
+ for _, tg in tags do
+ if tg.tag == 273 then
+ tg.vals = soffs
+ end
+ end
+ -- out-of-line values
+ local valOff: { [number]: number } = {}
+ for i, tg in tags do
+ local size = TYPE_SIZE[tg.typ]
+ local n = if tg.data then buffer.len(tg.data :: buffer) else #(tg.vals :: { number }) * size
+ if n > 4 then
+ if w:tell() % 2 == 1 then
+ w:u8(0)
+ end
+ valOff[i] = w:tell()
+ if tg.data then
+ w:bytes(tg.data :: buffer)
+ else
+ for _, v in tg.vals :: { number } do
+ if tg.typ == 3 then
+ w:u16le(v)
+ elseif tg.typ == 4 then
+ w:u32le(v)
+ elseif tg.typ == 5 then
+ w:u32le(math.floor(v * 10000 + 0.5))
+ w:u32le(10000)
+ end
+ end
+ end
+ end
+ end
+ if w:tell() % 2 == 1 then
+ w:u8(0)
+ end
+ local ifd = w:tell()
+ w:setU32le(prevNext, ifd)
+ w:u16le(#tags)
+ for i, tg in tags do
+ local count = if tg.data then buffer.len(tg.data :: buffer) else #(tg.vals :: { number })
+ w:u16le(tg.tag)
+ w:u16le(tg.typ)
+ w:u32le(count)
+ if valOff[i] then
+ w:u32le(valOff[i])
+ else
+ local start = w:tell()
+ if tg.data then
+ w:bytes(tg.data :: buffer)
+ else
+ for _, v in tg.vals :: { number } do
+ if tg.typ == 3 then
+ w:u16le(v)
+ else
+ w:u32le(v)
+ end
+ end
+ end
+ w:fill(0, 4 - (w:tell() - start))
+ end
+ end
+ prevNext = w:tell()
+ w:u32le(0)
+ end
+ return w:finish(), nil
+end
+
+return Tiff
diff --git a/src/Formats/image/webp/Alpha.luau b/src/Formats/image/webp/Alpha.luau
new file mode 100644
index 0000000..5da90de
--- /dev/null
+++ b/src/Formats/image/webp/Alpha.luau
@@ -0,0 +1,76 @@
+--!strict
+--!native
+-- image/webp/Alpha: the ALPH chunk (RFC 9649 section 2.7.1.2): header byte (compression, filter, pre-processing),
+-- raw or VP8L-compressed alpha (the green channel of a headerless VP8L stream), and the horizontal / vertical /
+-- gradient unfilters of libwebp src/dsp/filters.c (BSD-3-Clause, licenses/libwebp-LICENSE.txt). Never throws.
+local Vp8L = require("@formats/codecs/Vp8L")
+
+local readu8, writeu8 = buffer.readu8, buffer.writeu8
+
+local Alpha = {}
+
+local function unfilter(a: buffer, w: number, h: number, filter: number)
+ if filter == 0 then
+ return
+ end
+ for y = 0, h - 1 do
+ local row = y * w
+ local prev = row - w
+ if y == 0 or filter == 1 then
+ -- horizontal (also the first row of the other filters): the left pixel, the first one from above
+ local pred = if y == 0 then 0 else readu8(a, prev)
+ for i = row, row + w - 1 do
+ pred = (pred + readu8(a, i)) % 256
+ writeu8(a, i, pred)
+ end
+ elseif filter == 2 then
+ for i = 0, w - 1 do
+ writeu8(a, row + i, (readu8(a, prev + i) + readu8(a, row + i)) % 256)
+ end
+ else
+ local top = readu8(a, prev)
+ local topLeft, left = top, top
+ for i = 0, w - 1 do
+ top = readu8(a, prev + i)
+ local g = left + top - topLeft
+ g = if g < 0 then 0 elseif g > 255 then 255 else g
+ left = (readu8(a, row + i) + g) % 256
+ topLeft = top
+ writeu8(a, row + i, left)
+ end
+ end
+ end
+end
+
+-- decode(buf, off, len, w, h) -> w * h alpha bytes, header info | nil, message
+function Alpha.decode(buf: buffer, off: number, len: number, w: number, h: number): (buffer?, any)
+ if len <= 1 then
+ return nil, "truncated: ALPH chunk"
+ end
+ local hb = readu8(buf, off)
+ local method = hb % 4
+ local filter = (hb // 4) % 4
+ local pre = (hb // 16) % 4
+ if method > 1 or pre > 1 or hb >= 64 then
+ return nil, "bad ALPH header"
+ end
+ local a: buffer
+ if method == 0 then
+ if len - 1 < w * h then
+ return nil, "truncated: raw alpha"
+ end
+ a = buffer.create(w * h)
+ buffer.copy(a, 0, buf, off + 1, w * h)
+ else
+ local d, err = Vp8L.decodeAlpha(buf, off + 1, len - 1, w, h)
+ if not d then
+ local e = err :: any
+ return nil, if e.code == "TRUNCATED" then "truncated: alpha " .. e.message else "alpha: " .. e.message
+ end
+ a = d
+ end
+ unfilter(a, w, h, filter)
+ return a, { method = method, filter = filter, preprocessing = pre }
+end
+
+return Alpha
diff --git a/src/Formats/image/webp/Anim.luau b/src/Formats/image/webp/Anim.luau
new file mode 100644
index 0000000..559202d
--- /dev/null
+++ b/src/Formats/image/webp/Anim.luau
@@ -0,0 +1,162 @@
+--!strict
+--!native
+-- image/webp/Anim: animation compositing. coalesce() reproduces libwebp's WebPAnimDecoder (src/demux/anim_decode.c,
+-- BSD-3-Clause, licenses/libwebp-LICENSE.txt) exactly: key frame detection, transparent canvas (the background colour
+-- is ignored, as the spec recommends and libwebp does), non-premultiplied "over" blending of the pixels with alpha
+-- < 255, dispose to background. composite() is the generic Types.Frame model (also dispose "previous") used by the
+-- encoder to flatten frames WebP cannot store as they are. Pixels are rgba8; never throws.
+local band, rshift = bit32.band, bit32.rshift
+local readu32, writeu32 = buffer.readu32, buffer.writeu32
+local bcreate, bcopy, bfill = buffer.create, buffer.copy, buffer.fill
+
+local Anim = {}
+
+export type Frame = {
+ rgba: buffer, -- w * h rgba8
+ x: number,
+ y: number,
+ w: number,
+ h: number,
+ blend: boolean, -- alpha-blend over the canvas (false: overwrite)
+ disposeBg: boolean, -- after display, clear the rectangle to transparent
+ disposePrev: boolean?, -- after display, restore the canvas as it was before the frame (composite() only)
+ hasAlpha: boolean,
+}
+
+-- blend(src, dst) -> src over dst, both non-premultiplied 0xAABBGGRR (libwebp BlendPixelNonPremult)
+local function blendPixel(src: number, dst: number): number
+ local sa = rshift(src, 24)
+ if sa == 0 then
+ return dst
+ end
+ local da = rshift(dst, 24)
+ local dfa = rshift(da * (256 - sa), 8)
+ local ba = sa + dfa
+ local scale = 16777216 // ba
+ local r = ((band(src, 255) * sa + band(dst, 255) * dfa) * scale) // 16777216
+ local g = ((band(rshift(src, 8), 255) * sa + band(rshift(dst, 8), 255) * dfa) * scale) // 16777216
+ local b = ((band(rshift(src, 16), 255) * sa + band(rshift(dst, 16), 255) * dfa) * scale) // 16777216
+ return r + g * 256 + b * 65536 + ba * 16777216
+end
+Anim.blendPixel = blendPixel
+
+-- blendRow(cur, prev, offset, n): pixels of cur with alpha < 255 blended over prev (pixel offsets)
+local function blendRow(cur: buffer, prev: buffer, o: number, n: number)
+ for i = o, o + n - 1 do
+ local s = readu32(cur, i * 4)
+ if s < 0xff000000 then
+ writeu32(cur, i * 4, blendPixel(s, readu32(prev, i * 4)))
+ end
+ end
+end
+
+-- draw(canvas, cw, f): copy the frame rectangle into the canvas
+local function draw(canvas: buffer, cw: number, f: Frame)
+ for j = 0, f.h - 1 do
+ bcopy(canvas, ((f.y + j) * cw + f.x) * 4, f.rgba, j * f.w * 4, f.w * 4)
+ end
+end
+
+local function clearRect(canvas: buffer, cw: number, x: number, y: number, w: number, h: number)
+ for j = 0, h - 1 do
+ bfill(canvas, ((y + j) * cw + x) * 4, 0, w * 4)
+ end
+end
+
+-- coalesce(cw, ch, frames) -> one full canvas (rgba8) per frame, as WebPAnimDecoder returns them
+function Anim.coalesce(cw: number, ch: number, frames: { Frame }): { buffer }
+ local size = cw * ch * 4
+ local out: { buffer } = {}
+ local disposed = bcreate(size)
+ local prev: Frame? = nil
+ local prevKey = false
+ for n, f in frames do
+ local full = f.w == cw and f.h == ch
+ local key
+ if n == 1 then
+ key = true
+ elseif (not f.hasAlpha or not f.blend) and full then
+ key = true
+ else
+ local p = prev :: Frame
+ key = p.disposeBg and ((p.w == cw and p.h == ch) or prevKey)
+ end
+ local cur = bcreate(size)
+ if not key then
+ bcopy(cur, 0, disposed, 0, size)
+ end
+ draw(cur, cw, f)
+ if n > 1 and f.blend and not key then
+ local p = prev :: Frame
+ if not p.disposeBg then
+ for j = 0, f.h - 1 do
+ blendRow(cur, disposed, (f.y + j) * cw + f.x, f.w)
+ end
+ else
+ -- the previous rectangle was cleared: blending with transparent there is a no-op for libwebp
+ local pmx, pmy = p.x + p.w, p.y + p.h
+ local smx = f.x + f.w
+ for j = 0, f.h - 1 do
+ local cy = f.y + j
+ if cy < p.y or cy >= pmy or f.x >= pmx or smx <= p.x then
+ blendRow(cur, disposed, cy * cw + f.x, f.w)
+ else
+ if f.x < p.x then
+ blendRow(cur, disposed, cy * cw + f.x, p.x - f.x)
+ end
+ if smx > pmx then
+ blendRow(cur, disposed, cy * cw + pmx, smx - pmx)
+ end
+ end
+ end
+ end
+ end
+ table.insert(out, cur)
+ prev = f
+ prevKey = key
+ bcopy(disposed, 0, cur, 0, size)
+ if f.disposeBg then
+ clearRect(disposed, cw, f.x, f.y, f.w, f.h)
+ end
+ end
+ return out
+end
+
+-- composite(cw, ch, frames) -> one full canvas per frame in the generic model: start transparent, draw (blend or
+-- overwrite; "over" a fully transparent pixel copies it), show, then dispose (background: clear the rectangle;
+-- previous: restore)
+function Anim.composite(cw: number, ch: number, frames: { Frame }): { buffer }
+ local size = cw * ch * 4
+ local canvas = bcreate(size)
+ local out: { buffer } = {}
+ for _, f in frames do
+ local saved: buffer? = nil
+ if f.disposePrev then
+ saved = bcreate(size)
+ bcopy(saved :: buffer, 0, canvas, 0, size)
+ end
+ if f.blend then
+ for j = 0, f.h - 1 do
+ local co = (f.y + j) * cw + f.x
+ for i = 0, f.w - 1 do
+ local s = readu32(f.rgba, (j * f.w + i) * 4)
+ local d = readu32(canvas, (co + i) * 4)
+ writeu32(canvas, (co + i) * 4, if s >= 0xff000000 or d < 0x01000000 then s else blendPixel(s, d))
+ end
+ end
+ else
+ draw(canvas, cw, f)
+ end
+ local shown = bcreate(size)
+ bcopy(shown, 0, canvas, 0, size)
+ table.insert(out, shown)
+ if saved then
+ canvas = saved
+ elseif f.disposeBg then
+ clearRect(canvas, cw, f.x, f.y, f.w, f.h)
+ end
+ end
+ return out
+end
+
+return Anim
diff --git a/src/Formats/image/webp/init.luau b/src/Formats/image/webp/init.luau
new file mode 100644
index 0000000..418aaee
--- /dev/null
+++ b/src/Formats/image/webp/init.luau
@@ -0,0 +1,627 @@
+--!strict
+-- image/webp: WebP (RFC 9649; Google's "WebP Container Specification"). New code: the bitstreams are ports of libwebp 1.6
+-- (codecs/Vp8, codecs/Vp8L; BSD-3-Clause, licenses/libwebp-LICENSE.txt), the chunks go through containers/Riff, the
+-- container rules and the compositing follow libwebp's demux / WebPAnimDecoder.
+-- Supports: decode of lossy (VP8 key frames: bit-exact with dwebp, fancy or point chroma upsampling, or the raw
+-- yuv420p planes with opts.native), lossless (VP8L, bit-exact), alpha (ALPH raw or lossless, every filter), the
+-- extended format (VP8X), animation (ANIM / ANMF: frames as their own rectangles plus the composited first frame, or
+-- every frame composited exactly as WebPAnimDecoder with opts.coalesce), ICC / EXIF / XMP into meta.icc / meta.exif
+-- / meta.xmp; encode of rgba8 images and animations as lossless VP8L (VP8X / ANIM / ANMF for animations and
+-- metadata).
+-- Not supported: lossy encoding (UNSUPPORTED), the VP8 horizontal / vertical scale fields (ignored, as dwebp does),
+-- alpha dithering / premultiplied output.
+-- Speed (one Zen 5 core, 512 x 512, tools/bench.luau): lossy decode ~50 MB/s of rgba8 out (luau --codegen) / ~38 MB/s
+-- (LuaJIT), lossless decode ~43 / ~73 MB/s, lossless encode ~6 / ~8 MB/s at effort 5 (~15 / ~18 MB/s at effort 1).
+-- Encoded size: within ~4 % of cwebp -lossless on photos at effort 9, smaller on some synthetic images.
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Types = require("@formats/Types")
+local Vp8 = require("@formats/codecs/Vp8")
+local Vp8L = require("@formats/codecs/Vp8L")
+local Riff = require("@formats/containers/Riff")
+local Alpha = require("@formats/image/webp/Alpha")
+local Anim = require("@formats/image/webp/Anim")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Webp = {
+ name = "webp",
+ category = "image",
+ extensions = { "webp" },
+ mime = { "image/webp" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/Vp8", "codecs/Vp8L", "containers/Riff" },
+ caps = { decode = true, encode = true, animation = true, alpha = true, lossy = true, lossless = true, depths = { 8 } },
+}
+
+-- ------------------------------------------------------------------------------------------------ types
+export type DecodeOptions = {
+ maxPixels: number?, -- refuse a canvas or frame larger than this (default 2^26)
+ native: boolean?, -- a still lossy image without alpha decodes to its yuv420p planes (default false: rgba8)
+ upsampling: ("fancy" | "nearest")?, -- lossy chroma upsampling, default "fancy" (libwebp's default; "nearest" =
+ -- dwebp -nofancy)
+ coalesce: boolean?, -- animations: every frame is the full composited canvas (x = y = 0, dispose "none",
+ -- blend "source"), exactly what WebPAnimDecoder returns (default false: each frame's own rectangle)
+ frames: boolean?, -- animations: decode every frame (default true; false: only the first canvas)
+}
+
+export type EncodeOptions = {
+ lossless: boolean?, -- must be true or nil (lossy encoding is not supported)
+ effort: number?, -- 0..9, default 5: VP8L encoder effort (more = smaller, slower)
+ exact: boolean?, -- keep the RGB of fully transparent pixels (default false: they may be changed)
+ loops: number?, -- animations: loop count (default img.loops; 0 = forever)
+ background: { number }?, -- animations: ANIM background colour { r, g, b, a } (default meta.background or 0)
+}
+
+-- ------------------------------------------------------------------------------------------------ constants
+local DEFAULT_MAX_PIXELS = 2 ^ 26
+local FLAG_ANIM, FLAG_XMP, FLAG_EXIF, FLAG_ALPHA, FLAG_ICC = 0x02, 0x04, 0x08, 0x10, 0x20
+
+local readu8 = buffer.readu8
+
+local function u24(buf: buffer, p: number): number
+ return readu8(buf, p) + readu8(buf, p + 1) * 256 + readu8(buf, p + 2) * 65536
+end
+
+local function corrupt(msg: string, offset: number?): (nil, Err.Err)
+ return nil, Err.new(Err.CORRUPT, msg, offset)
+end
+
+-- an Err from a submodule message ("truncated: ...", "limit: ...", "unsupported: ...", else CORRUPT)
+local function fromMessage(msg: any, offset: number?): Err.Err
+ if Err.is(msg) then
+ return msg
+ end
+ local m = tostring(msg)
+ for _, k in { { "truncated: ", Err.TRUNCATED }, { "limit: ", Err.LIMIT }, { "unsupported: ", Err.UNSUPPORTED } } do
+ if string.sub(m, 1, #k[1]) == k[1] then
+ return Err.new(k[2], string.sub(m, #k[1] + 1), offset)
+ end
+ end
+ return Err.new(Err.CORRUPT, m, offset)
+end
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Webp.sniff(r: Bytes.Reader): number
+ if r:peek(4) == "RIFF" and r:peek(4, 8) == "WEBP" then
+ return 1
+ end
+ return 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+type Chunk = { id: string, off: number, size: number } -- off: absolute offset of the payload
+
+local function convert(list: { Riff.Chunk }): ({ Chunk }?, Err.Err?)
+ local out: { Chunk } = {}
+ for _, c in list do
+ if c.truncated then
+ return nil, Err.new(Err.TRUNCATED, "chunk '" .. c.id .. "' runs past the end", c.offset)
+ end
+ table.insert(out, { id = c.id, off = c.offset, size = c.size })
+ end
+ return out, nil
+end
+
+-- readChunks(r) -> the chunks of a RIFF "WEBP" file, the containers/Riff File | nil, Err. As libwebp: the RIFF size
+-- must fit the data (TRUNCATED) and bytes after it are ignored.
+local function readChunks(r: Bytes.Reader): ({ Chunk }?, any)
+ local buf, base, limit = r.buf, r.base, r.limit
+ if limit - base < 12 then
+ return nil, Err.new(Err.TRUNCATED, "RIFF header", base)
+ end
+ if buffer.readstring(buf, base, 4) ~= "RIFF" or buffer.readstring(buf, base + 8, 4) ~= "WEBP" then
+ return nil, Err.new(Err.CORRUPT, "not a RIFF WEBP file", base)
+ end
+ local size = buffer.readu32(buf, base + 4)
+ if size < 12 then
+ return nil, Err.new(Err.CORRUPT, "RIFF size too small", base + 4)
+ end
+ if 8 + size > limit - base then
+ return nil, Err.new(Err.TRUNCATED, "the RIFF size runs past the end of the data", base + 4)
+ end
+ local f, err = Riff.read(Bytes.reader(buf, base, 8 + size))
+ if not f then
+ return nil, err
+ end
+ local list, cerr = convert(f.chunks)
+ if not list then
+ return nil, cerr
+ end
+ return list, f
+end
+
+-- subChunks(f, c) -> the chunks inside an ANMF payload (after its 16-byte header)
+local function subChunks(f: Riff.File, c: Chunk): ({ Chunk }?, Err.Err?)
+ local n = c.size - 12
+ return convert(Riff.list(f, { id = c.id, offset = c.off + 12, size = n, declared = n, avail = n, truncated = false, streamed = false }))
+end
+
+type Bitstream = { rgba: buffer?, yuv: Types.Image?, w: number, h: number, hasAlpha: boolean, source: { [string]: any } }
+
+-- the image chunks of a still image or an ANMF frame: the first ALPH (if any) and the first VP8 / VP8L chunk
+local function findImage(chunks: { Chunk }, from: number): (Chunk?, Chunk?)
+ local alph: Chunk? = nil
+ for i = from, #chunks do
+ local c = chunks[i]
+ if c.id == "ALPH" and not alph then
+ alph = c
+ elseif c.id == "VP8 " or c.id == "VP8L" then
+ return c, alph
+ elseif c.id == "ANMF" then
+ break
+ end
+ end
+ return nil, nil
+end
+
+local function decodeBitstream(buf: buffer, c: Chunk, alph: Chunk?, opts: DecodeOptions, allowNative: boolean): (Bitstream?, Err.Err?)
+ local maxPixels = opts.maxPixels or DEFAULT_MAX_PIXELS
+ if c.id == "VP8L" then
+ local rgba, w, h, alphaHint = Vp8L.decode(buf, c.off, c.size, maxPixels)
+ if not rgba then
+ return nil, w
+ end
+ return { rgba = rgba, w = w, h = h :: number, hasAlpha = alphaHint == true, source = { codec = "vp8l", lossless = true } }, nil
+ end
+ local y, u, v, w, h = Vp8.decodePlanes(buf, c.off, c.size, { maxPixels = maxPixels })
+ if not y then
+ return nil, u
+ end
+ local fw, fh = w :: number, h :: number
+ local source: { [string]: any } = { codec = "vp8", lossless = false }
+ if allowNative and opts.native and not alph then
+ local img = Types.Image.new(fw, fh, "yuv420p")
+ local ny, nc = fw * fh, buffer.len(v :: buffer)
+ buffer.copy(img.pixels, 0, y, 0, ny)
+ buffer.copy(img.pixels, ny, u, 0, nc)
+ buffer.copy(img.pixels, ny + nc, v :: buffer, 0, nc)
+ return { yuv = img, w = fw, h = fh, hasAlpha = false, source = source }, nil
+ end
+ local rgba = Vp8.yuvToRgba(y, u, v :: buffer, fw, fh, opts.upsampling ~= "nearest")
+ if alph then
+ local a, info = Alpha.decode(buf, alph.off, alph.size, fw, fh)
+ if not a then
+ return nil, fromMessage(info, alph.off)
+ end
+ Vp8.setAlpha(rgba, a, fw * fh)
+ source.alpha = info
+ end
+ return { rgba = rgba, w = fw, h = fh, hasAlpha = alph ~= nil, source = source }, nil
+end
+
+local function collectMeta(buf: buffer, chunks: { Chunk }, meta: Types.ImageMeta)
+ for _, c in chunks do
+ local key = if c.id == "ICCP" then "icc" elseif c.id == "EXIF" then "exif" elseif c.id == "XMP " then "xmp" else nil
+ if key and meta[key] == nil then
+ local b = buffer.create(c.size)
+ buffer.copy(b, 0, buf, c.off, c.size)
+ meta[key] = b
+ end
+ end
+end
+
+function Webp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
+ local o: DecodeOptions = opts or {}
+ local maxPixels = o.maxPixels or DEFAULT_MAX_PIXELS
+ local buf = r.buf
+ local chunks, file = readChunks(r)
+ if not chunks then
+ return nil, file
+ end
+ local first = chunks[1]
+ if not first then
+ return corrupt("no chunks", r.base + 12)
+ end
+ if first.id == "VP8 " or first.id == "VP8L" then
+ local bs, err = decodeBitstream(buf, first, nil, o, true)
+ if not bs then
+ return nil, err
+ end
+ local img = bs.yuv or Types.Image.new(bs.w, bs.h, "rgba8")
+ if bs.rgba then
+ img.pixels = bs.rgba
+ end
+ bs.source.format = "webp"
+ bs.source.bitDepth = 8
+ bs.source.extended = false
+ img.meta.source = bs.source
+ return img, nil
+ end
+ if first.id ~= "VP8X" then
+ return corrupt("the first chunk is '" .. first.id .. "', not VP8, VP8L or VP8X", first.off - 8)
+ end
+ if first.size < 10 then
+ return nil, Err.new(Err.TRUNCATED, "VP8X chunk too small", first.off)
+ end
+ local flags = readu8(buf, first.off)
+ local cw = u24(buf, first.off + 4) + 1
+ local ch = u24(buf, first.off + 7) + 1
+ if cw * ch > maxPixels then
+ return nil, Err.new(Err.LIMIT, string.format("%d x %d canvas is over the %d pixel limit", cw, ch, maxPixels))
+ end
+ local meta: Types.ImageMeta = {}
+ collectMeta(buf, chunks, meta)
+
+ if bit32.band(flags, FLAG_ANIM) == 0 then
+ local c, alph = findImage(chunks, 2)
+ if not c then
+ return corrupt("no VP8 / VP8L image chunk")
+ end
+ local bs, err = decodeBitstream(buf, c, if c.id == "VP8 " then alph else nil, o, true)
+ if not bs then
+ return nil, err
+ end
+ if bs.w ~= cw or bs.h ~= ch then
+ return corrupt(string.format("image %d x %d does not match the %d x %d canvas", bs.w, bs.h, cw, ch), c.off)
+ end
+ local img = bs.yuv or Types.Image.new(cw, ch, "rgba8")
+ if bs.rgba then
+ img.pixels = bs.rgba
+ end
+ for k, v in meta do
+ img.meta[k] = v
+ end
+ bs.source.format = "webp"
+ bs.source.bitDepth = 8
+ bs.source.extended = true
+ bs.source.flags = flags
+ img.meta.source = bs.source
+ return img, nil
+ end
+
+ -- animation: ANIM then ANMF frames
+ local bg, loops = 0, 0
+ local haveAnim = false
+ local frames: { Anim.Frame } = {}
+ local sources: { any } = {}
+ local delays: { number } = {}
+ local wantAll = o.frames ~= false
+ for i = 2, #chunks do
+ local c = chunks[i]
+ if c.id == "ANIM" then
+ if c.size < 6 then
+ return nil, Err.new(Err.TRUNCATED, "ANIM chunk too small", c.off)
+ end
+ bg = buffer.readu32(buf, c.off)
+ loops = buffer.readu16(buf, c.off + 4)
+ haveAnim = true
+ elseif c.id == "ANMF" then
+ if not haveAnim then
+ return corrupt("ANMF before ANIM", c.off)
+ end
+ if c.size < 16 then
+ return nil, Err.new(Err.TRUNCATED, "ANMF chunk too small", c.off)
+ end
+ local fx = u24(buf, c.off) * 2
+ local fy = u24(buf, c.off + 3) * 2
+ local fw = u24(buf, c.off + 6) + 1
+ local fh = u24(buf, c.off + 9) + 1
+ local dur = u24(buf, c.off + 12)
+ local fl = readu8(buf, c.off + 15)
+ if fx + fw > cw or fy + fh > ch then
+ return corrupt("frame " .. (#frames + 1) .. " lies outside the canvas", c.off)
+ end
+ local sub, serr = subChunks(file, c)
+ if not sub then
+ return nil, serr
+ end
+ local img, alph = findImage(sub, 1)
+ if not img then
+ return corrupt("frame " .. (#frames + 1) .. " has no image data", c.off)
+ end
+ local bs, err = decodeBitstream(buf, img, if img.id == "VP8 " then alph else nil, o, false)
+ if not bs then
+ return nil, err
+ end
+ if bs.w ~= fw or bs.h ~= fh then
+ return corrupt(string.format("frame %d: image %d x %d does not match its ANMF size %d x %d", #frames + 1, bs.w, bs.h, fw, fh), c.off)
+ end
+ table.insert(frames, {
+ rgba = bs.rgba :: buffer,
+ x = fx,
+ y = fy,
+ w = fw,
+ h = fh,
+ blend = bit32.band(fl, 2) == 0,
+ disposeBg = bit32.band(fl, 1) == 1,
+ hasAlpha = bs.hasAlpha,
+ })
+ bs.source.hasAlpha = bs.hasAlpha
+ table.insert(sources, bs.source)
+ table.insert(delays, dur)
+ if not wantAll then
+ break
+ end
+ end
+ end
+ if #frames == 0 then
+ return corrupt("animation without frames")
+ end
+ local canvases = Anim.coalesce(cw, ch, frames)
+ local img = Types.Image.new(cw, ch, "rgba8")
+ img.pixels = canvases[1]
+ img.loops = loops
+ for k, v in meta do
+ img.meta[k] = v
+ end
+ img.meta.background = { bit32.band(bit32.rshift(bg, 16), 255), bit32.band(bit32.rshift(bg, 8), 255), bit32.band(bg, 255), bit32.rshift(bg, 24) }
+ img.meta.source = { format = "webp", bitDepth = 8, extended = true, flags = flags, animated = true, codec = sources[1].codec, lossless = sources[1].lossless }
+ if wantAll then
+ local list: { Types.Frame } = {}
+ for i, f in frames do
+ local fi: Types.Image
+ if o.coalesce then
+ fi = Types.Image.new(cw, ch, "rgba8")
+ fi.pixels = canvases[i]
+ else
+ fi = Types.Image.new(f.w, f.h, "rgba8")
+ fi.pixels = f.rgba
+ end
+ fi.meta.source = sources[i]
+ fi.meta.duration = delays[i]
+ list[i] = {
+ image = fi,
+ delay = delays[i] / 1000,
+ x = if o.coalesce then 0 else f.x,
+ y = if o.coalesce then 0 else f.y,
+ dispose = if not o.coalesce and f.disposeBg then "background" else "none",
+ blend = if not o.coalesce and f.blend then "over" else "source",
+ }
+ end
+ img.frames = list
+ end
+ return img, nil
+end
+
+-- info(r) -> { width, height, animated, alpha, lossless, frames? } from the headers only | nil, Err
+function Webp.info(r: Bytes.Reader): (any, Err.Err?)
+ local chunks, cerr = readChunks(r)
+ if not chunks then
+ return nil, cerr
+ end
+ local first = chunks[1]
+ if not first then
+ return corrupt("no chunks")
+ end
+ local buf = r.buf
+ if first.id == "VP8X" and first.size >= 10 then
+ local flags = readu8(buf, first.off)
+ local n = 0
+ for _, c in chunks do
+ if c.id == "ANMF" then
+ n += 1
+ end
+ end
+ return {
+ width = u24(buf, first.off + 4) + 1,
+ height = u24(buf, first.off + 7) + 1,
+ animated = bit32.band(flags, FLAG_ANIM) ~= 0,
+ alpha = bit32.band(flags, FLAG_ALPHA) ~= 0,
+ frames = if n > 0 then n else 1,
+ }, nil
+ elseif first.id == "VP8L" then
+ local i, err = Vp8L.info(buf, first.off, first.size)
+ if not i then
+ return nil, err
+ end
+ return { width = i.width, height = i.height, animated = false, alpha = i.alpha, lossless = true, frames = 1 }, nil
+ elseif first.id == "VP8 " then
+ local h, err = Vp8.info(buf, first.off, first.size)
+ if not h then
+ return nil, err
+ end
+ return { width = h.width, height = h.height, animated = false, alpha = false, lossless = false, frames = 1 }, nil
+ end
+ return corrupt("the first chunk is '" .. first.id .. "', not VP8, VP8L or VP8X")
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+local function hasAlpha(px: buffer, n: number): boolean
+ for i = 0, n - 1 do
+ if readu8(px, i * 4 + 3) ~= 255 then
+ return true
+ end
+ end
+ return false
+end
+
+local function validImage(img: any): boolean
+ return type(img) == "table" and img.format == "rgba8" and type(img.pixels) == "buffer" and type(img.width) == "number" and type(img.height) == "number" and img.width >= 1 and img.height >= 1 and img.width <= 16384 and img.height <= 16384 and img.width % 1 == 0 and img.height % 1 == 0 and buffer.len(img.pixels) >= img.width * img.height * 4
+end
+
+local function vp8x(flags: number, w: number, h: number): buffer
+ local b = Bytes.writer(10)
+ b:u8(flags)
+ b:u24le(0)
+ b:u24le(w - 1)
+ b:u24le(h - 1)
+ return b:finish()
+end
+
+local function metaChunk(meta: any, key: string): buffer?
+ local v = meta and meta[key]
+ if type(v) == "buffer" and buffer.len(v) > 0 then
+ return v
+ elseif type(v) == "string" and #v > 0 then
+ return buffer.fromstring(v)
+ end
+ return nil
+end
+
+function Webp.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
+ local o: EncodeOptions = opts or {}
+ if o.lossless == false then
+ return nil, Err.new(Err.UNSUPPORTED, "lossy WebP encoding is not supported (use lossless)")
+ end
+ if not validImage(img) then
+ return nil, Err.new(Err.ARG, "needs an rgba8 Image (1..16384 pixels a side)")
+ end
+ local effort = o.effort or 5
+ if type(effort) ~= "number" or effort < 0 or effort > 9 then
+ return nil, Err.new(Err.ARG, "effort must be 0..9")
+ end
+ local vopts: Vp8L.EncodeOptions = { effort = effort, exact = o.exact }
+ local w, h = img.width, img.height
+ local icc, exif, xmp = metaChunk(img.meta, "icc"), metaChunk(img.meta, "exif"), metaChunk(img.meta, "xmp")
+ local frames = img.frames
+ local body = Riff.writer("WEBP", { rf64 = false })
+
+ if not frames or #frames == 0 then
+ local bits, err = Vp8L.encode(img.pixels, w, h, vopts)
+ if not bits then
+ return nil, err
+ end
+ if icc or exif or xmp then
+ local flags = (if icc then FLAG_ICC else 0) + (if exif then FLAG_EXIF else 0) + (if xmp then FLAG_XMP else 0)
+ if hasAlpha(img.pixels, w * h) then
+ flags += FLAG_ALPHA
+ end
+ body:chunk("VP8X", vp8x(flags, w, h))
+ if icc then
+ body:chunk("ICCP", icc)
+ end
+ body:chunk("VP8L", bits)
+ if exif then
+ body:chunk("EXIF", exif)
+ end
+ if xmp then
+ body:chunk("XMP ", xmp)
+ end
+ else
+ body:chunk("VP8L", bits)
+ end
+ return body:finish()
+ end
+
+ -- animation: frames as they are when WebP can store them (even offsets, dispose none / background), else every
+ -- frame flattened to a full canvas
+ local list: { Anim.Frame } = {}
+ local direct = true
+ for i, f in frames do
+ if type(f) ~= "table" or not validImage(f.image) then
+ return nil, Err.new(Err.ARG, "frame " .. i .. ": needs an rgba8 image")
+ end
+ local fx, fy = f.x or 0, f.y or 0
+ local fw, fh = f.image.width, f.image.height
+ if type(fx) ~= "number" or type(fy) ~= "number" or fx < 0 or fy < 0 or fx % 1 ~= 0 or fy % 1 ~= 0 or fx + fw > w or fy + fh > h then
+ return nil, Err.new(Err.ARG, "frame " .. i .. ": rectangle outside the canvas")
+ end
+ local dispose = f.dispose or "none"
+ if dispose ~= "none" and dispose ~= "background" and dispose ~= "previous" then
+ return nil, Err.new(Err.ARG, "frame " .. i .. ": bad dispose " .. tostring(dispose))
+ end
+ if dispose == "previous" or fx % 2 == 1 or fy % 2 == 1 then
+ direct = false
+ end
+ table.insert(list, {
+ rgba = f.image.pixels,
+ x = fx,
+ y = fy,
+ w = fw,
+ h = fh,
+ blend = f.blend == "over",
+ disposeBg = dispose == "background",
+ disposePrev = dispose == "previous",
+ hasAlpha = true,
+ })
+ end
+ if not direct then
+ local canvases = Anim.composite(w, h, list)
+ for i, c in canvases do
+ list[i] = { rgba = c, x = 0, y = 0, w = w, h = h, blend = false, disposeBg = false, hasAlpha = true }
+ end
+ end
+ local anyAlpha = false
+ for _, f in list do
+ if hasAlpha(f.rgba, f.w * f.h) then
+ anyAlpha = true
+ break
+ end
+ end
+ local flags = FLAG_ANIM + (if anyAlpha then FLAG_ALPHA else 0) + (if icc then FLAG_ICC else 0) + (if exif then FLAG_EXIF else 0) + (if xmp then FLAG_XMP else 0)
+ body:chunk("VP8X", vp8x(flags, w, h))
+ if icc then
+ body:chunk("ICCP", icc)
+ end
+ local loops = o.loops or img.loops or 0
+ if type(loops) ~= "number" or loops < 0 or loops > 65535 then
+ return nil, Err.new(Err.ARG, "loops must be 0..65535")
+ end
+ local bgc = o.background or (img.meta and img.meta.background) or { 0, 0, 0, 0 }
+ if type(bgc) ~= "table" then
+ return nil, Err.new(Err.ARG, "background must be { r, g, b, a }")
+ end
+ for k = 1, 4 do
+ local v = bgc[k]
+ if v ~= nil and (type(v) ~= "number" or v < 0 or v > 255 or v % 1 ~= 0) then
+ return nil, Err.new(Err.ARG, "background must be { r, g, b, a } with 0..255 integers")
+ end
+ end
+ local anim = buffer.create(6)
+ -- the background colour is stored as B, G, R, A
+ buffer.writeu8(anim, 0, bgc[3] or 0)
+ buffer.writeu8(anim, 1, bgc[2] or 0)
+ buffer.writeu8(anim, 2, bgc[1] or 0)
+ buffer.writeu8(anim, 3, bgc[4] or 0)
+ buffer.writeu16(anim, 4, loops)
+ body:chunk("ANIM", anim)
+ for i, f in list do
+ local bits, err = Vp8L.encode(f.rgba, f.w, f.h, vopts)
+ if not bits then
+ return nil, err
+ end
+ local delay = frames[i].delay
+ local ms = if type(delay) == "number" and delay == delay then math.clamp(math.floor(delay * 1000 + 0.5), 0, 0xffffff) else 100
+ local hdr = Bytes.writer(16 + buffer.len(bits) + 9)
+ hdr:u24le(f.x // 2)
+ hdr:u24le(f.y // 2)
+ hdr:u24le(f.w - 1)
+ hdr:u24le(f.h - 1)
+ hdr:u24le(ms)
+ hdr:u8((if f.blend then 0 else 2) + (if f.disposeBg then 1 else 0))
+ local nb = buffer.len(bits)
+ hdr:string("VP8L")
+ hdr:u32le(nb)
+ hdr:bytes(bits)
+ if nb % 2 == 1 then
+ hdr:u8(0)
+ end
+ body:chunk("ANMF", hdr.buf, 0, hdr:tell())
+ end
+ if exif then
+ body:chunk("EXIF", exif)
+ end
+ if xmp then
+ body:chunk("XMP ", xmp)
+ end
+ return body:finish()
+end
+
+-- ------------------------------------------------------------------------------------------------ extras
+-- coalesce(img) -> the full composited canvases of a decoded animation's frames ({ buffer }, rgba8), the way
+-- WebPAnimDecoder composites them (nil for a still image or frames that do not fit the canvas)
+function Webp.coalesce(img: Types.Image): { buffer }?
+ if type(img) ~= "table" or type(img.frames) ~= "table" or type(img.width) ~= "number" or type(img.height) ~= "number" then
+ return nil
+ end
+ local list: { Anim.Frame } = {}
+ for _, f in img.frames :: { Types.Frame } do
+ if type(f) ~= "table" or not validImage(f.image) or type(f.x) ~= "number" or type(f.y) ~= "number" or f.x < 0 or f.y < 0 or f.x % 1 ~= 0 or f.y % 1 ~= 0 or f.x + f.image.width > img.width or f.y + f.image.height > img.height then
+ return nil
+ end
+ table.insert(list, {
+ rgba = f.image.pixels,
+ x = f.x,
+ y = f.y,
+ w = f.image.width,
+ h = f.image.height,
+ blend = f.blend == "over",
+ disposeBg = f.dispose == "background",
+ hasAlpha = not (f.image.meta.source and f.image.meta.source.hasAlpha == false),
+ })
+ end
+ return Anim.coalesce(img.width, img.height, list)
+end
+
+return Webp
diff --git a/src/Formats/init.luau b/src/Formats/init.luau
index 29090f1..19fd6c7 100644
--- a/src/Formats/init.luau
+++ b/src/Formats/init.luau
@@ -161,9 +161,118 @@ local function drain(dec: any): any
return a
end
+-- siblings(path) -> resolve(uri): reads files relative to path's directory (no absolute paths, no "..", no URLs)
+local function siblings(path: string): (uri: string) -> buffer?
+ local dir = string.match(path, "^(.*[/\\])") or ""
+ return function(uri: string): buffer?
+ if type(uri) ~= "string" or uri == "" or string.find(uri, "^%a[%w+.-]*:") or string.sub(uri, 1, 1) == "/" then
+ return nil
+ end
+ local u = string.gsub(uri, "%%(%x%x)", function(h: string): string
+ return string.char(tonumber(h, 16) :: number)
+ end)
+ for part in string.gmatch(u, "[^/\\]+") do
+ if part == ".." then
+ return nil
+ end
+ end
+ local b = host.readFile(dir .. u)
+ return b
+ end
+end
+
-- ------------------------------------------------------------------------------------------------ API
export type Options = { [string]: any } -- format (name or extension), category, path, data, name, + format options
+local load: (src: any, opts: Options?) -> (any, Err.Err?)
+
+-- bitmap fonts (font/bmfont) name their page images: attach a lazy loader, opts.loadPage(file, page) -> Image | buffer
+-- | string, else the files next to the descriptor on hosts with a file system
+local function pageLoader(value: any, name: string?, o: Options)
+ if type(value) ~= "table" or value.kind ~= "font" or type(value.meta) ~= "table" or type(value.meta.pageFiles) ~= "table" then
+ return
+ end
+ local user = o.loadPage
+ if value.pages or (value.meta.pageLoader and type(user) ~= "function") then
+ return
+ end
+ local dir = if name then string.match(name, "^(.*[/\\])") or "" else nil
+ if type(user) ~= "function" and not (dir and host.hasFiles) then
+ return
+ end
+ value.meta.pageLoader = function(file: string, page: number): (any, Err.Err?)
+ local src: any
+ if type(user) == "function" then
+ src = user(file, page)
+ else
+ src = (dir :: string) .. file
+ end
+ if type(src) == "table" then
+ return src -- already an Image
+ end
+ if src == nil then
+ return nil, Err.new(Err.IO, "no data for page " .. file)
+ end
+ return load(src, { category = "image", name = file, path = type(user) ~= "function" })
+ end
+end
+
+-- single-stream archives (gzip / zst / xz / bz2 / br: meta.stream) whose one entry sniffs as another archive (a
+-- .tar.gz) load as that inner archive, with meta.compression = the outer format. opts.unwrap = false keeps the outer
+-- one; an explicit opts.format also does.
+local function unwrap(value: any, formatName: string, o: Options): any
+ if o.unwrap == false or o.format ~= nil or (o._depth or 0) >= 3 then
+ return value
+ end
+ if type(value) ~= "table" or value.kind ~= "archive" or type(value.meta) ~= "table" or not value.meta.stream then
+ return value
+ end
+ local ok, list = pcall(value.list, value)
+ if not ok or type(list) ~= "table" or #list ~= 1 then
+ return value
+ end
+ local rok, inner = pcall(value.read, value, list[1].name)
+ if not rok or type(inner) ~= "buffer" then
+ return value
+ end
+ local e = detect(inner, nil, "archive", nil)
+ if not e then
+ return value
+ end
+ local io = table.clone(o)
+ io.category = "archive"
+ io.name = list[1].name
+ io._depth = (o._depth or 0) + 1
+ local v = load(inner, io)
+ if type(v) ~= "table" or type(v.meta) ~= "table" then
+ return value
+ end
+ v.meta.compression = formatName
+ return v
+end
+
+-- Embedded images (PNG inside ICO, JPEG inside TIFF, thumbnails, textures): a format never requires another format,
+-- so the api hands decoders opts.decodeImage(buf) -> Image | nil, Err and encoders opts.encodeImage(img, format) ->
+-- buffer | nil, Err (unless the caller passed its own). Formats work without them (returning Err.UNSUPPORTED for
+-- the embedded parts) when called directly.
+local function withHooks(o: Options): Options
+ if o.decodeImage ~= nil and o.encodeImage ~= nil then
+ return o
+ end
+ local c = table.clone(o)
+ if c.decodeImage == nil then
+ c.decodeImage = function(b: buffer): (any, Err.Err?)
+ return F.load(b, { category = "image" })
+ end
+ end
+ if c.encodeImage == nil then
+ c.encodeImage = function(img: any, format: string): (any, Err.Err?)
+ return F.save(img, nil, { format = format, category = "image" })
+ end
+ end
+ return c
+end
+
-- load(src, opts?) -> value | nil, Err
function F.load(src: any, opts: Options?): (any, Err.Err?)
local o = opts or {}
@@ -171,6 +280,10 @@ function F.load(src: any, opts: Options?): (any, Err.Err?)
if not buf then
return nil, ierr
end
+ if name and o.name == nil then
+ o = table.clone(o)
+ o.name = name -- formats may use the file name (single-stream archives name their entry after it)
+ end
local entry, derr = detect(buf, name, o.category, o.format)
if not entry then
return nil, derr
@@ -179,9 +292,14 @@ function F.load(src: any, opts: Options?): (any, Err.Err?)
if not m then
return nil, merr
end
+ if o.resolve == nil and name and name == (type(src) == "string" and src or nil) and host.hasFiles then
+ -- files next to the one loaded (OBJ .mtl, glTF .bin / images): opts.resolve(uri) for the decoder
+ o = table.clone(o)
+ o.resolve = siblings(name)
+ end
local value, err
if m.decode then
- local ok, v, e = pcall(m.decode, Bytes.reader(buf), o)
+ local ok, v, e = pcall(m.decode, Bytes.reader(buf), withHooks(o))
if not ok then
return nil, Err.wrap(Err.new(Err.CORRUPT, "decoder threw: " .. tostring(v)), entry.name)
end
@@ -202,8 +320,10 @@ function F.load(src: any, opts: Options?): (any, Err.Err?)
return nil, Err.wrap(err or Err.new(Err.CORRUPT, "decode failed"), entry.name)
end
tag(value, entry.name)
- return value
+ pageLoader(value, name, o)
+ return unwrap(value, entry.name, o)
end
+load = F.load
-- open(src, opts?) -> a streaming decoder (audio Decoder / VideoDecoder / Demuxer) | nil, Err
function F.open(src: any, opts: Options?): (any, Err.Err?)
@@ -233,8 +353,10 @@ function F.open(src: any, opts: Options?): (any, Err.Err?)
return dec
end
+local encodeTextures: (scene: any) -> Err.Err?
+
-- the writable format for a value: opts.format, the destination's extension, or the source format
-local function encoderFor(value: any, dest: string?, o: Options): (Registry.Entry?, any, Err.Err?)
+local function encoderFor(value: any, dest: string?, o: Options): (Registry.Entry?, any, Err.Err?, string?)
local category = o.category
if category == nil and type(value) == "table" and type(value.kind) == "string" then
category = KIND_CATEGORY[value.kind]
@@ -264,17 +386,50 @@ local function encoderFor(value: any, dest: string?, o: Options): (Registry.Entr
end
return nil, nil, Err.wrap(Err.new(Err.UNSUPPORTED, "read-only format" .. (if alt then "; try " .. alt else "")), entry.name)
end
- return entry, m, nil
+ return entry, m, nil, key
+end
+
+-- scene textures with only a decoded image get PNG bytes before a model writer sees them (writers never encode images)
+function encodeTextures(scene: any): Err.Err?
+ if type(scene.textures) ~= "table" then
+ return nil
+ end
+ for _, tex in scene.textures do
+ if type(tex) == "table" and tex.data == nil and type(tex.image) == "table" and tex.uri == nil then
+ local png, err = F.save(tex.image, nil, { format = "png" })
+ if not png then
+ return err
+ end
+ tex.data, tex.mime = png, "image/png"
+ end
+ end
+ return nil
end
-- save(value, dest?, opts?) -> buffer (no dest) | true (written to dest) | nil, Err
function F.save(value: any, dest: string?, opts: Options?): (any, Err.Err?)
local o = opts or {}
- local entry, m, err = encoderFor(value, dest, o)
+ local entry, m, err, key = encoderFor(value, dest, o)
if not entry then
return nil, err
end
- local ok, buf, e = pcall(m.encode, value, o)
+ -- the encoder sees the format key it was picked by ("glb" vs "gltf"), the destination's name, and (writing a file)
+ -- an opts.files table for the extra files it writes (OBJ .mtl, glTF .bin)
+ o = table.clone(o)
+ o.format = o.format or key
+ if dest then
+ o.name = o.name or string.match(dest, "([^/\\]+)$")
+ if o.files == nil then
+ o.files = {}
+ end
+ end
+ if type(value) == "table" and value.kind == "scene" then
+ local terr = encodeTextures(value)
+ if terr then
+ return nil, terr
+ end
+ end
+ local ok, buf, e = pcall(m.encode, value, withHooks(o))
if not ok then
return nil, Err.wrap(Err.new(Err.ARG, "encoder threw: " .. tostring(buf)), entry.name)
end
@@ -286,6 +441,15 @@ function F.save(value: any, dest: string?, opts: Options?): (any, Err.Err?)
if not wok then
return nil, werr
end
+ if type(o.files) == "table" and o.files ~= (opts and opts.files) then
+ local dir = string.match(dest, "^(.*[/\\])") or ""
+ for fname, data in o.files do
+ local fok, ferr = host.writeFile(dir .. fname, if type(data) == "string" then buffer.fromstring(data) else data)
+ if not fok then
+ return nil, ferr
+ end
+ end
+ end
return true
end
return buf
@@ -375,4 +539,33 @@ for category in Types.CATEGORIES do
end
F.data.null = Types.null
+-- F.model.loadTextures(scene, opts?) -> scene, { [index]: Err }: decodes each texture's encoded bytes (texture.data, or
+-- texture.uri through opts.resolve) into texture.image with F.image.load. Model formats never decode images
+-- themselves (a format does not require another format); this is the lazy step at the api layer. Textures whose
+-- image format is missing or broken keep image = nil and report an Err.
+F.model.loadTextures = function(scene: any, opts: Options?): (any, { [number]: Err.Err })
+ local errs: { [number]: Err.Err } = {}
+ if type(scene) ~= "table" or type(scene.textures) ~= "table" then
+ return scene, errs
+ end
+ local resolve = opts and opts.resolve
+ for i, tex in scene.textures do
+ if type(tex) == "table" and tex.image == nil then
+ local data = tex.data
+ if data == nil and tex.uri and resolve then
+ data = resolve(tex.uri)
+ end
+ if data ~= nil then
+ local img, err = F.load(data, { category = "image", name = tex.uri, data = true })
+ if img then
+ tex.image = img
+ elseif err then
+ errs[i] = err
+ end
+ end
+ end
+ end
+ return scene, errs
+end
+
return F
diff --git a/src/Formats/layered/aseprite/init.luau b/src/Formats/layered/aseprite/init.luau
new file mode 100644
index 0000000..6799137
--- /dev/null
+++ b/src/Formats/layered/aseprite/init.luau
@@ -0,0 +1,754 @@
+--!strict
+-- layered/aseprite: Aseprite .ase / .aseprite sprites (aseprite docs/ase-file-specs.md, v1.3). Supports: RGBA,
+-- grayscale and indexed sprites (to rgba8; the transparent index is clear except on background layers); every
+-- frame (duration -> delay); layers (normal and group, child levels -> a tree; visibility, blend mode, opacity,
+-- flags, UUIDs skipped; a group of normal blend at full opacity is "passThrough"); cels (raw, zlib-compressed, linked: a linked cel shares the Image of the frame it points to
+-- and records `link`), cel opacity (-> the leaf's fillOpacity), z-index; the palette (new 0x2019 chunk and the old
+-- 0x0004 / 0x0011 ones; entry names), tags (meta.tags, frames 1-based), user data text / colour on layers, cels and
+-- tags, the pixel ratio and grid. A Layered value: layers = frame 1's tree, frames[i] = { layers = frame i's tree,
+-- delay }.
+-- Encode: RGBA (or grayscale / indexed when opts.depth or meta.colorDepth asks and the pixels fit), one layer chunk
+-- per node of frame 1's tree, zlib cels, linked cels where a frame reuses an earlier frame's Image at the same place,
+-- palette, tags.
+-- Not supported: tilemap layers / tilesets (skipped: meta.skipped counts them), slices, external files, colour
+-- profiles (sRGB assumed).
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Types = require("@formats/Types")
+local Deflate = require("@formats/codecs/Deflate")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Aseprite = {
+ name = "aseprite",
+ category = "layered",
+ extensions = { "aseprite", "ase" },
+ mime = { "image/x-aseprite" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/Deflate" },
+ caps = { decode = true, encode = true, layers = true, groups = true, animation = true, depths = { 8, 16, 32 } },
+}
+
+export type DecodeOptions = {
+ maxPixels: number?, -- refuse sprites / cels larger than this (default 2^26)
+ maxFrames: number?, -- default 65535
+}
+export type EncodeOptions = {
+ depth: number?, -- 32 (RGBA), 16 (grayscale) or 8 (indexed, with layered.meta.palette); default meta.colorDepth if
+ -- the pixels fit it, else 32
+ level: number?, -- zlib level for the cels (default 6)
+}
+
+-- ------------------------------------------------------------------------------------------------ constants
+local BLENDS = { [0] = "normal", "multiply", "screen", "overlay", "darken", "lighten", "colorDodge", "colorBurn", "hardLight", "softLight", "difference", "exclusion", "hue", "saturation", "color", "luminosity", "linearDodge", "subtract", "divide" }
+local BLEND_IDS: { [string]: number } = {}
+for k, v in BLENDS do
+ BLEND_IDS[v] = k
+end
+BLEND_IDS.add = 16
+BLEND_IDS.passThrough = 0
+local DIRECTIONS = { [0] = "forward", "reverse", "pingpong", "pingpongReverse" }
+local DIRECTION_IDS = { forward = 0, reverse = 1, pingpong = 2, pingpongReverse = 3 }
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Aseprite.sniff(r: Bytes.Reader): number
+ if r:peekU8(4) == 0xE0 and r:peekU8(5) == 0xA5 then
+ local d = r:peekU8(12)
+ if (d == 32 or d == 16 or d == 8) and r:peekU8(13) == 0 then
+ return 1
+ end
+ return 0.5
+ end
+ return 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+local function str(r: Bytes.Reader): string
+ return r:string(r:u16le())
+end
+
+-- cel pixels (depth bytes per pixel) -> rgba8
+local function toRGBA(src: buffer, so: number, n: number, depth: number, palette: buffer, transparent: number, background: boolean): buffer
+ local out = buffer.create(n * 4)
+ if depth == 32 then
+ buffer.copy(out, 0, src, so, n * 4)
+ elseif depth == 16 then
+ for i = 0, n - 1 do
+ local v, a = buffer.readu8(src, so + i * 2), buffer.readu8(src, so + i * 2 + 1)
+ buffer.writeu32(out, i * 4, v + v * 256 + v * 65536 + a * 16777216)
+ end
+ else
+ for i = 0, n - 1 do
+ local k = buffer.readu8(src, so + i)
+ local c = buffer.readu32(palette, k * 4)
+ if k == transparent and not background then
+ c = 0
+ end
+ buffer.writeu32(out, i * 4, c)
+ end
+ end
+ return out
+end
+
+type LayerInfo = { name: string, flags: number, type: number, level: number, blend: number, opacity: number, userData: any? }
+
+function Aseprite.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Layered?, Err.Err?)
+ local maxPixels = opts and opts.maxPixels or 2 ^ 26
+ local maxFrames = opts and opts.maxFrames or 65535
+ if r:size() < 128 then
+ return nil, Err.new(Err.TRUNCATED, "header needs 128 bytes", r.pos)
+ end
+ r:skip(4)
+ if r:u16le() ~= 0xA5E0 then
+ return nil, Err.new(Err.CORRUPT, "bad magic", r.pos - 2)
+ end
+ local nframes, w, h, depth = r:u16le(), r:u16le(), r:u16le(), r:u16le()
+ local hflags = r:u32le()
+ r:skip(2 + 8)
+ local transparent = r:u8()
+ r:skip(3)
+ local ncolors = r:u16le()
+ local pw, ph = r:u8(), r:u8()
+ local gx, gy, gw, gh = r:i16le(), r:i16le(), r:u16le(), r:u16le()
+ r:seek(128)
+ if depth ~= 32 and depth ~= 16 and depth ~= 8 then
+ return nil, Err.new(Err.CORRUPT, "bad colour depth " .. depth)
+ end
+ if w < 1 or h < 1 then
+ return nil, Err.new(Err.CORRUPT, "bad size")
+ end
+ if w * h > maxPixels then
+ return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the pixel limit", w, h))
+ end
+ if nframes > maxFrames then
+ return nil, Err.new(Err.LIMIT, "too many frames")
+ end
+ local bpp = depth // 8
+ local palette = buffer.create(1024)
+ local palList: { { number } } = {}
+ local palNames: { [number]: string } = {}
+ local infos: { LayerInfo } = {}
+ local tags: { any } = {}
+ local frames: { { cels: { [number]: any }, delay: number } } = {}
+ local skipped = 0
+ local lastUser: any = nil -- the object the next user data chunk belongs to
+ local tagUser = 0 -- tags waiting for their user data chunks
+ for fi = 1, nframes do
+ local fstart = r.pos
+ local fbytes = r:u32le()
+ local fmagic = r:u16le()
+ local oldChunks = r:u16le()
+ local duration = r:u16le()
+ r:skip(2)
+ local newChunks = r:u32le()
+ if r.err then
+ return nil, r.err
+ end
+ if fmagic ~= 0xF1FA then
+ return nil, Err.new(Err.CORRUPT, "frame " .. fi .. ": bad magic", fstart + 4)
+ end
+ if fbytes < 16 or fstart + fbytes > r.limit then
+ return nil, Err.new(Err.TRUNCATED, "frame " .. fi .. " runs past the end", fstart)
+ end
+ local nchunks = if newChunks ~= 0 then newChunks else oldChunks
+ local frame = { cels = {}, delay = duration / 1000 }
+ frames[fi] = frame
+ local fr = Bytes.reader(r.buf, r.pos, fstart + fbytes - r.pos)
+ for _ = 1, nchunks do
+ if fr:remaining() < 6 then
+ break
+ end
+ local cstart = fr.pos
+ local csize = fr:u32le()
+ local ctype = fr:u16le()
+ if csize < 6 or cstart + csize > fr.limit then
+ return nil, Err.new(Err.CORRUPT, string.format("frame %d: chunk 0x%04x size %d", fi, ctype, csize), cstart)
+ end
+ local c = Bytes.reader(fr.buf, cstart + 6, csize - 6)
+ fr.pos = cstart + csize
+ if ctype == 0x2004 then
+ local info: LayerInfo = { flags = c:u16le(), type = c:u16le(), level = c:u16le(), name = "", blend = 0, opacity = 255 }
+ c:skip(4)
+ info.blend = c:u16le()
+ info.opacity = c:u8()
+ c:skip(3)
+ info.name = str(c)
+ if c.err then
+ return nil, c.err
+ end
+ if info.type == 2 then
+ skipped += 1
+ end
+ table.insert(infos, info)
+ lastUser = info
+ elseif ctype == 0x2005 then
+ local li = c:u16le()
+ local x, y = c:i16le(), c:i16le()
+ local op = c:u8()
+ local ctyp = c:u16le()
+ local z = c:i16le()
+ c:skip(5)
+ if c.err then
+ return nil, c.err
+ end
+ local cel: any = { x = x, y = y, opacity = op, z = z }
+ if ctyp == 0 or ctyp == 2 then
+ local cw, ch = c:u16le(), c:u16le()
+ if c.err then
+ return nil, c.err
+ end
+ if cw * ch > maxPixels then
+ return nil, Err.new(Err.LIMIT, "cel over the pixel limit")
+ end
+ local n = cw * ch
+ local raw: buffer, ro: number
+ if ctyp == 0 then
+ if not c:need(n * bpp) then
+ return nil, c.err
+ end
+ raw, ro = c.buf, c.pos
+ else
+ local z2, zerr = Deflate.zlib(c.buf, c.pos, c.limit - c.pos, n * bpp)
+ if not z2 then
+ -- some writers leave padding after the stream: inflate without the exact size
+ local loose = Deflate.zlib(c.buf, c.pos, c.limit - c.pos)
+ if not loose or buffer.len(loose) < n * bpp then
+ return nil, Err.new(Err.CORRUPT, "frame " .. fi .. ": cel data: " .. tostring(zerr and zerr.message), c.pos)
+ end
+ z2 = loose
+ end
+ raw, ro = z2 :: buffer, 0
+ end
+ cel.w, cel.h, cel.raw, cel.ro = cw, ch, raw, ro
+ elseif ctyp == 1 then
+ cel.link = c:u16le() + 1
+ else
+ cel.skip = true -- tilemap cel
+ end
+ frame.cels[li + 1] = cel
+ lastUser = cel
+ elseif ctype == 0x2018 then
+ local n = c:u16le()
+ c:skip(8)
+ tagUser = 0
+ for _ = 1, n do
+ local from, to = c:u16le(), c:u16le()
+ local dir = c:u8()
+ local rep = c:u16le()
+ c:skip(6)
+ local cr, cg, cb = c:u8(), c:u8(), c:u8()
+ c:skip(1)
+ local name = str(c)
+ if c.err then
+ return nil, c.err
+ end
+ table.insert(tags, { name = name, from = from + 1, to = to + 1, direction = DIRECTIONS[dir] or "forward", ["repeat"] = rep, color = { cr, cg, cb } })
+ tagUser += 1
+ end
+ lastUser = nil
+ elseif ctype == 0x2019 then
+ local size = c:u32le()
+ local first, last = c:u32le(), c:u32le()
+ c:skip(8)
+ if first > last or last > 255 or size > 256 then
+ return nil, Err.new(Err.CORRUPT, "bad palette range", cstart)
+ end
+ for k = first, last do
+ local f = c:u16le()
+ local cr, cg, cb, ca = c:u8(), c:u8(), c:u8(), c:u8()
+ if bit32.band(f, 1) ~= 0 then
+ palNames[k + 1] = str(c)
+ end
+ buffer.writeu32(palette, k * 4, cr + cg * 256 + cb * 65536 + ca * 16777216)
+ palList[k + 1] = { cr, cg, cb, ca }
+ end
+ for k = #palList + 1, size do
+ palList[k] = { 0, 0, 0, 255 }
+ end
+ if c.err then
+ return nil, c.err
+ end
+ elseif (ctype == 0x0004 or ctype == 0x0011) and #palList == 0 then
+ -- old palettes (used when there is no 0x2019 chunk): packets of (skip, count) entries of RGB
+ local packets = c:u16le()
+ local k = 0
+ for _ = 1, packets do
+ k += c:u8()
+ local n = c:u8()
+ if n == 0 then
+ n = 256
+ end
+ for _ = 1, n do
+ local cr, cg, cb = c:u8(), c:u8(), c:u8()
+ if ctype == 0x0011 then
+ cr, cg, cb = cr * 255 // 63, cg * 255 // 63, cb * 255 // 63
+ end
+ if k < 256 then
+ buffer.writeu32(palette, k * 4, cr + cg * 256 + cb * 65536 + 0xFF000000)
+ end
+ k += 1
+ end
+ end
+ if c.err then
+ return nil, c.err
+ end
+ for i = 0, math.min(k, 256) - 1 do
+ local v = buffer.readu32(palette, i * 4)
+ palList[i + 1] = { v % 256, v // 256 % 256, v // 65536 % 256, 255 }
+ end
+ palList = table.move(palList, 1, math.min(k, 256), 1, {})
+ elseif ctype == 0x2020 then
+ local f = c:u32le()
+ local ud: any = {}
+ if bit32.band(f, 1) ~= 0 then
+ ud.text = str(c)
+ end
+ if bit32.band(f, 2) ~= 0 then
+ ud.color = { c:u8(), c:u8(), c:u8(), c:u8() }
+ end
+ if not c.err then
+ if tagUser > 0 then
+ -- after a tags chunk, user data chunks follow for each tag in order
+ local t = tags[#tags - tagUser + 1]
+ if t then
+ t.userData = ud
+ end
+ tagUser -= 1
+ elseif lastUser then
+ lastUser.userData = ud
+ end
+ end
+ end
+ -- others (colour profile, slices, tilesets, external files, cel extras, masks, paths) are skipped
+ end
+ r.pos = fstart + fbytes
+ end
+ local _ = ncolors
+ -- the layer tree of one frame
+ local function build(fi: number): { Types.Layer }
+ local root: { Types.Layer } = {}
+ local stack: { { Types.Layer } } = { root } -- stack[level + 1] = the children list at that level
+ for li, info in infos do
+ local level = math.min(info.level, #stack - 1)
+ local list = stack[level + 1]
+ local l: any = {
+ name = info.name,
+ x = 0,
+ y = 0,
+ opacity = if bit32.band(hflags, 1) ~= 0 or info.type ~= 0 then info.opacity / 255 else 1,
+ blend = BLENDS[info.blend] or "normal",
+ visible = bit32.band(info.flags, 1) ~= 0,
+ flags = info.flags,
+ }
+ if info.userData then
+ l.userData = info.userData
+ end
+ if info.type == 1 then
+ l.image = Types.Image.new(0, 0)
+ l.children = {}
+ -- Aseprite renders a group straight onto the backdrop unless it has its own blend mode / opacity (then
+ -- into a buffer of its own): pass-through vs isolated
+ if bit32.band(hflags, 2) == 0 or (info.blend == 0 and info.opacity == 255) then
+ l.blend = "passThrough"
+ l.opacity = 1
+ end
+ table.insert(list, l)
+ -- deeper layers go into this group
+ for k = #stack, level + 2, -1 do
+ stack[k] = nil
+ end
+ stack[level + 2] = l.children
+ else
+ for k = #stack, level + 2, -1 do
+ stack[k] = nil
+ end
+ l.image = Types.Image.new(0, 0)
+ if info.type == 2 then
+ l.tilemap = true
+ end
+ local cel = frames[fi].cels[li]
+ local guard = 0
+ while cel and cel.link and guard < 8 do -- follow links (one hop in valid files)
+ l.link = cel.link
+ local target = frames[cel.link]
+ cel = if target then target.cels[li] else nil
+ guard += 1
+ end
+ if cel and cel.image then
+ l.image = cel.image
+ l.x, l.y = cel.x, cel.y
+ if cel.opacity < 255 then
+ l.fillOpacity = cel.opacity / 255
+ end
+ if cel.z ~= 0 then
+ l.zIndex = cel.z
+ end
+ if cel.userData then
+ l.celUserData = cel.userData
+ end
+ end
+ table.insert(list, l)
+ end
+ end
+ return root
+ end
+ -- cel images (shared by linked cels)
+ for _, f in frames do
+ for li, cel in pairs(f.cels) do -- sparse: pairs, not ipairs-style iteration
+ if cel.raw then
+ local info = infos[li]
+ local img = Types.Image.new(cel.w, cel.h)
+ img.pixels = toRGBA(cel.raw, cel.ro, cel.w * cel.h, depth, palette, transparent, info ~= nil and bit32.band(info.flags, 8) ~= 0)
+ cel.image = img
+ cel.raw = nil
+ end
+ end
+ end
+ local layered = Types.Layered.new(w, h)
+ local list = {}
+ for fi = 1, nframes do
+ list[fi] = { layers = build(fi), delay = frames[fi].delay }
+ end
+ if nframes > 0 then
+ layered.layers = list[1].layers
+ end
+ layered.frames = list
+ if #palList > 0 then
+ layered.meta.palette = palList
+ if next(palNames) then
+ layered.meta.paletteNames = palNames
+ end
+ end
+ layered.meta.tags = tags
+ layered.meta.colorDepth = depth
+ layered.meta.transparentIndex = transparent
+ layered.meta.pixelRatio = { if pw == 0 then 1 else pw, if ph == 0 then 1 else ph }
+ layered.meta.grid = { gx, gy, gw, gh }
+ if skipped > 0 then
+ layered.meta.skipped = skipped
+ end
+ layered.meta.source = { format = "aseprite", bitDepth = depth, colorType = if depth == 32 then "rgba" elseif depth == 16 then "graya" else "indexed" }
+ return layered, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+type Node = { layer: any, level: number }
+
+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 v.width >= 0 and v.height >= 0 and v.width < 65536 and v.height < 65536 and buffer.len(v.pixels) >= v.width * v.height * 4
+end
+
+-- the nodes of a tree in file order (a group, then its children one level deeper)
+local function nodes(layers: { any }, level: number, out: { Node }): boolean
+ for _, l in layers do
+ if type(l) ~= "table" or level > 64 then
+ return false
+ end
+ table.insert(out, { layer = l, level = level })
+ if type(l.children) == "table" then
+ if not nodes(l.children, level + 1, out) then
+ return false
+ end
+ end
+ end
+ return true
+end
+
+local function writeStr(w: Bytes.Writer, s: string)
+ local n = math.min(#s, 65535)
+ w:u16le(n)
+ w:string(string.sub(s, 1, n))
+end
+
+function Aseprite.encode(layered: Types.Layered, opts: EncodeOptions?): (buffer?, Err.Err?)
+ if type(layered) ~= "table" or type(layered.layers) ~= "table" or type(layered.width) ~= "number" or type(layered.height) ~= "number" then
+ return nil, Err.new(Err.ARG, "needs a Layered value")
+ end
+ local W, H = math.floor(layered.width), math.floor(layered.height)
+ if W < 1 or H < 1 or W > 65535 or H > 65535 then
+ return nil, Err.new(Err.ARG, "bad sprite size")
+ end
+ local meta: any = if type(layered.meta) == "table" then layered.meta else {}
+ local level = opts and opts.level or 6
+ -- frames: the layered frames, or one frame of the layers
+ local frameList: { any } = if type(layered.frames) == "table" and #layered.frames > 0 then layered.frames else { { layers = layered.layers, delay = 0.1 } }
+ local struct: { Node } = {}
+ if not nodes(frameList[1].layers, 0, struct) then
+ return nil, Err.new(Err.ARG, "bad layer tree")
+ end
+ if #struct > 65535 or #frameList > 65535 then
+ return nil, Err.new(Err.ARG, "too many layers / frames")
+ end
+ local perFrame: { { Node } } = {}
+ for fi, f in frameList do
+ if type(f) ~= "table" or type(f.layers) ~= "table" then
+ return nil, Err.new(Err.ARG, "frame " .. fi .. ": no layers")
+ end
+ local ns: { Node } = {}
+ if not nodes(f.layers, 0, ns) or #ns ~= #struct then
+ return nil, Err.new(Err.ARG, "frame " .. fi .. ": its layer tree differs from frame 1's")
+ end
+ for k, n in ns do
+ if (type(n.layer.children) == "table") ~= (type(struct[k].layer.children) == "table") then
+ return nil, Err.new(Err.ARG, "frame " .. fi .. ": its layer tree differs from frame 1's")
+ end
+ if type(n.layer.children) ~= "table" and not isImage(n.layer.image) then
+ return nil, Err.new(Err.ARG, "frame " .. fi .. ": layer " .. tostring(n.layer.name) .. " needs an rgba8 image")
+ end
+ end
+ perFrame[fi] = ns
+ end
+ -- the colour depth: requested, or the source's when every pixel fits
+ local depth = opts and opts.depth or meta.colorDepth or 32
+ local explicit = opts ~= nil and opts.depth ~= nil
+ if depth ~= 32 and depth ~= 16 and depth ~= 8 then
+ return nil, Err.new(Err.ARG, "depth must be 32, 16 or 8")
+ end
+ local palette: { { number } } = if type(meta.palette) == "table" then meta.palette else {}
+ local transparent = if type(meta.transparentIndex) == "number" then meta.transparentIndex else 0
+ local index: { [number]: number } = {}
+ for k = #palette, 1, -1 do
+ local c = palette[k]
+ if type(c) == "table" then
+ index[(c[1] or 0) + (c[2] or 0) * 256 + (c[3] or 0) * 65536 + (c[4] or 255) * 16777216] = k - 1
+ end
+ end
+ if depth ~= 32 then
+ local fits = depth ~= 8 or #palette > 0
+ for _, ns in perFrame do
+ for _, n in ns do
+ local img = n.layer.image
+ if fits and type(n.layer.children) ~= "table" then
+ local px = img.pixels
+ for i = 0, img.width * img.height - 1 do
+ local v = buffer.readu32(px, i * 4)
+ if depth == 16 then
+ local r, g, b = v % 256, v // 256 % 256, v // 65536 % 256
+ if r ~= g or g ~= b then
+ fits = false
+ break
+ end
+ elseif v // 16777216 ~= 0 and index[v] == nil then
+ fits = false
+ break
+ end
+ end
+ end
+ end
+ end
+ if not fits then
+ if explicit then
+ return nil, Err.new(Err.ARG, "the pixels do not fit depth " .. depth .. (if depth == 8 then " with meta.palette" else ""))
+ end
+ depth = 32
+ end
+ end
+ local bpp = depth // 8
+ local function pixels(n: any): buffer
+ local img = n.layer.image
+ local count = img.width * img.height
+ if depth == 32 then
+ return img.pixels
+ end
+ local out = buffer.create(count * bpp)
+ local px = img.pixels
+ for i = 0, count - 1 do
+ local v = buffer.readu32(px, i * 4)
+ if depth == 16 then
+ buffer.writeu8(out, i * 2, v % 256)
+ buffer.writeu8(out, i * 2 + 1, v // 16777216)
+ else
+ local k = if v // 16777216 == 0 and bit32.band(tonumber(n.layer.flags) or 0, 8) == 0 then transparent else index[v] or transparent
+ buffer.writeu8(out, i, k)
+ end
+ end
+ return out
+ end
+
+ local out = Bytes.writer(65536)
+ -- header (file size patched at the end)
+ out:u32le(0)
+ out:u16le(0xA5E0)
+ out:u16le(#frameList)
+ out:u16le(W)
+ out:u16le(H)
+ out:u16le(depth)
+ out:u32le(3) -- layer opacity and group opacity / blend valid
+ out:u16le(100)
+ out:u32le(0)
+ out:u32le(0)
+ out:u8(if depth == 8 then transparent else 0)
+ out:fill(0, 3)
+ out:u16le(if #palette > 0 and #palette < 256 then #palette else 0)
+ local ratio = if type(meta.pixelRatio) == "table" then meta.pixelRatio else { 1, 1 }
+ out:u8(math.clamp(tonumber(ratio[1]) or 1, 0, 255))
+ out:u8(math.clamp(tonumber(ratio[2]) or 1, 0, 255))
+ local grid = if type(meta.grid) == "table" then meta.grid else { 0, 0, 16, 16 }
+ out:i16le(tonumber(grid[1]) or 0)
+ out:i16le(tonumber(grid[2]) or 0)
+ out:u16le(math.clamp(tonumber(grid[3]) or 16, 0, 65535))
+ out:u16le(math.clamp(tonumber(grid[4]) or 16, 0, 65535))
+ out:fill(0, 84)
+
+ local function chunk(fw: Bytes.Writer, ctype: number, body: Bytes.Writer)
+ local b = body:finish()
+ fw:u32le(buffer.len(b) + 6)
+ fw:u16le(ctype)
+ fw:bytes(b)
+ end
+ local function userData(fw: Bytes.Writer, ud: any): number
+ if type(ud) ~= "table" then
+ return 0
+ end
+ local c = Bytes.writer(64)
+ local f = (if type(ud.text) == "string" then 1 else 0) + (if type(ud.color) == "table" then 2 else 0)
+ c:u32le(f)
+ if type(ud.text) == "string" then
+ writeStr(c, ud.text)
+ end
+ if type(ud.color) == "table" then
+ for k = 1, 4 do
+ c:u8(math.clamp(tonumber(ud.color[k]) or 0, 0, 255))
+ end
+ end
+ chunk(fw, 0x2020, c)
+ return 1
+ end
+ -- where each (layer, frame) cel's image was first written: linked cels
+ local firstAt: { [number]: { [any]: { frame: number, x: number, y: number, fill: number } } } = {}
+ for fi, f in frameList do
+ local fw = Bytes.writer(4096)
+ local count = 0
+ if fi == 1 then
+ -- colour profile: sRGB
+ local cp = Bytes.writer(16)
+ cp:u16le(1)
+ cp:u16le(0)
+ cp:u32le(0)
+ cp:fill(0, 8)
+ chunk(fw, 0x2007, cp)
+ count += 1
+ if #palette > 0 then
+ local p = Bytes.writer(#palette * 6 + 20)
+ local n = math.min(#palette, 256)
+ p:u32le(n)
+ p:u32le(0)
+ p:u32le(n - 1)
+ p:fill(0, 8)
+ local names = if type(meta.paletteNames) == "table" then meta.paletteNames else {}
+ for k = 1, n do
+ local c = palette[k]
+ local nm = names[k]
+ p:u16le(if type(nm) == "string" then 1 else 0)
+ p:u8(c[1] or 0)
+ p:u8(c[2] or 0)
+ p:u8(c[3] or 0)
+ p:u8(c[4] or 255)
+ if type(nm) == "string" then
+ writeStr(p, nm)
+ end
+ end
+ chunk(fw, 0x2019, p)
+ count += 1
+ end
+ for _, n in struct do
+ local l = n.layer
+ local c = Bytes.writer(64)
+ local isGroup = type(l.children) == "table"
+ local flags = tonumber(l.flags) or 3
+ flags = bit32.band(flags, bit32.bnot(1)) + (if l.visible == false then 0 else 1)
+ c:u16le(flags)
+ c:u16le(if isGroup then 1 else 0)
+ c:u16le(n.level)
+ c:u16le(0)
+ c:u16le(0)
+ c:u16le(BLEND_IDS[l.blend] or 0)
+ c:u8(math.clamp(math.floor((tonumber(l.opacity) or 1) * 255 + 0.5), 0, 255))
+ c:fill(0, 3)
+ writeStr(c, tostring(l.name or "Layer"))
+ chunk(fw, 0x2004, c)
+ count += 1
+ count += userData(fw, l.userData)
+ end
+ local tags = if type(meta.tags) == "table" then meta.tags else {}
+ if #tags > 0 then
+ local c = Bytes.writer(64)
+ c:u16le(#tags)
+ c:fill(0, 8)
+ for _, t in tags do
+ c:u16le(math.clamp((tonumber(t.from) or 1) - 1, 0, 65535))
+ c:u16le(math.clamp((tonumber(t.to) or 1) - 1, 0, 65535))
+ c:u8(DIRECTION_IDS[t.direction] or 0)
+ c:u16le(math.clamp(tonumber(t["repeat"]) or 0, 0, 65535))
+ c:fill(0, 6)
+ local col = if type(t.color) == "table" then t.color else { 0, 0, 0 }
+ c:u8(col[1] or 0)
+ c:u8(col[2] or 0)
+ c:u8(col[3] or 0)
+ c:u8(0)
+ writeStr(c, tostring(t.name or "Tag"))
+ end
+ chunk(fw, 0x2018, c)
+ count += 1
+ for _, t in tags do
+ if type(t.userData) == "table" then
+ count += userData(fw, t.userData)
+ else
+ local e = Bytes.writer(4)
+ e:u32le(0)
+ chunk(fw, 0x2020, e)
+ count += 1
+ end
+ end
+ end
+ end
+ for li, n in perFrame[fi] do
+ local l = n.layer
+ if type(l.children) == "table" or l.image.width == 0 or l.image.height == 0 then
+ continue
+ end
+ local x, y = math.floor(tonumber(l.x) or 0), math.floor(tonumber(l.y) or 0)
+ local fill = math.clamp(math.floor((tonumber(l.fillOpacity) or 1) * 255 + 0.5), 0, 255)
+ local c = Bytes.writer(256)
+ c:u16le(li - 1)
+ c:i16le(x)
+ c:i16le(y)
+ c:u8(fill)
+ local seen = firstAt[li] and firstAt[li][l.image]
+ if seen and seen.x == x and seen.y == y and seen.fill == fill then
+ c:u16le(1)
+ c:i16le(tonumber(l.zIndex) or 0)
+ c:fill(0, 5)
+ c:u16le(seen.frame - 1)
+ else
+ c:u16le(2)
+ c:i16le(tonumber(l.zIndex) or 0)
+ c:fill(0, 5)
+ c:u16le(l.image.width)
+ c:u16le(l.image.height)
+ local z = Deflate.zlibCompress(pixels(n), { level = level })
+ if not z then
+ return nil, Err.new(Err.ARG, "cel compression failed")
+ end
+ c:bytes(z)
+ firstAt[li] = firstAt[li] or {}
+ firstAt[li][l.image] = { frame = fi, x = x, y = y, fill = fill }
+ end
+ chunk(fw, 0x2005, c)
+ count += 1
+ count += userData(fw, l.celUserData)
+ end
+ local body = fw:finish()
+ out:u32le(buffer.len(body) + 16)
+ out:u16le(0xF1FA)
+ out:u16le(math.min(count, 0xFFFF))
+ out:u16le(math.clamp(math.floor((tonumber(f.delay) or 0.1) * 1000 + 0.5), 0, 65535))
+ out:u16le(0)
+ out:u32le(count)
+ out:bytes(body)
+ end
+ out:setU32le(0, out:tell())
+ return out:finish(), nil
+end
+
+return Aseprite
diff --git a/src/Formats/layered/psd/Channels.luau b/src/Formats/layered/psd/Channels.luau
new file mode 100644
index 0000000..51ce6de
--- /dev/null
+++ b/src/Formats/layered/psd/Channels.luau
@@ -0,0 +1,394 @@
+--!strict
+--!native
+-- layered/psd/Channels: PSD / PSB channel data. Decodes one channel (raw, PackBits RLE, ZIP, ZIP with prediction) to a
+-- plane of big-endian samples, converts planes to rgba8 for every colour mode, and PackBits-encodes rows for the
+-- writer. Adobe Photoshop File Formats Specification (2016), "Channel image data" / "Image data section".
+-- Never throws: every read is range-checked first; failures return nil, "message".
+local Deflate = require("@formats/codecs/Deflate")
+
+local Channels = {}
+
+local readu8, writeu8, readu16, writeu16, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16, buffer.readu32, buffer.writeu32
+local readf32, writef32, bcreate, bcopy, blen, bfill = buffer.readf32, buffer.writef32, buffer.create, buffer.copy, buffer.len, buffer.fill
+local floor, min, max = math.floor, math.min, math.max
+local byteswap = bit32.byteswap
+
+-- rowBytes(w, depth) -> bytes per row of one channel
+function Channels.rowBytes(w: number, depth: number): number
+ if depth == 1 then
+ return (w + 7) // 8
+ end
+ return w * (depth // 8)
+end
+
+-- packbits(src, p, limit, dst, d, n) -> the source offset after decoding n bytes into dst at d | nil
+local function packbits(src: buffer, p: number, limit: number, dst: buffer, d: number, n: number): number?
+ local e = d + n
+ while d < e do
+ if p >= limit then
+ return nil
+ end
+ local h = readu8(src, p)
+ p += 1
+ if h < 128 then
+ local c = h + 1
+ if p + c > limit or d + c > e then
+ return nil
+ end
+ bcopy(dst, d, src, p, c)
+ p += c
+ d += c
+ elseif h > 128 then
+ local c = 257 - h
+ if p >= limit or d + c > e then
+ return nil
+ end
+ bfill(dst, d, readu8(src, p), c)
+ p += 1
+ d += c
+ end
+ end
+ return p
+end
+
+-- rleCounts(src, p, limit, rows, psb) -> { counts }, offset after them | nil
+function Channels.rleCounts(src: buffer, p: number, limit: number, rows: number, psb: boolean): ({ number }?, number)
+ local size = if psb then 4 else 2
+ if rows < 0 or p + rows * size > limit then
+ return nil, p
+ end
+ local counts = table.create(rows)
+ for i = 1, rows do
+ if psb then
+ counts[i] = byteswap(readu32(src, p))
+ else
+ counts[i] = readu8(src, p) * 256 + readu8(src, p + 1)
+ end
+ p += size
+ end
+ return counts, p
+end
+
+-- rle(src, p, limit, counts, first, rows, rowBytes, dst, d) -> offset after the rows | nil, message
+function Channels.rle(src: buffer, p: number, limit: number, counts: { number }, first: number, rows: number, rowBytes: number, dst: buffer, d: number): (number?, string?)
+ for i = 0, rows - 1 do
+ local c = counts[first + i] or 0
+ if p + c > limit then
+ return nil, "RLE row past the end"
+ end
+ local q = packbits(src, p, p + c, dst, d + i * rowBytes, rowBytes)
+ if q == nil then
+ -- a short or overlong row: keep what decoded, zero the rest (Photoshop is lenient too)
+ return nil, "bad RLE row"
+ end
+ p += c
+ end
+ return p, nil
+end
+
+-- unpredict(plane, w, h, depth): undo ZIP-with-prediction deltas in place
+local function unpredict(plane: buffer, w: number, h: number, depth: number)
+ if depth == 8 then
+ for y = 0, h - 1 do
+ local o = y * w
+ local acc = readu8(plane, o)
+ for x = 1, w - 1 do
+ acc = (acc + readu8(plane, o + x)) % 256
+ writeu8(plane, o + x, acc)
+ end
+ end
+ elseif depth == 16 then
+ for y = 0, h - 1 do
+ local o = y * w * 2
+ local acc = readu8(plane, o) * 256 + readu8(plane, o + 1)
+ for x = 1, w - 1 do
+ local q = o + x * 2
+ acc = (acc + readu8(plane, q) * 256 + readu8(plane, q + 1)) % 65536
+ writeu8(plane, q, acc // 256)
+ writeu8(plane, q + 1, acc % 256)
+ end
+ end
+ elseif depth == 32 then
+ -- byte deltas over the row, then the row is 4 byte planes (all high bytes first)
+ local rb = w * 4
+ local tmp = bcreate(rb)
+ for y = 0, h - 1 do
+ local o = y * rb
+ local acc = readu8(plane, o)
+ for x = 1, rb - 1 do
+ acc = (acc + readu8(plane, o + x)) % 256
+ writeu8(plane, o + x, acc)
+ end
+ for x = 0, w - 1 do
+ writeu8(tmp, x * 4, readu8(plane, o + x))
+ writeu8(tmp, x * 4 + 1, readu8(plane, o + w + x))
+ writeu8(tmp, x * 4 + 2, readu8(plane, o + 2 * w + x))
+ writeu8(tmp, x * 4 + 3, readu8(plane, o + 3 * w + x))
+ end
+ bcopy(plane, o, tmp, 0, rb)
+ end
+ end
+end
+
+-- channel(src, p, limit, w, h, depth, psb) -> plane (h rows of rowBytes) | nil, message. src[p, limit) holds the
+-- 2-byte compression code and the data of one layer channel.
+function Channels.channel(src: buffer, p: number, limit: number, w: number, h: number, depth: number, psb: boolean): (buffer?, string?)
+ local rb = Channels.rowBytes(w, depth)
+ local plane = bcreate(rb * h)
+ if w == 0 or h == 0 then
+ return plane, nil
+ end
+ if p + 2 > limit then
+ return nil, "channel data past the end"
+ end
+ local comp = readu8(src, p) * 256 + readu8(src, p + 1)
+ p += 2
+ if comp == 0 then
+ if p + rb * h > limit then
+ return nil, "raw channel data past the end"
+ end
+ bcopy(plane, 0, src, p, rb * h)
+ elseif comp == 1 then
+ local counts, q = Channels.rleCounts(src, p, limit, h, psb)
+ if not counts then
+ return nil, "RLE row counts past the end"
+ end
+ local ok, err = Channels.rle(src, q, limit, counts, 1, h, rb, plane, 0)
+ if not ok then
+ return nil, err
+ end
+ elseif comp == 2 or comp == 3 then
+ local out, err = Deflate.zlib(src, p, limit - p, rb * h)
+ if not out then
+ return nil, "ZIP channel: " .. tostring(err)
+ end
+ plane = out
+ if comp == 3 then
+ unpredict(plane, w, h, depth)
+ end
+ else
+ return nil, "unknown channel compression " .. comp
+ end
+ return plane, nil
+end
+
+-- sample8(plane, i, depth) -> sample i as 0..255
+local function sample8(plane: buffer, i: number, depth: number): number
+ if depth == 8 then
+ return readu8(plane, i)
+ elseif depth == 16 then
+ return floor((readu8(plane, i * 2) * 256 + readu8(plane, i * 2 + 1)) / 257 + 0.5)
+ elseif depth == 32 then
+ local f = readf32(plane, i * 4) -- the plane holds big-endian floats: swapped by the caller
+ if f ~= f then
+ return 0
+ end
+ return floor(max(0, min(1, f)) * 255 + 0.5)
+ end
+ -- 1-bit (rows are padded, so this is only right for whole-byte widths; toRGBA reads bitmaps itself): 1 = black
+ return if readu8(plane, i // 8) // 2 ^ (7 - i % 8) % 2 == 1 then 0 else 255
+end
+
+-- swap32(plane): big-endian f32 samples to native order, in place
+function Channels.swap32(plane: buffer)
+ for i = 0, blen(plane) // 4 - 1 do
+ writeu32(plane, i * 4, byteswap(readu32(plane, i * 4)))
+ end
+end
+
+-- lab(L, a, b) 0..255 each (PSD Lab) -> sRGB r, g, b 0..255 (D50 -> D65 approximated by D65 white)
+local function srgb(c: number): number
+ c = if c <= 0.0031308 then 12.92 * c else 1.055 * c ^ (1 / 2.4) - 0.055
+ return floor(max(0, min(1, c)) * 255 + 0.5)
+end
+local function lab(l8: number, a8: number, b8: number): (number, number, number)
+ local L = l8 * 100 / 255
+ local a, b = a8 - 128, b8 - 128
+ local fy = (L + 16) / 116
+ local fx = fy + a / 500
+ local fz = fy - b / 200
+ local function f(t: number): number
+ return if t > 6 / 29 then t * t * t else 3 * (6 / 29) ^ 2 * (t - 4 / 29)
+ end
+ local X, Y, Z = 0.95047 * f(fx), f(fy), 1.08883 * f(fz)
+ local r = 3.2404542 * X - 1.5371385 * Y - 0.4985314 * Z
+ local g = -0.969266 * X + 1.8760108 * Y + 0.041556 * Z
+ local bl = 0.0556434 * X - 0.2040259 * Y + 1.0572252 * Z
+ return srgb(r), srgb(g), srgb(bl)
+end
+
+-- toRGBA(planes, w, h, depth, mode, palette?, dst?) -> rgba8 buffer. planes: { [1..k] = colour planes, alpha = plane? }
+-- mode: PSD colour mode (0 bitmap, 1 grey, 2 indexed, 3 RGB, 4 CMYK, 7 multichannel, 8 duotone, 9 Lab)
+function Channels.toRGBA(planes: { [any]: buffer }, w: number, h: number, depth: number, mode: number, palette: buffer?): buffer
+ local n = w * h
+ local out = bcreate(n * 4)
+ local c1, c2, c3, c4 = planes[1], planes[2], planes[3], planes[4]
+ local alpha = planes.alpha
+ local bitmapW = (w + 7) // 8
+ if depth == 8 and (mode == 3 or mode == 1) and c1 and blen(c1) >= n then
+ -- the common case, without a call per sample
+ local g8 = if mode == 3 and c2 and blen(c2) >= n then c2 else c1
+ local b8 = if mode == 3 and c3 and blen(c3) >= n then c3 else c1
+ local a8 = if alpha and blen(alpha) >= n then alpha else nil
+ for i = 0, n - 1 do
+ local a = if a8 then readu8(a8, i) else 255
+ writeu32(out, i * 4, readu8(c1, i) + readu8(g8, i) * 256 + readu8(b8, i) * 65536 + a * 16777216)
+ end
+ return out
+ end
+ for i = 0, n - 1 do
+ local r, g, b = 0, 0, 0
+ if mode == 3 then
+ r = if c1 then sample8(c1, i, depth) else 0
+ g = if c2 then sample8(c2, i, depth) else r
+ b = if c3 then sample8(c3, i, depth) else r
+ elseif mode == 4 then
+ local cc = if c1 then sample8(c1, i, depth) else 255
+ local mm = if c2 then sample8(c2, i, depth) else 255
+ local yy = if c3 then sample8(c3, i, depth) else 255
+ local kk = if c4 then sample8(c4, i, depth) else 255
+ r, g, b = floor(cc * kk / 255 + 0.5), floor(mm * kk / 255 + 0.5), floor(yy * kk / 255 + 0.5)
+ elseif mode == 2 then
+ local k = if c1 then readu8(c1, i) else 0
+ if palette and blen(palette) >= 768 then
+ r, g, b = readu8(palette, k), readu8(palette, 256 + k), readu8(palette, 512 + k)
+ else
+ r, g, b = k, k, k
+ end
+ elseif mode == 0 then
+ local y, x = i // w, i % w
+ local bit = if c1 then readu8(c1, y * bitmapW + x // 8) // 2 ^ (7 - x % 8) % 2 else 0
+ r = if bit == 1 then 0 else 255
+ g, b = r, r
+ elseif mode == 9 then
+ local L = if c1 then sample8(c1, i, depth) else 0
+ local A = if c2 then sample8(c2, i, depth) else 128
+ local B = if c3 then sample8(c3, i, depth) else 128
+ r, g, b = lab(L, A, B)
+ else -- grey, duotone, multichannel: the first channel as grey
+ r = if c1 then sample8(c1, i, depth) else 0
+ g, b = r, r
+ end
+ local a = if alpha then sample8(alpha, i, depth) else 255
+ writeu32(out, i * 4, r + g * 256 + b * 65536 + a * 16777216)
+ end
+ return out
+end
+
+-- gray8(plane, w, h, depth) -> 1 byte per pixel
+function Channels.gray8(plane: buffer, w: number, h: number, depth: number): buffer
+ local n = w * h
+ local out = bcreate(n)
+ for i = 0, n - 1 do
+ writeu8(out, i, sample8(plane, i, depth))
+ end
+ return out
+end
+
+-- unmatte(rgba, n): Photoshop stores a transparent merged image matted with white (C * a + 255 * (1 - a)): undo it
+function Channels.unmatte(rgba: buffer, n: number)
+ for i = 0, n - 1 do
+ local o = i * 4
+ local a = readu8(rgba, o + 3)
+ if a == 0 then
+ writeu32(rgba, o, 0)
+ elseif a < 255 then
+ local f = a / 255
+ for k = 0, 2 do
+ local v = (readu8(rgba, o + k) - 255 * (1 - f)) / f
+ writeu8(rgba, o + k, floor(max(0, min(255, v)) + 1e-6))
+ end
+ end
+ end
+end
+
+-- matte(rgba, n) -> a copy matted with white (the writer's merged image)
+function Channels.matte(rgba: buffer, n: number): buffer
+ local out = bcreate(n * 4)
+ bcopy(out, 0, rgba, 0, n * 4)
+ for i = 0, n - 1 do
+ local o = i * 4
+ local a = readu8(out, o + 3)
+ if a < 255 then
+ local f = a / 255
+ for k = 0, 2 do
+ writeu8(out, o + k, floor(readu8(out, o + k) * f + 255 * (1 - f) + 0.5))
+ end
+ end
+ end
+ return out
+end
+
+-- ------------------------------------------------------------------------------------------------ writer helpers
+-- packRow(src, o, n, out, d) -> bytes written: PackBits of src[o, o + n) into out at d (out needs n + n // 128 + 1)
+function Channels.packRow(src: buffer, o: number, n: number, out: buffer, d: number): number
+ local start = d
+ local i = 0
+ while i < n do
+ -- a run of at least 3 equal bytes?
+ local v = readu8(src, o + i)
+ local run = 1
+ while i + run < n and run < 128 and readu8(src, o + i + run) == v do
+ run += 1
+ end
+ if run >= 3 then
+ writeu8(out, d, 257 - run)
+ writeu8(out, d + 1, v)
+ d += 2
+ i += run
+ else
+ -- literals up to the next run of 3
+ local j = i
+ while j < n and j - i < 128 do
+ if j + 2 < n and readu8(src, o + j) == readu8(src, o + j + 1) and readu8(src, o + j) == readu8(src, o + j + 2) then
+ break
+ end
+ j += 1
+ end
+ local c = j - i
+ writeu8(out, d, c - 1)
+ bcopy(out, d + 1, src, o + i, c)
+ d += c + 1
+ i = j
+ end
+ end
+ return d - start
+end
+
+-- planes8(rgba, w, h) -> r, g, b, a planes (1 byte per pixel each)
+function Channels.planes8(rgba: buffer, w: number, h: number): (buffer, buffer, buffer, buffer)
+ local n = w * h
+ local r, g, b, a = bcreate(n), bcreate(n), bcreate(n), bcreate(n)
+ if blen(rgba) < n * 4 then
+ return r, g, b, a
+ end
+ for i = 0, n - 1 do
+ local v = readu32(rgba, i * 4)
+ writeu8(r, i, v % 256)
+ writeu8(g, i, v // 256 % 256)
+ writeu8(b, i, v // 65536 % 256)
+ writeu8(a, i, v // 16777216)
+ end
+ return r, g, b, a
+end
+
+-- rleChannel(plane, w, h, psb) -> the RLE data of one channel (counts, then rows), without the compression code
+function Channels.rleChannel(plane: buffer, w: number, h: number, psb: boolean): buffer
+ local cs = if psb then 4 else 2
+ local out = bcreate(h * cs + h * (w + w // 128 + 2))
+ local d = h * cs
+ for y = 0, h - 1 do
+ local n = Channels.packRow(plane, y * w, w, out, d)
+ if psb then
+ writeu32(out, y * 4, byteswap(n))
+ else
+ writeu16(out, y * 2, byteswap(n) // 65536)
+ end
+ d += n
+ end
+ local res = bcreate(d)
+ bcopy(res, 0, out, 0, d)
+ return res
+end
+
+return Channels
diff --git a/src/Formats/layered/psd/init.luau b/src/Formats/layered/psd/init.luau
new file mode 100644
index 0000000..af510e7
--- /dev/null
+++ b/src/Formats/layered/psd/init.luau
@@ -0,0 +1,758 @@
+--!strict
+-- layered/psd: Adobe Photoshop PSD and PSB (Adobe Photoshop File Formats Specification, 2016). Supports: decode of
+-- bitmap, greyscale, indexed, RGB, CMYK, Lab, duotone and multichannel documents at 1 / 8 / 16 / 32 bits; layers
+-- (raw, PackBits RLE, ZIP and ZIP-with-prediction channels; 16 / 32-bit layers in Lr16 / Lr32), their blend mode,
+-- opacity, fill opacity (iOpa), visibility, clipping, Unicode names (luni), user masks (as grey masks), groups (lsct /
+-- lsdk section dividers -> group layers with children; pass-through kept as the "passThrough" blend); the merged image
+-- (meta.composite); image resources (meta.resources, ICC profile in meta.icc). Everything converts to rgba8.
+-- Encode: an 8-bit RGB PSD (PSB when a side is over 30000) with the RLE merged composite (ops-free: codecs/Blend
+-- flattens the tree, or opts.composite) and every layer as RLE RGBA channels, groups as section dividers, masks,
+-- clipping, opacity / fill, hidden flags and Unicode names.
+-- Not supported: adjustment / fill / type / smart-object layer contents (their pixels, if any, are used), layer
+-- effects, vector masks, colour management, 16 / 32-bit or non-RGB output.
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Types = require("@formats/Types")
+local Blend = require("@formats/codecs/Blend")
+local Channels = require("@formats/layered/psd/Channels")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Psd = {
+ name = "psd",
+ category = "layered",
+ extensions = { "psd", "psb" },
+ mime = { "image/vnd.adobe.photoshop" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/Blend", "codecs/Deflate" },
+ caps = { decode = true, encode = true, layers = true, groups = true, depths = { 1, 8, 16, 32 } },
+}
+
+export type DecodeOptions = {
+ layers: boolean?, -- read the layers (default true; false reads only the merged image)
+ maxPixels: number?, -- refuse documents / layers larger than this (default 2^26)
+ maxLayers: number?, -- default 10000
+}
+export type EncodeOptions = {
+ composite: Types.Image?, -- the merged image to store (default: the layers flattened with codecs/Blend)
+}
+
+-- ------------------------------------------------------------------------------------------------ constants
+local BLEND_KEYS: { [string]: string } = {
+ norm = "normal",
+ diss = "dissolve",
+ dark = "darken",
+ ["mul "] = "multiply",
+ idiv = "colorBurn",
+ lbrn = "linearBurn",
+ dkCl = "darkerColor",
+ lite = "lighten",
+ scrn = "screen",
+ ["div "] = "colorDodge",
+ lddg = "linearDodge",
+ lgCl = "lighterColor",
+ over = "overlay",
+ sLit = "softLight",
+ hLit = "hardLight",
+ vLit = "vividLight",
+ lLit = "linearLight",
+ pLit = "pinLight",
+ hMix = "hardMix",
+ diff = "difference",
+ smud = "exclusion",
+ fsub = "subtract",
+ fdiv = "divide",
+ ["hue "] = "hue",
+ ["sat "] = "saturation",
+ colr = "color",
+ ["lum "] = "luminosity",
+ pass = "passThrough",
+}
+local BLEND_NAMES: { [string]: string } = {}
+for k, v in BLEND_KEYS do
+ BLEND_NAMES[v] = k
+end
+BLEND_NAMES.add = "lddg"
+
+-- colour channels per mode (the rest are alpha / spot channels)
+local COLOR_CHANNELS = { [0] = 1, [1] = 1, [2] = 1, [3] = 3, [4] = 4, [7] = 1, [8] = 1, [9] = 3 }
+local MODE_NAMES = { [0] = "bitmap", [1] = "gray", [2] = "indexed", [3] = "rgb", [4] = "cmyk", [7] = "multichannel", [8] = "duotone", [9] = "lab" }
+-- additional layer info keys with 8-byte lengths in PSB
+local LONG_KEYS = { LMsk = true, Lr16 = true, Lr32 = true, Layr = true, Mt16 = true, Mt32 = true, Mtrn = true, Alph = true, FMsk = true, lnk2 = true, FEid = true, FXid = true, PxSD = true }
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Psd.sniff(r: Bytes.Reader): number
+ local h = r:peek(6)
+ if string.sub(h, 1, 4) == "8BPS" and (string.sub(h, 5, 6) == "\0\1" or string.sub(h, 5, 6) == "\0\2") then
+ return 1
+ end
+ return 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+type Ctx = { psb: boolean, depth: number, mode: number, maxPixels: number, maxLayers: number }
+
+local function len(r: Bytes.Reader, psb: boolean): number
+ return if psb then r:u64be() else r:u32be()
+end
+
+local function utf16be(s: string): string
+ local out = {}
+ local i = 1
+ while i + 1 <= #s do
+ local c = string.byte(s, i) * 256 + string.byte(s, i + 1)
+ i += 2
+ if c >= 0xD800 and c < 0xDC00 and i + 1 <= #s then
+ local c2 = string.byte(s, i) * 256 + string.byte(s, i + 1)
+ if c2 >= 0xDC00 and c2 < 0xE000 then
+ c = 0x10000 + (c - 0xD800) * 1024 + (c2 - 0xDC00)
+ i += 2
+ end
+ end
+ if c ~= 0 then
+ table.insert(out, utf8.char(c))
+ end
+ end
+ return table.concat(out)
+end
+
+-- the layer records + channel data at r (a Reader over the layer info, after its length): flat records | nil, Err
+local function layerRecords(r: Bytes.Reader, c: Ctx): ({ any }?, boolean, Err.Err?)
+ local count = r:i16be()
+ local absAlpha = count < 0
+ count = math.abs(count)
+ if r.err then
+ return nil, absAlpha, r.err
+ end
+ if count > c.maxLayers then
+ return nil, absAlpha, Err.new(Err.LIMIT, "over " .. c.maxLayers .. " layers")
+ end
+ local recs = {}
+ for li = 1, count do
+ local top, left, bottom, right = r:i32be(), r:i32be(), r:i32be(), r:i32be()
+ local nch = r:u16be()
+ if r.err then
+ return nil, absAlpha, r.err
+ end
+ if nch > 56 then
+ return nil, absAlpha, Err.new(Err.CORRUPT, "layer " .. li .. ": " .. nch .. " channels", r.pos)
+ end
+ local chans = {}
+ for k = 1, nch do
+ chans[k] = { id = r:i16be(), size = len(r, c.psb) }
+ end
+ if r:string(4) ~= "8BIM" and not r.err then
+ return nil, absAlpha, Err.new(Err.CORRUPT, "layer " .. li .. ": bad blend mode signature", r.pos - 4)
+ end
+ local key = r:string(4)
+ local opacity, clipping, flags = r:u8(), r:u8(), r:u8()
+ r:skip(1)
+ local extraLen = r:u32be()
+ if r.err then
+ return nil, absAlpha, r.err
+ end
+ local ex = r:slice(extraLen)
+ local rec: { [string]: any } = {
+ top = top,
+ left = left,
+ bottom = bottom,
+ right = right,
+ chans = chans,
+ blend = BLEND_KEYS[key] or "normal",
+ blendKey = key,
+ opacity = opacity / 255,
+ clip = clipping ~= 0,
+ hidden = bit32.band(flags, 2) ~= 0,
+ flags = flags,
+ }
+ -- mask data
+ local ml = ex:u32be()
+ if ml > 0 then
+ local mr = ex:slice(ml)
+ if ml >= 18 then
+ rec.mask = { top = mr:i32be(), left = mr:i32be(), bottom = mr:i32be(), right = mr:i32be(), default = mr:u8(), flags = mr:u8() }
+ end
+ end
+ -- blending ranges
+ ex:skip(ex:u32be())
+ -- name: Pascal string padded to 4
+ local nl = ex:u8()
+ rec.name = ex:string(nl)
+ ex:skip((4 - (nl + 1) % 4) % 4)
+ -- additional layer info
+ while ex:remaining() >= 12 do
+ local sig = ex:string(4)
+ if sig ~= "8BIM" and sig ~= "8B64" then
+ break
+ end
+ local k = ex:string(4)
+ local l = if c.psb and LONG_KEYS[k] then ex:u64be() else ex:u32be()
+ if ex.err then
+ break
+ end
+ local d = ex:slice(l)
+ if k == "luni" then
+ local n = d:u32be()
+ local s = d:string(math.min(n * 2, d:remaining()))
+ rec.name = utf16be(s)
+ elseif k == "lsct" or k == "lsdk" then
+ rec.section = d:u32be()
+ if d:remaining() >= 8 and d:string(4) == "8BIM" then
+ rec.sectionBlend = d:string(4)
+ end
+ elseif k == "iOpa" then
+ rec.fill = d:u8() / 255
+ elseif k == "lyid" then
+ rec.id = d:u32be()
+ end
+ end
+ if r.err then
+ return nil, absAlpha, r.err
+ end
+ recs[li] = rec
+ end
+ -- channel image data
+ local b = r.buf
+ for li, rec in recs do
+ local w, h = rec.right - rec.left, rec.bottom - rec.top
+ if w < 0 or h < 0 or w > 300000 or h > 300000 then
+ return nil, absAlpha, Err.new(Err.CORRUPT, "layer " .. li .. ": bad bounds", r.pos)
+ end
+ if w * h > c.maxPixels then
+ return nil, absAlpha, Err.new(Err.LIMIT, string.format("layer %d: %d x %d is over the pixel limit", li, w, h))
+ end
+ local planes: { [any]: buffer } = {}
+ for _, ch in rec.chans do
+ local p = r.pos
+ if ch.size < 0 or p + ch.size > r.limit then
+ return nil, absAlpha, Err.new(Err.TRUNCATED, "layer " .. li .. ": channel data past the end", p)
+ end
+ r.pos = p + ch.size
+ local cw, chh = w, h
+ if ch.id == -2 or ch.id == -3 then
+ local m = rec.mask
+ if not m then
+ continue
+ end
+ cw, chh = m.right - m.left, m.bottom - m.top
+ if cw < 0 or chh < 0 or cw * chh > c.maxPixels then
+ continue
+ end
+ end
+ if ch.size < 2 then
+ continue -- an empty channel
+ end
+ local plane, perr = Channels.channel(b, p, p + ch.size, cw, chh, c.depth, c.psb)
+ if not plane then
+ return nil, absAlpha, Err.new(Err.CORRUPT, "layer " .. li .. " channel " .. ch.id .. ": " .. tostring(perr), p)
+ end
+ if c.depth == 32 then
+ Channels.swap32(plane)
+ end
+ if ch.id == -1 then
+ planes.alpha = plane
+ elseif ch.id == -2 then
+ rec.maskPlane = Channels.gray8(plane, cw, chh, c.depth)
+ elseif ch.id >= 0 and ch.id < 56 then
+ planes[ch.id + 1] = plane
+ end
+ end
+ local img = Types.Image.new(w, h)
+ if w > 0 and h > 0 then
+ img.pixels = Channels.toRGBA(planes, w, h, c.depth, c.mode, nil)
+ end
+ rec.image = img
+ end
+ return recs, absAlpha, nil
+end
+
+-- records (bottom to top) -> a layer tree
+local function tree(recs: { any }): { Types.Layer }
+ local root: { Types.Layer } = {}
+ local stack: { { Types.Layer } } = {}
+ local cur = root
+ local function layerOf(rec: any): Types.Layer
+ local l: any = {
+ name = rec.name,
+ image = rec.image,
+ x = rec.left,
+ y = rec.top,
+ opacity = rec.opacity,
+ blend = rec.blend,
+ visible = not rec.hidden,
+ }
+ if rec.clip then
+ l.clip = true
+ end
+ if rec.fill and rec.fill < 1 then
+ l.fillOpacity = rec.fill
+ end
+ if rec.id then
+ l.id = rec.id
+ end
+ if rec.mask and rec.maskPlane then
+ local m = rec.mask
+ local mi = Types.Image.new(m.right - m.left, m.bottom - m.top, "gray8")
+ mi.pixels = rec.maskPlane
+ l.mask = { image = mi, x = m.left, y = m.top, default = m.default, disabled = bit32.band(m.flags, 2) ~= 0 }
+ end
+ return l
+ end
+ for _, rec in recs do
+ local s = rec.section
+ if s == 3 then
+ table.insert(stack, cur)
+ cur = {}
+ elseif s == 1 or s == 2 then
+ local g = layerOf(rec)
+ g.image = Types.Image.new(0, 0)
+ g.children = cur
+ if rec.sectionBlend and BLEND_KEYS[rec.sectionBlend] then
+ g.blend = BLEND_KEYS[rec.sectionBlend]
+ end
+ ;(g :: any).collapsed = s == 2
+ cur = table.remove(stack) or root
+ table.insert(cur, g)
+ else
+ table.insert(cur, layerOf(rec))
+ end
+ end
+ -- unbalanced dividers: splice the open groups' layers back in
+ while #stack > 0 do
+ local parent = table.remove(stack) :: { Types.Layer }
+ for _, l in cur do
+ table.insert(parent, l)
+ end
+ cur = parent
+ end
+ return cur
+end
+
+function Psd.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Layered?, Err.Err?)
+ local o: DecodeOptions = opts or {}
+ local c: Ctx = { psb = false, depth = 8, mode = 3, maxPixels = o.maxPixels or 2 ^ 26, maxLayers = o.maxLayers or 10000 }
+ if Psd.sniff(r) == 0 then
+ return nil, Err.new(Err.CORRUPT, "not a PSD (bad signature)", r.pos)
+ end
+ r:skip(4)
+ local version = r:u16be()
+ r:skip(6)
+ local nch, h, w, depth, mode = r:u16be(), r:u32be(), r:u32be(), r:u16be(), r:u16be()
+ if r.err then
+ return nil, r.err
+ end
+ c.psb, c.depth, c.mode = version == 2, depth, mode
+ if nch < 1 or nch > 56 then
+ return nil, Err.new(Err.CORRUPT, "bad channel count " .. nch)
+ end
+ local maxSide = if c.psb then 300000 else 30000
+ if w < 1 or h < 1 or w > maxSide or h > maxSide then
+ return nil, Err.new(Err.CORRUPT, string.format("bad size %d x %d", w, h))
+ end
+ if not (depth == 1 or depth == 8 or depth == 16 or depth == 32) then
+ return nil, Err.new(Err.CORRUPT, "bad depth " .. depth)
+ end
+ if COLOR_CHANNELS[mode] == nil then
+ return nil, Err.new(Err.CORRUPT, "bad colour mode " .. mode)
+ end
+ if (mode == 0) ~= (depth == 1) then
+ return nil, Err.new(Err.UNSUPPORTED, "1-bit data outside bitmap mode")
+ end
+ if w * h > c.maxPixels then
+ return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, c.maxPixels))
+ end
+ local layered = Types.Layered.new(w, h)
+ -- colour mode data
+ local cm = r:slice(r:u32be())
+ local palette: buffer? = nil
+ if mode == 2 and cm:size() >= 768 then
+ palette = cm:bytes(768)
+ local pal = {}
+ for i = 0, 255 do
+ pal[i + 1] = { buffer.readu8(palette :: buffer, i), buffer.readu8(palette :: buffer, 256 + i), buffer.readu8(palette :: buffer, 512 + i), 255 }
+ end
+ layered.meta.palette = pal
+ end
+ -- image resources
+ local rr = r:slice(r:u32be())
+ if r.err then
+ return nil, r.err
+ end
+ local resources = {}
+ while rr:remaining() >= 12 and rr:string(4) == "8BIM" do
+ local id = rr:u16be()
+ local nl = rr:u8()
+ local name = rr:string(nl)
+ rr:skip((nl + 1) % 2)
+ local size = rr:u32be()
+ if rr.err or size > rr:remaining() then
+ break
+ end
+ local data = rr:bytes(size)
+ rr:skip(size % 2)
+ table.insert(resources, { id = id, name = name, data = data })
+ if id == 0x040F then
+ layered.meta.icc = data
+ end
+ end
+ layered.meta.resources = resources
+ -- layer and mask information
+ local lm = r:slice(len(r, c.psb))
+ if r.err then
+ return nil, r.err
+ end
+ local recs: { any }? = nil
+ local absAlpha = false
+ if o.layers ~= false and lm:size() > 0 then
+ local liLen = len(lm, c.psb)
+ local li = lm:slice(liLen)
+ if lm.err then
+ return nil, lm.err
+ end
+ if liLen > 0 then
+ local list, aa, lerr = layerRecords(li, c)
+ if not list then
+ return nil, lerr
+ end
+ recs, absAlpha = list, aa
+ end
+ -- global layer mask info, then additional info (16 / 32-bit layers live in Lr16 / Lr32)
+ lm:skip(lm:u32be())
+ while not lm.err and lm:remaining() >= 12 do
+ local sig = lm:string(4)
+ if sig ~= "8BIM" and sig ~= "8B64" then
+ break
+ end
+ local k = lm:string(4)
+ local l = if c.psb and LONG_KEYS[k] then lm:u64be() else lm:u32be()
+ if lm.err then
+ break
+ end
+ local d = lm:slice(l)
+ if (k == "Lr16" or k == "Lr32" or k == "Layr") and recs == nil then
+ local list, aa, lerr = layerRecords(d, c)
+ if not list then
+ return nil, lerr
+ end
+ recs, absAlpha = list, aa
+ end
+ lm:align(4)
+ end
+ end
+ if recs then
+ layered.layers = tree(recs)
+ end
+ -- the merged image
+ local comp = r:u16be()
+ if r.err then
+ return nil, r.err
+ end
+ local cc = COLOR_CHANNELS[mode]
+ if mode == 7 then
+ cc = math.min(nch, 3)
+ end
+ local useAlpha = nch > cc and (absAlpha or recs == nil) and mode ~= 7
+ local nread = math.min(nch, cc + (if useAlpha then 1 else 0))
+ local rb = Channels.rowBytes(w, depth)
+ local planes: { [any]: buffer } = {}
+ local b = r.buf
+ if comp == 0 then
+ for k = 1, nread do
+ local p = r.pos + (k - 1) * rb * h
+ if p + rb * h > r.limit then
+ return nil, Err.new(Err.TRUNCATED, "merged image past the end", p)
+ end
+ local plane = buffer.create(rb * h)
+ buffer.copy(plane, 0, b, p, rb * h)
+ planes[k] = plane
+ end
+ elseif comp == 1 then
+ local counts, q = Channels.rleCounts(b, r.pos, r.limit, h * nch, c.psb)
+ if not counts then
+ return nil, Err.new(Err.TRUNCATED, "merged image row counts past the end", r.pos)
+ end
+ local p: number = q
+ for k = 1, nread do
+ local plane = buffer.create(rb * h)
+ local np, perr = Channels.rle(b, p, r.limit, counts, (k - 1) * h + 1, h, rb, plane, 0)
+ if not np then
+ return nil, Err.new(Err.CORRUPT, "merged image: " .. tostring(perr), p)
+ end
+ p = np
+ planes[k] = plane
+ end
+ elseif comp == 2 or comp == 3 then
+ -- one zlib stream per channel would be Channels.channel; Photoshop writes all channels in one stream
+ local all = Channels.channel(b, r.pos - 2, r.limit, w, h * nread, depth, c.psb)
+ if not all then
+ return nil, Err.new(Err.CORRUPT, "merged image: bad ZIP data", r.pos)
+ end
+ for k = 1, nread do
+ local plane = buffer.create(rb * h)
+ buffer.copy(plane, 0, all, (k - 1) * rb * h, rb * h)
+ planes[k] = plane
+ end
+ else
+ return nil, Err.new(Err.CORRUPT, "bad merged image compression " .. comp)
+ end
+ if useAlpha then
+ planes.alpha = planes[cc + 1]
+ planes[cc + 1] = nil :: any
+ end
+ if depth == 32 then
+ for _, p in planes do
+ Channels.swap32(p)
+ end
+ end
+ local composite = Types.Image.new(w, h)
+ composite.pixels = Channels.toRGBA(planes, w, h, depth, mode, palette)
+ if planes.alpha then
+ Channels.unmatte(composite.pixels, w * h)
+ end
+ composite.meta.source = { format = "psd", bitDepth = depth, colorType = MODE_NAMES[mode] }
+ layered.meta.composite = composite
+ layered.meta.source = { format = "psd", version = version, bitDepth = depth, colorMode = MODE_NAMES[mode], channels = nch, psb = c.psb }
+ return layered, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+type Rec = { layer: any, section: number?, name: string }
+
+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 v.width >= 0 and v.height >= 0 and buffer.len(v.pixels) >= v.width * v.height * 4
+end
+
+local function pascal(name: string): string
+ local s = string.gsub(name, "[\128-\255]", "?")
+ s = string.sub(s, 1, 255)
+ local pad = (4 - (#s + 1) % 4) % 4
+ return string.char(#s) .. s .. string.rep("\0", pad)
+end
+
+local function block(w: Bytes.Writer, key: string, data: string)
+ w:string("8BIM")
+ w:string(key)
+ local pad = (4 - #data % 4) % 4 -- additional info is padded to 4
+ w:u32be(#data + pad)
+ w:string(data)
+ w:fill(0, pad)
+end
+
+local function u32s(v: number): string
+ return string.char(v // 16777216 % 256, v // 65536 % 256, v // 256 % 256, v % 256)
+end
+
+local function luni(name: string): string
+ local out = {}
+ local n = 0
+ for _, cp in utf8.codes(name) do
+ if cp >= 0x10000 then
+ local v = cp - 0x10000
+ local hi, lo = 0xD800 + v // 1024, 0xDC00 + v % 1024
+ table.insert(out, string.char(hi // 256, hi % 256, lo // 256, lo % 256))
+ n += 2
+ else
+ table.insert(out, string.char(cp // 256, cp % 256))
+ n += 1
+ end
+ end
+ return u32s(n) .. table.concat(out)
+end
+
+function Psd.encode(layered: Types.Layered, opts: EncodeOptions?): (buffer?, Err.Err?)
+ if type(layered) ~= "table" or type(layered.layers) ~= "table" or type(layered.width) ~= "number" or type(layered.height) ~= "number" then
+ return nil, Err.new(Err.ARG, "needs a Layered value")
+ end
+ local W, H = math.floor(layered.width), math.floor(layered.height)
+ if W < 1 or H < 1 or W > 300000 or H > 300000 then
+ return nil, Err.new(Err.ARG, "bad document size")
+ end
+ local psb = W > 30000 or H > 30000
+ -- the records, bottom to top
+ local recs: { Rec } = {}
+ local bad: string? = nil
+ local function walk(list: { any }, depth: number)
+ for _, l in list do
+ if type(l) ~= "table" then
+ bad = "a layer is not a table"
+ return
+ end
+ if type(l.children) == "table" then
+ if depth > 64 then
+ bad = "groups nested too deep"
+ return
+ end
+ table.insert(recs, { layer = l, section = 3, name = "" })
+ walk(l.children, depth + 1)
+ table.insert(recs, { layer = l, section = if l.collapsed then 2 else 1, name = tostring(l.name or "Group") })
+ else
+ if not isImage(l.image) then
+ bad = "layer " .. tostring(l.name) .. ": needs an rgba8 image"
+ return
+ end
+ table.insert(recs, { layer = l, name = tostring(l.name or "Layer") })
+ end
+ end
+ end
+ walk(layered.layers, 0)
+ if bad then
+ return nil, Err.new(Err.ARG, bad :: string)
+ end
+ if #recs > 32767 then
+ return nil, Err.new(Err.ARG, "too many layers")
+ end
+ local function lenW(w: Bytes.Writer, v: number)
+ if psb then
+ w:u64be(v)
+ else
+ w:u32be(v)
+ end
+ end
+ -- layer records and channel data
+ local info = Bytes.writer(4096)
+ local data = Bytes.writer(65536)
+ info:i16be(-#recs) -- negative: the merged image's first alpha channel is its transparency
+ for _, rec in recs do
+ local l = rec.layer
+ local img = if rec.section then nil else l.image
+ local x, y = math.floor(tonumber(l.x) or 0), math.floor(tonumber(l.y) or 0)
+ local w, h = if img then img.width else 0, if img then img.height else 0
+ if rec.section then
+ x, y = 0, 0
+ end
+ info:i32be(y)
+ info:i32be(x)
+ info:i32be(y + h)
+ info:i32be(x + w)
+ local chans: { { id: number, data: buffer } } = {}
+ if img and w > 0 and h > 0 then
+ local pr, pg, pb, pa = Channels.planes8(img.pixels, w, h)
+ chans = {
+ { id = -1, data = Channels.rleChannel(pa, w, h, psb) },
+ { id = 0, data = Channels.rleChannel(pr, w, h, psb) },
+ { id = 1, data = Channels.rleChannel(pg, w, h, psb) },
+ { id = 2, data = Channels.rleChannel(pb, w, h, psb) },
+ }
+ else
+ chans = { { id = -1, data = buffer.create(0) }, { id = 0, data = buffer.create(0) }, { id = 1, data = buffer.create(0) }, { id = 2, data = buffer.create(0) } }
+ end
+ -- the mask
+ local m = if rec.section == nil and type(l.mask) == "table" and type(l.mask.image) == "table" and type(l.mask.image.pixels) == "buffer" then l.mask else nil
+ local mw, mh = 0, 0
+ if m then
+ local mi = m.image
+ mw, mh = mi.width, mi.height
+ local plane = mi.pixels
+ if mi.format == "rgba8" then
+ plane = (Channels.planes8(mi.pixels, mw, mh))
+ elseif mi.format ~= "gray8" and mi.format ~= "alpha8" then
+ return nil, Err.new(Err.ARG, "mask images are gray8 / alpha8 / rgba8")
+ end
+ if buffer.len(plane) < mw * mh then
+ return nil, Err.new(Err.ARG, "bad mask image")
+ end
+ table.insert(chans, { id = -2, data = Channels.rleChannel(plane, mw, mh, psb) })
+ end
+ info:u16be(#chans)
+ for _, ch in chans do
+ info:i16be(ch.id)
+ lenW(info, buffer.len(ch.data) + 2)
+ data:u16be(if buffer.len(ch.data) > 0 then 1 else 0)
+ data:bytes(ch.data)
+ end
+ info:string("8BIM")
+ local blend = if type(l.blend) == "string" then l.blend else "normal"
+ local key = BLEND_NAMES[blend] or "norm"
+ if rec.section and rec.section ~= 3 then
+ key = if blend == "passThrough" then "pass" else key
+ end
+ info:string(key)
+ info:u8(math.clamp(math.floor((tonumber(l.opacity) or 1) * 255 + 0.5), 0, 255))
+ info:u8(if l.clip and rec.section == nil then 1 else 0)
+ local flags = 8 -- bit 3: bit 4 is meaningful
+ if l.visible == false and rec.section ~= 3 then
+ flags += 2
+ end
+ if rec.section then
+ flags += 16 -- pixel data irrelevant to the appearance
+ end
+ info:u8(flags)
+ info:u8(0)
+ local ex = Bytes.writer(256)
+ if m then
+ ex:u32be(20)
+ local mx, my = math.floor(tonumber(m.x) or 0), math.floor(tonumber(m.y) or 0)
+ ex:i32be(my)
+ ex:i32be(mx)
+ ex:i32be(my + mh)
+ ex:i32be(mx + mw)
+ ex:u8(math.clamp(math.floor(tonumber(m.default) or 0), 0, 255))
+ ex:u8(if m.disabled then 2 else 0)
+ ex:u16be(0)
+ else
+ ex:u32be(0)
+ end
+ ex:u32be(0) -- blending ranges
+ ex:string(pascal(rec.name))
+ block(ex, "luni", luni(rec.name))
+ if rec.section then
+ block(ex, "lsct", u32s(rec.section) .. (if rec.section ~= 3 then "8BIM" .. key else ""))
+ end
+ local fill = tonumber(l.fillOpacity)
+ if fill and fill < 1 and rec.section == nil then
+ block(ex, "iOpa", string.char(math.clamp(math.floor(fill * 255 + 0.5), 0, 255)) .. "\0\0\0")
+ end
+ local exb = ex:finish()
+ info:u32be(buffer.len(exb))
+ info:bytes(exb)
+ end
+ info:bytes(data:finish())
+ if info:tell() % 2 == 1 then
+ info:u8(0)
+ end
+ local infoB = info:finish()
+ -- the merged image
+ local comp: Types.Image? = opts and opts.composite
+ if comp ~= nil and (not isImage(comp) or comp.width ~= W or comp.height ~= H) then
+ return nil, Err.new(Err.ARG, "opts.composite must be a " .. W .. " x " .. H .. " rgba8 Image")
+ end
+ local merged: buffer
+ if comp then
+ merged = comp.pixels
+ else
+ merged = buffer.create(W * H * 4)
+ Blend.flatten(layered.layers, merged, W, H, false)
+ end
+ local out = Bytes.writer(buffer.len(infoB) + W * H * 4 + 1024)
+ out:string("8BPS")
+ out:u16be(if psb then 2 else 1)
+ out:fill(0, 6)
+ out:u16be(4)
+ out:u32be(H)
+ out:u32be(W)
+ out:u16be(8)
+ out:u16be(3)
+ out:u32be(0) -- colour mode data
+ out:u32be(0) -- image resources
+ local lmLen = (if psb then 8 else 4) + buffer.len(infoB) + 4
+ lenW(out, lmLen)
+ lenW(out, buffer.len(infoB))
+ out:bytes(infoB)
+ out:u32be(0) -- global layer mask info
+ -- merged: RLE, all row counts first
+ out:u16be(1)
+ local pr, pg, pb, pa = Channels.planes8(Channels.matte(merged, W * H), W, H)
+ local cs = if psb then 4 else 2
+ local parts = {}
+ for k, plane in { pr, pg, pb, pa } do
+ local ch = Channels.rleChannel(plane, W, H, psb)
+ parts[k] = ch
+ out:bytes(ch, 0, H * cs)
+ end
+ for k = 1, 4 do
+ out:bytes(parts[k], H * cs)
+ end
+ return out:finish(), nil
+end
+
+return Psd
diff --git a/src/Formats/model/gltf/Pack.luau b/src/Formats/model/gltf/Pack.luau
new file mode 100644
index 0000000..470d384
--- /dev/null
+++ b/src/Formats/model/gltf/Pack.luau
@@ -0,0 +1,74 @@
+--!strict
+--!native
+-- model/gltf/Pack: the byte loops of glTF accessors: strided / column-padded elements into tightly packed Scene
+-- accessor data (gather), the reverse for writing (scatter), and sparse substitution. Callers check every range
+-- first (offsets, strides and counts against the buffer lengths); nothing here throws.
+local Pack = {}
+
+local bcopy, readu8, readu16, readu32 = buffer.copy, buffer.readu8, buffer.readu16, buffer.readu32
+
+-- gather(dst, src, off, count, elem, stride, cols, colBytes, colStride): element i starts at off + i * stride; an element is
+-- cols columns of colBytes bytes, colStride apart (glTF pads matrix columns to 4 bytes); dst gets them packed (elem =
+-- cols * colBytes bytes each)
+function Pack.gather(dst: buffer, src: buffer, off: number, count: number, elem: number, stride: number, cols: number, colBytes: number, colStride: number)
+ if cols == 1 or colBytes == colStride then
+ if stride == elem then
+ bcopy(dst, 0, src, off, count * elem)
+ return
+ end
+ for i = 0, count - 1 do
+ bcopy(dst, i * elem, src, off + i * stride, elem)
+ end
+ return
+ end
+ for i = 0, count - 1 do
+ local s = off + i * stride
+ local d = i * elem
+ for c = 0, cols - 1 do
+ bcopy(dst, d + c * colBytes, src, s + c * colStride, colBytes)
+ end
+ end
+end
+
+-- scatter(dst, at, src, count, elem, stride, cols, colBytes, colStride): the reverse of gather (dst zero-filled)
+function Pack.scatter(dst: buffer, at: number, src: buffer, count: number, elem: number, stride: number, cols: number, colBytes: number, colStride: number)
+ if cols == 1 or colBytes == colStride then
+ if stride == elem then
+ bcopy(dst, at, src, 0, count * elem)
+ return
+ end
+ for i = 0, count - 1 do
+ bcopy(dst, at + i * stride, src, i * elem, elem)
+ end
+ return
+ end
+ for i = 0, count - 1 do
+ local d = at + i * stride
+ local s = i * elem
+ for c = 0, cols - 1 do
+ bcopy(dst, d + c * colStride, src, s + c * colBytes, colBytes)
+ end
+ end
+end
+
+-- sparse(dst, count, elem, idx, idxOff, idxSize, values, valOff, n) -> false when an index is out of range: element
+-- idx[k] of dst becomes value k (values packed, elem bytes each)
+function Pack.sparse(dst: buffer, count: number, elem: number, idx: buffer, idxOff: number, idxSize: number, values: buffer, valOff: number, n: number): boolean
+ for k = 0, n - 1 do
+ local i
+ if idxSize == 1 then
+ i = readu8(idx, idxOff + k)
+ elseif idxSize == 2 then
+ i = readu16(idx, idxOff + k * 2)
+ else
+ i = readu32(idx, idxOff + k * 4)
+ end
+ if i >= count then
+ return false
+ end
+ bcopy(dst, i * elem, values, valOff + k * elem, elem)
+ end
+ return true
+end
+
+return Pack
diff --git a/src/Formats/model/gltf/Read.luau b/src/Formats/model/gltf/Read.luau
new file mode 100644
index 0000000..ab59fe6
--- /dev/null
+++ b/src/Formats/model/gltf/Read.luau
@@ -0,0 +1,661 @@
+--!strict
+-- model/gltf/Read: a parsed glTF 2.0 JSON document (+ its buffers) -> Scene. Accessors of every component type
+-- (normalized ones as unorm / snorm, matrices with their column padding removed, byte strides, sparse substitution,
+-- accessors without a bufferView as zeros), images kept encoded (bufferView / data: URI / external file through the
+-- fetch callback), samplers, PBR materials with every material extension (textureInfo objects -> TextureRefs), the
+-- KHR_texture_transform of every texture reference, cameras, KHR_lights_punctual, skins, animations, morph targets,
+-- scenes. glTF extras and unhandled extensions are kept in