From 692ef055de4ef643a708b96b1c46ca65139007d9 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 08:44:15 -0500 Subject: [PATCH] imgA: image/jpeg (absorbed jpeg-luau decoder + arithmetic coding, meta, EXIF orientation, encoder byte-identical to cjpeg) and codecs/Dct - codecs/Dct: jpeg-luau's islow / reduced IDCTs + a forward islow DCT with jcdctmgr.c's quantiser; tests/codecs/dct.luau - image/jpeg: Decode (marker parser, absorbed + reader ranges, SOF9/SOF10 + DAC, EXIF / ICC / COM / JFIF density), Scan + Color (absorbed), Arith (jdarith.c port), Encode (baseline / optimised / progressive, 444/422/420, restarts, APP1/APP2/COM from meta), Tables (annex K) - tests: 115 cjpeg/jpegtran/Pillow files, 444 decodes bit-exact with djpeg at 1, 1/2, 1/4, 1/8 (104 arithmetic), 38 encodes byte-identical to cjpeg (so djpeg decodes them), orientation, meta, truncation, fuzz - licenses: libjpeg-turbo LICENSE + README.ijg, NOTICE rows - tools/bench.luau: jpeg block; tools/bench.sh runs every fixture generator (bench blocks read their outputs) --- dbg.luau | 25 + docs/FORMATS.md | 2 + licenses/NOTICE.md | 2 + licenses/libjpeg-README.ijg | 260 +++++++++ licenses/libjpeg-turbo-LICENSE.md | 147 +++++ src/Formats/Registry.luau | 12 + src/Formats/codecs/Dct/init.luau | 392 +++++++++++++ src/Formats/image/jpeg/Arith.luau | 414 ++++++++++++++ src/Formats/image/jpeg/Color.luau | 229 ++++++++ src/Formats/image/jpeg/Decode.luau | 666 ++++++++++++++++++++++ src/Formats/image/jpeg/Encode.luau | 883 +++++++++++++++++++++++++++++ src/Formats/image/jpeg/Scan.luau | 456 +++++++++++++++ src/Formats/image/jpeg/Tables.luau | 77 +++ src/Formats/image/jpeg/init.luau | 277 +++++++++ tests/codecs/dct.luau | 158 ++++++ tests/image/jpeg.luau | 293 ++++++++++ tools/bench.luau | 26 + tools/bench.sh | 2 +- tools/fixtures/jpeg.py | 293 ++++++++++ 19 files changed, 4613 insertions(+), 1 deletion(-) create mode 100644 dbg.luau create mode 100644 licenses/libjpeg-README.ijg create mode 100644 licenses/libjpeg-turbo-LICENSE.md create mode 100644 src/Formats/codecs/Dct/init.luau create mode 100644 src/Formats/image/jpeg/Arith.luau create mode 100644 src/Formats/image/jpeg/Color.luau create mode 100644 src/Formats/image/jpeg/Decode.luau create mode 100644 src/Formats/image/jpeg/Encode.luau create mode 100644 src/Formats/image/jpeg/Scan.luau create mode 100644 src/Formats/image/jpeg/Tables.luau create mode 100644 src/Formats/image/jpeg/init.luau create mode 100644 tests/codecs/dct.luau create mode 100644 tests/image/jpeg.luau create mode 100644 tools/fixtures/jpeg.py diff --git a/dbg.luau b/dbg.luau new file mode 100644 index 0000000..badfb0c --- /dev/null +++ b/dbg.luau @@ -0,0 +1,25 @@ +local Jpeg = require("@formats/image/jpeg") +local Types = require("@formats/Types") +local Enc = require("@tests/gen/jpeg_enc") +for _, c in Enc do + if c.name == "photo_444_prog" then + local img = Types.Image.new(c.width, c.height, c.format) + buffer.writestring(img.pixels, 0, c.pixels) + local out = buffer.tostring(Jpeg.encode(img, c.opts)) + -- list SOS offsets in both + for _, s in { out, c.want } do + local marks = {} + local i = 1 + while i < #s do + if s:byte(i) == 255 and s:byte(i+1) ~= 0 and s:byte(i+1) ~= 255 then + table.insert(marks, string.format("%x@%d", s:byte(i+1), i - 1)) + end + i += 1 + end + print(table.concat(marks, " ")) + end + local diffs = 0 + for i = 1, #out do if out:byte(i) ~= c.want:byte(i) then diffs += 1 end end + print("diff bytes", diffs) + end +end diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 17d4818..68a0199 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -5,9 +5,11 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | Category | Format | Extensions | Read | Write | Capabilities | Test | |---|---|---|---|---|---|---| +| 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: false, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` | Codecs (layer 1, shared by formats; not loadable on their own): +- codecs/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/Lzw: LZW decoder and encoder in the two variants file formats use. A codec (layer 1): image/gif and diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index 5d28e73..ccfd243 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -4,6 +4,8 @@ |---|---|---| | `src/Formats/codecs/Deflate/` (Inflate, init), `src/Formats/core/Crc32.luau`, `src/Formats/core/Adler32.luau`, `src/Formats/core/Huffman.luau` (table builder) | deflate-luau 1.0.0 (same author), written from RFC 1950-1952 | no licence chosen yet; no third-party code: [deflate-luau-NOTICE.txt](deflate-luau-NOTICE.txt) | | `src/Formats/image/png/` (init, Decode) | png-luau 1.0.0 (same author), written from the PNG specification | no licence chosen yet; no third-party code | +| `src/Formats/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 ba09f70..1cdd331 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -14,6 +14,18 @@ export type Entry = { } local list: { Entry } = { + { + 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", diff --git a/src/Formats/codecs/Dct/init.luau b/src/Formats/codecs/Dct/init.luau new file mode 100644 index 0000000..8adc3fe --- /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, d1, d2, d3, d4, d5, d6, d7 + 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/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..210a273 --- /dev/null +++ b/src/Formats/image/jpeg/init.luau @@ -0,0 +1,277 @@ +--!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) + 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 + 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/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/image/jpeg.luau b/tests/image/jpeg.luau new file mode 100644 index 0000000..964dc51 --- /dev/null +++ b/tests/image/jpeg.luau @@ -0,0 +1,293 @@ +-- 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") + 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/tools/bench.luau b/tools/bench.luau index 9f6aef7..81ee5a1 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -56,3 +56,29 @@ do Png.encode(img) end) end + +-- ------------------------------------------------------------------------------------------------ jpeg (ws-imgA) +do + local Jpeg = require("@formats/image/jpeg") + local Types = require("@formats/Types") + local JB = require("@tests/gen/jpeg_bench") + for _, c in JB.files do + local b = buffer.fromstring(c.data) + local img = Jpeg.decode(Bytes.reader(b)) + assert(img and Crc32.of(img.pixels) == c.crc, "jpeg bench: " .. c.name .. " does not match djpeg") + bench("jpeg decode " .. c.name, 3, c.width * c.height * 4, function() + Jpeg.decode(Bytes.reader(b)) + end) + end + local b0 = buffer.fromstring(JB.files[1].data) + bench("jpeg decode 1/8 (DC only)", 3, JB.width * JB.height * 4, function() + Jpeg.decode(Bytes.reader(b0), { scale = 8 }) + end) + local src = Types.Image.new(JB.width, JB.height, "rgb8") + buffer.writestring(src.pixels, 0, JB.rgb) + for _, o in { { label = "baseline 4:2:0 q85", quality = 85 }, { label = "progressive 4:2:0 q85", quality = 85, progressive = true }, { label = "baseline 4:4:4 q85 optimized", quality = 85, subsampling = "444", optimize = true } } do + bench("jpeg encode " .. o.label, 2, JB.width * JB.height * 3, function() + Jpeg.encode(src, o :: any) + end) + end +end diff --git a/tools/bench.sh b/tools/bench.sh index c5dea4a..9d59295 100644 --- a/tools/bench.sh +++ b/tools/bench.sh @@ -3,7 +3,7 @@ cd "$(dirname "$0")/.." || exit 1 LUAU=${LUAU:-$(command -v luau || nix shell nixpkgs#luau -c sh -c 'command -v luau')} LUAJIT=${LUAJIT:-$(command -v luajit || nix shell nixpkgs#luajit -c sh -c 'command -v luajit')} -python3 -I tools/fixtures.py deflate png > /dev/null || exit 1 +python3 -I tools/fixtures.py > /dev/null || exit 1 # every generator (up-to-date ones are skipped): the bench blocks read their outputs python3 -I tools/build.py luajit > /dev/null || exit 1 "$LUAU" --codegen -O2 tools/bench.luau "$LUAJIT" -e 'package.path = "build/luajit/?.lua;build/luajit/?/init.lua;" .. package.path' build/luajit/tools/bench.lua diff --git a/tools/fixtures/jpeg.py b/tools/fixtures/jpeg.py new file mode 100644 index 0000000..fd71fd1 --- /dev/null +++ b/tools/fixtures/jpeg.py @@ -0,0 +1,293 @@ +# JPEG fixtures (tools/fixtures.py), against libjpeg-turbo's cjpeg / djpeg / jpegtran (nix libjpeg_turbo) and Pillow. +# Ported from jpeg-luau tools/fixtures.py; the TMDB test photos are replaced by ImageMagick's built-in images. +# tests/gen/jpeg_dec.luau { { name, data, err?, refs = { { scale, width, height, crc } } | cmyk = rgb bytes } }: +# cjpeg encodes of synthetic and photo-like sources at every quality / sampling / +# progression / restart / colour setting, arithmetic-coded (sequential, progressive, +# restarts, grey, 12-bit), jpegtran transcodes, stripped DHT, odd sizes, 12-bit, CMYK / +# YCCK (Pillow); references = djpeg -dct int decodes at 1, 1/2, 1/4, 1/8 (CRC-32 of the +# RGBA8 pixels), files that must be refused (lossless). +# tests/gen/jpeg_enc.luau { { name, width, height, format, pixels, opts, want } }: raw sources and what cjpeg writes +# for the same settings (our encoder must produce the same bytes). +# tests/gen/jpeg_bench.luau 1024 x 768 baseline / progressive / arithmetic files for tools/bench.luau. +import os, shutil, subprocess, tempfile, zlib + +SOURCES = r''' +import os, random, sys +from PIL import Image, ImageDraw +out = sys.argv[1] +def synth(w, h, seed): + rnd = random.Random(seed) + im = Image.new("RGB", (w, h)) + px = im.load() + for y in range(h): + for x in range(w): + px[x, y] = ((x * 255) // max(1, w - 1), (y * 255) // max(1, h - 1), ((x + y) * 7) % 256) + d = ImageDraw.Draw(im) + for _ in range(6): + x0, y0 = rnd.randrange(w), rnd.randrange(h) + x1, y1 = x0 + rnd.randrange(1, w // 2 + 2), y0 + rnd.randrange(1, h // 2 + 2) + col = (rnd.randrange(256), rnd.randrange(256), rnd.randrange(256)) + if rnd.random() < 0.5: + d.ellipse([x0, y0, x1, y1], fill=col) + else: + d.line([x0, y0, x1, y1], fill=col, width=rnd.randrange(1, 4)) + for _ in range(w * h // 20): + x, y = rnd.randrange(w), rnd.randrange(h) + px[x, y] = (rnd.randrange(256), rnd.randrange(256), rnd.randrange(256)) + return im +synth(97, 71, 1).save(os.path.join(out, "synth.ppm")) +for w, h in ((1, 1), (7, 5), (17, 9), (33, 1), (1, 33), (16, 16)): + synth(w, h, w * 100 + h).save(os.path.join(out, "s%dx%d.ppm" % (w, h))) +photo = Image.open(os.path.join(out, "photo.ppm")).convert("RGB") +photo.convert("L").save(os.path.join(out, "photo.pgm")) +with open(os.path.join(out, "photo16.ppm"), "wb") as f: + f.write(b"P6\n160 120\n65535\n") + f.write(bytes(b for v in photo.tobytes() for b in ((v * 257) >> 8, (v * 257) & 255))) +cmyk = photo.convert("CMYK") +for name, kw in (("cmyk", {}), ("cmyk_prog", {"progressive": True})): + p = os.path.join(out, "photo_" + name + ".jpg") + cmyk.save(p, "JPEG", quality=90, **kw) + data = bytearray(open(p, "rb").read()) + i = data.find(b"Adobe") + assert i > 0 + data[i + 11] = 2 + open(os.path.join(out, "photo_" + name.replace("cmyk", "ycck") + ".jpg"), "wb").write(data) + for n in (name, name.replace("cmyk", "ycck")): + im = Image.open(os.path.join(out, "photo_" + n + ".jpg")) + raw = im.tobytes() + rgb = bytearray() + for k in range(0, len(raw), 4): + c, m, y, kk = raw[k:k + 4] + kk = 255 - kk + rgb += bytes((((255 - c) * kk + 127) // 255, ((255 - m) * kk + 127) // 255, ((255 - y) * kk + 127) // 255)) + open(os.path.join(out, "photo_" + n + ".ref"), "wb").write(rgb) +''' + +SCANS = { + "spectral": "0,1,2: 0-0, 0, 0;\n0: 1-5, 0, 0;\n0: 6-63, 0, 0;\n1: 1-63, 0, 0;\n2: 1-63, 0, 0;\n", + "deepsa": ( + "0,1,2: 0-0, 0, 2;\n0: 1-5, 0, 3;\n1: 1-63, 0, 1;\n2: 1-63, 0, 1;\n0: 6-63, 0, 3;\n" + "0: 1-63, 3, 2;\n0: 1-63, 2, 1;\n0: 1-63, 1, 0;\n1: 1-63, 1, 0;\n2: 1-63, 1, 0;\n" + "0,1,2: 0-0, 2, 1;\n0,1,2: 0-0, 1, 0;\n" + ), + "seqsplit": "0: 0-63, 0, 0;\n1: 0-63, 0, 0;\n2: 0-63, 0, 0;\n", + "dcsplit": "0: 0-0, 0, 0;\n1: 0-0, 0, 0;\n2: 0-0, 0, 0;\n0: 1-63, 0, 0;\n1: 1-63, 0, 0;\n2: 1-63, 0, 0;\n", +} +SAMPLINGS = {"444": "1x1", "422": "2x1", "420": "2x2", "411": "4x1", "440": "1x2"} + + +def parse_pnm(data): + """P5 / P6 -> w, h, RGB8 bytes (16-bit samples scaled as djpeg's 12-bit output)""" + fields, pos = [], 0 + while len(fields) < 4: + while data[pos:pos + 1].isspace(): + pos += 1 + if data[pos:pos + 1] == b"#": + while data[pos:pos + 1] != b"\n": + pos += 1 + continue + s = pos + while not data[pos:pos + 1].isspace(): + pos += 1 + fields.append(data[s:pos]) + pos += 1 + magic, w, h, mx = fields[0], int(fields[1]), int(fields[2]), int(fields[3]) + ch = 3 if magic == b"P6" else 1 + n = w * h * ch + if mx < 256: + px = data[pos:pos + n] + else: + raw = data[pos:pos + 2 * n] + px = bytes(((raw[2 * i] << 8 | raw[2 * i + 1]) * 255 + mx // 2) // mx for i in range(n)) + if ch == 1: + px = bytes(v for v in px for _ in range(3)) + return w, h, px + + +def rgba_crc(rgb): + out = bytearray(len(rgb) // 3 * 4) + out[0::4], out[1::4], out[2::4] = rgb[0::3], rgb[1::3], rgb[2::3] + out[3::4] = b"\xff" * (len(rgb) // 3) + return zlib.crc32(bytes(out)) + + +def generate(ctx): + bindir = os.path.dirname(ctx.nix("libjpeg_turbo", ["sh", "-c", "command -v cjpeg"]).decode().strip()) + magick = ctx.nix("imagemagick", ["sh", "-c", "command -v magick"]).decode().strip() + work = tempfile.mkdtemp(prefix="formats-jpeg-") + try: + _generate(ctx, bindir, magick, work) + finally: + shutil.rmtree(work, ignore_errors=True) + + +def _generate(ctx, bindir, magick, work): + def run(tool, *args): + exe = tool if os.path.isabs(tool) else os.path.join(bindir, tool) + r = subprocess.run([exe] + list(args), capture_output=True) + if r.returncode != 0: + raise SystemExit("fixtures/jpeg: %s %s failed: %s" % (tool, " ".join(args), r.stderr.decode())) + return r.stdout + + W = lambda n: os.path.join(work, n) + # photo-like sources: ImageMagick's built-in rose, and a plasma fractal + run(magick, "rose:", "-resize", "160x120!", W("photo.ppm")) + run(magick, "-size", "1024x768", "-seed", "7", "plasma:fractal", "-blur", "0x1", W("big.ppm")) + ctx.python(["pillow"], SOURCES.replace("sys.argv[1]", repr(work))) + for k, v in SCANS.items(): + with open(W(k + ".scans"), "w") as f: + f.write(v) + SRC = {"synth": W("synth.ppm"), "photo": W("photo.ppm"), "gray": W("photo.pgm"), "photo16": W("photo16.ppm")} + for w, h in ((1, 1), (7, 5), (17, 9), (33, 1), (1, 33), (16, 16)): + SRC["%dx%d" % (w, h)] = W("s%dx%d.ppm" % (w, h)) + + cases = [] # (name, path, scales | "cmyk", err) + + def cj(name, src, *args, scales=(1, 2, 4, 8), err=None): + out = W(name + ".jpg") + run("cjpeg", *args, "-outfile", out, SRC[src]) + cases.append((name, out, scales, err)) + + for q in (30, 90): + for sn, s in SAMPLINGS.items(): + cj("photo_q%d_%s" % (q, sn), "photo", "-quality", str(q), "-sample", s) + cj("photo_q%d_%s_prog" % (q, sn), "photo", "-quality", str(q), "-sample", s, "-progressive") + for sn, s in SAMPLINGS.items(): + cj("synth_q75_%s" % sn, "synth", "-quality", "75", "-sample", s) + cj("synth_q75_%s_prog" % sn, "synth", "-quality", "75", "-sample", s, "-progressive") + cj("photo_q100_420", "photo", "-quality", "100", "-sample", "2x2") + cj("photo_q100_420_prog", "photo", "-quality", "100", "-sample", "2x2", "-progressive") + cj("photo_q5_420", "photo", "-quality", "5", "-sample", "2x2") + cj("photo_q5_444_prog", "photo", "-quality", "5", "-sample", "1x1", "-progressive") + cj("photo_optimize", "photo", "-quality", "80", "-optimize") + cj("photo_s31", "photo", "-sample", "3x1,1x1,1x1") + cj("photo_s4242", "photo", "-sample", "4x2,1x1,1x1") + cj("photo_s222111", "photo", "-sample", "2x2,2x1,1x1") + cj("photo_s111222", "photo", "-sample", "1x1,2x2,2x2") + cj("photo_s1422", "photo", "-sample", "1x4,1x2,1x2", "-progressive") + cj("synth_s2222", "synth", "-sample", "2x2,2x2,2x2", "-scans", W("seqsplit.scans")) + cj("photo_rst1", "photo", "-sample", "2x2", "-restart", "1") + cj("photo_rst3b", "photo", "-sample", "2x2", "-restart", "3B") + cj("photo_rst1b_prog", "photo", "-sample", "2x2", "-restart", "1B", "-progressive") + cj("photo_rst2_prog444", "photo", "-sample", "1x1", "-restart", "2", "-progressive") + cj("photo_gray", "photo", "-grayscale") + cj("photo_gray_prog", "photo", "-grayscale", "-progressive") + cj("photo_gray_rst", "photo", "-grayscale", "-restart", "5B") + cj("photo_rgb", "photo", "-rgb") + cj("photo_rgb_prog", "photo", "-rgb", "-progressive") + for k in SCANS: + cj("photo_scans_" + k, "photo", "-sample", "2x2", "-scans", W(k + ".scans")) + cj("synth_scans_" + k, "synth", "-sample", "1x1", "-scans", W(k + ".scans")) + cj("photo_12bit_420", "photo16", "-precision", "12", "-sample", "2x2") + cj("photo_12bit_444_prog", "photo16", "-precision", "12", "-sample", "1x1", "-progressive") + cj("photo_12bit_gray", "photo16", "-precision", "12", "-grayscale") + for k in ("1x1", "7x5", "17x9", "33x1", "1x33", "16x16"): + cj("tiny_%s_420" % k, k, "-sample", "2x2") + cj("tiny_%s_422_prog" % k, k, "-sample", "2x1", "-progressive") + cj("tiny_%s_444" % k, k, "-sample", "1x1", "-quality", "95") + cj("tiny_%s_arith" % k, k, "-sample", "2x2", "-arithmetic") + # arithmetic coding + for sn in ("444", "420", "422"): + cj("photo_arith_%s" % sn, "photo", "-arithmetic", "-sample", SAMPLINGS[sn]) + cj("photo_arith_%s_prog" % sn, "photo", "-arithmetic", "-progressive", "-sample", SAMPLINGS[sn]) + cj("photo_arith_q5", "photo", "-arithmetic", "-quality", "5") + cj("photo_arith_q100_prog", "photo", "-arithmetic", "-progressive", "-quality", "100") + cj("photo_arith_rst", "photo", "-arithmetic", "-restart", "1") + cj("photo_arith_rst_prog", "photo", "-arithmetic", "-progressive", "-restart", "3B") + cj("photo_arith_gray", "photo", "-arithmetic", "-grayscale") + cj("photo_arith_gray_prog", "photo", "-arithmetic", "-grayscale", "-progressive") + cj("photo_arith_rgb", "photo", "-arithmetic", "-rgb") + cj("photo_arith_12bit", "photo16", "-arithmetic", "-precision", "12", "-sample", "2x2") + cj("photo_arith_12bit_prog", "photo16", "-arithmetic", "-precision", "12", "-progressive") + cj("synth_arith_deepsa", "synth", "-arithmetic", "-sample", "1x1", "-scans", W("deepsa.scans")) + cj("synth_arith_spectral", "synth", "-arithmetic", "-sample", "2x2", "-scans", W("spectral.scans")) + cj("synth_arith_seqsplit", "synth", "-arithmetic", "-sample", "2x2", "-scans", W("seqsplit.scans")) + # refused + cj("photo_lossless", "photo", "-lossless", "1", scales=(), err="lossless") + + base = W("photo_q90_420.jpg") + for name, args in (("tran_prog", ["-progressive"]), ("tran_rst", ["-restart", "2B"]), ("tran_optimize", ["-optimize"]), + ("tran_arith", ["-arithmetic"]), ("tran_arith_prog", ["-arithmetic", "-progressive"])): + out = W("photo_" + name + ".jpg") + run("jpegtran", *args, "-outfile", out, base) + cases.append(("photo_" + name, out, (1, 2, 4, 8), None)) + # an arithmetic file back to Huffman + out = W("photo_tran_unarith.jpg") + run("jpegtran", "-outfile", out, W("photo_arith_420.jpg")) + cases.append(("photo_tran_unarith", out, (1, 2, 4, 8), None)) + + # stripped DHT: the standard tables + data = open(base, "rb").read() + out, pos = bytearray(data[:2]), 2 + while pos < len(data): + m = data[pos + 1] + if m == 0xDA: + out += data[pos:] + break + ln = (data[pos + 2] << 8) | data[pos + 3] + if m != 0xC4: + out += data[pos:pos + 2 + ln] + pos += 2 + ln + open(W("photo_nodht.jpg"), "wb").write(bytes(out)) + cases.append(("photo_nodht", W("photo_nodht.jpg"), (1, 2, 4, 8), None)) + for n in ("cmyk", "cmyk_prog", "ycck", "ycck_prog"): + cases.append(("photo_" + n, W("photo_" + n + ".jpg"), "cmyk", None)) + + dec = [] + for name, path, scales, err in cases: + e = {"name": name, "data": open(path, "rb").read()} + if err: + e["err"] = err + if scales == "cmyk": + e["cmyk"] = open(path[:-4] + ".ref", "rb").read() + else: + refs = [] + for s in scales: + args = ["-dct", "int", "-pnm"] + (["-scale", "1/%d" % s] if s != 1 else []) + [path] + w, h, px = parse_pnm(run("djpeg", *args)) + refs.append({"scale": s, "width": w, "height": h, "crc": rgba_crc(px)}) + e["refs"] = refs + dec.append(e) + ctx.emit("jpeg_dec", dec) + + # encoder: cjpeg's bytes for the same settings + enc = [] + + def ce(name, src, fmt, opts, *args): + out = W("enc_" + name + ".jpg") + run("cjpeg", "-baseline", *args, "-outfile", out, SRC[src]) + w, h, px = parse_pnm(open(SRC[src], "rb").read()) + if fmt == "gray8": + px = px[0::3] + enc.append({"name": name, "width": w, "height": h, "format": fmt, "pixels": px, "opts": opts, + "want": open(out, "rb").read()}) + + for q in (10, 50, 75, 90, 100): + ce("photo_q%d_420" % q, "photo", "rgb8", {"quality": q}, "-quality", str(q), "-sample", "2x2") + for sn in ("444", "422", "420"): + ce("photo_%s" % sn, "photo", "rgb8", {"quality": 85, "subsampling": sn}, "-quality", "85", "-sample", SAMPLINGS[sn]) + ce("synth_%s" % sn, "synth", "rgb8", {"quality": 85, "subsampling": sn}, "-quality", "85", "-sample", SAMPLINGS[sn]) + ce("photo_%s_prog" % sn, "photo", "rgb8", {"quality": 85, "subsampling": sn, "progressive": True}, "-quality", "85", "-sample", SAMPLINGS[sn], "-progressive") + ce("synth_%s_prog" % sn, "synth", "rgb8", {"quality": 85, "subsampling": sn, "progressive": True}, "-quality", "85", "-sample", SAMPLINGS[sn], "-progressive") + ce("photo_%s_opt" % sn, "photo", "rgb8", {"quality": 85, "subsampling": sn, "optimize": True}, "-quality", "85", "-sample", SAMPLINGS[sn], "-optimize") + ce("photo_gray", "gray", "gray8", {"quality": 80}, "-quality", "80") + ce("photo_gray_prog", "gray", "gray8", {"quality": 80, "progressive": True}, "-quality", "80", "-progressive") + ce("photo_rgb_to_gray", "photo", "rgb8", {"quality": 80, "gray": True}, "-quality", "80", "-grayscale") + ce("photo_rst", "photo", "rgb8", {"quality": 75, "restart": 3}, "-quality", "75", "-sample", "2x2", "-restart", "3B") + ce("photo_rst_prog", "photo", "rgb8", {"quality": 75, "restart": 2, "progressive": True}, "-quality", "75", "-sample", "2x2", "-restart", "2B", "-progressive") + ce("photo_q100_prog444", "photo", "rgb8", {"quality": 100, "subsampling": "444", "progressive": True}, "-quality", "100", "-sample", "1x1", "-progressive") + for k in ("1x1", "7x5", "17x9", "33x1", "1x33", "16x16"): + ce("tiny_%s_420" % k, k, "rgb8", {"quality": 90}, "-quality", "90", "-sample", "2x2") + ce("tiny_%s_422_prog" % k, k, "rgb8", {"quality": 90, "subsampling": "422", "progressive": True}, "-quality", "90", "-sample", "2x1", "-progressive") + ctx.emit("jpeg_enc", enc) + + SRC["big"] = W("big.ppm") + bench = [] + for name, args in (("baseline 4:2:0", ["-sample", "2x2"]), ("progressive 4:2:0", ["-sample", "2x2", "-progressive"]), + ("arithmetic 4:2:0", ["-sample", "2x2", "-arithmetic"]), ("baseline 4:4:4", ["-sample", "1x1"])): + out = W("bench.jpg") + run("cjpeg", "-quality", "85", *args, "-outfile", out, SRC["big"]) + w, h, px = parse_pnm(run("djpeg", "-dct", "int", "-pnm", out)) + bench.append({"name": name, "width": w, "height": h, "data": open(out, "rb").read(), "crc": rgba_crc(px)}) + w, h, px = parse_pnm(open(SRC["big"], "rb").read()) + ctx.emit("jpeg_bench", {"files": bench, "width": w, "height": h, "rgb": px})