From 5e6909e34a2e1892bd1a4edf38a41dad557abd05 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:28:38 -0500 Subject: [PATCH 1/6] 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 From 43da7d723c0a8e43f3937ae89e691c8881c977ba Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:35:34 -0500 Subject: [PATCH 2/6] ws-video-codecs: codecs/Jpeg: 4:2:2 / 4:4:4 as ffmpeg writes them (2x2/1x2, 1x2) for yuv output; tests/codecs/jpeg.luau + tools/fixtures/mjpeg.py (ffmpeg mjpeg frames bit-exact vs TurboJPEG planes / djpeg, PSNR vs ffmpeg, stripped DHT, AVI1, fields, yuv420p encode byte-identical with tj3CompressFromYUV8) --- src/Formats/codecs/Jpeg/Decode.luau | 29 ++- tests/codecs/jpeg.luau | 250 ++++++++++++++++++++++ tools/fixtures/mjpeg.py | 307 ++++++++++++++++++++++++++++ 3 files changed, 575 insertions(+), 11 deletions(-) create mode 100644 tests/codecs/jpeg.luau create mode 100644 tools/fixtures/mjpeg.py diff --git a/src/Formats/codecs/Jpeg/Decode.luau b/src/Formats/codecs/Jpeg/Decode.luau index 94edc5a..3d88b8d 100644 --- a/src/Formats/codecs/Jpeg/Decode.luau +++ b/src/Formats/codecs/Jpeg/Decode.luau @@ -675,9 +675,10 @@ 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). +-- or upsampling: 8-bit YCbCr whose chroma is sampled at half the luma rate both ways ("420", 2x2 / 1x1); half +-- horizontally ("422", 2x1 / 1x1 or ffmpeg's 2x2 / 1x2: each pair of chroma rows averaged, rounding up); at the luma +-- rate ("444", 1x1 or ffmpeg's 1x2 everywhere: 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 @@ -688,14 +689,20 @@ function Decode.outputYuv(st: State): (number?, number?, buffer?, string?) 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" + elseif space == "ycbcr" then + -- the ratios of luma to chroma sampling (ffmpeg writes 4:2:2 as 2x2 / 1x2 and 4:4:4 as 1x2 everywhere) + local l, cb, cr = comps[1], comps[2], comps[3] + if l.h == f.hmax and l.v == f.vmax and cb.h == cr.h and cb.v == cr.v then + local rh, rv = f.hmax // cb.h, f.vmax // cb.v + if rh * cb.h ~= f.hmax or rv * cb.v ~= f.vmax then + mode = nil + elseif rh == 2 and rv == 2 then + mode = "420" + elseif rh == 2 and rv == 1 then + mode = "422" + elseif rh == 1 and rv == 1 then + mode = "444" + end end end if not mode then diff --git a/tests/codecs/jpeg.luau b/tests/codecs/jpeg.luau new file mode 100644 index 0000000..9542a11 --- /dev/null +++ b/tests/codecs/jpeg.luau @@ -0,0 +1,250 @@ +-- codecs/Jpeg tests (the Motion-JPEG side; tests/image/jpeg.luau covers the still-image decoder and encoder through +-- image/jpeg): ffmpeg mjpeg frames (4:2:0, 4:2:2, 4:4:4, odd sizes, stripped DHT, AVI1 + junk after EOI) decoded +-- to yuv420p bit-exact with libjpeg-turbo's IDCT planes (TurboJPEG) and to rgba8 bit-exact with djpeg, and within +-- PSNR thresholds of ffmpeg's own decode; an interlaced AVI1 frame (two fields) woven; the yuv420p encoder +-- byte-identical to TurboJPEG's tj3CompressFromYUV8, read back by djpeg (exact) and ffmpeg (PSNR); the API's +-- arguments; the fuzz no-throw pass. Fixtures: tools/fixtures/mjpeg.py. +local T = require("@tests/T") +local Jpeg = require("@formats/codecs/Jpeg") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Fx = require("@tests/gen/mjpeg_cases") +local Enc = require("@tests/gen/mjpeg_enc") + +local t = T.suite("codecs/jpeg") + +-- PSNR of n bytes of a at ao against b at bo +local function psnr(a: buffer, ao: number, b: buffer, bo: number, n: number): number + local se = 0 + for i = 0, n - 1 do + local d = buffer.readu8(a, ao + i) - buffer.readu8(b, bo + i) + se += d * d + end + if se == 0 then + return 99 + end + return 10 * math.log10(255 * 255 * n / se) +end + +-- PSNR of the RGB channels of two rgba8 buffers of n pixels +local function psnrRgb(a: buffer, b: buffer, n: 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 * 4 + k) + se += d * d + end + end + if se == 0 then + return 99 + end + return 10 * math.log10(255 * 255 * n * 3 / se) +end + +local function hasDht(s: string): boolean + local at = string.find(s, "\255\196", 1, true) + local sos = string.find(s, "\255\218", 1, true) + return at ~= nil and sos ~= nil and at < sos +end + +-- 1. ffmpeg's frames: yuv420p (TurboJPEG planes) and rgba8 (djpeg) bit-exact, PSNR against ffmpeg's decode +do + local frames, worstY, worstC, worstRgb = 0, 99, 99, 99 + for _, s in Fx.streams do + local w, h = s.width, s.height + local cw, ch = (w + 1) // 2, (h + 1) // 2 + for i, f in s.frames do + local label = string.format("%s frame %d", s.name, i) + local b = buffer.fromstring(f.data) + local img, err = Jpeg.decode(b, 0, buffer.len(b), { yuv = true }) + t:check(img, label .. ": " .. tostring(err)) + t:check(img.format == "yuv420p" and img.width == w and img.height == h, label .. ": a yuv420p " .. w .. "x" .. h .. " Image") + t:eq(buffer.len(img.pixels), w * h + 2 * cw * ch, label .. ": plane sizes") + t:check(img.meta.source.yuv == s.sampling and img.meta.source.range == "full", label .. ": meta.source.yuv " .. tostring(img.meta.source.yuv)) + t:check(not img.meta.truncated, label .. ": not truncated") + t:eq(Crc32.of(img.pixels), f.yuv, label .. ": yuv420p planes = TurboJPEG's") + local rgba = Jpeg.decode(b) :: Types.Image + t:check(rgba and rgba.format == "rgba8", label .. ": rgba8") + t:eq(Crc32.of(rgba.pixels), f.rgba, label .. ": rgba8 = djpeg") + if i == 1 then + local ref = buffer.fromstring(s.ff.yuv) + local py = psnr(img.pixels, 0, ref, 0, w * h) + local pc = math.min(psnr(img.pixels, w * h, ref, w * h, cw * ch), psnr(img.pixels, w * h + cw * ch, ref, w * h + cw * ch, cw * ch)) + -- ffmpeg's IDCT differs from libjpeg's islow by rounding only; its 4:2:2 / 4:4:4 -> 4:2:0 is a filter + t:check(py > 55, string.format("%s: luma PSNR %.1f dB against ffmpeg", s.name, py)) + t:check(pc > (if s.sampling == "420" then 55 else 20), string.format("%s: chroma PSNR %.1f dB against ffmpeg", s.name, pc)) + worstY, worstC = math.min(worstY, py), math.min(worstC, pc) + if s.ff.rgba then + local pr = psnrRgb(rgba.pixels, buffer.fromstring(s.ff.rgba), w * h) + -- swscale upsamples chroma differently from libjpeg (fancy): testsrc2's sharp colour edges cost ~10 dB + t:check(pr > 25, string.format("%s: rgba PSNR %.1f dB against ffmpeg", s.name, pr)) + worstRgb = math.min(worstRgb, pr) + end + end + if string.find(s.name, "nodht") then + t:check(not hasDht(f.data), label .. ": no DHT segment") + end + if s.name == "avi1_junk" then + t:eq(img.meta.source.avi1, 0, label .. ": AVI1 polarity") + t:eq(Jpeg.info(b).avi1, 0, label .. ": info.avi1") + end + frames += 1 + end + end + t:note("%d ffmpeg mjpeg frames bit-exact (yuv420p: TurboJPEG, rgba8: djpeg); worst PSNR against ffmpeg: luma %.1f, chroma %.1f, rgba %.1f dB", frames, worstY, worstC, worstRgb) +end + +-- 2. an interlaced frame: two fields (AVI1 polarity 1) woven, field 1 on the even rows +do + local F = Fx.fields + local b = buffer.fromstring(F.data) + local img = Jpeg.decode(b, 0, nil, { yuv = true }) :: Types.Image + t:check(img and img.width == F.width and img.height == F.height and img.format == "yuv420p", "fields: one 320x240 yuv420p frame") + t:eq(img.meta.source.fields, 2, "fields: meta.source.fields") + t:eq(Crc32.of(img.pixels), F.yuv, "fields: woven yuv420p planes = TurboJPEG's fields woven") + local src = buffer.fromstring(F.src) + local p = psnr(img.pixels, 0, src, 0, F.width * F.height) + t:check(p > 35, string.format("fields: luma PSNR %.1f dB against the source frame", p)) + local rgba = Jpeg.decode(b) :: Types.Image + t:check(rgba.height == F.height and Crc32.of(rgba.pixels) == F.rgba, "fields: woven rgba8 = djpeg's fields woven") + local one = Jpeg.decode(b, 0, nil, { yuv = true, fields = false }) :: Types.Image + t:check(one.height == F.height // 2 and one.meta.source.fields == 1, "fields = false: the first field only") + -- the first field alone (no second JPEG): a half-height frame, not an error + local first = string.find(F.data, "\255\217", 1, true) :: number + local half = Jpeg.decode(buffer.fromstring(string.sub(F.data, 1, first + 1)), 0, nil, { yuv = true }) :: Types.Image + t:check(half and half.height == F.height // 2 and half.meta.source.fields == 1, "a missing second field leaves the first") + t:check(Jpeg.info(b).avi1 == 1, "fields: info.avi1") +end + +-- 3. the yuv420p encoder: byte-identical with TurboJPEG, read back by djpeg (exact) and ffmpeg (PSNR) +do + local exact = 0 + for _, c in Enc do + local img = Types.Image.new(c.width, c.height, "yuv420p") + img.pixels = buffer.fromstring(c.yuv) + local out, err = Jpeg.encode(img, { quality = c.quality }) + t:check(out, c.name .. ": " .. tostring(err)) + local s = buffer.tostring(out :: buffer) + if s ~= c.want then + 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 tj3CompressFromYUV8 at byte %d (ours %d bytes, TurboJPEG %d)", c.name, at, #s, #c.want)) + end + exact += 1 + local back = Jpeg.decode(out :: buffer) :: Types.Image + t:eq(Crc32.of(back.pixels), c.rgba, c.name .. ": our decode of it = djpeg's") + local floor = if c.quality >= 75 then 30 else 26 + if c.width * c.height >= 1000 then + t:check(c.ffpsnr > floor, string.format("%s: ffmpeg reads it at %.1f dB luma PSNR", c.name, c.ffpsnr)) + local y = Jpeg.decode(out :: buffer, 0, nil, { yuv = true }) :: Types.Image + local p = psnr(y.pixels, 0, img.pixels, 0, c.width * c.height) + t:check(p > floor, string.format("%s: yuv round trip %.1f dB", c.name, p)) + end + end + t:note("%d yuv420p encodes byte-identical with tj3CompressFromYUV8", exact) + -- grey from yuv420p: the luma plane only + local c = Enc[1] + local img = Types.Image.new(c.width, c.height, "yuv420p") + img.pixels = buffer.fromstring(c.yuv) + local g = Jpeg.encode(img, { quality = 80, gray = true }) :: buffer + local gi = Jpeg.info(g) + t:check(gi and gi.components == 1, "yuv420p with gray = true: one component") + local gy = Jpeg.decode(g, 0, nil, { yuv = true }) :: Types.Image + t:check(gy.format == "yuv420p" and gy.meta.source.yuv == "gray" and buffer.readu8(gy.pixels, c.width * c.height) == 128, "grey decodes to yuv420p with chroma 128") + local p = Jpeg.encode(img, { quality = 80, progressive = true, restart = 2 }) :: buffer + local pi = Jpeg.info(p) + t:check(pi and pi.progressive and pi.sampling[1][1] == 2 and pi.sampling[1][2] == 2, "yuv420p progressive") + local pd = Jpeg.decode(p, 0, nil, { yuv = true }) :: Types.Image + t:check(psnr(pd.pixels, 0, img.pixels, 0, c.width * c.height) > 30, "yuv420p progressive round trip") + local s4 = Jpeg.encode(img, { subsampling = "444" }) :: buffer + t:eq(Jpeg.info(s4).sampling[1][1], 2, "yuv420p input is always 4:2:0") + -- extra segments and density + local seg = Jpeg.encode(img, { segments = { { marker = 0xFE, data = buffer.fromstring("hello") } }, density = { unit = 1, x = 72, y = 72 } }) :: buffer + local sd = Jpeg.decode(seg) :: Types.Image + t:check(sd.meta.text and sd.meta.text.comment == "hello" and sd.meta.dpi and sd.meta.dpi.x == 72, "segments and density") +end + +-- 4. the API: ranges, options, fallbacks, errors +do + local s = Fx.streams[1] + local data = s.frames[1].data + local big = buffer.create(#data + 30) + buffer.writestring(big, 17, data) + local a = Jpeg.decode(big, 17, #data, { yuv = true }) :: Types.Image + t:eq(Crc32.of(a.pixels), s.frames[1].yuv, "decode from a sub-range") + local i = Jpeg.info(big, 17, #data) + t:check(i and i.width == s.width and i.colorSpace == "ycbcr" and i.sampling[1][2] == 2, "info from a sub-range") + local sc = Jpeg.decode(buffer.fromstring(data), 0, nil, { yuv = true, scale = 2 }) :: Types.Image + t:check(sc.format == "rgba8" and sc.width == s.width // 2, "yuv with scale 2 falls back to rgba8") + local _, e1 = Jpeg.decode("nope" :: any) + t:check(e1 and e1.code == Err.ARG, "decode(string)") + local _, e2 = Jpeg.decode(buffer.fromstring("nope")) + t:check(e2 and e2.code == Err.CORRUPT, "junk") + local _, e3 = Jpeg.decode(buffer.fromstring(data), 0, nil, { maxPixels = 100, yuv = true }) + t:check(e3 and e3.code == Err.LIMIT, "maxPixels") + local _, e4 = Jpeg.decode(buffer.fromstring(data), 0, nil, 5 :: any) + t:check(e4 and e4.code == Err.ARG, "non-table options") + local _, e5 = Jpeg.encode(Types.Image.new(4, 4, "rgba16")) + t:check(e5 and e5.code == Err.ARG, "rgba16 is refused") + local short = Types.Image.new(8, 8, "yuv420p") + short.pixels = buffer.create(70) + local _, e6 = Jpeg.encode(short) + t:check(e6 and e6.code == Err.ARG, "a short yuv420p buffer") + local _, e7 = Jpeg.encode(Types.Image.new(8, 8), { segments = { { marker = 0xC4, data = buffer.create(1) } } }) + t:check(e7 and e7.code == Err.ARG, "a bad segment marker") + local _, e8 = Jpeg.info(buffer.create(0)) + t:check(e8 and Err.is(e8), "info of nothing") + -- truncated frames decode as far as they go or fail with an Err + local cuts, partial = 0, 0 + for cut = 0, #data - 1, #data // 37 do + local img, err = Jpeg.decode(buffer.fromstring(string.sub(data, 1, cut)), 0, nil, { yuv = true }) + t:check(img or Err.is(err), "cut at " .. cut .. ": no image and no Err") + if img then + partial += 1 + t:check(img.meta.truncated, "cut at " .. cut .. ": flagged truncated") + end + cuts += 1 + end + t:note("%d truncated frames, %d decoded partially", cuts, partial) +end + +-- 5. speed (a note; tools/bench.luau has the real numbers) +do + local s = Fx.streams[1] + local frames = {} + for _, f in s.frames do + table.insert(frames, buffer.fromstring(f.data)) + end + local t0, n = os.clock(), 0 + while os.clock() - t0 < 0.3 do + for _, b in frames do + Jpeg.decode(b, 0, nil, { yuv = true }) + n += 1 + end + end + t:note("%dx%d yuv420p decode: %.0f fps", s.width, s.height, n / (os.clock() - t0)) +end + +-- 6. fuzz +do + local samples = {} + for k, s in Fx.streams do + if k % 2 == 1 then + table.insert(samples, s.frames[1].data) + end + end + t:fuzz("decode yuv", function(b: buffer) + return Jpeg.decode(b, 0, nil, { yuv = true }) + end, samples, { mutations = 4, keepHeader = 2 }) + t:fuzz("decode fields", function(b: buffer) + return Jpeg.decode(b, 0, nil, { fields = true }) + end, { Fx.fields.data }, { mutations = 3, garbage = 10 }) +end + +t:done() diff --git a/tools/fixtures/mjpeg.py b/tools/fixtures/mjpeg.py new file mode 100644 index 0000000..63c0eda --- /dev/null +++ b/tools/fixtures/mjpeg.py @@ -0,0 +1,307 @@ +# Motion-JPEG fixtures for codecs/Jpeg (tools/fixtures.py): ffmpeg's mjpeg encoder (testsrc2 / mandelbrot sources, +# yuvj420p / yuvj422p / yuvj444p, odd sizes) split into its JPEG frames, and references for each frame: +# yuv CRC-32 of the yuv420p planes codecs/Jpeg must produce with { yuv = true }: libjpeg-turbo's own IDCT planes +# (TurboJPEG tj3DecompressToYUV8 through ctypes, the islow IDCT), cropped, 4:2:2 chroma row pairs averaged +# ((a + b + 1) >> 1), 4:4:4 chroma 2 x 2 averaged ((a + b + c + d + 2) >> 2): bit-exact +# rgba CRC-32 of djpeg -dct int (bit-exact) +# ff for the first frame of each stream: ffmpeg's own decode as yuvj420p and rgba (PSNR thresholds: ffmpeg's +# IDCT and its swscale conversions differ from libjpeg's; rgba for the small streams and one 320x240) +# Variants: frames written with ffmpeg's default (annex K) Huffman tables and their DHT segments stripped, as +# Motion-JPEG in AVI leaves them out; an AVI1 APP0 segment and junk after EOI; an interlaced frame (two fields, +# each its own half-height JPEG with an AVI1 segment of polarity 1, back to back). +# tests/gen/mjpeg_cases.luau { streams = { { name, width, height, sampling, frames = { { data, yuv, rgba } }, +# ff = { yuv, rgba? } } }, fields = { data, width, height, yuv, rgba, src } } +# tests/gen/mjpeg_enc.luau yuv420p sources and what tj3CompressFromYUV8 writes for them at a quality (our +# encoder must write the same bytes), with djpeg's CRC and ffmpeg's PSNR of that file +# tests/gen/mjpeg_bench.luau 320x240 and 640x480 frames (4:2:0, 4:2:2) and a 640x480 yuv420p source +import ctypes, math, os, shutil, subprocess, tempfile, zlib + +FF = ["-hide_banner", "-loglevel", "error", "-y"] + + +def tool(ctx, pkg, name): + p = shutil.which(name) + if p: + return p + return ctx.nix(pkg, ["sh", "-c", "command -v " + name]).decode().strip() + + +def store(attr): + return subprocess.run(["nix", "build", "nixpkgs#" + attr, "--no-link", "--print-out-paths"], check=True, + capture_output=True, text=True).stdout.strip().split("\n")[0] + + +class TurboJpeg: + """the TurboJPEG 3 API (libjpeg-turbo) through ctypes: raw YUV planes in and out""" + + def __init__(self): + lib = ctypes.CDLL(os.path.join(store("libjpeg_turbo.out"), "lib", "libturbojpeg.so")) + lib.tj3Init.restype = ctypes.c_void_p + lib.tj3Init.argtypes = [ctypes.c_int] + lib.tj3Set.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int] + lib.tj3Get.argtypes = [ctypes.c_void_p, ctypes.c_int] + lib.tj3DecompressHeader.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_size_t] + lib.tj3DecompressToYUV8.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_size_t, ctypes.c_char_p, ctypes.c_int] + lib.tj3CompressFromYUV8.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int, ctypes.c_int, ctypes.c_int, + ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(ctypes.c_size_t)] + lib.tj3Free.argtypes = [ctypes.c_void_p] + self.lib = lib + self.dec = lib.tj3Init(1) + self.enc = lib.tj3Init(0) + + def planes(self, jpeg): + """-> w, h, subsamp (0 444, 1 422, 2 420), Y, Cb, Cr (TurboJPEG's unpadded-alignment plane layout)""" + L = self.lib + assert L.tj3DecompressHeader(self.dec, jpeg, len(jpeg)) == 0 + w, h, ss = L.tj3Get(self.dec, 5), L.tj3Get(self.dec, 6), L.tj3Get(self.dec, 4) + mw, mh = {0: (1, 1), 1: (2, 1), 2: (2, 2)}[ss] + pw, ph = -(-w // mw) * mw, -(-h // mh) * mh + cw, ch = pw // mw, ph // mh + out = ctypes.create_string_buffer(pw * ph + 2 * cw * ch) + assert L.tj3DecompressToYUV8(self.dec, jpeg, len(jpeg), out, 1) == 0 + raw = out.raw + return w, h, ss, (raw[:pw * ph], pw), (raw[pw * ph:pw * ph + cw * ch], cw, ch), (raw[pw * ph + cw * ch:], cw, ch) + + def yuv420(self, jpeg): + """what codecs/Jpeg { yuv = true } must produce for this frame""" + w, h, ss, (Y, pw), cb, cr = self.planes(jpeg) + out = bytearray() + for y in range(h): + out += Y[y * pw:y * pw + w] + ow, oh = (w + 1) // 2, (h + 1) // 2 + for P, cw, ch in (cb, cr): + for y in range(oh): + if ss == 2: + out += P[y * cw:y * cw + ow] + elif ss == 1: + a = P[2 * y * cw:2 * y * cw + ow] + b = P[(2 * y + 1) * cw:(2 * y + 1) * cw + ow] if 2 * y + 1 < ch else a + out += bytes((p + q + 1) >> 1 for p, q in zip(a, b)) + else: + r0 = P[2 * y * cw:2 * y * cw + cw] + r1 = P[(2 * y + 1) * cw:(2 * y + 1) * cw + cw] if 2 * y + 1 < ch else r0 + row = bytearray() + for x in range(ow): + x1 = min(2 * x + 1, w - 1) + row.append((r0[2 * x] + r0[x1] + r1[2 * x] + r1[x1] + 2) >> 2) + out += row + return bytes(out) + + def compress420(self, yuv, w, h, quality): + """yuv420p (w x h luma) -> tj3CompressFromYUV8's JPEG; TurboJPEG wants the luma plane padded to even sizes""" + pw, ph = w + (w & 1), h + (h & 1) + Y = yuv[:w * h] + buf = bytearray() + for y in range(ph): + r = Y[min(y, h - 1) * w:min(y, h - 1) * w + w] + buf += r + r[-1:] * (pw - w) + buf += yuv[w * h:] + L = self.lib + L.tj3Set(self.enc, 3, quality) + L.tj3Set(self.enc, 4, 2) + p, n = ctypes.c_void_p(), ctypes.c_size_t(0) + assert L.tj3CompressFromYUV8(self.enc, bytes(buf), w, 1, h, ctypes.byref(p), ctypes.byref(n)) == 0 + data = ctypes.string_at(p, n.value) + L.tj3Free(p) + return data + + +def split(stream): + """a Motion-JPEG elementary stream -> its JPEG frames (SOI .. EOI)""" + frames, pos = [], 0 + while True: + s = stream.find(b"\xff\xd8", pos) + if s < 0: + return frames + p = s + 2 + while True: + m = stream[p + 1] + if m == 0xD9: + p += 2 + break + ln = (stream[p + 2] << 8) | stream[p + 3] + p += 2 + ln + if m == 0xDA: + while not (stream[p] == 0xFF and stream[p + 1] not in (0,) and not 0xD0 <= stream[p + 1] <= 0xD7): + p += 1 + frames.append(stream[s:p]) + pos = p + + +def strip_dht(jpeg): + out, pos = bytearray(jpeg[:2]), 2 + while pos < len(jpeg): + m = jpeg[pos + 1] + if m == 0xDA: + out += jpeg[pos:] + break + ln = (jpeg[pos + 2] << 8) | jpeg[pos + 3] + if m != 0xC4: + out += jpeg[pos:pos + 2 + ln] + pos += 2 + ln + return bytes(out) + + +def avi1(jpeg, polarity): + """an AVI1 APP0 segment right after SOI (polarity, 0, field size, field size less padding)""" + n = len(jpeg) + 18 + body = b"AVI1" + bytes([polarity, 0]) + n.to_bytes(4, "big") + n.to_bytes(4, "big") + return jpeg[:2] + b"\xff\xe0" + (len(body) + 2).to_bytes(2, "big") + body + jpeg[2:] + + +def generate(ctx): + work = tempfile.mkdtemp(prefix="formats-mjpeg-") + try: + _generate(ctx, work) + finally: + shutil.rmtree(work, ignore_errors=True) + + +def _generate(ctx, work): + ffmpeg = tool(ctx, "ffmpeg", "ffmpeg") + djpeg = os.path.join(os.path.dirname(ctx.nix("libjpeg_turbo", ["sh", "-c", "command -v djpeg"]).decode().strip()), "djpeg") + tj = TurboJpeg() + W = lambda n: os.path.join(work, n) + + def ff(*args): + subprocess.run([ffmpeg] + FF + list(args), check=True, capture_output=True) + + def source(src, w, h, frames, extra=()): + # a raw yuv420p / yuv444p source scaled to w x h (ffmpeg's lavfi sources only make even sizes) + sw, sh = w + (w & 1), h + (h & 1) + return ["-f", "lavfi", "-i", "%s=size=%dx%d:rate=25" % (src, sw, sh), "-frames:v", str(frames), + "-vf", "scale=%d:%d" % (w, h)] + list(extra) + + def rgba_crc(jpeg): + p = W("f.jpg") + open(p, "wb").write(jpeg) + r = subprocess.run([djpeg, "-dct", "int", "-pnm", p], check=True, capture_output=True).stdout + return zlib.crc32(rgba_of_pnm(r)) + + def rgba_of_pnm(d): + # djpeg's "P6\n \n255\n" + RGB -> RGBA + parts = d.split(maxsplit=3) + w, h = int(parts[1]), int(parts[2]) + rgb = d[len(d) - w * h * 3:] + out = bytearray(w * h * 4) + out[0::4], out[1::4], out[2::4] = rgb[0::3], rgb[1::3], rgb[2::3] + out[3::4] = b"\xff" * (w * h) + return bytes(out) + + def ffdecode(jpeg, fmt): + p = W("ff.jpg") + open(p, "wb").write(jpeg) + o = W("ff.raw") + ff("-f", "mjpeg", "-i", p, "-f", "rawvideo", "-pix_fmt", fmt, o) + return open(o, "rb").read() + + streams = [] + + def stream(name, src, w, h, pix, nframes, encargs=(), mutate=None): + out = W(name + ".mjpeg") + ff(*source(src, w, h, nframes), "-pix_fmt", pix, "-c:v", "mjpeg", *encargs, "-f", "mjpeg", out) + frames = split(open(out, "rb").read()) + assert len(frames) == nframes, (name, len(frames)) + entries = [] + for fr in frames: + ref = fr + data = mutate(fr) if mutate else fr + entries.append({"data": data, "yuv": zlib.crc32(tj.yuv420(ref)), "rgba": rgba_crc(ref)}) + ref = {"yuv": ffdecode(frames[0], "yuvj420p")} + if w * h <= 30000 or name == "testsrc_420": # keep tests/gen small: rgba for the small ones and one 320x240 + ref["rgba"] = ffdecode(frames[0], "rgba") + streams.append({"name": name, "width": w, "height": h, "sampling": pix[4:7], "frames": entries, "ff": ref}) + + stream("testsrc_420", "testsrc2", 320, 240, "yuvj420p", 4, ("-q:v", "3")) + stream("testsrc_422", "testsrc2", 320, 240, "yuvj422p", 4, ("-q:v", "3")) + stream("mandel_444", "mandelbrot", 176, 144, "yuvj444p", 2, ("-q:v", "4")) + stream("odd_420", "mandelbrot", 173, 97, "yuvj420p", 3, ("-q:v", "6")) + stream("odd_422", "testsrc2", 97, 61, "yuvj422p", 3, ("-q:v", "2")) + stream("odd_444", "testsrc2", 33, 17, "yuvj444p", 2, ("-q:v", "2")) + stream("q31_420", "testsrc2", 160, 120, "yuvj420p", 2, ("-q:v", "31")) + # Motion-JPEG as AVI stores it: the annex K tables left out + stream("nodht_420", "mandelbrot", 320, 240, "yuvj420p", 3, ("-q:v", "4", "-huffman", "default"), strip_dht) + stream("nodht_422", "testsrc2", 176, 144, "yuvj422p", 3, ("-q:v", "4", "-huffman", "default"), strip_dht) + # an AVI1 segment (progressive, polarity 0) and padding / junk after EOI + stream("avi1_junk", "testsrc2", 160, 120, "yuvj420p", 2, ("-q:v", "5"), + lambda f: avi1(f, 0) + b"\0\0\0\0\xff\xd9junk after the image\xff\xd8") + + # an interlaced frame: two fields of 320 x 120, each its own JPEG with AVI1 polarity 1, back to back + full = W("full.yuv") + ff(*source("testsrc2", 320, 240, 1), "-pix_fmt", "yuv420p", "-f", "rawvideo", full) + fy = open(full, "rb").read() + fw, fh = 320, 240 + fields, fsrc = [], [] + for k in range(2): + rows = b"".join(fy[y * fw:(y + 1) * fw] for y in range(k, fh, 2)) + cw = fw // 2 + chroma = b"" + for pl in range(2): + base = fw * fh + pl * cw * (fh // 2) + chroma += b"".join(fy[base + y * cw:base + (y + 1) * cw] for y in range(k, fh // 2, 2)) + p = W("field%d.yuv" % k) + open(p, "wb").write(rows + chroma) + o = W("field%d.jpg" % k) + ff("-f", "rawvideo", "-pix_fmt", "yuvj420p", "-s", "%dx%d" % (fw, fh // 2), "-i", p, "-pix_fmt", "yuvj420p", + "-c:v", "mjpeg", "-q:v", "3", "-f", "mjpeg", o) + fields.append(open(o, "rb").read()) + data = avi1(fields[0], 1) + b"\0" * 7 + avi1(fields[1], 1) + + def weave(a, b, w, hf, bpp): + out = bytearray() + for y in range(2 * hf): + src, k = (a, y // 2) if y % 2 == 0 else (b, y // 2) + out += src[k * w * bpp:(k + 1) * w * bpp] + return bytes(out) + + ya, yb = tj.yuv420(fields[0]), tj.yuv420(fields[1]) + hf, cw, chf = fh // 2, fw // 2, fh // 4 + wy = weave(ya[:fw * hf], yb[:fw * hf], fw, hf, 1) + for pl in range(2): + o = fw * hf + pl * cw * chf + wy += weave(ya[o:o + cw * chf], yb[o:o + cw * chf], cw, chf, 1) + + def rgba_raw(jpeg): + p = W("f.jpg") + open(p, "wb").write(jpeg) + return rgba_of_pnm(subprocess.run([djpeg, "-dct", "int", "-pnm", p], check=True, capture_output=True).stdout) + + wr = weave(rgba_raw(fields[0]), rgba_raw(fields[1]), fw, hf, 4) + ctx.emit("mjpeg_cases", {"streams": streams, "fields": {"data": data, "width": fw, "height": fh, + "yuv": zlib.crc32(wy), "rgba": zlib.crc32(wr), "src": fy}}) + + # the encoder: yuv420p sources, byte-identical with tj3CompressFromYUV8 + enc = [] + for name, src, w, h, qs in (("testsrc_320x240", "testsrc2", 320, 240, (50, 75, 90)), + ("mandel_176x144", "mandelbrot", 176, 144, (30, 95)), + ("odd_97x61", "testsrc2", 97, 61, (75,)), ("tiny_7x5", "mandelbrot", 7, 5, (90,)), + ("one_1x1", "testsrc2", 1, 1, (90,))): + p = W(name + ".yuv") + ff(*source(src, max(w, 2), max(h, 2), 1), "-pix_fmt", "yuv420p", "-f", "rawvideo", W("s.yuv")) + raw = open(W("s.yuv"), "rb").read() + if (w, h) == (1, 1): + raw = raw[:1] + raw[4:5] + raw[5:6] # the top-left luma and chroma samples of a 2x2 source + open(p, "wb").write(raw) + for q in qs: + want = tj.compress420(raw, w, h, q) + got = ffdecode(want, "yuvj420p") if w > 1 else None + psnr = 99.0 + if got: + se = sum((a - b) ** 2 for a, b in zip(got[:w * h], raw[:w * h])) + psnr = 99.0 if se == 0 else 10 * math.log10(255 * 255 * w * h / se) + enc.append({"name": "%s_q%d" % (name, q), "width": w, "height": h, "quality": q, "yuv": raw, + "want": want, "rgba": rgba_crc(want), "ffpsnr": round(psnr, 3)}) + ctx.emit("mjpeg_enc", enc) + + bench = [] + for name, w, h, pix in (("320x240 4:2:0", 320, 240, "yuvj420p"), ("640x480 4:2:0", 640, 480, "yuvj420p"), + ("640x480 4:2:2", 640, 480, "yuvj422p")): + o = W("bench.mjpeg") + ff(*source("testsrc2", w, h, 1), "-pix_fmt", pix, "-c:v", "mjpeg", "-q:v", "3", "-f", "mjpeg", o) + fr = split(open(o, "rb").read())[0] + bench.append({"name": name, "width": w, "height": h, "data": fr, "yuv": zlib.crc32(tj.yuv420(fr))}) + srcs = [] + for w, h in ((320, 240), (640, 480)): + ff(*source("testsrc2", w, h, 1), "-pix_fmt", "yuv420p", "-f", "rawvideo", W("b.yuv")) + srcs.append({"width": w, "height": h, "yuv": open(W("b.yuv"), "rb").read()}) + ctx.emit("mjpeg_bench", {"frames": bench, "sources": srcs}) From 33a5a5b409805afbd61d6f172093c839dd29350a Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:37:01 -0500 Subject: [PATCH 3/6] ws-video-codecs: codecs/Jpeg: yuv output crops four samples per write and reuses one frame-sized IDCT plane between calls --- src/Formats/codecs/Jpeg/Decode.luau | 17 ++++++++++++++++- src/Formats/codecs/Jpeg/Yuv.luau | 22 +++++++++++----------- 2 files changed, 27 insertions(+), 12 deletions(-) diff --git a/src/Formats/codecs/Jpeg/Decode.luau b/src/Formats/codecs/Jpeg/Decode.luau index 3d88b8d..05a0a7f 100644 --- a/src/Formats/codecs/Jpeg/Decode.luau +++ b/src/Formats/codecs/Jpeg/Decode.luau @@ -679,6 +679,21 @@ end -- horizontally ("422", 2x1 / 1x1 or ffmpeg's 2x2 / 1x2: each pair of chroma rows averaged, rounding up); at the luma -- rate ("444", 1x1 or ffmpeg's 1x2 everywhere: each 2 x 2 chroma block averaged, rounding to nearest); grey ("gray": -- chroma 128). Full scale only (opts.scale = 1). +-- one IDCT plane at a time is live (each is cropped into the output before the next component): frame-sized planes +-- (up to 4 MB) are kept between calls, so a stream of video frames does not allocate them per frame +local scratch: buffer? = nil +local function scratchPlane(n: number): buffer + local sc = scratch + if sc and buffer.len(sc) >= n then + return sc + end + local b = buffer.create(n) + if n <= 4 * 1024 * 1024 then + scratch = b + end + return b +end + function Decode.outputYuv(st: State): (number?, number?, buffer?, string?) local f: Frame = st.frame if st.scale ~= 1 or f.precision ~= 8 then @@ -719,7 +734,7 @@ function Decode.outputYuv(st: State): (number?, number?, buffer?, string?) 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 plane = scratchPlane(stride * rows * 2) local coef = c.coef or buffer.create(c.bpl * c.bpc * 128) local q = c.quant if not q then diff --git a/src/Formats/codecs/Jpeg/Yuv.luau b/src/Formats/codecs/Jpeg/Yuv.luau index 7ca340c..edb2778 100644 --- a/src/Formats/codecs/Jpeg/Yuv.luau +++ b/src/Formats/codecs/Jpeg/Yuv.luau @@ -5,27 +5,27 @@ -- 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 readu16, writeu8, readu32, writeu32 = buffer.readu16, buffer.writeu8, buffer.readu32, buffer.writeu32 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 + local quads = w // 4 + local rest = w - quads * 4 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 + -- four samples (two u32 reads of two u16 samples, each 0..255) per u32 write + for _ = 1, quads do + local a, b = readu32(src, s), readu32(src, s + 4) + writeu32(dst, d, a % 65536 + (a // 65536) * 256 + (b % 65536) * 65536 + (b // 65536) * 16777216) + s += 8 + d += 4 end - if w % 2 == 1 then - writeu8(dst, d, readu16(src, s)) + for k = 0, rest - 1 do + writeu8(dst, d + k, readu16(src, s + k * 2)) end end end From 2493b9db36a4021cc9cd106637600d05cce99bd5 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:41:27 -0500 Subject: [PATCH 4/6] ws-video-codecs: codecs/Mpeg1 absorbed from mpeg1-luau e2e2898 (jsmpeg port, MIT: licenses/jsmpeg-MIT.txt + NOTICE); requires and headers, frameImage (yuv420p / rgba8 copies); IDCT kept (bit-identical to codecs/Dct islow in put mode, but MPEG adds residuals before clamping); tests/codecs/mpeg1.luau + tools/fixtures/mpeg1.py (base64 / zlib fixtures, 5.6 MB) --- docs/FORMATS.md | 1 + licenses/NOTICE.md | 1 + licenses/jsmpeg-MIT.txt | 8 + src/Formats/codecs/Jpeg/init.luau | 2 +- src/Formats/codecs/Mpeg1/Decoder.luau | 1136 +++++++++++++++++++++++++ src/Formats/codecs/Mpeg1/Tables.luau | 117 +++ src/Formats/codecs/Mpeg1/Vlc.luau | 116 +++ src/Formats/codecs/Mpeg1/init.luau | 262 ++++++ tests/codecs/mpeg1.luau | 413 +++++++++ tools/fixtures/mpeg1.py | 170 ++++ 10 files changed, 2225 insertions(+), 1 deletion(-) create mode 100644 licenses/jsmpeg-MIT.txt create mode 100644 src/Formats/codecs/Mpeg1/Decoder.luau create mode 100644 src/Formats/codecs/Mpeg1/Tables.luau create mode 100644 src/Formats/codecs/Mpeg1/Vlc.luau create mode 100644 src/Formats/codecs/Mpeg1/init.luau create mode 100644 tests/codecs/mpeg1.luau create mode 100644 tools/fixtures/mpeg1.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index c5f7b88..c3baa23 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -72,6 +72,7 @@ Codecs (layer 1, shared by formats; not loadable on their own): - codecs/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. A codec (layer 3): - codecs/Lzw: LZW decoder and encoder in the two variants file formats use. A codec (layer 1): image/gif and - codecs/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). Walks +- codecs/Mpeg1: an MPEG-1 video decoder (ISO/IEC 11172-2) for the MPEG-TS / MPEG-PS video formats. Absorbed from - codecs/Quantize: palette quantization of rgba8 pixels. A codec (layer 1): image/gif (and later any palette - codecs/Raster: an antialiased scanline rasterizer for paths of lines, quadratic and cubic Béziers, under an affine - codecs/Text: text decoding helpers for the text formats: a UTF-8 BOM is stripped, text that is not valid UTF-8 is diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index 75c8972..a419d52 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -19,6 +19,7 @@ | `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/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 | +| `src/Formats/codecs/Mpeg1/` (init, Decoder, Vlc, Tables) | mpeg1-luau e2e2898 (same author), a port of jsmpeg's MPEG-1 video decoder (https://github.com/phoboslab/jsmpeg, src/mpeg1.js; the tables are generated from it) by Dominic Szablewski | MIT: [jsmpeg-MIT.txt](jsmpeg-MIT.txt) | | `tests/fixtures/pngsuite/` | PngSuite by Willem van Schaik | [PngSuite-LICENSE.txt](PngSuite-LICENSE.txt) | | `tests/fixtures/vox/{chr_knight,chr_sword,deer,maze}.vox`, `tests/fixtures/vox/MagicaVoxel-file-format-vox*.txt` (the format spec) | ephtracy/voxel-model (MagicaVoxel sample models) | MIT: [voxel-model-LICENSE.txt](voxel-model-LICENSE.txt) | | `tests/fixtures/vox/ogt_*.vox` | jpaver/opengametools `demo/vox/` (files saved by MagicaVoxel 0.99.x) | MIT: [opengametools-LICENSE.txt](opengametools-LICENSE.txt) | diff --git a/licenses/jsmpeg-MIT.txt b/licenses/jsmpeg-MIT.txt new file mode 100644 index 0000000..896c374 --- /dev/null +++ b/licenses/jsmpeg-MIT.txt @@ -0,0 +1,8 @@ +The MIT License (MIT) +Copyright (c) 2017 Dominic Szablewski + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/src/Formats/codecs/Jpeg/init.luau b/src/Formats/codecs/Jpeg/init.luau index e7a930e..ef3323d 100644 --- a/src/Formats/codecs/Jpeg/init.luau +++ b/src/Formats/codecs/Jpeg/init.luau @@ -296,7 +296,7 @@ function Jpeg.decode(buf: buffer, off: number?, len: number?, opts: DecodeOption local truncated = img.meta.truncated or b.meta.truncated img = weave(img, b) img.meta.truncated = truncated - img.meta.source.fields = 2 + (img.meta.source :: any).fields = 2 end end end diff --git a/src/Formats/codecs/Mpeg1/Decoder.luau b/src/Formats/codecs/Mpeg1/Decoder.luau new file mode 100644 index 0000000..c9a054c --- /dev/null +++ b/src/Formats/codecs/Mpeg1/Decoder.luau @@ -0,0 +1,1136 @@ +--!strict +--!native +-- codecs/Mpeg1/Decoder: the MPEG-1 video decoding core (ISO/IEC 11172-2; native, never throws): I, P and B pictures, +-- half-pel motion compensation, custom quantiser matrices, sequence headers anywhere in the stream. Absorbed from +-- mpeg1-luau e2e2898 (same author; src/Mpeg1/Decoder.luau, unchanged but for this header and the requires), a port +-- of jsmpeg's decoder (src/mpeg1.js by Dominic Szablewski, MIT, licenses/jsmpeg-MIT.txt) with these changes for +-- speed and accuracy in Luau: +-- * table-driven VLC decoding (Vlc.luau) on a 32-bit peek instead of a bit-by-bit tree walk; +-- * an accurate integer IDCT (the LL&M / "islow" factorisation, 13-bit constants) instead of jsmpeg's AAN +-- approximation, so P-picture drift stays close to ffmpeg's decode; dequantisation follows the standard +-- (magnitude, truncation toward zero, oddification); +-- * B pictures (forward, backward and interpolated prediction, skipped macroblocks), which jsmpeg skips; +-- * motion compensation four bytes at a time (SWAR rounding averages); +-- * BT.601 limited-range YCbCr -> RGBA8 (jsmpeg's canvas path treats Y as full range). +-- +-- The IDCT is not codecs/Dct's: it computes the same islow transform (its put mode is bit-identical to +-- Dct.idctBlock with a unit quantiser and no level shift, checked on 20000 random blocks), but MPEG-1 adds the +-- residual of P / B blocks to the prediction before clamping, dequantises into i32 coefficients itself (MPEG +-- rounding and oddification, not JPEG's q multiply) and writes u8 samples four per writeu32, where Dct clamps to +-- 0..maxv, dequantises JPEG-style and writes u16 planes. +-- +-- Everything works on flat buffers allocated per sequence size: no allocation per block, macroblock or picture. +-- Native code must never throw (an error unwinding through native code crashes Roblox Studio): every read +-- position is checked against the data end (plus a zero pad that bounds the overrun of one macroblock), motion +-- vectors are clamped to the reference picture, and bad data ends the slice instead of raising. +local V = require("@formats/codecs/Mpeg1/Vlc") +local T = require("@formats/codecs/Mpeg1/Tables") + +local readu8 = buffer.readu8 +local writeu8 = buffer.writeu8 +local readu32 = buffer.readu32 +local writeu32 = buffer.writeu32 +local readi32 = buffer.readi32 +local writei32 = buffer.writei32 +local band = bit32.band +local bor = bit32.bor +local bxor = bit32.bxor +local lshift = bit32.lshift +local rshift = bit32.rshift +local bswap = bit32.byteswap + +local PAD = 4096 -- zero bytes after the data: a macroblock reads at most ~1.5 KB, the pos check runs per macroblock + +local D = {} + +D.PICTURE_I = 1 +D.PICTURE_P = 2 +D.PICTURE_B = 3 + +local ZZ = buffer.create(64) +local DEF_INTRA = buffer.create(64) -- scan order (Q[n] = matrix[ZZ[n]]) +local DEF_NON_INTRA = buffer.create(64) +for i = 0, 63 do + buffer.writeu8(ZZ, i, T.ZIG_ZAG[i]) + buffer.writeu8(DEF_INTRA, i, T.DEFAULT_INTRA_QUANT_MATRIX[T.ZIG_ZAG[i]]) + buffer.writeu8(DEF_NON_INTRA, i, T.DEFAULT_NON_INTRA_QUANT_MATRIX[T.ZIG_ZAG[i]]) +end + +-- clamp to 0..255 by lookup: CLAMP[v + COFF] for any v in [-COFF, COFF]. IDCT outputs are bounded by +-- 64 * 2048 / 4 = 32768 for any coefficients, plus a prediction of up to 255. +local COFF = 40000 +local CLAMP = buffer.create(2 * COFF + 256) +for i = 0, 2 * COFF + 255 do + buffer.writeu8(CLAMP, i, math.clamp(i - COFF, 0, 255)) +end + +-- BT.601 limited range: R = 1.164 (Y - 16) + 1.596 (Cr - 128), G = 1.164 (Y - 16) - 0.392 (Cb - 128) - 0.813 (Cr - +-- 128), B = 1.164 (Y - 16) + 2.017 (Cb - 128), in 8-bit fixed point. The rounding offsets (-128, -160, -72 / 256) +-- are fitted to ffmpeg's swscale output, which lands about half a level below round-to-nearest. +-- the constant terms, plus COFF * 256 so the sums stay positive for rshift +local RBIAS = COFF * 256 - 298 * 16 - 409 * 128 - 128 +local GBIAS = COFF * 256 - 298 * 16 + 100 * 128 + 208 * 128 - 160 +local BBIAS = COFF * 256 - 298 * 16 - 516 * 128 - 72 + +local MBAI, MBAI_BITS = V.MBAI, V.MBAI_BITS +local CBP, CBP_BITS = V.CBP, V.CBP_BITS +local MOTION, MOTION_BITS = V.MOTION, V.MOTION_BITS +local DC_LUMA, DC_LUMA_BITS = V.DC_LUMA, V.DC_LUMA_BITS +local DC_CHROMA, DC_CHROMA_BITS = V.DC_CHROMA, V.DC_CHROMA_BITS +local DCT_FIRST, DCT_NEXT = V.DCT_FIRST, V.DCT_NEXT +local SUB, ESC, EOB = V.SUB, V.ESC, V.EOB +local MBTYPE = { V.MBTYPE_I, V.MBTYPE_P, V.MBTYPE_B } +local MBTYPE_BITS = { V.MBTYPE_I_BITS, V.MBTYPE_P_BITS, V.MBTYPE_B_BITS } + +-- Integer IDCT (LL&M factorisation as in the IJG "islow" IDCT: CONST_BITS 13, PASS1_BITS 2) of the 64 i32 +-- coefficients in blk (natural order), written to dst (put) or added to it (add), clamped to 0..255. +local function idct(blk: buffer, ws: buffer, dst: buffer, off: number, stride: number, add: boolean) + -- pass 1: columns, into ws scaled by 4 + for c = 0, 28, 4 do + local d0 = readi32(blk, c) + local d1 = readi32(blk, c + 32) + local d2 = readi32(blk, c + 64) + local d3 = readi32(blk, c + 96) + local d4 = readi32(blk, c + 128) + local d5 = readi32(blk, c + 160) + local d6 = readi32(blk, c + 192) + local d7 = readi32(blk, c + 224) + if d1 == 0 and d2 == 0 and d3 == 0 and d4 == 0 and d5 == 0 and d6 == 0 and d7 == 0 then + local dc = d0 * 4 + writei32(ws, c, dc) + writei32(ws, c + 32, dc) + writei32(ws, c + 64, dc) + writei32(ws, c + 96, dc) + writei32(ws, c + 128, dc) + writei32(ws, c + 160, dc) + writei32(ws, c + 192, dc) + writei32(ws, c + 224, dc) + else + -- even part + local z1 = (d2 + d6) * 4433 + local t2 = z1 - d6 * 15137 + local t3 = z1 + d2 * 6270 + local t0 = (d0 + d4) * 8192 + local t1 = (d0 - d4) * 8192 + local t10 = t0 + t3 + local t13 = t0 - t3 + local t11 = t1 + t2 + local t12 = t1 - t2 + -- odd part + local o0, o1, o2, o3 = d7, d5, d3, d1 + local y1 = o0 + o3 + local y2 = o1 + o2 + local y3 = o0 + o2 + local y4 = o1 + o3 + local z5 = (y3 + y4) * 9633 + o0 *= 2446 + o1 *= 16819 + o2 *= 25172 + o3 *= 12299 + y1 *= -7373 + y2 *= -20995 + y3 = y3 * -16069 + z5 + y4 = y4 * -3196 + z5 + o0 += y1 + y3 + o1 += y2 + y4 + o2 += y2 + y3 + o3 += y1 + y4 + writei32(ws, c, (t10 + o3 + 1024) // 2048) + writei32(ws, c + 224, (t10 - o3 + 1024) // 2048) + writei32(ws, c + 32, (t11 + o2 + 1024) // 2048) + writei32(ws, c + 192, (t11 - o2 + 1024) // 2048) + writei32(ws, c + 64, (t12 + o1 + 1024) // 2048) + writei32(ws, c + 160, (t12 - o1 + 1024) // 2048) + writei32(ws, c + 96, (t13 + o0 + 1024) // 2048) + writei32(ws, c + 128, (t13 - o0 + 1024) // 2048) + end + end + -- pass 2: rows, descaled by 2^18 (13 + 2 + 3), into the picture + for r = 0, 224, 32 do + local d0 = readi32(ws, r) + local d1 = readi32(ws, r + 4) + local d2 = readi32(ws, r + 8) + local d3 = readi32(ws, r + 12) + local d4 = readi32(ws, r + 16) + local d5 = readi32(ws, r + 20) + local d6 = readi32(ws, r + 24) + local d7 = readi32(ws, r + 28) + local p0, p1, p2, p3, p4, p5, p6, p7 + if d1 == 0 and d2 == 0 and d3 == 0 and d4 == 0 and d5 == 0 and d6 == 0 and d7 == 0 then + local v = (d0 + 16) // 32 + p0, p1, p2, p3, p4, p5, p6, p7 = v, v, v, v, v, v, v, v + else + local z1 = (d2 + d6) * 4433 + local t2 = z1 - d6 * 15137 + local t3 = z1 + d2 * 6270 + local t0 = (d0 + d4) * 8192 + local t1 = (d0 - d4) * 8192 + local t10 = t0 + t3 + 131072 + local t13 = t0 - t3 + 131072 + local t11 = t1 + t2 + 131072 + local t12 = t1 - t2 + 131072 + local o0, o1, o2, o3 = d7, d5, d3, d1 + local y1 = o0 + o3 + local y2 = o1 + o2 + local y3 = o0 + o2 + local y4 = o1 + o3 + local z5 = (y3 + y4) * 9633 + o0 *= 2446 + o1 *= 16819 + o2 *= 25172 + o3 *= 12299 + y1 *= -7373 + y2 *= -20995 + y3 = y3 * -16069 + z5 + y4 = y4 * -3196 + z5 + o0 += y1 + y3 + o1 += y2 + y4 + o2 += y2 + y3 + o3 += y1 + y4 + p0 = (t10 + o3) // 262144 + p7 = (t10 - o3) // 262144 + p1 = (t11 + o2) // 262144 + p6 = (t11 - o2) // 262144 + p2 = (t12 + o1) // 262144 + p5 = (t12 - o1) // 262144 + p3 = (t13 + o0) // 262144 + p4 = (t13 - o0) // 262144 + end + if add then + p0 += readu8(dst, off) + p1 += readu8(dst, off + 1) + p2 += readu8(dst, off + 2) + p3 += readu8(dst, off + 3) + p4 += readu8(dst, off + 4) + p5 += readu8(dst, off + 5) + p6 += readu8(dst, off + 6) + p7 += readu8(dst, off + 7) + end + writeu32( + dst, + off, + readu8(CLAMP, p0 + COFF) + + readu8(CLAMP, p1 + COFF) * 256 + + readu8(CLAMP, p2 + COFF) * 65536 + + readu8(CLAMP, p3 + COFF) * 16777216 + ) + writeu32( + dst, + off + 4, + readu8(CLAMP, p4 + COFF) + + readu8(CLAMP, p5 + COFF) * 256 + + readu8(CLAMP, p6 + COFF) * 65536 + + readu8(CLAMP, p7 + COFF) * 16777216 + ) + off += stride + end +end +D.idct = idct + +-- a constant 8x8 block (DC only): put or add v +local function fillBlock(dst: buffer, off: number, stride: number, v: number, add: boolean) + if not add then + local c = readu8(CLAMP, v + COFF) * 0x01010101 + for _ = 1, 8 do + writeu32(dst, off, c) + writeu32(dst, off + 4, c) + off += stride + end + else + for _ = 1, 8 do + for i = off, off + 7 do + writeu8(dst, i, readu8(CLAMP, readu8(dst, i) + v + COFF)) + end + off += stride + end + end +end + +-- Motion-compensated prediction of a size x size block (16 luma, 8 chroma) from src at sOff to dst at dOff with +-- half-pel flags hx / hy; avg averages into what dst holds (the second prediction of a B macroblock). Four bytes at +-- a time: avg(a, b) rounding up = (a | b) - ((a ^ b) & 0xFE..) >> 1; the 4-tap average splits each byte into its +-- low 2 bits and high 6 bits so no lane overflows. +local function mc(src: buffer, dst: buffer, stride: number, sOff: number, dOff: number, size: number, hx: number, hy: number, avg: boolean) + for _ = 1, size do + for i = 0, size - 4, 4 do + local p + if hx == 0 then + if hy == 0 then + p = readu32(src, sOff + i) + else + local a, b = readu32(src, sOff + i), readu32(src, sOff + i + stride) + p = bor(a, b) - rshift(band(bxor(a, b), 0xFEFEFEFE), 1) + end + elseif hy == 0 then + local a, b = readu32(src, sOff + i), readu32(src, sOff + i + 1) + p = bor(a, b) - rshift(band(bxor(a, b), 0xFEFEFEFE), 1) + else + local a, b = readu32(src, sOff + i), readu32(src, sOff + i + 1) + local c, d = readu32(src, sOff + i + stride), readu32(src, sOff + i + stride + 1) + local l = band(a, 0x03030303) + band(b, 0x03030303) + band(c, 0x03030303) + band(d, 0x03030303) + 0x02020202 + local h = rshift(band(a, 0xFCFCFCFC), 2) + rshift(band(b, 0xFCFCFCFC), 2) + rshift(band(c, 0xFCFCFCFC), 2) + rshift(band(d, 0xFCFCFCFC), 2) + p = h + band(rshift(l, 2), 0x0F0F0F0F) + end + if avg then + local q = readu32(dst, dOff + i) + p = bor(p, q) - rshift(band(bxor(p, q), 0xFEFEFEFE), 1) + end + writeu32(dst, dOff + i, p) + end + sOff += stride + dOff += stride + end +end +D.mc = mc + +-- YCbCr 4:2:0 planes (coded strides) -> RGBA8 (alpha 255), w x h, nearest chroma like ffmpeg's default swscale path +local function toRgba(Y: buffer, Cb: buffer, Cr: buffer, cw: number, w: number, h: number, out: buffer) + -- 2 x 2 pixels per chroma sample: the chroma terms are computed once per block of four + local chw = cw // 2 + local w2 = w // 2 -- whole pixel pairs per row + local stride = w * 4 + for y = 0, h - 1, 2 do + local yo = y * cw + local co = (y // 2) * chw + local o = y * stride + local two = y + 1 < h + for _ = 1, w2 do + local cb, cr = readu8(Cb, co), readu8(Cr, co) + co += 1 + local rr = cr * 409 + RBIAS + local gg = GBIAS - cb * 100 - cr * 208 + local bb = cb * 516 + BBIAS + local yv = readu8(Y, yo) * 298 + writeu32(out, o, math.clamp(rshift(yv + rr, 8) - COFF, 0, 255) + math.clamp(rshift(yv + gg, 8) - COFF, 0, 255) * 256 + math.clamp(rshift(yv + bb, 8) - COFF, 0, 255) * 65536 + 0xFF000000) + yv = readu8(Y, yo + 1) * 298 + writeu32(out, o + 4, math.clamp(rshift(yv + rr, 8) - COFF, 0, 255) + math.clamp(rshift(yv + gg, 8) - COFF, 0, 255) * 256 + math.clamp(rshift(yv + bb, 8) - COFF, 0, 255) * 65536 + 0xFF000000) + if two then + yv = readu8(Y, yo + cw) * 298 + writeu32(out, o + stride, math.clamp(rshift(yv + rr, 8) - COFF, 0, 255) + math.clamp(rshift(yv + gg, 8) - COFF, 0, 255) * 256 + math.clamp(rshift(yv + bb, 8) - COFF, 0, 255) * 65536 + 0xFF000000) + yv = readu8(Y, yo + cw + 1) * 298 + writeu32(out, o + stride + 4, math.clamp(rshift(yv + rr, 8) - COFF, 0, 255) + math.clamp(rshift(yv + gg, 8) - COFF, 0, 255) * 256 + math.clamp(rshift(yv + bb, 8) - COFF, 0, 255) * 65536 + 0xFF000000) + end + yo += 2 + o += 8 + end + if w % 2 == 1 then + -- the last column of an odd width + local cb, cr = readu8(Cb, co), readu8(Cr, co) + local rr = cr * 409 + RBIAS + local gg = GBIAS - cb * 100 - cr * 208 + local bb = cb * 516 + BBIAS + for k = 0, if two then 1 else 0 do + local yv = readu8(Y, yo + k * cw) * 298 + writeu32(out, o + k * stride, math.clamp(rshift(yv + rr, 8) - COFF, 0, 255) + math.clamp(rshift(yv + gg, 8) - COFF, 0, 255) * 256 + math.clamp(rshift(yv + bb, 8) - COFF, 0, 255) * 65536 + 0xFF000000) + end + end + end +end +D.toRgba = toRgba + +export type Store = { y: buffer, cb: buffer, cr: buffer, w: number, h: number, cw: number, tref: number, ptype: number, tag: any } + +export type Core = { + -- data + write: (src: buffer, off: number, n: number) -> (), + -- decodes the next picture; atEnd: the end of the data ends the picture. Returns the store decoded into (nil when + -- no picture is complete or it could not be decoded), and whether more data is needed. + nextPicture: (atEnd: boolean, tag: any) -> (Store?, boolean), + toRgba: (s: Store, out: buffer) -> (), + reset: () -> (), + state: { + width: number, + height: number, + codedWidth: number, + codedHeight: number, + frameRate: number, + aspect: number, + bitRate: number, + sizeChanged: boolean, + pictures: number, + errors: number, + skipped: number, + clamped: number, -- motion vectors pointing outside the reference (clamped) + maxPixels: number, + refOld: Store?, + refNew: Store?, + }, +} + +function D.new(maxPixels: number?): Core + local state = { + width = 0, + height = 0, + codedWidth = 0, + codedHeight = 0, + frameRate = 0, + aspect = 0, + bitRate = 0, + sizeChanged = false, + pictures = 0, + errors = 0, + skipped = 0, + clamped = 0, + maxPixels = maxPixels or 4096 * 2304, + refOld = nil :: Store?, + refNew = nil :: Store?, + } + + -- bitstream + local data = buffer.create(64 * 1024 + PAD) + local dataLen = 0 + local readByte = 0 -- next byte to look at for a start code + local scanPos = 0 -- resume point of the picture-end scan + local pos = 0 -- bit position inside data + local err = false + + -- sequence + local hasSeq = false + local mbW, mbH, mbSize = 0, 0, 0 + local cw, chw = 0, 0 -- luma / chroma strides (coded widths) + local intraQ = buffer.create(64) + local nonIntraQ = buffer.create(64) + buffer.copy(intraQ, 0, DEF_INTRA, 0, 64) + buffer.copy(nonIntraQ, 0, DEF_NON_INTRA, 0, 64) + local stores: { Store } = {} + local bStore: Store? = nil + + -- picture / slice / macroblock state + local ptype = 0 + local fullPelFw, fwRSize, fwF = false, 0, 1 + local fullPelBw, bwRSize, bwF = false, 0, 1 + local curY, curCb, curCr = data, data, data + local fwY, fwCb, fwCr = data, data, data + local bwY, bwCb, bwCr = data, data, data + local qs = 1 + local mbAddr, mbRow, mbCol = 0, 0, 0 + local dcY, dcCb, dcCr = 128, 128, 128 + local pmvFwH, pmvFwV, pmvBwH, pmvBwV = 0, 0, 0, 0 + local mvFwH, mvFwV, mvBwH, mvBwV = 0, 0, 0, 0 + local mbIntra = false + local motFw, motBw = false, false + local blk = buffer.create(256) + local ws = buffer.create(256) + + local function peek32(): number + local bp = rshift(pos, 3) + local w = bswap(readu32(data, bp)) + local s = band(pos, 7) + if s ~= 0 then + w = bor(lshift(w, s), rshift(readu8(data, bp + 4), 8 - s)) + end + return w + end + + local function read(n: number): number + local v = rshift(peek32(), 32 - n) + pos += n + return v + end + + local function vlc(lut: buffer, k: number): number + local e = readu32(lut, rshift(peek32(), 32 - k) * 4) + local l = rshift(e, 16) + if l == 0 then + err = true + return 0 + end + pos += l + return band(e, 0xFFFF) - 32768 + end + + -- byte offset of the next 00 00 01 xx at or after from (with xx before to), or -1 + local function findStart(from: number, to: number): number + local i = from + while i + 3 < to do + local c = readu8(data, i + 2) + if c > 1 then + i += 3 + elseif c == 1 then + if readu8(data, i) == 0 and readu8(data, i + 1) == 0 then + return i + end + i += 3 + else + i += 1 + end + end + return -1 + end + + local function newStore(): Store + local sz = cw * mbH * 16 + local y = buffer.create(sz) + local cb = buffer.create(sz // 4) + local cr = buffer.create(sz // 4) + buffer.fill(y, 0, 16) -- black until a picture is decoded into it + buffer.fill(cb, 0, 128) + buffer.fill(cr, 0, 128) + return { y = y, cb = cb, cr = cr, w = state.width, h = state.height, cw = cw, tref = 0, ptype = 0, tag = nil } + end + + -- sequence header at byte p (after the start code); returns false when invalid + local function sequenceHeader(p: number): boolean + pos = p * 8 + local w = read(12) + local h = read(12) + local aspect = read(4) + local rate = read(4) + local bitRate = read(18) + pos += 1 + 10 + 1 -- marker, vbv_buffer_size, constrained_parameters_flag + if w == 0 or h == 0 or w * h > state.maxPixels then + return false + end + if read(1) == 1 then + for i = 0, 63 do + local v = read(8) + writeu8(intraQ, i, if v == 0 then 1 else v) + end + else + buffer.copy(intraQ, 0, DEF_INTRA, 0, 64) + end + if read(1) == 1 then + for i = 0, 63 do + local v = read(8) + writeu8(nonIntraQ, i, if v == 0 then 1 else v) + end + else + buffer.copy(nonIntraQ, 0, DEF_NON_INTRA, 0, 64) + end + state.frameRate = T.PICTURE_RATE[rate] or 0 + state.aspect = aspect + state.bitRate = bitRate * 400 + if w ~= state.width or h ~= state.height then + state.width = w + state.height = h + mbW = (w + 15) // 16 + mbH = (h + 15) // 16 + mbSize = mbW * mbH + cw = mbW * 16 + chw = mbW * 8 + state.codedWidth = cw + state.codedHeight = mbH * 16 + stores = { newStore(), newStore() } + bStore = newStore() + state.refOld = nil + state.refNew = nil + state.sizeChanged = true + end + hasSeq = true + return true + end + + local function decodeMotion(rsize: number, f: number, pmv: number): number + local code = vlc(MOTION, MOTION_BITS) + local d = code + if code ~= 0 and f ~= 1 then + local r = read(rsize) + d = (math.abs(code) - 1) * f + r + 1 + if code < 0 then + d = -d + end + end + local v = pmv + d + if v > f * 16 - 1 then + v -= f * 32 + elseif v < -f * 16 then + v += f * 32 + end + return v + end + + -- prediction of the current macroblock from one reference (avg: average into the first prediction) + local function predict(rY: buffer, rCb: buffer, rCr: buffer, mvH: number, mvV: number, avg: boolean) + local ch = mbH * 16 + -- luma + local hx, hy = band(mvH, 1), band(mvV, 1) + local sx = mbCol * 16 + mvH // 2 + local sy = mbRow * 16 + mvV // 2 + if sx < 0 or sy < 0 or sx + 16 + hx > cw or sy + 16 + hy > ch then + -- outside the picture: a corrupt vector, clamped (full-pel) + hx, hy = 0, 0 + sx = if sx < 0 then 0 elseif sx > cw - 16 then cw - 16 else sx + sy = if sy < 0 then 0 elseif sy > ch - 16 then ch - 16 else sy + state.clamped += 1 + end + mc(rY, curY, cw, sy * cw + sx, mbRow * 16 * cw + mbCol * 16, 16, hx, hy, avg) + -- chroma: vector / 2 truncated toward zero + local cH = if mvH < 0 then -((-mvH) // 2) else mvH // 2 + local cV = if mvV < 0 then -((-mvV) // 2) else mvV // 2 + hx, hy = band(cH, 1), band(cV, 1) + sx = mbCol * 8 + cH // 2 + sy = mbRow * 8 + cV // 2 + local chh = mbH * 8 + if sx < 0 or sy < 0 or sx + 8 + hx > chw or sy + 8 + hy > chh then + hx, hy = 0, 0 + sx = if sx < 0 then 0 elseif sx > chw - 8 then chw - 8 else sx + sy = if sy < 0 then 0 elseif sy > chh - 8 then chh - 8 else sy + end + local so = sy * chw + sx + local dof = mbRow * 8 * chw + mbCol * 8 + mc(rCb, curCb, chw, so, dof, 8, hx, hy, avg) + mc(rCr, curCr, chw, so, dof, 8, hx, hy, avg) + end + + -- prediction of a non-intra macroblock from the current motion state + local function predictMb() + if ptype == 2 then + predict(fwY, fwCb, fwCr, mvFwH, mvFwV, false) + elseif motFw then + predict(fwY, fwCb, fwCr, mvFwH, mvFwV, false) + if motBw then + predict(bwY, bwCb, bwCr, mvBwH, mvBwV, true) + end + elseif motBw then + predict(bwY, bwCb, bwCr, mvBwH, mvBwV, false) + end + end + + -- Macroblocks no slice covers. ffmpeg's encoder skips the last macroblock of a row at the end of an MPEG-1 + -- slice (the next slice starts on the next row), and ffmpeg's decoder conceals it as a skipped macroblock; so do + -- we: P (and a damaged I) copies the reference with a zero vector, B repeats the prediction of the macroblock + -- before the gap. + local covered = 0 + local gapFw, gapBw = false, false + local gapFwH, gapFwV, gapBwH, gapBwV = 0, 0, 0, 0 + local hasRef = false + local function conceal(from: number, to: number) + if from > to or not hasRef then + return + end + local sFw, sBw, sFwH, sFwV, sBwH, sBwV = motFw, motBw, mvFwH, mvFwV, mvBwH, mvBwV + if ptype == 3 then + motFw, motBw, mvFwH, mvFwV, mvBwH, mvBwV = gapFw, gapBw, gapFwH, gapFwV, gapBwH, gapBwV + if not motFw and not motBw then + motFw = true + mvFwH, mvFwV = 0, 0 + end + elseif ptype == 2 and gapFw then + mvFwH, mvFwV = gapFwH, gapFwV + else + mvFwH, mvFwV = 0, 0 + end + local pt = ptype + if pt == 1 then + ptype = 2 -- a damaged I picture: copy the previous reference + end + for a = from, to do + mbRow = a // mbW + mbCol = a % mbW + predictMb() + end + ptype = pt + motFw, motBw, mvFwH, mvFwV, mvBwH, mvBwV = sFw, sBw, sFwH, sFwV, sBwH, sBwV + end + + -- one 8x8 block: coefficients, dequantisation, IDCT into the picture. False on a bitstream error. + local function decodeBlock(b: number): boolean + local n = 0 + local q: buffer + local onlyDc = true + if mbIntra then + local dc + if b < 4 then + local size = vlc(DC_LUMA, DC_LUMA_BITS) + dc = dcY + if size > 0 then + local diff = read(size) + if band(diff, lshift(1, size - 1)) == 0 then + diff = diff + 1 - lshift(1, size) + end + dc += diff + end + dcY = dc + else + local size = vlc(DC_CHROMA, DC_CHROMA_BITS) + dc = if b == 4 then dcCb else dcCr + if size > 0 then + local diff = read(size) + if band(diff, lshift(1, size - 1)) == 0 then + diff = diff + 1 - lshift(1, size) + end + dc += diff + end + if b == 4 then + dcCb = dc + else + dcCr = dc + end + end + if err then + return false + end + if dc < 0 or dc > 255 then + -- out of range (corrupt data): clamp, which also bounds the IDCT input + dc = if dc < 0 then 0 else 255 + if b < 4 then + dcY = dc + elseif b == 4 then + dcCb = dc + else + dcCr = dc + end + end + writei32(blk, 0, dc * 8) + q = intraQ + n = 1 + else + q = nonIntraQ + end + local lut = if n == 0 then DCT_FIRST else DCT_NEXT + local intra = mbIntra + local qscale = qs + while true do + -- inline peek + local bp = rshift(pos, 3) + local w = bswap(readu32(data, bp)) + local s = band(pos, 7) + if s ~= 0 then + w = bor(lshift(w, s), rshift(readu8(data, bp + 4), 8 - s)) + end + local e = readu32(lut, rshift(w, 24) * 4) + if e >= SUB then + e = readu32(lut, (band(e, 0xFFFF) * 256 + band(rshift(w, 16), 255)) * 4) + end + local l = rshift(e, 16) + if l == 0 then + err = true + return false + end + local v = band(e, 0xFFFF) + lut = DCT_NEXT + if v == EOB then + pos += l + break + end + local run, level, neg + if v == ESC then + -- 6-bit run, then an 8-bit level or 0x00 / 0x80 and 8 more bits + pos += l + run = read(6) + level = read(8) + if level == 0 then + level = read(8) + elseif level == 128 then + level = read(8) - 256 + elseif level > 128 then + level -= 256 + end + neg = level < 0 + if neg then + level = -level + end + if level == 0 then + err = true + return false + end + else + run = rshift(v, 8) + level = band(v, 255) + neg = band(lshift(w, l), 0x80000000) ~= 0 -- the sign bit follows the code + pos += l + 1 + end + n += run + if n > 63 then + err = true + return false + end + -- dequantise the magnitude (truncating), make it odd toward zero, clamp + local m + if intra then + m = (level * 2 * qscale * readu8(q, n)) // 16 + else + m = ((level * 2 + 1) * qscale * readu8(q, n)) // 16 + end + if band(m, 1) == 0 and m ~= 0 then + m -= 1 + end + if neg then + if m > 2048 then + m = 2048 + end + m = -m + elseif m > 2047 then + m = 2047 + end + local zz = readu8(ZZ, n) + if zz ~= 0 then + onlyDc = false + end + writei32(blk, zz * 4, m) + n += 1 + end + -- reconstruction + local dst, off, stride + if b < 4 then + dst = curY + stride = cw + off = (mbRow * 16 + (if b >= 2 then 8 else 0)) * cw + mbCol * 16 + (if b % 2 == 1 then 8 else 0) + else + dst = if b == 4 then curCb else curCr + stride = chw + off = mbRow * 8 * chw + mbCol * 8 + end + if onlyDc then + fillBlock(dst, off, stride, (readi32(blk, 0) + 4) // 8, not intra) + writei32(blk, 0, 0) + else + idct(blk, ws, dst, off, stride, not intra) + buffer.fill(blk, 0, 0, 256) + end + return true + end + + local function resetMv() + pmvFwH, pmvFwV, pmvBwH, pmvBwV = 0, 0, 0, 0 + mvFwH, mvFwV, mvBwH, mvBwV = 0, 0, 0, 0 + end + + -- one macroblock (with the skipped ones before it). False on a bitstream error or the end of the slice data. + local function decodeMacroblock(first: boolean, endBits: number): boolean + local inc = 0 + local t = vlc(MBAI, MBAI_BITS) + while t == 34 and not err and pos < endBits do -- stuffing + t = vlc(MBAI, MBAI_BITS) + end + while t == 35 and not err and pos < endBits do -- escape + inc += 33 + t = vlc(MBAI, MBAI_BITS) + end + if err or t < 1 or t > 33 then + err = true + return false + end + inc += t + if first then + mbAddr += inc + if mbAddr > covered and mbAddr <= mbSize then + conceal(covered, mbAddr - 1) + end + else + if mbAddr + inc >= mbSize then + err = true + return false + end + if inc > 1 then + dcY, dcCb, dcCr = 128, 128, 128 + if ptype == 2 then + resetMv() + end + -- skipped macroblocks: P copies the reference (zero vector), B repeats the previous prediction + for _ = 2, inc do + mbAddr += 1 + mbRow = mbAddr // mbW + mbCol = mbAddr % mbW + if ptype == 1 then + err = true -- no skipped macroblocks in I pictures + return false + end + predictMb() + end + end + mbAddr += 1 + end + if mbAddr < 0 or mbAddr >= mbSize then + err = true + return false + end + mbRow = mbAddr // mbW + mbCol = mbAddr % mbW + covered = mbAddr + 1 + + local mt = vlc(MBTYPE[ptype], MBTYPE_BITS[ptype]) + if err then + return false + end + mbIntra = band(mt, 1) ~= 0 + if band(mt, 0x10) ~= 0 then + qs = read(5) + if qs == 0 then + err = true + return false + end + end + if mbIntra then + resetMv() + else + dcY, dcCb, dcCr = 128, 128, 128 + motFw = band(mt, 8) ~= 0 + motBw = band(mt, 4) ~= 0 + if motFw then + pmvFwH = decodeMotion(fwRSize, fwF, pmvFwH) + pmvFwV = decodeMotion(fwRSize, fwF, pmvFwV) + mvFwH = if fullPelFw then pmvFwH * 2 else pmvFwH + mvFwV = if fullPelFw then pmvFwV * 2 else pmvFwV + elseif ptype == 2 then + resetMv() + end + if motBw then + pmvBwH = decodeMotion(bwRSize, bwF, pmvBwH) + pmvBwV = decodeMotion(bwRSize, bwF, pmvBwV) + mvBwH = if fullPelBw then pmvBwH * 2 else pmvBwH + mvBwV = if fullPelBw then pmvBwV * 2 else pmvBwV + end + if err then + return false + end + predictMb() + end + local cbp + if band(mt, 2) ~= 0 then + cbp = vlc(CBP, CBP_BITS) + if err then + return false + end + else + cbp = if mbIntra then 63 else 0 + end + if cbp ~= 0 then + for b = 0, 5 do + if band(cbp, rshift(32, b)) ~= 0 then + if not decodeBlock(b) then + return false + end + end + end + end + return pos <= endBits + end + + local function decodeSlice(row: number, endByte: number) + if row > mbH then + return + end + mbAddr = (row - 1) * mbW - 1 + resetMv() + dcY, dcCb, dcCr = 128, 128, 128 + motFw, motBw = false, false + qs = read(5) + local endBits = endByte * 8 + while read(1) == 1 and pos < endBits do + pos += 8 + end + if qs == 0 then + return + end + local first = true + while true do + if not decodeMacroblock(first, endBits) then + state.errors += 1 + buffer.fill(blk, 0, 0, 256) -- a block may have stopped half decoded + break + end + first = false + -- the slice ends at a start code (byte aligned) or at the end of the picture data + local i = rshift(pos + 7, 3) + if i >= endByte then + break + end + if readu8(data, i) == 0 and readu8(data, i + 1) == 0 and readu8(data, i + 2) == 1 then + break + end + end + -- the motion state a gap after this slice repeats (B pictures) + if mbIntra then + gapFw, gapBw = false, false + else + gapFw, gapBw, gapFwH, gapFwV, gapBwH, gapBwV = motFw, motBw, mvFwH, mvFwV, mvBwH, mvBwV + end + end + + -- the picture whose header starts at byte p (after 00 00 01 00) and ends at byte stop + local function decodePicture(p: number, stop: number, tag: any): Store? + pos = p * 8 + local tref = read(10) + ptype = read(3) + pos += 16 -- vbv_delay + if ptype < 1 or ptype > 3 then + state.skipped += 1 -- D pictures and invalid types + return nil + end + if ptype >= 2 then + fullPelFw = read(1) == 1 + local fcode = read(3) + if fcode == 0 then + state.skipped += 1 + return nil + end + fwRSize = fcode - 1 + fwF = lshift(1, fwRSize) + end + if ptype == 3 then + fullPelBw = read(1) == 1 + local bcode = read(3) + if bcode == 0 then + state.skipped += 1 + return nil + end + bwRSize = bcode - 1 + bwF = lshift(1, bwRSize) + end + -- references: P from the newest, B between the two newest + local target: Store + local refOld, refNew = state.refOld, state.refNew + if ptype == 1 then + target = if stores[1] == refNew then stores[2] else stores[1] + if refNew then + fwY, fwCb, fwCr = refNew.y, refNew.cb, refNew.cr + end + elseif ptype == 2 then + if refNew == nil then + state.skipped += 1 + return nil + end + target = if stores[1] == refNew then stores[2] else stores[1] + fwY, fwCb, fwCr = refNew.y, refNew.cb, refNew.cr + else + if refOld == nil or refNew == nil or bStore == nil then + state.skipped += 1 + return nil + end + target = bStore :: Store + local ro, rn = refOld :: Store, refNew :: Store + fwY, fwCb, fwCr = ro.y, ro.cb, ro.cr + bwY, bwCb, bwCr = rn.y, rn.cb, rn.cr + end + curY, curCb, curCr = target.y, target.cb, target.cr + err = false + covered = 0 + hasRef = refNew ~= nil + gapFw, gapBw = false, false + mbIntra = false + + -- slices + local at = findStart(rshift(pos + 7, 3), stop) + while at >= 0 do + local code = readu8(data, at + 3) + if code >= 0x01 and code <= 0xAF then + pos = (at + 4) * 8 + err = false + decodeSlice(code, stop) + local nb = rshift(pos + 7, 3) + if nb >= stop then + break + end + at = findStart(nb, stop) + elseif code == 0xB2 or code == 0xB5 then + at = findStart(at + 4, stop) + else + break + end + end + conceal(covered, mbSize - 1) + state.pictures += 1 + target.tref = tref + target.ptype = ptype + target.tag = tag + if ptype ~= 3 then + -- the new picture becomes the newest reference + state.refOld = refNew + state.refNew = target + end + return target + end + + local core = {} :: Core + core.state = state + + function core.write(src: buffer, off: number, n: number) + if n <= 0 then + return + end + -- drop consumed bytes, keeping the scan state relative + if readByte > 0 then + local keep = dataLen - readByte + if keep > 0 then + buffer.copy(data, 0, data, readByte, keep) + end + scanPos = math.max(0, scanPos - readByte) + dataLen = keep + readByte = 0 + end + local need = dataLen + n + PAD + if need > buffer.len(data) then + local cap = buffer.len(data) + while cap < need do + cap *= 2 + end + local nb = buffer.create(cap) + buffer.copy(nb, 0, data, 0, dataLen) + data = nb + end + buffer.copy(data, dataLen, src, off, n) + dataLen += n + buffer.fill(data, dataLen, 0, PAD) + end + + function core.nextPicture(atEnd: boolean, tag: any): (Store?, boolean) + while true do + local at = findStart(readByte, dataLen) + if at < 0 then + -- keep the last 3 bytes: a start code may straddle the next write + readByte = math.max(readByte, dataLen - 3) + if atEnd then + readByte = dataLen + end + return nil, true + end + local code = readu8(data, at + 3) + if code == 0xB3 or code == 0x00 then + -- a unit is complete when the next unit start (or the end of the data) follows it + local stop = dataLen + do + local s = findStart(math.max(at + 4, scanPos), dataLen) + while s >= 0 do + local c = readu8(data, s + 3) + if c == 0x00 or c == 0xB3 or c == 0xB7 or c == 0xB8 then + break + end + s = findStart(s + 4, dataLen) + end + if s < 0 then + if not atEnd then + scanPos = math.max(at + 4, dataLen - 3) + readByte = at + return nil, true + end + else + stop = s + end + end + scanPos = 0 + readByte = stop + if code == 0xB3 then + if not sequenceHeader(at + 4) then + state.errors += 1 + end + elseif hasSeq then + local s = decodePicture(at + 4, stop, tag) + if s then + return s, false + end + else + state.skipped += 1 + end + else + readByte = at + 4 -- GOP header, sequence end, user data, stray slices + end + end + end + + function core.toRgba(s: Store, out: buffer) + toRgba(s.y, s.cb, s.cr, s.cw, s.w, s.h, out) + end + + function core.reset() + dataLen = 0 + readByte = 0 + scanPos = 0 + state.refOld = nil + state.refNew = nil + end + + return core +end + +return D diff --git a/src/Formats/codecs/Mpeg1/Tables.luau b/src/Formats/codecs/Mpeg1/Tables.luau new file mode 100644 index 0000000..3e330ef --- /dev/null +++ b/src/Formats/codecs/Mpeg1/Tables.luau @@ -0,0 +1,117 @@ +--!strict +-- codecs/Mpeg1/Tables: the constant tables of jsmpeg's MPEG-1 video decoder (https://github.com/phoboslab/jsmpeg, +-- Dominic Szablewski, MIT, licenses/jsmpeg-MIT.txt), generated by mpeg1-luau's tools/gen_tables.py (absorbed from +-- mpeg1-luau e2e2898). Lists are 0-based like the JS arrays. +local T = {} +T.PICTURE_RATE = { [0] = 0.0, + 23.976, 24.0, 25.0, 29.97, 30.0, 50.0, 59.94, 60.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, +} +T.ZIG_ZAG = { [0] = 0, + 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, + 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, + 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63, +} +T.DEFAULT_INTRA_QUANT_MATRIX = { [0] = 8, + 16, 19, 22, 26, 27, 29, 34, 16, 16, 22, 24, 27, 29, 34, 37, 19, 22, 26, 27, 29, 34, 34, 38, 22, + 22, 26, 27, 29, 34, 37, 40, 22, 26, 27, 29, 32, 35, 40, 48, 26, 27, 29, 32, 35, 40, 48, 58, 26, + 27, 29, 34, 38, 46, 56, 69, 27, 29, 35, 38, 46, 56, 69, 83, +} +T.DEFAULT_NON_INTRA_QUANT_MATRIX = { [0] = 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, +} +T.MACROBLOCK_ADDRESS_INCREMENT = { [0] = 3, + 6, 0, 9, 12, 0, 0, 0, 1, 15, 18, 0, 21, 24, 0, 27, 30, 0, 33, 36, 0, 0, 0, 3, 0, + 0, 2, 39, 42, 0, 45, 48, 0, 0, 0, 5, 0, 0, 4, 51, 54, 0, 57, 60, 0, 0, 0, 7, 0, + 0, 6, 63, 66, 0, 69, 72, 0, 75, 78, 0, 81, 84, 0, -1, 87, 0, -1, 90, 0, 93, 96, 0, 99, + 102, 0, 105, 108, 0, 111, 114, 0, 0, 0, 9, 0, 0, 8, 117, 120, 0, 123, 126, 0, 129, 132, 0, 135, + 138, 0, 0, 0, 15, 0, 0, 14, 0, 0, 13, 0, 0, 12, 0, 0, 11, 0, 0, 10, 141, -1, 0, -1, + 144, 0, 147, 150, 0, 153, 156, 0, 159, 162, 0, 165, 168, 0, 171, 174, 0, 177, 180, 0, 183, -1, 0, -1, + 186, 0, 189, 192, 0, 195, 198, 0, 201, 204, 0, 207, 210, 0, 213, 216, 0, 219, 222, 0, 0, 0, 21, 0, + 0, 20, 0, 0, 19, 0, 0, 18, 0, 0, 17, 0, 0, 16, 0, 0, 35, 0, 0, 34, 0, 0, 33, 0, + 0, 32, 0, 0, 31, 0, 0, 30, 0, 0, 29, 0, 0, 28, 0, 0, 27, 0, 0, 26, 0, 0, 25, 0, + 0, 24, 0, 0, 23, 0, 0, 22, +} +T.MACROBLOCK_TYPE_INTRA = { [0] = 3, + 6, 0, -1, 9, 0, 0, 0, 1, 0, 0, 17, +} +T.MACROBLOCK_TYPE_PREDICTIVE = { [0] = 3, + 6, 0, 9, 12, 0, 0, 0, 10, 15, 18, 0, 0, 0, 2, 21, 24, 0, 0, 0, 8, 27, 30, 0, 33, + 36, 0, -1, 39, 0, 0, 0, 18, 0, 0, 26, 0, 0, 1, 0, 0, 17, +} +T.MACROBLOCK_TYPE_B = { [0] = 3, + 6, 0, 9, 15, 0, 12, 18, 0, 24, 21, 0, 0, 0, 12, 27, 30, 0, 0, 0, 14, 39, 42, 0, 36, + 33, 0, 0, 0, 4, 0, 0, 6, 54, 48, 0, 45, 51, 0, 0, 0, 8, 0, 0, 10, -1, 57, 0, 0, + 0, 1, 60, 63, 0, 0, 0, 30, 0, 0, 17, 0, 0, 22, 0, 0, 26, +} +T.CODE_BLOCK_PATTERN = { [0] = 6, + 3, 0, 9, 18, 0, 12, 15, 0, 24, 33, 0, 36, 39, 0, 27, 21, 0, 30, 42, 0, 60, 57, 0, 54, + 48, 0, 69, 51, 0, 81, 75, 0, 63, 84, 0, 45, 66, 0, 72, 78, 0, 0, 0, 60, 105, 120, 0, 132, + 144, 0, 114, 108, 0, 126, 141, 0, 87, 93, 0, 117, 96, 0, 0, 0, 32, 135, 138, 0, 99, 123, 0, 129, + 102, 0, 0, 0, 4, 90, 111, 0, 0, 0, 8, 0, 0, 16, 0, 0, 44, 150, 168, 0, 0, 0, 28, 0, + 0, 52, 0, 0, 62, 183, 177, 0, 156, 180, 0, 0, 0, 1, 165, 162, 0, 0, 0, 61, 0, 0, 56, 171, + 174, 0, 0, 0, 2, 0, 0, 40, 153, 186, 0, 0, 0, 48, 192, 189, 0, 147, 159, 0, 0, 0, 20, 0, + 0, 12, 240, 249, 0, 0, 0, 63, 231, 225, 0, 195, 219, 0, 252, 198, 0, 0, 0, 24, 0, 0, 36, 0, + 0, 3, 207, 261, 0, 243, 237, 0, 204, 213, 0, 210, 234, 0, 201, 228, 0, 216, 222, 0, 258, 255, 0, 264, + 246, 0, -1, 282, 0, 285, 291, 0, 0, 0, 33, 0, 0, 9, 318, 330, 0, 306, 348, 0, 0, 0, 5, 0, + 0, 10, 279, 267, 0, 0, 0, 6, 0, 0, 18, 0, 0, 17, 0, 0, 34, 339, 357, 0, 309, 312, 0, 270, + 276, 0, 327, 321, 0, 351, 354, 0, 303, 297, 0, 294, 288, 0, 300, 273, 0, 342, 345, 0, 315, 324, 0, 336, + 333, 0, 363, 375, 0, 0, 0, 41, 0, 0, 14, 0, 0, 21, 372, 366, 0, 360, 369, 0, 0, 0, 11, 0, + 0, 19, 0, 0, 7, 0, 0, 35, 0, 0, 13, 0, 0, 50, 0, 0, 49, 0, 0, 58, 0, 0, 37, 0, + 0, 25, 0, 0, 45, 0, 0, 57, 0, 0, 26, 0, 0, 29, 0, 0, 38, 0, 0, 53, 0, 0, 23, 0, + 0, 43, 0, 0, 46, 0, 0, 42, 0, 0, 22, 0, 0, 54, 0, 0, 51, 0, 0, 15, 0, 0, 30, 0, + 0, 39, 0, 0, 47, 0, 0, 55, 0, 0, 27, 0, 0, 59, 0, 0, 31, +} +T.MOTION = { [0] = 3, + 6, 0, 12, 9, 0, 0, 0, 0, 18, 15, 0, 24, 21, 0, 0, 0, -1, 0, 0, 1, 27, 30, 0, 36, + 33, 0, 0, 0, 2, 0, 0, -2, 42, 45, 0, 48, 39, 0, 60, 54, 0, 0, 0, 3, 0, 0, -3, 51, + 57, 0, -1, 69, 0, 81, 75, 0, 78, 63, 0, 72, 66, 0, 96, 84, 0, 87, 93, 0, -1, 99, 0, 108, + 105, 0, 0, 0, -4, 90, 102, 0, 0, 0, 4, 0, 0, -7, 0, 0, 5, 111, 123, 0, 0, 0, -5, 0, + 0, 7, 114, 120, 0, 126, 117, 0, 0, 0, -6, 0, 0, 6, 153, 162, 0, 150, 147, 0, 135, 138, 0, 156, + 141, 0, 129, 159, 0, 132, 144, 0, 0, 0, 10, 0, 0, 9, 0, 0, 8, 0, 0, -8, 171, 198, 0, 0, + 0, -9, 180, 192, 0, 168, 183, 0, 165, 186, 0, 174, 189, 0, 0, 0, -10, 177, 195, 0, 0, 0, 12, 0, + 0, 16, 0, 0, 13, 0, 0, 14, 0, 0, 11, 0, 0, 15, 0, 0, -16, 0, 0, -12, 0, 0, -14, 0, + 0, -15, 0, 0, -11, 0, 0, -13, +} +T.DCT_DC_SIZE_LUMINANCE = { [0] = 6, + 3, 0, 18, 15, 0, 9, 12, 0, 0, 0, 1, 0, 0, 2, 27, 24, 0, 21, 30, 0, 0, 0, 0, 36, + 33, 0, 0, 0, 4, 0, 0, 3, 39, 42, 0, 0, 0, 5, 0, 0, 6, 48, 45, 0, 51, -1, 0, 0, + 0, 7, 0, 0, 8, +} +T.DCT_DC_SIZE_CHROMINANCE = { [0] = 6, + 3, 0, 12, 9, 0, 18, 15, 0, 24, 21, 0, 0, 0, 2, 0, 0, 1, 0, 0, 0, 30, 27, 0, 0, + 0, 3, 36, 33, 0, 0, 0, 4, 42, 39, 0, 0, 0, 5, 48, 45, 0, 0, 0, 6, 51, -1, 0, 0, + 0, 7, 0, 0, 8, +} +T.DCT_COEFF = { [0] = 3, + 6, 0, 12, 9, 0, 0, 0, 1, 21, 24, 0, 18, 15, 0, 39, 27, 0, 33, 30, 0, 42, 36, 0, 0, + 0, 257, 60, 66, 0, 54, 63, 0, 48, 57, 0, 0, 0, 513, 51, 45, 0, 0, 0, 2, 0, 0, 3, 81, + 75, 0, 87, 93, 0, 72, 78, 0, 96, 90, 0, 0, 0, 1025, 69, 84, 0, 0, 0, 769, 0, 0, 258, 0, + 0, 1793, 0, 0, 65535, 0, 0, 1537, 111, 108, 0, 0, 0, 1281, 105, 102, 0, 117, 114, 0, 99, 126, 0, 120, + 123, 0, 156, 150, 0, 162, 159, 0, 144, 147, 0, 129, 135, 0, 138, 132, 0, 0, 0, 2049, 0, 0, 4, 0, + 0, 514, 0, 0, 2305, 153, 141, 0, 165, 171, 0, 180, 168, 0, 177, 174, 0, 183, 186, 0, 0, 0, 2561, 0, + 0, 3329, 0, 0, 6, 0, 0, 259, 0, 0, 5, 0, 0, 770, 0, 0, 2817, 0, 0, 3073, 228, 225, 0, 201, + 210, 0, 219, 213, 0, 234, 222, 0, 216, 231, 0, 207, 192, 0, 204, 189, 0, 198, 195, 0, 243, 261, 0, 273, + 240, 0, 246, 237, 0, 249, 258, 0, 279, 276, 0, 252, 255, 0, 270, 282, 0, 264, 267, 0, 0, 0, 515, 0, + 0, 260, 0, 0, 7, 0, 0, 1026, 0, 0, 1282, 0, 0, 4097, 0, 0, 3841, 0, 0, 3585, 315, 321, 0, 333, + 342, 0, 312, 291, 0, 375, 357, 0, 288, 294, 0, -1, 369, 0, 285, 303, 0, 318, 363, 0, 297, 306, 0, 339, + 309, 0, 336, 348, 0, 330, 300, 0, 372, 345, 0, 351, 366, 0, 327, 354, 0, 360, 324, 0, 381, 408, 0, 417, + 420, 0, 390, 378, 0, 435, 438, 0, 384, 387, 0, 0, 0, 2050, 396, 402, 0, 465, 462, 0, 0, 0, 8, 411, + 399, 0, 429, 432, 0, 453, 414, 0, 426, 423, 0, 0, 0, 10, 0, 0, 9, 0, 0, 11, 0, 0, 5377, 0, + 0, 1538, 0, 0, 771, 0, 0, 5121, 0, 0, 1794, 0, 0, 4353, 0, 0, 4609, 0, 0, 4865, 444, 456, 0, 0, + 0, 1027, 459, 450, 0, 0, 0, 261, 393, 405, 0, 0, 0, 516, 447, 441, 0, 516, 519, 0, 486, 474, 0, 510, + 483, 0, 504, 498, 0, 471, 537, 0, 507, 501, 0, 522, 513, 0, 534, 531, 0, 468, 477, 0, 492, 495, 0, 549, + 546, 0, 525, 528, 0, 0, 0, 263, 0, 0, 2562, 0, 0, 2306, 0, 0, 5633, 0, 0, 5889, 0, 0, 6401, 0, + 0, 6145, 0, 0, 1283, 0, 0, 772, 0, 0, 13, 0, 0, 12, 0, 0, 14, 0, 0, 15, 0, 0, 517, 0, + 0, 6657, 0, 0, 262, 540, 543, 0, 480, 489, 0, 588, 597, 0, 0, 0, 27, 609, 555, 0, 606, 603, 0, 0, + 0, 19, 0, 0, 22, 591, 621, 0, 0, 0, 18, 573, 576, 0, 564, 570, 0, 0, 0, 20, 552, 582, 0, 0, + 0, 21, 558, 579, 0, 0, 0, 23, 612, 594, 0, 0, 0, 25, 0, 0, 24, 600, 615, 0, 0, 0, 31, 0, + 0, 30, 0, 0, 28, 0, 0, 29, 0, 0, 26, 0, 0, 17, 0, 0, 16, 567, 618, 0, 561, 585, 0, 654, + 633, 0, 0, 0, 37, 645, 648, 0, 0, 0, 36, 630, 636, 0, 0, 0, 34, 639, 627, 0, 663, 666, 0, 657, + 624, 0, 651, 642, 0, 669, 660, 0, 0, 0, 35, 0, 0, 267, 0, 0, 40, 0, 0, 268, 0, 0, 266, 0, + 0, 32, 0, 0, 264, 0, 0, 265, 0, 0, 38, 0, 0, 269, 0, 0, 270, 0, 0, 33, 0, 0, 39, 0, + 0, 7937, 0, 0, 6913, 0, 0, 7681, 0, 0, 4098, 0, 0, 7425, 0, 0, 7169, 0, 0, 271, 0, 0, 274, 0, + 0, 273, 0, 0, 272, 0, 0, 1539, 0, 0, 2818, 0, 0, 3586, 0, 0, 3330, 0, 0, 3074, 0, 0, 3842, +} +return T diff --git a/src/Formats/codecs/Mpeg1/Vlc.luau b/src/Formats/codecs/Mpeg1/Vlc.luau new file mode 100644 index 0000000..8d34e39 --- /dev/null +++ b/src/Formats/codecs/Mpeg1/Vlc.luau @@ -0,0 +1,116 @@ +--!strict +-- codecs/Mpeg1/Vlc: lookup tables for the MPEG-1 variable-length codes, built at load time from jsmpeg's binary trees (Tables.luau). +-- +-- A flat table is indexed by the next K bits of the stream (K = the longest code) and holds +-- len * 65536 + (value + 32768) per entry; len = 0 marks an invalid code. The DCT coefficient tables are two-level +-- (8 bits, then 8 more for the long codes) and hold len * 65536 + value, value = run * 256 + level, ESC = 0xFFFF, +-- EOB = 0xFFFE, or SUB + subtable for a long-code prefix. DCT_NEXT is the table for every coefficient after the +-- first one of a block, where "10" is end_of_block and "11" is run 0 / level 1 (jsmpeg reads this as "1" and one +-- more bit); DCT_FIRST keeps "1" as run 0 / level 1. Absorbed from mpeg1-luau e2e2898 (same author), unchanged but +-- for this header and the require. +local T = require("@formats/codecs/Mpeg1/Tables") + +local V = {} + +type Leaf = { code: number, len: number, value: number } + +local function leaves(tree: { [number]: number }): { Leaf } + local out: { Leaf } = {} + local function walk(state: number, code: number, len: number) + if tree[state] == 0 and len > 0 then + table.insert(out, { code = code, len = len, value = tree[state + 2] }) + return + end + for bit = 0, 1 do + local nxt = tree[state + bit] + if nxt ~= nil and nxt > 0 then + walk(nxt, code * 2 + bit, len + 1) + end + end + end + walk(0, 0, 0) + return out +end + +local function flat(tree: { [number]: number }): (buffer, number) + local ls = leaves(tree) + local k = 0 + for _, l in ls do + k = math.max(k, l.len) + end + local lut = buffer.create(4 * 2 ^ k) + for _, l in ls do + local shift = k - l.len + local first = l.code * 2 ^ shift + for i = first, first + 2 ^ shift - 1 do + buffer.writeu32(lut, i * 4, l.len * 65536 + l.value + 32768) + end + end + return lut, k +end + +V.SUB = 0x1000000 +V.ESC = 0xFFFF +V.EOB = 0xFFFE + +-- two-level table: 256 first-level entries, then 256-entry subtables for prefixes of codes longer than 8 bits +local function twoLevel(ls: { Leaf }): buffer + local subs: { [number]: number } = {} + local nsub = 0 + for _, l in ls do + if l.len > 8 then + local prefix = l.code // 2 ^ (l.len - 8) + if subs[prefix] == nil then + nsub += 1 + subs[prefix] = nsub + end + end + end + local lut = buffer.create(4 * 256 * (1 + nsub)) + for _, l in ls do + if l.len <= 8 then + local shift = 8 - l.len + local first = l.code * 2 ^ shift + for i = first, first + 2 ^ shift - 1 do + buffer.writeu32(lut, i * 4, l.len * 65536 + l.value) + end + else + local prefix = l.code // 2 ^ (l.len - 8) + local s = subs[prefix] + buffer.writeu32(lut, prefix * 4, V.SUB + s) + local rest = l.code % 2 ^ (l.len - 8) + local shift = 16 - l.len + local first = rest * 2 ^ shift + for i = first, first + 2 ^ shift - 1 do + buffer.writeu32(lut, (s * 256 + i) * 4, l.len * 65536 + l.value) + end + end + end + return lut +end + +V.MBAI, V.MBAI_BITS = flat(T.MACROBLOCK_ADDRESS_INCREMENT) -- 34 = stuffing, 35 = escape +V.MBTYPE_I, V.MBTYPE_I_BITS = flat(T.MACROBLOCK_TYPE_INTRA) +V.MBTYPE_P, V.MBTYPE_P_BITS = flat(T.MACROBLOCK_TYPE_PREDICTIVE) +V.MBTYPE_B, V.MBTYPE_B_BITS = flat(T.MACROBLOCK_TYPE_B) +V.CBP, V.CBP_BITS = flat(T.CODE_BLOCK_PATTERN) +V.MOTION, V.MOTION_BITS = flat(T.MOTION) +V.DC_LUMA, V.DC_LUMA_BITS = flat(T.DCT_DC_SIZE_LUMINANCE) +V.DC_CHROMA, V.DC_CHROMA_BITS = flat(T.DCT_DC_SIZE_CHROMINANCE) + +do + local ls = leaves(T.DCT_COEFF) + V.DCT_FIRST = twoLevel(ls) + local nextLs: { Leaf } = {} + for _, l in ls do + if l.len == 1 and l.code == 1 then + table.insert(nextLs, { code = 2, len = 2, value = V.EOB }) -- "10" + table.insert(nextLs, { code = 3, len = 2, value = 0x0001 }) -- "11" + else + table.insert(nextLs, l) + end + end + V.DCT_NEXT = twoLevel(nextLs) +end + +return V diff --git a/src/Formats/codecs/Mpeg1/init.luau b/src/Formats/codecs/Mpeg1/init.luau new file mode 100644 index 0000000..2ff3118 --- /dev/null +++ b/src/Formats/codecs/Mpeg1/init.luau @@ -0,0 +1,262 @@ +--!strict +-- codecs/Mpeg1: an MPEG-1 video decoder (ISO/IEC 11172-2) for the MPEG-TS / MPEG-PS video formats. Absorbed from +-- mpeg1-luau e2e2898 (same author; README, docs/api.md and docs/performance.md there), a port of jsmpeg's decoder +-- (https://github.com/phoboslab/jsmpeg, Dominic Szablewski, MIT: licenses/jsmpeg-MIT.txt) extended with B-pictures, +-- an islow integer IDCT, table-driven VLC decoding and BT.601 RGBA8 output; added here: frameImage. +-- Supports: I, P and B pictures (D-pictures skipped), half / full-pel motion vectors with any f_code, custom +-- quantiser matrices, sequence headers anywhere (size changes), any size up to 4095 x 4095 (maxPixels), display +-- reordering. Accuracy: within ~0.75 MAE per RGBA channel of ffmpeg's decode (tests/codecs/mpeg1.luau). +-- Not supported: MPEG-2 streams (no picture coding extension parsing), field pictures, D-picture decoding. +-- +-- local dec = Mpeg1.new({ reorder = true, rgba = false }) +-- local frame = dec:decode(packetData, 0, len, pts) -- one picture (+ sequence / GOP headers) -> Frame?, tag = pts +-- local img = Mpeg1.frameImage(frame) -- a fresh yuv420p Types.Image (rgba8 with frameImage(f, true)) +-- dec:write(bytes); local f = dec:decodeFrame() -- or an elementary stream in pieces +-- while true do local f = dec:flush(); if not f then break end end -- at the end; dec:reset() after a seek +-- -- frame = { width, height, pixels (RGBA8 or nil, decoder-owned), y / cb / cr / codedWidth, pictureType, ... } +-- +-- Nothing here throws: bad arguments return nil / false, bad data is skipped (see Decoder.luau). +local Types = require("@formats/Types") +local D = require("@formats/codecs/Mpeg1/Decoder") + +local Mpeg1 = {} + +Mpeg1.PICTURE_I = 1 +Mpeg1.PICTURE_P = 2 +Mpeg1.PICTURE_B = 3 + +export type Frame = { + width: number, + height: number, + pixels: buffer?, -- RGBA8, width * height * 4 bytes, row-major, alpha 255; nil with { rgba = false } + pictureType: number, -- 1 I, 2 P, 3 B + temporalReference: number, -- the picture's 10-bit display index within its GOP + index: number, -- frames returned so far (1-based) + tag: any, -- the tag passed to decode() with this picture's data (follows the picture through reordering) + -- the decoded YCbCr 4:2:0 planes (decoder-owned, valid until the next decode): luma stride codedWidth, + -- chroma stride codedWidth / 2 + y: buffer, + cb: buffer, + cr: buffer, + codedWidth: number, +} + +export type Options = { + reorder: boolean?, -- true: return frames in display order (B-frame streams; one frame of delay, flush() at the + -- end). Default false: every picture is returned as soon as it is decoded (decode order, no delay), which is + -- display order for streams without B-frames. + rgba: boolean?, -- default true; false skips the RGBA conversion (use frame.y / cb / cr) + maxPixels: number?, -- larger sequence headers are rejected (default 4096 * 2304) +} + +local Decoder = {} +Decoder.__index = Decoder + +export type Decoder = typeof(setmetatable( + {} :: { + _core: D.Core, + _reorder: boolean, + _rgba: boolean, + _held: D.Store?, + _pixels: buffer?, + _count: number, + width: number, + height: number, + frameRate: number, + bitRate: number, + stats: { pictures: number, errors: number, skipped: number }, + }, + Decoder +)) + +function Mpeg1.new(opts: Options?): Decoder + local o: Options = if type(opts) == "table" then opts else {} + local core = D.new(o.maxPixels) + return setmetatable({ + _core = core, + _reorder = o.reorder == true, + _rgba = o.rgba ~= false, + _held = nil, + _pixels = nil, + _count = 0, + width = 0, + height = 0, + frameRate = 0, + bitRate = 0, + stats = { pictures = 0, errors = 0, skipped = 0 }, + }, Decoder) +end + +local function emit(self: Decoder, s: D.Store): Frame + local core = self._core + local pixels: buffer? = nil + if self._rgba then + local need = s.w * s.h * 4 + local px = self._pixels + if px == nil or buffer.len(px) ~= need then + px = buffer.create(need) + self._pixels = px + end + core.toRgba(s, px :: buffer) + pixels = px + end + self._count += 1 + return { + width = s.w, + height = s.h, + pixels = pixels, + pictureType = s.ptype, + temporalReference = s.tref, + index = self._count, + tag = s.tag, + y = s.y, + cb = s.cb, + cr = s.cr, + codedWidth = s.cw, + } +end + +local function sync(self: Decoder) + local st = self._core.state + self.width = st.width + self.height = st.height + self.frameRate = st.frameRate + self.bitRate = st.bitRate + self.stats.pictures = st.pictures + self.stats.errors = st.errors + self.stats.skipped = st.skipped +end + +-- a decoded picture -> the frame to return now (nil while reordering holds it) +local function handle(self: Decoder, s: D.Store): Frame? + if not self._reorder or s.ptype == D.PICTURE_B then + return emit(self, s) + end + local prev = self._held + self._held = s + if prev then + return emit(self, prev) + end + return nil +end + +local function run(self: Decoder, atEnd: boolean, tag: any): Frame? + local core = self._core + while true do + local s, needData = core.nextPicture(atEnd, tag) + sync(self) + if s then + local f = handle(self, s) + if f then + return f + end + elseif needData then + return nil + end + end +end + +local function append(self: Decoder, data: any, offset: number?, len: number?): boolean + local src: buffer + if type(data) == "string" then + src = buffer.fromstring(data) + elseif type(data) == "buffer" then + src = data + else + return false + end + local total = buffer.len(src) + local off = math.floor(tonumber(offset) or 0) + if off < 0 or off > total then + return false + end + local n = math.floor(tonumber(len) or (total - off)) + if n < 0 or off + n > total then + return false + end + self._core.write(src, off, n) + return true +end + +-- Appends elementary-stream bytes (buffer or string; offset / len select a part). False for a bad argument. +function Decoder.write(self: Decoder, data: buffer | string, offset: number?, len: number?): boolean + return append(self, data, offset, len) +end + +-- The next complete picture of the written stream as a frame, or nil when more data is needed (a picture is +-- complete once the next picture / sequence / GOP start code has been written; flush() ends the last one). +function Decoder.decodeFrame(self: Decoder): Frame? + return run(self, false, nil) +end + +-- Decodes one access unit (a picture, optionally preceded by sequence / GOP headers: a TS video unit's data). +-- The end of the data ends the picture. tag (any value, e.g. the unit's pts) comes back as frame.tag. +function Decoder.decode(self: Decoder, data: buffer | string, offset: number?, len: number?, tag: any): Frame? + if not append(self, data, offset, len) then + return nil + end + return run(self, true, tag) +end + +-- At the end of the stream: decodes what is left of the written data, then returns the reference picture held +-- for reordering. Call until it returns nil. +function Decoder.flush(self: Decoder): Frame? + local f = run(self, true, nil) + if f then + return f + end + local held = self._held + if held then + self._held = nil + return emit(self, held) + end + return nil +end + +-- Forgets buffered data and references (after a seek: the next picture decoded is the next I-picture). +function Decoder.reset(self: Decoder) + self._core.reset() + self._held = nil +end + +-- frameImage(frame, rgba?) -> Types.Image: a copy of a decoded frame (the decoder reuses its planes), cropped to +-- width x height: yuv420p from frame.y / cb / cr (BT.601 limited range, meta.source.range = "limited"), or rgba8 +-- (the decoder's BT.601 conversion) when rgba is true. nil for a value that is not a Frame. +function Mpeg1.frameImage(frame: Frame, rgba: boolean?): Types.Image? + if type(frame) ~= "table" or type(frame.y) ~= "buffer" or type(frame.cb) ~= "buffer" or type(frame.cr) ~= "buffer" then + return nil + end + local w, h, cw = frame.width, frame.height, frame.codedWidth + if type(w) ~= "number" or type(h) ~= "number" or type(cw) ~= "number" or w < 1 or h < 1 or cw < w then + return nil + end + local chw, ow, oh = cw // 2, (w + 1) // 2, (h + 1) // 2 + if buffer.len(frame.y) < cw * h or buffer.len(frame.cb) < chw * oh or buffer.len(frame.cr) < chw * oh then + return nil + end + local img + if rgba then + img = Types.Image.new(w, h) + D.toRgba(frame.y, frame.cb, frame.cr, cw, w, h, img.pixels) + else + img = Types.Image.new(w, h, "yuv420p") + local px = img.pixels + for y = 0, h - 1 do + buffer.copy(px, y * w, frame.y, y * cw, w) + end + local o = w * h + for y = 0, oh - 1 do + buffer.copy(px, o + y * ow, frame.cb, y * chw, ow) + buffer.copy(px, o + ow * oh + y * ow, frame.cr, y * chw, ow) + end + end + img.meta.source = { + format = "mpeg1", + pictureType = frame.pictureType, + temporalReference = frame.temporalReference, + range = if rgba then nil else "limited", + } + return img +end + +return Mpeg1 diff --git a/tests/codecs/mpeg1.luau b/tests/codecs/mpeg1.luau new file mode 100644 index 0000000..98b57e8 --- /dev/null +++ b/tests/codecs/mpeg1.luau @@ -0,0 +1,413 @@ +-- codecs/Mpeg1 tests, ported from mpeg1-luau tests/decode.luau and tests/robust.luau. Against ffmpeg +-- (tools/fixtures/mpeg1.py): every stream decodes, one access unit at a time, to as many frames as ffmpeg's decode, +-- in display order; each frame's RGBA channel means within 1.5 of ffmpeg's; whole sampled frames within 2 MAE per +-- channel (IDCT and colour rounding) and, as yuv420p (frameImage), within a PSNR floor of ffmpeg -pix_fmt yuv420p; +-- the same stream written in random pieces through write() / decodeFrame() gives identical frames; a size change. +-- Robustness / API: bad arguments, pictures before the first sequence header, reset(), rgba = false, tags through +-- B-frame reordering, string input, truncated units, bit flips and garbage (never throws, recovers at an +-- I-picture), an oversized sequence header; frameImage; the fuzz no-throw pass. +local T = require("@tests/T") +local Mpeg1 = require("@formats/codecs/Mpeg1") +local Base64 = require("@formats/core/Base64") +local Deflate = require("@formats/codecs/Deflate") +local Types = require("@formats/Types") + +local STREAMS = { + require("@tests/gen/mpeg1_qcif_200k"), + require("@tests/gen/mpeg1_main_450k"), + require("@tests/gen/mpeg1_zoom_150k"), + require("@tests/gen/mpeg1_zoom_1500k"), + require("@tests/gen/mpeg1_big_1000k"), + require("@tests/gen/mpeg1_odd_173x95"), + require("@tests/gen/mpeg1_matrix"), + require("@tests/gen/mpeg1_q1"), + require("@tests/gen/mpeg1_q31"), + require("@tests/gen/mpeg1_zeromv"), + require("@tests/gen/mpeg1_bframes"), + require("@tests/gen/mpeg1_bframes_zoom"), +} +local SizeChange = require("@tests/gen/mpeg1_sizechange") + +local t = T.suite("codecs/mpeg1") +local rand = T.rng(7) +local function between(a: number, b: number): number + return a + rand(b - a + 1) +end + +local function b64(s: string): buffer + return Base64.decode(s) :: buffer +end +local function z64(s: string): buffer + return Deflate.zlib(b64(s)) :: buffer +end + +-- mean absolute error per channel (r, g, b) between two RGBA8 buffers of n pixels, and the largest difference +local function mae(a: buffer, b: buffer, n: number): (number, number, number, number) + local sr, sg, sb, mx = 0, 0, 0, 0 + for i = 0, n - 1 do + local o = i * 4 + local dr = math.abs(buffer.readu8(a, o) - buffer.readu8(b, o)) + local dg = math.abs(buffer.readu8(a, o + 1) - buffer.readu8(b, o + 1)) + local db = math.abs(buffer.readu8(a, o + 2) - buffer.readu8(b, o + 2)) + sr += dr + sg += dg + sb += db + mx = math.max(mx, dr, dg, db) + end + return sr / n, sg / n, sb / n, mx +end + +local function means(a: buffer, n: number): (number, number, number) + local r, g, b = 0, 0, 0 + for i = 0, n - 1 do + local o = i * 4 + r += buffer.readu8(a, o) + g += buffer.readu8(a, o + 1) + b += buffer.readu8(a, o + 2) + end + return r / n, g / n, b / n +end + +local function psnr(a: buffer, ao: number, b: buffer, bo: number, n: number): number + local se = 0 + for i = 0, n - 1 do + local d = buffer.readu8(a, ao + i) - buffer.readu8(b, bo + i) + se += d * d + end + if se == 0 then + return 99 + end + return 10 * math.log10(255 * 255 * n / se) +end + +local MAE_LIMIT = 2 +local MEAN_LIMIT = 1.5 + +-- 1. every stream against ffmpeg +local worst, worstY, worstC = 0, 99, 99 +for _, fx in STREAMS do + local name = fx.name + local file = b64(fx.file) + local w, h = fx.width, fx.height + local n = w * h + local cw, ch = (w + 1) // 2, (h + 1) // 2 + local rgbaRef, yuvRef = {}, {} + for _, s in fx.rgba do + rgbaRef[s.index] = z64(s.pixels) + end + for _, s in fx.yuv do + yuvRef[s.index] = z64(s.planes) + end + local hasB = string.find(name, "bframes") ~= nil + local dec = Mpeg1.new({ reorder = hasB }) + local frames = 0 + local maxMae, maxMeanErr = 0, 0 + local sums = {} + local function onFrame(f: any) + frames += 1 + t:check(f.width == w and f.height == h, string.format("%s: size %dx%d", name, f.width, f.height)) + t:eq(f.index, frames, name .. ": frame index") + local px = f.pixels :: buffer + t:eq(buffer.len(px), n * 4, name .. ": pixels size") + local ref = fx.means[frames] + t:check(ref ~= nil, string.format("%s: more frames than ffmpeg (%d)", name, frames)) + local r, g, b = means(px, n) + local me = math.max(math.abs(r - ref[1]), math.abs(g - ref[2]), math.abs(b - ref[3])) + maxMeanErr = math.max(maxMeanErr, me) + t:check(me <= MEAN_LIMIT, string.format("%s frame %d: channel means off by %.2f", name, frames, me)) + local s = rgbaRef[frames] + if s then + local mr, mg, mb = mae(px, s, n) + local m = math.max(mr, mg, mb) + maxMae = math.max(maxMae, m) + t:check(m <= MAE_LIMIT, string.format("%s frame %d: MAE %.3f %.3f %.3f", name, frames, mr, mg, mb)) + local again = Mpeg1.frameImage(f, true) :: Types.Image + t:check(again.format == "rgba8" and buffer.tostring(again.pixels) == buffer.tostring(px), name .. ": frameImage(f, true) = frame.pixels") + end + local y = yuvRef[frames] + if y then + local img = Mpeg1.frameImage(f) :: Types.Image + t:check(img.format == "yuv420p" and img.width == w and img.height == h and buffer.len(img.pixels) == n + 2 * cw * ch, name .. ": frameImage yuv420p") + t:check(img.meta.source.range == "limited" and img.meta.source.pictureType == f.pictureType, name .. ": frameImage meta") + local py = psnr(img.pixels, 0, y, 0, n) + local pc = psnr(img.pixels, n, y, n, 2 * cw * ch) + worstY, worstC = math.min(worstY, py), math.min(worstC, pc) + t:check(py > 50 and pc > 50, string.format("%s frame %d: yuv420p PSNR %.1f / %.1f dB against ffmpeg", name, frames, py, pc)) + end + t:check(buffer.readu8(px, 3) == 255 and buffer.readu8(px, n * 4 - 1) == 255, "alpha 255") + sums[frames] = buffer.tostring(px) + end + local t0 = os.clock() + for _, u in fx.units do + local f = dec:decode(file, u[1], u[2]) + if f then + onFrame(f) + end + end + while true do + local f = dec:flush() + if f == nil then + break + end + onFrame(f) + end + local dt = os.clock() - t0 + t:eq(frames, fx.frames, name .. ": frames (ffmpeg's count)") + t:eq(dec.stats.errors, 0, name .. ": no bitstream errors") + worst = math.max(worst, maxMae) + t:note("%-13s %4dx%-4d %3d frames worst MAE %.3f means err %.3f %6.1f fps (with the checks)", name, w, h, frames, maxMae, maxMeanErr, frames / dt) + + -- streamed: random pieces through write / decodeFrame, then flush + local d2 = Mpeg1.new({ reorder = hasB }) + local got = 0 + local p, total = 0, buffer.len(file) + local function take(f: any) + got += 1 + t:check(sums[got] == buffer.tostring(f.pixels :: buffer), string.format("%s streamed frame %d identical", name, got)) + end + while p < total do + local k = math.min(total - p, between(1, 6000)) + t:check(d2:write(file, p, k), "write") + p += k + while true do + local f = d2:decodeFrame() + if f == nil then + break + end + take(f) + end + end + while true do + local f = d2:flush() + if f == nil then + break + end + take(f) + end + t:eq(got, frames, name .. ": streamed frame count") +end +t:note("worst sampled-frame MAE %.3f (limit %d); worst yuv420p PSNR luma %.1f, chroma %.1f dB", worst, MAE_LIMIT, worstY, worstC) + +-- 2. a size change mid-stream +do + local file = b64(SizeChange.file) + local dec = Mpeg1.new() + dec:write(file) + local list = {} + while true do + local f = dec:decodeFrame() or dec:flush() + if f == nil then + break + end + table.insert(list, { w = f.width, h = f.height, px = buffer.tostring(f.pixels :: buffer) }) + end + local a, b = SizeChange.parts[1], SizeChange.parts[2] + t:eq(#list, a.frames + b.frames, "sizechange: frame count") + t:check(list[1].w == a.width and list[1].h == a.height, "sizechange: first size") + t:check(list[a.frames].w == a.width and list[a.frames + 1].w == b.width and list[#list].h == b.height, "sizechange: second size") + for k, part in { a, b } do + local last = list[if k == 1 then a.frames else #list] + local mr, mg, mb = mae(buffer.fromstring(last.px), z64(part.last), part.width * part.height) + t:check(math.max(mr, mg, mb) <= MAE_LIMIT, string.format("sizechange part %d MAE %.3f %.3f %.3f", k, mr, mg, mb)) + end +end + +-- 3. robustness and the API +local function slice(b: buffer, from: number, n: number): buffer + local out = buffer.create(n) + buffer.copy(out, 0, b, from, n) + return out +end +local main = STREAMS[2] +local mainFile = b64(main.file) +local W, H = main.width, main.height +local ref = {} +do + local dec = Mpeg1.new() + for _, u in main.units do + local f = dec:decode(mainFile, u[1], u[2]) + table.insert(ref, buffer.tostring((f :: any).pixels)) + end + t:eq(#ref, #main.units, "reference decode") +end + +do -- bad arguments + local dec = Mpeg1.new() + t:check(dec:decode((nil :: any)) == nil, "decode(nil)") + t:check(dec:decode((42 :: any)) == nil, "decode(number)") + t:check(dec:write(buffer.create(4), 10) == false, "write offset past the end") + t:check(dec:write(buffer.create(4), 0, 9) == false, "write length past the end") + t:check(dec:write(buffer.create(4), -1) == false, "write negative offset") + t:check(dec:decodeFrame() == nil, "decodeFrame with no data") + t:check(dec:flush() == nil, "flush with no data") + t:check(Mpeg1.new((5 :: any)) ~= nil, "new(non-table)") + t:check(dec:decode(buffer.create(0)) == nil, "empty unit") + t:check(Mpeg1.frameImage(nil :: any) == nil and Mpeg1.frameImage({} :: any) == nil, "frameImage of a non-frame") +end + +do -- string input; pictures before the first sequence header are skipped + local dec = Mpeg1.new() + local u2 = main.units[2] + t:check(dec:decode(buffer.tostring(slice(mainFile, u2[1], u2[2]))) == nil, "P picture before any sequence header") + local u1 = main.units[1] + local f = dec:decode(buffer.tostring(slice(mainFile, u1[1], u1[2]))) + t:check(f ~= nil and buffer.tostring((f :: any).pixels) == ref[1], "string unit decodes") + t:check(dec.width == W and dec.height == H and math.abs(dec.frameRate - 24) < 0.01, "sequence fields") + t:check(f.pictureType == Mpeg1.PICTURE_I and f.codedWidth == 320 and buffer.len(f.y) == 320 * 192, "frame fields") + t:eq(dec.stats.skipped, 1, "stats.skipped") +end + +do -- rgba = false: planes only, frameImage still gives both + local dec = Mpeg1.new({ rgba = false }) + local u1 = main.units[1] + local f = dec:decode(mainFile, u1[1], u1[2]) :: any + t:check(f ~= nil and f.pixels == nil and buffer.len(f.y) > 0 and buffer.len(f.cb) == buffer.len(f.y) // 4, "rgba = false") + local img = Mpeg1.frameImage(f, true) :: Types.Image + t:check(img and buffer.tostring(img.pixels) == ref[1], "frameImage(f, true) after rgba = false") + local y = Mpeg1.frameImage(f) :: Types.Image + t:check(y.format == "yuv420p" and buffer.readu8(y.pixels, W) == buffer.readu8(f.y, f.codedWidth), "frameImage crops the coded width") +end + +do -- reset (seek): the next picture must be an I-picture again + local dec = Mpeg1.new() + for i = 1, 5 do + local u = main.units[i] + dec:decode(mainFile, u[1], u[2]) + end + dec:reset() + local u = main.units[10] + t:check(dec:decode(mainFile, u[1], u[2]) == nil, "P after reset has no reference") + u = main.units[1] + local f = dec:decode(mainFile, u[1], u[2]) + t:check(f ~= nil and buffer.tostring((f :: any).pixels) == ref[1], "I after reset") +end + +do -- tags (pts) follow pictures through reordering + local fx = STREAMS[11] + local b = b64(fx.file) + local dec = Mpeg1.new({ reorder = true, rgba = false }) + local order = {} + for i, u in fx.units do + local f = dec:decode(b, u[1], u[2], i) + if f then + table.insert(order, f) + end + end + while true do + local f = dec:flush() + if f == nil then + break + end + table.insert(order, f) + end + t:eq(#order, #fx.units, "bframes: every picture out") + local sawB = false + for i = 2, #order do + local a, c = order[i - 1], order[i] + if c.temporalReference ~= 0 then + t:check(c.temporalReference == a.temporalReference + 1, "display order at " .. i) + end + if c.pictureType == Mpeg1.PICTURE_B then + sawB = true + t:check(c.tag == a.tag + 1 or a.pictureType ~= Mpeg1.PICTURE_B, "B tag order") + end + end + t:check(sawB, "the stream has B-frames") + local d2 = Mpeg1.new() + for i, u in fx.units do + local f = d2:decode(b, u[1], u[2], i) + t:check(f ~= nil and f.tag == i, "decode order tag " .. i) + end +end + +do -- truncated units: every prefix length of a picture, then recovery + local dec = Mpeg1.new() + local u1 = main.units[1] + for k = 0, u1[2], 97 do + Mpeg1.new():decode(mainFile, u1[1], k) + end + for i = 1, 6 do + local u = main.units[i] + dec:decode(mainFile, u[1], u[2] // 2) + end + local f = dec:decode(mainFile, main.units[1][1], main.units[1][2]) + t:check(f ~= nil and buffer.tostring((f :: any).pixels) == ref[1], "recovers at an I-picture after truncation") +end + +-- bit flips and byte garbage in every unit: no throw, sane frames +local rounds = 0 +for _, k in { 2, 11, 8, 6 } do + local fx = STREAMS[k] + local b = b64(fx.file) + for round = 1, 6 do + local dec = Mpeg1.new({ reorder = round % 2 == 0 }) + for _, u in fx.units do + local unit = slice(b, u[1], u[2]) + local nflip = if round <= 3 then round * 3 else 40 + for _ = 1, nflip do + local at = between(0, u[2] - 1) + if round == 6 then + buffer.writeu8(unit, at, between(0, 255)) + else + buffer.writeu8(unit, at, bit32.bxor(buffer.readu8(unit, at), bit32.lshift(1, between(0, 7)))) + end + end + local ok, f = pcall(dec.decode, dec, unit) + t:check(ok, fx.name .. ": corrupt unit threw " .. tostring(f)) + if f then + t:check(buffer.len((f :: any).pixels) == f.width * f.height * 4, "frame size") + end + end + while dec:flush() do + end + rounds += 1 + end +end +t:note("%d corrupted-stream rounds", rounds) + +do -- streamed garbage and random units + local dec = Mpeg1.new() + for _ = 1, 300 do + local n = between(0, 3000) + local g = buffer.create(n) + for i = 0, n - 1 do + local r = between(0, 9) + buffer.writeu8(g, i, if r < 3 then 0 elseif r == 3 then 1 elseif r == 4 then 0xB3 else between(0, 255)) + end + dec:write(g) + while dec:decodeFrame() do + end + dec:decode(g) + end + dec:reset() + local f = dec:decode(mainFile, main.units[1][1], main.units[1][2]) + t:check(f ~= nil and buffer.tostring((f :: any).pixels) == ref[1], "clean after garbage") +end + +do -- a hostile sequence header: a huge size is rejected + local b = buffer.create(16) + buffer.writestring(b, 0, "\0\0\1\xB3\xFF\xFF\xFF\x13\xFF\xFF\xE0\x18\0\0\1\xB8") + local dec = Mpeg1.new({ maxPixels = 1000 * 1000 }) + dec:decode(b) + t:eq(dec.width, 0, "oversized sequence header rejected") +end + +-- 4. the fuzz pass: whole elementary streams (cut, mutated, garbage) through one decoder each +do + local samples = {} + for _, k in { 1, 9 } do + local fx = STREAMS[k] + local b = b64(fx.file) + local u = fx.units + table.insert(samples, buffer.tostring(slice(b, 0, u[4][1] + u[4][2]))) + end + t:fuzz("decode", function(b: buffer) + local dec = Mpeg1.new({ reorder = true }) + local out = { dec:decode(b) } + while dec:flush() do + end + return table.unpack(out) + end, samples, { mutations = 12, keepHeader = 4 }) +end + +t:done() diff --git a/tools/fixtures/mpeg1.py b/tools/fixtures/mpeg1.py new file mode 100644 index 0000000..bf54b0a --- /dev/null +++ b/tools/fixtures/mpeg1.py @@ -0,0 +1,170 @@ +# MPEG-1 video fixtures for codecs/Mpeg1 (tools/fixtures.py), ported from mpeg1-luau tools/fixtures.py: elementary +# streams made by ffmpeg's mpeg1video encoder (testsrc2 / mandelbrot, several bit rates, odd sizes, custom matrices, +# B-frames, a size change), their access units, and ffmpeg's own decode of each as references: +# tests/gen/mpeg1_.luau { name, width, height, frames, file (base64), units = { { offset, length } }, +# means = { { r, g, b } } (every frame, display order, ffmpeg's RGBA), +# rgba = { { index, pixels } } (two whole RGBA frames, base64 zlib), +# yuv = { { index, planes } } (three whole frames as ffmpeg -pix_fmt yuv420p, base64 zlib) } +# tests/gen/mpeg1_sizechange.luau { file (base64), parts = { { width, height, frames, last (RGBA, base64 zlib) } } } +# tests/gen/mpeg1_bench.luau { { width, height, file (base64), units } }: 320x240 and 640x480 streams (with +# B-frames) for tools/bench.luau +# Binary fields are base64 (file, units' data) or base64 of zlib data (frames: the test inflates them with +# codecs/Deflate): Luau string literals of binary data cost ~3.7 bytes per byte, base64 1.33. With short streams and +# few whole frames the set stays near 10 MB. +import base64, os, shutil, subprocess, tempfile, zlib + +def b64(b): + return base64.b64encode(b).decode() + + +def z64(b): + return base64.b64encode(zlib.compress(b, 9)).decode() + + +FF = ["-hide_banner", "-loglevel", "error", "-y"] +ENC = ["-c:v", "mpeg1video", "-f", "mpeg1video"] +# a non-default intra matrix (steeper) and inter matrix (rising), 64 values in natural order +INTRA = ",".join(str(8 + (i // 8 + i % 8) * 3) for i in range(64)) +INTER = ",".join(str(16 + (i // 8 + i % 8)) for i in range(64)) + + +def src(kind, w, h, rate, t): + return ["-f", "lavfi", "-i", "%s=size=%dx%d:rate=%s" % (kind, w, h, rate), "-t", str(t)] + + +# name: (ffmpeg input + encoder args, size patched into the sequence headers or None, rgba sample picks, yuv picks) +CASES = { + "qcif_200k": (src("testsrc2", 176, 144, 25, 1.2) + ["-b:v", "200k", "-bf", "0", "-g", "50"], None), + "main_450k": (src("testsrc2", 320, 180, 24, 1.5) + ["-b:v", "450k", "-bf", "0", "-g", "48"], None), + "zoom_150k": (src("mandelbrot", 320, 180, 24, 1.5) + ["-b:v", "150k", "-bf", "0", "-g", "48"], None), + "zoom_1500k": (src("mandelbrot", 320, 180, 24, 1) + ["-b:v", "1500k", "-bf", "0", "-g", "48"], None), + "big_1000k": (src("testsrc2", 640, 360, 24, 0.5) + ["-b:v", "1000k", "-bf", "0", "-g", "36"], None), + # odd sizes: ffmpeg's encoder only writes even ones, so the size in the sequence headers is patched; the + # reference is ffmpeg's decode of the unpatched stream, cropped (swscale's odd-size RGBA path interpolates + # chroma differently from its even-size one, which is what the decoder matches) + "odd_173x95": (src("mandelbrot", 174, 96, 24, 1) + ["-b:v", "300k", "-bf", "0", "-g", "24"], (173, 95)), + "bframes": (src("testsrc2", 320, 180, 24, 1) + ["-b:v", "600k", "-bf", "2", "-g", "24"], None), + "bframes_zoom": (src("mandelbrot", 176, 144, 24, 1.5) + ["-b:v", "250k", "-bf", "3", "-g", "16"], None), + "matrix": (src("testsrc2", 176, 144, 25, 1) + ["-b:v", "300k", "-bf", "0", "-g", "12", + "-intra_matrix", INTRA, "-inter_matrix", INTER], None), + "q1": (src("mandelbrot", 176, 144, 25, 0.6) + ["-q:v", "1", "-bf", "0", "-g", "8"], None), + "q31": (src("testsrc2", 176, 144, 25, 1) + ["-q:v", "31", "-bf", "0", "-g", "25"], None), + "zeromv": (src("mandelbrot", 176, 144, 25, 1) + ["-b:v", "300k", "-bf", "0", "-g", "25", "-me_method", "zero"], None), +} + + +def patch_size(es, w, h): + # every sequence header (00 00 01 B3): 12-bit width, 12-bit height + b = bytearray(es) + i = 0 + while True: + i = b.find(b"\x00\x00\x01\xb3", i) + if i < 0: + return bytes(b) + b[i + 4] = w >> 4 + b[i + 5] = ((w & 15) << 4) | (h >> 8) + b[i + 6] = h & 255 + i += 4 + + +def access_units(es): + # one unit per picture: from the first header byte before it (sequence / GOP) to the next unit start + starts = [] + i = 0 + pending = None + while True: + i = es.find(b"\x00\x00\x01", i) + if i < 0 or i + 3 >= len(es): + break + code = es[i + 3] + if code in (0xB3, 0xB8) and pending is None: + pending = i + elif code == 0x00: + starts.append(pending if pending is not None else i) + pending = None + i += 3 + return [[s, (starts[k + 1] if k + 1 < len(starts) else len(es)) - s] for k, s in enumerate(starts)] + + +def crop(frames, w, h, cw, ch, bpp): + fs = w * h * bpp + out = bytearray() + for k in range(len(frames) // fs): + for y in range(ch): + o = k * fs + y * w * bpp + out += frames[o:o + cw * bpp] + return bytes(out) + + +def crop_yuv(frames, w, h, cw, ch): + fs = w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2) + out = bytearray() + for k in range(len(frames) // fs): + f = frames[k * fs:(k + 1) * fs] + out += crop(f[:w * h], w, h, cw, ch, 1) + c = ((w + 1) // 2) * ((h + 1) // 2) + for pl in range(2): + out += crop(f[w * h + pl * c:w * h + (pl + 1) * c], (w + 1) // 2, (h + 1) // 2, (cw + 1) // 2, (ch + 1) // 2, 1) + return bytes(out) + + +def generate(ctx): + ffmpeg = shutil.which("ffmpeg") or ctx.nix("ffmpeg", ["sh", "-c", "command -v ffmpeg"]).decode().strip() + ffprobe = shutil.which("ffprobe") or os.path.join(os.path.dirname(ffmpeg), "ffprobe") + + def ff(args): + subprocess.run([ffmpeg] + FF + args, check=True, capture_output=True) + + with tempfile.TemporaryDirectory(prefix="formats-mpeg1-") as tmp: + def encode(name, args, size): + path = os.path.join(tmp, name + ".m1v") + ff(args + ENC + [path]) + es = open(path, "rb").read() + return (patch_size(es, *size) if size else es), path + + def reference(path, fmt): + out = path + "." + fmt + ff(["-i", path, "-f", "rawvideo", "-pix_fmt", fmt, out]) + r = subprocess.run([ffprobe, "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height", + "-of", "csv=p=0", path], check=True, capture_output=True) + w, h = (int(x) for x in r.stdout.decode().strip().split(",")[:2]) + return open(out, "rb").read(), w, h + + for name, (args, size) in CASES.items(): + es, path = encode(name, args, size) + rgba, w, h = reference(path, "rgba") + yuv, _, _ = reference(path, "yuv420p") + if size: + rgba, yuv = crop(rgba, w, h, size[0], size[1], 4), crop_yuv(yuv, w, h, size[0], size[1]) + w, h = size + fs, ys = w * h * 4, w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2) + n = len(rgba) // fs + means = [] + for k in range(n): + fr = rgba[k * fs:(k + 1) * fs] + means.append([round(sum(fr[c::4]) / (w * h), 4) for c in range(3)]) + # whole frames: the first P-picture and the last one (the most drift) as RGBA, three as yuv420p + picks = sorted({1, n - 1}) if n > 2 else list(range(n)) + ypicks = sorted({0, n // 2, n - 1}) + ctx.emit("mpeg1_" + name, { + "name": name, "width": w, "height": h, "frames": n, "file": b64(es), "units": access_units(es), + "means": means, + "rgba": [{"index": k + 1, "pixels": z64(rgba[k * fs:(k + 1) * fs])} for k in picks], + "yuv": [{"index": k + 1, "planes": z64(yuv[k * ys:(k + 1) * ys])} for k in ypicks], + }) + + # a size change mid-stream: 176x144 then 320x180 (each part decoded by ffmpeg on its own) + a, pa = encode("sc_a", src("testsrc2", 176, 144, 24, 0.5) + ["-b:v", "200k", "-bf", "0", "-g", "6"], None) + b, pb = encode("sc_b", src("mandelbrot", 320, 180, 24, 0.5) + ["-b:v", "400k", "-bf", "0", "-g", "6"], None) + parts = [] + for path in (pa, pb): + rg, w, h = reference(path, "rgba") + n = len(rg) // (w * h * 4) + parts.append({"width": w, "height": h, "frames": n, "last": z64(rg[(n - 1) * w * h * 4:])}) + ctx.emit("mpeg1_sizechange", {"file": b64(a + b), "parts": parts}) + + bench = [] + for w, h, rate in ((320, 240, "600k"), (640, 480, "1500k")): + es, _ = encode("bench", src("testsrc2", w, h, 25, 2) + ["-b:v", rate, "-bf", "2", "-g", "25"], None) + bench.append({"width": w, "height": h, "file": b64(es), "units": access_units(es)}) + ctx.emit("mpeg1_bench", bench) From 87d22bf67a3de7195b93a1fcf71fe87c896c3748 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:42:30 -0500 Subject: [PATCH 5/6] ws-video-codecs: mjpeg fixtures as base64 / zlib (8.6 -> 1.0 MB); codecs/Jpeg: no type assertion as an assignment target (darklua) --- src/Formats/codecs/Jpeg/init.luau | 3 ++- tests/codecs/jpeg.luau | 33 ++++++++++++++++++++++++++----- tools/fixtures/mjpeg.py | 32 +++++++++++++++++++----------- 3 files changed, 51 insertions(+), 17 deletions(-) diff --git a/src/Formats/codecs/Jpeg/init.luau b/src/Formats/codecs/Jpeg/init.luau index ef3323d..3163222 100644 --- a/src/Formats/codecs/Jpeg/init.luau +++ b/src/Formats/codecs/Jpeg/init.luau @@ -296,7 +296,8 @@ function Jpeg.decode(buf: buffer, off: number?, len: number?, opts: DecodeOption local truncated = img.meta.truncated or b.meta.truncated img = weave(img, b) img.meta.truncated = truncated - (img.meta.source :: any).fields = 2 + local source: any = img.meta.source + source.fields = 2 end end end diff --git a/tests/codecs/jpeg.luau b/tests/codecs/jpeg.luau index 9542a11..5b42f8d 100644 --- a/tests/codecs/jpeg.luau +++ b/tests/codecs/jpeg.luau @@ -9,11 +9,34 @@ local Jpeg = require("@formats/codecs/Jpeg") local Crc32 = require("@formats/core/Crc32") local Err = require("@formats/core/Err") local Types = require("@formats/Types") +local Base64 = require("@formats/core/Base64") +local Deflate = require("@formats/codecs/Deflate") local Fx = require("@tests/gen/mjpeg_cases") local Enc = require("@tests/gen/mjpeg_enc") local t = T.suite("codecs/jpeg") +-- the fixtures' binary fields: base64, and base64 of zlib data for raw planes / pixels +local function b64(s: string): string + return buffer.tostring(Base64.decode(s) :: buffer) +end +local function z64(s: string): buffer + return Deflate.zlib(Base64.decode(s) :: buffer) :: buffer +end +for _, s in Fx.streams do + for _, f in s.frames do + f.data = b64(f.data) + end + s.ff.yuv = z64(s.ff.yuv) + if s.ff.rgba then + s.ff.rgba = z64(s.ff.rgba) + end +end +Fx.fields.data = b64(Fx.fields.data) +for _, c in Enc do + c.want = b64(c.want) +end + -- PSNR of n bytes of a at ao against b at bo local function psnr(a: buffer, ao: number, b: buffer, bo: number, n: number): number local se = 0 @@ -68,7 +91,7 @@ do t:check(rgba and rgba.format == "rgba8", label .. ": rgba8") t:eq(Crc32.of(rgba.pixels), f.rgba, label .. ": rgba8 = djpeg") if i == 1 then - local ref = buffer.fromstring(s.ff.yuv) + local ref = s.ff.yuv local py = psnr(img.pixels, 0, ref, 0, w * h) local pc = math.min(psnr(img.pixels, w * h, ref, w * h, cw * ch), psnr(img.pixels, w * h + cw * ch, ref, w * h + cw * ch, cw * ch)) -- ffmpeg's IDCT differs from libjpeg's islow by rounding only; its 4:2:2 / 4:4:4 -> 4:2:0 is a filter @@ -76,7 +99,7 @@ do t:check(pc > (if s.sampling == "420" then 55 else 20), string.format("%s: chroma PSNR %.1f dB against ffmpeg", s.name, pc)) worstY, worstC = math.min(worstY, py), math.min(worstC, pc) if s.ff.rgba then - local pr = psnrRgb(rgba.pixels, buffer.fromstring(s.ff.rgba), w * h) + local pr = psnrRgb(rgba.pixels, s.ff.rgba, w * h) -- swscale upsamples chroma differently from libjpeg (fancy): testsrc2's sharp colour edges cost ~10 dB t:check(pr > 25, string.format("%s: rgba PSNR %.1f dB against ffmpeg", s.name, pr)) worstRgb = math.min(worstRgb, pr) @@ -103,7 +126,7 @@ do t:check(img and img.width == F.width and img.height == F.height and img.format == "yuv420p", "fields: one 320x240 yuv420p frame") t:eq(img.meta.source.fields, 2, "fields: meta.source.fields") t:eq(Crc32.of(img.pixels), F.yuv, "fields: woven yuv420p planes = TurboJPEG's fields woven") - local src = buffer.fromstring(F.src) + local src = z64(F.src) local p = psnr(img.pixels, 0, src, 0, F.width * F.height) t:check(p > 35, string.format("fields: luma PSNR %.1f dB against the source frame", p)) local rgba = Jpeg.decode(b) :: Types.Image @@ -122,7 +145,7 @@ do local exact = 0 for _, c in Enc do local img = Types.Image.new(c.width, c.height, "yuv420p") - img.pixels = buffer.fromstring(c.yuv) + img.pixels = z64(c.yuv) local out, err = Jpeg.encode(img, { quality = c.quality }) t:check(out, c.name .. ": " .. tostring(err)) local s = buffer.tostring(out :: buffer) @@ -151,7 +174,7 @@ do -- grey from yuv420p: the luma plane only local c = Enc[1] local img = Types.Image.new(c.width, c.height, "yuv420p") - img.pixels = buffer.fromstring(c.yuv) + img.pixels = z64(c.yuv) local g = Jpeg.encode(img, { quality = 80, gray = true }) :: buffer local gi = Jpeg.info(g) t:check(gi and gi.components == 1, "yuv420p with gray = true: one component") diff --git a/tools/fixtures/mjpeg.py b/tools/fixtures/mjpeg.py index 63c0eda..258ca8a 100644 --- a/tools/fixtures/mjpeg.py +++ b/tools/fixtures/mjpeg.py @@ -13,12 +13,22 @@ # ff = { yuv, rgba? } } }, fields = { data, width, height, yuv, rgba, src } } # tests/gen/mjpeg_enc.luau yuv420p sources and what tj3CompressFromYUV8 writes for them at a quality (our # encoder must write the same bytes), with djpeg's CRC and ffmpeg's PSNR of that file -# tests/gen/mjpeg_bench.luau 320x240 and 640x480 frames (4:2:0, 4:2:2) and a 640x480 yuv420p source -import ctypes, math, os, shutil, subprocess, tempfile, zlib +# tests/gen/mjpeg_bench.luau 320x240 and 640x480 frames (4:2:0, 4:2:2) and yuv420p sources +# Binary fields are base64 (JPEG data) or base64 of zlib data (raw planes / pixels, inflated with codecs/Deflate): +# Luau string literals of binary data cost ~3.7 bytes per byte, base64 1.33. +import base64, ctypes, math, os, shutil, subprocess, tempfile, zlib FF = ["-hide_banner", "-loglevel", "error", "-y"] +def b64(b): + return base64.b64encode(b).decode() + + +def z64(b): + return base64.b64encode(zlib.compress(b, 9)).decode() + + def tool(ctx, pkg, name): p = shutil.which(name) if p: @@ -206,10 +216,10 @@ def _generate(ctx, work): for fr in frames: ref = fr data = mutate(fr) if mutate else fr - entries.append({"data": data, "yuv": zlib.crc32(tj.yuv420(ref)), "rgba": rgba_crc(ref)}) - ref = {"yuv": ffdecode(frames[0], "yuvj420p")} + entries.append({"data": b64(data), "yuv": zlib.crc32(tj.yuv420(ref)), "rgba": rgba_crc(ref)}) + ref = {"yuv": z64(ffdecode(frames[0], "yuvj420p"))} if w * h <= 30000 or name == "testsrc_420": # keep tests/gen small: rgba for the small ones and one 320x240 - ref["rgba"] = ffdecode(frames[0], "rgba") + ref["rgba"] = z64(ffdecode(frames[0], "rgba")) streams.append({"name": name, "width": w, "height": h, "sampling": pix[4:7], "frames": entries, "ff": ref}) stream("testsrc_420", "testsrc2", 320, 240, "yuvj420p", 4, ("-q:v", "3")) @@ -267,8 +277,8 @@ def _generate(ctx, work): return rgba_of_pnm(subprocess.run([djpeg, "-dct", "int", "-pnm", p], check=True, capture_output=True).stdout) wr = weave(rgba_raw(fields[0]), rgba_raw(fields[1]), fw, hf, 4) - ctx.emit("mjpeg_cases", {"streams": streams, "fields": {"data": data, "width": fw, "height": fh, - "yuv": zlib.crc32(wy), "rgba": zlib.crc32(wr), "src": fy}}) + ctx.emit("mjpeg_cases", {"streams": streams, "fields": {"data": b64(data), "width": fw, "height": fh, + "yuv": zlib.crc32(wy), "rgba": zlib.crc32(wr), "src": z64(fy)}}) # the encoder: yuv420p sources, byte-identical with tj3CompressFromYUV8 enc = [] @@ -289,8 +299,8 @@ def _generate(ctx, work): if got: se = sum((a - b) ** 2 for a, b in zip(got[:w * h], raw[:w * h])) psnr = 99.0 if se == 0 else 10 * math.log10(255 * 255 * w * h / se) - enc.append({"name": "%s_q%d" % (name, q), "width": w, "height": h, "quality": q, "yuv": raw, - "want": want, "rgba": rgba_crc(want), "ffpsnr": round(psnr, 3)}) + enc.append({"name": "%s_q%d" % (name, q), "width": w, "height": h, "quality": q, "yuv": z64(raw), + "want": b64(want), "rgba": rgba_crc(want), "ffpsnr": round(psnr, 3)}) ctx.emit("mjpeg_enc", enc) bench = [] @@ -299,9 +309,9 @@ def _generate(ctx, work): o = W("bench.mjpeg") ff(*source("testsrc2", w, h, 1), "-pix_fmt", pix, "-c:v", "mjpeg", "-q:v", "3", "-f", "mjpeg", o) fr = split(open(o, "rb").read())[0] - bench.append({"name": name, "width": w, "height": h, "data": fr, "yuv": zlib.crc32(tj.yuv420(fr))}) + bench.append({"name": name, "width": w, "height": h, "data": b64(fr), "yuv": zlib.crc32(tj.yuv420(fr))}) srcs = [] for w, h in ((320, 240), (640, 480)): ff(*source("testsrc2", w, h, 1), "-pix_fmt", "yuv420p", "-f", "rawvideo", W("b.yuv")) - srcs.append({"width": w, "height": h, "yuv": open(W("b.yuv"), "rb").read()}) + srcs.append({"width": w, "height": h, "yuv": z64(open(W("b.yuv"), "rb").read())}) ctx.emit("mjpeg_bench", {"frames": bench, "sources": srcs}) From 850ec634a6ab8576c8611174328ed2e952de29aa Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:49:33 -0500 Subject: [PATCH 6/6] ws-video-codecs: bench lines: MJPEG decode (yuv / rgba) and yuv420p encode fps at 320x240 / 640x480, MPEG-1 decode fps (yuv / rgba) --- tools/bench.luau | 51 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/tools/bench.luau b/tools/bench.luau index 710195d..decc77c 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -535,3 +535,54 @@ do Webp.encode(img, { effort = 1 }) end) end +-- ------------------------------------------------------------------------------------------- ws-video-codecs: fps +do + local Jpeg = require("@formats/codecs/Jpeg") + local Mpeg1 = require("@formats/codecs/Mpeg1") + local Base64 = require("@formats/core/Base64") + local Types = require("@formats/Types") + local MB = require("@tests/gen/mjpeg_bench") + local M1 = require("@tests/gen/mpeg1_bench") + -- best of n runs of f (which handles `frames` frames): ms per frame and frames per second + local function fps(label: string, n: number, frames: number, f: () -> ()) + f() + local dt = math.huge + for _ = 1, n do + local t0 = os.clock() + f() + dt = math.min(dt, os.clock() - t0) + end + print(string.format("%-8s %-30s %8.2f ms %7.1f fps", runtime, label, dt * 1000 / frames, frames / dt)) + end + for _, c in MB.frames do + local b = Base64.decode(c.data) :: buffer + local img = assert(Jpeg.decode(b, 0, nil, { yuv = true })) + assert(Crc32.of(img.pixels) == c.yuv, "mjpeg bench: " .. c.name .. " does not match TurboJPEG") + fps("mjpeg decode yuv " .. c.name, 10, 1, function() + Jpeg.decode(b, 0, nil, { yuv = true }) + end) + fps("mjpeg decode rgba " .. c.name, 10, 1, function() + Jpeg.decode(b) + end) + end + for _, s in MB.sources do + local img = Types.Image.new(s.width, s.height, "yuv420p") + img.pixels = assert(Deflate.zlib(Base64.decode(s.yuv) :: buffer)) + fps(string.format("mjpeg encode yuv %dx%d q85", s.width, s.height), 5, 1, function() + Jpeg.encode(img, { quality = 85 }) + end) + end + for _, s in M1 do + local file = Base64.decode(s.file) :: buffer + for _, rgba in { false, true } do + fps(string.format("mpeg1 decode %s %dx%d", if rgba then "rgba" else "yuv", s.width, s.height), 3, #s.units, function() + local dec = Mpeg1.new({ reorder = true, rgba = rgba }) + for i, u in s.units do + dec:decode(file, u[1], u[2], i) + end + while dec:flush() do + end + end) + end + end +end