imgA: image/jpeg (absorbed jpeg-luau decoder + arithmetic coding, meta, EXIF orientation, encoder byte-identical to cjpeg) and codecs/Dct

- codecs/Dct: jpeg-luau's islow / reduced IDCTs + a forward islow DCT with jcdctmgr.c's quantiser; tests/codecs/dct.luau
- image/jpeg: Decode (marker parser, absorbed + reader ranges, SOF9/SOF10 + DAC, EXIF / ICC / COM / JFIF density),
  Scan + Color (absorbed), Arith (jdarith.c port), Encode (baseline / optimised / progressive, 444/422/420, restarts,
  APP1/APP2/COM from meta), Tables (annex K)
- tests: 115 cjpeg/jpegtran/Pillow files, 444 decodes bit-exact with djpeg at 1, 1/2, 1/4, 1/8 (104 arithmetic),
  38 encodes byte-identical to cjpeg (so djpeg decodes them), orientation, meta, truncation, fuzz
- licenses: libjpeg-turbo LICENSE + README.ijg, NOTICE rows
- tools/bench.luau: jpeg block; tools/bench.sh runs every fixture generator (bench blocks read their outputs)
This commit is contained in:
4DBug committed 2026-10-31 08:44:15 -05:00
1 parent 2eee0bc1a6
commit 692ef055de
19 files changed
+4613 -1

No files matched your search

