From cdcb5b0b77a8827e2a4d5c3ac4cc1cc09975e55f Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 08:18:01 -0500 Subject: [PATCH] formats-luau foundation: build (darklua + token passes) for Roblox and LuaJIT, compat prelude, core, Types, host adapters, API + registry, lint, tests on both runtimes; absorb deflate (codecs/Deflate + new compressor) and png (image/png + new encoder) --- .gitignore | 10 + .luaurc | 7 + README.md | 76 +++ compat/luajit.lua | 630 +++++++++++++++++++++++ default.project.json | 6 + docs/FORMATS.md | 12 + docs/STYLE.md | 247 +++++++++ licenses/NOTICE.md | 10 + licenses/PngSuite-LICENSE.txt | 9 + licenses/deflate-luau-NOTICE.txt | 7 + src/Formats/Registry.luau | 31 ++ src/Formats/Types.luau | 475 +++++++++++++++++ src/Formats/codecs/Deflate/Compress.luau | 432 ++++++++++++++++ src/Formats/codecs/Deflate/Inflate.luau | 435 ++++++++++++++++ src/Formats/codecs/Deflate/init.luau | 301 +++++++++++ src/Formats/core/Adler32.luau | 50 ++ src/Formats/core/Bits.luau | 287 +++++++++++ src/Formats/core/Bytes.luau | 537 +++++++++++++++++++ src/Formats/core/Crc32.luau | 98 ++++ src/Formats/core/Err.luau | 58 +++ src/Formats/core/Huffman.luau | 306 +++++++++++ src/Formats/core/Input.luau | 62 +++ src/Formats/host/Love.luau | 149 ++++++ src/Formats/host/LuaJIT.luau | 48 ++ src/Formats/host/Luau.luau | 21 + src/Formats/host/Roblox.luau | 40 ++ src/Formats/host/init.luau | 43 ++ src/Formats/image/png/Decode.luau | 253 +++++++++ src/Formats/image/png/Encode.luau | 162 ++++++ src/Formats/image/png/init.luau | 306 +++++++++++ src/Formats/init.luau | 378 ++++++++++++++ tests/T.luau | 127 +++++ tests/api.luau | 132 +++++ tests/codecs/deflate.luau | 172 +++++++ tests/compat.luau | 275 ++++++++++ tests/core/bits.luau | 178 +++++++ tests/core/bytes.luau | 184 +++++++ tests/fixtures/pngsuite/PngSuite.png | Bin 0 -> 2262 bytes tests/fixtures/pngsuite/basi0g01.png | Bin 0 -> 217 bytes tests/fixtures/pngsuite/basi0g02.png | Bin 0 -> 154 bytes tests/fixtures/pngsuite/basi0g04.png | Bin 0 -> 247 bytes tests/fixtures/pngsuite/basi0g08.png | Bin 0 -> 254 bytes tests/fixtures/pngsuite/basi0g16.png | Bin 0 -> 299 bytes tests/fixtures/pngsuite/basi2c08.png | Bin 0 -> 315 bytes tests/fixtures/pngsuite/basi2c16.png | Bin 0 -> 595 bytes tests/fixtures/pngsuite/basi3p01.png | Bin 0 -> 132 bytes tests/fixtures/pngsuite/basi3p02.png | Bin 0 -> 193 bytes tests/fixtures/pngsuite/basi3p04.png | Bin 0 -> 327 bytes tests/fixtures/pngsuite/basi3p08.png | Bin 0 -> 1527 bytes tests/fixtures/pngsuite/basi4a08.png | Bin 0 -> 214 bytes tests/fixtures/pngsuite/basi4a16.png | Bin 0 -> 2855 bytes tests/fixtures/pngsuite/basi6a08.png | Bin 0 -> 361 bytes tests/fixtures/pngsuite/basi6a16.png | Bin 0 -> 4180 bytes tests/fixtures/pngsuite/basn0g01.png | Bin 0 -> 164 bytes tests/fixtures/pngsuite/basn0g02.png | Bin 0 -> 104 bytes tests/fixtures/pngsuite/basn0g04.png | Bin 0 -> 145 bytes tests/fixtures/pngsuite/basn0g08.png | Bin 0 -> 138 bytes tests/fixtures/pngsuite/basn0g16.png | Bin 0 -> 167 bytes tests/fixtures/pngsuite/basn2c08.png | Bin 0 -> 145 bytes tests/fixtures/pngsuite/basn2c16.png | Bin 0 -> 302 bytes tests/fixtures/pngsuite/basn3p01.png | Bin 0 -> 112 bytes tests/fixtures/pngsuite/basn3p02.png | Bin 0 -> 146 bytes tests/fixtures/pngsuite/basn3p04.png | Bin 0 -> 216 bytes tests/fixtures/pngsuite/basn3p08.png | Bin 0 -> 1286 bytes tests/fixtures/pngsuite/basn4a08.png | Bin 0 -> 126 bytes tests/fixtures/pngsuite/basn4a16.png | Bin 0 -> 2206 bytes tests/fixtures/pngsuite/basn6a08.png | Bin 0 -> 184 bytes tests/fixtures/pngsuite/basn6a16.png | Bin 0 -> 3435 bytes tests/fixtures/pngsuite/bgai4a08.png | Bin 0 -> 214 bytes tests/fixtures/pngsuite/bgai4a16.png | Bin 0 -> 2855 bytes tests/fixtures/pngsuite/bgan6a08.png | Bin 0 -> 184 bytes tests/fixtures/pngsuite/bgan6a16.png | Bin 0 -> 3435 bytes tests/fixtures/pngsuite/bgbn4a08.png | Bin 0 -> 140 bytes tests/fixtures/pngsuite/bggn4a16.png | Bin 0 -> 2220 bytes tests/fixtures/pngsuite/bgwn6a08.png | Bin 0 -> 202 bytes tests/fixtures/pngsuite/bgyn6a16.png | Bin 0 -> 3453 bytes tests/fixtures/pngsuite/ccwn2c08.png | Bin 0 -> 1514 bytes tests/fixtures/pngsuite/ccwn3p08.png | Bin 0 -> 1554 bytes tests/fixtures/pngsuite/cdfn2c08.png | Bin 0 -> 404 bytes tests/fixtures/pngsuite/cdhn2c08.png | Bin 0 -> 344 bytes tests/fixtures/pngsuite/cdsn2c08.png | Bin 0 -> 232 bytes tests/fixtures/pngsuite/cdun2c08.png | Bin 0 -> 724 bytes tests/fixtures/pngsuite/ch1n3p04.png | Bin 0 -> 258 bytes tests/fixtures/pngsuite/ch2n3p08.png | Bin 0 -> 1810 bytes tests/fixtures/pngsuite/cm0n0g04.png | Bin 0 -> 292 bytes tests/fixtures/pngsuite/cm7n0g04.png | Bin 0 -> 292 bytes tests/fixtures/pngsuite/cm9n0g04.png | Bin 0 -> 292 bytes tests/fixtures/pngsuite/cs3n2c16.png | Bin 0 -> 214 bytes tests/fixtures/pngsuite/cs3n3p08.png | Bin 0 -> 259 bytes tests/fixtures/pngsuite/cs5n2c08.png | Bin 0 -> 186 bytes tests/fixtures/pngsuite/cs5n3p08.png | Bin 0 -> 271 bytes tests/fixtures/pngsuite/cs8n2c08.png | Bin 0 -> 149 bytes tests/fixtures/pngsuite/cs8n3p08.png | Bin 0 -> 256 bytes tests/fixtures/pngsuite/ct0n0g04.png | Bin 0 -> 273 bytes tests/fixtures/pngsuite/ct1n0g04.png | Bin 0 -> 792 bytes tests/fixtures/pngsuite/cten0g04.png | Bin 0 -> 742 bytes tests/fixtures/pngsuite/ctfn0g04.png | Bin 0 -> 716 bytes tests/fixtures/pngsuite/ctgn0g04.png | Bin 0 -> 1182 bytes tests/fixtures/pngsuite/cthn0g04.png | Bin 0 -> 1269 bytes tests/fixtures/pngsuite/ctjn0g04.png | Bin 0 -> 941 bytes tests/fixtures/pngsuite/ctzn0g04.png | Bin 0 -> 753 bytes tests/fixtures/pngsuite/exif2c08.png | Bin 0 -> 1788 bytes tests/fixtures/pngsuite/f00n0g08.png | Bin 0 -> 319 bytes tests/fixtures/pngsuite/f00n2c08.png | Bin 0 -> 2475 bytes tests/fixtures/pngsuite/f01n0g08.png | Bin 0 -> 321 bytes tests/fixtures/pngsuite/f01n2c08.png | Bin 0 -> 1180 bytes tests/fixtures/pngsuite/f02n0g08.png | Bin 0 -> 355 bytes tests/fixtures/pngsuite/f02n2c08.png | Bin 0 -> 1729 bytes tests/fixtures/pngsuite/f03n0g08.png | Bin 0 -> 389 bytes tests/fixtures/pngsuite/f03n2c08.png | Bin 0 -> 1291 bytes tests/fixtures/pngsuite/f04n0g08.png | Bin 0 -> 269 bytes tests/fixtures/pngsuite/f04n2c08.png | Bin 0 -> 985 bytes tests/fixtures/pngsuite/f99n0g04.png | Bin 0 -> 426 bytes tests/fixtures/pngsuite/g03n0g16.png | Bin 0 -> 345 bytes tests/fixtures/pngsuite/g03n2c08.png | Bin 0 -> 370 bytes tests/fixtures/pngsuite/g03n3p04.png | Bin 0 -> 214 bytes tests/fixtures/pngsuite/g04n0g16.png | Bin 0 -> 363 bytes tests/fixtures/pngsuite/g04n2c08.png | Bin 0 -> 377 bytes tests/fixtures/pngsuite/g04n3p04.png | Bin 0 -> 219 bytes tests/fixtures/pngsuite/g05n0g16.png | Bin 0 -> 339 bytes tests/fixtures/pngsuite/g05n2c08.png | Bin 0 -> 350 bytes tests/fixtures/pngsuite/g05n3p04.png | Bin 0 -> 206 bytes tests/fixtures/pngsuite/g07n0g16.png | Bin 0 -> 321 bytes tests/fixtures/pngsuite/g07n2c08.png | Bin 0 -> 340 bytes tests/fixtures/pngsuite/g07n3p04.png | Bin 0 -> 207 bytes tests/fixtures/pngsuite/g10n0g16.png | Bin 0 -> 262 bytes tests/fixtures/pngsuite/g10n2c08.png | Bin 0 -> 285 bytes tests/fixtures/pngsuite/g10n3p04.png | Bin 0 -> 214 bytes tests/fixtures/pngsuite/g25n0g16.png | Bin 0 -> 383 bytes tests/fixtures/pngsuite/g25n2c08.png | Bin 0 -> 405 bytes tests/fixtures/pngsuite/g25n3p04.png | Bin 0 -> 215 bytes tests/fixtures/pngsuite/oi1n0g16.png | Bin 0 -> 167 bytes tests/fixtures/pngsuite/oi1n2c16.png | Bin 0 -> 302 bytes tests/fixtures/pngsuite/oi2n0g16.png | Bin 0 -> 179 bytes tests/fixtures/pngsuite/oi2n2c16.png | Bin 0 -> 314 bytes tests/fixtures/pngsuite/oi4n0g16.png | Bin 0 -> 203 bytes tests/fixtures/pngsuite/oi4n2c16.png | Bin 0 -> 338 bytes tests/fixtures/pngsuite/oi9n0g16.png | Bin 0 -> 1283 bytes tests/fixtures/pngsuite/oi9n2c16.png | Bin 0 -> 3038 bytes tests/fixtures/pngsuite/pp0n2c16.png | Bin 0 -> 962 bytes tests/fixtures/pngsuite/pp0n6a08.png | Bin 0 -> 818 bytes tests/fixtures/pngsuite/ps1n0g08.png | Bin 0 -> 1456 bytes tests/fixtures/pngsuite/ps1n2c16.png | Bin 0 -> 1620 bytes tests/fixtures/pngsuite/ps2n0g08.png | Bin 0 -> 2320 bytes tests/fixtures/pngsuite/ps2n2c16.png | Bin 0 -> 2484 bytes tests/fixtures/pngsuite/s01i3p01.png | Bin 0 -> 113 bytes tests/fixtures/pngsuite/s01n3p01.png | Bin 0 -> 113 bytes tests/fixtures/pngsuite/s02i3p01.png | Bin 0 -> 114 bytes tests/fixtures/pngsuite/s02n3p01.png | Bin 0 -> 115 bytes tests/fixtures/pngsuite/s03i3p01.png | Bin 0 -> 118 bytes tests/fixtures/pngsuite/s03n3p01.png | Bin 0 -> 120 bytes tests/fixtures/pngsuite/s04i3p01.png | Bin 0 -> 126 bytes tests/fixtures/pngsuite/s04n3p01.png | Bin 0 -> 121 bytes tests/fixtures/pngsuite/s05i3p02.png | Bin 0 -> 134 bytes tests/fixtures/pngsuite/s05n3p02.png | Bin 0 -> 129 bytes tests/fixtures/pngsuite/s06i3p02.png | Bin 0 -> 143 bytes tests/fixtures/pngsuite/s06n3p02.png | Bin 0 -> 131 bytes tests/fixtures/pngsuite/s07i3p02.png | Bin 0 -> 149 bytes tests/fixtures/pngsuite/s07n3p02.png | Bin 0 -> 138 bytes tests/fixtures/pngsuite/s08i3p02.png | Bin 0 -> 149 bytes tests/fixtures/pngsuite/s08n3p02.png | Bin 0 -> 139 bytes tests/fixtures/pngsuite/s09i3p02.png | Bin 0 -> 147 bytes tests/fixtures/pngsuite/s09n3p02.png | Bin 0 -> 143 bytes tests/fixtures/pngsuite/s32i3p04.png | Bin 0 -> 355 bytes tests/fixtures/pngsuite/s32n3p04.png | Bin 0 -> 263 bytes tests/fixtures/pngsuite/s33i3p04.png | Bin 0 -> 385 bytes tests/fixtures/pngsuite/s33n3p04.png | Bin 0 -> 329 bytes tests/fixtures/pngsuite/s34i3p04.png | Bin 0 -> 349 bytes tests/fixtures/pngsuite/s34n3p04.png | Bin 0 -> 248 bytes tests/fixtures/pngsuite/s35i3p04.png | Bin 0 -> 399 bytes tests/fixtures/pngsuite/s35n3p04.png | Bin 0 -> 338 bytes tests/fixtures/pngsuite/s36i3p04.png | Bin 0 -> 356 bytes tests/fixtures/pngsuite/s36n3p04.png | Bin 0 -> 258 bytes tests/fixtures/pngsuite/s37i3p04.png | Bin 0 -> 393 bytes tests/fixtures/pngsuite/s37n3p04.png | Bin 0 -> 336 bytes tests/fixtures/pngsuite/s38i3p04.png | Bin 0 -> 357 bytes tests/fixtures/pngsuite/s38n3p04.png | Bin 0 -> 245 bytes tests/fixtures/pngsuite/s39i3p04.png | Bin 0 -> 420 bytes tests/fixtures/pngsuite/s39n3p04.png | Bin 0 -> 352 bytes tests/fixtures/pngsuite/s40i3p04.png | Bin 0 -> 357 bytes tests/fixtures/pngsuite/s40n3p04.png | Bin 0 -> 256 bytes tests/fixtures/pngsuite/tbbn0g04.png | Bin 0 -> 429 bytes tests/fixtures/pngsuite/tbbn2c16.png | Bin 0 -> 2041 bytes tests/fixtures/pngsuite/tbbn3p08.png | Bin 0 -> 1499 bytes tests/fixtures/pngsuite/tbgn2c16.png | Bin 0 -> 2041 bytes tests/fixtures/pngsuite/tbgn3p08.png | Bin 0 -> 1499 bytes tests/fixtures/pngsuite/tbrn2c08.png | Bin 0 -> 1633 bytes tests/fixtures/pngsuite/tbwn0g16.png | Bin 0 -> 1313 bytes tests/fixtures/pngsuite/tbwn3p08.png | Bin 0 -> 1496 bytes tests/fixtures/pngsuite/tbyn3p08.png | Bin 0 -> 1499 bytes tests/fixtures/pngsuite/tm3n3p02.png | Bin 0 -> 116 bytes tests/fixtures/pngsuite/tp0n0g08.png | Bin 0 -> 719 bytes tests/fixtures/pngsuite/tp0n2c08.png | Bin 0 -> 1594 bytes tests/fixtures/pngsuite/tp0n3p08.png | Bin 0 -> 1476 bytes tests/fixtures/pngsuite/tp1n3p08.png | Bin 0 -> 1483 bytes tests/fixtures/pngsuite/xc1n0g08.png | Bin 0 -> 138 bytes tests/fixtures/pngsuite/xc9n2c08.png | Bin 0 -> 145 bytes tests/fixtures/pngsuite/xcrn0g04.png | Bin 0 -> 145 bytes tests/fixtures/pngsuite/xcsn0g01.png | Bin 0 -> 164 bytes tests/fixtures/pngsuite/xd0n2c08.png | Bin 0 -> 145 bytes tests/fixtures/pngsuite/xd3n2c08.png | Bin 0 -> 145 bytes tests/fixtures/pngsuite/xd9n2c08.png | Bin 0 -> 145 bytes tests/fixtures/pngsuite/xdtn0g01.png | Bin 0 -> 61 bytes tests/fixtures/pngsuite/xhdn0g08.png | Bin 0 -> 138 bytes tests/fixtures/pngsuite/xlfn0g04.png | Bin 0 -> 145 bytes tests/fixtures/pngsuite/xs1n0g01.png | Bin 0 -> 164 bytes tests/fixtures/pngsuite/xs2n0g01.png | Bin 0 -> 164 bytes tests/fixtures/pngsuite/xs4n0g01.png | Bin 0 -> 164 bytes tests/fixtures/pngsuite/xs7n0g01.png | Bin 0 -> 164 bytes tests/fixtures/pngsuite/z00n2c08.png | Bin 0 -> 3172 bytes tests/fixtures/pngsuite/z03n2c08.png | Bin 0 -> 232 bytes tests/fixtures/pngsuite/z06n2c08.png | Bin 0 -> 224 bytes tests/fixtures/pngsuite/z09n2c08.png | Bin 0 -> 224 bytes tests/fixtures/pngsuite_ref.txt | 176 +++++++ tests/image/png.luau | 157 ++++++ tools/bench.luau | 58 +++ tools/bench.sh | 9 + tools/build.py | 440 ++++++++++++++++ tools/fixtures.py | 148 ++++++ tools/fixtures/_png_reference.py | 55 ++ tools/fixtures/deflate.py | 124 +++++ tools/fixtures/png.py | 165 ++++++ tools/gen_registry.py | 181 +++++++ tools/lint.sh | 30 ++ tools/lint_rules.py | 279 ++++++++++ tools/test.sh | 33 ++ 226 files changed, 8409 insertions(+) create mode 100644 .gitignore create mode 100644 .luaurc create mode 100644 README.md create mode 100644 compat/luajit.lua create mode 100644 default.project.json create mode 100644 docs/FORMATS.md create mode 100644 docs/STYLE.md create mode 100644 licenses/NOTICE.md create mode 100644 licenses/PngSuite-LICENSE.txt create mode 100644 licenses/deflate-luau-NOTICE.txt create mode 100644 src/Formats/Registry.luau create mode 100644 src/Formats/Types.luau create mode 100644 src/Formats/codecs/Deflate/Compress.luau create mode 100644 src/Formats/codecs/Deflate/Inflate.luau create mode 100644 src/Formats/codecs/Deflate/init.luau create mode 100644 src/Formats/core/Adler32.luau create mode 100644 src/Formats/core/Bits.luau create mode 100644 src/Formats/core/Bytes.luau create mode 100644 src/Formats/core/Crc32.luau create mode 100644 src/Formats/core/Err.luau create mode 100644 src/Formats/core/Huffman.luau create mode 100644 src/Formats/core/Input.luau create mode 100644 src/Formats/host/Love.luau create mode 100644 src/Formats/host/LuaJIT.luau create mode 100644 src/Formats/host/Luau.luau create mode 100644 src/Formats/host/Roblox.luau create mode 100644 src/Formats/host/init.luau create mode 100644 src/Formats/image/png/Decode.luau create mode 100644 src/Formats/image/png/Encode.luau create mode 100644 src/Formats/image/png/init.luau create mode 100644 src/Formats/init.luau create mode 100644 tests/T.luau create mode 100644 tests/api.luau create mode 100644 tests/codecs/deflate.luau create mode 100644 tests/compat.luau create mode 100644 tests/core/bits.luau create mode 100644 tests/core/bytes.luau create mode 100644 tests/fixtures/pngsuite/PngSuite.png create mode 100644 tests/fixtures/pngsuite/basi0g01.png create mode 100644 tests/fixtures/pngsuite/basi0g02.png create mode 100644 tests/fixtures/pngsuite/basi0g04.png create mode 100644 tests/fixtures/pngsuite/basi0g08.png create mode 100644 tests/fixtures/pngsuite/basi0g16.png create mode 100644 tests/fixtures/pngsuite/basi2c08.png create mode 100644 tests/fixtures/pngsuite/basi2c16.png create mode 100644 tests/fixtures/pngsuite/basi3p01.png create mode 100644 tests/fixtures/pngsuite/basi3p02.png create mode 100644 tests/fixtures/pngsuite/basi3p04.png create mode 100644 tests/fixtures/pngsuite/basi3p08.png create mode 100644 tests/fixtures/pngsuite/basi4a08.png create mode 100644 tests/fixtures/pngsuite/basi4a16.png create mode 100644 tests/fixtures/pngsuite/basi6a08.png create mode 100644 tests/fixtures/pngsuite/basi6a16.png create mode 100644 tests/fixtures/pngsuite/basn0g01.png create mode 100644 tests/fixtures/pngsuite/basn0g02.png create mode 100644 tests/fixtures/pngsuite/basn0g04.png create mode 100644 tests/fixtures/pngsuite/basn0g08.png create mode 100644 tests/fixtures/pngsuite/basn0g16.png create mode 100644 tests/fixtures/pngsuite/basn2c08.png create mode 100644 tests/fixtures/pngsuite/basn2c16.png create mode 100644 tests/fixtures/pngsuite/basn3p01.png create mode 100644 tests/fixtures/pngsuite/basn3p02.png create mode 100644 tests/fixtures/pngsuite/basn3p04.png create mode 100644 tests/fixtures/pngsuite/basn3p08.png create mode 100644 tests/fixtures/pngsuite/basn4a08.png create mode 100644 tests/fixtures/pngsuite/basn4a16.png create mode 100644 tests/fixtures/pngsuite/basn6a08.png create mode 100644 tests/fixtures/pngsuite/basn6a16.png create mode 100644 tests/fixtures/pngsuite/bgai4a08.png create mode 100644 tests/fixtures/pngsuite/bgai4a16.png create mode 100644 tests/fixtures/pngsuite/bgan6a08.png create mode 100644 tests/fixtures/pngsuite/bgan6a16.png create mode 100644 tests/fixtures/pngsuite/bgbn4a08.png create mode 100644 tests/fixtures/pngsuite/bggn4a16.png create mode 100644 tests/fixtures/pngsuite/bgwn6a08.png create mode 100644 tests/fixtures/pngsuite/bgyn6a16.png create mode 100644 tests/fixtures/pngsuite/ccwn2c08.png create mode 100644 tests/fixtures/pngsuite/ccwn3p08.png create mode 100644 tests/fixtures/pngsuite/cdfn2c08.png create mode 100644 tests/fixtures/pngsuite/cdhn2c08.png create mode 100644 tests/fixtures/pngsuite/cdsn2c08.png create mode 100644 tests/fixtures/pngsuite/cdun2c08.png create mode 100644 tests/fixtures/pngsuite/ch1n3p04.png create mode 100644 tests/fixtures/pngsuite/ch2n3p08.png create mode 100644 tests/fixtures/pngsuite/cm0n0g04.png create mode 100644 tests/fixtures/pngsuite/cm7n0g04.png create mode 100644 tests/fixtures/pngsuite/cm9n0g04.png create mode 100644 tests/fixtures/pngsuite/cs3n2c16.png create mode 100644 tests/fixtures/pngsuite/cs3n3p08.png create mode 100644 tests/fixtures/pngsuite/cs5n2c08.png create mode 100644 tests/fixtures/pngsuite/cs5n3p08.png create mode 100644 tests/fixtures/pngsuite/cs8n2c08.png create mode 100644 tests/fixtures/pngsuite/cs8n3p08.png create mode 100644 tests/fixtures/pngsuite/ct0n0g04.png create mode 100644 tests/fixtures/pngsuite/ct1n0g04.png create mode 100644 tests/fixtures/pngsuite/cten0g04.png create mode 100644 tests/fixtures/pngsuite/ctfn0g04.png create mode 100644 tests/fixtures/pngsuite/ctgn0g04.png create mode 100644 tests/fixtures/pngsuite/cthn0g04.png create mode 100644 tests/fixtures/pngsuite/ctjn0g04.png create mode 100644 tests/fixtures/pngsuite/ctzn0g04.png create mode 100644 tests/fixtures/pngsuite/exif2c08.png create mode 100644 tests/fixtures/pngsuite/f00n0g08.png create mode 100644 tests/fixtures/pngsuite/f00n2c08.png create mode 100644 tests/fixtures/pngsuite/f01n0g08.png create mode 100644 tests/fixtures/pngsuite/f01n2c08.png create mode 100644 tests/fixtures/pngsuite/f02n0g08.png create mode 100644 tests/fixtures/pngsuite/f02n2c08.png create mode 100644 tests/fixtures/pngsuite/f03n0g08.png create mode 100644 tests/fixtures/pngsuite/f03n2c08.png create mode 100644 tests/fixtures/pngsuite/f04n0g08.png create mode 100644 tests/fixtures/pngsuite/f04n2c08.png create mode 100644 tests/fixtures/pngsuite/f99n0g04.png create mode 100644 tests/fixtures/pngsuite/g03n0g16.png create mode 100644 tests/fixtures/pngsuite/g03n2c08.png create mode 100644 tests/fixtures/pngsuite/g03n3p04.png create mode 100644 tests/fixtures/pngsuite/g04n0g16.png create mode 100644 tests/fixtures/pngsuite/g04n2c08.png create mode 100644 tests/fixtures/pngsuite/g04n3p04.png create mode 100644 tests/fixtures/pngsuite/g05n0g16.png create mode 100644 tests/fixtures/pngsuite/g05n2c08.png create mode 100644 tests/fixtures/pngsuite/g05n3p04.png create mode 100644 tests/fixtures/pngsuite/g07n0g16.png create mode 100644 tests/fixtures/pngsuite/g07n2c08.png create mode 100644 tests/fixtures/pngsuite/g07n3p04.png create mode 100644 tests/fixtures/pngsuite/g10n0g16.png create mode 100644 tests/fixtures/pngsuite/g10n2c08.png create mode 100644 tests/fixtures/pngsuite/g10n3p04.png create mode 100644 tests/fixtures/pngsuite/g25n0g16.png create mode 100644 tests/fixtures/pngsuite/g25n2c08.png create mode 100644 tests/fixtures/pngsuite/g25n3p04.png create mode 100644 tests/fixtures/pngsuite/oi1n0g16.png create mode 100644 tests/fixtures/pngsuite/oi1n2c16.png create mode 100644 tests/fixtures/pngsuite/oi2n0g16.png create mode 100644 tests/fixtures/pngsuite/oi2n2c16.png create mode 100644 tests/fixtures/pngsuite/oi4n0g16.png create mode 100644 tests/fixtures/pngsuite/oi4n2c16.png create mode 100644 tests/fixtures/pngsuite/oi9n0g16.png create mode 100644 tests/fixtures/pngsuite/oi9n2c16.png create mode 100644 tests/fixtures/pngsuite/pp0n2c16.png create mode 100644 tests/fixtures/pngsuite/pp0n6a08.png create mode 100644 tests/fixtures/pngsuite/ps1n0g08.png create mode 100644 tests/fixtures/pngsuite/ps1n2c16.png create mode 100644 tests/fixtures/pngsuite/ps2n0g08.png create mode 100644 tests/fixtures/pngsuite/ps2n2c16.png create mode 100644 tests/fixtures/pngsuite/s01i3p01.png create mode 100644 tests/fixtures/pngsuite/s01n3p01.png create mode 100644 tests/fixtures/pngsuite/s02i3p01.png create mode 100644 tests/fixtures/pngsuite/s02n3p01.png create mode 100644 tests/fixtures/pngsuite/s03i3p01.png create mode 100644 tests/fixtures/pngsuite/s03n3p01.png create mode 100644 tests/fixtures/pngsuite/s04i3p01.png create mode 100644 tests/fixtures/pngsuite/s04n3p01.png create mode 100644 tests/fixtures/pngsuite/s05i3p02.png create mode 100644 tests/fixtures/pngsuite/s05n3p02.png create mode 100644 tests/fixtures/pngsuite/s06i3p02.png create mode 100644 tests/fixtures/pngsuite/s06n3p02.png create mode 100644 tests/fixtures/pngsuite/s07i3p02.png create mode 100644 tests/fixtures/pngsuite/s07n3p02.png create mode 100644 tests/fixtures/pngsuite/s08i3p02.png create mode 100644 tests/fixtures/pngsuite/s08n3p02.png create mode 100644 tests/fixtures/pngsuite/s09i3p02.png create mode 100644 tests/fixtures/pngsuite/s09n3p02.png create mode 100644 tests/fixtures/pngsuite/s32i3p04.png create mode 100644 tests/fixtures/pngsuite/s32n3p04.png create mode 100644 tests/fixtures/pngsuite/s33i3p04.png create mode 100644 tests/fixtures/pngsuite/s33n3p04.png create mode 100644 tests/fixtures/pngsuite/s34i3p04.png create mode 100644 tests/fixtures/pngsuite/s34n3p04.png create mode 100644 tests/fixtures/pngsuite/s35i3p04.png create mode 100644 tests/fixtures/pngsuite/s35n3p04.png create mode 100644 tests/fixtures/pngsuite/s36i3p04.png create mode 100644 tests/fixtures/pngsuite/s36n3p04.png create mode 100644 tests/fixtures/pngsuite/s37i3p04.png create mode 100644 tests/fixtures/pngsuite/s37n3p04.png create mode 100644 tests/fixtures/pngsuite/s38i3p04.png create mode 100644 tests/fixtures/pngsuite/s38n3p04.png create mode 100644 tests/fixtures/pngsuite/s39i3p04.png create mode 100644 tests/fixtures/pngsuite/s39n3p04.png create mode 100644 tests/fixtures/pngsuite/s40i3p04.png create mode 100644 tests/fixtures/pngsuite/s40n3p04.png create mode 100644 tests/fixtures/pngsuite/tbbn0g04.png create mode 100644 tests/fixtures/pngsuite/tbbn2c16.png create mode 100644 tests/fixtures/pngsuite/tbbn3p08.png create mode 100644 tests/fixtures/pngsuite/tbgn2c16.png create mode 100644 tests/fixtures/pngsuite/tbgn3p08.png create mode 100644 tests/fixtures/pngsuite/tbrn2c08.png create mode 100644 tests/fixtures/pngsuite/tbwn0g16.png create mode 100644 tests/fixtures/pngsuite/tbwn3p08.png create mode 100644 tests/fixtures/pngsuite/tbyn3p08.png create mode 100644 tests/fixtures/pngsuite/tm3n3p02.png create mode 100644 tests/fixtures/pngsuite/tp0n0g08.png create mode 100644 tests/fixtures/pngsuite/tp0n2c08.png create mode 100644 tests/fixtures/pngsuite/tp0n3p08.png create mode 100644 tests/fixtures/pngsuite/tp1n3p08.png create mode 100644 tests/fixtures/pngsuite/xc1n0g08.png create mode 100644 tests/fixtures/pngsuite/xc9n2c08.png create mode 100644 tests/fixtures/pngsuite/xcrn0g04.png create mode 100644 tests/fixtures/pngsuite/xcsn0g01.png create mode 100644 tests/fixtures/pngsuite/xd0n2c08.png create mode 100644 tests/fixtures/pngsuite/xd3n2c08.png create mode 100644 tests/fixtures/pngsuite/xd9n2c08.png create mode 100644 tests/fixtures/pngsuite/xdtn0g01.png create mode 100644 tests/fixtures/pngsuite/xhdn0g08.png create mode 100644 tests/fixtures/pngsuite/xlfn0g04.png create mode 100644 tests/fixtures/pngsuite/xs1n0g01.png create mode 100644 tests/fixtures/pngsuite/xs2n0g01.png create mode 100644 tests/fixtures/pngsuite/xs4n0g01.png create mode 100644 tests/fixtures/pngsuite/xs7n0g01.png create mode 100644 tests/fixtures/pngsuite/z00n2c08.png create mode 100644 tests/fixtures/pngsuite/z03n2c08.png create mode 100644 tests/fixtures/pngsuite/z06n2c08.png create mode 100644 tests/fixtures/pngsuite/z09n2c08.png create mode 100644 tests/fixtures/pngsuite_ref.txt create mode 100644 tests/image/png.luau create mode 100644 tools/bench.luau create mode 100644 tools/bench.sh create mode 100644 tools/build.py create mode 100644 tools/fixtures.py create mode 100644 tools/fixtures/_png_reference.py create mode 100644 tools/fixtures/deflate.py create mode 100644 tools/fixtures/png.py create mode 100644 tools/gen_registry.py create mode 100644 tools/lint.sh create mode 100644 tools/lint_rules.py create mode 100644 tools/test.sh diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..bf2550b --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +# build outputs (tools/build.py) and generated test fixtures (tools/fixtures.py) +/build/ +/tests/gen/ +# Rojo +/*.rbxm +/*.rbxmx +/*.rbxl +/*.rbxlx +sourcemap.json +__pycache__/ diff --git a/.luaurc b/.luaurc new file mode 100644 index 0000000..16031cc --- /dev/null +++ b/.luaurc @@ -0,0 +1,7 @@ +{ + "languageMode": "nonstrict", + "aliases": { + "formats": "./src/Formats", + "tests": "./tests" + } +} diff --git a/README.md b/README.md new file mode 100644 index 0000000..4c5c37e --- /dev/null +++ b/README.md @@ -0,0 +1,76 @@ +# formats-luau + +Read, write and convert file formats in pure Luau, from one source tree that runs on **Roblox** (Luau, native code +generation) and on **LuaJIT / LÖVE** (through `tools/build.py`). Every format of a category maps onto one standard type +(`src/Formats/Types.luau`): a PNG and a WebP both load as an `Image`, every audio format opens as the same streaming +`Decoder`. + +Status: foundation. Formats so far: PNG (read / write). Codecs: DEFLATE (inflate + compressor, zlib, gzip). See +[docs/FORMATS.md](docs/FORMATS.md) (generated) for the capability matrix. + +```luau +local F = require(Formats) -- LuaJIT: require("formats"); luau CLI: require("@formats") +local img, err = F.load(src) -- src: buffer | string | path (hosts with files) +if not img then print(tostring(err)) end -- errors are values: "png: CORRUPT at 0x21: bad filter type 7" +local buf = F.save(img, nil, { format = "png" }) -- a buffer; F.save(img, "out.png") writes a file +local s = F.saveString(img, { format = "png" }) +local out = F.convert(src, "png", { level = 9 }) +local img2 = F.image.load(src) -- category facades: F.image / audio / video / model / font / ... +for _, f in F.formats() do print(f.name, f.caps.decode, f.caps.encode) end +``` + +Nothing throws on bad data or bad arguments: every call returns `nil, err` (`err.code` is one of the `F.Err` codes). + +## Runtimes + +| Runtime | How | Files | +|---|---|---| +| Roblox | `python3 -I tools/build.py roblox`, then `rojo build` / `rojo serve` (`default.project.json` mounts `build/roblox/Formats`) | none: pass buffers / strings; `F.host.toEditableImage(img)` | +| LuaJIT | `python3 -I tools/build.py luajit`; `package.path = "build/luajit/?.lua;build/luajit/?/init.lua;" .. package.path` | `io.open` | +| LÖVE | the LuaJIT build, copied into the game | `love.filesystem` (+ `io`); `F.host.toImageData(img)`, `F.host.fromImageData(id)`, `F.host.toSoundData(audio or decoder)` | +| luau CLI | `luau` with the `.luaurc` alias `@formats` (`src/` directly) | none | + +The LuaJIT build supplies the Luau standard library pieces it needs from `compat/luajit.lua` (unsigned `bit32`, +`buffer` on FFI memory, `table.create`, `math.clamp`, `string.split`, `utf8`, ...), required by each module, without +touching globals (`require("formats._compat").install()` puts `buffer` / `bit32` / `utf8` / `typeof` in `_G` if a +game wants them). + +## Development + +```sh +bash tools/test.sh # fixtures, registry, build, every test under luau --codegen -O2 and LuaJIT, lint +bash tools/test.sh png # one test (both runtimes), no lint +bash tools/lint.sh # globals, headers, requires, native-throw, layers, deps, contract, registry +bash tools/bench.sh # throughput on both runtimes (pin it: taskset -c 2 bash tools/bench.sh) +python3 -I tools/build.py # build/roblox + build/luajit +python3 -I tools/gen_registry.py # src/Formats/Registry.luau + docs/FORMATS.md from the format folders +python3 -I tools/fixtures.py # tests/gen/*.luau from tools/fixtures/*.py +``` + +Tools: python3, and through nix: `luau` (+ `luau-analyze`), `luajit`, `darklua` 0.19, `rojo` (each script finds them +on PATH or runs them with `nix shell nixpkgs#`). + +Layout, layering, the format contract, how to add a format or absorb a repo: [docs/STYLE.md](docs/STYLE.md). + +``` +src/Formats/ init.luau (API) Types.luau Registry.luau (generated) core/ host/ codecs/ containers/ + // ops/ +compat/luajit.lua tools/ tests/ (T.luau, /.luau, fixtures/, gen/) docs/ licenses/ +``` + +## Performance (one Zen 5 core, `taskset -c 2 bash tools/bench.sh`) + +| | luau --codegen -O2 | LuaJIT 2.1 | +|---|---|---| +| inflate, 6 MB text + binary (exact size) | ~330 MB/s | ~470 MB/s | +| zlib (inflate + Adler-32) | ~170 MB/s | ~280 MB/s | +| CRC-32 | ~310 MB/s | ~520 MB/s | +| PNG decode 1024x768 RGBA | ~52 MB/s | ~30-75 MB/s | +| deflate compress -6 | ~12 MB/s | ~8-20 MB/s | + +LuaJIT numbers vary between runs: its trace recorder is randomised, and about one run in ten picks a slower trace +layout for a loop (inflate then runs at ~190 MB/s). Unpinned runs on this hybrid CPU also differ 2x between core types. + +## Licence + +See [licenses/NOTICE.md](licenses/NOTICE.md). diff --git a/compat/luajit.lua b/compat/luajit.lua new file mode 100644 index 0000000..3b7a194 --- /dev/null +++ b/compat/luajit.lua @@ -0,0 +1,630 @@ +-- compat/luajit.lua: the Luau standard library pieces formats-luau uses, for LuaJIT 2.1 (plain luajit and LÖVE). +-- tools/build.py copies this file to build/luajit/formats/_compat.lua, and every built module starts with +-- local __compat = require("formats._compat") local buffer, bit32, utf8, typeof, type, __iter = ... +-- on its first line (so line numbers match the source). Nothing here is installed as a global; the table/math/string +-- additions (table.create, math.clamp, string.split, ...) are added to the standard libraries only where missing. +-- +-- Semantics follow Luau (checked by tests/compat.luau under both runtimes): +-- bit32 unsigned 32-bit results; shift counts outside -31..31 give 0; extract/replace/countlz/countrz/byteswap +-- (fractional operands: see the bit32 section). +-- buffer fixed-size byte arrays on FFI memory, little-endian, zero-filled; out-of-bounds access throws +-- "buffer access out of bounds" like Luau. A buffer is a table { p = uint8_t*, n = length } with a +-- private metatable: typeof(b) and the injected type(b) return "buffer". +-- __iter Luau's generalized iteration (`for k, v in t do`): build.py rewrites such loops to +-- `for k, v in __iter(t) do`. Functions pass through; arrays iterate with ipairs (JIT-compiled) when the +-- table has no keys past #t, anything else with next. +-- LuaJIT-only extensions (not in Luau; host/love uses them when present): buffer.toffi(b) -> uint8_t* (valid while b +-- is alive), buffer.fromffi(ptr, n) -> a new buffer with a copy of n bytes. +local ffi = require("ffi") +local bit = require("bit") +local floor = math.floor +local rawtype, getmetatable, setmetatable, select, error, pairs, ipairs, next = type, getmetatable, setmetatable, select, error, pairs, ipairs, next + +local TWO32 = 4294967296 + +local M = {} + +-- ---------------------------------------------------------------------------------------------------- bit32 +-- LuaJIT's bit.* take any number in +-2^51 (reduced mod 2^32) and return a signed int32; Luau returns the uint32. +-- Performance (inflate, pinned to one core): the sign fix written inline as `if r < 0 then r = r + 2^32 end` runs +-- about 45% faster than `r % 2^32`; operands are passed to bit.* as they are (no truncation step). +-- Divergence from Luau: a fractional operand is rounded by bit.tobit where Luau truncates it. The library never +-- passes fractions to bit32 (tests/compat.luau checks integers only). +do + local band, bor, bxor, bnot, lshift, rshift, arshift, bswap = + bit.band, bit.bor, bit.bxor, bit.bnot, bit.lshift, bit.rshift, bit.arshift, bit.bswap + local B = {} + -- the 2- and 3-argument forms are the hot ones: no varargs on that path + function B.band(a, b, c, d, ...) + local r + if b == nil then + if a == nil then return TWO32 - 1 end + r = band(a, -1) + else + r = band(a, b) + if c ~= nil then + r = band(r, c) + if d ~= nil then + r = band(r, d) + for i = 1, select("#", ...) do r = band(r, (select(i, ...))) end + end + end + end + if r < 0 then r = r + TWO32 end + return r + end + function B.bor(a, b, c, d, ...) + local r + if b == nil then + if a == nil then return 0 end + r = band(a, -1) + else + r = bor(a, b) + if c ~= nil then + r = bor(r, c) + if d ~= nil then + r = bor(r, d) + for i = 1, select("#", ...) do r = bor(r, (select(i, ...))) end + end + end + end + if r < 0 then r = r + TWO32 end + return r + end + function B.bxor(a, b, c, d, e, f, g, h, ...) + local r + if b == nil then + if a == nil then return 0 end + r = band(a, -1) + else + r = bxor(a, b) + if c ~= nil then + r = bxor(r, c) + if d ~= nil then + r = bxor(r, d) + if e ~= nil then + r = bxor(r, e) + if f ~= nil then + r = bxor(r, f) + if g ~= nil then + r = bxor(r, g) + if h ~= nil then + r = bxor(r, h) + for i = 1, select("#", ...) do r = bxor(r, (select(i, ...))) end + end + end + end + end + end + end + end + if r < 0 then r = r + TWO32 end + return r + end + function B.btest(...) + return B.band(...) ~= 0 + end + function B.bnot(a) + local r = bnot(a) + if r < 0 then r = r + TWO32 end + return r + end + function B.lshift(a, n) + if n >= 32 or n <= -32 then return 0 end + local r + if n < 0 then r = rshift(a, -n) else r = lshift(a, n) end + if r < 0 then r = r + TWO32 end + return r + end + function B.rshift(a, n) + if n >= 32 or n <= -32 then return 0 end + local r + if n < 0 then r = lshift(a, -n) else r = rshift(a, n) end + if r < 0 then r = r + TWO32 end + return r + end + function B.arshift(a, n) + if n <= -32 then return 0 end + if n >= 32 then n = 31 end + local r + if n < 0 then r = lshift(a, -n) else r = arshift(a, n) end + if r < 0 then r = r + TWO32 end + return r + end + function B.lrotate(a, n) + n = n % 32 + local r = n == 0 and band(a, -1) or bor(lshift(a, n), rshift(a, 32 - n)) + if r < 0 then r = r + TWO32 end + return r + end + function B.rrotate(a, n) + return B.lrotate(a, -n) + end + function B.extract(a, field, width) + width = width or 1 + if field < 0 or width <= 0 or field + width > 32 then error("bit32.extract: trying to access non-existent bits", 2) end + local r = rshift(a, field) + if width < 32 then r = band(r, lshift(1, width) - 1) end + if r < 0 then r = r + TWO32 end + return r + end + function B.replace(a, v, field, width) + width = width or 1 + if field < 0 or width <= 0 or field + width > 32 then error("bit32.replace: trying to access non-existent bits", 2) end + local m = width == 32 and -1 or lshift(lshift(1, width) - 1, field) + local r = bor(band(a, bnot(m)), band(lshift(v, field), m)) + if r < 0 then r = r + TWO32 end + return r + end + function B.countlz(a) + a = band(a, -1) + if a == 0 then return 32 end + local n = 0 + if band(a, -65536) == 0 then n = n + 16; a = lshift(a, 16) end + if band(a, -16777216) == 0 then n = n + 8; a = lshift(a, 8) end + if band(a, -268435456) == 0 then n = n + 4; a = lshift(a, 4) end + if band(a, -1073741824) == 0 then n = n + 2; a = lshift(a, 2) end + if band(a, -2147483648) == 0 then n = n + 1 end + return n + end + function B.countrz(a) + a = band(a, -1) + if a == 0 then return 32 end + local n = 0 + while band(a, 1) == 0 do + a = rshift(a, 1) + n = n + 1 + end + return n + end + function B.byteswap(a) + local r = bswap(a) + if r < 0 then r = r + TWO32 end + return r + end + M.bit32 = B +end + +-- ---------------------------------------------------------------------------------------------------- buffer +do + ffi.cdef([[ + void *memmove(void *dst, const void *src, size_t n); + void *memset(void *s, int c, size_t n); + void *calloc(size_t n, size_t size); + void free(void *p); + ]]) + local C = ffi.C + local u8p = ffi.typeof("uint8_t*") + local i8p = ffi.typeof("int8_t*") + local u16p, i16p = ffi.typeof("uint16_t*"), ffi.typeof("int16_t*") + local u32p, i32p = ffi.typeof("uint32_t*"), ffi.typeof("int32_t*") + local f32p, f64p = ffi.typeof("float*"), ffi.typeof("double*") + local u8arr = ffi.typeof("uint8_t[?]") + local cast, fstring, fcopy = ffi.cast, ffi.string, ffi.copy + + local BUF = { __name = "buffer" } + BUF.__index = function() error("attempt to index a buffer value", 2) end + BUF.__tostring = function(b) return ("buffer: %p"):format(b.p) end + M.BUFFER_MT = BUF + + -- Small buffers live in GC memory (ffi.new); big ones in calloc'd memory, so they do not count against the + -- 2 GB GC heap of non-GC64 builds (LÖVE). The GC does not see calloc'd bytes, so a full collection runs every + -- 512 MB of them. + local BIG = 262144 + local external = 0 + + local function oob() + error("buffer access out of bounds", 3) + end + + local Buf = {} + local function create(n) + if rawtype(n) ~= "number" or n < 0 then error("buffer.create: invalid size", 2) end + n = floor(n) + local mem, p + if n < BIG then + mem = u8arr(n > 0 and n or 1) + p = cast(u8p, mem) + else + external = external + n + if external > 536870912 then + external = 0 + collectgarbage() + end + local raw = C.calloc(n, 1) + if raw == nil then error("buffer.create: out of memory", 2) end + mem = ffi.gc(cast(u8p, raw), C.free) + p = mem + end + -- p, n and m are raw fields, so the throwing __index only runs for misuse (b.x on a buffer) + return setmetatable({ p = p, n = n, m = mem }, BUF) + end + Buf.create = create + function Buf.len(b) return b.n end + + -- reads / writes: o must satisfy 0 <= o and o + size <= n (Luau truncates a fractional offset) + function Buf.readu8(b, o) + if o < 0 or o >= b.n then oob() end + return b.p[o] + end + function Buf.readi8(b, o) + if o < 0 or o >= b.n then oob() end + return cast(i8p, b.p)[o] + end + function Buf.readu16(b, o) + if o < 0 or o + 2 > b.n then oob() end + return cast(u16p, b.p + o)[0] + end + function Buf.readi16(b, o) + if o < 0 or o + 2 > b.n then oob() end + return cast(i16p, b.p + o)[0] + end + function Buf.readu32(b, o) + if o < 0 or o + 4 > b.n then oob() end + return cast(u32p, b.p + o)[0] + end + function Buf.readi32(b, o) + if o < 0 or o + 4 > b.n then oob() end + return cast(i32p, b.p + o)[0] + end + function Buf.readf32(b, o) + if o < 0 or o + 4 > b.n then oob() 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 + 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 + -- 8/16-bit stores and through int64 for 32-bit ones, so values in +-2^51 wrap correctly + function Buf.writeu8(b, o, v) + if o < 0 or o >= b.n then oob() end + b.p[o] = v + end + function Buf.writei8(b, o, v) + if o < 0 or o >= b.n then oob() end + b.p[o] = v + end + function Buf.writeu16(b, o, v) + if o < 0 or o + 2 > b.n then oob() end + cast(u16p, b.p + o)[0] = v + end + Buf.writei16 = Buf.writeu16 + function Buf.writeu32(b, o, v) + if o < 0 or o + 4 > b.n then oob() end + cast(u32p, b.p + o)[0] = v % TWO32 + end + Buf.writei32 = Buf.writeu32 + function Buf.writef32(b, o, v) + if o < 0 or o + 4 > b.n then oob() end + cast(f32p, b.p + o)[0] = v + end + function Buf.writef64(b, o, v) + if o < 0 or o + 8 > b.n then oob() end + cast(f64p, b.p + o)[0] = v + end + + function Buf.readstring(b, o, count) + if o < 0 or count < 0 or o + count > b.n then oob() end + return fstring(b.p + o, count) + end + function Buf.writestring(b, o, s, count) + count = count or #s + if count < 0 or count > #s then error("buffer.writestring: string length overflow", 2) end + if o < 0 or o + count > b.n then oob() end + fcopy(b.p + o, s, count) + end + function Buf.copy(target, toff, source, soff, count) + soff = soff or 0 + if soff < 0 or soff > source.n then oob() end + count = count or (source.n - soff) + if count < 0 or soff + count > source.n or toff < 0 or toff + count > target.n then oob() end + if count > 0 then C.memmove(target.p + toff, source.p + soff, count) end + end + function Buf.fill(b, o, v, count) + if o < 0 or o > b.n then oob() end + count = count or (b.n - o) + if count < 0 or o + count > b.n then oob() end + if count > 0 then C.memset(b.p + o, v % 256, count) end + end + function Buf.tostring(b) return fstring(b.p, b.n) end + function Buf.fromstring(s) + local b = create(#s) + fcopy(b.p, s, #s) + return b + end + + -- readbits / writebits: bit i of the buffer is bit (i % 8) of byte i // 8 (little-endian bit order), up to 32 bits + function Buf.readbits(b, bitOffset, bitCount) + if bitCount < 0 or bitCount > 32 then error("bit count is out of range of [0; 32]", 2) end + if bitOffset < 0 or bitOffset + bitCount > b.n * 8 then oob() end + local v, scale = 0, 1 + local i = bitOffset + local e = bitOffset + bitCount + while i < e do + local byte = floor(i / 8) + local sh = i % 8 + local take = 8 - sh + if take > e - i then take = e - i end + local x = bit.band(bit.rshift(b.p[byte], sh), bit.lshift(1, take) - 1) + v = v + x * scale + scale = scale * 2 ^ take + i = i + take + end + return v + end + function Buf.writebits(b, bitOffset, bitCount, value) + if bitCount < 0 or bitCount > 32 then error("bit count is out of range of [0; 32]", 2) end + if bitOffset < 0 or bitOffset + bitCount > b.n * 8 then oob() end + value = value % TWO32 + local i = bitOffset + local e = bitOffset + bitCount + while i < e do + local byte = floor(i / 8) + local sh = i % 8 + local take = 8 - sh + if take > e - i then take = e - i end + local m = bit.lshift(bit.lshift(1, take) - 1, sh) + local x = bit.band(bit.lshift(value % 256, sh), m) + b.p[byte] = bit.bor(bit.band(b.p[byte], bit.bnot(m)), x) + value = floor(value / 2 ^ take) + i = i + take + end + end + + -- LuaJIT-only extensions + function Buf.toffi(b) return b.p end + function Buf.fromffi(ptr, n) + local b = create(n) + if n > 0 then fcopy(b.p, ptr, n) end + return b + end + M.buffer = Buf +end + +-- ---------------------------------------------------------------------------------------------------- typeof / type +do + local BUF = M.BUFFER_MT + function M.type(v) + local t = rawtype(v) + if t == "table" and getmetatable(v) == BUF then + return "buffer" + end + return t + end + M.typeof = M.type + M.isbuffer = function(v) return getmetatable(v) == BUF end +end + +-- ---------------------------------------------------------------------------------------------------- __iter +function M.__iter(t, s, c) + if rawtype(t) == "function" then return t, s, c end + if rawtype(t) ~= "table" then error("attempt to iterate over a " .. M.type(t) .. " value", 2) end + 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 + return next, t, nil +end + +-- ---------------------------------------------------------------------------------------------------- table +do + local okn, tnew = pcall(require, "table.new") + local okc, tclear = pcall(require, "table.clear") + if not table.create then + function table.create(n, v) + local t = okn and tnew(n, 0) or {} + if v ~= nil then for i = 1, n do t[i] = v end end + return t + end + end + table.clear = table.clear or (okc and tclear) or function(t) for k in pairs(t) do t[k] = nil end end + table.unpack = table.unpack or unpack + table.pack = table.pack or function(...) return { n = select("#", ...), ... } end + table.find = table.find or function(t, v, init) + for i = init or 1, #t do if t[i] == v then return i end end + return nil + end + table.move = table.move or function(a1, f, e, t, a2) + a2 = a2 or a1 + if e >= f then + if t > f or t > e or a1 ~= a2 then + for i = 0, e - f do a2[t + i] = a1[f + i] end + else + for i = e - f, 0, -1 do a2[t + i] = a1[f + i] end + end + end + return a2 + end + -- freeze is advisory on LuaJIT (no read-only tables): it only records the table for isfrozen + local frozen = setmetatable({}, { __mode = "k" }) + table.freeze = table.freeze or function(t) frozen[t] = true; return t end + table.isfrozen = table.isfrozen or function(t) return frozen[t] == true end + table.clone = table.clone or function(t) + local c = {} + for k, v in pairs(t) do c[k] = v end + return setmetatable(c, getmetatable(t)) + end + table.maxn = table.maxn or function(t) + local m = 0 + for k in pairs(t) do if rawtype(k) == "number" and k > m then m = k end end + return m + end +end + +-- ---------------------------------------------------------------------------------------------------- math +do + math.clamp = math.clamp or function(x, lo, hi) + if lo > hi then error("max must be greater than or equal to min", 2) end + if x < lo then return lo elseif x > hi then return hi end + return x + end + math.sign = math.sign or function(x) + if x > 0 then return 1 elseif x < 0 then return -1 end + return 0 + end + -- Luau rounds half away from zero + math.round = math.round or function(x) + if x >= 0 then return floor(x + 0.5) end + return -floor(-x + 0.5) + end + math.lerp = math.lerp or function(a, b, t) return t == 1 and b or a + (b - a) * t end + math.map = math.map or function(x, a, b, c, d) return c + (d - c) * (x - a) / (b - a) end + math.isnan = math.isnan or function(x) return x ~= x end + math.isinf = math.isinf or function(x) return x == math.huge or x == -math.huge end + math.isfinite = math.isfinite or function(x) return x == x and x ~= math.huge and x ~= -math.huge end + -- stub: deterministic but not Roblox's Perlin noise (nothing in the library depends on its values) + math.noise = math.noise or function(x, y, z) + local s = math.sin((x or 0) * 12.9898 + (y or 0) * 78.233 + (z or 0) * 37.719) * 43758.5453 + return (s - floor(s)) - 0.5 + end +end + +-- ---------------------------------------------------------------------------------------------------- string +string.split = string.split or function(s, sep) + sep = sep or "," + local out = {} + if sep == "" then + for i = 1, #s do out[i] = s:sub(i, i) end + return out + end + local i = 1 + while true do + local a, b = s:find(sep, i, true) + if not a then + out[#out + 1] = s:sub(i) + return out + end + out[#out + 1] = s:sub(i, a - 1) + i = b + 1 + end +end + +-- ---------------------------------------------------------------------------------------------------- utf8 +do + -- Lua 5.1 patterns cannot hold a NUL byte: %z stands for it + local U = { charpattern = "[%z\x01-\x7F\xC2-\xFD][\x80-\xBF]*" } + local char, byte = string.char, string.byte + local function enc(c) + if c < 0x80 then return char(c) + elseif c < 0x800 then return char(0xC0 + floor(c / 64), 0x80 + c % 64) + elseif c < 0x10000 then return char(0xE0 + floor(c / 4096), 0x80 + floor(c / 64) % 64, 0x80 + c % 64) + end + return char(0xF0 + floor(c / 262144), 0x80 + floor(c / 4096) % 64, 0x80 + floor(c / 64) % 64, 0x80 + c % 64) + end + function U.char(...) + local n = select("#", ...) + if n == 1 then return enc((...)) end + local out = {} + for i = 1, n do out[i] = enc((select(i, ...))) end + return table.concat(out) + end + -- decode at byte i: codepoint, length; nil on invalid UTF-8 + local function dec(s, i) + local c = byte(s, i) + if not c then return nil end + if c < 0x80 then return c, 1 end + local n, v + if c >= 0xF0 and c < 0xF8 then n, v = 4, c % 8 + elseif c >= 0xE0 then n, v = 3, c % 16 + elseif c >= 0xC2 then n, v = 2, c % 32 + else return nil end + if c >= 0xF8 then return nil end + for k = 1, n - 1 do + local cc = byte(s, i + k) + if not cc or cc < 0x80 or cc >= 0xC0 then return nil end + v = v * 64 + cc % 64 + end + if (n == 3 and v < 0x800) or (n == 4 and (v < 0x10000 or v > 0x10FFFF)) or (v >= 0xD800 and v <= 0xDFFF) then + return nil + end + return v, n + end + function U.codes(s) + local i = 1 + return function() + if i > #s then return nil end + local c, n = dec(s, i) + if not c then error("invalid UTF-8 code", 2) end + local p = i + i = i + n + return p, c + end + end + function U.codepoint(s, i, j) + i = i or 1 + if i < 0 then i = #s + i + 1 end + j = j or i + if j < 0 then j = #s + j + 1 end + local out, k = {}, 0 + while i <= j do + local c, n = dec(s, i) + if not c then error("invalid UTF-8 code", 2) end + k = k + 1 + out[k] = c + i = i + n + end + return unpack(out, 1, k) + end + -- len(s, i, j) -> count | nil, position of the first invalid byte + function U.len(s, i, j) + i = i or 1 + j = j or #s + if i < 0 then i = #s + i + 1 end + if j < 0 then j = #s + j + 1 end + local n = 0 + while i <= j do + local c, l = dec(s, i) + if not c then return nil, i end + n = n + 1 + i = i + l + end + return n + end + local function iscont(s, i) + local c = byte(s, i) + return c ~= nil and c >= 0x80 and c < 0xC0 + end + function U.offset(s, n, i) + i = i or (n >= 0 and 1 or #s + 1) + if i < 0 then i = #s + i + 1 end + if n == 0 then + while i > 1 and iscont(s, i) do i = i - 1 end + return i + end + if iscont(s, i) then error("initial position is a continuation byte", 2) end + if n > 0 then + n = n - 1 + while n > 0 and i <= #s do + i = i + 1 + while iscont(s, i) do i = i + 1 end + n = n - 1 + end + if n == 0 then return i end + return nil + end + while n < 0 and i > 1 do + i = i - 1 + while i > 1 and iscont(s, i) do i = i - 1 end + n = n + 1 + end + if n == 0 then return i end + return nil + end + function U.graphemes(s) + return U.codes(s) + end + M.utf8 = utf8 or U +end + +-- install(): put the Luau globals in _G for code outside the library (a LÖVE game that wants buffer / bit32 itself) +function M.install(env) + env = env or _G + env.buffer = env.buffer or M.buffer + env.bit32 = env.bit32 or M.bit32 + env.utf8 = env.utf8 or M.utf8 + env.typeof = env.typeof or M.typeof + return M +end + +return M diff --git a/default.project.json b/default.project.json new file mode 100644 index 0000000..762d24e --- /dev/null +++ b/default.project.json @@ -0,0 +1,6 @@ +{ + "name": "Formats", + "tree": { + "$path": "build/roblox/Formats" + } +} diff --git a/docs/FORMATS.md b/docs/FORMATS.md new file mode 100644 index 0000000..181230b --- /dev/null +++ b/docs/FORMATS.md @@ -0,0 +1,12 @@ +# Formats + +GENERATED by `tools/gen_registry.py` from each format's contract (`caps`) - do not edit. Every format listed here +is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build) by `bash tools/test.sh`. + +| Category | Format | Extensions | Read | Write | Capabilities | Test | +|---|---|---|---|---|---|---| +| image | png | .png .apng | yes | yes | animation: false, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` | + +Codecs (layer 1, shared by formats; not loadable on their own): + +- codecs/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers. diff --git a/docs/STYLE.md b/docs/STYLE.md new file mode 100644 index 0000000..9d52919 --- /dev/null +++ b/docs/STYLE.md @@ -0,0 +1,247 @@ +# formats-luau style guide + +Every format looks the same: one folder, one contract, one test, one fixture generator. `bash tools/lint.sh` enforces +most of what follows (the rule names in CAPITALS are lint rules, implemented in `tools/lint_rules.py`). + +The reference implementation to copy is **PNG**: + +| What | Copy from | +|---|---| +| Format contract (`init.luau`) | `src/Formats/image/png/init.luau` | +| Private hot submodules (`--!native`) | `src/Formats/image/png/Decode.luau`, `src/Formats/image/png/Encode.luau` | +| Test | `tests/image/png.luau` | +| Fixture generator | `tools/fixtures/png.py` (a reference tool through nix: `tools/fixtures/_png_reference.py`) | +| A codec (layer 1) | `src/Formats/codecs/Deflate/` + `tests/codecs/deflate.luau` + `tools/fixtures/deflate.py` | + +## 1. Layout and layers + +``` +src/Formats/ + init.luau Registry.luau (generated) api (layer 6) + ops/ ops (layer 5.5) editing on the standard types + // formats (layer 5) image audio video model cad font archive data + vector layered subtitle music playlist + containers/ containers (layer 4) Riff, IsoBmff, Ebml, Ogg, Zip, Tar, ... + codecs/ codecs (layer 3) Deflate, Lzw, Dct, Huffman-heavy algorithms + host/ host (layer 2) runtime adapters; only the api uses them + Types.luau types (layer 1) standard types + constructors + core/ core (layer 0) Bytes, Bits, Err, Crc32, Adler32, Huffman, Input +``` + +LAYERS: a module requires only what is below it. core requires core; Types requires core; codecs require core, Types +and other codecs; containers add codecs; a format may require core, Types, codecs, containers and **its own folder**, +never another format (shared code moves down to `codecs/` or `containers/`: WebP lossy and WebM both use `codecs/Vp8`). +Nothing but the api requires `host/`: formats are pure functions of bytes. + +REQUIRE: every require is a string literal `require("@formats/")` (tests and tools may also use +`require("@tests/")`). No `script.X`, no `@self`, no relative paths, no computed requires: `tools/build.py` turns +these literals into Roblox instance paths and `require("formats.x.y")` for LuaJIT. `@formats/image/png` is the folder's +`init.luau`. + +DEPS: a format's `deps = { ... }` lists exactly the modules outside its folder that the folder requires. + +## 2. The format template + +### Files +``` +src/Formats///init.luau the contract (interpreted: never --!native) +src/Formats///.luau hot code, --!native allowed (Decode, Encode, Huffman tables, ...) +tests//.luau the test (both runtimes) +tools/fixtures/.py fixture generator (reference tools via nix) -> tests/gen/_*.luau +``` + +### File header (HEADER) +```luau +--!strict +--!native -- private hot submodules only +--!optimize 2 -- optional +-- image/png/Decode: . . . +``` +The first comment line starts with the module path (`core/Bytes:`, `image/png:`, `image/png/Decode:`; `Formats:` for +the root). A format's `init.luau` header says what is supported and what is not, and where it came from (spec, port, +absorbed repo). + +### Section order (CONTRACT) +Section markers are `-- ` + 96 dashes + ` `; in a format's `init.luau` they appear in this order (requires and +contract are mandatory, the rest as needed): + +`requires`, `contract`, `types`, `constants`, `sniff`, `decode`, `encode`, `open`, `extras` + +### The contract +```luau +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Decode = require("@formats/image/qoi/Decode") + +-- ------------------------------------------------------------------------------------------------ contract +local Qoi = { + name = "qoi", -- = the folder name + category = "image", -- = the folder category + extensions = { "qoi" }, -- lower case, no dot; the first is the canonical one + mime = { "image/qoi" }, + deps = { "core/Err", "core/Bytes", "Types" }, -- exactly the requires outside the folder + caps = { decode = true, encode = true, alpha = true, depths = { 8 } }, +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Qoi.sniff(r: Bytes.Reader): number -- 0..1 from the first bytes; never consumes, never throws + return if r:peek(4) == "qoif" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Qoi.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + ... + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Qoi.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + ... +end + +return Qoi +``` +Rules: +- The six fields are **one-line literals** in the table (`tools/gen_registry.py` copies them into `Registry.luau` and + `docs/FORMATS.md` without running Luau). `caps.decode` / `caps.encode` match the functions that exist + (`decode = true` also when only `open` exists). Other caps keys are free-form facts (`animation`, `alpha`, `depths`, + `lossy`, `channels`, `streaming`, ...). +- `decode(r, opts)` gets a `core/Bytes` Reader over exactly the file (`r.buf`, `r.base`, `r.limit`: the data may sit + inside a bigger buffer; never assume offset 0). It returns the category's standard type from `Types.luau` + (`Types.Image.new(w, h)`, `Types.Scene.new()`, ...), `rgba8` for images unless `opts.native` asks for the source layout. + Fill `meta.source = { format = "", ... }` with the source facts (bit depth, colour type, codec, ...). +- `encode(value, opts)` returns a buffer. Validate the value first and return `Err.ARG` for anything wrong. +- `open(r, opts)` (audio / video) returns the streaming Decoder / VideoDecoder / Demuxer from `Types.luau`. If a format + has `open` but no `decode`, `F.load` decodes the whole stream through it. +- Options are a typed table with defaults documented on each field (`level: number?, -- 0..9, default 6`). +- Extra format-specific functions (`Png.info(r)`) are fine; `F.format("png")` returns the module. +- No globals, no state between calls, no host access (no files, no `game`). + +### Errors (Err) +Nothing throws on bad data or bad arguments. Every failure is `return nil, Err.new(code, message, offset?)`: + +| Code | When | +|---|---| +| `Err.TRUNCATED` | the data ends early (a `Bytes` reader past its end sets this itself) | +| `Err.CORRUPT` | malformed data | +| `Err.CHECKSUM` | CRC / Adler / hash mismatch | +| `Err.UNSUPPORTED` | valid data using a feature not implemented (say which) | +| `Err.LIMIT` | over `opts.maxPixels` / `opts.maxBytes` / ... (decoders must have a size limit before allocating) | +| `Err.ARG` | bad argument / option / value to encode | +| `Err.IO`, `Err.UNKNOWN_FORMAT` | used by the api | + +Messages are lower case, without the format name (the api adds it: `png: CORRUPT at 0x21: bad filter type 7`). +The `Bytes` reader's errors are sticky: read a run of fields, then check `if r.err then return nil, r.err end` once. +Private submodules may return `false, "message"` or `nil, "message"`; `init.luau` turns that into an `Err`. + +### Native code (NATIVE) +A Luau error unwinding through a native frame crashes Roblox Studio, even inside `pcall`. So: +- `--!native` only in private submodules (never a format's `init.luau`), and on `core/` / `codecs/` modules. +- A `--!native` module contains no `error(` / `assert(` and requires no module that does; an `@native` function body + contains none either. +- Every buffer access in native code is in range by construction: check lengths before loops (`r:need(n)`, explicit + `if p + n > limit then return nil, "truncated" end`), clamp table indexes, validate sizes against limits first. +- The fuzz pass in every test (truncations, mutations, garbage) is the safety net: it must report 0 throws. + +### Performance on both runtimes +- Hot loops cache library functions in locals (`local readu8 = buffer.readu8`) and keep their own bit buffers. +- Bits / Bytes readers are for headers; inner loops read the buffer directly. +- LuaJIT runs the same code through `compat/luajit.lua` (FFI `buffer`, unsigned `bit32`). It is fastest with + straight-line code in the hottest loop: a tiny inner loop (`for k = 0, len - 1 do ... end` inside the symbol loop) + splits LuaJIT's traces; codecs/Deflate/Inflate copies short matches with four `readu32` / `writeu32` instead. +- Benchmark with `bash tools/bench.sh` pinned to one core (`taskset -c 2 bash tools/bench.sh`): on hybrid CPUs (this + machine: Zen 5 + Zen 5c) the same run differs 2x between core types. +- Avoid `string.pack` / `string.unpack` (not in LuaJIT), `\0` inside Lua patterns (LuaJIT: use `%z` or plain find), + and fractional operands to `bit32` (LuaJIT rounds where Luau truncates). + +## 3. Tests + +`tests//.luau`, run by `bash tools/test.sh [filter]` under `luau --codegen -O2` **and** LuaJIT. Template: + +```luau +-- image/qoi tests: . 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 Fx = require("@tests/gen/qoi") -- written by tools/fixtures/qoi.py + +local t = T.suite("qoi") +-- 1. the contract fields +-- 2. every fixture against the reference tool's output (pixel CRC / PSNR for lossy / PCM / mesh checksums) +for _, c in Fx.cases do + local img, err = Qoi.decode(Bytes.reader(buffer.fromstring(c.data))) + t:check(img, c.name .. ": " .. tostring(err)) + t:eq(Crc32.of(img.pixels), c.crc, c.name .. ": pixels") +end +-- 3. round trips through the encoder (lossless: equal; lossy: the reference decoder reads it, in the fixture step) +-- 4. error codes for crafted bad input (t:check(e.code == Err.CORRUPT, ...)) +-- 5. the fuzz no-throw pass +t:fuzz("decode", function(b: buffer) return Qoi.decode(Bytes.reader(b)) end, samples) +t:done() +``` + +- `tests/T.luau`: `T.suite(name)` with `:check(cond, label)`, `:eq(got, want, label)`, `:note(fmt, ...)`, + `:fuzz(label, fn, samples, opts?)`, `:done()`; `T.rng(seed)` (the same numbers on both runtimes), `T.bytes{...}`, + `T.hex(buf)`, `T.runtime`. +- Fixtures: the luau CLI has no file I/O, so fixtures are Luau modules of string literals in `tests/gen/` (gitignored). + Write `tools/fixtures/.py` with `def generate(ctx)` (see the header of `tools/fixtures.py`): `ctx.emit(name, + value)` writes `tests/gen/.luau`; `ctx.nix("imagemagick", [...])` / `ctx.python(["pillow"], code)` run + reference tools through nix; `INPUTS = [...]` lists committed inputs (`tests/fixtures//`, small files with + their licence in `licenses/`). Prefer generating over committing. Keep fixture modules under ~15 MB. +- Both runtimes read the same `require("@tests/gen/")`; there is no second mechanism. +- A fuzz pass is mandatory for every decoder (CONTRACT checks `:fuzz(`). + +## 4. Adding a format + +1. `src/Formats///init.luau` from the template above (copy `image/png/init.luau`), private submodules + next to it. Use `core/Bytes` for parsing, `core/Bits` / `core/Huffman` for entropy coding, `Types` constructors for + the result. +2. Shared code (a codec two formats need, a container) goes to `codecs/` or `containers/` instead, with its own test in + `tests/codecs/` / `tests/containers/`. +3. `deps = { ... }` = the requires outside the folder. +4. `python3 -I tools/gen_registry.py` (regenerates `src/Formats/Registry.luau` and `docs/FORMATS.md`; never edit those + by hand; after a merge, just rerun it). +5. `tools/fixtures/.py` + `tests//.luau`. +6. `bash tools/test.sh ` while working (both runtimes), then `bash tools/test.sh` (everything + lint). +7. The docs line comes from the contract (`docs/FORMATS.md`); put format notes (limits, spec deviations, bench numbers) + in the init header or `docs//.md` if long. + +Workstreams running in parallel own their folders (`//`, their tests, their fixture generators). +`core/`, `Types.luau`, the api, `tools/`, `compat/` and this file belong to the lead: propose changes there instead of +making them (a missing `Bytes` method, a new `Types` field, a `Err` code). + +## 5. Absorbing an existing repo + +1. Copy the source into its place (a codec into `codecs//`, a format into `//`); the old repo stays + untouched (other projects use it). +2. Provenance: the module header says `Absorbed from ()` and what changed. +3. Licence: copy the repo's licence / NOTICE into `licenses/` (`licenses/-LICENSE.txt`) and add a line to + `licenses/NOTICE.md`. Third-party ports keep their upstream licence text there too. +4. Requires: `if script then require(script.X) else require("@self/X")` becomes `require("@formats///X")`; + injected dependencies (`require(Png)(Deflate)`) become direct requires of the codec. +5. Checksums / bit readers / Huffman tables the repo carries are replaced by `core/` ones when equivalent. +6. Wrap the public API in the contract: `sniff`, `decode(r: Reader, opts)` (reading from `r.buf` between `r.base` and + `r.limit`), `encode`, the standard type out, `Err` values instead of strings or throws. +7. Port the tests to `tests//.luau` with `T`, and the fixture script to `tools/fixtures/.py` + (`ctx.emit` instead of writing files). Both runtimes must pass. + +## 6. Build notes (tools/build.py) + +darklua 0.19 does most of the LuaJIT lowering (`remove_types`, `remove_attribute`, `remove_compound_assignment`, +`remove_continue`, `remove_if_expression`, `remove_interpolated_string`, `remove_floor_division`, +`convert_luau_number`) and the Roblox require conversion (`convert_require` luau -> roblox). Token passes in build.py +cover what it cannot: +- **Generalized iteration** (`for k, v in t do`): no darklua rule. Rewritten to `for k, v in __iter(t) do` + (compat: functions pass through; arrays with no keys past `#t` use `ipairs`; other tables `next`). +- **darklua bug**: `remove_if_expression` nests `elseif` branches in reverse order (`if a then 1 elseif b then 2 + elseif c then 3 else 4` gives `a and 1 or (c and 3 or (b and 2 or 4))`). build.py rewrites every if-expression + `elseif` to `else if` before darklua. +- **If-expression tables**: darklua lowers `if c then x else y` to `(c and {x} or {y})[1]` unless `x` is a literal. + build.py turns it back into `(c and (x) or (y))` when `x` is provably not nil/false (numbers, strings, arithmetic). +- **Requires** become `require("formats.a.b")`; **stdlib names** come from `formats._compat` through locals injected on + the first line of each module (only the ones used: LuaJIT allows 60 upvalues per function). +- `string.format("%s", x)` with interpolation and `tostring` of floats print differently on LuaJIT (14 significant + digits); never compare formatted floats in tests. diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md new file mode 100644 index 0000000..5d28e73 --- /dev/null +++ b/licenses/NOTICE.md @@ -0,0 +1,10 @@ +# Third-party code, absorbed repositories and test data + +| Where | From | Licence | +|---|---|---| +| `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 | +| `tests/fixtures/pngsuite/` | PngSuite by Willem van Schaik | [PngSuite-LICENSE.txt](PngSuite-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/PngSuite-LICENSE.txt b/licenses/PngSuite-LICENSE.txt new file mode 100644 index 0000000..8d4d1d0 --- /dev/null +++ b/licenses/PngSuite-LICENSE.txt @@ -0,0 +1,9 @@ +PngSuite +-------- + +Permission to use, copy, modify and distribute these images for any +purpose and without fee is hereby granted. + + +(c) Willem van Schaik, 1996, 2011 + diff --git a/licenses/deflate-luau-NOTICE.txt b/licenses/deflate-luau-NOTICE.txt new file mode 100644 index 0000000..f0ed603 --- /dev/null +++ b/licenses/deflate-luau-NOTICE.txt @@ -0,0 +1,7 @@ +deflate-luau contains no third-party code. It was written from the specifications: + +- RFC 1951, DEFLATE Compressed Data Format Specification version 1.3 (P. Deutsch, 1996) +- RFC 1950, ZLIB Compressed Data Format Specification version 3.3 (P. Deutsch, J-L. Gailly, 1996) +- RFC 1952, GZIP file format specification version 4.3 (P. Deutsch, 1996) + +The test fixtures are generated at test time by Python's zlib (tools/fixtures.py) and are not distributed. diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau new file mode 100644 index 0000000..ba09f70 --- /dev/null +++ b/src/Formats/Registry.luau @@ -0,0 +1,31 @@ +--!strict +-- Registry: GENERATED by tools/gen_registry.py from the format folders - do not edit. +-- One entry per format: the contract metadata (copied from its init.luau) and load(), which requires the format +-- module on first use (a static require, as Roblox needs). Order: category, then name. +export type Entry = { + name: string, + category: string, + path: string, + extensions: { string }, + mime: { string }, + deps: { string }, + caps: { [string]: any }, + load: () -> any, +} + +local list: { Entry } = { + { + name = "png", + category = "image", + path = "image/png", + extensions = { "png", "apng" }, + mime = { "image/png", "image/apng" }, + deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/Deflate", "Types" }, + caps = { decode = true, encode = true, animation = false, alpha = true, depths = { 1, 2, 4, 8, 16 } }, + load = function() + return require("@formats/image/png") + end, + }, +} + +return list diff --git a/src/Formats/Types.luau b/src/Formats/Types.luau new file mode 100644 index 0000000..9f37bd1 --- /dev/null +++ b/src/Formats/Types.luau @@ -0,0 +1,475 @@ +--!strict +-- Types: the standard value types every format of a category decodes to and encodes from, plus small constructors. +-- A PNG and a WebP both load as an Image; a WAV and an MP3 both open as an audio Decoder. Every top-level value has a +-- `kind` field ("image", "audio", "scene", ...) so F.save knows the category without a format name. +-- +-- local T = require("@formats/Types") +-- local img = T.Image.new(64, 32) -- rgba8, zero-filled +-- local snd = T.Audio.new(44100, 2, 44100) -- 1 s of silent stereo f32 +-- +-- Shared enums are plain strings. Buffers are tightly packed, rows top to bottom, interleaved channels. +local Err = require("@formats/core/Err") + +local Types = {} + +export type Err = Err.Err + +-- ------------------------------------------------------------------------------------------------ Image +-- pixel formats: bytes per pixel. rgba8 is the default every decoder produces unless opts.native asks to keep the +-- source layout. yuv420p: Y plane (w*h) then U and V planes (ceil(w/2) * ceil(h/2) each). +export type PixelFormat = "rgba8" | "rgba16" | "rgbaf32" | "rgb8" | "gray8" | "gray16" | "graya8" | "alpha8" | "yuv420p" +local BPP: { [string]: number } = { + rgba8 = 4, + rgba16 = 8, + rgbaf32 = 16, + rgb8 = 3, + gray8 = 1, + gray16 = 2, + graya8 = 2, + alpha8 = 1, +} +Types.BPP = table.freeze(BPP) + +export type ImageMeta = { + colorSpace: string?, -- "srgb" (default), "linear", "display-p3", ... + gamma: number?, + icc: buffer?, -- the raw ICC profile + exif: buffer?, -- the raw EXIF block (TIFF header onwards) + dpi: { x: number, y: number }?, + palette: { { number } }?, -- { r, g, b, a } 0..255 per entry, for palette sources + text: { [string]: string }?, -- tEXt / comments + source: { format: string, bitDepth: number?, colorType: string?, [string]: any }?, + [string]: any, +} + +-- one frame of an animation (GIF, APNG, WebP): the image is the frame's own rectangle, composited at x, y +export type Frame = { + image: Image, + delay: number, -- seconds + x: number, + y: number, + dispose: "none" | "background" | "previous", + blend: "source" | "over", +} + +export type Image = { + kind: "image", + width: number, + height: number, + format: PixelFormat, + pixels: buffer, + frames: { Frame }?, -- animations: frame 1 is also width x height pixels (the composited first frame) + loops: number, -- 0 = forever + meta: ImageMeta, +} + +local Image = {} +-- new(width, height, format?) -> a zero-filled Image (format defaults to rgba8) +function Image.new(width: number, height: number, format: PixelFormat?): Image + local f: PixelFormat = format or "rgba8" + local size + if f == "yuv420p" then + local cw, ch = (width + 1) // 2, (height + 1) // 2 + size = width * height + 2 * cw * ch + else + size = width * height * (BPP[f] or 4) + end + return { + kind = "image", + width = width, + height = height, + format = f, + pixels = buffer.create(size), + frames = nil, + loops = 0, + meta = {}, + } +end +-- bpp(format) -> bytes per pixel (nil for planar formats) +function Image.bpp(format: string): number? + return BPP[format] +end +Types.Image = Image + +-- ------------------------------------------------------------------------------------------------ Audio +export type Tags = { [string]: string } -- title, artist, album, date, genre, track, comment, ... + +-- the streaming decoder every audio format's open() returns (the shape the absorbed wav/mp3/flac/ogg/opus share) +export type Decoder = { + sampleRate: number, + channels: number, + frames: number, -- total sample frames (estimate for VBR streams without an index), 0 = unknown + duration: number, -- seconds + bitrate: number, -- bits per second (average) + tags: Tags, + -- read(n, out?) -> interleaved f32 buffer, frames read (0 at the end); out (if given) is reused when big enough + read: (self: any, n: number, out: buffer?) -> (buffer, number), + seek: (self: any, seconds: number) -> (), + position: (self: any) -> number, -- seconds +} + +-- a fully decoded sound (F.load / F.audio.load) +export type Audio = { + kind: "audio", + sampleRate: number, + channels: number, + frames: number, + samples: buffer, -- interleaved f32, frames * channels * 4 bytes + tags: Tags, + meta: { source: { format: string, [string]: any }?, [string]: any }, +} + +local Audio = {} +function Audio.new(sampleRate: number, channels: number, frames: number): Audio + return { + kind = "audio", + sampleRate = sampleRate, + channels = channels, + frames = frames, + samples = buffer.create(frames * channels * 4), + tags = {}, + meta = {}, + } +end +Types.Audio = Audio + +-- ------------------------------------------------------------------------------------------------ Music (trackers, MIDI) +export type Module = { + kind: "music", + title: string, + format: string, -- "mod", "s3m", "xm", "it", "mid" + channels: number, + patterns: { any }, + order: { number }, + instruments: { any }, + samples: { any }, + render: (self: any, opts: any?) -> Decoder, -- every music file is also audio + meta: { [string]: any }, +} + +export type MidiEvent = { tick: number, type: string, channel: number?, data: { number }?, meta: any? } +export type Midi = { + kind: "midi", + format: number, -- SMF 0 / 1 / 2 + division: number, -- ticks per quarter note (or SMPTE, negative) + tracks: { { events: { MidiEvent }, name: string? } }, + meta: { [string]: any }, +} +local Midi = {} +function Midi.new(division: number?): Midi + return { kind = "midi", format = 1, division = division or 480, tracks = {}, meta = {} } +end +Types.Midi = Midi + +-- ------------------------------------------------------------------------------------------------ Video +export type Track = { + id: number, + kind: "video" | "audio" | "subtitle" | "data", + codec: string, -- "h264", "vp8", "mpeg1", "mjpeg", "aac", "mp3", "opus", ... + timescale: number, -- ticks per second for pts / duration + duration: number?, -- seconds + width: number?, + height: number?, + sampleRate: number?, + channels: number?, + config: buffer?, -- codec configuration (avcC, CodecPrivate, ...) + [string]: any, +} +export type Packet = { track: number, pts: number, dts: number?, duration: number?, keyframe: boolean, data: buffer } +export type Demuxer = { + tracks: { Track }, + duration: number, + -- packets(trackId?) -> iterator of Packets in file order (one track, or all) + packets: (self: any, track: number?) -> () -> Packet?, + seek: ((self: any, seconds: number) -> ())?, +} +export type VideoFrame = { image: Image, pts: number, duration: number } +export type VideoDecoder = { + width: number, + height: number, + frameRate: number, + duration: number, + nextFrame: (self: any) -> (VideoFrame?, Err?), -- nil, nil at the end + toRGBA: (self: any, frame: VideoFrame) -> Image, + seek: ((self: any, seconds: number) -> ())?, + audio: Decoder?, -- the first audio track, decoded + demuxer: Demuxer?, +} + +-- ------------------------------------------------------------------------------------------------ Scene (3D, glTF-shaped) +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) + count: number, +} +export type Primitive = { + attributes: { [string]: Accessor }, -- POSITION, NORMAL, TANGENT, TEXCOORD_0, COLOR_0, JOINTS_0, WEIGHTS_0 + indices: Accessor?, + mode: "triangles" | "lines" | "points" | "triangle_strip" | "triangle_fan" | "line_strip", + material: number?, -- index into scene.materials (1-based) +} +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 + baseColorTexture: TextureRef?, + metallic: number, + roughness: number, + metallicRoughnessTexture: TextureRef?, + normalTexture: TextureRef?, + occlusionTexture: TextureRef?, + emissive: { number }, + emissiveTexture: TextureRef?, + alphaMode: "opaque" | "mask" | "blend", + alphaCutoff: number, + doubleSided: boolean, + extras: { [string]: any }?, -- classic Phong (OBJ / FBX): ambient, diffuse, specular, shininess, ... +} +export type Node = { + name: string?, + children: { number }, -- node indices (1-based) + mesh: number?, + camera: number?, + light: number?, + skin: number?, + translation: { number }?, -- TRS, or matrix (column-major 4x4), not both + rotation: { number }?, -- quaternion x, y, z, w + scale: { number }?, + matrix: { number }?, + 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 Channel = { node: number, path: "translation" | "rotation" | "scale" | "weights", input: Accessor, output: Accessor, interpolation: "LINEAR" | "STEP" | "CUBICSPLINE" } +export type Animation = { name: string?, channels: { Channel } } +export type Scene = { + kind: "scene", + nodes: { Node }, + roots: { number }, -- top-level node indices + meshes: { Mesh }, + materials: { Material }, + textures: { Texture }, + cameras: { Camera }, + lights: { Light }, + skins: { Skin }, + animations: { Animation }, + meta: { up: "y" | "z"?, unit: number?, source: { format: string, [string]: any }?, [string]: any }, +} + +local Scene = {} +function Scene.new(): Scene + return { + kind = "scene", + nodes = {}, + roots = {}, + meshes = {}, + materials = {}, + textures = {}, + cameras = {}, + lights = {}, + skins = {}, + animations = {}, + meta = {}, + } +end +function Scene.accessor(data: buffer, type: any, components: number, count: number): Accessor + return { data = data, type = type, components = components, count = count } +end +function Scene.material(name: string?): Material + return { + name = name, + baseColor = { 1, 1, 1, 1 }, + metallic = 1, + roughness = 1, + emissive = { 0, 0, 0 }, + alphaMode = "opaque", + alphaCutoff = 0.5, + doubleSided = false, + } +end +-- one-node scene around a single primitive (mesh-only formats: STL, OBJ, PLY, OFF) +function Scene.fromPrimitive(prim: Primitive, name: string?): Scene + local s = Scene.new() + s.meshes[1] = { name = name, primitives = { prim } } + s.nodes[1] = { name = name, children = {}, mesh = 1 } + s.roots[1] = 1 + return s +end +Types.Scene = Scene + +-- ------------------------------------------------------------------------------------------------ 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 } } +export type Cad = { + kind: "cad", + schema: string, -- "AP203", "AP214", "AP242", ... + header: { [string]: any }, + entities: { [number]: StepEntity }, + meta: { [string]: any }, +} + +-- ------------------------------------------------------------------------------------------------ Font +export type Font = { + kind: "font", + info: { family: string?, style: string?, fullName: string?, [string]: any }, + unitsPerEm: number, + ascent: number, + descent: number, + lineGap: number, + glyphIndex: (self: any, codepoint: number) -> number, -- 0 = .notdef + advance: (self: any, glyph: number) -> number, -- font units + kern: (self: any, a: number, b: number) -> number, + outline: (self: any, glyph: number) -> { { op: string, [number]: number } }?, -- moveTo / lineTo / quadTo / cubicTo + rasterize: (self: any, glyph: number, px: number) -> Image?, -- alpha8 + pages: { Image }?, -- bitmap fonts (BMFont) + meta: { [string]: any }, +} + +-- ------------------------------------------------------------------------------------------------ Archive +export type ArchiveEntry = { name: string, size: number, compressedSize: number?, method: string?, mtime: number?, dir: boolean } +export type Archive = { + kind: "archive", + format: string, + list: (self: any) -> { ArchiveEntry }, + read: (self: any, name: string) -> (buffer?, Err?), + add: (self: any, name: string, data: buffer | string, opts: any?) -> (), + write: (self: any, opts: any?) -> (buffer?, Err?), + meta: { [string]: any }, +} + +-- ------------------------------------------------------------------------------------------------ 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. +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? } + +-- ------------------------------------------------------------------------------------------------ Vector +export type Paint = { type: "color", color: { number } } | { type: "linear" | "radial", stops: { { number } }, [string]: any } +export type VectorPath = { + d: { { op: string, [number]: number } }, -- absolute M / L / C / Q / Z commands + fill: Paint?, + fillRule: "nonzero" | "evenodd", + stroke: Paint?, + strokeWidth: number, + transform: { number }?, -- a, b, c, d, e, f + opacity: number, +} +export type Vector = { + kind: "vector", + width: number, + height: number, + viewBox: { number }, -- x, y, w, h + paths: { VectorPath }, + meta: { [string]: any }, +} +local Vector = {} +function Vector.new(width: number, height: number): Vector + return { kind = "vector", width = width, height = height, viewBox = { 0, 0, width, height }, paths = {}, meta = {} } +end +Types.Vector = Vector + +-- ------------------------------------------------------------------------------------------------ Layered (PSD, Aseprite) +export type Layer = { name: string, image: Image, x: number, y: number, opacity: number, blend: string, visible: boolean } +export type Layered = { + kind: "layered", + width: number, + height: number, + layers: { Layer }, -- bottom to top + frames: { { layers: { Layer }, delay: number } }?, + 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 +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 } } +export type TileMap = { + kind: "tilemap", + width: number, + height: number, + tileWidth: number, + tileHeight: number, + orientation: string, + tilesets: { Tileset }, + layers: { TileLayer }, + properties: { [string]: any }, + meta: { [string]: any }, +} + +-- ------------------------------------------------------------------------------------------------ Subtitles +export type Cue = { start: number, stop: number, text: string, style: string?, id: string?, [string]: any } -- seconds +export type Subtitles = { kind: "subtitles", cues: { Cue }, styles: { [string]: any }, meta: { [string]: any } } +local Subtitles = {} +function Subtitles.new(): Subtitles + return { kind = "subtitles", cues = {}, styles = {}, meta = {} } +end +Types.Subtitles = Subtitles + +-- ------------------------------------------------------------------------------------------------ Playlist +-- the playlist-luau shape +export type PlaylistEntry = { + url: string, + title: string?, + duration: number?, + playable: boolean, + reason: string?, + bandwidth: number?, + codecs: string?, + attributes: { [string]: string }?, + byteRange: { length: number, offset: number? }?, +} +export type Playlist = { + kind: "playlist", + format: string, -- "m3u", "pls", "hls", "xspf" + entries: { PlaylistEntry }, + warnings: { string }, + title: string?, + hls: { [string]: any }?, + meta: { [string]: any }, +} + +-- ------------------------------------------------------------------------------------------------ the format contract +-- what every format folder's init.luau returns (checked by tools/lint.sh CONTRACT; see docs/STYLE.md) +export type Caps = { decode: boolean, encode: boolean, [string]: any } +export type Format = { + name: string, + category: string, + extensions: { string }, + mime: { string }, + deps: { string }, + sniff: (r: any) -> number, -- confidence 0..1 from the first bytes (a core/Bytes Reader); must not consume / throw + decode: ((r: any, opts: any?) -> (any, Err?))?, + encode: ((value: any, opts: any?) -> (buffer?, Err?))?, + open: ((r: any, opts: any?) -> (any, Err?))?, -- streaming categories (audio / video) + caps: Caps, +} + +-- the categories, in the order F.formats() lists them; kind = the `kind` of the values they decode to +Types.CATEGORIES = table.freeze({ + image = "image", + audio = "audio", + video = "video", + model = "scene", + cad = "cad", + font = "font", + archive = "archive", + data = "data", + vector = "vector", + layered = "layered", + subtitle = "subtitles", + music = "music", + playlist = "playlist", +}) + +return Types diff --git a/src/Formats/codecs/Deflate/Compress.luau b/src/Formats/codecs/Deflate/Compress.luau new file mode 100644 index 0000000..d5d508f --- /dev/null +++ b/src/Formats/codecs/Deflate/Compress.luau @@ -0,0 +1,432 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Deflate/Compress: a DEFLATE (RFC 1951) compressor. LZ77 over a 32 KB window with hash chains (chain depth +-- and lazy matching by level), then per block the cheapest of stored / fixed-Huffman / dynamic-Huffman (core/Huffman +-- length-limited codes). Level 0 = stored blocks only. +-- +-- raw(buf, off, len, level) -> buffer. Never throws (the caller validated the arguments). +local Huffman = require("@formats/core/Huffman") + +local readu8, writeu8, writeu16 = buffer.readu8, buffer.writeu8, buffer.writeu16 +local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len +local floor = math.floor + +local WSIZE = 32768 +local HSIZE = 65536 +local MAXMATCH = 258 +local BLOCKSYMS = 16384 -- symbols per block + +-- per level (zlib's configuration_table): GOOD = a match this long quarters the chain for the lazy search, LAZY = no +-- lazy search after a match this long, NICE = stop searching at this length, CHAIN = max chain steps. Levels 1-3 are +-- greedy (no lazy matching). +local GOOD = { 4, 4, 4, 4, 8, 8, 8, 32, 32 } +local LAZY = { 0, 0, 0, 4, 16, 16, 32, 128, 258 } +local NICE = { 8, 16, 32, 16, 32, 128, 128, 258, 258 } +local CHAIN = { 4, 8, 32, 16, 32, 128, 256, 1024, 4096 } + +-- length 3..258 -> code 257..285 (index len), its extra bits and base +local LCODE, LEXTRA, LBASEOF = table.create(259, 0), table.create(259, 0), table.create(259, 0) +local LBASE = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258 } +local LEXT = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 } +for c = 1, 29 do + local base = LBASE[c] + local top = if c == 29 then 258 elseif c == 28 then 257 else LBASE[c + 1] - 1 + for len = base, top do + LCODE[len] = 256 + c + LEXTRA[len] = LEXT[c] + LBASEOF[len] = base + end +end +local DBASE = { + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, + 6145, 8193, 12289, 16385, 24577, +} +local DEXT = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 } +-- distance -> code (0..29): direct for 1..256, by (d - 1) // 128 above +local DSMALL, DLARGE = table.create(257, 0), table.create(257, 0) +for c = 1, 30 do + local base = DBASE[c] + local top = if c == 30 then 32768 else DBASE[c + 1] - 1 + for d = base, math.min(top, 256) do + DSMALL[d] = c - 1 + end + if top > 256 then + for k = math.max(base, 257), top, 128 do + DLARGE[(k - 1) // 128 + 1] = c - 1 + end + end +end +local function dcode(d: number): number + if d <= 256 then + return DSMALL[d] + end + return DLARGE[(d - 1) // 128 + 1] +end + +local CLORDER = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 } + +-- fixed codes +local FIXLEN = table.create(288, 0) +for i = 1, 288 do + FIXLEN[i] = if i <= 144 then 8 elseif i <= 256 then 9 elseif i <= 280 then 7 else 8 +end +local FIXDLEN = table.create(30, 5) + +-- reversed (LSB-first) canonical codes for lengths +local function revCodes(lens: { number }): { number } + local codes = Huffman.codes(lens) + for i, l in lens do + if l > 0 then + codes[i] = Huffman.reverse(codes[i], l) + end + end + return codes +end +local FIXCODE = revCodes(FIXLEN) +local FIXDCODE = revCodes(FIXDLEN) + +local POW = table.create(33, 0) +for i = 0, 32 do + POW[i + 1] = 2 ^ i +end + +-- ------------------------------------------------------------------------------------------------ bit output +type Out = { buf: buffer, op: number, acc: number, cnt: number } + +local function ensure(o: Out, n: number) + if o.op + n > blen(o.buf) then + local nb = bcreate(math.max(blen(o.buf) * 2, o.op + n)) + bcopy(nb, 0, o.buf, 0, o.op) + o.buf = nb + end +end + +-- put(v, n): n <= 24 bits, LSB first +local function put(o: Out, v: number, n: number) + local acc = o.acc + v * POW[o.cnt + 1] + local cnt = o.cnt + n + if cnt >= 8 then + ensure(o, 4) + local buf, op = o.buf, o.op + while cnt >= 8 do + local byte = acc % 256 + writeu8(buf, op, byte) + op += 1 + acc = (acc - byte) / 256 + cnt -= 8 + end + o.op = op + end + o.acc, o.cnt = acc, cnt +end + +local function alignOut(o: Out) + if o.cnt > 0 then + put(o, 0, 8 - o.cnt) + end +end + +-- ------------------------------------------------------------------------------------------------ blocks +-- syms: L[i] = literal 0..255 or 256 + match length; D[i] = distance (0 for literals) +local function storedBlock(o: Out, src: buffer, s: number, e: number, final: boolean) + local p = s + repeat + local n = math.min(65535, e - p) + local last = final and p + n >= e + put(o, if last then 1 else 0, 3) + alignOut(o) + ensure(o, 4 + n) + writeu16(o.buf, o.op, n) + writeu16(o.buf, o.op + 2, 65535 - n) + bcopy(o.buf, o.op + 4, src, p, n) + o.op += 4 + n + p += n + until p >= e +end + +local function emitSymbols(o: Out, L: { number }, D: { number }, nsym: number, lcode: { number }, llen: { number }, dcodes: { number }, dlen: { number }) + for i = 1, nsym do + local l = L[i] + if l < 256 then + put(o, lcode[l + 1], llen[l + 1]) + else + local len = l - 256 + local c = LCODE[len] + put(o, lcode[c + 1], llen[c + 1]) + local xb = LEXTRA[len] + if xb > 0 then + put(o, len - LBASEOF[len], xb) + end + local d = D[i] + local dc = dcode(d) + put(o, dcodes[dc + 1], dlen[dc + 1]) + xb = DEXT[dc + 1] + if xb > 0 then + put(o, d - DBASE[dc + 1], xb) + end + end + end + put(o, lcode[257], llen[257]) -- end of block +end + +local function block(o: Out, src: buffer, s: number, e: number, L: { number }, D: { number }, nsym: number, final: boolean) + local lf = table.create(286, 0) + local df = table.create(30, 0) + local extra = 0 + for i = 1, nsym do + local l = L[i] + if l < 256 then + lf[l + 1] += 1 + else + local len = l - 256 + lf[LCODE[len] + 1] += 1 + extra += LEXTRA[len] + local dc = dcode(D[i]) + df[dc + 1] += 1 + extra += DEXT[dc + 1] + end + end + lf[257] = 1 + local llen = Huffman.lengths(lf, 15) + local dlen = Huffman.lengths(df, 15) + local hlit = 286 + while hlit > 257 and llen[hlit] == 0 do + hlit -= 1 + end + local hdist = 30 + while hdist > 1 and dlen[hdist] == 0 do + hdist -= 1 + end + if dlen[1] == 0 and hdist == 1 then + dlen[1] = 1 -- at least one distance code (a lone 1-bit code, as zlib writes) + end + -- code-length symbols: RLE of the hlit + hdist lengths + local all = table.create(hlit + hdist, 0) + for i = 1, hlit do + all[i] = llen[i] + end + for i = 1, hdist do + all[hlit + i] = dlen[i] + end + local cs, cx = {}, {} -- symbol, extra value + local cf = table.create(19, 0) + local i = 1 + local total = hlit + hdist + while i <= total do + local v = all[i] + local run = 1 + while i + run <= total and all[i + run] == v do + run += 1 + end + if v == 0 and run >= 3 then + local r = math.min(run, 138) + if r >= 11 then + table.insert(cs, 18) + table.insert(cx, r - 11) + cf[19] += 1 + else + table.insert(cs, 17) + table.insert(cx, r - 3) + cf[18] += 1 + end + i += r + elseif v ~= 0 and run >= 4 then + table.insert(cs, v) + table.insert(cx, 0) + cf[v + 1] += 1 + local r = math.min(run - 1, 6) + table.insert(cs, 16) + table.insert(cx, r - 3) + cf[17] += 1 + i += 1 + r + else + table.insert(cs, v) + table.insert(cx, 0) + cf[v + 1] += 1 + i += 1 + end + end + local clen = Huffman.lengths(cf, 7) + local hclen = 19 + while hclen > 4 and clen[CLORDER[hclen] + 1] == 0 do + hclen -= 1 + end + -- costs in bits + local dyn = 17 + 3 * hclen + extra + for k = 1, 19 do + dyn += cf[k] * clen[k] + end + dyn += cf[17] * 2 + cf[18] * 3 + cf[19] * 7 + local fix = 3 + extra + for k = 1, 286 do + dyn += lf[k] * llen[k] + fix += lf[k] * FIXLEN[k] + end + for k = 1, 30 do + dyn += df[k] * dlen[k] + fix += df[k] * 5 + end + local stored = (e - s) * 8 + 40 * (floor((e - s) / 65535) + 1) + 7 + if stored <= dyn and stored <= fix then + storedBlock(o, src, s, e, final) + return + end + if fix <= dyn then + put(o, if final then 3 else 2, 3) + emitSymbols(o, L, D, nsym, FIXCODE, FIXLEN, FIXDCODE, FIXDLEN) + return + end + put(o, if final then 5 else 4, 3) + put(o, hlit - 257, 5) + put(o, hdist - 1, 5) + put(o, hclen - 4, 4) + for k = 1, hclen do + put(o, clen[CLORDER[k] + 1], 3) + end + local ccode = revCodes(clen) + for k = 1, #cs do + local c = cs[k] + put(o, ccode[c + 1], clen[c + 1]) + if c == 16 then + put(o, cx[k], 2) + elseif c == 17 then + put(o, cx[k], 3) + elseif c == 18 then + put(o, cx[k], 7) + end + end + emitSymbols(o, L, D, nsym, revCodes(llen), llen, revCodes(dlen), dlen) +end + +-- ------------------------------------------------------------------------------------------------ LZ77 +local Compress = {} + +function Compress.raw(src: buffer, off: number, len: number, level: number): buffer + local o: Out = { buf = bcreate(math.max(64, len // 2 + 64)), op = 0, acc = 0, cnt = 0 } + local e = off + len + if level == 0 or len == 0 then + if len == 0 then + put(o, 3, 3) -- one empty fixed block + put(o, 0, 7) + else + storedBlock(o, src, off, e, true) + end + alignOut(o) + local out = bcreate(o.op) + bcopy(out, 0, o.buf, 0, o.op) + return out + end + local maxChain = CHAIN[level] + local nice = NICE[level] + local good = GOOD[level] + local lazyMax = LAZY[level] + local head = table.create(HSIZE, -1) + local prev = table.create(WSIZE, -1) + local L = table.create(BLOCKSYMS, 0) + local D = table.create(BLOCKSYMS, 0) + local nsym = 0 + local blockStart = off + + local function hash(p: number): number + return ((readu8(src, p) * 251 + readu8(src, p + 1)) * 251 + readu8(src, p + 2)) % HSIZE + end + local function insert(p: number) + local h = hash(p) + 1 + prev[p % WSIZE + 1] = head[h] + head[h] = p + end + -- longest match at p among earlier positions: len (0 if < 3), dist + local function find(p: number, steps: number): (number, number) + local maxLen = math.min(MAXMATCH, e - p) + if maxLen < 3 then + return 0, 0 + end + local best, bestDist = 2, 0 + local c = head[hash(p) + 1] + local limit = p - WSIZE + while c >= 0 and c > limit and steps > 0 do + if readu8(src, c + best) == readu8(src, p + best) and readu8(src, c) == readu8(src, p) then + local k = 1 + while k < maxLen and readu8(src, c + k) == readu8(src, p + k) do + k += 1 + end + if k > best then + best, bestDist = k, p - c + if k >= nice or k >= maxLen then + break + end + end + end + local nc = prev[c % WSIZE + 1] + if nc >= c then + break -- the slot was reused by a newer position: the chain ends here + end + c = nc + steps -= 1 + end + if best < 3 then + return 0, 0 + end + return best, bestDist + end + local function flush(upto: number, final: boolean) + block(o, src, blockStart, upto, L, D, nsym, final) + nsym = 0 + blockStart = upto + end + + local p = off + local stop3 = e - 3 -- positions with 3 bytes ahead can be hashed + while p < e do + local mlen, mdist = 0, 0 + if p <= stop3 then + mlen, mdist = find(p, maxChain) + insert(p) + if mlen >= 3 and mlen < lazyMax and p + 1 <= stop3 then + local l2, d2 = find(p + 1, if mlen >= good then maxChain // 4 else maxChain) + if l2 > mlen then + -- a literal now, the longer match from p + 1 + nsym += 1 + L[nsym] = readu8(src, p) + D[nsym] = 0 + p += 1 + insert(p) + mlen, mdist = l2, d2 + end + end + end + if mlen >= 3 then + nsym += 1 + L[nsym] = 256 + mlen + D[nsym] = mdist + local q = p + 1 + local qe = math.min(p + mlen, stop3 + 1) + while q < qe do + insert(q) + q += 1 + end + p += mlen + else + nsym += 1 + L[nsym] = readu8(src, p) + D[nsym] = 0 + p += 1 + end + if nsym >= BLOCKSYMS - 2 then + flush(p, p >= e) + end + end + if nsym > 0 or blockStart < e then + flush(e, true) + elseif blockStart == e and o.op == 0 and o.cnt == 0 then + put(o, 3, 3) + put(o, 0, 7) + end + alignOut(o) + local out = bcreate(o.op) + bcopy(out, 0, o.buf, 0, o.op) + return out +end + +return Compress diff --git a/src/Formats/codecs/Deflate/Inflate.luau b/src/Formats/codecs/Deflate/Inflate.luau new file mode 100644 index 0000000..87f3e5f --- /dev/null +++ b/src/Formats/codecs/Deflate/Inflate.luau @@ -0,0 +1,435 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Deflate/Inflate: raw DEFLATE (RFC 1951) decoder: stored, fixed-Huffman and dynamic-Huffman blocks. +-- Absorbed from deflate-luau src/Deflate/Inflate.luau (same author); the table builder moved to core/Huffman, whose +-- entries are symbol * 32 + length (5 length bits instead of 4). +-- +-- Bits are read LSB first into a 32-bit bit buffer (refilled 4 bytes at a time with one readu32 while the input +-- lasts). Huffman codes decode through a core/Huffman LSB table indexed by the next LITBITS / DISTBITS bits; a longer +-- code's primary slot links to a subtable, so a symbol is one or two table reads. +-- +-- Nothing in this module throws on any input: every buffer read and write is bounds-checked, and corrupt data +-- returns nil, message. (Native code must never throw: it crashes Roblox Studio.) +local Huffman = require("@formats/core/Huffman") + +local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift +local readu8, readu16, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32 +local bcreate, bcopy, bfill, blen = buffer.create, buffer.copy, buffer.fill, buffer.len + +local LITBITS, DISTBITS, CLBITS = 10, 8, 7 +local LITMASK, DISTMASK, CLMASK = 1023, 255, 127 + +-- length codes 257..285 and distance codes 0..29: base value, extra bits +local LBASE = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258 } +local LEXT = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 } +local DBASE = { + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, + 6145, 8193, 12289, 16385, 24577, +} +local DEXT = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 } +-- the order code-length code lengths are sent in +local CLORDER = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 } + +-- table capacities (entries): primary + one subtable per code longer than the primary width, worst case +local LITCAP = Huffman.capacity(288, LITBITS, 15) +local DISTCAP = Huffman.capacity(32, DISTBITS, 15) +local CLCAP = Huffman.capacity(19, CLBITS, 7) + +-- fixed Huffman tables +local FLIT, FDIST = bcreate(LITCAP * 4), bcreate(DISTCAP * 4) +local FLITS, FDISTS +do + local l = bcreate(288) + bfill(l, 0, 8, 144) + bfill(l, 144, 9, 112) + bfill(l, 256, 7, 24) + bfill(l, 280, 8, 8) + FLITS = Huffman.buildLsb(l, 0, 288, FLIT, LITBITS) + local d = bcreate(30) + bfill(d, 0, 5, 30) + FDISTS = Huffman.buildLsb(d, 0, 30, FDIST, DISTBITS) +end + +local Inflate = {} + +-- Grow out (capacity cap) to hold at least need bytes. Returns the new buffer and capacity. +local function grow(out: buffer, op: number, need: number): (buffer, number) + local cap = math.max(blen(out) * 2, need, 1024) + local nb = bcreate(cap) + bcopy(nb, 0, out, 0, op) + return nb, cap +end + +-- Inflate src[start, endpos) into a buffer. cap: initial output capacity; exact: true = the output must fit in +-- cap bytes (an error otherwise), false = grow as needed. +-- Returns out, outLen, consumedEnd (the input offset just past the final block) or nil, message. +function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, exact: boolean): (buffer?, any, number?) + local out = bcreate(cap) + local op = 0 + local pos = start + local bitbuf, bitcnt, over = 0, 0, 0 + local lt, dt = bcreate(LITCAP * 4), bcreate(DISTCAP * 4) + local clt = bcreate(CLCAP * 4) + local lens = bcreate(320) + local final = 0 + repeat + -- block header (3 bits); also up to 14 bits of a dynamic header + if bitcnt < 17 then + if pos + 4 <= endpos then + bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt)) + local nb = rshift(32 - bitcnt, 3) + pos += nb + bitcnt += nb * 8 + else + while bitcnt <= 24 do + if pos < endpos then + bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt)) + pos += 1 + else + over += 1 + if over > 4 then + return nil, "truncated input" + end + end + bitcnt += 8 + end + end + end + final = band(bitbuf, 1) + local btype = band(rshift(bitbuf, 1), 3) + bitbuf = rshift(bitbuf, 3) + bitcnt -= 3 + if btype == 0 then + -- stored: skip to the byte boundary, give back the whole bytes still in the bit buffer + local k = band(bitcnt, 7) + bitcnt -= k + local real = rshift(bitcnt, 3) - over + if real < 0 then + return nil, "truncated input" + end + pos -= real + bitbuf, bitcnt, over = 0, 0, 0 + if pos + 4 > endpos then + return nil, "truncated input" + end + local n = readu16(src, pos) + if n ~= bxor(readu16(src, pos + 2), 0xFFFF) then + return nil, "stored block length mismatch" + end + pos += 4 + if pos + n > endpos then + return nil, "truncated input" + end + if op + n > cap then + if exact then + return nil, "output larger than expected" + end + out, cap = grow(out, op, op + n) + end + bcopy(out, op, src, pos, n) + op += n + pos += n + continue + end + local lsub, dsub + if btype == 1 then + lt, dt = FLIT, FDIST + lsub, dsub = FLITS, FDISTS + elseif btype == 2 then + if lt == FLIT then + lt, dt = bcreate(LITCAP * 4), bcreate(DISTCAP * 4) + end + local hlit = band(bitbuf, 31) + 257 + local hdist = band(rshift(bitbuf, 5), 31) + 1 + local hclen = band(rshift(bitbuf, 10), 15) + 4 + bitbuf = rshift(bitbuf, 14) + bitcnt -= 14 + if hlit > 286 or hdist > 30 then + return nil, "too many length or distance symbols" + end + bfill(lens, 0, 0, 19) + for i = 1, hclen do + if bitcnt < 3 then + if pos + 4 <= endpos then + bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt)) + local nb = rshift(32 - bitcnt, 3) + pos += nb + bitcnt += nb * 8 + else + while bitcnt <= 24 do + if pos < endpos then + bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt)) + pos += 1 + else + over += 1 + if over > 4 then + return nil, "truncated input" + end + end + bitcnt += 8 + end + end + end + writeu8(lens, CLORDER[i], band(bitbuf, 7)) + bitbuf = rshift(bitbuf, 3) + bitcnt -= 3 + end + if Huffman.buildLsb(lens, 0, 19, clt, CLBITS) < 0 then + return nil, "invalid code lengths set" + end + local total = hlit + hdist + local i = 0 + while i < total do + if bitcnt < 14 then + if pos + 4 <= endpos then + bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt)) + local nb = rshift(32 - bitcnt, 3) + pos += nb + bitcnt += nb * 8 + else + while bitcnt <= 24 do + if pos < endpos then + bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt)) + pos += 1 + else + over += 1 + if over > 4 then + return nil, "truncated input" + end + end + bitcnt += 8 + end + end + end + local e = readu32(clt, band(bitbuf, CLMASK) * 4) + local l = band(e, 31) + if l == 0 then + return nil, "invalid code lengths set" + end + bitbuf = rshift(bitbuf, l) + bitcnt -= l + local sym = rshift(e, 5) + if sym < 16 then + writeu8(lens, i, sym) + i += 1 + else + local rep, val + if sym == 16 then + if i == 0 then + return nil, "repeat with no first length" + end + val = readu8(lens, i - 1) + rep = 3 + band(bitbuf, 3) + bitbuf = rshift(bitbuf, 2) + bitcnt -= 2 + elseif sym == 17 then + val = 0 + rep = 3 + band(bitbuf, 7) + bitbuf = rshift(bitbuf, 3) + bitcnt -= 3 + else + val = 0 + rep = 11 + band(bitbuf, 127) + bitbuf = rshift(bitbuf, 7) + bitcnt -= 7 + end + if i + rep > total then + return nil, "too many code lengths" + end + bfill(lens, i, val, rep) + i += rep + end + end + if readu8(lens, 256) == 0 then + return nil, "missing end-of-block code" + end + lsub = Huffman.buildLsb(lens, 0, hlit, lt, LITBITS) + dsub = Huffman.buildLsb(lens, hlit, hdist, dt, DISTBITS) + if lsub < 0 or dsub < 0 then + return nil, "invalid literal/length or distance code set" + end + else + return nil, "invalid block type" + end + local lsmask = lshift(1, lsub) - 1 + local dsmask = lshift(1, dsub) - 1 + -- the symbol loop + while true do + if bitcnt < 15 then + if pos + 4 <= endpos then + bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt)) + local nb = rshift(32 - bitcnt, 3) + pos += nb + bitcnt += nb * 8 + else + while bitcnt <= 24 do + if pos < endpos then + bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt)) + pos += 1 + else + over += 1 + if over > 4 then + return nil, "truncated input" + end + end + bitcnt += 8 + end + end + end + local e = readu32(lt, band(bitbuf, LITMASK) * 4) + local l = band(e, 31) + if l == 0 then + if e == 0 then + return nil, "invalid literal/length code" + end + e = readu32(lt, (rshift(e, 5) + band(rshift(bitbuf, LITBITS), lsmask)) * 4) + l = band(e, 31) + if l == 0 then + return nil, "invalid literal/length code" + end + end + bitbuf = rshift(bitbuf, l) + bitcnt -= l + local sym = rshift(e, 5) + if sym < 256 then + if op >= cap then + if exact then + return nil, "output larger than expected" + end + out, cap = grow(out, op, op + 1) + end + writeu8(out, op, sym) + op += 1 + elseif sym == 256 then + break + else + sym -= 256 + if sym > 29 then + return nil, "invalid literal/length code" + end + -- up to 5 length extra bits + a 15-bit distance code + if bitcnt < 20 then + if pos + 4 <= endpos then + bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt)) + local nb = rshift(32 - bitcnt, 3) + pos += nb + bitcnt += nb * 8 + else + while bitcnt <= 24 do + if pos < endpos then + bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt)) + pos += 1 + else + over += 1 + if over > 4 then + return nil, "truncated input" + end + end + bitcnt += 8 + end + end + end + local len = LBASE[sym] + local xb = LEXT[sym] + if xb > 0 then + len += band(bitbuf, lshift(1, xb) - 1) + bitbuf = rshift(bitbuf, xb) + bitcnt -= xb + end + e = readu32(dt, band(bitbuf, DISTMASK) * 4) + l = band(e, 31) + if l == 0 then + if e == 0 then + return nil, "invalid distance code" + end + e = readu32(dt, (rshift(e, 5) + band(rshift(bitbuf, DISTBITS), dsmask)) * 4) + l = band(e, 31) + if l == 0 then + return nil, "invalid distance code" + end + end + bitbuf = rshift(bitbuf, l) + bitcnt -= l + local dsym = rshift(e, 5) + 1 + if dsym > 30 then + return nil, "invalid distance code" + end + local dist = DBASE[dsym] + xb = DEXT[dsym] + if xb > 0 then + if bitcnt < 13 then + if pos + 4 <= endpos then + bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt)) + local nb = rshift(32 - bitcnt, 3) + pos += nb + bitcnt += nb * 8 + else + while bitcnt <= 24 do + if pos < endpos then + bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt)) + pos += 1 + else + over += 1 + if over > 4 then + return nil, "truncated input" + end + end + bitcnt += 8 + end + end + end + dist += band(bitbuf, lshift(1, xb) - 1) + bitbuf = rshift(bitbuf, xb) + bitcnt -= xb + end + if dist > op then + return nil, "invalid distance too far back" + end + if op + len > cap then + if exact then + return nil, "output larger than expected" + end + out, cap = grow(out, op, op + len) + end + local s = op - dist + if dist >= len then + if len <= 16 and op + 16 <= cap then + -- straight-line 16-byte copy (the bytes past len are rewritten later): no inner loop, which + -- keeps LuaJIT's traces simple; chunks read only bytes before op or already copied ones + writeu32(out, op, readu32(out, s)) + writeu32(out, op + 4, readu32(out, s + 4)) + writeu32(out, op + 8, readu32(out, s + 8)) + writeu32(out, op + 12, readu32(out, s + 12)) + elseif len <= 16 then + for k = 0, len - 1 do + writeu8(out, op + k, readu8(out, s + k)) + end + else + bcopy(out, op, out, s, len) + end + op += len + elseif dist == 1 then + bfill(out, op, readu8(out, s), len) + op += len + else + -- overlapping: the pattern of period dist, copied in growing non-overlapping chunks + local rem = len + while rem > 0 do + local k = math.min(op - s, rem) + bcopy(out, op, out, s, k) + op += k + rem -= k + end + end + end + end + until final == 1 + local consumed = pos + over - rshift(bitcnt, 3) + if consumed > endpos then + return nil, "truncated input" + end + return out, op, consumed +end + +return Inflate diff --git a/src/Formats/codecs/Deflate/init.luau b/src/Formats/codecs/Deflate/init.luau new file mode 100644 index 0000000..c903ef8 --- /dev/null +++ b/src/Formats/codecs/Deflate/init.luau @@ -0,0 +1,301 @@ +--!strict +-- codecs/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers. +-- A codec (layer 1), not a format: png, zip, gzip, woff, tiff, ... build on it. Absorbed from deflate-luau 1.0.0 +-- (same author; no third-party code); the compressor is new. +-- +-- local Deflate = require("@formats/codecs/Deflate") +-- local out, err = Deflate.inflate(buf) -- raw deflate -> buffer, consumedEnd | nil, Err +-- local out, err = Deflate.inflate(buf, off, len, size) -- a range, with the exact output size if known +-- local out, err = Deflate.zlib(buf) -- checks the Adler-32 +-- local out, err = Deflate.gunzip(buf) -- checks CRC-32 + ISIZE, concatenates members +-- local z = Deflate.compress(buf, { level = 6 }) -- raw deflate; also zlibCompress / gzip +-- +-- Never throws: bad data and bad arguments return nil, Err (core/Err codes TRUNCATED / CORRUPT / CHECKSUM / ARG). +local Err = require("@formats/core/Err") +local Crc32 = require("@formats/core/Crc32") +local Adler32 = require("@formats/core/Adler32") +local Inflate = require("@formats/codecs/Deflate/Inflate") +local Compress = require("@formats/codecs/Deflate/Compress") + +local Deflate = {} + +Deflate.version = "1.1.0" + +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 + +-- (offset, length) clamped to the buffer; nil for non-numbers / negative / fractional / out-of-range offsets +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 shrink(out: buffer, n: number): buffer + if buffer.len(out) == n then + return out + end + local b = buffer.create(n) + buffer.copy(b, 0, out, 0, n) + return b +end + +local function inflateErr(msg: string, at: number?): Err.Err + local code = if string.find(msg, "truncated", 1, true) then Err.TRUNCATED else Err.CORRUPT + return Err.new(code, "inflate: " .. msg, at) +end + +-- inflate(buf, offset?, length?, expectedSize?) -> buffer, consumedEnd | nil, Err. Raw deflate. +-- expectedSize: the exact uncompressed size when known (a zip entry): the output is allocated once, and a stream +-- that inflates to a different size is an error. consumedEnd is the input offset just past the final block. +function Deflate.inflate(buf: buffer | string, offset: number?, length: number?, expectedSize: number?): (buffer?, any) + local b, o, l, aerr = args("Deflate.inflate", buf, offset, length) + if not b then + return nil, aerr + end + local exact = expectedSize ~= nil + local cap + if exact then + if type(expectedSize) ~= "number" or expectedSize < 0 or expectedSize % 1 ~= 0 then + return nil, Err.new(Err.ARG, "Deflate.inflate: bad expectedSize " .. tostring(expectedSize)) + end + cap = expectedSize + else + cap = math.max(1024, l * 4) + end + local out, n, consumed = Inflate.raw(b, o, o + l, cap :: number, exact) + if not out then + return nil, inflateErr(tostring(n), o) + end + if exact and n ~= expectedSize then + return nil, Err.new(Err.CORRUPT, string.format("inflate: output is %d bytes, expected %d", n, expectedSize :: number)) + end + return shrink(out, n), consumed +end + +-- zlib(buf, offset?, length?, expectedSize?) -> buffer, consumedEnd | nil, Err +function Deflate.zlib(buf: buffer | string, offset: number?, length: number?, expectedSize: number?): (buffer?, any) + local b, o, l, aerr = args("Deflate.zlib", buf, offset, length) + if not b then + return nil, aerr + end + if l < 6 then + return nil, Err.new(Err.TRUNCATED, "zlib: truncated header", o) + end + local cmf, flg = buffer.readu8(b, o), buffer.readu8(b, o + 1) + if cmf % 16 ~= 8 or cmf // 16 > 7 then + return nil, Err.new(Err.CORRUPT, "zlib: not a deflate stream (CMF " .. cmf .. ")", o) + end + if (cmf * 256 + flg) % 31 ~= 0 then + return nil, Err.new(Err.CORRUPT, "zlib: header check failed", o) + end + if bit32.band(flg, 0x20) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "zlib: preset dictionaries are not supported", o) + end + local out, consumed = Deflate.inflate(b, o + 2, l - 2, expectedSize) + if not out then + return nil, consumed + end + if consumed + 4 > o + l then + return nil, Err.new(Err.TRUNCATED, "zlib: missing Adler-32", consumed) + end + local want = bit32.byteswap(buffer.readu32(b, consumed)) + local got = Adler32.raw(out, 0, buffer.len(out)) + if got ~= want then + return nil, Err.new(Err.CHECKSUM, string.format("zlib: Adler-32 mismatch (%08x, expected %08x)", got, want), consumed) + end + return out, consumed + 4 +end + +-- gunzip(buf, offset?, length?) -> buffer | nil, Err. Members are concatenated; trailing data after a member that is +-- not another gzip member (zero padding, garbage) is ignored, as gzip -d does. +function Deflate.gunzip(buf: buffer | string, offset: number?, length: number?): (buffer?, Err.Err?) + local b, o, l, aerr = args("Deflate.gunzip", buf, offset, length) + if not b then + return nil, aerr + end + local e = o + l + local parts, total = {}, 0 + local p = o + repeat + if p + 18 > e then + if #parts > 0 then + break + end + return nil, Err.new(Err.TRUNCATED, "gzip: truncated member", p) + end + if buffer.readu8(b, p) ~= 0x1f or buffer.readu8(b, p + 1) ~= 0x8b then + if #parts > 0 then + break -- trailing garbage after a member: ignored, as gzip -d does + end + return nil, Err.new(Err.CORRUPT, "gzip: bad magic", p) + end + if buffer.readu8(b, p + 2) ~= 8 then + return nil, Err.new(Err.UNSUPPORTED, "gzip: unknown compression method", p + 2) + end + local flg = buffer.readu8(b, p + 3) + if flg >= 0x20 then + return nil, Err.new(Err.CORRUPT, "gzip: reserved flags set", p + 3) + end + local q = p + 10 + if bit32.band(flg, 4) ~= 0 then -- FEXTRA + if q + 2 > e then + return nil, Err.new(Err.TRUNCATED, "gzip: truncated header", q) + end + q += 2 + buffer.readu16(b, q) + end + for _, bit in { 8, 16 } do -- FNAME, FCOMMENT: zero-terminated + if bit32.band(flg, bit) ~= 0 then + while q < e and buffer.readu8(b, q) ~= 0 do + q += 1 + end + q += 1 + end + end + if bit32.band(flg, 2) ~= 0 then -- FHCRC + q += 2 + end + if q >= e then + return nil, Err.new(Err.TRUNCATED, "gzip: truncated header", q) + end + local out, consumed = Deflate.inflate(b, q, e - q) + if not out then + return nil, consumed + end + if consumed + 8 > e then + return nil, Err.new(Err.TRUNCATED, "gzip: missing trailer", consumed) + end + local want, isize = buffer.readu32(b, consumed), buffer.readu32(b, consumed + 4) + local got = Crc32.raw(out, 0, buffer.len(out)) + if got ~= want then + return nil, Err.new(Err.CHECKSUM, string.format("gzip: CRC-32 mismatch (%08x, expected %08x)", got, want), consumed) + end + if buffer.len(out) % 4294967296 ~= isize then + return nil, Err.new(Err.CORRUPT, "gzip: length mismatch", consumed + 4) + end + table.insert(parts, out) + total += buffer.len(out) + p = consumed + 8 + -- skip zero padding + local z = p + while z < e and buffer.readu8(b, z) == 0 do + z += 1 + end + if z == e then + break + end + until p >= e + if #parts == 1 then + return parts[1], nil + end + local res = buffer.create(total) + local w = 0 + for _, part in parts do + buffer.copy(res, w, part) + w += buffer.len(part) + end + return res, nil +end + +export type CompressOptions = { + level: number?, -- 0 (stored) .. 9 (best); default 6 +} + +local function level(opts: CompressOptions?): number? + local lv = if opts and opts.level ~= nil then opts.level else 6 + if type(lv) ~= "number" or lv < 0 or lv > 9 or lv % 1 ~= 0 then + return nil + end + return lv +end + +-- compress(buf, opts?) -> raw deflate buffer | nil, Err +function Deflate.compress(buf: buffer | string, opts: CompressOptions?): (buffer?, Err.Err?) + local b = toBuffer(buf) + local lv = level(opts) + if not b or not lv then + return nil, Err.new(Err.ARG, "Deflate.compress: expected a buffer or a string and opts.level 0..9") + end + return Compress.raw(b, 0, buffer.len(b), lv), nil +end + +-- zlibCompress(buf, opts?) -> zlib stream | nil, Err +function Deflate.zlibCompress(buf: buffer | string, opts: CompressOptions?): (buffer?, Err.Err?) + local b = toBuffer(buf) + local lv = level(opts) + if not b or not lv then + return nil, Err.new(Err.ARG, "Deflate.zlibCompress: expected a buffer or a string and opts.level 0..9") + end + local raw = Compress.raw(b, 0, buffer.len(b), lv) + local n = buffer.len(raw) + local out = buffer.create(n + 6) + local flevel = if lv < 2 then 0 elseif lv < 6 then 1 elseif lv == 6 then 2 else 3 + local cmf = 0x78 + local flg = flevel * 64 + flg += 31 - (cmf * 256 + flg) % 31 + buffer.writeu8(out, 0, cmf) + buffer.writeu8(out, 1, flg) + buffer.copy(out, 2, raw, 0, n) + buffer.writeu32(out, n + 2, bit32.byteswap(Adler32.raw(b, 0, buffer.len(b)))) + return out, nil +end + +-- gzip(buf, opts?) -> gzip member (no name, mtime 0) | nil, Err +function Deflate.gzip(buf: buffer | string, opts: CompressOptions?): (buffer?, Err.Err?) + local b = toBuffer(buf) + local lv = level(opts) + if not b or not lv then + return nil, Err.new(Err.ARG, "Deflate.gzip: expected a buffer or a string and opts.level 0..9") + end + local raw = Compress.raw(b, 0, buffer.len(b), lv) + local n = buffer.len(raw) + local out = buffer.create(n + 18) + buffer.writestring(out, 0, "\31\139\8\0\0\0\0\0") + buffer.writeu8(out, 8, if lv >= 9 then 2 elseif lv <= 1 then 4 else 0) + buffer.writeu8(out, 9, 255) + buffer.copy(out, 10, raw, 0, n) + buffer.writeu32(out, n + 10, Crc32.raw(b, 0, buffer.len(b))) + buffer.writeu32(out, n + 14, buffer.len(b) % 4294967296) + return out, nil +end + +-- crc32 / adler32 (kept from deflate-luau's API; the same as core/Crc32.of / core/Adler32.of) +Deflate.crc32 = function(buf: buffer | string, offset: number?, length: number?, crc: number?): number + local b = toBuffer(buf) or buffer.create(0) + return Crc32.of(b, offset, length, crc) +end +Deflate.adler32 = function(buf: buffer | string, offset: number?, length: number?, adler: number?): number + local b = toBuffer(buf) or buffer.create(0) + return Adler32.of(b, offset, length, adler) +end + +return Deflate diff --git a/src/Formats/core/Adler32.luau b/src/Formats/core/Adler32.luau new file mode 100644 index 0000000..8684aff --- /dev/null +++ b/src/Formats/core/Adler32.luau @@ -0,0 +1,50 @@ +--!strict +--!native +-- core/Adler32: Adler-32 (RFC 1950, the zlib checksum). Absorbed from deflate-luau src/Deflate/Checksum.luau (same author; +-- no third-party code). Never throws: the range is clamped. +-- +-- Adler32.of(buf, offset?, length?, adler?) -> u32 (starts at 1; pass a previous result to continue it) +-- Adler32.string(s, adler?) -> u32 +local readu8 = buffer.readu8 + +-- Adler-32 of buf[off, off + len), continuing adler (default 1) +local function adler32(buf: buffer, off: number, len: number, adler: number?): number + local a0 = adler or 1 + local a, b = a0 % 65536, a0 // 65536 + local i, e = off, off + len + while i < e do + -- 5552 is zlib's NMAX: the largest n with 255 n (n + 1) / 2 + (n + 1) (BASE - 1) < 2^32. Doubles hold far + -- more, but keeping the sums small keeps them exact and cheap. + local stop = math.min(e, i + 5552) + while i < stop do + a += readu8(buf, i) + b += a + i += 1 + end + a %= 65521 + b %= 65521 + end + return b * 65536 + a +end + +-- clamp (offset, length) to the buffer +local function range(buf: buffer, offset: number?, length: number?): (number, number) + local n = buffer.len(buf) + local o = math.clamp(offset or 0, 0, n) + return o, math.clamp(length or (n - o), 0, n - o) +end + +local Adler32 = {} + +function Adler32.of(buf: buffer, offset: number?, length: number?, adler: number?): number + local o, l = range(buf, offset, length) + return adler32(buf, o, l, adler) +end + +function Adler32.string(s: string, adler: number?): number + return adler32(buffer.fromstring(s), 0, #s, adler) +end + +Adler32.raw = adler32 + +return Adler32 diff --git a/src/Formats/core/Bits.luau b/src/Formats/core/Bits.luau new file mode 100644 index 0000000..e2d1fa1 --- /dev/null +++ b/src/Formats/core/Bits.luau @@ -0,0 +1,287 @@ +--!strict +--!native +-- core/Bits: bit readers and writers, LSB-first (DEFLATE, GIF LZW, VP8L, ...) and MSB-first (JPEG entropy data +-- without the 0xFF00 unstuffing, MPEG, H.264, FLAC, ...). Up to 32 bits per read / write. +-- +-- Plain arithmetic on an accumulator of at most 31 bits (no bit32 calls), exact on doubles, cheap on both runtimes. +-- These are the generic, convenient readers: a codec's innermost loop usually keeps its own local bit buffer (see +-- codecs/Deflate/Inflate) and uses these for headers. +-- +-- Never throws: reading past the end returns zero bits and sets the sticky `err` (Err.TRUNCATED). +-- +-- local br = Bits.lsbReader(buf, offset?, length?) -- or Bits.msbReader +-- local v = br:read(5); if br.err then return nil, br.err end +-- local bw = Bits.msbWriter(); bw:write(0b101, 3); local out = bw:finish() +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") + +local readu8, blen = buffer.readu8, buffer.len +local floor = math.floor + +-- 2^n for n = 0..32 +local POW = table.create(33, 0) +for i = 0, 32 do + POW[i + 1] = 2 ^ i +end + +local Bits = {} +Bits.POW = POW + +-- ------------------------------------------------------------------------------------------------ readers +export type BitReader = { + buf: buffer, + pos: number, -- next byte to load + limit: number, + acc: number, -- loaded, unread bits + cnt: number, -- how many + err: Err.Err?, + read: (BitReader, number) -> number, + peek: (BitReader, number) -> number, + skip: (BitReader, number) -> (), + align: (BitReader) -> (), + bytePos: (BitReader) -> number, + bitsLeft: (BitReader) -> number, +} + +local function overrun(self: any) + if not self.err then + self.err = Err.new(Err.TRUNCATED, "bit stream ends early", self.limit) + end +end + +-- LSB-first: the first bit of the stream is bit 0 of the first byte; a field's first bit is its least significant +local Lsb = {} +Lsb.__index = Lsb + +local function lsbFill(self: any, n: number) + local acc, cnt, pos = self.acc, self.cnt, self.pos + while cnt < n do + if pos < self.limit then + acc += readu8(self.buf, pos) * POW[cnt + 1] + pos += 1 + else + overrun(self) + end + cnt += 8 + end + self.acc, self.cnt, self.pos = acc, cnt, pos +end + +function Lsb.read(self: any, n: number): number + if n > 24 then + local lo = Lsb.read(self, 16) + return lo + Lsb.read(self, n - 16) * 65536 + end + if self.cnt < n then + lsbFill(self, n) + end + local m = POW[n + 1] + local v = self.acc % m + self.acc = (self.acc - v) / m + self.cnt -= n + return v +end +function Lsb.peek(self: any, n: number): number + if self.cnt < n then + local acc, cnt, pos = self.acc, self.cnt, self.pos + while cnt < n do -- no error for peeking past the end: the bits are zeros + if pos < self.limit then + acc += readu8(self.buf, pos) * POW[cnt + 1] + pos += 1 + end + cnt += 8 + end + -- keep the loaded bytes only when they are all real (zero padding past the end is not data) + if (pos - self.pos) * 8 == cnt - self.cnt then + self.acc, self.cnt, self.pos = acc, cnt, pos + end + return acc % POW[n + 1] + end + return self.acc % POW[n + 1] +end +function Lsb.skip(self: any, n: number) + while n > 24 do + Lsb.read(self, 24) + n -= 24 + end + Lsb.read(self, n) +end +-- align(): drop the bits up to the next byte boundary +function Lsb.align(self: any) + local k = self.cnt % 8 + if k > 0 then + Lsb.read(self, k) + end +end +-- bytePos(): the offset of the first byte not yet (even partly) consumed +function Lsb.bytePos(self: any): number + return self.pos - floor(self.cnt / 8) +end +function Lsb.bitsLeft(self: any): number + return (self.limit - self.pos) * 8 + self.cnt +end + +-- MSB-first: the first bit of the stream is bit 7 of the first byte; a field's first bit is its most significant +local Msb = {} +Msb.__index = Msb + +local function msbFill(self: any, n: number) + local acc, cnt, pos = self.acc, self.cnt, self.pos + while cnt < n do + if pos < self.limit then + acc = acc * 256 + readu8(self.buf, pos) + pos += 1 + else + acc *= 256 + overrun(self) + end + cnt += 8 + end + self.acc, self.cnt, self.pos = acc, cnt, pos +end + +function Msb.read(self: any, n: number): number + if n > 24 then + local hi = Msb.read(self, n - 16) + return hi * 65536 + Msb.read(self, 16) + end + if self.cnt < n then + msbFill(self, n) + end + local sh = POW[self.cnt - n + 1] + local v = floor(self.acc / sh) + self.acc -= v * sh + self.cnt -= n + return v +end +function Msb.peek(self: any, n: number): number + local acc, cnt, pos = self.acc, self.cnt, self.pos + while cnt < n do + if pos < self.limit then + acc = acc * 256 + readu8(self.buf, pos) + pos += 1 + else + acc *= 256 + end + cnt += 8 + end + -- keep the loaded bytes only when they are all real (zero padding past the end is not data) + if (pos - self.pos) * 8 == cnt - self.cnt then + self.acc, self.cnt, self.pos = acc, cnt, pos + end + return floor(acc / POW[cnt - n + 1]) +end +function Msb.skip(self: any, n: number) + while n > 24 do + Msb.read(self, 24) + n -= 24 + end + Msb.read(self, n) +end +function Msb.align(self: any) + local k = self.cnt % 8 + if k > 0 then + Msb.read(self, k) + end +end +Msb.bytePos = Lsb.bytePos +Msb.bitsLeft = Lsb.bitsLeft + +local function reader(meta: any, buf: buffer, offset: number?, length: number?): BitReader + local n = blen(buf) + local o = math.clamp(offset or 0, 0, n) + local l = math.clamp(length or (n - o), 0, n - o) + return setmetatable({ buf = buf, pos = o, limit = o + l, acc = 0, cnt = 0, err = nil }, meta) :: any +end + +-- lsbReader(buf, offset?, length?) / msbReader(buf, offset?, length?) -> BitReader +function Bits.lsbReader(buf: buffer, offset: number?, length: number?): BitReader + return reader(Lsb, buf, offset, length) +end +function Bits.msbReader(buf: buffer, offset: number?, length: number?): BitReader + return reader(Msb, buf, offset, length) +end + +-- ------------------------------------------------------------------------------------------------ writers +export type BitWriter = { + out: Bytes.Writer, -- the bytes so far (whole bytes only) + acc: number, + cnt: number, + write: (BitWriter, number, number) -> (), + align: (BitWriter) -> (), + finish: (BitWriter) -> buffer, +} + +local LsbW = {} +LsbW.__index = LsbW +function LsbW.write(self: any, v: number, n: number) + if n > 24 then + local lo = v % 65536 + LsbW.write(self, lo, 16) + LsbW.write(self, (v - lo) / 65536, n - 16) + return + end + local acc = self.acc + (v % POW[n + 1]) * POW[self.cnt + 1] + local cnt = self.cnt + n + local out = self.out + while cnt >= 8 do + local byte = acc % 256 + out:u8(byte) + acc = (acc - byte) / 256 + cnt -= 8 + end + self.acc, self.cnt = acc, cnt +end +-- align(): pad with zero bits to a byte boundary +function LsbW.align(self: any) + if self.cnt > 0 then + self.out:u8(self.acc) + self.acc, self.cnt = 0, 0 + end +end +function LsbW.finish(self: any): buffer + LsbW.align(self) + return self.out:finish() +end + +local MsbW = {} +MsbW.__index = MsbW +function MsbW.write(self: any, v: number, n: number) + if n > 24 then + local lo = v % 65536 + MsbW.write(self, (v - lo) / 65536, n - 16) + MsbW.write(self, lo, 16) + return + end + local acc = self.acc * POW[n + 1] + (v % POW[n + 1]) + local cnt = self.cnt + n + local out = self.out + while cnt >= 8 do + local sh = POW[cnt - 8 + 1] + local byte = floor(acc / sh) + out:u8(byte) + acc -= byte * sh + cnt -= 8 + end + self.acc, self.cnt = acc, cnt +end +function MsbW.align(self: any) + if self.cnt > 0 then + self.out:u8(self.acc * POW[8 - self.cnt + 1]) + self.acc, self.cnt = 0, 0 + end +end +function MsbW.finish(self: any): buffer + MsbW.align(self) + return self.out:finish() +end + +-- lsbWriter(capacity?) / msbWriter(capacity?) -> BitWriter +function Bits.lsbWriter(capacity: number?): BitWriter + return setmetatable({ out = Bytes.writer(capacity), acc = 0, cnt = 0 }, LsbW) :: any +end +function Bits.msbWriter(capacity: number?): BitWriter + return setmetatable({ out = Bytes.writer(capacity), acc = 0, cnt = 0 }, MsbW) :: any +end + +return Bits diff --git a/src/Formats/core/Bytes.luau b/src/Formats/core/Bytes.luau new file mode 100644 index 0000000..e9e921e --- /dev/null +++ b/src/Formats/core/Bytes.luau @@ -0,0 +1,537 @@ +--!strict +--!native +-- core/Bytes: a cursor Reader over a buffer range and a growable Writer. Little / big endian integers up to u64 (as a +-- double: exact to 2^53), f16 / f32 / f64, C strings, fixed strings, and zero-copy sub-readers. +-- +-- Never throws. A read past the end (or a failed seek) sets the reader's sticky `err` (Err.TRUNCATED), moves the cursor +-- to the end and returns 0 / "" (a zero-length buffer for bytes()); check `r.err` once after a run of reads: +-- +-- local r = Bytes.reader(buf) -- or Bytes.reader(buf, offset, length) +-- local magic, w, h = r:string(4), r:u32be(), r:u32be() +-- if r.err then return nil, r.err end +-- if magic ~= "abcd" then return r:fail(Err.CORRUPT, "bad magic") end +-- +-- local w = Bytes.writer() -- or Bytes.writer(initialCapacity) +-- w:string("abcd"); w:u32be(width); local out = w:finish() +local Err = require("@formats/core/Err") + +local readu8, readi8, readu16, readi16, readu32, readi32 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readi32 +local readf32, readf64, readstring = buffer.readf32, buffer.readf64, buffer.readstring +local writeu8, writeu16, writeu32, writef32, writef64, writestring = buffer.writeu8, buffer.writeu16, buffer.writeu32, buffer.writef32, buffer.writef64, buffer.writestring +local bcreate, bcopy, bfill, blen = buffer.create, buffer.copy, buffer.fill, buffer.len +local byteswap = bit32.byteswap + +local TWO32 = 4294967296 +local scratch = bcreate(8) -- reinterpret casts for big-endian floats + +local Bytes = {} + +-- ------------------------------------------------------------------------------------------------ Reader +local Reader = {} +Reader.__index = Reader + +export type Reader = typeof(setmetatable( + {} :: { + buf: buffer, + pos: number, -- absolute offset of the next byte in buf + base: number, -- absolute offset of the reader's first byte + limit: number, -- absolute offset just past the reader's last byte + err: Err.Err?, -- sticky: the first failure + }, + Reader +)) + +-- reader(buf, offset?, length?) -> Reader over buf[offset, offset + length), clamped to the buffer +function Bytes.reader(buf: buffer, offset: number?, length: number?): Reader + local n = blen(buf) + local o = math.clamp(offset or 0, 0, n) + local l = math.clamp(length or (n - o), 0, n - o) + return setmetatable({ buf = buf, pos = o, base = o, limit = o + l, err = nil :: Err.Err? }, Reader) +end + +-- fail(code, message) -> nil, Err: records the first error (at the cursor) and returns it, for `return r:fail(...)` +function Reader.fail(self: Reader, code: string, message: string): (nil, Err.Err) + if not self.err then + self.err = Err.new(code, message, self.pos) + end + return nil, self.err :: Err.Err +end + +-- need(n) -> true when n more bytes are available; otherwise records TRUNCATED and moves to the end +function Reader.need(self: Reader, n: number): boolean + if self.pos + n <= self.limit and n >= 0 then + return true + end + if not self.err then + self.err = Err.new(Err.TRUNCATED, string.format("need %d bytes, %d left", n, self.limit - self.pos), self.pos) + end + self.pos = self.limit + return false +end + +function Reader.tell(self: Reader): number + return self.pos - self.base +end +function Reader.size(self: Reader): number + return self.limit - self.base +end +function Reader.remaining(self: Reader): number + return self.limit - self.pos +end +function Reader.eof(self: Reader): boolean + return self.pos >= self.limit +end + +-- seek(offset) -> boolean: offset relative to the reader's start; out of range records TRUNCATED +function Reader.seek(self: Reader, offset: number): boolean + if offset < 0 or self.base + offset > self.limit then + self.pos = self.limit + if not self.err then + self.err = Err.new(Err.TRUNCATED, "seek to " .. offset .. " past the end", self.base + offset) + end + return false + end + self.pos = self.base + offset + return true +end + +function Reader.skip(self: Reader, n: number): boolean + if self:need(n) then + self.pos += n + return true + end + return false +end + +-- align(n): skip to the next multiple of n (relative to the reader's start) +function Reader.align(self: Reader, n: number): boolean + local r = (self.pos - self.base) % n + if r == 0 then + return true + end + return self:skip(n - r) +end + +-- integers +function Reader.u8(self: Reader): number + local p = self.pos + if p + 1 > self.limit then + self:need(1) + return 0 + end + self.pos = p + 1 + return readu8(self.buf, p) +end +function Reader.i8(self: Reader): number + local p = self.pos + if p + 1 > self.limit then + self:need(1) + return 0 + end + self.pos = p + 1 + return readi8(self.buf, p) +end +function Reader.u16le(self: Reader): number + local p = self.pos + if p + 2 > self.limit then + self:need(2) + return 0 + end + self.pos = p + 2 + return readu16(self.buf, p) +end +function Reader.u16be(self: Reader): number + local p = self.pos + if p + 2 > self.limit then + self:need(2) + return 0 + end + self.pos = p + 2 + return readu8(self.buf, p) * 256 + readu8(self.buf, p + 1) +end +function Reader.i16le(self: Reader): number + local p = self.pos + if p + 2 > self.limit then + self:need(2) + return 0 + end + self.pos = p + 2 + return readi16(self.buf, p) +end +function Reader.i16be(self: Reader): number + local v = self:u16be() + return if v >= 32768 then v - 65536 else v +end +function Reader.u24le(self: Reader): number + local p = self.pos + if p + 3 > self.limit then + self:need(3) + return 0 + end + self.pos = p + 3 + return readu16(self.buf, p) + readu8(self.buf, p + 2) * 65536 +end +function Reader.u24be(self: Reader): number + local p = self.pos + if p + 3 > self.limit then + self:need(3) + return 0 + end + self.pos = p + 3 + return readu8(self.buf, p) * 65536 + readu8(self.buf, p + 1) * 256 + readu8(self.buf, p + 2) +end +function Reader.u32le(self: Reader): number + local p = self.pos + if p + 4 > self.limit then + self:need(4) + return 0 + end + self.pos = p + 4 + return readu32(self.buf, p) +end +function Reader.u32be(self: Reader): number + local p = self.pos + if p + 4 > self.limit then + self:need(4) + return 0 + end + self.pos = p + 4 + return byteswap(readu32(self.buf, p)) +end +function Reader.i32le(self: Reader): number + local p = self.pos + if p + 4 > self.limit then + self:need(4) + return 0 + end + self.pos = p + 4 + return readi32(self.buf, p) +end +function Reader.i32be(self: Reader): number + local v = self:u32be() + return if v >= 2147483648 then v - TWO32 else v +end +-- 64-bit integers as doubles (exact below 2^53) +function Reader.u64le(self: Reader): number + local lo = self:u32le() + return lo + self:u32le() * TWO32 +end +function Reader.u64be(self: Reader): number + local hi = self:u32be() + return hi * TWO32 + self:u32be() +end +function Reader.i64le(self: Reader): number + local lo = self:u32le() + return lo + self:i32le() * TWO32 +end +function Reader.i64be(self: Reader): number + local hi = self:i32be() + return hi * TWO32 + self:u32be() +end + +-- floats +local function half(h: number): number + local s = if h >= 32768 then -1 else 1 + local e = bit32.band(bit32.rshift(h, 10), 31) + local m = bit32.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 +Bytes.half = half + +function Reader.f16le(self: Reader): number + return half(self:u16le()) +end +function Reader.f16be(self: Reader): number + return half(self:u16be()) +end +function Reader.f32le(self: Reader): number + local p = self.pos + if p + 4 > self.limit then + self:need(4) + return 0 + end + self.pos = p + 4 + return readf32(self.buf, p) +end +function Reader.f32be(self: Reader): number + local v = self:u32be() + writeu32(scratch, 0, v) + return readf32(scratch, 0) +end +function Reader.f64le(self: Reader): number + local p = self.pos + if p + 8 > self.limit then + self:need(8) + return 0 + end + self.pos = p + 8 + return readf64(self.buf, p) +end +function Reader.f64be(self: Reader): number + local hi = self:u32be() + local lo = self:u32be() + writeu32(scratch, 0, lo) + writeu32(scratch, 4, hi) + return readf64(scratch, 0) +end + +-- strings +function Reader.string(self: Reader, n: number): string + local p = self.pos + if n < 0 or p + n > self.limit then + self:need(n) + return "" + end + self.pos = p + n + return readstring(self.buf, p, n) +end + +-- fixed(n): an n-byte field, cut at the first NUL +function Reader.fixed(self: Reader, n: number): string + local s = self:string(n) + local z = string.find(s, "\0", 1, true) + return if z then string.sub(s, 1, z - 1) else s +end + +-- cstring(max?): bytes up to a NUL (consumed, not returned); no NUL before the end (or max bytes) records TRUNCATED +function Reader.cstring(self: Reader, max: number?): string + local p = self.pos + local e = if max then math.min(self.limit, p + max) else self.limit + local q = p + local buf = self.buf + while q < e and readu8(buf, q) ~= 0 do + q += 1 + end + if q >= e then + self.pos = e + self:need(1) + return readstring(buf, p, e - p) + end + self.pos = q + 1 + return readstring(buf, p, q - p) +end + +-- match(s) -> true (and skips s) when the next bytes are s; otherwise false, nothing consumed, no error +function Reader.match(self: Reader, s: string): boolean + local p, n = self.pos, #s + if p + n > self.limit or readstring(self.buf, p, n) ~= s then + return false + end + self.pos = p + n + return true +end + +-- peek(n, at?) -> up to n bytes as a string at the cursor (+ at), without consuming; short at the end, never an error +function Reader.peek(self: Reader, n: number, at: number?): string + local p = self.pos + (at or 0) + if p < self.base or p >= self.limit then + return "" + end + return readstring(self.buf, p, math.min(n, self.limit - p)) +end + +-- peekU8(at?) -> the byte at the cursor (+ at), or -1 past the end +function Reader.peekU8(self: Reader, at: number?): number + local p = self.pos + (at or 0) + if p < self.base or p >= self.limit then + return -1 + end + return readu8(self.buf, p) +end + +-- bytes(n) -> a new buffer with a copy of the next n bytes +function Reader.bytes(self: Reader, n: number): buffer + local p = self.pos + if n < 0 or p + n > self.limit then + self:need(n) + return bcreate(0) + end + local b = bcreate(n) + bcopy(b, 0, self.buf, p, n) + self.pos = p + n + return b +end + +-- slice(n) -> a Reader over the next n bytes (no copy); the parent skips them. Short data: a reader over what is +-- left, and the parent records TRUNCATED. +function Reader.slice(self: Reader, n: number): Reader + local p = self.pos + local l = math.max(0, math.min(n, self.limit - p)) + if l < n then + self:need(n) + else + self.pos = p + n + end + return setmetatable({ buf = self.buf, pos = p, base = p, limit = p + l, err = nil :: Err.Err? }, Reader) +end + +-- sub(offset, length?) -> a Reader over [offset, offset + length) relative to this reader's start (clamped), without +-- moving the cursor +function Reader.sub(self: Reader, offset: number, length: number?): Reader + local o = math.clamp(self.base + offset, self.base, self.limit) + local l = math.clamp(length or (self.limit - o), 0, self.limit - o) + return setmetatable({ buf = self.buf, pos = o, base = o, limit = o + l, err = nil :: Err.Err? }, Reader) +end + +-- ------------------------------------------------------------------------------------------------ Writer +local Writer = {} +Writer.__index = Writer + +export type Writer = typeof(setmetatable( + {} :: { + buf: buffer, + pos: number, -- bytes written (the next write offset) + }, + Writer +)) + +-- writer(capacity?) -> Writer +function Bytes.writer(capacity: number?): Writer + return setmetatable({ buf = bcreate(math.max(16, capacity or 256)), pos = 0 }, Writer) +end + +-- reserve(n): make room for n more bytes; returns the write offset (for direct buffer.write* into w.buf) +function Writer.reserve(self: Writer, n: number): number + local p = self.pos + local cap = blen(self.buf) + if p + n > cap then + local nb = bcreate(math.max(cap * 2, p + n)) + bcopy(nb, 0, self.buf, 0, p) + self.buf = nb + end + return p +end + +function Writer.tell(self: Writer): number + return self.pos +end + +function Writer.u8(self: Writer, v: number) + local p = self:reserve(1) + writeu8(self.buf, p, v) + self.pos = p + 1 +end +function Writer.u16le(self: Writer, v: number) + local p = self:reserve(2) + writeu16(self.buf, p, v) + self.pos = p + 2 +end +function Writer.u16be(self: Writer, v: number) + local p = self:reserve(2) + writeu8(self.buf, p, bit32.rshift(v, 8)) + writeu8(self.buf, p + 1, v) + self.pos = p + 2 +end +function Writer.u24le(self: Writer, v: number) + local p = self:reserve(3) + writeu16(self.buf, p, v) + writeu8(self.buf, p + 2, bit32.rshift(v, 16)) + self.pos = p + 3 +end +function Writer.u24be(self: Writer, v: number) + local p = self:reserve(3) + writeu8(self.buf, p, bit32.rshift(v, 16)) + writeu8(self.buf, p + 1, bit32.rshift(v, 8)) + writeu8(self.buf, p + 2, v) + self.pos = p + 3 +end +function Writer.u32le(self: Writer, v: number) + local p = self:reserve(4) + writeu32(self.buf, p, v) + self.pos = p + 4 +end +function Writer.u32be(self: Writer, v: number) + local p = self:reserve(4) + writeu32(self.buf, p, byteswap(v % TWO32)) + self.pos = p + 4 +end +Writer.i8 = Writer.u8 +Writer.i16le = Writer.u16le +Writer.i16be = Writer.u16be +Writer.i32le = Writer.u32le +Writer.i32be = Writer.u32be +function Writer.u64le(self: Writer, v: number) + self:u32le(v % TWO32) + self:u32le(math.floor(v / TWO32) % TWO32) +end +function Writer.u64be(self: Writer, v: number) + self:u32be(math.floor(v / TWO32) % TWO32) + self:u32be(v % TWO32) +end +Writer.i64le = Writer.u64le +Writer.i64be = Writer.u64be +function Writer.f32le(self: Writer, v: number) + local p = self:reserve(4) + writef32(self.buf, p, v) + self.pos = p + 4 +end +function Writer.f32be(self: Writer, v: number) + writef32(scratch, 0, v) + self:u32be(readu32(scratch, 0)) +end +function Writer.f64le(self: Writer, v: number) + local p = self:reserve(8) + writef64(self.buf, p, v) + self.pos = p + 8 +end +function Writer.f64be(self: Writer, v: number) + writef64(scratch, 0, v) + self:u32be(readu32(scratch, 4)) + self:u32be(readu32(scratch, 0)) +end + +function Writer.string(self: Writer, s: string) + local n = #s + local p = self:reserve(n) + writestring(self.buf, p, s) + self.pos = p + n +end +-- cstring(s): s and a NUL +function Writer.cstring(self: Writer, s: string) + self:string(s) + self:u8(0) +end +-- bytes(b, offset?, length?): copy a buffer range +function Writer.bytes(self: Writer, b: buffer, offset: number?, length: number?) + local o = offset or 0 + local n = length or (blen(b) - o) + local p = self:reserve(n) + bcopy(self.buf, p, b, o, n) + self.pos = p + n +end +function Writer.fill(self: Writer, v: number, n: number) + local p = self:reserve(n) + bfill(self.buf, p, v, n) + self.pos = p + n +end + +-- patch fields written earlier (lengths, CRCs) at an absolute offset < pos +function Writer.setU32le(self: Writer, at: number, v: number) + writeu32(self.buf, at, v) +end +function Writer.setU32be(self: Writer, at: number, v: number) + writeu32(self.buf, at, byteswap(v % TWO32)) +end +function Writer.setU16le(self: Writer, at: number, v: number) + writeu16(self.buf, at, v) +end +function Writer.setU8(self: Writer, at: number, v: number) + writeu8(self.buf, at, v) +end + +-- finish() -> a buffer of exactly the written bytes (the writer can keep going) +function Writer.finish(self: Writer): buffer + local b = bcreate(self.pos) + bcopy(b, 0, self.buf, 0, self.pos) + return b +end + +Bytes.Reader = Reader +Bytes.Writer = Writer + +return Bytes diff --git a/src/Formats/core/Crc32.luau b/src/Formats/core/Crc32.luau new file mode 100644 index 0000000..b6bf6e8 --- /dev/null +++ b/src/Formats/core/Crc32.luau @@ -0,0 +1,98 @@ +--!strict +--!native +-- core/Crc32: CRC-32 (IEEE 802.3, the zlib / gzip / zip / PNG polynomial 0xEDB88320, reflected), slice-by-8. +-- Absorbed from deflate-luau src/Deflate/Checksum.luau (same author; +-- no third-party code). Never throws: the range is clamped. +-- +-- Crc32.of(buf, offset?, length?, crc?) -> u32 (pass a previous result as crc to continue it) +-- Crc32.string(s, crc?) -> u32 +local band, bxor, rshift = bit32.band, bit32.bxor, bit32.rshift +local readu8, readu32 = buffer.readu8, buffer.readu32 + +local T0, T1, T2, T3 = table.create(256, 0), table.create(256, 0), table.create(256, 0), table.create(256, 0) +local T4, T5, T6, T7 = table.create(256, 0), table.create(256, 0), table.create(256, 0), table.create(256, 0) +for n = 0, 255 do + local c = n + for _ = 1, 8 do + if band(c, 1) ~= 0 then + c = bxor(0xEDB88320, rshift(c, 1)) + else + c = rshift(c, 1) + end + end + T0[n + 1] = c +end +for n = 0, 255 do + local c = T0[n + 1] + c = bxor(T0[band(c, 255) + 1], rshift(c, 8)) + T1[n + 1] = c + c = bxor(T0[band(c, 255) + 1], rshift(c, 8)) + T2[n + 1] = c + c = bxor(T0[band(c, 255) + 1], rshift(c, 8)) + T3[n + 1] = c + c = bxor(T0[band(c, 255) + 1], rshift(c, 8)) + T4[n + 1] = c + c = bxor(T0[band(c, 255) + 1], rshift(c, 8)) + T5[n + 1] = c + c = bxor(T0[band(c, 255) + 1], rshift(c, 8)) + T6[n + 1] = c + c = bxor(T0[band(c, 255) + 1], rshift(c, 8)) + T7[n + 1] = c +end + +-- CRC-32 of buf[off, off + len), continuing crc (default 0 = a new CRC). Values are finished CRCs (the inversion +-- happens inside), so crc(b, crc(a)) == the CRC of a .. b. +local function crc32(buf: buffer, off: number, len: number, crc: number?): number + local c = bxor(crc or 0, 0xFFFFFFFF) + local i, e = off, off + len + local e8 = e - 8 + while i <= e8 do + c = bxor(c, readu32(buf, i)) + local d = readu32(buf, i + 4) + c = bxor( + T7[band(c, 255) + 1], + T6[band(rshift(c, 8), 255) + 1], + T5[band(rshift(c, 16), 255) + 1], + T4[rshift(c, 24) + 1], + T3[band(d, 255) + 1], + T2[band(rshift(d, 8), 255) + 1], + T1[band(rshift(d, 16), 255) + 1], + T0[rshift(d, 24) + 1] + ) + i += 8 + end + local e4 = e - 4 + while i <= e4 do + c = bxor(c, readu32(buf, i)) + c = bxor(T3[band(c, 255) + 1], T2[band(rshift(c, 8), 255) + 1], T1[band(rshift(c, 16), 255) + 1], T0[rshift(c, 24) + 1]) + i += 4 + end + while i < e do + c = bxor(T0[band(bxor(c, readu8(buf, i)), 255) + 1], rshift(c, 8)) + i += 1 + end + return bxor(c, 0xFFFFFFFF) +end + +-- clamp (offset, length) to the buffer +local function range(buf: buffer, offset: number?, length: number?): (number, number) + local n = buffer.len(buf) + local o = math.clamp(offset or 0, 0, n) + return o, math.clamp(length or (n - o), 0, n - o) +end + +local Crc32 = {} + +function Crc32.of(buf: buffer, offset: number?, length: number?, crc: number?): number + local o, l = range(buf, offset, length) + return crc32(buf, o, l, crc) +end + +function Crc32.string(s: string, crc: number?): number + return crc32(buffer.fromstring(s), 0, #s, crc) +end + +-- raw(buf, off, len, crc?): no clamping, for callers that already checked the range (hot paths) +Crc32.raw = crc32 + +return Crc32 diff --git a/src/Formats/core/Err.luau b/src/Formats/core/Err.luau new file mode 100644 index 0000000..80b8373 --- /dev/null +++ b/src/Formats/core/Err.luau @@ -0,0 +1,58 @@ +--!strict +-- core/Err: the error values every decoder / encoder returns (`nil, err`; nothing in the library throws on bad data). +-- An Err is a table { code, message, offset?, format? } that prints as "png: CORRUPT at 0x1234: bad filter type 7". +-- Never throws: --!native modules may require it. +-- +-- return nil, Err.new(Err.TRUNCATED, "IDAT runs past the end", r.pos) +-- if err.code == Err.UNSUPPORTED then ... end +local Err = {} + +-- codes +Err.TRUNCATED = "TRUNCATED" -- the data ends early +Err.CORRUPT = "CORRUPT" -- the data is malformed (bad magic inside, bad table, out-of-range field) +Err.CHECKSUM = "CHECKSUM" -- a CRC / Adler / hash mismatch +Err.UNSUPPORTED = "UNSUPPORTED" -- valid data using a feature this library does not implement, or no encoder +Err.UNKNOWN_FORMAT = "UNKNOWN_FORMAT" -- no format recognised the data / name +Err.LIMIT = "LIMIT" -- over a size limit (opts.maxPixels, opts.maxBytes, ...) +Err.ARG = "ARG" -- a bad argument (wrong type, out-of-range option) +Err.IO = "IO" -- reading or writing a file failed, or the host has no file system + +export type Err = { + code: string, + message: string, + offset: number?, + format: string?, +} + +local Meta = {} +Meta.__tostring = function(e: Err): string + local s = if e.format then e.format .. ": " .. e.code else e.code + if e.offset then + s ..= string.format(" at 0x%x", e.offset) + end + return s .. ": " .. e.message +end + +-- new(code, message, offset?) -> Err +function Err.new(code: string, message: string, offset: number?): Err + return setmetatable({ code = code, message = message, offset = offset, format = nil :: string? }, Meta) :: any +end + +-- is(v) -> true when v is an Err +function Err.is(v: any): boolean + return type(v) == "table" and getmetatable(v) == Meta +end + +-- wrap(e, format) -> e with its format set (when not set yet); a string becomes a CORRUPT Err. Used by the API to +-- tag errors with the format name. +function Err.wrap(e: any, format: string?): Err + if not Err.is(e) then + e = Err.new(Err.CORRUPT, tostring(e)) + end + if e.format == nil then + e.format = format + end + return e +end + +return table.freeze(Err) diff --git a/src/Formats/core/Huffman.luau b/src/Formats/core/Huffman.luau new file mode 100644 index 0000000..5d200d8 --- /dev/null +++ b/src/Formats/core/Huffman.luau @@ -0,0 +1,306 @@ +--!strict +--!native +-- core/Huffman: canonical Huffman codes (RFC 1951 3.2.2 / JPEG Annex C order) for decoders and encoders. +-- +-- Decoding tables (built by buildLsb / buildMsb) are u32 buffers, indexed by the next P bits of the stream: +-- entry = symbol * 32 + length a code of `length` <= P bits +-- entry = offset * 32 (length 0) a link: index offset + the following S bits (subtable of 2^S entries) +-- entry = 0 no code (incomplete code set): the stream is corrupt +-- so a symbol is one or two table reads. LSB tables (DEFLATE, VP8L) are indexed by bit-reversed codes, MSB tables +-- (JPEG, MPEG) by the code itself. Code lengths are 1..MAXLEN (16), symbols < 2^27. +-- The hot loops (codecs/Deflate/Inflate) inline the lookup on their own bit buffer; decodeLsb / decodeMsb do it on a +-- core/Bits reader. +-- +-- Encoding: lengths(freqs, maxLen) -> length-limited code lengths; codes(lengths) -> canonical code values. +-- Never throws: bad code sets return -1 / nil. +local Bits = require("@formats/core/Bits") + +local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift +local readu8, readu32, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu32 +local bfill = buffer.fill + +local MAXLEN = 16 + +local Huffman = {} +Huffman.MAXLEN = MAXLEN + +-- 8-bit reversal +local REV = table.create(256, 0) +for i = 0, 255 do + local r, v = 0, i + for _ = 1, 8 do + r = r * 2 + v % 2 + v = v // 2 + end + REV[i + 1] = r +end + +-- reverse(code, len) -> the low len bits of code reversed (len <= 16) +local function reverse(code: number, len: number): number + return rshift(bor(lshift(REV[band(code, 255) + 1], 8), REV[band(rshift(code, 8), 255) + 1]), 16 - len) +end +Huffman.reverse = reverse + +-- capacity(nsym, P, maxLen) -> the table entries (u32) needed for nsym symbols, primary width P, codes up to maxLen +function Huffman.capacity(nsym: number, P: number, maxLen: number): number + return 2 ^ P + (if maxLen > P then nsym * 2 ^ (maxLen - P) else 0) +end + +local count = table.create(MAXLEN + 1, 0) +local nextc = table.create(MAXLEN + 1, 0) + +local function build(lens: buffer, off: number, n: number, tab: buffer, P: number, msb: boolean): number + for i = 1, MAXLEN + 1 do + count[i] = 0 + end + for s = 0, n - 1 do + local l = readu8(lens, off + s) + if l > MAXLEN then + return -1 + end + count[l + 1] += 1 + end + count[1] = 0 + local left = 1 + local maxLen = 0 + for l = 1, MAXLEN do + left = left * 2 - count[l + 1] + if left < 0 then + return -1 + end + if count[l + 1] > 0 then + maxLen = l + end + end + local code = 0 + for l = 1, MAXLEN do + code = (code + count[l]) * 2 + nextc[l] = code + end + local psize = lshift(1, P) + bfill(tab, 0, 0, psize * 4) + local S = if maxLen > P then maxLen - P else 0 + local ssize = lshift(1, S) + local nextSub = psize + for s = 0, n - 1 do + local l = readu8(lens, off + s) + if l > 0 then + local c = nextc[l] + nextc[l] = c + 1 + local entry = s * 32 + l + if l <= P then + if msb then + -- the code is the top l bits of the P-bit index: fill every completion of the low bits + local first = lshift(c, P - l) + local last = first + lshift(1, P - l) - 1 + for i = first, last do + writeu32(tab, i * 4, entry) + end + else + local step = lshift(1, l) + local i = reverse(c, l) + while i < psize do + writeu32(tab, i * 4, entry) + i += step + end + end + else + local pre, rest + if msb then + pre = rshift(c, l - P) + rest = band(c, lshift(1, l - P) - 1) + else + local rev = reverse(c, l) + pre = band(rev, psize - 1) + rest = rshift(rev, P) + end + local e = readu32(tab, pre * 4) + local sub + if e == 0 then + sub = nextSub + nextSub += ssize + bfill(tab, sub * 4, 0, ssize * 4) + writeu32(tab, pre * 4, sub * 32) + else + sub = rshift(e, 5) + end + local k = l - P -- bits of the code in the subtable index + if msb then + local first = lshift(rest, S - k) + for i = first, first + lshift(1, S - k) - 1 do + writeu32(tab, (sub + i) * 4, entry) + end + else + local step = lshift(1, k) + local i = rest + while i < ssize do + writeu32(tab, (sub + i) * 4, entry) + i += step + end + end + end + end + end + return S +end + +-- buildLsb(lens, off, n, tab, P) -> S: a table for the code lengths lens[off .. off + n - 1] (u8), indexed by the next +-- P bits LSB-first (bit-reversed codes). S = the subtable width (0 when no code is longer than P), -1 = an +-- over-subscribed or invalid code set. tab must hold capacity(n, P, maxLen) u32 entries. +function Huffman.buildLsb(lens: buffer, off: number, n: number, tab: buffer, P: number): number + return build(lens, off, n, tab, P, false) +end + +-- buildMsb(lens, off, n, tab, P) -> S: the same, indexed by the next P bits MSB-first +function Huffman.buildMsb(lens: buffer, off: number, n: number, tab: buffer, P: number): number + return build(lens, off, n, tab, P, true) +end + +-- decodeLsb(br, tab, P, S) -> symbol, or -1 for an invalid code (br: a core/Bits LSB reader) +function Huffman.decodeLsb(br: Bits.BitReader, tab: buffer, P: number, S: number): number + local e = readu32(tab, br:peek(P) * 4) + local l = band(e, 31) + if l == 0 then + if e == 0 then + return -1 + end + local idx = br:peek(P + S) + e = readu32(tab, (rshift(e, 5) + rshift(idx, P)) * 4) + l = band(e, 31) + if l == 0 then + return -1 + end + end + br:skip(l) + return rshift(e, 5) +end + +-- decodeMsb(br, tab, P, S) -> symbol, or -1 (br: a core/Bits MSB reader) +function Huffman.decodeMsb(br: Bits.BitReader, tab: buffer, P: number, S: number): number + local e = readu32(tab, br:peek(P) * 4) + local l = band(e, 31) + if l == 0 then + if e == 0 then + return -1 + end + local idx = br:peek(P + S) + e = readu32(tab, (rshift(e, 5) + band(idx, lshift(1, S) - 1)) * 4) + l = band(e, 31) + if l == 0 then + return -1 + end + end + br:skip(l) + return rshift(e, 5) +end + +-- codes(lengths) -> canonical code values (MSB-first, as written by an MSB writer; reverse() them for LSB streams). +-- lengths: { number } indexed 1..n (symbol + 1), 0 = unused. +function Huffman.codes(lengths: { number }): { number } + local cnt = table.create(MAXLEN + 1, 0) + for _, l in lengths do + if l > 0 then + cnt[l + 1] += 1 + end + end + local nxt = table.create(MAXLEN + 1, 0) + local code = 0 + for l = 1, MAXLEN do + code = (code + cnt[l]) * 2 + nxt[l + 1] = code + end + local out = table.create(#lengths, 0) + for i, l in lengths do + if l > 0 then + out[i] = nxt[l + 1] + nxt[l + 1] += 1 + end + end + return out +end + +-- lengths(freqs, maxLen) -> code lengths ({ number }, same indexing as freqs), at most maxLen bits, optimal without +-- the limit; over the limit, the JPEG Annex K.3 adjustment. A single used symbol gets length 1. +function Huffman.lengths(freqs: { number }, maxLen: number): { number } + local n = #freqs + local out = table.create(n, 0) + -- leaves sorted by frequency (ties by symbol, for determinism) + local syms = {} + for i = 1, n do + if freqs[i] > 0 then + table.insert(syms, i) + end + end + if #syms == 0 then + return out + end + if #syms == 1 then + out[syms[1]] = 1 + return out + end + table.sort(syms, function(a: number, b: number): boolean + if freqs[a] ~= freqs[b] then + return freqs[a] < freqs[b] + end + return a < b + end) + -- two-queue Huffman: leaves (sorted) and internal nodes (created in increasing weight order) + local m = #syms + local weight = table.create(2 * m, 0) + local parent = table.create(2 * m, 0) + for i = 1, m do + weight[i] = freqs[syms[i]] + end + local li, ni, nn = 1, m + 1, m + 1 -- next leaf, next internal node to take, next free node + local function take(): number + if li <= m and (ni >= nn or weight[li] <= weight[ni]) then + li += 1 + return li - 1 + end + ni += 1 + return ni - 1 + end + for _ = 1, m - 1 do + local a = take() + local b = take() + weight[nn] = weight[a] + weight[b] + parent[a] = nn + parent[b] = nn + nn += 1 + end + -- depths: the root is nn - 1 + local depth = table.create(2 * m, 0) + for i = nn - 2, 1, -1 do + depth[i] = depth[parent[i]] + 1 + end + -- count codes per length; limit (JPEG K.3: move pairs from the deepest level up) + local bl = table.create(m + maxLen + 2, 0) + local deepest = 0 + for i = 1, m do + bl[depth[i]] += 1 + deepest = math.max(deepest, depth[i]) + end + for l = deepest, maxLen + 1, -1 do + while bl[l] > 0 do + local j = l - 2 + while j > 0 and bl[j] == 0 do + j -= 1 + end + bl[l] -= 2 + bl[l - 1] += 1 + bl[j + 1] += 2 + bl[j] -= 1 + end + end + -- the longest codes go to the least frequent symbols (syms is sorted ascending) + local k = 1 + for l = math.min(deepest, maxLen), 1, -1 do + for _ = 1, bl[l] do + out[syms[k]] = l + k += 1 + end + end + return out +end + +return Huffman diff --git a/src/Formats/core/Input.luau b/src/Formats/core/Input.luau new file mode 100644 index 0000000..df745fa --- /dev/null +++ b/src/Formats/core/Input.luau @@ -0,0 +1,62 @@ +--!strict +-- core/Input: turns what the caller passed (a buffer, a string of bytes, or a file path) into a buffer, reading files +-- through the host adapter the API passes in (core never requires host itself). +-- +-- local buf, err, name = Input.resolve(src, opts, host) +-- +-- A string is a path when opts.path is true, or when the host has a file system and the string looks like a path +-- (under 4 KB, no NUL / newline) and the file exists; otherwise it is the data itself (opts.data = true forces that). +-- name: the path (for the extension fallback) or opts.name. Never throws. +local Err = require("@formats/core/Err") + +local Input = {} + +export type HostLike = { + hasFiles: boolean, + readFile: (path: string) -> (buffer?, Err.Err?), + exists: (path: string) -> boolean, +} + +-- looksLikePath(s) -> true for short strings without NUL / newline bytes +function Input.looksLikePath(s: string): boolean + return #s > 0 and #s < 4096 and not string.find(s, "\0", 1, true) and not string.find(s, "[\n\r]") +end + +-- resolve(src, opts?, host?) -> buffer, nil, name? | nil, Err +function Input.resolve(src: any, opts: any?, host: HostLike?): (buffer?, Err.Err?, string?) + local o = opts or {} + local t = type(src) + if t == "buffer" then + return src, nil, o.name + elseif t == "string" then + local isPath = false + if o.path == true then + isPath = true + elseif o.data ~= true and host and host.hasFiles and Input.looksLikePath(src) then + isPath = host.exists(src) + end + if isPath then + if not host then + return nil, Err.new(Err.IO, "no host to read " .. src), nil + end + local b, err = host.readFile(src) + if not b then + return nil, err, nil + end + return b, nil, src + end + return buffer.fromstring(src), nil, o.name + end + return nil, Err.new(Err.ARG, "expected a buffer, a string or a path, got " .. typeof(src)), nil +end + +-- extension(name) -> the lower-case extension without the dot ("png"), or nil +function Input.extension(name: string?): string? + if not name then + return nil + end + local ext = string.match(name, "%.([%w_]+)$") + return if ext then string.lower(ext) else nil +end + +return Input diff --git a/src/Formats/host/Love.luau b/src/Formats/host/Love.luau new file mode 100644 index 0000000..0ae01dc --- /dev/null +++ b/src/Formats/host/Love.luau @@ -0,0 +1,149 @@ +--!strict +-- host/Love: LÖVE 11+. Files through love.filesystem (the game folder and the save directory), falling back to io for +-- paths outside them; converts the standard types to LÖVE objects: +-- host.toImageData(img) -> love ImageData (rgba8) +-- host.fromImageData(imageData) -> Image (rgba8) +-- host.toSoundData(audio) -> love SoundData (an Audio, or a Decoder decoded to the end; 16-bit) +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") + +local Host = {} +Host.name = "love" +Host.hasFiles = true + +local function love(): any + return (_G :: any).love +end +local function io(): any + return (_G :: any).io +end +-- the FFI, when the build runs on LuaJIT (always, under LÖVE); called through _G so the build leaves it alone +local function ffi(): any + local req = (_G :: any).require + local ok, m = pcall(req, "ffi") + return if ok then m else nil +end + +function Host.readFile(path: string): (buffer?, Err.Err?) + local fs = love().filesystem + if fs.getInfo(path, "file") then + local s, msg = fs.read(path) + if type(s) ~= "string" then + return nil, Err.new(Err.IO, "cannot read " .. path .. ": " .. tostring(msg)) + end + return buffer.fromstring(s) + end + local f, msg = io().open(path, "rb") + if not f then + return nil, Err.new(Err.IO, "cannot open " .. path .. ": " .. tostring(msg)) + end + local s = f:read("*a") + f:close() + return buffer.fromstring(s) +end + +-- writeFile: relative paths go to the save directory (love.filesystem.write), absolute ones through io +function Host.writeFile(path: string, data: buffer): (boolean, Err.Err?) + local s = buffer.tostring(data) + if string.sub(path, 1, 1) ~= "/" and not string.find(path, "^%a:[/\\]") then + local ok, msg = love().filesystem.write(path, s) + if not ok then + return false, Err.new(Err.IO, "cannot write " .. path .. ": " .. tostring(msg)) + end + return true + end + local f, msg = io().open(path, "wb") + if not f then + return false, Err.new(Err.IO, "cannot create " .. path .. ": " .. tostring(msg)) + end + f:write(s) + f:close() + return true +end + +function Host.exists(path: string): boolean + if love().filesystem.getInfo(path, "file") then + return true + end + local f = io().open(path, "rb") + if f then + f:close() + return true + end + return false +end + +-- toImageData(img) -> ImageData | nil, Err +function Host.toImageData(img: any): (any, Err.Err?) + if img.format ~= "rgba8" then + return nil, Err.new(Err.ARG, "toImageData: needs rgba8 pixels, got " .. tostring(img.format)) + end + local n = img.width * img.height * 4 + local F = ffi() + local B = buffer :: any + if F and B.toffi then + local id = love().image.newImageData(img.width, img.height, "rgba8") + F.copy(id:getFFIPointer(), B.toffi(img.pixels), n) + return id + end + local bytes = love().data.newByteData(buffer.readstring(img.pixels, 0, n)) + return love().image.newImageData(img.width, img.height, "rgba8", bytes) +end + +-- fromImageData(imageData) -> Image (rgba8 copy) +function Host.fromImageData(id: any): Types.Image + local w, h = id:getDimensions() + local img = Types.Image.new(w, h, "rgba8") + local F = ffi() + local B = buffer :: any + if F and B.toffi and id:getFormat() == "rgba8" then + F.copy(B.toffi(img.pixels), id:getFFIPointer(), w * h * 4) + return img + end + local s = id:getString() + buffer.writestring(img.pixels, 0, s, math.min(#s, w * h * 4)) + return img +end + +-- toSoundData(audio) -> SoundData (16-bit). audio: an Audio, or a Decoder (decoded to the end). +function Host.toSoundData(a: any): (any, Err.Err?) + local samples, frames, channels, rate = a.samples, a.frames, a.channels, a.sampleRate + if samples == nil then + -- a Decoder: read everything + local parts, total = {}, 0 + while true do + local out, n = a:read(65536) + if n == 0 then + break + end + local copy = buffer.create(n * channels * 4) + buffer.copy(copy, 0, out, 0, n * channels * 4) + table.insert(parts, copy) + total += n + end + samples = buffer.create(total * channels * 4) + local o = 0 + for _, p in parts do + buffer.copy(samples, o, p) + o += buffer.len(p) + end + frames = total + end + local sd = love().sound.newSoundData(math.max(frames, 1), rate, 16, channels) + local count = frames * channels + local F = ffi() + if F then + local p = F.cast("int16_t*", sd:getFFIPointer()) + for i = 0, count - 1 do + local v = math.clamp(buffer.readf32(samples, i * 4), -1, 1) + p[i] = math.floor(v * 32767 + 0.5) + end + else + for i = 0, count - 1 do + sd:setSample(i, math.clamp(buffer.readf32(samples, i * 4), -1, 1)) + end + end + return sd +end + +return Host diff --git a/src/Formats/host/LuaJIT.luau b/src/Formats/host/LuaJIT.luau new file mode 100644 index 0000000..519a3ca --- /dev/null +++ b/src/Formats/host/LuaJIT.luau @@ -0,0 +1,48 @@ +--!strict +-- host/LuaJIT: plain LuaJIT (or any Lua with io): files through io.open. +local Err = require("@formats/core/Err") + +local Host = {} +Host.name = "luajit" +Host.hasFiles = true + +local function io(): any + return (_G :: any).io +end + +function Host.readFile(path: string): (buffer?, Err.Err?) + local f, msg = io().open(path, "rb") + if not f then + return nil, Err.new(Err.IO, "cannot open " .. path .. ": " .. tostring(msg)) + end + local s = f:read("*a") + f:close() + if type(s) ~= "string" then + return nil, Err.new(Err.IO, "cannot read " .. path) + end + return buffer.fromstring(s), nil +end + +function Host.writeFile(path: string, data: buffer): (boolean, Err.Err?) + local f, msg = io().open(path, "wb") + if not f then + return false, Err.new(Err.IO, "cannot create " .. path .. ": " .. tostring(msg)) + end + local ok, werr = f:write(buffer.tostring(data)) + f:close() + if not ok then + return false, Err.new(Err.IO, "cannot write " .. path .. ": " .. tostring(werr)) + end + return true, nil +end + +function Host.exists(path: string): boolean + local f = io().open(path, "rb") + if f then + f:close() + return true + end + return false +end + +return Host diff --git a/src/Formats/host/Luau.luau b/src/Formats/host/Luau.luau new file mode 100644 index 0000000..e16ea19 --- /dev/null +++ b/src/Formats/host/Luau.luau @@ -0,0 +1,21 @@ +--!strict +-- host/Luau: the Luau CLI (and any embedding without io): no file system. Sources are buffers or strings. +local Err = require("@formats/core/Err") + +local Host = {} +Host.name = "luau" +Host.hasFiles = false + +function Host.readFile(path: string): (buffer?, Err.Err?) + return nil, Err.new(Err.IO, "no file system on this host (luau): pass a buffer or a string, not the path " .. path) +end + +function Host.writeFile(path: string, _data: buffer): (boolean, Err.Err?) + return false, Err.new(Err.IO, "no file system on this host (luau): cannot write " .. path) +end + +function Host.exists(_path: string): boolean + return false +end + +return Host diff --git a/src/Formats/host/Roblox.luau b/src/Formats/host/Roblox.luau new file mode 100644 index 0000000..461c09f --- /dev/null +++ b/src/Formats/host/Roblox.luau @@ -0,0 +1,40 @@ +--!strict +-- host/Roblox: no file system (sources are buffers or strings, e.g. from HttpService or an asset); converts the +-- standard types to engine objects: +-- host.toEditableImage(img) -> EditableImage (rgba8; other formats are converted by the caller first) +local Err = require("@formats/core/Err") + +local Host = {} +Host.name = "roblox" +Host.hasFiles = false + +function Host.readFile(path: string): (buffer?, Err.Err?) + return nil, Err.new(Err.IO, "Roblox has no file system: pass a buffer or a string, not the path " .. path) +end + +function Host.writeFile(path: string, _data: buffer): (boolean, Err.Err?) + return false, Err.new(Err.IO, "Roblox has no file system: cannot write " .. path .. " (use F.save(value) for a buffer)") +end + +function Host.exists(_path: string): boolean + return false +end + +-- toEditableImage(img) -> EditableImage | nil, Err. img.format must be "rgba8". +function Host.toEditableImage(img: any): (any, Err.Err?) + if img.format ~= "rgba8" then + return nil, Err.new(Err.ARG, "toEditableImage: needs rgba8 pixels, got " .. tostring(img.format)) + end + local AssetService = (game :: any):GetService("AssetService") + local size = Vector2.new(img.width, img.height) + local ok, ei = pcall(function() + return AssetService:CreateEditableImage({ Size = size }) + end) + if not ok or not ei then + return nil, Err.new(Err.IO, "CreateEditableImage failed: " .. tostring(ei)) + end + ei:WritePixelsBuffer(Vector2.zero, size, img.pixels) + return ei +end + +return Host diff --git a/src/Formats/host/init.luau b/src/Formats/host/init.luau new file mode 100644 index 0000000..ed78da2 --- /dev/null +++ b/src/Formats/host/init.luau @@ -0,0 +1,43 @@ +--!strict +-- host: the runtime adapter, detected once at load time. Roblox (no file system; toEditableImage), LÖVE +-- (love.filesystem + io; toImageData / toSoundData), plain LuaJIT (io), the Luau CLI (no file system). +-- +-- local host = require("@formats/host") +-- print(host.name) -- "roblox" | "love" | "luajit" | "luau" +-- local buf, err = host.readFile("a.png") -- every host has readFile / writeFile / exists (failing with Err.IO +-- -- where there is no file system) +local Err = require("@formats/core/Err") + +export type Host = { + name: string, + hasFiles: boolean, + readFile: (path: string) -> (buffer?, Err.Err?), + writeFile: (path: string, data: buffer) -> (boolean, Err.Err?), + exists: (path: string) -> boolean, + [string]: any, +} + +local G = _G :: any +local name +if typeof(game) == "Instance" then + name = "roblox" +elseif G.love ~= nil and type(G.love) == "table" and G.love.filesystem ~= nil then + name = "love" +elseif G.jit ~= nil or G.io ~= nil then + name = "luajit" +else + name = "luau" +end + +local host: Host +if name == "roblox" then + host = require("@formats/host/Roblox") +elseif name == "love" then + host = require("@formats/host/Love") +elseif name == "luajit" then + host = require("@formats/host/LuaJIT") +else + host = require("@formats/host/Luau") +end +local _ = Err +return host diff --git a/src/Formats/image/png/Decode.luau b/src/Formats/image/png/Decode.luau new file mode 100644 index 0000000..ce12b8f --- /dev/null +++ b/src/Formats/image/png/Decode.luau @@ -0,0 +1,253 @@ +--!strict +--!native +--!optimize 2 +-- image/png/Decode: the PNG pixel stage. Undo the per-row filters (none / sub / up / average / Paeth) in place in the +-- inflated image data, then expand every colour type and bit depth to RGBA8, for one image or the 7 Adam7 passes. +-- Absorbed from png-luau src/Png/Decode.luau (same author). +-- +-- The caller (init) has validated the header and checked that the data holds at least the expected number of +-- bytes, so every index here is in range. A bad filter type returns false, message: nothing in this module throws. +local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift +local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32 +local bcopy = buffer.copy + +local Decode = {} + +-- Adam7: x0, y0, dx, dy per pass +local PASSES = { + { 0, 0, 8, 8 }, + { 4, 0, 8, 8 }, + { 0, 4, 4, 8 }, + { 2, 0, 4, 4 }, + { 0, 2, 2, 4 }, + { 1, 0, 2, 2 }, + { 0, 1, 1, 2 }, +} +Decode.PASSES = PASSES + +local CHANNELS = { [0] = 1, [2] = 3, [3] = 1, [4] = 2, [6] = 4 } +Decode.CHANNELS = CHANNELS + +-- bytes per row (without the filter byte) for a pass width +function Decode.rowBytes(pw: number, channels: number, depth: number): number + return (pw * channels * depth + 7) // 8 +end + +-- Unfilter ph rows of rb bytes starting at raw[p] (each row: a filter byte, then rb bytes). bpp: bytes per +-- complete pixel (at least 1). Returns true, or false + the bad filter type. +local function unfilter(raw: buffer, p: number, ph: number, rb: number, bpp: number): (boolean, number) + local stride = rb + 1 + for r = 0, ph - 1 do + local f = readu8(raw, p) + local cur = p + 1 + if f == 0 then + -- none + elseif f == 1 then + for i = cur + bpp, cur + rb - 1 do + writeu8(raw, i, readu8(raw, i) + readu8(raw, i - bpp)) + end + elseif f == 2 then + if r > 0 then + local i = cur + local e4 = cur + rb - 4 + while i <= e4 do + -- four bytes at once: add without carries between the byte lanes + local x, y = readu32(raw, i), readu32(raw, i - stride) + local lo = band(x, 0x7F7F7F7F) + band(y, 0x7F7F7F7F) + writeu32(raw, i, bit32.bxor(lo, band(bit32.bxor(x, y), 0x80808080))) + i += 4 + end + while i < cur + rb do + writeu8(raw, i, readu8(raw, i) + readu8(raw, i - stride)) + i += 1 + end + end + elseif f == 3 then + if r > 0 then + for i = cur, cur + bpp - 1 do + writeu8(raw, i, readu8(raw, i) + rshift(readu8(raw, i - stride), 1)) + end + for i = cur + bpp, cur + rb - 1 do + writeu8(raw, i, readu8(raw, i) + rshift(readu8(raw, i - bpp) + readu8(raw, i - stride), 1)) + end + else + for i = cur + bpp, cur + rb - 1 do + writeu8(raw, i, readu8(raw, i) + rshift(readu8(raw, i - bpp), 1)) + end + end + elseif f == 4 then + if r > 0 then + -- the first pixel: a = c = 0, so Paeth picks b + for i = cur, cur + bpp - 1 do + writeu8(raw, i, readu8(raw, i) + readu8(raw, i - stride)) + end + for i = cur + bpp, cur + rb - 1 do + local a = readu8(raw, i - bpp) + local b = readu8(raw, i - stride) + local c = readu8(raw, i - stride - bpp) + local pa = math.abs(b - c) + local pb = math.abs(a - c) + local pc = math.abs(a + b - c - c) + local v + if pa <= pb and pa <= pc then + v = a + elseif pb <= pc then + v = b + else + v = c + end + writeu8(raw, i, readu8(raw, i) + v) + end + else + -- no previous row: Paeth is sub + for i = cur + bpp, cur + rb - 1 do + writeu8(raw, i, readu8(raw, i) + readu8(raw, i - bpp)) + end + end + else + return false, f + end + p += stride + end + return true, 0 +end + +-- Expand one unfiltered row (pw pixels at raw[ro]) to RGBA8 at out[oo], oo stepping by ostep bytes. +-- pal: 256 RGBA8 entries (index -> u32 little-endian RGBA). tr: the tRNS key for grey / RGB (-1 if none), +-- as a sample value (grey) or r * 2^32 + g * 2^16 + b (RGB), at the image's bit depth. +local function convert(raw: buffer, ro: number, pw: number, out: buffer, oo: number, ostep: number, ct: number, depth: number, pal: buffer, tr: number) + if ct == 6 then + if depth == 8 then + if ostep == 4 then + bcopy(out, oo, raw, ro, pw * 4) + else + for x = 0, pw - 1 do + writeu32(out, oo + x * ostep, readu32(raw, ro + x * 4)) + end + end + else + for x = 0, pw - 1 do + local s = ro + x * 8 + local o = oo + x * ostep + writeu8(out, o, readu8(raw, s)) + writeu8(out, o + 1, readu8(raw, s + 2)) + writeu8(out, o + 2, readu8(raw, s + 4)) + writeu8(out, o + 3, readu8(raw, s + 6)) + end + end + elseif ct == 2 then + if depth == 8 then + for x = 0, pw - 1 do + local s = ro + x * 3 + local r, g, b = readu8(raw, s), readu8(raw, s + 1), readu8(raw, s + 2) + local a = 255 + if tr >= 0 and r * 4294967296 + g * 65536 + b == tr then + a = 0 + end + writeu32(out, oo + x * ostep, r + g * 256 + b * 65536 + a * 16777216) + end + else + for x = 0, pw - 1 do + local s = ro + x * 6 + local r = readu8(raw, s) * 256 + readu8(raw, s + 1) + local g = readu8(raw, s + 2) * 256 + readu8(raw, s + 3) + local b = readu8(raw, s + 4) * 256 + readu8(raw, s + 5) + local a = 255 + if tr >= 0 and r * 4294967296 + g * 65536 + b == tr then + a = 0 + end + writeu32(out, oo + x * ostep, rshift(r, 8) + band(g, 0xFF00) + lshift(rshift(b, 8), 16) + a * 16777216) + end + end + elseif ct == 3 then + if depth == 8 then + for x = 0, pw - 1 do + writeu32(out, oo + x * ostep, readu32(pal, readu8(raw, ro + x) * 4)) + end + else + local per = 8 // depth + local mask = lshift(1, depth) - 1 + for x = 0, pw - 1 do + local byte = readu8(raw, ro + x // per) + local idx = band(rshift(byte, 8 - depth - (x % per) * depth), mask) + writeu32(out, oo + x * ostep, readu32(pal, idx * 4)) + end + end + elseif ct == 0 then + if depth == 8 then + for x = 0, pw - 1 do + local v = readu8(raw, ro + x) + local a = if v == tr then 0 else 255 + writeu32(out, oo + x * ostep, v * 0x10101 + a * 16777216) + end + elseif depth == 16 then + for x = 0, pw - 1 do + local hi = readu8(raw, ro + x * 2) + local v = hi * 256 + readu8(raw, ro + x * 2 + 1) + local a = if v == tr then 0 else 255 + writeu32(out, oo + x * ostep, hi * 0x10101 + a * 16777216) + end + else + local per = 8 // depth + local mask = lshift(1, depth) - 1 + local scale = 255 // mask + for x = 0, pw - 1 do + local byte = readu8(raw, ro + x // per) + local v = band(rshift(byte, 8 - depth - (x % per) * depth), mask) + local a = if v == tr then 0 else 255 + writeu32(out, oo + x * ostep, v * scale * 0x10101 + a * 16777216) + end + end + else -- ct == 4: grey + alpha + if depth == 8 then + for x = 0, pw - 1 do + local v, a = readu8(raw, ro + x * 2), readu8(raw, ro + x * 2 + 1) + writeu32(out, oo + x * ostep, v * 0x10101 + a * 16777216) + end + else + for x = 0, pw - 1 do + local v, a = readu8(raw, ro + x * 4), readu8(raw, ro + x * 4 + 2) + writeu32(out, oo + x * ostep, v * 0x10101 + a * 16777216) + end + end + end +end + +-- Decode the inflated data raw (at least the expected size) of a w x h image to out (w * h * 4 bytes, RGBA8). +-- Returns true, or false + message. +function Decode.run(raw: buffer, w: number, h: number, depth: number, ct: number, interlace: number, pal: buffer, tr: number, out: buffer): (boolean, string?) + local channels = CHANNELS[ct] + local bpp = math.max(1, (channels * depth) // 8) + local p = 0 + if interlace == 0 then + local rb = Decode.rowBytes(w, channels, depth) + local ok, f = unfilter(raw, 0, h, rb, bpp) + if not ok then + return false, "bad filter type " .. f + end + for y = 0, h - 1 do + convert(raw, y * (rb + 1) + 1, w, out, y * w * 4, 4, ct, depth, pal, tr) + end + return true, nil + end + for _, pass in PASSES do + local x0, y0, dx, dy = pass[1], pass[2], pass[3], pass[4] + local pw = if w > x0 then (w - x0 + dx - 1) // dx else 0 + local ph = if h > y0 then (h - y0 + dy - 1) // dy else 0 + if pw > 0 and ph > 0 then + local rb = Decode.rowBytes(pw, channels, depth) + local ok, f = unfilter(raw, p, ph, rb, bpp) + if not ok then + return false, "bad filter type " .. f + end + for r = 0, ph - 1 do + local y = y0 + r * dy + convert(raw, p + r * (rb + 1) + 1, pw, out, (y * w + x0) * 4, dx * 4, ct, depth, pal, tr) + end + p += ph * (rb + 1) + end + end + return true, nil +end + +return Decode diff --git a/src/Formats/image/png/Encode.luau b/src/Formats/image/png/Encode.luau new file mode 100644 index 0000000..d3f261d --- /dev/null +++ b/src/Formats/image/png/Encode.luau @@ -0,0 +1,162 @@ +--!strict +--!native +--!optimize 2 +-- image/png/Encode: the PNG encoder's pixel stage. Picks the smallest lossless colour type for rgba8 pixels and +-- writes the filtered scanlines (a filter byte + the row), choosing each row's filter by the minimum sum of absolute +-- signed residuals (the libpng heuristic). Nothing here throws: the caller (init) validated the image. +local readu8, writeu8 = buffer.readu8, buffer.writeu8 +local bcreate, bcopy = buffer.create, buffer.copy + +local Encode = {} + +local CHANNELS = { [0] = 1, [2] = 3, [4] = 2, [6] = 4 } + +-- pickColorType(px, w, h) -> "rgba" | "rgb" | "graya" | "gray" +function Encode.pickColorType(px: buffer, w: number, h: number): string + local opaque, gray = true, true + for i = 0, w * h - 1 do + local o = i * 4 + local r, g, b, a = readu8(px, o), readu8(px, o + 1), readu8(px, o + 2), readu8(px, o + 3) + if a ~= 255 then + opaque = false + end + if r ~= g or g ~= b then + gray = false + end + if not opaque and not gray then + return "rgba" + end + end + if gray then + return if opaque then "gray" else "graya" + end + return "rgb" +end + +-- convert rgba8 to the colour type's packed rows (no filter bytes) +local function pack(px: buffer, w: number, h: number, ct: number): buffer + local ch = CHANNELS[ct] + if ch == 4 then + return px + end + local out = bcreate(w * h * ch) + local n = w * h + if ct == 2 then + for i = 0, n - 1 do + bcopy(out, i * 3, px, i * 4, 3) + end + elseif ct == 0 then + for i = 0, n - 1 do + writeu8(out, i, readu8(px, i * 4)) + end + else -- graya + for i = 0, n - 1 do + writeu8(out, i * 2, readu8(px, i * 4)) + writeu8(out, i * 2 + 1, readu8(px, i * 4 + 3)) + end + end + return out +end + +local function paeth(a: number, b: number, c: number): number + local pa = math.abs(b - c) + local pb = math.abs(a - c) + local pc = math.abs(a + b - c - c) + if pa <= pb and pa <= pc then + return a + elseif pb <= pc then + return b + end + return c +end + +-- the five filter costs (sums of |signed residual|) of the row at s (rb bytes; previous row at s - rb unless first); +-- the arithmetic is inlined: this runs for every byte +local function costs(src: buffer, s: number, rb: number, bpp: number, first: boolean): (number, number, number, number, number) + local c0, c1, c2, c3, c4 = 0, 0, 0, 0, 0 + local p = s - rb + for i = 0, rb - 1 do + local x = readu8(src, s + i) + local a = if i >= bpp then readu8(src, s + i - bpp) else 0 + local b, c = 0, 0 + if not first then + b = readu8(src, p + i) + if i >= bpp then + c = readu8(src, p + i - bpp) + end + end + local d = if x < 128 then x else 256 - x + c0 += d + d = (x - a) % 256 + c1 += if d < 128 then d else 256 - d + d = (x - b) % 256 + c2 += if d < 128 then d else 256 - d + d = (x - (a + b) // 2) % 256 + c3 += if d < 128 then d else 256 - d + local pa, pb, pc = math.abs(b - c), math.abs(a - c), math.abs(a + b - c - c) + local pr = if pa <= pb and pa <= pc then a elseif pb <= pc then b else c + d = (x - pr) % 256 + c4 += if d < 128 then d else 256 - d + end + return c0, c1, c2, c3, c4 +end + +-- write the row at s filtered with f to out[o + 1 ..] (out[o] = f) +local function apply(src: buffer, s: number, rb: number, bpp: number, first: boolean, f: number, out: buffer, o: number) + writeu8(out, o, f) + o += 1 + if f == 0 or (f == 2 and first) then + bcopy(out, o, src, s, rb) + return + end + local p = s - rb + for i = 0, rb - 1 do + local x = readu8(src, s + i) + local a = if i >= bpp then readu8(src, s + i - bpp) else 0 + local pred + if f == 1 then + pred = a + elseif f == 2 then + pred = readu8(src, p + i) + elseif f == 3 then + pred = (a + (if first then 0 else readu8(src, p + i))) // 2 + elseif first then + pred = a + else + local c = if i >= bpp then readu8(src, p + i - bpp) else 0 + pred = paeth(a, readu8(src, p + i), c) + end + writeu8(out, o + i, x - pred) + end +end + +-- filter(px, w, h, ct) -> the filtered scanlines (h * (1 + rowBytes)); each row's filter: the minimum sum of +-- |signed residuals| (the libpng heuristic) +function Encode.filter(px: buffer, w: number, h: number, ct: number): buffer + local ch = CHANNELS[ct] + local src = pack(px, w, h, ct) + local rb = w * ch + local out = bcreate(h * (rb + 1)) + for y = 0, h - 1 do + local s = y * rb + local first = y == 0 + local c0, c1, c2, c3, c4 = costs(src, s, rb, ch, first) + local best, bc = 0, c0 + if c1 < bc then + best, bc = 1, c1 + end + if c2 < bc then + best, bc = 2, c2 + end + if c3 < bc then + best, bc = 3, c3 + end + if c4 < bc then + best = 4 + end + apply(src, s, rb, ch, first, best, out, y * (rb + 1)) + end + return out +end + +return Encode diff --git a/src/Formats/image/png/init.luau b/src/Formats/image/png/init.luau new file mode 100644 index 0000000..f29ea0f --- /dev/null +++ b/src/Formats/image/png/init.luau @@ -0,0 +1,306 @@ +--!strict +-- image/png: PNG (ISO/IEC 15948, W3C PNG 3rd ed.). Absorbed from png-luau 1.0.0 (same author) + a new encoder. +-- Supports: decode of every colour type (grey, RGB, palette, grey + alpha, RGBA) at every bit depth (1, 2, 4, 8, 16), +-- PLTE / tRNS transparency, the five filters, Adam7, tEXt; encode of rgba8 to RGBA / RGB / grey / grey + alpha +-- (chosen automatically) with adaptive filters. Decodes to rgba8 (16-bit samples keep their high byte). +-- Not supported: APNG animation (the default image is decoded), colour management (gAMA / cHRM / sRGB / iCCP are +-- ignored; iCCP is kept raw-compressed in meta.iccCompressed), palette / 16-bit / interlaced output. + +-- ------------------------------------------------------------------------------------------------ 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 Types = require("@formats/Types") +local Decode = require("@formats/image/png/Decode") +local Encode = require("@formats/image/png/Encode") + +-- ------------------------------------------------------------------------------------------------ contract +local Png = { + name = "png", + category = "image", + extensions = { "png", "apng" }, + mime = { "image/png", "image/apng" }, + deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/Deflate", "Types" }, + caps = { decode = true, encode = true, animation = false, alpha = true, depths = { 1, 2, 4, 8, 16 } }, +} + +export type DecodeOptions = { + checkCrc: boolean?, -- verify every chunk's CRC-32 (default false) + maxPixels: number?, -- refuse larger images (default 2^26 = 64 Mpixel, a 256 MB RGBA buffer) +} +export type EncodeOptions = { + level: number?, -- deflate level 0..9 (default 6) + colorType: ("auto" | "rgba" | "rgb" | "gray" | "graya")?, -- default "auto": the smallest lossless one +} + +-- ------------------------------------------------------------------------------------------------ constants +local SIGNATURE = "\137PNG\r\n\26\n" +local VALID = { + [0] = { [1] = true, [2] = true, [4] = true, [8] = true, [16] = true }, + [2] = { [8] = true, [16] = true }, + [3] = { [1] = true, [2] = true, [4] = true, [8] = true }, + [4] = { [8] = true, [16] = true }, + [6] = { [8] = true, [16] = true }, +} +local COLOR_NAMES = { [0] = "gray", [2] = "rgb", [3] = "palette", [4] = "graya", [6] = "rgba" } + +local readu8, readu32 = buffer.readu8, buffer.readu32 +local function be32(b: buffer, o: number): number + return bit32.byteswap(readu32(b, o)) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Png.sniff(r: Bytes.Reader): number + return if r:peek(8) == SIGNATURE then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Header = { width: number, height: number, bitDepth: number, colorType: number, interlace: number } + +-- the IHDR at r's start: Header | nil, Err +local function header(r: Bytes.Reader): (Header?, Err.Err?) + local b, o, n = r.buf, r.base, r.limit - r.base + if n < 8 or readu8(b, o) ~= 137 or buffer.readstring(b, o, 8) ~= SIGNATURE then + return nil, Err.new(Err.CORRUPT, "bad signature", o) + end + if n < 33 or buffer.readstring(b, o + 12, 4) ~= "IHDR" or be32(b, o + 8) ~= 13 then + return nil, Err.new(Err.CORRUPT, "missing IHDR", o + 8) + end + local h = { + width = be32(b, o + 16), + height = be32(b, o + 20), + bitDepth = readu8(b, o + 24), + colorType = readu8(b, o + 25), + interlace = readu8(b, o + 28), + } + if h.width == 0 or h.height == 0 or h.width >= 2 ^ 31 or h.height >= 2 ^ 31 then + return nil, Err.new(Err.CORRUPT, "bad image size", o + 16) + end + local depths = VALID[h.colorType] + if not depths then + return nil, Err.new(Err.CORRUPT, "bad colour type " .. h.colorType, o + 25) + end + if not depths[h.bitDepth] then + return nil, Err.new(Err.CORRUPT, string.format("bad bit depth %d for colour type %d", h.bitDepth, h.colorType), o + 24) + end + if readu8(b, o + 26) ~= 0 or readu8(b, o + 27) ~= 0 or h.interlace > 1 then + return nil, Err.new(Err.UNSUPPORTED, "unknown compression, filter or interlace method", o + 26) + end + return h, nil +end + +-- info(r) -> { width, height, bitDepth, colorType, interlace } | nil, Err (reads only the header) +function Png.info(r: Bytes.Reader): (Header?, Err.Err?) + return header(r) +end + +function Png.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local checkCrc = opts and opts.checkCrc or false + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + local h, herr = header(r) + if not h then + return nil, herr + end + local w, ht, depth, ct = h.width, h.height, h.bitDepth, h.colorType + 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, n = r.buf, r.limit + -- chunks + local pal = buffer.create(1024) + for i = 0, 255 do + buffer.writeu32(pal, i * 4, 0xFF000000) -- out-of-range indexes: opaque black + end + local palCount = 0 + local tr = -1 + local idat: { { number } } = {} + local idatLen = 0 + local text: { [string]: string } = {} + local iccCompressed: buffer? = nil + local p = r.base + 8 + local first = true + while p + 12 <= n do + local len = be32(b, p) + local typ = buffer.readstring(b, p + 4, 4) + if len > n - p - 12 then + return nil, Err.new(Err.TRUNCATED, "chunk " .. typ .. " runs past the end", p) + end + local d = p + 8 + if checkCrc then + local want = be32(b, d + len) + if Crc32.raw(b, p + 4, len + 4) ~= want then + return nil, Err.new(Err.CHECKSUM, "CRC mismatch in chunk " .. typ, d + len) + end + end + if first and typ ~= "IHDR" then + return nil, Err.new(Err.CORRUPT, "IHDR is not the first chunk", p) + end + first = false + if typ == "PLTE" then + if len % 3 ~= 0 or len > 768 or len == 0 then + return nil, Err.new(Err.CORRUPT, "bad PLTE length", p) + end + palCount = len // 3 + for i = 0, palCount - 1 do + local q = d + i * 3 + buffer.writeu32(pal, i * 4, readu8(b, q) + readu8(b, q + 1) * 256 + readu8(b, q + 2) * 65536 + 0xFF000000) + end + elseif typ == "tRNS" then + if ct == 3 then + for i = 0, math.min(len, 256) - 1 do + buffer.writeu8(pal, i * 4 + 3, readu8(b, d + i)) + end + elseif ct == 0 and len >= 2 then + tr = readu8(b, d) * 256 + readu8(b, d + 1) + elseif ct == 2 and len >= 6 then + local function u16(q: number): number + return readu8(b, d + q) * 256 + readu8(b, d + q + 1) + end + tr = u16(0) * 4294967296 + u16(2) * 65536 + u16(4) + end + elseif typ == "IDAT" then + table.insert(idat, { d, len }) + idatLen += len + elseif typ == "tEXt" then + local s = buffer.readstring(b, d, len) + local z = string.find(s, "\0", 1, true) + if z then + text[string.sub(s, 1, z - 1)] = string.sub(s, z + 1) + end + elseif typ == "iCCP" then + local cb = buffer.create(len) + buffer.copy(cb, 0, b, d, len) + iccCompressed = cb + elseif typ == "IEND" then + break -- a missing IEND is tolerated (truncated tail after the data) + elseif bit32.band(readu8(b, p + 4), 0x20) == 0 and typ ~= "IHDR" then + return nil, Err.new(Err.UNSUPPORTED, "unknown critical chunk " .. typ, p) + end + p = d + len + 4 + end + if #idat == 0 then + return nil, Err.new(Err.TRUNCATED, "no image data", p) + end + if ct == 3 and palCount == 0 then + return nil, Err.new(Err.CORRUPT, "palette image without PLTE") + end + -- the inflated size: every (pass) row has a filter byte + local channels = Decode.CHANNELS[ct] + local expected = 0 + if h.interlace == 0 then + expected = ht * (Decode.rowBytes(w, channels, depth) + 1) + else + for _, pass in Decode.PASSES do + local x0, y0, dx, dy = pass[1], pass[2], pass[3], pass[4] + local pw = if w > x0 then (w - x0 + dx - 1) // dx else 0 + local ph = if ht > y0 then (ht - y0 + dy - 1) // dy else 0 + if pw > 0 and ph > 0 then + expected += ph * (Decode.rowBytes(pw, channels, depth) + 1) + end + end + end + local z: buffer + if #idat == 1 then + z = b + else + z = buffer.create(idatLen) + local w0 = 0 + for _, c in idat do + buffer.copy(z, w0, b, c[1], c[2]) + w0 += c[2] + end + end + local zo, zl = if #idat == 1 then idat[1][1] else 0, idatLen + local raw, zerr = Deflate.zlib(z, zo, zl, expected) + if not raw then + -- some encoders leave extra bytes after the rows: inflate without the exact size, keep the rows + local loose = Deflate.zlib(z, zo, zl) + if not loose or buffer.len(loose) < expected then + return nil, zerr + end + raw = loose + end + local img = Types.Image.new(w, ht, "rgba8") + local ok, derr = Decode.run(raw :: buffer, w, ht, depth, ct, h.interlace, pal, tr, img.pixels) + if not ok then + return nil, Err.new(Err.CORRUPT, tostring(derr)) + end + if ct == 3 then + local palette: { { number } } = {} + for i = 0, palCount - 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 next(text) then + img.meta.text = text + end + img.meta.iccCompressed = iccCompressed + img.meta.source = { format = "png", bitDepth = depth, colorType = COLOR_NAMES[ct], interlace = h.interlace } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local CT_CODES = { gray = 0, rgb = 2, graya = 4, rgba = 6 } + +function Png.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "png encode: needs an rgba8 Image") + end + local w, h = img.width, img.height + if w < 1 or h < 1 or buffer.len(img.pixels) < w * h * 4 then + return nil, Err.new(Err.ARG, "png encode: bad image size or pixel buffer") + end + local level = opts and opts.level or 6 + if type(level) ~= "number" or level < 0 or level > 9 then + return nil, Err.new(Err.ARG, "png encode: level must be 0..9") + end + local want = opts and opts.colorType or "auto" + local ctName: string = want + if want == "auto" then + ctName = Encode.pickColorType(img.pixels, w, h) + end + local ct = CT_CODES[ctName] + if ct == nil then + return nil, Err.new(Err.ARG, "png encode: unknown colorType " .. tostring(want)) + end + local raw = Encode.filter(img.pixels, w, h, ct) + local z = Deflate.zlibCompress(raw, { level = level }) :: buffer + + local out = Bytes.writer(buffer.len(z) + 128) + local function chunk(typ: string, data: buffer?) + local len = if data then buffer.len(data) else 0 + out:u32be(len) + local start = out:tell() + out:string(typ) + if data then + out:bytes(data) + end + out:u32be(Crc32.raw(out.buf, start, len + 4)) + end + out:string(SIGNATURE) + local ihdr = Bytes.writer(13) + ihdr:u32be(w) + ihdr:u32be(h) + ihdr:u8(8) + ihdr:u8(ct) + ihdr:u8(0) + ihdr:u8(0) + ihdr:u8(0) + chunk("IHDR", ihdr:finish()) + if img.meta and img.meta.text then + for k, v in img.meta.text do + local t = Bytes.writer() + t:string(k) + t:u8(0) + t:string(v) + chunk("tEXt", t:finish()) + end + end + chunk("IDAT", z) + chunk("IEND", nil) + return out:finish(), nil +end + +return Png diff --git a/src/Formats/init.luau b/src/Formats/init.luau new file mode 100644 index 0000000..29090f1 --- /dev/null +++ b/src/Formats/init.luau @@ -0,0 +1,378 @@ +--!strict +-- Formats: read, write and convert file formats in pure Luau, on Roblox and on LuaJIT / LÖVE (through tools/build.py). +-- Every format of a category maps onto one standard type (src/Formats/Types.luau): a PNG and a WebP both load as an +-- Image. Formats are found through the generated Registry: by content (each format's sniff), then by extension. +-- +-- local F = require(Formats) -- Roblox: the ModuleScript; LuaJIT: require("formats"); luau: "@formats" +-- local img, err = F.load(src, opts?) -- src: buffer | string | path (hosts with files); err: core/Err +-- local img = F.image.load(src) -- the same, restricted to one category (F.audio, F.model, ...) +-- local dec = F.audio.open(src) -- streaming decoders (audio / video) +-- local buf = F.save(img, nil, { format = "png" }) -- a buffer; without format: the source format +-- F.save(img, "out.png") -- a file (the format from the extension), on hosts with files +-- local s = F.saveString(img, { format = "png" }) +-- local buf = F.convert(src, "png", opts?) -- load + save +-- F.formats() -- the capability list (also docs/FORMATS.md) +-- +-- Never throws on bad data or bad arguments: every function returns nil, Err (Err.code, Err.message, tostring(err)). +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Input = require("@formats/core/Input") +local Types = require("@formats/Types") +local Registry = require("@formats/Registry") +local host = require("@formats/host") + +local F = {} + +F.version = "0.1.0" +F.Err = Err +F.Types = Types +F.Bytes = Bytes +F.null = Types.null +F.host = host +F.plugins = {} :: { [string]: any } -- injected optional dependencies (plugins.brep for cad/step) + +-- value.kind -> category +local KIND_CATEGORY: { [string]: string } = { + image = "image", + audio = "audio", + scene = "model", + cad = "cad", + font = "font", + archive = "archive", + vector = "vector", + tilemap = "vector", + layered = "layered", + subtitles = "subtitle", + music = "music", + midi = "music", + playlist = "playlist", +} + +-- ------------------------------------------------------------------------------------------------ registry access +local loaded: { [string]: any } = {} + +local function module(entry: Registry.Entry): (any, Err.Err?) + local m = loaded[entry.path] + if m then + return m + end + local ok, res = pcall(entry.load) + if not ok then + return nil, Err.new(Err.UNSUPPORTED, "format " .. entry.name .. " failed to load: " .. tostring(res)) + end + loaded[entry.path] = res + return res +end + +local function inCategory(entry: Registry.Entry, category: string?): boolean + return category == nil or entry.category == category +end + +-- find(nameOrExt, category?) -> the entry whose name, then whose extension, matches +local function find(key: string, category: string?): Registry.Entry? + local k = string.lower(key) + for _, e in Registry do + if e.name == k and inCategory(e, category) then + return e + end + end + for _, e in Registry do + if inCategory(e, category) and table.find(e.extensions, k) then + return e + end + end + return nil +end + +-- detect(buf, name?, category?, format?) -> entry | nil, Err: opts.format, else the best sniff, else the extension +local function detect(buf: buffer, name: string?, category: string?, format: string?): (Registry.Entry?, Err.Err?) + if format then + local e = find(format, category) + if not e then + return nil, Err.new(Err.UNKNOWN_FORMAT, "no format named " .. format .. (if category then " in " .. category else "")) + end + return e + end + local ext = Input.extension(name) + local best: Registry.Entry? = nil + local bestScore = 0 + for _, e in Registry do + if inCategory(e, category) and (e.caps.decode or e.caps.open) then + local m = module(e) + if m and m.sniff then + local ok, score = pcall(m.sniff, Bytes.reader(buf)) + if ok and type(score) == "number" and score > 0 then + if ext and table.find(e.extensions, ext) then + score += 0.01 -- ties go to the extension + end + if score > bestScore then + best, bestScore = e, score + end + end + end + end + end + if best then + return best + end + if ext then + local e = find(ext, category) + if e then + return e + end + end + return nil, Err.new(Err.UNKNOWN_FORMAT, "unrecognised data" .. (if name then " (" .. name .. ")" else "") .. (if category then " for " .. category else "")) +end + +local function tag(value: any, formatName: string) + if type(value) == "table" then + local meta = value.meta + if type(meta) == "table" then + if meta.source == nil then + meta.source = { format = formatName } + elseif type(meta.source) == "table" and meta.source.format == nil then + meta.source.format = formatName + end + end + end +end + +-- full decode through a streaming decoder (audio formats with open but no decode) +local function drain(dec: any): any + local channels = dec.channels + local parts, total = {}, 0 + while true do + local out, n = dec:read(65536) + if not out or n == 0 then + break + end + local copy = buffer.create(n * channels * 4) + buffer.copy(copy, 0, out, 0, n * channels * 4) + table.insert(parts, copy) + total += n + end + local a = Types.Audio.new(dec.sampleRate, channels, total) + local o = 0 + for _, p in parts do + buffer.copy(a.samples, o, p) + o += buffer.len(p) + end + a.tags = dec.tags or {} + return a +end + +-- ------------------------------------------------------------------------------------------------ API +export type Options = { [string]: any } -- format (name or extension), category, path, data, name, + format options + +-- load(src, opts?) -> value | nil, Err +function F.load(src: any, opts: Options?): (any, Err.Err?) + local o = opts or {} + local buf, ierr, name = Input.resolve(src, o, host) + if not buf then + return nil, ierr + end + local entry, derr = detect(buf, name, o.category, o.format) + if not entry then + return nil, derr + end + local m, merr = module(entry) + if not m then + return nil, merr + end + local value, err + if m.decode then + local ok, v, e = pcall(m.decode, Bytes.reader(buf), o) + if not ok then + return nil, Err.wrap(Err.new(Err.CORRUPT, "decoder threw: " .. tostring(v)), entry.name) + end + value, err = v, e + elseif m.open then + local ok, dec, e = pcall(m.open, Bytes.reader(buf), o) + if not ok then + return nil, Err.wrap(Err.new(Err.CORRUPT, "decoder threw: " .. tostring(dec)), entry.name) + end + if dec then + value = drain(dec) + end + err = e + else + return nil, Err.wrap(Err.new(Err.UNSUPPORTED, "no decoder"), entry.name) + end + if value == nil then + return nil, Err.wrap(err or Err.new(Err.CORRUPT, "decode failed"), entry.name) + end + tag(value, entry.name) + return value +end + +-- open(src, opts?) -> a streaming decoder (audio Decoder / VideoDecoder / Demuxer) | nil, Err +function F.open(src: any, opts: Options?): (any, Err.Err?) + local o = opts or {} + local buf, ierr, name = Input.resolve(src, o, host) + if not buf then + return nil, ierr + end + local entry, derr = detect(buf, name, o.category, o.format) + if not entry then + return nil, derr + end + local m, merr = module(entry) + if not m then + return nil, merr + end + if not m.open then + return nil, Err.wrap(Err.new(Err.UNSUPPORTED, "no streaming decoder (use load)"), entry.name) + end + local ok, dec, e = pcall(m.open, Bytes.reader(buf), o) + if not ok then + return nil, Err.wrap(Err.new(Err.CORRUPT, "decoder threw: " .. tostring(dec)), entry.name) + end + if dec == nil then + return nil, Err.wrap(e or Err.new(Err.CORRUPT, "open failed"), entry.name) + end + return dec +end + +-- 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 category = o.category + if category == nil and type(value) == "table" and type(value.kind) == "string" then + category = KIND_CATEGORY[value.kind] + end + local key = o.format or Input.extension(dest) + if key == nil and type(value) == "table" and type(value.meta) == "table" and type(value.meta.source) == "table" then + key = value.meta.source.format + end + if key == nil then + return nil, nil, Err.new(Err.ARG, "save: no format (pass opts.format or a destination with an extension)") + end + local entry = find(key, category) + if not entry then + return nil, nil, Err.new(Err.UNKNOWN_FORMAT, "no format named " .. key .. (if category then " for " .. category else "")) + end + local m, merr = module(entry) + if not m then + return nil, nil, merr + end + if not m.encode then + local alt = nil + for _, e in Registry do + if e.category == entry.category and e.caps.encode then + alt = e.name + break + end + 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 +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) + if not entry then + return nil, err + end + local ok, buf, e = pcall(m.encode, value, o) + if not ok then + return nil, Err.wrap(Err.new(Err.ARG, "encoder threw: " .. tostring(buf)), entry.name) + end + if buf == nil then + return nil, Err.wrap(e or Err.new(Err.ARG, "encode failed"), entry.name) + end + if dest then + local wok, werr = host.writeFile(dest, buf) + if not wok then + return nil, werr + end + return true + end + return buf +end + +-- saveString(value, opts?) -> string | nil, Err +function F.saveString(value: any, opts: Options?): (string?, Err.Err?) + local buf, err = F.save(value, nil, opts) + if not buf then + return nil, err + end + return buffer.tostring(buf) +end + +-- convert(src, format, opts?) -> buffer (or true with opts.out = a path) | nil, Err. opts go to both load and save. +function F.convert(src: any, format: string, opts: Options?): (any, Err.Err?) + local o = opts or {} + local value, err = F.load(src, o) + if value == nil then + return nil, err + end + local so = table.clone(o) + so.format = format + so.category = nil + return F.save(value, o.out, so) +end + +-- detect(src, opts?) -> format name | nil, Err +function F.detect(src: any, opts: Options?): (string?, Err.Err?) + local o = opts or {} + local buf, ierr, name = Input.resolve(src, o, host) + if not buf then + return nil, ierr + end + local entry, err = detect(buf, name, o.category, o.format) + if not entry then + return nil, err + end + return entry.name +end + +export type FormatInfo = { name: string, category: string, extensions: { string }, mime: { string }, caps: { [string]: any } } + +-- formats(category?) -> { FormatInfo } (no format module is loaded) +function F.formats(category: string?): { FormatInfo } + local out = {} + for _, e in Registry do + if inCategory(e, category) then + table.insert(out, { name = e.name, category = e.category, extensions = e.extensions, mime = e.mime, caps = e.caps }) + end + end + return out +end + +-- format(name) -> the format module itself (its contract table: sniff / decode / encode / extras such as png.info) +function F.format(name: string): (any, Err.Err?) + local e = find(name) + if not e then + return nil, Err.new(Err.UNKNOWN_FORMAT, "no format named " .. name) + end + return module(e) +end + +-- ------------------------------------------------------------------------------------------------ category facades +-- F.image.load / save / open / formats, F.audio..., F.model... : the same calls restricted to one category +local function with(opts: Options?, category: string): Options + local o = if opts then table.clone(opts) else {} + o.category = category + return o +end +for category in Types.CATEGORIES do + local cat: string = category + F[cat] = { + load = function(src: any, opts: Options?): (any, Err.Err?) + return F.load(src, with(opts, cat)) + end, + open = function(src: any, opts: Options?): (any, Err.Err?) + return F.open(src, with(opts, cat)) + end, + save = function(value: any, dest: string?, opts: Options?): (any, Err.Err?) + return F.save(value, dest, with(opts, cat)) + end, + formats = function(): { FormatInfo } + return F.formats(cat) + end, + } +end +F.data.null = Types.null + +return F diff --git a/tests/T.luau b/tests/T.luau new file mode 100644 index 0000000..b92063e --- /dev/null +++ b/tests/T.luau @@ -0,0 +1,127 @@ +--!strict +-- tests/T: the test helper every tests/**/*.luau uses, under both runtimes (luau --codegen -O2 and LuaJIT through the +-- build). A failed check throws, so the runner (tools/test.sh) sees a non-zero exit. +-- +-- local T = require("@tests/T") +-- local t = T.suite("png") +-- t:check(cond, "label") -- truthy +-- t:eq(got, want, "label") -- ==, with both values in the message +-- t:fuzz("decode", function(b) return Png.decode(Bytes.reader(b)) end, samples) -- the no-throw pass +-- t:done() -- prints "png: 123 checks passed (luajit)" +local T = {} + +T.runtime = if (_G :: any).jit ~= nil then "luajit" else "luau" + +-- deterministic LCG (the same numbers on both runtimes): rand(n) -> 0 .. n - 1 +function T.rng(seed: number): (n: number) -> number + local s = seed % 2147483648 + return function(n: number): number + s = (s * 1103515245 + 12345) % 2147483648 + return s % n + end +end + +-- bytes({ 1, 2, 3 }) -> buffer +function T.bytes(t: { number }): buffer + local b = buffer.create(#t) + for i, v in t do + buffer.writeu8(b, i - 1, v) + end + return b +end + +-- hex(buf, max?) -> "89 50 4e 47 ..." +function T.hex(b: buffer, max: number?): string + local n = math.min(buffer.len(b), max or 64) + local out = table.create(n) + for i = 0, n - 1 do + out[i + 1] = string.format("%02x", buffer.readu8(b, i)) + end + return table.concat(out, " ") .. (if buffer.len(b) > n then " ..." else "") +end + +-- clock() -> seconds (os.clock on both runtimes) +function T.clock(): number + return os.clock() +end + +local Suite = {} +Suite.__index = Suite + +export type Suite = typeof(setmetatable({} :: { name: string, passed: number, t0: number }, Suite)) + +function T.suite(name: string): Suite + return setmetatable({ name = name, passed = 0, t0 = os.clock() }, Suite) +end + +function Suite.check(self: Suite, cond: any, label: string) + if not cond then + error(string.format("FAILED [%s, %s]: %s", self.name, T.runtime, label), 2) + end + self.passed += 1 +end + +function Suite.eq(self: Suite, got: any, want: any, label: string) + if got ~= want then + error(string.format("FAILED [%s, %s]: %s: got %s, want %s", self.name, T.runtime, label, tostring(got), tostring(want)), 2) + end + self.passed += 1 +end + +-- note(fmt, ...): an indented progress line +function Suite.note(_self: Suite, fmt: string, ...: any) + print(" " .. string.format(fmt, ...)) +end + +-- fuzz(label, decode, samples, opts?): the no-throw pass every format test runs. For each sample (buffer or string): +-- truncations at several cuts, opts.mutations (default 8) copies with 1..4 random bytes changed, plus +-- opts.garbage (default 200) random buffers. decode(buf) may return anything except throw. Returns the counts. +function Suite.fuzz(self: Suite, label: string, decode: (buffer) -> any, samples: { any }, opts: { mutations: number?, garbage: number?, seed: number?, keepHeader: number? }?): (number, number) + local o: { mutations: number?, garbage: number?, seed: number?, keepHeader: number? } = opts or {} + local rand = T.rng(o.seed or 1234) + local tries, threw = 0, 0 + local function try(b: buffer, what: string) + tries += 1 + local ok, err = pcall(decode, b) + if not ok then + threw += 1 + print(string.format(" THREW on %s (%s): %s", what, label, tostring(err))) + end + end + local keep = o.keepHeader or 0 + for _, s in samples do + local str = if type(s) == "string" then s else buffer.tostring(s) + local n = #str + for _, cut in { 1, 2, 4, 8, 16, 33, n // 3, n // 2, n - 13, n - 4, n - 1 } do + if cut > 0 and cut < n then + try(buffer.fromstring(string.sub(str, 1, cut)), "truncation") + end + end + if n > keep then + for _ = 1, o.mutations or 8 do + local b = buffer.fromstring(str) + for _ = 1, 1 + rand(4) do + buffer.writeu8(b, keep + rand(n - keep), rand(256)) + end + try(b, "mutation") + end + end + end + for _ = 1, o.garbage or 200 do + local n = rand(300) + local b = buffer.create(n) + for k = 0, n - 1 do + buffer.writeu8(b, k, rand(256)) + end + try(b, "garbage") + end + self:check(threw == 0, label .. ": bad input never throws (" .. threw .. " of " .. tries .. " threw)") + self:note("%s: %d bad inputs, none threw", label, tries) + return tries, threw +end + +function Suite.done(self: Suite) + print(string.format("%s: %d checks passed (%s, %.2f s)", self.name, self.passed, T.runtime, os.clock() - self.t0)) +end + +return T diff --git a/tests/api.luau b/tests/api.luau new file mode 100644 index 0000000..00647cd --- /dev/null +++ b/tests/api.luau @@ -0,0 +1,132 @@ +-- API tests (src/Formats/init.luau): load / save / saveString / convert / open / detect / formats / format, the +-- category facades, sniff-then-extension detection, errors as Err values (never a throw), and file paths on hosts with +-- a file system (LuaJIT: a temporary file; the luau CLI has none). +local T = require("@tests/T") +local F = require("@formats") +local Err = require("@formats/core/Err") + +local t = T.suite("api") + +local function image(w: number, h: number): any + local img = F.Types.Image.new(w, h) + for i = 0, w * h * 4 - 1 do + buffer.writeu8(img.pixels, i, (i * 37) % 256) + end + return img +end + +-- host +t:eq(F.host.name, if T.runtime == "luajit" then "luajit" else "luau", "host detected") + +-- formats() +do + local all = F.formats() + t:check(#all >= 1, "formats() lists the registry") + local png + for _, f in all do + if f.name == "png" then + png = f + end + end + t:check(png and png.category == "image" and png.caps.encode and table.find(png.extensions, "png"), "png in formats()") + t:eq(#F.image.formats(), #F.formats("image"), "facade formats()") + t:eq(#F.formats("nonexistent"), 0, "unknown category") + t:check(F.format("png") and F.format("png").name == "png", "format(name)") + t:check(F.format("apng") and F.format("apng").name == "png", "format(extension)") + local _, e = F.format("nope") + t:check(e and e.code == Err.UNKNOWN_FORMAT, "format(unknown)") +end + +-- save -> load round trip through buffers and strings +do + local img = image(7, 5) + local buf, err = F.save(img, nil, { format = "png" }) + t:check(buf and type(buf) == "buffer", "save to a buffer: " .. tostring(err)) + local back = F.load(buf) + t:check(back and back.kind == "image" and back.width == 7 and back.height == 5, "load sniffs png") + t:eq(buffer.tostring(back.pixels), buffer.tostring(img.pixels), "pixels round trip") + t:eq(back.meta.source.format, "png", "meta.source.format") + -- save without a format: the source format + local again = F.save(back) + t:check(again and type(again) == "buffer", "save uses the source format") + local s = F.saveString(back) + t:check(type(s) == "string" and string.sub(s, 2, 4) == "PNG", "saveString") + local fromString = F.load(s) + t:check(fromString and fromString.width == 7, "load a string of bytes") + t:check(F.image.load(buf) ~= nil, "F.image.load") + t:eq(F.detect(buf), "png", "detect") + local conv = F.convert(s, "png", { level = 1 }) + t:check(conv and F.load(conv).width == 7, "convert") + -- format options reach the encoder + local stored = F.save(img, nil, { format = "png", level = 0 }) :: buffer + t:check(buffer.len(stored) > buffer.len(buf :: buffer), "opts.level reaches the encoder") +end + +-- detection: sniff beats the extension; the extension is the fallback; category restrictions +do + local png = F.save(image(2, 2), nil, { format = "png" }) :: buffer + t:eq(F.detect(png, { name = "photo.jpg" }), "png", "content beats a wrong extension") + local _, e = F.load("not an image at all") + t:check(e and e.code == Err.UNKNOWN_FORMAT, "unknown data: " .. tostring(e)) + local _, e2 = F.load(png, { category = "audio" }) + t:check(e2 and e2.code == Err.UNKNOWN_FORMAT, "png is not audio") + local _, e3 = F.audio.load(png) + t:check(e3 and e3.code == Err.UNKNOWN_FORMAT, "facade restricts the category") + -- forced format on bad data: the format's error, tagged with its name + local _, e4 = F.load("garbage!", { format = "png" }) + t:check(e4 and e4.format == "png" and e4.code == Err.CORRUPT, "forced format error: " .. tostring(e4)) + t:check(string.find(tostring(e4), "^png: ") ~= nil, "error message names the format") + local _, e5 = F.load("x", { format = "nope" }) + t:check(e5 and e5.code == Err.UNKNOWN_FORMAT, "unknown forced format") +end + +-- errors are values, never throws +do + local ok, v, e = pcall(F.load, 42 :: any) + t:check(ok and v == nil and e.code == Err.ARG, "load(42)") + local ok2, v2, e2 = pcall(F.save, image(1, 1)) + t:check(ok2 and v2 == nil and e2.code == Err.ARG, "save without a format") + local ok3, _, e3 = pcall(F.save, { kind = "image" } :: any, nil, { format = "png" }) + t:check(ok3 and e3 and e3.code == Err.ARG, "save of a broken image") + local ok4, _, e4 = pcall(F.save, image(1, 1), nil, { format = "nope" }) + t:check(ok4 and e4.code == Err.UNKNOWN_FORMAT, "save to an unknown format") + local _, e5 = F.open(F.save(image(1, 1), nil, { format = "png" })) + t:check(e5 and e5.code == Err.UNSUPPORTED, "open() of a non-streaming format") + t:fuzz("F.load", function(b: buffer) + return F.load(b) + end, { F.saveString(image(9, 4), { format = "png" }) :: string }, { mutations = 20 }) +end + +-- files (hosts with a file system) +if F.host.hasFiles then + local path = os.tmpname() .. ".png" + local img = image(3, 3) + local ok, err = F.save(img, path) + t:check(ok == true, "save to a path (format from the extension): " .. tostring(err)) + local back = F.load(path) + t:check(back and buffer.tostring(back.pixels) == buffer.tostring(img.pixels), "load from a path") + t:check(F.image.load(path) ~= nil, "facade load from a path") + local _, e = F.load("/nonexistent/dir/x.png", { path = true }) + t:check(e and e.code == Err.IO, "missing file is Err.IO") + os.remove(path) +else + local _, e = F.save(image(1, 1), "out.png") + t:check(e and e.code == Err.IO, "no file system: save to a path is Err.IO") + local _, e2 = F.load("x.png", { path = true }) + t:check(e2 and e2.code == Err.IO, "no file system: load of a path is Err.IO") +end + +-- Types constructors +do + local T2 = F.Types + t:eq(buffer.len(T2.Image.new(3, 2, "rgb8").pixels), 18, "Image.new rgb8") + t:eq(buffer.len(T2.Image.new(3, 3, "yuv420p").pixels), 9 + 2 * 4, "Image.new yuv420p") + local a = T2.Audio.new(8000, 2, 100) + t:check(a.kind == "audio" and buffer.len(a.samples) == 800, "Audio.new") + local sc = T2.Scene.fromPrimitive({ attributes = {}, mode = "triangles" }) + t:check(sc.kind == "scene" and #sc.nodes == 1 and sc.nodes[1].mesh == 1, "Scene.fromPrimitive") + t:eq(tostring(F.null), "null", "null sentinel") + t:check(F.data.null == F.null, "F.data.null") +end + +t:done() diff --git a/tests/codecs/deflate.luau b/tests/codecs/deflate.luau new file mode 100644 index 0000000..19f9814 --- /dev/null +++ b/tests/codecs/deflate.luau @@ -0,0 +1,172 @@ +-- codecs/Deflate tests: every fixture case (Python zlib, levels 0-9, every strategy, small windows, flushes, gzip +-- headers, multi-member gzip) decodes; exact-size mode; checksum vectors; the compressor round-trips every corpus at +-- every level (and its zlib / gzip framing); truncated / corrupted / random input returns nil, Err and never throws. +-- Ported from deflate-luau tests/inflate.luau. Fixtures: tools/fixtures/deflate.py. +local T = require("@tests/T") +local Deflate = require("@formats/codecs/Deflate") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/deflate") + +local t = T.suite("deflate") + +local function decode(kind: string, b: buffer, ...: any): (buffer?, any) + if kind == "raw" then + return Deflate.inflate(b, ...) + elseif kind == "zlib" then + return Deflate.zlib(b, ...) + else + return Deflate.gunzip(b, ...) + end +end + +-- checksum vectors +t:eq(Deflate.crc32("123456789"), 0xCBF43926, "crc32 check value") +t:eq(Deflate.crc32(""), 0, "crc32 empty") +t:eq(Deflate.adler32("Wikipedia"), 0x11E60398, "adler32 Wikipedia") +t:eq(Deflate.adler32(""), 1, "adler32 empty") +do + local s = string.rep("The quick brown fox jumps over the lazy dog. ", 400) + local b = buffer.fromstring(s) + local whole = Deflate.crc32(b) + local part = Deflate.crc32(b, 0, 1001) + t:eq(Deflate.crc32(b, 1001, nil, part), whole, "crc32 continuation") + local a = Deflate.adler32(b, 0, 7000) + t:eq(Deflate.adler32(b, 7000, nil, a), Deflate.adler32(b), "adler32 continuation") + t:eq(Deflate.crc32(b, 3, 17), Deflate.crc32(string.sub(s, 4, 20)), "crc32 range") +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, err = decode(c.kind, b) + t:check(out ~= nil, c.name .. ": " .. tostring(err)) + t:check(buffer.tostring(out :: buffer) == want, c.name .. ": output differs") + nbytes += #want + if c.kind == "raw" then + t:eq(err, #c.data, c.name .. ": consumed") + -- exact size, and a wrong exact size + local o2 = Deflate.inflate(b, 0, nil, #want) + t:check(o2 and buffer.tostring(o2) == want, c.name .. ": exact size") + if #want > 0 then + t:check(Deflate.inflate(b, 0, nil, #want - 1) == nil, c.name .. ": too small exact size fails") + end + t:check(Deflate.inflate(b, 0, nil, #want + 1) == nil, c.name .. ": too large exact size fails") + -- the same stream inside a bigger buffer, at an offset, with trailing bytes + local big = buffer.create(#c.data + 13) + buffer.fill(big, 0, 0xAB) + buffer.copy(big, 5, b) + local o3, e3 = Deflate.inflate(big, 5, #c.data + 8) + t:check(o3 and buffer.tostring(o3) == want and e3 == 5 + #c.data, c.name .. ": at an offset") + elseif c.kind == "zlib" then + t:eq(err, #c.data, c.name .. ": zlib consumed") + end +end +t:note("%d fixture streams, %.1f MB decoded", #Fx.cases, nbytes / 1e6) + +-- strings are accepted +t:check(buffer.tostring((Deflate.zlib(Fx.cases[25].data))) == Fx.corpora[Fx.cases[25].corpus], "string input") + +-- corrupted checksums +do + local z + for _, c in Fx.cases do + if c.kind == "zlib" and #Fx.corpora[c.corpus] > 100 then + z = c + break + end + end + local b = buffer.fromstring(z.data) + buffer.writeu8(b, buffer.len(b) - 1, bit32.bxor(buffer.readu8(b, buffer.len(b) - 1), 1)) + local out, err = Deflate.zlib(b) + t:check(out == nil and Err.is(err) and err.code == Err.CHECKSUM, "zlib adler mismatch: " .. tostring(err)) + for _, c in Fx.cases do + if c.kind == "gzip" and #Fx.corpora[c.corpus] > 100 then + local g = buffer.fromstring(c.data) + local n = buffer.len(g) + buffer.writeu8(g, n - 6, bit32.bxor(buffer.readu8(g, n - 6), 0x40)) + local o, e = Deflate.gunzip(g) + t:check(o == nil and e and e.code == Err.CHECKSUM, c.name .. ": gzip crc mismatch: " .. tostring(e)) + break + end + end +end + +-- hand-made streams +do + local bytes = T.bytes + -- stored block "hi" then a fixed block with only end-of-block + local o = Deflate.inflate(bytes({ 0x00, 0x02, 0x00, 0xFD, 0xFF, 0x68, 0x69, 0x03, 0x00 })) + t:check(o and buffer.tostring(o) == "hi", "stored + fixed EOB") + t:check(Deflate.inflate(bytes({ 0x01, 0x02, 0x00, 0xFC, 0xFF, 0x68, 0x69 })) == nil, "stored NLEN mismatch") + t:check(Deflate.inflate(bytes({ 0x07 })) == nil, "block type 3") + local _, e0 = Deflate.inflate(bytes({})) + t:check(e0 and e0.code == Err.TRUNCATED, "empty input is TRUNCATED: " .. tostring(e0)) + -- fixed block: a match before any output (distance too far back) + local _, e = Deflate.inflate(bytes({ 0x03, 0x02, 0x00 })) + t:check(e ~= nil and e.code == Err.CORRUPT, "distance too far back: " .. tostring(e)) + t:check(Deflate.zlib(bytes({ 0x78, 0x9c })) == nil, "zlib truncated header") + t:check(Deflate.zlib(bytes({ 0x78, 0x9d, 0x03, 0, 0, 0, 0, 1 })) == nil, "zlib FCHECK") + t:check(Deflate.gunzip(bytes({ 0x1f, 0x8c, 8, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0 })) == nil, "gzip magic") + local ok, r1, r2 = pcall(Deflate.inflate, 5 :: any) + t:check(ok and r1 == nil and r2.code == Err.ARG, "a non-buffer argument returns Err.ARG") + local ok2, _, r3 = pcall(Deflate.inflate, "abc", -1) + t:check(ok2 and r3.code == Err.ARG, "a bad offset returns Err.ARG") +end + +-- the compressor: every corpus, every level, raw / zlib / gzip; ratio against Python zlib -6 +do + local total, comp6, ref6 = 0, 0, 0 + for name, data in Fx.corpora do + local b = buffer.fromstring(data) + for level = 0, 9 do + local z, err = Deflate.compress(b, { level = level }) + t:check(z, name .. ": compress level " .. level .. ": " .. tostring(err)) + local back, berr = Deflate.inflate(z :: buffer) + t:check(back and buffer.tostring(back) == data, string.format("%s: level %d round trip: %s", name, level, tostring(berr))) + if level == 6 then + comp6 += buffer.len(z :: buffer) + total += #data + end + end + local zl = Deflate.zlibCompress(data) :: buffer + local back = Deflate.zlib(zl) + t:check(back and buffer.tostring(back) == data, name .. ": zlibCompress round trip") + local gz = Deflate.gzip(data, { level = 9 }) :: buffer + local back2 = Deflate.gunzip(gz) + t:check(back2 and buffer.tostring(back2) == data, name .. ": gzip round trip") + end + for _, c in Fx.cases do + if c.name == c.corpus .. "/zlib6" then + ref6 += #c.data - 6 + end + end + t:note("compress -6: %d -> %d bytes (%.1f%%); Python zlib -6: %d bytes", total, comp6, 100 * comp6 / total, ref6) + t:check(comp6 < ref6 * 1.25, "level 6 within 25% of zlib") + local _, e = Deflate.compress("x", { level = 11 }) + t:check(e and e.code == Err.ARG, "bad level returns Err.ARG") +end + +-- truncation, corruption and garbage never throw +do + local samples = {} + local kinds = {} + for i, c in Fx.cases do + if i % 9 == 0 and #c.data > 8 then + table.insert(samples, c.data) + kinds[c.data] = c.kind + end + end + t:fuzz("inflate", function(b: buffer) + return Deflate.inflate(b) + end, samples, { mutations = 6, garbage = 3000 }) + t:fuzz("zlib", function(b: buffer) + return Deflate.zlib(b) + end, samples, { mutations = 3, garbage = 300 }) + t:fuzz("gunzip", function(b: buffer) + return Deflate.gunzip(b) + end, samples, { mutations = 3, garbage = 300 }) +end + +t:done() diff --git a/tests/compat.luau b/tests/compat.luau new file mode 100644 index 0000000..6576b84 --- /dev/null +++ b/tests/compat.luau @@ -0,0 +1,275 @@ +-- compat tests: the Luau semantics the library relies on, checked under both runtimes. Under luau these pin down what +-- Luau does; under LuaJIT they check compat/luajit.lua (bit32, buffer, table / math / string / utf8 additions, typeof) +-- and tools/build.py's lowering (generalized iteration, if-expression chains, continue, compound assignment, string +-- interpolation, floor division, number literals). +local T = require("@tests/T") + +local t = T.suite("compat") + +-- ------------------------------------------------------------------------------------------------ bit32 +do + t:eq(bit32.band(0xFFFFFFFF, 0x0F0F0F0F), 0x0F0F0F0F, "band unsigned") + t:eq(bit32.band(-1), 0xFFFFFFFF, "band(-1)") + t:eq(bit32.band(), 0xFFFFFFFF, "band()") + t:eq(bit32.band(2 ^ 32 + 3, 7), 3, "band reduces mod 2^32") + t:eq(bit32.band(0xFF, 0xF0, 0x3C), 0x30, "band 3 args") + t:eq(bit32.band(0xFF, 0xF0, 0x3C, 0x20, 0x20), 0x20, "band 5 args") + t:eq(bit32.bor(0x80000000, 1), 0x80000001, "bor high bit") + t:eq(bit32.bor(), 0, "bor()") + t:eq(bit32.bor(1, 2, 4, 8, 16), 31, "bor 5 args") + t:eq(bit32.bxor(0xFFFFFFFF, 0x12345678), 0xEDCBA987, "bxor") + t:eq(bit32.bxor(1, 2, 4, 8, 16, 32, 64, 128, 256, 512), 1023, "bxor 10 args") + t:eq(bit32.bnot(0), 0xFFFFFFFF, "bnot") + t:eq(bit32.bnot(0xFFFFFFFF), 0, "bnot all") + t:eq(bit32.lshift(1, 31), 0x80000000, "lshift 31") + t:eq(bit32.lshift(1, 32), 0, "lshift 32") + t:eq(bit32.lshift(0xFFFFFFFF, 4), 0xFFFFFFF0, "lshift drops high bits") + t:eq(bit32.lshift(1, -1), 0, "lshift negative") + t:eq(bit32.lshift(8, -2), 2, "lshift negative = rshift") + t:eq(bit32.rshift(0x80000000, 31), 1, "rshift logical") + t:eq(bit32.rshift(0xFFFFFFFF, 0), 0xFFFFFFFF, "rshift 0 stays unsigned") + t:eq(bit32.rshift(2, -1), 4, "rshift negative = lshift") + t:eq(bit32.rshift(5, 40), 0, "rshift 40") + t:eq(bit32.arshift(0x80000000, 4), 0xF8000000, "arshift sign fill") + t:eq(bit32.arshift(0x80000000, 40), 0xFFFFFFFF, "arshift >= 32") + t:eq(bit32.lrotate(0x80000001, 1), 3, "lrotate") + t:eq(bit32.rrotate(3, 1), 0x80000001, "rrotate") + t:eq(bit32.extract(0xF0, 4, 4), 15, "extract") + t:eq(bit32.extract(0x80000000, 31), 1, "extract 1 bit") + t:eq(bit32.replace(0, 5, 4, 3), 80, "replace") + t:eq(bit32.countlz(1), 31, "countlz") + t:eq(bit32.countlz(0), 32, "countlz 0") + t:eq(bit32.countrz(8), 3, "countrz") + t:eq(bit32.countrz(0), 32, "countrz 0") + t:eq(bit32.byteswap(0x01020304), 0x04030201, "byteswap") + t:eq(bit32.byteswap(0x000000FF), 0xFF000000, "byteswap high") + t:check(bit32.btest(6, 2) and not bit32.btest(4, 2), "btest") +end + +-- ------------------------------------------------------------------------------------------------ buffer +do + local b = buffer.create(16) + t:eq(buffer.len(b), 16, "len") + t:eq(buffer.readu32(b, 12), 0, "zero-filled") + buffer.writeu32(b, 0, 0xDEADBEEF) + t:eq(buffer.readu32(b, 0), 0xDEADBEEF, "u32 round trip") + t:eq(buffer.readu8(b, 0), 0xEF, "little-endian") + t:eq(buffer.readu16(b, 2), 0xDEAD, "u16") + t:eq(buffer.readi8(b, 3), -34, "i8 sign") + t:eq(buffer.readi16(b, 2), 0xDEAD - 65536, "i16 sign") + t:eq(buffer.readi32(b, 0), 0xDEADBEEF - 2 ^ 32, "i32 sign") + buffer.writeu8(b, 0, 300) + t:eq(buffer.readu8(b, 0), 44, "writeu8 wraps") + buffer.writeu8(b, 0, -1) + t:eq(buffer.readu8(b, 0), 255, "writeu8 -1") + buffer.writeu8(b, 0, 3.7) + t:eq(buffer.readu8(b, 0), 3, "writeu8 truncates") + buffer.writeu8(b, 0, 255 + 255) + t:eq(buffer.readu8(b, 0), 254, "writeu8 of a sum") + buffer.writeu32(b, 4, -1) + t:eq(buffer.readu32(b, 4), 0xFFFFFFFF, "writeu32 -1") + buffer.writeu32(b, 4, 2 ^ 32 + 5) + t:eq(buffer.readu32(b, 4), 5, "writeu32 wraps") + buffer.writei16(b, 8, 40000) + t:eq(buffer.readi16(b, 8), -25536, "writei16 wraps") + buffer.writeu16(b, 8, -2) + t:eq(buffer.readu16(b, 8), 65534, "writeu16 -2") + buffer.writei32(b, 8, -5) + t:eq(buffer.readi32(b, 8), -5, "i32 round trip") + buffer.writef32(b, 0, 1.5) + t:eq(buffer.readf32(b, 0), 1.5, "f32") + buffer.writef32(b, 0, 0.1) + t:check(math.abs(buffer.readf32(b, 0) - 0.1) < 1e-8 and buffer.readf32(b, 0) ~= 0.1, "f32 rounds") + buffer.writef64(b, 8, math.pi) + t:eq(buffer.readf64(b, 8), math.pi, "f64") + local nan = buffer.readf32(buffer.fromstring("\0\0\192\127"), 0) + t:check(nan ~= nan, "f32 NaN") + -- out of bounds throws (both runtimes), and nothing is written + t:check(not pcall(buffer.readu8, b, 16), "readu8 past the end throws") + t:check(not pcall(buffer.readu8, b, -1), "readu8 at -1 throws") + t:check(not pcall(buffer.readu32, b, 13), "readu32 overlapping the end throws") + t:check(not pcall(buffer.writeu16, b, 15, 0), "writeu16 overlapping the end throws") + t:check(not pcall(buffer.readstring, b, 10, 7), "readstring past the end throws") + t:check(not pcall(buffer.copy, b, 10, b, 0, 7), "copy past the end throws") + t:check(not pcall(buffer.fill, b, 10, 0, 7), "fill past the end throws") + -- strings, NULs, copy, fill + local s = buffer.fromstring("a\0b\255c") + t:eq(buffer.len(s), 5, "fromstring with NUL") + t:eq(buffer.tostring(s), "a\0b\255c", "tostring with NUL") + t:eq(buffer.readstring(s, 1, 3), "\0b\255", "readstring") + buffer.writestring(b, 0, "hello world") + t:eq(buffer.readstring(b, 0, 11), "hello world", "writestring") + buffer.writestring(b, 0, "HELLO", 2) + t:eq(buffer.readstring(b, 0, 5), "HEllo", "writestring count") + buffer.copy(b, 2, b, 0, 6) -- overlapping (memmove) + t:eq(buffer.readstring(b, 0, 8), "HEHEllo ", "copy overlapping") + local c = buffer.create(4) + buffer.copy(c, 1, s, 2) + t:eq(buffer.readstring(c, 1, 3), "b\255c", "copy default count") + buffer.fill(c, 0, 0x41) + t:eq(buffer.tostring(c), "AAAA", "fill to the end") + buffer.fill(c, 1, 0x142, 2) + t:eq(buffer.tostring(c), "ABBA", "fill value wraps") + t:eq(buffer.len(buffer.create(0)), 0, "empty buffer") + t:eq(buffer.tostring(buffer.create(0)), "", "empty tostring") + -- readbits / writebits + local bb = buffer.create(8) + buffer.writeu32(bb, 0, 0xDEADBEEF) + t:eq(buffer.readbits(bb, 4, 12), 3054, "readbits") + t:eq(buffer.readbits(bb, 0, 32), 0xDEADBEEF, "readbits 32") + t:eq(buffer.readbits(bb, 0, 0), 0, "readbits 0") + buffer.writebits(bb, 3, 7, 0x7F) + t:eq(buffer.readu32(bb, 0), 3735928831, "writebits") + buffer.writebits(bb, 30, 20, 0xABCDE) + t:eq(buffer.readbits(bb, 30, 20), 0xABCDE, "writebits across bytes") + t:check(not pcall(buffer.readbits, bb, 60, 5), "readbits past the end throws") + -- big buffers (LuaJIT: calloc'd memory) + local big = buffer.create(1000000) + buffer.writeu32(big, 999996, 0x01020304) + t:eq(buffer.readu32(big, 999996), 0x01020304, "big buffer") + t:eq(buffer.readu8(big, 500000), 0, "big buffer zero-filled") +end + +-- ------------------------------------------------------------------------------------------------ typeof / type +do + local b = buffer.create(1) + t:eq(typeof(b), "buffer", "typeof buffer") + t:eq(type(b), "buffer", "type buffer") + t:eq(typeof({}), "table", "typeof table") + t:eq(type(1), "number", "type number") + t:eq(typeof(nil), "nil", "typeof nil") + t:eq(typeof("s"), "string", "typeof string") +end + +-- ------------------------------------------------------------------------------------------------ table / math / string +do + local c = table.create(3, 7) + t:eq(#c, 3, "table.create size") + t:eq(c[3], 7, "table.create value") + t:eq(#table.create(5), 0, "table.create without value") + t:eq(table.find({ 5, 6, 7 }, 6), 2, "table.find") + t:eq(table.find({ 5, 6, 7 }, 8), nil, "table.find missing") + t:eq(table.find({ 5, 6, 5 }, 5, 2), 3, "table.find init") + local x = { 1, 2, a = 3 } + table.clear(x) + t:check(next(x) == nil, "table.clear") + local f = table.freeze({ 1 }) + t:check(table.isfrozen(f) and not table.isfrozen({}), "freeze / isfrozen") + local cl = table.clone({ 1, 2, k = "v" }) + t:check(cl[2] == 2 and cl.k == "v", "table.clone") + t:eq(table.unpack({ 1, 2, 3 }, 2, 3), 2, "table.unpack") + t:eq(select("#", table.unpack({ 1, 2, 3 })), 3, "table.unpack count") + local m = table.move({ 1, 2, 3 }, 1, 3, 2) + t:check(m[1] == 1 and m[2] == 1 and m[3] == 2 and m[4] == 3, "table.move overlapping") + t:eq(math.clamp(5, 0, 3), 3, "clamp high") + t:eq(math.clamp(-1, 0, 3), 0, "clamp low") + t:eq(math.sign(-3), -1, "sign") + t:eq(math.sign(0), 0, "sign 0") + t:eq(math.round(2.5), 3, "round half up") + t:eq(math.round(-2.5), -3, "round half away from zero") + t:eq(math.round(2.4), 2, "round down") + t:check(type(math.noise(0.5, 0.3, 0.1)) == "number", "noise is a number") + local parts = string.split("a,b,,c", ",") + t:check(#parts == 4 and parts[1] == "a" and parts[3] == "" and parts[4] == "c", "string.split") + t:eq(#string.split("", ","), 1, "split empty") + t:eq(#("x y z"):split(" "), 3, "split as a method") + t:eq(string.format("%5.1f|%d|%x|%s", 3.14159, 42, 255, "s"), " 3.1|42|ff|s", "string.format") + t:eq(math.floor(-3.5), -4, "floor") +end + +-- ------------------------------------------------------------------------------------------------ utf8 +do + t:eq(utf8.char(72, 228, 8364, 128512), "H\xC3\xA4\xE2\x82\xAC\xF0\x9F\x98\x80", "utf8.char") + t:eq(utf8.len("h\xC3\xA4ll\xE2\x82\xAC"), 5, "utf8.len") + local n, bad = utf8.len("a\xFFb") + t:check(n == nil and bad == 2, "utf8.len invalid") + t:eq(utf8.codepoint("\xC3\xA4"), 228, "utf8.codepoint") + t:eq(utf8.offset("h\xC3\xA4ll", 3), 4, "utf8.offset") + local cps = {} + for _, c in utf8.codes("a\xC3\xA4\xE2\x82\xAC") do + table.insert(cps, c) + end + t:check(#cps == 3 and cps[2] == 228 and cps[3] == 8364, "utf8.codes") + t:check(string.find("\xC3\xA4", utf8.charpattern) == 1, "utf8.charpattern") +end + +-- ------------------------------------------------------------------------------------------------ syntax lowering +do + -- generalized iteration: arrays (in order), dictionaries, mixed, iterator functions, nested + local order = {} + for i, v in { 10, 20, 30 } do + table.insert(order, i * 100 + v) + end + t:check(order[1] == 110 and order[2] == 220 and order[3] == 330, "for over an array, in order") + local sum = 0 + for k, v in { a = 1, b = 2, c = 3 } do + sum += v + t:check(type(k) == "string", "dict keys") + end + t:eq(sum, 6, "for over a dictionary") + local count = 0 + for _ in { 1, 2, x = 3 } do + count += 1 + end + t:eq(count, 3, "for over a mixed table visits every key") + local w = {} + for word in string.gmatch("a b c", "%a") do + table.insert(w, word) + end + t:eq(#w, 3, "for over an iterator function") + local pc = 0 + for _, _ in pairs({ 1, 2 }) do + pc += 1 + end + t:eq(pc, 2, "pairs untouched") + local empty = 0 + for _ in {} do + empty += 1 + end + t:eq(empty, 0, "for over an empty table") + -- if-expressions: chains of elseif (darklua 0.19 reverses them; build.py rewrites them) + local function grade(i: number): string + return if i <= 144 then "a" elseif i <= 256 then "b" elseif i <= 280 then "c" else "d" + end + t:check(grade(1) == "a" and grade(200) == "b" and grade(270) == "c" and grade(285) == "d", "if-expression elseif chain") + local function n3(i: number): number + return if i < 0 then -1 elseif i == 0 then 0 elseif i < 10 then 1 elseif i < 100 then 2 else 3 + end + t:check(n3(-5) == -1 and n3(0) == 0 and n3(5) == 1 and n3(50) == 2 and n3(500) == 3, "numeric elseif chain") + local function falsy(c: boolean): any + return if c then nil else false + end + t:check(falsy(true) == nil and falsy(false) == false, "if-expression with falsy branches") + local function nested(a: boolean, b: boolean): number + return if a then (if b then 1 else 2) else if b then 3 else 4 + end + t:check(nested(true, true) == 1 and nested(true, false) == 2 and nested(false, true) == 3 and nested(false, false) == 4, "nested if-expressions") + local v = 5 + local arith = if v > 3 then v * 2 else v - 1 + t:eq(arith, 10, "if-expression arithmetic") + -- continue, compound assignment, interpolation, floor division, literals + local odd = 0 + for i = 1, 10 do + if i % 2 == 0 then + continue + end + odd += i + end + t:eq(odd, 25, "continue") + local s = "a" + s ..= "b" + local n = 7 + n //= 2 + n *= 3 + n -= 1 + n ^= 2 + t:check(s == "ab" and n == 64, "compound assignment") + t:eq(`x={n} y={1 + 2}`, "x=64 y=3", "string interpolation") + t:eq(-7 // 2, -4, "floor division of a negative") + t:eq(7.5 // 2, 3, "floor division of a fraction") + t:eq(-7 % 3, 2, "modulo of a negative") + t:eq(0b1010 + 1_000 + 0xFF_FF, 10 + 1000 + 65535, "number literals") + t:eq(0x7FFFFFFF + 1, 2147483648, "no integer overflow") +end + +t:done() diff --git a/tests/core/bits.luau b/tests/core/bits.luau new file mode 100644 index 0000000..000d7dc --- /dev/null +++ b/tests/core/bits.luau @@ -0,0 +1,178 @@ +-- core/Bits and core/Huffman tests: LSB / MSB readers and writers round-trip random fields of 1..32 bits, align / +-- peek / bytePos, overrun is a sticky error; canonical codes, length-limited code lengths, LSB and MSB decoding tables +-- (with subtables) decode what the writers wrote; invalid code sets are rejected. +local T = require("@tests/T") +local Bits = require("@formats/core/Bits") +local Huffman = require("@formats/core/Huffman") +local Err = require("@formats/core/Err") + +local t = T.suite("bits") +local rand = T.rng(7) + +-- round trips +for _, kind in { "lsb", "msb" } do + local w = if kind == "lsb" then Bits.lsbWriter() else Bits.msbWriter() + local fields = {} + for i = 1, 3000 do + local n = 1 + rand(32) + local v = if n == 32 then rand(65536) * 65536 + rand(65536) else rand(2 ^ n) + fields[i] = { v, n } + w:write(v, n) + if i % 500 == 0 then + w:align() + fields[i][3] = true + end + end + local buf = w:finish() + local r = if kind == "lsb" then Bits.lsbReader(buf) else Bits.msbReader(buf) + local ok = true + for i, f in fields do + if r:peek(math.min(f[2], 24)) ~= f[1] % 2 ^ math.min(f[2], 24) and kind == "lsb" then + ok = false + end + local v = r:read(f[2]) + if v ~= f[1] then + ok = false + print(" mismatch", kind, i, v, f[1], f[2]) + break + end + if f[3] then + r:align() + end + end + t:check(ok, kind .. ": 3000 random fields round trip") + t:check(r.err == nil, kind .. ": no error") + r:read(16) + t:check(r.err and r.err.code == Err.TRUNCATED, kind .. ": overrun is TRUNCATED") +end + +-- known bit orders +do + local lsb = Bits.lsbReader(T.bytes({ 0xB4 })) -- 1011 0100 + t:eq(lsb:read(3), 4, "lsb: first field is the low bits") + t:eq(lsb:read(5), 0x16, "lsb: rest") + local msb = Bits.msbReader(T.bytes({ 0xB4 })) + t:eq(msb:read(3), 5, "msb: first field is the high bits") + t:eq(msb:read(5), 0x14, "msb: rest") + local w = Bits.msbWriter() + w:write(5, 3) + w:write(0x14, 5) + w:write(1, 1) + t:eq(T.hex(w:finish()), "b4 80", "msb writer pads with zeros") + local r = Bits.lsbReader(T.bytes({ 0xFF, 0x12, 0x34 })) + r:read(3) + t:eq(r:bytePos(), 1, "bytePos after a partial byte") + r:align() + t:eq(r:read(8), 0x12, "align then read a byte") + t:eq(r:bitsLeft(), 8, "bitsLeft") + local e = Bits.msbReader(buffer.create(0)) + t:eq(e:peek(8), 0, "peek past the end is zeros") + t:check(e.err == nil, "peek past the end is not an error") +end + +-- Huffman: canonical codes (RFC 1951 3.2.2 example) +do + local codes = Huffman.codes({ 3, 3, 3, 3, 3, 2, 4, 4 }) + local want = { 2, 3, 4, 5, 6, 0, 14, 15 } + local ok = true + for i = 1, 8 do + ok = ok and codes[i] == want[i] + end + t:check(ok, "canonical codes (RFC 1951 example)") + t:eq(Huffman.reverse(0x91, 8), 0x89, "reverse") + t:eq(Huffman.reverse(1, 3), 4, "reverse 3 bits") +end + +-- lengths: limits, Kraft equality, single symbol +local function kraft(lens: { number }): number + local s = 0 + for _, l in lens do + if l > 0 then + s += 2 ^ -l + end + end + return s +end +do + local freqs = {} + for i = 1, 40 do + freqs[i] = math.floor(1.6 ^ i) -- Fibonacci-like: unlimited depth would be ~39 + end + local lens = Huffman.lengths(freqs, 15) + local maxl = 0 + for _, l in lens do + maxl = math.max(maxl, l) + end + t:check(maxl <= 15, "length limit 15 (got " .. maxl .. ")") + t:check(math.abs(kraft(lens) - 1) < 1e-12, "complete code") + local one = Huffman.lengths({ 0, 5, 0 }, 15) + t:check(one[1] == 0 and one[2] == 1 and one[3] == 0, "a single symbol gets length 1") + local none = Huffman.lengths({ 0, 0 }, 15) + t:check(none[1] == 0 and none[2] == 0, "no symbols") + local u = Huffman.lengths({ 1, 1, 1, 1 }, 15) + t:check(u[1] == 2 and u[4] == 2, "uniform") +end + +-- decoding tables: random code sets, encode with the writer, decode through LSB and MSB tables +for trial = 1, 30 do + local nsym = 2 + rand(300) + local freqs = {} + for i = 1, nsym do + freqs[i] = if rand(4) == 0 then 0 else 1 + rand(1000) * rand(50) + end + freqs[1] += 1 + freqs[2] += 1 + local maxLen = if trial % 2 == 0 then 15 else 16 + local lens = Huffman.lengths(freqs, maxLen) + local codes = Huffman.codes(lens) + local lensBuf = buffer.create(nsym) + for i = 1, nsym do + buffer.writeu8(lensBuf, i - 1, lens[i]) + end + local P = 4 + rand(6) + local msgs = {} + for i = 1, 500 do + local s + repeat + s = rand(nsym) + until lens[s + 1] > 0 + msgs[i] = s + end + for _, kind in { "lsb", "msb" } do + local tab = buffer.create(Huffman.capacity(nsym, P, maxLen) * 4) + local S = if kind == "lsb" then Huffman.buildLsb(lensBuf, 0, nsym, tab, P) else Huffman.buildMsb(lensBuf, 0, nsym, tab, P) + t:check(S >= 0, kind .. ": table built") + local w = if kind == "lsb" then Bits.lsbWriter() else Bits.msbWriter() + for _, s in msgs do + local l = lens[s + 1] + w:write(if kind == "lsb" then Huffman.reverse(codes[s + 1], l) else codes[s + 1], l) + end + local buf = w:finish() + local r = if kind == "lsb" then Bits.lsbReader(buf) else Bits.msbReader(buf) + local ok = true + for _, s in msgs do + local got = if kind == "lsb" then Huffman.decodeLsb(r, tab, P, S) else Huffman.decodeMsb(r, tab, P, S) + if got ~= s then + ok = false + break + end + end + t:check(ok, string.format("%s trial %d: %d symbols, P=%d, decode", kind, trial, nsym, P)) + end +end + +-- invalid code sets +do + local over = T.bytes({ 1, 1, 1 }) -- three 1-bit codes + t:eq(Huffman.buildLsb(over, 0, 3, buffer.create(1024 * 4), 8), -1, "over-subscribed") + local tooLong = T.bytes({ 17, 1 }) + t:eq(Huffman.buildMsb(tooLong, 0, 2, buffer.create(1024 * 4), 8), -1, "length over 16") + local incomplete = T.bytes({ 2, 0, 0 }) -- one 2-bit code: decoding the missing ones fails + local tab = buffer.create(256 * 4) + local S = Huffman.buildMsb(incomplete, 0, 3, tab, 4) + t:check(S >= 0, "incomplete code set builds") + local r = Bits.msbReader(T.bytes({ 0xC0 })) + t:eq(Huffman.decodeMsb(r, tab, 4, S), -1, "missing code decodes to -1") +end + +t:done() diff --git a/tests/core/bytes.luau b/tests/core/bytes.luau new file mode 100644 index 0000000..6e9cf21 --- /dev/null +++ b/tests/core/bytes.luau @@ -0,0 +1,184 @@ +-- core/Bytes, core/Err, core/Crc32, core/Adler32, core/Input tests: every Reader / Writer method both endians, the +-- sticky TRUNCATED error (never a throw), sub-readers without copies, Writer growth and patching. +local T = require("@tests/T") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Crc32 = require("@formats/core/Crc32") +local Adler32 = require("@formats/core/Adler32") +local Input = require("@formats/core/Input") + +local t = T.suite("bytes") + +-- Writer -> Reader round trip of every type +do + local w = Bytes.writer(4) -- grows + w:u8(0xAB) + w:u16le(0x1234) + w:u16be(0x1234) + w:u24le(0x123456) + w:u24be(0x123456) + w:u32le(0xDEADBEEF) + w:u32be(0xDEADBEEF) + w:i8(-2) + w:i16le(-300) + w:i16be(-300) + w:i32le(-70000) + w:i32be(-70000) + w:u64le(2 ^ 40 + 7) + w:u64be(2 ^ 52 + 3) + w:i64le(-5) + w:f32le(1.5) + w:f32be(-2.25) + w:f64le(math.pi) + w:f64be(-math.pi) + w:u16le(0x3C00) -- f16 1.0 + w:u16be(0xC000) -- f16 -2.0 + w:string("abc") + w:cstring("zero") + w:string("fix\0\0\0") + w:fill(7, 3) + local mark = w:tell() + w:u32be(0) + w:setU32be(mark, 0xCAFEBABE) + local buf = w:finish() + t:eq(buffer.len(buf), w:tell(), "finish is exactly the written bytes") + local r = Bytes.reader(buf) + t:eq(r:u8(), 0xAB, "u8") + t:eq(r:u16le(), 0x1234, "u16le") + t:eq(r:u16be(), 0x1234, "u16be") + t:eq(r:u24le(), 0x123456, "u24le") + t:eq(r:u24be(), 0x123456, "u24be") + t:eq(r:u32le(), 0xDEADBEEF, "u32le") + t:eq(r:u32be(), 0xDEADBEEF, "u32be") + t:eq(r:i8(), -2, "i8") + t:eq(r:i16le(), -300, "i16le") + t:eq(r:i16be(), -300, "i16be") + t:eq(r:i32le(), -70000, "i32le") + t:eq(r:i32be(), -70000, "i32be") + t:eq(r:u64le(), 2 ^ 40 + 7, "u64le") + t:eq(r:u64be(), 2 ^ 52 + 3, "u64be") + t:eq(r:i64le(), -5, "i64le") + t:eq(r:f32le(), 1.5, "f32le") + t:eq(r:f32be(), -2.25, "f32be") + t:eq(r:f64le(), math.pi, "f64le") + t:eq(r:f64be(), -math.pi, "f64be") + t:eq(r:f16le(), 1, "f16le") + t:eq(r:f16be(), -2, "f16be") + t:eq(r:string(3), "abc", "string") + t:eq(r:cstring(), "zero", "cstring") + t:eq(r:fixed(6), "fix", "fixed") + t:eq(r:u8() + r:u8() + r:u8(), 21, "fill") + t:eq(r:u32be(), 0xCAFEBABE, "patched field") + t:check(r:eof() and r.err == nil, "consumed everything, no error") + t:eq(Bytes.half(0x7C00), math.huge, "f16 infinity") + t:check(Bytes.half(0x7E00) ~= Bytes.half(0x7E00), "f16 NaN") + t:eq(Bytes.half(0x0001), 2 ^ -24, "f16 subnormal") +end + +-- sticky errors: reads past the end return 0 / "" and set err once, never throw +do + local r = Bytes.reader(buffer.fromstring("\1\2\3")) + t:eq(r:u16le(), 0x0201, "read within") + t:eq(r:u32le(), 0, "short read returns 0") + t:check(r.err and r.err.code == Err.TRUNCATED, "TRUNCATED") + t:eq(r.err.offset, 2, "error offset is where the read started") + local first = r.err + t:eq(r:u8(), 0, "reads after the error return 0") + t:eq(r:string(5), "", "string after the error") + t:check(r.err == first, "the first error sticks") + t:check(r:eof(), "cursor at the end") + local r2 = Bytes.reader(buffer.fromstring("abc")) + t:check(not r2:seek(4) and r2.err ~= nil, "seek past the end fails") + local r3 = Bytes.reader(buffer.fromstring("abc")) + t:eq(r3:cstring(), "abc", "unterminated cstring returns what there is") + t:check(r3.err and r3.err.code == Err.TRUNCATED, "unterminated cstring is TRUNCATED") + local r4 = Bytes.reader(buffer.fromstring("abcd")) + local nilv, e = r4:fail(Err.CORRUPT, "bad thing") + t:check(nilv == nil and e.code == Err.CORRUPT and tostring(e) == "CORRUPT at 0x0: bad thing", "fail(): " .. tostring(e)) + t:check(not r4:need(5) and r4.err == e, "need keeps the first error") + -- every method on an empty reader: no throw + local empty = Bytes.reader(buffer.create(0)) + for _, m in { "u8", "i8", "u16le", "u16be", "i16le", "i16be", "u24le", "u24be", "u32le", "u32be", "i32le", "i32be", "u64le", "u64be", "i64le", "i64be", "f16le", "f16be", "f32le", "f32be", "f64le", "f64be", "cstring" } do + local ok, v = pcall((Bytes.Reader :: any)[m], empty) + t:check(ok and (v == 0 or v == ""), m .. " on an empty reader") + end + local ok = pcall(function() + empty:string(-1) + empty:bytes(10) + empty:slice(10) + empty:skip(3) + empty:align(4) + end) + t:check(ok, "string / bytes / slice / skip / align on an empty reader") +end + +-- ranges, sub-readers, peek, match +do + local buf = buffer.fromstring("0123456789") + local r = Bytes.reader(buf, 2, 5) -- "23456" + t:eq(r:size(), 5, "size") + t:eq(r:peek(3), "234", "peek") + t:eq(r:peekU8(4), string.byte("6"), "peekU8") + t:eq(r:peekU8(5), -1, "peekU8 past the end") + t:check(r:match("23") and r:tell() == 2, "match consumes") + t:check(not r:match("xx") and r:tell() == 2, "no match consumes nothing") + local s = r:slice(2) -- "45" + t:check(s.buf == buf and s:size() == 2 and r:tell() == 4, "slice: no copy, parent skips") + t:eq(s:string(2), "45", "slice contents") + t:eq(s:u8(), 0, "slice is bounded") + local sub = r:sub(1, 3) -- "345" + t:eq(sub:string(3), "345", "sub") + t:eq(r:tell(), 4, "sub does not move the parent") + local clamped = Bytes.reader(buf, 8, 100) + t:eq(clamped:size(), 2, "reader length clamped") + local neg = Bytes.reader(buf, -5) + t:eq(neg:size(), 10, "negative offset clamped") + local copy = Bytes.reader(buf, 1, 3):bytes(3) + t:eq(buffer.tostring(copy), "123", "bytes copies") + local a = Bytes.reader(buf) + a:skip(3) + t:check(a:align(4) and a:tell() == 4, "align") +end + +-- checksums +do + t:eq(Crc32.string("123456789"), 0xCBF43926, "crc32 check value") + t:eq(Crc32.of(buffer.fromstring("xx123456789yy"), 2, 9), 0xCBF43926, "crc32 range") + t:eq(Crc32.of(buffer.fromstring("ab"), 5, 9), 0, "crc32 clamped range") + t:eq(Crc32.string("56789", Crc32.string("1234")), 0xCBF43926, "crc32 continuation") + t:eq(Adler32.string("Wikipedia"), 0x11E60398, "adler32") + t:eq(Adler32.string("pedia", Adler32.string("Wiki")), 0x11E60398, "adler32 continuation") +end + +-- Input (without a host) +do + local b = buffer.create(3) + t:check(Input.resolve(b) == b, "a buffer passes through") + local fromStr = Input.resolve("abc") + t:eq(buffer.tostring(fromStr :: buffer), "abc", "a string is data without a host") + local _, e = Input.resolve(42) + t:check(e and e.code == Err.ARG, "a number is Err.ARG") + t:eq(Input.extension("a/b.PNG"), "png", "extension") + t:eq(Input.extension("noext"), nil, "no extension") + t:check(Input.looksLikePath("a/b.png") and not Input.looksLikePath("a\0b") and not Input.looksLikePath("x\ny"), "looksLikePath") + local fake = { hasFiles = true, exists = function(p: string): boolean + return p == "img.png" + end, readFile = function(_p: string): (buffer?, any) + return buffer.fromstring("PNGDATA"), nil + end } + local fb, _, name = Input.resolve("img.png", nil, fake :: any) + t:check(fb and buffer.tostring(fb) == "PNGDATA" and name == "img.png", "a path through the host") + local db = Input.resolve("img.png", { data = true }, fake :: any) + t:eq(buffer.tostring(db :: buffer), "img.png", "opts.data forces data") +end + +-- Err +do + local e = Err.new(Err.CORRUPT, "bad", 16) + t:check(Err.is(e) and not Err.is({}) and not Err.is("x"), "Err.is") + t:eq(tostring(Err.wrap(e, "png")), "png: CORRUPT at 0x10: bad", "tostring with format and offset") + local w = Err.wrap("plain message", "gif") + t:check(w.code == Err.CORRUPT and w.format == "gif", "wrap a string") +end + +t:done() diff --git a/tests/fixtures/pngsuite/PngSuite.png b/tests/fixtures/pngsuite/PngSuite.png new file mode 100644 index 0000000000000000000000000000000000000000..205460d8287a90ab9c9b7372354d8b7a8b5317da GIT binary patch literal 2262 zcmeAS@N?(olHy`uVBq!ia0y~yU}OMc4kiW$hRXu>h71fGb3I)gLn`LHy=z#0#ZAI3 z@nk#K3dN--<#~8Td3i-OPspDsPeWJA@_wok?_=?IZ)?iZ!tTGb+s$W|7^AEf`7zwvl~U9DXw`-H!LxEO>OOe-2b>R-6XTi@2M#-R0^ z_noy$gBGL1V*UCWrWHaADh)e18$gs6qXW~7*$f(t4x_@OVZs1TB$OwJRbmHnpZ~Lt z*;vndx6WqHhh4YMzJ4jVYwy~;y}O&=ay&?`{FiOD|7}H7Ez|n5U>FAu-q`@A}5_rE&~=3D+gQ9n@iPj=1sma^LCbu}(+<)7!r#}xm1 z=fQY@iLvH8%Z06R3>)GY&c0;&QMH}n)>Eb%-*@i$%DQfO_yzs_@3-%7{A$`D-p>6i zhOgoE?CReI5&xIfHJtl?gYm(iv(DGPSJWPU{rQUU0fuvS|J3h4C}fO{e=mG%&GFOw zAK31Dw~_h9+V_9*D{ANMN?<%t#TYY};niEF3?T*`0f)VD47IoAuiG#!U}b9f%Cuq@ z|AT*T-<@9m{^cKU#yj^9e|vWCp4_$l^-;O@>)!h@q@JJtJifki{}Jx@eB}UZ-2P zZ-1W6edFHS{95+c)#u}{mpSgPzrB8axc=#fOy9T5y?Ym1`Ooe8{V%+)6PwcNYs>jv zPR|w(dH?gv7d>g)g{A&cALI9Zk-hNuc1ru_hrXY_{F-LKw^6vd>?Y92=v|l)e zx#C4u)&5MouPt$W3u5bj)+cc^2svE;wo&>ML(chmb9c47vnAXvd%WiL{ja~isUK|r z`hNSq_c`~2M=TDU3$lOT;AOJV6L6?CW!mwHX%-8^Yu19d zY>YDE91HeIF~(Ff`r1o1-qIt(f8HD_EHVnyFNW<`0=x#XvXCC-}z-N$_^|4zR$<`ppnI(pqZhMo8`lQ zVTW?21uO;yhm)B%I`m^}W$Nhb_bsw(I|DS51^Jjhp z=YRIRW8!uV3<``651Ba_gcw9dIiq1PB-6o~+uP3WW80khm-{~J)XB5mg^d^(7#KWV L{an^LB{Ts5oVVtB literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/basi0g01.png b/tests/fixtures/pngsuite/basi0g01.png new file mode 100644 index 0000000000000000000000000000000000000000..556fa72704084920c07066054bb57adc5a250b27 GIT binary patch literal 217 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;IMg|53Mjf{D^9&3OEa{HEjtq=#3k+XOi)Ub9 znBeK+7*a7ux7U#GkO7bD{bNl>L?x;imgq@V?T~BUsQ!Q_%#uMkd1=Fq2%XfE0;VNzwcil)+70R&CY_wpDy0JnHlqRe`NCgn_BCA=HFC*LS#n{joO__}9PF7+C9=_WT<6}ZZYc@*f*n*U{?tbSGCD#fP@d+Pr(OnDqA Vnf2VrHIj@DxLe z%R@0|4}}y#FOQ((0=r(>OB|MzVB#@wWMN*$b#TEXONKc?4Zf}0Zq_m|Ffe$!`njxg HN@xNA*)K4C literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/basi0g04.png b/tests/fixtures/pngsuite/basi0g04.png new file mode 100644 index 0000000000000000000000000000000000000000..3853273f93e5960e0642ca62f6d6ce7433654928 GIT binary patch literal 247 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I76t|e#wX8y>}OzLU`coMb!1>{TVVKNT08>- z!#YnF$B>FSseOThhYSQ<#AQTeL}XZGTC6lm1zss!aXjF7(D9(-0mq2~Dk01>J!hOd zTX*Np+ugHoAKr9mn`^1-?<2bo?sG17|9&j1+(!8t@5Z=}uSb)LEtWdw=w(XHc8}^j ztNwPO#?*Dae^)zSlZ#|e`Fg@iDcj*%=Dx%1KaJcA#M+Cj_8b0hUZml@bj!Nzxi?+mt%cD9GZwZ>e!`9N>W!~gUiM`dV_;xl@O1TaS?83{1OTUD BU*`Y- literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/basi0g08.png b/tests/fixtures/pngsuite/basi0g08.png new file mode 100644 index 0000000000000000000000000000000000000000..faed8bec445f282d68534af38ceb4006a55c3e86 GIT binary patch literal 254 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I4h9AWMny5veGCi?Ea{HEjtq=#3k+XOi)Ub9 z*y`!x7*a83>x5XYLk0pZb9bGPaXM1{!}+|bT}Q=+RpNsDir#mY?Ni~8Ra`pd+~p^; z&l>57sR)LOih9mi<>aBXLMu#V;i|4~m81PLXU^mh=ImVH#c(}Ghx2*PC#gG|I4!MG zgTreV7CJ0CI2^lKYp-o`rWjb{X=}sM*D`{>}&O}@i5BRMD)G?_~n81zT@Yb zbx%#Idc_duES(fS%_Nw8gX9U4Zp<>&hiddm**&))gp^@aR=4F(1V22WQ% Jmvv4FO#rj$Wv2iD literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/basi0g16.png b/tests/fixtures/pngsuite/basi0g16.png new file mode 100644 index 0000000000000000000000000000000000000000..a9f28165efd4a6eaab890f3f46eaab0812614046 GIT binary patch literal 299 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I0R{#J#=^Ffe;F7USkfJR9T^zg78t&m7SF)I z@W|7}F{EP7)``}9hYSQfLDAc69$1^NL zD*Njnn<(oAE}cR*rFR@vCexn1cz}XLsF>O!J#8e)${Cj)lovp6ff!Am7ZPo3otzV|FJW$~p zo15c;K!t5=SV`NEQ&lXs}EFH2-`+pE;ioVc|9XzYuZJgFX>S~B2x?(iY3*AbxfSp z@K{K-_S%9a=cO1K`W_1{{d{bW`LjQVztp9dEvWCl^>qvXyGxhtnBw%m{L}SHez-7q zq6BwwZugOhkfXU%C6d1^f3Pk0Jm*S=&;J)q>2;X+)MiBvOIL~|f0}lH*UV`N=Wen| zXwPC?v5#SC3d^#$51TeBSv#mc*71Gp%#!R{)^O5l?Xr`zi`$}B>mQghiFbmOf_?1$ zhtqjAT+^G?&i`Kj{?BE$kT1D{v!7JjHx;-4;gy&hedO9K8|5oe^|u=g-NKvA@B4BY VD*mxGW?*1o@O1TaS?83{1OR6SZ|!+)S5FnrYxxYXWpCJQ^{h>G&3fG@;4snJT8AaT zXL9bVG(kgm%BuE ze6mI|;Pb?E*W)`|b&3yt5=w}2%L-6uJz?CCd1B`azh65YUt3yDzjE?#vPiRt!h9K7 z6O$M2udZ3}KAL##Q-phxV3X4H z2d}2HeD-PDGlfCLgTe~DWM4fH9jNX literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/basi3p02.png b/tests/fixtures/pngsuite/basi3p02.png new file mode 100644 index 0000000000000000000000000000000000000000..bb16b44b30907b832b678a3b441278df340edb9f GIT binary patch literal 193 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;ICT0c(#!BHu9~l@JSkfJR9T^zg78t&m7SF)I zz+CL)8N$fOSff|o#K6G76W|l#%J84zKLf-6{|pQa|5NR?cQG(91bVtShE&W+t~kD7 zHe*Yy1k1r2XL=MZCB5$LU`+b*ZPDiadOvnGG}?FBcQKy$af%`3!(%aL4}}y#FOQ(_ v_9dbc$`Ui2Rxi+DVb=O6e{jJhONK2`wJ+sMA2KsAFfe$!`njxgN@xNAQSUy6 literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/basi3p04.png b/tests/fixtures/pngsuite/basi3p04.png new file mode 100644 index 0000000000000000000000000000000000000000..b4e888e2477d4fbaa3c8ed16a8007d40e58cd52c GIT binary patch literal 327 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I7G?$p#&5ylfeZ``Ea{HEjtq=#3k+XOi)Ub9 zU@ms@3}InmDgUu`F#`jGZh%jSs}jS1hX4ON82&5$XJDB5|9=|8U55YV{~7)>Ffja| zc^Aak{eL$DgUf%0|1Os{ci0D)kJsjnY3X*QhNTP+^U(0jT;v*A=|&><0rr^}WmaxEw- de}7DXfnjsms|=o!3!so-@O1TaS?83{1OR>Hf6M>? literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/basi3p08.png b/tests/fixtures/pngsuite/basi3p08.png new file mode 100644 index 0000000000000000000000000000000000000000..50a6d1cac7a111d53cd3aec0d35dc4d09311baab GIT binary patch literal 1527 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I4rT@hM&rf10vH$=SkfJR9T^zg78t&m7SF)I z%n;xc;;Q7r@b&-O^8e+h|Nj@{Vz4S_P*VE;U+}*m1A~$h!~Zp*Y5&vyr=|U8{I4X$ zaOeO3GyiA0xcp}b4OL=bIDPuRiwi^O|IpK?8H}YE{=d2N_W%DU|4;wFbI0YsOIq50 zV+IBnC5E?e|EHxf{9oeo|NpADZ$aAr{r~^>|G)qL8IAuNhiWk}GXC%A_|LFv6(b{q z3j;$(2gCm-r*}m&DE(JTGh+Dvf99%H|3euVR;^+~Lau^Z!ov9ftpRb}<+mGrVPZTg>qPf5%KO2EqUT%NZE{H#7dG<#RU+Mqqt^#7{= z|L@%S9~#QQz>s$54#ORWJI((Y%gg`&`}hC<|I`0NL(9t<{{3S(&2XB5;U6Ot10w^2 zkP^fH|4IxlF0=m||G%<|fgyC}%>OfIGVEg5r4`EX|MclC|I_}@Hva#A*D8ipP8|%v zs~G;TTE)QdmSNYf|NjLU{xL8xxG>C|Ig?@L|1&dpF)(y6bTHgu_&-^Rf#J@-|NmA6 zGn6xwGckg!WMDA<|Mow_E{6Zc#&7?>{ePrm&;N3URSaniX$(qAcNiEziRJ&D|J{NN z45t|w8ABOD89Epk7?c=6u0Q>jf#H8ghYN#C^e%?~d&>XM{Lhfau!N|b)-}wK|zRO7r3`~nWT^vIy=A>T8jNxXGVEbS$xN?HmluN#Ak~K9w zpRN$N^xi%1Y3(OYCWs&HY~+{y+a-TYvs@ zP@AjC>mCO{7)A-(GHaw*51VVSpjKfN-Ya&WVN+x3mrzuO}9eD>X#t^DFP*Ea*-(!7KfU)Gv; z-%$-(7wK_d)^w|)vxum%@$TKLSHFI3ZGH0O$z#V39Js!HtErKZ>e5wROiW(hZ{Kin zX=$H5TU+z#^U9Sc&z`-pW9`|iTUW1Mp`qE?)a2#0X_Ju9nzeiPh=@FT& zf%gvUE`H&M3VRxt7YN%O4qYH_!0UI2r-EVkL&Z5vzc@ZWw2^7Oy@5;bK-_}+AGq=k zM$KRo&;x9Ts2E zTEMS%(BKE(?}tWvm}jvYKV2Gj6DV4L@F}Qp@^tlcS?83{1OP?E&e#9| literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/basi4a08.png b/tests/fixtures/pngsuite/basi4a08.png new file mode 100644 index 0000000000000000000000000000000000000000..398132be5faadf83e159ac59c212213bcd43a894 GIT binary patch literal 214 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I4i*Lm#&so4FBupZSkfJR9T^zg78t&m7SF)I z(Cg{q7*a9kZU0%WW&@t%^^J00uI+XFt?}*Pca38I4R4=pm6H)&B;**@HbX$_(tmd) zNh_g~cV{Nu^x#wB{@ma&XY-#03uiN*-1mWb;)^QZl|~c9D{Ra|mqr_uTw$=O&r{qP zxw}s9`!*dru?Imb(h4IS*)sOsTvdL4iK*-wgM0&4zYPaD{dSoBXy@(Y>UraD%PAWf S8q2`Iz~JfX=d#Wzp$Pz8b5P#^ literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/basi4a16.png b/tests/fixtures/pngsuite/basi4a16.png new file mode 100644 index 0000000000000000000000000000000000000000..51192e731106e77cec52a3acda3d0c3cd54a16d5 GIT binary patch literal 2855 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I0Tu=Z#(z)ZRxvOzu%tWsIx;Y}EiimBEuMja z>z=2JV@SoE-s$xPA=gWf+eg`Y=9gc5^>&?rlaY{r$NiQC5;8I^Y+|MtuB353mMUNq zzBnswnF(KClF*kqFD?A9n3j3OJX-lt;h3}VhGg?;kFTs#*5%VSFyjko;^nx|#Ik9^ zma1^=x3AWgY<(r~?_-o}GueJ$@wq$p?`qEPd|q>Y=S_xZK0nUBPPpzc%~H5WdYPR- zyQ;TN^F%R;j@ec{Tex2DZr}7)>c_WftDfiI>)|-de^ZgS&W_(quEG0zqfxHO6Z?&t zOG^Kk>pbqAd+Kz3!})LRCZ+RIS*GnPbdJ2w&VRN(IXzwd(J7`AT$uubivPv+bWtRx;m^& zwkrDAOUVm2Ics|-gnpGN;SI6fzmebU+u>9157hgWeptP7!qU|Om;P~_Zs_=-Eb?^P zyMG^4W7mE-)WI(FpD}#$g=sCPwx7SI&A-L@wppz0KHu=`cFc2GKfHc_c<;^h*ZWH( z7TR3k^R8O(lz&&%E6v#2=TbIPinrCh>=!ut+hON^?j_vUSM(nSZsoILX zLT?Qow7%nic*-pHZ{+HAYF!DxOg`ANKYwT8>GA)NQCRPhH=pFA%K~jhOd5qQIcz%| zVYkG->4~wy23fu7uU>`Uzk2m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a5157fe2b029af4e2bb07f478ebe8bb GIT binary patch literal 164 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;IMg|53hG<6jNCpN5mUKs7M+U~W1%@xC#e;-B zT^vIy=IEZ;$jNNL!+P=cC6-NI3fxsD`4dEKnhy4ICAzW)etgiSzv|VcB`rDUR;mWG zJr6bs7kVVPNpZionys``v8rlZ_pMFy^0Q7EWa`b;Ow4FVdQ&MBb@ E0G9U~9{>OV literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/basn0g04.png b/tests/fixtures/pngsuite/basn0g04.png new file mode 100644 index 0000000000000000000000000000000000000000..0bf3687863d8a1f53bef0aa24b841b21b0e04d9e GIT binary patch literal 145 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I76t|ehRF|4XfiM`u%tWsIx;Y}EiimBEuMja z!Nb$VF{ENnazcWDNJx;8Sy>?`udlbZe!7A)!_?as9s3xx%AffZu>|Z~9X3(9;ndx| vvt<}V-pw?A!m*&}{XJE8hN-{b$x1RY$cwyVeD&Y)7sxJ8S3j3^P6;M1& literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/basn0g16.png b/tests/fixtures/pngsuite/basn0g16.png new file mode 100644 index 0000000000000000000000000000000000000000..e7c82f78eb954be5be51c35bd287e00018c69d82 GIT binary patch literal 167 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I0R{#J2DZkZ*$fN}Ea{HEjtq=#3k+XOi)Ub9 zi1T!D45^rN^^zgi0RtZAK+EX&^~dfkn0!E^+UTkl%i^2;_7)AxcZ3TICoiySN|5E4 z$#A#no5LxV7h-qVoYWk)FR-0p#JG!fd*cMo3%VKnOMDXS^V#3{f048}U(X$_K`!ug^>bP0l+XkKCtEmz literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/basn2c08.png b/tests/fixtures/pngsuite/basn2c08.png new file mode 100644 index 0000000000000000000000000000000000000000..db5ad15865f56e48e4bae5b43661d2dbc4e847e3 GIT binary patch literal 145 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I4kiW$hCdQ-7c($0u%tWsIx;Y}EiimBEuMja z!Nb$VF{EP7+p7mT84P%s99rK@{JXtK*xE(=%fcV$9%^slWwCDH68Rys;O&!Ip9+UY yCVsDW`9m%2A{rkSlvpUQbZFdNP`>y8W7Ec;ar_SFy%`u77(8A5T-G@yGywqXWH537 literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/basn2c16.png b/tests/fixtures/pngsuite/basn2c16.png new file mode 100644 index 0000000000000000000000000000000000000000..50c1cb91a0171e9f34991b079fe932f5f0bb16d6 GIT binary patch literal 302 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I0VW0phBY0A4;UC2SkfJR9T^zg78t&m7SF)I z@YK`AF{EP7)oBO0nhgY8mOpT;KV7%|@7izEvJU<1&fTQe}4O^Aoe0-!sktm@h{$dVyY}zw&8$% z$+9Ps8qUvSa+pnDyfI?>`of2?arcWeE7KS7&i(8uy}=<}UN52joQy_7uN>=-1YG!QjKmgA%J3=+yA6xb**rMDrP2hP|HkjjuZUq!}0(7(8A5T-G@yGywp>N-FyR literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/basn3p04.png b/tests/fixtures/pngsuite/basn3p04.png new file mode 100644 index 0000000000000000000000000000000000000000..0fbf9e827b467d65dc252db937d6590478bbf88e GIT binary patch literal 216 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I7G?$phQ^Te;|vT8Ea{HEjtq=#3k+XOi)Ub9 zU@ms@3}InmDgUu`F#`jGZh%jSs}jS1hX4ON82&5$XJDB5|9=|8U55YV{~7)>Ffja| zc^Aak{eL$DgUf%0|1Os{c|G)qL8IAuNhiWk}GXC%A_|LFv6(b{q z3j;$(2gCm-r*}m&DE(JTGh+Dvf99%H|3euVR;^+~Lau^Z!ov9ftpRb}<+mGrVPZTg>qPf5%KO2EqUT%NZE{H#7dG<#RU+Mqqt^#7{= z|L@%S9~#QQz>s$54#ORWJI((Y%gg`&`}hC<|I`0NL(9t<{{3S(&2XB5;U6Ot10w^2 zkP^fH|4IxlF0=m||G%<|fgyC}%>OfIGVEg5r4`EX|MclC|I_}@Hva#A*D8ipP8|%v zs~G;TTE)QdmSNYf|NjLU{(({y!_1j88D{=JGjkUMLkB|#!yShIla&}4?)>}zZ&ffu zIYT)UBgjey2IK#4|1<1j_-}0d_W#@eM>_WWFK1ZAkj9Y4prmw%fdQ0Q{@?lEEy%!d znt_oqlp&O%gMooTi4o-b({C9V{&#e^Ft|kTV)(zO{Qu1V3~3Cz{_kQaFE4%za)>d5 zF$2S{|KYP*e7WcHxof>Jh>HEIjGY)+hc^3X_)AVI`ROOy9vK2Sa+jF#X zop7edNoSv@TGkc^Se2w-{_J4eboBvo^Gxz1wK`-XEWCTH0kwa_YOj@?dq zD!WMf_=?l>RhEc9wse+x#=ojyqBYM#1=-G9YZh6o+;OJ;%oB@^9r7nUGtU{d32jkX z_1TDf$I<6o)11ZJ ib5EXT`()5K>kfOP^gn_2X(t|l@~Wq+pUXO@geCy$l4ENC literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/basn4a08.png b/tests/fixtures/pngsuite/basn4a08.png new file mode 100644 index 0000000000000000000000000000000000000000..3e13052201c9f8b90172ea2491b18d6d121c2786 GIT binary patch literal 126 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I4i*LmhMUEk>KPaqSkfJR9T^zg78t&m7SF)I zVCw1O7*a7O`Oo$z0ba_Q03+=ZF1yw*OF z40oUSHu8Vm`}vfiWQnr*P;2n=R`dl=)xpZ@$WO<@$ne`YX02{4~=!d+6H5S+ZvvLRmk@zS!IE zkYN6!UTs5m@`Gv-G46?L-t+vhZ+O5Zp~^A8;j5L&eWrX?v-Mt#_d4dR{hj!g<%;)% zJq)Ma6Hm4rW#U;PyW5^|BF~KV4m&t(KXWx6P~@1B`s|lvbCyqaJ#q;cZ_(H?u(Ko4PoBrUX`v0OU&fd64jWR zXz=a^|Mi9SOl!DW>UnK54Y~wog>kgpYrCMASe+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@O1TaS?83{1OUh>I|2Xz literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/basn6a16.png b/tests/fixtures/pngsuite/basn6a16.png new file mode 100644 index 0000000000000000000000000000000000000000..984a99525f5246cbc5d7083dd79006c7efa0ab0b GIT binary patch literal 3435 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I0X7B(2IW`Fwlgp=u%tWsIx;Y}EiimBEuMja zSIN`GF{EP7-I?(@GS^Fw)qn2a>|Nxm_cW@{n`Ob8c9w|@r?%X_aV)5l>9nsvhnPa7 zUeFbzr~?zCPj*dViYxq^q_dSR>SPy>hC#rAqArGQPn{NCRO^Vjtl6p2DLaeBg}H8m zi^)`3?+H7+^-tb?_~-Ru%kq_>p(g!~a$@(-&9yFnSN?AA^P1;9Q93ka692=F`%7*((_X>z z<7b*530Je`zA9vL+-Nbw*^6f+96qf2A99<|qvUPW?AToOE4$4~avSay?OIX(-&;NE zdS~3l&blSSvjd&~?3PLj<6Zc6TGFbwopHyzCLU~`x+9K#wbzebLVZ)8H9aWm{_*MQ zy2dC@sopSNNa0WBB^Fdz-HPwwfi^`Xp4={d_^ik7kZSI4U`tKfERLo(Bh&Mn6jUS034HeP-wr)={x zr`o%>U*Bu1v9wy=5*Nb!;#8&Ag=@b%tG<3PRs9#<^z}JQ_O17B-9LI|Umsho8ewy> zSRkQt=W6Z+ktanMn_Ty^CzNho%&fp;Bd;*4*qqVDfA@NZBf@^W8FON}l@onb%o)%A zD1ChI%uAEmch~F;h~HoPx9o*(dvO-S*GpUfU)g@=QQ<6K)pdn+4}%Y`elPJT{QTPb zC1FjsJld`x|ztMBLiy54@-v!FxQ-wEugI3Tcp zNB!fIQJm}M?=4n$*sH&t;lhv9Z;lNQBLA~ENSxwX)D_LrVP7D}(6Rqb4bOx*+vQn2 zj=c$NDA`=fs8D(H-u*NN@AG>CU+Z36h1J^jwzf8f_S+&d zHSYFf(h=RI&NwUDcrwGo>`!egUOi)c6p=Qe=Dr=rgf*M<8C2r8*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hmkcwNP;b!>r#`-Lr=yz97*A)3vlOITK)V_L|WNs_G(%pct6KWO-Y-+Rr6 zV~R4&`67!f3(Or$xbD<0Qh$5>X?C+M*GpB;EtkVp?{ArR>3{NszO4J|*Dl;$p4{sg za;dy`&BFSKXF}5tYC3*0-XI@)xP)g-U`CJWu}!KCUz$|@z1(5S6gDeuo90K(&xIz% zj&^Ek&;RA;+iy^`FU(VO{U$vRa=@W1p2 a`_vn64zInv^)mwl1B0ilpUXO@geCw?|A}e< literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/bgai4a08.png b/tests/fixtures/pngsuite/bgai4a08.png new file mode 100644 index 0000000000000000000000000000000000000000..398132be5faadf83e159ac59c212213bcd43a894 GIT binary patch literal 214 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I4i*Lm#&so4FBupZSkfJR9T^zg78t&m7SF)I z(Cg{q7*a9kZU0%WW&@t%^^J00uI+XFt?}*Pca38I4R4=pm6H)&B;**@HbX$_(tmd) zNh_g~cV{Nu^x#wB{@ma&XY-#03uiN*-1mWb;)^QZl|~c9D{Ra|mqr_uTw$=O&r{qP zxw}s9`!*dru?Imb(h4IS*)sOsTvdL4iK*-wgM0&4zYPaD{dSoBXy@(Y>UraD%PAWf S8q2`Iz~JfX=d#Wzp$Pz8b5P#^ literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/bgai4a16.png b/tests/fixtures/pngsuite/bgai4a16.png new file mode 100644 index 0000000000000000000000000000000000000000..51192e731106e77cec52a3acda3d0c3cd54a16d5 GIT binary patch literal 2855 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I0Tu=Z#(z)ZRxvOzu%tWsIx;Y}EiimBEuMja z>z=2JV@SoE-s$xPA=gWf+eg`Y=9gc5^>&?rlaY{r$NiQC5;8I^Y+|MtuB353mMUNq zzBnswnF(KClF*kqFD?A9n3j3OJX-lt;h3}VhGg?;kFTs#*5%VSFyjko;^nx|#Ik9^ zma1^=x3AWgY<(r~?_-o}GueJ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1N zPMpkgNq2%B`!@Czre#CP0Yn88~jb3CKd@g~oVZRcltM43OS zXWrxZ!KC^2Je3JKZ40A3Dh_5f{L8*j+^?)~TBzxgqK2=-O93B$2Ze_^;-{+l7}xVN z{WLHVH#)7LF2C%D!VLcHwG!zy0Ws{YQy;u%ju-ee`(X8Shey5=K8;Ts|FO9niJNkD z*|laWsxMk(YGBIpPuC!o_etvj``S-_Xep}KDX7E?UHaPZv`ecsL{8Kweb$6Z>6SCa+%N4E jpPUeX<8i+F!+uXjVapt`bg1q zcNsU!ma@7tpJH3_lQ&`kyPv6?Qf)&_Q^;fK4Nm+qck~!46*?yUf3$$nY(cdH`xF}i lmYWQc0cH;MjM5(%f)u3Yi1F|6VPIfj@O1TaS?83{1OUh>I|2Xz literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/bgan6a16.png b/tests/fixtures/pngsuite/bgan6a16.png new file mode 100644 index 0000000000000000000000000000000000000000..984a99525f5246cbc5d7083dd79006c7efa0ab0b GIT binary patch literal 3435 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I0X7B(2IW`Fwlgp=u%tWsIx;Y}EiimBEuMja zSIN`GF{EP7-I?(@GS^Fw)qn2a>|Nxm_cW@{n`Ob8c9w|@r?%X_aV)5l>9nsvhnPa7 zUeFbzr~?zCPj*dViYxq^q_dSR>SPy>hC#rAqArGQPn{NCRO^Vjtl6p2DLaeBg}H8m zi^)`3?+H7+^-tb?_~-Ru%kq_>p(g!~a$@(-&9yFnSN?AA^P1;9Q93ka692=F`%7*((_X>z z<7b*530Je`zA9vL+-Nbw*^6f+96qf2A99<|qvUPW?AToOE4$4~avSay?OIX(-&;NE zdS~3l&blSSvjd&~?3PLj<6Zc6TGFbwopHyzCLU~`x+9K#wbzebLVZ)8H9aWm{_*MQ zy2dC@sopSNNa0WBB^Fdz-HPwwfi^`Xp4={d_^ik7kZSI4U`tKfERLo(Bh&Mn6jUS034HeP-wr)={x zr`o%>U*Bu1v9wy=5*Nb!;#8&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TH@W97KWd!vt)u%(b;4K07Z&^vxgXf-zdBgSFsU@*zQdO%{SA=`0Y<$k-CsKG zC!`+|Uyv*ow*AD6gGw#c2dbGDU4HPc^@;I@_iZHsM}A#;b1CP$SVPHyT|5(fZXISg zdH#(%<0Rj2GIy5A31r0N*9KiUwM%5ibbaUR4r{k;VwhW7q_Bz4q z>hObqPOm)QF&v3!d!DSh@z#E!+DzVt(8ets-)vNvADnTvVR)C?Vb);Hf03c2hGlj9 z#B!Fu0#^^7b$rtx?0kv+8`BczgxI#HKcD_w$II|?N@#|0Lt5)e!`}t7`8l?{$lSN| zgnH{#&lfr&-o2V9#1>d`&P=pas7vGxS6`Scafrc2ev$Wsd)h{)ek!RvKUf#Qvdxso zhmkcwNP;b!>r#`-Lr=yz97*A)3vlOITK)V_L|WNs_G(%pct6KWO-Y-+Rr6 zV~R4&`67!f3(Or$xbD<0Qh$5>X?C+M*GpB;EtkVp?{ArR>3{NszO4J|*Dl;$p4{sg za;dy`&BFSKXF}5tYC3*0-XI@)xP)g-U`CJWu}!KCUz$|@z1(5S6gDeuo90K(&xIz% zj&^Ek&;RA;+iy^`FU(VO{U$vRa=@W1p2 a`_vn64zInv^)mwl1B0ilpUXO@geCw?|A}e< literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/bgbn4a08.png b/tests/fixtures/pngsuite/bgbn4a08.png new file mode 100644 index 0000000000000000000000000000000000000000..7cbefc3bff08a9d91666d6b0f8b5cb1c896b7987 GIT binary patch literal 140 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I4i*LmhMUEk>KPaqSkfJR9T^zg78t&m7SF)I zz?9_e?!v&Zs#n>Ffq}u))5S5QVovg(^9K$vw$8~gF;tqPb6-+}S;xL@ALHUg11Yu; r!vqrn_rncZY&~p`G9&^HGcerOQm8%hy7dGD0|SGntDnm{r-UW|POm3( literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/bggn4a16.png b/tests/fixtures/pngsuite/bggn4a16.png new file mode 100644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dw@A|Lyy(UWqv)SZDZ)f*+9LkNGYWu#VRNH_%^)vfAG0+JzuQwg{$nb$``(xztCbzKXAPN z&*G~&A3ygguG>}^vE{C`U~Bf)l=F836MsK4o%wU;=S!9cy4@c9 zWlfocx9pKRm}=Uj@+0Sh%x^}aXCj>IHH4^eropb7`=htQ?TAw(RJo(a2Yu?Y3FU(>1o*fa}>LGE4>B~Om zW4@|KJynnPtz~-hKD4JQ_E5{`riiSiO2>?h9^P>F*Uos)b#e=*=7AYgXXbBS^7&bd z$Q`*hH|7}OJ9~^4n@^Qos*s`0a!vgp?@FF>=SgQi1%CV-6d9xYZ)=l@?vqR6Dd!z; z$jMFm&Zg(_{B7cn&!QD_CWkNRI4ov*IA_yim6mt;jny32P6;Wzmz^xJHN|U&M2~fu zj@ml0Uaplq&eu*a4^a`AV0?K>dRX|<;`5W)Y=m!BX0R>T$Sif=Ntx3vKygDEXV|?d zUtZ-*{o{!RkeCW4oB6;=b8T5#KhOb!O#e zg}LRIE(N5E?9slk&dHi{?Q;>PuUvPERk!P}{&H*n1fKNJ7Ms1cr_LXD3D{NMy{-Ar zTYHUaxm}7m=Fd}}ooy(&Cpq<)mF0~ex)q)ulDHbHxaLUiH2E^W zowQM|TPG_X{#q)KHAbwJ+a&dT@9ab03jEUU>3Kb$E2HD@c)ZPz%Pi-|$MtD_y5dJq z^d!3ny*l=3-Kn?6T6@J*53_bnO4)VQb=ztU)*q7=z5O>uBgR0pI!~qb?b<14?s$7W zpKbhLNrLfei-go{Np0P7Q)4yrY4a*izFnBi8?s{+$;{=*N~lrk_dFnGH9xvX1I!%i8Kplk1Sv?(5#!(C!@$76;OXk;vd$@?2>?IF BLDT>M literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/bgyn6a16.png b/tests/fixtures/pngsuite/bgyn6a16.png new file mode 100644 index 0000000000000000000000000000000000000000..ae3e9be58a823cf7c6535b1cadd96c45f15cca8b GIT binary patch literal 3453 zcmeAS@N?(olHy`uVBq!ia0y~y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$gJ4puTu zDowcW@a0K=Lu5jLQEy83mrnZ$>4(G@B#VV@KQZH=QcLxLYUV|kAG~XQV!YvfTS>r? zUzgro%K0wVP;y`w&jg=ahZ#+Y88P{_K^IQ#5}7ew-}$=3+AW(H z=GGP|Y~nL1p0LvS0{_3Mv$wrE{NSI{E6;ZfN8;I@Cu?rJwO^<QJS=7ax3`3+cke|B8aa4y>tmeuE& z7IJ2iWa|U-2lx388h+sSUi0CYq6~As$Rf)EbH@^{JGG0{-(G*3-E7PCQq^%RK63wM_%_d14LD(_vhus-6M(DZ|vj-QM-$j2To;aL-y(PMgSlWN14 zCY66LcbGDT%}U#*`H}N;p-Hi$om$%SfB89i|Nj2^yYOp%9@|foX*aLcY&XlAnX>Jt tUdpyk$-HC7SW@yY|8p<=Fa5zj^~RgSYj1D;%)r3F;OXk;vd$@?2>|<&kl_FT literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/ccwn2c08.png b/tests/fixtures/pngsuite/ccwn2c08.png new file mode 100644 index 0000000000000000000000000000000000000000..47c24817b79c1e2df8eb3f4fe43798f249a063d6 GIT binary patch literal 1514 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I4kiW$hCdQ-7c($0u%tWsIx;Y}EiimBEgmG9 z>=ES4z)+>ez|hdb!0?NKfuZ3A14F3+1H-EX1_rAc3=HB0b9M#VFfg!|db&7dJa{cAI$%WrhoE8al6wM0pP%1(^3U@Bv;Q+I<;B&nXM0UL z<`EZ{X8hr|&H2Np&#ZQ7vEKPb)|Y*b^xhxb|Nrc){jL1>=+~L6f)tCpT&7B->?ttp=+i4P$oAzWO$$+VY3c{!cINq_MC6w60(N(!8nn7aQL; zbo3DrtT`iJclfgC;@gaU8^18t&M$Kixb#k_jI+9=x!$eAXS$ zME0I*w|i@*<%GN1hli>wdS8%kNKb`o0stxxR-rK3+2~#isrJVx|&y ztBCp29Ir01n>%Au`^$yO9fB4c4}IQkQ8jsU9q$Kjzv>@yyL$5$JBP4KU$9s)E6%|@ zO=@BF3P}TYyZS9>zi<8dayfJIvi*-QsU_Ts_BGL4rpW)&)kIM37Rxrr^GncT7UeZ`*yGTOxpp1}tl39ysqO$~-a-zzfpImRxf4&fWo$;UJwyt}Aw_SI? z5WD66a|VO#qUw%?F9qFSNOZ2XXg+%={iSoF4o|Cj+=Tak<7~J5o_t`wXDpNWU8k)V z*6KR5&yYLS+F|3AyR6u>HbXM%*tCtQNs>#?YM=k~xO@(~{C+lzP6;c%Q;s`VNIqWp zclGno_8D@iDTVGavZpT?&2r^_d{(pfh-B*1?ehZN?G3oU=Q7GC&iT)jc7EoQh0G;A z*Qef^dxmQ}kFIl~*$Unp0XZ3Me22x7&(D7H>56&9cU?PcehV?bht)sWo;En1S7Bdg zrlPfF$4Y}MJu=7a9#1IjKPhvwMJdthpxO$S$&XaF7?s*ReSQC-|NgY-^Oo$cZ`l{| zNE{S=%8^!_y*i{*E=p*IgiybVLgOh%o05jx2VYaI=82#jp9VfLNnRIPQ@TEyxRJ2bNZJJ}FeEy{IsX0pd z%QClaP8H*~YM*zF+nO=m)}2>WY~u-?UCT5zuNCM&=nK>|%T>t?xi-P~WcH@6Jxbb| zUR_N_+RGm+N`Jbl-_rftioHxb{dLuY6+$-~*mN#k2=U?mboz}&zr9QP3La1CO>Ji; znTrH>X+8}(Wi*>_{f%zv-K%~awf)@Aw@th(_IdEbDI5B7H<w+4_2$1a zcNx#=>~-+U?%uU#lV|b2MRQ^vy>I^cq*45P-OCI7k6NqqrtD_D^E!Ebz;lu0J9Zz9 zJ~Eg)PhSzVtaRfgo%o55pa1x<#&T=%{lD>bKU>}T-tAy@h2VC?rZ i_v7BFH(GE1$NOW=ZkIK(of-@b3=E#GelF{r5}E+#?9BN9 literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/ccwn3p08.png b/tests/fixtures/pngsuite/ccwn3p08.png new file mode 100644 index 0000000000000000000000000000000000000000..8bb2c10981594a83b7a8981436225d0b2241d27b GIT binary patch literal 1554 zcmeAS@N?(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Cc@ zzaLtv&^L4EQst+=zHZTa!xb|*J1gqWop-VRw=?E+`yNzTEERjVG;h)CpJsV`_V5Nb zh8DH7Dp6%ouetfakjLNBBip_$L9dTuk+g}$MAXefX7) znR`lJ-m%-crcFQIPd8dkg(XC3-J|Q;d-@YK1L98K|L@zB+M(QhZhG*?`qn{_L#V{D1#G2L>Lmth~QJd?VYgNe_LqvU16bT+a%NfLpfzzf8B;V1ED2jlgK@=Rb?9SNxf*o|N?NCzHb22@PH| zEH`KLO`5c~o!#8Lyz=LtpYK_cwl9CKm~?qlN4xvWnX6W{x9|Mue9PgJmG(9Y=8^^%#kulq3>E^@63=9kmp00i_>zopr0A?|9i2wiq literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/cdfn2c08.png b/tests/fixtures/pngsuite/cdfn2c08.png new file mode 100644 index 0000000000000000000000000000000000000000..559e5261e705daf7a562a18eee445ccc35990e97 GIT binary patch literal 404 zcmeAS@N?(olHy`uVBq!ia0y~yVBlb2U{K&-VqjocFlk*o0|Ns~x}&cn17q6)!xz)y z85kIti=8|}SXfxfe{5aMz`(#+;1OBOz`(!=Qp#WyWH6b5fl=Ml#WAE}PUxk?!Z!vy zEDzSt6cAty=4cJzXkA<&@=IY)kOc>Ct3!rDh`=5BvN>jxC41M#W`fKc^O|nUqIEIgu?oz&1n&u=MKi)Sa~Hs{_5sm@mE*vTkW&<1*4ze-YZuQ6>gQ_ zEdBcRu2$ZwO<`Yyc_$Z?nYOCx?=Sv*0Aj z{8Y2yPJgAL%(mDEJqI;5Xgj)j^SD`9TAWs`na1URsc-8|&*0!f-QJ>~b8Z>0WjVe6 zNc7RkO2@C&7MRE%w{^Vbv?a1vHgmhB(9OVlhtfZ*cilNIFK%4AtXSd0b_NCp22WQ% Jmvv4FO#sF#r7i#f literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/cdhn2c08.png b/tests/fixtures/pngsuite/cdhn2c08.png new file mode 100644 index 0000000000000000000000000000000000000000..3e07e8ecbd08b38031432052c4f8a4b02f866b8d GIT binary patch literal 344 zcmeAS@N?(olHy`uVBq!ia0y~yU{GLSVBp|jVqjnpf1dS&fq{V~-O<;Pfw66Y;frbU z3=9m+#ZI0fEG#VLKejGrU|`@Z@Q5r1DPv$@U}TVg5t_=t!0_7B#WAE}PVJ=ZjfWLP zTK1p0avOYBwQE4~WcT6~a^bB(@2gu;}2u`V4SbT;SgC`i03QuKsH;h^Rp z{gx3U?us0e^ zoUlryZI0g(Yl{OVUqy6(d~&l6j@RNcoSEep{nKie~F-3mu$25Un vrTrRq2iPVq*Ef4R_hWPWy_I#@m+Lvs#;nTN_j?Hg0|SGntDnm{r-UW|G~0<` literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/cdsn2c08.png b/tests/fixtures/pngsuite/cdsn2c08.png new file mode 100644 index 0000000000000000000000000000000000000000..076c32cc082066dc870e1282b97c15ec22192407 GIT binary patch literal 232 zcmeAS@N?(olHy`uVBq!ia0y~yVBi2@4kiW$2Jc+WI}8jAEa{HEjtq=#3k+XOi)Ub9 zU@ms@3}InmDgUu`F#`hwXMsm#F#`hwBN+Ru9=XQAz)QHSDdsNxg!`j6&k$`913I7UZ}lr>V_JV)}J$djCSsfbvBrAW5t;Qv6?drlk9!& zWQteb)sDVb+ijYC(lf{){__j7Z@0}tRMg$GTzUnL+XXZ~O|AVC5X-$u=v1P(u>alo f@^%rf8b+-R`WM9GuB~HWU|{fc^>bP0l+XkKErd(n literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/cdun2c08.png b/tests/fixtures/pngsuite/cdun2c08.png new file mode 100644 index 0000000000000000000000000000000000000000..846033be6b4fdec08cc010aa0abb35428b6659d0 GIT binary patch literal 724 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I4kiW$hCdQ-7c($0u%tWsIx;Y}EiimBEuMja zfw|bpGlYeOrToWMkThq3M`SSr1M>?IX53mGl+D1vla>Rw?MuqvTxi=+ws{AhrKYFWw{!H@= z{pcnR!AqA9@8M;XIn#T2Vy?hHafbx9?{i`|vM@gCX5gDPJ$Abp$5Ey;A1do?K6|$p zeUa$rW?+vun0?;#*Sa};Hb2fqHuc-}t^DKtUMeEdI(3y2*M^d#pC+8y82xj5ljjH9 zZ~szemzs+H3N!Avn<+O(&A$9#*yU}9-Y3hNC)3}jXR5iftG_G#W{%-cIC}MtQuNOc+-X4>RR-#3uIHwnWyo;$y}RP`vYFQp8Sh?w=sssF z*Mr?6Zy9*6`=s1le~HCDfpKG<_V){IDLE_+eOkTB_kX@Ch|pnXDOmt&E)aXESCVKQ+_xZrT~X_Out=HD51YbG-0rz3@Yq>F@t?Y&|bl z@0DpkZ{7W5#%pzNKYW;^-J{L@e0|Ho+a-2gML8EwJTqnZ)>$d)t9S9~=QN&xwPpuC e{`}YUms!B!`Z>Lv-9iiu3=E#GelF{r5}E+XgGo66 literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/ch1n3p04.png b/tests/fixtures/pngsuite/ch1n3p04.png new file mode 100644 index 0000000000000000000000000000000000000000..17cd12dfc9169036898b84dfcd8d7c547c8dfde0 GIT binary patch literal 258 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I7G?$phQ^Te;|vT8Ea{HEjtq=#3k+XOi)Ub9 zU@ms@3}InmDgUu`F#`jGZh%jSs}jS1hX4ON82&5$XJDB5|9=|8U55YV{~7)>Ffja| zc^Aak{eL$DgUf%0|1Os{c|G)qL8IAuNhiWk}GXC%A_|LFv6(b{q z3j;$(2gCm-r*}m&DE(JTGh+Dvf99%H|3euVR;^+~Lau^Z!ov9ftpRb}<+mGrVPZTg>qPf5%KO2EqUT%NZE{H#7dG<#RU+Mqqt^#7{= z|L@%S9~#QQz>s$54#ORWJI((Y%gg`&`}hC<|I`0NL(9t<{{3S(&2XB5;U6Ot10w^2 zkP^fH|4IxlF0=m||G%<|fgyC}%>OfIGVEg5r4`EX|MclC|I_}@Hva#A*D8ipP8|%v zs~G;TTE)QdmSNYf|NjLU{(({y!_1j88D{=JGjkUMLkB|#!yShIla&}4?)>}zZ&ffu zIYT)UBgjey2IK#4|1<1j_-}0d_W#@eM>_WWFK1ZAkj9Y4prmw%fdQ0Q{@?lEEy%!d znt_oqlp&O%gMooTi4o-b({C9V{&#e^Ft|kTV)(zO{Qu1V3~3Cz{_kQaFE4%za)>d5 zF$2S{|KC5h@$~|FZD{h{*=V;|R;Y^Q{&OT4ItSt_(DoMZm*}=BQ+tsYNt74YAhxZ5j z%aP{=xM^J>h5kZ=reornwbUjeOJ$*IFD5s8fu4%-Z!q`1eZp z@@oRVD^BU$x->&{OSo&2^{Kp(^m!fqatv-7kyPfh>c9Hb)6{qK`ED?Wf=`8b%e^tRmYo3J)vYofqEV5X+ z<4pURCl(t!qx-`c=%aaOMNh0tnvuaQ@tbFr zdzRW6cGP`QWZXY_qWVpzIg7dHo;=O=$)Iu89ri})e**2(PCNjW+n%m|F6*2UngDNe BYqkIY literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/cm0n0g04.png b/tests/fixtures/pngsuite/cm0n0g04.png new file mode 100644 index 0000000000000000000000000000000000000000..9fba5db3b82ca7725816efca47adfb44d61292f0 GIT binary patch literal 292 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I76t|ehRF|4XfiM`u%tWsIx;Y}EiimBEuMja zfxX1j*OmPOBO{NJ#oamo8yFZEPI$UFhE&Xny?BuKkO2>CfV`Fi#|IACg~}ValtUh! zU^QfvHekvLa7$pmvB1rCD%1QUo`H{Kw4NU=eLE#VOtmn(k=JA1$5|aKKW=HrW%^!! zmgCRX2lwZ5UhK8i5!sRU#^0OkIs1YOC4C1pPP}J*GU>Y9vbS#B)-M8fHLTxPT~Y8n zmf5mhpS_@8OGV?2*2~H_SDP1H|0j3rnikk@kH_`o5%P%0- ztcHxz2242tZVAjc7P#3?WtxA)Gw_j&*7KvKZ>J=PsTO88@_NksIICmj$1M%HOyBFz za{Sr);QoBhi@mlwB0JLF_+ zGF!ImvlsMhsc5{>dRh7AYV(5Y|Kx7HeE!1WyYn6eA;He-%d#oQ!UJH&c5J6N#6mD6Yp7{Ou8<&?5!KO^^1UA4eR$+R}?&t zWwvbBXD{g2Qqg#$^|JEK)#e4)|H<8Y`TT{$cjr9{LY&E03dQDi``r#zZqYO}+^*N# uC|V@&_!EN-jZe}uG?q4&{AG~4dC2w0|ITcX_dQ+xT-G@yGywpT)^bz; literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/cs3n2c16.png b/tests/fixtures/pngsuite/cs3n2c16.png new file mode 100644 index 0000000000000000000000000000000000000000..bf5fd20a20445fb7c9cf5d38a6ac4cd0fb28de29 GIT binary patch literal 214 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I0VW0phBY0A4;UC2SkfJR9T^zg78t&m7SF)I zz+CL)8N$oUd%?W-AOizKou`XqNX4AD(+~0#=y1;A$b7)@LgT|f4yir%O>FOzm7E;rCc3&XyE~j@HwaeCjHxe6 RXJBAp@O1TaS?83{1OU;1N@f56 literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/cs3n3p08.png b/tests/fixtures/pngsuite/cs3n3p08.png new file mode 100644 index 0000000000000000000000000000000000000000..f4a66237bfb3a113b7874d569367932762cd0ba8 GIT binary patch literal 259 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I4rT@h2A3sW#~2tGSkfJR9T^zg78t&m7SF)I zz+CL)8N$rWym-FVdQ&MBb@06uR!@c;k- literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/cs5n3p08.png b/tests/fixtures/pngsuite/cs5n3p08.png new file mode 100644 index 0000000000000000000000000000000000000000..dfd6e6e6ecfcf1d0be69730fb34292c8b6561376 GIT binary patch literal 271 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I4rT@h2A3sW#~2tGSkfJR9T^zg78t&m7SF)I zz+CL)8N$lSDxr4InSp^JA;2fZ^}i&8(|?Ae{}~wmS2O(I%kcj{!+!=4f9e1K_ZXJ` zXJAPF|9=hxgW~`HQ49?Kt^QjvB>!i423E!JKS~j#aSp@(dkoM1|Nqax(DMKPUIqrI z|NpBQT0l~g?)t4?85kJ6JzX3_D(18vWMw?Sz|dgu?%lh;(RNJIlO4V`g?-@2I;g6_ z(w-pF(iHT8i_K9Xf@S3c;gY6E0nRW-of|Bj3F0YDF$G*&2X!-!@E_bw~Nq_Zy`;1fugk+p+k-<#T> zEF1>Do$neSIBs|lFZh6Y0SkWz~JfX=d#Wzp$P!y Cx-zB! literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/cs8n3p08.png b/tests/fixtures/pngsuite/cs8n3p08.png new file mode 100644 index 0000000000000000000000000000000000000000..a44066eb6edf7e7c45720aed393b64efa2381847 GIT binary patch literal 256 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I4rT@h2A3sW#~2tGSkfJR9T^zg78t&m7SF)I zkPzS#;;QhU;lDfs2>-vo;6DSye|v`i{~7)>G=SLg4FBsBKs<&AAntsI2mc-ZgX9?w z{QrNSfnmY_|N9vj8vY*u$?pF@pMfFa|NnXh28aLu;~5wf{{OdU*xa}|nSp`9+tbA{ zq+(9%K~}~C3=9nh@7}%p8*RrVy;VV=rpdj4lkcF?43_2vf;mkQ6S%b;^#f)qh^RC< v1#m?j)azhbxj?w5DRKjs-$C7qqx_nW>==K14!+62z`)??>gTe~DWM4f$ar9+ literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/ct0n0g04.png b/tests/fixtures/pngsuite/ct0n0g04.png new file mode 100644 index 0000000000000000000000000000000000000000..40d1e062f8cd792950cbc4307c8eebde62ab5ada GIT binary patch literal 273 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I76t|ehRF|4XfiM`u%tWsIx;Y}EiimBEuMja z;e@A)V@SoE*oy~w4;k>V2FPnUaD3p9U8uZ)OF87x306Z!X#=L50Jj9@8w=cQr!vhy z;u-izM(g>}(zjC*#8eBj8+kqEeVo;?^5d3!)fENLW0@`6_1O#hwNy0TXuYg_bG3QF z^?!1=UOs=}@ZEWjf)Ho&l|r$3-F~-2m0L6o4Y%v{Hi{MrJo%8uEdIn`L*tY542`9Y aC4U*@ZXR;|@xL=0qZ};mPz>hkCFkdA_MLH;XJBBk0BLs4FQ_caOwTA`fU^{!CLs*bQ3%e= zOHVAwFG^J~w6rwUwKQu9V6k9eVE7F(!zHyixhS)sBr`vc!BHVOKer$=ClSO`$WK#9 zR47g@0WmUj6Vp?R6_Sfm6H8K46iV_HN>YnU6iPBuxyllYGV@D|6_WFF@{4p!DhpDJ zK{`q@QWXOH+!fODi*gf7^b|bvl5WpF6v{J8G87VX3NjKEk~0$X@=|jkVq7IfiFw5ZiAAY-$(2xpi}e&7b8-}tGD~z* zQVU8liWL%ba`MYT_9Q3g7o}w8rE`H?n~|zeT#%X!vR$E|D782>uSCz6lQ)}zfx!|K z48i$nCFO}lsSM6gFXrbdBr5o&MuZfXK!OA8KZVlb%)E33rGmWNlKg_abS1qkp_EDn z1_lw3AugH4$vKIcxv51AZbhl7AoKL%8+5!F7#L1?x;TbZ%!$2tkoS-Q4{LzDmIKEJ z4%vmu8@QB19-Uw{WRx~w$_a2wV7{@y&2}o&{3D)$k7Tr-A1!@5B|%KJFuRf0W8TME z9VX~<>zUVoP3&(;U`=W|}{wbc>Xk@m*lo9j9If(s>m2Q*H+XMHm1y4plk-(D=Y0TnJ3^p`ANzc$&+F0_JLGI=u*B}2oK>^3$>FVdQ&MBb@ E02hEDfB*mh literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/cten0g04.png b/tests/fixtures/pngsuite/cten0g04.png new file mode 100644 index 0000000000000000000000000000000000000000..a6a56faf2b3e8655f88c028070ac174823ccefd1 GIT binary patch literal 742 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I76t|ehRF|4XfiM`u%tWsIx;Y}EiimBEuMja zK{7KWq9i1@9_n4Vg!kX)3SSdyBeP?E1ul3HA%P?C|VP?lJfnO|D0ker{BU!+@7 zS&&)`(gBhR@N-v4%P-1JEYVZ&%uCKGO-W5rNGwWKNXkh}&Q>eW$Sg_KfoRlGC`imn zEh$M&(NQSREXhzv%qhr7R7lQ9%*#v7fr^zBCFT_uBo?LSC09ZXF4j|U%*jzm$}G`M zNi8VJC{{?!$;mGV*^``{UzC!WmkxGqMyf(_L25GC_JX3+;?%qny*g7~7X}6fcTl(l z=ckpFCl)~?6wY&odN@B%AyL6EH6o!KS$A@ f;b3c3UkM|_-OZl^L$8@k2PI%nS3j3^P6 z)a=Zx!%G;#GjnoMa}~-G^Av)UGZHhi6*S7hLJq}Xu3mC}uBPv%8CMw?7(76RIOi8s z7G@-id3cFJfSesOW4o`P>_c4A(lLVlh?ZfS8zVp(EN zc7A4FYMu^6qmDvBVoqvFNotCYLSjxqMxriAd0C>4LSk8dW^QR|N-9Vv%rx)B%gnp| Jvd$@?2>^p10G9v& literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/ctgn0g04.png b/tests/fixtures/pngsuite/ctgn0g04.png new file mode 100644 index 0000000000000000000000000000000000000000..453f2b0a49ee544fcc6b297a59dd685a06285005 GIT binary patch literal 1182 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I76t|ehRF|4XfiM`u%tWsIx;Y}EiimBEgmG9 z84^(vl39|I%D}*on!|8z$+`9CTh8r1xBq+-LqJ}7aA{^qszSTNP6h@BH;`J#(vpn) zBB^$xAA-vLwIIRPHL_~Sz?|-aB@asX10PxIatV{7|hj6 z&d=4nre&7Kz`)Q6GSNA|pt2}4J);C_=z?>5&uu;5dT!6Tjptj=?L4>Z+!}>*TfmHs z=XRd&gGy{+jR`*=A7GkZll8a=JT!Rc7uZK+~#xZ6wYlt-*CQ1 z;oMq~=^)A8b9>M22T3cO+Y0i<`JQuo&v%~Nt8l*I-2U^eAir%tx98kW5a)a&$c%G4 z&TT)p3*%zu5&xj?K!tj;d~3&3~<0~Jl}S{=X@hr;CwrnvFF?x zhzi~FE$4gBH$dcCKz1mc+jDOJ`Ns2Y=hi6%__^yToLg`X;EN_ z-*Rr_xt$8<_JfFx=bO(roNqke0}lSy^Nr`Wo^R4o09yx+5*>wt#GKTUlGGF(kPTZE z&aFAO`+VEEjS3L2fVk&&!sK91SbM%n;e5-v?dO|7-rEUIM1ByfiaL{c&w-e!PJ)L>$a~K#HVm)0PLo_DNJ?ALMpvdEVG2Rq9i1hkCFkdA zp7*VN4%QnIQR19mP+63jo>2l8V0f@(>Vu`750#q7 z%a&|-uw=!9rR`vYz|N| zX#!gbmg#@6WU9i0B|E@zF&~RK$nL2RmTY>kWQCprD4s#at^+%96I3}!7VOn250-%3 zwBx~&)nN0M=^&gBVy=3yv;(5}!IJr46$=#}EZGSbZ2~E11aKZU$CFO}l@I1ByoW@s!9Wfsi zqoDk={=t$B3=fuorTcKsS5rICSU&7Z-}sy73JgU9EaJZFC&1eIr=u6{1-oD!M<8ZpS? literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/ctjn0g04.png b/tests/fixtures/pngsuite/ctjn0g04.png new file mode 100644 index 0000000000000000000000000000000000000000..a77b8d2fee4c377c20b8e751317d094cc2be3cf4 GIT binary patch literal 941 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I76t|ehRF|4XfiM`u%tWsIx;Y}EiimBEgmG9 z84^(vl39|I%D}*omB{e8Y5(JEy>6) zf+&75ar%pfR)+A*oSf8Lg|fsvh2Z3j#LR33jdHM%Lot}EmzP2$o-Lp8xS{oN zC&>SeGaol~KW?1=xT*1R<7$wzIwm}Bocg$_2Q0Ycar45*&3hgjn8N9eYtxQSn=w| z&0s?s8Xq@L1P33)Rm&eY&V1a^1R@)EK5m5AI2mHmv+WzfZs>WscE-~=D;_sa2P*)% z^U3b1pnz&z{dC{t$Bm0Y9&eodxN*hf#-7KG%O5xPg8T(iKmTz<(_vQLEes3{$)G3* z&QB{TPb`8bs=Xi|GdATL|1$pU8kDDev*}MPw6sX01sSzQ?C5fQO zd(pY+$&N0Jz~2Y*MMKk}<{t(O3=Bpf>s&I6lXDU?b5o%S^J#1Ei%n~u?CO5Gpp^k^ z^(s)%f)W+T_QwrPWgncMF)%Qsdb&7X=(ob z&;PirWPbS{pK1JrCD t=JRuQR!^5qZ};mPz>hkCFkdA_MLH;XJBA(tO|)Jan3KOEXqvJC}Cizm{WXCe}&E| zpYs}l9OuuR^gJ7?;e95U!|$BOnKRb{InJH&_SZR~?-gpWWsAwxttQM2-HH55f}*Af zF)%Rf1{vm(TAW;zSx}Ohp9eBdw{IigAp;(l?{!CgeU|<|&=MiAKOx3h>5hdLPw0QS z@C}jss>{onZU=3il&-yjog=o!{*#mc%Li&tj1Kea-F@iU#=kY^{RN-3vbC!pax1Ca zS(k3JM)!%ZUh7v|c5mOd-9r2MvQOzf=9dZdJgQuCWR`8?7BwbyE!QvKrS}BBG-cw- z|Np@5;gYWEZ;y4Z2J;8x-mRXo_UulZ_S)PvFGDNx-E%K3{qcoW{!1Pm?|uf9e+T>Nfs-NpuR= zry}o9+@CH@{lc*9jiA%Kz!mEl7#L(hX1Qb*C+8$)=B5^bP1E-B)%Dl$y2{KT7|NV* zW!={I3=9k>JY5_^D(1vqJji>oM=+td5l*w>0E3eXl>u@n`FU`|~+3_S))* z>_~g#@6Gj`eZhs2z5^O3-m^ZLbX{)QTQ_d&7XiB(*6*vXD0m*rY}u~QUeK?lqVY!S zW#yZz%?qyole_iu`3r~d&U+MuIFqjwip}fxyB(_BqG@QjU9Y!Mv`FB|hcssKCk7iD ipQLAKENv|L%OH32kn4~Co!JZw3=E#GelF{r5}E*#0y6vn literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/exif2c08.png b/tests/fixtures/pngsuite/exif2c08.png new file mode 100644 index 0000000000000000000000000000000000000000..56eb734991497525b489b9baaf275d2e71d25683 GIT binary patch literal 1788 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I4kiW$hCdQ-7c($0UrLSeO!M_+&|+X<;9y{9 z6k=dzU|?WmU}Rumlwx27vl$qY7^UItEJh8e8YTt?CSfR>k%6IU1_Q`oaRvs4qV`M% z7O37X1_p*Z3=9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iO0bBAO@EbG+_yy?*9B(uK2n6#IGN4doT)KsL4?QpJzr*Zrfn9?3{md&*nBZZO{gyrZyJ~3QXE191>KebU^*9 z;+0qn;l}!%6N2teTgUOivLJnh-HQ$ebJqIks}i|_55E|=mY!P4v0wgoz}jM^LvPh< zSq^UG@c7lyG>v1C!ncp=7GACqzrJRMxqh>OauV(MIwz@gKqy5Wfa Xk=j!c0n5&91BHyItDnm{r-UW|MPY`} literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/f00n2c08.png b/tests/fixtures/pngsuite/f00n2c08.png new file mode 100644 index 0000000000000000000000000000000000000000..d6a1ffff62eb0f1f1dcdb4ba2b1d30473d3adacd GIT binary patch literal 2475 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I4kiW$hCdQ-7c($$7J0fjhE&Wcot9q^@>KNL z{O|Yf`kHMx*|vdG$8$5|O`Z*Z1g9q zKap|!PQ>-b$3K4?y{B3{%5l;=&!j}7`F@Yz=$t#B>S^bFyf~AQxiu#Ai0S7Y`&y($ z^429Ji{4-LtS{=_y7Xw}+p{ZH%zVE!=+R4=X4ajb6QT{WSJhl}jep zXD+&RX7buU750y1_gpx6I`)m_X?^`qZO5XoFPtX%Sk!IpsU_`*P&|A>RmQ~v~;-e12o>bx+o&DA6C(&lA9Y%Pm>_2Bv3 zH?}AD8Sg2axT`H&Lwq zIo*Y;K2)&o)~eh!>+aT`>z`|w?Q#D%*%z*DwkK2218BUfn5A;s* zms+2)(R_ON=gM4}{W=NpitEKcuHN})SBtqwUGTx#Q~#u!evP`f>iJu?f2%voXZ_6O z-k<$^zx9t=_4o5!EOgwJicGYQC$WW^9(l~>Yy4{0M3adtQ`CMMU+SFC^3!H#&l;8M z6Z9vSrZDfEd&hO#gtt!wKQXW2I{ErgQLM{7sj2t-B)_d{Q!YGQc(%gN{M&_+)|GqD z{L$QNzwhB^^PO+hv`g3RJUTsp^E)%?cLl$<-}$N=y)XIqcbg_x$CWxN>p4!ZR{r#B zMU1?0P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jFvWtrJ|#%m!r z*bdHPbvK(+S@86*t(cto9=RWTKAdmcB+#h(zj@s|(T|6ntku5kaM5kGZLT7uFNMlUHH$q3Yr1gYVlHDF`?iXgDbf@^yQ- zxGYu@6JDkDsBmGX({)v&RvDLDCm%k^C{lXq`KNnA&M^k=ptTYy&eLRX@;$Mf`2J9Y z`5n26Js*A<-0n|eUCOA#t;WOh`p}B*glv)g;~T<{PPFLDwpiXRH*3AY-s#TkjowSS z$38x?uchH&i;D3XF`g}lvYgvwon=mxDV=YvF^`e+`IOYffBDahl?ibQi3%FriLMf> zl_TU`Yk8tW-}Efj{n&WnXuHY(sV|RPeo^^s_h`jsPR5f3{)aQ%HnD1kMdWO_Wq6}e zM}1Rl!4AVq%@^Z*J|u3E51!i6_+X~OJl@1W2``q@iz7r2duzpYDzAB{8@tE(^ZS|i z4lS&nxm{mTVM(>rCQdeEA2F5aiAl{z`BpPa`lakjC|5q-{4maC^DqI}v7}hDMwLIWU_G0mOdDxq{tZQeXNOpyvzl2ATBY!Y#@zf{7N&5~4?M zNT{tSIR24aH&J26u_ux>JFa~zopr E00okh?EnA( literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/f01n0g08.png b/tests/fixtures/pngsuite/f01n0g08.png new file mode 100644 index 0000000000000000000000000000000000000000..4a1107b4637642335b8ec7b8e1856dc0ba7dab70 GIT binary patch literal 321 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I4h9AWhA=@@4F(2A4o?@ykcv62mlVB^I0~?S z_+D04_Kn4mqv>FRVT6ua_sKLN9+@jx!I5a0T8g(UfqG4!9x4lfykJ*Rh1_RqgoOYA literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/f01n2c08.png b/tests/fixtures/pngsuite/f01n2c08.png new file mode 100644 index 0000000000000000000000000000000000000000..26fee958ce7e62a59843205ad34f86a525718595 GIT binary patch literal 1180 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I4kiW$hCdQ-7c(%hBzw9zhE&X1JI(%$YN%w} z{O^DMo||L*{0)Z*i;_r0=S`>N#)&LK+8ZxSm=UmH?lCtmUk#lM4-E~S9>a}`48kTg zY&5+PG-2t|n}?hhbMmU{Tu*v;XYS3vZ`&43US4tD{ABIy{CCAAhc@)woS78_irM;0CYmUDix~>Pb=dU3aMAbt zBNHW;O^oc~*rqJZb+BW1&HYNX8)o|_f4v^x7H7hhd`UwmwBq)}k54BYu6>rxQKnvf zSp4rx^M(FjJQo|ya!Z}rx>;5-TyDzWx_O1$&i^|6Ix+8y*L+i{#o1?coKKXcgzPIh zcS0{Rf8WdKqdlW{bh|`0%l%pybI^Z>R{TfN`yY7iwM%N$d0HFg zkGQ^nY5d^$^5eqWCT%acx+v34}CeXI-8 z+?cVXXikSZo8|vS0!CwUVqHM?OM zUvBMGVAYwVET$Q#YN(pEOl{RgqqBbY_1p#T_n*?}=?vTwV$GHE^byy`6Q+yQU4s-{ zbtYX`JvZgdl$FQc-+#Euefz&NE27e@xsH@w61Z+~l3 z*C&@8Ta$VtP(fU=qw-jFl8Rf9RkB;${@G5NKEhjrR%b0WHEZ0!*07qocp2#s5gjzUDdKcTZ3cda5B{)@ZKiYM_)k09)y>SC4i}aI)n_|u=gz3rNvJ&~oIlUmW z{=A~dp_cVBtcTPDE-CPR+BD1Y^}e~*H>{onx(H6c5S6U)_`0Y)cgtdsGt~sVpEs>- xUfbMY<02B+)N<+Lxncnh_r?Ojj`)AvPVcI9o2sWjXJBAp@O1TaS?83{1OVloId1>} literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/f02n0g08.png b/tests/fixtures/pngsuite/f02n0g08.png new file mode 100644 index 0000000000000000000000000000000000000000..bfe410c5e7caaa19aa9f3294da29847720362d16 GIT binary patch literal 355 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I4h9AWhA=@@4F(2AEl(H6kcv627xlfH10`5L z9R6t`)~(Q?z|rK$!`$q9gIz)=qTSPgCyeDVH#hU)gonOO2|@>xHcIF;ISQ~ieyM#I ze|XvVo$n9r{dxT9oX-UXRyOO^F8_M+{f+bg|cEK#4 z*D)7V7vK*c+@MW5z&KeSQOQq`gXT643PRoxh;$Cp;l3u6Yf^Q45yX^v29(@t@ zDCOc){|nEPSa>#FeQ9jSR`oOX#g-Y2?rTpQY83L8+}gg>{}JDTH$^puR>4h*oPX@U zvO5cDug;c^wyvJ*Jh$1g^XXMr3GSwi3Sgq6NrCH;_{%5L_wPUR`Y$N-JYD@<);T3K F0RXgSmFfTh literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/f02n2c08.png b/tests/fixtures/pngsuite/f02n2c08.png new file mode 100644 index 0000000000000000000000000000000000000000..e590f1234816946731c677d0b353e2db5a08d71b GIT binary patch literal 1729 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I4kiW$hCdQ-7c(%hb$GfshE&YSz3SPaQYm`; zW4?=Sq<45~>f5WYc{&~)e7mUP!m-H;9Sist6~8!m+CjPE!m;Ld$qx$*n3XvC6gryU zGBrKW&{De8vExCL?UyNcx0b#Qy%{R{wZEr+pSa-6k2WrD;nzxzf2{veU-ACv|G!Sj zN8DbSZB6LD{$^(R&E5CY<$p}5{jsa|&Es#K{x_G~r^oL|jIX(vS9f#YC)3}*yubD4 z-_pLn?S0+(x)093Kl;BF-@hgP|FwTV)PJ9je;faQWA*86`x2{vmkC8ipV8@AC&8`x z`P3Yv)jryny_{zTsZI4vb=tY0M|<(96-JA$Oi@hrkPKm)65!})xHQ1Z%l+h3pFrNb zu8U3|3p%xE(}FYFn@{x^E%wn4_S)+&6@E->Y9OW;+HC#B`e7nb%lo+4L zOUsRWyJoK7l6t**S=qi>pM74WojEI(cW_Z_llLjtx5-QTCvM*7>#;ub@u?YKW+Wzh zXt{ALNjbD5Z(ZYTGjn&7^q6aQYN?K^vM$ZL7_cnp)u9y2*;5P?LnJ*{YMLfSNcw2I z9j<7qxD+F6o|@N|acsw;TAx#kzRWV4ZlrxxKR{CWl*=jB#286$$(20|r#PlM9J;3Q z(c&X(@#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N~x%lIwTsY@L`w2;-qu z$wzM%UDrCXfjtV?0P wm|8ARddbT1+pyZux=;7`vSi&$?0@8)?L?M`r`p;wFfcH9y85}Sb4q9e0Bmzg%K!iX literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/f03n0g08.png b/tests/fixtures/pngsuite/f03n0g08.png new file mode 100644 index 0000000000000000000000000000000000000000..ed01e2923c92fd8b8786524c6d6841365a44b9de GIT binary patch literal 389 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I4h9AWhA=@@4F(2AA5Ry@kcv6Amo|Dk1&SR1 z`2J;!OQ3)tucB*HfQSi;9-rfBX7+`O99>ERipUcrH!epxjhp7n* zuj2#x2m3!tU3p%4s=9oq%#VWiJHMA-DK)xzckkcBizmnY`?98@uCTJSHdt$VzP9M~ zwYx%nI~5u(+-~!_`)N^Yp4XNOyo*}b3F(@6Zn?m6(P{b-@m9CLU!VSbxv*@$JV)>2 zZneKtrROZ{{;}xy^3op$+g~*Cv?$0N*!|Y|IcEpc73R6GWWuIAF#I7l_h^UpgS8X4 zI;Efa{PS4pES46(+x%WjZ6$@QT17k5{U-NxR!V*U9^|7#Rz4o;x4kkW{Ip=fS?83{1OU1@rkDT# literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/f03n2c08.png b/tests/fixtures/pngsuite/f03n2c08.png new file mode 100644 index 0000000000000000000000000000000000000000..758115059d78260f7485521b83a864d4a930be84 GIT binary patch literal 1291 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I4kiW$hCdQ-7c(%hT=H~r45^q?J1w>&Bvs;g z{rNrV>Cewxm)sxqdxFj;{*9ZiX!PE4+CG8xu#=IKmTxQ9UI8AiD*lS(x`6Uaq2-r+ z!>cdmDjZabizrJJNP6npwD#Sbns;+*cUe52YiYcB_u<4D4`uG%|NY>gfkkHF z8;*9ZU9)ZV^;^H?H@&`g+g)z6^t>(7<~Ns{-+sRBR<8c7>2cfE_uRf-eyh{`?K{ui z&vkcym)-q7_V>N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= z>hwuQr}|`j`cEHe@$ox#Z||mh`@K~x83I4E#Zx7W*hIyquujr$@_6Y{^oNbFYO%S` zrRMPWS<7F3UzS&Mb&@zwfTL)u#?g+J$`=+6w|oD*3+P$ylC{IVbpDru^+}V&4Om-P zU8i5WSk#lstg`B>q0joPS0y|ZSFdhd5#DXI%C@cW_WSfDdtYfx{KD9_S1PF_O}Oo4 z_TCv+QgzlZp1EoDyCq8`%WL29GO$S;j?=vrem3MRd&!v}|CyKeP2W5H+_ZlT3=9mO Lu6{1-oD!M<89Q^B literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/f04n0g08.png b/tests/fixtures/pngsuite/f04n0g08.png new file mode 100644 index 0000000000000000000000000000000000000000..663fdae3e7d906df7379d92621a7a951313705cc GIT binary patch literal 269 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I4h9AWhA=@@4F(2=E1oWnAr*64FCNT2WFXS; z@cy^WXMN@_Ok!KYcYs%Od0xX6Z}k;ZbR)Q(6rUYnyv={x(xvL+^8YuxYVsec9g}e8 zxL2)zue11EWOlD1n{s+oKdaBArJVDe^l}?mt5`QEH^?%siTUjyx^0fu0YPr&_EQ3nGXqs{)jaEP^75kFZxEh6F3_MJ_4Sr@E0VLN}?o4;ab7<^=+ zwNG6VUZel|VE)J; Wrsl)0I5VLUcAJH-YmzJ|{A= zT5L%0nC`?Med7=t4@cfdo;g+9mpx&)ntIsd@uk<_OssD-9n`f8^I8}XzxML3qAB9% zdv;qcDePAFT6)E4=|0X(OU_wMO5OhFvb%I8Tumj-dumbHjUW8Kep+8T zv)CeN=I*$xMv>o2SGiVptO;^%HM6VH-ahd`_#wxYJzopB>gx|I6x00XuYQV2ccM^N z;?MZkSECR8++{bbeEVvRR8x;_rdvChyRDuqKfi6_1Mx$Z$Ez$JPg||R(9GA^<2F4aKKU=NGa#nT5mwCLu#5F7S-(Y<7ep?ZH%_{%wZKk_XWHCDi>z2K6oZZCE{a< zrg6wDReQdvmkRT5?mw*+Hc7S5tGn~pPmO->pM{+MUsiv9d#F&qJ@54tr%5{=%b$yF zOz&S=A1^U6VZwPv_n^5opH*|uZb^!|eAQ_6Z}I!g&)$}wne9-$%|7C|+O4>{6CZhw z`Gy2|Zt8cNsj^bnu4(0^bv4UpC>yZ!`SPoMzA^D|ih7{NQk97&FApB&S!NKt>%sHo zQccO?w~Jfkq^v4mwe1Q0^hz}LxNnw%LHM(SzuoyyZoIi{`un#0Uf!Gp-fWHyP5c{L z*m~uxO$3%PALV%)adt0PH3Qr6GWUJ$A2+|0d#C6iq4Vs-1$BYjZ&fB{dcXKn=)dfJ zqK7}fSlNTNT8oJEU+dU53G=#0JH0NJwcN6toso6&(^H4cehX>dIGwd-g3)8?w`-M5 z>U22UwQemp?w@Voye?NP<)bp+9t3W18S@YeQiYGMBHm@pT z*XC$l?i2R8q4|wDf8QxX{!dGJxVf(VXTEtWYhT}|#eWzW7#KWV{an^LB{Ts5t5eU! literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/f99n0g04.png b/tests/fixtures/pngsuite/f99n0g04.png new file mode 100644 index 0000000000000000000000000000000000000000..0b521c1d56ac6ba14d82547eea5c87dae391cfba GIT binary patch literal 426 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I76t|ehRF|4XfiM`7J9lkhE&Wc4czF*xr!~Pn)pNMZCzU zV56uzkB<@U(i z2W~FjnsF;kTeZ^I_^JPX*$p4A9j&gEfKamHREL`#*WJ)?VY7 zqWJvbn}<^;B>MC?mZjWFJuk1VerI83g~*wl-)kloJvdc)YuAcDs_|N@w_GawB-v0C zeM0b;C(jnyu4wbielD89ecu<@tL~2V)qDN*^^&lk`GJr7COGjNN!dAXwdB4@6DR5S g+uxSIfA&f}V?OKV=$7XtOF)s}>FVdQ&MBb@0NIVb^8f$< literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/g03n0g16.png b/tests/fixtures/pngsuite/g03n0g16.png new file mode 100644 index 0000000000000000000000000000000000000000..41083ca80f964707b6b89e1cc1266e381710175e GIT binary patch literal 345 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I0R{#J2DZkZ*$fN}Ea{HEjtmSPJN6#++`z!V zDB$Vh7*a83>s4Q_Lk0q@55m_(xdvz)jXfA_GX2ArIHm0ZF&s)wOCQDOmMS_L3ky4! zh&4*Scx}FP%f-KZYZrOEUwY;Dq6@!wWPUkV!Zi#+o*2RGf5-fN` zc-ZDO-S(CL^1HD~g;V59RU^}NEq@n(w)FXJ)9}7qwDYz{#uBsIjv3>#x0& zFDY5f_hn+3;b$(rwZYXPJm9>7Z@INZ7pI^4pGJMM#&L3q-eJOr`<#z6ZgpC}+HVmbrJ#E@9cejJW%+uA+Wt~$(696#3hJXM7 literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/g03n2c08.png b/tests/fixtures/pngsuite/g03n2c08.png new file mode 100644 index 0000000000000000000000000000000000000000..a9354dbee6f36cf88f7b6277d3fd43b6cabfd84a GIT binary patch literal 370 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I4kiW$hCdQ-7c($0u%tWsIx;YH?AUwMa{~hd zqo${eV@SoEr_+494mk+8tv3AU!XhYAuD9n%1xNpD#a|+NEaFB@5-D!!ZjTRjoK)$5 za(Kt4u&G{4XE2fS+!S~G=c1pd*jRp;H-Eg5Yqrui%-n+M!N$nV4=?0yFLB<@E?G03 zk&U@LdB)8=arNkP@`92zQyCX&{9bupb-O|{Geg#I{%;rN&vRU=(0qOuLyE)pr@MI8 ZMa_#;W{|xMk?H^d literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/g03n3p04.png b/tests/fixtures/pngsuite/g03n3p04.png new file mode 100644 index 0000000000000000000000000000000000000000..60396c95af19fc5f14aff9f83d391331a32b3dab GIT binary patch literal 214 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I7G?$phQ^Te;|vT8Ea{HEjtmSPJN6#++`z!V zAQ#{h;>y6l!0`Y7e}?}ICr+$g%W(HDhzH`|{r`XMf5Tl09SjT%$(}BbAr*6yHQ1R{ z6%5#z92F8A#1a@7f34tPZJO!85ZbjZZG^Cd2f^Y@Fe=W=JTGS1t2>~miG^9}0?H{3n+U=h24gA70Oiozdtj}x|jGKtWW z<<&^oSYT4Ix4>Y2wUo=m#f+?H(&n*UUb&d@tpk$*b9lpzgDHs z(ZJKiF{EP7)oHeQha3dl_D?-CzsH4{l~tFO{Q=v@g|#g*4NXmLO-&veK}vO#PKZcs zXpW!bUpQHF&DV{Qw%O;IXK-UE1*}-Pkz+;zCzdf5NhFSW-xdoRE8B-j>ujI{UC};bB{{Y(# zwzbnZ6`Fn`ebnKUIXKDJro zl=$V$2))gZl-AFiCZ6J8yqhs>^&7*={6AtT4h{LnGkgwJ{k@P9q%iTI9K-jtr5`PF z%bP0l+XkKf@A9?;?rjO%{Ww~_u6kh4*PmLrA~sN$tI*-S{Kl2R zzJl%YN0)ZZQsTSM!nK-p<20Am{nDLloWIY@hy!t$S-7 UZ|QQusUTN*y85}Sb4q9e0F9nj9{>OV literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/g05n0g16.png b/tests/fixtures/pngsuite/g05n0g16.png new file mode 100644 index 0000000000000000000000000000000000000000..70b37f01e2b9e13a30a6e9d3c51a114a2f0953ca GIT binary patch literal 339 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I0R{#J2DZkZ*$fN}Ea{HEjtmUfZd~z?Fk)a} z{XuATC4kC5Z_wcL5zcZP8}#CIlWFVI*Q9?KlT zvg7n=wO6;a4ltfpTW30jV-}n4iI;VD+!L3bUmnD8T3LXR@51hBPfO;@&8{zS3AldS sJwn>$L)Ay7js>eOG^KFK@!KEde;ePD#^kv90VuRQUHx3vIVCg!0LhhvF#rGn literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/g05n2c08.png b/tests/fixtures/pngsuite/g05n2c08.png new file mode 100644 index 0000000000000000000000000000000000000000..932c1365364fead1166e4772f29dcb7657f73f39 GIT binary patch literal 350 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I4kiW$hCdQ-7c($0u%tWsIx;X^yK%)o!ia%^ zQPk7LF{EP7(`lA`hYSQI;sC zocnQH|NO>9JMOGHEqNwo-7foedG6^9JZxA0T0Y_3!SSLjQ&mHtPjABe5|@Uo2`Wkr zJRBGDx*4u2^tm=Rg6-@w4uxjnC(^uvAL`kR986bScV&=dxxFZXE&Rpg zgMyzp8NXfNPjg_nx*)8XQ_D!fVMB09!=HA?S-W0t*>UX1nKPT7KhG=Hz-VQrYBs^z)@paD3ufOv)o{;a4xu;}wql#hL z>Fv8WUwROivf(2`g{b5jMR`}H2A;49{AmvLrx)&XHP5p2ojFHTC!B$Sfx*+&&t;uc GLK6TIIg{c5 literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/g05n3p04.png b/tests/fixtures/pngsuite/g05n3p04.png new file mode 100644 index 0000000000000000000000000000000000000000..9619930585eb3798db54058d41c09f6cd195c723 GIT binary patch literal 206 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I7G?$phQ^Te;|vT8Ea{HEjtmUfZd~z?Fk)a} zkPGk$ab;j&VEF(4%o&FNXZ|y+Tlb&ge|I;-e-L2!-~GS%k;)_n28L))7srr_Ims^= zngSFG7?~Uu5*)-57#M%82w-ZO>A(=)sN>)+n(2_h!%`r6f@#W11B0@{1jn$032zQP zYH()dm@-{_%HdE2ZiSTz3F(YkjzNKOeC6z$7-niQT;Zs&_IkS@6yy+3S3j3^P6@uB6%h@dCt_xH8VcxkEN|Jt^wcFsL44`X{hmG_ ze;#JKX~`Gx$RbO(CF=UtsOsCx>`oX}@a8!%Wd7niaExVw$~3mZoJ;}NX>3*v*A#ek zc}p19ItoZgtywMkfS=cgF^c*Ac9RQ?J-pxUUSRlt?s7_I1LKi|$a{>+k+UT4UN_d zPY6D4a?Qf{Gu`6Ju|Gvw4~|S$*a~3%mV?Vo&h29prJ~`E~Eog4b_& Y?3j)&ymCROSO*j~p00i_>zopr0B@gv`Tzg` literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/g07n2c08.png b/tests/fixtures/pngsuite/g07n2c08.png new file mode 100644 index 0000000000000000000000000000000000000000..597346460f1999fb225a46c941751a063ce744f4 GIT binary patch literal 340 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I4kiW$hCdQ-7c($0u%tWsIx;W{7Ia!igfTEM za(lWshE&YCI?a)**+9TmU8!@?j;|~`8?^Nwc)r?Lq_$r1?liGn%^R-Tp;q$7CJEMO zlzJ4;KMxP^Ju+RX;HYL@-Gk#Fc^OVknlFE_jwyyigG-Tt!`Wfp;>ix4yqkPDCP;NK z1~r?AGA&_CVldj##`Gqwfx%OWMS=NC$B~Bl#s+R26ZX0O&u3sPH<&IZ62xF6aj-6< zfbsKPBL}u9ZpH%&Qk^%<(ysb0p4T0|bq?e8IJVNY+vWzaHM1{xy=+yGG{Y1|rkb`h zNA3yjto+-{XrFnVCqaPMB`5oDUbd)UCL<@`O96M_uJo#|LglgsxQF8R^$h;7b}TjfzJUdIdD$lW>Eyq?p`_m4Y& z-{J`iGB5FV+1}XZ)MS0PIdR4^0cqiR*K_!P*&REUA$u*Ssq)>f&GN^7%oX0FGx-n4 zhwKyvhT~IA43B-Re#o*YH&an!xd?+!chJ8-3q8M`-?Hxc&Fd`ZSM%&)e8n+i|IJ=(JjAQ#qaFmV&reiJFD%l zhjIQ}wpr^l@890_jG=6^#B0eP=Ss?^FRbsXalaPq+q@}7X_b~7+i&|FISSblJ&%*N p=CDmZ_fPK4>k{6ezoCB^uB`P9xp%*R9s>gdgQu&X%Q~loCIEp+b2|V4 literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/g10n3p04.png b/tests/fixtures/pngsuite/g10n3p04.png new file mode 100644 index 0000000000000000000000000000000000000000..1b6a6be2ca571956ce45bae5470c03cd2266fd89 GIT binary patch literal 214 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I7G?$phQ^Te;|vT8Ea{HEjtq=#3k+XOi)Ub9 zkPGk$ab;j&ShNvQI>NzCvuoQ@%V4AYhz`)Nt!8z<;!klB% z8kRNnGA?3bIdz)*)MbeUS`U~UbUm~rZrp5WQ(CE^-@cnUvcX4`!R=A&$(dGyd<+Z> N44$rjF6*2UngEwaM=}5a literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/g25n0g16.png b/tests/fixtures/pngsuite/g25n0g16.png new file mode 100644 index 0000000000000000000000000000000000000000..a9f6787c7ab50968e37514529f53a6249762ca17 GIT binary patch literal 383 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I0R{#J2DZkZ*$fN}Ea{HEjttBfCj1EL@MmCP zH1l+E45^s2bjoSoLk2t!cZD2kl#ZnL<{fEdv|^8Ccqg-qse6Jc7stnTF$vmIfsjEfequXr2Aw%}OS_RsSLOm4hSWk^$CHE2Hk z(4U#BBYEM$j~&vzZ5JH464;hsp3nB&I8$Tc!KY2qXO~@gP&Jit1|#d1D5vJzyymxZ z7asikj(tk%fd(cv=9tUZ&+y3c-+58;hav4l%`Zli8H}tYyXzQ?7dXHAniIE{A6q-#z`U7{e=ub$6FCHEg)MoN2*?!xLK{94bgZzrgjEr&d51QgwC2Jh(moH|Sa4?j6fkJcsi}z(y8H|4L zC+sv)GMde5Y^GHCmwBz@`sb53nS9>KJ-K2614|NjF2|1 zIk7HT($_K`!ug^>bP0l+XkKCtEmz literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/oi1n2c16.png b/tests/fixtures/pngsuite/oi1n2c16.png new file mode 100644 index 0000000000000000000000000000000000000000..50c1cb91a0171e9f34991b079fe932f5f0bb16d6 GIT binary patch literal 302 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I0VW0phBY0A4;UC2SkfJR9T^zg78t&m7SF)I z@YK`AF{EP7)oBO0nhgY8mOpT;KV7%|@7izEvJU<1&fTQe}4O^Aoe0-!sktm@h{$dVyY}zw&8$% z$+9Ps8qUvSa+pnDyfI?>`of2?arcWeE7KS7&i(8uy}=<}UN52joQy_7uN>=-1J}{ dq{aDq2C*C7H{v%{#n*ydvd$@?2>_2bJ30UW literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/oi2n2c16.png b/tests/fixtures/pngsuite/oi2n2c16.png new file mode 100644 index 0000000000000000000000000000000000000000..4c2e3e3352babf7ab7b83c65bbd334a3e14f0632 GIT binary patch literal 314 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I0VW0phBY0A4;UC2SkfJR9T^zg78t&m7SF)I z(BSFf7*a9k>a>Gg%?1K4%O5z_pRU{fckQ=na%{|#+SJk}pQ(~)bA4iaZ9%_)6N8=p zgIVuWii+zbY}Jk9&prAaRlc3+^|=y_f@EIn1Un-WV}`ec{8{xckMKmFWw3=YIB--r$ffKeJ;&F#`ibD#$H*3GL@( zG!lB{SbrRU$1lsUE&Vy~7nk(+Y8T}9&OV^=MI+(6tVH*@-@RrA%yaifCdgH7K9KW8 zBcPtm26BKLh{w2#b$jCk s&I`I3{7ZZi?DN^*_a>Gg%?1K4%O5z_pRU{fckQ=na%{|#+SJk}pQ(~)bA4iaZ9%_)6N8=p zgIVuWii+zbY}Jk9&prAaRlc3+^|=y_f?ys$AzeQ8#nERl zcj+axpOeu@=#^vrar_;>EW@_+=e%EB(%-9Hkl#D|fW{Y%gzvHv-RFMyni(+9-5Z%8 zSGD;-&KHe=zk*q~J<#(0Knd iCxu6kG#MBem_Y9O7gr_DTgAY@z~JfX=d#Wzp$PyF;)s?2 literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/oi9n0g16.png b/tests/fixtures/pngsuite/oi9n0g16.png new file mode 100644 index 0000000000000000000000000000000000000000..9248413576d964953c7c15ee5f62c7ea5cfbb5e5 GIT binary patch literal 1283 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I0R{#J2DZkZ*$fN}Ea{HEjtq=#3k+XOi)Ub9 zVDxlx45=u4*76L-nRBsmQ9F!t^D=%$AIsluM3RBqu6J77{+lv{x7cC_0s29rT?sD^CsRUw#6_51f% zV_+Pk2k&(uYH(fZuH#SSLJq93~RBaE{+{dxZ`80Y47bMYB4PJgKV<473CeqLO_ zRT#&D!RlxkjMH$m;ok`uXL&-G_hJ}l$J-{iFc>HNuKCXWFplt=HXAdnoa8^vzMy0Q z4g-_`v3h5+BnqadNxN_U6Bs8UwM%9Lj3eu9Cuj)caHu{0dJD#xx$t!u2aLm@VNv@6 z#<_bT>T)BDgJSfznrB)EVKNSJPi!h+oKwM_VQw%EN{GH_dnvvMCL?y|&54~b4oYmZ z9gMzl7bfGh;Z9pHdqO3Qv*c&9lq8Jf6CP9$4CA20DN5qY|7yyp2vf$sE#`$cjPs_kA54$;NwcRP YU>p>g_{(n$dqJ7o)78&qol`;+0P#L$S^xk5 literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/oi9n2c16.png b/tests/fixtures/pngsuite/oi9n2c16.png new file mode 100644 index 0000000000000000000000000000000000000000..f0512e49f2306f1969bc9fcafedcb77f748b54f8 GIT binary patch literal 3038 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I0VW0phBY0A4;UC2SkfJR9T^zg78t&m7SF)I z!074X7*bL8tmPSuGv{LCqIMYP>b=J3%`nb1!w~P8FwVgv(f#LO9Ig{@r+kBPnqxZG z7r{6Nd=GtHU>pI{{@flI$0f4!M^Y^vMXHOVsZA1K`y)e$VnrB)EVH_0C$z3vc=!VI# z9gMzl7sg@UXs81USa7&aGPCS&fXTG!JdXYgZ5V)I}elxRc=0~F7x_ZppOhUqb${zB#-j1zzP zjbSg0b1vk`BzPi!lxFj94@~AWPtQF+7$<6R+fh&!0mo_iv&fm{Fd3AD#B|I|<_JvY zwfqA&2^a^(o|5{26K7#E8nV4tg5135j zruK7jFb+!azG!P6kXFN`QQQ`o6jvCWB&tPk2y4FiZv|=1`(!cS*PS z8<;W_15iqrmF-4pOJK^B z9F)>>8<$mfAWR0u+bBs4C9JO7QNT`(o2g zn9OYdr{*d!4oc2K2}Bgw!;Hm&6bWn-_+@TZT z9IPV)vlOMdg3^pI;q2**g(*XcIm>d}ub_q+*ahqJ0uN7wDZ8^g_OUpO({Qxm-w7B; z=yoH|0vN~Yoyn3Y7^nLE`>Qc9&c-Qm|31MuCoLo(1E~_vrX+3*(>^X}QwY3A`{Flwutvxu8^(DCN$FsjdBAUgTe~DWM4f4?$RT literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/pp0n2c16.png b/tests/fixtures/pngsuite/pp0n2c16.png new file mode 100644 index 0000000000000000000000000000000000000000..8f2aad7335206d0563ec5e8546bae83e16565080 GIT binary patch literal 962 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I0VW0phBY0A4;UC2SkfJR9T^zg78t&m7SF)I z)Dhql;>rL5#taN;3=A_F7|t*-{AVy`U@$gjFivAIp2=W*hQathNHWcsAuWv|Z6-t7 z8HTj~Ahk1%8D^$2%$&(E^9;kx{~)brj2X_PF`SvnaOModng0y`85sT>GyG3u_&<~3 z{~3n=|3LN)qoiR2(lV*Hortz6G#%KN;|7S4%Z*2TO&G`RJEK^{soP6L6NX=!KD(*A?|H`6$6W?I_J znQ1f6q|N*f^6nX9kmQ+}X=l!)o%x^kpCRqPaoYd1wEr{H{+~(v|9>VZ?2KoELTBbo zkpKUK!Up7}w3#4BpP6a=9~4v|i_>O;j6O3n?LR2wK+Kwg@82IT1fpg5Un4D!LunP)&o{|80U8Do%#K>Raj&ip^~pW)1Z<1_!$&itQw z=Kq;9|Nny`5FGs=SAb&_6rbQo0yzpC?x5%e2PMdj;LriZHrT@;CxiU}iu^OiprAT4 z6J#*h=>PvgvGo5x$WQ)(y ef0jK9jrTuu`WMH(`^Xzm-t%Im=&ab*AjV+Mva28Njo3}+Y^{xcXeFc=#%7^g89&txz@!(jX$B$;N+ke0@fHj^Rk z3`5#~klLBX3^UUhX3k`od4^%;e~{KQ#tdiD7|zUOICF;K%zuXe3=IE`8UCj+{GZA2 z{|v+b{~&`wMyDAw%rs^=W6ba$WRJ12v2mKQ@l0dmGsedMLDr@j8>giir_D4@J7b*o zALNRe#>O+#jAza?o_WT2=6{f*&KMh?Ni#k()A-C8<1_z_|1%i>H#YvCX8eDq@&7Z% z|Np0fykwjPa`enJkhA`Sd;qd3Ee&MWnKa}7AP=P(r-8uCw6rs6Y5zg~n`xXjGc9fA z%(R(j(q{e#dH0MlNb=0gv@>VY&iqgN&ye=tIPHI0+W(np|IeiT|34EHcE&S7p)+$P z$p8OAVFU6~+Dwq6&&)Lb4+<)f#c4A^MxU9P_8$~-AnCN3AaG{p%>ST(JYx*9_RP$g zXU@z#^MB@lhME73XZ}x{`G4lj|7T|Y|9=J)NycYD(J=E2D4_p?LLC%#X&|kj;P?-U zgf!zbATP~419J3#P@K#(2Kiv-%rhXP|AV6Fj4{YVApV&%Xa1l0&v53y@tOZ=Xa3JT z^Z(45|NlV|2#$V`E5I=dicfGPfgA-6cTn_#gA(LMaOi+y8|-0_lfixfMgAFMP*9zj z2{IUL^#A{$So;4TYjW(^>5+-ubaKIJo{J~7#NsOd|iErnSp^Jf#G0XXay)u$27=# fmzpy$Ff3|dmOlI~R9KWBq=3QG)z4*}Q$iB}HdA)w literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/ps1n0g08.png b/tests/fixtures/pngsuite/ps1n0g08.png new file mode 100644 index 0000000000000000000000000000000000000000..99625fa4ba1c6964446797075c47ee05dcae22f5 GIT binary patch literal 1456 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I4h9AWhA=@@4F(1VmUKs7M+U~W1%@xC#WOIl zN)-qAgcN61=q8sYr80n2{s*Zx29s%EaweEO11A52NMi;t307kaR$~lSV+>Yf3|5l{ zR+9!+lLl6k23C^>R+9!+GZU<4CRoi(u$q}*H8a6#W`fn60joI!R&xfd<_uWP8L*l& zU^V~2YW{=O{0FP~4_5OZtmZ#RjWGjAjWGjAjWGjAjWGjAjWGjAjWGjQ4cK4C#$YvI ze;I@QWeoP0G1y?^vCfHvy!Ty>F_Sa0Xzh;8{H52TwnP7j-1p8|y z*k3cj{+bE)*G#a#W`g~72JEjhV1Jzf`|AwYUuVGnIs^9C8L+?3fckQamXTbhC1NPS$u)ofL{dETHuQOnOodNsn4A@_1!2UV|_SYG(zs`XDbq4IOGhlz6 z0sHF=*k5PB{yGEp*BP+C&Vc=O2JEjhV1Jzf`|AwYU;n}W`VaQkf3Uy)gZ=d%?63b| zfBgsh>p$3E|H1zH5BAr8u)qF;{q-O0um50w{RjK&KiFUY!T$OW_Sb)~zy5>$^&jl7 z|6qUp2m9+k*kAv_{`wF0*MG3T{)7GXAMCIHV1NAw`|Cg0U;n}W`VaQkf3Uy)gZ-uS zKSPg!fx*$!#WAE}PI5|u3WEs8iOoE$tUdf3nm@kF+b2{S$cPx65}c5pvZykKhmEzT t|HG+&|Ihzue^zKHA!2aq!PL|g7KVVQ{|ZeX-G~GguAZ)bF6*2Ung9T8N>2a) literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/ps1n2c16.png b/tests/fixtures/pngsuite/ps1n2c16.png new file mode 100644 index 0000000000000000000000000000000000000000..0c7a6b380e9a2e60c887a260d43a41553260fc74 GIT binary patch literal 1620 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I0VW0phBY0A4;UC2SkfJR9T^zg78t&m7SF)I zDpefd6H=U6p_^Qql*+)tz`*dIfq{X+7)+*t$(dmC44C{6B8|anjKOM*!D@`bYK*~Z zjKONsz-rRKYSO@J(!grcz-rRKYG#7f%mk~M305-`tY#)y%}lVGGhj7mz-rEb)tmvV zIRjR62CU{kSj~U1n*U%m|G{ehgVp>8sWAro%NXo0V+N2KV+N2KV+N2KV+ODqu)mDK z{xSyp%NXo0W3a!B!TvG^`^y;YFJrL3jKTgg2K&nx>@Q=mzl_2DG6wt080;@&u)mDK z{xSyp%NXo0W3a!B!TvG^`^y;YFJrL3jKTgg2K&nx>@Q=mzl_2DN(1{V4eYNpu)os4 z{z?P;D-G?^vCfHvy!Ty>F_Sa0Xzh;8{H52TwnP7j-1p8|y z*k3cj{+bE)*G#a#W`g}S6YQ@uV1Jzf`|A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0AfM(f>;p$f>fHvlkZ5kdg!<3kzqE9LO~wQ()l?5`*c5g)>MDW-rJD5C*A% z>4k+eNDPEQ=E1@l#E0kw*$VM5hy~FLVnO^1Vu92$Fo0N)a0anpdST%VD(PT)Vc`rC zgXx8ZGe``k7m_bPCd0xRMDBo8tV5~>guOfSeK z5WNuhgJdDDfv{kDLFT~J!SsS?h!}_jVUP&Szp!uyiGgeZnFkAJkQl_jAYBkQgIEx~ zAQr@45DTIg!~*GpsRi->gUfUn3#Jzq&LCNsURXGT#9;Qq!WraFm|jpR0Wl92&LCNs zy&yM1WMSzURP(^}!qPKH3}!DRErQ$(5`pN2g)=BDV0uBZ36lk>1nGdKXOKFWn;~jI zvJjs@SRi*nSTMa1JrFUl-f0)Q+ZY%a96eneLn`JZrzEH_h;W?P%)`ps!_T4lh`}kr3F#?|Dr0!qSbO?Eocj0w{Ezl$g@zI$2B#iOO-*582zdIh(Dc!bNKg&z M>FVdQ&MBb@0FJmzdH?_b literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/ps2n2c16.png b/tests/fixtures/pngsuite/ps2n2c16.png new file mode 100644 index 0000000000000000000000000000000000000000..a4a181e4ecfc378abcba1a2af79c0aa96eae57e1 GIT binary patch literal 2484 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I0VW0phBY0A4;UC2SkfJR9T^zg78t&m7SF)I zQB@q^6H=U6p_^Qql*%B$00I9Y6oWAXjFkpw&4jbgz*+yHEMo=+I18rNm;t8Om;t8O zm;t62qzYn38eDH0+}<>}-ZZ%0G`L=nxe&cG;d*Dn_0ELroe9@F6RsEJ5{TY2aJ^^X zde6Z1o`LH<1J?_3J47#t1YwY`K|TQm+kd#;|8Twk;d((K1=0ZuDUdD(1`rFP7sLYj z2_gn^A%q3855fZJ2C+aYA*L8Z-3+2(dST%V5`*al*#OZ23ujQgfJ8y&!NM6N2D29y z&LAdO^O0gfoZ*5@%olu^?duVnOtRSdg#+v0!>(;S5TVFujoQ0GR^u z9fSqb3sMDgDJVo?_JVZ7#9;Qq(lbaMOfN_dq7D|$AXOj}L3Y5x86*aCGc24zVlX$u z!Wk5QFukyF28qG+!onFO2Ga|&9fUzHf$4>XGe``k7Z%PSF^FD}iy{66u^@UuERYHY z1`rFP7sP`27sP_;g@rRH_rmnT!Wkq6(+f!xAoD<~KrRJ^3d~+uID^Ds_Ci7iqyyql z2n%K}#0?-ZkS!4NK)PWpn7y!YhLj`_Sy(uO;o}AQng$Of882A6%xxSTMb?a0bc3^uod!BnGn=7S14d!t{bl35a>Ha0bc3 z>;<_AA`45;pqdA!7nYtuVlaClX%XaRkO)LCESy1M0n-bLO_(f5B}fM>J%iN2+ze3z zl7;vL!UDMq!h-3A=z)lV^-jCc-NwMc@YK`AF{EP7)oBO0nhgY8mOpT;KV7%|@7izE zvJU<1&fTQ ze}4O^Aoe0-!sktm@h{$dVyY}zw&8$%$+9Ps8qUvSa+pnDyfI?>`of2?arcWeE7KS7 z&i(8uy}=<}UN52joQy_7uN>=-1< eKg*tl#`~W+{flGYedG=d#Wzp$P!SsG*+# literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/s01i3p01.png b/tests/fixtures/pngsuite/s01i3p01.png new file mode 100644 index 0000000000000000000000000000000000000000..6c0fad1fc982e54aea994e12efd3fe3584cabdbc GIT binary patch literal 113 zcmeAS@N?(olHy`uVBq!ia0y~yU|Vh}gLC&ZP3;eS`frEmrY1};w*$B>FS$q5V$3``7+9_yDBGB7YO Nc)I$ztaD0e0st9I8UX+R literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/s02i3p01.png b/tests/fixtures/pngsuite/s02i3p01.png new file mode 100644 index 0000000000000000000000000000000000000000..2defaed911a29507f745bd7183a9819b29cc53de GIT binary patch literal 114 zcmeAS@N?(olHy`uVBq!ia0y~yU|<4aMrH;EM*I5p9~l@JSkfJR9T^zg78t&m7SF)I zz+CL)8N$NCQvPG>Vh}gLC&ZQE|9{CCeN_eq25wIm$B>FS$q5XM3=C`xjQ@JlPcSer OFnGH9xvXzopr04MMnm;e9( literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/s03i3p01.png b/tests/fixtures/pngsuite/s03i3p01.png new file mode 100644 index 0000000000000000000000000000000000000000..c23fdc463170faf97e53fccb4799386700b21a15 GIT binary patch literal 118 zcmeAS@N?(olHy`uVBq!ia0y~yU|*t(d3fq^Z+C&ZQEKg0iWhK)~`&Szj?;PG^E45^rtoY26`&cNWq;CSog SGZ_X31_n=8KbLh*2~7aFy&XCL literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/s03n3p01.png b/tests/fixtures/pngsuite/s03n3p01.png new file mode 100644 index 0000000000000000000000000000000000000000..6d96ee4f873baf1df3652a8d70994eeea799c30b GIT binary patch literal 120 zcmeAS@N?(olHy`uVBq!ia0y~yU|*t(d3fq^Z+C&cwXL;3&z470vF?_^+L5b<%M_9s+ bfkAQ|3**lF=HD0?7#KWV{an^LB{Ts5@*p4# literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/s04n3p01.png b/tests/fixtures/pngsuite/s04n3p01.png new file mode 100644 index 0000000000000000000000000000000000000000..956396c45b5103d3c38dd8906be14002e5bee48f GIT binary patch literal 121 zcmeAS@N?(olHy`uVBq!ia0y~yU|<1ZMrH;EhROCkwjfTrqpu?aW7`757t`Vy7#Ns~ zojgNWSXjz`Y+cO2z`z#Z6XN=xq5S`UhFRa8cQPc Tv1$7@kR=SBu6{1-oD!M<4yYZo literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/s05i3p02.png b/tests/fixtures/pngsuite/s05i3p02.png new file mode 100644 index 0000000000000000000000000000000000000000..d14cbd351ac11022eefcfa3bb2af528c3aadae41 GIT binary patch literal 134 zcmeAS@N?(olHy`uVBq!ia0y~yU|Vg?2V&H$efSBC%p%NhRvXJBw#vZ|PYfkD#K#WAE}PI5*zopr05}vQ1^@s6 literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/s05n3p02.png b/tests/fixtures/pngsuite/s05n3p02.png new file mode 100644 index 0000000000000000000000000000000000000000..bf940f057678363347961bbc920a0603b500d70d GIT binary patch literal 129 zcmeAS@N?(olHy`uVBq!ia0y~yU|Vg?2V&H$efSBC%p%NhRvXJBw#vZ|PYfkDL6#WAE}PIAQ60|r|g g6P0GfTxDR;VrQMOuIGyv0|Nttr>mdKI;Vst0Izu?=l}o! literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/s06i3p02.png b/tests/fixtures/pngsuite/s06i3p02.png new file mode 100644 index 0000000000000000000000000000000000000000..456ada3200643ae917af3ea3f9fa0df7471c0660 GIT binary patch literal 143 zcmeAS@N?(olHy`uVBq!ia0y~yU|<7bCT0c(##c+teHj=SSkfJR9T^zg78t&m7SF)I zz+CL)8N$NCQvPG>Vg?2V&H$efSBC!#4CVj-GyGrd%9p{wz@X&m;uumfCpjY_BVh)^ u5k4MW9&HI52_=bTY6d0&Mq#=P43_8F;x!BYo?>8NVDNPHb6Mw<&;$UQjv_1o literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/s07i3p02.png b/tests/fixtures/pngsuite/s07i3p02.png new file mode 100644 index 0000000000000000000000000000000000000000..44b66bab9e4ff6f2af2bd2f8c3c0a95c3b28e45c GIT binary patch literal 149 zcmeAS@N?(olHy`uVBq!ia0y~yU|Vg?2Vo&cW^*Z&OV4FAjj|7T!e_%H3ec@6^ugQ};CV@SoEWQzj@ z4G$R)v$yf`te5;}{3p?a@sK@Fc(O#^8OBKr2Osk^hBp1|WME)m@O1TaS?83{1OO0m BEQSC8 literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/s07n3p02.png b/tests/fixtures/pngsuite/s07n3p02.png new file mode 100644 index 0000000000000000000000000000000000000000..6a582593d654c8d43aa8c8dfa8f6516e4f24c8c4 GIT binary patch literal 138 zcmeAS@N?(olHy`uVBq!ia0y~yU|Vg?2Vo&cW^*Z&OV4FAjj|7T!e_%H3ec@6^ugOsO>V@SoEK|E5rZ)K|E5rZ)^rXKHESQJCJy$Y2}BYWveiK$wAnfx*+&&t;ucLK6T1jwWaT literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/s09i3p02.png b/tests/fixtures/pngsuite/s09i3p02.png new file mode 100644 index 0000000000000000000000000000000000000000..0bfae8e45678282b23bed2760c0dbbd736be9df8 GIT binary patch literal 147 zcmeAS@N?(olHy`uVBq!ia0y~yVBiE{CT0c(##cY?i83%Su%tWsIx;Y}EiimBEuMja zfw|bpGlYeOrToX%#S9D#JOMr-t_=Sf7|Q?uXZZiWoZ){MLka@}gR-ZKV@SoE6yQl=W+?s7?k3hVotc4wfx*+&&t;ucLK6U3)F+w% literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/s09n3p02.png b/tests/fixtures/pngsuite/s09n3p02.png new file mode 100644 index 0000000000000000000000000000000000000000..711ab8245189b4d5118b4dcd49ef9771bf924fb8 GIT binary patch literal 143 zcmeAS@N?(olHy`uVBq!ia0y~yVBiE{CT0c(hPnUWH8U_Uu%tWsIx;Y}EiimBEuMja zfw|bpGlYeOrToX%#S9D#JOMr-t_=Sf7|Q?uXZZiWoZ){MLka@}gS@AUV@SoEt~BdN|9uUYUV`fx*+&&t;ucLK6T3N+;m} literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/s32i3p04.png b/tests/fixtures/pngsuite/s32i3p04.png new file mode 100644 index 0000000000000000000000000000000000000000..0841910b72779aa7571cce45e56447eeb3de4520 GIT binary patch literal 355 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I7G?$p#&5ylfeZ``Ea{HEjtq=#3k+XOi)Ub9 zU@ms@3}InmDgUu`F#`jGdVo)eD+2?=e}-~~|NkKrL;3%55cB_kkVH91xE#d#x}VLO zfq~(Mr;B4q#hls+d-<9SMBMCM>mCK~khtEqQibn>+b%29!qt2_Z(15>t~Bmc`4F+~ zOPHpi+1crbcYc3n#vs%5_~eHt9&rzTeS6mRvc`SFiyi)EOb^Pk0%m7S+jzBb1@F~w z!J8tME%s3~h??;7_>prj-h4lENJF+mcWS~px6syA3r;mDsJwXK^Rh~-=>(<r~ZW zSP?6`>ePJ>wyw{YDK*KItm`+k<|}@5(THc>io!3fMsNNI%GR?kdh?+C#oEJFEk|6h xA6jbAvvkKlfgIH@t8EoG+}jjo{lC+^CFoMil($Ee85kHCJYD@<);T3K0RUiwmmB~9 literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/s32n3p04.png b/tests/fixtures/pngsuite/s32n3p04.png new file mode 100644 index 0000000000000000000000000000000000000000..fa58e3e3f69b3ad3cf92d96bc17b030d0fafbcb5 GIT binary patch literal 263 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I7G?$phQ^Te;|vT8Ea{HEjtq=#3k+XOi)Ub9 zU@ms@3}InmDgUu`F#`jGdVo)eD+2?=e}-~~|NkKrL;3%55cB_kkVH91xE#d#x}VLO zfq|jM)5S5QV$RfydwCla1Xv%0GjtYmN>@c~`((DDoKssp(SYB#=ecymIN2m4LGs?0|-jX4ocjrd&+C}*+tDEYX(_&d2 zqpt}(;a1^}3A{TVVKNT08>- z19P#HX9x=mOZktjiy0Ug)B}7%Tp1V`{xg&_{QnQ37|Q>bgP8ySgCxp9!sQ^=*ZpkP z3=9n4JY5_^D(1xY8x|ch5OB3WX`pe0_0ECG!WC}f9tRok>{z~NS+MuYNz=}4)&6B- z*T6S*|7y``m2#&i?F-B2JtFGdC!r1B z)iSePk4UX%@|w!{n)8?O5=~x~zndjuS0+vmyAmlXeabas!5>|l!ku$|>dpDM<8ff| z@dN4BI$taVWqaafI{A(<{&@B^Tl{JMx~RoG+Erh+y16`CWi#7(t>8VIRZ%H$6>t_%ze{~5{|{{M$i4CVjJLCpXEK@#O4;c^h`>wY$C z1_p+Go-U3d6?0k1uK5NLb2{_@K&;Y-Y46f~VFXzY?xV3QY(4e##h>FsvAdcB}Q zX4Ppv-Q9b5v;__@FF7{pIdhFyev3c>*HYHQ7cT34-5?gNon`1hBUP9uHpj)>BFZ}a z)rNK1K99qXG(VcS`?2fC6Sjp*E1pQ1g|0IWoRYope~6yd%Gh0ET}L#9o`=XO#lD@ literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/s34i3p04.png b/tests/fixtures/pngsuite/s34i3p04.png new file mode 100644 index 0000000000000000000000000000000000000000..bd99039be4a6c3a7a2a6048541436892bc4fd5ae GIT binary patch literal 349 zcmeAS@N?(olHy`uVBq!ia0y~yU{C^K7G?$p#{GF}=?n}EEa{HEjtq=#3k+XOi)Ub9 zU@ms@3}InmDgUu`F#`jGdVo)eD+2?=e}-~~|NkKrL;3%55cB_kkVH91xE#d#x}VLO zfq~(Yr;B4q#hlu{y`UU4~uWfe%P@$U}eQ$K5y5pEgZIj zyh^i{B}RC<%>LXnJ73rLj)0T%XREEL*QRMk&CDz^F*Wd;wJT_HHb-=<=ZT9~a#HdV zPfT?W+8-T1@#UwR)q$HA#0$B~F8XgK%9M1VKrL2h!TSK_>9L+?P4?KA{54*%Y*zsD pt)sD70mcHx`bM(t{}=pc_$c-NUDW*!O$G)A22WQ%mvv4FO#rn^k5>Qy literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/s34n3p04.png b/tests/fixtures/pngsuite/s34n3p04.png new file mode 100644 index 0000000000000000000000000000000000000000..9cbc68b3b9d5f263eb64bca9ad8bdfeae8205f63 GIT binary patch literal 248 zcmeAS@N?(olHy`uVBq!ia0y~yU{C^K7G?$ph7*}$9~l@JSkfJR9T^zg78t&m7SF)I zz+CL)8N$NCQvPG>Vg?2V^#Gp`R|W=#{|w~}|NlcMhVuXAAm;!7Ac=C2a5;$ebw8Um z0|P^@r;B4q#hj_{TVVKNT08>- z19P#HX9x=mOZktjiy0Ug)B}7%Tp1V`{xg&_{QnQ37|Q>bgP8ySgCxp9!sQ^=*ZpkP z3=E7co-U3d6?0N2*sf~|5NSF7gE_GKdznK-GTe!eS~OtHJ)`)CBXEnK(xR*TrYX-}uD(pqMi)o7^Ow#AK2R!+QR?ffZQJ?=c- z!nDx7ZO8SUqO-l_r_gd?=mN%DchZy`l`{m%{!soV^ zW#5b6>x|p+@z%YxU5}h@9xgqmpUQuozd#|`@kyI%p{9_qM5%A$?1>hK!rXik*v0HU q60K!F@cMK{FFw~PE?fAI{X*Bfg|jn7_!t-%7(8A5T-G@yGywqb9HWK+ literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/s35n3p04.png b/tests/fixtures/pngsuite/s35n3p04.png new file mode 100644 index 0000000000000000000000000000000000000000..90b892ebafc5b5318b2c4dd257eaca9377692ac5 GIT binary patch literal 338 zcmeAS@N?(olHy`uVBq!ia0y~yU{D5O7G?$phBx2WWic=?u%tWsIx;Y}EiimBEuMja zfw|bpGlYeOrToX%#S9D#>H$6>t_%ze{~5{|{{M$i4CVjJLCpXEK@#O4;c^h`>wY$C z1_p-Xo-U3d6?0NAD)Kcu2(&)DzGcd?8Q<7igeMd2}~OlRG8Z`JfU4_5z5h!l$vzuL3!{g2gFA)B$ zjGwA&S2Y&r-EGTvJ)82z_Ct!%H?})7d-l%$;gsw))%4t+@Qf#cDLh)t5AI92Eq=IB z?ZL*YpZxBJ7G?$p#uUx1whRmmEa{HEjtq=#3k+XOi)Ub9 zU@ms@3}InmDgUu`F#`jGdVo)eD+2?=e}-~~|NkKrL;3%55cB_kkVH91xE#d#x}VLO zfq~(sr;B4q#hl)Wd%2noMBMCe|GK>Wg;MNM&w~s11@126+L6gFUS3#GR>T)_;doY( z?;=m`wkMA(-tBc1>CoV?UVruDy^gTiKAvucUnbtRA6PBe0H#W*f3u>7&C9Dy!zMy0xmxxby4T*MVC$+Us;K;x))v)wW*yh{en1jrn&{H7q{5zE66;Abx+< xjg?vdn7481Bx>af>}D@5{kC#h)IUpmsTOg)-xBqQ7#J8BJYD@<);T3K0RSkyldb>& literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/s36n3p04.png b/tests/fixtures/pngsuite/s36n3p04.png new file mode 100644 index 0000000000000000000000000000000000000000..b38d179774ce64d3da2a9c3ab1e8c0fc5ce54771 GIT binary patch literal 258 zcmeAS@N?(olHy`uVBq!ia0y~yU{C>J7G?$p24TI{)eH;_Ea{HEjtq=#3k+XOi)Ub9 zU@ms@3}InmDgUu`F#`jGdVo)eD+2?=e}-~~|NkKrL;3%55cB_kkVH91xE#d#x}VLO zfq|ji)5S5QVoq`bL*t=$snb@uFHm6?Q&c#5ph+*~Kmki^N26$L24l0HU zqO}sNoTln1vgtVGNE|a~xZC=UL&wkcQ9w9{$cq(D+zn1WE1Y=dtYVkA(9)nHw$SO2 v6PtvYQNqTFjSVg?2V^#Gp`R|W=#{|w~}|NlcMhVuXAAm;!7Ac=C2a5;$ebw8Um z0|Uc9PZ!6KiaDthtc98k1ls-!%6<%d!7Jl;z(+6PA!EjywJTm`1P5KZwRG90?I#(F zG|Z(x8T^!(bY|1(?a~R8F1R^&hzZZ_Wz4!)%Ttrb+PG_;MuLuj%uJmPv!BeFwm+-S z`<$k7hoI)h6^{>T+__+pCvp7m37!BBPT$EY1`5+eMTN~26BpRum>9FTJE~Yw>tRQj zM6Frgjs?rT;-y^#=G~aEd&<^pUwO+dZOSqXuY_$3k6-PZbL;xGYu+`%b}xR5@72`b zlfLKw%#Tabzx%xWpiseir%<(mGp0efvq*nyPzCpi=nGH1p3N#g>9$qGFI#u7g~&a= jozva!ulu|#sH$F8U1XN>M*GbS3=9mOu6{1-oD!M<%x#|Z literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/s37n3p04.png b/tests/fixtures/pngsuite/s37n3p04.png new file mode 100644 index 0000000000000000000000000000000000000000..4d3054da516a3fc671bf5d2c4a401abe6886414a GIT binary patch literal 336 zcmeAS@N?(olHy`uVBq!ia0y~yU{D2N7G?$p2J;QJ1`G@gEa{HEjtq=#3k+XOi)Ub9 zU@ms@3}InmDgUu`F#`jGdVo)eD+2?=e}-~~|NkKrL;3%55cB_kkVH91xE#d#x}VLO zfq~(ur;B4q#hlcOx_r$J0&NfV7yABEf5678exrq3p^AY=u65n&wQG(%3R}PGcmV_7 z)tj12HyiWc6r3$kVeIf_(!82h&no4XhTsV{zxFLwE?uFO5_%|6#$XxSlrNn|g|6P` z_f3`3Ic;?OqxoaEikvJPj{dWndzWtuFSh!2J3CmdKI;Vst0FJ?lApigX literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/s38i3p04.png b/tests/fixtures/pngsuite/s38i3p04.png new file mode 100644 index 0000000000000000000000000000000000000000..a0a8a140ad7ec7f78f5b8cb398f54233e790fe7c GIT binary patch literal 357 zcmeAS@N?(olHy`uVBq!ia0y~yU{C{L7G?$pMqQC3+zbp1Ea{HEjtq=#3k+XOi)Ub9 zU@ms@3}InmDgUu`F#`jGdVo)eD+2?=e}-~~|NkKrL;3%55cB_kkVH91xE#d#x}VLO zfq~(cr;B4q#hj%R?YWyAWZLHci*SrzO1d{{%@5^wkgijA6xSsymV8$=DW@HjY8JTm&YBgY^(h~ yJ^SC2vIn#BlbWROzMeW=v-)_I)7Vg?2V^#Gp`R|W=#{|w~}|NlcMhVuXAAm;!7Ac=C2a5;$ebw8Um z0|P^rr;B4q#hl~>hQ>qhQm3tQPf%etGgLTxph+?9Kmm($Pot=F4r8-co5Te!AH$ro z2(5&|Zmpe3JU5QqFnF86u#5k&?u|P=XQV9*7o5Iul&2x-PDav!9hwOa;>?p$x)Tlg jXYXx3srz696T_!W?dEf9TpltoFfe$!`njxgN@xNAtpHa- literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/s39i3p04.png b/tests/fixtures/pngsuite/s39i3p04.png new file mode 100644 index 0000000000000000000000000000000000000000..04fee93eae400e745534756b48f5420cbe4a1d91 GIT binary patch literal 420 zcmeAS@N?(olHy`uVBq!ia0y~yU{D8P7G?$pM$WF92@DJjEa{HEjtq=#3k+XOi)Ub9 zU@ms@3}InmDgUu`F-UEIPlzi61H*rYa)$r^ArwRT|8fxX|9_A~IY_u1#QM6Q&6d%@#*r?y&0c}>l`8yLKE`9lV) zkT4-3j;DqPK5X6nUw=V$n(^Y0=4%N&B8z6a%+8$R5SSs@!}?U@=d`TvQCWXhmUVee z-M7K(vc*x;ueOf^`sB1;vF>`e__Kik_p7R4fdot0V~Qdnrr8H=MS7;(c)NvPm)BeQ z)e4)lvlbpY6R)>xjr`*~OYQv{N}IZbla8Irms2}pVf9+y{ZPwdC7%g8NB*64YT!oIY3a zc%GH~xtSkLQqR5JZF+yFz2CK(_wVYT)<65bm0!={Ro>dlzl=Q7OuzB`d-Q;Tfq}u( L)z4*}Q$iB}@Cvlw literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/s39n3p04.png b/tests/fixtures/pngsuite/s39n3p04.png new file mode 100644 index 0000000000000000000000000000000000000000..c750100d55fbd07d216bcc5af538a83b9f7772a3 GIT binary patch literal 352 zcmeAS@N?(olHy`uVBq!ia0y~yU{D8P7G?$phPqxKHUgYe7^F79C&ZP3f#E+xIm7?|5Q?Gve>sTx|365g93)&0Vtw7uX3fCB zaMjbrF{ENn?j=ROW(R@RhwdJ;r$|*bw+T-uXyoE+IJo$Ng^p0?(S_j;4P_dfOVd1^ z)6?n`j!6A5Vz{Fr^+(d|BG+>nA@!&W+jwmkvAH(xnDBIl`k7Unl6%!B?+v_My4qE= z@9~YwKU)_s`LpBKg5`g9y!x={&knD>w{Oi)x%#bj-{o5`4HC?sven(nP1zpW^*3GL z`I}wJ^miJeZzhV{NqpOOabuFYPx!lM=Sot~Coj|f{UyQ5WOiQ0@1NpQ<}dgzGJoT% sdU`ScZPL?u`fquTuX@AdKTThHnW?Du|M|}t7#J8lUHx3vIVCg!07uM~i2wiq literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/s40i3p04.png b/tests/fixtures/pngsuite/s40i3p04.png new file mode 100644 index 0000000000000000000000000000000000000000..68f358b822b92784fe065e4656061443a63795e1 GIT binary patch literal 357 zcmeAS@N?(olHy`uVBq!ia0y~yV9)?z7G?$pM$YR~PcSeru%tWsIx;Y}EiimBEuMja zfw|bpGlYeOrToX%#S9D#>H$6>t_%ze{~5{|{{M$i4CVjJLCpXEK@#O4;c^h`>wY$C z1_p*(o-U3d6?4}1ZRBb;5OH09G%EYIVC<6BDM2p+{;yc)$7o(!P$m@ES|EOW0e^PKW7tlvHLh?3y#}+T>k7J%yD2hR!?2 yxOVFtHAY2851A6q=8C)^+p`_nmt^;6#&L;d`4xPwu3%tbVDNPHb6Mw<&;$SlbdhcV literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/s40n3p04.png b/tests/fixtures/pngsuite/s40n3p04.png new file mode 100644 index 0000000000000000000000000000000000000000..864b6b9673b3b331f2956ad2299b7854210cdb41 GIT binary patch literal 256 zcmeAS@N?(olHy`uVBq!ia0y~yV9)?z7G?$phPn$&;}{qiSkfJR9T^zg78t&m7SF)I zz+CL)8N$NCQvPG>Vg?2V^#Gp`R|W=#{|w~}|NlcMhVuXAAm;!7Ac=C2a5;$ebw8Um z0|P^;r;B4q#hkMjHu5$Y@VH!b?$S}5wji-1$JNYZzUm4icGhOW6$1ZUUwAxxbTZ6u zdC*pwl~;buNV+57?x5(_FL{w6HBc_wJZ?QV_uP7?SD(M%m{nk5zQtT?iB5a2(4%Dx u;ZDAC54rYO;5Fw0^?*2Pz`xgs7F zxBo6He?R|s+{`;x6*F}mi~O~>bAJ%KI4N>Xzp=->Ls>ghl8gVVwVro;F)jCcS$FlC zziSeX%ud}M_SL3*_UB?&VZo}NVksHJdp4mTv{=ro@$`xAan8PR_FkMbvvAO|N6Nd` zKX7gq>zY`&oY5u!!nD{|k9+@wIP$EGV<{4_;1K_kRBR!F0F6H>w2^73|<498QjHCl%(-v-BoT|LA%qB)wNx^49$dp67E(Jw#$;ze*Nbs3& zw`5=BXJS>DVwJ{Yn0ChHaWVh4ohv{7tzTdk8L-Q-XMfA-r+xRn|F3^<{qgtzIX~7j z?}*@@bl~|D21{SDMIvVWoHf4RCRqhJczMaOm6nz_tc|{W;KmGY8EZ3Ey?rraMNH}^ zH8xIEN-}!d`07>4hQh~J4?Gl@BoMZ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8+gI-H{_)OB5vR3fJFmQYkh*T}hhJS^_m=Dbd-NiZXX6eF(UdebfjPz3 z)*e=Wd-JgF1&%xKxP2DPY-wj_dic=k(AiBsVG$aWb)(a^>P4#^`SHVNe|tfNRBoP_ z)6ycVP^~ys3*LJrYgEFU9wz=ddV=GeO>3(p%k9LoQuk^ePu{hwV9tw@-zQnsJ_r}? zEPGqDGsS3isG70FwKawkJ;%0Y_a5u$m}{-9)Kc-$l`nmnX^Y$Af((;AQN>bwSg%Yv zecR%9pxde*ODG(_r3Wwv%VdoF833dCX0*sA$%#qM{1pWr>|&$HDo+Z5)D^$UqVjO^ZDuHzEP{iE=^%)|FfxWiBV|M&Wf{A`||a=#WON`Y!< MPgg&ebxsLQ0OlFhZU6uP literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/tbbn3p08.png b/tests/fixtures/pngsuite/tbbn3p08.png new file mode 100644 index 0000000000000000000000000000000000000000..0ede3574db0fd51fa9266fb1cb91df3888dc8dbf GIT binary patch literal 1499 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I4rT@h2A3sW#~2tGSkfJR9T^zg78t&m7SF)I z^eDh5#P$FG{|#YbTet35;p8-b{``#!3f-cjbLY;LmX4e~do}|@%gmWG`cYI1HgJ^C0Jn3z%+ z7?Q#|!!$H%g1dt|JNwhq(^FGZV{>DLp9;6BspaeHx=eIQOiZ+%YwgnMVmsNEfnf>5 zX9k9k43UwM;o;$-p`pRS!6vOHfq{W4(^dTa{jIDV1q60&;^${L&cJY#;m@Bx42Kz5 zSf(=^WY8_w{q^e?!+r(^h75+i47aXa5fG^6T+8|6#}9^`3=G>D=FD06?b|n=g**(K z85lM)2uu`USk3V1()5elM~)mh!@zKvi>om^yTZws5TSy@R*Nl{TzK|#R`28O)6ysUz(sqf6mau@c8j#h6aX7Y;25-`6*$M3=AoLe%a^GpTB$e z0Ruzz$&)9=#2ghBBg4ZZU0f>m@8AFW?pwisqy(Q9a z)|w0P(b_8yr0sO5*?MoXsnu!AY@>r*T2rQHXWyUnX8)_|*J`U5Jv!3awRO^?^ev4E zwek@MxqsgLd{weGGXGRYX69An>vL_R!;f;Lth-hB!ZyP3T+Py*#!IG{1|0mPyRO~; zPV4(+NSvtpBYQLQFcvEK0p5T<}4hK)Yb#n}4(&b*r zwanE$XRE-RL#NN4)LpozV&kf7)4c7nj1M1XwOYWnOhxVO9jo^El*M}f<>z~jzAoQ0 z_1^6*tB*7+mRYsnamK5UYfmqGInV$8@pG59mb7nvk-jzdXz*;)#DgcdygxQ|uAh>0 z|NVQ{E}z|W=;zI&dwcIakKxn&AP z<)02mEEl;QeDhoFoHxtzPk%F$;|Qw!xl(GGLi+cqhmJH$&TA}xqyFXVjXl5boc{PL zHBZl-$;a`)zc1E`2mh5fzt4O0^xbX6s)?_YH~vdrnBH+CuKMk*e@B{sCRWb=QK7zb z$~)eCT`RTe*-ZfoWsg6x?tXmp`TOY4pE=)ue0eqB@@(j~kBUlgack{#D|}ge*5;dxu4md=+S1Fp=nlw2*VaGkw`g=LS z{fA@KH=brbSpBootbIm-7xTgHmuaFuo=8dv$vv2UoP~jR-T#Smr`|rmz`(%Z>FVdQ I&MBb@0P|^^UjP6A literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/tbgn2c16.png b/tests/fixtures/pngsuite/tbgn2c16.png new file mode 100644 index 0000000000000000000000000000000000000000..85cec395c01b305335172fe781aad11e485f45e1 GIT binary patch literal 2041 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I0VW0phBY0A4;UC2SkfJR9T^zg78t&m7SF)I zz*Z9E7yKU#=I!-10*NGfySp$j{Qu9uF!Nq#G6Ms9kEe@cNJQ(^8{9t9sWJ>7-cNBi z_|cK)(<>#W5-51_#*w7p8A%7krY+pMI8}LJnN5tWl7i2IkST|DT?&fgl9f#rkl-`l zZppsL&%~-Q#VU=*Fzt-X<6{18J6C@ETfe|8GGLcu&;FLvPy6nD|6l*!`s45abAGI6 z-Vwn)>A>?R43@rPi$u)$Ict2s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XIg(R zC%FG`top{&%m=G~R+_cXDDYxF*!?n1^v4rP2_d-$(~q+-@UHtmaqiUH2N)O_7(8A5 KT-G@yGywqIZJcZX literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/tbrn2c08.png b/tests/fixtures/pngsuite/tbrn2c08.png new file mode 100644 index 0000000000000000000000000000000000000000..5cca0d621047cacf1637cf7d77e997d51cc6b15a GIT binary patch literal 1633 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I4kiW$hCdQ-7c($0u%tWsIx;Y}EiimBEuMja zfvqISFPPy!2%1Mo*MdZnyxmBFf?%?1Zk71J1fOp5&k*_tzJHfEokCdi#+HaS+xNn`)-J9po|tF}M0FY)kyj)Lds z=H9z^@8rpo|0N3E-`l%w+qNxRwsdrKMAZK`aX)@pPR=&!ZS%y5^{f)|^6y{0I(7DJ zZ&z1POPgG2=~-jr%M4lytS4AjNiI8iaH01~8A+L%Z*Oh}F$M<*hp&&*)zsPK^D6o>@GsEA%e_y_Q`K5Hyy;F1N*sQ+S>j&Ds3F-_#K0R@(X9)Oqm;-6>#DHe*tlEaUr2c@893QdDD`= z;QzncqPY_%E<6<|Dk5^>Zjh7wp1#0u4<9~cWMoX*c;ou@@9*yJ{>)Hf`EusVZKB)W z1m|2&3ol){Ysr!&8#a76(kZ->`*z^oiRG(0ebi(+vRzAG`mPKKI?69&p)m1{x$$qQ7t707@3Ag= z^LFXlwQJcJp7fPZTAn@kwv}5^uu-UI@WPL4zJIZK92pQF5FZ~O9qn!I!m!G-pkRZK z*q*$*-w)(FD0gq2pXlN+W9rnJjEoZu3wG|TbbiXVh2j27hC_CWPoG?V)x5rB^MjDL zA>rZIFI;e7b}dzZAM)btY=5TB2TYY0m+R=k zre{N=r`qe6FAL8V9dm6EdCvZz{KvH)T(4VSFls4kiC**#5IVA8p=yIefuH=p%;@Ny z?d|gY)7eZ6d>nJ%dLC|=ZJxhN^KMB)NW-%Vq3o;Kty`U9<3k-nlomallRV+i$&@1D z$%S0=&xYmP6gu-TgK^T-&-Rk8Ssg6%J?ZJ=WhK^@54(!Q!toXYc;>sYoiyZa=RCE8ouD?*%znV)A$jI*m@8(u(7mFn@l2 zOuo;nH!?5x#BP>b?xR;mTwXwDoTEA`h5CBXC3DX#fu&p+d3VsG^Tn@*Z<#PQ)Kb* z+&RUZGTwrT=kMRX_U-8#@3e$eK0dx9BD3EV5Ayfz9qi%e(8z7`Oi zX5_ERw>w0 zxgz7p0>gXT^X1=){d)ZQ`T6+D8c+S*;`(thJBwPUnHgsEXg2rt^(~c&(MmYy=I*{V xO1D(p)^S?htFLnVjg5`JIMuFI&i_;TSG`W*PgdMqPf(q~;OXk;vd$@?2>{1W1`+@O literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/tbwn0g16.png b/tests/fixtures/pngsuite/tbwn0g16.png new file mode 100644 index 0000000000000000000000000000000000000000..99bdeed2b3b8564302d449e6578c4aca0f6261f5 GIT binary patch literal 1313 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I0R{#J2DZkZ*$fN}Ea{HEjtq=#3k+XOi)Ub9 zU@8gn3;zHA#Mb-ALA)eycbEVFMOGW0Wnf_0!(TCB!Aiz{`S~_KKPpGE z?Wx#UnjIUPm376>{BMgqH>*6SK<I*W7F#B-S5q@0cBVP2cQJ4_;cb?)WV zYgLk0=S>ffi3u~S{x(th{k?;{7RAfBfzBH?Lp6dGo$~Li!ro-hO(#4Gn-(oPbp5r>+{xZ4K|&~NqMuBqN`+Hv>o!C93}B-o9gzbl4s{y*Z*r`4Gj$poH((pX%k~odxhxI zq)Jy;uAKk>{`Dpu*p{35=i|$j{JVpGX{n!C6|CRgJ?YeMN$_kWSnmL)ZRD!gLbd=1jSzN%Zf%6qBo(zc0bS*LDJKR?$xKQ1mV zWy#c@oQ4f6w(U7Bq^hS_?znm9uMD<3J0{9ZOnf|XzVO}OYF2wyR;7d;nf=Fob6R7M zhd=-PB{Ixg{%`wPwK3UgR!v{hx8wbbB|p3hef054d)>i}-+F631tsUWURQGB7D+oZ z!!-NcoFgv&;Wrrq#g7(Wn*Vc3Wld$x)V}(kO=$<_+jFK*zJ2JsyNpgu;31iBy9-=T z+?*s9P;zdTsA#ID(&KaU6J=EP_J=oLclr>NU@+~?obMWmUWcXxTt3q^OS*A8_o}An z;^xhhu58JC`0&;6W~nfS*h(sZxpX7#m7&x0Sl zz4WS6Sl$2K8y?=NhGLHd=cE>fnZ&6C{rkOb%m4oyB^a2*^`1OiwrrX0xgB%Xif>pK zvT}d@qa(+TT?lY3t&5$<#>m)sb=BPGmjC}B&phz|fBwBKTbG6|{hXS{)*-I_<=eOK z;i0W9FU&u67F;h@mzq~$@bG{A9=3)@$yZmET>i4OPQN?7y!`vOX;WC(Z{PCL=C=MB zvFEZwc<i$8z*6u*DN%A-5m*tk izpnO=#D1=>>~w|)XQo{>HkT6ym3^MBelF{r5}E)DYm4>( literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/tbwn3p08.png b/tests/fixtures/pngsuite/tbwn3p08.png new file mode 100644 index 0000000000000000000000000000000000000000..eacab7a144cb54be28f7a5952a2fc63fd883766e GIT binary patch literal 1496 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I4rT@h2A3sW#~2tGSkfJR9T^zg78t&m7SF)I zbU(l+#P$FG{|#YbTet35;p8-b{``#!3f-cjbLY;LmX4e~do}|@%gmWG`cYI1HgJ^C0Jn3z%+ z7?Q#|!!$H%g1dt|JNwhq(^FGZV{>DLp9;6BspaeHx=eIQOiZ+%YwgnMVmsNEfnf>5 zX9k9k43UwM;o;$-p`pRS!6vOHfq{W4(^dTa{jIDV1q60&;^${L&cJY#;m@Bx42Kz5 zSf(=^WY8_w{q^e?!+r(^h75+i47aXa5fG^6T+8|6#}9^`3=G>D=FD06?b|n=g**(K z85lM)2uu`USk3V1()5elM~)mh!@zKvi>om^yTZws5TSy@R*Nl{TzK|#R`28O)6ysUz(sqf6mau@c8j#h6aX7Y;25-`6*$M3=AoLe%a^GpTB$e z0Ruzz$&)9=#2ghBBg4ZZU0f>m@8AFW?p@(X5g zcy=QV#7XjYcVXyYmGxj?VCwR8aSXBOO-@)~RPjNJxBrdpvZHDKIy3jz9MGEmGw#%u zwT-^{%|F_%hQ=!~2c%xk`VlrSbHkcBF`D}htlGP`_VD7;*z?H=n+(_gn)Z52q}{AF z7viI}R~|^)=}@!v-egm&)0Wvr2f4JSOwZ1~Kk3c>SJki8Rxf&Vq_b=5q(|vn8WU>e zBMx%^y!rX6WNl>rsf^6btH#&o+D3;T_?YQf`-S0C4&UiNaH|NZ0VE^RGo-~1wdYwXeB*`|pHPi}dCZ0cM;CF%bA z_pV(&yXnx+n@9Kd-g_R$y{3gVb!&CeJ;CF?+v>KzwY<6eIs_g02a8W+?=pICHLD4VZRG_y5na(cp!d#3gGa)SF0 z$Et5U&3v%>XQf&Di~=v_gWWIFM1MSyln|18F#R|S1Mj;36X#C7eSm?1fx*+&&t;uc GLK6TSKA5Bc literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/tbyn3p08.png b/tests/fixtures/pngsuite/tbyn3p08.png new file mode 100644 index 0000000000000000000000000000000000000000..656db0989ad8403c040f91caa6d1a79d11713715 GIT binary patch literal 1499 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I4rT@h2A3sW#~2tGSkfJR9T^zg78t&m7SF)I z^eDh5#P$FG{|#YbTet35;p8-b{``#!3f-cjbLY;LmX4e~do}|@%gmWG`cYI1HgJ^C0Jn3z%+ z7?Q#|!!$H%g1dt|JNwhq(^FGZV{>DLp9;6BspaeHx=eIQOiZ+%YwgnMVmsNEfnf>5 zX9k9k43UwM;o;$-p`pRS!6vOHfq{W4(^dTa{jIDV1q60&;^${L&cJY#;m@Bx42Kz5 zSf(=^WY8_w{q^e?!+r(^h75+i47aXa5fG^6T+8|6#}9^`3=G>D=FD06?b|n=g**(K z85lM)2uu`USk3V1()5elM~)mh!@zKvi>om^yTZws5TSy@R*Nl{TzK|#R`28O)6ysUz(sqf6mau@c8j#h6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ZWBK{nbQd;lkI&JS9+Dyln|@Vz zxfPVghh}D`9DK9$^CzXXDXm*$r?jv0OUYzsx;5fU6Q-?!uo>gtsjy{$C=50GT{H>iF{cEZc+#+4#0vGl4gguf~E>s;8@;%Q~loCIAkCP!RwC literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/tp0n2c08.png b/tests/fixtures/pngsuite/tp0n2c08.png new file mode 100644 index 0000000000000000000000000000000000000000..fc6e42cb420fd08ecd78340256157fa5f8a22934 GIT binary patch literal 1594 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I4kiW$hCdQ-7c($0u%tWsIx;Y}EiimBEuMja z^`obYV~9uR*=gK9lfy-h|Cbk$I@2x{Folh$ZKA?f1Le*H<`ohGM*=jLPH|LHdhjCQ z#O2P`g;T;cr+ojd=s1^W`8md7>BFf?%?1Zk71J1fOp5&k*_tzJa+j+{yXkbyRI|?9 zXA)n1{{5Ze^FQZz_n7DWkY~)hzwhq#>*l7WUuQ9vzrUB8pYQMQ-`~^I!_DDQUSjj~ z<;~R>@5syk^>66x?0om`-JU&rUcAVtjJP2fe!a%n*mMC)P@~R*w!~SiO?jf`Spzq4rRo;@~-iVtgd+LS&&H>dRVDamDm8fQ}biP{{8!xEmKofRW&sHm=O`tw>VjI`fY|ejOUnZ4=5CH zW~9wv^7dZZ?A*4qQZ0Z{gt2I&g`QrY*riXmZbflT6f)p9FfefN|797OF6!qupLsr` z?19K>y0>?2by3-sl5L%nP{2KdrH--glHz^_5gzAi-+$AO9yt=Q<}-t`va;7wBXe_e zZEbB`U0+Fw8<}}^$8JTveP3^3Y56t(^pw-l+w{ zA3c8T?Ci|U#I$SIu4jzz?(TM9XKZXdb?2!=hn%dUt9~9_E%DY)NlD4TAV5Xv=g*&a zcNVA1IaFIjN|sG6n=@JFx>$JV%vD>qY+145#gC7VGr4aI&Yf6(sxw4uZt>g4kCi8% z{1OsaS7%o|@nC3z)F!@2PfyOPL8+;!k&%&pe&;T-zPYf_SyA!#o3~SC{4`I?ZQIWO z?b9dQvNtp27%Efj(=M`}IgoZ`*^V7EVuTm$+BJ)-d7jqPu7A_k8Mit)O5WdJzdvHn z`7>{_6Bt@T zLR@@(?C!G2h#jAP3Qc0Lo$GV$_U+em-u7@aXrALg@czT=7r8?Yu07N1*JS3% zlNH7E;b(g3!}*&wPp+)`6&33Y^x(d7t?B*Skx+;}8Hy}EE zYJqm?;%9S`C;ahTY9u_FlWYFriTU?r4n56cm^5|qvSo=PE9w}&&MKd@-OS!=M##(r z77O0nTG2JDLuLAf`d6*eN(xwX=qtVk$2YF}=G0HX@i*6MFZ z($8$KEUGp5sF0D!eMk9j_}rLQc}CF-ydsCfA6s897Znw~vc)FO+JH^w%ZD3hpMQ=t z6Wifoed3&6Bu_vD8$@}-#o9xqD80=c@u818`_{+h?6}55EN z5>Ma0efy+@;nt(o=7yZ_UcQXv`S9ao^4ZGX&6h0yI8?a!w0yKou303_q}6dX=~Zsh z1U@g7NvWspl=@@xS~eGJv&`Q$IqG4n zuO3-orsjKZ$Hn6Z8cwxM65g2TeCh0L``2GLD=0XJhpb(@HtOSo#+kgCeN&F~NnAOW zwDHE-v%SYRo0@+8^3AW}Lqd_FdN<>6xsdMzzU?KY#yj&$;Q; zvu$-d}Th7mY)8y?U$GLy&rFX>4&}wIg`e4T%Lh} Ofx*+&&t;ucLK6Ukyyy-9 literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/tp0n3p08.png b/tests/fixtures/pngsuite/tp0n3p08.png new file mode 100644 index 0000000000000000000000000000000000000000..69a69e5872234d96cab4cbb017a0933fbfedba81 GIT binary patch literal 1476 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I4rT@h2A3sW#~2tGSkfJR9T^zg78t&m7SF)I zbU(l+#8pHjw;?QS>((7BoSf#*pTAK-p<7gR?%cW3(vh=g&t_m~nK^T2|MLFn)2C0J zI(72o$(ovB6DLk&V3^(C-`_p8TTgF!Z*Ok{14DOr_f7_e&dyFAo~sq5rS0wQ3=Er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eneB%=7wI2@DK(Tx?GAUE4W>fq{X+)78&qol`;+0CRJJS^xk5 literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/tp1n3p08.png b/tests/fixtures/pngsuite/tp1n3p08.png new file mode 100644 index 0000000000000000000000000000000000000000..a6c9f35a86271c056e955f637a8769381eb03827 GIT binary patch literal 1483 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I4rT@h2A3sW#~2tGSkfJR9T^zg78t&m7SF)I zbU(l+#P$FG{|#YbTet35;p8-b{``#!3f-cjbLY;LmX4e~do}|@%gmWG`cYI1HgJ^C0Jn3z%+ z7?Q#|!!$H%g1dt|JNwhq(^FGZV{>DLp9;6BspaeHx=eIQOiZ+%YwgnMVmsNEfnf>5 zX9k9k43UwM;o;$-p`pRS!6vOHfq{W4(^dTa{jIDV1q60&;^${L&cJY#;m@Bx42Kz5 zSf(=^WY8_w{q^e?!+r(^h75+i47aXa5fG^6T+8|6#}9^`3=G>D=FD06?b|n=g**(K z85lM)2uu`USk3V1()5elM~)mh!@zKvi>om^yTZws5TSy@R*Nl{TzK|#R`28O)6ysUz(sqf6mau@c8j#h6aX7Y;25-`6*$M3=AoLe%a^GpTB$e z0Ruzz$&)9=#2ghBBg4ZZU0f>m@8AFW?p@(X5g zcy=R=fq|*Z)5S5wqBl8Vfl9OJmO`Cu}lY|7+UoEs=J!)?A2>)?RraZKp%c z)_apptxj8J8y)1*nle2*`~IXi`(IVRR$IO3(UH!st&<+5Z)r@Zm5(^c{qyGMtCF>m z`KK~6Gp`z7pKBW(ev~6+-L1M8wh@l!YL@OaUNXfr;NU0Sb?yFlns+2ld~O;oSoiSf zD}xOsE00x8KdgSv(mB>r`{k6!n=)(m1gA`QIC$!?M^NR@l~T(T(!WnVbfj5wUSs(i^)Fv7?^v7SRd3x?lK8^?eeX&+N z_^-VAecq#|?`|trO?;ia@n7=7^o|>G)o*Y8JJS3!v2ym03iX{+-tp$^TB%LXZVFH+ zd;E!Y_v4$--$#G`%=!M~%d7d84+?helv=1T<#_Gp$S+fG)FeCBXLn2 zlQZW=(Y$*{Ro`0~K51M~6MbUQO`&YQO3}>Lq{-YtTn v?K29zm=AWpOcVX_L{dUX?!olqEDXHs{!g4c_4WY<1_lOCS3j3^P6I%RSkfJR9T^zg78t&m7SF)I z;OOb%7*a7OIVC}bL4@PPW*%179)1qZAK&He6Dkd4L<~*|PDoE#R2jp=#@f^W;nctX q=YO<6D>Rf4F*x;LYHA7#L%`F2g{F^gL^3ciFnGH9xvX{N literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/xc9n2c08.png b/tests/fixtures/pngsuite/xc9n2c08.png new file mode 100644 index 0000000000000000000000000000000000000000..b11c2a7b4049475d967a8cc76b93ef1039684a3a GIT binary patch literal 145 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I4o(IJ25rf#MGOoKEa{HEjtq=#3k+XOi)Ub9 z@bGkT45^s&_Ub`S1_K@@ht@X}|86f5wsz6}vhc^bhuT|sS*#nlM1IIDc>AQ*r^2C; xiQlVT{!k0Mh{lHnB^Jsn9U6BRlrKKO*tGFy9KXYPZw3Yi22WQ%mvv4FO#oG-FC_o~ literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/xcrn0g04.png b/tests/fixtures/pngsuite/xcrn0g04.png new file mode 100644 index 0000000000000000000000000000000000000000..48abba193ab36cb5a404b33a4b8f3d12e4646c4f GIT binary patch literal 145 zcmeAS@N?(omEvV!VBq!ia0y~yU{C;I76t|ehRF|4XfiM`u%tWsIx;Y}EiimBEuMja z!Nb$VF{ENnazcWDNJx;8Sy>?`udlbZe!7A)!_?as9s3xx%AffZu>|Z~9X3(9;ndx| vvt<}V-pw?A!m*&}{XJE8hN-{b$x1RY$cwyVeD&Y)7sxJ8S3j3^P6(j9#r85r9Z7`~Vm&%nUo z;pyTSQZeW4)q|W220Tm-t#2m&-CiVY?V|l<;g53zopr0J(iI0ssI2 literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/xd3n2c08.png b/tests/fixtures/pngsuite/xd3n2c08.png new file mode 100644 index 0000000000000000000000000000000000000000..9e4a3ff7accf4453ddcd58318f7048b326b44ad2 GIT binary patch literal 145 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;IW+ny(hVB!0HZd?Tu%tWsIx;Y}EiimBEuMja z!Nb$VF{EP7+p7mT84P%s99rK@{JXtK*xE(=%fcV$9%^slWwCDH68Rys;O&!Ip9+UY yCVsDW`9m%2A{rkSlvpUQbZFdNP`>y8W7Ec;ar_SFy%`u77(8A5T-G@yGywnu|1hcm literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/xd9n2c08.png b/tests/fixtures/pngsuite/xd9n2c08.png new file mode 100644 index 0000000000000000000000000000000000000000..2c3b91aa4f1220eeb2c32feb5a6be116a2ad4aa1 GIT binary patch literal 145 zcmeAS@N?(olHy`uVBq!ia0y~yU{Cy8W7Ec;ar_SFy%`u77(8A5T-G@yGywn|EHK{y literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/xdtn0g01.png b/tests/fixtures/pngsuite/xdtn0g01.png new file mode 100644 index 0000000000000000000000000000000000000000..1a81abef826f52b95708677c38c4b8e812e2f462 GIT binary patch literal 61 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;IMg|53hG<6jNCpN5mUKs7M+U~W1%@xC#e>8> MUHx3vIVCg!03C%3d;kCd literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/xhdn0g08.png b/tests/fixtures/pngsuite/xhdn0g08.png new file mode 100644 index 0000000000000000000000000000000000000000..fcb8737fa2505b43955e995d95c3d6972b85fe32 GIT binary patch literal 138 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I4h9AW2It^VUj_ySmUKs7M+U~W1%@xC#WOH4 zIC{D`hE&W+PDxN<5aBqnnTM6Nho3|9$9H-Agh~S$5rb2L6Vg)_RmSkJvG(+TIQ8%U o`5*1i3JoPh3{E|mnwrAG5b*S0q3NR=kswPvUHx3vIVCg!04nS%Z~y=R literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/xlfn0g04.png b/tests/fixtures/pngsuite/xlfn0g04.png new file mode 100644 index 0000000000000000000000000000000000000000..d9ec53ed94b34f50eeabf3029465e1106725ea2a GIT binary patch literal 145 zcmeAS@N?(llHy`uVBqrfa0y~yU{C;I76t|ehRF|4XfiM`u%tWsIx;Y}EiimBEuMja z!Nb$VF{ENnazcWDNJx;8Sy>?`m#??Be!7A)!_?as9s3xx%AffZu>|Z~9X3(9;ndx| vvt<}V-pw?A!m*&}{XJE8hN-{b$x1RY$cwyVeD&Y)7sxJ8S3j3^P6VBq!ia0y~yU{C;IMg|53hG<6jNCpN5mUKs7M+U~W1%@xC#e;-B zT^vIy=IEZ;$jNNL!+P=cC6-NI3fxsD`4dEKnhy4ICAzW)etgiSzv|VcB`rDUR;mWG zJr6bs7kVVPNpZionys``v8rlZ_pMFy^0Q7EWa`b;Ow4*avYFgIvH_5n(1I4kPrtXn@*Ai0lqAM=~`{$FzXTrh_d&!~yk9M~(xU jm=5*ig z1Fx75|M*Ye%~9fszCQo5t4q`SCAPs{TY`6P`~0syE$-_6FLtxJB`c;~XlT`7e`4wE zcd_%@0#3cZa~SR)TiOa-OWl9^Y|vb z+QuicYa#R8b+Hqp!dW9qD%ss)Z#2eEUvpw9Kl2_dd4>x!CmB|)PnmHqMlk3rr-xi3^ zsS0r2E+_cm(o5+tR^`o&erqz;Y-Xw}^*Z45y?@VzxytKH{auyr$|zjTmDVUZ%w`oE zJuxbrHKODvn_KLT#@Oj0PcBVojH{J%xS+0F{AK^d%wHRnmi^;Zczu_x=I>6&j=E5h drOZDWLMQv>83rBHVPIfj@O1TaS?83{1OVwOR=WTI literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite/z09n2c08.png b/tests/fixtures/pngsuite/z09n2c08.png new file mode 100644 index 0000000000000000000000000000000000000000..5f191a78ee5601a45f1add2a3ad7a77b7b1ae0f1 GIT binary patch literal 224 zcmeAS@N?(olHy`uVBq!ia0y~yU{C;I4kiW$hCdQ-7c($0EcbMA45_%a^`bXlgMt9_ zg;^U8{FWCh+hJHIkZ30xt}^NRg}k*3nM5@#`0rMJ@-EU{sPyUdLPp6GoT>rr-xi3^ zsS0r2E+_cm(o5+tR^`o&erqz;Y-Xw}^*Z45y?@VzxytKH{auyr$|zjTmDVUZ%w`oE zJuxbrHKODvn_KLT#@Oj0PcBVojH{J%xS+0F{AK^d%wHRnmi^;Zczu_x=I>6&j=E5h drOZDWLMQv>T@&2*m4ShQ!PC{xWt~$(696UISR()c literal 0 HcmV?d00001 diff --git a/tests/fixtures/pngsuite_ref.txt b/tests/fixtures/pngsuite_ref.txt new file mode 100644 index 0000000..fbc89eb --- /dev/null +++ b/tests/fixtures/pngsuite_ref.txt @@ -0,0 +1,176 @@ +PngSuite.png 256 256 c3a88ff4 +basi0g01.png 32 32 0da28714 +basi0g02.png 32 32 2e3fe285 +basi0g04.png 32 32 8d0f641b +basi0g08.png 32 32 c395683c +basi0g16.png 32 32 8b47d810 +basi2c08.png 32 32 2fb54036 +basi2c16.png 32 32 f3bb75e6 +basi3p01.png 32 32 4d8431a4 +basi3p02.png 32 32 e4dbb6bc +basi3p04.png 32 32 671f880f +basi3p08.png 32 32 39528682 +basi4a08.png 32 32 905d5b60 +basi4a16.png 32 32 9c7c3556 +basi6a08.png 32 32 a74df32c +basi6a16.png 32 32 285be560 +basn0g01.png 32 32 0da28714 +basn0g02.png 32 32 2e3fe285 +basn0g04.png 32 32 8d0f641b +basn0g08.png 32 32 c395683c +basn0g16.png 32 32 8b47d810 +basn2c08.png 32 32 2fb54036 +basn2c16.png 32 32 f3bb75e6 +basn3p01.png 32 32 4d8431a4 +basn3p02.png 32 32 e4dbb6bc +basn3p04.png 32 32 671f880f +basn3p08.png 32 32 39528682 +basn4a08.png 32 32 905d5b60 +basn4a16.png 32 32 9c7c3556 +basn6a08.png 32 32 a74df32c +basn6a16.png 32 32 285be560 +bgai4a08.png 32 32 905d5b60 +bgai4a16.png 32 32 9c7c3556 +bgan6a08.png 32 32 a74df32c +bgan6a16.png 32 32 285be560 +bgbn4a08.png 32 32 905d5b60 +bggn4a16.png 32 32 9c7c3556 +bgwn6a08.png 32 32 a74df32c +bgyn6a16.png 32 32 285be560 +ccwn2c08.png 32 32 40a6a67c +ccwn3p08.png 32 32 9192bfaa +cdfn2c08.png 8 32 2af2ddf8 +cdhn2c08.png 32 8 23cb0319 +cdsn2c08.png 8 8 d81f3e6b +cdun2c08.png 32 32 878a46a3 +ch1n3p04.png 32 32 671f880f +ch2n3p08.png 32 32 39528682 +cm0n0g04.png 32 32 b743ec84 +cm7n0g04.png 32 32 b743ec84 +cm9n0g04.png 32 32 b743ec84 +cs3n2c16.png 32 32 0a0758b6 +cs3n3p08.png 32 32 e1ccec94 +cs5n2c08.png 32 32 8423bc98 +cs5n3p08.png 32 32 8423bc98 +cs8n2c08.png 32 32 0a0758b6 +cs8n3p08.png 32 32 0a0758b6 +ct0n0g04.png 32 32 b743ec84 +ct1n0g04.png 32 32 b743ec84 +cten0g04.png 32 32 77c3d4de +ctfn0g04.png 32 32 fb03c836 +ctgn0g04.png 32 32 1495e441 +cthn0g04.png 32 32 6b22f4da +ctjn0g04.png 32 32 7ac255fd +ctzn0g04.png 32 32 b743ec84 +exif2c08.png 32 32 80d91236 +f00n0g08.png 32 32 0b907dec +f00n2c08.png 32 32 9ad4b08b +f01n0g08.png 32 32 2119c97f +f01n2c08.png 32 32 e31d06f2 +f02n0g08.png 32 32 c03634d7 +f02n2c08.png 32 32 ba0d4b27 +f03n0g08.png 32 32 3a9c7b91 +f03n2c08.png 32 32 6d296175 +f04n0g08.png 32 32 28fca0b1 +f04n2c08.png 32 32 c5c4baad +f99n0g04.png 32 32 f8617313 +g03n0g16.png 32 32 7c364c58 +g03n2c08.png 32 32 f6882c1f +g03n3p04.png 32 32 13427f49 +g04n0g16.png 32 32 71d8adfd +g04n2c08.png 32 32 92bcece3 +g04n3p04.png 32 32 8441c56f +g05n0g16.png 32 32 f968c4a8 +g05n2c08.png 32 32 754dcc75 +g05n3p04.png 32 32 2788ce48 +g07n0g16.png 32 32 3bd60fba +g07n2c08.png 32 32 304cc4f1 +g07n3p04.png 32 32 3977f102 +g10n0g16.png 32 32 a360b8f0 +g10n2c08.png 32 32 6df63c8c +g10n3p04.png 32 32 810df60d +g25n0g16.png 32 32 1197ce63 +g25n2c08.png 32 32 f3f12041 +g25n3p04.png 32 32 fb71efa9 +oi1n0g16.png 32 32 8b47d810 +oi1n2c16.png 32 32 f3bb75e6 +oi2n0g16.png 32 32 8b47d810 +oi2n2c16.png 32 32 f3bb75e6 +oi4n0g16.png 32 32 8b47d810 +oi4n2c16.png 32 32 f3bb75e6 +oi9n0g16.png 32 32 8b47d810 +oi9n2c16.png 32 32 f3bb75e6 +pp0n2c16.png 32 32 f3bb75e6 +pp0n6a08.png 32 32 0ee05c61 +ps1n0g08.png 32 32 c395683c +ps1n2c16.png 32 32 f3bb75e6 +ps2n0g08.png 32 32 c395683c +ps2n2c16.png 32 32 f3bb75e6 +s01i3p01.png 1 1 9f62cde3 +s01n3p01.png 1 1 9f62cde3 +s02i3p01.png 2 2 fc958ebf +s02n3p01.png 2 2 fc958ebf +s03i3p01.png 3 3 f53615d1 +s03n3p01.png 3 3 f53615d1 +s04i3p01.png 4 4 ce2b2aa8 +s04n3p01.png 4 4 ce2b2aa8 +s05i3p02.png 5 5 71f99a5f +s05n3p02.png 5 5 71f99a5f +s06i3p02.png 6 6 1707ae6e +s06n3p02.png 6 6 1707ae6e +s07i3p02.png 7 7 f3a27b20 +s07n3p02.png 7 7 f3a27b20 +s08i3p02.png 8 8 2eb65a34 +s08n3p02.png 8 8 2eb65a34 +s09i3p02.png 9 9 44d29bb4 +s09n3p02.png 9 9 44d29bb4 +s32i3p04.png 32 32 9410d2a5 +s32n3p04.png 32 32 9410d2a5 +s33i3p04.png 33 33 d001d86b +s33n3p04.png 33 33 d001d86b +s34i3p04.png 34 34 17cfe1ad +s34n3p04.png 34 34 17cfe1ad +s35i3p04.png 35 35 b8c8407d +s35n3p04.png 35 35 b8c8407d +s36i3p04.png 36 36 d5aec69b +s36n3p04.png 36 36 d5aec69b +s37i3p04.png 37 37 a1563224 +s37n3p04.png 37 37 a1563224 +s38i3p04.png 38 38 bdaf2e8a +s38n3p04.png 38 38 bdaf2e8a +s39i3p04.png 39 39 5cb9f129 +s39n3p04.png 39 39 5cb9f129 +s40i3p04.png 40 40 bf29afa5 +s40n3p04.png 40 40 bf29afa5 +tbbn0g04.png 32 32 5c8eaf83 +tbbn2c16.png 32 32 0370ef89 +tbbn3p08.png 32 32 9d56cd67 +tbgn2c16.png 32 32 0370ef89 +tbgn3p08.png 32 32 9d56cd67 +tbrn2c08.png 32 32 0370ef89 +tbwn0g16.png 32 32 b24d0a34 +tbwn3p08.png 32 32 9d56cd67 +tbyn3p08.png 32 32 9d56cd67 +tm3n3p02.png 32 32 e7daa7f5 +tp0n0g08.png 32 32 57965874 +tp0n2c08.png 32 32 679d24b4 +tp0n3p08.png 32 32 130aa165 +tp1n3p08.png 32 32 9d56cd67 +xc1n0g08.png corrupt +xc9n2c08.png corrupt +xcrn0g04.png corrupt +xcsn0g01.png corrupt +xd0n2c08.png corrupt +xd3n2c08.png corrupt +xd9n2c08.png corrupt +xdtn0g01.png corrupt +xhdn0g08.png corrupt +xlfn0g04.png corrupt +xs1n0g01.png corrupt +xs2n0g01.png corrupt +xs4n0g01.png corrupt +xs7n0g01.png corrupt +z00n2c08.png 32 32 67290c15 +z03n2c08.png 32 32 67290c15 +z06n2c08.png 32 32 67290c15 +z09n2c08.png 32 32 67290c15 diff --git a/tests/image/png.luau b/tests/image/png.luau new file mode 100644 index 0000000..2ab504b --- /dev/null +++ b/tests/image/png.luau @@ -0,0 +1,157 @@ +-- image/png tests: the whole PngSuite against reference decodes (pypng: tools/fixtures/_png_reference.py), the corrupt +-- x* files rejected (with checkCrc), generated images of every colour type / depth / interlace / filter, the encoder +-- (round trips for every colour type it picks, levels, text), the contract, and the fuzz no-throw pass. +-- Ported from png-luau tests/png.luau. Fixtures: tools/fixtures/png.py. +local T = require("@tests/T") +local Png = require("@formats/image/png") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Suite = require("@tests/gen/png_suite") +local Gen = require("@tests/gen/png_gen") + +local t = T.suite("png") + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return Png.decode(Bytes.reader(b), opts) +end + +-- the contract +t:eq(Png.name, "png", "name") +t:eq(Png.category, "image", "category") +t:check(table.find(Png.extensions, "png") ~= nil, "extensions") +t:check(Png.caps.decode and Png.caps.encode, "caps") + +local function verify(c: any, label: string) + local img, err = decode(c.data, { checkCrc = true }) + t:check(img, label .. ": " .. tostring(err)) + t:check(img.kind == "image" and img.format == "rgba8", label .. ": a standard rgba8 Image") + t:check(img.width == c.width and img.height == c.height, label .. ": size") + t:eq(buffer.len(img.pixels), c.width * c.height * 4, label .. ": pixel buffer size") + local crc = Crc32.of(img.pixels) + t:check(crc == c.crc, string.format("%s: pixels crc %08x, expected %08x", label, crc, c.crc)) + -- without the CRC check too, and at an offset inside a bigger buffer (the Reader's range) + local img2 = decode(c.data) + t:check(img2 and Crc32.of(img2.pixels) == c.crc, label .. ": no-CRC decode") + local big = buffer.create(#c.data + 10) + buffer.writestring(big, 7, c.data) + local img3 = Png.decode(Bytes.reader(big, 7, #c.data)) + t:check(img3 and Crc32.of(img3.pixels) == c.crc, label .. ": decode from a sub-range") +end + +local good, corrupt = 0, 0 +for _, c in Suite do + if c.corrupt then + local ok, img, err = pcall(decode, c.data, { checkCrc = true }) + t:check(ok, c.name .. ": threw " .. tostring(img)) + t:check(img == nil and Err.is(err), c.name .. ": corrupt file decoded") + corrupt += 1 + else + verify(c, c.name) + good += 1 + end +end +t:note("PngSuite: %d images match the reference, %d corrupt files rejected", good, corrupt) +for _, c in Gen do + verify(c, c.name) +end +t:note("%d generated images match", #Gen) + +-- sniff, info, palette, meta, limits +do + local c + for _, s in Suite do + if s.name == "basi3p04.png" then + c = s + end + end + t:eq(Png.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, "sniff a PNG") + t:eq(Png.sniff(Bytes.reader(buffer.fromstring("GIF89a......"))), 0, "sniff a GIF") + t:eq(Png.sniff(Bytes.reader(buffer.create(0))), 0, "sniff nothing") + local r = Bytes.reader(buffer.fromstring(c.data)) + local info = Png.info(r) + t:check(info and info.width == 32 and info.height == 32 and info.bitDepth == 4 and info.colorType == 3 and info.interlace == 1, "info") + t:eq(r:tell(), 0, "info does not move the reader") + local img = decode(c.data) + t:check(img.meta.palette and #img.meta.palette > 0 and #img.meta.palette[1] == 4, "palette table") + t:check(img.meta.source.format == "png" and img.meta.source.bitDepth == 4 and img.meta.source.colorType == "palette", "meta.source") + local _, e = decode(c.data, { maxPixels = 100 }) + t:check(e and e.code == Err.LIMIT, "maxPixels: " .. tostring(e)) + local _, e2 = decode("nope") + t:check(e2 and e2.code == Err.CORRUPT, "junk: " .. tostring(e2)) +end + +-- the encoder: round trips, colour type choice, levels, text +do + local rand = T.rng(99) + local function image(w: number, h: number, kind: string): Types.Image + local img = Types.Image.new(w, h) + for i = 0, w * h - 1 do + local o = i * 4 + local v = (i * 7 + (i // w) * 3) % 256 + local r, g, b, a = v, (v * 3) % 256, rand(256), rand(256) + if kind == "gray" or kind == "graya" then + g, b = r, r + end + if kind == "gray" or kind == "rgb" then + a = 255 + end + buffer.writeu8(img.pixels, o, r) + buffer.writeu8(img.pixels, o + 1, g) + buffer.writeu8(img.pixels, o + 2, b) + buffer.writeu8(img.pixels, o + 3, a) + end + return img + end + local CT = { rgba = 6, rgb = 2, gray = 0, graya = 4 } + for _, kind in { "rgba", "rgb", "gray", "graya" } do + for _, size in { { 1, 1 }, { 3, 2 }, { 37, 29 }, { 200, 3 } } do + local img = image(size[1], size[2], kind) + for _, level in { 0, 1, 6, 9 } do + local png, err = Png.encode(img, { level = level }) + t:check(png, kind .. ": encode: " .. tostring(err)) + local back, berr = Png.decode(Bytes.reader(png :: buffer), { checkCrc = true }) + t:check(back, kind .. ": decode our PNG: " .. tostring(berr)) + t:check(buffer.tostring(back.pixels) == buffer.tostring(img.pixels), string.format("%s %dx%d level %d: round trip", kind, size[1], size[2], level)) + t:eq(back.meta.source.colorType, kind, kind .. ": auto colour type") + t:eq(Png.info(Bytes.reader(png :: buffer)).colorType, CT[kind], kind .. ": IHDR colour type") + end + end + end + -- forced colour type, text chunks + local img = image(16, 16, "rgba") + img.meta.text = { Comment = "hello", Software = "formats-luau" } + local png = Png.encode(img, { colorType = "rgba" }) :: buffer + local back = Png.decode(Bytes.reader(png)) + t:check(back.meta.text and back.meta.text.Comment == "hello" and back.meta.text.Software == "formats-luau", "tEXt round trip") + -- the photo bench image compresses + local _, e = Png.encode({} :: any) + t:check(e and e.code == Err.ARG, "encode of a non-image returns Err.ARG") + local _, e2 = Png.encode(img, { colorType = "cmyk" } :: any) + t:check(e2 and e2.code == Err.ARG, "unknown colorType returns Err.ARG") +end + +-- fuzz: truncations, mutations (also of the IHDR fields) and garbage never throw +do + local samples = {} + for i, c in Suite do + if i % 4 == 0 then + table.insert(samples, c.data) + end + end + for i, c in Gen do + if i % 6 == 0 then + table.insert(samples, c.data) + end + end + t:fuzz("decode", function(b: buffer) + return Png.decode(Bytes.reader(b)) + end, samples, { mutations = 10, keepHeader = 8 }) + t:fuzz("decode checkCrc", function(b: buffer) + return Png.decode(Bytes.reader(b), { checkCrc = true }) + end, samples, { mutations = 2, garbage = 50 }) +end + +t:done() diff --git a/tools/bench.luau b/tools/bench.luau new file mode 100644 index 0000000..9f6aef7 --- /dev/null +++ b/tools/bench.luau @@ -0,0 +1,58 @@ +-- 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) and tools/fixtures/png.py (1024 x 768 images). +local Deflate = require("@formats/codecs/Deflate") +local Crc32 = require("@formats/core/Crc32") +local Bytes = require("@formats/core/Bytes") +local Png = require("@formats/image/png") +local B = require("@tests/gen/deflate_bench") +local PB = require("@tests/gen/png_bench") + +local runtime = if (_G :: any).jit ~= nil then "luajit" else "luau" + +local function bench(label: string, n: number, bytes: number, f: () -> ()) + f() + local dt = math.huge -- best of n: the machine is shared, the mean is noisy + for _ = 1, n do + local t0 = os.clock() + f() + dt = math.min(dt, os.clock() - t0) + end + print(string.format("%-8s %-30s %8.2f ms %7.1f MB/s", runtime, label, dt * 1000, bytes / dt / 1e6)) +end + +local z = buffer.fromstring(B.zlib) +local g = buffer.fromstring(B.gzip) +local out = assert(Deflate.zlib(z)) +assert(buffer.len(out) == B.size and Crc32.of(out) == B.crc, "bench corpus mismatch") +bench("inflate (growing output)", 5, B.size, function() + Deflate.inflate(z, 2, buffer.len(z) - 6) +end) +bench("inflate (exact size)", 5, B.size, function() + Deflate.inflate(z, 2, buffer.len(z) - 6, B.size) +end) +bench("zlib (+ adler32)", 5, B.size, function() + Deflate.zlib(z) +end) +bench("gunzip (+ crc32)", 5, B.size, function() + Deflate.gunzip(g) +end) +bench("crc32", 10, B.size, function() + Crc32.of(out) +end) +local part = buffer.create(1500000) +buffer.copy(part, 0, out, 0, 1500000) +bench("compress -6 (1.5 MB in)", 2, 1500000, function() + Deflate.compress(part, { level = 6 }) +end) +for _, c in PB do + local b = buffer.fromstring(c.data) + bench("png decode " .. c.name, 3, c.width * c.height * 4, function() + Png.decode(Bytes.reader(b)) + end) +end +do + local img = assert(Png.decode(Bytes.reader(buffer.fromstring(PB[1].data)))) + bench("png encode rgba8", 2, img.width * img.height * 4, function() + Png.encode(img) + end) +end diff --git a/tools/bench.sh b/tools/bench.sh new file mode 100644 index 0000000..c5dea4a --- /dev/null +++ b/tools/bench.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +# Timings (bash tools/bench.sh): tools/bench.luau under luau --codegen -O2 and under LuaJIT (the build output). +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 > /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/build.py b/tools/build.py new file mode 100644 index 0000000..9681a3a --- /dev/null +++ b/tools/build.py @@ -0,0 +1,440 @@ +#!/usr/bin/env python3 +# Build (python3 -I tools/build.py [roblox|luajit ...]): the two outputs of the one Luau source tree. +# +# build/roblox/Formats/... darklua convert_require (luau aliases -> Roblox instance paths). Types, --!native and +# @native are kept. Mounted by default.project.json (rojo build / rojo serve). +# build/luajit/formats/... plain Lua 5.1 for LuaJIT / LÖVE: darklua strips types, attributes (@native) and the +# Luau-only syntax, then the token passes below; requires become require("formats.a.b"). +# build/luajit/tools/... tools/*.luau (bench), built the same way. +# build/luajit/tests/... the tests, built the same way (require("@tests/T") -> require("tests.T")); tests/gen +# fixture modules are copied as they are (plain string literals; darklua is slow on them). +# +# Load the LuaJIT output with package.path = "build/luajit/?.lua;build/luajit/?/init.lua;" .. package.path, then +# local F = require("formats"). +# +# What darklua 0.19 cannot do, done here as token-level passes (lexer from imgui-luau tools/minify.py): +# 1. Generalized iteration (`for k, v in t do`): darklua has no rule for it. Every generic for whose iterator +# expression does not start with pairs / ipairs / next becomes `for k, v in __iter(expr) do` (compat's __iter: +# functions pass through with their state, arrays use ipairs, other tables next). +# 2. Luau stdlib names: each module gets, on its first line (line numbers stay the same), only the locals it uses of +# buffer, bit32, utf8, typeof, type, __iter from formats._compat (LuaJIT has a 60-upvalue limit per function). +# 3. If-expressions: darklua lowers `if c then a else b` to `(c and {a} or {b})[1]`, a table per evaluation. When +# `a` is provably not nil/false (a number or string literal, `#x`, or an arithmetic / concatenation expression +# at its top level) it becomes `(c and a or b)`. +# 4. Requires: `require("@formats/x/y")` -> `require("formats.x.y")`, `require("@tests/x")` -> `require("tests.x")`, +# done on the source before darklua (string literals only; computed requires are not allowed in the library). +import json, os, re, shutil, subprocess, sys, tempfile + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +SRC = os.path.join(ROOT, "src", "Formats") +TESTS = os.path.join(ROOT, "tests") +BUILD = os.path.join(ROOT, "build") +# darklua 0.19: $DARKLUA, else on PATH, else through nix +DARKLUA = os.environ.get("DARKLUA", "").split() or (["darklua"] if shutil.which("darklua") else + ["nix", "shell", "nixpkgs#darklua", "-c", "darklua"]) + +LUAJIT_RULES = [ + "remove_types", + "remove_attribute", + "remove_compound_assignment", + "remove_continue", + "remove_if_expression", + "remove_interpolated_string", + "remove_floor_division", + "convert_luau_number", +] +ROBLOX_RULES = [ + {"rule": "convert_require", "current": {"name": "luau"}, "target": {"name": "roblox", "indexing_style": "property"}}, +] +COMPAT_NAMES = ["buffer", "bit32", "utf8", "typeof", "type", "__iter"] + +# ------------------------------------------------------------------------------------------------ lexer +TOKEN = re.compile(r""" + (?P[ \t\r\n\f\v]+) +| (?P--\[(?P=*)\[.*?\](?P=ceq)\]) +| (?P--[^\n]*) +| (?P\[(?P=*)\[.*?\](?P=seq)\]) +| (?P"(?:\\.|\\\n|[^"\\\n])*"|'(?:\\.|\\\n|[^'\\\n])*'|`(?:\\.|\\\n|[^`\\])*`) +| (?P0[xX][0-9a-fA-F_]*(?:\.[0-9a-fA-F_]*)?(?:[pP][+-]?\d+)?|0[bB][01_]+|(?:\d[\d_]*(?:\.[\d_]*)?|\.\d[\d_]*)(?:[eE][+-]?\d+)?) +| (?P@?[A-Za-z_]\w*) +| (?P\.\.\.|\.\.=|//=|\.\.|==|~=|<=|>=|//|::|->|[-+*/%^]=|.) +""", re.S | re.X) + + +def lex(src): + """[(kind, text, start, end)] of the significant tokens (whitespace and comments dropped).""" + out, pos = [], 0 + while pos < len(src): + m = TOKEN.match(src, pos) + kind = m.lastgroup + if kind in ("ceq", "seq"): + kind = "lcom" if m.group(0).startswith("--") else "lstr" + if kind not in ("ws", "lcom", "com"): + out.append(("str" if kind == "lstr" else kind, m.group(0), m.start(), m.end())) + pos = m.end() + return out + + +def apply(src, edits): + """edits: [(start, end, text)], non-overlapping.""" + for s, e, t in sorted(edits, reverse=True): + src = src[:s] + t + src[e:] + return src + + +OPEN = {"(": ")", "[": "]", "{": "}"} +BLOCK_OPEN = {"function", "do", "then", "repeat"} # each closes with `end` (repeat with `until`) + + +def match_close(toks, i): + """index of the bracket closing toks[i] ( ( [ { ).""" + depth = 0 + for j in range(i, len(toks)): + t = toks[j][1] + if toks[j][0] == "op" and t in OPEN: + depth += 1 + elif toks[j][0] == "op" and t in (")", "]", "}"): + depth -= 1 + if depth == 0: + return j + return -1 + + +# ------------------------------------------------------------------------------------------------ pass 1: __iter +def pass_iter(src): + toks = lex(src) + edits = [] + for i, (k, t, s, e) in enumerate(toks): + if k != "name" or t != "for": + continue + # find `in` or `=` at depth 0 + j = i + 1 + while j < len(toks) and not (toks[j][0] == "name" and toks[j][1] == "in") and toks[j][1] != "=": + j += 1 + if j >= len(toks) or toks[j][1] == "=": + continue + first = j + 1 + # the expression runs to the `do` at bracket depth 0 and function depth 0 + depth, fdepth, comma, q = 0, 0, False, first + while q < len(toks): + qk, qt = toks[q][0], toks[q][1] + if qk == "op" and qt in OPEN: + depth += 1 + elif qk == "op" and qt in (")", "]", "}"): + depth -= 1 + elif qk == "name" and qt == "function": + fdepth += 1 + elif qk == "name" and qt == "end" and fdepth > 0: + fdepth -= 1 + elif qk == "name" and qt == "do" and depth == 0 and fdepth == 0: + break + elif qk == "op" and qt == "," and depth == 0 and fdepth == 0: + comma = True + q += 1 + if q >= len(toks) or comma: + continue + if toks[first][0] == "name" and toks[first][1] in ("pairs", "ipairs", "next"): + continue + edits.append((toks[first][2], toks[first][2], "__iter(")) + edits.append((toks[q - 1][3], toks[q - 1][3], ")")) + return apply(src, edits) + + +# ------------------------------------------------------------------------------------------------ pass 0: elseif +# darklua 0.19's remove_if_expression nests the elseif branches of an if-expression in reverse order (it folds them +# front to back): `if a then 1 elseif b then 2 elseif c then 3 else 4` becomes `a and 1 or (c and 3 or (b and 2 or 4))`. +# Before darklua, every `elseif` of an if-expression becomes `else if` (a nested if-expression, same meaning), so +# darklua only ever sees single-branch if-expressions. Statement ifs are told apart from expression ifs by the token +# before `if` and a stack of open constructs (blocks close with end / until; an expression if closes at its else). +EXPR_PREV = {"=", "(", ",", "{", "[", "return", "in", "and", "or", "not", "..", "+", "-", "*", "/", "//", "%", "^", + "#", "==", "~=", "<", ">", "<=", ">=", "+=", "-=", "*=", "/=", "//=", "%=", "^=", "..=", "if", "elseif", + "while", "until"} + + +def pass_elseif(src): + toks = lex(src) + edits = [] + stack = [] # "block" (function / do: end), "repeat" (until), "sif" (statement if: end), "eif" (expression if) + prev, prev_else_eif, prev_then_eif = None, False, False + for k, t, s, e in toks: + kw = t if k == "name" else (t if k == "op" else None) + else_eif = then_eif = False + if kw == "if": + expr = prev in EXPR_PREV or (prev == "then" and prev_then_eif) or (prev == "else" and prev_else_eif) + stack.append("eif" if expr else "sif") + elif kw == "then": + then_eif = bool(stack) and stack[-1] == "eif" + elif kw == "elseif": + if stack and stack[-1] == "eif": + edits.append((s, e, "else if")) + # the old expression closes at this else; the new nested one is still an expression if + then_eif = False + elif kw == "else": + if stack and stack[-1] == "eif": + stack.pop() + else_eif = True + elif kw in ("function", "do"): + stack.append("block") + elif kw == "repeat": + stack.append("repeat") + elif kw == "end" or kw == "until": + while stack and stack[-1] == "eif": # malformed input; keep going + stack.pop() + if stack: + stack.pop() + prev = t if k in ("name", "op") else k + prev_else_eif, prev_then_eif = else_eif, then_eif + return apply(src, edits) + + +# ------------------------------------------------------------------------------------------------ pass 3: if-expressions +ARITH = {"+", "-", "*", "/", "%", "^", ".."} +NOT_SAFE = {"and", "or", "not", "==", "~=", "<", ">", "<=", ">="} + + +def safe_truthy(toks): + """True when the expression toks always yields a number or a string (never nil / false).""" + if not toks: + return False + if len(toks) == 1: + return toks[0][0] in ("num", "str") + depth, arith = 0, False + for idx, (k, t, _, _) in enumerate(toks): + if k == "op" and t in OPEN: + depth += 1 + elif k == "op" and t in (")", "]", "}"): + depth -= 1 + elif depth == 0: + if t in NOT_SAFE or t == "function": + return False + if k == "op" and t in ARITH and idx > 0: + arith = True + if toks[0][1] == "#" and not arith: + # `#x` alone; `#x .. y` etc are covered by arith + return all(tk[1] not in NOT_SAFE for tk in toks) + if toks[0][1] == "(" and match_close(toks, 0) == len(toks) - 1: + return safe_truthy(toks[1:-1]) + return arith + + +def pass_ifexpr(src): + while True: + toks = lex(src) + edits = None + # ( C and { A } or { B } ) [ 1 ] + for i in range(len(toks)): + if toks[i][1] != "(" or toks[i][0] != "op": + continue + close = match_close(toks, i) + if close < 0 or close + 3 >= len(toks): + continue + if [t[1] for t in toks[close + 1:close + 4]] != ["[", "1", "]"]: + continue + # find `and {` at depth 1 + depth, a_open = 0, -1 + for j in range(i, close): + t = toks[j][1] + if toks[j][0] == "op" and t in OPEN: + depth += 1 + elif toks[j][0] == "op" and t in (")", "]", "}"): + depth -= 1 + elif depth == 1 and toks[j][0] == "name" and t == "and" and toks[j + 1][1] == "{": + a_open = j + 1 + if a_open < 0: + continue + a_close = match_close(toks, a_open) + if a_close + 2 > close or toks[a_close + 1][1] != "or" or toks[a_close + 2][1] != "{": + continue + b_open = a_close + 2 + b_close = match_close(toks, b_open) + if b_close != close - 1: + continue + a = toks[a_open + 1:a_close] + b = toks[b_open + 1:b_close] + if not safe_truthy(a) or any(t[1] == "," for t in a) or any(t[1] == "," for t in b): + continue + # rewrite: braces -> parentheses (a and b stay whole expressions), drop the [1] + edits = [ + (toks[a_open][2], toks[a_open][3], "("), + (toks[a_close][2], toks[a_close][3], ")"), + (toks[b_open][2], toks[b_open][3], "("), + (toks[b_close][2], toks[b_close][3], ")"), + (toks[close + 1][2], toks[close + 3][3], ""), + ] + break + if not edits: + return src + src = apply(src, edits) + + +# ------------------------------------------------------------------------------------------------ pass 2: compat header +def pass_header(src): + used = {t for k, t, _, _ in lex(src) if k == "name"} + names = [n for n in COMPAT_NAMES if n in used] + if not names: + return src + head = 'local __compat = require("formats._compat") local %s = %s ' % ( + ", ".join(names), ", ".join("__compat." + n for n in names)) + return head + src + + +# ------------------------------------------------------------------------------------------------ requires +REQ = re.compile(r'require\(\s*"@(formats|tests)((?:/[\w.]+)*)"\s*\)') + + +def luajit_requires(src): + def sub(m): + mod = m.group(1) + m.group(2).replace("/", ".") + return 'require("%s")' % mod + return REQ.sub(sub, src) + + +# ------------------------------------------------------------------------------------------------ darklua +def darklua(rules, src_dir, out_dir, cwd): + with tempfile.NamedTemporaryFile("w", suffix=".json", delete=False) as f: + json.dump({"generator": "retain_lines", "rules": rules}, f) + cfg = f.name + try: + r = subprocess.run(DARKLUA + ["process", "-c", cfg, src_dir, out_dir], cwd=cwd, capture_output=True, text=True) + if r.returncode != 0: + sys.stderr.write(r.stdout + r.stderr) + sys.exit("build: darklua failed") + finally: + os.unlink(cfg) + + +def files(root, ext=".luau"): + for d, _, fs in os.walk(root): + for f in sorted(fs): + if f.endswith(ext): + yield os.path.join(d, f) + + +def build_roblox(): + out = os.path.join(BUILD, "roblox", "Formats") + shutil.rmtree(os.path.join(BUILD, "roblox"), ignore_errors=True) + darklua(ROBLOX_RULES, os.path.relpath(SRC, ROOT), os.path.relpath(out, ROOT), ROOT) + n = sum(1 for _ in files(out)) + print("build: roblox %3d modules -> %s" % (n, os.path.relpath(out, ROOT))) + + +def build_luajit_tree(src_root, out_root, skip_dirs=()): + """src_root/**/*.luau -> out_root/**/*.lua through the require rewrite, darklua and the token passes.""" + tmp = tempfile.mkdtemp(prefix="formats-build-") + try: + stage = os.path.join(tmp, "in") + dl = os.path.join(tmp, "out") + count = 0 + for f in files(src_root): + rel = os.path.relpath(f, src_root) + if rel.split(os.sep)[0] in skip_dirs: + continue + dst = os.path.join(stage, rel) + os.makedirs(os.path.dirname(dst), exist_ok=True) + with open(f) as fh: + s = fh.read() + with open(dst, "w") as fh: + fh.write(pass_elseif(luajit_requires(s))) + count += 1 + if count == 0: + return 0 + darklua(LUAJIT_RULES, stage, dl, tmp) + for f in files(dl): + rel = os.path.relpath(f, dl) + with open(f) as fh: + s = fh.read() + s = pass_header(pass_ifexpr(pass_iter(s))) + dst = os.path.join(out_root, rel[:-5] + ".lua") + os.makedirs(os.path.dirname(dst), exist_ok=True) + with open(dst, "w") as fh: + fh.write(s) + return count + finally: + shutil.rmtree(tmp, ignore_errors=True) + + +def build_luajit(): + base = os.path.join(BUILD, "luajit") + shutil.rmtree(base, ignore_errors=True) + out = os.path.join(base, "formats") + n = build_luajit_tree(SRC, out) + shutil.copy(os.path.join(ROOT, "compat", "luajit.lua"), os.path.join(out, "_compat.lua")) + print("build: luajit %3d modules -> %s" % (n, os.path.relpath(out, ROOT))) + tout = os.path.join(base, "tests") + nt = build_luajit_tree(TESTS, tout, skip_dirs=("gen", "fixtures")) + gen = os.path.join(TESTS, "gen") + ng = 0 + for f in files(gen): + dst = os.path.join(tout, "gen", os.path.relpath(f, gen)[:-5] + ".lua") + os.makedirs(os.path.dirname(dst), exist_ok=True) + shutil.copy(f, dst) + ng += 1 + print("build: luajit %3d tests + %d fixture modules -> %s" % (nt, ng, os.path.relpath(tout, ROOT))) + # tools/*.luau (bench.luau): run with the same package.path + build_luajit_tree(os.path.join(ROOT, "tools"), os.path.join(base, "tools"), skip_dirs=("fixtures",)) + + +def selftest(): + cases = [ + ("for k, v in t do end", "for k, v in __iter(t) do end"), + ("for k, v in pairs(t) do end", "for k, v in pairs(t) do end"), + ("for k, v in next, t do end", "for k, v in next, t do end"), + ("for i = 1, 3 do end", "for i = 1, 3 do end"), + ("for _, x in f(function() for a in b do end end) do end", + "for _, x in __iter(f(function() for a in __iter(b) do end end)) do end"), + ] + for a, want in cases: + got = pass_iter(a) + assert got == want, (a, got) + ifs = [ + ("local a = (c and{v + 1 }or{0\n})[1]", "local a = (c and(v + 1 )or(0\n))"), + ("local a = (c and{v }or{w})[1]", None), + ("local a = (c and{x < 1 }or{w})[1]", None), + ("local a = (c and{#t }or{w})[1]", "local a = (c and(#t )or(w))"), + ("local a = (c and{(f(x) .. \"s\") }or{w})[1]", "local a = (c and((f(x) .. \"s\") )or(w))"), + ] + for a, want in ifs: + got = pass_ifexpr(a) + assert got == (want or a), (a, got) + els = [ + ("local x = if a then 1 elseif b then 2 elseif c then 3 else 4", + "local x = if a then 1 else if b then 2 else if c then 3 else 4"), + ("if a then f() elseif b then g() else h() end", None), + ("if a then x = if b then 1 elseif c then 2 else 3 elseif d then y() end", + "if a then x = if b then 1 else if c then 2 else 3 elseif d then y() end"), + ("return f(if a then 1 elseif b then 2 else 3), function() if p then elseif q then end end", + "return f(if a then 1 else if b then 2 else 3), function() if p then elseif q then end end"), + ("local y = if a then if b then 1 elseif c then 2 else 3 elseif d then 4 else 5", + "local y = if a then if b then 1 else if c then 2 else 3 else if d then 4 else 5"), + ] + for a, want in els: + got = pass_elseif(a) + assert got == (want or a), (a, got) + assert luajit_requires('require("@formats/core/Bytes")') == 'require("formats.core.Bytes")' + els = [ + ("local x = if a then 1 elseif b then 2 elseif c then 3 else 4", + "local x = if a then 1 else if b then 2 else if c then 3 else 4"), + ("if a then f() elseif b then g() else h() end", None), + ("if a then x = if b then 1 elseif c then 2 else 3 elseif d then y() end", + "if a then x = if b then 1 else if c then 2 else 3 elseif d then y() end"), + ("return f(if a then 1 elseif b then 2 else 3), function() if p then elseif q then end end", + "return f(if a then 1 else if b then 2 else 3), function() if p then elseif q then end end"), + ("local y = if a then if b then 1 elseif c then 2 else 3 elseif d then 4 else 5", + "local y = if a then if b then 1 else if c then 2 else 3 else if d then 4 else 5"), + ] + for a, want in els: + got = pass_elseif(a) + assert got == (want or a), (a, got) + assert luajit_requires('require( "@tests/gen/png_suite" )') == 'require("tests.gen.png_suite")' + print("build: self-test OK") + + +if __name__ == "__main__": + targets = sys.argv[1:] or ["roblox", "luajit"] + if "--test" in targets: + selftest() + sys.exit(0) + if "roblox" in targets: + build_roblox() + if "luajit" in targets: + build_luajit() diff --git a/tools/fixtures.py b/tools/fixtures.py new file mode 100644 index 0000000..08dce50 --- /dev/null +++ b/tools/fixtures.py @@ -0,0 +1,148 @@ +#!/usr/bin/env python3 +# Test fixtures (python3 -I tools/fixtures.py [filter] [--force] [--list]): runs every generator in tools/fixtures/*.py +# (or those whose name contains filter). Each writes Luau modules into tests/gen/ (gitignored) that return the fixture +# data as string literals, because the luau CLI has no file I/O; the LuaJIT test build copies them as they are, so +# both runtimes read the same bytes through the same require("@tests/gen/"). +# +# A generator is tools/fixtures/.py with: +# INPUTS = ["tests/fixtures/pngsuite", ...] # optional: files / dirs whose change triggers a rebuild +# def generate(ctx): ... # ctx.emit("png_suite", value), ctx.nix("imagemagick", [...]), ... +# A generator is skipped while all its outputs are newer than itself and its INPUTS (--force reruns it). +# +# ctx.emit(name, value): writes tests/gen/.luau returning value. Python values map to Luau: bytes -> string +# literal (any bytes), str -> string literal, int / float / bool, list / tuple -> array, dict -> table (string keys +# become fields). None is not allowed (nil cannot sit in a table): leave the key out. +# ctx.nix(packages, argv, input=None) -> stdout bytes: runs argv under `nix shell nixpkgs#...` (reference tools: +# ffmpeg, imagemagick, libwebp, flac, lame, opus-tools, ...). ctx.python(packages, code, input=None): a nix python3 +# with the given python packages (pypng, pillow, fonttools, msgpack, cbor2, ...). +# ctx.rng(seed): a random.Random. ctx.root / ctx.gen: paths. ctx.read(relpath) -> bytes from the repo. +import importlib.util, os, random, subprocess, sys + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +GEN = os.path.join(ROOT, "tests", "gen") +GENERATORS = os.path.join(ROOT, "tools", "fixtures") + +ESC = [chr(c) if 32 <= c < 127 and c not in (34, 92) else "\\x%02x" % c for c in range(256)] + + +def lit(b): + """bytes / str -> a Luau (and Lua 5.1 / LuaJIT) string literal""" + if isinstance(b, str): + b = b.encode() + return '"' + "".join(map(ESC.__getitem__, b)) + '"' + + +def luau(v, indent=1): + if isinstance(v, bool): + return "true" if v else "false" + if isinstance(v, (bytes, bytearray, str)): + return lit(bytes(v) if not isinstance(v, str) else v) + if isinstance(v, int): + return str(v) + if isinstance(v, float): + if v != v: + return "(0/0)" + if v in (float("inf"), float("-inf")): + return "math.huge" if v > 0 else "-math.huge" + return repr(v) + pad = "\t" * indent + if isinstance(v, (list, tuple)): + if not v: + return "{}" + return "{\n" + "".join("%s%s,\n" % (pad, luau(x, indent + 1)) for x in v) + "\t" * (indent - 1) + "}" + if isinstance(v, dict): + if not v: + return "{}" + out = [] + for k, x in v.items(): + if isinstance(k, str) and k.isidentifier() and k not in LUA_KEYWORDS: + key = k + else: + key = "[%s]" % luau(k) + out.append("%s%s = %s,\n" % (pad, key, luau(x, indent + 1))) + return "{\n" + "".join(out) + "\t" * (indent - 1) + "}" + raise TypeError("fixtures: cannot emit %r" % type(v)) + + +LUA_KEYWORDS = {"and", "break", "do", "else", "elseif", "end", "false", "for", "function", "if", "in", "local", "nil", + "not", "or", "repeat", "return", "then", "true", "until", "while", "continue"} + + +class Ctx: + def __init__(self, name): + self.name = name + self.root = ROOT + self.gen = GEN + self.outputs = [] + + def emit(self, name, value): + path = os.path.join(GEN, name + ".luau") + with open(path, "w") as f: + f.write("-- generated by tools/fixtures.py (tools/fixtures/%s.py) - do not edit\nreturn %s\n" % (self.name, luau(value))) + self.outputs.append(path) + + def rng(self, seed): + return random.Random(seed) + + def read(self, rel): + with open(os.path.join(ROOT, rel), "rb") as f: + return f.read() + + def nix(self, packages, argv, input=None): + if isinstance(packages, str): + packages = [packages] + cmd = ["nix", "shell"] + ["nixpkgs#" + p for p in packages] + ["-c"] + list(argv) + return subprocess.run(cmd, input=input, capture_output=True, check=True).stdout + + def python(self, packages, code, input=None): + expr = "with import {}; python3.withPackages (p: [%s])" % " ".join("p." + p for p in packages) + cmd = ["nix", "shell", "--impure", "--expr", expr, "-c", "python3", "-I", "-c", code] + return subprocess.run(cmd, input=input, capture_output=True, check=True).stdout + + +def load(path): + spec = importlib.util.spec_from_file_location("fixture_" + os.path.basename(path)[:-3], path) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +def mtime(p): + if os.path.isdir(p): + return max([os.path.getmtime(p)] + [mtime(os.path.join(p, f)) for f in os.listdir(p)]) + return os.path.getmtime(p) if os.path.exists(p) else float("inf") + + +def main(): + args = [a for a in sys.argv[1:] if not a.startswith("--")] + force = "--force" in sys.argv + os.makedirs(GEN, exist_ok=True) + stamps = os.path.join(GEN, ".stamps") + os.makedirs(stamps, exist_ok=True) + names = sorted(f[:-3] for f in os.listdir(GENERATORS) if f.endswith(".py") and not f.startswith("_")) + if "--list" in sys.argv: + print("\n".join(names)) + return + for name in names: + if args and not any(a in name for a in args): + continue + path = os.path.join(GENERATORS, name + ".py") + mod = load(path) + inputs = [path, os.path.abspath(__file__)] + [os.path.join(ROOT, p) for p in getattr(mod, "INPUTS", [])] + stamp = os.path.join(stamps, name) + if not force and os.path.exists(stamp): + outs = open(stamp).read().split("\n") + newest = max(mtime(p) for p in inputs) + if all(os.path.exists(o) and os.path.getmtime(o) > newest for o in outs if o): + print("fixtures: %s up to date" % name) + continue + ctx = Ctx(name) + mod.generate(ctx) + with open(stamp, "w") as f: + f.write("\n".join(ctx.outputs)) + size = sum(os.path.getsize(o) for o in ctx.outputs) + print("fixtures: %s -> %s (%.1f MB)" % (name, ", ".join(os.path.relpath(o, ROOT) for o in ctx.outputs), size / 1e6)) + + +if __name__ == "__main__": + main() diff --git a/tools/fixtures/_png_reference.py b/tools/fixtures/_png_reference.py new file mode 100644 index 0000000..17782ae --- /dev/null +++ b/tools/fixtures/_png_reference.py @@ -0,0 +1,55 @@ +# Reference decodes of the PngSuite (run once, the output is committed; from png-luau tools/png_reference.py): +# nix shell --impure --expr 'with import {}; python3.withPackages (p: [p.pypng p.pillow])' \ +# -c python3 -I tools/fixtures/_png_reference.py +# Writes tests/fixtures/pngsuite_ref.txt: " " per image, or +# " corrupt" for the suite's deliberately broken x* files. Pixels come from pypng (pure Python, exact at every bit depth) as RGBA, +# scaled to 8 bits the way png-luau does: 16-bit samples keep the high byte, 1/2/4-bit samples are scaled by +# 255 / (2^depth - 1). Pillow cross-checks every image without 16-bit samples. +import os, sys, zlib +import png +from PIL import Image + +ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +SUITE = os.path.join(ROOT, "tests", "fixtures", "pngsuite") + +def rgba8(path): + r = png.Reader(filename=path) + w, h, rows, info = r.asRGBA() + bd = info["bitdepth"] + out = bytearray() + for row in rows: + if bd == 16: + out += bytes(v >> 8 for v in row) + elif bd == 8: + out += bytes(row) + else: + m = (1 << bd) - 1 + out += bytes(v * 255 // m for v in row) + return w, h, bytes(out), bd + +lines, agree, checked = [], 0, 0 +for name in sorted(os.listdir(SUITE)): + if not name.endswith(".png"): + continue + path = os.path.join(SUITE, name) + if name.startswith("x"): + lines.append("%s corrupt" % name) # the suite's deliberately corrupt files (x*: bad signature, CRC, ...) + continue + try: + w, h, px, bd = rgba8(path) + except Exception as e: + lines.append("%s error" % name) + continue + lines.append("%s %d %d %08x" % (name, w, h, zlib.crc32(px))) + with open(path, "rb") as f: + raw = f.read() + if bd != 16 and b"sBIT" not in raw: + checked += 1 + im = Image.open(path).convert("RGBA") + if im.tobytes() == px: + agree += 1 + else: + print("pillow disagrees:", name, file=sys.stderr) +with open(os.path.join(ROOT, "tests", "fixtures", "pngsuite_ref.txt"), "w") as f: + f.write("\n".join(lines) + "\n") +print("%d images, %d rejected; pillow agrees on %d of %d checked" % (len(lines), sum(l.endswith(" error") for l in lines), agree, checked)) diff --git a/tools/fixtures/deflate.py b/tools/fixtures/deflate.py new file mode 100644 index 0000000..11e0e8a --- /dev/null +++ b/tools/fixtures/deflate.py @@ -0,0 +1,124 @@ +# Deflate fixtures (tools/fixtures.py): deterministic corpora compressed with Python's zlib at every level and +# strategy, raw / zlib / gzip framing, small windows, flushes, gzip headers and multi-member gzip; plus a 6 MB bench +# corpus. Ported from deflate-luau tools/fixtures.py. Reads Webamp skins (zips of BMPs) from $SKINS_DIR as data only, +# if present (the corpus is smaller without them; the tests do not depend on it). +# tests/gen/deflate.luau { corpora = { [name] = bytes }, cases = { { name, kind, corpus, data } } } +# tests/gen/deflate_bench.luau { size, crc, zlib, gzip } +import gzip, os, random, zipfile, zlib + +SKINS = os.environ.get("SKINS_DIR", "/tmp/wa-ref/webamp/packages/webamp-demo/skins") + + +def text_corpus(limit): + # Python's own stdlib sources: real text, deterministic for a given Python + 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 skin_bmps(limit): + out = bytearray() + if os.path.isdir(SKINS): + for name in sorted(os.listdir(SKINS)): + if name.lower().endswith(".wsz"): + with zipfile.ZipFile(os.path.join(SKINS, name)) as z: + for i in z.infolist(): + if i.filename.lower().endswith(".bmp"): + out += z.read(i) + if len(out) >= limit: + return bytes(out[:limit]) + return bytes(out) + + +def generate(ctx): + rng = random.Random(1) + def text_corpus(limit): + # Python's own stdlib sources: real text, deterministic for a given Python + 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 skin_bmps(limit): + out = bytearray() + if os.path.isdir(SKINS): + for name in sorted(os.listdir(SKINS)): + if name.lower().endswith(".wsz"): + with zipfile.ZipFile(os.path.join(SKINS, name)) as z: + for i in z.infolist(): + if i.filename.lower().endswith(".bmp"): + out += z.read(i) + if len(out) >= limit: + return bytes(out[:limit]) + return bytes(out) + + corpora = { + "empty": b"", + "one": b"a", + "text": text_corpus(160000), + "random": rng.randbytes(40000), + "runs": b"abc" * 4000 + b"\0" * 20000 + bytes(range(256)) * 40 + b"z" * 300, + "far": (lambda r: r + rng.randbytes(20000) + r)(rng.randbytes(12000)), + "bmp": skin_bmps(120000), + "binary": bytes(rng.choice(b"\0\0\0\x01\x02\xff ABC") for _ in range(30000)), + } + + cases = [] # (name, kind, corpus, compressed) + for cname, data in corpora.items(): + for level in range(10): + cases.append(("%s/zlib%d" % (cname, level), "zlib", cname, zlib.compress(data, level))) + for sname, strat in (("fixed", zlib.Z_FIXED), ("huffman", zlib.Z_HUFFMAN_ONLY), ("rle", zlib.Z_RLE), ("filtered", zlib.Z_FILTERED)): + c = zlib.compressobj(6, zlib.DEFLATED, -15, 8, strat) + cases.append(("%s/raw-%s" % (cname, sname), "raw", cname, c.compress(data) + c.flush())) + for wbits, mem in ((-9, 1), (-12, 9)): + c = zlib.compressobj(9, zlib.DEFLATED, wbits, mem) + cases.append(("%s/raw-w%d-m%d" % (cname, -wbits, mem), "raw", cname, c.compress(data) + c.flush())) + # flushes in the middle: empty stored blocks, byte alignment, several block types in one stream + c = zlib.compressobj(5, zlib.DEFLATED, -15) + parts = [] + step = max(1, len(data) // 5) + for i in range(0, len(data), step): + parts.append(c.compress(data[i:i + step])) + parts.append(c.flush(zlib.Z_SYNC_FLUSH if (i // step) % 2 == 0 else zlib.Z_FULL_FLUSH)) + parts.append(c.flush()) + cases.append(("%s/raw-flushes" % cname, "raw", cname, b"".join(parts))) + cases.append(("%s/gzip" % cname, "gzip", cname, gzip.compress(data, 6, mtime=0))) + + # gzip with a file name / comment / extra / header CRC (written by hand), and multi-member + def gzip_full(data): + hdr = bytearray(b"\x1f\x8b\x08\x1e\0\0\0\0\x00\x03") # FEXTRA | FNAME | FCOMMENT | FHCRC + hdr += (4).to_bytes(2, "little") + b"ab\x01\x00" + hdr += b"name.txt\0" + b"a comment\0" + hdr += (zlib.crc32(bytes(hdr)) & 0xFFFF).to_bytes(2, "little") + c = zlib.compressobj(9, zlib.DEFLATED, -15) + body = c.compress(data) + c.flush() + return bytes(hdr) + body + zlib.crc32(data).to_bytes(4, "little") + (len(data) & 0xFFFFFFFF).to_bytes(4, "little") + corpora["multi"] = corpora["text"][:50000] + corpora["runs"] + b"" + corpora["one"] + multi = gzip.compress(corpora["text"][:50000], 9, mtime=0) + gzip_full(corpora["runs"]) + gzip.compress(b"", mtime=0) + gzip.compress(b"a", 1, mtime=0) + b"\0" * 7 + cases.append(("multi/gzip-members", "gzip", "multi", multi)) + cases.append(("runs/gzip-fullheader", "gzip", "runs", gzip_full(corpora["runs"]))) + + + ctx.emit("deflate", { + "corpora": corpora, + "cases": [{"name": n, "kind": k, "corpus": c, "data": d} for n, k, c, d in cases], + }) + # bench corpus: ~6 MB of text and BMPs, zlib level 6 + bench = (corpora["text"] + corpora["bmp"]) * 1 + while len(bench) < 6_000_000: + bench += corpora["text"] + skin_bmps(600000) + corpora["binary"] + bench = bench[:6_000_000] + + ctx.emit("deflate_bench", {"size": len(bench), "crc": zlib.crc32(bench), "zlib": zlib.compress(bench, 6), + "gzip": gzip.compress(bench, 6, mtime=0)}) diff --git a/tools/fixtures/png.py b/tools/fixtures/png.py new file mode 100644 index 0000000..434adbb --- /dev/null +++ b/tools/fixtures/png.py @@ -0,0 +1,165 @@ +# PNG fixtures (tools/fixtures.py). Ported from png-luau tools/fixtures.py. +# tests/gen/png_suite.luau the PngSuite (tests/fixtures/pngsuite, licence in licenses/) with the committed reference +# decodes (tests/fixtures/pngsuite_ref.txt, from pypng: tools/fixtures/_png_reference.py) +# tests/gen/png_gen.luau images written by a small PNG writer here: every colour type and bit depth, plain and +# Adam7, odd sizes, every filter, split IDATs, tRNS keys; with the CRC-32 of the RGBA8 pixels +# tests/gen/png_bench.luau 1024 x 768 RGBA / RGB / Adam7 / palette images for tools/bench.luau +import os, random, struct, zlib + +INPUTS = ["tests/fixtures/pngsuite", "tests/fixtures/pngsuite_ref.txt"] + +# --- a small PNG writer +CHANNELS = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4} +PASSES = [(0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4, 4), (0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2)] + +def chunk(t, d): + return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d)) + +def pack_row(samples, depth): + if depth == 8: + return bytes(samples) + if depth == 16: + return b"".join(struct.pack(">H", s) for s in samples) + out, acc, nb = bytearray(), 0, 0 + for s in samples: + acc = (acc << depth) | s + nb += depth + if nb == 8: + out.append(acc) + acc, nb = 0, 0 + if nb: + out.append(acc << (8 - nb)) + return bytes(out) + +def paeth(a, b, c): + p = a + b - c + pa, pb, pc = abs(p - a), abs(p - b), abs(p - c) + return a if pa <= pb and pa <= pc else (b if pb <= pc else c) + +def filt(row, prev, bpp, ft): + out = bytearray([ft]) + for i, x in enumerate(row): + a = row[i - bpp] if i >= bpp else 0 + b = prev[i] if prev else 0 + c = prev[i - bpp] if prev and i >= bpp else 0 + pred = (0, a, b, (a + b) // 2, paeth(a, b, c))[ft] + out.append((x - pred) & 255) + return out + +def encode(w, h, ct, depth, px, interlace, rng, plte=None, trns=None, filters=None, idat_split=1, level=6): + # px[y][x] = tuple of samples at depth + ch = CHANNELS[ct] + bpp = max(1, ch * depth // 8) + raw = bytearray() + passes = PASSES if interlace else [(0, 0, 1, 1)] + for (x0, y0, dx, dy) in passes: + prev = None + for y in range(y0, h, dy): + xs = range(x0, w, dx) + if not len(xs): + break + row = pack_row([s for x in xs for s in px[y][x]], depth) + ft = filters(rng) if filters else rng.randrange(5) + raw += filt(row, prev, bpp, ft) + prev = row + z = zlib.compress(bytes(raw), level) + out = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, depth, ct, 0, 0, interlace)) + out += chunk(b"tEXt", b"Comment\0made by formats-luau tools/fixtures/png.py") + if plte: + out += chunk(b"PLTE", b"".join(bytes(c[:3]) for c in plte)) + if trns is not None: + out += chunk(b"tRNS", trns) + step = max(1, -(-len(z) // idat_split)) + for i in range(0, len(z), step): + out += chunk(b"IDAT", z[i:i + step]) + return out + chunk(b"IEND", b"") + +def rgba8(ct, depth, s, plte=None, palpha=None, key=None): + def sc(v): + return v >> 8 if depth == 16 else (v if depth == 8 else v * 255 // ((1 << depth) - 1)) + if ct == 3: + c = plte[s[0]] if s[0] < len(plte) else (0, 0, 0) + a = palpha[s[0]] if palpha and s[0] < len(palpha) else 255 + return bytes((c[0], c[1], c[2], a)) + if ct == 0: + return bytes((sc(s[0]),) * 3 + (0 if key == s[0] else 255,)) + if ct == 2: + return bytes((sc(s[0]), sc(s[1]), sc(s[2]), 0 if key == tuple(s) else 255)) + if ct == 4: + return bytes((sc(s[0]),) * 3 + (sc(s[1]),)) + return bytes(sc(v) for v in s) + +def image(w, h, ct, depth, rng, photo=False): + m = (1 << depth) - 1 + ch = CHANNELS[ct] + px = [] + for y in range(h): + row = [] + for x in range(w): + if photo: + base = [(x * 255 // max(1, w - 1) + rng.randrange(-6, 7)) & 255, (y * 255 // max(1, h - 1)) & 255, ((x + y) // 3 + rng.randrange(-3, 4)) & 255, 255 - ((x ^ y) & 63)] + row.append(tuple(v * m // 255 for v in base[:ch]) if ct != 3 else (base[0] * m // 255,)) + else: + row.append(tuple(rng.randrange(m + 1) if rng.random() < 0.5 else (x * 7 + y * 3 + k * 50) % (m + 1) for k in range(ch))) + px.append(row) + return px + +def make(w, h, ct, depth, interlace, rng, photo=False, **kw): + px = image(w, h, ct, depth, rng, photo) + want_key = kw.pop("key", True) + plte = palpha = trns = key = None + if ct == 3: + n = min(1 << depth, 256) - (1 if depth > 1 else 0) # leave an index past the palette now and then + plte = [(rng.randrange(256), rng.randrange(256), rng.randrange(256)) for _ in range(n)] + palpha = [rng.randrange(256) for _ in range(rng.randrange(n + 1))] + trns = bytes(palpha) if palpha else None + elif ct in (0, 2) and want_key: + key = px[h // 2][w // 2] if ct == 2 else px[h // 2][w // 2][0] + trns = b"".join(struct.pack(">H", v) for v in (key if ct == 2 else (key,))) + key = tuple(key) if ct == 2 else key + data = encode(w, h, ct, depth, px, interlace, rng, plte=plte, trns=trns, **kw) + exp = b"".join(rgba8(ct, depth, px[y][x], plte, palpha, key) for y in range(h) for x in range(w)) + return data, exp + + + +def generate(ctx): + suite = [] + for line in open(os.path.join(ctx.root, "tests", "fixtures", "pngsuite_ref.txt")).read().split("\n"): + if not line: + continue + parts = line.split() + data = ctx.read(os.path.join("tests", "fixtures", "pngsuite", parts[0])) + if parts[1] == "corrupt": + suite.append({"name": parts[0], "corrupt": True, "data": data}) + else: + suite.append({"name": parts[0], "width": int(parts[1]), "height": int(parts[2]), "crc": int(parts[3], 16), "data": data}) + ctx.emit("png_suite", suite) + + rng = random.Random(5) + cases = [] + for ct, depths in ((0, (1, 2, 4, 8, 16)), (2, (8, 16)), (3, (1, 2, 4, 8)), (4, (8, 16)), (6, (8, 16))): + for depth in depths: + for interlace in (0, 1): + for (w, h) in ((1, 1), (3, 2), (13, 11), (37, 29)): + data, exp = make(w, h, ct, depth, interlace, rng, idat_split=rng.choice((1, 1, 3))) + cases.append(("ct%d-d%d-%s-%dx%d" % (ct, depth, "adam7" if interlace else "plain", w, h), w, h, data, exp)) + for ft in range(5): # one filter for the whole image + data, exp = make(41, 23, 6, 8, 0, rng, filters=lambda r, ft=ft: ft) + cases.append(("filter%d" % ft, 41, 23, data, exp)) + data, exp = make(41, 23, 0, 2, 1, rng, filters=lambda r, ft=ft: ft) + cases.append(("filter%d-grey2-adam7" % ft, 41, 23, data, exp)) + data, exp = make(200, 150, 6, 8, 0, rng, photo=True, idat_split=40) + cases.append(("photo-200x150-40idat", 200, 150, data, exp)) + data, exp = make(64, 64, 2, 8, 0, rng, key=False, level=0) + cases.append(("stored-zlib", 64, 64, data, exp)) + + ctx.emit("png_gen", [{"name": n, "width": w, "height": h, "crc": zlib.crc32(exp), "data": d} for n, w, h, d, exp in cases]) + + # --- bench images (Paeth / up / sub mix, as encoders choose) + bench = [] + for label, ct, interlace in (("rgba8", 6, 0), ("rgb8", 2, 0), ("rgba8-adam7", 6, 1), ("palette8", 3, 0)): + data, exp = make(1024, 768, ct, 8, interlace, rng, photo=True, key=False, filters=lambda r: r.choice((1, 2, 4, 4))) + bench.append((label, data, zlib.crc32(exp))) + + ctx.emit("png_bench", [{"name": l, "width": 1024, "height": 768, "crc": c, "data": d} for l, d, c in bench]) diff --git a/tools/gen_registry.py b/tools/gen_registry.py new file mode 100644 index 0000000..802add1 --- /dev/null +++ b/tools/gen_registry.py @@ -0,0 +1,181 @@ +#!/usr/bin/env python3 +# Registry generator (python3 -I tools/gen_registry.py [--check]): scans the format folders +# src/Formats///init.luau and writes +# src/Formats/Registry.luau a static list (Roblox has no dynamic require): each format's contract metadata, copied +# from its init.luau, and a load() that requires the module on first use +# docs/FORMATS.md the capability matrix, from each contract's caps +# The metadata fields must be one-line literals in the contract table (tools/lint.sh CONTRACT checks the shape): +# name = "png", category = "image", extensions = { ... }, mime = { ... }, deps = { ... }, caps = { ... }, +# --check: exit 1 when either file is out of date (tools/lint.sh runs this). +import os, re, sys + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +SRC = os.path.join(ROOT, "src", "Formats") +CATEGORIES = ["image", "audio", "video", "model", "cad", "font", "archive", "data", "vector", "layered", "subtitle", + "music", "playlist"] +FIELDS = ["name", "category", "extensions", "mime", "deps", "caps"] +FIELD = re.compile(r"^\t(name|category|extensions|mime|deps|caps) = (.*),\s*(--.*)?$") + + +def contract(path): + """The one-line contract fields of a format's init.luau: {field: luau literal text}.""" + out = {} + with open(path) as f: + for line in f: + m = FIELD.match(line.rstrip("\n")) + if m and m.group(1) not in out: + out[m.group(1)] = m.group(2).strip() + return out + + +def lua_strings(lit): + return re.findall(r'"([^"]*)"', lit) + + +def scan(): + formats = [] + for cat in CATEGORIES: + d = os.path.join(SRC, cat) + if not os.path.isdir(d): + continue + for fmt in sorted(os.listdir(d)): + init = os.path.join(d, fmt, "init.luau") + if not os.path.isfile(init): + continue + c = contract(init) + missing = [k for k in FIELDS if k not in c] + if missing: + sys.exit("gen_registry: %s/%s/init.luau: missing contract fields %s" % (cat, fmt, ", ".join(missing))) + c["path"] = cat + "/" + fmt + c["folder_category"] = cat + formats.append(c) + return formats + + +def registry(formats): + out = [ + "--!strict", + "-- Registry: GENERATED by tools/gen_registry.py from the format folders - do not edit.", + "-- One entry per format: the contract metadata (copied from its init.luau) and load(), which requires the format", + "-- module on first use (a static require, as Roblox needs). Order: category, then name.", + "export type Entry = {", + "\tname: string,", + "\tcategory: string,", + "\tpath: string,", + "\textensions: { string },", + "\tmime: { string },", + "\tdeps: { string },", + "\tcaps: { [string]: any },", + "\tload: () -> any,", + "}", + "", + "local list: { Entry } = {", + ] + for c in formats: + out += [ + "\t{", + "\t\tname = %s," % c["name"], + "\t\tcategory = %s," % c["category"], + '\t\tpath = "%s",' % c["path"], + "\t\textensions = %s," % c["extensions"], + "\t\tmime = %s," % c["mime"], + "\t\tdeps = %s," % c["deps"], + "\t\tcaps = %s," % c["caps"], + "\t\tload = function()", + '\t\t\treturn require("@formats/%s")' % c["path"], + "\t\tend,", + "\t},", + ] + out += ["}", "", "return list", ""] + return "\n".join(out) + + +def caps_dict(lit): + """{ decode = true, depths = { 8 } } -> ordered [(key, text)] at the top level.""" + body = lit.strip()[1:-1] + items, depth, cur = [], 0, "" + for ch in body: + if ch == "{": + depth += 1 + elif ch == "}": + depth -= 1 + if ch == "," and depth == 0: + items.append(cur) + cur = "" + else: + cur += ch + if cur.strip(): + items.append(cur) + out = [] + for it in items: + if "=" in it: + k, v = it.split("=", 1) + out.append((k.strip(), v.strip())) + return out + + +def formats_md(formats): + lines = [ + "# Formats", + "", + "GENERATED by `tools/gen_registry.py` from each format's contract (`caps`) - do not edit. Every format listed here", + "is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build) by `bash tools/test.sh`.", + "", + "| Category | Format | Extensions | Read | Write | Capabilities | Test |", + "|---|---|---|---|---|---|---|", + ] + for c in formats: + caps = caps_dict(c["caps"]) + cd = dict(caps) + other = ", ".join("%s: %s" % (k, v.replace("{ ", "").replace(" }", "")) for k, v in caps if k not in ("decode", "encode")) + test = "tests/%s/%s.luau" % (c["folder_category"], lua_strings(c["name"])[0]) + has = os.path.isfile(os.path.join(ROOT, test)) + lines.append("| %s | %s | %s | %s | %s | %s | %s |" % ( + c["folder_category"], lua_strings(c["name"])[0], " ".join("." + e for e in lua_strings(c["extensions"])), + "yes" if cd.get("decode") == "true" else "-", "yes" if cd.get("encode") == "true" else "-", + other or "", "`%s`" % test if has else "**missing**")) + lines += ["", "Codecs (layer 1, shared by formats; not loadable on their own):", ""] + cdir = os.path.join(SRC, "codecs") + for name in sorted(os.listdir(cdir)) if os.path.isdir(cdir) else []: + p = os.path.join(cdir, name) + init = os.path.join(p, "init.luau") if os.path.isdir(p) else p + if os.path.isfile(init): + first = "" + with open(init) as f: + for line in f: + if line.startswith("-- codecs/"): + first = line[3:].strip() + break + lines.append("- %s" % (first or name)) + lines.append("") + return "\n".join(lines) + + +def main(): + formats = scan() + outputs = { + os.path.join(SRC, "Registry.luau"): registry(formats), + os.path.join(ROOT, "docs", "FORMATS.md"): formats_md(formats), + } + check = "--check" in sys.argv + stale = [] + for path, text in outputs.items(): + old = open(path).read() if os.path.exists(path) else None + if old != text: + stale.append(os.path.relpath(path, ROOT)) + if not check: + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "w") as f: + f.write(text) + if check: + if stale: + print("gen_registry: out of date: %s (run python3 -I tools/gen_registry.py)" % ", ".join(stale)) + sys.exit(1) + print("gen_registry: up to date (%d formats)" % len(formats)) + else: + print("gen_registry: %d formats -> src/Formats/Registry.luau, docs/FORMATS.md%s" % ( + len(formats), "" if stale else " (unchanged)")) + + +if __name__ == "__main__": + main() diff --git a/tools/lint.sh b/tools/lint.sh new file mode 100644 index 0000000..270d758 --- /dev/null +++ b/tools/lint.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash +# Lint (bash tools/lint.sh): +# 1. GLOBALS: unknown globals (luau-analyze), a local used before its declaration compiles fine but reads a nil +# global at runtime. Roblox globals are allowed (the library runs in Roblox, luau and LuaJIT). Other type errors +# are counted and printed with LINT_TYPES=1, but do not fail the lint (absorbed code predates --!strict). +# 2. HEADER, REQUIRE, NATIVE (native code never throws: it crashes Roblox Studio), LAYERS, DEPS, CONTRACT: +# tools/lint_rules.py (its header lists the rules; docs/STYLE.md explains them). +# 3. The generated registry / docs/FORMATS.md are up to date (tools/gen_registry.py --check), and tools/build.py's +# token passes pass their self-test. +cd "$(dirname "$0")/.." || exit 1 +ANALYZE=${ANALYZE:-$(command -v luau-analyze || nix shell nixpkgs#luau -c sh -c 'command -v luau-analyze')} +ALLOW="game|script|workspace|Instance|Enum|Vector3|Vector2|Color3|CFrame|task|typeof|warn|tick|time|buffer|vector|bit32|utf8|debug|shared|plugin|SharedTable|Random" +fail=0 +mapfile -t files < <(find src tests tools -name '*.luau' -not -path 'tests/gen/*' | sort) +report=$("$ANALYZE" "${files[@]}" 2>&1) +bad=$(echo "$report" | grep "Unknown global" | grep -vE "'($ALLOW)'") +if [ -n "$bad" ]; then + echo "$bad" + echo "lint: unknown globals (a local used before it is declared?)" + fail=1 +fi +ntype=$(echo "$report" | grep -c "Error:") +[ -n "$LINT_TYPES" ] && echo "$report" | grep -v "Unknown global" +python3 -I tools/lint_rules.py || { echo "lint: structure rules failed (see tools/lint_rules.py)"; fail=1; } +python3 -I tools/gen_registry.py --check > /dev/null || { python3 -I tools/gen_registry.py --check; fail=1; } +python3 -I tools/build.py --test > /dev/null || { echo "lint: tools/build.py --test failed"; fail=1; } +if [ $fail -eq 0 ]; then + echo "lint passed (globals, header, require, native, layers, deps, contract, registry; $ntype type diagnostics: LINT_TYPES=1 shows them)" +fi +exit $fail diff --git a/tools/lint_rules.py b/tools/lint_rules.py new file mode 100644 index 0000000..3c16eea --- /dev/null +++ b/tools/lint_rules.py @@ -0,0 +1,279 @@ +#!/usr/bin/env python3 +# The structural lint rules (python3 -I tools/lint_rules.py), run by tools/lint.sh. Prints one line per violation and +# exits 1 if there is any. The rules (docs/STYLE.md explains each): +# HEADER every src module starts with --!strict (then optional --!native / --!optimize N) and a comment line +# "-- : ..." (core/Bytes, image/png, image/png/Decode, Formats for the root, ...); every test +# starts with a comment. +# REQUIRE requires are string literals "@formats/" (tests / tools may also use "@tests/") naming an +# existing module; no script / @self / relative requires in src. +# NATIVE native code never throws: a --!native module has no error( / assert( and requires no module that has +# one; an @native function body has no error( / assert(. A format's init.luau is never --!native. +# LAYERS requires go downward: core < Types < host; core, Types < codecs < containers < formats (/) +# < ops < api (init, Registry). core / codecs / containers / ops may require their own layer; a format +# may require its own folder but never another format; only the api requires host. +# DEPS a format folder's requires outside itself are exactly the contract's deps = { ... }. +# CONTRACT a format's init.luau has the one-line fields name (= folder name), category (= folder category), +# extensions, mime, deps, caps (with decode / encode matching the functions), function .sniff, at least +# one of decode / encode / open, the section markers in order, and ends with return ; it has a test +# tests//.luau with a fuzz pass (:fuzz(). +import os, re, sys + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +SRC = os.path.join(ROOT, "src", "Formats") +CATEGORIES = ["image", "audio", "video", "model", "cad", "font", "archive", "data", "vector", "layered", "subtitle", + "music", "playlist"] +SECTIONS = ["requires", "contract", "types", "constants", "sniff", "decode", "encode", "open", "extras"] +THROW = re.compile(r"\b(error|assert)\s*\(") +REQ = re.compile(r"\brequire\s*\(([^)]*)\)") +MARKER = re.compile(r"^-- -{20,} (\w+)") + +out = [] + + +def bad(path, line, msg): + out.append("%s:%s: %s" % (os.path.relpath(path, ROOT), line, msg)) + + +def code(line): + """the line without its comment (strings containing -- are rare enough in this codebase)""" + return line.split("--", 1)[0] + + +def modpath(path): + """src/Formats/image/png/init.luau -> image/png; src/Formats/init.luau -> '' (the root)""" + rel = os.path.relpath(path, SRC)[:-5].replace(os.sep, "/") + if rel == "init": + return "" + if rel.endswith("/init"): + rel = rel[:-5] + return rel + + +def resolve(target): + """'core/Bytes' -> the file, or None""" + base = os.path.join(SRC, *target.split("/")) if target else SRC + for p in (base + ".luau", os.path.join(base, "init.luau")): + if os.path.isfile(p): + return p + return None + + +def layer(mod): + """(rank, group) of a module path""" + top = mod.split("/")[0] if mod else "" + if mod in ("", "Registry"): + return 6, "api" + if top == "core": + return 0, "core" + if mod == "Types": + return 1, "types" + if top == "host": + return 2, "host" + if top == "codecs": + return 3, "codecs" + if top == "containers": + return 4, "containers" + if top in CATEGORIES: + return 5, "format" + if top == "ops": + return 5.5, "ops" + return 7, "unknown" + + +def format_folder(mod): + parts = mod.split("/") + if parts[0] in CATEGORIES and len(parts) >= 2: + return parts[0] + "/" + parts[1] + return None + + +files = [] +for d, _, fs in os.walk(SRC): + for f in sorted(fs): + if f.endswith(".luau"): + files.append(os.path.join(d, f)) +files.sort() +text = {f: open(f).read().split("\n") for f in files} +mods = {f: modpath(f) for f in files} + +# requires per file: [(line, target)] +requires = {} +for f, lines in text.items(): + reqs = [] + for i, l in enumerate(lines, 1): + for m in REQ.finditer(code(l)): + arg = m.group(1).strip() + mm = re.fullmatch(r'"@formats(?:/([\w/]+))?"', arg) + if not mm: + bad(f, i, "REQUIRE: requires in src must be require(\"@formats/\"), got require(%s)" % arg) + continue + target = mm.group(1) or "" + if not resolve(target): + bad(f, i, "REQUIRE: no module @formats/%s" % target) + continue + reqs.append((i, target)) + requires[f] = reqs + +# ---------------------------------------------------------------------------------------------------- HEADER +for f, lines in text.items(): + i = 0 + if not lines or lines[0].strip() != "--!strict": + bad(f, 1, "HEADER: the first line must be --!strict") + while i < len(lines) and lines[i].startswith("--!"): + if not re.fullmatch(r"--!(strict|native|optimize [012])", lines[i].strip()): + bad(f, i + 1, "HEADER: unknown directive " + lines[i]) + i += 1 + want = mods[f] or "Formats" + if i >= len(lines) or not lines[i].startswith("-- %s:" % want): + bad(f, i + 1, "HEADER: the first comment line must start with \"-- %s:\"" % want) + +TESTS = os.path.join(ROOT, "tests") +for d, _, fs in os.walk(TESTS): + if os.path.relpath(d, TESTS).split(os.sep)[0] in ("gen", "fixtures"): + continue + for fn in fs: + if fn.endswith(".luau"): + p = os.path.join(d, fn) + first = open(p).readline() + if not first.startswith("--"): + bad(p, 1, "HEADER: a test starts with a comment saying what it covers") + for i, l in enumerate(open(p).read().split("\n"), 1): + for m in REQ.finditer(code(l)): + if not re.fullmatch(r'"@(formats|tests)(/[\w/]+)?"', m.group(1).strip()): + bad(p, i, "REQUIRE: tests require \"@formats/...\" or \"@tests/...\"") + +# ---------------------------------------------------------------------------------------------------- NATIVE +throwing = {mods[f] for f, lines in text.items() if any(THROW.search(code(l)) for l in lines)} +for f, lines in text.items(): + native = any(l.strip() == "--!native" for l in lines[:5]) + mod = mods[f] + if native: + if format_folder(mod) == mod: + bad(f, 1, "NATIVE: a format's init.luau is never --!native (put hot code in a private submodule)") + for i, l in enumerate(lines, 1): + if THROW.search(code(l)): + bad(f, i, "NATIVE: error / assert in a --!native module") + for i, target in requires[f]: + if target in throwing: + bad(f, i, "NATIVE: a --!native module requires %s, which can throw" % target) + for i, l in enumerate(lines): + if l.strip() == "@native": + ind = l[: len(l) - len(l.lstrip())] + j = i + 2 + while j < len(lines) and lines[j] != ind + "end": + if THROW.search(code(lines[j])): + bad(f, j + 1, "NATIVE: error / assert in an @native function") + j += 1 + if j == len(lines): + bad(f, i + 1, "NATIVE: @native function without a closing end at its indentation") + +# ---------------------------------------------------------------------------------------------------- LAYERS +ALLOWED = { + "core": {"core"}, + "types": {"core"}, + "host": {"core", "types", "host"}, + "codecs": {"core", "types", "codecs"}, + "containers": {"core", "types", "codecs", "containers"}, + "format": {"core", "types", "codecs", "containers"}, + "ops": {"core", "types", "codecs", "containers", "ops"}, + "api": {"core", "types", "host", "codecs", "containers", "format", "ops", "api"}, +} +for f in files: + mod = mods[f] + _, group = layer(mod) + if group == "unknown": + bad(f, 1, "LAYERS: %s is not in a known layer folder" % mod) + continue + for i, target in requires[f]: + _, tgroup = layer(target) + if group == "format": + mine, theirs = format_folder(mod), format_folder(target) + if tgroup == "format": + if mine != theirs: + bad(f, i, "LAYERS: a format never requires another format (%s -> %s): promote shared code to " + "codecs/ or containers/" % (mine, theirs)) + continue + if tgroup not in ALLOWED[group]: + bad(f, i, "LAYERS: %s (%s) may not require %s (%s)" % (mod or "Formats", group, target, tgroup)) + +# ---------------------------------------------------------------------------------------------------- DEPS + CONTRACT +FIELD = re.compile(r"^\t(name|category|extensions|mime|deps|caps) = (.*),\s*(--.*)?$") +folders = sorted({format_folder(m) for m in mods.values() if format_folder(m)}) +for folder in folders: + cat, fmt = folder.split("/") + init = os.path.join(SRC, cat, fmt, "init.luau") + if not os.path.isfile(init): + bad(os.path.join(SRC, cat, fmt), 0, "CONTRACT: a format folder needs an init.luau") + continue + lines = text[init] + fields = {} + for i, l in enumerate(lines, 1): + m = FIELD.match(l) + if m and m.group(1) not in fields: + fields[m.group(1)] = (i, m.group(2).strip()) + for k in ("name", "category", "extensions", "mime", "deps", "caps"): + if k not in fields: + bad(init, 0, "CONTRACT: missing the one-line field `%s = ...,` in the contract table" % k) + if "name" in fields and fields["name"][1] != '"%s"' % fmt: + bad(init, fields["name"][0], "CONTRACT: name must be \"%s\" (the folder name)" % fmt) + if "category" in fields and fields["category"][1] != '"%s"' % cat: + bad(init, fields["category"][0], "CONTRACT: category must be \"%s\" (the folder category)" % cat) + # the contract table's local name: `local X = {` right before the fields + tname = None + for l in lines: + m = re.match(r"^local (\w+) = \{$", l) + if m: + tname = m.group(1) + break + if not tname: + bad(init, 0, "CONTRACT: the contract is a table `local = {` with the fields on their own lines") + continue + funcs = {m.group(1) for l in lines for m in [re.match(r"^function %s\.(\w+)\(" % tname, l)] if m} + if "sniff" not in funcs: + bad(init, 0, "CONTRACT: missing function %s.sniff(r)" % tname) + if not funcs & {"decode", "encode", "open"}: + bad(init, 0, "CONTRACT: needs at least one of %s.decode / encode / open" % tname) + if "caps" in fields: + caps = fields["caps"][1] + for k in ("decode", "encode"): + m = re.search(r"\b%s = (true|false)" % k, caps) + if not m: + bad(init, fields["caps"][0], "CONTRACT: caps needs %s = true|false" % k) + elif (m.group(1) == "true") != (k in funcs or (k == "decode" and "open" in funcs)): + bad(init, fields["caps"][0], "CONTRACT: caps.%s = %s but %s.%s is %s" % ( + k, m.group(1), tname, k, "defined" if k in funcs else "missing")) + last = [l for l in lines if l.strip()][-1] + if last.strip() != "return %s" % tname: + bad(init, len(lines), "CONTRACT: the module ends with `return %s`" % tname) + seen = [MARKER.match(l).group(1) for l in lines if MARKER.match(l)] + for s in seen: + if s not in SECTIONS: + bad(init, 0, "CONTRACT: unknown section marker `%s` (known: %s)" % (s, ", ".join(SECTIONS))) + order = [SECTIONS.index(s) for s in seen if s in SECTIONS] + if order != sorted(order): + bad(init, 0, "CONTRACT: sections out of order (%s); the order is %s" % (", ".join(seen), ", ".join(SECTIONS))) + for s in ("requires", "contract"): + if s not in seen: + bad(init, 0, "CONTRACT: missing the `-- ---- %s` section marker" % s) + # DEPS + if "deps" in fields: + declared = set(re.findall(r'"([^"]*)"', fields["deps"][1])) + used = set() + for f in files: + if format_folder(mods[f]) == folder: + for _, target in requires[f]: + if format_folder(target) != folder: + used.add(target) + for d in sorted(used - declared): + bad(init, fields["deps"][0], "DEPS: requires %s but deps does not list it" % d) + for d in sorted(declared - used): + bad(init, fields["deps"][0], "DEPS: deps lists %s but nothing in %s requires it" % (d, folder)) + # the test + test = os.path.join(ROOT, "tests", cat, fmt + ".luau") + if not os.path.isfile(test): + bad(init, 0, "CONTRACT: missing the test tests/%s/%s.luau" % (cat, fmt)) + elif ":fuzz(" not in open(test).read(): + bad(test, 0, "CONTRACT: a format test includes the fuzz no-throw pass (t:fuzz(...))") + +print("\n".join(out)) +sys.exit(1 if out else 0) diff --git a/tools/test.sh b/tools/test.sh new file mode 100644 index 0000000..5e80063 --- /dev/null +++ b/tools/test.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +# Tests (bash tools/test.sh [filter]): generate the fixtures (tools/fixtures.py -> tests/gen), regenerate the registry, +# build both targets (tools/build.py), then run every tests/**/*.luau twice: under `luau --codegen -O2` (the source, +# through the .luaurc aliases) and under `luajit` (build/luajit/tests/**/*.lua, with the compat prelude), then the lint. +# A filter runs only the tests whose path contains it (and the fixture generators whose name contains it), and skips +# the lint. RUNTIMES="luau" or "luajit" runs one runtime only. +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')} +RUNTIMES=${RUNTIMES:-"luau luajit"} +LJPATH='package.path = "build/luajit/?.lua;build/luajit/?/init.lua;" .. package.path' +fail=0 +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 + [ -n "$1" ] && [[ "$t" != *$1* ]] && continue + for rt in $RUNTIMES; do + echo "== $t ($rt)" + if [ "$rt" = luau ]; then + "$LUAU" --codegen -O2 "$t" || { echo "FAILED: $t ($rt)"; fail=1; continue; } + else + "$LUAJIT" -e "$LJPATH" "build/luajit/${t%.luau}.lua" || { echo "FAILED: $t ($rt)"; fail=1; continue; } + fi + passed=$((passed + 1)) + done +done +if [ -z "$1" ]; then + bash tools/lint.sh || fail=1 +fi +[ $fail -eq 0 ] && echo "formats-luau: all tests passed ($passed runs)" || echo "formats-luau: FAILURES" +exit $fail