Files
rosetta/src/Formats/image/jpeg/Encode.luau
T
4DBug 692ef055de 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)
2026-10-31 08:44:15 -05:00

884 lines
21 KiB
Luau

--!strict
--!native
--!optimize 2
-- image/jpeg/Encode: the JPEG encoder (native; never throws). Baseline (SOF0) with the standard or optimised Huffman
-- tables and progressive (SOF2, libjpeg's jpeg_simple_progression script, optimised tables per scan); grey or YCbCr
-- 4:4:4 / 4:2:2 / 4:2:0; restart intervals. It follows libjpeg-turbo's encoder step for step so that its output is
-- byte-identical to cjpeg's for the same settings: jccolor.c (fixed-point RGB -> YCbCr), jcsample.c (box downsampling
-- with alternating rounding bias, right-edge replication), jccoefct.c (dummy edge blocks), jfdctint.c + jcdctmgr.c
-- (codecs/Dct), jchuff.c (sequential coding, jpeg_gen_optimal_table) and jcphuff.c (progressive coding: EOB runs,
-- correction-bit buffering). Luau translation of IJG code: licenses/libjpeg-turbo-LICENSE.md.
local Dct = require("@formats/codecs/Dct")
local Tables = require("@formats/image/jpeg/Tables")
local readu8, writeu8, readi16, writei16, readu16, writeu16 = buffer.readu8, buffer.writeu8, buffer.readi16, buffer.writei16, buffer.readu16, buffer.writeu16
local band, countlz = bit32.band, bit32.countlz
local Encode = {}
-- natural order index of zigzag position k
local ZZ = buffer.create(64)
do
local i = 0
for s = 0, 14 do
local lo, hi = math.max(0, s - 7), math.min(s, 7)
if s % 2 == 0 then
for r = hi, lo, -1 do
writeu8(ZZ, i, r * 8 + (s - r))
i += 1
end
else
for r = lo, hi do
writeu8(ZZ, i, r * 8 + (s - r))
i += 1
end
end
end
end
Encode.ZIGZAG = ZZ
-- ------------------------------------------------------------------------------------------------ output
local OUT = buffer.create(0)
local OP = 0
local CAP = 0
local ACC, NB = 0, 0
local GATHER = false
local function grow(n: number)
if OP + n > CAP then
local c = math.max(CAP * 2, OP + n + 1024)
local nb = buffer.create(c)
buffer.copy(nb, 0, OUT, 0, OP)
OUT = nb
CAP = c
end
end
local function byte(v: number)
grow(1)
writeu8(OUT, OP, v)
OP += 1
end
local function u16be(v: number)
byte(v // 256)
byte(v % 256)
end
-- n bits of v (n <= 16), MSB first, with 0xFF stuffing
local function bits(v: number, n: number)
if GATHER or n == 0 then
return
end
local p = 2 ^ n
ACC = ACC * p + band(v, p - 1)
NB += n
while NB >= 8 do
NB -= 8
local d = 2 ^ NB
local b = ACC // d
ACC -= b * d
grow(2)
writeu8(OUT, OP, b)
OP += 1
if b == 0xFF then
writeu8(OUT, OP, 0)
OP += 1
end
end
end
local function flushBits()
if NB > 0 then
bits(0x7F, 8 - NB) -- pad with ones
end
ACC, NB = 0, 0
end
local function nbits(v: number): number
return if v == 0 then 0 else 32 - countlz(v)
end
-- ------------------------------------------------------------------------------------------------ Huffman tables
-- a derived table: u16 code + u8 size per symbol (jpeg_make_c_derived_tbl)
export type Derived = { code: buffer, size: buffer }
local function derive(counts: { number }, symbols: { number }): Derived
local code, size = buffer.create(512), buffer.create(256)
local c, k = 0, 1
for l = 1, 16 do
for _ = 1, counts[l] or 0 do
local s = symbols[k]
if s then
writeu16(code, s * 2, c)
writeu8(size, s, l)
end
k += 1
c += 1
end
c *= 2
end
return { code = code, size = size }
end
-- jchuff.c jpeg_gen_optimal_table: freq (0..256, 1-based +1) -> counts, symbols
local function optimal(freqIn: { number }): ({ number }, { number })
local freq = table.create(257, 0)
local bitsT = table.create(34, 0)
local codesize = table.create(257, 0)
local others = table.create(257, -1)
local nz = table.create(257, 0)
local n = 0
for i = 0, 256 do
local f = if i == 256 then 1 else freqIn[i + 1]
if f > 0 then
n += 1
nz[n] = i
freq[n] = f
end
end
while true do
local c1, c2 = -1, -1
local v, v2 = 1e9, 1e9
for i = 1, n do
local f = freq[i]
if f <= v2 then
if f <= v then
c2 = c1
v2 = v
v = f
c1 = i
else
v2 = f
c2 = i
end
end
end
if c2 < 0 then
break
end
freq[c1] += freq[c2]
freq[c2] = 1000000001
codesize[c1] += 1
while others[c1] >= 0 do
c1 = others[c1]
codesize[c1] += 1
end
others[c1] = c2
codesize[c2] += 1
while others[c2] >= 0 do
c2 = others[c2]
codesize[c2] += 1
end
end
for i = 1, n do
local cs = math.min(codesize[i], 32)
bitsT[cs + 1] += 1
end
local bitPos = table.create(34, 0)
local p = 0
for i = 1, 32 do
bitPos[i + 1] = p
p += bitsT[i + 1]
end
local i = 32
while i > 16 do
while bitsT[i + 1] > 0 do
local j = i - 2
while bitsT[j + 1] == 0 do
j -= 1
end
bitsT[i + 1] -= 2
bitsT[i] += 1
bitsT[j + 2] += 2
bitsT[j + 1] -= 1
end
i -= 1
end
while bitsT[i + 1] == 0 do
i -= 1
end
bitsT[i + 1] -= 1
local counts = table.create(16, 0)
for l = 1, 16 do
counts[l] = bitsT[l + 1]
end
local symbols = table.create(n, 0)
for k = 1, n - 1 do
local cs = math.min(codesize[k], 32)
symbols[bitPos[cs + 1] + 1] = nz[k]
bitPos[cs + 1] += 1
end
local total = 0
for l = 1, 16 do
total += counts[l]
end
local out = table.create(total, 0)
for k = 1, total do
out[k] = symbols[k]
end
return counts, out
end
Encode.optimal = optimal
-- ------------------------------------------------------------------------------------------------ entropy coding state
local dcTab: { Derived } = {}
local acTab: { Derived } = {}
local dcFreq: { { number } } = {}
local acFreq: { { number } } = {}
local function symbol(t: Derived, freq: { number }, s: number)
if GATHER then
freq[s + 1] += 1
else
bits(readu16(t.code, s * 2), readu8(t.size, s))
end
end
export type Comp = {
id: number,
h: number,
v: number,
tq: number,
td: number, -- DC table slot
ta: number, -- AC table slot
bw: number, -- real blocks across / down
bh: number,
bpl: number, -- MCU-padded block grid
bpc: number,
coef: buffer, -- i16, 64 per block, natural order
last: number, -- DC predictor
}
local function dcDiff(c: Comp, diff: number)
local t = diff
local t2 = diff
if t < 0 then
t = -t
t2 -= 1
end
local n = nbits(t)
symbol(dcTab[c.td + 1], dcFreq[c.td + 1], n)
if n > 0 then
bits(t2, n)
end
end
-- jchuff.c encode_one_block
local function blockSeq(c: Comp, off: number)
local coef = c.coef
local dc = readi16(coef, off)
dcDiff(c, dc - c.last)
c.last = dc
local at, af = acTab[c.ta + 1], acFreq[c.ta + 1]
local r = 0
for k = 1, 63 do
local v = readi16(coef, off + readu8(ZZ, k) * 2)
if v == 0 then
r += 1
else
while r > 15 do
symbol(at, af, 0xF0)
r -= 16
end
local t, t2 = v, v
if t < 0 then
t = -t
t2 -= 1
end
local n = nbits(t)
symbol(at, af, r * 16 + n)
bits(t2, n)
r = 0
end
end
if r > 0 then
symbol(at, af, 0)
end
end
-- progressive state (jcphuff.c)
local EOBRUN = 0
local BE = 0
local CORR: { number } = table.create(1000, 0)
local curAc: Derived = { code = buffer.create(512), size = buffer.create(256) }
local curAcFreq: { number } = {}
local function emitEobrun()
if EOBRUN > 0 then
local n = nbits(EOBRUN) - 1
symbol(curAc, curAcFreq, n * 16)
if n > 0 then
bits(EOBRUN, n)
end
EOBRUN = 0
if not GATHER then
for i = 1, BE do
bits(CORR[i], 1)
end
end
BE = 0
end
end
local function blockDcFirst(c: Comp, off: number, al: number)
local t2 = readi16(c.coef, off) // 2 ^ al
dcDiff(c, t2 - c.last)
c.last = t2
end
local function blockAcFirst(c: Comp, off: number, ss: number, se: number, al: number)
local coef = c.coef
local d = 2 ^ al
local r = 0
for k = ss, se do
local v = readi16(coef, off + readu8(ZZ, k) * 2)
local t, t2
if v < 0 then
t = (-v) // d
t2 = -t - 1 -- ~t
else
t = v // d
t2 = t
end
if t == 0 then
r += 1
else
emitEobrun()
while r > 15 do
symbol(curAc, curAcFreq, 0xF0)
r -= 16
end
local n = nbits(t)
symbol(curAc, curAcFreq, r * 16 + n)
bits(t2, n)
r = 0
end
end
if r > 0 then
EOBRUN += 1
if EOBRUN == 0x7FFF then
emitEobrun()
end
end
end
local absv = table.create(64, 0)
local function blockAcRefine(c: Comp, off: number, ss: number, se: number, al: number)
local coef = c.coef
local d = 2 ^ al
local eob = 0
for k = ss, se do
local v = readi16(coef, off + readu8(ZZ, k) * 2)
local t = (if v < 0 then -v else v) // d
absv[k + 1] = t
if t == 1 then
eob = k
end
end
local r = 0
local br = 0 -- correction bits added in this block, at CORR[brStart + 1 ..]
local brStart = BE
for k = ss, se do
local t = absv[k + 1]
if t == 0 then
r += 1
continue
end
while r > 15 and k <= eob do
emitEobrun()
symbol(curAc, curAcFreq, 0xF0)
r -= 16
if not GATHER then
for i = 1, br do
bits(CORR[brStart + i], 1)
end
end
brStart = 0
br = 0
end
if t > 1 then
br += 1
CORR[brStart + br] = t % 2
continue
end
emitEobrun()
symbol(curAc, curAcFreq, r * 16 + 1)
bits(if readi16(coef, off + readu8(ZZ, k) * 2) < 0 then 0 else 1, 1)
if not GATHER then
for i = 1, br do
bits(CORR[brStart + i], 1)
end
end
brStart = 0
br = 0
r = 0
end
if r > 0 or br > 0 then
EOBRUN += 1
BE += br
if EOBRUN == 0x7FFF or BE > 1000 - 64 + 1 then
emitEobrun()
end
end
end
-- ------------------------------------------------------------------------------------------------ scans
export type ScanSpec = { comps: { number }, ss: number, se: number, ah: number, al: number }
-- iterate the scan's MCUs (or blocks, for one component), calling fn(c, off) per block; restart markers when ri > 0
local function walk(comps: { Comp }, mcusX: number, mcusY: number, ri: number, onRestart: (number) -> (), fn: (Comp, number) -> ())
local nc = #comps
local units, ux
if nc == 1 then
ux = comps[1].bw
units = ux * comps[1].bh
else
ux = mcusX
units = ux * mcusY
end
local rn = 0
for u = 0, units - 1 do
if ri > 0 and u > 0 and u % ri == 0 then
onRestart(rn)
rn = (rn + 1) % 8
end
local my, mx = u // ux, u % ux
for ci = 1, nc do
local c = comps[ci]
if nc == 1 then
fn(c, (my * c.bpl + mx) * 128)
else
for by = my * c.v, my * c.v + c.v - 1 do
for bx = mx * c.h, mx * c.h + c.h - 1 do
fn(c, (by * c.bpl + bx) * 128)
end
end
end
end
end
end
local function dht(class: number, slot: number, counts: { number }, symbols: { number })
byte(0xFF)
byte(0xC4)
u16be(2 + 17 + #symbols)
byte(class * 16 + slot)
for l = 1, 16 do
byte(counts[l])
end
for _, s in symbols do
byte(s)
end
end
local function sos(comps: { Comp }, ss: number, se: number, ah: number, al: number, dcOnly: boolean, acOnly: boolean)
byte(0xFF)
byte(0xDA)
u16be(6 + 2 * #comps)
byte(#comps)
for _, c in comps do
byte(c.id)
local td = if acOnly then 0 else c.td
local ta = if dcOnly then 0 else c.ta
byte(td * 16 + ta)
end
byte(ss)
byte(se)
byte(ah * 16 + al)
end
-- ------------------------------------------------------------------------------------------------ planes
-- jccolor.c rgb_ycc_start tables (16-bit fixed point)
local function fix(x: number): number
return math.floor(x * 65536 + 0.5)
end
local YR, YG, YB = fix(0.29900), fix(0.58700), fix(0.11400)
local CBR, CBG, HALF = fix(0.16874), fix(0.33126), fix(0.5)
local CRG, CRB = fix(0.41869), fix(0.08131)
local OFF = 128 * 65536 + 32768 - 1
-- pixels (rgba8 / rgb8 / gray8) -> Y, Cb, Cr planes (w * h bytes each; Cb / Cr nil for grey output)
local function planes(px: buffer, w: number, h: number, bpp: number, gray: boolean): (buffer, buffer?, buffer?)
local n = w * h
local Y = buffer.create(n)
if bpp == 1 then
buffer.copy(Y, 0, px, 0, n)
if gray then
return Y, nil, nil
end
local Cb = buffer.create(n)
buffer.fill(Cb, 0, 128, n)
local Cr = buffer.create(n)
buffer.fill(Cr, 0, 128, n)
return Y, Cb, Cr
end
if gray then
for i = 0, n - 1 do
local o = i * bpp
local r, g, b = readu8(px, o), readu8(px, o + 1), readu8(px, o + 2)
writeu8(Y, i, (YR * r + YG * g + YB * b + 32768) // 65536)
end
return Y, nil, nil
end
local Cb, Cr = buffer.create(n), buffer.create(n)
for i = 0, n - 1 do
local o = i * bpp
local r, g, b = readu8(px, o), readu8(px, o + 1), readu8(px, o + 2)
writeu8(Y, i, (YR * r + YG * g + YB * b + 32768) // 65536)
writeu8(Cb, i, (-CBR * r - CBG * g + HALF * b + OFF) // 65536)
writeu8(Cr, i, (HALF * r - CRG * g - CRB * b + OFF) // 65536)
end
return Y, Cb, Cr
end
-- jcsample.c: a full-resolution plane (w x h) -> the component's samples, (bw * 8) x ch, for factors hf x vf
-- (1 or 2 each); full-resolution columns past w - 1 repeat the last one, rows past h - 1 the last row
local function downsample(src: buffer, w: number, h: number, hf: number, vf: number, outW: number, outH: number): buffer
local out = buffer.create(outW * outH)
for oy = 0, outH - 1 do
local r0 = math.min(oy * vf, h - 1) * w
local r1 = math.min(oy * vf + vf - 1, h - 1) * w
local bias = if hf == 2 and vf == 2 then 1 elseif hf == 2 then 0 else (if vf == 2 then 1 else 0)
for ox = 0, outW - 1 do
local x0 = math.min(ox * hf, w - 1)
local x1 = math.min(ox * hf + hf - 1, w - 1)
local v
if hf == 2 and vf == 2 then
v = (readu8(src, r0 + x0) + readu8(src, r0 + x1) + readu8(src, r1 + x0) + readu8(src, r1 + x1) + bias) // 4
bias = 3 - bias
elseif hf == 2 then
v = (readu8(src, r0 + x0) + readu8(src, r0 + x1) + bias) // 2
bias = 1 - bias
else
v = (readu8(src, r0 + x0) + readu8(src, r1 + x0) + bias) // 2
bias = 1 - bias
end
writeu8(out, oy * outW + ox, v)
end
end
return out
end
-- ------------------------------------------------------------------------------------------------ encode
export type Options = {
quality: number, -- 1..100
sampling: string, -- "444" | "422" | "420"
progressive: boolean,
optimize: boolean, -- baseline: optimised Huffman tables (progressive always optimises)
gray: boolean,
restart: number, -- MCUs per restart interval (0 = none)
segments: { { marker: number, data: buffer } }, -- APPn / COM segments after the JFIF header
jfif: boolean,
density: { unit: number, x: number, y: number }?,
}
-- run(pixels, w, h, bpp, opts) -> buffer. pixels: w * h * bpp bytes (bpp 4 rgba8 / 3 rgb8 / 1 gray8); the caller
-- validated sizes (1..65535) and options.
function Encode.run(px: buffer, w: number, h: number, bpp: number, o: Options): buffer
OUT = buffer.create(math.max(1024, w * h // 2))
CAP = buffer.len(OUT)
OP = 0
ACC, NB = 0, 0
GATHER = false
EOBRUN, BE = 0, 0
local Y, Cb, Cr = planes(px, w, h, bpp, o.gray)
local hs, vs = 1, 1
if not o.gray then
if o.sampling == "420" then
hs, vs = 2, 2
elseif o.sampling == "422" then
hs, vs = 2, 1
end
end
local mcusX = math.ceil(w / (8 * hs))
local mcusY = math.ceil(h / (8 * vs))
local qt = { Tables.quant(Tables.LUMA, o.quality), Tables.quant(Tables.CHROMA, o.quality) }
local qdiv = {}
for t = 1, 2 do
local b = buffer.create(128)
for i = 1, 64 do
writeu16(b, (i - 1) * 2, qt[t][i])
end
qdiv[t] = b
end
-- components and their quantised coefficients
local comps: { Comp } = {}
local srcs = if o.gray then { Y } else { Y, Cb :: buffer, Cr :: buffer }
for i, src in srcs do
local ch, cv = if i == 1 then hs else 1, if i == 1 then vs else 1
local cw = math.ceil(w * ch / hs)
local chh = math.ceil(h * cv / vs)
local bw, bh = math.ceil(cw / 8), math.ceil(chh / 8)
local bpl, bpc = mcusX * ch, mcusY * cv
local plane, pw, ph = src, w, h
if ch < hs or cv < vs then
pw, ph = bw * 8, chh
plane = downsample(src, w, h, hs // ch, vs // cv, pw, ph)
end
local coef = buffer.create(bpl * bpc * 128)
local c: Comp = {
id = i,
h = ch,
v = cv,
tq = if i == 1 then 0 else 1,
td = if i == 1 then 0 else 1,
ta = if i == 1 then 0 else 1,
bw = bw,
bh = bh,
bpl = bpl,
bpc = bpc,
coef = coef,
last = 0,
}
local div = qdiv[c.tq + 1]
for by = 0, bpc - 1 do
for bx = 0, bpl - 1 do
local off = (by * bpl + bx) * 128
if by < bh and bx < bw then
Dct.fdctQuantize(plane, pw, bx * 8, by * 8, pw, ph, div, coef, off)
elseif by < bh then
writei16(coef, off, readi16(coef, off - 128)) -- right edge: the previous block's DC
else
-- bottom: the DC of the MCU's last block in the row above
local lb = (bx // ch) * ch + ch - 1
writei16(coef, off, readi16(coef, ((by - 1) * bpl + lb) * 128))
end
end
end
comps[i] = c
end
-- headers
byte(0xFF)
byte(0xD8)
if o.jfif then
local d = o.density or { unit = 0, x = 1, y = 1 }
byte(0xFF)
byte(0xE0)
u16be(16)
for _, ch in { 0x4A, 0x46, 0x49, 0x46, 0 } do
byte(ch)
end
byte(1)
byte(1)
byte(d.unit)
u16be(d.x)
u16be(d.y)
byte(0)
byte(0)
end
for _, s in o.segments do
local n = buffer.len(s.data)
byte(0xFF)
byte(s.marker)
u16be(n + 2)
grow(n)
buffer.copy(OUT, OP, s.data, 0, n)
OP += n
end
for t = 1, (if o.gray then 1 else 2) do
byte(0xFF)
byte(0xDB)
u16be(67)
byte(t - 1)
for k = 0, 63 do
byte(qt[t][readu8(ZZ, k) + 1])
end
end
byte(0xFF)
byte(if o.progressive then 0xC2 else 0xC0)
u16be(8 + 3 * #comps)
byte(8)
u16be(h)
u16be(w)
byte(#comps)
for _, c in comps do
byte(c.id)
byte(c.h * 16 + c.v)
byte(c.tq)
end
local ntab = if o.gray then 1 else 2
local function restartMarker(n: number)
flushBits()
byte(0xFF)
byte(0xD0 + n)
end
if not o.progressive then
if o.optimize then
GATHER = true
for t = 1, ntab do
dcFreq[t] = table.create(257, 0)
acFreq[t] = table.create(257, 0)
end
for _, c in comps do
c.last = 0
end
walk(comps, mcusX, mcusY, o.restart, function()
for _, c in comps do
c.last = 0
end
end, blockSeq)
GATHER = false
end
for t = 1, ntab do
local dcC, dcS, acC, acS
if o.optimize then
dcC, dcS = optimal(dcFreq[t])
acC, acS = optimal(acFreq[t])
else
local d, a = Tables.DC[t], Tables.AC[t]
dcC, dcS, acC, acS = d.counts, d.symbols, a.counts, a.symbols
end
dcTab[t] = derive(dcC, dcS)
acTab[t] = derive(acC, acS)
dcFreq[t] = table.create(257, 0)
acFreq[t] = table.create(257, 0)
-- libjpeg emits each table before the scan in component order: DC0, AC0, DC1, AC1
dht(0, t - 1, dcC, dcS)
dht(1, t - 1, acC, acS)
end
if o.restart > 0 then
byte(0xFF)
byte(0xDD)
u16be(4)
u16be(o.restart)
end
sos(comps, 0, 63, 0, 0, false, false)
for _, c in comps do
c.last = 0
end
walk(comps, mcusX, mcusY, o.restart, function(n: number)
restartMarker(n)
for _, c in comps do
c.last = 0
end
end, blockSeq)
flushBits()
else
local script: { ScanSpec }
if o.gray then
script = {
{ comps = { 1 }, ss = 0, se = 0, ah = 0, al = 1 },
{ comps = { 1 }, ss = 1, se = 5, ah = 0, al = 2 },
{ comps = { 1 }, ss = 6, se = 63, ah = 0, al = 2 },
{ comps = { 1 }, ss = 1, se = 63, ah = 2, al = 1 },
{ comps = { 1 }, ss = 0, se = 0, ah = 1, al = 0 },
{ comps = { 1 }, ss = 1, se = 63, ah = 1, al = 0 },
}
else
script = {
{ comps = { 1, 2, 3 }, ss = 0, se = 0, ah = 0, al = 1 },
{ comps = { 1 }, ss = 1, se = 5, ah = 0, al = 2 },
{ comps = { 3 }, ss = 1, se = 63, ah = 0, al = 1 },
{ comps = { 2 }, ss = 1, se = 63, ah = 0, al = 1 },
{ comps = { 1 }, ss = 6, se = 63, ah = 0, al = 2 },
{ comps = { 1 }, ss = 1, se = 63, ah = 2, al = 1 },
{ comps = { 1, 2, 3 }, ss = 0, se = 0, ah = 1, al = 0 },
{ comps = { 3 }, ss = 1, se = 63, ah = 1, al = 0 },
{ comps = { 2 }, ss = 1, se = 63, ah = 1, al = 0 },
{ comps = { 1 }, ss = 1, se = 63, ah = 1, al = 0 },
}
end
local driSent = false
for _, sc in script do
local sComps = {}
for _, ci in sc.comps do
table.insert(sComps, comps[ci])
end
local ss, se, ah, al = sc.ss, sc.se, sc.ah, sc.al
local isDc = ss == 0
local blockFn: (Comp, number) -> ()
if isDc and ah == 0 then
blockFn = function(c: Comp, off: number)
blockDcFirst(c, off, al)
end
elseif isDc then
blockFn = function(c: Comp, off: number)
bits(band(readi16(c.coef, off) // 2 ^ al, 1), 1)
end
elseif ah == 0 then
blockFn = function(c: Comp, off: number)
blockAcFirst(c, off, ss, se, al)
end
else
blockFn = function(c: Comp, off: number)
blockAcRefine(c, off, ss, se, al)
end
end
local function onRestart(n: number)
emitEobrun()
if not GATHER then
restartMarker(n)
end
for _, c in sComps do
c.last = 0
end
EOBRUN, BE = 0, 0
end
local function pass()
for _, c in sComps do
c.last = 0
end
EOBRUN, BE = 0, 0
walk(sComps, mcusX, mcusY, o.restart, onRestart, blockFn)
emitEobrun()
end
-- gather statistics, then emit the optimal tables this scan uses
if not (isDc and ah > 0) then
GATHER = true
for t = 1, ntab do
dcFreq[t] = table.create(257, 0)
acFreq[t] = table.create(257, 0)
end
if not isDc then
curAcFreq = acFreq[sComps[1].ta + 1]
end
pass()
GATHER = false
local sent = {}
for _, c in sComps do
local slot = if isDc then c.td else c.ta
if not sent[slot] then
sent[slot] = true
local counts, syms = optimal(if isDc then dcFreq[slot + 1] else acFreq[slot + 1])
dht(if isDc then 0 else 1, slot, counts, syms)
if isDc then
dcTab[slot + 1] = derive(counts, syms)
else
acTab[slot + 1] = derive(counts, syms)
end
end
end
if not isDc then
curAc = acTab[sComps[1].ta + 1]
end
end
if o.restart > 0 and not driSent then
driSent = true
byte(0xFF)
byte(0xDD)
u16be(4)
u16be(o.restart)
end
sos(sComps, ss, se, ah, al, isDc, not isDc or ah > 0) -- DC refinement uses no table: td = 0 (as libjpeg)
pass()
flushBits()
end
end
byte(0xFF)
byte(0xD9)
local res = buffer.create(OP)
buffer.copy(res, 0, OUT, 0, OP)
OUT = buffer.create(0)
CAP = 0
return res
end
return Encode