+158
View File
@@ -0,0 +1,158 @@
-- codecs/Dct tests: the islow inverse DCT against a double-precision reference (within 1 level per sample, as T.81
-- annex A accuracy needs), forward DCT + quantiser against the reference transform (round to nearest of v / (8 q)),
-- fdct -> idct round trips at q = 1 within 1 level, edge replication of fdctQuantize, and garbage coefficients never
-- throw (outputs stay clamped). The bit-exact djpeg / cjpeg checks are in tests/image/jpeg.luau.
local T = require("@tests/T")
local Dct = require("@formats/codecs/Dct")
local t = T.suite("dct")
local rand = T.rng(11)
local C = {}
for u = 0, 7 do
C[u] = if u == 0 then math.sqrt(0.5) else 1
end
local cosT = {}
for x = 0, 7 do
for u = 0, 7 do
cosT[x * 8 + u] = math.cos((2 * x + 1) * u * math.pi / 16)
end
end
local ones = buffer.create(128)
for i = 0, 63 do
buffer.writeu16(ones, i * 2, 1)
end
-- inverse: random sparse coefficients, compare with the float IDCT
do
local worst = 0
for trial = 1, 300 do
local coef = buffer.create(128)
local F = {}
for i = 0, 63 do
local v = 0
if rand(4) == 0 or i == 0 then
v = rand(512) - 256
if i == 0 then
v = rand(2048) - 1024
end
end
F[i] = v
buffer.writei16(coef, i * 2, v)
end
local plane = buffer.create(128)
Dct.idctBlock(coef, 0, ones, plane, 0, 8, 2, 128, 255)
for y = 0, 7 do
for x = 0, 7 do
local s = 0
for v = 0, 7 do
for u = 0, 7 do
s += C[u] * C[v] * F[v * 8 + u] * cosT[x * 8 + u] * cosT[y * 8 + v]
end
end
local want = math.clamp(math.floor(s / 4 + 128 + 0.5), 0, 255)
local got = buffer.readu16(plane, (y * 8 + x) * 2)
worst = math.max(worst, math.abs(got - want))
end
end
local _ = trial
end
t:check(worst <= 1, "idct within 1 of the float reference: " .. worst)
t:note("idct: worst error %d over 300 random blocks", worst)
end
-- forward + quantiser
do
local worst = 0
for _ = 1, 200 do
local src = buffer.create(64)
for i = 0, 63 do
buffer.writeu8(src, i, rand(256))
end
local q = buffer.create(128)
for i = 0, 63 do
buffer.writeu16(q, i * 2, 1 + rand(40))
end
local coef = buffer.create(128)
Dct.fdctQuantize(src, 8, 0, 0, 8, 8, q, coef, 0)
for v = 0, 7 do
for u = 0, 7 do
local s = 0
for y = 0, 7 do
for x = 0, 7 do
s += (buffer.readu8(src, y * 8 + x) - 128) * cosT[x * 8 + u] * cosT[y * 8 + v]
end
end
s *= C[u] * C[v] / 4
local want = s / buffer.readu16(q, (v * 8 + u) * 2)
worst = math.max(worst, math.abs(buffer.readi16(coef, (v * 8 + u) * 2) - want))
end
end
end
t:check(worst <= 0.75, "fdct + quantise within rounding of the float reference: " .. worst)
-- round trip at q = 1
local rt = 0
for _ = 1, 100 do
local src = buffer.create(64)
for i = 0, 63 do
buffer.writeu8(src, i, rand(256))
end
local coef = buffer.create(128)
Dct.fdctQuantize(src, 8, 0, 0, 8, 8, ones, coef, 0)
local plane = buffer.create(128)
Dct.idctBlock(coef, 0, ones, plane, 0, 8, 2, 128, 255)
for i = 0, 63 do
rt = math.max(rt, math.abs(buffer.readu16(plane, i * 2) - buffer.readu8(src, i)))
end
end
t:check(rt <= 1, "fdct -> idct round trip at q = 1: " .. rt)
-- edge replication: a 3x2 image is the same as its 8x8 edge-extended version
local small = T.bytes({ 10, 200, 30, 40, 50, 250 })
local ext = buffer.create(64)
for y = 0, 7 do
for x = 0, 7 do
buffer.writeu8(ext, y * 8 + x, buffer.readu8(small, math.min(y, 1) * 3 + math.min(x, 2)))
end
end
local a, b = buffer.create(128), buffer.create(128)
Dct.fdctQuantize(small, 3, 0, 0, 3, 2, ones, a, 0)
Dct.fdctQuantize(ext, 8, 0, 0, 8, 8, ones, b, 0)
t:check(buffer.tostring(a) == buffer.tostring(b), "edge replication")
end
-- components and garbage: clamped output, no throw
do
local coef = buffer.create(4 * 3 * 128)
for i = 0, buffer.len(coef) // 2 - 1 do
buffer.writei16(coef, i * 2, rand(65536) - 32768)
end
local q = buffer.create(128)
for i = 0, 63 do
buffer.writeu16(q, i * 2, rand(65536))
end
for _, size in { 8, 4, 2, 1 } do
for _, prec in { { 2, 128, 255 }, { 1, 2048, 4095 } } do
local plane = buffer.create(4 * size * 3 * size * 2)
local ok = pcall(Dct.idctComponent, coef, q, 4, 3, size, plane, prec[1], prec[2], prec[3])
t:check(ok, "idctComponent size " .. size .. " on garbage")
local inRange = true
for i = 0, buffer.len(plane) // 2 - 1 do
if buffer.readu16(plane, i * 2) > prec[3] then
inRange = false
end
end
t:check(inRange, "clamped output, size " .. size)
end
end
local samples = { string.rep("\0", 128) }
t:fuzz("idctBlock", function(b: buffer)
local cb = buffer.create(128)
buffer.copy(cb, 0, b, 0, math.min(128, buffer.len(b)))
local plane = buffer.create(128)
Dct.idctBlock(cb, 0, q, plane, 0, 8, 2, 128, 255)
return plane
end, samples, { garbage = 50 })
end
t:done()
+293
View File
@@ -0,0 +1,293 @@
-- image/jpeg tests: every cjpeg / jpegtran fixture (baseline, progressive, arithmetic, every sampling, restarts, grey,
-- RGB, 12-bit, odd sizes, stripped DHT) against djpeg's decodes at scales 1, 1/2, 1/4, 1/8 (bit-exact, CRC-32);
-- CMYK / YCCK against Pillow; refused files; info / meta (EXIF orientation applied, ICC, comment, density); the
-- encoder byte-identical to cjpeg for the same settings, its PSNR, round trips through our decoder; truncated files;
-- the fuzz no-throw pass. Ported from jpeg-luau tests/jpeg.luau. Fixtures: tools/fixtures/jpeg.py.
local T = require("@tests/T")
local Jpeg = require("@formats/image/jpeg")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Dec = require("@tests/gen/jpeg_dec")
local Enc = require("@tests/gen/jpeg_enc")
local t = T.suite("jpeg")
local function decode(data: any, opts: any?): (any, any)
local b = if type(data) == "string" then buffer.fromstring(data) else data
return Jpeg.decode(Bytes.reader(b), opts)
end
-- the contract
t:eq(Jpeg.name, "jpeg", "name")
t:eq(Jpeg.category, "image", "category")
t:check(Jpeg.caps.decode and Jpeg.caps.encode, "caps")
-- decodes against djpeg / Pillow
local files: { [string]: string } = {}
do
local refs, arith = 0, 0
for _, c in Dec do
files[c.name] = c.data
if c.err then
local img, err = decode(c.data)
t:check(img == nil and err and err.code == Err.UNSUPPORTED and string.find(err.message, c.err, 1, true), c.name .. ": expected UNSUPPORTED " .. c.err .. ", got " .. tostring(err))
elseif c.cmyk then
local img, err = decode(c.data)
t:check(img, c.name .. ": " .. tostring(err))
local n = #c.cmyk // 3
t:eq(img.width * img.height, n, c.name .. ": size")
local worst = 0
for i = 0, n - 1 do
for k = 0, 2 do
worst = math.max(worst, math.abs(buffer.readu8(img.pixels, i * 4 + k) - string.byte(c.cmyk, i * 3 + k + 1)))
end
end
t:check(worst <= 1, c.name .. ": max error " .. worst .. " against Pillow")
refs += 1
else
for _, r in c.refs do
local name = c.name .. " 1/" .. r.scale
local img, err = decode(c.data, { scale = r.scale })
t:check(img, name .. ": " .. tostring(err))
t:check(img.width == r.width and img.height == r.height, string.format("%s: size %dx%d, djpeg %dx%d", name, img.width, img.height, r.width, r.height))
t:check(not img.meta.truncated, name .. ": flagged truncated")
local crc = Crc32.of(img.pixels)
t:check(crc == r.crc, string.format("%s: pixels crc %08x, djpeg %08x", name, crc, r.crc))
refs += 1
if img.meta.source.arithmetic then
arith += 1
end
end
end
end
t:note("%d files, %d decodes bit-exact with djpeg / Pillow (%d arithmetic-coded)", #Dec, refs, arith)
end
local function file(name: string): buffer
return buffer.fromstring(files[name])
end
-- sniff, info, meta, options
do
t:eq(Jpeg.sniff(Bytes.reader(file("photo_q90_420"))), 1, "sniff a JPEG")
t:eq(Jpeg.sniff(Bytes.reader(buffer.fromstring("GIF89a"))), 0, "sniff a GIF")
t:eq(Jpeg.sniff(Bytes.reader(buffer.create(0))), 0, "sniff nothing")
local i = Jpeg.info(Bytes.reader(file("photo_q90_420_prog")))
t:check(i and i.width == 160 and i.height == 120 and i.progressive and i.components == 3, "info: progressive 4:2:0")
t:check(i.sampling[1][1] == 2 and i.sampling[1][2] == 2 and i.sampling[2][1] == 1, "info: sampling")
t:check(i.colorSpace == "ycbcr" and i.precision == 8 and i.jfif and not i.arithmetic, "info: colour space")
t:check(Jpeg.info(Bytes.reader(file("photo_arith_420_prog"))).arithmetic, "info: arithmetic")
t:eq(Jpeg.info(Bytes.reader(file("photo_gray"))).colorSpace, "gray", "info: grey")
t:eq(Jpeg.info(Bytes.reader(file("photo_rgb"))).colorSpace, "rgb", "info: RGB")
t:eq(Jpeg.info(Bytes.reader(file("photo_cmyk"))).colorSpace, "cmyk", "info: CMYK")
t:eq(Jpeg.info(Bytes.reader(file("photo_ycck"))).colorSpace, "ycck", "info: YCCK")
t:eq(Jpeg.info(Bytes.reader(file("photo_12bit_420"))).precision, 12, "info: 12-bit")
local img = decode(file("photo_q90_420_prog"))
local s = img.meta.source
t:check(img.kind == "image" and img.format == "rgba8", "a standard rgba8 Image")
t:check(s.format == "jpeg" and s.progressive and s.components == 3 and s.colorType == "ycbcr" and img.meta.orientation == 1, "meta.source")
local _, e = decode(file("photo_q90_420"), { maxPixels = 1000 })
t:check(e and e.code == Err.LIMIT, "maxPixels: " .. tostring(e))
t:check(decode(file("photo_q90_420"), { maxPixels = 160 * 120 }) ~= nil, "maxPixels at the limit")
local _, e2 = decode(file("photo_q90_420"), { scale = 3 })
t:check(e2 and e2.code == Err.ARG, "bad scale")
local _, e3 = decode("nope")
t:check(e3 and e3.code == Err.CORRUPT, "junk: " .. tostring(e3))
-- a range inside a bigger buffer
local data = files["photo_q90_420"]
local big = buffer.create(#data + 20)
buffer.writestring(big, 11, data)
local a = Jpeg.decode(Bytes.reader(big, 11, #data))
t:check(a and Crc32.of(a.pixels) == Crc32.of(decode(data).pixels), "decode from a sub-range")
end
-- EXIF orientation (both byte orders), applied with opts.orient; ICC + comment + density segments
local function withSegments(data: string, segs: { string }): string
return string.sub(data, 1, 2) .. table.concat(segs) .. string.sub(data, 3)
end
local function seg(marker: number, body: string): string
local len = #body + 2
return "\255" .. string.char(marker, len // 256, len % 256) .. body
end
local function exifSeg(orient: number, le: boolean): string
local tiff
if le then
tiff = "II\42\0\8\0\0\0" .. "\1\0" .. "\18\1\3\0\1\0\0\0" .. string.char(orient, 0, 0, 0) .. "\0\0\0\0"
else
tiff = "MM\0\42\0\0\0\8" .. "\0\1" .. "\1\18\0\3\0\0\0\1" .. string.char(0, orient, 0, 0) .. "\0\0\0\0"
end
return seg(0xE1, "Exif\0\0" .. tiff)
end
do
local base = files["photo_q90_420"]
local plain = decode(base)
local w, h = plain.width, plain.height
local function px(img: any, x: number, y: number): number
return buffer.readu32(img.pixels, (y * img.width + x) * 4)
end
for _, le in { true, false } do
for o = 1, 8 do
local d = withSegments(base, { exifSeg(o, le) })
local img = decode(d)
t:check(img and img.meta.orientation == o, "EXIF orientation " .. o)
t:check(img.meta.exif and buffer.readstring(img.meta.exif, 0, 2) == (if le then "II" else "MM"), "meta.exif")
t:eq(Jpeg.info(Bytes.reader(buffer.fromstring(d))).orientation, o, "info orientation " .. o)
local r = decode(d, { orient = true })
local swap = o >= 5
t:check(r.width == (if swap then h else w) and r.height == (if swap then w else h), "oriented size " .. o)
-- where the source's top-left pixel lands
local tl = px(plain, 0, 0)
local want = ({
{ 0, 0 },
{ r.width - 1, 0 },
{ r.width - 1, r.height - 1 },
{ 0, r.height - 1 },
{ 0, 0 },
{ r.width - 1, 0 },
{ r.width - 1, r.height - 1 },
{ 0, r.height - 1 },
})[o]
t:eq(px(r, want[1], want[2]), tl, "orientation " .. o .. ": top-left pixel")
end
end
local icc = string.rep("icc!", 50)
local d = withSegments(base, {
seg(0xE2, "ICC_PROFILE\0\1\2" .. string.sub(icc, 1, 120)),
seg(0xE2, "ICC_PROFILE\0\2\2" .. string.sub(icc, 121)),
seg(0xFE, "hello jpeg"),
})
local img = decode(d)
t:check(img.meta.icc and buffer.tostring(img.meta.icc) == icc, "ICC chunks joined")
t:check(img.meta.text and img.meta.text.comment == "hello jpeg", "COM")
t:check(img.meta.dpi == nil, "no density in cjpeg's JFIF (aspect only)")
end
-- the encoder: byte-identical to cjpeg
local function source(c: any): any
local img = Types.Image.new(c.width, c.height, c.format)
if c.format == "rgb8" then
buffer.writestring(img.pixels, 0, c.pixels)
else
buffer.writestring(img.pixels, 0, c.pixels)
end
return img
end
local function psnr(a: buffer, b: buffer, n: number, bpp: number): number
local se = 0
for i = 0, n - 1 do
for k = 0, 2 do
local d = buffer.readu8(a, i * 4 + k) - buffer.readu8(b, i * bpp + (if bpp == 1 then 0 else k))
se += d * d
end
end
if se == 0 then
return 99
end
return 10 * math.log10(255 * 255 * n * 3 / se)
end
do
local exact = 0
for _, c in Enc do
local img = source(c)
local out, err = Jpeg.encode(img, c.opts)
t:check(out, c.name .. ": encode: " .. tostring(err))
local same = buffer.tostring(out :: buffer) == c.want
if not same then
local s = buffer.tostring(out :: buffer)
local at = 0
for i = 1, math.min(#s, #c.want) do
if string.byte(s, i) ~= string.byte(c.want, i) then
at = i
break
end
end
t:check(false, string.format("%s: differs from cjpeg at byte %d (ours %d bytes, cjpeg %d)", c.name, at, #s, #c.want))
end
exact += 1
local back = decode(out)
t:check(back and back.width == c.width and back.height == c.height, c.name .. ": decodes")
local bpp = if c.format == "gray8" then 1 else 3
local q = c.opts.quality
local p = psnr(back.pixels, img.pixels, c.width * c.height, bpp)
if c.width * c.height >= 1000 and not c.opts.gray then
-- the synthetic source has salt-and-pepper noise: lower thresholds
local floor = (if q >= 75 then 28 elseif q >= 50 then 25 else 20) - (if string.find(c.name, "synth") then 10 else 0)
t:check(p > floor, string.format("%s: PSNR %.1f dB", c.name, p))
end
end
t:note("%d encodes byte-identical to cjpeg", exact)
end
-- encoder: meta segments round trip, rgba8 input, options, errors
do
local c = Enc[1]
local rgb = source(c)
local img = Types.Image.new(c.width, c.height)
for i = 0, c.width * c.height - 1 do
buffer.writeu32(img.pixels, i * 4, buffer.readu16(rgb.pixels, i * 3) + buffer.readu8(rgb.pixels, i * 3 + 2) * 65536 + 0x80000000)
end
local a = Jpeg.encode(rgb, { quality = 80 }) :: buffer
local b = Jpeg.encode(img, { quality = 80 }) :: buffer
t:check(buffer.tostring(a) == buffer.tostring(b), "rgba8 input encodes as rgb8 (alpha ignored)")
img.meta.icc = buffer.fromstring(string.rep("P", 70000))
img.meta.exif = buffer.fromstring("MM\0\42\0\0\0\8\0\1\1\18\0\3\0\0\0\1\0\6\0\0\0\0\0\0")
img.meta.text = { comment = "made by formats-luau" }
img.meta.dpi = { x = 300, y = 300 }
local m = Jpeg.encode(img, { quality = 80 }) :: buffer
local back = decode(m)
t:check(back.meta.icc and buffer.len(back.meta.icc) == 70000, "ICC round trip (two APP2 chunks)")
t:eq(back.meta.orientation, 6, "EXIF round trip")
t:check(back.meta.text and back.meta.text.comment == "made by formats-luau", "COM round trip")
t:check(back.meta.dpi and back.meta.dpi.x == 300, "density round trip")
local nm = Jpeg.encode(img, { quality = 80, meta = false, jfif = false }) :: buffer
t:check(buffer.len(nm) < buffer.len(a), "meta = false, jfif = false")
local _, e1 = Jpeg.encode({} :: any)
t:check(e1 and e1.code == Err.ARG, "encode of a non-image")
local _, e2 = Jpeg.encode(Types.Image.new(4, 4, "rgba16"))
t:check(e2 and e2.code == Err.ARG, "rgba16 is refused")
local _, e3 = Jpeg.encode(img, { quality = 0 })
t:check(e3 and e3.code == Err.ARG, "quality 0")
local _, e4 = Jpeg.encode(img, { subsampling = "411" } :: any)
t:check(e4 and e4.code == Err.ARG, "subsampling 411")
local one = Jpeg.encode(Types.Image.new(1, 1), { progressive = true, subsampling = "444" })
t:check(one and decode(one).width == 1, "1x1 progressive")
end
-- truncated files: decode what is there (flagged) or fail with an Err; never throw
do
local count, partial = 0, 0
for _, name in { "photo_q90_420", "photo_q90_420_prog", "photo_rst1", "photo_rst1b_prog", "photo_arith_420", "photo_arith_rst_prog" } do
local s = files[name]
for cut = 0, #s - 1, math.max(1, #s // 61) do
local ok, img, err = pcall(decode, string.sub(s, 1, cut))
t:check(ok, name .. " cut at " .. cut .. ": threw " .. tostring(img))
t:check(img or Err.is(err), name .. " cut at " .. cut .. ": no image and no Err")
if img then
partial += 1
t:check(img.meta.truncated or cut >= #s - 2, name .. " cut at " .. cut .. ": not flagged truncated")
end
count += 1
end
end
t:note("%d truncated files, %d decoded partially", count, partial)
end
-- fuzz
do
local samples = {}
for i, c in Dec do
if i % 9 == 0 and #c.data < 40000 then
table.insert(samples, c.data)
end
end
t:fuzz("decode", function(b: buffer)
return Jpeg.decode(Bytes.reader(b))
end, samples, { mutations = 6, keepHeader = 2 })
t:fuzz("decode 1/8", function(b: buffer)
return Jpeg.decode(Bytes.reader(b), { scale = 8 })
end, samples, { mutations = 2, garbage = 30 })
end
t:done()