diff --git a/docs/FORMATS.md b/docs/FORMATS.md
index 675899b..245d234 100644
--- a/docs/FORMATS.md
+++ b/docs/FORMATS.md
@@ -6,7 +6,15 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| Category | Format | Extensions | Read | Write | Capabilities | Test |
|---|---|---|---|---|---|---|
| image | bmp | .bmp .dib | yes | yes | alpha: true, depths: 1, 2, 4, 8, 16, 24, 32, rle: true | `tests/image/bmp.luau` |
+| image | gif | .gif | yes | yes | animation: true, alpha: true, palette: true, depths: 1, 2, 4, 8 | `tests/image/gif.luau` |
+| image | hdr | .hdr .pic .rgbe | yes | yes | alpha: false, float: true, depths: 32 | `tests/image/hdr.luau` |
+| image | ico | .ico .cur | yes | yes | alpha: true, frames: true, depths: 1, 4, 8, 16, 24, 32 | `tests/image/ico.luau` |
+| image | jpeg | .jpg .jpeg .jpe .jfif | yes | yes | lossy: true, alpha: false, depths: 8, 12, progressive: true, arithmetic: true | `tests/image/jpeg.luau` |
| image | png | .png .apng | yes | yes | animation: true, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` |
+| image | pnm | .pnm .pbm .pgm .ppm .pam .pfm | yes | yes | alpha: true, depths: 1, 8, 16, 32, float: true | `tests/image/pnm.luau` |
+| image | qoi | .qoi | yes | yes | alpha: true, depths: 8 | `tests/image/qoi.luau` |
+| image | tga | .tga .icb .vda .vst .tpic | yes | yes | alpha: true, palette: true, depths: 8, 15, 16, 24, 32 | `tests/image/tga.luau` |
+| image | tiff | .tif .tiff | yes | yes | alpha: true, pages: true, depths: 1, 2, 4, 8, 16, 32, float: true | `tests/image/tiff.luau` |
| audio | flac | .flac .oga | yes | - | streaming: true, depths: 4, 8, 12, 16, 20, 24, 32, ogg: true, seek: true | `tests/audio/flac.luau` |
| audio | mp3 | .mp3 .mp2 .mp1 .mpga | yes | - | streaming: true, seek: true, layers: 1, 2, 3, channels: 2 | `tests/audio/mp3.luau` |
| audio | opus | .opus | yes | - | streaming: true, seek: true, lossy: true, channels: 255, rates: 48000 | `tests/audio/opus.luau` |
@@ -41,9 +49,12 @@ Codecs (layer 1, shared by formats; not loadable on their own):
- codecs/Brotli: Brotli (RFC 7932) decompression. A codec (layer 3): archive/br and font/woff2 build on it. Written
- codecs/Bzip2: bzip2 decompressor (BWT + MTF + Huffman, the .bz2 stream format of bzip2 0.9.5 / 1.0.x). A codec
- codecs/Cff: Compact Font Format (Adobe TN #5176) and Type 2 charstrings (TN #5177): the outlines of OpenType fonts
+- codecs/Dct: the 8x8 DCTs JPEG, Motion-JPEG and MPEG-1 share (native; never throws).
- codecs/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers.
- codecs/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code.
- codecs/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. A codec (layer 3):
+- codecs/Lzw: LZW decoder and encoder in the two variants file formats use. A codec (layer 1): image/gif and
+- codecs/Quantize: palette quantization of rgba8 pixels. A codec (layer 1): image/gif (and later any palette
- codecs/Raster: an antialiased scanline rasterizer for paths of lines, quadratic and cubic Béziers, under an affine
- codecs/Text: text decoding helpers for the text formats: a UTF-8 BOM is stripped, text that is not valid UTF-8 is
- codecs/TrueType: the sfnt font container (TrueType .ttf, OpenType .otf with CFF outlines, collections .ttc) parsed
diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md
index a36c9eb..96d6c3b 100644
--- a/licenses/NOTICE.md
+++ b/licenses/NOTICE.md
@@ -17,6 +17,8 @@
| `tests/fixtures/bmpsuite/` | BMP Suite 2.8 by Jason Summers (generated images) | public domain: [bmpsuite-NOTICE.txt](bmpsuite-NOTICE.txt) |
| `src/Formats/containers/Zip/` (the reader), `src/Formats/archive/zip/` | zip-luau 121d4b0 (same author), written from PKWARE's APPNOTE.TXT 6.3 | no licence chosen yet; no third-party code |
| `src/Formats/playlist/` (m3u, pls; xspf is new), `src/Formats/codecs/Url/`, `src/Formats/codecs/Text/` | playlist-luau 3fc7fd3 (same author), written from RFC 3986 / RFC 8216 | no licence chosen yet; no third-party code |
+| `src/Formats/image/jpeg/` (Decode, Scan, Color), `src/Formats/codecs/Dct/` (inverse DCTs) | jpeg-luau 1.0 (same author); the IDCTs, upsampling, colour conversion and IDCT-size choice are Luau translations of libjpeg / libjpeg-turbo (jidctint.c, jidctred.c, jdsample.c, jdcolor.c, jdmaster.c) | IJG licence + libjpeg-turbo BSD: [libjpeg-turbo-LICENSE.md](libjpeg-turbo-LICENSE.md), [libjpeg-README.ijg](libjpeg-README.ijg). This software is based in part on the work of the Independent JPEG Group. |
+| `src/Formats/image/jpeg/Arith.luau`, `src/Formats/image/jpeg/Encode.luau`, `src/Formats/codecs/Dct/` (forward DCT) | new; Luau translations of libjpeg-turbo 3.2 jdarith.c / jaricom.c (Guido Vollbeding), jccolor.c, jcsample.c, jccoefct.c, jfdctint.c, jcdctmgr.c, jchuff.c, jcphuff.c, jcparam.c | as above |
| `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
diff --git a/licenses/libjpeg-README.ijg b/licenses/libjpeg-README.ijg
new file mode 100644
index 0000000..dbf8070
--- /dev/null
+++ b/licenses/libjpeg-README.ijg
@@ -0,0 +1,260 @@
+libjpeg-turbo note: This file has been modified by The libjpeg-turbo Project
+to include only information relevant to libjpeg-turbo, to wordsmith certain
+sections, and to remove impolitic language that existed in the libjpeg v8
+README. It is included only for reference. Please see README.md for
+information specific to libjpeg-turbo.
+
+
+The Independent JPEG Group's JPEG software
+==========================================
+
+This distribution contains a release of the Independent JPEG Group's free JPEG
+software. You are welcome to redistribute this software and to use it for any
+purpose, subject to the conditions under LEGAL ISSUES, below.
+
+This software is the work of Tom Lane, Guido Vollbeding, Philip Gladstone,
+Bill Allombert, Jim Boucher, Lee Crocker, Bob Friesenhahn, Ben Jackson,
+Julian Minguillon, Luis Ortiz, George Phillips, Davide Rossi, Ge' Weijers,
+and other members of the Independent JPEG Group.
+
+IJG is not affiliated with the ISO/IEC JTC1/SC29/WG1 standards committee
+(also known as JPEG, together with ITU-T SG16).
+
+
+DOCUMENTATION ROADMAP
+=====================
+
+This file contains the following sections:
+
+OVERVIEW General description of JPEG and the IJG software.
+LEGAL ISSUES Copyright, lack of warranty, terms of distribution.
+REFERENCES Where to learn more about JPEG.
+ARCHIVE LOCATIONS Where to find newer versions of this software.
+FILE FORMAT WARS Software *not* to get.
+TO DO Plans for future IJG releases.
+
+Other documentation files in the distribution are:
+
+User documentation:
+ doc/usage.txt Usage instructions for cjpeg, djpeg, jpegtran,
+ rdjpgcom, and wrjpgcom.
+ doc/*.1 Unix-style man pages for programs (same info as
+ usage.txt).
+ doc/wizard.txt Advanced usage instructions for JPEG wizards only.
+ doc/change.log Version-to-version change highlights.
+Programmer and internal documentation:
+ doc/libjpeg.txt How to use the JPEG library in your own programs.
+ src/example.c Sample code for calling the JPEG library.
+ doc/structure.txt Overview of the JPEG library's internal structure.
+ doc/coderules.txt Coding style rules --- please read if you contribute
+ code.
+
+Please read at least usage.txt. Some information can also be found in the JPEG
+FAQ (Frequently Asked Questions) article. See ARCHIVE LOCATIONS below to find
+out where to obtain the FAQ article.
+
+If you want to understand how the JPEG code works, we suggest reading one or
+more of the REFERENCES, then looking at the documentation files (in roughly
+the order listed) before diving into the code.
+
+
+OVERVIEW
+========
+
+This package contains C software to implement JPEG image encoding, decoding,
+and transcoding. JPEG (pronounced "jay-peg") is a standardized compression
+method for full-color and grayscale images. JPEG's strong suit is compressing
+photographic images or other types of images that have smooth color and
+brightness transitions between neighboring pixels. Images with sharp lines or
+other abrupt features may not compress well with JPEG, and a higher JPEG
+quality may have to be used to avoid visible compression artifacts with such
+images.
+
+JPEG is normally lossy, meaning that the output pixels are not necessarily
+identical to the input pixels. However, on photographic content and other
+"smooth" images, very good compression ratios can be obtained with no visible
+compression artifacts, and extremely high compression ratios are possible if
+you are willing to sacrifice image quality (by reducing the "quality" setting
+in the compressor.)
+
+This software implements JPEG baseline, extended-sequential, progressive, and
+lossless compression processes. Provision is made for supporting all variants
+of these processes, although some uncommon parameter settings aren't
+implemented yet. We have made no provision for supporting the hierarchical
+processes defined in the standard.
+
+We provide a set of library routines for reading and writing JPEG image files,
+plus two sample applications "cjpeg" and "djpeg", which use the library to
+perform conversion between JPEG and some other popular image file formats.
+The library is intended to be reused in other applications.
+
+In order to support file conversion and viewing software, we have included
+considerable functionality beyond the bare JPEG coding/decoding capability;
+for example, the color quantization modules are not strictly part of JPEG
+decoding, but they are essential for output to colormapped file formats. These
+extra functions can be compiled out of the library if not required for a
+particular application.
+
+We have also included "jpegtran", a utility for lossless transcoding between
+different JPEG processes, and "rdjpgcom" and "wrjpgcom", two simple
+applications for inserting and extracting textual comments in JFIF files.
+
+The emphasis in designing this software has been on achieving portability and
+flexibility, while also making it fast enough to be useful. In particular,
+the software is not intended to be read as a tutorial on JPEG. (See the
+REFERENCES section for introductory material.) Rather, it is intended to
+be reliable, portable, industrial-strength code. We do not claim to have
+achieved that goal in every aspect of the software, but we strive for it.
+
+We welcome the use of this software as a component of commercial products.
+No royalty is required, but we do ask for an acknowledgement in product
+documentation, as described under LEGAL ISSUES.
+
+
+LEGAL ISSUES
+============
+
+In plain English:
+
+1. We don't promise that this software works. (But if you find any bugs,
+ please let us know!)
+2. You can use this software for whatever you want. You don't have to pay us.
+3. You may not pretend that you wrote this software. If you use it in a
+ program, you must acknowledge somewhere in your documentation that
+ you've used the IJG code.
+
+In legalese:
+
+The authors make NO WARRANTY or representation, either express or implied,
+with respect to this software, its quality, accuracy, merchantability, or
+fitness for a particular purpose. This software is provided "AS IS", and you,
+its user, assume the entire risk as to its quality and accuracy.
+
+This software is copyright (C) 1991-2020, Thomas G. Lane, Guido Vollbeding.
+All Rights Reserved except as specified below.
+
+Permission is hereby granted to use, copy, modify, and distribute this
+software (or portions thereof) for any purpose, without fee, subject to these
+conditions:
+(1) If any part of the source code for this software is distributed, then this
+README file must be included, with this copyright and no-warranty notice
+unaltered; and any additions, deletions, or changes to the original files
+must be clearly indicated in accompanying documentation.
+(2) If only executable code is distributed, then the accompanying
+documentation must state that "this software is based in part on the work of
+the Independent JPEG Group".
+(3) Permission for use of this software is granted only if the user accepts
+full responsibility for any undesirable consequences; the authors accept
+NO LIABILITY for damages of any kind.
+
+These conditions apply to any software derived from or based on the IJG code,
+not just to the unmodified library. If you use our work, you ought to
+acknowledge us.
+
+Permission is NOT granted for the use of any IJG author's name or company name
+in advertising or publicity relating to this software or products derived from
+it. This software may be referred to only as "the Independent JPEG Group's
+software".
+
+We specifically permit and encourage the use of this software as the basis of
+commercial products, provided that all warranty or liability claims are
+assumed by the product vendor.
+
+
+REFERENCES
+==========
+
+We recommend reading one or more of these references before trying to
+understand the innards of the JPEG software.
+
+The best short technical introduction to the JPEG compression algorithm is
+ Wallace, Gregory K. "The JPEG Still Picture Compression Standard",
+ Communications of the ACM, April 1991 (vol. 34 no. 4), pp. 30-44.
+(Adjacent articles in that issue discuss MPEG motion picture compression,
+applications of JPEG, and related topics.) If you don't have the CACM issue
+handy, a PDF file containing a revised version of Wallace's article is
+available at http://www.ijg.org/files/Wallace.JPEG.pdf. The file (actually
+a preprint for an article that appeared in IEEE Trans. Consumer Electronics)
+omits the sample images that appeared in CACM, but it includes corrections
+and some added material. Note: the Wallace article is copyright ACM and IEEE,
+and it may not be used for commercial purposes.
+
+A somewhat less technical, more leisurely introduction to JPEG can be found in
+"The Data Compression Book" by Mark Nelson and Jean-loup Gailly, published by
+M&T Books (New York), 2nd ed. 1996, ISBN 1-55851-434-1. This book provides
+good explanations and example C code for a multitude of compression methods
+including JPEG. It is an excellent source if you are comfortable reading C
+code but don't know much about data compression in general. The book's JPEG
+sample code is far from industrial-strength, but when you are ready to look
+at a full implementation, you've got one here...
+
+The best currently available description of JPEG is the textbook "JPEG Still
+Image Data Compression Standard" by William B. Pennebaker and Joan L.
+Mitchell, published by Van Nostrand Reinhold, 1993, ISBN 0-442-01272-1.
+Price US$59.95, 638 pp. The book includes the complete text of the ISO JPEG
+standards (DIS 10918-1 and draft DIS 10918-2).
+
+The original JPEG standard is divided into two parts, Part 1 being the actual
+specification, while Part 2 covers compliance testing methods. Part 1 is
+titled "Digital Compression and Coding of Continuous-tone Still Images,
+Part 1: Requirements and guidelines" and has document numbers ISO/IEC IS
+10918-1, ITU-T T.81. Part 2 is titled "Digital Compression and Coding of
+Continuous-tone Still Images, Part 2: Compliance testing" and has document
+numbers ISO/IEC IS 10918-2, ITU-T T.83.
+
+The JPEG standard does not specify all details of an interchangeable file
+format. For the omitted details, we follow the "JFIF" conventions, revision
+1.02. JFIF version 1 has been adopted as ISO/IEC 10918-5 (05/2013) and
+Recommendation ITU-T T.871 (05/2011): Information technology - Digital
+compression and coding of continuous-tone still images: JPEG File Interchange
+Format (JFIF). It is available as a free download in PDF file format from
+https://www.iso.org/standard/54989.html and http://www.itu.int/rec/T-REC-T.871.
+A PDF file of the older JFIF 1.02 specification is available at
+http://www.w3.org/Graphics/JPEG/jfif3.pdf.
+
+The TIFF 6.0 file format specification can be obtained from
+http://mirrors.ctan.org/graphics/tiff/TIFF6.ps.gz. The JPEG incorporation
+scheme found in the TIFF 6.0 spec of 3-June-92 has a number of serious
+problems. IJG does not recommend use of the TIFF 6.0 design (TIFF Compression
+tag 6). Instead, we recommend the JPEG design proposed by TIFF Technical Note
+#2 (Compression tag 7). Copies of this Note can be obtained from
+http://www.ijg.org/files/. It is expected that the next revision
+of the TIFF spec will replace the 6.0 JPEG design with the Note's design.
+Although IJG's own code does not support TIFF/JPEG, the free libtiff library
+uses our library to implement TIFF/JPEG per the Note.
+
+
+ARCHIVE LOCATIONS
+=================
+
+The "official" archive site for this software is www.ijg.org.
+The most recent released version can always be found there in
+directory "files".
+
+The JPEG FAQ (Frequently Asked Questions) article is a source of some
+general information about JPEG. It is available at
+http://www.faqs.org/faqs/jpeg-faq.
+
+
+FILE FORMAT COMPATIBILITY
+=========================
+
+This software implements ITU T.81 | ISO/IEC 10918 with some extensions from
+ITU T.871 | ISO/IEC 10918-5 (JPEG File Interchange Format-- see REFERENCES).
+Informally, the term "JPEG image" or "JPEG file" most often refers to JFIF or
+a subset thereof, but there are other formats containing the name "JPEG" that
+are incompatible with the original JPEG standard or with JFIF (for instance,
+JPEG 2000 and JPEG XR). This software therefore does not support these
+formats. Indeed, one of the original reasons for developing this free software
+was to help force convergence on a common, interoperable format standard for
+JPEG files.
+
+JFIF is a minimal or "low end" representation. TIFF/JPEG (TIFF revision 6.0 as
+modified by TIFF Technical Note #2) can be used for "high end" applications
+that need to record a lot of additional data about an image.
+
+
+TO DO
+=====
+
+Please send bug reports, offers of help, etc. to jpeg-info@jpegclub.org.
diff --git a/licenses/libjpeg-turbo-LICENSE.md b/licenses/libjpeg-turbo-LICENSE.md
new file mode 100644
index 0000000..37a489b
--- /dev/null
+++ b/licenses/libjpeg-turbo-LICENSE.md
@@ -0,0 +1,147 @@
+libjpeg-turbo Licenses
+======================
+
+libjpeg-turbo is covered by two compatible BSD-style open source licenses:
+
+- The IJG (Independent JPEG Group) License, which is listed in
+ [README.ijg](README.ijg)
+
+ This license applies to the libjpeg API library and associated programs,
+ including any code inherited from libjpeg and any modifications to that
+ code.
+
+- The Modified (3-clause) BSD License, which is listed below
+
+ This license applies to the TurboJPEG API library and associated programs,
+ [libspng](https://libspng.org) (which is used by cjpeg and djpeg), and the
+ build/test system.
+
+ * The TurboJPEG API library wraps the libjpeg API library, so in the context
+ of the overall TurboJPEG API library, both the terms of the IJG License and
+ the terms of the Modified (3-clause) BSD License apply.
+ * cjpeg and djpeg use libspng, so in the context of those programs, both the
+ terms of the IJG License and the terms of the Modified (3-clause) BSD
+ License apply.
+
+
+Component Licenses
+==================
+
+Some of libjpeg-turbo's modules and internal dependencies are covered by less
+restrictive licenses, but in the context of libjpeg-turbo as a whole, the terms
+of the less restrictive licenses are subsumed by either the IJG License or the
+Modified BSD License. (In other words, the terms of the less restrictive
+licenses are satisfied if the terms of the IJG and Modified BSD Licenses are
+satisfied.)
+
+- The libjpeg-turbo SIMD source code and zlib are covered by the
+ [zlib License](https://spdx.org/licenses/Zlib.html), which is subsumed by the
+ IJG License in the context of the cjpeg and djpeg programs and the libjpeg
+ API library.
+
+- Some of the libspng source code is covered by the
+ [PNG Reference Library License v2](https://spdx.org/licenses/libpng-2.0.html),
+ which is subsumed by the IJG License in the context of the cjpeg and djpeg
+ programs and the TurboJPEG API library.
+
+- Most of the libspng source code is covered by the
+ [Simplified (2-clause) BSD License](https://spdx.org/licenses/BSD-2-Clause.html),
+ which is subsumed by the Modified BSD License in the context of the cjpeg and
+ djpeg programs and the TurboJPEG API library.
+
+
+Complying with the libjpeg-turbo Licenses
+=========================================
+
+This section provides a roll-up of the libjpeg-turbo licensing terms, to the
+best of our understanding. This is not a license in and of itself. It is
+intended solely for clarification.
+
+1. If you are distributing a modified version of the libjpeg-turbo source,
+ then:
+
+ 1. You cannot alter or remove any existing copyright or license notices
+ from the source.
+
+ **Origin**
+ - Clause 1 of the IJG License
+ - Clause 1 of the Modified BSD License
+
+ 2. You must add your own copyright notice to the header of each source
+ file you modified, so others can tell that you modified that file. (If
+ there is not an existing copyright header in that file, then you can
+ simply add a notice stating that you modified the file.)
+
+ **Origin**
+ - Clause 1 of the IJG License
+
+ 3. You must include the IJG README file, and you must not alter any of the
+ copyright or license text in that file.
+
+ **Origin**
+ - Clause 1 of the IJG License
+
+2. If you are distributing only libjpeg-turbo binaries without the source, or
+ if you are distributing an application that statically links with
+ libjpeg-turbo, then:
+
+ 1. Your product documentation must include a message stating:
+
+ This software is based in part on the work of the Independent JPEG
+ Group.
+
+ **Origin**
+ - Clause 2 of the IJG license
+
+ 2. If your binary distribution includes or uses the TurboJPEG API or
+ associated programs, cjpeg, or djpeg, then your product documentation
+ must include the text of the Modified BSD License (see below.)
+
+ **Origin**
+ - Clause 2 of the Modified BSD License
+
+3. You cannot use the name of the IJG or The libjpeg-turbo Project or the
+ contributors thereof in advertising, publicity, etc.
+
+ **Origin**
+ - IJG License
+ - Clause 3 of the Modified BSD License
+
+4. The authors and distributors do not warrant libjpeg-turbo to be free of
+ defects, nor do we accept any liability for undesirable consequences
+ resulting from your use of the software.
+
+ **Origin**
+ - IJG License
+ - Modified BSD License
+
+
+The Modified (3-clause) BSD License
+===================================
+
+Copyright (C) 2009-2026 D. R. Commander
+Copyright (C) 2018-2023 Randy
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+- Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+- Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+- Neither the name of the libjpeg-turbo Project nor the names of its
+ contributors may be used to endorse or promote products derived from this
+ software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS",
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGE.
diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau
index 67f5a98..bde3cf6 100644
--- a/src/Formats/Registry.luau
+++ b/src/Formats/Registry.luau
@@ -26,6 +26,54 @@ local list: { Entry } = {
return require("@formats/image/bmp")
end,
},
+ {
+ name = "gif",
+ category = "image",
+ path = "image/gif",
+ extensions = { "gif" },
+ mime = { "image/gif" },
+ deps = { "core/Err", "core/Bytes", "codecs/Lzw", "codecs/Quantize", "Types" },
+ caps = { decode = true, encode = true, animation = true, alpha = true, palette = true, depths = { 1, 2, 4, 8 } },
+ load = function()
+ return require("@formats/image/gif")
+ end,
+ },
+ {
+ name = "hdr",
+ category = "image",
+ path = "image/hdr",
+ extensions = { "hdr", "pic", "rgbe" },
+ mime = { "image/vnd.radiance", "image/x-hdr" },
+ deps = { "core/Err", "core/Bytes", "Types" },
+ caps = { decode = true, encode = true, alpha = false, float = true, depths = { 32 } },
+ load = function()
+ return require("@formats/image/hdr")
+ end,
+ },
+ {
+ name = "ico",
+ category = "image",
+ path = "image/ico",
+ extensions = { "ico", "cur" },
+ mime = { "image/vnd.microsoft.icon", "image/x-icon" },
+ deps = { "core/Err", "core/Bytes", "Types" },
+ caps = { decode = true, encode = true, alpha = true, frames = true, depths = { 1, 4, 8, 16, 24, 32 } },
+ load = function()
+ return require("@formats/image/ico")
+ end,
+ },
+ {
+ name = "jpeg",
+ category = "image",
+ path = "image/jpeg",
+ extensions = { "jpg", "jpeg", "jpe", "jfif" },
+ mime = { "image/jpeg" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/Dct" },
+ caps = { decode = true, encode = true, lossy = true, alpha = false, depths = { 8, 12 }, progressive = true, arithmetic = true },
+ load = function()
+ return require("@formats/image/jpeg")
+ end,
+ },
{
name = "png",
category = "image",
@@ -38,6 +86,54 @@ local list: { Entry } = {
return require("@formats/image/png")
end,
},
+ {
+ name = "pnm",
+ category = "image",
+ path = "image/pnm",
+ extensions = { "pnm", "pbm", "pgm", "ppm", "pam", "pfm" },
+ mime = { "image/x-portable-anymap", "image/x-portable-bitmap", "image/x-portable-graymap", "image/x-portable-pixmap", "image/x-portable-arbitrarymap", "image/x-portable-floatmap" },
+ deps = { "core/Err", "core/Bytes", "Types" },
+ caps = { decode = true, encode = true, alpha = true, depths = { 1, 8, 16, 32 }, float = true },
+ load = function()
+ return require("@formats/image/pnm")
+ end,
+ },
+ {
+ name = "qoi",
+ category = "image",
+ path = "image/qoi",
+ extensions = { "qoi" },
+ mime = { "image/qoi", "image/x-qoi" },
+ deps = { "core/Err", "core/Bytes", "Types" },
+ caps = { decode = true, encode = true, alpha = true, depths = { 8 } },
+ load = function()
+ return require("@formats/image/qoi")
+ end,
+ },
+ {
+ name = "tga",
+ category = "image",
+ path = "image/tga",
+ extensions = { "tga", "icb", "vda", "vst", "tpic" },
+ mime = { "image/x-tga", "image/x-targa" },
+ deps = { "core/Err", "core/Bytes", "Types" },
+ caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 8, 15, 16, 24, 32 } },
+ load = function()
+ return require("@formats/image/tga")
+ end,
+ },
+ {
+ name = "tiff",
+ category = "image",
+ path = "image/tiff",
+ extensions = { "tif", "tiff" },
+ mime = { "image/tiff" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/Deflate", "codecs/Lzw" },
+ caps = { decode = true, encode = true, alpha = true, pages = true, depths = { 1, 2, 4, 8, 16, 32 }, float = true },
+ load = function()
+ return require("@formats/image/tiff")
+ end,
+ },
{
name = "flac",
category = "audio",
diff --git a/src/Formats/codecs/Dct/init.luau b/src/Formats/codecs/Dct/init.luau
new file mode 100644
index 0000000..c46923c
--- /dev/null
+++ b/src/Formats/codecs/Dct/init.luau
@@ -0,0 +1,392 @@
+--!strict
+--!native
+--!optimize 2
+-- codecs/Dct: the 8x8 DCTs JPEG, Motion-JPEG and MPEG-1 share (native; never throws).
+-- Inverse: libjpeg's islow (jidctint.c: the Loeffler-Ligtenberg-Moschytz algorithm, 13-bit constants, two passes with
+-- PASS1_BITS of scaling between them), plus the reduced 4x4 / 2x2 / 1x1 IDCTs for scaled decodes (jidctred.c); the
+-- results match libjpeg-turbo's djpeg bit for bit. Absorbed from jpeg-luau 1.0 src/Jpeg/Idct.luau (same author).
+-- Forward: libjpeg's islow (jfdctint.c) with jcdctmgr.c's rounding quantiser, so an encoder built on it produces
+-- the same coefficients as cjpeg. Both are Luau translations of IJG code (licenses/libjpeg-turbo-LICENSE.md).
+-- Values are exact integers in doubles: no overflow even on corrupt coefficients; outputs are clamped to 0..maxv.
+--
+-- Dct.idctComponent(coef, q, bpl, bpc, size, plane, p1, center, maxv) -- every block of a component
+-- Dct.idctBlock(coef, off, q, plane, out, stride, p1, center, maxv) -- one 8x8 block (u16 samples)
+-- Dct.fdctQuantize(src, stride, x, y, w, h, div, coef, off) -- one block from u8 samples
+local readi16, readu16, writeu16, readu8, writei16 = buffer.readi16, buffer.readu16, buffer.writeu16, buffer.readu8, buffer.writei16
+local clamp = math.clamp
+
+local Dct = {}
+
+local ws = table.create(64, 0)
+
+local function idct8(coef: buffer, off: number, q: buffer, plane: buffer, out: number, stride: number, p1: number, center: number, maxv: number)
+ local s1 = 2 ^ (13 - p1)
+ local h1 = s1 / 2
+ local s2 = 2 ^ (16 + p1)
+ local h2 = s2 / 2 + center * s2
+ local dcm = 2 ^ p1
+ for c = 0, 7 do
+ local o = off + c * 2
+ local qo = c * 2
+ local c1, c2, c3 = readi16(coef, o + 16), readi16(coef, o + 32), readi16(coef, o + 48)
+ local c4, c5, c6, c7 = readi16(coef, o + 64), readi16(coef, o + 80), readi16(coef, o + 96), readi16(coef, o + 112)
+ if c1 == 0 and c2 == 0 and c3 == 0 and c4 == 0 and c5 == 0 and c6 == 0 and c7 == 0 then
+ local dc = readi16(coef, o) * readu16(q, qo) * dcm
+ ws[c + 1] = dc
+ ws[c + 9] = dc
+ ws[c + 17] = dc
+ ws[c + 25] = dc
+ ws[c + 33] = dc
+ ws[c + 41] = dc
+ ws[c + 49] = dc
+ ws[c + 57] = dc
+ else
+ -- even part
+ local z2 = c2 * readu16(q, qo + 32)
+ local z3 = c6 * readu16(q, qo + 96)
+ local z1 = (z2 + z3) * 4433
+ local tmp2 = z1 - z3 * 15137
+ local tmp3 = z1 + z2 * 6270
+ z2 = readi16(coef, o) * readu16(q, qo)
+ z3 = c4 * readu16(q, qo + 64)
+ local tmp0 = (z2 + z3) * 8192
+ local tmp1 = (z2 - z3) * 8192
+ local tmp10, tmp13 = tmp0 + tmp3, tmp0 - tmp3
+ local tmp11, tmp12 = tmp1 + tmp2, tmp1 - tmp2
+ -- odd part
+ local t0 = c7 * readu16(q, qo + 112)
+ local t1 = c5 * readu16(q, qo + 80)
+ local t2 = c3 * readu16(q, qo + 48)
+ local t3 = c1 * readu16(q, qo + 16)
+ z1 = t0 + t3
+ z2 = t1 + t2
+ z3 = t0 + t2
+ local z4 = t1 + t3
+ local z5 = (z3 + z4) * 9633
+ t0 *= 2446
+ t1 *= 16819
+ t2 *= 25172
+ t3 *= 12299
+ z1 *= -7373
+ z2 *= -20995
+ z3 = z3 * -16069 + z5
+ z4 = z4 * -3196 + z5
+ t0 += z1 + z3
+ t1 += z2 + z4
+ t2 += z2 + z3
+ t3 += z1 + z4
+ ws[c + 1] = (tmp10 + t3 + h1) // s1
+ ws[c + 57] = (tmp10 - t3 + h1) // s1
+ ws[c + 9] = (tmp11 + t2 + h1) // s1
+ ws[c + 49] = (tmp11 - t2 + h1) // s1
+ ws[c + 17] = (tmp12 + t1 + h1) // s1
+ ws[c + 41] = (tmp12 - t1 + h1) // s1
+ ws[c + 25] = (tmp13 + t0 + h1) // s1
+ ws[c + 33] = (tmp13 - t0 + h1) // s1
+ end
+ end
+ local sd = 2 ^ (p1 + 3)
+ local hd = sd / 2 + center * sd
+ for r = 0, 7 do
+ local b = r * 8
+ local w0, w1, w2, w3 = ws[b + 1], ws[b + 2], ws[b + 3], ws[b + 4]
+ local w4, w5, w6, w7 = ws[b + 5], ws[b + 6], ws[b + 7], ws[b + 8]
+ local o = (out + r * stride) * 2
+ if w1 == 0 and w2 == 0 and w3 == 0 and w4 == 0 and w5 == 0 and w6 == 0 and w7 == 0 then
+ local v = clamp((w0 + hd) // sd, 0, maxv)
+ for i = 0, 14, 2 do
+ writeu16(plane, o + i, v)
+ end
+ else
+ local z1 = (w2 + w6) * 4433
+ local tmp2 = z1 - w6 * 15137
+ local tmp3 = z1 + w2 * 6270
+ local tmp0 = (w0 + w4) * 8192
+ local tmp1 = (w0 - w4) * 8192
+ local tmp10, tmp13 = tmp0 + tmp3, tmp0 - tmp3
+ local tmp11, tmp12 = tmp1 + tmp2, tmp1 - tmp2
+ local t0, t1, t2, t3 = w7, w5, w3, w1
+ z1 = t0 + t3
+ local z2 = t1 + t2
+ local z3 = t0 + t2
+ local z4 = t1 + t3
+ local z5 = (z3 + z4) * 9633
+ t0 *= 2446
+ t1 *= 16819
+ t2 *= 25172
+ t3 *= 12299
+ z1 *= -7373
+ z2 *= -20995
+ z3 = z3 * -16069 + z5
+ z4 = z4 * -3196 + z5
+ t0 += z1 + z3
+ t1 += z2 + z4
+ t2 += z2 + z3
+ t3 += z1 + z4
+ writeu16(plane, o, clamp((tmp10 + t3 + h2) // s2, 0, maxv))
+ writeu16(plane, o + 14, clamp((tmp10 - t3 + h2) // s2, 0, maxv))
+ writeu16(plane, o + 2, clamp((tmp11 + t2 + h2) // s2, 0, maxv))
+ writeu16(plane, o + 12, clamp((tmp11 - t2 + h2) // s2, 0, maxv))
+ writeu16(plane, o + 4, clamp((tmp12 + t1 + h2) // s2, 0, maxv))
+ writeu16(plane, o + 10, clamp((tmp12 - t1 + h2) // s2, 0, maxv))
+ writeu16(plane, o + 6, clamp((tmp13 + t0 + h2) // s2, 0, maxv))
+ writeu16(plane, o + 8, clamp((tmp13 - t0 + h2) // s2, 0, maxv))
+ end
+ end
+end
+
+local function idct4(coef: buffer, off: number, q: buffer, plane: buffer, out: number, stride: number, p1: number, center: number, maxv: number)
+ local s1 = 2 ^ (14 - p1)
+ local h1 = s1 / 2
+ local dcm = 2 ^ p1
+ for c = 0, 7 do
+ if c ~= 4 then
+ local o = off + c * 2
+ local qo = c * 2
+ local c1, c2, c3 = readi16(coef, o + 16), readi16(coef, o + 32), readi16(coef, o + 48)
+ local c5, c6, c7 = readi16(coef, o + 80), readi16(coef, o + 96), readi16(coef, o + 112)
+ if c1 == 0 and c2 == 0 and c3 == 0 and c5 == 0 and c6 == 0 and c7 == 0 then
+ local dc = readi16(coef, o) * readu16(q, qo) * dcm
+ ws[c + 1] = dc
+ ws[c + 9] = dc
+ ws[c + 17] = dc
+ ws[c + 25] = dc
+ else
+ local tmp0 = readi16(coef, o) * readu16(q, qo) * 16384
+ local tmp2 = c2 * readu16(q, qo + 32) * 15137 - c6 * readu16(q, qo + 96) * 6270
+ local tmp10, tmp12 = tmp0 + tmp2, tmp0 - tmp2
+ local z1 = c7 * readu16(q, qo + 112)
+ local z2 = c5 * readu16(q, qo + 80)
+ local z3 = c3 * readu16(q, qo + 48)
+ local z4 = c1 * readu16(q, qo + 16)
+ tmp0 = z1 * -1730 + z2 * 11893 + z3 * -17799 + z4 * 8697
+ tmp2 = z1 * -4176 + z2 * -4926 + z3 * 7373 + z4 * 20995
+ ws[c + 1] = (tmp10 + tmp2 + h1) // s1
+ ws[c + 25] = (tmp10 - tmp2 + h1) // s1
+ ws[c + 9] = (tmp12 + tmp0 + h1) // s1
+ ws[c + 17] = (tmp12 - tmp0 + h1) // s1
+ end
+ end
+ end
+ local s2 = 2 ^ (17 + p1)
+ local h2 = s2 / 2 + center * s2
+ local sd = 2 ^ (p1 + 3)
+ local hd = sd / 2 + center * sd
+ for r = 0, 3 do
+ local b = r * 8
+ local w0, w1, w2, w3 = ws[b + 1], ws[b + 2], ws[b + 3], ws[b + 4]
+ local w5, w6, w7 = ws[b + 6], ws[b + 7], ws[b + 8]
+ local o = (out + r * stride) * 2
+ if w1 == 0 and w2 == 0 and w3 == 0 and w5 == 0 and w6 == 0 and w7 == 0 then
+ local v = clamp((w0 + hd) // sd, 0, maxv)
+ writeu16(plane, o, v)
+ writeu16(plane, o + 2, v)
+ writeu16(plane, o + 4, v)
+ writeu16(plane, o + 6, v)
+ else
+ local tmp0 = w0 * 16384
+ local tmp2 = w2 * 15137 - w6 * 6270
+ local tmp10, tmp12 = tmp0 + tmp2, tmp0 - tmp2
+ tmp0 = w7 * -1730 + w5 * 11893 + w3 * -17799 + w1 * 8697
+ tmp2 = w7 * -4176 + w5 * -4926 + w3 * 7373 + w1 * 20995
+ writeu16(plane, o, clamp((tmp10 + tmp2 + h2) // s2, 0, maxv))
+ writeu16(plane, o + 6, clamp((tmp10 - tmp2 + h2) // s2, 0, maxv))
+ writeu16(plane, o + 2, clamp((tmp12 + tmp0 + h2) // s2, 0, maxv))
+ writeu16(plane, o + 4, clamp((tmp12 - tmp0 + h2) // s2, 0, maxv))
+ end
+ end
+end
+
+local function idct2(coef: buffer, off: number, q: buffer, plane: buffer, out: number, stride: number, p1: number, center: number, maxv: number)
+ local s1 = 2 ^ (15 - p1)
+ local h1 = s1 / 2
+ local dcm = 2 ^ p1
+ for c = 0, 7 do
+ if c ~= 2 and c ~= 4 and c ~= 6 then
+ local o = off + c * 2
+ local qo = c * 2
+ local c1, c3 = readi16(coef, o + 16), readi16(coef, o + 48)
+ local c5, c7 = readi16(coef, o + 80), readi16(coef, o + 112)
+ if c1 == 0 and c3 == 0 and c5 == 0 and c7 == 0 then
+ local dc = readi16(coef, o) * readu16(q, qo) * dcm
+ ws[c + 1] = dc
+ ws[c + 9] = dc
+ else
+ local tmp10 = readi16(coef, o) * readu16(q, qo) * 32768
+ local tmp0 = c7 * readu16(q, qo + 112) * -5906
+ + c5 * readu16(q, qo + 80) * 6967
+ + c3 * readu16(q, qo + 48) * -10426
+ + c1 * readu16(q, qo + 16) * 29692
+ ws[c + 1] = (tmp10 + tmp0 + h1) // s1
+ ws[c + 9] = (tmp10 - tmp0 + h1) // s1
+ end
+ end
+ end
+ local s2 = 2 ^ (18 + p1)
+ local h2 = s2 / 2 + center * s2
+ local sd = 2 ^ (p1 + 3)
+ local hd = sd / 2 + center * sd
+ for r = 0, 1 do
+ local b = r * 8
+ local w0, w1, w3, w5, w7 = ws[b + 1], ws[b + 2], ws[b + 4], ws[b + 6], ws[b + 8]
+ local o = (out + r * stride) * 2
+ if w1 == 0 and w3 == 0 and w5 == 0 and w7 == 0 then
+ local v = clamp((w0 + hd) // sd, 0, maxv)
+ writeu16(plane, o, v)
+ writeu16(plane, o + 2, v)
+ else
+ local tmp10 = w0 * 32768
+ local tmp0 = w7 * -5906 + w5 * 6967 + w3 * -10426 + w1 * 29692
+ writeu16(plane, o, clamp((tmp10 + tmp0 + h2) // s2, 0, maxv))
+ writeu16(plane, o + 2, clamp((tmp10 - tmp0 + h2) // s2, 0, maxv))
+ end
+ end
+end
+
+-- Inverse-transforms every block of a component: coef (i16, 64 per block, natural order) on a bpl x bpc block
+-- grid, quantisation table q (64 u16, natural order), into plane (u16 samples, (bpl * size) per row) at size x
+-- size samples per block. p1 is PASS1_BITS (2 for 8-bit, 1 for 12-bit), center the level shift, maxv the top.
+function Dct.idctComponent(coef: buffer, q: buffer, bpl: number, bpc: number, size: number, plane: buffer, p1: number, center: number, maxv: number)
+ local stride = bpl * size
+ for by = 0, bpc - 1 do
+ for bx = 0, bpl - 1 do
+ local off = (by * bpl + bx) * 128
+ local out = by * size * stride + bx * size
+ if size == 8 then
+ idct8(coef, off, q, plane, out, stride, p1, center, maxv)
+ elseif size == 4 then
+ idct4(coef, off, q, plane, out, stride, p1, center, maxv)
+ elseif size == 2 then
+ idct2(coef, off, q, plane, out, stride, p1, center, maxv)
+ else
+ local v = (readi16(coef, off) * readu16(q, 0) + 4) // 8 + center
+ writeu16(plane, out * 2, clamp(v, 0, maxv))
+ end
+ end
+ end
+end
+
+-- idctBlock(coef, off, q, plane, out, stride, p1, center, maxv): one 8x8 block, coef (i16, natural order) at byte
+-- offset off, dequantised by q (64 u16), into the u16 plane at sample index out with stride samples per row
+function Dct.idctBlock(coef: buffer, off: number, q: buffer, plane: buffer, out: number, stride: number, p1: number, center: number, maxv: number)
+ idct8(coef, off, q, plane, out, stride, p1, center, maxv)
+end
+
+-- ------------------------------------------------------------------------------------------------ forward
+local fw = table.create(64, 0)
+
+local function quant(coef: buffer, off: number, div: buffer, v: number, i: number)
+ local qv = readu16(div, i * 2) * 8
+ local h = qv // 2
+ if v < 0 then
+ writei16(coef, off + i * 2, -((h - v) // qv))
+ else
+ writei16(coef, off + i * 2, (v + h) // qv)
+ end
+end
+
+-- fdctQuantize(src, stride, x, y, w, h, div, coef, off): the 8x8 block of u8 samples at (x, y) in src (stride bytes
+-- per row; samples past w - 1 / h - 1 repeat the edge), level-shifted by 128, forward DCT (jfdctint.c islow), then
+-- quantised as jcdctmgr.c: (|v| + q * 4) // (q * 8) with the sign restored, q = div (64 u16, natural order). Writes
+-- 64 i16 at coef[off] (natural order). The caller keeps x < w, y < h and the src range valid.
+function Dct.fdctQuantize(src: buffer, stride: number, x: number, y: number, w: number, h: number, div: buffer, coef: buffer, off: number)
+ local lastX, lastY = w - 1, h - 1
+ for r = 0, 7 do
+ local row = math.min(y + r, lastY) * stride
+ local d0: number, d1: number, d2: number, d3: number, d4: number, d5: number, d6: number, d7: number
+ if x + 7 <= lastX then
+ local p = row + x
+ d0, d1, d2, d3 = readu8(src, p), readu8(src, p + 1), readu8(src, p + 2), readu8(src, p + 3)
+ d4, d5, d6, d7 = readu8(src, p + 4), readu8(src, p + 5), readu8(src, p + 6), readu8(src, p + 7)
+ else
+ d0 = readu8(src, row + math.min(x, lastX))
+ d1 = readu8(src, row + math.min(x + 1, lastX))
+ d2 = readu8(src, row + math.min(x + 2, lastX))
+ d3 = readu8(src, row + math.min(x + 3, lastX))
+ d4 = readu8(src, row + math.min(x + 4, lastX))
+ d5 = readu8(src, row + math.min(x + 5, lastX))
+ d6 = readu8(src, row + math.min(x + 6, lastX))
+ d7 = readu8(src, row + math.min(x + 7, lastX))
+ end
+ d0 -= 128
+ d1 -= 128
+ d2 -= 128
+ d3 -= 128
+ d4 -= 128
+ d5 -= 128
+ d6 -= 128
+ d7 -= 128
+ local tmp0, tmp7 = d0 + d7, d0 - d7
+ local tmp1, tmp6 = d1 + d6, d1 - d6
+ local tmp2, tmp5 = d2 + d5, d2 - d5
+ local tmp3, tmp4 = d3 + d4, d3 - d4
+ local tmp10, tmp13 = tmp0 + tmp3, tmp0 - tmp3
+ local tmp11, tmp12 = tmp1 + tmp2, tmp1 - tmp2
+ local b = r * 8 + 1
+ fw[b] = (tmp10 + tmp11) * 4
+ fw[b + 4] = (tmp10 - tmp11) * 4
+ local z1 = (tmp12 + tmp13) * 4433
+ fw[b + 2] = (z1 + tmp13 * 6270 + 1024) // 2048
+ fw[b + 6] = (z1 - tmp12 * 15137 + 1024) // 2048
+ z1 = tmp4 + tmp7
+ local z2 = tmp5 + tmp6
+ local z3 = tmp4 + tmp6
+ local z4 = tmp5 + tmp7
+ local z5 = (z3 + z4) * 9633
+ tmp4 *= 2446
+ tmp5 *= 16819
+ tmp6 *= 25172
+ tmp7 *= 12299
+ z1 *= -7373
+ z2 *= -20995
+ z3 = z3 * -16069 + z5
+ z4 = z4 * -3196 + z5
+ fw[b + 7] = (tmp4 + z1 + z3 + 1024) // 2048
+ fw[b + 5] = (tmp5 + z2 + z4 + 1024) // 2048
+ fw[b + 3] = (tmp6 + z2 + z3 + 1024) // 2048
+ fw[b + 1] = (tmp7 + z1 + z4 + 1024) // 2048
+ end
+ for c = 1, 8 do
+ local d0, d1, d2, d3 = fw[c], fw[c + 8], fw[c + 16], fw[c + 24]
+ local d4, d5, d6, d7 = fw[c + 32], fw[c + 40], fw[c + 48], fw[c + 56]
+ local tmp0, tmp7 = d0 + d7, d0 - d7
+ local tmp1, tmp6 = d1 + d6, d1 - d6
+ local tmp2, tmp5 = d2 + d5, d2 - d5
+ local tmp3, tmp4 = d3 + d4, d3 - d4
+ local tmp10, tmp13 = tmp0 + tmp3, tmp0 - tmp3
+ local tmp11, tmp12 = tmp1 + tmp2, tmp1 - tmp2
+ local o0 = (tmp10 + tmp11 + 2) // 4
+ local o4 = (tmp10 - tmp11 + 2) // 4
+ local z1 = (tmp12 + tmp13) * 4433
+ local o2 = (z1 + tmp13 * 6270 + 16384) // 32768
+ local o6 = (z1 - tmp12 * 15137 + 16384) // 32768
+ z1 = tmp4 + tmp7
+ local z2 = tmp5 + tmp6
+ local z3 = tmp4 + tmp6
+ local z4 = tmp5 + tmp7
+ local z5 = (z3 + z4) * 9633
+ tmp4 *= 2446
+ tmp5 *= 16819
+ tmp6 *= 25172
+ tmp7 *= 12299
+ z1 *= -7373
+ z2 *= -20995
+ z3 = z3 * -16069 + z5
+ z4 = z4 * -3196 + z5
+ local o7 = (tmp4 + z1 + z3 + 16384) // 32768
+ local o5 = (tmp5 + z2 + z4 + 16384) // 32768
+ local o3 = (tmp6 + z2 + z3 + 16384) // 32768
+ local o1 = (tmp7 + z1 + z4 + 16384) // 32768
+ local cc = c - 1
+ quant(coef, off, div, o0, cc)
+ quant(coef, off, div, o1, cc + 8)
+ quant(coef, off, div, o2, cc + 16)
+ quant(coef, off, div, o3, cc + 24)
+ quant(coef, off, div, o4, cc + 32)
+ quant(coef, off, div, o5, cc + 40)
+ quant(coef, off, div, o6, cc + 48)
+ quant(coef, off, div, o7, cc + 56)
+ end
+end
+
+return Dct
diff --git a/src/Formats/codecs/Lzw/init.luau b/src/Formats/codecs/Lzw/init.luau
new file mode 100644
index 0000000..168ded4
--- /dev/null
+++ b/src/Formats/codecs/Lzw/init.luau
@@ -0,0 +1,282 @@
+--!strict
+--!native
+--!optimize 2
+-- codecs/Lzw: LZW decoder and encoder in the two variants file formats use. A codec (layer 1): image/gif and
+-- image/tiff build on it. New code (no port), written from the GIF89a spec (appendix F) and TIFF 6.0 section 13.
+-- gif LSB-first codes, a minimum code size 1..11 (2..8 in GIF), clear = 2^min, EOI = clear + 1, the code width
+-- grows when the next free code reaches 2^width (max 12 bits; a full table stays frozen until a clear).
+-- tiff MSB-first codes, 8-bit symbols, clear = 256, EOI = 257, "early change": the width grows one code
+-- earlier (next free code = 2^width - 1). Old-style (pre-6.0, LSB-first, no early change) TIFF LZW is
+-- detected by its first bytes (0x00 then an odd byte) and decoded too.
+--
+-- local n, err = Lzw.decode(src, off, len, out, outOff, maxOut, "gif", minCodeSize) -- bytes written
+-- local n, err = Lzw.decode(src, off, len, out, outOff, maxOut, "tiff")
+-- local codes = Lzw.encode(data, off, len, "gif", minCodeSize) -- buffer
+-- local codes = Lzw.encode(data, off, len, "tiff")
+--
+-- decode writes at most maxOut bytes at out[outOff ..] and returns how many it wrote; it stops at EOI, at the end of
+-- the input or when out is full. err is nil for a clean stream, "truncated" when the input ended without EOI, or
+-- "corrupt" for an impossible code (everything decoded up to it is kept). Never throws; the caller checks that
+-- [outOff, outOff + maxOut) lies inside out and [off, off + len) inside src (decode clamps both anyway).
+local readu8, writeu8, readu16, writeu16 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16
+local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift
+local blen = buffer.len
+
+local Lzw = {}
+
+local MAX_CODES = 4096
+
+-- per-call tables (allocated once: decode / encode are not re-entrant across coroutines, but never yield)
+local prefix = buffer.create(MAX_CODES * 2) -- u16: the code this entry extends
+local suffix = buffer.create(MAX_CODES) -- u8: its last byte
+local first = buffer.create(MAX_CODES) -- u8: its first byte
+local length = buffer.create(MAX_CODES * 2) -- u16: its length
+
+-- ------------------------------------------------------------------------------------------------ decode
+-- writes the string of code c (length l) ending at out[o + l - 1]; clipped to [o, lim)
+local function emit(out: buffer, o: number, c: number, l: number, lim: number)
+ local p = o + l - 1
+ if p < lim then
+ while p >= o do
+ writeu8(out, p, readu8(suffix, c))
+ c = readu16(prefix, c * 2)
+ p -= 1
+ end
+ else
+ while p >= o do
+ if p < lim then
+ writeu8(out, p, readu8(suffix, c))
+ end
+ c = readu16(prefix, c * 2)
+ p -= 1
+ end
+ end
+end
+
+function Lzw.decode(src: buffer, off: number, len: number, out: buffer, outOff: number, maxOut: number, variant: string, minCodeSize: number?): (number, string?)
+ local n = blen(src)
+ if off < 0 or off > n then
+ return 0, "corrupt"
+ end
+ local e = math.min(off + math.max(0, len), n)
+ local lim = math.min(outOff + math.max(0, maxOut), blen(out))
+ if outOff < 0 then
+ return 0, "corrupt"
+ end
+ local msb = variant == "tiff"
+ local early = 0 -- 1 for TIFF's early change
+ local min = minCodeSize or 8
+ if msb then
+ min = 8
+ early = 1
+ -- old-style TIFF LZW: LSB-first, no early change (libtiff LZWPreDecode's check)
+ if e - off >= 2 and readu8(src, off) == 0 and band(readu8(src, off + 1), 1) == 1 then
+ msb = false
+ early = 0
+ end
+ end
+ if min < 1 or min > 11 then
+ return 0, "corrupt"
+ end
+ local clear = lshift(1, min)
+ local eoi = clear + 1
+ for i = 0, clear - 1 do
+ writeu16(prefix, i * 2, 0)
+ writeu8(suffix, i, band(i, 255))
+ writeu8(first, i, band(i, 255))
+ writeu16(length, i * 2, 1)
+ end
+ local size = min + 1
+ local mask = lshift(1, size) - 1
+ local nextc = clear + 2
+ local prev = -1
+ local o = outOff
+ local p = off
+ local acc, nb = 0, 0
+ while true do
+ -- refill (at most 12 + 7 bits held: below 2^20)
+ while nb < size do
+ if p >= e then
+ return o - outOff, "truncated"
+ end
+ if msb then
+ acc = acc * 256 + readu8(src, p)
+ else
+ acc += lshift(readu8(src, p), nb)
+ end
+ p += 1
+ nb += 8
+ end
+ local c
+ if msb then
+ nb -= size
+ c = band(rshift(acc, nb), mask)
+ acc = band(acc, lshift(1, nb) - 1)
+ else
+ c = band(acc, mask)
+ acc = rshift(acc, size)
+ nb -= size
+ end
+ if c == clear then
+ size = min + 1
+ mask = lshift(1, size) - 1
+ nextc = clear + 2
+ prev = -1
+ elseif c == eoi then
+ return o - outOff, nil
+ else
+ if o >= lim then
+ return o - outOff, nil -- full: the rest (normally just EOI) is ignored
+ end
+ if prev < 0 then
+ if c >= clear then
+ return o - outOff, "corrupt"
+ end
+ writeu8(out, o, readu8(suffix, c))
+ o += 1
+ prev = c
+ else
+ local l
+ if c < nextc then
+ l = readu16(length, c * 2)
+ emit(out, o, c, l, lim)
+ if nextc < MAX_CODES then
+ writeu16(prefix, nextc * 2, prev)
+ writeu8(suffix, nextc, readu8(first, c))
+ writeu8(first, nextc, readu8(first, prev))
+ writeu16(length, nextc * 2, readu16(length, prev * 2) + 1)
+ nextc += 1
+ end
+ elseif c == nextc and nextc < MAX_CODES then
+ -- KwKwK: the new entry is prev + first(prev)
+ local f = readu8(first, prev)
+ writeu16(prefix, nextc * 2, prev)
+ writeu8(suffix, nextc, f)
+ writeu8(first, nextc, f)
+ l = readu16(length, prev * 2) + 1
+ writeu16(length, nextc * 2, l)
+ nextc += 1
+ emit(out, o, c, l, lim)
+ else
+ return o - outOff, "corrupt"
+ end
+ o = math.min(o + l, lim)
+ prev = c
+ end
+ if nextc + early >= lshift(1, size) and size < 12 then
+ size += 1
+ mask = lshift(1, size) - 1
+ end
+ end
+ end
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+local HASH = 8192 -- open addressing over (prefix << 8 | byte) keys: a power of two above 4096 entries
+local hkey = buffer.create(HASH * 4) -- i32 key + 1 (0 = empty)
+local hval = buffer.create(HASH * 2) -- u16 code
+
+-- encode(data, off, len, variant, minCodeSize?) -> the code stream (GIF: without the sub-block framing). Symbols in
+-- data must be below 2^minCodeSize (GIF; larger ones are masked) or bytes (TIFF).
+function Lzw.encode(data: buffer, off: number, len: number, variant: string, minCodeSize: number?): buffer
+ local msb = variant == "tiff"
+ local min = if msb then 8 else math.clamp(minCodeSize or 8, 1, 11)
+ local early = if msb then 1 else 0
+ local symMask = lshift(1, min) - 1
+ local clear = lshift(1, min)
+ local eoi = clear + 1
+ local n = blen(data)
+ off = math.clamp(off, 0, n)
+ local e = math.clamp(off + len, off, n)
+ local cap = (e - off) * 2 + 64
+ local out = buffer.create(cap)
+ local op = 0
+ local acc, nb = 0, 0
+ local size = min + 1
+ local function put(code: number)
+ if op + 4 > cap then
+ cap *= 2
+ local nbuf = buffer.create(cap)
+ buffer.copy(nbuf, 0, out, 0, op)
+ out = nbuf
+ end
+ if msb then
+ acc = acc * lshift(1, size) + code
+ nb += size
+ while nb >= 8 do
+ nb -= 8
+ writeu8(out, op, rshift(acc, nb))
+ op += 1
+ acc = band(acc, lshift(1, nb) - 1)
+ end
+ else
+ acc += lshift(code, nb)
+ nb += size
+ while nb >= 8 do
+ writeu8(out, op, band(acc, 255))
+ op += 1
+ acc = rshift(acc, 8)
+ nb -= 8
+ end
+ end
+ end
+ buffer.fill(hkey, 0, 0, HASH * 4)
+ local nextc = clear + 2
+ put(clear)
+ if e > off then
+ local cur = band(readu8(data, off), symMask)
+ for i = off + 1, e - 1 do
+ local b = band(readu8(data, i), symMask)
+ local key = cur * 256 + b + 1
+ local h = band(cur * 31 + b * 4099, HASH - 1)
+ local found = -1
+ while true do
+ local k = buffer.readi32(hkey, h * 4)
+ if k == 0 then
+ break
+ elseif k == key then
+ found = readu16(hval, h * 2)
+ break
+ end
+ h = band(h + 1, HASH - 1)
+ end
+ if found >= 0 then
+ cur = found
+ else
+ put(cur)
+ if nextc >= MAX_CODES - 2 then
+ put(clear)
+ size = min + 1
+ nextc = clear + 2
+ buffer.fill(hkey, 0, 0, HASH * 4)
+ else
+ buffer.writei32(hkey, h * 4, key)
+ writeu16(hval, h * 2, nextc)
+ nextc += 1
+ if nextc + early > lshift(1, size) and size < 12 then
+ size += 1
+ end
+ end
+ cur = b
+ end
+ end
+ put(cur)
+ -- the decoder adds an entry for this last code too: its width may grow before EOI
+ if nextc < MAX_CODES then
+ nextc += 1
+ if nextc + early > lshift(1, size) and size < 12 then
+ size += 1
+ end
+ end
+ end
+ put(eoi)
+ if nb > 0 then
+ writeu8(out, op, if msb then band(lshift(acc, 8 - nb), 255) else band(acc, 255))
+ op += 1
+ end
+ local res = buffer.create(op)
+ buffer.copy(res, 0, out, 0, op)
+ return res
+end
+
+return Lzw
diff --git a/src/Formats/codecs/Quantize/init.luau b/src/Formats/codecs/Quantize/init.luau
new file mode 100644
index 0000000..df4dd53
--- /dev/null
+++ b/src/Formats/codecs/Quantize/init.luau
@@ -0,0 +1,483 @@
+--!strict
+--!native
+--!optimize 2
+-- codecs/Quantize: palette quantization of rgba8 pixels. A codec (layer 1): image/gif (and later any palette
+-- writer) builds on it. New code: Heckbert's median cut and Gervautz-Purgathofer octree, both over a 5-bit-per-channel
+-- weighted histogram (palette colours are the exact means of the pixels they cover), nearest-colour mapping with
+-- optional Floyd-Steinberg error diffusion. Deterministic: the same palette and indexes on every runtime (no table
+-- iteration order is ever relied on).
+--
+-- local pal, exact = Quantize.palette(pixels, w, h, 256, { method = "mediancut" }) -- { {r, g, b, 255} }, boolean
+-- local idx = Quantize.map(pixels, w, h, pal, { dither = true, transparentIndex = 255 }) -- buffer of w * h u8
+--
+-- Pixels with alpha < 128 are "transparent": palette() ignores them, map() gives them opts.transparentIndex (0-based)
+-- when set (otherwise they map like opaque pixels). When the opaque pixels have at most maxColors distinct colours,
+-- palette() returns exactly those (in first-seen order) and exact = true, and map() is then lossless. The octree
+-- folds whole nodes, so it may return fewer than maxColors entries; below 8 colours median cut is used instead.
+-- Never throws: bad arguments give an empty palette / a zero-filled index buffer.
+local readu8, writeu8 = buffer.readu8, buffer.writeu8
+local readu32, writeu32, readf64, writef64 = buffer.readu32, buffer.writeu32, buffer.readf64, buffer.writef64
+local floor = math.floor
+local blen = buffer.len
+
+local Quantize = {}
+
+export type Color = { number } -- { r, g, b, a } 0..255
+export type PaletteOptions = {
+ method: ("mediancut" | "octree")?, -- default "mediancut"
+}
+export type MapOptions = {
+ dither: boolean?, -- Floyd-Steinberg error diffusion (default false)
+ transparentIndex: number?, -- 0-based index for pixels with alpha < 128 (default: none)
+}
+
+local BINS = 32768 -- 5 bits per channel
+
+-- ------------------------------------------------------------------------------------------------ helpers
+local function count(pixels: buffer, n: number): (buffer, buffer)
+ -- per bin: u32 count; f64 sums of r, g, b
+ local cnt = buffer.create(BINS * 4)
+ local sums = buffer.create(BINS * 24)
+ for i = 0, n - 1 do
+ local o = i * 4
+ if readu8(pixels, o + 3) >= 128 then
+ local r, g, b = readu8(pixels, o), readu8(pixels, o + 1), readu8(pixels, o + 2)
+ local bin = (r // 8) * 1024 + (g // 8) * 32 + b // 8
+ writeu32(cnt, bin * 4, readu32(cnt, bin * 4) + 1)
+ local s = bin * 24
+ writef64(sums, s, readf64(sums, s) + r)
+ writef64(sums, s + 8, readf64(sums, s + 8) + g)
+ writef64(sums, s + 16, readf64(sums, s + 16) + b)
+ end
+ end
+ return cnt, sums
+end
+
+local function mean(cnt: buffer, sums: buffer, bins: { number }, lo: number, hi: number): Color
+ local n, r, g, b = 0, 0, 0, 0
+ for i = lo, hi do
+ local bin = bins[i]
+ n += readu32(cnt, bin * 4)
+ r += readf64(sums, bin * 24)
+ g += readf64(sums, bin * 24 + 8)
+ b += readf64(sums, bin * 24 + 16)
+ end
+ if n == 0 then
+ return { 0, 0, 0, 255 }
+ end
+ return { floor(r / n + 0.5), floor(g / n + 0.5), floor(b / n + 0.5), 255 }
+end
+
+-- ------------------------------------------------------------------------------------------------ median cut
+local function medianCut(cnt: buffer, sums: buffer, maxColors: number): { Color }
+ local bins: { number } = {}
+ for bin = 0, BINS - 1 do
+ if readu32(cnt, bin * 4) > 0 then
+ table.insert(bins, bin)
+ end
+ end
+ if #bins == 0 then
+ return {}
+ end
+ -- boxes: { lo, hi } ranges of the bins array
+ local boxes: { { number } } = {}
+ local function channel(bin: number, c: number): number
+ if c == 0 then
+ return bin // 1024
+ elseif c == 1 then
+ return (bin // 32) % 32
+ end
+ return bin % 32
+ end
+ local function stats(box: { number }): (number, number, number)
+ -- returns the widest channel, its range, the pixel count
+ local mins, maxs = { 31, 31, 31 }, { 0, 0, 0 }
+ local n = 0
+ for i = box[1], box[2] do
+ local bin = bins[i]
+ n += readu32(cnt, bin * 4)
+ for c = 0, 2 do
+ local v = channel(bin, c)
+ if v < mins[c + 1] then
+ mins[c + 1] = v
+ end
+ if v > maxs[c + 1] then
+ maxs[c + 1] = v
+ end
+ end
+ end
+ local best, range = 0, -1
+ for c = 0, 2 do
+ local rg = maxs[c + 1] - mins[c + 1]
+ if rg > range then
+ best, range = c, rg
+ end
+ end
+ return best, range, n
+ end
+ local function scored(lo: number, hi: number): { number }
+ local c, range, n = stats({ lo, hi })
+ return { lo, hi, c, if hi > lo then range * math.sqrt(n) else 0 }
+ end
+ boxes[1] = scored(1, #bins)
+ while #boxes < maxColors do
+ -- split the box with the largest range * sqrt(count) score (ties: the first)
+ local pick, pickScore = 0, 0
+ for i, box in boxes do
+ if box[4] > pickScore then
+ pick, pickScore = i, box[4]
+ end
+ end
+ if pick == 0 then
+ break
+ end
+ local box = boxes[pick]
+ local lo, hi, c = box[1], box[2], box[3]
+ -- sort the range by the channel, ties by bin number: unique numeric keys, no comparator
+ local keys = table.create(hi - lo + 1)
+ for i = lo, hi do
+ keys[i - lo + 1] = channel(bins[i], c) * BINS + bins[i]
+ end
+ table.sort(keys)
+ local total = 0
+ for i = 1, #keys do
+ local bin = keys[i] % BINS
+ bins[lo + i - 1] = bin
+ total += readu32(cnt, bin * 4)
+ end
+ -- the weighted median, keeping both halves non-empty
+ local acc, cut = 0, lo
+ for i = lo, hi - 1 do
+ acc += readu32(cnt, bins[i] * 4)
+ cut = i
+ if acc * 2 >= total then
+ break
+ end
+ end
+ boxes[pick] = scored(lo, cut)
+ table.insert(boxes, scored(cut + 1, hi))
+ end
+ local pal = table.create(#boxes)
+ for i, box in boxes do
+ pal[i] = mean(cnt, sums, bins, box[1], box[2])
+ end
+ return pal
+end
+
+-- ------------------------------------------------------------------------------------------------ octree
+-- over the histogram bins: 5 levels (one bit of each channel per level). Nodes are array slots.
+local function octree(cnt: buffer, sums: buffer, maxColors: number): { Color }
+ local child: { number } = {} -- node * 8 + k -> node (0 = none)
+ local n: { number } = {} -- pixel count
+ local sr: { number }, sg: { number }, sb: { number } = {}, {}, {}
+ local leaf: { boolean } = {}
+ local level: { number } = {}
+ local nodes = 1
+ n[1], sr[1], sg[1], sb[1], leaf[1], level[1] = 0, 0, 0, 0, false, 0
+ for k = 1, 8 do
+ child[k] = 0
+ end
+ local byLevel: { { number } } = { {}, {}, {}, {}, {} } -- inner nodes per level 0..4, creation order
+ table.insert(byLevel[1], 1)
+ local leaves = 0
+ for bin = 0, BINS - 1 do
+ local c = readu32(cnt, bin * 4)
+ if c > 0 then
+ local r5, g5, b5 = bin // 1024, (bin // 32) % 32, bin % 32
+ local node = 1
+ for lv = 0, 4 do
+ local sh = 4 - lv
+ local k = ((r5 // 2 ^ sh) % 2) * 4 + ((g5 // 2 ^ sh) % 2) * 2 + (b5 // 2 ^ sh) % 2
+ local slot = (node - 1) * 8 + k + 1
+ local nx = child[slot]
+ if nx == 0 then
+ nodes += 1
+ nx = nodes
+ child[slot] = nx
+ for j = 1, 8 do
+ child[(nx - 1) * 8 + j] = 0
+ end
+ n[nx], sr[nx], sg[nx], sb[nx], level[nx] = 0, 0, 0, 0, lv + 1
+ leaf[nx] = lv == 4
+ if lv == 4 then
+ leaves += 1
+ else
+ table.insert(byLevel[lv + 2], nx)
+ end
+ end
+ node = nx
+ end
+ n[node] += c
+ sr[node] += readf64(sums, bin * 24)
+ sg[node] += readf64(sums, bin * 24 + 8)
+ sb[node] += readf64(sums, bin * 24 + 16)
+ end
+ end
+ -- fold the deepest inner nodes (fewest pixels first, ties by creation order) until few enough leaves remain
+ local function fold(node: number): number
+ -- merges the children (all leaves) into node; returns how many leaves disappeared
+ local merged = 0
+ for k = 1, 8 do
+ local slot = (node - 1) * 8 + k
+ local ch = child[slot]
+ if ch ~= 0 then
+ n[node] += n[ch]
+ sr[node] += sr[ch]
+ sg[node] += sg[ch]
+ sb[node] += sb[ch]
+ child[slot] = 0
+ merged += 1
+ end
+ end
+ leaf[node] = true
+ return merged - 1
+ end
+ local function subtotal(node: number): number
+ local s = 0
+ for k = 1, 8 do
+ local ch = child[(node - 1) * 8 + k]
+ if ch ~= 0 then
+ s += n[ch]
+ end
+ end
+ return s
+ end
+ for lv = 5, 1, -1 do
+ if leaves <= maxColors then
+ break
+ end
+ local list = byLevel[lv]
+ local order = table.create(#list)
+ for i, node in list do
+ order[i] = { node, subtotal(node), i }
+ end
+ table.sort(order, function(a: { number }, b: { number }): boolean
+ if a[2] ~= b[2] then
+ return a[2] < b[2]
+ end
+ return a[3] < b[3]
+ end)
+ for _, e in order do
+ if leaves <= maxColors then
+ break
+ end
+ leaves -= fold(e[1])
+ end
+ end
+ -- collect leaves depth first in child order
+ local pal: { Color } = {}
+ local function walk(node: number)
+ if leaf[node] then
+ local c = n[node]
+ if c > 0 then
+ table.insert(pal, { floor(sr[node] / c + 0.5), floor(sg[node] / c + 0.5), floor(sb[node] / c + 0.5), 255 })
+ end
+ return
+ end
+ for k = 1, 8 do
+ local ch = child[(node - 1) * 8 + k]
+ if ch ~= 0 then
+ walk(ch)
+ end
+ end
+ end
+ walk(1)
+ -- the root itself can end up a leaf with everything (maxColors 1)
+ while #pal > maxColors do
+ table.remove(pal)
+ end
+ return pal
+end
+
+-- ------------------------------------------------------------------------------------------------ palette
+-- palette(pixels, w, h, maxColors, opts?) -> palette, exact
+function Quantize.palette(pixels: buffer, w: number, h: number, maxColors: number, opts: PaletteOptions?): ({ Color }, boolean)
+ if type(pixels) ~= "buffer" or type(w) ~= "number" or type(h) ~= "number" or w < 0 or h < 0 or blen(pixels) < w * h * 4 then
+ return {}, false
+ end
+ local maxc = math.clamp(floor(tonumber(maxColors) or 256), 1, 65536)
+ local npx = w * h
+ -- exact colours, in first-seen order (stops counting past maxColors)
+ local seen: { [number]: boolean } = {}
+ local exact: { Color } = {}
+ local over = false
+ for i = 0, npx - 1 do
+ local o = i * 4
+ if readu8(pixels, o + 3) >= 128 then
+ local r, g, b = readu8(pixels, o), readu8(pixels, o + 1), readu8(pixels, o + 2)
+ local key = r * 65536 + g * 256 + b
+ if not seen[key] then
+ if #exact >= maxc then
+ over = true
+ break
+ end
+ seen[key] = true
+ table.insert(exact, { r, g, b, 255 })
+ end
+ end
+ end
+ if not over then
+ return exact, true
+ end
+ local cnt, sums = count(pixels, npx)
+ local method = opts and opts.method or "mediancut"
+ if method == "octree" and maxc >= 8 then -- below 8 the octree can only fold to a single colour
+ return octree(cnt, sums, maxc), false
+ end
+ return medianCut(cnt, sums, maxc), false
+end
+
+-- ------------------------------------------------------------------------------------------------ map
+-- map(pixels, w, h, palette, opts?) -> buffer of w * h palette indexes (0-based)
+function Quantize.map(pixels: buffer, w: number, h: number, palette: { Color }, opts: MapOptions?): buffer
+ if type(pixels) ~= "buffer" or type(w) ~= "number" or type(h) ~= "number" or w < 0 or h < 0 or blen(pixels) < w * h * 4 or type(palette) ~= "table" then
+ return buffer.create(0)
+ end
+ local npx = w * h
+ local out = buffer.create(npx)
+ local dither = opts and opts.dither or false
+ local tidx = opts and opts.transparentIndex
+ -- the searchable entries (the transparent slot is excluded)
+ local pr, pg, pb, pi = {}, {}, {}, {}
+ for i, c in palette do
+ if tidx == nil or i - 1 ~= tidx then
+ table.insert(pr, c[1] or 0)
+ table.insert(pg, c[2] or 0)
+ table.insert(pb, c[3] or 0)
+ table.insert(pi, i - 1)
+ end
+ end
+ local np = #pr
+ -- sorted by green (the heaviest weight), so the search can stop once 4 * dg^2 alone is worse than the best
+ do
+ local order = table.create(np)
+ for k = 1, np do
+ order[k] = pg[k] * 65536 + k
+ end
+ table.sort(order)
+ local r2, g2, b2, i2 = table.create(np), table.create(np), table.create(np), table.create(np)
+ for k = 1, np do
+ local j = order[k] % 65536
+ r2[k], g2[k], b2[k], i2[k] = pr[j], pg[j], pb[j], pi[j]
+ end
+ pr, pg, pb, pi = r2, g2, b2, i2
+ end
+ local startAt = table.create(256, np) -- the first entry with green >= g (1-based), np + 1 past the end
+ do
+ local k = 1
+ for g = 0, 255 do
+ while k <= np and pg[k] < g do
+ k += 1
+ end
+ startAt[g + 1] = k
+ end
+ end
+ if np == 0 then
+ if tidx then
+ buffer.fill(out, 0, math.clamp(tidx, 0, 255), npx)
+ end
+ return out
+ end
+ local cache: { [number]: number } = {}
+ local function nearest(r: number, g: number, b: number): number
+ local key = r * 65536 + g * 256 + b
+ local hit = cache[key]
+ if hit then
+ return hit
+ end
+ local best, bd = 1, math.huge
+ local up = startAt[math.clamp(g, 0, 255) + 1]
+ local down = up - 1
+ while up <= np or down >= 1 do
+ if up <= np then
+ local dg = pg[up] - g
+ if dg * dg * 4 >= bd then
+ up = np + 1
+ else
+ local dr, db = r - pr[up], b - pb[up]
+ local d = dr * dr * 2 + dg * dg * 4 + db * db * 3
+ if d < bd then
+ best, bd = up, d
+ end
+ up += 1
+ end
+ end
+ if down >= 1 then
+ local dg = g - pg[down]
+ if dg * dg * 4 >= bd then
+ down = 0
+ else
+ local dr, db = r - pr[down], b - pb[down]
+ local d = dr * dr * 2 + dg * dg * 4 + db * db * 3
+ if d < bd then
+ best, bd = down, d
+ end
+ down -= 1
+ end
+ end
+ end
+ cache[key] = best
+ return best
+ end
+ local tbyte = if tidx then math.clamp(tidx, 0, 255) else 0
+ if not dither then
+ for i = 0, npx - 1 do
+ local o = i * 4
+ if tidx and readu8(pixels, o + 3) < 128 then
+ writeu8(out, i, tbyte)
+ else
+ writeu8(out, i, pi[nearest(readu8(pixels, o), readu8(pixels, o + 1), readu8(pixels, o + 2))])
+ end
+ end
+ return out
+ end
+ -- Floyd-Steinberg: error rows (f64 r, g, b per pixel, one extra pixel each side)
+ local rowLen = (w + 2) * 24
+ local cur, nxt = buffer.create(rowLen), buffer.create(rowLen)
+ for y = 0, h - 1 do
+ buffer.fill(nxt, 0, 0, rowLen)
+ for x = 0, w - 1 do
+ local i = y * w + x
+ local o = i * 4
+ if tidx and readu8(pixels, o + 3) < 128 then
+ writeu8(out, i, tbyte)
+ else
+ local e = (x + 1) * 24
+ local r = math.clamp(floor(readu8(pixels, o) + readf64(cur, e) + 0.5), 0, 255)
+ local g = math.clamp(floor(readu8(pixels, o + 1) + readf64(cur, e + 8) + 0.5), 0, 255)
+ local b = math.clamp(floor(readu8(pixels, o + 2) + readf64(cur, e + 16) + 0.5), 0, 255)
+ local k = nearest(r, g, b)
+ writeu8(out, i, pi[k])
+ local er, eg, eb = r - pr[k], g - pg[k], b - pb[k]
+ -- 7/16 right, 3/16 down-left, 5/16 down, 1/16 down-right
+ writef64(cur, e + 24, readf64(cur, e + 24) + er * 0.4375)
+ writef64(cur, e + 32, readf64(cur, e + 32) + eg * 0.4375)
+ writef64(cur, e + 40, readf64(cur, e + 40) + eb * 0.4375)
+ writef64(nxt, e - 24, readf64(nxt, e - 24) + er * 0.1875)
+ writef64(nxt, e - 16, readf64(nxt, e - 16) + eg * 0.1875)
+ writef64(nxt, e - 8, readf64(nxt, e - 8) + eb * 0.1875)
+ writef64(nxt, e, readf64(nxt, e) + er * 0.3125)
+ writef64(nxt, e + 8, readf64(nxt, e + 8) + eg * 0.3125)
+ writef64(nxt, e + 16, readf64(nxt, e + 16) + eb * 0.3125)
+ writef64(nxt, e + 24, readf64(nxt, e + 24) + er * 0.0625)
+ writef64(nxt, e + 32, readf64(nxt, e + 32) + eg * 0.0625)
+ writef64(nxt, e + 40, readf64(nxt, e + 40) + eb * 0.0625)
+ end
+ end
+ cur, nxt = nxt, cur
+ end
+ return out
+end
+
+-- quantize(pixels, w, h, maxColors, opts?) -> indexes, palette, exact: palette() then map() (opts of both)
+function Quantize.quantize(pixels: buffer, w: number, h: number, maxColors: number, opts: any?): (buffer, { Color }, boolean)
+ local pal, exact = Quantize.palette(pixels, w, h, maxColors, opts)
+ local mo = opts
+ if exact and opts and opts.dither then
+ mo = table.clone(opts)
+ mo.dither = false -- nothing to diffuse
+ end
+ return Quantize.map(pixels, w, h, pal, mo), pal, exact
+end
+
+return Quantize
diff --git a/src/Formats/image/gif/Decode.luau b/src/Formats/image/gif/Decode.luau
new file mode 100644
index 0000000..98a6c7c
--- /dev/null
+++ b/src/Formats/image/gif/Decode.luau
@@ -0,0 +1,68 @@
+--!strict
+--!native
+--!optimize 2
+-- image/gif/Decode: the per-frame pixel work (native; never throws): palette indexes (plain or interlaced rows) to
+-- rgba8, and drawing a frame onto the canvas (transparent pixels leave the canvas as it is). The caller sizes every
+-- buffer: indexes fw * fh bytes, the palette 256 u32 entries, the frame fw * fh * 4, the canvas cw * ch * 4.
+local readu8, readu32, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu32
+
+local Decode = {}
+
+-- the source row of output row y in an interlaced frame (passes: every 8th from 0, every 8th from 4, every 4th from
+-- 2, every 2nd from 1)
+local function interlacedRow(fh: number): { number }
+ local map = table.create(fh, 0)
+ local r = 0
+ for _, pass in { { 0, 8 }, { 4, 8 }, { 2, 4 }, { 1, 2 } } do
+ local y = pass[1]
+ while y < fh do
+ map[y + 1] = r
+ r += 1
+ y += pass[2]
+ end
+ end
+ return map
+end
+
+-- toRgba(indexes, fw, fh, interlaced, palette, out): out = the frame in rgba8 (palette: 256 u32 entries, the
+-- transparent one already alpha 0)
+function Decode.toRgba(indexes: buffer, fw: number, fh: number, interlaced: boolean, palette: buffer, out: buffer)
+ local rows = if interlaced then interlacedRow(fh) else nil
+ for y = 0, fh - 1 do
+ local src = (if rows then rows[y + 1] else y) * fw
+ local dst = y * fw * 4
+ for x = 0, fw - 1 do
+ writeu32(out, dst + x * 4, readu32(palette, readu8(indexes, src + x) * 4))
+ end
+ end
+end
+
+-- draw(canvas, cw, ch, frame, fx, fy, fw, fh): frame pixels with alpha > 0 replace the canvas (clipped)
+function Decode.draw(canvas: buffer, cw: number, ch: number, frame: buffer, fx: number, fy: number, fw: number, fh: number)
+ local x0, y0 = math.max(0, fx), math.max(0, fy)
+ local x1, y1 = math.min(cw, fx + fw), math.min(ch, fy + fh)
+ for y = y0, y1 - 1 do
+ local s = ((y - fy) * fw - fx) * 4
+ local d = y * cw * 4
+ for x = x0, x1 - 1 do
+ local v = readu32(frame, s + x * 4)
+ if v >= 0x01000000 then
+ writeu32(canvas, d + x * 4, v)
+ end
+ end
+ end
+end
+
+-- clear(canvas, cw, ch, fx, fy, fw, fh): the frame's rectangle to transparent black (dispose to background)
+function Decode.clear(canvas: buffer, cw: number, ch: number, fx: number, fy: number, fw: number, fh: number)
+ local x0, y0 = math.max(0, fx), math.max(0, fy)
+ local x1, y1 = math.min(cw, fx + fw), math.min(ch, fy + fh)
+ if x1 <= x0 then
+ return
+ end
+ for y = y0, y1 - 1 do
+ buffer.fill(canvas, (y * cw + x0) * 4, 0, (x1 - x0) * 4)
+ end
+end
+
+return Decode
diff --git a/src/Formats/image/gif/init.luau b/src/Formats/image/gif/init.luau
new file mode 100644
index 0000000..c2b84f4
--- /dev/null
+++ b/src/Formats/image/gif/init.luau
@@ -0,0 +1,534 @@
+--!strict
+-- image/gif: GIF87a / GIF89a. New code from the GIF89a spec (W3C / CompuServe 1990). Supports: decode of every image
+-- (global / local colour tables, interlaced rows, LZW minimum code sizes 2..8 and the odd 1, transparency, frames
+-- smaller than or outside the canvas), animation (Graphic Control Extension delays, disposal none / background /
+-- previous, NETSCAPE2.0 / ANIMEXTS1.0 loop counts), comments (meta.text.comment); truncated files keep the frames
+-- read so far (meta.truncated). Encode of rgba8 images and animations (Types.Frame lists) through codecs/Quantize
+-- (median cut or octree, optional Floyd-Steinberg dithering; exact palettes, so lossless, at <= 256 colours) with
+-- alpha < 128 as the transparent index.
+-- Not supported: the plain text extension (skipped), the aspect ratio (kept in meta.source.aspect), the "user input"
+-- flag, and blend = "source" frames that clear pixels to transparent (GIF can only draw over).
+--
+-- Decoded value: img.pixels = the first frame composited on a transparent canvas; for animations img.frames = every
+-- frame's own rectangle (rgba8; blend "over" when it has a transparent index, else "source") and img.loops, the
+-- number of plays (0 = forever; 1 when the file has no loop extension). The NETSCAPE2.0 value counts repeats, as
+-- browsers and ImageMagick read it: a stored n plays n + 1 times (n = 0: forever).
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Lzw = require("@formats/codecs/Lzw")
+local Quantize = require("@formats/codecs/Quantize")
+local Types = require("@formats/Types")
+local Decode = require("@formats/image/gif/Decode")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Gif = {
+ name = "gif",
+ category = "image",
+ extensions = { "gif" },
+ mime = { "image/gif" },
+ deps = { "core/Err", "core/Bytes", "codecs/Lzw", "codecs/Quantize", "Types" },
+ caps = { decode = true, encode = true, animation = true, alpha = true, palette = true, depths = { 1, 2, 4, 8 } },
+}
+
+-- ------------------------------------------------------------------------------------------------ types
+export type DecodeOptions = {
+ maxPixels: number?, -- refuse a canvas or frame larger than this (default 2^26)
+ maxTotalPixels: number?, -- refuse animations whose frames add up to more (default 2^28)
+ maxFrames: number?, -- stop after this many frames (default: all)
+}
+export type EncodeOptions = {
+ maxColors: number?, -- 2..256 per palette (default 256; one is taken by transparency when needed)
+ method: ("mediancut" | "octree")?, -- default "mediancut"
+ dither: boolean?, -- Floyd-Steinberg (default false)
+ loops: number?, -- animation plays override (0 = forever, 1..65536; default img.loops)
+ globalPalette: boolean?, -- one palette for every frame (default false: a single image uses the global table,
+ -- each animation frame gets its own local table)
+}
+
+-- ------------------------------------------------------------------------------------------------ constants
+local readu8 = buffer.readu8
+local DISPOSE = { [0] = "none", [1] = "none", [2] = "background", [3] = "previous" }
+local DISPOSE_CODE = { none = 1, background = 2, previous = 3 }
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Gif.sniff(r: Bytes.Reader): number
+ local s = r:peek(6)
+ return if s == "GIF89a" or s == "GIF87a" then 1 else 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+-- a colour table at p (n entries) -> 256 u32 rgba entries (missing ones opaque black) and the { r, g, b, a } list
+local function colorTable(b: buffer, p: number, n: number): (buffer, { { number } })
+ local t = buffer.create(1024)
+ local list = table.create(n)
+ for i = 0, 255 do
+ buffer.writeu32(t, i * 4, 0xFF000000)
+ end
+ for i = 0, n - 1 do
+ local q = p + i * 3
+ local r, g, bl = readu8(b, q), readu8(b, q + 1), readu8(b, q + 2)
+ buffer.writeu32(t, i * 4, r + g * 256 + bl * 65536 + 0xFF000000)
+ list[i + 1] = { r, g, bl, 255 }
+ end
+ return t, list
+end
+
+function Gif.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
+ local maxPixels = opts and opts.maxPixels or 2 ^ 26
+ local maxTotal = opts and opts.maxTotalPixels or 2 ^ 28
+ local maxFrames = opts and opts.maxFrames or math.huge
+ local sig = r:string(6)
+ local cw, ch = r:u16le(), r:u16le()
+ local flags, bg, aspect = r:u8(), r:u8(), r:u8()
+ if r.err then
+ return nil, r.err
+ end
+ if sig ~= "GIF89a" and sig ~= "GIF87a" then
+ return nil, Err.new(Err.CORRUPT, "bad signature", r.base)
+ end
+ if cw == 0 or ch == 0 then
+ return nil, Err.new(Err.CORRUPT, "zero canvas size", r.base + 6)
+ end
+ if cw * ch > maxPixels then
+ return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", cw, ch, maxPixels))
+ end
+ local b = r.buf
+ local gct: buffer? = nil
+ local gpal: { { number } }? = nil
+ if bit32.band(flags, 0x80) ~= 0 then
+ local n = bit32.lshift(1, bit32.band(flags, 7) + 1)
+ if not r:need(n * 3) then
+ return nil, r.err
+ end
+ gct, gpal = colorTable(b, r.pos, n)
+ r.pos += n * 3
+ end
+ local img = Types.Image.new(cw, ch, "rgba8")
+ local frames: { Types.Frame } = {}
+ local comments: { string } = {}
+ local loops: number? = nil
+ local total = 0
+ -- the pending Graphic Control Extension
+ local delay, dispose, trans = 0, 0, -1
+ local truncated = false
+ local interlacedAny = false
+ local localTables = 0
+ local minCode = 8
+ local limit = r.limit
+ -- the sub-blocks at r.pos: joined into one buffer (nil when they run past the end)
+ local function subBlocks(): (buffer?, number)
+ local p = r.pos
+ local n = 0
+ while true do
+ if p >= limit then
+ return nil, p
+ end
+ local len = readu8(b, p)
+ if len == 0 then
+ break
+ end
+ if p + 1 + len > limit then
+ -- keep what is there: a truncated last block
+ n += limit - p - 1
+ p = limit
+ local out = buffer.create(n)
+ local q, o = r.pos, 0
+ while q < limit do
+ local l = math.min(readu8(b, q), limit - q - 1)
+ buffer.copy(out, o, b, q + 1, l)
+ o += l
+ q += 1 + l
+ end
+ return out, -1
+ end
+ n += len
+ p += 1 + len
+ end
+ local out = buffer.create(n)
+ local q, o = r.pos, 0
+ while q < p do
+ local l = readu8(b, q)
+ buffer.copy(out, o, b, q + 1, l)
+ o += l
+ q += 1 + l
+ end
+ return out, p + 1
+ end
+ local function skipBlocks(): boolean
+ local p = r.pos
+ while p < limit do
+ local len = readu8(b, p)
+ if len == 0 then
+ r.pos = p + 1
+ return true
+ end
+ p += 1 + len
+ end
+ r.pos = limit
+ return false
+ end
+ while true do
+ if r.pos >= limit then
+ truncated = true
+ break
+ end
+ local intro = r:u8()
+ if intro == 0x3B then
+ break
+ elseif intro == 0x21 then
+ local label = r:u8()
+ if r.err then
+ truncated = true
+ break
+ end
+ local p = r.pos
+ if label == 0xF9 and p + 6 <= limit and readu8(b, p) >= 4 then
+ local f = readu8(b, p + 1)
+ dispose = bit32.band(bit32.rshift(f, 2), 7)
+ delay = readu8(b, p + 2) + readu8(b, p + 3) * 256
+ trans = if bit32.band(f, 1) ~= 0 then readu8(b, p + 4) else -1
+ elseif label == 0xFF and p + 15 <= limit and readu8(b, p) == 11 then
+ local id = buffer.readstring(b, p + 1, 11)
+ if (id == "NETSCAPE2.0" or id == "ANIMEXTS1.0") and readu8(b, p + 12) >= 3 and readu8(b, p + 13) == 1 then
+ local rep = readu8(b, p + 14) + readu8(b, p + 15) * 256
+ loops = if rep == 0 then 0 else rep + 1 -- the stored value repeats: plays = value + 1
+ end
+ elseif label == 0xFE then
+ local data = subBlocks()
+ if data then
+ table.insert(comments, buffer.tostring(data))
+ end
+ end
+ if not skipBlocks() then
+ truncated = true
+ break
+ end
+ elseif intro == 0x2C then
+ local fx, fy, fw, fh = r:u16le(), r:u16le(), r:u16le(), r:u16le()
+ local f = r:u8()
+ if r.err then
+ truncated = true
+ break
+ end
+ if fw * fh > maxPixels then
+ return nil, Err.new(Err.LIMIT, string.format("a %d x %d frame is over the %d pixel limit", fw, fh, maxPixels), r.pos)
+ end
+ total += fw * fh
+ if total > maxTotal then
+ return nil, Err.new(Err.LIMIT, string.format("the frames add up to over %d pixels", maxTotal), r.pos)
+ end
+ local pal = gct
+ if bit32.band(f, 0x80) ~= 0 then
+ local n = bit32.lshift(1, bit32.band(f, 7) + 1)
+ if not r:need(n * 3) then
+ truncated = true
+ break
+ end
+ pal = colorTable(b, r.pos, n)
+ r.pos += n * 3
+ localTables += 1
+ end
+ local interlaced = bit32.band(f, 0x40) ~= 0
+ interlacedAny = interlacedAny or interlaced
+ local mc = r:u8()
+ if r.err then
+ truncated = true
+ break
+ end
+ if mc < 1 or mc > 11 then
+ return nil, Err.new(Err.CORRUPT, "bad LZW minimum code size " .. mc, r.pos - 1)
+ end
+ minCode = mc
+ local data, nextPos = subBlocks()
+ if not data then
+ truncated = true
+ break
+ end
+ local n = fw * fh
+ local idx = buffer.create(n)
+ local got, lerr = Lzw.decode(data, 0, buffer.len(data), idx, 0, n, "gif", mc)
+ if got < n or nextPos < 0 then
+ truncated = true -- the missing pixels stay index 0, as most decoders show them
+ end
+ local _ = lerr -- a corrupt code ends the frame early (kept: what was decoded is shown)
+ local t = buffer.create(1024)
+ if pal then
+ buffer.copy(t, 0, pal)
+ else
+ -- no colour table at all: a grey ramp (what the spec leaves to the decoder)
+ for i = 0, 255 do
+ buffer.writeu32(t, i * 4, i + i * 256 + i * 65536 + 0xFF000000)
+ end
+ end
+ if trans >= 0 then
+ buffer.writeu32(t, trans * 4, 0)
+ end
+ local fimg = Types.Image.new(fw, fh, "rgba8")
+ Decode.toRgba(idx, fw, fh, interlaced, t, fimg.pixels)
+ if #frames == 0 then
+ Decode.draw(img.pixels, cw, ch, fimg.pixels, fx, fy, fw, fh)
+ end
+ table.insert(frames, {
+ image = fimg,
+ delay = delay / 100,
+ x = fx,
+ y = fy,
+ dispose = DISPOSE[dispose] or "none",
+ blend = if trans >= 0 then "over" else "source",
+ } :: Types.Frame)
+ delay, dispose, trans = 0, 0, -1
+ if nextPos < 0 then
+ break
+ end
+ r.pos = nextPos
+ if #frames >= maxFrames then
+ break
+ end
+ else
+ -- junk between blocks: stop here, keeping what was read
+ if #frames == 0 then
+ return nil, Err.new(Err.CORRUPT, string.format("bad block introducer 0x%02x", intro), r.pos - 1)
+ end
+ truncated = true
+ break
+ end
+ end
+ if #frames == 0 then
+ return nil, Err.new(Err.TRUNCATED, "no image data", r.pos)
+ end
+ if #frames > 1 then
+ img.frames = frames
+ img.loops = loops or 1
+ else
+ img.loops = loops or 0
+ end
+ img.meta.palette = gpal
+ img.meta.background = bg
+ if #comments > 0 then
+ img.meta.text = { comment = table.concat(comments, "\n") }
+ end
+ if truncated then
+ img.meta.truncated = true
+ end
+ img.meta.source = {
+ format = "gif",
+ version = string.sub(sig, 4),
+ bitDepth = minCode,
+ colorType = "palette",
+ frames = #frames,
+ interlaced = interlacedAny,
+ localPalettes = localTables,
+ aspect = aspect,
+ loopExtension = loops ~= nil,
+ }
+ return img, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+local function validImage(i: any): boolean
+ return type(i) == "table" and i.format == "rgba8" and type(i.pixels) == "buffer" and type(i.width) == "number" and type(i.height) == "number" and i.width >= 1 and i.height >= 1 and i.width <= 65535 and i.height <= 65535 and i.width % 1 == 0 and i.height % 1 == 0 and buffer.len(i.pixels) >= i.width * i.height * 4
+end
+
+local function hasTransparency(px: buffer, n: number): boolean
+ for i = 0, n - 1 do
+ if readu8(px, i * 4 + 3) < 128 then
+ return true
+ end
+ end
+ return false
+end
+
+-- palette list -> padded table bytes (power of two entries, >= 2) and its size code
+local function writeTable(w: Bytes.Writer, pal: { { number } }): number
+ local bits = 1
+ while bit32.lshift(1, bits) < #pal do
+ bits += 1
+ end
+ for i = 1, bit32.lshift(1, bits) do
+ local c = pal[i]
+ if c then
+ w:u8(c[1])
+ w:u8(c[2])
+ w:u8(c[3])
+ else
+ w:fill(0, 3)
+ end
+ end
+ return bits
+end
+
+local function tableBits(n: number): number
+ local bits = 1
+ while bit32.lshift(1, bits) < n do
+ bits += 1
+ end
+ return bits
+end
+
+function Gif.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
+ if not validImage(img) then
+ return nil, Err.new(Err.ARG, "needs an rgba8 Image of 1..65535 x 1..65535 pixels")
+ end
+ local maxColors = opts and opts.maxColors or 256
+ if type(maxColors) ~= "number" or maxColors < 2 or maxColors > 256 then
+ return nil, Err.new(Err.ARG, "maxColors must be 2..256")
+ end
+ maxColors = math.floor(maxColors)
+ local method = opts and opts.method or "mediancut"
+ if method ~= "mediancut" and method ~= "octree" then
+ return nil, Err.new(Err.ARG, "method must be mediancut or octree")
+ end
+ local dither = opts and opts.dither or false
+ -- the frames to write: { image, x, y, delay, dispose }
+ local list: { Types.Frame } = {}
+ if type(img.frames) == "table" and #(img.frames :: any) > 0 then
+ for i, f in img.frames :: { Types.Frame } do
+ if type(f) ~= "table" or not validImage(f.image) then
+ return nil, Err.new(Err.ARG, "frame " .. i .. ": needs an rgba8 image")
+ end
+ local x, y = f.x or 0, f.y or 0
+ if type(x) ~= "number" or type(y) ~= "number" or x < 0 or y < 0 or x + f.image.width > 65535 or y + f.image.height > 65535 then
+ return nil, Err.new(Err.ARG, "frame " .. i .. ": bad position")
+ end
+ table.insert(list, f)
+ end
+ else
+ list[1] = { image = img, x = 0, y = 0, delay = 0, dispose = "none", blend = "source" }
+ end
+ local animated = #list > 1
+ local loops = opts and opts.loops or img.loops or 0
+ if type(loops) ~= "number" or loops < 0 or loops > 65536 or loops % 1 ~= 0 then
+ return nil, Err.new(Err.ARG, "loops must be 0..65536")
+ end
+ -- palettes
+ local shared = (opts and opts.globalPalette) or not animated
+ local qopts = { method = method, dither = dither }
+ local globalPal: { { number } }? = nil
+ local globalTrans = false
+ if shared then
+ -- every frame's pixels together
+ local npx = 0
+ for _, f in list do
+ npx += f.image.width * f.image.height
+ end
+ local all = buffer.create(npx * 4)
+ local o = 0
+ for _, f in list do
+ local n = f.image.width * f.image.height * 4
+ buffer.copy(all, o, f.image.pixels, 0, n)
+ o += n
+ end
+ globalTrans = hasTransparency(all, npx)
+ local pal = Quantize.palette(all, npx, 1, if globalTrans then maxColors - 1 else maxColors, qopts)
+ if #pal == 0 then
+ pal = { { 0, 0, 0, 255 } }
+ end
+ if globalTrans then
+ table.insert(pal, { 0, 0, 0, 0 })
+ end
+ globalPal = pal
+ end
+ local w = Bytes.writer(img.width * img.height + 1024)
+ w:string("GIF89a")
+ w:u16le(img.width)
+ w:u16le(img.height)
+ if globalPal then
+ w:u8(0x80 + 0x70 + (tableBits(#globalPal) - 1))
+ w:u8(0)
+ w:u8(0)
+ writeTable(w, globalPal)
+ else
+ w:u8(0x70)
+ w:u8(0)
+ w:u8(0)
+ end
+ if animated and loops ~= 1 then
+ w:u8(0x21)
+ w:u8(0xFF)
+ w:u8(11)
+ w:string("NETSCAPE2.0")
+ w:u8(3)
+ w:u8(1)
+ w:u16le(if loops == 0 then 0 else loops - 1)
+ w:u8(0)
+ end
+ local text = img.meta and img.meta.text
+ local comment = text and (text.comment or text.Comment)
+ if type(comment) == "string" and #comment > 0 then
+ w:u8(0x21)
+ w:u8(0xFE)
+ for i = 1, #comment, 255 do
+ local part = string.sub(comment, i, i + 254)
+ w:u8(#part)
+ w:string(part)
+ end
+ w:u8(0)
+ end
+ for _, f in list do
+ local fi = f.image
+ local fw, fh = fi.width, fi.height
+ local n = fw * fh
+ local pal: { { number } }
+ local tidx: number? = nil
+ if globalPal then
+ pal = globalPal
+ if globalTrans then
+ tidx = #pal - 1
+ end
+ else
+ local tr = hasTransparency(fi.pixels, n)
+ pal = Quantize.palette(fi.pixels, fw, fh, if tr then maxColors - 1 else maxColors, qopts)
+ if #pal == 0 then
+ pal = { { 0, 0, 0, 255 } }
+ end
+ if tr then
+ table.insert(pal, { 0, 0, 0, 0 })
+ tidx = #pal - 1
+ end
+ end
+ local idx = Quantize.map(fi.pixels, fw, fh, pal, { dither = dither, transparentIndex = tidx })
+ -- the Graphic Control Extension: always for animations, else only for transparency
+ if animated or tidx then
+ local d = DISPOSE_CODE[f.dispose or "none"] or 1
+ w:u8(0x21)
+ w:u8(0xF9)
+ w:u8(4)
+ w:u8(d * 4 + (if tidx then 1 else 0))
+ w:u16le(math.clamp(math.floor((f.delay or 0) * 100 + 0.5), 0, 65535))
+ w:u8(tidx or 0)
+ w:u8(0)
+ end
+ w:u8(0x2C)
+ w:u16le(f.x or 0)
+ w:u16le(f.y or 0)
+ w:u16le(fw)
+ w:u16le(fh)
+ local bits
+ if globalPal then
+ w:u8(0)
+ bits = tableBits(#globalPal)
+ else
+ bits = tableBits(#pal)
+ w:u8(0x80 + bits - 1)
+ writeTable(w, pal)
+ end
+ local mc = math.max(2, bits)
+ w:u8(mc)
+ local codes = Lzw.encode(idx, 0, n, "gif", mc)
+ local cl = buffer.len(codes)
+ local p = 0
+ while p < cl do
+ local l = math.min(255, cl - p)
+ w:u8(l)
+ w:bytes(codes, p, l)
+ p += l
+ end
+ w:u8(0)
+ end
+ w:u8(0x3B)
+ return w:finish(), nil
+end
+
+return Gif
diff --git a/src/Formats/image/hdr/Codec.luau b/src/Formats/image/hdr/Codec.luau
new file mode 100644
index 0000000..7f97f5e
--- /dev/null
+++ b/src/Formats/image/hdr/Codec.luau
@@ -0,0 +1,219 @@
+--!strict
+--!native
+--!optimize 2
+-- image/hdr/Codec: Radiance RGBE scanlines (native; never throws). Written from the Radiance file format notes
+-- (Greg Ward, "Real Pixels", Graphics Gems II) and Bruce Walter's rgbe.c conventions: flat pixels, old-style RLE
+-- (1, 1, 1, n repeats the previous pixel, shifted by 8 for consecutive markers) and new-style RLE (2, 2, width, then
+-- four run-length coded channel planes). RGBE -> float is mantissa * 2^(e - 136), as rgbe.c, stb_image and
+-- ImageMagick (no +0.5 offset); float -> RGBE as rgbe.c float2rgbe (frexp). Every read is bounds-checked.
+local readu8, writeu8, writef32, readf32 = buffer.readu8, buffer.writeu8, buffer.writef32, buffer.readf32
+local frexp = math.frexp
+
+local Codec = {}
+
+-- readLine(b, p, limit, w, row) -> new position | nil, message: one scanline into row (w * 4 RGBE bytes)
+function Codec.readLine(b: buffer, p: number, limit: number, w: number, row: buffer): (number?, string?)
+ if w >= 8 and w <= 32767 and p + 4 <= limit and readu8(b, p) == 2 and readu8(b, p + 1) == 2 and readu8(b, p + 2) < 128 then
+ if readu8(b, p + 2) * 256 + readu8(b, p + 3) ~= w then
+ return nil, "scanline width mismatch"
+ end
+ p += 4
+ for c = 0, 3 do
+ local x = 0
+ while x < w do
+ if p >= limit then
+ return nil, "truncated"
+ end
+ local n = readu8(b, p)
+ p += 1
+ if n > 128 then
+ n -= 128
+ if x + n > w or p >= limit then
+ return nil, if p >= limit then "truncated" else "bad run"
+ end
+ local v = readu8(b, p)
+ p += 1
+ for i = x, x + n - 1 do
+ writeu8(row, i * 4 + c, v)
+ end
+ else
+ if n == 0 or x + n > w then
+ return nil, "bad count"
+ end
+ if p + n > limit then
+ return nil, "truncated"
+ end
+ for i = x, x + n - 1 do
+ writeu8(row, i * 4 + c, readu8(b, p))
+ p += 1
+ end
+ end
+ x += n
+ end
+ end
+ return p, nil
+ end
+ -- flat pixels, with old-style runs
+ local x = 0
+ local shift = 0
+ while x < w do
+ if p + 4 > limit then
+ return nil, "truncated"
+ end
+ local r, g, bl, e = readu8(b, p), readu8(b, p + 1), readu8(b, p + 2), readu8(b, p + 3)
+ p += 4
+ if r == 1 and g == 1 and bl == 1 then
+ if x == 0 then
+ return nil, "run at the start of a scanline"
+ end
+ local n = e * 2 ^ shift
+ if x + n > w then
+ return nil, "bad run"
+ end
+ local q = (x - 1) * 4
+ local pr, pg, pb, pe = readu8(row, q), readu8(row, q + 1), readu8(row, q + 2), readu8(row, q + 3)
+ for i = x, x + n - 1 do
+ writeu8(row, i * 4, pr)
+ writeu8(row, i * 4 + 1, pg)
+ writeu8(row, i * 4 + 2, pb)
+ writeu8(row, i * 4 + 3, pe)
+ end
+ x += n
+ shift += 8
+ if shift > 24 then
+ return nil, "bad run"
+ end
+ else
+ writeu8(row, x * 4, r)
+ writeu8(row, x * 4 + 1, g)
+ writeu8(row, x * 4 + 2, bl)
+ writeu8(row, x * 4 + 3, e)
+ x += 1
+ shift = 0
+ end
+ end
+ return p, nil
+end
+
+-- toFloat(row, n, out, offsets): n RGBE pixels -> rgbaf32 at out byte offsets dest(i) = base + i * step
+function Codec.toFloat(row: buffer, n: number, out: buffer, base: number, step: number)
+ for i = 0, n - 1 do
+ local q = i * 4
+ local e = readu8(row, q + 3)
+ local o = base + i * step
+ if e == 0 then
+ writef32(out, o, 0)
+ writef32(out, o + 4, 0)
+ writef32(out, o + 8, 0)
+ else
+ local f = 2 ^ (e - 136)
+ writef32(out, o, readu8(row, q) * f)
+ writef32(out, o + 4, readu8(row, q + 1) * f)
+ writef32(out, o + 8, readu8(row, q + 2) * f)
+ end
+ writef32(out, o + 12, 1)
+ end
+end
+
+-- fromFloat(px, y, w, row): row y of an rgbaf32 image -> w RGBE pixels (rgbe.c float2rgbe)
+function Codec.fromFloat(px: buffer, y: number, w: number, row: buffer)
+ for x = 0, w - 1 do
+ local q = (y * w + x) * 16
+ local r, g, b = readf32(px, q), readf32(px, q + 4), readf32(px, q + 8)
+ if r ~= r or r < 0 then
+ r = 0
+ end
+ if g ~= g or g < 0 then
+ g = 0
+ end
+ if b ~= b or b < 0 then
+ b = 0
+ end
+ local v = math.max(r, g, b)
+ local o = x * 4
+ if v < 1e-32 or v == math.huge then
+ if v == math.huge then
+ -- clamp infinities to the largest RGBE value
+ writeu8(row, o, if r == math.huge then 255 else 0)
+ writeu8(row, o + 1, if g == math.huge then 255 else 0)
+ writeu8(row, o + 2, if b == math.huge then 255 else 0)
+ writeu8(row, o + 3, 255)
+ else
+ writeu8(row, o, 0)
+ writeu8(row, o + 1, 0)
+ writeu8(row, o + 2, 0)
+ writeu8(row, o + 3, 0)
+ end
+ else
+ local m, e = frexp(v)
+ if e > 127 then
+ writeu8(row, o, 255)
+ writeu8(row, o + 1, 255)
+ writeu8(row, o + 2, 255)
+ writeu8(row, o + 3, 255)
+ else
+ local s = m * 256 / v
+ writeu8(row, o, math.min(255, math.floor(r * s)))
+ writeu8(row, o + 1, math.min(255, math.floor(g * s)))
+ writeu8(row, o + 2, math.min(255, math.floor(b * s)))
+ writeu8(row, o + 3, e + 128)
+ end
+ end
+ end
+end
+
+-- writeLine(row, w, out, o) -> new offset: new-style RLE (rgbe.c RGBE_WriteBytes_RLE); out needs w * 4 + w + 8
+function Codec.writeLine(row: buffer, w: number, out: buffer, o: number): number
+ writeu8(out, o, 2)
+ writeu8(out, o + 1, 2)
+ writeu8(out, o + 2, w // 256)
+ writeu8(out, o + 3, w % 256)
+ o += 4
+ for c = 0, 3 do
+ local cur = 0
+ while cur < w do
+ -- find the next run of at least 4
+ local begRun = cur
+ local runCount = 0
+ local oldRun = 0
+ while runCount < 4 and begRun < w do
+ begRun += runCount
+ oldRun = runCount
+ runCount = 1
+ if begRun < w then
+ local v = readu8(row, begRun * 4 + c)
+ while begRun + runCount < w and runCount < 127 and readu8(row, (begRun + runCount) * 4 + c) == v do
+ runCount += 1
+ end
+ end
+ end
+ -- a short run just before the long one
+ if oldRun > 1 and oldRun == begRun - cur then
+ writeu8(out, o, 128 + oldRun)
+ writeu8(out, o + 1, readu8(row, cur * 4 + c))
+ o += 2
+ cur = begRun
+ end
+ -- raw bytes up to the run
+ while cur < begRun do
+ local n = math.min(begRun - cur, 128)
+ writeu8(out, o, n)
+ o += 1
+ for i = cur, cur + n - 1 do
+ writeu8(out, o, readu8(row, i * 4 + c))
+ o += 1
+ end
+ cur += n
+ end
+ if runCount >= 4 then
+ writeu8(out, o, 128 + runCount)
+ writeu8(out, o + 1, readu8(row, begRun * 4 + c))
+ o += 2
+ cur += runCount
+ end
+ end
+ end
+ return o
+end
+
+return Codec
diff --git a/src/Formats/image/hdr/init.luau b/src/Formats/image/hdr/init.luau
new file mode 100644
index 0000000..ceb84a3
--- /dev/null
+++ b/src/Formats/image/hdr/init.luau
@@ -0,0 +1,234 @@
+--!strict
+-- image/hdr: Radiance HDR / RGBE (.hdr, .pic), written from the Radiance file format notes and rgbe.c conventions.
+-- Decode: "#?RADIANCE" / "#?RGBE" (any "#?" program name) headers, FORMAT=32-bit_rle_rgbe, EXPOSURE (the product of
+-- every EXPOSURE line, kept in meta.exposure, not applied), other header lines in meta.text, the eight resolution
+-- orientations (-Y +X standard, +Y, -X and the X-major ones), flat, old-style RLE and new-style RLE scanlines.
+-- opts.native gives the linear rgbaf32 values (alpha 1); the default rgba8 is a display conversion:
+-- round(clamp(v, 0, 1) ^ (1 / 2.2) * 255) per channel. Encode: rgbaf32 (or rgba8 through the inverse curve) to a
+-- -Y +X file with new-style RLE (flat scanlines for widths outside 8..32767).
+-- Not supported: FORMAT=32-bit_rle_xyze (CIE XYZ files: UNSUPPORTED), PRIMARIES / COLORCORR (ignored).
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Types = require("@formats/Types")
+local Codec = require("@formats/image/hdr/Codec")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Hdr = {
+ name = "hdr",
+ category = "image",
+ extensions = { "hdr", "pic", "rgbe" },
+ mime = { "image/vnd.radiance", "image/x-hdr" },
+ deps = { "core/Err", "core/Bytes", "Types" },
+ caps = { decode = true, encode = true, alpha = false, float = true, depths = { 32 } },
+}
+
+-- ------------------------------------------------------------------------------------------------ types
+export type DecodeOptions = {
+ native: boolean?, -- linear rgbaf32 (default false: rgba8 through a 1 / 2.2 display gamma)
+ maxPixels: number?, -- refuse larger images (default 2^26)
+}
+export type EncodeOptions = {
+ rle: boolean?, -- new-style RLE scanlines (default true)
+ exposure: number?, -- write an EXPOSURE line (default meta.exposure when not 1)
+}
+
+-- ------------------------------------------------------------------------------------------------ constants
+local GAMMA = 1 / 2.2
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Hdr.sniff(r: Bytes.Reader): number
+ local s = r:peek(10)
+ if s == "#?RADIANCE" then
+ return 1
+ end
+ if string.sub(s, 1, 6) == "#?RGBE" then
+ return 1
+ end
+ if string.sub(s, 1, 2) == "#?" and string.match(s, "^#%?%u") then
+ return 0.5
+ end
+ return 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+function Hdr.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
+ local maxPixels = opts and opts.maxPixels or 2 ^ 26
+ local b, limit = r.buf, r.limit
+ local p = r.base
+ -- header lines up to the first empty one
+ local function line(): string?
+ local s = p
+ while p < limit and buffer.readu8(b, p) ~= 10 do
+ p += 1
+ end
+ if p >= limit then
+ return nil
+ end
+ local l = buffer.readstring(b, s, p - s)
+ p += 1
+ return l
+ end
+ local first = line()
+ if not first or string.sub(first, 1, 2) ~= "#?" then
+ return nil, Err.new(Err.CORRUPT, "not a Radiance file (no #? line)", r.base)
+ end
+ local exposure = 1
+ local format = nil
+ local text: { [string]: string } = {}
+ while true do
+ local l = line()
+ if l == nil then
+ return nil, Err.new(Err.TRUNCATED, "header ends early", p)
+ end
+ l = string.gsub(l, "\r$", "")
+ if l == "" then
+ break
+ end
+ local k, v = string.match(l, "^%s*([%w_%-]+)%s*=%s*(.-)%s*$")
+ if k == "FORMAT" then
+ format = v
+ elseif k == "EXPOSURE" then
+ local e = tonumber(v)
+ if e and e > 0 then
+ exposure *= e
+ end
+ elseif k then
+ text[k] = v :: string
+ end
+ end
+ if format and format ~= "32-bit_rle_rgbe" then
+ return nil, Err.new(Err.UNSUPPORTED, "FORMAT=" .. format)
+ end
+ local res = line()
+ if not res then
+ return nil, Err.new(Err.TRUNCATED, "no resolution line", p)
+ end
+ local s1, a1, n1, s2, a2, n2 = string.match(res, "^%s*([%+%-])([XY])%s+(%d+)%s+([%+%-])([XY])%s+(%d+)%s*$")
+ if not s1 or a1 == a2 or #n1 > 9 or #n2 > 9 then
+ return nil, Err.new(Err.CORRUPT, "bad resolution line", p)
+ end
+ local outer, inner = tonumber(n1) :: number, tonumber(n2) :: number
+ local w, h = if a1 == "Y" then inner else outer, if a1 == "Y" then outer else inner
+ if w < 1 or h < 1 then
+ return nil, Err.new(Err.CORRUPT, "zero size")
+ end
+ if w * h > maxPixels then
+ return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
+ end
+ local img = Types.Image.new(w, h, "rgbaf32")
+ local px = img.pixels
+ local row = buffer.create(inner * 4)
+ local truncated = false
+ for i = 0, outer - 1 do
+ local np, err = Codec.readLine(b, p, limit, inner, row)
+ if not np then
+ if err == "truncated" then
+ truncated = true
+ break
+ end
+ return nil, Err.new(Err.CORRUPT, tostring(err), p)
+ end
+ p = np
+ -- where scanline i, pixel j lands: Y decreasing ("-Y") = top first, X increasing ("+X") = left first
+ local base, step
+ if a1 == "Y" then
+ local y = if s1 == "-" then i else h - 1 - i
+ if s2 == "+" then
+ base, step = y * w * 16, 16
+ else
+ base, step = (y * w + w - 1) * 16, -16
+ end
+ else
+ local x = if s1 == "+" then i else w - 1 - i
+ if s2 == "-" then
+ base, step = x * 16, w * 16
+ else
+ base, step = ((h - 1) * w + x) * 16, -w * 16
+ end
+ end
+ Codec.toFloat(row, inner, px, base, step)
+ end
+ if not (opts and opts.native) then
+ local o = Types.Image.new(w, h, "rgba8")
+ for i = 0, w * h - 1 do
+ for c = 0, 2 do
+ local v = buffer.readf32(px, i * 16 + c * 4)
+ buffer.writeu8(o.pixels, i * 4 + c, math.floor(math.clamp(v, 0, 1) ^ GAMMA * 255 + 0.5))
+ end
+ buffer.writeu8(o.pixels, i * 4 + 3, 255)
+ end
+ o.meta = img.meta
+ img = o
+ end
+ img.meta.exposure = exposure
+ img.meta.colorSpace = "linear"
+ if next(text) then
+ img.meta.text = text
+ end
+ if truncated then
+ img.meta.truncated = true
+ end
+ img.meta.source = { format = "hdr", bitDepth = 32, colorType = "rgbe", program = string.sub(first, 3), orientation = string.format("%s%s %s%s", s1, a1, s2, a2) }
+ return img, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+function Hdr.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
+ if type(img) ~= "table" or type(img.pixels) ~= "buffer" or (img.format ~= "rgbaf32" and img.format ~= "rgba8") then
+ return nil, Err.new(Err.ARG, "needs an rgbaf32 or rgba8 Image")
+ end
+ local w, h = img.width, img.height
+ local bpp = if img.format == "rgbaf32" then 16 else 4
+ if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < w * h * bpp then
+ return nil, Err.new(Err.ARG, "bad image size or pixel buffer")
+ end
+ local o: any = opts or {}
+ local px = img.pixels
+ if bpp == 4 then
+ -- rgba8 through the inverse of the decoder's display curve
+ local lut = table.create(256, 0)
+ for v = 0, 255 do
+ lut[v + 1] = (v / 255) ^ 2.2
+ end
+ px = buffer.create(w * h * 16)
+ for i = 0, w * h - 1 do
+ for c = 0, 2 do
+ buffer.writef32(px, i * 16 + c * 4, lut[buffer.readu8(img.pixels, i * 4 + c) + 1])
+ end
+ buffer.writef32(px, i * 16 + 12, 1)
+ end
+ end
+ local exposure = o.exposure or (img.meta and img.meta.exposure)
+ local head = "#?RADIANCE\n# written by formats-luau\nFORMAT=32-bit_rle_rgbe\n"
+ if type(exposure) == "number" and exposure > 0 and exposure ~= 1 then
+ head ..= string.format("EXPOSURE=%.9g\n", exposure)
+ end
+ head ..= string.format("\n-Y %d +X %d\n", h, w)
+ local rle = o.rle ~= false and w >= 8 and w <= 32767
+ local out = buffer.create(#head + h * (w * 5 + 8))
+ buffer.writestring(out, 0, head)
+ local op = #head
+ local row = buffer.create(w * 4)
+ for y = 0, h - 1 do
+ Codec.fromFloat(px, y, w, row)
+ if rle then
+ op = Codec.writeLine(row, w, out, op)
+ else
+ buffer.copy(out, op, row, 0, w * 4)
+ for x = 0, w - 1 do
+ -- 1, 1, 1 would read as an old-style run marker
+ if buffer.readu8(out, op + x * 4) == 1 and buffer.readu8(out, op + x * 4 + 1) == 1 and buffer.readu8(out, op + x * 4 + 2) == 1 then
+ buffer.writeu8(out, op + x * 4 + 2, 0)
+ end
+ end
+ op += w * 4
+ end
+ end
+ local res = buffer.create(op)
+ buffer.copy(res, 0, out, 0, op)
+ return res, nil
+end
+
+return Hdr
diff --git a/src/Formats/image/ico/Dib.luau b/src/Formats/image/ico/Dib.luau
new file mode 100644
index 0000000..447fa5e
--- /dev/null
+++ b/src/Formats/image/ico/Dib.luau
@@ -0,0 +1,106 @@
+--!strict
+--!native
+--!optimize 2
+-- image/ico/Dib: the BMP device-independent bitmaps inside ICO / CUR entries (native; never throws). Written from
+-- the Microsoft ICO / BITMAPINFOHEADER documentation: a colour (XOR) bitmap of 1 / 4 / 8 / 16 (5-5-5) / 24 / 32-bit
+-- pixels, bottom-up rows padded to 4 bytes, then a 1-bit AND mask (1 = transparent). 32-bit entries use their alpha
+-- channel unless it is all zero (old icons), in which case the AND mask decides.
+local readu8, readu16, readu32, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu32
+
+local Dib = {}
+
+-- decode(b, p, e, w, h, bpp, pal, palN, out) -> ok, message: the XOR + AND bitmaps at b[p, e) into rgba8 out
+function Dib.decode(b: buffer, p: number, e: number, w: number, h: number, bpp: number, pal: buffer, palN: number, out: buffer): (boolean, string?)
+ local stride = ((w * bpp + 31) // 32) * 4
+ local maskStride = ((w + 31) // 32) * 4
+ if p + stride * h > e then
+ return false, "colour bitmap runs past the entry"
+ end
+ local hasMask = p + stride * h + maskStride * h <= e
+ local anyAlpha = false
+ for y = 0, h - 1 do
+ local row = p + (h - 1 - y) * stride
+ for x = 0, w - 1 do
+ local v
+ if bpp == 32 then
+ v = readu8(b, row + x * 4 + 2) + readu8(b, row + x * 4 + 1) * 256 + readu8(b, row + x * 4) * 65536 + readu8(b, row + x * 4 + 3) * 16777216
+ if v >= 16777216 then
+ anyAlpha = true
+ end
+ elseif bpp == 24 then
+ v = readu8(b, row + x * 3 + 2) + readu8(b, row + x * 3 + 1) * 256 + readu8(b, row + x * 3) * 65536 + 0xFF000000
+ elseif bpp == 16 then
+ local s = readu16(b, row + x * 2)
+ local r, g, bl = (s // 1024) % 32, (s // 32) % 32, s % 32
+ v = (r * 255 + 15) // 31 + ((g * 255 + 15) // 31) * 256 + ((bl * 255 + 15) // 31) * 65536 + 0xFF000000
+ else
+ local bit = x * bpp
+ local byte = readu8(b, row + bit // 8)
+ local idx = (byte // 2 ^ (8 - bpp - bit % 8)) % 2 ^ bpp
+ v = if idx < palN then readu32(pal, idx * 4) else 0xFF000000
+ end
+ writeu32(out, (y * w + x) * 4, v)
+ end
+ end
+ if bpp == 32 and anyAlpha then
+ return true, nil
+ end
+ if hasMask then
+ local mp = p + stride * h
+ for y = 0, h - 1 do
+ local row = mp + (h - 1 - y) * maskStride
+ for x = 0, w - 1 do
+ local o = (y * w + x) * 4
+ local px = readu32(out, o) % 16777216
+ if (readu8(b, row + x // 8) // 2 ^ (7 - x % 8)) % 2 == 1 then
+ writeu32(out, o, px) -- transparent
+ else
+ writeu32(out, o, px + 0xFF000000)
+ end
+ end
+ end
+ elseif bpp == 32 then
+ -- no alpha and no mask: opaque
+ for i = 0, w * h - 1 do
+ writeu32(out, i * 4, readu32(out, i * 4) % 16777216 + 0xFF000000)
+ end
+ end
+ return true, nil
+end
+
+-- encode(px, w, h, out, o) -> new offset: rgba8 as a 32-bit BGRA bitmap (bottom-up) + an AND mask (alpha 0 = 1).
+-- out needs room for w * h * 4 + maskStride * h bytes.
+function Dib.encode(px: buffer, w: number, h: number, out: buffer, o: number): number
+ for y = h - 1, 0, -1 do
+ for x = 0, w - 1 do
+ local q = (y * w + x) * 4
+ buffer.writeu8(out, o, readu8(px, q + 2))
+ buffer.writeu8(out, o + 1, readu8(px, q + 1))
+ buffer.writeu8(out, o + 2, readu8(px, q))
+ buffer.writeu8(out, o + 3, readu8(px, q + 3))
+ o += 4
+ end
+ end
+ local maskStride = ((w + 31) // 32) * 4
+ for y = h - 1, 0, -1 do
+ local acc, nb, written = 0, 0, 0
+ for x = 0, w - 1 do
+ acc = acc * 2 + (if readu8(px, (y * w + x) * 4 + 3) == 0 then 1 else 0)
+ nb += 1
+ if nb == 8 then
+ buffer.writeu8(out, o + written, acc)
+ written += 1
+ acc, nb = 0, 0
+ end
+ end
+ if nb > 0 then
+ buffer.writeu8(out, o + written, acc * 2 ^ (8 - nb))
+ written += 1
+ end
+ buffer.fill(out, o + written, 0, maskStride - written)
+ o += maskStride
+ end
+ return o
+end
+
+return Dib
diff --git a/src/Formats/image/ico/init.luau b/src/Formats/image/ico/init.luau
new file mode 100644
index 0000000..9fc05a1
--- /dev/null
+++ b/src/Formats/image/ico/init.luau
@@ -0,0 +1,282 @@
+--!strict
+-- image/ico: Windows icons and cursors (ICO / CUR), written from Microsoft's ICO format documentation. Decode: every
+-- directory entry, as a BMP DIB (1 / 4 / 8 / 16 / 24 / 32-bit with a colour table and the AND mask; 32-bit alpha) or
+-- an embedded PNG, decoded through the api hook opts.decodeImage (F.load supplies it; without it PNG entries are
+-- skipped, and a file of PNG entries only returns UNSUPPORTED). The image is the largest entry (then the deepest);
+-- img.frames lists every decoded entry in file order (Types.Frame, each frame image with meta.source.bitDepth / png
+-- and, for cursors, meta.hotspot = { x, y }). Encode: the image, or every img.frames image (each up to 256 x 256), as
+-- 32-bit DIB entries with an AND mask; 256-pixel entries (or all with opts.png) as PNG through opts.encodeImage when it
+-- is there; a cursor (CUR) with opts.cursor or when the image has meta.hotspot.
+-- Not supported: resizing to a set of icon sizes (do that with ops/ImageOps first), DIB compression (BI_BITFIELDS
+-- 16 / 32-bit is read as 5-5-5 / BGRA), the obsolete 2-colour planes.
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Types = require("@formats/Types")
+local Dib = require("@formats/image/ico/Dib")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Ico = {
+ name = "ico",
+ category = "image",
+ extensions = { "ico", "cur" },
+ mime = { "image/vnd.microsoft.icon", "image/x-icon" },
+ deps = { "core/Err", "core/Bytes", "Types" },
+ caps = { decode = true, encode = true, alpha = true, frames = true, depths = { 1, 4, 8, 16, 24, 32 } },
+}
+
+-- ------------------------------------------------------------------------------------------------ types
+export type DecodeOptions = {
+ decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?, -- decodes PNG entries (the api passes one)
+ maxPixels: number?, -- refuse larger entries (default 2^26)
+}
+export type EncodeOptions = {
+ encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?, -- writes PNG entries (the api passes one)
+ png: boolean?, -- every entry as PNG (needs encodeImage; default: only 256-pixel entries, when it exists)
+ cursor: boolean?, -- write a CUR (default: when the image has meta.hotspot)
+}
+
+-- ------------------------------------------------------------------------------------------------ constants
+local PNG_SIG = "\137PNG\r\n\26\n"
+local readu8 = buffer.readu8
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Ico.sniff(r: Bytes.Reader): number
+ if r:remaining() < 22 then
+ return 0
+ end
+ local b, o = r.buf, r.pos
+ local typ = buffer.readu16(b, o + 2)
+ local count = buffer.readu16(b, o + 4)
+ if buffer.readu16(b, o) ~= 0 or (typ ~= 1 and typ ~= 2) or count == 0 then
+ return 0
+ end
+ -- the first entry: reserved byte 0, a size and offset inside the file
+ local size, off = buffer.readu32(b, o + 14), buffer.readu32(b, o + 18)
+ if readu8(b, o + 9) ~= 0 or size == 0 or off < 6 + count * 16 then
+ return 0
+ end
+ return 0.8
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+local function le16(b: buffer, p: number): number
+ return buffer.readu16(b, p)
+end
+local function le32(b: buffer, p: number): number
+ return buffer.readu32(b, p)
+end
+
+function Ico.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
+ local maxPixels = opts and opts.maxPixels or 2 ^ 26
+ local decodeImage = opts and opts.decodeImage
+ local b, base, limit = r.buf, r.base, r.limit
+ if limit - base < 6 then
+ return nil, Err.new(Err.TRUNCATED, "short header", base)
+ end
+ local typ, count = le16(b, base + 2), le16(b, base + 4)
+ if le16(b, base) ~= 0 or (typ ~= 1 and typ ~= 2) then
+ return nil, Err.new(Err.CORRUPT, "not an ICO / CUR file", base)
+ end
+ if count == 0 then
+ return nil, Err.new(Err.CORRUPT, "no images", base)
+ end
+ if base + 6 + count * 16 > limit then
+ return nil, Err.new(Err.TRUNCATED, "directory runs past the end", base)
+ end
+ local frames: { Types.Frame } = {}
+ local best: Types.Image? = nil
+ local bestScore = -1
+ local skipped, lastErr = 0, nil :: Err.Err?
+ for i = 0, count - 1 do
+ local d = base + 6 + i * 16
+ local dw, dh = readu8(b, d), readu8(b, d + 1)
+ dw = if dw == 0 then 256 else dw
+ dh = if dh == 0 then 256 else dh
+ local f1, f2 = le16(b, d + 4), le16(b, d + 6)
+ local size, off = le32(b, d + 8), le32(b, d + 12)
+ local p, e = base + off, base + off + size
+ local img: Types.Image? = nil
+ local depth = 0
+ local isPng = false
+ if off < 6 or p >= limit then
+ lastErr = Err.new(Err.TRUNCATED, "entry " .. (i + 1) .. " lies past the end", d)
+ else
+ e = math.min(e, limit)
+ if e - p >= 8 and buffer.readstring(b, p, 8) == PNG_SIG then
+ isPng = true
+ depth = 32
+ if decodeImage then
+ local sub = buffer.create(e - p)
+ buffer.copy(sub, 0, b, p, e - p)
+ local ok, pimg, perr = pcall(decodeImage, sub)
+ if ok and pimg and pimg.format == "rgba8" then
+ img = pimg
+ else
+ lastErr = if ok and perr then perr else Err.new(Err.CORRUPT, "entry " .. (i + 1) .. ": bad PNG")
+ end
+ else
+ lastErr = Err.new(Err.UNSUPPORTED, "PNG entries need opts.decodeImage (F.load passes it)")
+ end
+ elseif e - p >= 40 then
+ local hs = le32(b, p)
+ local bw = buffer.readi32(b, p + 4)
+ local bh = buffer.readi32(b, p + 8)
+ local bpp = le16(b, p + 14)
+ local clrUsed = le32(b, p + 32)
+ local w = if bw > 0 then bw else dw
+ local h = if bh ~= 0 then math.abs(bh) // 2 else dh
+ if hs < 12 or hs > e - p or w < 1 or h < 1 or w > 4096 or h > 4096 then
+ lastErr = Err.new(Err.CORRUPT, "entry " .. (i + 1) .. ": bad bitmap header", p)
+ elseif bpp ~= 1 and bpp ~= 4 and bpp ~= 8 and bpp ~= 16 and bpp ~= 24 and bpp ~= 32 then
+ lastErr = Err.new(Err.UNSUPPORTED, "entry " .. (i + 1) .. ": " .. bpp .. "-bit bitmap", p)
+ elseif w * h > maxPixels then
+ return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
+ else
+ depth = bpp
+ local q = p + hs
+ local palN = 0
+ local pal = buffer.create(4)
+ if bpp <= 8 then
+ palN = if clrUsed > 0 and clrUsed < 2 ^ bpp then clrUsed else 2 ^ bpp
+ if q + palN * 4 > e then
+ palN = 0
+ lastErr = Err.new(Err.TRUNCATED, "entry " .. (i + 1) .. ": colour table runs past the entry", q)
+ else
+ pal = buffer.create(palN * 4)
+ for k = 0, palN - 1 do
+ local c = q + k * 4
+ buffer.writeu32(pal, k * 4, readu8(b, c + 2) + readu8(b, c + 1) * 256 + readu8(b, c) * 65536 + 0xFF000000)
+ end
+ q += palN * 4
+ end
+ end
+ if bpp > 8 or palN > 0 then
+ if bpp == 16 and le32(b, p + 16) == 3 then
+ q += 12 -- BI_BITFIELDS masks (assumed 5-5-5)
+ end
+ local out = Types.Image.new(w, h, "rgba8")
+ local ok, msg = Dib.decode(b, q, e, w, h, bpp, pal, palN, out.pixels)
+ if ok then
+ img = out
+ else
+ lastErr = Err.new(Err.TRUNCATED, "entry " .. (i + 1) .. ": " .. tostring(msg), q)
+ end
+ end
+ end
+ else
+ lastErr = Err.new(Err.TRUNCATED, "entry " .. (i + 1) .. " is too short", p)
+ end
+ end
+ if img then
+ local im = img :: Types.Image
+ im.meta.source = { format = "ico", bitDepth = depth, png = isPng, colorCount = readu8(b, d + 2) }
+ if typ == 2 then
+ im.meta.hotspot = { x = f1, y = f2 }
+ end
+ table.insert(frames, { image = im, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" })
+ local score = im.width * im.height * 64 + depth
+ if score > bestScore then
+ best, bestScore = im, score
+ end
+ else
+ skipped += 1
+ end
+ end
+ if not best then
+ return nil, lastErr or Err.new(Err.CORRUPT, "no decodable entry")
+ end
+ local main = best :: Types.Image
+ local img = Types.Image.new(main.width, main.height, "rgba8")
+ buffer.copy(img.pixels, 0, main.pixels)
+ if #frames > 1 then
+ img.frames = frames
+ end
+ img.meta.source = { format = "ico", type = if typ == 2 then "cur" else "ico", bitDepth = main.meta.source and main.meta.source.bitDepth, entries = count, skipped = skipped, png = main.meta.source and main.meta.source.png }
+ img.meta.hotspot = main.meta.hotspot
+ return img, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+function Ico.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
+ if type(img) ~= "table" then
+ return nil, Err.new(Err.ARG, "needs an Image")
+ end
+ local o: any = opts or {}
+ local list: { Types.Image } = {}
+ if type(img.frames) == "table" and #img.frames > 0 then
+ for _, f in img.frames do
+ table.insert(list, f.image)
+ end
+ else
+ list[1] = img
+ end
+ local cursor = o.cursor
+ if cursor == nil then
+ cursor = type(img.meta) == "table" and img.meta.hotspot ~= nil
+ end
+ local blobs: { buffer } = {}
+ for i, im in list do
+ if type(im) ~= "table" or im.format ~= "rgba8" or type(im.pixels) ~= "buffer" then
+ return nil, Err.new(Err.ARG, "entry " .. i .. ": needs an rgba8 Image")
+ end
+ local w, h = im.width, im.height
+ if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w > 256 or h > 256 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(im.pixels) < w * h * 4 then
+ return nil, Err.new(Err.ARG, "entry " .. i .. ": icons are 1..256 pixels per side")
+ end
+ local png = nil
+ if o.encodeImage and (o.png or w == 256 or h == 256) then
+ local ok, res, err = pcall(o.encodeImage, im, "png")
+ if not ok or not res then
+ return nil, if ok and err then err else Err.new(Err.ARG, "entry " .. i .. ": PNG encode failed")
+ end
+ png = res
+ elseif o.png then
+ return nil, Err.new(Err.ARG, "opts.png needs opts.encodeImage (F.save passes it)")
+ end
+ if png then
+ blobs[i] = png
+ else
+ local maskStride = ((w + 31) // 32) * 4
+ local n = 40 + w * h * 4 + maskStride * h
+ local d = buffer.create(n)
+ buffer.writeu32(d, 0, 40)
+ buffer.writei32(d, 4, w)
+ buffer.writei32(d, 8, h * 2)
+ buffer.writeu16(d, 12, 1)
+ buffer.writeu16(d, 14, 32)
+ buffer.writeu32(d, 20, w * h * 4 + maskStride * h)
+ Dib.encode(im.pixels, w, h, d, 40)
+ blobs[i] = d
+ end
+ end
+ local total = 6 + #list * 16
+ for _, bl in blobs do
+ total += buffer.len(bl)
+ end
+ local out = buffer.create(total)
+ buffer.writeu16(out, 2, if cursor then 2 else 1)
+ buffer.writeu16(out, 4, #list)
+ local off = 6 + #list * 16
+ for i, im in list do
+ local d = 6 + (i - 1) * 16
+ buffer.writeu8(out, d, im.width % 256)
+ buffer.writeu8(out, d + 1, im.height % 256)
+ if cursor then
+ local hs = (type(im.meta) == "table" and im.meta.hotspot) or (img.meta and img.meta.hotspot) or { x = 0, y = 0 }
+ buffer.writeu16(out, d + 4, math.clamp(math.floor(tonumber(hs.x) or 0), 0, 65535))
+ buffer.writeu16(out, d + 6, math.clamp(math.floor(tonumber(hs.y) or 0), 0, 65535))
+ else
+ buffer.writeu16(out, d + 4, 1)
+ buffer.writeu16(out, d + 6, 32)
+ end
+ buffer.writeu32(out, d + 8, buffer.len(blobs[i]))
+ buffer.writeu32(out, d + 12, off)
+ buffer.copy(out, off, blobs[i])
+ off += buffer.len(blobs[i])
+ end
+ return out, nil
+end
+
+return Ico
diff --git a/src/Formats/image/jpeg/Arith.luau b/src/Formats/image/jpeg/Arith.luau
new file mode 100644
index 0000000..a1044e2
--- /dev/null
+++ b/src/Formats/image/jpeg/Arith.luau
@@ -0,0 +1,414 @@
+--!strict
+--!native
+--!optimize 2
+-- image/jpeg/Arith: arithmetic-coded scans (ITU T.81 annex D / F.1.4, sequential and progressive) into quantised
+-- DCT coefficients (native; never throws). A Luau translation of libjpeg-turbo's jdarith.c (Guido Vollbeding's
+-- decoder, IJG licence: licenses/libjpeg-turbo-LICENSE.md) and the jaricom.c probability table.
+--
+-- It reads the destuffed scan data that Scan.destuff produces (0xFF 0x00 already removed, RSTn positions recorded);
+-- past the end of a restart segment it reads zero bytes, the convention libjpeg follows when the decoder runs into a
+-- marker (libjpeg's encoder also drops trailing zero bytes, so reading past the end is normal and not a sign of
+-- truncation: the caller flags a scan that runs into the end of the file instead). Statistics bins live in one buffer: DC tables at [t * 64], AC tables at [256 + t * 256], the fixed 0.5
+-- bin at [1280].
+local readu8, writeu8, readi16, writei16 = buffer.readu8, buffer.writeu8, buffer.readi16, buffer.writei16
+local band, bxor = bit32.band, bit32.bxor
+
+local Arith = {}
+
+-- jaricom.c: Qe << 16 | Next_Index_MPS << 8 | Switch_MPS << 7 | Next_Index_LPS
+local TAB = buffer.create(114 * 4)
+do
+ local raw = {
+ { 0x5a1d, 1, 1, 1 }, { 0x2586, 14, 2, 0 }, { 0x1114, 16, 3, 0 }, { 0x080b, 18, 4, 0 }, { 0x03d8, 20, 5, 0 },
+ { 0x01da, 23, 6, 0 }, { 0x00e5, 25, 7, 0 }, { 0x006f, 28, 8, 0 }, { 0x0036, 30, 9, 0 }, { 0x001a, 33, 10, 0 },
+ { 0x000d, 35, 11, 0 }, { 0x0006, 9, 12, 0 }, { 0x0003, 10, 13, 0 }, { 0x0001, 12, 13, 0 }, { 0x5a7f, 15, 15, 1 },
+ { 0x3f25, 36, 16, 0 }, { 0x2cf2, 38, 17, 0 }, { 0x207c, 39, 18, 0 }, { 0x17b9, 40, 19, 0 }, { 0x1182, 42, 20, 0 },
+ { 0x0cef, 43, 21, 0 }, { 0x09a1, 45, 22, 0 }, { 0x072f, 46, 23, 0 }, { 0x055c, 48, 24, 0 }, { 0x0406, 49, 25, 0 },
+ { 0x0303, 51, 26, 0 }, { 0x0240, 52, 27, 0 }, { 0x01b1, 54, 28, 0 }, { 0x0144, 56, 29, 0 }, { 0x00f5, 57, 30, 0 },
+ { 0x00b7, 59, 31, 0 }, { 0x008a, 60, 32, 0 }, { 0x0068, 62, 33, 0 }, { 0x004e, 63, 34, 0 }, { 0x003b, 32, 35, 0 },
+ { 0x002c, 33, 9, 0 }, { 0x5ae1, 37, 37, 1 }, { 0x484c, 64, 38, 0 }, { 0x3a0d, 65, 39, 0 }, { 0x2ef1, 67, 40, 0 },
+ { 0x261f, 68, 41, 0 }, { 0x1f33, 69, 42, 0 }, { 0x19a8, 70, 43, 0 }, { 0x1518, 72, 44, 0 }, { 0x1177, 73, 45, 0 },
+ { 0x0e74, 74, 46, 0 }, { 0x0bfb, 75, 47, 0 }, { 0x09f8, 77, 48, 0 }, { 0x0861, 78, 49, 0 }, { 0x0706, 79, 50, 0 },
+ { 0x05cd, 48, 51, 0 }, { 0x04de, 50, 52, 0 }, { 0x040f, 50, 53, 0 }, { 0x0363, 51, 54, 0 }, { 0x02d4, 52, 55, 0 },
+ { 0x025c, 53, 56, 0 }, { 0x01f8, 54, 57, 0 }, { 0x01a4, 55, 58, 0 }, { 0x0160, 56, 59, 0 }, { 0x0125, 57, 60, 0 },
+ { 0x00f6, 58, 61, 0 }, { 0x00cb, 59, 62, 0 }, { 0x00ab, 61, 63, 0 }, { 0x008f, 61, 32, 0 }, { 0x5b12, 65, 65, 1 },
+ { 0x4d04, 80, 66, 0 }, { 0x412c, 81, 67, 0 }, { 0x37d8, 82, 68, 0 }, { 0x2fe8, 83, 69, 0 }, { 0x293c, 84, 70, 0 },
+ { 0x2379, 86, 71, 0 }, { 0x1edf, 87, 72, 0 }, { 0x1aa9, 87, 73, 0 }, { 0x174e, 72, 74, 0 }, { 0x1424, 72, 75, 0 },
+ { 0x119c, 74, 76, 0 }, { 0x0f6b, 74, 77, 0 }, { 0x0d51, 75, 78, 0 }, { 0x0bb6, 77, 79, 0 }, { 0x0a40, 77, 48, 0 },
+ { 0x5832, 80, 81, 1 }, { 0x4d1c, 88, 82, 0 }, { 0x438e, 89, 83, 0 }, { 0x3bdd, 90, 84, 0 }, { 0x34ee, 91, 85, 0 },
+ { 0x2eae, 92, 86, 0 }, { 0x299a, 93, 87, 0 }, { 0x2516, 86, 71, 0 }, { 0x5570, 88, 89, 1 }, { 0x4ca9, 95, 90, 0 },
+ { 0x44d9, 96, 91, 0 }, { 0x3e22, 97, 92, 0 }, { 0x3824, 99, 93, 0 }, { 0x32b4, 99, 94, 0 }, { 0x2e17, 93, 86, 0 },
+ { 0x56a8, 95, 96, 1 }, { 0x4f46, 101, 97, 0 }, { 0x47e5, 102, 98, 0 }, { 0x41cf, 103, 99, 0 }, { 0x3c3d, 104, 100, 0 },
+ { 0x375e, 99, 93, 0 }, { 0x5231, 105, 102, 0 }, { 0x4c0f, 106, 103, 0 }, { 0x4639, 107, 104, 0 }, { 0x415e, 103, 99, 0 },
+ { 0x5627, 105, 106, 1 }, { 0x50e7, 108, 107, 0 }, { 0x4b85, 109, 103, 0 }, { 0x5597, 110, 109, 0 }, { 0x504f, 111, 107, 0 },
+ { 0x5a10, 110, 111, 1 }, { 0x5522, 112, 109, 0 }, { 0x59eb, 112, 111, 1 }, { 0x5a1d, 113, 113, 0 },
+ }
+ for i, e in raw do
+ buffer.writeu16(TAB, (i - 1) * 4, e[1]) -- Qe
+ writeu8(TAB, (i - 1) * 4 + 2, e[4] * 128 + e[2]) -- Switch_MPS << 7 | Next_Index_LPS
+ writeu8(TAB, (i - 1) * 4 + 3, e[3]) -- Next_Index_MPS
+ end
+end
+
+local ZZ: buffer = buffer.create(80) -- set by Arith.init (Scan.ZIGZAG)
+
+local STATS = 1281
+local POW2 = buffer.create(8)
+for i = 0, 7 do
+ writeu8(POW2, i, 2 ^ i)
+end
+local FIXED = 1280
+
+-- decoder state (one scan at a time; never yields)
+local D: buffer = buffer.create(0)
+local P = 0 -- next byte
+local SEGEND = 0 -- reads at or past this return 0
+local OVER = 0 -- zero bytes supplied past the end
+local C, A, CT = 0, 0, -16
+local st: buffer = buffer.create(STATS)
+
+local function decode(s: number): number
+ while A < 0x8000 do
+ CT -= 1
+ if CT < 0 then
+ local data = 0
+ if P < SEGEND then
+ data = readu8(D, P)
+ P += 1
+ else
+ OVER += 1
+ end
+ C = C * 256 + data
+ CT += 8
+ if CT < 0 then
+ CT += 1
+ if CT == 0 then
+ A = 0x8000
+ end
+ end
+ end
+ A *= 2
+ end
+ local sv = readu8(st, s)
+ local t = band(sv, 0x7F) * 4
+ local qe = buffer.readu16(TAB, t)
+ local nl = readu8(TAB, t + 2)
+ local nm = readu8(TAB, t + 3)
+ local temp = A - qe
+ A = temp
+ temp *= readu8(POW2, CT)
+ if C >= temp then
+ C -= temp
+ if A < qe then
+ A = qe
+ writeu8(st, s, bxor(band(sv, 0x80), nm))
+ else
+ A = qe
+ writeu8(st, s, bxor(band(sv, 0x80), nl))
+ sv = bxor(sv, 0x80)
+ end
+ elseif A < 0x8000 then
+ if A < qe then
+ writeu8(st, s, bxor(band(sv, 0x80), nl))
+ sv = bxor(sv, 0x80)
+ else
+ writeu8(st, s, bxor(band(sv, 0x80), nm))
+ end
+ end
+ return if sv >= 0x80 then 1 else 0
+end
+
+local function i16(v: number): number
+ v = band(v, 0xFFFF)
+ return if v >= 0x8000 then v - 0x10000 else v
+end
+
+export type ArithComp = {
+ coef: buffer,
+ bpl: number,
+ h: number,
+ v: number,
+ bw: number,
+ bh: number,
+ dcTbl: number, -- 0..3
+ acTbl: number,
+ pred: number,
+ ctx: number,
+}
+
+export type ArithParams = {
+ comps: { ArithComp },
+ mcusX: number,
+ mcusY: number,
+ ri: number,
+ mode: number, -- 0 sequential, 1 DC first, 2 DC refine, 3 AC first, 4 AC refine
+ ss: number,
+ se: number,
+ al: number,
+ dcL: { number }, -- conditioning per table (DAC), 1-based by table + 1
+ dcU: { number },
+ acK: { number },
+}
+
+-- DC difference (F.1.4.4.1 / figures F.19, F.21 - F.24); returns the new predictor or nil on a bad code
+local function dcDiff(c: ArithComp, L: number, U: number): number?
+ local base = c.dcTbl * 64
+ local s = base + c.ctx
+ if decode(s) == 0 then
+ c.ctx = 0
+ return c.pred
+ end
+ local sign = decode(s + 1)
+ s = s + 2 + sign
+ local m = decode(s)
+ if m ~= 0 then
+ s = base + 20
+ while decode(s) ~= 0 do
+ m *= 2
+ if m == 0x8000 then
+ return nil
+ end
+ s += 1
+ end
+ end
+ if m < 2 ^ L // 2 then
+ c.ctx = 0
+ elseif m > 2 ^ U // 2 then
+ c.ctx = 12 + sign * 4
+ else
+ c.ctx = 4 + sign * 4
+ end
+ local v = m
+ s += 14
+ m = m // 2
+ while m > 0 do
+ if decode(s) ~= 0 then
+ v += m
+ end
+ m = m // 2
+ end
+ v += 1
+ if sign ~= 0 then
+ v = -v
+ end
+ return band(c.pred + v, 0xFFFF)
+end
+
+-- AC coefficients k = ss..se of one block (figure F.20); false on a bad code
+local function acFirst(coef: buffer, off: number, tbl: number, ss: number, se: number, K: number, mul: number): boolean
+ local base = 256 + tbl * 256
+ local k = ss
+ while k <= se do
+ local s = base + 3 * (k - 1)
+ if decode(s) ~= 0 then
+ break -- EOB
+ end
+ while decode(s + 1) == 0 do
+ s += 3
+ k += 1
+ if k > se then
+ return false
+ end
+ end
+ local sign = decode(FIXED)
+ s += 2
+ local m = decode(s)
+ if m ~= 0 then
+ if decode(s) ~= 0 then
+ m *= 2
+ s = base + (if k <= K then 189 else 217)
+ while decode(s) ~= 0 do
+ m *= 2
+ if m == 0x8000 then
+ return false
+ end
+ s += 1
+ end
+ end
+ end
+ local v = m
+ s += 14
+ m = m // 2
+ while m > 0 do
+ if decode(s) ~= 0 then
+ v += m
+ end
+ m = m // 2
+ end
+ v += 1
+ if sign ~= 0 then
+ v = -v
+ end
+ writei16(coef, off + readu8(ZZ, k) * 2, i16(v * mul))
+ k += 1
+ end
+ return true
+end
+
+local function acRefine(coef: buffer, off: number, tbl: number, ss: number, se: number, al: number): boolean
+ local base = 256 + tbl * 256
+ local p1 = 2 ^ al
+ local m1 = -p1
+ local kex = se
+ while kex > 0 do
+ if readi16(coef, off + readu8(ZZ, kex) * 2) ~= 0 then
+ break
+ end
+ kex -= 1
+ end
+ local k = ss
+ while k <= se do
+ local s = base + 3 * (k - 1)
+ if k > kex then
+ if decode(s) ~= 0 then
+ break
+ end
+ end
+ while true do
+ local o = off + readu8(ZZ, k) * 2
+ local cv = readi16(coef, o)
+ if cv ~= 0 then
+ if decode(s + 2) ~= 0 then
+ writei16(coef, o, i16(if cv < 0 then cv + m1 else cv + p1))
+ end
+ break
+ end
+ if decode(s + 1) ~= 0 then
+ writei16(coef, o, i16(if decode(FIXED) ~= 0 then m1 else p1))
+ break
+ end
+ s += 3
+ k += 1
+ if k > se then
+ return false
+ end
+ end
+ k += 1
+ end
+ return true
+end
+
+function Arith.init(zigzag: buffer)
+ ZZ = zigzag
+end
+
+-- run(d, cleanLen, rst, nrst, P) -> truncated: decodes one scan (see Scan.run for the data layout)
+function Arith.run(d: buffer, cleanLen: number, rst: { number }, nrst: number, Pm: ArithParams): boolean
+ local comps = Pm.comps
+ local nc = #comps
+ local mode, ss, se, al, ri = Pm.mode, Pm.ss, Pm.se, Pm.al, Pm.ri
+ local units, ux
+ if nc == 1 then
+ ux = comps[1].bw
+ units = ux * comps[1].bh
+ else
+ ux = Pm.mcusX
+ units = ux * Pm.mcusY
+ end
+ local resetDc = mode == 0 or mode == 1
+ local resetAc = mode == 0 or mode == 3 or mode == 4
+ local function reset()
+ for i = 1, nc do
+ local c = comps[i]
+ if resetDc then
+ buffer.fill(st, c.dcTbl * 64, 0, 64)
+ c.pred = 0
+ c.ctx = 0
+ end
+ if resetAc then
+ buffer.fill(st, 256 + c.acTbl * 256, 0, 256)
+ end
+ end
+ C, A, CT = 0, 0, -16
+ end
+ D = d
+ P = 0
+ SEGEND = if nrst >= 1 then math.min(rst[1], cleanLen) else cleanLen
+ OVER = 0
+ writeu8(st, FIXED, 113)
+ reset()
+ local rstIdx = 0
+ local bad = false
+ local truncated = false
+ local mul = 2 ^ al
+ for u = 0, units - 1 do
+ if ri > 0 and u > 0 and u % ri == 0 then
+ rstIdx += 1
+ if rstIdx <= nrst then
+ P = math.min(rst[rstIdx], cleanLen)
+ SEGEND = if rstIdx + 1 <= nrst then math.min(rst[rstIdx + 1], cleanLen) else cleanLen
+ bad = false
+ else
+ truncated = true
+ break
+ end
+ reset()
+ end
+ if not bad then
+ local my, mx = u // ux, u % ux
+ for ci = 1, nc do
+ local c = comps[ci]
+ local bh, bw, by0, bx0
+ if nc == 1 then
+ bh, bw, by0, bx0 = 1, 1, my, mx
+ else
+ bh, bw, by0, bx0 = c.v, c.h, my * c.v, mx * c.h
+ end
+ local coef, bpl = c.coef, c.bpl
+ for by = by0, by0 + bh - 1 do
+ for bx = bx0, bx0 + bw - 1 do
+ local off = (by * bpl + bx) * 128
+ if mode == 0 then
+ local pred = dcDiff(c, Pm.dcL[c.dcTbl + 1], Pm.dcU[c.dcTbl + 1])
+ if not pred then
+ bad = true
+ else
+ c.pred = pred
+ writei16(coef, off, i16(pred))
+ if not acFirst(coef, off, c.acTbl, 1, 63, Pm.acK[c.acTbl + 1], 1) then
+ bad = true
+ end
+ end
+ elseif mode == 1 then
+ local pred = dcDiff(c, Pm.dcL[c.dcTbl + 1], Pm.dcU[c.dcTbl + 1])
+ if not pred then
+ bad = true
+ else
+ c.pred = pred
+ writei16(coef, off, i16(pred * mul))
+ end
+ elseif mode == 2 then
+ if decode(FIXED) ~= 0 then
+ local cv = readi16(coef, off)
+ if band(cv, mul) == 0 then
+ writei16(coef, off, i16(cv + mul))
+ end
+ end
+ elseif mode == 3 then
+ if not acFirst(coef, off, c.acTbl, ss, se, Pm.acK[c.acTbl + 1], mul) then
+ bad = true
+ end
+ else
+ if not acRefine(coef, off, c.acTbl, ss, se, al) then
+ bad = true
+ end
+ end
+ if bad then
+ break
+ end
+ end
+ if bad then
+ break
+ end
+ end
+ if bad then
+ break
+ end
+ end
+ end
+ end
+ D = buffer.create(0)
+ return truncated
+end
+
+return Arith
diff --git a/src/Formats/image/jpeg/Color.luau b/src/Formats/image/jpeg/Color.luau
new file mode 100644
index 0000000..af39c11
--- /dev/null
+++ b/src/Formats/image/jpeg/Color.luau
@@ -0,0 +1,229 @@
+--!strict
+--!native
+--!optimize 2
+-- image/jpeg/Color: chroma upsampling and colour conversion to RGBA8, one output row at a time (native; never
+-- throws). Absorbed from jpeg-luau 1.0 src/Jpeg/Color.luau (same author); a Luau translation of libjpeg-turbo's
+-- jdsample.c / jdcolor.c (IJG licence: licenses/libjpeg-turbo-LICENSE.md).
+--
+-- Upsampling follows libjpeg-turbo's jdsample.c, so the output matches djpeg's defaults:
+-- FULL the component is at output resolution
+-- H2V1 "fancy" triangle filter, 3/4 nearer + 1/4 further sample, alternating rounding (1, 2) / 4
+-- H2V2 fancy in both directions: vertical 3:1 column sums, then horizontal 3:1, rounding (8, 7) / 16
+-- H1V2 fancy vertical only, rounding 1 (upper row) / 2 (lower row)
+-- REPLICATE any other ratio (or no fancy upsampling): nearest sample, as int_upsample
+-- Edges replicate the last real sample (downW x downH), as libjpeg does with its context rows.
+-- Colour conversion is jdcolor.c's table-driven YCbCr -> RGB (16-bit fixed point), plus grey, RGB, CMYK and
+-- YCCK (Adobe inverted CMYK: R = C * K / 255).
+local readu16, readi32, readu8, writeu16, writeu32 = buffer.readu16, buffer.readi32, buffer.readu8, buffer.writeu16, buffer.writeu32
+local clamp, min, max = math.clamp, math.min, math.max
+
+local Color = {}
+
+Color.FULL = 0
+Color.REPLICATE = 1
+Color.H2V1 = 2
+Color.H2V2 = 3
+Color.H1V2 = 4
+
+Color.GRAY = 0
+Color.YCC = 1
+Color.RGB = 2
+Color.CMYK = 3
+Color.YCCK = 4
+Color.CMYK_PLAIN = 5 -- CMYK without an Adobe marker: not inverted
+
+export type Comp = {
+ plane: buffer, -- u16 samples, stride per row
+ stride: number,
+ rows: number, -- plane height
+ downW: number, -- real samples across / down (the rest is block padding)
+ downH: number,
+ method: number,
+ hIn: number,
+ hOut: number,
+ vIn: number,
+ vOut: number,
+ row: buffer, -- scratch row (u16, at least max(outW, 2 * downW) + 8 samples)
+}
+
+export type Params = {
+ comps: { Comp },
+ space: number,
+ outW: number,
+ outH: number,
+ maxv: number,
+ pixels: buffer,
+ -- YCbCr tables (maxv + 1 i32 entries)
+ crr: buffer,
+ cbb: buffer,
+ crg: buffer,
+ cbg: buffer,
+ toByte: buffer?, -- maxv + 1 u8 entries (12-bit), nil for 8-bit
+}
+
+-- jdcolor.c build_ycc_rgb_table
+function Color.tables(maxv: number): (buffer, buffer, buffer, buffer)
+ local n = maxv + 1
+ local center = n // 2
+ local crr, cbb, crg, cbg = buffer.create(n * 4), buffer.create(n * 4), buffer.create(n * 4), buffer.create(n * 4)
+ local function fix(x: number): number
+ return math.floor(x * 65536 + 0.5)
+ end
+ for i = 0, maxv do
+ local x = i - center
+ buffer.writei32(crr, i * 4, (fix(1.40200) * x + 32768) // 65536)
+ buffer.writei32(cbb, i * 4, (fix(1.77200) * x + 32768) // 65536)
+ buffer.writei32(crg, i * 4, -fix(0.71414) * x)
+ buffer.writei32(cbg, i * 4, -fix(0.34414) * x + 32768)
+ end
+ return crr, cbb, crg, cbg
+end
+
+-- fills c.row with output row y; returns the buffer and byte offset of the row's samples
+local function fetch(c: Comp, y: number, outW: number): (buffer, number)
+ local method = c.method
+ local plane, stride, row = c.plane, c.stride, c.row
+ if method == 0 then
+ return plane, min(y, c.rows - 1) * stride * 2
+ elseif method == 2 then
+ local w = c.downW
+ local b = min(y, c.rows - 1) * stride * 2
+ local cur = readu16(plane, b)
+ writeu16(row, 0, cur)
+ local nxt = readu16(plane, b + 2)
+ writeu16(row, 2, (cur * 3 + nxt + 2) // 4)
+ local prev = cur
+ cur = nxt
+ for i = 1, w - 2 do
+ nxt = readu16(plane, b + (i + 1) * 2)
+ local v3 = cur * 3
+ writeu16(row, i * 4, (v3 + prev + 1) // 4)
+ writeu16(row, i * 4 + 2, (v3 + nxt + 2) // 4)
+ prev = cur
+ cur = nxt
+ end
+ writeu16(row, (w - 1) * 4, (cur * 3 + prev + 1) // 4)
+ writeu16(row, (w - 1) * 4 + 2, cur)
+ return row, 0
+ elseif method == 3 then
+ local w = c.downW
+ local iy = min(y // 2, c.downH - 1)
+ local oy = if y % 2 == 0 then max(iy - 1, 0) else min(iy + 1, c.downH - 1)
+ local b0, b1 = iy * stride * 2, oy * stride * 2
+ local this = readu16(plane, b0) * 3 + readu16(plane, b1)
+ local nxt = readu16(plane, b0 + 2) * 3 + readu16(plane, b1 + 2)
+ writeu16(row, 0, (this * 4 + 8) // 16)
+ writeu16(row, 2, (this * 3 + nxt + 7) // 16)
+ local last = this
+ this = nxt
+ for i = 1, w - 2 do
+ nxt = readu16(plane, b0 + (i + 1) * 2) * 3 + readu16(plane, b1 + (i + 1) * 2)
+ local t3 = this * 3
+ writeu16(row, i * 4, (t3 + last + 8) // 16)
+ writeu16(row, i * 4 + 2, (t3 + nxt + 7) // 16)
+ last = this
+ this = nxt
+ end
+ writeu16(row, (w - 1) * 4, (this * 3 + last + 8) // 16)
+ writeu16(row, (w - 1) * 4 + 2, (this * 4 + 7) // 16)
+ return row, 0
+ elseif method == 4 then
+ local iy = min(y // 2, c.downH - 1)
+ local oy, bias
+ if y % 2 == 0 then
+ oy, bias = max(iy - 1, 0), 1
+ else
+ oy, bias = min(iy + 1, c.downH - 1), 2
+ end
+ local b0, b1 = iy * stride * 2, oy * stride * 2
+ for x = 0, outW - 1 do
+ writeu16(row, x * 2, (readu16(plane, b0 + x * 2) * 3 + readu16(plane, b1 + x * 2) + bias) // 4)
+ end
+ return row, 0
+ else
+ local hIn, hOut = c.hIn, c.hOut
+ local iy = min((y * c.vIn) // c.vOut, c.rows - 1)
+ local b = iy * stride * 2
+ local last = stride - 1
+ for x = 0, outW - 1 do
+ writeu16(row, x * 2, readu16(plane, b + min((x * hIn) // hOut, last) * 2))
+ end
+ return row, 0
+ end
+end
+
+function Color.run(P: Params)
+ local comps = P.comps
+ local nc = #comps
+ local space, outW, outH, maxv, out = P.space, P.outW, P.outH, P.maxv, P.pixels
+ local crr, cbb, crg, cbg = P.crr, P.cbb, P.crg, P.cbg
+ local toByte = P.toByte
+ local o = 0
+ for y = 0, outH - 1 do
+ local s0, b0 = fetch(comps[1], y, outW)
+ if space == 0 or nc < 3 then
+ for x = 0, outW - 1 do
+ local v = readu16(s0, b0 + x * 2)
+ if toByte then
+ v = readu8(toByte, v)
+ end
+ writeu32(out, o, 0xFF000000 + v * 0x10101)
+ o += 4
+ end
+ else
+ local s1, b1 = fetch(comps[2], y, outW)
+ local s2, b2 = fetch(comps[3], y, outW)
+ local s3, b3 = s0, b0
+ if nc >= 4 then
+ s3, b3 = fetch(comps[4], y, outW)
+ end
+ if space == 1 and not toByte then
+ -- the common case: 8-bit YCbCr
+ for x = 0, outW - 1 do
+ local i = x * 2
+ local yv, cb, cr = readu16(s0, b0 + i), readu16(s1, b1 + i), readu16(s2, b2 + i)
+ local r = clamp(yv + readi32(crr, cr * 4), 0, 255)
+ local g = clamp(yv + (readi32(cbg, cb * 4) + readi32(crg, cr * 4)) // 65536, 0, 255)
+ local b = clamp(yv + readi32(cbb, cb * 4), 0, 255)
+ writeu32(out, o, 0xFF000000 + r + g * 256 + b * 65536)
+ o += 4
+ end
+ continue
+ end
+ for x = 0, outW - 1 do
+ local i = x * 2
+ local c0, c1, c2 = readu16(s0, b0 + i), readu16(s1, b1 + i), readu16(s2, b2 + i)
+ local r, g, b
+ if space == 2 then
+ r, g, b = c0, c1, c2
+ elseif space == 3 or space == 5 then
+ local k = readu16(s3, b3 + i)
+ if space == 5 then
+ c0, c1, c2, k = maxv - c0, maxv - c1, maxv - c2, maxv - k
+ end
+ r = (c0 * k + maxv // 2) // maxv
+ g = (c1 * k + maxv // 2) // maxv
+ b = (c2 * k + maxv // 2) // maxv
+ else
+ r = clamp(c0 + readi32(crr, c2 * 4), 0, maxv)
+ g = clamp(c0 + (readi32(cbg, c1 * 4) + readi32(crg, c2 * 4)) // 65536, 0, maxv)
+ b = clamp(c0 + readi32(cbb, c1 * 4), 0, maxv)
+ if space == 4 then
+ -- YCCK: the YCC part decodes to inverted C, M, Y (libjpeg ycck_cmyk_convert), K as stored
+ local k = readu16(s3, b3 + i)
+ r = ((maxv - r) * k + maxv // 2) // maxv
+ g = ((maxv - g) * k + maxv // 2) // maxv
+ b = ((maxv - b) * k + maxv // 2) // maxv
+ end
+ end
+ if toByte then
+ r, g, b = readu8(toByte, r), readu8(toByte, g), readu8(toByte, b)
+ end
+ writeu32(out, o, 0xFF000000 + r + g * 256 + b * 65536)
+ o += 4
+ end
+ end
+ end
+end
+
+return Color
diff --git a/src/Formats/image/jpeg/Decode.luau b/src/Formats/image/jpeg/Decode.luau
new file mode 100644
index 0000000..11d2f64
--- /dev/null
+++ b/src/Formats/image/jpeg/Decode.luau
@@ -0,0 +1,666 @@
+--!strict
+-- image/jpeg/Decode: the JPEG marker parser and output stage (interpreted; it validates everything the native Scan /
+-- Arith / Dct / Color loops index). Absorbed from jpeg-luau 1.0 src/Jpeg/init.luau (same author) and extended:
+-- arithmetic-coded frames (SOF9 / SOF10, DAC), a reader range instead of a whole buffer, APP1 EXIF / APP2 ICC / COM
+-- / JFIF density collected for meta. The IDCT size choice for scaled decodes follows libjpeg-turbo's jdmaster.c.
+local Scan = require("@formats/image/jpeg/Scan")
+local Arith = require("@formats/image/jpeg/Arith")
+local Color = require("@formats/image/jpeg/Color")
+local Tables = require("@formats/image/jpeg/Tables")
+local Dct = require("@formats/codecs/Dct")
+
+local readu8 = buffer.readu8
+local band, rshift = bit32.band, bit32.rshift
+
+local Decode = {}
+
+Arith.init(Scan.ZIGZAG)
+
+local function be16(b: buffer, p: number): number
+ return readu8(b, p) * 256 + readu8(b, p + 1)
+end
+
+local stdBuilt: { [string]: buffer } = {}
+local function stdTable(class: string, slot: number): buffer?
+ local key = class .. slot
+ if not stdBuilt[key] then
+ local def = (if class == "dc" then Tables.DC else Tables.AC)[slot + 1]
+ if not def then
+ return nil
+ end
+ stdBuilt[key] = Scan.buildTable(def.counts, def.symbols)
+ end
+ return stdBuilt[key]
+end
+
+-- the EXIF TIFF block (after "Exif\0\0") and its orientation tag, from an APP1 segment at [p, e)
+local function exif(b: buffer, p: number, e: number): (number?, number?)
+ if e - p < 14 or buffer.readstring(b, p, 6) ~= "Exif\0\0" then
+ return nil, nil
+ end
+ local t = p + 6
+ local le
+ local bo = buffer.readstring(b, t, 2)
+ if bo == "II" then
+ le = true
+ elseif bo == "MM" then
+ le = false
+ else
+ return nil, nil
+ end
+ local function r16(at: number): number
+ if le then
+ return readu8(b, at) + readu8(b, at + 1) * 256
+ end
+ return readu8(b, at) * 256 + readu8(b, at + 1)
+ end
+ local function r32(at: number): number
+ if le then
+ return r16(at) + r16(at + 2) * 65536
+ end
+ return r16(at) * 65536 + r16(at + 2)
+ end
+ local ifd = t + r32(t + 4)
+ if ifd + 2 > e then
+ return t, nil
+ end
+ local count = r16(ifd)
+ for i = 0, count - 1 do
+ local en = ifd + 2 + i * 12
+ if en + 12 > e then
+ return t, nil
+ end
+ if r16(en) == 0x0112 then
+ local v = r16(en + 8)
+ return t, if v >= 1 and v <= 8 then v else nil
+ end
+ end
+ return t, nil
+end
+
+type Comp = {
+ id: number,
+ h: number,
+ v: number,
+ tq: number,
+ bpl: number,
+ bpc: number,
+ bw: number,
+ bh: number,
+ coef: buffer?,
+ quant: buffer?, -- latched at the component's first scan
+ dct: buffer?,
+ act: buffer?,
+ dcTbl: number,
+ acTbl: number,
+ pred: number,
+ ctx: number,
+}
+
+type Frame = {
+ width: number,
+ height: number,
+ precision: number,
+ progressive: boolean,
+ arithmetic: boolean,
+ comps: { Comp },
+ hmax: number,
+ vmax: number,
+ mcusX: number,
+ mcusY: number,
+}
+
+local SOF_REFUSED = {
+ [0xC3] = "lossless",
+ [0xC5] = "hierarchical",
+ [0xC6] = "hierarchical",
+ [0xC7] = "hierarchical",
+ [0xCB] = "lossless arithmetic-coded",
+ [0xCD] = "hierarchical arithmetic-coded",
+ [0xCE] = "hierarchical arithmetic-coded",
+ [0xCF] = "hierarchical arithmetic-coded",
+}
+
+-- failures carry a code: "corrupt" | "unsupported" | "limit" | "truncated"
+local function parseSof(b: buffer, p: number, e: number, m: number): (Frame?, string?, string?)
+ if e - p < 6 then
+ return nil, "corrupt", "short SOF"
+ end
+ local prec = readu8(b, p)
+ local height, width, nf = be16(b, p + 1), be16(b, p + 3), readu8(b, p + 5)
+ if prec ~= 8 and prec ~= 12 then
+ return nil, "unsupported", "sample precision " .. prec
+ end
+ if width == 0 or height == 0 then
+ if height == 0 and width > 0 then
+ return nil, "unsupported", "DNL (height 0 in the frame header)"
+ end
+ return nil, "corrupt", "bad size " .. width .. "x" .. height
+ end
+ if nf ~= 1 and nf ~= 3 and nf ~= 4 then
+ return nil, "unsupported", "component count " .. nf
+ end
+ if e - p < 6 + nf * 3 then
+ return nil, "corrupt", "short SOF"
+ end
+ local comps = {}
+ local hmax, vmax = 1, 1
+ for i = 0, nf - 1 do
+ local q = p + 6 + i * 3
+ local hv = readu8(b, q + 1)
+ local h, v, tq = rshift(hv, 4), band(hv, 15), readu8(b, q + 2)
+ if h < 1 or h > 4 or v < 1 or v > 4 then
+ return nil, "corrupt", "bad sampling factors " .. h .. "x" .. v
+ end
+ if tq > 3 then
+ return nil, "corrupt", "bad quantisation table selector " .. tq
+ end
+ local id = readu8(b, q)
+ for _, c in comps do
+ if c.id == id then
+ return nil, "corrupt", "duplicate component id " .. id
+ end
+ end
+ hmax, vmax = math.max(hmax, h), math.max(vmax, v)
+ table.insert(comps, { id = id, h = h, v = v, tq = tq, bpl = 0, bpc = 0, bw = 0, bh = 0, dcTbl = 0, acTbl = 0, pred = 0, ctx = 0 } :: Comp)
+ end
+ local mcusX = math.ceil(width / (8 * hmax))
+ local mcusY = math.ceil(height / (8 * vmax))
+ for _, c in comps do
+ c.bpl = mcusX * c.h
+ c.bpc = mcusY * c.v
+ c.bw = math.ceil(math.ceil(width * c.h / hmax) / 8)
+ c.bh = math.ceil(math.ceil(height * c.v / vmax) / 8)
+ end
+ return {
+ width = width,
+ height = height,
+ precision = prec,
+ progressive = m == 0xC2 or m == 0xCA,
+ arithmetic = m == 0xC9 or m == 0xCA,
+ comps = comps,
+ hmax = hmax,
+ vmax = vmax,
+ mcusX = mcusX,
+ mcusY = mcusY,
+ }
+end
+
+local function colorSpaceOf(frame: Frame, adobe: number?, jfif: boolean): string
+ local n = #frame.comps
+ if n == 1 then
+ return "gray"
+ elseif n == 3 then
+ if adobe ~= nil then
+ return if adobe == 0 then "rgb" else "ycbcr"
+ end
+ local c = frame.comps
+ if not jfif and c[1].id == 82 and c[2].id == 71 and c[3].id == 66 then
+ return "rgb"
+ end
+ return "ycbcr"
+ end
+ return if adobe == 2 then "ycck" else "cmyk"
+end
+Decode.colorSpaceOf = colorSpaceOf
+
+-- The IDCT size (8, 4, 2 or 1) for a component at a scale. libjpeg-turbo scales chroma up through a bigger IDCT
+-- instead of upsampling it, when the sampling ratios allow (jdmaster.c jpeg_calc_output_dimensions).
+local function idctSize(f: Frame, c: Comp, scale: number): number
+ local minSize = 8 // scale
+ local ssize = minSize
+ while ssize < 8 and (f.hmax * minSize) % (c.h * ssize * 2) == 0 and (f.vmax * minSize) % (c.v * ssize * 2) == 0 do
+ ssize *= 2
+ end
+ return ssize
+end
+
+export type State = {
+ frame: any,
+ adobe: number?,
+ jfif: boolean,
+ density: { unit: number, x: number, y: number }?,
+ orientation: number,
+ exif: buffer?,
+ icc: buffer?,
+ comments: { string },
+ truncated: boolean,
+ scale: number,
+}
+
+-- parse(b, base, limit, opts, headerOnly) -> State | nil, code, message. Walks the markers in b[base, limit); with
+-- headerOnly it stops at the frame header, otherwise it decodes every scan into the components' coefficients.
+function Decode.parse(b: buffer, base: number, n: number, opts: any, headerOnly: boolean): (State?, string?, string?)
+ if n - base < 4 or readu8(b, base) ~= 0xFF or readu8(b, base + 1) ~= 0xD8 then
+ return nil, "corrupt", "not a JPEG file (no SOI marker)"
+ end
+ local scale = (opts and opts.scale) or 1
+ if scale ~= 1 and scale ~= 2 and scale ~= 4 and scale ~= 8 then
+ return nil, "arg", "scale must be 1, 2, 4 or 8"
+ end
+ local maxPixels = (opts and opts.maxPixels) or 2 ^ 26
+ local quant: { [number]: buffer } = {}
+ local dcT: { [number]: buffer } = {}
+ local acT: { [number]: buffer } = {}
+ local dcL, dcU, acK = { 0, 0, 0, 0 }, { 1, 1, 1, 1 }, { 5, 5, 5, 5 }
+ local frame: Frame? = nil
+ local st: State = {
+ frame = nil,
+ adobe = nil,
+ jfif = false,
+ density = nil,
+ orientation = 1,
+ exif = nil,
+ icc = nil,
+ comments = {},
+ truncated = false,
+ scale = scale,
+ }
+ local iccChunks: { buffer } = {}
+ local ri = 0
+ local scans = 0
+ local clean: buffer? = nil
+ local rst = {}
+ local pos = base + 2
+ while pos < n do
+ -- find the next marker (tolerate garbage and fill bytes)
+ if readu8(b, pos) ~= 0xFF then
+ pos += 1
+ continue
+ end
+ while pos < n and readu8(b, pos) == 0xFF do
+ pos += 1
+ end
+ if pos >= n then
+ break
+ end
+ local m = readu8(b, pos)
+ pos += 1
+ if m == 0xD9 then
+ break -- EOI
+ elseif m == 0 or m == 0x01 or m == 0xD8 or (m >= 0xD0 and m <= 0xD7) then
+ continue -- standalone markers (or stray stuffing)
+ end
+ if pos + 2 > n then
+ st.truncated = true
+ break
+ end
+ local len = be16(b, pos)
+ if len < 2 then
+ return nil, "corrupt", string.format("bad segment length for marker %02X", m)
+ end
+ local p, e = pos + 2, pos + len
+ if e > n then
+ if m == 0xDA and frame and not headerOnly then
+ e = n -- a truncated SOS header still fails below
+ else
+ st.truncated = true
+ break
+ end
+ end
+ pos = e
+ if m == 0xE0 then
+ if e - p >= 12 and buffer.readstring(b, p, 5) == "JFIF\0" then
+ st.jfif = true
+ st.density = { unit = readu8(b, p + 7), x = be16(b, p + 8), y = be16(b, p + 10) }
+ end
+ elseif m == 0xE1 then
+ local t, o = exif(b, p, e)
+ if t and not st.exif then
+ local x = buffer.create(e - t)
+ buffer.copy(x, 0, b, t, e - t)
+ st.exif = x
+ end
+ if o then
+ st.orientation = o
+ end
+ elseif m == 0xE2 then
+ -- ICC_PROFILE\0, sequence number, count, data
+ if e - p >= 14 and buffer.readstring(b, p, 12) == "ICC_PROFILE\0" then
+ local seq = readu8(b, p + 12)
+ local x = buffer.create(e - p - 14)
+ buffer.copy(x, 0, b, p + 14, e - p - 14)
+ if seq >= 1 then
+ iccChunks[seq] = x
+ end
+ end
+ elseif m == 0xEE then
+ if e - p >= 12 and buffer.readstring(b, p, 5) == "Adobe" then
+ st.adobe = readu8(b, p + 11)
+ end
+ elseif m == 0xFE then
+ table.insert(st.comments, buffer.readstring(b, p, e - p))
+ elseif m == 0xDB then
+ -- DQT
+ while p < e do
+ local pt = readu8(b, p)
+ local pq, tq = rshift(pt, 4), band(pt, 15)
+ local size = if pq == 0 then 64 else 128
+ if tq > 3 or pq > 1 or p + 1 + size > e then
+ return nil, "corrupt", "bad DQT segment"
+ end
+ local q = buffer.create(128)
+ for k = 0, 63 do
+ local v = if pq == 0 then readu8(b, p + 1 + k) else be16(b, p + 1 + k * 2)
+ buffer.writeu16(q, readu8(Scan.ZIGZAG, k) * 2, v)
+ end
+ quant[tq] = q
+ p += 1 + size
+ end
+ elseif m == 0xC4 then
+ -- DHT
+ while p < e do
+ if p + 17 > e then
+ return nil, "corrupt", "bad DHT segment"
+ end
+ local tc = readu8(b, p)
+ local class, slot = rshift(tc, 4), band(tc, 15)
+ if class > 1 or slot > 3 then
+ return nil, "corrupt", "bad DHT table class / slot"
+ end
+ local counts, total = {}, 0
+ for l = 1, 16 do
+ counts[l] = readu8(b, p + l)
+ total += counts[l]
+ end
+ if total > 256 or p + 17 + total > e then
+ return nil, "corrupt", "bad DHT segment"
+ end
+ local syms = {}
+ for i = 1, total do
+ syms[i] = readu8(b, p + 16 + i)
+ end
+ local t = Scan.buildTable(counts, syms)
+ if class == 0 then
+ dcT[slot] = t
+ else
+ acT[slot] = t
+ end
+ p += 17 + total
+ end
+ elseif m == 0xCC then
+ -- DAC: arithmetic conditioning
+ while p + 2 <= e do
+ local tc, v = readu8(b, p), readu8(b, p + 1)
+ local class, slot = rshift(tc, 4), band(tc, 15)
+ if class > 1 or slot > 3 then
+ return nil, "corrupt", "bad DAC segment"
+ end
+ if class == 0 then
+ local L, U = band(v, 15), rshift(v, 4)
+ if L > U then
+ return nil, "corrupt", "bad DAC value"
+ end
+ dcL[slot + 1], dcU[slot + 1] = L, U
+ else
+ if v < 1 or v > 63 then
+ return nil, "corrupt", "bad DAC value"
+ end
+ acK[slot + 1] = v
+ end
+ p += 2
+ end
+ elseif m == 0xDD then
+ if e - p < 2 then
+ return nil, "corrupt", "bad DRI segment"
+ end
+ ri = be16(b, p)
+ elseif m == 0xC0 or m == 0xC1 or m == 0xC2 or m == 0xC9 or m == 0xCA then
+ if frame then
+ return nil, "corrupt", "more than one frame header"
+ end
+ local f, code, err = parseSof(b, p, e, m)
+ if not f then
+ return nil, code, err
+ end
+ if f.width * f.height > maxPixels then
+ return nil, "limit", string.format("%d x %d is over the %d pixel limit", f.width, f.height, maxPixels)
+ end
+ frame = f
+ st.frame = f
+ if headerOnly then
+ return st
+ end
+ elseif SOF_REFUSED[m] then
+ return nil, "unsupported", SOF_REFUSED[m] .. " JPEG"
+ elseif m == 0xDA then
+ if headerOnly then
+ break
+ end
+ if not frame then
+ return nil, "corrupt", "scan before the frame header"
+ end
+ local f = frame :: Frame
+ local ns = if p < e then readu8(b, p) else 0
+ if ns < 1 or ns > 4 or e - p < 4 + ns * 2 then
+ return nil, "corrupt", "bad SOS segment"
+ end
+ local sc = {}
+ local blocks = 0
+ for i = 0, ns - 1 do
+ local id, t = readu8(b, p + 1 + i * 2), readu8(b, p + 2 + i * 2)
+ local comp = nil
+ for _, c in f.comps do
+ if c.id == id then
+ comp = c
+ end
+ end
+ if not comp or table.find(sc, comp) then
+ return nil, "corrupt", "scan names an unknown component " .. id
+ end
+ local td, ta = rshift(t, 4), band(t, 15)
+ if td > 3 or ta > 3 then
+ return nil, "corrupt", "bad entropy table selector"
+ end
+ comp.dcTbl, comp.acTbl = td, ta
+ if not f.arithmetic then
+ comp.dct = dcT[td] or stdTable("dc", td)
+ comp.act = acT[ta] or stdTable("ac", ta)
+ end
+ blocks += comp.h * comp.v
+ table.insert(sc, comp)
+ end
+ local q = p + 1 + ns * 2
+ local ss, se, a = readu8(b, q), readu8(b, q + 1), readu8(b, q + 2)
+ local ah, al = rshift(a, 4), band(a, 15)
+ if ns > 1 and blocks > 10 then
+ return nil, "corrupt", "more than 10 blocks per MCU"
+ end
+ local mode
+ if not f.progressive then
+ mode = 0
+ ss, se, ah, al = 0, 63, 0, 0
+ else
+ if se > 63 or ss > se or ah > 13 or al > 13 or (ss == 0 and se ~= 0) or (ss > 0 and ns ~= 1) then
+ return nil, "corrupt", "bad progressive scan parameters"
+ end
+ if ss == 0 then
+ mode = if ah == 0 then 1 else 2
+ else
+ mode = if ah == 0 then 3 else 4
+ end
+ end
+ for _, c in sc do
+ if not f.arithmetic then
+ if (mode == 0 or mode == 1) and not c.dct then
+ return nil, "corrupt", "missing DC Huffman table"
+ end
+ if (mode == 0 or mode == 3 or mode == 4) and not c.act then
+ return nil, "corrupt", "missing AC Huffman table"
+ end
+ end
+ if not c.coef then
+ c.coef = buffer.create(c.bpl * c.bpc * 128)
+ end
+ if not c.quant then
+ c.quant = quant[c.tq]
+ end
+ end
+ if not clean then
+ clean = buffer.create(n - base + Scan.PAD)
+ end
+ local cb = clean :: buffer
+ local nextPos, cleanLen, nrst = Scan.destuff(b, pos, n, cb, rst)
+ if nextPos >= n then
+ st.truncated = true -- no EOI
+ end
+ -- a component decoded through the 1x1 IDCT only needs its DC coefficient: skip its AC scans
+ if not (mode >= 3 and idctSize(f, sc[1], scale) == 1) then
+ local params = {
+ comps = sc :: any,
+ mcusX = f.mcusX,
+ mcusY = f.mcusY,
+ ri = ri,
+ mode = mode,
+ ss = ss,
+ se = se,
+ al = al,
+ dcL = dcL,
+ dcU = dcU,
+ acK = acK,
+ }
+ local short
+ if f.arithmetic then
+ short = Arith.run(cb, cleanLen, rst, nrst, params)
+ else
+ local _
+ _, short = Scan.run(cb, cleanLen, rst, nrst, params)
+ end
+ st.truncated = st.truncated or short
+ end
+ scans += 1
+ pos = nextPos
+ end
+ end
+ if not frame then
+ return nil, if st.truncated then "truncated" else "corrupt", "no frame header"
+ end
+ if #iccChunks > 0 then
+ local total = 0
+ for _, c in iccChunks do
+ total += buffer.len(c)
+ end
+ local icc = buffer.create(total)
+ local o = 0
+ for _, c in iccChunks do
+ buffer.copy(icc, o, c)
+ o += buffer.len(c)
+ end
+ st.icc = icc
+ end
+ if headerOnly then
+ return st
+ end
+ if scans == 0 then
+ return nil, "truncated", "no image data"
+ end
+ return st
+end
+
+local SPACE_IDS = { gray = Color.GRAY, ycbcr = Color.YCC, rgb = Color.RGB, cmyk = Color.CMYK, ycck = Color.YCCK }
+
+local tableCache: { [number]: { buffer } } = {}
+local function yccTables(maxv: number): { buffer }
+ local t = tableCache[maxv]
+ if not t then
+ local a, b, c, d = Color.tables(maxv)
+ t = { a, b, c, d }
+ tableCache[maxv] = t
+ end
+ return t
+end
+
+local toByte12: buffer? = nil
+
+-- output(st) -> width, height, rgba8 pixels, colour space | nil, code, message
+function Decode.output(st: State): (number?, any, any, string?)
+ local f: Frame = st.frame
+ local scale = st.scale
+ local minSize = 8 // scale
+ local maxv = if f.precision == 12 then 4095 else 255
+ local center = (maxv + 1) // 2
+ local p1 = if f.precision == 12 then 1 else 2
+ local outW = math.ceil(f.width * minSize / 8)
+ local outH = math.ceil(f.height * minSize / 8)
+ local fancy = minSize > 1
+ local ccomps = {}
+ local zeroQ = buffer.create(128)
+ for _, c in f.comps do
+ local ssize = idctSize(f, c, scale)
+ local stride, rows = c.bpl * ssize, c.bpc * ssize
+ local plane = buffer.create(stride * rows * 2)
+ local coef = c.coef or buffer.create(c.bpl * c.bpc * 128)
+ local q = c.quant
+ if not q then
+ if c.coef then
+ return nil, "corrupt", "missing quantisation table " .. c.tq
+ end
+ q = zeroQ -- the component never appeared in a scan: mid grey
+ end
+ Dct.idctComponent(coef, q :: buffer, c.bpl, c.bpc, ssize, plane, p1, center, maxv)
+ local hIn, hOut = c.h * ssize // minSize, f.hmax
+ local vIn, vOut = c.v * ssize // minSize, f.vmax
+ local downW = math.ceil(f.width * c.h * ssize / (f.hmax * 8))
+ local downH = math.ceil(f.height * c.v * ssize / (f.vmax * 8))
+ local method
+ if hIn == hOut and vIn == vOut then
+ method = Color.FULL
+ elseif hIn * 2 == hOut and vIn * 2 == vOut and fancy and downW > 2 then
+ method = Color.H2V2
+ elseif hIn * 2 == hOut and vIn == vOut and fancy and downW > 2 then
+ method = Color.H2V1
+ elseif hIn == hOut and vIn * 2 == vOut and fancy then
+ method = Color.H1V2
+ else
+ method = Color.REPLICATE
+ end
+ table.insert(ccomps, {
+ plane = plane,
+ stride = stride,
+ rows = rows,
+ downW = downW,
+ downH = downH,
+ method = method,
+ hIn = hIn,
+ hOut = hOut,
+ vIn = vIn,
+ vOut = vOut,
+ row = buffer.create((math.max(outW, 2 * stride) + 8) * 2),
+ })
+ c.coef = nil -- free the coefficients early
+ end
+ local space = colorSpaceOf(f, st.adobe, st.jfif)
+ local spaceId = SPACE_IDS[space]
+ if space == "cmyk" and st.adobe == nil then
+ spaceId = Color.CMYK_PLAIN
+ end
+ local t = yccTables(maxv)
+ local tb = nil
+ if maxv == 4095 then
+ if not toByte12 then
+ local tbuf = buffer.create(4096)
+ for v = 0, 4095 do
+ buffer.writeu8(tbuf, v, (v * 255 + 2047) // 4095)
+ end
+ toByte12 = tbuf
+ end
+ tb = toByte12
+ end
+ local pixels = buffer.create(outW * outH * 4)
+ Color.run({
+ comps = ccomps,
+ space = spaceId,
+ outW = outW,
+ outH = outH,
+ maxv = maxv,
+ pixels = pixels,
+ crr = t[1],
+ cbb = t[2],
+ crg = t[3],
+ cbg = t[4],
+ toByte = tb,
+ })
+ return outW, outH, pixels, space
+end
+
+return Decode
diff --git a/src/Formats/image/jpeg/Encode.luau b/src/Formats/image/jpeg/Encode.luau
new file mode 100644
index 0000000..0ecf6eb
--- /dev/null
+++ b/src/Formats/image/jpeg/Encode.luau
@@ -0,0 +1,883 @@
+--!strict
+--!native
+--!optimize 2
+-- image/jpeg/Encode: the JPEG encoder (native; never throws). Baseline (SOF0) with the standard or optimised Huffman
+-- tables and progressive (SOF2, libjpeg's jpeg_simple_progression script, optimised tables per scan); grey or YCbCr
+-- 4:4:4 / 4:2:2 / 4:2:0; restart intervals. It follows libjpeg-turbo's encoder step for step so that its output is
+-- byte-identical to cjpeg's for the same settings: jccolor.c (fixed-point RGB -> YCbCr), jcsample.c (box downsampling
+-- with alternating rounding bias, right-edge replication), jccoefct.c (dummy edge blocks), jfdctint.c + jcdctmgr.c
+-- (codecs/Dct), jchuff.c (sequential coding, jpeg_gen_optimal_table) and jcphuff.c (progressive coding: EOB runs,
+-- correction-bit buffering). Luau translation of IJG code: licenses/libjpeg-turbo-LICENSE.md.
+local Dct = require("@formats/codecs/Dct")
+local Tables = require("@formats/image/jpeg/Tables")
+
+local readu8, writeu8, readi16, writei16, readu16, writeu16 = buffer.readu8, buffer.writeu8, buffer.readi16, buffer.writei16, buffer.readu16, buffer.writeu16
+local band, countlz = bit32.band, bit32.countlz
+
+local Encode = {}
+
+-- natural order index of zigzag position k
+local ZZ = buffer.create(64)
+do
+ local i = 0
+ for s = 0, 14 do
+ local lo, hi = math.max(0, s - 7), math.min(s, 7)
+ if s % 2 == 0 then
+ for r = hi, lo, -1 do
+ writeu8(ZZ, i, r * 8 + (s - r))
+ i += 1
+ end
+ else
+ for r = lo, hi do
+ writeu8(ZZ, i, r * 8 + (s - r))
+ i += 1
+ end
+ end
+ end
+end
+Encode.ZIGZAG = ZZ
+
+-- ------------------------------------------------------------------------------------------------ output
+local OUT = buffer.create(0)
+local OP = 0
+local CAP = 0
+local ACC, NB = 0, 0
+local GATHER = false
+
+local function grow(n: number)
+ if OP + n > CAP then
+ local c = math.max(CAP * 2, OP + n + 1024)
+ local nb = buffer.create(c)
+ buffer.copy(nb, 0, OUT, 0, OP)
+ OUT = nb
+ CAP = c
+ end
+end
+
+local function byte(v: number)
+ grow(1)
+ writeu8(OUT, OP, v)
+ OP += 1
+end
+
+local function u16be(v: number)
+ byte(v // 256)
+ byte(v % 256)
+end
+
+-- n bits of v (n <= 16), MSB first, with 0xFF stuffing
+local function bits(v: number, n: number)
+ if GATHER or n == 0 then
+ return
+ end
+ local p = 2 ^ n
+ ACC = ACC * p + band(v, p - 1)
+ NB += n
+ while NB >= 8 do
+ NB -= 8
+ local d = 2 ^ NB
+ local b = ACC // d
+ ACC -= b * d
+ grow(2)
+ writeu8(OUT, OP, b)
+ OP += 1
+ if b == 0xFF then
+ writeu8(OUT, OP, 0)
+ OP += 1
+ end
+ end
+end
+
+local function flushBits()
+ if NB > 0 then
+ bits(0x7F, 8 - NB) -- pad with ones
+ end
+ ACC, NB = 0, 0
+end
+
+local function nbits(v: number): number
+ return if v == 0 then 0 else 32 - countlz(v)
+end
+
+-- ------------------------------------------------------------------------------------------------ Huffman tables
+-- a derived table: u16 code + u8 size per symbol (jpeg_make_c_derived_tbl)
+export type Derived = { code: buffer, size: buffer }
+
+local function derive(counts: { number }, symbols: { number }): Derived
+ local code, size = buffer.create(512), buffer.create(256)
+ local c, k = 0, 1
+ for l = 1, 16 do
+ for _ = 1, counts[l] or 0 do
+ local s = symbols[k]
+ if s then
+ writeu16(code, s * 2, c)
+ writeu8(size, s, l)
+ end
+ k += 1
+ c += 1
+ end
+ c *= 2
+ end
+ return { code = code, size = size }
+end
+
+-- jchuff.c jpeg_gen_optimal_table: freq (0..256, 1-based +1) -> counts, symbols
+local function optimal(freqIn: { number }): ({ number }, { number })
+ local freq = table.create(257, 0)
+ local bitsT = table.create(34, 0)
+ local codesize = table.create(257, 0)
+ local others = table.create(257, -1)
+ local nz = table.create(257, 0)
+ local n = 0
+ for i = 0, 256 do
+ local f = if i == 256 then 1 else freqIn[i + 1]
+ if f > 0 then
+ n += 1
+ nz[n] = i
+ freq[n] = f
+ end
+ end
+ while true do
+ local c1, c2 = -1, -1
+ local v, v2 = 1e9, 1e9
+ for i = 1, n do
+ local f = freq[i]
+ if f <= v2 then
+ if f <= v then
+ c2 = c1
+ v2 = v
+ v = f
+ c1 = i
+ else
+ v2 = f
+ c2 = i
+ end
+ end
+ end
+ if c2 < 0 then
+ break
+ end
+ freq[c1] += freq[c2]
+ freq[c2] = 1000000001
+ codesize[c1] += 1
+ while others[c1] >= 0 do
+ c1 = others[c1]
+ codesize[c1] += 1
+ end
+ others[c1] = c2
+ codesize[c2] += 1
+ while others[c2] >= 0 do
+ c2 = others[c2]
+ codesize[c2] += 1
+ end
+ end
+ for i = 1, n do
+ local cs = math.min(codesize[i], 32)
+ bitsT[cs + 1] += 1
+ end
+ local bitPos = table.create(34, 0)
+ local p = 0
+ for i = 1, 32 do
+ bitPos[i + 1] = p
+ p += bitsT[i + 1]
+ end
+ local i = 32
+ while i > 16 do
+ while bitsT[i + 1] > 0 do
+ local j = i - 2
+ while bitsT[j + 1] == 0 do
+ j -= 1
+ end
+ bitsT[i + 1] -= 2
+ bitsT[i] += 1
+ bitsT[j + 2] += 2
+ bitsT[j + 1] -= 1
+ end
+ i -= 1
+ end
+ while bitsT[i + 1] == 0 do
+ i -= 1
+ end
+ bitsT[i + 1] -= 1
+ local counts = table.create(16, 0)
+ for l = 1, 16 do
+ counts[l] = bitsT[l + 1]
+ end
+ local symbols = table.create(n, 0)
+ for k = 1, n - 1 do
+ local cs = math.min(codesize[k], 32)
+ symbols[bitPos[cs + 1] + 1] = nz[k]
+ bitPos[cs + 1] += 1
+ end
+ local total = 0
+ for l = 1, 16 do
+ total += counts[l]
+ end
+ local out = table.create(total, 0)
+ for k = 1, total do
+ out[k] = symbols[k]
+ end
+ return counts, out
+end
+Encode.optimal = optimal
+
+-- ------------------------------------------------------------------------------------------------ entropy coding state
+local dcTab: { Derived } = {}
+local acTab: { Derived } = {}
+local dcFreq: { { number } } = {}
+local acFreq: { { number } } = {}
+
+local function symbol(t: Derived, freq: { number }, s: number)
+ if GATHER then
+ freq[s + 1] += 1
+ else
+ bits(readu16(t.code, s * 2), readu8(t.size, s))
+ end
+end
+
+export type Comp = {
+ id: number,
+ h: number,
+ v: number,
+ tq: number,
+ td: number, -- DC table slot
+ ta: number, -- AC table slot
+ bw: number, -- real blocks across / down
+ bh: number,
+ bpl: number, -- MCU-padded block grid
+ bpc: number,
+ coef: buffer, -- i16, 64 per block, natural order
+ last: number, -- DC predictor
+}
+
+local function dcDiff(c: Comp, diff: number)
+ local t = diff
+ local t2 = diff
+ if t < 0 then
+ t = -t
+ t2 -= 1
+ end
+ local n = nbits(t)
+ symbol(dcTab[c.td + 1], dcFreq[c.td + 1], n)
+ if n > 0 then
+ bits(t2, n)
+ end
+end
+
+-- jchuff.c encode_one_block
+local function blockSeq(c: Comp, off: number)
+ local coef = c.coef
+ local dc = readi16(coef, off)
+ dcDiff(c, dc - c.last)
+ c.last = dc
+ local at, af = acTab[c.ta + 1], acFreq[c.ta + 1]
+ local r = 0
+ for k = 1, 63 do
+ local v = readi16(coef, off + readu8(ZZ, k) * 2)
+ if v == 0 then
+ r += 1
+ else
+ while r > 15 do
+ symbol(at, af, 0xF0)
+ r -= 16
+ end
+ local t, t2 = v, v
+ if t < 0 then
+ t = -t
+ t2 -= 1
+ end
+ local n = nbits(t)
+ symbol(at, af, r * 16 + n)
+ bits(t2, n)
+ r = 0
+ end
+ end
+ if r > 0 then
+ symbol(at, af, 0)
+ end
+end
+
+-- progressive state (jcphuff.c)
+local EOBRUN = 0
+local BE = 0
+local CORR: { number } = table.create(1000, 0)
+local curAc: Derived = { code = buffer.create(512), size = buffer.create(256) }
+local curAcFreq: { number } = {}
+
+local function emitEobrun()
+ if EOBRUN > 0 then
+ local n = nbits(EOBRUN) - 1
+ symbol(curAc, curAcFreq, n * 16)
+ if n > 0 then
+ bits(EOBRUN, n)
+ end
+ EOBRUN = 0
+ if not GATHER then
+ for i = 1, BE do
+ bits(CORR[i], 1)
+ end
+ end
+ BE = 0
+ end
+end
+
+local function blockDcFirst(c: Comp, off: number, al: number)
+ local t2 = readi16(c.coef, off) // 2 ^ al
+ dcDiff(c, t2 - c.last)
+ c.last = t2
+end
+
+local function blockAcFirst(c: Comp, off: number, ss: number, se: number, al: number)
+ local coef = c.coef
+ local d = 2 ^ al
+ local r = 0
+ for k = ss, se do
+ local v = readi16(coef, off + readu8(ZZ, k) * 2)
+ local t, t2
+ if v < 0 then
+ t = (-v) // d
+ t2 = -t - 1 -- ~t
+ else
+ t = v // d
+ t2 = t
+ end
+ if t == 0 then
+ r += 1
+ else
+ emitEobrun()
+ while r > 15 do
+ symbol(curAc, curAcFreq, 0xF0)
+ r -= 16
+ end
+ local n = nbits(t)
+ symbol(curAc, curAcFreq, r * 16 + n)
+ bits(t2, n)
+ r = 0
+ end
+ end
+ if r > 0 then
+ EOBRUN += 1
+ if EOBRUN == 0x7FFF then
+ emitEobrun()
+ end
+ end
+end
+
+local absv = table.create(64, 0)
+
+local function blockAcRefine(c: Comp, off: number, ss: number, se: number, al: number)
+ local coef = c.coef
+ local d = 2 ^ al
+ local eob = 0
+ for k = ss, se do
+ local v = readi16(coef, off + readu8(ZZ, k) * 2)
+ local t = (if v < 0 then -v else v) // d
+ absv[k + 1] = t
+ if t == 1 then
+ eob = k
+ end
+ end
+ local r = 0
+ local br = 0 -- correction bits added in this block, at CORR[brStart + 1 ..]
+ local brStart = BE
+ for k = ss, se do
+ local t = absv[k + 1]
+ if t == 0 then
+ r += 1
+ continue
+ end
+ while r > 15 and k <= eob do
+ emitEobrun()
+ symbol(curAc, curAcFreq, 0xF0)
+ r -= 16
+ if not GATHER then
+ for i = 1, br do
+ bits(CORR[brStart + i], 1)
+ end
+ end
+ brStart = 0
+ br = 0
+ end
+ if t > 1 then
+ br += 1
+ CORR[brStart + br] = t % 2
+ continue
+ end
+ emitEobrun()
+ symbol(curAc, curAcFreq, r * 16 + 1)
+ bits(if readi16(coef, off + readu8(ZZ, k) * 2) < 0 then 0 else 1, 1)
+ if not GATHER then
+ for i = 1, br do
+ bits(CORR[brStart + i], 1)
+ end
+ end
+ brStart = 0
+ br = 0
+ r = 0
+ end
+ if r > 0 or br > 0 then
+ EOBRUN += 1
+ BE += br
+ if EOBRUN == 0x7FFF or BE > 1000 - 64 + 1 then
+ emitEobrun()
+ end
+ end
+end
+
+-- ------------------------------------------------------------------------------------------------ scans
+export type ScanSpec = { comps: { number }, ss: number, se: number, ah: number, al: number }
+
+-- iterate the scan's MCUs (or blocks, for one component), calling fn(c, off) per block; restart markers when ri > 0
+local function walk(comps: { Comp }, mcusX: number, mcusY: number, ri: number, onRestart: (number) -> (), fn: (Comp, number) -> ())
+ local nc = #comps
+ local units, ux
+ if nc == 1 then
+ ux = comps[1].bw
+ units = ux * comps[1].bh
+ else
+ ux = mcusX
+ units = ux * mcusY
+ end
+ local rn = 0
+ for u = 0, units - 1 do
+ if ri > 0 and u > 0 and u % ri == 0 then
+ onRestart(rn)
+ rn = (rn + 1) % 8
+ end
+ local my, mx = u // ux, u % ux
+ for ci = 1, nc do
+ local c = comps[ci]
+ if nc == 1 then
+ fn(c, (my * c.bpl + mx) * 128)
+ else
+ for by = my * c.v, my * c.v + c.v - 1 do
+ for bx = mx * c.h, mx * c.h + c.h - 1 do
+ fn(c, (by * c.bpl + bx) * 128)
+ end
+ end
+ end
+ end
+ end
+end
+
+local function dht(class: number, slot: number, counts: { number }, symbols: { number })
+ byte(0xFF)
+ byte(0xC4)
+ u16be(2 + 17 + #symbols)
+ byte(class * 16 + slot)
+ for l = 1, 16 do
+ byte(counts[l])
+ end
+ for _, s in symbols do
+ byte(s)
+ end
+end
+
+local function sos(comps: { Comp }, ss: number, se: number, ah: number, al: number, dcOnly: boolean, acOnly: boolean)
+ byte(0xFF)
+ byte(0xDA)
+ u16be(6 + 2 * #comps)
+ byte(#comps)
+ for _, c in comps do
+ byte(c.id)
+ local td = if acOnly then 0 else c.td
+ local ta = if dcOnly then 0 else c.ta
+ byte(td * 16 + ta)
+ end
+ byte(ss)
+ byte(se)
+ byte(ah * 16 + al)
+end
+
+-- ------------------------------------------------------------------------------------------------ planes
+-- jccolor.c rgb_ycc_start tables (16-bit fixed point)
+local function fix(x: number): number
+ return math.floor(x * 65536 + 0.5)
+end
+local YR, YG, YB = fix(0.29900), fix(0.58700), fix(0.11400)
+local CBR, CBG, HALF = fix(0.16874), fix(0.33126), fix(0.5)
+local CRG, CRB = fix(0.41869), fix(0.08131)
+local OFF = 128 * 65536 + 32768 - 1
+
+-- pixels (rgba8 / rgb8 / gray8) -> Y, Cb, Cr planes (w * h bytes each; Cb / Cr nil for grey output)
+local function planes(px: buffer, w: number, h: number, bpp: number, gray: boolean): (buffer, buffer?, buffer?)
+ local n = w * h
+ local Y = buffer.create(n)
+ if bpp == 1 then
+ buffer.copy(Y, 0, px, 0, n)
+ if gray then
+ return Y, nil, nil
+ end
+ local Cb = buffer.create(n)
+ buffer.fill(Cb, 0, 128, n)
+ local Cr = buffer.create(n)
+ buffer.fill(Cr, 0, 128, n)
+ return Y, Cb, Cr
+ end
+ if gray then
+ for i = 0, n - 1 do
+ local o = i * bpp
+ local r, g, b = readu8(px, o), readu8(px, o + 1), readu8(px, o + 2)
+ writeu8(Y, i, (YR * r + YG * g + YB * b + 32768) // 65536)
+ end
+ return Y, nil, nil
+ end
+ local Cb, Cr = buffer.create(n), buffer.create(n)
+ for i = 0, n - 1 do
+ local o = i * bpp
+ local r, g, b = readu8(px, o), readu8(px, o + 1), readu8(px, o + 2)
+ writeu8(Y, i, (YR * r + YG * g + YB * b + 32768) // 65536)
+ writeu8(Cb, i, (-CBR * r - CBG * g + HALF * b + OFF) // 65536)
+ writeu8(Cr, i, (HALF * r - CRG * g - CRB * b + OFF) // 65536)
+ end
+ return Y, Cb, Cr
+end
+
+-- jcsample.c: a full-resolution plane (w x h) -> the component's samples, (bw * 8) x ch, for factors hf x vf
+-- (1 or 2 each); full-resolution columns past w - 1 repeat the last one, rows past h - 1 the last row
+local function downsample(src: buffer, w: number, h: number, hf: number, vf: number, outW: number, outH: number): buffer
+ local out = buffer.create(outW * outH)
+ for oy = 0, outH - 1 do
+ local r0 = math.min(oy * vf, h - 1) * w
+ local r1 = math.min(oy * vf + vf - 1, h - 1) * w
+ local bias = if hf == 2 and vf == 2 then 1 elseif hf == 2 then 0 else (if vf == 2 then 1 else 0)
+ for ox = 0, outW - 1 do
+ local x0 = math.min(ox * hf, w - 1)
+ local x1 = math.min(ox * hf + hf - 1, w - 1)
+ local v
+ if hf == 2 and vf == 2 then
+ v = (readu8(src, r0 + x0) + readu8(src, r0 + x1) + readu8(src, r1 + x0) + readu8(src, r1 + x1) + bias) // 4
+ bias = 3 - bias
+ elseif hf == 2 then
+ v = (readu8(src, r0 + x0) + readu8(src, r0 + x1) + bias) // 2
+ bias = 1 - bias
+ else
+ v = (readu8(src, r0 + x0) + readu8(src, r1 + x0) + bias) // 2
+ bias = 1 - bias
+ end
+ writeu8(out, oy * outW + ox, v)
+ end
+ end
+ return out
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+export type Options = {
+ quality: number, -- 1..100
+ sampling: string, -- "444" | "422" | "420"
+ progressive: boolean,
+ optimize: boolean, -- baseline: optimised Huffman tables (progressive always optimises)
+ gray: boolean,
+ restart: number, -- MCUs per restart interval (0 = none)
+ segments: { { marker: number, data: buffer } }, -- APPn / COM segments after the JFIF header
+ jfif: boolean,
+ density: { unit: number, x: number, y: number }?,
+}
+
+-- run(pixels, w, h, bpp, opts) -> buffer. pixels: w * h * bpp bytes (bpp 4 rgba8 / 3 rgb8 / 1 gray8); the caller
+-- validated sizes (1..65535) and options.
+function Encode.run(px: buffer, w: number, h: number, bpp: number, o: Options): buffer
+ OUT = buffer.create(math.max(1024, w * h // 2))
+ CAP = buffer.len(OUT)
+ OP = 0
+ ACC, NB = 0, 0
+ GATHER = false
+ EOBRUN, BE = 0, 0
+
+ local Y, Cb, Cr = planes(px, w, h, bpp, o.gray)
+ local hs, vs = 1, 1
+ if not o.gray then
+ if o.sampling == "420" then
+ hs, vs = 2, 2
+ elseif o.sampling == "422" then
+ hs, vs = 2, 1
+ end
+ end
+ local mcusX = math.ceil(w / (8 * hs))
+ local mcusY = math.ceil(h / (8 * vs))
+ local qt = { Tables.quant(Tables.LUMA, o.quality), Tables.quant(Tables.CHROMA, o.quality) }
+ local qdiv = {}
+ for t = 1, 2 do
+ local b = buffer.create(128)
+ for i = 1, 64 do
+ writeu16(b, (i - 1) * 2, qt[t][i])
+ end
+ qdiv[t] = b
+ end
+
+ -- components and their quantised coefficients
+ local comps: { Comp } = {}
+ local srcs = if o.gray then { Y } else { Y, Cb :: buffer, Cr :: buffer }
+ for i, src in srcs do
+ local ch, cv = if i == 1 then hs else 1, if i == 1 then vs else 1
+ local cw = math.ceil(w * ch / hs)
+ local chh = math.ceil(h * cv / vs)
+ local bw, bh = math.ceil(cw / 8), math.ceil(chh / 8)
+ local bpl, bpc = mcusX * ch, mcusY * cv
+ local plane, pw, ph = src, w, h
+ if ch < hs or cv < vs then
+ pw, ph = bw * 8, chh
+ plane = downsample(src, w, h, hs // ch, vs // cv, pw, ph)
+ end
+ local coef = buffer.create(bpl * bpc * 128)
+ local c: Comp = {
+ id = i,
+ h = ch,
+ v = cv,
+ tq = if i == 1 then 0 else 1,
+ td = if i == 1 then 0 else 1,
+ ta = if i == 1 then 0 else 1,
+ bw = bw,
+ bh = bh,
+ bpl = bpl,
+ bpc = bpc,
+ coef = coef,
+ last = 0,
+ }
+ local div = qdiv[c.tq + 1]
+ for by = 0, bpc - 1 do
+ for bx = 0, bpl - 1 do
+ local off = (by * bpl + bx) * 128
+ if by < bh and bx < bw then
+ Dct.fdctQuantize(plane, pw, bx * 8, by * 8, pw, ph, div, coef, off)
+ elseif by < bh then
+ writei16(coef, off, readi16(coef, off - 128)) -- right edge: the previous block's DC
+ else
+ -- bottom: the DC of the MCU's last block in the row above
+ local lb = (bx // ch) * ch + ch - 1
+ writei16(coef, off, readi16(coef, ((by - 1) * bpl + lb) * 128))
+ end
+ end
+ end
+ comps[i] = c
+ end
+
+ -- headers
+ byte(0xFF)
+ byte(0xD8)
+ if o.jfif then
+ local d = o.density or { unit = 0, x = 1, y = 1 }
+ byte(0xFF)
+ byte(0xE0)
+ u16be(16)
+ for _, ch in { 0x4A, 0x46, 0x49, 0x46, 0 } do
+ byte(ch)
+ end
+ byte(1)
+ byte(1)
+ byte(d.unit)
+ u16be(d.x)
+ u16be(d.y)
+ byte(0)
+ byte(0)
+ end
+ for _, s in o.segments do
+ local n = buffer.len(s.data)
+ byte(0xFF)
+ byte(s.marker)
+ u16be(n + 2)
+ grow(n)
+ buffer.copy(OUT, OP, s.data, 0, n)
+ OP += n
+ end
+ for t = 1, (if o.gray then 1 else 2) do
+ byte(0xFF)
+ byte(0xDB)
+ u16be(67)
+ byte(t - 1)
+ for k = 0, 63 do
+ byte(qt[t][readu8(ZZ, k) + 1])
+ end
+ end
+ byte(0xFF)
+ byte(if o.progressive then 0xC2 else 0xC0)
+ u16be(8 + 3 * #comps)
+ byte(8)
+ u16be(h)
+ u16be(w)
+ byte(#comps)
+ for _, c in comps do
+ byte(c.id)
+ byte(c.h * 16 + c.v)
+ byte(c.tq)
+ end
+ local ntab = if o.gray then 1 else 2
+
+ local function restartMarker(n: number)
+ flushBits()
+ byte(0xFF)
+ byte(0xD0 + n)
+ end
+
+ if not o.progressive then
+ if o.optimize then
+ GATHER = true
+ for t = 1, ntab do
+ dcFreq[t] = table.create(257, 0)
+ acFreq[t] = table.create(257, 0)
+ end
+ for _, c in comps do
+ c.last = 0
+ end
+ walk(comps, mcusX, mcusY, o.restart, function()
+ for _, c in comps do
+ c.last = 0
+ end
+ end, blockSeq)
+ GATHER = false
+ end
+ for t = 1, ntab do
+ local dcC, dcS, acC, acS
+ if o.optimize then
+ dcC, dcS = optimal(dcFreq[t])
+ acC, acS = optimal(acFreq[t])
+ else
+ local d, a = Tables.DC[t], Tables.AC[t]
+ dcC, dcS, acC, acS = d.counts, d.symbols, a.counts, a.symbols
+ end
+ dcTab[t] = derive(dcC, dcS)
+ acTab[t] = derive(acC, acS)
+ dcFreq[t] = table.create(257, 0)
+ acFreq[t] = table.create(257, 0)
+ -- libjpeg emits each table before the scan in component order: DC0, AC0, DC1, AC1
+ dht(0, t - 1, dcC, dcS)
+ dht(1, t - 1, acC, acS)
+ end
+ if o.restart > 0 then
+ byte(0xFF)
+ byte(0xDD)
+ u16be(4)
+ u16be(o.restart)
+ end
+ sos(comps, 0, 63, 0, 0, false, false)
+ for _, c in comps do
+ c.last = 0
+ end
+ walk(comps, mcusX, mcusY, o.restart, function(n: number)
+ restartMarker(n)
+ for _, c in comps do
+ c.last = 0
+ end
+ end, blockSeq)
+ flushBits()
+ else
+ local script: { ScanSpec }
+ if o.gray then
+ script = {
+ { comps = { 1 }, ss = 0, se = 0, ah = 0, al = 1 },
+ { comps = { 1 }, ss = 1, se = 5, ah = 0, al = 2 },
+ { comps = { 1 }, ss = 6, se = 63, ah = 0, al = 2 },
+ { comps = { 1 }, ss = 1, se = 63, ah = 2, al = 1 },
+ { comps = { 1 }, ss = 0, se = 0, ah = 1, al = 0 },
+ { comps = { 1 }, ss = 1, se = 63, ah = 1, al = 0 },
+ }
+ else
+ script = {
+ { comps = { 1, 2, 3 }, ss = 0, se = 0, ah = 0, al = 1 },
+ { comps = { 1 }, ss = 1, se = 5, ah = 0, al = 2 },
+ { comps = { 3 }, ss = 1, se = 63, ah = 0, al = 1 },
+ { comps = { 2 }, ss = 1, se = 63, ah = 0, al = 1 },
+ { comps = { 1 }, ss = 6, se = 63, ah = 0, al = 2 },
+ { comps = { 1 }, ss = 1, se = 63, ah = 2, al = 1 },
+ { comps = { 1, 2, 3 }, ss = 0, se = 0, ah = 1, al = 0 },
+ { comps = { 3 }, ss = 1, se = 63, ah = 1, al = 0 },
+ { comps = { 2 }, ss = 1, se = 63, ah = 1, al = 0 },
+ { comps = { 1 }, ss = 1, se = 63, ah = 1, al = 0 },
+ }
+ end
+ local driSent = false
+ for _, sc in script do
+ local sComps = {}
+ for _, ci in sc.comps do
+ table.insert(sComps, comps[ci])
+ end
+ local ss, se, ah, al = sc.ss, sc.se, sc.ah, sc.al
+ local isDc = ss == 0
+ local blockFn: (Comp, number) -> ()
+ if isDc and ah == 0 then
+ blockFn = function(c: Comp, off: number)
+ blockDcFirst(c, off, al)
+ end
+ elseif isDc then
+ blockFn = function(c: Comp, off: number)
+ bits(band(readi16(c.coef, off) // 2 ^ al, 1), 1)
+ end
+ elseif ah == 0 then
+ blockFn = function(c: Comp, off: number)
+ blockAcFirst(c, off, ss, se, al)
+ end
+ else
+ blockFn = function(c: Comp, off: number)
+ blockAcRefine(c, off, ss, se, al)
+ end
+ end
+ local function onRestart(n: number)
+ emitEobrun()
+ if not GATHER then
+ restartMarker(n)
+ end
+ for _, c in sComps do
+ c.last = 0
+ end
+ EOBRUN, BE = 0, 0
+ end
+ local function pass()
+ for _, c in sComps do
+ c.last = 0
+ end
+ EOBRUN, BE = 0, 0
+ walk(sComps, mcusX, mcusY, o.restart, onRestart, blockFn)
+ emitEobrun()
+ end
+ -- gather statistics, then emit the optimal tables this scan uses
+ if not (isDc and ah > 0) then
+ GATHER = true
+ for t = 1, ntab do
+ dcFreq[t] = table.create(257, 0)
+ acFreq[t] = table.create(257, 0)
+ end
+ if not isDc then
+ curAcFreq = acFreq[sComps[1].ta + 1]
+ end
+ pass()
+ GATHER = false
+ local sent = {}
+ for _, c in sComps do
+ local slot = if isDc then c.td else c.ta
+ if not sent[slot] then
+ sent[slot] = true
+ local counts, syms = optimal(if isDc then dcFreq[slot + 1] else acFreq[slot + 1])
+ dht(if isDc then 0 else 1, slot, counts, syms)
+ if isDc then
+ dcTab[slot + 1] = derive(counts, syms)
+ else
+ acTab[slot + 1] = derive(counts, syms)
+ end
+ end
+ end
+ if not isDc then
+ curAc = acTab[sComps[1].ta + 1]
+ end
+ end
+ if o.restart > 0 and not driSent then
+ driSent = true
+ byte(0xFF)
+ byte(0xDD)
+ u16be(4)
+ u16be(o.restart)
+ end
+ sos(sComps, ss, se, ah, al, isDc, not isDc or ah > 0) -- DC refinement uses no table: td = 0 (as libjpeg)
+ pass()
+ flushBits()
+ end
+ end
+ byte(0xFF)
+ byte(0xD9)
+ local res = buffer.create(OP)
+ buffer.copy(res, 0, OUT, 0, OP)
+ OUT = buffer.create(0)
+ CAP = 0
+ return res
+end
+
+return Encode
diff --git a/src/Formats/image/jpeg/Scan.luau b/src/Formats/image/jpeg/Scan.luau
new file mode 100644
index 0000000..ec8f45f
--- /dev/null
+++ b/src/Formats/image/jpeg/Scan.luau
@@ -0,0 +1,456 @@
+--!strict
+--!native
+--!optimize 2
+-- image/jpeg/Scan: Huffman-coded scan decoding into quantised DCT coefficients (native; never throws). Absorbed from
+-- jpeg-luau 1.0 src/Jpeg/Scan.luau (same author); unchanged but for this header.
+--
+-- `destuff` copies one scan's entropy-coded bytes into a clean buffer: it drops the stuffed 0x00 after each 0xFF,
+-- records where each RSTn marker fell, and stops at any other marker. The clean buffer is followed by at least
+-- PAD zero bytes, so the bit reader can read 32 bits at any position up to PAD bytes past the end without a
+-- bounds check. `run` checks the position once per MCU, and no MCU (at most 10 blocks, enforced by the parser)
+-- can consume PAD bytes. So every buffer index stays in range, even on garbage data.
+--
+-- The bit reader keeps no state but a bit position: `peek` reads the big-endian 32-bit word that holds it.
+-- Huffman tables (built by `buildTable`) are buffers:
+-- [0, 1024) fast lookup by the next 9 bits: u16 (length << 8) | symbol, 0 = longer code
+-- [1024, 1096) maxcode[l], l = 0..17: u32, one past the last code of length l, left-aligned to 16 bits
+-- [1096, 1168) delta[l]: i32, symbol index = code + delta[l]
+-- [1168, 1424) symbols
+-- [1424, 1426) symbol count
+-- [1428, 3476) fast AC lookup by the next 9 bits: i32 value * 256 + run * 16 + total length, when the code
+-- and its extra bits fit in 9 bits (0 otherwise)
+local readu8, readu16, readu32, readi32, readi16 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi32, buffer.readi16
+local writeu8, writeu16, writeu32, writei32, writei16 = buffer.writeu8, buffer.writeu16, buffer.writeu32, buffer.writei32, buffer.writei16
+local band, bor, lshift, rshift, byteswap = bit32.band, bit32.bor, bit32.lshift, bit32.rshift, bit32.byteswap
+
+local Scan = {}
+
+Scan.PAD = 4096
+Scan.TABLE_SIZE = 3476
+
+local T_MAX = 1024
+local T_DELTA = 1096
+local T_VAL = 1168
+local T_COUNT = 1424
+local T_FASTAC = 1428
+
+-- zigzag index -> natural (row-major) index, padded with 63s so a run past the end stays in range
+local ZZ = buffer.create(80)
+do
+ local i = 0
+ for s = 0, 14 do
+ local lo, hi = math.max(0, s - 7), math.min(s, 7)
+ if s % 2 == 0 then
+ for r = hi, lo, -1 do
+ writeu8(ZZ, i, r * 8 + (s - r))
+ i += 1
+ end
+ else
+ for r = lo, hi do
+ writeu8(ZZ, i, r * 8 + (s - r))
+ i += 1
+ end
+ end
+ end
+ for j = 64, 79 do
+ writeu8(ZZ, j, 63)
+ end
+end
+Scan.ZIGZAG = ZZ
+
+-- Builds a Huffman table from the 16 code-length counts and the symbols (Luau arrays, 1-based). An
+-- over-subscribed table keeps the codes that fit; the rest decode as invalid.
+function Scan.buildTable(counts: { number }, symbols: { number }): buffer
+ local t = buffer.create(Scan.TABLE_SIZE)
+ local code, k = 0, 0
+ local nsym = #symbols
+ local codes, sizes = {}, {}
+ local broken = false
+ for l = 1, 16 do
+ writei32(t, T_DELTA + l * 4, k - code)
+ local n = counts[l] or 0
+ for _ = 1, n do
+ if broken or code >= lshift(1, l) or k >= nsym or k >= 256 then
+ broken = true
+ break
+ end
+ k += 1
+ codes[k] = code
+ sizes[k] = l
+ code += 1
+ end
+ writeu32(t, T_MAX + l * 4, if broken then 0 else lshift(code, 16 - l))
+ code *= 2
+ end
+ writeu32(t, T_MAX + 17 * 4, 0xFFFFFFFF)
+ for i = 1, k do
+ writeu8(t, T_VAL + i - 1, symbols[i])
+ end
+ writeu16(t, T_COUNT, k)
+ -- fast lookups
+ for i = 1, k do
+ local l = sizes[i]
+ if l <= 9 then
+ local sym = symbols[i]
+ local base = lshift(codes[i], 9 - l)
+ for j = 0, lshift(1, 9 - l) - 1 do
+ local idx = base + j
+ writeu16(t, idx * 2, l * 256 + sym)
+ local r, s = rshift(sym, 4), band(sym, 15)
+ if s ~= 0 and l + s <= 9 then
+ local v = band(rshift(idx, 9 - l - s), lshift(1, s) - 1)
+ if v < lshift(1, s - 1) then
+ v = v - lshift(1, s) + 1
+ end
+ writei32(t, T_FASTAC + idx * 4, v * 256 + r * 16 + l + s)
+ end
+ end
+ end
+ end
+ return t
+end
+
+-- Copies the entropy-coded data at src[pos..n) into dst (at least n - pos + PAD bytes): byte stuffing removed,
+-- RSTn offsets (in dst) stored in rst[1..]. Returns the source position of the marker that ended the scan (or n),
+-- the clean length, and the RST count. The PAD bytes after the clean data are zeroed.
+function Scan.destuff(src: buffer, pos: number, n: number, dst: buffer, rst: { number }): (number, number, number)
+ local o, nr = 0, 0
+ while pos < n do
+ local b = readu8(src, pos)
+ if b ~= 0xFF then
+ writeu8(dst, o, b)
+ o += 1
+ pos += 1
+ else
+ local q = pos + 1
+ while q < n and readu8(src, q) == 0xFF do
+ q += 1
+ end
+ if q >= n then
+ pos = n
+ break
+ end
+ local m = readu8(src, q)
+ if m == 0 then
+ writeu8(dst, o, 0xFF)
+ o += 1
+ pos = q + 1
+ elseif m >= 0xD0 and m <= 0xD7 then
+ nr += 1
+ rst[nr] = o
+ pos = q + 1
+ else
+ pos = q - 1
+ break
+ end
+ end
+ end
+ buffer.fill(dst, o, 0, Scan.PAD)
+ return pos, o, nr
+end
+
+local function huff(d: buffer, pos: number, t: buffer): (number, number)
+ local w = lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7))
+ local f = readu16(t, rshift(w, 23) * 2)
+ if f ~= 0 then
+ return band(f, 255), pos + rshift(f, 8)
+ end
+ local c = rshift(w, 16)
+ local l = 10
+ while c >= readu32(t, T_MAX + l * 4) do
+ l += 1
+ end
+ if l > 16 then
+ return 0, pos + 16 -- invalid code
+ end
+ local idx = rshift(c, 16 - l) + readi32(t, T_DELTA + l * 4)
+ if idx < 0 or idx >= readu16(t, T_COUNT) then
+ return 0, pos + l
+ end
+ return readu8(t, T_VAL + idx), pos + l
+end
+
+-- the next s bits (1 <= s <= 16) as an unsigned number
+local function bits(d: buffer, pos: number, s: number): number
+ return rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 32 - s)
+end
+
+local function extend(v: number, s: number): number
+ if v < lshift(1, s - 1) then
+ return v - lshift(1, s) + 1
+ end
+ return v
+end
+
+-- sequential (baseline / extended) block: returns pos, DC predictor
+local function blockSeq(d: buffer, pos: number, coef: buffer, off: number, dct: buffer, act: buffer, pred: number): (number, number)
+ local s
+ s, pos = huff(d, pos, dct)
+ if s ~= 0 then
+ if s > 16 then
+ s = 16
+ end
+ pred += extend(bits(d, pos, s), s)
+ pos += s
+ end
+ writei16(coef, off, pred)
+ local k = 1
+ while k < 64 do
+ local w = lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7))
+ local fa = readi32(act, T_FASTAC + rshift(w, 23) * 4)
+ if fa ~= 0 then
+ local low = fa % 256
+ k += low // 16
+ pos += low % 16
+ if k > 63 then
+ break
+ end
+ writei16(coef, off + readu8(ZZ, k) * 2, fa // 256)
+ k += 1
+ else
+ local rs
+ rs, pos = huff(d, pos, act)
+ local r, sz = rshift(rs, 4), band(rs, 15)
+ if sz == 0 then
+ if r ~= 15 then
+ break
+ end
+ k += 16
+ else
+ k += r
+ if k > 63 then
+ break
+ end
+ writei16(coef, off + readu8(ZZ, k) * 2, extend(bits(d, pos, sz), sz))
+ pos += sz
+ k += 1
+ end
+ end
+ end
+ return pos, pred
+end
+
+local function blockDcFirst(d: buffer, pos: number, coef: buffer, off: number, dct: buffer, pred: number, al: number): (number, number)
+ local s
+ s, pos = huff(d, pos, dct)
+ if s ~= 0 then
+ if s > 16 then
+ s = 16
+ end
+ pred += extend(bits(d, pos, s), s)
+ pos += s
+ end
+ writei16(coef, off, pred * lshift(1, al))
+ return pos, pred
+end
+
+local function blockAcFirst(d: buffer, pos: number, coef: buffer, off: number, act: buffer, ss: number, se: number, al: number, eobrun: number): (number, number)
+ if eobrun > 0 then
+ return pos, eobrun - 1
+ end
+ local mul = lshift(1, al)
+ local k = ss
+ while k <= se do
+ local w = lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7))
+ local fa = readi32(act, T_FASTAC + rshift(w, 23) * 4)
+ if fa ~= 0 then
+ local low = fa % 256
+ k += low // 16
+ pos += low % 16
+ if k > se then
+ break
+ end
+ writei16(coef, off + readu8(ZZ, k) * 2, (fa // 256) * mul)
+ k += 1
+ else
+ local rs
+ rs, pos = huff(d, pos, act)
+ local r, s = rshift(rs, 4), band(rs, 15)
+ if s == 0 then
+ if r < 15 then
+ eobrun = lshift(1, r) - 1
+ if r > 0 then
+ eobrun += bits(d, pos, r)
+ pos += r
+ end
+ break
+ end
+ k += 16
+ else
+ k += r
+ if k > se then
+ break
+ end
+ writei16(coef, off + readu8(ZZ, k) * 2, extend(bits(d, pos, s), s) * mul)
+ pos += s
+ k += 1
+ end
+ end
+ end
+ return pos, eobrun
+end
+
+-- successive-approximation refinement of AC coefficients ss..se (as stb_image / libjpeg decode_mcu_AC_refine)
+local function blockAcRefine(d: buffer, pos: number, coef: buffer, off: number, act: buffer, ss: number, se: number, al: number, eobrun: number): (number, number)
+ local bit = lshift(1, al)
+ if eobrun > 0 then
+ for k = ss, se do
+ local o = off + readu8(ZZ, k) * 2
+ local p = readi16(coef, o)
+ if p ~= 0 then
+ local b = rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 31)
+ pos += 1
+ if b ~= 0 and band(p, bit) == 0 then
+ writei16(coef, o, if p > 0 then p + bit else p - bit)
+ end
+ end
+ end
+ return pos, eobrun - 1
+ end
+ local k = ss
+ while k <= se do
+ local rs
+ rs, pos = huff(d, pos, act)
+ local s, r = band(rs, 15), rshift(rs, 4)
+ local val = 0
+ if s == 0 then
+ if r < 15 then
+ eobrun = lshift(1, r) - 1
+ if r > 0 then
+ eobrun += bits(d, pos, r)
+ pos += r
+ end
+ r = 64 -- the rest of the block only refines
+ end
+ else
+ -- s must be 1; anything else is corrupt and treated as 1
+ local b = rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 31)
+ pos += 1
+ val = if b ~= 0 then bit else -bit
+ end
+ while k <= se do
+ local o = off + readu8(ZZ, k) * 2
+ k += 1
+ local p = readi16(coef, o)
+ if p ~= 0 then
+ local b = rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 31)
+ pos += 1
+ if b ~= 0 and band(p, bit) == 0 then
+ writei16(coef, o, if p > 0 then p + bit else p - bit)
+ end
+ else
+ if r == 0 then
+ if val ~= 0 then
+ writei16(coef, o, val)
+ end
+ break
+ end
+ r -= 1
+ end
+ end
+ end
+ -- an EOB run that started in this block counts it already (eobrun = run length - 1)
+ return pos, eobrun
+end
+
+export type ScanComp = {
+ coef: buffer, -- i16 coefficients, 64 per block in natural order, blocks row-major on a bpl-wide grid
+ bpl: number,
+ h: number,
+ v: number,
+ bw: number, -- blocks across / down the component itself (non-interleaved scans)
+ bh: number,
+ dct: buffer?,
+ act: buffer?,
+ pred: number,
+}
+
+export type ScanParams = {
+ comps: { ScanComp },
+ mcusX: number,
+ mcusY: number,
+ ri: number, -- restart interval in MCUs (0 = none)
+ mode: number, -- 0 sequential, 1 DC first, 2 DC refine, 3 AC first, 4 AC refine
+ ss: number,
+ se: number,
+ al: number,
+}
+
+-- Decodes one scan from the clean data d (cleanLen bytes, then PAD zeros). Returns the final bit position and
+-- whether the data ran out (or overran) before the last MCU.
+function Scan.run(d: buffer, cleanLen: number, rst: { number }, nrst: number, P: ScanParams): (number, boolean)
+ local comps = P.comps
+ local nc = #comps
+ local mode, ss, se, al, ri = P.mode, P.ss, P.se, P.al, P.ri
+ local endBits = cleanLen * 8
+ local units, ux
+ if nc == 1 then
+ ux = comps[1].bw
+ units = ux * comps[1].bh
+ else
+ ux = P.mcusX
+ units = ux * P.mcusY
+ end
+ for i = 1, nc do
+ comps[i].pred = 0
+ end
+ local pos, eobrun, rstIdx = 0, 0, 0
+ local truncated, skipping = false, false
+ local bit = lshift(1, al)
+ for u = 0, units - 1 do
+ if ri > 0 and u > 0 and u % ri == 0 then
+ rstIdx += 1
+ if rstIdx <= nrst then
+ pos = rst[rstIdx] * 8
+ skipping = false
+ end
+ for i = 1, nc do
+ comps[i].pred = 0
+ end
+ eobrun = 0
+ end
+ if pos > endBits then
+ truncated = true
+ if ri == 0 or rstIdx >= nrst then
+ break
+ end
+ skipping = true
+ end
+ if not skipping then
+ local my, mx = u // ux, u % ux
+ for ci = 1, nc do
+ local c = comps[ci]
+ local bh, bw, by0, bx0
+ if nc == 1 then
+ bh, bw, by0, bx0 = 1, 1, my, mx
+ else
+ bh, bw, by0, bx0 = c.v, c.h, my * c.v, mx * c.h
+ end
+ local coef, bpl = c.coef, c.bpl
+ for by = by0, by0 + bh - 1 do
+ for bx = bx0, bx0 + bw - 1 do
+ local off = (by * bpl + bx) * 128
+ if mode == 0 then
+ pos, c.pred = blockSeq(d, pos, coef, off, c.dct :: buffer, c.act :: buffer, c.pred)
+ elseif mode == 1 then
+ pos, c.pred = blockDcFirst(d, pos, coef, off, c.dct :: buffer, c.pred, al)
+ elseif mode == 2 then
+ local b = rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 31)
+ pos += 1
+ if b ~= 0 then
+ writei16(coef, off, bor(readi16(coef, off), bit))
+ end
+ elseif mode == 3 then
+ pos, eobrun = blockAcFirst(d, pos, coef, off, c.act :: buffer, ss, se, al, eobrun)
+ else
+ pos, eobrun = blockAcRefine(d, pos, coef, off, c.act :: buffer, ss, se, al, eobrun)
+ end
+ end
+ end
+ end
+ end
+ end
+ return pos, truncated
+end
+
+return Scan
diff --git a/src/Formats/image/jpeg/Tables.luau b/src/Formats/image/jpeg/Tables.luau
new file mode 100644
index 0000000..e524d54
--- /dev/null
+++ b/src/Formats/image/jpeg/Tables.luau
@@ -0,0 +1,77 @@
+--!strict
+-- image/jpeg/Tables: the standard tables of ITU T.81 annex K: the example Huffman tables (K.3, which every baseline
+-- encoder without optimisation writes and Motion-JPEG frames leave out) and the luminance / chrominance quantisation
+-- tables (K.1) with libjpeg's quality scaling (jcparam.c jpeg_quality_scaling / jpeg_add_quant_table).
+local Tables = {}
+
+local function range(t: { number }, a: number, b: number)
+ for v = a, b do
+ table.insert(t, v)
+ end
+end
+
+-- { counts (16 code-length counts), symbols } per table: dc[1] luma, dc[2] chroma, ac[1], ac[2]
+local dcl = { 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 }
+local dcc = { 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 }
+local dcv = {}
+range(dcv, 0, 11)
+local acl = { 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d }
+local aclv = {
+ 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
+ 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
+ 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
+ 0x29, 0x2a,
+}
+range(aclv, 0x34, 0x3a)
+for hi = 4, 8 do
+ range(aclv, hi * 16 + 3, hi * 16 + 10)
+end
+for hi = 9, 13 do
+ range(aclv, hi * 16 + 2, hi * 16 + 10)
+end
+range(aclv, 0xe1, 0xea)
+range(aclv, 0xf1, 0xfa)
+local acc = { 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 }
+local accv = {
+ 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
+ 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
+ 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
+ 0x27, 0x28, 0x29, 0x2a,
+}
+range(accv, 0x35, 0x3a)
+for hi = 4, 7 do
+ range(accv, hi * 16 + 3, hi * 16 + 10)
+end
+for hi = 8, 14 do
+ range(accv, hi * 16 + 2, hi * 16 + 10)
+end
+range(accv, 0xf2, 0xfa)
+
+export type Spec = { counts: { number }, symbols: { number } }
+Tables.DC = { { counts = dcl, symbols = dcv }, { counts = dcc, symbols = dcv } } :: { Spec }
+Tables.AC = { { counts = acl, symbols = aclv }, { counts = acc, symbols = accv } } :: { Spec }
+
+-- K.1, natural (row-major) order
+Tables.LUMA = {
+ 16, 11, 10, 16, 24, 40, 51, 61, 12, 12, 14, 19, 26, 58, 60, 55, 14, 13, 16, 24, 40, 57, 69, 56, 14, 17, 22, 29,
+ 51, 87, 80, 62, 18, 22, 37, 56, 68, 109, 103, 77, 24, 35, 55, 64, 81, 104, 113, 92, 49, 64, 78, 87, 103, 121,
+ 120, 101, 72, 92, 95, 98, 112, 100, 103, 99,
+}
+Tables.CHROMA = {
+ 17, 18, 24, 47, 99, 99, 99, 99, 18, 21, 26, 66, 99, 99, 99, 99, 24, 26, 56, 99, 99, 99, 99, 99, 47, 66, 99, 99,
+ 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99,
+ 99, 99, 99, 99, 99, 99, 99, 99,
+}
+
+-- quant(base, quality) -> 64 values (natural order) for quality 1..100, clamped to 1..255 (baseline)
+function Tables.quant(base: { number }, quality: number): { number }
+ local q = math.clamp(math.floor(quality), 1, 100)
+ local scale = if q < 50 then 5000 // q else 200 - q * 2
+ local out = table.create(64, 1)
+ for i = 1, 64 do
+ out[i] = math.clamp((base[i] * scale + 50) // 100, 1, 255)
+ end
+ return out
+end
+
+return Tables
diff --git a/src/Formats/image/jpeg/init.luau b/src/Formats/image/jpeg/init.luau
new file mode 100644
index 0000000..f6c3077
--- /dev/null
+++ b/src/Formats/image/jpeg/init.luau
@@ -0,0 +1,285 @@
+--!strict
+-- image/jpeg: JPEG / JFIF / EXIF (ITU T.81). Absorbed from jpeg-luau 1.0 (same author: the Huffman decoder, IDCTs,
+-- upsampling and colour conversion, bit-exact with libjpeg-turbo's djpeg) and extended with arithmetic coding, meta
+-- (EXIF, ICC, comments, density) and an encoder. IJG-derived parts: licenses/libjpeg-turbo-LICENSE.md.
+-- Decode: baseline, extended and progressive frames, Huffman or arithmetic coded (SOF0/1/2/9/10), 8 and 12-bit
+-- samples, 1, 3 or 4 components with any sampling factors 1..4, restart intervals (resynchronising after corrupt
+-- data), grey / YCbCr / RGB / CMYK / YCCK (Adobe APP14), scaled decodes (opts.scale = 2, 4, 8 through libjpeg's
+-- reduced IDCTs), EXIF orientation reported in meta.orientation and applied with opts.orient. Truncated or corrupt
+-- scans decode as far as they go (meta.truncated = true).
+-- Encode: baseline (standard or optimised Huffman tables) and progressive (libjpeg's simple progression), grey or
+-- YCbCr 4:4:4 / 4:2:2 / 4:2:0, libjpeg quality tables, restart intervals, EXIF / ICC / comment segments from meta;
+-- byte-identical to cjpeg for the same settings.
+-- Not supported: lossless (SOF3) and hierarchical frames, DNL, 2-component images, ICC colour management, 12-bit
+-- or CMYK encoding.
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Types = require("@formats/Types")
+local Decode = require("@formats/image/jpeg/Decode")
+local Encode = require("@formats/image/jpeg/Encode")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Jpeg = {
+ name = "jpeg",
+ category = "image",
+ extensions = { "jpg", "jpeg", "jpe", "jfif" },
+ mime = { "image/jpeg" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/Dct" },
+ caps = { decode = true, encode = true, lossy = true, alpha = false, depths = { 8, 12 }, progressive = true, arithmetic = true },
+}
+
+-- ------------------------------------------------------------------------------------------------ types
+export type DecodeOptions = {
+ scale: number?, -- 1 (default), 2, 4 or 8: decode at ceil(size / scale) (8 reads the DC coefficients only)
+ orient: boolean?, -- apply the EXIF orientation (default false: reported in meta.orientation only)
+ native: boolean?, -- grey files decode to gray8 (default false: rgba8)
+ maxPixels: number?, -- refuse larger images (default 2^26)
+}
+export type EncodeOptions = {
+ quality: number?, -- 1..100 (default 90), libjpeg's scaling of the T.81 annex K tables
+ subsampling: ("420" | "422" | "444")?, -- chroma subsampling (default "420")
+ progressive: boolean?, -- default false
+ optimize: boolean?, -- optimised Huffman tables for baseline files (default false; progressive always optimises)
+ gray: boolean?, -- a one-component file (default: true for gray8 images)
+ restart: number?, -- restart interval in MCUs (default 0 = none)
+ jfif: boolean?, -- write the JFIF APP0 header (default true)
+ meta: boolean?, -- write meta.exif (APP1), meta.icc (APP2) and meta.text.comment (COM) (default true)
+}
+
+export type Info = {
+ width: number,
+ height: number,
+ components: number,
+ progressive: boolean,
+ arithmetic: boolean,
+ precision: number,
+ colorSpace: string,
+ sampling: { { number } }, -- { h, v } per component
+ orientation: number,
+ adobe: number?,
+ jfif: boolean,
+}
+
+-- ------------------------------------------------------------------------------------------------ constants
+local CODES = { corrupt = Err.CORRUPT, unsupported = Err.UNSUPPORTED, limit = Err.LIMIT, truncated = Err.TRUNCATED, arg = Err.ARG }
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Jpeg.sniff(r: Bytes.Reader): number
+ local s = r:peek(3)
+ return if s == "\255\216\255" then 1 else 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+local function parse(r: Bytes.Reader, opts: any, headerOnly: boolean): (Decode.State?, Err.Err?)
+ local ok, st, code, msg = pcall(Decode.parse, r.buf, r.base, r.limit, opts, headerOnly)
+ if not ok then
+ return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(st))
+ end
+ if not st then
+ return nil, Err.new(CODES[code :: string] or Err.CORRUPT, msg or "decode failed")
+ end
+ return st, nil
+end
+
+-- info(r) -> Info | nil, Err (reads the headers up to the frame header)
+function Jpeg.info(r: Bytes.Reader): (Info?, Err.Err?)
+ local st, err = parse(r, nil, true)
+ if not st then
+ return nil, err
+ end
+ local f = st.frame
+ local sampling = {}
+ for _, c in f.comps do
+ table.insert(sampling, { c.h, c.v })
+ end
+ return {
+ width = f.width,
+ height = f.height,
+ components = #f.comps,
+ progressive = f.progressive,
+ arithmetic = f.arithmetic,
+ precision = f.precision,
+ colorSpace = Decode.colorSpaceOf(f, st.adobe, st.jfif),
+ sampling = sampling,
+ orientation = st.orientation,
+ adobe = st.adobe,
+ jfif = st.jfif,
+ },
+ nil
+end
+
+-- the EXIF orientation applied to rgba8 pixels: buffer, width, height
+local function orient(px: buffer, w: number, h: number, o: number): (buffer, number, number)
+ if o <= 1 or o > 8 then
+ return px, w, h
+ end
+ local swap = o >= 5
+ local ow, oh = if swap then h else w, if swap then w else h
+ local out = buffer.create(ow * oh * 4)
+ local readu32, writeu32 = buffer.readu32, buffer.writeu32
+ for y = 0, oh - 1 do
+ for x = 0, ow - 1 do
+ local col, row
+ if o == 2 then
+ col, row = w - 1 - x, y
+ elseif o == 3 then
+ col, row = w - 1 - x, h - 1 - y
+ elseif o == 4 then
+ col, row = x, h - 1 - y
+ elseif o == 5 then
+ col, row = y, x
+ elseif o == 6 then
+ col, row = y, h - 1 - x
+ elseif o == 7 then
+ col, row = w - 1 - y, h - 1 - x
+ else
+ col, row = w - 1 - y, x
+ end
+ writeu32(out, (y * ow + x) * 4, readu32(px, (row * w + col) * 4))
+ end
+ end
+ return out, ow, oh
+end
+
+function Jpeg.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
+ local st, err = parse(r, opts, false)
+ if not st then
+ return nil, err
+ end
+ local ok, w, h, px, space = pcall(Decode.output, st :: Decode.State)
+ if not ok then
+ return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(w))
+ end
+ if not w then
+ return nil, Err.new(CODES[h :: string] or Err.CORRUPT, tostring(px))
+ end
+ local orientation = st.orientation
+ if opts and opts.orient then
+ px, w, h = orient(px, w, h, orientation)
+ end
+ local img = Types.Image.new(1, 1)
+ img.width, img.height, img.pixels = w, h, px
+ if opts and opts.native and space == "gray" then
+ local g = buffer.create(w * h)
+ for i = 0, w * h - 1 do
+ buffer.writeu8(g, i, buffer.readu8(px, i * 4))
+ end
+ img.pixels, img.format = g, "gray8"
+ end
+ local f = st.frame
+ local sampling = {}
+ for _, c in f.comps do
+ table.insert(sampling, { c.h, c.v })
+ end
+ img.meta.orientation = orientation
+ img.meta.oriented = (opts and opts.orient) or false
+ img.meta.exif = st.exif
+ img.meta.icc = st.icc
+ if #st.comments > 0 then
+ img.meta.text = { comment = table.concat(st.comments, "\n") }
+ end
+ if st.density and st.density.unit > 0 and st.density.x > 0 and st.density.y > 0 then
+ local k = if st.density.unit == 2 then 2.54 else 1
+ img.meta.dpi = { x = st.density.x * k, y = st.density.y * k }
+ end
+ img.meta.truncated = st.truncated
+ img.meta.source = {
+ format = "jpeg",
+ bitDepth = f.precision,
+ colorType = space,
+ components = #f.comps,
+ progressive = f.progressive,
+ arithmetic = f.arithmetic,
+ sampling = sampling,
+ scale = st.scale,
+ adobe = st.adobe,
+ jfif = st.jfif,
+ }
+ return img, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+local BPP = { rgba8 = 4, rgb8 = 3, gray8 = 1 }
+
+function Jpeg.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
+ if type(img) ~= "table" or type(img.pixels) ~= "buffer" or type(img.width) ~= "number" or type(img.height) ~= "number" then
+ return nil, Err.new(Err.ARG, "needs an Image")
+ end
+ local bpp = BPP[img.format]
+ if not bpp then
+ return nil, Err.new(Err.ARG, "needs an rgba8, rgb8 or gray8 Image (got " .. tostring(img.format) .. ")")
+ end
+ local w, h = img.width, img.height
+ if w < 1 or h < 1 or w > 65535 or h > 65535 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < w * h * bpp then
+ return nil, Err.new(Err.ARG, "bad image size or pixel buffer (1..65535 per side)")
+ end
+ local o: any = opts or {}
+ local quality = o.quality or 90
+ if type(quality) ~= "number" or quality < 1 or quality > 100 then
+ return nil, Err.new(Err.ARG, "quality must be 1..100")
+ end
+ local sub = o.subsampling or "420"
+ if sub ~= "420" and sub ~= "422" and sub ~= "444" then
+ return nil, Err.new(Err.ARG, "subsampling must be \"420\", \"422\" or \"444\"")
+ end
+ local restart = o.restart or 0
+ if type(restart) ~= "number" or restart < 0 or restart > 65535 or restart % 1 ~= 0 then
+ return nil, Err.new(Err.ARG, "restart must be 0..65535 MCUs")
+ end
+ local gray = o.gray
+ if gray == nil then
+ gray = img.format == "gray8"
+ end
+ local segments = {}
+ local meta = img.meta or {}
+ if o.meta ~= false then
+ if type(meta.exif) == "buffer" and buffer.len(meta.exif) <= 65527 then
+ local d = buffer.create(buffer.len(meta.exif) + 6)
+ buffer.writestring(d, 0, "Exif\0\0")
+ buffer.copy(d, 6, meta.exif)
+ table.insert(segments, { marker = 0xE1, data = d })
+ end
+ if type(meta.icc) == "buffer" then
+ local icc = meta.icc :: buffer
+ local n = buffer.len(icc)
+ local chunk = 65519
+ local count = math.max(1, math.ceil(n / chunk))
+ if count <= 255 then
+ for i = 1, count do
+ local a = (i - 1) * chunk
+ local l = math.min(chunk, n - a)
+ local d = buffer.create(l + 14)
+ buffer.writestring(d, 0, "ICC_PROFILE\0")
+ buffer.writeu8(d, 12, i)
+ buffer.writeu8(d, 13, count)
+ buffer.copy(d, 14, icc, a, l)
+ table.insert(segments, { marker = 0xE2, data = d })
+ end
+ end
+ end
+ local text = meta.text
+ if type(text) == "table" and type(text.comment) == "string" and #text.comment <= 65533 then
+ table.insert(segments, { marker = 0xFE, data = buffer.fromstring(text.comment) })
+ end
+ end
+ local density = nil
+ if type(meta.dpi) == "table" and type(meta.dpi.x) == "number" and type(meta.dpi.y) == "number" then
+ density = { unit = 1, x = math.clamp(math.floor(meta.dpi.x + 0.5), 1, 65535), y = math.clamp(math.floor(meta.dpi.y + 0.5), 1, 65535) }
+ end
+ local out = Encode.run(img.pixels, w, h, bpp, {
+ quality = quality,
+ sampling = sub,
+ progressive = o.progressive == true,
+ optimize = o.optimize == true,
+ gray = gray,
+ restart = restart,
+ segments = segments,
+ jfif = o.jfif ~= false,
+ density = density,
+ })
+ return out, nil
+end
+
+return Jpeg
diff --git a/src/Formats/image/pnm/Codec.luau b/src/Formats/image/pnm/Codec.luau
new file mode 100644
index 0000000..5bc6285
--- /dev/null
+++ b/src/Formats/image/pnm/Codec.luau
@@ -0,0 +1,289 @@
+--!strict
+--!native
+--!optimize 2
+-- image/pnm/Codec: the Netpbm sample loops (native; never throws). Written from the Netpbm format pages (pbm, pgm,
+-- ppm, pam, pfm). Reading: binary 8 / 16-bit samples, ASCII samples (P1 digits may run together), P4 bit rows, PFM
+-- floats (either byte order, bottom-to-top rows); packing samples into a Types pixel format with maxval scaling.
+-- Writing: samples of any pixel format extracted at 1..4 channels and 8 or 16 bits. Every read is bounds-checked.
+local readu8, writeu8, readu16, writeu16 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16
+local readf32, writef32, readu32, writeu32 = buffer.readf32, buffer.writef32, buffer.readu32, buffer.writeu32
+local byteswap = bit32.byteswap
+
+local Codec = {}
+
+-- readSamples(b, p, limit, count, mode, out) -> true | false, message: count raw values into out (u16 each).
+-- mode 1 = binary 8-bit, 2 = binary 16-bit big-endian, 3 = ASCII decimal, 4 = ASCII P1 (single digits)
+function Codec.readSamples(b: buffer, p: number, limit: number, count: number, mode: number, out: buffer): (boolean, string?)
+ if mode == 1 then
+ if p + count > limit then
+ return false, "truncated"
+ end
+ for i = 0, count - 1 do
+ writeu16(out, i * 2, readu8(b, p + i))
+ end
+ return true, nil
+ elseif mode == 2 then
+ if p + count * 2 > limit then
+ return false, "truncated"
+ end
+ for i = 0, count - 1 do
+ writeu16(out, i * 2, readu8(b, p + i * 2) * 256 + readu8(b, p + i * 2 + 1))
+ end
+ return true, nil
+ end
+ local i = 0
+ while i < count do
+ -- skip whitespace and comments
+ while p < limit do
+ local c = readu8(b, p)
+ if c == 35 then -- '#'
+ while p < limit and readu8(b, p) ~= 10 and readu8(b, p) ~= 13 do
+ p += 1
+ end
+ elseif c == 32 or (c >= 9 and c <= 13) then
+ p += 1
+ else
+ break
+ end
+ end
+ if p >= limit then
+ return false, "truncated"
+ end
+ local c = readu8(b, p)
+ if c < 48 or c > 57 then
+ return false, "bad ASCII sample"
+ end
+ if mode == 4 then
+ writeu16(out, i * 2, c - 48)
+ p += 1
+ else
+ local v = 0
+ while p < limit do
+ local d = readu8(b, p)
+ if d < 48 or d > 57 then
+ break
+ end
+ v = math.min(v * 10 + d - 48, 65535)
+ p += 1
+ end
+ writeu16(out, i * 2, v)
+ end
+ i += 1
+ end
+ return true, nil
+end
+
+-- readBits(b, p, limit, w, h, out) -> ok, message: P4 rows (MSB first, rows padded to bytes) as u16 0 / 1 values
+function Codec.readBits(b: buffer, p: number, limit: number, w: number, h: number, out: buffer): (boolean, string?)
+ local rowBytes = (w + 7) // 8
+ if p + rowBytes * h > limit then
+ return false, "truncated"
+ end
+ for y = 0, h - 1 do
+ local r = p + y * rowBytes
+ for x = 0, w - 1 do
+ local byte = readu8(b, r + x // 8)
+ writeu16(out, (y * w + x) * 2, (byte // 2 ^ (7 - x % 8)) % 2)
+ end
+ end
+ return true, nil
+end
+
+-- format codes for pack / extract
+Codec.RGBA8, Codec.RGB8, Codec.GRAY8, Codec.GRAYA8, Codec.RGBA16, Codec.GRAY16, Codec.RGBAF32 = 0, 1, 2, 3, 4, 5, 6
+
+-- pack(samples, n, ch, maxval, invert, fmt, dst): n pixels of ch raw samples (u16, 0..maxval; invert: 1 - v for
+-- PBM bits) into dst in pixel format fmt, scaled to the format's range (8-bit: round(v * 255 / maxval))
+function Codec.pack(s: buffer, n: number, ch: number, maxval: number, invert: boolean, fmt: number, dst: buffer)
+ local wide = fmt == 4 or fmt == 5
+ local top = if wide then 65535 else 255
+ local half = maxval // 2
+ local function get(i: number): number
+ local v = math.min(readu16(s, i * 2), maxval)
+ if invert then
+ v = maxval - v
+ end
+ if maxval == top then
+ return v
+ end
+ return (v * top + half) // maxval
+ end
+ for i = 0, n - 1 do
+ local q = i * ch
+ local r, g, b, a
+ if ch == 1 then
+ r = get(q)
+ g, b, a = r, r, top
+ elseif ch == 2 then
+ r = get(q)
+ g, b, a = r, r, get(q + 1)
+ elseif ch == 3 then
+ r, g, b, a = get(q), get(q + 1), get(q + 2), top
+ else
+ r, g, b, a = get(q), get(q + 1), get(q + 2), get(q + 3)
+ end
+ if fmt == 0 then
+ writeu32(dst, i * 4, r + g * 256 + b * 65536 + a * 16777216)
+ elseif fmt == 1 then
+ writeu8(dst, i * 3, r)
+ writeu8(dst, i * 3 + 1, g)
+ writeu8(dst, i * 3 + 2, b)
+ elseif fmt == 2 then
+ writeu8(dst, i, r)
+ elseif fmt == 3 then
+ writeu8(dst, i * 2, r)
+ writeu8(dst, i * 2 + 1, a)
+ elseif fmt == 4 then
+ writeu16(dst, i * 8, r)
+ writeu16(dst, i * 8 + 2, g)
+ writeu16(dst, i * 8 + 4, b)
+ writeu16(dst, i * 8 + 6, a)
+ elseif fmt == 5 then
+ writeu16(dst, i * 2, r)
+ end
+ end
+end
+
+-- readFloats(b, p, limit, w, h, ch, le, dst) -> ok, message: PFM rows (bottom-to-top) into rgbaf32 dst
+function Codec.readFloats(b: buffer, p: number, limit: number, w: number, h: number, ch: number, le: boolean, dst: buffer): (boolean, string?)
+ if p + w * h * ch * 4 > limit then
+ return false, "truncated"
+ end
+ local tmp = buffer.create(4)
+ for y = 0, h - 1 do
+ local row = p + (h - 1 - y) * w * ch * 4
+ for x = 0, w - 1 do
+ local o = (y * w + x) * 16
+ for c = 0, ch - 1 do
+ local v
+ if le then
+ v = readf32(b, row + (x * ch + c) * 4)
+ else
+ writeu32(tmp, 0, byteswap(readu32(b, row + (x * ch + c) * 4)))
+ v = readf32(tmp, 0)
+ end
+ writef32(dst, o + c * 4, v)
+ end
+ if ch == 1 then
+ local v = readf32(dst, o)
+ writef32(dst, o + 4, v)
+ writef32(dst, o + 8, v)
+ end
+ writef32(dst, o + 12, 1)
+ end
+ end
+ return true, nil
+end
+
+local function f(v: number): number
+ if v ~= v then
+ return 0
+ end
+ return math.floor(math.clamp(v, 0, 1) * 65535 + 0.5)
+end
+
+-- extract(px, fmt, n, ch, wide) -> u16 samples: n pixels of format fmt as ch channels (1 grey (Rec. 601 luma for
+-- colour sources, Pillow's L = (299 R + 587 G + 114 B) / 1000), 2 grey + alpha, 3 RGB, 4 RGBA), 16-bit if wide
+function Codec.extract(px: buffer, fmt: number, n: number, ch: number, wide: boolean): buffer
+ local out = buffer.create(n * ch * 2)
+ local srcWide = fmt == 4 or fmt == 5
+ local isGray = fmt == 2 or fmt == 3 or fmt == 5
+ for i = 0, n - 1 do
+ local r, g, b, a
+ if fmt == 0 then
+ r, g, b, a = readu8(px, i * 4), readu8(px, i * 4 + 1), readu8(px, i * 4 + 2), readu8(px, i * 4 + 3)
+ elseif fmt == 1 then
+ r, g, b, a = readu8(px, i * 3), readu8(px, i * 3 + 1), readu8(px, i * 3 + 2), 255
+ elseif fmt == 2 then
+ r = readu8(px, i)
+ g, b, a = r, r, 255
+ elseif fmt == 3 then
+ r, a = readu8(px, i * 2), readu8(px, i * 2 + 1)
+ g, b = r, r
+ elseif fmt == 4 then
+ r, g, b, a = readu16(px, i * 8), readu16(px, i * 8 + 2), readu16(px, i * 8 + 4), readu16(px, i * 8 + 6)
+ elseif fmt == 5 then
+ r = readu16(px, i * 2)
+ g, b, a = r, r, 65535
+ else
+ r, g, b, a = f(readf32(px, i * 16)), f(readf32(px, i * 16 + 4)), f(readf32(px, i * 16 + 8)), f(readf32(px, i * 16 + 12))
+ end
+ local w16 = srcWide or fmt == 6
+ local gray = r
+ if ch <= 2 and not isGray then
+ gray = (r * 299 + g * 587 + b * 114) // 1000
+ end
+ local vals = if ch == 1 then 1 elseif ch == 2 then 2 else ch
+ for c = 0, vals - 1 do
+ local v
+ if ch <= 2 then
+ v = if c == 0 then gray else a
+ else
+ v = if c == 0 then r elseif c == 1 then g elseif c == 2 then b else a
+ end
+ if wide and not w16 then
+ v *= 257
+ elseif w16 and not wide then
+ v = (v * 255 + 32767) // 65535
+ end
+ writeu16(out, (i * ch + c) * 2, v)
+ end
+ end
+ return out
+end
+
+-- writeSamples(s, count, wide, out, o) -> new offset: binary samples (8-bit or 16-bit big-endian)
+function Codec.writeSamples(s: buffer, count: number, wide: boolean, out: buffer, o: number): number
+ if wide then
+ for i = 0, count - 1 do
+ local v = readu16(s, i * 2)
+ writeu8(out, o, v // 256)
+ writeu8(out, o + 1, v % 256)
+ o += 2
+ end
+ else
+ for i = 0, count - 1 do
+ writeu8(out, o, readu16(s, i * 2))
+ o += 1
+ end
+ end
+ return o
+end
+
+-- writeBits(s, w, h, threshold, out, o) -> new offset: P4 rows from grey samples (below threshold = black = 1)
+function Codec.writeBits(s: buffer, w: number, h: number, threshold: number, out: buffer, o: number): number
+ for y = 0, h - 1 do
+ local acc, nb = 0, 0
+ for x = 0, w - 1 do
+ acc = acc * 2 + (if readu16(s, (y * w + x) * 2) < threshold then 1 else 0)
+ nb += 1
+ if nb == 8 then
+ writeu8(out, o, acc)
+ o += 1
+ acc, nb = 0, 0
+ end
+ end
+ if nb > 0 then
+ writeu8(out, o, acc * 2 ^ (8 - nb))
+ o += 1
+ end
+ end
+ return o
+end
+
+-- writeFloats(px, w, h, ch, out, o) -> new offset: rgbaf32 (ch 3) or its first channel (ch 1) as little-endian PFM
+-- rows, bottom-to-top
+function Codec.writeFloats(px: buffer, w: number, h: number, ch: number, out: buffer, o: number): number
+ for y = h - 1, 0, -1 do
+ for x = 0, w - 1 do
+ local q = (y * w + x) * 16
+ for c = 0, ch - 1 do
+ writef32(out, o, readf32(px, q + c * 4))
+ o += 4
+ end
+ end
+ end
+ return o
+end
+
+return Codec
diff --git a/src/Formats/image/pnm/init.luau b/src/Formats/image/pnm/init.luau
new file mode 100644
index 0000000..237e474
--- /dev/null
+++ b/src/Formats/image/pnm/init.luau
@@ -0,0 +1,383 @@
+--!strict
+-- image/pnm: the Netpbm family, written from the Netpbm format pages: PBM (P1 ASCII / P4 binary), PGM (P2 / P5),
+-- PPM (P3 / P6), PAM (P7: BLACKANDWHITE, GRAYSCALE, GRAYSCALE_ALPHA, RGB, RGB_ALPHA and their _ALPHA forms, any
+-- tuple type of depth 1..4) and PFM (PF colour / Pf grey 32-bit float, either byte order, bottom-to-top rows).
+-- maxval 1..65535 (scaled to 8 bits by round(v * 255 / maxval)). Decode: rgba8, or with opts.native the source layout
+-- (gray8, gray16, graya8, rgb8, rgba8, rgba16 for 16-bit colour or grey + alpha, rgbaf32 for PFM). PFM to rgba8 is
+-- clamp(v, 0, 1) * 255 rounded (linear, no gamma). Encode: any of the seven types, binary or ASCII, from every pixel
+-- format; the subtype comes from opts.format / the file extension (pbm, pgm, ppm, pam, pfm) or the image.
+-- Not supported: multi-image streams (the first image is read), PAM depths above 4.
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Types = require("@formats/Types")
+local Codec = require("@formats/image/pnm/Codec")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Pnm = {
+ name = "pnm",
+ category = "image",
+ extensions = { "pnm", "pbm", "pgm", "ppm", "pam", "pfm" },
+ mime = { "image/x-portable-anymap", "image/x-portable-bitmap", "image/x-portable-graymap", "image/x-portable-pixmap", "image/x-portable-arbitrarymap", "image/x-portable-floatmap" },
+ deps = { "core/Err", "core/Bytes", "Types" },
+ caps = { decode = true, encode = true, alpha = true, depths = { 1, 8, 16, 32 }, float = true },
+}
+
+-- ------------------------------------------------------------------------------------------------ types
+export type DecodeOptions = {
+ native: boolean?, -- keep the source layout (default false: rgba8)
+ maxPixels: number?, -- refuse larger images (default 2^26)
+}
+export type EncodeOptions = {
+ format: string?, -- "pbm" | "pgm" | "ppm" | "pam" | "pfm" (default: from the image: grey -> pgm, opaque colour
+ -- -> ppm, alpha -> pam, rgbaf32 -> pfm); "pnm" means the default
+ ascii: boolean?, -- P1 / P2 / P3 instead of P4 / P5 / P6 (default false)
+ maxval: number?, -- 1..65535 (default 255, or 65535 for 16-bit / float sources); pbm ignores it
+ threshold: number?, -- pbm: grey below this (0..255) is black (default 128)
+}
+
+-- ------------------------------------------------------------------------------------------------ constants
+local FMT_CODE = { rgba8 = 0, rgb8 = 1, gray8 = 2, graya8 = 3, rgba16 = 4, gray16 = 5, rgbaf32 = 6 }
+local BPP = { rgba8 = 4, rgb8 = 3, gray8 = 1, graya8 = 2, rgba16 = 8, gray16 = 2, rgbaf32 = 16 }
+local readu8 = buffer.readu8
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Pnm.sniff(r: Bytes.Reader): number
+ if r:remaining() < 3 then
+ return 0
+ end
+ local a, b, c = r:peekU8(0), r:peekU8(1), r:peekU8(2)
+ if a ~= 80 then -- 'P'
+ return 0
+ end
+ local ws = c == 32 or (c >= 9 and c <= 13)
+ if b >= 49 and b <= 55 and ws then -- P1..P7
+ return 0.9
+ end
+ if (b == 70 or b == 102) and ws then -- PF / Pf
+ return 0.9
+ end
+ return 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+local function isSpace(c: number): boolean
+ return c == 32 or (c >= 9 and c <= 13)
+end
+
+-- the next header token from p: token, position after it (nil at the end)
+local function token(b: buffer, p: number, limit: number): (string?, number)
+ while p < limit do
+ local c = readu8(b, p)
+ if c == 35 then
+ while p < limit and readu8(b, p) ~= 10 and readu8(b, p) ~= 13 do
+ p += 1
+ end
+ elseif isSpace(c) then
+ p += 1
+ else
+ break
+ end
+ end
+ local s = p
+ while p < limit and not isSpace(readu8(b, p)) and readu8(b, p) ~= 35 do
+ p += 1
+ end
+ if p == s then
+ return nil, p
+ end
+ return buffer.readstring(b, s, p - s), p
+end
+
+local function int(s: string?): number?
+ if s == nil or not string.match(s, "^%d+$") or #s > 9 then
+ return nil
+ end
+ return tonumber(s)
+end
+
+function Pnm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
+ local maxPixels = opts and opts.maxPixels or 2 ^ 26
+ local native = opts and opts.native or false
+ local b, limit = r.buf, r.limit
+ if r.limit - r.base < 3 or readu8(b, r.base) ~= 80 then
+ return nil, Err.new(Err.CORRUPT, "not a Netpbm file", r.base)
+ end
+ local kind = string.char(readu8(b, r.base + 1))
+ local p = r.base + 2
+ local w, h, maxval, ch, mode
+ local bits = false -- PBM: 1 = black
+ local bw = false -- PAM BLACKANDWHITE: 1 = white
+ local tupl: string? = nil
+ local scale: number? = nil
+ if kind == "1" or kind == "2" or kind == "3" or kind == "4" or kind == "5" or kind == "6" or kind == "F" or kind == "f" then
+ local t1, t2, t3
+ t1, p = token(b, p, limit)
+ t2, p = token(b, p, limit)
+ w, h = int(t1), int(t2)
+ if kind == "1" or kind == "4" then
+ maxval = 1
+ elseif kind == "F" or kind == "f" then
+ t3, p = token(b, p, limit)
+ scale = if t3 then tonumber(t3) else nil
+ if scale == nil or scale == 0 then
+ return nil, Err.new(Err.CORRUPT, "bad PFM scale", p)
+ end
+ maxval = 1
+ else
+ t3, p = token(b, p, limit)
+ maxval = int(t3)
+ end
+ if w == nil or h == nil or maxval == nil then
+ return nil, if p >= limit then Err.new(Err.TRUNCATED, "header ends early", p) else Err.new(Err.CORRUPT, "bad header", p)
+ end
+ if kind ~= "1" and kind ~= "2" and kind ~= "3" then
+ p += 1 -- exactly one whitespace byte before binary data
+ end
+ ch = if kind == "3" or kind == "6" or kind == "F" then 3 else 1
+ bits = kind == "1" or kind == "4"
+ mode = if kind == "1" then 4 elseif kind == "2" or kind == "3" then 3 elseif kind == "4" then 0 elseif maxval > 255 then 2 else 1
+ elseif kind == "7" then
+ local depth
+ while true do
+ local key
+ key, p = token(b, p, limit)
+ if key == nil then
+ return nil, Err.new(Err.TRUNCATED, "PAM header ends early", p)
+ end
+ if key == "ENDHDR" then
+ break
+ end
+ local v
+ v, p = token(b, p, limit)
+ if key == "WIDTH" then
+ w = int(v)
+ elseif key == "HEIGHT" then
+ h = int(v)
+ elseif key == "DEPTH" then
+ depth = int(v)
+ elseif key == "MAXVAL" then
+ maxval = int(v)
+ elseif key == "TUPLTYPE" then
+ tupl = v
+ -- the rest of the line belongs to the value
+ while p < limit and readu8(b, p) ~= 10 do
+ p += 1
+ end
+ end
+ end
+ -- ENDHDR ends with a newline
+ while p < limit and readu8(b, p) ~= 10 do
+ p += 1
+ end
+ p += 1
+ if w == nil or h == nil or depth == nil or maxval == nil then
+ return nil, Err.new(Err.CORRUPT, "PAM header misses WIDTH / HEIGHT / DEPTH / MAXVAL", p)
+ end
+ if depth < 1 or depth > 4 then
+ return nil, Err.new(Err.UNSUPPORTED, "PAM depth " .. depth)
+ end
+ ch = depth
+ bw = tupl ~= nil and string.sub(tupl, 1, 13) == "BLACKANDWHITE"
+ mode = if maxval > 255 then 2 else 1
+ else
+ return nil, Err.new(Err.CORRUPT, "not a Netpbm file", r.base)
+ end
+ if w < 1 or h < 1 or maxval < 1 or maxval > 65535 then
+ return nil, Err.new(Err.CORRUPT, string.format("bad size %d x %d or maxval %d", w, h, maxval))
+ end
+ if w * h > maxPixels then
+ return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
+ end
+ local n = w * h
+ local img: Types.Image
+ local colorType = if ch == 1 then "gray" elseif ch == 2 then "graya" elseif ch == 3 then "rgb" else "rgba"
+ if scale then
+ local f = Types.Image.new(w, h, "rgbaf32")
+ local ok, e = Codec.readFloats(b, p, limit, w, h, ch, (scale :: number) < 0, f.pixels)
+ if not ok then
+ return nil, Err.new(Err.TRUNCATED, tostring(e))
+ end
+ img = f
+ if not native then
+ local o = Types.Image.new(w, h, "rgba8")
+ for i = 0, n * 4 - 1 do
+ local v = buffer.readf32(f.pixels, i * 4)
+ buffer.writeu8(o.pixels, i, if v ~= v then 0 else math.floor(math.clamp(v, 0, 1) * 255 + 0.5))
+ end
+ img = o
+ end
+ img.meta.source = { format = "pnm", type = if ch == 3 then "pfm" else "pfm-gray", bitDepth = 32, colorType = colorType, scale = math.abs(scale :: number), byteOrder = if (scale :: number) < 0 then "little" else "big" }
+ return img, nil
+ end
+ local samples = buffer.create(n * ch * 2)
+ local ok, e
+ if mode == 0 then
+ ok, e = Codec.readBits(b, p, limit, w, h, samples)
+ else
+ ok, e = Codec.readSamples(b, p, limit, n * ch, mode, samples)
+ end
+ if not ok then
+ return nil, Err.new(if e == "truncated" then Err.TRUNCATED else Err.CORRUPT, tostring(e))
+ end
+ local fmt = "rgba8"
+ if native then
+ local wide = maxval > 255
+ if bits or bw or ch == 1 then
+ fmt = if wide then "gray16" else "gray8"
+ elseif ch == 2 then
+ fmt = if wide then "rgba16" else "graya8"
+ elseif ch == 3 then
+ fmt = if wide then "rgba16" else "rgb8"
+ else
+ fmt = if wide then "rgba16" else "rgba8"
+ end
+ end
+ img = Types.Image.new(w, h, fmt :: Types.PixelFormat)
+ Codec.pack(samples, n, ch, maxval, bits, FMT_CODE[fmt], img.pixels)
+ local typ = if kind == "7" then "pam" elseif bits then "pbm" elseif ch == 1 then "pgm" else "ppm"
+ img.meta.source = {
+ format = "pnm",
+ type = typ,
+ ascii = mode == 3 or mode == 4,
+ bitDepth = if bits or bw then 1 elseif maxval > 255 then 16 else 8,
+ maxval = maxval,
+ colorType = if bits or bw then "bilevel" else colorType,
+ tupltype = tupl,
+ }
+ return img, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+local SUBTYPES = { pbm = true, pgm = true, ppm = true, pam = true, pfm = true }
+
+function Pnm.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
+ if type(img) ~= "table" or type(img.pixels) ~= "buffer" then
+ return nil, Err.new(Err.ARG, "needs an Image")
+ end
+ local fc = FMT_CODE[img.format]
+ if fc == nil then
+ return nil, Err.new(Err.ARG, "unsupported pixel format " .. tostring(img.format))
+ end
+ local w, h = img.width, img.height
+ if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < w * h * BPP[img.format] then
+ return nil, Err.new(Err.ARG, "bad image size or pixel buffer")
+ end
+ local o: any = opts or {}
+ local n = w * h
+ local isGray = img.format == "gray8" or img.format == "gray16" or img.format == "graya8"
+ local hasAlpha = img.format == "graya8" or img.format == "rgba16" or img.format == "rgba8" or img.format == "rgbaf32"
+ if hasAlpha and img.format ~= "graya8" then
+ -- an alpha channel that is fully opaque does not count
+ local opaque = true
+ for i = 0, n - 1 do
+ local a
+ if img.format == "rgba8" then
+ a = buffer.readu8(img.pixels, i * 4 + 3) == 255
+ elseif img.format == "rgba16" then
+ a = buffer.readu16(img.pixels, i * 8 + 6) == 65535
+ else
+ a = buffer.readf32(img.pixels, i * 16 + 12) == 1
+ end
+ if not a then
+ opaque = false
+ break
+ end
+ end
+ hasAlpha = not opaque
+ end
+ local sub = if type(o.format) == "string" then string.lower(o.format) else nil
+ if not (sub and SUBTYPES[sub]) then
+ if img.format == "rgbaf32" and not hasAlpha then
+ sub = "pfm"
+ elseif hasAlpha then
+ sub = "pam"
+ elseif isGray then
+ sub = "pgm"
+ else
+ sub = "ppm"
+ end
+ end
+ local ascii = o.ascii == true
+ local wideSrc = img.format == "gray16" or img.format == "rgba16" or img.format == "rgbaf32"
+ local maxval = o.maxval or (if wideSrc then 65535 else 255)
+ if type(maxval) ~= "number" or maxval < 1 or maxval > 65535 or maxval % 1 ~= 0 then
+ return nil, Err.new(Err.ARG, "maxval must be 1..65535")
+ end
+ local out: buffer
+ local op = 0
+ local function header(s: string, extra: number)
+ out = buffer.create(#s + extra)
+ buffer.writestring(out, 0, s)
+ op = #s
+ end
+ if sub == "pfm" then
+ local ch = if isGray then 1 else 3
+ local src = img
+ if img.format ~= "rgbaf32" then
+ local s = Codec.extract(img.pixels, fc, n, 4, true)
+ src = Types.Image.new(w, h, "rgbaf32")
+ for i = 0, n * 4 - 1 do
+ buffer.writef32(src.pixels, i * 4, buffer.readu16(s, i * 2) / 65535)
+ end
+ end
+ header(string.format("%s\n%d %d\n-1.0\n", if ch == 3 then "PF" else "Pf", w, h), n * ch * 4)
+ op = Codec.writeFloats(src.pixels, w, h, ch, out, op)
+ return out, nil
+ end
+ local ch = if sub == "pbm" or sub == "pgm" then 1 elseif sub == "ppm" then 3 elseif isGray then (if hasAlpha then 2 else 1) else (if hasAlpha then 4 else 3)
+ if sub == "pbm" then
+ local thr = o.threshold or 128
+ local s = Codec.extract(img.pixels, fc, n, 1, false)
+ if ascii then
+ local parts = table.create(h + 1)
+ parts[1] = string.format("P1\n%d %d\n", w, h)
+ for y = 0, h - 1 do
+ local row = table.create(w)
+ for x = 0, w - 1 do
+ row[x + 1] = if buffer.readu16(s, (y * w + x) * 2) < thr then "1" else "0"
+ end
+ parts[y + 2] = table.concat(row, " ") .. "\n"
+ end
+ return buffer.fromstring(table.concat(parts)), nil
+ end
+ header(string.format("P4\n%d %d\n", w, h), ((w + 7) // 8) * h)
+ op = Codec.writeBits(s, w, h, thr, out, op)
+ return out, nil
+ end
+ local wide = maxval > 255
+ local s = Codec.extract(img.pixels, fc, n, ch, wide)
+ if maxval ~= 255 and maxval ~= 65535 then
+ local top = if wide then 65535 else 255
+ for i = 0, n * ch - 1 do
+ buffer.writeu16(s, i * 2, (buffer.readu16(s, i * 2) * maxval + top // 2) // top)
+ end
+ end
+ local magic
+ if sub == "pam" then
+ local tt = if ch == 1 then "GRAYSCALE" elseif ch == 2 then "GRAYSCALE_ALPHA" elseif ch == 3 then "RGB" else "RGB_ALPHA"
+ header(string.format("P7\nWIDTH %d\nHEIGHT %d\nDEPTH %d\nMAXVAL %d\nTUPLTYPE %s\nENDHDR\n", w, h, ch, maxval, tt), n * ch * (if wide then 2 else 1))
+ op = Codec.writeSamples(s, n * ch, wide, out, op)
+ return out, nil
+ end
+ magic = if sub == "pgm" then (if ascii then "P2" else "P5") else (if ascii then "P3" else "P6")
+ if ascii then
+ local parts = table.create(h + 1)
+ parts[1] = string.format("%s\n%d %d\n%d\n", magic, w, h, maxval)
+ local rowLen = w * ch
+ for y = 0, h - 1 do
+ local row = table.create(rowLen)
+ for i = 0, rowLen - 1 do
+ row[i + 1] = tostring(buffer.readu16(s, (y * rowLen + i) * 2))
+ end
+ parts[y + 2] = table.concat(row, " ") .. "\n"
+ end
+ return buffer.fromstring(table.concat(parts)), nil
+ end
+ header(string.format("%s\n%d %d\n%d\n", magic, w, h, maxval), n * ch * (if wide then 2 else 1))
+ op = Codec.writeSamples(s, n * ch, wide, out, op)
+ return out, nil
+end
+
+return Pnm
diff --git a/src/Formats/image/qoi/Codec.luau b/src/Formats/image/qoi/Codec.luau
new file mode 100644
index 0000000..2936f07
--- /dev/null
+++ b/src/Formats/image/qoi/Codec.luau
@@ -0,0 +1,144 @@
+--!strict
+--!native
+--!optimize 2
+-- image/qoi/Codec: the QOI op loops (native; never throws). Written from the QOI specification 1.0 (qoiformat.org).
+-- decode reads ops from b[p, limit) into an rgba8 buffer; encode writes ops for rgba8 / rgb8 pixels. Every input read
+-- is checked against limit; the output buffer has exactly w * h * 4 bytes and the loop stops when it is full.
+local readu8, writeu8, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu32
+
+local Codec = {}
+
+local index = buffer.create(256)
+
+-- decode(b, p, limit, out, n) -> true | false, "truncated" (n pixels into out)
+function Codec.decode(b: buffer, p: number, limit: number, out: buffer, n: number): (boolean, string?)
+ buffer.fill(index, 0, 0, 256)
+ local r, g, bl, a = 0, 0, 0, 255
+ local o = 0
+ local stop = n * 4
+ while o < stop do
+ if p >= limit then
+ return false, "truncated"
+ end
+ local op = readu8(b, p)
+ p += 1
+ if op == 0xFE then
+ if p + 3 > limit then
+ return false, "truncated"
+ end
+ r, g, bl = readu8(b, p), readu8(b, p + 1), readu8(b, p + 2)
+ p += 3
+ elseif op == 0xFF then
+ if p + 4 > limit then
+ return false, "truncated"
+ end
+ r, g, bl, a = readu8(b, p), readu8(b, p + 1), readu8(b, p + 2), readu8(b, p + 3)
+ p += 4
+ else
+ local tag = op // 64
+ if tag == 0 then
+ local q = op * 4
+ r, g, bl, a = readu8(index, q), readu8(index, q + 1), readu8(index, q + 2), readu8(index, q + 3)
+ elseif tag == 1 then
+ r = (r + (op // 16) % 4 - 2) % 256
+ g = (g + (op // 4) % 4 - 2) % 256
+ bl = (bl + op % 4 - 2) % 256
+ elseif tag == 2 then
+ if p >= limit then
+ return false, "truncated"
+ end
+ local d2 = readu8(b, p)
+ p += 1
+ local dg = op % 64 - 32
+ g = (g + dg) % 256
+ r = (r + dg + d2 // 16 - 8) % 256
+ bl = (bl + dg + d2 % 16 - 8) % 256
+ else
+ local run = op % 64 -- 1..62 more copies of the previous pixel (63 / 64 are RGB / RGBA)
+ local v = r + g * 256 + bl * 65536 + a * 16777216
+ local e = math.min(o + run * 4, stop - 4)
+ while o < e do
+ writeu32(out, o, v)
+ o += 4
+ end
+ end
+ end
+ writeu32(out, o, r + g * 256 + bl * 65536 + a * 16777216)
+ o += 4
+ local h = ((r * 3 + g * 5 + bl * 7 + a * 11) % 64) * 4
+ writeu8(index, h, r)
+ writeu8(index, h + 1, g)
+ writeu8(index, h + 2, bl)
+ writeu8(index, h + 3, a)
+ end
+ return true, nil
+end
+
+-- encode(px, n, bpp, out, o) -> new offset: n pixels of bpp (3 or 4) bytes; out has room for n * (bpp + 1) bytes
+function Codec.encode(px: buffer, n: number, bpp: number, out: buffer, o: number): number
+ buffer.fill(index, 0, 0, 256)
+ local pr, pg, pb, pa = 0, 0, 0, 255
+ local run = 0
+ local hasA = bpp == 4
+ for i = 0, n - 1 do
+ local q = i * bpp
+ local r, g, b = readu8(px, q), readu8(px, q + 1), readu8(px, q + 2)
+ local a = if hasA then readu8(px, q + 3) else 255
+ if r == pr and g == pg and b == pb and a == pa then
+ run += 1
+ if run == 62 or i == n - 1 then
+ writeu8(out, o, 0xC0 + run - 1)
+ o += 1
+ run = 0
+ end
+ else
+ if run > 0 then
+ writeu8(out, o, 0xC0 + run - 1)
+ o += 1
+ run = 0
+ end
+ local h = (r * 3 + g * 5 + b * 7 + a * 11) % 64
+ local hq = h * 4
+ if readu8(index, hq) == r and readu8(index, hq + 1) == g and readu8(index, hq + 2) == b and readu8(index, hq + 3) == a then
+ writeu8(out, o, h)
+ o += 1
+ else
+ writeu8(index, hq, r)
+ writeu8(index, hq + 1, g)
+ writeu8(index, hq + 2, b)
+ writeu8(index, hq + 3, a)
+ if a == pa then
+ local dr = (r - pr + 128) % 256 - 128
+ local dg = (g - pg + 128) % 256 - 128
+ local db = (b - pb + 128) % 256 - 128
+ local dgr, dgb = dr - dg, db - dg
+ if dr >= -2 and dr <= 1 and dg >= -2 and dg <= 1 and db >= -2 and db <= 1 then
+ writeu8(out, o, 0x40 + (dr + 2) * 16 + (dg + 2) * 4 + db + 2)
+ o += 1
+ elseif dg >= -32 and dg <= 31 and dgr >= -8 and dgr <= 7 and dgb >= -8 and dgb <= 7 then
+ writeu8(out, o, 0x80 + dg + 32)
+ writeu8(out, o + 1, (dgr + 8) * 16 + dgb + 8)
+ o += 2
+ else
+ writeu8(out, o, 0xFE)
+ writeu8(out, o + 1, r)
+ writeu8(out, o + 2, g)
+ writeu8(out, o + 3, b)
+ o += 4
+ end
+ else
+ writeu8(out, o, 0xFF)
+ writeu8(out, o + 1, r)
+ writeu8(out, o + 2, g)
+ writeu8(out, o + 3, b)
+ writeu8(out, o + 4, a)
+ o += 5
+ end
+ end
+ pr, pg, pb, pa = r, g, b, a
+ end
+ end
+ return o
+end
+
+return Codec
diff --git a/src/Formats/image/qoi/init.luau b/src/Formats/image/qoi/init.luau
new file mode 100644
index 0000000..ef11dc6
--- /dev/null
+++ b/src/Formats/image/qoi/init.luau
@@ -0,0 +1,122 @@
+--!strict
+-- image/qoi: QOI, the Quite OK Image format (specification 1.0, qoiformat.org). New code written from the spec.
+-- Supports: decode of RGB and RGBA files (either colour space tag) to rgba8 (opts.native: rgb8 for 3-channel files);
+-- encode of rgba8 (4 channels) and rgb8 (3 channels), lossless; meta.source.colorSpace keeps the sRGB / linear tag.
+-- Not supported: nothing in the spec is left out.
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Types = require("@formats/Types")
+local Codec = require("@formats/image/qoi/Codec")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Qoi = {
+ name = "qoi",
+ category = "image",
+ extensions = { "qoi" },
+ mime = { "image/qoi", "image/x-qoi" },
+ deps = { "core/Err", "core/Bytes", "Types" },
+ caps = { decode = true, encode = true, alpha = true, depths = { 8 } },
+}
+
+-- ------------------------------------------------------------------------------------------------ types
+export type DecodeOptions = {
+ native: boolean?, -- rgb8 for 3-channel files (default false: always rgba8)
+ maxPixels: number?, -- refuse larger images (default 2^26)
+}
+export type EncodeOptions = {
+ channels: number?, -- 3 or 4 (default: 3 for rgb8 images or opaque rgba8, else 4)
+ linear: boolean?, -- tag the file as linear instead of sRGB (default: meta.source.colorSpace == "linear")
+}
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Qoi.sniff(r: Bytes.Reader): number
+ return if r:peek(4) == "qoif" then 1 else 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+function Qoi.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
+ local maxPixels = opts and opts.maxPixels or 2 ^ 26
+ local magic = r:string(4)
+ local w, h = r:u32be(), r:u32be()
+ local channels, cs = r:u8(), r:u8()
+ if r.err then
+ return nil, r.err
+ end
+ if magic ~= "qoif" then
+ return nil, Err.new(Err.CORRUPT, "bad magic", r.base)
+ end
+ if w == 0 or h == 0 or (channels ~= 3 and channels ~= 4) or cs > 1 then
+ return nil, Err.new(Err.CORRUPT, "bad header", r.base + 4)
+ end
+ if w * h > maxPixels then
+ return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
+ end
+ local img = Types.Image.new(w, h, "rgba8")
+ local ok, e = Codec.decode(r.buf, r.pos, r.limit, img.pixels, w * h)
+ if not ok then
+ return nil, Err.new(Err.TRUNCATED, tostring(e))
+ end
+ if opts and opts.native and channels == 3 then
+ local rgb = Types.Image.new(w, h, "rgb8")
+ local src, dst = img.pixels, rgb.pixels
+ for i = 0, w * h - 1 do
+ buffer.writeu16(dst, i * 3, buffer.readu16(src, i * 4))
+ buffer.writeu8(dst, i * 3 + 2, buffer.readu8(src, i * 4 + 2))
+ end
+ img = rgb
+ end
+ img.meta.source = { format = "qoi", bitDepth = 8, colorType = if channels == 4 then "rgba" else "rgb", channels = channels, colorSpace = if cs == 1 then "linear" else "srgb" }
+ if cs == 1 then
+ img.meta.colorSpace = "linear"
+ end
+ return img, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+function Qoi.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
+ if type(img) ~= "table" or type(img.pixels) ~= "buffer" or (img.format ~= "rgba8" and img.format ~= "rgb8") then
+ return nil, Err.new(Err.ARG, "needs an rgba8 or rgb8 Image")
+ end
+ local w, h = img.width, img.height
+ local bpp = if img.format == "rgba8" then 4 else 3
+ if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < w * h * bpp then
+ return nil, Err.new(Err.ARG, "bad image size or pixel buffer")
+ end
+ local channels = opts and opts.channels
+ if channels == nil then
+ channels = 3
+ if bpp == 4 then
+ local px = img.pixels
+ for i = 0, w * h - 1 do
+ if buffer.readu8(px, i * 4 + 3) ~= 255 then
+ channels = 4
+ break
+ end
+ end
+ end
+ elseif channels ~= 3 and channels ~= 4 then
+ return nil, Err.new(Err.ARG, "channels must be 3 or 4")
+ end
+ local linear = opts and opts.linear
+ if linear == nil then
+ local src = img.meta and img.meta.source
+ linear = (type(src) == "table" and src.colorSpace == "linear") or (img.meta and img.meta.colorSpace == "linear") or false
+ end
+ local n = w * h
+ local out = buffer.create(14 + n * (bpp + 1) + 8)
+ buffer.writestring(out, 0, "qoif")
+ buffer.writeu32(out, 4, bit32.byteswap(w))
+ buffer.writeu32(out, 8, bit32.byteswap(h))
+ buffer.writeu8(out, 12, channels)
+ buffer.writeu8(out, 13, if linear then 1 else 0)
+ local o = Codec.encode(img.pixels, n, bpp, out, 14)
+ buffer.writestring(out, o, "\0\0\0\0\0\0\0\1")
+ o += 8
+ local res = buffer.create(o)
+ buffer.copy(res, 0, out, 0, o)
+ return res, nil
+end
+
+return Qoi
diff --git a/src/Formats/image/tga/Codec.luau b/src/Formats/image/tga/Codec.luau
new file mode 100644
index 0000000..1cbb0bd
--- /dev/null
+++ b/src/Formats/image/tga/Codec.luau
@@ -0,0 +1,157 @@
+--!strict
+--!native
+--!optimize 2
+-- image/tga/Codec: the Truevision TGA pixel loops (native; never throws). Written from the Truevision TGA 2.0
+-- specification. decode reads raw or RLE pixel data (packets may cross scanlines) into rgba8 at the oriented
+-- position; encode writes raw or RLE rows. Every read is bounds-checked; the output has exactly w * h * 4 bytes.
+local readu8, readu16, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32
+
+local Codec = {}
+
+-- one source pixel at b[p] -> rgba as a u32; kind: 0 grey 8, 1 grey + alpha 16, 2 = 15/16-bit ARGB1555,
+-- 3 = BGR 24, 4 = BGRA 32, 5 = index 8, 6 = index 16 (pal: u32 entries, palN of them)
+local function pixel(b: buffer, p: number, kind: number, alpha1: boolean, pal: buffer, palN: number): number
+ if kind == 0 then
+ return readu8(b, p) * 0x10101 + 0xFF000000
+ elseif kind == 1 then
+ return readu8(b, p) * 0x10101 + readu8(b, p + 1) * 0x1000000
+ elseif kind == 2 then
+ local v = readu16(b, p)
+ local r, g, bl = (v // 1024) % 32, (v // 32) % 32, v % 32
+ local a = if alpha1 and v < 32768 then 0 else 255
+ return (r * 255 + 15) // 31 + ((g * 255 + 15) // 31) * 256 + ((bl * 255 + 15) // 31) * 65536 + a * 16777216 -- round(v * 255 / 31), as ImageMagick
+ elseif kind == 3 then
+ return readu8(b, p + 2) + readu8(b, p + 1) * 256 + readu8(b, p) * 65536 + 0xFF000000
+ elseif kind == 4 then
+ return readu8(b, p + 2) + readu8(b, p + 1) * 256 + readu8(b, p) * 65536 + readu8(b, p + 3) * 16777216
+ end
+ local i = if kind == 5 then readu8(b, p) else readu16(b, p)
+ if i >= palN then
+ return 0xFF000000
+ end
+ return readu32(pal, i * 4)
+end
+Codec.pixel = pixel
+
+-- decode(b, p, limit, w, h, bpp, kind, alpha1, rle, bottomUp, rtl, pal, palN, out) -> pixels written, truncated?
+function Codec.decode(b: buffer, p: number, limit: number, w: number, h: number, bpp: number, kind: number, alpha1: boolean, rle: boolean, bottomUp: boolean, rtl: boolean, pal: buffer, palN: number, out: buffer): (number, boolean)
+ local n = w * h
+ local i = 0
+ local function put(v: number)
+ local row, col = i // w, i % w
+ if bottomUp then
+ row = h - 1 - row
+ end
+ if rtl then
+ col = w - 1 - col
+ end
+ writeu32(out, (row * w + col) * 4, v)
+ i += 1
+ end
+ if not rle then
+ local avail = math.min(n, (limit - p) // bpp)
+ for _ = 1, avail do
+ put(pixel(b, p, kind, alpha1, pal, palN))
+ p += bpp
+ end
+ return i, avail < n
+ end
+ while i < n do
+ if p >= limit then
+ return i, true
+ end
+ local hd = readu8(b, p)
+ p += 1
+ local count = hd % 128 + 1
+ if hd >= 128 then
+ if p + bpp > limit then
+ return i, true
+ end
+ local v = pixel(b, p, kind, alpha1, pal, palN)
+ p += bpp
+ for _ = 1, math.min(count, n - i) do
+ put(v)
+ end
+ else
+ for _ = 1, math.min(count, n - i) do
+ if p + bpp > limit then
+ return i, true
+ end
+ put(pixel(b, p, kind, alpha1, pal, palN))
+ p += bpp
+ end
+ end
+ end
+ return i, false
+end
+
+-- encode(px, w, h, srcBpp, outBpp, rle, topDown, out, o) -> new offset. px: rgba8 / rgb8 / gray8 (srcBpp 4 / 3 / 1);
+-- written as BGRA / BGR / grey (outBpp 4 / 3 / 1), rows top-down or bottom-up; RLE packets stay inside a row.
+-- out needs room for w * h * (outBpp + 1) bytes.
+function Codec.encode(px: buffer, w: number, h: number, srcBpp: number, outBpp: number, rle: boolean, topDown: boolean, out: buffer, o: number): number
+ local function get(q: number): number
+ if srcBpp == 1 then
+ return readu8(px, q)
+ elseif srcBpp == 3 then
+ return readu8(px, q) + readu8(px, q + 1) * 256 + readu8(px, q + 2) * 65536 + 0xFF000000
+ end
+ return readu32(px, q)
+ end
+ local function emit(v: number)
+ if outBpp == 1 then
+ writeu8(out, o, v % 256)
+ else
+ writeu8(out, o, (v // 65536) % 256)
+ writeu8(out, o + 1, (v // 256) % 256)
+ writeu8(out, o + 2, v % 256)
+ if outBpp == 4 then
+ writeu8(out, o + 3, v // 16777216)
+ end
+ end
+ o += outBpp
+ end
+ for y = 0, h - 1 do
+ local row = if topDown then y else h - 1 - y
+ local base = row * w * srcBpp
+ if not rle then
+ for x = 0, w - 1 do
+ emit(get(base + x * srcBpp))
+ end
+ else
+ local x = 0
+ while x < w do
+ local v = get(base + x * srcBpp)
+ local run = 1
+ while x + run < w and run < 128 and get(base + (x + run) * srcBpp) == v do
+ run += 1
+ end
+ if run >= 2 then
+ writeu8(out, o, 127 + run)
+ o += 1
+ emit(v)
+ x += run
+ else
+ -- a raw packet up to the next run of 2 or more
+ local s = x
+ local cnt = 0
+ while x < w and cnt < 128 do
+ local c = get(base + x * srcBpp)
+ if x + 1 < w and get(base + (x + 1) * srcBpp) == c then
+ break
+ end
+ cnt += 1
+ x += 1
+ end
+ writeu8(out, o, cnt - 1)
+ o += 1
+ for k = s, s + cnt - 1 do
+ emit(get(base + k * srcBpp))
+ end
+ end
+ end
+ end
+ end
+ return o
+end
+
+return Codec
diff --git a/src/Formats/image/tga/init.luau b/src/Formats/image/tga/init.luau
new file mode 100644
index 0000000..1b4400b
--- /dev/null
+++ b/src/Formats/image/tga/init.luau
@@ -0,0 +1,276 @@
+--!strict
+-- image/tga: Truevision TGA (TGA 2.0 specification; new code). Decode: colour-mapped (1), true-colour (2) and grey (3)
+-- images, raw or RLE (9, 10, 11; packets may cross scanlines), 8 / 15 / 16 / 24 / 32-bit pixels, 15 / 16 / 24 /
+-- 32-bit colour maps with a first index, 8 / 16-bit indexes, grey + alpha (16-bit type 3), every origin (bottom-left,
+-- top-left, right-to-left), the alpha bits of the descriptor (16-bit: alpha only when it declares 1 alpha bit; 32-bit:
+-- alpha always), the image ID (meta.text.id) and the TGA 2.0 footer (tolerated, not needed). Truncated pixel data
+-- leaves the rest transparent black (meta.truncated). opts.native: gray8 for grey files, rgb8 for 24-bit.
+-- Encode: rgba8 (32-bit BGRA when there is alpha, else 24-bit), rgb8 (24-bit), gray8 (type 3), raw or RLE, bottom-left
+-- (default) or top-left origin, with the TGA 2.0 footer. Not supported: the extension area's fields (gamma, postage
+-- stamp, ...), which are ignored.
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Types = require("@formats/Types")
+local Codec = require("@formats/image/tga/Codec")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Tga = {
+ name = "tga",
+ category = "image",
+ extensions = { "tga", "icb", "vda", "vst", "tpic" },
+ mime = { "image/x-tga", "image/x-targa" },
+ deps = { "core/Err", "core/Bytes", "Types" },
+ caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 8, 15, 16, 24, 32 } },
+}
+
+-- ------------------------------------------------------------------------------------------------ types
+export type DecodeOptions = {
+ native: boolean?, -- gray8 for grey files, rgb8 for 24-bit ones (default false: rgba8)
+ maxPixels: number?, -- refuse larger images (default 2^26)
+}
+export type EncodeOptions = {
+ rle: boolean?, -- run-length encode (default false)
+ origin: ("bottom-left" | "top-left")?, -- default "bottom-left" (the classic layout every reader understands)
+ alpha: boolean?, -- force 32-bit (true) or 24-bit (false) for rgba8 (default: 32-bit when any alpha < 255)
+ id: string?, -- the image ID field (up to 255 bytes; default meta.text.id)
+}
+
+-- ------------------------------------------------------------------------------------------------ constants
+local TYPES = { [1] = true, [2] = true, [3] = true, [9] = true, [10] = true, [11] = true }
+local FOOTER = "TRUEVISION-XFILE.\0"
+local readu8 = buffer.readu8
+
+-- ------------------------------------------------------------------------------------------------ sniff
+type Header = {
+ idLen: number,
+ cmapType: number,
+ imageType: number,
+ cmapFirst: number,
+ cmapLen: number,
+ cmapBits: number,
+ width: number,
+ height: number,
+ depth: number,
+ desc: number,
+}
+
+local function header(r: Bytes.Reader): Header?
+ if r.limit - r.base < 18 then
+ return nil
+ end
+ local b, o = r.buf, r.base
+ local function u16(q: number): number
+ return readu8(b, o + q) + readu8(b, o + q + 1) * 256
+ end
+ local h: Header = {
+ idLen = readu8(b, o),
+ cmapType = readu8(b, o + 1),
+ imageType = readu8(b, o + 2),
+ cmapFirst = u16(3),
+ cmapLen = u16(5),
+ cmapBits = readu8(b, o + 7),
+ width = u16(12),
+ height = u16(14),
+ depth = readu8(b, o + 16),
+ desc = readu8(b, o + 17),
+ }
+ return h
+end
+
+-- plausible(h) -> nil | why not
+local function implausible(h: Header): string?
+ local t = h.imageType
+ if not TYPES[t] then
+ return "image type " .. t
+ end
+ if h.cmapType > 1 then
+ return "colour map type " .. h.cmapType
+ end
+ local mapped = t == 1 or t == 9
+ if mapped and (h.cmapType ~= 1 or (h.depth ~= 8 and h.depth ~= 16)) then
+ return "colour-mapped image without a colour map"
+ end
+ if h.cmapType == 1 and h.cmapLen > 0 and h.cmapBits ~= 15 and h.cmapBits ~= 16 and h.cmapBits ~= 24 and h.cmapBits ~= 32 then
+ return "colour map entry size " .. h.cmapBits
+ end
+ if (t == 2 or t == 10) and h.depth ~= 15 and h.depth ~= 16 and h.depth ~= 24 and h.depth ~= 32 then
+ return "pixel depth " .. h.depth
+ end
+ if (t == 3 or t == 11) and h.depth ~= 8 and h.depth ~= 16 then
+ return "grey pixel depth " .. h.depth
+ end
+ if h.width == 0 or h.height == 0 then
+ return "zero size"
+ end
+ if h.desc >= 64 then
+ return "interleaving / reserved descriptor bits"
+ end
+ return nil
+end
+
+function Tga.sniff(r: Bytes.Reader): number
+ local h = header(r)
+ if not h or implausible(h) then
+ return 0
+ end
+ local n = r.limit - r.base
+ if n >= 44 and buffer.readstring(r.buf, r.limit - 18, 18) == FOOTER then
+ return 0.9
+ end
+ return 0.2
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+function Tga.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
+ local maxPixels = opts and opts.maxPixels or 2 ^ 26
+ local h = header(r)
+ if not h then
+ return nil, Err.new(Err.TRUNCATED, "short header", r.base)
+ end
+ local why = implausible(h)
+ if why then
+ return nil, Err.new(if h.imageType == 0 then Err.UNSUPPORTED else Err.CORRUPT, why, r.base)
+ end
+ local w, ht = h.width, h.height
+ if w * ht > maxPixels then
+ return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, ht, maxPixels))
+ end
+ local b = r.buf
+ local p = r.base + 18
+ local id = if h.idLen > 0 and p + h.idLen <= r.limit then buffer.readstring(b, p, h.idLen) else nil
+ p += h.idLen
+ -- colour map
+ local pal = buffer.create(4)
+ local palN = 0
+ if h.cmapType == 1 and h.cmapLen > 0 then
+ local eb = (h.cmapBits + 7) // 8
+ if p + h.cmapLen * eb > r.limit then
+ return nil, Err.new(Err.TRUNCATED, "colour map runs past the end", p)
+ end
+ local first = h.cmapFirst
+ palN = first + h.cmapLen
+ pal = buffer.create(palN * 4)
+ buffer.fill(pal, 0, 0, palN * 4)
+ local kind = if h.cmapBits == 24 then 3 elseif h.cmapBits == 32 then 4 else 2
+ for i = 0, h.cmapLen - 1 do
+ buffer.writeu32(pal, (first + i) * 4, Codec.pixel(b, p + i * eb, kind, false, pal, 0))
+ end
+ for i = 0, first - 1 do
+ buffer.writeu32(pal, i * 4, 0xFF000000)
+ end
+ p += h.cmapLen * eb
+ end
+ local t = h.imageType
+ local alphaBits = h.desc % 16
+ local kind
+ if t == 1 or t == 9 then
+ kind = if h.depth == 8 then 5 else 6
+ elseif t == 3 or t == 11 then
+ kind = if h.depth == 8 then 0 else 1
+ else
+ kind = if h.depth == 24 then 3 elseif h.depth == 32 then 4 else 2
+ end
+ local bpp = (h.depth + 7) // 8
+ local bottomUp = (h.desc // 32) % 2 == 0
+ local rtl = (h.desc // 16) % 2 == 1
+ local img = Types.Image.new(w, ht, "rgba8")
+ local _, truncated = Codec.decode(b, p, r.limit, w, ht, bpp, kind, h.depth == 16 and alphaBits >= 1, t >= 9, bottomUp, rtl, pal, palN, img.pixels)
+ local native = opts and opts.native
+ if native and kind == 0 then
+ local g = Types.Image.new(w, ht, "gray8")
+ for i = 0, w * ht - 1 do
+ buffer.writeu8(g.pixels, i, readu8(img.pixels, i * 4))
+ end
+ img = g
+ elseif native and kind == 3 then
+ local c = Types.Image.new(w, ht, "rgb8")
+ for i = 0, w * ht - 1 do
+ buffer.writeu16(c.pixels, i * 3, buffer.readu16(img.pixels, i * 4))
+ buffer.writeu8(c.pixels, i * 3 + 2, readu8(img.pixels, i * 4 + 2))
+ end
+ img = c
+ end
+ if palN > 0 then
+ local palette = {}
+ for i = 0, palN - 1 do
+ palette[i + 1] = { readu8(pal, i * 4), readu8(pal, i * 4 + 1), readu8(pal, i * 4 + 2), readu8(pal, i * 4 + 3) }
+ end
+ img.meta.palette = palette
+ end
+ if id then
+ img.meta.text = { id = id }
+ end
+ if truncated then
+ img.meta.truncated = true
+ end
+ img.meta.source = {
+ format = "tga",
+ bitDepth = h.depth,
+ colorType = if kind >= 5 then "palette" elseif kind <= 1 then (if kind == 1 then "graya" else "gray") else (if kind == 3 then "rgb" else "rgba"),
+ rle = t >= 9,
+ origin = (if bottomUp then "bottom" else "top") .. "-" .. (if rtl then "right" else "left"),
+ alphaBits = alphaBits,
+ }
+ return img, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+function Tga.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
+ if type(img) ~= "table" or type(img.pixels) ~= "buffer" then
+ return nil, Err.new(Err.ARG, "needs an Image")
+ end
+ local srcBpp = if img.format == "rgba8" then 4 elseif img.format == "rgb8" then 3 elseif img.format == "gray8" then 1 else nil
+ if not srcBpp then
+ return nil, Err.new(Err.ARG, "needs an rgba8, rgb8 or gray8 Image")
+ end
+ local w, h = img.width, img.height
+ if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w > 65535 or h > 65535 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < w * h * srcBpp then
+ return nil, Err.new(Err.ARG, "bad image size or pixel buffer (1..65535 per side)")
+ end
+ local o: any = opts or {}
+ local origin = o.origin or "bottom-left"
+ if origin ~= "bottom-left" and origin ~= "top-left" then
+ return nil, Err.new(Err.ARG, "origin must be \"bottom-left\" or \"top-left\"")
+ end
+ local outBpp = srcBpp
+ if srcBpp == 4 then
+ local alpha = o.alpha
+ if alpha == nil then
+ alpha = false
+ for i = 0, w * h - 1 do
+ if readu8(img.pixels, i * 4 + 3) ~= 255 then
+ alpha = true
+ break
+ end
+ end
+ end
+ outBpp = if alpha then 4 else 3
+ end
+ local id = o.id or (img.meta and img.meta.text and img.meta.text.id) or ""
+ if type(id) ~= "string" then
+ id = ""
+ end
+ id = string.sub(id, 1, 255)
+ local rle = o.rle == true
+ local out = buffer.create(18 + #id + w * h * (outBpp + 1) + 26)
+ buffer.writeu8(out, 0, #id)
+ buffer.writeu8(out, 2, (if outBpp == 1 then 3 else 2) + (if rle then 8 else 0))
+ buffer.writeu16(out, 12, w)
+ buffer.writeu16(out, 14, h)
+ buffer.writeu8(out, 16, outBpp * 8)
+ buffer.writeu8(out, 17, (if outBpp == 4 then 8 else 0) + (if origin == "top-left" then 32 else 0))
+ buffer.writestring(out, 18, id)
+ local op = Codec.encode(img.pixels, w, h, srcBpp, outBpp, rle, origin == "top-left", out, 18 + #id)
+ -- TGA 2.0 footer: no extension / developer areas
+ buffer.writeu32(out, op, 0)
+ buffer.writeu32(out, op + 4, 0)
+ buffer.writestring(out, op + 8, FOOTER)
+ op += 26
+ local res = buffer.create(op)
+ buffer.copy(res, 0, out, 0, op)
+ return res, nil
+end
+
+return Tga
diff --git a/src/Formats/image/tiff/Pixels.luau b/src/Formats/image/tiff/Pixels.luau
new file mode 100644
index 0000000..6ae16d4
--- /dev/null
+++ b/src/Formats/image/tiff/Pixels.luau
@@ -0,0 +1,469 @@
+--!strict
+--!native
+--!optimize 2
+-- image/tiff/Pixels: the hot loops of the TIFF codec (native; never throws): PackBits, the horizontal (2) and
+-- floating-point (3) predictors both ways (TIFF 6.0 section 14, Adobe TIFF technote 3; predictor 3 as libtiff's
+-- fpAcc / fpDiff), fill-order bit reversal, and the sample converter from decoded planes to a Types.Image layout.
+-- Callers (image/tiff/init) size every buffer before calling: planes hold h rows of rb bytes plus 8 bytes of slack.
+local readu8, writeu8, readu16, writeu16, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16, buffer.readu32, buffer.writeu32
+local readf32, writef32, readf64 = buffer.readf32, buffer.writef32, buffer.readf64
+local band, bor, rshift, lshift, byteswap = bit32.band, bit32.bor, bit32.rshift, bit32.lshift, bit32.byteswap
+local floor = math.floor
+
+local Pixels = {}
+
+local scratch = buffer.create(8)
+
+-- floats read through their bits: NaN / infinity never load from memory (LuaJIT's FFI would hand back a NaN with an
+-- arbitrary payload, which its NaN-tagged values misread as a table / userdata)
+local function f32(bits: number): number
+ if band(bits, 0x7F800000) == 0x7F800000 then
+ if band(bits, 0x7FFFFF) ~= 0 then
+ return 0 / 0
+ end
+ return if bits >= 0x80000000 then -math.huge else math.huge
+ end
+ writeu32(scratch, 0, bits)
+ return readf32(scratch, 0)
+end
+local function f64(lo: number, hi: number): number
+ if band(hi, 0x7FF00000) == 0x7FF00000 then
+ if band(hi, 0xFFFFF) ~= 0 or lo ~= 0 then
+ return 0 / 0
+ end
+ return if hi >= 0x80000000 then -math.huge else math.huge
+ end
+ writeu32(scratch, 0, lo)
+ writeu32(scratch, 4, hi)
+ return readf64(scratch, 0)
+end
+Pixels.f32 = f32
+Pixels.f64 = f64
+
+-- ------------------------------------------------------------------------------------------------ PackBits
+-- packbits(src, off, len, out, outOff, max) -> bytes written (stops when out or src is exhausted)
+function Pixels.packbits(src: buffer, off: number, len: number, out: buffer, outOff: number, max: number): number
+ local p, e = off, off + len
+ local o, lim = outOff, outOff + max
+ while p < e and o < lim do
+ local n = readu8(src, p)
+ p += 1
+ if n < 128 then
+ local cnt = math.min(n + 1, e - p, lim - o)
+ if cnt <= 0 then
+ break
+ end
+ buffer.copy(out, o, src, p, cnt)
+ p += n + 1
+ o += cnt
+ elseif n > 128 then
+ if p >= e then
+ break
+ end
+ local cnt = math.min(257 - n, lim - o)
+ buffer.fill(out, o, readu8(src, p), cnt)
+ p += 1
+ o += cnt
+ end
+ end
+ return o - outOff
+end
+
+-- packbitsEncode(src, off, len) -> buffer (one row at a time is the caller's business)
+function Pixels.packbitsEncode(src: buffer, off: number, len: number): buffer
+ local out = buffer.create(len + (len + 127) // 128 + 8)
+ local o = 0
+ local p, e = off, off + len
+ while p < e do
+ local run = 1
+ local v = readu8(src, p)
+ while p + run < e and run < 128 and readu8(src, p + run) == v do
+ run += 1
+ end
+ if run >= 3 then
+ writeu8(out, o, 257 - run)
+ writeu8(out, o + 1, v)
+ o += 2
+ p += run
+ else
+ local s = p
+ local n = 0
+ while p < e and n < 128 do
+ if p + 2 < e and readu8(src, p) == readu8(src, p + 1) and readu8(src, p) == readu8(src, p + 2) then
+ break
+ end
+ p += 1
+ n += 1
+ end
+ writeu8(out, o, n - 1)
+ buffer.copy(out, o + 1, src, s, n)
+ o += n + 1
+ end
+ end
+ local r = buffer.create(o)
+ buffer.copy(r, 0, out, 0, o)
+ return r
+end
+
+-- ------------------------------------------------------------------------------------------------ fill order
+local REV = buffer.create(256)
+for i = 0, 255 do
+ local r = 0
+ for k = 0, 7 do
+ if band(i, lshift(1, k)) ~= 0 then
+ r = bor(r, lshift(1, 7 - k))
+ end
+ end
+ writeu8(REV, i, r)
+end
+function Pixels.reverseBits(b: buffer, off: number, len: number)
+ for i = off, off + len - 1 do
+ writeu8(b, i, readu8(REV, readu8(b, i)))
+ end
+end
+
+-- ------------------------------------------------------------------------------------------------ predictors
+-- unpredict2(b, off, rows, rb, stride, bps, le): undo horizontal differencing (bps 8, 16 or 32; others untouched)
+function Pixels.unpredict2(b: buffer, off: number, rows: number, rb: number, stride: number, bps: number, le: boolean)
+ for r = 0, rows - 1 do
+ local base = off + r * rb
+ if bps == 8 then
+ for i = base + stride, base + rb - 1 do
+ writeu8(b, i, band(readu8(b, i) + readu8(b, i - stride), 255))
+ end
+ elseif bps == 16 then
+ local n = rb // 2
+ for k = stride, n - 1 do
+ local i = base + k * 2
+ local j = i - stride * 2
+ if le then
+ writeu16(b, i, band(readu16(b, i) + readu16(b, j), 0xFFFF))
+ else
+ local v = readu8(b, i) * 256 + readu8(b, i + 1) + readu8(b, j) * 256 + readu8(b, j + 1)
+ writeu8(b, i, band(rshift(v, 8), 255))
+ writeu8(b, i + 1, band(v, 255))
+ end
+ end
+ elseif bps == 32 then
+ local n = rb // 4
+ for k = stride, n - 1 do
+ local i = base + k * 4
+ local j = i - stride * 4
+ if le then
+ writeu32(b, i, (readu32(b, i) + readu32(b, j)) % 4294967296)
+ else
+ writeu32(b, i, byteswap((byteswap(readu32(b, i)) + byteswap(readu32(b, j))) % 4294967296))
+ end
+ end
+ end
+ end
+end
+
+-- predict2(b, off, rows, rb, stride, bps): apply horizontal differencing to little-endian samples (8 / 16 bit)
+function Pixels.predict2(b: buffer, off: number, rows: number, rb: number, stride: number, bps: number)
+ for r = 0, rows - 1 do
+ local base = off + r * rb
+ if bps == 8 then
+ for i = base + rb - 1, base + stride, -1 do
+ writeu8(b, i, band(readu8(b, i) - readu8(b, i - stride), 255))
+ end
+ elseif bps == 16 then
+ for k = rb // 2 - 1, stride, -1 do
+ local i = base + k * 2
+ writeu16(b, i, band(readu16(b, i) - readu16(b, i - stride * 2), 0xFFFF))
+ end
+ end
+ end
+end
+
+-- unpredict3(b, off, rows, rb, bytes, stride, tmp): undo the floating-point predictor; the samples come out little
+-- endian whatever the file's byte order (libtiff fpAcc). tmp holds at least rb bytes.
+function Pixels.unpredict3(b: buffer, off: number, rows: number, rb: number, bytes: number, stride: number, tmp: buffer)
+ local wc = rb // bytes
+ for r = 0, rows - 1 do
+ local base = off + r * rb
+ for i = base + stride, base + rb - 1 do
+ writeu8(b, i, band(readu8(b, i) + readu8(b, i - stride), 255))
+ end
+ buffer.copy(tmp, 0, b, base, rb)
+ for c = 0, wc - 1 do
+ for k = 0, bytes - 1 do
+ writeu8(b, base + c * bytes + k, readu8(tmp, (bytes - k - 1) * wc + c))
+ end
+ end
+ end
+end
+
+-- predict3(b, off, rows, rb, bytes, stride, tmp): the floating-point predictor on little-endian samples (fpDiff)
+function Pixels.predict3(b: buffer, off: number, rows: number, rb: number, bytes: number, stride: number, tmp: buffer)
+ local wc = rb // bytes
+ for r = 0, rows - 1 do
+ local base = off + r * rb
+ for c = 0, wc - 1 do
+ for k = 0, bytes - 1 do
+ writeu8(tmp, (bytes - k - 1) * wc + c, readu8(b, base + c * bytes + k))
+ end
+ end
+ buffer.copy(b, base, tmp, 0, rb)
+ for i = base + rb - 1, base + stride, -1 do
+ writeu8(b, i, band(readu8(b, i) - readu8(b, i - stride), 255))
+ end
+ end
+end
+
+-- ------------------------------------------------------------------------------------------------ samples
+local function half(h: number): number
+ local s = if h >= 0x8000 then -1 else 1
+ local e = band(rshift(h, 10), 31)
+ local m = band(h, 1023)
+ if e == 0 then
+ return s * m * 2 ^ -24
+ elseif e == 31 then
+ return if m == 0 then s * math.huge else 0 / 0
+ end
+ return s * (1 + m / 1024) * 2 ^ (e - 15)
+end
+
+export type Params = {
+ planes: { buffer },
+ rb: number, -- bytes per row in each plane
+ chunky: boolean,
+ w: number,
+ h: number,
+ spp: number,
+ bps: number,
+ sfmt: number, -- 1 uint, 2 int, 3 float
+ le: boolean,
+ photo: number, -- 0 min-is-white, 1 min-is-black, 2 RGB, 3 palette, 5 CMYK
+ alpha: number, -- sample index of the alpha channel, -1 = none
+ assoc: boolean, -- premultiplied alpha (undone)
+ cmap: buffer?, -- palette: 3 * 2^bps u16 (red block, green block, blue block)
+ kind: string, -- the output pixel format
+ out: buffer,
+}
+
+-- the common 8-bit chunky cases without per-sample dispatch; false when P is not one of them
+local function fast(P: Params): boolean
+ if not P.chunky or P.bps ~= 8 or P.sfmt ~= 1 or P.assoc then
+ return false
+ end
+ local b, rb, w, h, spp, alpha, kind, out = P.planes[1], P.rb, P.w, P.h, P.spp, P.alpha, P.kind, P.out
+ local o = 0
+ if P.photo == 2 and spp >= 3 and (kind == "rgba8" or kind == "rgb8") then
+ local four = kind == "rgba8"
+ for y = 0, h - 1 do
+ local p = y * rb
+ for _ = 0, w - 1 do
+ writeu8(out, o, readu8(b, p))
+ writeu8(out, o + 1, readu8(b, p + 1))
+ writeu8(out, o + 2, readu8(b, p + 2))
+ if four then
+ writeu8(out, o + 3, if alpha >= 0 then readu8(b, p + alpha) else 255)
+ o += 4
+ else
+ o += 3
+ end
+ p += spp
+ end
+ end
+ return true
+ elseif (P.photo == 1 or P.photo == 0) and (kind == "rgba8" or kind == "gray8" or kind == "graya8") then
+ local inv = if P.photo == 0 then 255 else 0
+ for y = 0, h - 1 do
+ local p = y * rb
+ for _ = 0, w - 1 do
+ local v = math.abs(inv - readu8(b, p))
+ if kind == "gray8" then
+ writeu8(out, o, v)
+ o += 1
+ elseif kind == "graya8" then
+ writeu8(out, o, v)
+ writeu8(out, o + 1, if alpha >= 0 then readu8(b, p + alpha) else 255)
+ o += 2
+ else
+ writeu32(out, o, v * 0x10101 + (if alpha >= 0 then readu8(b, p + alpha) else 255) * 0x1000000)
+ o += 4
+ end
+ p += spp
+ end
+ end
+ return true
+ end
+ return false
+end
+
+-- convert(P): every pixel into P.out in P.kind's layout
+function Pixels.convert(P: Params)
+ if fast(P) then
+ return
+ end
+ local planes, rb, chunky, w, h, spp, bps, sfmt, le = P.planes, P.rb, P.chunky, P.w, P.h, P.spp, P.bps, P.sfmt, P.le
+ local photo, alpha, assoc, cmap, kind, out = P.photo, P.alpha, P.assoc, P.cmap, P.kind, P.out
+ local maxv = 2 ^ math.min(bps, 32) - 1
+ local float = sfmt == 3
+ local signed = sfmt == 2
+ local cmapN = 2 ^ math.min(bps, 16)
+ -- raw sample s of pixel x in the row starting at byte ro of its plane
+ local function raw(s: number, x: number, row: number): number
+ local b, i
+ if chunky then
+ b, i = planes[1], x * spp + s
+ else
+ b, i = planes[s + 1], x
+ end
+ local ro = row * rb
+ if bps == 8 then
+ local v = readu8(b, ro + i)
+ return if signed then (v + 128) % 256 else v
+ elseif bps == 16 then
+ local p = ro + i * 2
+ local v = if le then readu16(b, p) else readu8(b, p) * 256 + readu8(b, p + 1)
+ if float then
+ return half(v)
+ end
+ return if signed then (v + 32768) % 65536 else v
+ elseif bps == 32 then
+ local p = ro + i * 4
+ if float then
+ return f32(if le then readu32(b, p) else byteswap(readu32(b, p)))
+ end
+ local v = if le then readu32(b, p) else byteswap(readu32(b, p))
+ return if signed then (v + 2147483648) % 4294967296 else v
+ elseif bps == 64 then
+ local p = ro + i * 8
+ if le then
+ return f64(readu32(b, p), readu32(b, p + 4))
+ end
+ return f64(byteswap(readu32(b, p + 4)), byteswap(readu32(b, p)))
+ else
+ -- any other depth (1..31): MSB-first bit fields
+ local bit = i * bps
+ local v = 0
+ local need = bps
+ local p = ro + rshift(bit, 3)
+ local sh = band(bit, 7)
+ local cur = band(readu8(b, p), rshift(255, sh))
+ local avail = 8 - sh
+ while need > 0 do
+ if need >= avail then
+ v = v * 2 ^ avail + cur
+ need -= avail
+ p += 1
+ cur = if need > 0 then readu8(b, p) else 0
+ avail = 8
+ else
+ v = v * 2 ^ need + rshift(cur, avail - need)
+ need = 0
+ end
+ end
+ return v
+ end
+ end
+ -- normalised 0..1 (floats as stored)
+ local function norm(s: number, x: number, row: number): number
+ local v = raw(s, x, row)
+ if float then
+ return v
+ end
+ return v / maxv
+ end
+ local o = 0
+ local is8 = kind == "rgba8" or kind == "rgb8" or kind == "gray8" or kind == "graya8"
+ local is16 = kind == "rgba16" or kind == "gray16"
+ local nch = if kind == "rgba8" or kind == "rgba16" or kind == "rgbaf32" then 4 elseif kind == "rgb8" then 3 elseif kind == "graya8" then 2 else 1
+ for y = 0, h - 1 do
+ for x = 0, w - 1 do
+ local r, g, bl, a
+ if photo == 3 then
+ local idx = raw(0, x, y)
+ if cmap and idx < cmapN then
+ r = readu16(cmap, idx * 2) / 65535
+ g = readu16(cmap, (cmapN + idx) * 2) / 65535
+ bl = readu16(cmap, (2 * cmapN + idx) * 2) / 65535
+ else
+ r, g, bl = 0, 0, 0
+ end
+ elseif photo == 2 then
+ r, g, bl = norm(0, x, y), norm(1, x, y), norm(2, x, y)
+ elseif photo == 5 then
+ local c, m, ye, k = norm(0, x, y), norm(1, x, y), norm(2, x, y), norm(3, x, y)
+ r, g, bl = (1 - c) * (1 - k), (1 - m) * (1 - k), (1 - ye) * (1 - k)
+ else
+ local v = norm(0, x, y)
+ if photo == 0 then
+ v = 1 - v
+ end
+ r, g, bl = v, v, v
+ end
+ if alpha >= 0 then
+ a = norm(alpha, x, y)
+ if assoc then
+ if a > 0 then
+ r, g, bl = math.min(r / a, 1), math.min(g / a, 1), math.min(bl / a, 1)
+ else
+ r, g, bl = 0, 0, 0
+ end
+ end
+ else
+ a = 1
+ end
+ if is8 then
+ if r ~= r then
+ r = 0
+ end
+ if g ~= g then
+ g = 0
+ end
+ if bl ~= bl then
+ bl = 0
+ end
+ if a ~= a then
+ a = 0
+ end
+ local R = floor(math.clamp(r, 0, 1) * 255 + 0.5)
+ if nch == 1 then
+ writeu8(out, o, R)
+ elseif nch == 2 then
+ writeu8(out, o, R)
+ writeu8(out, o + 1, floor(math.clamp(a, 0, 1) * 255 + 0.5))
+ else
+ writeu8(out, o, R)
+ writeu8(out, o + 1, floor(math.clamp(g, 0, 1) * 255 + 0.5))
+ writeu8(out, o + 2, floor(math.clamp(bl, 0, 1) * 255 + 0.5))
+ if nch == 4 then
+ writeu8(out, o + 3, floor(math.clamp(a, 0, 1) * 255 + 0.5))
+ end
+ end
+ o += nch
+ elseif is16 then
+ if r ~= r then
+ r = 0
+ end
+ if g ~= g then
+ g = 0
+ end
+ if bl ~= bl then
+ bl = 0
+ end
+ if a ~= a then
+ a = 0
+ end
+ writeu16(out, o, floor(math.clamp(r, 0, 1) * 65535 + 0.5))
+ if nch == 4 then
+ writeu16(out, o + 2, floor(math.clamp(g, 0, 1) * 65535 + 0.5))
+ writeu16(out, o + 4, floor(math.clamp(bl, 0, 1) * 65535 + 0.5))
+ writeu16(out, o + 6, floor(math.clamp(a, 0, 1) * 65535 + 0.5))
+ end
+ o += nch * 2
+ else
+ writef32(out, o, r)
+ writef32(out, o + 4, g)
+ writef32(out, o + 8, bl)
+ writef32(out, o + 12, a)
+ o += 16
+ end
+ end
+ end
+end
+
+return Pixels
diff --git a/src/Formats/image/tiff/init.luau b/src/Formats/image/tiff/init.luau
new file mode 100644
index 0000000..81dca4b
--- /dev/null
+++ b/src/Formats/image/tiff/init.luau
@@ -0,0 +1,841 @@
+--!strict
+-- image/tiff: TIFF 6.0 (+ Adobe technote 3 floating point, BigTIFF). New code from the TIFF 6.0 specification.
+-- Decode: both byte orders, classic and BigTIFF, strips and tiles, planar configuration 1 and 2, compression none /
+-- LZW (codecs/Lzw, also old-style) / Deflate (8 and 32946, codecs/Deflate) / PackBits, JPEG (7) through the api's
+-- opts.decodeImage hook (JPEGTables stitched to each strip / tile), predictors 2 (8 / 16 / 32-bit) and 3 (float),
+-- 1..32-bit unsigned / signed integer and 16 / 32 / 64-bit float samples, min-is-white / min-is-black, RGB, palette,
+-- CMYK (naive conversion), extra samples (associated alpha is un-premultiplied), fill order 2, every page as
+-- img.frames, resolution (meta.dpi), ICC (meta.icc). Decodes to rgba8, or with opts.native to the nearest standard
+-- layout (gray8, gray16, graya8, rgb8, rgba8, rgba16, rgbaf32).
+-- Encode: rgba8 / rgb8 / gray8 / graya8 / gray16 / rgba16 / rgbaf32 as the matching TIFF layout, compression none /
+-- deflate / lzw / packbits with predictor 2 (integers) or 3 (floats), strips, multi-page from img.frames.
+-- Not supported: old-style JPEG (6), CCITT fax (2, 3, 4), uncompressed YCbCr with subsampling, CIELab, JBIG.
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Types = require("@formats/Types")
+local Deflate = require("@formats/codecs/Deflate")
+local Lzw = require("@formats/codecs/Lzw")
+local Pixels = require("@formats/image/tiff/Pixels")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Tiff = {
+ name = "tiff",
+ category = "image",
+ extensions = { "tif", "tiff" },
+ mime = { "image/tiff" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/Deflate", "codecs/Lzw" },
+ caps = { decode = true, encode = true, alpha = true, pages = true, depths = { 1, 2, 4, 8, 16, 32 }, float = true },
+}
+
+-- ------------------------------------------------------------------------------------------------ types
+export type DecodeOptions = {
+ native: boolean?, -- keep the source layout (gray8 / gray16 / graya8 / rgb8 / rgba8 / rgba16 / rgbaf32); default rgba8
+ maxPixels: number?, -- per page (default 2^26)
+ maxPages: number?, -- pages decoded into img.frames (default 1024)
+ page: number?, -- decode only this page (1-based)
+ decodeImage: ((buffer) -> (any, any))?, -- the api's hook, for JPEG-compressed pages
+}
+export type EncodeOptions = {
+ compression: ("none" | "deflate" | "lzw" | "packbits")?, -- default "deflate"
+ predictor: boolean?, -- horizontal / float predictor with deflate and lzw (default true)
+ level: number?, -- deflate level 0..9 (default 6)
+ rowsPerStrip: number?, -- default: about 64 KB per strip
+}
+
+-- ------------------------------------------------------------------------------------------------ constants
+local TYPE_SIZE = { [1] = 1, [2] = 1, [3] = 2, [4] = 4, [5] = 8, [6] = 1, [7] = 1, [8] = 2, [9] = 4, [10] = 8, [11] = 4, [12] = 8, [13] = 4, [16] = 8, [17] = 8, [18] = 8 }
+local COMPRESSION = { [1] = "none", [5] = "lzw", [8] = "deflate", [32946] = "deflate", [32773] = "packbits", [7] = "jpeg" }
+local PHOTOMETRIC = { [0] = "miniswhite", [1] = "minisblack", [2] = "rgb", [3] = "palette", [5] = "cmyk", [6] = "ycbcr" }
+local TWO32 = 4294967296
+
+local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Tiff.sniff(r: Bytes.Reader): number
+ local s = r:peek(4)
+ if s == "II*\0" or s == "MM\0*" or s == "II+\0" or s == "MM\0+" then
+ return 1
+ end
+ return 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+type Entry = { tag: number, typ: number, count: number, at: number }
+type Ctx = { b: buffer, base: number, limit: number, le: boolean, big: boolean }
+
+local function u16(c: Ctx, at: number): number
+ if at < c.base or at + 2 > c.limit then
+ return 0
+ end
+ return if c.le then readu16(c.b, at) else readu8(c.b, at) * 256 + readu8(c.b, at + 1)
+end
+local function u32(c: Ctx, at: number): number
+ if at < c.base or at + 4 > c.limit then
+ return 0
+ end
+ local v = readu32(c.b, at)
+ return if c.le then v else bit32.byteswap(v)
+end
+local function u64(c: Ctx, at: number): number
+ local lo, hi = u32(c, at), u32(c, at + 4)
+ if not c.le then
+ lo, hi = hi, lo
+ end
+ return hi * TWO32 + lo
+end
+local function off(c: Ctx, at: number): number
+ return if c.big then u64(c, at) else u32(c, at)
+end
+
+-- values(c, e, max) -> the entry's numbers (rationals divided) | nil when out of range / too many
+local function values(c: Ctx, e: Entry?, max: number?): { number }?
+ if not e then
+ return nil
+ end
+ local size = TYPE_SIZE[e.typ]
+ if not size or e.count > (max or 1e7) or e.at < c.base or e.at + e.count * size > c.limit then
+ return nil
+ end
+ local out = table.create(e.count, 0)
+ local b = c.b
+ for i = 0, e.count - 1 do
+ local p = e.at + i * size
+ local t = e.typ
+ local v
+ if t == 1 or t == 2 or t == 7 then
+ v = readu8(b, p)
+ elseif t == 6 then
+ v = buffer.readi8(b, p)
+ elseif t == 3 then
+ v = u16(c, p)
+ elseif t == 8 then
+ v = u16(c, p)
+ if v >= 32768 then
+ v -= 65536
+ end
+ elseif t == 4 or t == 13 then
+ v = u32(c, p)
+ elseif t == 9 then
+ v = u32(c, p)
+ if v >= 2147483648 then
+ v -= TWO32
+ end
+ elseif t == 5 or t == 10 then
+ local n, d = u32(c, p), u32(c, p + 4)
+ if t == 10 then
+ if n >= 2147483648 then
+ n -= TWO32
+ end
+ if d >= 2147483648 then
+ d -= TWO32
+ end
+ end
+ v = if d ~= 0 then n / d else 0
+ elseif t == 11 then
+ v = Pixels.f32(u32(c, p))
+ elseif t == 12 then
+ local lo, hi = u32(c, p), u32(c, p + 4)
+ if not c.le then
+ lo, hi = hi, lo
+ end
+ v = Pixels.f64(lo, hi)
+ else
+ v = u64(c, p)
+ end
+ out[i + 1] = v
+ end
+ return out
+end
+
+local function one(c: Ctx, e: Entry?, default: number): number
+ local v = values(c, e, 64)
+ return if v and v[1] then v[1] else default
+end
+
+-- the IFD at absolute offset p: { [tag] = Entry }, next IFD offset (absolute, 0 = none) | nil, Err
+local function readIfd(c: Ctx, p: number): ({ [number]: Entry }?, number, Err.Err?)
+ local esize = if c.big then 20 else 12
+ local hsize = if c.big then 8 else 2
+ if p < c.base or p + hsize > c.limit then
+ return nil, 0, Err.new(Err.TRUNCATED, "IFD past the end", p)
+ end
+ local n = if c.big then u64(c, p) else u16(c, p)
+ if n == 0 or p + hsize + n * esize > c.limit then
+ return nil, 0, Err.new(if n == 0 then Err.CORRUPT else Err.TRUNCATED, "bad IFD entry count " .. n, p)
+ end
+ local entries: { [number]: Entry } = {}
+ for i = 0, n - 1 do
+ local q = p + hsize + i * esize
+ local tag, typ = u16(c, q), u16(c, q + 2)
+ local count = if c.big then u64(c, q + 4) else u32(c, q + 4)
+ local vat = q + (if c.big then 12 else 8)
+ local size = TYPE_SIZE[typ]
+ if size then
+ local at = vat
+ if count * size > (if c.big then 8 else 4) then
+ at = c.base + off(c, vat)
+ end
+ entries[tag] = { tag = tag, typ = typ, count = count, at = at }
+ end
+ end
+ local nq = p + hsize + n * esize
+ local nextOff = 0
+ if nq + (if c.big then 8 else 4) <= c.limit then
+ nextOff = off(c, nq)
+ end
+ return entries, if nextOff > 0 then c.base + nextOff else 0, nil
+end
+
+local function bytesOf(c: Ctx, e: Entry?, max: number): buffer?
+ if not e or e.at < c.base then
+ return nil
+ end
+ local size = TYPE_SIZE[e.typ] or 1
+ local n = e.count * size
+ if n > max or e.at + n > c.limit then
+ return nil
+ end
+ local x = buffer.create(n)
+ buffer.copy(x, 0, c.b, e.at, n)
+ return x
+end
+
+-- decompress one chunk at [p, p + len) into out[o, o + size): bytes produced | nil, Err
+local function inflateChunk(c: Ctx, comp: number, p: number, len: number, out: buffer, o: number, size: number, rev: boolean): (number?, Err.Err?)
+ if p < c.base or len < 0 or p + len > c.limit then
+ -- a chunk past the end: keep what exists (truncated files)
+ len = math.max(0, math.min(len, c.limit - p))
+ if p < c.base or p >= c.limit then
+ return 0
+ end
+ end
+ local src, sp = c.b, p
+ if rev then
+ src = buffer.create(len)
+ buffer.copy(src, 0, c.b, p, len)
+ Pixels.reverseBits(src, 0, len)
+ sp = 0
+ end
+ if comp == 1 then
+ local n = math.min(len, size)
+ buffer.copy(out, o, src, sp, n)
+ return n
+ elseif comp == 5 then
+ local n = Lzw.decode(src, sp, len, out, o, size, "tiff")
+ return n
+ elseif comp == 8 or comp == 32946 then
+ local raw = Deflate.zlib(src, sp, len, size)
+ if not raw then
+ raw = Deflate.zlib(src, sp, len) or Deflate.inflate(src, sp, len)
+ end
+ if not raw then
+ return nil, Err.new(Err.CORRUPT, "bad deflate data", p)
+ end
+ local n = math.min(buffer.len(raw :: buffer), size)
+ buffer.copy(out, o, raw :: buffer, 0, n)
+ return n
+ elseif comp == 32773 then
+ return Pixels.packbits(src, sp, len, out, o, size)
+ end
+ return nil, Err.new(Err.UNSUPPORTED, "compression " .. comp)
+end
+
+type Page = { image: Types.Image, info: { [string]: any } }
+
+local function decodePage(c: Ctx, t: { [number]: Entry }, opts: DecodeOptions?): (Types.Image?, Err.Err?)
+ local w, h = one(c, t[256], 0), one(c, t[257], 0)
+ if w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 then
+ return nil, Err.new(Err.CORRUPT, "bad image size")
+ end
+ local maxPixels = opts and opts.maxPixels or 2 ^ 26
+ if w * h > maxPixels then
+ return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
+ end
+ local spp = one(c, t[277], 1)
+ local bpsList = values(c, t[258], 64) or { 1 }
+ local bps = bpsList[1] or 1
+ for i = 2, math.min(#bpsList, spp) do
+ if bpsList[i] ~= bps then
+ return nil, Err.new(Err.UNSUPPORTED, "different bit depths per sample")
+ end
+ end
+ local comp = one(c, t[259], 1)
+ local photo = one(c, t[262], if spp >= 3 then 2 else 1)
+ local planar = one(c, t[284], 1)
+ local predictor = one(c, t[317], 1)
+ local sfmt = one(c, t[339], 1)
+ local fill = one(c, t[266], 1)
+ if spp < 1 or spp > 16 or bps < 1 or bps > 64 then
+ return nil, Err.new(Err.UNSUPPORTED, string.format("%d samples of %d bits", spp, bps))
+ end
+ if sfmt == 3 and bps ~= 16 and bps ~= 32 and bps ~= 64 then
+ return nil, Err.new(Err.UNSUPPORTED, bps .. "-bit floats")
+ end
+ if sfmt ~= 3 and bps > 32 then
+ return nil, Err.new(Err.UNSUPPORTED, bps .. "-bit integers")
+ end
+ if not COMPRESSION[comp] then
+ local names = { [2] = "CCITT RLE", [3] = "CCITT fax 3", [4] = "CCITT fax 4", [6] = "old-style JPEG", [34712] = "JPEG 2000", [34925] = "LZMA", [50000] = "Zstandard", [50001] = "WebP" }
+ return nil, Err.new(Err.UNSUPPORTED, (names[comp] or "compression") .. " (" .. comp .. ")")
+ end
+ if not PHOTOMETRIC[photo] then
+ return nil, Err.new(Err.UNSUPPORTED, "photometric interpretation " .. photo)
+ end
+ local cc = if photo == 2 or photo == 6 then 3 elseif photo == 5 then 4 else 1
+ if spp < cc then
+ return nil, Err.new(Err.CORRUPT, string.format("%d samples for photometric %d", spp, photo))
+ end
+ if photo == 5 and one(c, t[332], 1) ~= 1 then
+ return nil, Err.new(Err.UNSUPPORTED, "separated image that is not CMYK")
+ end
+ local extra = values(c, t[338], 16) or {}
+ local alpha, assoc = -1, false
+ if spp > cc then
+ local kind = extra[1] or 0
+ alpha = cc
+ assoc = kind == 1
+ end
+ local chunky = planar ~= 2 or spp == 1
+ local tiled = t[322] ~= nil
+ local cw = if tiled then one(c, t[322], 0) else w
+ local ch = if tiled then one(c, t[323], 0) else math.min(one(c, t[278], h), h)
+ if cw < 1 or ch < 1 or cw > 65536 or (tiled and ch > 65536) then
+ return nil, Err.new(Err.CORRUPT, "bad tile / strip size")
+ end
+ if ch > h and not tiled then
+ ch = h
+ end
+ local pspp = if chunky then spp else 1 -- samples per pixel in one plane
+ local nplanes = if chunky then 1 else spp
+ local rb = math.ceil(w * pspp * bps / 8) -- bytes per image row in a plane
+ local crb = math.ceil(cw * pspp * bps / 8) -- bytes per chunk row
+ if rb * h * nplanes > 2 ^ 30 or crb * ch > 2 ^ 30 then
+ return nil, Err.new(Err.LIMIT, "decoded data over 1 GB")
+ end
+ local across = if tiled then math.ceil(w / cw) else 1
+ local down = math.ceil(h / ch)
+ local perPlane = across * down
+ local offs = values(c, if tiled then t[324] else t[273], 2 ^ 24)
+ local lens = values(c, if tiled then t[325] else t[279], 2 ^ 24)
+ if not offs or #offs < perPlane * nplanes then
+ return nil, Err.new(Err.CORRUPT, "missing or short strip / tile offsets")
+ end
+ local planes = table.create(nplanes)
+ for i = 1, nplanes do
+ planes[i] = buffer.create(rb * h + 8)
+ end
+ local tmp = buffer.create(crb * ch + 8)
+ local ftmp = buffer.create(math.max(rb, crb) + 8)
+ local le = c.le
+ local bytesPer = bps // 8
+ local hook = opts and opts.decodeImage
+ local jpegTables = if comp == 7 then bytesOf(c, t[347], 1 * 2 ^ 20) else nil
+ local jpegPixels: buffer? = nil
+ if comp == 7 then
+ if type(hook) ~= "function" then
+ return nil, Err.new(Err.UNSUPPORTED, "JPEG-compressed TIFF needs opts.decodeImage (F.load supplies it)")
+ end
+ jpegPixels = buffer.create(w * h * 4)
+ end
+ for pl = 0, nplanes - 1 do
+ for ty = 0, down - 1 do
+ for tx = 0, across - 1 do
+ local idx = pl * perPlane + ty * across + tx
+ local p = c.base + offs[idx + 1]
+ local len = if lens and lens[idx + 1] then lens[idx + 1] else c.limit - p
+ local rows = if tiled then ch else math.min(ch, h - ty * ch)
+ local size = rows * crb
+ if comp == 7 then
+ -- JPEGTables (SOI .. EOI) + the chunk (SOI .. EOI): one stream without the inner EOI / SOI
+ if p < c.base or p + len > c.limit or len < 4 then
+ return nil, Err.new(Err.TRUNCATED, "JPEG chunk past the end", p)
+ end
+ local tl = if jpegTables and buffer.len(jpegTables) >= 4 then buffer.len(jpegTables) - 2 else 0
+ local s = buffer.create(tl + len - (if tl > 0 then 2 else 0))
+ if tl > 0 then
+ buffer.copy(s, 0, jpegTables :: buffer, 0, tl)
+ buffer.copy(s, tl, c.b, p + 2, len - 2)
+ else
+ buffer.copy(s, 0, c.b, p, len)
+ end
+ local ok, img, herr = pcall(hook :: any, s)
+ if not ok or type(img) ~= "table" or img.format ~= "rgba8" then
+ return nil, if ok and herr then herr else Err.new(Err.CORRUPT, "embedded JPEG: " .. tostring(if ok then herr else img))
+ end
+ local x0, y0 = tx * cw, ty * ch
+ local cwid = math.min(cw, w - x0, img.width)
+ for yy = 0, math.min(rows, h - y0, img.height) - 1 do
+ buffer.copy(jpegPixels :: buffer, ((y0 + yy) * w + x0) * 4, img.pixels, yy * img.width * 4, cwid * 4)
+ end
+ continue
+ end
+ buffer.fill(tmp, 0, 0, size)
+ local _, derr = inflateChunk(c, comp, p, len, tmp, 0, size, fill == 2)
+ if derr then
+ return nil, derr
+ end
+ if predictor == 2 then
+ Pixels.unpredict2(tmp, 0, rows, crb, pspp, bps, le)
+ elseif predictor == 3 and bytesPer >= 2 and crb % bytesPer == 0 then
+ Pixels.unpredict3(tmp, 0, rows, crb, bytesPer, pspp, ftmp)
+ end
+ -- into the plane
+ local plane = planes[pl + 1]
+ local x0b = math.floor(tx * cw * pspp * bps / 8)
+ local cols = math.min(cw, w - tx * cw)
+ local nb = math.min(math.ceil(cols * pspp * bps / 8), rb - x0b)
+ for yy = 0, rows - 1 do
+ local y = ty * ch + yy
+ if y >= h then
+ break
+ end
+ buffer.copy(plane, y * rb + x0b, tmp, yy * crb, nb)
+ end
+ end
+ end
+ end
+ local floatOut = sfmt == 3
+ if predictor == 3 and floatOut then
+ le = true -- fpAcc leaves the samples little endian
+ end
+ local colorType = PHOTOMETRIC[photo]
+ -- the output layout
+ local kind = "rgba8"
+ if opts and opts.native and comp ~= 7 then
+ if photo == 3 or photo == 5 then
+ kind = "rgba8"
+ elseif floatOut then
+ kind = "rgbaf32"
+ elseif cc == 1 then
+ if alpha >= 0 then
+ kind = if bps <= 8 then "graya8" else "rgba16"
+ else
+ kind = if bps <= 8 then "gray8" else "gray16"
+ end
+ else
+ if alpha >= 0 then
+ kind = if bps <= 8 then "rgba8" else "rgba16"
+ else
+ kind = if bps <= 8 then "rgb8" else "rgba16"
+ end
+ end
+ end
+ local img = Types.Image.new(w, h, kind :: any)
+ if comp == 7 then
+ img.pixels = jpegPixels :: buffer
+ else
+ if photo == 6 then
+ return nil, Err.new(Err.UNSUPPORTED, "uncompressed YCbCr")
+ end
+ local cmap = nil
+ if photo == 3 then
+ local n = 3 * 2 ^ math.min(bps, 16)
+ local cv = values(c, t[320], n)
+ if not cv or #cv < n then
+ return nil, Err.new(Err.CORRUPT, "palette image without a full ColorMap")
+ end
+ cmap = buffer.create(n * 2)
+ for i = 1, n do
+ buffer.writeu16(cmap, (i - 1) * 2, math.clamp(cv[i], 0, 65535))
+ end
+ end
+ Pixels.convert({
+ planes = planes,
+ rb = rb,
+ chunky = chunky,
+ w = w,
+ h = h,
+ spp = spp,
+ bps = bps,
+ sfmt = sfmt,
+ le = le,
+ photo = photo,
+ alpha = alpha,
+ assoc = assoc,
+ cmap = cmap,
+ kind = kind,
+ out = img.pixels,
+ })
+ end
+ local xr, yr = one(c, t[282], 0), one(c, t[283], 0)
+ if xr > 0 and yr > 0 then
+ local unit = one(c, t[296], 2)
+ local k = if unit == 3 then 2.54 else 1
+ if unit ~= 1 then
+ img.meta.dpi = { x = xr * k, y = yr * k }
+ end
+ end
+ img.meta.icc = bytesOf(c, t[34675], 2 ^ 26)
+ local function ascii(tag: number): string?
+ local v = bytesOf(c, t[tag], 65536)
+ if not v then
+ return nil
+ end
+ local s = buffer.tostring(v)
+ local z = string.find(s, "\0", 1, true)
+ return if z then string.sub(s, 1, z - 1) else s
+ end
+ local text = {}
+ for tag, key in { [270] = "description", [305] = "software", [306] = "datetime", [315] = "artist", [33432] = "copyright" } do
+ local s = ascii(tag)
+ if s and s ~= "" then
+ text[key] = s
+ end
+ end
+ if next(text) then
+ img.meta.text = text
+ end
+ img.meta.source = {
+ format = "tiff",
+ bitDepth = bps,
+ colorType = colorType,
+ photometric = photo,
+ samples = spp,
+ sampleFormat = if sfmt == 3 then "float" elseif sfmt == 2 then "int" else "uint",
+ compression = COMPRESSION[comp],
+ predictor = predictor,
+ planar = planar,
+ tiled = tiled,
+ alpha = if alpha >= 0 then (if assoc then "associated" else "unassociated") else nil,
+ bigtiff = c.big,
+ byteOrder = if c.le then "II" else "MM",
+ }
+ return img, nil
+end
+
+-- pages(r) -> the IFD tables of every page (and the context) | nil, Err
+local function pages(r: Bytes.Reader, maxPages: number): ({ { [number]: Entry } }?, Ctx?, Err.Err?)
+ local b, base, limit = r.buf, r.base, r.limit
+ if limit - base < 8 then
+ return nil, nil, Err.new(Err.TRUNCATED, "short header")
+ end
+ local bo = buffer.readstring(b, base, 2)
+ if bo ~= "II" and bo ~= "MM" then
+ return nil, nil, Err.new(Err.CORRUPT, "bad byte order mark")
+ end
+ local c: Ctx = { b = b, base = base, limit = limit, le = bo == "II", big = false }
+ local magic = u16(c, base + 2)
+ local first
+ if magic == 42 then
+ first = u32(c, base + 4)
+ elseif magic == 43 then
+ if limit - base < 16 or u16(c, base + 4) ~= 8 then
+ return nil, nil, Err.new(Err.CORRUPT, "bad BigTIFF header")
+ end
+ c.big = true
+ first = u64(c, base + 8)
+ else
+ return nil, nil, Err.new(Err.CORRUPT, "bad magic " .. magic)
+ end
+ local list = {}
+ local seen = {}
+ local p = base + first
+ while p > 0 and #list < maxPages do
+ if seen[p] then
+ break -- an IFD loop
+ end
+ seen[p] = true
+ local t, nextP, err = readIfd(c, p)
+ if not t then
+ if #list == 0 then
+ return nil, nil, err
+ end
+ break
+ end
+ table.insert(list, t)
+ p = nextP
+ end
+ return list, c, nil
+end
+
+-- info(r) -> { pages, width, height, bitDepth, samples, compression } of page 1 | nil, Err
+function Tiff.info(r: Bytes.Reader): ({ [string]: any }?, Err.Err?)
+ local list, c, err = pages(r, 1024)
+ if not list or not c then
+ return nil, err
+ end
+ local t = list[1]
+ return {
+ pages = #list,
+ width = one(c, t[256], 0),
+ height = one(c, t[257], 0),
+ bitDepth = one(c, t[258], 1),
+ samples = one(c, t[277], 1),
+ compression = COMPRESSION[one(c, t[259], 1)] or tostring(one(c, t[259], 1)),
+ photometric = PHOTOMETRIC[one(c, t[262], 1)],
+ bigtiff = c.big,
+ },
+ nil
+end
+
+function Tiff.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
+ local maxPages = opts and opts.maxPages or 1024
+ local list, c, err = pages(r, if opts and opts.page then math.max(1, opts.page) else maxPages)
+ if not list or not c then
+ return nil, err
+ end
+ if opts and opts.page then
+ local t = list[opts.page]
+ if not t then
+ return nil, Err.new(Err.ARG, "no page " .. tostring(opts.page))
+ end
+ local img, perr = decodePage(c, t, opts)
+ if img then
+ img.meta.source.pages = #list
+ end
+ return img, perr
+ end
+ local first: Types.Image? = nil
+ local frames = {}
+ for i, t in list do
+ -- reduced-resolution subfiles (thumbnails) after page 1 are skipped
+ local sub = one(c, t[254], 0)
+ if i > 1 and bit32.band(sub, 1) ~= 0 then
+ continue
+ end
+ local img, perr = decodePage(c, t, opts)
+ if not img then
+ if i == 1 then
+ return nil, perr
+ end
+ continue
+ end
+ if not first then
+ first = img
+ end
+ table.insert(frames, { image = img, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" })
+ end
+ local img = first :: Types.Image
+ img.meta.source.pages = #frames
+ if #frames > 1 then
+ img.frames = frames :: any
+ end
+ return img, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+-- layout per pixel format: samples, bits, sample format, photometric, extra samples
+local LAYOUT = {
+ gray8 = { 1, 8, 1, 1 },
+ graya8 = { 2, 8, 1, 1 },
+ gray16 = { 1, 16, 1, 1 },
+ rgb8 = { 3, 8, 1, 2 },
+ rgba8 = { 4, 8, 1, 2 },
+ rgba16 = { 4, 16, 1, 2 },
+ rgbaf32 = { 4, 32, 3, 2 },
+}
+local COMP_CODES = { none = 1, deflate = 8, lzw = 5, packbits = 32773 }
+
+type Tag = { tag: number, typ: number, vals: { number }?, data: buffer? }
+
+local function encodePage(img: Types.Image, o: EncodeOptions, comp: number): ({ Tag }?, { buffer }?, Err.Err?)
+ local L = LAYOUT[img.format]
+ if not L then
+ return nil, nil, Err.new(Err.ARG, "unsupported pixel format " .. tostring(img.format))
+ end
+ local w, h = img.width, img.height
+ local spp, bps, sfmt, photo = L[1], L[2], L[3], L[4]
+ local rb = w * spp * bps // 8
+ if type(w) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or w > 2 ^ 31 or buffer.len(img.pixels) < rb * h then
+ return nil, nil, Err.new(Err.ARG, "bad image size or pixel buffer")
+ end
+ local rps = o.rowsPerStrip or math.max(1, 65536 // rb)
+ if type(rps) ~= "number" or rps < 1 then
+ return nil, nil, Err.new(Err.ARG, "rowsPerStrip must be >= 1")
+ end
+ rps = math.min(math.floor(rps), h)
+ local predictor = 1
+ if (comp == 8 or comp == 5) and o.predictor ~= false then
+ predictor = if sfmt == 3 then 3 else 2
+ end
+ local strips = {}
+ local tmp = buffer.create(rb + 8)
+ for y0 = 0, h - 1, rps do
+ local rows = math.min(rps, h - y0)
+ local raw = buffer.create(rows * rb)
+ buffer.copy(raw, 0, img.pixels, y0 * rb, rows * rb)
+ if predictor == 2 then
+ Pixels.predict2(raw, 0, rows, rb, spp, bps)
+ elseif predictor == 3 then
+ Pixels.predict3(raw, 0, rows, rb, 4, spp, tmp)
+ end
+ local out
+ if comp == 1 then
+ out = raw
+ elseif comp == 8 then
+ out = Deflate.zlibCompress(raw, { level = o.level or 6 }) :: buffer
+ elseif comp == 5 then
+ out = Lzw.encode(raw, 0, rows * rb, "tiff")
+ else
+ local parts, total = {}, 0
+ for r = 0, rows - 1 do
+ local p = Pixels.packbitsEncode(raw, r * rb, rb)
+ table.insert(parts, p)
+ total += buffer.len(p)
+ end
+ out = buffer.create(total)
+ local q = 0
+ for _, p in parts do
+ buffer.copy(out, q, p)
+ q += buffer.len(p)
+ end
+ end
+ table.insert(strips, out)
+ end
+ local bpsv = table.create(spp, bps)
+ local tags: { Tag } = {
+ { tag = 254, typ = 4, vals = { 0 } },
+ { tag = 256, typ = 4, vals = { w } },
+ { tag = 257, typ = 4, vals = { h } },
+ { tag = 258, typ = 3, vals = bpsv },
+ { tag = 259, typ = 3, vals = { comp } },
+ { tag = 262, typ = 3, vals = { photo } },
+ { tag = 273, typ = 4, vals = table.create(#strips, 0) }, -- patched
+ { tag = 277, typ = 3, vals = { spp } },
+ { tag = 278, typ = 4, vals = { rps } },
+ { tag = 279, typ = 4, vals = table.create(#strips, 0) },
+ { tag = 284, typ = 3, vals = { 1 } },
+ }
+ for i, s in strips do
+ (tags[10].vals :: { number })[i] = buffer.len(s)
+ end
+ local dpi = img.meta and img.meta.dpi
+ if type(dpi) == "table" and type(dpi.x) == "number" and type(dpi.y) == "number" and dpi.x > 0 and dpi.y > 0 then
+ table.insert(tags, { tag = 282, typ = 5, vals = { dpi.x } })
+ table.insert(tags, { tag = 283, typ = 5, vals = { dpi.y } })
+ table.insert(tags, { tag = 296, typ = 3, vals = { 2 } })
+ end
+ if predictor > 1 then
+ table.insert(tags, { tag = 317, typ = 3, vals = { predictor } })
+ end
+ if spp == 2 or spp == 4 then
+ table.insert(tags, { tag = 338, typ = 3, vals = { 2 } })
+ end
+ if sfmt ~= 1 then
+ table.insert(tags, { tag = 339, typ = 3, vals = table.create(spp, sfmt) })
+ end
+ local icc = img.meta and img.meta.icc
+ if type(icc) == "buffer" then
+ table.insert(tags, { tag = 34675, typ = 7, data = icc })
+ end
+ local text = img.meta and img.meta.text
+ if type(text) == "table" then
+ for key, tag in { description = 270, software = 305, datetime = 306, artist = 315, copyright = 33432 } do
+ if type(text[key]) == "string" then
+ table.insert(tags, { tag = tag, typ = 2, data = buffer.fromstring(text[key] .. "\0") })
+ end
+ end
+ end
+ table.sort(tags, function(a: Tag, b: Tag): boolean
+ return a.tag < b.tag
+ end)
+ return tags, strips, nil
+end
+
+function Tiff.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
+ if type(img) ~= "table" or type(img.pixels) ~= "buffer" then
+ return nil, Err.new(Err.ARG, "needs an Image")
+ end
+ local o: EncodeOptions = opts or {}
+ local comp = COMP_CODES[o.compression or "deflate"]
+ if not comp then
+ return nil, Err.new(Err.ARG, "compression must be none, deflate, lzw or packbits")
+ end
+ local list = { img }
+ if type(img.frames) == "table" and #img.frames > 1 then
+ list = {}
+ for _, f in img.frames :: any do
+ if type(f) ~= "table" or type(f.image) ~= "table" then
+ return nil, Err.new(Err.ARG, "bad frame")
+ end
+ table.insert(list, f.image)
+ end
+ end
+ local w = Bytes.writer(1024)
+ w:string("II")
+ w:u16le(42)
+ w:u32le(0) -- first IFD, patched
+ local prevNext = 4
+ for _, page in list do
+ local tags, strips, err = encodePage(page, o, comp)
+ if not tags or not strips then
+ return nil, err
+ end
+ -- strip data first
+ local soffs = {}
+ for i, s in strips do
+ if w:tell() % 2 == 1 then
+ w:u8(0)
+ end
+ soffs[i] = w:tell()
+ w:bytes(s)
+ end
+ for _, tg in tags do
+ if tg.tag == 273 then
+ tg.vals = soffs
+ end
+ end
+ -- out-of-line values
+ local valOff: { [number]: number } = {}
+ for i, tg in tags do
+ local size = TYPE_SIZE[tg.typ]
+ local n = if tg.data then buffer.len(tg.data :: buffer) else #(tg.vals :: { number }) * size
+ if n > 4 then
+ if w:tell() % 2 == 1 then
+ w:u8(0)
+ end
+ valOff[i] = w:tell()
+ if tg.data then
+ w:bytes(tg.data :: buffer)
+ else
+ for _, v in tg.vals :: { number } do
+ if tg.typ == 3 then
+ w:u16le(v)
+ elseif tg.typ == 4 then
+ w:u32le(v)
+ elseif tg.typ == 5 then
+ w:u32le(math.floor(v * 10000 + 0.5))
+ w:u32le(10000)
+ end
+ end
+ end
+ end
+ end
+ if w:tell() % 2 == 1 then
+ w:u8(0)
+ end
+ local ifd = w:tell()
+ w:setU32le(prevNext, ifd)
+ w:u16le(#tags)
+ for i, tg in tags do
+ local count = if tg.data then buffer.len(tg.data :: buffer) else #(tg.vals :: { number })
+ w:u16le(tg.tag)
+ w:u16le(tg.typ)
+ w:u32le(count)
+ if valOff[i] then
+ w:u32le(valOff[i])
+ else
+ local start = w:tell()
+ if tg.data then
+ w:bytes(tg.data :: buffer)
+ else
+ for _, v in tg.vals :: { number } do
+ if tg.typ == 3 then
+ w:u16le(v)
+ else
+ w:u32le(v)
+ end
+ end
+ end
+ w:fill(0, 4 - (w:tell() - start))
+ end
+ end
+ prevNext = w:tell()
+ w:u32le(0)
+ end
+ return w:finish(), nil
+end
+
+return Tiff
diff --git a/src/Formats/init.luau b/src/Formats/init.luau
index 9379330..7601210 100644
--- a/src/Formats/init.luau
+++ b/src/Formats/init.luau
@@ -231,6 +231,28 @@ local function unwrap(value: any, formatName: string, o: Options): any
return v
end
+-- Embedded images (PNG inside ICO, JPEG inside TIFF, thumbnails, textures): a format never requires another format,
+-- so the api hands decoders opts.decodeImage(buf) -> Image | nil, Err and encoders opts.encodeImage(img, format) ->
+-- buffer | nil, Err (unless the caller passed its own). Formats work without them (returning Err.UNSUPPORTED for
+-- the embedded parts) when called directly.
+local function withHooks(o: Options): Options
+ if o.decodeImage ~= nil and o.encodeImage ~= nil then
+ return o
+ end
+ local c = table.clone(o)
+ if c.decodeImage == nil then
+ c.decodeImage = function(b: buffer): (any, Err.Err?)
+ return F.load(b, { category = "image" })
+ end
+ end
+ if c.encodeImage == nil then
+ c.encodeImage = function(img: any, format: string): (any, Err.Err?)
+ return F.save(img, nil, { format = format, category = "image" })
+ end
+ end
+ return c
+end
+
-- load(src, opts?) -> value | nil, Err
function F.load(src: any, opts: Options?): (any, Err.Err?)
local o = opts or {}
@@ -252,7 +274,7 @@ function F.load(src: any, opts: Options?): (any, Err.Err?)
end
local value, err
if m.decode then
- local ok, v, e = pcall(m.decode, Bytes.reader(buf), o)
+ local ok, v, e = pcall(m.decode, Bytes.reader(buf), withHooks(o))
if not ok then
return nil, Err.wrap(Err.new(Err.CORRUPT, "decoder threw: " .. tostring(v)), entry.name)
end
@@ -347,7 +369,7 @@ function F.save(value: any, dest: string?, opts: Options?): (any, Err.Err?)
if not entry then
return nil, err
end
- local ok, buf, e = pcall(m.encode, value, o)
+ local ok, buf, e = pcall(m.encode, value, withHooks(o))
if not ok then
return nil, Err.wrap(Err.new(Err.ARG, "encoder threw: " .. tostring(buf)), entry.name)
end
diff --git a/src/Formats/ops/ImageOps/Kernels.luau b/src/Formats/ops/ImageOps/Kernels.luau
new file mode 100644
index 0000000..68d0d58
--- /dev/null
+++ b/src/Formats/ops/ImageOps/Kernels.luau
@@ -0,0 +1,520 @@
+--!strict
+--!native
+--!optimize 2
+-- ops/ImageOps/Kernels: the hot loops behind ops/ImageOps (native; never throws). Every function trusts its caller
+-- (ops/ImageOps validates sizes, formats and buffer lengths first), so all buffer indexes are in range by
+-- construction. Samples are addressed by kind: 1 = u8, 2 = u16, 4 = f32 (little endian, as Types.Image buffers).
+-- The resampling follows Pillow's Resample.c (separable convolution, horizontal pass first, filter support scaled by
+-- the downscale ratio, 22-bit fixed-point coefficients for 8-bit samples) and Geometry.c (affine transforms through
+-- pixel centres, bilinear with clamped neighbours); the alpha compositing is Pillow's AlphaComposite.c.
+local readu8, writeu8, readu16, writeu16, readf32, writef32 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16, buffer.readf32, buffer.writef32
+local floor, clamp = math.floor, math.clamp
+
+local K = {}
+
+-- format ids: rgba8 1, rgba16 2, rgbaf32 3, rgb8 4, gray8 5, gray16 6, graya8 7, alpha8 8
+K.ID = { rgba8 = 1, rgba16 = 2, rgbaf32 = 3, rgb8 = 4, gray8 = 5, gray16 = 6, graya8 = 7, alpha8 = 8 }
+K.KIND = { rgba8 = 1, rgba16 = 2, rgbaf32 = 4, rgb8 = 1, gray8 = 1, gray16 = 2, graya8 = 1, alpha8 = 1 }
+K.CHANNELS = { rgba8 = 4, rgba16 = 4, rgbaf32 = 4, rgb8 = 3, gray8 = 1, gray16 = 1, graya8 = 2, alpha8 = 1 }
+
+local function rd(b: buffer, o: number, kind: number): number
+ if kind == 1 then
+ return readu8(b, o)
+ elseif kind == 2 then
+ return readu16(b, o)
+ end
+ return readf32(b, o)
+end
+
+local function wr(b: buffer, o: number, kind: number, v: number)
+ if kind == 1 then
+ writeu8(b, o, clamp(floor(v + 0.5), 0, 255))
+ elseif kind == 2 then
+ writeu16(b, o, clamp(floor(v + 0.5), 0, 65535))
+ else
+ writef32(b, o, v)
+ end
+end
+
+-- ------------------------------------------------------------------------------------------------ convert
+-- depth: 8 -> 0..255, 16 -> 0..65535, 0 -> float 0..1
+local DEPTH = { 8, 16, 0, 8, 8, 16, 8, 8 }
+
+local function depthConv(v: number, from: number, to: number): number
+ if from == to then
+ return v
+ end
+ if from == 8 then
+ if to == 16 then
+ return v * 257
+ end
+ return v / 255
+ elseif from == 16 then
+ if to == 8 then
+ return (v * 255 + 32767) // 65535
+ end
+ return v / 65535
+ end
+ -- float
+ if v ~= v then
+ v = 0
+ end
+ if to == 8 then
+ return clamp(floor(v * 255 + 0.5), 0, 255)
+ end
+ return clamp(floor(v * 65535 + 0.5), 0, 65535)
+end
+
+-- Pillow's L24 luma (19595 R + 38470 G + 7471 B + 0x8000) >> 16, in the source depth
+local function luma(r: number, g: number, b: number, depth: number): number
+ if depth == 0 then
+ return (r * 19595 + g * 38470 + b * 7471) / 65536
+ end
+ return (r * 19595 + g * 38470 + b * 7471 + 32768) // 65536
+end
+
+function K.convert(src: buffer, sf: number, dst: buffer, df: number, n: number)
+ local sd, dd = DEPTH[sf], DEPTH[df]
+ local smax = if sd == 8 then 255 elseif sd == 16 then 65535 else 1
+ local toGray = df == 5 or df == 6 or df == 7
+ for i = 0, n - 1 do
+ local r, g, b, a
+ if sf == 1 then
+ local o = i * 4
+ r, g, b, a = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2), readu8(src, o + 3)
+ elseif sf == 2 then
+ local o = i * 8
+ r, g, b, a = readu16(src, o), readu16(src, o + 2), readu16(src, o + 4), readu16(src, o + 6)
+ elseif sf == 3 then
+ local o = i * 16
+ r, g, b, a = readf32(src, o), readf32(src, o + 4), readf32(src, o + 8), readf32(src, o + 12)
+ elseif sf == 4 then
+ local o = i * 3
+ r, g, b, a = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2), 255
+ elseif sf == 5 then
+ local v = readu8(src, i)
+ r, g, b, a = v, v, v, 255
+ elseif sf == 6 then
+ local v = readu16(src, i * 2)
+ r, g, b, a = v, v, v, 65535
+ elseif sf == 7 then
+ local v = readu8(src, i * 2)
+ r, g, b, a = v, v, v, readu8(src, i * 2 + 1)
+ else
+ r, g, b, a = 255, 255, 255, readu8(src, i)
+ end
+ if toGray then
+ local isGray = sf == 5 or sf == 6 or sf == 7
+ local l = if isGray then r else luma(r, g, b, sd)
+ l = depthConv(l, sd, dd)
+ if df == 5 then
+ writeu8(dst, i, l)
+ elseif df == 6 then
+ writeu16(dst, i * 2, l)
+ else
+ writeu8(dst, i * 2, l)
+ writeu8(dst, i * 2 + 1, depthConv(a, sd, dd))
+ end
+ elseif df == 8 then
+ writeu8(dst, i, depthConv(a, sd, 8))
+ else
+ r, g, b = depthConv(r, sd, dd), depthConv(g, sd, dd), depthConv(b, sd, dd)
+ if df == 1 then
+ local o = i * 4
+ writeu8(dst, o, r)
+ writeu8(dst, o + 1, g)
+ writeu8(dst, o + 2, b)
+ writeu8(dst, o + 3, depthConv(a, sd, dd))
+ elseif df == 2 then
+ local o = i * 8
+ writeu16(dst, o, r)
+ writeu16(dst, o + 2, g)
+ writeu16(dst, o + 4, b)
+ writeu16(dst, o + 6, depthConv(a, sd, dd))
+ elseif df == 3 then
+ local o = i * 16
+ writef32(dst, o, r)
+ writef32(dst, o + 4, g)
+ writef32(dst, o + 8, b)
+ writef32(dst, o + 12, if a == smax and sd ~= 0 then 1 else depthConv(a, sd, dd))
+ else -- rgb8
+ local o = i * 3
+ writeu8(dst, o, r)
+ writeu8(dst, o + 1, g)
+ writeu8(dst, o + 2, b)
+ end
+ end
+ end
+end
+
+-- JPEG-style BT.601 full range
+function K.rgbaToYuv(src: buffer, w: number, h: number, dst: buffer)
+ local cw, ch = (w + 1) // 2, (h + 1) // 2
+ local uo, vo = w * h, w * h + cw * ch
+ for i = 0, w * h - 1 do
+ local o = i * 4
+ local r, g, b = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2)
+ writeu8(dst, i, clamp(floor(0.299 * r + 0.587 * g + 0.114 * b + 0.5), 0, 255))
+ end
+ for cy = 0, ch - 1 do
+ for cx = 0, cw - 1 do
+ local sr, sg, sb, n = 0, 0, 0, 0
+ for dy = 0, 1 do
+ local y = cy * 2 + dy
+ if y < h then
+ for dx = 0, 1 do
+ local x = cx * 2 + dx
+ if x < w then
+ local o = (y * w + x) * 4
+ sr += readu8(src, o)
+ sg += readu8(src, o + 1)
+ sb += readu8(src, o + 2)
+ n += 1
+ end
+ end
+ end
+ end
+ sr, sg, sb = sr / n, sg / n, sb / n
+ local i = cy * cw + cx
+ writeu8(dst, uo + i, clamp(floor(128 - 0.168736 * sr - 0.331264 * sg + 0.5 * sb + 0.5), 0, 255))
+ writeu8(dst, vo + i, clamp(floor(128 + 0.5 * sr - 0.418688 * sg - 0.081312 * sb + 0.5), 0, 255))
+ end
+ end
+end
+
+function K.yuvToRgba(src: buffer, w: number, h: number, dst: buffer)
+ local cw, ch = (w + 1) // 2, (h + 1) // 2
+ local uo, vo = w * h, w * h + cw * ch
+ for y = 0, h - 1 do
+ local crow = (y // 2) * cw
+ for x = 0, w - 1 do
+ local yy = readu8(src, y * w + x)
+ local ci = crow + x // 2
+ local u, v = readu8(src, uo + ci) - 128, readu8(src, vo + ci) - 128
+ local o = (y * w + x) * 4
+ writeu8(dst, o, clamp(floor(yy + 1.402 * v + 0.5), 0, 255))
+ writeu8(dst, o + 1, clamp(floor(yy - 0.344136 * u - 0.714136 * v + 0.5), 0, 255))
+ writeu8(dst, o + 2, clamp(floor(yy + 1.772 * u + 0.5), 0, 255))
+ writeu8(dst, o + 3, 255)
+ end
+ end
+ local _ = ch
+end
+
+-- ------------------------------------------------------------------------------------------------ geometry
+-- flip(src, dst, w, h, bpp, horizontal)
+function K.flip(src: buffer, dst: buffer, w: number, h: number, bpp: number, horizontal: boolean)
+ local stride = w * bpp
+ if not horizontal then
+ for y = 0, h - 1 do
+ buffer.copy(dst, (h - 1 - y) * stride, src, y * stride, stride)
+ end
+ return
+ end
+ for y = 0, h - 1 do
+ local row = y * stride
+ for x = 0, w - 1 do
+ buffer.copy(dst, row + (w - 1 - x) * bpp, src, row + x * bpp, bpp)
+ end
+ end
+end
+
+-- rotate90(src, dst, w, h, bpp, turns): counter-clockwise quarter turns 1..3
+function K.rotate90(src: buffer, dst: buffer, w: number, h: number, bpp: number, turns: number)
+ for y = 0, h - 1 do
+ for x = 0, w - 1 do
+ local ox, oy, ow
+ if turns == 1 then
+ ox, oy, ow = y, w - 1 - x, h
+ elseif turns == 2 then
+ ox, oy, ow = w - 1 - x, h - 1 - y, w
+ else
+ ox, oy, ow = h - 1 - y, x, h
+ end
+ local so, d = (y * w + x) * bpp, (oy * ow + ox) * bpp
+ if bpp == 4 then
+ buffer.writeu32(dst, d, buffer.readu32(src, so))
+ else
+ buffer.copy(dst, d, src, so, bpp)
+ end
+ end
+ end
+end
+
+-- ------------------------------------------------------------------------------------------------ resample
+local function bilinearF(x: number): number
+ if x < 0 then
+ x = -x
+ end
+ if x < 1 then
+ return 1 - x
+ end
+ return 0
+end
+
+local function sinc(x: number): number
+ if x == 0 then
+ return 1
+ end
+ x *= math.pi
+ return math.sin(x) / x
+end
+
+local function lanczosF(x: number): number
+ if x > -3 and x < 3 then
+ return sinc(x) * sinc(x / 3)
+ end
+ return 0
+end
+
+local function trunc(x: number): number
+ return if x < 0 then math.ceil(x) else floor(x)
+end
+
+-- Pillow precompute_coeffs: per output index its first input index, tap count and weights (normalised)
+export type Coeffs = { start: { number }, count: { number }, weights: { { number } } }
+
+function K.coeffs(inSize: number, outSize: number, filter: string): Coeffs
+ local support0 = if filter == "lanczos" then 3 else 1
+ local f = if filter == "lanczos" then lanczosF else bilinearF
+ local scale = inSize / outSize
+ local filterscale = math.max(scale, 1)
+ local support = support0 * filterscale
+ local ss = 1 / filterscale
+ local start, count, weights = table.create(outSize, 0), table.create(outSize, 0), table.create(outSize)
+ for xx = 0, outSize - 1 do
+ local center = (xx + 0.5) * scale
+ local xmin = math.max(0, trunc(center - support + 0.5))
+ local xmax = math.min(inSize, trunc(center + support + 0.5)) - xmin
+ local w = table.create(math.max(xmax, 0), 0)
+ local ww = 0
+ for x = 0, xmax - 1 do
+ local v = f((x + xmin - center + 0.5) * ss)
+ w[x + 1] = v
+ ww += v
+ end
+ if ww ~= 0 then
+ for x = 1, xmax do
+ w[x] /= ww
+ end
+ end
+ start[xx + 1], count[xx + 1], weights[xx + 1] = xmin, math.max(xmax, 0), w
+ end
+ return { start = start, count = count, weights = weights }
+end
+
+-- one separable pass. horizontal: src w x h -> dst outN x h; vertical: src w x h -> dst w x outN. ch channels of kind.
+function K.resamplePass(src: buffer, w: number, h: number, ch: number, kind: number, dst: buffer, outN: number, c: Coeffs, horizontal: boolean)
+ local start, count, weights = c.start, c.count, c.weights
+ local size = kind
+ local fixed = kind == 1
+ -- 8-bit: Pillow's 22-bit fixed-point coefficients
+ local iw: { { number } } = weights
+ if fixed then
+ iw = table.create(outN)
+ for i = 1, outN do
+ local src0 = weights[i]
+ local t = table.create(#src0, 0)
+ for k = 1, #src0 do
+ local v = src0[k] * 4194304
+ t[k] = if v < 0 then math.ceil(v - 0.5) else floor(v + 0.5)
+ end
+ iw[i] = t
+ end
+ end
+ if horizontal then
+ for y = 0, h - 1 do
+ local row = y * w
+ for xx = 0, outN - 1 do
+ local s0, n, wt = start[xx + 1], count[xx + 1], iw[xx + 1]
+ local o = ((y * outN) + xx) * ch * size
+ for cc = 0, ch - 1 do
+ if fixed then
+ local acc = 2097152
+ for k = 0, n - 1 do
+ acc += readu8(src, (row + s0 + k) * ch + cc) * wt[k + 1]
+ end
+ writeu8(dst, o + cc, clamp(acc // 4194304, 0, 255))
+ else
+ local acc = 0
+ for k = 0, n - 1 do
+ acc += rd(src, ((row + s0 + k) * ch + cc) * size, kind) * wt[k + 1]
+ end
+ wr(dst, o + cc * size, kind, acc)
+ end
+ end
+ end
+ end
+ else
+ for yy = 0, outN - 1 do
+ local s0, n, wt = start[yy + 1], count[yy + 1], iw[yy + 1]
+ for x = 0, w - 1 do
+ local o = (yy * w + x) * ch * size
+ for cc = 0, ch - 1 do
+ if fixed then
+ local acc = 2097152
+ for k = 0, n - 1 do
+ acc += readu8(src, ((s0 + k) * w + x) * ch + cc) * wt[k + 1]
+ end
+ writeu8(dst, o + cc, clamp(acc // 4194304, 0, 255))
+ else
+ local acc = 0
+ for k = 0, n - 1 do
+ acc += rd(src, (((s0 + k) * w + x) * ch + cc) * size, kind) * wt[k + 1]
+ end
+ wr(dst, o + cc * size, kind, acc)
+ end
+ end
+ end
+ end
+ end
+ local _ = h
+end
+
+-- nearest: dst pixel (x, y) = src pixel (floor((x + 0.5) * w / ow), ...)
+function K.nearest(src: buffer, w: number, h: number, bpp: number, dst: buffer, ow: number, oh: number)
+ local sx, sy = w / ow, h / oh
+ for y = 0, oh - 1 do
+ local iy = math.min(floor((y + 0.5) * sy), h - 1)
+ for x = 0, ow - 1 do
+ local ix = math.min(floor((x + 0.5) * sx), w - 1)
+ buffer.copy(dst, (y * ow + x) * bpp, src, (iy * w + ix) * bpp, bpp)
+ end
+ end
+end
+
+-- affine(src, w, h, ch, kind, dst, ow, oh, m): dst pixel centres mapped through m = { a, b, c, d, e, f } to src
+-- coordinates (xin = a x + b y + c), bilinear with clamped neighbours; centres outside the source -> zeros (Pillow)
+function K.affine(src: buffer, w: number, h: number, ch: number, kind: number, dst: buffer, ow: number, oh: number, m: { number })
+ local a, b, c, d, e, f = m[1], m[2], m[3], m[4], m[5], m[6]
+ local size = kind
+ for y = 0, oh - 1 do
+ local py = y + 0.5
+ for x = 0, ow - 1 do
+ local px = x + 0.5
+ local xin = a * px + b * py + c - 0.5
+ local yin = d * px + e * py + f - 0.5
+ local o = (y * ow + x) * ch * size
+ local x0 = floor(xin)
+ local y0 = floor(yin)
+ if xin < -0.5 or xin >= w - 0.5 or yin < -0.5 or yin >= h - 0.5 then
+ continue -- dst starts zeroed
+ end
+ local dx, dy = xin - x0, yin - y0
+ local xa, xb = clamp(x0, 0, w - 1), clamp(x0 + 1, 0, w - 1)
+ local ya, yb = clamp(y0, 0, h - 1), clamp(y0 + 1, 0, h - 1)
+ for cc = 0, ch - 1 do
+ local p00 = rd(src, ((ya * w + xa) * ch + cc) * size, kind)
+ local p01 = rd(src, ((ya * w + xb) * ch + cc) * size, kind)
+ local p10 = rd(src, ((yb * w + xa) * ch + cc) * size, kind)
+ local p11 = rd(src, ((yb * w + xb) * ch + cc) * size, kind)
+ local top = p00 + (p01 - p00) * dx
+ local bot = p10 + (p11 - p10) * dx
+ local v = top + (bot - top) * dy
+ if kind == 1 then
+ writeu8(dst, o + cc, clamp(floor(v), 0, 255)) -- Pillow truncates
+ else
+ wr(dst, o + cc * size, kind, v)
+ end
+ end
+ end
+ end
+end
+
+-- ------------------------------------------------------------------------------------------------ compositing
+-- overRgba8(dst, dw, src, sw, sx, sy, dx, dy, w, h, opacity255): Pillow's alpha_composite of src onto dst, in place
+function K.overRgba8(dst: buffer, dw: number, src: buffer, sw: number, sx: number, sy: number, dx: number, dy: number, w: number, h: number, opacity: number)
+ for y = 0, h - 1 do
+ for x = 0, w - 1 do
+ local so = ((sy + y) * sw + sx + x) * 4
+ local doff = ((dy + y) * dw + dx + x) * 4
+ local sa = readu8(src, so + 3)
+ if opacity < 255 then
+ sa = (sa * opacity + 127) // 255
+ end
+ if sa == 0 then
+ continue
+ end
+ local da = readu8(dst, doff + 3)
+ local blend = da * (255 - sa)
+ local outa255 = sa * 255 + blend
+ local coef1 = (sa * 255 * 255 * 128) // outa255
+ local coef2 = 255 * 128 - coef1
+ for cc = 0, 2 do
+ local t = readu8(src, so + cc) * coef1 + readu8(dst, doff + cc) * coef2 + 0x80 * 128
+ t = ((t // 256) + t) // 256
+ writeu8(dst, doff + cc, t // 128)
+ end
+ local t = outa255 + 0x80
+ writeu8(dst, doff + 3, ((t // 256) + t) // 256)
+ end
+ end
+end
+
+-- overFloat: straight-alpha "over" for rgba16 (kind 2) / rgbaf32 (kind 4); max = 65535 or 1
+function K.overFloat(dst: buffer, dw: number, src: buffer, sw: number, sx: number, sy: number, dx: number, dy: number, w: number, h: number, opacity: number, kind: number)
+ local max = if kind == 2 then 65535 else 1
+ local px = 4 * kind
+ for y = 0, h - 1 do
+ for x = 0, w - 1 do
+ local so = ((sy + y) * sw + sx + x) * px
+ local doff = ((dy + y) * dw + dx + x) * px
+ local sa = rd(src, so + 3 * kind, kind) / max * opacity
+ if sa <= 0 then
+ continue
+ end
+ local da = rd(dst, doff + 3 * kind, kind) / max
+ local oa = sa + da * (1 - sa)
+ for cc = 0, 2 do
+ local s = rd(src, so + cc * kind, kind)
+ local d = rd(dst, doff + cc * kind, kind)
+ wr(dst, doff + cc * kind, kind, if oa > 0 then (s * sa + d * da * (1 - sa)) / oa else 0)
+ end
+ wr(dst, doff + 3 * kind, kind, oa * max)
+ end
+ end
+end
+
+-- copyRect: rows of a rectangle (bpp bytes per pixel)
+function K.copyRect(dst: buffer, dw: number, src: buffer, sw: number, sx: number, sy: number, dx: number, dy: number, w: number, h: number, bpp: number)
+ for y = 0, h - 1 do
+ buffer.copy(dst, ((dy + y) * dw + dx) * bpp, src, ((sy + y) * sw + sx) * bpp, w * bpp)
+ end
+end
+
+-- premultiply / unpremultiply in place: ch channels, alpha last, kind
+function K.premultiply(b: buffer, n: number, ch: number, kind: number, un: boolean)
+ local max = if kind == 1 then 255 elseif kind == 2 then 65535 else 1
+ local px = ch * kind
+ for i = 0, n - 1 do
+ local o = i * px
+ local a = rd(b, o + (ch - 1) * kind, kind)
+ for cc = 0, ch - 2 do
+ local v = rd(b, o + cc * kind, kind)
+ local r
+ if un then
+ if a <= 0 then
+ r = 0
+ elseif kind == 4 then
+ r = v / a
+ elseif kind == 1 then
+ r = math.min(255, (v * 255) // a) -- Pillow's rgbA2rgba
+ else
+ r = math.min(max, (v * max + a // 2) // a)
+ end
+ else
+ if kind == 4 then
+ r = v * a
+ elseif kind == 1 then
+ local t = v * a + 128 -- Pillow's MULDIV255
+ r = ((t // 256) + t) // 256
+ else
+ r = (v * a + max // 2) // max
+ end
+ end
+ wr(b, o + cc * kind, kind, r)
+ end
+ end
+end
+
+return K
diff --git a/src/Formats/ops/ImageOps/init.luau b/src/Formats/ops/ImageOps/init.luau
new file mode 100644
index 0000000..6a5e976
--- /dev/null
+++ b/src/Formats/ops/ImageOps/init.luau
@@ -0,0 +1,689 @@
+--!strict
+-- ops/ImageOps: editing on the standard Image (layer 5.5: core, Types and codecs only). Pixel format conversion,
+-- crop, resize (nearest / bilinear / Lanczos-3, as Pillow), flips, quarter turns and arbitrary rotation (bilinear, as
+-- Pillow's rotate), alpha compositing (Pillow's alpha_composite for rgba8), premultiplication, pixel access, and
+-- helpers for animations (Image.frames). New code; the resampling and compositing follow Pillow's C sources.
+--
+-- local Ops = require("@formats/ops/ImageOps")
+-- local small = Ops.resize(img, 320, 240, "lanczos") -- every call returns a new Image | nil, Err (never throws)
+-- local grey = Ops.convert(img, "gray8")
+-- Ops.blit(canvas, sprite, 10, 20) -- in place on canvas, straight-alpha "over"
+-- for i, frame in Ops.coalesce(gif) do ... end -- full-canvas frames of an animation
+--
+-- Conventions: angles are degrees counter-clockwise and rotate90 turns are counter-clockwise quarter turns (as
+-- Pillow). Resizing and rotating filter premultiplied alpha (as Pillow does for RGBA / LA). Grey is Pillow's
+-- L = (19595 R + 38470 G + 7471 B + 32768) >> 16. 8 <-> 16 bit is * 257 and
+-- (v * 255 + 32767) // 65535; float <-> integer clamps to 0..1 and rounds (no gamma). alpha8 converts to white with
+-- that alpha. yuv420p is JPEG-style BT.601 full range (2x2 box chroma); geometric ops on yuv420p go through rgba8.
+local Err = require("@formats/core/Err")
+local Types = require("@formats/Types")
+local K = require("@formats/ops/ImageOps/Kernels")
+
+local ImageOps = {}
+
+local MAX_PIXELS = 2 ^ 26
+
+type Image = Types.Image
+
+-- ------------------------------------------------------------------------------------------------ validation
+local function arg(msg: string): (nil, Err.Err)
+ return nil, Err.new(Err.ARG, msg)
+end
+
+local function isInt(v: any): boolean
+ return type(v) == "number" and v == v and v % 1 == 0 and v > -2 ^ 31 and v < 2 ^ 31
+end
+
+local function bytesOf(fmt: string, w: number, h: number): number?
+ if fmt == "yuv420p" then
+ return w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2)
+ end
+ local bpp = Types.BPP[fmt]
+ return if bpp then w * h * bpp else nil
+end
+
+-- check(img) -> true | nil, Err: a well-formed Image (known format, sizes, buffer long enough)
+local function check(img: any): (boolean?, Err.Err?)
+ if type(img) ~= "table" or type(img.pixels) ~= "buffer" then
+ return arg("expected an Image")
+ end
+ if not isInt(img.width) or not isInt(img.height) or img.width < 1 or img.height < 1 then
+ return arg("bad image size")
+ end
+ local need = bytesOf(img.format, img.width, img.height)
+ if not need then
+ return arg("unknown pixel format " .. tostring(img.format))
+ end
+ if buffer.len(img.pixels) < need then
+ return arg("pixel buffer too small for " .. img.width .. " x " .. img.height .. " " .. img.format)
+ end
+ return true
+end
+ImageOps.check = check
+
+local function limit(w: number, h: number, opts: any): (boolean?, Err.Err?)
+ local max = (type(opts) == "table" and opts.maxPixels) or MAX_PIXELS
+ if w * h > max then
+ return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, max))
+ end
+ return true
+end
+
+-- a new Image of the same kind with a copy of meta's plain fields (source, palette...) but no frames
+local function like(img: Image, w: number, h: number, fmt: string?): Image
+ local out = Types.Image.new(w, h, (fmt or img.format) :: any)
+ for k, v in img.meta do
+ out.meta[k] = v
+ end
+ out.loops = img.loops
+ return out
+end
+
+-- ------------------------------------------------------------------------------------------------ basics
+-- new(w, h, format?) -> a zero-filled Image | nil, Err
+function ImageOps.new(w: number, h: number, format: string?): (Image?, Err.Err?)
+ local fmt = format or "rgba8"
+ if not isInt(w) or not isInt(h) or w < 1 or h < 1 then
+ return arg("bad image size")
+ end
+ if not bytesOf(fmt, 1, 1) then
+ return arg("unknown pixel format " .. tostring(fmt))
+ end
+ local ok, e = limit(w, h, nil)
+ if not ok then
+ return nil, e
+ end
+ return Types.Image.new(w, h, fmt :: any)
+end
+
+-- copy(img) -> a deep copy of the pixels (frames are shared)
+function ImageOps.copy(img: Image): (Image?, Err.Err?)
+ local ok, e = check(img)
+ if not ok then
+ return nil, e
+ end
+ local out = like(img, img.width, img.height)
+ buffer.copy(out.pixels, 0, img.pixels, 0, buffer.len(out.pixels))
+ out.frames = img.frames
+ return out
+end
+
+-- ------------------------------------------------------------------------------------------------ convert
+-- convert(img, format) -> a new Image in format (a copy when it is already)
+function ImageOps.convert(img: Image, format: string): (Image?, Err.Err?)
+ local ok, e = check(img)
+ if not ok then
+ return nil, e
+ end
+ if not bytesOf(format, 1, 1) then
+ return arg("unknown pixel format " .. tostring(format))
+ end
+ local w, h = img.width, img.height
+ if img.format == format then
+ return ImageOps.copy(img)
+ end
+ local src = img
+ if img.format == "yuv420p" then
+ local rgba = like(img, w, h, "rgba8")
+ K.yuvToRgba(img.pixels, w, h, rgba.pixels)
+ if format == "rgba8" then
+ return rgba
+ end
+ src = rgba
+ end
+ local out = like(img, w, h, format)
+ if format == "yuv420p" then
+ local rgba = src
+ if src.format ~= "rgba8" then
+ rgba = like(img, w, h, "rgba8")
+ K.convert(src.pixels, K.ID[src.format], rgba.pixels, K.ID.rgba8, w * h)
+ end
+ K.rgbaToYuv(rgba.pixels, w, h, out.pixels)
+ return out
+ end
+ K.convert(src.pixels, K.ID[src.format], out.pixels, K.ID[format], w * h)
+ return out
+end
+
+-- ops on yuv420p run on rgba8 and convert back
+local function viaRgba(img: Image, f: (Image) -> (Image?, Err.Err?)): (Image?, Err.Err?)
+ if img.format ~= "yuv420p" then
+ return f(img)
+ end
+ local rgba = ImageOps.convert(img, "rgba8") :: Image
+ local res, e = f(rgba)
+ if not res then
+ return nil, e
+ end
+ return ImageOps.convert(res, "yuv420p")
+end
+
+-- ------------------------------------------------------------------------------------------------ geometry
+local ALPHA_CH = { rgba8 = 4, rgba16 = 4, rgbaf32 = 4, graya8 = 2 }
+
+-- crop(img, x, y, w, h) -> the rectangle clipped to the image | nil, Err (empty)
+function ImageOps.crop(img: Image, x: number, y: number, w: number, h: number): (Image?, Err.Err?)
+ local ok, e = check(img)
+ if not ok then
+ return nil, e
+ end
+ if not (isInt(x) and isInt(y) and isInt(w) and isInt(h)) then
+ return arg("crop: integer x, y, w, h")
+ end
+ local x0, y0 = math.max(0, x), math.max(0, y)
+ local x1, y1 = math.min(img.width, x + w), math.min(img.height, y + h)
+ if x1 <= x0 or y1 <= y0 then
+ return arg("crop: the rectangle is outside the image or empty")
+ end
+ return viaRgba(img, function(im: Image): (Image?, Err.Err?)
+ local bpp = Types.BPP[im.format] :: number
+ local out = like(im, x1 - x0, y1 - y0)
+ K.copyRect(out.pixels, out.width, im.pixels, im.width, x0, y0, 0, 0, out.width, out.height, bpp)
+ return out
+ end)
+end
+
+-- flip(img, "h" | "v") -> mirrored horizontally (left-right) or vertically (top-bottom)
+function ImageOps.flip(img: Image, axis: string): (Image?, Err.Err?)
+ local ok, e = check(img)
+ if not ok then
+ return nil, e
+ end
+ if axis ~= "h" and axis ~= "v" then
+ return arg("flip: axis must be \"h\" or \"v\"")
+ end
+ return viaRgba(img, function(im: Image): (Image?, Err.Err?)
+ local out = like(im, im.width, im.height)
+ K.flip(im.pixels, out.pixels, im.width, im.height, Types.BPP[im.format] :: number, axis == "h")
+ return out
+ end)
+end
+
+-- rotate90(img, turns) -> turned by turns counter-clockwise quarter turns (any integer; negative = clockwise)
+function ImageOps.rotate90(img: Image, turns: number): (Image?, Err.Err?)
+ local ok, e = check(img)
+ if not ok then
+ return nil, e
+ end
+ if not isInt(turns) then
+ return arg("rotate90: integer turns")
+ end
+ local t = turns % 4
+ if t == 0 then
+ return ImageOps.copy(img)
+ end
+ return viaRgba(img, function(im: Image): (Image?, Err.Err?)
+ local swap = t ~= 2
+ local out = like(im, if swap then im.height else im.width, if swap then im.width else im.height)
+ K.rotate90(im.pixels, out.pixels, im.width, im.height, Types.BPP[im.format] :: number, t)
+ return out
+ end)
+end
+
+export type ResizeFilter = "nearest" | "bilinear" | "lanczos"
+
+-- resize(img, w, h, filter?, opts?) -> w x h (filter default "bilinear"; opts.maxPixels)
+function ImageOps.resize(img: Image, w: number, h: number, filter: string?, opts: any?): (Image?, Err.Err?)
+ local ok, e = check(img)
+ if not ok then
+ return nil, e
+ end
+ if not isInt(w) or not isInt(h) or w < 1 or h < 1 then
+ return arg("resize: bad target size")
+ end
+ local f = filter or "bilinear"
+ if f ~= "nearest" and f ~= "bilinear" and f ~= "lanczos" then
+ return arg("resize: filter must be nearest, bilinear or lanczos")
+ end
+ local lok, le = limit(w, h, opts)
+ if not lok then
+ return nil, le
+ end
+ return viaRgba(img, function(im: Image): (Image?, Err.Err?)
+ local fmt = im.format
+ local bpp = Types.BPP[fmt] :: number
+ local out = like(im, w, h)
+ if f == "nearest" then
+ K.nearest(im.pixels, im.width, im.height, bpp, out.pixels, w, h)
+ return out
+ end
+ local kind, ch = K.KIND[fmt], K.CHANNELS[fmt]
+ local src, sw, sh = im.pixels, im.width, im.height
+ local alpha = ALPHA_CH[fmt]
+ if alpha then
+ src = buffer.create(buffer.len(im.pixels))
+ buffer.copy(src, 0, im.pixels)
+ K.premultiply(src, sw * sh, alpha, kind, false)
+ end
+ if w ~= sw then
+ local tmp = buffer.create(w * sh * bpp)
+ K.resamplePass(src, sw, sh, ch, kind, tmp, w, K.coeffs(sw, w, f), true)
+ src, sw = tmp, w
+ end
+ if h ~= sh then
+ K.resamplePass(src, sw, sh, ch, kind, out.pixels, h, K.coeffs(sh, h, f), false)
+ elseif src == im.pixels or (w == im.width and alpha) then
+ buffer.copy(out.pixels, 0, im.pixels, 0, w * h * bpp)
+ return out
+ else
+ out.pixels = src
+ end
+ if alpha then
+ K.premultiply(out.pixels, w * h, alpha, kind, true)
+ end
+ return out
+ end)
+end
+
+-- rotate(img, degrees, opts?) -> rotated counter-clockwise about the centre with bilinear sampling (as Pillow's
+-- rotate(angle, BILINEAR, expand)): opts.expand (default true) grows the canvas to hold the whole image; uncovered
+-- pixels are zero (transparent). opts.maxPixels.
+function ImageOps.rotate(img: Image, degrees: number, opts: { expand: boolean?, maxPixels: number? }?): (Image?, Err.Err?)
+ local ok, e = check(img)
+ if not ok then
+ return nil, e
+ end
+ if type(degrees) ~= "number" or degrees ~= degrees or degrees == math.huge or degrees == -math.huge then
+ return arg("rotate: degrees must be a finite number")
+ end
+ local expand = not (opts and opts.expand == false)
+ if degrees % 90 == 0 and (expand or degrees % 180 == 0 or img.width == img.height) then
+ return ImageOps.rotate90(img, (degrees // 90) % 4)
+ end
+ local w, h = img.width, img.height
+ local ang = -math.rad(degrees)
+ local function r15(v: number): number
+ return math.floor(v * 1e15 + 0.5) / 1e15
+ end
+ local m = { r15(math.cos(ang)), r15(math.sin(ang)), 0, r15(-math.sin(ang)), r15(math.cos(ang)), 0 }
+ local function tr(x: number, y: number): (number, number)
+ return m[1] * x + m[2] * y + m[3], m[4] * x + m[5] * y + m[6]
+ end
+ local cx, cy = w / 2, h / 2
+ m[3], m[6] = tr(-cx, -cy)
+ m[3] += cx
+ m[6] += cy
+ local nw, nh = w, h
+ if expand then
+ local xs, ys = {}, {}
+ for _, p in { { 0, 0 }, { w, 0 }, { w, h }, { 0, h } } do
+ local x, y = tr(p[1], p[2])
+ table.insert(xs, x)
+ table.insert(ys, y)
+ end
+ nw = math.ceil(math.max(xs[1], xs[2], xs[3], xs[4])) - math.floor(math.min(xs[1], xs[2], xs[3], xs[4]))
+ nh = math.ceil(math.max(ys[1], ys[2], ys[3], ys[4])) - math.floor(math.min(ys[1], ys[2], ys[3], ys[4]))
+ m[3], m[6] = tr(-(nw - w) / 2, -(nh - h) / 2)
+ end
+ local lok, le = limit(nw, nh, opts)
+ if not lok then
+ return nil, le
+ end
+ return viaRgba(img, function(im: Image): (Image?, Err.Err?)
+ local out = like(im, nw, nh)
+ local kind = K.KIND[im.format]
+ local alpha = ALPHA_CH[im.format]
+ local src = im.pixels
+ if alpha then
+ src = buffer.create(buffer.len(im.pixels))
+ buffer.copy(src, 0, im.pixels)
+ K.premultiply(src, w * h, alpha, kind, false)
+ end
+ K.affine(src, w, h, K.CHANNELS[im.format], kind, out.pixels, nw, nh, m)
+ if alpha then
+ K.premultiply(out.pixels, nw * nh, alpha, kind, true)
+ end
+ return out
+ end)
+end
+
+-- ------------------------------------------------------------------------------------------------ compositing
+local RGBA = { rgba8 = true, rgba16 = true, rgbaf32 = true }
+
+export type BlitOptions = { blend: ("over" | "source")?, opacity: number? }
+
+-- blit(dst, src, x, y, opts?) -> dst (modified in place) | nil, Err. src is clipped to dst; it is converted to dst's
+-- format first when they differ. blend "over" (default: Porter-Duff over, straight alpha; Pillow's alpha_composite
+-- for rgba8) or "source" (copy); opts.opacity 0..1 scales src alpha ("over" only).
+function ImageOps.blit(dst: Image, src: Image, x: number, y: number, opts: BlitOptions?): (Image?, Err.Err?)
+ local ok, e = check(dst)
+ if not ok then
+ return nil, e
+ end
+ local ok2, e2 = check(src)
+ if not ok2 then
+ return nil, e2
+ end
+ if not isInt(x) or not isInt(y) then
+ return arg("blit: integer x, y")
+ end
+ local blend = (opts and opts.blend) or "over"
+ if blend ~= "over" and blend ~= "source" then
+ return arg("blit: blend must be \"over\" or \"source\"")
+ end
+ local opacity = (opts and opts.opacity) or 1
+ if type(opacity) ~= "number" or not (opacity >= 0 and opacity <= 1) then
+ return arg("blit: opacity must be 0..1")
+ end
+ -- clip
+ local sx, sy = math.max(0, -x), math.max(0, -y)
+ local dx, dy = math.max(0, x), math.max(0, y)
+ local w = math.min(src.width - sx, dst.width - dx)
+ local h = math.min(src.height - sy, dst.height - dy)
+ if w <= 0 or h <= 0 then
+ return dst
+ end
+ if dst.format == "yuv420p" or (blend == "over" and not RGBA[dst.format]) then
+ -- work on an rgba copy of the region, then write it back in dst's format
+ local region = ImageOps.crop(dst, dx, dy, w, h) :: Image
+ local work = if region.format == "rgba8" then region else ImageOps.convert(region, "rgba8") :: Image
+ ImageOps.blit(work, src, x - dx, y - dy, opts)
+ if dst.format == "yuv420p" then
+ local full = ImageOps.convert(dst, "rgba8") :: Image
+ ImageOps.blit(full, work, dx, dy, { blend = "source" })
+ local back = ImageOps.convert(full, "yuv420p") :: Image
+ buffer.copy(dst.pixels, 0, back.pixels, 0, buffer.len(back.pixels))
+ else
+ local back = ImageOps.convert(work, dst.format) :: Image
+ K.copyRect(dst.pixels, dst.width, back.pixels, back.width, 0, 0, dx, dy, w, h, Types.BPP[dst.format] :: number)
+ end
+ return dst
+ end
+ local s = src
+ if src.format ~= dst.format then
+ s = ImageOps.convert(src, dst.format) :: Image
+ end
+ if blend == "source" then
+ K.copyRect(dst.pixels, dst.width, s.pixels, s.width, sx, sy, dx, dy, w, h, Types.BPP[dst.format] :: number)
+ elseif dst.format == "rgba8" then
+ K.overRgba8(dst.pixels, dst.width, s.pixels, s.width, sx, sy, dx, dy, w, h, math.floor(opacity * 255 + 0.5))
+ else
+ K.overFloat(dst.pixels, dst.width, s.pixels, s.width, sx, sy, dx, dy, w, h, opacity, K.KIND[dst.format])
+ end
+ return dst
+end
+
+-- composite(dst, src, x?, y?, opts?) -> a new Image: a copy of dst with src blitted onto it
+function ImageOps.composite(dst: Image, src: Image, x: number?, y: number?, opts: BlitOptions?): (Image?, Err.Err?)
+ local out, e = ImageOps.copy(dst)
+ if not out then
+ return nil, e
+ end
+ out.frames = nil
+ return ImageOps.blit(out, src, x or 0, y or 0, opts)
+end
+
+local function premul(img: Image, un: boolean): (Image?, Err.Err?)
+ local out, e = ImageOps.copy(img)
+ if not out then
+ return nil, e
+ end
+ out.frames = nil
+ local ch = ALPHA_CH[img.format]
+ if ch then
+ K.premultiply(out.pixels, img.width * img.height, ch, K.KIND[img.format], un)
+ end
+ return out
+end
+
+-- premultiply(img) / unpremultiply(img) -> a new Image (formats without alpha are copied unchanged)
+function ImageOps.premultiply(img: Image): (Image?, Err.Err?)
+ return premul(img, false)
+end
+function ImageOps.unpremultiply(img: Image): (Image?, Err.Err?)
+ return premul(img, true)
+end
+
+-- ------------------------------------------------------------------------------------------------ pixels
+local MAXV = { rgba8 = 255, rgba16 = 65535, rgbaf32 = 1, rgb8 = 255, gray8 = 255, gray16 = 65535, graya8 = 255, alpha8 = 255, yuv420p = 255 }
+
+-- getPixel(img, x, y) -> r, g, b, a in the format's scale (0..255, 0..65535 or float); grey gives r = g = b;
+-- alpha8 gives white; yuv420p converts to RGB. nil, Err out of range.
+function ImageOps.getPixel(img: Image, x: number, y: number): (any, any, number?, number?)
+ local ok, e = check(img)
+ if not ok then
+ return nil, e
+ end
+ if not isInt(x) or not isInt(y) or x < 0 or y < 0 or x >= img.width or y >= img.height then
+ return arg("getPixel: coordinates out of range")
+ end
+ local b, f, i = img.pixels, img.format, y * img.width + x
+ local ru8, ru16, rf = buffer.readu8, buffer.readu16, buffer.readf32
+ if f == "rgba8" then
+ return ru8(b, i * 4), ru8(b, i * 4 + 1), ru8(b, i * 4 + 2), ru8(b, i * 4 + 3)
+ elseif f == "rgba16" then
+ return ru16(b, i * 8), ru16(b, i * 8 + 2), ru16(b, i * 8 + 4), ru16(b, i * 8 + 6)
+ elseif f == "rgbaf32" then
+ return rf(b, i * 16), rf(b, i * 16 + 4), rf(b, i * 16 + 8), rf(b, i * 16 + 12)
+ elseif f == "rgb8" then
+ return ru8(b, i * 3), ru8(b, i * 3 + 1), ru8(b, i * 3 + 2), 255
+ elseif f == "gray8" then
+ local v = ru8(b, i)
+ return v, v, v, 255
+ elseif f == "gray16" then
+ local v = ru16(b, i * 2)
+ return v, v, v, 65535
+ elseif f == "graya8" then
+ local v = ru8(b, i * 2)
+ return v, v, v, ru8(b, i * 2 + 1)
+ elseif f == "alpha8" then
+ return 255, 255, 255, ru8(b, i)
+ end
+ local one = ImageOps.crop(img, x - x % 2, y - y % 2, 2, 2) :: Image
+ local rgba = ImageOps.convert(one, "rgba8") :: Image
+ local j = ((y % 2) * rgba.width + (x % 2)) * 4
+ if j + 4 > buffer.len(rgba.pixels) then
+ j = 0
+ end
+ return ru8(rgba.pixels, j), ru8(rgba.pixels, j + 1), ru8(rgba.pixels, j + 2), 255
+end
+
+-- setPixel(img, x, y, r, g, b, a?) -> true (in place) | nil, Err. Values in the format's scale (clamped and
+-- rounded for integer formats); grey formats take Pillow's luma of r, g, b; a defaults to opaque. Not for yuv420p.
+function ImageOps.setPixel(img: Image, x: number, y: number, r: number, g: number, b: number, a: number?): (boolean?, Err.Err?)
+ local ok, e = check(img)
+ if not ok then
+ return nil, e
+ end
+ if not isInt(x) or not isInt(y) or x < 0 or y < 0 or x >= img.width or y >= img.height then
+ return arg("setPixel: coordinates out of range")
+ end
+ if type(r) ~= "number" or type(g) ~= "number" or type(b) ~= "number" or (a ~= nil and type(a) ~= "number") then
+ return arg("setPixel: numeric channels")
+ end
+ local f = img.format
+ if f == "yuv420p" then
+ return arg("setPixel: not supported on yuv420p (convert to rgba8 first)")
+ end
+ local max = MAXV[f]
+ local al = if a == nil then max else a
+ local function q(v: number): number
+ if max == 1 then
+ return v
+ end
+ if v ~= v then
+ return 0
+ end
+ return math.clamp(math.floor(v + 0.5), 0, max)
+ end
+ local px, i = img.pixels, y * img.width + x
+ local wu8, wu16, wf = buffer.writeu8, buffer.writeu16, buffer.writef32
+ local function grey(): number
+ if max == 1 then
+ return (r * 19595 + g * 38470 + b * 7471) / 65536
+ end
+ return (q(r) * 19595 + q(g) * 38470 + q(b) * 7471 + 32768) // 65536
+ end
+ if f == "rgba8" then
+ wu8(px, i * 4, q(r))
+ wu8(px, i * 4 + 1, q(g))
+ wu8(px, i * 4 + 2, q(b))
+ wu8(px, i * 4 + 3, q(al))
+ elseif f == "rgba16" then
+ wu16(px, i * 8, q(r))
+ wu16(px, i * 8 + 2, q(g))
+ wu16(px, i * 8 + 4, q(b))
+ wu16(px, i * 8 + 6, q(al))
+ elseif f == "rgbaf32" then
+ wf(px, i * 16, r)
+ wf(px, i * 16 + 4, g)
+ wf(px, i * 16 + 8, b)
+ wf(px, i * 16 + 12, al)
+ elseif f == "rgb8" then
+ wu8(px, i * 3, q(r))
+ wu8(px, i * 3 + 1, q(g))
+ wu8(px, i * 3 + 2, q(b))
+ elseif f == "gray8" then
+ wu8(px, i, grey())
+ elseif f == "gray16" then
+ wu16(px, i * 2, grey())
+ elseif f == "graya8" then
+ wu8(px, i * 2, grey())
+ wu8(px, i * 2 + 1, q(al))
+ else
+ wu8(px, i, q(al))
+ end
+ return true
+end
+
+-- fill(img, r, g, b, a?) -> img (in place) with every pixel set (values as setPixel)
+function ImageOps.fill(img: Image, r: number, g: number, b: number, a: number?): (Image?, Err.Err?)
+ local ok, e = check(img)
+ if not ok then
+ return nil, e
+ end
+ if img.format == "yuv420p" then
+ return arg("fill: not supported on yuv420p")
+ end
+ local sok, se = ImageOps.setPixel(img, 0, 0, r, g, b, a)
+ if not sok then
+ return nil, se
+ end
+ local bpp = Types.BPP[img.format] :: number
+ local n = img.width * img.height * bpp
+ local filled = bpp
+ while filled < n do
+ local c = math.min(filled, n - filled)
+ buffer.copy(img.pixels, filled, img.pixels, 0, c)
+ filled += c
+ end
+ return img
+end
+
+-- ------------------------------------------------------------------------------------------------ animation
+-- frameCount(img) -> the number of frames (1 for a still image)
+function ImageOps.frameCount(img: Image): number
+ if type(img) == "table" and type(img.frames) == "table" and #img.frames > 0 then
+ return #img.frames
+ end
+ return 1
+end
+
+-- durations(img) -> { seconds } per frame ({ 0 } for a still image)
+function ImageOps.durations(img: Image): { number }
+ local out = {}
+ if type(img) == "table" and type(img.frames) == "table" and #img.frames > 0 then
+ for i, f in img.frames do
+ out[i] = if type(f.delay) == "number" then f.delay else 0
+ end
+ return out
+ end
+ return { 0 }
+end
+
+-- coalesce(img) -> { Image } | nil, Err: every frame composited onto a width x height canvas (rgba8, or rgba16 /
+-- rgbaf32 when the image is), honouring each frame's x, y, blend ("over" / "source") and the previous frame's
+-- dispose ("none" keeps the canvas, "background" clears the frame's rectangle to transparent, "previous" restores
+-- the canvas from before the frame). A still image gives { img }.
+function ImageOps.coalesce(img: Image): ({ Image }?, Err.Err?)
+ local ok, e = check(img)
+ if not ok then
+ return nil, e
+ end
+ local frames = img.frames
+ if type(frames) ~= "table" or #frames == 0 then
+ return { img }
+ end
+ local fmt = if RGBA[img.format] then img.format else "rgba8"
+ local canvas = Types.Image.new(img.width, img.height, fmt :: any)
+ local bpp = Types.BPP[fmt] :: number
+ local out = {}
+ for i, f in frames do
+ if type(f) ~= "table" then
+ return arg("coalesce: frame " .. i .. " is not a Frame")
+ end
+ local fi = f.image
+ local fok, fe = check(fi)
+ if not fok then
+ return nil, Err.new(Err.ARG, "coalesce: frame " .. i .. ": " .. (fe :: Err.Err).message)
+ end
+ local fx, fy = if isInt(f.x) then f.x else 0, if isInt(f.y) then f.y else 0
+ local saved: buffer? = nil
+ if f.dispose == "previous" then
+ local sb = buffer.create(buffer.len(canvas.pixels))
+ buffer.copy(sb, 0, canvas.pixels)
+ saved = sb
+ end
+ local bok, be = ImageOps.blit(canvas, fi, fx, fy, { blend = if f.blend == "source" then "source" else "over" })
+ if not bok then
+ return nil, be
+ end
+ local snap = Types.Image.new(img.width, img.height, fmt :: any)
+ buffer.copy(snap.pixels, 0, canvas.pixels)
+ for k, v in img.meta do
+ snap.meta[k] = v
+ end
+ snap.meta.delay = f.delay
+ out[i] = snap
+ if f.dispose == "background" then
+ local x0, y0 = math.max(0, fx), math.max(0, fy)
+ local x1, y1 = math.min(img.width, fx + fi.width), math.min(img.height, fy + fi.height)
+ for y = y0, y1 - 1 do
+ if x1 > x0 then
+ buffer.fill(canvas.pixels, (y * img.width + x0) * bpp, 0, (x1 - x0) * bpp)
+ end
+ end
+ elseif saved then
+ canvas.pixels = saved
+ end
+ end
+ return out
+end
+
+-- fromFrames(images, delays?) -> an animated Image: img.frames = the images as full-canvas frames (x = y = 0,
+-- dispose "none", blend "source"), img.pixels = a copy of frame 1. delays: a number (every frame) or { seconds }
+-- (default 0.1). All images need the same size and format.
+function ImageOps.fromFrames(images: { Image }, delays: (number | { number })?): (Image?, Err.Err?)
+ if type(images) ~= "table" or #images == 0 then
+ return arg("fromFrames: a non-empty list of Images")
+ end
+ local first = images[1]
+ local ok, e = check(first)
+ if not ok then
+ return nil, e
+ end
+ local frames = {}
+ for i, im in images do
+ local iok, ie = check(im)
+ if not iok then
+ return nil, ie
+ end
+ if im.width ~= first.width or im.height ~= first.height or im.format ~= first.format then
+ return arg("fromFrames: frame " .. i .. " differs in size or format from frame 1")
+ end
+ local d = 0.1
+ if type(delays) == "number" then
+ d = delays
+ elseif type(delays) == "table" and type(delays[i]) == "number" then
+ d = delays[i]
+ end
+ frames[i] = { image = im, delay = d, x = 0, y = 0, dispose = "none", blend = "source" }
+ end
+ local out = like(first, first.width, first.height)
+ buffer.copy(out.pixels, 0, first.pixels, 0, buffer.len(out.pixels))
+ out.frames = frames :: any
+ out.loops = 0
+ return out
+end
+
+return ImageOps
diff --git a/tests/codecs/dct.luau b/tests/codecs/dct.luau
new file mode 100644
index 0000000..0e45a54
--- /dev/null
+++ b/tests/codecs/dct.luau
@@ -0,0 +1,158 @@
+-- codecs/Dct tests: the islow inverse DCT against a double-precision reference (within 1 level per sample, as T.81
+-- annex A accuracy needs), forward DCT + quantiser against the reference transform (round to nearest of v / (8 q)),
+-- fdct -> idct round trips at q = 1 within 1 level, edge replication of fdctQuantize, and garbage coefficients never
+-- throw (outputs stay clamped). The bit-exact djpeg / cjpeg checks are in tests/image/jpeg.luau.
+local T = require("@tests/T")
+local Dct = require("@formats/codecs/Dct")
+
+local t = T.suite("dct")
+local rand = T.rng(11)
+
+local C = {}
+for u = 0, 7 do
+ C[u] = if u == 0 then math.sqrt(0.5) else 1
+end
+local cosT = {}
+for x = 0, 7 do
+ for u = 0, 7 do
+ cosT[x * 8 + u] = math.cos((2 * x + 1) * u * math.pi / 16)
+ end
+end
+
+local ones = buffer.create(128)
+for i = 0, 63 do
+ buffer.writeu16(ones, i * 2, 1)
+end
+
+-- inverse: random sparse coefficients, compare with the float IDCT
+do
+ local worst = 0
+ for trial = 1, 300 do
+ local coef = buffer.create(128)
+ local F = {}
+ for i = 0, 63 do
+ local v = 0
+ if rand(4) == 0 or i == 0 then
+ v = rand(512) - 256
+ if i == 0 then
+ v = rand(2048) - 1024
+ end
+ end
+ F[i] = v
+ buffer.writei16(coef, i * 2, v)
+ end
+ local plane = buffer.create(128)
+ Dct.idctBlock(coef, 0, ones, plane, 0, 8, 2, 128, 255)
+ for y = 0, 7 do
+ for x = 0, 7 do
+ local s = 0
+ for v = 0, 7 do
+ for u = 0, 7 do
+ s += C[u] * C[v] * F[v * 8 + u] * cosT[x * 8 + u] * cosT[y * 8 + v]
+ end
+ end
+ local want = math.clamp(math.floor(s / 4 + 128 + 0.5), 0, 255)
+ local got = buffer.readu16(plane, (y * 8 + x) * 2)
+ worst = math.max(worst, math.abs(got - want))
+ end
+ end
+ local _ = trial
+ end
+ t:check(worst <= 1, "idct within 1 of the float reference: " .. worst)
+ t:note("idct: worst error %d over 300 random blocks", worst)
+end
+
+-- forward + quantiser
+do
+ local worst = 0
+ for _ = 1, 200 do
+ local src = buffer.create(64)
+ for i = 0, 63 do
+ buffer.writeu8(src, i, rand(256))
+ end
+ local q = buffer.create(128)
+ for i = 0, 63 do
+ buffer.writeu16(q, i * 2, 1 + rand(40))
+ end
+ local coef = buffer.create(128)
+ Dct.fdctQuantize(src, 8, 0, 0, 8, 8, q, coef, 0)
+ for v = 0, 7 do
+ for u = 0, 7 do
+ local s = 0
+ for y = 0, 7 do
+ for x = 0, 7 do
+ s += (buffer.readu8(src, y * 8 + x) - 128) * cosT[x * 8 + u] * cosT[y * 8 + v]
+ end
+ end
+ s *= C[u] * C[v] / 4
+ local want = s / buffer.readu16(q, (v * 8 + u) * 2)
+ worst = math.max(worst, math.abs(buffer.readi16(coef, (v * 8 + u) * 2) - want))
+ end
+ end
+ end
+ t:check(worst <= 0.75, "fdct + quantise within rounding of the float reference: " .. worst)
+ -- round trip at q = 1
+ local rt = 0
+ for _ = 1, 100 do
+ local src = buffer.create(64)
+ for i = 0, 63 do
+ buffer.writeu8(src, i, rand(256))
+ end
+ local coef = buffer.create(128)
+ Dct.fdctQuantize(src, 8, 0, 0, 8, 8, ones, coef, 0)
+ local plane = buffer.create(128)
+ Dct.idctBlock(coef, 0, ones, plane, 0, 8, 2, 128, 255)
+ for i = 0, 63 do
+ rt = math.max(rt, math.abs(buffer.readu16(plane, i * 2) - buffer.readu8(src, i)))
+ end
+ end
+ t:check(rt <= 1, "fdct -> idct round trip at q = 1: " .. rt)
+ -- edge replication: a 3x2 image is the same as its 8x8 edge-extended version
+ local small = T.bytes({ 10, 200, 30, 40, 50, 250 })
+ local ext = buffer.create(64)
+ for y = 0, 7 do
+ for x = 0, 7 do
+ buffer.writeu8(ext, y * 8 + x, buffer.readu8(small, math.min(y, 1) * 3 + math.min(x, 2)))
+ end
+ end
+ local a, b = buffer.create(128), buffer.create(128)
+ Dct.fdctQuantize(small, 3, 0, 0, 3, 2, ones, a, 0)
+ Dct.fdctQuantize(ext, 8, 0, 0, 8, 8, ones, b, 0)
+ t:check(buffer.tostring(a) == buffer.tostring(b), "edge replication")
+end
+
+-- components and garbage: clamped output, no throw
+do
+ local coef = buffer.create(4 * 3 * 128)
+ for i = 0, buffer.len(coef) // 2 - 1 do
+ buffer.writei16(coef, i * 2, rand(65536) - 32768)
+ end
+ local q = buffer.create(128)
+ for i = 0, 63 do
+ buffer.writeu16(q, i * 2, rand(65536))
+ end
+ for _, size in { 8, 4, 2, 1 } do
+ for _, prec in { { 2, 128, 255 }, { 1, 2048, 4095 } } do
+ local plane = buffer.create(4 * size * 3 * size * 2)
+ local ok = pcall(Dct.idctComponent, coef, q, 4, 3, size, plane, prec[1], prec[2], prec[3])
+ t:check(ok, "idctComponent size " .. size .. " on garbage")
+ local inRange = true
+ for i = 0, buffer.len(plane) // 2 - 1 do
+ if buffer.readu16(plane, i * 2) > prec[3] then
+ inRange = false
+ end
+ end
+ t:check(inRange, "clamped output, size " .. size)
+ end
+ end
+ local samples = { string.rep("\0", 128) }
+ t:fuzz("idctBlock", function(b: buffer)
+ local cb = buffer.create(128)
+ buffer.copy(cb, 0, b, 0, math.min(128, buffer.len(b)))
+ local plane = buffer.create(128)
+ Dct.idctBlock(cb, 0, q, plane, 0, 8, 2, 128, 255)
+ return plane
+ end, samples, { garbage = 50 })
+end
+
+t:done()
diff --git a/tests/codecs/lzw.luau b/tests/codecs/lzw.luau
new file mode 100644
index 0000000..04fe064
--- /dev/null
+++ b/tests/codecs/lzw.luau
@@ -0,0 +1,119 @@
+-- codecs/Lzw tests: GIF (LSB) and TIFF (MSB, early change) code streams from Pillow / libtiff decode to their data;
+-- our encoder round-trips random and structured data at every GIF minimum code size and through table resets; the
+-- output limit, truncated and corrupt streams; the fuzz no-throw pass. Fixtures: tools/fixtures/lzw.py.
+local T = require("@tests/T")
+local Lzw = require("@formats/codecs/Lzw")
+local Fx = require("@tests/gen/lzw")
+
+local t = T.suite("lzw")
+
+local function dec(codes: buffer, n: number, variant: string, min: number?): (string, number, string?)
+ local out = buffer.create(n)
+ local got, err = Lzw.decode(codes, 0, buffer.len(codes), out, 0, n, variant, min)
+ return buffer.tostring(out), got, err
+end
+
+-- reference streams
+for _, c in Fx.gif do
+ local s, n, err = dec(buffer.fromstring(c.codes), #c.data, "gif", c.min)
+ t:check(err == nil, "gif " .. c.name .. ": " .. tostring(err))
+ t:eq(n, #c.data, "gif " .. c.name .. ": length")
+ t:check(s == c.data, "gif " .. c.name .. ": data")
+end
+for _, c in Fx.tiff do
+ local s, n, err = dec(buffer.fromstring(c.codes), #c.data, "tiff")
+ t:check(err == nil, "tiff " .. c.name .. ": " .. tostring(err))
+ t:eq(n, #c.data, "tiff " .. c.name .. ": length")
+ t:check(s == c.data, "tiff " .. c.name .. ": data")
+end
+t:note("%d GIF and %d TIFF reference streams decode", #Fx.gif, #Fx.tiff)
+
+-- round trips
+local rand = T.rng(3)
+local function data(n: number, kind: number, max: number): buffer
+ local b = buffer.create(n)
+ for i = 0, n - 1 do
+ local v
+ if kind == 0 then
+ v = rand(max)
+ elseif kind == 1 then
+ v = (i // 7) % max
+ else
+ v = if rand(10) == 0 then rand(max) else (i % 13) % max
+ end
+ buffer.writeu8(b, i, v)
+ end
+ return b
+end
+local trips = 0
+for _, n in { 0, 1, 2, 3, 100, 5000, 70000 } do
+ for kind = 0, 2 do
+ for min = 2, 8 do
+ local d = data(n, kind, 2 ^ min)
+ local codes = Lzw.encode(d, 0, n, "gif", min)
+ local s, got, err = dec(codes, n, "gif", min)
+ t:check(err == nil and got == n and s == buffer.tostring(d), string.format("gif round trip n=%d kind=%d min=%d: %s", n, kind, min, tostring(err)))
+ trips += 1
+ end
+ local d = data(n, kind, 256)
+ local codes = Lzw.encode(d, 0, n, "tiff")
+ local s, got, err = dec(codes, n, "tiff")
+ t:check(err == nil and got == n and s == buffer.tostring(d), string.format("tiff round trip n=%d kind=%d: %s", n, kind, tostring(err)))
+ trips += 1
+ end
+end
+t:note("%d round trips", trips)
+
+-- compression actually happens; a range inside a bigger buffer
+do
+ local d = buffer.create(10000)
+ local codes = Lzw.encode(d, 0, 10000, "tiff")
+ t:check(buffer.len(codes) < 400, "zeros compress: " .. buffer.len(codes))
+ local big = data(300, 1, 256)
+ local codes2 = Lzw.encode(big, 100, 100, "gif", 8)
+ local out = buffer.create(120)
+ local n = Lzw.decode(codes2, 0, buffer.len(codes2), out, 10, 100, "gif", 8)
+ t:eq(n, 100, "sub-range length")
+ t:check(buffer.readstring(out, 10, 100) == buffer.readstring(big, 100, 100), "sub-range data")
+end
+
+-- limits, truncation, corruption
+do
+ local d = data(1000, 2, 16)
+ local codes = Lzw.encode(d, 0, 1000, "gif", 4)
+ local s, n, err = dec(codes, 500, "gif", 4)
+ t:check(n == 500 and err == nil and s == buffer.readstring(d, 0, 500), "output limit")
+ local cut = buffer.create(buffer.len(codes) // 2)
+ buffer.copy(cut, 0, codes, 0, buffer.len(cut))
+ local _, n2, err2 = dec(cut, 1000, "gif", 4)
+ t:check(err2 == "truncated" and n2 > 0 and n2 < 1000, "truncated: " .. tostring(err2))
+ local bad = buffer.fromstring("\255\255\255\255")
+ local _, _, err3 = dec(bad, 100, "gif", 2)
+ t:check(err3 == "corrupt", "corrupt: " .. tostring(err3))
+ local _, _, err4 = dec(codes, 100, "gif", 0)
+ t:check(err4 == "corrupt", "bad min code size")
+end
+
+-- fuzz
+do
+ local samples = {}
+ for i, c in Fx.gif do
+ if i % 2 == 1 then
+ table.insert(samples, c.codes)
+ end
+ end
+ for i, c in Fx.tiff do
+ if i % 2 == 0 then
+ table.insert(samples, c.codes)
+ end
+ end
+ local out = buffer.create(100000)
+ t:fuzz("decode gif", function(b: buffer)
+ return Lzw.decode(b, 0, buffer.len(b), out, 0, 100000, "gif", 8)
+ end, samples)
+ t:fuzz("decode tiff", function(b: buffer)
+ return Lzw.decode(b, 0, buffer.len(b), out, 0, 100000, "tiff")
+ end, samples)
+end
+
+t:done()
diff --git a/tests/codecs/quantize.luau b/tests/codecs/quantize.luau
new file mode 100644
index 0000000..7569e55
--- /dev/null
+++ b/tests/codecs/quantize.luau
@@ -0,0 +1,135 @@
+-- codecs/Quantize tests: palette size bounds for every method and colour budget, the exact (lossless) palette at
+-- <= maxColors colours, transparency handling, PSNR of quantized images above thresholds, determinism of both
+-- methods and of Floyd-Steinberg dithering (the same CRC on both runtimes), bad arguments, and a no-throw pass.
+local T = require("@tests/T")
+local Quantize = require("@formats/codecs/Quantize")
+local Crc32 = require("@formats/core/Crc32")
+
+local t = T.suite("quantize")
+local rand = T.rng(5)
+
+local function photo(w: number, h: number): buffer
+ local px = buffer.create(w * h * 4)
+ for i = 0, w * h - 1 do
+ local x, y = i % w, i // w
+ local r = (x * 255) // (w - 1)
+ local g = (y * 255) // (h - 1)
+ local b = math.floor(128 + 100 * math.sin(x * 0.11) * math.cos(y * 0.07)) + rand(9)
+ buffer.writeu32(px, i * 4, r + g * 256 + math.clamp(b, 0, 255) * 65536 + 0xFF000000)
+ end
+ return px
+end
+
+local function render(idx: buffer, pal: { { number } }, n: number): buffer
+ local out = buffer.create(n * 4)
+ for i = 0, n - 1 do
+ local c = pal[buffer.readu8(idx, i) + 1]
+ buffer.writeu32(out, i * 4, c[1] + c[2] * 256 + c[3] * 65536 + 0xFF000000)
+ end
+ return out
+end
+
+local function psnr(a: buffer, b: buffer): number
+ local se, n = 0, 0
+ for o = 0, buffer.len(a) - 4, 4 do
+ for k = 0, 2 do
+ local d = buffer.readu8(a, o + k) - buffer.readu8(b, o + k)
+ se += d * d
+ n += 1
+ end
+ end
+ return if se == 0 then 99 else 10 * math.log10(255 * 255 * n / se)
+end
+
+local W, H = 128, 96
+local px = photo(W, H)
+-- palette bounds and quality
+local MIN_PSNR = { [256] = 30, [64] = 24, [16] = 17, [2] = 10 }
+for _, method in { "mediancut", "octree" } do
+ for _, k in { 2, 16, 64, 256 } do
+ local pal, exact = Quantize.palette(px, W, H, k, { method = method })
+ t:check(#pal >= 1 and #pal <= k, string.format("%s %d: palette size %d", method, k, #pal))
+ t:check(not exact, method .. ": not exact")
+ for _, c in pal do
+ t:check(#c == 4 and c[4] == 255 and c[1] % 1 == 0 and c[1] >= 0 and c[1] <= 255, "palette entries")
+ end
+ for _, dither in { false, true } do
+ local idx = Quantize.map(px, W, H, pal, { dither = dither })
+ t:eq(buffer.len(idx), W * H, "index buffer size")
+ local p = psnr(render(idx, pal, W * H), px)
+ local want = MIN_PSNR[k] - (if dither then 4 else 0)
+ t:check(p > want, string.format("%s %d dither=%s: PSNR %.1f > %d", method, k, tostring(dither), p, want))
+ if k == 256 or k == 16 then
+ t:note("%-9s %3d colours dither=%-5s PSNR %.1f dB, crc %08x", method, k, tostring(dither), p, Crc32.of(idx))
+ end
+ end
+ end
+end
+
+-- exact palettes: lossless
+do
+ local n = 50 * 40
+ local b = buffer.create(n * 4)
+ for i = 0, n - 1 do
+ local k = (i * 7 + i // 50) % 200
+ buffer.writeu32(b, i * 4, (k * 3) % 256 + ((k * 11) % 256) * 256 + k * 65536 + 0xFF000000)
+ end
+ local pal, exact = Quantize.palette(b, 50, 40, 256)
+ t:check(exact and #pal == 200, "exact palette of 200 colours: " .. #pal)
+ local idx = Quantize.map(b, 50, 40, pal, { dither = true })
+ t:check(buffer.tostring(render(idx, pal, n)) == buffer.tostring(b), "exact palette maps losslessly (dither too)")
+ local pal2, exact2 = Quantize.palette(b, 50, 40, 199)
+ t:check(not exact2 and #pal2 <= 199, "199 colours is not exact")
+ local i3, p3, e3 = Quantize.quantize(b, 50, 40, 256, { dither = true })
+ t:check(e3 and #p3 == 200 and buffer.tostring(render(i3, p3, n)) == buffer.tostring(b), "quantize() exact")
+end
+
+-- transparency
+do
+ local b = buffer.create(16 * 4)
+ for i = 0, 15 do
+ buffer.writeu32(b, i * 4, if i % 3 == 0 then 0x10FFFFFF else 0xFF0000FF + i * 256)
+ end
+ local pal, exact = Quantize.palette(b, 4, 4, 255)
+ t:check(exact and #pal == 10, "transparent pixels are not in the palette")
+ table.insert(pal, { 0, 0, 0, 0 })
+ local idx = Quantize.map(b, 4, 4, pal, { transparentIndex = #pal - 1, dither = true })
+ for i = 0, 15 do
+ local v = buffer.readu8(idx, i)
+ t:check((i % 3 == 0) == (v == #pal - 1), "transparent index " .. i)
+ end
+end
+
+-- determinism (also across runtimes: these CRCs are pinned)
+do
+ local pal = Quantize.palette(px, W, H, 64, { method = "mediancut" })
+ local a = Crc32.of(Quantize.map(px, W, H, pal, { dither = true }))
+ local pal2 = Quantize.palette(px, W, H, 64, { method = "mediancut" })
+ t:eq(Crc32.of(Quantize.map(px, W, H, pal2, { dither = true })), a, "mediancut + dither deterministic")
+ t:eq(a, 0x50c4e466, "mediancut 64 + dither: the pinned CRC (the same on both runtimes)")
+ local o1 = Quantize.palette(px, W, H, 37, { method = "octree" })
+ local o2 = Quantize.palette(px, W, H, 37, { method = "octree" })
+ t:check(#o1 == #o2 and o1[#o1][1] == o2[#o2][1], "octree deterministic")
+end
+
+-- bad arguments never throw
+do
+ t:eq(#Quantize.palette(nil :: any, 1, 1, 4), 0, "nil pixels")
+ t:eq(#Quantize.palette(buffer.create(3), 1, 1, 4), 0, "short buffer")
+ t:eq(buffer.len(Quantize.map(px, W, H, {})), W * H, "empty palette")
+ t:eq(buffer.len(Quantize.map(buffer.create(1), 2, 2, { { 1, 2, 3, 255 } })), 0, "short buffer map")
+ local ok = pcall(function()
+ for i = 1, 20 do
+ local w, h = 1 + rand(20), 1 + rand(20)
+ local b = buffer.create(w * h * 4)
+ for k = 0, w * h * 4 - 1 do
+ buffer.writeu8(b, k, rand(256))
+ end
+ local pal = Quantize.palette(b, w, h, 1 + rand(256), { method = if i % 2 == 0 then "octree" else "mediancut" })
+ Quantize.map(b, w, h, pal, { dither = i % 3 == 0, transparentIndex = if i % 4 == 0 then 0 else nil })
+ end
+ end)
+ t:check(ok, "random images never throw")
+end
+
+t:done()
diff --git a/tests/image/gif.luau b/tests/image/gif.luau
new file mode 100644
index 0000000..a2ccae8
--- /dev/null
+++ b/tests/image/gif.luau
@@ -0,0 +1,221 @@
+-- image/gif tests: GIFs from ImageMagick and Pillow (static, interlaced, 2..256 colours, grey, transparency,
+-- animations with every disposal, sub-rectangles, local colour tables, loop counts, comments) against ImageMagick's
+-- decode of every frame; the encoder (lossless round trips at <= 256 colours, quantized PSNR above, animations with
+-- frames / delays / disposal / transparency / loops, options); error codes; the fuzz no-throw pass.
+-- Fixtures: tools/fixtures/gif.py.
+local T = require("@tests/T")
+local Gif = require("@formats/image/gif")
+local Bytes = require("@formats/core/Bytes")
+local Crc32 = require("@formats/core/Crc32")
+local Err = require("@formats/core/Err")
+local Types = require("@formats/Types")
+local Fx = require("@tests/gen/gif")
+
+local t = T.suite("gif")
+
+local function decode(data: any, opts: any?): (any, any)
+ local b = if type(data) == "string" then buffer.fromstring(data) else data
+ return Gif.decode(Bytes.reader(b), opts)
+end
+
+-- rgba8 with alpha-0 pixels zeroed (the fixtures' convention)
+local function norm(px: buffer): buffer
+ local n = buffer.len(px)
+ local c = buffer.create(n)
+ buffer.copy(c, 0, px)
+ for o = 0, n - 4, 4 do
+ if buffer.readu8(c, o + 3) == 0 then
+ buffer.writeu32(c, o, 0)
+ end
+ end
+ return c
+end
+
+-- the contract
+t:eq(Gif.name, "gif", "name")
+t:eq(Gif.category, "image", "category")
+t:check(Gif.caps.decode and Gif.caps.encode and Gif.caps.animation, "caps")
+
+-- every fixture against ImageMagick
+local nframes = 0
+for _, c in Fx do
+ local img, err = decode(c.data)
+ t:check(img, c.name .. ": " .. tostring(err))
+ t:check(img.width == c.width and img.height == c.height and img.format == "rgba8", c.name .. ": canvas")
+ t:check(not img.meta.truncated, c.name .. ": flagged truncated")
+ t:eq(Crc32.of(norm(img.pixels)), c.first, c.name .. ": first frame composited")
+ local frames = img.frames or { { image = img, x = 0, y = 0, delay = 0, dispose = "none" } }
+ t:eq(#frames, #c.frames, c.name .. ": frame count")
+ for i, rf in c.frames do
+ local f = frames[i]
+ local label = c.name .. " frame " .. i
+ if img.frames then
+ t:check(f.image.width == rf.w and f.image.height == rf.h and f.x == rf.x and f.y == rf.y, label .. ": rectangle")
+ t:eq(math.floor(f.delay * 100 + 0.5), rf.delay, label .. ": delay")
+ local want = if rf.dispose == "undefined" then "none" else rf.dispose
+ t:eq(f.dispose, want, label .. ": dispose")
+ t:eq(Crc32.of(norm(f.image.pixels)), rf.crc, label .. ": pixels")
+ else
+ t:eq(Crc32.of(norm(img.pixels)), rf.crc, label .. ": pixels")
+ end
+ nframes += 1
+ end
+ if c.loops then
+ t:eq(img.loops, if c.loops == 0 then 0 else c.loops + 1, c.name .. ": loops (plays)")
+ end
+ if c.comment then
+ t:eq(img.meta.text and img.meta.text.comment, c.comment, c.name .. ": comment")
+ end
+end
+t:note("%d files, %d frames match ImageMagick", #Fx, nframes)
+
+-- sniff, meta, limits, errors
+do
+ local c = Fx[1]
+ t:eq(Gif.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, "sniff a GIF")
+ t:eq(Gif.sniff(Bytes.reader(buffer.fromstring("\137PNG\r\n\26\n"))), 0, "sniff a PNG")
+ t:eq(Gif.sniff(Bytes.reader(buffer.create(0))), 0, "sniff nothing")
+ local img = decode(c.data)
+ t:check(img.meta.source.format == "gif" and img.meta.source.version == "89a", "meta.source")
+ t:check(img.meta.palette and #img.meta.palette >= 2 and #img.meta.palette[1] == 4, "meta.palette")
+ local _, e = decode(c.data, { maxPixels = 100 })
+ t:check(e and e.code == Err.LIMIT, "maxPixels: " .. tostring(e))
+ local _, e2 = decode("GIF89a")
+ t:check(e2 and e2.code == Err.TRUNCATED, "header only: " .. tostring(e2))
+ local _, e3 = decode("NOTGIF1234567")
+ t:check(e3 and e3.code == Err.CORRUPT, "junk: " .. tostring(e3))
+ -- a truncated file keeps its frames
+ for _, f in Fx do
+ if f.name == "anim_none" then
+ local cut = string.sub(f.data, 1, #f.data - 20)
+ local part = decode(cut)
+ t:check(part and part.meta.truncated, "truncated animation decodes partially")
+ local one = decode(f.data, { maxFrames = 1 })
+ t:check(one and one.frames == nil, "maxFrames = 1")
+ local big = buffer.create(#f.data + 9)
+ buffer.writestring(big, 5, f.data)
+ local sub = Gif.decode(Bytes.reader(big, 5, #f.data))
+ t:check(sub and sub.frames and #sub.frames == 4, "decode from a sub-range")
+ end
+ end
+end
+
+-- the encoder
+local rand = T.rng(17)
+local function image(w: number, h: number, colors: number?, alpha: boolean?): Types.Image
+ local img = Types.Image.new(w, h)
+ for i = 0, w * h - 1 do
+ local x, y = i % w, i // w
+ local r, g, b
+ if colors then
+ local k = (x // 3 + y // 2 * 7 + rand(2)) % colors
+ r, g, b = (k * 53) % 256, (k * 97) % 256, (k * 31) % 256
+ else
+ r, g, b = (x * 255) // math.max(1, w - 1), (y * 255) // math.max(1, h - 1), ((x + y) * 3 + rand(16)) % 256
+ end
+ local a = if alpha and (x * x + y * y) % 11 == 0 then 0 else 255
+ buffer.writeu32(img.pixels, i * 4, r + g * 256 + b * 65536 + a * 16777216)
+ end
+ return img
+end
+local function same(a: buffer, b: buffer): boolean
+ return buffer.tostring(norm(a)) == buffer.tostring(norm(b))
+end
+local function psnr(a: buffer, b: buffer): number
+ local se, n = 0, 0
+ for o = 0, buffer.len(a) - 4, 4 do
+ for k = 0, 2 do
+ local d = buffer.readu8(a, o + k) - buffer.readu8(b, o + k)
+ se += d * d
+ n += 1
+ end
+ end
+ if se == 0 then
+ return 99
+ end
+ return 10 * math.log10(255 * 255 * n / se)
+end
+do
+ for _, colors in { 2, 3, 16, 200, 256 } do
+ for _, alpha in { false, true } do
+ local ncol = if alpha and colors == 256 then 255 else colors
+ local img = image(37, 23, ncol, alpha)
+ local gif, err = Gif.encode(img)
+ t:check(gif, "encode: " .. tostring(err))
+ local back = decode(gif)
+ t:check(back and same(back.pixels, img.pixels), string.format("%d colours alpha=%s: lossless round trip", ncol, tostring(alpha)))
+ t:check(back.frames == nil, "single image")
+ end
+ end
+ -- more than 256 colours: quantized, every method, with and without dithering
+ local photo = image(96, 64)
+ for _, method in { "mediancut", "octree" } do
+ for _, dither in { false, true } do
+ local gif = Gif.encode(photo, { method = method, dither = dither }) :: buffer
+ local back = decode(gif)
+ local p = psnr(back.pixels, photo.pixels)
+ t:check(p > (if dither then 28 else 30), string.format("%s dither=%s: PSNR %.1f", method, tostring(dither), p))
+ t:note("encode %s dither=%s: %d bytes, PSNR %.1f dB", method, tostring(dither), buffer.len(gif), p)
+ end
+ end
+ local small = Gif.encode(photo, { maxColors = 4 }) :: buffer
+ local sb = decode(small)
+ t:check(sb.meta.palette and #sb.meta.palette <= 4, "maxColors = 4")
+ -- animation: frames, delays, disposal, transparency, loops, comment, local / global palettes
+ local anim = image(40, 30, 50)
+ anim.frames = {
+ { image = image(40, 30, 50), x = 0, y = 0, delay = 0.1, dispose = "none", blend = "source" },
+ { image = image(10, 12, 7, true), x = 5, y = 6, delay = 0.25, dispose = "background", blend = "over" },
+ { image = image(20, 5), x = 20, y = 25, delay = 1.5, dispose = "previous", blend = "source" },
+ }
+ anim.loops = 4
+ anim.meta.text = { comment = "hello gif" }
+ for _, global in { false, true } do
+ local gif, err = Gif.encode(anim, { globalPalette = global })
+ t:check(gif, "animation encode: " .. tostring(err))
+ local back = decode(gif)
+ t:check(back.frames and #back.frames == 3, "animation frames")
+ t:eq(back.loops, 4, "loops")
+ t:eq(back.meta.text.comment, "hello gif", "comment")
+ for i, f in anim.frames :: { Types.Frame } do
+ local g = back.frames[i]
+ t:check(g.x == f.x and g.y == f.y and g.image.width == f.image.width and g.image.height == f.image.height, "frame rectangle " .. i)
+ t:eq(g.delay, f.delay, "frame delay " .. i)
+ t:eq(g.dispose, f.dispose, "frame dispose " .. i)
+ end
+ t:check(same(back.frames[1].image.pixels, anim.frames[1].image.pixels), "frame 1 lossless")
+ t:check(same(back.frames[2].image.pixels, anim.frames[2].image.pixels), "frame 2 lossless (transparency)")
+ t:eq(back.frames[2].blend, "over", "frame 2 blend")
+ t:check(psnr(back.frames[3].image.pixels, anim.frames[3].image.pixels) > 25, "frame 3 quantized")
+ t:eq(back.meta.source.localPalettes, if global then 0 else 3, "palettes")
+ end
+ -- deterministic output
+ t:eq(Crc32.of(Gif.encode(photo, { dither = true }) :: buffer), Crc32.of(Gif.encode(photo, { dither = true }) :: buffer), "deterministic")
+ -- bad arguments
+ local _, e = Gif.encode({} :: any)
+ t:check(e and e.code == Err.ARG, "encode of a non-image")
+ local _, e2 = Gif.encode(photo, { maxColors = 1 })
+ t:check(e2 and e2.code == Err.ARG, "maxColors = 1")
+ local _, e3 = Gif.encode(photo, { method = "kmeans" } :: any)
+ t:check(e3 and e3.code == Err.ARG, "unknown method")
+ local _, e4 = Gif.encode(Types.Image.new(70000, 1))
+ t:check(e4 and e4.code == Err.ARG, "too wide")
+end
+
+-- fuzz
+do
+ local samples = {}
+ for _, c in Fx do
+ if #c.data < 40000 then
+ table.insert(samples, c.data)
+ end
+ end
+ t:fuzz("decode", function(b: buffer)
+ return Gif.decode(Bytes.reader(b))
+ end, samples, { mutations = 12, keepHeader = 6 })
+ t:fuzz("decode (header too)", function(b: buffer)
+ return Gif.decode(Bytes.reader(b), { maxPixels = 1e6 })
+ end, samples, { mutations = 4, garbage = 50 })
+end
+
+t:done()
diff --git a/tests/image/hdr.luau b/tests/image/hdr.luau
new file mode 100644
index 0000000..b923ef2
--- /dev/null
+++ b/tests/image/hdr.luau
@@ -0,0 +1,117 @@
+-- image/hdr tests: ImageMagick-written Radiance files (new-style RLE) against its float decodes, hand-written ones
+-- (flat and old-style RLE scanlines, "#?RGBE", EXPOSURE products, all orientations) against the rgbe.c rule; the
+-- display conversion to rgba8; our encoder round-trips (RLE and flat, rgbaf32 and rgba8) within RGBE precision;
+-- errors; the fuzz no-throw pass. Fixtures: tools/fixtures/hdr.py.
+local T = require("@tests/T")
+local Hdr = require("@formats/image/hdr")
+local Bytes = require("@formats/core/Bytes")
+local Err = require("@formats/core/Err")
+local Types = require("@formats/Types")
+local Fx = require("@tests/gen/hdr")
+
+local t = T.suite("hdr")
+
+t:eq(Hdr.name, "hdr", "name")
+t:check(Hdr.caps.decode and Hdr.caps.encode, "caps")
+
+local function dec(data: any, opts: any?): (any, any)
+ return Hdr.decode(Bytes.reader(if type(data) == "string" then buffer.fromstring(data) else data), opts)
+end
+
+-- worst relative error between two rgbaf32 buffers
+local function relErr(a: buffer, b: buffer, n: number): number
+ local worst = 0
+ for i = 0, n * 4 - 1 do
+ local x, y = buffer.readf32(a, i * 4), buffer.readf32(b, i * 4)
+ local d = math.abs(x - y) / math.max(math.abs(y), 1e-30)
+ if math.abs(x - y) > 1e-30 then
+ worst = math.max(worst, d)
+ end
+ end
+ return worst
+end
+
+for _, c in Fx do
+ local img, err = dec(c.data, { native = true })
+ t:check(img, c.name .. ": " .. tostring(err))
+ t:check(img.width == c.width and img.height == c.height and img.format == "rgbaf32", c.name .. ": size")
+ local e = relErr(img.pixels, buffer.fromstring(c.floats), c.width * c.height)
+ t:check(e < 1e-6, string.format("%s: relative error %g against the reference", c.name, e))
+ if c.exposure then
+ t:check(math.abs(img.meta.exposure - c.exposure) < 1e-9, c.name .. ": exposure")
+ end
+ -- the default rgba8 display conversion
+ local d8 = dec(c.data)
+ t:eq(d8.format, "rgba8", c.name .. ": rgba8 by default")
+ local v = buffer.readf32(img.pixels, 0)
+ t:eq(buffer.readu8(d8.pixels, 0), math.floor(math.clamp(v, 0, 1) ^ (1 / 2.2) * 255 + 0.5), c.name .. ": display curve")
+ -- round trips: RGBE is lossless for values already on its grid
+ for _, rle in { true, false } do
+ local enc = Hdr.encode(img, { rle = rle }) :: buffer
+ local back = dec(enc, { native = true })
+ local re = relErr(back.pixels, img.pixels, c.width * c.height)
+ t:check(re < 1e-6, string.format("%s: round trip rle=%s relative error %g", c.name, tostring(rle), re))
+ end
+end
+t:note("%d files match their references and round-trip", #Fx)
+
+do
+ -- arbitrary floats: RGBE keeps about 1% relative precision on the largest channel
+ local rand = T.rng(8)
+ local img = Types.Image.new(40, 10, "rgbaf32")
+ for i = 0, 399 do
+ for c = 0, 2 do
+ buffer.writef32(img.pixels, i * 16 + c * 4, rand(100000) / 1000)
+ end
+ buffer.writef32(img.pixels, i * 16 + 12, 1)
+ end
+ local back = dec(Hdr.encode(img) :: buffer, { native = true })
+ local worst = 0
+ for i = 0, 399 do
+ local m = 0
+ for c = 0, 2 do
+ m = math.max(m, buffer.readf32(img.pixels, i * 16 + c * 4))
+ end
+ for c = 0, 2 do
+ worst = math.max(worst, math.abs(buffer.readf32(back.pixels, i * 16 + c * 4) - buffer.readf32(img.pixels, i * 16 + c * 4)) / math.max(m, 1e-9))
+ end
+ end
+ t:check(worst < 1 / 128, "float precision " .. worst)
+ -- rgba8 in, rgba8 out
+ local i8 = Types.Image.new(9, 2)
+ for i = 0, 17 do
+ buffer.writeu32(i8.pixels, i * 4, 0xFF000000 + (i * 14) * 0x10101)
+ end
+ local b8 = dec(Hdr.encode(i8) :: buffer)
+ local w8 = 0
+ for i = 0, 71 do
+ w8 = math.max(w8, math.abs(buffer.readu8(b8.pixels, i) - buffer.readu8(i8.pixels, i)))
+ end
+ t:check(w8 <= 2, "rgba8 round trip within 2: " .. w8)
+ local ex = dec(Hdr.encode(img, { exposure = 0.5 }) :: buffer)
+ t:eq(ex.meta.exposure, 0.5, "exposure written")
+ t:eq(Hdr.sniff(Bytes.reader(buffer.fromstring("#?RADIANCE\n"))), 1, "sniff")
+ t:eq(Hdr.sniff(Bytes.reader(buffer.fromstring("P6\n"))), 0, "sniff other")
+ local _, e1 = dec("#?RADIANCE\nFORMAT=32-bit_rle_xyze\n\n-Y 1 +X 1\n\0\0\0\0")
+ t:check(e1 and e1.code == Err.UNSUPPORTED, "xyze unsupported")
+ local _, e2 = dec("#?RADIANCE\n\n-Y 10 +X 10\n", { maxPixels = 50 })
+ t:check(e2 and e2.code == Err.LIMIT, "maxPixels")
+ local _, e3 = dec("#?RADIANCE\n\nnonsense\n")
+ t:check(e3 and e3.code == Err.CORRUPT, "bad resolution")
+ local tr = dec(string.sub(Fx[1].data, 1, #Fx[1].data // 2))
+ t:check(tr and tr.meta.truncated, "truncated data flagged")
+ local _, e4 = Hdr.encode(Types.Image.new(1, 1, "gray8"))
+ t:check(e4 and e4.code == Err.ARG, "gray8 refused")
+end
+
+do
+ local samples = {}
+ for _, c in Fx do
+ table.insert(samples, c.data)
+ end
+ t:fuzz("decode", function(b: buffer)
+ return Hdr.decode(Bytes.reader(b))
+ end, samples)
+end
+
+t:done()
diff --git a/tests/image/ico.luau b/tests/image/ico.luau
new file mode 100644
index 0000000..00397f4
--- /dev/null
+++ b/tests/image/ico.luau
@@ -0,0 +1,123 @@
+-- image/ico tests: ImageMagick- and Pillow-written icons (PNG and BMP entries, a 256 PNG entry) and hand-built ones
+-- (1 / 4 / 8 / 24 / 32-bit DIBs with AND masks, a cursor with hotspots) against Pillow's decode of every entry; PNG
+-- entries through opts.decodeImage (and UNSUPPORTED without it); the main image is the largest entry; our encoder
+-- (DIB, PNG through opts.encodeImage, cursors) round-trips; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/ico.py.
+local T = require("@tests/T")
+local Ico = require("@formats/image/ico")
+local Png = require("@formats/image/png")
+local Bytes = require("@formats/core/Bytes")
+local Err = require("@formats/core/Err")
+local Types = require("@formats/Types")
+local Fx = require("@tests/gen/ico")
+
+local t = T.suite("ico")
+
+t:eq(Ico.name, "ico", "name")
+t:check(Ico.caps.decode and Ico.caps.encode, "caps")
+
+local hooks = {
+ decodeImage = function(b: buffer)
+ return Png.decode(Bytes.reader(b))
+ end,
+ encodeImage = function(img: any, _fmt: string)
+ return Png.encode(img)
+ end,
+}
+
+local function dec(data: any, opts: any?): (any, any)
+ return Ico.decode(Bytes.reader(if type(data) == "string" then buffer.fromstring(data) else data), opts)
+end
+
+local entries = 0
+for _, c in Fx do
+ local img, err = dec(c.data, hooks)
+ t:check(img, c.name .. ": " .. tostring(err))
+ local frames = img.frames or { { image = img } }
+ t:eq(#frames, #c.entries, c.name .. ": entry count")
+ local biggest = 0
+ for i, e in c.entries do
+ local f = frames[i].image
+ t:check(f.width == e.width and f.height == e.height, string.format("%s entry %d: size %dx%d, want %dx%d", c.name, i, f.width, f.height, e.width, e.height))
+ local worst = 0
+ for k = 0, #e.rgba - 1 do
+ worst = math.max(worst, math.abs(buffer.readu8(f.pixels, k) - string.byte(e.rgba, k + 1)))
+ end
+ t:check(worst == 0, string.format("%s entry %d: differs from Pillow by %d", c.name, i, worst))
+ biggest = math.max(biggest, e.width * e.height)
+ entries += 1
+ end
+ t:eq(img.width * img.height, biggest, c.name .. ": the main image is the largest entry")
+ -- round trip through our encoder (DIB entries, and PNG for 256 through the hook)
+ local enc, eerr = Ico.encode(img, hooks)
+ t:check(enc, c.name .. ": encode: " .. tostring(eerr))
+ local back = dec(enc, hooks)
+ local bf = back.frames or { { image = back } }
+ t:eq(#bf, #frames, c.name .. ": round trip entries")
+ for i, f in frames do
+ local a, b = f.image, bf[i].image
+ local same = a.width == b.width and a.height == b.height
+ if same then
+ -- alpha-0 pixels keep their colour in 32-bit DIBs too
+ same = buffer.tostring(a.pixels) == buffer.tostring(b.pixels)
+ end
+ t:check(same, string.format("%s: round trip entry %d", c.name, i))
+ end
+end
+t:note("%d icons, %d entries match Pillow and round-trip", #Fx, entries)
+
+do
+ local byName = {}
+ for _, c in Fx do
+ byName[c.name] = c
+ end
+ -- without the hook: PNG entries are skipped, BMP entries still decode
+ local big, sm = Types.Image.new(256, 256), Types.Image.new(16, 16)
+ buffer.fill(big.pixels, 0, 77, 256 * 256 * 4)
+ buffer.fill(sm.pixels, 0, 99, 16 * 16 * 4)
+ local two = Types.Image.new(256, 256)
+ two.frames = { { image = big, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" }, { image = sm, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" } }
+ local mixed = Ico.encode(two, hooks) :: buffer
+ t:eq(buffer.readstring(mixed, 6 + 32, 4), "\137PNG", "the 256 entry is written as PNG through the hook")
+ local im = dec(mixed)
+ t:check(im and im.width == 16 and im.meta.source.skipped == 1, "no hook: the PNG entry is skipped")
+ t:eq(dec(mixed, hooks).width, 256, "with the hook: the PNG entry is the main image")
+ local _, e = dec(byName["pil-png"].data)
+ t:check(e and e.code == Err.UNSUPPORTED, "PNG-only icon without the hook: " .. tostring(e))
+ local cur = dec(byName["hand-cur"].data)
+ t:check(cur.meta.source.type == "cur" and cur.meta.hotspot and cur.meta.hotspot.x == 3 and cur.meta.hotspot.y == 4, "cursor hotspot")
+ t:eq(cur.frames[2].image.meta.hotspot.x, 5, "second hotspot")
+ local cenc = Ico.encode(cur) :: buffer
+ t:eq(buffer.readu16(cenc, 2), 2, "cursor written as CUR")
+ local cb = dec(cenc)
+ t:check(cb.meta.hotspot.x == 3 and cb.frames[2].image.meta.hotspot.y == 6, "hotspots round-trip")
+ -- PNG entries on request
+ local small = Types.Image.new(16, 16)
+ buffer.fill(small.pixels, 0, 200, 16 * 16 * 4)
+ local pe = Ico.encode(small, { png = true, encodeImage = hooks.encodeImage }) :: buffer
+ t:eq(buffer.readstring(pe, 22, 4), "\137PNG", "opts.png writes a PNG entry")
+ local _, e2 = Ico.encode(small, { png = true })
+ t:check(e2 and e2.code == Err.ARG, "opts.png without a hook")
+ local _, e3 = Ico.encode(Types.Image.new(300, 10))
+ t:check(e3 and e3.code == Err.ARG, "over 256 pixels")
+ t:eq(Ico.sniff(Bytes.reader(buffer.fromstring(byName["pil-bmp"].data))), 0.8, "sniff")
+ t:eq(Ico.sniff(Bytes.reader(buffer.fromstring(string.rep("\0", 30)))), 0, "sniff zeros")
+ local _, e4 = dec(string.sub(byName["pil-bmp"].data, 1, 20))
+ t:check(e4 and e4.code == Err.TRUNCATED, "truncated directory")
+end
+
+do
+ local samples = {}
+ for _, c in Fx do
+ if #c.data < 40000 then
+ table.insert(samples, c.data)
+ end
+ end
+ t:fuzz("decode", function(b: buffer)
+ return Ico.decode(Bytes.reader(b), hooks)
+ end, samples)
+ t:fuzz("decode without hooks", function(b: buffer)
+ return Ico.decode(Bytes.reader(b))
+ end, samples, { mutations = 3, garbage = 50 })
+end
+
+t:done()
diff --git a/tests/image/jpeg.luau b/tests/image/jpeg.luau
new file mode 100644
index 0000000..c0af085
--- /dev/null
+++ b/tests/image/jpeg.luau
@@ -0,0 +1,300 @@
+-- image/jpeg tests: every cjpeg / jpegtran fixture (baseline, progressive, arithmetic, every sampling, restarts, grey,
+-- RGB, 12-bit, odd sizes, stripped DHT) against djpeg's decodes at scales 1, 1/2, 1/4, 1/8 (bit-exact, CRC-32);
+-- CMYK / YCCK against Pillow; refused files; info / meta (EXIF orientation applied, ICC, comment, density); the
+-- encoder byte-identical to cjpeg for the same settings, its PSNR, round trips through our decoder; truncated files;
+-- the fuzz no-throw pass. Ported from jpeg-luau tests/jpeg.luau. Fixtures: tools/fixtures/jpeg.py.
+local T = require("@tests/T")
+local Jpeg = require("@formats/image/jpeg")
+local Bytes = require("@formats/core/Bytes")
+local Crc32 = require("@formats/core/Crc32")
+local Err = require("@formats/core/Err")
+local Types = require("@formats/Types")
+local Dec = require("@tests/gen/jpeg_dec")
+local Enc = require("@tests/gen/jpeg_enc")
+
+local t = T.suite("jpeg")
+
+local function decode(data: any, opts: any?): (any, any)
+ local b = if type(data) == "string" then buffer.fromstring(data) else data
+ return Jpeg.decode(Bytes.reader(b), opts)
+end
+
+-- the contract
+t:eq(Jpeg.name, "jpeg", "name")
+t:eq(Jpeg.category, "image", "category")
+t:check(Jpeg.caps.decode and Jpeg.caps.encode, "caps")
+
+-- decodes against djpeg / Pillow
+local files: { [string]: string } = {}
+do
+ local refs, arith = 0, 0
+ for _, c in Dec do
+ files[c.name] = c.data
+ if c.err then
+ local img, err = decode(c.data)
+ t:check(img == nil and err and err.code == Err.UNSUPPORTED and string.find(err.message, c.err, 1, true), c.name .. ": expected UNSUPPORTED " .. c.err .. ", got " .. tostring(err))
+ elseif c.cmyk then
+ local img, err = decode(c.data)
+ t:check(img, c.name .. ": " .. tostring(err))
+ local n = #c.cmyk // 3
+ t:eq(img.width * img.height, n, c.name .. ": size")
+ local worst = 0
+ for i = 0, n - 1 do
+ for k = 0, 2 do
+ worst = math.max(worst, math.abs(buffer.readu8(img.pixels, i * 4 + k) - string.byte(c.cmyk, i * 3 + k + 1)))
+ end
+ end
+ t:check(worst <= 1, c.name .. ": max error " .. worst .. " against Pillow")
+ refs += 1
+ else
+ for _, r in c.refs do
+ local name = c.name .. " 1/" .. r.scale
+ local img, err = decode(c.data, { scale = r.scale })
+ t:check(img, name .. ": " .. tostring(err))
+ t:check(img.width == r.width and img.height == r.height, string.format("%s: size %dx%d, djpeg %dx%d", name, img.width, img.height, r.width, r.height))
+ t:check(not img.meta.truncated, name .. ": flagged truncated")
+ local crc = Crc32.of(img.pixels)
+ t:check(crc == r.crc, string.format("%s: pixels crc %08x, djpeg %08x", name, crc, r.crc))
+ refs += 1
+ if img.meta.source.arithmetic then
+ arith += 1
+ end
+ end
+ end
+ end
+ t:note("%d files, %d decodes bit-exact with djpeg / Pillow (%d arithmetic-coded)", #Dec, refs, arith)
+end
+
+local function file(name: string): buffer
+ return buffer.fromstring(files[name])
+end
+
+-- sniff, info, meta, options
+do
+ t:eq(Jpeg.sniff(Bytes.reader(file("photo_q90_420"))), 1, "sniff a JPEG")
+ t:eq(Jpeg.sniff(Bytes.reader(buffer.fromstring("GIF89a"))), 0, "sniff a GIF")
+ t:eq(Jpeg.sniff(Bytes.reader(buffer.create(0))), 0, "sniff nothing")
+ local i = Jpeg.info(Bytes.reader(file("photo_q90_420_prog")))
+ t:check(i and i.width == 160 and i.height == 120 and i.progressive and i.components == 3, "info: progressive 4:2:0")
+ t:check(i.sampling[1][1] == 2 and i.sampling[1][2] == 2 and i.sampling[2][1] == 1, "info: sampling")
+ t:check(i.colorSpace == "ycbcr" and i.precision == 8 and i.jfif and not i.arithmetic, "info: colour space")
+ t:check(Jpeg.info(Bytes.reader(file("photo_arith_420_prog"))).arithmetic, "info: arithmetic")
+ t:eq(Jpeg.info(Bytes.reader(file("photo_gray"))).colorSpace, "gray", "info: grey")
+ do
+ local g = decode(file("photo_gray"), { native = true })
+ local rgba = decode(file("photo_gray"))
+ t:check(g.format == "gray8" and buffer.len(g.pixels) == g.width * g.height, "native grey decodes to gray8")
+ t:eq(buffer.readu8(g.pixels, 77), buffer.readu8(rgba.pixels, 77 * 4), "gray8 samples")
+ t:eq(decode(file("photo_q90_420"), { native = true }).format, "rgba8", "native colour stays rgba8")
+ end
+ t:eq(Jpeg.info(Bytes.reader(file("photo_rgb"))).colorSpace, "rgb", "info: RGB")
+ t:eq(Jpeg.info(Bytes.reader(file("photo_cmyk"))).colorSpace, "cmyk", "info: CMYK")
+ t:eq(Jpeg.info(Bytes.reader(file("photo_ycck"))).colorSpace, "ycck", "info: YCCK")
+ t:eq(Jpeg.info(Bytes.reader(file("photo_12bit_420"))).precision, 12, "info: 12-bit")
+ local img = decode(file("photo_q90_420_prog"))
+ local s = img.meta.source
+ t:check(img.kind == "image" and img.format == "rgba8", "a standard rgba8 Image")
+ t:check(s.format == "jpeg" and s.progressive and s.components == 3 and s.colorType == "ycbcr" and img.meta.orientation == 1, "meta.source")
+ local _, e = decode(file("photo_q90_420"), { maxPixels = 1000 })
+ t:check(e and e.code == Err.LIMIT, "maxPixels: " .. tostring(e))
+ t:check(decode(file("photo_q90_420"), { maxPixels = 160 * 120 }) ~= nil, "maxPixels at the limit")
+ local _, e2 = decode(file("photo_q90_420"), { scale = 3 })
+ t:check(e2 and e2.code == Err.ARG, "bad scale")
+ local _, e3 = decode("nope")
+ t:check(e3 and e3.code == Err.CORRUPT, "junk: " .. tostring(e3))
+ -- a range inside a bigger buffer
+ local data = files["photo_q90_420"]
+ local big = buffer.create(#data + 20)
+ buffer.writestring(big, 11, data)
+ local a = Jpeg.decode(Bytes.reader(big, 11, #data))
+ t:check(a and Crc32.of(a.pixels) == Crc32.of(decode(data).pixels), "decode from a sub-range")
+end
+
+-- EXIF orientation (both byte orders), applied with opts.orient; ICC + comment + density segments
+local function withSegments(data: string, segs: { string }): string
+ return string.sub(data, 1, 2) .. table.concat(segs) .. string.sub(data, 3)
+end
+local function seg(marker: number, body: string): string
+ local len = #body + 2
+ return "\255" .. string.char(marker, len // 256, len % 256) .. body
+end
+local function exifSeg(orient: number, le: boolean): string
+ local tiff
+ if le then
+ tiff = "II\42\0\8\0\0\0" .. "\1\0" .. "\18\1\3\0\1\0\0\0" .. string.char(orient, 0, 0, 0) .. "\0\0\0\0"
+ else
+ tiff = "MM\0\42\0\0\0\8" .. "\0\1" .. "\1\18\0\3\0\0\0\1" .. string.char(0, orient, 0, 0) .. "\0\0\0\0"
+ end
+ return seg(0xE1, "Exif\0\0" .. tiff)
+end
+do
+ local base = files["photo_q90_420"]
+ local plain = decode(base)
+ local w, h = plain.width, plain.height
+ local function px(img: any, x: number, y: number): number
+ return buffer.readu32(img.pixels, (y * img.width + x) * 4)
+ end
+ for _, le in { true, false } do
+ for o = 1, 8 do
+ local d = withSegments(base, { exifSeg(o, le) })
+ local img = decode(d)
+ t:check(img and img.meta.orientation == o, "EXIF orientation " .. o)
+ t:check(img.meta.exif and buffer.readstring(img.meta.exif, 0, 2) == (if le then "II" else "MM"), "meta.exif")
+ t:eq(Jpeg.info(Bytes.reader(buffer.fromstring(d))).orientation, o, "info orientation " .. o)
+ local r = decode(d, { orient = true })
+ local swap = o >= 5
+ t:check(r.width == (if swap then h else w) and r.height == (if swap then w else h), "oriented size " .. o)
+ -- where the source's top-left pixel lands
+ local tl = px(plain, 0, 0)
+ local want = ({
+ { 0, 0 },
+ { r.width - 1, 0 },
+ { r.width - 1, r.height - 1 },
+ { 0, r.height - 1 },
+ { 0, 0 },
+ { r.width - 1, 0 },
+ { r.width - 1, r.height - 1 },
+ { 0, r.height - 1 },
+ })[o]
+ t:eq(px(r, want[1], want[2]), tl, "orientation " .. o .. ": top-left pixel")
+ end
+ end
+ local icc = string.rep("icc!", 50)
+ local d = withSegments(base, {
+ seg(0xE2, "ICC_PROFILE\0\1\2" .. string.sub(icc, 1, 120)),
+ seg(0xE2, "ICC_PROFILE\0\2\2" .. string.sub(icc, 121)),
+ seg(0xFE, "hello jpeg"),
+ })
+ local img = decode(d)
+ t:check(img.meta.icc and buffer.tostring(img.meta.icc) == icc, "ICC chunks joined")
+ t:check(img.meta.text and img.meta.text.comment == "hello jpeg", "COM")
+ t:check(img.meta.dpi == nil, "no density in cjpeg's JFIF (aspect only)")
+end
+
+-- the encoder: byte-identical to cjpeg
+local function source(c: any): any
+ local img = Types.Image.new(c.width, c.height, c.format)
+ if c.format == "rgb8" then
+ buffer.writestring(img.pixels, 0, c.pixels)
+ else
+ buffer.writestring(img.pixels, 0, c.pixels)
+ end
+ return img
+end
+local function psnr(a: buffer, b: buffer, n: number, bpp: number): number
+ local se = 0
+ for i = 0, n - 1 do
+ for k = 0, 2 do
+ local d = buffer.readu8(a, i * 4 + k) - buffer.readu8(b, i * bpp + (if bpp == 1 then 0 else k))
+ se += d * d
+ end
+ end
+ if se == 0 then
+ return 99
+ end
+ return 10 * math.log10(255 * 255 * n * 3 / se)
+end
+do
+ local exact = 0
+ for _, c in Enc do
+ local img = source(c)
+ local out, err = Jpeg.encode(img, c.opts)
+ t:check(out, c.name .. ": encode: " .. tostring(err))
+ local same = buffer.tostring(out :: buffer) == c.want
+ if not same then
+ local s = buffer.tostring(out :: buffer)
+ local at = 0
+ for i = 1, math.min(#s, #c.want) do
+ if string.byte(s, i) ~= string.byte(c.want, i) then
+ at = i
+ break
+ end
+ end
+ t:check(false, string.format("%s: differs from cjpeg at byte %d (ours %d bytes, cjpeg %d)", c.name, at, #s, #c.want))
+ end
+ exact += 1
+ local back = decode(out)
+ t:check(back and back.width == c.width and back.height == c.height, c.name .. ": decodes")
+ local bpp = if c.format == "gray8" then 1 else 3
+ local q = c.opts.quality
+ local p = psnr(back.pixels, img.pixels, c.width * c.height, bpp)
+ if c.width * c.height >= 1000 and not c.opts.gray then
+ -- the synthetic source has salt-and-pepper noise: lower thresholds
+ local floor = (if q >= 75 then 28 elseif q >= 50 then 25 else 20) - (if string.find(c.name, "synth") then 10 else 0)
+ t:check(p > floor, string.format("%s: PSNR %.1f dB", c.name, p))
+ end
+ end
+ t:note("%d encodes byte-identical to cjpeg", exact)
+end
+
+-- encoder: meta segments round trip, rgba8 input, options, errors
+do
+ local c = Enc[1]
+ local rgb = source(c)
+ local img = Types.Image.new(c.width, c.height)
+ for i = 0, c.width * c.height - 1 do
+ buffer.writeu32(img.pixels, i * 4, buffer.readu16(rgb.pixels, i * 3) + buffer.readu8(rgb.pixels, i * 3 + 2) * 65536 + 0x80000000)
+ end
+ local a = Jpeg.encode(rgb, { quality = 80 }) :: buffer
+ local b = Jpeg.encode(img, { quality = 80 }) :: buffer
+ t:check(buffer.tostring(a) == buffer.tostring(b), "rgba8 input encodes as rgb8 (alpha ignored)")
+ img.meta.icc = buffer.fromstring(string.rep("P", 70000))
+ img.meta.exif = buffer.fromstring("MM\0\42\0\0\0\8\0\1\1\18\0\3\0\0\0\1\0\6\0\0\0\0\0\0")
+ img.meta.text = { comment = "made by formats-luau" }
+ img.meta.dpi = { x = 300, y = 300 }
+ local m = Jpeg.encode(img, { quality = 80 }) :: buffer
+ local back = decode(m)
+ t:check(back.meta.icc and buffer.len(back.meta.icc) == 70000, "ICC round trip (two APP2 chunks)")
+ t:eq(back.meta.orientation, 6, "EXIF round trip")
+ t:check(back.meta.text and back.meta.text.comment == "made by formats-luau", "COM round trip")
+ t:check(back.meta.dpi and back.meta.dpi.x == 300, "density round trip")
+ local nm = Jpeg.encode(img, { quality = 80, meta = false, jfif = false }) :: buffer
+ t:check(buffer.len(nm) < buffer.len(a), "meta = false, jfif = false")
+ local _, e1 = Jpeg.encode({} :: any)
+ t:check(e1 and e1.code == Err.ARG, "encode of a non-image")
+ local _, e2 = Jpeg.encode(Types.Image.new(4, 4, "rgba16"))
+ t:check(e2 and e2.code == Err.ARG, "rgba16 is refused")
+ local _, e3 = Jpeg.encode(img, { quality = 0 })
+ t:check(e3 and e3.code == Err.ARG, "quality 0")
+ local _, e4 = Jpeg.encode(img, { subsampling = "411" } :: any)
+ t:check(e4 and e4.code == Err.ARG, "subsampling 411")
+ local one = Jpeg.encode(Types.Image.new(1, 1), { progressive = true, subsampling = "444" })
+ t:check(one and decode(one).width == 1, "1x1 progressive")
+end
+
+-- truncated files: decode what is there (flagged) or fail with an Err; never throw
+do
+ local count, partial = 0, 0
+ for _, name in { "photo_q90_420", "photo_q90_420_prog", "photo_rst1", "photo_rst1b_prog", "photo_arith_420", "photo_arith_rst_prog" } do
+ local s = files[name]
+ for cut = 0, #s - 1, math.max(1, #s // 61) do
+ local ok, img, err = pcall(decode, string.sub(s, 1, cut))
+ t:check(ok, name .. " cut at " .. cut .. ": threw " .. tostring(img))
+ t:check(img or Err.is(err), name .. " cut at " .. cut .. ": no image and no Err")
+ if img then
+ partial += 1
+ t:check(img.meta.truncated or cut >= #s - 2, name .. " cut at " .. cut .. ": not flagged truncated")
+ end
+ count += 1
+ end
+ end
+ t:note("%d truncated files, %d decoded partially", count, partial)
+end
+
+-- fuzz
+do
+ local samples = {}
+ for i, c in Dec do
+ if i % 9 == 0 and #c.data < 40000 then
+ table.insert(samples, c.data)
+ end
+ end
+ t:fuzz("decode", function(b: buffer)
+ return Jpeg.decode(Bytes.reader(b))
+ end, samples, { mutations = 6, keepHeader = 2 })
+ t:fuzz("decode 1/8", function(b: buffer)
+ return Jpeg.decode(Bytes.reader(b), { scale = 8 })
+ end, samples, { mutations = 2, garbage = 30 })
+end
+
+t:done()
diff --git a/tests/image/pnm.luau b/tests/image/pnm.luau
new file mode 100644
index 0000000..a5b58e4
--- /dev/null
+++ b/tests/image/pnm.luau
@@ -0,0 +1,125 @@
+-- image/pnm tests: ImageMagick-written P1-P7 / PFM files (ASCII and binary, 8 / 16-bit, PAM tuple types, both PFM
+-- byte orders) and hand-written edge cases (comments, packed P1 digits, odd maxvals) against ImageMagick's RGBA
+-- decodes (8-bit; 16-bit and float natively); round trips of every subtype through our encoder, binary and ASCII;
+-- errors; the fuzz no-throw pass. Fixtures: tools/fixtures/pnm.py.
+local T = require("@tests/T")
+local Pnm = require("@formats/image/pnm")
+local Bytes = require("@formats/core/Bytes")
+local Err = require("@formats/core/Err")
+local Types = require("@formats/Types")
+local Fx = require("@tests/gen/pnm")
+
+local t = T.suite("pnm")
+
+t:eq(Pnm.name, "pnm", "name")
+t:check(Pnm.caps.decode and Pnm.caps.encode, "caps")
+
+local function dec(data: any, opts: any?): (any, any)
+ return Pnm.decode(Bytes.reader(if type(data) == "string" then buffer.fromstring(data) else data), opts)
+end
+
+-- channel c (0..3) of pixel i of a native image, in 16-bit scale
+local function chan16(img: any, i: number, c: number): number
+ local px, f = img.pixels, img.format
+ if f == "gray16" then
+ return if c == 3 then 65535 else buffer.readu16(px, i * 2)
+ elseif f == "rgba16" then
+ return buffer.readu16(px, i * 8 + c * 2)
+ elseif f == "gray8" then
+ return if c == 3 then 65535 else buffer.readu8(px, i) * 257
+ elseif f == "graya8" then
+ return buffer.readu8(px, i * 2 + (if c == 3 then 1 else 0)) * 257
+ elseif f == "rgb8" then
+ return if c == 3 then 65535 else buffer.readu8(px, i * 3 + c) * 257
+ end
+ return buffer.readu8(px, i * 4 + c) * 257
+end
+
+for _, c in Fx do
+ local img, err = dec(c.data)
+ t:check(img, c.name .. ": " .. tostring(err))
+ t:check(img.width == c.width and img.height == c.height and img.format == "rgba8", c.name .. ": size")
+ local worst = 0
+ for i = 0, c.width * c.height * 4 - 1 do
+ worst = math.max(worst, math.abs(buffer.readu8(img.pixels, i) - string.byte(c.rgba8, i + 1)))
+ end
+ t:check(worst <= c.tol, string.format("%s: max difference %d against ImageMagick (allowed %d)", c.name, worst, c.tol))
+ local nat = dec(c.data, { native = true })
+ if c.rgba16 then
+ local w16 = 0
+ for i = 0, c.width * c.height - 1 do
+ for k = 0, 3 do
+ local o = (i * 4 + k) * 2 + 1
+ local want = string.byte(c.rgba16, o) * 256 + string.byte(c.rgba16, o + 1)
+ w16 = math.max(w16, math.abs(chan16(nat, i, k) - want))
+ end
+ end
+ t:check(w16 <= c.tol * 66, string.format("%s: 16-bit max difference %d", c.name, w16))
+ end
+ if c.floats then
+ t:eq(nat.format, "rgbaf32", c.name .. ": native float")
+ local fb = buffer.fromstring(c.floats)
+ local fw = 0
+ for i = 0, c.width * c.height * 4 - 1 do
+ fw = math.max(fw, math.abs(buffer.readf32(nat.pixels, i * 4) - buffer.readf32(fb, i * 4)))
+ end
+ t:check(fw < 1e-6, c.name .. ": floats")
+ end
+ -- round trips through our encoder: the same subtype, binary and ASCII
+ local ext = string.match(c.name, "%.(%a+)$")
+ for _, ascii in { false, true } do
+ local enc, eerr = Pnm.encode(nat, { format = ext, ascii = ascii })
+ t:check(enc, c.name .. ": encode: " .. tostring(eerr))
+ local back = dec(enc, { native = true })
+ t:check(back and back.format == nat.format and buffer.tostring(back.pixels) == buffer.tostring(nat.pixels), string.format("%s: round trip (ascii %s)", c.name, tostring(ascii)))
+ end
+end
+t:note("%d files match ImageMagick and round-trip", #Fx)
+
+-- encoder choices, conversions, options
+do
+ local img = Types.Image.new(3, 2)
+ for i = 0, 23 do
+ buffer.writeu8(img.pixels, i, (i * 40) % 256)
+ end
+ for i = 0, 5 do
+ buffer.writeu8(img.pixels, i * 4 + 3, 255)
+ end
+ local s = buffer.tostring(Pnm.encode(img) :: buffer)
+ t:eq(string.sub(s, 1, 2), "P6", "opaque rgba8 -> P6")
+ buffer.writeu8(img.pixels, 3, 7)
+ t:eq(string.sub(buffer.tostring(Pnm.encode(img) :: buffer), 1, 2), "P7", "alpha -> PAM")
+ t:eq(string.sub(buffer.tostring(Pnm.encode(img, { format = "pgm" }) :: buffer), 1, 2), "P5", "pgm by name")
+ t:eq(string.sub(buffer.tostring(Pnm.encode(img, { format = "pbm", ascii = true }) :: buffer), 1, 2), "P1", "ascii pbm")
+ t:eq(string.sub(buffer.tostring(Pnm.encode(img, { format = "pfm" }) :: buffer), 1, 2), "PF", "pfm by name")
+ local g = Types.Image.new(2, 1, "gray8")
+ t:eq(string.sub(buffer.tostring(Pnm.encode(g) :: buffer), 1, 2), "P5", "gray8 -> P5")
+ local m = Pnm.encode(g, { maxval = 15, ascii = true }) :: buffer
+ t:check(string.find(buffer.tostring(m), "\n15\n", 1, true) ~= nil, "maxval option")
+ local _, e = Pnm.encode(img, { maxval = 0 })
+ t:check(e and e.code == Err.ARG, "bad maxval")
+ local _, e2 = Pnm.encode({} :: any)
+ t:check(e2 and e2.code == Err.ARG, "not an image")
+ t:eq(Pnm.sniff(Bytes.reader(buffer.fromstring("P6\n1 1\n255\n..."))), 0.9, "sniff")
+ t:eq(Pnm.sniff(Bytes.reader(buffer.fromstring("PNG"))), 0, "sniff other")
+ local _, e3 = dec("P6\n100 100\n255\n" .. string.rep("x", 50))
+ t:check(e3 and e3.code == Err.TRUNCATED, "truncated")
+ local _, e4 = dec("P6\n10 10\n255\n", { maxPixels = 50 })
+ t:check(e4 and e4.code == Err.LIMIT, "maxPixels")
+ local _, e5 = dec("P3\n1 1\n255\n1 x 3\n")
+ t:check(e5 and e5.code == Err.CORRUPT, "bad ascii")
+end
+
+do
+ local samples = {}
+ for i, c in Fx do
+ if i % 3 == 0 then
+ table.insert(samples, c.data)
+ end
+ end
+ t:fuzz("decode", function(b: buffer)
+ return Pnm.decode(Bytes.reader(b))
+ end, samples)
+end
+
+t:done()
diff --git a/tests/image/qoi.luau b/tests/image/qoi.luau
new file mode 100644
index 0000000..d78c5cb
--- /dev/null
+++ b/tests/image/qoi.luau
@@ -0,0 +1,85 @@
+-- image/qoi tests: Pillow-written QOI files (RGB / RGBA, noise / gradients / runs / small deltas, 1x1 to 500x1)
+-- decode to Pillow's pixels; our encoder writes the same bytes as Pillow for the same pixels and round-trips exactly;
+-- native rgb8 output, the colour space tag, errors, and the fuzz no-throw pass. Fixtures: tools/fixtures/qoi.py.
+local T = require("@tests/T")
+local Qoi = require("@formats/image/qoi")
+local Bytes = require("@formats/core/Bytes")
+local Crc32 = require("@formats/core/Crc32")
+local Err = require("@formats/core/Err")
+local Types = require("@formats/Types")
+local Fx = require("@tests/gen/qoi")
+
+local t = T.suite("qoi")
+
+t:eq(Qoi.name, "qoi", "name")
+t:check(Qoi.caps.decode and Qoi.caps.encode, "caps")
+
+local same = 0
+for _, c in Fx do
+ local img, err = Qoi.decode(Bytes.reader(buffer.fromstring(c.data)))
+ t:check(img, c.name .. ": " .. tostring(err))
+ t:check(img.width == c.width and img.height == c.height and img.format == "rgba8", c.name .. ": size")
+ t:eq(Crc32.of(img.pixels), c.crc, c.name .. ": pixels against Pillow")
+ -- encode the source pixels: the same bytes as Pillow's writer
+ local src = Types.Image.new(c.width, c.height, if c.channels == 4 then "rgba8" else "rgb8")
+ src.pixels = buffer.fromstring(c.pixels)
+ local enc = Qoi.encode(src, { channels = c.channels, linear = string.byte(c.data, 14) == 1 }) :: buffer -- Pillow tags its files linear
+ if buffer.tostring(enc) == c.data then
+ same += 1
+ end
+ local back = Qoi.decode(Bytes.reader(enc))
+ t:eq(Crc32.of(back.pixels), c.crc, c.name .. ": our encoding round-trips")
+ -- native rgb8
+ if c.channels == 3 then
+ local n = Qoi.decode(Bytes.reader(buffer.fromstring(c.data)), { native = true })
+ t:check(n.format == "rgb8" and buffer.tostring(n.pixels) == c.pixels, c.name .. ": native rgb8")
+ end
+end
+t:eq(same, #Fx, "byte-identical to Pillow's encoder")
+t:note("%d Pillow files decode; %d of our encodings are byte-identical to Pillow's", #Fx, same)
+
+-- round trips of random images, a sub-range reader, colour space, errors
+do
+ local rand = T.rng(5)
+ for _, s in { { 1, 1 }, { 70, 3 }, { 33, 33 } } do
+ local img = Types.Image.new(s[1], s[2])
+ for i = 0, s[1] * s[2] * 4 - 1 do
+ buffer.writeu8(img.pixels, i, if rand(3) == 0 then rand(256) else (i // 4) % 256)
+ end
+ local back = Qoi.decode(Bytes.reader(Qoi.encode(img) :: buffer))
+ t:check(buffer.tostring(back.pixels) == buffer.tostring(img.pixels), "random round trip")
+ end
+ local c = Fx[4]
+ local big = buffer.create(#c.data + 9)
+ buffer.writestring(big, 5, c.data)
+ local img = Qoi.decode(Bytes.reader(big, 5, #c.data))
+ t:check(img and Crc32.of(img.pixels) == c.crc, "decode from a sub-range")
+ local lin = Types.Image.new(2, 2)
+ local d = Qoi.encode(lin, { linear = true }) :: buffer
+ t:eq(buffer.readu8(d, 13), 1, "linear tag")
+ t:eq(Qoi.decode(Bytes.reader(d)).meta.source.colorSpace, "linear", "linear read back")
+ t:eq(Qoi.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, "sniff")
+ t:eq(Qoi.sniff(Bytes.reader(buffer.fromstring("GIF8"))), 0, "sniff other")
+ local _, e = Qoi.decode(Bytes.reader(buffer.fromstring(c.data)), { maxPixels = 10 })
+ t:check(e and e.code == Err.LIMIT, "maxPixels")
+ local _, e2 = Qoi.decode(Bytes.reader(buffer.fromstring(string.sub(c.data, 1, 40))))
+ t:check(e2 and e2.code == Err.TRUNCATED, "truncated: " .. tostring(e2))
+ local _, e3 = Qoi.decode(Bytes.reader(buffer.fromstring("qoix" .. string.rep("\0", 20))))
+ t:check(e3 and e3.code == Err.CORRUPT, "bad magic")
+ local _, e4 = Qoi.encode(Types.Image.new(2, 2, "gray8"))
+ t:check(e4 and e4.code == Err.ARG, "encode gray8 -> ARG")
+end
+
+do
+ local samples = {}
+ for i, c in Fx do
+ if i % 2 == 0 then
+ table.insert(samples, c.data)
+ end
+ end
+ t:fuzz("decode", function(b: buffer)
+ return Qoi.decode(Bytes.reader(b))
+ end, samples, { keepHeader = 4 })
+end
+
+t:done()
diff --git a/tests/image/tga.luau b/tests/image/tga.luau
new file mode 100644
index 0000000..2fe016c
--- /dev/null
+++ b/tests/image/tga.luau
@@ -0,0 +1,96 @@
+-- image/tga tests: Pillow- and ImageMagick-written TGAs (RGB / RGBA / grey / grey + alpha / palette, raw and RLE, both
+-- origins) and hand-written ones (15 / 16-bit pixels and colour maps, first index, right-to-left, RLE across rows, an
+-- image ID) against the reference RGBA decodes; our encoder (raw / RLE, origins, 24 / 32-bit / grey) round-trips;
+-- sniffing stays low without a footer; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/tga.py.
+local T = require("@tests/T")
+local Tga = require("@formats/image/tga")
+local Bytes = require("@formats/core/Bytes")
+local Err = require("@formats/core/Err")
+local Types = require("@formats/Types")
+local Fx = require("@tests/gen/tga")
+
+local t = T.suite("tga")
+
+t:eq(Tga.name, "tga", "name")
+t:check(Tga.caps.decode and Tga.caps.encode, "caps")
+
+local function dec(data: any, opts: any?): (any, any)
+ return Tga.decode(Bytes.reader(if type(data) == "string" then buffer.fromstring(data) else data), opts)
+end
+
+for _, c in Fx do
+ local img, err = dec(c.data)
+ t:check(img, c.name .. ": " .. tostring(err))
+ t:check(img.width == c.width and img.height == c.height, c.name .. ": size")
+ local worst, at = 0, -1
+ for i = 0, #c.rgba - 1 do
+ local d = math.abs(buffer.readu8(img.pixels, i) - string.byte(c.rgba, i + 1))
+ if d > worst then
+ worst, at = d, i
+ end
+ end
+ t:check(worst == 0, string.format("%s: differs from the reference by %d at byte %d", c.name, worst, at))
+ t:check(not img.meta.truncated, c.name .. ": not truncated")
+ -- round trips through our encoder
+ for _, rle in { false, true } do
+ for _, origin in { "bottom-left", "top-left" } do
+ local enc = Tga.encode(img, { rle = rle, origin = origin }) :: buffer
+ local back = dec(enc)
+ t:check(back and buffer.tostring(back.pixels) == buffer.tostring(img.pixels), string.format("%s: round trip rle=%s %s", c.name, tostring(rle), origin))
+ end
+ end
+end
+t:note("%d files match the reference decodes and round-trip", #Fx)
+
+do
+ local byName = {}
+ for _, c in Fx do
+ byName[c.name] = c
+ end
+ local id = dec(byName["hand-id-top"].data)
+ t:check(id.meta.text and id.meta.text.id == "hello", "image ID")
+ local g = dec(byName["pil-L-raw-top"].data, { native = true })
+ t:eq(g.format, "gray8", "native grey")
+ t:eq(Tga.encode(g) and buffer.readu8(Tga.encode(g) :: buffer, 2), 3, "gray8 encodes as type 3")
+ local rgb = dec(byName["pil-RGB-raw-top"].data, { native = true })
+ t:eq(rgb.format, "rgb8", "native rgb8")
+ local p = dec(byName["pil-P-raw-top"].data)
+ t:check(p.meta.palette and #p.meta.palette > 0, "palette in meta")
+ -- sniff: low without a footer, higher with ours, never for other formats
+ t:eq(Tga.sniff(Bytes.reader(buffer.fromstring(byName["hand-16bit"].data))), 0.2, "sniff without a footer")
+ t:eq(Tga.sniff(Bytes.reader(Tga.encode(p) :: buffer)), 0.9, "sniff with the footer")
+ t:eq(Tga.sniff(Bytes.reader(buffer.fromstring("\0\0\1\0\1\0\16\16\0\0\1\0\32\0\0\0\0\0\0\0\0\0"))), 0, "an ICO header is not a TGA")
+ t:eq(Tga.sniff(Bytes.reader(buffer.fromstring("\137PNG\r\n\26\n\0\0\0\13IHDR\0\0\0\0\0\0"))), 0, "a PNG is not a TGA")
+ -- encoder choices
+ local img = Types.Image.new(3, 2)
+ buffer.fill(img.pixels, 0, 255, 24)
+ t:eq(buffer.readu8(Tga.encode(img) :: buffer, 16), 24, "opaque rgba8 -> 24-bit")
+ buffer.writeu8(img.pixels, 3, 0)
+ t:eq(buffer.readu8(Tga.encode(img) :: buffer, 16), 32, "alpha -> 32-bit")
+ local _, e = Tga.encode(img, { origin = "middle" } :: any)
+ t:check(e and e.code == Err.ARG, "bad origin")
+ local _, e2 = Tga.encode(Types.Image.new(2, 2, "gray16"))
+ t:check(e2 and e2.code == Err.ARG, "gray16 refused")
+ -- truncation keeps what is there
+ local s = byName["pil-RGBA-raw-top"].data
+ local tr = dec(string.sub(s, 1, #s // 2))
+ t:check(tr and tr.meta.truncated, "truncated pixels flagged")
+ local _, e3 = dec(string.sub(s, 1, 10))
+ t:check(e3 and e3.code == Err.TRUNCATED, "short header")
+ local _, e4 = dec(s, { maxPixels = 10 })
+ t:check(e4 and e4.code == Err.LIMIT, "maxPixels")
+end
+
+do
+ local samples = {}
+ for i, c in Fx do
+ if i % 3 == 0 then
+ table.insert(samples, c.data)
+ end
+ end
+ t:fuzz("decode", function(b: buffer)
+ return Tga.decode(Bytes.reader(b))
+ end, samples)
+end
+
+t:done()
diff --git a/tests/image/tiff.luau b/tests/image/tiff.luau
new file mode 100644
index 0000000..f5c0f7a
--- /dev/null
+++ b/tests/image/tiff.luau
@@ -0,0 +1,185 @@
+-- image/tiff tests: files written by tifffile / imagecodecs and ImageMagick (every compression, predictors, strips and
+-- tiles, planar, both byte orders, BigTIFF, 1..32-bit integer and 16 / 32 / 64-bit float samples, palette, CMYK,
+-- alpha, multi-page) against tifffile's decode, in rgba8 and native layouts; the JPEG hook; encoder round trips for
+-- every layout and compression; errors; the fuzz pass. Fixtures: tools/fixtures/tiff.py.
+local T = require("@tests/T")
+local Tiff = require("@formats/image/tiff")
+local Bytes = require("@formats/core/Bytes")
+local Crc32 = require("@formats/core/Crc32")
+local Err = require("@formats/core/Err")
+local Types = require("@formats/Types")
+local Fx = require("@tests/gen/tiff")
+
+local t = T.suite("tiff")
+
+local function decode(data: any, opts: any?): (any, any)
+ local b = if type(data) == "string" then buffer.fromstring(data) else data
+ return Tiff.decode(Bytes.reader(b), opts)
+end
+
+-- contract
+t:eq(Tiff.name, "tiff", "name")
+t:check(Tiff.caps.decode and Tiff.caps.encode, "caps")
+t:eq(Tiff.sniff(Bytes.reader(buffer.fromstring("II*\0\8\0\0\0"))), 1, "sniff II")
+t:eq(Tiff.sniff(Bytes.reader(buffer.fromstring("MM\0*"))), 1, "sniff MM")
+t:eq(Tiff.sniff(Bytes.reader(buffer.fromstring("\137PNG"))), 0, "sniff png")
+
+-- reference files
+local pagesChecked = 0
+for _, c in Fx.cases do
+ local img, err = decode(c.data)
+ t:check(img, c.name .. ": " .. tostring(err))
+ t:check(img.width == c.width and img.height == c.height and img.format == "rgba8", c.name .. ": size / format")
+ local frames = img.frames or { { image = img } }
+ t:eq(#frames, #c.pages, c.name .. ": pages")
+ local nat = decode(c.data, { native = true })
+ local nframes = nat.frames or { { image = nat } }
+ for i, p in c.pages do
+ local crc = Crc32.of(frames[i].image.pixels)
+ t:check(crc == p.crc, string.format("%s page %d: rgba8 crc %08x, want %08x", c.name, i, crc, p.crc))
+ local ni = nframes[i].image
+ t:eq(ni.format, p.native, c.name .. " page " .. i .. ": native format")
+ local ncrc = Crc32.of(ni.pixels)
+ t:check(ncrc == p.ncrc, string.format("%s page %d: native crc %08x, want %08x", c.name, i, ncrc, p.ncrc))
+ pagesChecked += 1
+ end
+ -- inside a bigger buffer
+ local big = buffer.create(#c.data + 9)
+ buffer.writestring(big, 5, c.data)
+ local img3 = Tiff.decode(Bytes.reader(big, 5, #c.data))
+ t:check(img3 and Crc32.of(img3.pixels) == c.pages[1].crc, c.name .. ": sub-range decode")
+end
+t:note("%d files, %d pages match tifffile", #Fx.cases, pagesChecked)
+
+-- info, single page, meta
+do
+ local multi
+ for _, c in Fx.cases do
+ if c.name == "pages3" then
+ multi = c
+ end
+ end
+ local info = Tiff.info(Bytes.reader(buffer.fromstring(multi.data)))
+ t:check(info and info.pages == 3 and info.width == multi.width, "info")
+ local p2 = decode(multi.data, { page = 2, native = true })
+ t:check(p2 and p2.format == "gray16" and Crc32.of(p2.pixels) == multi.pages[2].ncrc, "opts.page")
+ local _, e = decode(multi.data, { page = 9 })
+ t:check(e and e.code == Err.ARG, "missing page")
+ local _, e2 = decode(multi.data, { maxPixels = 10 })
+ t:check(e2 and e2.code == Err.LIMIT, "maxPixels")
+ local img = decode(multi.data)
+ t:check(img.meta.source.format == "tiff" and img.meta.source.compression == "deflate", "meta.source")
+end
+
+-- JPEG-compressed: needs the hook; the hook gets one stitched JPEG stream per strip
+do
+ local _, e = decode(Fx.jpeg)
+ t:check(e and e.code == Err.UNSUPPORTED, "jpeg without hook: " .. tostring(e))
+ local calls = 0
+ local img = decode(Fx.jpeg, {
+ decodeImage = function(b: buffer)
+ calls += 1
+ t:check(buffer.readu8(b, 0) == 0xFF and buffer.readu8(b, 1) == 0xD8, "stitched stream starts with SOI")
+ local s = buffer.tostring(b)
+ t:check(string.find(s, "\255\218", 1, true) ~= nil, "stitched stream has SOS")
+ t:check(string.find(s, "\255\196", 1, true) ~= nil or string.find(s, "\255\219", 1, true) ~= nil, "stitched stream has tables")
+ local im = Types.Image.new(64, 64)
+ buffer.fill(im.pixels, 0, 200)
+ return im
+ end,
+ })
+ t:check(img and calls > 0, "jpeg through the hook")
+ -- the real thing through the api (image/jpeg decodes the stitched streams): within 2 levels of libjpeg-turbo
+ local F = require("@formats")
+ local ref = Fx.jpegRef
+ local full, ferr = F.load(Fx.jpeg, { format = "tiff" })
+ t:check(full and full.width == ref.width and full.height == ref.height, "jpeg-in-tiff through F.load: " .. tostring(ferr))
+ local worst = 0
+ for i = 0, ref.width * ref.height - 1 do
+ for k = 0, 2 do
+ worst = math.max(worst, math.abs(buffer.readu8(full.pixels, i * 4 + k) - string.byte(ref.rgb, i * 3 + k + 1)))
+ end
+ end
+ t:check(worst <= 2, "jpeg-in-tiff pixels: max error " .. worst .. " against tifffile")
+ t:note("JPEG-in-TIFF through F.load: max error %d against tifffile / libjpeg-turbo", worst)
+end
+
+-- encoder round trips
+do
+ local rand = T.rng(11)
+ local function image(fmt: string, w: number, h: number): Types.Image
+ local img = Types.Image.new(w, h, fmt :: any)
+ local n = buffer.len(img.pixels)
+ if fmt == "rgbaf32" then
+ for i = 0, n // 4 - 1 do
+ buffer.writef32(img.pixels, i * 4, (rand(2000) - 300) / 1000)
+ end
+ else
+ for i = 0, n - 1 do
+ buffer.writeu8(img.pixels, i, if rand(3) == 0 then rand(256) else (i * 7) % 256)
+ end
+ end
+ return img
+ end
+ local trips = 0
+ for _, fmt in { "rgba8", "rgb8", "gray8", "graya8", "gray16", "rgba16", "rgbaf32" } do
+ for _, comp in { "none", "deflate", "lzw", "packbits" } do
+ for _, pred in { true, false } do
+ for _, size in { { 1, 1 }, { 13, 7 }, { 200, 90 } } do
+ local img = image(fmt, size[1], size[2])
+ img.meta.dpi = { x = 300, y = 150 }
+ local out, err = Tiff.encode(img, { compression = comp :: any, predictor = pred, rowsPerStrip = if size[1] == 200 then 16 else nil })
+ t:check(out, fmt .. " " .. comp .. ": " .. tostring(err))
+ local back, berr = Tiff.decode(Bytes.reader(out :: buffer), { native = true })
+ t:check(back, fmt .. " " .. comp .. ": decode: " .. tostring(berr))
+ t:eq(back.format, fmt, fmt .. " " .. comp .. ": format")
+ t:check(buffer.tostring(back.pixels) == buffer.tostring(img.pixels), string.format("%s %s pred=%s %dx%d: round trip", fmt, comp, tostring(pred), size[1], size[2]))
+ t:check(back.meta.dpi and math.abs(back.meta.dpi.x - 300) < 0.01 and math.abs(back.meta.dpi.y - 150) < 0.01, "dpi")
+ trips += 1
+ end
+ end
+ end
+ end
+ t:note("%d encoder round trips", trips)
+ -- multi-page
+ local a, b = image("rgb8", 20, 10), image("gray16", 7, 9)
+ local anim = image("rgb8", 20, 10)
+ anim.frames = { { image = a, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" }, { image = b, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" } } :: any
+ local out = Tiff.encode(anim, { compression = "lzw" }) :: buffer
+ local back = Tiff.decode(Bytes.reader(out), { native = true })
+ t:check(back.frames and #back.frames == 2, "multi-page count")
+ t:check(buffer.tostring(back.frames[1].image.pixels) == buffer.tostring(a.pixels), "page 1")
+ t:check(buffer.tostring(back.frames[2].image.pixels) == buffer.tostring(b.pixels) and back.frames[2].image.format == "gray16", "page 2")
+ local _, e = Tiff.encode({} :: any)
+ t:check(e and e.code == Err.ARG, "encode non-image")
+ local _, e2 = Tiff.encode(image("rgb8", 2, 2), { compression = "jpeg" } :: any)
+ t:check(e2 and e2.code == Err.ARG, "bad compression")
+ local _, e3 = Tiff.encode(Types.Image.new(2, 2, "yuv420p"))
+ t:check(e3 and e3.code == Err.ARG, "unsupported layout")
+end
+
+-- errors
+do
+ local _, e = decode("II*\0\255\255\0\0")
+ t:check(e and (e.code == Err.TRUNCATED or e.code == Err.CORRUPT), "bad IFD offset")
+ local _, e2 = decode("XX*\0")
+ t:check(e2 and e2.code == Err.TRUNCATED or e2.code == Err.CORRUPT, "junk")
+end
+
+-- fuzz
+do
+ local samples = {}
+ for i, c in Fx.cases do
+ if i % 3 == 0 and #c.data < 40000 then
+ table.insert(samples, c.data)
+ end
+ end
+ t:fuzz("decode", function(b: buffer)
+ return Tiff.decode(Bytes.reader(b))
+ end, samples, { mutations = 12 })
+ t:fuzz("decode native", function(b: buffer)
+ return Tiff.decode(Bytes.reader(b), { native = true })
+ end, samples, { mutations = 4, garbage = 50 })
+end
+
+t:done()
diff --git a/tests/ops/imageops.luau b/tests/ops/imageops.luau
new file mode 100644
index 0000000..2662d0d
--- /dev/null
+++ b/tests/ops/imageops.luau
@@ -0,0 +1,321 @@
+-- ops/ImageOps tests: against Pillow (tools/fixtures/imageops.py): grey conversion (exact), resize nearest / bilinear /
+-- Lanczos up and down (max error), rotate with bilinear + expand (PSNR), alpha_composite (exact); property tests for
+-- every pixel format (conversion round trips, flips, quarter turns, crop, premultiply, pixel access, fill), blit
+-- clipping and blend modes, animation helpers (coalesce with each disposal, fromFrames, durations), and a pass of bad
+-- arguments that must return nil, Err without throwing.
+local T = require("@tests/T")
+local Ops = require("@formats/ops/ImageOps")
+local Types = require("@formats/Types")
+local Err = require("@formats/core/Err")
+local Fx = require("@tests/gen/imageops")
+
+local t = T.suite("imageops")
+
+local function image(w: number, h: number, fmt: string, px: string): any
+ local img = Types.Image.new(w, h, fmt :: any)
+ buffer.writestring(img.pixels, 0, px)
+ return img
+end
+
+-- max abs difference and PSNR of two byte strings / buffers
+local function diff(a: buffer, b: string): (number, number)
+ local n = #b
+ local mx, se = 0, 0
+ for i = 0, n - 1 do
+ local d = math.abs(buffer.readu8(a, i) - string.byte(b, i + 1))
+ if d > mx then
+ mx = d
+ end
+ se += d * d
+ end
+ local mse = se / n
+ return mx, if mse == 0 then 99 else 10 * math.log10(255 * 255 / mse)
+end
+
+local rgb = image(Fx.rgb.w, Fx.rgb.h, "rgb8", Fx.rgb.px)
+local rgba = image(Fx.rgba.w, Fx.rgba.h, "rgba8", Fx.rgba.px)
+local rgba2 = image(Fx.rgba2.w, Fx.rgba2.h, "rgba8", Fx.rgba2.px)
+
+-- Pillow references
+do
+ local g = Ops.convert(rgb, "gray8") :: any
+ t:check(buffer.tostring(g.pixels) == Fx.gray, "rgb8 -> gray8 matches Pillow convert('L')")
+ local ga = Ops.convert(rgba, "gray8") :: any
+ t:check(buffer.tostring(ga.pixels) == Fx.graya, "rgba8 -> gray8 matches Pillow (alpha ignored)")
+ local gray = Ops.convert(rgb, "gray8") :: any
+ local worst = { nearest = 0, bilinear = 0, lanczos = 0 }
+ for _, c in Fx.resize do
+ local src = if c.mode == "RGB" then rgb else gray
+ local r = Ops.resize(src, c.w, c.h, c.filter) :: any
+ t:check(r and r.width == c.w and r.height == c.h, "resize size")
+ local mx = diff(r.pixels, c.px)
+ worst[c.filter] = math.max(worst[c.filter], mx)
+ t:check(mx <= (if c.filter == "nearest" then 0 else 1), string.format("resize %s %s %dx%d: max error %d", c.filter, c.mode, c.w, c.h, mx))
+ end
+ t:note("resize vs Pillow (%d cases): max error nearest %d, bilinear %d, lanczos %d", #Fx.resize, worst.nearest, worst.bilinear, worst.lanczos)
+ local minPsnr = 99
+ for _, c in Fx.rotate do
+ local r = Ops.rotate(rgba, c.angle, { expand = c.expand }) :: any
+ t:check(r and r.width == c.w and r.height == c.h, string.format("rotate %d: size %dx%d, Pillow %dx%d", c.angle, r.width, r.height, c.w, c.h))
+ local _, psnr = diff(r.pixels, c.px)
+ minPsnr = math.min(minPsnr, psnr)
+ t:check(psnr > 40, string.format("rotate %d: PSNR %.1f", c.angle, psnr))
+ end
+ t:note("rotate vs Pillow (%d cases): min PSNR %.1f dB", #Fx.rotate, minPsnr)
+ local c = Ops.composite(rgba, rgba2) :: any
+ local mx = diff(c.pixels, Fx.composite)
+ t:check(mx == 0, "alpha_composite matches Pillow exactly (max error " .. mx .. ")")
+end
+
+-- conversions between every format
+local FORMATS = { "rgba8", "rgba16", "rgbaf32", "rgb8", "gray8", "gray16", "graya8", "alpha8", "yuv420p" }
+do
+ for _, f in FORMATS do
+ local c = Ops.convert(rgba, f) :: any
+ t:check(c and c.format == f and c.width == rgba.width, "convert to " .. f)
+ local back = Ops.convert(c, "rgba8") :: any
+ t:check(back and back.format == "rgba8", f .. " back to rgba8")
+ if f == "rgba16" or f == "rgbaf32" then
+ t:check(buffer.tostring(back.pixels) == buffer.tostring(rgba.pixels), f .. ": lossless round trip")
+ end
+ if f == "yuv420p" then
+ -- a smooth image (4:2:0 drops chroma detail)
+ local sm = Types.Image.new(40, 30)
+ for i = 0, 40 * 30 - 1 do
+ local x, y = i % 40, i // 40
+ buffer.writeu32(sm.pixels, i * 4, 0xFF000000 + (x * 6) + (y * 8) * 256 + ((x + y) * 3) * 65536)
+ end
+ local yb = Ops.convert(Ops.convert(sm, "yuv420p") :: any, "rgba8") :: any
+ local _, psnr = diff(yb.pixels, buffer.tostring(sm.pixels))
+ t:check(psnr > 38, string.format("yuv420p round trip PSNR %.1f", psnr))
+ end
+ for _, g in FORMATS do
+ t:check(Ops.convert(c, g) ~= nil, f .. " -> " .. g)
+ end
+ end
+ local g16 = Ops.convert(Ops.convert(rgb, "gray8") :: any, "gray16") :: any
+ t:eq(buffer.readu16(g16.pixels, 0), buffer.readu8((Ops.convert(rgb, "gray8") :: any).pixels, 0) * 257, "8 -> 16 bit is * 257")
+ local f = Types.Image.new(1, 1, "rgbaf32")
+ buffer.writef32(f.pixels, 0, 1.5)
+ buffer.writef32(f.pixels, 4, -0.2)
+ buffer.writef32(f.pixels, 8, 0.5)
+ buffer.writef32(f.pixels, 12, 1)
+ local b = Ops.convert(f, "rgba8") :: any
+ t:check(buffer.readu8(b.pixels, 0) == 255 and buffer.readu8(b.pixels, 1) == 0 and buffer.readu8(b.pixels, 2) == 128, "float -> 8 bit clamps and rounds")
+end
+
+-- geometry properties on every format
+do
+ for _, f in FORMATS do
+ local img = Ops.convert(rgba, f) :: any
+ local s = buffer.tostring(img.pixels)
+ local r = img
+ for _ = 1, 4 do
+ r = Ops.rotate90(r, 1)
+ end
+ if f ~= "yuv420p" then
+ t:check(buffer.tostring(r.pixels) == s, f .. ": four quarter turns are the identity")
+ t:check(buffer.tostring((Ops.flip(Ops.flip(img, "h") :: any, "h") :: any).pixels) == s, f .. ": flip h twice")
+ t:check(buffer.tostring((Ops.flip(Ops.flip(img, "v") :: any, "v") :: any).pixels) == s, f .. ": flip v twice")
+ local q = Ops.rotate90(img, 1) :: any
+ t:check(q.width == img.height and q.height == img.width, f .. ": a quarter turn swaps the size")
+ t:check(buffer.tostring((Ops.rotate90(img, 2) :: any).pixels) == buffer.tostring((Ops.flip(Ops.flip(img, "h") :: any, "v") :: any).pixels), f .. ": half turn = both flips")
+ t:check(buffer.tostring((Ops.rotate(img, 90) :: any).pixels) == buffer.tostring(q.pixels), f .. ": rotate 90 = one quarter turn")
+ end
+ local c = Ops.crop(img, -5, 10, 20, 100) :: any
+ t:check(c and c.width == 15 and c.height == img.height - 10, f .. ": crop clipped")
+ for _, filter in { "nearest", "bilinear", "lanczos" } do
+ local z = Ops.resize(img, 23, 31, filter) :: any
+ t:check(z and z.width == 23 and z.height == 31 and z.format == f, f .. ": resize " .. filter)
+ end
+ local rr = Ops.rotate(img, 33) :: any
+ t:check(rr and rr.format == f, f .. ": rotate 33")
+ end
+ -- crop content, nearest identity, ccw convention
+ local c = Ops.crop(rgba, 3, 4, 5, 6) :: any
+ t:check(buffer.readu32(c.pixels, 0) == buffer.readu32(rgba.pixels, (4 * rgba.width + 3) * 4), "crop origin")
+ t:check(buffer.tostring((Ops.resize(rgba, rgba.width, rgba.height, "lanczos") :: any).pixels) == buffer.tostring(rgba.pixels), "same-size resize is a copy")
+ local q = Ops.rotate90(rgba, 1) :: any -- ccw: the top-right pixel goes to the top-left
+ t:eq(buffer.readu32(q.pixels, 0), buffer.readu32(rgba.pixels, (rgba.width - 1) * 4), "rotate90 is counter-clockwise")
+end
+
+-- pixels, fill, premultiply
+do
+ for _, f in FORMATS do
+ local img = Ops.new(3, 2, f) :: any
+ t:check(img and img.format == f, "new " .. f)
+ if f ~= "yuv420p" then
+ local max = if f == "rgba16" or f == "gray16" then 65535 elseif f == "rgbaf32" then 1 else 255
+ t:check(Ops.setPixel(img, 2, 1, max, max, max, max), f .. ": setPixel")
+ local r, g, b, a = Ops.getPixel(img, 2, 1)
+ t:check(r == max and g == max and b == max and a == max, f .. ": getPixel after setPixel")
+ Ops.fill(img, 0, 0, 0, 0)
+ local r2 = Ops.getPixel(img, 2, 1)
+ t:check(r2 == (if f == "alpha8" then 255 else 0), f .. ": fill")
+ else
+ t:check(Ops.setPixel(img, 0, 0, 1, 2, 3) == nil, "setPixel refuses yuv420p")
+ t:check(Ops.getPixel(img, 2, 1) ~= nil, "getPixel on yuv420p")
+ end
+ end
+ local p = Ops.premultiply(rgba) :: any
+ local u = Ops.unpremultiply(p) :: any
+ local worst = 0
+ for i = 0, rgba.width * rgba.height - 1 do
+ local a = buffer.readu8(rgba.pixels, i * 4 + 3)
+ t:check(buffer.readu8(p.pixels, i * 4) <= a, "premultiplied <= alpha")
+ if a >= 32 then
+ for c = 0, 2 do
+ worst = math.max(worst, math.abs(buffer.readu8(u.pixels, i * 4 + c) - buffer.readu8(rgba.pixels, i * 4 + c)))
+ end
+ end
+ end
+ t:check(worst <= 4, "premultiply round trip error " .. worst .. " (alpha >= 32)")
+ t:note("premultiply round trip: max error %d for alpha >= 32", worst)
+end
+
+-- blit
+do
+ local dst = Ops.new(10, 10, "rgba8") :: any
+ Ops.fill(dst, 10, 20, 30, 255)
+ local src = Ops.new(4, 4, "rgba8") :: any
+ Ops.fill(src, 200, 100, 50, 255)
+ Ops.blit(dst, src, -2, 8)
+ t:check(select(1, Ops.getPixel(dst, 0, 8)) == 200 and select(1, Ops.getPixel(dst, 1, 9)) == 200, "blit clipped at the left / bottom")
+ t:check(select(1, Ops.getPixel(dst, 2, 8)) == 10 and select(1, Ops.getPixel(dst, 0, 7)) == 10, "blit stays inside its rectangle")
+ Ops.fill(src, 0, 0, 0, 0)
+ Ops.blit(dst, src, 0, 0)
+ t:check(select(1, Ops.getPixel(dst, 0, 0)) == 10, "over with a transparent source keeps dst")
+ Ops.blit(dst, src, 0, 0, { blend = "source" })
+ t:check(select(4, Ops.getPixel(dst, 0, 0)) == 0, "source blend copies alpha")
+ Ops.fill(src, 255, 255, 255, 255)
+ Ops.blit(dst, src, 5, 5, { opacity = 0.5 })
+ local r = Ops.getPixel(dst, 5, 5)
+ t:check(math.abs(r - 133) <= 1, "opacity 0.5 over (10 -> " .. r .. ")")
+ -- rgb8 destination, gray source, float destination
+ local d3 = Ops.convert(dst, "rgb8") :: any
+ t:check(Ops.blit(d3, Ops.convert(src, "graya8") :: any, 1, 1) == d3, "blit onto rgb8")
+ local df = Ops.convert(dst, "rgbaf32") :: any
+ t:check(Ops.blit(df, src, 0, 0, { opacity = 0.25 }) == df, "blit onto rgbaf32")
+ local dy = Ops.convert(dst, "yuv420p") :: any
+ t:check(Ops.blit(dy, src, 3, 3) == dy, "blit onto yuv420p")
+end
+
+-- animation helpers
+do
+ local W, H = 6, 4
+ local function solid(w: number, h: number, r: number, a: number): any
+ local im = Ops.new(w, h, "rgba8") :: any
+ Ops.fill(im, r, 0, 0, a)
+ return im
+ end
+ local anim = Ops.new(W, H, "rgba8") :: any
+ anim.frames = {
+ { image = solid(W, H, 10, 255), delay = 0.1, x = 0, y = 0, dispose = "none", blend = "source" },
+ { image = solid(2, 2, 20, 255), delay = 0.2, x = 1, y = 1, dispose = "background", blend = "over" },
+ { image = solid(2, 2, 30, 255), delay = 0.3, x = 3, y = 1, dispose = "previous", blend = "over" },
+ { image = solid(1, 1, 40, 128), delay = 0.4, x = 5, y = 3, dispose = "none", blend = "over" },
+ }
+ local fr = Ops.coalesce(anim) :: any
+ t:eq(#fr, 4, "coalesce frame count")
+ local function at(i: number, x: number, y: number): (number, number)
+ local r, _, _, a = Ops.getPixel(fr[i], x, y)
+ return r, a
+ end
+ t:check(at(1, 0, 0) == 10 and at(1, 1, 1) == 10, "frame 1")
+ t:check(at(2, 1, 1) == 20 and at(2, 2, 2) == 20 and at(2, 0, 0) == 10, "frame 2 drawn at 1, 1")
+ local r3, a3 = at(3, 1, 1)
+ t:check(r3 == 0 and a3 == 0, "frame 2 disposed to background before frame 3")
+ t:check(at(3, 3, 1) == 30, "frame 3 drawn")
+ t:check(at(4, 3, 1) == 10, "frame 3 disposed to previous before frame 4")
+ local r4 = at(4, 5, 3)
+ t:check(r4 > 10 and r4 < 40, "frame 4 blends over")
+ t:eq(Ops.frameCount(anim), 4, "frameCount")
+ t:eq(Ops.durations(anim)[3], 0.3, "durations")
+ t:eq(Ops.frameCount(rgba), 1, "frameCount of a still")
+ t:check((Ops.coalesce(rgba) :: any)[1] == rgba, "coalesce of a still")
+ local made = Ops.fromFrames({ fr[1], fr[2], fr[3] }, { 0.5, 0.25 }) :: any
+ t:check(made and #made.frames == 3 and made.frames[2].delay == 0.25 and made.frames[3].delay == 0.1, "fromFrames delays")
+ t:check(buffer.tostring(made.pixels) == buffer.tostring(fr[1].pixels), "fromFrames pixels = frame 1")
+ local again = Ops.coalesce(made) :: any
+ t:check(buffer.tostring(again[3].pixels) == buffer.tostring(fr[3].pixels), "coalesce(fromFrames) round trip")
+ t:check(Ops.fromFrames({ fr[1], rgba }) == nil, "fromFrames refuses mixed sizes")
+end
+
+-- bad arguments: nil, Err, never a throw
+do
+ local rand = T.rng(5)
+ local junk: { any } = { nil, 0, -1, 1.5, 2 ^ 40, "x", {}, true, 0 / 0, math.huge, -7 }
+ local imgs: { any } = { rgba, rgb, {}, { pixels = buffer.create(1), width = 5, height = 5, format = "rgba8" }, Types.Image.new(1, 1, "alpha8"), Ops.convert(rgba, "yuv420p") }
+ local calls = {
+ function(a: any, b: any, c: any, d: any)
+ return Ops.convert(a, b)
+ end,
+ function(a: any, b: any, c: any, d: any)
+ return Ops.crop(a, b, c, d, b)
+ end,
+ function(a: any, b: any, c: any, _d: any)
+ return Ops.resize(a, b, c, "lanczos")
+ end,
+ function(a: any, b: any, c: any, _d: any)
+ return Ops.resize(a, b, c, b)
+ end,
+ function(a: any, b: any, _c: any, _d: any)
+ return Ops.rotate(a, b)
+ end,
+ function(a: any, b: any, _c: any, _d: any)
+ return Ops.rotate90(a, b)
+ end,
+ function(a: any, b: any, _c: any, _d: any)
+ return Ops.flip(a, b)
+ end,
+ function(a: any, b: any, c: any, d: any)
+ return Ops.blit(a, d, b, c)
+ end,
+ function(a: any, b: any, c: any, d: any)
+ return Ops.blit(a, a, b, c, { opacity = d })
+ end,
+ function(a: any, b: any, c: any, _d: any)
+ return Ops.getPixel(a, b, c)
+ end,
+ function(a: any, b: any, c: any, d: any)
+ return Ops.setPixel(a, b, c, d, d, d)
+ end,
+ function(a: any, b: any, _c: any, _d: any)
+ return Ops.new(a, b, "rgba8")
+ end,
+ function(a: any, _b: any, _c: any, _d: any)
+ return Ops.coalesce(a)
+ end,
+ function(a: any, b: any, _c: any, _d: any)
+ return Ops.fromFrames({ a, b } :: any)
+ end,
+ function(a: any, b: any, c: any, d: any)
+ return Ops.fill(a, b, c, d)
+ end,
+ }
+ local tries, threw = 0, 0
+ for _ = 1, 600 do
+ local f = calls[1 + rand(#calls)]
+ local a = imgs[1 + rand(#imgs)]
+ local args = { junk[1 + rand(#junk)], junk[1 + rand(#junk)], junk[1 + rand(#junk)] }
+ if rand(3) == 0 then
+ args[3] = imgs[1 + rand(#imgs)]
+ end
+ tries += 1
+ local ok, err = pcall(f, a, args[1], args[2], args[3])
+ if not ok then
+ threw += 1
+ print(" THREW: " .. tostring(err))
+ end
+ end
+ t:check(threw == 0, "bad arguments never throw (" .. threw .. " of " .. tries .. ")")
+ t:note("bad arguments: %d calls, none threw", tries)
+ local _, e = Ops.resize(rgba, 100000, 100000)
+ t:check(e and e.code == Err.LIMIT, "resize over the pixel limit")
+ local _, e2 = Ops.crop(rgba, 100, 100, 5, 5)
+ t:check(e2 and e2.code == Err.ARG, "empty crop")
+ local _, e3 = Ops.convert(rgba, "cmyk")
+ t:check(e3 and e3.code == Err.ARG, "unknown format")
+end
+
+t:done()
diff --git a/tools/bench.luau b/tools/bench.luau
index e5fa3aa..2dcc312 100644
--- a/tools/bench.luau
+++ b/tools/bench.luau
@@ -230,5 +230,164 @@ do
end)
bench("yaml encode", 3, #YB.text, function()
Yaml.encode(v)
+-- ------------------------------------------------------------------------------------------------ jpeg (ws-imgA)
+do
+ local Jpeg = require("@formats/image/jpeg")
+ local Types = require("@formats/Types")
+ local JB = require("@tests/gen/jpeg_bench")
+ for _, c in JB.files do
+ local b = buffer.fromstring(c.data)
+ local img = Jpeg.decode(Bytes.reader(b))
+ assert(img and Crc32.of(img.pixels) == c.crc, "jpeg bench: " .. c.name .. " does not match djpeg")
+ bench("jpeg decode " .. c.name, 3, c.width * c.height * 4, function()
+ Jpeg.decode(Bytes.reader(b))
+ end)
+ end
+ local b0 = buffer.fromstring(JB.files[1].data)
+ bench("jpeg decode 1/8 (DC only)", 3, JB.width * JB.height * 4, function()
+ Jpeg.decode(Bytes.reader(b0), { scale = 8 })
+ end)
+ local src = Types.Image.new(JB.width, JB.height, "rgb8")
+ buffer.writestring(src.pixels, 0, JB.rgb)
+ for _, o in { { label = "baseline 4:2:0 q85", quality = 85 }, { label = "progressive 4:2:0 q85", quality = 85, progressive = true }, { label = "baseline 4:4:4 q85 optimized", quality = 85, subsampling = "444", optimize = true } } do
+ bench("jpeg encode " .. o.label, 2, JB.width * JB.height * 3, function()
+ Jpeg.encode(src, o :: any)
+ end)
+ end
+end
+
+-- ---------------------------------------------------------------------------------------- ws-imgA: gif + quantize
+do
+ local Gif = require("@formats/image/gif")
+ local Quantize = require("@formats/codecs/Quantize")
+ local Types = require("@formats/Types")
+ local GB = require("@tests/gen/gif_bench")
+ local still = buffer.fromstring(GB.still)
+ local anim = buffer.fromstring(GB.anim)
+ local simg = assert(Gif.decode(Bytes.reader(still)))
+ local aimg = assert(Gif.decode(Bytes.reader(anim)))
+ local sw, sh = simg.width, simg.height
+ bench("gif decode 512x384", 5, sw * sh * 4, function()
+ Gif.decode(Bytes.reader(still))
+ end)
+ bench("gif decode 40 x 128x128 anim", 3, #(aimg.frames :: any) * 128 * 128 * 4, function()
+ Gif.decode(Bytes.reader(anim))
+ end)
+ bench("gif encode 512x384 (exact pal)", 3, sw * sh * 4, function()
+ Gif.encode(simg)
+ end)
+ local photo = Types.Image.new(sw, sh)
+ for i = 0, sw * sh - 1 do
+ local x, y = i % sw, i // sw
+ buffer.writeu32(photo.pixels, i * 4, (x % 256) + (y % 256) * 256 + ((x * y) % 256) * 65536 + 0xFF000000)
+ end
+ bench("quantize mediancut 256", 3, sw * sh * 4, function()
+ Quantize.palette(photo.pixels, sw, sh, 256)
+ end)
+ bench("quantize octree 256", 3, sw * sh * 4, function()
+ Quantize.palette(photo.pixels, sw, sh, 256, { method = "octree" })
+ end)
+ local pal = Quantize.palette(photo.pixels, sw, sh, 256)
+ bench("quantize map", 3, sw * sh * 4, function()
+ Quantize.map(photo.pixels, sw, sh, pal)
+ end)
+ bench("quantize map + dither", 3, sw * sh * 4, function()
+ Quantize.map(photo.pixels, sw, sh, pal, { dither = true })
+ end)
+ bench("gif encode 512x384 (quantize)", 2, sw * sh * 4, function()
+ Gif.encode(photo)
+ end)
+end
+
+-- ------------------------------------------------------------------------------------------------ ops/ImageOps
+do
+ local Ops = require("@formats/ops/ImageOps")
+ local img = assert(Png.decode(Bytes.reader(buffer.fromstring(PB[1].data))))
+ local n = img.width * img.height * 4
+ bench("imageops resize 1/2 bilinear", 2, n, function()
+ Ops.resize(img, img.width // 2, img.height // 2, "bilinear")
+ end)
+ bench("imageops resize 1/2 lanczos", 2, n, function()
+ Ops.resize(img, img.width // 2, img.height // 2, "lanczos")
+ end)
+ bench("imageops resize x1.5 bilinear", 1, n, function()
+ Ops.resize(img, img.width * 3 // 2, img.height * 3 // 2, "bilinear")
+ end)
+ bench("imageops rotate 30 (expand)", 1, n, function()
+ Ops.rotate(img, 30)
+ end)
+ bench("imageops rotate90", 3, n, function()
+ Ops.rotate90(img, 1)
+ end)
+ bench("imageops convert rgba8 -> gray8", 3, n, function()
+ Ops.convert(img, "gray8")
+ end)
+ local other = assert(Ops.flip(img, "h"))
+ bench("imageops composite over", 3, n, function()
+ Ops.composite(img, other)
+ end)
+end
+
+-- ------------------------------------------------------------------------------------------------ image/tiff (ws-imgA)
+do
+ local Tiff = require("@formats/image/tiff")
+ local Types = require("@formats/Types")
+ local src = Types.Image.new(1024, 768)
+ for i = 0, 1024 * 768 - 1 do
+ local x, y = i % 1024, i // 1024
+ buffer.writeu32(src.pixels, i * 4, 0xFF000000 + (x % 256) + ((y % 256) * 256) + (((x + y) // 4 % 256) * 65536))
+ end
+ for _, comp in { "none", "lzw", "deflate" } do
+ local enc = Tiff.encode(src, { compression = comp :: any }) :: buffer
+ bench("tiff decode rgba8 " .. comp, 3, 1024 * 768 * 4, function()
+ Tiff.decode(Bytes.reader(enc))
+ end)
+ bench("tiff encode rgba8 " .. comp, 2, 1024 * 768 * 4, function()
+ Tiff.encode(src, { compression = comp :: any })
+ end)
+ end
+ local enc16 = Tiff.encode(Types.Image.new(1024, 768, "rgba16"), { compression = "lzw" }) :: buffer
+ bench("tiff decode rgba16 lzw -> rgba8", 3, 1024 * 768 * 8, function()
+ Tiff.decode(Bytes.reader(enc16))
+ end)
+end
+
+-- ------------------------------------------------------------------------------------------------ imgA-simple: qoi / tga / pnm / hdr
+-- fixtures: tools/fixtures/qoi.py (tests/gen/qoi_bench.luau: run python3 -I tools/fixtures.py qoi first)
+do
+ local Qoi = require("@formats/image/qoi")
+ local Tga = require("@formats/image/tga")
+ local Pnm = require("@formats/image/pnm")
+ local Hdr = require("@formats/image/hdr")
+ local Types = require("@formats/Types")
+ local QB = require("@tests/gen/qoi_bench")
+ local qd = buffer.fromstring(QB.data)
+ local n = QB.width * QB.height * 4
+ bench("qoi decode 1024x768", 5, n, function()
+ Qoi.decode(Bytes.reader(qd))
+ end)
+ local img = Types.Image.new(QB.width, QB.height)
+ img.pixels = buffer.fromstring(QB.pixels)
+ bench("qoi encode 1024x768", 5, n, function()
+ Qoi.encode(img)
+ end)
+ local tr = Tga.encode(img, { rle = true }) :: buffer
+ bench("tga decode rle 1024x768", 3, n, function()
+ Tga.decode(Bytes.reader(tr))
+ end)
+ bench("tga encode rle 1024x768", 3, n, function()
+ Tga.encode(img, { rle = true })
+ end)
+ local pp = Pnm.encode(img, { format = "ppm" }) :: buffer
+ bench("ppm decode 1024x768", 3, n, function()
+ Pnm.decode(Bytes.reader(pp))
+ end)
+ local f = Hdr.decode(Bytes.reader(Hdr.encode(img) :: buffer), { native = true }) :: Types.Image
+ local hb = Hdr.encode(f) :: buffer
+ bench("hdr decode rle 1024x768 (rgbaf32)", 3, n, function()
+ Hdr.decode(Bytes.reader(hb), { native = true })
+ end)
+ bench("hdr encode rle 1024x768", 3, n, function()
+ Hdr.encode(f)
end)
end
diff --git a/tools/fixtures/gif.py b/tools/fixtures/gif.py
new file mode 100644
index 0000000..257fb21
--- /dev/null
+++ b/tools/fixtures/gif.py
@@ -0,0 +1,133 @@
+# GIF fixtures (tools/fixtures.py): GIFs written by ImageMagick and Pillow (static, interlaced, 2..256 colours, grey,
+# transparency, animations with every disposal method, sub-rectangle frames, local colour tables, loop counts,
+# comments), each with ImageMagick's decode of every frame as the reference.
+# tests/gen/gif.luau { { name, data, width, height, loops, frames = { { w, h, x, y, delay, dispose, crc } },
+# first = crc of the first frame on a transparent canvas, comment? } }
+# tests/gen/gif_bench.luau a 512 x 384 photo-like GIF (256 colours) and a 40-frame 128 x 128 animation
+# CRCs are of rgba8 with transparent pixels (alpha 0) zeroed to 0, 0, 0, 0. delay in centiseconds.
+import os, struct, tempfile, zlib
+
+PILLOW = r'''
+import io, sys, random
+from PIL import Image, ImageDraw
+out = sys.argv[1]
+rng = random.Random(4)
+def frame(w, h, seed, alpha=False):
+ im = Image.new("RGBA", (w, h), (0, 0, 0, 0) if alpha else (seed * 40 % 256, 90, 200, 255))
+ d = ImageDraw.Draw(im)
+ for i in range(5):
+ x, y = rng.randrange(w), rng.randrange(h)
+ d.ellipse([x - 6, y - 6, x + 6, y + 6], fill=(rng.randrange(256), rng.randrange(256), seed * 60 % 256, 255))
+ return im
+# animation with per-frame disposal, durations, loop
+fr = [frame(48, 32, i) for i in range(4)]
+fr[0].save(out + "/pil_anim.gif", save_all=True, append_images=fr[1:], duration=[50, 120, 70, 200], loop=2, disposal=[0, 1, 2, 3], optimize=False)
+# transparent animation (sub-rectangles from Pillow's optimizer)
+fr = [frame(40, 40, i, alpha=True) for i in range(5)]
+fr[0].save(out + "/pil_alpha.gif", save_all=True, append_images=fr[1:], duration=80, loop=0, disposal=2)
+# a static interlaced palette image with a comment
+im = frame(61, 37, 9).convert("P", palette=Image.Palette.ADAPTIVE, colors=32)
+im.save(out + "/pil_interlaced.gif", interlace=True, comment=b"made by tools/fixtures/gif.py")
+# 1-bit and a 3-colour image (minimum code size 2)
+Image.frombytes("L", (17, 9), bytes((x * 255 // 16) if (x + y) % 3 else 0 for y in range(9) for x in range(17))).convert("1").save(out + "/pil_1bit.gif")
+im = Image.new("P", (23, 19)); im.putpalette([255, 0, 0, 0, 255, 0, 0, 0, 255])
+im.putdata([(x * y) % 3 for y in range(19) for x in range(23)]); im.save(out + "/pil_3col.gif")
+'''
+
+
+def run_im(ctx, args):
+ return ctx.nix("imagemagick", ["magick"] + args)
+
+
+def reference(ctx, path):
+ info = run_im(ctx, ["identify", "-format", "%w %h %X %Y %T %D %W %H %[comment]|", path]).decode("latin-1")
+ raw = run_im(ctx, [path, "rgba:-"])
+ frames, pos = [], 0
+ comment = None
+ for line in info.split("|"):
+ if not line.strip():
+ continue
+ parts = line.split(" ", 8)
+ w, h, x, y, delay = int(parts[0]), int(parts[1]), int(parts[2]), int(parts[3]), int(parts[4])
+ dispose = parts[5]
+ cw, ch = int(parts[6]), int(parts[7])
+ if len(parts) > 8 and parts[8]:
+ comment = parts[8]
+ px = bytearray(raw[pos:pos + w * h * 4]); pos += w * h * 4
+ for i in range(0, len(px), 4):
+ if px[i + 3] == 0:
+ px[i:i + 4] = b"\0\0\0\0"
+ frames.append({"w": w, "h": h, "x": x, "y": y, "delay": delay, "dispose": dispose.lower(), "px": bytes(px), "crc": zlib.crc32(bytes(px))})
+ assert pos == len(raw), (path, pos, len(raw))
+ # the first frame on a transparent canvas
+ f = frames[0]
+ canvas = bytearray(cw * ch * 4)
+ for yy in range(f["h"]):
+ for xx in range(f["w"]):
+ X, Y = f["x"] + xx, f["y"] + yy
+ if 0 <= X < cw and 0 <= Y < ch:
+ p = f["px"][(yy * f["w"] + xx) * 4:(yy * f["w"] + xx) * 4 + 4]
+ if p[3]:
+ canvas[(Y * cw + X) * 4:(Y * cw + X) * 4 + 4] = p
+ for f in frames:
+ del f["px"]
+ return cw, ch, frames, zlib.crc32(bytes(canvas)), comment
+
+
+def loops_of(data):
+ i = data.find(b"NETSCAPE2.0")
+ if i < 0:
+ return None
+ return data[i + 13] | (data[i + 14] << 8)
+
+
+def generate(ctx):
+ work = tempfile.mkdtemp(prefix="gif-fx-")
+ files = []
+
+ def im(name, args):
+ p = os.path.join(work, name + ".gif")
+ run_im(ctx, args + [p])
+ files.append((name, p))
+
+ im("rose", ["rose:"])
+ im("rose_2col", ["rose:", "-colors", "2"])
+ im("rose_16col_interlaced", ["rose:", "-colors", "16", "-interlace", "GIF"])
+ im("rose_dither", ["rose:", "-resize", "200%", "-dither", "FloydSteinberg", "-colors", "64"])
+ im("logo", ["logo:", "-resize", "30%"])
+ im("gray", ["-size", "64x40", "gradient:", "-colorspace", "gray"])
+ im("transparent", ["-size", "40x30", "xc:none", "-fill", "red", "-draw", "circle 20,15 20,5"])
+ for disp in ("None", "Background", "Previous"):
+ im("anim_" + disp.lower(), ["-delay", "7", "-dispose", disp, "-size", "30x20", "xc:red",
+ "-size", "10x8", "-page", "+5+4", "xc:blue", "-page", "+12+9", "xc:lime",
+ "-page", "+0+0", "-size", "6x6", "xc:yellow", "-loop", "3"])
+ # local colour tables: frames with different 256-colour palettes
+ im("anim_local", ["-delay", "20", "rose:", "(", "rose:", "-negate", ")", "(", "logo:", "-resize", "70x46!", ")", "-loop", "0"])
+ # optimised transparency animation
+ im("anim_optimized", ["-delay", "5", "-size", "50x50", "xc:white", "-fill", "black",
+ "(", "+clone", "-draw", "circle 10,10 10,5", ")", "(", "+clone", "-draw", "circle 30,30 30,24", ")",
+ "(", "+clone", "-draw", "circle 40,12 40,6", ")", "-layers", "OptimizeTransparency", "-loop", "0"])
+ ctx.python(["pillow"], "import sys; sys.argv = ['', %r]\n" % work + PILLOW)
+ for n in ("pil_anim", "pil_alpha", "pil_interlaced", "pil_1bit", "pil_3col"):
+ files.append((n, os.path.join(work, n + ".gif")))
+ cases = []
+ for name, p in files:
+ data = open(p, "rb").read()
+ cw, ch, frames, first, comment = reference(ctx, p)
+ c = {"name": name, "data": data, "width": cw, "height": ch, "frames": frames, "first": first}
+ lp = loops_of(data)
+ if lp is not None:
+ c["loops"] = lp # the raw NETSCAPE2.0 repeat value
+ if comment:
+ c["comment"] = comment
+ cases.append(c)
+ ctx.emit("gif", cases)
+
+ bench = os.path.join(work, "bench.gif")
+ run_im(ctx, ["-size", "512x384", "-seed", "3", "plasma:fractal", "-colors", "256", bench])
+ anim = os.path.join(work, "bench_anim.gif")
+ args = ["-delay", "4"]
+ for i in range(40):
+ args += ["(", "-size", "128x128", "radial-gradient:", "-roll", "+%d+%d" % (i * 3, i * 2), ")"]
+ run_im(ctx, args + ["-colors", "128", "-loop", "0", anim])
+ ctx.emit("gif_bench", {"still": open(bench, "rb").read(), "anim": open(anim, "rb").read()})
diff --git a/tools/fixtures/hdr.py b/tools/fixtures/hdr.py
new file mode 100644
index 0000000..bdf1017
--- /dev/null
+++ b/tools/fixtures/hdr.py
@@ -0,0 +1,93 @@
+# Radiance HDR fixtures (tools/fixtures.py): files ImageMagick writes (new-style RLE, from float PFM sources) and
+# hand-written ones (flat and old-style RLE scanlines, narrow images, the "#?RGBE" header, EXPOSURE lines, every
+# orientation); references = ImageMagick's float decodes for its files, and for the hand-written ones the RGBE values
+# decoded by the rgbe.c rule (m * 2^(e - 136)) here.
+# tests/gen/hdr.luau { { name, data, width, height, floats (rgbaf32 little-endian bytes), exposure? } }
+import math, os, random, shutil, struct, subprocess, tempfile
+
+
+def rgbe(r, g, b):
+ v = max(r, g, b)
+ if v < 1e-32:
+ return (0, 0, 0, 0)
+ m, e = math.frexp(v)
+ s = m * 256 / v
+ return (min(255, int(r * s)), min(255, int(g * s)), min(255, int(b * s)), e + 128)
+
+
+def flt(p):
+ if p[3] == 0:
+ return (0.0, 0.0, 0.0)
+ f = math.ldexp(1.0, p[3] - 136)
+ return (p[0] * f, p[1] * f, p[2] * f)
+
+
+def generate(ctx):
+ magick = ctx.nix("imagemagick", ["sh", "-c", "command -v magick"]).decode().strip()
+ work = tempfile.mkdtemp(prefix="formats-hdr-")
+ try:
+ _generate(ctx, magick, work)
+ finally:
+ shutil.rmtree(work, ignore_errors=True)
+
+
+def _generate(ctx, magick, work):
+ rng = random.Random(4)
+ cases = []
+
+ def im_case(name, w, h, fn):
+ pfm = os.path.join(work, name + ".pfm")
+ with open(pfm, "wb") as f:
+ f.write(b"PF\n%d %d\n-1.0\n" % (w, h))
+ for y in range(h - 1, -1, -1):
+ for x in range(w):
+ f.write(struct.pack(" (x, y) of scanline i pixel j; pix: (i, j) -> RGBE"""
+ data = header + b"\n\n" + res + b"\n" + b"".join(r for r, _ in rows)
+ fl = [(0.0, 0.0, 0.0)] * (w * h)
+ for i, (_, pixels) in enumerate(rows):
+ for j, p in enumerate(pixels):
+ x, y = mapping(i, j)
+ fl[y * w + x] = flt(p)
+ c = {"name": name, "data": data, "width": w, "height": h,
+ "floats": b"".join(struct.pack("> (x % 8)
+ mask += row
+ return d + bytes(mask)
+def icon(entries, typ=1, hotspots=None):
+ hdr = struct.pack("> 8, (v * 257) & 255)))
+cmyk = photo.convert("CMYK")
+for name, kw in (("cmyk", {}), ("cmyk_prog", {"progressive": True})):
+ p = os.path.join(out, "photo_" + name + ".jpg")
+ cmyk.save(p, "JPEG", quality=90, **kw)
+ data = bytearray(open(p, "rb").read())
+ i = data.find(b"Adobe")
+ assert i > 0
+ data[i + 11] = 2
+ open(os.path.join(out, "photo_" + name.replace("cmyk", "ycck") + ".jpg"), "wb").write(data)
+ for n in (name, name.replace("cmyk", "ycck")):
+ im = Image.open(os.path.join(out, "photo_" + n + ".jpg"))
+ raw = im.tobytes()
+ rgb = bytearray()
+ for k in range(0, len(raw), 4):
+ c, m, y, kk = raw[k:k + 4]
+ kk = 255 - kk
+ rgb += bytes((((255 - c) * kk + 127) // 255, ((255 - m) * kk + 127) // 255, ((255 - y) * kk + 127) // 255))
+ open(os.path.join(out, "photo_" + n + ".ref"), "wb").write(rgb)
+'''
+
+SCANS = {
+ "spectral": "0,1,2: 0-0, 0, 0;\n0: 1-5, 0, 0;\n0: 6-63, 0, 0;\n1: 1-63, 0, 0;\n2: 1-63, 0, 0;\n",
+ "deepsa": (
+ "0,1,2: 0-0, 0, 2;\n0: 1-5, 0, 3;\n1: 1-63, 0, 1;\n2: 1-63, 0, 1;\n0: 6-63, 0, 3;\n"
+ "0: 1-63, 3, 2;\n0: 1-63, 2, 1;\n0: 1-63, 1, 0;\n1: 1-63, 1, 0;\n2: 1-63, 1, 0;\n"
+ "0,1,2: 0-0, 2, 1;\n0,1,2: 0-0, 1, 0;\n"
+ ),
+ "seqsplit": "0: 0-63, 0, 0;\n1: 0-63, 0, 0;\n2: 0-63, 0, 0;\n",
+ "dcsplit": "0: 0-0, 0, 0;\n1: 0-0, 0, 0;\n2: 0-0, 0, 0;\n0: 1-63, 0, 0;\n1: 1-63, 0, 0;\n2: 1-63, 0, 0;\n",
+}
+SAMPLINGS = {"444": "1x1", "422": "2x1", "420": "2x2", "411": "4x1", "440": "1x2"}
+
+
+def parse_pnm(data):
+ """P5 / P6 -> w, h, RGB8 bytes (16-bit samples scaled as djpeg's 12-bit output)"""
+ fields, pos = [], 0
+ while len(fields) < 4:
+ while data[pos:pos + 1].isspace():
+ pos += 1
+ if data[pos:pos + 1] == b"#":
+ while data[pos:pos + 1] != b"\n":
+ pos += 1
+ continue
+ s = pos
+ while not data[pos:pos + 1].isspace():
+ pos += 1
+ fields.append(data[s:pos])
+ pos += 1
+ magic, w, h, mx = fields[0], int(fields[1]), int(fields[2]), int(fields[3])
+ ch = 3 if magic == b"P6" else 1
+ n = w * h * ch
+ if mx < 256:
+ px = data[pos:pos + n]
+ else:
+ raw = data[pos:pos + 2 * n]
+ px = bytes(((raw[2 * i] << 8 | raw[2 * i + 1]) * 255 + mx // 2) // mx for i in range(n))
+ if ch == 1:
+ px = bytes(v for v in px for _ in range(3))
+ return w, h, px
+
+
+def rgba_crc(rgb):
+ out = bytearray(len(rgb) // 3 * 4)
+ out[0::4], out[1::4], out[2::4] = rgb[0::3], rgb[1::3], rgb[2::3]
+ out[3::4] = b"\xff" * (len(rgb) // 3)
+ return zlib.crc32(bytes(out))
+
+
+def generate(ctx):
+ bindir = os.path.dirname(ctx.nix("libjpeg_turbo", ["sh", "-c", "command -v cjpeg"]).decode().strip())
+ magick = ctx.nix("imagemagick", ["sh", "-c", "command -v magick"]).decode().strip()
+ work = tempfile.mkdtemp(prefix="formats-jpeg-")
+ try:
+ _generate(ctx, bindir, magick, work)
+ finally:
+ shutil.rmtree(work, ignore_errors=True)
+
+
+def _generate(ctx, bindir, magick, work):
+ def run(tool, *args):
+ exe = tool if os.path.isabs(tool) else os.path.join(bindir, tool)
+ r = subprocess.run([exe] + list(args), capture_output=True)
+ if r.returncode != 0:
+ raise SystemExit("fixtures/jpeg: %s %s failed: %s" % (tool, " ".join(args), r.stderr.decode()))
+ return r.stdout
+
+ W = lambda n: os.path.join(work, n)
+ # photo-like sources: ImageMagick's built-in rose, and a plasma fractal
+ run(magick, "rose:", "-resize", "160x120!", W("photo.ppm"))
+ run(magick, "-size", "1024x768", "-seed", "7", "plasma:fractal", "-blur", "0x1", W("big.ppm"))
+ ctx.python(["pillow"], SOURCES.replace("sys.argv[1]", repr(work)))
+ for k, v in SCANS.items():
+ with open(W(k + ".scans"), "w") as f:
+ f.write(v)
+ SRC = {"synth": W("synth.ppm"), "photo": W("photo.ppm"), "gray": W("photo.pgm"), "photo16": W("photo16.ppm")}
+ for w, h in ((1, 1), (7, 5), (17, 9), (33, 1), (1, 33), (16, 16)):
+ SRC["%dx%d" % (w, h)] = W("s%dx%d.ppm" % (w, h))
+
+ cases = [] # (name, path, scales | "cmyk", err)
+
+ def cj(name, src, *args, scales=(1, 2, 4, 8), err=None):
+ out = W(name + ".jpg")
+ run("cjpeg", *args, "-outfile", out, SRC[src])
+ cases.append((name, out, scales, err))
+
+ for q in (30, 90):
+ for sn, s in SAMPLINGS.items():
+ cj("photo_q%d_%s" % (q, sn), "photo", "-quality", str(q), "-sample", s)
+ cj("photo_q%d_%s_prog" % (q, sn), "photo", "-quality", str(q), "-sample", s, "-progressive")
+ for sn, s in SAMPLINGS.items():
+ cj("synth_q75_%s" % sn, "synth", "-quality", "75", "-sample", s)
+ cj("synth_q75_%s_prog" % sn, "synth", "-quality", "75", "-sample", s, "-progressive")
+ cj("photo_q100_420", "photo", "-quality", "100", "-sample", "2x2")
+ cj("photo_q100_420_prog", "photo", "-quality", "100", "-sample", "2x2", "-progressive")
+ cj("photo_q5_420", "photo", "-quality", "5", "-sample", "2x2")
+ cj("photo_q5_444_prog", "photo", "-quality", "5", "-sample", "1x1", "-progressive")
+ cj("photo_optimize", "photo", "-quality", "80", "-optimize")
+ cj("photo_s31", "photo", "-sample", "3x1,1x1,1x1")
+ cj("photo_s4242", "photo", "-sample", "4x2,1x1,1x1")
+ cj("photo_s222111", "photo", "-sample", "2x2,2x1,1x1")
+ cj("photo_s111222", "photo", "-sample", "1x1,2x2,2x2")
+ cj("photo_s1422", "photo", "-sample", "1x4,1x2,1x2", "-progressive")
+ cj("synth_s2222", "synth", "-sample", "2x2,2x2,2x2", "-scans", W("seqsplit.scans"))
+ cj("photo_rst1", "photo", "-sample", "2x2", "-restart", "1")
+ cj("photo_rst3b", "photo", "-sample", "2x2", "-restart", "3B")
+ cj("photo_rst1b_prog", "photo", "-sample", "2x2", "-restart", "1B", "-progressive")
+ cj("photo_rst2_prog444", "photo", "-sample", "1x1", "-restart", "2", "-progressive")
+ cj("photo_gray", "photo", "-grayscale")
+ cj("photo_gray_prog", "photo", "-grayscale", "-progressive")
+ cj("photo_gray_rst", "photo", "-grayscale", "-restart", "5B")
+ cj("photo_rgb", "photo", "-rgb")
+ cj("photo_rgb_prog", "photo", "-rgb", "-progressive")
+ for k in SCANS:
+ cj("photo_scans_" + k, "photo", "-sample", "2x2", "-scans", W(k + ".scans"))
+ cj("synth_scans_" + k, "synth", "-sample", "1x1", "-scans", W(k + ".scans"))
+ cj("photo_12bit_420", "photo16", "-precision", "12", "-sample", "2x2")
+ cj("photo_12bit_444_prog", "photo16", "-precision", "12", "-sample", "1x1", "-progressive")
+ cj("photo_12bit_gray", "photo16", "-precision", "12", "-grayscale")
+ for k in ("1x1", "7x5", "17x9", "33x1", "1x33", "16x16"):
+ cj("tiny_%s_420" % k, k, "-sample", "2x2")
+ cj("tiny_%s_422_prog" % k, k, "-sample", "2x1", "-progressive")
+ cj("tiny_%s_444" % k, k, "-sample", "1x1", "-quality", "95")
+ cj("tiny_%s_arith" % k, k, "-sample", "2x2", "-arithmetic")
+ # arithmetic coding
+ for sn in ("444", "420", "422"):
+ cj("photo_arith_%s" % sn, "photo", "-arithmetic", "-sample", SAMPLINGS[sn])
+ cj("photo_arith_%s_prog" % sn, "photo", "-arithmetic", "-progressive", "-sample", SAMPLINGS[sn])
+ cj("photo_arith_q5", "photo", "-arithmetic", "-quality", "5")
+ cj("photo_arith_q100_prog", "photo", "-arithmetic", "-progressive", "-quality", "100")
+ cj("photo_arith_rst", "photo", "-arithmetic", "-restart", "1")
+ cj("photo_arith_rst_prog", "photo", "-arithmetic", "-progressive", "-restart", "3B")
+ cj("photo_arith_gray", "photo", "-arithmetic", "-grayscale")
+ cj("photo_arith_gray_prog", "photo", "-arithmetic", "-grayscale", "-progressive")
+ cj("photo_arith_rgb", "photo", "-arithmetic", "-rgb")
+ cj("photo_arith_12bit", "photo16", "-arithmetic", "-precision", "12", "-sample", "2x2")
+ cj("photo_arith_12bit_prog", "photo16", "-arithmetic", "-precision", "12", "-progressive")
+ cj("synth_arith_deepsa", "synth", "-arithmetic", "-sample", "1x1", "-scans", W("deepsa.scans"))
+ cj("synth_arith_spectral", "synth", "-arithmetic", "-sample", "2x2", "-scans", W("spectral.scans"))
+ cj("synth_arith_seqsplit", "synth", "-arithmetic", "-sample", "2x2", "-scans", W("seqsplit.scans"))
+ # refused
+ cj("photo_lossless", "photo", "-lossless", "1", scales=(), err="lossless")
+
+ base = W("photo_q90_420.jpg")
+ for name, args in (("tran_prog", ["-progressive"]), ("tran_rst", ["-restart", "2B"]), ("tran_optimize", ["-optimize"]),
+ ("tran_arith", ["-arithmetic"]), ("tran_arith_prog", ["-arithmetic", "-progressive"])):
+ out = W("photo_" + name + ".jpg")
+ run("jpegtran", *args, "-outfile", out, base)
+ cases.append(("photo_" + name, out, (1, 2, 4, 8), None))
+ # an arithmetic file back to Huffman
+ out = W("photo_tran_unarith.jpg")
+ run("jpegtran", "-outfile", out, W("photo_arith_420.jpg"))
+ cases.append(("photo_tran_unarith", out, (1, 2, 4, 8), None))
+
+ # stripped DHT: the standard tables
+ data = open(base, "rb").read()
+ out, pos = bytearray(data[:2]), 2
+ while pos < len(data):
+ m = data[pos + 1]
+ if m == 0xDA:
+ out += data[pos:]
+ break
+ ln = (data[pos + 2] << 8) | data[pos + 3]
+ if m != 0xC4:
+ out += data[pos:pos + 2 + ln]
+ pos += 2 + ln
+ open(W("photo_nodht.jpg"), "wb").write(bytes(out))
+ cases.append(("photo_nodht", W("photo_nodht.jpg"), (1, 2, 4, 8), None))
+ for n in ("cmyk", "cmyk_prog", "ycck", "ycck_prog"):
+ cases.append(("photo_" + n, W("photo_" + n + ".jpg"), "cmyk", None))
+
+ dec = []
+ for name, path, scales, err in cases:
+ e = {"name": name, "data": open(path, "rb").read()}
+ if err:
+ e["err"] = err
+ if scales == "cmyk":
+ e["cmyk"] = open(path[:-4] + ".ref", "rb").read()
+ else:
+ refs = []
+ for s in scales:
+ args = ["-dct", "int", "-pnm"] + (["-scale", "1/%d" % s] if s != 1 else []) + [path]
+ w, h, px = parse_pnm(run("djpeg", *args))
+ refs.append({"scale": s, "width": w, "height": h, "crc": rgba_crc(px)})
+ e["refs"] = refs
+ dec.append(e)
+ ctx.emit("jpeg_dec", dec)
+
+ # encoder: cjpeg's bytes for the same settings
+ enc = []
+
+ def ce(name, src, fmt, opts, *args):
+ out = W("enc_" + name + ".jpg")
+ run("cjpeg", "-baseline", *args, "-outfile", out, SRC[src])
+ w, h, px = parse_pnm(open(SRC[src], "rb").read())
+ if fmt == "gray8":
+ px = px[0::3]
+ enc.append({"name": name, "width": w, "height": h, "format": fmt, "pixels": px, "opts": opts,
+ "want": open(out, "rb").read()})
+
+ for q in (10, 50, 75, 90, 100):
+ ce("photo_q%d_420" % q, "photo", "rgb8", {"quality": q}, "-quality", str(q), "-sample", "2x2")
+ for sn in ("444", "422", "420"):
+ ce("photo_%s" % sn, "photo", "rgb8", {"quality": 85, "subsampling": sn}, "-quality", "85", "-sample", SAMPLINGS[sn])
+ ce("synth_%s" % sn, "synth", "rgb8", {"quality": 85, "subsampling": sn}, "-quality", "85", "-sample", SAMPLINGS[sn])
+ ce("photo_%s_prog" % sn, "photo", "rgb8", {"quality": 85, "subsampling": sn, "progressive": True}, "-quality", "85", "-sample", SAMPLINGS[sn], "-progressive")
+ ce("synth_%s_prog" % sn, "synth", "rgb8", {"quality": 85, "subsampling": sn, "progressive": True}, "-quality", "85", "-sample", SAMPLINGS[sn], "-progressive")
+ ce("photo_%s_opt" % sn, "photo", "rgb8", {"quality": 85, "subsampling": sn, "optimize": True}, "-quality", "85", "-sample", SAMPLINGS[sn], "-optimize")
+ ce("photo_gray", "gray", "gray8", {"quality": 80}, "-quality", "80")
+ ce("photo_gray_prog", "gray", "gray8", {"quality": 80, "progressive": True}, "-quality", "80", "-progressive")
+ ce("photo_rgb_to_gray", "photo", "rgb8", {"quality": 80, "gray": True}, "-quality", "80", "-grayscale")
+ ce("photo_rst", "photo", "rgb8", {"quality": 75, "restart": 3}, "-quality", "75", "-sample", "2x2", "-restart", "3B")
+ ce("photo_rst_prog", "photo", "rgb8", {"quality": 75, "restart": 2, "progressive": True}, "-quality", "75", "-sample", "2x2", "-restart", "2B", "-progressive")
+ ce("photo_q100_prog444", "photo", "rgb8", {"quality": 100, "subsampling": "444", "progressive": True}, "-quality", "100", "-sample", "1x1", "-progressive")
+ for k in ("1x1", "7x5", "17x9", "33x1", "1x33", "16x16"):
+ ce("tiny_%s_420" % k, k, "rgb8", {"quality": 90}, "-quality", "90", "-sample", "2x2")
+ ce("tiny_%s_422_prog" % k, k, "rgb8", {"quality": 90, "subsampling": "422", "progressive": True}, "-quality", "90", "-sample", "2x1", "-progressive")
+ ctx.emit("jpeg_enc", enc)
+
+ SRC["big"] = W("big.ppm")
+ bench = []
+ for name, args in (("baseline 4:2:0", ["-sample", "2x2"]), ("progressive 4:2:0", ["-sample", "2x2", "-progressive"]),
+ ("arithmetic 4:2:0", ["-sample", "2x2", "-arithmetic"]), ("baseline 4:4:4", ["-sample", "1x1"])):
+ out = W("bench.jpg")
+ run("cjpeg", "-quality", "85", *args, "-outfile", out, SRC["big"])
+ w, h, px = parse_pnm(run("djpeg", "-dct", "int", "-pnm", out))
+ bench.append({"name": name, "width": w, "height": h, "data": open(out, "rb").read(), "crc": rgba_crc(px)})
+ w, h, px = parse_pnm(open(SRC["big"], "rb").read())
+ ctx.emit("jpeg_bench", {"files": bench, "width": w, "height": h, "rgb": px})
diff --git a/tools/fixtures/lzw.py b/tools/fixtures/lzw.py
new file mode 100644
index 0000000..6cb37f9
--- /dev/null
+++ b/tools/fixtures/lzw.py
@@ -0,0 +1,70 @@
+# LZW fixtures (tools/fixtures.py): code streams written by reference encoders, with the data they encode.
+# tests/gen/lzw.luau { gif = { { name, min, codes, data } }, tiff = { { name, codes, data } } }
+# gif: Pillow's GIF writer (its own LZW), the image data sub-blocks joined; data = the palette indexes
+# tiff: libtiff's LZW (Pillow compression="tiff_lzw"), one strip; data = the raw 8-bit samples
+import struct
+
+CODE = r'''
+import io, random, struct, sys
+from PIL import Image
+rng = random.Random(7)
+def img(w, h, kind, ncol):
+ px = bytearray()
+ for y in range(h):
+ for x in range(w):
+ if kind == "noise":
+ px.append(rng.randrange(ncol))
+ elif kind == "flat":
+ px.append(3 % ncol)
+ else:
+ px.append(((x // 3) ^ (y // 5)) % ncol if rng.random() < 0.97 else rng.randrange(ncol))
+ return bytes(px)
+out = []
+for (w, h, kind, ncol) in ((1, 1, "noise", 2), (16, 16, "noise", 2), (64, 48, "pattern", 4), (64, 48, "noise", 16),
+ (300, 200, "pattern", 256), (300, 200, "noise", 256), (256, 200, "flat", 256), (97, 3, "noise", 128)):
+ data = img(w, h, kind, ncol)
+ im = Image.frombytes("P", (w, h), data)
+ im.putpalette(bytes(range(256)) * 3)
+ b = io.BytesIO(); im.save(b, "GIF", optimize=False, interlace=False); g = b.getvalue()
+ # walk to the image descriptor
+ p = 13 + (3 << ((g[10] & 7) + 1) if g[10] & 0x80 else 0)
+ while g[p] != 0x2C:
+ p += 2
+ while g[p]: p += g[p] + 1
+ p += 1
+ flags = g[p + 9]; p += 10
+ if flags & 0x80: p += 3 << ((flags & 7) + 1)
+ mn = g[p]; p += 1; codes = bytearray()
+ while g[p]: codes += g[p + 1:p + 1 + g[p]]; p += g[p] + 1
+ # Pillow may reduce the palette: decode its own image back for the indexes
+ back = Image.open(io.BytesIO(g)); back.load()
+ out.append(("gif", "%dx%d-%s-%d" % (w, h, kind, ncol), mn, bytes(codes), back.tobytes()))
+ t = io.BytesIO()
+ Image.frombytes("L", (w, h), data).save(t, "TIFF", compression="tiff_lzw", rowsperstrip=h)
+ tb = t.getvalue()
+ le = tb[:2] == b"II"; E = "<" if le else ">"
+ ifd = struct.unpack(E + "I", tb[4:8])[0]; n = struct.unpack(E + "H", tb[ifd:ifd + 2])[0]
+ tags = {}
+ for i in range(n):
+ tag, typ, cnt, val = struct.unpack(E + "HHII", tb[ifd + 2 + i * 12: ifd + 14 + i * 12])
+ if typ == 3 and cnt == 1:
+ val = struct.unpack(E + "H", tb[ifd + 10 + i * 12: ifd + 12 + i * 12])[0]
+ tags[tag] = (val, cnt)
+ assert tags[259][0] == 5 and tags[273][1] == 1, "one LZW strip"
+ off, cnt = tags[273][0], tags[279][0]
+ out.append(("tiff", "%dx%d-%s-%d" % (w, h, kind, ncol), 8, tb[off:off + cnt], data))
+for kind, name, mn, codes, data in out:
+ sys.stdout.buffer.write(struct.pack("<4sB", kind.ljust(4).encode(), len(name)) + name.encode() + struct.pack("HHHH", r, g, b, a)
+ open(W("src.pam"), "wb").write(b"P7\nWIDTH %d\nHEIGHT %d\nDEPTH 4\nMAXVAL 65535\nTUPLTYPE RGB_ALPHA\nENDHDR\n" % (w, h) + bytes(src))
+
+ cases = []
+
+ def ref(path, wide, tol=0, floats=None, name=None):
+ data = open(path, "rb").read()
+ c = {"name": name or os.path.basename(path), "data": data, "tol": tol}
+ info = run(path, "-format", "%w %h", "info:").decode().split()
+ c["width"], c["height"] = int(info[0]), int(info[1])
+ c["rgba8"] = run(path, "-depth", "8", "rgba:-")
+ if wide:
+ c["rgba16"] = run(path, "-depth", "16", "-endian", "MSB", "rgba:-")
+ if floats is not None:
+ c["floats"] = floats
+ cases.append(c)
+
+ variants = [
+ ("p1.pbm", ["-colorspace", "gray", "-threshold", "50%", "-compress", "none"], "pbm:", False),
+ ("p4.pbm", ["-colorspace", "gray", "-threshold", "50%"], "pbm:", False),
+ ("p2.pgm", ["-colorspace", "gray", "-depth", "8", "-compress", "none"], "pgm:", False),
+ ("p5.pgm", ["-colorspace", "gray", "-depth", "8"], "pgm:", False),
+ ("p5-16.pgm", ["-colorspace", "gray", "-depth", "16"], "pgm:", True),
+ ("p2-16.pgm", ["-colorspace", "gray", "-depth", "16", "-compress", "none"], "pgm:", True),
+ ("p3.ppm", ["-alpha", "off", "-depth", "8", "-compress", "none"], "ppm:", False),
+ ("p6.ppm", ["-alpha", "off", "-depth", "8"], "ppm:", False),
+ ("p6-16.ppm", ["-alpha", "off", "-depth", "16"], "ppm:", True),
+ ("p3-16.ppm", ["-alpha", "off", "-depth", "16", "-compress", "none"], "ppm:", True),
+ ("rgba.pam", ["-depth", "8"], "pam:", False),
+ ("rgba16.pam", ["-depth", "16"], "pam:", True),
+ ("rgb.pam", ["-alpha", "off", "-depth", "8"], "pam:", False),
+ ("gray.pam", ["-alpha", "off", "-colorspace", "gray", "-depth", "8"], "pam:", False),
+ ("graya.pam", ["-colorspace", "gray", "-depth", "8"], "pam:", False),
+ ("graya16.pam", ["-colorspace", "gray", "-depth", "16"], "pam:", True),
+ ("bw.pam", ["-alpha", "off", "-colorspace", "gray", "-threshold", "50%", "-type", "bilevel"], "pam:", False),
+ ]
+ for name, args, prefix, wide in variants:
+ run(W("src.pam"), *args, prefix + W(name))
+ ref(W(name), wide)
+ for endian in ("LSB", "MSB"):
+ for col in ("rgb", "gray"):
+ name = "%s-%s.pfm" % (col, endian)
+ extra = ["-colorspace", "gray"] if col == "gray" else []
+ run(W("src.pam"), "-alpha", "off", *extra, "-endian", endian, "pfm:" + W(name))
+ fl = run(W(name), "-depth", "32", "-define", "quantum:format=floating-point", "-endian", "LSB", "rgba:-")
+ ref(W(name), False, tol=1, floats=fl)
+
+ # hand-written edge cases (references from ImageMagick too)
+ def hand(name, data, wide=False, tol=0):
+ open(W(name), "wb").write(data)
+ ref(W(name), wide, tol=tol)
+ hand("comments.ppm", b"P6\n# a comment\n3 # inline\n2\n#another\n255\n" + bytes(range(18)))
+ hand("packed.pbm", b"P1\n5 3\n10101\n01010\n1 1 1 0 0\n")
+ hand("maxval1000.pgm", b"P2\n4 2\n1000\n0 250 500 1000\n999 1 333 750\n", wide=True, tol=1)
+ hand("maxval7.ppm", b"P3 2 2 7 0 1 2 3 4 5 6 7 7 7 0 0\n", tol=1)
+ hand("p4-odd.pbm", b"P4\n11 3\n" + bytes([0b10101010, 0b11100000, 0b00001111, 0b00100000, 0b11111111, 0b11000000]))
+ hand("graya-hand.pam", b"P7\nWIDTH 2\nHEIGHT 2\nDEPTH 2\nMAXVAL 255\nTUPLTYPE GRAYSCALE_ALPHA\nENDHDR\n" + bytes([0, 255, 100, 128, 200, 0, 255, 255]))
+ ctx.emit("pnm", cases)
diff --git a/tools/fixtures/qoi.py b/tools/fixtures/qoi.py
new file mode 100644
index 0000000..9da4391
--- /dev/null
+++ b/tools/fixtures/qoi.py
@@ -0,0 +1,64 @@
+# QOI fixtures (tools/fixtures.py): Pillow's QOI writer and reader.
+# tests/gen/qoi.luau { { name, width, height, mode, pixels (source bytes, RGB or RGBA), data (Pillow's .qoi), crc
+# (CRC-32 of Pillow's RGBA decode) } }
+# tests/gen/qoi_bench.luau { width, height, pixels (RGBA), data }
+import struct
+
+CODE = r'''
+import io, random, struct, sys, zlib
+from PIL import Image
+rng = random.Random(11)
+def make(w, h, mode, kind):
+ n = len(mode)
+ px = bytearray()
+ for y in range(h):
+ for x in range(w):
+ if kind == "noise":
+ v = [rng.randrange(256) for _ in range(n)]
+ elif kind == "grad":
+ v = [(x * 3 + y) % 256, (y * 5) % 256, (x + y * 2) % 256, 255 - (x % 7) * 30][:n]
+ elif kind == "flat":
+ v = [10, 200, 30, 255][:n] if (x // 9 + y // 7) % 2 else [10, 200, 31, 128][:n]
+ else: # small deltas around a walk, with an occasional jump
+ base = (x * 2 + y) % 256
+ v = [(base + rng.randrange(-2, 2)) % 256, (base + rng.randrange(-30, 30)) % 256, (base + rng.randrange(-9, 9)) % 256, 255 if rng.random() < 0.9 else rng.randrange(256)][:n]
+ px += bytes(v)
+ return bytes(px)
+out = []
+for (w, h, mode, kind) in ((1, 1, "RGB", "noise"), (1, 1, "RGBA", "noise"), (3, 2, "RGBA", "grad"), (64, 48, "RGB", "grad"),
+ (64, 48, "RGBA", "grad"), (100, 37, "RGB", "noise"), (100, 37, "RGBA", "noise"),
+ (200, 150, "RGBA", "flat"), (200, 150, "RGB", "flat"), (128, 99, "RGBA", "walk"), (128, 99, "RGB", "walk"),
+ (500, 1, "RGBA", "flat"), (1, 300, "RGB", "walk")):
+ px = make(w, h, mode, kind)
+ im = Image.frombytes(mode, (w, h), px)
+ b = io.BytesIO(); im.save(b, "QOI"); data = b.getvalue()
+ back = Image.open(io.BytesIO(data)).convert("RGBA").tobytes()
+ name = "%dx%d-%s-%s" % (w, h, mode, kind)
+ sys.stdout.buffer.write(struct.pack("> 3) << 10) | ((g >> 3) << 5) | (b >> 3))
+cols = [((i * 40) % 256, (i * 90) % 256, (255 - i * 20) % 256) for i in range(12)]
+w, h = 6, 4
+idx = [(x + y * 2) % 12 for y in range(h) for x in range(w)]
+emit("hand-16bit", hdr(0, 0, 2, 0, 0, 0, w, h, 16, 0) + b"".join(p15(*cols[i]) for i in idx), magick_ref=True)
+emit("hand-15bit-rtl", hdr(0, 0, 2, 0, 0, 0, w, h, 15, 0x10) + b"".join(p15(*cols[i], a=0) for i in idx), magick_ref=True)
+emit("hand-cmap16", hdr(0, 1, 1, 0, 12, 16, w, h, 8, 0x20) + b"".join(p15(*c) for c in cols) + bytes(idx), magick_ref=True)
+emit("hand-cmap32-first", hdr(0, 1, 1, 4, 12, 32, w, h, 8, 0x28) + b"".join(bytes((c[2], c[1], c[0], 77)) for c in cols) + bytes(i + 4 for i in idx))
+emit("hand-cmap24-rle", hdr(0, 1, 9, 0, 12, 24, w, h, 8, 0) + b"".join(bytes((c[2], c[1], c[0])) for c in cols) + bytes([0x80 + 9, 3, 0x05, 1, 2, 3, 4, 5, 6, 0x80 + 7, 11]))
+emit("hand-id-top", hdr(5, 0, 3, 0, 0, 0, w, h, 8, 0x20) + b"hello" + bytes((i * 21) % 256 for i in idx))
+emit("hand-graya16", hdr(0, 0, 3, 0, 0, 0, w, h, 16, 0x28) + b"".join(bytes(((i * 21) % 256, (i * 50) % 256)) for i in idx))
+emit("hand-rle32-cross", hdr(0, 0, 10, 0, 0, 0, 5, 3, 32, 0x28) + bytes([0x80 + 6, 1, 2, 3, 200, 0x08]) + bytes(range(9 * 4)))
+for name, data, size, rgba in out:
+ sys.stdout.buffer.write(struct.pack("> 4).astype(np.uint8), photometric="minisblack", bitspersample=4)
+tw("gray2_lzw", (gray8 >> 6).astype(np.uint8), photometric="minisblack", bitspersample=2, compression=None)
+tw("bilevel", gray8 > 127, photometric="minisblack")
+tw("bilevel_white_packbits", gray8 > 100, photometric="miniswhite", compression="packbits")
+tw("gray12", (gray16 >> 4).astype(np.uint16), photometric="minisblack", bitspersample=12)
+tw("cmyk8", ramp(255, 4).astype(np.uint8), photometric="separated", compression="lzw")
+tw("graya8", np.stack([gray8, rgba8[:, :, 3]], -1), photometric="minisblack", extrasamples=["unassalpha"])
+with tifffile.TiffWriter(os.path.join(work, "pages3.tif")) as t:
+ t.write(rgb8, photometric="rgb", compression="zlib")
+ t.write(gray16, photometric="minisblack", compression="lzw")
+ t.write(rgba8, photometric="rgb", extrasamples=["unassalpha"])
+add("pages3", os.path.join(work, "pages3.tif"))
+# ImageMagick
+import subprocess
+src = os.path.join(work, "src.png")
+from PIL import Image
+Image.fromarray(rgba8, "RGBA").save(src)
+srgb = os.path.join(work, "srgb.png")
+Image.fromarray(rgb8, "RGB").save(srgb)
+def im(name, *args, s=srgb):
+ p = os.path.join(work, name + ".tif")
+ subprocess.run([magick, s] + list(args) + [p], check=True, capture_output=True)
+ add(name, p)
+im("im_lzw", "-compress", "LZW")
+im("im_zip_pred", "-compress", "Zip", "-define", "tiff:predictor=2")
+im("im_rle", "-compress", "RLE")
+im("im_none_msb", "-compress", "None", "-endian", "MSB")
+im("im_tiles", "-compress", "LZW", "-define", "tiff:tile-geometry=32x32")
+im("im_plane", "-compress", "Zip", "-interlace", "plane")
+im("im_16", "-depth", "16", "-compress", "LZW")
+im("im_float", "-depth", "32", "-define", "quantum:format=floating-point", "-compress", "Zip")
+im("im_alpha", "-compress", "LZW", s=src)
+im("im_alpha_assoc", "-define", "tiff:alpha=associated", s=src)
+im("im_gray4", "-colorspace", "gray", "-depth", "4")
+im("im_bilevel", "-monochrome")
+im("im_palette", "-type", "palette", "-compress", "LZW")
+im("im_palette4", "-colors", "12", "-type", "palette", "-depth", "4")
+im("im_cmyk", "-colorspace", "CMYK", "-compress", "LZW")
+p = os.path.join(work, "im_multi.tif")
+subprocess.run([magick, srgb, src, srgb, "-compress", "Zip", p], check=True, capture_output=True)
+add("im_multi", p)
+jp = os.path.join(work, "im_jpeg.tif")
+subprocess.run([magick, srgb, "-compress", "JPEG", jp], check=True, capture_output=True)
+
+def expect(page):
+ a = page.asarray()
+ spp = page.samplesperpixel
+ if spp > 1 and page.planarconfig == 2:
+ a = np.moveaxis(a, 0, -1)
+ if a.ndim == 2:
+ a = a[:, :, None]
+ a = a.reshape(page.imagelength, page.imagewidth, spp)
+ photo = int(page.photometric)
+ bps = page.bitspersample
+ fmt = int(page.sampleformat)
+ cc = 3 if photo in (2, 6) else (4 if photo == 5 else 1)
+ alpha = cc if spp > cc else -1
+ ex = page.extrasamples
+ assoc = alpha >= 0 and len(ex) > 0 and int(ex[0]) == 1
+ maxv = float(2 ** min(bps, 32) - 1)
+ if fmt == 3:
+ u = a.astype(np.float64)
+ elif fmt == 2:
+ u = (a.astype(np.float64) + 2 ** (bps - 1)) / maxv
+ else:
+ u = a.astype(np.float64) / maxv
+ if photo == 3:
+ cmap = page.colormap.astype(np.float64) / 65535.0
+ idx = a[:, :, 0].astype(np.int64)
+ rgb = np.stack([cmap[0][idx], cmap[1][idx], cmap[2][idx]], -1)
+ elif photo == 2:
+ rgb = u[:, :, 0:3]
+ elif photo == 5:
+ c, m, y, k = u[:, :, 0], u[:, :, 1], u[:, :, 2], u[:, :, 3]
+ rgb = np.stack([(1 - c) * (1 - k), (1 - m) * (1 - k), (1 - y) * (1 - k)], -1)
+ else:
+ v = u[:, :, 0]
+ if photo == 0:
+ v = 1 - v
+ rgb = np.stack([v, v, v], -1)
+ if alpha >= 0:
+ al = u[:, :, alpha]
+ if assoc:
+ safe = np.where(al > 0, al, 1)
+ rgb = np.where((al > 0)[:, :, None], np.minimum(rgb / safe[:, :, None], 1), 0)
+ else:
+ al = np.ones(rgb.shape[:2])
+ def q(x, m):
+ return np.floor(np.clip(np.nan_to_num(x), 0, 1) * m + 0.5)
+ rgba = np.concatenate([rgb, al[:, :, None]], -1)
+ out8 = q(rgba, 255).astype(np.uint8)
+ crc = zlib.crc32(out8.tobytes())
+ # native
+ if photo in (3, 5):
+ kind, nat = "rgba8", out8
+ elif fmt == 3:
+ kind, nat = "rgbaf32", rgba.astype("= 0:
+ if bps <= 8:
+ kind, nat = "graya8", q(np.stack([rgb[:, :, 0], al], -1), 255).astype(np.uint8)
+ else:
+ kind, nat = "rgba16", q(rgba, 65535).astype("= 0 else ("rgb8", out8[:, :, 0:3].copy())
+ else:
+ kind, nat = "rgba16", q(rgba, 65535).astype("