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 = { + "eNo8velyHMe1LvrbiOA7lNpni8Q20QBJTSYGB0dJ3hq4Bcq+2z4ORXZVdncB1VWtyiqATUkR4ICB4ABSnAXOMyUCIDhiIIGI", + "wxeg/pH/FOeiuhsR9yHu962EbBkS0J2VlcMavrVyrZWJX9FeNBgGflEHupgUlNvvRp72VKJMORqMwqBm/ES7flKLqjrsS00S", + "+P26GGs9GMX9id6X1LSKowEdFyKvFuCXYhRXClHUXw1ULfAHdOCHuqyDajmqaON7uhLFfNYLorCUlHVlwNeDRT/0qqqE99ZM", + "MQ2CslZeouOKVm5ZxVoV46iSxKmuqLhfFQKdVqOw7JfKGKcOVOiFetDoAR2GGI+rjC5ESbkamSQ12qsoT5fRpqzx3rJKQlXR", + "n/lhfyGISsbfrwtoj/GhXT/690M8E69vdf5UjgJPh54Z9JPyF+gfw/AG0YfxS2GCtmU1oEvoy2gduioIqiopD2r8N0hNRYdp", + "0Q8qVRUnfZEfJmXfBL5JSlGEsWpvEPMc1AbfFUwFc1eBiTCcKPbdMt5vAmWSRCtMt1Ir4pl+PywN+kGg8fmgir0Cni36sd6D", + "NesPo0GFDvPVsFTB+ieYbBApr4S1NzoohlGiK6lbLmquRViLI7ffd6MwCl0dYJ/K2BPP194n2J84DXQZ66b61D4/LEZukBYC", + "NWgCbUxZBUXDPURf+6NQb+ro+A/8x7jYoL2go1i5uhCk2P80HtS6v4i/yyCaEtYJm4j9xtjLOsSa9PfralJVBp361TiKKp/s", + "/fwz0Eu4t1YFPaJTPNOvdbUYqBLopx+r4xUxnwTjjbHnCWi2L61UE6yWh/4wBnwPCgYtYvS1fqwV1iEpYl9UmkSgjTjvgoZU", + "0A+6rg5gTTz0XwGtY0eTJI3DQoQf0Ak4IYgjo9M42GCw8HEUaDwKUkwMlht7q7GPgZfvq5bAGpUBFdfwTAJaDg0Ixouj6t9A", + "025UrW3Kd+S62lWPSbAQAXbDx8uwPlXwWb7kF7EGiWvMX0qxquEN4bulpDPGfmCMSYB5GuWjO+XhHQ72L+iLyiFopL8axZib", + "SdZ/va3NA112tRd6qlEUFzhvrOHX+d78IOimAn7dXN3X+Sn2MlZh/yD6HlQhaCggMXn/7PhXZ1WlwSDW26Sx/l8b1v9xUPlJ", + "BXsD2jOlSJsSeAJbU6piLO+0tTkB6CcN/QT7xn76QYeVQciPfZUgZ8jTmOLmjuo+LB3GPoj5RkExCtGnHxhVxLfoWVWNCzkQ", + "o+9iEA0WVKFmqio04Iv3MN4P8APWMaD9BHwXDPr9PmRCYhIQTuxj+qX2ADw4qFV/gr3YDZkDvseahAZ72I/trsVpaPrSoAZJ", + "1r8J/ZUiFZQgAgzep72S9r3unNGJeR/f5fvMX97DmP2is8FEEfYRcgJ0mKQFvV+TGkKMQ3ug6QTcHGHrQF5xZdNH1X0uZEAZ", + "617AOPaDlgciLLIytRg8C5oMqhijj/VyQf9b8K4+7H2iSqbgJwa0FYD5kn4IsBC024UFLmHR/tr75RdemtS+oHxRga5FKdY9", + "wRL5YZ/av9+lbKppU/RNeXBwMB/7Bn0WTDXWA5swD/ytN2Ni28GPHsaxpaNjYwF7DirA2OIQssQrRPvyReXHAcaD9WLfcV+K", + "OWu37Bc3vFMFnekBP/hfG3KgibgS4FkP9FCFfN7Y0dHBWXqxGiynYIpqlBTT0CuAj8qxLkKyBP26ZhL0UQa9g/ch13WwCcRo", + "Uj/Bo8FXvb05inzsSe3jXXtzWDOtfNAch+R7BkvbGaqBWgkMkfhV88c///nPGAdko1cDv5vWTueHarn6F8juAHwdDELB7C9v", + "zf6zfV2LA+EEeRXkW1q2fYh+qqkpQ5MkWJpOFzTwn+1d7WVouA+xRpAxSQwZ5rz7rgNtEmA/oV1AVRhExYeM6verCfYfOgr6", + "IdAl0EwVm/Ee1nRdy7oWl/QNmZDHYLoKcY8Gg1aw16XUh5wOsFEGrwaTKEqkqNLuV0rv/vGjzUEKXYt+sZSdIKpaCfRWTiqU", + "EoEXp6XdX+3aFUI+hVjDv4BYA1Ih1n6AOgC8hfVzQP9xrINaATrIgFa8tF+HyihXVfUgaKOUBsW9m7dsLYPWQPdJCTIFwh+6", + "L40hr2qbMP/161s7WztzPRUDoeWDf/zYM5AvBQ3OgRzfu+mjrdh6QwbA/IMPsIhF0MP/HbpoClHNQIbk0UVuz5e9ewsYTz/2", + "rrXzhx+gvGpYN2/D1//V+m2qPOxNvQ0Ktw3/g9Cv4pl1wB3J3k1/3jrgu5B+Xs3ThaQHE4MsC0LNcUaDezd9sNWDbNMDKti7", + "6cOtAdYfdAtyVEEV/BNGAwr8YEo61M7/HTpjoiJkU0Unvshx01XeAtmYxkXggCp0SVcS90Dn+q3fv7MB/9UYV7MAeoJ8iTs6", + "WjsrftDvtLX1+HEUAud4HnhrEPtkIj+opolp7zPtwAa1vZs3b/20d/sXezd3bFWeqmCt8K7NPX0Qgus3OuuhYpO9mzdtdTAf", + "6FmIel9VIFu62qs9JkqDzz79Yhf4EXglxhq8t7WrvKnnI6wtREDXn0Gnezve21oB1tr63gf/AA1oP3TL/wPMBfLimFfWt7aC", + "rmPsSUlDp4K0QuCe0Nu65cN/fBMVv1n/r9ZO0NZGtG0kkIk14oZoMCiAF7a+/8E//qoG1Ba8r+X7H1r+Y8eW/9i65b1/9Oli", + "cdf/s+dTyNLygA91B9I2wBfoY/XblDoU/AD6ga5KsHb5AujQA72WgUUgL4CRwmTrlg/+8cnevXvaNndsKkbQ1Ohj1xc7nX0Q", + "OFvff+8f27/c+T8e+uhs+aFF7/PR/v1/QL8Z0E6y/ofWTmCRBKzeqYDmfvihq/2f/r/yn0H/9Ff+z6NBvCcBzSnPM5AWAdhx", + "X2fLH36AyIpC7GUeiqGj4/1WrEWtD6LegKjAsZCzURFr0eps7ugAjYOHsRiAf8Cp4Im45mJfkxooSwNT+FGYhzJzoedKeC90", + "Yv59rNOecn4n5AGgnuCrEHzdD1qBplEh9OE+0IkLum/xoHPdwK+2Qvh8iOewDh07/7bTfPivnq4EfEkE7P/pT62D2DeAjKgK", + "5RFVE6j8QO/e9t8GdBK2bf5gb0B5Dlr/+qvPnEIaAJdH/Z0/rGv5ZNe2neC5VlUoQF6rcMOmP38EfFamUOhq90FbkCUpcTRw", + "gl/V37e1vNPRsbk1BND/56Z/df7zX50tn0UlB3olWdfyhz9AX5agUysFyKfW79a1dJAmsA/90db/D3INa92zzmxtb3fwIKQi", + "8W1pQ+t3LWjqQG+ux/SqXqqg/1SS/+uej1uxsd+mUYL/toDHISF/WAdSeA8/7+PnA/x8iJ+P8PPnzR3yzyb8bMbPFvyg3Wa0", + "24x2m9FuM9ptRrstaLcF7bag3Ra024J2W9BuC9ptYX/4bBO+24Q2m9C2A8904NkOfNeBNh1o24Fn0AEWAz9oh3+B0PDzEX4+", + "xM8H+HkfP+/hZwt+NuNnE37Q7iO0+wjtPkK7j9DuI7T7CO0+QruP0O4jtPsI7T5Euw/R7kO0+xDtPkS7D9HuQ7T7EO0+RLsP", + "0e4DtPsA7T5Auw/Q7gO0+wDtPkC7D9DuA7T7AO3eR7v30e59tHsf7d5Hu/fR7n20ex/t3ke79zHjDs76vU1b/gy1hMnjf8Cs", + "UeXVdVgTiSboqgLHJJEXlYHLXQgs9Wo2KvgQ0K+mlDKvpgZ8D3rDEHFFkEsRLRL8rlzsref3RbDdIuDUELqYFgWkKTg2KEXf", + "pq/uE9WG6BM6AlAAnAMdVFB9fB/JOVKlVFVTQMwwAksCe0OGBalPVQcjpxbBnlAQjnHVx/sLeGfABkHk+RH4Iua4/NfPXz98", + "/RI/S69f/Dr0+uGvQ78e+vWgfPb09TI+XcJfc2j1Er8/kb+WXj/Dd0v4ZO7X4deX0fYp/pn99Sh6OPr6x1+P/noA3z7C74/w", + "38vs4/Xs66v49yJ6wlOvr72+hc+fvr6EtgfR7op8+gL9P3x9Hj9n8HP510P4fBbve/r6At7/9PX865f47AX+uYHnDr1+9vbA", + "2/E3N9+OvB1+cxc/828PvT2Mv8fezL6ZwTd38f2Rt6Nvx94efjuMn0P4hL+Pvrn35jF+P/zmNp4dlT7G3x7EM6P47Bf0dI+/", + "Sdtx/H4YbfnfQ2+eSK/DaD/8duTNz/hsHG1G3kzJE8P45gne/gTY3STYeB0FsKYTmOWwg7E7QHW0+gk5CsSHMb811P607AF/", + "QEOwLXy36MNyJqiMqzRzoaKB8mBtAZHBTIdIiD3gP6MBatMqPQaG7gIDcqQRB3N/EL/QZIutAAYwpOUOO7sKiQ7sg/fqOIZh", + "HEL3qkKUJvQLAFgmAa3BQMz+BDYJpBmMUKDDuCTuBSO2OamHsNmFWeqmxoXRE9PoCwo0YwjRYIMIlSl6JWC3K9o7Fby75lOz", + "0ltgAL9D2qHsHq8H2oCeARwCPoCSfxeAsRPzgIkdxa6uUkHTkIZGK/mhKuIJ6FI/AZZMNb0Z+AK4BqpT70siQFciZPSMT/Fs", + "mADEG1NI/SAR0xdKQAN9pV4NzOjRvA49Q1MT/8XSlWEK0+ViwJpQa1DHaAzoQ1eARz9FiFUb0EC5plz098G8xoDCCOgvpucF", + "2BQ4CzpSBTEM7JgWrfk2hX7GklR1Oa2oEFqargtf/AvQztD2XgEc6cK0cSlasOLA6OUAdlEoxs8gRI2mQ8fQm2I8dg0REesC", + "pg9rPk3KMJPwLF5nsNhJeZDuGU7aA+m5xGIJlzOtJLAnKFTihM6U2g5Ihn5acDF9S9hQWKqBqmkij7jGd9RSMdO5TC4WNsHm", + "xQ5ALemqmlZpHhtVrQa1T7m/BeCqUlqFcKSfhNSEXrCmhua4wQbFEFDYWgrCfrpaaKYRcAMamBSPVZU8i+5JWyG9LiGJhr4j", + "7e0lsXLg5mNyAERbCHxAb06EhS0q0C/9SjWVggi5WwbTDzR9Fe2coEdvlvEAd2uwygIaSyrpS2G+JmX6KGBXmpCDLtBN4Eb0", + "J9AZxwlqekSMW3P5b4BjOlgMJWv/ILcZeE6HVV+7hPV+UMRENc1Kch70vF+ByapIHT6MQMIeNAcp02WnST1gv9QtF7jOcVQD", + "KjL9GpsHFIP5kSzAYA5XAmA9KcuOEl3VomIRJOFGVc3FhIkFFgd64E5brxzEQkx/CPRHnMREUwq2OKYahdhQETIwMQh3eyky", + "PiPVgVartch1YWrqYrIVuN2UQcUJ1wAmJRmHfjeTxoA7Rb6SBIyN5lqlSdSJ3Ul0nvZXhUwCY08F/0PKMXgZpgp0iyUexKd4", + "L83eEFLQp3PCLX/F/uiKhISM3TLBj6anz9DNaLwoLcCSqoVuAm6iFR4NYi91sUY2gPUCs5h2KShhABsK3qW30uwgX/ZSchF4", + "1/rE0wg7KgDOc3UHLfBeis0q+DOg3wUglxJBJDUMeApz6wQ19PQYuuSMonMCm2c0kSvleCiDxgZUsYT4M6GL1dDHxm9rZDDY", + "5Nh8Q18vBXdM7g5LMKC39HDLSgTd7ZUU8peb7O0hc6Jd6CURpA9ghO9toAO0QI8IPX7spQgjzSd5B4F4fGvFNf8ajCa0ddrb", + "YYIpjwZaqVZNdlHK01rt3EVipS8459K6g3QME3HlwrzI9ZCJgfjVAJ0YsIT9/dqUADwSDPe9njiiYxjf1tjBRtEdhDSeG1N3", + "+CUY0YOQ0J4CAWNBjO6hR0aH33zd++4ft/y5k1h33zckaigCDC3sA+X3qX15RavBgGXKdL059B0TvEOehtCmoRrI9dAJEIrX", + "i95EkAVWA/I+inupe4gysYMQCvQTmz5VFfEQwOz2QXPglFhR5WAem3sUbDhgLzAjuChWubb29r/TBWrohzJ0HJs9ZGLMMilT", + "54V0TvzFYAAJmJckCPBFCZfQ/VrEzmiossFcD9YfjB2nlLFQ9H+jPt9NyZAPdcItaYH5XHO+a6FHkh5zQ7cWSQWr7YEGvuVi", + "J7H4DAtRTMc/ZAeGC2FLv0hCqtR+vJkmlfiz6dMzO8jY4G5IOEp0nhMYOpToCMVa0+ddIbtQq1Ge+kbc215K0az3KVOMwe10", + "j2z8/nsxVKo5jBWbR7dELqJ7oasQt/cUMa/Y0Cfn6WpSduwJANjUpZTnaYM4LzshY0oh3VRmkKPiaDshXLpzdF9DZWFGn2Pm", + "Tj6f72oHdA1LBU6ahyAOPYedPFYAecdxDdICxK6L1BUl/Q3PQfIV0gZgiMK32K4qT1DkoKCrPYl76P4xHLyjQCEUQDR1A4iw", + "feASOg3KPKUxVLgufc2OgRA3gGqhuIaNswGUSie69w0xBF2fRrA7SahfTmKEGcnnHp0AnYNUJ5ib0RtaO3POdsIjPJru66M7", + "vgqZGNDJ09Pa6Rc3tFHIegrAEfDK6N2EVpg9z132abOXqhJKgpPRlZ6CinM9eRO73QklAwRYd84lOiyD1mqb3xPRl6RVH3RZ", + "Iw6rgukxCZCG+KoNZUceAl3z+EAH9A+adteYdp5AdPKIAgIlLRYLPjqlZ9/Q/dfRD05TsGPXtdCrD0yjU93tfPdD50fiBeSR", + "yne0fxUPm1zO1wdZlXm85cTkZ4JUQ89yrqbKUdRKZ/k2IlCeVhkw4qYe2EBpiQ5msdK7abOYH1qxgnR0dlYpVehSNDxfMB37", + "Pujo4KlBTvy4BaqORGHBKj5EGdFbAAbraqdzGTOCcGrj5pGk8phHyx8qZBIH9v6fd2/77672OCrpuEi3/g7yzGY6THnIY+hJ", + "6gJjJgl98WYzxwIIFva3Ot9/7wT0DPI0J/hjB0SaA3JyeG7nDXLFKeA6+9TW//eg8UHVXfTcx4AONR57wH4j/MWCVRPqme2U", + "na3OO92OR8xKrwddLRWoo35dq8C8DHiilqcb26kSO4Onwxo9iYYIJ7eJyzFIQE4PVqV377av9pK2HB84NtzowJanO6GFADc/", + "4AMMiCsV8iUEX0LL8ACM0DoKq+Rf8kxL1AbcwlMJOWox1JQOnW8hvS7fKS8q6PXcTN/r3tRBhdDJ4zonvzlf8XmIlqPbG1AD", + "27ODmKsAcag3c6TY5NY/8Zfv6cQG/0ETl8nimzZ35ByqWIi+nnUtVBDdng8QQI7HF1hwys6WPxaLRTARIAsRXo7wAcoaj7XS", + "+7xJeAE4qxpahzPsIW7FIR5VuFzEHCctp0OmDbzW5tHQank3SDrpeTVb3/voH108u22LUzAaT54cKkig9X4xFaqm28nlOqEM", + "oI+4apt4IgHxr0K60SNKw+6o+z8273YojWCaF3SXXyk5+Mn1bHSKfYa/OTmu3+d7o+p2ntjlQj0Y1HZiT/rd/Vqwsh8QK5NJ", + "3u8pqm9zPfvLbW64qQO72bYp19pJFN7N00LotzSoUZYYOpM6sXpd79BjETg89ICyWye77/TRliDHO9ytPDh3XcsgcQnPPkxK", + "cePxqKMApulPyFvgo5zDM1rgZwyNThDw97eg0TSq+CaCLQIZ6mk526FnxFRTGqCvZiM6TV5dT3xIXKCARNEnIjCep5OgzBRy", + "hn6UmENT6KwCkQq4WoHKitS36aspelWMefU4iFQt9VRR8/iB3hAAo4R2ZoRRJZGhh8UIBfOMNlL0dgRpiUdktYhHk9YBghUh", + "AgBdGPpUOT6FAb2aMhyLAkBLPXHa0HqPgHx1SLwIu8kjwxLs6fjVdcAiztj1477IiNtGxURWgBZpNSrTjSpkgLdBZwCaR1Dv", + "yoQ8xic005yqAgdqHq354geCKHF9VQS05PGRD7iHha1CUkSFFNMkuo4VSCzgn4ooEign3o9+CzTiMASQAV706nEl4iSjPv4J", + "XPNqocwmXIMa4L+rKmkfMDLQUFxMqUjwoqgE+0D5JeDiAa4LHVgAfFh87iWWt4L3gLagr7F3dFmFYQQBBgDlYszgHrpgDRbH", + "p1OqDE0WmwigFyuFVQUzvnocQnLtj+hYEN+UGeCYVTWqYaQhQRYYjp9FLtg5luMj2EgYC4WIy8fo1jL0koQkmvDVddp8vthA", + "sJ1ARq4MV9GWDEgbmDvsAAwDqwF0rQmTdRWaGGqR3eBpxkLQLQZ0Sy8aaKgU0PPGV2MhKgoimdaxXcDQB1V/a99hFI0gNyrT", + "qTfgqz4IXyDoV/epc0jyMWxi0E2fAnmDnmF+qYAaWQeaZjDQnJI9BFiNTJDyuB6bjK4CrhueoIUd008ohMQwBpcHnQN4OUYF", + "IvGiAWAmQ7efUZVCxENbj+18RWwrvKBMCqsdALkPqwvZTyMO0/NdhcV4NdUX8VXYMqWFpygKwAZ+bFIdcASRKYrHhh5GbrdM", + "kOsIy53+KO6qgkUWEZYp0m5C3RBon+EXhSigCxOrBiIE+OKAXh2QfXMZB4MnYGuAGNgjB3SdO40OeC5F1yclyH1SJ5mdfIKZ", + "UCkpAmb85oq9lYDh0RUlC2ithnXDJgUVoMuIAFKcqTQrgFB8TIvTh+wCZWMSEPiUJcDzVXHGisGmRKgZn8e43DLaGwDmEDz4", + "WNN900fkqBVdsuZd2qqdXkQtjY6h8Al6UutUAw0ZOudqhsMXdVHgoUwca4HhLk+v0yoNX5AeDFvKnrQCtYWnQpi6lDyENaBA", + "WAbVtAB9iacYLwM8ZUjnFbBgrBgkROeYAZ/GLiYUyyFrLB4nWBVaoIRmKI5bFvcE9odOx1iXMCo/YZwL2BaWEscJ3o2CtBLS", + "0oohFmlxi8OwR/v0XABIl5JyEfINZmdMFzgWDrgOVAxZSy7GBLR4x9JKBStAyzzm6mqvap1N+2CeeVXIOrcmKiChlU8WBYS3", + "0gR6F5IE1hywRMkT41IcXUachEBSPnZ6UMz1qgYxajJeqQYJmRLr0pFQBHPHjDNCD65QUlQsAgaDDTFAOhChYtNChW4I+gLF", + "yWrSKqN/gNECmEt0E3ni4AU8K/OkOpX+y6DUQRANZio+W/NloU+7ibgFjfX2gqwhW9xyLHFbFYwQBE+fXVloLKSyxTgxR4h7", + "kBrnCn77NlV05CWUOXSwGToguYOchcS08KAK44dZSSsbaxXxcBkWFPrB0n9GmYPpJHRKYW0ptitE8BqyWTNqSHtJVCoFWtzQ", + "oGueHpNufdeFIgUVEVdVatRkgypJYI3I4XVSFCd3WbAlo5tyPYxp0x7ovZgGwsk1sVXFY8J9By2AtlwMh9KpZP2QRu9zGYZC", + "D0CJ+4rxlGUxilDzibjErYfbYL8wNigH6CfGeUTxAClTfyUrRjYHgZEpCS6oh13MxDB6AIBbNiPnEPzRKaOTknh4yFMkINAk", + "0FmRIKEGERpURNDQW+zCTCa3+qHE2ylSyw5x3kWyy+LPhVTxvEDv4gkkxeEgHZgl5dYqwuPY7LRUZmyXFrCt6YMv+SHHraCZ", + "fL4LCsElFocAkbMCT/xkhPaMfVEcfyTnqUI/NTERGQ4BNefS3oQcAL+XPU1JHQstgWOJAVKIi6TCWMGaL55J4TUtrnvzhcgW", + "L6V8sN5EOTswjPrSHiGFdSzBFPIDcC5Wr0RvO893C8I7dOUxGgusYz4W2UWfLC0jelZdWauCeFmBYmNVBR1g96wvDMKDdA5I", + "l9QwC9JeFZZj0mYHUaW8rTDkp0SPIxR8CnEMWc/4FoAf9N3rxn41wRjonCeR0qqByPN8ciodYSR7zrFNvAhYR6wDqBACQQkN", + "8CRFe3SuaG+HrCEWmA60Mp0VKmB8IeMJcw7sG8gNrgls9+/otcEAi/6+SI4LPhE6zzM8ZoML4UEKIL4AXMPkAwXUVf5KJGEi", + "M+I5Bvk8gQzyhP63C6fD+kiTmriGKd9KUdIrEkxR0gOpCUVDKnG0ViOIRZxwB2PNbz4XCS9aCLRN93yv6AIR84Yj0N67YcFU", + "O+nUN1oMcYeqOvS66LZ1eD7uy3lNdw7MCmwh0X3ASgMSPUFraKuzt6wdjx61kpxLme27Pv70C+dzsAT1Mh31rtgDZZHMSkyK", + "T+UtFDyJ2VXBZutekaXgd3CDh7/dxB4LgHfA6b3CF/mWli9DcepojyZLrmcPcLhfFWeWKUtkAnYNPXwpUiKWtRciNqH4E3tF", + "2niaThu6b4Oas0HnS/mCLjPuIiKdYCIgHJ4DaIkCxA9PncS1mxjCQpmVb+zxk7eFBv73hHSeorfVrfEECEpOYl9h0O9nlB6l", + "vdBPT0HXIP3axP9P6VRNRBt6xDOh3h1FdAgoRn+KQ6TlG4rsnHhgRQ4bk3PaYcPlxRqLJDJVKCH+ch+j0Tg+bDCkmT8gnBsW", + "Jcpqp3XH0h7NqWqV2gzMk+uRw0XDGNd+wwhgMcFcemyhbTBnjFZvg1IHSuSyEQRjP/eIhu0qxBjLIJVLLKd04pfR3vff0y3E", + "+ed6fKvFwGOqRs7P9TDWCPJEh7A/IddSyhCAuFDc/GYTPYPfi/rhGuIjOU3J0XODt5OIOjkTJbpMBZvkjIGfgMhjHpQUsRzJ", + "VnE8OHLild8mWkAOloyxx32UG94n1rlPf2D89d7dbR/l5OjR2S5aIO/8HeiGB4V+JP5i4LeQsUEx0GbS99+pRKqQPsXXAgQF", + "AZ8ABYEPYNmUuONkTXpJnO98EysstKoJenHxSnoNcz1lkRhcDB7mkb/lCMnIeWqnLIMnztcuWArC3dzDtjZGtkJC+UkNk2G0", + "CJ5XqXjDnE1ymhEVEvqnidOMElfXRufT0KWjRHs14SAHOgT6RQ6O85To2pMTodo3JNb8bkF0dFxr73PRmIHRjl/cI5gNe92v", + "a62dEksrpnVJsJkcL5udgoF/YJDud2AfNN+OPrvai0LhcrKZLwoeljMK0yWeXh7cOB1VfFZRIDoMS0zgGGYAbDfBJ56cxxlG", + "zfjh++KMolMInEU7IMwTEG1QAyoRGwCr941MSSjBCG8qOSneWBTtJuhLYtFpAWOYG4Q74l7BgaRd9uzVcj0t/0lht7fMbYbm", + "wUz7CGlqjGXvaudRb7EGHIsufNgzcU2OcLt3iBQVR5yj5ITlG4FxPIZVHuXSAHSxi7WV85aWXrEOnJ10BrsEJrGc/BvxaHvb", + "6L52GMEb1Lx/ny/nepgDwHFS4MlpuqHZnBqJR6CT8p//6pQ4hHwphfETAx8w0pUj3MrTWe19SXDh8Fgj50DKpTyRwSbDROBh", + "mJw1Y5UAU4rALtBoO6wlBoMZUlSOhHtF+7S0/B1SOVEgm1iiA7biQUZXx0QniaxertX5k5OTHe8ppOQIOcc1n4uOpsYhkqwK", + "BKRM5jFVrmdAwg7EBo7lLBMaCmCFlmBC11oi2B6bB80UqoGefoY/G8qNXI8cTZtuOR+WA2GnLL11WIZvafk0dBwJk9gDO7Xf", + "b5NFxDsgB7eLxpezQadNaGmzyBzmSOR6OsTl+qVIuTYRTxXSFQiDdMt4RqdD2NGR4Agj1kGrFuuP6NuPGRuXcxxrJEjPbcL8", + "0F+79lW3ypEqcyb8kEY7ECMDOYyca6yTo2+n5Q/kwR4Gh/0Bn3s9LfJtS0GVGTcUc5NKjLQFT5Zg0VZljiau4t8SMTO2MjdV", + "PzfamB5aeXm6MX9g9ZczK8vX6wdm8Hk2+bI+dmpl8cHK3NDK3M/Z8INsYq4xfb1xcqQ5vZBdnswmZlYWb9cvHc/Gr9fPP1s9", + "/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", + "OgGVZmPnwTXYx2zuHCgtmxlpXDsAtiLdnribjT3js8cWsqsLIA+sLUaF9iCq1dHjnCOod+FYdu5S/cENUC+oEV1hkckFC5PN", + "oUPNmbOgdpLi1fnm9BQGTII8s5wtXKqPYbsXGidmshuHVu9crM/NZCePcRnvzYIS8NTqEETNUDb9E/du4hQ3/fSB+rXRbHRE", + "XneiefdmNvIYI8TCikw7iv6zifHmk5tY0vrYOUgYMAJkzsriTXBc4+4MFiS7DW5dwDpzpmeGsjPT2SiG8bBxZxESJls4A5mD", + "ZUF7UCOG1HhxrrkEwXIV3Ae515y5QSrF1l8C/z6mcLhyOFsaA+/Xf5yqn1lqLB5uLI5ijo2pc43JJ+AakEQ2Plm/fBt0Vb94", + "cPXcaQrPsYeNQ1Or5++hk9Uz06BerPPq5SvZ3Fzz6GxzZqpxcSlbuJPNHatfmiQ93H5cnznTXDrU4BhGmncPc2XIidMk+PP3", + "6odBnwcaj5ayl/fr5yHGKZ1Wf7lAaXMPgmt+9fIN7OPq6Kns1mHIfIiX1YsnQYqQeKunn4HdyCmY1NjIysIvjSP3yRqLE82T", + "t+vPIWGucYTTz7CzjbvHQXIih59jUmS68evUJqfGm9MPIUmofRaPNp/cWx2daJx5TlJ8OZudPp69OEsVMH4bLTFm7sXyL6tD", + "V7Mf72FVufUPf4Ikx0QaZx43Z0il9WvXsSPNmdvZiZFs4lE28TO4oLl8BmK/+WRqZf5hdvJ44+5DESYjoCgy4MwT8hTE8sKZ", + "bOq+yM/T1C/3jmYLE6CT5tiD+qVD2enr7I2b+CybPrSyfLk+fqs5BJlzZmVxPLt1v/Hz+WziJkRrfehAY/wZ/31kPhv7pTl9", + "C6/LlodXry9C5kMjZA8n+NKxU9kQqZTf/vwj9G92bLh+9MHqwZuQD3gvJSHk58gwxdFJTG2enA7+vTuCma5evAHGpN5cHsVQ", + "G2dmoVNIqJCcowuyzsfxVX3qJqQ6Jli/cLV+dnhl4Sjoh/r32ijmSPk/fr25dBqciDeC/LDjjetD0BcUZQsjZJnFhcYU6Pk0", + "tBsV0MlDkLckKiiXsR+zmXm8t3kE/D5DjTxyjPwLWXHpauOnw3z2l6ONqSONhbsQ5tkViKaJ1Z+PZdNXyONjzzB9DBVQAeNp", + "TC0Jvx/NTlzNxibr569RTUADAhIMHSWuAHePjdaPjWbHz5MLzk+tTo5kkzdEJwpzQa1PXqtP3WoM3wWV1p/PZpceY44kOejT", + "51eEzq+CyDEe6JHmMub1AgqCzE55eBqcK3qEuoZqZeYwVFvz7pFs6Tw55fgJqrOFqWz6GIinfvgqv5o+0rw5jAbg0NWD09QR", + "EIMLd1ZvXiUKuviycfhZ8+UDopTx2+xt+iGRDGT7dbz3GBifu/bwFMXIaUiwS83by+BEbOLq8I/Zwnk8Dn23snih/mAJEgDq", + "nlILuzx9jAKWyOQcNB006eqNkWzmBVEW5ntsERQCucH/L05kw3Nc1clr2fzjbAJccBhcmd24Aj6tXz4JdESyvHFlZf4o3tU8", + "QE1aPzuGHSdtzz8BMIOyI8WCIMG2M0eAN6C2Vpan62fms4mDK3Mn6kdOZ8cfgkMhjSnlbjxs3j1IcDJ1gWDs0VLj9pXmieey", + "UPcx2cbi3cbi1MrLa8AhlP/QifeuAylBlBFvQAbeuro6Ody8eKJ+Gurs0urNE8AY5Menz6HlSZ8vTwPVNK5OEbJevo6Vrz9a", + "bJw731w+SYSzcBezgLqHxMOyNMeAYMdAmcSfk1eBEMhWZydWgaBI24fxCqLHh4cotB+PEjECwY7faz65CgWRjYBP0dUywCeo", + "t37uJeHNxPnm9D0sDnkWCHni+OqdMaKsFwsUv0N3m8cOZWB5IOSjF1denFo9/wjrCSKklrl0vHl3iIJ94iAeAbNASJIHsb/L", + "l5szwFFLK/N3wODciKdHoRkbd4ncwOBcHCiy6Z+aB683blPv1M9NAYkBXVAHYYXHr4B3sJvArqujo5zXydtQXkQj2LvJabLb", + "2Cw0b/3UYaKLS0eof2+NNm++JKqBIL20gKWD1sumzoO8sdGQnxTyI2DYU0RNl2+QI4AeKQ+vQLCwt4dPQGCgXuGmcWCY5sMb", + "+H/94jS4iVJlDmQzvvLiGqXB2C/1qWP1yUf1o7dFj0wSNg8fJwdN/EyNef4ZFfHj0ea98ebSEvgLnMIdnL5BGDl0AL0BeONd", + "MBlolTx5AundePYIuJTIHxpq9GewD5gd74KWAdQBua5evs/9WqCGpRwG3b6AAroJ/Z6NXVu9eIuLPzbXHD+IhQJuwY7UH1yv", + "n52Dys4enqImHfsROA2asX5ERgV+PHmCCHD4nrz3KWTLysvHUDqNqTNQDUQay5dXf7oEoYcX1W8OgcawF9g76AJMs/7oR240", + "ZPXcXOPMT83RxxzPyRFiQiA96EpAmluAxM/w0uaV49n8XOPOBDE/UNbLG1RkoyPAupQngKywccYe1ocu1w+BCE9QjxyfABdA", + "E2FqxM+3X4I7aMIcOwJRSVKEBJuHuXSJBPbiF9AMtpvGyxFIj8MgRWx3/fIyaBUgDSILjEZz6cJpzI6QbxycMkkRDZvi+CgW", + "nGp64Q7368h98tTZJwCiGN7q0DVKTtLY+dWr9yFPmk/m2A8miK2cnFs9f4nSGNrh5Sw1HawqyHPgmel5rjCWa1yspMvXIQ9p", + "KgI9TnNrQPACcp5ls8NgHEjO5vIVMCkUUHYcduISHqRp8Pxudvs2RAStGGg9GLCXb1uTFjQM2iPNQJlC6UDaj1/h4oOp74xB", + "o2GDwF+rZy5iozmFk2PAexDp2dALEBgnO3mqcfkm9DJEE62whZ+hnlYvUJ1Roh5Zrh8dhphdPbssHLdAFAGLCVoYtsniE3AZ", + "hHN9fil7fiebeAzuXll8CRKCpgCLwaqC9oeso1EG2jhzNTsF8+omuAnwlTY46OcFqGK+eeQRSA7zwr7TVAQ3QWLAwD8M+jlO", + "UT98l9sHTQrBuHySZAOhtHy++fgmMdszAPLR7NJVQuWnF+uzV2HZUQGduEfoC6MP4788RX165C6tM5Dl0DVIG4IWtJlfFlty", + "oT4x0Vx+mE1cgJVEll+8Sn4/Irxw8X5zZokQ6xglNnEjLDi89MQiddCR47DKaR3MPwEV1S8fxNhAAytzL0G9VN8Xod1G6pd+", + "5hwhb2mkwM69CQlDLHRkLLt8vrnwC3YB880WRjBs4HYSnvAL7fFLV5uz8vkh2AKXCHcPTjemZwEtaKfPHoQSzCbOQZZSG8JQ", + "nZzDyoO1iYrHRlZ/vAq7Bn82rk8TV0NWLx2lZXR5CFZD/QoshYvNGSCiaaKg6cvNJ5chUQlabp7A3OsnxFqHhTXzYzZ9DTwC", + "sUO4df9s85dzjXNL+AqGCSUDRgLB+8tFatLDy41fbtdnJkSkTGW3LEeP4BNqn1v3609ug62IJCceNg7cBEUBo2LK9J/M/Qx9", + "lE1foDsCJgOQ/+Qc1fTYhcbZ24S+eGoJZt0YjaOlZQLpySlQIO3QseVs9mj92gTFEYxErDbIZvRJ4+cDpKgDpwWIPhB3ymkw", + "Rf36TVLs+GMIk2ziTnbrHPl3+BDwPE0AAoYLwGzZ5KRo5+vNn4HST6z+dLJx9wDWist19zBUZ/3ZWPPJfDY8Cy7Lli8AONFJ", + "BSN07g73/eRxTLZx8QV9Iy+GYElRjVKznxdNQUqDxIBNQctRLDj8jt5grYiJehU6moCfaJM+KKIUIIHLV6GqsNfgAsqxYfoo", + "sDhURi8uNO4OYRkB/LAmEKGrB8brY49IRRM36dtZuJU9nCXqWL4M81wsCDDyQbyasoWYii6ybHaWJAd1efgquLU+PU6Kun6l", + "fvJS9vBoNgtleoIG2tjz5pMbtJVuPly9CthGdxA+IZy7/BPlxvwjmEWYHUUcMNXkOC3oi6fwySr4/dgwpLr40J7REnw6SQgH", + "Q+DopAicYxgMZdqFmcalF43L2AtAlCfZPSiISSJJrM/xX+g6eHGhfugayDK7OUphODzbPDJDJ9jwMF00D+5gx1cvAic/w1yI", + "XoBAJmZgk+J10JL0PMBygXVJG2SJHoMbL9DPyovzAL318xP0g8FaxKZg47DRU+hwBpSzOnSQAvbEVew1QBfFIDo5NwpaArRu", + "LC5DyjXuEQU1FsewYjQ6jtyHHUcfy8lLjaMAgZPY8ZW52xR6D+eay5eykYuc8qUjsGQbv2Cdj8B+ac5eB5lhoTjy2y8bi5fx", + "YXb8AA3b5UPN5UlMCoYA9BGdTi8uZOPLbInBP7jZfDqRzcNCOUNnJnACmOvkKdEODymogbuml4AVIXP4lqeHgWDJNdeerP40", + "0bg8ROl06y6dgRdm6jNnSSEXFyirj50jl00fI+Ngs66egPCk+QPxC6V/5DTkbePMDfo37hwUD9U9Wn/LlxuAWJPXGk+uUT4A", + "WwJ7H7xHXDS5RG/k4UlRPeCRm1BbAplo41ODTx+pn/ixDuA3e2R19JhIuUmYbzRs7y+s3jkH8EyL49zh1fuzRNdzR9GG6zAC", + "6578AjN8Zf7I6oXH2fAR7D79US8OrixMZyMABkcbJ+5Txy3dwr4TQz48BaUMOqE9fm+WWnv4ObptnFkEaCF6eUyjFeqeWBRA", + "+tBL0DYdd9cfUEfDsrh0tD43XL/9U/3klcaDU/QSXzuwukhUBsoh2c9ebR6dwHYTnc4tNqavr154Vp9+2ry3mI2MN5YXmzOn", + "IITBONmBn4iIXrxYmT9Bo296hlv2/Hbj6FB9+OjKPADnXOPEDJn6KsTRItd8+SnRyBU6e4HiuJKwlI8tYzpuyjAOHQ74jOvz", + "Yt+TEMnYD33XjxJfV6pRNYq/TbWbMlCFJ55eJAGzoQRsGtY7iJUEzoZhVCnEWuJnw6qOmYSlGL8qIaXG9VNPeXLOHqk0RJ/S", + "j/HkE4maj6uxxnuNLr1aCCWO1AxEjOWQwFLDdJJQlVWBucslOUhjSK6R0EIOm9Eo36Z+1QY+GomtNSoopaFyozjWkU3uZEiv", + "H6s49guMPkRvZRm55gE4DzI4TlUp+GsRiYw7Zai5YaDfq6lQK8btuNoG4UrsqITmFhRDcGOJhcV4UsbpSWxPVGHAZjDAaEB+", + "jvnKKhkJwDUSpBtKVQAlkbyG51CMZuYpu6eZzx0VecYmkZ5G4mEiZk74SoIzOUesmBtVqjZzWxuJ9uGuxXiBL+GZPL+1kZCx", + "xH8aj/E3mGPs+qoaeRgEs7WTyPM5UPxeCCSomFECmGvA+h1+5Ma+8bGbzEPCTqXsAb/rIikEqxJjZSW9SmsGRkUSQC0Ryp6S", + "HlRU5OphBdBUt/HgnCujjJyVG4lVixizZPtnNChWKpK4QSNR1waT9Rlly5wRCaM2sdr/6jHeWfA505QxblGgvSjRIfYXk321", + "YCQ6j9GyfqgY14TxcmWUy7CmyH113fP3S9wnY//wlGR7Ke7+flK4H0TYRY6ZJB+/ur/PxztePa7q/aQqTw28mvJ0pAd4dllV", + "zAKuaIaQM5SVaUBMlyi+uu76gasKeEgigiV81UOfeDrqU1XMQoJhTUEoRCKnjYTRxhItHBZltbHX3HGG+hpJ1+VMMfeCHxRU", + "RI4A4ZArDWOYlMQ3etHrJ68Xf534dVSy5BdeP8TPHLPefz0unzz69YDkyj/G78u/DuHzg9Lm6a9H8HNI8up/kk9m8dtzyalf", + "tJn2r3+UZ5clC3+KvUmPL34dxacvmK2Pvxf5b2bx49klyep/jNZr378+w7G9vsr38jv0Jxn8kmH/4vWC9PdY+n/E3mVsL15f", + "f33v9Un89yGevWtnIc8+km/xJMZ9Q8b8RD7jW1/IfGXW+PZH+QRv+XVYZs2+WWOALZ/gn5fo+Uf7xrWxMdf/x99HiGcPrPXA", + "NkPocfbfFQPm8MRLWdMr8g/XekTe/lDa2DoGrCywJJUDltAzx2nrFyz9egC9Pfnt1tnfbo/+dmv+t9tj8vvQb7fm5JOzv91a", + "kk+O/nbrzG+3Hv5262f59z35dkIa4P/Lv92akqdG+SA/QZtb8tS8/HtEHpyXNjP8hf9eYhs2vo3f+xR5Wlpe4v/51PBvtx78", + "duuO/H7+t1tj8tWS/D4hnUzLG+/9duvpWp8c1e3f/413XZCRXPq9nyF5nfTD359Ky3vyyb3f+0T7IzKL6d9XYFpaYgyP5JM5", + "6W1anrojn5yWp0bkwwfSYEo+eSDd/sQH+dU9aXNe1nZIeht6M//28Nsjb27z329H3zx8c/fNjTfTb2bfzL+ZwT93f/8cP0+l", + "rsPC2/E3s1LJYYT1GdCeNRhG0H72zTO0O/z20NtR/H0Xn469HX57UOo8zEslh7vyOVuwYsPP6Pkgqzug36k399ET3vv2AD57", + "jt7u4e2z0vI2R4XfhtHiLlrOcLRSW2JcKknMv3mGb8ffHsDvU29+kbdybKPo9ybf+ObB2kxG8ftj1qLAeEbezMiYHsu7ZjE7", + "zpRVJR6ylgRa3pTaFMPo0Y74Z5kJRoCnWKPiKZ56gp8pfDIm1SpYDeOujJZP8D2znNfvz2KEN9H3GOZ5F0/fXPt8hG+TsXAm", + "Y/jnIMeLliNvprna8tvP0ucw3nj3zXWZ3bi0Yeun3BtZn9m3B1kdg6vENZZ9mZFx3JT2WGfs3c9cXTwxgs8eoI9hGcPP3JM3", + "D/DbfazSCFqO463DaM9ZLLx5hE9GMIfH3HEZz2Gp0sEVtqM7iPW5J/O+yxVGTzeFRli14zr3RMYxvLZ3h1jRA9+S5n7GNxzV", + "vX+v+mNZmUPyrnmhihmMD+OSt3Id5qW3Uel/lDMH3cy+ec4xSGyY5AYxRpKxp2mQlBnkGhRtBLbAOgY8pVWJRpQwJY+VNaS6", + "g0SqFZUp+1HYZWPsJeQkrgHuSE6vRNMzXZ+622YCmDgNQ8l+jvg4qxEwkldik5ldwzzOQR1I0UXgMzfQaSilF0LNrPZ+ohsV", + "1rwa1KpNyzcS0Deg3Br6ZLR5r50Ry9GgU8+X3IhYS3ZyLPPFGwosP1H2pWiEzQMwa+HKfAvDXXXMeFdGyLD4QJmR0YGNu88r", + "T3IepbKH9ga1RDsLtnSZVO2lLsvc8C+AGYZ8Mp3NVaFNnvBMKtMV0MzcIrfMtIU0ljoWzDJhwZECwEVNopSldKdivqcUbouZ", + "mIDvKopp7tqGJRpZAgKCkFgBgygxzg8gRyc1m48ha81UMonJ9xJAnxLTFBhpaxiWyXi4QHJ3CdZCQneGKNcI4jFcpowzzEmC", + "vphSV5XUhICxTDaXZGMfOsMjeLtsJ+uuoW/7pd7H4FmzlltRYLymq3dxpqa8w9JZUo4ZcrVHwqUdYERb9oGh8YkakOg7GgiY", + "u6QblXQvSIGV7ohn45qnXUY2MVmVySO+4f6x7geWmMUT/IR1Nhm8WJKEuoD0wZQBLS2NDXSS+hisUSH5rizeCHhtsxyMTcow", + "Nj6bRbu4ZiQw7ABjgH3JDiFpeH6JyLzqu1yebbbmSoXGBldeMeg3sDtt02SsRaQCEC4p0mZPtNuweCNxnQCNWuLGGCnL+aUm", + "cQraZnaYv1lqTZlsENQ0k8485kgwYI0B/sJjA34ESImFxOccpSQdCM13tadBz7oWBr2yqEAgdUkkns8PGcHH0E2m8pW0slNh", + "ATSAeonA115V0gzC1L5/p527qySt+++W1RhJmzIpB2zkgsrBI9rbxvIhTMmgfQPSKHGrHBvnZoN6GcdHatiWMussKelE5i6p", + "LYZDwV977Ba7SvjXJsgwz0CSXYjqXc38AW6wrLUh1cEy6d4kb/rECgGn2wn1oLPD7oNNbfJ6SSEq+MLKHsoQX0o4kEnA1+SH", + "HcxuK0k9ogILMjJk0xS05JJILLj2duo0MUzpCUnzEr8f2zo7LCaTDOq15P6gZuz8QFKcdK9lX8iXKslzX9kv+AkTft9pa9th", + "hYfUwGFC9QD3IUolCnQt72UtOWaDFVrVlDagFjndnbMh9w4DzqUwh1DIp2JLck9ABcwiApvVbGKLadvEmoItkogQV3ZYYcXi", + "tKHNCiKBVZlaU2KBFIZJWsEpMfza+5jUH0IKMwvIY2htXOnxYbmknh4sa0tSzATxeu2OuSphoP42qwNsTpEt8ARuCH0+L9JG", + "15jngpXfwezAUlRmyRFV+9hyODOGQLQbrQgSkgIpatalLpEZB0i7hoGJknsFwqcACmr5lhYmC+C1DojMA+2AA7ZDMmBzd1Dq", + "QkliiR2Wm/TRSn8aSy3qnCMZ2DaNw9C+9aUoM7MVPrMivZxKwqMfOmwFSaD82OzACjKdmRmGKijENjzblzyrQFqXtrIOb3fO", + "Zk84a0lKjPTHmoGZK37KLJB+zHZbhWVI1S5PcuP/Zef+udXaTEtxkkgiO7tzVKaB3seoaVJBIpkHBUbODmip+KXjNpt+Z9Pp", + "DGsy4HGW98Xcd4MZitE+KjcGJkNX0WgWYQWVtc+vpJWyFXKQK74X1CCfK1KFFFQCBY9xsuy3xHsbqW2FqWAE2uZWp6z2GiqT", + "1ECeeKvTa3FIzAzFVFOWRJXaVxZWYM1EN1ImU8ChZ7xPCXnn7RJss6hkl0eN7BhdIhd/FUGUJ45N5zB7lOtb0czcgLTqDEr5", + "Ioa7bh3UDst+bxMtuZalYb6x2XosuYRJK1cEBCsoY9+l6Ib2tjoSyptYMFSg1jVJATtR9BPGRWOAvVbAszIp1gwSGB2aSiTy", + "hXXy8B/fOCxozrnHRounBFvB+tTdOVF1IGhWFhpgzD9TEbgPUrm0ormi+/D+is0HjrVNDNqqxa3mYZEc1gVieLYCD4tKHlQ1", + "LrmzLWUeq80yMzss+LJZZUaKwEGPs2iakdQQDEIqYKxrqbKmNTR6LKmRLuuNVxPBbgwkjiVZzQZt2zROFgJjipyzfj0ZDwKE", + "c4cyDSSHFcIcMsSqeQuwtAJZgimZVi3igslqpjUvST6Sceyu5SFBk4hrx/rCPBvU79gcnFiKrjFOn7WK9C4J8ocwFm2/lmS5", + "w0I/X3xmQQhZTuiQyjZ+Y1MimNJBOmNAdK6HQjwgLJTOqAjwXRsgZ/9aGpn2/pqyPDL1UVUqxEELV8zeMlSccSrRfqIbbqMv", + "ZVmY1qgtM0PAU9xtFYraWGb5Le19GdQqABrfWCFpE1mNFKfCxACpQt9dy6K06YyMzwdSFB9uIsJDdsTmx0qRsaBWsomwUiIL", + "9GeL1FDxsRurFC3l51mVouxXWbDHZ2qtiC7JziFMYUEiL01kq5gdymxECxkT+b4kvBYwGYE5hNstngf65Xt/cKQwzx4LJ6Ei", + "Ka1Ysh4kthuEAUFv0xONZNJpbxd5hxqnSG3PVFwAHt5XAGnTq2UubXaVdlsozTyyqMgiJiwfJKWLqK5D5lyyXNaGjtZ2lpLu", + "k+raFBfWjOhNdLWsQyYQ6NCJCmJUSHmmdS2fS+aZwxXDUHOOFL2xKcsGemU3iLyl5XOwkWNzs4zE8mMfrNQr+gLJWCQDQ6PD", + "VMobMusCFoqsEgsmuT6MEYB0Y/osLX2sWSzA2c4iOWnFlibqSQZ9QWYREzNqrO7O8nMKuDzWjk2jYA0Z2mPlmE5EMi3ZUXKy", + "BFxClLJq8boWZ4c17kDr4EmW9DcYIN/uKCNv98E+klrYRbbo6WLlewAJQQ7rWmy+nrFj0XZBthLMohfXIuNNNv1Ayou1OMbu", + "WMHWzLIJp86glrS8jg5brw30DiIEDKUEk8ofEJ4+VbhT8HmtQo3XWzgsaupwA1kcHX+9GyuohE5e18DK26y8FpY2WOLdiX8B", + "VTF5j/TpMzWEpYD4hm1WlPwNsAz25wCIkV+mFDLGZQlCFYhqdbr/boWHVAmDiHVEndpkFa9LSWIvE5GwmM42yN/YFx1X1jt/", + "N1cTKBKP6S4DnBHTljsLioLFsDA3RwYJSKMYIgNrSh3uKNqUtD6BR9nZX5mSCMghmSaS8EY1YdM0bBqIs1tyXRyiGbJvrUpy", + "k9KHLm3Fii91EUPHL1qjKbEJYR4JCK9tt1KgYLNt2sRu2cqKnGL3My07L/lTuR6MDG9NYIMEWqw90rzk/OA7LHLqJ7vlsgGP", + "eU/kC+oBZaQ+Xq4Hs+Q62zRZAEjeGNDDazGcgtwygk1VjkitCg3UuNYumVP5ooUAHvYE6ozFaaDZXIvZpeSB2DK0vvxEtH2Y", + "ikj6q9RQd0RUmoTQD38WpfgkZQG4kmW9WHvTChRnsBxxuCTSlEU0pDCFAcjHeGXpWDJT8t1tQrfplZoFDsv4czejCreTSAlE", + "Rf2HF9mkxa5CjZvpfGEh6h7r7LApryynSfZg4hJ0eS/YA/1JTbegtoeaCRIycniCRcsmpZVMo9TYKgnMGaZ2MpKVbHiFCpaJ", + "9YRoZSnJa6LFDqFjkwg3tNlELDEjcj20ehK/2mtNZ1vpwOxN434MQgqn6jgvJTQ3CC5oaSlYGpTSdbyGg3maa5Ufur9iXYzY", + "k2zyoFblPSi+mMX+7ylELZLqtPWPaSAMJIdmRi5SEAkGU8CV8vACHbSbrvlDjBRTxcR2WieXXdaWrY5UApS6bzzGSiEcKmJQ", + "YavonsL49kl1O0lvXddiqxzk/7KvEjgDcq+N2GqsAMc6Atwk3qmANhr4uK2tpzUPjo032Iw9w8tV8ADrQOF/Ylbv139jGigI", + "RdJEQeOx251r32N9SB6zy+lJEsyXWCC4R0ppOLy1xvHDv7JyW1neTIBpbbUuyUbvUY7AYN7bEK6XK0Xijc4u6+EpwrYjKiPD", + "RPEnKc2h2jY/tjUOZCogG1oun0uZlcDm+pk9a46ljUBVnuPYvME19w9L1EomfREs3WJLYJiP5SYdZ5u1c/hsRYmes5UxABBr", + "LHEnOkBEM9sbSi8gXt+wdhwsc9bJj5iEBhycxDtstZLPUwNkYv5uzSsYVBXBpuK9o7bGen4qeaIbpXZmUGunnfuNAsvInQJS", + "i2DDtlTKLJJFQW7Wu7Xx01A4DpCYO/aJdnhJj00FN9vkMLbW8oc/sOLYThiVGkLI2mqSDJfrYWo3WEZwz369DXZfWVU22NIR", + "31kGqqbSdauosQ0267Fl57a92/7p/CdxInCF2EU0KhKMXhLX6YVjdcWa843U+1svYgayTFI5jV/cQNjwaSLDfZeX0HQ6uR6p", + "Q8sbbkAvX1ofp7ZAl1fiiOxh7mZYEvTjRKGU+xVYUay5lHzkKuuXSqDzB0Na1az5GQ6QPIVRwxI3DN/xChCQcM6BRdyd85iy", + "HVXtGxLMgRRgM2QNjH+OgtUpwc0qcGm8t3aKpLDJggoYgnJ+QNS/+A6hXrdZ7ytr8+o0VtaHJEfaYJUgICYaXJuYqBkjzr9i", + "TQSRVF8p+mRtDNpNdlqsSJMVy9Mie+rYgiuSj4lePpOSB852atioSG0o7sWQF8dQDYJS+umk7E8kOXm9TYzMObaUTfeglabU", + "8l/5pc4WmR/LYXCG27BRGx03TqV+Desa5Hrox0S/UnDTsJgdjWwaBunvhqaxWcEO2JAuCsGK3U7LOil6mURSZOAra7HvsX7h", + "3RZr7KGjgKV5pHTF3/yYpLVWkGGHdWvtsWjU5sJ3VgkVWOtC0eX5mVirjq1jYraFAExhzep35yvr2tllrXJrfhjXUjk2HZRi", + "oRgdKGL1tNlCNF9YPCi5oACZv1eHUCwnZEtyGN6yRHAixYKMSL5CjfpW6nbH/egT9AmCrAF80hXI79C5svKMF0Zh41paeqEo", + "nfVSBXm9rbph+nWNBcNF9wcBU9TRUirWtnbSO6kHHVutx5Fa2RCmscMEZiml0Lk22k7xvUIfSZ63sQmwDr0ROij2Wq/Kbi1J", + "2wOihLXUQzJlemChlhL6l4BkXamZQHXusEoUtafZmfZTKtoyQRvFIPaTQSvyeAsRNkA5kmKc25orJ0mVbwYn2qoTLVJ2KKjZ", + "WjSxaw0HMjp7F1wX9trjBPo78aKA5ZyTWtHaFhTyADXa2lUmpaNJ94oV6ZQtXX8lJU5CqR9gkm0B3SlKlI14PWheCfbN9eQF", + "hnpeJDiraBeE9VfRhv4QlZR3Wo23w7qObc0b02qVDYawBtN4IxxRghVd9Ml9ag3Nol9MNC/BcXgZW15Kd+blWoLQK9py8rDV", + "WEoIPBVIvnYJ8tvtdj7Hy/NiZEP6WWRctQVAlCN1rVl/DUvACvYUAuL/cgpitsS82cyh9Uw177BWgsPgFsH6sVQlWStyxAoK", + "iWinROoBB1HqFWO6WtDZ5+Ks2MTDLvp7YEFC6W237mGi/kgeYIjRgOVbqRAP8Cw17DxeswKRYWs6OFJoRHufWb/3J1IQypEb", + "n2q8OAh/1cTbBGkqBTMkaogQg5Xocz1GRlDiVT+gwe2Sld3KqnXY7NjWXvoYyphnZ9gAB5omZe01z9YjMCwO7IBYrEuPZTa5", + "xdSNWAkldo6lSCkAgEehubzITWUhy6ytL8X0WZmmmFoPlGOLXvTsZrk3U6O2FzjVh830vrbHHhyuuBQiHvLYM0VHnAGuTgVc", + "OJ9be9rm87doGhNhUtDiW4Ms2MH6aP4+EhG1fcV3/9gh/yPhxfRLeYCmji005oi2BWIBscgKAps63VJfmOdArNph9lhQynsM", + "iCMTeW8xFef0gNy5VLK1mKADxMZnbBQsWanirdfqvBjymKaXTjSKuNFc8gercNjSZ228JYb+AhWSWWxmPZbSIRprzUNrbmgV", + "p1FrpxQOtoxHrW2lDU9TqY5in3X5bMkjw/Kr+LGeWfC6Q2G3Q9C2sdWnnO2pGJprNYz2WqsA7Cv0XdWsWlGKPFal26tKpM9t", + "wlRbqbYgWL6SCi2gdIZgyQ2UEEi29MG7n7EgUBAOaocsscOex/01hVQ3FWuv0LVCXSUnEw4kvuFYIOJowEnV8PUbhfhgTUVs", + "HbSIhmQ5WtYnobVBq3ANJkBVEIba8la2apjZzhoPsdT/4QE4+R6i2dIgL890WH4+ht6Od1s3Ux9Pr2F9ii7P5615TGgSstyN", + "w6tTbGki1sMB34fyn8TGJOYcOb6JHdYIpgTF68JIbigTqoMMqVVAgWIQ8HYLHXfYshCEB0C/Fo/n2v/T6XrnnzvESHO6I3GO", + "OLRdwUdytZvnWPRLs8X8W70YxxoXEIZ4YFAOB11jq5/x2kqWTuGNkBSAmD+Xbs1HKtLNcWypuB/Ea7fBFhIss9haIdo3aFWd", + "nZjHWm37wWOOF8E0ia1zPO+Igh4czOewnwUxiEtS8T3aynXDWucdcZxZd5H5/vvvfugc9AUCREVTC+3y8JzUSE1STQ8niZ1V", + "V/bGKhVB6hhbwM4aKl1gp15ApW3WC27N3Ly1BpMd1hoUgsw5f/cDgI+KSWHFFnjnWIrdKvhSWzcvVwJssMUQHVt30EidmKgY", + "siaaCnbYk2zWsguU3FWABZHbAIJam3XxtNkii13tgd/T0pJ3xL0IxiMVQ/zS0b9rzScudb6cAV+JrVZltcoApEfPXpwGgp5j", + "cca5lhsJClivLw0oCMtk+qjfVk/c2G2JaMNa4TTxswIBS5F31mrG8n0ulUuc/+I9q15trRoUi/ezM/Gle9vlilcj1fu72gnq", + "iG1sPUcCeEjhsl8h1dCMKGAbxY7Ls84/S4PD3uS1jpxWEpm8vefRE+dDlcXSkpqlr62+EHTtM3vSqxxhhU90XBAejf1+ULKt", + "h5hfK/coxf/Wjr6rvAQS7CSetNix8tOhjxMmHdAF73ikUxRMEltMJGfjjsNTjwrvLvVjkbTQcX7yXxb5AwtHoR/Zeo3OWnnA", + "NT1hSxLSNUpvaK6VF6ltEGdAwMNtShRbVW1t0Bv32KgBLCPvGHToE+/OOVaf+aE4A7rsMYatbPO3nq7/3Q6RSBcQT6QtWDcs", + "yBoD3ooSljtWlHmn21mPv+kOlWtr4wQrYWvBbN0WqwKQHKUw5u5adxGri3G2cgrYZisGbgQpUW+w+jK+o8oEq+0IuHIhS6nR", + "GVcSfWudt1IVn2Jm7SzSajxMnbW4d1gL0xavMj3WbJWVoNcP2LMQ2JJ6jkRWYCpiFeSrZmvO+Ytjb45JQE486mLJdmyqrbdo", + "pMg+RsY7ROjG8Eg3hBWCEtB5d46KyJ5JMc5juyrAngnt+diamBF3A89gEzmC22YEvtpKdIbc58dkXfoJaXaDfj5hxeEo3Lzm", + "uXRdogtbJNRhOX4enVqY1iq36G2oUpqhe+uTBZv9NQ1qWMY/OTkiXB5w0u0KtEanE+hRLGG6+hy57XT9n9ZDHVpE7NgaalQ2", + "HI6ts2d4uTJ3hWfeaq0QqNNlSYpgSw4h2XIDS7aBEUguMDHAtLwSOu/IuZpcYCIlOvF7rd3yb6EkyAeKgRv+qb3zQi4bAfSz", + "8GBzdZ+zpbqvT24zycutSI6yFVTzMFSIWCw9t3WLT66T9EnVJAVj87ZPR1Sk021rt26krcOb6WxhQFtgik4yBiDxOkxHGVuz", + "1JMCgrGtzd/iUAlHUmWViLpo6YX6MaTH16Hbg0tOdWXPDwctrBgsixeWZ13g4kLcw/s+rS/HsSfE3aKkgCBS2vbaN+I/U7JF", + "zjav4sfi7t2nvU5b/db53MYo7SFdb3QoSWI/IpbiEWIsChb8ztKJ3Tm59oSFoOxhMNGvkpmIkBX0K8JYbj1wsFgVIn/ei+Ww", + "phl4Mk0M5JIp1tBtUYoIAr9A9kRipNlCaUaIL6TDDOxfIWziwYovINHzxam9m4ezMF7FM7fBFs+kP7KKbmych0NioFKgNcEj", + "V547G3ctzIDFrH4vJtdGQw1bBSsZurlma0+adqtGd8QRBqwcW++RVzBwYomYgyIgsA9aNF3rd4wdg4wTgBVYU4+XVUGj7Zb/", + "5SxP5+SKB+UwySOqGSIph3fF8BKN0B4GxxUrwdKCXMEQa4llIxQDRVqY1iPBj5iYlht2v7BHBn5oywFHshh/Z0nW9eYLe6wq", + "RSZVKMcJtANEO0JmEbTZcr01Iiu5Hlc0nq3L+R1hPysBSg1V8KBEhuSt79+RSmEb5N6mXE/KGvq5HqeXDmU6LQZEBUD7QltB", + "f2L/CH1Z8BjCBpO2p3KOY48j6DIBWW3I7fzy8x2RDTgUPmdchJg5zn/ZsA1bU5CHyBJPFFH9DloI3WlhWuKtCWqRIWEFBhV9", + "HszqIR4Wz5elnvWiRaHBpb6vt50hXLBvo8SWCpNaYdYu3lwSX0x1hw0hya/VobZlXyVYocwDWJ47MuiQss6VXkS38aTCsSFc", + "jB0wNBXKUsyQ8VmcAGSDjYXrLlg/Hw0paMzubodulS5Lri1SbpRnWXJUK8y4Vnw0Lxg9CqnYoT7z1ofIMyxaNqDfYhTbArGO", + "rVWIacs9Y5GVkbboX55yUEhMIrR2WG+9sZWAOWjMhkQKjibKwo5acc+9IwmTTnzMyJ7/YWFZlJG0C/gnJQwZeiIwzR5bfVOw", + "8AA4mFc9fGrBui0BvlE5cobDx7EUX0j9P0duANExb31n2Wx2rX6vizsYid98gy1ibFGFiBrMtc0y4B6peylLK7Ai5lZZK+kb", + "W/96o8RZSNipH3kb6XO357fWryaBg3K4vhbjydqVBK61bTYQJZFzw1q/xRqigte1kJuwK4qhV1EYpixaGuywAY7i7GdCkVBr", + "FAuQoNcGi4rmG/GhG8t9ZbZEXpuNazZfujwq42UNNNIsBzj0fOGBndbroOnUI2IxZZ6r8Z62gCd3gXUz4c9uP5GYFQZYDVBO", + "2NBSUShrxQ2NJboWa6TlfZqO0IPW9LJ68xvl8NIxgKF+lry3oVAbiagxsW8sgcplYbx/hCuw0UbbQcHKwhSE8SpyhxzUp9SB", + "d+wZn0M+EzVhiI1tDWXH0pkRNBHXbJF049hDoj02fglChltnY8i9otx6yIN1coccw/sho/QAVKig6TGzLnFeZ8TFYolfWD72", + "YFpigoJAbthzlC3e6diK33l2TQ32mRJcwSPhNPkECwgqEOu6UOPxmrV6eBrm+VI4uiBhTDUxfQJl9ZiRWpeJIY+VSB70voax", + "Lqbm97rSTvfXvXym1x6T2bKYRs5oQY6yAnlKC7zPnrRv5HWQPIdNpV6ksFMQWPDUbuXKN9/YuqyfqBgiz2uXO5esjBNMSe8q", + "Y70YcMEy80CH/TVsnvqaGXCelgPNdS3bElb+VXKEndp7tWobeU90QGMLf+V61qpgym2LjgJcpzcc1MOFlQr22Ly1gG0RAg6r", + "ojrftdj4I94HzUlvFGak9qJ3lJba33n/tOaOu0po4hPWWqYkkqCFtbqS31miZRwdfR5FiU3lgvCOcswPI6vYtzMgaZCxOEnM", + "HEdesoWVFV3KAVTouObaR/HXhpEuXdROBNasS+ubNhslVraePZbDxFtofcodjJoHCLyOjf7dRGwZam3aS3KKYXwbXFa0KmF7", + "WgS4imx5zi5xvkNex9z/aIc9MhArxw9tDdC14HFRnwDesG4HAPZtdXznB16ixRM2hx3JjToq4NFZyPBfysH2JOW1jyxmy4Pw", + "XrBeReJ/eQzY5nQppxzb6xagrJ0vvtzr2HL6G2VPFIRf7Nia+XTTJ1bDiim5rsUq+3zZcoeMkKdgPo9ncmTOXE9UAH5i+WKe", + "aEc5qoeiL4oda7SLwVowxKSaux+KJU/ZDNJXLCKf6L/yNi8d/w997+84hFNYbYYgSPgv5bRjbJQeRkqg8RcbjGrzJdbUtVPw", + "5e5KUbDdOSyGzCgRu/orSbfYaCtAO7aAtmPjUQblHlhQJ/0myqlan1VkBXyb3cBOG3pki6k7tiqyja/Qg1Wri+WCJkfKnmPS", + "ypF4ig2+KLc1x0KnPfvW4f4ag5PEMUF5RfL5zh4LcZSqWsMwyFf07IhXnT77FrlojTpQfOn/O+3o2LJDic/QURLp8Ic/2GhV", + "4UxI0q7eHV99umfvVzaAxVZbb5eg82jf9tqn3obcPkkANRsH7TEnxmKEKIsOuMyW5XcsQDXO13ToytlhWUk5cuyRbHGhxvLa", + "PFCzBx3WsPXabSF+ez1XOBAFxCh4A0/5lGXYgj2+/9Qew4vHuBTxwB4DtWzk2DiyLuuzUJ0sC93VbsugG4mvUolFDjYFINaO", + "rQEu/N1eVo7Y7FUbXfsJ9VE3PWRcZ+ZFAwn8TUnIX/c//9W5oZja2uSmvUfc4XS9QaN+atdF+KHrHXsAZBwbErJd+30SWQUl", + "+OqaZ8P2JSNbpxCo/ZDRJaX9ACYKhCP+to43RVNL9WlmP+D9ib0EpsLUYDeqvrpektsoYXIwSFouVIncJOUVVKmECLMLkr80", + "UPYuBya1m39nxCuefb66z/gJ11fGfqdsDlVk0/FZpZ3pvjbuQoWvFvBcpJj77TFLmLG6FQyiwEsfqdlsSnxkb5KCPdwnNpFg", + "4nK0lm8uWUVexHLqJcaIyqUbTCXnFX68nZE4f8CGq3Kc0asFXsUcie6IjE1timySkL3CSbJOYhag57VOfoQB8ZakiuS4RzZj", + "3GjrDJJrtZj3gqWKaX3qV7NRImE6vDLK80uRXEnhyT6gM3EN+EpZZxxWgtlTpZQO/NgWADBrtQX4l6/FzOeFREzkgvB7NZWk", + "vEgp5L1MzDrnDUgUvX1RUfSKkmwrnrfxOyURchDSkuFusGAMhsbo/VePQwmbSiRfFgO0Sfn2ygPDW39cVi9wXbaE7YOpx3Jx", + "l9yfy6hEXuoTv7pOWyf21yoTmMravjNLfwo4D3QTKrvkUpQBY+HtQj7vtqowc5wS59VCKFeERXIhWIXXhGFZlVQEkHh/xlrI", + "bdkVe20zbTGe1vMwnX8T5DMuCzypgKPW0pB4aaacAPKki04XuaM45h2i9paA32+y0fts2o145LEfdKJSSnKrEjnZ9xiCU1tL", + "RDRrUw7WEunM/jaJdti6lnYDnFBk7o22yQsJ78di2j0rrici32zKiFnL1vGIX/mgBO7KfH3J26L/iY5HRpGRnplZxVB0G0em", + "Ahr3RJ826EjHa7lcQI9GEuhoy4M6Al7fTKy/lrsjwo7qdC2XzkgyAYFGWJN0JVUwEl0pOXo81x2wt3HDmFf7GTsmERSML7TH", + "9OL1xIsHrGxzutbOkmmAMzaDxw8MREuikojCtaQcryC3B7Ee/aBYGmv7Jp42OvLMWnbSZ2v7bL07zJu0+W1y6zXfD3nLGIkK", + "OJCBM78nFliFHdTkYJ0ZNHK7a0y2UFQGRS73ALNZtLhvJSpUbqaRGPuEaUb/P1tv2iTXeV4JyrtR3eh9X69T7WZhXKgC5OkJ", + "N6pQDhAkRcgkxRAgq2c8PYpblbeqLpmVWZ03s4CkpAgQJLiJFGVbpGSZNkURJCEIAEGAAAFw+wD7q4L8ZDDmizuCpKiJmd8w", + "85xznue9b6JHC6oql3vf+67Pcp5z0DaQVSBOp2TsKmQieVywWq6kghTLn7y6s+nbVkQmeoeiQaHMRiwqxbpKoXSWtyCNYi8w", + "zsj6U4yuzVMY+PZ923aoHAh/H2YRVVqHlLjcxPgDaoroHKx+zANi8W1uRnUjggB25RGyiJiPfC57Zs/PTQjfsiGUtkHV3a86", + "EMQ2ZxHXUA4FXoW0ETCfx5j6XaIcJmU9XIV6rEJVnG9ElaFyBshIr55qHGje3Rg0RE0AsIP2A+QKN6zc2sI5sOFFndKGWV6y", + "TWnMMJkKBjqF79I9baJmXXgRosfgJ4Spr9mHKhaerouXH3BsxJhXR0KK2X3X690rdX/BC85iHWq6sb5Ixoi329YLDhubAMes", + "7xEgIt4NoqNdPCSWg0TeVlfZNff6OgFggAuMGif9dQ/wLTsav7uviMLTEeXYgeDHAjoc+4dUAYaIrLP+E0pa66MN1T7bPGcY", + "kUBU7qOoq0XYQoW6qxPKxYPeHgvVPklh0rXK91XOT8YqNiB8gJ5E5Fjrf9DDQKs6rIt5ayt2pIBMpxBCGqLFEyZtvFSokSJP", + "qJr0JgCAYL0q12j7HBB5W6iVMy91hK2D86NLZXQiurRP/wfBm+YdhbS6vGQG59IINTDcj1TqVUHQmaE2thYl3o66pXihPfvd", + "1nmwzLyWuvEC7QbBTEQpBZnAOG4OsJ9H3TgCAnaKVkqOdZZhjcEVUulrXX5NdTNF4aWK9/i+IY6h1REPa6p2aF+D1wO72QN9", + "M17j29A+NwuRtVKQ9uur3EnKBNZ1jMH3HB0PnCUN7obnnSoCuV98JfZ/1cl0vWy7QV4H+8FKbfse8itQBavWhbWqgV4ilBtQ", + "BaZ//ZyZMKFj8+5+GWo9AkZQcE77TavL5lZX+igLy17n3bC8ZKYoHLLWuHrdJCrfHEHelVYX1r9QqACHYp+3VWYeqO1fdjc8", + "o+aNzTczDoTAY7h+mS6wjQwl2/k/7Jhm8WDQrdMc5bZwj0o3CulIdZY7hfSXilmtO2g24n4elZ3h+T1cRbjSOqsudX5gEGru", + "k4teZweTG7p/tBqwroEKAUrD3D5s5V5sLO2QfcXnVarUkKWAMSnbf/U84x4yWUteOeKYA4CoeA7TT7KfS72a85plTTZ01O1m", + "4R0CV6vVkiJ7y5p/iC8KFiqUQ7ULAVycew6ULjYlfThahYdp93Yc2T6uPzuPHSnQ6dUPcYZ5GLHY5W6jF1t1pZszM8PFZguH", + "6sebkHPvc144i0DjsHmGE7An4ZxEtY9HFCc4i3HePzDusuLRS7DnkYbGdQpfwKpxh+IeQfIduE2luUkSeqO024jlGTw/oYFU", + "8pyaLxQW7dYEqxQqfVitdsv8290pVLnqwCgWEWL7c+ieOwmqfiRQqpK7yH3GFqRXJYNxioahzJ/eZF9xG3OAtwkMdBufNlTh", + "sM8Si4aaMtZuFDpX1yZ3mQ+DM59BYBuhqOJxFHTj5bN9ohoI8N/m/PgaCprLzSjsGn7d2TG0D6xOnD8AgQqu7LVedQx25UG3", + "k3vl0SHnk9q7LN1JKlxxvIusZBbryZxWTONlp7MwN30TUJi+E0UU1PHCCaD6xGbBgwILbgCLzgL7znA0XvfCpP2dDueh/XEU", + "uzNxGdxou1QEs/WjrGen8H20i921Udkf98X/CLXoemsR1fJ32LN13EuH7wCdauHZOgXmFmaQkC0oizQLXKqP3PcwXAjdOs9D", + "w1L0Qd04rHFmh3OKOBGHHR62OmyfRUgJ+xvKVWkDM/dAxUaGKFWFwnWwBUdvf0fwnTsdJON2YiP1zE5RDb06vOsxzsnmFtDf", + "IC1BFA8OG+pT/HxZopofDhgBexsnEZmH7hliLIXiS/uDPEXbR2d53gHI2vfAAlKrEm7cW8cRNe9pKG9/10vYCy+ebe5U/SNU", + "jjAPmy/7Pt9xkLyWG3Uth4iLOuNJU7odxBpJa+AdbjfRQbUHmC9U7D4hoqG35jClwkyyjdq8FufoKFgxtFLD04cfN2G2lPX+", + "2g+RDUPQVLsYqhT5/IVjjxsHChdeR1bt/r3f+0//effeDion4Eu68z4sgquDyo379ngGYQQfCXPZCUGa3V6DxBCA9aNjfQq6", + "ce15b9MGQXFUuzDf0vH9bd7Pi66XKjfrqGg0f3Rm5gABCtBAwj7G4NESSABWB92E1+wsI7qEc8kJZgDcHmGjecAmN4JoBGXb", + "cziIfR7kJKzltH0c+6hXKzYqlpzZoeIdzAux7Xg0fnE0EDJjaYE46uXBgz3EA0ovfkM8jlXde7zU1BkQmq/4vHXui24xe9Q2", + "uo1ivtDzwQ7BPkZ7qi22HjrFSuHzqfACi44TVhTOr4IgDe3DRackWPTirEBDaF8re3M+/wJBP6/SiY55Fyy5WfbwHlACq7a7", + "A/UGborRhs1He5AuHZqm+o8wve125tMRlkfxWrs/VxvbL2IUB5MGmqZgs8ruwEtfOohjmJ3TW/J0uNcSLi15EuXroIzZar7p", + "1CGNk0fEtCy8srOg7HYf9r3ynEsrik/2vByq8A238Kp5r19ulhRLLYJnwZlYUBZoe7xAWbCr5N/3JrucjGJUHmNpBcpA8L63", + "e8Y5Jxrs8uMbZxppMx8ZFO6oan7tnDGzCfqqE9s1rQvrhl612dFrNsknQGgOhr3ubUA39bqo1PDh2h/0OO5vb24dWwToe3fh", + "ddlO+tP483S3S9nrdm5sblEFWfEBpHlYVKXy8dgm9/A+nN9CRy95QeXBiO8ggLJWH5vxheLHW7HkG77TZDTMjwE2LzqYonDD", + "ys2bgiXmtm8z/QNqA2eDiVpEZsIwj8T7sx7V7oJ12HecRqmwnjebYFl2EPK40t/DoqF9pOJSxSXQVE3Lxveteal2HqI2qfX/", + "BE5BvG/37jhf0i5mSeqmcFaPhv1k4+TUA5g35qP04fTaZm8zUtig/djpYCM+UCLjiywQ+FEa51DpLK+Xm7qhypYLZEuw3nw+", + "FUiqE/2KXYhxpa19e7eOFfP+Aa9WaRxr/IVe+dAEO2sfcTbrIPYv61+4DXRo7dh5LqDW0oK7m/7+vi8seKDPucMK91sLZbY7", + "hRPeeDradgqHkTmJzMyspOB2zUoMbteGGTej5sG6drtxONi88eP+Xz0yuvHO8MEbr1VggAOzG0OkN37SJ0rMzEoP4rt2NzTT", + "GQlv+ogsY4LTDqsHPo4Dj/bHuijXBys1HCQP4zce4IaKHgyrEvsQzk+EbMY3fmLXp72N70/IkKpuGGzduA633NZ6MwBvqOwL", + "nLvcJxA37SHsQI3EPuJRCEaPEPWmf4HIBrhoPV6Ghoxqa50nFBraWzcu0c8wz9SMKUbkm3Lzxk9g+G4zWmIbA9iHuqQr3aKj", + "xoLVcuhFmIMtFKyhMgT3tedh0gJhUF/gnmxo+D1w6d64NOyaa/IQsiiDh8pIjAiASxVRG1gx/KB9Zc9OHICflDLRdmzj5HFf", + "Kmvic/536UmDxvuvJHdsvT0o8Ye1kZzG9lz4g7yoykPAjwfnTCQrzC4k8gS4jgHC7CU6sV+XiEvifp7isL16lYy6pbW6RwXs", + "mu+vIcqC1xmBh10T/gZDRY0KDDjuyN40KyXDW1UwcskPK4cejxkoSoO/4Vlq/sHAe+DGpW0kDBR/Gw1GN36yCgPD3n8ARMnU", + "lLf2Kx1VwnUdw31CAgQNUHUqihes926cQ5Jgm/0jHjv/HuYRMzuIuw4wn0nOAXXkiqWn2BPwi83PG5fMgRkg0sN+Y3kRROGx", + "yuBfiZ3XdiT2E8fD+mmwpf5nHqHG/WnvDlBMuW3XgRokrgewSr1SDz0uWNKu4boiQLYsNU3tUzfOIRDZvXEJZZTOj4F1x4wK", + "OKlvnBsg9b0Kzhtbudh3ze6BvWwOAvpnBZEYMDsBds7ifTsPS40//C70I8XMh+ulyrMHNM4wuxjvBPpQ4+GZnHPmHGyTZ5g0", + "YA+BRhqUUSPGu1n9p0QT0Ck3zoEdmEzZFZfv+tg+v42vWbtsmYLxONh9G3smOxseYn7mxhsl8iOAO3sCSvG2iicBlVE9v9io", + "ZNLWpS1ewKX1HIAcif9ZJb+V57psHqh/SmffvfDB5Q8fBpMtfn544sOnEw+w/cTfzib8zgfP6XOJuRd8vGDTJc/whyf9c9d4", + "TXAL6zpXdR8w3/Lzfj37v96/QKbhN+w6aM1V+wT/xmfJ2Pse+XivWUsedRbid8VpTFbg96w9+nkNd/rwONpsf+H+4j9+R+9/", + "+B22/Qm//1WwAztr8pvOASzW3gvO83uBbX+D9yTvsH0DjMDPgtEXf/GpT4Bx2a6NluP53uY18P3L/J49l7fP2qPPkEMZ7Wc7", + "0D68QgZk3OfbHz7Gfvo2RoOtAH/wm9ZuMSdf5tXe5HOqny7a7094f73D8blqz3bBGZsfIQvyBfsW2Yrtt/f4xBd8XL79wVvk", + "Z/4O+YovYZzIenzJ+++at/oE2aXftc/o++/5817wn5g9x9mjV+1anBd87WnMG84jMUWTs9nae5U8sI+KD/bmGbCzfnSSvLBi", + "jP0JX79ARtRHyX571k77p8Rue/PHYteFBQAuV7LFXv7oYed8bVlo8c2n7N0n7JU3wcFq74tLV5yzr/HbT4Bn9ubL9u5P7Yrn", + "ybir/58jeyyu8ig5ep8AV+vNKzev33zL2szrOgPwI3wH98dVXycD8KP2qdPe/kduvkl2WXAFnwTHrjPRvgZeXbTL3nsVHL1o", + "qf18i8yy4Islm67aj1Zbi8Xi+4a1/KQ/78NgsP3oBLl5T/J6F52V9ydgyLWfrztj7VPsUbDhiuP4J2CSxXfJtotvnkV/2Gdf", + "Jkfxk84g/Brvfc566Br74Yr99abf45J951H1J3h8+e3Xyb37mnhv7W4/CR5esvNeEWcyx/Rh3d+5es/Y+w/fvMLrovfOs28x", + "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", + "y8zOA7Z969iiu5pb5jKiwmNjEond1ci7i84OYBrWyHtCsLuVoB8gChPTa4QTK8YJVmBsTDYmWwOKxDbzykbP7lokSxdD2ESN", + "uHowODrxvHexh9ingUHrkNByy1lgnB8D9QZj1eZFdBd9imzJSLlQkSl2603PJ9o8OCggVdQwIt0DJ44m0urqeEvDOoDDtsZy", + "LtRIUtp+OHCUmdeD12JIQJEDuEVil1p3YE692kmVTFSRo6xVyrEvdKsY/dU017bGYEbBVaoeuR9URezjQTVbAQa2wo/nRsI5", + "yapUtiC5it2NvbHywCguVInDD1bF1slp0CBuu8Jc8BfTPjkzcwe91GKU8oTwOGr5f0jHsD5p5LGcEep2N30NMhLB51hKGQGF", + "lRAzug8CPlREW6kmA415cCVVXa8KtL8cSSTGEl8LYgSo+p2EDtg5E7woi4VjdFjTSdliVJ2S2xVE+gn8FHEtcC0xg8+WOhZt", + "50yRIB+BxygKRdD4bCvOu0tWOoWLSPrJ/gvOgqp/P6vnxyhrQsaUiXpgJcyPQT3oZrBHERfCDGjZY2AHlZzHigbFuMXnGQ5h", + "PMNZG8B+2S8cVuSoxIcwEwF4RGAC1ccUtmwiygZGB2Td8HiMeRJQuvGFmBu2WzhOdTYFtckqinmEE4zy8eAh6jh3etfTzMMJ", + "kW5bwgjFTr3Wrt9jiZtDcIi1cS9wVMMG9WhgGhtvEl7C3Crap/hEf2CHoh2yo0Xn/0BgV4xfNQvjhBtyFXBMj3E/ohMB6Fud", + "pNAcSMSRTMEg2f5MNeUh1q8ME5/jZOforSooTW5GrvOezU5PZGMsSXe/J2GLA/Bke06vN1b2cA2MxwzvcvZx679fu5l9eW/6", + "7laDeDROTiKzmENRuSieyGY2XkDmeUAtANvAQONacc0kwHETeYbeZDmBCAdkSwazMYJvQ/ZuvUnMLMS91woJEcyVEo+we9yT", + "LIWv9gOHiTioko0zCfpcK/ho7x4cRGKUYABKPdwv4VNi7kgLhCxnoBGKwxGFnxPLA+thBcuxq+xMN4HdIwDnSFSs1j7ML6BT", + "bB9S9t6BZLqy+HfBx/M/pWx4QJdXQTnp7q6CvrBpYnUvLSS75LbajKk9i0VdLAUcd5XIJoFfEvi3UTQY6y3YjnqT0UA8vURl", + "owZshHDzbif//dZM7Fhefw5bRRXVD5FDqNJ+ABA7H23Z1wzxHAMPSd5blX1W3c7FWqiEQWANOgLOEs4QJgOhxCPJigSUUTjX", + "lbJ5sCKXGwGPpPX2WCjjkoXHYJdSKlOQA8w1asTRvkKgYaMSw5GnvBtFb7G5Ouue7RFKbDUkBaUEMNhhUy4pnfHNl7Tz88R2", + "/FpYHmQ3wkZDzA96kSQ0O9o5iYAS+3Q5OSAJ898wbMskSWR4quaOtIclMH2jPOWYujEqH0WfFJ5dIBUjqaYTlngHAwpEwbh5", + "ir2zCp3SFsnkXN8cHVYpYnknWLfS+MjkJLRz4WgY6+h7xsfMdrPOWQ+mkRJRnEITS5klZNw6MoY7uxYdSHG0FBqNSu4soTDz", + "a39HsIk7ETV2hh6bX75z9iYOQYPXMdjyU3ec9oNUWdH/cna6xB474zBVJIRpJ5Lrl8hem+QwabSOHDJvG7nkqtH5B9IMWwPo", + "gnvnTEqOOiKEIX/UgxKU+Luxi+qka4gq6rmHJpgT/TemtLGPz8Z8mU2o4EZCENgVUh6mWSInLUxoHUHIk5A9hVhueTakcmQW", + "BO9LqYmnn98CpxWBZbRuth107vp/2L1Jf4z7eknKQ7D11pxkgOTLtBSxs9rVbXfn/EPgstoKkFBBNhmSwQKyrisnnOsXgnli", + "sNYcdcDVvHtP1v19Jg1gbxwdIpvbL1YmCUzTJFjoXuw73WF5tOyt9QblaB/IfGtI2hD3kvDnLay/kZI2TqQ7knW9Ag0xWqpb", + "yUeELSCQAe2rPgvKnUUSMEsviCgEGsMqww4nUB880hI5lNJ51XqYa16Y0pCN0qY9QcM67bv3J1+8V8fMOSzPAexdesHMDuzy", + "NJiahE2kfp9EGO5BFbMiBEjGCyogIUamy4mQF0RDeK3ugbRqU4Z38x6BOQfDSYK7fiEVrUB92O0ceJoVR1B9D1m+sMtxN3Bs", + "oCcJS1wxVxGImp6Uhg4n+96Z/KxjQG3mp66zY3SQ8C2UJwABsyelhWaqBKElfGjOddI4Ex3cMbNFtUqgOWTDIfOc8uE214JD", + "LhmWRVtcVRYIpg9ZpOFw8A7gQhDA0gro0/K1HdgZOVL2shDSHriQVMBQSCmVx4FYLcyCJ7qpLNaqo+DPF8ZJ8wf9JxQy0CwJ", + "GbF8AKr0lGYr0pTQHkFCeOfErMhwXJOvI0UhZhTzR55e6H/c404qJhfV+noCfoPZAOlY20HuTzGZg8kKCghxZzldeedCCymQ", + "EpPNiN0PNE33wdt27Vp01RX6Bi27LdYnfHZ/BfcIYEqTMMhFSYg++HQSttIsc8TvMKfuT7EgO09cpPP+FCsQkyBjChUlvK0F", + "LrFAsMpR6iRuVAlYnPDsBGOD9GfPnj0gRRsU66iySh6kYwZgj5NsxWe7AFbdxp5gNwCJa4P+g9WEe8hi6K7uu7sK+1SFIpQA", + "jmKUQpqw9IOGqy5qHpbWdpVAHUXCbBXOTwnLSEyPiJ9IFRQeKTOr2CSA7hNoKRh2duxg3yMqEvaVTVTnvwP6mDYQ8joQmBAN", + "XndcudKdJJsxqrDIxOVnthQonhwmJjkul5ez145EkdIc0lmyn7/ibJ1lX4gBFH/cmayCB20o5eeldRmVf4yMVfrGEJ7rOvD8", + "TVuRCV+oNr91SGbKrRoFNOJApWJYv+uovhJt7tJyC+ywrwBcfDX5EKjdQRzJrE336GGNbJGLUj4sPZ8yrP/tSsLO5KRxjt3e", + "RJ4SQj2ek7P2sSdX0QL6phwjWpFmd1YjWz1jrTMeizqYk/s5m8qpDmZ+aOEoB84wblUQaRjRbbPRcsqmgF1gCvry/f0Ee51x", + "XWIbVZyNiiwGN1BRdoooM7inrqwvwNgzk5B3AowTjaBhJhSjC/FcASErPSV3ecmJDdfHlWNJbAnQgg+gyG2Nc+7S0xxuyv9V", + "JcV4C4xMQOCuqwz3AaHUEgqdPNjyU+YTiux2ISI4+tYrFBZPVZUUJGVdZtW0529UpM2vSsQZ0M1+IV0wGfS7j/qclD1wmCB+", + "PLnbQzVMEZ+d+6gbCgGHgauhYL3eVx0t/lfA4sowS5o6VX1207k6jrrRwObY1gEgIg/YMiLg2xXRfyDxVh0uWd8OCgBljx9V", + "rbBFyu7kMOEnji2mjFKsjyZwJIQbqqQDJotOq2Qp0O4cwUdEZYNwXHNFsDGp1gLnfoLKYh9x0knn8Mb4AhvC430hRSHWq4i3", + "M0EjH6zqydKpUgFwgQoy7XCgc0xkZWYD7zeDjMBVDhcU42pK2oH7RSBx2AcAHYBvkWsVKx5I4aSVJ39Ge854CH8+GEMHrt4i", + "RKV2i6NRbVKkouq5yNRwpx5rPyC8jthv3EOyX6lCu0kgteIO7btAGAtUuHfPHkKneXOXMAtMDBmKXTEbG/Kg8FunqgZCb+6C", + "zbXhmGFoFTqTemcZqlsyYSKKU/bcj+qON11IDou+iJ0NcHet/iLBm1ON7TwSErtZ90JrrlfaoeX4InvsbiqR70lKryhHYofG", + "ZUrKVxGEhU14ILEBFTsKHy8Usx+CxUDgTJ5MCZmaPPDtStg52JgNdlvSwWuUIbLpUsgFbCqopmAOgItTKjzwZ4a1WIcHW46C", + "FBJZa58TtewLSI1zhrkYBgCTdSPhRErYKS5FVuIJ8bFMDMGgwDqg+DhlSlUwhXdXhgFd9zgrXAzWf3AXXfU4HIV7Gl3F56QY", + "XwU2w2yHug3Y8DHTuuAOkNCz1vmqcLN7ir3VJv6/eHuKySykAAdOEjhLdCA9I7GQWAUgNiO7cJRiBbZzjmxrGa5vJBt9Z/DG", + "zq6JXxOCjq43ywgfbZWdM4V5CaWiTStC4sMIAUe6lwRJ3YAxRmIkC4d5YYwOxt4+1xacoAQbrSPzN02dcZMoCArHrdovy+lU", + "S/XpSx40g/Qd4iiErs1L+q+zsACmc8+RkugOMMdge7ezFj7YaulVj0LQd4sAGvZT9kH8tmA+/Jsf/80f/83pv/mzvznz0cNk", + "ebv0fz4NAqUh3Er4+5UUNrnTEJ7TwFNzRBNZzWy68uzhu+OV2j8n26t2NjQiaVpkUJN21kraF3gtobpQxUn3F3PfgVnINzpL", + "GaNbvEdAeOsBVVd4t6g1qwfkO1BbBisOvkpl11UCbzWMQOILjfLx2KHDfkmaHWTTUsaYWXOzDXAeiXlfT6lYUA0tr549j726", + "Ap5CuN6l0F+CW0l7w9oceLQmeOhQ9uOgpcYr/6qHyiBVqKJfAL+y5t+4BNGFRC4BvRdrptk6DykWWTPt7rAxzzZTPCVtvGtI", + "V4iBDTUS4lgLWoWKIql0WchXdIVMRG+IXerDE/4afrsIDqYP3vnwWbIoXeerj5MTCbxTb9jPt+39yx+8Rz6mxEtFVqTr/Ake", + "q/fJM/V2YpO61PJRicmJd3kruJM+PJHeBQfWVXIrXSVr0xVyYLGl+NwHLzp31XX7zJvOlOQMUeK2+vBZewd8WI/oKROP1DVn", + "nMJvaN9x9sE7/FecXuKeupYYsk4mDqgL3hvgy3pHjF/4BFuIb3mbrS3B8oS7PWI9B4ap9/1537Qnv8DvXo3fnN9JfFn4Hlip", + "2vui9e+x19VmMYqRQYx3fpx98Tb/5nfttUfwCpmoNCJvk/tLHFJvpue47KMWo/U4+a9ejHHzz13NrnwtnpqcW3wXbF7ip7L7", + "vUSOquvOOAYurHc++GG6x3WO6CVv73voU2e0wni866MfrGRXxT+GsbQ+xbixD1L/vcf7XiZ/2A/Jn4U+ORX3BZ8Z2uIjJU6y", + "92PmWAvBEvasXU1j+eyHjzl72An75gle400yrF0gs9jJdL0LH/xF6g22hU8SM+KCPTl4zZ7mGF3AtXyUj/Np43OaZ9f5u7N6", + "2Zi/o1krdjP2+1X99uF3fG68w3l0iXMXHGRsH9nKnkmsZRjbd/E0ad6/w3Zr7n7X2nTSrnoRLFo3z9x8/aMnb76Ck8JZwfRT", + "HGLXwAoldinxfpGF6+TNs2TWeuqjJ8C0ZZ8TH1awjMV3r9irr5Cv6mG99tGJm5f8G9ecj+scmMvIIPUoT6wz+M3+PWGtAlvX", + "6+QPwzfeJPcUmLXIZmXvvmX3f8p+c5Ywu7I9B65i93kLrFrkKCOX2c3r1oIz+JZ94zRfA6+VnhWcYedTbzzl7XvDP3fi5mX7", + "rz0D23EycaqR/4yf/2nwscWz8Wm838guJtayR8RrhiuBSY3Phh56nc/zE3J+vYG2qE/BiGavgSHM+8Ce9wS5tx6z755ka8TQ", + "hc9dZk+etB56A0/EfiALnL3PpxGTGBnbToPbLI0CPneJXGInwWQG1jH2Pe74pPjMwI7mn8PdzqonfKStpX43tsaZzbzvnZPu", + "tTTGL2NmgDUuWM78Kuc5lpx/N1/15z2hUSSj2uvW9pP2/K/dfAs9jJlorXmU4/aWva4Zpj7XTD5LprM3Me7qe/vU686U9xZm", + "THP75Ei5DlakWUmNMEO4twUtzK/Xa/6qzmUC30LlWli4njvdnTYLlirGYPyL5MtMN+GneLGqv10PB0SneI6NsBiEZLcAyKqI", + "K9rsls3GYqoqR1mEpxqXFpQGpyeJmJmnuz35H6i1asQgMyP7GxTJbrPR+xJNV2d5TwvwqURCAM/BAT4C4qB21aO7IudxORz3", + "uw94RJOwpoCGkEd4y73IauR6ybPjYW/W4RebeAqmQxphenaDaplOCFMyKFajyW/X3dVGsto8ezP/pfu/+E1ybH0zWUmjSsm7", + "JZBpt5mexaU2W7JhlpJ1F9yumZm7o2xSejGCSiLctA9J5cXVQUIySn+5UObdXFSY9fs7ItVg0xGW+d+qElZ5Iiqpulsbg5GT", + "HAWDDMIOvdFiM94CtFGJH+ByJvexOopmffAyWfdtlsdUv7e/01gjHtIn7miHO7FM9cDe76QyxdJCSDYtjzYY4Vuph91hldiu", + "hF/jPMNIRZ7RI1h11QAw0njGL8Vam5kdydNpkSLdqHijUpSYyBAadp66Onh6ASfo/i/tlGtj4IsM9rIqGQXPIV/CPlOcNLz+", + "NVxRYUPzvw+srTMfMVJo2J25e21yQRl5MJxtzKmDB09UTF8e20olmSwnxCChQknBamnX2o2XWmgRIysqeawpGcoQWt3fpqNp", + "Dd41v64pPruLZjg9rd4dFRTJGFfotN5hrSAzO/VYGflWqSv5qwh8aJG1wQWFI+jkhiIIy3cDltOspFhlAWV5X2R3tGsoeKts", + "Zc23ACABTYXQTDjAxlOQTHk7Kowd1Z8UigN1U5ypkPCSYo8DwgOQcrmXMhEF8kZLLcC13XfsOpTJxiWiQoYbSBFkbijn6AuN", + "yEiSAlXhzEExzuNqqMRDUl6+dOIb7E2oLWgTrT+a7G6TfSBf94GVTCtnB3rfNpYeamMHgBP0MRMJpqwZGxAakSCnr9hkqRHX", + "sG27SDgnh4RhekpLwhP4hBD4GHcrFW8SktIMV/d3FpZaeKOnOIKkxWeqe6rIrC8tpARfyCdif6jJRqW6ZRYHkg4OB9Wq5w48", + "X1AVEqlmMHBeB9p9qAVeH9bSv6sOtPtOUrAETJmxb1Y/KqrHQFuqmy1mWwg2+teT7k6ys3fPnt9GDMU5L5ZayAPLPDHK+zu7", + "5hORUFrzg/6X+5GhKkKwD7kJZyVCAHoo/I7KDbPEgiJn5HrqlcNbwBTNofYYD1g65688dspyFtzZifJJGe9249rbRv8LSeXw", + "CrsWbZFqsidCEGgcgvkN0u59B5AiYgSkc1/bZ0KFd5ZbnD6Dry7fhC84vuG3UrxlcevYYuFnZ8jgIdLouRTGczedH6Lb5gUK", + "B9Apm98MPGS9tPE/x7B0SVexqj5zGoGVSVt90NaDYgsqIvl/VASDisdtAZKGCFu5+t/GtR+siocxuEvForFQi8Kf2K/foLQG", + "sGT74gAogEZCJBqImKqt1ehyUwCiB6iWLrY18t4kIH7UnHECJeT6fOLE600OZZv5qAjORy+cmzB2yop8QA1dloxPD6xjSRC6", + "xOwc0a1QDKGjw8idYb3ZXzhBMFie3OW2qVgjQuPOaFOScoe2T4h5IBaaUJEFhF4UnG5CLVQMGd4l0oQDNR/ZOFL2rBLgmXyd", + "ZYp7RoLeDCKb0mD0G0AdSmqjAgitubYQo9gabtbhCl2hzZ+qFdbUwOs0A96UTVfKACXHodIJxhyicllCH5o/hOxQLJ39IAZS", + "dPWhw18OnSSS3wyGAMm16axC7CJkE3HBLpKU2keDQI0Vy5yW+xLV4SwmHLvEbGVHjcdOIAqhhQeaENqwi0VBNNnCKmGW2rgw", + "qB3dGGmPuhmPTWNy7ZwJEZolhwUf0bm5VWvfAWzLE3Mhmwn6mEAoUCzOGTxoEPUFPxRZoXKgRHMJdDUomnLCQbizNcrKIgGR", + "giMVR12ChzbOxUFen2SyNqEaZ1e4W0JfWE2RjWdqTJSgdW8iRhTBXYNupzcJXTCkSeEPlMRVrvn+jvnr8D372oZKHQQ2C0hY", + "E8qttt5CvMcGlstfRlmzgaWjEvdSVKUgAWKSjC+HphiWNEGKzEp1WpgxMQXYQJt9pNDT12yui/pvo2rR24XT4yL/MOCJz3wv", + "OQ6i6VR8FRuuQKvI7jqlmjVvQ9YkODbsKD/kgnSdsO+sVf2U423BkpwwXmwxM5PZk4kytT17llS7cOc2IWuS6rK7dgok0Cs7", + "vr4OmcdaT0FZNofzSfQJi4aZ15rvHGxPp6iNsadQoorT895xMiJxSCFVYX+2h+UXsKP7B9x6xV+b9bEg8lipRkcrkWeE0Bum", + "RiKa7iWXdhtGTIBAI0FAtK2fWdvVwh1H7ij+C1gBnKyVkB4um/7qRKg7cgXa1xwihvXbbe31NqFfhBNkDZ1PbAMFiSdkShxo", + "jSfsUa7/ExArniJkpQaWjPum+CnmWtcnSl2snfdPRQS8OK8JNtDayTJ043JlBWeD0tLrERFoUo6oaL3xItRQw04VPpP5eZmL", + "Afbm8RVn8N4Q8bav3d1uushWueyqNnpOFMgEk7do6JYCNzEOgKBqLcY8Azo3WpDk5YCZRKjbStXW59ldv3jvEWnAHWitbRjQ", + "bq3cmUIGc/QAaVAm3V/cC9NwhRlhzRIUjm2QrGWDtlhUY7nzWgm1eC/NWwEiATvxjkqomb6I/WgOt8hKwg09Q2+rkVgLO4IO", + "tfZkoAlJwwN9xC52OWxhnvBLfvd2VsvXFG1dKfc+na6aUcypJsob2vckuqjy+iMyyhTy0fhADiHaUBachG5I7daU1dpIaIqV", + "SRrjKDjDCjfHfrQbRKhJQs6MC7d0sQiUvq5REzhorXiccwAJlF2FQ+yWYiMmeQBqToQuwJRrDc65pYV0slbyz+lWpx3mdw+1", + "/kVbIdrQB9jNPN18kSIjIdFFKtdktamUicdXaGqDQQqAZBlwWaWj7T9Rh8NbaOm5FCbGOxGjo5TYSfasEV4PB/ldMNwJSx8k", + "zzKmbfUSB0DRtiidhGETqCdFOIqSGEP739ZWnZj5e9BUDQXnFda8smUkFOLMOKp6AnbAZmXmp1SLj0RNiDkECTrfHGldowDR", + "kaHHK1KREk6zpK3vbKL4CDnvMnmLdiJiYpHIRxrKkExtIaG/n7BxdT/x7lddx0HCUdFPzp1U9UcYG7kt7Lr3ModMGyXohDMs", + "GIz0xjkYbdK25YzBOshyuFR0GuV1D8HmknY29nXnxSSesVs40oigNa0T0Nw1gobIOeG43U+GCupukzvK6zJHye7jksYyACK7", + "oIkG3kEW6bF1ZIEU8WYQpZrNdShVBM21EMRmRDojOm42U8MISXG5speCmmUv5YjNjSJ3kk1nTiOUoj+oOUmHzUYyqU0UZXFs", + "s9dv9g3W95vdksrcUy38sdHBVGvoJOLsNqAUQdMIwCfLqQhKblHcMyHCgT3VmuM+CruTFLRloDrIf7tZ+TaoqBpPnLZID8Rc", + "sGCw0zOGp/6l2dzw4MKB4zCkNlSx2Jbyz8lRJ4bH2vBgVW1pjKPSucEGWFADvdFMhiZI56A78TZeoZNpo8mAK0GYi47BxZIS", + "8oxRMQ+nQS7TGgTyQEyNUJSlKcGJyBpr7wey+gM+Qo7bUCH/bx3qHKjIblAWQmsQaCR2rmIB6C1BHnqTO9ucxM62/MWH0KbD", + "3HJrcO5paypwW6dBdOg+xigqGdzRdfqc0B+fAjoCQQsmeQcQeilHs69vJ8YiKQKX6IAWoDEnratAorL7sLYG8AQws8xDE4yL", + "BgUPd8HGvGQcEyZEE9AlhGoOqDif6tKKQxHfH7HG1AtUE3ctqgy0VdjOrWdjLL1e09mKYLttCmuqKCpt4o8UsNo5s0Nu984Z", + "9K+fZGsC1edqudheuS5o8HmNDtf8oEi2t0IR7LOj8n5xSAwTEJI+jRITQ2rjem6mCK5AcjM28oPIYkiWwLYio1htz6ygzcNC", + "Cfd5VxanKUjQOOg7Csu93yVqK6iCo2XQ2BfQUPAQBPObncFQOqxXhvV4kxXyOupqZ0i1JQ1WUd9T2wJYxh+Am4M+97AK9CkN", + "SD1rSGJjEwMRoG+vcOIVcQnGjLrlPaW+yXryh8xZpqoyJq1iWHZtH/Xd3XKSWP1ROKkDEui7sXTgweXRpszkk2kdN94YIMKB", + "IRdcO3Hju1YE2d25BUn9Q14Axo/AW8faD/r3YgV8GScRYGSqwAxdV+s+8EQhb2J+gSYtFY7Ds9QJGSeZTl7GB8oi8Wajf70N", + "iWe0HnlxAfnPyZtHUwhT3adBoB8ZxiL1Rrt42bKkuKPDx1GLAei2z97fes3S7PDVkrDuR8EWus7q+JWJusZh+w4/dWYuRxFv", + "oRDJHj7q/V29Y6TiG96KZOC9Nqo2z6WnwkGnnIYxEr5YoWIV+KaE+XH9fHX+cHAkTKExQQ7ci0zbWksIgO/4OZ5kOAC3LzZA", + "YEpEKVXbu+Te9KgMM406BAdrwrS6oeWxldFgr3XBnbapAq0pFxXGaWI/Q1bZa0AL7WCad2RPVXrHLw+fLxSESRJbBem7G4Xc", + "jbrdu8QyVsVuv1FvcV16LNMDgsqkht0r3DEpDJX6tt/shKR+NmcJu5RbVJEwuxvaaVV8GBsTRrMXEaDERYNJ626CnV3oVPiv", + "ELNIhXGlR384Qg4HVexVEeS6H1zVo+5y3y2nWtTTJC8GjWJi8aEHyOxLyjStjPoQJfeOCgQ1NokNGVRMgyk9zIi3rDds0KDl", + "bWeJh8jusV3QX01llDiEGyxLkNLe2YZOQokci6EN9bQMM3OufTD0heMWFgk0lSpKsXjls3jk1H3gMB/UlgULz4WLk8zObdA3", + "LRA8ZvXCGs5gFG248DXGonXwwP3T936QrSIXrcXHt5xBZA/1Eg5EDX1yLccJu2OH112pfKuIWjIPhJHM1bwd8fHZ3R6I3Six", + "ZfYnLZfDXAixjKE7sxURARQ3uWYIGGZ9CNysa6aqIEBs86CHFFGvjxB8r17WoiqgNU5jhPprXcnjfg0GliOyWTzdRgRSGBcn", + "juhUyRzcxA6ONeHjBjs8ppyOWo68bB3OXY9XYbIqbCIqYAEwpEexSgN6KJkwVaQtt24SrX/92jJWzYWyTYFJW4b00ah1Mpng", + "SMWmYZ+yxqU6iO0/hWxtWKrkQx5uLf6W32nOqzSEiw6up8ZJ2Onlk4Cf+5kK8PkOTXcvXlHxGSZoVH2gz1wEysyDBBPB6e/a", + "GGBwwPzmiuUiO8b4Vnr4mkaO2yVYTm6tiJ6G642V06IpcCMfpNVtny6wUIM0kRP3UHGuiTuXWS/hIBLlrafV4Yf7EzvRPSxi", + "8Uy4aRlkZvNcsWRA6LsciptfkYugQSLjVEsSrMBwdPveffwAocm9RD2LSi7Fz2yWwzD2EfKngOmzeWsqOe1yX1NzjrQRLakz", + "0Hg63Pr+wXHzheKbjEcVDMCECcRkyFYEKEQzw20w6kLoGqWCi1AFkn0GyZGeYsVwX0hCoeqfPinwuWDMgCQnuz9Jf1BEYs4Z", + "WRolOBREtVOEuyWU7SuWPWyidn/BzTo47e4wwYFVOKSRoklwmszRkJVLw88qSMFp1Jf6W7QX6iNpt1ftFKc9gFGx9IrE373Z", + "hvB9B4fv39LMzZGeHnk2M7fStj3vPBBNHnGp+zsyiNCordpxsm4shiY5TCnhhdhNSh26Ep+o07cjZ+mrkF2icwW/7siIwiCr", + "wCLdrtsaEguidUF9C+6TiMk2WC0enWZloHYk2IgD7RwesURZY3tYzh/0Cg1zj/wWUsUpe04PwvCNIi64m23VCPiUrbyWQvNS", + "iivHfboE3Fa2fd9xYA3WZKpMkmfpNlfKlhwdOOMGEyfyVmHhtat7jj3qNBp9Gnsuz+B79bwX8mJOJJjj6iTRytv2NihA16M0", + "GNO9yg+loBnXRc+XU+IhUR4dcZYB6MkPiZwmcmob4KQtYpdnfLkCp12jfYfJYqcd5L6+ns7NI23ynI1UnNSLcilPmkz3OTfH", + "vyYhpImXQzc9m6r9v3oGRPSpKqYJorhuqe5TiUdL2tvyRCLlssoA0Y1zpeavl8n0o5qlJOxCgunqB2iHt/UnTRTcoI6QIgo8", + "FgEGKTdrEpJVdnWhQ0JBindz0z1IGXmLtgInFeNYI+GxIp7dLbtuWuITq2DO1S0Sca/tNmOXl2/gjoKnl/S9qTamEd3Pqtec", + "jLt1qUIewgXgGor7kR+wVd41W+iBEtzrUVfUDDxXyv71ZCpoUphqXrNnQ5XbUM1B5NisITxx8EeyJ+FncQDo3WqEBLgFJw9L", + "kRxzo8gWf+3bFrCexoKkNnYTkIsF/TejGaJ92Ncp9iWGsAzh2yBcHPpYIbWAHWVhIRE1zXxZmrDCEgXe0X4Hb52nKvYl4U5z", + "jboV2NV3M5zGHTO4zDKAafSglHNbfMFCFm504kwUIM4WGT4oa/9CC8BarRYWjh49Or8+GKz3XGHnoZAVHoS1nGWxFXseel0k", + "HT5FGZXZrNTVwiEBbLtv7++ZfSlxxQmI86JBGdCvzV4S59hm81zxR1hUkFN42/b+5+yaoVFiJ2KW/+5+YU/7md0ZporHM7Je", + "KzZeyy0IBlI7a95BtyX6jtt23TVmMg2ewhxxEdsekkr53/2IogyGfgJ1QfTtPpjQFaGXqrphDrcdWF5d31DWqoDoCWrv24D1", + "/VW/30x629YB5YHWLJ5bwig7Jx+QwwsOHQZLStD8Ay1iS6dnP8sWINObZIi0GYcfCWid0J5lz9yIA0H2leGYmhQIr8WJFUm8", + "/Vkk0CWtpVM83x11oaRjDW4ZJMvewUE78LfNZTCcUCMFai2l0WHWtY3IQJFNFnXcWxYtq8xSW7LaudMOr1XKXdel0B0CWmZo", + "u678LYH0Ez+oPeMd9hlvdJP121ISU7MxTTLfOHRgiK4p2tJyhiGq0hotcSrPfvXwLvjR/S79m1kHGymfOF9kDkagBVarToYy", + "EpadaYLFg4wdHqWnAZBsRPeSdU6Xxn0TiK1l3lKV9c9ilup/YGxmcFAijtwQs/mRp3cOgTdAhsVchs7/HeeVdPw4edQV5GmK", + "JKU97LTcvAmE7kh4lAJgPvurqpZPdbzWn9gfPOnQshcDK7kJPeyQO9/c8n2VRRP7O/ZVMz6jypZ2v6OdGJGQ4NFwXC0eZrX2", + "wsKd91mPY1xcbEU8UkqqIUwce0WGHi0Sy5vNn4NZGxJ3CbjtfuuPIC239l93717+Vhv/n0muB5XcE2hwziWl5Cl7LbnSzkzN", + "cnBkWyoqOBv0CUqzwocmkHbcb5lBKfUaoibBuWh9kp0jRZIyL5id7ce4Z07+QmAlxHaLoKzziYmeSohDnBeutrOUZZm/OKaF", + "K7d0m4DRHkK7HsCN1INcSVtuczPzfeRD6Zu0gH1yBTq6dCbHdiq0ZJvD1rEiS1HsTerk9rxZvcveTQDg0pi25yNhM+6LrzMc", + "qLizeQE4CyStG3U+1v4vJSbvTtHHMqaD0jQtzHC1uj1U1O3zy1k0MTumZrJhLBILWJJo0e6CzSzQ/dlaMEentxb7c2YMF3Er", + "QnGDLy7LfUyU2ImiBfMtR3CBeoS9wlEXS6/tRcc2e/t0BrWsGmC1RfpSki2JPJWOVJUGLAfPJtFte8Iv2fHWuAN+f7bPo/4j", + "yC0Qw9rNm+wbZkfHLneFuL7g0tp2izmMrGaiaIHcH0TJCRNoisSBI34eet8LWeShoIryRt21SbBoQ2rXXyEOV3udmLCSfjfG", + "BQF8d0jx/VD23ZFVR7mabSkmcgGRqNQJcIOixA2F7OukOio1H1sn9w2gDs6pNJdVejUzO1qf1/byFOqpWugcqRiD5HfWXN6C", + "Goa75jtFy1eyle0z+Hw8Msfd8+I72nTOzEzm2COQ1gsOuRYoWdztWY274PW2Z0STwey1r6atGINxG4Z5QXDOYJwtUiiZ09RD", + "Hd9oYVD7soBikYW2i6TcKrRVb+DFIaGPXOXxWXv9QNGCWzNocJGhFbpCban9y3lJizJ1jK+utDl5IsuF76li3JlfjSAzQzbd", + "btVGMdoKtbasp+wdhsTMqPgqxFLsycP66HpYmnfvU7ZVuRBy+ESSuw1rFll5YHOoT63MOeZs29uW9Wbr74BShNOf8JkUHAKt", + "9CD8ha0sF8VNrnf7eAXfyQ7ILMhXyOPnUuoO26iuqGus+T0SpBSJ1u1QZgvRiPN9L3On2klbQMg3jddwY2x/SfqYvlucX/55", + "4rwY7BlqAmVx3yIYzciYxOsQptKwn73N5bBKCUD8HoDzZpNymzovCpUrAQJPIUtHvgJ9FzBlG9CEL3f4AWEQXCNe/UngfyX2", + "j8OkqsTOX/ZbT2bnTEDzHNaS1Ktxwfs8E5QW7xa2V7gW2odbxjqIGJYg/B83nuYLvBQ4F+PMZa7WnzcyRggV6azRv23cr1OI", + "F2mL66g/KFLebVhFiWhvEvse5upyhphnMs1zcvxi6DBmNljkMJRFS0BAduYhbJu1AMTUZVCIDm9RG9LTVnzhYOZ3ZEkFrzXU", + "asZtuKeTj9mNQ4Y/BTCy/fdY1KjiubLtqsjOMuXpnH0WdkbhuSOBeRQCJgebl6ukvLvOGsZOJSzo+SumLomraZCQ9XofbhNJ", + "qzTAQp5ymM38uEOjliwQGdE4f61ZXOKww5V7EsL4QOaDO9KQ0zgr22syG6YvbjG1M0kJgzmKvrCnMktWVPEwMWsjcQQd1Vpf", + "GfS6i4lbTqqayPcSLpQKlbCnteV1tbQmFPGgtGzxtXJYHDo04gohuWoT6zhD73NbLp1ljzn8FqHO+RyhS667hpHfItYg+rq1", + "pVcmwhQp+n0wxVIkzAprohu+iZ8FWf69AEN04Q7N/W3AOdv3Bn3PlBMgk8E3WTMTe4u8ZeFeApjoqDqiNrtZCaPOL1eZV9h3", + "K2op/Gxl37i9TbRWVssetajcNJmZ8h0iAz84S7UqwpI4JtaRzb7YG5ezwylVPHl9pZfINlk5fdPJYjs6H4kXsH219VlCB4Ix", + "B+bQCk7YATZ5N6KdDa4zGmx1Eis4ka8JCZ0jkncGjyuSDW63EK6g7DXzBo0riIwkQp0qexppGkY/u/AI8gHqTy+Oamv6uB96", + "KSB9NI97qFRYfhYaEEDKVC9kV9Ne4XV7OOur4MGT1m7YsUQQl0OKacbewTPUF0GS/WVGMBVrNswh+9o0fwokZl9erVo/EnmA", + "4F/DXAo/BmtTQHbNHCYUjoY/G3W+jjH262flXr5PSiqDh06Cb7VBq8ztnsHnSUEqrlmqtGeJF25JDbTi4Ozs6Sy3nPNikpPe", + "PAsApEhL/9cewGkOHJgVyacmEPjBld3Hrh6s6sgQrsrawKJK2WOWHVQpCYv1Fnn7OmPBD4ycP+8o1g7sVSSB4C9kAP0ZXV0x", + "hEGIJdsuBISlxwf30zNKaCJXKWVfpTN3Lhj9uI4a4OckS9FkcZ4o/58wN2qHraeZQ54W5kgnWTDUJyGpWM5DMPGMWULdZOdU", + "Yn3A1uFrFgFowqloMkBMp5fmvO1vLG5GjLG1EggL39RBTtn0hMg5Sk13rY3AaABd5HhbFqK3+zDYWMcpt+p9y8WfhLxRR0N7", + "8iu0S6PiMecFlh6TKzNgD0Z0uFLpZMriBvzJK31cmJY2AfqtZJ7fy8H9+lpfkONY9zWutmauaiO0h3YwZR512GXb8JqqTGR8", + "aI/V3h702zjyvFLCIyhtTDKzM4cMz/jBHsj0CctZQ22gs/wVWPTFnZuAdkc+XntLEdnFuWQXMRtfJIpk9A+3kXqtms3KnJez", + "B87gh0WVIP5mk5jpE/t5qrzS3ujF2/0B9xwsGtlGseNUycGx8TrUgtzmVrL4j3TqtZ6TrjSsSoGauJ9sUjHCc63al1R5uBqe", + "SW8CYhUW9CGGhlFxOPd2varetI6ZzQLZLXsz8hRu52DDjbhNyXxN6hauWX+yqEEjbtdrVDjPh5rjR1H5MdhMVSIobAj/16uY", + "/CxLe8g89c5Go+D8hh3eCK2QfNW5KPfBuDjkmvXQYTsxzhMK46rRLciSwH1DMwJrQPukelKH+KjncYBR4CzCrm/asgd2Qct2", + "UVNOurX9ErhXMvduK7b1Tk1FvyAkyNNarvuJLkJx+wTrUgHWyNe7g6Csy+zpVAPrWCIHuUzirJbygqq3j9gi0t6lsz+qTX2f", + "GUectiSgy21vooJrgqfTodD2g9lZTZXgbaDCRlx64NrNkWuw0122MTgX0D+t33TYk9gTVXhXguSuVBn3z96F/+N/b37nm/b/", + "/7CwXu36BjyBo0X1rUW3SXiWoyAr8WQHogTC3xuDVEyTylvIAFymOTyE6r1KCJsdWQFQqk5P9o/2ooxHCSzRnsf5g11VltP5", + "4AXy610i095LHx7/4H2yE14lQ93/+Pt7wS8GRq5Pz738i59+7+Or5z59/nGpQvvv1x5Ov3/6wpO/+LPvQnz52asfX7/+6YU/", + "/vR7739y/YVf/OD9Xzz+9CdvvWn/+/mp9z5+54cfX33742tPfvqnz3z87gs/v/T2z99+0T7583PPf3rpuc9ee9TXHdPg1hND", + "wQxCWwUggtWBx+uUKrctknGwLrVxBwEa8HwcPxNMmGUXNZS4/o2XJMocrw8aKdMxugzloZXygZIiy0KBl0rWT6DBrOsDGWCf", + "uKdeGdIepuqwmdpiYnDezTGM18BJRKG4c3k2daT6G/JggmGzfcYykBm4jgSD0IzuQHHaeC7wreh32xfT77hY5M4qyN1tVg5X", + "iHjdIEeJhPSzwCEpgg+0xUrIj5Zk7gNnIBj6fkRmw4fB/NfyQgbv5odPi00S7H/OxdjydoJd8jhZH8nKKPZJu8Jl8m8GW2Gw", + "cYKRMd3rw2cxhzk7L+bXcd5Ocg2KjTLuzb/f/eBdclW+yZl/BX8l5kKwFaZr2qdwxTfIU3ktu1fGjUh+xavkFNU9gxPzcrr+", + "ZbIjBrflVb5HZk3ru78k66ZYDhNPpn267cNHwHNJzsi37XnxLGA0fRKsoc7YeSnjCr3kPXwBDJ1gF/U+AQdly2552Z6e/WPj", + "En0D9saL6Fd7oredefECWUy/bc9+0V5zBtAPLvEq79v3vp1xSF7Onv0C+0nMnW87iyi5J8li+ra37k3xsHLE9JmrfKY3nEcV", + "MwBPRh5P8kGKLfNdu8N1tuCqX8fHEcyVZJa0e9sT4u/H2QLMz9S2D37czlvxYHJuvWM/T/isuZZ9F8/yPvk33wPzJUfxCjhl", + "OQP55Pbd98lpeoH9o/aKm/V9zXUbr6uJKRbvvu88tO/wOfwzU8/yXjYWV3U/zrn32jnMO2sGXI31RX7OEx+8lK2dd8QRCy7R", + "xKJ6ifPoXTwfn7ZdL5fR1zbCXF8ZB+jlliPU2vIIP33RWvGseFR9TYnhVuP7LtcA5u13bOa+y3Vz3H57x/l3n8jbz/V4wVfg", + "NY7/BbLEnuB1cN+37F7tHMY4tuso8aFq1rG/sf/8uXPZWv9k2twnqMJ8IbSkT7r+uDTQITkd0tIuIS2NbPvAM3zrufjlvVDH", + "ts+81EqQt9eRkPSr2TXPhHw5Zabx+gm+ci7UtE9l7TlOifb32s/j38tt2yDqndS6dd9rVPc+Hdd/Lj5zNvTQk0Q1BcT983qK", + "F1zBXNd06fYX23u195WE95P85Tl+/vVMFPsqb6fW6rne4r+P8bmeC1Xu90Oa/AobJiH4aDZe/wE758XpZzzePpe0s11zPPXS", + "cyGA/lpIvZ/M9OWlO6+HPc/7/kV8S/3/cvRJel4b2Xd43/SMJ+IzL/JBrlA1/pkQ6U5j/UKM4Ono27jmK09kguZn4u5prI+H", + "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", + "5DdLtyAx29x2RmYFnAd4EDxn2/IpBZ11J4m8B5cmK9C3Iak7b/90gkh0qFR70CciHHYv8jurG2PQnqjYwjO/+5n8i8wMg+wR", + "ht0aQtbaExoZBuLzawFCZ6XAXRnqtdhUFqrsV/YoxLknYHAIjDvhTxZMQZ6kIxBZh6FniSrt7yCymZjODo+3kB4sDkKTK4cW", + "F62uaW8ydx8D3g6T3Tq22Da8pfqrq+bOfO7Mjwb3ICt70LpstkUgkVmghdc5TbIH/e/KQCRzHslW0STGIdF9O0Z5DSwc4Alv", + "yEIC5ed7UV+IKF6/KpFNHJaixRhmuTgJ3aXkYyHFPu8qxraDTM1JbIlFcZrBDaFO2rpt0ntkGKCUw2Yqwvlg55HOYNY4UkGH", + "be7eBRY7wE1zvElLKMMyR1yINZ2A+SRmeGtOkNFwhTm4QZH2xNbrUAqHDSeqa+GwKVqdhGVnc5j1kQwKg6wX0xc2NVTs0CTi", + "4cRFZ698EWlFsvKiPDFPmiKfss0cNapGW9r9/Z3FIitceGDctEUnXlziRGxjpgCU1nPonlAdKHZsQQLCGWsLyHq0+AZTQJGO", + "nMkD3EWOGg6egUrcFYFhsr52hQKJ2pct1krMAs5H7VxVntKw6TJU2oEE60POS6fPJC7BMSIZf/nSgqQVYuvMqzSc7SdgkCzS", + "WrHZ9SAZk4auzlqkynfcJyu97k1aWWZbC8y9iAtkOAUWWsyQoyAuTbR3vYnQa9/MoWzebo52wAKWcrzFIC9uaPn8pdtM2hP7", + "zPq+hWO7mw17lqM2G3e39Shcp+KoZzblvgxBPucoCOFJMnxR1dLZOSrTJRY57bO8S4txRLI3R4zEVh1CsUOKWoJ9KMe4zbUJ", + "TfvoghNh87hLNHki9Aht854TdpSrQhm0lMyA94gX3nPe/YyjMhVSkKoFqU58CryqG4NNxNUlA64C/lIg3jSjsCXl6M9G21nC", + "1Yhrh0DBVCFJFHzVap43OVTv870g/lFCUgydOumKDCPcKVo+i+WpRGoCDjn/UAxe1VWKzGFIh+xs2R2Aku1xr+/DK21wIhaD", + "HDrh14n5DrBYUgM9CLCEJqTgA8HpKXyKnXxJ7rfdYeuy7wQrEnV3iJP+yB+uaIvBbFuez8tMxMEevCKB08LQZ3UvO2cOBSEG", + "4emEPBacL1WOA513YWNJAPv6qaMTnSETs9Px3sxKJ6IA7FGBJBWEL7Go4sOZ5EVCIjeOvNLK8jLIjUFstxmetDfBHr+1FazC", + "ThjO04X7W8Lkm2lFTCo+tjSFPnbgt6rglQZVhvUIksVBoiJaa8q3IgvpEs68pBaviARC55STIhVVERGCiogZL4lIkB9s3y07", + "pkitnPOyplqcK/kmiv0gzbBtIskzt6Vk9jFxZDtVNlKzKY+t2qAoTIhimU3yT+N0DAhnWyLQKWKZidssAWtsIhzId/8WtGct", + "2JEXzmYsf71JXknaxDnJPYR4ZK9z7RaZ3k7R6sg452Ui9Snb2jdS6hBOwx5NG11Ar2VeTNcSWHNEVIeTwU7FtlIAhHeTPjQh", + "WYuW+BswdxKZJKaY9Iudx6/I8fAsXa5LHYetkHFG2VbAPhgNBg8WgfEJ7ijOnaxgqDdZ8j2VP4IsW1snuGxjKhBgVaAE1T6R", + "EQiCQTQKWm3Ltdddz8f+yQt053LzuAke8YlqFXweOHsZBYMJgGw1PW213+HVik742dZyNUfIVupILhiAga7ddzCD480dmnZf", + "/Dxlr2A4Q2LG6Yz8DMZMszvxPFwZmEkd9FezeQlohkbrFBm5JwDhTd0k5qpE5+xQlCgZb4J+lAA4lVe11EMsGOLsycs2m9YS", + "4gV9wo3NKMEhcQSrUMwMvRYTl2EDSTxO+jK6qWt1b7MIhu3dqkJUgW+oJnBSRCGldorWKKkbF70PMj7XZMbe7oA1AcnGqCNZ", + "rajkCQhXy9jWiorYRRwrVhAFXofQsh/vZosFPtBZmbgiWyFeu9qOvBQR52nCimG/7tVetHp3BrQvDuTLOZHs42NOm6GTKVPk", + "KkpWFlWp5CvmNfG3wTsDcz9IBEQ+7AxSMFenbM9Us9qItkOsHEDzfbFlzxqstUTRxF5tVwl8FR1PACAReCqFtA7J69S2a7A+", + "/f8U288JwkZ0JEQfbGFESQT2kHTaUisnqYI0hVfT2yqhY1Zl7DJQ8mGrl/PK7cyBQnminyOofwn+PBa05UQDBZWRo/Q+zjmA", + "HJuc1b6ayQ8JWe7+Ryob8HrlFrqVyOeJLIxKBnGax3Sz+8xMzarEKkq2BqFc+YPciMEF1VpCACETcbzbp3NeCstyIM70phIT", + "7ZaLD6RiW5w/2YS1PbEKTXj360UjBEINovo8ppNvVdrDA1s8kw9J2ePWJTJaLJlUWtmSYcOMiFjAxMkkU4VPzuDQeDgJTGb9", + "bsiPkBcGZWx+tNX9rHBoYVlwrChXzskbMnr2RqdC0H25365dLI+ebXqxHsS8udW07PRewqThx/6caNN79baqpHz2hgJIb3LX", + "IMMKfyW3/TNiO9IatQeacJy+2KOW2gGBAel2Yvgwi5ZbaqsaqNoQCnMeJeBr6QzLn6PvNmoE/xPJ0CRcX3rSsJLTruZ8oOKU", + "yUtZSheueogreCGvsC3z+mKCtEKbJPQ7iDtGUYdcSGujK22VXXCPH0kQYrMY7cXtOjZvB1fK3yR6MXz0ln4KG74L+TEs4gXK", + "qnjMKpntsROU0vHSCZBt79ZsGWa9mGjJ1kg4WXJF5oSzTINVBGbTZrwqcTQpcquG7kuKfvUGZfegWZBmDZO7vY0zi8JLPZXX", + "sJQ9EV16JYoIl3DIEOWZSq6gbp55lMlKxXgx3huqIgHBJ3fLXVW3PSRIhRWA1OR0kcO4yAr40Wf3R4EOQ0Duo3ShBF+gjuco", + "MG2y+QJzGTU2DqJPYNHSNpIEW1/MajKW8rqHSaZmhcOCCNqj1dAsypwcsvxqcHdgI0jbICq6g5yZrU7vwLIjkjv8IevcuhcO", + "L3fYft9eRLkF/Mngrckfu1n20A/jqMF8J+Psji8X9335SHHgniN3fsVJ4mV5sl6lWfj9xq63X0eoQ1VbqK1NwY08MBDA2zGV", + "Z1om6N6kjchg70ucAYMmcxFsVwI/12Zw4Tn1oKZ/zj/Tp7EQhkUL/VYpblQZN9ViXr3Y7sg2cRYzZYp98lyDgTXxu4j4r80Q", + "+Pmis1w9699ZKa0XyuJe25kn4/5g2DxoFt+Dmzde6emP/oQ/xeH11y+RxcvTEKtSigFnXUu+pTxIgoSi4fzDJRlbxbNyc6Ve", + "H3N13DHAmQlt2NvmitvKrrTpPbhWb6JEhTkKMzlCsd05JDJ/IhIq8hH2OTbb/ZicEcRWwXJuRCQSK6ftXkOdg/d3cvIVPpb4", + "qN9hKQ/OLe+Hb/jbv3vgt79wl/1vaSo1Ej9tcph3sjCVBvrWrnxZzjcZNdDsgame2F/0zas4MByWExQZTMV6pk6cxa8CGzwa", + "Uy5jMtdZzjkppu6+vP82zgzbO6vRbYWrT7mNPFfkwfulXp2xklDYMykXZpSi2KtHlFbyJ1L6QwJCnWJmKoCeZFtLl3HbLFTZ", + "BiLOkKRIso5trfA8Gz3vD11MBStEJxG8/BnXPHlJE3FJdzI/FccuDuYpvEYjFY2JGklFgXbvzvv+fpA6FVLCIEmlHwxIrsB4", + "KhKdj0RikqjXVHyCFVTJiFEnp0rasq1cFqNia8eEd7zqvdTO1m1Ws7VH1tQKmFGMrXHrdGpfx06fcQkWU6kV3ySxQUUtYlp/", + "OcOD7Tx5OmJ3pgVn4357qylhV5tydWeWplISGVMv6h5cxUHfW9IU88wMy8xSBbkkD8NmqNtYEiqgdy0WDzTzdbfYbzO+VVfY", + "s+e3O1PbaaF6qIPmbA4AYmf0PIKTa7kxWkxlWPaO8nAI1HWtoSmajTmSVFy2OHs2ffbMP9BkSycTeqV6F7e3yIyz2u5O7Vuz", + "R+cz/bFZmeyjLv4ZLqe4FaZSeSjP5c4VU1GTgw9VdvaE1pynzv8AIk6DzTbrBBsFyT+aJHSsxYkXteOzUyEwMA+2ClkZP15K", + "jkQtXJuaY9KLz3WbeuI25x+yHWhmCSzCtoCSv7o8dRnXTXSHZnYqRb5jagtbnsootdWVaGum2IejPi9PXhaxc8SGPDbne89q", + "OVwhRZVtK91qZsoLjudkpmD3wlTAONO1kxBkthMtTSVkw1GUesqR+r9ff99u/Yf1f3/78ZHCP40byb7wKFG57/N7plILU2mc", + "JRqMzk5UdSO3D+ujU0wdTjNTzm5RrZrl29SlqIFlzUakqmW7QH8uTfkzZGohr2wYZDLBERmt6ZeGJOZUtKFw/94T2Yopx+7m", + "sXQflc6U4zoVfitcAsxHumnfSGTVu7GJA3uBiVhEbsEdCN9fAlQh9EbGtRO7InS29AKnW6q8dslWO1j7g1HrmGGitpWesKjN", + "6wOziYMGpKgZafLWzMSsS5z3xBu0GRs0NCO6c5+sFXw/kKeeikznx9zZdJLQ/1uaOpqLKXNGenLRHvoOie6AO6aXe9cyfFNS", + "u91RyHwSfoDq5LTepFy9TMao5Jgx3IFXGF8DdUsNZhsu8ixabdNjyg7ZObWKi0xpliGU2Ktx0Z1T69bVnv00mUo2izttGDz6", + "1HhLiYksJAFXssi58DLRjxR7WImjxFe4Fm7upYH3I54UplnYVNrBYCXXaXttpRYQYclEsSkvCaBQL4Xd6mwFFEVuGU/hboop", + "X7JYnMIvZUwNXAEZ6Klp2aGIHgA8IAlZZ9ztNo1arjJabFM7eybdd+vZURdTE2bKLgc0yomi0ULy9lOKEnMw0sBiexpWPId9", + "H2EPphz5H0IvLrnlUneMfgOLCicuo6b8XvJkM1K8vVvHMh4NjxY6nzfCA6KY8HW7Y/oB8zgpNkjbi3oe6fEgn9zBJsQTVGM7", + "5eilALGCdhnPp7OAZPW0zs3k0b4UhRHXSx7OnWrmaHYKiSfYCsttUWfbRtgkceqs3lhV5NhIQZx89TVVpP7UL3szNkHP86S+", + "9spxDxs4bb67/ZnuoPd8m5edmUppZrKELuDBjB1TL20dLfYyD8GkvHUizCcKRKlhz8X4kkagaN9KpkgFvqVWl4lCJAgjQdsW", + "K+DrME9boEu5VY/KWLc7ZzK8UePMlEmihGiOsdKkx+695247fb5SkaKEecgEU2uwo3VDu52WVerPqYRJ04yHa1JISZZc4lID", + "csAWIGN3q5Ov29nZevQpFR2U85mhd2jKLg8vK+kWZMp9UhMKdnJGkr2Lq+4dreJ8rNsqQrsHp/wjnaI4zDBqXEpJ6m1qJq9m", + "7Dr2ySmndWe9JpFrCl+tgS9augNBk1+nNHzCxXE03aK+z/tTc8Jp1QZtPgvxuK0qG/cDLVOF3WVmanuL0167APslnSuzU8t/", + "CrDXTMvVStg6xC6UVYsdemE5n2jFFESS62g8BOgztDUSb86iW55ra2vfmpmfmd4oWkEZRi+T9ixSVFMTm4mXtC/RgkgBO/cU", + "wyNqdcXtKlOpAqa4W+zuVFNWMu1G6xHZ9uI/sUNvEMlDCd7kLvRURG23q4+1e0HkGTwD5wRjPBsDtyVGrSQIbndPJHJilGmz", + "sfZJ2eqB4aRWY7Lk/OjBgkeAYaMqsusyux4sNTnUwH7keIkiM5Zmds5Mxcil5pXkcRK8k7ti1k5bM23I3WckUiiOdDjq4goy", + "+F2ZxPee9poQYetM4S0y5doChy33rIjYu/Th/k5/0Ckk9BbSy4cOzZn9a+2iI4+2tFLAEYath5BvapOnHLEcrSgwa/I3SwYZ", + "AqFh/ZKpxSYSt2Ducunu4BZqk1w5m54d7Z7yrptWj8lzYGXSYSAaONHCDAYuQNP2vvw2eQGZj8cfU2cjNo/Mymu9KAmmJaFy", + "sxRammzZZ0zaeVaVvloSeAx8aqZQk84rRrCc39RmgZ/MTfL/WjbQLKgIyzg6XVp6gyIjTHNosq+VEE31ZVbkJ7qiMYH7yPyc", + "Daq8rko6WwL0VZH4ySctmj09EbZkSjxN7SFb8pVDCXTHjlvv3sqbZ8eW9e4ULDAStG6fedbCF8VU8Hw1dgEl5Kbw+XMtRxYg", + "f1P++9IUhtxW2Fbz4GAD3HjNgzbd81jCBz9C7b/YND64htrl9q9k3Wc8C/WW/mJ1OuvRWef9HlkIogI/f+8a68jf9hr563lV", + "ur37F6pF/x+/BwaA9pofPv3BRXIMiAUh+6S9/6xzL5BvgH9dV3W8V3nnd3jZWoB68KusT8+YF+yv9ppgI3h4igsgq4H/8Dtk", + "HQGfA655kXwHqjEHN8LD6Rrvsg798dQrZJNgb7zLevg/ZXX7RVaSP+u98h5ZBq5O1e6DNeAyq9HfJafES1PPh0r9ZxIvw8Pk", + "gnjzw0dwt5blAJ/0yv4LXhl/nfX1aM+7vGu6A0Yp64nL/HmJte/+vfTeOx/8iJ9+m6wGF7wa7bGbZ26+/tGT6benokKIVVxX", + "WMnl9VRtdZuq5lId2xusO3qV1WRRcRd1Ri/bZ67YXy9NVXGpnurMzctZddJr+SfZGrumV1W9rGoqr3tCjd9Z+96j/t4J1kzp", + "KlduXkd1lz/Dw6gBs08+4d97g9Vjp6cq2aItqGCLtrx88zzr397wmq2Hswqyl6f+OsPnfQp1g/jroxNtrVbUgPn9zrNi7C1d", + "kz15xv695pVcT6EKzu+nerRzdpVr9l3VsD3qNWJngjXH+/OJrJ7tZdQhtnfPn8HudAb1a+m966oHhCia2YMC1AwXkxCmTqJQ", + "evEDvzMd1c0khUkHKvmVKILBdocNzXOlyLl8sxXMW/qt7mCVnFQMPjqzp22JFbJES9MB46nMnFm+01v5dHKnaQNh6xXSelMh", + "3RmCSFYhTLtKqG2knuDnA7qo+GFKVuaJmyYiO94qj24o790pMmsvHS7g6RQocWb68ItLRXy8DSPQeZ4KbdMXzfy1XYtTruqU", + "6d9Z3jWdhVuZyum0z7s6GDxY3xJBXPgW+uobsp337VnMNURAB+o65n6p+elkB47ZzDuaQn3NzOTJYzs7l6ZHJUu/4cqdKWxB", + "p63bcFbqIhdh8SRqzCt5bCks2VmeihpOW19L5ujq80cHw24zF9naQulaF/BOrN0ZeyoEI6atNWvV0arXa2ULipzFfed0MMN7", + "xcWwZzLV9jBpPPqblNBH9Yorxrqxl6pWphyefdOpqqViOhUfyQC3Xr5IzftEyTsd4vy8Z15tNt5v3T1piebUjDZtgXogT4NF", + "EIgTudXy7hRTa6WFm2nGw6ltbcovD7F6B8eKgxvj4epGJlyMD0/7vcR3ZYtHQJYNQs3MiPvWrtnc0tJYx+M2CceqS/s0azKA", + "5n3MChCml5am8MsZ1GM87M0yxty6pM0t3k+k5WQOT1VX9pNXmwWs2jQF75v5PRklID7fei4KhBVTSRXGjdr+i+oq93xaQC8R", + "k9O72fLRpGnNqUIq1K+DvByX3p9peGdGf3izwf3rkshmmAanpPueOZF7Fk0Sp2W2ykRrFrIviKZM5dlCHnzcugNFsOQy5JSH", + "IYvct7MRzRFUjMP0euVW2ihZE9lGX5N2pd6V6IwjZlcmmY680yfactaNiHZelzq9tga2qi0NSOtYIIZyuu707umNUSTwyS/M", + "wmThymZxpq/2JbVoT4jBW57egnKQI0Ohg637h4Otcr0MtmTXYM5qUCL6mpV9YIKIVs5c+fU+IKFVH/Gfw4iX2jO2eWfd6BDz", + "UmlU2q2KW2FWGLttc1Z+7HawTk7jWZwLNMX7p2qord3T6B7FcxOcLi92CTR2mwWf2kR3zpiDn0tZpbmqTYY5EcdLYpVphrol", + "sa9uihxkHEeMajoXi2kYDpZGprkj5sNiVpyIu5LKoMQM2yNV4oc5+AubW6pHxYom3ccZ0nSIoCmxAD0TjBznM76pi8H/821n", + "hgFdyemgFbqYcVKdDoqP51peF3z4ojNWnXreaUyc4eeHwZHyPslAzjltjr97xVmYnPUlb1Vilfl+ECslUpHg2sJ94/POoWRN", + "fZJfOR8sNO8Hscy1jFvG2vwIOEbwlR/xyj8m7cmpjHXqhaDKec6v7Jd6MThzxMTyfHbZn5IZ5ulgUzkdzUj8MGJAejXePTtF", + "OuTMJ8H8k4jC0qB4T55yWien5HqYb50NypfX4+snguPl1YwDJyihcKM/j1bpvuJ4eSsa/0LQlD0ZvEan+JZor07wjk/wymIM", + "+3YQOp0JEq2X+fuPg48op38RW9FPgwHmGfaMrvx83Pck5+EzbOd7+PcV0nk5y9BVp9DB76eiD58NZio90bmYPz9AY3ApsYG9", + "yktdjUF81Se2P8K1eN7oSZ9sz/ArifnqtSA7ej9olC5H152K532VVEIvxndPx3WuxBhpbiQeuVdj0p4KSqIXggXoTMZy9lZM", + "Zt3ieKygRD+VWHROxWp6OHaDx7NReC8YgcQv9JJTD+HDz8WIvx6sRKdjLTzil/J19O244Ivs57SfnGi3CO9MNemHMduD18uv", + "LG6fi/HhmLHek4k0LLoOH3vOv4K3RNkUXF748/W40QuxNYFFatg0v5NrbOweTWd5+HLO5T5KIGGm1acN7pmlW2AYxVRdWa9e", + "vsUrHnnN6Lzt5bzU/KodQg+2ma1i+jzZfYtJOxPXT351Oe2y71q8JTcE9HLXzB0ZKPuKW2zVFp9Ec2hf8LF7KLa4XbhklGv3", + "gTIKXcewqpcYiYVGGigCqv1C4LXewi2e3wzgGLneWKJ1Ce3ZbpfwuXvoe1TDhB9WQWzR3DIAC7fECpwD2SzTZmJX2OxMm5B7", + "RyQO39/5OjL3D3aWyUlTtMjLDO0NON7izC0Rg7liOptf0sRuNbtucdaX0v09w7h4SwcIp9CaqsTq5OWZxTTiKXN+VJeZ6XDB", + "CgpXM3zN5OOS/6Gz3LnFo5opiqm0Ki689z9lhR2eb7qjWivNDptVQVeiUClunzwkVXDnqwdx0DdHG/b+N9F/39wGfDVzDbNf", + "BXS5xQ/JMLDAeTQ5Lzi+cFhZpyRpk+sNqwZHy8ftxH2O1EgG5FTJCK7JXugPZCt2luWqtFjJvMSR411M40GnZ9eePb4+dpt5", + "WELwQ0WaKHlRfCjzo0k6Quc/09aDFusqZvCq3PDOtMO/+y4W0DLDXDaD/twty2FHc/vkSLmOjP9ss+uP9vzXW0zbpflbXmhn", + "ggJkt7FZt93mfsNtWX6MHehBoRQEbPF9jmvfou9RFEv65RYfZOThjDR/V27ZXxLHuEStd/3suZ+9bf9962fv/uzaz67/7Oz/", + "V9e19UZ1XeHnjMR/OJkosq16ZqBEVYPHExmbNFRJQKlRUvWhGs+MzcDYQ+eMsa2oUoyBkqSERAolQlVCCgmOG6gDcRgIxlL7", + "B/Abj/BSqf+ie932XvvCiy8z57ova6+91re+b/ccsAFjzJzyIA8w0r2DEfABRuDvINcxRtjN788xUwGRfOT79fMdzPl7j77F", + "s79AhmDgE97GnMCXmEXYwm8pY0GMysj5jL/943UEnvmUmQN3sHse8xiQHdji7MQWZwUe4RNc2j3HPLzEGg05mB3kG14jNlvz", + "/Px+u5/w+21jvgSZss0ZW3574NHb+KzUPltBdmTTRfcVJx7zkqm49nmIdHNcWUX84aeNX/+gMglrwNT2ZJ3Pv/vkPnDm0fWe", + "3AKWMryD4yajsz6yXH0XkO9Nvsf7I9/ehuQRPJ6zb8wTnKVPgmd0nHd8v153ptvXYi02l0+53GLN1VAyYVk1XKPQxiHIjS1d", + "OKmqlhgK0DJds7gi14+a+znZYRVQDCdSVSuFYPE3RQwQ9EJ/EggesToLHFnjSK7sRouBeXPYOYvQX4KUaMsZfFSd7y7gFMbJ", + "LOqe2SGQlOwZi1j2mBv2FLxIC9QqV/3MKKw6EnPmJvTcFoDE21O4Y4oij2N/6yASmR7pF0H1+lxJ5ohC6H2wLXVwQK5dEG9m", + "vDgBonmj2Rutzmmsdx3FftFZEBfC4JNdETvu/M1iw5h/8wNCI7Wq56GB6lOATQYZNIhu2hqgKFExVGU09HhxsT9b+nWxVnAo", + "TQtIPN2qd1RYEsJY1JtZ3sLoeLjaZaE7hEAfieshxkSXU8GjA4JjliSXaBnwK28QkKCKxlXdKuLuZtvLxVrQtXsKUGrTKjVB", + "l52IMSgWDG8GCyogGWcziqNOGo/LLFr1HFTlW9nJdgeQNT2gEgxcR8IaNfp2xFg+JAnCHT3exRBWNsGKuaLgYV+fcwId+y4H", + "Wwsn6qBcAuxuJ82DmG9bJXCxoNXm6vMtth+ukscc/C4JQLGClmgoZeIcHO11EYT1G/PPwgxUDGsiHAHMIioH2ZEQ8aKowAgW", + "hegUrabKzG6SG5Eth4uPS0xNIJgCDnHevTV9GFPMK1KaZtuDZaXAx8LoY+6XQgEyiDxUF8ZEColFKMuDUol2I/eYvzBmymBv", + "Em+qz3V5Hu+RibwndAsKgB/LtNCzGTOjmbYIHi0U3OWtttkKQSFv9i5mMnNXA8G20MHQeBwoZ4ZMm8cfhu3RJTgciCRh8Bxk", + "nagTmahSiCkUlMnfQpSNa9dAqJiIIbXzbsdWxSAyWBd/S0DziPGILdkJV7k67fM26C8KHoXYA6jWxl5US2BjPfQ8YvLafVtW", + "oIV4WUnHDBNW2CTQoi1aqYCCI+iutfyk1ERopL0TYFVsgCgS4J5laPeXuiXj8/asMOPUIsvhAVILVAmb8gFcrtfuNv1Chowa", + "yN9YMT8e5+06Kx4poZBjWeZJWHZRmLCn7IfHX4cIXBw9FC/HpvY4NyFvYTcm9ZkciBPMniw0wjbIfUDi4WNqV0obpbET9WUz", + "32dyjidU9pVdikqqjagzVJy7wtNauz/ogoCVLyERyXjR2PPT9YbZfiGKGJa/1nDx5f2TqsxvKHrm2hGl+4YimqNqJ0i+0i+r", + "Djwpa6ki3TCb4nr/gFnQzLoFeDSZhNHcL0QOWR43kPaeiDsni0aeQ2eKwmMxCx21YrSjVLxmfHt4rFcqna6xy1w92VQDlAak", + "qwQUrwDZ7DorioxDdBJdHdZY5ATqRDnh3TxyQzweaijqzRUkWaBqND8VBOuw9S+sq5p5CRXa6yLlGEmo4o69+uLUkcnp3x89", + "lElXaNIe+lmshTEpr4MxquLj/eBm45GjAXg6Idtc7EBVaWBcjK3wq56gX9+o98zzNnVExzlVXDVNrjLU10ow4MgySHvpZZu9", + "8pOtFcQKmBnDb6FGmtopcH3mLDJNdFQNsR7h5J5nkdvu12RgdUe00JSj1duvpUCL3oFx0lHJdUCu4qi3rB/gE/qVjcIc5epO", + "ZFEj6bDZPhMVCiNVprVAnXuhK9yogM6bouAwNny0KNUI6qOg3+tZGGOajp452tf0Hb4YAlGtXrfHJD5mIe4s5kgg4RVfYvRF", + "q7PRbs8MNSoRttw3k4cnONz0uhkrM93uSYsNcEwZCzRy6jZ3K3XXzihj2WtrXlXvI9NWvwPxswYpxlLy27yJhI9GpS9YW1hh", + "1ckK5Iz4P9LvK9XIWmQiJxayINWuyE4s3SdsYBZ7ziWY7C7QkDZuAm2GYbTMGS9nMedSvPwogH2Bt2POJcQ1qtryBwGdiwMY", + "EEhg3lXn6ExohhuCevNEHTE1doxh3MsLCBsnP2cCIst6qjhhienGXBcNrU3MHydiUmEox3pGRkrYcOsURB7Rh5JabEsLnFGF", + "qtAa6UolqSJ1jMTkRGreBIhHdns6qoalY3R1KsBqIG0IDWAzPHpI8QsEhwI78zYFdlrZaCN4N9CcXcL8mPFlYTBZ/XnroNsp", + "eW7tkmm1POBCMPOU8U4KoXKwC5YXCGGYPS8PasjMlk5BAnlkBrXw4JhTDSX0b7cPxR+5qG0KBRPw8yjed9wn+NW/RNwd7jPt", + "vYFBYLl86vipAGtnRl9kaAuOHVOoj+pAztVFE8F7XT9KC7KOPsYca1GZCMr58dO6wgHfXeB1Rbp5cWTM0fi0iV+25UHtsIlx", + "Uc00RRyXaWFIhrjV9o5lQTLK5yfBcYgrLO71KssliAirm3A/ZtF2Xn9LUTSbfrB/kM3E5znVRk6Xx5/tfvT4Z8Auo14Y6ZSF", + "n9wgFTBEkp+H+C4ruz0IVNhE1Y5jnP4nu5c4qnqXFd4grgpx3R38nyPDj3/AM3cIVY546of4F0V5N839KBp7D1HlHGNGhDfj", + "uvnuFFH+GXX9SNeM7g647wf8FsHzQEwZI7jbHDH+6+4niDw/h7j5Acd6QdnuB44mbyP6exs12rbw/vSmcAzh8OWTB/QWrNIG", + "d/8Uj3+AmnLboPKH+daLAhjYlITsBcyormJu+g5meym/bAEMSneMJZzOySnfSrr2vqTXL0q2mlK6Xyutq28VEoDy3VqBS9AR", + "8LmcBXnnq/j3V4ziYC0hQlxcVcnfMyrtvo7PsKrUfx6p97JoGfsWA7nOZ3jKHdE+WxdwyKbgCj7A629y3pyxBISrIVmcWwIR", + "eSiveQFP0WdRy6h25jbckFOUCo/DGFyUfLoGV+wo5MaGNPKH0hH3FT5HtaEDkFgsgYaCPJKuFzSCQ+P83UEIPM27VYVC+Ukh", + "Z65Li+1I79wTUIQCF3lIj4uigbWBf+wgwuQR6ze5pz0janqEHrnqQ1PuyME38cQz7k3dvTakRy7jWbcZoMJifDTAbkqb3BYF", + "Lmq6GyKzJZpufPfb3uhlPbsL2JIfIHCFYAwfCyiIRO7oef6m2v+8PN5fZDzbdv6ecSkOVvRQRu+6TJ91kaCyY0xQN+4T6qZ1", + "1c5b7joEDuF5sS4zzgpvreMT/kuJwaFiIPx7214nziN5tSmuImXNHLWO1RwbtqpB1IzgmPvm9788dR73ieg0hfmh77hO5AJm", + "qH7ELBVdGWpa1lGxiJ9HNI7UJ3cx23XWZqa+x+dahWoO1vG5Gd4Lj92Sv9SGUkIwS/vL3d5cZd+rr75aWUYSH9gjhEEh3PbC", + "t2OZTQVEURhhbVL6HEVgbxHW7/Fid3a2qCntmMZvDOQ2IFUvoH/jsUQBpeyloD4E3ECdsuIcjvWyXiqmBHz4ZC3owR8VqlE+", + "plI59HYx0zdcAtKSZuvYO4cnocR0Ab0lvuEJ43XTJQ6EiWfUGA9yKnnDRnUyG4/TdFZ82yz27uL9uOeQ8Y3jrs3ACw0iWpKo", + "wHanQFQl0bdx4AlbAjuZkkKv1QpLURrktSD1hrEVzPV718qiHeuBON5SwGihp+7Rr8YhqSwdKwnA7CowIyf74xtfypOQIFYH", + "r+Ac+cIyn8LAhey9gL8ux5aGDp8JwtU+ZBlOVuRLMkSzKJe4z9aZYETOTIS5GdDz5qCA2UvPAaIlmgjteQFVqS3MRKPebM1T", + "XIKQI7mKJAmqR+8q+fHLZtDwJuLgyuHmcLs5QkxyJwSYDVti2WYItdfIGDPOeH0bu+gFr58pRlaLI8aCVW65KheGiaPwBXNg", + "aE0HTl17GXD6GVuOtqcGQWHFgCuM6Aag7NkTfoBUHOz+F+b6QKw4VZ4sx+O+RDwMwgUBgY1RLU0m7B5uV9hU5dZB2ZBKmEmo", + "kyvEIP8n8ccsDkDOt3Nfnq07a3mqRrPjvCnM4+jmpDFj8zPturpYa9kMSCZF4eKUxZzUCVS7cSDQy/5CuMYP2tVnZ0F0oa9e", + "CLHn3MY8rVzwTjHERSFwCazAcYfhEgtNDXXkmeaycHa3rSUDeHIfkdzlUmvGvHMLmUXqkGzs9V3RIq12EAOySTfAGUlc0WZb", + "hQTBsly8zpFd9cgMZdIKQMwKr4fJ22Y/7PqL2B90iVMd7U6jfqougiSOBU0Hbr0hB6UpNORmF3s4TpUdc+1FKgZQ3yFyFs6U", + "QghsxbTBHBDAEbFZ3EFVPzX0XunYROnU8ZWc0A5WpAZwgGZJBRMmo8/GphrwRQPQdsPyGi45imYAGx5xI/SOObNy2DgX15xZ", + "jwZUeXT4hwKRIHXVQ44pmCaYzsB+bIC2YA+IIqBdXt5/6OX9kzzGzD/FkZGxMCIFK6RHUigxbDOs/hjUPYb4WoBZBkYaoZdx", + "nu29EvDITpmZNDwCRnu6PW/+yuIQTNFbVtizcB6S83mCglxUpbPvoFwjpKqV2cX2XI4bUm3gl84y3tjCcVQWL+EycYRe26e+", + "OEj6zkzN6rsioKy3NI0cw3VYrld46E3a0kjsAa13J4bHA9/yjXzuDi7qCXDOTFsx16vPI/7FIiC0wJGAl+z1HNrCK6yV4xIr", + "drx8/qlYTTg0ajmyPqqXv+CjqZWDnvpVrQovqoewMMrpEYhOXVCJHeKtsT43izPJxcS6mfDeitSXfa8v84Tnt6cQP18tNfDZ", + "GIggHeiPjSUWDccY5gRTrHKVqJO0QcyAZRs0Bpsw/x7AKsh8VuGnpybBeTF6H5/9WE290912c3jvyFjRYxy3pc7xVs3lHJzp", + "riVcbh9/SH8FFeoILiEMFGqOEucdvK9itpLJUI2DzA3OasPK0WnPYvOOejqIAkaJTVjmOCjhOHIPmu1THSIWtQw2ueP1ce+L", + "AyPAv2WJNuDkdS4+DuYXE+6jp3alXDdPros4vqIdHUmpYbbb/qWlm0SVwozgfphZMT7uSRqJbmw1RSyC7ZcFnYkgErep1epR", + "x3Fey9seBQXSCCXAPj0NOCKgQW4BO1JOnt0pyHdapqthu0F2ewjVVjYj6liwnX+U6KJalthAIgaHQAkIHIJnI/kyHw6BIxJl", + "gRy+UqlTob+y1M4BS4fZdJyGUp4M9iW4uV94SfOS9MNamFNsN+n9+IXgH5t1tFk1tUBAh3TnzchVjpcnl8g9MJuwL4jHZFko", + "xgchmf7i3OJ/NvJsmHLriyPCh7N75fH27ipmOzYxhxB89vgaZg1WkSOIciP3w9wFIczNOWcxC/BQ8inmepIFcTmEbeIMkuwD", + "cOvE5zJWPvzsGmVRzHUBwz6wGH3Kh2xZVp74ep/Q88ITO64dc39iB9rEz5APR/hNMOb3PSqvn+f42o8cKVxT2PEz9NmTW/CZ", + "v0Ydm34dbElO3pcxlKoWxi/dZTlWz+rIaEJak/FsCMeaGPvI7IBHFUSyKDqUp/ysYmoxUBhxZ5KsN1JQ7ghOt3D6VVNOinzp", + "eTiuKkSYwIzHFfmMcOEMOMjbjZPeKjcsnq1ybP+sCEPF0ylmR9F1H8r1virLUg556GijNx8t01SS4i1d9Cu07erI4OdLwPsJ", + "0/F9M5VLXLZVSPm4RFpT88lraPEKwhFyaEEfG7gUheqLpdIffAKPiXYPnqRWSLRIyjNdejq49nRw5+ngO/h5/+zTwZWng388", + "W/vm2dqnz9auPVu78mzt+rO1q8/Wvvjvrev/++fntuT8/qr5b0TyYpuSvKAsw9cYt/+QU2Cc6JGsDVdcXpR0m60qDTI4Nj1h", + "kwK2CnVDikAHnIWEsy67QlFXO2wri23x7BWVvgkSgh9LEfSO5LC+lMc7J/WkmyrJaKuGbb5yXQp+deJmNSrNvswVppwU0/ms", + "oEz7hhTzXuSidW6Tdayf3ZGvNiRBdlmO3JGU31fqdGqfM/jM+sMNqd71q+D5aTdVFvKGyhDZfqezrsuJt6VVzd2/9oRL7S44", + "RhMC/kC5EaosLRr28It3J6EHAWQr6jZSf4MGK9xfplb9Yi20gTRdEnH55fmOOtYZs4BeSqyn4qRRuxmzCiR8qJQ/XKmFIQ3a", + "1ZTTllvtON2k14bUWdcYfwnmM9iGcjWosu5qi1eqVN7dP1mpTE1PZe+9Mf3Wm9m+8t7M33RJRCbY8DBVlnlc5mnCrRvUSJiG", + "Knirp5ziIhm/NY3+O270VDvmB+dS+78saCze0eJdhoLeHIpjUAgg8q/A/Zoll6zxoV8kMlDV5JJZgETPaNYH5k549VFMvamq", + "L1WO5teRyzhLmv70BPCXM+sgpCJFpud77XqJusC8eW/RbJT+fa9KbR/Og8743jGqQ1fu0ftq449D+0AGzEjJgXr8hRdS8bR6", + "HxTkwyepJZf/5Fuk19VWshnGe8nbtcZTzor2xpvd7GDPOOmdEcW1OEDeRsLy3EFMEPjIPzn8jsc7eUeqMbH28i6xRypMU+IK", + "5lO4wiXihwSED9We+tYzO3rs4JuHJ7PiQr80HRAZQPfFMZVJ+B6iMQw70/lVssTGEC7kuu3T5mDa/Eu2c1+p711QubbT7/Ah", + "lYSHbGbjmK6AVEsLhor6b5tJVqa6lYMIf03aj4X6iTwes+ZKdjs7UkY8PA/e2IfFE3AMx2tNHHXEr1ORLrO7VauCduqr6dUi", + "jlrhQ6k1RFPuJTABOEvSljKOjmAj18vJzUqyWedbx9OvyQpR4WjR4wSHySvlvfuyaX/1twnH59yz+pzuKWbpFSzx8pj2HE+2", + "YX94KEuvC89pr2Iz7cTkgAzuJOAQ8fvT3Kim3RPIJye/wLlUjls6mss88wM3wi6Oz+nCwnOas5qy0/Bez2m2GqIzLykLxdaL", + "MJhSO8+7fod8HDCK0tahA/oSbeUOIhrtdQRrNhB31XrrlwXtdUXBygY+xu1jxQpD3v1NBVyyiLwdRfCzw9dMuPO0cbmMFFOE", + "29oUrNZXqX3Ghr8TuigkT48Q+TXwvXvGjv0foSWBhw==", + }, + 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(%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, "") + 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 ">") + 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, "") + 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 .extras.gltf = { extras, extensions }. +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Base64 = require("@formats/codecs/Base64") +local Pack = require("@formats/model/gltf/Pack") + +local Read = {} + +local COMPONENT: { [number]: { string } } = { + [5120] = { "i8", "snorm8" }, + [5121] = { "u8", "unorm8" }, + [5122] = { "i16", "snorm16" }, + [5123] = { "u16", "unorm16" }, + [5125] = { "u32", "" }, + [5126] = { "f32", "" }, +} +local SIZE = { [5120] = 1, [5121] = 1, [5122] = 2, [5123] = 2, [5125] = 4, [5126] = 4 } +local TYPE_COMPONENTS = { SCALAR = 1, VEC2 = 2, VEC3 = 3, VEC4 = 4, MAT2 = 4, MAT3 = 9, MAT4 = 16 } +local TYPE_COLUMNS = { MAT2 = 2, MAT3 = 3, MAT4 = 4 } +local MODES = { [0] = "points", [1] = "lines", [2] = "line_loop", [3] = "line_strip", [4] = "triangles", [5] = "triangle_strip", [6] = "triangle_fan" } +local WRAP = { [33071] = "clamp", [33648] = "mirror", [10497] = "repeat" } +local MIN_FILTER = { [9728] = "nearest", [9729] = "linear", [9984] = "nearest_mipmap_nearest", [9985] = "linear_mipmap_nearest", [9986] = "nearest_mipmap_linear", [9987] = "linear_mipmap_linear" } +-- the extensions this reader understands (everything else that is required -> UNSUPPORTED) +local KNOWN = { + KHR_lights_punctual = true, + KHR_mesh_quantization = true, + KHR_texture_transform = true, + KHR_materials_emissive_strength = true, + KHR_materials_unlit = true, + KHR_materials_clearcoat = true, + KHR_materials_transmission = true, + KHR_materials_volume = true, + KHR_materials_ior = true, + KHR_materials_specular = true, + KHR_materials_sheen = true, + KHR_materials_iridescence = true, + KHR_materials_anisotropy = true, + KHR_materials_dispersion = true, + KHR_materials_diffuse_transmission = true, + KHR_materials_variants = true, + KHR_materials_pbrSpecularGlossiness = true, + KHR_texture_basisu = true, -- the image stays encoded (image/ktx2) + EXT_texture_webp = true, + EXT_texture_avif = true, + KHR_node_visibility = true, + KHR_xmp_json_ld = true, +} +Read.KNOWN = KNOWN + +export type Fetch = (uri: string) -> buffer? +type View = { buf: buffer, offset: number, length: number, stride: number? } +type Img = { data: buffer?, mime: string?, uri: string?, name: string? } + +local function num(v: any, default: number): number + return if type(v) == "number" then v else default +end +local function int(v: any): number? + return if type(v) == "number" and v == math.floor(v) and v >= 0 then v else nil +end +local function arr(v: any): { any } + return if type(v) == "table" then v else {} +end +local function str(v: any): string? + return if type(v) == "string" then v else nil +end +local function numbers(v: any, n: number): { number }? + if type(v) ~= "table" or #v ~= n then + return nil + end + for i = 1, n do + if type(v[i]) ~= "number" then + return nil + end + end + return table.move(v, 1, n, 1, {}) +end + +-- extras.gltf: the JSON extras and the extensions not turned into Scene fields +local function keep(obj: any, handled: { [string]: boolean }?): { [string]: any }? + local extras = obj.extras + local ext: { [string]: any }? = nil + if type(obj.extensions) == "table" then + for k, v in obj.extensions do + if not (handled and handled[k]) then + ext = ext or {} + local e: any = ext + e[k] = v + end + end + end + if extras == nil and ext == nil then + return nil + end + return { gltf = { extras = extras, extensions = ext } } +end + +function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Scene?, Err.Err?) + local maxBytes = opts and opts.maxBytes or 2 ^ 30 + if type(doc) ~= "table" then + return nil, Err.new(Err.CORRUPT, "the JSON is not an object") + end + local asset = doc.asset + if type(asset) ~= "table" or type(asset.version) ~= "string" then + return nil, Err.new(Err.CORRUPT, "no asset.version") + end + if string.sub(asset.version, 1, 1) ~= "2" then + return nil, Err.new(Err.UNSUPPORTED, "glTF version " .. asset.version .. " (only 2.x)") + end + for _, e in arr(doc.extensionsRequired) do + if type(e) == "string" and not KNOWN[e] then + return nil, Err.new(Err.UNSUPPORTED, "required extension " .. e) + end + end + local scene = Types.Scene.new() + -- buffers + local buffers: { buffer } = {} + local total = 0 + for i, b in arr(doc.buffers) do + if type(b) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad buffer " .. (i - 1)) + end + local len = int(b.byteLength) + if not len then + return nil, Err.new(Err.CORRUPT, "buffer " .. (i - 1) .. " without byteLength") + end + total += len + if total > maxBytes then + return nil, Err.new(Err.LIMIT, "buffers over " .. maxBytes .. " bytes") + end + local data: buffer? = nil + local uri = str(b.uri) + if uri == nil then + if i == 1 and bin then + data = bin + else + return nil, Err.new(Err.CORRUPT, "buffer " .. (i - 1) .. " has no uri and no GLB BIN chunk") + end + elseif string.sub(uri, 1, 5) == "data:" then + local d, derr = Base64.decodeDataUri(uri) + if not d then + return nil, Err.new(Err.CORRUPT, "buffer " .. (i - 1) .. ": " .. tostring(derr)) + end + data = d + else + data = fetch(uri) + if not data then + return nil, Err.new(Err.IO, "buffer file " .. uri .. " not found (pass opts.resolve or opts.files)") + end + end + if buffer.len(data :: buffer) < len then + return nil, Err.new(Err.TRUNCATED, "buffer " .. (i - 1) .. " is shorter than its byteLength") + end + buffers[i] = data :: buffer + end + -- buffer views -> { buf, offset, length, stride } + local views: { View } = {} + for i, v in arr(doc.bufferViews) do + if type(v) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad bufferView " .. (i - 1)) + end + local bi, off, len = int(v.buffer), int(v.byteOffset or 0), int(v.byteLength) + local b = bi and buffers[bi + 1] + if not b or not off or not len or off + len > buffer.len(b) then + return nil, Err.new(Err.CORRUPT, "bufferView " .. (i - 1) .. " out of range") + end + local stride = v.byteStride + if stride ~= nil and (not int(stride) or stride < 4 or stride > 252) then + return nil, Err.new(Err.CORRUPT, "bufferView " .. (i - 1) .. ": bad byteStride") + end + views[i] = { buf = b, offset = off, length = len, stride = stride } + end + -- accessors + local accessors: { Types.Accessor } = {} + for i, a in arr(doc.accessors) do + local label = "accessor " .. (i - 1) + if type(a) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad " .. label) + end + local ct, count, typ = a.componentType, int(a.count), a.type + local names = COMPONENT[ct] + local comps = TYPE_COMPONENTS[typ] + if not names or not count or not comps then + return nil, Err.new(Err.CORRUPT, label .. ": bad componentType, count or type") + end + local normalized = a.normalized == true + local tname = if normalized then names[2] else names[1] + if tname == "" then + return nil, Err.new(Err.CORRUPT, label .. ": normalized " .. names[1]) + end + local size = SIZE[ct] + local cols = TYPE_COLUMNS[typ] or 1 + local rows = comps // cols + local colBytes = rows * size + local colStride = if cols > 1 then (colBytes + 3) // 4 * 4 else colBytes + local elem = comps * size + local padded = cols * colStride + if count * elem > maxBytes then + return nil, Err.new(Err.LIMIT, label .. " is over " .. maxBytes .. " bytes") + end + local data = buffer.create(count * elem) + local vi = a.bufferView + if vi ~= nil then + local view = int(vi) and views[vi + 1] + if not view then + return nil, Err.new(Err.CORRUPT, label .. ": bad bufferView") + end + local off = int(a.byteOffset or 0) + if not off then + return nil, Err.new(Err.CORRUPT, label .. ": bad byteOffset") + end + local stride = view.stride or padded + if stride < padded and count > 1 then + return nil, Err.new(Err.CORRUPT, label .. ": byteStride smaller than an element") + end + if count > 0 and off + (count - 1) * stride + padded > view.length then + return nil, Err.new(Err.CORRUPT, label .. " runs past its bufferView") + end + if count > 0 then + Pack.gather(data, view.buf, view.offset + off, count, elem, stride, cols, colBytes, colStride) + end + end + local sp = a.sparse + if type(sp) == "table" then + local n = int(sp.count) + local si, sv = sp.indices, sp.values + if not n or type(si) ~= "table" or type(sv) ~= "table" then + return nil, Err.new(Err.CORRUPT, label .. ": bad sparse") + end + local isz = SIZE[si.componentType] + local iv, vv = int(si.bufferView) and views[si.bufferView + 1], int(sv.bufferView) and views[sv.bufferView + 1] + local io, vo = int(si.byteOffset or 0), int(sv.byteOffset or 0) + local okType = si.componentType == 5121 or si.componentType == 5123 or si.componentType == 5125 + if not okType or not isz or not iv or not vv or not io or not vo then + return nil, Err.new(Err.CORRUPT, label .. ": bad sparse indices / values") + end + if io + n * isz > iv.length or vo + n * elem > vv.length then + return nil, Err.new(Err.CORRUPT, label .. ": sparse data runs past its bufferView") + end + -- sparse values are tightly packed (matrices: padded columns, rare enough to repack first) + local vals, valOff = vv.buf, vv.offset + vo + if cols > 1 and colBytes ~= colStride then + vals = buffer.create(n * elem) + Pack.gather(vals, vv.buf, vv.offset + vo, n, elem, padded, cols, colBytes, colStride) + valOff = 0 + end + if not Pack.sparse(data, count, elem, iv.buf, iv.offset + io, isz, vals, valOff, n) then + return nil, Err.new(Err.CORRUPT, label .. ": sparse index out of range") + end + end + local acc = Types.Scene.accessor(data, tname, comps, count) + if cols > 1 then + acc.matrix = true + end + acc.name = str(a.name) + accessors[i] = acc + end + local function accessor(v: any): Types.Accessor? + local k = int(v) + return if k then accessors[k + 1] else nil + end + -- images (kept encoded), samplers, textures + local images: { Img } = {} + for i, im in arr(doc.images) do + if type(im) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad image " .. (i - 1)) + end + local img: Img = { mime = str(im.mimeType), name = str(im.name) } + if im.bufferView ~= nil then + local view = int(im.bufferView) and views[im.bufferView + 1] + if not view then + return nil, Err.new(Err.CORRUPT, "image " .. (i - 1) .. ": bad bufferView") + end + local d = buffer.create(view.length) + buffer.copy(d, 0, view.buf, view.offset, view.length) + img.data = d + elseif type(im.uri) == "string" then + if string.sub(im.uri, 1, 5) == "data:" then + local d, mime = Base64.decodeDataUri(im.uri) + if d then + img.data = d + img.mime = img.mime or mime + end + else + img.uri = im.uri + img.data = fetch(im.uri) + if not img.mime then + local ext = string.lower(string.match(im.uri, "%.(%w+)$") or "") + img.mime = if ext == "png" then "image/png" elseif ext == "jpg" or ext == "jpeg" then "image/jpeg" elseif ext == "webp" then "image/webp" elseif ext == "ktx2" then "image/ktx2" else nil + end + end + end + images[i] = img + end + local samplers: { Types.Sampler } = {} + for i, s in arr(doc.samplers) do + if type(s) == "table" then + samplers[i] = { + wrapS = WRAP[s.wrapS] or (if s.wrapS == nil then nil else "repeat") :: any, + wrapT = WRAP[s.wrapT] or (if s.wrapT == nil then nil else "repeat") :: any, + filter = if s.magFilter == 9728 then "nearest" elseif s.magFilter == 9729 then "linear" else nil, + minFilter = MIN_FILTER[s.minFilter], + } + else + samplers[i] = {} + end + end + local TEX_SOURCE_EXT = { "KHR_texture_basisu", "EXT_texture_webp", "EXT_texture_avif" } + for i, t in arr(doc.textures) do + if type(t) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad texture " .. (i - 1)) + end + local src = t.source + local handled = {} + if type(t.extensions) == "table" then + for _, e in TEX_SOURCE_EXT do + local x = t.extensions[e] + if type(x) == "table" and int(x.source) then + src = x.source + handled[e] = true + break + end + end + end + local img = int(src) and images[src + 1] + local tex: Types.Texture = { name = str(t.name) } + if img then + tex.data, tex.mime, tex.uri = img.data, img.mime, img.uri + tex.name = tex.name or img.name + end + local si = int(t.sampler) + if si and samplers[si + 1] then + tex.sampler = table.clone(samplers[si + 1]) + end + tex.extras = keep(t, handled) + if next(handled) then + -- the fallback image (t.source) and the extension name, for writing the texture back the same way + tex.extras = tex.extras or { gltf = {} } + local g = (tex.extras :: any).gltf + g.sourceExtension = next(handled) + local fb = int(t.source) and images[t.source + 1] + if fb then + g.fallback = { data = fb.data, mime = fb.mime, uri = fb.uri } + end + end + table.insert(scene.textures, tex) + end + -- materials + local function texRef(info: any): Types.TextureRef? + if type(info) ~= "table" or not int(info.index) or info.index >= #scene.textures then + return nil + end + local r: Types.TextureRef = { texture = info.index + 1, texCoord = int(info.texCoord), scale = if type(info.scale) == "number" then info.scale else nil, strength = if type(info.strength) == "number" then info.strength else nil } + local tt = type(info.extensions) == "table" and info.extensions.KHR_texture_transform + if type(tt) == "table" then + r.transform = { offset = numbers(tt.offset, 2), scale = numbers(tt.scale, 2), rotation = if type(tt.rotation) == "number" then tt.rotation else nil, texCoord = int(tt.texCoord) } + end + return r + end + -- an extension object with every textureInfo (a table with an index, under a key ending in Texture) -> TextureRef + local function convertExt(v: any): any + if type(v) ~= "table" then + return v + end + local out = if Types.isObject(v) or next(v) == nil then Types.object() else {} + for k, x in v do + if type(k) == "string" and string.sub(k, -7) == "Texture" and type(x) == "table" and int(x.index) then + out[k] = texRef(x) + else + out[k] = convertExt(x) + end + end + return out + end + for i, m in arr(doc.materials) do + if type(m) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad material " .. (i - 1)) + end + local mat = Types.Scene.material(str(m.name)) + local pbr = if type(m.pbrMetallicRoughness) == "table" then m.pbrMetallicRoughness else {} + mat.baseColor = numbers(pbr.baseColorFactor, 4) or { 1, 1, 1, 1 } + mat.baseColorTexture = texRef(pbr.baseColorTexture) + mat.metallic = num(pbr.metallicFactor, 1) + mat.roughness = num(pbr.roughnessFactor, 1) + mat.metallicRoughnessTexture = texRef(pbr.metallicRoughnessTexture) + mat.normalTexture = texRef(m.normalTexture) + mat.occlusionTexture = texRef(m.occlusionTexture) + mat.emissive = numbers(m.emissiveFactor, 3) or { 0, 0, 0 } + mat.emissiveTexture = texRef(m.emissiveTexture) + mat.alphaMode = if m.alphaMode == "MASK" then "mask" elseif m.alphaMode == "BLEND" then "blend" else "opaque" + mat.alphaCutoff = num(m.alphaCutoff, 0.5) + mat.doubleSided = m.doubleSided == true + if type(m.extensions) == "table" then + local ext = {} + for k, v in m.extensions do + ext[k] = convertExt(v) + end + mat.extensions = ext + end + local kept = keep(m, mat.extensions and (mat.extensions :: any) or {}) + local pk = keep(pbr, nil) + if pk then + kept = kept or { gltf = {} } + local kk: any = kept + kk.gltf.pbr = pk.gltf + end + mat.extras = kept + table.insert(scene.materials, mat) + end + -- meshes + for i, m in arr(doc.meshes) do + if type(m) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad mesh " .. (i - 1)) + end + local mesh: Types.Mesh = { name = str(m.name), primitives = {}, weights = if type(m.weights) == "table" then table.clone(m.weights) else nil, extras = keep(m, nil) } + for k, p in arr(m.primitives) do + if type(p) ~= "table" or type(p.attributes) ~= "table" then + return nil, Err.new(Err.CORRUPT, string.format("mesh %d primitive %d: no attributes", i - 1, k - 1)) + end + if type(p.extensions) == "table" and (p.extensions.KHR_draco_mesh_compression or p.extensions.EXT_meshopt_compression) then + return nil, Err.new(Err.UNSUPPORTED, "compressed primitives (Draco / meshopt)") + end + local attrs: { [string]: Types.Accessor } = {} + local count = -1 + for name, ai in p.attributes do + local a = accessor(ai) + if not a then + return nil, Err.new(Err.CORRUPT, string.format("mesh %d: attribute %s: bad accessor", i - 1, tostring(name))) + end + if count >= 0 and a.count ~= count then + return nil, Err.new(Err.CORRUPT, string.format("mesh %d: attributes with different counts", i - 1)) + end + count = a.count + attrs[name] = a + end + local mode = MODES[if p.mode == nil then 4 else p.mode] + if not mode then + return nil, Err.new(Err.CORRUPT, "bad primitive mode") + end + local prim: Types.Primitive = { attributes = attrs, mode = mode :: any, material = if int(p.material) and p.material < #scene.materials then p.material + 1 else nil } + if p.indices ~= nil then + local ind = accessor(p.indices) + if not ind or ind.components ~= 1 or (ind.type ~= "u8" and ind.type ~= "u16" and ind.type ~= "u32") then + return nil, Err.new(Err.CORRUPT, "bad indices accessor") + end + -- indices must reference existing vertices + local get = Types.Scene.reader(ind) :: any + for q = 0, ind.count - 1 do + if get(q, 0) >= count then + return nil, Err.new(Err.CORRUPT, "index out of range") + end + end + prim.indices = ind + end + if type(p.targets) == "table" then + local targets = {} + for ti, t in p.targets do + local tt = {} + for name, ai in (if type(t) == "table" then t else {}) do + local a = accessor(ai) + if not a or a.count ~= count then + return nil, Err.new(Err.CORRUPT, "bad morph target accessor") + end + tt[name] = a + end + targets[ti] = tt + end + prim.targets = targets + end + prim.extras = keep(p, nil) + table.insert(mesh.primitives, prim) + end + table.insert(scene.meshes, mesh) + end + -- cameras, lights + for _, c in arr(doc.cameras) do + if type(c) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad camera") + end + if c.type == "orthographic" and type(c.orthographic) == "table" then + local o = c.orthographic + table.insert(scene.cameras, { name = str(c.name), type = "orthographic", xmag = num(o.xmag, 1), ymag = num(o.ymag, 1), znear = num(o.znear, 0), zfar = num(o.zfar, 100) }) + else + local p = if type(c.perspective) == "table" then c.perspective else {} + table.insert(scene.cameras, { name = str(c.name), type = "perspective", yfov = num(p.yfov, 0.8), aspect = if type(p.aspectRatio) == "number" then p.aspectRatio else nil, znear = num(p.znear, 0.01), zfar = if type(p.zfar) == "number" then p.zfar else nil }) + end + end + local lp = type(doc.extensions) == "table" and doc.extensions.KHR_lights_punctual + for _, l in arr(lp and lp.lights) do + if type(l) == "table" then + local spot = if type(l.spot) == "table" then l.spot else {} + table.insert(scene.lights, { + name = str(l.name), + type = if l.type == "spot" or l.type == "point" then l.type else "directional", + color = numbers(l.color, 3) or { 1, 1, 1 }, + intensity = num(l.intensity, 1), + range = if type(l.range) == "number" then l.range else nil, + innerCone = if l.type == "spot" then num(spot.innerConeAngle, 0) else nil, + outerCone = if l.type == "spot" then num(spot.outerConeAngle, math.pi / 4) else nil, + }) + end + end + -- nodes + local nodes = arr(doc.nodes) + for i, n in nodes do + if type(n) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad node " .. (i - 1)) + end + local node: Types.Node = { name = str(n.name), children = {} } + for _, c in arr(n.children) do + if not int(c) or c >= #nodes then + return nil, Err.new(Err.CORRUPT, "node " .. (i - 1) .. ": bad child") + end + table.insert(node.children, c + 1) + end + if int(n.mesh) and n.mesh < #scene.meshes then + node.mesh = n.mesh + 1 + end + if int(n.camera) and n.camera < #scene.cameras then + node.camera = n.camera + 1 + end + if int(n.skin) and n.skin < #arr(doc.skins) then + node.skin = n.skin + 1 + end + node.matrix = numbers(n.matrix, 16) + node.translation = numbers(n.translation, 3) + node.rotation = numbers(n.rotation, 4) + node.scale = numbers(n.scale, 3) + node.weights = if type(n.weights) == "table" then table.clone(n.weights) else nil + local handled = {} + local le = type(n.extensions) == "table" and n.extensions.KHR_lights_punctual + if type(le) == "table" and int(le.light) and le.light < #scene.lights then + node.light = le.light + 1 + handled.KHR_lights_punctual = true + end + node.extras = keep(n, handled) + scene.nodes[i] = node + end + -- a node may have one parent only, and no cycles + local parent: { [number]: number } = {} + for i, node in scene.nodes do + for _, c in node.children do + if parent[c] or c == i then + return nil, Err.new(Err.CORRUPT, "node " .. (c - 1) .. " has two parents or is its own child") + end + parent[c] = i + end + end + for i in scene.nodes do + local seen, p = 0, parent[i] + while p do + seen += 1 + if seen > #scene.nodes then + return nil, Err.new(Err.CORRUPT, "the node hierarchy has a cycle") + end + p = parent[p] + end + end + -- skins + for _, s in arr(doc.skins) do + if type(s) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad skin") + end + local joints = {} + for _, j in arr(s.joints) do + if not int(j) or j >= #scene.nodes then + return nil, Err.new(Err.CORRUPT, "skin: bad joint") + end + table.insert(joints, j + 1) + end + table.insert(scene.skins, { name = str(s.name), joints = joints, inverseBindMatrices = accessor(s.inverseBindMatrices), skeleton = if int(s.skeleton) and s.skeleton < #scene.nodes then s.skeleton + 1 else nil }) + end + -- animations + for _, a in arr(doc.animations) do + if type(a) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad animation") + end + local anim: Types.Animation = { name = str(a.name), channels = {} } + local samplersA = arr(a.samplers) + local skipped = {} + for _, c in arr(a.channels) do + local s = type(c) == "table" and int(c.sampler) and samplersA[c.sampler + 1] + local target = type(c) == "table" and c.target + if not s or type(target) ~= "table" then + return nil, Err.new(Err.CORRUPT, "animation: bad channel") + end + local input, output = accessor(s.input), accessor(s.output) + if not input or not output then + return nil, Err.new(Err.CORRUPT, "animation: bad sampler accessors") + end + local path = target.path + if int(target.node) and target.node < #scene.nodes and (path == "translation" or path == "rotation" or path == "scale" or path == "weights") then + table.insert(anim.channels, { + node = target.node + 1, + path = path, + input = input, + output = output, + interpolation = if s.interpolation == "STEP" or s.interpolation == "CUBICSPLINE" then s.interpolation else "LINEAR", + }) + else + table.insert(skipped, c) -- KHR_animation_pointer and friends + end + end + if #skipped > 0 then + local aa: any = anim + aa.extras = { gltf = { skippedChannels = #skipped } } + end + table.insert(scene.animations, anim) + end + -- scenes + local scenes = arr(doc.scenes) + local list = {} + for _, s in scenes do + local roots = {} + for _, n in arr(type(s) == "table" and s.nodes) do + if int(n) and n < #scene.nodes and not parent[n + 1] then + table.insert(roots, n + 1) + end + end + table.insert(list, { name = type(s) == "table" and str(s.name) or nil, nodes = roots, extras = if type(s) == "table" then keep(s, nil) else nil }) + end + local which = int(doc.scene) or 0 + if list[which + 1] then + scene.roots = list[which + 1].nodes + elseif #list == 0 then + for i in scene.nodes do + if not parent[i] then + table.insert(scene.roots, i) + end + end + end + -- root extensions other than the lights, asset info + local rootExt = nil + if type(doc.extensions) == "table" then + for k, v in doc.extensions do + if k ~= "KHR_lights_punctual" then + rootExt = rootExt or {} + rootExt[k] = v + end + end + end + scene.meta.up = "y" + scene.meta.unit = 1 + scene.meta.gltf = { + asset = asset, + scenes = list, + scene = if doc.scene ~= nil then which + 1 else nil, + extensionsUsed = doc.extensionsUsed, + extensionsRequired = doc.extensionsRequired, + extensions = rootExt, + extras = doc.extras, + } + return scene, nil +end + +return Read diff --git a/src/Formats/model/gltf/Write.luau b/src/Formats/model/gltf/Write.luau new file mode 100644 index 0000000..473f293 --- /dev/null +++ b/src/Formats/model/gltf/Write.luau @@ -0,0 +1,696 @@ +--!strict +-- model/gltf/Write: Scene -> a glTF 2.0 JSON document + one binary buffer. One bufferView per accessor (vertex +-- attributes 4-byte aligned per element with a byteStride when needed, matrix columns padded as glTF requires), +-- accessors shared between primitives / animations written once, f64 / i32 data converted (glTF has neither), +-- POSITION and animation input min / max, KHR_mesh_quantization declared when attributes are not floats, +-- KHR_texture_transform / KHR_lights_punctual / material extensions declared when used, images deduplicated by their +-- bytes (or uri), samplers by their settings. "polygons" primitives are fan-triangulated (MeshOps.triangulate first +-- for concave faces). +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Pack = require("@formats/model/gltf/Pack") + +local Write = {} + +local object = Types.object +local CT = { i8 = 5120, u8 = 5121, i16 = 5122, u16 = 5123, u32 = 5125, f32 = 5126, unorm8 = 5121, unorm16 = 5123, snorm8 = 5120, snorm16 = 5122 } +local SIZE = Types.COMPONENT_SIZE +local NORMALIZED = { unorm8 = true, unorm16 = true, snorm8 = true, snorm16 = true } +local MODES = { points = 0, lines = 1, line_loop = 2, line_strip = 3, triangles = 4, triangle_strip = 5, triangle_fan = 6 } +local WRAP = { clamp = 33071, mirror = 33648, ["repeat"] = 10497 } +local MIN_FILTER = { nearest = 9728, linear = 9729, nearest_mipmap_nearest = 9984, linear_mipmap_nearest = 9985, nearest_mipmap_linear = 9986, linear_mipmap_linear = 9987 } +-- attribute types the core spec allows (others need KHR_mesh_quantization) +local CORE = { + POSITION = { f32 = true }, + NORMAL = { f32 = true }, + TANGENT = { f32 = true }, + TEXCOORD = { f32 = true, unorm8 = true, unorm16 = true }, + COLOR = { f32 = true, unorm8 = true, unorm16 = true }, + JOINTS = { u8 = true, u16 = true }, + WEIGHTS = { f32 = true, unorm8 = true, unorm16 = true }, +} + +export type Options = { embedImages: boolean?, binary: boolean? } +export type Out = { doc: any, bin: buffer, images: { { data: buffer, mime: string?, name: string } } } + +local function convert(acc: Types.Accessor, to: string): Types.Accessor + local get = Types.Scene.reader(acc) :: (number, number) -> number + local out = Types.Scene.accessor(nil, to, acc.components, acc.count) + local w = if to == "f32" then buffer.writef32 else buffer.writeu32 + local size = SIZE[to] + for i = 0, acc.count - 1 do + for c = 0, acc.components - 1 do + local v = get(i, c) + if to == "u32" then + v = math.clamp(math.floor(v), 0, 4294967295) + end + w(out.data, (i * acc.components + c) * size, v) + end + end + out.matrix = acc.matrix + out.name = acc.name + return out +end + +local function checkAcc(acc: any, label: string): Err.Err? + if type(acc) ~= "table" or type(acc.data) ~= "buffer" or not SIZE[acc.type] or type(acc.count) ~= "number" or type(acc.components) ~= "number" then + return Err.new(Err.ARG, label .. ": not an accessor") + end + if acc.components < 1 or acc.components > 16 or buffer.len(acc.data) < acc.count * acc.components * SIZE[acc.type] then + return Err.new(Err.ARG, label .. ": data is smaller than count x components") + end + return nil +end + +function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) + local binary = opts and opts.binary or false + local embedImages = not (opts and opts.embedImages == false) + local doc: { [string]: any } = object() + local used: { [string]: boolean } = {} + local required: { [string]: boolean } = {} + local bin = Bytes.writer(65536) + local views: { any } = {} + local accessors: { any } = {} + local accIndex: { [any]: number } = {} + local failure: Err.Err? = nil + + local function view(data: buffer, length: number, target: number?, stride: number?): number + local pad = (4 - bin:tell() % 4) % 4 + bin:fill(0, pad) + local v = object() + v.buffer = 0 + v.byteOffset = bin:tell() + v.byteLength = length + v.target = target + v.byteStride = stride + bin:bytes(data, 0, length) + table.insert(views, v) + return #views - 1 + end + + -- accessor(acc, usage, attribute?) -> the glTF index (0-based) + local function accessor(acc: Types.Accessor, usage: string, attribute: string?): number + local known = accIndex[acc] + if known then + return known + end + local err = checkAcc(acc, attribute or usage) + if err then + failure = failure or err + return 0 + end + local a = acc + if usage == "index" then + if a.type ~= "u8" and a.type ~= "u16" and a.type ~= "u32" then + a = convert(a, "u32") + end + elseif a.type == "f64" or a.type == "i32" or a.type == "u32" and usage ~= "index" and attribute ~= nil then + a = convert(a, "f32") + end + if attribute then + local kind = string.match(attribute, "^([A-Z]+)_%d+$") or attribute + local core = CORE[kind] + if core and not core[a.type] then + used.KHR_mesh_quantization = true + required.KHR_mesh_quantization = true + end + end + local size = SIZE[a.type] + local comps = a.components + local isMat = a.matrix == true and (comps == 4 or comps == 9 or comps == 16) + local cols = if isMat then math.sqrt(comps) else 1 + local colBytes = (comps // cols) * size + local colStride = if cols > 1 then (colBytes + 3) // 4 * 4 else colBytes + local elem = comps * size + local padded = cols * colStride + local stride = padded + local byteStride: number? = nil + if usage == "vertex" and padded % 4 ~= 0 then + stride = (padded + 3) // 4 * 4 + byteStride = stride + end + local data = a.data + local length = a.count * stride + if stride ~= elem then + data = buffer.create(length) + Pack.scatter(data, 0, a.data, a.count, elem, stride, cols, colBytes, colStride) + end + local g = object() + g.bufferView = view(data, length, if usage == "vertex" then 34962 elseif usage == "index" then 34963 else nil, byteStride) + g.componentType = CT[a.type] + g.normalized = if NORMALIZED[a.type] then true else nil + g.count = a.count + g.type = if isMat then ({ [4] = "MAT2", [9] = "MAT3", [16] = "MAT4" })[comps] else ({ "SCALAR", "VEC2", "VEC3", "VEC4" })[comps] + g.name = acc.name + if not g.type then + failure = failure or Err.new(Err.ARG, (attribute or usage) .. ": " .. comps .. " components is not a glTF type") + return 0 + end + if attribute == "POSITION" or usage == "input" then + -- min / max of the raw component values + local raw = Types.Scene.accessor(a.data, if a.type == "unorm8" then "u8" elseif a.type == "unorm16" then "u16" elseif a.type == "snorm8" then "i8" elseif a.type == "snorm16" then "i16" else a.type, comps, a.count) + local get = Types.Scene.reader(raw) :: (number, number) -> number + local lo, hi = table.create(comps, math.huge), table.create(comps, -math.huge) + for i = 0, a.count - 1 do + for c = 1, comps do + local v = get(i, c - 1) + if v < lo[c] then + lo[c] = v + end + if v > hi[c] then + hi[c] = v + end + end + end + if a.count > 0 then + g.min, g.max = lo, hi + end + end + table.insert(accessors, g) + local index = #accessors - 1 + accIndex[acc] = index + return index + end + + -- extras.gltf -> extras / extensions fields of a glTF object + local function restore(g: any, extras: any) + local saved = type(extras) == "table" and extras.gltf + if type(saved) ~= "table" then + return + end + if saved.extras ~= nil then + g.extras = saved.extras + end + if type(saved.extensions) == "table" then + g.extensions = g.extensions or object() + for k, v in saved.extensions do + if g.extensions[k] == nil then + g.extensions[k] = v + used[k] = true + end + end + end + end + + -- images, samplers, textures + local images: { any } = {} + local imageOut: { { data: buffer, mime: string?, name: string } } = {} + local imageIndex: { [any]: number } = {} + local function image(data: buffer?, mime: string?, uri: string?, name: string?): number? + local key: any = data or uri + if key == nil then + return nil + end + if imageIndex[key] then + return imageIndex[key] + end + local im = object() + im.name = name + if data then + if binary then + im.bufferView = view(data, buffer.len(data), nil, nil) + im.mimeType = mime or "image/png" + elseif embedImages then + im.uri = "\0image" .. (#images + 1) -- replaced by a data: URI by the caller (init) / a file name + im.mimeType = mime + table.insert(imageOut, { data = data, mime = mime, name = im.uri }) + else + im.uri = uri or ("\0file" .. (#images + 1)) + im.mimeType = mime + table.insert(imageOut, { data = data, mime = mime, name = im.uri }) + end + else + im.uri = uri + im.mimeType = mime + end + table.insert(images, im) + imageIndex[key] = #images - 1 + return #images - 1 + end + local samplers: { any } = {} + local samplerIndex: { [string]: number } = {} + local function sampler(s: Types.Sampler?): number? + if type(s) ~= "table" then + return nil + end + local g = object() + g.wrapS = if s.wrapS then WRAP[s.wrapS] else nil + g.wrapT = if s.wrapT then WRAP[s.wrapT] else nil + g.magFilter = if s.filter == "nearest" then 9728 elseif s.filter == "linear" then 9729 else nil + g.minFilter = if s.minFilter then MIN_FILTER[s.minFilter] else nil + local key = string.format("%s/%s/%s/%s", tostring(g.wrapS), tostring(g.wrapT), tostring(g.magFilter), tostring(g.minFilter)) + if samplerIndex[key] == nil then + table.insert(samplers, g) + samplerIndex[key] = #samplers - 1 + end + return samplerIndex[key] + end + local textures: { any } = {} + for i, t in scene.textures or {} do + if type(t) ~= "table" then + return nil, Err.new(Err.ARG, "texture " .. i .. ": not a table") + end + local g = object() + g.name = t.name + g.sampler = sampler(t.sampler) + local saved = type(t.extras) == "table" and type(t.extras.gltf) == "table" and t.extras.gltf or nil + local srcExt = saved and saved.sourceExtension + local img = image(t.data, t.mime, t.uri, t.name) + if srcExt and img then + g.extensions = object() + local e = object() + e.source = img + g.extensions[srcExt] = e + used[srcExt] = true + local fb = saved.fallback + if type(fb) == "table" then + g.source = image(fb.data, fb.mime, fb.uri, nil) + end + if g.source == nil then + required[srcExt] = true + end + else + g.source = img + end + restore(g, t.extras) + table.insert(textures, g) + end + local function texInfo(r: any, kind: string?): any + if type(r) ~= "table" or type(r.texture) ~= "number" or not textures[r.texture] then + return nil + end + local g = object() + g.index = r.texture - 1 + if r.texCoord and r.texCoord ~= 0 then + g.texCoord = r.texCoord + end + if kind == "normal" and r.scale ~= nil and r.scale ~= 1 then + g.scale = r.scale + end + if kind == "occlusion" and r.strength ~= nil and r.strength ~= 1 then + g.strength = r.strength + end + if type(r.transform) == "table" then + local tt = object() + tt.offset = r.transform.offset + tt.scale = r.transform.scale + tt.rotation = r.transform.rotation + tt.texCoord = r.transform.texCoord + g.extensions = object() + g.extensions.KHR_texture_transform = tt + used.KHR_texture_transform = true + end + return g + end + local function extValue(v: any, key: string?): any + if type(v) ~= "table" then + return v + end + if key and string.sub(key, -7) == "Texture" and type(v.texture) == "number" then + return texInfo(v, if key == "normalTexture" or key == "clearcoatNormalTexture" then "normal" else nil) + end + local out = if Types.isObject(v) or next(v) == nil then object() else {} + for k, x in v do + out[k] = extValue(x, if type(k) == "string" then k else nil) + end + return out + end + -- materials + local materials: { any } = {} + for i, m in scene.materials or {} do + if type(m) ~= "table" then + return nil, Err.new(Err.ARG, "material " .. i .. ": not a table") + end + local g = object() + g.name = m.name + local pbr = object() + local bc = m.baseColor or { 1, 1, 1, 1 } + if bc[1] ~= 1 or bc[2] ~= 1 or bc[3] ~= 1 or (bc[4] or 1) ~= 1 then + pbr.baseColorFactor = { bc[1], bc[2], bc[3], bc[4] or 1 } + end + pbr.baseColorTexture = texInfo(m.baseColorTexture) + if m.metallic ~= nil and m.metallic ~= 1 then + pbr.metallicFactor = m.metallic + end + if m.roughness ~= nil and m.roughness ~= 1 then + pbr.roughnessFactor = m.roughness + end + pbr.metallicRoughnessTexture = texInfo(m.metallicRoughnessTexture) + local saved = type(m.extras) == "table" and type(m.extras.gltf) == "table" and m.extras.gltf or nil + if saved and saved.pbr then + restore(pbr, { gltf = saved.pbr }) + end + g.pbrMetallicRoughness = pbr + g.normalTexture = texInfo(m.normalTexture, "normal") + g.occlusionTexture = texInfo(m.occlusionTexture, "occlusion") + g.emissiveTexture = texInfo(m.emissiveTexture) + local em = m.emissive or { 0, 0, 0 } + if em[1] ~= 0 or em[2] ~= 0 or em[3] ~= 0 then + g.emissiveFactor = { em[1], em[2], em[3] } + end + if m.alphaMode == "mask" then + g.alphaMode = "MASK" + if m.alphaCutoff ~= nil and m.alphaCutoff ~= 0.5 then + g.alphaCutoff = m.alphaCutoff + end + elseif m.alphaMode == "blend" then + g.alphaMode = "BLEND" + end + if m.doubleSided then + g.doubleSided = true + end + if type(m.extensions) == "table" then + g.extensions = object() + for k, v in m.extensions do + g.extensions[k] = extValue(v, nil) + used[k] = true + end + end + restore(g, m.extras) + table.insert(materials, g) + end + -- meshes + local meshes: { any } = {} + for i, mesh in scene.meshes or {} do + if type(mesh) ~= "table" or type(mesh.primitives) ~= "table" then + return nil, Err.new(Err.ARG, "mesh " .. i .. ": no primitives") + end + local g = object() + g.name = mesh.name + g.primitives = {} + for k, p in mesh.primitives do + if type(p) ~= "table" or type(p.attributes) ~= "table" or not p.attributes.POSITION then + return nil, Err.new(Err.ARG, string.format("mesh %d primitive %d: no POSITION", i, k)) + end + local gp = object() + gp.attributes = object() + local names = {} + for name in p.attributes do + table.insert(names, name) + end + table.sort(names) + for _, name in names do + gp.attributes[name] = accessor(p.attributes[name], "vertex", name) + end + local mode = p.mode or "triangles" + local indices = p.indices + if mode == "polygons" then + -- fan-triangulate + local faces = p.faces + local getf = faces and Types.Scene.reader(faces) + local n = if indices then indices.count else p.attributes.POSITION.count + local geti = if indices then Types.Scene.reader(indices) else nil + if not faces or not getf or (indices and not geti) then + return nil, Err.new(Err.ARG, "polygons without faces") + end + local list = {} + local at = 0 + for f = 0, faces.count - 1 do + local c = getf(f, 0) + if at + c > n then + return nil, Err.new(Err.ARG, "faces run past the indices") + end + for a = 1, c - 2 do + for _, j in { at, at + a, at + a + 1 } do + table.insert(list, if geti then geti(j, 0) else j) + end + end + at += c + end + local ib = buffer.create(#list * 4) + for q, v in list do + buffer.writeu32(ib, (q - 1) * 4, v) + end + indices = Types.Scene.accessor(ib, "u32", 1, #list) + mode = "triangles" + end + if MODES[mode] == nil then + return nil, Err.new(Err.ARG, "unknown primitive mode " .. tostring(mode)) + end + if indices then + gp.indices = accessor(indices, "index", nil) + end + if mode ~= "triangles" then + gp.mode = MODES[mode] + end + if type(p.material) == "number" and materials[p.material] then + gp.material = p.material - 1 + end + if type(p.targets) == "table" and #p.targets > 0 then + gp.targets = {} + for _, t in p.targets do + local gt = object() + local tn = {} + for name in t do + table.insert(tn, name) + end + table.sort(tn) + for _, name in tn do + gt[name] = accessor(t[name], "vertex", nil) + end + table.insert(gp.targets, gt) + end + end + restore(gp, p.extras) + table.insert(g.primitives, gp) + end + g.weights = mesh.weights + restore(g, mesh.extras) + table.insert(meshes, g) + end + -- cameras, lights + local cameras: { any } = {} + for _, c in scene.cameras or {} do + local g = object() + g.name = c.name + g.type = c.type + local p = object() + if c.type == "orthographic" then + p.xmag, p.ymag, p.znear, p.zfar = c.xmag or 1, c.ymag or 1, c.znear or 0, c.zfar or 100 + g.orthographic = p + else + g.type = "perspective" + p.yfov, p.aspectRatio, p.znear, p.zfar = c.yfov or 0.8, c.aspect, c.znear or 0.01, c.zfar + g.perspective = p + end + table.insert(cameras, g) + end + local lights: { any } = {} + for _, l in scene.lights or {} do + local g = object() + g.name = l.name + g.type = l.type + if l.color and (l.color[1] ~= 1 or l.color[2] ~= 1 or l.color[3] ~= 1) then + g.color = { l.color[1], l.color[2], l.color[3] } + end + if l.intensity ~= nil and l.intensity ~= 1 then + g.intensity = l.intensity + end + if l.type ~= "directional" then + g.range = l.range + end + if l.type == "spot" then + local s = object() + s.innerConeAngle = if l.innerCone and l.innerCone ~= 0 then l.innerCone else nil + s.outerConeAngle = if l.outerCone and math.abs(l.outerCone - math.pi / 4) > 1e-12 then l.outerCone else nil + g.spot = s + end + table.insert(lights, g) + end + -- nodes + local nodes: { any } = {} + local nodeCount = #(scene.nodes or {}) + for i, n in scene.nodes or {} do + if type(n) ~= "table" then + return nil, Err.new(Err.ARG, "node " .. i .. ": not a table") + end + local g = object() + g.name = n.name + if n.children and #n.children > 0 then + g.children = {} + for _, c in n.children do + if type(c) ~= "number" or c < 1 or c > nodeCount then + return nil, Err.new(Err.ARG, "node " .. i .. ": bad child") + end + table.insert(g.children, c - 1) + end + end + if n.mesh and meshes[n.mesh] then + g.mesh = n.mesh - 1 + end + if n.camera and cameras[n.camera] then + g.camera = n.camera - 1 + end + if n.skin and scene.skins[n.skin] then + g.skin = n.skin - 1 + end + if n.matrix then + local ident = true + for k = 1, 16 do + if n.matrix[k] ~= Types.Scene.IDENTITY[k] then + ident = false + end + end + if not ident then + g.matrix = n.matrix + end + else + g.translation, g.rotation, g.scale = n.translation, n.rotation, n.scale + end + g.weights = n.weights + if n.light and lights[n.light] then + g.extensions = object() + local le = object() + le.light = n.light - 1 + g.extensions.KHR_lights_punctual = le + used.KHR_lights_punctual = true + end + restore(g, n.extras) + table.insert(nodes, g) + end + -- skins + local skins: { any } = {} + for _, s in scene.skins or {} do + local g = object() + g.name = s.name + g.joints = {} + for _, j in s.joints or {} do + table.insert(g.joints, j - 1) + end + if s.inverseBindMatrices then + local ibm = s.inverseBindMatrices + if ibm.matrix == nil and ibm.components == 16 then + ibm.matrix = true + end + g.inverseBindMatrices = accessor(ibm, "other", nil) + end + if s.skeleton then + g.skeleton = s.skeleton - 1 + end + table.insert(skins, g) + end + -- animations + local animations: { any } = {} + for _, a in scene.animations or {} do + local g = object() + g.name = a.name + g.channels, g.samplers = {}, {} + local samplerOf: { [string]: number } = {} + for _, c in a.channels or {} do + local input = accessor(c.input, "input", nil) + local output = accessor(c.output, "other", nil) + local key = input .. "/" .. output .. "/" .. tostring(c.interpolation) + if samplerOf[key] == nil then + local s = object() + s.input, s.output = input, output + if c.interpolation and c.interpolation ~= "LINEAR" then + s.interpolation = c.interpolation + end + table.insert(g.samplers, s) + samplerOf[key] = #g.samplers - 1 + end + local ch = object() + ch.sampler = samplerOf[key] + ch.target = object() + ch.target.node = c.node - 1 + ch.target.path = c.path + table.insert(g.channels, ch) + end + table.insert(animations, g) + end + if failure then + return nil, failure + end + -- scenes: the original list (meta.gltf.scenes) when it is there, else the roots + local meta = if type(scene.meta) == "table" then scene.meta else {} + local mg = type(meta.gltf) == "table" and meta.gltf or {} + local scenes = {} + if type(mg.scenes) == "table" and #mg.scenes > 0 then + for _, s in mg.scenes do + local g = object() + g.name = s.name + g.nodes = {} + for _, n in s.nodes or {} do + if nodes[n] then + table.insert(g.nodes, n - 1) + end + end + restore(g, s.extras) + table.insert(scenes, g) + end + -- the current roots replace the default scene's list + local which = mg.scene or 1 + if scenes[which] then + scenes[which].nodes = {} + for _, r in scene.roots or {} do + table.insert(scenes[which].nodes, r - 1) + end + end + doc.scene = (mg.scene or 1) - 1 + else + local g = object() + g.nodes = {} + for _, r in scene.roots or {} do + table.insert(g.nodes, r - 1) + end + table.insert(scenes, g) + doc.scene = 0 + end + local asset = object() + asset.version = "2.0" + asset.generator = "formats-luau" + if type(mg.asset) == "table" then + asset.copyright = mg.asset.copyright + asset.minVersion = mg.asset.minVersion + asset.extras = mg.asset.extras + end + doc.asset = asset + -- root extensions kept from the source (variants, ...), the lights + if type(mg.extensions) == "table" then + doc.extensions = object() + for k, v in mg.extensions do + doc.extensions[k] = v + used[k] = true + end + end + if #lights > 0 then + doc.extensions = doc.extensions or object() + local lp = object() + lp.lights = lights + doc.extensions.KHR_lights_punctual = lp + used.KHR_lights_punctual = true + end + doc.extras = mg.extras + local function list(t: { [string]: boolean }): { string }? + local out = {} + for k in t do + table.insert(out, k) + end + table.sort(out) + return if #out > 0 then out else nil + end + -- the source's required extensions that are still used stay required + for _, e in (if type(mg.extensionsRequired) == "table" then mg.extensionsRequired else {}) do + if used[e] then + required[e] = true + end + end + doc.extensionsUsed = list(used) + doc.extensionsRequired = list(required) + doc.scenes = scenes + doc.nodes = if #nodes > 0 then nodes else nil + doc.meshes = if #meshes > 0 then meshes else nil + doc.materials = if #materials > 0 then materials else nil + doc.textures = if #textures > 0 then textures else nil + doc.images = if #images > 0 then images else nil + doc.samplers = if #samplers > 0 then samplers else nil + doc.cameras = if #cameras > 0 then cameras else nil + doc.skins = if #skins > 0 then skins else nil + doc.animations = if #animations > 0 then animations else nil + doc.accessors = if #accessors > 0 then accessors else nil + doc.bufferViews = if #views > 0 then views else nil + return { doc = doc, bin = bin:finish(), images = imageOut }, nil +end + +return Write diff --git a/src/Formats/model/gltf/init.luau b/src/Formats/model/gltf/init.luau new file mode 100644 index 0000000..3f533a0 --- /dev/null +++ b/src/Formats/model/gltf/init.luau @@ -0,0 +1,248 @@ +--!strict +-- model/gltf: glTF 2.0 (Khronos specification 2.0.1), JSON (.gltf with embedded data: URIs or external files) and +-- binary (.glb). New code. +-- Reads: scenes, the node tree (TRS / matrix), meshes (every primitive mode, morph targets), accessors of every +-- component type (normalized -> unorm / snorm, sparse, byte strides, padded matrix columns, no bufferView), PBR +-- materials + the KHR_materials_* extensions (emissive_strength, unlit, clearcoat, transmission, volume, ior, +-- specular, sheen, iridescence, anisotropy, dispersion, diffuse_transmission, pbrSpecularGlossiness: their fields kept, +-- textureInfo objects as TextureRefs), KHR_texture_transform, textures + samplers + images (kept encoded: bytes + mime, +-- or the uri; KHR_texture_basisu / EXT_texture_webp / EXT_texture_avif sources), cameras, KHR_lights_punctual, skins, +-- animations, KHR_mesh_quantization, extras and unknown extensions (written back). Images are never decoded here (a +-- format does not require another format): F.model.loadTextures(scene) decodes them at the api layer. +-- External .bin / image files come from opts.resolve(uri) or opts.files[uri] (the api sets resolve for paths). +-- Writes .gltf (buffers and images embedded as data: URIs by default; opts.external = true writes .bin and the +-- images into opts.files) or .glb (opts.binary, or opts.format == "glb": the api passes the destination's extension). +-- Not supported: Draco (KHR_draco_mesh_compression) and meshopt (EXT_meshopt_compression) compressed primitives +-- (UNSUPPORTED), KHR_animation_pointer channels (skipped and counted in the animation's extras). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Json = require("@formats/codecs/Json") +local Base64 = require("@formats/codecs/Base64") +local Read = require("@formats/model/gltf/Read") +local Write = require("@formats/model/gltf/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local Gltf = { + name = "gltf", + category = "model", + 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 }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + resolve: ((uri: string) -> any)?, -- external .bin / image files (buffer or string); the api sets it for paths + files: { [string]: any }?, -- or: the files by uri + maxBytes: number?, -- refuse buffers / accessors over this many bytes in total (default 2^30) +} +export type EncodeOptions = { + binary: boolean?, -- write GLB (default: when opts.format is "glb") + format: string?, -- "glb" -> binary (set by the api from the destination's extension) + external: boolean?, -- .gltf: write the buffer and images as files into opts.files (default false: data: URIs) + files: { [string]: any }?, -- receives .bin and images with external = true + name: string?, -- the destination's file name (names the external files) + embedImages: boolean?, -- default true (false with external = true) +} + +-- ------------------------------------------------------------------------------------------------ constants +local GLB_MAGIC = 0x46546C67 -- "glTF" +local CHUNK_JSON = 0x4E4F534A +local CHUNK_BIN = 0x004E4942 + +-- ------------------------------------------------------------------------------------------------ sniff +function Gltf.sniff(r: Bytes.Reader): number + if r:peek(4) == "glTF" then + return 1 + end + local head = r:peek(1024) + local s = string.gsub(head, "^\239\187\191", "") + if string.find(s, "^%s*{") and string.find(s, "\"asset\"", 1, true) then + return 0.9 + end + if string.find(s, "^%s*{") and (string.find(s, "\"accessors\"", 1, true) or string.find(s, "\"bufferViews\"", 1, true)) then + return 0.6 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function fetcher(opts: DecodeOptions?): Read.Fetch + return function(uri: string): buffer? + if not opts then + return nil + end + local decoded = string.gsub(uri, "%%(%x%x)", function(h: string): string + return string.char(tonumber(h, 16) :: number) + end) + local v: any = nil + if type(opts.files) == "table" then + v = opts.files[uri] or opts.files[decoded] + end + if v == nil and type(opts.resolve) == "function" then + local ok, res = pcall(opts.resolve, uri) + v = if ok then res else nil + end + if type(v) == "string" then + return buffer.fromstring(v) + end + return if type(v) == "buffer" then v else nil + end +end + +-- the JSON text and BIN chunk of a GLB +local function glb(r: Bytes.Reader): (string?, buffer?, Err.Err?) + local magic, version, length = r:u32le(), r:u32le(), r:u32le() + if r.err then + return nil, nil, r.err + end + if magic ~= GLB_MAGIC then + return nil, nil, Err.new(Err.CORRUPT, "bad GLB magic") + end + if version ~= 2 then + return nil, nil, Err.new(Err.UNSUPPORTED, "GLB version " .. version) + end + if length > r:size() then + return nil, nil, Err.new(Err.TRUNCATED, "the GLB is shorter than its header says", r.base + 8) + end + local json: string? = nil + local bin: buffer? = nil + while r:tell() + 8 <= length do + local clen, ctype = r:u32le(), r:u32le() + if clen > length - r:tell() then + return nil, nil, Err.new(Err.TRUNCATED, "a GLB chunk runs past the end", r.base + r:tell() - 8) + end + if ctype == CHUNK_JSON and json == nil then + json = r:string(clen) + elseif ctype == CHUNK_BIN and bin == nil and json ~= nil then + bin = r:bytes(clen) + else + r:skip(clen) + end + if r.err then + return nil, nil, r.err + end + end + if not json then + return nil, nil, Err.new(Err.CORRUPT, "GLB without a JSON chunk") + end + return json, bin, nil +end + +function Gltf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local binary = r:peek(4) == "glTF" + local text: string?, bin: buffer? + if binary then + local t, b, err = glb(r) + if not t then + return nil, err + end + text, bin = t, b + else + text = buffer.readstring(r.buf, r.base, r.limit - r.base) + end + local doc, jerr = Json.decode(text :: string) + if doc == nil then + return nil, jerr + end + local scene, err = Read.scene(doc, bin, fetcher(opts), opts) + if not scene then + return nil, err + end + scene.meta.source = { format = "gltf", binary = binary, generator = type(doc.asset) == "table" and doc.asset.generator or nil } + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/webp"] = "webp", ["image/ktx2"] = "ktx2", ["image/avif"] = "avif" } + +function Gltf.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(scene) ~= "table" or scene.kind ~= "scene" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + local binary = opts and (opts.binary or opts.format == "glb") or false + local external = opts and opts.external == true and type(opts.files) == "table" and not binary + local embedImages = if opts and opts.embedImages ~= nil then opts.embedImages else not external + local out, err = Write.build(scene, { binary = binary, embedImages = embedImages }) + if not out then + return nil, err + end + local doc = out.doc + local base = opts and opts.name and string.gsub(string.match(opts.name, "([^/\\]+)$") or opts.name, "%.[^.]*$", "") or "model" + local files = opts and opts.files + -- images: data: URIs, or files + if doc.images then + local n = 0 + for _, im in doc.images do + if type(im.uri) == "string" and string.sub(im.uri, 1, 1) == "\0" then + for _, o in out.images do + if o.name == im.uri then + if string.sub(im.uri, 1, 6) == "\0image" or type(files) ~= "table" then + im.uri = Base64.dataUri(o.data, o.mime or "image/png") + else + n += 1 + local fname = base .. "_" .. n .. "." .. (EXT[o.mime or ""] or "png") + files[fname] = o.data + im.uri = fname + end + break + end + end + elseif type(im.uri) == "string" and type(files) == "table" and not embedImages then + for _, o in out.images do + if o.name == im.uri then + files[im.uri] = o.data + end + end + end + end + end + local binLen = buffer.len(out.bin) + if binLen > 0 then + local b = Types.object() + b.byteLength = binLen + if not binary then + if external then + local fname = base .. ".bin" + b.uri = fname + local ff: any = files + ff[fname] = out.bin + else + b.uri = Base64.dataUri(out.bin, "application/octet-stream") + end + end + doc.buffers = { b } + end + local text, jerr = Json.encode(doc, if binary then nil else { indent = 2 }) + if not text then + return nil, Err.new(Err.ARG, "JSON: " .. tostring(jerr and jerr.message or jerr)) + end + if not binary then + return buffer.fromstring(text :: string), nil + end + local jpad = (4 - #(text :: string) % 4) % 4 + local bpad = (4 - binLen % 4) % 4 + local w = Bytes.writer(12 + 8 + #(text :: string) + jpad + 8 + binLen + bpad) + w:u32le(GLB_MAGIC) + w:u32le(2) + local lenAt = w:tell() + w:u32le(0) + w:u32le(#(text :: string) + jpad) + w:u32le(CHUNK_JSON) + w:string(text :: string) + w:string(string.rep(" ", jpad)) + if binLen > 0 then + w:u32le(binLen + bpad) + w:u32le(CHUNK_BIN) + w:bytes(out.bin) + w:fill(0, bpad) + end + w:setU32le(lenAt, w:tell()) + return w:finish(), nil +end + +return Gltf diff --git a/src/Formats/model/obj/Mtl.luau b/src/Formats/model/obj/Mtl.luau new file mode 100644 index 0000000..64f18de --- /dev/null +++ b/src/Formats/model/obj/Mtl.luau @@ -0,0 +1,294 @@ +--!strict +-- model/obj/Mtl: Wavefront .mtl material libraries (Paul Bourke's MTL spec + the common PBR extension: Pr, Pm, Ps, Pc, +-- Pcr, aniso, anisor, Ke, map_Pr, map_Pm, map_Ke, norm). parse(text) -> { name -> { statement -> values } } keeping +-- every statement; toMaterial maps one onto the Scene Material (glTF PBR, Phong values in extras.obj); write is the +-- reverse (from extras.obj when present, else from the PBR fields). +local Types = require("@formats/Types") + +local Mtl = {} + +export type Map = { file: string, options: { [string]: { string } } } -- -o / -s / -bm / -clamp / ... with their values +export type Entry = { name: string, values: { [string]: { number } }, maps: { [string]: Map }, order: { string } } + +-- the number of arguments of each texture map option (Bourke): -o / -s / -t take 1..3 numbers +local OPT_ARGS = { blendu = 1, blendv = 1, cc = 1, clamp = 1, mm = 2, bm = 1, boost = 1, texres = 1, imfchan = 1, type = 1 } +local MAPS = { + map_Ka = true, map_Kd = true, map_Ks = true, map_Ke = true, map_Ns = true, map_d = true, map_Tr = true, + map_bump = true, bump = true, map_Bump = true, disp = true, decal = true, refl = true, norm = true, map_Pr = true, + map_Pm = true, map_Ps = true, map_Pc = true, map_Pcr = true, map_RMA = true, map_ORM = true, map_aniso = true, +} +Mtl.MAPS = MAPS + +local function parseMap(args: { string }): Map + local opts: { [string]: { string } } = {} + local i = 1 + while i <= #args and string.sub(args[i], 1, 1) == "-" and tonumber(args[i]) == nil do + local key = string.sub(args[i], 2) + local vals = {} + i += 1 + local n = OPT_ARGS[key] + if n then + for _ = 1, n do + if i <= #args then + table.insert(vals, args[i]) + i += 1 + end + end + else + -- -o / -s / -t: up to three numbers + while i <= #args and #vals < 3 and tonumber(args[i]) ~= nil and i < #args do + table.insert(vals, args[i]) + i += 1 + end + end + opts[key] = vals + end + -- the file name is the rest (it may contain spaces) + local file = table.concat(args, " ", i) + return { file = file, options = opts } +end + +-- parse(text) -> { Entry } in file order +function Mtl.parse(text: string): { Entry } + local out: { Entry } = {} + local cur: Entry? = nil + for line in string.gmatch(text, "[^\r\n]+") do + local l = string.gsub(line, "#.*$", "") + local words = {} + for w in string.gmatch(l, "%S+") do + table.insert(words, w) + end + local key = words[1] + if key == "newmtl" then + cur = { name = table.concat(words, " ", 2), values = {}, maps = {}, order = {} } + table.insert(out, cur :: Entry) + elseif key and cur then + local e = cur :: Entry + local args = table.move(words, 2, #words, 1, {}) + if MAPS[key] then + e.maps[key] = parseMap(args) + table.insert(e.order, key) + else + local nums = {} + for _, a in args do + local v = tonumber(a) + if v == nil then + nums = nil :: any + break + end + table.insert(nums, v) + end + if nums then + if e.values[key] == nil then + table.insert(e.order, key) + end + e.values[key] = nums + end + end + end + end + return out +end + +local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", webp = "image/webp", gif = "image/gif", bmp = "image/bmp", tga = "image/x-tga", tif = "image/tiff", tiff = "image/tiff", dds = "image/vnd-ms.dds", ktx2 = "image/ktx2", exr = "image/x-exr", hdr = "image/vnd.radiance" } +function Mtl.mime(file: string): string? + local ext = string.match(file, "%.([%w]+)$") + return if ext then MIME[string.lower(ext)] else nil +end + +-- toMaterial(entry, texture) -> Material: texture(map) returns the scene texture index for a map +function Mtl.toMaterial(e: Entry, texture: (Map) -> number): Types.Material + local m = Types.Scene.material(e.name) + local v = e.values + local kd = v.Kd + if kd and #kd >= 3 then + m.baseColor = { kd[1], kd[2], kd[3], 1 } + end + local d = if v.d then v.d[1] elseif v.Tr then 1 - v.Tr[1] else 1 + m.baseColor[4] = d + if d < 1 then + m.alphaMode = "blend" + end + local ke = v.Ke + if ke and #ke >= 3 then + m.emissive = { ke[1], ke[2], ke[3] } + end + m.metallic = if v.Pm then v.Pm[1] else 0 + if v.Pr then + m.roughness = v.Pr[1] + elseif v.Ns then + m.roughness = math.clamp(math.sqrt(2 / (math.max(v.Ns[1], 0) + 2)), 0, 1) + end + local function ref(key: string): Types.TextureRef? + local map = e.maps[key] + if not map or map.file == "" then + return nil + end + local r: Types.TextureRef = { texture = texture(map) } + local o, s = map.options.o, map.options.s + if o or s then + r.transform = { + offset = if o then { tonumber(o[1]) or 0, tonumber(o[2]) or 0 } else nil, + scale = if s then { tonumber(s[1]) or 1, tonumber(s[2]) or 1 } else nil, + } + end + if map.options.bm then + r.scale = tonumber(map.options.bm[1]) + end + return r + end + m.baseColorTexture = ref("map_Kd") + m.emissiveTexture = ref("map_Ke") + m.normalTexture = ref("norm") or ref("map_bump") or ref("bump") or ref("map_Bump") + m.metallicRoughnessTexture = ref("map_ORM") or ref("map_RMA") + if m.emissiveTexture and not ke then + m.emissive = { 1, 1, 1 } + end + -- everything else as it was, for the writer and for Phong renderers + local extra: { [string]: any } = {} + for k, vals in v do + extra[k] = vals + end + local maps: { [string]: any } = {} + for k, map in e.maps do + maps[k] = { file = map.file, options = map.options, texture = texture(map) } + end + m.extras = { obj = { values = extra, maps = maps, order = e.order } } + return m +end + +local function num(v: number): string + if v == math.floor(v) and math.abs(v) < 1e15 then + return string.format("%d", v) + end + for _, f in { "%.6g", "%.9g", "%.17g" } do + local s = string.format(f, v) + if tonumber(s) == v then + return s + end + end + return string.format("%.17g", v) +end +Mtl.num = num + +-- write(materials, name, textureFile) -> MTL text. textureFile(index) -> the file name a map refers to. +function Mtl.write(materials: { Types.Material }, names: { string }, textureFile: (number) -> string?): string + local out = { "# written by formats-luau" } + for i, m in materials do + table.insert(out, "") + table.insert(out, "newmtl " .. names[i]) + local saved = m.extras and m.extras.obj + local values: { [string]: { number } } = {} + local maps: { [string]: any } = {} + local order: { string } = {} + if type(saved) == "table" and type(saved.values) == "table" then + for k, vals in saved.values do + values[k] = vals + end + for k, mp in saved.maps or {} do + maps[k] = mp + end + order = table.clone(saved.order or {}) + end + -- the PBR fields win over the saved Phong values they map to + local bc = m.baseColor or { 1, 1, 1, 1 } + values.Kd = { bc[1], bc[2], bc[3] } + if (bc[4] or 1) < 1 or values.d then + values.d = { bc[4] or 1 } + values.Tr = nil + end + local em = m.emissive or { 0, 0, 0 } + if em[1] ~= 0 or em[2] ~= 0 or em[3] ~= 0 or values.Ke then + values.Ke = { em[1], em[2], em[3] } + end + if not (saved and saved.values and saved.values.Ns and not saved.values.Pr) then + values.Pr = { m.roughness } + end + if m.metallic ~= 0 or values.Pm then + values.Pm = { m.metallic } + end + local function setMap(key: string, ref: Types.TextureRef?) + if ref then + local file = textureFile(ref.texture) + if file then + local prev = maps[key] + local options = if prev and prev.texture == ref.texture then prev.options else {} + options = table.clone(options or {}) + if ref.transform then + if ref.transform.offset then + options.o = { num(ref.transform.offset[1]), num(ref.transform.offset[2]) } + end + if ref.transform.scale then + options.s = { num(ref.transform.scale[1]), num(ref.transform.scale[2]) } + end + end + if ref.scale and key ~= "map_Kd" then + options.bm = { num(ref.scale) } + end + maps[key] = { file = file, options = options, texture = ref.texture } + end + end + end + setMap("map_Kd", m.baseColorTexture) + setMap("map_Ke", m.emissiveTexture) + if m.normalTexture and not maps.map_bump and not maps.bump and not maps.map_Bump then + setMap("norm", m.normalTexture) + end + setMap("map_ORM", m.metallicRoughnessTexture) + -- the saved order first, then the rest sorted + local keys = {} + local seen = {} + for _, k in order do + if (values[k] or maps[k]) and not seen[k] then + table.insert(keys, k) + seen[k] = true + end + end + local rest = {} + for k in values do + if not seen[k] then + table.insert(rest, k) + end + end + for k in maps do + if not seen[k] and not values[k] then + table.insert(rest, k) + end + end + table.sort(rest) + for _, k in rest do + seen[k] = true + table.insert(keys, k) + end + for _, k in keys do + local mp = maps[k] + if mp and type(mp.file) == "string" then + local file = if type(mp.texture) == "number" then (textureFile(mp.texture) or mp.file) else mp.file + local parts = { k } + local okeys = {} + for ok in mp.options or {} do + table.insert(okeys, ok) + end + table.sort(okeys) + for _, ok in okeys do + table.insert(parts, "-" .. ok) + for _, ov in mp.options[ok] do + table.insert(parts, tostring(ov)) + end + end + table.insert(parts, file) + table.insert(out, table.concat(parts, " ")) + elseif values[k] then + local parts = { k } + for _, x in values[k] do + table.insert(parts, num(x)) + end + table.insert(out, table.concat(parts, " ")) + end + end + end + table.insert(out, "") + return table.concat(out, "\n") +end + +return Mtl diff --git a/src/Formats/model/obj/init.luau b/src/Formats/model/obj/init.luau new file mode 100644 index 0000000..f39a894 --- /dev/null +++ b/src/Formats/model/obj/init.luau @@ -0,0 +1,762 @@ +--!strict +-- model/obj: Wavefront OBJ (+ MTL), from Paul Bourke's OBJ / MTL specifications and what Blender / Maya / assimp +-- write. Supports: v (with the common "v x y z r g b" vertex colour extension), vt, vn, f with every index form +-- (v, v/vt, v//vn, v/vt/vn, negative = relative), l, p, o / g (nodes), usemtl / mtllib (materials: Phong + the PBR +-- extension, texture maps with -o / -s / -bm options; texture images stay encoded bytes or file names, see Types), line +-- continuations, comments. n-gons are fan-triangulated by default (opts.triangulate = false keeps them as "polygons", +-- MeshOps.triangulate ear-clips concave ones). TEXCOORD_0 is flipped to glTF's top-left origin (opts.flipV = false +-- keeps OBJ's). +-- Nodes: one per object (o); groups (g) inside an object become child nodes; files without o: one root node per group. +-- Each node has a mesh with one primitive per material. Vertices are unwelded per (v, vt, vn) combination. +-- Not supported: free-form geometry (curv, surf, ...: skipped and counted in meta.source.skipped), smoothing groups +-- (s: kept per node in extras.obj.smoothing, not used to compute normals). +-- encode: every mesh primitive of the scene baked into world space, one o per node; materials into a .mtl (written to +-- opts.files[.mtl] when opts.files is a table, see Types), embedded texture bytes into opts.files too. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Mtl = require("@formats/model/obj/Mtl") + +-- ------------------------------------------------------------------------------------------------ contract +local Obj = { + name = "obj", + category = "model", + extensions = { "obj" }, + mime = { "model/obj" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, materials = true, polygons = true, vertexColors = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + triangulate: boolean?, -- fan-triangulate n-gons (default true); false keeps "polygons" primitives + flipV: boolean?, -- TEXCOORD_0.v = 1 - v (default true: glTF's convention) + mtl: (string | buffer)?, -- the material library text, when not found through resolve / files + resolve: ((uri: string) -> any)?, -- reads mtllib / texture files (the api sets it for paths) + files: { [string]: any }?, -- or: the other files by name + maxVertices: number?, -- refuse more v / vt / vn / corners (default 2^25) +} +export type EncodeOptions = { + name: string?, -- the destination file name: the .mtl is named after it (default "model.mtl") + mtlName: string?, -- the .mtl file name (overrides name) + files: { [string]: any }?, -- receives the .mtl and embedded textures + flipV: boolean?, -- default true (the inverse of decode) + normals: boolean?, -- write vn (default true when the primitives have NORMAL) + texcoords: boolean?, -- write vt (default true when the primitives have TEXCOORD_0) + colors: boolean?, -- write vertex colours after v (default true when COLOR_0 exists) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Obj.sniff(r: Bytes.Reader): number + local head = r:peek(512) + if string.find(head, "\0", 1, true) then + return 0 + end + if string.find(head, "^%s*v%s+[%-%d%.]") or string.find(head, "\n%s*v%s+[%-%d%.]") then + return 0.6 + end + if string.find(head, "^#") and (string.find(head, "\nmtllib ") or string.find(head, "\no ") or string.find(head, "\ng ")) then + return 0.4 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function fetch(opts: DecodeOptions?, uri: string): string? + if not opts then + return nil + end + local v: any = nil + if type(opts.files) == "table" then + v = opts.files[uri] + if v == nil then + v = opts.files[string.match(uri, "([^/\\]+)$") or uri] + end + end + if v == nil and type(opts.resolve) == "function" then + local ok, res = pcall(opts.resolve, uri) + v = if ok then res else nil + end + if type(v) == "buffer" then + return buffer.tostring(v) + elseif type(v) == "string" then + return v + end + return nil +end + +type Prim = { + material: string?, + mode: string, + cv: { number }, -- per corner: position index (0-based), texcoord index (-1 none), normal index (-1 none) + ct: { number }, + cn: { number }, + faces: { number }, -- corners per face (polygons / lines) + hasT: boolean, + hasN: boolean, +} +type Section = { object: string?, group: string?, prims: { Prim }, byKey: { [string]: Prim }, smoothing: string? } + +function Obj.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local triangulate = not (opts and opts.triangulate == false) + local flipV = not (opts and opts.flipV == false) + local maxV = opts and opts.maxVertices or 2 ^ 25 + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local P, C, UV, N = {}, {}, {}, {} + local np, nt, nn = 0, 0, 0 + local hasColor = false + local sections: { Section } = {} + local byName: { [string]: Section } = {} + local cur: Section? = nil + local object: string? = nil + local group: string? = nil + local material: string? = nil + local smoothing: string? = nil + local mtllibs: { string } = {} + local skipped = 0 + local corners = 0 + local hasObjects = false + local lineNo = 0 + local pos = 1 + local len = #text + local function section(): Section + if cur then + return cur + end + local key = (object or "") .. "\0" .. (group or "") + local s = byName[key] + if not s then + s = { object = object, group = group, prims = {}, byKey = {}, smoothing = smoothing } + byName[key] = s + table.insert(sections, s) + end + cur = s + return s + end + local function prim(mode: string): Prim + local s = section() + local key = mode .. "\0" .. (material or "") + local p = s.byKey[key] + if not p then + p = { material = material, mode = mode, cv = {}, ct = {}, cn = {}, faces = {}, hasT = false, hasN = false } + s.byKey[key] = p + table.insert(s.prims, p) + end + return p + end + -- one corner "v/vt/vn" -> indices (0-based, -1 for none) | nil + local function corner(tok: string): (number?, number, number) + local a, b, c = string.match(tok, "^([^/]*)/?([^/]*)/?([^/]*)$") + local vi = tonumber(a) + if not vi then + return nil, -1, -1 + end + vi = if vi < 0 then np + vi else vi - 1 + local ti, ni = -1, -1 + local t = tonumber(b) + if t then + ti = if t < 0 then nt + t else t - 1 + if ti < 0 or ti >= nt then + return nil, -1, -1 + end + end + local n = tonumber(c) + if n then + ni = if n < 0 then nn + n else n - 1 + if ni < 0 or ni >= nn then + return nil, -1, -1 + end + end + if vi < 0 or vi >= np then + return nil, -1, -1 + end + return vi, ti, ni + end + local fs: { string } = {} + while pos <= len do + local e = string.find(text, "\n", pos, true) or (len + 1) + local line = string.sub(text, pos, e - 1) + pos = e + 1 + lineNo += 1 + -- continuation lines + while string.sub(line, -1) == "\\" or string.sub(line, -2) == "\\\r" do + line = string.gsub(line, "\\\r?$", " ") + local e2 = string.find(text, "\n", pos, true) or (len + 1) + line ..= string.sub(text, pos, e2 - 1) + pos = e2 + 1 + lineNo += 1 + end + local key, rest = string.match(line, "^%s*(%S+)%s*(.-)%s*$") + if key == nil or string.sub(key, 1, 1) == "#" then + continue + end + local hash = string.find(rest, "#", 1, true) + if hash then + rest = string.gsub(string.sub(rest, 1, hash - 1), "%s+$", "") + end + if key == "v" then + local x, y, z, a, b, c = string.match(rest, "^(%S+)%s+(%S+)%s+(%S+)%s*(%S*)%s*(%S*)%s*(%S*)") + local fx, fy, fz = tonumber(x), tonumber(y), tonumber(z) + if not fx or not fy or not fz then + return nil, Err.new(Err.CORRUPT, "bad vertex on line " .. lineNo) + end + if np >= maxV then + return nil, Err.new(Err.LIMIT, "over " .. maxV .. " vertices") + end + P[np * 3 + 1], P[np * 3 + 2], P[np * 3 + 3] = fx, fy, fz + local cr, cg, cb = tonumber(a), tonumber(b), tonumber(c) + if cr and cg and cb then + hasColor = true + C[np * 3 + 1], C[np * 3 + 2], C[np * 3 + 3] = cr, cg, cb + end + np += 1 + elseif key == "vt" then + local u, v = string.match(rest, "^(%S+)%s*(%S*)") + local fu = tonumber(u) + if not fu then + return nil, Err.new(Err.CORRUPT, "bad texture coordinate on line " .. lineNo) + end + if nt >= maxV then + return nil, Err.new(Err.LIMIT, "over " .. maxV .. " texture coordinates") + end + local fv = tonumber(v) or 0 + UV[nt * 2 + 1], UV[nt * 2 + 2] = fu, if flipV then 1 - fv else fv + nt += 1 + elseif key == "vn" then + local x, y, z = string.match(rest, "^(%S+)%s+(%S+)%s+(%S+)") + local fx, fy, fz = tonumber(x), tonumber(y), tonumber(z) + if not fx or not fy or not fz then + return nil, Err.new(Err.CORRUPT, "bad normal on line " .. lineNo) + end + if nn >= maxV then + return nil, Err.new(Err.LIMIT, "over " .. maxV .. " normals") + end + N[nn * 3 + 1], N[nn * 3 + 2], N[nn * 3 + 3] = fx, fy, fz + nn += 1 + elseif key == "f" or key == "l" or key == "p" then + table.clear(fs) + for tok in string.gmatch(rest, "%S+") do + table.insert(fs, tok) + end + local k = #fs + local mode = if key == "f" then (if triangulate then "triangles" else "polygons") elseif key == "l" then "lines" else "points" + if (key == "f" and k < 3) or (key == "l" and k < 2) or k < 1 then + return nil, Err.new(Err.CORRUPT, "an element with too few corners on line " .. lineNo) + end + corners += k + if corners > maxV * 4 then + return nil, Err.new(Err.LIMIT, "too many face corners") + end + local p = prim(mode) + local base = #p.cv + for i, tok in fs do + local vi, ti, ni = corner(tok) + if not vi then + return nil, Err.new(Err.CORRUPT, "bad index '" .. tok .. "' on line " .. lineNo) + end + p.cv[base + i], p.ct[base + i], p.cn[base + i] = vi, ti, ni + if ti >= 0 then + p.hasT = true + end + if ni >= 0 then + p.hasN = true + end + end + if mode == "triangles" and k > 3 then + -- fan: rewrite the k corners as (k - 2) triangles + local cv, ct, cn = table.move(p.cv, base + 1, base + k, 1, {}), table.move(p.ct, base + 1, base + k, 1, {}), table.move(p.cn, base + 1, base + k, 1, {}) + local o = base + for a = 2, k - 1 do + for _, j in { 1, a, a + 1 } do + o += 1 + p.cv[o], p.ct[o], p.cn[o] = cv[j], ct[j], cn[j] + end + end + elseif mode == "lines" then + -- a polyline -> segments + local cv, ct, cn = table.move(p.cv, base + 1, base + k, 1, {}), table.move(p.ct, base + 1, base + k, 1, {}), table.move(p.cn, base + 1, base + k, 1, {}) + local o = base + for a = 1, k - 1 do + for _, j in { a, a + 1 } do + o += 1 + p.cv[o], p.ct[o], p.cn[o] = cv[j], ct[j], cn[j] + end + end + elseif mode == "polygons" then + table.insert(p.faces, k) + end + elseif key == "o" then + object = rest + group = nil + hasObjects = true + cur = nil + elseif key == "g" then + group = if rest == "" then nil else rest + cur = nil + elseif key == "usemtl" then + material = rest + elseif key == "mtllib" then + table.insert(mtllibs, rest) + elseif key == "s" then + smoothing = rest + if cur then + cur.smoothing = cur.smoothing or rest + end + else + skipped += 1 + end + end + -- materials + local scene = Types.Scene.new() + local matIndex: { [string]: number } = {} + local texIndex: { [string]: number } = {} + local function texture(map: Mtl.Map): number + local file = string.gsub(map.file, "\\", "/") + local i = texIndex[file] + if i then + return i + end + local tex: Types.Texture = { uri = file, mime = Mtl.mime(file) } + local data = fetch(opts, file) + if data then + tex.data = buffer.fromstring(data) + end + if map.options.clamp and map.options.clamp[1] == "on" then + tex.sampler = { wrapS = "clamp", wrapT = "clamp" } + end + table.insert(scene.textures, tex) + i = #scene.textures + texIndex[file] = i + return i + end + local mtlText = if opts and opts.mtl then (if type(opts.mtl) == "buffer" then buffer.tostring(opts.mtl) else opts.mtl) else nil + local missing: { string } = {} + local libs: { string } = {} + if mtlText then + table.insert(libs, mtlText :: string) + end + for _, lib in mtllibs do + local t = fetch(opts, lib) + if t then + table.insert(libs, t) + elseif not mtlText then + table.insert(missing, lib) + end + end + for _, lt in libs do + for _, e in Mtl.parse(lt) do + if not matIndex[e.name] then + table.insert(scene.materials, Mtl.toMaterial(e, texture)) + matIndex[e.name] = #scene.materials + end + end + end + -- materials named by usemtl but not defined anywhere: a default one with the name + for _, s in sections do + for _, p in s.prims do + if p.material and not matIndex[p.material] then + table.insert(scene.materials, Types.Scene.material(p.material)) + scene.materials[#scene.materials].metallic = 0 + matIndex[p.material] = #scene.materials + end + end + end + -- vertices: one per distinct (v, vt, vn) in each primitive + local f32 = buffer.writef32 + local KT, KN = nt + 1, nn + 1 + local numericKeys = np * KT * KN < 2 ^ 52 + local function build(p: Prim): Types.Primitive + local n = #p.cv + local map: { [any]: number } = {} + local verts: { number } = {} + local idx = buffer.create(n * 4) + local count = 0 + for i = 1, n do + local v, t, nr = p.cv[i], p.ct[i], p.cn[i] + local key: any = if numericKeys then (v * KT + (t + 1)) * KN + (nr + 1) else string.format("%d/%d/%d", v, t, nr) + local k = map[key] + if k == nil then + k = count + map[key] = k + count += 1 + verts[count * 3 - 2], verts[count * 3 - 1], verts[count * 3] = v, t, nr + end + buffer.writeu32(idx, (i - 1) * 4, k) + end + local pb = buffer.create(count * 12) + local tb = if p.hasT then buffer.create(count * 8) else nil + local nb = if p.hasN then buffer.create(count * 12) else nil + local cb = if hasColor then buffer.create(count * 12) else nil + for k = 0, count - 1 do + local v, t, nr = verts[k * 3 + 1], verts[k * 3 + 2], verts[k * 3 + 3] + f32(pb, k * 12, P[v * 3 + 1]) + f32(pb, k * 12 + 4, P[v * 3 + 2]) + f32(pb, k * 12 + 8, P[v * 3 + 3]) + if tb and t >= 0 then + f32(tb, k * 8, UV[t * 2 + 1]) + f32(tb, k * 8 + 4, UV[t * 2 + 2]) + end + if nb and nr >= 0 then + f32(nb, k * 12, N[nr * 3 + 1]) + f32(nb, k * 12 + 4, N[nr * 3 + 2]) + f32(nb, k * 12 + 8, N[nr * 3 + 3]) + end + if cb then + f32(cb, k * 12, C[v * 3 + 1] or 1) + f32(cb, k * 12 + 4, C[v * 3 + 2] or 1) + f32(cb, k * 12 + 8, C[v * 3 + 3] or 1) + end + end + local A = Types.Scene.accessor + local attrs: { [string]: Types.Accessor } = { POSITION = A(pb, "f32", 3, count) } + if tb then + attrs.TEXCOORD_0 = A(tb, "f32", 2, count) + end + if nb then + attrs.NORMAL = A(nb, "f32", 3, count) + end + if cb then + attrs.COLOR_0 = A(cb, "f32", 3, count) + end + local out: Types.Primitive = { attributes = attrs, indices = A(idx, "u32", 1, n), mode = p.mode :: any, material = if p.material then matIndex[p.material] else nil } + if p.mode == "points" then + out.indices = if count == n then nil else out.indices + end + if p.mode == "polygons" then + local fb = buffer.create(#p.faces * 4) + for i, k in p.faces do + buffer.writeu32(fb, (i - 1) * 4, k) + end + out.faces = A(fb, "u32", 1, #p.faces) + end + return out + end + -- nodes: objects at the root, their groups as children; without objects every group is a root + local objectNode: { [string]: number } = {} + for _, s in sections do + if #s.prims > 0 then + local mesh: Types.Mesh = { name = s.group or s.object, primitives = {} } + for _, p in s.prims do + table.insert(mesh.primitives, build(p)) + end + table.insert(scene.meshes, mesh) + local node: Types.Node = { name = s.group or s.object, children = {}, mesh = #scene.meshes } + if s.smoothing then + node.extras = { obj = { smoothing = s.smoothing } } + end + if hasObjects and s.object and s.group then + local oi = objectNode[s.object] + if not oi then + table.insert(scene.nodes, { name = s.object, children = {} }) + oi = #scene.nodes + objectNode[s.object] = oi + table.insert(scene.roots, oi) + end + table.insert(scene.nodes, node) + table.insert(scene.nodes[oi].children, #scene.nodes) + else + if hasObjects and s.object and not s.group and objectNode[s.object] == nil then + table.insert(scene.nodes, node) + objectNode[s.object] = #scene.nodes + table.insert(scene.roots, #scene.nodes) + elseif hasObjects and s.object and objectNode[s.object] then + -- the object's own faces after its groups: a child too + table.insert(scene.nodes, node) + table.insert(scene.nodes[objectNode[s.object]].children, #scene.nodes) + else + table.insert(scene.nodes, node) + table.insert(scene.roots, #scene.nodes) + end + end + end + end + scene.meta.up = "y" + scene.meta.source = { + format = "obj", + positions = np, + texcoords = nt, + normals = nn, + vertexColors = hasColor, + mtllib = if #mtllibs > 0 then mtllibs else nil, + missingMtl = if #missing > 0 then missing else nil, + skipped = skipped, + } + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- the shortest decimal that reads back as the same f32 +local probe = buffer.create(4) +local function f32str(v: number): string + if v ~= v or v == math.huge or v == -math.huge then + return "0" + end + if v == math.floor(v) and math.abs(v) < 1e7 then + return string.format("%d", v) + end + buffer.writef32(probe, 0, v) + local want = buffer.readf32(probe, 0) + for _, f in { "%.6g", "%.7g", "%.8g" } do + local s = string.format(f, v) + buffer.writef32(probe, 0, tonumber(s) :: number) + if buffer.readf32(probe, 0) == want then + return s + end + end + return string.format("%.9g", v) +end + +local function nameOk(s: string): string + local t = string.gsub(s, "[\r\n]", " ") + return t +end + +local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/webp"] = "webp", ["image/gif"] = "gif", ["image/bmp"] = "bmp", ["image/ktx2"] = "ktx2" } + +function Obj.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(scene) ~= "table" or scene.kind ~= "scene" or type(scene.nodes) ~= "table" or type(scene.meshes) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + local flipV = not (opts and opts.flipV == false) + local base = opts and opts.name and string.gsub(string.match(opts.name, "([^/\\]+)$") or opts.name, "%.[^.]*$", "") or "model" + local mtlName = opts and opts.mtlName or (base .. ".mtl") + local files = opts and opts.files + local placed = Types.Scene.flatten(scene) + local out = { "# written by formats-luau" } + local mats = scene.materials or {} + -- material names (unique), texture file names + local names: { string } = {} + local used: { [string]: boolean } = {} + for i, m in mats do + local n = string.gsub(m.name or ("material_" .. i), "%s", "_") + while used[n] do + n ..= "_" .. i + end + used[n] = true + names[i] = n + end + local texFiles: { [number]: string } = {} + local function textureFile(i: number): string? + if texFiles[i] then + return texFiles[i] + end + local tex = scene.textures and scene.textures[i] + if not tex then + return nil + end + local file = tex.uri + if (file == nil or string.find(file, "^data:")) and tex.data then + file = base .. "_" .. i .. "." .. (EXT[tex.mime or ""] or "png") + end + if file and tex.data and type(files) == "table" then + files[file] = tex.data + end + texFiles[i] = file + return file + end + if #mats > 0 then + table.insert(out, "mtllib " .. mtlName) + if type(files) == "table" then + files[mtlName] = Mtl.write(mats, names, textureFile) + end + end + local nv, nt, nn = 0, 0, 0 + local lastNode = -1 + for _, pl in placed do + local prim = pl.primitive + local attrs = prim.attributes + local pos = attrs and attrs.POSITION + if not pos then + continue + end + local P = Types.Scene.reader(pos) + if not P then + return nil, Err.new(Err.ARG, "bad POSITION accessor") + end + if buffer.len(pos.data) < pos.count * pos.components * (Types.COMPONENT_SIZE[pos.type] or 4) then + return nil, Err.new(Err.ARG, "POSITION data is smaller than its count") + end + local m = pl.matrix + local ident = m == Types.Scene.IDENTITY + local node = scene.nodes[pl.node] + if pl.node ~= lastNode then + lastNode = pl.node + table.insert(out, "o " .. nameOk(node.name or ("node_" .. pl.node))) + end + local n = pos.count + local Cc = if attrs.COLOR_0 and not (opts and opts.colors == false) then Types.Scene.reader(attrs.COLOR_0) else nil + local T = if attrs.TEXCOORD_0 and not (opts and opts.texcoords == false) then Types.Scene.reader(attrs.TEXCOORD_0) else nil + local Nr = if attrs.NORMAL and not (opts and opts.normals == false) then Types.Scene.reader(attrs.NORMAL) else nil + for _, a in { attrs.COLOR_0, attrs.TEXCOORD_0, attrs.NORMAL } do + if a and (a.count < n or buffer.len(a.data) < a.count * a.components * (Types.COMPONENT_SIZE[a.type] or 4)) then + return nil, Err.new(Err.ARG, "an attribute is shorter than POSITION") + end + end + -- the normal matrix (inverse transpose) for baked normals + local nm: { number }? = nil + if Nr and not ident then + local a, b, c, d, e, f, g, h, i = m[1], m[5], m[9], m[2], m[6], m[10], m[3], m[7], m[11] + local det = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g) + local k = if det ~= 0 then 1 / det else 1 + nm = { (e * i - f * h) * k, -(d * i - f * g) * k, (d * h - e * g) * k, -(b * i - c * h) * k, (a * i - c * g) * k, -(a * h - b * g) * k, (b * f - c * e) * k, -(a * f - c * d) * k, (a * e - b * d) * k } + end + for v = 0, n - 1 do + local x, y, z = P(v, 0), P(v, 1), P(v, 2) + if not ident then + x, y, z = m[1] * x + m[5] * y + m[9] * z + m[13], m[2] * x + m[6] * y + m[10] * z + m[14], m[3] * x + m[7] * y + m[11] * z + m[15] + end + if Cc then + table.insert(out, string.format("v %s %s %s %s %s %s", f32str(x), f32str(y), f32str(z), f32str(Cc(v, 0)), f32str(Cc(v, 1)), f32str(Cc(v, 2)))) + else + table.insert(out, string.format("v %s %s %s", f32str(x), f32str(y), f32str(z))) + end + end + if T then + for v = 0, n - 1 do + local tv = T(v, 1) + table.insert(out, string.format("vt %s %s", Mtl.num(T(v, 0)), Mtl.num(if flipV then 1 - tv else tv))) + end + end + if Nr then + for v = 0, n - 1 do + local x, y, z = Nr(v, 0), Nr(v, 1), Nr(v, 2) + if nm then + x, y, z = nm[1] * x + nm[4] * y + nm[7] * z, nm[2] * x + nm[5] * y + nm[8] * z, nm[3] * x + nm[6] * y + nm[9] * z + local l = math.sqrt(x * x + y * y + z * z) + if l > 0 then + x, y, z = x / l, y / l, z / l + end + end + table.insert(out, string.format("vn %s %s %s", f32str(x), f32str(y), f32str(z))) + end + end + if prim.material and names[prim.material] then + table.insert(out, "usemtl " .. names[prim.material]) + end + local function ref(i: number): string + local s = tostring(nv + i + 1) + if T and Nr then + return string.format("%s/%d/%d", s, nt + i + 1, nn + i + 1) + elseif T then + return string.format("%s/%d", s, nt + i + 1) + elseif Nr then + return string.format("%s//%d", s, nn + i + 1) + end + return s + end + -- the corner list + local ind = prim.indices + local I: ((number, number) -> number)? = if ind then Types.Scene.reader(ind) else nil + local count = if ind then ind.count else n + if ind and buffer.len(ind.data) < ind.count * (Types.COMPONENT_SIZE[ind.type] or 4) then + return nil, Err.new(Err.ARG, "indices data is smaller than its count") + end + local function at(i: number): number + return if I then I(i, 0) else i + end + for i = 0, count - 1 do + if at(i) >= n then + return nil, Err.new(Err.ARG, "index out of range") + end + end + local mirror = not ident and (m[1] * (m[6] * m[11] - m[10] * m[7]) - m[5] * (m[2] * m[11] - m[10] * m[3]) + m[9] * (m[2] * m[7] - m[6] * m[3])) < 0 + local function face(list: { number }) + local parts = table.create(#list + 1) + parts[1] = "f" + if mirror then + for k = #list, 1, -1 do + table.insert(parts, ref(list[k])) + end + else + for k = 1, #list do + table.insert(parts, ref(list[k])) + end + end + table.insert(out, table.concat(parts, " ")) + end + local mode = prim.mode or "triangles" + if mode == "triangles" then + for t = 0, count // 3 - 1 do + face({ at(t * 3), at(t * 3 + 1), at(t * 3 + 2) }) + end + elseif mode == "polygons" then + local F = if prim.faces then Types.Scene.reader(prim.faces) else nil + if not F or not prim.faces then + return nil, Err.new(Err.ARG, "polygons without faces") + end + local o = 0 + for f = 0, prim.faces.count - 1 do + local k = F(f, 0) + if o + k > count then + return nil, Err.new(Err.ARG, "faces run past the indices") + end + local list = table.create(k) + for j = 0, k - 1 do + list[j + 1] = at(o + j) + end + if k >= 3 then + face(list) + end + o += k + end + elseif mode == "triangle_strip" or mode == "triangle_fan" then + for t = 0, count - 3 do + local a, b, c = at(t), at(t + 1), at(t + 2) + if mode == "triangle_fan" then + a = at(0) + elseif t % 2 == 1 then + a, b = b, a + end + face({ a, b, c }) + end + elseif mode == "lines" then + for s = 0, count // 2 - 1 do + table.insert(out, "l " .. ref(at(s * 2)) .. " " .. ref(at(s * 2 + 1))) + end + elseif mode == "line_strip" or mode == "line_loop" then + local parts = { "l" } + for i = 0, count - 1 do + table.insert(parts, ref(at(i))) + end + if mode == "line_loop" and count > 0 then + table.insert(parts, ref(at(0))) + end + table.insert(out, table.concat(parts, " ")) + elseif mode == "points" then + for i = 0, count - 1 do + table.insert(out, "p " .. ref(at(i))) + end + end + nv += n + if T then + nt += n + end + if Nr then + nn += n + end + end + table.insert(out, "") + return buffer.fromstring(table.concat(out, "\n")), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- encodeMtl(scene, opts?) -> the .mtl text for the scene's materials (what encode puts in opts.files) +function Obj.encodeMtl(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(scene) ~= "table" or type(scene.materials) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + local files = {} + local o: any = table.clone(opts or {}) + o.files = files + o.mtlName = "x.mtl" + local _, err = Obj.encode(scene, o) + if err then + return nil, err + end + local text = files["x.mtl"] + return buffer.fromstring(text or ""), nil +end + +return Obj diff --git a/src/Formats/model/off/init.luau b/src/Formats/model/off/init.luau new file mode 100644 index 0000000..92b4107 --- /dev/null +++ b/src/Formats/model/off/init.luau @@ -0,0 +1,480 @@ +--!strict +-- model/off: OFF (Geomview Object File Format), text, read + write. Written from the Geomview OFF description +-- (geomview.org/docs/html/OFF.html). +-- Decode: the header keyword [ST][C][N]OFF (texture coordinates, vertex colours, normals; the counts may follow on the +-- same line), `nv nf [ne]`, vertex lines `x y z [nx ny nz] [r g b [a]] [s t]`, face lines `n i1 .. in [colour]`; +-- `#` comments and blank lines anywhere. Vertices: POSITION f32 x3, NORMAL f32 x3, TEXCOORD_0 f32 x2, COLOR_0: unorm8 +-- x4 when the colours are integers (0..255) and some value is above 1, else f32 x4 (alpha full when only RGB is given). +-- Faces: triangles as u32 indices; n-gons fan-triangulated (opts.triangulate, default true: right for convex faces; +-- faces of fewer than 3 vertices are dropped, prim.extras.faceOfTriangle maps triangles to file faces when there are +-- face colours) or kept as mode "polygons" (prim.faces). Face colours (3 or 4 values after the indices; integers or +-- floats as for vertices; faces without one get opaque white): prim.extras.faceColors, one per file face. A single +-- value after the indices (a colormap index) is ignored (meta.source.colormap = true). No faces: mode "points". +-- meta.source = { format, keyword, vertices, faces, edges }. +-- Encode: every primitive in world space (node transforms applied) into one vertex list, NOFF / COFF / STOFF prefixes +-- for NORMAL / COLOR_0 / TEXCOORD_0 (unorm8 colours as integers 0..255, other colour types as floats 0..1), n-gons +-- natively, face colours from prim.extras.faceColors (a single primitive), point clouds with 0 faces; lines are +-- skipped. Floats print as %.9g (f32-exact). Not supported: 4OFF / nOFF (homogeneous / n-dimensional) and binary OFF +-- (UNSUPPORTED). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Flatten = require("@formats/codecs/MeshFlatten") + +-- ------------------------------------------------------------------------------------------------ contract +local Off = { + name = "off", + category = "model", + 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 }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + triangulate: boolean?, -- fan-triangulate n-gons (default true); false keeps them as mode "polygons" + maxVertices: number?, -- default 2^24 + maxFaces: number?, -- default 2^25 +} +export type EncodeOptions = { + colors: boolean?, -- write COLOR_0 (COFF) and prim.extras.faceColors when present (default true) + normals: boolean?, -- write NORMAL (NOFF) when present (default true) + texcoords: boolean?, -- write TEXCOORD_0 (STOFF) when present (default true) + comment: string?, -- a "# ..." line after the header keyword +} + +-- ------------------------------------------------------------------------------------------------ constants +local writef32, writeu8, writeu32 = buffer.writef32, buffer.writeu8, buffer.writeu32 + +-- ------------------------------------------------------------------------------------------------ sniff +function Off.sniff(r: Bytes.Reader): number + local head = r:peek(512) + for _ = 1, 16 do -- leading comment lines + local rest = string.match(head, "^%s*#[^\n]*\n(.*)$") + if not rest then + break + end + head = rest + end + local kw = string.match(head, "^%s*(%w+)") + if kw and string.match(kw, "^S?T?C?N?4?n?OFF$") then + return 0.9 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- colours: a list of numbers + whether a token looked like a float; decide unorm8 or f32 +type ColorSet = { values: { number }, float: boolean, max: number } + +local function colorType(c: ColorSet): string + return if not c.float and c.max > 1 then "unorm8" else "f32" +end + +-- the colour accessor for count entries of 4 values (nan = absent: opaque white) +local function colorAccessor(c: ColorSet, count: number): (Types.Accessor?, string?) + local t = colorType(c) + local buf = buffer.create(count * (if t == "unorm8" then 4 else 16)) + local vals = c.values + for i = 0, count * 4 - 1 do + local v = vals[i + 1] + if t == "unorm8" then + if v ~= v then + v = 255 + elseif v < 0 or v > 255 or v % 1 ~= 0 then + return nil, "colour value out of range" + end + writeu8(buf, i, v) + else + writef32(buf, i * 4, if v ~= v then 1 else v) + end + end + return Types.Scene.accessor(buf, t, 4, count), nil +end + +local function addColor(c: ColorSet, toks: { string }, from: number, n: number) + local vals = c.values + for k = 0, 3 do + if k < n then + local s = toks[from + k] + local v = tonumber(s) :: number + table.insert(vals, v) + if not c.float and string.find(s, "[%.eEnN]") then + c.float = true + end + if v > c.max then + c.max = v + end + else + table.insert(vals, 0 / 0) -- absent: full (opaque white) + end + end +end + +function Off.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local triangulate = true + if opts and opts.triangulate == false then + triangulate = false + end + local maxVertices = opts and opts.maxVertices or 2 ^ 24 + local maxFaces = opts and opts.maxFaces or 2 ^ 25 + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + -- the next non-empty line's tokens (comments stripped) + local at = 1 + local lineNo = 0 + local function line(): { string }? + while at <= #text do + local e = string.find(text, "\n", at, true) or (#text + 1) + local s = string.sub(text, at, e - 1) + at = e + 1 + lineNo += 1 + local hash = string.find(s, "#", 1, true) + if hash then + s = string.sub(s, 1, hash - 1) + end + local toks = {} + for w in string.gmatch(s, "%S+") do + table.insert(toks, w) + end + if #toks > 0 then + return toks + end + end + return nil + end + local head = line() + if not head then + return nil, Err.new(Err.TRUNCATED, "empty file") + end + local kw = head[1] + local rest = kw + local st, hasC, hasN = false, false, false + if string.sub(rest, 1, 2) == "ST" then + st, rest = true, string.sub(rest, 3) + end + if string.sub(rest, 1, 1) == "C" then + hasC, rest = true, string.sub(rest, 2) + end + if string.sub(rest, 1, 1) == "N" then + hasN, rest = true, string.sub(rest, 2) + end + if rest == "4OFF" or rest == "nOFF" or rest == "4nOFF" then + return nil, Err.new(Err.UNSUPPORTED, kw .. " (homogeneous / n-dimensional vertices)") + elseif rest ~= "OFF" then + return nil, Err.new(Err.CORRUPT, "bad header keyword " .. string.sub(kw, 1, 20)) + end + local counts: { string } + if head[2] == "BINARY" then + return nil, Err.new(Err.UNSUPPORTED, "binary OFF") + elseif #head >= 3 then + counts = { head[2], head[3], head[4] } + else + local c = line() + if not c then + return nil, Err.new(Err.TRUNCATED, "no counts line") + end + counts = c + end + local nv, nf, ne = tonumber(counts[1]), tonumber(counts[2]), tonumber(counts[3] or "0") + if not nv or not nf or nv < 0 or nf < 0 or nv % 1 ~= 0 or nf % 1 ~= 0 then + return nil, Err.new(Err.CORRUPT, "bad counts line") + end + if nv > maxVertices then + return nil, Err.new(Err.LIMIT, string.format("%d vertices is over the %d vertex limit", nv, maxVertices)) + end + if nf > maxFaces then + return nil, Err.new(Err.LIMIT, string.format("%d faces is over the %d face limit", nf, maxFaces)) + end + -- every vertex / face line takes at least 6 / 2 bytes + if nv * 6 + nf * 2 > #text - at + 2 then + return nil, Err.new(Err.TRUNCATED, "fewer lines than the counts need") + end + local fixed = 3 + (if hasN then 3 else 0) + (if st then 2 else 0) + local pos = buffer.create(nv * 12) + local nrm = if hasN then buffer.create(nv * 12) else nil + local tex = if st then buffer.create(nv * 8) else nil + local vcol: ColorSet = { values = {}, float = false, max = 0 } + for i = 0, nv - 1 do + local t = line() + if not t then + return nil, Err.new(Err.TRUNCATED, string.format("vertex %d missing", i)) + end + local n = #t + local nc = 0 + if hasC then + nc = n - fixed + if nc ~= 3 and nc ~= 4 then + return nil, Err.new(Err.CORRUPT, string.format("vertex %d: expected %d values and an RGB / RGBA colour", i, fixed)) + end + elseif n < fixed then + return nil, Err.new(Err.CORRUPT, string.format("vertex %d: expected %d values", i, fixed)) + end + for k = 1, fixed + nc do + if tonumber(t[k]) == nil then + return nil, Err.new(Err.CORRUPT, string.format("vertex %d: bad number", i)) + end + end + writef32(pos, i * 12, tonumber(t[1]) :: number) + writef32(pos, i * 12 + 4, tonumber(t[2]) :: number) + writef32(pos, i * 12 + 8, tonumber(t[3]) :: number) + local k = 4 + if nrm then + writef32(nrm, i * 12, tonumber(t[4]) :: number) + writef32(nrm, i * 12 + 4, tonumber(t[5]) :: number) + writef32(nrm, i * 12 + 8, tonumber(t[6]) :: number) + k = 7 + end + if hasC then + addColor(vcol, t, k, nc) + k += nc + end + if tex then + writef32(tex, i * 8, tonumber(t[k]) :: number) + writef32(tex, i * 8 + 4, tonumber(t[k + 1]) :: number) + end + end + local sizes = buffer.create(nf * 4) + local corners: { number } = {} + local fcol: ColorSet = { values = {}, float = false, max = 0 } + local anyFaceColor, colormap = false, false + for f = 0, nf - 1 do + local t = line() + if not t then + return nil, Err.new(Err.TRUNCATED, string.format("face %d missing", f)) + end + local n = tonumber(t[1]) + if n == nil or n < 0 or n % 1 ~= 0 or #t < n + 1 then + return nil, Err.new(Err.CORRUPT, string.format("face %d: bad vertex count", f)) + end + writeu32(sizes, f * 4, n) + for k = 2, n + 1 do + local v = tonumber(t[k]) + if v == nil or v < 0 or v >= nv or v % 1 ~= 0 then + return nil, Err.new(Err.CORRUPT, string.format("face %d: vertex index out of range", f)) + end + table.insert(corners, v) + end + local nc = #t - n - 1 + if nc == 3 or nc == 4 then + for k = n + 2, #t do + if tonumber(t[k]) == nil then + return nil, Err.new(Err.CORRUPT, string.format("face %d: bad colour", f)) + end + end + addColor(fcol, t, n + 2, nc) + anyFaceColor = true + else + if nc == 1 then + colormap = true + end + addColor(fcol, t, 1, 0) + end + end + -- the primitive + local attrs: { [string]: Types.Accessor } = { POSITION = Types.Scene.accessor(pos, "f32", 3, nv) } + if nrm then + attrs.NORMAL = Types.Scene.accessor(nrm, "f32", 3, nv) + end + if hasC then + local acc, cerr = colorAccessor(vcol, nv) + if not acc then + return nil, Err.new(Err.CORRUPT, "vertex " .. tostring(cerr)) + end + attrs.COLOR_0 = acc + end + if tex then + attrs.TEXCOORD_0 = Types.Scene.accessor(tex, "f32", 2, nv) + end + local prim: Types.Primitive = { attributes = attrs, mode = "points" } + local extras: { [string]: any } = {} + if anyFaceColor then + local acc, cerr = colorAccessor(fcol, nf) + if not acc then + return nil, Err.new(Err.CORRUPT, "face " .. tostring(cerr)) + end + extras.faceColors = acc + end + if nf > 0 then + local total = #corners + local cbuf = buffer.create(total * 4) + for i = 1, total do + writeu32(cbuf, (i - 1) * 4, corners[i]) + end + local allTri = total == nf * 3 + if allTri then + for f = 0, nf - 1 do + if buffer.readu32(sizes, f * 4) ~= 3 then + allTri = false + break + end + end + end + if allTri then + prim.mode = "triangles" + prim.indices = Types.Scene.accessor(cbuf, "u32", 1, total) + elseif triangulate then + local tris: { number } = {} + local fot: { number } = {} + local p = 0 + for f = 0, nf - 1 do + local s = buffer.readu32(sizes, f * 4) + for k = 1, s - 2 do + table.insert(tris, corners[p + 1]) + table.insert(tris, corners[p + k + 1]) + table.insert(tris, corners[p + k + 2]) + table.insert(fot, f) + end + p += s + end + local ib = buffer.create(#tris * 4) + for i, v in tris do + writeu32(ib, (i - 1) * 4, v) + end + prim.mode = "triangles" + prim.indices = Types.Scene.accessor(ib, "u32", 1, #tris) + if anyFaceColor then + local fb = buffer.create(#fot * 4) + for i, v in fot do + writeu32(fb, (i - 1) * 4, v) + end + extras.faceOfTriangle = Types.Scene.accessor(fb, "u32", 1, #fot) + end + else + prim.mode = "polygons" + prim.indices = Types.Scene.accessor(cbuf, "u32", 1, total) + prim.faces = Types.Scene.accessor(sizes, "u32", 1, nf) + end + end + if next(extras) then + prim.extras = extras + end + local scene = Types.Scene.fromPrimitive(prim, nil) + scene.meta.source = { format = "off", keyword = kw, vertices = nv, faces = nf, edges = ne or 0, colormap = colormap or nil } + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local scratch = buffer.create(4) +local function fnum(v: number): string? + writef32(scratch, 0, v) + v = buffer.readf32(scratch, 0) + if v ~= v or v == math.huge or v == -math.huge then + return nil + end + return string.format("%.9g", v) +end + +-- a colour attribute's 4 components of entry i (0-based) as text +local function colorText(a: Flatten.Attr, vals: { number }, comps: number, i: number): string + local out = table.create(4) + for c = 1, 4 do + local v = if c <= comps then vals[i * comps + c] else nil + if a.raw and a.type == "unorm8" then + out[c] = string.format("%d", if v == nil then 255 else math.clamp(v, 0, 255)) + else + if v == nil then + v = 1 + elseif a.raw then + v = if a.type == "unorm16" then v / 65535 elseif a.type == "snorm8" then math.max(v / 127, -1) else math.max(v / 32767, -1) + end + out[c] = fnum(v :: number) or "0" + end + end + return table.concat(out, " ") +end + +function Off.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local wantC, wantN, wantT = o.colors ~= false, o.normals ~= false, o.texcoords ~= false + local m, merr = Flatten.merge(scene, function(name: string): boolean + return (name == "NORMAL" and wantN) or (name == "COLOR_0" and wantC) or (name == "TEXCOORD_0" and wantT) + end, { triangulate = false }) + if not m then + return nil, Err.new(Err.ARG, tostring(merr)) + end + local A = m.attrs + local P, N, C, T = A.POSITION, A.NORMAL, A.COLOR_0, A.TEXCOORD_0 + if T and T.raw then + return nil, Err.new(Err.ARG, "TEXCOORD_0 of a normalized integer type") + end + local nv = m.count + local sizes = m.sizes or {} + local nf = #sizes + local out = table.create(nv + nf + 3) + table.insert(out, (if T then "ST" else "") .. (if C then "C" else "") .. (if N then "N" else "") .. "OFF") + if o.comment then + table.insert(out, "# " .. string.gsub(o.comment, "[\r\n]", " ")) + end + table.insert(out, string.format("%d %d 0", nv, nf)) + local pv = P.values + for i = 0, nv - 1 do + local x, y, z = fnum(pv[i * 3 + 1]), fnum(pv[i * 3 + 2]), fnum(pv[i * 3 + 3]) + if not (x and y and z) then + return nil, Err.new(Err.ARG, "OFF cannot hold a non-finite coordinate") + end + local s = x .. " " .. y .. " " .. z + if N then + local nvv = N.values + s ..= " " .. (fnum(nvv[i * 3 + 1]) or "0") .. " " .. (fnum(nvv[i * 3 + 2]) or "0") .. " " .. (fnum(nvv[i * 3 + 3]) or "0") + end + if C then + s ..= " " .. colorText(C, C.values, C.components, i) + end + if T then + local tv, tc = T.values, T.components + s ..= " " .. (fnum(tv[i * tc + 1]) or "0") .. " " .. (fnum(if tc >= 2 then tv[i * tc + 2] else 0) or "0") + end + table.insert(out, s) + end + -- face colours of a single primitive (per file face, or through faceOfTriangle) + local fc: Flatten.Attr? = nil + local fcMap: { number }? = nil + if wantC and #m.parts == 1 and nf > 0 then + local ex = m.parts[1].prim.extras + local acc = type(ex) == "table" and ex.faceColors + if acc then + local raw = acc.type == "unorm8" or acc.type == "unorm16" or acc.type == "snorm8" or acc.type == "snorm16" + local vals = Flatten.numbers(acc, raw) + if vals then + local a: Flatten.Attr = { type = acc.type, components = acc.components, raw = raw, values = vals } + if acc.count == nf then + fc = a + elseif ex.faceOfTriangle then + local fot = Flatten.numbers(ex.faceOfTriangle, true) + if fot and #fot == nf then + fc, fcMap = a, fot + for _, f in fot do + if f < 0 or f >= acc.count then + fc = nil + break + end + end + end + end + end + end + end + local corners = m.corners + local p = 0 + for f = 1, nf do + local s = sizes[f] + local line = table.create(s + 2) + line[1] = string.format("%d", s) + for k = 1, s do + line[k + 1] = string.format("%d", corners[p + k]) + end + p += s + if fc then + local src = if fcMap then fcMap[f] else f - 1 + table.insert(line, colorText(fc, fc.values, fc.components, src)) + end + table.insert(out, table.concat(line, " ")) + end + table.insert(out, "") + return buffer.fromstring(table.concat(out, "\n")), nil +end + +return Off diff --git a/src/Formats/model/ply/Binary.luau b/src/Formats/model/ply/Binary.luau new file mode 100644 index 0000000..5bfdf92 --- /dev/null +++ b/src/Formats/model/ply/Binary.luau @@ -0,0 +1,212 @@ +--!strict +--!native +--!optimize 2 +-- model/ply/Binary: PLY element data loops. Value read / write by type code (1 i8, 2 u8, 3 i16, 4 u16, 5 i32, 6 u32, +-- 7 f32, 8 f64) in either byte order, the column copy of fixed-size rows (scalar properties only) and the row walk of +-- rows with lists (a scan for the list totals, then the fill). The caller (init) sizes every destination from the +-- header counts and the scan, and checks the rows fit in the data first, so every index here is in range; a bad list +-- count or an out-of-range vertex index returns false / -1 with a message. Nothing here throws. +local readu8, readi8, readu16, readi16, readu32, readi32 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readi32 +local readf32, readf64 = buffer.readf32, buffer.readf64 +local writeu8, writei8, writeu16, writei16, writeu32, writei32 = buffer.writeu8, buffer.writei8, buffer.writeu16, buffer.writei16, buffer.writeu32, buffer.writei32 +local writef32, writef64 = buffer.writef32, buffer.writef64 +local byteswap, band, rshift = bit32.byteswap, bit32.band, bit32.rshift + +local Binary = {} + +Binary.SIZE = { 1, 1, 2, 2, 4, 4, 4, 8 } +local SIZE = Binary.SIZE +local scratch = buffer.create(8) + +local function swap16(v: number): number + return rshift(v, 8) + band(v, 255) * 256 +end + +-- rd(b, q, code, be) -> the value at q +local function rd(b: buffer, q: number, code: number, be: boolean): number + if not be then + if code == 7 then + return readf32(b, q) + elseif code == 2 then + return readu8(b, q) + elseif code == 5 then + return readi32(b, q) + elseif code == 6 then + return readu32(b, q) + elseif code == 8 then + return readf64(b, q) + elseif code == 1 then + return readi8(b, q) + elseif code == 3 then + return readi16(b, q) + end + return readu16(b, q) + end + if code <= 2 then + return if code == 1 then readi8(b, q) else readu8(b, q) + elseif code <= 4 then + local v = swap16(readu16(b, q)) + return if code == 3 and v >= 32768 then v - 65536 else v + elseif code <= 7 then + local v = byteswap(readu32(b, q)) + if code == 6 then + return v + elseif code == 5 then + return if v >= 2147483648 then v - 4294967296 else v + end + writeu32(scratch, 0, v) + return readf32(scratch, 0) + end + writeu32(scratch, 0, byteswap(readu32(b, q + 4))) + writeu32(scratch, 4, byteswap(readu32(b, q))) + return readf64(scratch, 0) +end +Binary.rd = rd + +-- wr(d, o, code, v): v as code, little endian +local function wr(d: buffer, o: number, code: number, v: number) + if code == 7 then + writef32(d, o, v) + elseif code == 6 then + writeu32(d, o, v) + elseif code == 5 then + writei32(d, o, v) + elseif code == 2 then + writeu8(d, o, v) + elseif code == 8 then + writef64(d, o, v) + elseif code == 1 then + writei8(d, o, v) + elseif code == 3 then + writei16(d, o, v) + else + writeu16(d, o, v) + end +end +Binary.wr = wr + +-- put(d, o, code, v, be): v as code in either byte order (the writer) +function Binary.put(d: buffer, o: number, code: number, v: number, be: boolean) + if not be or code <= 2 then + wr(d, o, code, v) + return + end + wr(scratch, 0, code, v) + if code <= 4 then + writeu16(d, o, swap16(readu16(scratch, 0))) + elseif code <= 7 then + writeu32(d, o, byteswap(readu32(scratch, 0))) + else + writeu32(d, o, byteswap(readu32(scratch, 4))) + writeu32(d, o + 4, byteswap(readu32(scratch, 0))) + end +end + +-- fixed(b, p, n, rowSize, np, srcOff, code, be, dst, dOff, dStride, dCode): column copies of n fixed-size rows at p +function Binary.fixed(b: buffer, p: number, n: number, rowSize: number, np: number, srcOff: { number }, code: { number }, be: boolean, dst: { buffer }, dOff: { number }, dStride: { number }, dCode: { number }) + for k = 1, np do + local sc, dc, d = code[k], dCode[k], dst[k] + local q0, o0, st = p + srcOff[k], dOff[k], dStride[k] + if sc == dc and not be then + local sz = SIZE[sc] + if sz == 4 then + for i = 0, n - 1 do + writeu32(d, o0 + i * st, readu32(b, q0 + i * rowSize)) + end + elseif sz == 1 then + for i = 0, n - 1 do + writeu8(d, o0 + i * st, readu8(b, q0 + i * rowSize)) + end + elseif sz == 2 then + for i = 0, n - 1 do + writeu16(d, o0 + i * st, readu16(b, q0 + i * rowSize)) + end + else + for i = 0, n - 1 do + writeu32(d, o0 + i * st, readu32(b, q0 + i * rowSize)) + writeu32(d, o0 + i * st + 4, readu32(b, q0 + i * rowSize + 4)) + end + end + else + for i = 0, n - 1 do + wr(d, o0 + i * st, dc, rd(b, q0 + i * rowSize, sc, be)) + end + end + end +end + +-- scan(b, p, limit, n, np, code, isList, countCode, be) -> the end offset and the item total of each list property, +-- or -1, message (truncated rows, a negative / fractional count) +function Binary.scan(b: buffer, p: number, limit: number, n: number, np: number, code: { number }, isList: { boolean }, countCode: { number }, be: boolean): (number, any) + local totals = table.create(np, 0) + local q = p + for _ = 1, n do + for k = 1, np do + if isList[k] then + local cc = countCode[k] + local csz = SIZE[cc] + if q + csz > limit then + return -1, "list runs past the end" + end + local c = rd(b, q, cc, be) + if c < 0 or c ~= c // 1 then + return -1, "bad list count" + end + q += csz + c * SIZE[code[k]] + if q > limit then + return -1, "list runs past the end" + end + totals[k] += c + else + q += SIZE[code[k]] + if q > limit then + return -1, "row runs past the end" + end + end + end + end + return q, totals +end + +-- rows(b, p, n, np, code, isList, countCode, be, dst, dOff, dStride, dCode, sizes, bound) -> true | false, message. +-- Scalars go to dst[k] at dOff + row * dStride as dCode; lists write their count to sizes[k] (u32 per row) and their +-- items one after the other into dst[k] as dCode; bound[k] >= 0 checks items are integers in 0 .. bound - 1. The rows +-- must have passed scan() with the same arguments. +function Binary.rows(b: buffer, p: number, n: number, np: number, code: { number }, isList: { boolean }, countCode: { number }, be: boolean, dst: { buffer }, dOff: { number }, dStride: { number }, dCode: { number }, sizes: { buffer }, bound: { number }): (boolean, string?) + local at = table.create(np, 0) + local q = p + for i = 0, n - 1 do + for k = 1, np do + local sc, dc, d = code[k], dCode[k], dst[k] + if isList[k] then + local cc = countCode[k] + local c = rd(b, q, cc, be) + q += SIZE[cc] + writeu32(sizes[k], i * 4, c) + local ia, ssz, dsz, bd = at[k], SIZE[sc], SIZE[dc], bound[k] + if bd >= 0 then + for j = 0, c - 1 do + local v = rd(b, q, sc, be) + q += ssz + if v < 0 or v >= bd or v ~= v // 1 then + return false, "vertex index out of range" + end + wr(d, (ia + j) * dsz, dc, v) + end + else + for j = 0, c - 1 do + wr(d, (ia + j) * dsz, dc, rd(b, q, sc, be)) + q += ssz + end + end + at[k] = ia + c + else + wr(d, dOff[k] + i * dStride[k], dc, rd(b, q, sc, be)) + q += SIZE[sc] + end + end + end + return true, nil +end + +return Binary diff --git a/src/Formats/model/ply/init.luau b/src/Formats/model/ply/init.luau new file mode 100644 index 0000000..8b9350e --- /dev/null +++ b/src/Formats/model/ply/init.luau @@ -0,0 +1,1148 @@ +--!strict +-- model/ply: PLY (Stanford polygon file format, Greg Turk 1994), ascii / binary_little_endian / binary_big_endian, +-- read + write. Written from the format description (paulbourke.net/dataformats/ply, the rply / plyfile behaviour). +-- Decode: the vertex element maps x y z -> POSITION f32 x3, nx ny nz -> NORMAL f32 x3, red green blue [alpha] -> +-- COLOR_0 (uchar: unorm8 x4, ushort: unorm16 x4, float / double: f32 x4; alpha full when absent), u v / s t / texture_u +-- texture_v / texture_s texture_t -> TEXCOORD_0 f32 x2, every other property -> "_" .. name in its own type (char -> +-- i8, uchar -> u8, ..., double -> f64). Doubles in x / y / z / normals / texcoords become f32. The face element's +-- vertex_indices / vertex_index list gives the faces: triangles stay triangles (u32 indices), n-gons are +-- fan-triangulated (opts.triangulate, default true: right for convex faces; faces of fewer than 3 vertices are +-- dropped) or kept as mode "polygons" (prim.faces = vertex count per face). No faces: a point cloud (mode "points", +-- no indices). Other face properties: prim.extras.faceAttributes[name] (one value per file face, its own type), face +-- lists: prim.extras.faceLists[name] = { countType, itemType, sizes (u32 accessor), items (accessor) }; after +-- triangulating n-gons prim.extras.faceOfTriangle (u32, 0-based) maps triangles to file faces. Other elements (edge, +-- material, ...) are kept raw in scene.meta.ply.elements (in their types) and written back, as are comments +-- (meta.ply.comments), obj_info lines (meta.ply.objInfo), the element order and the vertex / face property order and +-- types. meta.source = { format, encoding, vertices, faces }. +-- Encode: every primitive in world space (node transforms applied) into one vertex list: POSITION, NORMAL, COLOR_0, +-- TEXCOORD_0 and "_" attributes (under their name, in their type; several components: name_0, name_1, ...), faces +-- (triangles and polygons natively as `property list uchar int vertex_indices`, a wider count / uint index type when +-- needed), point clouds without a face element; lines are skipped. Floats print as %.9g (f32-exact), doubles %.17g. +-- Not supported: list properties in the vertex element (UNSUPPORTED). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Binary = require("@formats/model/ply/Binary") +local Flatten = require("@formats/codecs/MeshFlatten") + +-- ------------------------------------------------------------------------------------------------ contract +local Ply = { + name = "ply", + category = "model", + 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 }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + triangulate: boolean?, -- fan-triangulate n-gons (default true); false keeps them as mode "polygons" + maxVertices: number?, -- default 2^24 + maxFaces: number?, -- faces, and rows of any other element (default 2^25) +} +export type EncodeOptions = { + format: ("binary_little_endian" | "binary_big_endian" | "ascii")?, -- default "binary_little_endian" + comments: { string }?, -- extra comment lines (after those in scene.meta.ply.comments) +} + +type Prop = { name: string, ply: string, code: number, list: boolean, countPly: string?, countCode: number? } +type Elem = { name: string, count: number, props: { Prop } } + +-- ------------------------------------------------------------------------------------------------ constants +local CODES: { [string]: number } = { + char = 1, + int8 = 1, + uchar = 2, + uint8 = 2, + short = 3, + int16 = 3, + ushort = 4, + uint16 = 4, + int = 5, + int32 = 5, + uint = 6, + uint32 = 6, + float = 7, + float32 = 7, + double = 8, + float64 = 8, +} +local ACC_TYPE = { "i8", "u8", "i16", "u16", "i32", "u32", "f32", "f64" } +local PLY_NAME = { "char", "uchar", "short", "ushort", "int", "uint", "float", "double" } +local CODE_OF_ACC: { [string]: number } = { i8 = 1, u8 = 2, i16 = 3, u16 = 4, i32 = 5, u32 = 6, f32 = 7, f64 = 8, unorm8 = 2, unorm16 = 4, snorm8 = 1, snorm16 = 3 } +local RANGE = { { -128, 127 }, { 0, 255 }, { -32768, 32767 }, { 0, 65535 }, { -2147483648, 2147483647 }, { 0, 4294967295 } } +local SIZE = Binary.SIZE +local ENCODINGS = { ascii = true, binary_little_endian = true, binary_big_endian = true } +local MAX_HEADER = 1048576 +local TEXCOORD_PAIRS = { { "u", "v" }, { "s", "t" }, { "texture_u", "texture_v" }, { "texture_s", "texture_t" } } + +-- ------------------------------------------------------------------------------------------------ sniff +function Ply.sniff(r: Bytes.Reader): number + local h = r:peek(4) + return if h == "ply\n" or h == "ply\r" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Header = { encoding: string, elems: { Elem }, comments: { string }, objInfo: { string }, dataStart: number } + +local function parseHeader(r: Bytes.Reader): (Header?, Err.Err?) + local b, base, size = r.buf, r.base, r.limit - r.base + local text = buffer.readstring(b, base, math.min(size, MAX_HEADER)) + if string.sub(text, 1, 3) ~= "ply" or not string.match(string.sub(text, 4, 5), "^\r?\n") then + return nil, Err.new(Err.CORRUPT, "bad signature", base) + end + local h: Header = { encoding = "", elems = {}, comments = {}, objInfo = {}, dataStart = -1 } + local at = 1 + local first = true + while true do + local e = string.find(text, "\n", at, true) + if not e then + if size > MAX_HEADER then + return nil, Err.new(Err.LIMIT, "header longer than 1 MB") + end + return nil, Err.new(Err.TRUNCATED, "no end_header", base + at - 1) + end + local line = string.sub(text, at, e - 1) + if string.sub(line, -1) == "\r" then + line = string.sub(line, 1, -2) + end + local lineAt = base + at - 1 + at = e + 1 + local kw = string.match(line, "^%s*(%S+)") + if first then + first = false -- "ply" + elseif kw == nil then + -- blank line + elseif kw == "end_header" then + h.dataStart = base + at - 1 + break + elseif kw == "comment" or kw == "obj_info" then + local rest = string.match(line, "^%s*%S+ ?(.*)$") or "" + table.insert(if kw == "comment" then h.comments else h.objInfo, rest) + elseif kw == "format" then + local enc, ver = string.match(line, "^%s*format%s+(%S+)%s+(%S+)") + if not enc or not ENCODINGS[enc] then + return nil, Err.new(Err.UNSUPPORTED, "unknown format " .. tostring(enc), lineAt) + end + if string.sub(ver, 1, 1) ~= "1" then + return nil, Err.new(Err.UNSUPPORTED, "version " .. ver, lineAt) + end + h.encoding = enc + elseif kw == "element" then + local name, count = string.match(line, "^%s*element%s+(%S+)%s+(%d+)%s*$") + local n = tonumber(count) + if not name or not n then + return nil, Err.new(Err.CORRUPT, "bad element line", lineAt) + end + table.insert(h.elems, { name = name, count = n, props = {} }) + elseif kw == "property" then + local el = h.elems[#h.elems] + if not el then + return nil, Err.new(Err.CORRUPT, "property before any element", lineAt) + end + local words = {} + for w in string.gmatch(line, "%S+") do + table.insert(words, w) + end + local p: Prop + if words[2] == "list" and #words == 5 then + local cc, ic = CODES[words[3]], CODES[words[4]] + if not cc or not ic then + return nil, Err.new(Err.CORRUPT, "unknown property type in " .. line, lineAt) + end + p = { name = words[5], ply = words[4], code = ic, list = true, countPly = words[3], countCode = cc } + elseif #words == 3 and CODES[words[2]] then + p = { name = words[3], ply = words[2], code = CODES[words[2]], list = false } + else + return nil, Err.new(Err.CORRUPT, "bad property line: " .. string.sub(line, 1, 60), lineAt) + end + for _, q in el.props do + if q.name == p.name then + return nil, Err.new(Err.CORRUPT, "duplicate property " .. p.name, lineAt) + end + end + table.insert(el.props, p) + else + return nil, Err.new(Err.CORRUPT, "unknown header line: " .. string.sub(line, 1, 60), lineAt) + end + end + if h.encoding == "" then + return nil, Err.new(Err.CORRUPT, "no format line", base) + end + return h, nil +end + +-- the reading plan of one element: per property, where its values go +type Plan = { + code: { number }, + isList: { boolean }, + countCode: { number }, + dst: { buffer }, + dOff: { number }, + dStride: { number }, + dCode: { number }, + sizes: { buffer }, + bound: { number }, + totals: { number }, +} + +local function newPlan(e: Elem): Plan + local np = #e.props + local pl: Plan = { + code = table.create(np, 0), + isList = table.create(np, false), + countCode = table.create(np, 2), + dst = table.create(np), + dOff = table.create(np, 0), + dStride = table.create(np, 0), + dCode = table.create(np, 0), + sizes = table.create(np), + bound = table.create(np, -1), + totals = table.create(np, 0), + } + for k, p in e.props do + pl.code[k] = p.code + pl.isList[k] = p.list + pl.countCode[k] = p.countCode or 2 + pl.dCode[k] = p.code + pl.dStride[k] = SIZE[p.code] + end + return pl +end + +-- unset scalar destinations get their own native buffer +local function ownBuffers(e: Elem, pl: Plan) + for k, p in e.props do + if not p.list and pl.dst[k] == nil then + pl.dst[k] = buffer.create(e.count * SIZE[p.code]) + end + end +end + +-- read one element's rows (binary) into the plan; returns the next offset or nil, Err +local function readBinary(r: Bytes.Reader, p: number, e: Elem, pl: Plan, be: boolean): (number?, Err.Err?) + local b, limit, n, np = r.buf, r.limit, e.count, #e.props + local hasList, rowSize = false, 0 + for k, pr in e.props do + if pr.list then + hasList = true + rowSize += SIZE[pr.countCode :: number] + else + rowSize += SIZE[pr.code] + end + end + if n * rowSize > limit - p then + return nil, Err.new(Err.TRUNCATED, string.format("element %s: %d rows need at least %d bytes", e.name, n, n * rowSize), p) + end + if not hasList then + ownBuffers(e, pl) + local srcOff = table.create(np, 0) + local o = 0 + for k, pr in e.props do + srcOff[k] = o + o += SIZE[pr.code] + end + Binary.fixed(b, p, n, rowSize, np, srcOff, pl.code, be, pl.dst, pl.dOff, pl.dStride, pl.dCode) + return p + n * rowSize, nil + end + local q, totals = Binary.scan(b, p, limit, n, np, pl.code, pl.isList, pl.countCode, be) + if q < 0 then + return nil, Err.new(if totals == "bad list count" then Err.CORRUPT else Err.TRUNCATED, "element " .. e.name .. ": " .. tostring(totals), p) + end + ownBuffers(e, pl) + for k, pr in e.props do + if pr.list then + pl.totals[k] = totals[k] + pl.sizes[k] = buffer.create(n * 4) + pl.dst[k] = buffer.create(totals[k] * SIZE[pl.dCode[k]]) + end + end + local ok, msg = Binary.rows(b, p, n, np, pl.code, pl.isList, pl.countCode, be, pl.dst, pl.dOff, pl.dStride, pl.dCode, pl.sizes, pl.bound) + if not ok then + return nil, Err.new(Err.CORRUPT, "element " .. e.name .. ": " .. tostring(msg), p) + end + return q, nil +end + +-- a token as a value of type code, or nil +local function value(tok: string?, code: number): number? + if tok == nil then + return nil + end + local v = tonumber(tok) + if v == nil then + return nil + end + local rg = RANGE[code] + if rg and (v ~= v // 1 or v < rg[1] or v > rg[2]) then + return nil + end + return v +end + +-- read one element's rows (ascii) from the token stream +local function readAscii(nextTok: () -> string?, e: Elem, pl: Plan): Err.Err? + ownBuffers(e, pl) + local n = e.count + local listSizes: { [number]: { number } } = {} + local listItems: { [number]: { number } } = {} + for k, p in e.props do + if p.list then + listSizes[k] = table.create(n) + listItems[k] = {} + end + end + local wr = Binary.wr + for i = 0, n - 1 do + for k, p in e.props do + if p.list then + local t = nextTok() + local c = value(t, p.countCode :: number) + if c == nil or c < 0 or c % 1 ~= 0 then + return Err.new(if t == nil then Err.TRUNCATED else Err.CORRUPT, string.format("element %s row %d: bad list count", e.name, i)) + end + listSizes[k][i + 1] = c + local items, bd, code = listItems[k], pl.bound[k], p.code + for _ = 1, c do + local t2 = nextTok() + local v = value(t2, code) + if v == nil then + return Err.new(if t2 == nil then Err.TRUNCATED else Err.CORRUPT, string.format("element %s row %d: bad value", e.name, i)) + end + if bd >= 0 and (v < 0 or v >= bd or v ~= v // 1) then + return Err.new(Err.CORRUPT, string.format("element %s row %d: vertex index out of range", e.name, i)) + end + table.insert(items, v) + end + else + local t = nextTok() + local v = value(t, p.code) + if v == nil then + return Err.new(if t == nil then Err.TRUNCATED else Err.CORRUPT, string.format("element %s row %d: bad %s value", e.name, i, p.name)) + end + wr(pl.dst[k], pl.dOff[k] + i * pl.dStride[k], pl.dCode[k], v) + end + end + end + for k in listSizes do + local sz, items = listSizes[k], listItems[k] + local s = buffer.create(n * 4) + for i = 1, n do + buffer.writeu32(s, (i - 1) * 4, sz[i]) + end + local dc = pl.dCode[k] + local d = buffer.create(#items * SIZE[dc]) + for j = 1, #items do + wr(d, (j - 1) * SIZE[dc], dc, items[j]) + end + pl.sizes[k], pl.dst[k], pl.totals[k] = s, d, #items + end + return nil +end + +local function propIndex(e: Elem, name: string): number? + for k, p in e.props do + if p.name == name then + return k + end + end + return nil +end + +-- vertex element -> attributes: sets the plan's destinations, returns the attribute table +local function planVertex(e: Elem, pl: Plan): ({ [string]: Types.Accessor }?, Err.Err?) + local nv = e.count + local attrs: { [string]: Types.Accessor } = {} + local taken: { [number]: boolean } = {} + for _, p in e.props do + if p.list then + return nil, Err.new(Err.UNSUPPORTED, "list property " .. p.name .. " in the vertex element") + end + end + -- group(attr, names, required, ok, comps, fill): the first `required` names must exist, the others are optional + local function group(attr: string, names: { string }, required: number, ok: (codes: { number }) -> number?, comps: number, fillValue: number?) + local ks: { [number]: number } = {} + local codes = {} + for i, nm in names do + local k = propIndex(e, nm) + if k == nil then + if i <= required then + return + end + else + ks[i] = k + table.insert(codes, e.props[k].code) + end + end + local dc = ok(codes) + if dc == nil then + return + end + local sz = SIZE[dc] + local buf = buffer.create(nv * comps * sz) + if fillValue then + for i = 0, nv - 1 do + Binary.wr(buf, (i * comps + comps - 1) * sz, dc, fillValue) + end + end + for i, k in ks do + pl.dst[k], pl.dOff[k], pl.dStride[k], pl.dCode[k] = buf, (i - 1) * sz, comps * sz, dc + taken[k] = true + end + local accType = if attr == "COLOR_0" and dc == 2 then "unorm8" elseif attr == "COLOR_0" and dc == 4 then "unorm16" else ACC_TYPE[dc] + attrs[attr] = Types.Scene.accessor(buf, accType, comps, nv) + end + local function floats(codes: { number }): number? + for _, c in codes do + if c ~= 7 and c ~= 8 then + return nil + end + end + return 7 + end + local function anyNumber(_codes: { number }): number? + return 7 + end + group("POSITION", { "x", "y", "z" }, 3, anyNumber, 3, nil) + group("NORMAL", { "nx", "ny", "nz" }, 3, floats, 3, nil) + -- colours: one type class for all channels + do + local rk, gk, bk, ak = propIndex(e, "red"), propIndex(e, "green"), propIndex(e, "blue"), propIndex(e, "alpha") + if rk and gk and bk then + local codes = { e.props[rk].code, e.props[gk].code, e.props[bk].code } + if ak then + table.insert(codes, e.props[ak].code) + end + local cls: number? = codes[1] + for _, c in codes do + local a = if c == 8 then 7 else c + local b0 = if cls == 8 then 7 else cls + if a ~= b0 then + cls = nil + end + end + local dc = if cls == 2 then 2 elseif cls == 4 then 4 elseif cls == 7 or cls == 8 then 7 else nil + if dc then + group("COLOR_0", { "red", "green", "blue", "alpha" }, 3, function() + return dc + end, 4, if dc == 2 then 255 elseif dc == 4 then 65535 else 1) + end + end + end + for _, pair in TEXCOORD_PAIRS do + if attrs.TEXCOORD_0 == nil then + group("TEXCOORD_0", pair, 2, floats, 2, nil) + end + end + for k, p in e.props do + if not taken[k] then + local buf = buffer.create(nv * SIZE[p.code]) + pl.dst[k] = buf + attrs["_" .. p.name] = Types.Scene.accessor(buf, ACC_TYPE[p.code], 1, nv) + end + end + return attrs, nil +end + +-- the fan triangulation of faces with sizes / corners; returns indices (u32), triangle count, faceOfTriangle +local function fan(sizes: buffer, corners: buffer, nf: number): (buffer, number, buffer) + local nt = 0 + for f = 0, nf - 1 do + local s = buffer.readu32(sizes, f * 4) + if s >= 3 then + nt += s - 2 + end + end + local idx, fot = buffer.create(nt * 12), buffer.create(nt * 4) + local p, t = 0, 0 + local readu32, writeu32 = buffer.readu32, buffer.writeu32 + for f = 0, nf - 1 do + local s = readu32(sizes, f * 4) + local a = readu32(corners, p * 4) + for k = 1, s - 2 do + writeu32(idx, t * 12, a) + writeu32(idx, t * 12 + 4, readu32(corners, (p + k) * 4)) + writeu32(idx, t * 12 + 8, readu32(corners, (p + k + 1) * 4)) + writeu32(fot, t * 4, f) + t += 1 + end + p += s + end + return idx, nt, fot +end + +function Ply.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local triangulate = true + if opts and opts.triangulate == false then + triangulate = false + end + local maxVertices = opts and opts.maxVertices or 2 ^ 24 + local maxFaces = opts and opts.maxFaces or 2 ^ 25 + local h, herr = parseHeader(r) + if not h then + return nil, herr + end + local vi, fi, idxK + for i, e in h.elems do + if e.name == "vertex" and vi == nil then + vi = i + if e.count > maxVertices then + return nil, Err.new(Err.LIMIT, string.format("%d vertices is over the %d vertex limit", e.count, maxVertices)) + end + elseif e.name == "face" and fi == nil then + local k = propIndex(e, "vertex_indices") or propIndex(e, "vertex_index") + if k and e.props[k].list then + fi, idxK = i, k + end + end + if e.count > maxFaces then + return nil, Err.new(Err.LIMIT, string.format("element %s: %d rows is over the %d limit", e.name, e.count, maxFaces)) + end + end + if vi == nil then + return nil, Err.new(Err.CORRUPT, "no vertex element") + end + local nv = h.elems[vi].count + local be = h.encoding == "binary_big_endian" + local ascii = h.encoding == "ascii" + local nextTok: () -> string? = function() + return nil + end + if ascii then + local body = buffer.readstring(r.buf, h.dataStart, r.limit - h.dataStart) + -- each value takes at least 2 bytes (a digit and a separator): bound the counts before allocating + local need = 0 + for _, e in h.elems do + need += e.count * #e.props + end + if need > (#body + 1) // 2 then + return nil, Err.new(Err.TRUNCATED, "fewer values than the element counts need", h.dataStart) + end + nextTok = string.gmatch(body, "%S+") :: any + end + local plans: { Plan } = {} + local attrs: { [string]: Types.Accessor } = {} + local p = h.dataStart + if not ascii then + -- every row takes at least its scalar sizes and list counts: bound the counts before allocating + local need = 0 + for _, e in h.elems do + local row = 0 + for _, pr in e.props do + row += SIZE[if pr.list then pr.countCode :: number else pr.code] + end + need += e.count * row + end + if need > r.limit - h.dataStart then + return nil, Err.new(Err.TRUNCATED, string.format("the elements need at least %d bytes, %d left", need, r.limit - h.dataStart), h.dataStart) + end + end + for i, e in h.elems do + local pl = newPlan(e) + plans[i] = pl + if i == vi then + local a, aerr = planVertex(e, pl) + if not a then + return nil, aerr + end + attrs = a + elseif i == fi then + pl.dCode[idxK] = 6 + pl.bound[idxK] = nv + end + if ascii then + local err = readAscii(nextTok, e, pl) + if err then + return nil, err + end + else + local q, err = readBinary(r, p, e, pl, be) + if not q then + return nil, err + end + p = q + end + end + -- the primitive + local prim: Types.Primitive = { attributes = attrs, mode = "points" } + local nf = 0 + local extras: { [string]: any } = {} + local faceProps: { any } = {} + if fi then + local e, pl = h.elems[fi], plans[fi] + nf = e.count + local sizes, corners, total = pl.sizes[idxK], pl.dst[idxK], pl.totals[idxK] + local faceAttributes: { [string]: Types.Accessor } = {} + local faceLists: { [string]: any } = {} + local anyExtra = false + for k, pr in e.props do + table.insert(faceProps, { name = pr.name, type = pr.ply, countType = pr.countPly }) + if k ~= idxK then + anyExtra = true + if pr.list then + faceLists[pr.name] = { + countType = pr.countPly, + itemType = pr.ply, + sizes = Types.Scene.accessor(pl.sizes[k], "u32", 1, nf), + items = Types.Scene.accessor(pl.dst[k], ACC_TYPE[pr.code], 1, pl.totals[k]), + } + else + faceAttributes[pr.name] = Types.Scene.accessor(pl.dst[k], ACC_TYPE[pr.code], 1, nf) + end + end + end + if next(faceAttributes) then + extras.faceAttributes = faceAttributes + end + if next(faceLists) then + extras.faceLists = faceLists + end + if nf > 0 then + local allTri = total == nf * 3 + if allTri then + for f = 0, nf - 1 do + if buffer.readu32(sizes, f * 4) ~= 3 then + allTri = false + break + end + end + end + if allTri then + prim.mode = "triangles" + prim.indices = Types.Scene.accessor(corners, "u32", 1, total) + elseif triangulate then + local idx, nt, fot = fan(sizes, corners, nf) + prim.mode = "triangles" + prim.indices = Types.Scene.accessor(idx, "u32", 1, nt * 3) + if anyExtra then + extras.faceOfTriangle = Types.Scene.accessor(fot, "u32", 1, nt) + end + else + prim.mode = "polygons" + prim.indices = Types.Scene.accessor(corners, "u32", 1, total) + prim.faces = Types.Scene.accessor(sizes, "u32", 1, nf) + end + end + end + if next(extras) then + prim.extras = extras + end + -- raw elements, element order, property order + local elements: { any } = {} + local order: { string } = {} + for i, e in h.elems do + table.insert(order, e.name) + if i ~= vi and i ~= fi then + local pl = plans[i] + local props = {} + for k, pr in e.props do + props[k] = { name = pr.name, type = pr.ply, countType = pr.countPly, values = pl.dst[k], sizes = pl.sizes[k], total = if pr.list then pl.totals[k] else nil } + end + table.insert(elements, { name = e.name, count = e.count, properties = props }) + end + end + local vprops = {} + for _, pr in h.elems[vi].props do + table.insert(vprops, { name = pr.name, type = pr.ply }) + end + local scene = Types.Scene.fromPrimitive(prim, nil) + scene.meta.source = { format = "ply", encoding = h.encoding, vertices = nv, faces = nf } + scene.meta.ply = { + comments = h.comments, + objInfo = h.objInfo, + elements = elements, + order = order, + vertexProperties = vprops, + faceProperties = if fi then faceProps else nil, + } + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- a column to write: ply type code + spelling, the values (one per row, or per row * stride at offset) +type Column = { name: string, ply: string, code: number, values: { number }, stride: number, offset: number } +type ListColumn = { name: string, ply: string, code: number, countPly: string, countCode: number, sizes: { number }, items: { number } } + +local function keep(name: string): boolean + return name == "NORMAL" or name == "COLOR_0" or name == "TEXCOORD_0" or string.sub(name, 1, 1) == "_" +end + +-- the spelling `want` from the source file when it means the same type as code, else the classic name +local function spell(want: string?, code: number): string + if want and CODES[want] == code then + return want + end + return PLY_NAME[code] +end + +local function toInt(v: number, code: number): number + local rg = RANGE[code] + if rg then + if v ~= v then + return 0 + end + return math.clamp(math.floor(v + 0.5), rg[1], rg[2]) + end + return v +end + +-- write rows of columns (+ list columns, in `order`) for n rows: ascii lines into out, binary into the writer +type Row = { kind: "s", col: Column } | { kind: "l", col: ListColumn } + +local function rowsAscii(out: { string }, n: number, cols: { Row }) + local fmt = string.format + local function num(code: number, v: number): string + if code == 7 then + return fmt("%.9g", v) + elseif code == 8 then + return fmt("%.17g", v) + end + return fmt("%d", toInt(v, code)) + end + local at: { [number]: number } = {} + for i = 0, n - 1 do + local parts = {} + for k, c in cols do + if c.kind == "s" then + local col = c.col :: Column + table.insert(parts, num(col.code, col.values[i * col.stride + col.offset + 1])) + else + local col = c.col :: ListColumn + local s = col.sizes[i + 1] + table.insert(parts, fmt("%d", s)) + local a = at[k] or 0 + for j = 1, s do + table.insert(parts, num(col.code, col.items[a + j])) + end + at[k] = a + s + end + end + table.insert(out, table.concat(parts, " ")) + end +end + +local function rowsBinary(w: Bytes.Writer, n: number, cols: { Row }, be: boolean) + local size = 0 + for _, c in cols do + if c.kind == "s" then + size += n * SIZE[(c.col :: Column).code] + else + local col = c.col :: ListColumn + size += n * SIZE[col.countCode] + #col.items * SIZE[col.code] + end + end + local o = w:reserve(size) + local d = w.buf + local put = Binary.put + local at: { [number]: number } = {} + for i = 0, n - 1 do + for k, c in cols do + if c.kind == "s" then + local col = c.col :: Column + local code = col.code + put(d, o, code, toInt(col.values[i * col.stride + col.offset + 1], code), be) + o += SIZE[code] + else + local col = c.col :: ListColumn + local s = col.sizes[i + 1] + put(d, o, col.countCode, s, be) + o += SIZE[col.countCode] + local a, code = at[k] or 0, col.code + for j = 1, s do + put(d, o, code, toInt(col.items[a + j], code), be) + o += SIZE[code] + end + at[k] = a + s + end + end + end + w.pos = o +end + +-- numbers of a raw element column (buffer of a ply type) +local function bufNumbers(b: any, code: number, count: number): { number }? + if type(b) ~= "buffer" or buffer.len(b) < count * SIZE[code] then + return nil + end + local out = table.create(count) + for i = 0, count - 1 do + out[i + 1] = Binary.rd(b, i * SIZE[code], code, false) + end + return out +end + +-- the list count type for a maximum count +local function countCodeFor(maxCount: number): number + return if maxCount <= 255 then 2 elseif maxCount <= 65535 then 4 else 6 +end + +function Ply.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local enc = o.format or "binary_little_endian" + if not ENCODINGS[enc] then + return nil, Err.new(Err.ARG, "format must be ascii, binary_little_endian or binary_big_endian") + end + local m, merr = Flatten.merge(scene, keep, { triangulate = false }) + if not m then + return nil, Err.new(Err.ARG, tostring(merr)) + end + local meta: any = if type(scene) == "table" and type(scene.meta) == "table" and type(scene.meta.ply) == "table" then scene.meta.ply else {} + local nv = m.count + -- source property spellings / order + local srcType: { [string]: string } = {} + local srcOrder: { [string]: number } = {} + if type(meta.vertexProperties) == "table" then + for i, vp in meta.vertexProperties do + if type(vp) == "table" and type(vp.name) == "string" then + srcType[vp.name] = vp.type + srcOrder[vp.name] = i + end + end + end + local cols: { Column } = {} + local function add(name: string, code: number, a: Flatten.Attr, comp: number) + table.insert(cols, { name = name, ply = spell(srcType[name], code), code = code, values = a.values, stride = a.components, offset = comp }) + end + local function floatCode(name: string): number + return if CODES[srcType[name] or ""] == 8 then 8 else 7 + end + local A = m.attrs + for i, nm in { "x", "y", "z" } do + add(nm, floatCode(nm), A.POSITION, i - 1) + end + if A.NORMAL then + for i, nm in { "nx", "ny", "nz" } do + add(nm, floatCode(nm), A.NORMAL, i - 1) + end + end + local C = A.COLOR_0 + if C then + local code = if C.raw and C.type == "unorm8" then 2 elseif C.raw and C.type == "unorm16" then 4 else 7 + if C.raw and code == 7 then + -- another normalized type: as floats + local vals = table.create(#C.values) + local scale = if C.type == "snorm8" then 127 else 32767 + for i, v in C.values do + vals[i] = math.max(v / scale, -1) + end + C = { type = "f32", components = C.components, raw = false, values = vals } + end + local cc = C :: Flatten.Attr + for i, nm in { "red", "green", "blue" } do + if i <= cc.components then + add(nm, code, cc, i - 1) + end + end + if cc.components >= 4 then + local full = if code == 2 then 255 elseif code == 4 then 65535 else 1 + local need = srcOrder.alpha ~= nil + if not need then + for i = 0, nv - 1 do + if cc.values[i * cc.components + 4] ~= full then + need = true + break + end + end + end + if need then + add("alpha", code, cc, 3) + end + end + end + if A.TEXCOORD_0 then + local names = { "s", "t" } + for _, pair in TEXCOORD_PAIRS do + if srcOrder[pair[1]] and srcOrder[pair[2]] then + names = pair + break + end + end + local tc = A.TEXCOORD_0 + if tc.raw then + return nil, Err.new(Err.ARG, "TEXCOORD_0 of a normalized integer type") + end + add(names[1], floatCode(names[1]), tc, 0) + if tc.components >= 2 then + add(names[2], floatCode(names[2]), tc, 1) + end + end + local customs = {} + for name in A do + if string.sub(name, 1, 1) == "_" then + table.insert(customs, name) + end + end + table.sort(customs) + for _, name in customs do + local a = A[name] + local code = CODE_OF_ACC[a.type] or 7 + local base = string.sub(name, 2) + if a.components == 1 then + add(base, code, a, 0) + else + for c = 0, a.components - 1 do + add(base .. "_" .. c, code, a, c) + end + end + end + -- the source order first (stable for the rest) + local rank: { [Column]: number } = {} + for i, c in cols do + rank[c] = (srcOrder[c.name] or (1000000 + i)) + end + table.sort(cols, function(a: Column, b: Column): boolean + return rank[a] < rank[b] + end) + -- faces + local faceRows: { Row }? = nil + local nf = 0 + if m.sizes then + local sizes = m.sizes :: { number } + nf = #sizes + local maxS, maxI = 0, 0 + for _, s in sizes do + maxS = math.max(maxS, s) + end + for _, c in m.corners do + maxI = math.max(maxI, c) + end + local fprops: { any } = if type(meta.faceProperties) == "table" then meta.faceProperties else {} + local idxName, idxType, idxCount = "vertex_indices", nil, nil + for _, fp in fprops do + if type(fp) == "table" and (fp.name == "vertex_indices" or fp.name == "vertex_index") then + idxName, idxType, idxCount = fp.name, fp.type, fp.countType + end + end + local cc = countCodeFor(maxS) + local srcCC = CODES[idxCount or ""] + if srcCC and srcCC <= 6 and SIZE[srcCC] >= SIZE[cc] then + cc = srcCC + end + local ic = if maxI < 2147483648 then 5 else 6 + local srcIC = CODES[idxType or ""] + if srcIC == 6 or (srcIC and srcIC <= 6 and maxI <= RANGE[srcIC][2]) then + ic = srcIC + end + local rows: { Row } = { + { kind = "l", col = { name = idxName, ply = spell(idxType, ic), code = ic, countPly = spell(idxCount, cc), countCode = cc, sizes = sizes, items = m.corners } }, + } + -- per-face data of a single primitive + if #m.parts == 1 then + local ex = m.parts[1].prim.extras + local fot: { number }? = nil + if type(ex) == "table" and ex.faceOfTriangle then + fot = Flatten.numbers(ex.faceOfTriangle, true) + end + local function perFace(vals: { number }, count: number): { number }? + if count == nf then + return vals + elseif fot and #fot == nf then + local out = table.create(nf) + for i = 1, nf do + local v = vals[fot[i] + 1] + if v == nil then + return nil + end + out[i] = v + end + return out + end + return nil + end + local extraRows: { [string]: Row } = {} + if type(ex) == "table" and type(ex.faceAttributes) == "table" then + for name, acc in ex.faceAttributes do + local vals = Flatten.numbers(acc, true) + local code = CODE_OF_ACC[acc.type] + if vals and code and acc.components == 1 then + local pv = perFace(vals, acc.count) + if pv then + extraRows[name] = { kind = "s", col = { name = name, ply = PLY_NAME[code], code = code, values = pv, stride = 1, offset = 0 } } + end + end + end + end + if type(ex) == "table" and type(ex.faceLists) == "table" then + for name, fl in ex.faceLists do + local sz = type(fl) == "table" and Flatten.numbers(fl.sizes, true) + local items = type(fl) == "table" and Flatten.numbers(fl.items, true) + local code = type(fl) == "table" and (CODES[fl.itemType or ""] or CODE_OF_ACC[fl.items and fl.items.type or ""]) + if sz and items and code and #sz == nf and fot == nil then + local mx = 0 + for _, s in sz do + mx = math.max(mx, s) + end + local lcc = countCodeFor(mx) + local scc = CODES[fl.countType or ""] + if scc and scc <= 6 and SIZE[scc] >= SIZE[lcc] then + lcc = scc + end + extraRows[name] = { kind = "l", col = { name = name, ply = spell(fl.itemType, code), code = code, countPly = spell(fl.countType, lcc), countCode = lcc, sizes = sz, items = items } } + end + end + end + -- the source order, then the rest by name + local placed: { [string]: boolean } = { [idxName] = true } + local ordered: { Row } = {} + for _, fp in fprops do + if type(fp) == "table" then + if fp.name == idxName then + table.insert(ordered, rows[1]) + elseif extraRows[fp.name] then + table.insert(ordered, extraRows[fp.name]) + placed[fp.name] = true + end + end + end + if not table.find(ordered, rows[1]) then + table.insert(ordered, 1, rows[1]) + end + local rest = {} + for name in extraRows do + if not placed[name] then + table.insert(rest, name) + end + end + table.sort(rest) + for _, name in rest do + table.insert(ordered, extraRows[name]) + end + rows = ordered + end + faceRows = rows + end + -- raw elements + type Raw = { name: string, count: number, rows: { Row } } + local raws: { [string]: Raw } = {} + local rawOrder: { string } = {} + if type(meta.elements) == "table" then + for _, el in meta.elements do + if type(el) == "table" and type(el.name) == "string" and type(el.count) == "number" and type(el.properties) == "table" and el.name ~= "vertex" and not raws[el.name] then + if el.name == "face" and faceRows then + continue + end + local rows: { Row } = {} + for _, pr in el.properties do + local code = CODES[pr.type or ""] + if not code then + return nil, Err.new(Err.ARG, "element " .. el.name .. ": unknown property type") + end + if pr.countType then + local cc = CODES[pr.countType] + local sz = cc and bufNumbers(pr.sizes, 6, el.count) + local total = 0 + if sz then + for _, s in sz do + total += s + end + end + local items = sz and bufNumbers(pr.values, code, total) + if not (cc and sz and items) then + return nil, Err.new(Err.ARG, "element " .. el.name .. ": bad list property " .. tostring(pr.name)) + end + table.insert(rows, { kind = "l", col = { name = pr.name, ply = pr.type, code = code, countPly = pr.countType, countCode = cc, sizes = sz, items = items } }) + else + local vals = bufNumbers(pr.values, code, el.count) + if not vals then + return nil, Err.new(Err.ARG, "element " .. el.name .. ": bad property " .. tostring(pr.name)) + end + table.insert(rows, { kind = "s", col = { name = pr.name, ply = pr.type, code = code, values = vals, stride = 1, offset = 0 } }) + end + end + raws[el.name] = { name = el.name, count = el.count, rows = rows } + table.insert(rawOrder, el.name) + end + end + end + -- element order: the source's, then vertex, face, the rest + local order: { string } = {} + local seen: { [string]: boolean } = {} + local function want(name: string) + if seen[name] then + return + end + if name == "vertex" or (name == "face" and faceRows) or raws[name] then + seen[name] = true + table.insert(order, name) + end + end + if type(meta.order) == "table" then + for _, name in meta.order do + if type(name) == "string" then + want(name) + end + end + end + want("vertex") + want("face") + for _, name in rawOrder do + want(name) + end + -- header + local vrows: { Row } = {} + for _, c in cols do + table.insert(vrows, { kind = "s", col = c }) + end + local lines = { "ply", "format " .. enc .. " 1.0" } + local function noNewline(s: any): string + return (string.gsub(tostring(s), "[\r\n]", " ")) + end + for _, c in (if type(meta.comments) == "table" then meta.comments else {}) :: { any } do + table.insert(lines, "comment " .. noNewline(c)) + end + for _, c in o.comments or {} do + table.insert(lines, "comment " .. noNewline(c)) + end + for _, c in (if type(meta.objInfo) == "table" then meta.objInfo else {}) :: { any } do + table.insert(lines, "obj_info " .. noNewline(c)) + end + local function elementRows(name: string): (number, { Row }) + if name == "vertex" then + return nv, vrows + elseif name == "face" and faceRows then + return nf, faceRows + end + local raw = raws[name] + return raw.count, raw.rows + end + for _, name in order do + local n, rows = elementRows(name) + table.insert(lines, "element " .. noNewline(name) .. " " .. string.format("%d", n)) + for _, rw in rows do + if rw.kind == "s" then + local c = rw.col :: Column + table.insert(lines, "property " .. c.ply .. " " .. noNewline(c.name)) + else + local c = rw.col :: ListColumn + table.insert(lines, "property list " .. c.countPly .. " " .. c.ply .. " " .. noNewline(c.name)) + end + end + end + table.insert(lines, "end_header") + local header = table.concat(lines, "\n") .. "\n" + if enc == "ascii" then + local out = { header } + local body: { string } = {} + for _, name in order do + local n, rows = elementRows(name) + rowsAscii(body, n, rows) + end + if #body > 0 then + table.insert(out, table.concat(body, "\n")) + table.insert(out, "\n") + end + return buffer.fromstring(table.concat(out)), nil + end + local w = Bytes.writer(#header + nv * 32 + nf * 16) + w:string(header) + for _, name in order do + local n, rows = elementRows(name) + rowsBinary(w, n, rows, enc == "binary_big_endian") + end + return w:finish(), nil +end + +return Ply diff --git a/src/Formats/model/stl/Decode.luau b/src/Formats/model/stl/Decode.luau new file mode 100644 index 0000000..d99ad3c --- /dev/null +++ b/src/Formats/model/stl/Decode.luau @@ -0,0 +1,77 @@ +--!strict +--!native +--!optimize 2 +-- model/stl/Decode: the binary STL facet loop (50 bytes per facet: normal, 3 vertices, u16 attribute) and the 5-5-5 +-- colour expansion of the VisCAM / SolidView and Materialise Magics conventions. The caller (init) has checked that +-- the facets fit in the data and allocated the outputs, so every index here is in range; nothing here throws. +local readu16, readu32, writeu8, writeu16, writeu32 = buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu16, buffer.writeu32 +local band, bor, rshift = bit32.band, bit32.bor, bit32.rshift + +local Decode = {} + +-- binary(b, p, n, pos, nrm, attr) -> the OR of every attribute word. Copies the vertices (f32 bits as they are) into +-- pos (n * 36 bytes), the facet normal three times into nrm (n * 36 bytes) and the attributes into attr (n * 2 bytes). +function Decode.binary(b: buffer, p: number, n: number, pos: buffer, nrm: buffer, attr: buffer): number + local any = 0 + for i = 0, n - 1 do + local q = p + i * 50 + local o = i * 36 + local nx, ny, nz = readu32(b, q), readu32(b, q + 4), readu32(b, q + 8) + writeu32(nrm, o, nx) + writeu32(nrm, o + 4, ny) + writeu32(nrm, o + 8, nz) + writeu32(nrm, o + 12, nx) + writeu32(nrm, o + 16, ny) + writeu32(nrm, o + 20, nz) + writeu32(nrm, o + 24, nx) + writeu32(nrm, o + 28, ny) + writeu32(nrm, o + 32, nz) + writeu32(pos, o, readu32(b, q + 12)) + writeu32(pos, o + 4, readu32(b, q + 16)) + writeu32(pos, o + 8, readu32(b, q + 20)) + writeu32(pos, o + 12, readu32(b, q + 24)) + writeu32(pos, o + 16, readu32(b, q + 28)) + writeu32(pos, o + 20, readu32(b, q + 32)) + writeu32(pos, o + 24, readu32(b, q + 36)) + writeu32(pos, o + 28, readu32(b, q + 40)) + writeu32(pos, o + 32, readu32(b, q + 44)) + local a = readu16(b, q + 48) + writeu16(attr, i * 2, a) + any = bor(any, a) + end + return any +end + +-- 5-bit -> 8-bit, rounded +local function x8(v: number): number + return (v * 255 + 15) // 31 +end + +-- colors(attr, n, magics, r, g, b, a, out): unorm8 RGBA per vertex (n * 12 bytes). VisCAM: bit 15 set = valid, +-- red in bits 10..14, blue in 0..4 (invalid facets get r, g, b, a). Magics: bit 15 clear = the facet's own colour, +-- red in bits 0..4, blue in 10..14 (set: the object colour r, g, b, a). +function Decode.colors(attr: buffer, n: number, magics: boolean, dr: number, dg: number, db: number, da: number, out: buffer) + for i = 0, n - 1 do + local w = readu16(attr, i * 2) + local r, g, bl, al = dr, dg, db, da + local own = if magics then w < 0x8000 else w >= 0x8000 + if own then + local lo, mid, hi = x8(band(w, 31)), x8(band(rshift(w, 5), 31)), x8(band(rshift(w, 10), 31)) + g, al = mid, 255 + if magics then + r, bl = lo, hi + else + r, bl = hi, lo + end + end + local o = i * 12 + for k = 0, 2 do + writeu8(out, o + k * 4, r) + writeu8(out, o + k * 4 + 1, g) + writeu8(out, o + k * 4 + 2, bl) + writeu8(out, o + k * 4 + 3, al) + end + end +end + +return Decode diff --git a/src/Formats/model/stl/init.luau b/src/Formats/model/stl/init.luau new file mode 100644 index 0000000..50cfe41 --- /dev/null +++ b/src/Formats/model/stl/init.luau @@ -0,0 +1,467 @@ +--!strict +-- model/stl: STL (3D Systems stereolithography), ASCII and binary, read + write. Written from the format description +-- (Wikipedia "STL (file format)" and the 3D Systems SLC spec). +-- Decode: a triangle soup, 3 vertices per facet, no indices: POSITION f32 x3, NORMAL f32 x3 (the facet normal from the +-- file on each of its vertices), COLOR_0 unorm8 x4 when the binary file uses a colour convention (VisCAM / SolidView: +-- attribute bit 15 = colour valid, RGB 5-5-5 with red high; Materialise Magics: "COLOR=" rgba in the header is the +-- object colour, bit 15 clear = the facet's own colour, red low). Other non-zero attribute words are kept per facet in +-- prim.extras.faceAttributes.attribute (u16). Binary files may start with "solid": a file whose size is exactly +-- 84 + 50 * count is binary. ASCII: keywords in any case, any whitespace, several solids (one primitive per solid in +-- one mesh, prim.extras.solid = its name), facets with more than 3 vertices are fan-triangulated, a missing final +-- endsolid is tolerated. meta.up = "z"; meta.source = { format, binary, header, colors, defaultColor, material, +-- solids, facets }. +-- Encode: every primitive of the scene in world space (node transforms applied; polygons / strips / fans +-- fan-triangulated, points and lines skipped), binary (default) or ASCII (one solid per primitive, named after +-- prim.extras.solid / the mesh / the node, made distinct), facet normals computed from the triangle +-- (right-hand rule) unless opts.normals = "attribute", colours from COLOR_0 (the facet's first vertex) in either +-- convention. Not supported: binary-only extensions other than the two colour conventions. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Decode = require("@formats/model/stl/Decode") +local Flatten = require("@formats/codecs/MeshFlatten") + +-- ------------------------------------------------------------------------------------------------ contract +local Stl = { + name = "stl", + category = "model", + 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 }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + maxFaces: number?, -- refuse more facets (default 2^25) + colors: ("auto" | "viscam" | "magics" | "none")?, -- binary colour convention (default "auto": "COLOR=" in the + -- header = magics, else any attribute with bit 15 set = viscam, else none) +} +export type EncodeOptions = { + ascii: boolean?, -- default false (binary) + colors: ("viscam" | "magics")?, -- write COLOR_0 (the first vertex of each facet) in that convention (binary only) + defaultColor: { number }?, -- magics: the object colour r, g, b, a 0..255 (default opaque white); facets of exactly + -- that colour refer to it, the others carry their own (alpha 255) + name: string?, -- the ASCII solid name (default: the mesh / node name, else "mesh") + header: string?, -- the binary header text (at most 80 bytes; default "formats-luau STL") + normals: ("compute" | "attribute")?, -- facet normals from the triangle (default) or the first vertex's NORMAL +} + +-- ------------------------------------------------------------------------------------------------ constants +local readu8, readu32 = buffer.readu8, buffer.readu32 +local writef32, writeu16, writeu32 = buffer.writef32, buffer.writeu16, buffer.writeu32 + +local function lower5(s: string): boolean + return string.lower(s) == "solid" +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Stl.sniff(r: Bytes.Reader): number + local size = r:remaining() + if size >= 84 then + local c = r:peek(4, 80) + local n = string.byte(c, 1) + string.byte(c, 2) * 256 + string.byte(c, 3) * 65536 + string.byte(c, 4) * 16777216 + if 84 + 50 * n == size then + return 0.9 + end + end + local head = r:peek(512) + local s = string.match(head, "^%s*(%a+)") + if s and lower5(s) then + local l = string.lower(head) + return if string.find(l, "facet", 1, true) or string.find(l, "endsolid", 1, true) then 0.9 else 0.5 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function soupPrim(n: number, pos: buffer, nrm: buffer): Types.Primitive + return { + attributes = { + POSITION = Types.Scene.accessor(pos, "f32", 3, n * 3), + NORMAL = Types.Scene.accessor(nrm, "f32", 3, n * 3), + }, + mode = "triangles", + } +end + +local function decodeBinary(r: Bytes.Reader, maxFaces: number, colors: string): (Types.Scene?, Err.Err?) + local b, base, size = r.buf, r.base, r.limit - r.base + local n = readu32(b, base + 80) + if n > maxFaces then + return nil, Err.new(Err.LIMIT, string.format("%d facets is over the %d facet limit", n, maxFaces), base + 80) + end + if 84 + 50 * n > size then + return nil, Err.new(Err.TRUNCATED, string.format("%d facets need %d bytes, the file has %d", n, 84 + 50 * n, size), base + 80) + end + local pos, nrm, attr = buffer.create(n * 36), buffer.create(n * 36), buffer.create(n * 2) + local any = Decode.binary(b, base + 84, n, pos, nrm, attr) + local header = buffer.readstring(b, base, 80) + local cut = string.find(header, "\0", 1, true) -- the text before the first NUL + local text = if cut then string.sub(header, 1, cut - 1) else header + local mode = colors + local ci = string.find(header, "COLOR=", 1, true) + if mode == "auto" then + mode = if ci and ci + 9 <= 80 then "magics" elseif any >= 0x8000 then "viscam" else "none" + end + local prim = soupPrim(n, pos, nrm) + local source: { [string]: any } = { format = "stl", binary = true, header = text, facets = n } + if mode == "viscam" or mode == "magics" then + local dc = { 255, 255, 255, 255 } + if mode == "magics" and ci and ci + 9 <= 80 then + local o = base + ci + 5 -- the 4 bytes after "COLOR=" (ci is 1-based) + dc = { readu8(b, o), readu8(b, o + 1), readu8(b, o + 2), readu8(b, o + 3) } + source.defaultColor = dc + local mi = string.find(header, "MATERIAL=", 1, true) + if mi and mi + 8 + 12 <= 80 then + local m = base + mi + 8 + local function rgba(k: number): { number } + return { readu8(b, m + k), readu8(b, m + k + 1), readu8(b, m + k + 2), readu8(b, m + k + 3) } + end + source.material = { diffuse = rgba(0), specular = rgba(4), ambient = rgba(8) } + end + end + local col = buffer.create(n * 12) + Decode.colors(attr, n, mode == "magics", dc[1], dc[2], dc[3], dc[4], col) + prim.attributes.COLOR_0 = Types.Scene.accessor(col, "unorm8", 4, n * 3) + source.colors = mode + elseif any ~= 0 then + prim.extras = { faceAttributes = { attribute = Types.Scene.accessor(attr, "u16", 1, n) } } + end + local scene = Types.Scene.fromPrimitive(prim, nil) + scene.meta.up = "z" + scene.meta.source = source :: any + return scene, nil +end + +local function decodeAscii(r: Bytes.Reader, maxFaces: number): (Types.Scene?, Err.Err?) + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local at = 1 + local function tok(): string? + local s, e = string.find(text, "%S+", at) + if not s then + return nil + end + at = (e :: number) + 1 + return string.sub(text, s, e) + end + local function restOfLine(): string + local e = string.find(text, "\n", at, true) or (#text + 1) + local line = string.sub(text, at, e - 1) + at = e + 1 + return string.match(line, "^%s*(.-)%s*$") or "" + end + local function num(): number? + local t = tok() + return if t then tonumber(t) else nil + end + type Solid = { name: string, pos: { number }, nrm: { number } } + local solids: { Solid } = {} + local facets = 0 + while true do + local t = tok() + if t == nil then + break + end + if string.lower(t) ~= "solid" then + return nil, Err.new(Err.CORRUPT, "expected solid, found " .. string.sub(t, 1, 20)) + end + local cur: Solid = { name = restOfLine(), pos = {}, nrm = {} } + table.insert(solids, cur) + local pos, nrm = cur.pos, cur.nrm + while true do + local w = tok() + if w == nil then + break -- a missing endsolid at the end + end + local lw = string.lower(w) + if lw == "endsolid" then + restOfLine() + break + elseif lw ~= "facet" then + return nil, Err.new(Err.CORRUPT, "expected facet or endsolid, found " .. string.sub(w, 1, 20)) + end + local nx, ny, nz = 0, 0, 0 + local k = tok() + if k and string.lower(k) == "normal" then + local a, bb, c = num(), num(), num() + if a == nil or bb == nil or c == nil then + return nil, Err.new(if at > #text then Err.TRUNCATED else Err.CORRUPT, "bad facet normal") + end + nx, ny, nz = a, bb, c + k = tok() + end + local l2 = tok() + if k == nil or l2 == nil then + return nil, Err.new(Err.TRUNCATED, "facet cut short") + end + if string.lower(k) ~= "outer" or string.lower(l2) ~= "loop" then + return nil, Err.new(Err.CORRUPT, "expected outer loop") + end + local vs: { number } = {} + while true do + local v = tok() + if v == nil then + return nil, Err.new(Err.TRUNCATED, "facet cut short") + end + local lv = string.lower(v) + if lv == "endloop" then + break + elseif lv ~= "vertex" then + return nil, Err.new(Err.CORRUPT, "expected vertex or endloop, found " .. string.sub(v, 1, 20)) + end + local x, y, z = num(), num(), num() + if x == nil or y == nil or z == nil then + return nil, Err.new(if at > #text then Err.TRUNCATED else Err.CORRUPT, "bad vertex") + end + table.insert(vs, x) + table.insert(vs, y) + table.insert(vs, z) + end + local e = tok() + if e == nil then + return nil, Err.new(Err.TRUNCATED, "facet cut short") + elseif string.lower(e) ~= "endfacet" then + return nil, Err.new(Err.CORRUPT, "expected endfacet") + end + local nvs = #vs // 3 + if nvs < 3 then + return nil, Err.new(Err.CORRUPT, "facet with fewer than 3 vertices") + end + for j = 2, nvs - 1 do + for _, vi in { 0, j - 1, j } do + table.insert(pos, vs[vi * 3 + 1]) + table.insert(pos, vs[vi * 3 + 2]) + table.insert(pos, vs[vi * 3 + 3]) + table.insert(nrm, nx) + table.insert(nrm, ny) + table.insert(nrm, nz) + end + facets += 1 + end + if facets > maxFaces then + return nil, Err.new(Err.LIMIT, string.format("over the %d facet limit", maxFaces)) + end + end + end + if #solids == 0 then + return nil, Err.new(Err.TRUNCATED, "no solid") + end + local prims: { Types.Primitive } = {} + local names: { string } = {} + for i, s in solids do + local n = #s.pos // 9 + local pos, nrm = buffer.create(n * 36), buffer.create(n * 36) + for j = 1, n * 9 do + writef32(pos, (j - 1) * 4, s.pos[j]) + writef32(nrm, (j - 1) * 4, s.nrm[j]) + end + local prim = soupPrim(n, pos, nrm) + prim.extras = { solid = s.name } + prims[i] = prim + names[i] = s.name + end + local first = solids[1].name + local scene = Types.Scene.fromPrimitive(prims[1], if first ~= "" then first else nil) + for i = 2, #prims do + table.insert(scene.meshes[1].primitives, prims[i]) + end + scene.meta.up = "z" + scene.meta.source = { format = "stl", binary = false, solids = names, facets = facets } + return scene, nil +end + +function Stl.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local maxFaces = opts and opts.maxFaces or 2 ^ 25 + local colors = opts and opts.colors or "auto" + if colors ~= "auto" and colors ~= "viscam" and colors ~= "magics" and colors ~= "none" then + return nil, Err.new(Err.ARG, "colors must be auto, viscam, magics or none") + end + local size = r.limit - r.base + if size >= 84 and 84 + 50 * readu32(r.buf, r.base + 80) == size then + return decodeBinary(r, maxFaces, colors) + end + local s = string.match(buffer.readstring(r.buf, r.base, math.min(size, 256)), "^%s*(%a+)") + if s and lower5(s) then + return decodeAscii(r, maxFaces) + end + if size < 84 then + return nil, Err.new(Err.TRUNCATED, "shorter than a binary STL header", r.base) + end + -- binary with extra bytes after the facets (tolerated) or too few (TRUNCATED) + return decodeBinary(r, maxFaces, colors) +end + +-- ------------------------------------------------------------------------------------------------ encode +local scratch = buffer.create(4) +local function f32(v: number): number + writef32(scratch, 0, v) + return buffer.readf32(scratch, 0) +end + +-- a COLOR_0 component as 0..255 +local function byte(a: Flatten.Attr, v: number): number + if a.raw then + if a.type == "unorm16" then + return (v * 255 + 32767) // 65535 + end + return math.clamp(v, 0, 255) + end + return math.floor(math.clamp(v, 0, 1) * 255 + 0.5) +end + +local function to5(c: number): number + return (c * 31 + 127) // 255 +end + +local function keep(name: string): boolean + return name == "NORMAL" or name == "COLOR_0" +end + +function Stl.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local colors = o.colors + if colors ~= nil and colors ~= "viscam" and colors ~= "magics" then + return nil, Err.new(Err.ARG, "colors must be viscam or magics") + end + if o.normals ~= nil and o.normals ~= "compute" and o.normals ~= "attribute" then + return nil, Err.new(Err.ARG, "normals must be compute or attribute") + end + if o.header ~= nil and (type(o.header) ~= "string" or #o.header > 80) then + return nil, Err.new(Err.ARG, "header must be a string of at most 80 bytes") + end + local m, merr = Flatten.merge(scene, keep, { triangulate = true }) + if not m then + return nil, Err.new(Err.ARG, tostring(merr)) + end + local P = m.attrs.POSITION.values + local N = if o.normals == "attribute" and m.attrs.NORMAL then m.attrs.NORMAL.values else nil + local C = m.attrs.COLOR_0 + local corners = m.corners + local nf = #corners // 3 + -- facet normal (computed in double from the f32 vertices) and colour of facet f (0-based) + local function normal(f: number): (number, number, number) + local a, b, c = corners[f * 3 + 1], corners[f * 3 + 2], corners[f * 3 + 3] + if N then + return N[a * 3 + 1], N[a * 3 + 2], N[a * 3 + 3] + end + local ax, ay, az = P[a * 3 + 1], P[a * 3 + 2], P[a * 3 + 3] + local ux, uy, uz = P[b * 3 + 1] - ax, P[b * 3 + 2] - ay, P[b * 3 + 3] - az + local vx, vy, vz = P[c * 3 + 1] - ax, P[c * 3 + 2] - ay, P[c * 3 + 3] - az + local nx, ny, nz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + local l = math.sqrt(nx * nx + ny * ny + nz * nz) + if l > 0 and l < math.huge then + return nx / l, ny / l, nz / l + end + return 0, 0, 0 + end + if o.ascii then + local out = table.create(nf * 7 + 2 * #m.parts) + local used: { [string]: boolean } = {} + local function fmt(v: number): string? + v = f32(v) + if v ~= v or v == math.huge or v == -math.huge then + return nil + end + return string.format("%.9g", v) + end + for _, part in m.parts do + local name = o.name + if name == nil then + local ex = part.prim.extras + name = if ex and type(ex.solid) == "string" then ex.solid elseif part.mesh and part.mesh.name then part.mesh.name elseif part.node and part.node.name then part.node.name else "mesh" + end + name = string.gsub(tostring(name), "[\r\n]", " ") + if used[name] then -- distinct names: some readers merge solids by name + local k = 2 + while used[name .. "_" .. k] do + k += 1 + end + name = name .. "_" .. k + end + used[name] = true + table.insert(out, "solid " .. name .. "\n") + for f = part.firstFace, part.firstFace + part.faceCount - 1 do + local nx, ny, nz = normal(f) + table.insert(out, string.format(" facet normal %s %s %s\n outer loop\n", fmt(nx) or "0", fmt(ny) or "0", fmt(nz) or "0")) + for k = 1, 3 do + local v = corners[f * 3 + k] * 3 + local x, y, z = fmt(P[v + 1]), fmt(P[v + 2]), fmt(P[v + 3]) + if not (x and y and z) then + return nil, Err.new(Err.ARG, "ASCII STL cannot hold a non-finite coordinate") + end + table.insert(out, " vertex " .. x .. " " .. y .. " " .. z .. "\n") + end + table.insert(out, " endloop\n endfacet\n") + end + table.insert(out, "endsolid " .. name .. "\n") + end + if #m.parts == 0 then + table.insert(out, "solid " .. (o.name or "mesh") .. "\nendsolid " .. (o.name or "mesh") .. "\n") + end + return buffer.fromstring(table.concat(out)), nil + end + -- binary + local buf = buffer.create(84 + 50 * nf) + local header = o.header or "formats-luau STL" + if colors == "magics" then + local dc = o.defaultColor or { 255, 255, 255, 255 } + if type(dc) ~= "table" or #dc < 4 then + return nil, Err.new(Err.ARG, "defaultColor must be { r, g, b, a }") + end + header = string.sub(header, 1, 69) .. " COLOR=" .. string.char(math.clamp(dc[1], 0, 255) // 1, math.clamp(dc[2], 0, 255) // 1, math.clamp(dc[3], 0, 255) // 1, math.clamp(dc[4], 0, 255) // 1) + end + local dcol: { number }? = nil + if colors == "magics" then + local dc = o.defaultColor or { 255, 255, 255, 255 } + dcol = { dc[1] // 1, dc[2] // 1, dc[3] // 1, dc[4] // 1 } + end + buffer.writestring(buf, 0, header) + writeu32(buf, 80, nf) + -- the attribute words: colours, or the raw words of a single STL-decoded primitive + local rawAttr: { number }? = nil + if colors == nil and #m.parts == 1 then + local ex = m.parts[1].prim.extras + local fa = ex and ex.faceAttributes + local acc = fa and fa.attribute + if acc and acc.count == nf then + rawAttr = Flatten.numbers(acc, true) + end + end + for f = 0, nf - 1 do + local q = 84 + f * 50 + local nx, ny, nz = normal(f) + writef32(buf, q, nx) + writef32(buf, q + 4, ny) + writef32(buf, q + 8, nz) + for k = 0, 2 do + local v = corners[f * 3 + k + 1] * 3 + writef32(buf, q + 12 + k * 12, P[v + 1]) + writef32(buf, q + 16 + k * 12, P[v + 2]) + writef32(buf, q + 20 + k * 12, P[v + 3]) + end + local w = 0 + if colors and C then + local a = corners[f * 3 + 1] * C.components + local cv = C.values + local r5, g5, b5 = to5(byte(C, cv[a + 1])), to5(byte(C, cv[a + 2] or 0)), to5(byte(C, cv[a + 3] or 0)) + if colors == "viscam" then + w = 0x8000 + r5 * 1024 + g5 * 32 + b5 + elseif dcol and byte(C, cv[a + 1]) == dcol[1] and byte(C, cv[a + 2] or 0) == dcol[2] and byte(C, cv[a + 3] or 0) == dcol[3] and (if C.components >= 4 then byte(C, cv[a + 4]) else 255) == dcol[4] then + w = 0x8000 -- the object colour + else + w = r5 + g5 * 32 + b5 * 1024 + end + elseif colors == "magics" then + w = 0x8000 -- the object colour + elseif rawAttr then + w = math.clamp(rawAttr[f + 1] // 1, 0, 65535) + end + writeu16(buf, q + 48, w) + end + return buf, nil +end + +return Stl diff --git a/src/Formats/model/vox/Grid.luau b/src/Formats/model/vox/Grid.luau new file mode 100644 index 0000000..4a6601e --- /dev/null +++ b/src/Formats/model/vox/Grid.luau @@ -0,0 +1,61 @@ +--!strict +--!native +-- model/vox/Grid: the voxel loops of the VOX format: XYZI records into a dense grid, and a dense grid back into XYZI +-- records. Callers check every range first; nothing here throws. +local Grid = {} + +local readu8, writeu8 = buffer.readu8, buffer.writeu8 + +-- fill(dst, sx, sy, sz, src, off, n) -> skipped: writes n XYZI records (x, y, z, index bytes at src[off ..]) into the +-- dense grid dst (cell x + sx * (y + sy * z)); records outside the grid or with index 0 are skipped and counted. +-- The caller guarantees off + 4 * n <= buffer.len(src) and buffer.len(dst) >= sx * sy * sz. +function Grid.fill(dst: buffer, sx: number, sy: number, sz: number, src: buffer, off: number, n: number): number + local skipped = 0 + local sxy = sx * sy + for k = 0, n - 1 do + local p = off + k * 4 + local x, y, z, i = readu8(src, p), readu8(src, p + 1), readu8(src, p + 2), readu8(src, p + 3) + if x < sx and y < sy and z < sz and i ~= 0 then + writeu8(dst, x + sx * y + sxy * z, i) + else + skipped += 1 + end + end + return skipped +end + +-- count(data, cells) -> the number of non-empty cells in data[0, cells) +function Grid.count(data: buffer, cells: number): number + local n = 0 + for k = 0, cells - 1 do + if readu8(data, k) ~= 0 then + n += 1 + end + end + return n +end + +-- write(dst, at, data, sx, sy, sz) -> the offset after the last record: one XYZI record per non-empty cell (x fastest). +-- The caller sizes dst with count() (sx, sy, sz <= 256). +function Grid.write(dst: buffer, at: number, data: buffer, sx: number, sy: number, sz: number): number + local p = at + local k = 0 + for z = 0, sz - 1 do + for y = 0, sy - 1 do + for x = 0, sx - 1 do + local i = readu8(data, k) + if i ~= 0 then + writeu8(dst, p, x) + writeu8(dst, p + 1, y) + writeu8(dst, p + 2, z) + writeu8(dst, p + 3, i) + p += 4 + end + k += 1 + end + end + end + return p +end + +return Grid diff --git a/src/Formats/model/vox/init.luau b/src/Formats/model/vox/init.luau new file mode 100644 index 0000000..81277aa --- /dev/null +++ b/src/Formats/model/vox/init.luau @@ -0,0 +1,903 @@ +--!strict +-- model/vox: MagicaVoxel .vox, from ephtracy's spec (voxel-model/MagicaVoxel-file-format-vox.txt and -vox-extension.txt) +-- and the files MagicaVoxel 0.99.x saves (version 150 and 200). +-- Reads every chunk: SIZE + XYZI models, RGBA palette (the default palette when absent), the scene graph (nTRN / nGRP / +-- nSHP, with names, hidden flags, layers, 90-degree rotations, translations and animation frames), MATL materials, +-- LAYR layers, rOBJ render settings, rCAM cameras, NOTE palette notes, IMAP, META; PACK and MATT (old) and unknown +-- chunks are kept raw and written back. +-- decode -> a Scene (meta.up = "z", units = voxels): scene.voxels holds the grids (Types.Voxels: size, one byte per +-- cell, palette, materials), each scene node from an nTRN, its nGRP children as node.children, its nSHP model as +-- node.voxels. Vox.decodeVoxels gives the grids alone. Meshes: ops/MeshOps.meshVoxels(scene) (greedy meshing; a shape is +-- centred on its node like MagicaVoxel does: cell (x, y, z) spans x - floor(sx / 2) .. + 1). A format never meshes. +-- encode <- a Scene with voxels (or one Types.Voxels): models, the node tree back as nTRN / nGRP / nSHP (rotations must +-- be multiples of 90 degrees; translations are rounded to whole voxels), palette, materials and every meta chunk. +-- Not supported: models over 256 cells per axis on write (MagicaVoxel's limit); node scale other than mirroring. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Grid = require("@formats/model/vox/Grid") + +-- ------------------------------------------------------------------------------------------------ contract +local Vox = { + name = "vox", + category = "model", + extensions = { "vox" }, + mime = { "model/x-vox" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, voxels = true, sceneGraph = true, materials = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + maxCells: number?, -- refuse files whose grids hold more cells in total (default 2^27) +} +export type EncodeOptions = { + version: number?, -- the file version (default 200, what MagicaVoxel 0.99.7 writes; 150 is the older one) +} +type Dict = { [string]: string } +type GraphNode = { + kind: string, + id: number, + attrs: Dict, + child: number?, + layer: number?, + frames: { Dict }?, + children: { number }?, + models: { { model: number, attributes: Dict } }?, +} + +-- ------------------------------------------------------------------------------------------------ constants +-- the default palette (spec section 8): a 6 x 6 x 6 colour cube without black, then red, green, blue and grey ramps +local DEFAULT_PALETTE: { { number } } = {} +do + local steps = { 0xff, 0xcc, 0x99, 0x66, 0x33, 0x00 } + for _, r in steps do + for _, g in steps do + for _, b in steps do + if #DEFAULT_PALETTE < 215 then + table.insert(DEFAULT_PALETTE, { r, g, b, 255 }) + end + end + end + end + local ramp = { 0xee, 0xdd, 0xbb, 0xaa, 0x88, 0x77, 0x55, 0x44, 0x22, 0x11 } + for ch = 1, 4 do + for _, v in ramp do + local c = { 0, 0, 0, 255 } + if ch == 4 then + c = { v, v, v, 255 } + else + c[ch] = v + end + table.insert(DEFAULT_PALETTE, c) + end + end +end +Vox.DEFAULT_PALETTE = DEFAULT_PALETTE + +local IDENTITY_R = 4 -- _r of the identity: row 0 -> column 0, row 1 -> column 1, no signs +local MAX_DEPTH = 256 + +-- ------------------------------------------------------------------------------------------------ sniff +function Vox.sniff(r: Bytes.Reader): number + return if r:peek(4) == "VOX " and r:peek(4, 8) == "MAIN" then 1 elseif r:peek(4) == "VOX " then 0.8 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function str(r: Bytes.Reader): string + local n = r:i32le() + if n < 0 or n > r:remaining() then + r:fail(Err.CORRUPT, "bad string length") + return "" + end + return r:string(n) +end + +local function dict(r: Bytes.Reader): Dict + local d: Dict = {} + local n = r:i32le() + if n < 0 or n * 8 > r:remaining() then + r:fail(Err.CORRUPT, "bad dictionary size") + return d + end + for _ = 1, n do + local k = str(r) + local v = str(r) + if r.err then + break + end + d[k] = v + end + return d +end + +local function ints(s: string?): { number } + local out = {} + if s then + for w in string.gmatch(s, "%S+") do + table.insert(out, tonumber(w) or 0) + end + end + return out +end + +-- _r byte -> the row-major 3 x 3 rotation (rows of { column, sign }) | nil when the byte is not a permutation +local function rotation(b: number): { { number } }? + local i0, i1 = bit32.band(b, 3), bit32.band(bit32.rshift(b, 2), 3) + if i0 > 2 or i1 > 2 or i0 == i1 then + return nil + end + local i2 = 3 - i0 - i1 + local function sign(bit: number): number + return if bit32.band(b, bit32.lshift(1, bit)) ~= 0 then -1 else 1 + end + return { { i0, sign(4) }, { i1, sign(5) }, { i2, sign(6) } } +end + +-- the node transform of a frame dictionary (_r, _t) +local function applyFrame(node: Types.Node, f: Dict) + local t = ints(f._t) + local tx, ty, tz = t[1] or 0, t[2] or 0, t[3] or 0 + local rb = tonumber(f._r) + local rows = if rb and rb ~= IDENTITY_R then rotation(rb) else nil + if not rows then + if tx ~= 0 or ty ~= 0 or tz ~= 0 then + node.translation = { tx, ty, tz } + end + return + end + -- R[row][col], then the determinant: +1 -> a quaternion, -1 (a mirror) -> a matrix + local R = { { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 } } + for row = 1, 3 do + R[row][rows[row][1] + 1] = rows[row][2] + end + local det = R[1][1] * (R[2][2] * R[3][3] - R[2][3] * R[3][2]) - R[1][2] * (R[2][1] * R[3][3] - R[2][3] * R[3][1]) + R[1][3] * (R[2][1] * R[3][2] - R[2][2] * R[3][1]) + if det < 0 then + node.matrix = { + R[1][1], R[2][1], R[3][1], 0, + R[1][2], R[2][2], R[3][2], 0, + R[1][3], R[2][3], R[3][3], 0, + tx, ty, tz, 1, + } + return + end + local m00, m11, m22 = R[1][1], R[2][2], R[3][3] + local tr = m00 + m11 + m22 + local x, y, z, w + if tr > 0 then + local s = math.sqrt(tr + 1) * 2 + w, x, y, z = 0.25 * s, (R[3][2] - R[2][3]) / s, (R[1][3] - R[3][1]) / s, (R[2][1] - R[1][2]) / s + elseif m00 > m11 and m00 > m22 then + local s = math.sqrt(1 + m00 - m11 - m22) * 2 + w, x, y, z = (R[3][2] - R[2][3]) / s, 0.25 * s, (R[1][2] + R[2][1]) / s, (R[1][3] + R[3][1]) / s + elseif m11 > m22 then + local s = math.sqrt(1 + m11 - m00 - m22) * 2 + w, x, y, z = (R[1][3] - R[3][1]) / s, (R[1][2] + R[2][1]) / s, 0.25 * s, (R[2][3] + R[3][2]) / s + else + local s = math.sqrt(1 + m22 - m00 - m11) * 2 + w, x, y, z = (R[2][1] - R[1][2]) / s, (R[1][3] + R[3][1]) / s, (R[2][3] + R[3][2]) / s, 0.25 * s + end + node.rotation = { x, y, z, w } + if tx ~= 0 or ty ~= 0 or tz ~= 0 then + node.translation = { tx, ty, tz } + end +end + +-- MATL dictionary -> VoxelMaterial: _type -> type (without "_"), the other keys without their "_", numbers as numbers +local function material(d: Dict): Types.VoxelMaterial + local m: Types.VoxelMaterial = { type = "diffuse" } + for k, v in d do + local key = if string.sub(k, 1, 1) == "_" then string.sub(k, 2) else k + if key == "type" then + m.type = if string.sub(v, 1, 1) == "_" then string.sub(v, 2) else v + else + m[key] = tonumber(v) or v + end + end + return m +end + +type Parsed = { + version: number, + models: { Types.Voxels }, + palette: { { number } }?, + materials: { [number]: Types.VoxelMaterial }, + graph: { [number]: GraphNode }, + meta: { [string]: any }, + skipped: number, +} + +local function parse(r: Bytes.Reader, opts: DecodeOptions?): (Parsed?, Err.Err?) + local maxCells = opts and opts.maxCells or 2 ^ 27 + if r:string(4) ~= "VOX " then + return nil, Err.new(Err.CORRUPT, "bad signature", r.base) + end + local version = r:u32le() + if r:string(4) ~= "MAIN" then + if r.err then + return nil, r.err + end + return nil, Err.new(Err.CORRUPT, "missing MAIN chunk", 8) + end + local mainN, mainM = r:i32le(), r:i32le() + if r.err then + return nil, r.err + end + if mainN < 0 or mainM < 0 or not r:skip(mainN) then + return nil, Err.new(Err.CORRUPT, "bad MAIN chunk", 12) + end + local out: Parsed = { version = version, models = {}, palette = nil, materials = {}, graph = {}, meta = {}, skipped = 0 } + local meta = out.meta + local unknown: { any } = {} + local layers, robjs, cams = {}, {}, {} + local stop = r:tell() + mainM + if stop > r:size() then + return nil, Err.new(Err.TRUNCATED, "the MAIN chunk runs past the end", r.base + 16) + end + local pending: { number }? = nil + local cells = 0 + while r:tell() + 12 <= stop do + local at = r:tell() + local id = r:string(4) + local n, m = r:i32le(), r:i32le() + if n < 0 or m < 0 then + return nil, Err.new(Err.CORRUPT, "bad size of chunk " .. id, at) + elseif n > stop - r:tell() or m > stop - r:tell() - n then + return nil, Err.new(Err.TRUNCATED, "chunk " .. id .. " runs past the end", at) + end + local c = r:slice(n) + if id == "SIZE" then + local sx, sy, sz = c:i32le(), c:i32le(), c:i32le() + if c.err or sx < 1 or sy < 1 or sz < 1 then + return nil, Err.new(Err.CORRUPT, "bad model size", at) + end + cells += sx * sy * sz + if cells > maxCells then + return nil, Err.new(Err.LIMIT, string.format("models hold over %d cells", maxCells), at) + end + pending = { sx, sy, sz } + elseif id == "XYZI" then + local size = pending + if not size then + return nil, Err.new(Err.CORRUPT, "XYZI without SIZE", at) + end + pending = nil + local count = c:i32le() + if c.err or count < 0 or count * 4 > c:remaining() then + return nil, Err.new(Err.CORRUPT, "bad voxel count", at) + end + local v = Types.Voxels.new(size[1], size[2], size[3], DEFAULT_PALETTE) + out.skipped += Grid.fill(v.data, size[1], size[2], size[3], c.buf, c.base + c:tell(), count) + table.insert(out.models, v) + elseif id == "RGBA" then + if n < 1024 then + return nil, Err.new(Err.CORRUPT, "short RGBA chunk", at) + end + local pal = table.create(255) + for i = 1, 255 do + pal[i] = { c:u8(), c:u8(), c:u8(), c:u8() } + end + out.palette = pal + elseif id == "MATL" then + local mid = c:i32le() + local d = dict(c) + if c.err then + return nil, Err.new(Err.CORRUPT, "bad MATL chunk", at) + end + out.materials[mid] = material(d) + elseif id == "nTRN" then + local node: GraphNode = { kind = id, id = c:i32le(), attrs = dict(c), child = c:i32le() } + c:i32le() -- reserved + node.layer = c:i32le() + local nf = c:i32le() + if c.err or nf < 0 or nf * 4 > c:remaining() then + return nil, Err.new(Err.CORRUPT, "bad nTRN chunk", at) + end + local frames = {} + for k = 1, nf do + frames[k] = dict(c) + end + node.frames = frames + if c.err then + return nil, Err.new(Err.CORRUPT, "bad nTRN frames", at) + end + out.graph[node.id] = node + elseif id == "nGRP" then + local node: GraphNode = { kind = id, id = c:i32le(), attrs = dict(c) } + local nc = c:i32le() + if c.err or nc < 0 or nc * 4 > c:remaining() then + return nil, Err.new(Err.CORRUPT, "bad nGRP chunk", at) + end + local children = table.create(nc) + for k = 1, nc do + children[k] = c:i32le() + end + node.children = children + out.graph[node.id] = node + elseif id == "nSHP" then + local node: GraphNode = { kind = id, id = c:i32le(), attrs = dict(c) } + local nm = c:i32le() + if c.err or nm < 0 or nm * 8 > c:remaining() then + return nil, Err.new(Err.CORRUPT, "bad nSHP chunk", at) + end + local models = {} + for k = 1, nm do + models[k] = { model = c:i32le() + 1, attributes = dict(c) } + end + if c.err then + return nil, Err.new(Err.CORRUPT, "bad nSHP models", at) + end + node.models = models + out.graph[node.id] = node + elseif id == "LAYR" then + local lid = c:i32le() + local d = dict(c) + if c.err then + return nil, Err.new(Err.CORRUPT, "bad LAYR chunk", at) + end + table.insert(layers, { id = lid, name = d._name, hidden = d._hidden == "1", attributes = d }) + elseif id == "rOBJ" then + local d = dict(c) + if c.err then + return nil, Err.new(Err.CORRUPT, "bad rOBJ chunk", at) + end + table.insert(robjs, d) + elseif id == "rCAM" then + local cid = c:i32le() + local d = dict(c) + if c.err then + return nil, Err.new(Err.CORRUPT, "bad rCAM chunk", at) + end + table.insert(cams, { id = cid, attributes = d }) + elseif id == "NOTE" then + local nn = c:i32le() + if c.err or nn < 0 or nn * 4 > c:remaining() then + return nil, Err.new(Err.CORRUPT, "bad NOTE chunk", at) + end + local notes = table.create(nn) + for k = 1, nn do + notes[k] = str(c) + end + if c.err then + return nil, Err.new(Err.CORRUPT, "bad NOTE names", at) + end + meta.notes = notes + elseif id == "IMAP" then + local map = {} + for k = 1, math.min(n, 256) do + map[k] = c:u8() + end + meta.indexMap = map + elseif id == "META" then + local d = dict(c) + if c.err then + return nil, Err.new(Err.CORRUPT, "bad META chunk", at) + end + meta.info = d + else + if id == "PACK" then + meta.pack = c:i32le() + end + table.insert(unknown, { id = id, content = c:sub(0, n):bytes(n), children = nil :: buffer? }) + end + if m > 0 then + local kids = r:bytes(math.min(m, r:remaining())) + if #unknown > 0 and unknown[#unknown].children == nil and unknown[#unknown].id == id then + unknown[#unknown].children = kids + end + end + if r.err then + return nil, r.err + end + end + if r:tell() < stop then + return nil, Err.new(Err.TRUNCATED, "a partial chunk at the end", r.base + r:tell()) + end + if #out.models == 0 then + return nil, Err.new(Err.CORRUPT, "no models") + end + if #layers > 0 then + meta.layers = layers + end + if #robjs > 0 then + meta.renderObjects = robjs + end + if #cams > 0 then + meta.cameras = cams + end + if #unknown > 0 then + meta.chunks = unknown + end + return out, nil +end + +-- the Scene node tree from the nTRN at id (nil for a missing / looping / non-transform node) +local function build(scene: Types.Scene, graph: { [number]: GraphNode }, id: number, depth: number, visiting: { [number]: boolean }, nmodels: number): number? + local t = graph[id] + if not t or t.kind ~= "nTRN" or depth > MAX_DEPTH or visiting[id] then + return nil + end + visiting[id] = true + local node: Types.Node = { name = t.attrs._name, children = {} } + local index = #scene.nodes + 1 + scene.nodes[index] = node + local frames = t.frames or {} + if frames[1] then + applyFrame(node, frames[1]) + end + local vox: { [string]: any } = { attributes = t.attrs, layer = t.layer } + if #frames > 1 or (frames[1] and frames[1]._f) then + vox.frames = frames + end + node.extras = { vox = vox } + local child = if t.child then graph[t.child] else nil + if child and child.kind == "nGRP" then + vox.group = child.attrs + for _, c in child.children or {} do + local ci = build(scene, graph, c, depth + 1, visiting, nmodels) + if ci then + table.insert(node.children, ci) + end + end + elseif child and child.kind == "nSHP" then + local models = child.models or {} + vox.shape = { attributes = child.attrs, models = models } + local first = models[1] + if first and first.model >= 1 and first.model <= nmodels then + node.voxels = first.model + end + end + visiting[id] = nil + return index +end + +-- decodeVoxels(r, opts?) -> { Voxels } (every model, in file order) | nil, Err +function Vox.decodeVoxels(r: Bytes.Reader, opts: DecodeOptions?): ({ Types.Voxels }?, Err.Err?) + local p, err = parse(r, opts) + if not p then + return nil, err + end + local pal = p.palette or DEFAULT_PALETTE + local mats = if next(p.materials) then p.materials else nil + for _, v in p.models do + v.palette = pal + v.materials = mats + end + return p.models, nil +end + +function Vox.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local p, err = parse(r, opts) + if not p then + return nil, err + end + local scene = Types.Scene.new() + local pal = p.palette or DEFAULT_PALETTE + local mats = if next(p.materials) then p.materials else nil + for _, v in p.models do + v.palette = pal + v.materials = mats + end + scene.voxels = p.models + if p.graph[0] then + local root = build(scene, p.graph, 0, 0, {}, #p.models) + if root then + scene.roots = { root } + end + end + if #scene.nodes == 0 then + -- no scene graph (version 150 files): one node per model + for i = 1, #p.models do + scene.nodes[i] = { children = {}, voxels = i } + scene.roots[i] = i + end + end + scene.meta.up = "z" + scene.meta.vox = p.meta + scene.meta.source = { format = "vox", version = p.version, models = #p.models, palette = p.palette ~= nil, skippedVoxels = p.skipped } + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function number(v: any): string + if type(v) ~= "number" then + return tostring(v) + end + if v == math.floor(v) and math.abs(v) < 2 ^ 53 then + return string.format("%d", v) + end + for _, f in { "%.6g", "%.9g", "%.17g" } do + local s = string.format(f, v) + if tonumber(s) == v then + return s + end + end + return string.format("%.17g", v) +end + +local function sortedKeys(d: { [string]: any }): { string } + local keys = {} + for k in d do + if type(k) == "string" then + table.insert(keys, k) + end + end + table.sort(keys) + return keys +end + +local function wstr(w: Bytes.Writer, s: string) + w:u32le(#s) + w:string(s) +end + +local function wdict(w: Bytes.Writer, d: { [string]: any }?) + if not d then + w:u32le(0) + return + end + local keys = sortedKeys(d) + w:u32le(#keys) + for _, k in keys do + wstr(w, k) + wstr(w, number(d[k])) + end +end + +-- a node's transform as a frame dictionary (_r, _t) | nil, message +local function frameOf(node: Types.Node, base: Dict?): (Dict?, string?) + local f: Dict = {} + if base then + for k, v in base do + if k ~= "_r" and k ~= "_t" then + f[k] = v + end + end + end + local m = Types.Scene.nodeMatrix(node) + local cols, signs = {}, {} + for row = 0, 2 do + local best, bv, rest = 0, 0, 0 + for col = 0, 2 do + local v = m[col * 4 + row + 1] + if math.abs(v) > math.abs(bv) then + rest = math.max(rest, math.abs(bv)) + best, bv = col, v + else + rest = math.max(rest, math.abs(v)) + end + end + if math.abs(math.abs(bv) - 1) > 1e-4 or rest > 1e-4 or table.find(cols, best) then + return nil, "node rotation is not a multiple of 90 degrees (or has a scale)" + end + table.insert(cols, best) + signs[row + 1] = if bv < 0 then 1 else 0 + end + local rb = cols[1] + cols[2] * 4 + signs[1] * 16 + signs[2] * 32 + signs[3] * 64 + if rb ~= IDENTITY_R then + f._r = tostring(rb) + end + local tx, ty, tz = math.floor(m[13] + 0.5), math.floor(m[14] + 0.5), math.floor(m[15] + 0.5) + if tx ~= 0 or ty ~= 0 or tz ~= 0 then + f._t = string.format("%d %d %d", tx, ty, tz) + end + return f, nil +end + +type Record = { kind: string, id: number, attrs: { [string]: any }?, child: number?, layer: number?, frames: { Dict }?, children: { number }?, models: { { model: number, attributes: Dict? } }? } + +function Vox.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local version = opts and opts.version or 200 + if type(version) ~= "number" or version < 0 then + return nil, Err.new(Err.ARG, "bad version") + end + if type(value) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Scene with voxels or a Voxels grid") + end + local scene: Types.Scene + if value.kind == "voxels" then + scene = Types.Scene.new() + scene.voxels = { value } + scene.nodes[1] = { children = {}, voxels = 1 } + scene.roots[1] = 1 + elseif value.kind == "scene" then + scene = value + else + return nil, Err.new(Err.ARG, "needs a Scene with voxels or a Voxels grid") + end + local models = scene.voxels + if type(models) ~= "table" or #models == 0 then + return nil, Err.new(Err.ARG, "the scene has no voxels (MeshOps cannot voxelize meshes yet)") + end + for i, v in models do + local s = v.size + if type(s) ~= "table" or type(v.data) ~= "buffer" then + return nil, Err.new(Err.ARG, "voxels " .. i .. ": not a Voxels grid") + end + for k = 1, 3 do + if type(s[k]) ~= "number" or s[k] < 1 or s[k] > 256 or s[k] ~= math.floor(s[k]) then + return nil, Err.new(Err.ARG, "voxels " .. i .. ": size must be 1..256 per axis") + end + end + if buffer.len(v.data) < s[1] * s[2] * s[3] then + return nil, Err.new(Err.ARG, "voxels " .. i .. ": data is smaller than the grid") + end + end + local meta = if type(scene.meta) == "table" and type(scene.meta.vox) == "table" then scene.meta.vox else {} + local w = Bytes.writer(65536) + w:string("VOX ") + w:u32le(version) + w:string("MAIN") + w:u32le(0) + local mAt = w:tell() + w:u32le(0) + local function chunk(id: string, body: () -> ()) + w:string(id) + local at = w:tell() + w:u32le(0) + w:u32le(0) + body() + w:setU32le(at, w:tell() - at - 8) + end + if type(meta.info) == "table" then + chunk("META", function() + wdict(w, meta.info) + end) + end + -- models + for _, v in models do + local sx, sy, sz = v.size[1], v.size[2], v.size[3] + chunk("SIZE", function() + w:u32le(sx) + w:u32le(sy) + w:u32le(sz) + end) + local count = Grid.count(v.data, sx * sy * sz) + chunk("XYZI", function() + w:u32le(count) + local at = w:reserve(count * 4) + Grid.write(w.buf, at, v.data, sx, sy, sz) + w.pos = at + count * 4 + end) + end + -- the scene graph + local records: { Record } = {} + local nextId = 0 + local function alloc(): number + local id = nextId + nextId += 1 + return id + end + local nodes = scene.nodes or {} + local visiting: { [number]: boolean } = {} + local failure: string? = nil + local function shape(model: number, vx: any?): number + local id = alloc() + local ms = {} + local saved = vx and vx.shape + if saved and type(saved.models) == "table" and saved.models[1] and saved.models[1].model == model then + for _, sm in saved.models do + if type(sm.model) == "number" and sm.model >= 1 and sm.model <= #models then + table.insert(ms, { model = sm.model - 1, attributes = sm.attributes }) + end + end + end + if #ms == 0 then + ms[1] = { model = model - 1, attributes = nil } + end + table.insert(records, { kind = "nSHP", id = id, attrs = saved and saved.attributes, models = ms }) + return id + end + local function visit(index: number, depth: number, layer: number?): number? + local node = nodes[index] + if not node or visiting[index] or depth > MAX_DEPTH then + failure = failure or "the node tree has a loop or is too deep" + return nil + end + visiting[index] = true + local vx = if type(node.extras) == "table" and type(node.extras.vox) == "table" then node.extras.vox else nil + local id = alloc() + local attrs: { [string]: any } = {} + if vx and type(vx.attributes) == "table" then + for k, v in vx.attributes do + attrs[k] = v + end + end + attrs._name = node.name + local saved = vx and type(vx.frames) == "table" and vx.frames or nil + local f, ferr = frameOf(node, saved and saved[1]) + if not f then + failure = failure or ferr + f = {} + end + local frames = { f :: Dict } + if saved then + for k = 2, #saved do + frames[k] = saved[k] + end + end + local rec: Record = { kind = "nTRN", id = id, attrs = attrs, layer = layer or (vx and tonumber(vx.layer)) or 0, frames = frames } + table.insert(records, rec) + local kids = node.children or {} + local hasVox = type(node.voxels) == "number" and node.voxels >= 1 and node.voxels <= #models + if hasVox and #kids == 0 then + rec.child = shape(node.voxels :: number, vx) + else + local gid = alloc() + local grp: Record = { kind = "nGRP", id = gid, attrs = vx and vx.group, children = {} } + table.insert(records, grp) + rec.child = gid + if hasVox then + local tid = alloc() + local t2: Record = { kind = "nTRN", id = tid, attrs = {}, layer = 0, frames = { {} } } + table.insert(records, t2) + table.insert(grp.children :: { number }, tid) + t2.child = shape(node.voxels :: number, vx) + end + for _, c in kids do + local cid = visit(c, depth + 1, nil) + if cid then + table.insert(grp.children :: { number }, cid) + end + end + end + visiting[index] = nil + return id + end + local roots = scene.roots or {} + local single = if #roots == 1 then nodes[roots[1]] else nil + if single and single.voxels == nil then + visit(roots[1], 0, -1) + elseif #roots > 0 then + local rid = alloc() + local gid = alloc() + local rec: Record = { kind = "nTRN", id = rid, attrs = {}, child = gid, layer = -1, frames = { {} } } + local grp: Record = { kind = "nGRP", id = gid, attrs = nil, children = {} } + table.insert(records, rec) + table.insert(records, grp) + for _, ri in roots do + local cid = visit(ri, 1, nil) + if cid then + table.insert(grp.children :: { number }, cid) + end + end + end + if failure then + return nil, Err.new(Err.ARG, failure) + end + for _, rec in records do + chunk(rec.kind, function() + w:u32le(rec.id) + wdict(w, rec.attrs) + if rec.kind == "nTRN" then + w:u32le(rec.child or 0) + w:u32le(0xFFFFFFFF) + w:u32le((rec.layer or 0) % 4294967296) + local frames = rec.frames or { {} } + w:u32le(#frames) + for _, f in frames do + wdict(w, f) + end + elseif rec.kind == "nGRP" then + local ch = rec.children or {} + w:u32le(#ch) + for _, c in ch do + w:u32le(c) + end + else + local ms = rec.models or {} + w:u32le(#ms) + for _, sm in ms do + w:u32le(sm.model) + wdict(w, sm.attributes) + end + end + end) + end + -- layers + if type(meta.layers) == "table" then + for _, l in meta.layers do + chunk("LAYR", function() + w:u32le(tonumber(l.id) or 0) + local d: { [string]: any } = {} + if type(l.attributes) == "table" then + for k, v in l.attributes do + d[k] = v + end + end + d._name = l.name + d._hidden = if l.hidden then "1" elseif d._hidden ~= nil then "0" else nil + wdict(w, d) + w:u32le(0xFFFFFFFF) + end) + end + end + -- palette + local pal = models[1].palette or DEFAULT_PALETTE + chunk("RGBA", function() + for i = 1, 256 do + local c = pal[i] + if type(c) == "table" then + w:u8(math.clamp(math.floor(tonumber(c[1]) or 0), 0, 255)) + w:u8(math.clamp(math.floor(tonumber(c[2]) or 0), 0, 255)) + w:u8(math.clamp(math.floor(tonumber(c[3]) or 0), 0, 255)) + w:u8(math.clamp(math.floor(tonumber(c[4]) or 255), 0, 255)) + else + w:u32le(0) + end + end + end) + if type(meta.indexMap) == "table" then + chunk("IMAP", function() + for k = 1, 256 do + w:u8(math.clamp(math.floor(tonumber(meta.indexMap[k]) or 0), 0, 255)) + end + end) + end + -- materials + local mats = models[1].materials + if type(mats) == "table" then + local ids = {} + for id in mats do + if type(id) == "number" then + table.insert(ids, id) + end + end + table.sort(ids) + for _, id in ids do + local m = mats[id] + chunk("MATL", function() + w:u32le(id) + local d: { [string]: any } = { _type = "_" .. tostring(m.type or "diffuse") } + for k, v in m do + if k ~= "type" and type(k) == "string" then + d["_" .. k] = v + end + end + wdict(w, d) + end) + end + end + if type(meta.renderObjects) == "table" then + for _, d in meta.renderObjects do + chunk("rOBJ", function() + wdict(w, d) + end) + end + end + if type(meta.cameras) == "table" then + for _, cam in meta.cameras do + chunk("rCAM", function() + w:u32le(tonumber(cam.id) or 0) + wdict(w, cam.attributes) + end) + end + end + if type(meta.notes) == "table" then + chunk("NOTE", function() + w:u32le(#meta.notes) + for _, s in meta.notes do + wstr(w, tostring(s)) + end + end) + end + if type(meta.chunks) == "table" then + for _, u in meta.chunks do + if type(u.id) == "string" and #u.id == 4 and type(u.content) == "buffer" and u.id ~= "PACK" then + w:string(u.id) + w:u32le(buffer.len(u.content)) + w:u32le(if u.children then buffer.len(u.children) else 0) + w:bytes(u.content) + if u.children then + w:bytes(u.children) + end + end + end + end + w:setU32le(mAt, w:tell() - mAt - 4) + return w:finish(), nil +end + +return Vox diff --git a/src/Formats/ops/ImageOps/Kernels.luau b/src/Formats/ops/ImageOps/Kernels.luau new file mode 100644 index 0000000..68d0d58 --- /dev/null +++ b/src/Formats/ops/ImageOps/Kernels.luau @@ -0,0 +1,520 @@ +--!strict +--!native +--!optimize 2 +-- ops/ImageOps/Kernels: the hot loops behind ops/ImageOps (native; never throws). Every function trusts its caller +-- (ops/ImageOps validates sizes, formats and buffer lengths first), so all buffer indexes are in range by +-- construction. Samples are addressed by kind: 1 = u8, 2 = u16, 4 = f32 (little endian, as Types.Image buffers). +-- The resampling follows Pillow's Resample.c (separable convolution, horizontal pass first, filter support scaled by +-- the downscale ratio, 22-bit fixed-point coefficients for 8-bit samples) and Geometry.c (affine transforms through +-- pixel centres, bilinear with clamped neighbours); the alpha compositing is Pillow's AlphaComposite.c. +local readu8, writeu8, readu16, writeu16, readf32, writef32 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16, buffer.readf32, buffer.writef32 +local floor, clamp = math.floor, math.clamp + +local K = {} + +-- format ids: rgba8 1, rgba16 2, rgbaf32 3, rgb8 4, gray8 5, gray16 6, graya8 7, alpha8 8 +K.ID = { rgba8 = 1, rgba16 = 2, rgbaf32 = 3, rgb8 = 4, gray8 = 5, gray16 = 6, graya8 = 7, alpha8 = 8 } +K.KIND = { rgba8 = 1, rgba16 = 2, rgbaf32 = 4, rgb8 = 1, gray8 = 1, gray16 = 2, graya8 = 1, alpha8 = 1 } +K.CHANNELS = { rgba8 = 4, rgba16 = 4, rgbaf32 = 4, rgb8 = 3, gray8 = 1, gray16 = 1, graya8 = 2, alpha8 = 1 } + +local function rd(b: buffer, o: number, kind: number): number + if kind == 1 then + return readu8(b, o) + elseif kind == 2 then + return readu16(b, o) + end + return readf32(b, o) +end + +local function wr(b: buffer, o: number, kind: number, v: number) + if kind == 1 then + writeu8(b, o, clamp(floor(v + 0.5), 0, 255)) + elseif kind == 2 then + writeu16(b, o, clamp(floor(v + 0.5), 0, 65535)) + else + writef32(b, o, v) + end +end + +-- ------------------------------------------------------------------------------------------------ convert +-- depth: 8 -> 0..255, 16 -> 0..65535, 0 -> float 0..1 +local DEPTH = { 8, 16, 0, 8, 8, 16, 8, 8 } + +local function depthConv(v: number, from: number, to: number): number + if from == to then + return v + end + if from == 8 then + if to == 16 then + return v * 257 + end + return v / 255 + elseif from == 16 then + if to == 8 then + return (v * 255 + 32767) // 65535 + end + return v / 65535 + end + -- float + if v ~= v then + v = 0 + end + if to == 8 then + return clamp(floor(v * 255 + 0.5), 0, 255) + end + return clamp(floor(v * 65535 + 0.5), 0, 65535) +end + +-- Pillow's L24 luma (19595 R + 38470 G + 7471 B + 0x8000) >> 16, in the source depth +local function luma(r: number, g: number, b: number, depth: number): number + if depth == 0 then + return (r * 19595 + g * 38470 + b * 7471) / 65536 + end + return (r * 19595 + g * 38470 + b * 7471 + 32768) // 65536 +end + +function K.convert(src: buffer, sf: number, dst: buffer, df: number, n: number) + local sd, dd = DEPTH[sf], DEPTH[df] + local smax = if sd == 8 then 255 elseif sd == 16 then 65535 else 1 + local toGray = df == 5 or df == 6 or df == 7 + for i = 0, n - 1 do + local r, g, b, a + if sf == 1 then + local o = i * 4 + r, g, b, a = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2), readu8(src, o + 3) + elseif sf == 2 then + local o = i * 8 + r, g, b, a = readu16(src, o), readu16(src, o + 2), readu16(src, o + 4), readu16(src, o + 6) + elseif sf == 3 then + local o = i * 16 + r, g, b, a = readf32(src, o), readf32(src, o + 4), readf32(src, o + 8), readf32(src, o + 12) + elseif sf == 4 then + local o = i * 3 + r, g, b, a = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2), 255 + elseif sf == 5 then + local v = readu8(src, i) + r, g, b, a = v, v, v, 255 + elseif sf == 6 then + local v = readu16(src, i * 2) + r, g, b, a = v, v, v, 65535 + elseif sf == 7 then + local v = readu8(src, i * 2) + r, g, b, a = v, v, v, readu8(src, i * 2 + 1) + else + r, g, b, a = 255, 255, 255, readu8(src, i) + end + if toGray then + local isGray = sf == 5 or sf == 6 or sf == 7 + local l = if isGray then r else luma(r, g, b, sd) + l = depthConv(l, sd, dd) + if df == 5 then + writeu8(dst, i, l) + elseif df == 6 then + writeu16(dst, i * 2, l) + else + writeu8(dst, i * 2, l) + writeu8(dst, i * 2 + 1, depthConv(a, sd, dd)) + end + elseif df == 8 then + writeu8(dst, i, depthConv(a, sd, 8)) + else + r, g, b = depthConv(r, sd, dd), depthConv(g, sd, dd), depthConv(b, sd, dd) + if df == 1 then + local o = i * 4 + writeu8(dst, o, r) + writeu8(dst, o + 1, g) + writeu8(dst, o + 2, b) + writeu8(dst, o + 3, depthConv(a, sd, dd)) + elseif df == 2 then + local o = i * 8 + writeu16(dst, o, r) + writeu16(dst, o + 2, g) + writeu16(dst, o + 4, b) + writeu16(dst, o + 6, depthConv(a, sd, dd)) + elseif df == 3 then + local o = i * 16 + writef32(dst, o, r) + writef32(dst, o + 4, g) + writef32(dst, o + 8, b) + writef32(dst, o + 12, if a == smax and sd ~= 0 then 1 else depthConv(a, sd, dd)) + else -- rgb8 + local o = i * 3 + writeu8(dst, o, r) + writeu8(dst, o + 1, g) + writeu8(dst, o + 2, b) + end + end + end +end + +-- JPEG-style BT.601 full range +function K.rgbaToYuv(src: buffer, w: number, h: number, dst: buffer) + local cw, ch = (w + 1) // 2, (h + 1) // 2 + local uo, vo = w * h, w * h + cw * ch + for i = 0, w * h - 1 do + local o = i * 4 + local r, g, b = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2) + writeu8(dst, i, clamp(floor(0.299 * r + 0.587 * g + 0.114 * b + 0.5), 0, 255)) + end + for cy = 0, ch - 1 do + for cx = 0, cw - 1 do + local sr, sg, sb, n = 0, 0, 0, 0 + for dy = 0, 1 do + local y = cy * 2 + dy + if y < h then + for dx = 0, 1 do + local x = cx * 2 + dx + if x < w then + local o = (y * w + x) * 4 + sr += readu8(src, o) + sg += readu8(src, o + 1) + sb += readu8(src, o + 2) + n += 1 + end + end + end + end + sr, sg, sb = sr / n, sg / n, sb / n + local i = cy * cw + cx + writeu8(dst, uo + i, clamp(floor(128 - 0.168736 * sr - 0.331264 * sg + 0.5 * sb + 0.5), 0, 255)) + writeu8(dst, vo + i, clamp(floor(128 + 0.5 * sr - 0.418688 * sg - 0.081312 * sb + 0.5), 0, 255)) + end + end +end + +function K.yuvToRgba(src: buffer, w: number, h: number, dst: buffer) + local cw, ch = (w + 1) // 2, (h + 1) // 2 + local uo, vo = w * h, w * h + cw * ch + for y = 0, h - 1 do + local crow = (y // 2) * cw + for x = 0, w - 1 do + local yy = readu8(src, y * w + x) + local ci = crow + x // 2 + local u, v = readu8(src, uo + ci) - 128, readu8(src, vo + ci) - 128 + local o = (y * w + x) * 4 + writeu8(dst, o, clamp(floor(yy + 1.402 * v + 0.5), 0, 255)) + writeu8(dst, o + 1, clamp(floor(yy - 0.344136 * u - 0.714136 * v + 0.5), 0, 255)) + writeu8(dst, o + 2, clamp(floor(yy + 1.772 * u + 0.5), 0, 255)) + writeu8(dst, o + 3, 255) + end + end + local _ = ch +end + +-- ------------------------------------------------------------------------------------------------ geometry +-- flip(src, dst, w, h, bpp, horizontal) +function K.flip(src: buffer, dst: buffer, w: number, h: number, bpp: number, horizontal: boolean) + local stride = w * bpp + if not horizontal then + for y = 0, h - 1 do + buffer.copy(dst, (h - 1 - y) * stride, src, y * stride, stride) + end + return + end + for y = 0, h - 1 do + local row = y * stride + for x = 0, w - 1 do + buffer.copy(dst, row + (w - 1 - x) * bpp, src, row + x * bpp, bpp) + end + end +end + +-- rotate90(src, dst, w, h, bpp, turns): counter-clockwise quarter turns 1..3 +function K.rotate90(src: buffer, dst: buffer, w: number, h: number, bpp: number, turns: number) + for y = 0, h - 1 do + for x = 0, w - 1 do + local ox, oy, ow + if turns == 1 then + ox, oy, ow = y, w - 1 - x, h + elseif turns == 2 then + ox, oy, ow = w - 1 - x, h - 1 - y, w + else + ox, oy, ow = h - 1 - y, x, h + end + local so, d = (y * w + x) * bpp, (oy * ow + ox) * bpp + if bpp == 4 then + buffer.writeu32(dst, d, buffer.readu32(src, so)) + else + buffer.copy(dst, d, src, so, bpp) + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ resample +local function bilinearF(x: number): number + if x < 0 then + x = -x + end + if x < 1 then + return 1 - x + end + return 0 +end + +local function sinc(x: number): number + if x == 0 then + return 1 + end + x *= math.pi + return math.sin(x) / x +end + +local function lanczosF(x: number): number + if x > -3 and x < 3 then + return sinc(x) * sinc(x / 3) + end + return 0 +end + +local function trunc(x: number): number + return if x < 0 then math.ceil(x) else floor(x) +end + +-- Pillow precompute_coeffs: per output index its first input index, tap count and weights (normalised) +export type Coeffs = { start: { number }, count: { number }, weights: { { number } } } + +function K.coeffs(inSize: number, outSize: number, filter: string): Coeffs + local support0 = if filter == "lanczos" then 3 else 1 + local f = if filter == "lanczos" then lanczosF else bilinearF + local scale = inSize / outSize + local filterscale = math.max(scale, 1) + local support = support0 * filterscale + local ss = 1 / filterscale + local start, count, weights = table.create(outSize, 0), table.create(outSize, 0), table.create(outSize) + for xx = 0, outSize - 1 do + local center = (xx + 0.5) * scale + local xmin = math.max(0, trunc(center - support + 0.5)) + local xmax = math.min(inSize, trunc(center + support + 0.5)) - xmin + local w = table.create(math.max(xmax, 0), 0) + local ww = 0 + for x = 0, xmax - 1 do + local v = f((x + xmin - center + 0.5) * ss) + w[x + 1] = v + ww += v + end + if ww ~= 0 then + for x = 1, xmax do + w[x] /= ww + end + end + start[xx + 1], count[xx + 1], weights[xx + 1] = xmin, math.max(xmax, 0), w + end + return { start = start, count = count, weights = weights } +end + +-- one separable pass. horizontal: src w x h -> dst outN x h; vertical: src w x h -> dst w x outN. ch channels of kind. +function K.resamplePass(src: buffer, w: number, h: number, ch: number, kind: number, dst: buffer, outN: number, c: Coeffs, horizontal: boolean) + local start, count, weights = c.start, c.count, c.weights + local size = kind + local fixed = kind == 1 + -- 8-bit: Pillow's 22-bit fixed-point coefficients + local iw: { { number } } = weights + if fixed then + iw = table.create(outN) + for i = 1, outN do + local src0 = weights[i] + local t = table.create(#src0, 0) + for k = 1, #src0 do + local v = src0[k] * 4194304 + t[k] = if v < 0 then math.ceil(v - 0.5) else floor(v + 0.5) + end + iw[i] = t + end + end + if horizontal then + for y = 0, h - 1 do + local row = y * w + for xx = 0, outN - 1 do + local s0, n, wt = start[xx + 1], count[xx + 1], iw[xx + 1] + local o = ((y * outN) + xx) * ch * size + for cc = 0, ch - 1 do + if fixed then + local acc = 2097152 + for k = 0, n - 1 do + acc += readu8(src, (row + s0 + k) * ch + cc) * wt[k + 1] + end + writeu8(dst, o + cc, clamp(acc // 4194304, 0, 255)) + else + local acc = 0 + for k = 0, n - 1 do + acc += rd(src, ((row + s0 + k) * ch + cc) * size, kind) * wt[k + 1] + end + wr(dst, o + cc * size, kind, acc) + end + end + end + end + else + for yy = 0, outN - 1 do + local s0, n, wt = start[yy + 1], count[yy + 1], iw[yy + 1] + for x = 0, w - 1 do + local o = (yy * w + x) * ch * size + for cc = 0, ch - 1 do + if fixed then + local acc = 2097152 + for k = 0, n - 1 do + acc += readu8(src, ((s0 + k) * w + x) * ch + cc) * wt[k + 1] + end + writeu8(dst, o + cc, clamp(acc // 4194304, 0, 255)) + else + local acc = 0 + for k = 0, n - 1 do + acc += rd(src, (((s0 + k) * w + x) * ch + cc) * size, kind) * wt[k + 1] + end + wr(dst, o + cc * size, kind, acc) + end + end + end + end + end + local _ = h +end + +-- nearest: dst pixel (x, y) = src pixel (floor((x + 0.5) * w / ow), ...) +function K.nearest(src: buffer, w: number, h: number, bpp: number, dst: buffer, ow: number, oh: number) + local sx, sy = w / ow, h / oh + for y = 0, oh - 1 do + local iy = math.min(floor((y + 0.5) * sy), h - 1) + for x = 0, ow - 1 do + local ix = math.min(floor((x + 0.5) * sx), w - 1) + buffer.copy(dst, (y * ow + x) * bpp, src, (iy * w + ix) * bpp, bpp) + end + end +end + +-- affine(src, w, h, ch, kind, dst, ow, oh, m): dst pixel centres mapped through m = { a, b, c, d, e, f } to src +-- coordinates (xin = a x + b y + c), bilinear with clamped neighbours; centres outside the source -> zeros (Pillow) +function K.affine(src: buffer, w: number, h: number, ch: number, kind: number, dst: buffer, ow: number, oh: number, m: { number }) + local a, b, c, d, e, f = m[1], m[2], m[3], m[4], m[5], m[6] + local size = kind + for y = 0, oh - 1 do + local py = y + 0.5 + for x = 0, ow - 1 do + local px = x + 0.5 + local xin = a * px + b * py + c - 0.5 + local yin = d * px + e * py + f - 0.5 + local o = (y * ow + x) * ch * size + local x0 = floor(xin) + local y0 = floor(yin) + if xin < -0.5 or xin >= w - 0.5 or yin < -0.5 or yin >= h - 0.5 then + continue -- dst starts zeroed + end + local dx, dy = xin - x0, yin - y0 + local xa, xb = clamp(x0, 0, w - 1), clamp(x0 + 1, 0, w - 1) + local ya, yb = clamp(y0, 0, h - 1), clamp(y0 + 1, 0, h - 1) + for cc = 0, ch - 1 do + local p00 = rd(src, ((ya * w + xa) * ch + cc) * size, kind) + local p01 = rd(src, ((ya * w + xb) * ch + cc) * size, kind) + local p10 = rd(src, ((yb * w + xa) * ch + cc) * size, kind) + local p11 = rd(src, ((yb * w + xb) * ch + cc) * size, kind) + local top = p00 + (p01 - p00) * dx + local bot = p10 + (p11 - p10) * dx + local v = top + (bot - top) * dy + if kind == 1 then + writeu8(dst, o + cc, clamp(floor(v), 0, 255)) -- Pillow truncates + else + wr(dst, o + cc * size, kind, v) + end + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ compositing +-- overRgba8(dst, dw, src, sw, sx, sy, dx, dy, w, h, opacity255): Pillow's alpha_composite of src onto dst, in place +function K.overRgba8(dst: buffer, dw: number, src: buffer, sw: number, sx: number, sy: number, dx: number, dy: number, w: number, h: number, opacity: number) + for y = 0, h - 1 do + for x = 0, w - 1 do + local so = ((sy + y) * sw + sx + x) * 4 + local doff = ((dy + y) * dw + dx + x) * 4 + local sa = readu8(src, so + 3) + if opacity < 255 then + sa = (sa * opacity + 127) // 255 + end + if sa == 0 then + continue + end + local da = readu8(dst, doff + 3) + local blend = da * (255 - sa) + local outa255 = sa * 255 + blend + local coef1 = (sa * 255 * 255 * 128) // outa255 + local coef2 = 255 * 128 - coef1 + for cc = 0, 2 do + local t = readu8(src, so + cc) * coef1 + readu8(dst, doff + cc) * coef2 + 0x80 * 128 + t = ((t // 256) + t) // 256 + writeu8(dst, doff + cc, t // 128) + end + local t = outa255 + 0x80 + writeu8(dst, doff + 3, ((t // 256) + t) // 256) + end + end +end + +-- overFloat: straight-alpha "over" for rgba16 (kind 2) / rgbaf32 (kind 4); max = 65535 or 1 +function K.overFloat(dst: buffer, dw: number, src: buffer, sw: number, sx: number, sy: number, dx: number, dy: number, w: number, h: number, opacity: number, kind: number) + local max = if kind == 2 then 65535 else 1 + local px = 4 * kind + for y = 0, h - 1 do + for x = 0, w - 1 do + local so = ((sy + y) * sw + sx + x) * px + local doff = ((dy + y) * dw + dx + x) * px + local sa = rd(src, so + 3 * kind, kind) / max * opacity + if sa <= 0 then + continue + end + local da = rd(dst, doff + 3 * kind, kind) / max + local oa = sa + da * (1 - sa) + for cc = 0, 2 do + local s = rd(src, so + cc * kind, kind) + local d = rd(dst, doff + cc * kind, kind) + wr(dst, doff + cc * kind, kind, if oa > 0 then (s * sa + d * da * (1 - sa)) / oa else 0) + end + wr(dst, doff + 3 * kind, kind, oa * max) + end + end +end + +-- copyRect: rows of a rectangle (bpp bytes per pixel) +function K.copyRect(dst: buffer, dw: number, src: buffer, sw: number, sx: number, sy: number, dx: number, dy: number, w: number, h: number, bpp: number) + for y = 0, h - 1 do + buffer.copy(dst, ((dy + y) * dw + dx) * bpp, src, ((sy + y) * sw + sx) * bpp, w * bpp) + end +end + +-- premultiply / unpremultiply in place: ch channels, alpha last, kind +function K.premultiply(b: buffer, n: number, ch: number, kind: number, un: boolean) + local max = if kind == 1 then 255 elseif kind == 2 then 65535 else 1 + local px = ch * kind + for i = 0, n - 1 do + local o = i * px + local a = rd(b, o + (ch - 1) * kind, kind) + for cc = 0, ch - 2 do + local v = rd(b, o + cc * kind, kind) + local r + if un then + if a <= 0 then + r = 0 + elseif kind == 4 then + r = v / a + elseif kind == 1 then + r = math.min(255, (v * 255) // a) -- Pillow's rgbA2rgba + else + r = math.min(max, (v * max + a // 2) // a) + end + else + if kind == 4 then + r = v * a + elseif kind == 1 then + local t = v * a + 128 -- Pillow's MULDIV255 + r = ((t // 256) + t) // 256 + else + r = (v * a + max // 2) // max + end + end + wr(b, o + cc * kind, kind, r) + end + end +end + +return K diff --git a/src/Formats/ops/ImageOps/init.luau b/src/Formats/ops/ImageOps/init.luau new file mode 100644 index 0000000..6a5e976 --- /dev/null +++ b/src/Formats/ops/ImageOps/init.luau @@ -0,0 +1,689 @@ +--!strict +-- ops/ImageOps: editing on the standard Image (layer 5.5: core, Types and codecs only). Pixel format conversion, +-- crop, resize (nearest / bilinear / Lanczos-3, as Pillow), flips, quarter turns and arbitrary rotation (bilinear, as +-- Pillow's rotate), alpha compositing (Pillow's alpha_composite for rgba8), premultiplication, pixel access, and +-- helpers for animations (Image.frames). New code; the resampling and compositing follow Pillow's C sources. +-- +-- local Ops = require("@formats/ops/ImageOps") +-- local small = Ops.resize(img, 320, 240, "lanczos") -- every call returns a new Image | nil, Err (never throws) +-- local grey = Ops.convert(img, "gray8") +-- Ops.blit(canvas, sprite, 10, 20) -- in place on canvas, straight-alpha "over" +-- for i, frame in Ops.coalesce(gif) do ... end -- full-canvas frames of an animation +-- +-- Conventions: angles are degrees counter-clockwise and rotate90 turns are counter-clockwise quarter turns (as +-- Pillow). Resizing and rotating filter premultiplied alpha (as Pillow does for RGBA / LA). Grey is Pillow's +-- L = (19595 R + 38470 G + 7471 B + 32768) >> 16. 8 <-> 16 bit is * 257 and +-- (v * 255 + 32767) // 65535; float <-> integer clamps to 0..1 and rounds (no gamma). alpha8 converts to white with +-- that alpha. yuv420p is JPEG-style BT.601 full range (2x2 box chroma); geometric ops on yuv420p go through rgba8. +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local K = require("@formats/ops/ImageOps/Kernels") + +local ImageOps = {} + +local MAX_PIXELS = 2 ^ 26 + +type Image = Types.Image + +-- ------------------------------------------------------------------------------------------------ validation +local function arg(msg: string): (nil, Err.Err) + return nil, Err.new(Err.ARG, msg) +end + +local function isInt(v: any): boolean + return type(v) == "number" and v == v and v % 1 == 0 and v > -2 ^ 31 and v < 2 ^ 31 +end + +local function bytesOf(fmt: string, w: number, h: number): number? + if fmt == "yuv420p" then + return w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2) + end + local bpp = Types.BPP[fmt] + return if bpp then w * h * bpp else nil +end + +-- check(img) -> true | nil, Err: a well-formed Image (known format, sizes, buffer long enough) +local function check(img: any): (boolean?, Err.Err?) + if type(img) ~= "table" or type(img.pixels) ~= "buffer" then + return arg("expected an Image") + end + if not isInt(img.width) or not isInt(img.height) or img.width < 1 or img.height < 1 then + return arg("bad image size") + end + local need = bytesOf(img.format, img.width, img.height) + if not need then + return arg("unknown pixel format " .. tostring(img.format)) + end + if buffer.len(img.pixels) < need then + return arg("pixel buffer too small for " .. img.width .. " x " .. img.height .. " " .. img.format) + end + return true +end +ImageOps.check = check + +local function limit(w: number, h: number, opts: any): (boolean?, Err.Err?) + local max = (type(opts) == "table" and opts.maxPixels) or MAX_PIXELS + if w * h > max then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, max)) + end + return true +end + +-- a new Image of the same kind with a copy of meta's plain fields (source, palette...) but no frames +local function like(img: Image, w: number, h: number, fmt: string?): Image + local out = Types.Image.new(w, h, (fmt or img.format) :: any) + for k, v in img.meta do + out.meta[k] = v + end + out.loops = img.loops + return out +end + +-- ------------------------------------------------------------------------------------------------ basics +-- new(w, h, format?) -> a zero-filled Image | nil, Err +function ImageOps.new(w: number, h: number, format: string?): (Image?, Err.Err?) + local fmt = format or "rgba8" + if not isInt(w) or not isInt(h) or w < 1 or h < 1 then + return arg("bad image size") + end + if not bytesOf(fmt, 1, 1) then + return arg("unknown pixel format " .. tostring(fmt)) + end + local ok, e = limit(w, h, nil) + if not ok then + return nil, e + end + return Types.Image.new(w, h, fmt :: any) +end + +-- copy(img) -> a deep copy of the pixels (frames are shared) +function ImageOps.copy(img: Image): (Image?, Err.Err?) + local ok, e = check(img) + if not ok then + return nil, e + end + local out = like(img, img.width, img.height) + buffer.copy(out.pixels, 0, img.pixels, 0, buffer.len(out.pixels)) + out.frames = img.frames + return out +end + +-- ------------------------------------------------------------------------------------------------ convert +-- convert(img, format) -> a new Image in format (a copy when it is already) +function ImageOps.convert(img: Image, format: string): (Image?, Err.Err?) + local ok, e = check(img) + if not ok then + return nil, e + end + if not bytesOf(format, 1, 1) then + return arg("unknown pixel format " .. tostring(format)) + end + local w, h = img.width, img.height + if img.format == format then + return ImageOps.copy(img) + end + local src = img + if img.format == "yuv420p" then + local rgba = like(img, w, h, "rgba8") + K.yuvToRgba(img.pixels, w, h, rgba.pixels) + if format == "rgba8" then + return rgba + end + src = rgba + end + local out = like(img, w, h, format) + if format == "yuv420p" then + local rgba = src + if src.format ~= "rgba8" then + rgba = like(img, w, h, "rgba8") + K.convert(src.pixels, K.ID[src.format], rgba.pixels, K.ID.rgba8, w * h) + end + K.rgbaToYuv(rgba.pixels, w, h, out.pixels) + return out + end + K.convert(src.pixels, K.ID[src.format], out.pixels, K.ID[format], w * h) + return out +end + +-- ops on yuv420p run on rgba8 and convert back +local function viaRgba(img: Image, f: (Image) -> (Image?, Err.Err?)): (Image?, Err.Err?) + if img.format ~= "yuv420p" then + return f(img) + end + local rgba = ImageOps.convert(img, "rgba8") :: Image + local res, e = f(rgba) + if not res then + return nil, e + end + return ImageOps.convert(res, "yuv420p") +end + +-- ------------------------------------------------------------------------------------------------ geometry +local ALPHA_CH = { rgba8 = 4, rgba16 = 4, rgbaf32 = 4, graya8 = 2 } + +-- crop(img, x, y, w, h) -> the rectangle clipped to the image | nil, Err (empty) +function ImageOps.crop(img: Image, x: number, y: number, w: number, h: number): (Image?, Err.Err?) + local ok, e = check(img) + if not ok then + return nil, e + end + if not (isInt(x) and isInt(y) and isInt(w) and isInt(h)) then + return arg("crop: integer x, y, w, h") + end + local x0, y0 = math.max(0, x), math.max(0, y) + local x1, y1 = math.min(img.width, x + w), math.min(img.height, y + h) + if x1 <= x0 or y1 <= y0 then + return arg("crop: the rectangle is outside the image or empty") + end + return viaRgba(img, function(im: Image): (Image?, Err.Err?) + local bpp = Types.BPP[im.format] :: number + local out = like(im, x1 - x0, y1 - y0) + K.copyRect(out.pixels, out.width, im.pixels, im.width, x0, y0, 0, 0, out.width, out.height, bpp) + return out + end) +end + +-- flip(img, "h" | "v") -> mirrored horizontally (left-right) or vertically (top-bottom) +function ImageOps.flip(img: Image, axis: string): (Image?, Err.Err?) + local ok, e = check(img) + if not ok then + return nil, e + end + if axis ~= "h" and axis ~= "v" then + return arg("flip: axis must be \"h\" or \"v\"") + end + return viaRgba(img, function(im: Image): (Image?, Err.Err?) + local out = like(im, im.width, im.height) + K.flip(im.pixels, out.pixels, im.width, im.height, Types.BPP[im.format] :: number, axis == "h") + return out + end) +end + +-- rotate90(img, turns) -> turned by turns counter-clockwise quarter turns (any integer; negative = clockwise) +function ImageOps.rotate90(img: Image, turns: number): (Image?, Err.Err?) + local ok, e = check(img) + if not ok then + return nil, e + end + if not isInt(turns) then + return arg("rotate90: integer turns") + end + local t = turns % 4 + if t == 0 then + return ImageOps.copy(img) + end + return viaRgba(img, function(im: Image): (Image?, Err.Err?) + local swap = t ~= 2 + local out = like(im, if swap then im.height else im.width, if swap then im.width else im.height) + K.rotate90(im.pixels, out.pixels, im.width, im.height, Types.BPP[im.format] :: number, t) + return out + end) +end + +export type ResizeFilter = "nearest" | "bilinear" | "lanczos" + +-- resize(img, w, h, filter?, opts?) -> w x h (filter default "bilinear"; opts.maxPixels) +function ImageOps.resize(img: Image, w: number, h: number, filter: string?, opts: any?): (Image?, Err.Err?) + local ok, e = check(img) + if not ok then + return nil, e + end + if not isInt(w) or not isInt(h) or w < 1 or h < 1 then + return arg("resize: bad target size") + end + local f = filter or "bilinear" + if f ~= "nearest" and f ~= "bilinear" and f ~= "lanczos" then + return arg("resize: filter must be nearest, bilinear or lanczos") + end + local lok, le = limit(w, h, opts) + if not lok then + return nil, le + end + return viaRgba(img, function(im: Image): (Image?, Err.Err?) + local fmt = im.format + local bpp = Types.BPP[fmt] :: number + local out = like(im, w, h) + if f == "nearest" then + K.nearest(im.pixels, im.width, im.height, bpp, out.pixels, w, h) + return out + end + local kind, ch = K.KIND[fmt], K.CHANNELS[fmt] + local src, sw, sh = im.pixels, im.width, im.height + local alpha = ALPHA_CH[fmt] + if alpha then + src = buffer.create(buffer.len(im.pixels)) + buffer.copy(src, 0, im.pixels) + K.premultiply(src, sw * sh, alpha, kind, false) + end + if w ~= sw then + local tmp = buffer.create(w * sh * bpp) + K.resamplePass(src, sw, sh, ch, kind, tmp, w, K.coeffs(sw, w, f), true) + src, sw = tmp, w + end + if h ~= sh then + K.resamplePass(src, sw, sh, ch, kind, out.pixels, h, K.coeffs(sh, h, f), false) + elseif src == im.pixels or (w == im.width and alpha) then + buffer.copy(out.pixels, 0, im.pixels, 0, w * h * bpp) + return out + else + out.pixels = src + end + if alpha then + K.premultiply(out.pixels, w * h, alpha, kind, true) + end + return out + end) +end + +-- rotate(img, degrees, opts?) -> rotated counter-clockwise about the centre with bilinear sampling (as Pillow's +-- rotate(angle, BILINEAR, expand)): opts.expand (default true) grows the canvas to hold the whole image; uncovered +-- pixels are zero (transparent). opts.maxPixels. +function ImageOps.rotate(img: Image, degrees: number, opts: { expand: boolean?, maxPixels: number? }?): (Image?, Err.Err?) + local ok, e = check(img) + if not ok then + return nil, e + end + if type(degrees) ~= "number" or degrees ~= degrees or degrees == math.huge or degrees == -math.huge then + return arg("rotate: degrees must be a finite number") + end + local expand = not (opts and opts.expand == false) + if degrees % 90 == 0 and (expand or degrees % 180 == 0 or img.width == img.height) then + return ImageOps.rotate90(img, (degrees // 90) % 4) + end + local w, h = img.width, img.height + local ang = -math.rad(degrees) + local function r15(v: number): number + return math.floor(v * 1e15 + 0.5) / 1e15 + end + local m = { r15(math.cos(ang)), r15(math.sin(ang)), 0, r15(-math.sin(ang)), r15(math.cos(ang)), 0 } + local function tr(x: number, y: number): (number, number) + return m[1] * x + m[2] * y + m[3], m[4] * x + m[5] * y + m[6] + end + local cx, cy = w / 2, h / 2 + m[3], m[6] = tr(-cx, -cy) + m[3] += cx + m[6] += cy + local nw, nh = w, h + if expand then + local xs, ys = {}, {} + for _, p in { { 0, 0 }, { w, 0 }, { w, h }, { 0, h } } do + local x, y = tr(p[1], p[2]) + table.insert(xs, x) + table.insert(ys, y) + end + nw = math.ceil(math.max(xs[1], xs[2], xs[3], xs[4])) - math.floor(math.min(xs[1], xs[2], xs[3], xs[4])) + nh = math.ceil(math.max(ys[1], ys[2], ys[3], ys[4])) - math.floor(math.min(ys[1], ys[2], ys[3], ys[4])) + m[3], m[6] = tr(-(nw - w) / 2, -(nh - h) / 2) + end + local lok, le = limit(nw, nh, opts) + if not lok then + return nil, le + end + return viaRgba(img, function(im: Image): (Image?, Err.Err?) + local out = like(im, nw, nh) + local kind = K.KIND[im.format] + local alpha = ALPHA_CH[im.format] + local src = im.pixels + if alpha then + src = buffer.create(buffer.len(im.pixels)) + buffer.copy(src, 0, im.pixels) + K.premultiply(src, w * h, alpha, kind, false) + end + K.affine(src, w, h, K.CHANNELS[im.format], kind, out.pixels, nw, nh, m) + if alpha then + K.premultiply(out.pixels, nw * nh, alpha, kind, true) + end + return out + end) +end + +-- ------------------------------------------------------------------------------------------------ compositing +local RGBA = { rgba8 = true, rgba16 = true, rgbaf32 = true } + +export type BlitOptions = { blend: ("over" | "source")?, opacity: number? } + +-- blit(dst, src, x, y, opts?) -> dst (modified in place) | nil, Err. src is clipped to dst; it is converted to dst's +-- format first when they differ. blend "over" (default: Porter-Duff over, straight alpha; Pillow's alpha_composite +-- for rgba8) or "source" (copy); opts.opacity 0..1 scales src alpha ("over" only). +function ImageOps.blit(dst: Image, src: Image, x: number, y: number, opts: BlitOptions?): (Image?, Err.Err?) + local ok, e = check(dst) + if not ok then + return nil, e + end + local ok2, e2 = check(src) + if not ok2 then + return nil, e2 + end + if not isInt(x) or not isInt(y) then + return arg("blit: integer x, y") + end + local blend = (opts and opts.blend) or "over" + if blend ~= "over" and blend ~= "source" then + return arg("blit: blend must be \"over\" or \"source\"") + end + local opacity = (opts and opts.opacity) or 1 + if type(opacity) ~= "number" or not (opacity >= 0 and opacity <= 1) then + return arg("blit: opacity must be 0..1") + end + -- clip + local sx, sy = math.max(0, -x), math.max(0, -y) + local dx, dy = math.max(0, x), math.max(0, y) + local w = math.min(src.width - sx, dst.width - dx) + local h = math.min(src.height - sy, dst.height - dy) + if w <= 0 or h <= 0 then + return dst + end + if dst.format == "yuv420p" or (blend == "over" and not RGBA[dst.format]) then + -- work on an rgba copy of the region, then write it back in dst's format + local region = ImageOps.crop(dst, dx, dy, w, h) :: Image + local work = if region.format == "rgba8" then region else ImageOps.convert(region, "rgba8") :: Image + ImageOps.blit(work, src, x - dx, y - dy, opts) + if dst.format == "yuv420p" then + local full = ImageOps.convert(dst, "rgba8") :: Image + ImageOps.blit(full, work, dx, dy, { blend = "source" }) + local back = ImageOps.convert(full, "yuv420p") :: Image + buffer.copy(dst.pixels, 0, back.pixels, 0, buffer.len(back.pixels)) + else + local back = ImageOps.convert(work, dst.format) :: Image + K.copyRect(dst.pixels, dst.width, back.pixels, back.width, 0, 0, dx, dy, w, h, Types.BPP[dst.format] :: number) + end + return dst + end + local s = src + if src.format ~= dst.format then + s = ImageOps.convert(src, dst.format) :: Image + end + if blend == "source" then + K.copyRect(dst.pixels, dst.width, s.pixels, s.width, sx, sy, dx, dy, w, h, Types.BPP[dst.format] :: number) + elseif dst.format == "rgba8" then + K.overRgba8(dst.pixels, dst.width, s.pixels, s.width, sx, sy, dx, dy, w, h, math.floor(opacity * 255 + 0.5)) + else + K.overFloat(dst.pixels, dst.width, s.pixels, s.width, sx, sy, dx, dy, w, h, opacity, K.KIND[dst.format]) + end + return dst +end + +-- composite(dst, src, x?, y?, opts?) -> a new Image: a copy of dst with src blitted onto it +function ImageOps.composite(dst: Image, src: Image, x: number?, y: number?, opts: BlitOptions?): (Image?, Err.Err?) + local out, e = ImageOps.copy(dst) + if not out then + return nil, e + end + out.frames = nil + return ImageOps.blit(out, src, x or 0, y or 0, opts) +end + +local function premul(img: Image, un: boolean): (Image?, Err.Err?) + local out, e = ImageOps.copy(img) + if not out then + return nil, e + end + out.frames = nil + local ch = ALPHA_CH[img.format] + if ch then + K.premultiply(out.pixels, img.width * img.height, ch, K.KIND[img.format], un) + end + return out +end + +-- premultiply(img) / unpremultiply(img) -> a new Image (formats without alpha are copied unchanged) +function ImageOps.premultiply(img: Image): (Image?, Err.Err?) + return premul(img, false) +end +function ImageOps.unpremultiply(img: Image): (Image?, Err.Err?) + return premul(img, true) +end + +-- ------------------------------------------------------------------------------------------------ pixels +local MAXV = { rgba8 = 255, rgba16 = 65535, rgbaf32 = 1, rgb8 = 255, gray8 = 255, gray16 = 65535, graya8 = 255, alpha8 = 255, yuv420p = 255 } + +-- getPixel(img, x, y) -> r, g, b, a in the format's scale (0..255, 0..65535 or float); grey gives r = g = b; +-- alpha8 gives white; yuv420p converts to RGB. nil, Err out of range. +function ImageOps.getPixel(img: Image, x: number, y: number): (any, any, number?, number?) + local ok, e = check(img) + if not ok then + return nil, e + end + if not isInt(x) or not isInt(y) or x < 0 or y < 0 or x >= img.width or y >= img.height then + return arg("getPixel: coordinates out of range") + end + local b, f, i = img.pixels, img.format, y * img.width + x + local ru8, ru16, rf = buffer.readu8, buffer.readu16, buffer.readf32 + if f == "rgba8" then + return ru8(b, i * 4), ru8(b, i * 4 + 1), ru8(b, i * 4 + 2), ru8(b, i * 4 + 3) + elseif f == "rgba16" then + return ru16(b, i * 8), ru16(b, i * 8 + 2), ru16(b, i * 8 + 4), ru16(b, i * 8 + 6) + elseif f == "rgbaf32" then + return rf(b, i * 16), rf(b, i * 16 + 4), rf(b, i * 16 + 8), rf(b, i * 16 + 12) + elseif f == "rgb8" then + return ru8(b, i * 3), ru8(b, i * 3 + 1), ru8(b, i * 3 + 2), 255 + elseif f == "gray8" then + local v = ru8(b, i) + return v, v, v, 255 + elseif f == "gray16" then + local v = ru16(b, i * 2) + return v, v, v, 65535 + elseif f == "graya8" then + local v = ru8(b, i * 2) + return v, v, v, ru8(b, i * 2 + 1) + elseif f == "alpha8" then + return 255, 255, 255, ru8(b, i) + end + local one = ImageOps.crop(img, x - x % 2, y - y % 2, 2, 2) :: Image + local rgba = ImageOps.convert(one, "rgba8") :: Image + local j = ((y % 2) * rgba.width + (x % 2)) * 4 + if j + 4 > buffer.len(rgba.pixels) then + j = 0 + end + return ru8(rgba.pixels, j), ru8(rgba.pixels, j + 1), ru8(rgba.pixels, j + 2), 255 +end + +-- setPixel(img, x, y, r, g, b, a?) -> true (in place) | nil, Err. Values in the format's scale (clamped and +-- rounded for integer formats); grey formats take Pillow's luma of r, g, b; a defaults to opaque. Not for yuv420p. +function ImageOps.setPixel(img: Image, x: number, y: number, r: number, g: number, b: number, a: number?): (boolean?, Err.Err?) + local ok, e = check(img) + if not ok then + return nil, e + end + if not isInt(x) or not isInt(y) or x < 0 or y < 0 or x >= img.width or y >= img.height then + return arg("setPixel: coordinates out of range") + end + if type(r) ~= "number" or type(g) ~= "number" or type(b) ~= "number" or (a ~= nil and type(a) ~= "number") then + return arg("setPixel: numeric channels") + end + local f = img.format + if f == "yuv420p" then + return arg("setPixel: not supported on yuv420p (convert to rgba8 first)") + end + local max = MAXV[f] + local al = if a == nil then max else a + local function q(v: number): number + if max == 1 then + return v + end + if v ~= v then + return 0 + end + return math.clamp(math.floor(v + 0.5), 0, max) + end + local px, i = img.pixels, y * img.width + x + local wu8, wu16, wf = buffer.writeu8, buffer.writeu16, buffer.writef32 + local function grey(): number + if max == 1 then + return (r * 19595 + g * 38470 + b * 7471) / 65536 + end + return (q(r) * 19595 + q(g) * 38470 + q(b) * 7471 + 32768) // 65536 + end + if f == "rgba8" then + wu8(px, i * 4, q(r)) + wu8(px, i * 4 + 1, q(g)) + wu8(px, i * 4 + 2, q(b)) + wu8(px, i * 4 + 3, q(al)) + elseif f == "rgba16" then + wu16(px, i * 8, q(r)) + wu16(px, i * 8 + 2, q(g)) + wu16(px, i * 8 + 4, q(b)) + wu16(px, i * 8 + 6, q(al)) + elseif f == "rgbaf32" then + wf(px, i * 16, r) + wf(px, i * 16 + 4, g) + wf(px, i * 16 + 8, b) + wf(px, i * 16 + 12, al) + elseif f == "rgb8" then + wu8(px, i * 3, q(r)) + wu8(px, i * 3 + 1, q(g)) + wu8(px, i * 3 + 2, q(b)) + elseif f == "gray8" then + wu8(px, i, grey()) + elseif f == "gray16" then + wu16(px, i * 2, grey()) + elseif f == "graya8" then + wu8(px, i * 2, grey()) + wu8(px, i * 2 + 1, q(al)) + else + wu8(px, i, q(al)) + end + return true +end + +-- fill(img, r, g, b, a?) -> img (in place) with every pixel set (values as setPixel) +function ImageOps.fill(img: Image, r: number, g: number, b: number, a: number?): (Image?, Err.Err?) + local ok, e = check(img) + if not ok then + return nil, e + end + if img.format == "yuv420p" then + return arg("fill: not supported on yuv420p") + end + local sok, se = ImageOps.setPixel(img, 0, 0, r, g, b, a) + if not sok then + return nil, se + end + local bpp = Types.BPP[img.format] :: number + local n = img.width * img.height * bpp + local filled = bpp + while filled < n do + local c = math.min(filled, n - filled) + buffer.copy(img.pixels, filled, img.pixels, 0, c) + filled += c + end + return img +end + +-- ------------------------------------------------------------------------------------------------ animation +-- frameCount(img) -> the number of frames (1 for a still image) +function ImageOps.frameCount(img: Image): number + if type(img) == "table" and type(img.frames) == "table" and #img.frames > 0 then + return #img.frames + end + return 1 +end + +-- durations(img) -> { seconds } per frame ({ 0 } for a still image) +function ImageOps.durations(img: Image): { number } + local out = {} + if type(img) == "table" and type(img.frames) == "table" and #img.frames > 0 then + for i, f in img.frames do + out[i] = if type(f.delay) == "number" then f.delay else 0 + end + return out + end + return { 0 } +end + +-- coalesce(img) -> { Image } | nil, Err: every frame composited onto a width x height canvas (rgba8, or rgba16 / +-- rgbaf32 when the image is), honouring each frame's x, y, blend ("over" / "source") and the previous frame's +-- dispose ("none" keeps the canvas, "background" clears the frame's rectangle to transparent, "previous" restores +-- the canvas from before the frame). A still image gives { img }. +function ImageOps.coalesce(img: Image): ({ Image }?, Err.Err?) + local ok, e = check(img) + if not ok then + return nil, e + end + local frames = img.frames + if type(frames) ~= "table" or #frames == 0 then + return { img } + end + local fmt = if RGBA[img.format] then img.format else "rgba8" + local canvas = Types.Image.new(img.width, img.height, fmt :: any) + local bpp = Types.BPP[fmt] :: number + local out = {} + for i, f in frames do + if type(f) ~= "table" then + return arg("coalesce: frame " .. i .. " is not a Frame") + end + local fi = f.image + local fok, fe = check(fi) + if not fok then + return nil, Err.new(Err.ARG, "coalesce: frame " .. i .. ": " .. (fe :: Err.Err).message) + end + local fx, fy = if isInt(f.x) then f.x else 0, if isInt(f.y) then f.y else 0 + local saved: buffer? = nil + if f.dispose == "previous" then + local sb = buffer.create(buffer.len(canvas.pixels)) + buffer.copy(sb, 0, canvas.pixels) + saved = sb + end + local bok, be = ImageOps.blit(canvas, fi, fx, fy, { blend = if f.blend == "source" then "source" else "over" }) + if not bok then + return nil, be + end + local snap = Types.Image.new(img.width, img.height, fmt :: any) + buffer.copy(snap.pixels, 0, canvas.pixels) + for k, v in img.meta do + snap.meta[k] = v + end + snap.meta.delay = f.delay + out[i] = snap + if f.dispose == "background" then + local x0, y0 = math.max(0, fx), math.max(0, fy) + local x1, y1 = math.min(img.width, fx + fi.width), math.min(img.height, fy + fi.height) + for y = y0, y1 - 1 do + if x1 > x0 then + buffer.fill(canvas.pixels, (y * img.width + x0) * bpp, 0, (x1 - x0) * bpp) + end + end + elseif saved then + canvas.pixels = saved + end + end + return out +end + +-- fromFrames(images, delays?) -> an animated Image: img.frames = the images as full-canvas frames (x = y = 0, +-- dispose "none", blend "source"), img.pixels = a copy of frame 1. delays: a number (every frame) or { seconds } +-- (default 0.1). All images need the same size and format. +function ImageOps.fromFrames(images: { Image }, delays: (number | { number })?): (Image?, Err.Err?) + if type(images) ~= "table" or #images == 0 then + return arg("fromFrames: a non-empty list of Images") + end + local first = images[1] + local ok, e = check(first) + if not ok then + return nil, e + end + local frames = {} + for i, im in images do + local iok, ie = check(im) + if not iok then + return nil, ie + end + if im.width ~= first.width or im.height ~= first.height or im.format ~= first.format then + return arg("fromFrames: frame " .. i .. " differs in size or format from frame 1") + end + local d = 0.1 + if type(delays) == "number" then + d = delays + elseif type(delays) == "table" and type(delays[i]) == "number" then + d = delays[i] + end + frames[i] = { image = im, delay = d, x = 0, y = 0, dispose = "none", blend = "source" } + end + local out = like(first, first.width, first.height) + buffer.copy(out.pixels, 0, first.pixels, 0, buffer.len(out.pixels)) + out.frames = frames :: any + out.loops = 0 + return out +end + +return ImageOps diff --git a/src/Formats/ops/LayerOps.luau b/src/Formats/ops/LayerOps.luau new file mode 100644 index 0000000..bf4b242 --- /dev/null +++ b/src/Formats/ops/LayerOps.luau @@ -0,0 +1,101 @@ +--!strict +-- ops/LayerOps: editing on the Layered type (PSD, Aseprite): flatten a layer tree (or one animation frame) to an +-- rgba8 Image with the blend modes of codecs/Blend, opacity, groups (isolated, or pass-through), clipping layers and +-- grey layer masks; every frame as an animated Image; walking the leaves. +-- +-- local LayerOps = require("@formats/ops/LayerOps") +-- local img = LayerOps.flatten(layered) -- frame 1 / the layers +-- local img3 = LayerOps.flatten(layered, { frame = 3 }) +-- local anim = LayerOps.flattenFrames(layered) -- an Image with frames (delays from the Layered frames) +-- for layer, depth in LayerOps.leaves(layered.layers) do ... end +-- +-- Never throws: bad values return nil, Err.ARG. +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Blend = require("@formats/codecs/Blend") + +local LayerOps = {} + +export type FlattenOptions = { + frame: number?, -- 1-based animation frame (default: layered.layers, which is frame 1) + hidden: boolean?, -- include hidden layers (default false) + background: { number }?, -- r, g, b, a 0..255 under everything (default transparent) +} + +-- flatten(layered, opts?) -> rgba8 Image (layered.width x layered.height) | nil, Err +function LayerOps.flatten(layered: Types.Layered, opts: FlattenOptions?): (Types.Image?, Err.Err?) + if type(layered) ~= "table" or type(layered.width) ~= "number" or type(layered.height) ~= "number" or type(layered.layers) ~= "table" then + return nil, Err.new(Err.ARG, "flatten: needs a Layered value") + end + local o: FlattenOptions = opts or {} + local w, h = math.floor(layered.width), math.floor(layered.height) + if w < 0 or h < 0 or w * h > 2 ^ 28 then + return nil, Err.new(Err.ARG, "flatten: bad size") + end + local layers = layered.layers + if o.frame then + local f = if type(layered.frames) == "table" then layered.frames[o.frame] else nil + if f == nil and o.frame ~= 1 then + return nil, Err.new(Err.ARG, "flatten: no frame " .. tostring(o.frame)) + end + if f then + layers = f.layers + end + end + local img = Types.Image.new(w, h) + local bg = o.background + if type(bg) == "table" then + local v = (bg[1] or 0) + (bg[2] or 0) * 256 + (bg[3] or 0) * 65536 + (bg[4] or 255) * 16777216 + for i = 0, w * h - 1 do + buffer.writeu32(img.pixels, i * 4, v) + end + end + Blend.flatten(layers, img.pixels, w, h, o.hidden == true) + return img, nil +end + +-- flattenFrames(layered, opts?) -> an rgba8 Image whose frames are every flattened frame (frame 1 is the image) +function LayerOps.flattenFrames(layered: Types.Layered, opts: FlattenOptions?): (Types.Image?, Err.Err?) + local first, err = LayerOps.flatten(layered, opts) + if not first then + return nil, err + end + local frames = if type(layered.frames) == "table" then layered.frames else {} + if #frames == 0 then + return first, nil + end + local list: { Types.Frame } = {} + for i, f in frames do + local o: FlattenOptions = table.clone(opts or {}) :: any + o.frame = i + local img = if i == 1 then first else LayerOps.flatten(layered, o) + if not img then + return nil, Err.new(Err.ARG, "flatten: frame " .. i) + end + list[i] = { image = img, delay = tonumber(f.delay) or 0.1, x = 0, y = 0, dispose = "none", blend = "source" } + end + first.frames = list + return first, nil +end + +-- leaves(layers) -> iterator of (layer, depth) over the non-group layers of a tree, bottom to top +function LayerOps.leaves(layers: { Types.Layer }): () -> (Types.Layer?, number?) + local stack: { { any } } = { { layers, 0, 0 } } + return function(): (Types.Layer?, number?) + while #stack > 0 do + local top = stack[#stack] + top[2] += 1 + local l = top[1][top[2]] + if l == nil then + table.remove(stack) + elseif type(l.children) == "table" then + table.insert(stack, { l.children, 0, top[3] + 1 }) + else + return l, top[3] + end + end + return nil, nil + end +end + +return LayerOps diff --git a/src/Formats/ops/MeshOps/Greedy.luau b/src/Formats/ops/MeshOps/Greedy.luau new file mode 100644 index 0000000..26ddb50 --- /dev/null +++ b/src/Formats/ops/MeshOps/Greedy.luau @@ -0,0 +1,167 @@ +--!strict +--!native +-- ops/MeshOps/Greedy: greedy meshing of a dense voxel grid (one byte per cell, 0 = empty): for each axis and each +-- slice between two layers of cells, the exposed faces are masked by palette index, and runs of equal faces are merged +-- into maximal rectangles (Mikola Lysenko's "Meshing in a Minecraft game", 2012). Faces between two filled cells are +-- hidden whatever their indices. Output: 4 vertices and 2 triangles per rectangle, counter-clockwise seen from the +-- outside. Never throws; the caller checks buffer.len(data) >= sx * sy * sz. +local Greedy = {} + +local readu8, readi32, writei32 = buffer.readu8, buffer.readi32, buffer.writei32 +local writef32, writeu8, writeu32 = buffer.writef32, buffer.writeu8, buffer.writeu32 + +export type Out = { + positions: buffer, -- f32 x3 per vertex + normals: buffer, -- f32 x3 per vertex + index: buffer, -- u8 palette index per vertex + indices: buffer, -- u32, 6 per quad + vertices: number, + quads: number, +} + +-- run(data, sx, sy, sz, ox, oy, oz, scale) -> Out: vertex position = (cell corner + (ox, oy, oz)) * scale +function Greedy.run(data: buffer, sx: number, sy: number, sz: number, ox: number, oy: number, oz: number, scale: number): Out + local cap = 1024 + local pos = buffer.create(cap * 48) + local nrm = buffer.create(cap * 48) + local idx = buffer.create(cap * 4) + local tri = buffer.create(cap * 24) + local quads = 0 + local maxFace = math.max(sx * sy, sy * sz, sz * sx) + local mask = buffer.create(maxFace * 4) + local corner = { 0, 0, 0 } + for d = 0, 2 do + -- u, v: the two other axes, cyclic so that e_u x e_v = e_d + local u, v = (d + 1) % 3, (d + 2) % 3 + local nd = if d == 0 then sx elseif d == 1 then sy else sz + local nu = if u == 0 then sx elseif u == 1 then sy else sz + local nv = if v == 0 then sx elseif v == 1 then sy else sz + local std = if d == 0 then 1 elseif d == 1 then sx else sx * sy + local stu = if u == 0 then 1 elseif u == 1 then sx else sx * sy + local stv = if v == 0 then 1 elseif v == 1 then sx else sx * sy + for slice = -1, nd - 1 do + -- the mask of faces between layer slice and slice + 1: +index (faces +d, owned by slice), -index (faces -d) + local any = false + for j = 0, nv - 1 do + for i = 0, nu - 1 do + local base = i * stu + j * stv + local a = if slice >= 0 then readu8(data, base + slice * std) else 0 + local b = if slice + 1 < nd then readu8(data, base + (slice + 1) * std) else 0 + local m = 0 + if a ~= 0 and b == 0 then + m = a + elseif a == 0 and b ~= 0 then + m = -b + end + if m ~= 0 then + any = true + end + writei32(mask, (i + j * nu) * 4, m) + end + end + if any then + for j = 0, nv - 1 do + local i = 0 + while i < nu do + local m = readi32(mask, (i + j * nu) * 4) + if m == 0 then + i += 1 + else + local w = 1 + while i + w < nu and readi32(mask, (i + w + j * nu) * 4) == m do + w += 1 + end + local h = 1 + local grow = true + while j + h < nv and grow do + for k = 0, w - 1 do + if readi32(mask, (i + k + (j + h) * nu) * 4) ~= m then + grow = false + break + end + end + if grow then + h += 1 + end + end + for jj = j, j + h - 1 do + for k = 0, w - 1 do + writei32(mask, (i + k + jj * nu) * 4, 0) + end + end + -- emit the rectangle + if quads == cap then + local ncap = cap * 2 + local function grow2(b: buffer, per: number): buffer + local nb = buffer.create(ncap * per) + buffer.copy(nb, 0, b, 0, cap * per) + return nb + end + pos, nrm, idx, tri = grow2(pos, 48), grow2(nrm, 48), grow2(idx, 4), grow2(tri, 24) + cap = ncap + end + corner[d + 1] = slice + 1 + corner[u + 1] = i + corner[v + 1] = j + local cx, cy, cz = corner[1], corner[2], corner[3] + -- the u and v edge vectors + local ux = if u == 0 then w else 0 + local uy = if u == 1 then w else 0 + local uz = if u == 2 then w else 0 + local vx = if v == 0 then h else 0 + local vy = if v == 1 then h else 0 + local vz = if v == 2 then h else 0 + local nsign = if m > 0 then 1 else -1 + local nx = if d == 0 then nsign else 0 + local ny = if d == 1 then nsign else 0 + local nz = if d == 2 then nsign else 0 + local col = if m > 0 then m else -m + local vb = quads * 48 + local px0, py0, pz0 = (cx + ox) * scale, (cy + oy) * scale, (cz + oz) * scale + writef32(pos, vb, px0) + writef32(pos, vb + 4, py0) + writef32(pos, vb + 8, pz0) + writef32(pos, vb + 12, px0 + ux * scale) + writef32(pos, vb + 16, py0 + uy * scale) + writef32(pos, vb + 20, pz0 + uz * scale) + writef32(pos, vb + 24, px0 + (ux + vx) * scale) + writef32(pos, vb + 28, py0 + (uy + vy) * scale) + writef32(pos, vb + 32, pz0 + (uz + vz) * scale) + writef32(pos, vb + 36, px0 + vx * scale) + writef32(pos, vb + 40, py0 + vy * scale) + writef32(pos, vb + 44, pz0 + vz * scale) + for k = 0, 3 do + writef32(nrm, vb + k * 12, nx) + writef32(nrm, vb + k * 12 + 4, ny) + writef32(nrm, vb + k * 12 + 8, nz) + writeu8(idx, quads * 4 + k, col) + end + local v0 = quads * 4 + local ib = quads * 24 + if m > 0 then + writeu32(tri, ib, v0) + writeu32(tri, ib + 4, v0 + 1) + writeu32(tri, ib + 8, v0 + 2) + writeu32(tri, ib + 12, v0) + writeu32(tri, ib + 16, v0 + 2) + writeu32(tri, ib + 20, v0 + 3) + else + writeu32(tri, ib, v0) + writeu32(tri, ib + 4, v0 + 2) + writeu32(tri, ib + 8, v0 + 1) + writeu32(tri, ib + 12, v0) + writeu32(tri, ib + 16, v0 + 3) + writeu32(tri, ib + 20, v0 + 2) + end + quads += 1 + i += w + end + end + end + end + end + end + return { positions = pos, normals = nrm, index = idx, indices = tri, vertices = quads * 4, quads = quads } +end + +return Greedy diff --git a/src/Formats/ops/MeshOps/init.luau b/src/Formats/ops/MeshOps/init.luau new file mode 100644 index 0000000..4bcfacd --- /dev/null +++ b/src/Formats/ops/MeshOps/init.luau @@ -0,0 +1,1087 @@ +--!strict +-- ops/MeshOps: editing meshes in the standard Scene type (Types.luau): triangulate (strips, fans, n-gons by fan or ear +-- clipping), transform (positions, normals, tangents; winding kept for mirrors), computeNormals (area weighted, or flat), +-- computeTangents (per-triangle UV derivatives, Lengyel 2001, Gram-Schmidt + handedness in w), weld (exact or within an +-- epsilon), bounds, merge (a whole scene baked into world space, one primitive or one per material), unit and up-axis +-- changes, and greedy meshing of voxel grids (VOX: voxelsToPrimitive, meshVoxels). +-- Every function takes / returns Primitives and Scenes as decoded by the model formats; inputs may use any accessor type +-- (f32, unorm8, snorm16, ...): outputs are f32 attributes and u32 indices. Bad arguments return nil, Err (never throw). +-- +-- local MeshOps = require("@formats/ops/MeshOps") -- F.ops.mesh in the api (when it lists ops) +-- local prim = MeshOps.merge(scene) -- one triangle primitive in world space +-- MeshOps.computeNormals(prim) +-- MeshOps.meshVoxels(voxScene) -- greedy meshes for every voxel shape +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Greedy = require("@formats/ops/MeshOps/Greedy") + +local MeshOps = {} + +type Accessor = Types.Accessor +type Primitive = Types.Primitive +type Scene = Types.Scene + +local Scene = Types.Scene +local readf32, writef32 = buffer.readf32, buffer.writef32 +local readu32, writeu32 = buffer.readu32, buffer.writeu32 + +-- ------------------------------------------------------------------------------------------------ accessors +-- f32(acc) -> the accessor as f32 (the same accessor when it already is), nil for a broken one +function MeshOps.f32(acc: Accessor): Accessor? + if acc.type == "f32" then + return acc + end + local get = Scene.reader(acc) + if not get then + return nil + end + local n, c = acc.count, acc.components + local out = buffer.create(n * c * 4) + for i = 0, n - 1 do + for k = 0, c - 1 do + writef32(out, (i * c + k) * 4, get(i, k)) + end + end + local a = Scene.accessor(out, "f32", c, n) + a.matrix = acc.matrix + return a +end + +-- the index list of a primitive (u32 buffer, count): its indices, or 0 .. n - 1 +local function indexBuffer(prim: Primitive): (buffer, number) + local ind = prim.indices + if ind then + if ind.type == "u32" and ind.components == 1 then + return ind.data, ind.count + end + local get = Scene.reader(ind) + local out = buffer.create(ind.count * 4) + if get then + for i = 0, ind.count - 1 do + writeu32(out, i * 4, get(i, 0)) + end + end + return out, ind.count + end + local pos = prim.attributes.POSITION + local n = if pos then pos.count else 0 + local out = buffer.create(n * 4) + for i = 0, n - 1 do + writeu32(out, i * 4, i) + end + return out, n +end + +local function vertexCount(prim: Primitive): number + local pos = prim.attributes.POSITION + return if pos then pos.count else 0 +end + +local function checkPrim(prim: any): Err.Err? + if type(prim) ~= "table" or type(prim.attributes) ~= "table" then + return Err.new(Err.ARG, "expected a Primitive") + end + local pos = prim.attributes.POSITION + if not pos or type(pos.data) ~= "buffer" or pos.components < 3 then + return Err.new(Err.ARG, "primitive without a POSITION accessor") + end + local n = pos.count + for name, a in prim.attributes do + local size = Types.COMPONENT_SIZE[a.type] + if not size or type(a.data) ~= "buffer" or buffer.len(a.data) < a.count * a.components * size then + return Err.new(Err.ARG, "attribute " .. tostring(name) .. ": bad accessor") + end + if a.count ~= n then + return Err.new(Err.ARG, "attribute " .. tostring(name) .. ": count differs from POSITION") + end + end + if prim.indices then + local ind = prim.indices + local size = Types.COMPONENT_SIZE[ind.type] + if not size or type(ind.data) ~= "buffer" or buffer.len(ind.data) < ind.count * size then + return Err.new(Err.ARG, "bad indices accessor") + end + local get = Scene.reader(ind) + if get then + for i = 0, ind.count - 1 do + if get(i, 0) >= n then + return Err.new(Err.ARG, "index out of range") + end + end + end + end + return nil +end +MeshOps.check = checkPrim + +-- ------------------------------------------------------------------------------------------------ triangulate +-- ear clipping of one polygon (corner indices into px / py / pz) -> triangles appended to out; fan when it gets stuck +local function earclip(poly: { number }, P: (number, number) -> number, out: { number }) + local k = #poly + if k < 3 then + return + end + if k == 3 then + table.insert(out, poly[1]) + table.insert(out, poly[2]) + table.insert(out, poly[3]) + return + end + -- Newell normal -> the projection plane (drop the dominant axis) + local nx, ny, nz = 0, 0, 0 + for a = 1, k do + local i, j = poly[a], poly[a % k + 1] + local xi, yi, zi = P(i, 0), P(i, 1), P(i, 2) + local xj, yj, zj = P(j, 0), P(j, 1), P(j, 2) + nx += (yi - yj) * (zi + zj) + ny += (zi - zj) * (xi + xj) + nz += (xi - xj) * (yi + yj) + end + local ax, ay, az = math.abs(nx), math.abs(ny), math.abs(nz) + local cu, cv, sign = 0, 1, nz + if ax >= ay and ax >= az then + cu, cv, sign = 1, 2, nx + elseif ay >= az then + cu, cv, sign = 2, 0, ny + end + local function uv(i: number): (number, number) + return P(i, cu), P(i, cv) + end + local s = if sign < 0 then -1 else 1 + local ring = table.clone(poly) + local guard = 0 + while #ring > 3 and guard < k * k do + guard += 1 + local n = #ring + local clipped = false + for a = 1, n do + local ia, ib, ic = ring[(a - 2) % n + 1], ring[a], ring[a % n + 1] + local ax2, ay2 = uv(ia) + local bx, by = uv(ib) + local cx, cy = uv(ic) + local cross = ((bx - ax2) * (cy - ay2) - (by - ay2) * (cx - ax2)) * s + if cross > 0 then + local inside = false + for q = 1, n do + local iq = ring[q] + if iq ~= ia and iq ~= ib and iq ~= ic then + local qx, qy = uv(iq) + local d1 = ((bx - ax2) * (qy - ay2) - (by - ay2) * (qx - ax2)) * s + local d2 = ((cx - bx) * (qy - by) - (cy - by) * (qx - bx)) * s + local d3 = ((ax2 - cx) * (qy - cy) - (ay2 - cy) * (qx - cx)) * s + if d1 >= 0 and d2 >= 0 and d3 >= 0 then + inside = true + break + end + end + end + if not inside then + table.insert(out, ia) + table.insert(out, ib) + table.insert(out, ic) + table.remove(ring, a) + clipped = true + break + end + end + end + if not clipped then + break + end + end + -- whatever is left (3 corners, or a degenerate / self-intersecting rest): a fan + for a = 2, #ring - 1 do + table.insert(out, ring[1]) + table.insert(out, ring[a]) + table.insert(out, ring[a + 1]) + end +end + +local function u32(list: { number }): Accessor + local n = #list + local b = buffer.create(n * 4) + for i = 1, n do + writeu32(b, (i - 1) * 4, list[i]) + end + return Scene.accessor(b, "u32", 1, n) +end + +-- triangulate(prim, opts?) -> a new triangle Primitive (the same attributes) | nil, Err. opts.method: "earclip" +-- (default; handles concave n-gons) or "fan". Strips and fans are unrolled (strip winding alternates as glTF says). +-- Lines and points come back unchanged. +function MeshOps.triangulate(prim: Primitive, opts: { method: string? }?): (Primitive?, Err.Err?) + local err = checkPrim(prim) + if err then + return nil, err + end + local mode = prim.mode or "triangles" + if mode == "lines" or mode == "points" or mode == "line_strip" or mode == "line_loop" then + return prim, nil + end + local method = opts and opts.method or "earclip" + local ib, n = indexBuffer(prim) + local out: { number } = {} + if mode == "triangles" then + local m = n - n % 3 + for i = 0, m - 1 do + out[i + 1] = readu32(ib, i * 4) + end + elseif mode == "triangle_strip" then + for i = 0, n - 3 do + local a, b, c = readu32(ib, i * 4), readu32(ib, i * 4 + 4), readu32(ib, i * 4 + 8) + if i % 2 == 1 then + a, b = b, a + end + if a ~= b and b ~= c and a ~= c then + table.insert(out, a) + table.insert(out, b) + table.insert(out, c) + end + end + elseif mode == "triangle_fan" then + for i = 1, n - 2 do + table.insert(out, readu32(ib, 0)) + table.insert(out, readu32(ib, i * 4)) + table.insert(out, readu32(ib, i * 4 + 4)) + end + elseif mode == "polygons" then + local faces = prim.faces + if not faces then + return nil, Err.new(Err.ARG, "polygons primitive without faces") + end + local getf = Scene.reader(faces) + if not getf then + return nil, Err.new(Err.ARG, "bad faces accessor") + end + local pos = MeshOps.f32(prim.attributes.POSITION) :: Accessor + local pd = pos.data + local P = function(i: number, c: number): number + return readf32(pd, (i * 3 + c) * 4) + end + local at = 0 + for f = 0, faces.count - 1 do + local k = getf(f, 0) + if at + k > n then + return nil, Err.new(Err.ARG, "faces run past the indices") + end + if k >= 3 then + if method == "fan" or k == 3 then + for a = 1, k - 2 do + table.insert(out, readu32(ib, at * 4)) + table.insert(out, readu32(ib, (at + a) * 4)) + table.insert(out, readu32(ib, (at + a + 1) * 4)) + end + else + local poly = table.create(k) + for a = 0, k - 1 do + poly[a + 1] = readu32(ib, (at + a) * 4) + end + earclip(poly, P, out) + end + end + at += k + end + else + return nil, Err.new(Err.ARG, "unknown mode " .. tostring(mode)) + end + return { + attributes = prim.attributes, + indices = u32(out), + mode = "triangles", + material = prim.material, + targets = prim.targets, + extras = prim.extras, + }, nil +end + +-- ------------------------------------------------------------------------------------------------ transform +local function det3(m: { number }): number + return m[1] * (m[6] * m[11] - m[10] * m[7]) - m[5] * (m[2] * m[11] - m[10] * m[3]) + m[9] * (m[2] * m[7] - m[6] * m[3]) +end + +-- the inverse transpose of m's 3 x 3 part (column-major 9), for normals +local function normalMatrix(m: { number }): { number } + local a, b, c = m[1], m[5], m[9] + local d, e, f = m[2], m[6], m[10] + local g, h, i = m[3], m[7], m[11] + local det = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g) + if det == 0 then + det = 1 + end + local k = 1 / det + -- cofactor matrix / det (= inverse transpose), column-major + return { + (e * i - f * h) * k, -(b * i - c * h) * k, (b * f - c * e) * k, + -(d * i - f * g) * k, (a * i - c * g) * k, -(a * f - c * d) * k, + (d * h - e * g) * k, -(a * h - b * g) * k, (a * e - b * d) * k, + } +end + +-- transform(prim, matrix) -> prim (changed in place: POSITION, NORMAL, TANGENT become f32; morph target deltas too). +-- A mirroring matrix (negative determinant) also reverses the triangle winding so faces stay front-facing. +function MeshOps.transform(prim: Primitive, m: { number }): (Primitive?, Err.Err?) + local err = checkPrim(prim) + if err then + return nil, err + end + if type(m) ~= "table" or #m ~= 16 then + return nil, Err.new(Err.ARG, "expected a column-major 4x4 matrix (16 numbers)") + end + local nm = normalMatrix(m) + local function points(acc: Accessor?, w: number): Accessor? + if not acc then + return nil + end + local a = MeshOps.f32(acc) :: Accessor + if a == acc then + a = Scene.accessor(buffer.create(buffer.len(acc.data)), "f32", acc.components, acc.count) + buffer.copy(a.data, 0, acc.data, 0, acc.count * acc.components * 4) + end + local d, c = a.data, a.components + for i = 0, a.count - 1 do + local o = i * c * 4 + local x, y, z = readf32(d, o), readf32(d, o + 4), readf32(d, o + 8) + writef32(d, o, m[1] * x + m[5] * y + m[9] * z + m[13] * w) + writef32(d, o + 4, m[2] * x + m[6] * y + m[10] * z + m[14] * w) + writef32(d, o + 8, m[3] * x + m[7] * y + m[11] * z + m[15] * w) + end + return a + end + local function dirs(acc: Accessor?, mat: { number }, normalize: boolean, flipW: boolean): Accessor? + if not acc then + return nil + end + local a = MeshOps.f32(acc) :: Accessor + if a == acc then + a = Scene.accessor(buffer.create(buffer.len(acc.data)), "f32", acc.components, acc.count) + buffer.copy(a.data, 0, acc.data, 0, acc.count * acc.components * 4) + end + local d, c = a.data, a.components + for i = 0, a.count - 1 do + local o = i * c * 4 + local x, y, z = readf32(d, o), readf32(d, o + 4), readf32(d, o + 8) + local nx = mat[1] * x + mat[4] * y + mat[7] * z + local ny = mat[2] * x + mat[5] * y + mat[8] * z + local nz = mat[3] * x + mat[6] * y + mat[9] * z + if normalize then + local l = math.sqrt(nx * nx + ny * ny + nz * nz) + if l > 0 then + nx, ny, nz = nx / l, ny / l, nz / l + end + end + writef32(d, o, nx) + writef32(d, o + 4, ny) + writef32(d, o + 8, nz) + if flipW and c >= 4 then + writef32(d, o + 12, -readf32(d, o + 12)) + end + end + return a + end + local mirror = det3(m) < 0 + local m3 = { m[1], m[2], m[3], m[5], m[6], m[7], m[9], m[10], m[11] } + local attrs = prim.attributes + attrs.POSITION = points(attrs.POSITION, 1) :: Accessor + attrs.NORMAL = dirs(attrs.NORMAL, nm, true, false) + attrs.TANGENT = dirs(attrs.TANGENT, m3, true, mirror) + if prim.targets then + for _, t in prim.targets do + t.POSITION = points(t.POSITION, 0) + t.NORMAL = dirs(t.NORMAL, nm, false, false) + t.TANGENT = dirs(t.TANGENT, m3, false, false) + end + end + if mirror and (prim.mode == "triangles" or prim.mode == nil) then + local ib, n = indexBuffer(prim) + local nb = buffer.create(n * 4) + buffer.copy(nb, 0, ib, 0, n * 4) + for t = 0, n // 3 - 1 do + local o = t * 12 + local b = readu32(nb, o + 4) + writeu32(nb, o + 4, readu32(nb, o + 8)) + writeu32(nb, o + 8, b) + end + prim.indices = Scene.accessor(nb, "u32", 1, n) + elseif mirror and prim.mode == "polygons" and prim.faces then + local ib, n = indexBuffer(prim) + local nb = buffer.create(n * 4) + local getf = Scene.reader(prim.faces) + local at = 0 + if getf then + for f = 0, prim.faces.count - 1 do + local k = getf(f, 0) + for a = 0, k - 1 do + if at + a < n then + writeu32(nb, (at + a) * 4, readu32(ib, (at + k - 1 - a) * 4)) + end + end + at += k + end + end + prim.indices = Scene.accessor(nb, "u32", 1, n) + end + return prim, nil +end + +-- ------------------------------------------------------------------------------------------------ normals / tangents +-- computeNormals(prim, opts?) -> prim with NORMAL (f32, area-weighted average of the triangle normals of each vertex) | +-- nil, Err. opts.flat = true: split every triangle's corners first (unwelded, one face normal per corner). Non-triangle +-- modes are triangulated first (the returned primitive is then a new one). +function MeshOps.computeNormals(prim: Primitive, opts: { flat: boolean? }?): (Primitive?, Err.Err?) + local p = prim + if (prim.mode or "triangles") ~= "triangles" then + local t, err = MeshOps.triangulate(prim) + if not t then + return nil, err + end + p = t + else + local err = checkPrim(prim) + if err then + return nil, err + end + end + if p.mode ~= "triangles" then + return p, nil -- lines / points: nothing to do + end + if opts and opts.flat then + p = MeshOps.unweld(p) + end + local pos = MeshOps.f32(p.attributes.POSITION) :: Accessor + local pd = pos.data + local nv = pos.count + local ib, n = indexBuffer(p) + local acc = table.create(nv * 3, 0) + for t = 0, n // 3 - 1 do + local a, b, c = readu32(ib, t * 12), readu32(ib, t * 12 + 4), readu32(ib, t * 12 + 8) + local ax, ay, az = readf32(pd, a * 12), readf32(pd, a * 12 + 4), readf32(pd, a * 12 + 8) + local e1x, e1y, e1z = readf32(pd, b * 12) - ax, readf32(pd, b * 12 + 4) - ay, readf32(pd, b * 12 + 8) - az + local e2x, e2y, e2z = readf32(pd, c * 12) - ax, readf32(pd, c * 12 + 4) - ay, readf32(pd, c * 12 + 8) - az + -- the cross product is twice the area times the unit normal: area weighting for free + local nx, ny, nz = e1y * e2z - e1z * e2y, e1z * e2x - e1x * e2z, e1x * e2y - e1y * e2x + for _, v in { a, b, c } do + acc[v * 3 + 1] += nx + acc[v * 3 + 2] += ny + acc[v * 3 + 3] += nz + end + end + local out = buffer.create(nv * 12) + for v = 0, nv - 1 do + local x, y, z = acc[v * 3 + 1], acc[v * 3 + 2], acc[v * 3 + 3] + local l = math.sqrt(x * x + y * y + z * z) + if l > 0 then + x, y, z = x / l, y / l, z / l + else + x, y, z = 0, 0, 1 + end + writef32(out, v * 12, x) + writef32(out, v * 12 + 4, y) + writef32(out, v * 12 + 8, z) + end + p.attributes.NORMAL = Scene.accessor(out, "f32", 3, nv) + return p, nil +end + +-- computeTangents(prim, opts?) -> prim with TANGENT (f32 vec4: xyz orthogonal to the normal, w = +-1 handedness) | +-- nil, Err. Needs triangles, NORMAL (computed when missing) and TEXCOORD_. +function MeshOps.computeTangents(prim: Primitive, opts: { texCoord: number? }?): (Primitive?, Err.Err?) + local p = prim + if not p.attributes.NORMAL or (p.mode or "triangles") ~= "triangles" then + local q, err = MeshOps.computeNormals(prim) + if not q then + return nil, err + end + p = q + end + local err = checkPrim(p) + if err then + return nil, err + end + local uvAcc = p.attributes["TEXCOORD_" .. tostring(opts and opts.texCoord or 0)] + if not uvAcc then + return nil, Err.new(Err.ARG, "computeTangents needs texture coordinates") + end + local pos = MeshOps.f32(p.attributes.POSITION) :: Accessor + local nrm = MeshOps.f32(p.attributes.NORMAL :: Accessor) :: Accessor + local uv = MeshOps.f32(uvAcc) :: Accessor + local pd, nd, ud = pos.data, nrm.data, uv.data + local nv = pos.count + local ib, n = indexBuffer(p) + local tan = table.create(nv * 3, 0) + local bit = table.create(nv * 3, 0) + for t = 0, n // 3 - 1 do + local a, b, c = readu32(ib, t * 12), readu32(ib, t * 12 + 4), readu32(ib, t * 12 + 8) + local ax, ay, az = readf32(pd, a * 12), readf32(pd, a * 12 + 4), readf32(pd, a * 12 + 8) + local x1, y1, z1 = readf32(pd, b * 12) - ax, readf32(pd, b * 12 + 4) - ay, readf32(pd, b * 12 + 8) - az + local x2, y2, z2 = readf32(pd, c * 12) - ax, readf32(pd, c * 12 + 4) - ay, readf32(pd, c * 12 + 8) - az + local us, vs = readf32(ud, a * 8), readf32(ud, a * 8 + 4) + local s1, t1 = readf32(ud, b * 8) - us, readf32(ud, b * 8 + 4) - vs + local s2, t2 = readf32(ud, c * 8) - us, readf32(ud, c * 8 + 4) - vs + local den = s1 * t2 - s2 * t1 + if den ~= 0 then + local r = 1 / den + local tx, ty, tz = (t2 * x1 - t1 * x2) * r, (t2 * y1 - t1 * y2) * r, (t2 * z1 - t1 * z2) * r + local bx, by, bz = (s1 * x2 - s2 * x1) * r, (s1 * y2 - s2 * y1) * r, (s1 * z2 - s2 * z1) * r + for _, v in { a, b, c } do + tan[v * 3 + 1] += tx + tan[v * 3 + 2] += ty + tan[v * 3 + 3] += tz + bit[v * 3 + 1] += bx + bit[v * 3 + 2] += by + bit[v * 3 + 3] += bz + end + end + end + local out = buffer.create(nv * 16) + for v = 0, nv - 1 do + local nx, ny, nz = readf32(nd, v * 12), readf32(nd, v * 12 + 4), readf32(nd, v * 12 + 8) + local tx, ty, tz = tan[v * 3 + 1], tan[v * 3 + 2], tan[v * 3 + 3] + local dot = nx * tx + ny * ty + nz * tz + tx, ty, tz = tx - nx * dot, ty - ny * dot, tz - nz * dot + local l = math.sqrt(tx * tx + ty * ty + tz * tz) + if l > 1e-20 then + tx, ty, tz = tx / l, ty / l, tz / l + else + -- no UV gradient: any unit vector orthogonal to the normal + if math.abs(nx) < 0.9 then + tx, ty, tz = 0, nz, -ny + else + tx, ty, tz = -nz, 0, nx + end + local l2 = math.sqrt(tx * tx + ty * ty + tz * tz) + if l2 > 0 then + tx, ty, tz = tx / l2, ty / l2, tz / l2 + end + end + -- handedness: (n x t) . b + local cx, cy, cz = ny * tz - nz * ty, nz * tx - nx * tz, nx * ty - ny * tx + local w = if cx * bit[v * 3 + 1] + cy * bit[v * 3 + 2] + cz * bit[v * 3 + 3] < 0 then -1 else 1 + writef32(out, v * 16, tx) + writef32(out, v * 16 + 4, ty) + writef32(out, v * 16 + 8, tz) + writef32(out, v * 16 + 12, w) + end + p.attributes.TANGENT = Scene.accessor(out, "f32", 4, nv) + return p, nil +end + +-- ------------------------------------------------------------------------------------------------ weld / unweld +local function gather(acc: Accessor, ib: buffer, n: number): Accessor + local size = (Types.COMPONENT_SIZE[acc.type] or 4) * acc.components + local out = buffer.create(n * size) + for i = 0, n - 1 do + buffer.copy(out, i * size, acc.data, readu32(ib, i * 4) * size, size) + end + local a = Scene.accessor(out, acc.type, acc.components, n) + a.matrix = acc.matrix + return a +end + +-- unweld(prim) -> a new primitive with one vertex per index (no indices; triangle soups, flat normals) +function MeshOps.unweld(prim: Primitive): Primitive + local ib, n = indexBuffer(prim) + local attrs = {} + for name, a in prim.attributes do + attrs[name] = gather(a, ib, n) + end + local targets = nil + if prim.targets then + targets = {} + for k, t in prim.targets do + local tt = {} + for name, a in t do + tt[name] = gather(a, ib, n) + end + targets[k] = tt + end + end + return { attributes = attrs, indices = nil, mode = prim.mode, faces = prim.faces, material = prim.material, targets = targets, extras = prim.extras } +end + +-- weld(prim, opts?) -> a new indexed primitive where vertices with identical attributes are one | nil, Err. +-- opts.epsilon > 0: positions within epsilon (on a grid of that size) merge too, keeping the first vertex's other +-- attributes only when they are equal (opts.positionsOnly = true merges by position alone, keeping the first vertex). +-- Morph targets are kept per merged vertex (the first one's). +function MeshOps.weld(prim: Primitive, opts: { epsilon: number?, positionsOnly: boolean? }?): (Primitive?, Err.Err?) + local err = checkPrim(prim) + if err then + return nil, err + end + local eps = opts and opts.epsilon or 0 + local posOnly = opts and opts.positionsOnly or false + local names = {} + for name in prim.attributes do + if not (posOnly and name ~= "POSITION") and not (eps > 0 and name == "POSITION") then + table.insert(names, name) + end + end + table.sort(names) + local nv = vertexCount(prim) + local pos = MeshOps.f32(prim.attributes.POSITION) :: Accessor + local pd = pos.data + local inv = if eps > 0 then 1 / eps else 0 + local remap = buffer.create(nv * 4) + local keep: { number } = {} + local seen: { [string]: number } = {} + local parts = table.create(#names + 1) + for v = 0, nv - 1 do + local np = 0 + if eps > 0 then + np += 1 + parts[np] = string.format("%d,%d,%d", math.floor(readf32(pd, v * 12) * inv + 0.5), math.floor(readf32(pd, v * 12 + 4) * inv + 0.5), math.floor(readf32(pd, v * 12 + 8) * inv + 0.5)) + end + for _, name in names do + local a = prim.attributes[name] + local size = (Types.COMPONENT_SIZE[a.type] or 4) * a.components + np += 1 + parts[np] = buffer.readstring(a.data, v * size, size) + end + local key = table.concat(parts, "\1", 1, np) + local k = seen[key] + if k == nil then + k = #keep + seen[key] = k + table.insert(keep, v) + end + writeu32(remap, v * 4, k) + end + local kb = buffer.create(#keep * 4) + for i, v in keep do + writeu32(kb, (i - 1) * 4, v) + end + local attrs = {} + for name, a in prim.attributes do + attrs[name] = gather(a, kb, #keep) + end + local targets = nil + if prim.targets then + targets = {} + for k, t in prim.targets do + local tt = {} + for name, a in t do + tt[name] = gather(a, kb, #keep) + end + targets[k] = tt + end + end + local ib, n = indexBuffer(prim) + local out = buffer.create(n * 4) + for i = 0, n - 1 do + writeu32(out, i * 4, readu32(remap, readu32(ib, i * 4) * 4)) + end + return { + attributes = attrs, + indices = Scene.accessor(out, "u32", 1, n), + mode = prim.mode, + faces = prim.faces, + material = prim.material, + targets = targets, + extras = prim.extras, + }, nil +end + +-- ------------------------------------------------------------------------------------------------ bounds +-- bounds(primitive | scene) -> min { x, y, z }, max { x, y, z } (a scene: in world space, every mesh primitive and +-- voxel shape cell corners excluded) | nil, nil when there are no positions +function MeshOps.bounds(x: any): ({ number }?, { number }?) + local lo = { math.huge, math.huge, math.huge } + local hi = { -math.huge, -math.huge, -math.huge } + local function add(prim: Primitive, m: { number }?) + local pos = prim.attributes and prim.attributes.POSITION + if not pos then + return + end + local get = Scene.reader(pos) + if not get then + return + end + for i = 0, pos.count - 1 do + local px, py, pz = get(i, 0), get(i, 1), get(i, 2) + if m and m ~= Scene.IDENTITY then + px, py, pz = m[1] * px + m[5] * py + m[9] * pz + m[13], m[2] * px + m[6] * py + m[10] * pz + m[14], m[3] * px + m[7] * py + m[11] * pz + m[15] + end + if px < lo[1] then + lo[1] = px + end + if py < lo[2] then + lo[2] = py + end + if pz < lo[3] then + lo[3] = pz + end + if px > hi[1] then + hi[1] = px + end + if py > hi[2] then + hi[2] = py + end + if pz > hi[3] then + hi[3] = pz + end + end + end + if type(x) ~= "table" then + return nil, nil + end + if x.kind == "scene" then + for _, pl in Scene.flatten(x) do + add(pl.primitive, pl.matrix) + end + else + add(x, nil) + end + if lo[1] > hi[1] then + return nil, nil + end + return lo, hi +end + +-- ------------------------------------------------------------------------------------------------ merge +-- the value of an attribute nobody had (COLOR_n white, WEIGHTS_0 { 1, 0, 0, 0 }, the rest zero) +local function defaultFor(name: string, k: number): number + if string.sub(name, 1, 6) == "COLOR_" then + return 1 + end + if string.sub(name, 1, 8) == "WEIGHTS_" then + return if k == 0 then 1 else 0 + end + return 0 +end + +-- merge(scene | { Primitive }, opts?) -> one triangle Primitive with every mesh primitive baked into world space | +-- { Primitive } with opts.byMaterial (one per material, in material order) | nil, Err. Attributes present in any input +-- appear in the output (f32; missing ones filled with defaults: white colours, zeros); custom "_x" attributes too. +-- Lines and points are skipped (opts.keepPoints = true keeps a point-only input as points). Skins and morph targets +-- are not applied (the rest pose). +function MeshOps.merge(input: any, opts: { byMaterial: boolean?, method: string? }?): (any, Err.Err?) + local placed: { Types.Placed } = {} + if type(input) ~= "table" then + return nil, Err.new(Err.ARG, "merge: expected a Scene or a list of Primitives") + end + if input.kind == "scene" then + placed = Scene.flatten(input) + else + for i, p in input do + placed[i] = { primitive = p, matrix = Scene.IDENTITY, node = 0, mesh = 0 } + end + end + -- triangulate + bake each + local groups: { [number]: { Primitive } } = {} + local order: { number } = {} + local allPoints = #placed > 0 + for _, pl in placed do + if pl.primitive.mode ~= "points" then + allPoints = false + end + end + for _, pl in placed do + local p = pl.primitive + local mode = p.mode or "triangles" + if mode ~= "lines" and mode ~= "line_strip" and mode ~= "line_loop" and (mode ~= "points" or allPoints) then + local t, err = if mode == "points" then p else MeshOps.triangulate(p, opts) + if not t then + return nil, err + end + -- a private copy of the attributes to bake + local copy: Primitive = { attributes = {}, indices = t.indices, mode = t.mode, material = t.material } + for name, a in t.attributes do + copy.attributes[name] = MeshOps.f32(a) + end + if pl.matrix ~= Scene.IDENTITY then + local ok, terr = MeshOps.transform(copy, pl.matrix) + if not ok then + return nil, terr + end + end + local key = if opts and opts.byMaterial then (copy.material or 0) else 0 + if not groups[key] then + groups[key] = {} + table.insert(order, key) + end + table.insert(groups[key], copy) + end + end + table.sort(order) + local function concat(list: { Primitive }, material: number?): Primitive + local names: { [string]: number } = {} + local nv, ni = 0, 0 + local points = false + for _, p in list do + for name, a in p.attributes do + names[name] = math.max(names[name] or 0, a.components) + end + nv += vertexCount(p) + local _, n = indexBuffer(p) + ni += n + points = points or p.mode == "points" + end + local attrs: { [string]: Accessor } = {} + for name, comps in names do + local out = buffer.create(nv * comps * 4) + local base = 0 + for _, p in list do + local a = p.attributes[name] + local cnt = vertexCount(p) + for v = 0, cnt - 1 do + for k = 0, comps - 1 do + local value = if a and k < a.components then readf32(a.data, (v * a.components + k) * 4) else defaultFor(name, k) + writef32(out, ((base + v) * comps + k) * 4, value) + end + end + base += cnt + end + attrs[name] = Scene.accessor(out, "f32", comps, nv) + end + local idx = buffer.create(ni * 4) + local base, at = 0, 0 + for _, p in list do + local ib, n = indexBuffer(p) + for i = 0, n - 1 do + writeu32(idx, (at + i) * 4, readu32(ib, i * 4) + base) + end + at += n + base += vertexCount(p) + end + return { + attributes = attrs, + indices = if points then nil else Scene.accessor(idx, "u32", 1, ni), + mode = if points then "points" else "triangles", + material = material, + } + end + if opts and opts.byMaterial then + local out = {} + for _, key in order do + table.insert(out, concat(groups[key], if key == 0 then nil else key)) + end + return out, nil + end + local all = groups[0] or {} + local first = all[1] + return concat(all, first and first.material), nil +end + +-- ------------------------------------------------------------------------------------------------ units / up axis +local function scaleAccessor(acc: Accessor?, f: number): Accessor? + if not acc then + return nil + end + local a = MeshOps.f32(acc) :: Accessor + if a == acc then + a = Scene.accessor(buffer.create(acc.count * acc.components * 4), "f32", acc.components, acc.count) + buffer.copy(a.data, 0, acc.data, 0, acc.count * acc.components * 4) + end + for i = 0, a.count * a.components - 1 do + writef32(a.data, i * 4, readf32(a.data, i * 4) * f) + end + return a +end + +-- scale(scene, factor) -> scene, scaled in place: mesh positions and morph target deltas, node translations (TRS and +-- matrices), translation animations, inverse bind matrices, camera clip planes, light ranges; meta.unit is divided by +-- factor (the same physical size in smaller units). +function MeshOps.scale(scene: Scene, f: number): (Scene?, Err.Err?) + if type(scene) ~= "table" or scene.kind ~= "scene" or type(f) ~= "number" or f ~= f or f == 0 then + return nil, Err.new(Err.ARG, "scale: expected a Scene and a non-zero factor") + end + local done: { [any]: boolean } = {} + for _, mesh in scene.meshes do + for _, p in mesh.primitives do + if not done[p] then + done[p] = true + p.attributes.POSITION = scaleAccessor(p.attributes.POSITION, f) :: Accessor + for _, t in p.targets or {} do + t.POSITION = scaleAccessor(t.POSITION, f) + end + end + end + end + for _, n in scene.nodes do + if n.translation then + n.translation = { n.translation[1] * f, n.translation[2] * f, n.translation[3] * f } + end + if n.matrix then + local m = table.clone(n.matrix) + m[13], m[14], m[15] = m[13] * f, m[14] * f, m[15] * f + n.matrix = m + end + end + for _, a in scene.animations do + for _, c in a.channels do + if c.path == "translation" and not done[c.output] then + done[c.output] = true + c.output = scaleAccessor(c.output, f) :: Accessor + end + end + end + for _, s in scene.skins do + local ibm = s.inverseBindMatrices + if ibm and not done[ibm] then + local a = MeshOps.f32(ibm) :: Accessor + if a == ibm then + a = Scene.accessor(buffer.create(ibm.count * 64), "f32", 16, ibm.count) + buffer.copy(a.data, 0, ibm.data, 0, ibm.count * 64) + end + for i = 0, a.count - 1 do + for k = 12, 14 do + writef32(a.data, (i * 16 + k) * 4, readf32(a.data, (i * 16 + k) * 4) * f) + end + end + a.matrix = true + s.inverseBindMatrices = a + done[a] = true + end + end + for _, c in scene.cameras do + if c.type == "perspective" then + c.znear *= math.abs(f) + if c.zfar then + c.zfar *= math.abs(f) + end + else + c.znear *= math.abs(f) + if c.zfar then + c.zfar *= math.abs(f) + end + c.xmag = c.xmag and c.xmag * math.abs(f) + c.ymag = c.ymag and c.ymag * math.abs(f) + end + end + for _, l in scene.lights do + if l.range then + l.range *= math.abs(f) + end + end + scene.meta.unit = (scene.meta.unit or 1) / f + return scene, nil +end + +-- setUnit(scene, metresPerUnit) -> scene scaled so that one unit is metresPerUnit (from meta.unit, default 1 m) +function MeshOps.setUnit(scene: Scene, metresPerUnit: number): (Scene?, Err.Err?) + if type(scene) ~= "table" or type(metresPerUnit) ~= "number" or metresPerUnit <= 0 then + return nil, Err.new(Err.ARG, "setUnit: expected a Scene and a positive unit") + end + local from = scene.meta.unit or 1 + return MeshOps.scale(scene, from / metresPerUnit) +end + +-- setUp(scene, "y" | "z") -> scene with a new root node rotating the old roots from meta.up (default "y") to up. +-- Nothing is baked: the vertex data stays as it is (MeshOps.merge bakes it). +function MeshOps.setUp(scene: Scene, up: string): (Scene?, Err.Err?) + if type(scene) ~= "table" or scene.kind ~= "scene" or (up ~= "y" and up ~= "z") then + return nil, Err.new(Err.ARG, "setUp: expected a Scene and \"y\" or \"z\"") + end + local from = scene.meta.up or "y" + if from == up then + return scene, nil + end + local h = math.sqrt(0.5) + -- z-up -> y-up: -90 degrees about x; y-up -> z-up: +90 degrees about x + local q = if up == "y" then { -h, 0, 0, h } else { h, 0, 0, h } + table.insert(scene.nodes, { name = "up_" .. up, children = scene.roots, rotation = q }) + scene.roots = { #scene.nodes } + scene.meta.up = up :: any + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ voxels +local function linear(c: number): number + local s = c / 255 + return if s <= 0.04045 then s / 12.92 else ((s + 0.055) / 1.055) ^ 2.4 +end + +-- voxelsToPrimitive(voxels, opts?) -> a triangle Primitive of the grid's visible faces, greedily merged (POSITION, +-- NORMAL f32; COLOR_0 from the palette; u32 indices) | nil, Err. +-- opts.pivot: "center" (default: MagicaVoxel's placement, cell x spans x - floor(sx / 2) ..) or "corner" (0 .. sx); +-- opts.scale: units per voxel (default 1); opts.colors: "linear" (default: f32 linear RGBA, glTF's COLOR_0 meaning) or +-- "srgb" (unorm8, the palette bytes as they are); opts.indexAttribute = true adds "_PALETTE_INDEX" (u8 per vertex). +function MeshOps.voxelsToPrimitive(v: Types.Voxels, opts: { pivot: string?, scale: number?, colors: string?, indexAttribute: boolean? }?): (Primitive?, Err.Err?) + if type(v) ~= "table" or type(v.size) ~= "table" or type(v.data) ~= "buffer" then + return nil, Err.new(Err.ARG, "expected a Voxels grid") + end + local sx, sy, sz = v.size[1], v.size[2], v.size[3] + if type(sx) ~= "number" or type(sy) ~= "number" or type(sz) ~= "number" or sx < 1 or sy < 1 or sz < 1 or buffer.len(v.data) < sx * sy * sz then + return nil, Err.new(Err.ARG, "bad voxel grid size") + end + local pivot = opts and opts.pivot or "center" + local scale = opts and opts.scale or 1 + local ox, oy, oz = 0, 0, 0 + if pivot == "center" then + ox, oy, oz = -(sx // 2), -(sy // 2), -(sz // 2) + end + local g = Greedy.run(v.data, sx, sy, sz, ox, oy, oz, scale) + local nv = g.vertices + local function trim(b: buffer, size: number): buffer + local out = buffer.create(size) + buffer.copy(out, 0, b, 0, size) + return out + end + local attrs: { [string]: Accessor } = { + POSITION = Scene.accessor(trim(g.positions, nv * 12), "f32", 3, nv), + NORMAL = Scene.accessor(trim(g.normals, nv * 12), "f32", 3, nv), + } + local pal = v.palette or {} + local srgb = opts and opts.colors == "srgb" + local col = buffer.create(nv * (if srgb then 4 else 16)) + local lut: { { number } } = {} + for i = 1, 255 do + local c = pal[i] or { 255, 255, 255, 255 } + if srgb then + lut[i] = { c[1] or 0, c[2] or 0, c[3] or 0, c[4] or 255 } + else + lut[i] = { linear(c[1] or 0), linear(c[2] or 0), linear(c[3] or 0), (c[4] or 255) / 255 } + end + end + for k = 0, nv - 1 do + local c = lut[buffer.readu8(g.index, k)] or lut[1] + if srgb then + for j = 0, 3 do + buffer.writeu8(col, k * 4 + j, c[j + 1]) + end + else + for j = 0, 3 do + writef32(col, k * 16 + j * 4, c[j + 1]) + end + end + end + attrs.COLOR_0 = Scene.accessor(col, if srgb then "unorm8" else "f32", 4, nv) + if opts and opts.indexAttribute then + attrs._PALETTE_INDEX = Scene.accessor(trim(g.index, nv), "u8", 1, nv) + end + return { attributes = attrs, indices = Scene.accessor(trim(g.indices, g.quads * 24), "u32", 1, g.quads * 6), mode = "triangles" }, nil +end + +-- meshVoxels(scene, opts?) -> scene with a mesh for every voxel grid (scene.voxels) and node.mesh set on every node +-- that shows one (node.voxels); one shared material (white, rough, not metallic: the colours are per vertex). Options as +-- voxelsToPrimitive. Each call adds new meshes (call it once per scene, after editing the grids). +function MeshOps.meshVoxels(scene: Scene, opts: { pivot: string?, scale: number?, colors: string?, indexAttribute: boolean? }?): (Scene?, Err.Err?) + if type(scene) ~= "table" or scene.kind ~= "scene" then + return nil, Err.new(Err.ARG, "expected a Scene") + end + local grids = scene.voxels or {} + local mat = 0 + local meshOf: { [number]: number } = {} + for i, v in grids do + local prim, err = MeshOps.voxelsToPrimitive(v, opts) + if not prim then + return nil, err + end + if mat == 0 then + local m = Scene.material("voxels") + m.metallic = 0 + table.insert(scene.materials, m) + mat = #scene.materials + end + prim.material = mat + table.insert(scene.meshes, { name = v.name or ("voxels " .. i), primitives = { prim } }) + meshOf[i] = #scene.meshes + end + for _, n in scene.nodes do + if n.voxels and meshOf[n.voxels] then + n.mesh = meshOf[n.voxels] + end + end + return scene, nil +end + +return MeshOps diff --git a/src/Formats/playlist/m3u/init.luau b/src/Formats/playlist/m3u/init.luau new file mode 100644 index 0000000..d023619 --- /dev/null +++ b/src/Formats/playlist/m3u/init.luau @@ -0,0 +1,369 @@ +--!strict +-- playlist/m3u: M3U / M3U8 and HLS (RFC 8216) playlists. Absorbed from playlist-luau 3fc7fd3 (same author, no +-- third-party code). Decode: #EXTM3U / #EXTINF (durations, titles with attributes and commas), #PLAYLIST, plain +-- location lists, a BOM, CRLF / CR, Windows-1252 text; HLS master playlists (variants with BANDWIDTH / CODECS / +-- attributes, EXT-X-MEDIA renditions) and media playlists (segments, durations, byte ranges, target duration, media +-- sequence, end list, encryption, the segment format). Locations resolve against opts.baseUrl (RFC 3986, +-- codecs/Url); Windows / UNC paths stay as they are and are flagged unplayable, as are relative paths without a base +-- and non-HTTP schemes (mp3 HLS segments are playable; .ts / .aac / fMP4 are flagged). Encode: M3U8 (#EXTM3U, +-- #EXTINF, #PLAYLIST). Not supported: writing HLS tags. +-- +-- local pl = M3u.decode(Bytes.reader(buf), { baseUrl = "https://example.com/music/list.m3u" }) +-- for _, e in pl.entries do print(e.url, e.title, e.duration, e.playable) end -- pl.format: "m3u" | "hls" +-- local out = M3u.encode(pl, { title = "My Mix" }) + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Url = require("@formats/codecs/Url") +local Text = require("@formats/codecs/Text") + +-- ------------------------------------------------------------------------------------------------ contract +local M3u = { + name = "m3u", + category = "playlist", + 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 }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type Entry = { + url: string, + title: string?, + duration: number?, -- seconds; nil when unknown (-1 in the file) + playable: boolean, -- an http(s) URL the player can fetch + reason: string?, -- why not playable: "local path", "relative path without a base URL", "scheme ftp", ... + -- HLS + bandwidth: number?, -- master: BANDWIDTH + codecs: string?, -- master: CODECS + attributes: { [string]: string }?, -- master: the whole EXT-X-STREAM-INF / EXT-X-MEDIA attribute list + byteRange: { length: number, offset: number? }?, -- media: EXT-X-BYTERANGE +} + +export type Hls = { + master: boolean, + targetDuration: number?, + mediaSequence: number?, + endList: boolean, -- media playlist: EXT-X-ENDLIST seen (false = live, the playlist grows) + encrypted: boolean, -- EXT-X-KEY with a METHOD other than NONE + totalDuration: number?, -- media: sum of the segment durations + segmentFormat: string?, -- media: the segments' common extension ("mp3", "ts", "aac", ...) or "mixed" +} + +export type Result = { + kind: "playlist", + format: "m3u" | "pls" | "hls" | "xspf", + meta: { [string]: any }, + entries: { Entry }, + warnings: { string }, + title: string?, -- #PLAYLIST: / PLS has none + hls: Hls?, +} + +export type DecodeOptions = { + baseUrl: string?, -- the playlist's own URL (or Windows path), for relative entries + maxBytes: number?, -- refuse bigger files (default 64 MB) +} +export type EncodeOptions = { + title: string?, -- #PLAYLIST: (default: the playlist's title) +} + +-- ------------------------------------------------------------------------------------------------ constants +local UNSUPPORTED_SEGMENTS = { ts = true, aac = true, m4s = true, mp4 = true, m4a = true, fmp4 = true, cmfa = true } + +-- The extension of a URL's path (lower case), or nil +local function extension(url: string): string? + local p = Url.split(url).path + local ext = string.match(p, "%.([%w]+)$") + return if ext then string.lower(ext) else nil +end + +local function duration(s: string?): number? + local d = tonumber(s and Text.trim(s)) + if not d or d < 0 or d ~= d or d == math.huge then + return nil + end + return d +end + +-- RFC 8216 attribute list: KEY=value pairs, quoted strings may hold commas +local function attributes(s: string): { [string]: string } + local out = {} + local i, n = 1, #s + while i <= n do + local key, eq = string.match(s, "^%s*([%w%-_]+)%s*()=", i) + if not key then + break + end + i = (eq :: number) + 1 + local value + if string.sub(s, i, i) == '"' then + local j = string.find(s, '"', i + 1, true) or (n + 1) + value = string.sub(s, i + 1, j - 1) + i = j + 1 + else + local j = string.find(s, ",", i, true) or (n + 1) + value = Text.trim(string.sub(s, i, j - 1)) + i = j + end + out[string.upper(key)] = value + local c = string.find(s, ",", i, true) + if not c then + break + end + i = c + 1 + end + return out +end + +-- #EXTINF:[ attr="v" ...], +local function extinf(rest: string): (number?, string?) + -- the first comma outside quoted attribute values + local comma, quoted = nil, false + for i = 1, #rest do + local c = string.byte(rest, i) + if c == 34 then + quoted = not quoted + elseif c == 44 and not quoted then + comma = i + break + end + end + local head = if comma then string.sub(rest, 1, comma - 1) else rest + local title = if comma then Text.trim(string.sub(rest, comma + 1)) else nil + local d = string.match(head, "^%s*([%-%+]?[%d%.]+)") + return duration(d), if title and title ~= "" then title else nil +end + + +-- ------------------------------------------------------------------------------------------------ sniff +function M3u.sniff(r: Bytes.Reader): number + local s = r:peek(512) + if string.sub(s, 1, 3) == "\239\187\191" then + s = string.sub(s, 4) + end + s = (string.match(s, "^%s*(.*)$") :: string) + if string.sub(s, 1, 7) == "#EXTM3U" then + return 0.95 + end + if string.find(s, "^#EXTINF:") or string.find(s, "^#EXT%-X%-") then + return 0.8 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function parseM3u(ls: { string }, base: string?, baseScheme: string?, warnings: { string }): Result + local res: Result = { kind = "playlist", format = "m3u", entries = {}, warnings = warnings, meta = {} } + local pendingDur, pendingTitle = nil, nil + for n, line in ls do + local l = Text.trim(line) + if l == "" then + continue + end + if string.sub(l, 1, 1) == "#" then + local upper = string.upper(string.sub(l, 1, 10)) + if string.sub(upper, 1, 8) == "#EXTINF:" then + pendingDur, pendingTitle = extinf(string.sub(l, 9)) + elseif string.sub(upper, 1, 10) == "#PLAYLIST:" then + res.title = Text.trim(string.sub(l, 11)) + end + -- #EXTM3U, #EXTGRP, #EXTALB, ... and plain comments: ignored + continue + end + local e: Entry = Url.locate(l, base, baseScheme) + e.title = pendingTitle + e.duration = pendingDur + pendingDur, pendingTitle = nil, nil + table.insert(res.entries, e) + if e.reason and e.reason ~= "local path" then + table.insert(warnings, ("line %d: %s: %s"):format(n, e.reason, e.url)) + end + end + return res +end + +local function parseHls(ls: { string }, base: string?, baseScheme: string?, warnings: { string }): Result + local hls: Hls = { master = false, endList = false, encrypted = false } + local res: Result = { kind = "playlist", format = "hls", entries = {}, warnings = warnings, hls = hls, meta = {} } + local pendingDur, pendingTitle, pendingRange = nil, nil, nil + local pendingStream: { [string]: string }? = nil + local lastRangeEnd: number? = nil + local total = 0 + local formats = {} + local fmp4 = false + for n, line in ls do + local l = Text.trim(line) + if l == "" then + continue + end + if string.sub(l, 1, 1) == "#" then + local tag, rest = string.match(l, "^(#[%w%-]+):?(.*)$") + tag = if tag then string.upper(tag) else nil + if tag == "#EXT-X-STREAM-INF" then + hls.master = true + pendingStream = attributes(rest :: string) + elseif tag == "#EXT-X-MEDIA" then + hls.master = true + local a = attributes(rest :: string) + if a.URI then + local e: Entry = Url.locate(a.URI, base, baseScheme) + e.title = a.NAME + e.attributes = a + e.codecs = a.CODECS + table.insert(res.entries, e) + end + elseif tag == "#EXT-X-TARGETDURATION" then + hls.targetDuration = tonumber(Text.trim(rest :: string)) + elseif tag == "#EXT-X-MEDIA-SEQUENCE" then + hls.mediaSequence = tonumber(Text.trim(rest :: string)) + elseif tag == "#EXT-X-ENDLIST" then + hls.endList = true + elseif tag == "#EXT-X-KEY" then + local a = attributes(rest :: string) + if a.METHOD and string.upper(a.METHOD) ~= "NONE" then + if not hls.encrypted then + table.insert(warnings, ("line %d: encrypted segments (METHOD=%s) are not supported"):format(n, a.METHOD)) + end + hls.encrypted = true + end + elseif tag == "#EXT-X-MAP" then + fmp4 = true + elseif tag == "#EXTINF" then + pendingDur, pendingTitle = extinf(rest :: string) + elseif tag == "#EXT-X-BYTERANGE" then + local len, off = string.match(rest :: string, "^%s*(%d+)@?(%d*)") + if len then + local o = tonumber(off) or lastRangeEnd + pendingRange = { length = tonumber(len) :: number, offset = o } + lastRangeEnd = (o or 0) + (tonumber(len) :: number) + end + end + continue + end + local e: Entry = Url.locate(l, base, baseScheme) + if pendingStream then + e.attributes = pendingStream + e.bandwidth = tonumber(pendingStream.BANDWIDTH) + e.codecs = pendingStream.CODECS + e.title = pendingStream.NAME + pendingStream = nil + else + e.title = pendingTitle + e.duration = pendingDur + e.byteRange = pendingRange + if pendingDur then + total += pendingDur + end + local ext = extension(e.url) or "?" + formats[ext] = true + if e.playable and (UNSUPPORTED_SEGMENTS[ext] or fmp4) then + e.playable = false + e.reason = "segment format " .. (if fmp4 then "fmp4" else ext) + end + if e.playable and hls.encrypted then + e.playable = false + e.reason = "encrypted" + end + end + pendingDur, pendingTitle, pendingRange = nil, nil, nil + table.insert(res.entries, e) + if e.reason == "relative path without a base URL" or (e.reason and string.sub(e.reason, 1, 7) == "scheme ") then + table.insert(warnings, ("line %d: %s: %s"):format(n, e.reason, e.url)) + end + end + if not hls.master then + hls.totalDuration = total + local list = {} + for ext in formats do + table.insert(list, ext) + end + table.sort(list) + hls.segmentFormat = if #list == 1 then list[1] elseif #list == 0 then nil else "mixed" + local bad = {} + for _, ext in list do + if UNSUPPORTED_SEGMENTS[ext] then + table.insert(bad, "." .. ext) + end + end + if fmp4 then + table.insert(bad, "fMP4 (EXT-X-MAP)") + end + if #bad > 0 then + table.insert(warnings, "HLS segments are " .. table.concat(bad, ", ") + .. ": only mp3 segments can be played (concatenated)") + end + if not hls.endList then + table.insert(warnings, "live HLS playlist (no EXT-X-ENDLIST): it has to be reloaded for new segments") + end + end + return res +end + +-- decode(r, opts?) -> Types.Playlist | nil, Err. Bad lines become warnings (pl.warnings), never errors. +function M3u.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Playlist?, Err.Err?) + local n = r.limit - r.pos + if n > (opts and opts.maxBytes or 2 ^ 26) then + return nil, Err.new(Err.LIMIT, "playlist over the size limit") + end + local warnings = {} + local base, baseScheme = Url.base(opts and opts.baseUrl, warnings) + local t = Text.toUtf8(r:string(n), warnings) + local ls = Text.lines(t) + local res = if string.find(t, "#EXT%-X%-") then parseHls(ls, base, baseScheme, warnings) else parseM3u(ls, base, baseScheme, warnings) + local nLocal = 0 + for _, e in res.entries do + if e.reason == "local path" then + nLocal += 1 + end + end + if nLocal > 0 then + table.insert(warnings, string.format("%d local path%s (not playable)", nLocal, if nLocal == 1 then "" else "s")) + end + res.meta.source = { format = "m3u", hls = res.format == "hls" } + return res :: any, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- Writes entries as M3U8 (UTF-8, #EXTM3U, #EXTINF:<seconds>,<title>). Durations are rounded; unknown = -1. +-- opts.title adds #PLAYLIST:. Line breaks inside titles and URLs become spaces. +local function serialize(entries: { any }, opts: { title: string? }?): string + local out = { "#EXTM3U" } + local function clean(s: string): string + return (string.gsub(s, "[\r\n]+", " ")) + end + if opts and opts.title then + table.insert(out, "#PLAYLIST:" .. clean(opts.title)) + end + for _, e in entries or {} do + if type(e) ~= "table" or type(e.url) ~= "string" then + continue + end + local d = tonumber(e.duration) + local secs = if d and d >= 0 and d == d and d ~= math.huge then math.floor(d + 0.5) else -1 + if e.title or d then + table.insert(out, ("#EXTINF:%d,%s"):format(secs, clean(tostring(e.title or "")))) + end + table.insert(out, clean(e.url)) + end + return table.concat(out, "\n") .. "\n" +end + +-- encode(playlist, opts?) -> buffer | nil, Err: M3U8 text. playlist: a Types.Playlist (any format's) or a list of +-- entries ({ url, title?, duration? }) +function M3u.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(value) ~= "table" then + return nil, Err.new(Err.ARG, "encode: needs a Playlist or a list of entries") + end + local entries = if type(value.entries) == "table" then value.entries else value + local title = if opts and opts.title then opts.title else value.title + return buffer.fromstring(serialize(entries, { title = if type(title) == "string" then title else nil })), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +M3u.Url = Url + +return M3u diff --git a/src/Formats/playlist/pls/init.luau b/src/Formats/playlist/pls/init.luau new file mode 100644 index 0000000..ea24213 --- /dev/null +++ b/src/Formats/playlist/pls/init.luau @@ -0,0 +1,237 @@ +--!strict +-- playlist/pls: PLS playlists ([playlist], FileN / TitleN / LengthN, NumberOfEntries, Version). Absorbed from +-- playlist-luau 3fc7fd3 (same author, no third-party code; the parser), plus a new writer. Decode: keys in any case +-- and order, comments, a BOM, CRLF / CR, Windows-1252 text, gaps in the numbering (entries sort by number), a +-- NumberOfEntries mismatch as a warning; locations resolve against opts.baseUrl (RFC 3986, codecs/Url), local / +-- relative / non-HTTP locations are flagged unplayable. Encode: Version=2, Length -1 for unknown durations. +-- +-- local pl = Pls.decode(Bytes.reader(buf), { baseUrl = "https://radio.example/list.pls" }) +-- local out = Pls.encode(pl) + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Url = require("@formats/codecs/Url") +local Text = require("@formats/codecs/Text") + +-- ------------------------------------------------------------------------------------------------ contract +local Pls = { + name = "pls", + category = "playlist", + extensions = { "pls" }, + mime = { "audio/x-scpls", "audio/scpls" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Url", "codecs/Text" }, + caps = { decode = true, encode = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type Entry = { + url: string, + title: string?, + duration: number?, -- seconds; nil when unknown (-1 in the file) + playable: boolean, -- an http(s) URL the player can fetch + reason: string?, -- why not playable: "local path", "relative path without a base URL", "scheme ftp", ... + -- HLS + bandwidth: number?, -- master: BANDWIDTH + codecs: string?, -- master: CODECS + attributes: { [string]: string }?, -- master: the whole EXT-X-STREAM-INF / EXT-X-MEDIA attribute list + byteRange: { length: number, offset: number? }?, -- media: EXT-X-BYTERANGE +} + +export type Hls = { + master: boolean, + targetDuration: number?, + mediaSequence: number?, + endList: boolean, -- media playlist: EXT-X-ENDLIST seen (false = live, the playlist grows) + encrypted: boolean, -- EXT-X-KEY with a METHOD other than NONE + totalDuration: number?, -- media: sum of the segment durations + segmentFormat: string?, -- media: the segments' common extension ("mp3", "ts", "aac", ...) or "mixed" +} + +export type Result = { + kind: "playlist", + format: "m3u" | "pls" | "hls" | "xspf", + meta: { [string]: any }, + entries: { Entry }, + warnings: { string }, + title: string?, -- #PLAYLIST: / PLS has none + hls: Hls?, +} + +export type DecodeOptions = { + baseUrl: string?, -- the playlist's own URL (or Windows path), for relative entries + maxBytes: number?, -- refuse bigger files (default 64 MB) +} + +-- ------------------------------------------------------------------------------------------------ constants +local function duration(s: string?): number? + local d = tonumber(s and Text.trim(s)) + if not d or d < 0 or d ~= d or d == math.huge then + return nil + end + return d +end + +-- RFC 8216 attribute list: KEY=value pairs, quoted strings may hold commas +local function attributes(s: string): { [string]: string } + local out = {} + local i, n = 1, #s + while i <= n do + local key, eq = string.match(s, "^%s*([%w%-_]+)%s*()=", i) + if not key then + break + end + i = (eq :: number) + 1 + local value + if string.sub(s, i, i) == '"' then + local j = string.find(s, '"', i + 1, true) or (n + 1) + value = string.sub(s, i + 1, j - 1) + i = j + 1 + else + local j = string.find(s, ",", i, true) or (n + 1) + value = Text.trim(string.sub(s, i, j - 1)) + i = j + end + out[string.upper(key)] = value + local c = string.find(s, ",", i, true) + if not c then + break + end + i = c + 1 + end + return out +end + +-- #EXTINF:<duration>[ attr="v" ...],<title> +local function extinf(rest: string): (number?, string?) + -- the first comma outside quoted attribute values + local comma, quoted = nil, false + for i = 1, #rest do + local c = string.byte(rest, i) + if c == 34 then + quoted = not quoted + elseif c == 44 and not quoted then + comma = i + break + end + end + local head = if comma then string.sub(rest, 1, comma - 1) else rest + local title = if comma then Text.trim(string.sub(rest, comma + 1)) else nil + local d = string.match(head, "^%s*([%-%+]?[%d%.]+)") + return duration(d), if title and title ~= "" then title else nil +end + + +-- ------------------------------------------------------------------------------------------------ sniff +function Pls.sniff(r: Bytes.Reader): number + local s = r:peek(64) + if string.sub(s, 1, 3) == "\239\187\191" then + s = string.sub(s, 4) + end + local first = string.match(s, "^%s*([^\r\n]*)") + return if first and string.lower(Text.trim(first)) == "[playlist]" then 0.95 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function parsePls(ls: { string }, base: string?, baseScheme: string?, warnings: { string }): Result + local res: Result = { kind = "playlist", format = "pls", entries = {}, warnings = warnings, meta = {} } + local files, titles, lengths = {}, {}, {} + local declared = nil + for _, line in ls do + local l = Text.trim(line) + if l == "" or string.sub(l, 1, 1) == ";" or string.sub(l, 1, 1) == "#" or string.sub(l, 1, 1) == "[" then + continue + end + local key, value = string.match(l, "^([^=]-)%s*=%s*(.*)$") + if not key then + continue + end + local k = string.lower(Text.trim(key :: string)) + local name, idx = string.match(k, "^(%a+)(%d+)$") + local i = tonumber(idx) + if name == "file" and i then + files[i] = value + elseif name == "title" and i then + titles[i] = value + elseif name == "length" and i then + lengths[i] = value + elseif k == "numberofentries" then + declared = tonumber(value) + end + end + local order = {} + for i in files do + table.insert(order, i) + end + table.sort(order) + for _, i in order do + local e: Entry = Url.locate(files[i], base, baseScheme) + local t = titles[i] and Text.trim(titles[i]) + e.title = if t and t ~= "" then t else nil + e.duration = duration(lengths[i]) + table.insert(res.entries, e) + if e.reason and e.reason ~= "local path" then + table.insert(warnings, ("File%d: %s: %s"):format(i, e.reason, e.url)) + end + end + if declared and declared ~= #order then + table.insert(warnings, ("NumberOfEntries=%d but %d files"):format(declared, #order)) + end + return res +end + +-- decode(r, opts?) -> Types.Playlist | nil, Err. Bad lines become warnings (pl.warnings), never errors. +function Pls.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Playlist?, Err.Err?) + local n = r.limit - r.pos + if n > (opts and opts.maxBytes or 2 ^ 26) then + return nil, Err.new(Err.LIMIT, "playlist over the size limit") + end + local warnings = {} + local base, baseScheme = Url.base(opts and opts.baseUrl, warnings) + local t = Text.toUtf8(r:string(n), warnings) + local res = parsePls(Text.lines(t), base, baseScheme, warnings) + local nLocal = 0 + for _, e in res.entries do + if e.reason == "local path" then + nLocal += 1 + end + end + if nLocal > 0 then + table.insert(warnings, string.format("%d local path%s (not playable)", nLocal, if nLocal == 1 then "" else "s")) + end + res.meta.source = { format = "pls" } + return res :: any, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- encode(playlist, opts?) -> buffer | nil, Err: PLS text (Version=2). playlist: a Types.Playlist (any format's) or a +-- list of entries ({ url, title?, duration? }). Line breaks inside titles and URLs become spaces. +function Pls.encode(value: any, _opts: any?): (buffer?, Err.Err?) + if type(value) ~= "table" then + return nil, Err.new(Err.ARG, "encode: needs a Playlist or a list of entries") + end + local entries = if type(value.entries) == "table" then value.entries else value + local function clean(s: string): string + return (string.gsub(s, "[\r\n]+", " ")) + end + local out = { "[playlist]" } + local n = 0 + for _, e in entries do + if type(e) == "table" and type(e.url) == "string" then + n += 1 + table.insert(out, string.format("File%d=%s", n, clean(e.url))) + if type(e.title) == "string" then + table.insert(out, string.format("Title%d=%s", n, clean(e.title))) + end + local d = tonumber(e.duration) + local secs = if d and d >= 0 and d == d and d ~= math.huge then math.floor(d + 0.5) else -1 + table.insert(out, string.format("Length%d=%d", n, secs)) + end + end + table.insert(out, "NumberOfEntries=" .. n) + table.insert(out, "Version=2") + return buffer.fromstring(table.concat(out, "\n") .. "\n"), nil +end + +return Pls diff --git a/src/Formats/playlist/xspf/init.luau b/src/Formats/playlist/xspf/init.luau new file mode 100644 index 0000000..b18034c --- /dev/null +++ b/src/Formats/playlist/xspf/init.luau @@ -0,0 +1,214 @@ +--!strict +-- playlist/xspf: XSPF 1 ("spiff", https://xspf.org/spec) playlists on codecs/Xml. New in formats-luau (playlist-luau +-- had no XSPF). Decode: the playlist's title / creator / annotation / info / location / identifier / image / date, +-- every track's location (the first one is the entry url, all of them in entry.locations), title, creator, album, +-- annotation, info, image, trackNum and duration (milliseconds -> seconds), xml:base on the playlist and on tracks; +-- locations resolve against xml:base, then opts.baseUrl (RFC 3986, codecs/Url), and are classified like the other +-- playlist formats (local / relative / non-HTTP locations are unplayable). Encode: XSPF version 1 with those fields. +-- Not supported: extension / link / meta elements (skipped), XSPF version 0 differences. +-- +-- local pl = Xspf.decode(Bytes.reader(buf), { baseUrl = "https://example.com/list.xspf" }) +-- for _, e in pl.entries do print(e.url, e.title, e.creator, e.duration) end +-- local out = Xspf.encode(pl) + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Url = require("@formats/codecs/Url") +local Xml = require("@formats/codecs/Xml") + +-- ------------------------------------------------------------------------------------------------ contract +local Xspf = { + name = "xspf", + category = "playlist", + extensions = { "xspf" }, + mime = { "application/xspf+xml" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Url", "codecs/Xml" }, + caps = { decode = true, encode = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + baseUrl: string?, -- the playlist's own URL (or Windows path), for relative locations + maxBytes: number?, -- refuse bigger files (default 64 MB) +} + +-- ------------------------------------------------------------------------------------------------ constants +local NS = "http://xspf.org/ns/0/" +local PLAYLIST_FIELDS = { "title", "creator", "annotation", "info", "location", "identifier", "image", "date", "license" } +local TRACK_FIELDS = { "title", "creator", "album", "annotation", "info", "image" } + +local function trim(s: string): string + return (string.match(s, "^%s*(.-)%s*$") :: string) +end + +-- the text of the first child element with this local name, trimmed (nil when missing or empty) +local function field(node: any, name: string): string? + for _, c in node.children do + if type(c) == "table" and Xml.localName(c.name) == name then + local s = trim(Xml.text(c)) + return if s ~= "" then s else nil + end + end + return nil +end + +local function elements(node: any, name: string): { any } + local out = {} + for _, c in node.children do + if type(c) == "table" and Xml.localName(c.name) == name then + table.insert(out, c) + end + end + return out +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Xspf.sniff(r: Bytes.Reader): number + local s = r:peek(1024) + local i = string.find(s, "<%w*:?playlist[%s>]") + if i and string.find(s, NS, 1, true) then + return 0.95 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(r, opts?) -> Types.Playlist | nil, Err (malformed XML or a root that is not <playlist> is an error; odd +-- tracks become warnings) +function Xspf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Playlist?, Err.Err?) + local n = r.limit - r.pos + if n > (opts and opts.maxBytes or 2 ^ 26) then + return nil, Err.new(Err.LIMIT, "playlist over the size limit") + end + local doc, err = Xml.decode(r:string(n)) + if not doc then + return nil, err + end + local root = (doc :: any).root + if not root or Xml.localName(root.name) ~= "playlist" then + return nil, Err.new(Err.CORRUPT, "the root element is not <playlist>") + end + local warnings: { string } = {} + local base, baseScheme = Url.base(opts and opts.baseUrl, warnings) + local function withXmlBase(node: any, b: string?, s: string?): (string?, string?) + local xb = node.attrs and node.attrs["xml:base"] + if type(xb) ~= "string" or xb == "" then + return b, s + end + local l = Url.locate(xb, b, s) + if Url.scheme(l.url) then + return l.url, Url.scheme(l.url) + end + return b, s + end + local pbase, pscheme = withXmlBase(root, base, baseScheme) + local pl: any = { + kind = "playlist", + format = "xspf", + entries = {}, + warnings = warnings, + title = field(root, "title"), + meta = { source = { format = "xspf", version = root.attrs and root.attrs.version } }, + } + for _, k in PLAYLIST_FIELDS do + if k ~= "title" then + pl.meta[k] = field(root, k) + end + end + local nLocal = 0 + for _, list in elements(root, "trackList") do + for i, track in elements(list, "track") do + local tbase, tscheme = withXmlBase(track, pbase, pscheme) + local locs = {} + for _, l in elements(track, "location") do + local s = trim(Xml.text(l)) + if s ~= "" then + table.insert(locs, s) + end + end + if #locs == 0 then + table.insert(warnings, string.format("track %d: no location", i)) + else + local e: any = Url.locate(locs[1], tbase, tscheme) + for _, k in TRACK_FIELDS do + e[k] = field(track, k) + end + local d = tonumber(field(track, "duration")) + e.duration = if d and d >= 0 and d == d and d ~= math.huge then d / 1000 else nil + e.trackNum = tonumber(field(track, "trackNum")) + if #locs > 1 then + local all = {} + for _, l in locs do + table.insert(all, Url.locate(l, tbase, tscheme).url) + end + e.locations = all + end + if e.reason == "local path" then + nLocal += 1 + elseif e.reason then + table.insert(warnings, string.format("track %d: %s: %s", i, e.reason, e.url)) + end + table.insert(pl.entries, e) + end + end + end + if nLocal > 0 then + table.insert(warnings, string.format("%d local path%s (not playable)", nLocal, if nLocal == 1 then "" else "s")) + end + return pl, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- encode(playlist, opts?) -> buffer | nil, Err: XSPF version 1. playlist: a Types.Playlist (any format's) or a list +-- of entries ({ url, title?, duration?, creator?, album?, ... }). opts.indent (default 2) pretty-prints. +function Xspf.encode(value: any, opts: { indent: number?, title: string? }?): (buffer?, Err.Err?) + if type(value) ~= "table" then + return nil, Err.new(Err.ARG, "encode: needs a Playlist or a list of entries") + end + local entries = if type(value.entries) == "table" then value.entries else value + local root = Xml.element("playlist", { version = "1", xmlns = NS }) + local function add(parent: any, name: string, v: any) + if type(v) == "string" and v ~= "" then + Xml.append(parent, Xml.element(name, nil, { v })) + elseif type(v) == "number" and v == v and v ~= math.huge and v ~= -math.huge then + Xml.append(parent, Xml.element(name, nil, { tostring(math.floor(v + 0.5)) })) + end + end + local title = if opts and opts.title then opts.title else value.title + add(root, "title", title) + local meta = if type(value.meta) == "table" then value.meta else {} + for _, k in PLAYLIST_FIELDS do + if k ~= "title" then + add(root, k, meta[k]) + end + end + local list = Xml.append(root, Xml.element("trackList")) + for _, e in entries do + if type(e) == "table" and type(e.url) == "string" then + local tr = Xml.append(list, Xml.element("track")) + add(tr, "location", e.url) + if type(e.locations) == "table" then + for i = 2, #e.locations do + add(tr, "location", e.locations[i]) + end + end + for _, k in TRACK_FIELDS do + add(tr, k, e[k]) + end + local d = tonumber(e.duration) + if d and d >= 0 then + add(tr, "duration", d * 1000) + end + add(tr, "trackNum", tonumber(e.trackNum)) + end + end + local s = Xml.encode(Xml.document(root), { indent = if opts and opts.indent ~= nil then opts.indent else 2 }) + if type(s) ~= "string" then + return nil, Err.new(Err.ARG, "encode: the XML serializer failed") + end + return buffer.fromstring(s), nil +end + +return Xspf diff --git a/src/Formats/subtitle/ass/init.luau b/src/Formats/subtitle/ass/init.luau new file mode 100644 index 0000000..ee521f4 --- /dev/null +++ b/src/Formats/subtitle/ass/init.luau @@ -0,0 +1,459 @@ +--!strict +-- subtitle/ass: Advanced SubStation Alpha (v4.00+) and SubStation Alpha (v4.00) scripts (the de-facto spec of +-- Aegisub / libass / ffmpeg). Supports: [Script Info] (meta.scriptInfo, in order), the [V4+ Styles] / [V4 Styles] +-- Format + Style lines (subs.styles[name] = { field = value } as strings, meta.styleFormat / meta.styleOrder), the +-- [Events] Format + Dialogue lines (cues with layer, name, margins, effect; Comment lines in meta.comments), any +-- other section kept verbatim (meta.sections: [Fonts], [Graphics], [Aegisub Project Garbage], ...), H:MM:SS.cc times. +-- Cue text: `\N` / `\n` become line breaks, `\h` a no-break space, the {\i1} / {\b1} / {\u1} / {\s1} overrides become +-- the shared <i> / <b> / <u> / <s> markup and other override blocks are dropped; the original text stays in cue.raw. +-- Encode: an ASS v4.00+ script (or the source's style / event formats), cue.raw when cue.text still matches it, +-- otherwise the markup converted back; times rounded to the centisecond. Styles are data: nothing is rendered. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") + +-- ------------------------------------------------------------------------------------------------ contract +local Ass = { + name = "ass", + category = "subtitle", + extensions = { "ass", "ssa" }, + mime = { "text/x-ssa", "text/x-ass" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, styles = true }, +} + +export type DecodeOptions = { + maxBytes: number?, -- refuse larger files (default 64 MB) +} +export type EncodeOptions = { + crlf: boolean?, -- CRLF line ends (default false) +} + +-- ------------------------------------------------------------------------------------------------ constants +local STYLE_FORMAT = { "Name", "Fontname", "Fontsize", "PrimaryColour", "SecondaryColour", "OutlineColour", "BackColour", "Bold", "Italic", "Underline", "StrikeOut", "ScaleX", "ScaleY", "Spacing", "Angle", "BorderStyle", "Outline", "Shadow", "Alignment", "MarginL", "MarginR", "MarginV", "Encoding" } +local STYLE_DEFAULT: { [string]: string } = { + Name = "Default", + Fontname = "Arial", + Fontsize = "16", + PrimaryColour = "&Hffffff", + SecondaryColour = "&Hffffff", + OutlineColour = "&H0", + TertiaryColour = "&H0", + BackColour = "&H0", + Bold = "0", + Italic = "0", + Underline = "0", + StrikeOut = "0", + ScaleX = "100", + ScaleY = "100", + Spacing = "0", + Angle = "0", + BorderStyle = "1", + Outline = "1", + Shadow = "0", + Alignment = "2", + MarginL = "10", + MarginR = "10", + MarginV = "10", + AlphaLevel = "0", + Encoding = "0", +} +local EVENT_FORMAT = { "Layer", "Start", "End", "Style", "Name", "MarginL", "MarginR", "MarginV", "Effect", "Text" } +-- event fields -> cue keys (the rest keep their field name) +local EVENT_KEY = { Layer = "layer", Name = "name", Actor = "name", MarginL = "marginL", MarginR = "marginR", MarginV = "marginV", Effect = "effect", Marked = "marked" } + +local function trim(s: string): string + return (string.match(s, "^%s*(.-)%s*$")) :: string +end + +local function fields(s: string): { string } + local out = {} + for _, f in string.split(s, ",") do + table.insert(out, trim(f)) + end + return out +end + +-- H:MM:SS.cc (also more / fewer fraction digits) -> seconds | nil +local function time(s: string): number? + local h, m, sec, f = string.match(s, "^%s*(%d+):(%d+):(%d+)%.?(%d*)%s*$") + if not h then + return nil + end + local fr = if f ~= "" then (tonumber(f) :: number) / 10 ^ #(f :: string) else 0 + return tonumber(h) :: number * 3600 + tonumber(m) :: number * 60 + tonumber(sec) :: number + fr +end + +-- ASS text -> the shared markup +local TAGS = { i = "i", b = "b", u = "u", s = "s" } +function Ass.toMarkup(raw: string): string + local open: { [string]: boolean } = {} + local out = string.gsub(raw, "{([^}]*)}", function(block: string): string + local acc = {} + for tag, arg in string.gmatch(block, "\\(%a+)([^\\]*)") do + local t = TAGS[tag] + if t then + local on = arg == "" or (tonumber(arg) or 0) ~= 0 + if arg == "" then + on = not open[t] + end + if on and not open[t] then + table.insert(acc, "<" .. t .. ">") + open[t] = true + elseif not on and open[t] then + table.insert(acc, "</" .. t .. ">") + open[t] = false + end + elseif tag == "r" then + for _, k in { "s", "u", "b", "i" } do + if open[k] then + table.insert(acc, "</" .. k .. ">") + open[k] = false + end + end + end + end + return table.concat(acc) + end) + out = string.gsub(out, "\\[Nn]", "\n") + out = string.gsub(out, "\\h", "\194\160") + for _, k in { "s", "u", "b", "i" } do + if open[k] then + out ..= "</" .. k .. ">" + end + end + return out +end + +-- the shared markup -> ASS text +function Ass.fromMarkup(text: string): string + local s = string.gsub(text, "\r\n?", "\n") + s = string.gsub(s, "<(/?)(%a+)[^>]*>", function(close: string, tag: string): string + local t = TAGS[string.lower(tag)] + if not t then + return "" + end + return "{\\" .. t .. (if close == "/" then "0" else "1") .. "}" + end) + s = string.gsub(s, "\n", "\\N") + return s +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Ass.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, "^%s*%[[Ss]cript [Ii]nfo%]") then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Ass.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Subtitles?, Err.Err?) + local maxBytes = opts and opts.maxBytes or 2 ^ 26 + if r.limit - r.base > maxBytes then + return nil, Err.new(Err.LIMIT, "file is over the " .. maxBytes .. " byte limit") + end + if Ass.sniff(r) == 0 then + return nil, Err.new(Err.CORRUPT, "missing [Script Info]", r.base) + end + local s = buffer.readstring(r.buf, r.base, r.limit - r.base) + if string.find(s, "\0", 1, true) then + return nil, Err.new(Err.CORRUPT, "binary data (NUL bytes) in a text format") + end + if string.sub(s, 1, 3) == "\239\187\191" then + s = string.sub(s, 4) + end + s = string.gsub(s, "\r\n", "\n") + s = string.gsub(s, "\r", "\n") + local subs = Types.Subtitles.new() + local info: { [string]: string } = {} + local infoOrder: { string } = {} + local styleFormat: { string }? = nil + local styleOrder: { string } = {} + local eventFormat: { string } = EVENT_FORMAT + local comments = {} + local sections: { { name: string, lines: { string } } } = {} + local section = "" + local stylesName: string? = nil + for _, line in string.split(s, "\n") do + local name = string.match(line, "^%s*%[(.-)%]%s*$") + if name then + section = string.lower(name) + if section == "v4+ styles" or section == "v4 styles" or section == "v4 styles+" then + stylesName = name + section = "styles" + elseif section ~= "script info" and section ~= "events" then + table.insert(sections, { name = name, lines = {} }) + end + continue + end + if section == "script info" then + if string.sub(line, 1, 1) == ";" or string.sub(line, 1, 1) == "!" then + table.insert(infoOrder, line) -- a comment line, kept in place + else + local k, v = string.match(line, "^([^:]+):%s?(.*)$") + if k then + k = trim(k) + if info[k] == nil then + table.insert(infoOrder, k) + end + info[k] = v :: string + end + end + elseif section == "styles" then + local k, v = string.match(line, "^%s*(%a+):%s*(.*)$") + if k == "Format" then + styleFormat = fields(v :: string) + elseif k == "Style" then + local fmt = styleFormat or STYLE_FORMAT + local vals = string.split(v :: string, ",") + local st: { [string]: string } = {} + for fi, f in fmt do + st[f] = trim(vals[fi] or "") + end + local sname = st.Name or "" + if subs.styles[sname] == nil then + table.insert(styleOrder, sname) + end + subs.styles[sname] = st + end + elseif section == "events" then + local k, v = string.match(line, "^%s*(%a+):%s?(.*)$") + if k == "Format" then + eventFormat = fields(v :: string) + elseif k == "Dialogue" or k == "Comment" then + local vals: { string } = {} + local rest = v :: string + for fi = 1, #eventFormat do + if fi == #eventFormat then + vals[fi] = rest + else + local c = string.find(rest, ",", 1, true) + if not c then + vals[fi] = rest + rest = "" + else + vals[fi] = string.sub(rest, 1, c - 1) + rest = string.sub(rest, c + 1) + end + end + end + local cue: { [string]: any } = { text = "", start = 0, stop = 0 } + local ok = true + for fi, f in eventFormat do + local val = vals[fi] or "" + if f == "Start" or f == "End" then + local t = time(val) + if not t then + ok = false + else + cue[if f == "Start" then "start" else "stop"] = t + end + elseif f == "Text" then + cue.raw = val + cue.text = Ass.toMarkup(val) + elseif f == "Style" then + cue.style = trim(val) + elseif f == "Layer" then + cue.layer = tonumber(trim(val)) or 0 + else + cue[EVENT_KEY[f] or f] = trim(val) + end + end + if ok then + if k == "Comment" then + cue.after = #subs.cues -- written back after that many dialogue lines + table.insert(comments, cue) + else + table.insert(subs.cues, cue :: any) + end + end + end + elseif section ~= "" then + table.insert(sections[#sections].lines, line) + end + end + subs.meta.scriptInfo = info + subs.meta.scriptInfoOrder = infoOrder + subs.meta.styleFormat = styleFormat + subs.meta.styleOrder = styleOrder + subs.meta.stylesSection = stylesName + subs.meta.eventFormat = eventFormat + if #comments > 0 then + subs.meta.comments = comments + end + if #sections > 0 then + -- drop trailing blank lines (the writer adds its own) + for _, sec in sections do + while #sec.lines > 0 and string.match(sec.lines[#sec.lines], "^%s*$") do + table.remove(sec.lines) + end + end + subs.meta.sections = sections + end + subs.meta.source = { format = "ass", scriptType = info.ScriptType } + return subs, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function stamp(t: number): string + local cs = math.floor(t * 100 + 0.5) + return string.format("%d:%02d:%02d.%02d", cs // 360000, cs // 6000 % 60, cs // 100 % 60, cs % 100) +end + +local function field(v: any): string + return (string.gsub(tostring(v), "[\r\n,]", " ")) +end + +function Ass.encode(subs: Types.Subtitles, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(subs) ~= "table" or type(subs.cues) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Subtitles value") + end + local meta: any = if type(subs.meta) == "table" then subs.meta else {} + local out = { "[Script Info]" } + local info: any = if type(meta.scriptInfo) == "table" then meta.scriptInfo else {} + local order = if type(meta.scriptInfoOrder) == "table" then meta.scriptInfoOrder else {} + local written: { [string]: boolean } = {} + if info.ScriptType == nil then + table.insert(out, "ScriptType: v4.00+") + end + for _, k in order do + if type(k) == "string" and (string.sub(k, 1, 1) == ";" or string.sub(k, 1, 1) == "!") then + table.insert(out, k) + elseif info[k] ~= nil and not written[k] then + table.insert(out, k .. ": " .. tostring(info[k])) + written[k] = true + end + end + local rest = {} + for k, v in info do + if not written[k] and type(k) == "string" then + table.insert(rest, k .. ": " .. string.gsub(tostring(v), "[\r\n]", " ")) + end + end + table.sort(rest) + table.move(rest, 1, #rest, #out + 1, out) + -- styles + local ssa = type(info.ScriptType) == "string" and string.lower(info.ScriptType) == "v4.00" + local sfmt: { string } = if type(meta.styleFormat) == "table" then meta.styleFormat else STYLE_FORMAT + table.insert(out, "") + table.insert(out, "[" .. (if type(meta.stylesSection) == "string" then meta.stylesSection elseif ssa then "V4 Styles" else "V4+ Styles") .. "]") + table.insert(out, "Format: " .. table.concat(sfmt, ", ")) + local names: { string } = {} + local seen: { [string]: boolean } = {} + if type(meta.styleOrder) == "table" then + for _, nm in meta.styleOrder do + if type(nm) == "string" and type(subs.styles) == "table" and subs.styles[nm] ~= nil and not seen[nm] then + table.insert(names, nm) + seen[nm] = true + end + end + end + local extra = {} + if type(subs.styles) == "table" then + for nm, st in subs.styles do + if type(nm) == "string" and type(st) == "table" and not seen[nm] then + table.insert(extra, nm) + end + end + end + table.sort(extra) + table.move(extra, 1, #extra, #names + 1, names) + if #names == 0 then + names = { "Default" } + end + for _, nm in names do + local st = if type(subs.styles) == "table" and type(subs.styles[nm]) == "table" then subs.styles[nm] else {} + local vals = {} + for fi, f in sfmt do + local v = if f == "Name" then nm else st[f] + vals[fi] = field(if v ~= nil then v else (STYLE_DEFAULT[f] or "0")) + end + table.insert(out, "Style: " .. table.concat(vals, ",")) + end + -- events + local efmt: { string } = if type(meta.eventFormat) == "table" then meta.eventFormat else EVENT_FORMAT + if efmt[#efmt] ~= "Text" then + return nil, Err.new(Err.ARG, "meta.eventFormat must end with Text") + end + table.insert(out, "") + table.insert(out, "[Events]") + table.insert(out, "Format: " .. table.concat(efmt, ", ")) + local function event(kind: string, c: any, i: number): Err.Err? + if type(c) ~= "table" or type(c.start) ~= "number" or type(c.stop) ~= "number" or type(c.text) ~= "string" or c.start < 0 or c.stop < 0 then + return Err.new(Err.ARG, "cue " .. i .. ": needs start / stop >= 0 (seconds) and a text string") + end + local vals = {} + for fi, f in efmt do + local v: any + if f == "Start" then + v = stamp(c.start) + elseif f == "End" then + v = stamp(c.stop) + elseif f == "Style" then + v = field(c.style or names[1]) + elseif f == "Text" then + if type(c.raw) == "string" and Ass.toMarkup(c.raw) == c.text then + v = string.gsub(c.raw, "[\r\n]", " ") + else + v = Ass.fromMarkup(c.text) + end + elseif f == "Layer" then + v = tostring(tonumber(c.layer) or 0) + elseif f == "Marked" then + v = field(c.marked or "Marked=0") + else + local key = EVENT_KEY[f] or f + local x = c[key] + v = field(if x ~= nil then x elseif string.sub(f, 1, 6) == "Margin" then "0" else "") + end + vals[fi] = v + end + table.insert(out, kind .. ": " .. table.concat(vals, ",")) + return nil + end + local comments = if type(meta.comments) == "table" then meta.comments else {} + local function commentsAfter(n: number?): Err.Err? + for i, c in comments do + if (type(c) == "table" and c.after == n) or (n == nil and (type(c) ~= "table" or type(c.after) ~= "number" or c.after > #subs.cues)) then + local e = event("Comment", c, i) + if e then + return e + end + end + end + return nil + end + for i = 0, #subs.cues do + local e = (if i > 0 then event("Dialogue", subs.cues[i], i) else nil) or commentsAfter(i) + if e then + return nil, e + end + end + local e = commentsAfter(nil) + if e then + return nil, e + end + if type(meta.sections) == "table" then + for _, sec in meta.sections do + if type(sec) == "table" and type(sec.name) == "string" and type(sec.lines) == "table" then + table.insert(out, "") + table.insert(out, "[" .. sec.name .. "]") + for _, l in sec.lines do + table.insert(out, tostring(l)) + end + end + end + end + table.insert(out, "") + local nl = if opts and opts.crlf then "\r\n" else "\n" + return buffer.fromstring(table.concat(out, nl)), nil +end + +return Ass diff --git a/src/Formats/subtitle/srt/init.luau b/src/Formats/subtitle/srt/init.luau new file mode 100644 index 0000000..1354e6a --- /dev/null +++ b/src/Formats/subtitle/srt/init.luau @@ -0,0 +1,181 @@ +--!strict +-- subtitle/srt: SubRip text (the de-facto format; matches ffmpeg's srt demuxer / muxer). Supports: numbered or +-- unnumbered cues, `HH:MM:SS,mmm --> HH:MM:SS,mmm` timings (also `.` decimals and 1..3 fraction digits), the trailing +-- `X1:.. Y1:..` coordinates (kept in cue.settings), multi-line text with blank lines inside a cue (a blank line ends +-- the cue only before an index / timing line), BOM, CRLF / CR line ends. Text is kept as written (its <i> / <b> / +-- <u> / <s> / <font> tags included): the shared markup of Subtitles cue text. +-- Encode: cues renumbered from 1 in order, times rounded to the millisecond, opts.crlf for CRLF line ends. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") + +-- ------------------------------------------------------------------------------------------------ contract +local Srt = { + name = "srt", + category = "subtitle", + extensions = { "srt" }, + mime = { "application/x-subrip", "text/srt" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, styles = false }, +} + +export type DecodeOptions = { + maxBytes: number?, -- refuse larger files (default 64 MB) +} +export type EncodeOptions = { + crlf: boolean?, -- CRLF line ends (default false: LF) +} + +-- ------------------------------------------------------------------------------------------------ constants +local TIMING = "^%s*(%d+):(%d%d?):(%d%d?)[,.](%d+)%s*%-%->%s*(%d+):(%d%d?):(%d%d?)[,.](%d+)%s*(.-)%s*$" + +-- text of the reader's range: BOM stripped, line ends normalised to LF; nil when it holds NUL bytes (binary) +local function text(r: Bytes.Reader): string? + local s = buffer.readstring(r.buf, r.base, r.limit - r.base) + if string.find(s, "\0", 1, true) then + return nil + end + if string.sub(s, 1, 3) == "\239\187\191" then + s = string.sub(s, 4) + end + s = string.gsub(s, "\r\n", "\n") + s = string.gsub(s, "\r", "\n") + return s +end + +local function frac(digits: string): number + return (tonumber(digits) :: number) / 10 ^ #digits +end + +-- timing(line) -> start, stop, settings | nil +local function timing(line: string): (number?, number?, string?) + local h1, m1, s1, f1, h2, m2, s2, f2, rest = string.match(line, TIMING) + if not h1 then + return nil, nil, nil + end + local a = tonumber(h1) :: number * 3600 + tonumber(m1) :: number * 60 + tonumber(s1) :: number + frac(f1 :: string) + local b = tonumber(h2) :: number * 3600 + tonumber(m2) :: number * 60 + tonumber(s2) :: number + frac(f2 :: string) + return a, b, rest +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Srt.sniff(r: Bytes.Reader): number + local head = r:peek(512) + if string.sub(head, 1, 3) == "\239\187\191" then + head = string.sub(head, 4) + end + head = string.gsub(head, "\r", "\n") + local first, second = string.match(head, "^%s*([^\n]*)\n([^\n]*)") + if first and string.match(first, "^%d+%s*$") and second and timing(second) then + return 0.9 + end + if first and timing(first) then + return 0.6 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Srt.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Subtitles?, Err.Err?) + local maxBytes = opts and opts.maxBytes or 2 ^ 26 + if r.limit - r.base > maxBytes then + return nil, Err.new(Err.LIMIT, "file is over the " .. maxBytes .. " byte limit") + end + local s = text(r) + if not s then + return nil, Err.new(Err.CORRUPT, "binary data (NUL bytes) in a text format") + end + local lines = string.split(s, "\n") + local n = #lines + local subs = Types.Subtitles.new() + local i = 1 + local function isStart(k: number): boolean -- a cue starts at line k (index + timing, or a timing) + local l = lines[k] + if l == nil then + return false + end + if timing(l) then + return true + end + return string.match(l, "^%s*%d+%s*$") ~= nil and lines[k + 1] ~= nil and timing(lines[k + 1]) ~= nil + end + while i <= n do + local line = lines[i] + local a, b, settings = timing(line) + if a then + local id: string? = nil + if i > 1 then + local prev = string.match(lines[i - 1], "^%s*(%d+)%s*$") + id = prev + end + i += 1 + local body = {} + while i <= n do + local l = lines[i] + if string.match(l, "^%s*$") then + -- blank: the end of the cue unless more text follows before the next cue + local k = i + while k <= n and string.match(lines[k], "^%s*$") do + k += 1 + end + if k > n or isStart(k) then + break + end + for _ = i, k - 1 do + table.insert(body, "") + end + i = k + elseif timing(l) then + break -- a cue without the blank separator + else + table.insert(body, l) + i += 1 + end + end + -- an index line right before the next timing belongs to the next cue + if #body > 0 and i <= n and timing(lines[i]) and string.match(body[#body], "^%s*%d+%s*$") then + table.remove(body) + end + local cue: Types.Cue = { start = a, stop = b :: number, text = table.concat(body, "\n"), id = id } + if settings and settings ~= "" then + cue.settings = settings + end + table.insert(subs.cues, cue) + else + i += 1 + end + end + if #subs.cues == 0 and string.find(s, "%S") then + return nil, Err.new(Err.CORRUPT, "no cues (no `-->` timing line)") + end + subs.meta.source = { format = "srt" } + return subs, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function stamp(t: number): string + local ms = math.floor(t * 1000 + 0.5) + return string.format("%02d:%02d:%02d,%03d", ms // 3600000, ms // 60000 % 60, ms // 1000 % 60, ms % 1000) +end + +function Srt.encode(subs: Types.Subtitles, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(subs) ~= "table" or type(subs.cues) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Subtitles value") + end + local nl = if opts and opts.crlf then "\r\n" else "\n" + local out = table.create(#subs.cues) + for i, c in subs.cues do + if type(c) ~= "table" or type(c.start) ~= "number" or type(c.stop) ~= "number" or type(c.text) ~= "string" or c.start < 0 or c.stop < 0 then + return nil, Err.new(Err.ARG, "cue " .. i .. ": needs start / stop >= 0 (seconds) and a text string") + end + -- blank lines inside the text are fine: the decoder ends a cue at a blank line only before the next cue + local body = string.gsub(c.text, "\r\n?", "\n") + local settings = if type(c.settings) == "string" and c.settings ~= "" and string.match(c.settings, "X1:") then " " .. c.settings else "" + out[i] = i .. nl .. stamp(c.start) .. " --> " .. stamp(c.stop) .. settings .. nl .. (string.gsub(body, "\n", nl)) .. nl + end + return buffer.fromstring(table.concat(out, nl) .. nl), nil +end + +return Srt diff --git a/src/Formats/subtitle/vtt/init.luau b/src/Formats/subtitle/vtt/init.luau new file mode 100644 index 0000000..1592219 --- /dev/null +++ b/src/Formats/subtitle/vtt/init.luau @@ -0,0 +1,212 @@ +--!strict +-- subtitle/vtt: WebVTT (W3C WebVTT, 2019 CR). Supports: the WEBVTT header (its trailing text and header lines kept in +-- meta.header), cue identifiers, `[hh:]mm:ss.ttt` timings, cue settings (cue.settings, as written), NOTE comments +-- (meta.notes), STYLE blocks (meta.css) and REGION blocks (meta.regions); BOM, CRLF / CR line ends. Cue text is kept +-- as written (<i> / <b> / <c.class> / <v Name> spans, timestamps, entities). +-- Encode: the header, STYLE / REGION blocks, then the cues (times to the millisecond); blank lines inside cue text +-- are dropped and `-->` escaped (WebVTT cue text cannot hold them). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") + +-- ------------------------------------------------------------------------------------------------ contract +local Vtt = { + name = "vtt", + category = "subtitle", + extensions = { "vtt", "webvtt" }, + mime = { "text/vtt" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, styles = true }, +} + +export type DecodeOptions = { + maxBytes: number?, -- refuse larger files (default 64 MB) +} +export type EncodeOptions = {} + +-- ------------------------------------------------------------------------------------------------ constants +local function frac(digits: string): number + return (tonumber(digits) :: number) / 10 ^ #digits +end + +-- one timestamp at the start of s: seconds, the rest | nil +local function timestamp(s: string): (number?, string) + local h, m, sec, f, rest = string.match(s, "^(%d+):(%d%d):(%d%d)%.(%d+)(.*)$") + if h then + return tonumber(h) :: number * 3600 + tonumber(m) :: number * 60 + tonumber(sec) :: number + frac(f :: string), rest :: string + end + local m2, s2, f2, rest2 = string.match(s, "^(%d+):(%d%d)%.(%d+)(.*)$") + if m2 then + return tonumber(m2) :: number * 60 + tonumber(s2) :: number + frac(f2 :: string), rest2 :: string + end + return nil, s +end + +-- timing(line) -> start, stop, settings | nil +local function timing(line: string): (number?, number?, string?) + local a, rest = timestamp((string.gsub(line, "^%s+", ""))) + if not a then + return nil, nil, nil + end + local after = string.match(rest, "^%s*%-%->%s*(.*)$") + if not after then + return nil, nil, nil + end + local b, rest2 = timestamp(after) + if not b then + return nil, nil, nil + end + local settings = string.match(rest2, "^%s*(.-)%s*$") or "" + return a, b, settings +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Vtt.sniff(r: Bytes.Reader): number + local head = r:peek(10) + if string.sub(head, 1, 3) == "\239\187\191" then + head = string.sub(head, 4) + end + if string.sub(head, 1, 6) == "WEBVTT" then + local c = string.sub(head, 7, 7) + if c == "" or c == " " or c == "\t" or c == "\n" or c == "\r" then + return 1 + end + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Vtt.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Subtitles?, Err.Err?) + local maxBytes = opts and opts.maxBytes or 2 ^ 26 + if r.limit - r.base > maxBytes then + return nil, Err.new(Err.LIMIT, "file is over the " .. maxBytes .. " byte limit") + end + if Vtt.sniff(r) == 0 then + return nil, Err.new(Err.CORRUPT, "missing the WEBVTT signature", r.base) + end + local s = buffer.readstring(r.buf, r.base, r.limit - r.base) + if string.find(s, "\0", 1, true) then + return nil, Err.new(Err.CORRUPT, "binary data (NUL bytes) in a text format") + end + if string.sub(s, 1, 3) == "\239\187\191" then + s = string.sub(s, 4) + end + s = string.gsub(s, "\r\n", "\n") + s = string.gsub(s, "\r", "\n") + local lines = string.split(s, "\n") + local n = #lines + local subs = Types.Subtitles.new() + -- the header block: WEBVTT[ text] + lines up to the first blank + local header = { (string.match(lines[1], "^WEBVTT[ \t]*(.*)$")) or "" } + local i = 2 + while i <= n and lines[i] ~= "" do + table.insert(header, lines[i]) + i += 1 + end + if #header > 1 or header[1] ~= "" then + subs.meta.header = table.concat(header, "\n") + end + local notes, css, regions = {}, {}, {} + while i <= n do + if lines[i] == "" then + i += 1 + continue + end + -- a block: lines up to the next blank + local first = i + while i <= n and lines[i] ~= "" do + i += 1 + end + local block = table.move(lines, first, i - 1, 1, {}) + local head = block[1] + if string.match(head, "^NOTE[ \t]") or head == "NOTE" then + table.insert(notes, (string.gsub(table.concat(block, "\n"), "^NOTE[ \t]?", ""))) + elseif (head == "STYLE" or string.match(head, "^STYLE[ \t]")) and not string.find(table.concat(block, "\n"), "-->", 1, true) then + table.insert(css, table.concat(block, "\n", 2)) + elseif (head == "REGION" or string.match(head, "^REGION[ \t]")) and not string.find(table.concat(block, "\n"), "-->", 1, true) then + table.insert(regions, table.concat(block, "\n", 2)) + else + local k, id = 1, nil + local a, b, settings = timing(block[1]) + if not a and block[2] then + id = block[1] + k = 2 + a, b, settings = timing(block[2]) + end + if a then + local cue: Types.Cue = { start = a, stop = b :: number, text = table.concat(block, "\n", k + 1), id = id } + if settings and settings ~= "" then + cue.settings = settings + end + table.insert(subs.cues, cue) + end + -- a block with no timing is skipped (the spec's parser ignores it) + end + end + if #notes > 0 then + subs.meta.notes = notes + end + if #css > 0 then + subs.meta.css = css + end + if #regions > 0 then + subs.meta.regions = regions + end + subs.meta.source = { format = "vtt" } + return subs, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function stamp(t: number): string + local ms = math.floor(t * 1000 + 0.5) + return string.format("%02d:%02d:%02d.%03d", ms // 3600000, ms // 60000 % 60, ms // 1000 % 60, ms % 1000) +end + +-- one block's text: no blank lines (they end a block), no `-->` +local function clean(s: string): string + s = string.gsub(s, "\r\n?", "\n") + s = string.gsub(s, "\n[ \t]*\n", "\n") + s = string.gsub(s, "\n[ \t]*\n", "\n") + s = string.gsub(s, "^\n+", "") + s = string.gsub(s, "%-%->", "-->") + return s +end + +function Vtt.encode(subs: Types.Subtitles, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(subs) ~= "table" or type(subs.cues) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Subtitles value") + end + local meta: any = if type(subs.meta) == "table" then subs.meta else {} + local out = {} + local header = if type(meta.header) == "string" and meta.header ~= "" then meta.header else nil + if header then + local h = string.gsub(clean(header), "%-%->", "") + table.insert(out, "WEBVTT " .. h .. "\n") + else + table.insert(out, "WEBVTT\n") + end + for _, key in { "regions", "css" } do + local list = meta[key] + if type(list) == "table" then + for _, b in list do + if type(b) == "string" then + table.insert(out, (if key == "css" then "STYLE\n" else "REGION\n") .. clean(b) .. "\n") + end + end + end + end + for i, c in subs.cues do + if type(c) ~= "table" or type(c.start) ~= "number" or type(c.stop) ~= "number" or type(c.text) ~= "string" or c.start < 0 or c.stop < 0 then + return nil, Err.new(Err.ARG, "cue " .. i .. ": needs start / stop >= 0 (seconds) and a text string") + end + local id = if type(c.id) == "string" and c.id ~= "" and not string.find(c.id, "-->", 1, true) then (string.gsub(c.id, "[\r\n]", " ")) .. "\n" else "" + local settings = if type(c.settings) == "string" and c.settings ~= "" then " " .. (string.gsub(c.settings, "[\r\n]", " ")) else "" + local body = clean(c.text) + table.insert(out, id .. stamp(c.start) .. " --> " .. stamp(c.stop) .. settings .. "\n" .. body .. (if body ~= "" then "\n" else "")) + end + return buffer.fromstring(table.concat(out, "\n")), nil +end + +return Vtt diff --git a/src/Formats/vector/svg/Parse.luau b/src/Formats/vector/svg/Parse.luau new file mode 100644 index 0000000..86001c7 --- /dev/null +++ b/src/Formats/vector/svg/Parse.luau @@ -0,0 +1,758 @@ +--!strict +-- vector/svg/Parse: an SVG document (a codecs/Xml tree) to a Types.Vector: the cascade (presentation attributes, +-- <style> rules by specificity, style="", inheritance), the shapes as absolute path commands in their user space +-- with the full transform to the root's viewBox space, paints (colours with fill- / stroke-opacity folded into +-- alpha, linear / radial gradients with href inheritance), groups that need their own layer (opacity < 1, or a +-- clip-path) in meta.groups, clip paths resolved per use in meta.clips, <use> / <symbol> / nested <svg> / <switch>. +-- Unsupported elements (text, image, pattern, mask, marker, filter, foreignObject) are counted in meta.unsupported. +-- Never throws. +local Xml = require("@formats/codecs/Xml") +local Types = require("@formats/Types") +local Style = require("@formats/vector/svg/Style") +local PathData = require("@formats/vector/svg/PathData") + +local Parse = {} + +type Node = Types.XmlNode +type M = { number } + +local IDENTITY = { 1, 0, 0, 1, 0, 0 } +local mul = Style.multiply + +-- properties that inherit, and their initial values +local INHERITED: { [string]: string } = { + fill = "black", + ["fill-opacity"] = "1", + ["fill-rule"] = "nonzero", + stroke = "none", + ["stroke-width"] = "1", + ["stroke-opacity"] = "1", + ["stroke-linecap"] = "butt", + ["stroke-linejoin"] = "miter", + ["stroke-miterlimit"] = "4", + ["stroke-dasharray"] = "none", + ["stroke-dashoffset"] = "0", + ["clip-rule"] = "nonzero", + visibility = "visible", + color = "black", + ["font-size"] = "16", +} +-- not inherited (reset per element) +local LOCAL: { [string]: boolean } = { + opacity = true, + ["clip-path"] = true, + display = true, + ["stop-color"] = true, + ["stop-opacity"] = true, + mask = true, + filter = true, +} + +local UNSUPPORTED = { text = true, image = true, pattern = true, mask = true, marker = true, filter = true, foreignObject = true, textPath = true, tspan = true } +local CONTAINERS = { g = true, a = true, switch = true } +local SHAPES = { path = true, rect = true, circle = true, ellipse = true, line = true, polyline = true, polygon = true } + +type Ctx = { + ids: { [string]: Node }, + rules: { Style.Rule }, + vector: Types.Vector, + groups: { any }, + clips: { any }, + unsupported: { [string]: number }, + vw: number, -- the current viewport (for percentages) + vh: number, + depth: number, + useDepth: number, +} + +local function local_(n: Node): string + return Xml.localName(n.name) +end +local function attr(n: Node, k: string): string? + local a = n.attrs :: any + return a[k] +end +local function href(n: Node): string? + local h = attr(n, "href") or attr(n, "xlink:href") + if h == nil then + for k, v in pairs(n.attrs :: any) do + if type(k) == "string" and Xml.localName(k) == "href" then + return v + end + end + end + return h +end +local function refId(s: string?): string? + if s == nil then + return nil + end + return string.match(s, "^%s*#(.-)%s*$") or string.match(s, "^%s*url%(%s*['\"]?#(.-)['\"]?%s*%)") +end + +-- the specified properties of an element: presentation attributes < CSS rules (by specificity, then order) < style="" +local function specified(n: Node, ctx: Ctx): { [string]: string } + local out: { [string]: string } = {} + for k, v in pairs(n.attrs :: any) do + if type(k) == "string" and type(v) == "string" and (INHERITED[k] or LOCAL[k]) then + out[k] = v + end + end + if #ctx.rules > 0 then + local classes: { [string]: boolean } = {} + for c in string.gmatch(attr(n, "class") or "", "%S+") do + classes[c] = true + end + local hits = {} + for _, r in ctx.rules do + if Style.matches(r.selector, local_(n), attr(n, "id"), classes) then + table.insert(hits, r) + end + end + table.sort(hits, function(a: any, b: any): boolean + if a.selector.specificity ~= b.selector.specificity then + return a.selector.specificity < b.selector.specificity + end + return a.order < b.order + end) + for _, r in hits do + for k, v in pairs(r.decls) do + out[k] = v + end + end + end + local st = attr(n, "style") + if st then + for k, v in pairs(Style.declarations(st)) do + out[k] = v + end + end + return out +end + +-- computed(parent, n) -> the element's computed property strings +local function computed(parent: { [string]: string }, n: Node, ctx: Ctx): { [string]: string } + local out: { [string]: string } = {} + for k in pairs(INHERITED) do + out[k] = parent[k] + end + for k, v in pairs(specified(n, ctx)) do + if v == "inherit" then + out[k] = parent[k] + elseif INHERITED[k] or LOCAL[k] then + out[k] = v + end + end + return out +end + +local function len(s: string?, ref: number, st: { [string]: string }, default: number?): number? + local fs = Style.length(st["font-size"], 16) or 16 + local v = Style.length(s, ref, fs) + if v == nil then + return default + end + return v +end + +-- ------------------------------------------------------------------------------------------------ paints +local function stops(g: Node, ctx: Ctx, seen: { [Node]: boolean }): { { number } } + local list = {} + local parentStyle = computed(INHERITED, g, ctx) + for _, s in Xml.children(g) do + if local_(s) == "stop" then + local st = computed(parentStyle, s, ctx) + local off = attr(s, "offset") or "0" + local o = tonumber(string.match(off, "^%s*([%d.eE+-]+)%s*%%%s*$") or "") + local offset = if o then o / 100 else (tonumber(off) or 0) + offset = math.clamp(offset, 0, 1) + if #list > 0 and offset < list[#list][1] then + offset = list[#list][1] + end + local col = Style.color(st["stop-color"] or "black", Style.color(st.color or "black")) or { 0, 0, 0, 255 } + if col == "none" then + col = { 0, 0, 0, 0 } + end + local op = math.clamp(tonumber(st["stop-opacity"] or "1") or 1, 0, 1) + table.insert(list, { offset, col[1], col[2], col[3], math.floor(col[4] * op + 0.5) }) + end + end + if #list == 0 then + local h = refId(href(g)) + local other = if h then ctx.ids[h] else nil + if other and not seen[other] then + seen[other] = true + return stops(other, ctx, seen) + end + end + return list +end + +-- a gradient attribute, looked up through href templates +local function gattr(g: Node, k: string, ctx: Ctx): string? + local cur: Node? = g + local guard = 0 + while cur and guard < 16 do + local v = attr(cur, k) + if v ~= nil then + return v + end + local h = refId(href(cur)) + cur = if h then ctx.ids[h] else nil + guard += 1 + end + return nil +end + +local function gradient(g: Node, opacity: number, ctx: Ctx): any + local kind = local_(g) + local units = gattr(g, "gradientUnits", ctx) or "objectBoundingBox" + local obb = units ~= "userSpaceOnUse" + local list = stops(g, ctx, { [g] = true }) + if #list == 0 then + return "none" + end + if #list == 1 then + local s = list[1] + return { type = "color", color = { s[2], s[3], s[4], math.floor(s[5] * opacity + 0.5) } } + end + local function coord(k: string, default: string, ref: number): number + local v = gattr(g, k, ctx) or default + local pct = string.match(v, "^%s*([%d.eE+-]+)%s*%%%s*$") + if pct then + local x = tonumber(pct) or 0 + return if obb then x / 100 else x / 100 * ref + end + return Style.length(v, ref) or 0 + end + local diag = math.sqrt((ctx.vw * ctx.vw + ctx.vh * ctx.vh) / 2) + local p: any = { + type = if kind == "linearGradient" then "linear" else "radial", + units = if obb then "objectBoundingBox" else "userSpaceOnUse", + spread = gattr(g, "spreadMethod", ctx) or "pad", + stops = list, + opacity = opacity, + } + local t = gattr(g, "gradientTransform", ctx) + if t then + p.transform = Style.transform(t) + end + if p.type == "linear" then + p.x1, p.y1 = coord("x1", "0%", ctx.vw), coord("y1", "0%", ctx.vh) + p.x2, p.y2 = coord("x2", "100%", ctx.vw), coord("y2", "0%", ctx.vh) + else + p.cx, p.cy = coord("cx", "50%", ctx.vw), coord("cy", "50%", ctx.vh) + p.r = coord("r", "50%", diag) + p.fx = if gattr(g, "fx", ctx) then coord("fx", "50%", ctx.vw) else p.cx + p.fy = if gattr(g, "fy", ctx) then coord("fy", "50%", ctx.vh) else p.cy + p.fr = coord("fr", "0%", diag) + end + return p +end + +-- paint(value, opacity, st) -> Paint | nil (none) +local function paint(value: string?, opacity: number, st: { [string]: string }, ctx: Ctx): any + if value == nil then + return nil + end + local id = string.match(value, "^%s*url%(%s*['\"]?#(.-)['\"]?%s*%)%s*(.*)$") + if id then + local fallback = string.match(value, "%)%s*(.-)%s*$") + local g = ctx.ids[id] + if g and (local_(g) == "linearGradient" or local_(g) == "radialGradient") then + local p = gradient(g, opacity, ctx) + return if p == "none" then nil else p + end + if g and local_(g) == "pattern" then + ctx.unsupported.pattern = (ctx.unsupported.pattern or 0) + 1 + end + if fallback and fallback ~= "" then + return paint(fallback, opacity, st, ctx) + end + return nil + end + local c = Style.color(value, Style.color(st.color or "black") :: any) + if c == nil or c == "none" then + return nil + end + return { type = "color", color = { c[1], c[2], c[3], math.floor(c[4] * opacity + 0.5) } } +end + +-- ------------------------------------------------------------------------------------------------ shapes +local function shape(n: Node, st: { [string]: string }, ctx: Ctx): { PathData.Cmd }? + local kind = local_(n) + local vw, vh = ctx.vw, ctx.vh + local diag = math.sqrt((vw * vw + vh * vh) / 2) + if kind == "path" then + local d = attr(n, "d") + if d == nil then + return nil + end + local cmds = PathData.parse(d) + return cmds + elseif kind == "rect" then + local x, y = len(attr(n, "x"), vw, st, 0) :: number, len(attr(n, "y"), vh, st, 0) :: number + local w, h = len(attr(n, "width"), vw, st, 0) :: number, len(attr(n, "height"), vh, st, 0) :: number + if w <= 0 or h <= 0 then + return nil + end + local rx, ry = len(attr(n, "rx"), vw, st), len(attr(n, "ry"), vh, st) + if rx and rx < 0 then + rx = nil + end + if ry and ry < 0 then + ry = nil + end + rx = rx or ry or 0 + ry = ry or rx + rx, ry = math.min(rx :: number, w / 2), math.min(ry :: number, h / 2) + if rx <= 0 or ry <= 0 then + return { { op = "M", x, y }, { op = "L", x + w, y }, { op = "L", x + w, y + h }, { op = "L", x, y + h }, { op = "Z" } } + end + local out: { PathData.Cmd } = { { op = "M", x + rx, y }, { op = "L", x + w - rx, y } } + PathData.arc(x + w - rx, y, rx, ry, 0, false, true, x + w, y + ry, out) + table.insert(out, { op = "L", x + w, y + h - ry }) + PathData.arc(x + w, y + h - ry, rx, ry, 0, false, true, x + w - rx, y + h, out) + table.insert(out, { op = "L", x + rx, y + h }) + PathData.arc(x + rx, y + h, rx, ry, 0, false, true, x, y + h - ry, out) + table.insert(out, { op = "L", x, y + ry }) + PathData.arc(x, y + ry, rx, ry, 0, false, true, x + rx, y, out) + table.insert(out, { op = "Z" }) + return out + elseif kind == "circle" or kind == "ellipse" then + local cx, cy = len(attr(n, "cx"), vw, st, 0) :: number, len(attr(n, "cy"), vh, st, 0) :: number + local rx, ry + if kind == "circle" then + rx = len(attr(n, "r"), diag, st, 0) :: number + ry = rx + else + rx, ry = len(attr(n, "rx"), vw, st), len(attr(n, "ry"), vh, st) + rx = rx or ry or 0 + ry = ry or rx + end + if (rx :: number) <= 0 or (ry :: number) <= 0 then + return nil + end + local out: { PathData.Cmd } = { { op = "M", cx + rx, cy } } + PathData.arc(cx + rx, cy, rx, ry, 0, false, true, cx, cy + ry, out) + PathData.arc(cx, cy + ry, rx, ry, 0, false, true, cx - rx, cy, out) + PathData.arc(cx - rx, cy, rx, ry, 0, false, true, cx, cy - ry, out) + PathData.arc(cx, cy - ry, rx, ry, 0, false, true, cx + rx, cy, out) + table.insert(out, { op = "Z" }) + return out + elseif kind == "line" then + local x1, y1 = len(attr(n, "x1"), vw, st, 0) :: number, len(attr(n, "y1"), vh, st, 0) :: number + local x2, y2 = len(attr(n, "x2"), vw, st, 0) :: number, len(attr(n, "y2"), vh, st, 0) :: number + return { { op = "M", x1, y1 }, { op = "L", x2, y2 } } + elseif kind == "polyline" or kind == "polygon" then + local v = Style.numbers(attr(n, "points")) + if #v < 4 then + return nil + end + local out: { PathData.Cmd } = { { op = "M", v[1], v[2] } } + for i = 3, #v - 1, 2 do + table.insert(out, { op = "L", v[i], v[i + 1] }) + end + if kind == "polygon" then + table.insert(out, { op = "Z" }) + end + return out + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ clip paths +local function transformOf(n: Node): M + local t = attr(n, "transform") + if t then + return Style.transform(t) or IDENTITY + end + return IDENTITY +end + +-- clip(id, ctm, bbox) -> clip index | nil. The clipPath's shapes in root space; objectBoundingBox units mapped to bbox. +local function clip(ref: string, ctm: M, bbox: { number }?, st: { [string]: string }, ctx: Ctx): number? + local cp = ctx.ids[ref] + if cp == nil or local_(cp) ~= "clipPath" then + return nil + end + local base = mul(ctm, transformOf(cp)) + if attr(cp, "clipPathUnits") == "objectBoundingBox" then + if not bbox then + return nil + end + base = mul(base, { bbox[3] - bbox[1], 0, 0, bbox[4] - bbox[2], bbox[1], bbox[2] }) + end + local cpStyle = computed(st, cp, ctx) + local paths = {} + local function add(n: Node, parentStyle: { [string]: string }, m: M, depth: number) + if depth > 8 then + return + end + local s = computed(parentStyle, n, ctx) + if s.display == "none" or s.visibility == "hidden" then + return + end + local k = local_(n) + local tm = mul(m, transformOf(n)) + if SHAPES[k] then + local cmds = shape(n, s, ctx) + if cmds and #cmds > 0 then + table.insert(paths, { d = cmds, transform = tm, rule = s["clip-rule"] or "nonzero" }) + end + elseif k == "use" then + local h = refId(href(n)) + local target = if h then ctx.ids[h] else nil + if target then + local x, y = len(attr(n, "x"), ctx.vw, s, 0) :: number, len(attr(n, "y"), ctx.vh, s, 0) :: number + add(target, s, mul(tm, { 1, 0, 0, 1, x, y }), depth + 1) + end + end + end + for _, c in Xml.children(cp) do + add(c, cpStyle, base, 0) + end + table.insert(ctx.clips, { paths = paths }) + return #ctx.clips +end + +-- ------------------------------------------------------------------------------------------------ the walk +local walk: (n: Node, parentStyle: { [string]: string }, ctm: M, group: number?, ctx: Ctx) -> () + +local function bboxOf(cmds: { PathData.Cmd }): { number }? + local x0, y0, x1, y1 = PathData.bounds(cmds) + if not x0 then + return nil + end + return { x0 :: number, y0 :: number, x1 :: number, y1 :: number } +end + +local function emitShape(n: Node, st: { [string]: string }, ctm: M, group: number?, ctx: Ctx) + if st.visibility == "hidden" or st.visibility == "collapse" then + return + end + local cmds = shape(n, st, ctx) + if not cmds or #cmds == 0 then + return + end + local tm = mul(ctm, transformOf(n)) + local opacity = math.clamp(tonumber(st.opacity or "1") or 1, 0, 1) + local fill = paint(st.fill, math.clamp(tonumber(st["fill-opacity"]) or 1, 0, 1), st, ctx) + local stroke = paint(st.stroke, math.clamp(tonumber(st["stroke-opacity"]) or 1, 0, 1), st, ctx) + local diag = math.sqrt((ctx.vw * ctx.vw + ctx.vh * ctx.vh) / 2) + local sw = len(st["stroke-width"], diag, st, 1) :: number + if sw <= 0 then + stroke = nil + end + if fill == nil and stroke == nil then + return + end + if local_(n) == "line" then + fill = nil -- a line has no inside + end + local clipRef = refId(st["clip-path"]) + local clipId: number? = nil + if clipRef then + clipId = clip(clipRef, tm, bboxOf(cmds), st, ctx) + if clipId == nil and ctx.ids[clipRef] then + return -- a broken clip reference (bad units): nothing shows + end + end + -- opacity on a shape with both a fill and a stroke: a group, so the overlap is not counted twice + local g = group + if opacity < 1 and fill and stroke then + table.insert(ctx.groups, { opacity = opacity, parent = group }) + g = #ctx.groups + opacity = 1 + end + local p: any = { + d = cmds, + fill = fill, + fillRule = if st["fill-rule"] == "evenodd" then "evenodd" else "nonzero", + stroke = stroke, + strokeWidth = sw, + transform = tm, + opacity = opacity, + group = g, + clip = clipId, + id = attr(n, "id"), + } + if stroke then + p.strokeLineJoin = st["stroke-linejoin"] + p.strokeLineCap = st["stroke-linecap"] + p.strokeMiterLimit = tonumber(st["stroke-miterlimit"]) or 4 + local dash = st["stroke-dasharray"] + if dash and dash ~= "none" then + local list = {} + local ok = true + for part in string.gmatch(dash, "[^,%s]+") do + local v = len(part, diag, st) + if v == nil or v < 0 then + ok = false + end + table.insert(list, v or 0) + end + local sum = 0 + for _, v in list do + sum += v + end + if ok and sum > 0 then + if #list % 2 == 1 then + table.move(list, 1, #list, #list + 1, list) + end + p.strokeDashArray = list + p.strokeDashOffset = len(st["stroke-dashoffset"], diag, st, 0) + end + end + end + table.insert(ctx.vector.paths, p) +end + +-- viewBox + preserveAspectRatio -> the transform from the viewBox to a w x h viewport at (x, y) +function Parse.viewTransform(vb: { number }?, par: string?, x: number, y: number, w: number, h: number): M + if vb == nil or vb[3] <= 0 or vb[4] <= 0 then + return { 1, 0, 0, 1, x, y } + end + local sx, sy = w / vb[3], h / vb[4] + local align, mode = "xmidymid", "meet" + if par then + local a, m = string.match(string.lower(par), "^%s*([%w]+)%s*(%a*)") + if a == "defer" then + a, m = string.match(string.lower(par), "^%s*defer%s+([%w]+)%s*(%a*)") + end + align = a or align + if m and m ~= "" then + mode = m + end + end + if align == "none" then + return { sx, 0, 0, sy, x - vb[1] * sx, y - vb[2] * sy } + end + local s = if mode == "slice" then math.max(sx, sy) else math.min(sx, sy) + local tx, ty = x - vb[1] * s, y - vb[2] * s + local ax, ay = string.match(align, "^x(%a%a%a)y(%a%a%a)$") + if ax == "mid" then + tx += (w - vb[3] * s) / 2 + elseif ax == "max" then + tx += w - vb[3] * s + end + if ay == "mid" then + ty += (h - vb[4] * s) / 2 + elseif ay == "max" then + ty += h - vb[4] * s + end + return { s, 0, 0, s, tx, ty } +end + +local function viewBox(n: Node): { number }? + local v = Style.numbers(attr(n, "viewBox")) + if #v == 4 and v[3] > 0 and v[4] > 0 then + return v + end + return nil +end + +local function container(n: Node, st: { [string]: string }, ctm: M, group: number?, ctx: Ctx, children: { Node }?) + -- a layer for opacity / clip-path + local opacity = math.clamp(tonumber(st.opacity or "1") or 1, 0, 1) + local clipRef = refId(st["clip-path"]) + local g = group + if opacity < 1 or clipRef then + local clipId: number? = nil + if clipRef then + local bbox: { number }? = nil + local cp = ctx.ids[clipRef] + if cp and attr(cp, "clipPathUnits") == "objectBoundingBox" then + -- the group's bounding box in its user space: walk once into a scratch vector + local saveV, saveG, saveC = ctx.vector, ctx.groups, ctx.clips + local scratch = Types.Vector.new(0, 0) + ctx.vector, ctx.groups, ctx.clips = scratch, {}, {} + for _, c in children or Xml.children(n) do + walk(c, st, IDENTITY, nil, ctx) + end + ctx.vector, ctx.groups, ctx.clips = saveV, saveG, saveC + local x0, y0, x1, y1 = math.huge, math.huge, -math.huge, -math.huge + for _, p in scratch.paths do + local b = bboxOf(p.d) + if b then + local m = p.transform or IDENTITY + for _, corner in { { b[1], b[2] }, { b[3], b[2] }, { b[1], b[4] }, { b[3], b[4] } } do + local px = m[1] * corner[1] + m[3] * corner[2] + m[5] + local py = m[2] * corner[1] + m[4] * corner[2] + m[6] + x0, y0, x1, y1 = math.min(x0, px), math.min(y0, py), math.max(x1, px), math.max(y1, py) + end + end + end + if x0 <= x1 then + bbox = { x0, y0, x1, y1 } + end + end + clipId = clip(clipRef, ctm, bbox, st, ctx) + if clipId == nil and cp then + return + end + end + table.insert(ctx.groups, { opacity = opacity, parent = group, clip = clipId }) + g = #ctx.groups + end + if local_(n) == "switch" then + -- the first child that renders (conditional attributes are not evaluated) + for _, c in children or Xml.children(n) do + if UNSUPPORTED[local_(c)] == nil then + walk(c, st, ctm, g, ctx) + return + end + end + return + end + for _, c in children or Xml.children(n) do + walk(c, st, ctm, g, ctx) + end +end + +-- a viewport clip (nested svg / symbol: overflow is hidden unless it says otherwise) as a group of its own +local function viewportGroup(n: Node, m: M, x: number, y: number, w: number, h: number, group: number?, ctx: Ctx): number? + local ov = attr(n, "overflow") + if ov == "visible" or ov == "auto" then + return group + end + local rect = { { op = "M", x, y }, { op = "L", x + w, y }, { op = "L", x + w, y + h }, { op = "L", x, y + h }, { op = "Z" } } + table.insert(ctx.clips, { paths = { { d = rect, transform = m, rule = "nonzero" } } }) + table.insert(ctx.groups, { opacity = 1, parent = group, clip = #ctx.clips }) + return #ctx.groups +end + +walk = function(n: Node, parentStyle: { [string]: string }, ctm: M, group: number?, ctx: Ctx) + if ctx.depth > 200 then + return + end + local kind = local_(n) + if kind == "defs" or kind == "clipPath" or kind == "linearGradient" or kind == "radialGradient" or kind == "symbol" or kind == "style" or kind == "title" or kind == "desc" or kind == "metadata" then + return + end + local st = computed(parentStyle, n, ctx) + if st.display == "none" then + return + end + if UNSUPPORTED[kind] then + ctx.unsupported[kind] = (ctx.unsupported[kind] or 0) + 1 + return + end + ctx.depth += 1 + if CONTAINERS[kind] then + container(n, st, mul(ctm, transformOf(n)), group, ctx) + elseif SHAPES[kind] then + emitShape(n, st, ctm, group, ctx) + elseif kind == "use" then + local h = refId(href(n)) + local target = if h then ctx.ids[h] else nil + if target and ctx.useDepth < 16 then + ctx.useDepth += 1 + local x, y = len(attr(n, "x"), ctx.vw, st, 0) :: number, len(attr(n, "y"), ctx.vh, st, 0) :: number + local m = mul(mul(ctm, transformOf(n)), { 1, 0, 0, 1, x, y }) + local tk = local_(target) + if tk == "symbol" or tk == "svg" then + local w = len(attr(n, "width") or attr(target, "width") or "100%", ctx.vw, st, ctx.vw) :: number + local h2 = len(attr(n, "height") or attr(target, "height") or "100%", ctx.vh, st, ctx.vh) :: number + local vb = viewBox(target) + local inner = mul(m, Parse.viewTransform(vb, attr(target, "preserveAspectRatio"), 0, 0, w, h2)) + local saveW, saveH = ctx.vw, ctx.vh + if vb then + ctx.vw, ctx.vh = vb[3], vb[4] + end + local tst = computed(st, target, ctx) + -- the use element's own opacity applies to the symbol's content too + local uo = math.clamp(tonumber(st.opacity or "1") or 1, 0, 1) + if uo < 1 then + tst.opacity = tostring(uo * math.clamp(tonumber(tst.opacity or "1") or 1, 0, 1)) + end + if tst["clip-path"] == nil then + tst["clip-path"] = st["clip-path"] + end + -- the symbol's children as a group of the use element, clipped to its viewport + local vg = viewportGroup(target, m, 0, 0, w, h2, group, ctx) + container(n, tst, mul(inner, transformOf(target)), vg, ctx, Xml.children(target)) + ctx.vw, ctx.vh = saveW, saveH + else + -- the referenced element as if it were the use element's only child + container(n, st, m, group, ctx, { target }) + end + ctx.useDepth -= 1 + end + elseif kind == "svg" then + local x, y = len(attr(n, "x"), ctx.vw, st, 0) :: number, len(attr(n, "y"), ctx.vh, st, 0) :: number + local w = len(attr(n, "width") or "100%", ctx.vw, st, ctx.vw) :: number + local h = len(attr(n, "height") or "100%", ctx.vh, st, ctx.vh) :: number + local vb = viewBox(n) + local m = mul(ctm, Parse.viewTransform(vb, attr(n, "preserveAspectRatio"), x, y, w, h)) + local saveW, saveH = ctx.vw, ctx.vh + if vb then + ctx.vw, ctx.vh = vb[3], vb[4] + else + ctx.vw, ctx.vh = w, h + end + container(n, st, m, viewportGroup(n, ctm, x, y, w, h, group, ctx), ctx) + ctx.vw, ctx.vh = saveW, saveH + end + ctx.depth -= 1 +end + +-- ------------------------------------------------------------------------------------------------ entry +-- document(doc, opts) -> Vector | nil, message +function Parse.document(doc: any): (Types.Vector?, string?) + local root = doc.root + if root == nil or Xml.localName(root.name) ~= "svg" then + return nil, "the root element is not <svg>" + end + local ids: { [string]: Node } = {} + local rules: { Style.Rule } = {} + local count = 0 + local function index(n: Node) + count += 1 + if count > 1000000 then + return + end + local id = attr(n, "id") + if id and ids[id] == nil then + ids[id] = n + end + if local_(n) == "style" then + Style.css(Xml.text(n), rules) + end + for _, c in Xml.children(n) do + index(c) + end + end + index(root) + local vb = viewBox(root) + local w = Style.length(attr(root, "width") or "100%", if vb then vb[3] else 100) or 100 + local h = Style.length(attr(root, "height") or "100%", if vb then vb[4] else 100) or 100 + if w <= 0 or h <= 0 then + w, h = 100, 100 + end + local v = Types.Vector.new(w, h) + v.viewBox = vb or { 0, 0, w, h } + local ctx: Ctx = { + ids = ids, + rules = rules, + vector = v, + groups = {}, + clips = {}, + unsupported = {}, + vw = v.viewBox[3], + vh = v.viewBox[4], + depth = 0, + useDepth = 0, + } + local st = computed(INHERITED, root, ctx) + container(root, st, IDENTITY, nil, ctx) + v.meta.preserveAspectRatio = attr(root, "preserveAspectRatio") + v.meta.groups = ctx.groups + v.meta.clips = ctx.clips + if next(ctx.unsupported) then + v.meta.unsupported = ctx.unsupported + end + return v, nil +end + +return Parse diff --git a/src/Formats/vector/svg/PathData.luau b/src/Formats/vector/svg/PathData.luau new file mode 100644 index 0000000..5cb7887 --- /dev/null +++ b/src/Formats/vector/svg/PathData.luau @@ -0,0 +1,377 @@ +--!strict +-- vector/svg/PathData: SVG path data (SVG 1.1 section 8.3 / SVG 2 "Path data") to absolute M / L / C / Q / Z commands +-- (H / V become L, S / T become C / Q with the reflected control point, arcs become cubic Béziers per the +-- implementation notes F.6 (endpoint to centre parameterisation, out-of-range radii scaled up)); the bounds of a +-- command list; and serialization back to compact path data. Never throws: parsing stops at the first error (the +-- commands so far are kept, as the spec's error handling says). +local PathData = {} + +export type Cmd = { op: string, [number]: number } + +local byte, sub, find = string.byte, string.sub, string.find +local abs, sqrt, cos, sin, atan2, ceil, pi = math.abs, math.sqrt, math.cos, math.sin, math.atan2, math.ceil, math.pi + +local ARGS = { M = 2, L = 2, H = 1, V = 1, C = 6, S = 4, Q = 4, T = 2, A = 7, Z = 0 } + +-- arc(x1, y1, rx, ry, phi, fa, fs, x2, y2, out): cubic segments (absolute) appended to out +local function arc(x1: number, y1: number, rx: number, ry: number, phiDeg: number, fa: boolean, fs: boolean, x2: number, y2: number, out: { Cmd }) + if x1 == x2 and y1 == y2 then + return + end + rx, ry = abs(rx), abs(ry) + if rx == 0 or ry == 0 then + table.insert(out, { op = "L", x2, y2 }) + return + end + local phi = phiDeg % 360 * pi / 180 + local cp, sp = cos(phi), sin(phi) + local dx, dy = (x1 - x2) / 2, (y1 - y2) / 2 + local x1p, y1p = cp * dx + sp * dy, -sp * dx + cp * dy + local lambda = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry) + if lambda > 1 then + local s = sqrt(lambda) + rx, ry = rx * s, ry * s + end + local num = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p + local den = rx * rx * y1p * y1p + ry * ry * x1p * x1p + local coef = if den == 0 then 0 else sqrt(math.max(0, num / den)) + if fa == fs then + coef = -coef + end + local cxp, cyp = coef * rx * y1p / ry, -coef * ry * x1p / rx + local cx, cy = cp * cxp - sp * cyp + (x1 + x2) / 2, sp * cxp + cp * cyp + (y1 + y2) / 2 + local function angle(ux: number, uy: number, vx: number, vy: number): number + return atan2(ux * vy - uy * vx, ux * vx + uy * vy) + end + local ux, uy = (x1p - cxp) / rx, (y1p - cyp) / ry + local vx, vy = (-x1p - cxp) / rx, (-y1p - cyp) / ry + local t1 = angle(1, 0, ux, uy) + local dt = angle(ux, uy, vx, vy) + if not fs and dt > 0 then + dt -= 2 * pi + elseif fs and dt < 0 then + dt += 2 * pi + end + local n = math.max(1, ceil(abs(dt) / (pi / 2) - 1e-9)) + local step = dt / n + local k = 4 / 3 * math.tan(step / 4) + local px, py = x1, y1 + for i = 1, n do + local a0 = t1 + (i - 1) * step + local a1 = t1 + i * step + local c0, s0, c1, s1 = cos(a0), sin(a0), cos(a1), sin(a1) + -- the unit-circle segment's control points, scaled by the radii, rotated by phi, moved to the centre + local e1x, e1y = c0 - k * s0, s0 + k * c0 + local e2x, e2y = c1 + k * s1, s1 - k * c1 + local ex, ey = c1, s1 + local function map(x: number, y: number): (number, number) + x, y = x * rx, y * ry + return cp * x - sp * y + cx, sp * x + cp * y + cy + end + local ax, ay = map(e1x, e1y) + local bx, by = map(e2x, e2y) + local qx, qy = map(ex, ey) + if i == n then + qx, qy = x2, y2 + end + table.insert(out, { op = "C", ax, ay, bx, by, qx, qy }) + px, py = qx, qy + end + local _ = px + py +end +PathData.arc = arc + +-- parse(d) -> commands (absolute M L C Q Z), ok (false when an error stopped parsing) +function PathData.parse(d: string): ({ Cmd }, boolean) + local out: { Cmd } = {} + local i, n = 1, #d + local cx, cy = 0, 0 -- current point + local sx, sy = 0, 0 -- subpath start + local lcx, lcy = 0, 0 -- last control point (for S / T) + local last = "" -- previous command letter (upper case) + local cmd: string? = nil + local rel = false + local nums: { number } = table.create(7) + local function ws() + while i <= n do + local c = byte(d, i) + if c == 32 or c == 9 or c == 10 or c == 13 or c == 12 then + i += 1 + else + break + end + end + end + local function comma() + ws() + if i <= n and byte(d, i) == 44 then + i += 1 + ws() + end + end + local function digits(): boolean + local any = false + while i <= n do + local c = byte(d, i) + if c >= 48 and c <= 57 then + i += 1 + any = true + else + break + end + end + return any + end + -- an SVG number: sign? (digits ("." digits?)? | "." digits) exponent?; "1.5.5" is 1.5 then .5 + local function number(): number? + ws() + local s = i + local c = byte(d, i) + if c == 43 or c == 45 then + i += 1 + end + local whole = digits() + local frac = false + if i <= n and byte(d, i) == 46 then + i += 1 + frac = digits() + end + if not whole and not frac then + i = s + return nil + end + c = byte(d, i) + if c == 101 or c == 69 then + local save = i + i += 1 + c = byte(d, i) + if c == 43 or c == 45 then + i += 1 + end + if not digits() then + i = save + end + end + return tonumber(sub(d, s, i - 1)) + end + local function flag(): number? + ws() + local c = byte(d, i) + if c == 48 or c == 49 then + i += 1 + return c - 48 + end + return nil + end + while true do + ws() + if i > n then + break + end + local c = sub(d, i, i) + local up = string.upper(c) + if ARGS[up] ~= nil and find(c, "%a") then + cmd = up + rel = c ~= up + i += 1 + if up == "Z" then + table.insert(out, { op = "Z" }) + cx, cy = sx, sy + last = "Z" + cmd = nil + continue + end + elseif cmd == nil then + return out, false + end + local c2 = cmd :: string + local na = ARGS[c2] + for k = 1, na do + local v = if c2 == "A" and (k == 4 or k == 5) then flag() else number() + if v == nil then + return out, false + end + nums[k] = v + if k < na then + comma() + end + end + comma() + local ox, oy = if rel then cx else 0, if rel then cy else 0 + if c2 == "M" then + cx, cy = nums[1] + ox, nums[2] + oy + sx, sy = cx, cy + table.insert(out, { op = "M", cx, cy }) + cmd = "L" -- further pairs are line-tos + elseif c2 == "L" then + cx, cy = nums[1] + ox, nums[2] + oy + table.insert(out, { op = "L", cx, cy }) + elseif c2 == "H" then + cx = nums[1] + ox + table.insert(out, { op = "L", cx, cy }) + elseif c2 == "V" then + cy = nums[1] + (if rel then cy else 0) + table.insert(out, { op = "L", cx, cy }) + elseif c2 == "C" then + local x1, y1, x2, y2 = nums[1] + ox, nums[2] + oy, nums[3] + ox, nums[4] + oy + cx, cy = nums[5] + ox, nums[6] + oy + table.insert(out, { op = "C", x1, y1, x2, y2, cx, cy }) + lcx, lcy = x2, y2 + elseif c2 == "S" then + local x1, y1 = cx, cy + if last == "C" or last == "S" then + x1, y1 = 2 * cx - lcx, 2 * cy - lcy + end + local x2, y2 = nums[1] + ox, nums[2] + oy + cx, cy = nums[3] + ox, nums[4] + oy + table.insert(out, { op = "C", x1, y1, x2, y2, cx, cy }) + lcx, lcy = x2, y2 + elseif c2 == "Q" then + local x1, y1 = nums[1] + ox, nums[2] + oy + cx, cy = nums[3] + ox, nums[4] + oy + table.insert(out, { op = "Q", x1, y1, cx, cy }) + lcx, lcy = x1, y1 + elseif c2 == "T" then + local x1, y1 = cx, cy + if last == "Q" or last == "T" then + x1, y1 = 2 * cx - lcx, 2 * cy - lcy + end + cx, cy = nums[1] + ox, nums[2] + oy + table.insert(out, { op = "Q", x1, y1, cx, cy }) + lcx, lcy = x1, y1 + elseif c2 == "A" then + local x2, y2 = nums[6] + ox, nums[7] + oy + arc(cx, cy, nums[1], nums[2], nums[3], nums[4] ~= 0, nums[5] ~= 0, x2, y2, out) + cx, cy = x2, y2 + end + last = if c2 == "M" then "M" else c2 + end + return out, true +end + +-- bounds(cmds) -> x0, y0, x1, y1 of every point and control point (nil when empty): the control polygon's box +-- contains the curve; exact enough for objectBoundingBox units on lines, and close for curves +function PathData.bounds(cmds: { Cmd }): (number?, number?, number?, number?) + local x0, y0, x1, y1 = math.huge, math.huge, -math.huge, -math.huge + local px, py = 0, 0 + for _, c in cmds do + local op = c.op + if op == "C" then + -- the curve's exact extrema + local ax, ay, bx, by, ex, ey = c[1], c[2], c[3], c[4], c[5], c[6] + for axis = 1, 2 do + local p0 = if axis == 1 then px else py + local p1 = if axis == 1 then ax else ay + local p2 = if axis == 1 then bx else by + local p3 = if axis == 1 then ex else ey + local a = -p0 + 3 * p1 - 3 * p2 + p3 + local b = 2 * (p0 - 2 * p1 + p2) + local cc = p1 - p0 + local ts = {} + if abs(a) < 1e-12 then + if abs(b) > 1e-12 then + table.insert(ts, -cc / b) + end + else + local disc = b * b - 4 * a * cc + if disc >= 0 then + local s = sqrt(disc) + table.insert(ts, (-b + s) / (2 * a)) + table.insert(ts, (-b - s) / (2 * a)) + end + end + for _, t in ts do + if t > 0 and t < 1 then + local mt = 1 - t + local v = mt * mt * mt * p0 + 3 * mt * mt * t * p1 + 3 * mt * t * t * p2 + t * t * t * p3 + if axis == 1 then + x0, x1 = math.min(x0, v), math.max(x1, v) + else + y0, y1 = math.min(y0, v), math.max(y1, v) + end + end + end + end + px, py = ex, ey + elseif op == "Q" then + local ax, ay, ex, ey = c[1], c[2], c[3], c[4] + for axis = 1, 2 do + local p0 = if axis == 1 then px else py + local p1 = if axis == 1 then ax else ay + local p2 = if axis == 1 then ex else ey + local den = p0 - 2 * p1 + p2 + if abs(den) > 1e-12 then + local t = (p0 - p1) / den + if t > 0 and t < 1 then + local mt = 1 - t + local v = mt * mt * p0 + 2 * mt * t * p1 + t * t * p2 + if axis == 1 then + x0, x1 = math.min(x0, v), math.max(x1, v) + else + y0, y1 = math.min(y0, v), math.max(y1, v) + end + end + end + end + px, py = ex, ey + elseif op == "M" or op == "L" then + px, py = c[1], c[2] + end + if op ~= "Z" then + x0, x1 = math.min(x0, px), math.max(x1, px) + y0, y1 = math.min(y0, py), math.max(y1, py) + end + end + if x0 > x1 then + return nil, nil, nil, nil + end + return x0, y0, x1, y1 +end + +-- num(v) -> short text for a coordinate (up to 4 decimals, no trailing zeros) +local function num(v: number): string + if v ~= v or v == math.huge or v == -math.huge then + return "0" + end + local r = math.floor(v * 10000 + 0.5) / 10000 + if r == math.floor(r) and abs(r) < 1e15 then + return string.format("%d", r) + end + local s = string.format("%.4f", r) + s = string.gsub(s, "0+$", "") + return s +end +PathData.num = num + +-- serialize(cmds) -> path data text +function PathData.serialize(cmds: { Cmd }): string + local out = {} + for _, c in cmds do + local k = ARGS[c.op] + if k ~= nil then + local parts = { c.op } + local cnt = if c.op == "C" then 6 elseif c.op == "Q" then 4 elseif c.op == "Z" then 0 else 2 + for j = 1, cnt do + table.insert(parts, num(tonumber(c[j]) or 0)) + end + table.insert(out, table.concat(parts, " ")) + end + end + return table.concat(out, " ") +end + +-- toRaster(cmds) -> the codecs/Raster command list (moveTo / lineTo / quadTo / cubicTo / close) +local RASTER = { M = "moveTo", L = "lineTo", Q = "quadTo", C = "cubicTo", Z = "close" } +function PathData.toRaster(cmds: { Cmd }): { any } + local out = table.create(#cmds) + for i, c in cmds do + local r: any = { op = RASTER[c.op] or "close" } + for j = 1, #c do + r[j] = c[j] + end + out[i] = r + end + return out +end + +return PathData diff --git a/src/Formats/vector/svg/Render.luau b/src/Formats/vector/svg/Render.luau new file mode 100644 index 0000000..e9c90e7 --- /dev/null +++ b/src/Formats/vector/svg/Render.luau @@ -0,0 +1,427 @@ +--!strict +-- vector/svg/Render: a Types.Vector to an rgba8 Image with codecs/Raster (antialiased coverage, nonzero / even-odd, +-- the stroker) and codecs/Blend (group layers with opacity and clip masks): fills and strokes with solid colours and +-- linear / radial gradients (objectBoundingBox / userSpaceOnUse units, gradientTransform, pad / reflect / repeat, +-- the SVG 1.1 focal point), dashes, joins, caps, miter limits, per-path opacity, groups and clip paths. The viewBox +-- maps onto the image by meta.preserveAspectRatio. Never throws. +local Types = require("@formats/Types") +local Raster = require("@formats/codecs/Raster") +local Blend = require("@formats/codecs/Blend") +local PathData = require("@formats/vector/svg/PathData") +local Parse = require("@formats/vector/svg/Parse") + +local Render = {} + +type M = { number } + +local function mul(m: M, n: M): M + return Raster.multiply(m, n) +end + +-- ------------------------------------------------------------------------------------------------ gradients +local function stopColor(stops: { { number } }, t: number): (number, number, number, number) + local n = #stops + if t <= stops[1][1] then + local s = stops[1] + return s[2], s[3], s[4], s[5] + end + if t >= stops[n][1] then + local s = stops[n] + return s[2], s[3], s[4], s[5] + end + for i = 2, n do + local b = stops[i] + if t <= b[1] then + local a = stops[i - 1] + local span = b[1] - a[1] + local f = if span > 0 then (t - a[1]) / span else 1 + return a[2] + (b[2] - a[2]) * f, a[3] + (b[3] - a[3]) * f, a[4] + (b[4] - a[4]) * f, a[5] + (b[5] - a[5]) * f + end + end + local s = stops[n] + return s[2], s[3], s[4], s[5] +end + +-- a paint function(x, y) for a gradient, given the device transform of the path and its user-space bounds +local function gradientFn(p: any, device: M, bbox: { number }?): ((number, number) -> (number, number, number, number))? + local stops = p.stops + if type(stops) ~= "table" or #stops == 0 then + return nil + end + local g: M = { 1, 0, 0, 1, 0, 0 } + if p.units ~= "userSpaceOnUse" then + if not bbox or bbox[3] - bbox[1] <= 0 or bbox[4] - bbox[2] <= 0 then + return nil -- a zero-size box: the gradient is not rendered + end + g = { bbox[3] - bbox[1], 0, 0, bbox[4] - bbox[2], bbox[1], bbox[2] } + end + if type(p.transform) == "table" then + g = mul(g, p.transform) + end + local inv = Raster.invert(mul(device, g)) + if not inv then + return nil + end + local a, b, c, d, e, f = inv[1], inv[2], inv[3], inv[4], inv[5], inv[6] + local spread = p.spread + local opacity = tonumber(p.opacity) or 1 + local function wrap(t: number): number + if spread == "repeat" then + return t - math.floor(t) + elseif spread == "reflect" then + local r = t % 2 + return if r > 1 then 2 - r else r + end + return t + end + if p.type == "linear" then + local x1, y1, x2, y2 = p.x1 or 0, p.y1 or 0, p.x2 or 1, p.y2 or 0 + local dx, dy = x2 - x1, y2 - y1 + local dd = dx * dx + dy * dy + if dd == 0 then + local r, gg, bb, aa = stopColor(stops, 1) + return function(): (number, number, number, number) + return r, gg, bb, aa * opacity + end + end + return function(x: number, y: number): (number, number, number, number) + local gx, gy = a * x + c * y + e, b * x + d * y + f + local t = wrap(((gx - x1) * dx + (gy - y1) * dy) / dd) + local r, gg, bb, aa = stopColor(stops, t) + return r, gg, bb, aa * opacity + end + end + local cx, cy, r = p.cx or 0.5, p.cy or 0.5, p.r or 0.5 + local fx, fy = p.fx or cx, p.fy or cy + if r <= 0 then + local rr, gg, bb, aa = stopColor(stops, 1) + return function(): (number, number, number, number) + return rr, gg, bb, aa * opacity + end + end + -- SVG 1.1: a focal point outside the circle moves onto it + local fdx, fdy = fx - cx, fy - cy + local fd = math.sqrt(fdx * fdx + fdy * fdy) + if fd > r * 0.999 then + local k = r * 0.999 / fd + fx, fy = cx + fdx * k, cy + fdy * k + end + return function(x: number, y: number): (number, number, number, number) + local gx, gy = a * x + c * y + e, b * x + d * y + f + local dx, dy = gx - fx, gy - fy + local t + if dx == 0 and dy == 0 then + t = 0 + else + -- the ray from the focus through the point meets the circle at s: t = 1 / s + local ox, oy = fx - cx, fy - cy + local qa = dx * dx + dy * dy + local qb = 2 * (dx * ox + dy * oy) + local qc = ox * ox + oy * oy - r * r + local disc = qb * qb - 4 * qa * qc + local s = (-qb + math.sqrt(math.max(0, disc))) / (2 * qa) + t = if s > 0 then 1 / s else 1 + end + local rr, gg, bb, aa = stopColor(stops, wrap(t)) + return rr, gg, bb, aa * opacity + end +end + +-- ------------------------------------------------------------------------------------------------ dashes +-- subpaths of a command list with their closed flag +local function subpaths(cmds: { any }): { { cmds: { any }, closed: boolean } } + local out = {} + local cur: { any }? = nil + for _, c in cmds do + if c.op == "M" then + cur = { c } + table.insert(out, { cmds = cur, closed = false }) + elseif c.op == "Z" then + if cur then + out[#out].closed = true + -- a new subpath starts at the same point if more segments follow + local first = (cur :: { any })[1] + cur = { { op = "M", first[1], first[2] } } + table.insert(out, { cmds = cur, closed = false }) + end + elseif cur then + table.insert(cur, c) + end + end + return out +end + +-- polyline(cmds, tol) -> { x1, y1, x2, y2, ... } of one subpath (curves subdivided to about tol) +local function polyline(cmds: { any }, tol: number): { number } + local pts: { number } = {} + local px, py = 0, 0 + for _, c in cmds do + local op = c.op + if op == "M" or op == "L" then + px, py = c[1], c[2] + table.insert(pts, px) + table.insert(pts, py) + elseif op == "Q" or op == "C" then + local len = 0 + local lx, ly = px, py + for k = 1, #c - 1, 2 do + len += math.sqrt((c[k] - lx) ^ 2 + (c[k + 1] - ly) ^ 2) + lx, ly = c[k], c[k + 1] + end + local steps = math.clamp(math.ceil(math.sqrt(len / math.max(tol, 1e-4))), 1, 512) + for i = 1, steps do + local t = i / steps + local mt = 1 - t + local x, y + if op == "Q" then + x = mt * mt * px + 2 * mt * t * c[1] + t * t * c[3] + y = mt * mt * py + 2 * mt * t * c[2] + t * t * c[4] + else + x = mt * mt * mt * px + 3 * mt * mt * t * c[1] + 3 * mt * t * t * c[3] + t * t * t * c[5] + y = mt * mt * mt * py + 3 * mt * mt * t * c[2] + 3 * mt * t * t * c[4] + t * t * t * c[6] + end + table.insert(pts, x) + table.insert(pts, y) + end + px, py = c[#c - 1], c[#c] + end + end + return pts +end + +local function dashed(cmds: { any }, dashes: { number }, offset: number, tol: number): { any } + local out = {} + local total = 0 + for _, v in dashes do + total += v + end + if total <= 0 then + return cmds + end + for _, sp in subpaths(cmds) do + if #sp.cmds < 2 then + continue + end + local pts = polyline(sp.cmds, tol) + if #pts < 4 then + continue + end + if sp.closed then + table.insert(pts, pts[1]) + table.insert(pts, pts[2]) + end + -- dash state at the start (offset wraps through the pattern) + local idx, left = 1, 0 + local o = offset % total + if o < 0 then + o += total + end + while o > 0 do + if o >= dashes[idx] then + o -= dashes[idx] + idx = idx % #dashes + 1 + else + break + end + end + left = dashes[idx] - o + local on = idx % 2 == 1 + local cur: { any }? = nil + if on then + cur = { { op = "M", pts[1], pts[2] } } + end + for i = 1, #pts - 3, 2 do + local x0, y0, x1, y1 = pts[i], pts[i + 1], pts[i + 2], pts[i + 3] + local seg = math.sqrt((x1 - x0) ^ 2 + (y1 - y0) ^ 2) + local pos = 0 + local guard = 0 + while seg - pos > left and guard < 100000 do + guard += 1 + pos += left + local t = pos / seg + local x, y = x0 + (x1 - x0) * t, y0 + (y1 - y0) * t + if on then + table.insert(cur :: { any }, { op = "L", x, y }) + for _, c in cur :: { any } do + table.insert(out, c) + end + cur = nil + else + cur = { { op = "M", x, y } } + end + on = not on + idx = idx % #dashes + 1 + left = dashes[idx] + end + left -= seg - pos + if on and cur then + table.insert(cur, { op = "L", x1, y1 }) + end + end + if on and cur and #cur > 1 then + for _, c in cur do + table.insert(out, c) + end + end + end + return out +end + +-- ------------------------------------------------------------------------------------------------ rendering +export type Options = { + background: { number }?, -- r, g, b, a under the drawing (default transparent) + tolerance: number?, -- curve flattening in device pixels (default 0.1) +} + +-- the device transform scale (for stroke flattening tolerances) +local function scaleOf(m: M): number + return math.sqrt(math.abs(m[1] * m[4] - m[2] * m[3])) +end + +-- rasterize(v, w, h, opts?) -> rgba8 Image +function Render.rasterize(v: Types.Vector, w: number, h: number, opts: Options?): Types.Image + local o: Options = opts or {} + local img = Types.Image.new(w, h) + local px = img.pixels + local n = w * h + local bg = o.background + if type(bg) == "table" then + local val = (bg[1] or 0) + (bg[2] or 0) * 256 + (bg[3] or 0) * 65536 + (bg[4] or 255) * 16777216 + for i = 0, n - 1 do + buffer.writeu32(px, i * 4, val) + end + end + local meta: any = if type(v.meta) == "table" then v.meta else {} + local view = Parse.viewTransform(v.viewBox, meta.preserveAspectRatio, 0, 0, w, h) + local groups: { any } = if type(meta.groups) == "table" then meta.groups else {} + local clips: { any } = if type(meta.clips) == "table" then meta.clips else {} + local tol = o.tolerance or 0.1 + local clipCache: { [number]: buffer } = {} + -- a clip's coverage over the whole image (1 byte per pixel) + local function clipMask(id: number): buffer? + if clipCache[id] then + return clipCache[id] + end + local c = clips[id] + if type(c) ~= "table" then + return nil + end + local mask = buffer.create(n) + for _, cp in (if type(c.paths) == "table" then c.paths else {}) do + local m = Raster.mask(PathData.toRaster(cp.d), { transform = mul(view, cp.transform or Raster.IDENTITY), rule = cp.rule, clip = { 0, 0, w, h }, tolerance = tol }) + if m then + for y = 0, m.height - 1 do + for x = 0, m.width - 1 do + local cv = buffer.readu8(m.coverage, y * m.width + x) + if cv > 0 then + local i = (m.y + y) * w + m.x + x + local old = buffer.readu8(mask, i) + buffer.writeu8(mask, i, math.min(255, old + cv - math.floor(old * cv / 255 + 0.5))) + end + end + end + end + end + clipCache[id] = mask + return mask + end + -- the layer stack: { group id, image } + local stack: { { id: number?, img: Types.Image } } = { { id = nil, img = img } } + local function chain(g: number?): { number } + local out = {} + local guard = 0 + while g ~= nil and guard < 256 do + table.insert(out, 1, g) + local gr = groups[g] + g = if type(gr) == "table" then gr.parent else nil + guard += 1 + end + return out + end + local function pop() + local top = table.remove(stack) :: any + local below = stack[#stack].img + local gr = groups[top.id] or {} + local mask: any = nil + if gr.clip then + local cm = clipMask(gr.clip) + mask = if cm then { pixels = cm, width = w, height = h, x = 0, y = 0, default = 0 } else { default = 0 } + end + Blend.composite(below.pixels, w, h, top.img.pixels, w, h, 0, 0, math.clamp(tonumber(gr.opacity) or 1, 0, 1), "normal", { mask = mask }) + end + local function draw(target: Types.Image, cmds: { any }, paint: any, device: M, rule: string?, opacity: number, bbox: { number }?) + local fill: any + if paint.type == "color" then + fill = paint.color + else + fill = gradientFn(paint, device, bbox) + if not fill then + return + end + end + Raster.fill(target, cmds, fill, { transform = device, rule = rule, opacity = opacity, tolerance = tol }) + end + for _, p in v.paths do + if type(p) ~= "table" or type(p.d) ~= "table" then + continue + end + -- groups: pop the layers this path is not in, push the ones it needs + local want = chain(p.group) + local keep = 1 + while keep < #stack and stack[keep + 1].id == want[keep] do + keep += 1 + end + while #stack > keep do + pop() + end + for k = keep, #want do + table.insert(stack, { id = want[k], img = Types.Image.new(w, h) }) + end + local device = mul(view, p.transform or Raster.IDENTITY) + local target = stack[#stack].img + local clipMaskBuf: buffer? = nil + if p.clip then + clipMaskBuf = clipMask(p.clip) + if not clipMaskBuf then + continue + end + target = Types.Image.new(w, h) + end + local opacity = math.clamp(tonumber(p.opacity) or 1, 0, 1) + local rcmds = PathData.toRaster(p.d) + local bbox: { number }? = nil + if (p.fill and p.fill.type ~= "color") or (p.stroke and p.stroke.type ~= "color") then + local x0, y0, x1, y1 = PathData.bounds(p.d) + if x0 then + bbox = { x0 :: number, y0 :: number, x1 :: number, y1 :: number } + end + end + if type(p.fill) == "table" then + draw(target, rcmds, p.fill, device, p.fillRule, opacity, bbox) + end + if type(p.stroke) == "table" and (tonumber(p.strokeWidth) or 1) > 0 then + local scale = math.max(scaleOf(device), 1e-6) + local src = p.d + if type(p.strokeDashArray) == "table" and #p.strokeDashArray > 0 then + src = dashed(p.d, p.strokeDashArray, tonumber(p.strokeDashOffset) or 0, tol / scale) + end + local outline = Raster.stroke(PathData.toRaster(src), { + width = tonumber(p.strokeWidth) or 1, + join = p.strokeLineJoin, + cap = p.strokeLineCap, + miterLimit = p.strokeMiterLimit, + tolerance = tol / scale, + }) + draw(target, outline, p.stroke, device, "nonzero", opacity, bbox) + end + if clipMaskBuf then + Blend.composite(stack[#stack].img.pixels, w, h, target.pixels, w, h, 0, 0, 1, "normal", { mask = { pixels = clipMaskBuf, width = w, height = h, x = 0, y = 0, default = 0 } }) + end + end + while #stack > 1 do + pop() + end + return img +end + +return Render diff --git a/src/Formats/vector/svg/Style.luau b/src/Formats/vector/svg/Style.luau new file mode 100644 index 0000000..a48db64 --- /dev/null +++ b/src/Formats/vector/svg/Style.luau @@ -0,0 +1,389 @@ +--!strict +-- vector/svg/Style: the value syntaxes of SVG presentation attributes: colours (CSS Color 3 names, #rgb / #rgba / +-- #rrggbb / #rrggbbaa, rgb() / rgba() / hsl() / hsla() with numbers or percentages, transparent, currentColor), +-- lengths with units, transform lists, style="" declarations, and a CSS subset for <style> (rules of comma-separated +-- compound selectors made of a type, .classes, #id and *, with specificity; @rules and other combinators are skipped). +-- Never throws. +local Style = {} + +local NAMED: { [string]: number } = { + aliceblue = 0xf0f8ff, antiquewhite = 0xfaebd7, aqua = 0x00ffff, aquamarine = 0x7fffd4, azure = 0xf0ffff, + beige = 0xf5f5dc, bisque = 0xffe4c4, black = 0x000000, blanchedalmond = 0xffebcd, blue = 0x0000ff, + blueviolet = 0x8a2be2, brown = 0xa52a2a, burlywood = 0xdeb887, cadetblue = 0x5f9ea0, chartreuse = 0x7fff00, + chocolate = 0xd2691e, coral = 0xff7f50, cornflowerblue = 0x6495ed, cornsilk = 0xfff8dc, crimson = 0xdc143c, + cyan = 0x00ffff, darkblue = 0x00008b, darkcyan = 0x008b8b, darkgoldenrod = 0xb8860b, darkgray = 0xa9a9a9, + darkgreen = 0x006400, darkgrey = 0xa9a9a9, darkkhaki = 0xbdb76b, darkmagenta = 0x8b008b, darkolivegreen = 0x556b2f, + darkorange = 0xff8c00, darkorchid = 0x9932cc, darkred = 0x8b0000, darksalmon = 0xe9967a, darkseagreen = 0x8fbc8f, + darkslateblue = 0x483d8b, darkslategray = 0x2f4f4f, darkslategrey = 0x2f4f4f, darkturquoise = 0x00ced1, + darkviolet = 0x9400d3, deeppink = 0xff1493, deepskyblue = 0x00bfff, dimgray = 0x696969, dimgrey = 0x696969, + dodgerblue = 0x1e90ff, firebrick = 0xb22222, floralwhite = 0xfffaf0, forestgreen = 0x228b22, fuchsia = 0xff00ff, + gainsboro = 0xdcdcdc, ghostwhite = 0xf8f8ff, gold = 0xffd700, goldenrod = 0xdaa520, gray = 0x808080, + grey = 0x808080, green = 0x008000, greenyellow = 0xadff2f, honeydew = 0xf0fff0, hotpink = 0xff69b4, + indianred = 0xcd5c5c, indigo = 0x4b0082, ivory = 0xfffff0, khaki = 0xf0e68c, lavender = 0xe6e6fa, + lavenderblush = 0xfff0f5, lawngreen = 0x7cfc00, lemonchiffon = 0xfffacd, lightblue = 0xadd8e6, lightcoral = 0xf08080, + lightcyan = 0xe0ffff, lightgoldenrodyellow = 0xfafad2, lightgray = 0xd3d3d3, lightgreen = 0x90ee90, + lightgrey = 0xd3d3d3, lightpink = 0xffb6c1, lightsalmon = 0xffa07a, lightseagreen = 0x20b2aa, + lightskyblue = 0x87cefa, lightslategray = 0x778899, lightslategrey = 0x778899, lightsteelblue = 0xb0c4de, + lightyellow = 0xffffe0, lime = 0x00ff00, limegreen = 0x32cd32, linen = 0xfaf0e6, magenta = 0xff00ff, + maroon = 0x800000, mediumaquamarine = 0x66cdaa, mediumblue = 0x0000cd, mediumorchid = 0xba55d3, + mediumpurple = 0x9370db, mediumseagreen = 0x3cb371, mediumslateblue = 0x7b68ee, mediumspringgreen = 0x00fa9a, + mediumturquoise = 0x48d1cc, mediumvioletred = 0xc71585, midnightblue = 0x191970, mintcream = 0xf5fffa, + mistyrose = 0xffe4e1, moccasin = 0xffe4b5, navajowhite = 0xffdead, navy = 0x000080, oldlace = 0xfdf5e6, + olive = 0x808000, olivedrab = 0x6b8e23, orange = 0xffa500, orangered = 0xff4500, orchid = 0xda70d6, + palegoldenrod = 0xeee8aa, palegreen = 0x98fb98, paleturquoise = 0xafeeee, palevioletred = 0xdb7093, + papayawhip = 0xffefd5, peachpuff = 0xffdab9, peru = 0xcd853f, pink = 0xffc0cb, plum = 0xdda0dd, + powderblue = 0xb0e0e6, purple = 0x800080, rebeccapurple = 0x663399, red = 0xff0000, rosybrown = 0xbc8f8f, + royalblue = 0x4169e1, saddlebrown = 0x8b4513, salmon = 0xfa8072, sandybrown = 0xf4a460, seagreen = 0x2e8b57, + seashell = 0xfff5ee, sienna = 0xa0522d, silver = 0xc0c0c0, skyblue = 0x87ceeb, slateblue = 0x6a5acd, + slategray = 0x708090, slategrey = 0x708090, snow = 0xfffafa, springgreen = 0x00ff7f, steelblue = 0x4682b4, + tan = 0xd2b48c, teal = 0x008080, thistle = 0xd8bfd8, tomato = 0xff6347, turquoise = 0x40e0d0, violet = 0xee82ee, + wheat = 0xf5deb3, white = 0xffffff, whitesmoke = 0xf5f5f5, yellow = 0xffff00, yellowgreen = 0x9acd32, +} + +local function clamp255(v: number): number + return math.clamp(math.floor(v + 0.5), 0, 255) +end + +local function hue(p: number, q: number, t: number): number + t %= 1 + if t < 1 / 6 then + return p + (q - p) * 6 * t + elseif t < 1 / 2 then + return q + elseif t < 2 / 3 then + return p + (q - p) * (2 / 3 - t) * 6 + end + return p +end + +-- color(s, current?) -> { r, g, b, a (0..255) } | "none" | nil (not a colour). current: the currentColor value +function Style.color(s: string, current: { number }?): any + s = string.lower((string.gsub(s, "^%s*(.-)%s*$", "%1"))) + if s == "none" then + return "none" + elseif s == "transparent" then + return { 0, 0, 0, 0 } + elseif s == "currentcolor" then + return current or { 0, 0, 0, 255 } + end + local hex = string.match(s, "^#(%x+)$") + if hex then + local n = #hex + if n == 3 or n == 4 then + local v = {} + for k = 1, n do + v[k] = (tonumber(string.sub(hex, k, k), 16) :: number) * 17 + end + return { v[1], v[2], v[3], v[4] or 255 } + elseif n == 6 or n == 8 then + local v = {} + for k = 1, n // 2 do + v[k] = tonumber(string.sub(hex, k * 2 - 1, k * 2), 16) :: number + end + return { v[1], v[2], v[3], v[4] or 255 } + end + return nil + end + local fn, args = string.match(s, "^(%a+)%s*%((.*)%)$") + if fn then + local parts = {} + for p in string.gmatch(args :: string, "[^,%s/]+") do + table.insert(parts, p) + end + local function comp(p: string?, scale: number): number? + if p == nil then + return nil + end + local pct = string.match(p, "^([%d.eE+-]+)%%$") + if pct then + local v = tonumber(pct) + return if v then v / 100 * scale else nil + end + return tonumber(p) + end + local function alpha(p: string?): number + if p == nil then + return 255 + end + local v = comp(p, 1) + return clamp255((v or 1) * 255) + end + if fn == "rgb" or fn == "rgba" then + local r, g, b = comp(parts[1], 255), comp(parts[2], 255), comp(parts[3], 255) + if not (r and g and b) then + return nil + end + return { clamp255(r :: number), clamp255(g :: number), clamp255(b :: number), alpha(parts[4]) } + elseif fn == "hsl" or fn == "hsla" then + local h = tonumber((string.gsub(parts[1] or "", "deg$", ""))) + local sat, l = comp(parts[2], 1), comp(parts[3], 1) + if not (h and sat and l) then + return nil + end + local hh = (h :: number) / 360 + local ss, ll = math.clamp(sat :: number, 0, 1), math.clamp(l :: number, 0, 1) + local q = if ll < 0.5 then ll * (1 + ss) else ll + ss - ll * ss + local p = 2 * ll - q + return { clamp255(hue(p, q, hh + 1 / 3) * 255), clamp255(hue(p, q, hh) * 255), clamp255(hue(p, q, hh - 1 / 3) * 255), alpha(parts[4]) } + end + return nil + end + local v = NAMED[s] + if v then + return { v // 65536, v // 256 % 256, v % 256, 255 } + end + return nil +end + +-- scan(s, i) -> the SVG number at s[i] (sign? digits? ("." digits)? exponent?), the index after it | nil +local function scan(s: string, i: number): (number?, number) + local n = #s + local st = i + local c = string.byte(s, i) + if c == 43 or c == 45 then + i += 1 + end + local any = false + while i <= n do + c = string.byte(s, i) + if c >= 48 and c <= 57 then + i += 1 + any = true + else + break + end + end + if i <= n and string.byte(s, i) == 46 then + i += 1 + while i <= n do + c = string.byte(s, i) + if c >= 48 and c <= 57 then + i += 1 + any = true + else + break + end + end + end + if not any then + return nil, st + end + c = string.byte(s, i) + if c == 101 or c == 69 then + local save = i + i += 1 + c = string.byte(s, i) + if c == 43 or c == 45 then + i += 1 + end + local e = false + while i <= n do + c = string.byte(s, i) + if c >= 48 and c <= 57 then + i += 1 + e = true + else + break + end + end + if not e then + i = save + end + end + return tonumber(string.sub(s, st, i - 1)), i +end + +-- length(s, ref?, fontSize?) -> number in user units | nil. ref: what 100% is (default 100) +local UNITS = { px = 1, pt = 4 / 3, pc = 16, mm = 96 / 25.4, cm = 96 / 2.54, ["in"] = 96, q = 96 / 101.6 } +function Style.length(s: string?, ref: number?, fontSize: number?): number? + if s == nil then + return nil + end + local t = string.match(s, "^%s*(.-)%s*$") :: string + local x, j = scan(t, 1) + if x == nil then + return nil + end + local u = string.lower(string.sub(t, j)) + if u == "" then + return x + elseif u == "%" then + return x / 100 * (ref or 100) + elseif u == "em" then + return x * (fontSize or 16) + elseif u == "ex" then + return x * (fontSize or 16) / 2 + end + local k = UNITS[u] + return if k then x * k else nil +end + +-- numbers(s) -> the numbers of a whitespace / comma separated list ("1, 2 3e1-4"); stops at anything else +function Style.numbers(s: string?): { number } + local out = {} + if s == nil then + return out + end + local i, n = 1, #s + while i <= n do + local c = string.byte(s, i) + if c == 32 or c == 44 or c == 9 or c == 10 or c == 13 then + i += 1 + else + local v, j = scan(s, i) + if v == nil then + break + end + table.insert(out, v) + i = j + end + end + return out +end + +-- transform(s) -> { a, b, c, d, e, f } (the product of the list) | nil on a syntax error +local function mul(m: { number }, n: { number }): { number } + 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 +Style.multiply = mul +function Style.transform(s: string): { number }? + local m = { 1, 0, 0, 1, 0, 0 } + local rest = s + while true do + rest = string.gsub(rest, "^[%s,]+", "") + if rest == "" then + break + end + local name, args, after = string.match(rest, "^(%a+)%s*(%b())(.*)$") + if not name then + return nil + end + rest = after :: string + local v = Style.numbers(string.sub(args :: string, 2, -2)) + local t: { number } + if name == "matrix" and #v == 6 then + t = v + elseif name == "translate" and (#v == 1 or #v == 2) then + t = { 1, 0, 0, 1, v[1], v[2] or 0 } + elseif name == "scale" and (#v == 1 or #v == 2) then + t = { v[1], 0, 0, v[2] or v[1], 0, 0 } + elseif name == "rotate" and (#v == 1 or #v == 3) then + local r = v[1] * math.pi / 180 + local c, sn = math.cos(r), math.sin(r) + t = { c, sn, -sn, c, 0, 0 } + if #v == 3 then + t = mul(mul({ 1, 0, 0, 1, v[2], v[3] }, t), { 1, 0, 0, 1, -v[2], -v[3] }) + end + elseif name == "skewX" and #v == 1 then + t = { 1, 0, math.tan(v[1] * math.pi / 180), 1, 0, 0 } + elseif name == "skewY" and #v == 1 then + t = { 1, math.tan(v[1] * math.pi / 180), 0, 1, 0, 0 } + else + return nil + end + m = mul(m, t) + end + return m +end + +-- declarations("a: b; c: d") -> { [name] = value } (lower-case names, !important dropped) +function Style.declarations(s: string): { [string]: string } + local out: { [string]: string } = {} + for decl in string.gmatch(s, "[^;]+") do + local k, v = string.match(decl, "^%s*([%w-]+)%s*:%s*(.-)%s*$") + if k and v then + v = string.gsub(v :: string, "%s*!important$", "") + out[string.lower(k :: string)] = v :: string + end + end + return out +end + +-- ------------------------------------------------------------------------------------------------ CSS +export type Selector = { tag: string?, id: string?, classes: { string }, specificity: number } +export type Rule = { selector: Selector, decls: { [string]: string }, order: number } + +local function selector(s: string): Selector? + s = string.gsub(s, "^%s*(.-)%s*$", "%1") + if s == "" or string.find(s, "[%s>+~%[:]") then + return nil -- combinators, attribute and pseudo selectors: not supported + end + local sel: Selector = { classes = {}, specificity = 0 } + local tag = string.match(s, "^([%a_][%w_-]*)") + if tag then + sel.tag = tag + sel.specificity += 1 + s = string.sub(s, #tag + 1) + elseif string.sub(s, 1, 1) == "*" then + s = string.sub(s, 2) + end + while s ~= "" do + local kind, name, rest = string.match(s, "^([.#])([%w_-]+)(.*)$") + if not kind then + return nil + end + if kind == "." then + table.insert(sel.classes, name :: string) + sel.specificity += 100 + else + sel.id = name + sel.specificity += 10000 + end + s = rest :: string + end + return sel +end + +-- css(text, rules?) -> rules (appended to the list given) +function Style.css(text: string, rules: { Rule }?): { Rule } + local out: { Rule } = rules or {} + text = string.gsub(text, "/%*.-%*/", "") + text = string.gsub(text, "<!%-%-", "") + text = string.gsub(text, "%-%->", "") + -- drop @rules with blocks (@media { ... { } }) and simple ones (@import ...;) + local guard = 0 + while guard < 100 do + guard += 1 + local s, e = string.find(text, "@[%w-]+[^{;]*%b{}") + if not s then + break + end + text = string.sub(text, 1, s - 1) .. string.sub(text, e + 1) + end + text = string.gsub(text, "@[%w-]+[^;{]*;", "") + for sels, body in string.gmatch(text, "([^{}]+)(%b{})") do + local decls = Style.declarations(string.sub(body, 2, -2)) + for one in string.gmatch(sels, "[^,]+") do + local sel = selector(one) + if sel then + table.insert(out, { selector = sel, decls = decls, order = #out + 1 }) + end + end + end + return out +end + +-- matches(sel, tag, id, classes) -> boolean +function Style.matches(sel: Selector, tag: string, id: string?, classes: { [string]: boolean }): boolean + if sel.tag and sel.tag ~= tag then + return false + end + if sel.id and sel.id ~= id then + return false + end + for _, c in sel.classes do + if not classes[c] then + return false + end + end + return true +end + +return Style diff --git a/src/Formats/vector/svg/Write.luau b/src/Formats/vector/svg/Write.luau new file mode 100644 index 0000000..5ca891a --- /dev/null +++ b/src/Formats/vector/svg/Write.luau @@ -0,0 +1,203 @@ +--!strict +-- vector/svg/Write: a Types.Vector to SVG text: <svg> with width / height / viewBox / preserveAspectRatio, gradients +-- and clip paths in <defs>, groups as nested <g opacity clip-path>, every path as <path d transform fill stroke ...> +-- (colour alpha as fill- / stroke-opacity). Never throws: bad values return nil, message. +local Xml = require("@formats/codecs/Xml") +local Types = require("@formats/Types") +local PathData = require("@formats/vector/svg/PathData") + +local Write = {} + +local num = PathData.num + +local function el(name: string, attrs: { { any } }, children: { any }?): any + local o = Types.object() + for _, kv in attrs do + if kv[2] ~= nil then + Types.set(o, kv[1], if type(kv[2]) == "number" then num(kv[2]) else tostring(kv[2])) + end + end + return Xml.element(name, o :: any, children) +end + +local function hex(c: { number }): string + return string.format("#%02x%02x%02x", math.clamp(math.floor(c[1] or 0), 0, 255), math.clamp(math.floor(c[2] or 0), 0, 255), math.clamp(math.floor(c[3] or 0), 0, 255)) +end + +local function matrix(m: any): string? + if type(m) ~= "table" or #m < 6 then + return nil + end + if m[1] == 1 and m[2] == 0 and m[3] == 0 and m[4] == 1 then + if m[5] == 0 and m[6] == 0 then + return nil + end + return "translate(" .. num(m[5]) .. " " .. num(m[6]) .. ")" + end + local parts = {} + for k = 1, 6 do + parts[k] = num(tonumber(m[k]) or 0) + end + return "matrix(" .. table.concat(parts, " ") .. ")" +end + +-- write(v) -> SVG text | nil, message +function Write.vector(v: Types.Vector): (string?, string?) + if type(v) ~= "table" or type(v.paths) ~= "table" or type(v.width) ~= "number" or type(v.height) ~= "number" then + return nil, "needs a Vector value" + end + local meta: any = if type(v.meta) == "table" then v.meta else {} + local groups: { any } = if type(meta.groups) == "table" then meta.groups else {} + local clips: { any } = if type(meta.clips) == "table" then meta.clips else {} + local defs = {} + local gradients = 0 + -- paints -> attribute values (gradients go to defs) + local function paintAttrs(p: any, which: string): { { any } } + if type(p) ~= "table" then + return { { which, "none" } } + end + if p.type == "color" and type(p.color) == "table" then + local a = p.color[4] or 255 + return { { which, hex(p.color) }, { which .. "-opacity", if a < 255 then num(a / 255) else nil } } + end + if p.type ~= "linear" and p.type ~= "radial" then + return { { which, "none" } } + end + gradients += 1 + local id = "g" .. gradients + local kids = {} + for _, s in (if type(p.stops) == "table" then p.stops else {}) do + local a = s[5] or 255 + table.insert(kids, el("stop", { { "offset", s[1] or 0 }, { "stop-color", hex({ s[2], s[3], s[4] }) }, { "stop-opacity", if a < 255 then num(a / 255) else nil } })) + end + local attrs: { { any } } = { { "id", id }, { "gradientUnits", if p.units == "userSpaceOnUse" then "userSpaceOnUse" else nil } } + if p.type == "linear" then + table.insert(attrs, { "x1", p.x1 or 0 }) + table.insert(attrs, { "y1", p.y1 or 0 }) + table.insert(attrs, { "x2", p.x2 or 1 }) + table.insert(attrs, { "y2", p.y2 or 0 }) + else + table.insert(attrs, { "cx", p.cx or 0.5 }) + table.insert(attrs, { "cy", p.cy or 0.5 }) + table.insert(attrs, { "r", p.r or 0.5 }) + table.insert(attrs, { "fx", p.fx }) + table.insert(attrs, { "fy", p.fy }) + if p.fr and p.fr ~= 0 then + table.insert(attrs, { "fr", p.fr }) + end + end + table.insert(attrs, { "spreadMethod", if p.spread and p.spread ~= "pad" then p.spread else nil }) + table.insert(attrs, { "gradientTransform", matrix(p.transform) }) + table.insert(defs, el(if p.type == "linear" then "linearGradient" else "radialGradient", attrs, kids)) + local op = tonumber(p.opacity) or 1 + return { { which, "url(#" .. id .. ")" }, { which .. "-opacity", if op < 1 then num(op) else nil } } + end + local clipIds: { [number]: string } = {} + local function clipRef(id: number?): string? + if id == nil or type(clips[id]) ~= "table" then + return nil + end + if clipIds[id] == nil then + local cid = "c" .. id + clipIds[id] = cid + local kids = {} + for _, cp in (if type(clips[id].paths) == "table" then clips[id].paths else {}) do + table.insert(kids, el("path", { { "d", PathData.serialize(cp.d or {}) }, { "transform", matrix(cp.transform) }, { "clip-rule", if cp.rule == "evenodd" then "evenodd" else nil } })) + end + table.insert(defs, el("clipPath", { { "id", cid } }, kids)) + end + return "url(#" .. clipIds[id] .. ")" + end + local root = {} + -- the open <g> stack: { id, children } + local stack: { { id: number?, kids: { any } } } = { { id = nil, kids = root } } + local function chain(g: number?): { number } + local out = {} + local guard = 0 + while g ~= nil and guard < 256 do + table.insert(out, 1, g) + local gr = groups[g] + g = if type(gr) == "table" then gr.parent else nil + guard += 1 + end + return out + end + for _, p in v.paths do + if type(p) ~= "table" or type(p.d) ~= "table" then + continue + end + local want = chain(p.group) + local keep = 1 + while keep < #stack and stack[keep + 1].id == want[keep] do + keep += 1 + end + while #stack > keep do + table.remove(stack) + end + for k = keep, #want do + local gr = groups[want[k]] or {} + local kids = {} + local op = tonumber(gr.opacity) or 1 + table.insert(stack[#stack].kids, el("g", { { "opacity", if op < 1 then op else nil }, { "clip-path", clipRef(gr.clip) } }, kids)) + table.insert(stack, { id = want[k], kids = kids }) + end + local attrs: { { any } } = { { "id", p.id }, { "d", PathData.serialize(p.d) }, { "transform", matrix(p.transform) } } + for _, kv in paintAttrs(p.fill, "fill") do + table.insert(attrs, kv) + end + table.insert(attrs, { "fill-rule", if p.fillRule == "evenodd" then "evenodd" else nil }) + for _, kv in paintAttrs(p.stroke, "stroke") do + if kv[2] ~= "none" then + table.insert(attrs, kv) + end + end + if type(p.stroke) == "table" then + local sw = tonumber(p.strokeWidth) or 1 + table.insert(attrs, { "stroke-width", if sw ~= 1 then sw else nil }) + table.insert(attrs, { "stroke-linejoin", if p.strokeLineJoin and p.strokeLineJoin ~= "miter" then p.strokeLineJoin else nil }) + table.insert(attrs, { "stroke-linecap", if p.strokeLineCap and p.strokeLineCap ~= "butt" then p.strokeLineCap else nil }) + local ml = tonumber(p.strokeMiterLimit) + table.insert(attrs, { "stroke-miterlimit", if ml and ml ~= 4 then ml else nil }) + if type(p.strokeDashArray) == "table" and #p.strokeDashArray > 0 then + local parts = {} + for k, d in p.strokeDashArray do + parts[k] = num(tonumber(d) or 0) + end + table.insert(attrs, { "stroke-dasharray", table.concat(parts, " ") }) + local off = tonumber(p.strokeDashOffset) + table.insert(attrs, { "stroke-dashoffset", if off and off ~= 0 then off else nil }) + end + end + local op = tonumber(p.opacity) or 1 + table.insert(attrs, { "opacity", if op < 1 then op else nil }) + local node = el("path", attrs) + local cr = clipRef(p.clip) + if cr then + node = el("g", { { "clip-path", cr } }, { node }) + end + table.insert(stack[#stack].kids, node) + end + local children = {} + if #defs > 0 then + table.insert(children, el("defs", {}, defs)) + end + for _, c in root do + table.insert(children, c) + end + local vb = v.viewBox + local vbText = if type(vb) == "table" and #vb == 4 then num(vb[1]) .. " " .. num(vb[2]) .. " " .. num(vb[3]) .. " " .. num(vb[4]) else nil + local svg = el("svg", { + { "xmlns", "http://www.w3.org/2000/svg" }, + { "width", v.width }, + { "height", v.height }, + { "viewBox", vbText }, + { "preserveAspectRatio", meta.preserveAspectRatio }, + }, children) + local s, err = Xml.encode(Xml.document(svg, { version = "1.0", encoding = "UTF-8" }), { indent = 1 }) + if not s then + return nil, tostring(err) + end + return s .. "\n", nil +end + +return Write diff --git a/src/Formats/vector/svg/init.luau b/src/Formats/vector/svg/init.luau new file mode 100644 index 0000000..0ec3be9 --- /dev/null +++ b/src/Formats/vector/svg/init.luau @@ -0,0 +1,96 @@ +--!strict +-- vector/svg: SVG 1.1 / SVG 2 static documents (W3C SVG 1.1 2nd ed., SVG 2 CR). Supports: paths (every command, arcs +-- as cubic Béziers), rect (rounded), circle, ellipse, line, polyline, polygon, transforms, g / a / switch, nested svg +-- (viewBox + preserveAspectRatio), use (also of symbol), defs, presentation attributes, style="", a CSS subset from +-- <style> (type, .class, #id, * and compound selectors, specificity), inheritance, currentColor, fill / stroke / +-- opacity / fill-opacity / stroke-opacity, fill-rule, stroke width / joins / caps / miter limit / dashes, linear and +-- radial gradients (units, gradientTransform, spreadMethod, href inheritance, focal point), group opacity, clip-path +-- (userSpaceOnUse and objectBoundingBox, on shapes and groups), units (px pt pc mm cm in em ex %). +-- Decodes to a Types.Vector (paths in their user space with the full transform to the root's viewBox space; groups and +-- clips in meta); Svg.rasterize(v, w, h) renders it with codecs/Raster; encode writes SVG back from a Vector. +-- Not supported (counted in meta.unsupported): text, image, pattern, mask, marker, filter, foreignObject; also +-- conditional processing in switch, CSS combinators / pseudo-classes, non-scaling strokes. + +-- ------------------------------------------------------------------------------------------------ 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 Parse = require("@formats/vector/svg/Parse") +local Render = require("@formats/vector/svg/Render") +local Write = require("@formats/vector/svg/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local Svg = { + name = "svg", + category = "vector", + 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 }, +} + +export type DecodeOptions = { + maxBytes: number?, -- refuse larger files (default 64 MB) +} +export type EncodeOptions = {} +export type RasterizeOptions = Render.Options + +-- ------------------------------------------------------------------------------------------------ sniff +function Svg.sniff(r: Bytes.Reader): number + local h = r:peek(4096) + if string.sub(h, 1, 3) == "\239\187\191" then + h = string.sub(h, 4) + end + if not string.match(h, "^%s*<") then + return 0 + end + if string.find(h, "<svg[%s>:]") or string.find(h, "<%w+:svg[%s>]") then + return 0.95 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Svg.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Vector?, Err.Err?) + local maxBytes = opts and opts.maxBytes or 2 ^ 26 + if r.limit - r.base > maxBytes then + return nil, Err.new(Err.LIMIT, "file is over the byte limit") + end + local doc, xerr = Xml.decode(buffer.readstring(r.buf, r.base, r.limit - r.base)) + if not doc then + return nil, xerr + end + local v, msg = Parse.document(doc) + if not v then + return nil, Err.new(Err.CORRUPT, msg or "bad SVG") + end + v.meta.source = { format = "svg" } + return v, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Svg.encode(v: Types.Vector, opts: EncodeOptions?): (buffer?, Err.Err?) + local s, err = Write.vector(v) + if not s then + return nil, Err.new(Err.ARG, err or "bad Vector") + end + return buffer.fromstring(s), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- rasterize(v, w?, h?, opts?) -> rgba8 Image | nil, Err. w / h default to the vector's size (rounded up); the viewBox +-- maps onto w x h by its preserveAspectRatio. +function Svg.rasterize(v: Types.Vector, w: number?, h: number?, opts: RasterizeOptions?): (Types.Image?, Err.Err?) + if type(v) ~= "table" or type(v.paths) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Vector value") + end + local W = math.ceil(w or v.width or 0) + local H = math.ceil(h or v.height or 0) + if W < 1 or H < 1 or W * H > 2 ^ 26 then + return nil, Err.new(Err.ARG, "bad raster size") + end + return Render.rasterize(v, W, H, opts), nil +end + +return Svg diff --git a/src/Formats/vector/tiled/Data.luau b/src/Formats/vector/tiled/Data.luau new file mode 100644 index 0000000..7338b74 --- /dev/null +++ b/src/Formats/vector/tiled/Data.luau @@ -0,0 +1,156 @@ +--!strict +-- vector/tiled/Data: tile layer data shared by the TMX and TMJ halves: CSV text, base64 (uncompressed, zlib, gzip) +-- to gids and back; property values and their types; number formatting. Never throws. +local Base64 = require("@formats/core/Base64") +local Deflate = require("@formats/codecs/Deflate") + +local Data = {} + +-- csv(text) -> { gid } (any whitespace / commas between the numbers) | nil, message +function Data.csv(text: string): ({ number }?, string?) + local out = {} + for tok in string.gmatch(text, "[^,%s]+") do + local v = tonumber(tok) + if v == nil or v < 0 or v >= 4294967296 or v % 1 ~= 0 then + return nil, "bad gid " .. string.sub(tok, 1, 20) + end + table.insert(out, v) + end + return out, nil +end + +-- base64(text, compression) -> { gid } | nil, message, unsupported? +function Data.base64(text: string, compression: string?): ({ number }?, string?, boolean?) + local raw, err = Base64.decode(text) + if not raw then + return nil, err + end + local bytes: buffer = raw + if compression == "zlib" then + local z, zerr = Deflate.zlib(bytes) + if not z then + return nil, "zlib: " .. tostring(zerr) + end + bytes = z + elseif compression == "gzip" then + local z, zerr = Deflate.gunzip(bytes) + if not z then + return nil, "gzip: " .. tostring(zerr) + end + bytes = z + elseif compression ~= nil and compression ~= "" then + return nil, "compression " .. compression .. " is not supported", true + end + local n = buffer.len(bytes) // 4 + local out = table.create(n) + for i = 0, n - 1 do + out[i + 1] = buffer.readu32(bytes, i * 4) + end + return out, nil +end + +-- toBase64(gids, compression?, level?) -> text | nil, message +function Data.toBase64(gids: { number }, compression: string?, level: number?): (string?, string?) + local b = buffer.create(#gids * 4) + for i, g in gids do + buffer.writeu32(b, (i - 1) * 4, g % 4294967296) + end + if compression == "zlib" then + local z = Deflate.zlibCompress(b, { level = level or 6 }) + if not z then + return nil, "zlib failed" + end + b = z + elseif compression == "gzip" then + local z = Deflate.gzip(b, { level = level or 6 }) + if not z then + return nil, "gzip failed" + end + b = z + elseif compression ~= nil and compression ~= "" then + return nil, "compression " .. compression .. " is not supported" + end + return Base64.encode(b), nil +end + +-- num(v) -> text: integers without a fraction (gids up to 2^32 too), others in the shortest form both runtimes print +function Data.num(v: number): string + if v % 1 == 0 and math.abs(v) < 2 ^ 53 then + return string.format("%.0f", v) + end + local s = string.format("%.15g", v) + if tonumber(s) ~= v then + s = string.format("%.17g", v) + end + return s +end + +-- csvText(gids, width) -> "1,2,3,\n4,5,6" (Tiled's layout: one row per line) +function Data.csvText(gids: { number }, width: number): string + local rows = {} + local row = {} + for i, g in gids do + table.insert(row, Data.num(g)) + if width > 0 and i % width == 0 then + table.insert(rows, table.concat(row, ",")) + row = {} + end + end + if #row > 0 then + table.insert(rows, table.concat(row, ",")) + end + return "\n" .. table.concat(rows, ",\n") .. "\n" +end + +-- color(s) -> Tiled's canonical colour text: lower case "#rrggbb", or "#aarrggbb" when not opaque (nil stays nil) +function Data.color(s: string?): string? + if type(s) ~= "string" then + return nil + end + local h = string.lower((string.gsub(s, "^#", ""))) + if #h == 8 and string.sub(h, 1, 2) == "ff" then + h = string.sub(h, 3) + end + return "#" .. h +end + +-- property values: TMX / TMJ type names -> a Luau value from text +function Data.value(typ: string, text: string): any + if typ == "int" or typ == "float" or typ == "object" then + return tonumber(text) or 0 + elseif typ == "bool" then + return text == "true" or text == "1" + elseif typ == "color" then + return Data.color(text) or "" + end + return text +end + +-- typeOf(v, declared?) -> the Tiled type to write for v +function Data.typeOf(v: any, declared: string?): string + if declared then + return declared + end + if type(v) == "boolean" then + return "bool" + elseif type(v) == "number" then + return if v % 1 == 0 then "int" else "float" + elseif type(v) == "table" then + return "class" + end + return "string" +end + +-- sortedKeys(t) -> its string keys, sorted +function Data.sortedKeys(t: { [any]: any }): { string } + local out = {} + for k in pairs(t) do + if type(k) == "string" then + table.insert(out, k) + end + end + table.sort(out) + return out +end + +return Data diff --git a/src/Formats/vector/tiled/Tmj.luau b/src/Formats/vector/tiled/Tmj.luau new file mode 100644 index 0000000..ce23c8a --- /dev/null +++ b/src/Formats/vector/tiled/Tmj.luau @@ -0,0 +1,634 @@ +--!strict +-- vector/tiled/Tmj: the TMJ (JSON) half of vector/tiled: a decoded JSON value <-> a Types.TileMap, and TSJ +-- tilesets. JSON map format, Tiled 1.12 docs. Never throws: failures return nil, message, unsupported?. +local Types = require("@formats/Types") +local Data = require("@formats/vector/tiled/Data") + +local Tmj = {} + +local function n(v: any, default: number?): number? + if type(v) == "number" then + return v + end + return default +end +local function b(v: any, default: boolean): boolean + if type(v) == "boolean" then + return v + end + return default +end +local function s(v: any): string? + if type(v) == "string" then + return v + end + return nil +end +local function list(v: any): { any } + if type(v) == "table" then + return v + end + return {} +end + +-- ------------------------------------------------------------------------------------------------ read +local function properties(v: any): ({ [string]: any }, { [string]: string }?) + local props: { [string]: any } = {} + local types: { [string]: string }? = nil + for _, p in list(v) do + if type(p) == "table" and type(p.name) == "string" then + local typ = s(p.type) or "string" + local val: any = p.value + if typ == "class" then + local inner, innerTypes = {}, nil + if type(val) == "table" then + -- a class value is an object of member -> value (types come from the project): keep them as they are + for k, x in pairs(val) do + if type(k) == "string" then + inner[k] = x + end + end + end + val = { class = s(p.propertytype) or "", properties = inner, propertyTypes = innerTypes } + elseif typ == "int" or typ == "float" or typ == "object" then + val = n(val, 0) + elseif typ == "bool" then + val = val == true + elseif typ == "color" then + val = Data.color(s(val)) or "" + elseif type(val) ~= "string" then + val = if val == nil then "" else tostring(val) + end + props[p.name] = val + if typ ~= "string" then + types = types or {} + ;(types :: any)[p.name] = typ + end + end + end + return props, types +end + +local function withProps(t: any, v: any) + local props, types = properties(v.properties) + t.properties = props + if types then + t.propertyTypes = types + end +end + +local function gids(v: any, encoding: string?, compression: string?): ({ number }?, string?, boolean?) + if type(v) == "string" then + if encoding == "base64" or encoding == nil then + return Data.base64(v, compression) + end + return nil, "unknown encoding " .. tostring(encoding), true + end + local out = {} + for _, g in list(v) do + if type(g) ~= "number" or g < 0 or g >= 4294967296 then + return nil, "bad gid" + end + table.insert(out, g) + end + return out, nil +end + +local function object(o: any): any + local obj: any = { + id = n(o.id), + name = s(o.name) or "", + class = s(o.class) or s(o.type) or "", + x = n(o.x, 0), + y = n(o.y, 0), + width = n(o.width, 0), + height = n(o.height, 0), + rotation = n(o.rotation, 0), + gid = n(o.gid), + visible = b(o.visible, true), + template = s(o.template), + shape = "rectangle", + } + withProps(obj, o) + if o.ellipse == true then + obj.shape = "ellipse" + elseif o.point == true then + obj.shape = "point" + end + for _, kind in { "polygon", "polyline" } do + if type(o[kind]) == "table" then + obj.shape = kind + local pts = {} + for _, p in o[kind] do + if type(p) == "table" then + table.insert(pts, { n(p.x, 0), n(p.y, 0) }) + end + end + obj.points = pts + end + end + if type(o.text) == "table" then + local t = o.text + obj.shape = "text" + obj.text = { + text = s(t.text) or "", + fontFamily = s(t.fontfamily) or "sans-serif", + pixelSize = n(t.pixelsize, 16), + wrap = b(t.wrap, false), + color = Data.color(s(t.color)) or "#000000", + bold = b(t.bold, false), + italic = b(t.italic, false), + underline = b(t.underline, false), + strikeout = b(t.strikeout, false), + kerning = b(t.kerning, true), + halign = s(t.halign) or "left", + valign = s(t.valign) or "top", + } + end + return obj +end + +local TYPES = { tilelayer = "tiles", objectgroup = "objects", imagelayer = "image", group = "group" } + +local layer: (v: any, depth: number) -> (any, string?, boolean?) + +local function common(v: any, typ: string): any + local l: any = { + type = typ, + id = n(v.id), + name = s(v.name) or "", + visible = b(v.visible, true), + opacity = n(v.opacity, 1), + x = n(v.x, 0), + y = n(v.y, 0), + offsetX = n(v.offsetx, 0), + offsetY = n(v.offsety, 0), + parallaxX = n(v.parallaxx, 1), + parallaxY = n(v.parallaxy, 1), + tintColor = Data.color(s(v.tintcolor)), + class = s(v.class) or "", + locked = b(v.locked, false), + } + withProps(l, v) + return l +end + +local function objectGroup(v: any): any + local l = common(v, "objects") + l.drawOrder = s(v.draworder) or "topdown" + l.color = Data.color(s(v.color)) + l.objects = {} + for _, o in list(v.objects) do + if type(o) == "table" then + table.insert(l.objects, object(o)) + end + end + return l +end + +layer = function(v: any, depth: number): (any, string?, boolean?) + if type(v) ~= "table" then + return nil, "a layer is not an object" + end + if depth > 100 then + return nil, "groups nested too deep" + end + local typ = TYPES[v.type] + if typ == "tiles" then + local l = common(v, "tiles") + l.width = n(v.width, 0) + l.height = n(v.height, 0) + l.encoding = s(v.encoding) + l.compression = s(v.compression) + if type(v.chunks) == "table" then + l.chunks = {} + for _, c in v.chunks do + if type(c) == "table" then + local g, err, uns = gids(c.data, l.encoding, l.compression) + if not g then + return nil, err, uns + end + table.insert(l.chunks, { x = n(c.x, 0), y = n(c.y, 0), width = n(c.width, 0), height = n(c.height, 0), data = g }) + end + end + elseif v.data ~= nil then + local g, err, uns = gids(v.data, l.encoding, l.compression) + if not g then + return nil, err, uns + end + l.data = g + end + return l + elseif typ == "objects" then + return objectGroup(v) + elseif typ == "image" then + local l = common(v, "image") + l.imageSource = s(v.image) + l.imageWidth = n(v.imagewidth) + l.imageHeight = n(v.imageheight) + l.transparentColor = Data.color(s(v.transparentcolor)) + l.repeatX = b(v.repeatx, false) + l.repeatY = b(v.repeaty, false) + return l + elseif typ == "group" then + local l = common(v, "group") + l.layers = {} + for _, c in list(v.layers) do + local sub, err, uns = layer(c, depth + 1) + if not sub then + return nil, err, uns + end + table.insert(l.layers, sub) + end + return l + end + return nil, "unknown layer type " .. tostring(v.type) +end + +-- tileset(v) -> Tileset (a map's entry, or a .tsj root) +function Tmj.tileset(v: any): any + local ts: any = { + firstGid = n(v.firstgid, 1), + source = s(v.source), + name = s(v.name) or "", + tileWidth = n(v.tilewidth, 0), + tileHeight = n(v.tileheight, 0), + spacing = n(v.spacing, 0), + margin = n(v.margin, 0), + count = n(v.tilecount, 0), + columns = n(v.columns, 0), + objectAlignment = s(v.objectalignment), + class = s(v.class) or "", + imageSource = s(v.image), + imageWidth = n(v.imagewidth), + imageHeight = n(v.imageheight), + transparentColor = Data.color(s(v.transparentcolor)), + } + withProps(ts, v) + if type(v.tileoffset) == "table" then + ts.tileOffset = { x = n(v.tileoffset.x, 0), y = n(v.tileoffset.y, 0) } + end + local tiles = {} + for _, t in list(v.tiles) do + if type(t) == "table" then + local tile: any = { id = n(t.id, 0), class = s(t.class) or s(t.type) or "", probability = n(t.probability) } + withProps(tile, t) + tile.imageSource = s(t.image) + tile.imageWidth = n(t.imagewidth) + tile.imageHeight = n(t.imageheight) + if type(t.animation) == "table" then + tile.animation = {} + for _, f in t.animation do + if type(f) == "table" then + table.insert(tile.animation, { tileId = n(f.tileid, 0), duration = n(f.duration, 0) }) + end + end + end + if type(t.objectgroup) == "table" then + tile.objectGroup = objectGroup(t.objectgroup) + end + table.insert(tiles, tile) + end + end + table.sort(tiles, function(x: any, y: any): boolean + return x.id < y.id + end) + ts.tiles = tiles + return ts +end + +-- read(value) -> TileMap | nil, message, unsupported? +function Tmj.read(v: any): (any, string?, boolean?) + if type(v) ~= "table" or (v.type ~= nil and v.type ~= "map") then + return nil, "not a Tiled map (type is not \"map\")" + end + local map: any = Types.TileMap.new(n(v.width, 0) :: number, n(v.height, 0) :: number, n(v.tilewidth, 0) :: number, n(v.tileheight, 0) :: number) + map.version = if type(v.version) == "number" then Data.num(v.version) else s(v.version) + map.tiledVersion = s(v.tiledversion) + map.orientation = s(v.orientation) or "orthogonal" + map.renderOrder = s(v.renderorder) or "right-down" + map.infinite = b(v.infinite, false) + map.nextLayerId = n(v.nextlayerid) + map.nextObjectId = n(v.nextobjectid) + map.backgroundColor = Data.color(s(v.backgroundcolor)) + map.hexSideLength = n(v.hexsidelength) + map.staggerAxis = s(v.staggeraxis) + map.staggerIndex = s(v.staggerindex) + map.class = s(v.class) or "" + map.parallaxOriginX = n(v.parallaxoriginx, 0) + map.parallaxOriginY = n(v.parallaxoriginy, 0) + withProps(map, v) + for _, ts in list(v.tilesets) do + if type(ts) == "table" then + table.insert(map.tilesets, Tmj.tileset(ts)) + end + end + for _, l in list(v.layers) do + local x, err, uns = layer(l, 0) + if not x then + return nil, err, uns + end + table.insert(map.layers, x) + end + return map, nil +end + +-- ------------------------------------------------------------------------------------------------ write +local function obj(pairs_: { { any } }): any + local o = Types.object() + for _, kv in pairs_ do + if kv[2] ~= nil then + Types.set(o, kv[1], kv[2]) + end + end + return o +end +local function nz(v: any, default: any): any + if v == nil or v == default then + return nil + end + return v +end +local function str(v: any): string? + if type(v) == "string" and v ~= "" then + return v + end + return nil +end + +local function propList(props: any, types: any): { any }? + if type(props) ~= "table" or next(props) == nil then + return nil + end + local out = {} + for _, k in Data.sortedKeys(props) do + local v = props[k] + local typ = Data.typeOf(v, if type(types) == "table" then types[k] else nil) + if typ == "class" and type(v) == "table" then + local members = Types.object() + if type(v.properties) == "table" then + for _, mk in Data.sortedKeys(v.properties) do + Types.set(members, mk, v.properties[mk]) + end + end + table.insert(out, obj({ { "name", k }, { "propertytype", v.class or "" }, { "type", "class" }, { "value", members } })) + else + table.insert(out, obj({ { "name", k }, { "type", typ }, { "value", v } })) + end + end + return out +end + +local function writeObject(o: any): any + local t: any = nil + if o.shape == "text" and type(o.text) == "table" then + local x = o.text + t = obj({ + { "bold", nz(x.bold, false) }, + { "color", nz(x.color, "#000000") }, + { "fontfamily", nz(x.fontFamily, "sans-serif") }, + { "halign", nz(x.halign, "left") }, + { "italic", nz(x.italic, false) }, + { "kerning", nz(x.kerning, true) }, + { "pixelsize", nz(x.pixelSize, 16) }, + { "strikeout", nz(x.strikeout, false) }, + { "text", tostring(x.text or "") }, + { "underline", nz(x.underline, false) }, + { "valign", nz(x.valign, "top") }, + { "wrap", nz(x.wrap, false) }, + }) + end + local pts: any = nil + if (o.shape == "polygon" or o.shape == "polyline") and type(o.points) == "table" then + pts = {} + for _, p in o.points do + table.insert(pts, obj({ { "x", tonumber(p[1]) or 0 }, { "y", tonumber(p[2]) or 0 } })) + end + end + return obj({ + { "ellipse", if o.shape == "ellipse" then true else nil }, + { "gid", o.gid }, + { "height", o.height or 0 }, + { "id", o.id }, + { "name", o.name or "" }, + { "point", if o.shape == "point" then true else nil }, + { "polygon", if o.shape == "polygon" then pts else nil }, + { "polyline", if o.shape == "polyline" then pts else nil }, + { "properties", propList(o.properties, o.propertyTypes) }, + { "rotation", o.rotation or 0 }, + { "template", o.template }, + { "text", t }, + { "type", o.class or "" }, + { "visible", o.visible ~= false }, + { "width", o.width or 0 }, + { "x", o.x or 0 }, + { "y", o.y or 0 }, + }) +end + +export type WriteOptions = { encoding: string?, compression: string?, level: number? } + +local function writeObjectGroup(l: any): any + local objs = {} + for _, o in (if type(l.objects) == "table" then l.objects else {}) do + table.insert(objs, writeObject(o)) + end + return objs +end + +local writeLayer: (l: any, o: WriteOptions) -> (any, string?) + +writeLayer = function(l: any, o: WriteOptions): (any, string?) + local t = l.type + local fields: { { any } } = {} + local function add(k: string, v: any) + table.insert(fields, { k, v }) + end + if t == "tiles" then + local enc = o.encoding or l.encoding + if enc ~= "base64" then + enc = nil + end + local comp = if enc then (o.compression or (if o.encoding then nil else l.compression)) else nil + local function payload(g: { number }): (any, string?) + if enc == "base64" then + return Data.toBase64(g, comp, o.level) + end + return g, nil + end + if type(l.chunks) == "table" then + local chunks = {} + for _, c in l.chunks do + local d, err = payload(c.data or {}) + if d == nil then + return nil, err + end + table.insert(chunks, obj({ { "data", d }, { "height", c.height or 0 }, { "width", c.width or 0 }, { "x", c.x or 0 }, { "y", c.y or 0 } })) + end + add("chunks", chunks) + local sx, sy = math.huge, math.huge + for _, c in l.chunks do + sx, sy = math.min(sx, c.x or 0), math.min(sy, c.y or 0) + end + if #l.chunks > 0 then + add("startx", sx) + add("starty", sy) + end + elseif type(l.data) == "table" then + local d, err = payload(l.data) + if d == nil then + return nil, err + end + add("data", d) + end + add("compression", comp) + add("encoding", enc) + add("height", l.height or 0) + elseif t == "objects" then + add("color", l.color) + add("draworder", l.drawOrder or "topdown") + elseif t == "image" then + add("image", l.imageSource or "") + add("imageheight", l.imageHeight) + add("imagewidth", l.imageWidth) + elseif t == "group" then + local kids = {} + for _, c in (if type(l.layers) == "table" then l.layers else {}) do + local x, err = writeLayer(c, o) + if x == nil then + return nil, err + end + table.insert(kids, x) + end + add("layers", kids) + else + return nil, "unknown layer type " .. tostring(t) + end + add("class", str(l.class)) + add("id", l.id) + add("locked", nz(l.locked, false)) + add("name", l.name or "") + if t == "objects" then + add("objects", writeObjectGroup(l)) + end + add("offsetx", nz(l.offsetX, 0)) + add("offsety", nz(l.offsetY, 0)) + add("opacity", l.opacity or 1) + add("parallaxx", nz(l.parallaxX, 1)) + add("parallaxy", nz(l.parallaxY, 1)) + add("properties", propList(l.properties, l.propertyTypes)) + if t == "image" then + add("repeatx", nz(l.repeatX, false)) + add("repeaty", nz(l.repeatY, false)) + end + add("tintcolor", l.tintColor) + if t == "image" then + add("transparentcolor", l.transparentColor) + end + add("type", if t == "tiles" then "tilelayer" elseif t == "objects" then "objectgroup" elseif t == "image" then "imagelayer" else "group") + add("visible", l.visible ~= false) + if t == "tiles" then + add("width", l.width or 0) + end + add("x", l.x or 0) + add("y", l.y or 0) + return obj(fields), nil +end + +-- tilesetValue(ts, inMap) -> a JSON object +function Tmj.tilesetValue(ts: any, inMap: boolean): any + if inMap and type(ts.source) == "string" then + return obj({ { "firstgid", ts.firstGid or 1 }, { "source", ts.source } }) + end + local tiles: any = nil + if type(ts.tiles) == "table" and #ts.tiles > 0 then + tiles = {} + for _, tile in ts.tiles do + local anim: any = nil + if type(tile.animation) == "table" then + anim = {} + for _, f in tile.animation do + table.insert(anim, obj({ { "duration", f.duration or 0 }, { "tileid", f.tileId or 0 } })) + end + end + local og: any = nil + if type(tile.objectGroup) == "table" then + og = writeLayer(tile.objectGroup, {}) + end + table.insert(tiles, obj({ + { "animation", anim }, + { "id", tile.id or 0 }, + { "image", tile.imageSource }, + { "imageheight", tile.imageHeight }, + { "imagewidth", tile.imageWidth }, + { "objectgroup", og }, + { "probability", tile.probability }, + { "properties", propList(tile.properties, tile.propertyTypes) }, + { "type", str(tile.class) }, + })) + end + end + return obj({ + { "class", str(ts.class) }, + { "columns", ts.columns or 0 }, + { "firstgid", if inMap then ts.firstGid or 1 else nil }, + { "image", ts.imageSource }, + { "imageheight", ts.imageHeight }, + { "imagewidth", ts.imageWidth }, + { "margin", ts.margin or 0 }, + { "name", ts.name or "" }, + { "objectalignment", ts.objectAlignment }, + { "properties", propList(ts.properties, ts.propertyTypes) }, + { "spacing", ts.spacing or 0 }, + { "tilecount", ts.count or 0 }, + { "tileheight", ts.tileHeight or 0 }, + { "tileoffset", if type(ts.tileOffset) == "table" then obj({ { "x", ts.tileOffset.x or 0 }, { "y", ts.tileOffset.y or 0 } }) else nil }, + { "tiles", tiles }, + { "tilewidth", ts.tileWidth or 0 }, + { "transparentcolor", ts.transparentColor }, + { "type", if inMap then nil else "tileset" }, + }) +end + +-- write(map, opts) -> a JSON value | nil, message +function Tmj.write(map: any, o: WriteOptions): (any, string?) + local layers = {} + for _, l in map.layers do + local x, err = writeLayer(l, o) + if x == nil then + return nil, err + end + table.insert(layers, x) + end + local tilesets = {} + for _, ts in map.tilesets do + table.insert(tilesets, Tmj.tilesetValue(ts, true)) + end + return obj({ + { "backgroundcolor", map.backgroundColor }, + { "class", str(map.class) }, + { "compressionlevel", -1 }, + { "height", map.height }, + { "hexsidelength", map.hexSideLength }, + { "infinite", map.infinite == true }, + { "layers", layers }, + { "nextlayerid", map.nextLayerId }, + { "nextobjectid", map.nextObjectId }, + { "orientation", map.orientation or "orthogonal" }, + { "parallaxoriginx", nz(map.parallaxOriginX, 0) }, + { "parallaxoriginy", nz(map.parallaxOriginY, 0) }, + { "properties", propList(map.properties, map.propertyTypes) }, + { "renderorder", map.renderOrder or "right-down" }, + { "staggeraxis", map.staggerAxis }, + { "staggerindex", map.staggerIndex }, + { "tiledversion", map.tiledVersion }, + { "tileheight", map.tileHeight }, + { "tilesets", tilesets }, + { "tilewidth", map.tileWidth }, + { "type", "map" }, + { "version", map.version or "1.10" }, + { "width", map.width }, + }), nil +end + +return Tmj diff --git a/src/Formats/vector/tiled/Tmx.luau b/src/Formats/vector/tiled/Tmx.luau new file mode 100644 index 0000000..b415329 --- /dev/null +++ b/src/Formats/vector/tiled/Tmx.luau @@ -0,0 +1,618 @@ +--!strict +-- vector/tiled/Tmx: the TMX (XML) half of vector/tiled: a codecs/Xml tree <-> a Types.TileMap, and TSX tilesets. +-- TMX map format, Tiled 1.12 docs. Never throws: failures return nil, message, unsupported?. +local Xml = require("@formats/codecs/Xml") +local Types = require("@formats/Types") +local Data = require("@formats/vector/tiled/Data") + +local Tmx = {} + +type Node = Types.XmlNode + +local function a(n: Node, k: string): string? + return (n.attrs :: any)[k] +end +local function num(n: Node, k: string, default: number?): number? + local v = a(n, k) + if v == nil then + return default + end + return tonumber(v) or default +end +local function flag(n: Node, k: string, default: boolean): boolean + local v = a(n, k) + if v == nil then + return default + end + return v == "1" or v == "true" +end + +-- ------------------------------------------------------------------------------------------------ read +-- <properties> -> values, types (types only for the non-string ones) +local function properties(n: Node?): ({ [string]: any }, { [string]: string }?) + local props: { [string]: any } = {} + local types: { [string]: string }? = nil + if n == nil then + return props, nil + end + for _, p in Xml.children(n, "property") do + local name = a(p, "name") + if name then + local typ = a(p, "type") or "string" + local v: any + if typ == "class" then + local inner, innerTypes = properties(Xml.child(p, "properties")) + v = { class = a(p, "propertytype") or "", properties = inner, propertyTypes = innerTypes } + else + local text = a(p, "value") + if text == nil then + text = Xml.text(p) -- multi-line strings + end + v = Data.value(typ, text :: string) + end + props[name] = v + if typ ~= "string" then + types = types or {} + ;(types :: any)[name] = typ + end + end + end + return props, types +end + +local function withProps(t: any, n: Node) + local props, types = properties(Xml.child(n, "properties")) + t.properties = props + if types then + t.propertyTypes = types + end +end + +-- the gids of a <data> (or <chunk>) node +local function gids(d: Node, encoding: string?, compression: string?): ({ number }?, string?, boolean?) + if encoding == "csv" then + return Data.csv(Xml.text(d)) + elseif encoding == "base64" then + return Data.base64(Xml.text(d), compression) + elseif encoding == nil or encoding == "" then + local out = {} + for _, t in Xml.children(d, "tile") do + table.insert(out, num(t, "gid", 0) :: number) + end + return out, nil + end + return nil, "unknown encoding " .. encoding, true +end + +local function object(o: Node): any + local obj: any = { + id = num(o, "id"), + name = a(o, "name") or "", + class = a(o, "class") or a(o, "type") or "", + x = num(o, "x", 0), + y = num(o, "y", 0), + width = num(o, "width", 0), + height = num(o, "height", 0), + rotation = num(o, "rotation", 0), + gid = num(o, "gid"), + visible = flag(o, "visible", true), + template = a(o, "template"), + shape = "rectangle", + } + withProps(obj, o) + if Xml.child(o, "ellipse") then + obj.shape = "ellipse" + elseif Xml.child(o, "point") then + obj.shape = "point" + end + for _, kind in { "polygon", "polyline" } do + local p = Xml.child(o, kind) + if p then + obj.shape = kind + local pts = {} + for x, y in string.gmatch(a(p, "points") or "", "([^,%s]+),([^,%s]+)") do + table.insert(pts, { tonumber(x) or 0, tonumber(y) or 0 }) + end + obj.points = pts + end + end + local t = Xml.child(o, "text") + if t then + obj.shape = "text" + obj.text = { + text = Xml.text(t), + fontFamily = a(t, "fontfamily") or "sans-serif", + pixelSize = num(t, "pixelsize", 16), + wrap = flag(t, "wrap", false), + color = Data.color(a(t, "color")) or "#000000", + bold = flag(t, "bold", false), + italic = flag(t, "italic", false), + underline = flag(t, "underline", false), + strikeout = flag(t, "strikeout", false), + kerning = flag(t, "kerning", true), + halign = a(t, "halign") or "left", + valign = a(t, "valign") or "top", + } + end + return obj +end + +local layer: (n: Node) -> (any, string?, boolean?) + +local function common(n: Node, typ: string): any + local l: any = { + type = typ, + id = num(n, "id"), + name = a(n, "name") or "", + visible = flag(n, "visible", true), + opacity = num(n, "opacity", 1), + x = num(n, "x", 0), + y = num(n, "y", 0), + offsetX = num(n, "offsetx", 0), + offsetY = num(n, "offsety", 0), + parallaxX = num(n, "parallaxx", 1), + parallaxY = num(n, "parallaxy", 1), + tintColor = Data.color(a(n, "tintcolor")), + class = a(n, "class") or "", + locked = flag(n, "locked", false), + } + withProps(l, n) + return l +end + +local function objectGroup(n: Node): any + local l = common(n, "objects") + l.drawOrder = a(n, "draworder") or "topdown" + l.color = Data.color(a(n, "color")) + l.objects = {} + for _, o in Xml.children(n, "object") do + table.insert(l.objects, object(o)) + end + return l +end + +layer = function(n: Node): (any, string?, boolean?) + local name = n.name + if name == "layer" then + local l = common(n, "tiles") + l.width = num(n, "width", 0) + l.height = num(n, "height", 0) + local d = Xml.child(n, "data") + if d then + local enc, comp = a(d, "encoding"), a(d, "compression") + l.encoding, l.compression = enc, comp + local chunks = Xml.children(d, "chunk") + if #chunks > 0 then + l.chunks = {} + for _, c in chunks do + local g, err, uns = gids(c, enc, comp) + if not g then + return nil, err, uns + end + table.insert(l.chunks, { x = num(c, "x", 0), y = num(c, "y", 0), width = num(c, "width", 0), height = num(c, "height", 0), data = g }) + end + else + local g, err, uns = gids(d, enc, comp) + if not g then + return nil, err, uns + end + l.data = g + end + end + return l + elseif name == "objectgroup" then + return objectGroup(n) + elseif name == "imagelayer" then + local l = common(n, "image") + l.repeatX = flag(n, "repeatx", false) + l.repeatY = flag(n, "repeaty", false) + local img = Xml.child(n, "image") + if img then + l.imageSource = a(img, "source") + l.imageWidth = num(img, "width") + l.imageHeight = num(img, "height") + l.transparentColor = Data.color(a(img, "trans")) + end + return l + elseif name == "group" then + local l = common(n, "group") + l.layers = {} + for _, c in n.children do + if type(c) == "table" then + local sub, err, uns = layer(c) + if err then + return nil, err, uns + end + if sub then + table.insert(l.layers, sub) + end + end + end + return l + end + return nil +end + +-- a <tileset> element (in a map, or a .tsx root) -> Tileset +function Tmx.tileset(n: Node): any + local ts: any = { + firstGid = num(n, "firstgid", 1), + source = a(n, "source"), + name = a(n, "name") or "", + tileWidth = num(n, "tilewidth", 0), + tileHeight = num(n, "tileheight", 0), + spacing = num(n, "spacing", 0), + margin = num(n, "margin", 0), + count = num(n, "tilecount", 0), + columns = num(n, "columns", 0), + objectAlignment = a(n, "objectalignment"), + class = a(n, "class") or "", + } + withProps(ts, n) + local off = Xml.child(n, "tileoffset") + if off then + ts.tileOffset = { x = num(off, "x", 0), y = num(off, "y", 0) } + end + local img = Xml.child(n, "image") + if img then + ts.imageSource = a(img, "source") + ts.imageWidth = num(img, "width") + ts.imageHeight = num(img, "height") + ts.transparentColor = Data.color(a(img, "trans")) + end + local tiles = {} + for _, t in Xml.children(n, "tile") do + local tile: any = { id = num(t, "id", 0), class = a(t, "class") or a(t, "type") or "", probability = num(t, "probability") } + withProps(tile, t) + local ti = Xml.child(t, "image") + if ti then + tile.imageSource = a(ti, "source") + tile.imageWidth = num(ti, "width") + tile.imageHeight = num(ti, "height") + end + local anim = Xml.child(t, "animation") + if anim then + tile.animation = {} + for _, f in Xml.children(anim, "frame") do + table.insert(tile.animation, { tileId = num(f, "tileid", 0), duration = num(f, "duration", 0) }) + end + end + local og = Xml.child(t, "objectgroup") + if og then + tile.objectGroup = objectGroup(og) + end + table.insert(tiles, tile) + end + ts.tiles = tiles + return ts +end + +-- read(root) -> TileMap | nil, message, unsupported? +function Tmx.read(root: Node): (any, string?, boolean?) + if root.name ~= "map" then + return nil, "the root element is <" .. root.name .. ">, not <map>" + end + local map: any = Types.TileMap.new(num(root, "width", 0) :: number, num(root, "height", 0) :: number, num(root, "tilewidth", 0) :: number, num(root, "tileheight", 0) :: number) + map.version = a(root, "version") + map.tiledVersion = a(root, "tiledversion") + map.orientation = a(root, "orientation") or "orthogonal" + map.renderOrder = a(root, "renderorder") or "right-down" + map.infinite = flag(root, "infinite", false) + map.nextLayerId = num(root, "nextlayerid") + map.nextObjectId = num(root, "nextobjectid") + map.backgroundColor = Data.color(a(root, "backgroundcolor")) + map.hexSideLength = num(root, "hexsidelength") + map.staggerAxis = a(root, "staggeraxis") + map.staggerIndex = a(root, "staggerindex") + map.class = a(root, "class") or "" + map.parallaxOriginX = num(root, "parallaxoriginx", 0) + map.parallaxOriginY = num(root, "parallaxoriginy", 0) + withProps(map, root) + for _, c in root.children do + if type(c) == "table" then + if c.name == "tileset" then + table.insert(map.tilesets, Tmx.tileset(c)) + else + local l, err, uns = layer(c) + if err then + return nil, err, uns + end + if l then + table.insert(map.layers, l) + end + end + end + end + return map, nil +end + +-- ------------------------------------------------------------------------------------------------ write +type Attrs = { [string]: string } + +local function el(name: string, attrs: { { any } }, children: { any }?): Node + -- attrs in order; nil / default values dropped by the caller + local o = Types.object() + for _, kv in attrs do + if kv[2] ~= nil then + local v = kv[2] + Types.set(o, kv[1], if type(v) == "number" then Data.num(v) elseif type(v) == "boolean" then (if v then "1" else "0") else tostring(v)) + end + end + return Xml.element(name, o :: any, children) +end + +local function nz(v: any, default: any): any + if v == nil or v == default then + return nil + end + return v +end +local function str(v: any): string? + if type(v) == "string" and v ~= "" then + return v + end + return nil +end + +local function propsNode(props: any, types: any): Node? + if type(props) ~= "table" or next(props) == nil then + return nil + end + local list = {} + for _, k in Data.sortedKeys(props) do + local v = props[k] + local typ = Data.typeOf(v, if type(types) == "table" then types[k] else nil) + if typ == "class" and type(v) == "table" then + local inner = propsNode(v.properties, v.propertyTypes) + table.insert(list, el("property", { { "name", k }, { "type", "class" }, { "propertytype", v.class or "" } }, if inner then { inner } else nil)) + else + local text = if type(v) == "boolean" then (if v then "true" else "false") elseif type(v) == "number" then Data.num(v) else tostring(v) + if string.find(text, "\n", 1, true) then + table.insert(list, el("property", { { "name", k }, { "type", if typ ~= "string" then typ else nil } }, { text })) + else + table.insert(list, el("property", { { "name", k }, { "type", if typ ~= "string" then typ else nil }, { "value", text } })) + end + end + end + return el("properties", {}, list) +end + +local function addProps(children: { any }, t: any) + local p = propsNode(t.properties, t.propertyTypes) + if p then + table.insert(children, p) + end +end + +local function writeObject(o: any): Node + local kids = {} + addProps(kids, o) + local shape = o.shape + if shape == "ellipse" then + table.insert(kids, el("ellipse", {})) + elseif shape == "point" then + table.insert(kids, el("point", {})) + elseif (shape == "polygon" or shape == "polyline") and type(o.points) == "table" then + local pts = {} + for _, p in o.points do + table.insert(pts, Data.num(tonumber(p[1]) or 0) .. "," .. Data.num(tonumber(p[2]) or 0)) + end + table.insert(kids, el(shape, { { "points", table.concat(pts, " ") } })) + elseif shape == "text" and type(o.text) == "table" then + local t = o.text + table.insert(kids, el("text", { + { "fontfamily", nz(t.fontFamily, "sans-serif") }, + { "pixelsize", nz(t.pixelSize, 16) }, + { "wrap", nz(t.wrap, false) }, + { "color", nz(t.color, "#000000") }, + { "bold", nz(t.bold, false) }, + { "italic", nz(t.italic, false) }, + { "underline", nz(t.underline, false) }, + { "strikeout", nz(t.strikeout, false) }, + { "kerning", nz(t.kerning, true) }, + { "halign", nz(t.halign, "left") }, + { "valign", nz(t.valign, "top") }, + }, { tostring(t.text or "") })) + end + return el("object", { + { "id", o.id }, + { "name", str(o.name) }, + { "type", str(o.class) }, + { "gid", o.gid }, + { "x", o.x or 0 }, + { "y", o.y or 0 }, + { "width", nz(o.width, 0) }, + { "height", nz(o.height, 0) }, + { "rotation", nz(o.rotation, 0) }, + { "visible", nz(o.visible, true) }, + { "template", o.template }, + }, kids) +end + +local function commonAttrs(l: any, extra: { { any } }): { { any } } + local out: { { any } } = { { "id", l.id }, { "name", str(l.name) or "" }, { "class", str(l.class) } } + table.move(extra, 1, #extra, #out + 1, out) + local tail = { + { "visible", nz(l.visible, true) }, + { "locked", nz(l.locked, false) }, + { "opacity", nz(l.opacity, 1) }, + { "tintcolor", l.tintColor }, + { "offsetx", nz(l.offsetX, 0) }, + { "offsety", nz(l.offsetY, 0) }, + { "parallaxx", nz(l.parallaxX, 1) }, + { "parallaxy", nz(l.parallaxY, 1) }, + } + table.move(tail, 1, #tail, #out + 1, out) + return out +end + +local function writeObjectGroup(l: any, tag: string?): Node + local kids = {} + addProps(kids, l) + for _, o in (if type(l.objects) == "table" then l.objects else {}) do + table.insert(kids, writeObject(o)) + end + return el(tag or "objectgroup", commonAttrs(l, { { "color", l.color }, { "draworder", nz(l.drawOrder, "topdown") } }), kids) +end + +export type WriteOptions = { encoding: string?, compression: string?, level: number? } + +local writeLayer: (l: any, o: WriteOptions) -> (Node?, string?) + +writeLayer = function(l: any, o: WriteOptions): (Node?, string?) + local t = l.type + if t == "tiles" then + local kids = {} + addProps(kids, l) + local enc = o.encoding or l.encoding or "csv" + local comp = if o.encoding then o.compression else (o.compression or l.compression) + if enc ~= "base64" then + comp = nil + end + local function payload(g: { number }, width: number): (string?, string?) + if enc == "csv" then + return Data.csvText(g, width), nil + end + local s, err = Data.toBase64(g, comp, o.level) + if not s then + return nil, err + end + return "\n " .. s .. "\n ", nil + end + local dataKids = {} + if type(l.chunks) == "table" then + for _, c in l.chunks do + local kids: { any } = {} + if enc == "xml" then + for _, g in (c.data or {}) do + table.insert(kids, el("tile", { { "gid", if g ~= 0 then g else nil } })) + end + else + local s, err = payload(c.data or {}, c.width or 0) + if not s then + return nil, err + end + kids = { s } + end + table.insert(dataKids, el("chunk", { { "x", c.x or 0 }, { "y", c.y or 0 }, { "width", c.width or 0 }, { "height", c.height or 0 } }, kids)) + end + elseif type(l.data) == "table" and enc == "xml" then + for _, g in l.data do + table.insert(dataKids, el("tile", { { "gid", if g ~= 0 then g else nil } })) + end + elseif type(l.data) == "table" then + local s, err = payload(l.data, l.width or 0) + if not s then + return nil, err + end + dataKids = { s } + end + table.insert(kids, el("data", { { "encoding", if enc == "xml" then nil else enc }, { "compression", comp } }, dataKids)) + return el("layer", commonAttrs(l, { { "x", nz(l.x, 0) }, { "y", nz(l.y, 0) }, { "width", l.width or 0 }, { "height", l.height or 0 } }), kids), nil + elseif t == "objects" then + return writeObjectGroup(l), nil + elseif t == "image" then + local kids = {} + addProps(kids, l) + if l.imageSource then + table.insert(kids, el("image", { { "source", l.imageSource }, { "trans", l.transparentColor }, { "width", l.imageWidth }, { "height", l.imageHeight } })) + end + return el("imagelayer", commonAttrs(l, { { "repeatx", nz(l.repeatX, false) }, { "repeaty", nz(l.repeatY, false) } }), kids), nil + elseif t == "group" then + local kids = {} + addProps(kids, l) + for _, c in (if type(l.layers) == "table" then l.layers else {}) do + local n, err = writeLayer(c, o) + if not n then + return nil, err + end + table.insert(kids, n) + end + return el("group", commonAttrs(l, {}), kids), nil + end + return nil, "unknown layer type " .. tostring(t) +end + +-- tilesetNode(ts, inMap) -> <tileset> +function Tmx.tilesetNode(ts: any, inMap: boolean): Node + if inMap and type(ts.source) == "string" then + return el("tileset", { { "firstgid", ts.firstGid or 1 }, { "source", ts.source } }) + end + local kids = {} + if type(ts.tileOffset) == "table" then + table.insert(kids, el("tileoffset", { { "x", ts.tileOffset.x or 0 }, { "y", ts.tileOffset.y or 0 } })) + end + addProps(kids, ts) + if ts.imageSource then + table.insert(kids, el("image", { { "source", ts.imageSource }, { "trans", ts.transparentColor }, { "width", ts.imageWidth }, { "height", ts.imageHeight } })) + end + for _, tile in (if type(ts.tiles) == "table" then ts.tiles else {}) do + local tk = {} + addProps(tk, tile) + if tile.imageSource then + table.insert(tk, el("image", { { "source", tile.imageSource }, { "width", tile.imageWidth }, { "height", tile.imageHeight } })) + end + if type(tile.objectGroup) == "table" then + table.insert(tk, writeObjectGroup(tile.objectGroup)) + end + if type(tile.animation) == "table" then + local frames = {} + for _, f in tile.animation do + table.insert(frames, el("frame", { { "tileid", f.tileId or 0 }, { "duration", f.duration or 0 } })) + end + table.insert(tk, el("animation", {}, frames)) + end + table.insert(kids, el("tile", { { "id", tile.id or 0 }, { "type", str(tile.class) }, { "probability", tile.probability } }, tk)) + end + return el("tileset", { + { "firstgid", if inMap then ts.firstGid or 1 else nil }, + { "name", ts.name or "" }, + { "class", str(ts.class) }, + { "tilewidth", ts.tileWidth or 0 }, + { "tileheight", ts.tileHeight or 0 }, + { "spacing", nz(ts.spacing, 0) }, + { "margin", nz(ts.margin, 0) }, + { "tilecount", ts.count or 0 }, + { "columns", ts.columns or 0 }, + { "objectalignment", ts.objectAlignment }, + }, kids) +end + +-- write(map, opts) -> an XML document node | nil, message +function Tmx.write(map: any, o: WriteOptions): (Node?, string?) + local kids = {} + addProps(kids, map) + for _, ts in map.tilesets do + table.insert(kids, Tmx.tilesetNode(ts, true)) + end + for _, l in map.layers do + local n, err = writeLayer(l, o) + if not n then + return nil, err + end + table.insert(kids, n) + end + local root = el("map", { + { "version", map.version or "1.10" }, + { "tiledversion", map.tiledVersion }, + { "class", str(map.class) }, + { "orientation", map.orientation or "orthogonal" }, + { "renderorder", map.renderOrder or "right-down" }, + { "width", map.width }, + { "height", map.height }, + { "tilewidth", map.tileWidth }, + { "tileheight", map.tileHeight }, + { "hexsidelength", map.hexSideLength }, + { "staggeraxis", map.staggerAxis }, + { "staggerindex", map.staggerIndex }, + { "parallaxoriginx", nz(map.parallaxOriginX, 0) }, + { "parallaxoriginy", nz(map.parallaxOriginY, 0) }, + { "backgroundcolor", map.backgroundColor }, + { "infinite", map.infinite == true }, + { "nextlayerid", map.nextLayerId }, + { "nextobjectid", map.nextObjectId }, + }, kids) + return Xml.document(root, { version = "1.0", encoding = "UTF-8" }), nil +end + +return Tmx diff --git a/src/Formats/vector/tiled/init.luau b/src/Formats/vector/tiled/init.luau new file mode 100644 index 0000000..4777295 --- /dev/null +++ b/src/Formats/vector/tiled/init.luau @@ -0,0 +1,189 @@ +--!strict +-- vector/tiled: Tiled maps, TMX (XML) and TMJ (JSON), and standalone TSX / TSJ tilesets (Tiled 1.12 docs: "TMX Map +-- Format", "JSON Map Format"). Supports: every orientation's attributes, tile layers (CSV, base64 uncompressed / zlib / +-- gzip, the old <tile gid> XML), infinite maps (chunks), flip bits kept in the gids, object groups (rectangles, +-- ellipses, points, polygons, polylines, text, tile objects, templates as references), image layers, group layers, +-- typed custom properties (string / int / float / bool / color / file / object / class) on everything, tilesets +-- (embedded, or external references kept as `source`), their image as a path (imageSource: tileset images stay +-- references), per-tile class, properties, images, animations and collision object groups. Both flavours decode to the +-- same Types.TileMap and encode from it: opts.format = "tmx" (default: the source's flavour) or "tmj" / "json". +-- Not supported: zstd-compressed layer data (Err.UNSUPPORTED), Wang sets / terrains (dropped), loading external +-- tilesets or images (callers resolve `source` / `imageSource` paths themselves). + +-- ------------------------------------------------------------------------------------------------ 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 Tmx = require("@formats/vector/tiled/Tmx") +local Tmj = require("@formats/vector/tiled/Tmj") + +-- ------------------------------------------------------------------------------------------------ contract +local Tiled = { + name = "tiled", + category = "vector", + 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 }, +} + +export type DecodeOptions = { + maxBytes: number?, -- refuse larger files (default 256 MB) +} +export type EncodeOptions = { + format: string?, -- "tmx" | "tsx" (XML) or "tmj" | "tsj" | "json" (JSON); default: the source's flavour, else tmx + encoding: string?, -- tile data: "csv" (TMX default) | "base64" | "xml" (TMX only); TMJ: arrays unless "base64" + compression: string?, -- base64 data: nil | "zlib" | "gzip" + level: number?, -- deflate level for compressed data (default 6) + indent: number?, -- spaces per level (default 1 for TMX, 2 for TMJ; 0 = compact JSON) +} + +-- ------------------------------------------------------------------------------------------------ sniff +local function head(r: Bytes.Reader): string + local h = r:peek(1024) + if string.sub(h, 1, 3) == "\239\187\191" then + h = string.sub(h, 4) + end + return h +end + +function Tiled.sniff(r: Bytes.Reader): number + local h = head(r) + if string.match(h, "^%s*<") then + if string.find(h, "<map[%s>]") or string.find(h, "<tileset[%s>]") then + return 0.9 + end + return 0 + end + if string.match(h, "^%s*{") then + -- Tiled writes its keys sorted: "type" comes last, so look at the tail too + local n = r:remaining() + local tail = if n > 1024 then r:peek(1024, n - 1024) else "" + for _, part in { h, tail } do + if string.find(part, "\"type\"%s*:%s*\"map\"") or string.find(part, "\"type\"%s*:%s*\"tileset\"") then + return 0.8 + end + end + if string.find(h, "\"tilewidth\"", 1, true) and (string.find(h, "\"orientation\"", 1, true) or string.find(h, "\"tilesets\"", 1, true)) then + return 0.6 + end + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(r, opts?) -> TileMap (or, for a .tsx / .tsj file, a TileMap with that one tileset and no layers; its +-- meta.tileset is true) | nil, Err +function Tiled.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.TileMap?, Err.Err?) + local maxBytes = opts and opts.maxBytes or 2 ^ 28 + if r.limit - r.base > maxBytes then + return nil, Err.new(Err.LIMIT, "file is over the byte limit") + end + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local h = head(r) + local map: any, msg: string?, unsupported: boolean? + local flavour + if string.match(h, "^%s*<") then + local doc, xerr = Xml.decode(text) + if not doc then + return nil, xerr + end + local root = (doc :: any).root + if root == nil then + return nil, Err.new(Err.CORRUPT, "no root element") + end + if root.name == "tileset" then + map = Types.TileMap.new(0, 0, 0, 0) + map.tilesets = { Tmx.tileset(root) } + map.meta.tileset = true + flavour = "tsx" + else + map, msg, unsupported = Tmx.read(root) + flavour = "tmx" + end + else + local v, jerr = Json.decode(text) + if v == nil then + return nil, jerr + end + if type(v) == "table" and v.type == "tileset" then + map = Types.TileMap.new(0, 0, 0, 0) + map.tilesets = { Tmj.tileset(v) } + map.meta.tileset = true + flavour = "tsj" + else + map, msg, unsupported = Tmj.read(v) + flavour = "tmj" + end + end + if not map then + return nil, Err.new(if unsupported then Err.UNSUPPORTED else Err.CORRUPT, msg or "bad map") + end + map.meta.source = { format = flavour } + return map, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Tiled.encode(map: Types.TileMap, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(map) ~= "table" or type(map.layers) ~= "table" or type(map.tilesets) ~= "table" then + return nil, Err.new(Err.ARG, "needs a TileMap value") + end + local o: EncodeOptions = opts or {} + local meta: any = if type(map.meta) == "table" then map.meta else {} + local fmt = o.format or (if type(meta.source) == "table" then meta.source.format else nil) or "tmx" + fmt = string.lower(fmt) + if fmt == "tiled" then + fmt = if type(meta.source) == "table" and meta.source.format then meta.source.format else "tmx" + end + local tilesetOnly = meta.tileset == true or fmt == "tsx" or fmt == "tsj" + if o.encoding and o.encoding ~= "csv" and o.encoding ~= "base64" and o.encoding ~= "xml" then + return nil, Err.new(Err.ARG, "encoding must be csv, base64 or xml") + end + if o.compression and o.compression ~= "zlib" and o.compression ~= "gzip" then + return nil, Err.new(Err.ARG, "compression must be zlib or gzip") + end + local wo = { encoding = o.encoding, compression = o.compression, level = o.level } + if fmt == "tmx" or fmt == "tsx" or fmt == "xml" then + local doc: any, err: string? + if tilesetOnly then + if not map.tilesets[1] then + return nil, Err.new(Err.ARG, "no tileset to write") + end + doc = Xml.document(Tmx.tilesetNode(map.tilesets[1], false), { version = "1.0", encoding = "UTF-8" }) + else + doc, err = Tmx.write(map, wo) + end + if not doc then + return nil, Err.new(Err.ARG, err or "bad map") + end + local s, xerr = Xml.encode(doc, { indent = o.indent or 1 }) + if not s then + return nil, xerr + end + return buffer.fromstring(s .. "\n"), nil + elseif fmt == "tmj" or fmt == "tsj" or fmt == "json" then + local v: any, err: string? + if tilesetOnly then + if not map.tilesets[1] then + return nil, Err.new(Err.ARG, "no tileset to write") + end + v = Tmj.tilesetValue(map.tilesets[1], false) + else + v, err = Tmj.write(map, wo) + end + if v == nil then + return nil, Err.new(Err.ARG, err or "bad map") + end + local indent = if o.indent == 0 then nil else (o.indent or 2) + local s, jerr = Json.encode(v, { indent = indent }) + if not s then + return nil, jerr + end + return buffer.fromstring(s .. "\n"), nil + end + return nil, Err.new(Err.ARG, "unknown format " .. tostring(fmt) .. " (tmx, tmj, tsx, tsj)") +end + +return Tiled diff --git a/tests/archive/7z.luau b/tests/archive/7z.luau new file mode 100644 index 0000000..c10d3b0 --- /dev/null +++ b/tests/archive/7z.luau @@ -0,0 +1,115 @@ +-- archive/7z tests: the contract and sniff; every archive 7-Zip wrote in tools/fixtures/7z.py (LZMA / LZMA2 / copy / +-- Deflate, solid and not, BCJ / ARM64 / ARM / PPC + SPARC / delta chains, plain and encoded headers) lists exactly the +-- source tree (names incl. UTF-16 surrogates, directories, empty files, mtimes) and reads every file back; unsupported +-- methods (PPMd, BCJ2, AES) list but fail on read with Err.UNSUPPORTED naming the method; corrupt CRCs; F.load; +-- the fuzz no-throw pass. +local T = require("@tests/T") +local SevenZip = require("@formats/archive/7z") +local F = require("@formats") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/7z") + +local t = T.suite("7z") + +t:eq(SevenZip.name, "7z", "name") +t:eq(SevenZip.category, "archive", "category") +t:check(SevenZip.caps.decode and not SevenZip.caps.encode, "caps") + +local function decode(data: string, opts: any?): (any, any) + return SevenZip.decode(Bytes.reader(buffer.fromstring(data)), opts) +end + +local want: { [string]: any } = {} +for _, f in Fx.files do + want[f.name] = f +end + +local nfiles = 0 +for _, c in Fx.cases do + t:eq(SevenZip.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, c.name .. ": sniff") + local a, err = decode(c.data) + t:check(a, c.name .. ": " .. tostring(err)) + local list = a:list() + if c.empty then + t:eq(#list, 0, c.name .. ": no entries") + continue + end + local seen = {} + for _, e in list do + local w = want[e.name] + t:check(w ~= nil, c.name .. ": unexpected entry " .. e.name) + seen[e.name] = true + t:eq(e.dir, w.dir, c.name .. ": " .. e.name .. ": dir") + t:eq(e.mtime, w.mtime, c.name .. ": " .. e.name .. ": mtime") + if not w.dir then + t:eq(e.size, #w.data, c.name .. ": " .. e.name .. ": size") + local b, rerr = a:read(e.name) + if c.unsupported and #w.data > 0 then + t:check(b == nil and rerr and rerr.code == Err.UNSUPPORTED and string.find(rerr.message, c.unsupported, 1, true) ~= nil, + c.name .. ": " .. e.name .. ": unsupported: " .. tostring(rerr)) + else + t:check(b and buffer.tostring(b) == w.data, c.name .. ": " .. e.name .. ": data: " .. tostring(rerr)) + nfiles += 1 + end + end + end + for name in want do + t:check(seen[name], c.name .. ": missing " .. name) + end +end +t:note("%d archives, %d files read", #Fx.cases, nfiles) + +-- corrupt data: a flipped byte in a stored file is a CRC error on read; a flipped header byte a header CRC error +do + local c + for _, x in Fx.cases do + if x.name == "copy" then + c = x + end + end + local s = c.data + local at = string.find(s, "deep\ndeep", 1, true) :: number + local bad = string.sub(s, 1, at - 1) .. "D" .. string.sub(s, at + 1) + local a = decode(bad) + t:check(a, "copy archive with a flipped data byte still lists") + local b, e = a:read("a/b/c/deep.txt") + t:check(b == nil and e and e.code == Err.CHECKSUM, "data CRC: " .. tostring(e)) + local _, e2 = decode(string.sub(s, 1, #s - 3) .. "\0\0\0") + t:check(e2 and (e2.code == Err.CHECKSUM or e2.code == Err.CORRUPT), "header CRC: " .. tostring(e2)) + local _, e3 = decode(string.sub(s, 1, 20)) + t:check(e3 and e3.code == Err.TRUNCATED, "truncated: " .. tostring(e3)) + local a4 = decode(bad, { checkCrc = false }) + t:check(a4 and a4:read("a/b/c/deep.txt"), "checkCrc = false") +end + +-- through the api +do + local c = Fx.cases[2] + local a, err = F.load(c.data) + t:check(a and a.format == "7z", "F.load: " .. tostring(err)) + t:eq(F.detect(c.data), "7z", "F.detect") + local r = a:read("readme.txt") + t:check(r and buffer.tostring(r) == want["readme.txt"].data, "F.load read") +end + +-- fuzz: decode + read every entry +do + local samples = {} + for _, c in Fx.cases do + if #c.data < 60000 then + table.insert(samples, c.data) + end + end + t:fuzz("decode", function(b: buffer) + local a = SevenZip.decode(Bytes.reader(b), { maxBytes = 2 ^ 21 }) + if a then + for _, e in a:list() do + a:read(e.name) + end + end + return a + end, samples, { mutations = 12, garbage = 300 }) +end + +t:done() diff --git a/tests/archive/br.luau b/tests/archive/br.luau new file mode 100644 index 0000000..ee1acdb --- /dev/null +++ b/tests/archive/br.luau @@ -0,0 +1,97 @@ +-- archive/br tests: the contract; fixture streams (tools/fixtures/brotli.py) load as a one-entry stream archive named +-- after the file; detection through F.load (sniff + extension); sniff rejects garbage and other formats; errors as +-- Err values; the fuzz no-throw pass. +local T = require("@tests/T") +local Br = require("@formats/archive/br") +local F = require("@formats") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/brotli") + +local t = T.suite("br") + +-- 1. the contract +t:eq(Br.name, "br", "name") +t:eq(Br.category, "archive", "category") +t:check(Br.caps.decode and not Br.caps.encode, "caps") + +-- 2. fixtures +local n = 0 +for i, c in Fx.cases do + if i % 4 == 0 then + local a, err = Br.decode(Bytes.reader(buffer.fromstring(c.data)), { name = "dir/file.txt.br" }) + t:check(a, c.name .. ": " .. tostring(err)) + t:check(a.kind == "archive" and a.format == "br" and a.meta.stream, c.name .. ": a stream archive") + local list = a:list() + t:eq(#list, 1, c.name .. ": one entry") + t:eq(list[1].name, "file.txt", c.name .. ": entry name") + t:eq(list[1].size, #Fx.corpora[c.corpus], c.name .. ": entry size") + t:eq(list[1].compressedSize, #c.data, c.name .. ": compressed size") + local data = a:read("file.txt") + t:check(data and buffer.tostring(data) == Fx.corpora[c.corpus], c.name .. ": entry data") + n += 1 + end +end +t:note("%d streams", n) + +-- default entry name +do + local a = Br.decode(Bytes.reader(buffer.fromstring(Fx.cases[5].data))) + t:eq(a:list()[1].name, "data", "default entry name") +end + +-- 3. through the api: by sniff (with and without the extension) and by format name +do + local c = Fx.cases[40] + local a, err = F.load(c.data, { name = "x.br" }) + t:check(a and a.format == "br", "F.load by sniff + extension: " .. tostring(err)) + t:eq(a:list()[1].name, "x", "F.load names the entry") + local a2 = F.load(c.data) + t:check(a2 and a2.format == "br", "F.load by sniff alone") + local a3 = F.archive.load(c.data, { format = "br" }) + t:check(a3 and a3.format == "br", "F.archive.load with format") + t:eq(F.detect(c.data, { name = "x.br" }), "br", "F.detect") + local _, e = F.save(a3, nil, { format = "br" }) + t:check(e and e.code == Err.UNSUPPORTED, "no encoder: " .. tostring(e)) +end + +-- 4. sniff: garbage and plain text are rejected +do + local rand = T.rng(99) + local hits = 0 + for _ = 1, 300 do + local len = 16 + rand(400) + local b = buffer.create(len) + for k = 0, len - 1 do + buffer.writeu8(b, k, rand(256)) + end + if Br.sniff(Bytes.reader(b)) > 0 then + hits += 1 + end + end + t:note("sniff accepted %d of 300 random buffers", hits) + t:check(hits <= 3, "sniff rejects random data") + t:eq(Br.sniff(Bytes.reader(buffer.fromstring("Hello, world! This is plain text.\n"))), 0, "sniff rejects text") + t:eq(Br.sniff(Bytes.reader(buffer.create(0))), 0, "sniff of nothing") + t:check(Br.sniff(Bytes.reader(buffer.fromstring(Fx.cases[40].data))) > 0, "sniff accepts a stream") + local _, e = Br.decode(Bytes.reader(buffer.fromstring("\x1b\xff\xff"))) + t:check(e and Err.is(e) and (e.code == Err.CORRUPT or e.code == Err.TRUNCATED), "bad data: " .. tostring(e)) +end + +-- 5. fuzz +do + local samples = {} + for i, c in Fx.cases do + if i % 23 == 0 and #c.data > 8 then + table.insert(samples, if #c.data > 8000 then string.sub(c.data, 1, 8000) else c.data) + end + end + t:fuzz("decode", function(b: buffer) + return Br.decode(Bytes.reader(b)) + end, samples, { mutations = 4, garbage = 500 }) + t:fuzz("sniff", function(b: buffer) + return Br.sniff(Bytes.reader(b)) + end, samples, { mutations = 2, garbage = 300 }) +end + +t:done() diff --git a/tests/archive/bz2.luau b/tests/archive/bz2.luau new file mode 100644 index 0000000..506b155 --- /dev/null +++ b/tests/archive/bz2.luau @@ -0,0 +1,65 @@ +-- archive/bz2 tests: the contract, sniff, a .bz2 as a one-entry single-stream archive (entry named after the file), +-- the api path (F.load by sniff, .tar.bz2 unwrap is the api's: covered once tar exists), errors, the fuzz pass. +-- Fixtures: tools/fixtures/bzip2.py. +local T = require("@tests/T") +local Bz2 = require("@formats/archive/bz2") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local F = require("@formats") +local Fx = require("@tests/gen/bzip2") + +local t = T.suite("bz2") + +t:eq(Bz2.name, "bz2", "name") +t:eq(Bz2.category, "archive", "category") +t:check(Bz2.caps.decode and not Bz2.caps.encode, "caps") + +for _, c in Fx.cases do + t:eq(Bz2.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, c.name .. ": sniff") +end +t:eq(Bz2.sniff(Bytes.reader(buffer.fromstring("BZh9hello"))), 0, "sniff: no block magic") +t:eq(Bz2.sniff(Bytes.reader(buffer.fromstring("\x1f\x8b\x08\x00"))), 0, "sniff: gzip") + +do + local c = Fx.cases[1] + for _, x in Fx.cases do + if x.name == "text/l9" then + c = x + end + end + local a, err = Bz2.decode(Bytes.reader(buffer.fromstring(c.data)), { name = "dir/notes.txt.bz2" }) + t:check(a, "decode: " .. tostring(err)) + t:check(a.kind == "archive" and a.format == "bz2" and a.meta.stream, "a single-stream archive") + local list = a:list() + t:eq(#list, 1, "one entry") + t:eq(list[1].name, "notes.txt", "entry named after the file") + t:eq(list[1].size, #Fx.corpora.text, "entry size") + t:eq(list[1].compressedSize, #c.data, "compressed size") + t:check(buffer.tostring((a:read("notes.txt"))) == Fx.corpora.text, "read") + local _, re = a:read("nope") + t:check(re and re.code == Err.ARG, "read of a missing entry") + local _, we = a:write() + t:check(we and we.code == Err.UNSUPPORTED, "read-only") + local a2 = Bz2.decode(Bytes.reader(buffer.fromstring(c.data)), { name = "x.tbz2" }) + t:eq(a2:list()[1].name, "x.tar", ".tbz2 -> .tar") + local a3 = Bz2.decode(Bytes.reader(buffer.fromstring(c.data))) + t:eq(a3:list()[1].name, "data", "no name -> data") + -- through the api + local v, ferr = F.load(c.data) + t:check(v and v.kind == "archive" and v.format == "bz2", "F.load sniffs bz2: " .. tostring(ferr)) + t:eq(F.detect(c.data), "bz2", "F.detect") + local _, de = Bz2.decode(Bytes.reader(buffer.fromstring(string.sub(c.data, 1, 100)))) + t:check(de and de.code == Err.TRUNCATED, "truncated: " .. tostring(de)) +end + +local samples = {} +for i, c in Fx.cases do + if i % 6 == 0 and #c.data < 30000 then + table.insert(samples, c.data) + end +end +t:fuzz("decode", function(b: buffer) + return Bz2.decode(Bytes.reader(b)) +end, samples, { mutations = 6, garbage = 300 }) + +t:done() diff --git a/tests/archive/gzip.luau b/tests/archive/gzip.luau new file mode 100644 index 0000000..ff51f40 --- /dev/null +++ b/tests/archive/gzip.luau @@ -0,0 +1,93 @@ +-- archive/gzip tests: members from Python's gzip and the gzip CLI (FNAME, MTIME, levels, concatenated members) decode +-- to one entry with the right name / mtime / data; the writer round-trips (buffer, string, one-entry archive, several +-- entries as a .tar.gz) and keeps FNAME / MTIME; the api; errors; the fuzz pass. Fixtures: tools/fixtures/tar.py. +local T = require("@tests/T") +local F = require("@formats") +local Gzip = require("@formats/archive/gzip") +local Deflate = require("@formats/codecs/Deflate") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/tar") + +local t = T.suite("gzip") +t:eq(Gzip.name, "gzip", "name") + +for _, c in Fx.gzips do + local a, err = Gzip.decode(Bytes.reader(buffer.fromstring(c.data))) + t:check(a, c.name .. ": " .. tostring(err)) + t:check(a.meta.stream, c.name .. ": single stream") + local l = a:list() + t:eq(#l, 1, c.name .. ": one entry") + t:eq(l[1].name, c.entry, c.name .. ": entry name") + t:eq(l[1].mtime, if c.mtime > 0 then c.mtime else nil, c.name .. ": mtime") + t:eq(l[1].size, c.size, c.name .. ": size") + t:eq(Crc32.of((a:read(l[1].name))), c.crc, c.name .. ": data") + t:eq(F.detect(c.data), "gzip", c.name .. ": F.detect") +end + +-- the file name names the entry when there is no FNAME +do + local a = F.load(Fx.gzips[2].data, { name = "dir/notes.txt.gz" }) + t:eq(a:list()[1].name, "notes.txt", "entry named after the file") + local b = F.load(Fx.gzips[2].data, { name = "x.tgz" }) + t:eq(b:list()[1].name, "x.tar", ".tgz entry is a .tar") +end + +-- writing +do + local text = string.rep("gzip round trip ", 500) + for _, level in { 0, 1, 6, 9 } do + local z = Gzip.encode(text, { level = level }) :: buffer + t:eq(buffer.tostring((Deflate.gunzip(z))), text, "string level " .. level) + end + local one = Gzip.new(text, "notes.txt") + one._byName["notes.txt"].mtime = 1600000000 + local z = one:write() + local back = Gzip.decode(Bytes.reader(z :: buffer)) + t:eq(back:list()[1].name, "notes.txt", "FNAME written") + t:eq(back:list()[1].mtime, 1600000000, "MTIME written") + t:eq(buffer.tostring((back:read("notes.txt"))), text, "one-entry archive round trip") + -- a decoded gzip saves back as gzip (its source format) + local g = F.load(Fx.gzips[1].data) + local again = F.load(F.save(g)) + t:eq(again:list()[1].name, "story.txt", "F.save(gzip) keeps the name") + -- several entries: a .tar.gz, which the api unwraps + local multi = Gzip.new() + multi:add("a.txt", "A") + multi:add("b.txt", "BB") + local tgz = multi:write() + local tar = F.load(tgz) + t:eq(tar.format, "tar", "several entries write a .tar.gz") + t:eq(tar.meta.compression, "gzip", "unwrapped") + t:eq(buffer.tostring((tar:read("b.txt"))), "BB", ".tar.gz entry") + -- any archive converts: tar -> gzip -> tar + local tb = F.convert(Fx.tars[1].data, "gzip") + local t2 = F.load(tb) + t:eq(#t2:list(), #Fx.tars[1].entries, "tar -> tar.gz -> tar") + local _, e = Gzip.encode(text, { level = 12 }) + t:check(e and e.code == Err.ARG, "bad level") + local _, e2 = Gzip.encode({ kind = "image" }) + t:check(e2 and e2.code == Err.ARG, "not an archive") +end + +-- errors +do + local d = Fx.gzips[1].data + local _, e1 = Gzip.decode(Bytes.reader(buffer.fromstring(string.sub(d, 1, 20)))) + t:check(e1 and e1.code == Err.TRUNCATED, "truncated: " .. tostring(e1)) + local b = buffer.fromstring(d) + buffer.writeu8(b, #d - 6, bit32.bxor(buffer.readu8(b, #d - 6), 1)) + local _, e2 = Gzip.decode(Bytes.reader(b)) + t:check(e2 and e2.code == Err.CHECKSUM, "crc: " .. tostring(e2)) +end + +local samples = {} +for _, c in Fx.gzips do + table.insert(samples, c.data) +end +t:fuzz("decode", function(b: buffer) + return Gzip.decode(Bytes.reader(b)) +end, samples, { mutations = 20 }) + +t:done() diff --git a/tests/archive/tar.luau b/tests/archive/tar.luau new file mode 100644 index 0000000..0ed363d --- /dev/null +++ b/tests/archive/tar.luau @@ -0,0 +1,156 @@ +-- archive/tar tests: archives from Python's tarfile (ustar / GNU / pax) and GNU tar (ustar / gnu / posix / v7) list +-- the same entries as tarfile reads (names, types, sizes, links, mtimes, modes, data CRCs); the writer produces the same +-- bytes as tarfile for the same entries in all three formats and round-trips; Archive values (add / read / write, +-- conversion of a gzip / any archive to tar); .tar.gz / .tgz / .tar.bz2 / .tar.xz / .tar.zst / .tar.br load through the +-- api as the tar inside; errors; the fuzz pass. Fixtures: tools/fixtures/tar.py. +local T = require("@tests/T") +local F = require("@formats") +local TarF = require("@formats/archive/tar") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/tar") + +local t = T.suite("tar") +t:eq(TarF.name, "tar", "name") + +local function check(a: any, want: any, label: string) + local list = a:list() + t:eq(#list, #want, label .. ": entry count") + local by = {} + for _, e in list do + by[e.name] = e + end + for _, w in want do + local e = by[w.name] + t:check(e, label .. ": has " .. w.name) + t:eq(e.type, w.type, label .. ": " .. w.name .. " type") + t:eq(e.size, w.size, label .. ": " .. w.name .. " size") + t:eq(e.mtime, w.mtime, label .. ": " .. w.name .. " mtime") + t:eq(e.mode, w.mode, label .. ": " .. w.name .. " mode") + t:eq(e.link, w.link, label .. ": " .. w.name .. " link") + t:eq(e.dir, w.type == "5", label .. ": " .. w.name .. " dir") + if w.crc then + local b, err = a:read(w.name) + t:check(b, label .. ": read " .. w.name .. ": " .. tostring(err)) + t:eq(Crc32.of(b), w.crc, label .. ": " .. w.name .. " data") + end + end +end + +-- 1. reading +for _, c in Fx.tars do + local a, err = TarF.decode(Bytes.reader(buffer.fromstring(c.data))) + t:check(a, c.name .. ": " .. tostring(err)) + check(a, c.entries, c.name) + t:eq(F.detect(c.data), "tar", c.name .. ": F.detect") + t:note("%-18s %2d entries", c.name, #c.entries) +end + +-- 2. writing: byte-identical to Python's tarfile (which pads to 10240-byte records) +for _, w in Fx.writes do + local list = {} + for _, e in w.entries do + table.insert(list, { + name = e.name, + data = if e.data then buffer.fromstring(e.data) else nil, + dir = e.dir, + type = e.type, + link = e.link, + mode = e.mode or (if e.dir then 0x1ED else 0x1A4), + mtime = 1700000000, + uname = "user", + gname = "group", + }) + end + local a = TarF.new() + for _, e in list do + a:add(e.name, e.data or "", { dir = e.dir, mtime = e.mtime, mode = e.mode }) + local ent = a._byName[e.name] + ent.type, ent.link, ent.uname, ent.gname = e.type, e.link, e.uname, e.gname + end + local out, err = a:write({ format = w.format }) + t:check(out, w.format .. ": write: " .. tostring(err)) + local s = buffer.tostring(out :: buffer) + local ref = w.data + t:check(#s <= #ref and string.sub(ref, 1, #s) == s and not string.find(string.sub(ref, #s + 1), "[^%z]"), w.format .. ": bytes identical to tarfile") + local back = TarF.decode(Bytes.reader(out :: buffer)) + t:eq(#back:list(), #list, w.format .. ": round trip count") + for _, e in w.entries do + if e.data then + t:eq(buffer.tostring((back:read(e.name))), e.data, w.format .. ": round trip " .. e.name) + end + end +end + +-- 3. Archive values: add / read / write, other archives to tar +do + local a = TarF.new() + a:add("a.txt", "alpha", { mtime = 5 }) + a:add("b/", "", { dir = true }) + a:add("b/c.bin", buffer.fromstring("\0\1\2")) + a:add("a.txt", "replaced") + t:eq(#a:list(), 3, "add replaces by name") + local buf = F.save(a) + t:check(buf, "F.save(tar archive) uses the source format") + local back = F.load(buf) + t:eq(buffer.tostring(back:read("a.txt")), "replaced", "read back") + t:check(back:list()[2].dir, "directory entry") + local _, e = back:read("missing") + t:check(e and e.code == Err.ARG, "missing entry") + -- a gzip (single-stream archive) converts to a tar holding its one entry + local g = F.load(Fx.gzips[1].data) + local tb = F.save(g, nil, { format = "tar" }) + local ta = F.load(tb) + t:eq(ta:list()[1].name, "story.txt", "gzip -> tar entry name") + t:eq(ta:list()[1].size, Fx.gzips[1].size, "gzip -> tar entry size") +end + +-- 4. compressed tars through the api +for _, w in Fx.wrapped do + local a, err = F.load(w.data, { name = w.name }) + t:check(a, w.name .. ": " .. tostring(err)) + t:eq(a.format, "tar", w.name .. ": unwrapped to the tar") + t:eq(a.meta.compression, w.outer, w.name .. ": meta.compression") + check(a, Fx.innerEntries, w.name) + local outer = F.load(w.data, { name = w.name, unwrap = false }) + t:eq(outer.format, w.outer, w.name .. ": unwrap = false keeps the outer archive") + t:eq(outer:list()[1].name, "a.tar", w.name .. ": inner entry named after the file") +end + +-- 5. errors +do + local good = Fx.tars[1].data + local b = buffer.fromstring(good) + buffer.writeu8(b, 10, buffer.readu8(b, 10) + 1) + local _, e1 = TarF.decode(Bytes.reader(b)) + t:check(e1 and e1.code == Err.CORRUPT, "first header checksum: " .. tostring(e1)) + local _, e2 = TarF.decode(Bytes.reader(buffer.fromstring(string.sub(good, 1, 700)))) + t:check(e2 and e2.code == Err.TRUNCATED, "truncated data: " .. tostring(e2)) + local _, e3 = TarF.encode({ kind = "image" }) + t:check(e3 and e3.code == Err.ARG, "encode a non-archive") + local u = TarF.new() + u:add(string.rep("y", 120), "x") + local _, e4 = u:write({ format = "ustar" }) + t:check(e4 and e4.code == Err.ARG, "ustar cannot hold a 120-byte name without a slash") + t:eq(TarF.sniff(Bytes.reader(buffer.fromstring(string.rep("\0", 1024)))), 0, "zeros are not a tar") +end + +local samples = {} +for _, c in Fx.tars do + if #c.data <= 30000 then + table.insert(samples, c.data) + end +end +t:fuzz("decode", function(b: buffer) + local a = TarF.decode(Bytes.reader(b)) + if a then + for _, e in a:list() do + a:read(e.name) + end + a:write() + end + return a +end, samples, { mutations = 30, keepHeader = 0 }) + +t:done() diff --git a/tests/archive/xz.luau b/tests/archive/xz.luau new file mode 100644 index 0000000..6dc0468 --- /dev/null +++ b/tests/archive/xz.luau @@ -0,0 +1,78 @@ +-- archive/xz tests: the contract, sniffing (.xz magic, conservative .lzma), every xz / .lzma fixture of +-- tools/fixtures/lzma.py read as a one-entry archive (entry names from opts.name), F.load through the registry, errors, +-- and the fuzz no-throw pass. +local T = require("@tests/T") +local Xz = require("@formats/archive/xz") +local F = require("@formats") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/lzma") + +local t = T.suite("xz") + +t:eq(Xz.name, "xz", "name") +t:eq(Xz.category, "archive", "category") +t:check(Xz.caps.decode and not Xz.caps.encode, "caps") + +local function reader(s: string): Bytes.Reader + return Bytes.reader(buffer.fromstring(s)) +end + +local n = 0 +for _, c in Fx.cases do + if c.kind == "xz" or c.kind == "alone" then + local want = Fx.corpora[c.corpus] + t:check(Xz.sniff(reader(c.data)) > 0, c.name .. ": sniff") + local a, err = Xz.decode(reader(c.data), { name = "dir/file.txt." .. (if c.kind == "xz" then "xz" else "lzma") }) + t:check(a, c.name .. ": " .. tostring(err)) + local list = a:list() + t:eq(#list, 1, c.name .. ": one entry") + t:eq(list[1].name, "file.txt", c.name .. ": entry name") + t:eq(list[1].size, #want, c.name .. ": size") + t:check(a.meta.stream == true, c.name .. ": meta.stream") + local b = a:read("file.txt") + t:check(b and buffer.tostring(b) == want, c.name .. ": data") + n += 1 + end +end +t:note("%d xz / lzma files", n) + +-- sniff: not xz +t:eq(Xz.sniff(reader("PK\3\4 hello")), 0, "zip is not xz") +t:eq(Xz.sniff(reader("")), 0, "empty") +t:eq(Xz.sniff(reader(string.rep("\0", 40))), 0, "zeros are not .lzma") + +-- through the api +do + local c = Fx.cases[1] + for _, x in Fx.cases do + if x.name == "text/xz-6" then + c = x + end + end + local a, err = F.load(c.data, { name = "notes.txz" }) + t:check(a and a.kind == "archive" and a.format == "xz", "F.load: " .. tostring(err)) + t:eq(a:list()[1].name, "notes.tar", "txz -> tar entry name") + t:eq(F.detect(c.data), "xz", "F.detect") + local a2 = F.archive.load(c.data) + t:eq(a2:list()[1].name, "data", "unnamed entry") + local _, e2 = F.save(a2, nil, { format = "xz" }) + t:check(e2 and e2.code == Err.UNSUPPORTED, "xz is read-only: " .. tostring(e2)) + local _, e3 = F.load(string.sub(c.data, 1, 100), { format = "xz" }) + t:check(e3 and e3.code == Err.TRUNCATED, "truncated: " .. tostring(e3)) +end + +-- fuzz +do + local samples = {} + for i, c in Fx.cases do + if (c.kind == "xz" or c.kind == "alone") and i % 5 == 0 and #c.data < 30000 then + table.insert(samples, c.data) + end + end + t:fuzz("decode", function(b: buffer) + return Xz.decode(Bytes.reader(b), { maxBytes = 2 ^ 20 }) + end, samples, { mutations = 6, garbage = 400 }) +end + +t:done() diff --git a/tests/archive/zst.luau b/tests/archive/zst.luau new file mode 100644 index 0000000..4908393 --- /dev/null +++ b/tests/archive/zst.luau @@ -0,0 +1,90 @@ +-- archive/zst tests: the contract, sniff (zstd and skippable-frame magic), decode of zstd CLI output into a one-entry +-- single-stream archive (entry name from opts.name, size, read), F.load detection by content, read-only errors, and +-- the fuzz no-throw pass. Fixtures: tools/fixtures/zstd.py (shared with tests/codecs/zstd.luau). +local T = require("@tests/T") +local F = require("@formats") +local Zst = require("@formats/archive/zst") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/zstd") + +local t = T.suite("zst") + +-- contract +t:eq(Zst.name, "zst", "name") +t:eq(Zst.category, "archive", "category") +t:check(Zst.caps.decode and not Zst.caps.encode, "caps") + +local function case(name: string): any + for _, c in Fx.cases do + if c.name == name then + return c + end + end + error("no case " .. name) +end + +-- sniff +t:eq(Zst.sniff(Bytes.reader(buffer.fromstring(case("text/l3").data))), 1, "sniff zstd") +t:eq(Zst.sniff(Bytes.reader(buffer.fromstring(case("skipfirst/frames").data))), 0.5, "sniff skippable frame") +t:eq(Zst.sniff(Bytes.reader(buffer.fromstring("PK\3\4"))), 0, "sniff other") +t:eq(Zst.sniff(Bytes.reader(buffer.create(0))), 0, "sniff empty") + +-- decode: one entry, named after the file +for _, name in { "text/l3", "runs/ultra22", "multi/frames", "empty/l3", "big/l19" } do + local c = case(name) + local a, err = Zst.decode(Bytes.reader(buffer.fromstring(c.data)), { name = "dir/notes.txt.zst" }) + t:check(a, name .. ": " .. tostring(err)) + local list = a:list() + t:eq(#list, 1, name .. ": one entry") + t:eq(list[1].name, "notes.txt", name .. ": entry name") + t:eq(list[1].size, #Fx.corpora[c.corpus], name .. ": size") + t:eq(list[1].compressedSize, #c.data, name .. ": compressedSize") + t:check(a.meta.stream == true and a.kind == "archive" and a.format == "zst", name .. ": archive fields") + local data = a:read(list[1].name) + t:check(data and buffer.tostring(data) == Fx.corpora[c.corpus], name .. ": read") +end +do + local c = case("short/l3") + local a = Zst.decode(Bytes.reader(buffer.fromstring(c.data))) :: any + t:eq(a:list()[1].name, "data", "no name -> data") + local a2 = Zst.decode(Bytes.reader(buffer.fromstring(c.data)), { name = "backup.tzst" }) :: any + t:eq(a2:list()[1].name, "backup.tar", ".tzst -> .tar") + local _, e = a:read("nope") + t:check(e and e.code == Err.ARG, "missing entry") + local _, we = a:write() + t:check(we and we.code == Err.UNSUPPORTED, "read-only: " .. tostring(we)) + -- inside a bigger buffer (the reader's range) + local big = buffer.create(#c.data + 10) + buffer.writestring(big, 5, c.data) + local a3 = Zst.decode(Bytes.reader(big, 5, #c.data)) :: any + t:check(a3 and buffer.tostring(a3:read("data")) == Fx.corpora.short, "reader range") +end + +-- the api: detection by content, the name from opts +do + local c = case("text/l5") + local a, err = F.load(c.data, { name = "x/readme.md.zst" }) + t:check(a and a.format == "zst", "F.load detects zst: " .. tostring(err)) + t:eq(a:list()[1].name, "readme.md", "F.load entry name") + t:eq(F.detect(c.data), "zst", "F.detect") + local _, e = F.load(string.sub(c.data, 1, 30), { format = "zst" }) + t:check(e and e.code == Err.TRUNCATED, "truncated through the api: " .. tostring(e)) + local _, se = F.save(a, nil, { format = "zst" }) + t:check(se and se.code == Err.UNSUPPORTED, "no encoder") +end + +-- fuzz +do + local samples = {} + for i, c in Fx.cases do + if i % 11 == 0 and #c.data < 30000 then + table.insert(samples, c.data) + end + end + t:fuzz("decode", function(b: buffer) + return Zst.decode(Bytes.reader(b), { maxBytes = 1e6 }) + end, samples, { mutations = 10, garbage = 500 }) +end + +t:done() diff --git a/tests/audio/_encode_cases.luau b/tests/audio/_encode_cases.luau new file mode 100644 index 0000000..1e7bd23 --- /dev/null +++ b/tests/audio/_encode_cases.luau @@ -0,0 +1,12 @@ +-- tests/audio/_encode_cases: the files our ALAC / CAF writers produce for the reference check (tools/fixtures/m4a.py +-- runs tools/fixtures/_m4a_encode.luau over them; tests/audio/m4a.luau and caf.luau re-encode and compare). +return { + { name = "ours_alac16_stereo", container = "m4a", rate = 44100, frames = 4096 * 3 + 1234, channels = 2, bits = 16, seed = 1, tags = { title = "Our Title \u{e9}", artist = "formats-luau", album = "Tests", track = "5", tracktotal = "10", date = "2026", genre = "Test", comment = "round trip" } }, + { name = "ours_alac16_mono", container = "m4a", rate = 22050, frames = 5000, channels = 1, bits = 16, seed = 2 }, + { name = "ours_alac24_stereo", container = "m4a", rate = 48000, frames = 9000, channels = 2, bits = 24, seed = 3 }, + { name = "ours_alac16_6ch", container = "m4a", rate = 48000, frames = 4500, channels = 6, bits = 16, seed = 4 }, + { name = "ours_alac20_stereo", container = "m4a", rate = 96000, frames = 3000, channels = 2, bits = 20, seed = 5 }, + { name = "ours_caf_alac16", container = "caf", codec = "alac", rate = 44100, frames = 7000, channels = 2, bits = 16, seed = 6 }, + { name = "ours_caf_pcm16", container = "caf", codec = "pcm", rate = 44100, frames = 3000, channels = 2, bits = 16, seed = 7 }, + { name = "ours_caf_pcm24", container = "caf", codec = "pcm", rate = 48000, frames = 2000, channels = 1, bits = 24, seed = 8 }, +} diff --git a/tests/audio/_opus_cases.luau b/tests/audio/_opus_cases.luau new file mode 100644 index 0000000..1163827 --- /dev/null +++ b/tests/audio/_opus_cases.luau @@ -0,0 +1,42 @@ +-- tests/audio/_opus_cases: the inputs of the CELT encoder reference check (tools/fixtures/opus_celt.py runs +-- tools/fixtures/_opus_encode.luau over them; tests/audio/opus_encode.luau re-encodes and compares): a deterministic +-- music-like signal (chord + vibrato + chirp + clicks + a silent stretch) at a given rate / channel count. +local Types = require("@formats/Types") + +local Cases = {} + +Cases.list = { + { name = "celt_mono_64k", rate = 48000, channels = 1, seconds = 1.5, bitrate = 64000, minSnr = 15 }, + { name = "celt_stereo_128k", rate = 48000, channels = 2, seconds = 1.5, bitrate = 128000, minSnr = 15 }, + { name = "celt_stereo_256k", rate = 48000, channels = 2, seconds = 1, bitrate = 256000, minSnr = 22 }, + { name = "celt_mono_24k", rate = 48000, channels = 1, seconds = 1, bitrate = 24000, minSnr = 8 }, + { name = "celt_44k_stereo_96k", rate = 44100, channels = 2, seconds = 1, bitrate = 96000, minSnr = 0, tags = { title = "Celt \u{e9}", artist = "formats-luau", album = "Opus" } }, + { name = "celt_short", rate = 48000, channels = 1, seconds = 0.01, bitrate = 48000, minSnr = -100 }, +} + +function Cases.signal(c: any): Types.Audio + local n = math.floor(c.seconds * c.rate + 0.5) + local a = Types.Audio.new(c.rate, c.channels, n) + local s = 7 + for i = 0, n - 1 do + local t = i / c.rate + for ch = 0, c.channels - 1 do + s = (s * 48271) % 2147483647 + local v = 0.18 * math.sin(2 * math.pi * 220 * t + 2 * math.sin(2 * math.pi * 5 * t)) + v += 0.12 * math.sin(2 * math.pi * (277.2 + ch * 2) * t) + 0.1 * math.sin(2 * math.pi * 329.6 * t) + v += 0.08 * math.sin(2 * math.pi * (1000 + 3000 * t) * t) + v += 0.01 * (s / 2147483647 - 0.5) + if i % (c.rate // 4) < 30 then + v += 0.4 * (if (i // 5) % 2 == 0 then 1 else -1) + end + if t > 0.6 and t < 0.75 then + v = 0 -- digital silence (the encoder's silence frames) + end + buffer.writef32(a.samples, (i * c.channels + ch) * 4, v) + end + end + a.tags = c.tags or {} + return a +end + +return Cases diff --git a/tests/audio/_signal.luau b/tests/audio/_signal.luau new file mode 100644 index 0000000..4986a7e --- /dev/null +++ b/tests/audio/_signal.luau @@ -0,0 +1,42 @@ +-- tests/audio/_signal: the deterministic integer test signal of tools/fixtures/_m4a_signal.py (the same numbers), as +-- an interleaved integer array and as a Types.Audio (f32, exact for up to 24 bits). Used by the m4a / caf tests and the +-- fixture-time encoder runs (tools/fixtures/_m4a_encode.luau). +local Types = require("@formats/Types") + +local Signal = {} + +function Signal.ints(frames: number, channels: number, bits: number, seed: number): { number } + local s = seed + local peak = 2 ^ (bits - 1) - 1 + local out = table.create(frames * channels, 0) + local k = 1 + for i = 0, frames - 1 do + for c = 0, channels - 1 do + s = (s * 48271) % 2147483647 + local p1 = 97 + 31 * c + local tri = math.abs((i % p1) * 2 - p1) * 2 - p1 + local v = tri * (peak // (4 * p1)) + local p2 = 1500 + 200 * c + v += if (i // p2) % 2 == 0 then peak // 6 else -(peak // 6) + v += ((s // 65536) % 4096 - 2048) * (peak // 65536 + 1) + if i % 7001 < 3 then + v += peak // 2 + end + out[k] = math.clamp(v, -peak - 1, peak) + k += 1 + end + end + return out +end + +function Signal.audio(rate: number, frames: number, channels: number, bits: number, seed: number): Types.Audio + local ints = Signal.ints(frames, channels, bits, seed) + local a = Types.Audio.new(rate, channels, frames) + local scale = 1 / 2 ^ (bits - 1) + for i, v in ints do + buffer.writef32(a.samples, (i - 1) * 4, v * scale) + end + return a +end + +return Signal diff --git a/tests/audio/aac.luau b/tests/audio/aac.luau new file mode 100644 index 0000000..360d39a --- /dev/null +++ b/tests/audio/aac.luau @@ -0,0 +1,117 @@ +-- audio/aac tests: ADTS streams from ffmpeg and fdkaac (stereo, mono 32 kHz) against ffmpeg's float decode (SNR, +-- length); an HE-AAC ADTS stream plays its core; a leading ID3v2 tag (skipped, text frames as tags) and garbage before +-- the first frame (resync); a truncated last frame; streaming + seek; sniff; errors; the fuzz no-throw pass. +-- Fixtures: tools/fixtures/m4a.py. +local T = require("@tests/T") +local AacF = require("@formats/audio/aac") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/m4a_aac") +local He = require("@tests/gen/m4a_he") + +local t = T.suite("aac") + +local function reader(s: string): Bytes.Reader + return Bytes.reader(buffer.fromstring(s)) +end + +local function snr(a: any, ref: string, skip: number?): number + local off = (skip or 0) * a.channels + local n = math.min(a.frames * a.channels - off, #ref // 4) + local rb = buffer.fromstring(ref) + local sig, err = 0, 0 + for i = 0, n - 1 do + local r = buffer.readf32(rb, i * 4) + local d = buffer.readf32(a.samples, (off + i) * 4) - r + sig += r * r + err += d * d + end + return if err == 0 then math.huge else 10 * math.log10(sig / err) +end + +t:eq(AacF.name, "aac", "name") +t:check(AacF.caps.decode and not AacF.caps.encode and AacF.encode == nil, "caps: decode only") + +local first +for _, c in Fx do + if c.container ~= "adts" then + continue + end + first = first or c + local r = reader(c.data) + t:check(AacF.sniff(r) >= 0.9, c.name .. ": sniff") + local a, err = AacF.decode(r) + t:check(a, c.name .. ": " .. tostring(err)) + t:check(a.channels == c.channels and a.sampleRate == c.rate, c.name .. ": format") + t:eq(a.frames, c.frames, c.name .. ": frames (ADTS keeps the priming)") + local s = snr(a, c.ref) + t:check(s > 90, string.format("%s: SNR %.1f dB", c.name, s)) + t:note("%s: %d ch %d Hz, %d frames, SNR %.1f dB vs ffmpeg", c.name, c.channels, c.rate, a.frames, s) +end + +-- HE-AAC ADTS: the core +for _, c in He do + if string.sub(c.name, -4) == ".aac" then + local a, err = AacF.decode(reader(c.data)) + t:check(a and a.sampleRate == c.rate // 2 and a.frames > 0, c.name .. ": core decode: " .. tostring(err)) + end +end + +-- ID3v2 in front + garbage, truncated tail +do + local function frame(id: string, text: string): string + local body = "\3" .. text + local n = #body + return id .. string.char(0, 0, n // 128, n % 128) .. "\0\0" .. body + end + local frames = frame("TIT2", "Adts Title") .. frame("TPE1", "Someone") + local n = #frames + local id3 = "ID3\4\0\0" .. string.char(0, 0, n // 128, n % 128) .. frames + local data = id3 .. "\0\1\2garbage" .. first.data + local a, err = AacF.decode(reader(data)) + t:check(a, "id3 + garbage: " .. tostring(err)) + t:check(a.tags.title == "Adts Title" and a.tags.artist == "Someone", "id3 tags") + t:eq(a.frames, first.frames, "id3 + garbage: same frames") + t:check(snr(a, first.ref) > 90, "id3 + garbage: same audio") + local cut = AacF.decode(reader(string.sub(first.data, 1, #first.data - 5))) :: any + t:check(cut and cut.frames == first.frames - 1024, "truncated last frame dropped") +end + +-- streaming + seek +do + local whole = AacF.decode(reader(first.data)) :: any + local dec = AacF.open(reader(first.data)) :: any + for _, at in { 0.3, 0.0, 0.5123 } do + dec:seek(at) + local b, n = dec:read(600) + local f0 = math.floor(at * whole.sampleRate + 0.5) + local maxd = 0 + for i = 0, n * whole.channels - 1 do + maxd = math.max(maxd, math.abs(buffer.readf32(b, i * 4) - buffer.readf32(whole.samples, (f0 * whole.channels + i) * 4))) + end + -- (the stream has no PNS: noise substitution would draw different noise after a seek) + t:check(n == 600 and maxd < 1e-6, string.format("seek %.3f s (max diff %g)", at, maxd)) + end +end + +-- errors +do + t:eq(AacF.sniff(reader("RIFF....WAVE")), 0, "sniff a WAV") + local _, e = AacF.decode(reader(string.rep("\0", 100))) + t:check(e and e.code == Err.CORRUPT, "no frames: " .. tostring(e)) +end + +-- fuzz +do + local samples = {} + for _, c in Fx do + if c.container == "adts" then + table.insert(samples, string.sub(c.data, 1, 6000)) + end + end + t:fuzz("decode", function(b: buffer) + return AacF.decode(Bytes.reader(b)) + end, samples, { mutations = 30 }) +end + +t:done() diff --git a/tests/audio/caf.luau b/tests/audio/caf.luau new file mode 100644 index 0000000..c0f40ff --- /dev/null +++ b/tests/audio/caf.luau @@ -0,0 +1,177 @@ +-- audio/caf tests: ALAC CAF from ffmpeg bit-exact; AAC CAF (ffmpeg's ADTS frames wrapped by the fixture) against +-- ffmpeg's float decode; our CAF writer (PCM 16 / 24-bit, ALAC; re-encoded here and compared with the bytes ffmpeg +-- decoded bit-exactly); PCM layouts (little / big endian, float) through our writer + a hand-built header; info tags; +-- seek; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/m4a.py. +local T = require("@tests/T") +local Caf = require("@formats/audio/caf") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Signal = require("@tests/audio/_signal") +local Cases = require("@tests/audio/_encode_cases") +local Alac = require("@tests/gen/m4a_alac") +local Aac = require("@tests/gen/m4a_aac") +local Ours = require("@tests/gen/m4a_ours") + +local t = T.suite("caf") + +local function reader(s: string | buffer): Bytes.Reader + return Bytes.reader(if type(s) == "string" then buffer.fromstring(s) else s) +end + +local function intCrc(a: any, bits: number): number + local n = a.frames * a.channels + local b = buffer.create(n * 4) + local scale = 2 ^ (bits - 1) + for i = 0, n - 1 do + buffer.writei32(b, i * 4, math.floor(buffer.readf32(a.samples, i * 4) * scale + 0.5)) + end + return Crc32.of(b) +end + +t:eq(Caf.name, "caf", "name") +t:check(Caf.caps.decode and Caf.caps.encode, "caps") + +for _, c in Alac do + if c.container == "caf" then + local r = reader(c.data) + t:eq(Caf.sniff(r), 1, c.name .. ": sniff") + local a, err = Caf.decode(r) + t:check(a, c.name .. ": " .. tostring(err)) + t:check(a.channels == c.channels and a.sampleRate == c.rate and a.frames == c.frames, c.name .. ": format / length (pakt)") + t:eq(intCrc(a, c.bits), c.crc, c.name .. ": bit-exact") + end +end + +for _, c in Aac do + if c.container == "caf" then + local a, err = Caf.decode(reader(c.data)) + t:check(a, c.name .. ": " .. tostring(err)) + t:eq(a.frames, c.frames, c.name .. ": frames") + local rb = buffer.fromstring(c.ref) + local sig, e = 0, 0 + for i = 0, a.frames * a.channels - 1 do + local r = buffer.readf32(rb, i * 4) + sig += r * r + e += (buffer.readf32(a.samples, i * 4) - r) ^ 2 + end + local snr = if e == 0 then math.huge else 10 * math.log10(sig / e) + t:check(snr > 90, string.format("%s: SNR %.1f dB", c.name, snr)) + t:note("%s: SNR %.1f dB vs ffmpeg", c.name, snr) + end +end + +-- our writer: the bytes ffmpeg validated +do + local byName = {} + for _, o in Ours do + byName[o.name] = o + end + for _, c in Cases do + if c.container ~= "caf" then + continue + end + local o = byName[c.name] + t:check(o and o.ffmpeg, c.name .. ": ffmpeg decoded it bit-exactly") + local a = Signal.audio(c.rate, c.frames, c.channels, c.bits, c.seed) + local file = Caf.encode(a, { codec = c.codec, bitDepth = c.bits }) :: buffer + t:eq(string.format("%08x", Crc32.of(file)), string.format("%08x", o.crc), c.name .. ": the validated bytes") + local back = Caf.decode(reader(file)) :: any + t:check(back and back.frames == c.frames, c.name .. ": our length") + local ints = Signal.ints(c.frames, c.channels, c.bits, c.seed) + local ok = true + local scale = 2 ^ (c.bits - 1) + for i = 1, #ints do + ok = ok and math.floor(buffer.readf32(back.samples, (i - 1) * 4) * scale + 0.5) == ints[i] + end + t:check(ok, c.name .. ": round trip") + end +end + +-- float PCM, tags, a decoder as the source, a hand-built little-endian header +do + local a = Signal.audio(32000, 3000, 3, 16, 12) + a.tags = { title = "Caf Title", artist = "A", date = "1999", comment = "c", custom = "x" } + local file = Caf.encode(a, { codec = "pcm", bitDepth = 32 }) :: buffer + local back = Caf.decode(reader(file)) :: any + t:check(back.frames == 3000 and buffer.tostring(back.samples) == buffer.tostring(a.samples), "float PCM round trip") + for k, v in a.tags do + t:eq(back.tags[k], v, "tag " .. k) + end + local dec = Caf.open(reader(file)) :: any + local again = Caf.encode(dec, { codec = "alac" }) :: buffer + local b2 = Caf.decode(reader(again)) :: any + t:check(b2.frames == 3000 and buffer.tostring(b2.samples) == buffer.tostring(a.samples), "ALAC from a streaming decoder") + -- little-endian 24-bit integer PCM, data chunk of unknown size (-1) + local w = Bytes.writer(64) + w:string("caff") + w:u16be(1) + w:u16be(0) + w:string("desc") + w:u64be(32) + w:f64be(8000) + w:string("lpcm") + w:u32be(2) + w:u32be(3) + w:u32be(1) + w:u32be(1) + w:u32be(24) + w:string("data") + w:u32be(0xFFFFFFFF) + w:u32be(0xFFFFFFFF) + w:u32be(0) + for _, v in { 0, 4194304, -4194304, 8388607, -8388608 } do + w:u24le(v % 16777216) + end + local le = Caf.decode(Bytes.reader(w:finish())) :: any + t:check(le and le.frames == 5, "24-bit LE, data size -1") + t:check(le and math.abs(buffer.readf32(le.samples, 4) - 0.5) < 1e-7 and math.abs(buffer.readf32(le.samples, 16) + 1) < 1e-7, "24-bit LE values") +end + +-- seek +do + local c = Alac[#Alac] + local whole = Caf.decode(reader(c.data)) :: any + local dec = Caf.open(reader(c.data)) :: any + for _, at in { 0.1, 0.0, 0.15 } do + dec:seek(at) + local b, n = dec:read(400) + local f0 = math.floor(at * whole.sampleRate + 0.5) + local same = n == 400 + for i = 0, n * whole.channels - 1 do + same = same and buffer.readf32(b, i * 4) == buffer.readf32(whole.samples, (f0 * whole.channels + i) * 4) + end + t:check(same, string.format("seek %.2f s", at)) + end +end + +-- errors +do + t:eq(Caf.sniff(reader("caff\0\2\0\0")), 0, "sniff: wrong version") + local _, e = Caf.decode(reader("caff\0\1\0\0")) + t:check(e and e.code == Err.CORRUPT, "no desc: " .. tostring(e)) + local _, e2 = Caf.encode(Signal.audio(8000, 10, 1, 16, 1), { codec = "mp3" } :: any) + t:check(e2 and e2.code == Err.ARG, "bad codec: " .. tostring(e2)) +end + +-- fuzz +do + local samples = {} + for _, c in Alac do + if c.container == "caf" then + table.insert(samples, string.sub(c.data, 1, 9000)) + end + end + for _, c in Aac do + if c.container == "caf" then + table.insert(samples, string.sub(c.data, 1, 6000)) + end + end + local pcm = Caf.encode(Signal.audio(8000, 300, 2, 16, 3), { codec = "pcm" }) :: buffer + table.insert(samples, buffer.tostring(pcm)) + t:fuzz("decode", function(b: buffer) + return Caf.decode(Bytes.reader(b)) + end, samples, { mutations = 30 }) +end + +t:done() diff --git a/tests/audio/m4a.luau b/tests/audio/m4a.luau new file mode 100644 index 0000000..273f71e --- /dev/null +++ b/tests/audio/m4a.luau @@ -0,0 +1,218 @@ +-- audio/m4a tests: ALAC files from ffmpeg decode bit-exactly (16 / 24-bit, mono / stereo / 5.1, partial frames); +-- AAC-LC files from ffmpeg and fdkaac (stereo / mono / 5.1, 8 - 96 kHz, PNS / intensity / M/S / TNS) against ffmpeg's +-- float decode (SNR, gapless length through the edit list); HE-AAC / HE-AACv2 play their core; our ALAC writer +-- (re-encoded here, compared with the bytes ffmpeg decoded bit-exactly and MP4Box accepted in the fixture step); tags +-- and cover art round trips; streaming reads, seeking; the contract; the fuzz no-throw pass. +-- Fixtures: tools/fixtures/m4a.py. +local T = require("@tests/T") +local M4a = require("@formats/audio/m4a") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Signal = require("@tests/audio/_signal") +local Cases = require("@tests/audio/_encode_cases") +local Alac = require("@tests/gen/m4a_alac") +local Aac = require("@tests/gen/m4a_aac") +local He = require("@tests/gen/m4a_he") +local Ours = require("@tests/gen/m4a_ours") + +local t = T.suite("m4a") + +local function reader(s: string | buffer): Bytes.Reader + return Bytes.reader(if type(s) == "string" then buffer.fromstring(s) else s) +end + +-- the integers of a decoded Audio (exact for <= 24-bit sources), CRC-32 as little-endian int32 +local function intCrc(a: any, bits: number): number + local n = a.frames * a.channels + local b = buffer.create(n * 4) + local scale = 2 ^ (bits - 1) + for i = 0, n - 1 do + buffer.writei32(b, i * 4, math.floor(buffer.readf32(a.samples, i * 4) * scale + 0.5)) + end + return Crc32.of(b) +end + +local function snr(a: any, ref: string): (number, number) + local n = math.min(a.frames * a.channels, #ref // 4) + local rb = buffer.fromstring(ref) + local sig, err = 0, 0 + for i = 0, n - 1 do + local r = buffer.readf32(rb, i * 4) + local d = buffer.readf32(a.samples, i * 4) - r + sig += r * r + err += d * d + end + if err == 0 then + return math.huge, n + end + return 10 * math.log10(sig / err), n +end + +-- the contract +t:eq(M4a.name, "m4a", "name") +t:eq(M4a.category, "audio", "category") +t:check(M4a.caps.decode and M4a.caps.encode, "caps") + +-- ALAC from ffmpeg: bit-exact +for _, c in Alac do + if c.container ~= "m4a" then + continue + end + local r = reader(c.data) + t:check(M4a.sniff(r) == 1, c.name .. ": sniff") + local a, err = M4a.decode(r) + t:check(a, c.name .. ": " .. tostring(err)) + t:check(a.channels == c.channels and a.sampleRate == c.rate, c.name .. ": format") + t:eq(a.frames, c.frames, c.name .. ": frames") + t:eq(intCrc(a, c.bits), c.crc, c.name .. ": samples bit-exact") + t:eq(a.meta.source.codec, "alac", c.name .. ": codec") +end +t:note("%d ffmpeg ALAC files decode bit-exactly", #Alac - 1) + +-- AAC: against ffmpeg's float decode +local worst = math.huge +for _, c in Aac do + if c.container ~= "m4a" then + continue + end + local a, err = M4a.decode(reader(c.data)) + t:check(a, c.name .. ": " .. tostring(err)) + t:check(a.channels == c.channels and a.sampleRate == c.rate, c.name .. ": format") + t:eq(a.frames, c.frames, c.name .. ": gapless length") + local s = snr(a, c.ref) + worst = math.min(worst, s) + t:check(s > 90, string.format("%s: SNR %.1f dB vs ffmpeg", c.name, s)) + t:note("%s: %d ch %d Hz, %d frames, SNR %.1f dB vs ffmpeg", c.name, c.channels, c.rate, a.frames, s) +end + +-- HE-AAC: the AAC-LC core at half the rate, SBR seen +for _, c in He do + if string.sub(c.name, -4) ~= ".m4a" then + continue + end + local dec, err = M4a.open(reader(c.data)) + t:check(dec, c.name .. ": " .. tostring(err)) + t:eq(dec.sampleRate, c.rate // 2, c.name .. ": core rate") + local b, n = dec:read(8192) + local e = 0 + for i = 0, n * dec.channels - 1 do + e += buffer.readf32(b, i * 4) ^ 2 + end + t:check(n == 8192 and e > 1, c.name .. ": the core decodes (energy " .. e .. ")") +end + +-- our ALAC writer: the bytes ffmpeg validated +do + local byName = {} + for _, o in Ours do + byName[o.name] = o + end + for _, c in Cases do + if c.container ~= "m4a" then + continue + end + local o = byName[c.name] + t:check(o and o.ffmpeg and o.mp4box and o.codec == "alac", c.name .. ": ffmpeg decoded it bit-exactly, MP4Box read it") + t:eq(o.frames, c.frames, c.name .. ": ffmpeg's length") + local a = Signal.audio(c.rate, c.frames, c.channels, c.bits, c.seed) + a.tags = c.tags or {} + local file, err = M4a.encode(a, { bitDepth = c.bits }) + t:check(file, c.name .. ": encode: " .. tostring(err)) + t:eq(string.format("%08x", Crc32.of(file :: buffer)), string.format("%08x", o.crc), c.name .. ": the validated bytes") + -- and our own decoder gets the integers back + local back = M4a.decode(Bytes.reader(file :: buffer)) :: any + local ints = Signal.ints(c.frames, c.channels, c.bits, c.seed) + local ok = back.frames == c.frames + local scale = 2 ^ (c.bits - 1) + for i = 1, #ints, 7 do + ok = ok and math.floor(buffer.readf32(back.samples, (i - 1) * 4) * scale + 0.5) == ints[i] + end + t:check(ok, c.name .. ": round trip") + if c.tags then + for k, v in c.tags do + t:eq(back.tags[k], v, c.name .. ": tag " .. k) + end + t:eq(o.tags.title, c.tags.title, c.name .. ": ffprobe title") + t:eq(o.tags.track, c.tags.track .. "/" .. c.tags.tracktotal, c.name .. ": ffprobe track") + t:eq(o.tags.artist, c.tags.artist, c.name .. ": ffprobe artist") + end + t:note("%s: %d bytes (%.0f%% of PCM)", c.name, buffer.len(file :: buffer), 100 * buffer.len(file :: buffer) / (c.frames * c.channels * c.bits / 8)) + end +end + +-- cover art + streaming a decoder into the encoder +do + local a = Signal.audio(44100, 5000, 2, 16, 9) + a.meta.pictures = { { mime = "image/png", data = buffer.fromstring("\137PNG fake") } } + a.tags = { title = "Pic" } + local file = M4a.encode(a) :: buffer + local back = M4a.decode(Bytes.reader(file)) :: any + t:check(back.meta.pictures and #back.meta.pictures == 1 and back.meta.pictures[1].mime == "image/png", "cover art round trip") + local dec = M4a.open(Bytes.reader(file)) :: any + local again = M4a.encode(dec) :: buffer + local back2 = M4a.decode(Bytes.reader(again)) :: any + t:check(back2.frames == 5000 and buffer.tostring(back2.samples) == buffer.tostring(back.samples), "encode from a streaming decoder") + local _, e = M4a.encode({} :: any) + t:check(e and e.code == Err.ARG, "encode of a non-audio returns Err.ARG") + local _, e2 = M4a.encode(a, { bitDepth = 12 }) + t:check(e2 and e2.code == Err.ARG, "bad bitDepth returns Err.ARG") +end + +-- streaming + seek (AAC without PNS: its noise is random, so a seek changes it; and ALAC) +for _, c in { Aac[1], Alac[1] } do + local whole = M4a.decode(reader(c.data)) :: any + local dec = M4a.open(reader(c.data)) :: any + t:eq(dec.frames, whole.frames, c.name .. ": decoder frames") + -- read in odd chunks + local got, out = 0, buffer.create(whole.frames * whole.channels * 4) + while true do + local b, n = dec:read(777) + if n == 0 then + break + end + buffer.copy(out, got * whole.channels * 4, b, 0, n * whole.channels * 4) + got += n + end + t:check(got == whole.frames and buffer.tostring(out) == buffer.tostring(whole.samples), c.name .. ": chunked reads equal the whole decode") + for _, at in { 0.1, 0.0, 0.05 } do + dec:seek(at) + local b, n = dec:read(500) + local f0 = math.floor(at * whole.sampleRate + 0.5) + local maxd = 0 + for i = 0, n * whole.channels - 1 do + maxd = math.max(maxd, math.abs(buffer.readf32(b, i * 4) - buffer.readf32(whole.samples, (f0 * whole.channels + i) * 4))) + end + t:check(n == 500 and maxd < 1e-6, string.format("%s: seek %.2f s (max diff %g)", c.name, at, maxd)) + t:check(math.abs(dec:position() - (f0 + 500) / whole.sampleRate) < 1e-9, c.name .. ": position after seek") + end +end + +-- errors +do + local _, e = M4a.decode(reader("\0\0\0\8ftypM4A ")) + t:check(e ~= nil, "a lone ftyp: " .. tostring(e)) + local _, e2 = M4a.decode(reader("hello world, not an mp4")) + t:check(e2 ~= nil and Err.is(e2), "junk: " .. tostring(e2)) + t:eq(M4a.sniff(reader("hello")), 0, "sniff junk") +end + +-- fuzz +do + local samples = {} + for i, c in Alac do + if c.container == "m4a" and i <= 2 then + table.insert(samples, string.sub(c.data, 1, 12000)) + end + end + for i, c in Aac do + if c.container == "m4a" and i <= 2 then + table.insert(samples, string.sub(c.data, 1, 9000)) + end + end + t:fuzz("decode", function(b: buffer) + return M4a.decode(Bytes.reader(b)) + end, samples, { mutations = 25 }) +end + +t:done() diff --git a/tests/audio/opus.luau b/tests/audio/opus.luau index c876dce..8403251 100644 --- a/tests/audio/opus.luau +++ b/tests/audio/opus.luau @@ -81,7 +81,7 @@ end -- ------------------------------------------------------------------------------------------------ contract t:eq(Opus.name, "opus", "name") t:eq(Opus.category, "audio", "category") -t:check(Opus.caps.decode and not Opus.caps.encode and Opus.open ~= nil and Opus.decode ~= nil, "caps") +t:check(Opus.caps.decode and Opus.caps.encode and Opus.open ~= nil and Opus.decode ~= nil and Opus.encode ~= nil, "caps (the CELT encoder: tests/audio/opus_encode.luau)") t:eq(Opus.sniff(Bytes.reader(FX.celt_st_128.data)), 1, "sniff an Opus file") t:eq(Opus.sniff(Bytes.reader(buffer.fromstring("OggS" .. string.rep("\0", 40)))), 0, "sniff another Ogg") t:eq(Opus.sniff(Bytes.reader(buffer.create(0))), 0, "sniff nothing") diff --git a/tests/audio/opus_encode.luau b/tests/audio/opus_encode.luau new file mode 100644 index 0000000..c3aeff4 --- /dev/null +++ b/tests/audio/opus_encode.luau @@ -0,0 +1,114 @@ +-- audio/opus encoder tests (the CELT-only writer, ws-m4a; mono and mid / side stereo): our Ogg Opus files (re-encoded here, compared with the bytes +-- checked in the fixture step) decode in libopus' opusdec to the input's exact length (pre-skip + end trimming) with a +-- minimum SNR, opusinfo finds no problem, ffmpeg reads them, OpusTags carry the tags; our decoder agrees with opusdec; +-- resampled 44.1 kHz input; silence frames; streaming input; errors; a fuzz no-throw pass over our files. +-- Fixtures: tools/fixtures/opus_celt.py. +local T = require("@tests/T") +local Opus = require("@formats/audio/opus") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Cases = require("@tests/audio/_opus_cases") +local Fx = require("@tests/gen/opus_celt") + +local t = T.suite("opus-encode") + +t:check(Opus.caps.encode and Opus.encode ~= nil, "caps: encode") + +local byName = {} +for _, f in Fx do + byName[f.name] = f +end + +local function snr(ref: buffer, refBase: number, got: buffer, n: number): number + local s, e = 0, 0 + for i = 0, n - 1 do + local x = buffer.readf32(ref, (refBase + i) * 4) + local d = buffer.readf32(got, (refBase + i) * 4) - x + s += x * x + e += d * d + end + return if e == 0 then math.huge else 10 * math.log10(s / math.max(e, 1e-30)) +end + +local files = {} +for _, c in Cases.list do + local fx = byName[c.name] + t:check(fx, c.name .. ": fixture") + local input = Cases.signal(c) + local file, err = Opus.encode(input, { bitrate = c.bitrate }) + t:check(file, c.name .. ": encode: " .. tostring(err)) + table.insert(files, file) + t:eq(string.format("%08x", Crc32.of(file :: buffer)), string.format("%08x", fx.crc), c.name .. ": the bytes the reference tools checked") + t:check(fx.opusinfo, c.name .. ": opusinfo reports no problem") + t:check(fx.ffmpeg, c.name .. ": ffmpeg decodes it") + local frames48 = math.floor(input.frames * 48000 / c.rate + 0.5) + local ch = c.channels + t:eq(#fx.opusdec // (4 * ch), frames48, c.name .. ": opusdec length = the input's (pre-skip + end trimming)") + t:eq(fx.ffmpegFrames, frames48, c.name .. ": ffmpeg length") + -- our decoder vs opusdec + local ours = Opus.decode(Bytes.reader(file :: buffer)) :: any + t:eq(ours.frames, frames48, c.name .. ": our decoder's length") + local ref = buffer.fromstring(fx.opusdec) + local agree = snr(ref, 0, ours.samples, frames48 * ch) + t:check(agree > 60, string.format("%s: our decoder vs opusdec %.1f dB", c.name, agree)) + -- quality vs the input (48 kHz inputs; skip the edges) + if c.rate == 48000 and frames48 > 4000 then + local s = snr(input.samples, 960 * ch, ref, (frames48 - 1920) * ch) + t:check(s >= c.minSnr, string.format("%s: SNR %.1f dB (minimum %d)", c.name, s, c.minSnr)) + t:note("%s: %d bytes, SNR %.1f dB vs the input, our decoder vs opusdec %.1f dB", c.name, buffer.len(file :: buffer), s, agree) + end + if c.tags then + for k, v in c.tags do + t:eq(fx.comments[k], v, c.name .. ": opusinfo comment " .. k) + t:eq(ours.tags[k], v, c.name .. ": our tag " .. k) + end + end +end + +-- silence frames decode to silence +do + local c = Cases.list[1] + local ref = buffer.fromstring(byName[c.name].opusdec) + local peak = 0 + for i = math.floor(0.62 * 48000), math.floor(0.73 * 48000) do + peak = math.max(peak, math.abs(buffer.readf32(ref, i * 4))) + end + t:check(peak < 1e-3, "digital silence stays silent (peak " .. peak .. ")") +end + +-- a streaming decoder as the input +do + local c = Cases.list[1] + local dec = Opus.open(Bytes.reader(files[1] :: buffer)) :: any + local again, err = Opus.encode(dec, { bitrate = 64000 }) + t:check(again, "encode from a decoder: " .. tostring(err)) + local back = Opus.decode(Bytes.reader(again :: buffer)) :: any + t:eq(back.frames, math.floor(c.seconds * 48000 + 0.5), "re-encoded length") +end + +-- errors +do + local three = Cases.signal({ rate = 48000, channels = 3, seconds = 0.05 }) + local _, e = Opus.encode(three) + t:check(e and e.code == Err.UNSUPPORTED, "3 channels: " .. tostring(e)) + local _, e2 = Opus.encode(Cases.signal(Cases.list[6]), { bitrate = 1000 }) + t:check(e2 and e2.code == Err.ARG, "bitrate too low") + local _, e3 = Opus.encode({} :: any) + t:check(e3 and e3.code == Err.ARG, "not audio") +end + +-- fuzz the decoder over our files +do + local samples = {} + for i, f in files do + if i <= 3 then + table.insert(samples, string.sub(buffer.tostring(f :: buffer), 1, 4000)) + end + end + t:fuzz("decode our files", function(b: buffer) + return Opus.decode(Bytes.reader(b)) + end, samples, { mutations = 10, garbage = 30 }) +end + +t:done() diff --git a/tests/codecs/aac.luau b/tests/codecs/aac.luau new file mode 100644 index 0000000..b340bd4 --- /dev/null +++ b/tests/codecs/aac.luau @@ -0,0 +1,182 @@ +-- codecs/Aac tests: AudioSpecificConfig parsing (every fixture's esds, explicit SBR / PS signalling from fdkaac, +-- crafted configs: PCE channel counts, 960-sample frames, Main / LTP object types), ADTS headers, raw frames decoded +-- straight from ADTS against ffmpeg's float decode, the FIL extension hook on HE-AAC (implicit SBR), reset, errors, +-- the fuzz no-throw pass on raw frames. Fixtures: tools/fixtures/m4a.py. +local T = require("@tests/T") +local Aac = require("@formats/codecs/Aac") +local IsoBmff = require("@formats/containers/IsoBmff") +local Bytes = require("@formats/core/Bytes") +local Bits = require("@formats/core/Bits") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/m4a_aac") +local He = require("@tests/gen/m4a_he") + +local t = T.suite("aac-codec") + +-- ADTS frames of a stream: { offset, size } of the raw blocks +local function frames(data: buffer): ({ { number } }, Aac.Adts?) + local out, p, first = {}, 0, nil + while true do + local h = Aac.adts(data, p, buffer.len(data)) + if not h or p + h.frameSize > buffer.len(data) then + break + end + first = first or h + table.insert(out, { p + h.headerSize, h.frameSize - h.headerSize }) + p += h.frameSize + end + return out, first +end + +-- ASCs from the M4A fixtures +for _, c in Fx do + if c.container == "m4a" then + local r = Bytes.reader(buffer.fromstring(c.data)) + local movie = IsoBmff.parse(r) :: IsoBmff.Movie + local cfg, err = Aac.config(movie.tracks[1].config :: buffer) + t:check(cfg, c.name .. ": " .. tostring(err)) + t:check(cfg.objectType == 2 and cfg.sampleRate == c.rate and cfg.channels == c.channels and not cfg.sbr, c.name .. ": AAC-LC config") + end +end +for _, c in He do + if string.sub(c.name, -4) == ".m4a" then + local r = Bytes.reader(buffer.fromstring(c.data)) + local movie = IsoBmff.parse(r) :: IsoBmff.Movie + local cfg, err = Aac.config(movie.tracks[1].config :: buffer) + t:check(cfg, c.name .. ": " .. tostring(err)) + t:check(cfg.sbr and cfg.sampleRate == c.rate // 2 and cfg.extensionRate == c.rate, c.name .. ": SBR signalled, core at half rate") + t:eq(cfg.ps, c.ps, c.name .. ": PS signalled") + end +end + +-- crafted configs +do + local asc = Aac.asc(2, 4, 2) + local cfg = Aac.config(asc) :: Aac.Config + t:check(cfg and cfg.sampleRate == 44100 and cfg.channels == 2, "asc(2, 44.1 kHz, stereo)") + local _, e1 = Aac.config(Aac.asc(1, 4, 2)) + t:check(e1 and e1.code == Err.UNSUPPORTED, "AAC Main: " .. tostring(e1)) + local _, e2 = Aac.config(Aac.asc(23, 4, 2)) + t:check(e2 and e2.code == Err.UNSUPPORTED, "ER AAC LD") + local b960 = Aac.asc(2, 3, 1) + buffer.writeu8(b960, 1, bit32.bor(buffer.readu8(b960, 1), 4)) -- frameLengthFlag + local _, e3 = Aac.config(b960) + t:check(e3 and e3.code == Err.UNSUPPORTED, "960-sample frames") + -- channel configuration 0 with a PCE: front C (SCE) + L/R (CPE), back L/R (CPE), one LFE = 6 channels + local bw = Bits.msbWriter() + bw:write(2, 5) + bw:write(3, 4) + bw:write(0, 4) + bw:write(0, 3) -- GASpecificConfig flags + bw:write(0, 4) -- PCE: tag + bw:write(1, 2) + bw:write(3, 4) + bw:write(2, 4) -- front + bw:write(0, 4) -- side + bw:write(1, 4) -- back + bw:write(1, 2) -- lfe + bw:write(0, 3) + bw:write(0, 4) + bw:write(0, 3) -- mixdowns + bw:write(0, 5) + bw:write(16 + 1, 5) -- front: SCE 0, CPE 1 + bw:write(16 + 2, 5) -- back: CPE 2 + bw:write(0, 4) -- lfe tag + bw:align() + bw:write(0, 8) -- comment + local pcfg, perr = Aac.config(bw:finish()) + t:check(pcfg and pcfg.channels == 6 and pcfg.channelConfig == 0, "PCE: 6 channels: " .. tostring(perr)) + local _, e4 = Aac.decoder("nope" :: any) + t:check(e4 and e4.code == Err.ARG, "decoder of a string") +end + +-- ADTS headers + raw frames against ffmpeg +for _, c in Fx do + if c.container ~= "adts" then + continue + end + local data = buffer.fromstring(c.data) + local list, h = frames(data) + t:check(h and h.objectType == 2 and h.sampleRate == c.rate, c.name .. ": ADTS header") + local dec = Aac.decoder({ sfIndex = (h :: Aac.Adts).sfIndex, channels = c.channels }) :: Aac.Decoder + local ref = buffer.fromstring(c.ref) + local sig, err = 0, 0 + local o = 0 + for _, f in list do + local n, e = dec:decode(data, f[1], f[2]) + t:check(n == 1024, c.name .. ": frame: " .. tostring(e)) + for k = 1, 1024 * c.channels do + local r = buffer.readf32(ref, o) + sig += r * r + err += (dec.pcm[k] - r) ^ 2 + o += 4 + end + end + local snr = 10 * math.log10(sig / math.max(err, 1e-30)) + t:check(snr > 90, string.format("%s: SNR %.1f dB", c.name, snr)) + t:note("%s: %d raw frames, SNR %.1f dB vs ffmpeg", c.name, #list, snr) + -- reset: decoding again from the start gives the same first frames + dec:reset() + dec:decode(data, list[1][1], list[1][2]) + local again = table.clone(dec.pcm) + local dec2 = Aac.decoder({ sfIndex = (h :: Aac.Adts).sfIndex, channels = c.channels }) :: Aac.Decoder + dec2:decode(data, list[1][1], list[1][2]) + local same = true + for k = 1, 1024 * c.channels do + same = same and again[k] == dec2.pcm[k] + end + t:check(same, c.name .. ": reset clears the overlap") +end + +-- the extension hook on HE-AAC (implicit SBR in ADTS) +for _, c in He do + if string.sub(c.name, -4) == ".aac" then + local data = buffer.fromstring(c.data) + local list, h = frames(data) + local dec = Aac.decoder({ sfIndex = (h :: Aac.Adts).sfIndex, channels = 2 }) :: Aac.Decoder + local seen, bits = 0, 0 + dec.onExtension = function(kind: number, _element: number, _buf: buffer, _pos: number, n: number) + if kind == 13 or kind == 14 then + seen += 1 + bits += n + end + end + for _, f in list do + dec:decode(data, f[1], f[2]) + end + t:check(seen == #list and dec.sbr, string.format("%s: an SBR payload per frame (%d of %d, %d bits)", c.name, seen, #list, bits)) + end +end + +-- errors +do + local dec = Aac.decoder(Aac.asc(2, 4, 2)) :: Aac.Decoder + local _, e = dec:decode(buffer.fromstring("\x20\x00\x00\x00\x00")) + t:check(e and e.code == Err.CORRUPT, "garbage frame: " .. tostring(e)) + local _, e2 = dec:decode(buffer.create(4), 3, 10) + t:check(e2 and e2.code == Err.ARG, "range out of the buffer") + t:check(Aac.adts(buffer.fromstring("\255\241"), 0, 2) == nil, "short ADTS header") +end + +-- fuzz raw frames (stereo with every tool, mono, 5.1) +do + local pick = {} + for _, c in Fx do + if c.container == "adts" then + local data = buffer.fromstring(c.data) + local list, h = frames(data) + local f = list[math.min(#list, 9)] + local raw = buffer.create(f[2]) + buffer.copy(raw, 0, data, f[1], f[2]) + table.insert(pick, { raw, (h :: Aac.Adts).sfIndex, c.channels }) + end + end + for _, p in pick do + local dec = Aac.decoder({ sfIndex = p[2], channels = p[3] }) :: Aac.Decoder + t:fuzz("raw frame " .. p[3] .. " ch", function(b: buffer) + return dec:decode(b) + end, { p[1] }, { mutations = 60, garbage = 100 }) + end +end + +t:done() diff --git a/tests/codecs/alac.luau b/tests/codecs/alac.luau new file mode 100644 index 0000000..8dff395 --- /dev/null +++ b/tests/codecs/alac.luau @@ -0,0 +1,181 @@ +-- codecs/Alac tests: encoder -> decoder round trips over silence (zero runs), full-scale noise (uncompressed frames), +-- tones, steps, 1 - 8 channels, 16 / 20 / 24 bits, partial and tiny frames, custom frame lengths; ffmpeg's ALAC +-- packets (through containers/IsoBmff) decode to the source integers; the magic cookie (plain, behind frma / alac atoms, +-- bad versions / depths); errors; the fuzz no-throw pass on packets. Fixtures: tools/fixtures/m4a.py. +local T = require("@tests/T") +local Alac = require("@formats/codecs/Alac") +local IsoBmff = require("@formats/containers/IsoBmff") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/m4a_alac") + +local t = T.suite("alac") +local rand = T.rng(42) + +local function roundTrip(label: string, ch: number, bits: number, frames: number, gen: (number, number) -> number, fl: number?) + local enc = Alac.encoder({ sampleRate = 44100, channels = ch, bitDepth = bits, frameLength = fl }) :: Alac.Encoder + t:check(enc, label .. ": encoder") + local per = enc.config.frameLength + local src = table.create(frames * ch, 0) + for i = 0, frames - 1 do + for c = 1, ch do + src[i * ch + c] = gen(i, c) + end + end + local packets = {} + local bytes = 0 + local f = 0 + while f < frames do + local n = math.min(per, frames - f) + local p, err = enc:encode(src, f * ch + 1, n) + t:check(p, label .. ": encode: " .. tostring(err)) + table.insert(packets, { p, n }) + bytes += buffer.len(p :: buffer) + f += n + end + local cfg = Alac.config(Alac.cookie(enc.config)) :: Alac.Config + t:check(cfg and cfg.maxFrameBytes >= 1 and cfg.channels == ch and cfg.bitDepth == bits, label .. ": cookie") + local dec = Alac.decoder(cfg) + local ok = true + local at = 0 + for _, pk in packets do + local n, err = dec:decode(pk[1]) + if n ~= pk[2] then + ok = false + t:check(false, label .. ": decode: " .. tostring(err)) + break + end + for k = 1, n * ch do + if dec.pcm[k] ~= src[at * ch + k] then + ok = false + end + end + at += n + end + t:check(ok, label .. ": round trip") + return bytes / (frames * ch * bits / 8) +end + +local peakOf = function(bits: number): number + return 2 ^ (bits - 1) +end + +for _, bits in { 16, 20, 24 } do + local pk = peakOf(bits) + for _, ch in { 1, 2, 3, 6, 8 } do + local r1 = roundTrip(string.format("tone %d-bit %d ch", bits, ch), ch, bits, 9000, function(i, c) + return math.floor(math.sin(i * 0.031 * c) * (pk * 0.6) + math.sin(i * 0.0071) * pk * 0.2) + end) + if ch == 2 then + t:note("%d-bit stereo tone: %.0f%% of PCM", bits, r1 * 100) + end + end + roundTrip(bits .. "-bit silence (zero runs)", 2, bits, 10000, function() + return 0 + end) + local r = roundTrip(bits .. "-bit full-scale noise (escape frames)", 2, bits, 5000, function() + return rand(2 ^ bits) - pk + end) + t:check(r < 1.01, bits .. "-bit noise stays near PCM size") + roundTrip(bits .. "-bit extremes", 1, bits, 600, function(i) + return if i % 2 == 0 then pk - 1 else -pk + end) + roundTrip(bits .. "-bit sparse clicks (zero runs + values)", 2, bits, 7000, function(i, c) + return if i % 997 == c then pk // 3 else 0 + end) +end +for _, n in { 1, 2, 3, 5, 9, 17, 4095 } do + roundTrip("partial frame of " .. n, 2, 16, n, function(i, c) + return (i * 37 + c * 1000) % 3000 - 1500 + end) +end +roundTrip("frame length 1024", 2, 16, 5000, function(i) + return math.floor(math.sin(i * 0.05) * 10000) +end, 1024) +roundTrip("identical channels", 2, 16, 5000, function(i) + return math.floor(math.sin(i * 0.02) * 20000) +end) + +-- ffmpeg's packets +for _, c in Fx do + if c.container == "m4a" then + local r = Bytes.reader(buffer.fromstring(c.data)) + local movie = IsoBmff.parse(r) :: IsoBmff.Movie + local tr = movie.tracks[1] + local cfg = Alac.config(tr.config :: buffer) :: Alac.Config + t:check(cfg and cfg.bitDepth == c.bits and cfg.channels == c.channels, c.name .. ": cookie") + local dec = Alac.decoder(cfg) + local out = buffer.create(c.frames * c.channels * 4) + local o = 0 + for i = 1, tr.sampleCount do + local n, err = dec:decode(r.buf, tr.offsets[i], tr.sizes[i]) + t:check(n, c.name .. ": packet " .. i .. ": " .. tostring(err)) + for k = 1, (n :: number) * c.channels do + buffer.writei32(out, o, dec.pcm[k]) + o += 4 + end + end + t:eq(Crc32.of(out), c.crc, c.name .. ": ffmpeg's packets decode to the source") + end +end + +-- the cookie behind QuickTime atoms, bad cookies +do + local enc = Alac.encoder({ sampleRate = 48000, channels = 2 }) :: Alac.Encoder + local plain = Alac.cookie(enc.config) + local w = Bytes.writer(64) + w:u32be(12) + w:string("frma") + w:string("alac") + w:u32be(36) + w:string("alac") + w:u32be(0) + w:bytes(plain) + local cfg = Alac.config(w:finish()) + t:check(cfg and cfg.sampleRate == 48000 and cfg.frameLength == 4096, "cookie behind frma / alac atoms") + local bad = buffer.fromstring(buffer.tostring(plain)) + buffer.writeu8(bad, 5, 12) + local _, e = Alac.config(bad) + t:check(e and e.code == Err.UNSUPPORTED, "12-bit cookie: " .. tostring(e)) + local _, e2 = Alac.config(buffer.create(10)) + t:check(e2 and e2.code == Err.TRUNCATED, "short cookie") + local _, e3 = Alac.encoder({ sampleRate = 44100, channels = 9 }) + t:check(e3 and e3.code == Err.ARG, "9 channels") + local _, e4 = enc:encode({ 1, 2 }, 1, 5) + t:check(e4 and e4.code == Err.ARG, "too few samples") + local dec = Alac.decoder(cfg :: Alac.Config) + local _, e5 = dec:decode(buffer.fromstring("\1\255\255\255")) + t:check(e5 and e5.code == Err.CORRUPT, "bad packet: " .. tostring(e5)) +end + +-- fuzz the packet decoder +do + local enc = Alac.encoder({ sampleRate = 44100, channels = 2, bitDepth = 16 }) :: Alac.Encoder + local src = table.create(2 * 3000, 0) + for i = 1, #src do + src[i] = math.floor(math.sin(i * 0.01) * 8000) + rand(64) + end + local samples = {} + table.insert(samples, (enc:encode(src, 1, 3000))) + for i = 1, #src do + src[i] = if i % 300 < 3 then 5000 else 0 + end + table.insert(samples, (enc:encode(src, 1, 3000))) + local dec = Alac.decoder(enc.config) + local enc24 = Alac.encoder({ sampleRate = 44100, channels = 1, bitDepth = 24 }) :: Alac.Encoder + local dec24 = Alac.decoder(enc24.config) + local s24 = table.create(2000, 0) + for i = 1, 2000 do + s24[i] = rand(2 ^ 24) - 2 ^ 23 + end + local p24 = enc24:encode(s24, 1, 2000) :: buffer + t:fuzz("decode packet", function(b: buffer) + return dec:decode(b) + end, samples, { mutations = 40 }) + t:fuzz("decode 24-bit escape packet", function(b: buffer) + return dec24:decode(b) + end, { p24 }, { mutations = 20, garbage = 50 }) +end + +t:done() diff --git a/tests/codecs/base64.luau b/tests/codecs/base64.luau new file mode 100644 index 0000000..7d9e4b4 --- /dev/null +++ b/tests/codecs/base64.luau @@ -0,0 +1,46 @@ +-- codecs/Base64 tests: encode / decode against Python's base64 (standard, URL-safe, unpadded) for every length 0..70 +-- and some large inputs, whitespace and missing padding on decode, data: URIs, bad input, and the fuzz no-throw pass. +-- Fixtures: tools/fixtures/base64.py. +local T = require("@tests/T") +local Base64 = require("@formats/codecs/Base64") +local Cases = require("@tests/gen/base64_cases") + +local t = T.suite("base64") + +for _, c in Cases do + local b = buffer.fromstring(c.data) + t:eq(Base64.encode(b), c.std, "encode " .. #c.data) + t:eq(Base64.encode(b, { url = true }), c.url, "encode url " .. #c.data) + t:eq(Base64.encode(b, { pad = false }), c.nopad, "encode unpadded " .. #c.data) + for _, s in { c.std, c.url, c.nopad } do + local d, err = Base64.decode(s) + t:check(d and buffer.tostring(d) == c.data, "decode " .. #c.data .. ": " .. tostring(err)) + end + -- with line breaks every 76 characters (MIME) + local wrapped = string.gsub(c.std, "(" .. string.rep(".", 76) .. ")", "%1\r\n") + local d = Base64.decode(wrapped) + t:check(d and buffer.tostring(d) == c.data, "decode wrapped " .. #c.data) +end +-- a sub-range +t:eq(Base64.encode(buffer.fromstring("xxhelloyy"), nil, 2, 5), "aGVsbG8=", "encode a range") +-- data URIs +local b, mime = Base64.decodeDataUri("data:application/gltf-buffer;base64,AAEC") +t:check(b and buffer.len(b) == 3 and buffer.readu8(b, 2) == 2 and mime == "application/gltf-buffer", "data URI") +local b2, m2 = Base64.decodeDataUri("data:,a%20b") +t:check(b2 and buffer.tostring(b2) == "a b" and m2 == "text/plain", "percent-encoded data URI") +t:eq(Base64.dataUri(buffer.fromstring("hi"), "text/plain"), "data:text/plain;base64,aGk=", "dataUri") +-- bad input +t:check(Base64.decode("ab$d") == nil, "bad character") +t:check(Base64.decode("abcde") == nil, "a lone last character") +t:check(Base64.decode("ab==cd") == nil, "data after padding") +t:check(Base64.decodeDataUri("http://x") == nil, "not a data URI") +local samples = {} +for i, c in Cases do + if i % 10 == 0 then + table.insert(samples, c.std) + end +end +t:fuzz("decode", function(x: buffer) + return Base64.decode(x) +end, samples) +t:done() diff --git a/tests/codecs/brotli.luau b/tests/codecs/brotli.luau new file mode 100644 index 0000000..8a9df45 --- /dev/null +++ b/tests/codecs/brotli.luau @@ -0,0 +1,126 @@ +-- codecs/Brotli tests: every fixture stream (reference encoder: qualities 0..11, windows 10..24, text / font / generic +-- modes, large windows) decodes to its corpus; consumedEnd; offsets inside a bigger buffer; the static dictionary; +-- hand-made streams (empty, metadata, uncompressed); maxBytes; truncated / corrupted / random input returns nil, Err +-- and never throws. Fixtures: tools/fixtures/brotli.py. +local T = require("@tests/T") +local Brotli = require("@formats/codecs/Brotli") +local Err = require("@formats/core/Err") +local Crc32 = require("@formats/core/Crc32") +local Fx = require("@tests/gen/brotli") + +local t = T.suite("brotli") + +-- the static dictionary +do + local d = Brotli.dictionary() + t:check(d and buffer.len(d) == 122784, "dictionary size") + t:eq(buffer.readstring(d :: buffer, 0, 8), "timedown", "dictionary starts with the length-4 words") +end + +-- every case +local nbytes = 0 +for _, c in Fx.cases do + local want = Fx.corpora[c.corpus] + local out, e = Brotli.decompress(c.data) + t:check(out ~= nil, c.name .. ": " .. tostring(e)) + if buffer.tostring(out :: buffer) ~= want then + t:check(false, c.name .. ": output differs (" .. buffer.len(out :: buffer) .. " bytes, want " .. #want .. ")") + end + t:eq(e, #c.data, c.name .. ": consumed") + nbytes += #want +end +t:note("%d fixture streams, %.1f MB decoded", #Fx.cases, nbytes / 1e6) + +-- at an offset inside a bigger buffer, with trailing bytes +do + local c = Fx.cases[30] + local big = buffer.create(#c.data + 13) + buffer.fill(big, 0, 0xAB) + buffer.writestring(big, 5, c.data) + local out, e = Brotli.decompress(big, 5, #c.data + 8) + t:check(out and buffer.tostring(out) == Fx.corpora[c.corpus] and e == 5 + #c.data, "at an offset") +end + +-- hand-made streams +do + local bytes = T.bytes + -- WBITS 16 (bit 0), ISLAST, ISLASTEMPTY: 0b110 = 6 + local o, e = Brotli.decompress(bytes({ 6 })) + t:check(o and buffer.len(o) == 0 and e == 1, "empty stream: " .. tostring(e)) + -- 0x3b: python brotli's empty stream (WBITS 22) + local o2 = Brotli.decompress(bytes({ 0x3b })) + t:check(o2 and buffer.len(o2) == 0, "empty stream (WBITS 22)") + local _, e0 = Brotli.decompress(bytes({})) + t:check(e0 and e0.code == Err.TRUNCATED, "empty input is TRUNCATED") + -- an uncompressed meta-block "hi": WBITS 16 [0], ISLAST 0, MNIBBLES 4 [00], MLEN-1 = 1 [1000 0000 0000 0000], + -- ISUNCOMPRESSED 1, pad, "hi", then ISLAST 1 ISLASTEMPTY 1 + -- bits LSB first: 0 | 0 | 00 | 1000 | 0000 0000 0000 | 1 -> byte0 = 0b00010000 = 0x10 (bits 0..7: 0,0,0,0,1,0,0,0) + -- byte1 = 0, byte2 = bits 16..23: 0,0,0,0 (rest of nibbles) 1 (ISUNCOMPRESSED) + pad 000 = 0x10 + local o3 = Brotli.decompress(bytes({ 0x10, 0x00, 0x10, 0x68, 0x69, 0x03 })) + t:check(o3 and buffer.tostring(o3) == "hi", "uncompressed meta-block") + local _, e3 = Brotli.decompress(bytes({ 0x10, 0x00, 0x10, 0x68 })) + t:check(e3 and e3.code == Err.TRUNCATED, "truncated uncompressed block: " .. tostring(e3)) + -- nonzero padding at the end + local _, e4 = Brotli.decompress(bytes({ 0x10, 0x00, 0x10, 0x68, 0x69, 0x0b })) + t:check(e4 and e4.code == Err.CORRUPT, "nonzero padding: " .. tostring(e4)) + -- a metadata block (MNIBBLES 3, 1 byte length, 2 bytes skipped) before the last empty one + -- bits: WBITS 0 | ISLAST 0 | MNIBBLES 11 | reserved 0 | MSKIPBYTES 01 | len-1 = 1 (8 bits) | pad | 2 bytes | 11 + -- 0,0,1,1,0,1,0, then 8 bits of 1: 1,0,0,0,0,0,0,0, pad to 16 -> byte0 = 0b0 1 0 1 1 0 0 = bits0..7: 0,0,1,1,0,1,0,1 + local o5 = Brotli.decompress(bytes({ 0xAC, 0x00, 0xEE, 0xEE, 0x03 })) + t:check(o5 and buffer.len(o5) == 0, "metadata block skipped") + local ok, r1, r2 = pcall(Brotli.decompress, 5 :: any) + t:check(ok and r1 == nil and r2.code == Err.ARG, "a non-buffer argument returns Err.ARG") +end + +-- maxBytes +do + local c + for _, x in Fx.cases do + if x.corpus == "english" then + c = x + break + end + end + local _, e = Brotli.decompress(c.data, nil, nil, { maxBytes = 1000 }) + t:check(e and e.code == Err.LIMIT, "maxBytes: " .. tostring(e)) + local big + for _, x in Fx.cases do + if string.find(x.name, "large", 1, true) then + big = x + break + end + end + local _, e2 = Brotli.decompress(big.data, nil, nil, { largeWindow = false }) + t:check(e2 and e2.code == Err.UNSUPPORTED, "largeWindow = false: " .. tostring(e2)) +end + +-- a corrupted stream reports CORRUPT or TRUNCATED, never a wrong success with the right CRC +do + local bad = 0 + for i, c in Fx.cases do + if i % 17 == 0 and #c.data > 20 then + local b = buffer.fromstring(c.data) + buffer.writeu8(b, #c.data // 2, bit32.bxor(buffer.readu8(b, #c.data // 2), 0x5A)) + local out = Brotli.decompress(b) + if out and Crc32.of(out) == Crc32.of(buffer.fromstring(Fx.corpora[c.corpus])) then + bad += 1 + end + end + end + t:eq(bad, 0, "corrupted streams never decode to the original") +end + +-- truncation, corruption and garbage never throw +do + local samples = {} + for i, c in Fx.cases do + if i % 11 == 0 and #c.data > 8 then + table.insert(samples, if #c.data > 20000 then string.sub(c.data, 1, 20000) else c.data) + end + end + t:fuzz("decompress", function(b: buffer) + return Brotli.decompress(b) + end, samples, { mutations = 6, garbage = 3000 }) +end + +t:done() diff --git a/tests/codecs/bzip2.luau b/tests/codecs/bzip2.luau new file mode 100644 index 0000000..71a872d --- /dev/null +++ b/tests/codecs/bzip2.luau @@ -0,0 +1,103 @@ +-- codecs/Bzip2 tests: every fixture stream (Python bz2 = libbzip2, block sizes 1..9, RLE1 run edges, block-boundary +-- runs, random / skewed data, concatenated streams with trailing garbage) decodes exactly; offsets / consumedEnd; +-- maxBytes; CRC mismatches are Err.CHECKSUM; truncations are Err.TRUNCATED; the fuzz no-throw pass. +-- Fixtures: tools/fixtures/bzip2.py. +local T = require("@tests/T") +local Bzip2 = require("@formats/codecs/Bzip2") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/bzip2") + +local t = T.suite("bzip2") + +t:eq(Bzip2.crc(buffer.fromstring("123456789")), 0xFC891918, "CRC-32/BZIP2 check value") + +local nbytes = 0 +for _, c in Fx.cases do + local want = Fx.corpora[c.corpus] + local out, consumed = Bzip2.decompress(c.data) + t:check(out ~= nil, c.name .. ": " .. tostring(consumed)) + t:check(buffer.tostring(out :: buffer) == want, c.name .. ": output differs") + if c.name ~= "multi/trailing" then + t:eq(consumed, #c.data, c.name .. ": consumedEnd") + end + nbytes += #want +end +t:note("%d fixture streams, %.1f MB decoded", #Fx.cases, nbytes / 1e6) + +local function case(name: string): any + for _, c in Fx.cases do + if c.name == name then + return c + end + end + error("no case " .. name) +end + +-- inside a bigger buffer, at an offset +do + local c = case("text/l9") + local big = buffer.create(#c.data + 20) + buffer.fill(big, 0, 0xAB) + buffer.writestring(big, 7, c.data) + local out, consumed = Bzip2.decompress(big, 7, #c.data + 5) + t:check(out and buffer.tostring(out) == Fx.corpora.text, "at an offset") + t:eq(consumed, 7 + #c.data, "consumedEnd at an offset") +end + +-- maxBytes +do + local c = case("zeros/l9") + local _, e = Bzip2.decompress(c.data, nil, nil, { maxBytes = 1000 }) + t:check(e and e.code == Err.LIMIT, "maxBytes: " .. tostring(e)) + local ok = Bzip2.decompress(c.data, nil, nil, { maxBytes = 250000 }) + t:check(ok ~= nil, "maxBytes = exact size") +end + +-- block CRC / stream CRC mismatches +do + local c = case("text/l9") + local b = buffer.fromstring(c.data) + -- block CRC sits at bytes 10..13 (after "BZh9" + 6 magic bytes) + buffer.writeu8(b, 11, bit32.bxor(buffer.readu8(b, 11), 0x10)) + local _, e = Bzip2.decompress(b) + t:check(e and e.code == Err.CHECKSUM, "block CRC mismatch: " .. tostring(e)) + local s = case("one/l9") + local b2 = buffer.fromstring(s.data) + local n = buffer.len(b2) + buffer.writeu8(b2, n - 2, bit32.bxor(buffer.readu8(b2, n - 2), 0x01)) + local _, e2 = Bzip2.decompress(b2) + t:check(e2 and (e2.code == Err.CHECKSUM or e2.code == Err.CORRUPT), "stream CRC mismatch: " .. tostring(e2)) +end + +-- truncation -> TRUNCATED, bad magic -> CORRUPT, bad args -> ARG +do + local c = case("text/l1") + for _, cut in { 3, 10, 40, #c.data // 2, #c.data - 3 } do + local _, e = Bzip2.decompress(string.sub(c.data, 1, cut)) + t:check(e and e.code == Err.TRUNCATED, "truncated at " .. cut .. ": " .. tostring(e)) + end + local _, e = Bzip2.decompress("BZx9abcdefgh") + t:check(e and e.code == Err.CORRUPT, "bad magic") + local _, e2 = Bzip2.decompress(5 :: any) + t:check(e2 and e2.code == Err.ARG, "non-buffer") + local _, e3 = Bzip2.decompress("BZh9", -1) + t:check(e3 and e3.code == Err.ARG, "bad offset") +end + +-- fuzz +do + local samples = {} + for i, c in Fx.cases do + if i % 4 == 0 and #c.data < 40000 then + table.insert(samples, c.data) + end + end + t:fuzz("decompress", function(b: buffer) + return Bzip2.decompress(b) + end, samples, { mutations = 12, garbage = 1000, keepHeader = 4 }) + t:fuzz("decompress (no header kept)", function(b: buffer) + return Bzip2.decompress(b) + end, samples, { mutations = 4, garbage = 200 }) +end + +t:done() diff --git a/tests/codecs/dct.luau b/tests/codecs/dct.luau new file mode 100644 index 0000000..0e45a54 --- /dev/null +++ b/tests/codecs/dct.luau @@ -0,0 +1,158 @@ +-- codecs/Dct tests: the islow inverse DCT against a double-precision reference (within 1 level per sample, as T.81 +-- annex A accuracy needs), forward DCT + quantiser against the reference transform (round to nearest of v / (8 q)), +-- fdct -> idct round trips at q = 1 within 1 level, edge replication of fdctQuantize, and garbage coefficients never +-- throw (outputs stay clamped). The bit-exact djpeg / cjpeg checks are in tests/image/jpeg.luau. +local T = require("@tests/T") +local Dct = require("@formats/codecs/Dct") + +local t = T.suite("dct") +local rand = T.rng(11) + +local C = {} +for u = 0, 7 do + C[u] = if u == 0 then math.sqrt(0.5) else 1 +end +local cosT = {} +for x = 0, 7 do + for u = 0, 7 do + cosT[x * 8 + u] = math.cos((2 * x + 1) * u * math.pi / 16) + end +end + +local ones = buffer.create(128) +for i = 0, 63 do + buffer.writeu16(ones, i * 2, 1) +end + +-- inverse: random sparse coefficients, compare with the float IDCT +do + local worst = 0 + for trial = 1, 300 do + local coef = buffer.create(128) + local F = {} + for i = 0, 63 do + local v = 0 + if rand(4) == 0 or i == 0 then + v = rand(512) - 256 + if i == 0 then + v = rand(2048) - 1024 + end + end + F[i] = v + buffer.writei16(coef, i * 2, v) + end + local plane = buffer.create(128) + Dct.idctBlock(coef, 0, ones, plane, 0, 8, 2, 128, 255) + for y = 0, 7 do + for x = 0, 7 do + local s = 0 + for v = 0, 7 do + for u = 0, 7 do + s += C[u] * C[v] * F[v * 8 + u] * cosT[x * 8 + u] * cosT[y * 8 + v] + end + end + local want = math.clamp(math.floor(s / 4 + 128 + 0.5), 0, 255) + local got = buffer.readu16(plane, (y * 8 + x) * 2) + worst = math.max(worst, math.abs(got - want)) + end + end + local _ = trial + end + t:check(worst <= 1, "idct within 1 of the float reference: " .. worst) + t:note("idct: worst error %d over 300 random blocks", worst) +end + +-- forward + quantiser +do + local worst = 0 + for _ = 1, 200 do + local src = buffer.create(64) + for i = 0, 63 do + buffer.writeu8(src, i, rand(256)) + end + local q = buffer.create(128) + for i = 0, 63 do + buffer.writeu16(q, i * 2, 1 + rand(40)) + end + local coef = buffer.create(128) + Dct.fdctQuantize(src, 8, 0, 0, 8, 8, q, coef, 0) + for v = 0, 7 do + for u = 0, 7 do + local s = 0 + for y = 0, 7 do + for x = 0, 7 do + s += (buffer.readu8(src, y * 8 + x) - 128) * cosT[x * 8 + u] * cosT[y * 8 + v] + end + end + s *= C[u] * C[v] / 4 + local want = s / buffer.readu16(q, (v * 8 + u) * 2) + worst = math.max(worst, math.abs(buffer.readi16(coef, (v * 8 + u) * 2) - want)) + end + end + end + t:check(worst <= 0.75, "fdct + quantise within rounding of the float reference: " .. worst) + -- round trip at q = 1 + local rt = 0 + for _ = 1, 100 do + local src = buffer.create(64) + for i = 0, 63 do + buffer.writeu8(src, i, rand(256)) + end + local coef = buffer.create(128) + Dct.fdctQuantize(src, 8, 0, 0, 8, 8, ones, coef, 0) + local plane = buffer.create(128) + Dct.idctBlock(coef, 0, ones, plane, 0, 8, 2, 128, 255) + for i = 0, 63 do + rt = math.max(rt, math.abs(buffer.readu16(plane, i * 2) - buffer.readu8(src, i))) + end + end + t:check(rt <= 1, "fdct -> idct round trip at q = 1: " .. rt) + -- edge replication: a 3x2 image is the same as its 8x8 edge-extended version + local small = T.bytes({ 10, 200, 30, 40, 50, 250 }) + local ext = buffer.create(64) + for y = 0, 7 do + for x = 0, 7 do + buffer.writeu8(ext, y * 8 + x, buffer.readu8(small, math.min(y, 1) * 3 + math.min(x, 2))) + end + end + local a, b = buffer.create(128), buffer.create(128) + Dct.fdctQuantize(small, 3, 0, 0, 3, 2, ones, a, 0) + Dct.fdctQuantize(ext, 8, 0, 0, 8, 8, ones, b, 0) + t:check(buffer.tostring(a) == buffer.tostring(b), "edge replication") +end + +-- components and garbage: clamped output, no throw +do + local coef = buffer.create(4 * 3 * 128) + for i = 0, buffer.len(coef) // 2 - 1 do + buffer.writei16(coef, i * 2, rand(65536) - 32768) + end + local q = buffer.create(128) + for i = 0, 63 do + buffer.writeu16(q, i * 2, rand(65536)) + end + for _, size in { 8, 4, 2, 1 } do + for _, prec in { { 2, 128, 255 }, { 1, 2048, 4095 } } do + local plane = buffer.create(4 * size * 3 * size * 2) + local ok = pcall(Dct.idctComponent, coef, q, 4, 3, size, plane, prec[1], prec[2], prec[3]) + t:check(ok, "idctComponent size " .. size .. " on garbage") + local inRange = true + for i = 0, buffer.len(plane) // 2 - 1 do + if buffer.readu16(plane, i * 2) > prec[3] then + inRange = false + end + end + t:check(inRange, "clamped output, size " .. size) + end + end + local samples = { string.rep("\0", 128) } + t:fuzz("idctBlock", function(b: buffer) + local cb = buffer.create(128) + buffer.copy(cb, 0, b, 0, math.min(128, buffer.len(b))) + local plane = buffer.create(128) + Dct.idctBlock(cb, 0, q, plane, 0, 8, 2, 128, 255) + return plane + end, samples, { garbage = 50 }) +end + +t:done() diff --git a/tests/codecs/json.luau b/tests/codecs/json.luau new file mode 100644 index 0000000..dacb399 --- /dev/null +++ b/tests/codecs/json.luau @@ -0,0 +1,210 @@ +-- codecs/Json tests: the JSONTestSuite parsing corpus (y_ must parse to Python's value, n_ must fail, i_ must not +-- throw), Python json.dumps output in four styles parsed and reproduced byte for byte (compact sorted, ordered, +-- indent 2, ensure_ascii), events / lines / decodeAt / writer, options, error codes, and the fuzz pass. +-- Fixtures: tools/fixtures/json.py. +local T = require("@tests/T") +local Json = require("@formats/codecs/Json") +local Types = require("@formats/Types") +local Err = require("@formats/core/Err") +local Canon = require("@tests/data/Canon") +local Suite = require("@tests/gen/json_suite") +local Corpus = require("@tests/gen/json_corpus") + +local t = T.suite("json") + +-- events() rebuilt into a value (checks the pull tokenizer agrees with decode) +local function fromEvents(s: string): (any, any) + local stack, keys = {}, {} + local top: any = nil + local key: any = nil + local function add(v: any) + local cur = stack[#stack] + if cur == nil then + top = v + elseif keys[#stack] ~= false then + cur[key] = v + else + table.insert(cur, v) + end + end + for ev, v in Json.events(s) do + if ev == "error" then + return nil, v + elseif ev == "object" or ev == "array" then + local tbl = if ev == "object" then Types.object() else {} + add(tbl) + table.insert(stack, tbl) + keys[#stack] = if ev == "object" then true else false + elseif ev == "endObject" or ev == "endArray" then + keys[#stack] = nil + table.remove(stack) + elseif ev == "key" then + key = v + else + add(v) + end + end + return top, nil +end + +-- 1. JSONTestSuite +local counts = { y = 0, n = 0, i = 0, iok = 0 } +for _, c in Suite do + local v, err = Json.decode(c.data) + local ev, everr = fromEvents(c.data) + if c.expect == "y" then + t:check(v ~= nil, c.name .. ": parses (" .. tostring(err) .. ")") + t:eq(Canon.of(v), c.canon, c.name .. ": value") + t:check(ev ~= nil, c.name .. ": events parse (" .. tostring(everr) .. ")") + t:eq(Canon.of(ev), c.canon, c.name .. ": events value") + -- and our output reads back the same + local s = Json.encode(v) + t:check(s ~= nil, c.name .. ": encodes") + t:eq(Canon.of(Json.decode(s :: string)), c.canon, c.name .. ": round trip") + elseif c.expect == "n" then + t:check(v == nil and Err.is(err), c.name .. ": rejected") + t:check(ev == nil, c.name .. ": events reject") + else + counts.iok += if v ~= nil then 1 else 0 + end + counts[c.expect] += 1 +end +t:note("JSONTestSuite: %d y_ accepted, %d n_ rejected, %d of %d i_ accepted", counts.y, counts.n, counts.iok, counts.i) + +-- 2. Python's json.dumps output: parse, compare, re-encode byte for byte +for i, c in Corpus do + local v, err = Json.decode(c.compact) + t:check(v ~= nil, "corpus " .. i .. ": " .. tostring(err)) + t:eq(Canon.of(v), c.canon, "corpus " .. i .. ": value") + t:eq(Json.encode(v), c.compact, "corpus " .. i .. ": compact text") + t:eq(Json.encode(v, { indent = 2 }), c.pretty, "corpus " .. i .. ": indent 2 text") + t:eq(Json.encode(v, { ascii = true }), c.ascii, "corpus " .. i .. ": ensure_ascii text") + local o = Json.decode(c.ordered, { ordered = true }) + t:eq(Json.encode(o), c.ordered, "corpus " .. i .. ": ordered text") + t:eq(Canon.of(Json.decode(c.ascii)), c.canon, "corpus " .. i .. ": ascii parse") + t:eq(Canon.of(Json.decode(c.pretty)), c.canon, "corpus " .. i .. ": pretty parse") +end + +-- 3. options and API +do + local v = Json.decode('[12345678901234567890, -9007199254740993, 9007199254740991, 1.5e300]', { bigInts = "string" }) + t:eq(v[1], "12345678901234567890", "bigInts string") + t:eq(v[2], "-9007199254740993", "bigInts negative") + t:eq(v[3], 9007199254740991, "2^53 - 1 stays a number") + t:eq(v[4], 1.5e300, "floats stay numbers") + t:eq(Json.decode("[null]", { null = false })[1], false, "opts.null") + t:eq(Json.decode("null"), Types.null, "top-level null") + t:eq(Json.decode("\239\187\191[1]")[1], 1, "BOM skipped") + t:eq(Json.decode(buffer.fromstring(" 7 ")), 7, "buffer input") + local e = Json.decode('{"b":1,"a":{},"c":[]}') + t:eq(Json.encode(e), '{"a":{},"b":1,"c":[]}', "empty object stays an object") + local o = Json.decode('{"z":1,"a":2,"m":{"y":1,"b":2}}', { ordered = true }) + t:eq(Json.encode(o), '{"z":1,"a":2,"m":{"y":1,"b":2}}', "ordered keys") + Types.set(o, "b", 3) + o.a = nil + t:eq(Json.encode(o), '{"z":1,"m":{"y":1,"b":2},"b":3}', "ordered set / remove") + t:eq(Json.encode({}, { emptyTable = "object" }), "{}", "emptyTable object") + t:eq(Json.encode({ [1] = "a", [3] = "c" }), '{"1":"a","3":"c"}', "sparse array -> object") + t:eq(Json.encode({ 1, 2, x = 1 }), '{"1":1,"2":2,"x":1}', "mixed table -> object") + t:eq(Json.encode("a/b", { escapeSlash = true }), '"a\\/b"', "escapeSlash") + t:eq(Json.encode(0 / 0, { nan = "null" }), "null", "nan null") + local _, ne = Json.encode(math.huge) + t:eq(ne and ne.code, Err.ARG, "inf is an error") + local cyc = {} + cyc.self = cyc + local _, ce = Json.encode(cyc) + t:eq(ce and ce.code, Err.ARG, "cycle is an error") + local _, fe = Json.encode({ f = print }) + t:eq(fe and fe.code, Err.ARG, "function is an error") + t:eq(Json.encode(Types.Date.parse("1979-05-27T07:32:00Z")), '"1979-05-27T07:32:00Z"', "dates as strings") + for _, x in { 0.1, 1 / 3, -2.5e-8, 1e300, 123456789012345, 2 ^ 53, 5e-324, 1.7976931348623157e308 } do + t:eq(Json.decode(Json.encode(x) :: string), x, "number round trip " .. string.format("%.17g", x)) + end +end + +-- 4. streaming: lines, decodeAt, writer +do + local got = {} + for _, v in Json.lines('{"a":1}\n[2]\n"x"\n 3 ') do + table.insert(got, (Json.encode(v))) + end + t:eq(table.concat(got, "|"), '{"a":1}|[2]|"x"|3', "lines") + local n, last = 0, nil + for _, v, e in Json.lines("1 2 [") do + if e then + last = e + else + n += 1 + end + end + t:eq(n, 2, "lines stop at the bad value") + t:eq(last and last.code, Err.TRUNCATED, "lines report the error") + local v, p = Json.decodeAt("[1] [2]", 1) + t:eq(v[1], 1, "decodeAt value") + t:eq(p, 4, "decodeAt next") + t:eq(Json.decodeAt(" ", 1), nil, "decodeAt at the end") + + local w = Json.writer({ indent = 2 }) + w:beginObject():key("a"):value({ 1, 2 }):key("b"):beginArray():value("x"):beginObject():endObject():endArray():endObject() + local s = w:tostring() + t:eq(s, Json.encode(Json.decode('{"a":[1,2],"b":["x",{}]}', { ordered = true }), { indent = 2 }), "writer pretty") + local w2 = Json.writer() + w2:beginArray() + local parts = {} + for i = 1, 5 do + w2:value(i) + table.insert(parts, w2:flush()) + end + w2:endArray() + table.insert(parts, w2:flush()) + t:eq(table.concat(parts), "[1,2,3,4,5]", "writer flush chunks") + t:eq(w2:tostring(), "[1,2,3,4,5]", "writer tostring after flushes") + local w3 = Json.writer() + w3:beginArray():key("x") + t:check(w3.err ~= nil, "writer: key in array") + local w4 = Json.writer() + w4:beginObject():value(1) + t:check(w4.err ~= nil, "writer: value without key") + local w5 = Json.writer() + w5:beginObject() + t:check(w5:tostring() == nil, "writer: unclosed") +end + +-- 5. errors +local function code(s: string, opts: any?): string? + local _, e = Json.decode(s, opts) + return e and e.code +end +t:eq(code('{"a":'), Err.TRUNCATED, "truncated object") +t:eq(code('"abc'), Err.TRUNCATED, "truncated string") +t:eq(code("[1 2]"), Err.CORRUPT, "missing comma") +t:eq(code("[1] x"), Err.CORRUPT, "trailing data") +t:eq(code(string.rep("[", 50) .. string.rep("]", 50), { maxDepth = 10 }), Err.LIMIT, "maxDepth") +t:eq(code(string.rep("[", 100000)), Err.LIMIT, "100000 opening brackets") +t:eq(code(""), Err.TRUNCATED, "empty input") +local _, ae = Json.decode(42 :: any) +t:eq(ae and ae.code, Err.ARG, "bad argument") +do + local _, e = Json.decode('{"a": tru}') + t:eq(e and e.offset, 6, "error offset") +end + +-- 6. fuzz +local samples = {} +for i = 1, 40 do + table.insert(samples, Corpus[i].compact) +end +for _, c in Suite do + if #samples < 120 and c.expect == "y" and #c.data < 200 then + table.insert(samples, c.data) + end +end +t:fuzz("decode", function(b: buffer) + return Json.decode(b) +end, samples) +t:fuzz("events", function(b: buffer) + for _ in Json.events(b) do + end + return nil +end, samples, { garbage = 50 }) +t:done() diff --git a/tests/codecs/lzma.luau b/tests/codecs/lzma.luau new file mode 100644 index 0000000..669b265 --- /dev/null +++ b/tests/codecs/lzma.luau @@ -0,0 +1,142 @@ +-- codecs/Lzma tests: every fixture (liblzma through Python's lzma module and the xz CLI: presets 0-9 and -e, lc / lp / +-- pb variants, raw LZMA1 / LZMA2, .lzma files, xz with every check type, BCJ and delta filters, multiple blocks, +-- multiple streams and stream padding) decodes to its corpus; consumed offsets; checksum / size / truncation errors; +-- maxBytes; the fuzz no-throw pass. Fixtures: tools/fixtures/lzma.py. +local T = require("@tests/T") +local Lzma = require("@formats/codecs/Lzma") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/lzma") + +local t = T.suite("lzma") + +local function decode(c: any, b: buffer, opts: any?): (buffer?, any) + if c.kind == "raw" then + return Lzma.lzma(b, 0, nil, c.props, c.size, opts) + elseif c.kind == "raw2" then + return Lzma.lzma2(b, 0, nil, nil, nil, opts) + elseif c.kind == "alone" then + return Lzma.alone(b, 0, nil, opts) + end + return Lzma.xz(b, 0, nil, opts) +end + +local nbytes = 0 +for _, c in Fx.cases do + local want = Fx.corpora[c.corpus] + local b = buffer.fromstring(c.data) + local out, res = decode(c, b) + t:check(out ~= nil, c.name .. ": " .. tostring(res)) + t:check(buffer.tostring(out :: buffer) == want, c.name .. ": output differs") + if c.kind ~= "raw" then + t:eq(res, #c.data, c.name .. ": consumed") + end + nbytes += #want +end +t:note("%d fixture streams, %.1f MB decoded", #Fx.cases, nbytes / 1e6) + +-- at an offset inside a bigger buffer, with trailing bytes +do + for _, c in Fx.cases do + if c.kind == "xz" and c.name == "text/xz-6" then + local big = buffer.create(#c.data + 11) + buffer.fill(big, 0, 0xAB) + buffer.writestring(big, 3, c.data) + local out, res = Lzma.xz(big, 3, #c.data) + t:check(out and buffer.tostring(out) == Fx.corpora.text and res == 3 + #c.data, "xz at an offset") + end + end +end + +-- errors +do + local xz, xzc + for _, c in Fx.cases do + if c.name == "text/xz-check-crc32" then + xz = c + elseif c.name == "text/xz-6" then + xzc = c + end + end + -- the check field: the last bytes before the index; flip a data bit near the end of the block instead + local b = buffer.fromstring(xzc.data) + local n = buffer.len(b) + -- footer magic + buffer.writeu8(b, n - 1, 0) + local _, e1 = Lzma.xz(b) + t:check(e1 and (e1.code == Err.CORRUPT or e1.code == Err.CHECKSUM), "bad footer: " .. tostring(e1)) + -- the stream header CRC + local b2 = buffer.fromstring(xz.data) + buffer.writeu8(b2, 8, bit32.bxor(buffer.readu8(b2, 8), 1)) + local _, e2 = Lzma.xz(b2) + t:check(e2 and e2.code == Err.CHECKSUM, "header crc: " .. tostring(e2)) + -- the block check (CRC-32 / CRC-64): flip a byte of the check field (found from the index: the 4 / 8 bytes before + -- the index indicator, which follows the block padding) + for _, c in { xz, xzc } do + local b3 = buffer.fromstring(c.data) + local n3 = buffer.len(b3) + local backward = (buffer.readu32(b3, n3 - 8) + 1) * 4 + local indexAt = n3 - 12 - backward + buffer.writeu8(b3, indexAt - 1, bit32.bxor(buffer.readu8(b3, indexAt - 1), 0x10)) + local _, e3 = Lzma.xz(b3) + t:check(e3 and e3.code == Err.CHECKSUM, c.name .. ": block check: " .. tostring(e3)) + end + -- truncations are TRUNCATED or CORRUPT, never a throw + local _, e4 = Lzma.xz(buffer.fromstring(string.sub(xzc.data, 1, #xzc.data // 2))) + t:check(e4 and e4.code == Err.TRUNCATED, "truncated xz: " .. tostring(e4)) + -- maxBytes + local _, e5 = Lzma.xz(xzc.data, nil, nil, { maxBytes = 1000 }) + t:check(e5 and e5.code == Err.LIMIT, "maxBytes: " .. tostring(e5)) + local ok, r1, r2 = pcall(Lzma.xz, 5 :: any) + t:check(ok and r1 == nil and r2.code == Err.ARG, "a non-buffer argument returns Err.ARG") + local _, e6 = Lzma.lzma("\0\0\0\0\0", 0, nil, "\255") + t:check(e6 and e6.code == Err.CORRUPT, "bad props byte: " .. tostring(e6)) +end + +-- raw LZMA with the size known: decoding stops at the size even without an end marker +do + for _, c in Fx.cases do + if c.kind == "raw" and #Fx.corpora[c.corpus] > 1000 then + local want = Fx.corpora[c.corpus] + local out = Lzma.lzma(c.data, 0, nil, { lc = 3, lp = 0, pb = 2 }, nil) + if c.name == c.corpus .. "/raw-lc3-lp0-pb2" then + t:check(out and buffer.tostring(out) == want, c.name .. ": table props, end marker") + end + local part = Lzma.lzma(c.data, 0, nil, c.props, 500) + t:check(part and buffer.tostring(part) == string.sub(want, 1, 500), c.name .. ": a prefix by size") + end + end +end + +-- fuzz +do + local samples = {} + for i, c in Fx.cases do + if i % 7 == 0 and #c.data > 16 and #c.data < 40000 then + table.insert(samples, c) + end + end + local xs, as, rs = {}, {}, {} + for _, c in samples do + if c.kind == "xz" then + table.insert(xs, c.data) + elseif c.kind == "alone" then + table.insert(as, c.data) + else + table.insert(rs, c.data) + end + end + t:fuzz("xz", function(b: buffer) + return Lzma.xz(b, 0, nil, { maxBytes = 1 * 2 ^ 20 }) + end, xs, { mutations = 6, garbage = 300 }) + t:fuzz("alone", function(b: buffer) + return Lzma.alone(b, 0, nil, { maxBytes = 1 * 2 ^ 20 }) + end, as, { mutations = 6, garbage = 300 }) + t:fuzz("lzma2", function(b: buffer) + return Lzma.lzma2(b, 0, nil, nil, nil, { maxBytes = 1 * 2 ^ 20 }) + end, rs, { mutations = 4, garbage = 1000 }) + t:fuzz("lzma", function(b: buffer) + return Lzma.lzma(b, 0, nil, "\93", nil, { maxBytes = 1 * 2 ^ 20 }) + end, rs, { mutations = 2, garbage = 1000 }) +end + +t:done() diff --git a/tests/codecs/lzw.luau b/tests/codecs/lzw.luau new file mode 100644 index 0000000..04fe064 --- /dev/null +++ b/tests/codecs/lzw.luau @@ -0,0 +1,119 @@ +-- codecs/Lzw tests: GIF (LSB) and TIFF (MSB, early change) code streams from Pillow / libtiff decode to their data; +-- our encoder round-trips random and structured data at every GIF minimum code size and through table resets; the +-- output limit, truncated and corrupt streams; the fuzz no-throw pass. Fixtures: tools/fixtures/lzw.py. +local T = require("@tests/T") +local Lzw = require("@formats/codecs/Lzw") +local Fx = require("@tests/gen/lzw") + +local t = T.suite("lzw") + +local function dec(codes: buffer, n: number, variant: string, min: number?): (string, number, string?) + local out = buffer.create(n) + local got, err = Lzw.decode(codes, 0, buffer.len(codes), out, 0, n, variant, min) + return buffer.tostring(out), got, err +end + +-- reference streams +for _, c in Fx.gif do + local s, n, err = dec(buffer.fromstring(c.codes), #c.data, "gif", c.min) + t:check(err == nil, "gif " .. c.name .. ": " .. tostring(err)) + t:eq(n, #c.data, "gif " .. c.name .. ": length") + t:check(s == c.data, "gif " .. c.name .. ": data") +end +for _, c in Fx.tiff do + local s, n, err = dec(buffer.fromstring(c.codes), #c.data, "tiff") + t:check(err == nil, "tiff " .. c.name .. ": " .. tostring(err)) + t:eq(n, #c.data, "tiff " .. c.name .. ": length") + t:check(s == c.data, "tiff " .. c.name .. ": data") +end +t:note("%d GIF and %d TIFF reference streams decode", #Fx.gif, #Fx.tiff) + +-- round trips +local rand = T.rng(3) +local function data(n: number, kind: number, max: number): buffer + local b = buffer.create(n) + for i = 0, n - 1 do + local v + if kind == 0 then + v = rand(max) + elseif kind == 1 then + v = (i // 7) % max + else + v = if rand(10) == 0 then rand(max) else (i % 13) % max + end + buffer.writeu8(b, i, v) + end + return b +end +local trips = 0 +for _, n in { 0, 1, 2, 3, 100, 5000, 70000 } do + for kind = 0, 2 do + for min = 2, 8 do + local d = data(n, kind, 2 ^ min) + local codes = Lzw.encode(d, 0, n, "gif", min) + local s, got, err = dec(codes, n, "gif", min) + t:check(err == nil and got == n and s == buffer.tostring(d), string.format("gif round trip n=%d kind=%d min=%d: %s", n, kind, min, tostring(err))) + trips += 1 + end + local d = data(n, kind, 256) + local codes = Lzw.encode(d, 0, n, "tiff") + local s, got, err = dec(codes, n, "tiff") + t:check(err == nil and got == n and s == buffer.tostring(d), string.format("tiff round trip n=%d kind=%d: %s", n, kind, tostring(err))) + trips += 1 + end +end +t:note("%d round trips", trips) + +-- compression actually happens; a range inside a bigger buffer +do + local d = buffer.create(10000) + local codes = Lzw.encode(d, 0, 10000, "tiff") + t:check(buffer.len(codes) < 400, "zeros compress: " .. buffer.len(codes)) + local big = data(300, 1, 256) + local codes2 = Lzw.encode(big, 100, 100, "gif", 8) + local out = buffer.create(120) + local n = Lzw.decode(codes2, 0, buffer.len(codes2), out, 10, 100, "gif", 8) + t:eq(n, 100, "sub-range length") + t:check(buffer.readstring(out, 10, 100) == buffer.readstring(big, 100, 100), "sub-range data") +end + +-- limits, truncation, corruption +do + local d = data(1000, 2, 16) + local codes = Lzw.encode(d, 0, 1000, "gif", 4) + local s, n, err = dec(codes, 500, "gif", 4) + t:check(n == 500 and err == nil and s == buffer.readstring(d, 0, 500), "output limit") + local cut = buffer.create(buffer.len(codes) // 2) + buffer.copy(cut, 0, codes, 0, buffer.len(cut)) + local _, n2, err2 = dec(cut, 1000, "gif", 4) + t:check(err2 == "truncated" and n2 > 0 and n2 < 1000, "truncated: " .. tostring(err2)) + local bad = buffer.fromstring("\255\255\255\255") + local _, _, err3 = dec(bad, 100, "gif", 2) + t:check(err3 == "corrupt", "corrupt: " .. tostring(err3)) + local _, _, err4 = dec(codes, 100, "gif", 0) + t:check(err4 == "corrupt", "bad min code size") +end + +-- fuzz +do + local samples = {} + for i, c in Fx.gif do + if i % 2 == 1 then + table.insert(samples, c.codes) + end + end + for i, c in Fx.tiff do + if i % 2 == 0 then + table.insert(samples, c.codes) + end + end + local out = buffer.create(100000) + t:fuzz("decode gif", function(b: buffer) + return Lzw.decode(b, 0, buffer.len(b), out, 0, 100000, "gif", 8) + end, samples) + t:fuzz("decode tiff", function(b: buffer) + return Lzw.decode(b, 0, buffer.len(b), out, 0, 100000, "tiff") + end, samples) +end + +t:done() diff --git a/tests/codecs/quantize.luau b/tests/codecs/quantize.luau new file mode 100644 index 0000000..7569e55 --- /dev/null +++ b/tests/codecs/quantize.luau @@ -0,0 +1,135 @@ +-- codecs/Quantize tests: palette size bounds for every method and colour budget, the exact (lossless) palette at +-- <= maxColors colours, transparency handling, PSNR of quantized images above thresholds, determinism of both +-- methods and of Floyd-Steinberg dithering (the same CRC on both runtimes), bad arguments, and a no-throw pass. +local T = require("@tests/T") +local Quantize = require("@formats/codecs/Quantize") +local Crc32 = require("@formats/core/Crc32") + +local t = T.suite("quantize") +local rand = T.rng(5) + +local function photo(w: number, h: number): buffer + local px = buffer.create(w * h * 4) + for i = 0, w * h - 1 do + local x, y = i % w, i // w + local r = (x * 255) // (w - 1) + local g = (y * 255) // (h - 1) + local b = math.floor(128 + 100 * math.sin(x * 0.11) * math.cos(y * 0.07)) + rand(9) + buffer.writeu32(px, i * 4, r + g * 256 + math.clamp(b, 0, 255) * 65536 + 0xFF000000) + end + return px +end + +local function render(idx: buffer, pal: { { number } }, n: number): buffer + local out = buffer.create(n * 4) + for i = 0, n - 1 do + local c = pal[buffer.readu8(idx, i) + 1] + buffer.writeu32(out, i * 4, c[1] + c[2] * 256 + c[3] * 65536 + 0xFF000000) + end + return out +end + +local function psnr(a: buffer, b: buffer): number + local se, n = 0, 0 + for o = 0, buffer.len(a) - 4, 4 do + for k = 0, 2 do + local d = buffer.readu8(a, o + k) - buffer.readu8(b, o + k) + se += d * d + n += 1 + end + end + return if se == 0 then 99 else 10 * math.log10(255 * 255 * n / se) +end + +local W, H = 128, 96 +local px = photo(W, H) +-- palette bounds and quality +local MIN_PSNR = { [256] = 30, [64] = 24, [16] = 17, [2] = 10 } +for _, method in { "mediancut", "octree" } do + for _, k in { 2, 16, 64, 256 } do + local pal, exact = Quantize.palette(px, W, H, k, { method = method }) + t:check(#pal >= 1 and #pal <= k, string.format("%s %d: palette size %d", method, k, #pal)) + t:check(not exact, method .. ": not exact") + for _, c in pal do + t:check(#c == 4 and c[4] == 255 and c[1] % 1 == 0 and c[1] >= 0 and c[1] <= 255, "palette entries") + end + for _, dither in { false, true } do + local idx = Quantize.map(px, W, H, pal, { dither = dither }) + t:eq(buffer.len(idx), W * H, "index buffer size") + local p = psnr(render(idx, pal, W * H), px) + local want = MIN_PSNR[k] - (if dither then 4 else 0) + t:check(p > want, string.format("%s %d dither=%s: PSNR %.1f > %d", method, k, tostring(dither), p, want)) + if k == 256 or k == 16 then + t:note("%-9s %3d colours dither=%-5s PSNR %.1f dB, crc %08x", method, k, tostring(dither), p, Crc32.of(idx)) + end + end + end +end + +-- exact palettes: lossless +do + local n = 50 * 40 + local b = buffer.create(n * 4) + for i = 0, n - 1 do + local k = (i * 7 + i // 50) % 200 + buffer.writeu32(b, i * 4, (k * 3) % 256 + ((k * 11) % 256) * 256 + k * 65536 + 0xFF000000) + end + local pal, exact = Quantize.palette(b, 50, 40, 256) + t:check(exact and #pal == 200, "exact palette of 200 colours: " .. #pal) + local idx = Quantize.map(b, 50, 40, pal, { dither = true }) + t:check(buffer.tostring(render(idx, pal, n)) == buffer.tostring(b), "exact palette maps losslessly (dither too)") + local pal2, exact2 = Quantize.palette(b, 50, 40, 199) + t:check(not exact2 and #pal2 <= 199, "199 colours is not exact") + local i3, p3, e3 = Quantize.quantize(b, 50, 40, 256, { dither = true }) + t:check(e3 and #p3 == 200 and buffer.tostring(render(i3, p3, n)) == buffer.tostring(b), "quantize() exact") +end + +-- transparency +do + local b = buffer.create(16 * 4) + for i = 0, 15 do + buffer.writeu32(b, i * 4, if i % 3 == 0 then 0x10FFFFFF else 0xFF0000FF + i * 256) + end + local pal, exact = Quantize.palette(b, 4, 4, 255) + t:check(exact and #pal == 10, "transparent pixels are not in the palette") + table.insert(pal, { 0, 0, 0, 0 }) + local idx = Quantize.map(b, 4, 4, pal, { transparentIndex = #pal - 1, dither = true }) + for i = 0, 15 do + local v = buffer.readu8(idx, i) + t:check((i % 3 == 0) == (v == #pal - 1), "transparent index " .. i) + end +end + +-- determinism (also across runtimes: these CRCs are pinned) +do + local pal = Quantize.palette(px, W, H, 64, { method = "mediancut" }) + local a = Crc32.of(Quantize.map(px, W, H, pal, { dither = true })) + local pal2 = Quantize.palette(px, W, H, 64, { method = "mediancut" }) + t:eq(Crc32.of(Quantize.map(px, W, H, pal2, { dither = true })), a, "mediancut + dither deterministic") + t:eq(a, 0x50c4e466, "mediancut 64 + dither: the pinned CRC (the same on both runtimes)") + local o1 = Quantize.palette(px, W, H, 37, { method = "octree" }) + local o2 = Quantize.palette(px, W, H, 37, { method = "octree" }) + t:check(#o1 == #o2 and o1[#o1][1] == o2[#o2][1], "octree deterministic") +end + +-- bad arguments never throw +do + t:eq(#Quantize.palette(nil :: any, 1, 1, 4), 0, "nil pixels") + t:eq(#Quantize.palette(buffer.create(3), 1, 1, 4), 0, "short buffer") + t:eq(buffer.len(Quantize.map(px, W, H, {})), W * H, "empty palette") + t:eq(buffer.len(Quantize.map(buffer.create(1), 2, 2, { { 1, 2, 3, 255 } })), 0, "short buffer map") + local ok = pcall(function() + for i = 1, 20 do + local w, h = 1 + rand(20), 1 + rand(20) + local b = buffer.create(w * h * 4) + for k = 0, w * h * 4 - 1 do + buffer.writeu8(b, k, rand(256)) + end + local pal = Quantize.palette(b, w, h, 1 + rand(256), { method = if i % 2 == 0 then "octree" else "mediancut" }) + Quantize.map(b, w, h, pal, { dither = i % 3 == 0, transparentIndex = if i % 4 == 0 then 0 else nil }) + end + end) + t:check(ok, "random images never throw") +end + +t:done() diff --git a/tests/codecs/raster.luau b/tests/codecs/raster.luau new file mode 100644 index 0000000..8103a25 --- /dev/null +++ b/tests/codecs/raster.luau @@ -0,0 +1,259 @@ +-- codecs/Raster tests: exact coverage of axis-aligned rectangles at fractional positions; areas of circles; random +-- polygons and curves under random transforms against an independent 12 x 12 supersampled winding-number reference +-- (both fill rules); clipping, the stroker (width, caps, joins against analytic areas), fill() compositing and paint +-- functions; malformed paths never throw. Glyph rendering against FreeType is in tests/font/ttf.luau. +local T = require("@tests/T") +local R = require("@formats/codecs/Raster") +local Types = require("@formats/Types") + +local t = T.suite("raster") + +local function sum(m: any): number + if not m then + return 0 + end + local s = 0 + for i = 0, m.width * m.height - 1 do + s += buffer.readu8(m.coverage, i) + end + return s / 255 +end + +local function at(m: any, x: number, y: number): number + local i, j = x - m.x, y - m.y + if i < 0 or j < 0 or i >= m.width or j >= m.height then + return 0 + end + return buffer.readu8(m.coverage, j * m.width + i) +end + +-- 1. rectangles: exact per-pixel coverage +do + local p = R.path():rect(1.25, 2.5, 3.5, 2) + local m = R.mask(p) :: any + t:check(m, "rect mask") + t:eq(m.x, 1, "rect x") + t:eq(m.y, 2, "rect y") + t:eq(m.width, 4, "rect width") + t:eq(m.height, 3, "rect height") + -- row 2 covers y 2.5..3 (half), columns: 1 covers 0.75, 2-3 full, 4 covers 0.75 + t:eq(at(m, 1, 2), math.floor(0.75 * 0.5 * 255 + 0.5), "corner pixel") + t:eq(at(m, 2, 2), math.floor(0.5 * 255 + 0.5), "top edge pixel") + t:eq(at(m, 2, 3), 255, "interior pixel") + t:eq(at(m, 4, 3), math.floor(0.75 * 255 + 0.5), "right edge pixel") + t:check(math.abs(sum(m) - 7) < 0.02, "rect area 7: " .. sum(m)) + -- reversed orientation gives the same coverage + local q = R.path():moveTo(1.25, 2.5):lineTo(1.25, 4.5):lineTo(4.75, 4.5):lineTo(4.75, 2.5):close() + t:check(math.abs(sum(R.mask(q)) - 7) < 0.02, "reversed rect") +end + +-- 2. circles: area pi r^2 (cubic approximation error ~ 2.7e-4 r) +for _, r in { 3, 10.5, 40 } do + local m = R.mask(R.path():ellipse(50.3, 50.7, r, r)) + local a = sum(m) + t:check(math.abs(a - math.pi * r * r) < 0.01 * math.pi * r * r + 1, string.format("circle r=%g area %.2f", r, a)) +end + +-- 3. random paths against a supersampled winding reference +local function wind(polys: { { number } }, px: number, py: number): number + local w = 0 + for _, poly in polys do + local n = #poly + local x0, y0 = poly[n - 1], poly[n] + for i = 1, n - 1, 2 do + local x1, y1 = poly[i], poly[i + 1] + if y0 <= py then + if y1 > py and (x1 - x0) * (py - y0) - (px - x0) * (y1 - y0) > 0 then + w += 1 + end + elseif y1 <= py and (x1 - x0) * (py - y0) - (px - x0) * (y1 - y0) < 0 then + w -= 1 + end + x0, y0 = x1, y1 + end + end + return w +end + +local rand = T.rng(7) +local function rf(a: number, b: number): number + return a + (b - a) * rand(100000) / 100000 +end + +local worst, total, count = 0, 0, 0 +for case = 1, 24 do + local p = R.path() + for _ = 1, 1 + rand(3) do + p:moveTo(rf(0, 28), rf(0, 28)) + for _ = 1, 2 + rand(5) do + local k = rand(3) + if k == 0 then + p:lineTo(rf(0, 28), rf(0, 28)) + elseif k == 1 then + p:quadTo(rf(0, 28), rf(0, 28), rf(0, 28), rf(0, 28)) + else + p:cubicTo(rf(0, 28), rf(0, 28), rf(0, 28), rf(0, 28), rf(0, 28), rf(0, 28)) + end + end + p:close() + end + local ang = rf(0, 6.28) + local tr = R.multiply(R.translate(rf(-5, 5), rf(-5, 5)), R.multiply(R.rotate(ang), R.scale(rf(0.5, 1.2), rf(0.5, 1.2)))) + local rule = if case % 2 == 0 then "evenodd" else "nonzero" + local clip = { 0, 0, 32, 32 } + local m = R.mask(p, { transform = tr, rule = rule :: any, clip = clip, tolerance = 0.05 }) + local polys = R.flatten(p, tr, 0.01) + local err, n, mx = 0, 0, 0 + for y = 0, 31 do + for x = 0, 31 do + local inside = 0 + for sy = 0, 11 do + for sx = 0, 11 do + local w = wind(polys, x + (sx + 0.5) / 12, y + (sy + 0.5) / 12) + if (rule == "nonzero" and w ~= 0) or (rule == "evenodd" and w % 2 == 1) then + inside += 1 + end + end + end + local want = inside / 144 + local got = if m then at(m, x, y) / 255 else 0 + local d = math.abs(got - want) + err += d + n += 1 + if d > mx then + mx = d + end + end + end + total += err + count += n + worst = math.max(worst, err / n) + -- the area rules approximate where edges of opposite winding meet inside one pixel; on average they agree + t:check(err / n < 0.015, string.format("case %d (%s): mean abs error %.4f (max %.3f)", case, rule, err / n, mx)) +end +t:note("random paths: mean abs coverage error %.4f (worst case mean %.4f) vs 12x12 supersampling", total / count, worst) + +-- 4. even-odd vs nonzero on two nested squares of the same orientation +do + local p = R.path():rect(0, 0, 10, 10):rect(3, 3, 4, 4) + t:check(math.abs(sum(R.mask(p)) - 100) < 0.01, "nonzero fills the hole") + t:check(math.abs(sum(R.mask(p, { rule = "evenodd" })) - 84) < 0.01, "evenodd leaves the hole") + -- opposite orientation: a hole under both rules + local q = R.path():rect(0, 0, 10, 10):moveTo(3, 3):lineTo(3, 7):lineTo(7, 7):lineTo(7, 3):close() + t:check(math.abs(sum(R.mask(q)) - 84) < 0.01, "nonzero hole with opposite winding") +end + +-- 5. clipping: a shape larger than the clip, partly outside on every side +do + local m = R.mask(R.path():rect(-20.5, -3.25, 100, 50), { clip = { 0, 0, 16, 8 } }) :: any + t:check(m and m.x == 0 and m.y == 0 and m.width == 16 and m.height == 8, "clipped bounds") + t:check(math.abs(sum(m) - 128) < 0.01, "clipped area " .. sum(m)) + local m2 = R.mask(R.path():moveTo(-50, 4):lineTo(60, 4.5):lineTo(60, 6):lineTo(-50, 5):close(), { clip = { 0, 0, 10, 10 } }) + t:check(m2 ~= nil, "a sliver crossing the clip") + t:check(R.mask(R.path():rect(20, 20, 5, 5), { clip = { 0, 0, 10, 10 } }) == nil, "outside the clip is empty") +end + +-- 6. strokes: a line of length L and width w covers L*w (butt), L*w + w^2 (square), L*w + pi w^2/4 (round) +do + local line = R.path():moveTo(5, 10):lineTo(35, 10) + local a = sum(R.mask(R.stroke(line, { width = 4 }))) + t:check(math.abs(a - 120) < 0.05, "butt stroke area " .. a) + a = sum(R.mask(R.stroke(line, { width = 4, cap = "square" }))) + t:check(math.abs(a - 136) < 0.05, "square cap area " .. a) + a = sum(R.mask(R.stroke(line, { width = 4, cap = "round", tolerance = 0.01 }))) + t:check(math.abs(a - (120 + math.pi * 4)) < 0.3, "round cap area " .. a) + -- a closed square outline of side 20, width 2, miter joins: outer 22^2 - inner 18^2 + local sq = R.path():rect(10, 10, 20, 20) + a = sum(R.mask(R.stroke(sq, { width = 2 }))) + t:check(math.abs(a - (484 - 324)) < 0.1, "mitered square outline " .. a) + a = sum(R.mask(R.stroke(sq, { width = 2, join = "bevel" }))) + t:check(math.abs(a - (160 - 4 * 0.5)) < 0.1, "bevelled square outline " .. a) + a = sum(R.mask(R.stroke(sq, { width = 2, join = "round", tolerance = 0.01 }))) + t:check(math.abs(a - (160 - 4 * (1 - math.pi / 4))) < 0.15, "rounded square outline " .. a) + -- a sharp zig-zag past the miter limit falls back to bevels; still covered without holes + local zig = R.path():moveTo(0, 0):lineTo(20, 2):lineTo(0, 4) + t:check(sum(R.mask(R.stroke(zig, { width = 1, miterLimit = 4 }))) > 30, "zig-zag stroke") + -- a curve stroke: a circle outline of radius 10, width 1: area 2 pi r w + a = sum(R.mask(R.stroke(R.path():ellipse(20, 20, 10, 10), { width = 1, join = "round", tolerance = 0.01 }))) + t:check(math.abs(a - 2 * math.pi * 10) < 1, "circle outline " .. a) +end + +-- 7. fill onto an image: colours, opacity, paint functions, compositing over existing pixels +do + local img = Types.Image.new(8, 8) + t:check(R.fill(img, R.path():rect(0, 0, 4, 8), { 255, 0, 0, 255 }), "fill red") + t:eq(buffer.readu32(img.pixels, 0), 0xFF0000FF, "opaque red pixel") + t:eq(buffer.readu32(img.pixels, 4 * 5), 0, "untouched pixel") + R.fill(img, R.path():rect(2, 0, 4, 8), { 0, 0, 255, 255 }, { opacity = 0.5 }) + local p = 4 * 3 + t:check(buffer.readu8(img.pixels, p) == 128 and buffer.readu8(img.pixels, p + 2) == 128 and buffer.readu8(img.pixels, p + 3) == 255, "half blue over red") + p = 4 * 5 + t:check(buffer.readu8(img.pixels, p + 2) == 255 and buffer.readu8(img.pixels, p + 3) == 128, "half blue over transparent") + local calls = 0 + R.fill(img, R.path():rect(0, 7, 8, 1), function(x: number, _y: number) + calls += 1 + return x * 30, 0, 0, 255 + end) + t:eq(calls, 8, "paint function per covered pixel") + t:eq(buffer.readu8(img.pixels, (7 * 8 + 2) * 4), math.floor(2.5 * 30 + 0.5), "paint at the pixel centre") + -- a transform scaling a unit square to the whole image + local img2 = Types.Image.new(4, 4) + R.fill(img2, R.path():rect(0, 0, 1, 1), { 0, 255, 0, 255 }, { transform = R.scale(4) }) + t:eq(buffer.readu32(img2.pixels, 4 * 15), 0xFF00FF00, "transformed fill") + local inv = R.invert({ 2, 0, 0, 4, 3, 5 }) :: any + local x, y = R.apply(inv, R.apply({ 2, 0, 0, 4, 3, 5 }, 7, 11)) + t:check(math.abs(x - 7) < 1e-9 and math.abs(y - 11) < 1e-9, "invert") + t:check(R.fill(img2, R.path():rect(0, 0, 1, 1), function() + error("boom") + end) == false, "a failing paint function returns false") +end + +-- 8. malformed paths and huge / non-finite coordinates never throw +do + local bad: { any } = { + { { op = "moveTo" }, { op = "lineTo", 1 }, { op = "quadTo", 1, 2, "x", 4 }, { op = "close" } }, + { { op = "lineTo", 0 / 0, 1 }, { op = "lineTo", 5, 5 }, { op = "lineTo", 0, 5 } }, + { { op = "moveTo", 0, 0 }, { op = "lineTo", math.huge, 1 }, { op = "lineTo", 1, 1e300 } }, + { { op = "moveTo", -1e6, -1e6 }, { op = "lineTo", 1e6, -1e6 }, { op = "lineTo", 1e6, 1e6 } }, + { 5, "x", { op = "cubicTo" }, { op = 3 } }, + {}, + } + local threw = 0 + for i, p in bad do + for _, rule in { "nonzero", "evenodd" } do + local ok = pcall(function() + R.mask(p, { rule = rule :: any, clip = { 0, 0, 64, 64 } }) + R.mask(p, { transform = { 0 / 0, 0, 0, 1, 0, 0 } }) + R.stroke(p, { width = 3, cap = "round", join = "round" }) + R.fill(Types.Image.new(16, 16), p, { 1, 2, 3, 4 }, { transform = { 1e9, 0, 0, 1e9, 0, 0 } }) + end) + if not ok then + threw += 1 + print(" threw on bad path " .. i) + end + end + end + local _, why = R.mask(R.path():rect(0, 0, 5000, 5000), { maxPixels = 1000 }) + t:eq(why, "limit", "over maxPixels") + t:check(R.mask("nope") == nil and R.mask(nil) == nil, "non-paths") + -- random command soup through the fuzz helper: bytes -> commands + t:fuzz("mask", function(b: buffer) + local cmds = {} + local ops = { "moveTo", "lineTo", "quadTo", "cubicTo", "close" } + local i = 0 + while i + 1 < buffer.len(b) do + local c: any = { op = ops[buffer.readu8(b, i) % 5 + 1] } + for k = 1, 6 do + local q = i + k + c[k] = if q < buffer.len(b) then (buffer.readi8(b, q)) * 0.73 else 0 + end + table.insert(cmds, c) + i += 7 + end + R.mask(cmds, { rule = if buffer.len(b) % 2 == 0 then "evenodd" else "nonzero", clip = { -10, -10, 40, 40 } }) + return R.stroke(cmds, { width = 2.5, cap = "square", join = "miter" }) + end, { "\0\1\2\3\4\5\6\1\9\9\9\9\9\9\2\1\2\3\4\5\6\3\1\2\3\4\5\6\4" }, { garbage = 400 }) + t:eq(threw, 0, "malformed paths never throw") +end + +t:done() diff --git a/tests/codecs/url.luau b/tests/codecs/url.luau new file mode 100644 index 0000000..82075b3 --- /dev/null +++ b/tests/codecs/url.luau @@ -0,0 +1,108 @@ +-- codecs/Url + codecs/Text tests: every example of RFC 3986 section 5.4 (normal and abnormal), dot-segment removal, +-- splitting, encoding and the location helpers (ported from playlist-luau tests/url.luau); random references against +-- Python's urllib.parse.urljoin; Url.locate / Url.base; Windows-1252 decoding against Python's cp1252 codec; lines, +-- BOM, trim; the fuzz pass. Fixtures: tools/fixtures/playlist.py. +local T = require("@tests/T") +local Url = require("@formats/codecs/Url") +local Text = require("@formats/codecs/Text") +local Ref = require("@tests/gen/playlist_url") +local Cp = require("@tests/gen/playlist_cp1252") + +local t = T.suite("url") +local function eq(got: any, want: any, label: string) + t:eq(got, want, label) +end + +local BASE = "http://a/b/c/d;p?q" +local cases = { + -- 5.4.1 normal + { "g:h", "g:h" }, { "g", "http://a/b/c/g" }, { "./g", "http://a/b/c/g" }, { "g/", "http://a/b/c/g/" }, + { "/g", "http://a/g" }, { "//g", "http://g" }, { "?y", "http://a/b/c/d;p?y" }, { "g?y", "http://a/b/c/g?y" }, + { "#s", "http://a/b/c/d;p?q#s" }, { "g#s", "http://a/b/c/g#s" }, { "g?y#s", "http://a/b/c/g?y#s" }, + { ";x", "http://a/b/c/;x" }, { "g;x", "http://a/b/c/g;x" }, { "g;x?y#s", "http://a/b/c/g;x?y#s" }, + { "", "http://a/b/c/d;p?q" }, { ".", "http://a/b/c/" }, { "./", "http://a/b/c/" }, { "..", "http://a/b/" }, + { "../", "http://a/b/" }, { "../g", "http://a/b/g" }, { "../..", "http://a/" }, { "../../", "http://a/" }, + { "../../g", "http://a/g" }, + -- 5.4.2 abnormal + { "../../../g", "http://a/g" }, { "../../../../g", "http://a/g" }, { "/./g", "http://a/g" }, + { "/../g", "http://a/g" }, { "g.", "http://a/b/c/g." }, { ".g", "http://a/b/c/.g" }, { "g..", "http://a/b/c/g.." }, + { "..g", "http://a/b/c/..g" }, { "./../g", "http://a/b/g" }, { "./g/.", "http://a/b/c/g/" }, + { "g/./h", "http://a/b/c/g/h" }, { "g/../h", "http://a/b/c/h" }, { "g;x=1/./y", "http://a/b/c/g;x=1/y" }, + { "g;x=1/../y", "http://a/b/c/y" }, { "g?y/./x", "http://a/b/c/g?y/./x" }, { "g?y/../x", "http://a/b/c/g?y/../x" }, + { "g#s/./x", "http://a/b/c/g#s/./x" }, { "g#s/../x", "http://a/b/c/g#s/../x" }, { "http:g", "http:g" }, +} +for _, c in cases do + eq(Url.resolve(c[1], BASE), c[2], "resolve " .. c[1]) +end +-- base with an empty path +eq(Url.resolve("g", "http://a"), "http://a/g", "empty base path") +eq(Url.resolve("g", "http://a?x"), "http://a/g", "empty base path with query") + +eq(Url.removeDotSegments("/a/b/c/./../../g"), "/a/g", "remove_dot_segments 1") +eq(Url.removeDotSegments("mid/content=5/../6"), "mid/6", "remove_dot_segments 2") + +local p = Url.split("https://user@host:8080/p/a.mp3?x=1&y#frag") +eq(p.scheme, "https", "split scheme") +eq(p.authority, "user@host:8080", "split authority") +eq(p.path, "/p/a.mp3", "split path") +eq(p.query, "x=1&y", "split query") +eq(p.fragment, "frag", "split fragment") +eq(Url.join(p), "https://user@host:8080/p/a.mp3?x=1&y#frag", "join") +local q = Url.split("a/b") +eq(q.scheme, nil, "relative has no scheme") +eq(q.authority, nil, "relative has no authority") + +eq(Url.encodeUnsafe("a b/ü%20?x=\"1\"#f"), "a%20b/%C3%BC%20?x=%221%22#f", "encodeUnsafe") +eq(Url.isWindowsPath("C:\\Music\\a.mp3"), true, "windows drive") +eq(Url.isWindowsPath("d:/x.mp3"), true, "windows drive with slash") +eq(Url.isWindowsPath("\\\\server\\share\\a.mp3"), true, "UNC") +eq(Url.isWindowsPath("http://x/a"), false, "http is not windows") +eq(Url.scheme("C:\\a.mp3"), nil, "a drive letter is not a scheme") +eq(Url.scheme("HTTPS://x"), "https", "scheme lower-cased") +eq(Url.scheme("music/a.mp3"), nil, "relative has no scheme") + + +-- Python's urljoin +for _, c in Ref do + eq(Url.resolve(c[1], c[2]), c[3], "urljoin " .. c[1] .. " against " .. c[2]) +end +t:note("%d random references resolve as urllib.parse.urljoin", #Ref) + +-- locate / base +do + local w = {} + local base, scheme = Url.base("https://h/a/list.m3u", w) + t:check(base == "https://h/a/list.m3u" and scheme == "https", "base") + local l = Url.locate(" b c.mp3 ", base, scheme) + t:check(l.url == "https://h/a/b%20c.mp3" and l.playable, "locate relative") + t:check(Url.locate("C:\\x.mp3", base, scheme).reason == "local path", "locate windows") + t:check(Url.locate("ftp://x/y", base, scheme).reason == "scheme ftp", "locate ftp") + local nb, ns = Url.base("lists/x.m3u", w) + t:check(nb == nil and ns == nil and #w == 1, "a relative base is ignored with a warning") + t:check(select(2, Url.base("C:\\Music\\l.m3u")) == "windows", "windows base") +end + +-- Text +do + for _, c in Cp do + eq(Text.toUtf8("x" .. string.char(c[1]) .. "y"), "x" .. c[2] .. "y", string.format("cp1252 0x%02x", c[1])) + end + local w = {} + Text.toUtf8("\150", w) + t:check(#w == 1, "cp1252 warning") + eq(Text.toUtf8("\239\187\191abc"), "abc", "BOM stripped") + eq(Text.toUtf8("h\u{e9}"), "h\u{e9}", "UTF-8 kept") + local ls = Text.lines("a\r\nb\rc\nd") + t:check(#ls == 4 and ls[1] == "a" and ls[2] == "b" and ls[3] == "c" and ls[4] == "d", "lines") + eq(Text.trim(" x y \t"), "x y", "trim") +end + +t:fuzz("resolve + locate", function(b: buffer) + local s = buffer.tostring(b) + Url.resolve(s, "http://a/b/c/d;p?q") + Url.resolve("g/../h", s) + Url.locate(s, "http://h/", "http") + return Text.lines(Text.toUtf8(s)) +end, { "http://a/b/../c?x#y", "C:\\a\\b.mp3", "\239\187\191#EXTM3U\r\n" }, { mutations = 30 }) + +t:done() diff --git a/tests/codecs/vp8.luau b/tests/codecs/vp8.luau new file mode 100644 index 0000000..484c3f1 --- /dev/null +++ b/tests/codecs/vp8.luau @@ -0,0 +1,80 @@ +-- codecs/Vp8 tests: the VP8 key frames of the WebP fixtures (cwebp at many settings and libvpx through ffmpeg, with +-- 1..8 token partitions) decoded through the codec API: the yuv420p planes against dwebp -yuv, toRgba against +-- dwebp -pam (fancy upsampling) and -nofancy, the decoder object over successive frames, headers, error codes and the +-- fuzz no-throw pass on raw frames. Fixtures: tools/fixtures/webp.py. +local T = require("@tests/T") +local Vp8 = require("@formats/codecs/Vp8") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Cases = require("@tests/gen/webp_cases") + +local t = T.suite("vp8") + +local function chunk(data: string): (buffer?, number, number) + if string.sub(data, 13, 16) ~= "VP8 " then + return nil, 0, 0 + end + local b = buffer.fromstring(data) + return b, 20, buffer.readu32(b, 16) +end + +local n, vpx = 0, 0 +local frames = {} +local dec = Vp8.newDecoder() +for _, c in Cases do + local b, off, len = chunk(c.data) + if b then + local img, err = Vp8.decodeFrame(b, off, len) + t:check(img, c.name .. ": " .. tostring(err)) + t:check(img.format == "yuv420p" and img.width == c.width and img.height == c.height, c.name .. ": size") + t:eq(Crc32.of(img.pixels), c.yuv, c.name .. ": yuv420p (dwebp -yuv)") + local rgba = Vp8.toRgba(img) :: any + t:eq(Crc32.of(rgba.pixels), c.crc, c.name .. ": rgba (dwebp -pam)") + local nf = Vp8.toRgba(img, false) :: any + t:eq(Crc32.of(nf.pixels), c.nofancy, c.name .. ": rgba (dwebp -nofancy -pam)") + -- the same frame through one long-lived decoder + local again = dec:decodeFrame(b, off, len) + t:check(again and Crc32.of(again.pixels) == c.yuv, c.name .. ": decoder object") + local y, u, v, w, h = Vp8.decodePlanes(b, off, len) + t:check(y and w == c.width and h == c.height and buffer.len(u) == buffer.len(v :: buffer), c.name .. ": decodePlanes") + local info = Vp8.info(b, off, len) + t:check(info and info.keyFrame and info.show and info.width == c.width, c.name .. ": info") + n += 1 + if string.find(c.name, "vpx", 1, true) then + vpx += 1 + end + if #frames < 10 and len < 6000 then + table.insert(frames, buffer.readstring(b, off, len)) + end + end +end +t:note("%d VP8 key frames (%d from libvpx) match dwebp: planes, fancy and point upsampling", n, vpx) + +-- errors +do + local f = buffer.fromstring(frames[1]) + local inter = buffer.fromstring(frames[1]) + buffer.writeu8(inter, 0, bit32.bor(buffer.readu8(inter, 0), 1)) + local _, e1 = Vp8.decodeFrame(inter) + t:check(e1 and e1.code == Err.UNSUPPORTED, "inter frame: " .. tostring(e1)) + local bad = buffer.fromstring(frames[1]) + buffer.writeu8(bad, 3, 0) + local _, e2 = Vp8.decodeFrame(bad) + t:check(e2 and e2.code == Err.CORRUPT, "bad start code: " .. tostring(e2)) + local _, e3 = Vp8.decodeFrame(f, 0, 12) + t:check(e3 and e3.code == Err.TRUNCATED, "truncated: " .. tostring(e3)) + local _, e4 = Vp8.decodeFrame(f, 0, buffer.len(f), { maxPixels = 4 }) + t:check(e4 and e4.code == Err.LIMIT, "maxPixels: " .. tostring(e4)) + local _, e5 = Vp8.toRgba({} :: any) + t:check(e5 and e5.code == Err.ARG, "toRgba of a non-yuv image") +end + +-- fuzz on raw frames +t:fuzz("decodeFrame", function(b: buffer) + return Vp8.decodeFrame(b, 0, buffer.len(b), { maxPixels = 2 ^ 20 }) +end, frames, { mutations = 12, keepHeader = 10 }) +t:fuzz("decodeFrame (headers too)", function(b: buffer) + return Vp8.decodeFrame(b, 0, buffer.len(b), { maxPixels = 2 ^ 20 }) +end, frames, { mutations = 4, garbage = 100 }) + +t:done() diff --git a/tests/codecs/vp8l.luau b/tests/codecs/vp8l.luau new file mode 100644 index 0000000..b506cc2 --- /dev/null +++ b/tests/codecs/vp8l.luau @@ -0,0 +1,120 @@ +-- codecs/Vp8L tests: the VP8L bitstreams of the WebP fixtures (cwebp -z 0..9, -exact, near-lossless) decoded through +-- the codec API against dwebp, the encoder at every effort on generated images (gradients, noise, palettes of 1..300 +-- colours, odd sizes, alpha), headerless alpha streams, error codes, and the fuzz no-throw pass on raw bitstreams. +-- Fixtures: tools/fixtures/webp.py. +local T = require("@tests/T") +local Vp8L = require("@formats/codecs/Vp8L") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Cases = require("@tests/gen/webp_cases") + +local t = T.suite("vp8l") + +-- the VP8L chunk of a simple-format file +local function chunk(data: string): (buffer?, number, number) + if string.sub(data, 13, 16) ~= "VP8L" then + return nil, 0, 0 + end + local b = buffer.fromstring(data) + return b, 20, buffer.readu32(b, 16) +end + +local n = 0 +local streams = {} +for _, c in Cases do + local b, off, len = chunk(c.data) + if b then + local px, w, h = Vp8L.decode(b, off, len) + t:check(px, c.name .. ": " .. tostring(w)) + t:check(w == c.width and h == c.height, c.name .. ": size") + t:eq(Crc32.of(px :: buffer), c.crc, c.name .. ": pixels (dwebp)") + local info = Vp8L.info(b, off, len) + t:check(info and info.width == c.width and info.height == c.height and info.alpha == c.alpha, c.name .. ": info") + local argb = Vp8L.decodeArgb(b, off, len) + t:check(argb and Crc32.of(Vp8L.toRgba(argb, c.width * c.height)) == c.crc, c.name .. ": decodeArgb + toRgba") + n += 1 + if #streams < 12 and len < 8000 then + table.insert(streams, buffer.readstring(b, off, len)) + end + end +end +t:note("%d VP8L bitstreams match dwebp", n) + +-- the encoder: round trips at every effort +local rand = T.rng(5) +local function gen(w: number, h: number, kind: string): buffer + local px = buffer.create(w * h * 4) + local pal = {} + local np = if kind == "pal1" then 1 elseif kind == "pal4" then 4 elseif kind == "pal40" then 40 elseif kind == "pal300" then 300 else 0 + for i = 1, np do + pal[i] = rand(2 ^ 24) * 256 + (if i % 3 == 0 then rand(256) else 255) + end + for y = 0, h - 1 do + for x = 0, w - 1 do + local o = (y * w + x) * 4 + if np > 0 then + local v = pal[(x * 7 + y * 3 + (x * y) % 5) % np + 1] + buffer.writeu32(px, o, v) + elseif kind == "noise" then + buffer.writeu32(px, o, rand(2 ^ 16) * 65536 + rand(2 ^ 16)) + else + buffer.writeu8(px, o, (x * 4 + y) % 256) + buffer.writeu8(px, o + 1, (y * 3) % 256) + buffer.writeu8(px, o + 2, (x * y) % 256) + buffer.writeu8(px, o + 3, if kind == "alpha" then (x * 9) % 256 else 255) + end + end + end + return px +end +local count = 0 +for _, kind in { "grad", "alpha", "noise", "pal1", "pal4", "pal40", "pal300" } do + for _, size in { { 1, 1 }, { 2, 3 }, { 17, 5 }, { 64, 33 }, { 130, 2 } } do + local w, h = size[1], size[2] + local px = gen(w, h, kind) + for effort = 0, 9 do + local bits, err = Vp8L.encode(px, w, h, { effort = effort, exact = true }) + t:check(bits, kind .. ": encode: " .. tostring(err)) + local back, bw, bh = Vp8L.decode(bits :: buffer) + t:check(back and bw == w and bh == h, string.format("%s %dx%d effort %d: decode: %s", kind, w, h, effort, tostring(bw))) + t:check(buffer.tostring(back :: buffer) == buffer.tostring(px), string.format("%s %dx%d effort %d: round trip", kind, w, h, effort)) + count += 1 + end + -- a headerless alpha plane + local a = buffer.create(w * h) + for i = 0, w * h - 1 do + buffer.writeu8(a, i, buffer.readu8(px, i * 4 + 1)) + end + local s = Vp8L.encodeAlpha(a, w, h) :: buffer + local ab = Vp8L.decodeAlpha(s, 0, buffer.len(s), w, h) + t:check(ab and buffer.tostring(ab) == buffer.tostring(a), kind .. ": alpha stream round trip") + end +end +t:note("%d encoder round trips", count) + +-- errors +do + local _, e1 = Vp8L.decode(buffer.fromstring("\x2e\0\0\0\0")) + t:check(e1 and e1.code == Err.CORRUPT, "bad signature: " .. tostring(e1)) + local _, e2 = Vp8L.decode(buffer.fromstring("\x2f\0\0\0\x20")) + t:check(e2 and e2.code == Err.CORRUPT, "bad version: " .. tostring(e2)) + local _, e3 = Vp8L.decode(buffer.fromstring("\x2f\0")) + t:check(e3 and e3.code == Err.TRUNCATED, "short header: " .. tostring(e3)) + local big = Vp8L.encode(gen(64, 33, "grad"), 64, 33) :: buffer + local _, e4 = Vp8L.decode(big, 0, buffer.len(big), 100) + t:check(e4 and e4.code == Err.LIMIT, "maxPixels: " .. tostring(e4)) + local _, e5 = Vp8L.decode(big, 0, buffer.len(big) // 2) + t:check(e5 and e5.code == Err.TRUNCATED, "truncated stream: " .. tostring(e5)) + local _, e6 = Vp8L.encode(buffer.create(4), 2, 2) + t:check(e6 and e6.code == Err.ARG, "encode: short pixel buffer") +end + +-- fuzz on raw bitstreams +t:fuzz("decode", function(b: buffer) + return Vp8L.decode(b, 0, buffer.len(b), 2 ^ 20) +end, streams, { mutations = 10, keepHeader = 5 }) +t:fuzz("decodeAlpha", function(b: buffer) + return Vp8L.decodeAlpha(b, 0, buffer.len(b), 37, 11) +end, streams, { mutations = 4, garbage = 100 }) + +t:done() diff --git a/tests/codecs/xml.luau b/tests/codecs/xml.luau new file mode 100644 index 0000000..dac3f32 --- /dev/null +++ b/tests/codecs/xml.luau @@ -0,0 +1,197 @@ +-- codecs/Xml tests: random documents (namespaces, escapes, CDATA, comments, PIs, DOCTYPE entities, UTF-16, Latin-1) +-- against Python's ElementTree trees; encode -> decode round trips; well-formedness verdicts against expat +-- (hand-written cases and random mutations); events, helpers, options, error codes; the fuzz pass. +-- Fixtures: tools/fixtures/xml.py. +local T = require("@tests/T") +local Xml = require("@formats/codecs/Xml") +local Types = require("@formats/Types") +local Err = require("@formats/core/Err") +local Docs = require("@tests/gen/xml_docs") +local Wf = require("@tests/gen/xml_wf") + +local t = T.suite("xml") + +-- ElementTree's view of an element (tools/fixtures/xml.py canon): Clark names, xmlns attributes dropped, text / tail +local function s(x: string?): string + x = x or "" + return #(x :: string) .. ":" .. (x :: string) +end +local function canon(e: any, tail: string?): string + local out = { "(" .. s(Xml.clark(e)) } + local keys = {} + local vals = {} + for _, k in Types.keys(e.attrs) do + if k ~= "xmlns" and string.sub(k, 1, 6) ~= "xmlns:" then + local ck = Xml.clark(e, k) + table.insert(keys, ck) + vals[ck] = e.attrs[k] + end + end + table.sort(keys) + for _, k in keys do + table.insert(out, "|" .. s(k) .. "=" .. s(vals[k])) + end + -- text: strings before the first element child; each child's tail: strings after it + local text = {} + local i = 1 + local ch = e.children + while i <= #ch and (type(ch[i]) == "string" or ch[i].name == "#cdata") do + table.insert(text, Xml.text(ch[i])) + i += 1 + end + table.insert(out, "|t" .. s(table.concat(text))) + while i <= #ch do + local c = ch[i] + i += 1 + local tl = {} + while i <= #ch and (type(ch[i]) == "string" or ch[i].name == "#cdata") do + table.insert(tl, Xml.text(ch[i])) + i += 1 + end + table.insert(out, canon(c, table.concat(tl))) + end + return table.concat(out) .. ")t" .. s(tail) +end + +-- 1. documents vs ElementTree, and round trips +for i, d in Docs do + local doc, err = Xml.decode(d.data, { whitespace = true }) + t:check(doc, "doc " .. i .. ": " .. tostring(err)) + t:eq(canon((doc :: any).root), d.canon, "doc " .. i .. ": tree") + -- keep everything, encode, decode again: the same tree + local full = Xml.decode(d.data, { whitespace = true, comments = true, cdata = true, pi = true }) :: any + local out, eerr = Xml.encode(full) + t:check(out, "doc " .. i .. ": encodes (" .. tostring(eerr) .. ")") + local again, aerr = Xml.decode(out :: string, { whitespace = true }) + t:check(again, "doc " .. i .. ": re-decodes (" .. tostring(aerr) .. ")") + t:eq(canon((again :: any).root), d.canon, "doc " .. i .. ": round trip") + local pretty = Xml.encode(full, { indent = 2 }) :: string + t:check(Xml.decode(pretty), "doc " .. i .. ": pretty output parses") + -- the namespace option agrees with the clark helper + local nsdoc = Xml.decode(d.data, { namespaces = true }) :: any + local root = nsdoc.root + local want = string.match(Xml.clark(root), "^{([^}]*)}") + t:eq(root.ns, want, "doc " .. i .. ": node.ns") +end + +-- 2. well-formedness against expat +local agree, total, accepted, rejected = 0, 0, 0, 0 +for i, c in Wf do + local doc = Xml.decode(c.data) + local ok = doc ~= nil + total += 1 + if ok == c.ok then + agree += 1 + elseif i <= 60 then + t:check(false, "wf case " .. i .. " " .. string.format("%q", c.data) .. ": expat says " .. tostring(c.ok)) + end + if c.ok then + accepted += 1 + else + rejected += 1 + end +end +t:note("well-formedness: %d of %d verdicts agree with expat (%d well-formed, %d not)", agree, total, accepted, rejected) +t:check(agree >= total * 0.99, "well-formedness agreement >= 99%") + +-- 3. API details +do + local src = '<?xml version="1.0"?>\n<!DOCTYPE r [<!ENTITY e "E&#38;">]>\n<!--c--><r xmlns="urn:d" xmlns:p="urn:p" z="1" a="2"><p:x p:k="v">t<![CDATA[<c>]]>u</p:x><?go now?><y/>\n</r>' + local doc = Xml.decode(src, { comments = true, cdata = true, pi = true, namespaces = true }) :: any + t:eq(doc.declaration.version, "1.0", "declaration") + t:eq(doc.doctype.name, "r", "doctype name") + t:eq(doc.doctype.entities.e, "E&", "doctype entities (char refs expanded once)") + t:eq(doc.children[1].name, "#comment", "prolog comment kept") + local r = doc.root + t:eq(table.concat(Types.keys(r.attrs), ","), "xmlns,xmlns:p,z,a", "attribute order") + t:eq(r.ns, "urn:d", "default namespace") + local x = Xml.child(r, "x") :: any + t:eq(x.name, "p:x", "child by local name") + t:eq(x.ns, "urn:p", "prefixed namespace") + t:eq(Xml.clark(x, "p:k"), "{urn:p}k", "attribute clark") + t:eq(x.children[2].name, "#cdata", "cdata node") + t:eq(Xml.text(x), "t<c>u", "text with cdata") + t:eq(r.children[2].name, "#pi", "pi node") + t:eq(r.children[2].target .. "|" .. r.children[2].text, "go|now", "pi target / data") + t:eq(#Xml.children(r), 2, "element children") + t:eq(#Xml.descendants(doc), 3, "descendants") + t:eq(x.parent, r, "parent link") + t:eq(Xml.decode("<a>&e;</a>") == nil, true, "undefined entity") + local d2 = Xml.decode('<!DOCTYPE r [<!ENTITY e "E&#38;">]><r a="&e;">&e;</r>') :: any + t:eq(d2.root.attrs.a, "E&", "entity in attribute") + t:eq(Xml.text(d2.root), "E&", "entity in text") + -- whitespace handling + local w = Xml.decode("<a>\n <b> x </b>\n <c xml:space='preserve'> </c>\n</a>") :: any + t:eq(#w.root.children, 2, "whitespace-only text dropped") + t:eq(Xml.text(w.root.children[1]), " x ", "other text kept as is") + t:eq(w.root.children[2].children[1], " ", "xml:space preserve") + t:eq(#(Xml.decode("<a>\n <b/>\n</a>", { whitespace = true }) :: any).root.children, 3, "opts.whitespace") + -- attribute normalization and line endings + local n = Xml.decode("<a b='x\ty\r\nz '>l1\r\nl2\rl3</a>") :: any + t:eq(n.root.attrs.b, "x y z\n", "attribute value normalization") + t:eq(Xml.text(n.root), "l1\nl2\nl3", "line endings") + -- builders and encode + local e = Xml.element("svg", { width = "10", height = "5" }, { Xml.element("rect", { x = "1" }), "a<b & \"c\"" }) + Xml.setAttr(e, "id", "q\"\n") + t:eq(Xml.encode(e), '<svg height="5" width="10" id="q" "><rect x="1"/>a<b & "c"</svg>', "encode element") + local d3 = Xml.document(Xml.element("r", nil, { Xml.element("a"), Xml.element("b", nil, { "t" }) })) + t:eq(Xml.encode(d3, { indent = 2 }), '<?xml version="1.0" encoding="UTF-8"?>\n<r>\n <a/>\n <b>t</b>\n</r>\n', "pretty document") + t:eq(Xml.encode(Xml.element("a"), { selfClose = false }), "<a></a>", "selfClose false") + local _, be = Xml.encode(Xml.element("1bad")) + t:eq(be and be.code, Err.ARG, "bad name on encode") + local cyc = Xml.element("a") + table.insert(cyc.children, cyc) + local _, ce = Xml.encode(cyc) + t:eq(ce and ce.code, Err.ARG, "cycle on encode") + t:eq(Xml.encode({ name = "#cdata", attrs = Types.object(), children = {}, text = "a]]>b" } :: any), "<![CDATA[a]]]]><![CDATA[>b]]>", "cdata split") + -- events + local evs = {} + for ev, a in Xml.events("<a x='1'><b>t</b><!--c--></a>") do + table.insert(evs, ev .. (if type(a) == "string" then ":" .. a else "")) + end + t:eq(table.concat(evs, " "), "start:a start:b text:t end:b comment:c end:a", "events") + local last + for ev, a in Xml.events("<a><b></a>") do + last = { ev, a } + end + t:eq(last[1], "error", "events error") + t:eq(last[2].code, Err.CORRUPT, "events error code") + -- UTF-16 without BOM and encodings + local u16 = buffer.create(8) + for k, ch in { 60, 0, 97, 0, 47, 0, 62, 0 } do + buffer.writeu8(u16, k - 1, ch) + end + t:eq((Xml.decode(u16) :: any).root.name, "a", "UTF-16LE without BOM") + local _, ue = Xml.decode("<?xml version='1.0' encoding='EBCDIC'?><a/>") + t:eq(ue and ue.code, Err.UNSUPPORTED, "unsupported encoding") +end + +-- 4. errors and limits +local function code(src: string, opts: any?): string? + local _, e = Xml.decode(src, opts) + return e and e.code +end +t:eq(code("<a><b>"), Err.TRUNCATED, "unclosed") +t:eq(code("<a></b>"), Err.CORRUPT, "mismatch") +t:eq(code("<a b='1' b='2'/>"), Err.CORRUPT, "duplicate attribute") +t:eq(code(string.rep("<a>", 60) .. string.rep("</a>", 60), { maxDepth = 50 }), Err.LIMIT, "maxDepth") +t:eq(code('<!DOCTYPE r [<!ENTITY a "aaaaaaaaaa"><!ENTITY b "&a;&a;&a;&a;&a;&a;&a;&a;&a;&a;"><!ENTITY c "&b;&b;&b;&b;&b;&b;&b;&b;&b;&b;"><!ENTITY d "&c;&c;&c;&c;&c;&c;&c;&c;&c;&c;"><!ENTITY e "&d;&d;&d;&d;&d;&d;&d;&d;&d;&d;">]><r>&e;&e;&e;&e;&e;&e;&e;&e;&e;&e;&e;&e;</r>', { maxExpansion = 100000 }), Err.LIMIT, "billion laughs") +t:eq(code('<!DOCTYPE r [<!ENTITY a "&a;">]><r>&a;</r>'), Err.CORRUPT, "recursive entity") +t:eq(code('<!DOCTYPE r [<!ENTITY x SYSTEM "file.xml">]><r>&x;</r>'), Err.UNSUPPORTED, "external entity") +t:eq(code("<p:a/>", { namespaces = true }), Err.CORRUPT, "undeclared prefix") +local _, ae = Xml.decode(5 :: any) +t:eq(ae and ae.code, Err.ARG, "bad argument") + +-- 5. fuzz +local samples = {} +for i = 1, 40 do + table.insert(samples, Docs[i].data) +end +t:fuzz("decode", function(b: buffer) + return Xml.decode(b, { comments = true, namespaces = true }) +end, samples) +t:fuzz("encode(decode)", function(b: buffer) + local d = Xml.decode(b, { comments = true, cdata = true, pi = true }) + return d and Xml.encode(d, { indent = 1 }) +end, samples, { garbage = 20 }) +t:done() diff --git a/tests/codecs/zstd.luau b/tests/codecs/zstd.luau new file mode 100644 index 0000000..8e25cf6 --- /dev/null +++ b/tests/codecs/zstd.luau @@ -0,0 +1,115 @@ +-- codecs/Zstd tests: every fixture case (the zstd CLI at levels 1..19, --ultra -22, --fast, --long, small windows, +-- with / without checksum and content size, multi-frame and skippable frames, empty input) decodes to its corpus; +-- offsets / consumedEnd; XXH64 vectors; checksum, limit and error codes; truncated / corrupted / random input never +-- throws. Fixtures: tools/fixtures/zstd.py. +local T = require("@tests/T") +local Zstd = require("@formats/codecs/Zstd") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/zstd") + +local t = T.suite("zstd") + +-- XXH64 reference values (xxhsum -H64) +do + local function hex(s: string): string + local hi, lo = Zstd.xxh64(buffer.fromstring(s)) + return string.format("%08x%08x", hi, lo) + end + t:eq(hex(""), "ef46db3751d8e999", "xxh64 empty") + t:eq(hex("a"), "d24ec4f1a98c6e5b", "xxh64 a") + t:eq(hex("abc"), "44bc2cf5ad770999", "xxh64 abc") + t:eq(hex("Nobody inspects the spammish repetition"), "fbcea83c8a378bf1", "xxh64 sentence") + t:eq(hex(string.rep("0123456789", 10)), "f80e7b96315afffa", "xxh64 100 bytes") +end + +-- every case decodes to its corpus +local nbytes = 0 +for _, c in Fx.cases do + local want = Fx.corpora[c.corpus] + local b = buffer.fromstring(c.data) + local out, consumed = Zstd.decompress(b) + t:check(out ~= nil, c.name .. ": " .. tostring(consumed)) + t:check(buffer.tostring(out :: buffer) == want, c.name .. ": output differs") + t:eq(consumed, #c.data, c.name .. ": consumed") + nbytes += #want +end +t:note("%d fixture streams, %.1f MB decoded", #Fx.cases, nbytes / 1e6) + +local function case(name: string): any + for _, c in Fx.cases do + if c.name == name then + return c + end + end + error("no case " .. name) +end + +-- at an offset inside a bigger buffer, and string input +do + local c = case("text/l3") + local big = buffer.create(#c.data + 20) + buffer.fill(big, 0, 0xAB) + buffer.writestring(big, 7, c.data) + local out, consumed = Zstd.decompress(big, 7, #c.data) + t:check(out and buffer.tostring(out) == Fx.corpora.text, "at an offset") + t:eq(consumed, 7 + #c.data, "consumed at an offset") + t:check(buffer.tostring((Zstd.decompress(c.data))) == Fx.corpora.text, "string input") + t:check(Zstd.isFrame(buffer.fromstring(c.data)), "isFrame") + t:check(not Zstd.isFrame(buffer.fromstring("abcd")), "isFrame on other data") + -- trailing garbage is an error, as zstd -d says + local _, e = Zstd.decompress(c.data .. "junk") + t:check(e and e.code == Err.CORRUPT, "trailing garbage: " .. tostring(e)) +end + +-- checksum mismatch (the last 4 bytes), and verify = false skips it +do + local c = case("text/l9") + local b = buffer.fromstring(c.data) + local n = buffer.len(b) + buffer.writeu8(b, n - 1, bit32.bxor(buffer.readu8(b, n - 1), 0x10)) + local out, e = Zstd.decompress(b) + t:check(out == nil and Err.is(e) and e.code == Err.CHECKSUM, "checksum mismatch: " .. tostring(e)) + local out2 = Zstd.decompress(b, nil, nil, { verify = false }) + t:check(out2 and buffer.tostring(out2) == Fx.corpora.text, "verify = false") +end + +-- limits and arguments +do + local c = case("text/l3") + local _, e = Zstd.decompress(c.data, nil, nil, { maxBytes = 1000 }) + t:check(e and e.code == Err.LIMIT, "maxBytes with a content size: " .. tostring(e)) + local s = case("text/stdin") + local _, e2 = Zstd.decompress(s.data, nil, nil, { maxBytes = 1000 }) + t:check(e2 and e2.code == Err.LIMIT, "maxBytes without a content size: " .. tostring(e2)) + local ok, r1, r2 = pcall(Zstd.decompress, 5 :: any) + t:check(ok and r1 == nil and r2.code == Err.ARG, "a non-buffer argument returns Err.ARG") + local _, e3 = Zstd.decompress("") + t:check(e3 and e3.code == Err.TRUNCATED, "empty input is TRUNCATED: " .. tostring(e3)) + local _, e4 = Zstd.decompress("\40\181\47\253\0") + t:check(e4 and e4.code == Err.TRUNCATED, "header only: " .. tostring(e4)) + -- a dictionary ID: FHD with Dictionary_ID_flag = 1, single segment, then a 1-byte dictionary id and 1-byte size + local _, e5 = Zstd.decompress("\40\181\47\253\33\7\0\1\0\0") + t:check(e5 and e5.code == Err.UNSUPPORTED, "dictionary: " .. tostring(e5)) + -- reserved block type + local _, e6 = Zstd.decompress("\40\181\47\253\32\0\7\0\0") + t:check(e6 and e6.code == Err.CORRUPT, "reserved block type: " .. tostring(e6)) +end + +-- truncation, corruption and garbage never throw +do + local samples = {} + for i, c in Fx.cases do + if i % 5 == 0 and #c.data > 8 and #c.data < 40000 then + table.insert(samples, c.data) + end + end + t:fuzz("decompress", function(b: buffer) + return Zstd.decompress(b) + end, samples, { mutations = 12, garbage = 2000 }) + -- keep the frame header intact so the mutations reach the blocks + t:fuzz("decompress (blocks)", function(b: buffer) + return Zstd.decompress(b, nil, nil, { verify = false, maxBytes = 1e6 }) + end, samples, { mutations = 40, garbage = 0, keepHeader = 12, seed = 99 }) +end + +t:done() diff --git a/tests/compat.luau b/tests/compat.luau index 6576b84..2883d58 100644 --- a/tests/compat.luau +++ b/tests/compat.luau @@ -212,6 +212,12 @@ do count += 1 end t:eq(count, 3, "for over a mixed table visits every key") + local zero = { [0] = 5, 6, 7 } + local zsum = 0 + for _, v in zero do + zsum += v + end + t:eq(zsum, 18, "for over a table with key 0 visits it (LuaJIT keeps t[0] in the array part)") local w = {} for word in string.gmatch("a b c", "%a") do table.insert(w, word) @@ -272,4 +278,25 @@ do t:eq(0x7FFFFFFF + 1, 2147483648, "no integer overflow") end +do -- float reads: NaNs with a payload come back as the canonical NaN (LuaJIT: never an aliased object value) + local b = buffer.create(16) + buffer.writeu32(b, 0, 0x7fc12345) + buffer.writeu32(b, 4, 0x7f800000) + buffer.writeu32(b, 8, 0xdeadbeef) + buffer.writeu32(b, 12, 0xfff12345) + local a, i, c = buffer.readf32(b, 0), buffer.readf32(b, 4), buffer.readf64(b, 8) + t:eq(type(a), "number", "f32 NaN payload is a number") + t:check(a ~= a, "f32 NaN payload reads as NaN") + t:eq(i, math.huge, "f32 +inf") + t:eq(type(c), "number", "f64 NaN payload is a number") + t:check(c ~= c, "f64 NaN payload reads as NaN") + buffer.writeu32(b, 8, 0) + buffer.writeu32(b, 12, 0xfff00000) + t:eq(buffer.readf64(b, 8), -math.huge, "f64 -inf") + buffer.writef32(b, 0, 1.5) + buffer.writef64(b, 8, -2.25) + t:eq(buffer.readf32(b, 0), 1.5, "f32 normal") + t:eq(buffer.readf64(b, 8), -2.25, "f64 normal") +end + t:done() diff --git a/tests/containers/isobmff.luau b/tests/containers/isobmff.luau new file mode 100644 index 0000000..f05280e --- /dev/null +++ b/tests/containers/isobmff.luau @@ -0,0 +1,241 @@ +-- containers/IsoBmff tests: ffmpeg / MP4Box files (H.264 + AAC with B-frames, fast start, QuickTime MJPEG + PCM, HEVC, +-- fragmented by ffmpeg and MP4Box, stz2 + co64, ALAC) demuxed packet for packet against ffprobe (-ignore_editlist); +-- track facts and codec configurations; iTunes tags and cover art; AVIF items (libavif, plain and with alpha); the +-- muxer round-trips through the demuxer (sizes, times, cts, sync, tags, 64-bit sizes); a sub-range reader; the fuzz +-- no-throw pass. Fixtures: tools/fixtures/isobmff.py. +local T = require("@tests/T") +local IsoBmff = require("@formats/containers/IsoBmff") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Fx = require("@tests/gen/isobmff") + +local t = T.suite("isobmff") + +local CODEC = { h264 = "h264", aac = "aac", mjpeg = "mjpeg", pcm_s16be = "pcm", hevc = "hevc", alac = "alac" } + +local function reader(s: string, pad: number?): Bytes.Reader + if pad then + local b = buffer.create(#s + pad * 2) + buffer.writestring(b, pad, s) + return Bytes.reader(b, pad, #s) + end + return Bytes.reader(buffer.fromstring(s)) +end + +-- every fixture against ffprobe +for _, c in Fx.cases do + for _, pad in { 0, 5 } do + local r = reader(c.data, if pad > 0 then pad else nil) + local label = c.name .. (if pad > 0 then " (sub-range)" else "") + t:check(IsoBmff.sniff(r) ~= nil, label .. ": sniff") + local dmx, err = IsoBmff.demux(r) + t:check(dmx, label .. ": " .. tostring(err)) + t:eq(#dmx.tracks, #c.streams, label .. ": track count") + for i, s in c.streams do + local tr = dmx.tracks[i] + t:eq(tr.kind, s.kind, label .. ": track " .. i .. " kind") + t:eq(tr.codec, CODEC[s.codec] or s.codec, label .. ": track " .. i .. " codec") + t:eq(tr.timescale, s.timescale, label .. ": timescale") + if s.width then + t:check(tr.width == s.width and tr.height == s.height, label .. ": video size") + end + if s.sampleRate then + t:check(tr.sampleRate == s.sampleRate and tr.channels == s.channels, label .. ": audio format") + end + if s.extradata > 0 and s.codec ~= "alac" then + t:eq(if tr.config then buffer.len(tr.config) else 0, s.extradata, label .. ": codec config size") + end + end + -- packets in file order + local n, bad = 0, nil + local base = r.base + for p in dmx:packets() do + n += 1 + local want = c.packets[n] + if not want then + bad = bad or ("extra packet " .. n) + break + end + local tr = dmx.tracks[want.stream] + if p.track ~= tr.id then + bad = bad or ("packet " .. n .. " track") + end + local off = tr.offsets[p.index] + if off - base ~= want.pos or buffer.len(p.data) ~= want.size or p.dts ~= want.dts or p.pts ~= want.pts or p.keyframe ~= want.key then + bad = bad or string.format("packet %d: pos %d/%d size %d/%d dts %d/%d pts %d/%d key %s/%s", n, off - base, want.pos, buffer.len(p.data), want.size, p.dts, want.dts, p.pts, want.pts, tostring(p.keyframe), tostring(want.key)) + end + end + t:check(bad == nil, label .. ": " .. tostring(bad)) + t:eq(n, #c.packets, label .. ": packet count") + if pad == 0 then + t:note("%s: %d tracks, %d packets match ffprobe", c.name, #c.streams, n) + end + end +end + +-- per-track packets, seek +do + local c = Fx.cases[1] + local dmx = IsoBmff.demux(reader(c.data)) + local v = dmx.tracks[1] + local count = 0 + for p in dmx:packets(v.id) do + count += 1 + t:eq(p.track, v.id, "per-track packets") + end + t:eq(count, v.sampleCount, "per-track packet count") + dmx:seek(0.75) + local p = dmx:packets(v.id)() + t:check(p and p.keyframe and p.dts / v.timescale <= 0.75, "seek lands on a keyframe before the time") + t:check(v.skip >= 0 and v.edits ~= nil, "edit list parsed") +end + +-- tags and cover +do + local r = reader(Fx.tagged.data) + local movie = IsoBmff.parse(r) :: IsoBmff.Movie + local tags, pics = IsoBmff.tags(r, movie) + for k, v in Fx.tagged.tags do + t:eq(tags[k], v, "tag " .. k) + end + t:check(tags.encoder ~= nil, "encoder tag") + t:eq(#pics, 1, "one cover") + t:eq(pics[1] and buffer.len(pics[1].data), Fx.tagged.cover, "cover bytes") + t:eq(pics[1] and pics[1].mime, "image/png", "cover mime") +end + +-- AVIF items +for _, c in Fx.avif do + local r = reader(c.data) + t:check(IsoBmff.sniff(r) == "avif", c.name .. ": brand") + local movie = IsoBmff.parse(r) :: IsoBmff.Movie + t:check(movie and #movie.tracks == 0, c.name .. ": no tracks") + local items, err = IsoBmff.items(r, movie) + t:check(items, c.name .. ": items: " .. tostring(err)) + local prim = items.items[items.primary] + t:check(prim and prim.type == "av01", c.name .. ": primary item is av01") + local ispe, av1C + for _, p in prim.properties do + if p.type == "ispe" then + ispe = p + elseif p.type == "av1C" then + av1C = p + end + end + t:check(ispe and ispe.width == c.width and ispe.height == c.height, c.name .. ": ispe") + t:check(av1C and av1C.config and buffer.readu8(av1C.config, 0) == 0x81, c.name .. ": av1C marker / version") + local data = IsoBmff.itemData(r, items, items.primary :: number) + t:check(data and buffer.len(data) > 10, c.name .. ": item data") + -- an AV1 OBU stream: the first OBU is a sequence header (type 1) or a temporal delimiter (2) + local obu = data and bit32.band(bit32.rshift(buffer.readu8(data, 0), 3), 15) + t:check(obu == 1 or obu == 2, c.name .. ": AV1 OBU stream") + local auxl = nil + for _, id in items.order do + local it = items.items[id] + if it.refs.auxl then + auxl = it + end + end + t:eq(auxl ~= nil, c.alpha, c.name .. ": alpha auxiliary item") +end + +-- the muxer: round trip through the demuxer +do + local rand = T.rng(5) + local function sample(n: number): buffer + local b = buffer.create(n) + for i = 0, n - 1 do + buffer.writeu8(b, i, rand(256)) + end + return b + end + local aud, vid = {}, {} + for i = 1, 90 do + aud[i] = sample(50 + rand(200)) + end + for i = 1, 30 do + vid[i] = sample(100 + rand(900)) + end + local cts = {} + local sync = {} + for i = 1, 30 do + cts[i] = (i % 3) * 512 + sync[i] = i % 10 == 1 + end + local cfg = buffer.fromstring("\x12\x10") + local file, err = IsoBmff.mux({ + brand = "mp42", + compatible = { "mp42", "isom" }, + tracks = { + { kind = "video", entry = "avc1", timescale = 15360, samples = vid, durations = 512, cts = cts, sync = sync, width = 64, height = 48, config = buffer.fromstring("\1\100\0\10\255") }, + { kind = "audio", entry = "mp4a", timescale = 44100, samples = aud, durations = 1024, sampleRate = 44100, channels = 2, config = cfg, skip = 1024, playDuration = 44100 * 2 }, + }, + tags = { title = "Mux Test", artist = "Me", track = "2", tracktotal = "9", custom = "free form", bpm = "120" }, + pictures = { { mime = "image/jpeg", data = buffer.fromstring("\255\216\255\217") } }, + chunkDuration = 0.25, + }) + t:check(file, "mux: " .. tostring(err)) + local r = Bytes.reader(file :: buffer) + local dmx = IsoBmff.demux(r) + t:check(dmx and #dmx.tracks == 2, "mux: demux our file") + local v, a = dmx.tracks[1], dmx.tracks[2] + t:check(v.codec == "h264" and v.width == 64 and v.height == 48 and v.config and buffer.len(v.config) == 5, "mux: video track") + t:check(a.codec == "aac" and a.sampleRate == 44100 and a.channels == 2 and a.config and buffer.tostring(a.config) == "\x12\x10", "mux: audio track + esds") + t:check(a.skip == 1024 and a.playDuration == 88200, "mux: edit list") + local ok = true + for i = 1, 30 do + local s = IsoBmff.sample(r, v, i) :: buffer + ok = ok and buffer.tostring(s) == buffer.tostring(vid[i]) and v.dts[i] == (i - 1) * 512 and (v.cts :: any)[i] == cts[i] and ((v.sync :: any)[i] == true) == sync[i] + end + t:check(ok, "mux: video samples, times, cts, sync") + ok = true + for i = 1, 90 do + ok = ok and buffer.tostring(IsoBmff.sample(r, a, i) :: buffer) == buffer.tostring(aud[i]) and a.durations[i] == 1024 + end + t:check(ok, "mux: audio samples") + -- interleaved: offsets alternate between the tracks + t:check(v.offsets[30] > a.offsets[1] and a.offsets[90] > v.offsets[1], "mux: interleaved chunks") + local tags, pics = IsoBmff.tags(r, dmx.movie) + t:check(tags.title == "Mux Test" and tags.artist == "Me" and tags.track == "2" and tags.tracktotal == "9" and tags.custom == "free form" and tags.bpm == "120", "mux: tags round trip") + t:check(#pics == 1 and buffer.len(pics[1].data) == 4, "mux: cover round trip") + t:note("mux: %d bytes, crc %08x", buffer.len(file :: buffer), Crc32.of(file :: buffer)) + -- data + sizes form, bad specs + local f2 = IsoBmff.mux({ tracks = { { kind = "audio", entry = "alac", timescale = 8000, data = buffer.create(30), sizes = { 10, 10, 10 }, durations = { 4096, 4096, 100 }, config = buffer.create(24) } } }) + local d2 = IsoBmff.demux(Bytes.reader(f2 :: buffer)) + t:check(d2 and d2.tracks[1].codec == "alac" and d2.tracks[1].sampleCount == 3 and d2.tracks[1].durations[3] == 100 and buffer.len(d2.tracks[1].config) == 24, "mux: data + sizes, alac cookie") + for _, bad in { {}, { tracks = {} }, { tracks = { { kind = "audio", entry = "toolong", timescale = 1, samples = {}, durations = 1 } } }, { tracks = { { kind = "x", entry = "abcd", timescale = 1, samples = {}, durations = 1 } } }, { tracks = { { kind = "audio", entry = "abcd", timescale = 1 } } } } do + local f, e = IsoBmff.mux(bad :: any) + t:check(f == nil and e and e.code == "ARG", "mux: bad spec -> ARG") + end +end + +-- fuzz +do + local samples = {} + for _, c in Fx.cases do + table.insert(samples, string.sub(c.data, 1, 6000)) + table.insert(samples, c.data) + end + for _, c in Fx.avif do + table.insert(samples, c.data) + end + t:fuzz("demux", function(b: buffer) + local r = Bytes.reader(b) + local dmx = IsoBmff.demux(r) + if dmx then + for p in dmx:packets() do + local _ = p + end + IsoBmff.tags(r, dmx.movie) + local items = IsoBmff.items(r, dmx.movie) + if items then + for _, id in items.order do + IsoBmff.itemData(r, items, id) + end + end + end + return dmx + end, samples, { mutations = 12 }) +end + +t:done() diff --git a/tests/containers/tar.luau b/tests/containers/tar.luau new file mode 100644 index 0000000..fb2bc0d --- /dev/null +++ b/tests/containers/tar.luau @@ -0,0 +1,165 @@ +-- containers/Tar and containers/Archive tests: hand-made headers for the edge cases the reference archives do not hit +-- (base-256 numbers, the historical signed checksum, GNU 'K' long links, pax 'g' global records, pax size overrides, +-- v7 headers without magic, a missing end-of-archive marker), the writer's GNU / pax extensions (long links, fractional +-- and negative mtimes), and Archive helpers (streamName, entries of foreign archive values, failing loaders). +local T = require("@tests/T") +local Tar = require("@formats/containers/Tar") +local Archive = require("@formats/containers/Archive") +local Err = require("@formats/core/Err") + +local t = T.suite("containers/tar") + +-- a header block built by hand +local function hdr(fields: { [string]: any }): buffer + local h = buffer.create(512) + buffer.writestring(h, 0, fields.name or "f") + buffer.writestring(h, 100, fields.mode or "0000644\0") + buffer.writestring(h, 124, fields.size or "00000000000\0") + buffer.writestring(h, 136, fields.mtime or "00000000000\0") + buffer.writestring(h, 156, fields.type or "0") + if fields.link then + buffer.writestring(h, 157, fields.link) + end + if fields.magic ~= false then + buffer.writestring(h, 257, "ustar\00000") + end + if fields.raw then + for at, v in fields.raw do + buffer.writeu8(h, at, v) + end + end + buffer.writestring(h, 148, " ") + local sum, signed = 0, 0 + for i = 0, 511 do + local v = buffer.readu8(h, i) + sum += v + signed += if v >= 128 then v - 256 else v + end + buffer.writestring(h, 148, string.format("%06o\0 ", if fields.signed then signed % 0x40000 else sum)) + return h +end +local function cat(parts: { any }): buffer + local s = {} + for _, p in parts do + table.insert(s, if type(p) == "string" then p else buffer.tostring(p)) + end + return buffer.fromstring(table.concat(s)) +end +local function block(s: string): string + return s .. string.rep("\0", (512 - #s % 512) % 512) +end +local END = string.rep("\0", 1024) + +-- base-256 size (GNU), checksum with the signed sum, no end marker +do + local raw = { [124] = 0x80 } + for i = 125, 134 do + raw[i] = 0 + end + raw[135] = 5 + local b = cat({ hdr({ name = "big\200", raw = raw, signed = true }), block("hello") }) + local list, err = Tar.read(b) + t:check(list, "base-256 / signed checksum: " .. tostring(err)) + t:eq(list[1].size, 5, "base-256 size") + t:check(Tar.valid(b, 0), "valid() accepts the signed sum") +end + +-- GNU long link ('K'), pax global + per-file records, v7 header +do + local rec = "21 path=from/pax.txt\n" + local glob = "20 uname=globaluser\n" + local b = cat({ + hdr({ name = "././@LongLink", type = "K", size = string.format("%011o\0", 131) }), + block(string.rep("L", 130) .. "\0"), + hdr({ name = "sym", type = "2", link = "short" }), + hdr({ name = "pax_global", type = "g", size = string.format("%011o\0", #glob) }), + block(glob), + hdr({ name = "PaxHeaders/x", type = "x", size = string.format("%011o\0", #rec + 15) }), + block(rec .. "15 size=000003\n"), + hdr({ name = "ignored-name", size = "00000000077\0" }), + block("abc"), + hdr({ name = "v7file", magic = false, size = "00000000002\0", mtime = "12345670123\0" }), + block("v7"), + END, + }) + local list, err = Tar.read(b) + t:check(list, "extensions: " .. tostring(err)) + t:eq(#list, 3, "meta records are not entries") + t:eq(list[1].link, string.rep("L", 130), "GNU long link") + t:eq(list[2].name, "from/pax.txt", "pax path") + t:eq(list[2].size, 3, "pax size overrides the header") + t:eq(list[2].uname, "globaluser", "pax global record") + t:eq(list[3].name, "v7file", "v7 header") + t:eq(list[3].mtime, tonumber("12345670123", 8), "octal mtime") + t:eq(list[3].uname, "globaluser", "global records apply to later entries") +end + +-- errors +do + local _, e1 = Tar.read(cat({ hdr({ size = "00000002000\0" }), block("x") })) + t:check(e1 and e1.code == Err.TRUNCATED, "data past the end: " .. tostring(e1)) + local _, e2 = Tar.read(cat({ hdr({ type = "x", size = "00000000010\0" }), block("garbage!"), END })) + t:check(e2 and e2.code == Err.CORRUPT, "bad pax record: " .. tostring(e2)) + local good = hdr({}) + local bad = cat({ good, hdr({ name = "two" }) }) + buffer.writeu8(bad, 513, 77) + local _, e3 = Tar.read(bad) + t:check(e3 and e3.code == Err.CHECKSUM, "second header checksum: " .. tostring(e3)) + local list = Tar.read(buffer.create(0)) + t:check(list and #list == 0, "empty input is an empty archive") +end + +-- writer extensions +do + local long = string.rep("n", 120) + for _, fmt in { "gnu", "pax" } do + local out = Tar.write({ + { name = long, data = buffer.fromstring("x"), mtime = -5.25 }, + { name = "l", type = "2", link = string.rep("k", 150) }, + }, { format = fmt :: any }) :: buffer + local list = Tar.read(out) :: any + t:eq(list[1].name, long, fmt .. ": long name") + t:eq(list[2].link, string.rep("k", 150), fmt .. ": long link") + if fmt == "pax" then + t:eq(list[1].mtime, -5.25, "pax fractional negative mtime") + end + end + local _, e = Tar.write({ { name = "" } }) + t:check(e and e.code == Err.ARG, "empty name") +end + +-- Archive helpers +do + t:eq(Archive.streamName({ name = "/x/y/notes.txt.gz" }, { "gz" }), "notes.txt", "streamName strips the extension") + t:eq(Archive.streamName({ name = "a.tbz2" }, { "bz2" }), "a.tar", "streamName .tbz2") + t:eq(Archive.streamName(nil, { "gz" }), "data", "streamName default") + t:eq(Archive.streamName({ name = "plain" }, { "gz" }), "plain", "streamName without an extension") + local foreign = { + kind = "archive", + list = function() + return { { name = "a", size = 1, dir = false } } + end, + read = function() + error("boom") + end, + } + local items = Archive.entries(foreign) :: any + t:eq(#items, 1, "entries of a foreign archive") + local b, e = items[1].read() + t:check(b == nil and e and e.code == Err.CORRUPT, "a throwing read() becomes an Err") + t:check(Archive.entries({ kind = "image" }) == nil, "not an archive") + local a = Archive.new("x") + Archive.put(a, { name = "f", size = 1, dir = false, load = function() + error("bad") + end }) + local _, e2 = a:read("f") + t:check(e2 and e2.code == Err.CORRUPT, "a throwing loader becomes an Err") + local _, e3 = a:write() + t:check(e3 and e3.code == Err.UNSUPPORTED, "read-only archives") +end + +t:fuzz("read", function(b: buffer) + return Tar.read(b) +end, { buffer.tostring(Tar.write({ { name = string.rep("p", 130), data = buffer.fromstring("abc") }, { name = "d", dir = true } }) :: buffer) }, { mutations = 60 }) + +t:done() diff --git a/tests/core/base64.luau b/tests/core/base64.luau new file mode 100644 index 0000000..73c0880 --- /dev/null +++ b/tests/core/base64.luau @@ -0,0 +1,25 @@ +-- core/Base64 tests: the RFC 4648 vectors, whitespace / missing padding / URL-safe input, bad characters, random +-- round trips. +local T = require("@tests/T") +local Base64 = require("@formats/core/Base64") + +local t = T.suite("base64") +for _, v in { { "", "" }, { "f", "Zg==" }, { "fo", "Zm8=" }, { "foo", "Zm9v" }, { "foob", "Zm9vYg==" }, { "fooba", "Zm9vYmE=" }, { "foobar", "Zm9vYmFy" } } do + t:eq(Base64.encode(v[1]), v[2], "encode " .. v[1]) + t:eq(buffer.tostring(Base64.decode(v[2]) :: buffer), v[1], "decode " .. v[2]) +end +t:eq(buffer.tostring(Base64.decode(" Zm9v\nYmE ") :: buffer), "fooba", "whitespace and no padding") +t:eq(buffer.tostring(Base64.decode("-_8=") :: buffer), "\251\255", "URL-safe alphabet") +local b, err = Base64.decode("Zm9v!") +t:check(b == nil and err, "bad character") +local b2 = Base64.decode("Zg==Zg") +t:check(b2 == nil, "data after padding") +local rand = T.rng(5) +for n = 0, 40 do + local s = buffer.create(n) + for i = 0, n - 1 do + buffer.writeu8(s, i, rand(256)) + end + t:eq(buffer.tostring(Base64.decode(Base64.encode(s)) :: buffer), buffer.tostring(s), "round trip " .. n) +end +t:done() diff --git a/tests/data/Canon.luau b/tests/data/Canon.luau new file mode 100644 index 0000000..9291fb2 --- /dev/null +++ b/tests/data/Canon.luau @@ -0,0 +1,86 @@ +-- tests/data/Canon: the canonical text of a decoded data value, the same as tools/fixtures/_data_common.py canon() on +-- Python's parse: null n, true t, false f, numbers #%d (integral under 2^53) or #%.17g, strings s<len>:<bytes>, +-- buffers b<len>:<bytes>, arrays [x,...], objects {k=v,...} sorted by key text, dates d<rfc3339>. A module the data +-- tests require (running it alone does nothing). +local Types = require("@formats/Types") + +local Canon = {} + +local function num(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 + return string.format("#%d", x) + end + return "#" .. string.format("%.17g", x) +end + +local function isArray(t: { [any]: any }): boolean + if Types.isObject(t) then + return false + end + local n = #t + local c = 0 + for _ in next, t do + c += 1 + end + return c == n +end + +local function canon(v: any, out: { string }) + local tv = type(v) + if v == Types.null then + table.insert(out, "n") + elseif tv == "boolean" then + table.insert(out, if v then "t" else "f") + elseif tv == "number" then + table.insert(out, num(v)) + elseif tv == "string" then + table.insert(out, "s" .. #v .. ":" .. v) + elseif tv == "buffer" then + table.insert(out, "b" .. buffer.len(v) .. ":" .. buffer.tostring(v)) + elseif tv == "table" and Types.Date.is(v) then + table.insert(out, "d" .. tostring(v)) + elseif tv == "table" then + if isArray(v) then + table.insert(out, "[") + for i = 1, #v do + canon(v[i], out) + table.insert(out, ",") + end + table.insert(out, "]") + else + local items = {} + for k, x in next, v do + local ko = {} + canon(k, ko) + table.insert(items, { table.concat(ko), x }) + end + table.sort(items, function(a, b) + return a[1] < b[1] + end) + table.insert(out, "{") + for _, it in items do + table.insert(out, it[1] .. "=") + canon(it[2], out) + table.insert(out, ",") + end + table.insert(out, "}") + end + else + table.insert(out, "?" .. tv) + end +end + +-- of(v) -> the canonical text +function Canon.of(v: any): string + local out = {} + canon(v, out) + return table.concat(out) +end + +return Canon diff --git a/tests/data/cbor.luau b/tests/data/cbor.luau new file mode 100644 index 0000000..8501da2 --- /dev/null +++ b/tests/data/cbor.luau @@ -0,0 +1,121 @@ +-- data/cbor tests: the RFC 8949 Appendix A examples and random items encoded by Python's cbor2 decode to cbor2's +-- values (canonical form), re-encode to the same bytes, big integers as doubles and exact text, indefinite lengths, +-- tags / simple values / undefined, half floats, sequences, options, error codes, and the fuzz pass. +-- Fixtures: tools/fixtures/cbor.py. +local T = require("@tests/T") +local Cbor = require("@formats/data/cbor") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Canon = require("@tests/data/Canon") +local Fx = require("@tests/gen/cbor") + +local t = T.suite("data/cbor") + +t:eq(Cbor.name, "cbor", "name") +t:check(Cbor.caps.decode and Cbor.caps.encode, "caps") + +local function dec(s: string | buffer, opts: any?): (any, any) + local b = if type(s) == "string" then buffer.fromstring(s) else s + return Cbor.decode(Bytes.reader(b), opts) +end + +-- the fixture's view of tags / simple values / undefined +local function plain(v: any): any + if v == Cbor.undefined then + return { "undefined" } + elseif Cbor.isSimple(v) then + return { "simple", v.value } + elseif Cbor.isTagged(v) then + return { "tag", v.tag, plain(v.value) } + elseif type(v) == "table" and not Types.Date.is(v) and v ~= Types.null then + local o = if Types.isObject(v) then Types.object() else {} + for k, x in next, v do + o[plain(k)] = plain(x) + end + return o + end + return v +end + +local nApp = 0 +for _, c in Fx.appendix do + local v, err = dec(c.data) + if c.error then + t:check(v == nil and err ~= nil, c.hex .. ": rejected like cbor2") + else + t:check(v ~= nil or err == nil, c.hex .. ": " .. tostring(err)) + t:eq(Canon.of(plain(v)), c.canon, c.hex .. ": value") + t:eq(Canon.of(plain(dec(c.data, { bigInts = "string" }))), c.canonStr, c.hex .. ": exact") + t:eq(Canon.of(plain(dec(Cbor.encode(v) :: buffer))), c.canon, c.hex .. ": round trip") + t:eq(Canon.of(plain(dec(Cbor.encode(v, { compactFloats = true }) :: buffer))), c.canon, c.hex .. ": compact round trip") + end + nApp += 1 +end +t:note("RFC 8949 appendix A: %d examples", nApp) + +for i, c in Fx.safe do + local v, err = dec(c.data) + t:check(v ~= nil, "safe " .. i .. ": " .. tostring(err)) + t:eq(Canon.of(plain(v)), c.canon, "safe " .. i .. ": value") + local b = Cbor.encode(v) :: buffer + t:check(b and buffer.tostring(b) == c.data, "safe " .. i .. ": same bytes") +end +for i, c in Fx.wide do + local v, err = dec(c.data) + t:check(v ~= nil, "wide " .. i .. ": " .. tostring(err)) + t:eq(Canon.of(plain(v)), c.canon, "wide " .. i .. ": value") + t:eq(Canon.of(plain(dec(c.data, { bigInts = "string" }))), c.canonStr, "wide " .. i .. ": exact") +end + +-- details +do + local function hex(b: buffer): string + return (string.gsub(buffer.tostring(b), ".", function(ch) + return string.format("%02x", string.byte(ch)) + end)) + end + t:eq(hex(Cbor.encode(1.5, { compactFloats = true }) :: buffer), "f93e00", "half float") + t:eq(hex(Cbor.encode(100000.0 + 0.5, { compactFloats = true }) :: buffer), "fa47c35040", "single float") + t:eq(hex(Cbor.encode(1.1) :: buffer), "fb3ff199999999999a", "double float") + t:eq(hex(Cbor.encode(-0.0, { compactFloats = true }) :: buffer), "f98000", "negative zero") + t:eq(hex(Cbor.encode(0 / 0, { compactFloats = true }) :: buffer), "f97e00", "nan") + t:eq(hex(Cbor.encode(-2 ^ 64) :: buffer), "3bffffffffffffffff", "-2^64") + t:eq(hex(Cbor.encode(Cbor.tagged(32, "x")) :: buffer), "d8206178", "tagged") + t:eq(hex(Cbor.encode(Cbor.simple(255)) :: buffer), "f8ff", "simple") + t:eq(hex(Cbor.encode(Cbor.undefined) :: buffer), "f7", "undefined") + t:eq(hex(Cbor.encode(Types.Date.parse("2013-03-21T20:04:00Z")) :: buffer), "c074323031332d30332d32315432303a30343a30305a", "date tag 0") + t:eq(hex(Cbor.encode(Types.Date.parse("2013-03-21T20:04:00Z"), { dates = "epoch" }) :: buffer), "c11a514b67b0", "date tag 1") + t:eq(hex(Cbor.encode({ 1 }, { selfDescribe = true }) :: buffer), "d9d9f78101", "self-describe") + t:eq(dec("\217\217\247\1"), 1, "self-describe stripped") + t:eq(Cbor.sniff(Bytes.reader(buffer.fromstring("\217\217\247\1"))), 1, "sniff self-describe") + t:eq(#dec("\1\2\3", { all = true }), 3, "sequence") + t:eq(hex(Cbor.encode({ 1, "a" }, { all = true }) :: buffer), "016161", "encode sequence") + local function code(s: string): string? + local _, e = dec(s) + return e and e.code + end + t:eq(code("\x9b\xff\xff\xff\xff\xff\xff\xff\xff"), Err.TRUNCATED, "huge array count") + t:eq(code("\x5f\x61\x61\xff"), Err.CORRUPT, "text chunk in a byte string") + t:eq(code("\xff"), Err.CORRUPT, "lone break") + t:eq(code("\x1c"), Err.CORRUPT, "reserved additional info") + t:eq(code("\x62\xc3\x28"), Err.CORRUPT, "invalid UTF-8") + t:eq(code("\x01\x02"), Err.CORRUPT, "trailing data") + t:eq(code("\xc0\x01"), Err.CORRUPT, "tag 0 on a number") + t:eq(code(string.rep("\x81", 600) .. "\x01"), Err.LIMIT, "depth") + t:eq(code("\x9f\x01"), Err.TRUNCATED, "unterminated indefinite array") +end + +local samples = {} +for _, c in Fx.appendix do + table.insert(samples, c.data) +end +for i = 1, 40 do + if #Fx.safe[i].data < 3000 then + table.insert(samples, Fx.safe[i].data) + end +end +t:fuzz("decode", function(b: buffer) + return Cbor.decode(Bytes.reader(b)) +end, samples, { mutations = 4 }) +t:done() diff --git a/tests/data/csv.luau b/tests/data/csv.luau new file mode 100644 index 0000000..fd098cf --- /dev/null +++ b/tests/data/csv.luau @@ -0,0 +1,76 @@ +-- data/csv tests: tables written by Python's csv.writer / DictWriter (every delimiter, quotes, line breaks inside +-- fields, empty fields) read back as csv.reader does, re-encoded byte for byte, keyed rows with a header, options, +-- error codes, and the fuzz pass. Fixtures: tools/fixtures/csv.py. +local T = require("@tests/T") +local F = require("@formats") +local Csv = require("@formats/data/csv") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Canon = require("@tests/data/Canon") +local Fx = require("@tests/gen/csv") + +local t = T.suite("data/csv") + +t:eq(Csv.name, "csv", "name") +t:check(Csv.caps.decode and Csv.caps.encode, "caps") + +local function dec(s: string, opts: any?): (any, any) + return Csv.decode(Bytes.reader(buffer.fromstring(s)), opts) +end + +for i, c in Fx do + local rows, err = dec(c.data, { delimiter = c.delimiter }) + t:check(rows ~= nil, "case " .. i .. ": " .. tostring(err)) + t:eq(Canon.of(rows), Canon.of(c.rows), "case " .. i .. ": rows") + local b = Csv.encode(rows, { delimiter = c.delimiter, newline = c.newline }) :: buffer + t:eq(buffer.tostring(b), c.data, "case " .. i .. ": same text") + if c.delimiter ~= "," or i % 3 == 0 then + local auto = dec(c.data, { delimiter = "auto" }) + if c.rows[1] and #c.rows[1] > 1 and auto then + -- auto only has the first line to go on; it must at least split like the real delimiter there + t:check(#auto[1] >= 1, "case " .. i .. ": auto") + end + end + if c.keyed then + local keyed = dec(c.data, { header = true }) :: any + t:eq(#keyed, #c.rows - 1, "case " .. i .. ": keyed row count") + t:eq(table.concat(Types.keys(keyed[1]), "|"), table.concat(c.rows[1], "|"), "case " .. i .. ": column order") + local kb = Csv.encode(keyed) :: buffer + t:eq(buffer.tostring(kb), c.data, "case " .. i .. ": keyed re-encode (DictWriter text)") + end +end + +-- details +do + t:eq(Canon.of(dec("a,b\n\n1,2\r\n3,4\r5,6")), Canon.of({ { "a", "b" }, { "1", "2" }, { "3", "4" }, { "5", "6" } }), "line ends, blank lines") + t:eq(Canon.of(dec('"a""b",c"d,"e"x')), Canon.of({ { 'a"b', 'c"d', "ex" } }), "lenient quotes like Python") + t:eq(Canon.of(dec("a;b|c", { delimiter = "auto" })), Canon.of({ { "a", "b|c" } }), "auto delimiter") + t:eq(Canon.of(dec("x,1.5,-2,1e3,abc, 7 ", { numbers = true })), Canon.of({ { "x", 1.5, -2, 1000, "abc", 7 } }), "numbers") + t:eq(Canon.of(dec("a,b,c\n1,2")[1]), Canon.of({ "a", "b", "c" }), "ragged rows kept") + local k = dec("a,b\n1,2,3\n4", { header = true }) + t:eq(k[1].b, "2", "keyed") + t:eq(k[2].b, nil, "short keyed row") + t:eq(buffer.tostring(Csv.encode({ { 1, true, F.null, 0.5 } }) :: buffer), "1,true,,0.5\r\n", "field types") + t:eq(buffer.tostring(Csv.encode({ { "a", "b" } }, { quoteAll = true, newline = "\n" }) :: buffer), '"a","b"\n', "quoteAll") + t:eq(buffer.tostring(Csv.encode({ { "" } }) :: buffer), '""\r\n', "single empty field quoted") + local _, e = dec('a,"b') + t:eq(e and e.code, Err.TRUNCATED, "unterminated quote") + local _, e2 = dec("a", { delimiter = "ab" }) + t:eq(e2 and e2.code, Err.ARG, "bad delimiter") + local _, e3 = Csv.encode({ { {} } }) + t:eq(e3 and e3.code, Err.ARG, "bad field") + local _, e4 = dec("1\n2\n3", { maxRows = 2 }) + t:eq(e4 and e4.code, Err.LIMIT, "maxRows") + local v = F.load(buffer.fromstring("a,b\r\n1,2\r\n"), { format = "csv", header = true }) + t:eq(v[1].a, "1", "through the API") +end + +local samples = {} +for i = 1, 40 do + table.insert(samples, Fx[i].data) +end +t:fuzz("decode", function(b: buffer) + return Csv.decode(Bytes.reader(b), { delimiter = "auto", header = true, numbers = true }) +end, samples) +t:done() diff --git a/tests/data/ini.luau b/tests/data/ini.luau new file mode 100644 index 0000000..0cf8e6d --- /dev/null +++ b/tests/data/ini.luau @@ -0,0 +1,71 @@ +-- data/ini tests: configs written by Python's configparser read back to configparser's values and re-encoded byte for +-- byte, messy hand-written files read as configparser(strict = false) reads them, options (inline comments, keys +-- without values, types, strict), top-level keys, error codes, and the fuzz pass. Fixtures: tools/fixtures/ini.py. +local T = require("@tests/T") +local Ini = require("@formats/data/ini") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Canon = require("@tests/data/Canon") +local Fx = require("@tests/gen/ini") + +local t = T.suite("data/ini") + +t:eq(Ini.name, "ini", "name") +t:check(Ini.caps.decode and Ini.caps.encode, "caps") + +local function dec(s: string, opts: any?): (any, any) + return Ini.decode(Bytes.reader(buffer.fromstring(s)), opts) +end + +for i, c in Fx.written do + local v, err = dec(c.data) + t:check(v ~= nil, "written " .. i .. ": " .. tostring(err)) + t:eq(Canon.of(v), c.canon, "written " .. i .. ": values") + t:eq(buffer.tostring(Ini.encode(v) :: buffer), c.data, "written " .. i .. ": same text") +end +for i, c in Fx.read do + local v, err = dec(c.data) + t:check(v ~= nil, "messy " .. i .. ": " .. tostring(err)) + t:eq(Canon.of(v), c.canon, "messy " .. i .. ": values") +end + +do + local v = dec("top = 1\n[s]\na = 2 ; c\nflag\nn = 0x10\nb = Yes\n", { inlineComments = true, allowNoValue = true, types = true }) + t:eq(v.top, 1, "top-level key, typed") + t:eq(v.s.a, 2, "inline comment stripped") + t:eq(v.s.flag, true, "key without value") + t:eq(v.s.n, 16, "hex number") + t:eq(v.s.b, true, "yes -> true") + t:eq(table.concat(Types.keys(v), ","), "top,s", "order") + local o = Types.object() + Types.set(o, "name", "x") + local sub = Types.object() + Types.set(sub, "k", "multi\nline") + Types.set(sub, "inner", { z = 1 }) + Types.set(o, "sec", sub) + t:eq(buffer.tostring(Ini.encode(o) :: buffer), "name = x\n\n[sec]\nk = multi\n\tline\n\n[sec.inner]\nz = 1\n\n", "encode nested") + local function code(s: string, opts: any?): string? + local _, e = dec(s, opts) + return e and e.code + end + t:eq(code("[a]\njunk line\n"), Err.CORRUPT, "line without delimiter") + t:eq(code("[a]\nk=1\nk=2\n", { strict = true }), Err.CORRUPT, "strict duplicate key") + t:eq(code("[a]\n[a]\n", { strict = true }), Err.CORRUPT, "strict duplicate section") + t:eq(code("[a]\n= v\n"), Err.CORRUPT, "empty key") + local _, ee = Ini.encode({ ["bad=key"] = "v" }) + t:eq(ee and ee.code, Err.ARG, "unwritable key") + t:eq(Ini.sniff(Bytes.reader(buffer.fromstring("; c\n[section]\nk=v"))), 0.2, "sniff") +end + +local samples = {} +for _, c in Fx.read do + table.insert(samples, c.data) +end +for i = 1, 20 do + table.insert(samples, Fx.written[i].data) +end +t:fuzz("decode", function(b: buffer) + return Ini.decode(Bytes.reader(b), { types = true, inlineComments = true }) +end, samples) +t:done() diff --git a/tests/data/json.luau b/tests/data/json.luau new file mode 100644 index 0000000..b313221 --- /dev/null +++ b/tests/data/json.luau @@ -0,0 +1,71 @@ +-- data/json tests: the contract, the format through the API (F.load / F.save / sniffing), JSON Lines, Python's +-- json.dumps corpus through the format, and the fuzz pass. The codec itself is tested in tests/codecs/json.luau. +-- Fixtures: tools/fixtures/json.py. +local T = require("@tests/T") +local F = require("@formats") +local JsonF = require("@formats/data/json") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Canon = require("@tests/data/Canon") +local Corpus = require("@tests/gen/json_corpus") + +local t = T.suite("data/json") + +t:eq(JsonF.name, "json", "name") +t:eq(JsonF.category, "data", "category") +t:check(JsonF.caps.decode and JsonF.caps.encode, "caps") + +local function dec(s: string, opts: any?): (any, any) + return JsonF.decode(Bytes.reader(buffer.fromstring(s)), opts) +end + +for i, c in Corpus do + local v, err = dec(c.pretty) + t:check(v ~= nil, "corpus " .. i .. ": " .. tostring(err)) + t:eq(Canon.of(v), c.canon, "corpus " .. i) + local b = JsonF.encode(v, { indent = 2 }) :: buffer + t:eq(buffer.tostring(b), c.pretty .. "\n", "corpus " .. i .. ": encode") +end + +-- through the API: sniffed, by name, saved +do + local v, err = F.load(buffer.fromstring('{"a": [1, 2], "b": null}')) + t:check(v ~= nil, "F.load sniffs json: " .. tostring(err)) + t:eq(v.b, F.null, "F.null") + local v2 = F.load(buffer.fromstring("[1, 2]"), { format = "json" }) + t:eq(v2[2], 2, "F.load format = json") + local s = F.saveString({ x = 1, y = { true, false } }, { format = "json" }) + t:eq(s, '{"x":1,"y":[true,false]}', "F.saveString json") + local back = F.data.load(buffer.fromstring(s :: string), { format = "json" }) + t:eq(back.y[1], true, "F.data.load") +end + +-- JSON Lines +do + local v = dec('{"a":1}\n{"a":2}\n\n[3]\n', { lines = true }) + t:eq(#v, 3, "lines decode count") + t:eq(v[2].a, 2, "lines decode value") + local b = JsonF.encode({ { a = 1 }, { 2, 3 } }, { lines = true }) :: buffer + t:eq(buffer.tostring(b), '{"a":1}\n[2,3]\n', "lines encode") + local _, e = dec("1\n[", { lines = true }) + t:eq(e and e.code, Err.TRUNCATED, "lines error") +end + +-- reader range: the data inside a bigger buffer +do + local big = buffer.fromstring("xx[1,2,3]yy") + local v = JsonF.decode(Bytes.reader(big, 2, 7)) + t:eq(#v, 3, "reader range") +end + +t:eq(JsonF.sniff(Bytes.reader(buffer.fromstring(' {"a":1}'))), 0.6, "sniff object") +t:eq(JsonF.sniff(Bytes.reader(buffer.fromstring("hello"))), 0, "sniff text") + +local samples = {} +for i = 1, 30 do + table.insert(samples, Corpus[i].pretty) +end +t:fuzz("decode", function(b: buffer) + return JsonF.decode(Bytes.reader(b)) +end, samples) +t:done() diff --git a/tests/data/msgpack.luau b/tests/data/msgpack.luau new file mode 100644 index 0000000..7b254c3 --- /dev/null +++ b/tests/data/msgpack.luau @@ -0,0 +1,96 @@ +-- data/msgpack tests: values packed by Python's msgpack decode to msgpack's own values (canonical form), re-encode to +-- the same bytes, 64-bit integers as doubles and as exact strings, timestamps / ext, streams, options, error codes, +-- and the fuzz pass. Fixtures: tools/fixtures/msgpack.py. +local T = require("@tests/T") +local Mp = require("@formats/data/msgpack") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Canon = require("@tests/data/Canon") +local Fx = require("@tests/gen/msgpack") + +local t = T.suite("data/msgpack") + +t:eq(Mp.name, "msgpack", "name") +t:check(Mp.caps.decode and Mp.caps.encode, "caps") + +local function dec(s: string | buffer, opts: any?): (any, any) + local b = if type(s) == "string" then buffer.fromstring(s) else s + return Mp.decode(Bytes.reader(b), opts) +end + +-- ext values canonicalise like the fixture's ["ext", code, data] +local function plain(v: any): any + if Mp.isExt(v) then + return { "ext", v.type, v.data } + elseif type(v) == "table" and not Types.Date.is(v) and v ~= Types.null then + local o = if Types.isObject(v) then Types.object() else {} + for k, x in next, v do + o[k] = plain(x) + end + return o + end + return v +end + +for i, c in Fx.safe do + local v, err = dec(c.data) + t:check(v ~= nil, "safe " .. i .. ": " .. tostring(err)) + t:eq(Canon.of(plain(v)), c.canon, "safe " .. i .. ": value") + local b = Mp.encode(v) :: buffer + t:check(b and buffer.tostring(b) == c.data, "safe " .. i .. ": same bytes") +end +for i, c in Fx.wide do + local v, err = dec(c.data) + t:check(v ~= nil, "wide " .. i .. ": " .. tostring(err)) + t:eq(Canon.of(plain(v)), c.canon, "wide " .. i .. ": value") + local vs = dec(c.data, { bigInts = "string" }) + t:eq(Canon.of(plain(vs)), c.canonStr, "wide " .. i .. ": exact big integers") + t:eq(Canon.of(plain(dec(Mp.encode(v) :: buffer))), c.canon, "wide " .. i .. ": round trip") +end + +-- details +do + t:eq(Mp.isExt(dec("\xd4\x05\x07")), true, "fixext1") + local d = dec("\xd6\xff\x00\x00\x00\x00") + t:check(Types.Date.is(d) and tostring(d) == "1970-01-01T00:00:00Z", "timestamp32") + t:eq(dec("\xcf\xff\xff\xff\xff\xff\xff\xff\xff", { bigInts = "string" }), "18446744073709551615", "u64 max text") + t:eq(dec("\xd3\x80\x00\x00\x00\x00\x00\x00\x00", { bigInts = "string" }), "-9223372036854775808", "i64 min text") + t:eq(dec("\xd3\xff\xff\xff\xff\xff\xff\xff\xff"), -1, "i64 -1") + t:eq(buffer.tostring(Mp.encode(-2 ^ 40) :: buffer), "\xd3\xff\xff\xff\x00\x00\x00\x00\x00", "encode i64") + t:eq(buffer.tostring(Mp.encode(1.5, { float32 = true }) :: buffer), "\xca\x3f\xc0\x00\x00", "float32") + t:eq(buffer.tostring(Mp.encode({}) :: buffer), "\x90", "empty table = array") + t:eq(buffer.tostring(Mp.encode({}, { emptyTable = "map" }) :: buffer), "\x80", "emptyTable map") + t:eq(buffer.tostring(Mp.encode(Types.object()) :: buffer), "\x80", "Types.object = map") + t:eq(buffer.tostring(Mp.encode({ b = 1, a = 2 }) :: buffer), "\x82\xa1a\x02\xa1b\x01", "plain keys sorted") + t:eq(buffer.tostring(Mp.encode("ab", { stringsAsBin = true }) :: buffer), "\xc4\x02ab", "stringsAsBin") + t:eq(buffer.tostring(Mp.encode(Mp.ext(3, buffer.fromstring("xyz"))) :: buffer), "\xc7\x03\x03xyz", "ext8") + local all = dec("\x01\x02\xa1x", { all = true }) + t:eq(#all, 3, "stream") + t:eq(buffer.tostring(Mp.encode({ 1, "x" }, { all = true }) :: buffer), "\x01\xa1x", "encode stream") + t:eq(dec("\xc0"), Types.null, "nil -> null") + local cyc = {} + cyc[1] = cyc + local _, ce = Mp.encode(cyc) + t:eq(ce and ce.code, Err.ARG, "cycle") + local function code(s: string, o: any?): string? + local _, e = dec(s, o) + return e and e.code + end + t:eq(code("\xdd\xff\xff\xff\xff"), Err.TRUNCATED, "huge array count") + t:eq(code("\xa5ab"), Err.TRUNCATED, "short string") + t:eq(code("\xc1"), Err.CORRUPT, "reserved byte") + t:eq(code("\x01\x02"), Err.CORRUPT, "trailing data") + t:eq(code(string.rep("\x91", 600) .. "\x01"), Err.LIMIT, "depth") +end + +local samples = {} +for i = 5, 60 do + if #Fx.safe[i].data < 3000 then + table.insert(samples, Fx.safe[i].data) + end +end +t:fuzz("decode", function(b: buffer) + return Mp.decode(Bytes.reader(b)) +end, samples) +t:done() diff --git a/tests/data/plist.luau b/tests/data/plist.luau new file mode 100644 index 0000000..231a20f --- /dev/null +++ b/tests/data/plist.luau @@ -0,0 +1,86 @@ +-- data/plist tests: values written by Python's plistlib as XML and binary decode to plistlib's values; our XML writer +-- reproduces plistlib's XML byte for byte; binary-only values (UIDs, 64-bit integers); a hand-written XML plist; +-- error codes; the fuzz pass (XML and binary). Fixtures: tools/fixtures/plist.py. +local T = require("@tests/T") +local F = require("@formats") +local Plist = require("@formats/data/plist") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Canon = require("@tests/data/Canon") +local Fx = require("@tests/gen/plist") + +local t = T.suite("data/plist") + +t:eq(Plist.name, "plist", "name") +t:check(Plist.caps.decode and Plist.caps.encode, "caps") + +local function dec(s: string, opts: any?): (any, any) + return Plist.decode(Bytes.reader(buffer.fromstring(s)), opts) +end +local function plain(v: any): any + if Plist.isUid(v) then + return { "uid", v.uid } + elseif type(v) == "table" and not Types.Date.is(v) then + local o = if Types.isObject(v) then Types.object() else {} + for k, x in next, v do + o[k] = plain(x) + end + return o + end + return v +end + +for i, c in Fx.cases do + local v, err = dec(c.xml) + t:check(v ~= nil, "xml " .. i .. ": " .. tostring(err)) + t:eq(Canon.of(v), c.canon, "xml " .. i .. ": value") + local vb, berr = dec(c.binary) + t:check(vb ~= nil, "binary " .. i .. ": " .. tostring(berr)) + t:eq(Canon.of(vb), c.canon, "binary " .. i .. ": value") + t:eq(buffer.tostring(Plist.encode(v) :: buffer), c.xml, "xml " .. i .. ": same text as plistlib") +end +for i, c in Fx.wide do + local v, err = dec(c.binary) + t:check(v ~= nil, "wide " .. i .. ": " .. tostring(err)) + t:eq(Canon.of(plain(v)), c.canon, "wide " .. i .. ": value") +end +do + local v = dec(Fx.extra) + t:eq(Canon.of(v), Fx.extraCanon, "hand-written plist") + t:eq(v.hex, 31, "hex integer") + local f = F.load(buffer.fromstring(Fx.cases[1].binary)) + t:check(f ~= nil, "F.load sniffs binary plists") + local fx = F.load(buffer.fromstring(Fx.cases[1].xml)) + t:eq(Canon.of(fx), Fx.cases[1].canon, "F.load sniffs XML plists over plain XML") + t:eq(dec("<plist><string>x</string></plist>"), "x", "bare root value") + local function code(s: string): string? + local _, e = dec(s) + return e and e.code + end + t:eq(code("<plist><dict><key>a</key></dict></plist>"), Err.CORRUPT, "key without value") + t:eq(code("<plist><integer>x</integer></plist>"), Err.CORRUPT, "bad integer") + t:eq(code("<plist><data>!!</data></plist>"), Err.CORRUPT, "bad base64") + t:eq(code("<plist><foo/></plist>"), Err.CORRUPT, "unknown element") + t:eq(code("bplist00"), Err.TRUNCATED, "short binary") + local _, ne = Plist.encode({ a = F.null }) + t:eq(ne and ne.code, Err.ARG, "null cannot be written") + local _, ke = Plist.encode({ [1] = 1, x = 2 }) + t:eq(ke and ke.code, Err.ARG, "non-string key") + -- a binary plist with a cycle: array 0 -> [array 0] + local cyc = "bplist00" .. "\xa1\x00" .. "\x08" .. string.rep("\0", 6) .. "\1\1" .. "\0\0\0\0\0\0\0\1" .. "\0\0\0\0\0\0\0\0" .. "\0\0\0\0\0\0\0\10" + t:eq(code(cyc), Err.CORRUPT, "reference cycle") +end + +local samples = {} +for i = 1, 25 do + table.insert(samples, Fx.cases[i].xml) + table.insert(samples, Fx.cases[i].binary) +end +t:fuzz("decode", function(b: buffer) + return Plist.decode(Bytes.reader(b)) +end, samples, { keepHeader = 0 }) +t:fuzz("decode binary (header kept)", function(b: buffer) + return Plist.decode(Bytes.reader(b)) +end, { Fx.cases[3].binary, Fx.cases[4].binary, Fx.wide[1].binary }, { keepHeader = 8, mutations = 200, garbage = 0 }) +t:done() diff --git a/tests/data/toml.luau b/tests/data/toml.luau new file mode 100644 index 0000000..4e2babc --- /dev/null +++ b/tests/data/toml.luau @@ -0,0 +1,121 @@ +-- data/toml tests: the toml-test suite's TOML 1.0 files (every valid/ case decodes to its expected value, every +-- invalid/ case fails), a tomli-w corpus against Python's tomllib, encoder round trips (decode(encode(v)) is the same +-- value) and exact encoder output, options, error codes, the contract and the fuzz pass. Fixtures: tools/fixtures/toml.py. +local T = require("@tests/T") +local Toml = require("@formats/data/toml") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Canon = require("@tests/data/Canon") +local Suite = require("@tests/gen/toml_suite") +local Corpus = require("@tests/gen/toml_corpus") + +local t = T.suite("data/toml") + +t:eq(Toml.name, "toml", "name") +t:eq(Toml.category, "data", "category") +t:check(Toml.caps.decode and Toml.caps.encode, "caps") + +local function dec(s: string, opts: any?): (any, any) + return Toml.decode(Bytes.reader(buffer.fromstring(s)), opts) +end +local function enc(v: any, opts: any?): (string?, any) + local b, e = Toml.encode(v, opts) + return if b then buffer.tostring(b) else nil, e +end + +-- 1. toml-test +local nv, ni, rt = 0, 0, 0 +for _, c in Suite do + local v, err = dec(c.data) + if c.valid then + t:check(v ~= nil, c.name .. ": parses (" .. tostring(err) .. ")") + t:eq(Canon.of(v), c.canon, c.name .. ": value") + -- the encoder's output reads back as the same value (floats that are integral become integers, so compare + -- the decoded values, not the toml-test canon) + local s, eerr = enc(v) + t:check(s ~= nil, c.name .. ": encodes (" .. tostring(eerr) .. ")") + local back, berr = dec(s :: string) + t:check(back ~= nil, c.name .. ": re-decodes (" .. tostring(berr) .. ")\n" .. tostring(s)) + t:eq(Canon.of(back), Canon.of(v), c.name .. ": round trip") + nv += 1 + rt += 1 + else + t:check(v == nil and Err.is(err), c.name .. ": rejected") + ni += 1 + end +end +t:note("toml-test 1.0: %d valid decoded and round-tripped, %d invalid rejected", nv, ni) + +-- 2. tomli-w corpus vs tomllib +for i, c in Corpus do + local v, err = dec(c.data) + t:check(v ~= nil, "corpus " .. i .. ": " .. tostring(err)) + t:eq(Canon.of(v), c.canon, "corpus " .. i .. ": value") + local s = enc(v) :: string + t:eq(Canon.of(dec(s)), c.canon, "corpus " .. i .. ": round trip") + t:eq(Canon.of(dec(enc(v, { inline = true }) :: string)), c.canon, "corpus " .. i .. ": inline round trip") +end + +-- 3. API details +do + local v = dec('z = 1\na = 2\n[t]\ny = "x"\nb = 1979-05-27T07:32:00.5-07:00\n[[arr]]\nk = 1\n[[arr]]\nk = 2\n') + t:eq(table.concat(Types.keys(v), ","), "z,a,t,arr", "key order") + t:check(Types.Date.is(v.t.b) and v.t.b.kind == "datetime" and v.t.b.offset == -420, "datetime value") + t:eq(tostring(v.t.b), "1979-05-27T07:32:00.5-07:00", "datetime text") + t:eq(v.arr[2].k, 2, "array of tables") + t:eq(enc(v), 'z = 1\na = 2\n\n[t]\ny = "x"\nb = 1979-05-27T07:32:00.5-07:00\n\n[[arr]]\nk = 1\n\n[[arr]]\nk = 2\n', "encode text") + t:eq(enc({ b = { 1, 2.5, "s" }, a = { x = true } }), 'b = [1, 2.5, "s"]\n\n[a]\nx = true\n', "plain tables: scalars first, sorted") + t:eq(enc({ ["a b"] = "q\"\n\1" }), '"a b" = "q\\"\\n\\u0001"\n', "key / string escapes") + t:eq(enc({ a = { x = 1 } }, { inline = true }), "a = { x = 1 }\n", "inline option") + t:eq(enc({ f = 0 / 0, g = math.huge, h = 1e300, i = -0.5 }), "f = nan\ng = inf\nh = 1e+300\ni = -0.5\n", "floats") + t:eq(enc({ a = { b = { c = 1 } } }, { indent = 2 }), "[a]\n\n [a.b]\n c = 1\n", "indent") + local big = dec("a = 9223372036854775807\nb = 0x7fffffffffffffff\nc = 12", { bigInts = "string" }) + t:eq(big.a, "9223372036854775807", "bigInts string") + t:eq(big.b, "0x7fffffffffffffff", "bigInts string hex") + t:eq(big.c, 12, "small ints stay numbers") + t:eq(dec("a = 9223372036854775807").a, 9223372036854775807, "bigInts number") + local _, e1 = enc({ a = Types.null }) + t:eq(e1 and e1.code, Err.ARG, "null is an error") + local cyc = {} + cyc.self = cyc + local _, e2 = enc(cyc) + t:eq(e2 and e2.code, Err.ARG, "cycle is an error") + local _, e3 = enc({ 1, 2 }) + t:eq(e3 and e3.code, Err.ARG, "top level must be a table") + local _, e4 = enc({ [1] = 1, x = 2 }) + t:eq(e4 and e4.code, Err.ARG, "non-string key") +end + +-- 4. errors +local function code(s: string): (string?, number?) + local _, e = dec(s) + return e and e.code, e and e.offset +end +t:eq(code('a = "abc'), Err.TRUNCATED, "unterminated string") +t:eq(code("a = 1\na = 2"), Err.CORRUPT, "duplicate key") +t:eq(code("[a]\n[a]"), Err.CORRUPT, "duplicate table") +t:eq(code("a = 01"), Err.CORRUPT, "leading zero") +t:eq(code("a = 9223372036854775808"), Err.CORRUPT, "int64 overflow") +t:eq(select(2, code("x = 1\na = tru")), 10, "error offset") +t:eq(Toml.sniff(Bytes.reader(buffer.fromstring("# c\n[server]\nport = 80\n"))), 0.2, "sniff") +t:eq(Toml.sniff(Bytes.reader(buffer.fromstring("{\"a\": 1}"))), 0, "sniff json") + +-- 5. fuzz +local samples = {} +for _, c in Suite do + if c.valid and #samples < 80 and #c.data < 400 then + table.insert(samples, c.data) + end +end +for i = 1, 20 do + table.insert(samples, Corpus[i].data) +end +t:fuzz("decode", function(b: buffer) + return Toml.decode(Bytes.reader(b)) +end, samples) +t:fuzz("encode(decode)", function(b: buffer) + local v = Toml.decode(Bytes.reader(b)) + return v and Toml.encode(v) +end, samples, { garbage = 20 }) +t:done() diff --git a/tests/data/xml.luau b/tests/data/xml.luau new file mode 100644 index 0000000..6edbe02 --- /dev/null +++ b/tests/data/xml.luau @@ -0,0 +1,49 @@ +-- data/xml tests: the contract, the format through the API (F.load / F.save / sniffing), documents from Python's +-- ElementTree fixtures decoded and re-encoded through the format, and the fuzz pass. The codec itself is tested in +-- tests/codecs/xml.luau. Fixtures: tools/fixtures/xml.py. +local T = require("@tests/T") +local F = require("@formats") +local XmlF = require("@formats/data/xml") +local Xml = require("@formats/codecs/Xml") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Docs = require("@tests/gen/xml_docs") + +local t = T.suite("data/xml") + +t:eq(XmlF.name, "xml", "name") +t:eq(XmlF.category, "data", "category") +t:check(XmlF.caps.decode and XmlF.caps.encode, "caps") + +for i = 1, 60 do + local d = Docs[i] + local doc, err = XmlF.decode(Bytes.reader(buffer.fromstring(d.data)), { comments = true, cdata = true, whitespace = true }) + t:check(doc ~= nil, "doc " .. i .. ": " .. tostring(err)) + local b, eerr = XmlF.encode(doc :: any) + t:check(b ~= nil, "doc " .. i .. ": encode " .. tostring(eerr)) + local again = XmlF.decode(Bytes.reader(b :: buffer), { comments = true, cdata = true, whitespace = true }) + t:check(again ~= nil, "doc " .. i .. ": re-decode") + t:eq(Xml.text((again :: any).root), Xml.text((doc :: any).root), "doc " .. i .. ": same text") +end + +do + local doc, err = F.load(buffer.fromstring('<?xml version="1.0"?><r><a k="v">t</a></r>')) + t:check(doc ~= nil, "F.load sniffs xml: " .. tostring(err)) + t:eq(doc.root.name, "r", "root") + local s = F.saveString(doc, { format = "xml" }) + t:eq(s, '<?xml version="1.0" encoding="UTF-8"?>\n<r><a k="v">t</a></r>', "F.saveString") + local _, e = XmlF.encode(5 :: any) + t:eq(e and e.code, Err.ARG, "encode argument check") + local _, e2 = F.load(buffer.fromstring("<r><a></r>"), { format = "xml" }) + t:eq(e2 and e2.code, Err.CORRUPT, "error through the API") + t:eq(e2 and e2.format, "xml", "error tagged with the format") +end + +local samples = {} +for i = 1, 30 do + table.insert(samples, Docs[i].data) +end +t:fuzz("decode", function(b: buffer) + return XmlF.decode(Bytes.reader(b)) +end, samples) +t:done() diff --git a/tests/data/yaml.luau b/tests/data/yaml.luau new file mode 100644 index 0000000..e804e39 --- /dev/null +++ b/tests/data/yaml.luau @@ -0,0 +1,198 @@ +-- data/yaml tests: the yaml-test-suite (every case with an in.json must decode to it, every error case must be +-- rejected, the valid cases without JSON must decode), a random corpus dumped by PyYAML in five styles (block, flow, +-- indent 4 with explicit markers, sorted / narrow, multi-document) compared with Python's values, encoder round trips, +-- options, errors and limits, the API, and the fuzz pass. Fixtures: tools/fixtures/yaml.py. +local T = require("@tests/T") +local F = require("@formats") +local Yaml = require("@formats/data/yaml") +local Json = require("@formats/codecs/Json") +local Types = require("@formats/Types") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Canon = require("@tests/data/Canon") +local Suite = require("@tests/gen/yaml_suite") +local Corpus = require("@tests/gen/yaml_corpus") + +local t = T.suite("data/yaml") + +t:eq(Yaml.name, "yaml", "name") +t:eq(Yaml.category, "data", "category") +t:check(Yaml.caps.decode and Yaml.caps.encode, "caps") + +local function dec(s: string, opts: any?): (any, any) + return Yaml.decode(Bytes.reader(buffer.fromstring(s)), opts) +end +local function enc(v: any, opts: any?): string? + local b = Yaml.encode(v, opts) + return if b then buffer.tostring(b) else nil +end + +-- 1. yaml-test-suite +local SKIP = { -- !!binary decodes to a buffer; the suite's JSON keeps the base64 text + ["565N"] = true, + ["name/construct-binary"] = true, +} +local pass, valid, rejected, errors, other, otherOk = 0, 0, 0, 0, 0, 0 +for _, c in Suite do + local v, e = dec(c.yaml, { all = true, tags = "ignore" }) + t:check(e == nil or not string.find(e.message, "internal error", 1, true), c.name .. ": " .. tostring(e)) + if c.error then + errors += 1 + t:check(v == nil, c.name .. ": an error case is rejected") + rejected += if v == nil then 1 else 0 + elseif c.json and not SKIP[c.name] then + valid += 1 + t:check(v ~= nil, c.name .. ": decodes (" .. tostring(e) .. ")") + local want = {} + for _, x in Json.lines(c.json) do + table.insert(want, Canon.of(x)) + end + local got = {} + for _, d in v do + local s = Json.encode(d, { nan = "null" }) + table.insert(got, if s then Canon.of(Json.decode(s)) else "?") + end + t:eq(table.concat(got, "|"), table.concat(want, "|"), c.name .. ": value") + pass += 1 + elseif not c.json then + other += 1 + otherOk += if v ~= nil or (e and e.code == Err.UNSUPPORTED) then 1 else 0 + end +end +t:note("yaml-test-suite: %d of %d JSON cases match, %d of %d error cases rejected, %d of %d other valid cases decode or say UNSUPPORTED", pass, valid, rejected, errors, otherOk, other) +t:check(otherOk == other, "valid cases without JSON never fail as CORRUPT") + +-- 2. PyYAML's output in five styles +for i, c in Corpus do + for style, text in c.texts do + if style == "multi" then + local v, e = dec(text, { all = true }) + t:check(v ~= nil, "corpus " .. i .. " " .. style .. ": " .. tostring(e)) + t:eq(Canon.of(v), c.multi, "corpus " .. i .. " " .. style) + else + local v, e = dec(text) + t:check(v ~= nil or e == nil, "corpus " .. i .. " " .. style .. ": " .. tostring(e)) + t:eq(Canon.of(v), c.canon, "corpus " .. i .. " " .. style) + end + end + -- our own output reads back the same (indent 2 and 4, explicit start) + local v = dec(c.texts.block) + for _, o in { {}, { indent = 4 }, { explicitStart = true } } do + local s = enc(v, o) + t:check(s ~= nil, "corpus " .. i .. ": encodes") + t:eq(Canon.of(dec(s :: string)), c.canon, "corpus " .. i .. ": round trip " .. tostring(s)) + end + local m = dec(c.texts.multi, { all = true }) + t:eq(Canon.of(dec(enc(m, { all = true }) :: string, { all = true })), c.multi, "corpus " .. i .. ": multi round trip") +end + +-- 3. details +do + local v = dec("b: 1\na: 2\nc: {}\nd: []\ne:\nf: ~\n") + t:eq(table.concat(Types.keys(v), ","), "b,a,c,d,e,f", "key order") + t:check(Types.isObject(v.c), "empty flow map is an object") + t:eq(v.e, Types.null, "empty value is null") + t:eq(enc(v), "b: 1\na: 2\nc: {}\nd: []\ne: null\nf: null\n", "encode keeps the order") + local s = dec("a: &x [1, 2]\nb: *x\n") + t:check(s.a == s.b, "aliases are shared references") + t:eq(enc(s), "a: &id001\n - 1\n - 2\nb: *id001\n", "shared tables get anchors") + local n = dec("[0o17, 0x1F, +12, -0.5e1, .5, .inf, -.Inf, .nan, 1_000, 0b11, yes, ~, Null, TRUE]") + t:eq(n[1], 15, "0o") + t:eq(n[2], 31, "0x") + t:eq(n[3], 12, "+int") + t:eq(n[4], -5, "float exp") + t:eq(n[5], 0.5, ".5") + t:eq(n[6], math.huge, ".inf") + t:eq(n[7], -math.huge, "-.Inf") + t:check(n[8] ~= n[8], ".nan") + t:eq(n[9], "1_000", "1.1 ints are strings") + t:eq(n[10], "0b11", "0b is a string") + t:eq(n[11], "yes", "yes is a string") + t:eq(n[12], Types.null, "~") + t:eq(n[13], Types.null, "Null") + t:eq(n[14], true, "TRUE") + local tg = dec("a: !!str 12\nb: !!float 3\nc: !!binary aGVsbG8=\nd: !!timestamp 2001-12-14T21:59:43Z\ne: !!int '7'\n") + t:eq(tg.a, "12", "!!str") + t:eq(tg.b, 3, "!!float") + t:eq(buffer.tostring(tg.c), "hello", "!!binary") + t:check(Types.Date.is(tg.d), "!!timestamp") + t:eq(tg.e, 7, "!!int on a quoted scalar") + local _, te = dec("a: !custom x") + t:eq(te and te.code, Err.UNSUPPORTED, "unknown tags are UNSUPPORTED") + t:eq(dec("a: !custom x", { tags = "ignore" }).a, "x", "tags = ignore") + t:eq(dec("--- 1\n--- 2\n"), 1, "the first document") + t:eq(#dec("--- 1\n--- 2\n", { all = true }), 2, "all documents") + t:eq(dec(""), Types.null, "empty stream") + t:eq(dec("k: |\n a\n b\n\nz: >+\n f\n g\n\n").k, "a\nb\n", "literal") + t:eq(dec("k: |\n a\n b\n\nz: >+\n f\n g\n\n").z, "f g\n\n", "folded keep") + t:eq(dec("? a\n: b\n").a, "b", "explicit key") + t:eq(dec("[a: 1, {b: 2}]")[1].a, 1, "single-pair flow mapping") + -- strings that need quoting survive + for _, str in { "", "true", "null", "12", "1.5", "- x", "a: b", "# c", "x #y", " lead", "tail ", "multi\nline", "two\n\n", "\ttab", "é", "\0\1", "'", '"', "yes", "on", "~", "[", "@", "&a", "*a", "!t", "%", "---", "...", "a\u{2028}b", ".inf", "0x10", "0o7", "-", "?", ":" } do + local v2 = dec(enc({ k = str }) :: string) + t:eq(v2 and v2.k, str, "string round trip " .. string.format("%q", str)) + end + for _, x in { 0.1, -2.5e-8, 1e300, 2 ^ 53, -0.0, 123456789, math.huge, -math.huge } do + t:eq(dec(enc({ x }) :: string)[1], x, "number round trip " .. tostring(x)) + end + local cyc = {} + cyc.self = cyc + local _, ce = Yaml.encode(cyc) + t:eq(ce and ce.code, Err.ARG, "cycles are an error") + local _, fe = Yaml.encode({ f = print }) + t:eq(fe and fe.code, Err.ARG, "functions are an error") + t:eq(enc(buffer.fromstring("hi")), "!!binary aGk=\n", "buffers as !!binary") +end + +-- 4. errors and limits +local function code(s: string, opts: any?): string? + local _, e = dec(s, opts) + return e and e.code +end +t:eq(code("a: [1, 2"), Err.TRUNCATED, "unterminated flow") +t:eq(code('a: "x'), Err.TRUNCATED, "unterminated quote") +t:eq(code("a: b: c"), Err.CORRUPT, "mapping on its key's line") +t:eq(code("a: *nope"), Err.CORRUPT, "undefined alias") +t:eq(code("a:\n b: 1\n c: 2"), Err.CORRUPT, "bad indentation") +t:eq(code("[[1]]: x"), Err.UNSUPPORTED, "collection keys") +t:eq(code(string.rep("[", 600) .. string.rep("]", 600)), Err.LIMIT, "depth limit") +do + local bomb = { "a: &a [x, x, x, x, x, x, x, x, x, x]" } + for i = 2, 8 do + local prev = string.char(96 + i - 1) + table.insert(bomb, string.format("%s: &%s [*%s, *%s, *%s, *%s, *%s, *%s, *%s, *%s, *%s, *%s]", string.char(96 + i), string.char(96 + i), prev, prev, prev, prev, prev, prev, prev, prev, prev, prev)) + end + t:eq(code(table.concat(bomb, "\n")), Err.LIMIT, "alias bomb") + t:check(dec(table.concat(bomb, "\n", 1, 3)) ~= nil, "small alias trees are fine") +end +do + local _, e = dec("a: 1\nb: [1, }\n") + t:eq(e and e.offset, 12, "error offset") +end + +-- 5. API +do + local v, err = F.load(buffer.fromstring("---\nname: x\nlist:\n - 1\n")) + t:check(v ~= nil, "F.load sniffs yaml: " .. tostring(err)) + t:eq(v.list[1], 1, "F.load value") + t:eq(F.saveString(v, { format = "yaml" }), "name: x\nlist:\n - 1\n", "F.saveString yaml") +end + +local samples = {} +for i = 1, 30 do + table.insert(samples, Corpus[i].texts.block) + table.insert(samples, Corpus[i].texts.flow) +end +for i = 1, 400, 7 do + if Suite[i] then + table.insert(samples, Suite[i].yaml) + end +end +t:fuzz("decode", function(b: buffer) + return Yaml.decode(Bytes.reader(b), { all = true }) +end, samples) +t:fuzz("encode(decode)", function(b: buffer) + local v = Yaml.decode(Bytes.reader(b)) + return v and Yaml.encode(v) +end, samples, { garbage = 20 }) +t:done() diff --git a/tests/fixtures/gltf/AnimatedMorphCube/LICENSE.md b/tests/fixtures/gltf/AnimatedMorphCube/LICENSE.md new file mode 100644 index 0000000..ae8546c --- /dev/null +++ b/tests/fixtures/gltf/AnimatedMorphCube/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Animated Morph Cube + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Zero v1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/legalcode) [SPDX license identifier: "CC0-1.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + +<!-- This file is auto-generated by modelmetadata. Do not edit by hand. --> diff --git a/tests/fixtures/gltf/AnimatedMorphCube/glTF-Quantized/AnimatedMorphCube.bin b/tests/fixtures/gltf/AnimatedMorphCube/glTF-Quantized/AnimatedMorphCube.bin new file mode 100644 index 0000000..7520d98 Binary files /dev/null and b/tests/fixtures/gltf/AnimatedMorphCube/glTF-Quantized/AnimatedMorphCube.bin differ diff --git a/tests/fixtures/gltf/AnimatedMorphCube/glTF-Quantized/AnimatedMorphCube.gltf b/tests/fixtures/gltf/AnimatedMorphCube/glTF-Quantized/AnimatedMorphCube.gltf new file mode 100644 index 0000000..870695e --- /dev/null +++ b/tests/fixtures/gltf/AnimatedMorphCube/glTF-Quantized/AnimatedMorphCube.gltf @@ -0,0 +1,259 @@ +{ + "buffers":[ + { + "uri":"AnimatedMorphCube.bin", + "byteLength":1700 + } + ], + "asset":{ + "version":"2.0", + "generator":"gltfpack 0.13" + }, + "extensionsUsed":[ + "KHR_mesh_quantization" + ], + "extensionsRequired":[ + "KHR_mesh_quantization" + ], + "bufferViews":[ + { + "buffer":0, + "byteOffset":0, + "byteLength":288, + "byteStride":4, + "target":34962 + }, + { + "buffer":0, + "byteOffset":288, + "byteLength":576, + "byteStride":8, + "target":34962 + }, + { + "buffer":0, + "byteOffset":864, + "byteLength":72, + "target":34963 + }, + { + "buffer":0, + "byteOffset":936, + "byteLength":508 + }, + { + "buffer":0, + "byteOffset":1444, + "byteLength":254 + } + ], + "accessors":[ + { + "bufferView":0, + "byteOffset":0, + "componentType":5120, + "count":24, + "type":"VEC3", + "normalized":true + }, + { + "bufferView":1, + "byteOffset":0, + "componentType":5123, + "count":24, + "type":"VEC3", + "min":[ + 0, + 5451, + 0 + ], + "max":[ + 5481, + 10932, + 5481 + ] + }, + { + "bufferView":0, + "byteOffset":96, + "componentType":5120, + "count":24, + "type":"VEC3", + "normalized":true + }, + { + "bufferView":1, + "byteOffset":192, + "componentType":5122, + "count":24, + "type":"VEC3", + "min":[ + 0, + 0, + 0 + ], + "max":[ + 0, + 5188, + 0 + ] + }, + { + "bufferView":0, + "byteOffset":192, + "componentType":5120, + "count":24, + "type":"VEC3", + "normalized":true + }, + { + "bufferView":1, + "byteOffset":384, + "componentType":5122, + "count":24, + "type":"VEC3", + "min":[ + 0, + 0, + 0 + ], + "max":[ + 0, + 5451, + 0 + ] + }, + { + "bufferView":2, + "byteOffset":0, + "componentType":5123, + "count":36, + "type":"SCALAR" + }, + { + "bufferView":3, + "byteOffset":0, + "componentType":5126, + "count":127, + "type":"SCALAR", + "min":[ + 0 + ], + "max":[ + 4.19999981 + ] + }, + { + "bufferView":4, + "byteOffset":0, + "componentType":5121, + "count":254, + "type":"SCALAR", + "normalized":true + } + ], + "materials":[ + { + "name":"Material", + "pbrMetallicRoughness":{ + "baseColorFactor":[ + 0.603827417, + 0.603827417, + 0.603827417, + 1 + ], + "metallicFactor":0, + "roughnessFactor":0.5 + } + } + ], + "meshes":[ + { + "primitives":[ + { + "attributes":{ + "NORMAL":0, + "POSITION":1 + }, + "mode":4, + "targets":[ + { + "NORMAL":2, + "POSITION":3 + }, + { + "NORMAL":4, + "POSITION":5 + } + ], + "indices":6, + "material":0 + } + ], + "weights":[ + 0, + 0 + ] + } + ], + "animations":[ + { + "name":"Square", + "samplers":[ + { + "input":7, + "output":8 + } + ], + "channels":[ + { + "sampler":0, + "target":{ + "node":0, + "path":"weights" + } + } + ] + } + ], + "nodes":[ + { + "mesh":0, + "translation":[ + -0.0100000044, + -0.0298908409, + -0.00999999978 + ], + "scale":[ + 3.64900689e-06, + 3.64900689e-06, + 3.64900689e-06 + ] + }, + { + "name":"AnimatedMorphCube", + "rotation":[ + 0, + 0.707106709, + -0.707106829, + 0 + ], + "scale":[ + 100, + 100, + 100 + ], + "children":[ + 0 + ] + } + ], + "scenes":[ + { + "nodes":[ + 1 + ] + } + ], + "scene":0 +} \ No newline at end of file diff --git a/tests/fixtures/gltf/AnimatedTriangle/LICENSE.md b/tests/fixtures/gltf/AnimatedTriangle/LICENSE.md new file mode 100644 index 0000000..e940ed1 --- /dev/null +++ b/tests/fixtures/gltf/AnimatedTriangle/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Animated Triangle + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Zero v1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/legalcode) [SPDX license identifier: "CC0-1.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + +<!-- This file is auto-generated by modelmetadata. Do not edit by hand. --> diff --git a/tests/fixtures/gltf/AnimatedTriangle/glTF/AnimatedTriangle.gltf b/tests/fixtures/gltf/AnimatedTriangle/glTF/AnimatedTriangle.gltf new file mode 100644 index 0000000..b7b1e25 --- /dev/null +++ b/tests/fixtures/gltf/AnimatedTriangle/glTF/AnimatedTriangle.gltf @@ -0,0 +1,118 @@ +{ + "scene" : 0, + "scenes" : [ + { + "nodes" : [ 0 ] + } + ], + + "nodes" : [ + { + "mesh" : 0, + "rotation" : [ 0.0, 0.0, 0.0, 1.0 ] + } + ], + + "meshes" : [ + { + "primitives" : [ { + "attributes" : { + "POSITION" : 1 + }, + "indices" : 0 + } ] + } + ], + + "animations": [ + { + "samplers" : [ + { + "input" : 2, + "interpolation" : "LINEAR", + "output" : 3 + } + ], + "channels" : [ { + "sampler" : 0, + "target" : { + "node" : 0, + "path" : "rotation" + } + } ] + } + ], + + "buffers" : [ + { + "uri" : "AnimatedTriangle_geometry.bin", + "byteLength" : 44 + }, + { + "uri" : "AnimatedTriangle_animation.bin", + "byteLength" : 100 + } + ], + "bufferViews" : [ + { + "buffer" : 0, + "byteOffset" : 0, + "byteLength" : 6, + "target" : 34963 + }, + { + "buffer" : 0, + "byteOffset" : 8, + "byteLength" : 36, + "target" : 34962 + }, + { + "buffer" : 1, + "byteOffset" : 0, + "byteLength" : 100 + } + ], + "accessors" : [ + { + "bufferView" : 0, + "byteOffset" : 0, + "componentType" : 5123, + "count" : 3, + "type" : "SCALAR", + "max" : [ 2 ], + "min" : [ 0 ] + }, + { + "bufferView" : 1, + "byteOffset" : 0, + "componentType" : 5126, + "count" : 3, + "type" : "VEC3", + "max" : [ 1.0, 1.0, 0.0 ], + "min" : [ 0.0, 0.0, 0.0 ] + }, + { + "bufferView" : 2, + "byteOffset" : 0, + "componentType" : 5126, + "count" : 5, + "type" : "SCALAR", + "max" : [ 1.0 ], + "min" : [ 0.0 ] + }, + { + "bufferView" : 2, + "byteOffset" : 20, + "componentType" : 5126, + "count" : 5, + "type" : "VEC4", + "max" : [ 0.0, 0.0, 1.0, 1.0 ], + "min" : [ 0.0, 0.0, 0.0, -0.707 ] + } + ], + + "asset" : { + "version" : "2.0" + } + +} diff --git a/tests/fixtures/gltf/AnimatedTriangle/glTF/AnimatedTriangle_animation.bin b/tests/fixtures/gltf/AnimatedTriangle/glTF/AnimatedTriangle_animation.bin new file mode 100644 index 0000000..fa20e9f Binary files /dev/null and b/tests/fixtures/gltf/AnimatedTriangle/glTF/AnimatedTriangle_animation.bin differ diff --git a/tests/fixtures/gltf/AnimatedTriangle/glTF/AnimatedTriangle_geometry.bin b/tests/fixtures/gltf/AnimatedTriangle/glTF/AnimatedTriangle_geometry.bin new file mode 100644 index 0000000..d642500 Binary files /dev/null and b/tests/fixtures/gltf/AnimatedTriangle/glTF/AnimatedTriangle_geometry.bin differ diff --git a/tests/fixtures/gltf/AnisotropyStrengthTest/LICENSE.md b/tests/fixtures/gltf/AnisotropyStrengthTest/LICENSE.md new file mode 100644 index 0000000..329c208 --- /dev/null +++ b/tests/fixtures/gltf/AnisotropyStrengthTest/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Anisotropy Strength Test + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Zero v1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/legalcode) [SPDX license identifier: "CC0-1.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + +<!-- This file is auto-generated by modelmetadata. Do not edit by hand. --> diff --git a/tests/fixtures/gltf/AnisotropyStrengthTest/glTF-Binary/AnisotropyStrengthTest.glb b/tests/fixtures/gltf/AnisotropyStrengthTest/glTF-Binary/AnisotropyStrengthTest.glb new file mode 100644 index 0000000..6161291 Binary files /dev/null and b/tests/fixtures/gltf/AnisotropyStrengthTest/glTF-Binary/AnisotropyStrengthTest.glb differ diff --git a/tests/fixtures/gltf/AttenuationTest/LICENSE.md b/tests/fixtures/gltf/AttenuationTest/LICENSE.md new file mode 100644 index 0000000..4329dc8 --- /dev/null +++ b/tests/fixtures/gltf/AttenuationTest/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Attenuation Test + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + +<!-- This file is auto-generated by modelmetadata. Do not edit by hand. --> diff --git a/tests/fixtures/gltf/AttenuationTest/glTF-Binary/AttenuationTest.glb b/tests/fixtures/gltf/AttenuationTest/glTF-Binary/AttenuationTest.glb new file mode 100644 index 0000000..070457d Binary files /dev/null and b/tests/fixtures/gltf/AttenuationTest/glTF-Binary/AttenuationTest.glb differ diff --git a/tests/fixtures/gltf/Box/LICENSE.md b/tests/fixtures/gltf/Box/LICENSE.md new file mode 100644 index 0000000..87f5e5e --- /dev/null +++ b/tests/fixtures/gltf/Box/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Box + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + +<!-- This file is auto-generated by modelmetadata. Do not edit by hand. --> diff --git a/tests/fixtures/gltf/Box/glTF-Binary/Box.glb b/tests/fixtures/gltf/Box/glTF-Binary/Box.glb new file mode 100644 index 0000000..95ec886 Binary files /dev/null and b/tests/fixtures/gltf/Box/glTF-Binary/Box.glb differ diff --git a/tests/fixtures/gltf/Box/glTF/Box.gltf b/tests/fixtures/gltf/Box/glTF/Box.gltf new file mode 100644 index 0000000..7f603f0 --- /dev/null +++ b/tests/fixtures/gltf/Box/glTF/Box.gltf @@ -0,0 +1,142 @@ +{ + "asset": { + "generator": "COLLADA2GLTF", + "version": "2.0" + }, + "scene": 0, + "scenes": [ + { + "nodes": [ + 0 + ] + } + ], + "nodes": [ + { + "children": [ + 1 + ], + "matrix": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + -1.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "mesh": 0 + } + ], + "meshes": [ + { + "primitives": [ + { + "attributes": { + "NORMAL": 1, + "POSITION": 2 + }, + "indices": 0, + "mode": 4, + "material": 0 + } + ], + "name": "Mesh" + } + ], + "accessors": [ + { + "bufferView": 0, + "byteOffset": 0, + "componentType": 5123, + "count": 36, + "max": [ + 23 + ], + "min": [ + 0 + ], + "type": "SCALAR" + }, + { + "bufferView": 1, + "byteOffset": 0, + "componentType": 5126, + "count": 24, + "max": [ + 1.0, + 1.0, + 1.0 + ], + "min": [ + -1.0, + -1.0, + -1.0 + ], + "type": "VEC3" + }, + { + "bufferView": 1, + "byteOffset": 288, + "componentType": 5126, + "count": 24, + "max": [ + 0.5, + 0.5, + 0.5 + ], + "min": [ + -0.5, + -0.5, + -0.5 + ], + "type": "VEC3" + } + ], + "materials": [ + { + "pbrMetallicRoughness": { + "baseColorFactor": [ + 0.800000011920929, + 0.0, + 0.0, + 1.0 + ], + "metallicFactor": 0.0 + }, + "name": "Red" + } + ], + "bufferViews": [ + { + "buffer": 0, + "byteOffset": 576, + "byteLength": 72, + "target": 34963 + }, + { + "buffer": 0, + "byteOffset": 0, + "byteLength": 576, + "byteStride": 12, + "target": 34962 + } + ], + "buffers": [ + { + "byteLength": 648, + "uri": "Box0.bin" + } + ] +} diff --git a/tests/fixtures/gltf/Box/glTF/Box0.bin b/tests/fixtures/gltf/Box/glTF/Box0.bin new file mode 100644 index 0000000..d7798ab Binary files /dev/null and b/tests/fixtures/gltf/Box/glTF/Box0.bin differ diff --git a/tests/fixtures/gltf/BoxInterleaved/LICENSE.md b/tests/fixtures/gltf/BoxInterleaved/LICENSE.md new file mode 100644 index 0000000..2c7c940 --- /dev/null +++ b/tests/fixtures/gltf/BoxInterleaved/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Box with interleaved position and normal attributes + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + +<!-- This file is auto-generated by modelmetadata. Do not edit by hand. --> diff --git a/tests/fixtures/gltf/BoxInterleaved/glTF-Binary/BoxInterleaved.glb b/tests/fixtures/gltf/BoxInterleaved/glTF-Binary/BoxInterleaved.glb new file mode 100644 index 0000000..25cb404 Binary files /dev/null and b/tests/fixtures/gltf/BoxInterleaved/glTF-Binary/BoxInterleaved.glb differ diff --git a/tests/fixtures/gltf/BoxTextured/LICENSE.md b/tests/fixtures/gltf/BoxTextured/LICENSE.md new file mode 100644 index 0000000..c8993e0 --- /dev/null +++ b/tests/fixtures/gltf/BoxTextured/LICENSE.md @@ -0,0 +1,19 @@ +# LICENSE file for the model: Box Textured + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + + * [Cesium Trademark or Logo](../../LICENSES/LicenseRef-LegalMark-Cesium.txt) + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + +<!-- This file is auto-generated by modelmetadata. Do not edit by hand. --> diff --git a/tests/fixtures/gltf/BoxTextured/glTF-Embedded/BoxTextured.gltf b/tests/fixtures/gltf/BoxTextured/glTF-Embedded/BoxTextured.gltf new file mode 100644 index 0000000..2743fc1 --- /dev/null +++ b/tests/fixtures/gltf/BoxTextured/glTF-Embedded/BoxTextured.gltf @@ -0,0 +1,181 @@ +{ + "asset": { + "generator": "COLLADA2GLTF", + "version": "2.0" + }, + "scene": 0, + "scenes": [ + { + "nodes": [ + 0 + ] + } + ], + "nodes": [ + { + "children": [ + 1 + ], + "matrix": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + -1.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "mesh": 0 + } + ], + "meshes": [ + { + "primitives": [ + { + "attributes": { + "NORMAL": 1, + "POSITION": 2, + "TEXCOORD_0": 3 + }, + "indices": 0, + "mode": 4, + "material": 0 + } + ], + "name": "Mesh" + } + ], + "accessors": [ + { + "bufferView": 0, + "byteOffset": 0, + "componentType": 5123, + "count": 36, + "max": [ + 23 + ], + "min": [ + 0 + ], + "type": "SCALAR" + }, + { + "bufferView": 1, + "byteOffset": 0, + "componentType": 5126, + "count": 24, + "max": [ + 1.0, + 1.0, + 1.0 + ], + "min": [ + -1.0, + -1.0, + -1.0 + ], + "type": "VEC3" + }, + { + "bufferView": 1, + "byteOffset": 288, + "componentType": 5126, + "count": 24, + "max": [ + 0.5, + 0.5, + 0.5 + ], + "min": [ + -0.5, + -0.5, + -0.5 + ], + "type": "VEC3" + }, + { + "bufferView": 2, + "byteOffset": 0, + "componentType": 5126, + "count": 24, + "max": [ + 6.0, + 1.0 + ], + "min": [ + 0.0, + 0.0 + ], + "type": "VEC2" + } + ], + "materials": [ + { + "pbrMetallicRoughness": { + "baseColorTexture": { + "index": 0 + }, + "metallicFactor": 0.0 + }, + "name": "Texture" + } + ], + "textures": [ + { + "sampler": 0, + "source": 0 + } + ], + "images": [ + { + "uri": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAMAAABrrFhUAAAAYFBMVEXc3Ny+1ejU2t6tzOaXwuVyseJprN9srd9gqd9/tuKHuuPh7vn////1+fnL2+ns8Onm6+B+nlyyw6GXsH1zl0ljjTBahiFchydRggWLp2u9yq+mupHM1MPg3+HY3NPf3t2inO6qAAAOAUlEQVR42uzWh7nkOAwDYIkBINmE+u/yJl3aHDyW9NZ/B4D1wWznuVwul8vlchnf8AdEb03+1aX3Ll3+1T50DXLXVc2sKv0GN36TVWWm2uWufUCjSVezdD44/wMg6XTeed6LkDY+0LNvomqV6e4k7kiCXwCA9JusZws3m4d/vvhyR+CO34Unet1L6DJutv3y9/TJCAD8SQAimGbaRfbrYDQR6ZaIAPjLgIhIU5HtRkHUHDf8fQDcVHZ6/E0tnYdytz1+DY/Zq3QCPBAAz7Lexlh+9a0cAA8HhJeprNvBGK/dA98EEW4qsmgDImoIgG8ERJSKtBVpOXgCoFTaYoZoOU/jpTLWim9JgCcBkLZOBaN1TQR4IgRS1/gpjiZaCPBkCNQSp5F0C4ATAFFdpuc3B6eBm8x9/lpOcBrQS9uYd/lZApwKSJM5WzikmwOcDHDrMqMB0QxwAYhUmbl+84WbnH77pHMhnr2NU0/f5FJAVxkn5vcAl4I4sQExD04zfwikAC4IOOcy7g5wSYD3E47f5MLy7YexJsBlAan751+4AVEHuLZwlfflB7g84G0NqHMHCJXxlv13cAtwlTF//+Y2sH/+1RroCXAfh9+EkgQ3Ah7awJDidqqP4/IbwN3AZByVXx3cDvywBjSDG4rUw34A3FJkbweQcnBL4F/cnAdiAykMRZcBPqJI3gtkuf8pt6VnKshjxnkXiIYItS8cp3sEQB+eldcwoA6AYTQAqHPlVt0VVJMwvLkjn5xLEUToCANVeQFo+LzfWSOSRYx17XIEKS/B+Aog2lzeye0TWcCpMmCi0d+fy1eyD41QMhoJKGBsHnO5fCenRpMQ0vPOgMjl8pPc6pTw3VrB5Mc6ACUpcyRSa2c8PWcPCLJc5rBtTAXo7QsNwlAQpSwhEc0n2ekAYShkc1kiWwptoGs4MlwFISnLGGrXSnpqYApjoVyWkWbLqMMFnMdlDwA4vx40kcJVDyD7nqZI4QDXuwLomAy06gAIoyFRxACdUlIvsQZKhssSbCh0kFqqIePDeMit1AF9Mwpvnk0IgZeyhPE4WSip+39iYCnIjnr10np4FYauInKXOd09+uHFkWochUuAJPpWqL0jqJeRAhGS+ZkB+nV6wNaDgzC60vJrLp9k1Z4uuemYA1xICwTISeZXsjiCLqYccoFrLQOAKFojIsZGIihjyjExlMLF8MH74IMaRDNQC1GAVx60PHZ9NVyTVfbD4DTg+0duz02z56B//Gqmqe4uxP1mDwhx9wD83cIW/Qf+4xJhlF4xewshemsBIvLOWmPEWKv+RTUt/5uTXs0xdjpbDQFRdEZyzvw/OWcxTl3D6H576Ys5t5ftRjBCv9Ahmct3sljnCSM8P1rz3ZzbX5t9ACl7l2RzWSTb5IGHxzw3GyzeThyFwLtcVskPXzjzSbj8hF/O2okCvf69VVgS4aHvx3jBHv7znE4YIJu5bMLZgsKDmP87du9ArdZDNbrYJZsHxUKQW3NHXo+CtfsGANFwOQBr397ooxGfMQxDNGUNxVRP8f28bsHL/dcCEUw5jIk43/+5rMK3radxehlvH+sxQFTbiYIaTRxkc2mALeGB63UNQcAF9O5zNpFPlZ4QhDsPIHV9P1IujeQzU4G3e+VIbduK0CeAGSx+SAJ4rwXrHV9HAba0w6cFwiP+eKt3fB64FQB5IxmfJL9QlPIPb1eiHSEOw/Yaz7HjwnA45mj4/7/cx170sFoETPUDTTSOoigOhVDgBMDn0fYpbjn21TBU/VjeYZ/H8RAkAJrn8VT9mBURsKkxSE6x4hbj0PgMb4YxHhLb9b1nQ9ap7/wfdGOpiAB0JcITXgytu6Vkydy9KjT0xCI/JAA6dvNw7J/xdBkRQJt0pLjlwyz9D/Mux4vgeBUI16MOracF3vQZJOJCC8Cf8fxbS29g1pUhAzseZIATiYbzb8zSAkvNGIvgWQ5R3KlzS+9gbVfGbkCe7wC0as3eD8fGHNqAsxwhAOXglj7AvC5jN3CcEEpcjzq29un36PMU2YCzHNHFNrinTzCvNGTgLE9+YJK7T8OxtjqCALmGAjA2ngKYj+FeyPkhPpIoBk+fCRjGIwh4iQXQLUXwLmSAkwHekQ7BcCzV4+teAuQcCoB2raUQ5nXBdz7vrcc+qEdIAEoDiNBRK7ME4M2gcTYgRxAQOtL8iMfTEQRwimuWILwNTTF+DEt1foQbUp2i8RhHAK+4ANZaBu8A5SkOoOjd0lMIEMGKmzDMu+kZIalInMmNjuqxIQhgFBcI4ALkBkR2hqBoQ47RIgL4MxdWXCCE4/HZgFzCeixrt0RVwG116hgrboMUEBwMiWyAqEdwBKSXAK+4XaS4AQPFsdkAEAAF9UgQQCpu5ZZWwFvgBrbOP65HzS2ev+0hQC6E4kaw2A3oRjeA6rFJlo6vAOwAxoentQS0U9g7sUkG5Izq8cshrCMAKK5SihsAZAPwtTJ/Daoj2JAJI7RbcTHMh4JyA7wD6DwRBIDTIKG42HIAIeyVcQP8EcDTLgIwTqEAAsXF8Mcx2YDE9bgcgQC25gEoBHyAP0i7gZcL+fyBcQAgD1iACVgWgPJHIKDDdbgIKBmQsB41gx0QRGJEKowcQOuJhrX93mzgghypWfqWgDzhewGsuHQGgGHWxDJwEyFCebYeQSqMb4Z4xSXcQHgsCtwA40i1d1tTfoCALYprlrbBB40YWCkDQmQAgRunL0eR4lYNP/+lELdnA7KE8rwjtTZPRH8Aqbj73cB1syPXIJMKD4N5IjtEoOK6pc0wA1emsrExT/vWV5VeTADuEYKKW3naA0tDsaWBStCtnJmtIqDLE9UlhjKAWHEJmMfZwFKKTGNeXlmP1gx5ovoE2QyAgDMh6XIrd99Tj95UmeoUlQupuAS8y/hLOfhIztcjbpHBn07AX7bkMwA6G7gIduQ769EfmegW36m4a+oRXJnixjxCAMD9FPFeQM6h5dLRKQvI35WAQ4FIvCHVra0/iU7E1zOQ4vICiI9FJWinFqIRKvl6xgfizRBohS4HT0fB2m61G0Ct+dkZA9oTr8ZiAbz3Zuk4WK8rGbiA+TfGbDzjim9IAQdEKy4vAzgmhpFEOThDQD2t+ZQsmD/ohHyOG3j3zhQ/zdWKDOVfv/mPyv/QLiKnxXGwisu7gZiBq7wZDngLytWjN9VMAGbgejrLjPPpFq9/7fkjMHtlulwX3U7zeObhXMHTrJJbjz7fCWAUOrM+44pegmRLh8O8GRW8LvrjfBG5wOFox9WjzychjFLv81cvXuYvToD5Y8J3wNKjBBOch/MCh6MVN3/zeQVgvBbvHtcQiksB9FEi4OHoSOqRNf1MAMYyCkC4edoP1EBFgw7lfbkUAiVwByAVl4d5f2fB30r5ciUACMA/A1ZcHqidmgS/Hm0pgBgTXANAcZ8vAxhV4/S5YyGAXwM6AAfwZDcABTBohSYuxQAmxQLIFhzPQKWMACbjTx145ngNHJsBcTExRuYzSRyIYxnEfQfP2gp09fwTgSAPhtC4/o+fP3BqvAEgLuN+WYFCoxPgnltArkyXkyFGj9c/htkSBXAyqLluseAeroT1+K3/4fR/WQELAYwdLvsdCQgP964vv9z+Bt80Hq8DBQBHwgVa5to9/STMvc4FOv6VVeO2bXHBgyDeCVVz527ppzFToPp5Lf7Vvn2mua7CYADWAs45MwYhBKjsf5d3TG6vcVzxzTvld/QZRMnjXj6/vNVWWDgELEwpnyRNzf6UwIfElFYcNx2epB8fZhJamTAT5VMQZZxKC2KfH98/Pk1qiwVX9GJCUXiSW4xlQmJmyqchYiacSowtxlIwrfo4xM0cnuQy8ReifDbiX639OCjwNLeKlC+G1u6vzOFpDiVTvhNCMViiTnyr+lM0WKQfNu+Di8AyGpDvNACawzJujelOA8BhIa33GQL9FLCUW7hNABxFYTGVQnSTAKrDcm413SIA4mYKL3Brd0iA0iQOLzGZbjAJGIM5vMYb8g32gA4L3G4/yEXgdS6Fh58ADmsEpNFXAIcV1BoPPgEUVlEZ+GaAMgqsZYJE4x4CzWEta8jj34KsYTHxmA2wCGxBZczdAE/VYRMqhcffAayhFelmDXD5yXi4AJoobMatjdUIKRVx2NJYCVAuAttyGSgB4iIOG1NpiYapvypsTiUOciqgqSrswEc5F6WqsAsb4aKcKInBPhzk8scC4qmaw160JzB8/1tBr70aUt65fvA5gXxZac0N2PjfFxFFcdifBeQrRsCpCRzCarleAsQYxOEQ6hITX6/9m8JRVCISXWr3U0QdjqPWMF9IiuJwLKsT03Wmv8HhTFq6RATMUQyO52qhMNP5j7+JO5xB4fReSJxKMIWzuLUpnRgBpcfjP5FLzOfpZ7+TmdXCTGc1f4OzuZsEPD4CZmxi7nA+V6vt2AiIGWM1dbiGviIe94IZEWFp8ij/UhGkTEfU318pVIersVqIjtn5mMEF+WNBYNp38pcgBhelJrVNPYP9Wl9v/VflqlZbRGai7V8jTaUFUXW4NFeVVhAzbZcBfUlYmpg6jMC9timllLeSEsZq7uAwCjPZphtQn/liZjAUdzORUBK/ngIR94lfpTe+4bi6SQ0tIs+IFpU+w9JCFQFVGJSrqklosUyY5qJo9u/drteecCpxrl5VHcbmrupSewiIc2ukf5RTSoi9+Crei78NB4ceQ8H0q/yQfoHYSze4K/uZ1BpCay3GWGKMrbVQq4hYBzfmD2Az+Y3NwDv4P/BerM7m/ycU/vb29vb29vb2E95qsPCUXPMVAAAAAElFTkSuQmCC" + } + ], + "samplers": [ + { + "magFilter": 9729, + "minFilter": 9986, + "wrapS": 10497, + "wrapT": 10497 + } + ], + "bufferViews": [ + { + "buffer": 0, + "byteOffset": 768, + "byteLength": 72, + "target": 34963 + }, + { + "buffer": 0, + "byteOffset": 0, + "byteLength": 576, + "byteStride": 12, + "target": 34962 + }, + { + "buffer": 0, + "byteOffset": 576, + "byteLength": 192, + "byteStride": 8, + "target": 34962 + } + ], + "buffers": [ + { + "byteLength": 840, + "uri": "data:application/octet-stream;base64,AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AACAPwAAAAAAAAAAAACAPwAAAAAAAAAAAACAPwAAAAAAAAAAAACAPwAAAAAAAAAAAAAAAAAAgD8AAAAAAAAAAAAAgD8AAAAAAAAAAAAAgD8AAAAAAAAAAAAAgD8AAAAAAAAAAAAAgL8AAAAAAAAAAAAAgL8AAAAAAAAAAAAAgL8AAAAAAAAAAAAAgL8AAAAAAACAvwAAAAAAAAAAAACAvwAAAAAAAAAAAACAvwAAAAAAAAAAAACAvwAAAAAAAAAAAAAAAAAAAAAAAIC/AAAAAAAAAAAAAIC/AAAAAAAAAAAAAIC/AAAAAAAAAAAAAIC/AAAAvwAAAL8AAAA/AAAAPwAAAL8AAAA/AAAAvwAAAD8AAAA/AAAAPwAAAD8AAAA/AAAAPwAAAD8AAAA/AAAAPwAAAL8AAAA/AAAAPwAAAD8AAAC/AAAAPwAAAL8AAAC/AAAAvwAAAD8AAAA/AAAAPwAAAD8AAAA/AAAAvwAAAD8AAAC/AAAAPwAAAD8AAAC/AAAAPwAAAL8AAAA/AAAAvwAAAL8AAAA/AAAAPwAAAL8AAAC/AAAAvwAAAL8AAAC/AAAAvwAAAL8AAAA/AAAAvwAAAD8AAAA/AAAAvwAAAL8AAAC/AAAAvwAAAD8AAAC/AAAAvwAAAL8AAAC/AAAAvwAAAD8AAAC/AAAAPwAAAL8AAAC/AAAAPwAAAD8AAAC/AADAQAAAAAAAAKBAAAAAAAAAwED+/38/AACgQP7/fz8AAIBAAAAAAAAAoEAAAAAAAACAQAAAgD8AAKBAAACAPwAAAEAAAAAAAACAPwAAAAAAAABAAACAPwAAgD8AAIA/AABAQAAAAAAAAIBAAAAAAAAAQEAAAIA/AACAQAAAgD8AAEBAAAAAAAAAAEAAAAAAAABAQAAAgD8AAABAAACAPwAAAAAAAAAAAAAAAP7/fz8AAIA/AAAAAAAAgD/+/38/AAABAAIAAwACAAEABAAFAAYABwAGAAUACAAJAAoACwAKAAkADAANAA4ADwAOAA0AEAARABIAEwASABEAFAAVABYAFwAWABUA" + } + ] +} diff --git a/tests/fixtures/gltf/BoxTextured/glTF/BoxTextured.gltf b/tests/fixtures/gltf/BoxTextured/glTF/BoxTextured.gltf new file mode 100644 index 0000000..eff658f --- /dev/null +++ b/tests/fixtures/gltf/BoxTextured/glTF/BoxTextured.gltf @@ -0,0 +1,181 @@ +{ + "asset": { + "generator": "COLLADA2GLTF", + "version": "2.0" + }, + "scene": 0, + "scenes": [ + { + "nodes": [ + 0 + ] + } + ], + "nodes": [ + { + "children": [ + 1 + ], + "matrix": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + -1.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "mesh": 0 + } + ], + "meshes": [ + { + "primitives": [ + { + "attributes": { + "NORMAL": 1, + "POSITION": 2, + "TEXCOORD_0": 3 + }, + "indices": 0, + "mode": 4, + "material": 0 + } + ], + "name": "Mesh" + } + ], + "accessors": [ + { + "bufferView": 0, + "byteOffset": 0, + "componentType": 5123, + "count": 36, + "max": [ + 23 + ], + "min": [ + 0 + ], + "type": "SCALAR" + }, + { + "bufferView": 1, + "byteOffset": 0, + "componentType": 5126, + "count": 24, + "max": [ + 1.0, + 1.0, + 1.0 + ], + "min": [ + -1.0, + -1.0, + -1.0 + ], + "type": "VEC3" + }, + { + "bufferView": 1, + "byteOffset": 288, + "componentType": 5126, + "count": 24, + "max": [ + 0.5, + 0.5, + 0.5 + ], + "min": [ + -0.5, + -0.5, + -0.5 + ], + "type": "VEC3" + }, + { + "bufferView": 2, + "byteOffset": 0, + "componentType": 5126, + "count": 24, + "max": [ + 6.0, + 1.0 + ], + "min": [ + 0.0, + 0.0 + ], + "type": "VEC2" + } + ], + "materials": [ + { + "pbrMetallicRoughness": { + "baseColorTexture": { + "index": 0 + }, + "metallicFactor": 0.0 + }, + "name": "Texture" + } + ], + "textures": [ + { + "sampler": 0, + "source": 0 + } + ], + "images": [ + { + "uri": "CesiumLogoFlat.png" + } + ], + "samplers": [ + { + "magFilter": 9729, + "minFilter": 9986, + "wrapS": 10497, + "wrapT": 10497 + } + ], + "bufferViews": [ + { + "buffer": 0, + "byteOffset": 768, + "byteLength": 72, + "target": 34963 + }, + { + "buffer": 0, + "byteOffset": 0, + "byteLength": 576, + "byteStride": 12, + "target": 34962 + }, + { + "buffer": 0, + "byteOffset": 576, + "byteLength": 192, + "byteStride": 8, + "target": 34962 + } + ], + "buffers": [ + { + "byteLength": 840, + "uri": "BoxTextured0.bin" + } + ] +} diff --git a/tests/fixtures/gltf/BoxTextured/glTF/BoxTextured0.bin b/tests/fixtures/gltf/BoxTextured/glTF/BoxTextured0.bin new file mode 100644 index 0000000..d2a7355 Binary files /dev/null and b/tests/fixtures/gltf/BoxTextured/glTF/BoxTextured0.bin differ diff --git a/tests/fixtures/gltf/BoxTextured/glTF/CesiumLogoFlat.png b/tests/fixtures/gltf/BoxTextured/glTF/CesiumLogoFlat.png new file mode 100644 index 0000000..8d5a3ad Binary files /dev/null and b/tests/fixtures/gltf/BoxTextured/glTF/CesiumLogoFlat.png differ diff --git a/tests/fixtures/gltf/BoxVertexColors/LICENSE.md b/tests/fixtures/gltf/BoxVertexColors/LICENSE.md new file mode 100644 index 0000000..afa6d28 --- /dev/null +++ b/tests/fixtures/gltf/BoxVertexColors/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Box Vertex Colors + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Zero v1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/legalcode) [SPDX license identifier: "CC0-1.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + +<!-- This file is auto-generated by modelmetadata. Do not edit by hand. --> diff --git a/tests/fixtures/gltf/BoxVertexColors/glTF-Binary/BoxVertexColors.glb b/tests/fixtures/gltf/BoxVertexColors/glTF-Binary/BoxVertexColors.glb new file mode 100644 index 0000000..875d95a Binary files /dev/null and b/tests/fixtures/gltf/BoxVertexColors/glTF-Binary/BoxVertexColors.glb differ diff --git a/tests/fixtures/gltf/Cameras/LICENSE.md b/tests/fixtures/gltf/Cameras/LICENSE.md new file mode 100644 index 0000000..f718127 --- /dev/null +++ b/tests/fixtures/gltf/Cameras/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Cameras + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Zero v1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/legalcode) [SPDX license identifier: "CC0-1.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + +<!-- This file is auto-generated by modelmetadata. Do not edit by hand. --> diff --git a/tests/fixtures/gltf/Cameras/glTF/Cameras.bin b/tests/fixtures/gltf/Cameras/glTF/Cameras.bin new file mode 100644 index 0000000..a6edb3b Binary files /dev/null and b/tests/fixtures/gltf/Cameras/glTF/Cameras.bin differ diff --git a/tests/fixtures/gltf/Cameras/glTF/Cameras.gltf b/tests/fixtures/gltf/Cameras/glTF/Cameras.gltf new file mode 100644 index 0000000..48d5adf --- /dev/null +++ b/tests/fixtures/gltf/Cameras/glTF/Cameras.gltf @@ -0,0 +1,99 @@ +{ + "scene" : 0, + "scenes" : [ + { + "nodes" : [ 0, 1, 2 ] + } + ], + "nodes" : [ + { + "rotation" : [ -0.383, 0.0, 0.0, 0.92375 ], + "mesh" : 0 + }, + { + "translation" : [ 0.5, 0.5, 3.0 ], + "camera" : 0 + }, + { + "translation" : [ 0.5, 0.5, 3.0 ], + "camera" : 1 + } + ], + + "cameras" : [ + { + "type": "perspective", + "perspective": { + "aspectRatio": 1.0, + "yfov": 0.7, + "zfar": 100, + "znear": 0.01 + } + }, + { + "type": "orthographic", + "orthographic": { + "xmag": 1.0, + "ymag": 1.0, + "zfar": 100, + "znear": 0.01 + } + } + ], + + "meshes" : [ + { + "primitives" : [ { + "attributes" : { + "POSITION" : 1 + }, + "indices" : 0 + } ] + } + ], + + "buffers" : [ + { + "uri" : "Cameras.bin", + "byteLength" : 60 + } + ], + "bufferViews" : [ + { + "buffer" : 0, + "byteOffset" : 0, + "byteLength" : 12, + "target" : 34963 + }, + { + "buffer" : 0, + "byteOffset" : 12, + "byteLength" : 48, + "target" : 34962 + } + ], + "accessors" : [ + { + "bufferView" : 0, + "byteOffset" : 0, + "componentType" : 5123, + "count" : 6, + "type" : "SCALAR", + "max" : [ 3 ], + "min" : [ 0 ] + }, + { + "bufferView" : 1, + "byteOffset" : 0, + "componentType" : 5126, + "count" : 4, + "type" : "VEC3", + "max" : [ 1.0, 1.0, 0.0 ], + "min" : [ 0.0, 0.0, 0.0 ] + } + ], + + "asset" : { + "version" : "2.0" + } +} diff --git a/tests/fixtures/gltf/ClearCoatCarPaint/LICENSE.md b/tests/fixtures/gltf/ClearCoatCarPaint/LICENSE.md new file mode 100644 index 0000000..2ec4dac --- /dev/null +++ b/tests/fixtures/gltf/ClearCoatCarPaint/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Clear Coat Car Paint + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Zero v1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/legalcode) [SPDX license identifier: "CC0-1.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + +<!-- This file is auto-generated by modelmetadata. Do not edit by hand. --> diff --git a/tests/fixtures/gltf/ClearCoatCarPaint/glTF-Binary/ClearCoatCarPaint.glb b/tests/fixtures/gltf/ClearCoatCarPaint/glTF-Binary/ClearCoatCarPaint.glb new file mode 100644 index 0000000..6258704 Binary files /dev/null and b/tests/fixtures/gltf/ClearCoatCarPaint/glTF-Binary/ClearCoatCarPaint.glb differ diff --git a/tests/fixtures/gltf/EmissiveStrengthTest/LICENSE.md b/tests/fixtures/gltf/EmissiveStrengthTest/LICENSE.md new file mode 100644 index 0000000..b2e3125 --- /dev/null +++ b/tests/fixtures/gltf/EmissiveStrengthTest/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Emissive Strength Test + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + +<!-- This file is auto-generated by modelmetadata. Do not edit by hand. --> diff --git a/tests/fixtures/gltf/EmissiveStrengthTest/glTF-Binary/EmissiveStrengthTest.glb b/tests/fixtures/gltf/EmissiveStrengthTest/glTF-Binary/EmissiveStrengthTest.glb new file mode 100644 index 0000000..6020aa6 Binary files /dev/null and b/tests/fixtures/gltf/EmissiveStrengthTest/glTF-Binary/EmissiveStrengthTest.glb differ diff --git a/tests/fixtures/gltf/InterpolationTest/LICENSE.md b/tests/fixtures/gltf/InterpolationTest/LICENSE.md new file mode 100644 index 0000000..98cc3eb --- /dev/null +++ b/tests/fixtures/gltf/InterpolationTest/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Interpolation Test + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Zero v1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/legalcode) [SPDX license identifier: "CC0-1.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + +<!-- This file is auto-generated by modelmetadata. Do not edit by hand. --> diff --git a/tests/fixtures/gltf/InterpolationTest/glTF-Binary/InterpolationTest.glb b/tests/fixtures/gltf/InterpolationTest/glTF-Binary/InterpolationTest.glb new file mode 100644 index 0000000..4200fcc Binary files /dev/null and b/tests/fixtures/gltf/InterpolationTest/glTF-Binary/InterpolationTest.glb differ diff --git a/tests/fixtures/gltf/LightVisibility/LICENSE.md b/tests/fixtures/gltf/LightVisibility/LICENSE.md new file mode 100644 index 0000000..d95f2cf --- /dev/null +++ b/tests/fixtures/gltf/LightVisibility/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: LightVisibility + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Zero v1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/legalcode) [SPDX license identifier: "CC0-1.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + +<!-- This file is auto-generated by modelmetadata. Do not edit by hand. --> diff --git a/tests/fixtures/gltf/LightVisibility/glTF-Binary/LightVisibility.glb b/tests/fixtures/gltf/LightVisibility/glTF-Binary/LightVisibility.glb new file mode 100644 index 0000000..861a523 Binary files /dev/null and b/tests/fixtures/gltf/LightVisibility/glTF-Binary/LightVisibility.glb differ diff --git a/tests/fixtures/gltf/MeshPrimitiveModes/LICENSE.md b/tests/fixtures/gltf/MeshPrimitiveModes/LICENSE.md new file mode 100644 index 0000000..083a4b6 --- /dev/null +++ b/tests/fixtures/gltf/MeshPrimitiveModes/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Mesh Primitive Modes + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Zero v1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/legalcode) [SPDX license identifier: "CC0-1.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + +<!-- This file is auto-generated by modelmetadata. Do not edit by hand. --> diff --git a/tests/fixtures/gltf/MeshPrimitiveModes/glTF/MeshPrimitiveModes.gltf b/tests/fixtures/gltf/MeshPrimitiveModes/glTF/MeshPrimitiveModes.gltf new file mode 100644 index 0000000..b392211 --- /dev/null +++ b/tests/fixtures/gltf/MeshPrimitiveModes/glTF/MeshPrimitiveModes.gltf @@ -0,0 +1,233 @@ +{ + "asset": { + "version": "2.0" + }, + + "scene": 0, + "scenes": [ + { + "nodes": [0, 1, 2, 3, 4, 5, 6] + } + ], + + "nodes": [ + { + "translation": [-0, 3, 0], + "mesh": 0 + }, + { + "translation": [-2, 0, 0], + "mesh": 1 + }, + { + "translation": [0, 0, 0], + "mesh": 2 + }, + { + "translation": [2, 0, 0], + "mesh": 3 + }, + { + "translation": [-2, -3, 0], + "mesh": 4 + }, + { + "translation": [0, -3, 0], + "mesh": 5 + }, + { + "translation": [2, -3, 0], + "mesh": 6 + } + ], + + "meshes": [ + { + "name": "mesh with POINTS", + "primitives": [ + { + "attributes": { + "POSITION": 7 + }, + "indices": 0, + "mode": 0 + } + ] + }, + { + "name": "mesh with LINES", + "primitives": [ + { + "attributes": { + "POSITION": 7 + }, + "indices": 1, + "mode": 1 + } + ] + }, + { + "name": "mesh with LINE_LOOP", + "primitives": [ + { + "attributes": { + "POSITION": 7 + }, + "indices": 2, + "mode": 2 + } + ] + }, + { + "name": "mesh with LINE_STRIP", + "primitives": [ + { + "attributes": { + "POSITION": 7 + }, + "indices": 3, + "mode": 3 + } + ] + }, + { + "name": "mesh with TRIANGLES", + "primitives": [ + { + "attributes": { + "POSITION": 7 + }, + "indices": 4, + "mode": 4 + } + ] + }, + { + "name": "mesh with GL_TRIANGLE_STRIP", + "primitives": [ + { + "attributes": { + "POSITION": 7 + }, + "indices": 5, + "mode": 5 + } + ] + }, + { + "name": "mesh with GL_TRIANGLE_FAN", + "primitives": [ + { + "attributes": { + "POSITION": 7 + }, + "indices": 6, + "mode": 6 + } + ] + } + ], + + "buffers": [ + { + "uri": "buffer.bin", + "byteLength": 216 + } + ], + "bufferViews": [ + { + "buffer": 0, + "byteOffset": 0, + "byteLength": 130, + "target": 34963 + }, + { + "buffer": 0, + "byteOffset": 132, + "byteLength": 84, + "target": 34962 + } + ], + "accessors": [ + { + "name": "indices for POINTS", + "bufferView": 0, + "byteOffset": 0, + "componentType": 5123, + "count": 7, + "type": "SCALAR", + "max": [6], + "min": [0] + }, + { + "name": "indices for LINES", + "bufferView": 0, + "byteOffset": 14, + "componentType": 5123, + "count": 12, + "type": "SCALAR", + "max": [6], + "min": [0] + }, + { + "name": "indices for LINE_LOOP", + "bufferView": 0, + "byteOffset": 38, + "componentType": 5123, + "count": 7, + "type": "SCALAR", + "max": [6], + "min": [0] + }, + { + "name": "indices for LINE_STRIP", + "bufferView": 0, + "byteOffset": 52, + "componentType": 5123, + "count": 7, + "type": "SCALAR", + "max": [6], + "min": [0] + }, + { + "name": "indices for TRIANGLES", + "bufferView": 0, + "byteOffset": 66, + "componentType": 5123, + "count": 18, + "type": "SCALAR", + "max": [6], + "min": [0] + }, + { + "name": "indices for TRIANGLE_STRIP", + "bufferView": 0, + "byteOffset": 102, + "componentType": 5123, + "count": 6, + "type": "SCALAR", + "max": [6], + "min": [1] + }, + { + "name": "indices for TRIANGLE_FAN", + "bufferView": 0, + "byteOffset": 114, + "componentType": 5123, + "count": 8, + "type": "SCALAR", + "max": [6], + "min": [0] + }, + { + "name": "positions", + "bufferView": 1, + "byteOffset": 0, + "componentType": 5126, + "count": 7, + "type": "VEC3", + "max": [0.866, 1.0, 0.0], + "min": [-0.866, -1.0, 0.0] + } + ] +} diff --git a/tests/fixtures/gltf/MeshPrimitiveModes/glTF/buffer.bin b/tests/fixtures/gltf/MeshPrimitiveModes/glTF/buffer.bin new file mode 100644 index 0000000..069020a Binary files /dev/null and b/tests/fixtures/gltf/MeshPrimitiveModes/glTF/buffer.bin differ diff --git a/tests/fixtures/gltf/MultiUVTest/LICENSE.md b/tests/fixtures/gltf/MultiUVTest/LICENSE.md new file mode 100644 index 0000000..367cc0d --- /dev/null +++ b/tests/fixtures/gltf/MultiUVTest/LICENSE.md @@ -0,0 +1,19 @@ +# LICENSE file for the model: MultiUV Test + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + + * [Khronos Trademark or Logo](../../LICENSES/LicenseRef-LegalMark-Khronos.txt) + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + +<!-- This file is auto-generated by modelmetadata. Do not edit by hand. --> diff --git a/tests/fixtures/gltf/MultiUVTest/glTF-Binary/MultiUVTest.glb b/tests/fixtures/gltf/MultiUVTest/glTF-Binary/MultiUVTest.glb new file mode 100644 index 0000000..69ed2fe Binary files /dev/null and b/tests/fixtures/gltf/MultiUVTest/glTF-Binary/MultiUVTest.glb differ diff --git a/tests/fixtures/gltf/MultipleScenes/LICENSE.md b/tests/fixtures/gltf/MultipleScenes/LICENSE.md new file mode 100644 index 0000000..1ba45c7 --- /dev/null +++ b/tests/fixtures/gltf/MultipleScenes/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Multiple Scenes + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Zero v1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/legalcode) [SPDX license identifier: "CC0-1.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + +<!-- This file is auto-generated by modelmetadata. Do not edit by hand. --> diff --git a/tests/fixtures/gltf/MultipleScenes/glTF/MultipleScenes.gltf b/tests/fixtures/gltf/MultipleScenes/glTF/MultipleScenes.gltf new file mode 100644 index 0000000..a61070a --- /dev/null +++ b/tests/fixtures/gltf/MultipleScenes/glTF/MultipleScenes.gltf @@ -0,0 +1,118 @@ +{ + "scene" : 1, + "scenes" : [ + { + "nodes" : [ 0 ] + }, + { + "nodes" : [ 1 ] + } + ], + + "nodes" : [ + { + "mesh" : 0 + }, + { + "mesh" : 1 + } + ], + + "meshes" : [ + { + "primitives" : [ { + "attributes" : { + "POSITION" : 1 + }, + "indices" : 0 + } ] + }, + { + "primitives" : [ { + "attributes" : { + "POSITION" : 3 + }, + "indices" : 2 + } ] + } + ], + + "buffers" : [ + { + "uri" : "MultipleScenes_triangle.bin", + "byteLength" : 44 + }, + { + "uri" : "MultipleScenes_square.bin", + "byteLength" : 60 + } + ], + "bufferViews" : [ + { + "buffer" : 0, + "byteOffset" : 0, + "byteLength" : 6, + "target" : 34963 + }, + { + "buffer" : 0, + "byteOffset" : 8, + "byteLength" : 36, + "target" : 34962 + }, + { + "buffer" : 1, + "byteOffset" : 0, + "byteLength" : 12, + "target" : 34963 + }, + { + "buffer" : 1, + "byteOffset" : 12, + "byteLength" : 48, + "target" : 34962 + } + ], + "accessors" : [ + { + "bufferView" : 0, + "byteOffset" : 0, + "componentType" : 5123, + "count" : 3, + "type" : "SCALAR", + "max" : [ 2 ], + "min" : [ 0 ] + }, + { + "bufferView" : 1, + "byteOffset" : 0, + "componentType" : 5126, + "count" : 3, + "type" : "VEC3", + "max" : [ 1.0, 1.0, 0.0 ], + "min" : [ 0.0, 0.0, 0.0 ] + }, + { + "bufferView" : 2, + "byteOffset" : 0, + "componentType" : 5123, + "count" : 6, + "type" : "SCALAR", + "max" : [ 3 ], + "min" : [ 0 ] + }, + { + "bufferView" : 3, + "byteOffset" : 0, + "componentType" : 5126, + "count" : 4, + "type" : "VEC3", + "max" : [ 1.0, 1.0, 0.0 ], + "min" : [ 0.0, 0.0, 0.0 ] + } + ], + + "asset" : { + "version" : "2.0" + } +} diff --git a/tests/fixtures/gltf/MultipleScenes/glTF/MultipleScenes_square.bin b/tests/fixtures/gltf/MultipleScenes/glTF/MultipleScenes_square.bin new file mode 100644 index 0000000..a6edb3b Binary files /dev/null and b/tests/fixtures/gltf/MultipleScenes/glTF/MultipleScenes_square.bin differ diff --git a/tests/fixtures/gltf/MultipleScenes/glTF/MultipleScenes_triangle.bin b/tests/fixtures/gltf/MultipleScenes/glTF/MultipleScenes_triangle.bin new file mode 100644 index 0000000..d642500 Binary files /dev/null and b/tests/fixtures/gltf/MultipleScenes/glTF/MultipleScenes_triangle.bin differ diff --git a/tests/fixtures/gltf/NegativeScaleTest/LICENSE.md b/tests/fixtures/gltf/NegativeScaleTest/LICENSE.md new file mode 100644 index 0000000..7fbbd09 --- /dev/null +++ b/tests/fixtures/gltf/NegativeScaleTest/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Negative Scale Test + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + +<!-- This file is auto-generated by modelmetadata. Do not edit by hand. --> diff --git a/tests/fixtures/gltf/NegativeScaleTest/glTF-Binary/NegativeScaleTest.glb b/tests/fixtures/gltf/NegativeScaleTest/glTF-Binary/NegativeScaleTest.glb new file mode 100644 index 0000000..00efded Binary files /dev/null and b/tests/fixtures/gltf/NegativeScaleTest/glTF-Binary/NegativeScaleTest.glb differ diff --git a/tests/fixtures/gltf/PointLightIntensityTest/LICENSE.md b/tests/fixtures/gltf/PointLightIntensityTest/LICENSE.md new file mode 100644 index 0000000..3e0f6ce --- /dev/null +++ b/tests/fixtures/gltf/PointLightIntensityTest/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Point Light Intensity Test + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Zero v1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/legalcode) [SPDX license identifier: "CC0-1.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + +<!-- This file is auto-generated by modelmetadata. Do not edit by hand. --> diff --git a/tests/fixtures/gltf/PointLightIntensityTest/glTF-Binary/PointLightIntensityTest.glb b/tests/fixtures/gltf/PointLightIntensityTest/glTF-Binary/PointLightIntensityTest.glb new file mode 100644 index 0000000..ff8ae99 Binary files /dev/null and b/tests/fixtures/gltf/PointLightIntensityTest/glTF-Binary/PointLightIntensityTest.glb differ diff --git a/tests/fixtures/gltf/RiggedSimple/LICENSE.md b/tests/fixtures/gltf/RiggedSimple/LICENSE.md new file mode 100644 index 0000000..2a98e37 --- /dev/null +++ b/tests/fixtures/gltf/RiggedSimple/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Rigged Simple + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + +<!-- This file is auto-generated by modelmetadata. Do not edit by hand. --> diff --git a/tests/fixtures/gltf/RiggedSimple/glTF-Binary/RiggedSimple.glb b/tests/fixtures/gltf/RiggedSimple/glTF-Binary/RiggedSimple.glb new file mode 100644 index 0000000..d56b94e Binary files /dev/null and b/tests/fixtures/gltf/RiggedSimple/glTF-Binary/RiggedSimple.glb differ diff --git a/tests/fixtures/gltf/SimpleMeshes/LICENSE.md b/tests/fixtures/gltf/SimpleMeshes/LICENSE.md new file mode 100644 index 0000000..6c1201c --- /dev/null +++ b/tests/fixtures/gltf/SimpleMeshes/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Simple Meshes + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Zero v1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/legalcode) [SPDX license identifier: "CC0-1.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + +<!-- This file is auto-generated by modelmetadata. Do not edit by hand. --> diff --git a/tests/fixtures/gltf/SimpleMeshes/glTF/SimpleMeshes.bin b/tests/fixtures/gltf/SimpleMeshes/glTF/SimpleMeshes.bin new file mode 100644 index 0000000..291b43c Binary files /dev/null and b/tests/fixtures/gltf/SimpleMeshes/glTF/SimpleMeshes.bin differ diff --git a/tests/fixtures/gltf/SimpleMeshes/glTF/SimpleMeshes.gltf b/tests/fixtures/gltf/SimpleMeshes/glTF/SimpleMeshes.gltf new file mode 100644 index 0000000..c3f3d44 --- /dev/null +++ b/tests/fixtures/gltf/SimpleMeshes/glTF/SimpleMeshes.gltf @@ -0,0 +1,84 @@ +{ + "scene" : 0, + "scenes" : [ + { + "nodes" : [ 0, 1] + } + ], + "nodes" : [ + { + "mesh" : 0 + }, + { + "mesh" : 0, + "translation" : [ 1.0, 0.0, 0.0 ] + } + ], + + "meshes" : [ + { + "primitives" : [ { + "attributes" : { + "POSITION" : 1, + "NORMAL" : 2 + }, + "indices" : 0 + } ] + } + ], + + "buffers" : [ + { + "uri" : "SimpleMeshes.bin", + "byteLength" : 80 + } + ], + "bufferViews" : [ + { + "buffer" : 0, + "byteOffset" : 0, + "byteLength" : 6, + "target" : 34963 + }, + { + "buffer" : 0, + "byteOffset" : 8, + "byteLength" : 72, + "byteStride" : 12, + "target" : 34962 + } + ], + "accessors" : [ + { + "bufferView" : 0, + "byteOffset" : 0, + "componentType" : 5123, + "count" : 3, + "type" : "SCALAR", + "max" : [ 2 ], + "min" : [ 0 ] + }, + { + "bufferView" : 1, + "byteOffset" : 0, + "componentType" : 5126, + "count" : 3, + "type" : "VEC3", + "max" : [ 1.0, 1.0, 0.0 ], + "min" : [ 0.0, 0.0, 0.0 ] + }, + { + "bufferView" : 1, + "byteOffset" : 36, + "componentType" : 5126, + "count" : 3, + "type" : "VEC3", + "max" : [ 0.0, 0.0, 1.0 ], + "min" : [ 0.0, 0.0, 1.0 ] + } + ], + + "asset" : { + "version" : "2.0" + } +} diff --git a/tests/fixtures/gltf/SimpleMorph/LICENSE.md b/tests/fixtures/gltf/SimpleMorph/LICENSE.md new file mode 100644 index 0000000..b889d88 --- /dev/null +++ b/tests/fixtures/gltf/SimpleMorph/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Simple Morph + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Zero v1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/legalcode) [SPDX license identifier: "CC0-1.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + +<!-- This file is auto-generated by modelmetadata. Do not edit by hand. --> diff --git a/tests/fixtures/gltf/SimpleMorph/glTF/SimpleMorph.gltf b/tests/fixtures/gltf/SimpleMorph/glTF/SimpleMorph.gltf new file mode 100644 index 0000000..0d5f960 --- /dev/null +++ b/tests/fixtures/gltf/SimpleMorph/glTF/SimpleMorph.gltf @@ -0,0 +1,189 @@ +{ + "scene" : 0, + "scenes":[ + { + "nodes":[ + 0 + ] + } + ], + "nodes":[ + { + "mesh":0 + } + ], + "meshes":[ + { + "primitives":[ + { + "attributes":{ + "POSITION":1 + }, + "targets":[ + { + "POSITION":2 + }, + { + "POSITION":3 + } + ], + "indices":0 + } + ], + "weights":[ + 0.5, + 0.5 + ] + } + ], + "animations":[ + { + "samplers":[ + { + "input":4, + "interpolation":"LINEAR", + "output":5 + } + ], + "channels":[ + { + "sampler":0, + "target":{ + "node":0, + "path":"weights" + } + } + ] + } + ], + "buffers":[ + { + "uri" : "SimpleMorph_geometry.bin", + "byteLength":116 + }, + { + "uri" : "SimpleMorph_animation.bin", + "byteLength":60 + } + ], + "bufferViews":[ + { + "buffer":0, + "byteOffset":0, + "byteLength":6, + "target":34963 + }, + { + "buffer":0, + "byteOffset":8, + "byteLength":108, + "byteStride":12, + "target":34962 + }, + { + "buffer":1, + "byteOffset":0, + "byteLength":20 + }, + { + "buffer":1, + "byteOffset":20, + "byteLength":40 + } + ], + "accessors":[ + { + "bufferView":0, + "byteOffset":0, + "componentType":5123, + "count":3, + "type":"SCALAR", + "max":[ + 2 + ], + "min":[ + 0 + ] + }, + { + "bufferView":1, + "byteOffset":0, + "componentType":5126, + "count":3, + "type":"VEC3", + "max":[ + 1.0, + 0.5, + 0.0 + ], + "min":[ + 0.0, + 0.0, + 0.0 + ] + }, + { + "bufferView":1, + "byteOffset":36, + "componentType":5126, + "count":3, + "type":"VEC3", + "max":[ + 0.0, + 1.0, + 0.0 + ], + "min":[ + -1.0, + 0.0, + 0.0 + ] + }, + { + "bufferView":1, + "byteOffset":72, + "componentType":5126, + "count":3, + "type":"VEC3", + "max":[ + 1.0, + 1.0, + 0.0 + ], + "min":[ + 0.0, + 0.0, + 0.0 + ] + }, + { + "bufferView":2, + "byteOffset":0, + "componentType":5126, + "count":5, + "type":"SCALAR", + "max":[ + 4.0 + ], + "min":[ + 0.0 + ] + }, + { + "bufferView":3, + "byteOffset":0, + "componentType":5126, + "count":10, + "type":"SCALAR", + "max":[ + 1.0 + ], + "min":[ + 0.0 + ] + } + ], + "asset":{ + "version":"2.0" + } +} diff --git a/tests/fixtures/gltf/SimpleMorph/glTF/SimpleMorph_animation.bin b/tests/fixtures/gltf/SimpleMorph/glTF/SimpleMorph_animation.bin new file mode 100644 index 0000000..bbd0ee6 Binary files /dev/null and b/tests/fixtures/gltf/SimpleMorph/glTF/SimpleMorph_animation.bin differ diff --git a/tests/fixtures/gltf/SimpleMorph/glTF/SimpleMorph_geometry.bin b/tests/fixtures/gltf/SimpleMorph/glTF/SimpleMorph_geometry.bin new file mode 100644 index 0000000..70b73c2 Binary files /dev/null and b/tests/fixtures/gltf/SimpleMorph/glTF/SimpleMorph_geometry.bin differ diff --git a/tests/fixtures/gltf/SimpleSkin/LICENSE.md b/tests/fixtures/gltf/SimpleSkin/LICENSE.md new file mode 100644 index 0000000..8437c87 --- /dev/null +++ b/tests/fixtures/gltf/SimpleSkin/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Simple Skin + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Zero v1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/legalcode) [SPDX license identifier: "CC0-1.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + +<!-- This file is auto-generated by modelmetadata. Do not edit by hand. --> diff --git a/tests/fixtures/gltf/SimpleSkin/glTF/SimpleSkin.gltf b/tests/fixtures/gltf/SimpleSkin/glTF/SimpleSkin.gltf new file mode 100644 index 0000000..1d586df --- /dev/null +++ b/tests/fixtures/gltf/SimpleSkin/glTF/SimpleSkin.gltf @@ -0,0 +1,131 @@ +{ + "scene" : 0, + "scenes" : [ { + "nodes" : [ 0, 1 ] + } ], + + "nodes" : [ { + "skin" : 0, + "mesh" : 0 + }, { + "children" : [ 2 ] + }, { + "translation" : [ 0.0, 1.0, 0.0 ], + "rotation" : [ 0.0, 0.0, 0.0, 1.0 ] + } ], + + "meshes" : [ { + "primitives" : [ { + "attributes" : { + "POSITION" : 1, + "JOINTS_0" : 2, + "WEIGHTS_0" : 3 + }, + "indices" : 0 + } ] + } ], + + "skins" : [ { + "inverseBindMatrices" : 4, + "joints" : [ 1, 2 ] + } ], + + "animations" : [ { + "channels" : [ { + "sampler" : 0, + "target" : { + "node" : 2, + "path" : "rotation" + } + } ], + "samplers" : [ { + "input" : 5, + "interpolation" : "LINEAR", + "output" : 6 + } ] + } ], + + "buffers" : [ { + "uri" : "SimpleSkin_geometry.bin", + "byteLength" : 168 + }, { + "uri" : "SimpleSkin_skinningData.bin", + "byteLength" : 320 + }, { + "uri" : "SimpleSkin_inverseBindMatrices.bin", + "byteLength" : 128 + }, { + "uri" : "SimpleSkin_animation.bin", + "byteLength" : 240 + } ], + + "bufferViews" : [ { + "buffer" : 0, + "byteLength" : 48, + "target" : 34963 + }, { + "buffer" : 0, + "byteOffset" : 48, + "byteLength" : 120, + "target" : 34962 + }, { + "buffer" : 1, + "byteLength" : 320, + "byteStride" : 16 + }, { + "buffer" : 2, + "byteLength" : 128 + }, { + "buffer" : 3, + "byteLength" : 240 + } ], + + "accessors" : [ { + "bufferView" : 0, + "componentType" : 5123, + "count" : 24, + "type" : "SCALAR" + }, { + "bufferView" : 1, + "componentType" : 5126, + "count" : 10, + "type" : "VEC3", + "max" : [ 0.5, 2.0, 0.0 ], + "min" : [ -0.5, 0.0, 0.0 ] + }, { + "bufferView" : 2, + "componentType" : 5123, + "count" : 10, + "type" : "VEC4" + }, { + "bufferView" : 2, + "byteOffset" : 160, + "componentType" : 5126, + "count" : 10, + "type" : "VEC4" + }, { + "bufferView" : 3, + "componentType" : 5126, + "count" : 2, + "type" : "MAT4" + }, { + "bufferView" : 4, + "componentType" : 5126, + "count" : 12, + "type" : "SCALAR", + "max" : [ 5.5 ], + "min" : [ 0.0 ] + }, { + "bufferView" : 4, + "byteOffset" : 48, + "componentType" : 5126, + "count" : 12, + "type" : "VEC4", + "max" : [ 0.0, 0.0, 0.707, 1.0 ], + "min" : [ 0.0, 0.0, -0.707, 0.707 ] + } ], + + "asset" : { + "version" : "2.0" + } +} \ No newline at end of file diff --git a/tests/fixtures/gltf/SimpleSkin/glTF/SimpleSkin_animation.bin b/tests/fixtures/gltf/SimpleSkin/glTF/SimpleSkin_animation.bin new file mode 100644 index 0000000..ff550c6 Binary files /dev/null and b/tests/fixtures/gltf/SimpleSkin/glTF/SimpleSkin_animation.bin differ diff --git a/tests/fixtures/gltf/SimpleSkin/glTF/SimpleSkin_geometry.bin b/tests/fixtures/gltf/SimpleSkin/glTF/SimpleSkin_geometry.bin new file mode 100644 index 0000000..15375c4 Binary files /dev/null and b/tests/fixtures/gltf/SimpleSkin/glTF/SimpleSkin_geometry.bin differ diff --git a/tests/fixtures/gltf/SimpleSkin/glTF/SimpleSkin_inverseBindMatrices.bin b/tests/fixtures/gltf/SimpleSkin/glTF/SimpleSkin_inverseBindMatrices.bin new file mode 100644 index 0000000..5af0b5e Binary files /dev/null and b/tests/fixtures/gltf/SimpleSkin/glTF/SimpleSkin_inverseBindMatrices.bin differ diff --git a/tests/fixtures/gltf/SimpleSkin/glTF/SimpleSkin_skinningData.bin b/tests/fixtures/gltf/SimpleSkin/glTF/SimpleSkin_skinningData.bin new file mode 100644 index 0000000..fd0c165 Binary files /dev/null and b/tests/fixtures/gltf/SimpleSkin/glTF/SimpleSkin_skinningData.bin differ diff --git a/tests/fixtures/gltf/SimpleSparseAccessor/LICENSE.md b/tests/fixtures/gltf/SimpleSparseAccessor/LICENSE.md new file mode 100644 index 0000000..acf8487 --- /dev/null +++ b/tests/fixtures/gltf/SimpleSparseAccessor/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Simple Sparse Accessor + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + +<!-- This file is auto-generated by modelmetadata. Do not edit by hand. --> diff --git a/tests/fixtures/gltf/SimpleSparseAccessor/glTF-Embedded/SimpleSparseAccessor.gltf b/tests/fixtures/gltf/SimpleSparseAccessor/glTF-Embedded/SimpleSparseAccessor.gltf new file mode 100644 index 0000000..ca69e2f --- /dev/null +++ b/tests/fixtures/gltf/SimpleSparseAccessor/glTF-Embedded/SimpleSparseAccessor.gltf @@ -0,0 +1,77 @@ +{ + "scene" : 0, + "scenes" : [ { + "nodes" : [ 0 ] + } ], + + "nodes" : [ { + "mesh" : 0 + } ], + + "meshes" : [ { + "primitives" : [ { + "attributes" : { + "POSITION" : 1 + }, + "indices" : 0 + } ] + } ], + + "buffers" : [ { + "uri" : "data:application/gltf-buffer;base64,AAAIAAcAAAABAAgAAQAJAAgAAQACAAkAAgAKAAkAAgADAAoAAwALAAoAAwAEAAsABAAMAAsABAAFAAwABQANAAwABQAGAA0AAAAAAAAAAAAAAAAAAACAPwAAAAAAAAAAAAAAQAAAAAAAAAAAAABAQAAAAAAAAAAAAACAQAAAAAAAAAAAAACgQAAAAAAAAAAAAADAQAAAAAAAAAAAAAAAAAAAgD8AAAAAAACAPwAAgD8AAAAAAAAAQAAAgD8AAAAAAABAQAAAgD8AAAAAAACAQAAAgD8AAAAAAACgQAAAgD8AAAAAAADAQAAAgD8AAAAACAAKAAwAAAAAAIA/AAAAQAAAAAAAAEBAAABAQAAAAAAAAKBAAACAQAAAAAA=", + "byteLength" : 284 + } ], + + "bufferViews" : [ { + "buffer" : 0, + "byteOffset" : 0, + "byteLength" : 72, + "target" : 34963 + }, { + "buffer" : 0, + "byteOffset" : 72, + "byteLength" : 168 + }, { + "buffer" : 0, + "byteOffset" : 240, + "byteLength" : 6 + }, { + "buffer" : 0, + "byteOffset" : 248, + "byteLength" : 36 + } ], + + "accessors" : [ { + "bufferView" : 0, + "byteOffset" : 0, + "componentType" : 5123, + "count" : 36, + "type" : "SCALAR", + "max" : [ 13 ], + "min" : [ 0 ] + }, { + "bufferView" : 1, + "byteOffset" : 0, + "componentType" : 5126, + "count" : 14, + "type" : "VEC3", + "max" : [ 6.0, 4.0, 0.0 ], + "min" : [ 0.0, 0.0, 0.0 ], + "sparse" : { + "count" : 3, + "indices" : { + "bufferView" : 2, + "byteOffset" : 0, + "componentType" : 5123 + }, + "values" : { + "bufferView" : 3, + "byteOffset" : 0 + } + } + } ], + + "asset" : { + "version" : "2.0" + } +} \ No newline at end of file diff --git a/tests/fixtures/gltf/TextureCoordinateTest/LICENSE.md b/tests/fixtures/gltf/TextureCoordinateTest/LICENSE.md new file mode 100644 index 0000000..ba67d93 --- /dev/null +++ b/tests/fixtures/gltf/TextureCoordinateTest/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Texture Coordinate Test + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Zero v1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/legalcode) [SPDX license identifier: "CC0-1.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + +<!-- This file is auto-generated by modelmetadata. Do not edit by hand. --> diff --git a/tests/fixtures/gltf/TextureCoordinateTest/glTF-Binary/TextureCoordinateTest.glb b/tests/fixtures/gltf/TextureCoordinateTest/glTF-Binary/TextureCoordinateTest.glb new file mode 100644 index 0000000..39d3da6 Binary files /dev/null and b/tests/fixtures/gltf/TextureCoordinateTest/glTF-Binary/TextureCoordinateTest.glb differ diff --git a/tests/fixtures/gltf/TextureTransformTest/LICENSE.md b/tests/fixtures/gltf/TextureTransformTest/LICENSE.md new file mode 100644 index 0000000..1315107 --- /dev/null +++ b/tests/fixtures/gltf/TextureTransformTest/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Texture Transform Test + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Zero v1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/legalcode) [SPDX license identifier: "CC0-1.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + +<!-- This file is auto-generated by modelmetadata. Do not edit by hand. --> diff --git a/tests/fixtures/gltf/TextureTransformTest/glTF/Arrow.png b/tests/fixtures/gltf/TextureTransformTest/glTF/Arrow.png new file mode 100644 index 0000000..fe3405b Binary files /dev/null and b/tests/fixtures/gltf/TextureTransformTest/glTF/Arrow.png differ diff --git a/tests/fixtures/gltf/TextureTransformTest/glTF/Correct.png b/tests/fixtures/gltf/TextureTransformTest/glTF/Correct.png new file mode 100644 index 0000000..e332824 Binary files /dev/null and b/tests/fixtures/gltf/TextureTransformTest/glTF/Correct.png differ diff --git a/tests/fixtures/gltf/TextureTransformTest/glTF/Error.png b/tests/fixtures/gltf/TextureTransformTest/glTF/Error.png new file mode 100644 index 0000000..35acf6e Binary files /dev/null and b/tests/fixtures/gltf/TextureTransformTest/glTF/Error.png differ diff --git a/tests/fixtures/gltf/TextureTransformTest/glTF/NotSupported.png b/tests/fixtures/gltf/TextureTransformTest/glTF/NotSupported.png new file mode 100644 index 0000000..721e7fd Binary files /dev/null and b/tests/fixtures/gltf/TextureTransformTest/glTF/NotSupported.png differ diff --git a/tests/fixtures/gltf/TextureTransformTest/glTF/TextureTransformTest.bin b/tests/fixtures/gltf/TextureTransformTest/glTF/TextureTransformTest.bin new file mode 100644 index 0000000..6765a13 Binary files /dev/null and b/tests/fixtures/gltf/TextureTransformTest/glTF/TextureTransformTest.bin differ diff --git a/tests/fixtures/gltf/TextureTransformTest/glTF/TextureTransformTest.gltf b/tests/fixtures/gltf/TextureTransformTest/glTF/TextureTransformTest.gltf new file mode 100644 index 0000000..6dde51d --- /dev/null +++ b/tests/fixtures/gltf/TextureTransformTest/glTF/TextureTransformTest.gltf @@ -0,0 +1,540 @@ +{ + "accessors": [ + { + "bufferView": 0, + "componentType": 5126, + "count": 4, + "type": "VEC3", + "max": [ + 0.5, + 0.5, + 0.0 + ], + "min": [ + -0.5, + -0.5, + 0.0 + ], + "name": "Positions" + }, + { + "bufferView": 1, + "componentType": 5126, + "count": 4, + "type": "VEC2", + "name": "UV0" + }, + { + "bufferView": 2, + "componentType": 5126, + "count": 4, + "type": "VEC2", + "name": "UV1" + }, + { + "bufferView": 3, + "componentType": 5125, + "count": 6, + "type": "SCALAR", + "name": "Indices" + } + ], + "asset": { + "version": "2.0" + }, + "buffers": [ + { + "uri": "TextureTransformTest.bin", + "byteLength": 136 + } + ], + "bufferViews": [ + { + "buffer": 0, + "byteLength": 48, + "name": "Positions" + }, + { + "buffer": 0, + "byteOffset": 48, + "byteLength": 32, + "name": "UV0" + }, + { + "buffer": 0, + "byteOffset": 80, + "byteLength": 32, + "name": "UV1" + }, + { + "buffer": 0, + "byteOffset": 112, + "byteLength": 24, + "name": "Indices" + } + ], + "extensionsUsed": [ + "KHR_texture_transform" + ], + "images": [ + { + "uri": "UV.png" + }, + { + "uri": "Arrow.png" + }, + { + "uri": "Correct.png" + }, + { + "uri": "NotSupported.png" + }, + { + "uri": "Error.png" + } + ], + "materials": [ + { + "name": "Offset U", + "pbrMetallicRoughness": { + "baseColorTexture": { + "index": 0, + "extensions": { + "KHR_texture_transform": { + "offset": [ + 0.5, + 0.0 + ] + } + } + }, + "metallicFactor": 0 + } + }, + { + "name": "Offset V", + "pbrMetallicRoughness": { + "baseColorTexture": { + "index": 0, + "extensions": { + "KHR_texture_transform": { + "offset": [ + 0.0, + 0.5 + ] + } + } + }, + "metallicFactor": 0 + } + }, + { + "name": "Offset UV", + "pbrMetallicRoughness": { + "baseColorTexture": { + "index": 0, + "extensions": { + "KHR_texture_transform": { + "offset": [ + 0.5, + 0.5 + ] + } + } + }, + "metallicFactor": 0 + } + }, + { + "name": "Rotation", + "pbrMetallicRoughness": { + "baseColorTexture": { + "index": 1, + "extensions": { + "KHR_texture_transform": { + "rotation": 0.39269908169872415480783042290994 + } + } + }, + "metallicFactor": 0 + } + }, + { + "name": "Scale", + "pbrMetallicRoughness": { + "baseColorTexture": { + "index": 1, + "extensions": { + "KHR_texture_transform": { + "scale": [ + 1.5, + 1.5 + ] + } + } + }, + "metallicFactor": 0 + } + }, + { + "name": "All", + "pbrMetallicRoughness": { + "baseColorTexture": { + "index": 1, + "extensions": { + "KHR_texture_transform": { + "offset": [ + -0.2, + -0.1 + ], + "rotation": 0.3, + "scale": [ + 1.5, + 1.5 + ] + } + } + }, + "metallicFactor": 0 + } + }, + { + "name": "Correct", + "pbrMetallicRoughness": { + "baseColorTexture": { + "index": 2 + }, + "metallicFactor": 0 + } + }, + { + "name": "NotSupported", + "pbrMetallicRoughness": { + "baseColorTexture": { + "index": 3 + }, + "metallicFactor": 0 + } + }, + { + "name": "Error", + "pbrMetallicRoughness": { + "baseColorTexture": { + "index": 4 + }, + "metallicFactor": 0 + } + } + ], + "meshes": [ + { + "name": "Offset U", + "primitives": [ + { + "attributes": { + "POSITION": 0, + "TEXCOORD_0": 2 + }, + "indices": 3, + "material": 0 + } + ] + }, + { + "name": "Offset V", + "primitives": [ + { + "attributes": { + "POSITION": 0, + "TEXCOORD_0": 2 + }, + "indices": 3, + "material": 1 + } + ] + }, + { + "name": "Offset UV", + "primitives": [ + { + "attributes": { + "POSITION": 0, + "TEXCOORD_0": 2 + }, + "indices": 3, + "material": 2 + } + ] + }, + { + "name": "Rotation", + "primitives": [ + { + "attributes": { + "POSITION": 0, + "TEXCOORD_0": 1 + }, + "indices": 3, + "material": 3 + } + ] + }, + { + "name": "Scale", + "primitives": [ + { + "attributes": { + "POSITION": 0, + "TEXCOORD_0": 1 + }, + "indices": 3, + "material": 4 + } + ] + }, + { + "name": "All", + "primitives": [ + { + "attributes": { + "POSITION": 0, + "TEXCOORD_0": 1 + }, + "indices": 3, + "material": 5 + } + ] + }, + { + "name": "Correct Marker", + "primitives": [ + { + "attributes": { + "POSITION": 0, + "TEXCOORD_0": 1 + }, + "indices": 3, + "material": 6 + } + ] + }, + { + "name": "Not Supported Marker", + "primitives": [ + { + "attributes": { + "POSITION": 0, + "TEXCOORD_0": 1 + }, + "indices": 3, + "material": 7 + } + ] + }, + { + "name": "Error Marker", + "primitives": [ + { + "attributes": { + "POSITION": 0, + "TEXCOORD_0": 1 + }, + "indices": 3, + "material": 8 + } + ] + } + ], + "nodes": [ + { + "name": "Offset U", + "mesh": 0, + "translation": [ + -1.1, + 0.55, + 0 + ] + }, + { + "name": "Offset V", + "mesh": 1, + "translation": [ + 0, + 0.55, + 0 + ] + }, + { + "name": "Offset UV", + "mesh": 2, + "translation": [ + 1.1, + 0.55, + 0 + ] + }, + { + "name": "Rotation", + "mesh": 3, + "translation": [ + -1.1, + -0.55, + 0 + ], + "children": [ + 4, + 5, + 6 + ] + }, + { + "name": "Rotation - Correct", + "mesh": 6, + "translation": [ + -0.07904822439840125109869401756656, + -0.51626748576241543174100150833647, + 0.01 + ], + "scale": [ + 0.15, + 0.15, + 0.15 + ] + }, + { + "name": "Rotation - Not Supported", + "mesh": 7, + "translation": [ + 0.27781745930520227684092879831533, + -0.27781745930520227684092879831533, + 0.01 + ], + "scale": [ + 0.15, + 0.15, + 0.15 + ] + }, + { + "name": "Rotation - Error", + "mesh": 8, + "translation": [ + 0.51626748576241543174100150833647, + 0.07904822439840125109869401756656, + 0.01 + ], + "scale": [ + 0.15, + 0.15, + 0.15 + ] + }, + { + "name": "Scale", + "mesh": 4, + "translation": [ + 0, + -0.55, + 0 + ], + "children": [ + 8, + 9 + ] + }, + { + "name": "Scale - Correct", + "mesh": 6, + "translation": [ + 0.01854497287013485122728586554355, + -0.01854497287013485122728586554355, + 0.01 + ], + "scale": [ + 0.1, + 0.1, + 0.1 + ] + }, + { + "name": "Scale - Not Supported", + "mesh": 7, + "translation": [ + 0.27781745930520227684092879831533, + -0.27781745930520227684092879831533, + 0.01 + ], + "scale": [ + 0.15, + 0.15, + 0.15 + ] + }, + { + "name": "All", + "mesh": 5, + "translation": [ + 1.1, + -0.55, + 0 + ], + "children": [ + 11 + ] + }, + { + "name": "All - Correct", + "mesh": 6, + "translation": [ + -0.07, + -0.25, + 0.01 + ], + "scale": [ + 0.1, + 0.1, + 0.1 + ] + } + ], + "scene": 0, + "scenes": [ + { + "nodes": [ + 0, + 1, + 2, + 3, + 7, + 10 + ] + } + ], + "textures": [ + { + "source": 0, + "sampler": 0 + }, + { + "source": 1, + "sampler": 0 + }, + { + "source": 2 + }, + { + "source": 3 + }, + { + "source": 4 + } + ], + "samplers": [ + { + "wrapS": 33071, + "wrapT": 33071, + "magFilter": 9729, + "minFilter": 9729 + } + ] +} \ No newline at end of file diff --git a/tests/fixtures/gltf/TextureTransformTest/glTF/UV.png b/tests/fixtures/gltf/TextureTransformTest/glTF/UV.png new file mode 100644 index 0000000..c1a6d4d Binary files /dev/null and b/tests/fixtures/gltf/TextureTransformTest/glTF/UV.png differ diff --git a/tests/fixtures/gltf/Triangle/LICENSE.md b/tests/fixtures/gltf/Triangle/LICENSE.md new file mode 100644 index 0000000..65dc616 --- /dev/null +++ b/tests/fixtures/gltf/Triangle/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Triangle + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Zero v1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/legalcode) [SPDX license identifier: "CC0-1.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + +<!-- This file is auto-generated by modelmetadata. Do not edit by hand. --> diff --git a/tests/fixtures/gltf/Triangle/glTF-Embedded/Triangle.gltf b/tests/fixtures/gltf/Triangle/glTF-Embedded/Triangle.gltf new file mode 100644 index 0000000..40cab5a --- /dev/null +++ b/tests/fixtures/gltf/Triangle/glTF-Embedded/Triangle.gltf @@ -0,0 +1,70 @@ +{ + "scene" : 0, + "scenes" : [ + { + "nodes" : [ 0 ] + } + ], + + "nodes" : [ + { + "mesh" : 0 + } + ], + + "meshes" : [ + { + "primitives" : [ { + "attributes" : { + "POSITION" : 1 + }, + "indices" : 0 + } ] + } + ], + + "buffers" : [ + { + "uri" : "data:application/octet-stream;base64,AAABAAIAAAAAAAAAAAAAAAAAAAAAAIA/AAAAAAAAAAAAAAAAAACAPwAAAAA=", + "byteLength" : 44 + } + ], + "bufferViews" : [ + { + "buffer" : 0, + "byteOffset" : 0, + "byteLength" : 6, + "target" : 34963 + }, + { + "buffer" : 0, + "byteOffset" : 8, + "byteLength" : 36, + "target" : 34962 + } + ], + "accessors" : [ + { + "bufferView" : 0, + "byteOffset" : 0, + "componentType" : 5123, + "count" : 3, + "type" : "SCALAR", + "max" : [ 2 ], + "min" : [ 0 ] + }, + { + "bufferView" : 1, + "byteOffset" : 0, + "componentType" : 5126, + "count" : 3, + "type" : "VEC3", + "max" : [ 1.0, 1.0, 0.0 ], + "min" : [ 0.0, 0.0, 0.0 ] + } + ], + + "asset" : { + "version" : "2.0" + } +} diff --git a/tests/fixtures/gltf/TriangleWithoutIndices/LICENSE.md b/tests/fixtures/gltf/TriangleWithoutIndices/LICENSE.md new file mode 100644 index 0000000..4c12f0e --- /dev/null +++ b/tests/fixtures/gltf/TriangleWithoutIndices/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Triangle Without Indices + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Zero v1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/legalcode) [SPDX license identifier: "CC0-1.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + +<!-- This file is auto-generated by modelmetadata. Do not edit by hand. --> diff --git a/tests/fixtures/gltf/TriangleWithoutIndices/glTF/TriangleWithoutIndices.bin b/tests/fixtures/gltf/TriangleWithoutIndices/glTF/TriangleWithoutIndices.bin new file mode 100644 index 0000000..f9f96d8 Binary files /dev/null and b/tests/fixtures/gltf/TriangleWithoutIndices/glTF/TriangleWithoutIndices.bin differ diff --git a/tests/fixtures/gltf/TriangleWithoutIndices/glTF/TriangleWithoutIndices.gltf b/tests/fixtures/gltf/TriangleWithoutIndices/glTF/TriangleWithoutIndices.gltf new file mode 100644 index 0000000..b3acc55 --- /dev/null +++ b/tests/fixtures/gltf/TriangleWithoutIndices/glTF/TriangleWithoutIndices.gltf @@ -0,0 +1,55 @@ +{ + "scene" : 0, + "scenes" : [ + { + "nodes" : [ 0 ] + } + ], + + "nodes" : [ + { + "mesh" : 0 + } + ], + + "meshes" : [ + { + "primitives" : [ { + "attributes" : { + "POSITION" : 0 + } + } ] + } + ], + + "buffers" : [ + { + "uri" : "TriangleWithoutIndices.bin", + "byteLength" : 36 + } + ], + "bufferViews" : [ + { + "buffer" : 0, + "byteOffset" : 0, + "byteLength" : 36, + "target" : 34962 + } + ], + "accessors" : [ + { + "bufferView" : 0, + "byteOffset" : 0, + "componentType" : 5126, + "count" : 3, + "type" : "VEC3", + "max" : [ 1.0, 1.0, 0.0 ], + "min" : [ 0.0, 0.0, 0.0 ] + } + ], + + "asset" : { + "version" : "2.0" + } +} + diff --git a/tests/fixtures/gltf/UnicodeTest/LICENSE.md b/tests/fixtures/gltf/UnicodeTest/LICENSE.md new file mode 100644 index 0000000..06103d1 --- /dev/null +++ b/tests/fixtures/gltf/UnicodeTest/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Unicode❤♻Test + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Zero v1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/legalcode) [SPDX license identifier: "CC0-1.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + +<!-- This file is auto-generated by modelmetadata. Do not edit by hand. --> diff --git a/tests/fixtures/gltf/UnicodeTest/glTF-Binary/UnicodeTest.glb b/tests/fixtures/gltf/UnicodeTest/glTF-Binary/UnicodeTest.glb new file mode 100644 index 0000000..e5e8409 Binary files /dev/null and b/tests/fixtures/gltf/UnicodeTest/glTF-Binary/UnicodeTest.glb differ diff --git a/tests/fixtures/gltf/UnlitTest/LICENSE.md b/tests/fixtures/gltf/UnlitTest/LICENSE.md new file mode 100644 index 0000000..2fc6a6a --- /dev/null +++ b/tests/fixtures/gltf/UnlitTest/LICENSE.md @@ -0,0 +1,17 @@ +# LICENSE file for the model: Unlit Test + +All files in this directory tree are licensed as indicated below. + +* All files directly associated with the model including all text, image and binary files: + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +* This file and all other metadocumentation files including "metadata.json": + + * [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) [SPDX license identifier: "CC-BY-4.0"] + +Full license text of these licenses are available at the links above. + +This license excludes logos and associated trademarks. + +<!-- This file is auto-generated by modelmetadata. Do not edit by hand. --> diff --git a/tests/fixtures/gltf/UnlitTest/glTF-Binary/UnlitTest.glb b/tests/fixtures/gltf/UnlitTest/glTF-Binary/UnlitTest.glb new file mode 100644 index 0000000..6998aea Binary files /dev/null and b/tests/fixtures/gltf/UnlitTest/glTF-Binary/UnlitTest.glb differ diff --git a/tests/fixtures/vox/MagicaVoxel-file-format-vox-extension.txt b/tests/fixtures/vox/MagicaVoxel-file-format-vox-extension.txt new file mode 100644 index 0000000..181b376 --- /dev/null +++ b/tests/fixtures/vox/MagicaVoxel-file-format-vox-extension.txt @@ -0,0 +1,165 @@ +* there can be multiple SIZE and XYZI chunks for multiple models; model id is their index in the stored order +* the palette chunk is always stored into the file, so default palette is not needed any more +* the MATT chunk is deprecated, replaced by the MATL chunk, see (4) +* (a), (b), (c) are special data types; (d) is the scene graph in the world editor + +================================= +(a) STRING type + +int32 : buffer size (in bytes) +int8xN : buffer (without the ending "\0") + +================================= +(b) DICT type + +int32 : num of key-value pairs + +// for each key-value pair +{ +STRING : key +STRING : value +}xN + +================================= +(c) ROTATION type + +store a row-major rotation in the bits of a byte + +for example : +R = + 0 1 0 + 0 0 -1 +-1 0 0 +==> +unsigned char _r = (1 << 0) | (2 << 2) | (0 << 4) | (1 << 5) | (1 << 6) + +bit | value +0-1 : 1 : index of the non-zero entry in the first row +2-3 : 2 : index of the non-zero entry in the second row +4 : 0 : the sign in the first row (0 : positive; 1 : negative) +5 : 1 : the sign in the second row (0 : positive; 1 : negative) +6 : 1 : the sign in the third row (0 : positive; 1 : negative) + +================================= +(d) Scene Graph + +T : Transform Node +G : Group Node +S : Shape Node + + T + | + G + / \ + T T + | | + G S + / \ + T T + | | + S S + +================================= +(1) Transform Node Chunk : "nTRN" + +int32 : node id +DICT : node attributes + (_name : string) + (_hidden : 0/1) +int32 : child node id +int32 : reserved id (must be -1) +int32 : layer id +int32 : num of frames (must be greater than 0) + +// for each frame +{ +DICT : frame attributes + (_r : int8) ROTATION, see (c) + (_t : int32x3) translation + (_f : int32) frame index, start from 0 +}xN + +================================= +(2) Group Node Chunk : "nGRP" + +int32 : node id +DICT : node attributes +int32 : num of children nodes + +// for each child +{ +int32 : child node id +}xN + +================================= +(3) Shape Node Chunk : "nSHP" + +int32 : node id +DICT : node attributes +int32 : num of models (must be greater than 0) + +// for each model +{ +int32 : model id +DICT : model attributes : reserved + (_f : int32) frame index, start from 0 +}xN + +================================= +(4) Material Chunk : "MATL" + +int32 : material id +DICT : material properties + (_type : str) _diffuse, _metal, _glass, _emit + (_weight : float) range 0 ~ 1 + (_rough : float) + (_spec : float) + (_ior : float) + (_att : float) + (_flux : float) + (_plastic) + +================================= +(5) Layer Chunk : "LAYR" + +int32 : layer id +DICT : layer attribute + (_name : string) + (_hidden : 0/1) +int32 : reserved id, must be -1 + +================================= +(6) Render Objects Chunk : "rOBJ" + +DICT : rendering attributes + +================================= +(7) Render Camera Chunk : "rCAM" + +int32 : camera id +DICT : camera attribute + (_mode : string) + (_focus : vec(3)) + (_angle : vec(3)) + (_radius : int) + (_frustum : float) + (_fov : int) + +================================= +(8) Palette Note Chunk : "NOTE" + +int32 : num of color names + +// for each name +{ +STRING : color name +}xN + +================================= +(9) Index MAP Chunk : "IMAP" + +size : 256 +// for each index +{ +int32 : palette index association +}x256 diff --git a/tests/fixtures/vox/MagicaVoxel-file-format-vox.txt b/tests/fixtures/vox/MagicaVoxel-file-format-vox.txt new file mode 100644 index 0000000..d15efe7 --- /dev/null +++ b/tests/fixtures/vox/MagicaVoxel-file-format-vox.txt @@ -0,0 +1,111 @@ +MagicaVoxel .vox File Format [10/18/2016] + +1. File Structure : RIFF style +------------------------------------------------------------------------------- +# Bytes | Type | Value +------------------------------------------------------------------------------- +1x4 | char | id 'VOX ' : 'V' 'O' 'X' 'space', 'V' is first +4 | int | version number : 150 + +Chunk 'MAIN' +{ + // pack of models + Chunk 'PACK' : optional + + // models + Chunk 'SIZE' + Chunk 'XYZI' + + Chunk 'SIZE' + Chunk 'XYZI' + + ... + + Chunk 'SIZE' + Chunk 'XYZI' + + // palette + Chunk 'RGBA' : optional +} +------------------------------------------------------------------------------- + + +2. Chunk Structure +------------------------------------------------------------------------------- +# Bytes | Type | Value +------------------------------------------------------------------------------- +1x4 | char | chunk id +4 | int | num bytes of chunk content (N) +4 | int | num bytes of children chunks (M) + +N | | chunk content + +M | | children chunks +------------------------------------------------------------------------------- + + +3. Chunk id 'MAIN' : the root chunk and parent chunk of all the other chunks + + +4. Chunk id 'PACK' : if it is absent, only one model in the file; only used for the animation in 0.98.2 +------------------------------------------------------------------------------- +# Bytes | Type | Value +------------------------------------------------------------------------------- +4 | int | numModels : num of SIZE and XYZI chunks +------------------------------------------------------------------------------- + + +5. Chunk id 'SIZE' : model size +------------------------------------------------------------------------------- +# Bytes | Type | Value +------------------------------------------------------------------------------- +4 | int | size x +4 | int | size y +4 | int | size z : gravity direction +------------------------------------------------------------------------------- + + +6. Chunk id 'XYZI' : model voxels, paired with the SIZE chunk +------------------------------------------------------------------------------- +# Bytes | Type | Value +------------------------------------------------------------------------------- +4 | int | numVoxels (N) +4 x N | int | (x, y, z, colorIndex) : 1 byte for each component +------------------------------------------------------------------------------- + + +7. Chunk id 'RGBA' : palette +------------------------------------------------------------------------------- +# Bytes | Type | Value +------------------------------------------------------------------------------- +4 x 256 | int | (R, G, B, A) : 1 byte for each component + | * <NOTICE> + | * color [0-254] are mapped to palette index [1-255], e.g : + | + | for ( int i = 0; i <= 254; i++ ) { + | palette[i + 1] = ReadRGBA(); + | } +------------------------------------------------------------------------------- + + +8. Default Palette : if chunk 'RGBA' is absent +------------------------------------------------------------------------------- +unsigned int default_palette[256] = { + 0x00000000, 0xffffffff, 0xffccffff, 0xff99ffff, 0xff66ffff, 0xff33ffff, 0xff00ffff, 0xffffccff, 0xffccccff, 0xff99ccff, 0xff66ccff, 0xff33ccff, 0xff00ccff, 0xffff99ff, 0xffcc99ff, 0xff9999ff, + 0xff6699ff, 0xff3399ff, 0xff0099ff, 0xffff66ff, 0xffcc66ff, 0xff9966ff, 0xff6666ff, 0xff3366ff, 0xff0066ff, 0xffff33ff, 0xffcc33ff, 0xff9933ff, 0xff6633ff, 0xff3333ff, 0xff0033ff, 0xffff00ff, + 0xffcc00ff, 0xff9900ff, 0xff6600ff, 0xff3300ff, 0xff0000ff, 0xffffffcc, 0xffccffcc, 0xff99ffcc, 0xff66ffcc, 0xff33ffcc, 0xff00ffcc, 0xffffcccc, 0xffcccccc, 0xff99cccc, 0xff66cccc, 0xff33cccc, + 0xff00cccc, 0xffff99cc, 0xffcc99cc, 0xff9999cc, 0xff6699cc, 0xff3399cc, 0xff0099cc, 0xffff66cc, 0xffcc66cc, 0xff9966cc, 0xff6666cc, 0xff3366cc, 0xff0066cc, 0xffff33cc, 0xffcc33cc, 0xff9933cc, + 0xff6633cc, 0xff3333cc, 0xff0033cc, 0xffff00cc, 0xffcc00cc, 0xff9900cc, 0xff6600cc, 0xff3300cc, 0xff0000cc, 0xffffff99, 0xffccff99, 0xff99ff99, 0xff66ff99, 0xff33ff99, 0xff00ff99, 0xffffcc99, + 0xffcccc99, 0xff99cc99, 0xff66cc99, 0xff33cc99, 0xff00cc99, 0xffff9999, 0xffcc9999, 0xff999999, 0xff669999, 0xff339999, 0xff009999, 0xffff6699, 0xffcc6699, 0xff996699, 0xff666699, 0xff336699, + 0xff006699, 0xffff3399, 0xffcc3399, 0xff993399, 0xff663399, 0xff333399, 0xff003399, 0xffff0099, 0xffcc0099, 0xff990099, 0xff660099, 0xff330099, 0xff000099, 0xffffff66, 0xffccff66, 0xff99ff66, + 0xff66ff66, 0xff33ff66, 0xff00ff66, 0xffffcc66, 0xffcccc66, 0xff99cc66, 0xff66cc66, 0xff33cc66, 0xff00cc66, 0xffff9966, 0xffcc9966, 0xff999966, 0xff669966, 0xff339966, 0xff009966, 0xffff6666, + 0xffcc6666, 0xff996666, 0xff666666, 0xff336666, 0xff006666, 0xffff3366, 0xffcc3366, 0xff993366, 0xff663366, 0xff333366, 0xff003366, 0xffff0066, 0xffcc0066, 0xff990066, 0xff660066, 0xff330066, + 0xff000066, 0xffffff33, 0xffccff33, 0xff99ff33, 0xff66ff33, 0xff33ff33, 0xff00ff33, 0xffffcc33, 0xffcccc33, 0xff99cc33, 0xff66cc33, 0xff33cc33, 0xff00cc33, 0xffff9933, 0xffcc9933, 0xff999933, + 0xff669933, 0xff339933, 0xff009933, 0xffff6633, 0xffcc6633, 0xff996633, 0xff666633, 0xff336633, 0xff006633, 0xffff3333, 0xffcc3333, 0xff993333, 0xff663333, 0xff333333, 0xff003333, 0xffff0033, + 0xffcc0033, 0xff990033, 0xff660033, 0xff330033, 0xff000033, 0xffffff00, 0xffccff00, 0xff99ff00, 0xff66ff00, 0xff33ff00, 0xff00ff00, 0xffffcc00, 0xffcccc00, 0xff99cc00, 0xff66cc00, 0xff33cc00, + 0xff00cc00, 0xffff9900, 0xffcc9900, 0xff999900, 0xff669900, 0xff339900, 0xff009900, 0xffff6600, 0xffcc6600, 0xff996600, 0xff666600, 0xff336600, 0xff006600, 0xffff3300, 0xffcc3300, 0xff993300, + 0xff663300, 0xff333300, 0xff003300, 0xffff0000, 0xffcc0000, 0xff990000, 0xff660000, 0xff330000, 0xff0000ee, 0xff0000dd, 0xff0000bb, 0xff0000aa, 0xff000088, 0xff000077, 0xff000055, 0xff000044, + 0xff000022, 0xff000011, 0xff00ee00, 0xff00dd00, 0xff00bb00, 0xff00aa00, 0xff008800, 0xff007700, 0xff005500, 0xff004400, 0xff002200, 0xff001100, 0xffee0000, 0xffdd0000, 0xffbb0000, 0xffaa0000, + 0xff880000, 0xff770000, 0xff550000, 0xff440000, 0xff220000, 0xff110000, 0xffeeeeee, 0xffdddddd, 0xffbbbbbb, 0xffaaaaaa, 0xff888888, 0xff777777, 0xff555555, 0xff444444, 0xff222222, 0xff111111 +}; +------------------------------------------------------------------------------- diff --git a/tests/fixtures/vox/chr_knight.vox b/tests/fixtures/vox/chr_knight.vox new file mode 100644 index 0000000..3ec1006 Binary files /dev/null and b/tests/fixtures/vox/chr_knight.vox differ diff --git a/tests/fixtures/vox/chr_sword.vox b/tests/fixtures/vox/chr_sword.vox new file mode 100644 index 0000000..870b63e Binary files /dev/null and b/tests/fixtures/vox/chr_sword.vox differ diff --git a/tests/fixtures/vox/deer.vox b/tests/fixtures/vox/deer.vox new file mode 100644 index 0000000..759e055 Binary files /dev/null and b/tests/fixtures/vox/deer.vox differ diff --git a/tests/fixtures/vox/maze.vox b/tests/fixtures/vox/maze.vox new file mode 100644 index 0000000..2d14dd4 Binary files /dev/null and b/tests/fixtures/vox/maze.vox differ diff --git a/tests/fixtures/vox/ogt_chr_knight.vox b/tests/fixtures/vox/ogt_chr_knight.vox new file mode 100644 index 0000000..a5017f1 Binary files /dev/null and b/tests/fixtures/vox/ogt_chr_knight.vox differ diff --git a/tests/fixtures/vox/ogt_test_groups.vox b/tests/fixtures/vox/ogt_test_groups.vox new file mode 100644 index 0000000..41c26d5 Binary files /dev/null and b/tests/fixtures/vox/ogt_test_groups.vox differ diff --git a/tests/fixtures/vox/ogt_test_meta_chunk.vox b/tests/fixtures/vox/ogt_test_meta_chunk.vox new file mode 100644 index 0000000..9b566a0 Binary files /dev/null and b/tests/fixtures/vox/ogt_test_meta_chunk.vox differ diff --git a/tests/fixtures/vox/ogt_test_multiple_model_scene.vox b/tests/fixtures/vox/ogt_test_multiple_model_scene.vox new file mode 100644 index 0000000..2e74aeb Binary files /dev/null and b/tests/fixtures/vox/ogt_test_multiple_model_scene.vox differ diff --git a/tests/font/bmfont.luau b/tests/font/bmfont.luau new file mode 100644 index 0000000..46ae665 --- /dev/null +++ b/tests/font/bmfont.luau @@ -0,0 +1,166 @@ +-- font/bmfont tests: the text, XML and binary descriptors (an independent Python writer, glyphs rendered by FreeType) +-- decode to the reference description; each variant re-encodes to every variant and decodes back unchanged (binary: +-- byte-identical to the Python writer); Font methods (glyphIndex / advance / kern); lazy pages through opts.loadPage +-- and the page PNG (glyph crops against FreeType's bitmaps); bake() from a TrueType font; errors; the fuzz pass. +-- Fixtures: tools/fixtures/bmfont.py. +local T = require("@tests/T") +local F = require("@formats") +local Bmfont = require("@formats/font/bmfont") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/bmfont") + +local t = T.suite("bmfont") +t:eq(Bmfont.name, "bmfont", "name") + +local CHAR_KEYS = { "id", "x", "y", "width", "height", "xoffset", "yoffset", "xadvance", "page", "chnl" } + +local function sameDesc(got: any, want: any, label: string, faceQuotes: boolean) + local face = want.info.face + if not faceQuotes then + face = string.gsub(face, '"', "") + end + t:eq(got.info.face, face, label .. ": face") + for _, k in { "size", "bold", "italic", "unicode", "stretchH", "smooth", "aa", "outline" } do + t:eq(got.info[k], want.info[k], label .. ": info." .. k) + end + for i = 1, 4 do + t:eq(got.info.padding[i], want.info.padding[i], label .. ": padding") + end + t:eq(got.info.spacing[1] .. "," .. got.info.spacing[2], want.info.spacing[1] .. "," .. want.info.spacing[2], label .. ": spacing") + for k, v in want.common do + t:eq(got.common[k], v, label .. ": common." .. k) + end + t:eq(#got.pages, #want.pages, label .. ": pages") + t:eq(got.pages[1], want.pages[1], label .. ": page file") + t:eq(#got.chars, #want.chars, label .. ": char count") + for i, c in want.chars do + for _, k in CHAR_KEYS do + t:eq(got.chars[i][k], c[k], string.format("%s: char %d %s", label, c.id, k)) + end + end + t:eq(#got.kernings, #want.kernings, label .. ": kerning count") + for i, k in want.kernings do + local g = got.kernings[i] + t:check(g[1] == k[1] and g[2] == k[2] and g[3] == k[3], label .. ": kerning " .. i) + end +end + +-- 1. the three encodings +local fonts = {} +for _, v in { "text", "xml", "binary" } do + local f, err = Bmfont.decode(Bytes.reader(buffer.fromstring(Fx[v]))) + t:check(f, v .. ": " .. tostring(err)) + t:eq(f.meta.variant, v, v .. ": variant") + sameDesc(f.meta.bmfont, Fx.desc, v, v ~= "text") + fonts[v] = f + t:eq(F.detect(Fx[v]), "bmfont", v .. ": F.detect") +end + +-- 2. re-encode every variant to every variant +for from, f in fonts do + for _, to in { "text", "xml", "binary" } do + local b, err = Bmfont.encode(f, { variant = to :: any }) + t:check(b, from .. " -> " .. to .. ": " .. tostring(err)) + local back = Bmfont.decode(Bytes.reader(b :: buffer)) + t:check(back and back.meta.variant == to, from .. " -> " .. to .. ": decodes") + sameDesc(back.meta.bmfont, Fx.desc, from .. " -> " .. to, from ~= "text" and to ~= "text") + if from == "binary" and to == "binary" then + t:eq(buffer.tostring(b :: buffer), Fx.binary, "binary re-encode is byte-identical to the reference writer") + end + end +end +t:eq(buffer.tostring(F.save(fonts.xml, nil, { format = "fnt" })):sub(1, 5), "<?xml", "F.save keeps the variant") + +-- 3. Font methods +do + local f = fonts.text + local gA, gV = f:glyphIndex(65), f:glyphIndex(86) + t:check(gA > 0 and gV > 0, "glyphIndex") + t:eq(f:glyphIndex(0x1F600), 0, "missing glyph") + t:eq(f:advance(gA), Fx.desc.chars[gA].xadvance, "advance") + t:eq(f:kern(gA, gV), Fx.desc.kernings[2][3], "kern A V") + t:eq(f:kern(gV, gA), Fx.desc.kernings[9][3], "kern V A") + t:eq(f.unitsPerEm, 24, "size") + t:check(f:outline(gA) == nil, "bitmap fonts have no outline") + t:check(f:rasterize(gA, 24) == nil, "no pages loaded yet") + local ok, e = f:loadPages() + t:check(not ok and e and e.code == Err.ARG, "loadPages without a loader") +end + +-- 4. lazy pages: the api attaches opts.loadPage; the PNG goes through F.load +do + local asked = {} + local f = F.load(Fx.binary, { + loadPage = function(file: string) + table.insert(asked, file) + return Fx.page + end, + }) + t:check(f and f.pages == nil and #asked == 0, "pages are lazy") + local crcs = {} + for _, c in Fx.crops do + crcs[c.id] = c.crc + end + local n = 0 + for _, c in Fx.desc.chars do + local img = f:rasterize(f:glyphIndex(c.id), 24) + t:check(img and img.format == "alpha8" and img.width == c.width, "rasterize " .. c.id) + t:eq(Crc32.of(img.pixels), crcs[c.id], "glyph crop " .. c.id .. " = FreeType's bitmap") + t:eq(img.meta.left, c.xoffset, "left") + n += 1 + end + t:eq(#asked, 1, "page loaded once") + t:eq(asked[1], "karla_0.png", "page file name") + t:note("%d glyph crops from the lazily loaded page match FreeType", n) +end + +-- 5. bake from a TrueType font +do + local ttf = F.font.load(Fx.ttf) + t:check(ttf, "ttf loads") + local baked, err = Bmfont.bake(ttf, { px = 20, chars = "Hello, wörld! AV" }) + t:check(baked, "bake: " .. tostring(err)) + t:eq(#baked.meta.bmfont.chars, 13, "unique characters baked") + t:check(baked.pages and #baked.pages == 1, "one page") + local g = baked:glyphIndex(string.byte("H")) + local a = baked:rasterize(g, 20) + local b = ttf:rasterize(ttf:glyphIndex(string.byte("H")), 20) + t:check(a and b and a.width == b.width and a.height == b.height, "baked glyph size") + t:eq(Crc32.of(a.pixels), Crc32.of(b.pixels), "baked glyph pixels = rasterize") + t:eq(a.meta.left, b.meta.left, "baked left") + t:eq(a.meta.top, b.meta.top, "baked top") + local enc = F.save(baked, nil, { format = "bmfont", variant = "binary" }) + local back = F.load(enc) + t:check(back and #back.meta.bmfont.chars == 13, "baked font round trip") + -- an outline font saved as fnt is baked on the way + local fnt = F.convert(Fx.ttf, "fnt", { px = 16 }) + t:check(fnt and string.sub(buffer.tostring(fnt), 1, 9) == "info face", "F.convert ttf -> fnt (text)") +end + +-- 6. errors and validation +do + local _, e1 = Bmfont.decode(Bytes.reader(buffer.fromstring("BMF\2"))) + t:check(e1 and e1.code == Err.UNSUPPORTED, "binary version 2: " .. tostring(e1)) + local _, e2 = Bmfont.decode(Bytes.reader(buffer.fromstring(string.sub(Fx.binary, 1, 40)))) + t:check(e2 and e2.code == Err.TRUNCATED, "truncated binary: " .. tostring(e2)) + local _, e3 = Bmfont.decode(Bytes.reader(buffer.fromstring("hello"))) + t:check(e3 and e3.code == Err.CORRUPT, "not a descriptor") + local f = Bmfont.decode(Bytes.reader(buffer.fromstring(Fx.text))) + f.meta.bmfont.chars[3].x = 1.5 + local _, e4 = Bmfont.encode(f) + t:check(e4 and e4.code == Err.ARG, "fractional field: " .. tostring(e4)) + local _, e5 = Bmfont.encode({ kind = "image" }) + t:check(e5 and e5.code == Err.ARG, "not a font") +end + +t:fuzz("decode", function(b: buffer) + local f = Bmfont.decode(Bytes.reader(b)) + if f then + Bmfont.encode(f, { variant = "binary" }) + end + return f +end, { Fx.binary, string.sub(Fx.text, 1, 3000), string.sub(Fx.xml, 1, 3000) }, { mutations = 40 }) + +t:done() diff --git a/tests/font/ttf.luau b/tests/font/ttf.luau new file mode 100644 index 0000000..5d78823 --- /dev/null +++ b/tests/font/ttf.luau @@ -0,0 +1,237 @@ +-- font/ttf tests (and codecs/TrueType, codecs/Cff): for the imgui-luau TrueType fonts, Source Sans 3 (CFF), a +-- 'kern'-table font and a collection: metrics, names, cmap samples, advances / side bearings, outline control boxes and +-- areas against fontTools; kerning against HarfBuzz (GPOS) and FreeType ('kern'); rasterize() against FreeType's +-- unhinted renders (PSNR); the api; errors; the fuzz pass. Fixtures: tools/fixtures/fonts.py. +local T = require("@tests/T") +local F = require("@formats") +local Ttf = require("@formats/font/ttf") +local Raster = require("@formats/codecs/Raster") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/fonts") + +local t = T.suite("ttf") + +t:eq(Ttf.name, "ttf", "name") +t:check(table.find(Ttf.extensions, "otf") and table.find(Ttf.extensions, "ttc"), "extensions") + +-- shoelace area of the flattened outline (font units) +local function area(cmds: any): number + local polys = Raster.flatten(cmds, nil, 0.02) + local a = 0 + for _, p in polys do + local n = #p + local x0, y0 = p[n - 1], p[n] + for i = 1, n - 1, 2 do + a += x0 * p[i + 1] - p[i] * y0 + x0, y0 = p[i], p[i + 1] + end + end + return a / 2 +end + +local function psnr(img: any, r: any): (number, number) + -- union of both bitmaps, aligned on the pen position + local ax0, ay0 = img.meta.left, -img.meta.top + local bx0, by0 = r.left, -r.top + local x0, y0 = math.min(ax0, bx0), math.min(ay0, by0) + local x1, y1 = math.max(ax0 + img.width, bx0 + r.w), math.max(ay0 + img.height, by0 + r.h) + local se, n, ink = 0, 0, 0 + for y = y0, y1 - 1 do + for x = x0, x1 - 1 do + local a, b = 0, 0 + local ix, iy = x - ax0, y - ay0 + if ix >= 0 and iy >= 0 and ix < img.width and iy < img.height then + a = buffer.readu8(img.pixels, iy * img.width + ix) + end + local jx, jy = x - bx0, y - by0 + if jx >= 0 and jy >= 0 and jx < r.w and jy < r.h then + b = string.byte(r.pixels, jy * r.w + jx + 1) + end + se += (a - b) * (a - b) + ink += b + n += 1 + end + end + if n == 0 or se == 0 then + return 99, ink + end + return 10 * math.log10(255 * 255 / (se / n)), ink +end + +local fonts: { [string]: any } = {} +local worstPsnr, sumPsnr, nPsnr = 99, 0, 0 +for _, c in Fx.fonts do + local font, err = Ttf.decode(Bytes.reader(buffer.fromstring(c.data)), { index = c.index }) + t:check(font, c.name .. ": decode: " .. tostring(err)) + fonts[c.name] = font + t:eq(font.kind, "font", c.name .. ": kind") + t:eq(font.unitsPerEm, c.upem, c.name .. ": unitsPerEm") + t:eq(font.ascent, c.ascent, c.name .. ": ascent") + t:eq(font.descent, c.descent, c.name .. ": descent") + t:eq(font.lineGap, c.lineGap, c.name .. ": lineGap") + t:eq(font.numGlyphs, c.numGlyphs, c.name .. ": numGlyphs") + t:eq(font.info.family, c.family, c.name .. ": family") + t:eq(font.info.style, c.style, c.name .. ": style") + t:eq(font.info.fullName, c.fullName, c.name .. ": fullName") + t:eq(font.meta.outlines, if c.cff then "cff" else "truetype", c.name .. ": outlines") + if c.weight > 0 then + t:eq(font.meta.os2.weightClass, c.weight, c.name .. ": weight") + end + for _, m in c.cmap do + t:eq(font:glyphIndex(m[1]), m[2], string.format("%s: cmap U+%04X", c.name, m[1])) + end + local maxAreaErr = 0 + for _, g in c.glyphs do + local gid = g.gid + t:eq(font:advance(gid), g.adv, c.name .. ": advance " .. gid) + if not c.cff then + t:eq(font:leftSideBearing(gid), g.lsb, c.name .. ": lsb " .. gid) + end + local cmds = font:outline(gid) + t:check(cmds, c.name .. ": outline " .. gid .. ": " .. tostring(font.meta.lastError)) + local x0, y0, x1, y1 = font:bounds(gid) + if g.box then + t:check(x0 ~= nil, c.name .. ": glyph " .. gid .. " has bounds") + local b = g.box + local ok = math.abs(x0 - b[1]) < 1e-6 and math.abs(y0 - b[2]) < 1e-6 and math.abs(x1 - b[3]) < 1e-6 and math.abs(y1 - b[4]) < 1e-6 + t:check(ok, string.format("%s: glyph %d control box %g %g %g %g, want %g %g %g %g", c.name, gid, x0 or 0, y0, x1, y1, b[1], b[2], b[3], b[4])) + local a = area(cmds) + -- fontTools' AreaPen: positive for counter-clockwise contours, as the shoelace here + local d = math.abs(a - g.area) / math.max(1, math.abs(g.area)) + maxAreaErr = math.max(maxAreaErr, d) + t:check(d < 0.002 or math.abs(a - g.area) < 2, string.format("%s: glyph %d area %.1f, want %.1f", c.name, gid, a, g.area)) + else + t:check(x0 == nil, c.name .. ": empty glyph " .. gid) + end + end + for _, k in c.kern do + t:eq(font:kern(k[1], k[2]), k[3], string.format("%s: kern %d %d", c.name, k[1], k[2])) + end + local worst = 99 + for _, r in c.renders do + local img = font:rasterize(r.gid, r.px) + t:check(img and img.format == "alpha8", c.name .. ": rasterize " .. r.gid) + local p, ink = psnr(img, r) + worst = math.min(worst, p) + sumPsnr += p + nPsnr += 1 + t:check(p > 28 or ink == 0, string.format("%s: glyph %d at %d px: PSNR %.1f dB vs FreeType", c.name, r.gid, r.px, p)) + t:check(math.abs(img.meta.advance - font:advance(r.gid) * r.px / font.unitsPerEm) < 1e-9, "advance in pixels") + end + worstPsnr = math.min(worstPsnr, worst) + t:note("%-20s %4d glyphs, %3d cmap, %3d kern pairs, area err %.5f, worst PSNR %.1f dB", c.name, #c.glyphs, #c.cmap, #c.kern, maxAreaErr, worst) +end +t:note("rasterize vs FreeType: mean PSNR %.1f dB, worst %.1f dB over %d renders", sumPsnr / nPsnr, worstPsnr, nPsnr) + +-- kerning is non-trivial in at least the GPOS and 'kern' fonts +do + local nz = 0 + for _, c in Fx.fonts do + for _, k in c.kern do + if k[3] ~= 0 then + nz += 1 + end + end + end + t:check(nz > 20, "fixtures have non-zero kerning pairs: " .. nz) +end + +-- collections +if Fx.ttc then + local b = buffer.fromstring(Fx.ttc.data) + t:eq(Ttf.count(Bytes.reader(b)), Fx.ttc.count, "collection count") + local f0 = Ttf.decode(Bytes.reader(b)) + t:check(f0 and f0.meta.collection and f0.meta.collection.count == 2, "collection font 0") + local _, e = Ttf.decode(Bytes.reader(b), { index = 5 }) + t:check(e and e.code == Err.ARG, "collection index out of range") + local f1 = F.load(b, { index = 1 }) + t:check(f1 and f1.info.family == fonts["collection-1"].info.family, "F.load with opts.index") +end + +-- the api: detection by content, the font facade +do + local c = Fx.fonts[1] + t:eq(F.detect(c.data), "ttf", "F.detect") + local f = F.font.load(c.data) + t:check(f and f.kind == "font" and f.meta.source.format == "ttf", "F.font.load") + local g = f:glyphIndex(65) + t:check(g > 0 and f:advance(g) > 0, "glyph A") + t:eq(f:glyphIndex(-1), 0, "negative code point") + t:eq(f:glyphIndex(0.5), 0, "fractional code point") + t:check(f:outline(-1) == nil and f:outline(1e9) == nil and f:rasterize(g, -3) == nil, "bad glyph / size") + local sp = f:rasterize(f:glyphIndex(32), 20) + t:check(sp and sp.width == 0, "space rasterizes to an empty image") + local _, e = F.save(f, nil, { format = "ttf" }) + t:check(e and e.code == Err.UNSUPPORTED, "ttf is read-only") +end + +-- errors +do + local _, e1 = Ttf.decode(Bytes.reader(buffer.fromstring("OTTO"))) + t:check(e1 and e1.code == Err.TRUNCATED, "short file: " .. tostring(e1)) + local _, e2 = Ttf.decode(Bytes.reader(buffer.fromstring("\0\1\0\0\0\0\0\0\0\0\0\0"))) + t:check(e2 and e2.code == Err.CORRUPT, "no tables: " .. tostring(e2)) + t:eq(Ttf.sniff(Bytes.reader(buffer.fromstring("wOFF"))), 0, "sniff rejects woff") +end + +-- fuzz: whole-font mutations, then glyph access on whatever still parses +do + local samples = {} + for _, c in Fx.fonts do + if #c.data < 60000 then + table.insert(samples, c.data) + end + end + local rand = T.rng(99) + t:fuzz("decode + glyphs", function(b: buffer) + local f = Ttf.decode(Bytes.reader(b)) + if f then + for _ = 1, 12 do + local g = rand(f.numGlyphs + 2) + f:outline(g) + f:advance(g) + f:kern(g, rand(f.numGlyphs + 1)) + f:glyphIndex(rand(70000)) + f:rasterize(g, 9) + end + end + return f + end, samples, { mutations = 30, garbage = 200 }) + -- mutations inside the glyph data only (the header survives, so the outline parsers see the damage) + local hits = 0 + local cff = Fx.fonts[#Fx.fonts - 2] -- (any font: the loop below picks the CFF one) + for _, c in Fx.fonts do + if c.cff then + cff = c + end + end + local tries = 0 + for _, c in { Fx.fonts[1], cff } do + local base = buffer.fromstring(c.data) + local n = buffer.len(base) + for _ = 1, 40 do + local b = buffer.create(n) + buffer.copy(b, 0, base) + for _ = 1, 20 do + local p = n // 4 + rand(n - n // 4) + buffer.writeu8(b, p, rand(256)) + end + tries += 1 + local ok = pcall(function() + local f = Ttf.decode(Bytes.reader(b)) + if f then + for g = 0, math.min(f.numGlyphs, 300) - 1 do + f:outline(g) + f:rasterize(g, 8) + end + hits += 1 + end + end) + t:check(ok, c.name .. ": glyph-data mutation threw") + end + end + t:note("glyph-data mutations: %d fonts (%d parsed), every glyph outlined + rasterized, none threw", tries, hits) +end + +t:done() diff --git a/tests/font/woff.luau b/tests/font/woff.luau new file mode 100644 index 0000000..218a1cc --- /dev/null +++ b/tests/font/woff.luau @@ -0,0 +1,100 @@ +-- font/woff tests: every fixture font as WOFF 1.0 (fontTools, zlib tables) decodes to the same font as the sfnt itself (font/ttf, checked against +-- fontTools / FreeType in tests/font/ttf.luau): metrics, names, every glyph's outline, advance and side bearing, +-- cmap and kerning samples; rasterize works; the api detects it; errors; the fuzz pass. Fixtures: tools/fixtures/fonts.py. +local T = require("@tests/T") +local F = require("@formats") +local Woff = require("@formats/font/woff") +local Ttf = require("@formats/font/ttf") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/fonts") + +local t = T.suite("woff") +t:eq(Woff.name, "woff", "name") + +local function same(a: any, b: any, label: string) + for _, k in { "unitsPerEm", "ascent", "descent", "lineGap", "numGlyphs" } do + t:eq(a[k], b[k], label .. ": " .. k) + end + t:eq(a.info.family, b.info.family, label .. ": family") + t:eq(a.info.fullName, b.info.fullName, label .. ": fullName") + for g = 0, a.numGlyphs - 1 do + t:eq(a:advance(g), b:advance(g), label .. ": advance " .. g) + t:eq(a:leftSideBearing(g), b:leftSideBearing(g), label .. ": lsb " .. g) + local oa, ob = a:outline(g), b:outline(g) + t:check(oa and ob and #oa == #ob, label .. ": outline " .. g .. " command count") + for i, c in oa do + local d = ob[i] + local ok = c.op == d.op and #c == #d + for j = 1, #c do + ok = ok and c[j] == d[j] + end + if not ok then + t:check(false, string.format("%s: glyph %d command %d differs", label, g, i)) + end + end + end + for cp = 0, 0x2FF do + t:eq(a:glyphIndex(cp), b:glyphIndex(cp), label .. ": cmap " .. cp) + end + local ga, gv = a:glyphIndex(65), a:glyphIndex(86) + t:eq(a:kern(ga, gv), b:kern(ga, gv), label .. ": kern A V") +end + +local refs: { [string]: string } = {} +for _, c in Fx.fonts do + refs[c.name] = c.data +end +local samples = {} +local n = 0 +for _, w in Fx.woff do + for _, key in { "woff" } do + local data = w[key] + local font, err = Woff.decode(Bytes.reader(buffer.fromstring(data))) + t:check(font, w.name .. " (" .. key .. "): " .. tostring(err)) + t:eq(font.meta.source.format, "woff", "source format") + local ref = assert(Ttf.decode(Bytes.reader(buffer.fromstring(refs[w.name])))) + same(font, ref, w.name .. " (" .. key .. ")") + local img = font:rasterize(font:glyphIndex(65), 24) + t:check(img and img.width > 0, w.name .. ": rasterize") + n += 1 + if #data < 40000 then + table.insert(samples, data) + end + t:note("%-20s %-7s %7d bytes (sfnt %d), %d glyphs identical", w.name, key, #data, #refs[w.name], font.numGlyphs) + end +end +t:check(n >= 6, "fixture count") + +-- the api +do + local data = Fx.woff[1].woff + t:eq(F.detect(data), "woff", "F.detect") + local f = F.font.load(data) + t:check(f and f.kind == "font", "F.font.load") + t:eq(Woff.sniff(Bytes.reader(buffer.fromstring("wOFF"))) + Woff.sniff(Bytes.reader(buffer.fromstring("wOF2"))), 1, "sniff") +end + +-- errors +do + local data = Fx.woff[1].woff + local _, e1 = Woff.decode(Bytes.reader(buffer.fromstring(string.sub(data, 1, 30)))) + t:check(e1 and e1.code == Err.TRUNCATED, "truncated header: " .. tostring(e1)) + local _, e2 = Woff.decode(Bytes.reader(buffer.fromstring(string.sub(data, 1, #data - 100)))) + t:check(e2 ~= nil, "truncated data: " .. tostring(e2)) + local _, e3 = Woff.decode(Bytes.reader(buffer.fromstring("ttcf" .. string.rep("\0", 60)))) + t:check(e3 and e3.code == Err.CORRUPT, "bad signature: " .. tostring(e3)) +end + +t:fuzz("decode", function(b: buffer) + local f = Woff.decode(Bytes.reader(b)) + if f then + for g = 0, math.min(f.numGlyphs, 40) - 1 do + f:outline(g) + f:rasterize(g, 8) + end + end + return f +end, samples, { mutations = 25, garbage = 200 }) + +t:done() diff --git a/tests/font/woff2.luau b/tests/font/woff2.luau new file mode 100644 index 0000000..ca7af20 --- /dev/null +++ b/tests/font/woff2.luau @@ -0,0 +1,100 @@ +-- font/woff2 tests: every fixture font as WOFF2 (fontTools: the default glyf / loca transform, and with the hmtx transform too) decodes to the same font as the sfnt itself (font/ttf, checked against +-- fontTools / FreeType in tests/font/ttf.luau): metrics, names, every glyph's outline, advance and side bearing, +-- cmap and kerning samples; rasterize works; the api detects it; errors; the fuzz pass. Fixtures: tools/fixtures/fonts.py. +local T = require("@tests/T") +local F = require("@formats") +local Woff2 = require("@formats/font/woff2") +local Ttf = require("@formats/font/ttf") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/fonts") + +local t = T.suite("woff2") +t:eq(Woff2.name, "woff2", "name") + +local function same(a: any, b: any, label: string) + for _, k in { "unitsPerEm", "ascent", "descent", "lineGap", "numGlyphs" } do + t:eq(a[k], b[k], label .. ": " .. k) + end + t:eq(a.info.family, b.info.family, label .. ": family") + t:eq(a.info.fullName, b.info.fullName, label .. ": fullName") + for g = 0, a.numGlyphs - 1 do + t:eq(a:advance(g), b:advance(g), label .. ": advance " .. g) + t:eq(a:leftSideBearing(g), b:leftSideBearing(g), label .. ": lsb " .. g) + local oa, ob = a:outline(g), b:outline(g) + t:check(oa and ob and #oa == #ob, label .. ": outline " .. g .. " command count") + for i, c in oa do + local d = ob[i] + local ok = c.op == d.op and #c == #d + for j = 1, #c do + ok = ok and c[j] == d[j] + end + if not ok then + t:check(false, string.format("%s: glyph %d command %d differs", label, g, i)) + end + end + end + for cp = 0, 0x2FF do + t:eq(a:glyphIndex(cp), b:glyphIndex(cp), label .. ": cmap " .. cp) + end + local ga, gv = a:glyphIndex(65), a:glyphIndex(86) + t:eq(a:kern(ga, gv), b:kern(ga, gv), label .. ": kern A V") +end + +local refs: { [string]: string } = {} +for _, c in Fx.fonts do + refs[c.name] = c.data +end +local samples = {} +local n = 0 +for _, w in Fx.woff do + for _, key in { "woff2", "woff2h" } do + local data = w[key] + local font, err = Woff2.decode(Bytes.reader(buffer.fromstring(data))) + t:check(font, w.name .. " (" .. key .. "): " .. tostring(err)) + t:eq(font.meta.source.format, "woff2", "source format") + local ref = assert(Ttf.decode(Bytes.reader(buffer.fromstring(refs[w.name])))) + same(font, ref, w.name .. " (" .. key .. ")") + local img = font:rasterize(font:glyphIndex(65), 24) + t:check(img and img.width > 0, w.name .. ": rasterize") + n += 1 + if #data < 40000 then + table.insert(samples, data) + end + t:note("%-20s %-7s %7d bytes (sfnt %d), %d glyphs identical", w.name, key, #data, #refs[w.name], font.numGlyphs) + end +end +t:check(n >= 6, "fixture count") + +-- the api +do + local data = Fx.woff[1].woff2 + t:eq(F.detect(data), "woff2", "F.detect") + local f = F.font.load(data) + t:check(f and f.kind == "font", "F.font.load") + t:eq(Woff2.sniff(Bytes.reader(buffer.fromstring("wOFF"))) + Woff2.sniff(Bytes.reader(buffer.fromstring("wOF2"))), 1, "sniff") +end + +-- errors +do + local data = Fx.woff[1].woff2 + local _, e1 = Woff2.decode(Bytes.reader(buffer.fromstring(string.sub(data, 1, 30)))) + t:check(e1 and e1.code == Err.TRUNCATED, "truncated header: " .. tostring(e1)) + local _, e2 = Woff2.decode(Bytes.reader(buffer.fromstring(string.sub(data, 1, #data - 100)))) + t:check(e2 ~= nil, "truncated data: " .. tostring(e2)) + local _, e3 = Woff2.decode(Bytes.reader(buffer.fromstring("ttcf" .. string.rep("\0", 60)))) + t:check(e3 and e3.code == Err.CORRUPT, "bad signature: " .. tostring(e3)) +end + +t:fuzz("decode", function(b: buffer) + local f = Woff2.decode(Bytes.reader(b)) + if f then + for g = 0, math.min(f.numGlyphs, 40) - 1 do + f:outline(g) + f:rasterize(g, 8) + end + end + return f +end, samples, { mutations = 25, garbage = 200 }) + +t:done() diff --git a/tests/image/gif.luau b/tests/image/gif.luau new file mode 100644 index 0000000..a2ccae8 --- /dev/null +++ b/tests/image/gif.luau @@ -0,0 +1,221 @@ +-- image/gif tests: GIFs from ImageMagick and Pillow (static, interlaced, 2..256 colours, grey, transparency, +-- animations with every disposal, sub-rectangles, local colour tables, loop counts, comments) against ImageMagick's +-- decode of every frame; the encoder (lossless round trips at <= 256 colours, quantized PSNR above, animations with +-- frames / delays / disposal / transparency / loops, options); error codes; the fuzz no-throw pass. +-- Fixtures: tools/fixtures/gif.py. +local T = require("@tests/T") +local Gif = require("@formats/image/gif") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Fx = require("@tests/gen/gif") + +local t = T.suite("gif") + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return Gif.decode(Bytes.reader(b), opts) +end + +-- rgba8 with alpha-0 pixels zeroed (the fixtures' convention) +local function norm(px: buffer): buffer + local n = buffer.len(px) + local c = buffer.create(n) + buffer.copy(c, 0, px) + for o = 0, n - 4, 4 do + if buffer.readu8(c, o + 3) == 0 then + buffer.writeu32(c, o, 0) + end + end + return c +end + +-- the contract +t:eq(Gif.name, "gif", "name") +t:eq(Gif.category, "image", "category") +t:check(Gif.caps.decode and Gif.caps.encode and Gif.caps.animation, "caps") + +-- every fixture against ImageMagick +local nframes = 0 +for _, c in Fx do + local img, err = decode(c.data) + t:check(img, c.name .. ": " .. tostring(err)) + t:check(img.width == c.width and img.height == c.height and img.format == "rgba8", c.name .. ": canvas") + t:check(not img.meta.truncated, c.name .. ": flagged truncated") + t:eq(Crc32.of(norm(img.pixels)), c.first, c.name .. ": first frame composited") + local frames = img.frames or { { image = img, x = 0, y = 0, delay = 0, dispose = "none" } } + t:eq(#frames, #c.frames, c.name .. ": frame count") + for i, rf in c.frames do + local f = frames[i] + local label = c.name .. " frame " .. i + if img.frames then + t:check(f.image.width == rf.w and f.image.height == rf.h and f.x == rf.x and f.y == rf.y, label .. ": rectangle") + t:eq(math.floor(f.delay * 100 + 0.5), rf.delay, label .. ": delay") + local want = if rf.dispose == "undefined" then "none" else rf.dispose + t:eq(f.dispose, want, label .. ": dispose") + t:eq(Crc32.of(norm(f.image.pixels)), rf.crc, label .. ": pixels") + else + t:eq(Crc32.of(norm(img.pixels)), rf.crc, label .. ": pixels") + end + nframes += 1 + end + if c.loops then + t:eq(img.loops, if c.loops == 0 then 0 else c.loops + 1, c.name .. ": loops (plays)") + end + if c.comment then + t:eq(img.meta.text and img.meta.text.comment, c.comment, c.name .. ": comment") + end +end +t:note("%d files, %d frames match ImageMagick", #Fx, nframes) + +-- sniff, meta, limits, errors +do + local c = Fx[1] + t:eq(Gif.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, "sniff a GIF") + t:eq(Gif.sniff(Bytes.reader(buffer.fromstring("\137PNG\r\n\26\n"))), 0, "sniff a PNG") + t:eq(Gif.sniff(Bytes.reader(buffer.create(0))), 0, "sniff nothing") + local img = decode(c.data) + t:check(img.meta.source.format == "gif" and img.meta.source.version == "89a", "meta.source") + t:check(img.meta.palette and #img.meta.palette >= 2 and #img.meta.palette[1] == 4, "meta.palette") + local _, e = decode(c.data, { maxPixels = 100 }) + t:check(e and e.code == Err.LIMIT, "maxPixels: " .. tostring(e)) + local _, e2 = decode("GIF89a") + t:check(e2 and e2.code == Err.TRUNCATED, "header only: " .. tostring(e2)) + local _, e3 = decode("NOTGIF1234567") + t:check(e3 and e3.code == Err.CORRUPT, "junk: " .. tostring(e3)) + -- a truncated file keeps its frames + for _, f in Fx do + if f.name == "anim_none" then + local cut = string.sub(f.data, 1, #f.data - 20) + local part = decode(cut) + t:check(part and part.meta.truncated, "truncated animation decodes partially") + local one = decode(f.data, { maxFrames = 1 }) + t:check(one and one.frames == nil, "maxFrames = 1") + local big = buffer.create(#f.data + 9) + buffer.writestring(big, 5, f.data) + local sub = Gif.decode(Bytes.reader(big, 5, #f.data)) + t:check(sub and sub.frames and #sub.frames == 4, "decode from a sub-range") + end + end +end + +-- the encoder +local rand = T.rng(17) +local function image(w: number, h: number, colors: number?, alpha: boolean?): Types.Image + local img = Types.Image.new(w, h) + for i = 0, w * h - 1 do + local x, y = i % w, i // w + local r, g, b + if colors then + local k = (x // 3 + y // 2 * 7 + rand(2)) % colors + r, g, b = (k * 53) % 256, (k * 97) % 256, (k * 31) % 256 + else + r, g, b = (x * 255) // math.max(1, w - 1), (y * 255) // math.max(1, h - 1), ((x + y) * 3 + rand(16)) % 256 + end + local a = if alpha and (x * x + y * y) % 11 == 0 then 0 else 255 + buffer.writeu32(img.pixels, i * 4, r + g * 256 + b * 65536 + a * 16777216) + end + return img +end +local function same(a: buffer, b: buffer): boolean + return buffer.tostring(norm(a)) == buffer.tostring(norm(b)) +end +local function psnr(a: buffer, b: buffer): number + local se, n = 0, 0 + for o = 0, buffer.len(a) - 4, 4 do + for k = 0, 2 do + local d = buffer.readu8(a, o + k) - buffer.readu8(b, o + k) + se += d * d + n += 1 + end + end + if se == 0 then + return 99 + end + return 10 * math.log10(255 * 255 * n / se) +end +do + for _, colors in { 2, 3, 16, 200, 256 } do + for _, alpha in { false, true } do + local ncol = if alpha and colors == 256 then 255 else colors + local img = image(37, 23, ncol, alpha) + local gif, err = Gif.encode(img) + t:check(gif, "encode: " .. tostring(err)) + local back = decode(gif) + t:check(back and same(back.pixels, img.pixels), string.format("%d colours alpha=%s: lossless round trip", ncol, tostring(alpha))) + t:check(back.frames == nil, "single image") + end + end + -- more than 256 colours: quantized, every method, with and without dithering + local photo = image(96, 64) + for _, method in { "mediancut", "octree" } do + for _, dither in { false, true } do + local gif = Gif.encode(photo, { method = method, dither = dither }) :: buffer + local back = decode(gif) + local p = psnr(back.pixels, photo.pixels) + t:check(p > (if dither then 28 else 30), string.format("%s dither=%s: PSNR %.1f", method, tostring(dither), p)) + t:note("encode %s dither=%s: %d bytes, PSNR %.1f dB", method, tostring(dither), buffer.len(gif), p) + end + end + local small = Gif.encode(photo, { maxColors = 4 }) :: buffer + local sb = decode(small) + t:check(sb.meta.palette and #sb.meta.palette <= 4, "maxColors = 4") + -- animation: frames, delays, disposal, transparency, loops, comment, local / global palettes + local anim = image(40, 30, 50) + anim.frames = { + { image = image(40, 30, 50), x = 0, y = 0, delay = 0.1, dispose = "none", blend = "source" }, + { image = image(10, 12, 7, true), x = 5, y = 6, delay = 0.25, dispose = "background", blend = "over" }, + { image = image(20, 5), x = 20, y = 25, delay = 1.5, dispose = "previous", blend = "source" }, + } + anim.loops = 4 + anim.meta.text = { comment = "hello gif" } + for _, global in { false, true } do + local gif, err = Gif.encode(anim, { globalPalette = global }) + t:check(gif, "animation encode: " .. tostring(err)) + local back = decode(gif) + t:check(back.frames and #back.frames == 3, "animation frames") + t:eq(back.loops, 4, "loops") + t:eq(back.meta.text.comment, "hello gif", "comment") + for i, f in anim.frames :: { Types.Frame } do + local g = back.frames[i] + t:check(g.x == f.x and g.y == f.y and g.image.width == f.image.width and g.image.height == f.image.height, "frame rectangle " .. i) + t:eq(g.delay, f.delay, "frame delay " .. i) + t:eq(g.dispose, f.dispose, "frame dispose " .. i) + end + t:check(same(back.frames[1].image.pixels, anim.frames[1].image.pixels), "frame 1 lossless") + t:check(same(back.frames[2].image.pixels, anim.frames[2].image.pixels), "frame 2 lossless (transparency)") + t:eq(back.frames[2].blend, "over", "frame 2 blend") + t:check(psnr(back.frames[3].image.pixels, anim.frames[3].image.pixels) > 25, "frame 3 quantized") + t:eq(back.meta.source.localPalettes, if global then 0 else 3, "palettes") + end + -- deterministic output + t:eq(Crc32.of(Gif.encode(photo, { dither = true }) :: buffer), Crc32.of(Gif.encode(photo, { dither = true }) :: buffer), "deterministic") + -- bad arguments + local _, e = Gif.encode({} :: any) + t:check(e and e.code == Err.ARG, "encode of a non-image") + local _, e2 = Gif.encode(photo, { maxColors = 1 }) + t:check(e2 and e2.code == Err.ARG, "maxColors = 1") + local _, e3 = Gif.encode(photo, { method = "kmeans" } :: any) + t:check(e3 and e3.code == Err.ARG, "unknown method") + local _, e4 = Gif.encode(Types.Image.new(70000, 1)) + t:check(e4 and e4.code == Err.ARG, "too wide") +end + +-- fuzz +do + local samples = {} + for _, c in Fx do + if #c.data < 40000 then + table.insert(samples, c.data) + end + end + t:fuzz("decode", function(b: buffer) + return Gif.decode(Bytes.reader(b)) + end, samples, { mutations = 12, keepHeader = 6 }) + t:fuzz("decode (header too)", function(b: buffer) + return Gif.decode(Bytes.reader(b), { maxPixels = 1e6 }) + end, samples, { mutations = 4, garbage = 50 }) +end + +t:done() diff --git a/tests/image/hdr.luau b/tests/image/hdr.luau new file mode 100644 index 0000000..b923ef2 --- /dev/null +++ b/tests/image/hdr.luau @@ -0,0 +1,117 @@ +-- image/hdr tests: ImageMagick-written Radiance files (new-style RLE) against its float decodes, hand-written ones +-- (flat and old-style RLE scanlines, "#?RGBE", EXPOSURE products, all orientations) against the rgbe.c rule; the +-- display conversion to rgba8; our encoder round-trips (RLE and flat, rgbaf32 and rgba8) within RGBE precision; +-- errors; the fuzz no-throw pass. Fixtures: tools/fixtures/hdr.py. +local T = require("@tests/T") +local Hdr = require("@formats/image/hdr") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Fx = require("@tests/gen/hdr") + +local t = T.suite("hdr") + +t:eq(Hdr.name, "hdr", "name") +t:check(Hdr.caps.decode and Hdr.caps.encode, "caps") + +local function dec(data: any, opts: any?): (any, any) + return Hdr.decode(Bytes.reader(if type(data) == "string" then buffer.fromstring(data) else data), opts) +end + +-- worst relative error between two rgbaf32 buffers +local function relErr(a: buffer, b: buffer, n: number): number + local worst = 0 + for i = 0, n * 4 - 1 do + local x, y = buffer.readf32(a, i * 4), buffer.readf32(b, i * 4) + local d = math.abs(x - y) / math.max(math.abs(y), 1e-30) + if math.abs(x - y) > 1e-30 then + worst = math.max(worst, d) + end + end + return worst +end + +for _, c in Fx do + local img, err = dec(c.data, { native = true }) + t:check(img, c.name .. ": " .. tostring(err)) + t:check(img.width == c.width and img.height == c.height and img.format == "rgbaf32", c.name .. ": size") + local e = relErr(img.pixels, buffer.fromstring(c.floats), c.width * c.height) + t:check(e < 1e-6, string.format("%s: relative error %g against the reference", c.name, e)) + if c.exposure then + t:check(math.abs(img.meta.exposure - c.exposure) < 1e-9, c.name .. ": exposure") + end + -- the default rgba8 display conversion + local d8 = dec(c.data) + t:eq(d8.format, "rgba8", c.name .. ": rgba8 by default") + local v = buffer.readf32(img.pixels, 0) + t:eq(buffer.readu8(d8.pixels, 0), math.floor(math.clamp(v, 0, 1) ^ (1 / 2.2) * 255 + 0.5), c.name .. ": display curve") + -- round trips: RGBE is lossless for values already on its grid + for _, rle in { true, false } do + local enc = Hdr.encode(img, { rle = rle }) :: buffer + local back = dec(enc, { native = true }) + local re = relErr(back.pixels, img.pixels, c.width * c.height) + t:check(re < 1e-6, string.format("%s: round trip rle=%s relative error %g", c.name, tostring(rle), re)) + end +end +t:note("%d files match their references and round-trip", #Fx) + +do + -- arbitrary floats: RGBE keeps about 1% relative precision on the largest channel + local rand = T.rng(8) + local img = Types.Image.new(40, 10, "rgbaf32") + for i = 0, 399 do + for c = 0, 2 do + buffer.writef32(img.pixels, i * 16 + c * 4, rand(100000) / 1000) + end + buffer.writef32(img.pixels, i * 16 + 12, 1) + end + local back = dec(Hdr.encode(img) :: buffer, { native = true }) + local worst = 0 + for i = 0, 399 do + local m = 0 + for c = 0, 2 do + m = math.max(m, buffer.readf32(img.pixels, i * 16 + c * 4)) + end + for c = 0, 2 do + worst = math.max(worst, math.abs(buffer.readf32(back.pixels, i * 16 + c * 4) - buffer.readf32(img.pixels, i * 16 + c * 4)) / math.max(m, 1e-9)) + end + end + t:check(worst < 1 / 128, "float precision " .. worst) + -- rgba8 in, rgba8 out + local i8 = Types.Image.new(9, 2) + for i = 0, 17 do + buffer.writeu32(i8.pixels, i * 4, 0xFF000000 + (i * 14) * 0x10101) + end + local b8 = dec(Hdr.encode(i8) :: buffer) + local w8 = 0 + for i = 0, 71 do + w8 = math.max(w8, math.abs(buffer.readu8(b8.pixels, i) - buffer.readu8(i8.pixels, i))) + end + t:check(w8 <= 2, "rgba8 round trip within 2: " .. w8) + local ex = dec(Hdr.encode(img, { exposure = 0.5 }) :: buffer) + t:eq(ex.meta.exposure, 0.5, "exposure written") + t:eq(Hdr.sniff(Bytes.reader(buffer.fromstring("#?RADIANCE\n"))), 1, "sniff") + t:eq(Hdr.sniff(Bytes.reader(buffer.fromstring("P6\n"))), 0, "sniff other") + local _, e1 = dec("#?RADIANCE\nFORMAT=32-bit_rle_xyze\n\n-Y 1 +X 1\n\0\0\0\0") + t:check(e1 and e1.code == Err.UNSUPPORTED, "xyze unsupported") + local _, e2 = dec("#?RADIANCE\n\n-Y 10 +X 10\n", { maxPixels = 50 }) + t:check(e2 and e2.code == Err.LIMIT, "maxPixels") + local _, e3 = dec("#?RADIANCE\n\nnonsense\n") + t:check(e3 and e3.code == Err.CORRUPT, "bad resolution") + local tr = dec(string.sub(Fx[1].data, 1, #Fx[1].data // 2)) + t:check(tr and tr.meta.truncated, "truncated data flagged") + local _, e4 = Hdr.encode(Types.Image.new(1, 1, "gray8")) + t:check(e4 and e4.code == Err.ARG, "gray8 refused") +end + +do + local samples = {} + for _, c in Fx do + table.insert(samples, c.data) + end + t:fuzz("decode", function(b: buffer) + return Hdr.decode(Bytes.reader(b)) + end, samples) +end + +t:done() diff --git a/tests/image/ico.luau b/tests/image/ico.luau new file mode 100644 index 0000000..00397f4 --- /dev/null +++ b/tests/image/ico.luau @@ -0,0 +1,123 @@ +-- image/ico tests: ImageMagick- and Pillow-written icons (PNG and BMP entries, a 256 PNG entry) and hand-built ones +-- (1 / 4 / 8 / 24 / 32-bit DIBs with AND masks, a cursor with hotspots) against Pillow's decode of every entry; PNG +-- entries through opts.decodeImage (and UNSUPPORTED without it); the main image is the largest entry; our encoder +-- (DIB, PNG through opts.encodeImage, cursors) round-trips; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/ico.py. +local T = require("@tests/T") +local Ico = require("@formats/image/ico") +local Png = require("@formats/image/png") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Fx = require("@tests/gen/ico") + +local t = T.suite("ico") + +t:eq(Ico.name, "ico", "name") +t:check(Ico.caps.decode and Ico.caps.encode, "caps") + +local hooks = { + decodeImage = function(b: buffer) + return Png.decode(Bytes.reader(b)) + end, + encodeImage = function(img: any, _fmt: string) + return Png.encode(img) + end, +} + +local function dec(data: any, opts: any?): (any, any) + return Ico.decode(Bytes.reader(if type(data) == "string" then buffer.fromstring(data) else data), opts) +end + +local entries = 0 +for _, c in Fx do + local img, err = dec(c.data, hooks) + t:check(img, c.name .. ": " .. tostring(err)) + local frames = img.frames or { { image = img } } + t:eq(#frames, #c.entries, c.name .. ": entry count") + local biggest = 0 + for i, e in c.entries do + local f = frames[i].image + t:check(f.width == e.width and f.height == e.height, string.format("%s entry %d: size %dx%d, want %dx%d", c.name, i, f.width, f.height, e.width, e.height)) + local worst = 0 + for k = 0, #e.rgba - 1 do + worst = math.max(worst, math.abs(buffer.readu8(f.pixels, k) - string.byte(e.rgba, k + 1))) + end + t:check(worst == 0, string.format("%s entry %d: differs from Pillow by %d", c.name, i, worst)) + biggest = math.max(biggest, e.width * e.height) + entries += 1 + end + t:eq(img.width * img.height, biggest, c.name .. ": the main image is the largest entry") + -- round trip through our encoder (DIB entries, and PNG for 256 through the hook) + local enc, eerr = Ico.encode(img, hooks) + t:check(enc, c.name .. ": encode: " .. tostring(eerr)) + local back = dec(enc, hooks) + local bf = back.frames or { { image = back } } + t:eq(#bf, #frames, c.name .. ": round trip entries") + for i, f in frames do + local a, b = f.image, bf[i].image + local same = a.width == b.width and a.height == b.height + if same then + -- alpha-0 pixels keep their colour in 32-bit DIBs too + same = buffer.tostring(a.pixels) == buffer.tostring(b.pixels) + end + t:check(same, string.format("%s: round trip entry %d", c.name, i)) + end +end +t:note("%d icons, %d entries match Pillow and round-trip", #Fx, entries) + +do + local byName = {} + for _, c in Fx do + byName[c.name] = c + end + -- without the hook: PNG entries are skipped, BMP entries still decode + local big, sm = Types.Image.new(256, 256), Types.Image.new(16, 16) + buffer.fill(big.pixels, 0, 77, 256 * 256 * 4) + buffer.fill(sm.pixels, 0, 99, 16 * 16 * 4) + local two = Types.Image.new(256, 256) + two.frames = { { image = big, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" }, { image = sm, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" } } + local mixed = Ico.encode(two, hooks) :: buffer + t:eq(buffer.readstring(mixed, 6 + 32, 4), "\137PNG", "the 256 entry is written as PNG through the hook") + local im = dec(mixed) + t:check(im and im.width == 16 and im.meta.source.skipped == 1, "no hook: the PNG entry is skipped") + t:eq(dec(mixed, hooks).width, 256, "with the hook: the PNG entry is the main image") + local _, e = dec(byName["pil-png"].data) + t:check(e and e.code == Err.UNSUPPORTED, "PNG-only icon without the hook: " .. tostring(e)) + local cur = dec(byName["hand-cur"].data) + t:check(cur.meta.source.type == "cur" and cur.meta.hotspot and cur.meta.hotspot.x == 3 and cur.meta.hotspot.y == 4, "cursor hotspot") + t:eq(cur.frames[2].image.meta.hotspot.x, 5, "second hotspot") + local cenc = Ico.encode(cur) :: buffer + t:eq(buffer.readu16(cenc, 2), 2, "cursor written as CUR") + local cb = dec(cenc) + t:check(cb.meta.hotspot.x == 3 and cb.frames[2].image.meta.hotspot.y == 6, "hotspots round-trip") + -- PNG entries on request + local small = Types.Image.new(16, 16) + buffer.fill(small.pixels, 0, 200, 16 * 16 * 4) + local pe = Ico.encode(small, { png = true, encodeImage = hooks.encodeImage }) :: buffer + t:eq(buffer.readstring(pe, 22, 4), "\137PNG", "opts.png writes a PNG entry") + local _, e2 = Ico.encode(small, { png = true }) + t:check(e2 and e2.code == Err.ARG, "opts.png without a hook") + local _, e3 = Ico.encode(Types.Image.new(300, 10)) + t:check(e3 and e3.code == Err.ARG, "over 256 pixels") + t:eq(Ico.sniff(Bytes.reader(buffer.fromstring(byName["pil-bmp"].data))), 0.8, "sniff") + t:eq(Ico.sniff(Bytes.reader(buffer.fromstring(string.rep("\0", 30)))), 0, "sniff zeros") + local _, e4 = dec(string.sub(byName["pil-bmp"].data, 1, 20)) + t:check(e4 and e4.code == Err.TRUNCATED, "truncated directory") +end + +do + local samples = {} + for _, c in Fx do + if #c.data < 40000 then + table.insert(samples, c.data) + end + end + t:fuzz("decode", function(b: buffer) + return Ico.decode(Bytes.reader(b), hooks) + end, samples) + t:fuzz("decode without hooks", function(b: buffer) + return Ico.decode(Bytes.reader(b)) + end, samples, { mutations = 3, garbage = 50 }) +end + +t:done() diff --git a/tests/image/jpeg.luau b/tests/image/jpeg.luau new file mode 100644 index 0000000..c0af085 --- /dev/null +++ b/tests/image/jpeg.luau @@ -0,0 +1,300 @@ +-- image/jpeg tests: every cjpeg / jpegtran fixture (baseline, progressive, arithmetic, every sampling, restarts, grey, +-- RGB, 12-bit, odd sizes, stripped DHT) against djpeg's decodes at scales 1, 1/2, 1/4, 1/8 (bit-exact, CRC-32); +-- CMYK / YCCK against Pillow; refused files; info / meta (EXIF orientation applied, ICC, comment, density); the +-- encoder byte-identical to cjpeg for the same settings, its PSNR, round trips through our decoder; truncated files; +-- the fuzz no-throw pass. Ported from jpeg-luau tests/jpeg.luau. Fixtures: tools/fixtures/jpeg.py. +local T = require("@tests/T") +local Jpeg = require("@formats/image/jpeg") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Dec = require("@tests/gen/jpeg_dec") +local Enc = require("@tests/gen/jpeg_enc") + +local t = T.suite("jpeg") + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return Jpeg.decode(Bytes.reader(b), opts) +end + +-- the contract +t:eq(Jpeg.name, "jpeg", "name") +t:eq(Jpeg.category, "image", "category") +t:check(Jpeg.caps.decode and Jpeg.caps.encode, "caps") + +-- decodes against djpeg / Pillow +local files: { [string]: string } = {} +do + local refs, arith = 0, 0 + for _, c in Dec do + files[c.name] = c.data + if c.err then + local img, err = decode(c.data) + t:check(img == nil and err and err.code == Err.UNSUPPORTED and string.find(err.message, c.err, 1, true), c.name .. ": expected UNSUPPORTED " .. c.err .. ", got " .. tostring(err)) + elseif c.cmyk then + local img, err = decode(c.data) + t:check(img, c.name .. ": " .. tostring(err)) + local n = #c.cmyk // 3 + t:eq(img.width * img.height, n, c.name .. ": size") + local worst = 0 + for i = 0, n - 1 do + for k = 0, 2 do + worst = math.max(worst, math.abs(buffer.readu8(img.pixels, i * 4 + k) - string.byte(c.cmyk, i * 3 + k + 1))) + end + end + t:check(worst <= 1, c.name .. ": max error " .. worst .. " against Pillow") + refs += 1 + else + for _, r in c.refs do + local name = c.name .. " 1/" .. r.scale + local img, err = decode(c.data, { scale = r.scale }) + t:check(img, name .. ": " .. tostring(err)) + t:check(img.width == r.width and img.height == r.height, string.format("%s: size %dx%d, djpeg %dx%d", name, img.width, img.height, r.width, r.height)) + t:check(not img.meta.truncated, name .. ": flagged truncated") + local crc = Crc32.of(img.pixels) + t:check(crc == r.crc, string.format("%s: pixels crc %08x, djpeg %08x", name, crc, r.crc)) + refs += 1 + if img.meta.source.arithmetic then + arith += 1 + end + end + end + end + t:note("%d files, %d decodes bit-exact with djpeg / Pillow (%d arithmetic-coded)", #Dec, refs, arith) +end + +local function file(name: string): buffer + return buffer.fromstring(files[name]) +end + +-- sniff, info, meta, options +do + t:eq(Jpeg.sniff(Bytes.reader(file("photo_q90_420"))), 1, "sniff a JPEG") + t:eq(Jpeg.sniff(Bytes.reader(buffer.fromstring("GIF89a"))), 0, "sniff a GIF") + t:eq(Jpeg.sniff(Bytes.reader(buffer.create(0))), 0, "sniff nothing") + local i = Jpeg.info(Bytes.reader(file("photo_q90_420_prog"))) + t:check(i and i.width == 160 and i.height == 120 and i.progressive and i.components == 3, "info: progressive 4:2:0") + t:check(i.sampling[1][1] == 2 and i.sampling[1][2] == 2 and i.sampling[2][1] == 1, "info: sampling") + t:check(i.colorSpace == "ycbcr" and i.precision == 8 and i.jfif and not i.arithmetic, "info: colour space") + t:check(Jpeg.info(Bytes.reader(file("photo_arith_420_prog"))).arithmetic, "info: arithmetic") + t:eq(Jpeg.info(Bytes.reader(file("photo_gray"))).colorSpace, "gray", "info: grey") + do + local g = decode(file("photo_gray"), { native = true }) + local rgba = decode(file("photo_gray")) + t:check(g.format == "gray8" and buffer.len(g.pixels) == g.width * g.height, "native grey decodes to gray8") + t:eq(buffer.readu8(g.pixels, 77), buffer.readu8(rgba.pixels, 77 * 4), "gray8 samples") + t:eq(decode(file("photo_q90_420"), { native = true }).format, "rgba8", "native colour stays rgba8") + end + t:eq(Jpeg.info(Bytes.reader(file("photo_rgb"))).colorSpace, "rgb", "info: RGB") + t:eq(Jpeg.info(Bytes.reader(file("photo_cmyk"))).colorSpace, "cmyk", "info: CMYK") + t:eq(Jpeg.info(Bytes.reader(file("photo_ycck"))).colorSpace, "ycck", "info: YCCK") + t:eq(Jpeg.info(Bytes.reader(file("photo_12bit_420"))).precision, 12, "info: 12-bit") + local img = decode(file("photo_q90_420_prog")) + local s = img.meta.source + t:check(img.kind == "image" and img.format == "rgba8", "a standard rgba8 Image") + t:check(s.format == "jpeg" and s.progressive and s.components == 3 and s.colorType == "ycbcr" and img.meta.orientation == 1, "meta.source") + local _, e = decode(file("photo_q90_420"), { maxPixels = 1000 }) + t:check(e and e.code == Err.LIMIT, "maxPixels: " .. tostring(e)) + t:check(decode(file("photo_q90_420"), { maxPixels = 160 * 120 }) ~= nil, "maxPixels at the limit") + local _, e2 = decode(file("photo_q90_420"), { scale = 3 }) + t:check(e2 and e2.code == Err.ARG, "bad scale") + local _, e3 = decode("nope") + t:check(e3 and e3.code == Err.CORRUPT, "junk: " .. tostring(e3)) + -- a range inside a bigger buffer + local data = files["photo_q90_420"] + local big = buffer.create(#data + 20) + buffer.writestring(big, 11, data) + local a = Jpeg.decode(Bytes.reader(big, 11, #data)) + t:check(a and Crc32.of(a.pixels) == Crc32.of(decode(data).pixels), "decode from a sub-range") +end + +-- EXIF orientation (both byte orders), applied with opts.orient; ICC + comment + density segments +local function withSegments(data: string, segs: { string }): string + return string.sub(data, 1, 2) .. table.concat(segs) .. string.sub(data, 3) +end +local function seg(marker: number, body: string): string + local len = #body + 2 + return "\255" .. string.char(marker, len // 256, len % 256) .. body +end +local function exifSeg(orient: number, le: boolean): string + local tiff + if le then + tiff = "II\42\0\8\0\0\0" .. "\1\0" .. "\18\1\3\0\1\0\0\0" .. string.char(orient, 0, 0, 0) .. "\0\0\0\0" + else + tiff = "MM\0\42\0\0\0\8" .. "\0\1" .. "\1\18\0\3\0\0\0\1" .. string.char(0, orient, 0, 0) .. "\0\0\0\0" + end + return seg(0xE1, "Exif\0\0" .. tiff) +end +do + local base = files["photo_q90_420"] + local plain = decode(base) + local w, h = plain.width, plain.height + local function px(img: any, x: number, y: number): number + return buffer.readu32(img.pixels, (y * img.width + x) * 4) + end + for _, le in { true, false } do + for o = 1, 8 do + local d = withSegments(base, { exifSeg(o, le) }) + local img = decode(d) + t:check(img and img.meta.orientation == o, "EXIF orientation " .. o) + t:check(img.meta.exif and buffer.readstring(img.meta.exif, 0, 2) == (if le then "II" else "MM"), "meta.exif") + t:eq(Jpeg.info(Bytes.reader(buffer.fromstring(d))).orientation, o, "info orientation " .. o) + local r = decode(d, { orient = true }) + local swap = o >= 5 + t:check(r.width == (if swap then h else w) and r.height == (if swap then w else h), "oriented size " .. o) + -- where the source's top-left pixel lands + local tl = px(plain, 0, 0) + local want = ({ + { 0, 0 }, + { r.width - 1, 0 }, + { r.width - 1, r.height - 1 }, + { 0, r.height - 1 }, + { 0, 0 }, + { r.width - 1, 0 }, + { r.width - 1, r.height - 1 }, + { 0, r.height - 1 }, + })[o] + t:eq(px(r, want[1], want[2]), tl, "orientation " .. o .. ": top-left pixel") + end + end + local icc = string.rep("icc!", 50) + local d = withSegments(base, { + seg(0xE2, "ICC_PROFILE\0\1\2" .. string.sub(icc, 1, 120)), + seg(0xE2, "ICC_PROFILE\0\2\2" .. string.sub(icc, 121)), + seg(0xFE, "hello jpeg"), + }) + local img = decode(d) + t:check(img.meta.icc and buffer.tostring(img.meta.icc) == icc, "ICC chunks joined") + t:check(img.meta.text and img.meta.text.comment == "hello jpeg", "COM") + t:check(img.meta.dpi == nil, "no density in cjpeg's JFIF (aspect only)") +end + +-- the encoder: byte-identical to cjpeg +local function source(c: any): any + local img = Types.Image.new(c.width, c.height, c.format) + if c.format == "rgb8" then + buffer.writestring(img.pixels, 0, c.pixels) + else + buffer.writestring(img.pixels, 0, c.pixels) + end + return img +end +local function psnr(a: buffer, b: buffer, n: number, bpp: number): number + local se = 0 + for i = 0, n - 1 do + for k = 0, 2 do + local d = buffer.readu8(a, i * 4 + k) - buffer.readu8(b, i * bpp + (if bpp == 1 then 0 else k)) + se += d * d + end + end + if se == 0 then + return 99 + end + return 10 * math.log10(255 * 255 * n * 3 / se) +end +do + local exact = 0 + for _, c in Enc do + local img = source(c) + local out, err = Jpeg.encode(img, c.opts) + t:check(out, c.name .. ": encode: " .. tostring(err)) + local same = buffer.tostring(out :: buffer) == c.want + if not same then + local s = buffer.tostring(out :: buffer) + local at = 0 + for i = 1, math.min(#s, #c.want) do + if string.byte(s, i) ~= string.byte(c.want, i) then + at = i + break + end + end + t:check(false, string.format("%s: differs from cjpeg at byte %d (ours %d bytes, cjpeg %d)", c.name, at, #s, #c.want)) + end + exact += 1 + local back = decode(out) + t:check(back and back.width == c.width and back.height == c.height, c.name .. ": decodes") + local bpp = if c.format == "gray8" then 1 else 3 + local q = c.opts.quality + local p = psnr(back.pixels, img.pixels, c.width * c.height, bpp) + if c.width * c.height >= 1000 and not c.opts.gray then + -- the synthetic source has salt-and-pepper noise: lower thresholds + local floor = (if q >= 75 then 28 elseif q >= 50 then 25 else 20) - (if string.find(c.name, "synth") then 10 else 0) + t:check(p > floor, string.format("%s: PSNR %.1f dB", c.name, p)) + end + end + t:note("%d encodes byte-identical to cjpeg", exact) +end + +-- encoder: meta segments round trip, rgba8 input, options, errors +do + local c = Enc[1] + local rgb = source(c) + local img = Types.Image.new(c.width, c.height) + for i = 0, c.width * c.height - 1 do + buffer.writeu32(img.pixels, i * 4, buffer.readu16(rgb.pixels, i * 3) + buffer.readu8(rgb.pixels, i * 3 + 2) * 65536 + 0x80000000) + end + local a = Jpeg.encode(rgb, { quality = 80 }) :: buffer + local b = Jpeg.encode(img, { quality = 80 }) :: buffer + t:check(buffer.tostring(a) == buffer.tostring(b), "rgba8 input encodes as rgb8 (alpha ignored)") + img.meta.icc = buffer.fromstring(string.rep("P", 70000)) + img.meta.exif = buffer.fromstring("MM\0\42\0\0\0\8\0\1\1\18\0\3\0\0\0\1\0\6\0\0\0\0\0\0") + img.meta.text = { comment = "made by formats-luau" } + img.meta.dpi = { x = 300, y = 300 } + local m = Jpeg.encode(img, { quality = 80 }) :: buffer + local back = decode(m) + t:check(back.meta.icc and buffer.len(back.meta.icc) == 70000, "ICC round trip (two APP2 chunks)") + t:eq(back.meta.orientation, 6, "EXIF round trip") + t:check(back.meta.text and back.meta.text.comment == "made by formats-luau", "COM round trip") + t:check(back.meta.dpi and back.meta.dpi.x == 300, "density round trip") + local nm = Jpeg.encode(img, { quality = 80, meta = false, jfif = false }) :: buffer + t:check(buffer.len(nm) < buffer.len(a), "meta = false, jfif = false") + local _, e1 = Jpeg.encode({} :: any) + t:check(e1 and e1.code == Err.ARG, "encode of a non-image") + local _, e2 = Jpeg.encode(Types.Image.new(4, 4, "rgba16")) + t:check(e2 and e2.code == Err.ARG, "rgba16 is refused") + local _, e3 = Jpeg.encode(img, { quality = 0 }) + t:check(e3 and e3.code == Err.ARG, "quality 0") + local _, e4 = Jpeg.encode(img, { subsampling = "411" } :: any) + t:check(e4 and e4.code == Err.ARG, "subsampling 411") + local one = Jpeg.encode(Types.Image.new(1, 1), { progressive = true, subsampling = "444" }) + t:check(one and decode(one).width == 1, "1x1 progressive") +end + +-- truncated files: decode what is there (flagged) or fail with an Err; never throw +do + local count, partial = 0, 0 + for _, name in { "photo_q90_420", "photo_q90_420_prog", "photo_rst1", "photo_rst1b_prog", "photo_arith_420", "photo_arith_rst_prog" } do + local s = files[name] + for cut = 0, #s - 1, math.max(1, #s // 61) do + local ok, img, err = pcall(decode, string.sub(s, 1, cut)) + t:check(ok, name .. " cut at " .. cut .. ": threw " .. tostring(img)) + t:check(img or Err.is(err), name .. " cut at " .. cut .. ": no image and no Err") + if img then + partial += 1 + t:check(img.meta.truncated or cut >= #s - 2, name .. " cut at " .. cut .. ": not flagged truncated") + end + count += 1 + end + end + t:note("%d truncated files, %d decoded partially", count, partial) +end + +-- fuzz +do + local samples = {} + for i, c in Dec do + if i % 9 == 0 and #c.data < 40000 then + table.insert(samples, c.data) + end + end + t:fuzz("decode", function(b: buffer) + return Jpeg.decode(Bytes.reader(b)) + end, samples, { mutations = 6, keepHeader = 2 }) + t:fuzz("decode 1/8", function(b: buffer) + return Jpeg.decode(Bytes.reader(b), { scale = 8 }) + end, samples, { mutations = 2, garbage = 30 }) +end + +t:done() diff --git a/tests/image/pnm.luau b/tests/image/pnm.luau new file mode 100644 index 0000000..a5b58e4 --- /dev/null +++ b/tests/image/pnm.luau @@ -0,0 +1,125 @@ +-- image/pnm tests: ImageMagick-written P1-P7 / PFM files (ASCII and binary, 8 / 16-bit, PAM tuple types, both PFM +-- byte orders) and hand-written edge cases (comments, packed P1 digits, odd maxvals) against ImageMagick's RGBA +-- decodes (8-bit; 16-bit and float natively); round trips of every subtype through our encoder, binary and ASCII; +-- errors; the fuzz no-throw pass. Fixtures: tools/fixtures/pnm.py. +local T = require("@tests/T") +local Pnm = require("@formats/image/pnm") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Fx = require("@tests/gen/pnm") + +local t = T.suite("pnm") + +t:eq(Pnm.name, "pnm", "name") +t:check(Pnm.caps.decode and Pnm.caps.encode, "caps") + +local function dec(data: any, opts: any?): (any, any) + return Pnm.decode(Bytes.reader(if type(data) == "string" then buffer.fromstring(data) else data), opts) +end + +-- channel c (0..3) of pixel i of a native image, in 16-bit scale +local function chan16(img: any, i: number, c: number): number + local px, f = img.pixels, img.format + if f == "gray16" then + return if c == 3 then 65535 else buffer.readu16(px, i * 2) + elseif f == "rgba16" then + return buffer.readu16(px, i * 8 + c * 2) + elseif f == "gray8" then + return if c == 3 then 65535 else buffer.readu8(px, i) * 257 + elseif f == "graya8" then + return buffer.readu8(px, i * 2 + (if c == 3 then 1 else 0)) * 257 + elseif f == "rgb8" then + return if c == 3 then 65535 else buffer.readu8(px, i * 3 + c) * 257 + end + return buffer.readu8(px, i * 4 + c) * 257 +end + +for _, c in Fx do + local img, err = dec(c.data) + t:check(img, c.name .. ": " .. tostring(err)) + t:check(img.width == c.width and img.height == c.height and img.format == "rgba8", c.name .. ": size") + local worst = 0 + for i = 0, c.width * c.height * 4 - 1 do + worst = math.max(worst, math.abs(buffer.readu8(img.pixels, i) - string.byte(c.rgba8, i + 1))) + end + t:check(worst <= c.tol, string.format("%s: max difference %d against ImageMagick (allowed %d)", c.name, worst, c.tol)) + local nat = dec(c.data, { native = true }) + if c.rgba16 then + local w16 = 0 + for i = 0, c.width * c.height - 1 do + for k = 0, 3 do + local o = (i * 4 + k) * 2 + 1 + local want = string.byte(c.rgba16, o) * 256 + string.byte(c.rgba16, o + 1) + w16 = math.max(w16, math.abs(chan16(nat, i, k) - want)) + end + end + t:check(w16 <= c.tol * 66, string.format("%s: 16-bit max difference %d", c.name, w16)) + end + if c.floats then + t:eq(nat.format, "rgbaf32", c.name .. ": native float") + local fb = buffer.fromstring(c.floats) + local fw = 0 + for i = 0, c.width * c.height * 4 - 1 do + fw = math.max(fw, math.abs(buffer.readf32(nat.pixels, i * 4) - buffer.readf32(fb, i * 4))) + end + t:check(fw < 1e-6, c.name .. ": floats") + end + -- round trips through our encoder: the same subtype, binary and ASCII + local ext = string.match(c.name, "%.(%a+)$") + for _, ascii in { false, true } do + local enc, eerr = Pnm.encode(nat, { format = ext, ascii = ascii }) + t:check(enc, c.name .. ": encode: " .. tostring(eerr)) + local back = dec(enc, { native = true }) + t:check(back and back.format == nat.format and buffer.tostring(back.pixels) == buffer.tostring(nat.pixels), string.format("%s: round trip (ascii %s)", c.name, tostring(ascii))) + end +end +t:note("%d files match ImageMagick and round-trip", #Fx) + +-- encoder choices, conversions, options +do + local img = Types.Image.new(3, 2) + for i = 0, 23 do + buffer.writeu8(img.pixels, i, (i * 40) % 256) + end + for i = 0, 5 do + buffer.writeu8(img.pixels, i * 4 + 3, 255) + end + local s = buffer.tostring(Pnm.encode(img) :: buffer) + t:eq(string.sub(s, 1, 2), "P6", "opaque rgba8 -> P6") + buffer.writeu8(img.pixels, 3, 7) + t:eq(string.sub(buffer.tostring(Pnm.encode(img) :: buffer), 1, 2), "P7", "alpha -> PAM") + t:eq(string.sub(buffer.tostring(Pnm.encode(img, { format = "pgm" }) :: buffer), 1, 2), "P5", "pgm by name") + t:eq(string.sub(buffer.tostring(Pnm.encode(img, { format = "pbm", ascii = true }) :: buffer), 1, 2), "P1", "ascii pbm") + t:eq(string.sub(buffer.tostring(Pnm.encode(img, { format = "pfm" }) :: buffer), 1, 2), "PF", "pfm by name") + local g = Types.Image.new(2, 1, "gray8") + t:eq(string.sub(buffer.tostring(Pnm.encode(g) :: buffer), 1, 2), "P5", "gray8 -> P5") + local m = Pnm.encode(g, { maxval = 15, ascii = true }) :: buffer + t:check(string.find(buffer.tostring(m), "\n15\n", 1, true) ~= nil, "maxval option") + local _, e = Pnm.encode(img, { maxval = 0 }) + t:check(e and e.code == Err.ARG, "bad maxval") + local _, e2 = Pnm.encode({} :: any) + t:check(e2 and e2.code == Err.ARG, "not an image") + t:eq(Pnm.sniff(Bytes.reader(buffer.fromstring("P6\n1 1\n255\n..."))), 0.9, "sniff") + t:eq(Pnm.sniff(Bytes.reader(buffer.fromstring("PNG"))), 0, "sniff other") + local _, e3 = dec("P6\n100 100\n255\n" .. string.rep("x", 50)) + t:check(e3 and e3.code == Err.TRUNCATED, "truncated") + local _, e4 = dec("P6\n10 10\n255\n", { maxPixels = 50 }) + t:check(e4 and e4.code == Err.LIMIT, "maxPixels") + local _, e5 = dec("P3\n1 1\n255\n1 x 3\n") + t:check(e5 and e5.code == Err.CORRUPT, "bad ascii") +end + +do + local samples = {} + for i, c in Fx do + if i % 3 == 0 then + table.insert(samples, c.data) + end + end + t:fuzz("decode", function(b: buffer) + return Pnm.decode(Bytes.reader(b)) + end, samples) +end + +t:done() diff --git a/tests/image/qoi.luau b/tests/image/qoi.luau new file mode 100644 index 0000000..d78c5cb --- /dev/null +++ b/tests/image/qoi.luau @@ -0,0 +1,85 @@ +-- image/qoi tests: Pillow-written QOI files (RGB / RGBA, noise / gradients / runs / small deltas, 1x1 to 500x1) +-- decode to Pillow's pixels; our encoder writes the same bytes as Pillow for the same pixels and round-trips exactly; +-- native rgb8 output, the colour space tag, errors, and the fuzz no-throw pass. Fixtures: tools/fixtures/qoi.py. +local T = require("@tests/T") +local Qoi = require("@formats/image/qoi") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Fx = require("@tests/gen/qoi") + +local t = T.suite("qoi") + +t:eq(Qoi.name, "qoi", "name") +t:check(Qoi.caps.decode and Qoi.caps.encode, "caps") + +local same = 0 +for _, c in Fx do + local img, err = Qoi.decode(Bytes.reader(buffer.fromstring(c.data))) + t:check(img, c.name .. ": " .. tostring(err)) + t:check(img.width == c.width and img.height == c.height and img.format == "rgba8", c.name .. ": size") + t:eq(Crc32.of(img.pixels), c.crc, c.name .. ": pixels against Pillow") + -- encode the source pixels: the same bytes as Pillow's writer + local src = Types.Image.new(c.width, c.height, if c.channels == 4 then "rgba8" else "rgb8") + src.pixels = buffer.fromstring(c.pixels) + local enc = Qoi.encode(src, { channels = c.channels, linear = string.byte(c.data, 14) == 1 }) :: buffer -- Pillow tags its files linear + if buffer.tostring(enc) == c.data then + same += 1 + end + local back = Qoi.decode(Bytes.reader(enc)) + t:eq(Crc32.of(back.pixels), c.crc, c.name .. ": our encoding round-trips") + -- native rgb8 + if c.channels == 3 then + local n = Qoi.decode(Bytes.reader(buffer.fromstring(c.data)), { native = true }) + t:check(n.format == "rgb8" and buffer.tostring(n.pixels) == c.pixels, c.name .. ": native rgb8") + end +end +t:eq(same, #Fx, "byte-identical to Pillow's encoder") +t:note("%d Pillow files decode; %d of our encodings are byte-identical to Pillow's", #Fx, same) + +-- round trips of random images, a sub-range reader, colour space, errors +do + local rand = T.rng(5) + for _, s in { { 1, 1 }, { 70, 3 }, { 33, 33 } } do + local img = Types.Image.new(s[1], s[2]) + for i = 0, s[1] * s[2] * 4 - 1 do + buffer.writeu8(img.pixels, i, if rand(3) == 0 then rand(256) else (i // 4) % 256) + end + local back = Qoi.decode(Bytes.reader(Qoi.encode(img) :: buffer)) + t:check(buffer.tostring(back.pixels) == buffer.tostring(img.pixels), "random round trip") + end + local c = Fx[4] + local big = buffer.create(#c.data + 9) + buffer.writestring(big, 5, c.data) + local img = Qoi.decode(Bytes.reader(big, 5, #c.data)) + t:check(img and Crc32.of(img.pixels) == c.crc, "decode from a sub-range") + local lin = Types.Image.new(2, 2) + local d = Qoi.encode(lin, { linear = true }) :: buffer + t:eq(buffer.readu8(d, 13), 1, "linear tag") + t:eq(Qoi.decode(Bytes.reader(d)).meta.source.colorSpace, "linear", "linear read back") + t:eq(Qoi.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, "sniff") + t:eq(Qoi.sniff(Bytes.reader(buffer.fromstring("GIF8"))), 0, "sniff other") + local _, e = Qoi.decode(Bytes.reader(buffer.fromstring(c.data)), { maxPixels = 10 }) + t:check(e and e.code == Err.LIMIT, "maxPixels") + local _, e2 = Qoi.decode(Bytes.reader(buffer.fromstring(string.sub(c.data, 1, 40)))) + t:check(e2 and e2.code == Err.TRUNCATED, "truncated: " .. tostring(e2)) + local _, e3 = Qoi.decode(Bytes.reader(buffer.fromstring("qoix" .. string.rep("\0", 20)))) + t:check(e3 and e3.code == Err.CORRUPT, "bad magic") + local _, e4 = Qoi.encode(Types.Image.new(2, 2, "gray8")) + t:check(e4 and e4.code == Err.ARG, "encode gray8 -> ARG") +end + +do + local samples = {} + for i, c in Fx do + if i % 2 == 0 then + table.insert(samples, c.data) + end + end + t:fuzz("decode", function(b: buffer) + return Qoi.decode(Bytes.reader(b)) + end, samples, { keepHeader = 4 }) +end + +t:done() diff --git a/tests/image/tga.luau b/tests/image/tga.luau new file mode 100644 index 0000000..2fe016c --- /dev/null +++ b/tests/image/tga.luau @@ -0,0 +1,96 @@ +-- image/tga tests: Pillow- and ImageMagick-written TGAs (RGB / RGBA / grey / grey + alpha / palette, raw and RLE, both +-- origins) and hand-written ones (15 / 16-bit pixels and colour maps, first index, right-to-left, RLE across rows, an +-- image ID) against the reference RGBA decodes; our encoder (raw / RLE, origins, 24 / 32-bit / grey) round-trips; +-- sniffing stays low without a footer; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/tga.py. +local T = require("@tests/T") +local Tga = require("@formats/image/tga") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Fx = require("@tests/gen/tga") + +local t = T.suite("tga") + +t:eq(Tga.name, "tga", "name") +t:check(Tga.caps.decode and Tga.caps.encode, "caps") + +local function dec(data: any, opts: any?): (any, any) + return Tga.decode(Bytes.reader(if type(data) == "string" then buffer.fromstring(data) else data), opts) +end + +for _, c in Fx do + local img, err = dec(c.data) + t:check(img, c.name .. ": " .. tostring(err)) + t:check(img.width == c.width and img.height == c.height, c.name .. ": size") + local worst, at = 0, -1 + for i = 0, #c.rgba - 1 do + local d = math.abs(buffer.readu8(img.pixels, i) - string.byte(c.rgba, i + 1)) + if d > worst then + worst, at = d, i + end + end + t:check(worst == 0, string.format("%s: differs from the reference by %d at byte %d", c.name, worst, at)) + t:check(not img.meta.truncated, c.name .. ": not truncated") + -- round trips through our encoder + for _, rle in { false, true } do + for _, origin in { "bottom-left", "top-left" } do + local enc = Tga.encode(img, { rle = rle, origin = origin }) :: buffer + local back = dec(enc) + t:check(back and buffer.tostring(back.pixels) == buffer.tostring(img.pixels), string.format("%s: round trip rle=%s %s", c.name, tostring(rle), origin)) + end + end +end +t:note("%d files match the reference decodes and round-trip", #Fx) + +do + local byName = {} + for _, c in Fx do + byName[c.name] = c + end + local id = dec(byName["hand-id-top"].data) + t:check(id.meta.text and id.meta.text.id == "hello", "image ID") + local g = dec(byName["pil-L-raw-top"].data, { native = true }) + t:eq(g.format, "gray8", "native grey") + t:eq(Tga.encode(g) and buffer.readu8(Tga.encode(g) :: buffer, 2), 3, "gray8 encodes as type 3") + local rgb = dec(byName["pil-RGB-raw-top"].data, { native = true }) + t:eq(rgb.format, "rgb8", "native rgb8") + local p = dec(byName["pil-P-raw-top"].data) + t:check(p.meta.palette and #p.meta.palette > 0, "palette in meta") + -- sniff: low without a footer, higher with ours, never for other formats + t:eq(Tga.sniff(Bytes.reader(buffer.fromstring(byName["hand-16bit"].data))), 0.2, "sniff without a footer") + t:eq(Tga.sniff(Bytes.reader(Tga.encode(p) :: buffer)), 0.9, "sniff with the footer") + t:eq(Tga.sniff(Bytes.reader(buffer.fromstring("\0\0\1\0\1\0\16\16\0\0\1\0\32\0\0\0\0\0\0\0\0\0"))), 0, "an ICO header is not a TGA") + t:eq(Tga.sniff(Bytes.reader(buffer.fromstring("\137PNG\r\n\26\n\0\0\0\13IHDR\0\0\0\0\0\0"))), 0, "a PNG is not a TGA") + -- encoder choices + local img = Types.Image.new(3, 2) + buffer.fill(img.pixels, 0, 255, 24) + t:eq(buffer.readu8(Tga.encode(img) :: buffer, 16), 24, "opaque rgba8 -> 24-bit") + buffer.writeu8(img.pixels, 3, 0) + t:eq(buffer.readu8(Tga.encode(img) :: buffer, 16), 32, "alpha -> 32-bit") + local _, e = Tga.encode(img, { origin = "middle" } :: any) + t:check(e and e.code == Err.ARG, "bad origin") + local _, e2 = Tga.encode(Types.Image.new(2, 2, "gray16")) + t:check(e2 and e2.code == Err.ARG, "gray16 refused") + -- truncation keeps what is there + local s = byName["pil-RGBA-raw-top"].data + local tr = dec(string.sub(s, 1, #s // 2)) + t:check(tr and tr.meta.truncated, "truncated pixels flagged") + local _, e3 = dec(string.sub(s, 1, 10)) + t:check(e3 and e3.code == Err.TRUNCATED, "short header") + local _, e4 = dec(s, { maxPixels = 10 }) + t:check(e4 and e4.code == Err.LIMIT, "maxPixels") +end + +do + local samples = {} + for i, c in Fx do + if i % 3 == 0 then + table.insert(samples, c.data) + end + end + t:fuzz("decode", function(b: buffer) + return Tga.decode(Bytes.reader(b)) + end, samples) +end + +t:done() diff --git a/tests/image/tiff.luau b/tests/image/tiff.luau new file mode 100644 index 0000000..f5c0f7a --- /dev/null +++ b/tests/image/tiff.luau @@ -0,0 +1,185 @@ +-- image/tiff tests: files written by tifffile / imagecodecs and ImageMagick (every compression, predictors, strips and +-- tiles, planar, both byte orders, BigTIFF, 1..32-bit integer and 16 / 32 / 64-bit float samples, palette, CMYK, +-- alpha, multi-page) against tifffile's decode, in rgba8 and native layouts; the JPEG hook; encoder round trips for +-- every layout and compression; errors; the fuzz pass. Fixtures: tools/fixtures/tiff.py. +local T = require("@tests/T") +local Tiff = require("@formats/image/tiff") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Fx = require("@tests/gen/tiff") + +local t = T.suite("tiff") + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return Tiff.decode(Bytes.reader(b), opts) +end + +-- contract +t:eq(Tiff.name, "tiff", "name") +t:check(Tiff.caps.decode and Tiff.caps.encode, "caps") +t:eq(Tiff.sniff(Bytes.reader(buffer.fromstring("II*\0\8\0\0\0"))), 1, "sniff II") +t:eq(Tiff.sniff(Bytes.reader(buffer.fromstring("MM\0*"))), 1, "sniff MM") +t:eq(Tiff.sniff(Bytes.reader(buffer.fromstring("\137PNG"))), 0, "sniff png") + +-- reference files +local pagesChecked = 0 +for _, c in Fx.cases do + local img, err = decode(c.data) + t:check(img, c.name .. ": " .. tostring(err)) + t:check(img.width == c.width and img.height == c.height and img.format == "rgba8", c.name .. ": size / format") + local frames = img.frames or { { image = img } } + t:eq(#frames, #c.pages, c.name .. ": pages") + local nat = decode(c.data, { native = true }) + local nframes = nat.frames or { { image = nat } } + for i, p in c.pages do + local crc = Crc32.of(frames[i].image.pixels) + t:check(crc == p.crc, string.format("%s page %d: rgba8 crc %08x, want %08x", c.name, i, crc, p.crc)) + local ni = nframes[i].image + t:eq(ni.format, p.native, c.name .. " page " .. i .. ": native format") + local ncrc = Crc32.of(ni.pixels) + t:check(ncrc == p.ncrc, string.format("%s page %d: native crc %08x, want %08x", c.name, i, ncrc, p.ncrc)) + pagesChecked += 1 + end + -- inside a bigger buffer + local big = buffer.create(#c.data + 9) + buffer.writestring(big, 5, c.data) + local img3 = Tiff.decode(Bytes.reader(big, 5, #c.data)) + t:check(img3 and Crc32.of(img3.pixels) == c.pages[1].crc, c.name .. ": sub-range decode") +end +t:note("%d files, %d pages match tifffile", #Fx.cases, pagesChecked) + +-- info, single page, meta +do + local multi + for _, c in Fx.cases do + if c.name == "pages3" then + multi = c + end + end + local info = Tiff.info(Bytes.reader(buffer.fromstring(multi.data))) + t:check(info and info.pages == 3 and info.width == multi.width, "info") + local p2 = decode(multi.data, { page = 2, native = true }) + t:check(p2 and p2.format == "gray16" and Crc32.of(p2.pixels) == multi.pages[2].ncrc, "opts.page") + local _, e = decode(multi.data, { page = 9 }) + t:check(e and e.code == Err.ARG, "missing page") + local _, e2 = decode(multi.data, { maxPixels = 10 }) + t:check(e2 and e2.code == Err.LIMIT, "maxPixels") + local img = decode(multi.data) + t:check(img.meta.source.format == "tiff" and img.meta.source.compression == "deflate", "meta.source") +end + +-- JPEG-compressed: needs the hook; the hook gets one stitched JPEG stream per strip +do + local _, e = decode(Fx.jpeg) + t:check(e and e.code == Err.UNSUPPORTED, "jpeg without hook: " .. tostring(e)) + local calls = 0 + local img = decode(Fx.jpeg, { + decodeImage = function(b: buffer) + calls += 1 + t:check(buffer.readu8(b, 0) == 0xFF and buffer.readu8(b, 1) == 0xD8, "stitched stream starts with SOI") + local s = buffer.tostring(b) + t:check(string.find(s, "\255\218", 1, true) ~= nil, "stitched stream has SOS") + t:check(string.find(s, "\255\196", 1, true) ~= nil or string.find(s, "\255\219", 1, true) ~= nil, "stitched stream has tables") + local im = Types.Image.new(64, 64) + buffer.fill(im.pixels, 0, 200) + return im + end, + }) + t:check(img and calls > 0, "jpeg through the hook") + -- the real thing through the api (image/jpeg decodes the stitched streams): within 2 levels of libjpeg-turbo + local F = require("@formats") + local ref = Fx.jpegRef + local full, ferr = F.load(Fx.jpeg, { format = "tiff" }) + t:check(full and full.width == ref.width and full.height == ref.height, "jpeg-in-tiff through F.load: " .. tostring(ferr)) + local worst = 0 + for i = 0, ref.width * ref.height - 1 do + for k = 0, 2 do + worst = math.max(worst, math.abs(buffer.readu8(full.pixels, i * 4 + k) - string.byte(ref.rgb, i * 3 + k + 1))) + end + end + t:check(worst <= 2, "jpeg-in-tiff pixels: max error " .. worst .. " against tifffile") + t:note("JPEG-in-TIFF through F.load: max error %d against tifffile / libjpeg-turbo", worst) +end + +-- encoder round trips +do + local rand = T.rng(11) + local function image(fmt: string, w: number, h: number): Types.Image + local img = Types.Image.new(w, h, fmt :: any) + local n = buffer.len(img.pixels) + if fmt == "rgbaf32" then + for i = 0, n // 4 - 1 do + buffer.writef32(img.pixels, i * 4, (rand(2000) - 300) / 1000) + end + else + for i = 0, n - 1 do + buffer.writeu8(img.pixels, i, if rand(3) == 0 then rand(256) else (i * 7) % 256) + end + end + return img + end + local trips = 0 + for _, fmt in { "rgba8", "rgb8", "gray8", "graya8", "gray16", "rgba16", "rgbaf32" } do + for _, comp in { "none", "deflate", "lzw", "packbits" } do + for _, pred in { true, false } do + for _, size in { { 1, 1 }, { 13, 7 }, { 200, 90 } } do + local img = image(fmt, size[1], size[2]) + img.meta.dpi = { x = 300, y = 150 } + local out, err = Tiff.encode(img, { compression = comp :: any, predictor = pred, rowsPerStrip = if size[1] == 200 then 16 else nil }) + t:check(out, fmt .. " " .. comp .. ": " .. tostring(err)) + local back, berr = Tiff.decode(Bytes.reader(out :: buffer), { native = true }) + t:check(back, fmt .. " " .. comp .. ": decode: " .. tostring(berr)) + t:eq(back.format, fmt, fmt .. " " .. comp .. ": format") + t:check(buffer.tostring(back.pixels) == buffer.tostring(img.pixels), string.format("%s %s pred=%s %dx%d: round trip", fmt, comp, tostring(pred), size[1], size[2])) + t:check(back.meta.dpi and math.abs(back.meta.dpi.x - 300) < 0.01 and math.abs(back.meta.dpi.y - 150) < 0.01, "dpi") + trips += 1 + end + end + end + end + t:note("%d encoder round trips", trips) + -- multi-page + local a, b = image("rgb8", 20, 10), image("gray16", 7, 9) + local anim = image("rgb8", 20, 10) + anim.frames = { { image = a, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" }, { image = b, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" } } :: any + local out = Tiff.encode(anim, { compression = "lzw" }) :: buffer + local back = Tiff.decode(Bytes.reader(out), { native = true }) + t:check(back.frames and #back.frames == 2, "multi-page count") + t:check(buffer.tostring(back.frames[1].image.pixels) == buffer.tostring(a.pixels), "page 1") + t:check(buffer.tostring(back.frames[2].image.pixels) == buffer.tostring(b.pixels) and back.frames[2].image.format == "gray16", "page 2") + local _, e = Tiff.encode({} :: any) + t:check(e and e.code == Err.ARG, "encode non-image") + local _, e2 = Tiff.encode(image("rgb8", 2, 2), { compression = "jpeg" } :: any) + t:check(e2 and e2.code == Err.ARG, "bad compression") + local _, e3 = Tiff.encode(Types.Image.new(2, 2, "yuv420p")) + t:check(e3 and e3.code == Err.ARG, "unsupported layout") +end + +-- errors +do + local _, e = decode("II*\0\255\255\0\0") + t:check(e and (e.code == Err.TRUNCATED or e.code == Err.CORRUPT), "bad IFD offset") + local _, e2 = decode("XX*\0") + t:check(e2 and e2.code == Err.TRUNCATED or e2.code == Err.CORRUPT, "junk") +end + +-- fuzz +do + local samples = {} + for i, c in Fx.cases do + if i % 3 == 0 and #c.data < 40000 then + table.insert(samples, c.data) + end + end + t:fuzz("decode", function(b: buffer) + return Tiff.decode(Bytes.reader(b)) + end, samples, { mutations = 12 }) + t:fuzz("decode native", function(b: buffer) + return Tiff.decode(Bytes.reader(b), { native = true }) + end, samples, { mutations = 4, garbage = 50 }) +end + +t:done() diff --git a/tests/image/webp.luau b/tests/image/webp.luau new file mode 100644 index 0000000..bf76303 --- /dev/null +++ b/tests/image/webp.luau @@ -0,0 +1,246 @@ +-- image/webp tests: every still file of tools/fixtures/webp.py (cwebp lossless / lossy / alpha variants, libvpx key +-- frames with token partitions, metadata) against dwebp (-pam, -nofancy -pam, -yuv: bit-exact), animations (img2webp, +-- gif2webp, webpmux) against Pillow's WebPAnimDecoder frames (bit-exact), our encoder (round trips at every effort, +-- dwebp / Pillow decoding our files at fixture time, metadata, animations), error codes, and the fuzz no-throw pass. +-- Fixtures: tools/fixtures/webp.py. +local T = require("@tests/T") +local Webp = require("@formats/image/webp") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Cases = require("@tests/gen/webp_cases") +local Anims = require("@tests/gen/webp_anim") +local Src = require("@tests/gen/webp_src") +local Enc = require("@tests/gen/webp_enc") + +local t = T.suite("webp") + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return Webp.decode(Bytes.reader(b), opts) +end + +-- the contract +t:eq(Webp.name, "webp", "name") +t:eq(Webp.category, "image", "category") +t:check(table.find(Webp.extensions, "webp") ~= nil, "extensions") +t:check(Webp.caps.decode and Webp.caps.encode and Webp.caps.animation and Webp.caps.alpha, "caps") + +-- still files, bit-exact with dwebp +do + local lossy, lossless, alpha = 0, 0, 0 + for _, c in Cases do + local img, err = decode(c.data) + t:check(img, c.name .. ": " .. tostring(err)) + t:check(img.kind == "image" and img.format == "rgba8" and img.width == c.width and img.height == c.height, c.name .. ": size") + local crc = Crc32.of(img.pixels) + t:check(crc == c.crc, string.format("%s: pixels crc %08x, dwebp %08x", c.name, crc, c.crc)) + t:eq(img.meta.source.format, "webp", c.name .. ": meta.source") + t:eq(img.meta.source.lossless, not c.lossy, c.name .. ": lossless flag") + if c.lossy then + lossy += 1 + local nf = decode(c.data, { upsampling = "nearest" }) + t:check(Crc32.of(nf.pixels) == c.nofancy, c.name .. ": -nofancy") + if not c.alpha then + local y = decode(c.data, { native = true }) + t:check(y.format == "yuv420p" and Crc32.of(y.pixels) == c.yuv, c.name .. ": yuv420p planes (dwebp -yuv)") + end + else + lossless += 1 + end + if c.alpha then + alpha += 1 + end + if c.icc then + t:check(img.meta.icc and Crc32.of(img.meta.icc) == c.icc, c.name .. ": ICC profile") + end + if c.exif then + t:check(img.meta.exif and Crc32.of(img.meta.exif) == c.exif, c.name .. ": EXIF") + t:check(img.meta.xmp and buffer.tostring(img.meta.xmp) == c.xmp, c.name .. ": XMP") + end + end + -- inside a bigger buffer (the Reader's range) + local c = Cases[3] + local big = buffer.create(#c.data + 11) + buffer.writestring(big, 5, c.data) + local img = Webp.decode(Bytes.reader(big, 5, #c.data)) + t:check(img and Crc32.of(img.pixels) == c.crc, "decode from a sub-range") + t:note("%d lossless and %d lossy files (%d with alpha) match dwebp", lossless, lossy, alpha) +end + +-- animations, bit-exact with Pillow (libwebp WebPAnimDecoder) +local function opaque(px: buffer, n: number): buffer + local b = buffer.create(n * 4) + buffer.copy(b, 0, px, 0, n * 4) + for i = 0, n - 1 do + buffer.writeu8(b, i * 4 + 3, 255) + end + return b +end +local function checkAnim(a: any, label: string) + local img, err = decode(a.data, { coalesce = true }) + t:check(img and img.frames, label .. ": " .. tostring(err)) + t:eq(#img.frames, #a.frames, label .. ": frame count") + t:eq(img.loops, a.loops, label .. ": loops") + local n = img.width * img.height + for i, f in img.frames do + local px = if a.rgba == false then opaque(f.image.pixels, n) else f.image.pixels + t:check(Crc32.of(px) == a.frames[i].crc, string.format("%s: frame %d", label, i)) + t:eq(math.floor(f.delay * 1000 + 0.5), a.frames[i].ms, label .. ": duration") + t:check(f.x == 0 and f.y == 0 and f.dispose == "none" and f.blend == "source", label .. ": coalesced frame fields") + end + t:check(buffer.tostring(img.pixels) == buffer.tostring(img.frames[1].image.pixels), label .. ": pixels = first canvas") + -- the frames as stored, then composited by Webp.coalesce: the same canvases + local raw = decode(a.data) + local canv = Webp.coalesce(raw) :: { buffer } + for i, c in canv do + local px = if a.rgba == false then opaque(c, n) else c + t:check(Crc32.of(px) == a.frames[i].crc, string.format("%s: Webp.coalesce frame %d", label, i)) + end + local only = decode(a.data, { frames = false }) + t:check(only.frames == nil and buffer.tostring(only.pixels) == buffer.tostring(img.pixels), label .. ": frames = false") + return raw +end +for _, a in Anims do + local raw = checkAnim(a, a.name) + t:check(raw.meta.source.animated and raw.frames[1].image.meta.source.codec ~= nil, a.name .. ": meta") + if a.name == "anim_mux_icc.webp" then + t:check(raw.meta.icc ~= nil, a.name .. ": ICC") + t:check(raw.meta.background[1] == 1 and raw.meta.background[2] == 2 and raw.meta.background[3] == 3 and raw.meta.background[4] == 255, a.name .. ": background colour") + t:check(raw.frames[2].x == 10 and raw.frames[2].y == 6 and raw.frames[2].dispose == "background" and raw.frames[2].blend == "over", a.name .. ": frame placement") + end +end +t:note("%d animations match Pillow", #Anims) + +-- the encoder: round trips, the fixture-time dwebp / Pillow checks of our files, metadata, animations +local function image(s: any): Types.Image + local img = Types.Image.new(s.width, s.height) + img.pixels = buffer.fromstring(s.rgba) + return img +end +do + local rt = 0 + for _, s in Src do + local img = image(s) + for _, effort in { 0, 2, 5, 7 } do + local out, err = Webp.encode(img, { effort = effort, exact = true }) + t:check(out, s.name .. ": encode: " .. tostring(err)) + local back = decode(out) + t:check(back and buffer.tostring(back.pixels) == s.rgba, string.format("%s effort %d: lossless round trip", s.name, effort)) + rt += 1 + end + -- without exact, fully transparent pixels may change, nothing else + local back = decode(Webp.encode(img)) + local same = true + for i = 0, s.width * s.height - 1 do + local a = buffer.readu8(img.pixels, i * 4 + 3) + if a ~= 0 and buffer.readu32(back.pixels, i * 4) ~= buffer.readu32(img.pixels, i * 4) then + same = false + elseif a == 0 and buffer.readu8(back.pixels, i * 4 + 3) ~= 0 then + same = false + end + end + t:check(same, s.name .. ": default (not exact) round trip") + end + local ok, ours, cwebp = 0, 0, 0 + for _, e in Enc.still do + t:check(e.ok, string.format("dwebp decodes our %s (effort %d%s)", e.name, e.effort, if e.exact then ", exact" else "")) + ok += 1 + if e.effort == 9 and e.exact then + ours += e.size + cwebp += e.cwebp + end + end + t:note("%d round trips; dwebp reads our %d files; effort 9: %d bytes, cwebp -lossless: %d bytes", rt, ok, ours, cwebp) + for _, a in Enc.anim do + t:check(a.ok, a.name .. ": Pillow composites our animation as its input frames") + checkAnim({ data = a.data, frames = (function() + local f = {} + for i, c in a.frames do + f[i] = { crc = c, ms = a.ms[i] } + end + return f + end)(), loops = a.loops, rgba = true }, "our " .. a.name) + end + -- metadata chunks + local img = image(Src[1]) + img.meta.icc = buffer.fromstring("icc profile bytes") + img.meta.exif = buffer.fromstring("Exif\0\0MM") + img.meta.xmp = "<x:xmpmeta/>" + local back = decode(Webp.encode(img)) + t:check(back.meta.icc and buffer.tostring(back.meta.icc) == "icc profile bytes", "ICC round trip") + t:check(back.meta.exif and buffer.tostring(back.meta.exif) == "Exif\0\0MM", "EXIF round trip") + t:check(back.meta.xmp and buffer.tostring(back.meta.xmp) == "<x:xmpmeta/>", "XMP round trip") + t:check(back.meta.source.extended and buffer.tostring(back.pixels) == Src[1].rgba, "VP8X still round trip") + -- an animation round trip through our own decoder (frame fields kept) + local anim = Types.Image.new(8, 6) + local f1 = Types.Image.new(8, 6) + buffer.fill(f1.pixels, 0, 200) + local f2 = Types.Image.new(4, 2) + buffer.fill(f2.pixels, 0, 77) + anim.frames = { + { image = f1, delay = 0.25, x = 0, y = 0, dispose = "none", blend = "source" }, + { image = f2, delay = 1.5, x = 2, y = 4, dispose = "background", blend = "over" }, + } + anim.loops = 7 + local ab = decode(Webp.encode(anim, { background = { 10, 20, 30, 40 } })) + t:check(ab.frames and #ab.frames == 2 and ab.loops == 7, "animation round trip: frames, loops") + t:check(ab.frames[2].x == 2 and ab.frames[2].y == 4 and ab.frames[2].dispose == "background" and ab.frames[2].blend == "over" and ab.frames[2].delay == 1.5, "animation round trip: frame fields") + t:check(buffer.tostring(ab.frames[2].image.pixels) == buffer.tostring(f2.pixels), "animation round trip: frame pixels") + t:check(ab.meta.background[1] == 10 and ab.meta.background[4] == 40, "animation round trip: background") + -- bad arguments + local _, e1 = Webp.encode({} :: any) + t:check(e1 and e1.code == Err.ARG, "encode a non-image: ARG") + local _, e2 = Webp.encode(img, { lossless = false }) + t:check(e2 and e2.code == Err.UNSUPPORTED, "lossy encode: UNSUPPORTED") + local _, e3 = Webp.encode(img, { effort = 11 }) + t:check(e3 and e3.code == Err.ARG, "bad effort: ARG") + anim.frames[2].x = 6 + local _, e4 = Webp.encode(anim) + t:check(e4 and e4.code == Err.ARG, "frame outside the canvas: ARG") +end + +-- sniff, info, errors +do + local c = Cases[1] + t:eq(Webp.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, "sniff WebP") + t:eq(Webp.sniff(Bytes.reader(buffer.fromstring("RIFF\0\0\0\0WAVEfmt "))), 0, "sniff WAV") + t:eq(Webp.sniff(Bytes.reader(buffer.create(0))), 0, "sniff nothing") + local r = Bytes.reader(buffer.fromstring(c.data)) + local info = Webp.info(r) + t:check(info and info.width == c.width and info.height == c.height and info.frames == 1, "info") + local ai = Webp.info(Bytes.reader(buffer.fromstring(Anims[1].data))) + t:check(ai and ai.animated and ai.frames == #Anims[1].frames, "info of an animation") + local _, e1 = decode("RIFF\4\0\0\0WEBP") + t:check(e1 and e1.code == Err.CORRUPT, "RIFF size too small: " .. tostring(e1)) + local _, e2 = decode(string.sub(c.data, 1, #c.data - 5)) + t:check(e2 and e2.code == Err.TRUNCATED, "truncated: " .. tostring(e2)) + local _, e3 = decode(c.data, { maxPixels = 10 }) + t:check(e3 and e3.code == Err.LIMIT, "maxPixels: " .. tostring(e3)) + local _, e4 = decode("not a webp file at all") + t:check(e4 and e4.code == Err.CORRUPT, "junk: " .. tostring(e4)) +end + +-- fuzz: truncations, mutations and garbage never throw +do + local samples = {} + for i, c in Cases do + if i % 7 == 0 and #c.data < 20000 then + table.insert(samples, c.data) + end + end + for _, a in Anims do + if #a.data < 40000 then + table.insert(samples, a.data) + end + end + t:fuzz("decode", function(b: buffer) + return Webp.decode(Bytes.reader(b), { maxPixels = 2 ^ 20 }) + end, samples, { mutations = 6 }) + t:fuzz("decode coalesce", function(b: buffer) + return Webp.decode(Bytes.reader(b), { maxPixels = 2 ^ 20, coalesce = true, upsampling = "nearest" }) + end, samples, { mutations = 3, keepHeader = 30, garbage = 20 }) +end + +t:done() diff --git a/tests/layered/aseprite.luau b/tests/layered/aseprite.luau new file mode 100644 index 0000000..06558f6 --- /dev/null +++ b/tests/layered/aseprite.luau @@ -0,0 +1,172 @@ +-- layered/aseprite tests: sprites written by tools/fixtures/aseprite.py (RGBA / grayscale / indexed; raw, zlib and +-- linked cels; groups, hidden layers, blend modes, layer and cel opacity; old and new palettes; tags; user data) and +-- by LibreSprite (re-saved and from a GIF): every cel's pixels and position, and our flatten of every frame against +-- LibreSprite's rendering (PSNR); our encoder's sprite rendered by LibreSprite (tools/fixtures/_ours.luau); round +-- trips (linked cels kept), the contract and the fuzz pass. Fixtures: tools/fixtures/aseprite.py. +local T = require("@tests/T") +local Ase = require("@formats/layered/aseprite") +local LayerOps = require("@formats/ops/LayerOps") +local Types = require("@formats/Types") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/aseprite") +local Ours = require("@tests/gen/aseprite_ours") + +local t = T.suite("aseprite") + +local function decode(s: string | buffer, opts: any?): (any, any) + local b = if type(s) == "string" then buffer.fromstring(s) else s + return Ase.decode(Bytes.reader(b), opts) +end +local function psnr(a: buffer, b: string): number + local n = math.min(buffer.len(a), #b) + local se = 0 + for i = 0, n - 1, 4 do + local aa, ab = buffer.readu8(a, i + 3), string.byte(b, i + 4) + for k = 0, 2 do + local d = (buffer.readu8(a, i + k) * aa - string.byte(b, i + k + 1) * ab) / 255 + se += d * d + end + se += (aa - ab) * (aa - ab) + end + if se == 0 then + return 99 + end + return 10 * math.log10(255 * 255 / (se / n)) +end +-- the n-th node (groups included, file order) of a frame's tree +local function nodes(layers: { any }, out: { any }?): { any } + local o = out or {} + for _, l in layers do + table.insert(o, l) + if l.children then + nodes(l.children, o) + end + end + return o +end + +t:eq(Ase.name, "aseprite", "name") +t:eq(Ase.category, "layered", "category") +t:check(Ase.caps.decode and Ase.caps.encode, "caps") + +local samples = {} +for _, c in Fx.cases do + local doc, err = decode(c.data) + t:check(doc, c.name .. ": " .. tostring(err)) + t:check(doc.width == c.width and doc.height == c.height, c.name .. ": size") + t:eq(#doc.frames, c.nframes, c.name .. ": frames") + for _, cel in c.cels do + local l = nodes(doc.frames[cel.frame].layers)[cel.layer] + local label = string.format("%s: frame %d layer %d", c.name, cel.frame, cel.layer) + t:check(l and l.x == cel.x and l.y == cel.y and l.image.width == cel.w and l.image.height == cel.h, label .. ": position / size") + t:eq(Crc32.of(l.image.pixels), cel.crc, label .. ": pixels") + end + -- our flatten vs LibreSprite's rendering of each frame + for fi, want in c.frames do + local img = LayerOps.flatten(doc, { frame = fi }) :: any + local p = psnr(img.pixels, want) + t:check(p >= 40, string.format("%s: frame %d vs LibreSprite: %.1f dB", c.name, fi, p)) + if p < 99 then + t:note("%s frame %d: flatten vs LibreSprite %.1f dB", c.name, fi, p) + end + end + table.insert(samples, c.data) +end + +-- the hand-made RGBA sprite's details +do + local doc = decode(Fx.cases[1].data) + local L = doc.layers + t:eq(#L, 4, "top level: Background, Group, Hidden, Top") + t:eq(L[2].name, "Group", "group") + t:eq(#L[2].children, 2, "group children") + t:eq(L[2].children[1].blend, "multiply", "blend") + t:eq(math.floor(L[2].children[1].opacity * 255 + 0.5), 200, "layer opacity") + t:eq(math.floor(L[2].children[2].fillOpacity * 255 + 0.5), 128, "cel opacity -> fillOpacity") + t:eq(L[3].visible, false, "hidden") + t:eq(L[2].children[1].userData.text, "mul layer", "layer user data") + t:eq(L[2].children[1].userData.color[4], 4, "user data colour") + t:eq(L[2].children[1].celUserData.text, "a cel", "cel user data") + t:eq(doc.frames[2].delay, 0.15, "frame delay") + t:check(doc.frames[3].layers[1].image == L[1].image and doc.frames[3].layers[1].link == 1, "linked cel shares the image") + t:eq(#doc.meta.tags, 2, "tags") + t:check(doc.meta.tags[2].name == "back" and doc.meta.tags[2].from == 2 and doc.meta.tags[2].to == 3 and doc.meta.tags[2].direction == "pingpong" and doc.meta.tags[2]["repeat"] == 3, "tag fields") + t:eq(doc.meta.tags[1].userData.text, "walk tag", "tag user data") + t:eq(#doc.meta.palette, 16, "palette") + t:eq(doc.meta.paletteNames[4], "fourth", "palette names") + t:eq(doc.meta.colorDepth, 32, "depth") + local idx = decode(Fx.cases[3].data) + t:eq(#idx.meta.palette, 5, "old palette chunk") + t:eq(idx.meta.colorDepth, 8, "indexed") + + -- round trips: every frame's nodes and pixels, linked cels stay shared, depth kept + for ci, c in Fx.cases do + local d = decode(c.data) + local out, eerr = Ase.encode(d) + t:check(out, c.name .. ": encode: " .. tostring(eerr)) + local back = decode(out :: buffer) + t:check(back, c.name .. ": decode ours") + t:eq(#back.frames, #d.frames, c.name .. ": rt frames") + t:eq(back.meta.colorDepth, d.meta.colorDepth, c.name .. ": rt depth") + for fi, f in d.frames do + local a, b = nodes(f.layers), nodes(back.frames[fi].layers) + t:eq(#b, #a, c.name .. ": rt nodes") + for k, l in a do + t:eq(b[k].name, l.name, "rt name") + t:check(buffer.tostring(b[k].image.pixels) == buffer.tostring(l.image.pixels), c.name .. ": rt pixels " .. l.name .. " frame " .. fi) + t:check(b[k].x == l.x and b[k].y == l.y, "rt position") + t:eq(b[k].visible, l.visible, "rt visible") + t:eq(b[k].fillOpacity, l.fillOpacity, "rt cel opacity") + if not l.children then + t:eq(b[k].blend, l.blend, "rt blend") + end + end + t:eq(back.frames[fi].delay, f.delay, "rt delay") + end + if ci == 1 then + t:check(back.frames[3].layers[1].image == back.layers[1].image, "rt: linked cel written as a link") + t:eq(back.meta.tags[2].direction, "pingpong", "rt tags") + t:eq(back.meta.paletteNames[1], "first", "rt palette names") + end + table.insert(samples, buffer.tostring(out :: buffer)) + end + -- forced depths + local _, e = Ase.encode(doc, { depth = 16 }) + t:check(e and e.code == Err.ARG, "colour sprite as grayscale: " .. tostring(e)) + local g = decode(Fx.cases[2].data) + local g32 = decode(Ase.encode(g, { depth = 32 }) :: buffer) + t:eq(g32.meta.colorDepth, 32, "grayscale written as RGBA") +end + +-- LibreSprite renders our encoder's sprite like our flatten does +t:eq(#Ours.frames, Ours.nframes, "LibreSprite read every frame of our sprite") +for fi, want in Ours.frames do + local ours = Ours.ours[fi] + local p = psnr(buffer.fromstring(ours), want) + t:check(p >= 40, string.format("our sprite frame %d: LibreSprite vs our flatten %.1f dB", fi, p)) + t:note("our sprite frame %d: LibreSprite vs our flatten %.1f dB", fi, p) +end + +-- a Layered without frames is one frame +do + local d = Types.Layered.new(4, 3) + d.layers = { Types.Layered.layer("only", Types.Image.new(2, 2), 1, 1) } + local back = decode(Ase.encode(d) :: buffer) + t:check(back and #back.frames == 1 and back.layers[1].name == "only" and back.layers[1].x == 1, "single frame") + local _, e = Ase.encode({ width = 4, height = 4, layers = { { name = "x" } } } :: any) + t:check(e and e.code == Err.ARG, "layer without an image") + local _, e2 = decode("\0\0\0\0\224\165") + t:check(e2 and e2.code == Err.TRUNCATED, "short header") + local bad = buffer.fromstring(Fx.cases[1].data) + buffer.writeu16(bad, 12, 24) + local _, e3 = decode(bad) + t:check(e3 and e3.code == Err.CORRUPT, "bad depth") + t:eq(Ase.sniff(Bytes.reader(buffer.fromstring(Fx.cases[1].data))), 1, "sniff") +end + +t:fuzz("decode", function(b: buffer) + return Ase.decode(Bytes.reader(b)) +end, samples, { mutations = 30, keepHeader = 6 }) +t:done() diff --git a/tests/layered/psd.luau b/tests/layered/psd.luau new file mode 100644 index 0000000..5d3227a --- /dev/null +++ b/tests/layered/psd.luau @@ -0,0 +1,184 @@ +-- layered/psd tests: PSD / PSB files of every colour mode and depth, compression, groups, pass-through, clipping, +-- masks, fill opacity and blend mode (written by tools/fixtures/psd.py) plus an ImageMagick PSD, against psd-tools: +-- the merged image and every layer's pixels exact (8-bit; 16 / 32-bit within rounding), our flatten (ops/LayerOps) +-- against psd-tools' composite by PSNR; our encoder's PSD read back by psd-tools (tools/fixtures/_ours.luau), round +-- trips, the contract and the fuzz pass. Fixtures: tools/fixtures/psd.py. +local T = require("@tests/T") +local Psd = require("@formats/layered/psd") +local LayerOps = require("@formats/ops/LayerOps") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/psd") +local Ours = require("@tests/gen/psd_ours") + +local t = T.suite("psd") + +local function decode(s: string | buffer, opts: any?): (any, any) + local b = if type(s) == "string" then buffer.fromstring(s) else s + return Psd.decode(Bytes.reader(b), opts) +end +-- PSNR of two rgba8 buffers, colours premultiplied by alpha (the colour of a transparent pixel does not matter); +-- identical -> 99 +local function psnr(a: buffer, b: string, opaque: boolean?): number + local n = math.min(buffer.len(a), #b) + local se = 0 + for i = 0, n - 1, 4 do + local aa, ab = buffer.readu8(a, i + 3), string.byte(b, i + 4) + if opaque then + aa, ab = 255, 255 + end + for k = 0, 2 do + local d = (buffer.readu8(a, i + k) * aa - string.byte(b, i + k + 1) * ab) / 255 + se += d * d + end + se += (aa - ab) * (aa - ab) + end + if se == 0 then + return 99 + end + return 10 * math.log10(255 * 255 / (se / n)) +end +local function leaves(layers: any): { any } + local out = {} + for l in LayerOps.leaves(layers) do + table.insert(out, l) + end + return out +end + +t:eq(Psd.name, "psd", "name") +t:eq(Psd.category, "layered", "category") +t:check(Psd.caps.decode and Psd.caps.encode, "caps") + +-- PSNR floors for our flatten vs psd-tools' composite: blend modes where psd-tools' formulas differ from the W3C ones +-- (Photoshop's own differ from both) get a lower bar +local LOW = { ["blend-diss"] = 8, ["blend-hMix"] = 15, ["blend-sLit"] = 30, ["blend-vLit"] = 25, ["blend-lLit"] = 30, ["blend-pLit"] = 30, ["blend-div"] = 30, ["blend-idiv"] = 30, ["blend-fdiv"] = 25, ["blend-hue"] = 25, ["blend-sat"] = 25, ["blend-colr"] = 25, ["blend-lum"] = 25 } +local samples = {} +for _, c in Fx.cases do + local doc, err = decode(c.data) + t:check(doc, c.name .. ": " .. tostring(err)) + t:eq(doc.kind, "layered", c.name .. ": kind") + t:check(doc.width == c.width and doc.height == c.height, c.name .. ": size") + local comp = doc.meta.composite + if #c.composite > 0 then + local src = doc.meta.source + local exact = (src.bitDepth == 8 or src.bitDepth == 1) and src.colorMode ~= "lab" and src.colorMode ~= "cmyk" + if exact then + t:check(buffer.tostring(comp.pixels) == c.composite, c.name .. ": merged image = psd-tools") + else + -- (PIL turns Lab into RGBA with alpha 0: compare the colours only) + local p = psnr(comp.pixels, c.composite, src.colorMode == "lab") + -- 16 / 32 bits: rounding; CMYK / Lab: different conversions (ours: naive CMYK, D65 Lab) + local floor = if src.colorMode == "lab" then 20 elseif src.colorMode == "cmyk" then 30 else 45 + t:check(p > floor, string.format("%s: merged image PSNR %.1f", c.name, p)) + t:note("%s: merged image vs psd-tools %.1f dB", c.name, p) + end + end + -- layers, in order, against psd-tools + local ours = leaves(doc.layers) + local ref = {} + for _, l in c.layers do + if not l.group then + table.insert(ref, l) + end + end + t:eq(#ours, #ref, c.name .. ": leaf count") + for i, r in ref do + local l = ours[i] + t:eq(l.name, r.name, c.name .. ": layer name") + if r.width > 0 then + t:check(l.x == r.left and l.y == r.top and l.image.width == r.width and l.image.height == r.height, c.name .. ": " .. r.name .. ": bounds") + end + if r.crc and doc.meta.source.bitDepth == 8 then + t:eq(Crc32.of(l.image.pixels), r.crc, c.name .. ": " .. r.name .. ": pixels") + end + end + -- our flatten vs psd-tools' composite + if c.flat and #ours > 0 then + local flat = LayerOps.flatten(doc) :: any + local p = psnr(flat.pixels, c.flat) + local floor = LOW[c.name] or 38 + t:check(p >= floor, string.format("%s: flatten PSNR %.1f dB (floor %d)", c.name, p, floor)) + if p < 99 then + t:note("%s: flatten vs psd-tools %.1f dB", c.name, p) + end + end + if #samples < 8 and (c.name == "rgb-layers" or c.name == "psb" or c.name == "rgb16-lr16" or c.name == "gray" or c.name == "indexed" or c.name == "bitmap" or c.name == "rgb32" or c.name == "cmyk") then + table.insert(samples, c.data) + end +end + +-- the full document's structure +do + local doc + for _, c in Fx.cases do + if c.name == "rgb-layers" then + doc = decode(c.data) + end + end + local L = doc.layers + t:eq(#L, 8, "top level: bg, multiply, isolated, pass, base, clipped, masked, fill") + t:eq(L[2].blend, "multiply", "blend") + t:eq(math.floor(L[2].opacity * 255 + 0.5), 200, "opacity") + t:eq(L[3].name, "Isolated", "group name") + t:eq(L[3].blend, "normal", "isolated group blend") + t:eq(#L[3].children, 2, "group children") + t:eq(L[4].blend, "passThrough", "pass-through group") + t:eq(L[4].children[1].name, "Diff \u{e9}\u{65e5}", "unicode name (luni)") + t:eq(L[4].children[2].visible, false, "hidden layer") + t:eq(L[6].clip, true, "clipping layer") + t:check(L[7].mask and L[7].mask.image.format == "gray8" and L[7].mask.x == 8 and L[7].mask.y == 5, "mask") + t:eq(math.floor(L[8].fillOpacity * 255 + 0.5), 128, "fill opacity") + local only = decode(Fx.cases[1].data, { layers = false }) + t:check(only and #only.layers == 0 and only.meta.composite, "layers = false: merged image only") + + -- round trip: our PSD of the decoded document decodes to the same layers, and its merged image is our flatten + local out, eerr = Psd.encode(doc) + t:check(out, "encode: " .. tostring(eerr)) + local back = decode(out :: buffer) + t:check(back, "decode our PSD") + local a, b = leaves(doc.layers), leaves(back.layers) + t:eq(#b, #a, "round trip: leaves") + for i, l in a do + t:eq(b[i].name, l.name, "rt name") + t:check(buffer.tostring(b[i].image.pixels) == buffer.tostring(l.image.pixels), "rt pixels " .. l.name) + t:check(b[i].x == l.x and b[i].y == l.y, "rt position") + t:eq(b[i].blend, l.blend, "rt blend") + t:eq(b[i].visible, l.visible, "rt visible") + t:eq(b[i].clip, l.clip, "rt clip") + t:eq(b[i].opacity, l.opacity, "rt opacity") + end + t:eq(back.layers[4].blend, "passThrough", "rt pass-through group") + t:check(back.layers[7].mask and buffer.tostring(back.layers[7].mask.image.pixels) == buffer.tostring(L[7].mask.image.pixels), "rt mask") + local flat = LayerOps.flatten(doc) :: any + -- the merged image is stored matted with white (as Photoshop does): exact where opaque, rounding elsewhere + local p = psnr(back.meta.composite.pixels, buffer.tostring(flat.pixels)) + t:check(p > 45, string.format("rt merged = flatten (%.1f dB)", p)) + table.insert(samples, buffer.tostring(out :: buffer)) +end + +-- psd-tools reads our encoder's PSD (checked when the fixtures were made) +for _, c in Ours.checks do + t:check(c.ok, "psd-tools on our PSD: " .. c.label) +end +t:note("psd-tools agrees with our PSD on %d facts", #Ours.checks) + +-- errors +do + local _, e = decode("8BPS\0\1\0\0\0\0\0\0\0\3\0\0\0\10\0\0\0\10\0\8\0\3") + t:check(e and e.code == Err.TRUNCATED, "truncated after the header: " .. tostring(e)) + local _, e2 = decode("8BPS\0\1\0\0\0\0\0\0\0\3\0\0\0\10\0\0\0\10\0\7\0\3") + t:check(e2 and e2.code == Err.CORRUPT, "bad depth: " .. tostring(e2)) + local _, e3 = decode(Fx.cases[1].data, { maxPixels = 100 }) + t:check(e3 and e3.code == Err.LIMIT, "maxPixels") + t:eq(Psd.sniff(Bytes.reader(buffer.fromstring("8BPS\0\1"))), 1, "sniff") + t:eq(Psd.sniff(Bytes.reader(buffer.fromstring("8BPS\0\3"))), 0, "sniff version 3") + local _, e4 = Psd.encode({ width = 4, height = 4, layers = { { name = "x" } } } :: any) + t:check(e4 and e4.code == Err.ARG, "encode: layer without an image") +end + +t:fuzz("decode", function(b: buffer) + return Psd.decode(Bytes.reader(b)) +end, samples, { mutations = 30, keepHeader = 4 }) +t:done() diff --git a/tests/model/gltf.luau b/tests/model/gltf.luau new file mode 100644 index 0000000..b737320 --- /dev/null +++ b/tests/model/gltf.luau @@ -0,0 +1,351 @@ +-- model/gltf tests: Khronos glTF-Sample-Assets models (JSON with external / embedded buffers, GLB, sparse, interleaved, +-- quantized, morph targets, skins, animations, cameras, lights, texture transforms, material extensions), gltfpack +-- quantized variants and assimp's exporter output, against assimp (meshes, faces, bounds, animations, cameras, +-- lights) and trimesh (area, triangles); full-structure round trips through GLB, embedded .gltf and external files; +-- assimp / trimesh reading our output (gltf_xcheck); textures decoded lazily at the api layer; errors; the fuzz +-- no-throw pass. Fixtures: tools/fixtures/gltf.py. +local T = require("@tests/T") +local F = require("@formats") +local Gltf = require("@formats/model/gltf") +local MeshOps = require("@formats/ops/MeshOps") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Cases = require("@tests/gen/gltf_cases") +local Xcheck = require("@tests/gen/gltf_xcheck") + +local t = T.suite("gltf") + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return Gltf.decode(Bytes.reader(b), opts) +end + +t:eq(Gltf.name, "gltf", "name") +t:eq(Gltf.category, "model", "category") +t:check(Gltf.caps.decode and Gltf.caps.encode and table.find(Gltf.extensions, "glb"), "contract") + +local function near(a: number, b: number, eps: number): boolean + return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b)) +end + +local function triArea(prim: any): number + local pos = prim.attributes.POSITION + local ind = prim.indices + if not ind then + return 0 + end + local area = 0 + local function P(i: number, k: number): number + return buffer.readf32(pos.data, (i * 3 + k) * 4) + end + for tri = 0, ind.count // 3 - 1 do + local a, b, c = buffer.readu32(ind.data, tri * 12), buffer.readu32(ind.data, tri * 12 + 4), buffer.readu32(ind.data, tri * 12 + 8) + local e1 = { P(b, 0) - P(a, 0), P(b, 1) - P(a, 1), P(b, 2) - P(a, 2) } + local e2 = { P(c, 0) - P(a, 0), P(c, 1) - P(a, 1), P(c, 2) - P(a, 2) } + local x, y, z = e1[2] * e2[3] - e1[3] * e2[2], e1[3] * e2[1] - e1[1] * e2[3], e1[1] * e2[2] - e1[2] * e2[1] + area += math.sqrt(x * x + y * y + z * z) / 2 + end + return area +end + +-- assimp's counts: one mesh per primitive, faces after strips / fans / loops are unrolled +local function counts(scene: any): (number, number) + local prims, faces = 0, 0 + -- the meshes of the default scene (assimp imports that one only) + local meshes, seen = {}, {} + for _, pl in Types.Scene.flatten(scene) do + if not seen[pl.mesh] then + seen[pl.mesh] = true + table.insert(meshes, scene.meshes[pl.mesh]) + end + end + for _, m in meshes do + for _, p in m.primitives do + prims += 1 + local n = if p.indices then p.indices.count else p.attributes.POSITION.count + local mode = p.mode + faces += if mode == "triangles" then n // 3 + elseif mode == "triangle_strip" or mode == "triangle_fan" then math.max(n - 2, 0) + elseif mode == "lines" then n // 2 + elseif mode == "line_strip" then math.max(n - 1, 0) + elseif mode == "line_loop" then n + else n + end + end + return prims, faces +end + +-- every value of two scenes equal (buffers by content), meta skipped +local function same(a: any, b: any, path: string, seen: { [any]: boolean }?, skip: { [string]: boolean }?): (boolean, string?) + local s = seen or {} + local sk = skip or { meta = true, extras = true } + if type(a) == "buffer" and type(b) == "buffer" then + return buffer.tostring(a) == buffer.tostring(b), path + end + if type(a) ~= "table" or type(b) ~= "table" then + if type(a) == "number" and type(b) == "number" then + return near(a, b, 1e-6), path + end + return a == b, path + end + if s[a] then + return true, nil + end + s[a] = true + for k, v in a do + if not sk[k] then + local ok, where = same(v, b[k], path .. "." .. tostring(k), s, sk) + if not ok then + return false, where + end + end + end + for k, v in b do + if not sk[k] and a[k] == nil and v ~= nil then + return false, path .. "." .. tostring(k) .. " (extra)" + end + end + return true, nil +end + +local byName = {} +local checked = { assimp = 0, trimesh = 0, roundTrips = 0 } +for i, c in Cases do + byName[c.name] = c + local scene, err = decode(c.data, { files = c.files }) + t:check(scene, c.name .. ": decode: " .. tostring(err)) + local ref = if c.like then nil else c.assimp + local prims, faces = counts(scene) + if ref and not ref.failed then + t:eq(prims, ref.meshes, c.name .. ": meshes (assimp)") + t:eq(faces, ref.faces, c.name .. ": faces (assimp)") + if ref.animations then + t:eq(#scene.animations, ref.animations, c.name .. ": animations (assimp)") + end + if ref.cameras then + t:eq(#scene.cameras, ref.cameras, c.name .. ": cameras (assimp)") + end + if ref.lights then + t:eq(#scene.lights, ref.lights, c.name .. ": lights (assimp)") + end + checked.assimp += 1 + end + -- trimesh: the whole scene in world space (quantized variants: against the original model, within quantization) + local tm = if c.like then byName[c.like].trimesh else c.trimesh + local merged = MeshOps.merge(scene) + local onlyTriangles = true -- trimesh reads TRIANGLES primitives only (not strips / fans) + for _, m in scene.meshes do + for _, p in m.primitives do + if p.mode == "triangle_strip" or p.mode == "triangle_fan" then + onlyTriangles = false + end + end + end + -- trimesh ignores sparse accessors + local sparse = string.find(c.data, "\"sparse\"", 1, true) ~= nil + if tm and not tm.failed and tm.faces > 0 and onlyTriangles and not sparse then + local eps = if c.like then 2e-3 else 1e-5 + t:eq(merged.indices.count // 3, tm.faces, c.name .. ": triangles (trimesh)") + t:check(near(triArea(merged), tm.area, eps), string.format("%s: area %.6g, trimesh %.6g", c.name, triArea(merged), tm.area)) + local lo, hi = MeshOps.bounds(merged) + for k = 1, 3 do + t:check(near(lo[k], tm.bounds[k], eps * 10) and near(hi[k], tm.bounds[k + 3], eps * 10), c.name .. ": bounds (trimesh)") + end + checked.trimesh += 1 + end + -- round trips: GLB, embedded .gltf, external files + local glb, gerr = Gltf.encode(scene, { binary = true }) + t:check(glb, c.name .. ": encode glb: " .. tostring(gerr)) + local back = decode(glb) + t:check(back, c.name .. ": decode our glb") + local SKIP = { meta = true, extras = true, uri = true } -- embedded images lose their file names + local ok, where = same(scene, back, "scene", nil, SKIP) + t:check(ok, c.name .. ": glb round trip differs at " .. tostring(where)) + local text = Gltf.encode(scene) :: buffer + local back2 = decode(text) + local ok2, where2 = same(scene, back2, "scene", nil, SKIP) + t:check(ok2, c.name .. ": embedded .gltf round trip differs at " .. tostring(where2)) + local files = {} + local ext = Gltf.encode(scene, { external = true, files = files, name = "x.gltf" }) :: buffer + t:check(files["x.bin"] ~= nil or #scene.meshes == 0, c.name .. ": external .bin") + local back3 = decode(ext, { files = files }) + local ok3, where3 = same(scene, back3, "scene", nil, SKIP) + t:check(ok3, c.name .. ": external .gltf round trip differs at " .. tostring(where3)) + -- writing what we read back gives the same bytes + t:check(buffer.tostring(Gltf.encode(back, { binary = true }) :: buffer) == buffer.tostring(glb :: buffer), c.name .. ": writing is stable") + checked.roundTrips += 1 + c.index = i +end +t:note("%d files: %d against assimp, %d against trimesh, %d round trips", #Cases, checked.assimp, checked.trimesh, checked.roundTrips) + +-- the reference tools read our files like the originals +local nx = 0 +for _, x in Xcheck do + local c = Cases[x.case] + local a, ca = x.assimp, c.assimp + if not ca.failed then + t:check(not a.failed, x.name .. ": assimp reads our file") + t:eq(a.faces, ca.faces, x.name .. ": assimp faces of our file (" .. c.name .. ")") + t:eq(a.meshes, ca.meshes, x.name .. ": assimp meshes of our file") + for k = 1, 3 do + t:check(near(a.min[k], ca.min[k], 1e-4) and near(a.max[k], ca.max[k], 1e-4), x.name .. ": assimp bounds of our file (" .. c.name .. ")") + end + t:eq(a.animations, ca.animations, x.name .. ": assimp animations of our file") + t:eq(a.cameras, ca.cameras, x.name .. ": assimp cameras of our file") + t:eq(a.lights, ca.lights, x.name .. ": assimp lights of our file") + end + if c.trimesh and not c.trimesh.failed and c.trimesh.faces > 0 and c.name ~= "MeshPrimitiveModes/glTF" and not string.find(c.data, "\"sparse\"", 1, true) then + t:check(not x.trimesh.failed and near(x.trimesh.area, c.trimesh.area, 1e-5) and x.trimesh.faces == c.trimesh.faces, x.name .. ": trimesh area of our file (" .. c.name .. ")") + end + nx += 1 +end +t:note("%d of our files read back by assimp / trimesh like the originals", nx) + +-- details +do + local function load(name: string): any + local c = byName[name] + return decode(c.data, { files = c.files }) + end + local box = load("Box/glTF") + t:check(box.nodes[box.roots[1]].matrix ~= nil and box.meta.source.binary == false, "Box: a matrix node, JSON") + t:check(box.materials[1].metallic == 0 and near(box.materials[1].baseColor[1], 0.8, 1e-6), "Box: material") + local bt = load("BoxTextured/glTF") + local tex = bt.textures[1] + t:check(tex.uri == "CesiumLogoFlat.png" and tex.mime == "image/png" and buffer.tostring(tex.data) == byName["BoxTextured/glTF"].files["CesiumLogoFlat.png"], "BoxTextured: the image bytes from opts.files") + t:check(tex.sampler and tex.sampler.wrapS == "repeat" and tex.sampler.minFilter == "nearest_mipmap_linear", "sampler") + -- the api decodes textures lazily (PNG here) + local _, terrs = F.model.loadTextures(bt) + t:check(tex.image and tex.image.width == 256 and next(terrs) == nil, "F.model.loadTextures decodes the PNG") + local files = {} + local ext = Gltf.encode(bt, { external = true, files = files, name = "bt.gltf" }) :: buffer + t:check(files["CesiumLogoFlat.png"] ~= nil and string.find(buffer.tostring(ext), "\"uri\": \"CesiumLogoFlat.png\"", 1, true) ~= nil, "external images keep their file names") + local emb = load("BoxTextured/glTF-Embedded") + t:check(emb.textures[1].data and buffer.tostring(emb.textures[1].data) == buffer.tostring(tex.data), "embedded data: URI image = the external file") + local sparse = load("SimpleSparseAccessor/glTF-Embedded") + local pos = sparse.meshes[1].primitives[1].attributes.POSITION + local maxY = -math.huge + for v = 0, pos.count - 1 do + maxY = math.max(maxY, buffer.readf32(pos.data, v * 12 + 4)) + end + t:eq(maxY, 4, "sparse values substituted (the raised vertices, max = the accessor max)") + local cams = load("Cameras/glTF") + t:check(#cams.cameras == 2 and cams.cameras[1].type == "perspective" and cams.cameras[2].type == "orthographic", "cameras") + local skin = load("SimpleSkin/glTF") + t:check(#skin.skins == 1 and #skin.skins[1].joints == 2 and skin.skins[1].inverseBindMatrices.matrix and skin.skins[1].inverseBindMatrices.components == 16, "skin") + t:check(#skin.animations == 1 and skin.animations[1].channels[1].path == "rotation", "skin animation") + local morph = load("SimpleMorph/glTF") + t:check(#morph.meshes[1].primitives[1].targets == 2 and morph.meshes[1].weights[1] == 0.5, "morph targets, weights") + local q = load("AnimatedMorphCube/glTF-Quantized") + local qp = q.meshes[1].primitives[1] + t:check(qp.attributes.NORMAL.type == "snorm8" and qp.targets and qp.targets[1].POSITION.type == "i16", "quantized normals / target deltas") + local unlit = load("UnlitTest/glTF-Binary") + t:check(unlit.materials[1].extensions and unlit.materials[1].extensions.KHR_materials_unlit ~= nil, "KHR_materials_unlit") + local es = load("EmissiveStrengthTest/glTF-Binary") + local strength = 0 + for _, m in es.materials do + local e = m.extensions and m.extensions.KHR_materials_emissive_strength + if e then + strength = math.max(strength, e.emissiveStrength) + end + end + t:check(strength > 1, "KHR_materials_emissive_strength") + local cc = load("ClearCoatCarPaint/glTF-Binary") + local clear = cc.materials[1].extensions and cc.materials[1].extensions.KHR_materials_clearcoat + t:check(clear and clear.clearcoatFactor ~= nil, "KHR_materials_clearcoat") + local tt = load("TextureTransformTest/glTF") + local nt = 0 + for _, m in tt.materials do + if m.baseColorTexture and m.baseColorTexture.transform then + nt += 1 + end + end + t:check(nt >= 5, "KHR_texture_transform on " .. nt .. " materials") + local lights = load("PointLightIntensityTest/glTF-Binary") + t:check(#lights.lights > 0 and lights.lights[1].type == "point", "KHR_lights_punctual") + local ms = load("MultipleScenes/glTF") + t:check(#ms.meta.gltf.scenes == 2, "multiple scenes kept") + local modes = load("MeshPrimitiveModes/glTF") + local seen = {} + for _, m in modes.meshes do + for _, p in m.primitives do + seen[p.mode] = true + end + end + t:check(seen.points and seen.lines and seen.line_loop and seen.line_strip and seen.triangle_strip and seen.triangle_fan, "every primitive mode") + local inter = load("BoxInterleaved/glTF-Binary") + t:check(inter.meshes[1].primitives[1].attributes.NORMAL.count == 24, "interleaved (byteStride) attributes") + -- quantized output declares KHR_mesh_quantization + local qglb = Gltf.encode(q, { binary = true }) :: buffer + t:check(string.find(buffer.tostring(qglb), "KHR_mesh_quantization", 1, true) ~= nil, "KHR_mesh_quantization written") + -- a Scene made by hand (an OBJ-like mesh with u8 colours and polygons) writes and reads back + local s = Types.Scene.new() + local p = Types.Scene.accessor(nil, "f32", 3, 4) + for v, xyz in { { 0, 0, 0 }, { 1, 0, 0 }, { 1, 1, 0 }, { 0, 1, 0 } } do + for k = 1, 3 do + buffer.writef32(p.data, ((v - 1) * 3 + k - 1) * 4, xyz[k]) + end + end + local col = Types.Scene.accessor(nil, "unorm8", 3, 4) + local faces = Types.Scene.accessor(nil, "u32", 1, 1) + buffer.writeu32(faces.data, 0, 4) + local ind = Types.Scene.accessor(nil, "u32", 1, 4) + for k = 0, 3 do + buffer.writeu32(ind.data, k * 4, k) + end + local s2 = Types.Scene.fromPrimitive({ attributes = { POSITION = p, COLOR_0 = col }, indices = ind, faces = faces, mode = "polygons" }, "quad") + local out = Gltf.encode(s2, { binary = true }) :: buffer + local back = decode(out) + t:check(back and back.meshes[1].primitives[1].indices.count == 6 and back.meshes[1].primitives[1].attributes.COLOR_0.type == "unorm8", "polygons fan-triangulated, unorm8 VEC3 colours (padded stride)") + -- through the api: the destination's extension picks GLB + local viaApi = F.save(s2, nil, { format = "glb" }) + t:check(viaApi and buffer.readstring(viaApi, 0, 4) == "glTF", "F.save format glb") + local viaApi2 = F.save(s2, nil, { format = "gltf" }) + t:check(viaApi2 and buffer.readstring(viaApi2, 0, 1) == "{", "F.save format gltf") + local loaded = F.load(viaApi) + t:check(loaded and loaded.kind == "scene" and loaded.meta.source.format == "gltf", "F.load detects GLB") +end + +-- errors +do + local _, e = decode("{ not json") + t:check(e and (e.code == Err.CORRUPT or e.code == Err.TRUNCATED), "bad JSON: " .. tostring(e)) + local _, e2 = decode('{"asset": {"version": "1.0"}}') + t:check(e2 and e2.code == Err.UNSUPPORTED, "glTF 1: " .. tostring(e2)) + local _, e3 = decode('{"asset": {"version": "2.0"}, "extensionsRequired": ["KHR_draco_mesh_compression"]}') + t:check(e3 and e3.code == Err.UNSUPPORTED, "Draco: " .. tostring(e3)) + local c = byName["Box/glTF"] + local _, e4 = decode(c.data) + t:check(e4 and e4.code == Err.IO, "missing .bin: " .. tostring(e4)) + local _, e5 = decode('{"asset": {"version": "2.0"}, "buffers": [{"byteLength": 4, "uri": "data:application/octet-stream;base64,AAAAAA=="}], "bufferViews": [{"buffer": 0, "byteLength": 4}], "accessors": [{"bufferView": 0, "componentType": 5126, "count": 2, "type": "SCALAR"}]}') + t:check(e5 and e5.code == Err.CORRUPT, "accessor past its view: " .. tostring(e5)) + local glb = byName["Box/glTF-Binary"].data + local _, e6 = decode(string.sub(glb, 1, 100)) + t:check(e6 and e6.code == Err.TRUNCATED, "truncated GLB: " .. tostring(e6)) + local _, e7 = Gltf.encode({} :: any) + t:check(e7 and e7.code == Err.ARG, "encode junk") + local bad = Types.Scene.fromPrimitive({ attributes = { POSITION = Types.Scene.accessor(buffer.create(4), "f32", 3, 10) }, mode = "triangles" }) + local _, e8 = Gltf.encode(bad) + t:check(e8 and e8.code == Err.ARG, "encode a short accessor: " .. tostring(e8)) +end + +-- fuzz +do + local samples = {} + for _, c in Cases do + if #c.data < 40000 then + table.insert(samples, c.data) + end + end + t:fuzz("decode", function(b: buffer) + local s = Gltf.decode(Bytes.reader(b)) + if s then + Gltf.encode(s, { binary = true }) + MeshOps.merge(s) + end + return s + end, samples, { mutations = 20 }) +end + +t:done() diff --git a/tests/model/obj.luau b/tests/model/obj.luau new file mode 100644 index 0000000..e65810e --- /dev/null +++ b/tests/model/obj.luau @@ -0,0 +1,235 @@ +-- model/obj tests: OBJ / MTL files (materials and texture maps, objects and groups, n-gons, negative indices, vertex +-- colours, continuations, lines and points, a concave polygon, assimp's exporter output) against assimp (meshes, +-- vertices, faces, bounds, materials) and trimesh (area, triangles); MTL mapping; ear clipping (MeshOps) against the +-- exact polygon area; round trips through the writer, and assimp / trimesh reading our output (obj_xcheck); errors; +-- the fuzz no-throw pass. Fixtures: tools/fixtures/obj.py. +local T = require("@tests/T") +local Obj = require("@formats/model/obj") +local MeshOps = require("@formats/ops/MeshOps") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Cases = require("@tests/gen/obj_cases") +local Xcheck = require("@tests/gen/obj_xcheck") + +local t = T.suite("obj") + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return Obj.decode(Bytes.reader(b), opts) +end + +t:eq(Obj.name, "obj", "name") +t:eq(Obj.category, "model", "category") +t:check(Obj.caps.decode and Obj.caps.encode, "caps") + +local function near(a: number, b: number, eps: number): boolean + return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b)) +end + +local function triArea(prim: any): number + local pos = prim.attributes.POSITION + local ind = prim.indices + local area = 0 + local function P(i: number, k: number): number + return buffer.readf32(pos.data, (i * 3 + k) * 4) + end + for tri = 0, ind.count // 3 - 1 do + local a, b, c = buffer.readu32(ind.data, tri * 12), buffer.readu32(ind.data, tri * 12 + 4), buffer.readu32(ind.data, tri * 12 + 8) + local e1 = { P(b, 0) - P(a, 0), P(b, 1) - P(a, 1), P(b, 2) - P(a, 2) } + local e2 = { P(c, 0) - P(a, 0), P(c, 1) - P(a, 1), P(c, 2) - P(a, 2) } + local x, y, z = e1[2] * e2[3] - e1[3] * e2[2], e1[3] * e2[1] - e1[1] * e2[3], e1[1] * e2[2] - e1[2] * e2[1] + area += math.sqrt(x * x + y * y + z * z) / 2 + end + return area +end + +-- the counts assimp reports: meshes (= our primitives), vertices, faces (triangles + line segments + points) +local function counts(scene: any): (number, number, number) + local prims, verts, faces = 0, 0, 0 + for _, m in scene.meshes do + for _, p in m.primitives do + prims += 1 + verts += p.attributes.POSITION.count + local n = if p.indices then p.indices.count else p.attributes.POSITION.count + faces += if p.mode == "triangles" then n // 3 elseif p.mode == "lines" then n // 2 else n + end + end + return prims, verts, faces +end + +local function checkAgainst(scene: any, assimp: any, trimesh: any?, label: string, vertices: boolean, fanArea: number) + local prims, verts, faces = counts(scene) + t:eq(prims, assimp.meshes, label .. ": meshes (assimp)") + if vertices then + t:eq(verts, assimp.vertices, label .. ": vertices (assimp)") + end + t:eq(faces, assimp.faces, label .. ": faces (assimp)") + local lo, hi = MeshOps.bounds(scene) + t:check(lo and hi, label .. ": bounds") + for k = 1, 3 do + t:check(near(lo[k], assimp.min[k], 1e-5) and near(hi[k], assimp.max[k], 1e-5), label .. ": bounds = assimp's") + end + local all = MeshOps.merge(scene) + t:check(near(triArea(all), fanArea, 1e-5), string.format("%s: area %g, exact fan area %g", label, triArea(all), fanArea)) + if trimesh then + local merged = MeshOps.merge(scene) + t:eq(merged.indices.count // 3, trimesh.faces, label .. ": triangles (trimesh)") + t:check(near(triArea(merged), trimesh.area, 1e-5), string.format("%s: area %g, trimesh %g", label, triArea(merged), trimesh.area)) + end +end + +local byName = {} +for _, c in Cases do + byName[c.name] = c + local scene, err = decode(c.data, { files = c.files }) + t:check(scene, c.name .. ": decode: " .. tostring(err)) + checkAgainst(scene, c.assimp, c.trimesh, c.name, not c.noVertexCount, c.fanArea) + if #scene.materials > 0 then + t:eq(#scene.materials, c.assimp.materials, c.name .. ": materials (assimp)") + end + -- round trip through our writer + local files = {} + local out, eerr = Obj.encode(scene, { name = "rt.obj", files = files }) + t:check(out, c.name .. ": encode: " .. tostring(eerr)) + local back, berr = decode(out, { files = files }) + t:check(back, c.name .. ": decode our OBJ: " .. tostring(berr)) + local p1, v1, f1 = counts(scene) + local p2, v2, f2 = counts(back) + t:check(p1 == p2 and v1 == v2 and f1 == f2, c.name .. ": round trip counts") + local m1, m2 = MeshOps.merge(scene), MeshOps.merge(back) + for _, attr in { "POSITION", "TEXCOORD_0", "NORMAL", "COLOR_0" } do + local a, b = m1.attributes[attr], m2.attributes[attr] + t:check((a == nil) == (b == nil), c.name .. ": round trip has " .. attr) + if a and b then + t:check(buffer.tostring(a.data) == buffer.tostring(b.data), c.name .. ": round trip " .. attr .. " exact") + end + end + if m1.indices then + t:check(buffer.tostring(m1.indices.data) == buffer.tostring(m2.indices.data), c.name .. ": round trip indices") + end + t:eq(#back.materials, #scene.materials, c.name .. ": round trip materials") +end + +-- the reference tools read our output like the original +for _, x in Xcheck do + local orig = byName[string.sub(x.name, 4)] + t:check(orig ~= nil, x.name .. ": a case") + t:eq(x.assimp.faces, orig.assimp.faces, x.name .. ": assimp faces of our file") + if not orig.noVertexCount then + t:eq(x.assimp.vertices, orig.assimp.vertices, x.name .. ": assimp vertices of our file") + end + t:eq(x.assimp.materials, orig.assimp.materials, x.name .. ": assimp materials of our file") + for k = 1, 3 do + t:check(near(x.assimp.min[k], orig.assimp.min[k], 1e-5) and near(x.assimp.max[k], orig.assimp.max[k], 1e-5), x.name .. ": assimp bounds of our file") + end + if orig.trimesh then + t:check(near(x.trimesh.area, orig.trimesh.area, 1e-5) and x.trimesh.faces == orig.trimesh.faces, x.name .. ": trimesh area of our file") + end +end +t:note("%d files match assimp / trimesh; %d of our files read back by assimp / trimesh", #Cases, #Xcheck) + +-- the cube in detail: nodes, materials, textures +do + local c = byName["cube.obj"] + local s = decode(c.data, { files = c.files }) + t:eq(#s.roots, 1, "one object") + local root = s.nodes[s.roots[1]] + t:check(root.name == "Cube" and #root.children == 2 and root.mesh == nil, "the object holds two groups") + t:check(s.nodes[root.children[1]].name == "top" and s.nodes[root.children[2]].name == "bottom", "group names") + local red, blue = s.materials[1], s.materials[2] + t:check(red.name == "red" and red.baseColor[1] == 1 and red.baseColor[2] == 0 and red.metallic == 0, "red: Kd, not metallic") + t:check(near(red.roughness, math.sqrt(2 / 52), 1e-9), "red: roughness from Ns") + local tex = s.textures[red.baseColorTexture.texture] + t:check(tex.uri == "textures/tex.png" and tex.mime == "image/png" and tex.data and buffer.len(tex.data) > 30, "map_Kd: uri, mime, bytes through opts.files") + t:check(red.baseColorTexture.transform.scale[1] == 2 and red.baseColorTexture.transform.offset[1] == 0.5, "map_Kd -s / -o") + t:check(red.normalTexture and red.normalTexture.scale == 0.5, "map_Bump -bm") + t:check(red.extras.obj.values.Ns[1] == 50 and red.extras.obj.values.illum[1] == 2, "Phong values in extras") + t:check(blue.baseColor[4] == 0.5 and blue.alphaMode == "blend" and blue.roughness == 0.25 and blue.metallic == 1 and blue.emissive[3] == 0.3, "blue: d, Pr, Pm, Ke") + t:check(s.nodes[root.children[1]].extras.obj.smoothing == "1", "smoothing group kept") + -- the uv flip + local top = s.meshes[s.nodes[root.children[1]].mesh].primitives[1] + t:check(top.attributes.TEXCOORD_0 ~= nil and buffer.readf32(top.attributes.TEXCOORD_0.data, 4) == 1, "vt 0 0 -> (0, 1) (top-left origin)") + local s2 = decode(c.data, { files = c.files, flipV = false }) + local top2 = s2.meshes[s2.nodes[s2.nodes[s2.roots[1]].children[1]].mesh].primitives[1] + t:check(buffer.readf32(top2.attributes.TEXCOORD_0.data, 4) == 0, "flipV = false") + -- without the MTL: named default materials, the library listed as missing + local s3 = decode(c.data) + t:check(#s3.materials == 2 and s3.meta.source.missingMtl[1] == "cube.mtl", "missing mtllib") + -- through opts.mtl / resolve + local s4 = decode(c.data, { mtl = c.files["cube.mtl"] }) + t:check(s4.materials[1].baseColor[1] == 1 and s4.textures[1].data == nil, "opts.mtl (texture bytes not found)") + local asked = {} + local s5 = decode(c.data, { resolve = function(uri: string): any + table.insert(asked, uri) + return c.files[uri] + end }) + t:check(s5.materials[2].baseColor[4] == 0.5 and table.find(asked, "cube.mtl") and table.find(asked, "textures/tex.png"), "opts.resolve") + -- the MTL written back keeps the maps and their options + local files = {} + Obj.encode(s, { name = "x.obj", files = files }) + local mtl = files["x.mtl"] + t:check(type(mtl) == "string" and string.find(mtl, "map_Kd -o 0.5 0 -s 2 2 textures/tex.png", 1, true) ~= nil, "MTL map_Kd written: " .. tostring(mtl)) + t:check(string.find(mtl, "newmtl blue", 1, true) and string.find(mtl, "\nd 0.5", 1, true), "MTL blue written") + t:check(files["textures/tex.png"] ~= nil, "texture bytes written to opts.files") +end + +-- polygons: triangulate = false keeps them; ear clipping gets the concave area right, the fan does not +do + local c = byName["concave.obj"] + local s = decode(c.data, { triangulate = false }) + local p = s.meshes[1].primitives[1] + t:check(p.mode == "polygons" and p.faces.count == 2 and p.indices.count == 14, "polygons kept") + local tri = MeshOps.triangulate(p) :: any + t:check(near(triArea(tri), c.polygonArea, 1e-9), "ear clipping area " .. triArea(tri) .. " = " .. c.polygonArea) + local fan = MeshOps.triangulate(p, { method = "fan" }) :: any + t:check(near(triArea(fan), c.trimesh.area, 1e-9), "fan area = trimesh's (fan) area") + -- n-gons written as n-gons + local out = Obj.encode(s) :: buffer + t:check(string.find(buffer.tostring(out), "\nf 7 8 9 10 11 12 13 14", 1, true) ~= nil, "an octagon written as one face") + local back = decode(out, { triangulate = false }) + t:eq(back.meshes[1].primitives[1].faces.count, 2, "polygons round trip") +end + +-- lines and points +do + local s = decode(byName["wire.obj"].data) + local modes = {} + for _, p in s.meshes[1].primitives do + modes[p.mode] = p + end + t:check(modes.lines and modes.lines.indices.count == 8 and modes.points and modes.triangles, "l (polyline -> 4 segments), p, f") +end + +-- errors +do + local _, e = decode("v 0 0 0\nf 1 2 3\n") + t:check(e and e.code == Err.CORRUPT, "index out of range: " .. tostring(e)) + local _, e2 = decode("v 0 0\n") + t:check(e2 and e2.code == Err.CORRUPT, "short vertex: " .. tostring(e2)) + local _, e3 = decode(byName["random.obj"].data, { maxVertices = 10 }) + t:check(e3 and e3.code == Err.LIMIT, "maxVertices: " .. tostring(e3)) + local _, e4 = Obj.encode({} :: any) + t:check(e4 and e4.code == Err.ARG, "encode junk") + t:check(Obj.sniff(Bytes.reader(buffer.fromstring(byName["cube.obj"].data))) > 0, "sniff an OBJ") + t:eq(Obj.sniff(Bytes.reader(buffer.fromstring("\137PNG\r\n\26\n"))), 0, "sniff a PNG") + local empty = decode("# nothing\n") + t:check(empty and #empty.nodes == 0, "an empty file is an empty scene") +end + +-- fuzz +do + local samples = {} + for _, c in Cases do + table.insert(samples, c.data) + end + t:fuzz("decode", function(b: buffer) + local s = Obj.decode(Bytes.reader(b), { triangulate = false }) + if s then + Obj.encode(s) + MeshOps.merge(s) + end + return s + end, samples, { mutations = 40 }) +end + +t:done() diff --git a/tests/model/off.luau b/tests/model/off.luau new file mode 100644 index 0000000..5a72e5b --- /dev/null +++ b/tests/model/off.luau @@ -0,0 +1,214 @@ +-- model/off tests: OFF files written by trimesh and by the generator (COFF integer / float colours, RGB / RGBA, NOFF, +-- STOFF, STCNOFF, face colours, colormap indices, comments, counts on the header line, CRLF, tabs, n-gons, a point +-- cloud) against the values they were written from (positions cross-checked with trimesh); our encoder's output read +-- back by trimesh, assimp and the generator's reader (verdicts from the fixture step); round trips (polygons, +-- triangles, face colours, scenes); the contract, error codes and the fuzz no-throw pass. Fixtures: +-- tools/fixtures/off.py. +local T = require("@tests/T") +local Off = require("@formats/model/off") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Fx = require("@tests/gen/off") +local Scenes = require("@tests/gen/off_scenes") + +local t = T.suite("off") + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return Off.decode(Bytes.reader(b), opts) +end + +local function same(a: any, b: any): boolean + if a == nil or b == nil then + return a == b + end + return a.type == b.type and a.components == b.components and a.count == b.count and buffer.tostring(a.data) == buffer.tostring(b.data) +end + +-- 1. the contract +t:eq(Off.name, "off", "name") +t:eq(Off.category, "model", "category") +t:check(table.find(Off.extensions, "off") ~= nil, "extensions") +t:check(Off.caps.decode and Off.caps.encode, "caps") + +-- 2. every fixture against the values it was written from; 3. round trips +for _, c in Fx.cases do + local label = c.name + local scene, err = decode(c.data) + t:check(scene, label .. ": " .. tostring(err)) + local src = scene.meta.source + t:check(src.format == "off" and src.keyword == c.keyword and src.vertices == c.vertices and src.faces == c.faces, label .. ": meta.source") + t:eq(src.colormap, c.colormap, label .. ": colormap flag") + local p = scene.meshes[1].primitives[1] + local A = p.attributes + t:eq(Crc32.of(A.POSITION.data), c.pos_crc, label .. ": POSITION crc") + t:check((A.NORMAL and Crc32.of(A.NORMAL.data)) == c.nrm_crc, label .. ": NORMAL") + t:check((A.TEXCOORD_0 and Crc32.of(A.TEXCOORD_0.data)) == c.tex_crc, label .. ": TEXCOORD_0") + if c.color then + t:check(A.COLOR_0 and A.COLOR_0.type == c.color.type and A.COLOR_0.components == 4, label .. ": COLOR_0 type") + t:eq(Crc32.of(A.COLOR_0.data), c.color.crc, label .. ": COLOR_0 crc") + else + t:check(A.COLOR_0 == nil, label .. ": no COLOR_0") + end + local ex = p.extras or {} + if c.faceColors then + t:check(ex.faceColors and ex.faceColors.type == c.faceColors.type and ex.faceColors.count == c.faces, label .. ": faceColors type") + t:eq(Crc32.of(ex.faceColors.data), c.faceColors.crc, label .. ": faceColors crc") + else + t:check(ex.faceColors == nil, label .. ": no faceColors") + end + if c.faces == 0 then + t:check(p.mode == "points" and p.indices == nil, label .. ": a point cloud") + else + t:eq(p.mode, "triangles", label .. ": mode") + t:eq(p.indices.count, c.tris * 3, label .. ": index count") + t:eq(Crc32.of(p.indices.data), if c.allTri then c.corners_crc else c.tri_crc, label .. ": indices crc") + if c.faceColors and not c.allTri then + t:eq(Crc32.of(ex.faceOfTriangle.data), c.fot_crc, label .. ": faceOfTriangle") + end + end + t:eq(Off.sniff(Bytes.reader(buffer.fromstring(c.data))), 0.9, label .. ": sniff") + -- polygons kept + local poly = decode(c.data, { triangulate = false }) + local pp = poly.meshes[1].primitives[1] + if c.faces > 0 and not c.allTri then + t:eq(pp.mode, "polygons", label .. ": polygons") + t:eq(Crc32.of(pp.indices.data), c.corners_crc, label .. ": corners") + t:eq(Crc32.of(pp.faces.data), c.sizes_crc, label .. ": sizes") + end + -- round trips: polygons in, polygons out; triangles in, triangles out (face colours through faceOfTriangle) + for _, s in { poly, scene } do + local out, eerr = Off.encode(s) + t:check(out, label .. ": encode: " .. tostring(eerr)) + local back, berr = decode(out, { triangulate = false }) + t:check(back, label .. ": decode our output: " .. tostring(berr)) + local bp, sp = back.meshes[1].primitives[1], s.meshes[1].primitives[1] + for name, a in sp.attributes do + t:check(same(bp.attributes[name], a), label .. ": " .. name .. " round trip") + end + t:eq(bp.mode, sp.mode, label .. ": mode round trip") + t:check(same(bp.indices, sp.indices) and same(bp.faces, sp.faces), label .. ": faces round trip") + local sfc = sp.extras and sp.extras.faceColors + local bfc = bp.extras and bp.extras.faceColors + if sfc and sp.extras.faceOfTriangle then + t:eq(bfc.count, sp.extras.faceOfTriangle.count, label .. ": a colour per triangle") + else + t:check(same(bfc, sfc), label .. ": faceColors round trip") + end + end +end +t:note("%d files match their source values and round-trip", #Fx.cases) + +for _, v in Fx.ours do + t:check(v.ok, "trimesh / assimp read our " .. v.name .. ": " .. v.detail) +end +t:note("%d encodings read back by trimesh, assimp and the generator", #Fx.ours) + +-- the encoder scenes: decode(encode()) gives the scene back (identity transforms) +local function build(spec: any): Types.Scene + local scene = Types.Scene.new() + for i, m in spec.meshes do + local prims = {} + for _, p in m.prims do + local attrs = {} + for name, a in p.attrs do + attrs[name] = Types.Scene.accessor(buffer.fromstring(a[3]), a[1], a[2], p.count) + end + local prim: any = { attributes = attrs, mode = p.mode } + if p.indices then + prim.indices = Types.Scene.accessor(buffer.fromstring(p.indices), "u32", 1, #p.indices // 4) + end + if p.faces then + prim.faces = Types.Scene.accessor(buffer.fromstring(p.faces), "u32", 1, #p.faces // 4) + end + if p.faceColors then + prim.extras = { faceColors = Types.Scene.accessor(buffer.fromstring(p.faceColors), "unorm8", 4, #p.faceColors // 4) } + end + table.insert(prims, prim) + end + scene.meshes[i] = { primitives = prims } + end + for i, n in spec.nodes do + scene.nodes[i] = { mesh = n.mesh, children = n.children or {}, translation = n.translation, rotation = n.rotation, scale = n.scale, matrix = n.matrix } + end + scene.roots = spec.roots + return scene +end +for _, spec in Scenes do + local scene = build(spec) + local sp = scene.meshes[1].primitives[1] + local out = Off.encode(scene) :: buffer + local back = decode(out, { triangulate = false }) + local bp = back.meshes[1].primitives[1] + if spec.name ~= "polys" then + for name, a in sp.attributes do + t:check(same(bp.attributes[name], a), spec.name .. ": " .. name .. " round trip") + end + end + t:eq(bp.mode, sp.mode, spec.name .. ": mode") + t:check(same(bp.indices, sp.indices) and same(bp.faces, sp.faces), spec.name .. ": faces") + t:check(same(bp.extras and bp.extras.faceColors, sp.extras and sp.extras.faceColors), spec.name .. ": face colours") +end +do + local scene = build(Scenes[1]) + local plain = buffer.tostring(Off.encode(scene, { colors = false, normals = false, texcoords = false }) :: buffer) + t:eq(string.sub(plain, 1, 4), "OFF\n", "plain OFF") + t:eq(string.sub(buffer.tostring(Off.encode(scene, { colors = false }) :: buffer), 1, 6), "STNOFF", "no colours") + local cm = buffer.tostring(Off.encode(scene, { comment = "made\nhere" }) :: buffer) + t:check(string.find(cm, "STCNOFF\n# made here\n", 1, true) ~= nil, "comment option") +end + +-- 4. error codes +do + local function code(s: string, opts: any?): string? + local _, e = decode(s, opts) + return e and e.code + end + t:check(decode("OFF\n3 1 0\n0 0 0\n1 0 0\n0 1 0\n3 0 1 2\n"), "a minimal file") + t:eq(code("PFF\n3 1 0\n"), Err.CORRUPT, "bad keyword") + t:eq(code("4OFF\n1 0 0\n0 0 0 1\n"), Err.UNSUPPORTED, "4OFF") + t:eq(code("nOFF\n4\n1 0 0\n0 0 0 0\n"), Err.UNSUPPORTED, "nOFF") + t:eq(code("OFF BINARY\n"), Err.UNSUPPORTED, "binary OFF") + t:eq(code("OFF\n"), Err.TRUNCATED, "no counts") + t:eq(code("# nothing\n\n"), Err.TRUNCATED, "empty") + t:eq(code("OFF\nx 1 0\n"), Err.CORRUPT, "bad counts") + t:eq(code("OFF\n3 1 0\n0 0 0\n1 0 0\n0 1 0\n"), Err.TRUNCATED, "face missing") + t:eq(code("OFF\n3 1 0\n0 0 0\n1 0 0\n0 1 0\n3 0 1 3\n"), Err.CORRUPT, "index out of range") + t:eq(code("OFF\n3 1 0\n0 0 0\n1 0 0\n0 1 0\n4 0 1 2\n"), Err.CORRUPT, "short face") + t:eq(code("OFF\n3 1 0\n0 0 0\n1 q 0\n0 1 0\n3 0 1 2\n"), Err.CORRUPT, "bad number") + t:eq(code("OFF\n3 1 0\n0 0 0\n1 0\n0 1 0\n3 0 1 2\n"), Err.CORRUPT, "short vertex") + t:eq(code("COFF\n3 1 0\n0 0 0 1 2\n1 0 0 1 2\n0 1 0 1 2\n3 0 1 2\n"), Err.CORRUPT, "two colour values") + t:eq(code("COFF\n3 1 0\n0 0 0 300 2 3\n1 0 0 1 2 3\n0 1 0 1 2 3\n3 0 1 2\n"), Err.CORRUPT, "colour over 255") + t:eq(code("OFF\n3 1 0\n0 0 0\n1 0 0\n0 1 0\n3 0 1 2\n", { maxVertices = 2 }), Err.LIMIT, "maxVertices") + t:eq(code("OFF\n3 1 0\n0 0 0\n1 0 0\n0 1 0\n3 0 1 2\n", { maxFaces = 0 }), Err.LIMIT, "maxFaces") + t:eq(code("OFF\n10000000 0 0\n1 2 3\n"), Err.TRUNCATED, "counts over the data") + local _, a1 = Off.encode({} :: any) + t:check(a1 and a1.code == Err.ARG, "encode a non-scene: " .. tostring(a1)) + local nan = Types.Scene.fromPrimitive({ attributes = { POSITION = Types.Scene.accessor(nil, "f32", 3, 1) }, mode = "points" }) + buffer.writef32(nan.meshes[1].primitives[1].attributes.POSITION.data, 0, math.huge) + local _, a2 = Off.encode(nan) + t:check(a2 and a2.code == Err.ARG, "infinite coordinate: " .. tostring(a2)) + t:eq(Off.sniff(Bytes.reader(buffer.fromstring("solid x\n"))), 0, "sniff an STL") +end + +-- 5. fuzz +do + local samples = {} + for _, c in Fx.cases do + table.insert(samples, c.data) + end + t:fuzz("decode", function(b: buffer) + return Off.decode(Bytes.reader(b)) + end, samples, { mutations = 20 }) + t:fuzz("decode polygons + re-encode", function(b: buffer) + local s = Off.decode(Bytes.reader(b), { triangulate = false }) + if s then + return Off.encode(s) + end + return nil + end, samples, { mutations = 6, garbage = 20 }) +end + +t:done() diff --git a/tests/model/ply.luau b/tests/model/ply.luau new file mode 100644 index 0000000..961f453 --- /dev/null +++ b/tests/model/ply.luau @@ -0,0 +1,379 @@ +-- model/ply tests: files written by plyfile (ascii / binary LE / BE, every property type and spelling, odd orders, +-- n-gons up to 300 vertices, face properties and lists, extra elements, comments, point clouds) and by assimp, against +-- plyfile's reading mapped to the Scene conventions (CRC-32 of every attribute, the indices triangulated or as +-- polygons, face data, raw elements); our encoder's output read back by plyfile and assimp (verdicts from the fixture +-- step); round trips in every encoding (fixtures and generated scenes, polygons and points); the contract, error +-- codes, the fuzz no-throw pass and a binary decode throughput note. Fixtures: tools/fixtures/ply.py. +local T = require("@tests/T") +local Ply = require("@formats/model/ply") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Fx = require("@tests/gen/ply") +local Scenes = require("@tests/gen/ply_scenes") + +local t = T.suite("ply") + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return Ply.decode(Bytes.reader(b), opts) +end + +local ENCODINGS = { "ascii", "binary_little_endian", "binary_big_endian" } + +-- 1. the contract +t:eq(Ply.name, "ply", "name") +t:eq(Ply.category, "model", "category") +t:check(table.find(Ply.extensions, "ply") ~= nil, "extensions") +t:check(Ply.caps.decode and Ply.caps.encode, "caps") + +-- a decoded scene against a reference case (triangulated) +local function verify(scene: any, c: any, label: string) + t:check(scene.kind == "scene" and #scene.meshes == 1 and #scene.meshes[1].primitives == 1, label .. ": one primitive") + local p = scene.meshes[1].primitives[1] + local n = 0 + for name, want in c.attrs do + local a = p.attributes[name] + t:check(a ~= nil, label .. ": attribute " .. name) + t:eq(a.type, want.type, label .. ": " .. name .. " type") + t:eq(a.components, want.components, label .. ": " .. name .. " components") + t:eq(a.count, c.vertices, label .. ": " .. name .. " count") + t:eq(Crc32.of(a.data), want.crc, label .. ": " .. name .. " crc") + n += 1 + end + local m = 0 + for _ in p.attributes do + m += 1 + end + t:eq(m, n, label .. ": no other attributes") + if c.faces > 0 then + t:eq(p.mode, "triangles", label .. ": mode") + t:eq(Crc32.of(p.indices.data), if c.allTri then c.corners_crc else c.tri_crc, label .. ": indices crc") + t:eq(p.indices.count, c.tris * 3, label .. ": index count") + local fa = c.faceAttributes + local ex = p.extras or {} + if next(fa) ~= nil and not c.allTri then + t:eq(Crc32.of(ex.faceOfTriangle.data), c.fot_crc, label .. ": faceOfTriangle") + else + t:check(ex.faceOfTriangle == nil, label .. ": no faceOfTriangle") + end + for name, want in fa do + if want.list then + local fl = ex.faceLists[name] + t:eq(Crc32.of(fl.sizes.data), want.sizes_crc, label .. ": face list " .. name .. " sizes") + t:eq(Crc32.of(fl.items.data), want.items_crc, label .. ": face list " .. name .. " items") + else + local a = ex.faceAttributes[name] + t:eq(a.type, want.type, label .. ": face attribute " .. name .. " type") + t:eq(Crc32.of(a.data), want.crc, label .. ": face attribute " .. name) + end + end + else + t:eq(p.mode, "points", label .. ": a point cloud") + t:check(p.indices == nil, label .. ": no indices") + end + local meta = scene.meta.ply + t:eq(#meta.comments, #c.comments, label .. ": comment count") + for i, s in c.comments do + t:eq(meta.comments[i], s, label .. ": comment") + end + t:eq(#meta.objInfo, #c.objInfo, label .. ": obj_info count") + for i, s in c.objInfo do + t:eq(meta.objInfo[i], s, label .. ": obj_info") + end + t:eq(table.concat(meta.order, ","), table.concat(c.order, ","), label .. ": element order") + t:eq(#meta.elements, #c.elements, label .. ": raw elements") + for i, want in c.elements do + local el = meta.elements[i] + t:eq(el.name, want.name, label .. ": element name") + t:eq(el.count, want.count, label .. ": element count") + for k, wp in want.props do + local pr = el.properties[k] + t:eq(pr.name, wp.name, label .. ": element property") + if wp.list then + t:eq(Crc32.of(pr.sizes), wp.sizes_crc, label .. ": " .. el.name .. "." .. pr.name .. " sizes") + t:eq(Crc32.of(pr.values), wp.values_crc, label .. ": " .. el.name .. "." .. pr.name .. " items") + else + t:eq(Crc32.of(pr.values), wp.crc, label .. ": " .. el.name .. "." .. pr.name) + end + end + end +end + +-- 2. every fixture against plyfile; 3. round trips of every fixture in every encoding +for _, c in Fx.cases do + local label = c.name + local scene, err = decode(c.data) + t:check(scene, label .. ": " .. tostring(err)) + t:eq(scene.meta.source.format, "ply", label .. ": meta.source.format") + t:eq(scene.meta.source.encoding, c.encoding, label .. ": encoding") + t:eq(scene.meta.source.vertices, c.vertices, label .. ": vertices") + t:eq(scene.meta.source.faces, c.faces, label .. ": faces") + verify(scene, c, label) + t:eq(Ply.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, label .. ": sniff") + local big = buffer.create(#c.data + 9) + buffer.writestring(big, 4, c.data) + local s2 = Ply.decode(Bytes.reader(big, 4, #c.data)) + t:check(s2 and Crc32.of(s2.meshes[1].primitives[1].attributes.POSITION.data) == c.attrs.POSITION.crc, label .. ": decode from a sub-range") + -- polygons kept + local poly = decode(c.data, { triangulate = false }) + local pp = poly.meshes[1].primitives[1] + if c.faces > 0 and not c.allTri then + t:eq(pp.mode, "polygons", label .. ": polygons mode") + t:eq(Crc32.of(pp.indices.data), c.corners_crc, label .. ": polygon corners") + t:eq(Crc32.of(pp.faces.data), c.sizes_crc, label .. ": polygon sizes") + end + for _, enc in ENCODINGS do + local out, eerr = Ply.encode(scene, { format = enc }) + t:check(out, label .. " -> " .. enc .. ": " .. tostring(eerr)) + local back, berr = decode(out) + t:check(back, label .. " -> " .. enc .. ": decode: " .. tostring(berr)) + t:eq(back.meta.source.encoding, enc, label .. " -> " .. enc .. ": encoding") + local cc = table.clone(c) + if c.faces > 0 and not c.allTri then + -- written as triangles: the face data goes through faceOfTriangle, one row per triangle + cc.faces, cc.allTri, cc.corners_crc = c.tris, true, c.tri_crc + cc.faceAttributes = {} + local bp = back.meshes[1].primitives[1] + local fa = bp.extras and bp.extras.faceAttributes + for name in c.faceAttributes do + if not c.faceAttributes[name].list then + t:check(fa and fa[name] and fa[name].count == c.tris, label .. ": face attribute per triangle") + end + end + end + verify(back, cc, label .. " -> " .. enc) + -- polygons in, polygons out + local pout = Ply.encode(poly, { format = enc }) :: buffer + local pback = decode(pout, { triangulate = false }) + verify(decode(pout), c, label .. " -> " .. enc .. " (polygons)") + local bp = pback.meshes[1].primitives[1] + t:eq(bp.mode, pp.mode, label .. ": polygons round trip mode") + if pp.indices then + t:check(buffer.tostring(bp.indices.data) == buffer.tostring(pp.indices.data), label .. ": polygons round trip indices") + end + if pp.faces then + t:check(buffer.tostring(bp.faces.data) == buffer.tostring(pp.faces.data), label .. ": polygons round trip sizes") + end + -- binary output of a binary input with the same byte order is the same file, header included + if enc == c.encoding and enc ~= "ascii" and string.sub(label, 1, 6) ~= "assimp" then + t:check(buffer.tostring(pout) == c.data, label .. ": byte-exact re-encode") + end + end +end +t:note("%d files match plyfile and round-trip in 3 encodings", #Fx.cases) + +for _, v in Fx.ours do + t:check(v.ok, "plyfile / assimp read our " .. v.name .. ": " .. v.detail) +end +t:note("%d encodings read back by plyfile and assimp", #Fx.ours) + +-- the encoder scenes: decode(encode()) against the properties computed by the generator +local function build(spec: any): Types.Scene + local scene = Types.Scene.new() + for i, m in spec.meshes do + local prims = {} + for _, p in m.prims do + local attrs = {} + for name, a in p.attrs do + attrs[name] = Types.Scene.accessor(buffer.fromstring(a[3]), a[1], a[2], p.count) + end + local prim: any = { attributes = attrs, mode = p.mode } + if p.indices then + prim.indices = Types.Scene.accessor(buffer.fromstring(p.indices), "u32", 1, #p.indices // 4) + end + if p.faces then + prim.faces = Types.Scene.accessor(buffer.fromstring(p.faces), "u32", 1, #p.faces // 4) + end + table.insert(prims, prim) + end + scene.meshes[i] = { primitives = prims } + end + for i, n in spec.nodes do + scene.nodes[i] = { mesh = n.mesh, children = n.children or {}, translation = n.translation, rotation = n.rotation, scale = n.scale, matrix = n.matrix } + end + scene.roots = spec.roots + return scene +end +local ATTR_OF: { [string]: { string | number } } = { + x = { "POSITION", 0 }, + y = { "POSITION", 1 }, + z = { "POSITION", 2 }, + nx = { "NORMAL", 0 }, + ny = { "NORMAL", 1 }, + nz = { "NORMAL", 2 }, + red = { "COLOR_0", 0 }, + green = { "COLOR_0", 1 }, + blue = { "COLOR_0", 2 }, + alpha = { "COLOR_0", 3 }, + s = { "TEXCOORD_0", 0 }, + t = { "TEXCOORD_0", 1 }, +} +local READ: { [string]: (buffer, number) -> number } = { ["<f4"] = buffer.readf32, u1 = buffer.readu8, ["<u2"] = buffer.readu16 } +local SIZE: { [string]: number } = { ["<f4"] = 4, u1 = 1, ["<u2"] = 2 } +for _, spec in Scenes do + local scene = build(spec) + for _, enc in ENCODINGS do + local label = spec.name .. "/" .. enc + local out, err = Ply.encode(scene, { format = enc }) + t:check(out, label .. ": " .. tostring(err)) + local back = decode(out, { triangulate = false }) + local p = back.meshes[1].primitives[1] + for _, prop in spec.props do + local where = ATTR_OF[prop.name] + local a = if where then p.attributes[where[1]] else p.attributes["_" .. prop.name] + t:check(a ~= nil, label .. ": property " .. prop.name) + local comp = if where then where[2] :: number else 0 + local rd, sz = READ[prop.dtype], SIZE[prop.dtype] + local vals = buffer.fromstring(prop.values) + local n = buffer.len(vals) // sz + t:eq(a.count, n, label .. ": " .. prop.name .. " count") + local csz = Types.COMPONENT_SIZE[a.type] + for i = 0, n - 1 do + local got = rd(a.data, (i * a.components + comp) * csz) + local want = rd(vals, i * sz) + if prop.tol then + t:check(math.abs(got - want) <= prop.tol, label .. ": " .. prop.name .. " value") + else + t:eq(got, want, label .. ": " .. prop.name .. " value") + end + end + end + if spec.faces then + local sizes = buffer.fromstring(spec.faceSizes) + local corners = buffer.fromstring(spec.faceCorners) + t:check(buffer.tostring(p.indices.data) == buffer.tostring(corners), label .. ": corners") + if p.mode == "polygons" then + t:check(buffer.tostring(p.faces.data) == buffer.tostring(sizes), label .. ": face sizes") + else + t:eq(p.mode, "triangles", label .. ": mode") + t:eq(p.indices.count, buffer.len(sizes) // 4 * 3, label .. ": all triangles") + end + else + t:eq(p.mode, "points", label .. ": points") + end + -- identity scenes: every attribute comes back as it was (COLOR_0 of the merged scene filled with white) + if not spec.transformed and #spec.meshes == 1 then + for name, a in scene.meshes[1].primitives[1].attributes do + t:check(buffer.tostring(p.attributes[name].data) == buffer.tostring(a.data), label .. ": " .. name .. " round trip") + t:eq(p.attributes[name].type, a.type, label .. ": " .. name .. " type") + end + end + end +end + +-- options and meta: comments, extra elements written back, faceAttributes of a triangulated mesh +do + local scene = build(Scenes[1]) + scene.meta.ply = { comments = { "first" }, objInfo = { "info line" } } + local out = Ply.encode(scene, { format = "ascii", comments = { "second" } }) :: buffer + local s = buffer.tostring(out) + t:check(string.find(s, "comment first\ncomment second\nobj_info info line\n", 1, true) ~= nil, "comments and obj_info") + local back = decode(out) + t:eq(back.meta.ply.comments[2], "second", "comment option") + local _, e = Ply.encode(scene, { format = "binary" } :: any) + t:check(e and e.code == Err.ARG, "bad format option: " .. tostring(e)) + -- the default is binary little endian + t:check(string.find(buffer.tostring(Ply.encode(scene) :: buffer), "format binary_little_endian 1.0", 1, true) ~= nil, "default encoding") + -- a scene without nodes uses its meshes + local bare = Types.Scene.new() + bare.meshes[1] = scene.meshes[1] + t:eq(decode(Ply.encode(bare) :: buffer).meta.source.vertices, 20, "a scene without nodes") +end + +-- 4. error codes +do + local function code(s: string, opts: any?): string? + local _, e = decode(s, opts) + return e and e.code + end + local H = "ply\nformat ascii 1.0\nelement vertex 3\nproperty float x\nproperty float y\nproperty float z\nelement face 1\nproperty list uchar int vertex_indices\nend_header\n" + t:check(decode(H .. "0 0 0\n1 0 0\n0 1 0\n3 0 1 2\n"), "a minimal ascii file") + t:eq(code("plx\n"), Err.CORRUPT, "bad signature") + t:eq(code("ply\nformat ascii 2.0\nend_header\n"), Err.UNSUPPORTED, "version 2") + t:eq(code("ply\nformat text 1.0\nend_header\n"), Err.UNSUPPORTED, "unknown format") + t:eq(code("ply\nformat ascii 1.0\nelement vertex 1\n"), Err.TRUNCATED, "no end_header") + t:eq(code("ply\nformat ascii 1.0\nproperty float x\nend_header\n"), Err.CORRUPT, "property before element") + t:eq(code("ply\nformat ascii 1.0\nelement vertex 1\nproperty float x\nproperty float x\nend_header\n0 0\n"), Err.CORRUPT, "duplicate property") + t:eq(code("ply\nformat ascii 1.0\nelement vertex 1\nproperty quad x\nend_header\n"), Err.CORRUPT, "unknown type") + t:eq(code("ply\nformat ascii 1.0\nelement vertex 1\nproperty list uchar float x\nend_header\n1 0\n"), Err.UNSUPPORTED, "list in the vertex element") + t:eq(code("ply\nformat ascii 1.0\nbanana\nend_header\n"), Err.CORRUPT, "unknown header line") + t:eq(code("ply\nformat ascii 1.0\nelement face 0\nend_header\n"), Err.CORRUPT, "no vertex element") + t:eq(code(H .. "0 0 0\n1 0 0\n0 1 0\n3 0 1 3\n"), Err.CORRUPT, "ascii index out of range") + t:eq(code(H .. "0 0 0\n1 0 0\n0 1 0\n3 0 1 -1\n"), Err.CORRUPT, "negative index") + t:eq(code(H .. "0 0 0\n1 0 0\n0 1 0\n3 0 1\n"), Err.TRUNCATED, "ascii cut") + t:eq(code(H .. "0 0 0\n1 zz 0\n0 1 0\n3 0 1 2\n"), Err.CORRUPT, "bad number") + t:eq(code(H .. "0 0 0\n1 0 0\n0 1 0\n300 0 1 2\n"), Err.CORRUPT, "uchar count over 255") + t:eq(code(H .. "0 0 0\n1 0 0\n0 1 0\n3 0 1 2.5\n"), Err.CORRUPT, "fractional index") + t:eq(code(H .. "0 0 0\n1 0 0\n0 1 0\n3 0 1 2\n", { maxVertices = 2 }), Err.LIMIT, "maxVertices") + t:eq(code(H .. "0 0 0\n1 0 0\n0 1 0\n3 0 1 2\n", { maxFaces = 0 }), Err.LIMIT, "maxFaces") + t:eq(code("ply\nformat ascii 1.0\nelement vertex 1000000\nproperty float x\nend_header\n1\n"), Err.TRUNCATED, "ascii count over the data") + local B = "ply\nformat binary_little_endian 1.0\nelement vertex 3\nproperty float x\nproperty float y\nproperty float z\nelement face 1\nproperty list uchar int vertex_indices\nend_header\n" + local verts = string.rep("\0", 36) + t:check(decode(B .. verts .. "\3\0\0\0\0\1\0\0\0\2\0\0\0"), "a minimal binary file") + t:eq(code(B .. verts .. "\3\0\0\0\0\1\0\0\0\3\0\0\0"), Err.CORRUPT, "binary index out of range") + t:eq(code(B .. verts .. "\3\0\0\0\0\1\0\0\0\2\0\0"), Err.TRUNCATED, "binary list cut") + t:eq(code(B .. string.sub(verts, 1, 30)), Err.TRUNCATED, "binary rows cut") + t:eq(code("ply\nformat binary_big_endian 1.0\nelement vertex 4000000000\nproperty float x\nend_header\n", { maxVertices = 2 ^ 40, maxFaces = 2 ^ 40 }), Err.TRUNCATED, "huge count") + local _, a1 = Ply.encode({} :: any) + t:check(a1 and a1.code == Err.ARG, "encode a non-scene: " .. tostring(a1)) + local noPos = Types.Scene.fromPrimitive({ attributes = {}, mode = "points" }) + local _, a2 = Ply.encode(noPos) + t:check(a2 and a2.code == Err.ARG, "no POSITION: " .. tostring(a2)) +end + +-- 5. fuzz +do + local samples = {} + for _, c in Fx.cases do + if #c.data < 30000 then + table.insert(samples, c.data) + end + end + t:fuzz("decode", function(b: buffer) + return Ply.decode(Bytes.reader(b)) + end, samples, { mutations = 30 }) + t:fuzz("decode polygons + re-encode", function(b: buffer) + local s = Ply.decode(Bytes.reader(b), { triangulate = false }) + if s then + return Ply.encode(s, { format = "ascii" }) + end + return nil + end, samples, { mutations = 6, garbage = 20 }) +end + +-- throughput: a 500 x 500 grid (250k vertices, 498k triangles), binary little endian +do + local W = 500 + local pos = buffer.create(W * W * 12) + for i = 0, W * W - 1 do + buffer.writef32(pos, i * 12, i % W) + buffer.writef32(pos, i * 12 + 4, i // W) + buffer.writef32(pos, i * 12 + 8, (i * 7) % 13) + end + local nt = (W - 1) * (W - 1) * 2 + local idx = buffer.create(nt * 12) + local k = 0 + for y = 0, W - 2 do + for x = 0, W - 2 do + local a = y * W + x + for _, v in { a, a + 1, a + W + 1, a, a + W + 1, a + W } do + buffer.writeu32(idx, k * 4, v) + k += 1 + end + end + end + local scene = Types.Scene.fromPrimitive({ attributes = { POSITION = Types.Scene.accessor(pos, "f32", 3, W * W) }, indices = Types.Scene.accessor(idx, "u32", 1, nt * 3), mode = "triangles" }) + local t0 = os.clock() + local data = Ply.encode(scene) :: buffer + local te = os.clock() - t0 + t0 = os.clock() + local back = Ply.decode(Bytes.reader(data)) + local dt = os.clock() - t0 + t:check(back and back.meshes[1].primitives[1].indices.count == nt * 3, "bench decode") + t:check(buffer.tostring(back.meshes[1].primitives[1].indices.data) == buffer.tostring(idx), "bench round trip") + t:note("binary LE decode: %d vertices + %d triangles (%.1f MB) in %.3f s, %.0f MB/s (encode %.2f s)", W * W, nt, buffer.len(data) / 1e6, dt, buffer.len(data) / 1e6 / math.max(dt, 1e-6), te) +end + +t:done() diff --git a/tests/model/stl.luau b/tests/model/stl.luau new file mode 100644 index 0000000..56763ce --- /dev/null +++ b/tests/model/stl.luau @@ -0,0 +1,342 @@ +-- model/stl tests: files made by trimesh, assimp and by hand (binary starting with "solid", VisCAM / Magics colours, +-- raw attribute words, odd ASCII, several solids, quads, no endsolid, trailing bytes) against trimesh's raw reader +-- (CRC-32 of the f32 vertices / normals, area, bounds), our encoder's output read back by trimesh and assimp (verdicts +-- from the fixture step), round trips of every encoding and option, the contract, error codes, the fuzz no-throw pass +-- and a binary decode throughput note. Fixtures: tools/fixtures/stl.py. +local T = require("@tests/T") +local Stl = require("@formats/model/stl") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Fx = require("@tests/gen/stl") +local Scenes = require("@tests/gen/stl_scenes") + +local t = T.suite("stl") + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return Stl.decode(Bytes.reader(b), opts) +end + +-- every primitive's accessor `name` concatenated (nil when a primitive lacks it) +local function concat(scene: any, name: string): buffer? + local parts = {} + for _, p in scene.meshes[1].primitives do + local a = p.attributes[name] + if not a then + return nil + end + table.insert(parts, buffer.tostring(a.data)) + end + return buffer.fromstring(table.concat(parts)) +end + +-- 1. the contract +t:eq(Stl.name, "stl", "name") +t:eq(Stl.category, "model", "category") +t:check(table.find(Stl.extensions, "stl") ~= nil, "extensions") +t:check(Stl.caps.decode and Stl.caps.encode, "caps") + +-- 2. every fixture against the reference +for _, c in Fx.cases do + local label = c.name + local scene, err = decode(c.data) + t:check(scene, label .. ": " .. tostring(err)) + t:check(scene.kind == "scene" and #scene.meshes == 1 and #scene.nodes == 1 and scene.roots[1] == 1, label .. ": a one-node scene") + t:eq(scene.meta.up, "z", label .. ": up") + t:eq(scene.meta.source.format, "stl", label .. ": meta.source.format") + t:eq(scene.meta.source.binary, c.binary, label .. ": binary") + t:eq(scene.meta.source.facets, c.facets, label .. ": facet count") + local pos = concat(scene, "POSITION") :: buffer + t:eq(buffer.len(pos), c.facets * 36, label .. ": POSITION size") + t:eq(Crc32.of(pos), c.pos_crc, label .. ": POSITION crc") + for _, p in scene.meshes[1].primitives do + t:check(p.mode == "triangles" and p.indices == nil and p.attributes.POSITION.type == "f32" and p.attributes.POSITION.components == 3, label .. ": a triangle soup") + end + if c.nrm_crc then + t:eq(Crc32.of(concat(scene, "NORMAL") :: buffer), c.nrm_crc, label .. ": NORMAL crc") + end + if c.area then + local area = 0 + local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } + for f = 0, c.facets - 1 do + local v = {} + for k = 0, 8 do + v[k + 1] = buffer.readf32(pos, f * 36 + k * 4) + end + for k = 0, 2 do + for a = 1, 3 do + lo[a] = math.min(lo[a], v[k * 3 + a]) + hi[a] = math.max(hi[a], v[k * 3 + a]) + end + end + local ux, uy, uz = v[4] - v[1], v[5] - v[2], v[6] - v[3] + local wx, wy, wz = v[7] - v[1], v[8] - v[2], v[9] - v[3] + local cx, cy, cz = uy * wz - uz * wy, uz * wx - ux * wz, ux * wy - uy * wx + area += math.sqrt(cx * cx + cy * cy + cz * cz) / 2 + end + t:check(math.abs(area - c.area) <= 1e-6 * math.max(1, c.area), string.format("%s: area %.9g, want %.9g", label, area, c.area)) + if c.facets > 0 then + -- trimesh keeps ASCII coordinates as doubles: compare with them rounded to f32 + local function f32(x: number): number + local sb = buffer.create(4) + buffer.writef32(sb, 0, x) + return buffer.readf32(sb, 0) + end + for a = 1, 3 do + t:check(lo[a] == f32(c.bounds[a]) and hi[a] == f32(c.bounds[a + 3]), label .. ": bounds") + end + end + end + local p1 = scene.meshes[1].primitives[1] + if c.col_crc then + t:eq(scene.meta.source.colors, c.colors, label .. ": colour convention") + t:check(p1.attributes.COLOR_0 and p1.attributes.COLOR_0.type == "unorm8" and p1.attributes.COLOR_0.components == 4, label .. ": COLOR_0 unorm8 x4") + t:eq(Crc32.of(p1.attributes.COLOR_0.data), c.col_crc, label .. ": COLOR_0 crc") + else + t:check(p1.attributes.COLOR_0 == nil, label .. ": no colours") + end + if c.defaultColor then + local d = scene.meta.source.defaultColor + t:check(d and d[1] == c.defaultColor[1] and d[2] == c.defaultColor[2] and d[3] == c.defaultColor[3] and d[4] == c.defaultColor[4], label .. ": magics default colour") + t:check(scene.meta.source.material and scene.meta.source.material.specular[1] == 4, label .. ": magics material") + end + if c.attr_crc then + local fa = p1.extras and p1.extras.faceAttributes and p1.extras.faceAttributes.attribute + t:check(fa and fa.type == "u16" and fa.count == c.facets, label .. ": raw attribute words") + t:eq(Crc32.of(fa.data), c.attr_crc, label .. ": attribute words crc") + end + if c.solids then + local prims = scene.meshes[1].primitives + t:eq(#prims, #c.solids, label .. ": one primitive per solid") + for i, name in c.solids do + t:eq(prims[i].extras.solid, name, label .. ": solid name") + t:eq(prims[i].attributes.POSITION.count, c.solidFacets[i] * 3, label .. ": solid facets") + end + end + -- inside a bigger buffer (the Reader's range) + local big = buffer.create(#c.data + 11) + buffer.writestring(big, 5, c.data) + local s2 = Stl.decode(Bytes.reader(big, 5, #c.data)) + t:check(s2 and Crc32.of(concat(s2, "POSITION") :: buffer) == c.pos_crc, label .. ": decode from a sub-range") + if label ~= "bin-trailing.stl" then -- no magic, and the size does not match: not recognisable + t:check(Stl.sniff(Bytes.reader(buffer.fromstring(c.data))) >= 0.5, label .. ": sniff") + end + -- re-encode (binary with the file's normals, and ASCII): the same triangles and normals + for _, ascii in { false, true } do + local opts: any = { ascii = ascii, normals = "attribute", colors = if c.col_crc then c.colors else nil } + if c.defaultColor then + opts.defaultColor = c.defaultColor + end + local out, eerr = Stl.encode(scene, opts) + t:check(out, label .. ": encode: " .. tostring(eerr)) + local back = decode(out) + t:check(back, label .. ": decode our output") + t:check(buffer.tostring(concat(back, "POSITION") :: buffer) == buffer.tostring(pos), label .. ": re-encoded POSITION (ascii " .. tostring(ascii) .. ")") + t:check(buffer.tostring(concat(back, "NORMAL") :: buffer) == buffer.tostring(concat(scene, "NORMAL") :: buffer), label .. ": re-encoded NORMAL") + if c.col_crc and not ascii then + t:eq(Crc32.of(back.meshes[1].primitives[1].attributes.COLOR_0.data), c.col_crc, label .. ": re-encoded colours") + end + if c.attr_crc and not ascii then + t:eq(Crc32.of(back.meshes[1].primitives[1].extras.faceAttributes.attribute.data), c.attr_crc, label .. ": re-encoded attribute words") + end + if c.solids and ascii then + t:eq(back.meshes[1].primitives[1].extras.solid, c.solids[1], label .. ": solid name round trip") + end + end +end +t:note("%d files match trimesh / the generator", #Fx.cases) + +-- 3. the reference tools read our output +for _, v in Fx.ours do + t:check(v.ok, "trimesh / assimp read our " .. v.name .. ": " .. v.detail) +end +t:note("%d encodings read back by trimesh and assimp", #Fx.ours) + +-- round trips of the encoder scenes: world-space soup as the generator computed it, colour words, idempotence +local function acc(s: string, ty: string, comps: number, count: number): Types.Accessor + return Types.Scene.accessor(buffer.fromstring(s), ty, comps, count) +end +local function build(spec: any): Types.Scene + local scene = Types.Scene.new() + for i, m in spec.meshes do + local prims = {} + for _, p in m.prims do + local prim: any = { attributes = { POSITION = acc(p.pos, p.posType or "f32", 3, p.count) }, mode = p.mode } + if p.indices then + prim.indices = acc(p.indices, "u32", 1, #p.indices // 4) + end + if p.faces then + prim.faces = acc(p.faces, "u32", 1, #p.faces // 4) + end + if p.color then + prim.attributes.COLOR_0 = acc(p.color, "unorm8", 4, p.count) + end + table.insert(prims, prim) + end + scene.meshes[i] = { name = m.name, primitives = prims } + end + for i, n in spec.nodes do + scene.nodes[i] = { name = n.name, mesh = n.mesh, children = n.children or {}, translation = n.translation, rotation = n.rotation, scale = n.scale, matrix = n.matrix } + end + scene.roots = spec.roots + return scene +end +local OPTS: { [string]: any } = { binary = {}, ascii = { ascii = true }, viscam = { colors = "viscam" }, magics = { colors = "magics" } } +for _, spec in Scenes do + local scene = build(spec) + local want = buffer.fromstring(spec.expect) + local nf = buffer.len(want) // 36 + for _, e in spec.encodings do + local label = spec.name .. "/" .. e + local out, err = Stl.encode(scene, OPTS[e]) + t:check(out, label .. ": encode: " .. tostring(err)) + local back, berr = decode(out) + t:check(back, label .. ": decode: " .. tostring(berr)) + local got = concat(back, "POSITION") :: buffer + t:eq(buffer.len(got), nf * 36, label .. ": facets") + local worst = 0 + for i = 0, nf * 9 - 1 do + worst = math.max(worst, math.abs(buffer.readf32(got, i * 4) - buffer.readf32(want, i * 4))) + end + t:check(if spec.exact then worst == 0 else worst < 1e-4, string.format("%s: positions off by %g", label, worst)) + -- facet normals: unit length, right-hand rule + local nrm = concat(back, "NORMAL") :: buffer + for f = 0, nf - 1 do + local o = f * 36 + local n = { buffer.readf32(nrm, o), buffer.readf32(nrm, o + 4), buffer.readf32(nrm, o + 8) } + local len = math.sqrt(n[1] ^ 2 + n[2] ^ 2 + n[3] ^ 2) + t:check(math.abs(len - 1) < 1e-5, label .. ": unit normal") + local p = {} + for k = 0, 8 do + p[k + 1] = buffer.readf32(got, o + k * 4) + end + local cx = (p[5] - p[2]) * (p[9] - p[3]) - (p[6] - p[3]) * (p[8] - p[2]) + local cy = (p[6] - p[3]) * (p[7] - p[1]) - (p[4] - p[1]) * (p[9] - p[3]) + local cz = (p[4] - p[1]) * (p[8] - p[2]) - (p[5] - p[2]) * (p[7] - p[1]) + t:check(cx * n[1] + cy * n[2] + cz * n[3] > 0, label .. ": normal follows the winding") + end + if e == "viscam" or e == "magics" then + local words = if e == "viscam" then spec.viscamWords else spec.magicsWords + for f = 0, nf - 1 do + t:eq(buffer.readu16(out :: buffer, 84 + f * 50 + 48), words[f + 1], label .. ": colour word") + end + t:eq(back.meta.source.colors, e, label .. ": detected convention") + -- the colours are on 5-bit steps: decode(encode()) gives the first vertex colour of each facet back + local col = back.meshes[1].primitives[1].attributes.COLOR_0.data + local src = scene.meshes[1].primitives[1] + local idx = src.indices :: Types.Accessor + for f = 0, nf - 1 do + local a = buffer.readu32(idx.data, f * 12) + t:eq(buffer.readu32(col, f * 12), buffer.readu32(src.attributes.COLOR_0.data, a * 4), label .. ": facet colour") + end + end + -- idempotent: encoding the decoded soup again gives the same file + local again = Stl.encode(back, { ascii = OPTS[e].ascii, colors = OPTS[e].colors, normals = "attribute" }) :: buffer + t:check(buffer.tostring(again) == buffer.tostring(out :: buffer), label .. ": re-encode is identical") + end +end +-- options: header, name, computed vs attribute normals +do + local scene = build(Scenes[1]) + local out = Stl.encode(scene, { header = "my header", ascii = false }) :: buffer + t:eq(buffer.readstring(out, 0, 9), "my header", "header option") + t:eq(decode(out).meta.source.header, "my header", "meta.source.header") + local a = buffer.tostring(Stl.encode(scene, { ascii = true, name = "part 7" }) :: buffer) + t:check(string.sub(a, 1, 12) == "solid part 7" and string.find(a, "endsolid part 7", 1, true) ~= nil, "name option") + local m = Stl.encode(scene, { colors = "magics", defaultColor = { 1, 2, 3, 4 } }) :: buffer + local d = decode(m).meta.source.defaultColor + t:check(d[1] == 1 and d[2] == 2 and d[3] == 3 and d[4] == 4, "defaultColor option") + -- points / lines only: an empty STL + local pts = Types.Scene.fromPrimitive({ attributes = { POSITION = Types.Scene.accessor(nil, "f32", 3, 4) }, mode = "points" }) + local e0 = Stl.encode(pts) :: buffer + t:eq(buffer.len(e0), 84, "points only: no facets") + -- a scene without nodes uses its meshes + local bare = Types.Scene.new() + bare.meshes[1] = scene.meshes[1] + t:eq(buffer.len(Stl.encode(bare) :: buffer), 84 + 50 * 60, "a scene without nodes") +end + +-- 4. error codes +do + local cube = Fx.cases[1].data + local _, e1 = decode(string.sub(cube, 1, 84 + 50 * 3 + 7)) + t:check(e1 and e1.code == Err.TRUNCATED, "cut binary: " .. tostring(e1)) + local _, e2 = decode("solid x\nfacet normal 1 2 zz\n") + t:check(e2 and e2.code == Err.CORRUPT, "bad number: " .. tostring(e2)) + local _, e3 = decode("solid x\nfacet normal 1 2 3\nouter loop\nvertex 1 2 3\n") + t:check(e3 and e3.code == Err.TRUNCATED, "cut ascii: " .. tostring(e3)) + local _, e4 = decode("solid x\nfacet normal 0 0 1\nouter loop\nvertex 1 2 3\nvertex 1 2 3\nendloop\nendfacet\nendsolid\n") + t:check(e4 and e4.code == Err.CORRUPT, "two-vertex facet: " .. tostring(e4)) + local _, e5 = decode("hello") + t:check(e5 and e5.code == Err.TRUNCATED, "tiny junk: " .. tostring(e5)) + local _, e6 = decode(cube, { maxFaces = 10 }) + t:check(e6 and e6.code == Err.LIMIT, "maxFaces: " .. tostring(e6)) + local _, e7 = decode(cube, { colors = "rainbow" }) + t:check(e7 and e7.code == Err.ARG, "bad colors option: " .. tostring(e7)) + local _, e8 = decode("solid x\nbanana\n") + t:check(e8 and e8.code == Err.CORRUPT, "bad keyword: " .. tostring(e8)) + local hdr = buffer.create(84) + buffer.writeu32(hdr, 80, 1000000) + local _, e9 = Stl.decode(Bytes.reader(hdr)) + t:check(e9 and e9.code == Err.TRUNCATED, "huge count: " .. tostring(e9)) + local _, a1 = Stl.encode({} :: any) + t:check(a1 and a1.code == Err.ARG, "encode a non-scene: " .. tostring(a1)) + local scene = build(Scenes[1]) + local _, a2 = Stl.encode(scene, { colors = "rgb" } :: any) + t:check(a2 and a2.code == Err.ARG, "bad colors: " .. tostring(a2)) + local bad = Types.Scene.fromPrimitive({ attributes = { POSITION = Types.Scene.accessor(nil, "f32", 3, 3) }, indices = Types.Scene.accessor(nil, "u32", 1, 3), mode = "triangles" }) + buffer.writeu32((bad.meshes[1].primitives[1].indices :: Types.Accessor).data, 4, 7) + local _, a3 = Stl.encode(bad) + t:check(a3 and a3.code == Err.ARG, "index out of range: " .. tostring(a3)) + local nan = Types.Scene.fromPrimitive({ attributes = { POSITION = Types.Scene.accessor(nil, "f32", 3, 3) }, mode = "triangles" }) + buffer.writef32(nan.meshes[1].primitives[1].attributes.POSITION.data, 0, 0 / 0) + local _, a4 = Stl.encode(nan, { ascii = true }) + t:check(a4 and a4.code == Err.ARG, "NaN in ASCII: " .. tostring(a4)) + t:check(Stl.encode(nan) ~= nil, "NaN in binary is fine") + local cyc = build(Scenes[3]) + cyc.nodes[2].children = { 1 } + local _, a5 = Stl.encode(cyc) + t:check(a5 and a5.code == Err.ARG, "cyclic nodes: " .. tostring(a5)) + t:eq(Stl.sniff(Bytes.reader(buffer.fromstring("ply\nformat ascii 1.0\n"))), 0, "sniff a PLY") +end + +-- 5. fuzz +do + local samples = {} + for i, c in Fx.cases do + if #c.data < 20000 or i % 3 == 0 then + table.insert(samples, c.data) + end + end + t:fuzz("decode", function(b: buffer) + return Stl.decode(Bytes.reader(b)) + end, samples, { mutations = 12 }) + t:fuzz("decode re-encode", function(b: buffer) + local s = Stl.decode(Bytes.reader(b)) + if s then + return Stl.encode(s, { ascii = true }) + end + return nil + end, samples, { mutations = 4, garbage = 20 }) +end + +-- throughput: a synthetic binary STL of 200k facets +do + local n = 200000 + local b = buffer.create(84 + 50 * n) + buffer.writeu32(b, 80, n) + for i = 0, n - 1 do + for k = 0, 11 do + buffer.writef32(b, 84 + i * 50 + k * 4, (i * 12 + k) % 1000 * 0.25) + end + end + local t0 = os.clock() + local s = Stl.decode(Bytes.reader(b)) + local dt = os.clock() - t0 + t:check(s and s.meshes[1].primitives[1].attributes.POSITION.count == n * 3, "bench decode") + t:note("binary decode: %d facets (%.1f MB) in %.3f s, %.0f MB/s", n, buffer.len(b) / 1e6, dt, buffer.len(b) / 1e6 / math.max(dt, 1e-6)) +end + +t:done() diff --git a/tests/model/vox.luau b/tests/model/vox.luau new file mode 100644 index 0000000..77d0ec2 --- /dev/null +++ b/tests/model/vox.luau @@ -0,0 +1,289 @@ +-- model/vox tests: MagicaVoxel files (ephtracy samples, opengametools scene files saved by MagicaVoxel 0.99.x) and +-- synthetic files with every chunk type, against an independent reader (tools/fixtures/vox.py): grids (CRC), palette, +-- the default palette (parsed from the spec text), scene graph world transforms (rotations, mirrors, nesting), layers, +-- materials, notes, cameras, render objects; greedy meshes (MeshOps) against the exposed face count; round trips +-- through the writer; error codes; the fuzz no-throw pass. Fixtures: tools/fixtures/vox.py. +local T = require("@tests/T") +local Vox = require("@formats/model/vox") +local MeshOps = require("@formats/ops/MeshOps") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Cases = require("@tests/gen/vox_cases") +local DefaultPalette = require("@tests/gen/vox_default_palette") + +local t = T.suite("vox") + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return Vox.decode(Bytes.reader(b), opts) +end + +-- the contract +t:eq(Vox.name, "vox", "name") +t:eq(Vox.category, "model", "category") +t:check(Vox.extensions[1] == "vox" and Vox.caps.decode and Vox.caps.encode, "contract") + +-- the default palette = the spec's array +do + t:eq(#Vox.DEFAULT_PALETTE, 255, "default palette size") + local same = true + for i = 1, 255 do + for k = 1, 4 do + if Vox.DEFAULT_PALETTE[i][k] ~= DefaultPalette[i][k] then + same = false + end + end + end + t:check(same, "default palette equals the spec's") +end + +local function paletteCrc(pal: { { number } }): number + local b = buffer.create(255 * 4) + for i = 1, 255 do + for k = 1, 4 do + buffer.writeu8(b, (i - 1) * 4 + k - 1, pal[i][k]) + end + end + return Crc32.of(b) +end + +local function countKeys(tbl: any): number + local n = 0 + for _ in tbl or {} do + n += 1 + end + return n +end + +-- shape nodes depth first with world matrices (column-major 4x4) +local function shapes(scene: any): { any } + local out = {} + local function walk(i: number, parent: { number }) + local node = scene.nodes[i] + local world = Types.Scene.mul(parent, Types.Scene.nodeMatrix(node)) + if node.voxels then + table.insert(out, { name = node.name or "", model = node.voxels, world = world }) + end + for _, c in node.children do + walk(c, world) + end + end + for _, r in scene.roots do + walk(r, Types.Scene.IDENTITY) + end + return out +end + +local function checkScene(scene: any, c: any, label: string) + t:eq(scene.kind, "scene", label .. ": a Scene") + t:eq(scene.meta.up, "z", label .. ": z up") + t:eq(#scene.voxels, #c.models, label .. ": models") + for i, m in c.models do + local v = scene.voxels[i] + t:check(v.size[1] == m.size[1] and v.size[2] == m.size[2] and v.size[3] == m.size[3], label .. ": model " .. i .. " size") + t:eq(Crc32.of(v.data), m.crc, label .. ": model " .. i .. " grid") + end + t:eq(paletteCrc(scene.voxels[1].palette), c.paletteCrc, label .. ": palette") + local vm = scene.meta.vox + t:eq(#(vm.layers or {}), c.layers, label .. ": layers") + t:eq(countKeys(scene.voxels[1].materials), c.materials, label .. ": materials") + t:eq(#(vm.notes or {}), c.notes, label .. ": notes") + t:eq(#(vm.cameras or {}), c.cameras, label .. ": cameras") + t:eq(#(vm.renderObjects or {}), c.robjs, label .. ": render objects") + local glass = 0 + for _, m in scene.voxels[1].materials or {} do + if m.type == "glass" then + glass += 1 + end + end + t:eq(glass, c.glassMaterials, label .. ": glass materials") + if #c.shapes > 0 then + local got = shapes(scene) + t:eq(#got, #c.shapes, label .. ": shape nodes") + for k, want in c.shapes do + local g = got[k] + t:eq(g.name, want.name, label .. ": shape " .. k .. " name") + t:eq(g.model, want.model, label .. ": shape " .. k .. " model") + local ok = true + for row = 0, 2 do + for col = 0, 3 do + local w = want.world[row * 4 + col + 1] + local v = g.world[col * 4 + row + 1] + if math.abs(w - v) > 1e-6 then + ok = false + end + end + end + t:check(ok, label .. ": shape " .. k .. " (" .. want.name .. ") world transform") + end + end +end + +-- area and winding of a greedy mesh +local function meshFacts(prim: any): (number, boolean, number) + local pos, nrm = prim.attributes.POSITION.data, prim.attributes.NORMAL.data + local ind = prim.indices.data + local area, wound = 0, true + for tri = 0, prim.indices.count // 3 - 1 do + local a, b, c = buffer.readu32(ind, tri * 12), buffer.readu32(ind, tri * 12 + 4), buffer.readu32(ind, tri * 12 + 8) + local function p(i: number, k: number): number + return buffer.readf32(pos, i * 12 + k * 4) + end + local e1 = { p(b, 0) - p(a, 0), p(b, 1) - p(a, 1), p(b, 2) - p(a, 2) } + local e2 = { p(c, 0) - p(a, 0), p(c, 1) - p(a, 1), p(c, 2) - p(a, 2) } + local nx, ny, nz = e1[2] * e2[3] - e1[3] * e2[2], e1[3] * e2[1] - e1[1] * e2[3], e1[1] * e2[2] - e1[2] * e2[1] + area += math.sqrt(nx * nx + ny * ny + nz * nz) / 2 + local dot = nx * buffer.readf32(nrm, a * 12) + ny * buffer.readf32(nrm, a * 12 + 4) + nz * buffer.readf32(nrm, a * 12 + 8) + if dot <= 0 then + wound = false + end + end + return area, wound, prim.indices.count // 3 +end + +local totalQuads, totalFaces = 0, 0 +for _, c in Cases do + local label = c.name + local scene, err = decode(c.data) + t:check(scene, label .. ": decode: " .. tostring(err)) + checkScene(scene, c, label) + t:eq(scene.meta.source.version, c.version, label .. ": version") + -- decodeVoxels, and from a sub-range of a bigger buffer + local big = buffer.create(#c.data + 9) + buffer.writestring(big, 5, c.data) + local grids = Vox.decodeVoxels(Bytes.reader(big, 5, #c.data)) + t:check(grids and #grids == #c.models and Crc32.of(grids[1].data) == c.models[1].crc, label .. ": decodeVoxels from a sub-range") + -- greedy meshing: the area is the number of exposed unit faces, every triangle faces its normal + for i, m in c.models do + local prim, perr = MeshOps.voxelsToPrimitive(scene.voxels[i], { pivot = "corner" }) + t:check(prim, label .. ": mesh: " .. tostring(perr)) + local area, wound, tris = meshFacts(prim) + t:eq(area, m.faces, label .. ": model " .. i .. " greedy mesh area = exposed faces") + t:check(wound, label .. ": model " .. i .. " winding matches the normals") + t:check(tris <= m.faces * 2, label .. ": model " .. i .. " no more triangles than faces") + totalQuads += tris // 2 + totalFaces += m.faces + end + -- round trip through the writer + local out, eerr = Vox.encode(scene) + t:check(out, label .. ": encode: " .. tostring(eerr)) + local back, berr = Vox.decode(Bytes.reader(out :: buffer)) + t:check(back, label .. ": decode our file: " .. tostring(berr)) + checkScene(back, c, label .. " (round trip)") + t:eq(back.meta.source.version, 200, label .. ": written as version 200") + local out2 = Vox.encode(back) :: buffer + t:check(buffer.tostring(out2) == buffer.tostring(out :: buffer), label .. ": writing is stable") + if scene.meta.vox.info then + t:check(back.meta.vox.info and back.meta.vox.info._anim_range == scene.meta.vox.info._anim_range, label .. ": META") + end +end +t:note("%d files: grids, palettes, scene graphs and round trips match; greedy: %d quads for %d faces", #Cases, totalQuads, totalFaces) + +-- the synthetic scene in detail: names, hidden, layers, animation frames, materials, notes, IMAP, unknown chunks +do + local c + for _, x in Cases do + if x.name == "syn-scene" then + c = x + end + end + local scene = decode(c.data) + local byName = {} + for _, n in scene.nodes do + if n.name then + byName[n.name] = n + end + end + t:check(byName.group and byName.group.extras.vox.attributes._hidden == "1" and byName.group.extras.vox.layer == 1, "hidden group on layer 1") + t:check(byName.b and byName.b.matrix ~= nil, "a mirrored node keeps a matrix") + t:check(byName.a and byName.a.matrix == nil and byName.a.rotation == nil and byName.a.translation[3] == 3, "identity rotation: translation only") + t:check(byName.anim and #byName.anim.extras.vox.frames == 2 and #byName.anim.extras.vox.shape.models == 2, "animation frames and shape models") + local mats = scene.voxels[1].materials + t:check(mats[1].type == "glass" and mats[2].type == "emit" and mats[1].rough == 0.25 and mats[1].ior == 1.5 and mats[200].type == "emit", "materials") + t:check(scene.meta.vox.notes[2] == "second" and scene.meta.vox.indexMap[256] == 255, "notes, IMAP") + t:check(scene.meta.vox.layers[2].name == "one" and scene.meta.vox.layers[2].hidden, "layers") + t:check(scene.meta.vox.cameras[1].attributes._fov == "45", "rCAM") + t:check(scene.meta.vox.chunks and scene.meta.vox.chunks[1].id == "ZZZZ", "unknown chunk kept") + local back = Vox.decode(Bytes.reader(Vox.encode(scene) :: buffer)) :: any + local bn = {} + for _, n in back.nodes do + if n.name then + bn[n.name] = n + end + end + t:check(bn.anim and #bn.anim.extras.vox.frames == 2 and bn.anim.extras.vox.frames[2]._t == "4 4 4", "frames round trip") + t:check(back.meta.vox.chunks and buffer.tostring(back.meta.vox.chunks[1].content) == "unknown payload", "unknown chunk round trip") + t:check(back.voxels[1].materials[200].flux == 2, "material round trip") + -- meshVoxels: every shape node gets the mesh of its grid + MeshOps.meshVoxels(back) + local meshed = 0 + for _, n in back.nodes do + if n.voxels then + t:check(n.mesh ~= nil and back.meshes[n.mesh].primitives[1].attributes.COLOR_0 ~= nil, "meshVoxels sets node.mesh") + meshed += 1 + end + end + t:check(meshed == 4 and #back.meshes == 4, "four shapes meshed") + local lo, hi = MeshOps.bounds(back) + t:check(lo and hi and hi[1] > lo[1], "scene bounds of the meshed shapes") +end + +-- a Voxels grid alone; the centred pivot; sRGB colours +do + local v = Types.Voxels.new(3, 4, 5, Vox.DEFAULT_PALETTE) + Types.Voxels.set(v, 0, 0, 0, 1) + Types.Voxels.set(v, 2, 3, 4, 200) + local out, err = Vox.encode(v) + t:check(out, "encode a Voxels grid: " .. tostring(err)) + local back = Vox.decode(Bytes.reader(out :: buffer)) :: any + t:check(back and #back.voxels == 1 and Types.Voxels.get(back.voxels[1], 2, 3, 4) == 200 and Types.Voxels.get(back.voxels[1], 1, 1, 1) == 0, "Voxels round trip") + local prim = MeshOps.voxelsToPrimitive(v, { colors = "srgb", indexAttribute = true }) :: any + local lo, hi = MeshOps.bounds(prim) + t:check(lo and hi and lo[1] == -1 and lo[2] == -2 and lo[3] == -2 and hi[1] == 2 and hi[2] == 2 and hi[3] == 3, "centre pivot") + t:check(prim.attributes.COLOR_0.type == "unorm8" and prim.attributes._PALETTE_INDEX.type == "u8", "srgb colours, index attribute") + t:eq(prim.indices.count, 72, "two separate cubes: 12 quads") +end + +-- errors +do + local _, e = decode("nope") + t:check(e and e.code == Err.CORRUPT, "junk: " .. tostring(e)) + local c = Cases[1] + local _, e2 = decode(c.data, { maxCells = 10 }) + t:check(e2 and e2.code == Err.LIMIT, "maxCells: " .. tostring(e2)) + local _, e3 = decode(string.sub(c.data, 1, 30)) + t:check(e3 ~= nil, "truncated: " .. tostring(e3)) + local _, e4 = Vox.encode({} :: any) + t:check(e4 and e4.code == Err.ARG, "encode junk") + local big = Types.Voxels.new(300, 1, 1) + local _, e5 = Vox.encode(big) + t:check(e5 and e5.code == Err.ARG, "over 256 cells: " .. tostring(e5)) + local s = Vox.decode(Bytes.reader(buffer.fromstring(Cases[1].data))) :: any + s.nodes[s.roots[1]].rotation = { 0, 0, math.sin(0.3), math.cos(0.3) } + local _, e6 = Vox.encode(s) + t:check(e6 and e6.code == Err.ARG, "a 34 degree rotation: " .. tostring(e6)) + local _, e7 = MeshOps.voxelsToPrimitive({} :: any) + t:check(e7 and e7.code == Err.ARG, "voxelsToPrimitive of junk") +end + +-- fuzz +do + local samples = {} + for _, c in Cases do + if #c.data < 100000 then + table.insert(samples, c.data) + end + end + t:fuzz("decode", function(b: buffer) + local s = Vox.decode(Bytes.reader(b)) + if s then + MeshOps.meshVoxels(s) + Vox.encode(s) + end + return s + end, samples, { mutations = 30, keepHeader = 8 }) +end + +t:done() diff --git a/tests/ops/imageops.luau b/tests/ops/imageops.luau new file mode 100644 index 0000000..2662d0d --- /dev/null +++ b/tests/ops/imageops.luau @@ -0,0 +1,321 @@ +-- ops/ImageOps tests: against Pillow (tools/fixtures/imageops.py): grey conversion (exact), resize nearest / bilinear / +-- Lanczos up and down (max error), rotate with bilinear + expand (PSNR), alpha_composite (exact); property tests for +-- every pixel format (conversion round trips, flips, quarter turns, crop, premultiply, pixel access, fill), blit +-- clipping and blend modes, animation helpers (coalesce with each disposal, fromFrames, durations), and a pass of bad +-- arguments that must return nil, Err without throwing. +local T = require("@tests/T") +local Ops = require("@formats/ops/ImageOps") +local Types = require("@formats/Types") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/imageops") + +local t = T.suite("imageops") + +local function image(w: number, h: number, fmt: string, px: string): any + local img = Types.Image.new(w, h, fmt :: any) + buffer.writestring(img.pixels, 0, px) + return img +end + +-- max abs difference and PSNR of two byte strings / buffers +local function diff(a: buffer, b: string): (number, number) + local n = #b + local mx, se = 0, 0 + for i = 0, n - 1 do + local d = math.abs(buffer.readu8(a, i) - string.byte(b, i + 1)) + if d > mx then + mx = d + end + se += d * d + end + local mse = se / n + return mx, if mse == 0 then 99 else 10 * math.log10(255 * 255 / mse) +end + +local rgb = image(Fx.rgb.w, Fx.rgb.h, "rgb8", Fx.rgb.px) +local rgba = image(Fx.rgba.w, Fx.rgba.h, "rgba8", Fx.rgba.px) +local rgba2 = image(Fx.rgba2.w, Fx.rgba2.h, "rgba8", Fx.rgba2.px) + +-- Pillow references +do + local g = Ops.convert(rgb, "gray8") :: any + t:check(buffer.tostring(g.pixels) == Fx.gray, "rgb8 -> gray8 matches Pillow convert('L')") + local ga = Ops.convert(rgba, "gray8") :: any + t:check(buffer.tostring(ga.pixels) == Fx.graya, "rgba8 -> gray8 matches Pillow (alpha ignored)") + local gray = Ops.convert(rgb, "gray8") :: any + local worst = { nearest = 0, bilinear = 0, lanczos = 0 } + for _, c in Fx.resize do + local src = if c.mode == "RGB" then rgb else gray + local r = Ops.resize(src, c.w, c.h, c.filter) :: any + t:check(r and r.width == c.w and r.height == c.h, "resize size") + local mx = diff(r.pixels, c.px) + worst[c.filter] = math.max(worst[c.filter], mx) + t:check(mx <= (if c.filter == "nearest" then 0 else 1), string.format("resize %s %s %dx%d: max error %d", c.filter, c.mode, c.w, c.h, mx)) + end + t:note("resize vs Pillow (%d cases): max error nearest %d, bilinear %d, lanczos %d", #Fx.resize, worst.nearest, worst.bilinear, worst.lanczos) + local minPsnr = 99 + for _, c in Fx.rotate do + local r = Ops.rotate(rgba, c.angle, { expand = c.expand }) :: any + t:check(r and r.width == c.w and r.height == c.h, string.format("rotate %d: size %dx%d, Pillow %dx%d", c.angle, r.width, r.height, c.w, c.h)) + local _, psnr = diff(r.pixels, c.px) + minPsnr = math.min(minPsnr, psnr) + t:check(psnr > 40, string.format("rotate %d: PSNR %.1f", c.angle, psnr)) + end + t:note("rotate vs Pillow (%d cases): min PSNR %.1f dB", #Fx.rotate, minPsnr) + local c = Ops.composite(rgba, rgba2) :: any + local mx = diff(c.pixels, Fx.composite) + t:check(mx == 0, "alpha_composite matches Pillow exactly (max error " .. mx .. ")") +end + +-- conversions between every format +local FORMATS = { "rgba8", "rgba16", "rgbaf32", "rgb8", "gray8", "gray16", "graya8", "alpha8", "yuv420p" } +do + for _, f in FORMATS do + local c = Ops.convert(rgba, f) :: any + t:check(c and c.format == f and c.width == rgba.width, "convert to " .. f) + local back = Ops.convert(c, "rgba8") :: any + t:check(back and back.format == "rgba8", f .. " back to rgba8") + if f == "rgba16" or f == "rgbaf32" then + t:check(buffer.tostring(back.pixels) == buffer.tostring(rgba.pixels), f .. ": lossless round trip") + end + if f == "yuv420p" then + -- a smooth image (4:2:0 drops chroma detail) + local sm = Types.Image.new(40, 30) + for i = 0, 40 * 30 - 1 do + local x, y = i % 40, i // 40 + buffer.writeu32(sm.pixels, i * 4, 0xFF000000 + (x * 6) + (y * 8) * 256 + ((x + y) * 3) * 65536) + end + local yb = Ops.convert(Ops.convert(sm, "yuv420p") :: any, "rgba8") :: any + local _, psnr = diff(yb.pixels, buffer.tostring(sm.pixels)) + t:check(psnr > 38, string.format("yuv420p round trip PSNR %.1f", psnr)) + end + for _, g in FORMATS do + t:check(Ops.convert(c, g) ~= nil, f .. " -> " .. g) + end + end + local g16 = Ops.convert(Ops.convert(rgb, "gray8") :: any, "gray16") :: any + t:eq(buffer.readu16(g16.pixels, 0), buffer.readu8((Ops.convert(rgb, "gray8") :: any).pixels, 0) * 257, "8 -> 16 bit is * 257") + local f = Types.Image.new(1, 1, "rgbaf32") + buffer.writef32(f.pixels, 0, 1.5) + buffer.writef32(f.pixels, 4, -0.2) + buffer.writef32(f.pixels, 8, 0.5) + buffer.writef32(f.pixels, 12, 1) + local b = Ops.convert(f, "rgba8") :: any + t:check(buffer.readu8(b.pixels, 0) == 255 and buffer.readu8(b.pixels, 1) == 0 and buffer.readu8(b.pixels, 2) == 128, "float -> 8 bit clamps and rounds") +end + +-- geometry properties on every format +do + for _, f in FORMATS do + local img = Ops.convert(rgba, f) :: any + local s = buffer.tostring(img.pixels) + local r = img + for _ = 1, 4 do + r = Ops.rotate90(r, 1) + end + if f ~= "yuv420p" then + t:check(buffer.tostring(r.pixels) == s, f .. ": four quarter turns are the identity") + t:check(buffer.tostring((Ops.flip(Ops.flip(img, "h") :: any, "h") :: any).pixels) == s, f .. ": flip h twice") + t:check(buffer.tostring((Ops.flip(Ops.flip(img, "v") :: any, "v") :: any).pixels) == s, f .. ": flip v twice") + local q = Ops.rotate90(img, 1) :: any + t:check(q.width == img.height and q.height == img.width, f .. ": a quarter turn swaps the size") + t:check(buffer.tostring((Ops.rotate90(img, 2) :: any).pixels) == buffer.tostring((Ops.flip(Ops.flip(img, "h") :: any, "v") :: any).pixels), f .. ": half turn = both flips") + t:check(buffer.tostring((Ops.rotate(img, 90) :: any).pixels) == buffer.tostring(q.pixels), f .. ": rotate 90 = one quarter turn") + end + local c = Ops.crop(img, -5, 10, 20, 100) :: any + t:check(c and c.width == 15 and c.height == img.height - 10, f .. ": crop clipped") + for _, filter in { "nearest", "bilinear", "lanczos" } do + local z = Ops.resize(img, 23, 31, filter) :: any + t:check(z and z.width == 23 and z.height == 31 and z.format == f, f .. ": resize " .. filter) + end + local rr = Ops.rotate(img, 33) :: any + t:check(rr and rr.format == f, f .. ": rotate 33") + end + -- crop content, nearest identity, ccw convention + local c = Ops.crop(rgba, 3, 4, 5, 6) :: any + t:check(buffer.readu32(c.pixels, 0) == buffer.readu32(rgba.pixels, (4 * rgba.width + 3) * 4), "crop origin") + t:check(buffer.tostring((Ops.resize(rgba, rgba.width, rgba.height, "lanczos") :: any).pixels) == buffer.tostring(rgba.pixels), "same-size resize is a copy") + local q = Ops.rotate90(rgba, 1) :: any -- ccw: the top-right pixel goes to the top-left + t:eq(buffer.readu32(q.pixels, 0), buffer.readu32(rgba.pixels, (rgba.width - 1) * 4), "rotate90 is counter-clockwise") +end + +-- pixels, fill, premultiply +do + for _, f in FORMATS do + local img = Ops.new(3, 2, f) :: any + t:check(img and img.format == f, "new " .. f) + if f ~= "yuv420p" then + local max = if f == "rgba16" or f == "gray16" then 65535 elseif f == "rgbaf32" then 1 else 255 + t:check(Ops.setPixel(img, 2, 1, max, max, max, max), f .. ": setPixel") + local r, g, b, a = Ops.getPixel(img, 2, 1) + t:check(r == max and g == max and b == max and a == max, f .. ": getPixel after setPixel") + Ops.fill(img, 0, 0, 0, 0) + local r2 = Ops.getPixel(img, 2, 1) + t:check(r2 == (if f == "alpha8" then 255 else 0), f .. ": fill") + else + t:check(Ops.setPixel(img, 0, 0, 1, 2, 3) == nil, "setPixel refuses yuv420p") + t:check(Ops.getPixel(img, 2, 1) ~= nil, "getPixel on yuv420p") + end + end + local p = Ops.premultiply(rgba) :: any + local u = Ops.unpremultiply(p) :: any + local worst = 0 + for i = 0, rgba.width * rgba.height - 1 do + local a = buffer.readu8(rgba.pixels, i * 4 + 3) + t:check(buffer.readu8(p.pixels, i * 4) <= a, "premultiplied <= alpha") + if a >= 32 then + for c = 0, 2 do + worst = math.max(worst, math.abs(buffer.readu8(u.pixels, i * 4 + c) - buffer.readu8(rgba.pixels, i * 4 + c))) + end + end + end + t:check(worst <= 4, "premultiply round trip error " .. worst .. " (alpha >= 32)") + t:note("premultiply round trip: max error %d for alpha >= 32", worst) +end + +-- blit +do + local dst = Ops.new(10, 10, "rgba8") :: any + Ops.fill(dst, 10, 20, 30, 255) + local src = Ops.new(4, 4, "rgba8") :: any + Ops.fill(src, 200, 100, 50, 255) + Ops.blit(dst, src, -2, 8) + t:check(select(1, Ops.getPixel(dst, 0, 8)) == 200 and select(1, Ops.getPixel(dst, 1, 9)) == 200, "blit clipped at the left / bottom") + t:check(select(1, Ops.getPixel(dst, 2, 8)) == 10 and select(1, Ops.getPixel(dst, 0, 7)) == 10, "blit stays inside its rectangle") + Ops.fill(src, 0, 0, 0, 0) + Ops.blit(dst, src, 0, 0) + t:check(select(1, Ops.getPixel(dst, 0, 0)) == 10, "over with a transparent source keeps dst") + Ops.blit(dst, src, 0, 0, { blend = "source" }) + t:check(select(4, Ops.getPixel(dst, 0, 0)) == 0, "source blend copies alpha") + Ops.fill(src, 255, 255, 255, 255) + Ops.blit(dst, src, 5, 5, { opacity = 0.5 }) + local r = Ops.getPixel(dst, 5, 5) + t:check(math.abs(r - 133) <= 1, "opacity 0.5 over (10 -> " .. r .. ")") + -- rgb8 destination, gray source, float destination + local d3 = Ops.convert(dst, "rgb8") :: any + t:check(Ops.blit(d3, Ops.convert(src, "graya8") :: any, 1, 1) == d3, "blit onto rgb8") + local df = Ops.convert(dst, "rgbaf32") :: any + t:check(Ops.blit(df, src, 0, 0, { opacity = 0.25 }) == df, "blit onto rgbaf32") + local dy = Ops.convert(dst, "yuv420p") :: any + t:check(Ops.blit(dy, src, 3, 3) == dy, "blit onto yuv420p") +end + +-- animation helpers +do + local W, H = 6, 4 + local function solid(w: number, h: number, r: number, a: number): any + local im = Ops.new(w, h, "rgba8") :: any + Ops.fill(im, r, 0, 0, a) + return im + end + local anim = Ops.new(W, H, "rgba8") :: any + anim.frames = { + { image = solid(W, H, 10, 255), delay = 0.1, x = 0, y = 0, dispose = "none", blend = "source" }, + { image = solid(2, 2, 20, 255), delay = 0.2, x = 1, y = 1, dispose = "background", blend = "over" }, + { image = solid(2, 2, 30, 255), delay = 0.3, x = 3, y = 1, dispose = "previous", blend = "over" }, + { image = solid(1, 1, 40, 128), delay = 0.4, x = 5, y = 3, dispose = "none", blend = "over" }, + } + local fr = Ops.coalesce(anim) :: any + t:eq(#fr, 4, "coalesce frame count") + local function at(i: number, x: number, y: number): (number, number) + local r, _, _, a = Ops.getPixel(fr[i], x, y) + return r, a + end + t:check(at(1, 0, 0) == 10 and at(1, 1, 1) == 10, "frame 1") + t:check(at(2, 1, 1) == 20 and at(2, 2, 2) == 20 and at(2, 0, 0) == 10, "frame 2 drawn at 1, 1") + local r3, a3 = at(3, 1, 1) + t:check(r3 == 0 and a3 == 0, "frame 2 disposed to background before frame 3") + t:check(at(3, 3, 1) == 30, "frame 3 drawn") + t:check(at(4, 3, 1) == 10, "frame 3 disposed to previous before frame 4") + local r4 = at(4, 5, 3) + t:check(r4 > 10 and r4 < 40, "frame 4 blends over") + t:eq(Ops.frameCount(anim), 4, "frameCount") + t:eq(Ops.durations(anim)[3], 0.3, "durations") + t:eq(Ops.frameCount(rgba), 1, "frameCount of a still") + t:check((Ops.coalesce(rgba) :: any)[1] == rgba, "coalesce of a still") + local made = Ops.fromFrames({ fr[1], fr[2], fr[3] }, { 0.5, 0.25 }) :: any + t:check(made and #made.frames == 3 and made.frames[2].delay == 0.25 and made.frames[3].delay == 0.1, "fromFrames delays") + t:check(buffer.tostring(made.pixels) == buffer.tostring(fr[1].pixels), "fromFrames pixels = frame 1") + local again = Ops.coalesce(made) :: any + t:check(buffer.tostring(again[3].pixels) == buffer.tostring(fr[3].pixels), "coalesce(fromFrames) round trip") + t:check(Ops.fromFrames({ fr[1], rgba }) == nil, "fromFrames refuses mixed sizes") +end + +-- bad arguments: nil, Err, never a throw +do + local rand = T.rng(5) + local junk: { any } = { nil, 0, -1, 1.5, 2 ^ 40, "x", {}, true, 0 / 0, math.huge, -7 } + local imgs: { any } = { rgba, rgb, {}, { pixels = buffer.create(1), width = 5, height = 5, format = "rgba8" }, Types.Image.new(1, 1, "alpha8"), Ops.convert(rgba, "yuv420p") } + local calls = { + function(a: any, b: any, c: any, d: any) + return Ops.convert(a, b) + end, + function(a: any, b: any, c: any, d: any) + return Ops.crop(a, b, c, d, b) + end, + function(a: any, b: any, c: any, _d: any) + return Ops.resize(a, b, c, "lanczos") + end, + function(a: any, b: any, c: any, _d: any) + return Ops.resize(a, b, c, b) + end, + function(a: any, b: any, _c: any, _d: any) + return Ops.rotate(a, b) + end, + function(a: any, b: any, _c: any, _d: any) + return Ops.rotate90(a, b) + end, + function(a: any, b: any, _c: any, _d: any) + return Ops.flip(a, b) + end, + function(a: any, b: any, c: any, d: any) + return Ops.blit(a, d, b, c) + end, + function(a: any, b: any, c: any, d: any) + return Ops.blit(a, a, b, c, { opacity = d }) + end, + function(a: any, b: any, c: any, _d: any) + return Ops.getPixel(a, b, c) + end, + function(a: any, b: any, c: any, d: any) + return Ops.setPixel(a, b, c, d, d, d) + end, + function(a: any, b: any, _c: any, _d: any) + return Ops.new(a, b, "rgba8") + end, + function(a: any, _b: any, _c: any, _d: any) + return Ops.coalesce(a) + end, + function(a: any, b: any, _c: any, _d: any) + return Ops.fromFrames({ a, b } :: any) + end, + function(a: any, b: any, c: any, d: any) + return Ops.fill(a, b, c, d) + end, + } + local tries, threw = 0, 0 + for _ = 1, 600 do + local f = calls[1 + rand(#calls)] + local a = imgs[1 + rand(#imgs)] + local args = { junk[1 + rand(#junk)], junk[1 + rand(#junk)], junk[1 + rand(#junk)] } + if rand(3) == 0 then + args[3] = imgs[1 + rand(#imgs)] + end + tries += 1 + local ok, err = pcall(f, a, args[1], args[2], args[3]) + if not ok then + threw += 1 + print(" THREW: " .. tostring(err)) + end + end + t:check(threw == 0, "bad arguments never throw (" .. threw .. " of " .. tries .. ")") + t:note("bad arguments: %d calls, none threw", tries) + local _, e = Ops.resize(rgba, 100000, 100000) + t:check(e and e.code == Err.LIMIT, "resize over the pixel limit") + local _, e2 = Ops.crop(rgba, 100, 100, 5, 5) + t:check(e2 and e2.code == Err.ARG, "empty crop") + local _, e3 = Ops.convert(rgba, "cmyk") + t:check(e3 and e3.code == Err.ARG, "unknown format") +end + +t:done() diff --git a/tests/ops/layerops.luau b/tests/ops/layerops.luau new file mode 100644 index 0000000..94f4692 --- /dev/null +++ b/tests/ops/layerops.luau @@ -0,0 +1,144 @@ +-- ops/LayerOps + codecs/Blend tests: blend mode formulas on single pixels against hand-computed W3C values, opacity, +-- masks, clipping, isolated vs pass-through groups, hidden layers, frames, leaves, bad arguments. (Whole-document +-- flattening against psd-tools is in tests/layered/psd.luau.) +local T = require("@tests/T") +local LayerOps = require("@formats/ops/LayerOps") +local Blend = require("@formats/codecs/Blend") +local Types = require("@formats/Types") +local Err = require("@formats/core/Err") + +local t = T.suite("layerops") + +local function px(r: number, g: number, b: number, a: number): Types.Image + local img = Types.Image.new(1, 1) + buffer.writeu8(img.pixels, 0, r) + buffer.writeu8(img.pixels, 1, g) + buffer.writeu8(img.pixels, 2, b) + buffer.writeu8(img.pixels, 3, a) + return img +end +local function get(img: any): (number, number, number, number) + local p = img.pixels + return buffer.readu8(p, 0), buffer.readu8(p, 1), buffer.readu8(p, 2), buffer.readu8(p, 3) +end +local function doc(layers: { any }): any + local d = Types.Layered.new(1, 1) + d.layers = layers + return d +end +local L = Types.Layered.layer + +-- separable modes on opaque pixels: backdrop (200, 100, 50), source (100, 150, 250); values from the W3C formulas +local cases = { + normal = { 100, 150, 250 }, + multiply = { 78, 59, 49 }, + screen = { 222, 191, 251 }, + darken = { 100, 100, 50 }, + lighten = { 200, 150, 250 }, + difference = { 100, 50, 200 }, + exclusion = { 143, 132, 202 }, + linearDodge = { 255, 250, 255 }, + linearBurn = { 45, 0, 45 }, + subtract = { 100, 0, 0 }, + overlay = { 188, 118, 98 }, + hardLight = { 157, 127, 247 }, + colorDodge = { 255, 243, 255 }, + colorBurn = { 115, 0, 46 }, + hardMix = { 255, 0, 255 }, +} +for mode, want in cases do + local top = L("top", px(100, 150, 250, 255)) + top.blend = mode + local img = LayerOps.flatten(doc({ L("bottom", px(200, 100, 50, 255)), top })) :: any + local r, g, b, a = get(img) + t:check(math.abs(r - want[1]) <= 1 and math.abs(g - want[2]) <= 1 and math.abs(b - want[3]) <= 1 and a == 255, string.format("%s: got %d %d %d, want %d %d %d", mode, r, g, b, want[1], want[2], want[3])) +end +-- non-separable: luminosity of the source on the backdrop's hue +do + local top = L("top", px(255, 255, 255, 255)) + top.blend = "luminosity" + local r, g, b = get(LayerOps.flatten(doc({ L("bottom", px(255, 0, 0, 255)), top }))) + t:check(r == 255 and g == 255 and b == 255, "luminosity of white") + top.blend = "color" + local r2, g2, b2 = get(LayerOps.flatten(doc({ L("bottom", px(128, 128, 128, 255)), top }))) + t:check(r2 == g2 and g2 == b2 and math.abs(r2 - 128) <= 1, "colour of a grey source keeps the grey") +end +-- opacity and alpha: 50% red over opaque blue +do + local top = L("top", px(255, 0, 0, 255)) + top.opacity = 0.5 + local r, g, b, a = get(LayerOps.flatten(doc({ L("bottom", px(0, 0, 255, 255)), top }))) + t:check(math.abs(r - 128) <= 1 and g == 0 and math.abs(b - 128) <= 1 and a == 255, "opacity mix") + local r2, _, _, a2 = get(LayerOps.flatten(doc({ top }))) + t:check(r2 == 255 and math.abs(a2 - 128) <= 1, "over transparent: alpha scales") +end +-- hidden layers, masks, clipping +do + local top = L("top", px(255, 0, 0, 255)) + top.visible = false + local r = get(LayerOps.flatten(doc({ L("bottom", px(0, 0, 255, 255)), top }))) + t:eq(r, 0, "hidden layer skipped") + local r2 = get(LayerOps.flatten(doc({ L("bottom", px(0, 0, 255, 255)), top }), { hidden = true })) + t:eq(r2, 255, "hidden = true includes it") + top.visible = true + local m = Types.Image.new(1, 1, "gray8") + top.mask = { image = m, x = 0, y = 0, default = 255 } + t:eq((get(LayerOps.flatten(doc({ L("bottom", px(0, 0, 255, 255)), top })))), 0, "black mask hides") + top.mask = { image = m, x = 5, y = 5, default = 255 } + t:eq((get(LayerOps.flatten(doc({ L("bottom", px(0, 0, 255, 255)), top })))), 255, "outside the mask: default white") + top.mask = nil + local base = L("base", px(0, 255, 0, 0)) -- transparent base: the clipped layer shows nowhere + top.clip = true + local r3, g3, b3, a3 = get(LayerOps.flatten(doc({ base, top }))) + t:check(a3 == 0, "clipped to a transparent base: " .. r3 .. g3 .. b3 .. a3) + base = L("base", px(0, 255, 0, 255)) + local r4, g4 = get(LayerOps.flatten(doc({ base, top }))) + t:check(r4 == 255 and g4 == 0, "clipped to an opaque base") +end +-- groups: an isolated multiply group multiplies its composite; pass-through multiplies each child onto the backdrop +do + local child = L("child", px(128, 128, 128, 255)) + child.blend = "multiply" + local g = Types.Layered.group("g", { child }) + local bottom = L("bottom", px(200, 200, 200, 255)) + local r = get(LayerOps.flatten(doc({ bottom, g }))) + t:check(math.abs(r - 100) <= 1, "pass-through: child multiplies the backdrop: " .. r) + g.blend = "normal" + local r2 = get(LayerOps.flatten(doc({ bottom, g }))) + t:eq(r2, 128, "isolated group: the child multiplies nothing") + g.blend = "passThrough" + g.opacity = 0.5 + local r3 = get(LayerOps.flatten(doc({ bottom, g }))) + t:check(math.abs(r3 - 150) <= 1, "pass-through opacity mixes before / after: " .. r3) +end +-- frames, leaves, flattenFrames +do + local d = doc({ L("a", px(1, 2, 3, 255)) }) + d.frames = { { layers = d.layers, delay = 0.1 }, { layers = { L("b", px(9, 8, 7, 255)) }, delay = 0.2 } } + t:eq((get(LayerOps.flatten(d, { frame = 2 }))), 9, "frame 2") + local anim = LayerOps.flattenFrames(d) :: any + t:check(anim.frames and #anim.frames == 2 and anim.frames[2].delay == 0.2, "flattenFrames") + local _, e = LayerOps.flatten(d, { frame = 5 }) + t:check(e and e.code == Err.ARG, "missing frame") + local names = {} + for l, depth in LayerOps.leaves({ L("x", px(0, 0, 0, 0)), Types.Layered.group("g", { L("y", px(0, 0, 0, 0)), Types.Layered.group("h", { L("z", px(0, 0, 0, 0)) }) }) }) do + table.insert(names, (l :: any).name .. depth) + end + t:eq(table.concat(names, " "), "x0 y1 z2", "leaves with depth") + local _, e2 = LayerOps.flatten(5 :: any) + t:check(e2 and e2.code == Err.ARG, "flatten of a non-Layered") +end +-- Blend.composite clips its rectangles (no throw, nothing outside) +do + local dst = buffer.create(4 * 4 * 4) + local src = buffer.create(3 * 3 * 4) + buffer.fill(src, 0, 255) + for _, pos in { { -2, -2 }, { 3, 3 }, { -10, 0 }, { 100, 100 } } do + Blend.composite(dst, 4, 4, src, 3, 3, pos[1], pos[2], 1, "multiply") + end + Blend.composite(dst, 4, 4, src, 3, 3, 0, 0, 1, "nope") + Blend.composite(dst, 4, 4, src, 30, 30, 0, 0, 1, "normal") -- src too short: ignored + t:eq(buffer.readu8(dst, 0), 255, "composite clipping") + t:check(Blend.MODES.softLight and not Blend.MODES.nope, "MODES") +end +t:done() diff --git a/tests/ops/meshops.luau b/tests/ops/meshops.luau new file mode 100644 index 0000000..9b5e153 --- /dev/null +++ b/tests/ops/meshops.luau @@ -0,0 +1,355 @@ +-- ops/MeshOps tests: triangulate (strips, fans, convex / concave / degenerate n-gons), transform (normals by the inverse +-- transpose, mirrors flip the winding), computeNormals (smooth sphere normals = the radial direction, flat cube normals), +-- computeTangents (orthogonal, unit, handedness), weld / unweld, bounds, merge (instances baked, mixed attributes), +-- scale / setUnit / setUp, greedy voxel meshing (exposed face area, winding, the checkerboard worst case), errors. +-- Analytic references (closed forms); the format tests check merge / bounds against assimp and trimesh. +local T = require("@tests/T") +local MeshOps = require("@formats/ops/MeshOps") +local Types = require("@formats/Types") +local Err = require("@formats/core/Err") +local F = require("@formats") + +local t = T.suite("meshops") +local S = Types.Scene + +local function f32(list: { number }, comps: number): Types.Accessor + local a = S.accessor(nil, "f32", comps, #list // comps) + for i, v in list do + buffer.writef32(a.data, (i - 1) * 4, v) + end + return a +end +local function u32(list: { number }): Types.Accessor + local a = S.accessor(nil, "u32", 1, #list) + for i, v in list do + buffer.writeu32(a.data, (i - 1) * 4, v) + end + return a +end +local function idx(acc: Types.Accessor): { number } + local out = {} + for i = 0, acc.count - 1 do + out[i + 1] = buffer.readu32(acc.data, i * 4) + end + return out +end +local function get(acc: Types.Accessor, i: number, c: number): number + return (S.reader(acc) :: any)(i, c) +end +local function near(a: number, b: number, eps: number?): boolean + return math.abs(a - b) <= (eps or 1e-5) +end +local function area(prim: any): number + local pos, ind = prim.attributes.POSITION, prim.indices + local total = 0 + for tri = 0, ind.count // 3 - 1 do + local a, b, c = buffer.readu32(ind.data, tri * 12), buffer.readu32(ind.data, tri * 12 + 4), buffer.readu32(ind.data, tri * 12 + 8) + local e1 = { get(pos, b, 0) - get(pos, a, 0), get(pos, b, 1) - get(pos, a, 1), get(pos, b, 2) - get(pos, a, 2) } + local e2 = { get(pos, c, 0) - get(pos, a, 0), get(pos, c, 1) - get(pos, a, 1), get(pos, c, 2) - get(pos, a, 2) } + local x, y, z = e1[2] * e2[3] - e1[3] * e2[2], e1[3] * e2[1] - e1[1] * e2[3], e1[1] * e2[2] - e1[2] * e2[1] + total += math.sqrt(x * x + y * y + z * z) / 2 + end + return total +end + +-- a unit cube as 6 quads (polygons), 24 corners +local function cube(): Types.Primitive + local P = {} + local faces = { + { { 0, 0, 0 }, { 0, 1, 0 }, { 1, 1, 0 }, { 1, 0, 0 } }, + { { 0, 0, 1 }, { 1, 0, 1 }, { 1, 1, 1 }, { 0, 1, 1 } }, + { { 0, 0, 0 }, { 1, 0, 0 }, { 1, 0, 1 }, { 0, 0, 1 } }, + { { 0, 1, 0 }, { 0, 1, 1 }, { 1, 1, 1 }, { 1, 1, 0 } }, + { { 0, 0, 0 }, { 0, 0, 1 }, { 0, 1, 1 }, { 0, 1, 0 } }, + { { 1, 0, 0 }, { 1, 1, 0 }, { 1, 1, 1 }, { 1, 0, 1 } }, + } + local ind, sizes = {}, {} + for _, f in faces do + for _, v in f do + table.insert(P, v[1]) + table.insert(P, v[2]) + table.insert(P, v[3]) + table.insert(ind, #ind) + end + table.insert(sizes, 4) + end + return { attributes = { POSITION = f32(P, 3) }, indices = u32(ind), faces = u32(sizes), mode = "polygons" } +end + +-- triangulate +do + local c = cube() + local tri = MeshOps.triangulate(c) :: any + t:check(tri.mode == "triangles" and tri.indices.count == 36, "cube quads -> 12 triangles") + t:check(near(area(tri), 6), "cube area 6") + -- every triangle faces outward (the cube is centred at 0.5) + local nm = MeshOps.computeNormals(MeshOps.unweld(tri)) :: any + local outward = true + for v = 0, nm.attributes.POSITION.count - 1 do + local d = 0 + for k = 0, 2 do + d += (get(nm.attributes.POSITION, v, k) - 0.5) * get(nm.attributes.NORMAL, v, k) + end + if d <= 0 then + outward = false + end + end + t:check(outward, "triangulated winding keeps the faces outward") + -- strips and fans + local P = f32({ 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 2, 0, 1, 2, 0 }, 3) + local strip = MeshOps.triangulate({ attributes = { POSITION = P }, mode = "triangle_strip" }) :: any + t:check(table.concat(idx(strip.indices), ",") == "0,1,2,2,1,3,2,3,4,4,3,5", "strip unrolled with alternating winding") + t:check(near(area(strip), 2), "strip area") + local fan = MeshOps.triangulate({ attributes = { POSITION = P }, indices = u32({ 0, 1, 3, 2 }), mode = "triangle_fan" }) :: any + t:check(table.concat(idx(fan.indices), ",") == "0,1,3,0,3,2", "fan unrolled") + -- a concave n-gon (a star) by ear clipping vs the shoelace area + local star, sidx = {}, {} + local shoelace = 0 + for k = 0, 9 do + local r = if k % 2 == 0 then 2 else 0.8 + local a = math.pi * 2 * k / 10 + table.insert(star, r * math.cos(a)) + table.insert(star, 0) + table.insert(star, -r * math.sin(a)) + table.insert(sidx, k) + end + for k = 0, 9 do + local x1, z1 = star[k * 3 + 1], star[k * 3 + 3] + local x2, z2 = star[((k + 1) % 10) * 3 + 1], star[((k + 1) % 10) * 3 + 3] + shoelace += x1 * z2 - x2 * z1 + end + local sp = { attributes = { POSITION = f32(star, 3) }, indices = u32(sidx), faces = u32({ 10 }), mode = "polygons" } + local ear = MeshOps.triangulate(sp) :: any + t:check(ear.indices.count == 24 and near(area(ear), math.abs(shoelace) / 2, 1e-4), "star: ear clipping area " .. area(ear) .. " = " .. math.abs(shoelace) / 2) + t:check(area(MeshOps.triangulate(sp, { method = "fan" }) :: any) ~= area(ear), "the fan gets a concave polygon wrong") + -- degenerate polygons: collinear corners, faces of 1 or 2 corners are dropped + local deg = { attributes = { POSITION = f32({ 0, 0, 0, 1, 0, 0, 2, 0, 0, 3, 0, 0 }, 3) }, indices = u32({ 0, 1, 2, 3, 0, 1 }), faces = u32({ 4, 2 }), mode = "polygons" } + local d = MeshOps.triangulate(deg) :: any + t:check(d and d.indices.count == 6 and near(area(d), 0), "collinear quad: two zero-area triangles, the 2-gon dropped") + local lines = { attributes = { POSITION = P }, mode = "lines" } + t:check(MeshOps.triangulate(lines) == lines, "lines come back unchanged") +end + +-- transform +do + local tri = MeshOps.triangulate(cube()) :: any + MeshOps.computeNormals(MeshOps.unweld(tri)) + local soup = MeshOps.computeNormals(MeshOps.unweld(tri)) :: any + -- non-uniform scale: normals by the inverse transpose stay perpendicular to the faces + local m = { 2, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0.5, 0, 10, 20, 30, 1 } + MeshOps.transform(soup, m) + local lo, hi = MeshOps.bounds(soup) + t:check(lo and near(lo[1], 10) and near(hi[1], 12) and near(lo[2], 20) and near(hi[2], 21) and near(lo[3], 30) and near(hi[3], 30.5), "transformed bounds") + local ok = true + for tri0 = 0, soup.attributes.POSITION.count // 3 - 1 do + local a = tri0 * 3 + for e = 1, 2 do + local d = 0 + for k = 0, 2 do + d += (get(soup.attributes.POSITION, a + e, k) - get(soup.attributes.POSITION, a, k)) * get(soup.attributes.NORMAL, a, k) + end + if math.abs(d) > 1e-5 then + ok = false + end + end + end + t:check(ok, "normals stay perpendicular under non-uniform scale") + -- a mirror flips the winding: recomputed normals still agree with the transformed ones + local mir = MeshOps.computeNormals(MeshOps.unweld(MeshOps.triangulate(cube()) :: any)) :: any + local before = MeshOps.computeNormals(MeshOps.unweld(MeshOps.triangulate(cube()) :: any)) :: any + MeshOps.transform(mir, { -1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }) + local saved = buffer.tostring(mir.attributes.NORMAL.data) + local re = MeshOps.computeNormals(MeshOps.unweld(mir)) :: any + local agree = true + for v = 0, re.attributes.NORMAL.count - 1 do + for k = 0, 2 do + if not near(get(re.attributes.NORMAL, v, k), buffer.readf32(buffer.fromstring(saved), (v * 3 + k) * 4), 1e-5) then + agree = false + end + end + end + t:check(agree and before ~= nil, "mirror: winding reversed (recomputed normals = transformed normals)") + local _, e = MeshOps.transform(mir, { 1, 2, 3 }) + t:check(e and e.code == Err.ARG, "transform: a bad matrix") +end + +-- normals, tangents on a UV sphere +do + local rings, segs = 16, 32 + local P, UV, ind = {}, {}, {} + for i = 0, rings do + local th = math.pi * i / rings + for j = 0, segs do + local ph = 2 * math.pi * j / segs + table.insert(P, math.sin(th) * math.cos(ph)) + table.insert(P, math.cos(th)) + table.insert(P, math.sin(th) * math.sin(ph)) + table.insert(UV, j / segs) + table.insert(UV, i / rings) + end + end + for i = 0, rings - 1 do + for j = 0, segs - 1 do + local a, b = i * (segs + 1) + j, i * (segs + 1) + j + 1 + local c, d = a + segs + 1, b + segs + 1 + for _, v in { a, b, c, b, d, c } do + table.insert(ind, v) + end + end + end + local sphere: any = { attributes = { POSITION = f32(P, 3), TEXCOORD_0 = f32(UV, 2) }, indices = u32(ind), mode = "triangles" } + MeshOps.computeNormals(sphere) + -- smooth normals of interior vertices (not on the seam / poles) point along the radius + local worst = 0 + for i = 1, rings - 1 do + for j = 1, segs - 1 do + local v = i * (segs + 1) + j + local dot = 0 + for k = 0, 2 do + dot += get(sphere.attributes.NORMAL, v, k) * get(sphere.attributes.POSITION, v, k) + end + worst = math.max(worst, 1 - dot) + end + end + t:check(worst < 1e-3, "sphere normals = radial directions (worst 1 - cos " .. worst .. ")") + t:check(get(sphere.attributes.NORMAL, (rings // 2) * (segs + 1) + 3, 1) < 1e-3, "outward, not inward") + MeshOps.computeTangents(sphere) + local tan = sphere.attributes.TANGENT + t:check(tan and tan.components == 4, "TANGENT vec4") + local ortho, unit, hand = 0, 0, true + for i = 1, rings - 1 do + for j = 1, segs - 1 do + local v = i * (segs + 1) + j + local d, l = 0, 0 + for k = 0, 2 do + d += get(tan, v, k) * get(sphere.attributes.NORMAL, v, k) + l += get(tan, v, k) ^ 2 + end + ortho = math.max(ortho, math.abs(d)) + unit = math.max(unit, math.abs(l - 1)) + if math.abs(get(tan, v, 3)) ~= 1 then + hand = false + end + -- u grows with phi: the tangent follows d/dphi = (-sin phi, 0, cos phi) + local ph = 2 * math.pi * j / segs + if get(tan, v, 0) * -math.sin(ph) + get(tan, v, 2) * math.cos(ph) < 0.99 then + hand = false + end + end + end + t:check(ortho < 1e-5 and unit < 1e-5 and hand, string.format("tangents orthogonal (%g), unit (%g), along +u", ortho, unit)) + local _, e = MeshOps.computeTangents({ attributes = { POSITION = f32(P, 3) }, indices = u32(ind), mode = "triangles" }) + t:check(e and e.code == Err.ARG, "computeTangents without uv") + -- flat normals on the cube: 36 corners, axis-aligned + local flat = MeshOps.computeNormals(MeshOps.triangulate(cube()) :: any, { flat = true }) :: any + t:check(flat.attributes.NORMAL.count == 36 and flat.indices == nil, "flat: unwelded corners") + local axis = true + for v = 0, 35 do + local s = math.abs(get(flat.attributes.NORMAL, v, 0)) + math.abs(get(flat.attributes.NORMAL, v, 1)) + math.abs(get(flat.attributes.NORMAL, v, 2)) + if not near(s, 1) then + axis = false + end + end + t:check(axis, "flat cube normals are axis-aligned") +end + +-- weld +do + local soup = MeshOps.unweld(MeshOps.triangulate(cube()) :: any) :: any + t:eq(soup.attributes.POSITION.count, 36, "unwelded cube: 36 vertices") + local w = MeshOps.weld(soup) :: any + t:check(w.attributes.POSITION.count == 8 and w.indices.count == 36, "welded by position: 8") + t:check(near(area(w), 6), "weld keeps the surface") + local withN = MeshOps.weld(MeshOps.computeNormals(soup, { flat = true }) :: any) :: any + t:eq(withN.attributes.POSITION.count, 24, "welded with flat normals: 24") + -- an epsilon merges near-identical positions + local P = f32({ 0, 0, 0, 1, 0, 0, 0, 1, 0, 1e-7, 0, 0, 1, 1e-7, 0, 0, 1, 1e-7 }, 3) + local two = { attributes = { POSITION = P }, mode = "triangles" } + t:eq((MeshOps.weld(two) :: any).attributes.POSITION.count, 6, "exact: 6") + t:eq((MeshOps.weld(two, { epsilon = 1e-4 }) :: any).attributes.POSITION.count, 3, "epsilon: 3") + local positionsOnly = MeshOps.weld(withN, { positionsOnly = true }) :: any + t:eq(positionsOnly.attributes.POSITION.count, 8, "positionsOnly: 8") +end + +-- merge, bounds +do + local s = S.new() + local tri = MeshOps.triangulate(cube()) :: any + tri.attributes.COLOR_0 = S.accessor(nil, "unorm8", 4, tri.attributes.POSITION.count) + buffer.fill(tri.attributes.COLOR_0.data, 0, 255) + s.meshes[1] = { primitives = { tri } } + local other = { attributes = { POSITION = f32({ 0, 0, 0, 1, 0, 0, 0, 1, 0 }, 3), _CUSTOM = S.accessor(nil, "u16", 1, 3) }, mode = "triangles", material = 2 } + s.meshes[2] = { primitives = { other } } + s.nodes = { + { children = { 2, 3 } }, + { children = {}, mesh = 1, translation = { 10, 0, 0 } }, + { children = {}, mesh = 1, translation = { -10, 0, 0 }, scale = { 2, 2, 2 } }, + { children = {}, mesh = 2, rotation = { 0, 0, math.sqrt(0.5), math.sqrt(0.5) } }, + } + s.roots = { 1, 4 } + local m = MeshOps.merge(s) :: any + t:check(m.indices.count == 36 * 2 + 3, "two cube instances and a triangle") + t:check(near(area(m), 6 + 24 + 0.5), "instances baked (scale 2: area x4)") + t:check(m.attributes.COLOR_0 and m.attributes._CUSTOM and m.attributes.COLOR_0.type == "f32", "attributes unioned (f32)") + local white = get(m.attributes.COLOR_0, m.attributes.POSITION.count - 1, 0) + t:eq(white, 1, "missing colours are white") + local lo, hi = MeshOps.bounds(s) + t:check(lo and near(lo[1], -10) and near(hi[1], 11) and near(lo[2], 0) and near(hi[2], 2), "scene bounds in world space") + local byMat = MeshOps.merge(s, { byMaterial = true }) :: any + t:check(#byMat == 2 and byMat[1].material == nil and byMat[2].material == 2, "byMaterial") + local _, e = MeshOps.merge(5 :: any) + t:check(e and e.code == Err.ARG, "merge junk") +end + +-- units and up axis +do + local s = S.fromPrimitive(MeshOps.triangulate(cube()) :: any) + s.nodes[1].translation = { 1, 2, 3 } + s.meta.unit = 0.01 -- centimetres + MeshOps.setUnit(s, 1) + local lo, hi = MeshOps.bounds(s) + t:check(lo and near(lo[1], 0.01) and near(hi[1], 0.02) and near(lo[3], 0.03), "cm -> m") + t:eq(s.meta.unit, 1, "meta.unit updated") + s.meta.up = "z" + MeshOps.setUp(s, "y") + local lo2, hi2 = MeshOps.bounds(s) + -- z-up (x, y, z) -> y-up (x, z, -y) + t:check(lo2 and near(lo2[2], 0.03) and near(hi2[2], 0.04) and near(lo2[3], -0.03) and near(hi2[3], -0.02), "z-up -> y-up") + t:check(MeshOps.setUp(s, "x" :: any) == nil, "setUp: bad axis") +end + +-- greedy voxels +do + local v = Types.Voxels.new(4, 4, 4) + for x = 0, 3 do + for y = 0, 3 do + for z = 0, 3 do + Types.Voxels.set(v, x, y, z, 1) + end + end + end + local p = MeshOps.voxelsToPrimitive(v, { pivot = "corner" }) :: any + t:check(p.indices.count == 36 and near(area(p), 96), "a full 4x4x4 block: 6 quads, area 96") + Types.Voxels.set(v, 1, 1, 3, 2) + local p2 = MeshOps.voxelsToPrimitive(v, { pivot = "corner" }) :: any + t:check(near(area(p2), 96) and p2.indices.count > 36, "a different colour splits the top face, same area") + local scaled = MeshOps.voxelsToPrimitive(v, { scale = 0.5 }) :: any + local lo, hi = MeshOps.bounds(scaled) + t:check(lo and near(lo[1], -1) and near(hi[1], 1), "scale and centre pivot") +end + +-- the api encodes image-only textures to PNG before a model writer sees them +do + local s = S.fromPrimitive(MeshOps.triangulate(cube()) :: any) + s.textures[1] = { image = Types.Image.new(2, 2) } + s.materials[1] = S.material("m") + s.materials[1].baseColorTexture = { texture = 1 } + s.meshes[1].primitives[1].material = 1 + local glb = F.save(s, nil, { format = "glb" }) + t:check(glb and s.textures[1].mime == "image/png" and s.textures[1].data ~= nil, "F.save: texture image -> PNG bytes") + local back = F.load(glb) + local _, errs = F.model.loadTextures(back) + t:check(back.textures[1].image and back.textures[1].image.width == 2 and next(errs) == nil, "PNG texture through GLB and back") +end + +t:done() diff --git a/tests/playlist/m3u.luau b/tests/playlist/m3u.luau new file mode 100644 index 0000000..3229e53 --- /dev/null +++ b/tests/playlist/m3u.luau @@ -0,0 +1,357 @@ +-- playlist/m3u tests (+ the PLS parts of the ported suite): M3U / M3U8 (EXTINF, comments, BOM, CRLF / CR, +-- Windows-1252, relative / absolute / local locations), PLS, HLS master and media playlists, detection, serialize round +-- trips, bad input; Python-written playlists (tools/fixtures/playlist.py) decode to their entries, and our M3U8 output +-- decodes back; the api; the fuzz pass. Ported from playlist-luau tests/playlist.luau. Fixtures: +-- tools/fixtures/playlist.py. +local T = require("@tests/T") +local M3u = require("@formats/playlist/m3u") +local Pls = require("@formats/playlist/pls") +local Bytes = require("@formats/core/Bytes") +local F = require("@formats") +local Cases = require("@tests/gen/playlist_cases") + +local t = T.suite("m3u") +local function eq(got: any, want: any, label: string) + t:eq(got, want, label) +end +local function has(list: { string }, pattern: string): boolean + for _, w in list do + if string.find(w, pattern) then + return true + end + end + return false +end + +-- the playlist-luau API on top of the two formats (the ported tests below use it) +local Playlist = {} +function Playlist.detect(text: string): string + if type(text) ~= "string" then + return "m3u" + end + local r = Bytes.reader(buffer.fromstring(text)) + if Pls.sniff(r) > 0 then + return "pls" + end + return if string.find(text, "#EXT%-X%-") then "hls" else "m3u" +end +function Playlist.parse(text: any, baseUrl: string?): any + if type(text) ~= "string" then + return { kind = "m3u", entries = {}, warnings = { "expected a string" } } + end + local kind = Playlist.detect(text) + local mod = if kind == "pls" then Pls else M3u + local pl = mod.decode(Bytes.reader(buffer.fromstring(text)), { baseUrl = baseUrl }) :: any + pl.kind = pl.format -- the old field + return pl +end +function Playlist.serialize(entries: any, opts: any?): string + return buffer.tostring(M3u.encode(entries, opts) :: buffer) +end + +-- M3U8 with EXTINF, comments, blank lines, BOM, CRLF +do + local text = "\239\187\191#EXTM3U\r\n#PLAYLIST:My Mix\r\n\r\n# a comment\r\n#EXTINF:123,Daft Punk - One More Time\r\n" + .. "music/one more time.mp3\r\n#EXTINF:-1,Radio\r\nhttp://radio.example/stream\r\n" + .. "#EXTINF:61.5 tvg-id=\"x\" group-title=\"a,b\",Grouped, with comma\r\n../other/b.mp3\r\n" + .. "#EXTGRP:ignored\r\n/abs/c.mp3\r\n https://cdn.example/d.mp3?x=1 \r\n" + local pl = Playlist.parse(text, "https://host.example/lists/m.m3u8") + eq(pl.kind, "m3u", "kind") + eq(pl.title, "My Mix", "#PLAYLIST") + eq(#pl.entries, 5, "entry count") + local e = pl.entries + eq(e[1].url, "https://host.example/lists/music/one%20more%20time.mp3", "relative resolved + encoded") + eq(e[1].title, "Daft Punk - One More Time", "EXTINF title") + eq(e[1].duration, 123, "EXTINF duration") + eq(e[1].playable, true, "https playable") + eq(e[2].url, "http://radio.example/stream", "absolute kept") + eq(e[2].duration, nil, "duration -1 = unknown") + eq(e[2].title, "Radio", "title 2") + eq(e[3].url, "https://host.example/other/b.mp3", "dot-dot resolved") + eq(e[3].duration, 61.5, "fractional duration with attributes") + eq(e[3].title, "Grouped, with comma", "title after the attributes keeps its commas") + eq(e[4].url, "https://host.example/abs/c.mp3", "absolute path") + eq(e[4].title, nil, "EXTINF does not leak to the next entry") + eq(e[5].url, "https://cdn.example/d.mp3?x=1", "trimmed absolute") + eq(#pl.warnings, 0, "no warnings") +end + +-- plain M3U (no header), CR line endings, Windows paths, relative without base, other schemes +do + local text = "C:\\Music\\Song A.mp3\rD:/Other/b.mp3\r\\\\server\\share\\c.mp3\rsongs\\d.mp3\rftp://x/e.mp3\rfile:///home/u/f.mp3" + local pl = Playlist.parse(text) + eq(#pl.entries, 6, "plain count") + eq(pl.entries[1].url, "C:\\Music\\Song A.mp3", "windows path kept as is") + eq(pl.entries[1].playable, false, "windows path unplayable") + eq(pl.entries[1].reason, "local path", "windows path reason") + eq(pl.entries[2].reason, "local path", "drive with slash") + eq(pl.entries[3].reason, "local path", "UNC") + eq(pl.entries[4].url, "songs\\d.mp3", "relative without base kept") + eq(pl.entries[4].reason, "relative path without a base URL", "relative without base reason") + eq(pl.entries[5].reason, "scheme ftp", "ftp unplayable") + eq(pl.entries[6].reason, "local path", "file: is local") + eq(has(pl.warnings, "relative path without a base URL"), true, "warning for relative") + eq(has(pl.warnings, "4 local paths"), true, "local paths summary") + -- with a URL base, Windows separators in relative entries become slashes; drive paths stay local + local pl2 = Playlist.parse(text, "http://h/x/list.m3u") + eq(pl2.entries[4].url, "http://h/x/songs/d.mp3", "backslash relative resolved") + eq(pl2.entries[4].playable, true, "backslash relative playable") + eq(pl2.entries[1].url, "C:\\Music\\Song A.mp3", "windows path untouched with a base") + -- with a Windows base, relative entries are paths next to the playlist + local pl3 = Playlist.parse("a.mp3\nsub\\b.mp3", "C:\\Music\\list.m3u") + eq(pl3.entries[1].url, "C:\\Music\\a.mp3", "windows base") + eq(pl3.entries[2].url, "C:\\Music\\sub\\b.mp3", "windows base sub") + eq(pl3.entries[1].playable, false, "windows base unplayable") + -- file: base + local pl4 = Playlist.parse("a.mp3", "file:///C:/Music/list.m3u") + eq(pl4.entries[1].url, "file:///C:/Music/a.mp3", "file base") + eq(pl4.entries[1].reason, "local path", "file base local") + -- a relative base is not used + local pl5 = Playlist.parse("a.mp3", "lists/x.m3u") + eq(has(pl5.warnings, "not absolute"), true, "relative base warning") +end + +-- Windows-1252 text (a classic .m3u), and UTF-8 kept +do + local pl = Playlist.parse("#EXTM3U\n#EXTINF:10,Bj\246rk \150 J\243ga\nhttp://x/j.mp3\n") + eq(pl.entries[1].title, "Björk – Jóga", "cp1252 transcoded") + eq(has(pl.warnings, "Windows%-1252"), true, "cp1252 warning") + local pl2 = Playlist.parse("#EXTINF:10,Björk – Jóga\nhttp://x/j.mp3") + eq(pl2.entries[1].title, "Björk – Jóga", "utf-8 kept") + eq(#pl2.warnings, 0, "utf-8 no warning") + local pl3 = Playlist.parse("http://x/Björk.mp3") + eq(pl3.entries[1].url, "http://x/Bj%C3%B6rk.mp3", "utf-8 url encoded") +end + +-- PLS +do + local text = "[playlist]\r\nNumberOfEntries=3\r\nFile2=http://s.example:8000/live\r\nTitle2=(#1) Some Radio\r\nLength2=-1\r\n" + .. "File1=music/a.mp3\r\nTitle1=Artist - Song\r\nLength1=200\r\n; comment\r\nfile10 = http://x/z.mp3\r\nVersion=2\r\n" + local pl = Playlist.parse(text, "http://h/p/list.pls") + eq(pl.kind, "pls", "pls kind") + eq(#pl.entries, 3, "pls count") + eq(pl.entries[1].url, "http://h/p/music/a.mp3", "pls order by index + resolved") + eq(pl.entries[1].title, "Artist - Song", "pls title") + eq(pl.entries[1].duration, 200, "pls length") + eq(pl.entries[2].url, "http://s.example:8000/live", "pls 2") + eq(pl.entries[2].duration, nil, "pls length -1") + eq(pl.entries[3].url, "http://x/z.mp3", "pls key case / spaces / index 10") + eq(pl.entries[3].title, nil, "pls no title") + eq(#pl.warnings, 0, "pls no warnings") + local bad = Playlist.parse("[Playlist]\nNumberOfEntries=2\nFile1=http://a/1.mp3\n") + eq(bad.kind, "pls", "pls case-insensitive header") + eq(has(bad.warnings, "NumberOfEntries=2 but 1"), true, "pls count mismatch warning") +end + +-- HLS master playlist: variants with attributes (quoted commas), EXT-X-MEDIA audio renditions +do + local text = [[#EXTM3U +#EXT-X-VERSION:3 +#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="aud",NAME="English",LANGUAGE="en",URI="audio/en.m3u8" +#EXT-X-STREAM-INF:BANDWIDTH=128000,CODECS="mp4a.40.2,avc1.4d401e",RESOLUTION=640x360,AUDIO="aud" +low/index.m3u8 +#EXT-X-STREAM-INF:BANDWIDTH=320000,CODECS="mp4a.40.34" +http://other.example/hi/index.m3u8 +]] + local pl = Playlist.parse(text, "https://cdn.example/show/master.m3u8") + eq(pl.kind, "hls", "hls kind") + assert(pl.hls) + eq(pl.hls.master, true, "master") + eq(#pl.entries, 3, "variants + rendition") + eq(pl.entries[1].url, "https://cdn.example/show/audio/en.m3u8", "rendition url") + eq(pl.entries[1].title, "English", "rendition name") + eq(pl.entries[2].url, "https://cdn.example/show/low/index.m3u8", "variant 1 url") + eq(pl.entries[2].bandwidth, 128000, "variant 1 bandwidth") + eq(pl.entries[2].codecs, "mp4a.40.2,avc1.4d401e", "variant codecs keeps its comma") + eq((pl.entries[2].attributes :: any).RESOLUTION, "640x360", "variant attributes") + eq(pl.entries[3].bandwidth, 320000, "variant 2 bandwidth") + eq(pl.entries[3].url, "http://other.example/hi/index.m3u8", "variant 2 absolute") + eq(#pl.warnings, 0, "master no warnings") +end + +-- HLS media playlist with mp3 segments (VOD) +do + local text = [[#EXTM3U +#EXT-X-VERSION:3 +#EXT-X-TARGETDURATION:10 +#EXT-X-MEDIA-SEQUENCE:7 +#EXTINF:10.0, +seg7.mp3 +#EXTINF:9.5,Part two +seg8.mp3?token=a +#EXT-X-BYTERANGE:1000@0 +#EXTINF:4, +all.mp3 +#EXT-X-BYTERANGE:500 +#EXTINF:2, +all.mp3 +#EXT-X-ENDLIST +]] + local pl = Playlist.parse(text, "https://h/radio/list.m3u8") + assert(pl.hls) + eq(pl.kind, "hls", "media kind") + eq(pl.hls.master, false, "media not master") + eq(pl.hls.targetDuration, 10, "target duration") + eq(pl.hls.mediaSequence, 7, "media sequence") + eq(pl.hls.endList, true, "endlist") + eq(pl.hls.totalDuration, 25.5, "total duration") + eq(pl.hls.segmentFormat, "mp3", "segment format") + eq(#pl.entries, 4, "segments") + eq(pl.entries[1].url, "https://h/radio/seg7.mp3", "segment url") + eq(pl.entries[1].duration, 10, "segment duration") + eq(pl.entries[1].title, nil, "empty title is nil") + eq(pl.entries[2].title, "Part two", "segment title") + eq(pl.entries[2].url, "https://h/radio/seg8.mp3?token=a", "segment query") + eq(pl.entries[2].playable, true, "mp3 segments playable") + eq((pl.entries[3].byteRange :: any).length, 1000, "byterange length") + eq((pl.entries[3].byteRange :: any).offset, 0, "byterange offset") + eq((pl.entries[4].byteRange :: any).offset, 1000, "byterange continues") + eq(#pl.warnings, 0, "mp3 VOD no warnings") +end + +-- HLS media playlists with unsupported segments, live, encrypted, fMP4 +do + local ts = Playlist.parse("#EXTM3U\n#EXT-X-TARGETDURATION:6\n#EXTINF:6,\na.ts\n#EXTINF:6,\nb.ts\n", "http://h/x.m3u8") + assert(ts.hls) + eq(ts.entries[1].playable, false, "ts unplayable") + eq(ts.entries[1].reason, "segment format ts", "ts reason") + eq(ts.hls.segmentFormat, "ts", "ts format") + eq(has(ts.warnings, "HLS segments are %.ts"), true, "ts warning") + eq(has(ts.warnings, "live HLS"), true, "live warning") + local aac = Playlist.parse("#EXTM3U\n#EXT-X-TARGETDURATION:6\n#EXTINF:6,\na.aac\n#EXTINF:6,\nb.mp3\n#EXT-X-ENDLIST\n", "http://h/x.m3u8") + assert(aac.hls) + eq(aac.hls.segmentFormat, "mixed", "mixed format") + eq(has(aac.warnings, "%.aac"), true, "aac warning") + eq(aac.entries[2].playable, true, "mp3 among aac still playable") + local m4s = Playlist.parse("#EXTM3U\n#EXT-X-TARGETDURATION:4\n#EXT-X-MAP:URI=\"init.mp4\"\n#EXTINF:4,\n1.m4s\n#EXT-X-ENDLIST\n", "http://h/x.m3u8") + eq(m4s.entries[1].playable, false, "m4s unplayable") + eq(has(m4s.warnings, "%.m4s") and has(m4s.warnings, "fMP4"), true, "m4s + fmp4 warning") + local enc = Playlist.parse("#EXTM3U\n#EXT-X-TARGETDURATION:4\n#EXT-X-KEY:METHOD=AES-128,URI=\"k\"\n#EXTINF:4,\n1.mp3\n#EXT-X-ENDLIST\n", "http://h/x.m3u8") + assert(enc.hls) + eq(enc.hls.encrypted, true, "encrypted") + eq(enc.entries[1].playable, false, "encrypted unplayable") + eq(has(enc.warnings, "encrypted"), true, "encrypted warning") + local none = Playlist.parse("#EXTM3U\n#EXT-X-TARGETDURATION:4\n#EXT-X-KEY:METHOD=NONE\n#EXTINF:4,\n1.mp3\n#EXT-X-ENDLIST\n", "http://h/x.m3u8") + eq(none.entries[1].playable, true, "METHOD=NONE is clear") +end + +-- detection +do + eq(Playlist.detect("[playlist]\nFile1=a"), "pls", "detect pls") + eq(Playlist.detect("\239\187\191 [PLAYLIST]\r\n"), "pls", "detect pls with BOM / spaces") + eq(Playlist.detect("#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=1\na.m3u8"), "hls", "detect hls master") + eq(Playlist.detect("#EXTM3U\n#EXT-X-TARGETDURATION:5\n"), "hls", "detect hls media") + eq(Playlist.detect("#EXTM3U\n#EXTINF:1,a\na.mp3"), "m3u", "detect m3u") + eq(Playlist.detect("a.mp3"), "m3u", "detect plain") +end + +-- serialize: M3U8, round trip +do + local entries = { + { url = "http://x/a.mp3", title = "A - B", duration = 61.6 }, + { url = "http://x/b.mp3" }, + { url = "http://x/c.mp3", title = "multi\nline" }, + { url = "http://x/d.mp3", duration = 5 }, + { title = "no url" }, + } + local text = Playlist.serialize(entries :: any, { title = "Mix" }) + eq(text, "#EXTM3U\n#PLAYLIST:Mix\n#EXTINF:62,A - B\nhttp://x/a.mp3\nhttp://x/b.mp3\n#EXTINF:-1,multi line\nhttp://x/c.mp3\n" + .. "#EXTINF:5,\nhttp://x/d.mp3\n", "serialize text") + local back = Playlist.parse(text) + eq(#back.entries, 4, "round trip count") + eq(back.title, "Mix", "round trip title") + eq(back.entries[1].title, "A - B", "round trip title 1") + eq(back.entries[1].duration, 62, "round trip duration") + eq(back.entries[2].title, nil, "round trip no title") + eq(back.entries[3].duration, nil, "round trip unknown duration") + eq(Playlist.serialize({}), "#EXTM3U\n", "serialize empty") + -- parse -> serialize -> parse keeps everything of a real playlist + local pl = Playlist.parse("#EXTM3U\n#EXTINF:100,X - Y\nhttp://h/1.mp3\n#EXTINF:-1,Live\nhttp://h/live\n") + local again = Playlist.parse(Playlist.serialize(pl.entries)) + for i, e in pl.entries do + eq(again.entries[i].url, e.url, "rt url " .. i) + eq(again.entries[i].title, e.title, "rt title " .. i) + eq(again.entries[i].duration, e.duration, "rt duration " .. i) + end +end + +-- bad input never throws +do + local inputs: { any } = { "", "\n\n\n", "#EXTM3U", "#EXTINF:abc,\n", "[playlist]\n=\nFile=\nFilex1=y", "#EXT-X-STREAM-INF:\n", + "#EXT-X-STREAM-INF:BANDWIDTH=\"unterminated\n", "#EXT-X-BYTERANGE:x\n#EXT-X-TARGETDURATION:\n", "\255\254\0\0", 42, nil } + for i = 1, 11 do + local ok, pl = pcall(Playlist.parse, inputs[i], "http://h/") + eq(ok, true, "bad input " .. i .. " threw " .. tostring(pl)) + eq(type(pl.entries), "table", "bad input " .. i .. " entries") + end + eq(#Playlist.parse("").entries, 0, "empty text") + eq(has(Playlist.parse(42 :: any).warnings, "expected a string"), true, "non-string warning") + local ok = pcall(Playlist.serialize, { 1, "x", { url = 5 } } :: any) + eq(ok, true, "serialize skips junk") + -- random bytes + local state = 7 + for _ = 1, 300 do + local t = table.create(80) + for k = 1, 80 do + state = (state * 1103515245 + 12345) % 2147483648 + t[k] = string.char(({ 10, 13, 35, 44, 58, 61, 34, 92, 47, 46, 65, 120, 200 })[state % 13 + 1]) + end + local s = "#EXTM3U\n#EXT-X-" .. table.concat(t) + local ok2, err = pcall(Playlist.parse, s, "http://h/a/") + eq(ok2, true, "fuzz threw " .. tostring(err)) + local ok3, err3 = pcall(Playlist.parse, "[playlist]\n" .. table.concat(t), "http://h/a/") + eq(ok3, true, "fuzz pls threw " .. tostring(err3)) + end +end + + +-- Python-written playlists +for _, c in Cases do + local pl = M3u.decode(Bytes.reader(buffer.fromstring(c.m3u))) :: any + eq(#pl.entries, #c.entries, c.name .. ": entries") + for i, e in c.entries do + local g = pl.entries[i] + eq(g.url, e.url, c.name .. ": url " .. i) + eq(g.duration, e.duration, c.name .. ": duration " .. i) + if e.title then + eq(g.title, e.title, c.name .. ": title " .. i) + end + end + local back = M3u.decode(Bytes.reader(M3u.encode(pl, { title = c.title }) :: buffer)) :: any + eq(back.title, c.title, c.name .. ": #PLAYLIST round trip") + for i, e in pl.entries do + eq(back.entries[i].url, e.url, c.name .. ": round trip url " .. i) + eq(back.entries[i].title, e.title, c.name .. ": round trip title " .. i) + end +end +t:note("%d Python-written M3U8 files decode to their entries", #Cases) + +-- the contract and the api +do + eq(M3u.name, "m3u", "name") + eq(M3u.category, "playlist", "category") + local c = Cases[1] + eq(F.detect(c.m3u), "m3u", "F.detect") + local pl = F.playlist.load(c.m3u, { baseUrl = "http://x/" }) + t:check(pl and pl.kind == "playlist" and pl.format == "m3u" and #pl.entries == #c.entries, "F.playlist.load") + local saved = F.save(pl, nil, { format = "m3u8" }) + t:check(saved and string.sub(buffer.tostring(saved), 1, 7) == "#EXTM3U", "F.save m3u8") + local hls = F.playlist.load("#EXTM3U\n#EXT-X-TARGETDURATION:4\n#EXTINF:4,\n1.mp3\n#EXT-X-ENDLIST\n", { baseUrl = "http://h/x.m3u8" }) + t:check(hls and hls.format == "hls" and hls.hls.endList, "F.playlist.load HLS") + t:eq(M3u.sniff(Bytes.reader(buffer.fromstring("\239\187\191 #EXTM3U\n"))), 0.95, "sniff with BOM") + t:eq(M3u.sniff(Bytes.reader(buffer.fromstring("a.mp3\n"))), 0, "plain lists are found by extension") + local _, e = M3u.encode(5 :: any) + t:check(e ~= nil, "encode a number") +end + +local samples = {} +for _, c in Cases do + table.insert(samples, c.m3u) +end +table.insert(samples, "#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=128000,CODECS=\"mp4a.40.2\"\nlo.m3u8\n#EXT-X-MEDIA:TYPE=AUDIO,URI=\"a.m3u8\",NAME=\"x\"\n") +table.insert(samples, "#EXTM3U\n#EXT-X-TARGETDURATION:6\n#EXT-X-BYTERANGE:100@0\n#EXTINF:6,\na.mp3\n#EXT-X-KEY:METHOD=AES-128\n#EXT-X-ENDLIST\n") +t:fuzz("decode", function(b: buffer) + return M3u.decode(Bytes.reader(b), { baseUrl = "http://h/a/" }) +end, samples, { mutations = 20 }) + +t:done() diff --git a/tests/playlist/pls.luau b/tests/playlist/pls.luau new file mode 100644 index 0000000..39ddd5c --- /dev/null +++ b/tests/playlist/pls.luau @@ -0,0 +1,69 @@ +-- playlist/pls tests: Python-written PLS files (tools/fixtures/playlist.py) decode to their entries; keys in any case +-- and order, gaps in the numbering, comments, NumberOfEntries mismatches, Windows-1252, relative locations; the +-- writer round-trips (titles, unknown lengths, line breaks); the api; the fuzz pass. (The playlist-luau PLS cases run +-- in tests/playlist/m3u.luau.) Fixtures: tools/fixtures/playlist.py. +local T = require("@tests/T") +local Pls = require("@formats/playlist/pls") +local Bytes = require("@formats/core/Bytes") +local F = require("@formats") +local Cases = require("@tests/gen/playlist_cases") + +local t = T.suite("pls") +local function decode(s: string, base: string?): any + return Pls.decode(Bytes.reader(buffer.fromstring(s)), { baseUrl = base }) +end + +for _, c in Cases do + local pl = decode(c.pls) + t:eq(#pl.entries, #c.entries, c.name .. ": entries") + t:eq(#pl.warnings, 0, c.name .. ": no warnings") + for i, e in c.entries do + local g = pl.entries[i] + t:eq(g.url, e.url, c.name .. ": url " .. i) + t:eq(g.title, e.title, c.name .. ": title " .. i) + t:eq(g.duration, e.duration, c.name .. ": duration " .. i) + t:check(g.playable, c.name .. ": playable " .. i) + end + local back = decode(buffer.tostring(Pls.encode(pl) :: buffer)) + t:eq(#back.entries, #pl.entries, c.name .. ": round trip count") + for i, e in pl.entries do + local g = back.entries[i] + t:check(g.url == e.url and g.title == e.title and g.duration == e.duration, c.name .. ": round trip " .. i) + end +end +t:note("%d Python-written PLS files decode to their entries and round-trip", #Cases) + +do + local pl = decode("; comment\n[PlayList]\nversion=2\nTITLE2=Second\nfile2=b.mp3\nFile10=http://x/ten.mp3\nLength2=7\nFile1=a.mp3\nnumberofentries=4\n", "http://h/dir/list.pls") + t:eq(#pl.entries, 3, "entries sorted by number") + t:eq(pl.entries[1].url, "http://h/dir/a.mp3", "relative resolved") + t:check(pl.entries[2].title == "Second" and pl.entries[2].duration == 7, "case-insensitive keys") + t:eq(pl.entries[3].url, "http://x/ten.mp3", "gap in numbering") + t:check(string.find(pl.warnings[1], "NumberOfEntries=4", 1, true) ~= nil, "count mismatch warning") + local cp = decode("[playlist]\nFile1=http://x/a.mp3\nTitle1=Bj\246rk\nNumberOfEntries=1\n") + t:eq(cp.entries[1].title, "Bj\u{f6}rk", "Windows-1252 text") + local loc = decode("[playlist]\nFile1=C:\\Music\\a.mp3\nNumberOfEntries=1\n") + t:check(not loc.entries[1].playable and loc.entries[1].reason == "local path", "local path") + -- the writer + local out = buffer.tostring(Pls.encode({ { url = "http://a/1.mp3", title = "One\nTwo", duration = 61.6 }, { url = "http://a/2.mp3" }, { url = 5 } } :: any) :: buffer) + t:eq(out, "[playlist]\nFile1=http://a/1.mp3\nTitle1=One Two\nLength1=62\nFile2=http://a/2.mp3\nLength2=-1\nNumberOfEntries=2\nVersion=2\n", "writer output") + t:check(select(2, Pls.encode(5 :: any)) ~= nil, "encode a number") + t:eq(Pls.sniff(Bytes.reader(buffer.fromstring("\239\187\191 [playlist]\r\nFile1=a"))), 0.95, "sniff") + t:eq(Pls.sniff(Bytes.reader(buffer.fromstring("#EXTM3U"))), 0, "sniff m3u") + -- the api + t:eq(F.detect(Cases[1].pls), "pls", "F.detect") + local a = F.playlist.load(Cases[1].pls) + t:check(a and a.format == "pls", "F.playlist.load") + local m = F.convert(Cases[1].pls, "m3u") + t:check(m and string.sub(buffer.tostring(m), 1, 7) == "#EXTM3U", "F.convert pls -> m3u") +end + +local samples = {} +for _, c in Cases do + table.insert(samples, c.pls) +end +t:fuzz("decode", function(b: buffer) + return Pls.decode(Bytes.reader(b), { baseUrl = "http://h/a/" }) +end, samples, { mutations = 20 }) + +t:done() diff --git a/tests/playlist/xspf.luau b/tests/playlist/xspf.luau new file mode 100644 index 0000000..8cb2aef --- /dev/null +++ b/tests/playlist/xspf.luau @@ -0,0 +1,89 @@ +-- playlist/xspf tests: XSPF files written by Python's xml.etree.ElementTree (tools/fixtures/playlist.py) decode to +-- their entries; every track field, multiple locations, xml:base, relative / local locations, a prefixed namespace; +-- the writer round-trips (and escapes; its output was also checked by hand with ElementTree); errors (malformed XML, +-- another root); the api; the fuzz pass. +-- Fixtures: tools/fixtures/playlist.py. +local T = require("@tests/T") +local Xspf = require("@formats/playlist/xspf") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local F = require("@formats") +local Cases = require("@tests/gen/playlist_cases") + +local t = T.suite("xspf") +local function decode(s: string, base: string?): (any, any) + return Xspf.decode(Bytes.reader(buffer.fromstring(s)), { baseUrl = base }) +end + +for _, c in Cases do + local pl, err = decode(c.xspf) + t:check(pl, c.name .. ": decode: " .. tostring(err)) + t:eq(pl.title, c.title, c.name .. ": title") + t:eq(#pl.entries, #c.entries, c.name .. ": entries") + for i, e in c.entries do + local g = pl.entries[i] + t:check(g.url == e.url and g.title == e.title and g.duration == e.duration and g.playable, c.name .. ": entry " .. i) + end + local back = decode(buffer.tostring(Xspf.encode(pl) :: buffer)) + t:eq(back.title, pl.title, c.name .. ": round trip title") + for i, e in pl.entries do + local g = back.entries[i] + t:check(g.url == e.url and g.title == e.title and g.duration == e.duration, c.name .. ": round trip " .. i) + end +end +t:note("%d ElementTree-written XSPF files decode to their entries and round-trip", #Cases) + +do + local text = [[<?xml version="1.0" encoding="UTF-8"?> +<x:playlist version="1" xmlns:x="http://xspf.org/ns/0/" xml:base="http://media.example/base/"> + <x:title> My & list </x:title><x:creator>Me</x:creator> + <x:trackList> + <x:track><x:location>a%20b.mp3</x:location><x:location>http://mirror.example/a.mp3</x:location> + <x:title>A</x:title><x:creator>Artist</x:creator><x:album>Album</x:album><x:duration>1500</x:duration> + <x:trackNum>3</x:trackNum><x:image>cover.jpg</x:image><x:extension application="x"><y/></x:extension></x:track> + <x:track xml:base="http://other.example/dir/"><x:location>../b.mp3</x:location></x:track> + <x:track><x:title>no location</x:title></x:track> + <x:track><x:location>C:\Music\c.mp3</x:location></x:track> + </x:trackList> +</x:playlist>]] + local pl = decode(text, "http://ignored.example/") + t:eq(pl.title, "My & list", "title (entity, trimmed)") + t:eq(pl.meta.creator, "Me", "playlist creator") + t:eq(#pl.entries, 3, "a track without a location is skipped") + local a = pl.entries[1] + t:eq(a.url, "http://media.example/base/a%20b.mp3", "xml:base on the playlist") + t:check(a.title == "A" and a.creator == "Artist" and a.album == "Album" and a.duration == 1.5 and a.trackNum == 3 and a.image == "cover.jpg", "track fields") + t:check(a.locations and #a.locations == 2 and a.locations[2] == "http://mirror.example/a.mp3", "multiple locations") + t:eq(pl.entries[2].url, "http://other.example/b.mp3", "xml:base on a track") + t:check(not pl.entries[3].playable and pl.entries[3].reason == "local path", "local path") + t:check(#pl.warnings >= 2, "warnings for the missing location and the local path") + -- writer: escaping, extra fields, a plain entry list + local out = buffer.tostring(Xspf.encode({ { url = "http://x/a?b=1&c=2", title = "<A & B>", duration = 2.5, creator = "C" } } :: any) :: buffer) + t:check(string.find(out, "http://x/a?b=1&c=2", 1, true) ~= nil and string.find(out, "<A & B>", 1, true) ~= nil, "escaping") + local back = decode(out) + t:check(back.entries[1].url == "http://x/a?b=1&c=2" and back.entries[1].title == "<A & B>" and back.entries[1].duration == 2.5 and back.entries[1].creator == "C", "writer round trip") + -- errors + local _, e1 = decode("<playlist><trackList>") + t:check(e1 and Err.is(e1), "malformed XML: " .. tostring(e1)) + local _, e2 = decode("<html/>") + t:check(e2 and e2.code == Err.CORRUPT, "another root") + t:check(select(2, Xspf.encode(5 :: any)) ~= nil, "encode a number") + t:eq(Xspf.sniff(Bytes.reader(buffer.fromstring(Cases[1].xspf))), 0.95, "sniff") + t:eq(Xspf.sniff(Bytes.reader(buffer.fromstring("<playlist/>"))), 0, "sniff without the namespace") + -- the api + t:eq(F.detect(Cases[1].xspf), "xspf", "F.detect") + local la = F.playlist.load(Cases[1].xspf) + t:check(la and la.format == "xspf" and #la.entries == #Cases[1].entries, "F.playlist.load") + local m = F.convert(Cases[1].m3u, "xspf") + t:check(m and #decode(buffer.tostring(m)).entries == #Cases[1].entries, "F.convert m3u -> xspf") +end + +local samples = {} +for _, c in Cases do + table.insert(samples, c.xspf) +end +t:fuzz("decode", function(b: buffer) + return Xspf.decode(Bytes.reader(b), { baseUrl = "http://h/a/" }) +end, samples, { mutations = 20 }) + +t:done() diff --git a/tests/subtitle/ass.luau b/tests/subtitle/ass.luau new file mode 100644 index 0000000..bf28ca5 --- /dev/null +++ b/tests/subtitle/ass.luau @@ -0,0 +1,109 @@ +-- subtitle/ass tests: ffmpeg's ASS output of a random script (times to the centisecond, text through the override +-- markup), hand-written ASS (styles, comments, commas in text, overrides, [Fonts]) and SSA v4 files against ffmpeg's +-- SRT conversion of them, styles as data, round trips through the encoder, the contract and the fuzz pass. +-- Fixtures: tools/fixtures/subtitles.py. +local T = require("@tests/T") +local Ass = require("@formats/subtitle/ass") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/subtitles") + +local t = T.suite("ass") + +local function decode(s: string): (any, any) + return Ass.decode(Bytes.reader(buffer.fromstring(s))) +end +local function plain(s: string): string + s = string.gsub(s, "<[^>]*>", "") + s = string.gsub(s, "{[^}]*}", "") + return s +end +local function same(subs: any, want: any, label: string, tol: number) + t:eq(#subs.cues, #want, label .. ": cue count") + for i, w in want do + local c = subs.cues[i] + t:check(math.abs(c.start * 1000 - w.start) <= tol, label .. ": cue " .. i .. " start " .. c.start) + t:check(math.abs(c.stop * 1000 - w.stop) <= tol, label .. ": cue " .. i .. " stop " .. c.stop) + t:eq(plain(c.text), w.plain, label .. ": cue " .. i .. " text") + end +end + +t:eq(Ass.name, "ass", "name") +t:check(Ass.caps.decode and Ass.caps.encode, "caps") +t:eq(Ass.sniff(Bytes.reader(buffer.fromstring(Fx.ffmpeg_ass))), 1, "sniff") + +-- ffmpeg converts SRT to ASS with its own rounding (start and duration to centiseconds): within 10 ms +local subs, err = decode(Fx.ffmpeg_ass) +t:check(subs, "ffmpeg ass: " .. tostring(err)) +same(subs, Fx.cues, "ffmpeg ass", 10) +t:eq(subs.styles.Default.Fontname, "Arial", "ffmpeg's Default style") +t:eq(subs.meta.scriptInfo.PlayResX, "384", "script info") + +for _, h in Fx.hand do + if h.name ~= "vtt" then + local s, e = decode(h.data) + t:check(s, h.name .. ": " .. tostring(e)) + same(s, h.cues, h.name .. " vs ffmpeg", 0.5) + end +end +local a = decode(Fx.hand[2].data) +t:eq(a.meta.scriptInfo.Title, "test", "Title") +t:eq(a.meta.scriptInfoOrder[1], "; Script generated by hand", "comment kept in order") +t:eq(a.styles.Top.Fontname, "Verdana", "style field") +t:eq(a.styles.Top.Alignment, "8", "style alignment") +t:eq(a.meta.styleOrder[2], "Top", "style order") +t:eq(a.cues[1].name, "Bob", "actor") +t:eq(a.cues[1].text, "Hello, <i>world</i>!", "italic markup") +t:eq(a.cues[1].raw, "Hello, {\\i1}world{\\i0}!", "raw text") +t:eq(a.cues[2].layer, 1, "layer") +t:eq(a.cues[2].style, "Top", "style") +t:eq(a.cues[2].text, "<b>Bold top</b>\nsecond line", "bold, \\N, an8 dropped") +t:eq(a.cues[3].text, "commas, inside, the text", "commas in the text field") +t:eq(#a.meta.comments, 1, "comment event") +t:eq(a.meta.sections[1].name, "Fonts", "[Fonts] kept") +t:eq(a.meta.sections[1].lines[2], "ABCDEF", "[Fonts] lines") +local ssa = decode(Fx.hand[3].data) +t:eq(ssa.meta.source.scriptType, "v4.00", "SSA script type") +t:eq(ssa.styles.Default.TertiaryColour, "65535", "SSA style field") +t:eq(ssa.cues[1].marked, "Marked=0", "SSA Marked") + +-- round trips: the hand files exactly (same fields, same order), and the ffmpeg file through the cues +for _, s in { a, ssa, subs } do + local out = Ass.encode(s) :: buffer + local back = Ass.decode(Bytes.reader(out)) + t:check(back, "round trip") + t:eq(#back.cues, #s.cues, "rt count") + for i, c in s.cues do + t:eq(math.floor(back.cues[i].start * 100 + 0.5), math.floor(c.start * 100 + 0.5), "rt start") + t:eq(math.floor(back.cues[i].stop * 100 + 0.5), math.floor(c.stop * 100 + 0.5), "rt stop") + t:eq(back.cues[i].text, c.text, "rt text") + t:eq(back.cues[i].raw, c.raw, "rt raw") + t:eq(back.cues[i].style, c.style, "rt style") + end + for nm, st in s.styles do + for k, v in st do + t:eq(back.styles[nm][k], v, "rt style " .. nm .. "." .. k) + end + end +end +t:eq(buffer.tostring(Ass.encode(a) :: buffer), Fx.hand[2].data, "hand ASS written back byte for byte") +-- cues from another format: markup converted, a Default style made +do + local out = Ass.encode({ kind = "subtitles", cues = { { start = 1, stop = 2.5, text = "<i>it</i> and <b>bold</b>\nline <font color=\"red\">x</font>" } }, styles = {}, meta = {} } :: any) :: buffer + local back = Ass.decode(Bytes.reader(out)) + t:eq(back.cues[1].raw, "{\\i1}it{\\i0} and {\\b1}bold{\\b0}\\Nline x", "markup to overrides") + t:check(back.styles.Default ~= nil, "a Default style") + t:eq(back.cues[1].style, "Default", "cue style") +end + +do + local _, e = decode("Dialogue: 0,0:00:01.00,0:00:02.00,Default,,0,0,0,,x") + t:check(e and e.code == Err.CORRUPT, "no [Script Info]") + local _, e2 = Ass.encode({ cues = { { start = 0, stop = "x", text = "" } } } :: any) + t:check(e2 and e2.code == Err.ARG, "encode: bad stop") +end + +t:fuzz("decode", function(b: buffer) + return Ass.decode(Bytes.reader(b)) +end, { Fx.ffmpeg_ass, Fx.hand[2].data, Fx.hand[3].data }, { keepHeader = 13 }) +t:done() diff --git a/tests/subtitle/srt.luau b/tests/subtitle/srt.luau new file mode 100644 index 0000000..6e6b82e --- /dev/null +++ b/tests/subtitle/srt.luau @@ -0,0 +1,102 @@ +-- subtitle/srt tests: a random SRT script against ffmpeg (its own parse via its srt muxer: times to the millisecond, +-- text), ffmpeg's conversions of WebVTT / ASS / SSA files to SRT, odd layouts (no index, blank lines in text, CRLF, +-- BOM, dot decimals, coordinates), round trips through the encoder, the contract and the fuzz pass. +-- Fixtures: tools/fixtures/subtitles.py. +local T = require("@tests/T") +local Srt = require("@formats/subtitle/srt") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/subtitles") + +local t = T.suite("srt") + +local function decode(s: string): (any, any) + return Srt.decode(Bytes.reader(buffer.fromstring(s))) +end +local function plain(s: string): string + s = string.gsub(s, "<[^>]*>", "") + s = string.gsub(s, "{[^}]*}", "") + return s +end +local function ms(x: number): number + return math.floor(x * 1000 + 0.5) +end +local function same(subs: any, want: any, label: string) + t:eq(#subs.cues, #want, label .. ": cue count") + for i, w in want do + local c = subs.cues[i] + t:eq(ms(c.start), w.start, label .. ": cue " .. i .. " start") + t:eq(ms(c.stop), w.stop, label .. ": cue " .. i .. " stop") + t:eq(plain(c.text), w.plain, label .. ": cue " .. i .. " text") + end +end + +t:eq(Srt.name, "srt", "name") +t:eq(Srt.category, "subtitle", "category") +t:check(Srt.caps.decode and Srt.caps.encode, "caps") + +-- the random script and ffmpeg's re-mux of it +local subs, err = decode(Fx.srt) +t:check(subs, "decode: " .. tostring(err)) +same(subs, Fx.cues, "random") +t:eq(subs.cues[3].text, "<u>dog</u>\nalpha dog dog na\195\175ve alpha", "markup and lines kept") +t:eq(subs.cues[1].id, "1", "id") +same(decode(Fx.ffmpeg_srt), Fx.cues, "ffmpeg srt") +t:eq(Srt.sniff(Bytes.reader(buffer.fromstring(Fx.srt))), 0.9, "sniff") +t:eq(Srt.sniff(Bytes.reader(buffer.fromstring(Fx.ffmpeg_vtt))), 0, "sniff a vtt") +for _, h in Fx.hand do + same(decode(h.ffmpeg_srt), h.cues, "ffmpeg " .. h.name .. " -> srt") +end + +-- odd layouts +do + local s = "\239\187\1911\r\n00:00:01.5 --> 00:00:02,25 X1:10 X2:20 Y1:5 Y2:6\r\nfirst\r\n\r\nsecond paragraph\r\n\r\n\r\n00:00:03,000 --> 00:00:04,000\r\nno index\r\n2\r\n00:00:05,000-->00:00:06,000\r\n" + local r = decode(s) + t:check(r, "odd layouts") + t:eq(#r.cues, 3, "odd: count") + t:eq(r.cues[1].start, 1.5, "odd: 1-digit fraction") + t:eq(r.cues[1].stop, 2.25, "odd: 2-digit fraction") + t:eq(r.cues[1].text, "first\n\nsecond paragraph", "odd: blank line inside a cue") + t:eq(r.cues[1].settings, "X1:10 X2:20 Y1:5 Y2:6", "odd: coordinates") + t:eq(r.cues[2].text, "no index", "odd: cue without an index, the next index stripped") + t:eq(r.cues[2].id, nil, "odd: no id") + t:eq(r.cues[3].text, "", "odd: empty cue") + local again = decode(buffer.tostring(Srt.encode(r) :: buffer)) + t:eq(again.cues[1].text, r.cues[1].text, "odd: round trip keeps the blank line") + t:eq(again.cues[1].settings, r.cues[1].settings, "odd: round trip keeps the coordinates") +end + +-- round trips (LF and CRLF) +for _, crlf in { false, true } do + local out = Srt.encode(subs, { crlf = crlf }) :: buffer + local back = Srt.decode(Bytes.reader(out)) + t:check(back, "round trip decode") + t:eq(#back.cues, #subs.cues, "round trip count") + for i, c in subs.cues do + t:eq(ms(back.cues[i].start), ms(c.start), "round trip start " .. i) + t:eq(ms(back.cues[i].stop), ms(c.stop), "round trip stop " .. i) + t:eq(back.cues[i].text, c.text, "round trip text " .. i) + end + if not crlf then + t:eq(buffer.tostring(out), Fx.srt, "the encoder writes the canonical file byte for byte") + end +end + +-- errors +do + local _, e = decode("just some text\nno timings") + t:check(e and e.code == Err.CORRUPT, "no cues: " .. tostring(e)) + local _, e2 = decode("1\n00:00:01,000 --> 00:00:02,000\n\0bin") + t:check(e2 and e2.code == Err.CORRUPT, "NUL bytes") + local empty = decode("") + t:check(empty and #empty.cues == 0, "empty file: no cues") + local _, e3 = Srt.encode({ cues = { { start = -1, stop = 1, text = "x" } } } :: any) + t:check(e3 and e3.code == Err.ARG, "encode: negative time") + local _, e4 = Srt.encode(5 :: any) + t:check(e4 and e4.code == Err.ARG, "encode: not Subtitles") +end + +t:fuzz("decode", function(b: buffer) + return Srt.decode(Bytes.reader(b)) +end, { Fx.srt, Fx.ffmpeg_srt, Fx.hand[1].ffmpeg_srt }) +t:done() diff --git a/tests/subtitle/vtt.luau b/tests/subtitle/vtt.luau new file mode 100644 index 0000000..8c3c05f --- /dev/null +++ b/tests/subtitle/vtt.luau @@ -0,0 +1,95 @@ +-- subtitle/vtt tests: ffmpeg's WebVTT output of a random script (times, text), a hand-written file with a header, +-- STYLE / REGION / NOTE blocks, ids, settings and hour timestamps against ffmpeg's SRT conversion of it, round trips +-- through the encoder, the contract and the fuzz pass. Fixtures: tools/fixtures/subtitles.py. +local T = require("@tests/T") +local Vtt = require("@formats/subtitle/vtt") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/subtitles") + +local t = T.suite("vtt") + +local function decode(s: string): (any, any) + return Vtt.decode(Bytes.reader(buffer.fromstring(s))) +end +local function plain(s: string): string + s = string.gsub(s, "<[^>]*>", "") + s = string.gsub(s, "{[^}]*}", "") + s = string.gsub(s, "&", "&") + return s +end +local function ms(x: number): number + return math.floor(x * 1000 + 0.5) +end +local function same(subs: any, want: any, label: string) + t:eq(#subs.cues, #want, label .. ": cue count") + for i, w in want do + local c = subs.cues[i] + t:eq(ms(c.start), w.start, label .. ": cue " .. i .. " start") + t:eq(ms(c.stop), w.stop, label .. ": cue " .. i .. " stop") + t:eq(plain(c.text), w.plain, label .. ": cue " .. i .. " text") + end +end + +t:eq(Vtt.name, "vtt", "name") +t:check(Vtt.caps.decode and Vtt.caps.encode, "caps") +t:eq(Vtt.sniff(Bytes.reader(buffer.fromstring(Fx.ffmpeg_vtt))), 1, "sniff") +t:eq(Vtt.sniff(Bytes.reader(buffer.fromstring("WEBVTTX"))), 0, "sniff WEBVTTX") + +local subs, err = decode(Fx.ffmpeg_vtt) +t:check(subs, "ffmpeg vtt: " .. tostring(err)) +same(subs, Fx.cues, "ffmpeg vtt") + +local hand +for _, h in Fx.hand do + if h.name == "vtt" then + hand = h + end +end +local v, verr = decode(hand.data) +t:check(v, "hand vtt: " .. tostring(verr)) +same(v, hand.cues, "hand vtt vs ffmpeg") +t:eq(v.meta.header, "- a test file\nKind: captions", "header") +t:eq(v.meta.css[1], "::cue { color: yellow }", "STYLE") +t:eq(v.meta.regions[1], "id:r1 width:40%", "REGION") +t:eq(v.meta.notes[1], "this is a comment\nover two lines", "NOTE") +t:eq(v.cues[1].id, "intro", "id") +t:eq(v.cues[1].settings, "align:start position:10%", "settings") +t:eq(v.cues[1].text, "<v Roger>Hello <i>there</i></v>", "text kept") +t:eq(v.cues[3].settings, "line:0", "settings 3") + +for _, s in { subs, v } do + local out = Vtt.encode(s) :: buffer + local back = Vtt.decode(Bytes.reader(out)) + t:check(back, "round trip") + t:eq(#back.cues, #s.cues, "round trip count") + for i, c in s.cues do + t:eq(ms(back.cues[i].start), ms(c.start), "rt start") + t:eq(ms(back.cues[i].stop), ms(c.stop), "rt stop") + t:eq(back.cues[i].text, c.text, "rt text") + t:eq(back.cues[i].id, c.id, "rt id") + t:eq(back.cues[i].settings, c.settings, "rt settings") + end + t:eq(back.meta.header, s.meta.header, "rt header") +end +do + local back = decode(buffer.tostring(Vtt.encode(v) :: buffer)) + t:eq(back.meta.css[1], v.meta.css[1], "rt css") + t:eq(back.meta.regions[1], v.meta.regions[1], "rt region") + -- text that WebVTT cannot hold + local w = Vtt.encode({ kind = "subtitles", cues = { { start = 0, stop = 1, text = "a\n\nb --> c" } }, styles = {}, meta = {} } :: any) :: buffer + local wb = Vtt.decode(Bytes.reader(w)) + t:eq(wb.cues[1].text, "a\nb --> c", "blank lines dropped, arrow escaped") +end + +do + local _, e = decode("1\n00:00:01,000 --> 00:00:02,000\nx") + t:check(e and e.code == Err.CORRUPT, "no signature") + local _, e2 = Vtt.encode({ cues = { { start = 0, stop = 1 } } } :: any) + t:check(e2 and e2.code == Err.ARG, "encode: cue without text") +end + +t:fuzz("decode", function(b: buffer) + return Vtt.decode(Bytes.reader(b)) +end, { Fx.ffmpeg_vtt, hand.data }, { keepHeader = 6 }) +t:done() diff --git a/tests/vector/svg.luau b/tests/vector/svg.luau new file mode 100644 index 0000000..a2e2e49 --- /dev/null +++ b/tests/vector/svg.luau @@ -0,0 +1,151 @@ +-- vector/svg tests: hand-written SVGs, one feature area each (shapes, every path command, arcs, transforms, stroke +-- joins / caps / dashes, fill rules, opacity, gradients, href, CSS, use / symbol, viewBox + preserveAspectRatio, nested +-- svg, clip paths, units, colours, inheritance), rasterized by us and compared with resvg by PSNR; our SVG writer's +-- output rendered by resvg against resvg's rendering of the original (tools/fixtures/_ours.luau); path data and +-- colour parsing details; round trips; errors; the fuzz pass. Fixtures: tools/fixtures/svg.py. +local T = require("@tests/T") +local Svg = require("@formats/vector/svg") +local PathData = require("@formats/vector/svg/PathData") +local Style = require("@formats/vector/svg/Style") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/svg") + +local t = T.suite("svg") + +local function decode(s: string): (any, any) + return Svg.decode(Bytes.reader(buffer.fromstring(s))) +end +-- PSNR over premultiplied RGBA (the colour of transparent pixels does not matter) +local function psnr(a: buffer | string, b: string): number + local sa = if type(a) == "string" then a else buffer.tostring(a) + local n = math.min(#sa, #b) + local se = 0 + for i = 1, n, 4 do + local aa, ab = string.byte(sa, i + 3), string.byte(b, i + 3) + for k = 0, 2 do + local d = (string.byte(sa, i + k) * aa - string.byte(b, i + k) * ab) / 255 + se += d * d + end + se += (aa - ab) * (aa - ab) + end + if se == 0 then + return 99 + end + return 10 * math.log10(255 * 255 / (se / n)) +end + +t:eq(Svg.name, "svg", "name") +t:eq(Svg.category, "vector", "category") +t:check(Svg.caps.decode and Svg.caps.encode, "caps") + +-- antialiasing differs between rasterizers (resvg: tiny-skia's analytic AA; ours: exact area coverage), so edges +-- cost a few dB; the floor catches wrong geometry / paint +local FLOOR = 30 +local samples = {} +local worst, worstName = 99, "" +for _, c in Fx.cases do + local v, err = decode(c.svg) + t:check(v, c.name .. ": " .. tostring(err)) + t:eq(v.kind, "vector", c.name .. ": kind") + local img = Svg.rasterize(v, c.width, c.height) :: any + t:check(img and img.width == c.width and img.height == c.height, c.name .. ": raster size") + local p = psnr(img.pixels, c.ref) + t:check(p >= FLOOR, string.format("%s: ours vs resvg %.1f dB", c.name, p)) + t:note("%-16s ours vs resvg %5.1f dB, resvg(our SVG) vs resvg %5.1f dB", c.name, p, psnr(c.ours_ref, c.ref)) + if p < worst then + worst, worstName = p, c.name + end + -- the writer: resvg renders our SVG like the original + t:check(#c.ours > 0, c.name .. ": our encoder wrote SVG") + local wp = psnr(c.ours_ref, c.ref) + t:check(wp >= 35, string.format("%s: resvg on our SVG vs the original %.1f dB", c.name, wp)) + -- and we read our own SVG back to the same picture + local back = decode(c.ours) + t:check(back, c.name .. ": decode our SVG") + local img2 = Svg.rasterize(back, c.width, c.height) :: any + t:check(psnr(img2.pixels, buffer.tostring(img.pixels)) >= 40, c.name .. ": our SVG rasterizes like the original") + table.insert(samples, c.svg) +end +t:note("worst: %s %.1f dB", worstName, worst) + +-- path data +do + local cmds, ok = PathData.parse("M1.5.5L-2-3e1 1e-1.2zm1,1 h2 v2 a1 1 0 0 1 2 2") + t:check(ok, "parse ok") + t:check(cmds[1].op == "M" and cmds[1][1] == 1.5 and cmds[1][2] == 0.5, "1.5.5 is two numbers") + t:check(cmds[2].op == "L" and cmds[2][1] == -2 and cmds[2][2] == -30, "-2-3e1") + t:check(cmds[3].op == "L" and cmds[3][1] == 0.1 and cmds[3][2] == 0.2, "implicit line-to after an exponent") + t:eq(cmds[4].op, "Z", "close") + t:check(cmds[5].op == "M" and cmds[5][1] == 2.5 and cmds[5][2] == 1.5, "relative move after close is from the start") + t:check(cmds[6].op == "L" and cmds[6][1] == 4.5, "h") + t:eq(cmds[#cmds].op, "C", "arc as cubics") + t:check(math.abs(cmds[#cmds][5] - 6.5) < 1e-9 and math.abs(cmds[#cmds][6] - 5.5) < 1e-9, "arc end point exact") + local part, ok2 = PathData.parse("M0 0 L10 10 L oops") + t:check(not ok2 and #part == 2, "an error keeps the commands before it") + local x0, y0, x1, y1 = PathData.bounds(PathData.parse("M0 0 C 10 -10 20 10 30 0")) + t:check(x0 == 0 and x1 == 30 and math.abs((y0 :: number) + 2.886751) < 1e-4 and math.abs((y1 :: number) - 2.886751) < 1e-4, "cubic bounds") + t:eq(PathData.serialize({ { op = "M", 1, 2.5 }, { op = "C", 0.12345, 1, 2, 3, 4, 5 }, { op = "Z" } }), "M 1 2.5 C 0.1235 1 2 3 4 5 Z", "serialize") +end + +-- colours and lengths +do + local function col(s: string): string + local c = Style.color(s) + return if type(c) == "table" then table.concat(c, ",") else tostring(c) + end + t:eq(col("#f80"), "255,136,0,255", "#rgb") + t:eq(col("#ff008080"), "255,0,128,128", "#rrggbbaa") + t:eq(col("rgb(10%, 50%, 90%)"), "26,128,230,255", "rgb %") + t:eq(col("hsl(120, 100%, 25%)"), "0,128,0,255", "hsl") + t:eq(col("RebeccaPurple"), "102,51,153,255", "named, any case") + t:eq(col("none"), "none", "none") + t:eq(col("bogus"), "nil", "not a colour") + t:eq(Style.length("2mm"), 2 * 96 / 25.4, "mm") + t:eq(Style.length("50%", 64), 32, "%") + t:eq(Style.length("1.5em", nil, 10), 15, "em") + local m = Style.transform("translate(10) rotate(90) scale(2 3)") :: { number } + t:check(math.abs(m[1]) < 1e-12 and math.abs(m[2] - 2) < 1e-12 and math.abs(m[3] + 3) < 1e-12 and m[5] == 10, "transform list") + t:eq(Style.transform("translate(1,"), nil, "bad transform") +end + +-- the model +do + local v = decode(Fx.cases[1].svg) + t:check(#v.paths == 7, "shapes: one path each") + t:check(v.paths[1].fill.type == "color" and v.paths[1].fill.color[1] == 255, "fill red") + t:eq(v.paths[2].strokeWidth, 2, "stroke width") + local text = decode("<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10'><text>hi</text><image href='x.png'/><rect width='5' height='5'/></svg>") + t:check(text.meta.unsupported.text == 1 and text.meta.unsupported.image == 1 and #text.paths == 1, "unsupported elements counted") + local ns = decode("<s:svg xmlns:s='http://www.w3.org/2000/svg' width='4' height='4'><s:rect width='4' height='4'/></s:svg>") + t:check(ns and #ns.paths == 1, "prefixed SVG namespace") + -- a round trip keeps the paths + local back = decode(buffer.tostring(Svg.encode(v) :: buffer)) + t:eq(#back.paths, #v.paths, "round trip path count") + t:eq(Svg.sniff(Bytes.reader(buffer.fromstring(Fx.cases[1].svg))), 0.95, "sniff") + t:eq(Svg.sniff(Bytes.reader(buffer.fromstring("<html></html>"))), 0, "sniff html") +end + +-- errors +do + local _, e = decode("<html/>") + t:check(e and e.code == Err.CORRUPT, "not svg: " .. tostring(e)) + local _, e2 = decode("<svg><rect") + t:check(e2 ~= nil, "bad XML") + local _, e3 = Svg.encode({} :: any) + t:check(e3 and e3.code == Err.ARG, "encode a non-Vector") + local _, e4 = Svg.rasterize(decode(Fx.cases[1].svg), 0, 10) + t:check(e4 and e4.code == Err.ARG, "rasterize 0 x 10") + -- hostile: deep use recursion, huge coordinates + local r = decode("<svg xmlns='http://www.w3.org/2000/svg' width='8' height='8'><g id='a'><use href='#a'/><rect width='1e30' height='1e30'/></g></svg>") + t:check(r ~= nil and Svg.rasterize(r, 8, 8) ~= nil, "self-referencing use, huge rect") +end + +t:fuzz("decode + rasterize", function(b: buffer) + local v = Svg.decode(Bytes.reader(b)) + if v then + return Svg.rasterize(v, 16, 16) + end + return nil +end, samples, { mutations = 4, garbage = 50 }) +t:done() diff --git a/tests/vector/tiled.luau b/tests/vector/tiled.luau new file mode 100644 index 0000000..686e052 --- /dev/null +++ b/tests/vector/tiled.luau @@ -0,0 +1,184 @@ +-- vector/tiled tests: hand-written TMX maps (CSV / base64 zlib / gzip / raw / XML tile data, flip bits, infinite +-- chunks, hexagonal attributes, groups, image layers, every object shape, text, typed properties, embedded and +-- external tilesets with per-tile data) against Tiled's own TMJ export and TMX re-save of them (the same TileMap from +-- all three), a TSX tileset against Tiled's TSJ, our encoder's TMX / TMJ read back by Tiled (tools/fixtures/_ours.luau), +-- round trips in every data encoding, errors, and the fuzz pass. Fixtures: tools/fixtures/tiled.py. +local T = require("@tests/T") +local Tiled = require("@formats/vector/tiled") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/tiled") +local Ours = require("@tests/gen/tiled_ours") + +local t = T.suite("tiled") + +local function decode(s: string | buffer): (any, any) + local b = if type(s) == "string" then buffer.fromstring(s) else s + return Tiled.decode(Bytes.reader(b)) +end + +-- deep comparison of decoded maps, without the fields that only say who wrote the file +local SKIP = { version = true, tiledVersion = true, encoding = true, compression = true, meta = true } +local function same(a: any, b: any, path: string, out: { string }) + if #out > 8 then + return + end + if type(a) == "table" and type(b) == "table" then + local keys = {} + for k in pairs(a) do + keys[k] = true + end + for k in pairs(b) do + keys[k] = true + end + for k in pairs(keys) do + if not SKIP[k] then + same(a[k], b[k], path .. "." .. tostring(k), out) + end + end + elseif type(a) == "number" and type(b) == "number" then + if math.abs(a - b) > 1e-9 then + table.insert(out, path .. ": " .. a .. " vs " .. b) + end + elseif a ~= b then + table.insert(out, path .. ": " .. tostring(a) .. " vs " .. tostring(b)) + end +end +local function eqMap(a: any, b: any, label: string) + local out = {} + same(a, b, "", out) + t:check(#out == 0, label .. ": " .. table.concat(out, "; ")) +end + +t:eq(Tiled.name, "tiled", "name") +t:eq(Tiled.category, "vector", "category") +t:check(Tiled.caps.decode and Tiled.caps.encode, "caps") + +local samples = {} +local maps = {} +for _, c in Fx.cases do + local m, err = decode(c.tmx) + t:check(m, c.name .. ": tmx: " .. tostring(err)) + t:eq(m.kind, "tilemap", c.name .. ": kind") + local j, jerr = decode(c.tmj) + t:check(j, c.name .. ": Tiled's tmj: " .. tostring(jerr)) + local x, xerr = decode(c.tiled_tmx) + t:check(x, c.name .. ": Tiled's tmx: " .. tostring(xerr)) + eqMap(m, j, c.name .. ": hand TMX = Tiled's TMJ") + eqMap(m, x, c.name .. ": hand TMX = Tiled's TMX") + t:eq(Tiled.sniff(Bytes.reader(buffer.fromstring(c.tmx))), 0.9, c.name .. ": sniff tmx") + t:eq(Tiled.sniff(Bytes.reader(buffer.fromstring(c.tmj))), 0.8, c.name .. ": sniff tmj") + maps[c.name] = m + table.insert(samples, c.tmx) + table.insert(samples, c.tmj) +end + +-- details of the orthogonal map +do + local m = maps.ortho + t:eq(m.class, "Level", "map class") + t:eq(m.renderOrder, "left-up", "render order") + t:eq(m.backgroundColor, "#102030", "background (canonical: opaque alpha dropped)") + t:eq(m.properties.title, "\u{dc}n\u{ef}code & more", "string property") + t:eq(m.properties.count, 42, "int property") + t:eq(m.properties.ratio, 1.5, "float property") + t:eq(m.properties.on, true, "bool property") + t:eq(m.propertyTypes.tint, "color", "color type") + t:eq(m.properties.target, 3, "object property") + t:eq(m.properties.notes, "line one\nline two", "multi-line property") + t:eq(#m.tilesets, 2, "tilesets") + t:eq(m.tilesets[1].imageSource, "tiles.png", "tileset image stays a path") + t:eq(m.tilesets[1].tiles[2].class, "Door", "tile class") + t:eq(m.tilesets[2].source, "ext.tsx", "external tileset reference") + t:eq(m.tilesets[2].firstGid, 9, "firstgid") + local L = m.layers + t:eq(L[1].data[4], 0x80000000 + 3, "horizontal flip bit kept") + t:eq(L[1].opacity, 0.75, "opacity") + t:eq(L[1].tintColor, "#ff00ff", "tint") + t:eq(L[2].visible, false, "hidden layer") + t:eq(L[2].data[8], 1, "zlib data") + t:eq(L[3].locked, true, "locked") + t:eq(#L[4].data, 24, "raw base64 data") + t:eq(L[5].type, "group", "group") + t:eq(L[5].layers[1].type, "image", "image layer") + t:eq(L[5].layers[1].imageSource, "sky.png", "image layer path") + t:eq(L[5].layers[1].repeatX, true, "repeatx") + local objs = L[5].layers[2].objects + t:eq(#objs, 7, "objects") + t:check(objs[1].class == "Crate" and objs[1].rotation == 45 and objs[1].properties.weight == 2.25, "rectangle") + t:eq(objs[2].shape, "ellipse", "ellipse") + t:eq(objs[3].shape, "point", "point") + t:check(objs[4].shape == "polygon" and #objs[4].points == 3 and objs[4].points[3][2] == -12.5, "polygon") + t:check(objs[5].shape == "polyline" and objs[5].visible == false, "polyline") + t:check(objs[6].shape == "text" and objs[6].text.text == "Hello <Tiled>" and objs[6].text.bold and objs[6].text.halign == "center", "text") + t:eq(objs[7].gid, 2147483651, "tile object gid with flip") + t:eq(maps.hex.hexSideLength, 14, "hex side") + t:eq(maps.hex.layers[1].data[5], 2, "XML tile data") + t:eq(#maps.infinite.layers[1].chunks, 3, "chunks") + t:eq(maps.infinite.layers[1].chunks[2].x, -16, "chunk position") +end + +-- the external tileset, TSX vs Tiled's TSJ +do + local a = decode(Fx.tsx) + local b = decode(Fx.tsj) + t:check(a and a.meta.tileset and b and b.meta.tileset, "tileset files") + local ta, tb = a.tilesets[1], b.tilesets[1] + ta.firstGid, tb.firstGid = nil, nil + eqMap(ta, tb, "TSX = Tiled's TSJ") + t:eq(ta.tiles[1].animation[2].duration, 150, "animation") + t:eq(ta.tiles[2].objectGroup.objects[2].shape, "ellipse", "collision shapes") + t:eq(ta.tileOffset.y, -3, "tile offset") + for _, fmt in { "tsx", "tsj" } do + local back = decode(Tiled.encode(a, { format = fmt }) :: buffer) + back.tilesets[1].firstGid = nil + eqMap(back.tilesets[1], ta, "tileset round trip " .. fmt) + end +end + +-- round trips through every flavour and data encoding +for name, m in maps do + for _, o in { { format = "tmx" }, { format = "tmx", encoding = "base64" }, { format = "tmx", encoding = "base64", compression = "zlib" }, { format = "tmx", encoding = "base64", compression = "gzip" }, { format = "tmx", encoding = "xml" }, { format = "tmj" }, { format = "tmj", encoding = "base64", compression = "zlib" }, { format = "json", indent = 0 } } do + local out, err = Tiled.encode(m, o :: any) + local label = name .. " " .. o.format .. " " .. tostring(o.encoding) .. " " .. tostring(o.compression) + t:check(out, label .. ": " .. tostring(err)) + local back, berr = decode(out :: buffer) + t:check(back, label .. ": decode: " .. tostring(berr)) + eqMap(back, m, label .. ": round trip") + table.insert(samples, buffer.tostring(out :: buffer)) + end +end +do + local m = maps.ortho + t:eq(m.meta.source.format, "tmx", "source flavour") + t:eq(string.sub(buffer.tostring(Tiled.encode(m) :: buffer), 1, 5), "<?xml", "default: the source flavour") + local j = decode(Fx.cases[1].tmj) + t:eq(string.sub(buffer.tostring(Tiled.encode(j) :: buffer), 1, 1), "{", "a TMJ source writes TMJ") +end + +-- Tiled read our TMX and TMJ (checked when the fixtures were made) +for _, c in Ours.checks do + t:check(c.ok, c.label) +end + +-- errors +do + local zstd = string.gsub(Fx.cases[1].tmx, "compression=\"zlib\"", "compression=\"zstd\"") + local _, e = decode(zstd) + t:check(e and e.code == Err.UNSUPPORTED, "zstd: " .. tostring(e)) + local _, e2 = decode("<map><layer><data encoding=\"csv\">1,x,2</data></layer></map>") + t:check(e2 and e2.code == Err.CORRUPT, "bad csv: " .. tostring(e2)) + local _, e3 = decode("<notmap/>") + t:check(e3 and e3.code == Err.CORRUPT, "not a map") + local _, e4 = decode("{\"type\":\"map\",\"layers\":[{\"type\":\"weird\"}]}") + t:check(e4 and e4.code == Err.CORRUPT, "unknown layer type") + local _, e5 = Tiled.encode(maps.ortho, { format = "png" } :: any) + t:check(e5 and e5.code == Err.ARG, "unknown flavour") + local _, e6 = Tiled.encode({} :: any) + t:check(e6 and e6.code == Err.ARG, "not a TileMap") +end + +t:fuzz("decode", function(b: buffer) + return Tiled.decode(Bytes.reader(b)) +end, samples, { mutations = 6 }) +t:done() diff --git a/tools/bench.luau b/tools/bench.luau index 71ecaf0..75f4804 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -1,7 +1,8 @@ -- Throughput (bash tools/bench.sh): codec MB/s under both runtimes. MB/s are of decompressed output, best of n runs. -- Fixtures: tools/fixtures/deflate.py (a 6 MB corpus), tools/fixtures/png.py (1024 x 768 images), tools/fixtures/mp3.py, -- tools/fixtures/opus.py (3 s stereo files; MB/s of f32 output, 48 kHz stereo f32 is 0.384 MB/s of real time), --- tools/fixtures/flac.py; wav encodes / decodes a generated tone. +-- tools/fixtures/flac.py; wav encodes / decodes a generated tone; zstd / brotli / bzip2 / lzma (*_bench corpora), fonts +-- (glyphs per second), json / xml / yaml, jpeg / gif / tiff / qoi / tga / pnm / hdr and ImageOps. local Deflate = require("@formats/codecs/Deflate") local Crc32 = require("@formats/core/Crc32") local Bytes = require("@formats/core/Bytes") @@ -174,3 +175,486 @@ do end) print(string.format("%-8s %-30s %8.1fx real time", runtime, "", 10 / dt)) end +do + local Json = require("@formats/codecs/Json") + local JB = require("@tests/gen/json_bench") + local v = assert(Json.decode(JB.text)) + assert(Json.encode(v) == JB.compact, "json bench mismatch") + bench("json decode (indented)", 5, #JB.text, function() + Json.decode(JB.text) + end) + bench("json decode (compact)", 5, #JB.compact, function() + Json.decode(JB.compact) + end) + bench("json encode (compact, sorted)", 5, #JB.compact, function() + Json.encode(v) + end) +end +do + local Xml = require("@formats/codecs/Xml") + local XB = require("@tests/gen/xml_bench") + local doc = assert(Xml.decode(XB.text)) + bench("xml decode (DOM)", 5, #XB.text, function() + Xml.decode(XB.text) + end) + bench("xml events", 5, #XB.text, function() + for _ in Xml.events(XB.text) do + end + end) + bench("xml encode", 5, #XB.text, function() + Xml.encode(doc) + end) +end + +-- ws-arch codecs: zstd, brotli, bzip2, xz / lzma +do + local Zstd = require("@formats/codecs/Zstd") + local ZB = require("@tests/gen/zstd_bench") + local z3, z19 = buffer.fromstring(ZB.data3), buffer.fromstring(ZB.data19) + local zo = assert(Zstd.decompress(z3)) + assert(buffer.len(zo) == ZB.size and Crc32.of(zo) == ZB.crc, "zstd bench corpus mismatch") + bench("zstd -3 (+ xxh64)", 3, ZB.size, function() + Zstd.decompress(z3) + end) + bench("zstd -3 (no checksum)", 3, ZB.size, function() + Zstd.decompress(z3, nil, nil, { verify = false }) + end) + bench("zstd -19 (no checksum)", 3, ZB.size, function() + Zstd.decompress(z19, nil, nil, { verify = false }) + end) +end +do + local Brotli = require("@formats/codecs/Brotli") + local BB = require("@tests/gen/brotli_bench") + local bz = buffer.fromstring(BB.data) + local bout = assert(Brotli.decompress(bz)) + assert(buffer.len(bout) == BB.size and Crc32.of(bout) == BB.crc, "brotli bench corpus mismatch") + bench("brotli decompress (q9 w22)", 5, BB.size, function() + Brotli.decompress(bz) + end) +end +do + local Bzip2 = require("@formats/codecs/Bzip2") + local BZ = require("@tests/gen/bzip2_bench") + local bz = buffer.fromstring(BZ.data) + bench("bzip2 decompress -9", 3, BZ.size, function() + Bzip2.decompress(bz) + end) +end +do + local Lzma = require("@formats/codecs/Lzma") + local LB = require("@tests/gen/lzma_bench") + local lx, la = buffer.fromstring(LB.xz), buffer.fromstring(LB.alone) + local lo = assert(Lzma.xz(lx)) + assert(buffer.len(lo) == LB.size and Crc32.of(lo) == LB.crc, "lzma bench corpus mismatch") + bench("xz -6 (lzma2 + crc64)", 3, LB.size, function() + Lzma.xz(lx) + end) + bench("lzma alone -6", 3, LB.size, function() + Lzma.alone(la) + end) +end + +-- fonts: outlines and rasterization (MB/s here = thousands of glyphs per second) +do + local Ttf = require("@formats/font/ttf") + local FX = require("@tests/gen/fonts") + for _, c in FX.fonts do + if c.name == "Roboto-Medium" or c.name == "SourceSans3-Regular" then + local f = assert(Ttf.decode(Bytes.reader(buffer.fromstring(c.data)))) + local gl = {} + for cp = 33, 126 do + table.insert(gl, f:glyphIndex(cp)) + end + bench(c.name .. " outlines (kglyph/s)", 3, #gl * 1000, function() + for _, g in gl do + f:outline(g) + end + end) + bench(c.name .. " rasterize 32 px (kglyph/s)", 3, #gl * 1000, function() + for _, g in gl do + f:rasterize(g, 32) + end + end) + end + end +end +do + local Yaml = require("@formats/data/yaml") + local YB = require("@tests/gen/yaml_bench") + local yb = buffer.fromstring(YB.text) + local v = assert(Yaml.decode(Bytes.reader(yb))) + bench("yaml decode (block)", 3, #YB.text, function() + Yaml.decode(Bytes.reader(yb)) + end) + bench("yaml encode", 3, #YB.text, function() + Yaml.encode(v) + end) +end +-- ------------------------------------------------------------------------------------------------ jpeg (ws-imgA) +do + local Jpeg = require("@formats/image/jpeg") + local Types = require("@formats/Types") + local JB = require("@tests/gen/jpeg_bench") + for _, c in JB.files do + local b = buffer.fromstring(c.data) + local img = Jpeg.decode(Bytes.reader(b)) + assert(img and Crc32.of(img.pixels) == c.crc, "jpeg bench: " .. c.name .. " does not match djpeg") + bench("jpeg decode " .. c.name, 3, c.width * c.height * 4, function() + Jpeg.decode(Bytes.reader(b)) + end) + end + local b0 = buffer.fromstring(JB.files[1].data) + bench("jpeg decode 1/8 (DC only)", 3, JB.width * JB.height * 4, function() + Jpeg.decode(Bytes.reader(b0), { scale = 8 }) + end) + local src = Types.Image.new(JB.width, JB.height, "rgb8") + buffer.writestring(src.pixels, 0, JB.rgb) + for _, o in { { label = "baseline 4:2:0 q85", quality = 85 }, { label = "progressive 4:2:0 q85", quality = 85, progressive = true }, { label = "baseline 4:4:4 q85 optimized", quality = 85, subsampling = "444", optimize = true } } do + bench("jpeg encode " .. o.label, 2, JB.width * JB.height * 3, function() + Jpeg.encode(src, o :: any) + end) + end +end +-- ---------------------------------------------------------------------------------------- ws-imgA: gif + quantize +do + local Gif = require("@formats/image/gif") + local Quantize = require("@formats/codecs/Quantize") + local Types = require("@formats/Types") + local GB = require("@tests/gen/gif_bench") + local still = buffer.fromstring(GB.still) + local anim = buffer.fromstring(GB.anim) + local simg = assert(Gif.decode(Bytes.reader(still))) + local aimg = assert(Gif.decode(Bytes.reader(anim))) + local sw, sh = simg.width, simg.height + bench("gif decode 512x384", 5, sw * sh * 4, function() + Gif.decode(Bytes.reader(still)) + end) + bench("gif decode 40 x 128x128 anim", 3, #(aimg.frames :: any) * 128 * 128 * 4, function() + Gif.decode(Bytes.reader(anim)) + end) + bench("gif encode 512x384 (exact pal)", 3, sw * sh * 4, function() + Gif.encode(simg) + end) + local photo = Types.Image.new(sw, sh) + for i = 0, sw * sh - 1 do + local x, y = i % sw, i // sw + buffer.writeu32(photo.pixels, i * 4, (x % 256) + (y % 256) * 256 + ((x * y) % 256) * 65536 + 0xFF000000) + end + bench("quantize mediancut 256", 3, sw * sh * 4, function() + Quantize.palette(photo.pixels, sw, sh, 256) + end) + bench("quantize octree 256", 3, sw * sh * 4, function() + Quantize.palette(photo.pixels, sw, sh, 256, { method = "octree" }) + end) + local pal = Quantize.palette(photo.pixels, sw, sh, 256) + bench("quantize map", 3, sw * sh * 4, function() + Quantize.map(photo.pixels, sw, sh, pal) + end) + bench("quantize map + dither", 3, sw * sh * 4, function() + Quantize.map(photo.pixels, sw, sh, pal, { dither = true }) + end) + bench("gif encode 512x384 (quantize)", 2, sw * sh * 4, function() + Gif.encode(photo) + end) +end +-- ------------------------------------------------------------------------------------------------ ops/ImageOps +do + local Ops = require("@formats/ops/ImageOps") + local img = assert(Png.decode(Bytes.reader(buffer.fromstring(PB[1].data)))) + local n = img.width * img.height * 4 + bench("imageops resize 1/2 bilinear", 2, n, function() + Ops.resize(img, img.width // 2, img.height // 2, "bilinear") + end) + bench("imageops resize 1/2 lanczos", 2, n, function() + Ops.resize(img, img.width // 2, img.height // 2, "lanczos") + end) + bench("imageops resize x1.5 bilinear", 1, n, function() + Ops.resize(img, img.width * 3 // 2, img.height * 3 // 2, "bilinear") + end) + bench("imageops rotate 30 (expand)", 1, n, function() + Ops.rotate(img, 30) + end) + bench("imageops rotate90", 3, n, function() + Ops.rotate90(img, 1) + end) + bench("imageops convert rgba8 -> gray8", 3, n, function() + Ops.convert(img, "gray8") + end) + local other = assert(Ops.flip(img, "h")) + bench("imageops composite over", 3, n, function() + Ops.composite(img, other) + end) +end +-- ------------------------------------------------------------------------------------------------ image/tiff (ws-imgA) +do + local Tiff = require("@formats/image/tiff") + local Types = require("@formats/Types") + local src = Types.Image.new(1024, 768) + for i = 0, 1024 * 768 - 1 do + local x, y = i % 1024, i // 1024 + buffer.writeu32(src.pixels, i * 4, 0xFF000000 + (x % 256) + ((y % 256) * 256) + (((x + y) // 4 % 256) * 65536)) + end + for _, comp in { "none", "lzw", "deflate" } do + local enc = Tiff.encode(src, { compression = comp :: any }) :: buffer + bench("tiff decode rgba8 " .. comp, 3, 1024 * 768 * 4, function() + Tiff.decode(Bytes.reader(enc)) + end) + bench("tiff encode rgba8 " .. comp, 2, 1024 * 768 * 4, function() + Tiff.encode(src, { compression = comp :: any }) + end) + end + local enc16 = Tiff.encode(Types.Image.new(1024, 768, "rgba16"), { compression = "lzw" }) :: buffer + bench("tiff decode rgba16 lzw -> rgba8", 3, 1024 * 768 * 8, function() + Tiff.decode(Bytes.reader(enc16)) + end) +end +-- ------------------------------------------------------------------------------------------------ imgA-simple: qoi / tga / pnm / hdr +-- fixtures: tools/fixtures/qoi.py (tests/gen/qoi_bench.luau: run python3 -I tools/fixtures.py qoi first) +do + local Qoi = require("@formats/image/qoi") + local Tga = require("@formats/image/tga") + local Pnm = require("@formats/image/pnm") + local Hdr = require("@formats/image/hdr") + local Types = require("@formats/Types") + local QB = require("@tests/gen/qoi_bench") + local qd = buffer.fromstring(QB.data) + local n = QB.width * QB.height * 4 + bench("qoi decode 1024x768", 5, n, function() + Qoi.decode(Bytes.reader(qd)) + end) + local img = Types.Image.new(QB.width, QB.height) + img.pixels = buffer.fromstring(QB.pixels) + bench("qoi encode 1024x768", 5, n, function() + Qoi.encode(img) + end) + local tr = Tga.encode(img, { rle = true }) :: buffer + bench("tga decode rle 1024x768", 3, n, function() + Tga.decode(Bytes.reader(tr)) + end) + bench("tga encode rle 1024x768", 3, n, function() + Tga.encode(img, { rle = true }) + end) + local pp = Pnm.encode(img, { format = "ppm" }) :: buffer + bench("ppm decode 1024x768", 3, n, function() + Pnm.decode(Bytes.reader(pp)) + end) + local f = Hdr.decode(Bytes.reader(Hdr.encode(img) :: buffer), { native = true }) :: Types.Image + local hb = Hdr.encode(f) :: buffer + bench("hdr decode rle 1024x768 (rgbaf32)", 3, n, function() + Hdr.decode(Bytes.reader(hb), { native = true }) + end) + bench("hdr encode rle 1024x768", 3, n, function() + Hdr.encode(f) + end) +end +do + -- 3D (ws-3d): a 400 x 400 grid mesh (160k vertices, 318k triangles) through our own writers, then the readers; a + -- 128^3 noise voxel grid through VOX and greedy meshing + local Types = require("@formats/Types") + local MeshOps = require("@formats/ops/MeshOps") + local Gltf = require("@formats/model/gltf") + local Obj = require("@formats/model/obj") + local Stl = require("@formats/model/stl") + local Ply = require("@formats/model/ply") + local Vox = require("@formats/model/vox") + local N = 400 + local pos = Types.Scene.accessor(nil, "f32", 3, N * N) + local uv = Types.Scene.accessor(nil, "f32", 2, N * N) + for y = 0, N - 1 do + for x = 0, N - 1 do + local i = y * N + x + buffer.writef32(pos.data, i * 12, x / N) + buffer.writef32(pos.data, i * 12 + 4, math.sin(x * 0.1) * math.cos(y * 0.1) * 0.05) + buffer.writef32(pos.data, i * 12 + 8, y / N) + buffer.writef32(uv.data, i * 8, x / N) + buffer.writef32(uv.data, i * 8 + 4, y / N) + end + end + local ind = Types.Scene.accessor(nil, "u32", 1, (N - 1) * (N - 1) * 6) + local k = 0 + for y = 0, N - 2 do + for x = 0, N - 2 do + local a = y * N + x + for _, v in { a, a + N, a + 1, a + 1, a + N, a + N + 1 } do + buffer.writeu32(ind.data, k * 4, v) + k += 1 + end + end + end + local prim = { attributes = { POSITION = pos, TEXCOORD_0 = uv }, indices = ind, mode = "triangles" } :: any + MeshOps.computeNormals(prim) + local scene = Types.Scene.fromPrimitive(prim, "grid") + bench("meshops computeNormals 318k tris", 3, buffer.len(pos.data), function() + MeshOps.computeNormals(prim) + end) + local glb = assert(Gltf.encode(scene, { binary = true })) + bench("gltf glb decode (" .. buffer.len(glb) // 1000 .. " KB)", 5, buffer.len(glb), function() + Gltf.decode(Bytes.reader(glb)) + end) + bench("gltf glb encode", 3, buffer.len(glb), function() + Gltf.encode(scene, { binary = true }) + end) + local obj = assert(Obj.encode(scene)) + bench("obj decode (" .. buffer.len(obj) // 1000 .. " KB)", 2, buffer.len(obj), function() + Obj.decode(Bytes.reader(obj)) + end) + bench("obj encode", 2, buffer.len(obj), function() + Obj.encode(scene) + end) + local stl = assert(Stl.encode(scene)) + bench("stl binary decode (" .. buffer.len(stl) // 1000 .. " KB)", 5, buffer.len(stl), function() + Stl.decode(Bytes.reader(stl)) + end) + local ply = assert(Ply.encode(scene)) + bench("ply binary decode (" .. buffer.len(ply) // 1000 .. " KB)", 5, buffer.len(ply), function() + Ply.decode(Bytes.reader(ply)) + end) + local V = 128 + local grid = Types.Voxels.new(V, V, V) + for z = 0, V - 1 do + for y = 0, V - 1 do + for x = 0, V - 1 do + local h = (math.sin(x * 0.11) + math.cos(y * 0.07) + 2) * V / 8 + z * 0 + if z < h then + Types.Voxels.set(grid, x, y, z, 1 + (x // 8 + y // 8) % 6) + end + end + end + end + local vox = assert(Vox.encode(grid)) + bench("vox decode (" .. buffer.len(vox) // 1000 .. " KB)", 5, buffer.len(vox), function() + Vox.decode(Bytes.reader(vox)) + end) + bench("greedy mesh 128^3 (MB of cells)", 3, V * V * V, function() + MeshOps.voxelsToPrimitive(grid) + end) +end +do + -- layered + vector (ws-vec): PSD decode / encode of 8 RGBA layers 1024 x 768, flatten (codecs/Blend), SVG + -- rasterize at 512 x 512 (codecs/Raster). No fixtures: the inputs are built here. + local Types = require("@formats/Types") + local Psd = require("@formats/layered/psd") + local LayerOps = require("@formats/ops/LayerOps") + local Svg = require("@formats/vector/svg") + local W, H = 1024, 768 + local doc = Types.Layered.new(W, H) + local modes = { "normal", "multiply", "screen", "overlay", "normal", "softLight", "difference", "normal" } + for k = 1, 8 do + local img = Types.Image.new(W, H) + local px = img.pixels + for i = 0, W * H - 1 do + local x, y = i % W, i // W + buffer.writeu32(px, i * 4, ((x * k) % 256) + ((y * 3) % 256) * 256 + (((x + y) // 4) % 256) * 65536 + (if (x // 64 + y // 64 + k) % 3 == 0 then 0 else 200) * 16777216) + end + local l = Types.Layered.layer("L" .. k, img) + l.blend = modes[k] + doc.layers[k] = l + end + local psd = assert(Psd.encode(doc)) + bench("psd decode 8 layers 1024x768", 2, W * H * 4 * 9, function() + Psd.decode(Bytes.reader(psd)) + end) + bench("psd encode 8 layers (RLE)", 1, W * H * 4 * 9, function() + Psd.encode(doc) + end) + bench("flatten 8 layers (blend modes)", 2, W * H * 4 * 8, function() + LayerOps.flatten(doc) + end) + local shapes = {} + for k = 0, 39 do + table.insert(shapes, string.format("<circle cx='%d' cy='%d' r='%d' fill='url(#g)' stroke='#222' stroke-width='2' opacity='0.8'/>", (k * 37) % 100, (k * 53) % 100, 5 + k % 12)) + table.insert(shapes, string.format("<path d='M%d %d q 20 -30 40 0 t 40 0' fill='none' stroke='hsl(%d, 70%%, 50%%)' stroke-width='3' stroke-dasharray='4 2'/>", k % 50, k * 2, k * 9)) + end + local text = "<svg xmlns='http://www.w3.org/2000/svg' width='100' height='100'><defs><radialGradient id='g' fx='0.3' fy='0.3'><stop offset='0' stop-color='#fff'/><stop offset='1' stop-color='#36c'/></radialGradient></defs>" .. table.concat(shapes) .. "</svg>" + local v = assert(Svg.decode(Bytes.reader(buffer.fromstring(text)))) + bench("svg parse (80 elements)", 5, #text, function() + Svg.decode(Bytes.reader(buffer.fromstring(text))) + end) + bench("svg rasterize 512x512 (80 shapes)", 2, 512 * 512 * 4, function() + Svg.rasterize(v, 512, 512) + end) +end +do + local Webp = require("@formats/image/webp") + local WB = require("@tests/gen/webp_bench") + local n = WB.width * WB.height * 4 + local lossy, lossless = buffer.fromstring(WB.lossy), buffer.fromstring(WB.lossless) + bench("webp lossy decode 512x512", 3, n, function() + Webp.decode(Bytes.reader(lossy)) + end) + bench("webp lossless decode 512x512", 3, n, function() + Webp.decode(Bytes.reader(lossless)) + end) + local img = assert(Webp.decode(Bytes.reader(lossless))) + bench("webp lossless encode (effort 5)", 1, n, function() + Webp.encode(img) + end) + bench("webp lossless encode (effort 1)", 1, n, function() + Webp.encode(img, { effort = 1 }) + end) +end +do + local Xml = require("@formats/codecs/Xml") + local XB = require("@tests/gen/xml_bench") + local doc = assert(Xml.decode(XB.text)) + bench("xml decode (DOM)", 5, #XB.text, function() + Xml.decode(XB.text) + end) + bench("xml events", 5, #XB.text, function() + for _ in Xml.events(XB.text) do + end + end) + bench("xml encode", 5, #XB.text, function() + Xml.encode(doc) + end) +end + +-- ws-m4a: AAC-LC / ALAC decode and ALAC encode (MB/s of 16-bit PCM equivalent: frames * channels * 2), MDCT +do + local M4a = require("@formats/audio/m4a") + local Alac = require("@formats/codecs/Alac") + local Mdct = require("@formats/codecs/Mdct") + local MA = require("@tests/gen/m4a_aac") + local ML = require("@tests/gen/m4a_alac") + local aac = buffer.fromstring(MA[1].data) + local a = assert(M4a.decode(Bytes.reader(aac))) + bench("aac-lc decode (m4a, stereo)", 3, a.frames * a.channels * 2, function() + M4a.decode(Bytes.reader(aac)) + end) + local alac = buffer.fromstring(ML[1].data) + local l = assert(M4a.decode(Bytes.reader(alac))) + bench("alac decode (m4a, stereo 16)", 3, l.frames * l.channels * 2, function() + M4a.decode(Bytes.reader(alac)) + end) + local enc = assert(Alac.encoder({ sampleRate = 44100, channels = 2, bitDepth = 16 })) + local ints = table.create(a.frames * 2, 0) + for i = 1, a.frames * 2 do + ints[i] = math.floor(buffer.readf32(a.samples, (i - 1) * 4) * 32767) + end + bench("alac encode (stereo 16)", 2, a.frames * 2 * 2, function() + local f = 0 + while f < a.frames do + local n = math.min(4096, a.frames - f) + enc:encode(ints, f * 2 + 1, n) + f += n + end + end) + local plan = assert(Mdct.new(2048)) + local x, X = table.create(2048, 0.5), table.create(1024, 0) + bench("mdct 2048 x 1000 (forward)", 3, 1000 * 2048 * 4, function() + for _ = 1, 1000 do + Mdct.forward(plan, x, 1, X, 1) + end + end) +end +do + local Opus = require("@formats/audio/opus") + local Cases = require("@tests/audio/_opus_cases") + local c = Cases.list[2] + local a = Cases.signal(c) + local dt = bench("opus celt encode 128k (1.5 s st)", 2, a.frames * a.channels * 2, function() + Opus.encode(a, { bitrate = 128000 }) + end) + local _ = dt +end diff --git a/tools/bench.sh b/tools/bench.sh index afc7a43..64e3012 100644 --- a/tools/bench.sh +++ b/tools/bench.sh @@ -3,7 +3,7 @@ cd "$(dirname "$0")/.." || exit 1 LUAU=${LUAU:-$(command -v luau || nix shell nixpkgs#luau -c sh -c 'command -v luau')} LUAJIT=${LUAJIT:-$(command -v luajit || nix shell nixpkgs#luajit -c sh -c 'command -v luajit')} -python3 -I tools/fixtures.py deflate png mp3 opus flac vorbis > /dev/null || exit 1 +python3 -I tools/fixtures.py > /dev/null || exit 1 python3 -I tools/build.py luajit > /dev/null || exit 1 "$LUAU" --codegen -O2 tools/bench.luau "$LUAJIT" -e 'package.path = "build/luajit/?.lua;build/luajit/?/init.lua;" .. package.path' build/luajit/tools/bench.lua diff --git a/tools/brotli_static.py b/tools/brotli_static.py new file mode 100644 index 0000000..f0cecb3 --- /dev/null +++ b/tools/brotli_static.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python3 +# Brotli static data generator (python3 -I tools/brotli_static.py [brotli-source-dir]): writes +# src/Formats/codecs/Brotli/Static.luau from the official brotli C sources (MIT; licenses/brotli-LICENSE.txt): +# the 122784-byte RFC 7932 static dictionary (c/common/dictionary_inc.h, stored deflated + base64), the context +# lookup table (c/common/context.c) and the 121 word transforms (c/common/transform.c). +# Without an argument the source comes from `nix build nixpkgs#brotli.src`. +import base64, os, re, subprocess, sys, zlib + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +OUT = os.path.join(ROOT, "src", "Formats", "codecs", "Brotli", "Static.luau") + + +def c_array(text, name): + m = re.search(re.escape(name) + r"[^=]*=\s*\{(.*?)\};", text, re.S) + body = re.sub(r"/\*.*?\*/", "", m.group(1), flags=re.S) + body = body.replace("BROTLI_TRANSFORM_IDENTITY", "0").replace("BROTLI_TRANSFORM_UPPERCASE_FIRST", "10") + body = body.replace("BROTLI_TRANSFORM_UPPERCASE_ALL", "11") + body = re.sub(r"BROTLI_TRANSFORM_OMIT_LAST_(\d)", lambda k: k.group(1), body) + body = re.sub(r"BROTLI_TRANSFORM_OMIT_FIRST_(\d)", lambda k: str(11 + int(k.group(1))), body) + return [int(x, 0) for x in re.findall(r"0x[0-9a-fA-F]+|\d+", body)] + + +def c_string(text, name): + m = re.search(re.escape(name) + r"[^=]*=\s*(.*?);", text, re.S) + parts = re.findall(r'"((?:[^"\\]|\\.)*)"', re.sub(r"/\*.*?\*/", "", m.group(1), flags=re.S)) + s = "".join(parts) + return s.encode("latin-1").decode("unicode_escape").encode("latin-1") + b"\0" + + +def b64_chunks(data, width=96): + s = base64.b64encode(data).decode() + return [s[i:i + width] for i in range(0, len(s), width)] + + +def main(): + src = sys.argv[1] if len(sys.argv) > 1 else subprocess.run( + ["nix", "build", "nixpkgs#brotli.src", "--no-link", "--print-out-paths"], capture_output=True, check=True, + text=True).stdout.strip() + common = os.path.join(src, "c", "common") + dict_text = open(os.path.join(common, "dictionary_inc.h")).read() + dictionary = bytes(c_array(dict_text, "kBrotliDictionaryData")) + assert len(dictionary) == 122784 + ctx = bytes(c_array(open(os.path.join(common, "context.c")).read(), "_kBrotliContextLookupTable")) + assert len(ctx) == 2048 + tr_text = open(os.path.join(common, "transform.c")).read() + ps = c_string(tr_text, "kPrefixSuffix") + assert len(ps) == 217, len(ps) + psmap = c_array(tr_text, "kPrefixSuffixMap") + trans = c_array(tr_text, "kTransformsData") + assert len(psmap) == 50 and len(trans) == 363 + z = zlib.compress(dictionary, 9) + lines = [ + "--!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 {", + "\tdictionarySize = %d," % len(dictionary), + "\tdictionaryCrc = %d," % zlib.crc32(dictionary), + "\tdictionary = {", + ] + lines += ['\t\t"%s",' % c for c in b64_chunks(z)] + lines += ["\t},", "\tcontext = {"] + lines += ['\t\t"%s",' % c for c in b64_chunks(ctx)] + lines += ["\t},"] + lines += ['\tprefixSuffix = "%s",' % base64.b64encode(ps).decode()] + lines += ["\tprefixSuffixMap = { %s }," % ", ".join(map(str, psmap))] + lines += ["\ttransforms = {"] + for i in range(0, len(trans), 30): + lines.append("\t\t%s," % ", ".join(map(str, trans[i:i + 30]))) + lines += ["\t},", "}", ""] + with open(OUT, "w") as f: + f.write("\n".join(lines)) + print("brotli_static: wrote %s (%d bytes)" % (os.path.relpath(OUT, ROOT), os.path.getsize(OUT))) + + +if __name__ == "__main__": + main() diff --git a/tools/fixtures/7z.py b/tools/fixtures/7z.py new file mode 100644 index 0000000..aa4d0c4 --- /dev/null +++ b/tools/fixtures/7z.py @@ -0,0 +1,103 @@ +# 7z fixtures (tools/fixtures.py): a small tree (text, x86 machine code, runs, an empty file, empty and nested +# directories, UTF-16 names with accents and a surrogate pair) archived by 7-Zip 2x (nix _7zz) with many method chains: +# LZMA / LZMA2 / copy / Deflate, solid and non-solid, BCJ / ARM64 / delta filters, plain and compressed headers; plus +# BZip2 archives (codecs/Bzip2), archives whose methods are not supported (PPMd, BCJ2, AES) and an empty archive. +# tests/gen/7z.luau { files = { { name, dir, data?, mtime } }, cases = { { name, data, unsupported? } } } +import os, random, subprocess, sys, tempfile + +TOOL = "_7zz" + + +def tree(rng): + with open(os.path.realpath(sys.executable), "rb") as f: + code = f.read(60000) + base = os.path.dirname(os.__file__) + text = b"" + for name in sorted(os.listdir(base)): + if name.endswith(".py"): + with open(os.path.join(base, name), "rb") as f: + text += f.read() + if len(text) > 50000: + break + return [ + ("readme.txt", text[:50000]), + ("bin/code.bin", code), + ("bin/runs.dat", b"ab" * 5000 + b"\0" * 9000 + bytes(range(256)) * 8), + ("bin/random.dat", rng.randbytes(3000)), + ("empty.txt", b""), + ("emptydir/", None), + ("a/b/c/deep.txt", b"deep\n" * 10), + ("héllo wörld ☃.txt", "unicode ☃\n".encode()), + ("\U0001d11e clef.txt", b"g clef\n"), + ] + + +def generate(ctx): + rng = random.Random(77) + files = tree(rng) + mtime = 1600000000 + out_files = [] + cases = [] + with tempfile.TemporaryDirectory() as d: + src = os.path.join(d, "src") + for name, data in files: + p = os.path.join(src, name) + if data is None: + os.makedirs(p, exist_ok=True) + os.utime(p, (mtime, mtime)) + out_files.append({"name": name.rstrip("/"), "dir": True, "mtime": mtime}) + else: + os.makedirs(os.path.dirname(p), exist_ok=True) + with open(p, "wb") as f: + f.write(data) + os.utime(p, (mtime + 60, mtime + 60)) + out_files.append({"name": name, "dir": False, "data": data, "mtime": mtime + 60}) + for sub in ("bin", "a", "a/b", "a/b/c"): + os.utime(os.path.join(src, sub), (mtime, mtime)) + out_files.append({"name": sub, "dir": True, "mtime": mtime}) + + def make(name, args, unsupported=None): + arc = os.path.join(d, name + ".7z") + if os.path.exists(arc): + os.remove(arc) + subprocess.run(["nix", "shell", "nixpkgs#" + TOOL, "-c", "7zz", "a", "-bd", "-y", arc] + args + ["."], + cwd=src, capture_output=True, check=True) + with open(arc, "rb") as f: + c = {"name": name, "data": f.read()} + if unsupported: + c["unsupported"] = unsupported + cases.append(c) + + make("lzma-nonsolid", ["-m0=LZMA", "-ms=off", "-mhc=off"]) + make("lzma-solid", ["-m0=LZMA:d=1m", "-ms=on"]) + make("lzma2-solid", ["-m0=LZMA2", "-ms=on"]) + make("lzma2-mt-blocks", ["-m0=LZMA2:d=64k:c=20k", "-ms=on", "-mmt=4"]) + make("lzma2-hc-off", ["-m0=LZMA2", "-mhc=off"]) + make("copy", ["-m0=Copy", "-mhc=off"]) + make("copy-hc", ["-m0=Copy"]) + make("deflate", ["-m0=Deflate", "-ms=on"]) + make("bcj-lzma", ["-m0=BCJ", "-m1=LZMA", "-ms=on"]) + make("bcj-lzma2", ["-m0=BCJ", "-m1=LZMA2", "-ms=off"]) + make("arm64-lzma2", ["-m0=ARM64", "-m1=LZMA2"]) + make("arm-lzma2", ["-m0=ARM", "-m1=LZMA2"]) + make("delta-lzma", ["-m0=Delta:4", "-m1=LZMA"]) + make("ppc-sparc", ["-m0=PPC", "-m1=SPARC", "-m2=LZMA2"]) + make("lzma-lc-lp", ["-m0=LZMA:lc=0:lp=2:pb=0", "-ms=e"]) + make("auto", ["-mx=9"]) + make("fast", ["-mx=1"]) + make("bzip2", ["-m0=BZip2", "-mhc=off"]) + make("bzip2-solid-bcj", ["-m0=BCJ", "-m1=BZip2", "-ms=on", "-mhc=on"]) + make("ppmd", ["-m0=PPMd", "-mhc=off"], unsupported="ppmd") + make("bcj2", ["-m0=BCJ2", "-m1=LZMA", "-m2=LZMA", "-m3=LZMA", "-mb0s0:1", "-mb0s1:2", "-mb0s2:3", "-mhc=off"], + unsupported="bcj2") + make("aes", ["-m0=LZMA2", "-mhc=off", "-pSecret"], unsupported="aes") + # an empty archive + arc = os.path.join(d, "empty.7z") + empty = os.path.join(d, "emptysrc") + os.makedirs(empty) + subprocess.run(["nix", "shell", "nixpkgs#" + TOOL, "-c", "7zz", "a", "-bd", "-y", arc, "-x!*", "."], + cwd=empty, capture_output=True) + if os.path.exists(arc): + with open(arc, "rb") as f: + cases.append({"name": "empty", "data": f.read(), "empty": True}) + ctx.emit("7z", {"files": out_files, "cases": cases}) diff --git a/tools/fixtures/_data_common.py b/tools/fixtures/_data_common.py new file mode 100644 index 0000000..4ac47e8 --- /dev/null +++ b/tools/fixtures/_data_common.py @@ -0,0 +1,110 @@ +# Shared helpers for the data-format fixture generators (json, xml, csv, toml, yaml, msgpack, cbor, plist, ...): +# fetch(url, sha256) -> a nix store path of an unpacked tarball (official test suites, pinned by hash) +# canon(value) -> the canonical text a Luau test computes too (tests/data/_canon.luau): typed, sorted keys, +# numbers as %.17g, so Python's parse and ours compare exactly. +import os, subprocess, datetime + + +def fetch(url, sha256): + expr = 'builtins.fetchTarball { url = "%s"; sha256 = "%s"; }' % (url, sha256) + out = subprocess.run(["nix", "eval", "--raw", "--impure", "--expr", expr], capture_output=True, check=True) + return out.stdout.decode() + + +def _b(s): + if isinstance(s, str): + return s.encode("utf-8", "surrogatepass") + return bytes(s) + + +def canon(v): + """null n; true t; false f; number #%d (integral, under 2^53) or #%.17g; string s<len>:<bytes>; + bytes b<len>:<bytes>; list [..]; dict {k v ...} with keys sorted by their canon bytes; dates d<rfc3339>""" + out = bytearray() + _canon(v, out) + return bytes(out) + + +def num(x): + x = float(x) + if x != x: + return b"#nan" + if x in (float("inf"), float("-inf")): + return b"#inf" if x > 0 else b"#-inf" + if x == int(x) and abs(x) < 2 ** 53: + return b"#%d" % int(x) + return b"#" + ("%.17g" % x).encode() + + +def _canon(v, out): + if v is None: + out += b"n" + elif v is True: + out += b"t" + elif v is False: + out += b"f" + elif isinstance(v, (int, float)): + out += num(v) + elif isinstance(v, str): + b = _b(v) + out += b"s%d:" % len(b) + b + elif isinstance(v, (bytes, bytearray)): + out += b"b%d:" % len(v) + bytes(v) + elif isinstance(v, (list, tuple)): + out += b"[" + for x in v: + _canon(x, out) + out += b"," + out += b"]" + elif isinstance(v, dict): + items = [] + for k, x in v.items(): + kb = bytearray() + _canon(k, kb) + items.append((bytes(kb), x)) + items.sort(key=lambda p: p[0]) + out += b"{" + for kb, x in items: + out += kb + b"=" + _canon(x, out) + out += b"," + out += b"}" + elif isinstance(v, (datetime.datetime, datetime.date, datetime.time)): + out += b"d" + date_text(v).encode() + else: + raise TypeError("canon: %r" % type(v)) + + +def date_text(v): + """RFC 3339 the way Types.Date prints: fraction without trailing zeros, Z for +00:00""" + def frac(us): + return ("." + ("%06d" % us).rstrip("0")) if us else "" + + def tz(t): + off = t.utcoffset() + if off is None: + return "" + m = int(off.total_seconds()) // 60 + if m == 0: + return "Z" + sign = "-" if m < 0 else "+" + m = abs(m) + return "%s%02d:%02d" % (sign, m // 60, m % 60) + + if isinstance(v, datetime.datetime): + return "%04d-%02d-%02dT%02d:%02d:%02d%s%s" % (v.year, v.month, v.day, v.hour, v.minute, v.second, + frac(v.microsecond), tz(v)) + if isinstance(v, datetime.date): + return "%04d-%02d-%02d" % (v.year, v.month, v.day) + return "%02d:%02d:%02d%s" % (v.hour, v.minute, v.second, frac(v.microsecond)) + + +def python(ctx, packages, body): + """run body (with these helpers prepended, so canon() / date_text() exist) under a nix python with packages; + returns stdout bytes, raising with the script's stderr on failure""" + import subprocess as sp + src = open(os.path.abspath(__file__)).read() + try: + return ctx.python(packages, src + "\n" + body) + except sp.CalledProcessError as e: + raise RuntimeError("fixture python failed:\n" + e.stderr.decode(errors="replace")[-3000:]) diff --git a/tools/fixtures/_font_reference.py b/tools/fixtures/_font_reference.py new file mode 100644 index 0000000..17ba026 --- /dev/null +++ b/tools/fixtures/_font_reference.py @@ -0,0 +1,181 @@ +# Font reference data (run by tools/fixtures/fonts.py inside a nix python with fonttools, freetype-py, uharfbuzz and +# brotli). Reads a JSON list of {name, path | b64} on stdin; writes JSON on stdout: per font the bytes, the metrics, +# names, cmap samples (fontTools), advances / side bearings / control boxes / areas of sample glyphs (fontTools pens), +# kerning of sample pairs (HarfBuzz GPOS 'kern', or FreeType for 'kern' tables), FreeType renders (no hinting) of +# sample glyphs at a few sizes, and the WOFF / WOFF2 versions (fontTools). +import base64, io, json, sys + +import freetype +import uharfbuzz as hb +from fontTools.pens.areaPen import AreaPen +from fontTools.pens.boundsPen import ControlBoundsPen +from fontTools.ttLib import TTFont, newTable +from fontTools.ttLib.tables._k_e_r_n import KernTable_format_0 + +SAMPLE_TEXT = "AVTWYLPFoaey.,'\"-0147" +SIZES = [11, 24, 47] + + +def b64(b): + return base64.b64encode(b).decode() + + +def load(spec): + if "path" in spec: + return open(spec["path"], "rb").read() + return base64.b64decode(spec["b64"]) + + +def with_kern_table(data): + """a copy with a 'kern' format 0 table of a few pairs (none of the sample fonts has one)""" + f = TTFont(io.BytesIO(data)) + cmap = f.getBestCmap() + order = f.getGlyphOrder() + pairs = {} + letters = "AVTWYLoaey" + for i, a in enumerate(letters): + for j, b in enumerate(letters): + if ord(a) in cmap and ord(b) in cmap and (i * 7 + j * 3) % 4 == 0: + pairs[(cmap[ord(a)], cmap[ord(b)])] = -((i * 13 + j * 5) % 90) - 10 + k = newTable("kern") + k.version = 0 + st = KernTable_format_0() + st.version, st.coverage, st.format = 0, 1, 0 + st.kernTable = pairs + k.kernTables = [st] + f["kern"] = k + if "GPOS" in f: + del f["GPOS"] + out = io.BytesIO() + f.save(out) + return out.getvalue() + + +def collection(datas): + from fontTools.ttLib.ttCollection import TTCollection + c = TTCollection() + c.fonts = [TTFont(io.BytesIO(d)) for d in datas] + out = io.BytesIO() + c.save(out) + return out.getvalue() + + +def reference(name, data, index=0): + f = TTFont(io.BytesIO(data), fontNumber=index) + gs = f.getGlyphSet() + order = f.getGlyphOrder() + head, hhea, maxp = f["head"], f["hhea"], f["maxp"] + names = f["name"] + def nm(i): + r = names.getName(i, 3, 1, 0x409) or names.getName(i, 3, 1) or names.getName(i, 1, 0, 0) or names.getName(i, 0, 3) + return r.toUnicode() if r else "" + cmap = f.getBestCmap() or {} + cps = sorted(cmap) + sample_cps = cps[:: max(1, len(cps) // 150)] + [0x10FFFF, 0xFFFF, 0x7F, 0x9999] + cm = [[cp, f.getGlyphID(cmap[cp]) if cp in cmap else 0] for cp in sample_cps] + # glyphs: every glyph for small fonts, else a sample (plus the sample text's) + gids = list(range(len(order))) if len(order) <= 400 else list(range(0, len(order), len(order) // 300)) + for ch in SAMPLE_TEXT: + if ord(ch) in cmap: + gids.append(f.getGlyphID(cmap[ord(ch)])) + gids = sorted(set(gids)) + hmtx = f["hmtx"] + glyphs = [] + for g in gids: + gn = order[g] + adv, lsb = hmtx[gn] + bp = ControlBoundsPen(gs) + gs[gn].draw(bp) + ap = AreaPen(gs) + gs[gn].draw(ap) + e = {"gid": g, "adv": adv, "lsb": lsb, "area": float(ap.value)} + if bp.bounds: + e["box"] = [float(v) for v in bp.bounds] + glyphs.append(e) + # kerning + kern = [] + letters = [c for c in SAMPLE_TEXT if ord(c) in cmap] + if "kern" in f and "GPOS" not in f: + face = freetype.Face(io.BytesIO(data), index) + for a in letters: + for b in letters: + ga, gb = f.getGlyphID(cmap[ord(a)]), f.getGlyphID(cmap[ord(b)]) + v = face.get_kerning(a, b, freetype.FT_KERNING_UNSCALED) # freetype-py maps characters to glyphs + kern.append([ga, gb, v.x]) + elif "GPOS" in f: + blob = hb.Blob(data) + hface = hb.Face(blob, index) + hfont = hb.Font(hface) + feats = {"kern": True, "liga": False, "clig": False, "calt": False, "mark": False, "mkmk": False, "ccmp": False, "locl": False, "rlig": False, "dist": False, "curs": False} + for a in letters: + for b in letters: + buf = hb.Buffer() + buf.add_str(a + b) + buf.guess_segment_properties() + hb.shape(hfont, buf, feats) + ga, gb = buf.glyph_infos[0].codepoint, buf.glyph_infos[1].codepoint + adv = buf.glyph_positions[0].x_advance - hmtx[order[ga]][0] + kern.append([ga, gb, adv]) + # FreeType renders + face = freetype.Face(io.BytesIO(data), index) + renders = [] + rg = [f.getGlyphID(cmap[ord(c)]) for c in "AgQ@&e%" if ord(c) in cmap] + for px in SIZES: + face.set_pixel_sizes(0, px) + for g in rg: + face.load_glyph(g, freetype.FT_LOAD_NO_HINTING | freetype.FT_LOAD_NO_BITMAP) + face.glyph.render(freetype.FT_RENDER_MODE_NORMAL) + bm = face.glyph.bitmap + rows = [] + for y in range(bm.rows): + rows.append(bytes(bm.buffer[y * bm.pitch: y * bm.pitch + bm.width])) + renders.append({"gid": g, "px": px, "w": bm.width, "h": bm.rows, "left": face.glyph.bitmap_left, + "top": face.glyph.bitmap_top, "pixels": b64(b"".join(rows))}) + os2 = f["OS/2"] if "OS/2" in f else None + return { + "name": name, "data": b64(data), "index": index, "upem": head.unitsPerEm, "ascent": hhea.ascent, + "descent": hhea.descent, "lineGap": hhea.lineGap, "numGlyphs": maxp.numGlyphs, "family": nm(16) or nm(1), + "style": nm(17) or nm(2), "fullName": nm(4), "weight": os2.usWeightClass if os2 else 0, + "cff": "CFF " in f, "cmap": cm, "glyphs": glyphs, "kern": kern, "renders": renders, + } + + +def flavors(data): + out = {} + for fl in ("woff", "woff2"): + f = TTFont(io.BytesIO(data)) + f.flavor = fl + b = io.BytesIO() + f.save(b) + out[fl] = b64(b.getvalue()) + from fontTools.ttLib import woff2 + src, dst = io.BytesIO(data), io.BytesIO() + woff2.compress(src, dst, transform_tables={"glyf", "loca", "hmtx"}) + out["woff2h"] = b64(dst.getvalue()) + return out + + +def main(): + specs = json.load(sys.stdin) + fonts = {} + for s in specs: + fonts[s["name"]] = load(s) + res = {"fonts": [], "woff": []} + for name, data in fonts.items(): + res["fonts"].append(reference(name, data)) + kd = with_kern_table(fonts["ProggyClean"] if "ProggyClean" in fonts else next(iter(fonts.values()))) + res["fonts"].append(reference("kern-table", kd)) + names = [n for n in ("Karla-Regular", "Cousine-Regular") if n in fonts] + if len(names) == 2: + ttc = collection([fonts[n] for n in names]) + r = reference("collection-1", ttc, 1) + res["fonts"].append(r) + res["ttc"] = {"data": b64(ttc), "count": 2, "second": names[1]} + # woff / woff2 of every font (the reference values are the sfnt's own) + for name, data in fonts.items(): + fl = flavors(data) + res["woff"].append({"name": name, "woff": fl["woff"], "woff2": fl["woff2"], "woff2h": fl["woff2h"]}) + json.dump(res, sys.stdout) + + +main() diff --git a/tools/fixtures/_gltf_encode.luau b/tools/fixtures/_gltf_encode.luau new file mode 100644 index 0000000..b7c037f --- /dev/null +++ b/tools/fixtures/_gltf_encode.luau @@ -0,0 +1,34 @@ +-- tools/fixtures/_gltf_encode: run by tools/fixtures/gltf.py (luau CLI, repo root): decodes every glTF case with our +-- reader and encodes it with our writer as .glb and as .gltf with an external .bin and image files, printing +-- "<file>\t<hex>" lines for the reference tools (assimp, trimesh) to read back. Files: rt_<case>.glb, rt_<case>.gltf. +local Gltf = require("@formats/model/gltf") +local Bytes = require("@formats/core/Bytes") +local Cases = require("@tests/gen/gltf_cases") + +local HEX = {} +for i = 0, 255 do + HEX[i] = string.format("%02x", i) +end +local function hex(s: string): string + local out = table.create(#s) + for i = 1, #s do + out[i] = HEX[string.byte(s, i)] + end + return table.concat(out) +end + +for i, c in Cases do + local scene, err = Gltf.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files }) + if scene then + local glb = assert(Gltf.encode(scene, { binary = true })) + print(string.format("rt_%d.glb\t%s", i, hex(buffer.tostring(glb)))) + local files = {} + local gltf = assert(Gltf.encode(scene, { external = true, files = files, name = "rt_" .. i .. ".gltf" })) + print(string.format("rt_%d.gltf\t%s", i, hex(buffer.tostring(gltf)))) + for name, data in files do + print(name .. "\t" .. hex(if type(data) == "string" then data else buffer.tostring(data))) + end + else + print("skipped " .. c.name .. ": " .. tostring(err)) + end +end diff --git a/tools/fixtures/_m4a_encode.luau b/tools/fixtures/_m4a_encode.luau new file mode 100644 index 0000000..8a42eb5 --- /dev/null +++ b/tools/fixtures/_m4a_encode.luau @@ -0,0 +1,31 @@ +-- tools/fixtures/_m4a_encode: run by tools/fixtures/m4a.py (luau, from the repo root) so the reference tools can check +-- our writers: encodes the test signal (tests/audio/_signal) to ALAC M4A (audio/m4a) and ALAC / PCM CAF (audio/caf) +-- and prints "<name> <hex>" lines. The tests re-encode and compare the CRC with the file ffmpeg validated. +local Signal = require("@tests/audio/_signal") +local M4a = require("@formats/audio/m4a") +local Caf = require("@formats/audio/caf") + +local function hex(b: buffer): string + local t = table.create(buffer.len(b)) + for i = 0, buffer.len(b) - 1 do + t[i + 1] = string.format("%02x", buffer.readu8(b, i)) + end + return table.concat(t) +end + +local Cases = require("@tests/audio/_encode_cases") +for _, c in Cases do + local a = Signal.audio(c.rate, c.frames, c.channels, c.bits, c.seed) + a.tags = c.tags or {} + local out, err + if c.container == "caf" then + out, err = Caf.encode(a, { codec = c.codec, bitDepth = c.bits }) + else + out, err = M4a.encode(a, { bitDepth = c.bits }) + end + if not out then + print(c.name .. " ERROR " .. tostring(err)) + else + print(c.name .. " " .. hex(out)) + end +end diff --git a/tools/fixtures/_m4a_signal.py b/tools/fixtures/_m4a_signal.py new file mode 100644 index 0000000..7eb72ed --- /dev/null +++ b/tools/fixtures/_m4a_signal.py @@ -0,0 +1,41 @@ +# The deterministic integer test signal shared by tools/fixtures/m4a.py, tools/fixtures/caf.py and the Luau side +# (tests/audio/_signal.luau computes the same numbers): triangle + square + MINSTD noise (exact in doubles) + clicks, per channel. +import struct + + +def signal(frames, channels, bits, seed): + s = seed + peak = 2 ** (bits - 1) - 1 + out = [] + for i in range(frames): + for c in range(channels): + s = (s * 48271) % 2147483647 + p1 = 97 + 31 * c + tri = abs((i % p1) * 2 - p1) * 2 - p1 + v = tri * (peak // (4 * p1)) + p2 = 1500 + 200 * c + v += (peak // 6) if (i // p2) % 2 == 0 else -(peak // 6) + v += ((s // 65536) % 4096 - 2048) * (peak // 65536 + 1) + if i % 7001 < 3: + v += peak // 2 + out.append(max(-peak - 1, min(peak, v))) + return out + + +def pack(samples, bits, big=False): + e = ">" if big else "<" + if bits == 16: + return struct.pack(e + "%dh" % len(samples), *samples) + if bits == 24: + b = bytearray() + for v in samples: + x = struct.pack("<i", v)[:3] + b += x[::-1] if big else x + return bytes(b) + return struct.pack(e + "%di" % len(samples), *samples) + + +def wav(samples, channels, rate, bits): + data = pack(samples, bits) + fmt = struct.pack("<HHIIHH", 1, channels, rate, rate * channels * bits // 8, channels * bits // 8, bits) + return b"RIFF" + struct.pack("<I", 36 + len(data)) + b"WAVEfmt " + struct.pack("<I", 16) + fmt + b"data" + struct.pack("<I", len(data)) + data diff --git a/tools/fixtures/_model_ref.py b/tools/fixtures/_model_ref.py new file mode 100644 index 0000000..6cd3ede --- /dev/null +++ b/tools/fixtures/_model_ref.py @@ -0,0 +1,69 @@ +# Shared helpers for the model fixture generators (obj.py, gltf.py): reference tools through nix. +# assimp_info(ctx, paths, raw?) -> [ { meshes, materials, vertices, faces, nodes, min, max, perMesh = [ { vertices, faces } ] } ] +# trimesh_metrics(ctx, paths) -> [ { area, faces, bounds, volume? } ] (trimesh, process=False, every geometry merged) +# luau_encode(ctx, script) -> { name: bytes }: runs a Luau script (repo-relative, .luaurc aliases) that prints +# "<name>\t<hex>" lines: how a generator gets our encoder's output for the reference tools to read back. +import json, os, re, subprocess, tempfile, shutil + +FLOAT = r"(-?[\d.]+(?:e[-+]?\d+)?|-?nan|-?inf)" + + +def assimp_info(ctx, paths, raw=False): + # raw: `assimp info -r` (no post-processing: no joined vertices, no merged identical meshes) + out = [] + for p in paths: + try: + txt = ctx.nix("assimp", ["assimp", "info", p] + (["-r"] if raw else [])).decode("utf-8", "replace") + except subprocess.CalledProcessError: + out.append({"failed": True}) + continue + + def num(label): + m = re.search(r"^" + label + r":\s+(\d+)", txt, re.M) + return int(m.group(1)) if m else -1 + + def point(label): + m = re.search(label + r"\s+\(" + FLOAT + " " + FLOAT + " " + FLOAT + r"\)", txt) + return [float(m.group(i)) for i in (1, 2, 3)] if m else [] + + per = [{"vertices": int(a), "faces": int(c)} for a, b, c in re.findall(r"^\s+\d+ \(.*?\): \[(\d+) / (\d+) / (\d+) \|", txt, re.M)] + out.append({ + "meshes": num("Meshes"), "materials": num("Materials"), "vertices": num("Vertices"), "faces": num("Faces"), + "nodes": num("Nodes"), "min": point("Minimum point"), "max": point("Maximum point"), "perMesh": per, + }) + return out + + +TRIMESH = r""" +import json, sys, trimesh, numpy as np +res = [] +for p in json.loads(sys.stdin.read()): + try: + m = trimesh.load(p, force="mesh", process=False) + d = {"area": float(m.area), "faces": int(len(m.faces)), "bounds": [float(v) for v in np.asarray(m.bounds).ravel()] if len(m.faces) else []} + except Exception as e: + d = {"failed": True} + res.append(d) +print(json.dumps(res)) +""" + + +def trimesh_metrics(ctx, paths): + out = ctx.python(["trimesh", "numpy", "networkx", "lxml", "pillow"], TRIMESH, input=json.dumps(paths).encode()) + return json.loads(out) + + +def luau_encode(ctx, script): + exe = shutil.which("luau") + cmd = [exe, script] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau", script] + res = subprocess.run(cmd, cwd=ctx.root, capture_output=True, check=True) + files = {} + for line in res.stdout.decode().split("\n"): + if "\t" in line: + name, hexdata = line.split("\t", 1) + files[name] = bytes.fromhex(hexdata.strip()) + return files + + +def tempdir(): + return tempfile.mkdtemp(prefix="formats-model-") diff --git a/tools/fixtures/_obj_encode.luau b/tools/fixtures/_obj_encode.luau new file mode 100644 index 0000000..cc38920 --- /dev/null +++ b/tools/fixtures/_obj_encode.luau @@ -0,0 +1,32 @@ +-- tools/fixtures/_obj_encode: run by tools/fixtures/obj.py (luau CLI, repo root): decodes every OBJ case with our +-- reader, encodes it again with our writer and prints "<file>\t<hex>" lines (the OBJ, its .mtl, textures) for the +-- reference tools (assimp, trimesh) to read back. +local Obj = require("@formats/model/obj") +local Bytes = require("@formats/core/Bytes") +local Cases = require("@tests/gen/obj_cases") + +local HEX = {} +for i = 0, 255 do + HEX[i] = string.format("%02x", i) +end +local function hex(s: string): string + local out = table.create(#s) + for i = 1, #s do + out[i] = HEX[string.byte(s, i)] + end + return table.concat(out) +end + +for _, c in Cases do + local scene, err = Obj.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files }) + if not scene then + error(c.name .. ": " .. tostring(err)) + end + local name = "rt_" .. c.name + local files = {} + local out = assert(Obj.encode(scene, { name = name, files = files })) + print(name .. "\t" .. hex(buffer.tostring(out))) + for fname, data in files do + print(fname .. "\t" .. hex(if type(data) == "string" then data else buffer.tostring(data))) + end +end diff --git a/tools/fixtures/_off_encode.luau b/tools/fixtures/_off_encode.luau new file mode 100644 index 0000000..2fbb49c --- /dev/null +++ b/tools/fixtures/_off_encode.luau @@ -0,0 +1,56 @@ +-- tools/fixtures/_off_encode.luau: run by tools/fixtures/off.py under the luau CLI (no file I/O): encodes the scenes of +-- tests/gen/off_scenes with each listed option set ("default" = {}, "plain" = no colours / normals / texcoords) and +-- prints "<scene>/<encoding> <hex>" lines, which the fixture step hands to trimesh, assimp and its own reader. +local Off = require("@formats/model/off") +local Types = require("@formats/Types") +local Scenes = require("@tests/gen/off_scenes") + +local function build(spec: any): Types.Scene + local scene = Types.Scene.new() + for i, m in spec.meshes do + local prims = {} + for _, p in m.prims do + local attrs = {} + for name, a in p.attrs do + attrs[name] = Types.Scene.accessor(buffer.fromstring(a[3]), a[1], a[2], p.count) + end + local prim: any = { attributes = attrs, mode = p.mode } + if p.indices then + prim.indices = Types.Scene.accessor(buffer.fromstring(p.indices), "u32", 1, #p.indices // 4) + end + if p.faces then + prim.faces = Types.Scene.accessor(buffer.fromstring(p.faces), "u32", 1, #p.faces // 4) + end + if p.faceColors then + prim.extras = { faceColors = Types.Scene.accessor(buffer.fromstring(p.faceColors), "unorm8", 4, #p.faceColors // 4) } + end + table.insert(prims, prim) + end + scene.meshes[i] = { primitives = prims } + end + for i, n in spec.nodes do + scene.nodes[i] = { mesh = n.mesh, children = n.children or {}, translation = n.translation, rotation = n.rotation, scale = n.scale, matrix = n.matrix } + end + scene.roots = spec.roots + return scene +end + +local function hex(b: buffer): string + local out = table.create(buffer.len(b)) + for i = 0, buffer.len(b) - 1 do + out[i + 1] = string.format("%02x", buffer.readu8(b, i)) + end + return table.concat(out) +end + +local OPTS: { [string]: any } = { default = {}, plain = { colors = false, normals = false, texcoords = false } } +for _, spec in Scenes do + local scene = build(spec) + for e in spec.encodings do + local b, err = Off.encode(scene, OPTS[e]) + if not b then + error(spec.name .. "/" .. e .. ": " .. tostring(err)) + end + print(spec.name .. "/" .. e .. " " .. hex(b)) + end +end diff --git a/tools/fixtures/_off_reference.py b/tools/fixtures/_off_reference.py new file mode 100644 index 0000000..89f961a --- /dev/null +++ b/tools/fixtures/_off_reference.py @@ -0,0 +1,32 @@ +# OFF reference values (run by tools/fixtures/off.py through ctx.python(["trimesh", "numpy"], ...), python -I). +# stdin: JSON {"dir": tmp, "make": [name], "read": [name]} +# stdout: JSON {name (only the files trimesh reads): {"vertices": n, "pos_crc": crc of the f32 vertices, "faces": [[...]] or None (n-gons over 4)}} +# make: OFF files written by trimesh (an icosphere, a capsule) +# read: every file read with trimesh.exchange.off.load_off (positions; faces when all are triangles / quads, the +# only polygons trimesh keeps as they are) +import json, os, sys, zlib +import numpy as np +import trimesh +from trimesh.exchange import off as toff + +req = json.load(sys.stdin) +d = req["dir"] +out = {} +for name in req["make"]: + m = trimesh.creation.icosphere(subdivisions=2, radius=3.0) if "ico" in name else trimesh.creation.capsule(height=2.0, radius=0.5) + with open(os.path.join(d, name), "w") as f: + f.write(toff.export_off(m, digits=9)) +for name in req["read"]: + try: + with open(os.path.join(d, name), "rb") as f: + r = toff.load_off(f) + except Exception: # noqa: BLE001 - trimesh fails on polygons of more than 4 vertices: no reference then + continue + v = np.asarray(r["vertices"], dtype=np.float64).reshape(-1, 3) + res = {"vertices": len(v), "pos_crc": zlib.crc32(v.astype("<f4").tobytes())} + faces = r.get("faces") + res["tris"] = int(len(faces)) if faces is not None and len(np.shape(faces)) == 2 and np.shape(faces)[1] == 3 else -1 + if res["tris"] >= 0: + res["faces"] = [[int(x) for x in f] for f in np.asarray(faces)] + out[name] = res +json.dump(out, sys.stdout) diff --git a/tools/fixtures/_opus_encode.luau b/tools/fixtures/_opus_encode.luau new file mode 100644 index 0000000..a974148 --- /dev/null +++ b/tools/fixtures/_opus_encode.luau @@ -0,0 +1,17 @@ +-- tools/fixtures/_opus_encode: run by tools/fixtures/opus_celt.py (luau, from the repo root): encodes +-- tests/audio/_opus_cases with audio/opus's CELT encoder and prints "<name> <hex>" lines for opusdec / ffmpeg. +local Opus = require("@formats/audio/opus") +local Cases = require("@tests/audio/_opus_cases") + +for _, c in Cases.list do + local out, err = Opus.encode(Cases.signal(c), { bitrate = c.bitrate }) + if not out then + print(c.name .. " ERROR " .. tostring(err)) + else + local t = table.create(buffer.len(out)) + for i = 0, buffer.len(out) - 1 do + t[i + 1] = string.format("%02x", buffer.readu8(out, i)) + end + print(c.name .. " " .. table.concat(t)) + end +end diff --git a/tools/fixtures/_ours.luau b/tools/fixtures/_ours.luau new file mode 100644 index 0000000..146e416 --- /dev/null +++ b/tools/fixtures/_ours.luau @@ -0,0 +1,180 @@ +-- tools/fixtures/_ours.luau: our encoders' output for the reference tools to read (run by tools/fixtures/*.py through +-- `luau tools/fixtures/_ours.luau -a <format>`). Prints one JSON object: { "data": hex of the encoded file, ... the +-- facts the python side checks the reference's reading against }. +local Types = require("@formats/Types") +local Crc32 = require("@formats/core/Crc32") +local LayerOps = require("@formats/ops/LayerOps") + +local function hex(b: buffer): string + local t = table.create(buffer.len(b)) + for i = 0, buffer.len(b) - 1 do + t[i + 1] = string.format("%02x", buffer.readu8(b, i)) + end + return table.concat(t) +end + +local function jstr(s: string): string + return '"' .. string.gsub(s, '[%c"\\]', function(c: string): string + return string.format("\\u%04x", string.byte(c)) + end) .. '"' +end + +local function json(v: any): string + if type(v) == "table" then + if #v > 0 or next(v) == nil then + local t = {} + for i, x in v do + t[i] = json(x) + end + return "[" .. table.concat(t, ",") .. "]" + end + local t = {} + for k, x in v do + table.insert(t, jstr(k) .. ":" .. json(x)) + end + return "{" .. table.concat(t, ",") .. "}" + elseif type(v) == "string" then + return jstr(v) + elseif type(v) == "boolean" then + return if v then "true" else "false" + end + return tostring(v) +end + +-- a deterministic rgba8 image +local function image(w: number, h: number, seed: number, alpha: boolean?): Types.Image + local img = Types.Image.new(w, h) + for y = 0, h - 1 do + for x = 0, w - 1 do + local o = (y * w + x) * 4 + buffer.writeu8(img.pixels, o, (x * (seed + 3) * 7 + y * 5) % 256) + buffer.writeu8(img.pixels, o + 1, (y * (seed + 1) * 9 + x) % 256) + buffer.writeu8(img.pixels, o + 2, ((x + seed) * (y + 1) * 3) % 256) + buffer.writeu8(img.pixels, o + 3, if alpha and (x + y) % 3 == 0 then (x * 40 + seed) % 256 else 255) + end + end + return img +end +local function gray(w: number, h: number): Types.Image + local img = Types.Image.new(w, h, "gray8") + for i = 0, w * h - 1 do + buffer.writeu8(img.pixels, i, (i * 13) % 256) + end + return img +end + +-- the Layered document tests/layered/psd.luau also builds (keep them in step) +local function psdDoc(): Types.Layered + local L = Types.Layered + local doc = L.new(36, 24) + local bg = L.layer("Background", image(36, 24, 1)) + local mul = L.layer("Multiply", image(20, 12, 2, true), 4, 3) + mul.blend = "multiply" + mul.opacity = 200 / 255 + local scr = L.layer("Screen", image(18, 18, 3, true), 12, 4) + scr.blend = "screen" + local iso = L.group("Isolated", { scr }) + iso.blend = "normal" + iso.opacity = 180 / 255 + local hid = L.layer("Hidden", image(8, 8, 4), 1, 1) + hid.visible = false + local diff = L.layer("Diff \u{e9}\u{65e5}", image(14, 10, 5, true), 18, 12) + diff.blend = "difference" + local pass = L.group("Pass", { hid, diff }) + local base = L.layer("Base", image(10, 8, 6), 24, 14) + local clip = L.layer("Clipped", image(14, 12, 7, true), 20, 10) + clip.clip = true + local masked = L.layer("Masked", image(16, 10, 8), 2, 12) + masked.mask = { image = gray(12, 8), x = 4, y = 13, default = 0 } + local fill = L.layer("Fill", image(8, 24, 9, true), 28, 0) + fill.fillOpacity = 128 / 255 + fill.blend = "lighten" + doc.layers = { bg, mul, iso, pass, base, clip, masked, fill } + return doc +end + +-- an animated sprite (tests/layered/aseprite.luau builds the same one) +local function aseDoc(): Types.Layered + local L = Types.Layered + local doc = L.new(24, 16) + local bgImg = image(24, 16, 1) + local shared = image(10, 8, 2, true) + local frames = {} + for f = 1, 3 do + local bg = L.layer("Background", bgImg) + local mul = L.layer("Mul", if f == 2 then image(10, 8, 7, true) else shared, 3 + (if f == 2 then 1 else 0), 2) + mul.blend = "multiply" + local half = L.layer("Half", image(12, 9, 3 + f, true), f * 2, 4) + half.fillOpacity = 128 / 255 + local g = L.group("Group", { mul, half }) + local top = L.layer("Top", image(6, 6, 9 + f, true), 16 - f, 8) + top.opacity = 200 / 255 + frames[f] = { layers = { bg, g, top }, delay = 0.05 * f } + end + doc.frames = frames + doc.layers = frames[1].layers + doc.meta.tags = { { name = "all", from = 1, to = 3, direction = "pingpong", ["repeat"] = 0 } } + return doc +end + +-- a Tiled map (tools/fixtures/tiled.py has Tiled read our TMX and TMJ of it) +local function tiledMap(): Types.TileMap + local m: any = Types.TileMap.new(5, 4, 16, 16) + m.nextLayerId, m.nextObjectId = 5, 4 + m.properties = { name = "ours", n = 7, f = 0.5, ok = false, c = "#ff112233" } + m.propertyTypes = { c = "color" } + m.tilesets = { { firstGid = 1, name = "tiles", tileWidth = 16, tileHeight = 16, columns = 4, count = 8, spacing = 0, margin = 0, imageSource = "tiles.png", imageWidth = 64, imageHeight = 32, properties = {}, tiles = { { id = 2, class = "Wall", properties = { hard = true } }, { id = 4, properties = {}, animation = { { tileId = 4, duration = 120 }, { tileId = 5, duration = 80 } } } } } } + local data = {} + for i = 1, 20 do + data[i] = (i * 3) % 9 + end + data[2] += 0x80000000 + data[10] += 0x40000000 + local tiles = { type = "tiles", id = 1, name = "ground", width = 5, height = 4, data = data, visible = true, opacity = 0.8, offsetX = 2, offsetY = 0, properties = { deep = 3 }, encoding = "base64", compression = "zlib" } + local objs = { + { id = 1, name = "a", class = "Spawn", x = 4, y = 5.5, width = 8, height = 8, rotation = 30, visible = true, shape = "rectangle", properties = { team = "red" } }, + { id = 2, name = "b", class = "", x = 20, y = 10, width = 0, height = 0, rotation = 0, visible = true, shape = "polyline", points = { { 0, 0 }, { 8, 4 }, { 16, 0 } }, properties = {} }, + { id = 3, name = "c", class = "", x = 30, y = 30, width = 60, height = 14, rotation = 0, visible = false, shape = "text", text = { text = "hi there", fontFamily = "sans-serif", pixelSize = 14, wrap = true, color = "#00ff00", bold = false, italic = true, underline = false, strikeout = false, kerning = true, halign = "right", valign = "top" }, properties = {} }, + } + local og = { type = "objects", id = 3, name = "things", visible = true, opacity = 1, drawOrder = "topdown", objects = objs, properties = {} } + local img = { type = "image", id = 4, name = "sky", visible = true, opacity = 1, imageSource = "sky.png", imageWidth = 40, imageHeight = 20, repeatX = true, repeatY = false, properties = {} } + local group = { type = "group", id = 2, name = "grp", visible = true, opacity = 0.5, layers = { og, img }, properties = {} } + m.layers = { tiles, group } + return m +end + +local which, arg = ... +if which == "psd" then + local Psd = require("@formats/layered/psd") + local doc = psdDoc() + local data = Psd.encode(doc) :: buffer + local flat = LayerOps.flatten(doc) :: Types.Image + local layers = {} + for l, depth in LayerOps.leaves(doc.layers) do + local lay = l :: any + table.insert(layers, { name = lay.name, crc = Crc32.of(lay.image.pixels), left = lay.x, top = lay.y, width = lay.image.width, height = lay.image.height, blend = lay.blend, visible = lay.visible, clip = lay.clip == true, opacity = math.floor(lay.opacity * 255 + 0.5), depth = depth }) + end + print(json({ data = hex(data), composite = Crc32.of(flat.pixels), layers = layers })) +elseif which == "aseprite" then + local Ase = require("@formats/layered/aseprite") + local doc = aseDoc() + local data = Ase.encode(doc) :: buffer + local frames = {} + for f = 1, 3 do + frames[f] = hex((LayerOps.flatten(doc, { frame = f }) :: Types.Image).pixels) + end + print(json({ data = hex(data), nframes = 3, frames = frames })) +elseif which == "tiled" then + local Tiled = require("@formats/vector/tiled") + local m = tiledMap() + local tmx = Tiled.encode(m, { format = "tmx" }) :: buffer + local tmj = Tiled.encode(m, { format = "tmj" }) :: buffer + print(json({ tmx = hex(tmx), tmj = hex(tmj) })) +elseif which == "svg" then + -- the SVG text given on the command line, decoded and written back by our encoder + local Svg = require("@formats/vector/svg") + local Bytes = require("@formats/core/Bytes") + local v = Svg.decode(Bytes.reader(buffer.fromstring(arg))) + local out = if v then Svg.encode(v) else nil + print(json({ svg = if out then buffer.tostring(out) else "" })) +end diff --git a/tools/fixtures/_ply_encode.luau b/tools/fixtures/_ply_encode.luau new file mode 100644 index 0000000..0418d8a --- /dev/null +++ b/tools/fixtures/_ply_encode.luau @@ -0,0 +1,52 @@ +-- tools/fixtures/_ply_encode.luau: run by tools/fixtures/ply.py under the luau CLI (no file I/O): encodes the scenes of +-- tests/gen/ply_scenes in the three encodings and prints "<scene>/<encoding> <hex>" lines, which the fixture step +-- hands to plyfile and assimp. +local Ply = require("@formats/model/ply") +local Types = require("@formats/Types") +local Scenes = require("@tests/gen/ply_scenes") + +local function build(spec: any): Types.Scene + local scene = Types.Scene.new() + for i, m in spec.meshes do + local prims = {} + for _, p in m.prims do + local attrs = {} + for name, a in p.attrs do + attrs[name] = Types.Scene.accessor(buffer.fromstring(a[3]), a[1], a[2], p.count) + end + local prim: any = { attributes = attrs, mode = p.mode } + if p.indices then + prim.indices = Types.Scene.accessor(buffer.fromstring(p.indices), "u32", 1, #p.indices // 4) + end + if p.faces then + prim.faces = Types.Scene.accessor(buffer.fromstring(p.faces), "u32", 1, #p.faces // 4) + end + table.insert(prims, prim) + end + scene.meshes[i] = { primitives = prims } + end + for i, n in spec.nodes do + scene.nodes[i] = { mesh = n.mesh, children = n.children or {}, translation = n.translation, rotation = n.rotation, scale = n.scale, matrix = n.matrix } + end + scene.roots = spec.roots + return scene +end + +local function hex(b: buffer): string + local out = table.create(buffer.len(b)) + for i = 0, buffer.len(b) - 1 do + out[i + 1] = string.format("%02x", buffer.readu8(b, i)) + end + return table.concat(out) +end + +for _, spec in Scenes do + local scene = build(spec) + for _, e in { "ascii", "binary_little_endian", "binary_big_endian" } do + local b, err = Ply.encode(scene, { format = e }) + if not b then + error(spec.name .. "/" .. e .. ": " .. tostring(err)) + end + print(spec.name .. "/" .. e .. " " .. hex(b)) + end +end diff --git a/tools/fixtures/_ply_reference.py b/tools/fixtures/_ply_reference.py new file mode 100644 index 0000000..99e5381 --- /dev/null +++ b/tools/fixtures/_ply_reference.py @@ -0,0 +1,307 @@ +# PLY reference values (run by tools/fixtures/ply.py through ctx.python(["plyfile", "numpy"], ...), python -I). +# stdin: JSON {"dir": tmp, "make": [name], "ref": [name], "ours": [{name, file, scene}]} +# stdout: JSON {"ref": {name: {...}}, "ours": {name: [ok, detail]}} +# make: PLY files written by plyfile (every encoding, every property type, odd orders, lists, extra elements) +# ref: every file read with plyfile, mapped to the library's Scene conventions here (independently of the Luau +# code): CRC-32 of each attribute's packed little-endian bytes, the triangulated / polygon indices, face +# properties, raw elements, comments +# ours: our encoder's output read back by plyfile and compared property by property with the scene it came from +import json, os, sys, zlib +import numpy as np +from plyfile import PlyData, PlyElement + +req = json.load(sys.stdin) +d = req["dir"] +out = {"ref": {}, "ours": {}} + + +def path(n): + return os.path.join(d, n) + + +def crc(a): + return zlib.crc32(np.ascontiguousarray(a).tobytes()) + + +def le(a): + a = np.asarray(a) + return a.astype(a.dtype.newbyteorder("<")) + + +def sphere(rng, n): + """a UV sphere with n x n quads (poles as triangle fans): vertices, quads and triangles""" + vs = [(0.0, 0.0, 1.0)] + for i in range(1, n): + th = np.pi * i / n + for j in range(n): + ph = 2 * np.pi * j / n + vs.append((np.sin(th) * np.cos(ph), np.sin(th) * np.sin(ph), np.cos(th))) + vs.append((0.0, 0.0, -1.0)) + faces = [] + for j in range(n): + faces.append([0, 1 + j, 1 + (j + 1) % n]) + for i in range(n - 2): + for j in range(n): + a = 1 + i * n + j + b = 1 + i * n + (j + 1) % n + faces.append([a, a + n, b + n, b]) + last = len(vs) - 1 + for j in range(n): + a = 1 + (n - 2) * n + faces.append([last, a + (j + 1) % n, a + j]) + return np.array(vs) * (1 + 0.05 * rng.random((len(vs), 1))), faces + + +def faces_el(faces, ct="u1", it="i4", name="vertex_indices", extra=()): + dt = [(name, "O")] + [(n, t) for n, t, _ in extra] + a = np.empty(len(faces), dtype=dt) + a[name] = [np.array(f, dtype=it) for f in faces] + for n, t, vals in extra: + a[n] = vals + return PlyElement.describe(a, "face", len_types={name: ct}, val_types={name: it[1:] if it[0] in "<>" else it}) + + +def make(name): + seed = sum(map(ord, name)) + rng = np.random.default_rng(seed) + comments, obj_info = [], [] + if name == "cube-le.ply": + v = np.array([(x, y, z) for x in (0, 1) for y in (0, 1) for z in (0, 1)], dtype=[("x", "f4"), ("y", "f4"), ("z", "f4")]) + quads = [[0, 1, 3, 2], [4, 6, 7, 5], [0, 4, 5, 1], [2, 3, 7, 6], [0, 2, 6, 4], [1, 5, 7, 3]] + tris = [t for q in quads for t in ([q[0], q[1], q[2]], [q[0], q[2], q[3]])] + els = [PlyElement.describe(v, "vertex"), faces_el(tris)] + text, byte_order = False, "<" + elif name == "colors-be.ply": + pos, faces = sphere(rng, 12) + n = len(pos) + v = np.empty(n, dtype=[("x", "f4"), ("y", "f4"), ("z", "f4"), ("nx", "f4"), ("ny", "f4"), ("nz", "f4"), ("red", "u1"), + ("green", "u1"), ("blue", "u1"), ("alpha", "u1"), ("quality", "f4"), ("flags", "u2")]) + v["x"], v["y"], v["z"] = pos.T + nn = pos / np.linalg.norm(pos, axis=1)[:, None] + v["nx"], v["ny"], v["nz"] = nn.T + for c in ("red", "green", "blue", "alpha"): + v[c] = rng.integers(0, 256, n) + v["quality"] = rng.random(n) + v["flags"] = rng.integers(0, 65536, n) + els = [PlyElement.describe(v, "vertex"), faces_el(faces, "u1", "u4")] + comments = ["made by plyfile", "big endian, quads and triangles"] + text, byte_order = False, ">" + elif name == "ascii-mixed.ply": + n = 40 + v = np.empty(n, dtype=[("red", "u1"), ("z", "f8"), ("y", "f8"), ("x", "f8"), ("s", "f4"), ("t", "f4"), ("intensity", "i1"), ("id", "i4")]) + v["red"] = rng.integers(0, 256, n) + for c in ("x", "y", "z"): + v[c] = rng.random(n) * 20 - 10 + v["s"], v["t"] = rng.random(n), rng.random(n) + v["intensity"] = rng.integers(-128, 128, n) + v["id"] = rng.integers(-2 ** 31, 2 ** 31, n) + faces = [list(rng.choice(n, size=int(rng.integers(3, 7)), replace=False)) for _ in range(25)] + f = faces_el(faces, "u1", "i4", "vertex_index", extra=[("material", "u1", rng.integers(0, 4, 25)), ("weight", "f4", rng.random(25))]) + e = np.empty(10, dtype=[("vertex1", "i4"), ("vertex2", "i4"), ("crease", "u1")]) + e["vertex1"], e["vertex2"], e["crease"] = rng.integers(0, n, 10), rng.integers(0, n, 10), rng.integers(0, 256, 10) + m = np.empty(3, dtype=[("params", "O"), ("index", "i2")]) + m["params"] = [np.array(rng.random(k), dtype="f4") for k in (2, 0, 5)] + m["index"] = [-1, 0, 7] + els = [PlyElement.describe(v, "vertex"), f, PlyElement.describe(e, "edge"), + PlyElement.describe(m, "material", len_types={"params": "u1"}, val_types={"params": "f4"})] + comments = ["ascii with odd property order", ""] + obj_info = ["num_cols 5", "num_rows 8"] + text, byte_order = True, "=" + elif name == "points-le.ply": + n = 500 + v = np.empty(n, dtype=[("x", "f4"), ("y", "f4"), ("z", "f4"), ("red", "u1"), ("green", "u1"), ("blue", "u1")]) + for c in ("x", "y", "z"): + v[c] = rng.random(n) * 100 + for c in ("red", "green", "blue"): + v[c] = rng.integers(0, 256, n) + els = [PlyElement.describe(v, "vertex")] + text, byte_order = False, "<" + elif name == "points-ascii-float.ply": + n = 60 + v = np.empty(n, dtype=[("x", "f4"), ("y", "f4"), ("z", "f4"), ("red", "f4"), ("green", "f4"), ("blue", "f4"), ("u", "f4"), ("v", "f4")]) + for c in v.dtype.names: + v[c] = rng.random(n) + els = [PlyElement.describe(v, "vertex")] + text, byte_order = True, "=" + elif name == "types-be.ply": + n = 400 + types = [("a", "i1"), ("b", "u1"), ("c", "i2"), ("d", "u2"), ("e", "i4"), ("f", "u4"), ("g", "f4"), ("h", "f8")] + v = np.empty(n, dtype=[("x", "f4"), ("y", "f4"), ("z", "f4")] + types) + v["x"], v["y"] = np.cos(np.arange(n) * 2 * np.pi / n), np.sin(np.arange(n) * 2 * np.pi / n) + v["z"] = 0 + for nm, t in types: + info = np.iinfo(t) if t[0] in "iu" else None + v[nm] = rng.integers(info.min, info.max, n, endpoint=True, dtype=t) if info else rng.standard_normal(n) * 1e3 + faces = [list(range(n - 1, 99, -1)), list(range(0, 100))] # a 300-gon (ushort count) and a 100-gon + els = [PlyElement.describe(v, "vertex"), faces_el(faces, "u2", "i4")] + text, byte_order = False, ">" + elif name == "big-le.ply": + pos, faces = sphere(rng, 180) + tris = [t for q in faces for t in (([q[0], q[1], q[2]], [q[0], q[2], q[3]]) if len(q) == 4 else ([q[0], q[1], q[2]],))] + v = np.empty(len(pos), dtype=[("x", "f4"), ("y", "f4"), ("z", "f4")]) + v["x"], v["y"], v["z"] = pos.T + els = [PlyElement.describe(v, "vertex"), faces_el(tris, "u1", "i4")] + text, byte_order = False, "<" + elif name == "tristrips.ply": + v = np.array([(i, i % 2, 0) for i in range(8)], dtype=[("x", "f4"), ("y", "f4"), ("z", "f4")]) + s = np.empty(1, dtype=[("vertex_indices", "O")]) + s["vertex_indices"] = [np.array([0, 1, 2, 3, 4, -1, 4, 5, 6, 7], dtype="i4")] + els = [PlyElement.describe(v, "vertex"), PlyElement.describe(s, "tristrips", len_types={"vertex_indices": "i4"}, val_types={"vertex_indices": "i4"})] + text, byte_order = False, "<" + else: + raise ValueError(name) + PlyData(els, text=text, byte_order=byte_order, comments=comments, obj_info=obj_info).write(path(name)) + + +for name in req["make"]: + make(name) + +ACC = {"i1": "i8", "u1": "u8", "i2": "i16", "u2": "u16", "i4": "i32", "u4": "u32", "f4": "f32", "f8": "f64"} +PAIRS = [("u", "v"), ("s", "t"), ("texture_u", "texture_v"), ("texture_s", "texture_t")] + + +def kind(a): + return np.dtype(a.dtype).str[1:] + + +def index_list(f): + for n in ("vertex_indices", "vertex_index"): + if n in f.data.dtype.names and f.properties[[p.name for p in f.properties].index(n)].__class__.__name__ == "PlyListProperty": + return n + return None + + +def reference(name): + ply = PlyData.read(path(name)) + v = ply["vertex"].data + names = v.dtype.names + taken = set() + attrs = {} + + def group(attr, cols, acc_type, dt, fill=None): + arr = np.stack([v[c].astype(dt) for c in cols] + ([np.full(len(v), fill, dtype=dt)] if fill is not None else []), axis=1) + attrs[attr] = {"type": acc_type, "components": arr.shape[1], "crc": crc(le(arr))} + taken.update(cols) + + if all(c in names for c in "xyz"): + group("POSITION", ["x", "y", "z"], "f32", "<f4") + if all(c in names for c in ("nx", "ny", "nz")) and all(kind(v[c])[0] == "f" for c in ("nx", "ny", "nz")): + group("NORMAL", ["nx", "ny", "nz"], "f32", "<f4") + if all(c in names for c in ("red", "green", "blue")): + cols = ["red", "green", "blue"] + (["alpha"] if "alpha" in names else []) + ks = {"f" if kind(v[c])[0] == "f" else kind(v[c]) for c in cols} + if ks == {"u1"}: + group("COLOR_0", cols, "unorm8", "u1", None if "alpha" in names else 255) + elif ks == {"u2"}: + group("COLOR_0", cols, "unorm16", "<u2", None if "alpha" in names else 65535) + elif ks == {"f"}: + group("COLOR_0", cols, "f32", "<f4", None if "alpha" in names else 1.0) + for a, b in PAIRS: + if a in names and b in names and kind(v[a])[0] == "f" and kind(v[b])[0] == "f": + group("TEXCOORD_0", [a, b], "f32", "<f4") + break + for c in names: + if c not in taken: + attrs["_" + c] = {"type": ACC[kind(v[c])], "components": 1, "crc": crc(le(v[c]))} + encoding = "ascii" if ply.text else ("binary_big_endian" if ply.byte_order == ">" else "binary_little_endian") + res = {"vertices": len(v), "attrs": attrs, "encoding": encoding, + "comments": list(ply.comments), "objInfo": list(ply.obj_info), "order": [e.name for e in ply.elements]} + face = None + if "face" in ply: + f = ply["face"] + il = index_list(f) + if il: + face = f + if face is not None and len(face.data): + lists = [np.asarray(x, dtype=np.int64) for x in face.data[il]] + sizes = [len(x) for x in lists] + corners = np.concatenate(lists) if lists else np.zeros(0, dtype=np.int64) + res["faces"] = len(lists) + res["corners_crc"] = crc(corners.astype("<u4")) + res["sizes_crc"] = crc(np.array(sizes, dtype="<u4")) + tris, fot = [], [] + for i, x in enumerate(lists): + for k in range(1, len(x) - 1): + tris += [x[0], x[k], x[k + 1]] + fot.append(i) + res["tri_crc"] = crc(np.array(tris, dtype="<u4")) + res["tris"] = len(tris) // 3 + res["fot_crc"] = crc(np.array(fot, dtype="<u4")) + res["allTri"] = all(s == 3 for s in sizes) + fa = {} + for p in face.properties: + if p.name == il: + continue + col = face.data[p.name] + if p.__class__.__name__ == "PlyListProperty": + items = np.concatenate([np.asarray(x) for x in col]) if len(col) else np.zeros(0) + fa[p.name] = {"list": True, "sizes_crc": crc(np.array([len(x) for x in col], dtype="<u4")), + "items_crc": crc(le(np.asarray(items, dtype=np.dtype(p.val_dtype))))} + else: + fa[p.name] = {"type": ACC[kind(col)], "crc": crc(le(col))} + res["faceAttributes"] = fa + else: + res["faces"] = 0 + els = [] + for e in ply.elements: + if e.name == "vertex" or (face is not None and e is face): + continue + props = [] + for p in e.properties: + col = e.data[p.name] + if p.__class__.__name__ == "PlyListProperty": + vd = np.dtype(p.val_dtype) + items = np.concatenate([np.asarray(x, dtype=vd) for x in col]) if len(col) else np.zeros(0, dtype=vd) + props.append({"name": p.name, "list": True, "sizes_crc": crc(np.array([len(x) for x in col], dtype="<u4")), + "values_crc": crc(le(items))}) + else: + props.append({"name": p.name, "crc": crc(le(col))}) + els.append({"name": e.name, "count": len(e.data), "props": props}) + res["elements"] = els + return res + + +for name in req["ref"]: + out["ref"][name] = reference(name) + +# our encoder's output: every expected vertex property (name, kind, values) and the faces +for o in req["ours"]: + name = o["name"] + try: + ply = PlyData.read(path(o["file"])) + v = ply["vertex"].data + ok, detail = True, "%d vertices" % len(v) + want_names = [p["name"] for p in o["props"]] + if list(v.dtype.names) != want_names: + ok, detail = False, "vertex properties %s, want %s" % (list(v.dtype.names), want_names) + else: + for p in o["props"]: + got = np.asarray(v[p["name"]]) + want = np.frombuffer(bytes.fromhex(p["values"]), dtype=p["dtype"]) + if kind(got) != np.dtype(p["dtype"]).str[1:]: + ok, detail = False, "%s: type %s, want %s" % (p["name"], kind(got), p["dtype"]) + break + if p.get("tol"): + if got.shape != want.shape or float(np.abs(got.astype(np.float64) - want).max(initial=0)) > p["tol"]: + ok, detail = False, "%s: values differ" % p["name"] + break + elif not np.array_equal(got, want): + ok, detail = False, "%s: values differ" % p["name"] + break + if ok: + if o.get("faces") is None: + if "face" in ply: + ok, detail = False, "a point cloud with a face element" + else: + f = ply["face"].data + il = "vertex_indices" if "vertex_indices" in f.dtype.names else "vertex_index" + got = [list(map(int, x)) for x in f[il]] + if got != o["faces"]: + ok, detail = False, "faces differ" + else: + detail += ", %d faces" % len(got) + out["ours"][name] = [ok, detail] + except Exception as e: # noqa: BLE001 - a reference failure is a verdict + out["ours"][name] = [False, "plyfile: %s" % e] + +json.dump(out, sys.stdout) diff --git a/tools/fixtures/_stl_encode.luau b/tools/fixtures/_stl_encode.luau new file mode 100644 index 0000000..df10a1f --- /dev/null +++ b/tools/fixtures/_stl_encode.luau @@ -0,0 +1,56 @@ +-- tools/fixtures/_stl_encode.luau: run by tools/fixtures/stl.py under the luau CLI (no file I/O): encodes the scenes of +-- tests/gen/stl_scenes with every encoding they list and prints "<scene>/<encoding> <hex>" lines, which the fixture +-- step hands to trimesh and assimp. +local Stl = require("@formats/model/stl") +local Types = require("@formats/Types") +local Scenes = require("@tests/gen/stl_scenes") + +local function acc(s: string, t: string, comps: number, count: number): Types.Accessor + return Types.Scene.accessor(buffer.fromstring(s), t, comps, count) +end + +local function build(spec: any): Types.Scene + local scene = Types.Scene.new() + for i, m in spec.meshes do + local prims = {} + for _, p in m.prims do + local prim: any = { attributes = { POSITION = acc(p.pos, p.posType or "f32", 3, p.count) }, mode = p.mode } + if p.indices then + prim.indices = acc(p.indices, "u32", 1, #p.indices // 4) + end + if p.faces then + prim.faces = acc(p.faces, "u32", 1, #p.faces // 4) + end + if p.color then + prim.attributes.COLOR_0 = acc(p.color, "unorm8", 4, p.count) + end + table.insert(prims, prim) + end + scene.meshes[i] = { name = m.name, primitives = prims } + end + for i, n in spec.nodes do + scene.nodes[i] = { name = n.name, mesh = n.mesh, children = n.children or {}, translation = n.translation, rotation = n.rotation, scale = n.scale, matrix = n.matrix } + end + scene.roots = spec.roots + return scene +end + +local function hex(b: buffer): string + local out = table.create(buffer.len(b)) + for i = 0, buffer.len(b) - 1 do + out[i + 1] = string.format("%02x", buffer.readu8(b, i)) + end + return table.concat(out) +end + +local OPTS: { [string]: any } = { binary = {}, ascii = { ascii = true }, viscam = { colors = "viscam" }, magics = { colors = "magics" } } +for _, spec in Scenes do + local scene = build(spec) + for _, e in spec.encodings do + local b, err = Stl.encode(scene, OPTS[e]) + if not b then + error(spec.name .. "/" .. e .. ": " .. tostring(err)) + end + print(spec.name .. "/" .. e .. " " .. hex(b)) + end +end diff --git a/tools/fixtures/_stl_reference.py b/tools/fixtures/_stl_reference.py new file mode 100644 index 0000000..efbd5f1 --- /dev/null +++ b/tools/fixtures/_stl_reference.py @@ -0,0 +1,112 @@ +# STL reference values (run by tools/fixtures/stl.py through ctx.python(["trimesh", "numpy"], ...), python -I). +# stdin: JSON {"dir": tmp, "make": [[name, kind, file_type, seed]], "ref": [name], "ours": [{name, file, ...}]} +# stdout: JSON {"ref": {name: {...}}, "ours": {name: [ok, detail]}} +# make: meshes made and exported by trimesh itself (binary / ascii STL) +# ref: every file read with trimesh.exchange.stl.load_stl (the raw arrays, no processing): facet count, CRC-32 of +# the f32 triangle vertices / facet normals (as the file has them), area, bounds, the raw attribute words +# ours: our encoder's output read back by trimesh and compared with the expected world-space triangles +import json, os, sys, zlib +import numpy as np +import trimesh +from trimesh.exchange import stl as tstl + +req = json.load(sys.stdin) +d = req["dir"] +out = {"ref": {}, "ours": {}} + + +def path(n): + return os.path.join(d, n) + + +for name, kind, ftype, seed in req["make"]: + rng = np.random.default_rng(seed) + if kind == "icosphere": + m = trimesh.creation.icosphere(subdivisions=3, radius=2.5) + elif kind == "box": + m = trimesh.creation.box(extents=(1.5, 2.0, 0.25)) + elif kind == "capsule": + m = trimesh.creation.capsule(height=3.0, radius=0.7) + else: + tri = (rng.random((1500, 3, 3)) * 200 - 100).astype(np.float32) + m = trimesh.Trimesh(vertices=tri.reshape(-1, 3), faces=np.arange(4500).reshape(-1, 3), process=False) + data = m.export(file_type=ftype) + with open(path(name), "wb") as f: + f.write(data.encode() if isinstance(data, str) else data) + + +def load(name): + with open(path(name), "rb") as f: + r = tstl.load_stl(f) + if "geometry" in r: # several solids + parts = list(r["geometry"].values()) + if not parts: + return np.zeros((0, 3)), np.zeros((0, 3), dtype=np.int64), np.zeros((0, 3)), None + vs, fs, ns, off = [], [], [], 0 + for g in parts: + vs.append(g["vertices"]) + fs.append(np.asarray(g["faces"]) + off) + ns.append(g["face_normals"]) + off += len(g["vertices"]) + # trimesh does not read normals written on the "outer loop" line: no normals then + nrm = None if any(x is None for x in ns) else np.concatenate(ns) + return np.concatenate(vs), np.concatenate(fs), nrm, None + attr = r.get("face_attributes", {}).get("stl") + return np.asarray(r["vertices"]), np.asarray(r["faces"]), np.asarray(r["face_normals"]), attr + + +def crc(a, dt): + return zlib.crc32(np.ascontiguousarray(np.asarray(a).astype(dt)).tobytes()) + + +for name in req["ref"]: + v, f, n, attr = load(name) + tri = v[f].astype(np.float32) # (n, 3, 3) + m = trimesh.Trimesh(vertices=v, faces=f, process=False) + res = { + "facets": int(len(f)), + "pos_crc": crc(tri, "<f4"), + "area": float(m.area) if len(f) else 0.0, + "bounds": [float(x) for x in (m.bounds.reshape(-1) if len(f) else np.zeros(6))], + } + if n is not None: + res["nrm_crc"] = crc(np.repeat(np.asarray(n, dtype=np.float32), 3, axis=0), "<f4") + if attr is not None: + res["attr"] = [int(x) for x in attr] + out["ref"][name] = res + +# our encoder's files +for o in req["ours"]: + name = o["name"] + try: + v, f, n, attr = load(o["file"]) + tri = v[f].astype(np.float32).reshape(-1, 9) + want = np.frombuffer(bytes.fromhex(o["expect"]), dtype="<f4").reshape(-1, 9) + if tri.shape != want.shape: + out["ours"][name] = [False, "facet count %s, want %s" % (tri.shape, want.shape)] + continue + tol = 0 if o["exact"] else 1e-5 * max(1.0, float(np.abs(want).max())) + err = float(np.abs(tri.astype(np.float64) - want.astype(np.float64)).max()) if len(want) else 0.0 + if err > tol: + out["ours"][name] = [False, "positions differ by %g" % err] + continue + # the stored facet normals: the right-hand rule normal of each triangle + t = want.astype(np.float64).reshape(-1, 3, 3) + cn = np.cross(t[:, 1] - t[:, 0], t[:, 2] - t[:, 0]) + ln = np.linalg.norm(cn, axis=1) + cn[ln > 0] /= ln[ln > 0, None] + nerr = float(np.abs(np.asarray(n, dtype=np.float64) - cn).max()) if len(want) else 0.0 + if nerr > 1e-4: + out["ours"][name] = [False, "facet normals differ by %g" % nerr] + continue + if "colors" in o: + want_words = o["colors"] + got = [int(x) for x in attr] if attr is not None else [] + if got != want_words: + out["ours"][name] = [False, "attribute words differ"] + continue + out["ours"][name] = [True, "%d facets, max error %g" % (len(want), err)] + except Exception as e: # noqa: BLE001 - a reference failure is a verdict + out["ours"][name] = [False, "trimesh: %s" % e] + +json.dump(out, sys.stdout) diff --git a/tools/fixtures/_webp_encode.luau b/tools/fixtures/_webp_encode.luau new file mode 100644 index 0000000..c7c9b3c --- /dev/null +++ b/tools/fixtures/_webp_encode.luau @@ -0,0 +1,95 @@ +-- tools/fixtures/_webp_encode: run by tools/fixtures/webp.py (luau CLI, repo root). Encodes the WebP fixture sources +-- (tests/gen/webp_src) with image/webp at several efforts and two animations, and prints one line per file: +-- "<name> <hex>" (stills: <source>_e<effort>_<exact|loose>) or "anim<k>:<crc>,<crc>,... <hex>" with the CRC-32 of each +-- canvas the input frames composite to (image/webp/Anim.composite), for dwebp / Pillow to check. +local Webp = require("@formats/image/webp") +local Anim = require("@formats/image/webp/Anim") +local Types = require("@formats/Types") +local Crc32 = require("@formats/core/Crc32") +local Src = require("@tests/gen/webp_src") + +local HEX = {} +for i = 0, 255 do + HEX[i] = string.format("%02x", i) +end +local function hex(b: buffer): string + local t = table.create(buffer.len(b)) + for i = 0, buffer.len(b) - 1 do + t[i + 1] = HEX[buffer.readu8(b, i)] + end + return table.concat(t) +end + +local function image(s: any): Types.Image + local img = Types.Image.new(s.width, s.height) + img.pixels = buffer.fromstring(s.rgba) + return img +end + +local bySrc = {} +for _, s in Src do + bySrc[s.name] = s + for _, effort in { 0, 3, 5, 9 } do + local out = assert(Webp.encode(image(s), { effort = effort, exact = true })) + print(string.format("%s_e%d_exact %s", s.name, effort, hex(out))) + end + local out = assert(Webp.encode(image(s), { effort = 5 })) + print(string.format("%s_e5_loose %s", s.name, hex(out))) +end + +-- crop(src, x, y, w, h) -> an rgba8 Image +local function crop(s: any, x: number, y: number, w: number, h: number): Types.Image + local img = Types.Image.new(w, h) + local px = buffer.fromstring(s.rgba) + for j = 0, h - 1 do + buffer.copy(img.pixels, j * w * 4, px, ((y + j) * s.width + x) * 4, w * 4) + end + return img +end + +local function animation(cw: number, ch: number, frames: { Types.Frame }): Types.Image + local img = Types.Image.new(cw, ch) + img.frames = frames + img.loops = 2 + return img +end + +local rose, rosea, grad = bySrc.rose, bySrc.rose_a, bySrc.grad +local anims = { + -- stored as they are: even offsets, blending, dispose to background + animation(70, 46, { + { image = crop(rose, 0, 0, 70, 46), delay = 0.1, x = 0, y = 0, dispose = "none", blend = "source" }, + { image = crop(rosea, 10, 4, 30, 20), delay = 0.05, x = 10, y = 4, dispose = "background", blend = "over" }, + { image = crop(rosea, 20, 10, 40, 30), delay = 0.2, x = 20, y = 10, dispose = "none", blend = "over" }, + { image = crop(grad, 0, 0, 24, 16), delay = 0.033, x = 46, y = 30, dispose = "none", blend = "source" }, + }), + -- flattened: odd offsets and dispose "previous" + animation(70, 46, { + { image = crop(rosea, 0, 0, 70, 46), delay = 0.1, x = 0, y = 0, dispose = "none", blend = "source" }, + { image = crop(grad, 3, 3, 21, 13), delay = 0.1, x = 5, y = 7, dispose = "previous", blend = "over" }, + { image = crop(rose, 1, 1, 9, 9), delay = 0.1, x = 33, y = 21, dispose = "background", blend = "over" }, + { image = crop(grad, 0, 0, 10, 10), delay = 0.1, x = 60, y = 36, dispose = "none", blend = "over" }, + }), +} +for k, img in anims do + local list = {} + for _, f in img.frames :: { Types.Frame } do + 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", + disposePrev = f.dispose == "previous", + hasAlpha = true, + }) + end + local crcs = {} + for _, c in Anim.composite(img.width, img.height, list) do + table.insert(crcs, tostring(Crc32.of(c))) + end + local out = assert(Webp.encode(img, { effort = 5, exact = true })) + print(string.format("anim%d:%s %s", k, table.concat(crcs, ","), hex(out))) +end diff --git a/tools/fixtures/aseprite.py b/tools/fixtures/aseprite.py new file mode 100644 index 0000000..4624623 --- /dev/null +++ b/tools/fixtures/aseprite.py @@ -0,0 +1,213 @@ +# Aseprite fixtures (tools/fixtures.py). Sprites written here by a small writer following docs/ase-file-specs.md +# (RGBA / grayscale / indexed, raw / zlib / linked cels, groups, hidden layers, blend modes, layer and cel opacity, +# old and new palette chunks, tags, user data), sprites written by LibreSprite (the reference: an Aseprite 1.1 fork, +# in nixpkgs) and LibreSprite's flattened rendering of every frame: +# tests/gen/aseprite.luau { cases = { { name, data, width, height, nframes, cels = { { frame, layer, x, y, w, h, +# crc } }, frames = { RGBA of LibreSprite's frame i } } } } +# tests/gen/aseprite_ours.luau { frames = { ... }, ours = { ... } }: our encoder's sprite (tools/fixtures/_ours.luau) +# rendered by LibreSprite, with our flatten of the same frames +import json, os, shutil, struct, subprocess, tempfile, zlib + +INPUTS = ["src/Formats/layered/aseprite", "src/Formats/codecs/Blend.luau", "tools/fixtures/_ours.luau"] + + +def s(text): + b = text.encode() + return struct.pack("<H", len(b)) + b + + +def chunk(ctype, body): + return struct.pack("<IH", len(body) + 6, ctype) + body + + +def layer_chunk(name, flags=3, ltype=0, level=0, blend=0, opacity=255): + return chunk(0x2004, struct.pack("<HHHHHHB3x", flags, ltype, level, 0, 0, blend, opacity) + s(name)) + + +def cel_chunk(layer, x, y, w, h, pixels, opacity=255, kind=2, link=None, z=0): + head = struct.pack("<HhhBHh5x", layer, x, y, opacity, 1 if link is not None else kind, z) + if link is not None: + return chunk(0x2005, head + struct.pack("<H", link)) + if kind == 0: + return chunk(0x2005, head + struct.pack("<HH", w, h) + pixels) + return chunk(0x2005, head + struct.pack("<HH", w, h) + zlib.compress(pixels)) + + +def palette_chunk(colors, names=None): + body = struct.pack("<III8x", len(colors), 0, len(colors) - 1) + for i, c in enumerate(colors): + n = (names or {}).get(i) + body += struct.pack("<H4B", 1 if n else 0, *c) + (s(n) if n else b"") + return chunk(0x2019, body) + + +def old_palette_chunk(colors): + body = struct.pack("<HBB", 1, 0, len(colors) & 255) + b"".join(bytes(c[:3]) for c in colors) + return chunk(0x0004, body) + + +def tags_chunk(tags): + body = struct.pack("<H8x", len(tags)) + for name, a, b, d, rep in tags: + body += struct.pack("<HHBH6x3Bx", a, b, d, rep, 255, 0, 0) + s(name) + return chunk(0x2018, body) + + +def user_chunk(text=None, color=None): + f = (1 if text is not None else 0) | (2 if color else 0) + return chunk(0x2020, struct.pack("<I", f) + (s(text) if text is not None else b"") + (bytes(color) if color else b"")) + + +def sprite(w, h, depth, frames, transparent=0, flags=3, ncolors=0): + """frames: [(duration_ms, [chunk bytes])]""" + body = b"" + for dur, chunks in frames: + data = b"".join(chunks) + body += struct.pack("<IHHHxxI", len(data) + 16, 0xF1FA, min(len(chunks), 0xFFFF), dur, len(chunks)) + data + head = struct.pack("<IHHHHHIH II B3x H BB hhHH", 128 + len(body), 0xA5E0, len(frames), w, h, depth, flags, 100, 0, 0, transparent, ncolors, 1, 1, 0, 0, 16, 16) + head += b"\0" * (128 - len(head)) + return head + body + + +def rgba(w, h, seed, alpha=True): + out = bytearray() + for y in range(h): + for x in range(w): + a = 255 if not alpha or (x + y) % 4 else (x * 50 + seed * 30) % 256 + out += bytes(((x * (seed + 2) * 9 + y * 3) % 256, (y * (seed + 1) * 11 + x) % 256, ((x + seed) * (y + 2) * 5) % 256, a)) + return bytes(out) + + +def case_rgba(): + W, H = 32, 24 + cels = [] + def cel(frame, layer, x, y, w, h, px, **kw): + cels.append({"frame": frame, "layer": layer, "x": x, "y": y, "w": w, "h": h, "crc": zlib.crc32(px)}) + return cel_chunk(layer - 1, x, y, w, h, px, **kw) + bg = rgba(W, H, 1, alpha=False) + pal = [(i, 255 - i, (i * 7) % 256, 255) for i in range(0, 256, 16)] + f1 = [ + palette_chunk(pal, {0: "first", 3: "fourth"}), + layer_chunk("Background", flags=1 | 2 | 8), + layer_chunk("Group", ltype=1, flags=3), + layer_chunk("Mul", level=1, blend=1, opacity=200), + user_chunk("mul layer", (1, 2, 3, 4)), + layer_chunk("Half", level=1), + layer_chunk("Hidden", flags=2), + layer_chunk("Top"), + tags_chunk([("walk", 0, 1, 0, 0), ("back", 1, 2, 2, 3)]), + user_chunk("walk tag"), + user_chunk(None), + cel(1, 1, 0, 0, W, H, bg, kind=0), + cel(1, 3, 4, 3, 16, 12, rgba(16, 12, 2)), + user_chunk("a cel"), + cel(1, 4, 10, 8, 14, 10, rgba(14, 10, 3), opacity=128), + cel(1, 5, 0, 0, 8, 8, rgba(8, 8, 4)), + cel(1, 6, 20, 2, 10, 20, rgba(10, 20, 5)), + ] + f2 = [ + cel_chunk(0, 0, 0, W, H, bg, link=0), + cel(2, 3, 6, 5, 16, 12, rgba(16, 12, 6)), + cel(2, 6, -4, 10, 12, 8, rgba(12, 8, 7), kind=0), + ] + f3 = [ + cel_chunk(0, 0, 0, W, H, bg, link=0), + cel_chunk(2, 4, 3, 16, 12, b"", link=0), + cel(3, 4, 1, 1, 30, 20, rgba(30, 20, 8), opacity=64), + ] + # linked cels repeat their target + cels.append({"frame": 2, "layer": 1, "x": 0, "y": 0, "w": W, "h": H, "crc": zlib.crc32(bg)}) + cels.append({"frame": 3, "layer": 1, "x": 0, "y": 0, "w": W, "h": H, "crc": zlib.crc32(bg)}) + cels.append({"frame": 3, "layer": 3, "x": 4, "y": 3, "w": 16, "h": 12, "crc": zlib.crc32(rgba(16, 12, 2))}) + return sprite(W, H, 32, [(100, f1), (150, f2), (200, f3)], ncolors=len(pal)), cels + + +def case_gray(): + cels = [] + px = bytes(v for x in range(10 * 6) for v in ((x * 4) % 256, 255 if x % 3 else 128)) + exp = b"".join(bytes((px[i * 2],) * 3 + (px[i * 2 + 1],)) for i in range(60)) + cels.append({"frame": 1, "layer": 1, "x": 1, "y": 1, "w": 10, "h": 6, "crc": zlib.crc32(exp)}) + cels.append({"frame": 2, "layer": 1, "x": 3, "y": 2, "w": 10, "h": 6, "crc": zlib.crc32(exp)}) + f1 = [layer_chunk("G"), cel_chunk(0, 1, 1, 10, 6, px)] + f2 = [cel_chunk(0, 3, 2, 10, 6, px, kind=0)] + return sprite(14, 9, 16, [(80, f1), (80, f2)]), cels + + +def case_indexed(): + # the background cel covers the sprite (as Aseprite writes it): its transparent index stays opaque + pal = [(0, 0, 0, 255), (255, 0, 0, 255), (0, 255, 0, 255), (0, 0, 255, 255), (255, 255, 0, 255)] + idx = bytes((x + y) % 5 for y in range(7) for x in range(9)) + bgi = bytes((x * y) % 5 for y in range(9) for x in range(12)) + exp = b"".join(bytes(pal[i][:3]) + bytes((0 if i == 0 else 255,)) for i in idx) + exp_bg = b"".join(bytes(pal[i]) for i in bgi) + cels = [{"frame": 1, "layer": 1, "x": 0, "y": 0, "w": 12, "h": 9, "crc": zlib.crc32(exp_bg)}, + {"frame": 1, "layer": 2, "x": 2, "y": 1, "w": 9, "h": 7, "crc": zlib.crc32(exp)}] + f1 = [old_palette_chunk(pal), layer_chunk("Back", flags=1 | 2 | 8), layer_chunk("Sprite"), cel_chunk(0, 0, 0, 12, 9, bgi), cel_chunk(1, 2, 1, 9, 7, idx)] + return sprite(12, 9, 8, [(100, f1)], transparent=0, ncolors=5), cels + + +def libresprite(ctx, argv, cwd): + if shutil.which("libresprite"): + subprocess.run(["libresprite"] + argv, check=True, capture_output=True, cwd=cwd) + else: + subprocess.run(["nix", "shell", "nixpkgs#libresprite", "-c", "libresprite"] + argv, check=True, capture_output=True, cwd=cwd) + + +def rgba_of(ctx, png): + argv = ["magick", png, "-depth", "8", "rgba:-"] + try: + return subprocess.run(argv, check=True, capture_output=True).stdout + except (OSError, subprocess.CalledProcessError): + return ctx.nix("imagemagick", argv) + + +def render(ctx, data, nframes): + """LibreSprite's flattened frames of an .ase (RGBA bytes each)""" + with tempfile.TemporaryDirectory() as d: + open(os.path.join(d, "in.aseprite"), "wb").write(data) + libresprite(ctx, ["-b", "in.aseprite", "--save-as", "f.png"], d) + if nframes == 1: + return [rgba_of(ctx, os.path.join(d, "f.png"))] + return [rgba_of(ctx, os.path.join(d, "f%d.png" % i)) for i in range(1, nframes + 1)] + + +def resave(ctx, data, ext_in="aseprite"): + with tempfile.TemporaryDirectory() as d: + open(os.path.join(d, "in." + ext_in), "wb").write(data) + libresprite(ctx, ["-b", "in." + ext_in, "--save-as", "out.aseprite"], d) + return open(os.path.join(d, "out.aseprite"), "rb").read() + + +def run_ours(ctx, fmt): + script = os.path.join(ctx.root, "tools", "fixtures", "_ours.luau") + luau = shutil.which("luau") + argv = [luau, script, "-a", fmt] if luau else ["nix", "shell", "nixpkgs#luau", "-c", "luau", script, "-a", fmt] + return json.loads(subprocess.run(argv, check=True, capture_output=True, cwd=ctx.root).stdout) + + +def gif(ctx): + with tempfile.TemporaryDirectory() as d: + a, b, g = os.path.join(d, "a.png"), os.path.join(d, "b.png"), os.path.join(d, "anim.gif") + for argv in (["magick", "-size", "12x8", "gradient:red-blue", a], ["magick", "-size", "12x8", "xc:green", b], ["magick", "-delay", "20", a, b, "-loop", "0", g]): + try: + subprocess.run(argv, check=True, capture_output=True) + except (OSError, subprocess.CalledProcessError): + ctx.nix("imagemagick", argv) + return open(g, "rb").read() + + +def generate(ctx): + cases = [] + for name, (data, cels) in (("rgba", case_rgba()), ("gray", case_gray()), ("indexed", case_indexed())): + n = struct.unpack_from("<H", data, 6)[0] + w, h = struct.unpack_from("<HH", data, 8) + cases.append({"name": name, "data": data, "width": w, "height": h, "nframes": n, "cels": cels, "frames": render(ctx, data, n)}) + # sprites LibreSprite writes: our rgba case re-saved, and a GIF converted + re = resave(ctx, cases[0]["data"]) + cases.append({"name": "libresprite-resave", "data": re, "width": 32, "height": 24, "nframes": 3, "cels": [], "frames": render(ctx, re, 3)}) + g = resave(ctx, gif(ctx), "gif") + cases.append({"name": "libresprite-gif", "data": g, "width": 12, "height": 8, "nframes": 2, "cels": [], "frames": render(ctx, g, 2)}) + ctx.emit("aseprite", {"cases": cases}) + o = run_ours(ctx, "aseprite") + data = bytes.fromhex(o["data"]) + ctx.emit("aseprite_ours", {"nframes": o["nframes"], "frames": render(ctx, data, o["nframes"]), "ours": [bytes.fromhex(f) for f in o["frames"]]}) diff --git a/tools/fixtures/base64.py b/tools/fixtures/base64.py new file mode 100644 index 0000000..253a529 --- /dev/null +++ b/tools/fixtures/base64.py @@ -0,0 +1,13 @@ +# Base64 fixtures (tools/fixtures.py): random byte strings of every length 0..70 plus a few large ones, with Python's +# base64 (standard, URL-safe, unpadded) as the reference. +# tests/gen/base64_cases.luau { data, std, url, nopad } +import base64 + + +def generate(ctx): + rng = ctx.rng(3) + cases = [] + for n in list(range(71)) + [1000, 4097, 65536]: + d = bytes(rng.randrange(256) for _ in range(n)) + cases.append({"data": d, "std": base64.b64encode(d), "url": base64.urlsafe_b64encode(d), "nopad": base64.b64encode(d).rstrip(b"=")}) + ctx.emit("base64_cases", cases) diff --git a/tools/fixtures/bmfont.py b/tools/fixtures/bmfont.py new file mode 100644 index 0000000..a8b1420 --- /dev/null +++ b/tools/fixtures/bmfont.py @@ -0,0 +1,105 @@ +# BMFont fixtures (tools/fixtures.py): a bitmap font rendered from Karla-Regular (imgui-luau fonts, or DejaVu Sans +# from nixpkgs when missing) with FreeType + Pillow, written by an independent Python writer of the three AngelCode +# encodings (text, XML, binary v3) from the BMFont documentation, plus its page PNG. +# tests/gen/bmfont.luau { text, xml, binary, page (png bytes), desc = { info, common, pages, chars, kernings }, +# crops = { { id, crc } } (CRC-32 of each glyph's alpha crop) } +import base64, json, os, subprocess + +FONT = os.path.join(os.environ.get("IMGUI_FONTS", os.path.expanduser("~/dev/luau/imgui/imgui-luau/fonts")), "Karla-Regular.ttf") + +CODE = r''' +import base64, io, json, struct, sys, zlib +import freetype +from PIL import Image +data = base64.b64decode(sys.stdin.read()) +face = freetype.Face(io.BytesIO(data)) +face.set_pixel_sizes(0, 24) +chars = [c for c in range(32, 127)] + [0xE9, 0x2014] +page = Image.new("RGBA", (256, 256), (255, 255, 255, 0)) +x, y, rowh = 1, 1, 0 +out = [] +crops = [] +for cp in chars: + face.load_char(chr(cp), freetype.FT_LOAD_RENDER | freetype.FT_LOAD_NO_HINTING) + g = face.glyph + bm = g.bitmap + w, h = bm.width, bm.rows + if x + w + 1 > 256: + x, y, rowh = 1, y + rowh + 1, 0 + alpha = bytes(bm.buffer[r * bm.pitch + c] for r in range(h) for c in range(w)) + for r in range(h): + for c in range(w): + page.putpixel((x + c, y + r), (255, 255, 255, alpha[r * w + c])) + out.append({"id": cp, "x": x, "y": y, "width": w, "height": h, "xoffset": g.bitmap_left, + "yoffset": 19 - g.bitmap_top, "xadvance": g.advance.x // 64, "page": 0, "chnl": 15}) + crops.append({"id": cp, "crc": zlib.crc32(alpha)}) + x += w + 1 + rowh = max(rowh, h) +kern = [] +for a in "AVTWYLo": + for b in "AVTWYoe.": + k = face.get_kerning(a, b).x // 64 + kern.append([ord(a), ord(b), -((ord(a) * 7 + ord(b)) % 5) - 1]) +info = {"face": "Karla \"Test\" & Co", "size": 24, "bold": 0, "italic": 1, "charset": "", "unicode": 1, "stretchH": 100, + "smooth": 1, "aa": 1, "padding": [1, 2, 3, 4], "spacing": [1, 1], "outline": 0} +common = {"lineHeight": 28, "base": 19, "scaleW": 256, "scaleH": 256, "pages": 1, "packed": 0, "alphaChnl": 0, + "redChnl": 4, "greenChnl": 4, "blueChnl": 4} +pages = ["karla_0.png"] +CHAR_KEYS = ["id", "x", "y", "width", "height", "xoffset", "yoffset", "xadvance", "page", "chnl"] +def tq(s): return '"' + s.replace('"', "") + '"' +lines = ["info face=%s size=24 bold=0 italic=1 charset=\"\" unicode=1 stretchH=100 smooth=1 aa=1 padding=1,2,3,4 spacing=1,1 outline=0" % tq(info["face"]), + "common lineHeight=28 base=19 scaleW=256 scaleH=256 pages=1 packed=0 alphaChnl=0 redChnl=4 greenChnl=4 blueChnl=4", + 'page id=0 file="karla_0.png"', "chars count=%d" % len(out)] +for c in out: + lines.append("char " + " ".join("%s=%d" % (k, c[k]) for k in CHAR_KEYS)) +lines.append("kernings count=%d" % len(kern)) +for k in kern: + lines.append("kerning first=%d second=%d amount=%d" % tuple(k)) +text = "\r\n".join(lines) + "\r\n" +def xe(s): return s.replace("&", "&").replace("<", "<").replace('"', """) +xl = ['<?xml version="1.0"?>', "<font>", + ' <info face="%s" size="24" bold="0" italic="1" charset="" unicode="1" stretchH="100" smooth="1" aa="1" padding="1,2,3,4" spacing="1,1" outline="0"/>' % xe(info["face"]), + ' <common lineHeight="28" base="19" scaleW="256" scaleH="256" pages="1" packed="0" alphaChnl="0" redChnl="4" greenChnl="4" blueChnl="4"/>', + " <pages>", ' <page id="0" file="karla_0.png" />', " </pages>", ' <chars count="%d">' % len(out)] +for c in out: + xl.append(" <char " + " ".join('%s="%d"' % (k, c[k]) for k in CHAR_KEYS) + " />") +xl.append(" </chars>") +xl.append(' <kernings count="%d">' % len(kern)) +for k in kern: + xl.append(' <kerning first="%d" second="%d" amount="%d" />' % tuple(k)) +xl += [" </kernings>", "</font>"] +xml = "\n".join(xl) + "\n" +face_name = info["face"].encode() +b = bytearray(b"BMF\x03") +blk = struct.pack("<hBBHBBBBBBBB", 24, 0x80 | 0x40 | 0x20, 0, 100, 1, 1, 2, 3, 4, 1, 1, 0) + face_name + b"\0" +b += struct.pack("<BI", 1, len(blk)) + blk +blk = struct.pack("<HHHHHBBBBB", 28, 19, 256, 256, 1, 0, 0, 4, 4, 4) +b += struct.pack("<BI", 2, len(blk)) + blk +blk = b"karla_0.png\0" +b += struct.pack("<BI", 3, len(blk)) + blk +blk = b"".join(struct.pack("<IHHHHhhhBB", *[c[k] for k in CHAR_KEYS]) for c in out) +b += struct.pack("<BI", 4, len(blk)) + blk +blk = b"".join(struct.pack("<IIh", *k) for k in kern) +b += struct.pack("<BI", 5, len(blk)) + blk +png = io.BytesIO() +page.save(png, "PNG") +json.dump({"text": base64.b64encode(text.encode()).decode(), "xml": base64.b64encode(xml.encode()).decode(), + "binary": base64.b64encode(bytes(b)).decode(), "page": base64.b64encode(png.getvalue()).decode(), + "desc": {"info": info, "common": common, "pages": pages, "chars": out, "kernings": kern}, "crops": crops}, + sys.stdout) +''' + + +def generate(ctx): + path = FONT + if not os.path.exists(path): + out = subprocess.run(["nix", "build", "--no-link", "--print-out-paths", "nixpkgs#dejavu_fonts"], capture_output=True, + check=True, text=True).stdout.strip().split("\n")[-1] + path = os.path.join(out, "share", "fonts", "truetype", "DejaVuSans.ttf") + raw = ctx.python(["freetype-py", "pillow"], CODE, input=base64.b64encode(open(path, "rb").read())) + res = json.loads(raw) + d = base64.b64decode + for k in ("text", "xml", "binary", "page"): + res[k] = d(res[k]) + res["ttf"] = open(path, "rb").read() + ctx.emit("bmfont", res) diff --git a/tools/fixtures/brotli.py b/tools/fixtures/brotli.py new file mode 100644 index 0000000..e04f7e4 --- /dev/null +++ b/tools/fixtures/brotli.py @@ -0,0 +1,101 @@ +# Brotli fixtures (tools/fixtures.py): deterministic corpora compressed by the reference encoder (python brotli +# through nix, and the brotli CLI for the large-window extension): every quality 0..11, windows 10..24, the text / +# font / generic modes, empty input, dictionary-heavy English, and a few-MB bench corpus. +# tests/gen/brotli.luau { corpora = { [name] = bytes }, cases = { { name, corpus, data } } } +# tests/gen/brotli_bench.luau { size, crc, data } +import os, pickle, random, zlib + +ENCODE = r''' +import brotli, pickle, sys +jobs = pickle.load(sys.stdin.buffer) +out = [] +for data, q, w, mode in jobs: + m = {"generic": brotli.MODE_GENERIC, "text": brotli.MODE_TEXT, "font": brotli.MODE_FONT}[mode] + out.append(brotli.compress(data, mode=m, quality=q, lgwin=w)) +sys.stdout.buffer.write(pickle.dumps(out)) +''' + +WORDS = ("the of and to in is that for it as was with be by on not he this are or his from at which but have an they " + "you were her she there one all we their been has who more will would if so can its what when about into than " + "them only other time new some could these two may first then do any like my now over such our man me even " + "most made after also did many before must through back years where much your way well down should because " + "each just those people Mr how too little state good very make world still own see men work long get here " + "between both life being under never day same another know while last might us great old year off come since " + "against go came right used take three himself few house use during without again place American around " + "however home small found Mrs thought went say part once general high upon school every don't does got united " + "left number course war until always away something fact though water less public put think almost hand " + "enough far took head yet government system better set told nothing night end why called didn't eyes find " + "going look asked later knew point next program city business give group toward young days let room president " + "side social present given several order national possible rather second face per among form important often " + "things looked early white case John become large big need four within felt along children saw best church " + "ever least power development light thing seemed family interest want members mind country area others done " + "turned although open God service certain kind problem began different door thus help sense means whole " + "matter perhaps itself York it's times law human line above name example action company local show whether " + "five history gave today either act feet across taken past quite anything seen having death week experience " + "really body word half field").split() + + +def english(rng, n): + out = [] + size = 0 + while size < n: + k = rng.randint(4, 16) + s = " ".join(rng.choice(WORDS) for _ in range(k)) + s = s[0].upper() + s[1:] + rng.choice([". ", ", ", "; ", "! ", "? ", ".\n", ". The ", " - "]) + if rng.random() < 0.05: + s = '<a href="http://www.' + rng.choice(WORDS) + '.com/">' + s + "</a>\n" + out.append(s) + size += len(s) + return "".join(out).encode()[:n] + + +def text_corpus(limit): + base = os.path.dirname(os.__file__) + out = bytearray() + for name in sorted(os.listdir(base)): + if name.endswith(".py"): + with open(os.path.join(base, name), "rb") as f: + out += f.read() + if len(out) >= limit: + break + return bytes(out[:limit]) + + +def generate(ctx): + rng = random.Random(7) + text = text_corpus(400000) + corpora = { + "empty": b"", + "one": b"a", + "english": english(rng, 120000), + "text": text[:150000], + "random": rng.randbytes(30000), + "runs": b"abc" * 4000 + b"\0" * 20000 + bytes(range(256)) * 40 + b"z" * 300, + "binary": bytes(rng.choice(b"\0\0\0\x01\x02\xff ABC") for _ in range(30000)), + "utf8": ("Grüße, Привет, 你好, こんにちは, ¡Hola! " * 600).encode(), + "far": (lambda r: r + rng.randbytes(70000) + r)(rng.randbytes(9000)), + } + jobs, names = [], [] + for cname, data in corpora.items(): + for q in range(12): + jobs.append((data, q, 22, "generic")) + names.append(("%s/q%d" % (cname, q), cname)) + for w in (10, 12, 16, 18, 24): + jobs.append((data, 9, w, "generic")) + names.append(("%s/q9-w%d" % (cname, w), cname)) + for mode in ("text", "font"): + for q in (5, 11): + jobs.append((data, q, 20, mode)) + names.append(("%s/%s-q%d" % (cname, mode, q), cname)) + outs = pickle.loads(ctx.python(["brotli"], ENCODE, input=pickle.dumps(jobs))) + cases = [{"name": n, "corpus": c, "data": d} for (n, c), d in zip(names, outs)] + # the large-window extension (brotli CLI), on the far-match corpus and the text + for cname in ("far", "text", "english"): + for q in (5, 11): + d = ctx.nix("brotli", ["brotli", "-c", "-q", str(q), "--large_window=26"], input=corpora[cname]) + cases.append({"name": "%s/large-q%d" % (cname, q), "corpus": cname, "data": d}) + ctx.emit("brotli", {"corpora": corpora, "cases": cases}) + bench = (text + english(rng, 1500000) + corpora["binary"] * 10 + text) * 2 + bench = bench[:4000000] + bout = pickle.loads(ctx.python(["brotli"], ENCODE, input=pickle.dumps([(bench, 9, 22, "generic")])))[0] + ctx.emit("brotli_bench", {"size": len(bench), "crc": zlib.crc32(bench), "data": bout}) diff --git a/tools/fixtures/bzip2.py b/tools/fixtures/bzip2.py new file mode 100644 index 0000000..0464a8a --- /dev/null +++ b/tools/fixtures/bzip2.py @@ -0,0 +1,61 @@ +# Bzip2 fixtures (tools/fixtures.py): deterministic corpora compressed with Python's bz2 module (libbzip2) at block +# sizes 1..9, RLE1 edge cases (runs of 1..300 bytes, runs straddling block ends), every byte value, random data, +# concatenated streams with trailing garbage; plus a 4 MB bench corpus. +# tests/gen/bzip2.luau { corpora = { [name] = bytes }, cases = { { name, corpus, data } } } +# tests/gen/bzip2_bench.luau { size, crc, data } +import bz2, os, zlib + + +def text_corpus(limit): + base = os.path.dirname(os.__file__) + out = bytearray() + for name in sorted(os.listdir(base)): + if name.endswith(".py"): + with open(os.path.join(base, name), "rb") as f: + out += f.read() + if len(out) >= limit: + break + return bytes(out[:limit]) + + +def generate(ctx): + rng = ctx.rng(7) + runs = bytearray() + for n in list(range(1, 20)) + [250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 300, 1000, 5000]: + runs += bytes([n % 251]) * n + b"x" + corpora = { + "empty": b"", + "one": b"a", + "two": b"ab", + "four": b"aaaa", + "five": b"aaaaa", + "text": text_corpus(300000), + "random": rng.randbytes(60000), + "runs": bytes(runs), + "zeros": b"\0" * 250000, + "allbytes": bytes(range(256)) * 50, + "binary": bytes(rng.choice(b"\0\0\0\x01\x02\xff ABC") for _ in range(40000)), + # a run crossing the 100k block boundary at level 1 + "boundary": b"q" * 99990 + b"r" * 30 + rng.randbytes(1000), + # more than 18 Huffman group switches / many symbols in use + "skewed": bytes(rng.choice(range(256)) if rng.random() < 0.1 else 65 for _ in range(120000)), + } + cases = [] + for cname, data in corpora.items(): + for level in (1, 5, 9) if len(data) > 1000 else (9,): + cases.append(("%s/l%d" % (cname, level), cname, bz2.compress(data, level))) + for level in range(1, 10): + cases.append(("text/all-l%d" % level, "text", bz2.compress(corpora["text"], level))) + corpora["multi"] = corpora["text"][:20000] + b"" + corpora["runs"] + multi = bz2.compress(corpora["text"][:20000], 9) + bz2.compress(b"", 1) + bz2.compress(corpora["runs"], 3) + cases.append(("multi/streams", "multi", multi)) + cases.append(("multi/trailing", "multi", multi + b"garbage after the last stream")) + ctx.emit("bzip2", { + "corpora": corpora, + "cases": [{"name": n, "corpus": c, "data": d} for n, c, d in cases], + }) + bench = bytearray() + while len(bench) < 4_000_000: + bench += corpora["text"] + corpora["binary"] + rng.randbytes(20000) + bench = bytes(bench[:4_000_000]) + ctx.emit("bzip2_bench", {"size": len(bench), "crc": zlib.crc32(bench), "data": bz2.compress(bench, 9)}) diff --git a/tools/fixtures/cbor.py b/tools/fixtures/cbor.py new file mode 100644 index 0000000..e0f3166 --- /dev/null +++ b/tools/fixtures/cbor.py @@ -0,0 +1,108 @@ +# data/cbor fixtures: RFC 8949 Appendix A examples and random values encoded by Python's cbor2 (through nix): every +# integer width (and bignums), floats, text / byte strings, nested arrays / maps, dates (tags 0 / 1), other tags, +# simple values, undefined, indefinite-length items (written by hand), with the canonical form of cbor2's decode. +# tests/gen/cbor.luau { appendix = { { hex, data, canon } }, safe = { { data, canon } }, wide = { { data, canon, +# canonStr } } } safe: our decode + encode gives the same bytes; wide: big integers (doubles / exact text) +import importlib.util, os, pickle + +_spec = importlib.util.spec_from_file_location("_data_common", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_data_common.py")) +C = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(C) + +APPENDIX = """00 01 0a 17 1818 1819 1864 1903e8 1a000f4240 1b000000e8d4a51000 1bffffffffffffffff c249010000000000000000 +3bffffffffffffffff c349010000000000000000 20 29 3863 3903e7 f90000 f98000 f93c00 fb3ff199999999999a f93e00 f97bff +fa47c35000 fa7f7fffff fb7e37e43c8800759c f90001 f90400 f9c400 fbc010666666666666 f97c00 f97e00 f9fc00 fa7f800000 +fa7fc00000 faff800000 fb7ff0000000000000 fb7ff8000000000000 fbfff0000000000000 f4 f5 f6 f7 f0 f818 f8ff +c074323031332d30332d32315432303a30343a30305a c11a514b67b0 c1fb41d452d9ec200000 d74401020304 +d818456449455446 d82076687474703a2f2f7777772e6578616d706c652e636f6d 40 4401020304 60 6161 6449455446 62225c +62c3bc 63e6b0b4 64f0908591 80 83010203 8301820203820405 98190102030405060708090a0b0c0d0e0f101112131415161718181819 +a0 a201020304 a26161016162820203 826161a161626163 a56161614161626142616361436164614461656145 5f42010243030405ff +7f657374726561646d696e67ff 9fff 9f018202039f0405ffff 9f01820203820405ff 83018202039f0405ff 83019f0203ff820405 +9f0102030405060708090a0b0c0d0e0f101112131415161718181819ff bf61610161629f0203ffff 826161bf61626163ff +bf6346756ef563416d7421ff""" + +BODY = r''' +import cbor2, pickle, random, sys, datetime +from collections.abc import Mapping +HEXES = sys.argv[1:] if False else HEXLIST +def conv(v): + if v is cbor2.undefined: + return ["undefined"] + if isinstance(v, cbor2.CBORSimpleValue): + return ["simple", v.value] + if isinstance(v, cbor2.CBORTag): + return ["tag", v.tag, conv(v.value)] + if isinstance(v, (list, tuple)): + return [conv(x) for x in v] + if isinstance(v, Mapping) or hasattr(v, "items"): + return {(tuple(conv(k)) if isinstance(k, list) else k): conv(x) for k, x in v.items()} + return v +def cstr(v): + if isinstance(v, cbor2.CBORTag): + return cbor2.CBORTag(v.tag, cstr(v.value)) + if isinstance(v, int) and not isinstance(v, bool) and abs(v) >= 2**53: + return str(v) + if isinstance(v, (list, tuple)): + return [cstr(x) for x in v] + if isinstance(v, Mapping) or hasattr(v, "items"): + return {k: cstr(x) for k, x in v.items()} + return v +out = {"appendix": [], "safe": [], "wide": []} +for h in HEXES: + data = bytes.fromhex(h) + try: + v = cbor2.loads(data) + except Exception: + out["appendix"].append({"hex": h, "data": data, "error": True}) # e.g. f818: invalid since RFC 8949 + continue + if type(v).__name__ in ("Decimal", "Fraction", "UUID") or (isinstance(v, str) and h.startswith("d820")): + continue # semantic tags cbor2 interprets and we keep tagged + out["appendix"].append({"hex": h, "data": data, "canon": canon(conv(v)), "canonStr": canon(conv(cstr(v)))}) +rng = random.Random(9) +def rint(wide): + lim = rng.choice([23, 24, 255, 256, 65535, 65536, 2**32 - 1, 2**32, 2**53 - 1]) + if wide and rng.random() < 0.4: + lim = rng.choice([2**64 - 1, 2**70]) + v = rng.randrange(0, lim + 1) + return -v - 1 if rng.random() < 0.5 else v +def rstr(): + return "".join(rng.choice("abé中\U0001f600 \n\x00") for _ in range(rng.choice([0, 1, 23, 24, 255, 300]))) +def rval(d, wide): + r = rng.random() + if d > 3 or r < 0.5: + k = rng.randrange(10) + if k == 0: return None + if k == 1: return rng.random() < 0.5 + if k in (2, 3): return rint(wide) + if k == 4: + f = rng.uniform(-1e6, 1e6) * 10 ** rng.randrange(-5, 5) + return f if not f.is_integer() else f + 0.5 + if k == 5: return rstr() + if k == 6: return rng.randbytes(rng.choice([0, 3, 24, 256])) + if k == 7: + return datetime.datetime.fromtimestamp(rng.randrange(0, 2**33), datetime.timezone.utc) + if k == 8: + return cbor2.CBORTag(rng.choice([6, 1000, 100000]), rval(d + 1, wide)) + return rng.choice([cbor2.undefined, cbor2.CBORSimpleValue(rng.choice([0, 19, 32, 255]))]) + if r < 0.75: + return [rval(d + 1, wide) for _ in range(rng.choice([0, 1, 3, 23, 24] if d < 2 else [0, 1, 3]))] + m = {} + for _ in range(rng.choice([0, 1, 3, 23, 24] if d < 2 else [0, 1, 3])): + key = rint(False) if rng.random() < 0.3 else "".join(rng.choice("abcé") for _ in range(rng.randrange(6))) + m[key] = rval(d + 1, wide) + return m +for i in range(250): + data = cbor2.dumps(rval(0, False)) + out["safe"].append({"data": data, "canon": canon(conv(cbor2.loads(data)))}) +for i in range(120): + data = cbor2.dumps(rval(0, True)) + v = cbor2.loads(data) + out["wide"].append({"data": data, "canon": canon(conv(v)), "canonStr": canon(conv(cstr(v)))}) +sys.stdout.buffer.write(pickle.dumps(out, protocol=4)) +''' + + +def generate(ctx): + hexes = APPENDIX.split() + out = pickle.loads(C.python(ctx, ["cbor2"], "HEXLIST = %r\n" % hexes + BODY)) + ctx.emit("cbor", out) diff --git a/tools/fixtures/csv.py b/tools/fixtures/csv.py new file mode 100644 index 0000000..4ec279f --- /dev/null +++ b/tools/fixtures/csv.py @@ -0,0 +1,43 @@ +# data/csv fixtures: random tables (quotes, delimiters, CR / LF / CRLF inside fields, empty fields, unicode) written +# by Python's csv.writer / DictWriter in several dialects, with the rows csv.reader reads back (blank rows dropped: +# we skip blank lines). +# tests/gen/csv.luau { { data, delimiter, rows = { { field } }, keyed? } } +# keyed: the file has a header row (DictWriter) +import csv, io + + +def rand_field(rng): + alph = 'ab ,;\t|"\n\ré中1.' + k = rng.random() + if k < 0.15: + return "" + if k < 0.3: + return str(rng.randrange(-1000, 1000)) + return "".join(rng.choice(alph) for _ in range(rng.randrange(1, 8))) + + +def generate(ctx): + rng = ctx.rng(13) + cases = [] + for i in range(200): + delim = rng.choice([",", ",", ";", "\t", "|"]) + ncol = rng.randrange(1, 6) + rows = [[rand_field(rng) for _ in range(ncol)] for _ in range(rng.randrange(1, 12))] + buf = io.StringIO(newline="") + lt = "\r\n" if delim == "," else rng.choice(["\r\n", "\n"]) + w = csv.writer(buf, delimiter=delim, lineterminator=lt) + w.writerows(rows) + data = buf.getvalue() + back = [r for r in csv.reader(io.StringIO(data, newline=""), delimiter=delim) if r] + cases.append({"data": data.encode(), "delimiter": delim, "newline": lt, "rows": back}) + for i in range(30): + cols = ["id", "name", "note é", "x,y"][: rng.randrange(1, 5)] + rows = [{c: rand_field(rng) for c in cols} for _ in range(rng.randrange(1, 8))] + buf = io.StringIO(newline="") + w = csv.DictWriter(buf, fieldnames=cols) + w.writeheader() + w.writerows(rows) + data = buf.getvalue() + back = [r for r in csv.reader(io.StringIO(data, newline="")) if r] + cases.append({"data": data.encode(), "delimiter": ",", "newline": "\r\n", "rows": back, "keyed": True}) + ctx.emit("csv", cases) diff --git a/tools/fixtures/fonts.py b/tools/fixtures/fonts.py new file mode 100644 index 0000000..bab68e6 --- /dev/null +++ b/tools/fixtures/fonts.py @@ -0,0 +1,37 @@ +# Font fixtures (tools/fixtures.py): the imgui-luau fonts (TrueType: Cousine, DroidSans, Karla, Proggy*, Roboto, read +# from ~/dev/luau/imgui/imgui-luau/fonts or $IMGUI_FONTS; skipped if missing) and Source Sans 3 (CFF OpenType, nixpkgs +# source-sans), plus a copy of ProggyClean with a 'kern' table and a two-font collection, both made with fontTools. +# Reference values come from tools/fixtures/_font_reference.py: fontTools (metrics, names, cmap, hmtx, control boxes, +# areas, WOFF / WOFF2), HarfBuzz (GPOS kerning), FreeType (kern tables, unhinted renders). +# tests/gen/fonts.luau { fonts = { { name, data, upem, ..., cmap, glyphs, kern, renders } }, woff = { ... }, ttc } +import base64, glob, json, os, subprocess + +INPUTS = ["tools/fixtures/_font_reference.py"] + +FONTS = os.environ.get("IMGUI_FONTS", os.path.expanduser("~/dev/luau/imgui/imgui-luau/fonts")) +PICK = ["Cousine-Regular", "DroidSans", "Karla-Regular", "ProggyClean", "Roboto-Medium"] + + +def generate(ctx): + specs = [] + for name in PICK: + p = os.path.join(FONTS, name + ".ttf") + if os.path.exists(p): + specs.append({"name": name, "b64": base64.b64encode(open(p, "rb").read()).decode()}) + out = subprocess.run(["nix", "build", "--no-link", "--print-out-paths", "nixpkgs#source-sans"], capture_output=True, + check=True, text=True).stdout.strip().split("\n")[-1] + otf = os.path.join(out, "share", "fonts", "opentype", "SourceSans3-Regular.otf") + specs.append({"name": "SourceSans3-Regular", "b64": base64.b64encode(open(otf, "rb").read()).decode()}) + code = open(os.path.join(ctx.root, "tools", "fixtures", "_font_reference.py")).read() + raw = ctx.python(["fonttools", "freetype-py", "uharfbuzz", "brotli"], code, input=json.dumps(specs).encode()) + res = json.loads(raw) + d = base64.b64decode + for f in res["fonts"]: + f["data"] = d(f["data"]) + for r in f["renders"]: + r["pixels"] = d(r["pixels"]) + for w in res["woff"]: + w["woff"], w["woff2"], w["woff2h"] = d(w["woff"]), d(w["woff2"]), d(w["woff2h"]) + if "ttc" in res: + res["ttc"]["data"] = d(res["ttc"]["data"]) + ctx.emit("fonts", res) diff --git a/tools/fixtures/gif.py b/tools/fixtures/gif.py new file mode 100644 index 0000000..257fb21 --- /dev/null +++ b/tools/fixtures/gif.py @@ -0,0 +1,133 @@ +# GIF fixtures (tools/fixtures.py): GIFs written by ImageMagick and Pillow (static, interlaced, 2..256 colours, grey, +# transparency, animations with every disposal method, sub-rectangle frames, local colour tables, loop counts, +# comments), each with ImageMagick's decode of every frame as the reference. +# tests/gen/gif.luau { { name, data, width, height, loops, frames = { { w, h, x, y, delay, dispose, crc } }, +# first = crc of the first frame on a transparent canvas, comment? } } +# tests/gen/gif_bench.luau a 512 x 384 photo-like GIF (256 colours) and a 40-frame 128 x 128 animation +# CRCs are of rgba8 with transparent pixels (alpha 0) zeroed to 0, 0, 0, 0. delay in centiseconds. +import os, struct, tempfile, zlib + +PILLOW = r''' +import io, sys, random +from PIL import Image, ImageDraw +out = sys.argv[1] +rng = random.Random(4) +def frame(w, h, seed, alpha=False): + im = Image.new("RGBA", (w, h), (0, 0, 0, 0) if alpha else (seed * 40 % 256, 90, 200, 255)) + d = ImageDraw.Draw(im) + for i in range(5): + x, y = rng.randrange(w), rng.randrange(h) + d.ellipse([x - 6, y - 6, x + 6, y + 6], fill=(rng.randrange(256), rng.randrange(256), seed * 60 % 256, 255)) + return im +# animation with per-frame disposal, durations, loop +fr = [frame(48, 32, i) for i in range(4)] +fr[0].save(out + "/pil_anim.gif", save_all=True, append_images=fr[1:], duration=[50, 120, 70, 200], loop=2, disposal=[0, 1, 2, 3], optimize=False) +# transparent animation (sub-rectangles from Pillow's optimizer) +fr = [frame(40, 40, i, alpha=True) for i in range(5)] +fr[0].save(out + "/pil_alpha.gif", save_all=True, append_images=fr[1:], duration=80, loop=0, disposal=2) +# a static interlaced palette image with a comment +im = frame(61, 37, 9).convert("P", palette=Image.Palette.ADAPTIVE, colors=32) +im.save(out + "/pil_interlaced.gif", interlace=True, comment=b"made by tools/fixtures/gif.py") +# 1-bit and a 3-colour image (minimum code size 2) +Image.frombytes("L", (17, 9), bytes((x * 255 // 16) if (x + y) % 3 else 0 for y in range(9) for x in range(17))).convert("1").save(out + "/pil_1bit.gif") +im = Image.new("P", (23, 19)); im.putpalette([255, 0, 0, 0, 255, 0, 0, 0, 255]) +im.putdata([(x * y) % 3 for y in range(19) for x in range(23)]); im.save(out + "/pil_3col.gif") +''' + + +def run_im(ctx, args): + return ctx.nix("imagemagick", ["magick"] + args) + + +def reference(ctx, path): + info = run_im(ctx, ["identify", "-format", "%w %h %X %Y %T %D %W %H %[comment]|", path]).decode("latin-1") + raw = run_im(ctx, [path, "rgba:-"]) + frames, pos = [], 0 + comment = None + for line in info.split("|"): + if not line.strip(): + continue + parts = line.split(" ", 8) + w, h, x, y, delay = int(parts[0]), int(parts[1]), int(parts[2]), int(parts[3]), int(parts[4]) + dispose = parts[5] + cw, ch = int(parts[6]), int(parts[7]) + if len(parts) > 8 and parts[8]: + comment = parts[8] + px = bytearray(raw[pos:pos + w * h * 4]); pos += w * h * 4 + for i in range(0, len(px), 4): + if px[i + 3] == 0: + px[i:i + 4] = b"\0\0\0\0" + frames.append({"w": w, "h": h, "x": x, "y": y, "delay": delay, "dispose": dispose.lower(), "px": bytes(px), "crc": zlib.crc32(bytes(px))}) + assert pos == len(raw), (path, pos, len(raw)) + # the first frame on a transparent canvas + f = frames[0] + canvas = bytearray(cw * ch * 4) + for yy in range(f["h"]): + for xx in range(f["w"]): + X, Y = f["x"] + xx, f["y"] + yy + if 0 <= X < cw and 0 <= Y < ch: + p = f["px"][(yy * f["w"] + xx) * 4:(yy * f["w"] + xx) * 4 + 4] + if p[3]: + canvas[(Y * cw + X) * 4:(Y * cw + X) * 4 + 4] = p + for f in frames: + del f["px"] + return cw, ch, frames, zlib.crc32(bytes(canvas)), comment + + +def loops_of(data): + i = data.find(b"NETSCAPE2.0") + if i < 0: + return None + return data[i + 13] | (data[i + 14] << 8) + + +def generate(ctx): + work = tempfile.mkdtemp(prefix="gif-fx-") + files = [] + + def im(name, args): + p = os.path.join(work, name + ".gif") + run_im(ctx, args + [p]) + files.append((name, p)) + + im("rose", ["rose:"]) + im("rose_2col", ["rose:", "-colors", "2"]) + im("rose_16col_interlaced", ["rose:", "-colors", "16", "-interlace", "GIF"]) + im("rose_dither", ["rose:", "-resize", "200%", "-dither", "FloydSteinberg", "-colors", "64"]) + im("logo", ["logo:", "-resize", "30%"]) + im("gray", ["-size", "64x40", "gradient:", "-colorspace", "gray"]) + im("transparent", ["-size", "40x30", "xc:none", "-fill", "red", "-draw", "circle 20,15 20,5"]) + for disp in ("None", "Background", "Previous"): + im("anim_" + disp.lower(), ["-delay", "7", "-dispose", disp, "-size", "30x20", "xc:red", + "-size", "10x8", "-page", "+5+4", "xc:blue", "-page", "+12+9", "xc:lime", + "-page", "+0+0", "-size", "6x6", "xc:yellow", "-loop", "3"]) + # local colour tables: frames with different 256-colour palettes + im("anim_local", ["-delay", "20", "rose:", "(", "rose:", "-negate", ")", "(", "logo:", "-resize", "70x46!", ")", "-loop", "0"]) + # optimised transparency animation + im("anim_optimized", ["-delay", "5", "-size", "50x50", "xc:white", "-fill", "black", + "(", "+clone", "-draw", "circle 10,10 10,5", ")", "(", "+clone", "-draw", "circle 30,30 30,24", ")", + "(", "+clone", "-draw", "circle 40,12 40,6", ")", "-layers", "OptimizeTransparency", "-loop", "0"]) + ctx.python(["pillow"], "import sys; sys.argv = ['', %r]\n" % work + PILLOW) + for n in ("pil_anim", "pil_alpha", "pil_interlaced", "pil_1bit", "pil_3col"): + files.append((n, os.path.join(work, n + ".gif"))) + cases = [] + for name, p in files: + data = open(p, "rb").read() + cw, ch, frames, first, comment = reference(ctx, p) + c = {"name": name, "data": data, "width": cw, "height": ch, "frames": frames, "first": first} + lp = loops_of(data) + if lp is not None: + c["loops"] = lp # the raw NETSCAPE2.0 repeat value + if comment: + c["comment"] = comment + cases.append(c) + ctx.emit("gif", cases) + + bench = os.path.join(work, "bench.gif") + run_im(ctx, ["-size", "512x384", "-seed", "3", "plasma:fractal", "-colors", "256", bench]) + anim = os.path.join(work, "bench_anim.gif") + args = ["-delay", "4"] + for i in range(40): + args += ["(", "-size", "128x128", "radial-gradient:", "-roll", "+%d+%d" % (i * 3, i * 2), ")"] + run_im(ctx, args + ["-colors", "128", "-loop", "0", anim]) + ctx.emit("gif_bench", {"still": open(bench, "rb").read(), "anim": open(anim, "rb").read()}) diff --git a/tools/fixtures/gltf.py b/tools/fixtures/gltf.py new file mode 100644 index 0000000..a424fcf --- /dev/null +++ b/tools/fixtures/gltf.py @@ -0,0 +1,115 @@ +# glTF fixtures (tools/fixtures.py): Khronos glTF-Sample-Assets models (tests/fixtures/gltf, licences per model +# folder), gltfpack (meshoptimizer) quantized variants (KHR_mesh_quantization, normalized and integer positions, +# KHR_texture_transform), and files exported by assimp, with reference values from assimp (`assimp info`: meshes, faces, +# bounds, materials, animations, cameras, lights) and trimesh (area, triangles, bounds of the whole scene). +# tests/gen/gltf_cases.luau { name, main, data, files = { uri -> bytes }, assimp, trimesh, like? (the original of a +# quantized variant: compare against its references with a tolerance) } +# tests/gen/gltf_xcheck.luau our encoder's .glb and .gltf for every case (tools/fixtures/_gltf_encode.luau), read back +# by assimp and trimesh: { name, case, assimp, trimesh } +import importlib.util, json, os, struct + +INPUTS = ["tests/fixtures/gltf", "src/Formats/model/gltf", "src/Formats/codecs/Json", "src/Formats/codecs/Base64", + "tools/fixtures/_model_ref.py", "tools/fixtures/_gltf_encode.luau"] + + +def ref_module(ctx): + spec = importlib.util.spec_from_file_location("_model_ref", os.path.join(ctx.root, "tools", "fixtures", "_model_ref.py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def assimp_extra(ctx, path): + # cameras / lights / animations counts from assimp info (the shared helper parses meshes / faces / bounds) + import re, subprocess + try: + txt = ctx.nix("assimp", ["assimp", "info", path, "-r"]).decode("utf-8", "replace") + except subprocess.CalledProcessError: + return {} + out = {} + for label in ("Animations", "Cameras", "Lights", "Bones"): + m = re.search(r"^" + label + r":\s+(\d+)", txt, re.M) + if m: + out[label.lower()] = int(m.group(1)) + return out + + +def ply_torus(R=2.0, r=0.5, a=16, b=8): + import math + vs, fs = [], [] + for i in range(a): + for j in range(b): + u, v = 2 * math.pi * i / a, 2 * math.pi * j / b + vs.append(((R + r * math.cos(v)) * math.cos(u), r * math.sin(v), (R + r * math.cos(v)) * math.sin(u))) + for i in range(a): + for j in range(b): + p, q = i * b + j, ((i + 1) % a) * b + j + p2, q2 = i * b + (j + 1) % b, ((i + 1) % a) * b + (j + 1) % b + fs.append((p, p2, q2)) + fs.append((p, q2, q)) + head = "ply\nformat ascii 1.0\nelement vertex %d\nproperty float x\nproperty float y\nproperty float z\nelement face %d\nproperty list uchar int vertex_indices\nend_header\n" % (len(vs), len(fs)) + return (head + "".join("%r %r %r\n" % v for v in vs) + "".join("3 %d %d %d\n" % f for f in fs)).encode() + + +def generate(ctx): + M = ref_module(ctx) + root = os.path.join(ctx.root, "tests", "fixtures", "gltf") + cases = [] + for model in sorted(os.listdir(root)): + for variant in sorted(os.listdir(os.path.join(root, model))): + d = os.path.join(root, model, variant) + if not os.path.isdir(d): + continue + mains = [f for f in sorted(os.listdir(d)) if f.endswith(".gltf") or f.endswith(".glb")] + if not mains: + continue + files = {f: open(os.path.join(d, f), "rb").read() for f in sorted(os.listdir(d)) if f != mains[0]} + cases.append({"name": model + "/" + variant, "main": mains[0], "path": os.path.join(d, mains[0]), "files": files}) + # gltfpack variants of a few models: default (integer positions + texture transform), -vpn (normalized positions), + # -vpf (float positions, quantized normals / uvs) + tmp = M.tempdir() + for model, variant, main in (("BoxTextured", "glTF", "BoxTextured.gltf"), ("Box", "glTF-Binary", "Box.glb"), ("SimpleSkin", "glTF", "SimpleSkin.gltf"), ("MultiUVTest", "glTF-Binary", "MultiUVTest.glb")): + for flag in ("", "-vpn", "-vpf", "-vpi"): + out = os.path.join(tmp, "%s_q%s.glb" % (model, flag)) + args = ["gltfpack", "-i", os.path.join(root, model, variant, main), "-o", out, "-kn", "-km"] + ([flag] if flag else []) + ctx.nix("meshoptimizer", args) + cases.append({"name": "gltfpack/%s%s" % (model, flag), "main": os.path.basename(out), "path": out, "files": {}, "like": model + "/" + variant}) + # assimp's glTF exporters + ply = os.path.join(tmp, "torus.ply") + with open(ply, "wb") as f: + f.write(ply_torus()) + for ext in ("glb", "gltf"): + out = os.path.join(tmp, "torus_assimp." + ext) + ctx.nix("assimp", ["assimp", "export", ply, out, "-f" + ("glb2" if ext == "glb" else "gltf2")]) + files = {} + for f in os.listdir(tmp): + if f.startswith("torus_assimp") and f.endswith(".bin"): + files[f] = open(os.path.join(tmp, f), "rb").read() + cases.append({"name": "assimp/torus." + ext, "main": os.path.basename(out), "path": out, "files": files}) + infos = M.assimp_info(ctx, [c["path"] for c in cases], raw=True) + tms = M.trimesh_metrics(ctx, [c["path"] for c in cases]) + for c, a, t in zip(cases, infos, tms): + a.update(assimp_extra(ctx, c["path"])) + c["assimp"] = a + c["trimesh"] = t + c["data"] = open(c["path"], "rb").read() + del c["path"] + ctx.emit("gltf_cases", cases) + + # the reference tools read our output + ours = M.luau_encode(ctx, "tools/fixtures/_gltf_encode.luau") + xtmp = M.tempdir() + names = [] + for name, data in sorted(ours.items()): + with open(os.path.join(xtmp, name), "wb") as f: + f.write(data) + if name.endswith(".glb") or name.endswith(".gltf"): + names.append(name) + paths = [os.path.join(xtmp, n) for n in names] + xi = M.assimp_info(ctx, paths, raw=True) + xt = M.trimesh_metrics(ctx, paths) + out = [] + for n, a, t in zip(names, xi, xt): + a.update(assimp_extra(ctx, os.path.join(xtmp, n))) + out.append({"name": n, "case": int(n.split("_")[1].split(".")[0]), "assimp": a, "trimesh": t}) + ctx.emit("gltf_xcheck", out) diff --git a/tools/fixtures/hdr.py b/tools/fixtures/hdr.py new file mode 100644 index 0000000..bdf1017 --- /dev/null +++ b/tools/fixtures/hdr.py @@ -0,0 +1,93 @@ +# Radiance HDR fixtures (tools/fixtures.py): files ImageMagick writes (new-style RLE, from float PFM sources) and +# hand-written ones (flat and old-style RLE scanlines, narrow images, the "#?RGBE" header, EXPOSURE lines, every +# orientation); references = ImageMagick's float decodes for its files, and for the hand-written ones the RGBE values +# decoded by the rgbe.c rule (m * 2^(e - 136)) here. +# tests/gen/hdr.luau { { name, data, width, height, floats (rgbaf32 little-endian bytes), exposure? } } +import math, os, random, shutil, struct, subprocess, tempfile + + +def rgbe(r, g, b): + v = max(r, g, b) + if v < 1e-32: + return (0, 0, 0, 0) + m, e = math.frexp(v) + s = m * 256 / v + return (min(255, int(r * s)), min(255, int(g * s)), min(255, int(b * s)), e + 128) + + +def flt(p): + if p[3] == 0: + return (0.0, 0.0, 0.0) + f = math.ldexp(1.0, p[3] - 136) + return (p[0] * f, p[1] * f, p[2] * f) + + +def generate(ctx): + magick = ctx.nix("imagemagick", ["sh", "-c", "command -v magick"]).decode().strip() + work = tempfile.mkdtemp(prefix="formats-hdr-") + try: + _generate(ctx, magick, work) + finally: + shutil.rmtree(work, ignore_errors=True) + + +def _generate(ctx, magick, work): + rng = random.Random(4) + cases = [] + + def im_case(name, w, h, fn): + pfm = os.path.join(work, name + ".pfm") + with open(pfm, "wb") as f: + f.write(b"PF\n%d %d\n-1.0\n" % (w, h)) + for y in range(h - 1, -1, -1): + for x in range(w): + f.write(struct.pack("<fff", *fn(x, y))) + out = os.path.join(work, name + ".hdr") + subprocess.run([magick, pfm, out], check=True, capture_output=True) + fl = subprocess.run([magick, out, "-depth", "32", "-define", "quantum:format=floating-point", "-endian", "LSB", "rgba:-"], check=True, capture_output=True).stdout + cases.append({"name": name, "data": open(out, "rb").read(), "width": w, "height": h, "floats": fl}) + + im_case("im-gradient", 64, 20, lambda x, y: (x / 16.0, y / 5.0, (x * y) % 7 * 0.3)) + im_case("im-noise", 33, 9, lambda x, y: (rng.random() * 100, rng.random(), rng.random() * 0.001)) + im_case("im-flat", 100, 3, lambda x, y: (0.5, 0.25, 2.0) if x < 60 else (0.0, 0.0, 0.0)) + + def hand(name, w, h, header, res, rows, mapping, exposure=None): + """rows: list of scanline byte strings; mapping(i, j) -> (x, y) of scanline i pixel j; pix: (i, j) -> RGBE""" + data = header + b"\n\n" + res + b"\n" + b"".join(r for r, _ in rows) + fl = [(0.0, 0.0, 0.0)] * (w * h) + for i, (_, pixels) in enumerate(rows): + for j, p in enumerate(pixels): + x, y = mapping(i, j) + fl[y * w + x] = flt(p) + c = {"name": name, "data": data, "width": w, "height": h, + "floats": b"".join(struct.pack("<ffff", *v, 1.0) for v in fl)} + if exposure: + c["exposure"] = exposure + cases.append(c) + + def flat_row(n, seed): + px = [rgbe(rng.random() * 4, rng.random(), rng.random() * 0.1) for _ in range(n)] + px = [p if p[:3] != (1, 1, 1) else (2, 1, 1, p[3]) for p in px] + return b"".join(bytes(p) for p in px), px + + def oldrle_row(n): + p = rgbe(0.7, 0.2, 0.1) + q = rgbe(3.0, 3.0, 3.0) + # p, then a run of 3 more p, then q, then a run of 2 + (1 << 8)*0 ... keep it simple: q x (n - 5) + pix = [p] * 4 + [q] * (n - 4) + run = n - 5 + return bytes(p) + bytes((1, 1, 1, 3)) + bytes(q) + bytes((1, 1, 1, run)), pix + + w, h = 5, 3 + rows = [flat_row(w, i) for i in range(h)] + hand("flat-narrow", w, h, b"#?RGBE\nFORMAT=32-bit_rle_rgbe\nEXPOSURE=2.0\nEXPOSURE=1.5", b"-Y 3 +X 5", rows, lambda i, j: (j, i), exposure=3.0) + rows = [oldrle_row(12) for _ in range(2)] + hand("old-rle", 12, 2, b"#?RADIANCE\nFORMAT=32-bit_rle_rgbe\nSOFTWARE=hand", b"-Y 2 +X 12", rows, lambda i, j: (j, i)) + for res, mp in ((b"+Y 3 +X 5", lambda i, j: (j, 2 - i)), (b"-Y 3 -X 5", lambda i, j: (4 - j, i)), + (b"+Y 3 -X 5", lambda i, j: (4 - j, 2 - i))): + rows = [flat_row(5, i) for i in range(3)] + hand("orient " + res.decode(), 5, 3, b"#?RADIANCE", res, rows, mp) + for res, mp in ((b"+X 5 -Y 3", lambda i, j: (i, j)), (b"-X 5 +Y 3", lambda i, j: (4 - i, 2 - j))): + rows = [flat_row(3, i) for i in range(5)] + hand("orient " + res.decode(), 5, 3, b"#?RADIANCE", res, rows, mp) + ctx.emit("hdr", cases) diff --git a/tools/fixtures/ico.py b/tools/fixtures/ico.py new file mode 100644 index 0000000..e6a51a2 --- /dev/null +++ b/tools/fixtures/ico.py @@ -0,0 +1,93 @@ +# ICO / CUR fixtures (tools/fixtures.py): icons written by ImageMagick (auto-resize sets with a 256 PNG entry) and +# Pillow (PNG and BMP entries), and hand-built ones from Pillow's BMP writer (1 / 4 / 8 / 24 / 32-bit DIBs with AND +# masks, a cursor with hotspots); references = Pillow's RGBA decode of every entry, in file order. +# tests/gen/ico.luau { { name, data, entries = { { width, height, rgba (bytes) } } } } +import struct + +CODE = r''' +import io, struct, subprocess, sys +from PIL import Image, IcoImagePlugin +magick = sys.argv[1] +out = [] +def refs(data): + if data[2] == 2: # IcoFile reads icons only: decode a cursor's entries as an icon's + data = data[:2] + b"\x01" + data[3:] + f = IcoImagePlugin.IcoFile(io.BytesIO(data)) + order = sorted(range(len(f.entry)), key=lambda i: f.entry[i].offset) + res = [] + for i in order: + im = f.frame(i).convert("RGBA") + res.append((im.size[0], im.size[1], im.tobytes())) + return res +def emit(name, data): + out.append((name, data, refs(data))) +src = Image.new("RGBA", (64, 64)) +px = src.load() +for y in range(64): + for x in range(64): + a = 255 if (x - 32) ** 2 + (y - 32) ** 2 < 900 else (0 if x < 8 else 128) + px[x, y] = ((x * 4) % 256, (y * 4) % 256, ((x ^ y) * 8) % 256, a) +png = io.BytesIO(); src.save(png, "PNG") +r = subprocess.run([magick, "png:-", "-define", "icon:auto-resize=256,48,32,16", "ico:-"], input=png.getvalue(), capture_output=True, check=True) +emit("im-autoresize", r.stdout) +for fmt in ("png", "bmp"): + b = io.BytesIO(); src.save(b, "ICO", sizes=[(16, 16), (32, 32), (64, 64)], bitmap_format=fmt); emit("pil-" + fmt, b.getvalue()) +# hand-built DIB entries from Pillow BMPs +def dib(im, mask_fn): + b = io.BytesIO(); im.save(b, "BMP"); d = b.getvalue()[14:] + w, h = im.size + hs = struct.unpack("<I", d[:4])[0] + d = d[:8] + struct.pack("<i", h * 2) + d[12:] + stride = ((w + 31) // 32) * 4 + mask = bytearray() + for y in range(h - 1, -1, -1): + row = bytearray(stride) + for x in range(w): + if mask_fn(x, y): + row[x // 8] |= 0x80 >> (x % 8) + mask += row + return d + bytes(mask) +def icon(entries, typ=1, hotspots=None): + hdr = struct.pack("<HHH", 0, typ, len(entries)) + off = 6 + 16 * len(entries) + dirs, blobs = b"", b"" + for i, (im, blob, bpp) in enumerate(entries): + w, h = im.size + f1, f2 = (1, bpp) if typ == 1 else hotspots[i] + dirs += struct.pack("<BBBBHHII", w % 256, h % 256, 0, 0, f1, f2, len(blob), off) + off += len(blob); blobs += blob + return hdr + dirs + blobs +base = src.resize((24, 20)) +m = lambda x, y: (x + y) % 7 == 0 +e1 = base.convert("1"); e4 = base.convert("RGB").quantize(16); e8 = base.convert("RGB").quantize(200); e24 = base.convert("RGB") +emit("hand-dibs", icon([(e1, dib(e1, m), 1), (e4, dib(e4, m), 4), (e8, dib(e8, m), 8), (e24, dib(e24, m), 24)])) +e32 = src.resize((30, 17)) +b = io.BytesIO(); e32.save(b, "BMP"); d32 = b.getvalue()[14:] +# Pillow writes 32-bit BMPs as BGRA? if not, build one by hand +w, h = e32.size +bgra = b"".join(bytes((p[2], p[1], p[0], p[3])) for y in range(h - 1, -1, -1) for p in (e32.getpixel((x, y)) for x in range(w))) +stride = ((w + 31) // 32) * 4 +d32 = struct.pack("<IiiHHIIiiII", 40, w, h * 2, 1, 32, 0, len(bgra), 0, 0, 0, 0) + bgra + bytes(stride * h) +emit("hand-32", icon([(e32, d32, 32)])) +emit("hand-cur", icon([(e24, dib(e24, m), 24), (e8, dib(e8, m), 8)], typ=2, hotspots=[(3, 4), (5, 6)])) +for name, data, rs in out: + sys.stdout.buffer.write(struct.pack("<HIH", len(name), len(data), len(rs)) + name.encode() + data) + for w, h, px in rs: + sys.stdout.buffer.write(struct.pack("<III", w, h, len(px)) + px) +''' + + +def generate(ctx): + magick = ctx.nix("imagemagick", ["sh", "-c", "command -v magick"]).decode().strip() + raw = ctx.python(["pillow"], CODE.replace("sys.argv[1]", repr(magick))) + cases, p = [], 0 + while p < len(raw): + nl, dl, ne = struct.unpack("<HIH", raw[p:p + 8]); p += 8 + name = raw[p:p + nl].decode(); p += nl + data = raw[p:p + dl]; p += dl + ents = [] + for _ in range(ne): + w, h, pl = struct.unpack("<III", raw[p:p + 12]); p += 12 + ents.append({"width": w, "height": h, "rgba": raw[p:p + pl]}); p += pl + cases.append({"name": name, "data": data, "entries": ents}) + ctx.emit("ico", cases) diff --git a/tools/fixtures/imageops.py b/tools/fixtures/imageops.py new file mode 100644 index 0000000..c7866af --- /dev/null +++ b/tools/fixtures/imageops.py @@ -0,0 +1,65 @@ +# ImageOps fixtures (tools/fixtures.py): Pillow references for ops/ImageOps. +# tests/gen/imageops.luau { rgb = { w, h, px }, rgba = {...}, rgba2 = {...}, gray = L bytes of rgb, +# resize = { { filter, mode, w, h, px } }, rotate = { { angle, expand, w, h, px } }, +# composite = bytes } +# rgb / rgba: smooth gradients + noise + shapes (Pillow drawing), deterministic. +import struct + +CODE = r''' +import random, struct, sys +from PIL import Image, ImageDraw +rng = random.Random(11) +def src(w, h, mode): + im = Image.new("RGBA", (w, h)) + px = im.load() + for y in range(h): + for x in range(w): + px[x, y] = ((x * 255) // (w - 1), (y * 255) // (h - 1), (x * y) % 256, 255 if mode == "RGB" else (x * 7 + y * 3) % 256) + d = ImageDraw.Draw(im) + for _ in range(5): + x0, y0 = rng.randrange(w), rng.randrange(h) + d.ellipse([x0, y0, x0 + rng.randrange(4, 20), y0 + rng.randrange(4, 20)], fill=(rng.randrange(256), rng.randrange(256), rng.randrange(256), 255 if mode == "RGB" else rng.randrange(256))) + return im.convert(mode) +out = [] +def emit(tag, *parts): + data = b"".join(parts) + out.append(struct.pack("<16sI", tag.encode().ljust(16), len(data)) + data) +rgb = src(61, 47, "RGB"); rgba = src(61, 47, "RGBA"); rgba2 = src(61, 47, "RGBA") +hdr = lambda im: struct.pack("<II", *im.size) +emit("rgb", hdr(rgb), rgb.tobytes()); emit("rgba", hdr(rgba), rgba.tobytes()); emit("rgba2", hdr(rgba2), rgba2.tobytes()) +emit("gray", rgb.convert("L").tobytes()) +emit("graya", rgba.convert("L").tobytes()) +F = {"nearest": Image.NEAREST, "bilinear": Image.BILINEAR, "lanczos": Image.LANCZOS} +for fname, f in F.items(): + for (w, h) in ((30, 20), (100, 80), (61, 20), (13, 47), (7, 3), (200, 150)): + for mode in ("RGB", "L"): + r = rgb.convert(mode).resize((w, h), f) + emit("resize", struct.pack("<16s4sII", fname.encode().ljust(16), mode.encode().ljust(4), w, h), r.tobytes()) +for angle, expand in ((30, True), (-45, True), (123.4, True), (17, False), (200, False)): + r = rgba.rotate(angle, Image.BILINEAR, expand=expand) + emit("rotate", struct.pack("<dBII", angle, 1 if expand else 0, *r.size), r.tobytes()) +emit("composite", Image.alpha_composite(rgba, rgba2).tobytes()) +sys.stdout.buffer.write(b"".join(out)) +''' + + +def generate(ctx): + raw = ctx.python(["pillow"], CODE) + p = 0 + fx = {"resize": [], "rotate": []} + while p < len(raw): + tag, n = struct.unpack("<16sI", raw[p:p + 20]); p += 20 + tag = tag.decode().strip() + data = raw[p:p + n]; p += n + if tag in ("rgb", "rgba", "rgba2"): + w, h = struct.unpack("<II", data[:8]) + fx[tag] = {"w": w, "h": h, "px": data[8:]} + elif tag in ("gray", "graya", "composite"): + fx[tag] = data + elif tag == "resize": + f, mode, w, h = struct.unpack("<16s4sII", data[:28]) + fx["resize"].append({"filter": f.decode().strip(), "mode": mode.decode().strip(), "w": w, "h": h, "px": data[28:]}) + elif tag == "rotate": + a, e, w, h = struct.unpack("<dBII", data[:17]) + fx["rotate"].append({"angle": a, "expand": bool(e), "w": w, "h": h, "px": data[17:]}) + ctx.emit("imageops", fx) diff --git a/tools/fixtures/ini.py b/tools/fixtures/ini.py new file mode 100644 index 0000000..412d4f7 --- /dev/null +++ b/tools/fixtures/ini.py @@ -0,0 +1,62 @@ +# data/ini fixtures: random configs written by Python's configparser (interpolation off, key case kept), and +# hand-written messy files (comments, ':' delimiters, continuation lines, odd spacing, duplicates) with what +# configparser(strict=False) reads from them. +# tests/gen/ini.luau { written = { { data, canon } }, read = { { data, canon } } } +import configparser, importlib.util, io, os + +_spec = importlib.util.spec_from_file_location("_data_common", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_data_common.py")) +C = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(C) + + +def parser(): + p = configparser.ConfigParser(interpolation=None, strict=False) + p.optionxform = str + return p + + +def as_dict(p): + return {s: dict(p.items(s, raw=True)) for s in p.sections()} + + +MESSY = [ + "[a]\nx=1\ny : two words \n; comment\n # indented comment\nz =\n", + "[s]\nkey = line one\n line two\n\tline three\nk2: v\n", + "# top comment\n[one]\na = 1\n[two]\nb = 2\n[one]\nc = 3\n", + "[dup]\na = 1\na = 2\n", + "[weird name with spaces]\n key with spaces = value with = sign \n", + "[s]\nurl = http://x:8080/p?a=b\npath: C:\\dir\n", + "[x]\r\nwin = yes\r\nmore = no\r\n", + "[\u00e9]\n\u4e2d = \u00fc\n", + "[a]\nk = v ; not a comment by default\n", + "[e]\nempty =\nalso:\n", +] + + +def generate(ctx): + rng = ctx.rng(17) + written = [] + alph = "ab xyz09_-.\u00e9/=:;#" + for i in range(80): + p = parser() + for s in range(rng.randrange(1, 5)): + name = "sec%d %s" % (s, rng.choice(["", "x", "\u00e9"])) + p.add_section(name) + for k in range(rng.randrange(0, 6)): + key = "k%d%s" % (k, rng.choice(["", "_a", ".b"])) + val = "".join(rng.choice(alph) for _ in range(rng.randrange(0, 12))).strip() + if rng.random() < 0.15: + val = val + "\nsecond line" + rng.choice(["", "\nthird"]) + p.set(name, key, val) + buf = io.StringIO() + p.write(buf) + data = buf.getvalue() + back = parser() + back.read_string(data) + written.append({"data": data.encode(), "canon": C.canon(as_dict(back))}) + read = [] + for m in MESSY: + p = parser() + p.read_string(m) + read.append({"data": m.encode(), "canon": C.canon(as_dict(p))}) + ctx.emit("ini", {"written": written, "read": read}) diff --git a/tools/fixtures/isobmff.py b/tools/fixtures/isobmff.py new file mode 100644 index 0000000..4239ca6 --- /dev/null +++ b/tools/fixtures/isobmff.py @@ -0,0 +1,89 @@ +# containers/IsoBmff fixtures (tools/fixtures.py): small files from ffmpeg / MP4Box / avifenc (nix) with ffprobe's +# packet lists as the reference. +# tests/gen/isobmff.luau { cases = { { name, data, streams = { { codec, kind, timescale, width?, height?, +# sampleRate?, channels?, extradata }, ... }, packets = { { stream, pos, size, dts, pts, key }, +# ... } } }, tagged = { data, tags, cover }, avif = { { name, data, width, height, alpha } } } +import json, os, shutil, subprocess, tempfile + +PKGS = ["ffmpeg", "gpac", "libavif"] + + +def sh(ctx, script, cwd): + return ctx.nix(PKGS, ["sh", "-c", "cd '%s' && %s" % (cwd, script)]) + + +def probe(ctx, path, cwd): + out = sh(ctx, "ffprobe -v error -ignore_editlist 1 -show_streams -show_packets -of json '%s'" % path, cwd) + j = json.loads(out) + streams = [] + for s in j["streams"]: + kind = s["codec_type"] + if kind == "video" and s.get("disposition", {}).get("attached_pic"): + continue + tb = s["time_base"].split("/") + e = {"codec": s["codec_name"], "kind": kind, "timescale": int(tb[1]), "index": s["index"], + "extradata": int(s.get("extradata_size", 0))} + if kind == "video": + e["width"], e["height"] = s["width"], s["height"] + if kind == "audio": + e["sampleRate"], e["channels"] = int(s["sample_rate"]), s["channels"] + streams.append(e) + index = {s["index"]: i + 1 for i, s in enumerate(streams)} + packets = [] + for p in j["packets"]: + if p["stream_index"] not in index: + continue + packets.append({"stream": index[p["stream_index"]], "pos": int(p["pos"]), "size": int(p["size"]), + "dts": int(p["dts"]), "pts": int(p["pts"]), "key": "K" in p["flags"]}) + for s in streams: + del s["index"] + return streams, packets + + +def generate(ctx): + d = tempfile.mkdtemp(prefix="isobmff-fx-") + try: + src_v = "-f lavfi -i testsrc=size=64x48:rate=10 -t 1.2" + src_a = "-f lavfi -i sine=frequency=440:sample_rate=44100 -t 1.0" + steps = [ + ("h264_aac.mp4", "ffmpeg -v error %s %s -c:v libx264 -bf 2 -g 5 -pix_fmt yuv420p -c:a aac -b:a 64k -ac 2 h264_aac.mp4" % (src_v, src_a)), + ("faststart.mp4", "ffmpeg -v error -i h264_aac.mp4 -c copy -movflags +faststart faststart.mp4"), + ("mjpeg_pcm.mov", "ffmpeg -v error %s %s -c:v mjpeg -c:a pcm_s16be mjpeg_pcm.mov" % (src_v, src_a)), + ("hevc.mp4", "ffmpeg -v error %s -c:v libx265 -x265-params log-level=none -tag:v hvc1 hevc.mp4" % src_v), + ("frag.mp4", "ffmpeg -v error -i h264_aac.mp4 -c copy -movflags frag_keyframe+empty_moov+default_base_moof frag.mp4"), + ("mp4box_frag.mp4", "MP4Box -quiet -frag 300 -out mp4box_frag.mp4 h264_aac.mp4 >/dev/null 2>&1"), + ("stz2_co64.mp4", "MP4Box -quiet -add h264_aac.mp4#video -add h264_aac.mp4#audio:stz2 -co64 -new stz2_co64.mp4 >/dev/null 2>&1"), + ("alac.m4a", "ffmpeg -v error %s -c:a alac alac.m4a" % src_a), + ] + cases = [] + for name, cmd in steps: + sh(ctx, cmd, d) + streams, packets = probe(ctx, name, d) + with open(os.path.join(d, name), "rb") as f: + data = f.read() + cases.append({"name": name, "data": data, "streams": streams, "packets": packets}) + # tags + cover + sh(ctx, "ffmpeg -v error -f lavfi -i color=red:size=8x8 -frames:v 1 -update 1 cover.png", d) + tags = {"title": "Test Title", "artist": "Some Artist", "album": "An Album", "date": "2024", + "genre": "Electronic", "comment": "a comment", "composer": "Composer X", "album_artist": "AA"} + meta = " ".join("-metadata %s='%s'" % (k, v) for k, v in tags.items()) + sh(ctx, "ffmpeg -v error %s -i cover.png -map 0 -map 1 -c:a aac -b:a 48k -c:v png -disposition:v attached_pic -t 1 %s -metadata track=3/12 -metadata disc=1/2 tagged.m4a" % (src_a, meta), d) + with open(os.path.join(d, "tagged.m4a"), "rb") as f: + tagged = f.read() + with open(os.path.join(d, "cover.png"), "rb") as f: + cover = f.read() + want = {"title": "Test Title", "artist": "Some Artist", "album": "An Album", "date": "2024", + "genre": "Electronic", "comment": "a comment", "composer": "Composer X", "albumartist": "AA", + "track": "3", "tracktotal": "12", "disc": "1", "disctotal": "2"} + # AVIF stills (libavif): plain and with alpha + avif = [] + sh(ctx, "ffmpeg -v error -f lavfi -i testsrc=size=40x24 -frames:v 1 still.png && " + "ffmpeg -v error -f lavfi -i 'testsrc=size=40x24,format=rgba,geq=r=r(X\\,Y):a=X*6' -frames:v 1 alpha.png", d) + for name, png, alpha in (("still.avif", "still.png", False), ("alpha.avif", "alpha.png", True)): + sh(ctx, "avifenc -q 60 -s 10 %s %s >/dev/null" % (png, name), d) + with open(os.path.join(d, name), "rb") as f: + avif.append({"name": name, "data": f.read(), "width": 40, "height": 24, "alpha": alpha}) + ctx.emit("isobmff", {"cases": cases, "tagged": {"data": tagged, "tags": want, "cover": len(cover)}, + "avif": avif}) + finally: + shutil.rmtree(d, ignore_errors=True) diff --git a/tools/fixtures/jpeg.py b/tools/fixtures/jpeg.py new file mode 100644 index 0000000..fd71fd1 --- /dev/null +++ b/tools/fixtures/jpeg.py @@ -0,0 +1,293 @@ +# JPEG fixtures (tools/fixtures.py), against libjpeg-turbo's cjpeg / djpeg / jpegtran (nix libjpeg_turbo) and Pillow. +# Ported from jpeg-luau tools/fixtures.py; the TMDB test photos are replaced by ImageMagick's built-in images. +# tests/gen/jpeg_dec.luau { { name, data, err?, refs = { { scale, width, height, crc } } | cmyk = rgb bytes } }: +# cjpeg encodes of synthetic and photo-like sources at every quality / sampling / +# progression / restart / colour setting, arithmetic-coded (sequential, progressive, +# restarts, grey, 12-bit), jpegtran transcodes, stripped DHT, odd sizes, 12-bit, CMYK / +# YCCK (Pillow); references = djpeg -dct int decodes at 1, 1/2, 1/4, 1/8 (CRC-32 of the +# RGBA8 pixels), files that must be refused (lossless). +# tests/gen/jpeg_enc.luau { { name, width, height, format, pixels, opts, want } }: raw sources and what cjpeg writes +# for the same settings (our encoder must produce the same bytes). +# tests/gen/jpeg_bench.luau 1024 x 768 baseline / progressive / arithmetic files for tools/bench.luau. +import os, shutil, subprocess, tempfile, zlib + +SOURCES = r''' +import os, random, sys +from PIL import Image, ImageDraw +out = sys.argv[1] +def synth(w, h, seed): + rnd = random.Random(seed) + im = Image.new("RGB", (w, h)) + px = im.load() + for y in range(h): + for x in range(w): + px[x, y] = ((x * 255) // max(1, w - 1), (y * 255) // max(1, h - 1), ((x + y) * 7) % 256) + d = ImageDraw.Draw(im) + for _ in range(6): + x0, y0 = rnd.randrange(w), rnd.randrange(h) + x1, y1 = x0 + rnd.randrange(1, w // 2 + 2), y0 + rnd.randrange(1, h // 2 + 2) + col = (rnd.randrange(256), rnd.randrange(256), rnd.randrange(256)) + if rnd.random() < 0.5: + d.ellipse([x0, y0, x1, y1], fill=col) + else: + d.line([x0, y0, x1, y1], fill=col, width=rnd.randrange(1, 4)) + for _ in range(w * h // 20): + x, y = rnd.randrange(w), rnd.randrange(h) + px[x, y] = (rnd.randrange(256), rnd.randrange(256), rnd.randrange(256)) + return im +synth(97, 71, 1).save(os.path.join(out, "synth.ppm")) +for w, h in ((1, 1), (7, 5), (17, 9), (33, 1), (1, 33), (16, 16)): + synth(w, h, w * 100 + h).save(os.path.join(out, "s%dx%d.ppm" % (w, h))) +photo = Image.open(os.path.join(out, "photo.ppm")).convert("RGB") +photo.convert("L").save(os.path.join(out, "photo.pgm")) +with open(os.path.join(out, "photo16.ppm"), "wb") as f: + f.write(b"P6\n160 120\n65535\n") + f.write(bytes(b for v in photo.tobytes() for b in ((v * 257) >> 8, (v * 257) & 255))) +cmyk = photo.convert("CMYK") +for name, kw in (("cmyk", {}), ("cmyk_prog", {"progressive": True})): + p = os.path.join(out, "photo_" + name + ".jpg") + cmyk.save(p, "JPEG", quality=90, **kw) + data = bytearray(open(p, "rb").read()) + i = data.find(b"Adobe") + assert i > 0 + data[i + 11] = 2 + open(os.path.join(out, "photo_" + name.replace("cmyk", "ycck") + ".jpg"), "wb").write(data) + for n in (name, name.replace("cmyk", "ycck")): + im = Image.open(os.path.join(out, "photo_" + n + ".jpg")) + raw = im.tobytes() + rgb = bytearray() + for k in range(0, len(raw), 4): + c, m, y, kk = raw[k:k + 4] + kk = 255 - kk + rgb += bytes((((255 - c) * kk + 127) // 255, ((255 - m) * kk + 127) // 255, ((255 - y) * kk + 127) // 255)) + open(os.path.join(out, "photo_" + n + ".ref"), "wb").write(rgb) +''' + +SCANS = { + "spectral": "0,1,2: 0-0, 0, 0;\n0: 1-5, 0, 0;\n0: 6-63, 0, 0;\n1: 1-63, 0, 0;\n2: 1-63, 0, 0;\n", + "deepsa": ( + "0,1,2: 0-0, 0, 2;\n0: 1-5, 0, 3;\n1: 1-63, 0, 1;\n2: 1-63, 0, 1;\n0: 6-63, 0, 3;\n" + "0: 1-63, 3, 2;\n0: 1-63, 2, 1;\n0: 1-63, 1, 0;\n1: 1-63, 1, 0;\n2: 1-63, 1, 0;\n" + "0,1,2: 0-0, 2, 1;\n0,1,2: 0-0, 1, 0;\n" + ), + "seqsplit": "0: 0-63, 0, 0;\n1: 0-63, 0, 0;\n2: 0-63, 0, 0;\n", + "dcsplit": "0: 0-0, 0, 0;\n1: 0-0, 0, 0;\n2: 0-0, 0, 0;\n0: 1-63, 0, 0;\n1: 1-63, 0, 0;\n2: 1-63, 0, 0;\n", +} +SAMPLINGS = {"444": "1x1", "422": "2x1", "420": "2x2", "411": "4x1", "440": "1x2"} + + +def parse_pnm(data): + """P5 / P6 -> w, h, RGB8 bytes (16-bit samples scaled as djpeg's 12-bit output)""" + fields, pos = [], 0 + while len(fields) < 4: + while data[pos:pos + 1].isspace(): + pos += 1 + if data[pos:pos + 1] == b"#": + while data[pos:pos + 1] != b"\n": + pos += 1 + continue + s = pos + while not data[pos:pos + 1].isspace(): + pos += 1 + fields.append(data[s:pos]) + pos += 1 + magic, w, h, mx = fields[0], int(fields[1]), int(fields[2]), int(fields[3]) + ch = 3 if magic == b"P6" else 1 + n = w * h * ch + if mx < 256: + px = data[pos:pos + n] + else: + raw = data[pos:pos + 2 * n] + px = bytes(((raw[2 * i] << 8 | raw[2 * i + 1]) * 255 + mx // 2) // mx for i in range(n)) + if ch == 1: + px = bytes(v for v in px for _ in range(3)) + return w, h, px + + +def rgba_crc(rgb): + out = bytearray(len(rgb) // 3 * 4) + out[0::4], out[1::4], out[2::4] = rgb[0::3], rgb[1::3], rgb[2::3] + out[3::4] = b"\xff" * (len(rgb) // 3) + return zlib.crc32(bytes(out)) + + +def generate(ctx): + bindir = os.path.dirname(ctx.nix("libjpeg_turbo", ["sh", "-c", "command -v cjpeg"]).decode().strip()) + magick = ctx.nix("imagemagick", ["sh", "-c", "command -v magick"]).decode().strip() + work = tempfile.mkdtemp(prefix="formats-jpeg-") + try: + _generate(ctx, bindir, magick, work) + finally: + shutil.rmtree(work, ignore_errors=True) + + +def _generate(ctx, bindir, magick, work): + def run(tool, *args): + exe = tool if os.path.isabs(tool) else os.path.join(bindir, tool) + r = subprocess.run([exe] + list(args), capture_output=True) + if r.returncode != 0: + raise SystemExit("fixtures/jpeg: %s %s failed: %s" % (tool, " ".join(args), r.stderr.decode())) + return r.stdout + + W = lambda n: os.path.join(work, n) + # photo-like sources: ImageMagick's built-in rose, and a plasma fractal + run(magick, "rose:", "-resize", "160x120!", W("photo.ppm")) + run(magick, "-size", "1024x768", "-seed", "7", "plasma:fractal", "-blur", "0x1", W("big.ppm")) + ctx.python(["pillow"], SOURCES.replace("sys.argv[1]", repr(work))) + for k, v in SCANS.items(): + with open(W(k + ".scans"), "w") as f: + f.write(v) + SRC = {"synth": W("synth.ppm"), "photo": W("photo.ppm"), "gray": W("photo.pgm"), "photo16": W("photo16.ppm")} + for w, h in ((1, 1), (7, 5), (17, 9), (33, 1), (1, 33), (16, 16)): + SRC["%dx%d" % (w, h)] = W("s%dx%d.ppm" % (w, h)) + + cases = [] # (name, path, scales | "cmyk", err) + + def cj(name, src, *args, scales=(1, 2, 4, 8), err=None): + out = W(name + ".jpg") + run("cjpeg", *args, "-outfile", out, SRC[src]) + cases.append((name, out, scales, err)) + + for q in (30, 90): + for sn, s in SAMPLINGS.items(): + cj("photo_q%d_%s" % (q, sn), "photo", "-quality", str(q), "-sample", s) + cj("photo_q%d_%s_prog" % (q, sn), "photo", "-quality", str(q), "-sample", s, "-progressive") + for sn, s in SAMPLINGS.items(): + cj("synth_q75_%s" % sn, "synth", "-quality", "75", "-sample", s) + cj("synth_q75_%s_prog" % sn, "synth", "-quality", "75", "-sample", s, "-progressive") + cj("photo_q100_420", "photo", "-quality", "100", "-sample", "2x2") + cj("photo_q100_420_prog", "photo", "-quality", "100", "-sample", "2x2", "-progressive") + cj("photo_q5_420", "photo", "-quality", "5", "-sample", "2x2") + cj("photo_q5_444_prog", "photo", "-quality", "5", "-sample", "1x1", "-progressive") + cj("photo_optimize", "photo", "-quality", "80", "-optimize") + cj("photo_s31", "photo", "-sample", "3x1,1x1,1x1") + cj("photo_s4242", "photo", "-sample", "4x2,1x1,1x1") + cj("photo_s222111", "photo", "-sample", "2x2,2x1,1x1") + cj("photo_s111222", "photo", "-sample", "1x1,2x2,2x2") + cj("photo_s1422", "photo", "-sample", "1x4,1x2,1x2", "-progressive") + cj("synth_s2222", "synth", "-sample", "2x2,2x2,2x2", "-scans", W("seqsplit.scans")) + cj("photo_rst1", "photo", "-sample", "2x2", "-restart", "1") + cj("photo_rst3b", "photo", "-sample", "2x2", "-restart", "3B") + cj("photo_rst1b_prog", "photo", "-sample", "2x2", "-restart", "1B", "-progressive") + cj("photo_rst2_prog444", "photo", "-sample", "1x1", "-restart", "2", "-progressive") + cj("photo_gray", "photo", "-grayscale") + cj("photo_gray_prog", "photo", "-grayscale", "-progressive") + cj("photo_gray_rst", "photo", "-grayscale", "-restart", "5B") + cj("photo_rgb", "photo", "-rgb") + cj("photo_rgb_prog", "photo", "-rgb", "-progressive") + for k in SCANS: + cj("photo_scans_" + k, "photo", "-sample", "2x2", "-scans", W(k + ".scans")) + cj("synth_scans_" + k, "synth", "-sample", "1x1", "-scans", W(k + ".scans")) + cj("photo_12bit_420", "photo16", "-precision", "12", "-sample", "2x2") + cj("photo_12bit_444_prog", "photo16", "-precision", "12", "-sample", "1x1", "-progressive") + cj("photo_12bit_gray", "photo16", "-precision", "12", "-grayscale") + for k in ("1x1", "7x5", "17x9", "33x1", "1x33", "16x16"): + cj("tiny_%s_420" % k, k, "-sample", "2x2") + cj("tiny_%s_422_prog" % k, k, "-sample", "2x1", "-progressive") + cj("tiny_%s_444" % k, k, "-sample", "1x1", "-quality", "95") + cj("tiny_%s_arith" % k, k, "-sample", "2x2", "-arithmetic") + # arithmetic coding + for sn in ("444", "420", "422"): + cj("photo_arith_%s" % sn, "photo", "-arithmetic", "-sample", SAMPLINGS[sn]) + cj("photo_arith_%s_prog" % sn, "photo", "-arithmetic", "-progressive", "-sample", SAMPLINGS[sn]) + cj("photo_arith_q5", "photo", "-arithmetic", "-quality", "5") + cj("photo_arith_q100_prog", "photo", "-arithmetic", "-progressive", "-quality", "100") + cj("photo_arith_rst", "photo", "-arithmetic", "-restart", "1") + cj("photo_arith_rst_prog", "photo", "-arithmetic", "-progressive", "-restart", "3B") + cj("photo_arith_gray", "photo", "-arithmetic", "-grayscale") + cj("photo_arith_gray_prog", "photo", "-arithmetic", "-grayscale", "-progressive") + cj("photo_arith_rgb", "photo", "-arithmetic", "-rgb") + cj("photo_arith_12bit", "photo16", "-arithmetic", "-precision", "12", "-sample", "2x2") + cj("photo_arith_12bit_prog", "photo16", "-arithmetic", "-precision", "12", "-progressive") + cj("synth_arith_deepsa", "synth", "-arithmetic", "-sample", "1x1", "-scans", W("deepsa.scans")) + cj("synth_arith_spectral", "synth", "-arithmetic", "-sample", "2x2", "-scans", W("spectral.scans")) + cj("synth_arith_seqsplit", "synth", "-arithmetic", "-sample", "2x2", "-scans", W("seqsplit.scans")) + # refused + cj("photo_lossless", "photo", "-lossless", "1", scales=(), err="lossless") + + base = W("photo_q90_420.jpg") + for name, args in (("tran_prog", ["-progressive"]), ("tran_rst", ["-restart", "2B"]), ("tran_optimize", ["-optimize"]), + ("tran_arith", ["-arithmetic"]), ("tran_arith_prog", ["-arithmetic", "-progressive"])): + out = W("photo_" + name + ".jpg") + run("jpegtran", *args, "-outfile", out, base) + cases.append(("photo_" + name, out, (1, 2, 4, 8), None)) + # an arithmetic file back to Huffman + out = W("photo_tran_unarith.jpg") + run("jpegtran", "-outfile", out, W("photo_arith_420.jpg")) + cases.append(("photo_tran_unarith", out, (1, 2, 4, 8), None)) + + # stripped DHT: the standard tables + data = open(base, "rb").read() + out, pos = bytearray(data[:2]), 2 + while pos < len(data): + m = data[pos + 1] + if m == 0xDA: + out += data[pos:] + break + ln = (data[pos + 2] << 8) | data[pos + 3] + if m != 0xC4: + out += data[pos:pos + 2 + ln] + pos += 2 + ln + open(W("photo_nodht.jpg"), "wb").write(bytes(out)) + cases.append(("photo_nodht", W("photo_nodht.jpg"), (1, 2, 4, 8), None)) + for n in ("cmyk", "cmyk_prog", "ycck", "ycck_prog"): + cases.append(("photo_" + n, W("photo_" + n + ".jpg"), "cmyk", None)) + + dec = [] + for name, path, scales, err in cases: + e = {"name": name, "data": open(path, "rb").read()} + if err: + e["err"] = err + if scales == "cmyk": + e["cmyk"] = open(path[:-4] + ".ref", "rb").read() + else: + refs = [] + for s in scales: + args = ["-dct", "int", "-pnm"] + (["-scale", "1/%d" % s] if s != 1 else []) + [path] + w, h, px = parse_pnm(run("djpeg", *args)) + refs.append({"scale": s, "width": w, "height": h, "crc": rgba_crc(px)}) + e["refs"] = refs + dec.append(e) + ctx.emit("jpeg_dec", dec) + + # encoder: cjpeg's bytes for the same settings + enc = [] + + def ce(name, src, fmt, opts, *args): + out = W("enc_" + name + ".jpg") + run("cjpeg", "-baseline", *args, "-outfile", out, SRC[src]) + w, h, px = parse_pnm(open(SRC[src], "rb").read()) + if fmt == "gray8": + px = px[0::3] + enc.append({"name": name, "width": w, "height": h, "format": fmt, "pixels": px, "opts": opts, + "want": open(out, "rb").read()}) + + for q in (10, 50, 75, 90, 100): + ce("photo_q%d_420" % q, "photo", "rgb8", {"quality": q}, "-quality", str(q), "-sample", "2x2") + for sn in ("444", "422", "420"): + ce("photo_%s" % sn, "photo", "rgb8", {"quality": 85, "subsampling": sn}, "-quality", "85", "-sample", SAMPLINGS[sn]) + ce("synth_%s" % sn, "synth", "rgb8", {"quality": 85, "subsampling": sn}, "-quality", "85", "-sample", SAMPLINGS[sn]) + ce("photo_%s_prog" % sn, "photo", "rgb8", {"quality": 85, "subsampling": sn, "progressive": True}, "-quality", "85", "-sample", SAMPLINGS[sn], "-progressive") + ce("synth_%s_prog" % sn, "synth", "rgb8", {"quality": 85, "subsampling": sn, "progressive": True}, "-quality", "85", "-sample", SAMPLINGS[sn], "-progressive") + ce("photo_%s_opt" % sn, "photo", "rgb8", {"quality": 85, "subsampling": sn, "optimize": True}, "-quality", "85", "-sample", SAMPLINGS[sn], "-optimize") + ce("photo_gray", "gray", "gray8", {"quality": 80}, "-quality", "80") + ce("photo_gray_prog", "gray", "gray8", {"quality": 80, "progressive": True}, "-quality", "80", "-progressive") + ce("photo_rgb_to_gray", "photo", "rgb8", {"quality": 80, "gray": True}, "-quality", "80", "-grayscale") + ce("photo_rst", "photo", "rgb8", {"quality": 75, "restart": 3}, "-quality", "75", "-sample", "2x2", "-restart", "3B") + ce("photo_rst_prog", "photo", "rgb8", {"quality": 75, "restart": 2, "progressive": True}, "-quality", "75", "-sample", "2x2", "-restart", "2B", "-progressive") + ce("photo_q100_prog444", "photo", "rgb8", {"quality": 100, "subsampling": "444", "progressive": True}, "-quality", "100", "-sample", "1x1", "-progressive") + for k in ("1x1", "7x5", "17x9", "33x1", "1x33", "16x16"): + ce("tiny_%s_420" % k, k, "rgb8", {"quality": 90}, "-quality", "90", "-sample", "2x2") + ce("tiny_%s_422_prog" % k, k, "rgb8", {"quality": 90, "subsampling": "422", "progressive": True}, "-quality", "90", "-sample", "2x1", "-progressive") + ctx.emit("jpeg_enc", enc) + + SRC["big"] = W("big.ppm") + bench = [] + for name, args in (("baseline 4:2:0", ["-sample", "2x2"]), ("progressive 4:2:0", ["-sample", "2x2", "-progressive"]), + ("arithmetic 4:2:0", ["-sample", "2x2", "-arithmetic"]), ("baseline 4:4:4", ["-sample", "1x1"])): + out = W("bench.jpg") + run("cjpeg", "-quality", "85", *args, "-outfile", out, SRC["big"]) + w, h, px = parse_pnm(run("djpeg", "-dct", "int", "-pnm", out)) + bench.append({"name": name, "width": w, "height": h, "data": open(out, "rb").read(), "crc": rgba_crc(px)}) + w, h, px = parse_pnm(open(SRC["big"], "rb").read()) + ctx.emit("jpeg_bench", {"files": bench, "width": w, "height": h, "rgb": px}) diff --git a/tools/fixtures/json.py b/tools/fixtures/json.py new file mode 100644 index 0000000..52776b6 --- /dev/null +++ b/tools/fixtures/json.py @@ -0,0 +1,91 @@ +# codecs/Json + data/json fixtures: the JSONTestSuite parsing corpus (nst/JSONTestSuite, pinned tarball through nix) +# with Python's json verdicts and canonical values, plus a random corpus written by Python's json.dumps in several +# styles (compact sorted, insertion order, indent 2, ensure_ascii) that the tests must parse and reproduce exactly. +# tests/gen/json_suite.luau { { name, expect = "y" | "n" | "i", data, canon? } } +# tests/gen/json_corpus.luau { { canon, compact, ordered, pretty, ascii } } +# tests/gen/json_bench.luau { text, compact } (~1 MB, indent 1; compact = sorted keys) +import importlib.util, json, os + +_spec = importlib.util.spec_from_file_location("_data_common", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_data_common.py")) +C = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(C) + +SUITE_URL = "https://github.com/nst/JSONTestSuite/archive/1ef36fa01286573e846ac449e8683f8833c5b26a.tar.gz" +SUITE_SHA = "0zp4gbpfxac9hfzlgjmqg70w8dhql6rbrkh8dhi3rn5aan0qqv5k" + + +def rand_value(rng, depth=0): + v = _rand_value(rng, depth) + if isinstance(v, float) and v.is_integer(): + return int(v) # Python writes 1.0, we write 1: keep integral numbers ints + return v + + +def _rand_value(rng, depth=0): + r = rng.random() + if depth > 4 or r < 0.45: + k = rng.randrange(9) + if k == 0: + return None + if k == 1: + return rng.random() < 0.5 + if k == 2: + return rng.randrange(-10 ** 15, 10 ** 15) + if k == 3: + return rng.randrange(-1000, 1000) + if k == 4: + return round(rng.uniform(-1e6, 1e6), rng.randrange(1, 8)) + if k == 5: + return rng.uniform(-1, 1) * 10 ** rng.randrange(-4, 14) + return rand_str(rng) + if r < 0.72: + return [rand_value(rng, depth + 1) for _ in range(rng.randrange(0, 7))] + d = {} + for _ in range(rng.randrange(0, 7)): + d[rand_str(rng)] = rand_value(rng, depth + 1) + return d + + +ALPH = "abcxyz ABC_019\"\\/\n\t\r\b\f\x01\x1f\x7féü中文\U0001f600
" + + +def rand_str(rng): + return "".join(rng.choice(ALPH) for _ in range(rng.randrange(0, 12))) + + +def generate(ctx): + root = C.fetch(SUITE_URL, SUITE_SHA) + d = os.path.join(root, "test_parsing") + cases = [] + for name in sorted(os.listdir(d)): + if not name.endswith(".json"): + continue + data = open(os.path.join(d, name), "rb").read() + c = {"name": name, "expect": name[0], "data": data} + try: + v = json.loads(data.decode("utf-8", "surrogatepass")) + c["canon"] = C.canon(v) + except Exception: + pass + cases.append(c) + ctx.emit("json_suite", cases) + + rng = ctx.rng(7) + corpus = [] + for _ in range(300): + v = rand_value(rng) + corpus.append({ + "canon": C.canon(v), + "compact": json.dumps(v, separators=(",", ":"), sort_keys=True, ensure_ascii=False), + "ordered": json.dumps(v, separators=(",", ":"), ensure_ascii=False), + "pretty": json.dumps(v, indent=2, sort_keys=True, ensure_ascii=False), + "ascii": json.dumps(v, separators=(",", ":"), sort_keys=True), + }) + ctx.emit("json_corpus", corpus) + + big = [rand_value(rng) for _ in range(3000)] + text = json.dumps(big, ensure_ascii=False, indent=1) + while len(text) < 1_000_000: + big = big + big + text = json.dumps(big, ensure_ascii=False, indent=1) + ctx.emit("json_bench", {"text": text, "compact": json.dumps(big, separators=(",", ":"), sort_keys=True, ensure_ascii=False)}) diff --git a/tools/fixtures/lzma.py b/tools/fixtures/lzma.py new file mode 100644 index 0000000..09be77f --- /dev/null +++ b/tools/fixtures/lzma.py @@ -0,0 +1,105 @@ +# LZMA / LZMA2 / xz fixtures (tools/fixtures.py): deterministic corpora compressed by liblzma (Python's lzma module and +# the xz CLI): every preset and -e, lc / lp / pb variants, raw LZMA1 / LZMA2, .lzma files with and without the size +# and end marker, xz with every check type, BCJ (x86, PowerPC, ARM, ARM-Thumb, SPARC, ARM64) and delta filters, +# multi-block (--block-size), multi-stream and stream padding. +# tests/gen/lzma.luau { corpora = { [name] = bytes }, cases = { { name, kind, corpus, data, props?, dict?, +# size? } } } kind: "raw" (LZMA1), "raw2" (LZMA2), "alone", "xz" +# tests/gen/lzma_bench.luau { size, crc, xz, alone } (a ~4 MB corpus at -6) +import lzma, os, random, subprocess, sys, zlib + + +def text_corpus(limit): + base = os.path.dirname(os.__file__) + out = bytearray() + for name in sorted(os.listdir(base)): + if name.endswith(".py"): + with open(os.path.join(base, name), "rb") as f: + out += f.read() + if len(out) >= limit: + break + return bytes(out[:limit]) + + +def binary_corpus(limit): + # machine code: a slice of the Python interpreter (x86-64 here; exercises the x86 BCJ filter) + with open(os.path.realpath(sys.executable), "rb") as f: + data = f.read() + if len(data) < limit: + lib = os.path.join(os.path.dirname(os.path.realpath(sys.executable)), "..", "lib") + for name in sorted(os.listdir(lib)): + p = os.path.join(lib, name) + if name.startswith("libpython") and os.path.isfile(p): + with open(p, "rb") as f: + data += f.read(limit) + break + return data[:limit] + + +def xz_cli(args, data): + return subprocess.run(["xz"] + args + ["-c"], input=data, capture_output=True, check=True).stdout + + +def generate(ctx): + rng = random.Random(7) + corpora = { + "empty": b"", + "one": b"a", + "text": text_corpus(150000), + "binary": binary_corpus(120000), + "random": rng.randbytes(20000), + "runs": b"abc" * 3000 + b"\0" * 30000 + bytes(range(256)) * 30 + b"z" * 300, + "words": b" ".join(rng.choice([b"lorem", b"ipsum", b"dolor", b"sit", b"amet", b"\xff\xfe", b"0123"]) for _ in range(20000)), + } + cases = [] + + def add(name, kind, corpus, data, **extra): + c = {"name": name, "kind": kind, "corpus": corpus, "data": data} + c.update(extra) + cases.append(c) + + for cname, data in corpora.items(): + small = cname in ("empty", "one", "random") + presets = [0, 6] if small else [0, 1, 3, 6, 9, 9 | lzma.PRESET_EXTREME] + for p in presets: + add("%s/xz-%d%s" % (cname, p & 15, "e" if p & lzma.PRESET_EXTREME else ""), "xz", cname, + lzma.compress(data, lzma.FORMAT_XZ, check=lzma.CHECK_CRC64, preset=p)) + for chk, cn in ((lzma.CHECK_NONE, "none"), (lzma.CHECK_CRC32, "crc32"), (lzma.CHECK_SHA256, "sha256")): + add("%s/xz-check-%s" % (cname, cn), "xz", cname, lzma.compress(data, lzma.FORMAT_XZ, check=chk, preset=2)) + # .lzma (alone): with a size (Python writes an end marker and no size; the CLI writes the same); raw streams + add("%s/alone" % cname, "alone", cname, lzma.compress(data, lzma.FORMAT_ALONE, preset=6)) + for lc, lp, pb in ((3, 0, 2), (0, 2, 0), (4, 0, 4), (1, 3, 1), (0, 4, 3)): + f = [{"id": lzma.FILTER_LZMA1, "preset": 6, "lc": lc, "lp": lp, "pb": pb, "dict_size": 1 << 20}] + raw = lzma.compress(data, lzma.FORMAT_RAW, filters=f) + add("%s/raw-lc%d-lp%d-pb%d" % (cname, lc, lp, pb), "raw", cname, raw, props=bytes([(pb * 5 + lp) * 9 + lc]), size=len(data)) + for lc, lp, pb in ((3, 0, 2), (0, 4, 4), (2, 2, 1)): + f = [{"id": lzma.FILTER_LZMA2, "preset": 6, "lc": lc, "lp": lp, "pb": pb}] + add("%s/raw2-lc%d-lp%d-pb%d" % (cname, lc, lp, pb), "raw2", cname, lzma.compress(data, lzma.FORMAT_RAW, filters=f)) + if not small: + for fid, fname in ((lzma.FILTER_X86, "x86"), (lzma.FILTER_POWERPC, "ppc"), (lzma.FILTER_ARM, "arm"), + (lzma.FILTER_ARMTHUMB, "armthumb"), (lzma.FILTER_SPARC, "sparc")): + f = [{"id": fid}, {"id": lzma.FILTER_LZMA2, "preset": 3}] + add("%s/xz-%s" % (cname, fname), "xz", cname, lzma.compress(data, lzma.FORMAT_XZ, filters=f)) + f = [{"id": lzma.FILTER_X86, "start_offset": 0x1000}, {"id": lzma.FILTER_LZMA2, "preset": 3}] + add("%s/xz-x86-start" % cname, "xz", cname, lzma.compress(data, lzma.FORMAT_XZ, filters=f)) + for dist in (1, 4, 256): + f = [{"id": lzma.FILTER_DELTA, "dist": dist}, {"id": lzma.FILTER_LZMA2, "preset": 3}] + add("%s/xz-delta%d" % (cname, dist), "xz", cname, lzma.compress(data, lzma.FORMAT_XZ, filters=f)) + add("%s/xz-cli-arm64" % cname, "xz", cname, xz_cli(["--arm64", "--lzma2=preset=3"], data)) + add("%s/xz-cli-blocks" % cname, "xz", cname, xz_cli(["-6", "--block-size=20000"], data)) + add("%s/xz-cli-x86-delta" % cname, "xz", cname, xz_cli(["--x86", "--delta=dist=2", "--lzma2=preset=1"], data)) + add("%s/alone-cli" % cname, "alone", cname, xz_cli(["--format=lzma", "-3"], data)) + # multi-stream + stream padding + corpora["multi"] = corpora["text"][:40000] + corpora["runs"] + b"" + corpora["one"] + multi = (lzma.compress(corpora["text"][:40000], lzma.FORMAT_XZ, preset=1) + b"\0" * 8 + + lzma.compress(corpora["runs"], lzma.FORMAT_XZ, check=lzma.CHECK_CRC32) + + lzma.compress(b"", lzma.FORMAT_XZ) + lzma.compress(b"a", lzma.FORMAT_XZ, check=lzma.CHECK_NONE) + b"\0" * 4) + add("multi/xz-streams", "xz", "multi", multi) + + ctx.emit("lzma", {"corpora": corpora, "cases": cases}) + + # real text and machine code, little long-range repetition + bench = text_corpus(2_000_000) + binary_corpus(1_000_000) + bench = bench[:3_000_000] + ctx.emit("lzma_bench", {"size": len(bench), "crc": zlib.crc32(bench), + "xz": lzma.compress(bench, lzma.FORMAT_XZ, preset=6), + "alone": lzma.compress(bench, lzma.FORMAT_ALONE, preset=6)}) diff --git a/tools/fixtures/lzw.py b/tools/fixtures/lzw.py new file mode 100644 index 0000000..6cb37f9 --- /dev/null +++ b/tools/fixtures/lzw.py @@ -0,0 +1,70 @@ +# LZW fixtures (tools/fixtures.py): code streams written by reference encoders, with the data they encode. +# tests/gen/lzw.luau { gif = { { name, min, codes, data } }, tiff = { { name, codes, data } } } +# gif: Pillow's GIF writer (its own LZW), the image data sub-blocks joined; data = the palette indexes +# tiff: libtiff's LZW (Pillow compression="tiff_lzw"), one strip; data = the raw 8-bit samples +import struct + +CODE = r''' +import io, random, struct, sys +from PIL import Image +rng = random.Random(7) +def img(w, h, kind, ncol): + px = bytearray() + for y in range(h): + for x in range(w): + if kind == "noise": + px.append(rng.randrange(ncol)) + elif kind == "flat": + px.append(3 % ncol) + else: + px.append(((x // 3) ^ (y // 5)) % ncol if rng.random() < 0.97 else rng.randrange(ncol)) + return bytes(px) +out = [] +for (w, h, kind, ncol) in ((1, 1, "noise", 2), (16, 16, "noise", 2), (64, 48, "pattern", 4), (64, 48, "noise", 16), + (300, 200, "pattern", 256), (300, 200, "noise", 256), (256, 200, "flat", 256), (97, 3, "noise", 128)): + data = img(w, h, kind, ncol) + im = Image.frombytes("P", (w, h), data) + im.putpalette(bytes(range(256)) * 3) + b = io.BytesIO(); im.save(b, "GIF", optimize=False, interlace=False); g = b.getvalue() + # walk to the image descriptor + p = 13 + (3 << ((g[10] & 7) + 1) if g[10] & 0x80 else 0) + while g[p] != 0x2C: + p += 2 + while g[p]: p += g[p] + 1 + p += 1 + flags = g[p + 9]; p += 10 + if flags & 0x80: p += 3 << ((flags & 7) + 1) + mn = g[p]; p += 1; codes = bytearray() + while g[p]: codes += g[p + 1:p + 1 + g[p]]; p += g[p] + 1 + # Pillow may reduce the palette: decode its own image back for the indexes + back = Image.open(io.BytesIO(g)); back.load() + out.append(("gif", "%dx%d-%s-%d" % (w, h, kind, ncol), mn, bytes(codes), back.tobytes())) + t = io.BytesIO() + Image.frombytes("L", (w, h), data).save(t, "TIFF", compression="tiff_lzw", rowsperstrip=h) + tb = t.getvalue() + le = tb[:2] == b"II"; E = "<" if le else ">" + ifd = struct.unpack(E + "I", tb[4:8])[0]; n = struct.unpack(E + "H", tb[ifd:ifd + 2])[0] + tags = {} + for i in range(n): + tag, typ, cnt, val = struct.unpack(E + "HHII", tb[ifd + 2 + i * 12: ifd + 14 + i * 12]) + if typ == 3 and cnt == 1: + val = struct.unpack(E + "H", tb[ifd + 10 + i * 12: ifd + 12 + i * 12])[0] + tags[tag] = (val, cnt) + assert tags[259][0] == 5 and tags[273][1] == 1, "one LZW strip" + off, cnt = tags[273][0], tags[279][0] + out.append(("tiff", "%dx%d-%s-%d" % (w, h, kind, ncol), 8, tb[off:off + cnt], data)) +for kind, name, mn, codes, data in out: + sys.stdout.buffer.write(struct.pack("<4sB", kind.ljust(4).encode(), len(name)) + name.encode() + struct.pack("<BII", mn, len(codes), len(data)) + codes + data) +''' + + +def generate(ctx): + raw = ctx.python(["pillow"], CODE) + gif, tiff, p = [], [], 0 + while p < len(raw): + kind, nl = struct.unpack("<4sB", raw[p:p + 5]); p += 5 + name = raw[p:p + nl].decode(); p += nl + mn, cl, dl = struct.unpack("<BII", raw[p:p + 9]); p += 9 + codes, data = raw[p:p + cl], raw[p + cl:p + cl + dl]; p += cl + dl + (gif if kind.strip() == b"gif" else tiff).append({"name": name, "min": mn, "codes": codes, "data": data}) + ctx.emit("lzw", {"gif": gif, "tiff": tiff}) diff --git a/tools/fixtures/m4a.py b/tools/fixtures/m4a.py new file mode 100644 index 0000000..8ffe43e --- /dev/null +++ b/tools/fixtures/m4a.py @@ -0,0 +1,198 @@ +# M4A / AAC / ALAC / CAF fixtures (tools/fixtures.py). Reference tools through nix: ffmpeg (AAC + ALAC encoders and +# decoders, the CAF muxer), fdkaac (Fraunhofer's encoder: plain and HE-AAC), MP4Box (-info on our files). +# tests/gen/m4a_alac.luau ALAC in M4A / CAF from ffmpeg: { name, data, container, channels, rate, bits, frames, +# crc } where crc is the CRC-32 of the source integers as little-endian int32 +# tests/gen/m4a_aac.luau AAC from ffmpeg / faac (M4A, ADTS, CAF): { name, data, container, channels, rate, frames, +# ref } with ref = ffmpeg's float decode (f32le) of the file +# tests/gen/m4a_he.luau HE-AAC / HE-AACv2 from fdkaac: { name, data, rate (the SBR output rate), ps } +# tests/gen/m4a_ours.luau our writers' files (tools/fixtures/_m4a_encode.luau over tests/audio/_encode_cases.luau) +# checked by ffmpeg: { name, crc (of our bytes), ffmpeg (decodes bit-exactly), frames, +# tags (ffprobe's view), mp4box (MP4Box -info exit status 0) } +import importlib.util, json, math, os, shutil, struct, subprocess, tempfile, zlib + +# the shared signal module, loaded by path (tools/fixtures/ must not go on sys.path: xml.py there would shadow xml) +_spec = importlib.util.spec_from_file_location("_m4a_signal", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_m4a_signal.py")) +_sig = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(_sig) +signal, pack, wav = _sig.signal, _sig.pack, _sig.wav + +INPUTS = ["src/Formats/audio/m4a", "src/Formats/audio/caf", "src/Formats/codecs/Alac", "src/Formats/containers/IsoBmff", + "tests/audio/_signal.luau", "tests/audio/_encode_cases.luau", "tools/fixtures/_m4a_encode.luau", + "tools/fixtures/_m4a_signal.py"] +PKGS = ["ffmpeg", "fdk-aac-encoder", "gpac"] + + +def run(ctx, cmd, cwd): + return ctx.nix(PKGS, ["sh", "-c", "cd '%s' && %s" % (cwd, cmd)]) + + +def crc_ints(ints): + return zlib.crc32(struct.pack("<%di" % len(ints), *ints)) + + +def music(frames, channels, rate, seed): + """a float test signal for the lossy codecs: tones with vibrato, a chord, noise bursts and clicks (transients)""" + rng = __import__("random").Random(seed) + out = [] + for i in range(frames): + t = i / rate + for c in range(channels): + v = 0.25 * math.sin(2 * math.pi * (220 * (c + 1)) * t + 3 * math.sin(2 * math.pi * 5 * t)) + v += 0.12 * math.sin(2 * math.pi * 660 * t) + 0.08 * math.sin(2 * math.pi * 1320.5 * t + c) + v += 0.05 * math.sin(2 * math.pi * (5000 + 300 * c) * t) + if (i // (rate // 8)) % 3 == 1: + v += 0.15 * (rng.random() * 2 - 1) + if i % (rate // 3) < 40: + v += 0.6 * (1 - (i % (rate // 3)) / 40) * (1 if (i // 7) % 2 else -1) + out.append(max(-32768, min(32767, int(round(v * 20000))))) + return out + + +def adts_to_caf(adts): + frames, p = [], 0 + while p + 7 <= len(adts): + b1, b2, b3, b4, b5 = adts[p + 1], adts[p + 2], adts[p + 3], adts[p + 4], adts[p + 5] + hs = 7 if b1 & 1 else 9 + size = ((b3 & 3) << 11) | (b4 << 3) | (b5 >> 5) + frames.append(adts[p + hs:p + size]) + sfi, ch, aot = (b2 >> 2) & 15, ((b2 & 1) << 2) | (b3 >> 6), (b2 >> 6) + 1 + p += size + rate = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350][sfi] + asc = struct.pack(">H", (aot << 11) | (sfi << 7) | (ch << 3)) + dsi = b"\x05" + bytes([len(asc)]) + asc + dcd = b"\x04" + bytes([13 + len(dsi)]) + bytes([0x40, 0x15, 0, 0, 0]) + struct.pack(">II", 0, 0) + dsi + esd = b"\x03" + bytes([3 + len(dcd) + 3]) + b"\x00\x00\x00" + dcd + b"\x06\x01\x02" + + def ber(n): + out = [n & 127] + n >>= 7 + while n: + out.insert(0, 128 | (n & 127)) + n >>= 7 + return bytes(out) + + def chunk(t, body): + return t + struct.pack(">q", len(body)) + body + + desc = struct.pack(">d4sIIIII", rate, b"aac ", 2, 0, 1024, ch, 0) + pakt = struct.pack(">qqii", len(frames), len(frames) * 1024, 0, 0) + b"".join(ber(len(f)) for f in frames) + data = b"\x00\x00\x00\x00" + b"".join(frames) + return b"caff\x00\x01\x00\x00" + chunk(b"desc", desc) + chunk(b"kuki", b"\x00\x00\x00\x00" + esd) + chunk(b"pakt", pakt) + chunk(b"data", data) + + +def generate(ctx): + d = tempfile.mkdtemp(prefix="m4a-fx-") + try: + # --- ALAC from ffmpeg: lossless, the decode must equal the source integers + alac = [] + for name, frames, ch, rate, bits, container in ( + ("alac16_stereo.m4a", 10000, 2, 44100, 16, "m4a"), + ("alac16_mono.m4a", 4097, 1, 8000, 16, "m4a"), + ("alac24_stereo.m4a", 6000, 2, 96000, 24, "m4a"), + ("alac16_6ch.m4a", 5000, 6, 48000, 16, "m4a"), + ("alac16_stereo.caf", 9000, 2, 44100, 16, "caf"), + ): + ints = signal(frames, ch, bits, 11 + frames) + with open(os.path.join(d, "in.wav"), "wb") as f: + f.write(wav(ints, ch, rate, bits)) + fmt = "-sample_fmt s32p" if bits == 24 else "" + run(ctx, "ffmpeg -v error -y -i in.wav -c:a alac %s %s" % (fmt, name), d) + with open(os.path.join(d, name), "rb") as f: + data = f.read() + alac.append({"name": name, "data": data, "container": container, "channels": ch, "rate": rate, + "bits": bits, "frames": frames, "crc": crc_ints(ints)}) + ctx.emit("m4a_alac", alac) + + # --- AAC from ffmpeg / faac: our decode against ffmpeg's float decode + aac = [] + specs = ( + # name, frames, channels, rate, encoder command (in.wav -> name) + ("aac_stereo_128k.m4a", 60000, 2, 44100, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 128k -aac_pns 0 %s"), + ("aac_mono_22k.m4a", 30000, 1, 22050, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 48k %s"), + ("aac_51_48k.m4a", 30000, 6, 48000, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 256k %s"), + ("aac_tools_40k.m4a", 50000, 2, 44100, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 40k -aac_pns 1 -aac_is 1 -aac_ms 1 -aac_tns 1 %s"), + ("aac_8k_mono.m4a", 12000, 1, 8000, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 16k %s"), + ("aac_96k.m4a", 30000, 2, 96000, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 192k %s"), + ("aac_stereo.aac", 40000, 2, 44100, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 96k -aac_pns 0 -f adts %s"), + ("fdk_stereo.aac", 40000, 2, 44100, "fdkaac -S -b 96000 -f 2 -o %s in.wav"), + ("fdk_mono_32k.aac", 20000, 1, 32000, "fdkaac -S -b 48000 -f 2 -o %s in.wav"), + ("fdk_stereo.m4a", 40000, 2, 48000, "fdkaac -S -b 128000 -o %s in.wav"), + ("aac_stereo.caf", 30000, 2, 44100, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 96k -f adts %s.adts"), + ) + for name, frames, ch, rate, cmd in specs: + ints = music(frames, ch, rate, frames + ch) + with open(os.path.join(d, "in.wav"), "wb") as f: + f.write(wav(ints, ch, rate, 16)) + run(ctx, cmd % name, d) + if name.endswith(".caf"): + # ffmpeg cannot write AAC in CAF: wrap its ADTS frames ourselves (desc, kuki esds, pakt, data) + with open(os.path.join(d, name + ".adts"), "rb") as f: + adts = f.read() + with open(os.path.join(d, name), "wb") as f: + f.write(adts_to_caf(adts)) + with open(os.path.join(d, name), "rb") as f: + data = f.read() + ref = run(ctx, "ffmpeg -v error -i %s -f f32le -c:a pcm_f32le -" % name, d) + container = "caf" if name.endswith(".caf") else ("adts" if name.endswith(".aac") else "m4a") + aac.append({"name": name, "data": data, "container": container, "channels": ch, "rate": rate, + "frames": len(ref) // (4 * ch), "ref": ref}) + ctx.emit("m4a_aac", aac) + # HE-AAC (SBR) and HE-AACv2 (SBR + PS) from fdkaac: we decode the AAC-LC core at the core rate + he = [] + for name, frames, ch, rate, prof, br in (("he_aac.m4a", 48000, 2, 44100, 5, 48000), ("he_aac_v2.m4a", 48000, 2, 44100, 29, 32000), ("he_aac.aac", 48000, 2, 44100, 5, 48000)): + ints = music(frames, ch, rate, 99) + with open(os.path.join(d, "in.wav"), "wb") as f: + f.write(wav(ints, ch, rate, 16)) + run(ctx, "fdkaac -S -p %d -b %d %s -o %s in.wav" % (prof, br, "-f 2" if name.endswith(".aac") else "", name), d) + with open(os.path.join(d, name), "rb") as f: + he.append({"name": name, "data": f.read(), "rate": rate, "ps": prof == 29}) + ctx.emit("m4a_he", he) + + # --- our writers, checked by ffmpeg / ffprobe / MP4Box + luau = os.environ.get("LUAU") or shutil.which("luau") + if luau: + out = subprocess.run([luau, "tools/fixtures/_m4a_encode.luau"], capture_output=True, check=True, cwd=ctx.root).stdout + else: + out = ctx.nix("luau", ["luau", os.path.join(ctx.root, "tools/fixtures/_m4a_encode.luau")]) + ours = [] + meta = { + # name -> frames, channels, bits, seed (tests/audio/_encode_cases.luau) + "ours_alac16_stereo": (4096 * 3 + 1234, 2, 16, 1), "ours_alac16_mono": (5000, 1, 16, 2), + "ours_alac24_stereo": (9000, 2, 24, 3), "ours_alac16_6ch": (4500, 6, 16, 4), + "ours_alac20_stereo": (3000, 2, 20, 5), "ours_caf_alac16": (7000, 2, 16, 6), + "ours_caf_pcm16": (3000, 2, 16, 7), "ours_caf_pcm24": (2000, 1, 24, 8), + } + for line in out.decode().split("\n"): + if not line.strip(): + continue + name, hx = line.split(" ", 1) + if hx.startswith("ERROR"): + raise RuntimeError("m4a fixtures: our encoder failed on %s: %s" % (name, hx)) + data = bytes.fromhex(hx) + ext = "caf" if "caf" in name else "m4a" + path = name + "." + ext + with open(os.path.join(d, path), "wb") as f: + f.write(data) + frames, ch, bits, seed = meta[name] + ints = signal(frames, ch, bits, seed) + wide = bits > 16 + want = pack([v << (32 - bits) for v in ints] if wide else ints, 32 if wide else 16) + got = run(ctx, "ffmpeg -v error -i %s -f %s -" % (path, "s32le" if wide else "s16le"), d) + fbytes = (4 if wide else 2) * ch + # ffmpeg's CAF reader drops the pakt remainder from a partial last ALAC packet (also on its own files): + # accept its output when it is an exact prefix of ours + ok = got == want or (ext == "caf" and len(got) > 0 and want.startswith(got)) + probe = json.loads(run(ctx, "ffprobe -v error -show_format -show_streams -of json %s" % path, d)) + tags = {k.lower(): v for k, v in probe["format"].get("tags", {}).items()} + mp4box = True + if ext == "m4a": + try: + run(ctx, "MP4Box -info %s >/dev/null 2>&1" % path, d) + except subprocess.CalledProcessError: + mp4box = False + ours.append({"name": name, "crc": zlib.crc32(data), "ffmpeg": ok, "frames": len(got) // fbytes, + "tags": tags, "mp4box": mp4box, + "codec": probe["streams"][0]["codec_name"]}) + ctx.emit("m4a_ours", ours) + finally: + shutil.rmtree(d, ignore_errors=True) diff --git a/tools/fixtures/msgpack.py b/tools/fixtures/msgpack.py new file mode 100644 index 0000000..d395813 --- /dev/null +++ b/tools/fixtures/msgpack.py @@ -0,0 +1,94 @@ +# data/msgpack fixtures: random values packed by Python's msgpack (through nix): every integer width, floats, +# str / bin of every length class, nested arrays / maps (int and str keys), nil / bools, timestamps (all three +# widths) and other ext types; with the canonical form of msgpack's own unpacking. +# tests/gen/msgpack.luau { safe = { { data, canon } }, wide = { { data, canon, canonStr } } } +# safe: no integers past 2^53, no integral floats: our decode + encode must give the same bytes +# wide: 64-bit integers too (canon = as doubles, canonStr = exact text via bigInts = "string") +import importlib.util, os, pickle + +_spec = importlib.util.spec_from_file_location("_data_common", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_data_common.py")) +C = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(C) + +BODY = r''' +import msgpack, pickle, random, sys, datetime +rng = random.Random(5) +def rint(wide): + k = rng.randrange(8) + lim = [2**5, 2**7, 2**8, 2**15, 2**16, 2**31, 2**32, 2**53 - 1][k] + if wide and rng.random() < 0.4: + lim = rng.choice([2**63 - 1, 2**64 - 1]) + v = rng.randrange(0, lim + 1) + if lim == 2**63 - 1 and rng.random() < 0.5: + v = -v - 1 + return v + v = rng.randrange(-lim, lim + 1) + return v +def rstr(): + n = rng.choice([0, 1, 5, 31, 32, 200, 255, 256, 300]) + alph = "abé中\U0001f600 \n\x00" + return "".join(rng.choice(alph) for _ in range(n))[:n] +def rval(d, wide): + r = rng.random() + if d > 3 or r < 0.5: + k = rng.randrange(9) + if k == 0: return None + if k == 1: return rng.random() < 0.5 + if k in (2, 3): return rint(wide) + if k == 4: + f = rng.uniform(-1e6, 1e6) * 10 ** rng.randrange(-5, 5) + return f if not f.is_integer() else f + 0.5 + if k == 5: return rstr() + if k == 6: return rng.randbytes(rng.choice([0, 3, 255, 256])) + if k == 7: + sec = rng.choice([rng.randrange(0, 2**32), rng.randrange(0, 2**34), rng.randrange(-2**35, 2**37)]) + us = rng.choice([0, rng.randrange(1000000)]) + return msgpack.Timestamp(sec, us * 1000) + return msgpack.ExtType(rng.randrange(0, 128), rng.randbytes(rng.choice([1, 2, 4, 8, 16, 3, 300]))) + if r < 0.75: + return [rval(d + 1, wide) for _ in range(rng.choice([0, 1, 3, 15, 16, 20] if d < 2 else [0, 1, 3]))] + m = {} + for _ in range(rng.choice([0, 1, 3, 15, 16, 17] if d < 2 else [0, 1, 3])): + key = rint(False) if rng.random() < 0.3 else "".join(rng.choice("abc\u00e9") for _ in range(rng.randrange(6))) + m[key] = rval(d + 1, wide) + return m +def conv(v): + if isinstance(v, msgpack.Timestamp): + return v.to_datetime() + if isinstance(v, msgpack.ExtType): + return ["ext", v.code, v.data] + if isinstance(v, list): + return [conv(x) for x in v] + if isinstance(v, dict): + return {k: conv(x) for k, x in v.items()} + return v +def cstr(v): + if isinstance(v, int) and not isinstance(v, bool) and abs(v) >= 2**53: + return str(v) + if isinstance(v, list): + return [cstr(x) for x in v] + if isinstance(v, dict): + return {k: cstr(x) for k, x in v.items()} + return v +out = {"safe": [], "wide": []} +# the 32-bit length forms, once each +for v in ["x" * 70000, b"y" * 70000, list(range(70000)), {i: i for i in range(70000)}]: + data = msgpack.packb(v, use_bin_type=True) + out["safe"].append({"data": data, "canon": canon(msgpack.unpackb(data, strict_map_key=False))}) +for i in range(250): + v = rval(0, False) + data = msgpack.packb(v, use_bin_type=True) + back = msgpack.unpackb(data, raw=False, strict_map_key=False) + out["safe"].append({"data": data, "canon": canon(conv(back))}) +for i in range(150): + v = rval(0, True) + data = msgpack.packb(v, use_bin_type=True) + back = conv(msgpack.unpackb(data, raw=False, strict_map_key=False)) + out["wide"].append({"data": data, "canon": canon(back), "canonStr": canon(cstr(back))}) +sys.stdout.buffer.write(pickle.dumps(out, protocol=4)) +''' + + +def generate(ctx): + out = pickle.loads(C.python(ctx, ["msgpack"], BODY)) + ctx.emit("msgpack", out) diff --git a/tools/fixtures/obj.py b/tools/fixtures/obj.py new file mode 100644 index 0000000..5b66708 --- /dev/null +++ b/tools/fixtures/obj.py @@ -0,0 +1,257 @@ +# OBJ fixtures (tools/fixtures.py): OBJ / MTL files written here (materials, textures, objects and groups, n-gons, +# negative indices, vertex colours, continuation lines, comments, lines and points, a concave polygon) and files +# exported by assimp (from generated PLY meshes), with reference values from assimp (`assimp info`: meshes, materials, +# vertices, faces, bounds) and trimesh (area, triangle count, bounds). +# tests/gen/obj_cases.luau { name, data, files = { name -> bytes }, assimp = {...}, trimesh = {...}, polygonArea? } +# tests/gen/obj_xcheck.luau our encoder's output for every case (tools/fixtures/_obj_encode.luau), read back by assimp +# and trimesh: { name, assimp, trimesh, want = the original's values } +import importlib.util, math, os, struct + +INPUTS = ["src/Formats/model/obj", "tools/fixtures/_model_ref.py", "tools/fixtures/_obj_encode.luau"] + + +def ref_module(ctx): + spec = importlib.util.spec_from_file_location("_model_ref", os.path.join(ctx.root, "tools", "fixtures", "_model_ref.py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def png_1x1(): + import zlib + def ch(t, d): + return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d)) + return b"\x89PNG\r\n\x1a\n" + ch(b"IHDR", struct.pack(">IIBBBBB", 1, 1, 8, 6, 0, 0, 0)) + ch(b"IDAT", zlib.compress(b"\0\xff\0\0\xff")) + ch(b"IEND", b"") + + +def fmt(v): + return "%.6g" % v + + +CUBE = """# a cube: one object, two groups, two materials, a textured quad +mtllib cube.mtl +o Cube +v 0 0 0 +v 1 0 0 +v 1 1 0 +v 0 1 0 +v 0 0 1 +v 1 0 1 +v 1 1 1 +v 0 1 1 +vt 0 0 +vt 1 0 +vt 1 1 +vt 0 1 +vn 0 0 1 +g top +usemtl red +s 1 +f 5/1/1 6/2/1 7/3/1 8/4/1 +g bottom +usemtl blue +f 1 4 3 2 +f 1 2 6 5 +f 2 3 7 6 +f 3 4 8 7 +f 4 1 5 8 +""" + +CUBE_MTL = """# materials +newmtl red +Ka 0.1 0.1 0.1 +Kd 1 0 0 +Ks 0.5 0.5 0.5 +Ns 50 +illum 2 +map_Kd -s 2 2 1 -o 0.5 0 0 textures/tex.png +map_Bump -bm 0.5 normal.png +newmtl blue +Kd 0 0 1 +d 0.5 +Pr 0.25 +Pm 1 +Ke 0.1 0.2 0.3 +""" + + +def sphere(rng, rings, segs, colors=False): + vs, fs = [], [] + for i in range(rings - 1): # no poles: assimp turns degenerate triangles into lines + th = math.pi * (i + 1) / rings + for j in range(segs): + ph = 2 * math.pi * j / segs + vs.append((math.sin(th) * math.cos(ph), math.cos(th), math.sin(th) * math.sin(ph))) + for i in range(rings - 2): + for j in range(segs): + a, b = i * segs + j, i * segs + (j + 1) % segs + c, d = a + segs, b + segs + fs.append((a, c, d, b)) + return vs, fs + + +def random_obj(rng): + vs, fs = sphere(rng, 6, 9) + lines = ["# random sphere: quads, triangles, pentagons, negative indices, vertex colours, continuations"] + for v in vs: + lines.append("v %s %s %s %s %s %s" % (fmt(v[0]), fmt(v[1]), fmt(v[2]), fmt(rng.random()), fmt(rng.random()), fmt(rng.random()))) + for k in range(len(vs)): + lines.append("vt %s %s" % (fmt(rng.random()), fmt(rng.random()))) + lines.append("vn 0 1 0") + lines.append("vn 1 0 0") + lines.append("g sphere") + n = len(vs) + for i, f in enumerate(fs): + if i % 7 == 0: + # negative (relative) indices + lines.append("f " + " ".join("%d/%d" % (v - n, v - n) for v in f)) + elif i % 7 == 1: + lines.append("f " + " ".join("%d//%d" % (v + 1, 1 + i % 2) for v in f)) + elif i % 7 == 2: + lines.append("f %d/%d/1 %d/%d/2 \\\n %d/%d/1 %d/%d/2" % (f[0] + 1, f[0] + 1, f[1] + 1, f[1] + 1, f[2] + 1, f[2] + 1, f[3] + 1, f[3] + 1)) + elif i % 7 == 3: + lines.append("f %d %d %d" % (f[0] + 1, f[1] + 1, f[2] + 1)) + lines.append("f %d %d %d" % (f[0] + 1, f[2] + 1, f[3] + 1)) + else: + lines.append("f " + " ".join("%d/%d" % (v + 1, v + 1) for v in f)) + # a convex pentagon and a hexagon + base = len(vs) + for k in range(5): + lines.append("v %s %s 2" % (fmt(math.cos(2 * math.pi * k / 5)), fmt(math.sin(2 * math.pi * k / 5)))) + lines.append("g pentagon") + lines.append("f " + " ".join(str(base + k + 1) for k in range(5))) + return "\n".join(lines) + "\n" + + +def concave(): + # an L-shaped hexagon (area 3) and a U-shaped octagon (area 5) in the xz plane, as n-gons + L = [(0, 0), (2, 0), (2, 1), (1, 1), (1, 2), (0, 2)] + U = [(3, 0), (6, 0), (6, 2), (5, 2), (5, 1), (4, 1), (4, 2), (3, 2)] + lines = ["o shapes"] + for x, z in L + U: + lines.append("v %d 0 %d" % (x, z)) + lines.append("f " + " ".join(str(k + 1) for k in range(len(L)))) + lines.append("f " + " ".join(str(len(L) + k + 1) for k in range(len(U)))) + area = sum(abs(sum(p[i][0] * p[(i + 1) % len(p)][1] - p[(i + 1) % len(p)][0] * p[i][1] for i in range(len(p)))) / 2 for p in (L, U)) + return "\n".join(lines) + "\n", area + + +def lines_points(): + return """o wire +v 0 0 0 +v 1 0 0 +v 1 1 0 +v 0 1 0 +l 1 2 3 4 1 +p 1 3 +f 1 2 3 +""" + + +def ply_torus(rng, R=2.0, r=0.5, a=24, b=12): + vs, fs = [], [] + for i in range(a): + for j in range(b): + u, v = 2 * math.pi * i / a, 2 * math.pi * j / b + vs.append(((R + r * math.cos(v)) * math.cos(u), r * math.sin(v), (R + r * math.cos(v)) * math.sin(u))) + for i in range(a): + for j in range(b): + p, q = i * b + j, ((i + 1) % a) * b + j + p2, q2 = i * b + (j + 1) % b, ((i + 1) % a) * b + (j + 1) % b + fs.append((p, p2, q2, q)) + head = "ply\nformat ascii 1.0\nelement vertex %d\nproperty float x\nproperty float y\nproperty float z\nelement face %d\nproperty list uchar int vertex_indices\nend_header\n" % (len(vs), len(fs)) + body = "".join("%r %r %r\n" % v for v in vs) + "".join("4 %d %d %d %d\n" % f for f in fs) + return (head + body).encode() + + +def fan_area(text): + # the area of every face fan-triangulated (an exact reference in double precision) + text = text.replace("\\\n", " ") + V, A = [], 0.0 + for l in text.split("\n"): + w = l.split() + if not w: + continue + if w[0] == "v": + V.append([float(x) for x in w[1:4]]) + elif w[0] == "f": + idx = [] + for c in w[1:]: + v = int(c.split("/")[0]) + idx.append(v - 1 if v > 0 else len(V) + v) + for k in range(1, len(idx) - 1): + a, b, c = V[idx[0]], V[idx[k]], V[idx[k + 1]] + e1 = [b[i] - a[i] for i in range(3)] + e2 = [c[i] - a[i] for i in range(3)] + x, y, z = e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0] + A += math.sqrt(x * x + y * y + z * z) / 2 + return A + + +def generate(ctx): + M = ref_module(ctx) + rng = ctx.rng(11) + tmp = M.tempdir() + cases = [] + + def add(name, data, files=None, **extra): + path = os.path.join(tmp, name) + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "wb") as f: + f.write(data) + for fn, fd in (files or {}).items(): + p = os.path.join(tmp, fn) + os.makedirs(os.path.dirname(p), exist_ok=True) + with open(p, "wb") as f: + f.write(fd) + c = {"name": name, "data": data, "files": files or {}, "path": path, "fanArea": fan_area(data.decode())} + c.update(extra) + cases.append(c) + + png = png_1x1() + add("cube.obj", CUBE.encode(), {"cube.mtl": CUBE_MTL.encode(), "textures/tex.png": png, "normal.png": png}) + # assimp joins mixed-attribute corners differently (136 vertices where the file has 101 distinct v/vt/vn): no + # vertex count check for this one + # and trimesh gets its area wrong (12.60 for 12.52: mixed index forms?): only the exact fan area here + add("random.obj", random_obj(rng).encode(), noVertexCount=True, noTrimesh=True) + text, area = concave() + add("concave.obj", text.encode(), polygonArea=area) + add("wire.obj", lines_points().encode(), noTrimesh=True) + # assimp's OBJ exporter, from a PLY torus + ply = os.path.join(tmp, "torus.ply") + with open(ply, "wb") as f: + f.write(ply_torus(rng)) + out = os.path.join(tmp, "torus_assimp.obj") + ctx.nix("assimp", ["assimp", "export", ply, out]) + files = {} + if os.path.exists(out[:-4] + ".mtl"): + files["torus_assimp.mtl"] = open(out[:-4] + ".mtl", "rb").read() + add("torus_assimp.obj", open(out, "rb").read(), files) + + paths = [c["path"] for c in cases] + infos = M.assimp_info(ctx, paths) + tm = M.trimesh_metrics(ctx, [c["path"] for c in cases if not c.get("noTrimesh")]) + k = 0 + for c, info in zip(cases, infos): + c["assimp"] = info + if not c.get("noTrimesh"): + c["trimesh"] = tm[k] + k += 1 + for c in cases: + del c["path"] + ctx.emit("obj_cases", cases) + + # the reference tools read our encoder's output (decode -> encode in Luau, then assimp / trimesh) + ours = M.luau_encode(ctx, "tools/fixtures/_obj_encode.luau") + xtmp = M.tempdir() + names = [] + for name, data in sorted(ours.items()): + p = os.path.join(xtmp, name) + os.makedirs(os.path.dirname(p), exist_ok=True) + with open(p, "wb") as f: + f.write(data) + if name.endswith(".obj"): + names.append(name) + xinfos = M.assimp_info(ctx, [os.path.join(xtmp, n) for n in names]) + xtm = M.trimesh_metrics(ctx, [os.path.join(xtmp, n) for n in names]) + ctx.emit("obj_xcheck", [{"name": n, "assimp": a, "trimesh": t} for n, a, t in zip(names, xinfos, xtm)]) diff --git a/tools/fixtures/off.py b/tools/fixtures/off.py new file mode 100644 index 0000000..a44c626 --- /dev/null +++ b/tools/fixtures/off.py @@ -0,0 +1,343 @@ +# OFF fixtures (tools/fixtures.py). +# tests/gen/off_scenes.luau scenes for the encoder (STCNOFF mesh, polygons under a TRS node, a float-colour point +# cloud, polygons with face colours) with the expected file content, computed here +# tests/gen/off.luau cases: OFF files written by trimesh and by hand here (COFF with integer / float colours, +# RGB / RGBA, NOFF, STOFF, STCNOFF, face colours of both kinds, colormap indices, comments +# everywhere, counts on the header line, CRLF and tabs, n-gons, a point cloud), with the +# values they were written from (positions cross-checked with trimesh's OFF reader); +# `ours`: our encoder's output (luau CLI: tools/fixtures/_off_encode.luau) read back by +# trimesh, assimp and a small reader here, as verdicts +import json, math, os, shutil, struct, subprocess, tempfile, zlib + +INPUTS = ["src/Formats/model/off", "tools/fixtures/_off_reference.py", "tools/fixtures/_off_encode.luau"] + + +def f32(x): + return struct.unpack("<f", struct.pack("<f", x))[0] + + +def pack(fmt, vals): + return struct.pack("<%d%s" % (len(vals), fmt), *vals) + + +def crc(b): + return zlib.crc32(b) + + +def fan(faces): + tris, fot = [], [] + for i, f in enumerate(faces): + for k in range(1, len(f) - 1): + tris += [f[0], f[k], f[k + 1]] + fot.append(i) + return tris, fot + + +def random_faces(rng, nv, nf, sizes=(3, 4, 5, 6)): + out = [] + for _ in range(nf): + s = rng.choice(sizes) + out.append(rng.sample(range(nv), s)) + return out + + +def colour_tokens(rng, kind, comps): + if kind == "int": + vals = [rng.randrange(256) for _ in range(comps)] + return [str(v) for v in vals], vals + vals = [round(rng.random(), 6) for _ in range(comps)] + return ["%.6f" % v for v in vals], vals + + +def colour_bytes(kind, vals_list, comps_list): + """the expected COLOR_0 / faceColors bytes (unorm8 x4 or f32 x4; missing alpha / colour = full)""" + out = b"" + for vals, comps in zip(vals_list, comps_list): + if kind == "int": + v = list(vals) + [255] * (4 - len(vals)) + out += bytes(v) + else: + v = list(vals) + [1.0] * (4 - len(vals)) + out += pack("f", v) + return out + + +def make_case(rng, name, nv, faces, normals=False, st=False, vcol=None, fcol=None, style=None): + """an OFF file and the values it holds. vcol / fcol = (kind "int" | "float" | "map", comps)""" + style = style or {} + kw = ("ST" if st else "") + ("C" if vcol else "") + ("N" if normals else "") + "OFF" + nl = "\r\n" if style.get("crlf") else "\n" + sep = "\t" if style.get("tabs") else " " + lines = [] + if style.get("comments"): + lines.append("# a comment before the keyword") + if style.get("inline"): + lines.append("%s %d %d 0" % (kw, nv, len(faces))) + else: + lines.append(kw + (" # keyword" if style.get("comments") else "")) + if style.get("comments"): + lines += ["", "# counts next"] + lines.append("%d %d %d" % (nv, len(faces), 0)) + pos, nrm, tex, vc_vals, vc_comps = [], [], [], [], [] + for i in range(nv): + p = [f32(rng.uniform(-10, 10)) for _ in range(3)] + pos += p + toks = [repr(c) for c in p] + if normals: + v = [rng.uniform(-1, 1) for _ in range(3)] + ln = math.sqrt(sum(c * c for c in v)) + n = [f32(c / ln) for c in v] + nrm += n + toks += [repr(c) for c in n] + if vcol: + comps = vcol[1] if vcol[1] != "mixed" else rng.choice((3, 4)) + ct, cv = colour_tokens(rng, vcol[0], comps) + toks += ct + vc_vals.append(cv) + vc_comps.append(comps) + if st: + t = [f32(rng.random()) for _ in range(2)] + tex += t + toks += [repr(c) for c in t] + line = sep.join(toks) + if style.get("comments") and i % 3 == 0: + line += " # vertex %d" % i + lines.append(line) + if style.get("comments") and i == 1: + lines.append("") + lines.append(" # an indented comment line") + fc_vals, fc_comps, any_fc, colormap = [], [], False, False + for i, f in enumerate(faces): + toks = [str(len(f))] + [str(x) for x in f] + if fcol and not (fcol[1] == "some" and i % 3 == 1): + if fcol[0] == "map": + toks.append(str(rng.randrange(16))) + colormap = True + fc_vals.append([]) + fc_comps.append(0) + else: + comps = 4 if fcol[1] in (4, "some") else 3 + ct, cv = colour_tokens(rng, fcol[0], comps) + toks += ct + fc_vals.append(cv) + fc_comps.append(comps) + any_fc = True + else: + fc_vals.append([]) + fc_comps.append(0) + lines.append(sep.join(toks)) + data = (nl.join(lines) + nl).encode() + exp = {"name": name, "data": data, "keyword": kw, "vertices": nv, "faces": len(faces), "pos_crc": crc(pack("f", pos))} + if normals: + exp["nrm_crc"] = crc(pack("f", nrm)) + if st: + exp["tex_crc"] = crc(pack("f", tex)) + if vcol: + exp["color"] = {"type": "unorm8" if vcol[0] == "int" else "f32", "crc": crc(colour_bytes(vcol[0], vc_vals, vc_comps))} + if any_fc: + exp["faceColors"] = {"type": "unorm8" if fcol[0] == "int" else "f32", "crc": crc(colour_bytes(fcol[0], fc_vals, fc_comps))} + if colormap: + exp["colormap"] = True + tris, fot = fan(faces) + exp["allTri"] = all(len(f) == 3 for f in faces) + exp["tris"] = len(tris) // 3 + exp["tri_crc"] = crc(pack("I", tris)) + exp["fot_crc"] = crc(pack("I", fot)) + exp["corners_crc"] = crc(pack("I", [c for f in faces for c in f])) + exp["sizes_crc"] = crc(pack("I", [len(f) for f in faces])) + return exp + + +def handmade(rng): + cases = [] + cases.append(make_case(rng, "coff-int.off", 30, random_faces(rng, 30, 20), vcol=("int", 4), fcol=("int", 3), style={"comments": True})) + cases.append(make_case(rng, "coff-float-rgb.off", 25, random_faces(rng, 25, 12, (3, 4)), vcol=("float", 3), fcol=("float", 4))) + cases.append(make_case(rng, "coff-mixed-alpha.off", 12, random_faces(rng, 12, 6, (3,)), vcol=("int", "mixed"))) + cases.append(make_case(rng, "noff.off", 20, random_faces(rng, 20, 10, (3,)), normals=True)) + cases.append(make_case(rng, "stoff.off", 16, random_faces(rng, 16, 9), st=True, style={"tabs": True})) + cases.append(make_case(rng, "stcnoff.off", 18, random_faces(rng, 18, 11), normals=True, st=True, vcol=("int", 4), fcol=("int", "some"))) + cases.append(make_case(rng, "inline-crlf.off", 10, random_faces(rng, 10, 5, (3, 4)), style={"inline": True, "crlf": True})) + cases.append(make_case(rng, "colormap.off", 9, random_faces(rng, 9, 4, (3, 4)), fcol=("map", 1))) + cases.append(make_case(rng, "points.off", 40, [])) + cases.append(make_case(rng, "big-ngon.off", 300, [list(range(300)), list(range(0, 300, 7))])) + return cases + + +# --- encoder scenes +def mat_trs(node): + x, y, z, w = node.get("rotation", [0, 0, 0, 1]) + sx, sy, sz = node.get("scale", [1, 1, 1]) + tx, ty, tz = node.get("translation", [0, 0, 0]) + r = [ + [1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)], + [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)], + [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)], + ] + return [[r[i][0] * sx, r[i][1] * sy, r[i][2] * sz, (tx, ty, tz)[i]] for i in range(3)] + + +def scenes(rng): + out = [] + n = 12 + pos = [f32(rng.uniform(-5, 5)) for _ in range(n * 3)] + nrm = [f32(rng.uniform(-1, 1)) for _ in range(n * 3)] + col = [rng.randrange(256) for _ in range(n * 4)] + tex = [f32(rng.random()) for _ in range(n * 2)] + idx = [rng.randrange(n) for _ in range(30)] + faces = [idx[i:i + 3] for i in range(0, 30, 3)] + vlines = [pos[i * 3:i * 3 + 3] + nrm[i * 3:i * 3 + 3] + col[i * 4:i * 4 + 4] + tex[i * 2:i * 2 + 2] for i in range(n)] + out.append({"name": "mesh", "nodes": [{"mesh": 1}], "roots": [1], "meshes": [{"prims": [{ + "mode": "triangles", "count": n, "indices": pack("I", idx), + "attrs": {"POSITION": ["f32", 3, pack("f", pos)], "NORMAL": ["f32", 3, pack("f", nrm)], "COLOR_0": ["unorm8", 4, bytes(col)], + "TEXCOORD_0": ["f32", 2, pack("f", tex)]}}]}], + "encodings": {"default": {"keyword": "STCNOFF", "vertices": vlines, "faces": faces}, + "plain": {"keyword": "OFF", "vertices": [v[:3] for v in vlines], "faces": faces}}}) + pv = [0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 2, 0, 0, 3, 0.5, 0, 2.5, 1.5, 0.2, 1.5, 1.2, 0.1, 0, 0, 1] + q = [rng.uniform(-1, 1) for _ in range(4)] + ln = math.sqrt(sum(c * c for c in q)) + node = {"mesh": 1, "translation": [1, 2, 3], "rotation": [c / ln for c in q], "scale": [2, 0.5, 1.5]} + m = mat_trs(node) + w = [[m[i][0] * pv[k * 3] + m[i][1] * pv[k * 3 + 1] + m[i][2] * pv[k * 3 + 2] + m[i][3] for i in range(3)] for k in range(9)] + pf = [[0, 1, 2, 3], [1, 4, 5, 6, 7, 2], [0, 3, 8]] + out.append({"name": "polys", "nodes": [node], "roots": [1], "meshes": [{"prims": [{ + "mode": "polygons", "count": 9, "indices": pack("I", [c for f in pf for c in f]), "faces": pack("I", [len(f) for f in pf]), + "attrs": {"POSITION": ["f32", 3, pack("f", pv)]}}]}], + "encodings": {"default": {"keyword": "OFF", "vertices": w, "faces": pf, "tol": 1e-5}}}) + n = 20 + pos = [f32(rng.uniform(-50, 50)) for _ in range(n * 3)] + col = [f32(rng.random()) for _ in range(n * 4)] + out.append({"name": "cloud", "nodes": [{"mesh": 1}], "roots": [1], "meshes": [{"prims": [{ + "mode": "points", "count": n, "attrs": {"POSITION": ["f32", 3, pack("f", pos)], "COLOR_0": ["f32", 4, pack("f", col)]}}]}], + "encodings": {"default": {"keyword": "COFF", "vertices": [pos[i * 3:i * 3 + 3] + col[i * 4:i * 4 + 4] for i in range(n)], "faces": []}}}) + # face colours on planar polygons (assimp triangulates non-planar ones its own way) + pf = [[0, 1, 2, 3], [1, 4, 5, 6, 7, 2], [0, 3, 8]] + pos = [f32(v) for v in pv] + fc = [rng.randrange(256) for _ in range(12)] + out.append({"name": "facecolors", "nodes": [{"mesh": 1}], "roots": [1], "meshes": [{"prims": [{ + "mode": "polygons", "count": 9, "indices": pack("I", [c for f in pf for c in f]), "faces": pack("I", [len(f) for f in pf]), + "attrs": {"POSITION": ["f32", 3, pack("f", pos)]}, "faceColors": bytes(fc)}]}], + "encodings": {"default": {"keyword": "OFF", "vertices": [pos[i * 3:i * 3 + 3] for i in range(9)], "faces": pf, + "faceColors": [fc[i * 4:i * 4 + 4] for i in range(3)]}}}) + return out + + +def parse_off(text): + """a small OFF reader for checking our output: keyword, vertex rows (numbers), faces, face colour rows""" + rows = [] + for line in text.split("\n"): + line = line.split("#", 1)[0].strip() + if line: + rows.append(line.split()) + kw = rows[0][0] + nv, nf = int(rows[1][0]), int(rows[1][1]) + verts = [[float(x) for x in r] for r in rows[2:2 + nv]] + faces, fcols = [], [] + for r in rows[2 + nv:2 + nv + nf]: + k = int(r[0]) + faces.append([int(x) for x in r[1:1 + k]]) + fcols.append([float(x) for x in r[1 + k:]]) + return kw, verts, faces, fcols, len(rows) == 2 + nv + nf + + +def check_ours(text, want): + kw, verts, faces, fcols, exact_rows = parse_off(text) + if kw != want["keyword"]: + return False, "keyword %s, want %s" % (kw, want["keyword"]) + if not exact_rows: + return False, "extra or missing rows" + if len(verts) != len(want["vertices"]): + return False, "vertex count" + tol = want.get("tol", 0) + for got, exp in zip(verts, want["vertices"]): + if len(got) != len(exp): + return False, "vertex row length %d, want %d" % (len(got), len(exp)) + for g, e in zip(got, exp): + if (abs(f32(g) - f32(e)) > tol * max(1, abs(e))) if tol else f32(g) != f32(e): + return False, "vertex value %r, want %r" % (g, e) + if faces != want["faces"]: + return False, "faces differ" + if "faceColors" in want: + if [list(map(int, c)) for c in fcols] != want["faceColors"]: + return False, "face colours differ" + elif any(fcols): + return False, "unexpected face colours" + return True, "%d vertices, %d faces" % (len(verts), len(faces)) + + +def luau_cmd(): + exe = shutil.which("luau") + return [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"] + + +def assimp_faces(ctx, path): + txt = ctx.nix("assimp", ["assimp", "info", path]).decode(errors="replace") + for line in txt.split("\n"): + if line.startswith("Faces:"): + return int(line.split()[1]) + return None + + +def generate(ctx): + rng = ctx.rng(53) + tmp = tempfile.mkdtemp(prefix="formats-off-") + try: + _generate(ctx, rng, tmp) + finally: + shutil.rmtree(tmp, ignore_errors=True) + + +def _generate(ctx, rng, tmp): + sc = scenes(rng) + ctx.emit("off_scenes", sc) + cases = handmade(rng) + for c in cases: + with open(os.path.join(tmp, c["name"]), "wb") as f: + f.write(c["data"]) + make = ["trimesh-ico.off", "trimesh-capsule.off"] + enc = subprocess.run(luau_cmd() + [os.path.join(ctx.root, "tools", "fixtures", "_off_encode.luau")], capture_output=True, check=True, cwd=ctx.root).stdout.decode() + ours = [] + byname = {s["name"]: s for s in sc} + for line in enc.split("\n"): + if not line.strip(): + continue + label, hexdata = line.split(" ", 1) + scene_name, encoding = label.split("/") + fn = "ours-%s-%s.off" % (scene_name, encoding) + data = bytes.fromhex(hexdata.strip()) + with open(os.path.join(tmp, fn), "wb") as f: + f.write(data) + ours.append((label, fn, data, byname[scene_name]["encodings"][encoding])) + names = [c["name"] for c in cases if c["vertices"] > 0] + make + [o[1] for o in ours] + code = open(os.path.join(ctx.root, "tools", "fixtures", "_off_reference.py")).read() + try: + ref = json.loads(ctx.python(["trimesh", "numpy"], code, input=json.dumps({"dir": tmp, "make": make, "read": names}).encode())) + except subprocess.CalledProcessError as e: + raise RuntimeError("off reference: " + e.stderr.decode(errors="replace")[-3000:]) + # trimesh agrees with the values the files were written from + for c in cases: + r = ref.get(c["name"]) + if r: + assert r["vertices"] == c["vertices"] and r["pos_crc"] == c["pos_crc"], c["name"] + for name in make: + with open(os.path.join(tmp, name), "rb") as f: + data = f.read() + r = ref[name] + tris = [x for f in r["faces"] for x in f] + cases.append({"name": name, "data": data, "keyword": "OFF", "vertices": r["vertices"], "faces": r["tris"], "pos_crc": r["pos_crc"], + "allTri": True, "tris": r["tris"], "tri_crc": crc(pack("I", tris)), "corners_crc": crc(pack("I", tris)), + "sizes_crc": crc(pack("I", [3] * r["tris"]))}) + verdicts = [] + for label, fn, data, want in ours: + ok, detail = check_ours(data.decode(), want) + r = ref.get(fn) + if ok and r and not want.get("tol"): + exp = pack("f", [c for v in want["vertices"] for c in v[:3]]) + if r["pos_crc"] != crc(exp): + ok, detail = False, "trimesh reads other positions" + if ok and want["faces"]: + got = assimp_faces(ctx, os.path.join(tmp, fn)) + exp_f = sum(len(f) - 2 for f in want["faces"]) + if got != exp_f: + ok, detail = False, "assimp reads %s faces, want %d" % (got, exp_f) + verdicts.append({"name": label, "ok": ok, "detail": detail}) + ctx.emit("off", {"cases": cases, "ours": verdicts}) diff --git a/tools/fixtures/opus_celt.py b/tools/fixtures/opus_celt.py new file mode 100644 index 0000000..5db280b --- /dev/null +++ b/tools/fixtures/opus_celt.py @@ -0,0 +1,48 @@ +# The CELT encoder reference check (tools/fixtures.py): runs tools/fixtures/_opus_encode.luau (our encoder over +# tests/audio/_opus_cases.luau), then the reference tools through nix: opusdec --float (libopus), opusinfo (stream +# structure), ffmpeg (an independent Ogg / Opus reader). +# tests/gen/opus_celt.luau { { name, crc (of our bytes), opusdec (f32le 48 kHz decode), opusinfo (exit 0), +# ffmpeg (decoded), ffmpegFrames, comments (opusinfo's user comments) } } +import os, re, shutil, subprocess, tempfile, zlib + +INPUTS = ["src/Formats/audio/opus", "src/Formats/codecs/Mdct", "src/Formats/containers/Ogg", + "tests/audio/_opus_cases.luau", "tools/fixtures/_opus_encode.luau"] + + +def generate(ctx): + luau = os.environ.get("LUAU") or shutil.which("luau") + script = os.path.join(ctx.root, "tools/fixtures/_opus_encode.luau") + if luau: + out = subprocess.run([luau, script], capture_output=True, check=True, cwd=ctx.root).stdout + else: + out = ctx.nix("luau", ["luau", script]) + d = tempfile.mkdtemp(prefix="opus-celt-fx-") + try: + cases = [] + for line in out.decode().split("\n"): + if not line.strip(): + continue + name, hx = line.split(" ", 1) + if hx.startswith("ERROR"): + raise RuntimeError("opus_celt fixtures: our encoder failed on %s: %s" % (name, hx)) + data = bytes.fromhex(hx) + path = os.path.join(d, name + ".opus") + with open(path, "wb") as f: + f.write(data) + raw = os.path.join(d, name + ".f32") + ctx.nix("opus-tools", ["opusdec", "--quiet", "--float", "--rate", "48000", path, raw]) + with open(raw, "rb") as f: + pcm = f.read() + info = subprocess.run(["nix", "shell", "nixpkgs#opus-tools", "-c", "opusinfo", path], capture_output=True) + text = info.stdout.decode(errors="replace") + comments = {} + for m in re.finditer(r"^\s*([A-Za-z]+)=(.*)$", text, re.M): + comments[m.group(1).lower()] = m.group(2) + ok = info.returncode == 0 and "WARNING" not in text and "ERROR" not in text.upper().replace("ERRORS", "") + ff = subprocess.run(["nix", "shell", "nixpkgs#ffmpeg", "-c", "ffmpeg", "-v", "error", "-i", path, "-f", "f32le", "-ac", "1", "-"], capture_output=True) + cases.append({"name": name, "crc": zlib.crc32(data), "opusdec": pcm, "opusinfo": ok, + "ffmpeg": ff.returncode == 0 and len(ff.stderr) == 0, "ffmpegFrames": len(ff.stdout) // 4, + "comments": comments}) + ctx.emit("opus_celt", cases) + finally: + shutil.rmtree(d, ignore_errors=True) diff --git a/tools/fixtures/playlist.py b/tools/fixtures/playlist.py new file mode 100644 index 0000000..4af9918 --- /dev/null +++ b/tools/fixtures/playlist.py @@ -0,0 +1,66 @@ +# Playlist fixtures (tools/fixtures.py): playlist/m3u, playlist/pls, playlist/xspf, codecs/Url, codecs/Text. +# tests/gen/playlist_url.luau random relative references resolved by Python's urllib.parse.urljoin (RFC 3986) +# tests/gen/playlist_cp1252.luau every Windows-1252 byte decoded by Python's cp1252 codec (undefined bytes: U+FFFD) +# tests/gen/playlist_cases.luau playlists written here (M3U8 with EXTINF, PLS via configparser-style lines, XSPF via +# xml.etree.ElementTree) with the entries they hold: { url, title?, duration? } +import random, urllib.parse, xml.etree.ElementTree as ET + +BASES = ["http://a/b/c/d;p?q", "https://host.example/lists/m.m3u8", "http://h/x/", "https://cdn.example/a/b/c/list.pls", + "http://a"] +SEGS = ["g", "h", "..", ".", "music", "a b", "x.mp3", "s;p", "%41", "ü"] + + +def ref(rng): + parts = [rng.choice(SEGS) for _ in range(rng.randrange(1, 5))] + r = "/".join(parts) + k = rng.randrange(6) + if k == 0: + r = "/" + r + elif k == 1: + r = "./" + r + if rng.random() < 0.2: + r += "?y=" + rng.choice(SEGS) + if rng.random() < 0.15: + r += "#" + rng.choice(["s", "f/../x"]) + return r + + +def generate(ctx): + rng = random.Random(8) + cases = [] + for _ in range(400): + base = rng.choice(BASES) + r = ref(rng) + if " " in r or "ü" in r or (base == "http://a" and r.startswith(".")): + continue # raw spaces / UTF-8 are encoded first by the playlist code; urljoin keeps a leading "." here + cases.append([r, base, urllib.parse.urljoin(base, r)]) + ctx.emit("playlist_url", cases) + ctx.emit("playlist_cp1252", [[b, bytes([b]).decode("cp1252", errors="replace")] for b in range(0x80, 0x100)]) + + out = [] + for n in range(12): + ents = [] + for i in range(rng.randrange(1, 9)): + e = {"url": "http://media.example/%d/track%d.mp3" % (n, i)} + if rng.random() < 0.8: + e["title"] = rng.choice(["Song %d" % i, "Björk – Jóga", "A, B & C", "x <y> \"z\""]) + if rng.random() < 0.7: + e["duration"] = rng.randrange(1, 600) + ents.append(e) + m3u = "#EXTM3U\n" + "".join(("#EXTINF:%d,%s\n" % (e.get("duration", -1), e.get("title", "")) if ("title" in e or "duration" in e) else "") + e["url"] + "\n" for e in ents) + pls = "[playlist]\n" + "".join("File%d=%s\n" % (i + 1, e["url"]) + ("Title%d=%s\n" % (i + 1, e["title"]) if "title" in e else "") + ("Length%d=%d\n" % (i + 1, e.get("duration", -1))) for i, e in enumerate(ents)) + "NumberOfEntries=%d\nVersion=2\n" % len(ents) + root = ET.Element("playlist", {"version": "1", "xmlns": "http://xspf.org/ns/0/"}) + ET.SubElement(root, "title").text = "List %d" % n + tl = ET.SubElement(root, "trackList") + for e in ents: + t = ET.SubElement(tl, "track") + ET.SubElement(t, "location").text = e["url"] + if "title" in e: + ET.SubElement(t, "title").text = e["title"] + if "duration" in e: + ET.SubElement(t, "duration").text = str(e["duration"] * 1000) + xspf = ET.tostring(root, encoding="UTF-8", xml_declaration=True) + expect = [{k: v for k, v in e.items()} for e in ents] + # M3U loses a title when there is no EXTINF text; PLS keeps only what it wrote + out.append({"name": "list%d" % n, "m3u": m3u, "pls": pls, "xspf": xspf, "title": "List %d" % n, "entries": expect}) + ctx.emit("playlist_cases", out) diff --git a/tools/fixtures/plist.py b/tools/fixtures/plist.py new file mode 100644 index 0000000..f89f1dc --- /dev/null +++ b/tools/fixtures/plist.py @@ -0,0 +1,83 @@ +# data/plist fixtures: random values written by Python's plistlib as XML (insertion order) and as binary, with the +# canonical form of plistlib's own reading (aware UTC datetimes; UIDs as ["uid", n]). +# tests/gen/plist.luau { { xml, binary, canon } } (our XML writer must reproduce xml byte for byte) +# + wide = { { binary, canon } } (UIDs, 64-bit integers: binary only) +import datetime, importlib.util, os, plistlib + +_spec = importlib.util.spec_from_file_location("_data_common", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_data_common.py")) +C = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(C) + + +def rval(rng, d, wide): + r = rng.random() + if d > 3 or r < 0.5: + k = rng.randrange(8) + if k == 0: + return rng.random() < 0.5 + if k == 1: + return rng.randrange(-2 ** 31, 2 ** 31) + if k == 2: + return rng.choice([rng.randrange(-2 ** 63, 2 ** 63), rng.randrange(0, 2 ** 64)]) if wide else rng.randrange(-2 ** 53, 2 ** 53) + if k == 3: + f = rng.uniform(-1e6, 1e6) * 10 ** rng.randrange(-5, 5) + return f if not f.is_integer() else f + 0.5 + if k == 4: + return "".join(rng.choice("ab <>&\"'é中\U0001f600\n\t") for _ in range(rng.randrange(0, 12))) + if k == 5: + return rng.randbytes(rng.choice([0, 1, 2, 3, 40, 57, 58, 200])) + if k == 6: + return datetime.datetime.fromtimestamp(rng.randrange(-2 ** 31, 2 ** 33), datetime.timezone.utc) + return plistlib.UID(rng.randrange(0, 2 ** 32)) if wide else "x" + if r < 0.75: + return [rval(rng, d + 1, wide) for _ in range(rng.randrange(0, 6))] + return {"".join(rng.choice("abcé <&") for _ in range(rng.randrange(0, 6))): rval(rng, d + 1, wide) for _ in range(rng.randrange(0, 6))} + + +def conv(v): + if isinstance(v, plistlib.UID): + return ["uid", v.data] + if isinstance(v, list): + return [conv(x) for x in v] + if isinstance(v, dict): + return {k: conv(x) for k, x in v.items()} + return v + + +def generate(ctx): + rng = ctx.rng(21) + cases = [] + for i in range(200): + v = rval(rng, 0, False) + if not isinstance(v, (list, dict)) and rng.random() < 0.5: + v = {"root": v} + xml = plistlib.dumps(v, fmt=plistlib.FMT_XML, sort_keys=False, aware_datetime=True) + binary = plistlib.dumps(v, fmt=plistlib.FMT_BINARY, sort_keys=False, aware_datetime=True) + back = plistlib.loads(xml, aware_datetime=True) + assert C.canon(conv(plistlib.loads(binary, aware_datetime=True))) == C.canon(conv(back)) + cases.append({"xml": xml, "binary": binary, "canon": C.canon(conv(back))}) + wide = [] + for i in range(80): + v = [rval(rng, 1, True) for _ in range(4)] + binary = plistlib.dumps(v, fmt=plistlib.FMT_BINARY, aware_datetime=True) + wide.append({"binary": binary, "canon": C.canon(conv(plistlib.loads(binary, aware_datetime=True)))}) + # a hand-written XML plist with whitespace, comments, hex integers, odd reals, a bare value root + extra = b"""<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> +<plist version="1.0"> + <!-- comment --> + <dict> + <key>hex</key> <integer>0x1F</integer> + <key>neg</key> <integer>-5</integer> + <key>real</key> <real> 2.5e3 </real> + <key>data</key> <data> + AAEC + AwQ= + </data> + <key>empty</key> <string/> + <key>date</key> <date>2001-01-01T00:00:00Z</date> + </dict> +</plist> +""" + ctx.emit("plist", {"cases": cases, "wide": wide, "extra": extra, + "extraCanon": C.canon(plistlib.loads(extra, aware_datetime=True))}) diff --git a/tools/fixtures/ply.py b/tools/fixtures/ply.py new file mode 100644 index 0000000..327f05b --- /dev/null +++ b/tools/fixtures/ply.py @@ -0,0 +1,192 @@ +# PLY fixtures (tools/fixtures.py). +# tests/gen/ply_scenes.luau scenes for the encoder (an indexed mesh with every attribute kind and custom properties, +# polygons under a TRS node, a float-colour point cloud, two meshes merged, a mirrored +# polygon) with the expected vertex properties (names, types, values) and faces, computed +# here +# tests/gen/ply.luau cases: PLY files written by plyfile (ascii / binary LE / BE, every property type, odd +# orders, n-gons up to 300 vertices, face properties and lists, edge / material / tristrips +# elements, comments, obj_info, point clouds, a 65k-vertex sphere) and by assimp (OFF / OBJ +# -> PLY), each with reference values from plyfile mapped to the Scene conventions; +# `ours`: our encoder's output (luau CLI: tools/fixtures/_ply_encode.luau) read back by +# plyfile and assimp, as verdicts +import json, math, os, shutil, struct, subprocess, tempfile + +INPUTS = ["src/Formats/model/ply", "tools/fixtures/_ply_reference.py", "tools/fixtures/_ply_encode.luau"] + + +def f32(x): + return struct.unpack("<f", struct.pack("<f", x))[0] + + +def pack(fmt, vals): + return struct.pack("<%d%s" % (len(vals), fmt), *vals) + + +def mat_trs(node): + x, y, z, w = node.get("rotation", [0, 0, 0, 1]) + sx, sy, sz = node.get("scale", [1, 1, 1]) + tx, ty, tz = node.get("translation", [0, 0, 0]) + r = [ + [1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)], + [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)], + [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)], + ] + return [[r[i][0] * sx, r[i][1] * sy, r[i][2] * sz, (tx, ty, tz)[i]] for i in range(3)] + + +def quat(rng): + q = [rng.uniform(-1, 1) for _ in range(4)] + ln = math.sqrt(sum(c * c for c in q)) + return [c / ln for c in q] + + +def scenes(rng): + out = [] + # an indexed mesh with every attribute kind + W, H = 5, 4 + n = W * H + pos = [f32(v) for y in range(H) for x in range(W) for v in (x, y, rng.uniform(-1, 1))] + nrm = [] + for _ in range(n): + v = [rng.uniform(-1, 1) for _ in range(3)] + ln = math.sqrt(sum(c * c for c in v)) + nrm += [f32(c / ln) for c in v] + col = [rng.randrange(256) for _ in range(n * 4)] + tex = [f32(rng.random()) for _ in range(n * 2)] + quality = [f32(rng.uniform(0, 10)) for _ in range(n)] + label = [rng.randrange(65536) for _ in range(n)] + idx = [] + for y in range(H - 1): + for x in range(W - 1): + a = y * W + x + idx += [a, a + 1, a + W + 1, a, a + W + 1, a + W] + out.append({"name": "mesh", "nodes": [{"mesh": 1}], "roots": [1], "meshes": [{"prims": [{ + "mode": "triangles", "count": n, "indices": pack("I", idx), + "attrs": {"POSITION": ["f32", 3, pack("f", pos)], "NORMAL": ["f32", 3, pack("f", nrm)], "COLOR_0": ["unorm8", 4, bytes(col)], + "TEXCOORD_0": ["f32", 2, pack("f", tex)], "_quality": ["f32", 1, pack("f", quality)], "_label": ["u16", 1, pack("H", label)]}}]}], + "props": [("x", "<f4", pos[0::3]), ("y", "<f4", pos[1::3]), ("z", "<f4", pos[2::3]), ("nx", "<f4", nrm[0::3]), ("ny", "<f4", nrm[1::3]), + ("nz", "<f4", nrm[2::3]), ("red", "u1", col[0::4]), ("green", "u1", col[1::4]), ("blue", "u1", col[2::4]), ("alpha", "u1", col[3::4]), + ("s", "<f4", tex[0::2]), ("t", "<f4", tex[1::2]), ("label", "<u2", label), ("quality", "<f4", quality)], + "faces": [idx[i:i + 3] for i in range(0, len(idx), 3)]}) + # polygons under a TRS node (positions transformed: compared with a tolerance) + pv = [0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 2, 0, 0, 3, 0.5, 0, 2.5, 1.5, 0.2, 1.5, 1.2, 0.1, 0, 0, 1] + node = {"mesh": 1, "translation": [1, 2, 3], "rotation": quat(rng), "scale": [2, 0.5, 1.5]} + m = mat_trs(node) + w = [[f32(m[i][0] * pv[k * 3] + m[i][1] * pv[k * 3 + 1] + m[i][2] * pv[k * 3 + 2] + m[i][3]) for i in range(3)] for k in range(9)] + out.append({"name": "polys", "nodes": [node], "roots": [1], "meshes": [{"prims": [{ + "mode": "polygons", "count": 9, "indices": pack("I", [0, 1, 2, 3, 1, 4, 5, 6, 7, 2, 0, 3, 8]), "faces": pack("I", [4, 6, 3]), + "attrs": {"POSITION": ["f32", 3, pack("f", pv)]}}]}], + "props": [("x", "<f4", [p[0] for p in w], 1e-5), ("y", "<f4", [p[1] for p in w], 1e-5), ("z", "<f4", [p[2] for p in w], 1e-5)], + "faces": [[0, 1, 2, 3], [1, 4, 5, 6, 7, 2], [0, 3, 8]], "transformed": True}) + # a point cloud with float colours (alpha all 1: not written) + n = 30 + pos = [f32(rng.uniform(-50, 50)) for _ in range(n * 3)] + col = [f32(rng.random()) if k % 4 != 3 else 1.0 for k in range(n * 4)] + out.append({"name": "cloud", "nodes": [{"mesh": 1}], "roots": [1], "meshes": [{"prims": [{ + "mode": "points", "count": n, "attrs": {"POSITION": ["f32", 3, pack("f", pos)], "COLOR_0": ["f32", 4, pack("f", col)]}}]}], + "props": [("x", "<f4", pos[0::3]), ("y", "<f4", pos[1::3]), ("z", "<f4", pos[2::3]), ("red", "<f4", col[0::4]), + ("green", "<f4", col[1::4]), ("blue", "<f4", col[2::4])]}) + # two meshes merged: the second has no colours (filled with opaque white: alpha not written) + pa = [0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0] + ca = [10, 20, 30, 255, 40, 50, 60, 255, 70, 80, 90, 255, 100, 110, 120, 255] + pb = [5, 5, 5, 6, 5, 5, 6, 6, 5, 5, 6, 5.5] + allp = pa + pb + allc = ca + [255] * 16 + out.append({"name": "multi", "nodes": [{"mesh": 1}, {"mesh": 2}], "roots": [1, 2], "meshes": [ + {"prims": [{"mode": "triangles", "count": 4, "indices": pack("I", [0, 1, 2, 0, 2, 3]), + "attrs": {"POSITION": ["f32", 3, pack("f", pa)], "COLOR_0": ["unorm8", 4, bytes(ca)]}}]}, + {"prims": [{"mode": "polygons", "count": 4, "indices": pack("I", [0, 1, 2, 3]), "faces": pack("I", [4]), + "attrs": {"POSITION": ["f32", 3, pack("f", pb)]}}]}], + "props": [("x", "<f4", allp[0::3]), ("y", "<f4", allp[1::3]), ("z", "<f4", allp[2::3]), ("red", "u1", allc[0::4]), + ("green", "u1", allc[1::4]), ("blue", "u1", allc[2::4])], + "faces": [[0, 1, 2], [0, 2, 3], [4, 5, 6, 7]]}) + # a mirrored polygon: the winding reverses (first corner kept) + pm = [0, 0, 0, 1, 0, 0, 1.5, 1, 0, 0.5, 1.5, 0, -0.5, 1, 0] + out.append({"name": "mirror", "nodes": [{"mesh": 1, "scale": [-1, 1, 1]}], "roots": [1], "meshes": [{"prims": [{ + "mode": "polygons", "count": 5, "indices": pack("I", [0, 1, 2, 3, 4]), "faces": pack("I", [5]), + "attrs": {"POSITION": ["f32", 3, pack("f", pm)]}}]}], + "props": [("x", "<f4", [-v for v in pm[0::3]]), ("y", "<f4", pm[1::3]), ("z", "<f4", pm[2::3])], + "faces": [[0, 4, 3, 2, 1]], "transformed": True}) + for sc in out: + sc["props"] = [{"name": p[0], "dtype": p[1], "values": struct.pack("<%d%s" % (len(p[2]), {"<f4": "f", "u1": "B", "<u2": "H"}[p[1]]), *p[2]), + **({"tol": p[3]} if len(p) > 3 else {})} for p in sc["props"]] + if "faces" in sc: + sc["faceSizes"] = pack("I", [len(f) for f in sc["faces"]]) + sc["faceCorners"] = pack("I", [c for f in sc["faces"] for c in f]) + return out + + +def luau_cmd(): + exe = shutil.which("luau") + return [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"] + + +def assimp_faces(ctx, path): + txt = ctx.nix("assimp", ["assimp", "info", path]).decode(errors="replace") + for line in txt.split("\n"): + if line.startswith("Faces:"): + return int(line.split()[1]) + return None + + +def generate(ctx): + rng = ctx.rng(47) + tmp = tempfile.mkdtemp(prefix="formats-ply-") + try: + _generate(ctx, rng, tmp) + finally: + shutil.rmtree(tmp, ignore_errors=True) + + +def _generate(ctx, rng, tmp): + sc = scenes(rng) + ctx.emit("ply_scenes", sc) + make = ["cube-le.ply", "colors-be.ply", "ascii-mixed.ply", "points-le.ply", "points-ascii-float.ply", "types-be.ply", "big-le.ply", "tristrips.ply"] + # assimp conversions: OFF -> PLY (ascii), OBJ -> PLY (binary) + off = "OFF\n6 3 0\n" + "".join("%r %r %r\n" % (f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5))) for _ in range(6)) + off += "3 0 1 2\n4 1 3 4 2\n3 4 5 2\n" + obj = "".join("v %r %r %r\n" % (f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5))) for _ in range(8)) + obj += "vn 0 0 1\nf 1//1 2//1 3//1 4//1\nf 5//1 6//1 7//1\nf 1//1 8//1 5//1\n" + with open(os.path.join(tmp, "in.off"), "w") as f: + f.write(off) + with open(os.path.join(tmp, "in.obj"), "w") as f: + f.write(obj) + ctx.nix("assimp", ["assimp", "export", os.path.join(tmp, "in.off"), os.path.join(tmp, "assimp-off.ply"), "-fply"]) + ctx.nix("assimp", ["assimp", "export", os.path.join(tmp, "in.obj"), os.path.join(tmp, "assimp-obj-b.ply"), "-fplyb"]) + refs = make + ["assimp-off.ply", "assimp-obj-b.ply"] + enc = subprocess.run(luau_cmd() + [os.path.join(ctx.root, "tools", "fixtures", "_ply_encode.luau")], capture_output=True, check=True, cwd=ctx.root).stdout.decode() + ours = [] + byname = {s["name"]: s for s in sc} + for line in enc.split("\n"): + if not line.strip(): + continue + label, hexdata = line.split(" ", 1) + scene_name, encoding = label.split("/") + s = byname[scene_name] + fn = "ours-%s-%s.ply" % (scene_name, encoding) + with open(os.path.join(tmp, fn), "wb") as f: + f.write(bytes.fromhex(hexdata.strip())) + ours.append({"name": label, "file": fn, "props": [{**p, "values": p["values"].hex()} for p in s["props"]], "faces": s.get("faces")}) + code = open(os.path.join(ctx.root, "tools", "fixtures", "_ply_reference.py")).read() + try: + res = json.loads(ctx.python(["plyfile", "numpy"], code, input=json.dumps({"dir": tmp, "make": make, "ref": refs, "ours": ours}).encode())) + except subprocess.CalledProcessError as e: + raise RuntimeError("ply reference: " + e.stderr.decode(errors="replace")[-3000:]) + verdicts = [] + for o in ours: + ok, detail = res["ours"][o["name"]] + if o["faces"]: + want = sum(len(f) - 2 for f in o["faces"]) + got = assimp_faces(ctx, os.path.join(tmp, o["file"])) + if got != want: + ok, detail = False, "assimp reads %s faces, want %d" % (got, want) + verdicts.append({"name": o["name"], "ok": ok, "detail": detail}) + cases = [] + for name in refs: + with open(os.path.join(tmp, name), "rb") as f: + data = f.read() + r = res["ref"][name] + c = {"name": name, "data": data} + c.update({k: v for k, v in r.items() if v is not None}) + cases.append(c) + ctx.emit("ply", {"cases": cases, "ours": verdicts}) diff --git a/tools/fixtures/pnm.py b/tools/fixtures/pnm.py new file mode 100644 index 0000000..e2b2646 --- /dev/null +++ b/tools/fixtures/pnm.py @@ -0,0 +1,93 @@ +# Netpbm fixtures (tools/fixtures.py): files written by ImageMagick (P1-P7, ASCII / binary, 8 / 16-bit, PAM tuple +# types, PFM both byte orders) and a few hand-written edge cases (comments, packed P1 digits, odd maxvals, PAM +# GRAYSCALE_ALPHA / BLACKANDWHITE); references = ImageMagick's RGBA decodes (8-bit, and 16-bit for 16-bit files). +# tests/gen/pnm.luau { { name, data, width, height, rgba8 (bytes), rgba16? (bytes, big-endian), tol, floats? } } +import os, random, shutil, struct, subprocess, tempfile + + +def generate(ctx): + magick = ctx.nix("imagemagick", ["sh", "-c", "command -v magick"]).decode().strip() + work = tempfile.mkdtemp(prefix="formats-pnm-") + try: + _generate(ctx, magick, work) + finally: + shutil.rmtree(work, ignore_errors=True) + + +def _generate(ctx, magick, work): + rng = random.Random(3) + W = lambda n: os.path.join(work, n) + + def run(*args, inp=None): + r = subprocess.run([magick] + list(args), input=inp, capture_output=True) + if r.returncode != 0: + raise SystemExit("fixtures/pnm: magick %s failed: %s" % (" ".join(args), r.stderr.decode())) + return r.stdout + + # a 16-bit RGBA source with gradients, noise and transparency, written as a 16-bit PAM for ImageMagick + w, h = 37, 23 + src = bytearray() + for y in range(h): + for x in range(w): + r = (x * 65535) // (w - 1) + g = (y * 65535) // (h - 1) + b = rng.randrange(65536) + a = 65535 if (x + y) % 5 else (x * 3000) % 65536 + src += struct.pack(">HHHH", r, g, b, a) + open(W("src.pam"), "wb").write(b"P7\nWIDTH %d\nHEIGHT %d\nDEPTH 4\nMAXVAL 65535\nTUPLTYPE RGB_ALPHA\nENDHDR\n" % (w, h) + bytes(src)) + + cases = [] + + def ref(path, wide, tol=0, floats=None, name=None): + data = open(path, "rb").read() + c = {"name": name or os.path.basename(path), "data": data, "tol": tol} + info = run(path, "-format", "%w %h", "info:").decode().split() + c["width"], c["height"] = int(info[0]), int(info[1]) + c["rgba8"] = run(path, "-depth", "8", "rgba:-") + if wide: + c["rgba16"] = run(path, "-depth", "16", "-endian", "MSB", "rgba:-") + if floats is not None: + c["floats"] = floats + cases.append(c) + + variants = [ + ("p1.pbm", ["-colorspace", "gray", "-threshold", "50%", "-compress", "none"], "pbm:", False), + ("p4.pbm", ["-colorspace", "gray", "-threshold", "50%"], "pbm:", False), + ("p2.pgm", ["-colorspace", "gray", "-depth", "8", "-compress", "none"], "pgm:", False), + ("p5.pgm", ["-colorspace", "gray", "-depth", "8"], "pgm:", False), + ("p5-16.pgm", ["-colorspace", "gray", "-depth", "16"], "pgm:", True), + ("p2-16.pgm", ["-colorspace", "gray", "-depth", "16", "-compress", "none"], "pgm:", True), + ("p3.ppm", ["-alpha", "off", "-depth", "8", "-compress", "none"], "ppm:", False), + ("p6.ppm", ["-alpha", "off", "-depth", "8"], "ppm:", False), + ("p6-16.ppm", ["-alpha", "off", "-depth", "16"], "ppm:", True), + ("p3-16.ppm", ["-alpha", "off", "-depth", "16", "-compress", "none"], "ppm:", True), + ("rgba.pam", ["-depth", "8"], "pam:", False), + ("rgba16.pam", ["-depth", "16"], "pam:", True), + ("rgb.pam", ["-alpha", "off", "-depth", "8"], "pam:", False), + ("gray.pam", ["-alpha", "off", "-colorspace", "gray", "-depth", "8"], "pam:", False), + ("graya.pam", ["-colorspace", "gray", "-depth", "8"], "pam:", False), + ("graya16.pam", ["-colorspace", "gray", "-depth", "16"], "pam:", True), + ("bw.pam", ["-alpha", "off", "-colorspace", "gray", "-threshold", "50%", "-type", "bilevel"], "pam:", False), + ] + for name, args, prefix, wide in variants: + run(W("src.pam"), *args, prefix + W(name)) + ref(W(name), wide) + for endian in ("LSB", "MSB"): + for col in ("rgb", "gray"): + name = "%s-%s.pfm" % (col, endian) + extra = ["-colorspace", "gray"] if col == "gray" else [] + run(W("src.pam"), "-alpha", "off", *extra, "-endian", endian, "pfm:" + W(name)) + fl = run(W(name), "-depth", "32", "-define", "quantum:format=floating-point", "-endian", "LSB", "rgba:-") + ref(W(name), False, tol=1, floats=fl) + + # hand-written edge cases (references from ImageMagick too) + def hand(name, data, wide=False, tol=0): + open(W(name), "wb").write(data) + ref(W(name), wide, tol=tol) + hand("comments.ppm", b"P6\n# a comment\n3 # inline\n2\n#another\n255\n" + bytes(range(18))) + hand("packed.pbm", b"P1\n5 3\n10101\n01010\n1 1 1 0 0\n") + hand("maxval1000.pgm", b"P2\n4 2\n1000\n0 250 500 1000\n999 1 333 750\n", wide=True, tol=1) + hand("maxval7.ppm", b"P3 2 2 7 0 1 2 3 4 5 6 7 7 7 0 0\n", tol=1) + hand("p4-odd.pbm", b"P4\n11 3\n" + bytes([0b10101010, 0b11100000, 0b00001111, 0b00100000, 0b11111111, 0b11000000])) + hand("graya-hand.pam", b"P7\nWIDTH 2\nHEIGHT 2\nDEPTH 2\nMAXVAL 255\nTUPLTYPE GRAYSCALE_ALPHA\nENDHDR\n" + bytes([0, 255, 100, 128, 200, 0, 255, 255])) + ctx.emit("pnm", cases) diff --git a/tools/fixtures/psd.py b/tools/fixtures/psd.py new file mode 100644 index 0000000..d134b70 --- /dev/null +++ b/tools/fixtures/psd.py @@ -0,0 +1,389 @@ +# PSD fixtures (tools/fixtures.py): PSD / PSB files written here (a small writer below: every colour mode, 1/8/16/32 +# bits, raw / RLE / ZIP / ZIP-with-prediction channels, groups, pass-through, clipping, masks, fill opacity, hidden +# layers, Unicode names, every blend mode) and one written by ImageMagick, all read by psd-tools (the reference): +# tests/gen/psd.luau { cases = { { name, data, width, height, composite (RGBA of psd-tools' merged image), +# layers = { { name, left, top, width, height, crc (RGBA of psd-tools' layer.topil()) } }, +# flat (psd-tools' composite of the layers, RGBA) } } } +# tests/gen/psd_ours.luau { checks = { { label, ok } } }: our encoder's PSD (tools/fixtures/_ours.luau, run with +# luau) read by psd-tools, compared with the layers and the flattened image we wrote. +import json, os, random, shutil, struct, subprocess, tempfile, zlib + +INPUTS = ["src/Formats/layered/psd", "src/Formats/codecs/Blend.luau", "src/Formats/ops/LayerOps.luau", "tools/fixtures/_ours.luau"] + +BLEND = ["norm", "diss", "dark", "mul ", "idiv", "lbrn", "dkCl", "lite", "scrn", "div ", "lddg", "lgCl", "over", "sLit", + "hLit", "vLit", "lLit", "pLit", "hMix", "diff", "smud", "fsub", "fdiv", "hue ", "sat ", "colr", "lum "] + + +def packbits(row): + out, i, n = bytearray(), 0, len(row) + while i < n: + j = i + while j + 1 < n and row[j + 1] == row[i] and j - i < 127: + j += 1 + if j - i >= 2: + out += bytes([257 - (j - i + 1), row[i]]) + i = j + 1 + else: + k = i + while k < n and k - i < 128 and not (k + 2 < n and row[k] == row[k + 1] == row[k + 2]): + k += 1 + out += bytes([k - i - 1]) + row[i:k] + i = k + return bytes(out) + + +def bytes_per(depth): + return {8: 1, 16: 2, 32: 4}[depth] + + +def channel_data(plane, w, h, depth, comp, psb=False): + """plane: bytes (rows of w samples, big endian) -> compression code + data""" + rb = w * bytes_per(depth) + if w == 0 or h == 0: + return struct.pack(">H", 0) + if comp == 0: + return struct.pack(">H", 0) + plane + if comp == 1: + rows = [packbits(plane[y * rb:(y + 1) * rb]) for y in range(h)] + fmt = ">I" if psb else ">H" + return struct.pack(">H", 1) + b"".join(struct.pack(fmt, len(r)) for r in rows) + b"".join(rows) + if comp == 2: + return struct.pack(">H", 2) + zlib.compress(plane) + # zip with prediction + out = bytearray() + for y in range(h): + row = plane[y * rb:(y + 1) * rb] + if depth == 8: + out += bytes([row[0]] + [(row[x] - row[x - 1]) & 255 for x in range(1, w)]) + elif depth == 16: + vals = struct.unpack(">%dH" % w, row) + out += struct.pack(">%dH" % w, *([vals[0]] + [(vals[x] - vals[x - 1]) & 0xFFFF for x in range(1, w)])) + else: + planes = bytes(row[x * 4 + k] for k in range(4) for x in range(w)) + out += bytes([planes[0]] + [(planes[x] - planes[x - 1]) & 255 for x in range(1, len(planes))]) + return struct.pack(">H", 3) + zlib.compress(bytes(out)) + + +def pascal(name, pad=4): + b = name.encode("latin-1", "replace")[:255] + s = bytes([len(b)]) + b + while len(s) % pad: + s += b"\0" + return s + + +def block(key, data, psb=False): + while len(data) % 4: + data += b"\0" + return b"8BIM" + key + (struct.pack(">Q", len(data)) if psb and key in (b"Lr16", b"Lr32", b"Layr") else struct.pack(">I", len(data))) + data + + +def luni(name): + u = name.encode("utf-16-be") + return struct.pack(">I", len(u) // 2) + u + + +class Layer: + def __init__(self, name, left, top, w, h, chans, blend="norm", opacity=255, clip=0, hidden=False, section=None, + section_blend=None, fill=None, mask=None, comp=1): + self.__dict__.update(locals()) + + +def layer_info(layers, depth, psb, neg): + recs, data = bytearray(), bytearray() + for L in layers: + recs += struct.pack(">iiii", L.top, L.left, L.top + L.h, L.left + L.w) + chans = list(L.chans.items()) + if L.mask: + chans.append((-2, L.mask["plane"])) + recs += struct.pack(">H", len(chans)) + for cid, plane in chans: + if cid == -2: + m = L.mask + cd = channel_data(plane, m["w"], m["h"], depth, 1, psb) + else: + cd = channel_data(plane, L.w, L.h, depth, L.comp, psb) + recs += struct.pack(">h", cid) + (struct.pack(">Q", len(cd)) if psb else struct.pack(">I", len(cd))) + data += cd + flags = 8 | (2 if L.hidden else 0) | (16 if L.section else 0) + recs += b"8BIM" + L.blend.encode() + bytes([L.opacity, L.clip, flags, 0]) + ex = bytearray() + if L.mask: + m = L.mask + ex += struct.pack(">IiiiiBBH", 20, m["top"], m["left"], m["top"] + m["h"], m["left"] + m["w"], m["default"], m.get("flags", 0), 0) + else: + ex += struct.pack(">I", 0) + ex += struct.pack(">I", 0) + ex += pascal(L.name) + ex += block(b"luni", luni(L.name)) + if L.section is not None: + ex += block(b"lsct", struct.pack(">I", L.section) + (b"8BIM" + L.section_blend.encode() if L.section_blend else b"")) + if L.fill is not None: + ex += block(b"iOpa", bytes([L.fill, 0, 0, 0])) + recs += struct.pack(">I", len(ex)) + ex + body = struct.pack(">h", -len(layers) if neg else len(layers)) + recs + data + if len(body) % 2: + body += b"\0" + return body + + +def psd(w, h, mode, depth, nch, merged_planes, layers=None, psb=False, comp=1, palette=None, lr16=False, neg=True, resources=b""): + out = b"8BPS" + struct.pack(">H", 2 if psb else 1) + b"\0" * 6 + struct.pack(">HIIHH", nch, h, w, depth, mode) + cm = palette or b"" + out += struct.pack(">I", len(cm)) + cm + out += struct.pack(">I", len(resources)) + resources + L = lambda n: struct.pack(">Q", n) if psb else struct.pack(">I", n) + if layers: + li = layer_info(layers, depth, psb, neg) + if lr16: + lm = L(0) + struct.pack(">I", 0) + block(b"Lr16" if depth == 16 else b"Lr32", li, psb) + else: + lm = L(len(li)) + li + struct.pack(">I", 0) + out += L(len(lm)) + lm + else: + out += L(0) + rb = (w + 7) // 8 if depth == 1 else w * bytes_per(depth) + if comp == 0: + out += struct.pack(">H", 0) + b"".join(merged_planes) + elif comp == 1: + rows = [packbits(p[y * rb:(y + 1) * rb]) for p in merged_planes for y in range(h)] + fmt = ">I" if psb else ">H" + out += struct.pack(">H", 1) + b"".join(struct.pack(fmt, len(r)) for r in rows) + b"".join(rows) + else: + out += struct.pack(">H", 2) + zlib.compress(b"".join(merged_planes)) + return out + + +def plane8(w, h, f): + return bytes(f(x, y) & 255 for y in range(h) for x in range(w)) + + +def plane16(w, h, f): + return b"".join(struct.pack(">H", f(x, y) & 0xFFFF) for y in range(h) for x in range(w)) + + +def plane32(w, h, f): + return b"".join(struct.pack(">f", f(x, y)) for y in range(h) for x in range(w)) + + +def rgba_layer(name, left, top, w, h, seed, **kw): + rng = random.Random(seed) + k = [rng.randrange(1, 9) for _ in range(8)] + chans = { + 0: plane8(w, h, lambda x, y: x * k[0] * 7 + y * k[1]), + 1: plane8(w, h, lambda x, y: y * k[2] * 9 + x * k[3]), + 2: plane8(w, h, lambda x, y: (x ^ y) * k[4] * 5), + -1: plane8(w, h, lambda x, y: 255 if (x + y) % 5 else 90 + (x * k[5] * 13) % 160), + } + return Layer(name, left, top, w, h, chans, **kw) + + +def divider(): + return Layer("</Layer group>", 0, 0, 0, 0, {0: b"", 1: b"", 2: b"", -1: b""}, section=3) + + +def group(name, blend="pass", opacity=255, hidden=False): + return Layer(name, 0, 0, 0, 0, {0: b"", 1: b"", 2: b"", -1: b""}, blend=blend, opacity=opacity, section=1, section_blend=blend, hidden=hidden) + + +def merged_rgb(w, h, alpha=True): + ps = [plane8(w, h, lambda x, y, c=c: x * 5 + y * 3 + c * 70) for c in range(3)] + if alpha: + ps.append(plane8(w, h, lambda x, y: 255 - x)) + return ps + + +def cases(): + W, H = 40, 30 + out = [] + # 1. a full RGB document: groups, pass-through, clipping, masks, fill, hidden, every compression + mask = {"top": 5, "left": 8, "w": 20, "h": 12, "default": 0, "plane": plane8(20, 12, lambda x, y: x * 12)} + layers = [ + rgba_layer("Background", 0, 0, W, H, 1, comp=0), + rgba_layer("Multiply", 5, 4, 20, 15, 2, blend="mul ", opacity=200), + divider(), + rgba_layer("Screen", -3, 10, 25, 25, 3, blend="scrn", comp=2), + rgba_layer("Overlay", 15, 2, 30, 12, 4, blend="over", comp=3), + group("Isolated", blend="norm", opacity=180), + divider(), + rgba_layer("Diff é日", 10, 10, 20, 15, 5, blend="diff"), + rgba_layer("Hidden", 0, 0, 10, 10, 6, hidden=True), + group("Pass"), + rgba_layer("Base", 20, 15, 15, 10, 7), + rgba_layer("Clipped", 15, 12, 20, 14, 8, clip=1, blend="mul "), + rgba_layer("Masked", 2, 2, 30, 20, 9, mask=mask), + rgba_layer("Fill", 25, 0, 15, 30, 10, fill=128, blend="lite"), + ] + out.append(("rgb-layers", psd(W, H, 3, 8, 4, merged_rgb(W, H), layers))) + # 2. every blend mode on its own (two layers) + for key in BLEND: + ls = [rgba_layer("Bottom", 0, 0, 24, 16, 11, comp=0), rgba_layer("Top " + key, 4, 2, 18, 12, 12, blend=key, opacity=230)] + out.append(("blend-" + key.strip(), psd(24, 16, 3, 8, 4, merged_rgb(24, 16), ls))) + # 3. 16-bit RGB with the layers in Lr16, ZIP with prediction + ch16 = lambda s: {0: plane16(12, 9, lambda x, y: x * 5000 + y * 31 + s), 1: plane16(12, 9, lambda x, y: y * 7000 + s), 2: plane16(12, 9, lambda x, y: (x * y * 997) + s), -1: plane16(12, 9, lambda x, y: 65535 - x * 3000)} + l16 = [Layer("L16a", 0, 0, 12, 9, ch16(1), comp=3), Layer("L16b", 3, 2, 12, 9, ch16(77), comp=1, blend="mul ")] + m16 = [plane16(16, 12, lambda x, y, c=c: x * 4000 + y * 100 + c * 9000) for c in range(3)] + [plane16(16, 12, lambda x, y: 65535)] + out.append(("rgb16-lr16", psd(16, 12, 3, 16, 4, m16, l16, lr16=True))) + # 4. 32-bit: merged only (floats) and a layer in Lr32 + m32 = [plane32(10, 7, lambda x, y, c=c: (x + c) / 12.0) for c in range(3)] + l32 = [Layer("F", 1, 1, 6, 5, {0: plane32(6, 5, lambda x, y: x / 6.0), 1: plane32(6, 5, lambda x, y: y / 5.0), 2: plane32(6, 5, lambda x, y: 0.5), -1: plane32(6, 5, lambda x, y: 1.0)}, comp=3)] + out.append(("rgb32", psd(10, 7, 3, 32, 3, m32, l32, lr16=True, comp=0))) + # 5. greyscale with layers, raw merged + gl = [Layer("G1", 0, 0, 20, 10, {0: plane8(20, 10, lambda x, y: x * 12), -1: plane8(20, 10, lambda x, y: 255)}), + Layer("G2", 5, 3, 10, 6, {0: plane8(10, 6, lambda x, y: 200 - y * 20), -1: plane8(10, 6, lambda x, y: 128 + x * 10)}, blend="scrn")] + out.append(("gray", psd(20, 10, 1, 8, 2, [plane8(20, 10, lambda x, y: x * 12 + y), plane8(20, 10, lambda x, y: 255)], gl, comp=0))) + # 6. CMYK, merged + a layer + cm = [plane8(14, 8, lambda x, y, c=c: 255 - (x * 15 + c * 40) % 256) for c in range(4)] + cl = [Layer("C", 2, 1, 8, 5, {0: plane8(8, 5, lambda x, y: 200), 1: plane8(8, 5, lambda x, y: 40 * x), 2: plane8(8, 5, lambda x, y: 255), 3: plane8(8, 5, lambda x, y: 220 + y), -1: plane8(8, 5, lambda x, y: 255)})] + out.append(("cmyk", psd(14, 8, 4, 8, 4, cm, cl))) + # 7. indexed (merged only), 8. bitmap (merged only), 9. Lab + pal = bytes(range(256)) + bytes((i * 3) % 256 for i in range(256)) + bytes(255 - i for i in range(256)) + out.append(("indexed", psd(17, 9, 2, 8, 1, [plane8(17, 9, lambda x, y: x * 15 + y)], palette=pal, comp=1))) + out.append(("bitmap", psd(24, 7, 0, 1, 1, [bytes((x * 37 + y * 11) & 255 for y in range(7) for x in range(3))], comp=0))) + out.append(("lab", psd(9, 5, 9, 8, 3, [plane8(9, 5, lambda x, y: x * 28), plane8(9, 5, lambda x, y: 100 + y * 10), plane8(9, 5, lambda x, y: 150)], comp=1))) + # 10. PSB with layers (8-byte lengths, 4-byte RLE counts) + out.append(("psb", psd(W, H, 3, 8, 4, merged_rgb(W, H), [rgba_layer("A", 0, 0, W, H, 21), rgba_layer("B", 3, 3, 10, 10, 22, blend="mul ")], psb=True))) + # 11. no alpha in the merged image, positive layer count + out.append(("rgb-noalpha", psd(W, H, 3, 8, 3, merged_rgb(W, H, False), [rgba_layer("Only", 0, 0, W, H, 31)], neg=False))) + return out + + +REF = r''' +import json, os, sys, zlib +from psd_tools import PSDImage +d = %r +res = [] +for name in sorted(os.listdir(d)): + if not name.endswith(".psd"): + continue + psd = PSDImage.open(os.path.join(d, name)) + c = {"name": name[:-4], "width": psd.width, "height": psd.height} + try: + im = psd.topil() + c["composite"] = im.convert("RGBA").tobytes().hex() if im is not None else "" + except Exception as e: + c["composite"] = "" + layers = [] + for l in psd.descendants(): + if l.is_group(): + layers.append({"name": l.name, "group": True}) + continue + e = {"name": l.name, "left": l.left, "top": l.top, "width": l.width, "height": l.height} + try: + im = l.topil() + if im is not None: + e["crc"] = zlib.crc32(im.convert("RGBA").tobytes()) + except Exception: + pass + layers.append(e) + c["layers"] = layers + try: + f = psd.composite(force=True, color=0.0, alpha=0.0) + c["flat"] = f.convert("RGBA").tobytes().hex() + except Exception as e: + c["flaterr"] = str(e) + res.append(c) +print(json.dumps(res)) +''' + + +def pyrun(ctx, code): + try: + return ctx.python(["psd-tools", "numpy", "pillow"], code) + except subprocess.CalledProcessError as e: + raise RuntimeError("psd-tools failed:\n" + e.stderr.decode(errors="replace")) + + +def reference(ctx, files): + with tempfile.TemporaryDirectory() as d: + for name, data in files: + open(os.path.join(d, name + ".psd"), "wb").write(data) + res = json.loads(pyrun(ctx, REF % d)) + by = {r["name"]: r for r in res} + out = [] + for name, data in files: + r = by[name] + case = {"name": name, "data": data, "width": r["width"], "height": r["height"], "composite": bytes.fromhex(r["composite"])} + if "flat" in r: + case["flat"] = bytes.fromhex(r["flat"]) + case["layers"] = r["layers"] + out.append(case) + return out + + +def imagemagick(ctx): + # image 0 is the merged image, the rest are layers (ImageMagick 7.1 writes the blend key of some layers byte-reversed + # ("mron"), which psd-tools refuses: these layers avoid it) + with tempfile.TemporaryDirectory() as d: + p = os.path.join(d, "im.psd") + argv = ["magick", "-size", "32x24", "gradient:red-blue", "(", "-clone", "0", ")", + "(", "-size", "8x8", "radial-gradient:yellow-none", "-repage", "+20+10", ")", p] + try: + subprocess.run(argv, check=True, capture_output=True) + except (OSError, subprocess.CalledProcessError): + ctx.nix("imagemagick", argv) + return open(p, "rb").read() + + +def generate(ctx): + files = cases() + files.append(("imagemagick", imagemagick(ctx))) + ctx.emit("psd", {"cases": reference(ctx, files)}) + ctx.emit("psd_ours", {"checks": ours(ctx)}) + + +def run_ours(ctx, fmt): + """our encoder's output and facts, from tools/fixtures/_ours.luau""" + script = os.path.join(ctx.root, "tools", "fixtures", "_ours.luau") + argv = [shutil.which("luau") or "luau", script, "-a", fmt] + if shutil.which("luau"): + out = subprocess.run(argv, check=True, capture_output=True, cwd=ctx.root).stdout + else: + out = subprocess.run(["nix", "shell", "nixpkgs#luau", "-c", "luau", script, "-a", fmt], check=True, capture_output=True, cwd=ctx.root).stdout + return json.loads(out) + + +OURS = r''' +import json, sys, zlib +from psd_tools import PSDImage +psd = PSDImage.open(%r) +res = {"width": psd.width, "height": psd.height, "composite": zlib.crc32(psd.topil().convert("RGBA").tobytes()), "layers": []} +for l in psd.descendants(): + if l.is_group(): + res["layers"].append({"group": True, "name": l.name, "blend": str(l.blend_mode), "opacity": l.opacity, "visible": l.visible}) + continue + res["layers"].append({"name": l.name, "left": l.left, "top": l.top, "width": l.width, "height": l.height, + "crc": zlib.crc32(l.topil().convert("RGBA").tobytes()), "blend": str(l.blend_mode), "opacity": l.opacity, + "visible": l.visible, "clip": bool(l.clipping_layer), "mask": l.has_mask()}) +print(json.dumps(res)) +''' + +PSD_BLEND = {"normal": "NORMAL", "multiply": "MULTIPLY", "screen": "SCREEN", "difference": "DIFFERENCE", "lighten": "LIGHTEN"} + + +def ours(ctx): + o = run_ours(ctx, "psd") + with tempfile.TemporaryDirectory() as d: + p = os.path.join(d, "ours.psd") + open(p, "wb").write(bytes.fromhex(o["data"])) + ref = json.loads(pyrun(ctx, OURS % p)) + checks = [] + def check(label, ok): + checks.append({"label": label, "ok": bool(ok)}) + check("psd-tools: composite = our flatten", ref["composite"] == o["composite"]) + leaves = [l for l in ref["layers"] if not l.get("group")] + check("psd-tools: leaf count", len(leaves) == len(o["layers"])) + for want, got in zip(o["layers"], leaves): + n = want["name"] + check(n + ": name", got["name"] == n) + check(n + ": pixels", got["crc"] == want["crc"]) + check(n + ": bounds", (got["left"], got["top"], got["width"], got["height"]) == (want["left"], want["top"], want["width"], want["height"])) + check(n + ": blend", got["blend"].endswith(PSD_BLEND.get(want["blend"], "?"))) + check(n + ": opacity", got["opacity"] == want["opacity"]) + check(n + ": visible", got["visible"] == want["visible"]) + check(n + ": clip", got["clip"] == want["clip"]) + groups = [l for l in ref["layers"] if l.get("group")] + check("psd-tools: two groups", [g["name"] for g in groups] == ["Isolated", "Pass"]) + check("psd-tools: pass-through group", len(groups) == 2 and groups[1]["blend"].endswith("PASS_THROUGH") and groups[0]["blend"].endswith("NORMAL")) + check("psd-tools: masked layer has a mask", any(l.get("mask") for l in leaves if l["name"] == "Masked")) + return checks diff --git a/tools/fixtures/qoi.py b/tools/fixtures/qoi.py new file mode 100644 index 0000000..9da4391 --- /dev/null +++ b/tools/fixtures/qoi.py @@ -0,0 +1,64 @@ +# QOI fixtures (tools/fixtures.py): Pillow's QOI writer and reader. +# tests/gen/qoi.luau { { name, width, height, mode, pixels (source bytes, RGB or RGBA), data (Pillow's .qoi), crc +# (CRC-32 of Pillow's RGBA decode) } } +# tests/gen/qoi_bench.luau { width, height, pixels (RGBA), data } +import struct + +CODE = r''' +import io, random, struct, sys, zlib +from PIL import Image +rng = random.Random(11) +def make(w, h, mode, kind): + n = len(mode) + px = bytearray() + for y in range(h): + for x in range(w): + if kind == "noise": + v = [rng.randrange(256) for _ in range(n)] + elif kind == "grad": + v = [(x * 3 + y) % 256, (y * 5) % 256, (x + y * 2) % 256, 255 - (x % 7) * 30][:n] + elif kind == "flat": + v = [10, 200, 30, 255][:n] if (x // 9 + y // 7) % 2 else [10, 200, 31, 128][:n] + else: # small deltas around a walk, with an occasional jump + base = (x * 2 + y) % 256 + v = [(base + rng.randrange(-2, 2)) % 256, (base + rng.randrange(-30, 30)) % 256, (base + rng.randrange(-9, 9)) % 256, 255 if rng.random() < 0.9 else rng.randrange(256)][:n] + px += bytes(v) + return bytes(px) +out = [] +for (w, h, mode, kind) in ((1, 1, "RGB", "noise"), (1, 1, "RGBA", "noise"), (3, 2, "RGBA", "grad"), (64, 48, "RGB", "grad"), + (64, 48, "RGBA", "grad"), (100, 37, "RGB", "noise"), (100, 37, "RGBA", "noise"), + (200, 150, "RGBA", "flat"), (200, 150, "RGB", "flat"), (128, 99, "RGBA", "walk"), (128, 99, "RGB", "walk"), + (500, 1, "RGBA", "flat"), (1, 300, "RGB", "walk")): + px = make(w, h, mode, kind) + im = Image.frombytes(mode, (w, h), px) + b = io.BytesIO(); im.save(b, "QOI"); data = b.getvalue() + back = Image.open(io.BytesIO(data)).convert("RGBA").tobytes() + name = "%dx%d-%s-%s" % (w, h, mode, kind) + sys.stdout.buffer.write(struct.pack("<HIIB", len(name), w, h, len(mode)) + name.encode() + struct.pack("<III", len(px), len(data), zlib.crc32(back)) + px + data) +# bench: 1024 x 768 RGBA walk image +w, h = 1024, 768 +px = bytearray() +for y in range(h): + for x in range(w): + base = (x // 4 + y // 3) % 256 + px += bytes(((base + (x * y) % 5) % 256, (base * 2) % 256, (255 - base + x % 3) % 256, 255)) +b = io.BytesIO(); Image.frombytes("RGBA", (w, h), bytes(px)).save(b, "QOI") +sys.stdout.buffer.write(struct.pack("<HIIB", 0, w, h, 4) + struct.pack("<III", len(px), len(b.getvalue()), 0) + bytes(px) + b.getvalue()) +''' + + +def generate(ctx): + raw = ctx.python(["pillow"], CODE) + cases, p, bench = [], 0, None + while p < len(raw): + nl, w, h, ch = struct.unpack("<HIIB", raw[p:p + 11]); p += 11 + name = raw[p:p + nl].decode(); p += nl + pl, dl, crc = struct.unpack("<III", raw[p:p + 12]); p += 12 + px, data = raw[p:p + pl], raw[p + pl:p + pl + dl]; p += pl + dl + e = {"name": name, "width": w, "height": h, "channels": ch, "pixels": px, "data": data, "crc": crc} + if nl == 0: + bench = e + else: + cases.append(e) + ctx.emit("qoi", cases) + ctx.emit("qoi_bench", bench) diff --git a/tools/fixtures/stl.py b/tools/fixtures/stl.py new file mode 100644 index 0000000..c5baef9 --- /dev/null +++ b/tools/fixtures/stl.py @@ -0,0 +1,383 @@ +# STL fixtures (tools/fixtures.py). +# tests/gen/stl_scenes.luau scenes for the encoder (indexed grid with colours, polygons under a TRS node, a node tree +# with a matrix, a mirror and u16 positions) with the expected world-space triangle soup +# (computed here with numpy) and the expected colour attribute words +# tests/gen/stl.luau cases: STL files made by trimesh (binary / ascii), by assimp (obj / ply -> stl / stlb) +# and by hand here (binary starting with "solid", VisCAM and Magics colours, raw attribute +# words, odd ASCII: case, tabs, CRLF, several solids, quads, no endsolid, trailing bytes, +# empty), each with reference values from trimesh's raw STL reader (facets, CRC-32 of the +# f32 vertices and normals, area, bounds, attribute words); `ours`: our encoder's output +# (run through the luau CLI: tools/fixtures/_stl_encode.luau) read back by trimesh and +# assimp, as verdicts +import json, math, os, shutil, struct, subprocess, tempfile, zlib + +INPUTS = ["src/Formats/model/stl", "tools/fixtures/_stl_reference.py", "tools/fixtures/_stl_encode.luau"] + + +def f32(x): + return struct.unpack("<f", struct.pack("<f", x))[0] + + +def binary_stl(header, tris, normals=None, attrs=None, extra=b""): + out = bytearray(header.ljust(80, b"\0")[:80]) + out += struct.pack("<I", len(tris)) + for i, t in enumerate(tris): + n = normals[i] if normals else (0.0, 0.0, 0.0) + out += struct.pack("<3f", *n) + for v in t: + out += struct.pack("<3f", *v) + out += struct.pack("<H", attrs[i] if attrs else 0) + return bytes(out) + extra + + +def rand_tris(rng, n, scale=10.0): + return [[tuple(f32(rng.uniform(-scale, scale)) for _ in range(3)) for _ in range(3)] for _ in range(n)] + + +def unit_normal(t): + ux, uy, uz = (t[1][k] - t[0][k] for k in range(3)) + vx, vy, vz = (t[2][k] - t[0][k] for k in range(3)) + n = (uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx) + ln = math.sqrt(sum(c * c for c in n)) or 1.0 + return tuple(f32(c / ln) for c in n) + + +def x8(v): + return (v * 255 + 15) // 31 + + +def to5(c): + return (c * 31 + 127) // 255 + + +def soup_bytes(tris): + return b"".join(struct.pack("<3f", *v) for t in tris for v in t) + + +def crc(b): + return zlib.crc32(b) + + +# --- hand-made files: (name, data, expected) where expected holds what trimesh cannot tell us +def handmade(rng): + cases = [] + tris = rand_tris(rng, 12) + cases.append(("bin-solid-header.stl", binary_stl(b"solid this is binary all the same", tris, [unit_normal(t) for t in tris]), {})) + # VisCAM: bit 15 = valid, red high; some facets invalid + tris = rand_tris(rng, 40) + words, cols = [], [] + for i in range(40): + r, g, b = rng.randrange(32), rng.randrange(32), rng.randrange(32) + if i % 7 == 3: + words.append(rng.randrange(0x8000)) # not valid: the default (opaque white) + cols.append((255, 255, 255, 255)) + else: + words.append(0x8000 | r << 10 | g << 5 | b) + cols.append((x8(r), x8(g), x8(b), 255)) + cases.append(("viscam.stl", binary_stl(b"VisCAM colours", tris, None, words), {"colors": "viscam", "cols": cols})) + # Magics: COLOR= object colour, bit 15 clear = own colour, red low + tris = rand_tris(rng, 40) + dc = (200, 100, 50, 180) + header = b"magics part COLOR=" + bytes(dc) + b",MATERIAL=" + bytes(range(12)) + words, cols = [], [] + for i in range(40): + r, g, b = rng.randrange(32), rng.randrange(32), rng.randrange(32) + if i % 5 == 0: + words.append(0x8000 | rng.randrange(0x8000)) + cols.append(dc) + else: + words.append(r | g << 5 | b << 10) + cols.append((x8(r), x8(g), x8(b), 255)) + cases.append(("magics.stl", binary_stl(header, tris, None, words), {"colors": "magics", "cols": cols, "defaultColor": list(dc)})) + # raw attribute words (no colour convention) + tris = rand_tris(rng, 9) + words = [rng.randrange(1, 0x8000) for _ in range(9)] + cases.append(("attrs.stl", binary_stl(b"attribute words", tris, None, words), {"words": words})) + cases.append(("bin-empty.stl", binary_stl(b"empty", []), {})) + # ASCII oddities: case, tabs, CRLF, exponents, two solids (one unnamed), blank lines + t1, t2 = rand_tris(rng, 3), rand_tris(rng, 2) + s = "SOLID first part\r\n" + for t in t1: + s += "\tFACET NORMAL %.6e %.6e %.6e\r\n\t\tOUTER LOOP\r\n" % unit_normal(t) + for v in t: + s += "\t\t\tVERTEX %.9g\t%.9e %r\r\n" % (v[0], v[1], v[2]) + s += "\t\tENDLOOP\r\n\tENDFACET\r\n\r\n" + s += "ENDSOLID first part\r\n\nsolid\n" + for t in t2: + s += "facet normal %r %r %r outer loop\n" % unit_normal(t) + s += " ".join("vertex %r %r %r" % v for v in t) + "\nendloop endfacet\n" + s += "endsolid\n" + normals = [tuple(f32(float("%.6e" % c)) for c in unit_normal(t)) for t in t1] + [unit_normal(t) for t in t2] + cases.append(("ascii-odd.stl", s.encode(), {"solids": ["first part", ""], "solidFacets": [3, 2], "normals": normals})) + # a quad facet (fan-triangulated: trimesh cannot read it, the expectation is computed here) + q = [(0.0, 0.0, 0.0), (2.0, 0.0, 0.0), (2.0, 1.0, 0.0), (0.0, 1.0, 0.5)] + s = "solid quad\nfacet normal 0 0 1\nouter loop\n" + "".join("vertex %r %r %r\n" % v for v in q) + "endloop\nendfacet\nendsolid quad\n" + qt = [[q[0], q[1], q[2]], [q[0], q[2], q[3]]] + cases.append(("ascii-quad.stl", s.encode(), {"self": True, "tris": qt, "normals": [(0.0, 0.0, 1.0)] * 2})) + # no final endsolid + t3 = rand_tris(rng, 2) + s = "solid open\n" + "".join("facet normal 0 0 0\nouter loop\n" + "".join("vertex %r %r %r\n" % v for v in t) + "endloop\nendfacet\n" for t in t3) + cases.append(("ascii-noend.stl", s.encode(), {"self": True, "tris": t3, "normals": [(0.0, 0.0, 0.0)] * 2})) + # binary with trailing bytes (size != 84 + 50 n: trimesh refuses, we tolerate) + t4 = rand_tris(rng, 5) + n4 = [unit_normal(t) for t in t4] + cases.append(("bin-trailing.stl", binary_stl(b"trailing junk", t4, n4, extra=b"JUNK!!!"), {"self": True, "tris": t4, "normals": n4})) + return cases + + +# --- encoder scenes (also used by tests/model/stl.luau for round trips) +def quat(rng): + q = [rng.uniform(-1, 1) for _ in range(4)] + ln = math.sqrt(sum(c * c for c in q)) + return [c / ln for c in q] + + +def mmul(a, b): + return [[sum(a[i][k] * b[k][j] for k in range(4)) for j in range(4)] for i in range(4)] + + +def det3(m): + return (m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0]) + + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0])) + + +EYE = [[1.0 if i == j else 0.0 for j in range(4)] for i in range(4)] + + +def mat_trs(node): + """row-major 4x4 of a node (glTF: column-major matrix, or T * R * S)""" + if "matrix" in node: + c = node["matrix"] + return [[c[j * 4 + i] for j in range(4)] for i in range(4)] + x, y, z, w = node.get("rotation", [0, 0, 0, 1]) + sx, sy, sz = node.get("scale", [1, 1, 1]) + tx, ty, tz = node.get("translation", [0, 0, 0]) + r = [ + [1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)], + [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)], + [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)], + ] + return [[r[0][0] * sx, r[0][1] * sy, r[0][2] * sz, tx], [r[1][0] * sx, r[1][1] * sy, r[1][2] * sz, ty], + [r[2][0] * sx, r[2][1] * sy, r[2][2] * sz, tz], [0.0, 0.0, 0.0, 1.0]] + + +def unpack(fmt, data): + n = len(data) // struct.calcsize("<" + fmt) + return list(struct.unpack("<%d%s" % (n, fmt), data)) + + +def expected_soup(sc): + """world-space triangles (fan-triangulated polygons, reversed winding under a mirror) as f32 bytes, and the + colour of each facet's first vertex""" + out, cols = [], [] + + def prim_tris(p): + n = p["count"] + flat = unpack("H" if p.get("posType") == "u16" else "f", p["pos"]) + pos = [flat[i * 3:i * 3 + 3] for i in range(n)] + idx = unpack("I", p["indices"]) if "indices" in p else list(range(n)) + if p["mode"] == "polygons": + tris, at = [], 0 + for s in unpack("I", p["faces"]): + for k in range(1, s - 1): + tris.append((idx[at], idx[at + k], idx[at + k + 1])) + at += s + else: + tris = [tuple(idx[i:i + 3]) for i in range(0, len(idx) - len(idx) % 3, 3)] + return pos, tris + + def walk(ni, parent): + node = sc["nodes"][ni - 1] + has = any(k in node for k in ("matrix", "translation", "rotation", "scale")) + m = mmul(parent, mat_trs(node)) if has else parent + if "mesh" in node: + for p in sc["meshes"][node["mesh"] - 1]["prims"]: + pos, tris = prim_tris(p) + flip = det3(m) < 0 + w = [[m[i][0] * v[0] + m[i][1] * v[1] + m[i][2] * v[2] + m[i][3] for i in range(3)] for v in pos] + col = p.get("color") + for a, b, c in tris: + if flip: + b, c = c, b + out.append(w[a] + w[b] + w[c]) + if col is not None: + cols.append(tuple(col[a * 4:a * 4 + 4])) + for c in node.get("children", []): + walk(c, m) + + for r in sc["roots"]: + walk(r, EYE) + return b"".join(struct.pack("<9f", *t) for t in out), cols + + +def pack(fmt, vals): + return struct.pack("<%d%s" % (len(vals), fmt), *vals) + + +def scenes(rng): + out = [] + # grid: indexed, colours on 5-bit steps, no transform + W, H = 7, 6 + pos = [v for y in range(H) for x in range(W) for v in (x * 0.5, y * 0.5, rng.uniform(-1, 1))] + idx = [] + for y in range(H - 1): + for x in range(W - 1): + a = y * W + x + idx += [a, a + 1, a + W + 1, a, a + W + 1, a + W] + col = bytes(v for _ in range(W * H) for v in (x8(rng.randrange(32)), x8(rng.randrange(32)), x8(rng.randrange(32)), 255)) + out.append({"name": "grid", "nodes": [{"mesh": 1, "name": "grid"}], "roots": [1], "meshes": [{"name": "grid", "prims": [ + {"mode": "triangles", "count": W * H, "pos": pack("f", pos), "indices": pack("I", idx), "color": col}]}], + "encodings": ["binary", "ascii", "viscam", "magics"]}) + # polygons under a TRS node + pv = [0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 2, 0, 0, 3, 0.5, 0, 2.5, 1.5, 0.2, 1.5, 1.2, 0.1, 0, 0, 1] + corners = [0, 1, 2, 3, 1, 4, 5, 6, 7, 2, 0, 3, 8] + out.append({"name": "polys", "nodes": [{"mesh": 1, "translation": [1, 2, 3], "rotation": quat(rng), "scale": [2, 0.5, 1.5]}], "roots": [1], + "meshes": [{"name": "polys", "prims": [{"mode": "polygons", "count": 9, "pos": pack("f", pv), + "indices": pack("I", corners), "faces": pack("I", [4, 6, 3])}]}], + "encodings": ["binary", "ascii"]}) + # a node tree: a matrix root, a mirrored child (winding flips), a child without its own transform, u16 positions, + # a soup without indices + soup = [rng.uniform(-3, 3) for _ in range(45)] + u16 = [rng.randrange(0, 100) for _ in range(18)] + c, s = math.cos(0.7), math.sin(0.7) + m = [c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, 5, -2, 0.5, 1] # column-major: rotate about z, translate + out.append({"name": "tree", "nodes": [ + {"mesh": 2, "matrix": m, "children": [2, 3]}, + {"mesh": 1, "scale": [-1, 1, 1], "translation": [0, 0, 1]}, + {"mesh": 3, "name": "plain"}, + ], "roots": [1], "meshes": [ + {"name": "soup", "prims": [{"mode": "triangles", "count": 15, "pos": pack("f", soup)}]}, + {"name": "u16", "prims": [{"mode": "triangles", "count": 6, "posType": "u16", "pos": pack("H", u16), + "indices": pack("I", [0, 1, 2, 2, 3, 4, 4, 5, 0, 1, 3, 5])}]}, + {"name": "pair", "prims": [{"mode": "triangles", "count": 4, "pos": pack("f", [0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0.25]), + "indices": pack("I", [0, 1, 2, 0, 2, 3])}]}, + ], "encodings": ["binary", "ascii"]}) + for sc in out: + soup_b, cols = expected_soup(sc) + sc["expect"] = soup_b + sc["exact"] = sc["name"] == "grid" + if cols: + sc["viscamWords"] = [0x8000 | to5(r) << 10 | to5(g) << 5 | to5(b) for r, g, b, _ in cols] + sc["magicsWords"] = [to5(r) | to5(g) << 5 | to5(b) << 10 for r, g, b, _ in cols] + return out + + +def luau_cmd(): + exe = shutil.which("luau") + return [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"] + + +def assimp_info(ctx, path): + txt = ctx.nix("assimp", ["assimp", "info", path]).decode(errors="replace") + faces = verts = None + for line in txt.split("\n"): + if line.startswith("Faces:"): + faces = int(line.split()[1]) + if line.startswith("Vertices:"): + verts = int(line.split()[1]) + return faces, verts + + +def generate(ctx): + rng = ctx.rng(31) + tmp = tempfile.mkdtemp(prefix="formats-stl-") + try: + _generate(ctx, rng, tmp) + finally: + shutil.rmtree(tmp, ignore_errors=True) + + +def _generate(ctx, rng, tmp): + # scenes first: the encoder script reads them + sc = scenes(rng) + ctx.emit("stl_scenes", sc) + files = {} + hand = handmade(rng) + for name, data, _ in hand: + files[name] = data + # assimp conversions: an OBJ with quads and a PLY -> ASCII and binary STL + obj = "".join("v %r %r %r\n" % (f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5))) for _ in range(12)) + obj += "f 1 2 3 4\nf 5 6 7\nf 8 9 10 11 12\nf 2 4 6\n" + ply = "ply\nformat ascii 1.0\nelement vertex 5\nproperty float x\nproperty float y\nproperty float z\nelement face 3\nproperty list uchar int vertex_indices\nend_header\n" + ply += "".join("%r %r %r\n" % (f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5))) for _ in range(5)) + ply += "3 0 1 2\n4 0 2 3 4\n3 4 3 1\n" + with open(os.path.join(tmp, "in.obj"), "w") as f: + f.write(obj) + with open(os.path.join(tmp, "in.ply"), "w") as f: + f.write(ply) + for src, dst, fid in (("in.obj", "assimp-obj.stl", "stl"), ("in.obj", "assimp-obj-b.stl", "stlb"), ("in.ply", "assimp-ply-b.stl", "stlb")): + ctx.nix("assimp", ["assimp", "export", os.path.join(tmp, src), os.path.join(tmp, dst), "-f" + fid]) + for name, data in files.items(): + with open(os.path.join(tmp, name), "wb") as f: + f.write(data) + make = [["trimesh-icosphere.stl", "icosphere", "stl", 1], ["trimesh-icosphere-ascii.stl", "icosphere", "stl_ascii", 1], + ["trimesh-box.stl", "box", "stl", 2], ["trimesh-capsule-ascii.stl", "capsule", "stl_ascii", 3], + ["trimesh-soup.stl", "soup", "stl", 4], ["trimesh-soup-ascii.stl", "soup", "stl_ascii", 5]] + refnames = [m[0] for m in make] + ["assimp-obj.stl", "assimp-obj-b.stl", "assimp-ply-b.stl"] + refnames += [n for n, _, e in hand if not e.get("self")] + # our encoder's output (the luau CLI prints "<scene>/<encoding> <hex>" lines) + enc = subprocess.run(luau_cmd() + [os.path.join(ctx.root, "tools", "fixtures", "_stl_encode.luau")], capture_output=True, check=True, cwd=ctx.root).stdout.decode() + ours = [] + byname = {s["name"]: s for s in sc} + for line in enc.split("\n"): + if not line.strip(): + continue + label, hexdata = line.split(" ", 1) + scene_name, encoding = label.split("/") + s = byname[scene_name] + fn = "ours-%s-%s.stl" % (scene_name, encoding) + with open(os.path.join(tmp, fn), "wb") as f: + f.write(bytes.fromhex(hexdata.strip())) + o = {"name": label, "file": fn, "expect": s["expect"].hex(), "exact": s["exact"]} + if encoding == "viscam": + o["colors"] = s["viscamWords"] + elif encoding == "magics": + o["colors"] = s["magicsWords"] + ours.append(o) + code = open(os.path.join(ctx.root, "tools", "fixtures", "_stl_reference.py")).read() + try: + res = json.loads(ctx.python(["trimesh", "numpy"], code, input=json.dumps({"dir": tmp, "make": make, "ref": refnames, "ours": ours}).encode())) + except subprocess.CalledProcessError as e: + raise RuntimeError("stl reference: " + e.stderr.decode(errors="replace")[-3000:]) + verdicts = [] + for o in ours: + ok, detail = res["ours"][o["name"]] + # assimp reads it too + faces, _ = assimp_info(ctx, os.path.join(tmp, o["file"])) + want = len(bytes.fromhex(o["expect"])) // 36 + if faces != want: + ok, detail = False, "assimp reads %s faces, want %d" % (faces, want) + verdicts.append({"name": o["name"], "ok": ok, "detail": detail}) + cases = [] + for name in refnames: + with open(os.path.join(tmp, name), "rb") as f: + data = f.read() + r = res["ref"][name] + c = {"name": name, "data": data, "facets": r["facets"], "pos_crc": r["pos_crc"], "area": r["area"], "bounds": r["bounds"]} + extra = next((e for n, _, e in hand if n == name), {}) + if "nrm_crc" in r: + c["nrm_crc"] = r["nrm_crc"] + elif "normals" in extra: # the normals written here (%.6e / repr of f32 values, read as f32) + c["nrm_crc"] = crc(b"".join(struct.pack("<3f", *n) * 3 for n in extra["normals"])) + if "cols" in extra: + c["colors"] = extra["colors"] + c["col_crc"] = crc(b"".join(bytes(col) * 3 for col in extra["cols"])) + # the colour words trimesh read must be the ones written + assert r.get("attr") is not None + if "defaultColor" in extra: + c["defaultColor"] = extra["defaultColor"] + if "words" in extra: + assert r["attr"] == extra["words"] + c["attr_crc"] = crc(struct.pack("<%dH" % len(extra["words"]), *extra["words"])) + if "solids" in extra: + c["solids"] = extra["solids"] + c["solidFacets"] = extra["solidFacets"] + c["binary"] = not data.lstrip()[:5].lower() == b"solid" or (len(data) >= 84 and 84 + 50 * struct.unpack("<I", data[80:84])[0] == len(data)) + cases.append(c) + for name, data, e in hand: + if e.get("self"): + tris = e["tris"] + cases.append({"name": name, "data": data, "facets": len(tris), "pos_crc": crc(soup_bytes(tris)), + "nrm_crc": crc(b"".join(struct.pack("<3f", *n) * 3 for n in e["normals"])), + "binary": not data.startswith(b"solid")}) + ctx.emit("stl", {"cases": cases, "ours": verdicts}) diff --git a/tools/fixtures/subtitles.py b/tools/fixtures/subtitles.py new file mode 100644 index 0000000..1421471 --- /dev/null +++ b/tools/fixtures/subtitles.py @@ -0,0 +1,140 @@ +# Subtitle fixtures (tests/gen/subtitles.luau, for tests/subtitle/srt.luau, vtt.luau and ass.luau) with +# ffmpeg as the reference: a random SRT script converted by ffmpeg to SRT / WebVTT / ASS, and hand-written WebVTT / +# ASS / SSA files with their features, converted by ffmpeg to SRT. Every case carries the expected cues +# ({ start_ms, stop_ms, plain text }) so the tests compare our decode with ffmpeg's view of the same file. +import os, random, re, shutil, subprocess, tempfile + +WORDS = ["alpha", "beta", "gamma", "delta", "omega", "café", "naïve", "日本", "fox", "dog", "42", "hello", "world"] + + +def ffmpeg(ctx, src_bytes, src_ext, dst_ext): + with tempfile.TemporaryDirectory() as d: + src = os.path.join(d, "in." + src_ext) + dst = os.path.join(d, "out." + dst_ext) + open(src, "wb").write(src_bytes) + argv = ["ffmpeg", "-hide_banner", "-loglevel", "error", "-y", "-i", src, dst] + if shutil.which("ffmpeg"): + subprocess.run(argv, check=True, capture_output=True) + else: + ctx.nix("ffmpeg", argv) + return open(dst, "rb").read() + + +def plain(s): + return re.sub(r"{[^}]*}", "", re.sub(r"<[^>]*>", "", s)).replace("&", "&") + + +def srt_time(ms): + return "%02d:%02d:%02d,%03d" % (ms // 3600000, ms // 60000 % 60, ms // 1000 % 60, ms % 1000) + + +def random_srt(rng, n): + cues, t = [], 500 + for i in range(n): + start = t + rng.randrange(0, 3000) + stop = start + rng.randrange(300, 5000) + t = stop + lines = [] + for _ in range(rng.randrange(1, 3)): + words = [rng.choice(WORDS) for _ in range(rng.randrange(1, 6))] + if rng.random() < 0.3: + k = rng.randrange(len(words)) + tag = rng.choice("ibu") + words[k] = "<%s>%s</%s>" % (tag, words[k], tag) + lines.append(" ".join(words)) + cues.append((start, stop, "\n".join(lines))) + text = "".join("%d\n%s --> %s\n%s\n\n" % (i + 1, srt_time(a), srt_time(b), t) for i, (a, b, t) in enumerate(cues)) + return text.encode(), [{"start": a, "stop": b, "plain": plain(t)} for a, b, t in cues] + + +VTT = """WEBVTT - a test file +Kind: captions + +STYLE +::cue { color: yellow } + +REGION +id:r1 width:40% + +NOTE this is a comment +over two lines + +intro +00:01.000 --> 00:04.500 align:start position:10% +<v Roger>Hello <i>there</i></v> + +00:05.250 --> 00:07.000 +first line +second line + +01:00:02.000 --> 01:00:03.123 line:0 +<c.loud>an hour in</c> & more +""" + +ASS = """[Script Info] +; Script generated by hand +Title: test +ScriptType: v4.00+ +PlayResX: 640 +PlayResY: 480 + +[V4+ Styles] +Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding +Style: Default,Arial,20,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,2,2,2,10,10,10,1 +Style: Top,Verdana,24,&H0000FFFF,&H000000FF,&H00000000,&H80000000,-1,0,0,0,100,100,0,0,1,2,0,8,10,10,10,1 + +[Events] +Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text +Dialogue: 0,0:00:01.00,0:00:03.50,Default,Bob,0,0,0,,Hello, {\\i1}world{\\i0}! +Comment: 0,0:00:02.00,0:00:04.00,Default,,0,0,0,,a comment line +Dialogue: 1,0:00:04.20,0:00:06.00,Top,,0,0,0,,{\\an8\\b1}Bold top{\\b0}\\Nsecond line +Dialogue: 0,0:01:02.03,0:01:05.99,Default,,0,0,0,,{\\pos(10,20)}commas, inside, the text + +[Fonts] +fontname: x.ttf +ABCDEF +""" + +SSA = """[Script Info] +Title: old +ScriptType: v4.00 + +[V4 Styles] +Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, TertiaryColour, BackColour, Bold, Italic, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, AlphaLevel, Encoding +Style: Default,Tahoma,24,16777215,65535,65535,-2147483640,-1,0,1,3,0,2,30,30,30,0,0 + +[Events] +Format: Marked, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text +Dialogue: Marked=0,0:00:00.50,0:00:02.00,Default,,0000,0000,0000,,old style +Dialogue: Marked=0,0:00:02.50,0:00:04.25,Default,,0000,0000,0000,,{\\i1}two{\\i0}\\Nlines +""" + + +def parse_srt(data): + """the cues of an SRT (ffmpeg's output) -> [{start, stop, plain}]""" + out = [] + text = data.decode("utf-8-sig").replace("\r\n", "\n") + for block in re.split(r"\n\s*\n", text.strip()): + lines = block.split("\n") + for k, l in enumerate(lines): + m = re.match(r"(\d+):(\d+):(\d+)[,.](\d+) --> (\d+):(\d+):(\d+)[,.](\d+)", l) + if m: + g = [int(x) for x in m.groups()] + out.append({"start": ((g[0] * 60 + g[1]) * 60 + g[2]) * 1000 + g[3], "stop": ((g[4] * 60 + g[5]) * 60 + g[6]) * 1000 + g[7], "plain": plain("\n".join(lines[k + 1:]))}) + break + return out + + +def generate(ctx): + rng = random.Random(7) + src, cues = random_srt(rng, 40) + out = {"srt": src, "cues": cues} + for ext in ("srt", "vtt", "ass"): + out["ffmpeg_" + ext] = ffmpeg(ctx, src, "srt", ext) + hand = [] + for name, ext, data in (("vtt", "vtt", VTT), ("ass", "ass", ASS), ("ssa", "ssa", SSA)): + b = data.encode() + ref = ffmpeg(ctx, b, ext, "srt") + hand.append({"name": name, "data": b, "ffmpeg_srt": ref, "cues": parse_srt(ref)}) + out["hand"] = hand + ctx.emit("subtitles", out) diff --git a/tools/fixtures/svg.py b/tools/fixtures/svg.py new file mode 100644 index 0000000..4c70218 --- /dev/null +++ b/tools/fixtures/svg.py @@ -0,0 +1,202 @@ +# SVG fixtures (tools/fixtures.py): hand-written SVGs, one feature area each, rendered by resvg (nixpkgs#resvg, the +# reference rasterizer), and the same documents decoded and written back by our encoder (tools/fixtures/_ours.luau) +# then rendered by resvg too: +# tests/gen/svg.luau { cases = { { name, svg, width, height, ref (resvg RGBA), ours (our SVG text), ours_ref +# (resvg's RGBA of our SVG) } } } +import json, os, shutil, subprocess, tempfile + +INPUTS = ["src/Formats/vector/svg", "tools/fixtures/_ours.luau"] + +def svg(w, h, body, extra=""): + return '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="%d" height="%d"%s>\n%s\n</svg>\n' % (w, h, extra, body) + +CASES = { + "shapes": svg(64, 64, """ + <rect x="4" y="4" width="20" height="14" fill="red"/> + <rect x="30" y="4" width="28" height="16" rx="5" fill="#0a0" stroke="black" stroke-width="2"/> + <circle cx="14" cy="34" r="9" fill="blue"/> + <ellipse cx="44" cy="34" rx="14" ry="7" fill="orange" stroke="purple"/> + <line x1="4" y1="50" x2="30" y2="60" stroke="black" stroke-width="3"/> + <polyline points="34,60 40,48 46,58 52,46 60,60" fill="none" stroke="teal" stroke-width="2"/> + <polygon points="4,62 10,52 16,62" fill="magenta"/>"""), + "path-commands": svg(64, 64, """ + <path d="M4 4 L20 4 H28 V12 L4 12 Z" fill="#c00"/> + <path d="m34 4 l10 0 h8 v8 l-18 0 z" fill="#0c0"/> + <path d="M4 20 C10 14 18 30 24 20 S36 26 40 20" fill="none" stroke="blue" stroke-width="2"/> + <path d="M4 34 Q14 24 24 34 T44 34 T60 30" fill="none" stroke="black" stroke-width="2"/> + <path d="m4 44 c4-6 12 6 16 0 s8-6 12 0 q4 6 8 0 t8 0" fill="none" stroke="#a0a" stroke-width="2"/> + <path d="M4,60L10,52,16,60zM20 60 52 60 36 50z" fill="gold" stroke="brown"/>"""), + "arcs": svg(64, 64, """ + <path d="M8 16 A12 8 0 0 1 32 16" fill="none" stroke="red" stroke-width="2"/> + <path d="M36 16 A12 8 0 1 0 60 16" fill="none" stroke="blue" stroke-width="2"/> + <path d="M8 40 a10 10 0 1 1 20 0 a10 10 0 1 1 -20 0" fill="#9c9"/> + <path d="M36 32 A14 6 30 0 1 58 48" fill="none" stroke="black" stroke-width="2"/> + <path d="M36 58 A3 3 0 0 1 58 58" fill="none" stroke="purple" stroke-width="2"/>"""), + "transforms": svg(64, 64, """ + <g transform="translate(32 32)"> + <rect x="-6" y="-6" width="12" height="12" fill="red" transform="rotate(30)"/> + <g transform="scale(1.5, 0.75)"><circle cx="12" cy="-20" r="5" fill="blue"/></g> + <rect x="-28" y="10" width="14" height="10" fill="green" transform="skewX(20)"/> + <rect x="10" y="10" width="10" height="10" fill="orange" transform="matrix(1 0.3 -0.2 1 2 0) rotate(-15 15 15)"/> + </g>"""), + "stroke-styles": svg(64, 64, """ + <polyline points="6,20 18,6 30,20" fill="none" stroke="black" stroke-width="6" stroke-linejoin="miter"/> + <polyline points="36,20 48,6 60,20" fill="none" stroke="black" stroke-width="6" stroke-linejoin="round"/> + <polyline points="6,40 18,26 30,40" fill="none" stroke="black" stroke-width="6" stroke-linejoin="bevel"/> + <polyline points="36,40 48,38 60,40" fill="none" stroke="black" stroke-width="5" stroke-miterlimit="1.5"/> + <line x1="8" y1="48" x2="56" y2="48" stroke="blue" stroke-width="5" stroke-linecap="butt"/> + <line x1="8" y1="55" x2="56" y2="55" stroke="blue" stroke-width="5" stroke-linecap="round"/> + <line x1="8" y1="62" x2="56" y2="62" stroke="blue" stroke-width="3" stroke-linecap="square"/>"""), + "dashes": svg(64, 64, """ + <line x1="4" y1="8" x2="60" y2="8" stroke="black" stroke-width="3" stroke-dasharray="6 3"/> + <line x1="4" y1="18" x2="60" y2="18" stroke="red" stroke-width="3" stroke-dasharray="5,2,1" stroke-dashoffset="3"/> + <circle cx="20" cy="42" r="14" fill="none" stroke="blue" stroke-width="3" stroke-dasharray="8 4"/> + <rect x="40" y="30" width="20" height="24" fill="none" stroke="green" stroke-width="2" stroke-dasharray="4" stroke-linecap="round"/>"""), + "fill-rule": svg(64, 32, """ + <path d="M16 2 L22 30 L2 12 L30 12 L10 30 Z" fill="navy" fill-rule="nonzero"/> + <path d="M48 2 L54 30 L34 12 L62 12 L42 30 Z" fill="navy" fill-rule="evenodd"/>"""), + "opacity": svg(64, 64, """ + <rect x="2" y="2" width="60" height="60" fill="#eee"/> + <g opacity="0.5"><rect x="6" y="6" width="24" height="24" fill="red"/><rect x="16" y="16" width="24" height="24" fill="blue"/></g> + <rect x="34" y="6" width="24" height="24" fill="green" fill-opacity="0.4" stroke="black" stroke-width="4" stroke-opacity="0.6"/> + <circle cx="20" cy="48" r="12" fill="orange" stroke="purple" stroke-width="6" opacity="0.6"/> + <circle cx="46" cy="48" r="12" fill="rgba(0,0,255,0.5)"/>"""), + "linear-gradient": svg(64, 64, """ + <defs> + <linearGradient id="a"><stop offset="0" stop-color="red"/><stop offset="0.5" stop-color="yellow"/><stop offset="1" stop-color="blue"/></linearGradient> + <linearGradient id="b" x1="0" y1="0" x2="0.3" y2="0" spreadMethod="reflect"><stop offset="0" stop-color="#000"/><stop offset="1" stop-color="#fff"/></linearGradient> + <linearGradient id="c" x1="0" y1="0" x2="0.25" y2="0.25" spreadMethod="repeat"><stop offset="0%" stop-color="green"/><stop offset="100%" stop-color="white" stop-opacity="0.2"/></linearGradient> + <linearGradient id="d" gradientTransform="rotate(90 0.5 0.5)"><stop offset="0" stop-color="purple"/><stop offset="1" stop-color="orange"/></linearGradient> + </defs> + <rect x="2" y="2" width="60" height="12" fill="url(#a)"/> + <rect x="2" y="16" width="60" height="12" fill="url(#b)"/> + <rect x="2" y="30" width="28" height="30" fill="url(#c)"/> + <circle cx="47" cy="45" r="14" fill="url(#d)" stroke="url(#a)" stroke-width="3"/>"""), + "radial-gradient": svg(64, 64, """ + <defs> + <radialGradient id="r1"><stop offset="0" stop-color="white"/><stop offset="1" stop-color="blue"/></radialGradient> + <radialGradient id="r2" cx="0.5" cy="0.5" r="0.5" fx="0.25" fy="0.25"><stop offset="0" stop-color="yellow"/><stop offset="0.6" stop-color="red"/><stop offset="1" stop-color="black"/></radialGradient> + <radialGradient id="r3" gradientUnits="userSpaceOnUse" cx="16" cy="48" r="8" spreadMethod="repeat"><stop offset="0" stop-color="#fff"/><stop offset="1" stop-color="#080"/></radialGradient> + </defs> + <rect x="2" y="2" width="28" height="28" fill="url(#r1)"/> + <ellipse cx="47" cy="16" rx="15" ry="12" fill="url(#r2)"/> + <rect x="2" y="34" width="28" height="28" fill="url(#r3)"/> + <circle cx="47" cy="48" r="13" fill="url(#r2)" fill-opacity="0.7"/>"""), + "gradient-href": svg(64, 32, """ + <defs> + <linearGradient id="base"><stop offset="0" stop-color="#f00"/><stop offset="1" stop-color="#00f"/></linearGradient> + <linearGradient id="tilted" xlink:href="#base" x2="0" y2="1"/> + <radialGradient id="rad" href="#base"/> + </defs> + <rect x="2" y="2" width="28" height="28" fill="url(#tilted)"/> + <rect x="34" y="2" width="28" height="28" fill="url(#rad)"/>"""), + "css": svg(64, 64, """ + <style> + rect { fill: red; stroke: black } + .blue { fill: blue } + #special { fill: green; stroke-width: 4 } + circle.big, ellipse { fill: orange; } + /* a comment */ + @media print { rect { fill: pink } } + </style> + <rect x="4" y="4" width="20" height="20"/> + <rect x="30" y="4" width="20" height="20" class="blue"/> + <rect x="4" y="30" width="20" height="20" class="blue" id="special"/> + <rect x="30" y="30" width="20" height="20" class="blue" style="fill: purple"/> + <circle class="big" cx="58" cy="58" r="5"/> + <ellipse cx="10" cy="58" rx="6" ry="4" fill="black"/>"""), + "use-symbol": svg(64, 64, """ + <defs> + <g id="dot"><circle r="5" fill="red"/><circle r="2" fill="white"/></g> + <symbol id="sym" viewBox="0 0 10 10"><rect width="10" height="10" fill="blue"/><path d="M0 0 L10 10" stroke="white"/></symbol> + <rect id="bar" width="20" height="4"/> + </defs> + <use href="#dot" x="10" y="10"/> + <use xlink:href="#dot" transform="translate(30 10) scale(1.5)"/> + <use href="#sym" x="4" y="24" width="20" height="20"/> + <use href="#sym" x="30" y="24" width="30" height="15"/> + <use href="#bar" x="4" y="54" fill="green"/> + <use href="#bar" x="30" y="54" style="fill: orange" opacity="0.5"/>"""), + "viewbox-meet": svg(64, 40, """ + <rect width="100" height="100" fill="#ccc"/><circle cx="50" cy="50" r="40" fill="red"/>""", ' viewBox="0 0 100 100" preserveAspectRatio="xMinYMax meet"'), + "viewbox-slice": svg(64, 40, """ + <rect width="100" height="100" fill="#ccc"/><circle cx="50" cy="50" r="40" fill="blue"/>""", ' viewBox="0 0 100 100" preserveAspectRatio="xMidYMid slice"'), + "viewbox-none": svg(64, 40, """ + <rect width="100" height="100" fill="#ccc"/><circle cx="50" cy="50" r="40" fill="green"/>""", ' viewBox="0 0 100 100" preserveAspectRatio="none"'), + "nested-svg": svg(64, 64, """ + <rect width="64" height="64" fill="#eef"/> + <svg x="8" y="8" width="48" height="24" viewBox="0 0 20 10"><circle cx="5" cy="5" r="5" fill="red"/><circle cx="15" cy="5" r="5" fill="blue"/></svg> + <svg x="8" y="36" width="20" height="20"><rect x="5" y="5" width="50%" height="50%" fill="green"/><circle cx="20" cy="10" r="8" fill="red"/></svg>"""), + "clip-path": svg(64, 64, """ + <defs> + <clipPath id="c1"><circle cx="16" cy="16" r="12"/></clipPath> + <clipPath id="c2" clipPathUnits="objectBoundingBox"><rect x="0.25" y="0" width="0.5" height="1"/></clipPath> + <clipPath id="c3"><path d="M34 34 h26 v26 h-26z M40 40 h14 v14 h-14z" clip-rule="evenodd"/></clipPath> + </defs> + <rect x="2" y="2" width="30" height="30" fill="red" clip-path="url(#c1)"/> + <g clip-path="url(#c2)"><rect x="34" y="2" width="28" height="28" fill="blue"/><circle cx="48" cy="16" r="10" fill="yellow"/></g> + <rect x="2" y="34" width="28" height="28" fill="green" clip-path="url(#c2)"/> + <rect x="34" y="34" width="28" height="28" fill="purple" clip-path="url(#c3)"/>"""), + "units": svg(64, 64, """ + <rect x="2mm" y="2mm" width="10mm" height="5mm" fill="red"/> + <rect x="40pt" y="4" width="12pt" height="12pt" fill="blue"/> + <rect x="10%" y="50%" width="25%" height="10%" fill="green"/> + <circle cx="48" cy="48" r="1em" fill="orange" style="font-size: 8px"/> + <rect x="4" y="52" width="1in" height="0.1in" fill="black" transform="scale(0.5)"/>"""), + "colors": svg(64, 32, """ + <g color="teal"> + <rect x="0" y="0" width="8" height="16" fill="cornflowerblue"/> + <rect x="8" y="0" width="8" height="16" fill="#f80"/> + <rect x="16" y="0" width="8" height="16" fill="#ff008080"/> + <rect x="24" y="0" width="8" height="16" fill="rgb(10%, 50%, 90%)"/> + <rect x="32" y="0" width="8" height="16" fill="rgba(200, 0, 100, 0.5)"/> + <rect x="40" y="0" width="8" height="16" fill="hsl(120, 100%, 25%)"/> + <rect x="48" y="0" width="8" height="16" fill="currentColor"/> + <rect x="56" y="0" width="8" height="16" fill="transparent" stroke="currentColor"/> + <rect x="0" y="16" width="64" height="16" fill="none" stroke="DarkOrchid" stroke-width="4"/> + </g>"""), + "inheritance": svg(64, 64, """ + <g fill="red" stroke="blue" stroke-width="3"> + <rect x="4" y="4" width="24" height="24"/> + <g fill="green"><rect x="36" y="4" width="24" height="24" stroke="inherit"/></g> + <g style="stroke: none"><circle cx="16" cy="46" r="12"/></g> + <g display="none"><rect x="36" y="36" width="24" height="24"/></g> + <rect x="36" y="36" width="10" height="10" visibility="hidden"/> + <g visibility="hidden"><rect x="48" y="48" width="12" height="12" visibility="visible"/></g> + </g>"""), +} + + +def resvg(ctx, data, w, h): + with tempfile.TemporaryDirectory() as d: + src, png = os.path.join(d, "in.svg"), os.path.join(d, "out.png") + open(src, "wb").write(data) + argv = ["resvg", "-w", str(w), "-h", str(h), src, png] + if shutil.which("resvg"): + subprocess.run(argv, check=True, capture_output=True) + else: + subprocess.run(["nix", "shell", "nixpkgs#resvg", "-c"] + argv, check=True, capture_output=True) + argv = ["magick", png, "-depth", "8", "rgba:-"] + try: + return subprocess.run(argv, check=True, capture_output=True).stdout + except (OSError, subprocess.CalledProcessError): + return ctx.nix("imagemagick", argv) + + +def ours(ctx, text): + script = os.path.join(ctx.root, "tools", "fixtures", "_ours.luau") + luau = shutil.which("luau") + argv = [luau, script, "-a", "svg", text] if luau else ["nix", "shell", "nixpkgs#luau", "-c", "luau", script, "-a", "svg", text] + return json.loads(subprocess.run(argv, check=True, capture_output=True, cwd=ctx.root).stdout)["svg"] + + +def generate(ctx): + import re + cases = [] + for name, text in CASES.items(): + w, h = (int(x) for x in re.search(r'width="(\d+)" height="(\d+)"', text).groups()) + data = text.encode() + mine = ours(ctx, text) + cases.append({"name": name, "svg": data, "width": w, "height": h, "ref": resvg(ctx, data, w, h), "ours": mine, + "ours_ref": resvg(ctx, mine.encode(), w, h)}) + ctx.emit("svg", {"cases": cases}) diff --git a/tools/fixtures/tar.py b/tools/fixtures/tar.py new file mode 100644 index 0000000..4c7f03e --- /dev/null +++ b/tools/fixtures/tar.py @@ -0,0 +1,125 @@ +# tar + gzip fixtures (tools/fixtures.py): reference archives from Python's tarfile (ustar / GNU / pax formats, long +# names, non-ASCII names, links, directories, pax mtimes) and from the host / nix GNU tar (--format=ustar / gnu / +# posix / v7), gzip members from Python's gzip and the gzip CLI (FNAME, MTIME, levels, concatenated members), and +# compressed tars (.tar.gz, .tgz, .tar.zst, .tar.xz, .tar.bz2, .tar.br) for the api's unwrap. +# tests/gen/tar.luau { files = { { name, data, ... } }, writes = { { format, entries, data } }, tars = { { name, +# data, entries = { { name, size, type, link?, mtime, mode, crc } } } }, gzips = { ... }, +# wrapped = { { name, data, inner = "tar" } } } +import bz2, gzip, io, json, lzma, os, shutil, subprocess, tarfile, tempfile, zlib + + +def tool(name, pkg, argv, input=None, cwd=None): + exe = shutil.which(name) + cmd = ([exe] if exe else ["nix", "shell", "nixpkgs#" + pkg, "-c", name]) + argv + return subprocess.run(cmd, input=input, capture_output=True, check=True, cwd=cwd).stdout + + +def entries_of(data): + out = [] + with tarfile.open(fileobj=io.BytesIO(data)) as t: + for m in t.getmembers(): + e = {"name": m.name + ("/" if m.isdir() and not m.name.endswith("/") else ""), "type": m.type.decode() if m.type != b"\0" else "0", + "size": m.size if m.isfile() else 0, "mtime": m.mtime, "mode": m.mode} + if m.issym() or m.islnk(): + e["link"] = m.linkname + if m.isfile(): + e["crc"] = zlib.crc32(t.extractfile(m).read()) + out.append(e) + return out + + +def generate(ctx): + rng = ctx.rng(5) + files = [ + ("hello.txt", b"hello, tar\n"), + ("empty", b""), + ("dir/sub/data.bin", rng.randbytes(3000)), + ("exact512", bytes(range(256)) * 2), + ("d" * 60 + "/" + "e" * 60 + "/long-name-over-100-bytes.txt", b"long " * 50), + ("x" * 150, b"no slash to split at"), + ("unicodé/naïve-ファイル.txt", "ünïcödé".encode()), + ] + # the writer test: the same entries through Python's tarfile in three formats (fixed metadata) + writes = [] + for fmt, pf in (("ustar", tarfile.USTAR_FORMAT), ("gnu", tarfile.GNU_FORMAT), ("pax", tarfile.PAX_FORMAT)): + buf = io.BytesIO() + with tarfile.open(fileobj=buf, mode="w", format=pf) as t: + ents = [] + for name, data in files: + if fmt == "ustar" and (not name.isascii() or name.startswith("x" * 101)): + continue + ti = tarfile.TarInfo(name) + ti.size, ti.mtime, ti.mode, ti.uname, ti.gname = len(data), 1700000000, 0o644, "user", "group" + t.addfile(ti, io.BytesIO(data)) + ents.append({"name": name, "data": data}) + ti = tarfile.TarInfo("adir") + ti.type, ti.mtime, ti.mode, ti.uname, ti.gname = tarfile.DIRTYPE, 1700000000, 0o755, "user", "group" + t.addfile(ti) + ents.append({"name": "adir", "dir": True}) + ti = tarfile.TarInfo("link-to-hello") + ti.type, ti.linkname, ti.mtime, ti.mode, ti.uname, ti.gname = tarfile.SYMTYPE, "hello.txt", 1700000000, 0o777, "user", "group" + t.addfile(ti) + ents.append({"name": "link-to-hello", "type": "2", "link": "hello.txt", "mode": 0o777}) + writes.append({"format": fmt, "entries": ents, "data": buf.getvalue()}) + + tars = [] + for w in writes: + tars.append({"name": "python-" + w["format"], "data": w["data"], "entries": entries_of(w["data"])}) + # pax with a fractional mtime and a huge uid + buf = io.BytesIO() + with tarfile.open(fileobj=buf, mode="w", format=tarfile.PAX_FORMAT) as t: + ti = tarfile.TarInfo("frac.txt") + ti.size, ti.mtime, ti.uid = 3, 1600000000.5, 3000000 + t.addfile(ti, io.BytesIO(b"abc")) + tars.append({"name": "python-pax-extras", "data": buf.getvalue(), "entries": entries_of(buf.getvalue())}) + # GNU tar on a real tree + tmp = tempfile.mkdtemp() + try: + root = os.path.join(tmp, "tree") + for name, data in files: + p = os.path.join(root, name) + os.makedirs(os.path.dirname(p), exist_ok=True) + with open(p, "wb") as f: + f.write(data) + os.makedirs(os.path.join(root, "emptydir")) + os.symlink("hello.txt", os.path.join(root, "sym")) + os.link(os.path.join(root, "hello.txt"), os.path.join(root, "hard")) + for dirpath, dirs, fs in os.walk(root): + for n in dirs + fs: + os.utime(os.path.join(dirpath, n), (1650000000, 1650000000), follow_symlinks=False) + for fmt in ("ustar", "gnu", "posix", "v7"): + argv = ["--format=" + fmt, "--sort=name", "--owner=0", "--group=0", "--numeric-owner", "-cf", "-", "."] + if fmt in ("ustar", "v7"): + argv = ["--exclude=./" + "x" * 150, "--exclude=./d" + "d" * 59] + argv + if fmt == "v7": + argv = ["--exclude=./unicodé"] + argv + data = tool("tar", "gnutar", argv, cwd=root) + tars.append({"name": "gnutar-" + fmt, "data": data, "entries": entries_of(data)}) + finally: + shutil.rmtree(tmp) + + # gzip + text = ("The quick brown fox jumps over the lazy dog. " * 300).encode() + gzips = [] + b = io.BytesIO() + with gzip.GzipFile(filename="story.txt", mode="wb", fileobj=b, mtime=1234567890, compresslevel=9) as g: + g.write(text) + gzips.append({"name": "python-fname", "data": b.getvalue(), "entry": "story.txt", "mtime": 1234567890, "crc": zlib.crc32(text), "size": len(text)}) + gzips.append({"name": "python-noname", "data": gzip.compress(text, 1, mtime=0), "entry": "data", "mtime": 0, "crc": zlib.crc32(text), "size": len(text)}) + cli = tool("gzip", "gzip", ["-9", "-n", "-c"], input=text) + gzips.append({"name": "cli-n", "data": cli, "entry": "data", "mtime": 0, "crc": zlib.crc32(text), "size": len(text)}) + two = gzip.compress(text[:1000], mtime=0) + gzip.compress(text[1000:], mtime=0) + gzips.append({"name": "members", "data": two, "entry": "data", "mtime": 0, "crc": zlib.crc32(text), "size": len(text)}) + + # compressed tars + inner = writes[2]["data"] + wrapped = [ + {"name": "a.tar.gz", "data": gzip.compress(inner, mtime=0), "outer": "gzip"}, + {"name": "a.tgz", "data": tool("gzip", "gzip", ["-c", "-n"], input=inner), "outer": "gzip"}, + {"name": "a.tar.bz2", "data": bz2.compress(inner), "outer": "bz2"}, + {"name": "a.tar.xz", "data": lzma.compress(inner), "outer": "xz"}, + {"name": "a.tar.zst", "data": tool("zstd", "zstd", ["-c", "-q"], input=inner), "outer": "zst"}, + {"name": "a.tar.br", "data": ctx.python(["brotli"], "import brotli, sys; sys.stdout.buffer.write(brotli.compress(sys.stdin.buffer.read()))", input=inner), "outer": "br"}, + ] + ctx.emit("tar", {"files": [{"name": n, "data": d} for n, d in files], "writes": writes, "tars": tars, + "gzips": gzips, "wrapped": wrapped, "innerEntries": entries_of(inner)}) diff --git a/tools/fixtures/tga.py b/tools/fixtures/tga.py new file mode 100644 index 0000000..a6a2e46 --- /dev/null +++ b/tools/fixtures/tga.py @@ -0,0 +1,87 @@ +# TGA fixtures (tools/fixtures.py): files written by Pillow (RGB / RGBA / L / P / LA, raw and RLE, both origins) and +# ImageMagick (raw / RLE, palette, grey), plus hand-written ones (15 / 16-bit pixels and colour maps, 8 / 16-bit +# indexes with a first index, right-to-left, RLE packets crossing rows, an image ID, 16-bit grey + alpha); +# references = Pillow's RGBA decodes, ImageMagick's for the files Pillow +# refuses (right-to-left, 16-bit grey + alpha) and for 15 / 16-bit colour, where Pillow differs (5-bit scaling, alpha). +# tests/gen/tga.luau { { name, data, width, height, rgba (bytes) } } +import struct + +CODE = r''' +import io, os, random, struct, subprocess, sys +from PIL import Image +magick = sys.argv[1] +rng = random.Random(9) +out = [] +def emit(name, data, magick_ref=False): + try: + if magick_ref: + raise ValueError("15 / 16-bit: Pillow scales 5-bit values by x * 255 // 31 and inverts the alpha bit") + im = Image.open(io.BytesIO(data)) + rgba = im.convert("RGBA").tobytes() + size = im.size + except Exception: + # files Pillow refuses (right-to-left, 16-bit grey + alpha): ImageMagick's decode + info = subprocess.run([magick, "tga:-", "-format", "%w %h", "info:"], input=data, capture_output=True, check=True).stdout.split() + size = (int(info[0]), int(info[1])) + rgba = subprocess.run([magick, "tga:-", "-depth", "8", "rgba:-"], input=data, capture_output=True, check=True).stdout + out.append((name, data, size, rgba)) +w, h = 29, 17 +px = bytearray() +for y in range(h): + for x in range(w): + a = 255 if (x + y) % 4 else (x * 37) % 256 + px += bytes(((x * 9) % 256, (y * 15) % 256, rng.randrange(256) if x % 3 == 0 else 100, a)) +rgba = Image.frombytes("RGBA", (w, h), bytes(px)) +for mode in ("RGB", "RGBA", "L", "LA", "P"): + im = rgba.convert(mode) if mode != "P" else rgba.convert("RGB").quantize(37) + for comp in (None, "tga_rle"): + for orient in (1, -1): + b = io.BytesIO() + kw = {"orientation": orient} + if comp: + kw["compression"] = comp + im.save(b, "TGA", **kw) + emit("pil-%s-%s-%s" % (mode, comp or "raw", "top" if orient == 1 else "bottom"), b.getvalue()) +# runs that cross rows (RLE) +flat = Image.new("RGB", (13, 9), (10, 20, 30)) +for x in range(5): + flat.putpixel((x, 4), (200, 0, 0)) +b = io.BytesIO(); flat.save(b, "TGA", compression="tga_rle"); emit("pil-runs", b.getvalue()) +# ImageMagick writers +src = io.BytesIO(); rgba.save(src, "PNG") +for name, args in (("im-rgba", []), ("im-rle", ["-compress", "RLE"]), ("im-gray", ["-colorspace", "gray"]), ("im-palette", ["-colors", "20", "-type", "Palette"]), + ("im-rgb", ["-alpha", "off"])): + r = subprocess.run([magick, "png:-"] + args + ["tga:-"], input=src.getvalue(), capture_output=True, check=True) + emit(name, r.stdout) +# hand-written +def hdr(idlen, cmt, it, cfirst, clen, cbits, w, h, depth, desc): + return struct.pack("<BBBHHBHHHHBB", idlen, cmt, it, cfirst, clen, cbits, 0, 0, w, h, depth, desc) +def p15(r, g, b, a=1): + return struct.pack("<H", (a << 15) | ((r >> 3) << 10) | ((g >> 3) << 5) | (b >> 3)) +cols = [((i * 40) % 256, (i * 90) % 256, (255 - i * 20) % 256) for i in range(12)] +w, h = 6, 4 +idx = [(x + y * 2) % 12 for y in range(h) for x in range(w)] +emit("hand-16bit", hdr(0, 0, 2, 0, 0, 0, w, h, 16, 0) + b"".join(p15(*cols[i]) for i in idx), magick_ref=True) +emit("hand-15bit-rtl", hdr(0, 0, 2, 0, 0, 0, w, h, 15, 0x10) + b"".join(p15(*cols[i], a=0) for i in idx), magick_ref=True) +emit("hand-cmap16", hdr(0, 1, 1, 0, 12, 16, w, h, 8, 0x20) + b"".join(p15(*c) for c in cols) + bytes(idx), magick_ref=True) +emit("hand-cmap32-first", hdr(0, 1, 1, 4, 12, 32, w, h, 8, 0x28) + b"".join(bytes((c[2], c[1], c[0], 77)) for c in cols) + bytes(i + 4 for i in idx)) +emit("hand-cmap24-rle", hdr(0, 1, 9, 0, 12, 24, w, h, 8, 0) + b"".join(bytes((c[2], c[1], c[0])) for c in cols) + bytes([0x80 + 9, 3, 0x05, 1, 2, 3, 4, 5, 6, 0x80 + 7, 11])) +emit("hand-id-top", hdr(5, 0, 3, 0, 0, 0, w, h, 8, 0x20) + b"hello" + bytes((i * 21) % 256 for i in idx)) +emit("hand-graya16", hdr(0, 0, 3, 0, 0, 0, w, h, 16, 0x28) + b"".join(bytes(((i * 21) % 256, (i * 50) % 256)) for i in idx)) +emit("hand-rle32-cross", hdr(0, 0, 10, 0, 0, 0, 5, 3, 32, 0x28) + bytes([0x80 + 6, 1, 2, 3, 200, 0x08]) + bytes(range(9 * 4))) +for name, data, size, rgba in out: + sys.stdout.buffer.write(struct.pack("<HIIII", len(name), len(data), size[0], size[1], len(rgba)) + name.encode() + data + rgba) +''' + + +def generate(ctx): + magick = ctx.nix("imagemagick", ["sh", "-c", "command -v magick"]).decode().strip() + raw = ctx.python(["pillow"], CODE.replace("sys.argv[1]", repr(magick))) + cases, p = [], 0 + while p < len(raw): + nl, dl, w, h, rl = struct.unpack("<HIIII", raw[p:p + 18]); p += 18 + name = raw[p:p + nl].decode(); p += nl + data = raw[p:p + dl]; p += dl + rgba = raw[p:p + rl]; p += rl + cases.append({"name": name, "data": data, "width": w, "height": h, "rgba": rgba}) + ctx.emit("tga", cases) diff --git a/tools/fixtures/tiff.py b/tools/fixtures/tiff.py new file mode 100644 index 0000000..d6ed3b3 --- /dev/null +++ b/tools/fixtures/tiff.py @@ -0,0 +1,226 @@ +# TIFF fixtures (tools/fixtures.py): files written by tifffile (+ imagecodecs) and ImageMagick, with references from +# tifffile's decode (the native sample arrays) turned into what image/tiff must produce. +# tests/gen/tiff.luau { cases = { { name, data, width, height, pages = { { crc, native, ncrc } } } }, +# jpeg = data (a JPEG-compressed TIFF for the decodeImage hook test), +# jpegRef = { width, height, rgb } (tifffile + imagecodecs' libjpeg-turbo decode of it) } +# crc CRC-32 of the default rgba8 decode +# native / ncrc: the opts.native pixel format and the CRC-32 of its little-endian bytes +# Every case is decoded by tifffile; the expected pixels follow image/tiff's rules: unsigned samples v / (2^bits - 1), +# floats as stored, min-is-white inverted, palette = ColorMap / 65535, CMYK r = (1 - c)(1 - k), associated alpha +# divided out, then 8-bit = floor(clamp(u) * 255 + 0.5) (16-bit: * 65535). +import os, shutil, struct, subprocess, tempfile + +CODE = r''' +import os, struct, sys, zlib +import numpy as np, tifffile +work = WORK +magick = MAGICK +rng = np.random.default_rng(5) +H, W = 37, 53 +yy, xx = np.mgrid[0:H, 0:W] +def ramp(maxv, ch): + base = [(xx * 7 + yy * 3) % 256, (xx * 255 // (W - 1)), (yy * 255 // (H - 1)), 255 - ((xx ^ yy) & 63)] + a = np.stack([b for b in base[:ch]], -1).astype(np.float64) / 255.0 + noise = rng.random(a.shape) < 0.2 + a = np.where(noise, rng.random(a.shape), a) + return np.squeeze(np.round(a * maxv)) +cases = [] +def add(name, path): + cases.append((name, path)) +def tw(name, data, **kw): + p = os.path.join(work, name + ".tif") + tifffile.imwrite(p, data, **kw) + add(name, p) +rgb8 = ramp(255, 3).astype(np.uint8) +rgba8 = ramp(255, 4).astype(np.uint8) +gray8 = ramp(255, 1).astype(np.uint8) +gray16 = ramp(65535, 1).astype(np.uint16) +rgb16 = ramp(65535, 3).astype(np.uint16) +rgba16 = ramp(65535, 4).astype(np.uint16) +f32 = (ramp(1000, 3) / 1000.0 * 1.2 - 0.1).astype(np.float32) +for comp in (None, "lzw", "zlib", "adobe_deflate", "packbits"): + cn = comp or "none" + tw("rgb8_" + cn, rgb8, photometric="rgb", compression=comp) + tw("gray16_" + cn, gray16, photometric="minisblack", compression=comp) +for comp in ("lzw", "zlib"): + tw("rgb8_pred_" + comp, rgb8, photometric="rgb", compression=comp, predictor=True) + tw("rgba16_pred_be_" + comp, rgba16, photometric="rgb", compression=comp, predictor=True, byteorder=">", extrasamples=["unassalpha"]) + tw("gray16_pred_" + comp, gray16, photometric="minisblack", compression=comp, predictor=True) + tw("f32_fpred_" + comp, f32, photometric="rgb", compression=comp, predictor=3) + tw("f32_fpred_be_" + comp, f32, photometric="rgb", compression=comp, predictor=3, byteorder=">") +tw("rgba8_assoc", rgba8, photometric="rgb", extrasamples=["assocalpha"]) +tw("rgba8_unassoc_tiles", rgba8, photometric="rgb", extrasamples=["unassalpha"], tile=(16, 16), compression="zlib") +tw("rgb8_planar", np.ascontiguousarray(np.moveaxis(rgb8, -1, 0)), photometric="rgb", planarconfig="separate", compression="lzw") +tw("rgb16_planar_tiles_be", np.ascontiguousarray(np.moveaxis(rgb16, -1, 0)), photometric="rgb", planarconfig="separate", tile=(32, 16), byteorder=">", compression="zlib", predictor=True) +tw("rgb8_strips5", rgb8, photometric="rgb", rowsperstrip=5, compression="packbits") +tw("rgb8_bigtiff", rgb8, photometric="rgb", bigtiff=True, compression="zlib") +tw("rgb8_bigtiff_be_tiles", rgb8, photometric="rgb", bigtiff=True, byteorder=">", tile=(16, 32)) +tw("gray8_miniswhite", gray8, photometric="miniswhite") +tw("gray8_be", gray8, photometric="minisblack", byteorder=">") +tw("f16_gray", (gray16 / 65535.0).astype(np.float16), photometric="minisblack") +tw("f64_rgb", (f32.astype(np.float64)), photometric="rgb") +tw("f32_gray_tiles", f32[:, :, 0].copy(), photometric="minisblack", tile=(16, 16), compression="zlib") +tw("int16_gray", (gray16.astype(np.int32) - 32768).astype(np.int16), photometric="minisblack") +tw("int8_gray", (gray8.astype(np.int16) - 128).astype(np.int8), photometric="minisblack") +tw("u32_gray", (gray16.astype(np.uint32) * 65537), photometric="minisblack", compression="zlib") +cm = (rng.integers(0, 65536, (3, 256))).astype(np.uint16) +tw("palette8", gray8, photometric="palette", colormap=cm, compression="lzw") +tw("gray4", (gray8 >> 4).astype(np.uint8), photometric="minisblack", bitspersample=4) +tw("gray2_lzw", (gray8 >> 6).astype(np.uint8), photometric="minisblack", bitspersample=2, compression=None) +tw("bilevel", gray8 > 127, photometric="minisblack") +tw("bilevel_white_packbits", gray8 > 100, photometric="miniswhite", compression="packbits") +tw("gray12", (gray16 >> 4).astype(np.uint16), photometric="minisblack", bitspersample=12) +tw("cmyk8", ramp(255, 4).astype(np.uint8), photometric="separated", compression="lzw") +tw("graya8", np.stack([gray8, rgba8[:, :, 3]], -1), photometric="minisblack", extrasamples=["unassalpha"]) +with tifffile.TiffWriter(os.path.join(work, "pages3.tif")) as t: + t.write(rgb8, photometric="rgb", compression="zlib") + t.write(gray16, photometric="minisblack", compression="lzw") + t.write(rgba8, photometric="rgb", extrasamples=["unassalpha"]) +add("pages3", os.path.join(work, "pages3.tif")) +# ImageMagick +import subprocess +src = os.path.join(work, "src.png") +from PIL import Image +Image.fromarray(rgba8, "RGBA").save(src) +srgb = os.path.join(work, "srgb.png") +Image.fromarray(rgb8, "RGB").save(srgb) +def im(name, *args, s=srgb): + p = os.path.join(work, name + ".tif") + subprocess.run([magick, s] + list(args) + [p], check=True, capture_output=True) + add(name, p) +im("im_lzw", "-compress", "LZW") +im("im_zip_pred", "-compress", "Zip", "-define", "tiff:predictor=2") +im("im_rle", "-compress", "RLE") +im("im_none_msb", "-compress", "None", "-endian", "MSB") +im("im_tiles", "-compress", "LZW", "-define", "tiff:tile-geometry=32x32") +im("im_plane", "-compress", "Zip", "-interlace", "plane") +im("im_16", "-depth", "16", "-compress", "LZW") +im("im_float", "-depth", "32", "-define", "quantum:format=floating-point", "-compress", "Zip") +im("im_alpha", "-compress", "LZW", s=src) +im("im_alpha_assoc", "-define", "tiff:alpha=associated", s=src) +im("im_gray4", "-colorspace", "gray", "-depth", "4") +im("im_bilevel", "-monochrome") +im("im_palette", "-type", "palette", "-compress", "LZW") +im("im_palette4", "-colors", "12", "-type", "palette", "-depth", "4") +im("im_cmyk", "-colorspace", "CMYK", "-compress", "LZW") +p = os.path.join(work, "im_multi.tif") +subprocess.run([magick, srgb, src, srgb, "-compress", "Zip", p], check=True, capture_output=True) +add("im_multi", p) +jp = os.path.join(work, "im_jpeg.tif") +subprocess.run([magick, srgb, "-compress", "JPEG", jp], check=True, capture_output=True) + +def expect(page): + a = page.asarray() + spp = page.samplesperpixel + if spp > 1 and page.planarconfig == 2: + a = np.moveaxis(a, 0, -1) + if a.ndim == 2: + a = a[:, :, None] + a = a.reshape(page.imagelength, page.imagewidth, spp) + photo = int(page.photometric) + bps = page.bitspersample + fmt = int(page.sampleformat) + cc = 3 if photo in (2, 6) else (4 if photo == 5 else 1) + alpha = cc if spp > cc else -1 + ex = page.extrasamples + assoc = alpha >= 0 and len(ex) > 0 and int(ex[0]) == 1 + maxv = float(2 ** min(bps, 32) - 1) + if fmt == 3: + u = a.astype(np.float64) + elif fmt == 2: + u = (a.astype(np.float64) + 2 ** (bps - 1)) / maxv + else: + u = a.astype(np.float64) / maxv + if photo == 3: + cmap = page.colormap.astype(np.float64) / 65535.0 + idx = a[:, :, 0].astype(np.int64) + rgb = np.stack([cmap[0][idx], cmap[1][idx], cmap[2][idx]], -1) + elif photo == 2: + rgb = u[:, :, 0:3] + elif photo == 5: + c, m, y, k = u[:, :, 0], u[:, :, 1], u[:, :, 2], u[:, :, 3] + rgb = np.stack([(1 - c) * (1 - k), (1 - m) * (1 - k), (1 - y) * (1 - k)], -1) + else: + v = u[:, :, 0] + if photo == 0: + v = 1 - v + rgb = np.stack([v, v, v], -1) + if alpha >= 0: + al = u[:, :, alpha] + if assoc: + safe = np.where(al > 0, al, 1) + rgb = np.where((al > 0)[:, :, None], np.minimum(rgb / safe[:, :, None], 1), 0) + else: + al = np.ones(rgb.shape[:2]) + def q(x, m): + return np.floor(np.clip(np.nan_to_num(x), 0, 1) * m + 0.5) + rgba = np.concatenate([rgb, al[:, :, None]], -1) + out8 = q(rgba, 255).astype(np.uint8) + crc = zlib.crc32(out8.tobytes()) + # native + if photo in (3, 5): + kind, nat = "rgba8", out8 + elif fmt == 3: + kind, nat = "rgbaf32", rgba.astype("<f4") + elif cc == 1: + if alpha >= 0: + if bps <= 8: + kind, nat = "graya8", q(np.stack([rgb[:, :, 0], al], -1), 255).astype(np.uint8) + else: + kind, nat = "rgba16", q(rgba, 65535).astype("<u2") + else: + if bps <= 8: + kind, nat = "gray8", q(rgb[:, :, 0], 255).astype(np.uint8) + else: + kind, nat = "gray16", q(rgb[:, :, 0], 65535).astype("<u2") + else: + if bps <= 8: + kind, nat = ("rgba8", out8) if alpha >= 0 else ("rgb8", out8[:, :, 0:3].copy()) + else: + kind, nat = "rgba16", q(rgba, 65535).astype("<u2") + return crc, kind, zlib.crc32(np.ascontiguousarray(nat).tobytes()) + +def emit(b): + sys.stdout.buffer.write(struct.pack("<I", len(b)) + b) +emit(str(len(cases)).encode()) +for name, path in cases: + with tifffile.TiffFile(path) as t: + pages = [p for p in t.pages if not (int(p.subfiletype) & 1)] + info = [] + for pg in pages: + info.append("%d:%s:%d" % expect(pg)) + w, h = pages[0].imagewidth, pages[0].imagelength + emit(name.encode()); emit(open(path, "rb").read()); emit(("%d %d " % (w, h) + " ".join(info)).encode()) +emit(open(jp, "rb").read()) +with tifffile.TiffFile(jp) as t: + a = t.pages[0].asarray() + emit(("%d %d" % (a.shape[1], a.shape[0])).encode()) + emit(np.ascontiguousarray(a[:, :, 0:3]).astype(np.uint8).tobytes()) +''' + + +def generate(ctx): + magick = ctx.nix("imagemagick", ["sh", "-c", "command -v magick"]).decode().strip() + work = tempfile.mkdtemp(prefix="formats-tiff-") + try: + raw = ctx.python(["pillow", "tifffile", "numpy", "imagecodecs"], CODE.replace("WORK", repr(work)).replace("MAGICK", repr(magick))) + finally: + shutil.rmtree(work, ignore_errors=True) + p = 0 + items = [] + while p < len(raw): + n = struct.unpack("<I", raw[p:p + 4])[0] + items.append(raw[p + 4:p + 4 + n]) + p += 4 + n + count = int(items[0]) + cases = [] + for i in range(count): + name, data, info = items[1 + i * 3], items[2 + i * 3], items[3 + i * 3].decode().split() + pages = [] + for s in info[2:]: + crc, kind, ncrc = s.split(":") + pages.append({"crc": int(crc), "native": kind, "ncrc": int(ncrc)}) + cases.append({"name": name.decode(), "data": data, "width": int(info[0]), "height": int(info[1]), "pages": pages}) + jw, jh = map(int, items[2 + count * 3].decode().split()) + ctx.emit("tiff", {"cases": cases, "jpeg": items[1 + count * 3], + "jpegRef": {"width": jw, "height": jh, "rgb": items[3 + count * 3]}}) diff --git a/tools/fixtures/tiled.py b/tools/fixtures/tiled.py new file mode 100644 index 0000000..cf3804f --- /dev/null +++ b/tools/fixtures/tiled.py @@ -0,0 +1,279 @@ +# Tiled fixtures (tools/fixtures.py), with Tiled itself (nixpkgs#tiled, run headless) as the reference: +# tests/gen/tiled.luau { cases = { { name, tmx (hand-written), tmj (Tiled's export), tiled_tmx (Tiled's re-save) } }, +# tsx, tsj (an external tileset and Tiled's JSON export of it) } +# tests/gen/tiled_ours.luau { checks = { { label, ok } } }: a map built and written by our encoder (TMX with +# base64 + zlib data, and TMJ; tools/fixtures/_ours.luau) re-exported by Tiled as JSON and +# compared with our own TMJ +import base64, gzip, json, os, shutil, struct, subprocess, tempfile, zlib + +INPUTS = ["src/Formats/vector/tiled", "tools/fixtures/_ours.luau"] + +TSX = """<?xml version="1.0" encoding="UTF-8"?> +<tileset version="1.10" tiledversion="1.10.2" name="ext" tilewidth="16" tileheight="16" spacing="0" margin="0" tilecount="8" columns="4"> + <tileoffset x="2" y="-3"/> + <properties> + <property name="kind" value="terrain"/> + </properties> + <image source="tiles.png" width="64" height="32"/> + <tile id="1" type="Water" probability="0.5"> + <properties> + <property name="speed" type="float" value="0.25"/> + </properties> + <animation> + <frame tileid="1" duration="100"/> + <frame tileid="2" duration="150"/> + </animation> + </tile> + <tile id="5"> + <objectgroup draworder="index" id="2"> + <object id="1" x="1" y="2" width="10" height="12"/> + <object id="2" x="3" y="3"> + <ellipse/> + </object> + </objectgroup> + </tile> +</tileset> +""" + + +def layer_bytes(gids): + return b"".join(struct.pack("<I", g) for g in gids) + + +def ortho(): + W, H = 6, 4 + g1 = [(x + y * W) % 9 for y in range(H) for x in range(W)] + g1[3] |= 0x80000000 + g1[7] |= 0x40000000 + g1[11] |= 0x20000000 + g2 = [(x * y) % 5 for y in range(H) for x in range(W)] + g3 = [9 + (x + y) % 8 if (x + y) % 3 else 0 for y in range(H) for x in range(W)] + g4 = [1 + (x % 2) for y in range(H) for x in range(W)] + csv = ",\n".join(",".join(str(g) for g in g1[y * W:(y + 1) * W]) for y in range(H)) + z = base64.b64encode(zlib.compress(layer_bytes(g2))).decode() + gz = base64.b64encode(gzip.compress(layer_bytes(g3), mtime=0)).decode() + raw = base64.b64encode(layer_bytes(g4)).decode() + return f"""<?xml version="1.0" encoding="UTF-8"?> +<map version="1.10" tiledversion="1.10.2" class="Level" orientation="orthogonal" renderorder="left-up" width="{W}" height="{H}" tilewidth="16" tileheight="16" backgroundcolor="#ff102030" infinite="0" nextlayerid="9" nextobjectid="10"> + <properties> + <property name="title" value="Ünïcode & more"/> + <property name="count" type="int" value="42"/> + <property name="ratio" type="float" value="1.5"/> + <property name="on" type="bool" value="true"/> + <property name="tint" type="color" value="#80ff0000"/> + <property name="file" type="file" value="other.tmx"/> + <property name="target" type="object" value="3"/> + <property name="notes">line one +line two</property> + </properties> + <tileset firstgid="1" name="inner" tilewidth="16" tileheight="16" spacing="0" margin="0" tilecount="8" columns="4"> + <image source="tiles.png" width="64" height="32"/> + <tile id="0"> + <properties> + <property name="solid" type="bool" value="true"/> + </properties> + </tile> + <tile id="3" type="Door"/> + </tileset> + <tileset firstgid="9" source="ext.tsx"/> + <layer id="1" name="csv" width="{W}" height="{H}" opacity="0.75" offsetx="3" offsety="-2" tintcolor="#ff00ff"> + <properties> + <property name="layerprop" value="x"/> + </properties> + <data encoding="csv"> +{csv} +</data> + </layer> + <layer id="2" name="zlib" width="{W}" height="{H}" visible="0" parallaxx="0.5"> + <data encoding="base64" compression="zlib"> + {z} + </data> + </layer> + <layer id="3" name="gzip" width="{W}" height="{H}" locked="1"> + <data encoding="base64" compression="gzip"> + {gz} + </data> + </layer> + <layer id="4" name="raw" class="Deco" width="{W}" height="{H}"> + <data encoding="base64"> + {raw} + </data> + </layer> + <group id="5" name="group" opacity="0.5" offsetx="1"> + <imagelayer id="6" name="sky" repeatx="1"> + <image source="sky.png" width="40" height="20"/> + </imagelayer> + <objectgroup id="7" name="things" color="#a0a0a4" draworder="index"> + <object id="1" name="box" type="Crate" x="10" y="12.5" width="16" height="8" rotation="45"> + <properties> + <property name="weight" type="float" value="2.25"/> + </properties> + </object> + <object id="2" name="ring" x="40" y="5" width="10" height="10"> + <ellipse/> + </object> + <object id="3" name="spot" x="7" y="9"> + <point/> + </object> + <object id="4" name="poly" x="20" y="20"> + <polygon points="0,0 16,0 8,-12.5"/> + </object> + <object id="5" name="line" x="30" y="30" visible="0"> + <polyline points="0,0 5,5 10,0 15,5"/> + </object> + <object id="6" name="label" x="2" y="40" width="80" height="20"> + <text fontfamily="Serif" pixelsize="12" wrap="1" color="#ff0000" bold="1" halign="center" valign="bottom">Hello <Tiled></text> + </object> + <object id="7" name="tile" gid="2147483651" x="50" y="50" width="16" height="16"/> + </objectgroup> + </group> +</map> +""" + + +def iso(): + W, H = 3, 3 + tiles = "\n".join(' <tile gid="%d"/>' % ((x + y) % 4) for y in range(H) for x in range(W)) + return f"""<?xml version="1.0" encoding="UTF-8"?> +<map version="1.10" tiledversion="1.10.2" orientation="hexagonal" renderorder="right-down" width="{W}" height="{H}" tilewidth="32" tileheight="28" infinite="0" hexsidelength="14" staggeraxis="x" staggerindex="even" nextlayerid="2" nextobjectid="1"> + <tileset firstgid="1" name="inner" tilewidth="16" tileheight="16" tilecount="8" columns="4"> + <image source="tiles.png" width="64" height="32"/> + </tileset> + <layer id="1" name="xmltiles" width="{W}" height="{H}"> + <data> +{tiles} + </data> + </layer> +</map> +""" + + +def infinite(): + def chunk(cx, cy): + g = [(cx // 16 + cy // 16 + x + y) % 5 for y in range(16) for x in range(16)] + rows = ",\n".join(",".join(str(v) for v in g[y * 16:(y + 1) * 16]) for y in range(16)) + return f' <chunk x="{cx}" y="{cy}" width="16" height="16">\n{rows}\n</chunk>' + # Tiled's canonical layout: chunks by row, the layer's size = the chunks' bounds + chunks = "\n".join(chunk(cx, cy) for cx, cy in ((16, -16), (-16, 0), (0, 0))) + return f"""<?xml version="1.0" encoding="UTF-8"?> +<map version="1.10" tiledversion="1.10.2" orientation="orthogonal" renderorder="right-down" width="30" height="20" tilewidth="16" tileheight="16" infinite="1" nextlayerid="2" nextobjectid="1"> + <tileset firstgid="1" name="inner" tilewidth="16" tileheight="16" tilecount="8" columns="4"> + <image source="tiles.png" width="64" height="32"/> + </tileset> + <layer id="1" name="chunks" width="48" height="32"> + <data encoding="csv"> +{chunks} + </data> + </layer> +</map> +""" + + +def tiled(ctx, argv, cwd): + env = dict(os.environ, QT_QPA_PLATFORM="offscreen") + if shutil.which("tiled"): + subprocess.run(["tiled"] + argv, check=True, capture_output=True, cwd=cwd, env=env) + else: + subprocess.run(["nix", "shell", "nixpkgs#tiled", "-c", "tiled"] + argv, check=True, capture_output=True, cwd=cwd, env=env) + + +def magick(ctx, argv): + try: + subprocess.run(argv, check=True, capture_output=True) + except (OSError, subprocess.CalledProcessError): + ctx.nix("imagemagick", argv) + + +def workdir(ctx, d): + magick(ctx, ["magick", "-size", "64x32", "gradient:red-blue", os.path.join(d, "tiles.png")]) + magick(ctx, ["magick", "-size", "40x20", "xc:skyblue", os.path.join(d, "sky.png")]) + open(os.path.join(d, "ext.tsx"), "w").write(TSX) + + +def run_ours(ctx, fmt): + script = os.path.join(ctx.root, "tools", "fixtures", "_ours.luau") + luau = shutil.which("luau") + argv = [luau, script, "-a", fmt] if luau else ["nix", "shell", "nixpkgs#luau", "-c", "luau", script, "-a", fmt] + return json.loads(subprocess.run(argv, check=True, capture_output=True, cwd=ctx.root).stdout) + + +def gids(layer): + """a JSON tile layer's gids (arrays, or base64 with compression) -> list""" + d = layer.get("data") + if isinstance(d, str): + raw = base64.b64decode(d) + c = layer.get("compression", "") + raw = zlib.decompress(raw) if c == "zlib" else gzip.decompress(raw) if c == "gzip" else raw + return list(struct.unpack("<%dI" % (len(raw) // 4), raw)) + return d + + +IGNORE = {"version", "tiledversion", "compressionlevel", "encoding", "compression", "opacity_obj"} + + +DEFAULTS = {"offsetx": 0, "offsety": 0, "parallaxx": 1, "parallaxy": 1, "locked": False} + + +def norm(v, obj=False): + """a JSON map without the fields that only say which Tiled wrote it, or that hold defaults""" + if isinstance(v, dict): + out = {} + if v.get("type") == "tilelayer" and "data" in v: + v = dict(v, data=gids(v)) + for k, x in v.items(): + if k in IGNORE or (k in DEFAULTS and x == DEFAULTS[k]) or (obj and k == "opacity"): + continue + out[k] = [norm(o, True) for o in x] if k == "objects" else norm(x) + return out + if isinstance(v, list): + return [norm(x) for x in v] + if isinstance(v, float) and v.is_integer(): + return int(v) + return v + + +def diff(a, b, path="", out=None): + out = [] if out is None else out + if isinstance(a, dict) and isinstance(b, dict): + for k in sorted(set(a) | set(b)): + if k not in a or k not in b: + out.append("%s.%s: %s vs %s" % (path, k, a.get(k, "<missing>"), b.get(k, "<missing>"))) + else: + diff(a[k], b[k], path + "." + k, out) + elif isinstance(a, list) and isinstance(b, list): + if len(a) != len(b): + out.append("%s: length %d vs %d" % (path, len(a), len(b))) + for i, (x, y) in enumerate(zip(a, b)): + diff(x, y, "%s[%d]" % (path, i), out) + elif a != b: + out.append("%s: %r vs %r" % (path, a, b)) + return out + + +def generate(ctx): + cases = [] + with tempfile.TemporaryDirectory() as d: + workdir(ctx, d) + for name, text in (("ortho", ortho()), ("hex", iso()), ("infinite", infinite())): + open(os.path.join(d, name + ".tmx"), "w").write(text) + tiled(ctx, ["--export-map", name + ".tmx", name + "-out.tmj"], d) + tiled(ctx, ["--export-map", name + ".tmx", name + "-out.tmx"], d) + cases.append({"name": name, "tmx": text, "tmj": open(os.path.join(d, name + "-out.tmj"), "rb").read(), + "tiled_tmx": open(os.path.join(d, name + "-out.tmx"), "rb").read()}) + tiled(ctx, ["--export-tileset", "ext.tsx", "ext.tsj"], d) + tsj = open(os.path.join(d, "ext.tsj"), "rb").read() + ctx.emit("tiled", {"cases": cases, "tsx": TSX, "tsj": tsj}) + + # our encoder's files, read by Tiled + o = run_ours(ctx, "tiled") + open(os.path.join(d, "ours.tmx"), "wb").write(bytes.fromhex(o["tmx"])) + open(os.path.join(d, "ours.tmj"), "wb").write(bytes.fromhex(o["tmj"])) + tiled(ctx, ["--export-map", "ours.tmx", "ours-from-tmx.tmj"], d) + tiled(ctx, ["--export-map", "ours.tmj", "ours-from-tmj.tmj"], d) + mine = norm(json.loads(bytes.fromhex(o["tmj"]))) + checks = [] + for label, f in (("Tiled on our TMX", "ours-from-tmx.tmj"), ("Tiled on our TMJ", "ours-from-tmj.tmj")): + theirs = norm(json.load(open(os.path.join(d, f)))) + dd = diff(mine, theirs) + checks.append({"label": label + (": " + "; ".join(dd[:5]) if dd else ""), "ok": not dd}) + ctx.emit("tiled_ours", {"checks": checks}) diff --git a/tools/fixtures/toml.py b/tools/fixtures/toml.py new file mode 100644 index 0000000..7ba5cc5 --- /dev/null +++ b/tools/fixtures/toml.py @@ -0,0 +1,120 @@ +# data/toml fixtures: the toml-test suite (toml-lang/toml-test v2.2.0, pinned tarball through nix; the files listed +# in tests/files-toml-1.0.0) with each valid case's expected value as the canonical text tests/data/Canon.luau +# computes, plus a random corpus written by tomli-w and read back by Python's tomllib. +# tests/gen/toml_suite.luau { { name, valid, data, canon? } } +# tests/gen/toml_corpus.luau { { data, canon } } +import datetime, importlib.util, json, os, re, tomllib + +_spec = importlib.util.spec_from_file_location("_data_common", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_data_common.py")) +C = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(C) + +SUITE_URL = "https://github.com/toml-lang/toml-test/archive/refs/tags/v2.2.0.tar.gz" +SUITE_SHA = "1nkgbfcdjaccqgf5pkjs49jh0z1pz4lval94qfxq4j6ikvmlg80s" +DATES = ("datetime", "datetime-local", "date-local", "time-local") + + +def norm_date(v): + """a toml-test datetime string the way Types.Date prints it""" + m = re.match(r"^(\d{4}-\d{2}-\d{2})?(?:[Tt ]?(\d{2}:\d{2}:\d{2})(?:\.(\d+))?)?([Zz]|[+-]\d{2}:\d{2})?$", v) + date, time, frac, off = m.groups() + out = date or "" + if time: + out += ("T" if date else "") + time + f = (frac or "")[:9].rstrip("0") + if f: + out += "." + f + if off: + out += "Z" if off in ("Z", "z", "+00:00", "-00:00") else off + return out + + +def tagged(v, out): + if isinstance(v, dict) and set(v) == {"type", "value"} and isinstance(v["type"], str) and isinstance(v["value"], str): + t, x = v["type"], v["value"] + if t == "string": + b = x.encode("utf-8", "surrogatepass") + out += b"s%d:" % len(b) + b + elif t == "integer": + out += C.num(int(x)) + elif t == "float": + out += C.num(float(x)) + elif t == "bool": + out += b"t" if x == "true" else b"f" + elif t in DATES: + out += b"d" + norm_date(x).encode() + else: + raise ValueError(t) + elif isinstance(v, list): + out += b"[" + for x in v: + tagged(x, out) + out += b"," + out += b"]" + else: + items = [] + for k, x in v.items(): + kb = k.encode("utf-8", "surrogatepass") + items.append((b"s%d:" % len(kb) + kb, x)) + items.sort(key=lambda p: p[0]) + out += b"{" + for kb, x in items: + out += kb + b"=" + tagged(x, out) + out += b"," + out += b"}" + + +GEN = r''' +import datetime, json, random, sys, tomli_w +rng = random.Random(5) +KEYS = ["a", "b-c", "d_e", "1", "with space", "dot.ted", "é", "quote\"", "", "tab\t"] +def scalar(): + k = rng.randrange(8) + if k == 0: return rng.randrange(-2**63, 2**63) + if k == 1: return rng.randrange(-1000, 1000) + if k == 2: return rng.choice([0.5, -1.25e-7, 3.14159, 1e300, float("inf"), -float("inf"), 6.02e23]) + if k == 3: return rng.random() < 0.5 + if k == 4: return "".join(rng.choice("ab \"\\\n\té中\U0001f600\x01\x7f'#=[]") for _ in range(rng.randrange(12))) + if k == 5: + tz = rng.choice([None, datetime.timezone.utc, datetime.timezone(datetime.timedelta(hours=-7, minutes=-30))]) + return datetime.datetime(rng.randrange(1, 9999), rng.randrange(1, 13), rng.randrange(1, 29), rng.randrange(24), rng.randrange(60), rng.randrange(60), rng.choice([0, 999999, 500000]), tzinfo=tz) + if k == 6: return datetime.date(rng.randrange(1, 9999), rng.randrange(1, 13), rng.randrange(1, 29)) + return datetime.time(rng.randrange(24), rng.randrange(60), rng.randrange(60), rng.choice([0, 123000])) +def table(depth): + d = {} + for _ in range(rng.randrange(1, 6)): + r = rng.random() + k = rng.choice(KEYS) + if depth < 3 and r < 0.2: d[k] = table(depth + 1) + elif depth < 3 and r < 0.3: d[k] = [table(depth + 1) for _ in range(rng.randrange(1, 3))] + elif r < 0.45: d[k] = [scalar() for _ in range(rng.randrange(0, 4))] + elif r < 0.5: d[k] = [[scalar()], [scalar(), scalar()], {"x": scalar()}] + else: d[k] = scalar() + return d +out = [] +for _ in range(200): + out.append(tomli_w.dumps(table(0), multiline_strings=rng.random() < 0.3)) +json.dump(out, sys.stdout) +''' + + +def generate(ctx): + root = os.path.join(C.fetch(SUITE_URL, SUITE_SHA), "tests") + names = [l.strip() for l in open(os.path.join(root, "files-toml-1.0.0")) if l.strip().endswith(".toml")] + cases = [] + for name in names: + data = open(os.path.join(root, name), "rb").read() + c = {"name": name, "valid": name.startswith("valid/"), "data": data} + if c["valid"]: + out = bytearray() + tagged(json.load(open(os.path.join(root, name[:-5] + ".json"), encoding="utf-8")), out) + c["canon"] = bytes(out) + cases.append(c) + ctx.emit("toml_suite", cases) + + texts = json.loads(ctx.python(["tomli-w"], GEN)) + corpus = [] + for t in texts: + corpus.append({"data": t.encode("utf-8"), "canon": C.canon(tomllib.loads(t))}) + ctx.emit("toml_corpus", corpus) diff --git a/tools/fixtures/vox.py b/tools/fixtures/vox.py new file mode 100644 index 0000000..405c886 --- /dev/null +++ b/tools/fixtures/vox.py @@ -0,0 +1,292 @@ +# VOX fixtures (tools/fixtures.py). There is no MagicaVoxel reader in nixpkgs, so the reference is (1) files saved by +# MagicaVoxel itself (tests/fixtures/vox: ephtracy/voxel-model samples, version 150, and jpaver/opengametools demo files +# with scene graphs, layers, materials, render objects, cameras, notes and META; licences in licenses/), parsed here +# by an independent Python reader written from the spec, and (2) synthetic files written here with every chunk type, +# rotations (including mirrors), nested groups, animation frames and odd cases. +# tests/gen/vox_cases.luau { name, data, version, models = { { size, count, crc (of the dense x-fastest grid), +# faces (exposed unit faces: the greedy mesh area) } }, paletteCrc, chunks = { id = n }, +# nodes = { { name, world (row-major 3x4: R | t) } } for every shape node, names, layers, +# materials, notes, cameras, robjs } +import os, struct, zlib + +INPUTS = ["tests/fixtures/vox"] + +def default_palette(): + steps = [0xff, 0xcc, 0x99, 0x66, 0x33, 0] + pal = [(r, g, b, 255) for r in steps for g in steps for b in steps][:215] + ramp = [0xee, 0xdd, 0xbb, 0xaa, 0x88, 0x77, 0x55, 0x44, 0x22, 0x11] + for ch in range(3): + for v in ramp: + c = [0, 0, 0, 255] + c[ch] = v + pal.append(tuple(c)) + pal += [(v, v, v, 255) for v in ramp] + return pal + + +def spec_palette(text): + # the default_palette[256] array of the spec text (ABGR words, entry i = palette index i) + body = text[text.index("default_palette[256]"):] + body = body[body.index("{") + 1:body.index("}")] + words = [int(w, 16) for w in body.replace(",", " ").split()] + return [(w & 255, (w >> 8) & 255, (w >> 16) & 255, w >> 24) for w in words] + + +# ---------------------------------------------------------------------------------------------- reader (reference) +def rd_dict(d, p): + n, = struct.unpack_from("<i", d, p) + p += 4 + out = {} + for _ in range(n): + kl, = struct.unpack_from("<i", d, p) + k = d[p + 4:p + 4 + kl].decode("latin1") + p += 4 + kl + vl, = struct.unpack_from("<i", d, p) + v = d[p + 4:p + 4 + vl].decode("latin1") + p += 4 + vl + out[k] = v + return out, p + + +def rot(b): + i0, i1 = b & 3, (b >> 2) & 3 + i2 = 3 - i0 - i1 + R = [[0] * 3 for _ in range(3)] + for row, (i, bit) in enumerate(((i0, 4), (i1, 5), (i2, 6))): + R[row][i] = -1 if b & (1 << bit) else 1 + return R + + +def matmul(A, B): # 3x4 affine (R | t) + R = [[sum(A[r][k] * B[k][c] for k in range(3)) for c in range(3)] for r in range(3)] + t = [sum(A[r][k] * B[k][3] for k in range(3)) + A[r][3] for r in range(3)] + return [R[r] + [t[r]] for r in range(3)] + + +def parse(d): + assert d[:4] == b"VOX " + version, = struct.unpack_from("<i", d, 4) + assert d[8:12] == b"MAIN" + n, m = struct.unpack_from("<ii", d, 12) + p = 20 + n + end = min(p + m, len(d)) + models, size, palette = [], None, None + graph, counts = {}, {} + mats, layers, notes, cams, robjs = {}, [], [], [], [] + while p + 12 <= end: + cid = d[p:p + 4].decode("latin1") + n, m = struct.unpack_from("<ii", d, p + 4) + c = p + 12 + counts[cid] = counts.get(cid, 0) + 1 + if cid == "SIZE": + size = struct.unpack_from("<iii", d, c) + elif cid == "XYZI": + k, = struct.unpack_from("<i", d, c) + sx, sy, sz = size + grid = bytearray(sx * sy * sz) + for i in range(k): + x, y, z, ci = d[c + 4 + i * 4:c + 8 + i * 4] + if x < sx and y < sy and z < sz and ci: + grid[x + sx * (y + sy * z)] = ci + models.append((size, grid)) + elif cid == "RGBA": + palette = [tuple(d[c + i * 4:c + i * 4 + 4]) for i in range(255)] + elif cid == "MATL": + mid, = struct.unpack_from("<i", d, c) + mats[mid], _ = rd_dict(d, c + 4) + elif cid == "nTRN": + nid, = struct.unpack_from("<i", d, c) + attrs, q = rd_dict(d, c + 4) + child, _, layer, nf = struct.unpack_from("<iiii", d, q) + q += 16 + frames = [] + for _ in range(nf): + f, q = rd_dict(d, q) + frames.append(f) + graph[nid] = ("T", attrs, child, frames) + elif cid == "nGRP": + nid, = struct.unpack_from("<i", d, c) + attrs, q = rd_dict(d, c + 4) + k, = struct.unpack_from("<i", d, q) + graph[nid] = ("G", attrs, list(struct.unpack_from("<%di" % k, d, q + 4))) + elif cid == "nSHP": + nid, = struct.unpack_from("<i", d, c) + attrs, q = rd_dict(d, c + 4) + k, = struct.unpack_from("<i", d, q) + mid, = struct.unpack_from("<i", d, q + 4) + graph[nid] = ("S", attrs, mid) + elif cid == "LAYR": + lid, = struct.unpack_from("<i", d, c) + layers.append(rd_dict(d, c + 4)[0]) + elif cid == "NOTE": + k, = struct.unpack_from("<i", d, c) + q = c + 4 + for _ in range(k): + l, = struct.unpack_from("<i", d, q) + notes.append(d[q + 4:q + 4 + l].decode("latin1")) + q += 4 + l + elif cid == "rCAM": + cams.append(struct.unpack_from("<i", d, c)[0]) + elif cid == "rOBJ": + robjs.append(rd_dict(d, c)[0]) + p = c + n + m + # shape nodes in depth-first order with world transforms + shapes = [] + + def walk(nid, parent): + kind, attrs, child, frames = graph[nid] + f = frames[0] if frames else {} + R = rot(int(f["_r"])) if "_r" in f else [[1, 0, 0], [0, 1, 0], [0, 0, 1]] + t = [int(v) for v in f.get("_t", "0 0 0").split()] + world = matmul(parent, [R[r] + [t[r]] for r in range(3)]) + ch = graph.get(child) + if ch and ch[0] == "G": + for c2 in ch[2]: + walk(c2, world) + elif ch and ch[0] == "S": + shapes.append({"name": attrs.get("_name", ""), "model": ch[2] + 1, "world": [v for row in world for v in row]}) + + if 0 in graph: + walk(0, [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0]]) + pal = palette or default_palette() + out_models = [] + for (sx, sy, sz), grid in models: + faces = 0 + for z in range(sz): + for y in range(sy): + for x in range(sx): + if grid[x + sx * (y + sy * z)]: + for dx, dy, dz in ((1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1)): + X, Y, Z = x + dx, y + dy, z + dz + if not (0 <= X < sx and 0 <= Y < sy and 0 <= Z < sz) or not grid[X + sx * (Y + sy * Z)]: + faces += 1 + out_models.append({"size": [sx, sy, sz], "count": sum(1 for v in grid if v), "crc": zlib.crc32(bytes(grid)), "faces": faces}) + return { + "version": version, + "models": out_models, + "paletteCrc": zlib.crc32(bytes(v for c in pal for v in c)), + "hasPalette": palette is not None, + "chunks": counts, + "shapes": shapes, + "layers": len(layers), + "materials": len(mats), + "notes": len(notes), + "cameras": len(cams), + "robjs": len(robjs), + "glassMaterials": sum(1 for m in mats.values() if m.get("_type") == "_glass"), + } + + +# ---------------------------------------------------------------------------------------------- writer (synthetic files) +def s(x): + b = x.encode() + return struct.pack("<i", len(b)) + b + + +def dct(d): + return struct.pack("<i", len(d)) + b"".join(s(k) + s(v) for k, v in d.items()) + + +def chunk(cid, content, children=b""): + return cid.encode() + struct.pack("<ii", len(content), len(children)) + content + children + + +def vox(chunks, version=200, main_size=None): + body = b"".join(chunks) + return b"VOX " + struct.pack("<i", version) + b"MAIN" + struct.pack("<ii", 0, main_size if main_size is not None else len(body)) + body + + +def model(rng, sx, sy, sz, fill=0.4, colors=(1, 255)): + vox_list = [] + for z in range(sz): + for y in range(sy): + for x in range(sx): + if rng.random() < fill: + vox_list.append((x, y, z, rng.randrange(*colors))) + rng.shuffle(vox_list) + return [chunk("SIZE", struct.pack("<iii", sx, sy, sz)), chunk("XYZI", struct.pack("<i", len(vox_list)) + b"".join(bytes(v) for v in vox_list))] + + +def ntrn(nid, child, attrs=None, frames=None, layer=0): + frames = frames or [{}] + return chunk("nTRN", struct.pack("<i", nid) + dct(attrs or {}) + struct.pack("<iiii", child, -1, layer, len(frames)) + b"".join(dct(f) for f in frames)) + + +def ngrp(nid, children, attrs=None): + return chunk("nGRP", struct.pack("<i", nid) + dct(attrs or {}) + struct.pack("<i", len(children)) + b"".join(struct.pack("<i", c) for c in children)) + + +def nshp(nid, models_): + return chunk("nSHP", struct.pack("<i", nid) + dct({}) + struct.pack("<i", len(models_)) + b"".join(struct.pack("<i", m) + dct({"_f": str(i)} if len(models_) > 1 else {}) for i, m in enumerate(models_))) + + +def rgba(rng): + return chunk("RGBA", bytes(rng.randrange(256) for _ in range(1024))) + + +def synthetic(rng): + out = [] + # 1. a plain v150 model without a palette (the default palette) + out.append(("syn-default-palette", vox(model(rng, 7, 5, 3), 150))) + # 2. full scene: nested groups, every rotation family, mirrors, hidden, layers, materials, notes, cameras, IMAP, META + ch = [] + for _ in range(4): + ch += model(rng, rng.randrange(1, 12), rng.randrange(1, 12), rng.randrange(1, 12)) + ch += [ + ntrn(0, 1, layer=-1), + ngrp(1, [2, 4, 8]), + ntrn(2, 3, {"_name": "a"}, [{"_r": "4", "_t": "1 2 3"}]), + nshp(3, [0]), + ntrn(4, 5, {"_name": "group", "_hidden": "1"}, [{"_r": "17", "_t": "-5 0 7"}], layer=1), # 90 deg about z + ngrp(5, [6, 10]), + ntrn(6, 7, {"_name": "b"}, [{"_r": "20", "_t": "0 0 -4"}]), # a mirror (x flipped) + nshp(7, [1]), + ntrn(8, 9, {"_name": "anim"}, [{"_r": "9", "_t": "3 3 3", "_f": "0"}, {"_r": "4", "_t": "4 4 4", "_f": "5"}]), + nshp(9, [2, 3]), + ntrn(10, 11, {"_name": "c"}, [{"_r": "98", "_t": "10 -20 30"}]), + nshp(11, [3]), + chunk("LAYR", struct.pack("<i", 0) + dct({"_name": "zero"}) + struct.pack("<i", -1)), + chunk("LAYR", struct.pack("<i", 1) + dct({"_name": "one", "_hidden": "1", "_color": "255 0 0"}) + struct.pack("<i", -1)), + rgba(rng), + chunk("IMAP", bytes(range(256))), + ] + for mid in (1, 2, 200): + ch.append(chunk("MATL", struct.pack("<i", mid) + dct({"_type": ["_diffuse", "_glass", "_emit"][mid % 3], "_rough": "0.25", "_ior": "1.5", "_flux": "2"}))) + ch.append(chunk("rOBJ", dct({"_type": "_bg", "_color": "0 0 0"}))) + ch.append(chunk("rCAM", struct.pack("<i", 0) + dct({"_mode": "pers", "_focus": "0 0 0", "_angle": "30 40 0", "_radius": "80", "_frustum": "0.4", "_fov": "45"}))) + ch.append(chunk("NOTE", struct.pack("<i", 2) + s("first") + s("second"))) + ch.insert(0, chunk("META", dct({"_anim_range": "0 30"}))) + ch.append(chunk("ZZZZ", b"unknown payload")) + out.append(("syn-scene", vox(ch))) + # 3. edge cases: voxels outside the grid, index 0, duplicates, a 1x1x1 model + vox_list = [(0, 0, 0, 5), (9, 0, 0, 7), (1, 1, 1, 0), (1, 1, 1, 9), (1, 1, 1, 10)] + ch = [chunk("SIZE", struct.pack("<iii", 2, 2, 2)), chunk("XYZI", struct.pack("<i", len(vox_list)) + b"".join(bytes(v) for v in vox_list)), rgba(rng)] + out.append(("syn-edge", vox(ch))) + out.append(("syn-single", vox([chunk("SIZE", struct.pack("<iii", 1, 1, 1)), chunk("XYZI", struct.pack("<i", 1) + bytes((0, 0, 0, 1)))]))) + # 4. a full 64^3 block and a 3d checkerboard (worst case for greedy meshing) + full = [(x, y, z, 1 + (z % 3)) for z in range(64) for y in range(64) for x in range(64)] + out.append(("syn-block64", vox([chunk("SIZE", struct.pack("<iii", 64, 64, 64)), chunk("XYZI", struct.pack("<i", len(full)) + b"".join(bytes(v) for v in full))]))) + chk = [(x, y, z, 3) for z in range(16) for y in range(16) for x in range(16) if (x + y + z) % 2 == 0] + out.append(("syn-checker16", vox([chunk("SIZE", struct.pack("<iii", 16, 16, 16)), chunk("XYZI", struct.pack("<i", len(chk)) + b"".join(bytes(v) for v in chk))]))) + return out + + +def generate(ctx): + rng = ctx.rng(7) + cases = [] + folder = os.path.join("tests", "fixtures", "vox") + for f in sorted(os.listdir(os.path.join(ctx.root, folder))): + if f.endswith(".vox"): + cases.append((f, ctx.read(os.path.join(folder, f)))) + cases += synthetic(rng) + out = [] + for name, data in cases: + ref = parse(data) + ref["name"] = name + ref["data"] = data + out.append(ref) + ctx.emit("vox_cases", out) + # the spec's default palette (parsed from the spec text) must equal the formula used by both readers + pal = spec_palette(ctx.read(os.path.join(folder, "MagicaVoxel-file-format-vox.txt")).decode())[1:] + assert pal == default_palette(), "default palette formula differs from the spec" + ctx.emit("vox_default_palette", [list(c) for c in pal]) diff --git a/tools/fixtures/webp.py b/tools/fixtures/webp.py new file mode 100644 index 0000000..da5ea3d --- /dev/null +++ b/tools/fixtures/webp.py @@ -0,0 +1,344 @@ +# WebP fixtures (tools/fixtures.py). Reference tools: libwebp 1.6 (cwebp, dwebp, img2webp, gif2webp, webpmux), +# ImageMagick (built-in test images, an animated GIF), ffmpeg's libvpx (VP8 key frames from a second encoder, with +# token partitions and loop filter deltas, wrapped in a RIFF here) and Pillow (WebPAnimDecoder: composited frames). +# tests/gen/webp_src.luau the source images: { name, width, height, rgba } +# tests/gen/webp_cases.luau still files: { name, data, width, height, crc (dwebp -pam), lossy, yuv (dwebp -yuv), +# nofancy (dwebp -nofancy -pam), alpha, meta } +# tests/gen/webp_anim.luau animations: { name, data, width, height, loops, frames = { crc, ms } (Pillow) } +# tests/gen/webp_enc.luau our encoder's output checked by dwebp / Pillow (tools/fixtures/_webp_encode.luau): +# { name, effort, crc, ok, size, cwebp }, animations { name, crc, frames } +# tests/gen/webp_bench.luau bigger lossy / lossless files for tools/bench.luau +import json, os, random, shutil, struct, subprocess, tempfile, zlib + +INPUTS = ["tools/fixtures/_webp_encode.luau", "src/Formats/codecs/Vp8L", "src/Formats/image/webp"] + +TOOLS = ["libwebp", "imagemagick", "ffmpeg"] + + +def run(tmp, script): + path = os.path.join(tmp, "run.sh") + with open(path, "w") as f: + f.write("set -e\n" + script) + cmd = ["nix", "shell"] + ["nixpkgs#" + t for t in TOOLS] + ["-c", "bash", path] + subprocess.run(cmd, cwd=tmp, check=True, capture_output=True) + + +def pam_write(path, w, h, rgba): + with open(path, "wb") as f: + f.write(b"P7\nWIDTH %d\nHEIGHT %d\nDEPTH 4\nMAXVAL 255\nTUPLTYPE RGB_ALPHA\nENDHDR\n" % (w, h) + bytes(rgba)) + + +def pam_read(data): + end = data.index(b"ENDHDR\n") + 7 + hdr = dict(l.split(b" ", 1) for l in data[:end].split(b"\n")[1:] if b" " in l) + w, h, d = int(hdr[b"WIDTH"]), int(hdr[b"HEIGHT"]), int(hdr[b"DEPTH"]) + px = data[end:end + w * h * d] + if d == 4: + return w, h, px + out = bytearray(w * h * 4) + for i in range(w * h): + if d == 3: + out[i * 4:i * 4 + 3] = px[i * 3:i * 3 + 3] + else: + out[i * 4:i * 4 + 3] = bytes([px[i * d]]) * 3 + out[i * 4 + 3] = 255 if d < 2 or d == 3 else px[i * d + 1] + return w, h, bytes(out) + + +def synthetic(rng): + out = [] + + def img(name, w, h, f): + px = bytearray() + for y in range(h): + for x in range(w): + px += bytes(f(x, y)) + out.append((name, w, h, bytes(px))) + + img("tiny", 1, 1, lambda x, y: (200, 10, 30, 255)) + img("odd", 3, 7, lambda x, y: (rng.randrange(256), rng.randrange(256), rng.randrange(256), 255)) + img("strip", 257, 3, lambda x, y: ((x * 7) & 255, (x + y * 50) & 255, (x * x) & 255, 255)) + two = [(0, 0, 0, 255), (255, 255, 255, 255)] + img("pal2", 33, 17, lambda x, y: two[(x * 3 + y * 5) % 7 < 3]) + three = [(255, 0, 0, 255), (0, 255, 0, 128), (0, 0, 255, 0)] + img("pal3", 40, 9, lambda x, y: three[(x // 3 + y) % 3]) + five = [(rng.randrange(256), rng.randrange(256), rng.randrange(256), 255) for _ in range(5)] + img("pal5", 25, 25, lambda x, y: five[(x * y + x) % 5]) + p16 = [(rng.randrange(256), rng.randrange(256), rng.randrange(256), rng.choice([255, 255, 90])) for _ in range(16)] + img("pal16", 64, 40, lambda x, y: p16[((x // 4) * 3 + y // 5) % 16]) + p17 = [(i * 15, 255 - i * 15, (i * 77) & 255, 255) for i in range(17)] + img("pal17", 51, 30, lambda x, y: p17[(x + y) % 17]) + p256 = [(i, (i * 3) & 255, (i * 7) & 255, 255 if i % 9 else 128) for i in range(256)] + img("pal256", 64, 64, lambda x, y: p256[(x * 64 + y * 5 + x * y) % 256]) + img("noise", 48, 48, lambda x, y: (rng.randrange(256), rng.randrange(256), rng.randrange(256), rng.randrange(256))) + img("grad", 100, 60, lambda x, y: (x * 255 // 99, y * 255 // 59, (x + y) * 255 // 158, min(255, x * 3 + y))) + img("trans", 50, 50, lambda x, y: (rng.randrange(256), rng.randrange(256), rng.randrange(256), 0 if (x - 25) ** 2 + (y - 25) ** 2 > 300 else 255)) + return out + + +def add_alpha(name, w, h, px, kind): + out = bytearray(px) + for y in range(h): + for x in range(w): + i = (y * w + x) * 4 + 3 + if kind == "ramp": + out[i] = 0 if x < w // 6 else min(255, (x * 255) // max(1, w - 1) + 20) + else: + out[i] = 255 if (x // 8 + y // 8) % 3 else (x * y) & 255 + return name, w, h, bytes(out) + + +LOSSLESS = [("z0", "-lossless -z 0"), ("z3", "-lossless -z 3"), ("z6", "-lossless -z 6"), ("z9", "-lossless -z 9"), + ("exact", "-lossless -exact -m 6 -q 100"), ("near", "-lossless -near_lossless 40")] +LOSSY = [("q5", "-q 5"), ("q50", "-q 50"), ("q90", "-q 90 -m 6"), ("simple", "-q 75 -nostrong -sharpness 5"), + ("seg1", "-q 30 -f 100 -segments 1"), ("nofilter", "-q 60 -sns 0 -f 0"), ("sharpyuv", "-q 80 -sharp_yuv -af")] +ALPHA = [("araw", "-q 70 -alpha_method 0"), ("afnone", "-q 70 -alpha_filter none"), ("affast", "-q 70 -alpha_filter fast"), + ("afbest", "-q 70 -alpha_filter best -exact"), ("aq30", "-q 70 -alpha_q 30")] +FULL = {"rose", "plasma", "rose_a", "pal16", "grad", "odd"} # every lossless / lossy variant; others get a few + + +def ivf_frames(data): + frames, p = [], 32 + while p + 12 <= len(data): + n = struct.unpack_from("<I", data, p)[0] + frames.append(data[p + 12:p + 12 + n]) + p += 12 + n + return frames + + +def riff(chunks): + body = b"WEBP" + for fourcc, payload in chunks: + body += fourcc + struct.pack("<I", len(payload)) + payload + (b"\0" if len(payload) % 2 else b"") + return b"RIFF" + struct.pack("<I", len(body)) + body + + +def chunks_of(data): + out, p = [], 12 + while p + 8 <= len(data): + fourcc, n = data[p:p + 4], struct.unpack_from("<I", data, p + 4)[0] + out.append((fourcc, data[p + 8:p + 8 + n])) + p += 8 + n + n % 2 + return out + + +def filter_alpha(a, w, h, f): + out = bytearray(w * h) + for y in range(h): + for x in range(w): + i = y * w + x + if f == 0: + pred = 0 + elif y == 0: + pred = a[i - 1] if x else 0 + elif x == 0: + pred = a[i - w] + elif f == 1: + pred = a[i - 1] + elif f == 2: + pred = a[i - w] + else: + pred = max(0, min(255, a[i - 1] + a[i - w] - a[i - w - 1])) + out[i] = (a[i] - pred) & 255 + return bytes(out) + + +def craft_alpha(tmp, base_alpha): + name, w, h, px = base_alpha + a = bytes(px[i] for i in range(3, len(px), 4)) + src = dict(chunks_of(open(os.path.join(tmp, "rose_a_afnone.webp"), "rb").read())) + out = [] + for f in range(4): + alph = bytes([f << 2]) + filter_alpha(a, w, h, f) + data = riff([(b"VP8X", src[b"VP8X"]), (b"ALPH", alph), (b"VP8 ", src[b"VP8 "])]) + fname = "alph_raw_f%d.webp" % f + open(os.path.join(tmp, fname), "wb").write(data) + out.append((fname, {"lossy": True})) + return out + + +def generate(ctx): + tmp = tempfile.mkdtemp(prefix="webp_fx_") + try: + _generate(ctx, tmp) + finally: + shutil.rmtree(tmp, ignore_errors=True) + + +def _generate(ctx, tmp): + rng = ctx.rng(20260) + # 1. sources: ImageMagick's built-in images (resized) + synthetic ones + run(tmp, "\n".join([ + "magick rose: -alpha off PAM:rose.pam", + "magick granite: -alpha off PAM:granite.pam", + "magick netscape: -alpha off PAM:netscape.pam", + "magick wizard: -resize 120x160 -alpha off PAM:wizard.pam", + "magick logo: -resize 160x120 -alpha off PAM:logo.pam", + "magick -seed 7 -size 200x150 plasma:fractal -depth 8 -alpha off PAM:plasma.pam", + "magick wizard: -resize 512x512! -alpha off PAM:bench.pam", + ])) + sources = [] + for n in ["rose", "granite", "netscape", "wizard", "logo", "plasma"]: + w, h, px = pam_read(open(os.path.join(tmp, n + ".pam"), "rb").read()) + sources.append((n, w, h, px)) + base = {s[0]: s for s in sources} + sources.append(add_alpha("rose_a", *base["rose"][1:], "ramp")) + sources.append(add_alpha("plasma_a", *base["plasma"][1:], "blocks")) + sources += synthetic(rng) + for n, w, h, px in sources: + pam_write(os.path.join(tmp, n + ".pam"), w, h, px) + ctx.emit("webp_src", [{"name": n, "width": w, "height": h, "rgba": px} for n, w, h, px in sources]) + + # 2. still files: cwebp lossless / lossy / alpha variants, libvpx key frames, metadata + files = [] # (name, extra info) + lines = [] + for n, w, h, px in sources: + has_alpha = any(px[i] != 255 for i in range(3, len(px), 4)) + full = n in FULL + for tag, args in LOSSLESS if full else LOSSLESS[2:3]: + lines.append("cwebp -quiet %s %s.pam -o %s_%s.webp" % (args, n, n, tag)) + files.append(("%s_%s.webp" % (n, tag), {"lossy": False})) + for tag, args in LOSSY if full else LOSSY[1:2]: + lines.append("cwebp -quiet %s %s.pam -o %s_%s.webp" % (args, n, n, tag)) + files.append(("%s_%s.webp" % (n, tag), {"lossy": True})) + if has_alpha: + for tag, args in ALPHA if full or n == "plasma_a" else ALPHA[1:2]: + lines.append("cwebp -quiet %s %s.pam -o %s_%s.webp" % (args, n, n, tag)) + files.append(("%s_%s.webp" % (n, tag), {"lossy": True})) + for n in ["rose", "granite", "plasma", "wizard"]: + for k, (slices, q) in enumerate([(1, 10), (2, 30), (4, 50), (8, 63)]): + lines.append("magick %s.pam -alpha off PNG24:%s_vpx.png" % (n, n)) + lines.append("ffmpeg -loglevel error -y -i %s_vpx.png -c:v libvpx -slices %d -qmin %d -qmax %d -b:v 1M -sharpness %d -f ivf %s_vpx%d.ivf" + % (n, slices, q, q, k, n, k)) + lines.append("cwebp -quiet -q 60 rose_a.pam -o meta_base.webp") + lines.append("head -c 600 /dev/urandom > meta.icc && head -c 100 /dev/urandom > meta.exif && printf '<x:xmpmeta/>' > meta.xmp") + lines.append("webpmux -set icc meta.icc meta_base.webp -o meta1.webp") + lines.append("webpmux -set exif meta.exif meta1.webp -o meta2.webp") + lines.append("webpmux -set xmp meta.xmp meta2.webp -o meta_all.webp") + lines.append("cwebp -quiet -lossless -metadata all rose.pam -o meta_ll.webp && webpmux -set icc meta.icc meta_ll.webp -o meta_ll_icc.webp") + files.append(("meta_all.webp", {"lossy": True, "meta": True})) + files.append(("meta_ll_icc.webp", {"lossy": False, "meta": True})) + run(tmp, "\n".join(lines)) + for n in ["rose", "granite", "plasma", "wizard"]: + for k in range(4): + data = open(os.path.join(tmp, "%s_vpx%d.ivf" % (n, k)), "rb").read() + frame = ivf_frames(data)[0] + name = "%s_vpx%d.webp" % (n, k) + open(os.path.join(tmp, name), "wb").write(riff([(b"VP8 ", frame)])) + files.append((name, {"lossy": True})) + # raw ALPH chunks with each of the four filters, written here (rose_a's alpha over its lossy VP8 data) + files += craft_alpha(tmp, base_alpha=[s for s in sources if s[0] == "rose_a"][0]) + # references + lines = [] + for name, info in files: + lines.append("dwebp -quiet %s -pam -o %s.pam" % (name, name)) + if info["lossy"]: + lines.append("dwebp -quiet %s -nofancy -pam -o %s.nf.pam" % (name, name)) + lines.append("dwebp -quiet %s -yuv -o %s.yuv" % (name, name)) + run(tmp, "\n".join(lines)) + cases = [] + for name, info in files: + data = open(os.path.join(tmp, name), "rb").read() + w, h, px = pam_read(open(os.path.join(tmp, name + ".pam"), "rb").read()) + c = {"name": name, "data": data, "width": w, "height": h, "crc": zlib.crc32(px), "lossy": info["lossy"], + "alpha": any(px[i] != 255 for i in range(3, len(px), 4))} + if info["lossy"]: + c["nofancy"] = zlib.crc32(pam_read(open(os.path.join(tmp, name + ".nf.pam"), "rb").read())[2]) + c["yuv"] = zlib.crc32(open(os.path.join(tmp, name + ".yuv"), "rb").read()) + if info.get("meta"): + c["icc"] = zlib.crc32(open(os.path.join(tmp, "meta.icc"), "rb").read()) + if name == "meta_all.webp": + c["exif"] = zlib.crc32(open(os.path.join(tmp, "meta.exif"), "rb").read()) + c["xmp"] = "<x:xmpmeta/>" + cases.append(c) + ctx.emit("webp_cases", cases) + + # 3. animations: img2webp (sub-rectangles, blending, mixed lossy / lossless), gif2webp, webpmux frames + lines = [] + # frames of one canvas size: rose-sized crops of the sources + for i, (n, w, h, px) in enumerate([s for s in sources if s[0] in ("plasma", "plasma_a", "wizard", "grad", "noise", "netscape")]): + lines.append("magick %s.pam -resize 70x46! -depth 8 PAM:af%d.pam" % (n, i)) + lines.append("magick rose.pam -fill red -draw 'rectangle 10,10 30,20' PAM:af6.pam") + lines.append("magick rose.pam -fill blue -draw 'rectangle 40,20 60,40' PAM:af7.pam") + lines.append("magick rose.pam -alpha on -channel A -evaluate set 50%% +channel PAM:af8.pam") + lines.append("img2webp -loop 3 -lossless rose.pam -d 80 af6.pam -d 120 af7.pam af8.pam -lossy -q 60 af0.pam -o anim_mixed.webp") + lines.append("img2webp -min_size -lossless af1.pam af3.pam -d 40 af4.pam af8.pam -o anim_alpha.webp") + lines.append("img2webp -kmax 2 -lossy -q 40 af0.pam af2.pam af5.pam -mixed af6.pam af7.pam -o anim_lossy.webp") + lines.append("magick -dispose background -delay 10 -size 60x40 xc:none -fill red -draw 'circle 20,20 30,20' " + "-dispose previous -delay 20 -size 60x40 xc:none -fill blue -draw 'rectangle 5,5 25,30' " + "-dispose none -delay 30 -size 60x40 xc:none -fill green -draw 'rectangle 30,10 55,35' " + "-loop 0 anim.gif") + lines.append("gif2webp -quiet anim.gif -o anim_gif.webp") + lines.append("gif2webp -quiet -lossy -q 50 anim.gif -o anim_gif_lossy.webp") + lines.append("cwebp -quiet -lossless af6.pam -o fr1.webp && cwebp -quiet -q 50 af7.pam -o fr2.webp") + lines.append("webpmux -frame fr1.webp +100+0+0+0-b -frame fr2.webp +50+10+6+1+b -loop 1 -bgcolor 255,1,2,3 -o anim_mux.webp") + lines.append("webpmux -set icc meta.icc anim_mux.webp -o anim_mux_icc.webp") + run(tmp, "\n".join(lines)) + anims = ["anim_mixed.webp", "anim_alpha.webp", "anim_lossy.webp", "anim_gif.webp", "anim_gif_lossy.webp", "anim_mux_icc.webp"] + ref = pillow_frames(ctx, [os.path.join(tmp, a) for a in anims]) + out = [] + for a, r in zip(anims, ref): + out.append({"name": a, "data": open(os.path.join(tmp, a), "rb").read(), "width": r["w"], "height": r["h"], + "loops": r["loop"], "rgba": r["mode"] == "RGBA", "frames": [{"crc": c, "ms": d} for c, d in r["frames"]]}) + ctx.emit("webp_anim", out) + + # 4. our encoder, checked by dwebp (still) and Pillow (animations) + res = subprocess.run(["nix", "shell", "nixpkgs#luau", "-c", "luau", "tools/fixtures/_webp_encode.luau"], + cwd=ctx.root, check=True, capture_output=True).stdout.decode() + ours = [] + for line in res.split("\n"): + if line.strip(): + name, hexdata = line.split(" ") + path = os.path.join(tmp, "ours_" + name.split(":")[0] + ".webp") + open(path, "wb").write(bytes.fromhex(hexdata)) + ours.append((name, path)) + run(tmp, "\n".join("dwebp -quiet %s -pam -o %s.pam" % (p, p) for n, p in ours if not n.startswith("anim")) + "\n" + + "\n".join("cwebp -quiet -lossless -exact %s.pam -o cw_%s.webp" % (n, n) for n, w, h, px in sources)) + src = {n: (w, h, px) for n, w, h, px in sources} + enc = [] + anim_paths = [(n, p) for n, p in ours if n.startswith("anim")] + aref = pillow_frames(ctx, [p for n, p in anim_paths]) + for name, path in ours: + if name.startswith("anim"): + continue + sname, effort, mode = name.rsplit("_", 2) + w, h, px = src[sname] + _, _, got = pam_read(open(path + ".pam", "rb").read()) + want = px if mode == "exact" else bytes(b if px[(i // 4) * 4 + 3] else 0 for i, b in enumerate(px)) + enc.append({"name": sname, "effort": int(effort[1:]), "exact": mode == "exact", "ok": got == want, + "size": os.path.getsize(path), "cwebp": os.path.getsize(os.path.join(tmp, "cw_%s.webp" % sname))}) + anim_out = [] + for (n, p), r in zip(anim_paths, aref): + aname, want = n.split(":") + got = [c for c, d in r["frames"]] + anim_out.append({"name": aname, "data": open(p, "rb").read(), "frames": got, "ms": [d for c, d in r["frames"]], + "loops": r["loop"], "ok": got == [int(c) for c in want.split(",")]}) + ctx.emit("webp_enc", {"still": enc, "anim": anim_out}) + + # 5. bench: a 512 x 512 lossy and lossless file + run(tmp, "cwebp -quiet -q 80 bench.pam -o bench_lossy.webp\ncwebp -quiet -lossless bench.pam -o bench_ll.webp") + w, h, px = pam_read(open(os.path.join(tmp, "bench.pam"), "rb").read()) + ctx.emit("webp_bench", {"width": w, "height": h, "rgba": px, + "lossy": open(os.path.join(tmp, "bench_lossy.webp"), "rb").read(), + "lossless": open(os.path.join(tmp, "bench_ll.webp"), "rb").read()}) + + +PILLOW = r""" +import json, sys, zlib +from PIL import Image +out = [] +for path in sys.argv[1:]: + im = Image.open(path) + frames = [] + for i in range(getattr(im, "n_frames", 1)): + im.seek(i) + frames.append([zlib.crc32(im.convert("RGBA").tobytes()), im.info.get("duration", 0)]) + out.append({"w": im.width, "h": im.height, "mode": im.mode, "loop": im.info.get("loop", 0), "frames": frames}) +print(json.dumps(out)) +""" + + +def pillow_frames(ctx, paths): + expr = "with import <nixpkgs> {}; python3.withPackages (p: [p.pillow])" + cmd = ["nix", "shell", "--impure", "--expr", expr, "-c", "python3", "-I", "-c", PILLOW] + paths + return json.loads(subprocess.run(cmd, capture_output=True, check=True).stdout) diff --git a/tools/fixtures/xml.py b/tools/fixtures/xml.py new file mode 100644 index 0000000..14cf720 --- /dev/null +++ b/tools/fixtures/xml.py @@ -0,0 +1,174 @@ +# codecs/Xml + data/xml fixtures: random documents (namespaces, attributes with every escape, CDATA, comments, PIs, +# entities from an internal DOCTYPE, mixed content) written by hand, then parsed by Python's xml.etree (expat) for the +# reference tree; the same documents re-encoded as UTF-16 and Latin-1; and well-formedness cases (hand-written plus +# random mutations) with expat's verdict. +# tests/gen/xml_docs.luau { { data, canon } } canon: see canon() below (the test computes the same) +# tests/gen/xml_wf.luau { { data, ok } } ok: expat accepts it +# tests/gen/xml_bench.luau { text } (~1 MB) +import xml.etree.ElementTree as ET +from xml.parsers import expat + +NS = [("", None), ("a", "urn:a"), ("b", "http://example.com/b")] +TAGS = ["item", "x", "Data", "set-1", "q.r", "_u", "élément", "名"] +TXT = "ab <>&\"' é中\U0001f600\t\n ]]" + + +def s(x): + x = x or "" + b = x.encode("utf-8", "surrogatepass") + return b"%d:" % len(b) + b + + +def canon(e): + out = b"(" + s(e.tag) + for k in sorted(e.attrib): + out += b"|" + s(k) + b"=" + s(e.attrib[k]) + out += b"|t" + s(e.text) + for c in e: + out += canon(c) + return out + b")t" + s(e.tail) + + +def esc_text(t): + return t.replace("&", "&").replace("<", "<").replace(">", ">") + + +def esc_attr(t, q): + t = t.replace("&", "&").replace("<", "<") + return t.replace(q, """ if q == '"' else "'") + + +def rand_text(rng): + return "".join(rng.choice(TXT) for _ in range(rng.randrange(0, 10))) + + +def gen_elem(rng, depth, declared): + prefix = rng.choice([p for p in declared]) + local = rng.choice(TAGS) + name = (prefix + ":" + local) if prefix else local + attrs = [] + newdecl = set(declared) + if depth > 0 and rng.random() < 0.15: + p, uri = rng.choice(NS[1:]) + attrs.append(("xmlns:" + p, uri)) + newdecl.add(p) + if rng.random() < 0.1: + attrs.append(("xmlns", "urn:default%d" % rng.randrange(3))) + used = set(a for a, _ in attrs) + for _ in range(rng.randrange(0, 4)): + an = rng.choice(["id", "k", "v-1", "é", "x.y"]) + if rng.random() < 0.2 and len(newdecl) > 1: + an = rng.choice([p for p in newdecl if p]) + ":" + an + if an in used: + continue + used.add(an) + attrs.append((an, rand_text(rng))) + parts = ["<" + name] + for k, v in attrs: + q = rng.choice("\"'") + parts.append(" %s=%s%s%s" % (k, q, esc_attr(v, q), q)) + if depth > 4 or rng.random() < 0.15: + parts.append(rng.choice(["/>", " />"])) + return "".join(parts) + parts.append(">") + for _ in range(rng.randrange(0, 5)): + r = rng.random() + if r < 0.35: + parts.append(esc_text(rand_text(rng))) + elif r < 0.45: + parts.append("<![CDATA[" + rand_text(rng).replace("]", "] ") + "<&>]]>") + elif r < 0.5: + parts.append("<!-- c " + rand_text(rng).replace("-", "=") + " -->") + elif r < 0.53: + parts.append("<?pi data " + rand_text(rng).replace("?", "") + "?>") + elif r < 0.58: + parts.append(rng.choice(["&ent;", "é", "😀", "&", "<", " "])) + else: + parts.append(gen_elem(rng, depth + 1, newdecl)) + parts.append("</%s>" % name) + return "".join(parts) + + +def gen_doc(rng): + head = "" + if rng.random() < 0.5: + head += '<?xml version="1.0" encoding="UTF-8"?>\n' + head += '<!DOCTYPE root [\n <!ENTITY ent "entity &#38; text <">\n <!-- a comment -->\n]>\n' + if rng.random() < 0.3: + head += "<!-- prolog comment -->\n" + declared = {""} + body = gen_elem(rng, 0, declared) + # the root must declare every prefix it may use: declare all at the root + root_decl = " ".join('xmlns:%s="%s"' % (p, u) for p, u in NS[1:]) + i = body.index(">") if not body.startswith("<") else 0 + name_end = 1 + while body[name_end] not in " />": + name_end += 1 + body = body[:name_end] + " " + root_decl + body[name_end:] + return head + body + ("\n" if rng.random() < 0.5 else "") + + +def expat_ok(data): + p = expat.ParserCreate() + try: + p.Parse(data, True) + return True + except Exception: # ExpatError, or LookupError for an unknown encoding name + return False + + +WF = [ + "<a/>", "<a></a>", "<a><b/></a>", "<a>x</b>", "<a>", "</a>", "<a/><b/>", "text<a/>", "<a/>text", "<a b='1' b='2'/>", + "<a b=1/>", "<a b='<'/>", "<a>&undefined;</a>", "<a>�</a>", "<a>�</a>", "<a>�</a>", "<a>& </a>", + "<a><!-- x -- y --></a>", "<a><!-- x ---></a>", "<a>]]></a>", "<1a/>", "<a 1b='x'/>", "<a b='x'c='y'/>", + "<?xml version='1.0'?><a/>", " <?xml version='1.0'?><a/>", "<a/><?xml version='1.0'?>", "<a><![CDATA[x]]></a>", + "<![CDATA[x]]><a/>", "<a><![CDATA[x</a>", "<a>\x01</a>", "<a b='\x01'/>", "<a><?pi x?></a>", "<a><?pi?></a>", + "<!DOCTYPE a><a/>", "<a/><!DOCTYPE a>", "<!DOCTYPE a [<!ENTITY e 'v'>]><a>&e;</a>", "<a b='<A'/>", + "<a:b xmlns:a='u'/>", "<a\n b\n =\n 'c'\n/>", "<a></a >", "<a></ a>", "< a/>", "<a/ >", "<a b='x' / >", + "<a>é\U0001f600</a>", "<a>&<>"'</a>", "<?xml version='1.0' encoding='UTF-8' standalone='yes'?><a/>", + "<!-- c --><a/><!-- d -->", "<a><!----></a>", "", " ", "<a>x</a>trailing", "<a>x</a><!-- ok --> ", +] + + +def generate(ctx): + rng = ctx.rng(11) + docs = [] + for k in range(250): + text = gen_doc(rng) + root = ET.fromstring(text.encode("utf-8")) + docs.append({"data": text.encode("utf-8"), "canon": canon(root)}) + # other encodings: UTF-16 (BOM, both byte orders) and Latin-1 + for k in range(10): + text = gen_doc(rng) + body = text.split("?>", 1)[1] if text.startswith("<?xml") else text + c = canon(ET.fromstring(text.encode("utf-8"))) + docs.append({"data": ('<?xml version="1.0" encoding="UTF-16"?>' + body).encode("utf-16"), "canon": c}) + docs.append({"data": b"\xfe\xff" + ('<?xml version="1.0" encoding="UTF-16"?>' + body).encode("utf-16-be"), "canon": c}) + for k in range(10): + text = "<?xml version='1.0' encoding='ISO-8859-1'?><r a='éÿ'>café ½ 中</r>" + data = text.encode("latin-1") + docs.append({"data": data, "canon": canon(ET.fromstring(data))}) + ctx.emit("xml_docs", docs) + + wf = [{"data": d.encode("utf-8"), "ok": expat_ok(d.encode("utf-8"))} for d in WF] + # mutations of valid documents: delete / duplicate / replace one markup character + for k in range(400): + text = gen_doc(rng).encode("utf-8") + b = bytearray(text) + for _ in range(rng.randrange(1, 3)): + pos = rng.randrange(len(b)) + op = rng.randrange(3) + ch = rng.choice(b"<>/&;='\"![]-? ") + if op == 0: + del b[pos] + elif op == 1: + b.insert(pos, ch) + else: + b[pos] = ch + wf.append({"data": bytes(b), "ok": expat_ok(bytes(b))}) + ctx.emit("xml_wf", wf) + + parts = [] + while sum(map(len, parts)) < 1_000_000: + parts.append(gen_elem(rng, 1, {""})) + ctx.emit("xml_bench", {"text": "<root>" + "\n".join(p for p in parts if "&ent;" not in p) + "</root>"}) diff --git a/tools/fixtures/yaml.py b/tools/fixtures/yaml.py new file mode 100644 index 0000000..c45522c --- /dev/null +++ b/tools/fixtures/yaml.py @@ -0,0 +1,111 @@ +# data/yaml fixtures: the yaml-test-suite (data release 2022-01-17, pinned tarball through nix: every case's +# in.yaml, its in.json when there is one, and whether it is an error case), and a random corpus dumped by PyYAML +# (through nix) in several styles: block, flow, indent 4, explicit documents, allow_unicode, multi-document. The +# corpus avoids the strings where YAML 1.1 (PyYAML) and 1.2 resolve plain scalars differently. +# tests/gen/yaml_suite.luau { { name, yaml, json?, error } } +# tests/gen/yaml_corpus.luau { { canon, texts = { [style] = yaml } } } +# tests/gen/yaml_bench.luau { text } (~500 KB, block style) +import importlib.util, json, os, random + +_spec = importlib.util.spec_from_file_location("_data_common", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_data_common.py")) +C = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(C) + +SUITE_URL = "https://github.com/yaml/yaml-test-suite/archive/refs/tags/data-2022-01-17.tar.gz" +SUITE_SHA = "00xcny67bp56xkvz4iq6d2prvj9p48z7r705xrw49invvgyp4wnd" + +WORDS = ["a", "key", "value", "x y", "café", "中文", "\U0001f600", "multi\nline", "trail\n", "two\n\n", + " lead", "tail ", "a: b", "# c", "- x", "[x]", "{y}", "'q'", "\"dq\"", "true", "null", "~", "12", "1.5", + "0x1F", "yes", "no", "on", "-", "?", ":", "a#b", "tab\there", "back\\slash", "", "éé é", + "line1\n indented\nline3", "ends with colon:", "---", "...", "%x", "@x", "`x", "*x", "&x", "!x", "|", ">"] + + +def rand_value(rng, depth=0): + r = rng.random() + if depth > 3 or r < 0.5: + k = rng.randrange(8) + if k == 0: + return None + if k == 1: + return rng.random() < 0.5 + if k == 2: + return rng.randrange(-10 ** 12, 10 ** 12) + if k == 3: + v = round(rng.uniform(-1e5, 1e5), rng.randrange(1, 6)) + return int(v) if v.is_integer() else v + return rng.choice(WORDS) + (rng.choice(WORDS) if rng.random() < 0.3 else "") + if r < 0.75: + return [rand_value(rng, depth + 1) for _ in range(rng.randrange(0, 5))] + d = {} + for _ in range(rng.randrange(0, 5)): + k = rng.choice(WORDS[:30]) + if rng.random() < 0.15: + k = rng.randrange(100) + d[k] = rand_value(rng, depth + 1) + return d + + +DUMP = r''' +import json, sys, yaml +values = json.loads(sys.stdin.read()) +def fix(v): # JSON object keys are strings: restore the int keys marked "#int:" + if isinstance(v, dict): + return {(int(k[5:]) if k.startswith("#int:") else k): fix(x) for k, x in v.items()} + if isinstance(v, list): + return [fix(x) for x in v] + return v +out = [] +for v in values: + v = fix(v) + t = { + "block": yaml.safe_dump(v, default_flow_style=False, sort_keys=False, allow_unicode=True), + "flow": yaml.safe_dump(v, default_flow_style=True, sort_keys=False), + "indent4": yaml.safe_dump(v, default_flow_style=False, indent=4, explicit_start=True, explicit_end=True), + "auto": yaml.safe_dump(v, sort_keys=True, width=20), + "multi": yaml.safe_dump_all([v, {"second": v}], default_flow_style=False, allow_unicode=True), + } + back = yaml.safe_load(t["block"]) + out.append({"texts": t, "same": back == v}) +print(json.dumps(out)) +''' + + +def keyed(v): + if isinstance(v, dict): + return {("#int:%d" % k if isinstance(k, int) else k): keyed(x) for k, x in v.items()} + if isinstance(v, list): + return [keyed(x) for x in v] + return v + + +def generate(ctx): + root = C.fetch(SUITE_URL, SUITE_SHA) + cases = [] + for name in sorted(os.listdir(root)): + d = os.path.join(root, name) + if not os.path.isdir(d) or name.startswith("."): + continue + dirs = [d] if os.path.exists(os.path.join(d, "in.yaml")) else [os.path.join(d, x) for x in sorted(os.listdir(d))] + for dd in dirs: + if not os.path.exists(os.path.join(dd, "in.yaml")): + continue + c = {"name": os.path.relpath(dd, root), "yaml": open(os.path.join(dd, "in.yaml"), "rb").read(), + "error": os.path.exists(os.path.join(dd, "error"))} + if os.path.exists(os.path.join(dd, "in.json")): + c["json"] = open(os.path.join(dd, "in.json"), "rb").read() + cases.append(c) + ctx.emit("yaml_suite", cases) + + rng = ctx.rng(5) + values = [rand_value(rng) for _ in range(250)] + dumped = json.loads(ctx.python(["pyyaml"], DUMP, input=json.dumps([keyed(v) for v in values]).encode())) + corpus = [] + for v, d in zip(values, dumped): + if d["same"]: + corpus.append({"canon": C.canon(v), "multi": C.canon([v, {"second": v}]), "texts": d["texts"]}) + ctx.emit("yaml_corpus", corpus) + + big = [rand_value(rng) for _ in range(1500)] + text = json.loads(ctx.python(["pyyaml"], "import json, sys, yaml\nprint(json.dumps(yaml.safe_dump(json.loads(sys.stdin.read()), default_flow_style=False, allow_unicode=True)))", + input=json.dumps([x for x in big if not isinstance(x, dict) or all(isinstance(k, str) for k in x)]).encode())) + ctx.emit("yaml_bench", {"text": text}) diff --git a/tools/fixtures/zstd.py b/tools/fixtures/zstd.py new file mode 100644 index 0000000..afaa29c --- /dev/null +++ b/tools/fixtures/zstd.py @@ -0,0 +1,85 @@ +# Zstd fixtures (tools/fixtures.py): deterministic corpora compressed with the zstd CLI (the reference) at levels +# 1..19 and --ultra -22, --long, small windows (small blocks), with / without the content checksum, with / without the +# content size (stdin), multi-frame and skippable-frame streams, and empty input; plus a ~6 MB bench corpus. +# tests/gen/zstd.luau { corpora = { [name] = bytes }, cases = { { name, corpus, data } } } +# tests/gen/zstd_bench.luau { size, data3, data19, crc } +import os, random, shutil, subprocess, tempfile, zlib + + +def generate(ctx): + rng = random.Random(7) + + def zstd(args, data, from_file=True): + exe = shutil.which("zstd") + if from_file: + with tempfile.TemporaryDirectory() as d: + p = os.path.join(d, "in") + with open(p, "wb") as f: + f.write(data) + argv = ["zstd", "-q", "-c"] + args + [p] + if exe: + return subprocess.run([exe] + argv[1:], capture_output=True, check=True).stdout + return ctx.nix("zstd", argv) + argv = ["zstd", "-q", "-c"] + args + if exe: + return subprocess.run([exe] + argv[1:], input=data, capture_output=True, check=True).stdout + return ctx.nix("zstd", argv, input=data) + + def text_corpus(limit): + base = os.path.dirname(os.__file__) + out = bytearray() + for name in sorted(os.listdir(base)): + if name.endswith(".py"): + with open(os.path.join(base, name), "rb") as f: + out += f.read() + if len(out) >= limit: + break + return bytes(out[:limit]) + + text = text_corpus(400000) + corpora = { + "empty": b"", + "one": b"a", + "short": b"hello, hello, hello zstd world\n", + "text": text[:200000], + "random": rng.randbytes(50000), + "runs": b"abc" * 4000 + b"\0" * 20000 + bytes(range(256)) * 40 + b"z" * 300, + "far": (lambda r: r + rng.randbytes(30000) + r)(rng.randbytes(20000)), + "binary": bytes(rng.choice(b"\0\0\0\x01\x02\xff ABC") for _ in range(60000)), + "mixed": bytes(rng.choice(b"aaaaabbbcd\n") for _ in range(30000)) + rng.randbytes(3000) + text[200000:300000], + "big": (text + bytes(rng.choice(b"\0\0\x01\x02\x03xyz") for _ in range(200000))), + } + + cases = [] # (name, corpus, data) + for cname, data in corpora.items(): + levels = [1, 3, 19] if cname in ("big",) else [1, 2, 3, 5, 7, 9, 12, 15, 17, 19] + for lv in levels: + cases.append(("%s/l%d" % (cname, lv), cname, zstd(["-%d" % lv], data))) + if cname != "big": + cases.append(("%s/ultra22" % cname, cname, zstd(["--ultra", "-22"], data))) + cases.append(("%s/long" % cname, cname, zstd(["--long=24", "-9"], data))) + cases.append(("%s/negative" % cname, cname, zstd(["--fast=3"], data))) + cases.append(("%s/wlog10" % cname, cname, zstd(["--zstd=wlog=10", "-6"], data))) + cases.append(("%s/nocheck" % cname, cname, zstd(["-5", "--no-check"], data))) + cases.append(("%s/stdin" % cname, cname, zstd(["-4", "--check"], data, from_file=False))) + + # several frames, a skippable frame between them, and a skippable frame first + t = corpora["text"] + skip = (0x184D2A53).to_bytes(4, "little") + (11).to_bytes(4, "little") + b"skip me now" + multi = zstd(["-3"], t[:50000]) + skip + zstd(["-1", "--no-check"], corpora["runs"]) + zstd(["-3"], b"") + zstd(["-19"], t[50000:90000]) + corpora["multi"] = t[:50000] + corpora["runs"] + t[50000:90000] + cases.append(("multi/frames", "multi", multi)) + corpora["skipfirst"] = corpora["short"] + cases.append(("skipfirst/frames", "skipfirst", skip + zstd(["-3"], corpora["short"]) + skip)) + + ctx.emit("zstd", { + "corpora": corpora, + "cases": [{"name": n, "corpus": c, "data": d} for n, c, d in cases], + }) + + bench = bytearray() + while len(bench) < 6_000_000: + bench += text + bytes(rng.choice(b"\0\0\0\x01\x02\xff ABC") for _ in range(100000)) + rng.randbytes(20000) + bench = bytes(bench[:6_000_000]) + ctx.emit("zstd_bench", {"size": len(bench), "crc": zlib.crc32(bench), "data3": zstd(["-3"], bench), + "data19": zstd(["-19"], bench)}) diff --git a/tools/test.sh b/tools/test.sh index 5e80063..30868d2 100644 --- a/tools/test.sh +++ b/tools/test.sh @@ -14,7 +14,7 @@ python3 -I tools/fixtures.py $1 || { echo "FAILED: fixtures"; exit 1; } python3 -I tools/gen_registry.py > /dev/null || { echo "FAILED: gen_registry"; exit 1; } python3 -I tools/build.py || { echo "FAILED: build"; exit 1; } passed=0 -for t in $(find tests -name '*.luau' -not -path 'tests/gen/*' -not -path 'tests/fixtures/*' -not -name 'T.luau' | sort); do +for t in $(find tests -name '*.luau' -not -path 'tests/gen/*' -not -path 'tests/fixtures/*' -not -name 'T.luau' -not -name '_*' | sort); do [ -n "$1" ] && [[ "$t" != *$1* ]] && continue for rt in $RUNTIMES; do echo "== $t ($rt)"