From 2ca0d1f10a68e7e17db6d743b9100f38257849e7 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:28:38 -0500 Subject: [PATCH] ws-video-codecs: codecs/Jpeg (the JPEG engine moved down from image/jpeg; byte-range API, yuv420p decode / encode, AVI1 fields); image/jpeg is a thin format over it --- docs/FORMATS.md | 1 + licenses/NOTICE.md | 4 +- src/Formats/Registry.luau | 2 +- .../{image/jpeg => codecs/Jpeg}/Arith.luau | 2 +- .../{image/jpeg => codecs/Jpeg}/Color.luau | 2 +- .../{image/jpeg => codecs/Jpeg}/Decode.luau | 90 +++- .../{image/jpeg => codecs/Jpeg}/Encode.luau | 36 +- .../{image/jpeg => codecs/Jpeg}/Scan.luau | 2 +- .../{image/jpeg => codecs/Jpeg}/Tables.luau | 2 +- src/Formats/codecs/Jpeg/Yuv.luau | 76 ++++ src/Formats/codecs/Jpeg/init.luau | 386 ++++++++++++++++++ src/Formats/image/jpeg/init.luau | 286 ++++--------- 12 files changed, 653 insertions(+), 236 deletions(-) rename src/Formats/{image/jpeg => codecs/Jpeg}/Arith.luau (99%) rename src/Formats/{image/jpeg => codecs/Jpeg}/Color.luau (98%) rename src/Formats/{image/jpeg => codecs/Jpeg}/Decode.luau (83%) rename src/Formats/{image/jpeg => codecs/Jpeg}/Encode.luau (93%) rename src/Formats/{image/jpeg => codecs/Jpeg}/Scan.luau (99%) rename src/Formats/{image/jpeg => codecs/Jpeg}/Tables.luau (96%) create mode 100644 src/Formats/codecs/Jpeg/Yuv.luau create mode 100644 src/Formats/codecs/Jpeg/init.luau diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 40e275f..c5f7b88 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -67,6 +67,7 @@ Codecs (layer 1, shared by formats; not loadable on their own): - codecs/Cff: Compact Font Format (Adobe TN #5176) and Type 2 charstrings (TN #5177): the outlines of OpenType fonts - codecs/Dct: the 8x8 DCTs JPEG, Motion-JPEG and MPEG-1 share (native; never throws). - codecs/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers. +- codecs/Jpeg: the JPEG codec (ITU T.81) on byte ranges: image/jpeg is a thin format over it, and the Motion-JPEG - codecs/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code. - codecs/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. A codec (layer 3): - codecs/Lzw: LZW decoder and encoder in the two variants file formats use. A codec (layer 1): image/gif and diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index dab5523..75c8972 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -17,8 +17,8 @@ | `tests/fixtures/bmpsuite/` | BMP Suite 2.8 by Jason Summers (generated images) | public domain: [bmpsuite-NOTICE.txt](bmpsuite-NOTICE.txt) | | `src/Formats/containers/Zip/` (the reader), `src/Formats/archive/zip/` | zip-luau 121d4b0 (same author), written from PKWARE's APPNOTE.TXT 6.3 | no licence chosen yet; no third-party code | | `src/Formats/playlist/` (m3u, pls; xspf is new), `src/Formats/codecs/Url/`, `src/Formats/codecs/Text/` | playlist-luau 3fc7fd3 (same author), written from RFC 3986 / RFC 8216 | no licence chosen yet; no third-party code | -| `src/Formats/image/jpeg/` (Decode, Scan, Color), `src/Formats/codecs/Dct/` (inverse DCTs) | jpeg-luau 1.0 (same author); the IDCTs, upsampling, colour conversion and IDCT-size choice are Luau translations of libjpeg / libjpeg-turbo (jidctint.c, jidctred.c, jdsample.c, jdcolor.c, jdmaster.c) | IJG licence + libjpeg-turbo BSD: [libjpeg-turbo-LICENSE.md](libjpeg-turbo-LICENSE.md), [libjpeg-README.ijg](libjpeg-README.ijg). This software is based in part on the work of the Independent JPEG Group. | -| `src/Formats/image/jpeg/Arith.luau`, `src/Formats/image/jpeg/Encode.luau`, `src/Formats/codecs/Dct/` (forward DCT) | new; Luau translations of libjpeg-turbo 3.2 jdarith.c / jaricom.c (Guido Vollbeding), jccolor.c, jcsample.c, jccoefct.c, jfdctint.c, jcdctmgr.c, jchuff.c, jcphuff.c, jcparam.c | as above | +| `src/Formats/codecs/Jpeg/` (Decode, Scan, Color, Yuv; moved from image/jpeg), `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/codecs/Jpeg/Arith.luau`, `src/Formats/codecs/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) | | `tests/fixtures/vox/{chr_knight,chr_sword,deer,maze}.vox`, `tests/fixtures/vox/MagicaVoxel-file-format-vox*.txt` (the format spec) | ephtracy/voxel-model (MagicaVoxel sample models) | MIT: [voxel-model-LICENSE.txt](voxel-model-LICENSE.txt) | | `tests/fixtures/vox/ogt_*.vox` | jpaver/opengametools `demo/vox/` (files saved by MagicaVoxel 0.99.x) | MIT: [opengametools-LICENSE.txt](opengametools-LICENSE.txt) | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index d514aa9..8a1190e 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -68,7 +68,7 @@ local list: { Entry } = { path = "image/jpeg", extensions = { "jpg", "jpeg", "jpe", "jfif" }, mime = { "image/jpeg" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Dct" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Jpeg" }, caps = { decode = true, encode = true, lossy = true, alpha = false, depths = { 8, 12 }, progressive = true, arithmetic = true }, load = function() return require("@formats/image/jpeg") diff --git a/src/Formats/image/jpeg/Arith.luau b/src/Formats/codecs/Jpeg/Arith.luau similarity index 99% rename from src/Formats/image/jpeg/Arith.luau rename to src/Formats/codecs/Jpeg/Arith.luau index a1044e2..984c8a5 100644 --- a/src/Formats/image/jpeg/Arith.luau +++ b/src/Formats/codecs/Jpeg/Arith.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- image/jpeg/Arith: arithmetic-coded scans (ITU T.81 annex D / F.1.4, sequential and progressive) into quantised +-- codecs/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. -- diff --git a/src/Formats/image/jpeg/Color.luau b/src/Formats/codecs/Jpeg/Color.luau similarity index 98% rename from src/Formats/image/jpeg/Color.luau rename to src/Formats/codecs/Jpeg/Color.luau index af39c11..46e1cf8 100644 --- a/src/Formats/image/jpeg/Color.luau +++ b/src/Formats/codecs/Jpeg/Color.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- image/jpeg/Color: chroma upsampling and colour conversion to RGBA8, one output row at a time (native; never +-- codecs/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). -- diff --git a/src/Formats/image/jpeg/Decode.luau b/src/Formats/codecs/Jpeg/Decode.luau similarity index 83% rename from src/Formats/image/jpeg/Decode.luau rename to src/Formats/codecs/Jpeg/Decode.luau index 11d2f64..94edc5a 100644 --- a/src/Formats/image/jpeg/Decode.luau +++ b/src/Formats/codecs/Jpeg/Decode.luau @@ -1,12 +1,15 @@ --!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") +-- codecs/Jpeg/Decode: the JPEG marker parser and output stage (interpreted; it validates everything the native Scan / +-- Arith / Dct / Color / Yuv loops index). Absorbed from jpeg-luau 1.0 src/Jpeg/init.luau (same author) and extended: +-- arithmetic-coded frames (SOF9 / SOF10, DAC), a byte range instead of a whole buffer, APP1 EXIF / APP2 ICC / COM +-- / JFIF density collected for meta, the AVI1 APP0 field polarity and the end of the image (Motion-JPEG), and a +-- yuv420p output straight from the IDCT planes (outputYuv). The IDCT size choice for scaled decodes follows +-- libjpeg-turbo's jdmaster.c. Moved from image/jpeg/Decode to codecs/Jpeg/Decode for the video formats. +local Scan = require("@formats/codecs/Jpeg/Scan") +local Arith = require("@formats/codecs/Jpeg/Arith") +local Color = require("@formats/codecs/Jpeg/Color") +local Tables = require("@formats/codecs/Jpeg/Tables") +local Yuv = require("@formats/codecs/Jpeg/Yuv") local Dct = require("@formats/codecs/Dct") local readu8 = buffer.readu8 @@ -226,6 +229,8 @@ export type State = { comments: { string }, truncated: boolean, scale: number, + avi1: number?, -- the AVI1 APP0 field polarity (0 = progressive, 1 / 2 = interlaced: two fields back to back) + endPos: number, -- the byte after the EOI marker (or the end of the data) } -- parse(b, base, limit, opts, headerOnly) -> State | nil, code, message. Walks the markers in b[base, limit); with @@ -255,6 +260,8 @@ function Decode.parse(b: buffer, base: number, n: number, opts: any, headerOnly: comments = {}, truncated = false, scale = scale, + avi1 = nil, + endPos = n, } local iccChunks: { buffer } = {} local ri = 0 @@ -277,6 +284,7 @@ function Decode.parse(b: buffer, base: number, n: number, opts: any, headerOnly: local m = readu8(b, pos) pos += 1 if m == 0xD9 then + st.endPos = pos break -- EOI elseif m == 0 or m == 0x01 or m == 0xD8 or (m >= 0xD0 and m <= 0xD7) then continue -- standalone markers (or stray stuffing) @@ -303,6 +311,8 @@ function Decode.parse(b: buffer, base: number, n: number, opts: any, headerOnly: 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) } + elseif e - p >= 5 and buffer.readstring(b, p, 4) == "AVI1" then + st.avi1 = readu8(b, p + 4) end elseif m == 0xE1 then local t, o = exif(b, p, e) @@ -663,4 +673,68 @@ function Decode.output(st: State): (number?, any, any, string?) return outW, outH, pixels, space end +-- outputYuv(st) -> width, height, yuv420p pixels, sampling | nil when the frame has no direct yuv420p form (the +-- caller falls back to output). The IDCT output planes as they are, cropped to the image, without colour conversion +-- or upsampling: 8-bit YCbCr with 2x2 luma and 1x1 chroma sampling ("420"); 2x1 luma ("422": each pair of chroma +-- rows averaged, rounding up); 1x1 everywhere ("444": each 2 x 2 chroma block averaged, rounding to nearest); grey +-- ("gray": chroma 128). Full scale only (opts.scale = 1). +function Decode.outputYuv(st: State): (number?, number?, buffer?, string?) + local f: Frame = st.frame + if st.scale ~= 1 or f.precision ~= 8 then + return nil + end + local comps = f.comps + local space = colorSpaceOf(f, st.adobe, st.jfif) + local mode = nil + if space == "gray" then + mode = "gray" + elseif space == "ycbcr" and comps[2].h == 1 and comps[2].v == 1 and comps[3].h == 1 and comps[3].v == 1 then + local l = comps[1] + if l.h == 2 and l.v == 2 then + mode = "420" + elseif l.h == 2 and l.v == 1 then + mode = "422" + elseif l.h == 1 and l.v == 1 then + mode = "444" + end + end + if not mode then + return nil + end + for _, c in comps do + if c.coef and not c.quant then + return nil -- output() reports the missing table + end + end + local w, h = f.width, f.height + local cw, ch = (w + 1) // 2, (h + 1) // 2 + local out = buffer.create(w * h + 2 * cw * ch) + local zeroQ: buffer? = nil + for i, c in comps do + local stride, rows = c.bpl * 8, c.bpc * 8 + 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 + zeroQ = zeroQ or buffer.create(128) -- the component never appeared in a scan: mid grey + q = zeroQ + end + Dct.idctComponent(coef, q :: buffer, c.bpl, c.bpc, 8, plane, 2, 128, 255) + if i == 1 then + Yuv.crop(plane, stride, w, h, out, 0) + elseif mode == "420" then + Yuv.crop(plane, stride, cw, ch, out, w * h + (i - 2) * cw * ch) + elseif mode == "422" then + Yuv.rows(plane, stride, cw, h, out, w * h + (i - 2) * cw * ch) + else + Yuv.box(plane, stride, w, h, out, w * h + (i - 2) * cw * ch) + end + c.coef = nil + end + if mode == "gray" then + buffer.fill(out, w * h, 128, 2 * cw * ch) + end + return w, h, out, mode +end + return Decode diff --git a/src/Formats/image/jpeg/Encode.luau b/src/Formats/codecs/Jpeg/Encode.luau similarity index 93% rename from src/Formats/image/jpeg/Encode.luau rename to src/Formats/codecs/Jpeg/Encode.luau index 0ecf6eb..642b737 100644 --- a/src/Formats/image/jpeg/Encode.luau +++ b/src/Formats/codecs/Jpeg/Encode.luau @@ -1,15 +1,16 @@ --!strict --!native --!optimize 2 --- image/jpeg/Encode: the JPEG encoder (native; never throws). Baseline (SOF0) with the standard or optimised Huffman +-- codecs/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, +-- 4:4:4 / 4:2:2 / 4:2:0, or yuv420p planes coded as they are (4:2:0, no colour conversion: the Motion-JPEG +-- encoders); restart intervals. Moved from image/jpeg/Encode to codecs/Jpeg/Encode. 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 Tables = require("@formats/codecs/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 @@ -574,8 +575,9 @@ export type Options = { 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. +-- run(pixels, w, h, bpp, opts) -> buffer. pixels: w * h * bpp bytes (bpp 4 rgba8 / 3 rgb8 / 1 gray8), or bpp 0: +-- yuv420p (w * h luma, then ceil(w / 2) * ceil(h / 2) Cb and Cr; opts.sampling must be "420" unless opts.gray). The +-- caller validated sizes (1..65535), the buffer length 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) @@ -584,7 +586,19 @@ function Encode.run(px: buffer, w: number, h: number, bpp: number, o: Options): GATHER = false EOBRUN, BE = 0, 0 - local Y, Cb, Cr = planes(px, w, h, bpp, o.gray) + local yuv = bpp == 0 + local Y, Cb, Cr + if yuv then + local n, cn = w * h, ((w + 1) // 2) * ((h + 1) // 2) + Y = px + if not o.gray then + Cb, Cr = buffer.create(cn), buffer.create(cn) + buffer.copy(Cb :: buffer, 0, px, n, cn) + buffer.copy(Cr :: buffer, 0, px, n + cn, cn) + end + else + Y, Cb, Cr = planes(px, w, h, bpp, o.gray) + end local hs, vs = 1, 1 if not o.gray then if o.sampling == "420" then @@ -615,7 +629,9 @@ function Encode.run(px: buffer, w: number, h: number, bpp: number, o: Options): 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 + if yuv and i > 1 then + pw, ph = (w + 1) // 2, (h + 1) // 2 -- already 4:2:0: fdctQuantize repeats the edges as jcsample.c does + elseif ch < hs or cv < vs then pw, ph = bw * 8, chh plane = downsample(src, w, h, hs // ch, vs // cv, pw, ph) end diff --git a/src/Formats/image/jpeg/Scan.luau b/src/Formats/codecs/Jpeg/Scan.luau similarity index 99% rename from src/Formats/image/jpeg/Scan.luau rename to src/Formats/codecs/Jpeg/Scan.luau index ec8f45f..f8f62eb 100644 --- a/src/Formats/image/jpeg/Scan.luau +++ b/src/Formats/codecs/Jpeg/Scan.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- image/jpeg/Scan: Huffman-coded scan decoding into quantised DCT coefficients (native; never throws). Absorbed from +-- codecs/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, diff --git a/src/Formats/image/jpeg/Tables.luau b/src/Formats/codecs/Jpeg/Tables.luau similarity index 96% rename from src/Formats/image/jpeg/Tables.luau rename to src/Formats/codecs/Jpeg/Tables.luau index e524d54..9e9c4df 100644 --- a/src/Formats/image/jpeg/Tables.luau +++ b/src/Formats/codecs/Jpeg/Tables.luau @@ -1,5 +1,5 @@ --!strict --- image/jpeg/Tables: the standard tables of ITU T.81 annex K: the example Huffman tables (K.3, which every baseline +-- codecs/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 = {} diff --git a/src/Formats/codecs/Jpeg/Yuv.luau b/src/Formats/codecs/Jpeg/Yuv.luau new file mode 100644 index 0000000..7ca340c --- /dev/null +++ b/src/Formats/codecs/Jpeg/Yuv.luau @@ -0,0 +1,76 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Jpeg/Yuv: the yuv420p output of the JPEG decoder (native; never throws): the IDCT output planes (u16 +-- samples, block-padded) cropped into u8 yuv420p planes without colour conversion or upsampling, 4:2:2 / 4:4:4 +-- chroma reduced to 4:2:0 by averaging, and the interleaving of two fields (AVI1 interlaced Motion-JPEG). +-- The callers (codecs/Jpeg/Decode, codecs/Jpeg) size every buffer; each loop reads and writes inside those sizes. +local readu16, writeu8, readu32 = buffer.readu16, buffer.writeu8, buffer.readu32 + +local Yuv = {} + +-- crop(src, stride, w, h, dst, doff): the top-left w x h samples of a u16 plane (stride samples per row) into u8 +-- samples at dst[doff], w per row +function Yuv.crop(src: buffer, stride: number, w: number, h: number, dst: buffer, doff: number) + local npairs = w // 2 + for y = 0, h - 1 do + local s = y * stride * 2 + local d = doff + y * w + -- two samples per u32 read + for _ = 1, npairs do + local v = readu32(src, s) + writeu8(dst, d, v % 65536) + writeu8(dst, d + 1, v // 65536) + s += 4 + d += 2 + end + if w % 2 == 1 then + writeu8(dst, d, readu16(src, s)) + end + end +end + +-- rows(src, stride, w, h, dst, doff): a u16 plane of w x h samples (4:2:2 chroma) -> u8 w x ceil(h / 2), each output +-- row the rounded mean of two source rows (the last row alone when h is odd) +function Yuv.rows(src: buffer, stride: number, w: number, h: number, dst: buffer, doff: number) + local oh = (h + 1) // 2 + for y = 0, oh - 1 do + local a = 2 * y * stride * 2 + local b = if 2 * y + 1 < h then a + stride * 2 else a + local d = doff + y * w + for x = 0, w - 1 do + writeu8(dst, d + x, (readu16(src, a + x * 2) + readu16(src, b + x * 2) + 1) // 2) + end + end +end + +-- box(src, stride, w, h, dst, doff): a u16 plane of w x h samples (4:4:4 chroma) -> u8 ceil(w / 2) x ceil(h / 2), +-- each output sample the rounded mean of a 2 x 2 block (edges repeat the last row / column) +function Yuv.box(src: buffer, stride: number, w: number, h: number, dst: buffer, doff: number) + local ow, oh = (w + 1) // 2, (h + 1) // 2 + for y = 0, oh - 1 do + local a = 2 * y * stride * 2 + local b = if 2 * y + 1 < h then a + stride * 2 else a + local d = doff + y * ow + for x = 0, ow - 1 do + local x0 = 2 * x * 2 + local x1 = if 2 * x + 1 < w then x0 + 2 else x0 + writeu8(dst, d + x, (readu16(src, a + x0) + readu16(src, a + x1) + readu16(src, b + x0) + readu16(src, b + x1) + 2) // 4) + end + end +end + +-- weave(top, toff, bottom, boff, rowBytes, rows, dst, doff): interleave rows of two planes (field 1 on the even rows, field +-- 2 on the odd rows) into rows output rows at dst[doff]; top holds ceil(rows / 2) rows, bottom floor(rows / 2) +function Yuv.weave(top: buffer, toff: number, bottom: buffer, boff: number, rowBytes: number, rows: number, dst: buffer, doff: number) + for y = 0, rows - 1 do + local k = y // 2 + if y % 2 == 0 then + buffer.copy(dst, doff + y * rowBytes, top, toff + k * rowBytes, rowBytes) + else + buffer.copy(dst, doff + y * rowBytes, bottom, boff + k * rowBytes, rowBytes) + end + end +end + +return Yuv diff --git a/src/Formats/codecs/Jpeg/init.luau b/src/Formats/codecs/Jpeg/init.luau new file mode 100644 index 0000000..e7a930e --- /dev/null +++ b/src/Formats/codecs/Jpeg/init.luau @@ -0,0 +1,386 @@ +--!strict +-- codecs/Jpeg: the JPEG codec (ITU T.81) on byte ranges: image/jpeg is a thin format over it, and the Motion-JPEG +-- video tracks (AVI / Matroska / QuickTime) decode and encode their frames with it. The engine (Huffman and +-- arithmetic scan decoding, IDCTs through codecs/Dct, libjpeg-turbo's upsampling and colour conversion, the encoder) +-- was absorbed from jpeg-luau 1.0 (same author) into image/jpeg and moved down here; it is bit-exact with libjpeg-turbo's +-- djpeg and byte-identical with cjpeg. IJG-derived parts: licenses/libjpeg-turbo-LICENSE.md. +-- +-- local img, err = Jpeg.decode(buf, off?, len?, opts?) -- one JPEG -> rgba8 (or gray8 / yuv420p) Types.Image +-- local img = Jpeg.decode(frame, 0, n, { yuv = true }) -- video: yuv420p straight from the IDCT planes +-- local out, err = Jpeg.encode(img, opts?) -- rgba8 / rgb8 / gray8 / yuv420p Image -> buffer +-- local info, err = Jpeg.info(buf, off?, len?) -- the headers up to the frame header +-- +-- 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), EXIF orientation +-- (meta.orientation, applied with opts.orient). Truncated or corrupt scans decode as far as they go +-- (meta.truncated = true). +-- Motion-JPEG: frames without DHT segments use the T.81 annex K tables; the AVI1 APP0 segment is read (its field +-- polarity) and data after EOI is ignored. Two fields back to back (AVI1 interlaced: two JPEGs of half the frame +-- height, polarity 1 or 2, or opts.fields = true) are decoded and woven into one frame, the first field on the even +-- rows (top field first, as ffmpeg, which ignores the polarity value); a missing or different-sized second field +-- leaves the first field alone (meta.source.fields = 1). +-- opts.yuv: 8-bit YCbCr frames come out as yuv420p (full-range BT.601, meta.source.range = "full") without colour +-- conversion or upsampling: 4:2:0 (2x2 luma) as the planes are; 4:2:2 (2x1 luma, the usual Motion-JPEG camera +-- layout) with each pair of chroma rows averaged; 4:4:4 with 2 x 2 chroma averages; grey with chroma 128. Other +-- layouts (RGB, CMYK, 4:1:1, 4:4:0, 12-bit) and scaled decodes fall back to rgba8 (check img.format). +-- 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, extra APPn / COM segments +-- (opts.segments); yuv420p input is coded from its planes as they are (4:2:0, no colour conversion). +-- Not supported: lossless (SOF3) and hierarchical frames, DNL, 2-component images, 12-bit or CMYK encoding. +-- Never throws: bad data or arguments return nil, Err. +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Decode = require("@formats/codecs/Jpeg/Decode") +local Encode = require("@formats/codecs/Jpeg/Encode") +local Yuv = require("@formats/codecs/Jpeg/Yuv") + +local Jpeg = {} + +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; rgba8 / gray8) + native: boolean?, -- grey files decode to gray8 (default false: rgba8) + yuv: boolean?, -- 8-bit YCbCr / grey frames decode to yuv420p (default false); see the header for the layouts + fields: boolean?, -- two JPEGs back to back are two fields of one frame (default: when the AVI1 segment says so) + 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"; yuv420p input is always 4:2:0) + 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) + density: { unit: number, x: number, y: number }?, -- the JFIF density (default unit 0, 1 x 1) + segments: { { marker: number, data: buffer } }?, -- APPn / COM segments written after the JFIF header +} + +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, + avi1: number?, -- the AVI1 field polarity, when the segment comes before the frame header +} + +local CODES = { corrupt = Err.CORRUPT, unsupported = Err.UNSUPPORTED, limit = Err.LIMIT, truncated = Err.TRUNCATED, arg = Err.ARG } + +local function range(buf: buffer, off: number?, len: number?): (number, number) + local n = buffer.len(buf) + local o = math.clamp(math.floor(tonumber(off) or 0), 0, n) + return o, math.clamp(math.floor(tonumber(len) or (n - o)), 0, n - o) +end + +-- the marker parser over [o, o + l): State | nil, Err +local function parse(buf: buffer, o: number, l: number, opts: any, headerOnly: boolean): (Decode.State?, Err.Err?) + local ok, st, code, msg = pcall(Decode.parse, buf, o, o + l, 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", o) + end + return st, nil +end + +local function samplingOf(f: any): { { number } } + local sampling = {} + for _, c in f.comps do + table.insert(sampling, { c.h, c.v }) + end + return sampling +end + +-- info(buf, off?, len?) -> Info | nil, Err (reads the headers up to the frame header) +function Jpeg.info(buf: buffer, off: number?, len: number?): (Info?, Err.Err?) + if type(buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "expected a buffer") + end + local o, l = range(buf, off, len) + local st, err = parse(buf, o, l, nil, true) + if not st then + return nil, err + end + local f = st.frame + 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 = samplingOf(f), + orientation = st.orientation, + adobe = st.adobe, + jfif = st.jfif, + avi1 = st.avi1, + }, + 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 + +-- one JPEG at [o, o + l): Image, State | nil, Err +local function decodeOne(buf: buffer, o: number, l: number, opts: DecodeOptions?): (Types.Image?, any) + local st, err = parse(buf, o, l, opts, false) + if not st then + return nil, err + end + local s = st :: Decode.State + local img = Types.Image.new(0, 0) + local space, mode = nil, nil + if opts and opts.yuv then + local ok, w, h, px, m = pcall(Decode.outputYuv, s) + if not ok then + return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(w)) + end + if w then + img.width, img.height, img.pixels, img.format = w, h :: number, px :: buffer, "yuv420p" + mode = m + space = Decode.colorSpaceOf(s.frame, s.adobe, s.jfif) + end + end + if not mode then + local ok, w, h, px, sp = pcall(Decode.output, s) + 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), o) + end + space = sp + if opts and opts.orient then + px, w, h = orient(px, w, h, s.orientation) + end + img.width, img.height, img.pixels = w, h, px + if opts and opts.native and space == "gray" then + local g = buffer.create(w * h) + for i = 0, w * h - 1 do + buffer.writeu8(g, i, buffer.readu8(px, i * 4)) + end + img.pixels, img.format = g, "gray8" + end + end + local f = s.frame + local meta = img.meta + meta.orientation = s.orientation + meta.oriented = (opts and opts.orient and not mode) or false + meta.exif = s.exif + meta.icc = s.icc + if #s.comments > 0 then + meta.text = { comment = table.concat(s.comments, "\n") } + end + if s.density and s.density.unit > 0 and s.density.x > 0 and s.density.y > 0 then + local k = if s.density.unit == 2 then 2.54 else 1 + meta.dpi = { x = s.density.x * k, y = s.density.y * k } + end + meta.truncated = s.truncated + meta.source = { + format = "jpeg", + bitDepth = f.precision, + colorType = space, + components = #f.comps, + progressive = f.progressive, + arithmetic = f.arithmetic, + sampling = samplingOf(f), + scale = s.scale, + adobe = s.adobe, + jfif = s.jfif, + avi1 = s.avi1, + yuv = mode, -- "420" | "422" | "444" | "gray": how the yuv420p planes were made (opts.yuv) + range = if mode then "full" else nil, + fields = 1, + } + return img, s +end + +-- the start of a second JPEG (FF D8 FF) at or after p, before e; -1 if none +local function nextSoi(buf: buffer, p: number, e: number): number + local readu8 = buffer.readu8 + while p + 3 <= e do + if readu8(buf, p) == 0xFF and readu8(buf, p + 1) == 0xD8 and readu8(buf, p + 2) == 0xFF then + return p + end + p += 1 + end + return -1 +end + +-- two fields (same size and format) -> one frame of twice the height, field a on the even rows +local function weave(a: Types.Image, b: Types.Image): Types.Image + local w, hf = a.width, a.height + local h = hf * 2 + local out = Types.Image.new(w, h, a.format) + local dst = out.pixels + if a.format == "yuv420p" then + local cw, chf = (w + 1) // 2, (hf + 1) // 2 + local ch = (h + 1) // 2 -- = hf + Yuv.weave(a.pixels, 0, b.pixels, 0, w, h, dst, 0) + for k = 0, 1 do + Yuv.weave(a.pixels, w * hf + k * cw * chf, b.pixels, w * hf + k * cw * chf, cw, ch, dst, w * h + k * cw * ch) + end + else + local bpp = Types.Image.bpp(a.format) or 4 + Yuv.weave(a.pixels, 0, b.pixels, 0, w * bpp, h, dst, 0) + end + out.meta = a.meta + return out +end + +-- decode(buf, off?, len?, opts?) -> Image | nil, Err: one JPEG (or one interlaced Motion-JPEG frame) in [off, off + len) +function Jpeg.decode(buf: buffer, off: number?, len: number?, opts: DecodeOptions?): (Types.Image?, Err.Err?) + if type(buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "expected a buffer") + end + if opts ~= nil and type(opts) ~= "table" then + return nil, Err.new(Err.ARG, "options must be a table") + end + local o, l = range(buf, off, len) + local img, st = decodeOne(buf, o, l, opts) + if not img then + return nil, st + end + local s = st :: Decode.State + local wantFields = if opts and opts.fields ~= nil then opts.fields else (s.avi1 == 1 or s.avi1 == 2) + if wantFields and not (opts and opts.orient) then + local e = o + l + local p = nextSoi(buf, s.endPos, e) + if p >= 0 then + local o2 = table.clone(opts or {}) :: any + if o2.maxPixels then + o2.maxPixels = math.max(0, o2.maxPixels - img.width * img.height) + end + local b = decodeOne(buf, p, e - p, o2) + if b and b.width == img.width and b.height == img.height and b.format == img.format then + local truncated = img.meta.truncated or b.meta.truncated + img = weave(img, b) + img.meta.truncated = truncated + img.meta.source.fields = 2 + end + end + end + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local BPP = { rgba8 = 4, rgb8 = 3, gray8 = 1, yuv420p = 0 } + +-- encode(img, opts?) -> buffer | nil, Err: an rgba8 / rgb8 / gray8 / yuv420p Image as a baseline or progressive JPEG +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, gray8 or yuv420p Image (got " .. tostring(img.format) .. ")") + end + local w, h = img.width, img.height + local need = if bpp == 0 then w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2) else w * h * bpp + 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) < need then + return nil, Err.new(Err.ARG, "bad image size or pixel buffer (1..65535 per side)") + end + if opts ~= nil and type(opts) ~= "table" then + return nil, Err.new(Err.ARG, "options must be a table") + 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 + if bpp == 0 then + sub = "420" + 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 = {} + if o.segments ~= nil then + if type(o.segments) ~= "table" then + return nil, Err.new(Err.ARG, "segments must be a list of { marker, data }") + end + for _, sg in o.segments do + if type(sg) ~= "table" or type(sg.data) ~= "buffer" or buffer.len(sg.data) > 65533 or type(sg.marker) ~= "number" then + return nil, Err.new(Err.ARG, "bad segment (marker 0xE0..0xEF / 0xFE, at most 65533 bytes)") + end + if not ((sg.marker >= 0xE0 and sg.marker <= 0xEF) or sg.marker == 0xFE) then + return nil, Err.new(Err.ARG, "bad segment marker (0xE0..0xEF / 0xFE)") + end + table.insert(segments, sg) + end + end + local density = o.density + if density ~= nil then + if type(density) ~= "table" or type(density.unit) ~= "number" or type(density.x) ~= "number" or type(density.y) ~= "number" then + return nil, Err.new(Err.ARG, "bad density") + end + density = { + unit = math.clamp(math.floor(density.unit), 0, 2), + x = math.clamp(math.floor(density.x), 1, 65535), + y = math.clamp(math.floor(density.y), 1, 65535), + } + end + local out = Encode.run(img.pixels, w, h, bpp, { + quality = quality, + sampling = sub, + progressive = o.progressive == true, + optimize = o.optimize == true, + gray = gray, + restart = restart, + segments = segments, + jfif = o.jfif ~= false, + density = density, + }) + return out, nil +end + +return Jpeg diff --git a/src/Formats/image/jpeg/init.luau b/src/Formats/image/jpeg/init.luau index f6c3077..aeffeea 100644 --- a/src/Formats/image/jpeg/init.luau +++ b/src/Formats/image/jpeg/init.luau @@ -1,7 +1,10 @@ --!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. +-- image/jpeg: JPEG / JFIF / EXIF (ITU T.81), a thin format over codecs/Jpeg (the engine, shared with the Motion-JPEG +-- video tracks; absorbed from jpeg-luau 1.0, same author, bit-exact with libjpeg-turbo's djpeg and byte-identical +-- with cjpeg; IJG-derived parts: licenses/libjpeg-turbo-LICENSE.md). This module is the contract, the sniff, the +-- options and the meta segments: meta.exif (APP1), meta.icc (APP2 chunks), meta.text.comment (COM) and meta.dpi +-- (JFIF density) are written from the Image on encode and read back on decode. Encode also takes yuv420p Images +-- (coded 4:2:0 from the planes as they are). -- 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 @@ -17,8 +20,7 @@ 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") +local Codec = require("@formats/codecs/Jpeg") -- ------------------------------------------------------------------------------------------------ contract local Jpeg = { @@ -26,7 +28,7 @@ local Jpeg = { category = "image", extensions = { "jpg", "jpeg", "jpe", "jfif" }, mime = { "image/jpeg" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/Dct" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Jpeg" }, caps = { decode = true, encode = true, lossy = true, alpha = false, depths = { 8, 12 }, progressive = true, arithmetic = true }, } @@ -48,22 +50,7 @@ export type EncodeOptions = { 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 } +export type Info = Codec.Info -- ------------------------------------------------------------------------------------------------ sniff function Jpeg.sniff(r: Bytes.Reader): number @@ -72,214 +59,91 @@ function Jpeg.sniff(r: Bytes.Reader): number 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 + return Codec.info(r.buf, r.base, r.limit - r.base) 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 + if opts ~= nil and type(opts) ~= "table" then + return nil, Err.new(Err.ARG, "options must be a table") end - local ok, w, h, px, space = pcall(Decode.output, st :: Decode.State) - if not ok then - return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(w)) - end - if not w then - return nil, Err.new(CODES[h :: string] or Err.CORRUPT, tostring(px)) - end - local orientation = st.orientation - if opts and opts.orient then - px, w, h = orient(px, w, h, orientation) - end - local img = Types.Image.new(1, 1) - img.width, img.height, img.pixels = w, h, px - if opts and opts.native and space == "gray" then - local g = buffer.create(w * h) - for i = 0, w * h - 1 do - buffer.writeu8(g, i, buffer.readu8(px, i * 4)) - end - img.pixels, img.format = g, "gray8" - end - local f = st.frame - local sampling = {} - for _, c in f.comps do - table.insert(sampling, { c.h, c.v }) - end - img.meta.orientation = orientation - img.meta.oriented = (opts and opts.orient) or false - img.meta.exif = st.exif - img.meta.icc = st.icc - if #st.comments > 0 then - img.meta.text = { comment = table.concat(st.comments, "\n") } - end - if st.density and st.density.unit > 0 and st.density.x > 0 and st.density.y > 0 then - local k = if st.density.unit == 2 then 2.54 else 1 - img.meta.dpi = { x = st.density.x * k, y = st.density.y * k } - end - img.meta.truncated = st.truncated - img.meta.source = { - format = "jpeg", - bitDepth = f.precision, - colorType = space, - components = #f.comps, - progressive = f.progressive, - arithmetic = f.arithmetic, - sampling = sampling, - scale = st.scale, - adobe = st.adobe, - jfif = st.jfif, - } - return img, nil + local o = opts or {} :: DecodeOptions + -- one image: no yuv output, no field weaving (two JPEGs back to back are an image and a preview, as in MPF) + return Codec.decode(r.buf, r.base, r.limit - r.base, { + scale = o.scale, + orient = o.orient, + native = o.native, + maxPixels = o.maxPixels, + fields = false, + }) 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 +-- the APP1 / APP2 / COM segments and the JFIF density from img.meta +local function metaSegments(meta: any): ({ { marker: number, data: buffer } }, { unit: number, x: number, y: number }?) 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 + 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 - 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 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 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, + return segments, density +end + +function Jpeg.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" then + return nil, Err.new(Err.ARG, "needs an Image") + end + if opts ~= nil and type(opts) ~= "table" then + return nil, Err.new(Err.ARG, "options must be a table") + end + local o: any = opts or {} + local segments, density = {}, nil + if o.meta ~= false then + segments, density = metaSegments(img.meta or {}) + elseif type(img.meta) == "table" then + local _ + _, density = metaSegments({ dpi = img.meta.dpi }) + end + return Codec.encode(img, { + quality = o.quality, + subsampling = o.subsampling, + progressive = o.progressive, + optimize = o.optimize, + gray = o.gray, + restart = o.restart, + jfif = o.jfif, density = density, + segments = segments, }) - return out, nil end return Jpeg