ws-video: merge ws/video-codecs (codecs/Jpeg, codecs/Mpeg1)
This commit is contained in:
commit
dac404aa52
22 files changed
+3540
-236
No files matched your search
@@ -0,0 +1,414 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- 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.
|
||||
--
|
||||
-- It reads the destuffed scan data that Scan.destuff produces (0xFF 0x00 already removed, RSTn positions recorded);
|
||||
-- past the end of a restart segment it reads zero bytes, the convention libjpeg follows when the decoder runs into a
|
||||
-- marker (libjpeg's encoder also drops trailing zero bytes, so reading past the end is normal and not a sign of
|
||||
-- truncation: the caller flags a scan that runs into the end of the file instead). Statistics bins live in one buffer: DC tables at [t * 64], AC tables at [256 + t * 256], the fixed 0.5
|
||||
-- bin at [1280].
|
||||
local readu8, writeu8, readi16, writei16 = buffer.readu8, buffer.writeu8, buffer.readi16, buffer.writei16
|
||||
local band, bxor = bit32.band, bit32.bxor
|
||||
|
||||
local Arith = {}
|
||||
|
||||
-- jaricom.c: Qe << 16 | Next_Index_MPS << 8 | Switch_MPS << 7 | Next_Index_LPS
|
||||
local TAB = buffer.create(114 * 4)
|
||||
do
|
||||
local raw = {
|
||||
{ 0x5a1d, 1, 1, 1 }, { 0x2586, 14, 2, 0 }, { 0x1114, 16, 3, 0 }, { 0x080b, 18, 4, 0 }, { 0x03d8, 20, 5, 0 },
|
||||
{ 0x01da, 23, 6, 0 }, { 0x00e5, 25, 7, 0 }, { 0x006f, 28, 8, 0 }, { 0x0036, 30, 9, 0 }, { 0x001a, 33, 10, 0 },
|
||||
{ 0x000d, 35, 11, 0 }, { 0x0006, 9, 12, 0 }, { 0x0003, 10, 13, 0 }, { 0x0001, 12, 13, 0 }, { 0x5a7f, 15, 15, 1 },
|
||||
{ 0x3f25, 36, 16, 0 }, { 0x2cf2, 38, 17, 0 }, { 0x207c, 39, 18, 0 }, { 0x17b9, 40, 19, 0 }, { 0x1182, 42, 20, 0 },
|
||||
{ 0x0cef, 43, 21, 0 }, { 0x09a1, 45, 22, 0 }, { 0x072f, 46, 23, 0 }, { 0x055c, 48, 24, 0 }, { 0x0406, 49, 25, 0 },
|
||||
{ 0x0303, 51, 26, 0 }, { 0x0240, 52, 27, 0 }, { 0x01b1, 54, 28, 0 }, { 0x0144, 56, 29, 0 }, { 0x00f5, 57, 30, 0 },
|
||||
{ 0x00b7, 59, 31, 0 }, { 0x008a, 60, 32, 0 }, { 0x0068, 62, 33, 0 }, { 0x004e, 63, 34, 0 }, { 0x003b, 32, 35, 0 },
|
||||
{ 0x002c, 33, 9, 0 }, { 0x5ae1, 37, 37, 1 }, { 0x484c, 64, 38, 0 }, { 0x3a0d, 65, 39, 0 }, { 0x2ef1, 67, 40, 0 },
|
||||
{ 0x261f, 68, 41, 0 }, { 0x1f33, 69, 42, 0 }, { 0x19a8, 70, 43, 0 }, { 0x1518, 72, 44, 0 }, { 0x1177, 73, 45, 0 },
|
||||
{ 0x0e74, 74, 46, 0 }, { 0x0bfb, 75, 47, 0 }, { 0x09f8, 77, 48, 0 }, { 0x0861, 78, 49, 0 }, { 0x0706, 79, 50, 0 },
|
||||
{ 0x05cd, 48, 51, 0 }, { 0x04de, 50, 52, 0 }, { 0x040f, 50, 53, 0 }, { 0x0363, 51, 54, 0 }, { 0x02d4, 52, 55, 0 },
|
||||
{ 0x025c, 53, 56, 0 }, { 0x01f8, 54, 57, 0 }, { 0x01a4, 55, 58, 0 }, { 0x0160, 56, 59, 0 }, { 0x0125, 57, 60, 0 },
|
||||
{ 0x00f6, 58, 61, 0 }, { 0x00cb, 59, 62, 0 }, { 0x00ab, 61, 63, 0 }, { 0x008f, 61, 32, 0 }, { 0x5b12, 65, 65, 1 },
|
||||
{ 0x4d04, 80, 66, 0 }, { 0x412c, 81, 67, 0 }, { 0x37d8, 82, 68, 0 }, { 0x2fe8, 83, 69, 0 }, { 0x293c, 84, 70, 0 },
|
||||
{ 0x2379, 86, 71, 0 }, { 0x1edf, 87, 72, 0 }, { 0x1aa9, 87, 73, 0 }, { 0x174e, 72, 74, 0 }, { 0x1424, 72, 75, 0 },
|
||||
{ 0x119c, 74, 76, 0 }, { 0x0f6b, 74, 77, 0 }, { 0x0d51, 75, 78, 0 }, { 0x0bb6, 77, 79, 0 }, { 0x0a40, 77, 48, 0 },
|
||||
{ 0x5832, 80, 81, 1 }, { 0x4d1c, 88, 82, 0 }, { 0x438e, 89, 83, 0 }, { 0x3bdd, 90, 84, 0 }, { 0x34ee, 91, 85, 0 },
|
||||
{ 0x2eae, 92, 86, 0 }, { 0x299a, 93, 87, 0 }, { 0x2516, 86, 71, 0 }, { 0x5570, 88, 89, 1 }, { 0x4ca9, 95, 90, 0 },
|
||||
{ 0x44d9, 96, 91, 0 }, { 0x3e22, 97, 92, 0 }, { 0x3824, 99, 93, 0 }, { 0x32b4, 99, 94, 0 }, { 0x2e17, 93, 86, 0 },
|
||||
{ 0x56a8, 95, 96, 1 }, { 0x4f46, 101, 97, 0 }, { 0x47e5, 102, 98, 0 }, { 0x41cf, 103, 99, 0 }, { 0x3c3d, 104, 100, 0 },
|
||||
{ 0x375e, 99, 93, 0 }, { 0x5231, 105, 102, 0 }, { 0x4c0f, 106, 103, 0 }, { 0x4639, 107, 104, 0 }, { 0x415e, 103, 99, 0 },
|
||||
{ 0x5627, 105, 106, 1 }, { 0x50e7, 108, 107, 0 }, { 0x4b85, 109, 103, 0 }, { 0x5597, 110, 109, 0 }, { 0x504f, 111, 107, 0 },
|
||||
{ 0x5a10, 110, 111, 1 }, { 0x5522, 112, 109, 0 }, { 0x59eb, 112, 111, 1 }, { 0x5a1d, 113, 113, 0 },
|
||||
}
|
||||
for i, e in raw do
|
||||
buffer.writeu16(TAB, (i - 1) * 4, e[1]) -- Qe
|
||||
writeu8(TAB, (i - 1) * 4 + 2, e[4] * 128 + e[2]) -- Switch_MPS << 7 | Next_Index_LPS
|
||||
writeu8(TAB, (i - 1) * 4 + 3, e[3]) -- Next_Index_MPS
|
||||
end
|
||||
end
|
||||
|
||||
local ZZ: buffer = buffer.create(80) -- set by Arith.init (Scan.ZIGZAG)
|
||||
|
||||
local STATS = 1281
|
||||
local POW2 = buffer.create(8)
|
||||
for i = 0, 7 do
|
||||
writeu8(POW2, i, 2 ^ i)
|
||||
end
|
||||
local FIXED = 1280
|
||||
|
||||
-- decoder state (one scan at a time; never yields)
|
||||
local D: buffer = buffer.create(0)
|
||||
local P = 0 -- next byte
|
||||
local SEGEND = 0 -- reads at or past this return 0
|
||||
local OVER = 0 -- zero bytes supplied past the end
|
||||
local C, A, CT = 0, 0, -16
|
||||
local st: buffer = buffer.create(STATS)
|
||||
|
||||
local function decode(s: number): number
|
||||
while A < 0x8000 do
|
||||
CT -= 1
|
||||
if CT < 0 then
|
||||
local data = 0
|
||||
if P < SEGEND then
|
||||
data = readu8(D, P)
|
||||
P += 1
|
||||
else
|
||||
OVER += 1
|
||||
end
|
||||
C = C * 256 + data
|
||||
CT += 8
|
||||
if CT < 0 then
|
||||
CT += 1
|
||||
if CT == 0 then
|
||||
A = 0x8000
|
||||
end
|
||||
end
|
||||
end
|
||||
A *= 2
|
||||
end
|
||||
local sv = readu8(st, s)
|
||||
local t = band(sv, 0x7F) * 4
|
||||
local qe = buffer.readu16(TAB, t)
|
||||
local nl = readu8(TAB, t + 2)
|
||||
local nm = readu8(TAB, t + 3)
|
||||
local temp = A - qe
|
||||
A = temp
|
||||
temp *= readu8(POW2, CT)
|
||||
if C >= temp then
|
||||
C -= temp
|
||||
if A < qe then
|
||||
A = qe
|
||||
writeu8(st, s, bxor(band(sv, 0x80), nm))
|
||||
else
|
||||
A = qe
|
||||
writeu8(st, s, bxor(band(sv, 0x80), nl))
|
||||
sv = bxor(sv, 0x80)
|
||||
end
|
||||
elseif A < 0x8000 then
|
||||
if A < qe then
|
||||
writeu8(st, s, bxor(band(sv, 0x80), nl))
|
||||
sv = bxor(sv, 0x80)
|
||||
else
|
||||
writeu8(st, s, bxor(band(sv, 0x80), nm))
|
||||
end
|
||||
end
|
||||
return if sv >= 0x80 then 1 else 0
|
||||
end
|
||||
|
||||
local function i16(v: number): number
|
||||
v = band(v, 0xFFFF)
|
||||
return if v >= 0x8000 then v - 0x10000 else v
|
||||
end
|
||||
|
||||
export type ArithComp = {
|
||||
coef: buffer,
|
||||
bpl: number,
|
||||
h: number,
|
||||
v: number,
|
||||
bw: number,
|
||||
bh: number,
|
||||
dcTbl: number, -- 0..3
|
||||
acTbl: number,
|
||||
pred: number,
|
||||
ctx: number,
|
||||
}
|
||||
|
||||
export type ArithParams = {
|
||||
comps: { ArithComp },
|
||||
mcusX: number,
|
||||
mcusY: number,
|
||||
ri: number,
|
||||
mode: number, -- 0 sequential, 1 DC first, 2 DC refine, 3 AC first, 4 AC refine
|
||||
ss: number,
|
||||
se: number,
|
||||
al: number,
|
||||
dcL: { number }, -- conditioning per table (DAC), 1-based by table + 1
|
||||
dcU: { number },
|
||||
acK: { number },
|
||||
}
|
||||
|
||||
-- DC difference (F.1.4.4.1 / figures F.19, F.21 - F.24); returns the new predictor or nil on a bad code
|
||||
local function dcDiff(c: ArithComp, L: number, U: number): number?
|
||||
local base = c.dcTbl * 64
|
||||
local s = base + c.ctx
|
||||
if decode(s) == 0 then
|
||||
c.ctx = 0
|
||||
return c.pred
|
||||
end
|
||||
local sign = decode(s + 1)
|
||||
s = s + 2 + sign
|
||||
local m = decode(s)
|
||||
if m ~= 0 then
|
||||
s = base + 20
|
||||
while decode(s) ~= 0 do
|
||||
m *= 2
|
||||
if m == 0x8000 then
|
||||
return nil
|
||||
end
|
||||
s += 1
|
||||
end
|
||||
end
|
||||
if m < 2 ^ L // 2 then
|
||||
c.ctx = 0
|
||||
elseif m > 2 ^ U // 2 then
|
||||
c.ctx = 12 + sign * 4
|
||||
else
|
||||
c.ctx = 4 + sign * 4
|
||||
end
|
||||
local v = m
|
||||
s += 14
|
||||
m = m // 2
|
||||
while m > 0 do
|
||||
if decode(s) ~= 0 then
|
||||
v += m
|
||||
end
|
||||
m = m // 2
|
||||
end
|
||||
v += 1
|
||||
if sign ~= 0 then
|
||||
v = -v
|
||||
end
|
||||
return band(c.pred + v, 0xFFFF)
|
||||
end
|
||||
|
||||
-- AC coefficients k = ss..se of one block (figure F.20); false on a bad code
|
||||
local function acFirst(coef: buffer, off: number, tbl: number, ss: number, se: number, K: number, mul: number): boolean
|
||||
local base = 256 + tbl * 256
|
||||
local k = ss
|
||||
while k <= se do
|
||||
local s = base + 3 * (k - 1)
|
||||
if decode(s) ~= 0 then
|
||||
break -- EOB
|
||||
end
|
||||
while decode(s + 1) == 0 do
|
||||
s += 3
|
||||
k += 1
|
||||
if k > se then
|
||||
return false
|
||||
end
|
||||
end
|
||||
local sign = decode(FIXED)
|
||||
s += 2
|
||||
local m = decode(s)
|
||||
if m ~= 0 then
|
||||
if decode(s) ~= 0 then
|
||||
m *= 2
|
||||
s = base + (if k <= K then 189 else 217)
|
||||
while decode(s) ~= 0 do
|
||||
m *= 2
|
||||
if m == 0x8000 then
|
||||
return false
|
||||
end
|
||||
s += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
local v = m
|
||||
s += 14
|
||||
m = m // 2
|
||||
while m > 0 do
|
||||
if decode(s) ~= 0 then
|
||||
v += m
|
||||
end
|
||||
m = m // 2
|
||||
end
|
||||
v += 1
|
||||
if sign ~= 0 then
|
||||
v = -v
|
||||
end
|
||||
writei16(coef, off + readu8(ZZ, k) * 2, i16(v * mul))
|
||||
k += 1
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
local function acRefine(coef: buffer, off: number, tbl: number, ss: number, se: number, al: number): boolean
|
||||
local base = 256 + tbl * 256
|
||||
local p1 = 2 ^ al
|
||||
local m1 = -p1
|
||||
local kex = se
|
||||
while kex > 0 do
|
||||
if readi16(coef, off + readu8(ZZ, kex) * 2) ~= 0 then
|
||||
break
|
||||
end
|
||||
kex -= 1
|
||||
end
|
||||
local k = ss
|
||||
while k <= se do
|
||||
local s = base + 3 * (k - 1)
|
||||
if k > kex then
|
||||
if decode(s) ~= 0 then
|
||||
break
|
||||
end
|
||||
end
|
||||
while true do
|
||||
local o = off + readu8(ZZ, k) * 2
|
||||
local cv = readi16(coef, o)
|
||||
if cv ~= 0 then
|
||||
if decode(s + 2) ~= 0 then
|
||||
writei16(coef, o, i16(if cv < 0 then cv + m1 else cv + p1))
|
||||
end
|
||||
break
|
||||
end
|
||||
if decode(s + 1) ~= 0 then
|
||||
writei16(coef, o, i16(if decode(FIXED) ~= 0 then m1 else p1))
|
||||
break
|
||||
end
|
||||
s += 3
|
||||
k += 1
|
||||
if k > se then
|
||||
return false
|
||||
end
|
||||
end
|
||||
k += 1
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
function Arith.init(zigzag: buffer)
|
||||
ZZ = zigzag
|
||||
end
|
||||
|
||||
-- run(d, cleanLen, rst, nrst, P) -> truncated: decodes one scan (see Scan.run for the data layout)
|
||||
function Arith.run(d: buffer, cleanLen: number, rst: { number }, nrst: number, Pm: ArithParams): boolean
|
||||
local comps = Pm.comps
|
||||
local nc = #comps
|
||||
local mode, ss, se, al, ri = Pm.mode, Pm.ss, Pm.se, Pm.al, Pm.ri
|
||||
local units, ux
|
||||
if nc == 1 then
|
||||
ux = comps[1].bw
|
||||
units = ux * comps[1].bh
|
||||
else
|
||||
ux = Pm.mcusX
|
||||
units = ux * Pm.mcusY
|
||||
end
|
||||
local resetDc = mode == 0 or mode == 1
|
||||
local resetAc = mode == 0 or mode == 3 or mode == 4
|
||||
local function reset()
|
||||
for i = 1, nc do
|
||||
local c = comps[i]
|
||||
if resetDc then
|
||||
buffer.fill(st, c.dcTbl * 64, 0, 64)
|
||||
c.pred = 0
|
||||
c.ctx = 0
|
||||
end
|
||||
if resetAc then
|
||||
buffer.fill(st, 256 + c.acTbl * 256, 0, 256)
|
||||
end
|
||||
end
|
||||
C, A, CT = 0, 0, -16
|
||||
end
|
||||
D = d
|
||||
P = 0
|
||||
SEGEND = if nrst >= 1 then math.min(rst[1], cleanLen) else cleanLen
|
||||
OVER = 0
|
||||
writeu8(st, FIXED, 113)
|
||||
reset()
|
||||
local rstIdx = 0
|
||||
local bad = false
|
||||
local truncated = false
|
||||
local mul = 2 ^ al
|
||||
for u = 0, units - 1 do
|
||||
if ri > 0 and u > 0 and u % ri == 0 then
|
||||
rstIdx += 1
|
||||
if rstIdx <= nrst then
|
||||
P = math.min(rst[rstIdx], cleanLen)
|
||||
SEGEND = if rstIdx + 1 <= nrst then math.min(rst[rstIdx + 1], cleanLen) else cleanLen
|
||||
bad = false
|
||||
else
|
||||
truncated = true
|
||||
break
|
||||
end
|
||||
reset()
|
||||
end
|
||||
if not bad then
|
||||
local my, mx = u // ux, u % ux
|
||||
for ci = 1, nc do
|
||||
local c = comps[ci]
|
||||
local bh, bw, by0, bx0
|
||||
if nc == 1 then
|
||||
bh, bw, by0, bx0 = 1, 1, my, mx
|
||||
else
|
||||
bh, bw, by0, bx0 = c.v, c.h, my * c.v, mx * c.h
|
||||
end
|
||||
local coef, bpl = c.coef, c.bpl
|
||||
for by = by0, by0 + bh - 1 do
|
||||
for bx = bx0, bx0 + bw - 1 do
|
||||
local off = (by * bpl + bx) * 128
|
||||
if mode == 0 then
|
||||
local pred = dcDiff(c, Pm.dcL[c.dcTbl + 1], Pm.dcU[c.dcTbl + 1])
|
||||
if not pred then
|
||||
bad = true
|
||||
else
|
||||
c.pred = pred
|
||||
writei16(coef, off, i16(pred))
|
||||
if not acFirst(coef, off, c.acTbl, 1, 63, Pm.acK[c.acTbl + 1], 1) then
|
||||
bad = true
|
||||
end
|
||||
end
|
||||
elseif mode == 1 then
|
||||
local pred = dcDiff(c, Pm.dcL[c.dcTbl + 1], Pm.dcU[c.dcTbl + 1])
|
||||
if not pred then
|
||||
bad = true
|
||||
else
|
||||
c.pred = pred
|
||||
writei16(coef, off, i16(pred * mul))
|
||||
end
|
||||
elseif mode == 2 then
|
||||
if decode(FIXED) ~= 0 then
|
||||
local cv = readi16(coef, off)
|
||||
if band(cv, mul) == 0 then
|
||||
writei16(coef, off, i16(cv + mul))
|
||||
end
|
||||
end
|
||||
elseif mode == 3 then
|
||||
if not acFirst(coef, off, c.acTbl, ss, se, Pm.acK[c.acTbl + 1], mul) then
|
||||
bad = true
|
||||
end
|
||||
else
|
||||
if not acRefine(coef, off, c.acTbl, ss, se, al) then
|
||||
bad = true
|
||||
end
|
||||
end
|
||||
if bad then
|
||||
break
|
||||
end
|
||||
end
|
||||
if bad then
|
||||
break
|
||||
end
|
||||
end
|
||||
if bad then
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
D = buffer.create(0)
|
||||
return truncated
|
||||
end
|
||||
|
||||
return Arith
|
||||
@@ -0,0 +1,229 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- 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).
|
||||
--
|
||||
-- Upsampling follows libjpeg-turbo's jdsample.c, so the output matches djpeg's defaults:
|
||||
-- FULL the component is at output resolution
|
||||
-- H2V1 "fancy" triangle filter, 3/4 nearer + 1/4 further sample, alternating rounding (1, 2) / 4
|
||||
-- H2V2 fancy in both directions: vertical 3:1 column sums, then horizontal 3:1, rounding (8, 7) / 16
|
||||
-- H1V2 fancy vertical only, rounding 1 (upper row) / 2 (lower row)
|
||||
-- REPLICATE any other ratio (or no fancy upsampling): nearest sample, as int_upsample
|
||||
-- Edges replicate the last real sample (downW x downH), as libjpeg does with its context rows.
|
||||
-- Colour conversion is jdcolor.c's table-driven YCbCr -> RGB (16-bit fixed point), plus grey, RGB, CMYK and
|
||||
-- YCCK (Adobe inverted CMYK: R = C * K / 255).
|
||||
local readu16, readi32, readu8, writeu16, writeu32 = buffer.readu16, buffer.readi32, buffer.readu8, buffer.writeu16, buffer.writeu32
|
||||
local clamp, min, max = math.clamp, math.min, math.max
|
||||
|
||||
local Color = {}
|
||||
|
||||
Color.FULL = 0
|
||||
Color.REPLICATE = 1
|
||||
Color.H2V1 = 2
|
||||
Color.H2V2 = 3
|
||||
Color.H1V2 = 4
|
||||
|
||||
Color.GRAY = 0
|
||||
Color.YCC = 1
|
||||
Color.RGB = 2
|
||||
Color.CMYK = 3
|
||||
Color.YCCK = 4
|
||||
Color.CMYK_PLAIN = 5 -- CMYK without an Adobe marker: not inverted
|
||||
|
||||
export type Comp = {
|
||||
plane: buffer, -- u16 samples, stride per row
|
||||
stride: number,
|
||||
rows: number, -- plane height
|
||||
downW: number, -- real samples across / down (the rest is block padding)
|
||||
downH: number,
|
||||
method: number,
|
||||
hIn: number,
|
||||
hOut: number,
|
||||
vIn: number,
|
||||
vOut: number,
|
||||
row: buffer, -- scratch row (u16, at least max(outW, 2 * downW) + 8 samples)
|
||||
}
|
||||
|
||||
export type Params = {
|
||||
comps: { Comp },
|
||||
space: number,
|
||||
outW: number,
|
||||
outH: number,
|
||||
maxv: number,
|
||||
pixels: buffer,
|
||||
-- YCbCr tables (maxv + 1 i32 entries)
|
||||
crr: buffer,
|
||||
cbb: buffer,
|
||||
crg: buffer,
|
||||
cbg: buffer,
|
||||
toByte: buffer?, -- maxv + 1 u8 entries (12-bit), nil for 8-bit
|
||||
}
|
||||
|
||||
-- jdcolor.c build_ycc_rgb_table
|
||||
function Color.tables(maxv: number): (buffer, buffer, buffer, buffer)
|
||||
local n = maxv + 1
|
||||
local center = n // 2
|
||||
local crr, cbb, crg, cbg = buffer.create(n * 4), buffer.create(n * 4), buffer.create(n * 4), buffer.create(n * 4)
|
||||
local function fix(x: number): number
|
||||
return math.floor(x * 65536 + 0.5)
|
||||
end
|
||||
for i = 0, maxv do
|
||||
local x = i - center
|
||||
buffer.writei32(crr, i * 4, (fix(1.40200) * x + 32768) // 65536)
|
||||
buffer.writei32(cbb, i * 4, (fix(1.77200) * x + 32768) // 65536)
|
||||
buffer.writei32(crg, i * 4, -fix(0.71414) * x)
|
||||
buffer.writei32(cbg, i * 4, -fix(0.34414) * x + 32768)
|
||||
end
|
||||
return crr, cbb, crg, cbg
|
||||
end
|
||||
|
||||
-- fills c.row with output row y; returns the buffer and byte offset of the row's samples
|
||||
local function fetch(c: Comp, y: number, outW: number): (buffer, number)
|
||||
local method = c.method
|
||||
local plane, stride, row = c.plane, c.stride, c.row
|
||||
if method == 0 then
|
||||
return plane, min(y, c.rows - 1) * stride * 2
|
||||
elseif method == 2 then
|
||||
local w = c.downW
|
||||
local b = min(y, c.rows - 1) * stride * 2
|
||||
local cur = readu16(plane, b)
|
||||
writeu16(row, 0, cur)
|
||||
local nxt = readu16(plane, b + 2)
|
||||
writeu16(row, 2, (cur * 3 + nxt + 2) // 4)
|
||||
local prev = cur
|
||||
cur = nxt
|
||||
for i = 1, w - 2 do
|
||||
nxt = readu16(plane, b + (i + 1) * 2)
|
||||
local v3 = cur * 3
|
||||
writeu16(row, i * 4, (v3 + prev + 1) // 4)
|
||||
writeu16(row, i * 4 + 2, (v3 + nxt + 2) // 4)
|
||||
prev = cur
|
||||
cur = nxt
|
||||
end
|
||||
writeu16(row, (w - 1) * 4, (cur * 3 + prev + 1) // 4)
|
||||
writeu16(row, (w - 1) * 4 + 2, cur)
|
||||
return row, 0
|
||||
elseif method == 3 then
|
||||
local w = c.downW
|
||||
local iy = min(y // 2, c.downH - 1)
|
||||
local oy = if y % 2 == 0 then max(iy - 1, 0) else min(iy + 1, c.downH - 1)
|
||||
local b0, b1 = iy * stride * 2, oy * stride * 2
|
||||
local this = readu16(plane, b0) * 3 + readu16(plane, b1)
|
||||
local nxt = readu16(plane, b0 + 2) * 3 + readu16(plane, b1 + 2)
|
||||
writeu16(row, 0, (this * 4 + 8) // 16)
|
||||
writeu16(row, 2, (this * 3 + nxt + 7) // 16)
|
||||
local last = this
|
||||
this = nxt
|
||||
for i = 1, w - 2 do
|
||||
nxt = readu16(plane, b0 + (i + 1) * 2) * 3 + readu16(plane, b1 + (i + 1) * 2)
|
||||
local t3 = this * 3
|
||||
writeu16(row, i * 4, (t3 + last + 8) // 16)
|
||||
writeu16(row, i * 4 + 2, (t3 + nxt + 7) // 16)
|
||||
last = this
|
||||
this = nxt
|
||||
end
|
||||
writeu16(row, (w - 1) * 4, (this * 3 + last + 8) // 16)
|
||||
writeu16(row, (w - 1) * 4 + 2, (this * 4 + 7) // 16)
|
||||
return row, 0
|
||||
elseif method == 4 then
|
||||
local iy = min(y // 2, c.downH - 1)
|
||||
local oy, bias
|
||||
if y % 2 == 0 then
|
||||
oy, bias = max(iy - 1, 0), 1
|
||||
else
|
||||
oy, bias = min(iy + 1, c.downH - 1), 2
|
||||
end
|
||||
local b0, b1 = iy * stride * 2, oy * stride * 2
|
||||
for x = 0, outW - 1 do
|
||||
writeu16(row, x * 2, (readu16(plane, b0 + x * 2) * 3 + readu16(plane, b1 + x * 2) + bias) // 4)
|
||||
end
|
||||
return row, 0
|
||||
else
|
||||
local hIn, hOut = c.hIn, c.hOut
|
||||
local iy = min((y * c.vIn) // c.vOut, c.rows - 1)
|
||||
local b = iy * stride * 2
|
||||
local last = stride - 1
|
||||
for x = 0, outW - 1 do
|
||||
writeu16(row, x * 2, readu16(plane, b + min((x * hIn) // hOut, last) * 2))
|
||||
end
|
||||
return row, 0
|
||||
end
|
||||
end
|
||||
|
||||
function Color.run(P: Params)
|
||||
local comps = P.comps
|
||||
local nc = #comps
|
||||
local space, outW, outH, maxv, out = P.space, P.outW, P.outH, P.maxv, P.pixels
|
||||
local crr, cbb, crg, cbg = P.crr, P.cbb, P.crg, P.cbg
|
||||
local toByte = P.toByte
|
||||
local o = 0
|
||||
for y = 0, outH - 1 do
|
||||
local s0, b0 = fetch(comps[1], y, outW)
|
||||
if space == 0 or nc < 3 then
|
||||
for x = 0, outW - 1 do
|
||||
local v = readu16(s0, b0 + x * 2)
|
||||
if toByte then
|
||||
v = readu8(toByte, v)
|
||||
end
|
||||
writeu32(out, o, 0xFF000000 + v * 0x10101)
|
||||
o += 4
|
||||
end
|
||||
else
|
||||
local s1, b1 = fetch(comps[2], y, outW)
|
||||
local s2, b2 = fetch(comps[3], y, outW)
|
||||
local s3, b3 = s0, b0
|
||||
if nc >= 4 then
|
||||
s3, b3 = fetch(comps[4], y, outW)
|
||||
end
|
||||
if space == 1 and not toByte then
|
||||
-- the common case: 8-bit YCbCr
|
||||
for x = 0, outW - 1 do
|
||||
local i = x * 2
|
||||
local yv, cb, cr = readu16(s0, b0 + i), readu16(s1, b1 + i), readu16(s2, b2 + i)
|
||||
local r = clamp(yv + readi32(crr, cr * 4), 0, 255)
|
||||
local g = clamp(yv + (readi32(cbg, cb * 4) + readi32(crg, cr * 4)) // 65536, 0, 255)
|
||||
local b = clamp(yv + readi32(cbb, cb * 4), 0, 255)
|
||||
writeu32(out, o, 0xFF000000 + r + g * 256 + b * 65536)
|
||||
o += 4
|
||||
end
|
||||
continue
|
||||
end
|
||||
for x = 0, outW - 1 do
|
||||
local i = x * 2
|
||||
local c0, c1, c2 = readu16(s0, b0 + i), readu16(s1, b1 + i), readu16(s2, b2 + i)
|
||||
local r, g, b
|
||||
if space == 2 then
|
||||
r, g, b = c0, c1, c2
|
||||
elseif space == 3 or space == 5 then
|
||||
local k = readu16(s3, b3 + i)
|
||||
if space == 5 then
|
||||
c0, c1, c2, k = maxv - c0, maxv - c1, maxv - c2, maxv - k
|
||||
end
|
||||
r = (c0 * k + maxv // 2) // maxv
|
||||
g = (c1 * k + maxv // 2) // maxv
|
||||
b = (c2 * k + maxv // 2) // maxv
|
||||
else
|
||||
r = clamp(c0 + readi32(crr, c2 * 4), 0, maxv)
|
||||
g = clamp(c0 + (readi32(cbg, c1 * 4) + readi32(crg, c2 * 4)) // 65536, 0, maxv)
|
||||
b = clamp(c0 + readi32(cbb, c1 * 4), 0, maxv)
|
||||
if space == 4 then
|
||||
-- YCCK: the YCC part decodes to inverted C, M, Y (libjpeg ycck_cmyk_convert), K as stored
|
||||
local k = readu16(s3, b3 + i)
|
||||
r = ((maxv - r) * k + maxv // 2) // maxv
|
||||
g = ((maxv - g) * k + maxv // 2) // maxv
|
||||
b = ((maxv - b) * k + maxv // 2) // maxv
|
||||
end
|
||||
end
|
||||
if toByte then
|
||||
r, g, b = readu8(toByte, r), readu8(toByte, g), readu8(toByte, b)
|
||||
end
|
||||
writeu32(out, o, 0xFF000000 + r + g * 256 + b * 65536)
|
||||
o += 4
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return Color
|
||||
@@ -0,0 +1,762 @@
|
||||
--!strict
|
||||
-- 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
|
||||
local band, rshift = bit32.band, bit32.rshift
|
||||
|
||||
local Decode = {}
|
||||
|
||||
Arith.init(Scan.ZIGZAG)
|
||||
|
||||
local function be16(b: buffer, p: number): number
|
||||
return readu8(b, p) * 256 + readu8(b, p + 1)
|
||||
end
|
||||
|
||||
local stdBuilt: { [string]: buffer } = {}
|
||||
local function stdTable(class: string, slot: number): buffer?
|
||||
local key = class .. slot
|
||||
if not stdBuilt[key] then
|
||||
local def = (if class == "dc" then Tables.DC else Tables.AC)[slot + 1]
|
||||
if not def then
|
||||
return nil
|
||||
end
|
||||
stdBuilt[key] = Scan.buildTable(def.counts, def.symbols)
|
||||
end
|
||||
return stdBuilt[key]
|
||||
end
|
||||
|
||||
-- the EXIF TIFF block (after "Exif\0\0") and its orientation tag, from an APP1 segment at [p, e)
|
||||
local function exif(b: buffer, p: number, e: number): (number?, number?)
|
||||
if e - p < 14 or buffer.readstring(b, p, 6) ~= "Exif\0\0" then
|
||||
return nil, nil
|
||||
end
|
||||
local t = p + 6
|
||||
local le
|
||||
local bo = buffer.readstring(b, t, 2)
|
||||
if bo == "II" then
|
||||
le = true
|
||||
elseif bo == "MM" then
|
||||
le = false
|
||||
else
|
||||
return nil, nil
|
||||
end
|
||||
local function r16(at: number): number
|
||||
if le then
|
||||
return readu8(b, at) + readu8(b, at + 1) * 256
|
||||
end
|
||||
return readu8(b, at) * 256 + readu8(b, at + 1)
|
||||
end
|
||||
local function r32(at: number): number
|
||||
if le then
|
||||
return r16(at) + r16(at + 2) * 65536
|
||||
end
|
||||
return r16(at) * 65536 + r16(at + 2)
|
||||
end
|
||||
local ifd = t + r32(t + 4)
|
||||
if ifd + 2 > e then
|
||||
return t, nil
|
||||
end
|
||||
local count = r16(ifd)
|
||||
for i = 0, count - 1 do
|
||||
local en = ifd + 2 + i * 12
|
||||
if en + 12 > e then
|
||||
return t, nil
|
||||
end
|
||||
if r16(en) == 0x0112 then
|
||||
local v = r16(en + 8)
|
||||
return t, if v >= 1 and v <= 8 then v else nil
|
||||
end
|
||||
end
|
||||
return t, nil
|
||||
end
|
||||
|
||||
type Comp = {
|
||||
id: number,
|
||||
h: number,
|
||||
v: number,
|
||||
tq: number,
|
||||
bpl: number,
|
||||
bpc: number,
|
||||
bw: number,
|
||||
bh: number,
|
||||
coef: buffer?,
|
||||
quant: buffer?, -- latched at the component's first scan
|
||||
dct: buffer?,
|
||||
act: buffer?,
|
||||
dcTbl: number,
|
||||
acTbl: number,
|
||||
pred: number,
|
||||
ctx: number,
|
||||
}
|
||||
|
||||
type Frame = {
|
||||
width: number,
|
||||
height: number,
|
||||
precision: number,
|
||||
progressive: boolean,
|
||||
arithmetic: boolean,
|
||||
comps: { Comp },
|
||||
hmax: number,
|
||||
vmax: number,
|
||||
mcusX: number,
|
||||
mcusY: number,
|
||||
}
|
||||
|
||||
local SOF_REFUSED = {
|
||||
[0xC3] = "lossless",
|
||||
[0xC5] = "hierarchical",
|
||||
[0xC6] = "hierarchical",
|
||||
[0xC7] = "hierarchical",
|
||||
[0xCB] = "lossless arithmetic-coded",
|
||||
[0xCD] = "hierarchical arithmetic-coded",
|
||||
[0xCE] = "hierarchical arithmetic-coded",
|
||||
[0xCF] = "hierarchical arithmetic-coded",
|
||||
}
|
||||
|
||||
-- failures carry a code: "corrupt" | "unsupported" | "limit" | "truncated"
|
||||
local function parseSof(b: buffer, p: number, e: number, m: number): (Frame?, string?, string?)
|
||||
if e - p < 6 then
|
||||
return nil, "corrupt", "short SOF"
|
||||
end
|
||||
local prec = readu8(b, p)
|
||||
local height, width, nf = be16(b, p + 1), be16(b, p + 3), readu8(b, p + 5)
|
||||
if prec ~= 8 and prec ~= 12 then
|
||||
return nil, "unsupported", "sample precision " .. prec
|
||||
end
|
||||
if width == 0 or height == 0 then
|
||||
if height == 0 and width > 0 then
|
||||
return nil, "unsupported", "DNL (height 0 in the frame header)"
|
||||
end
|
||||
return nil, "corrupt", "bad size " .. width .. "x" .. height
|
||||
end
|
||||
if nf ~= 1 and nf ~= 3 and nf ~= 4 then
|
||||
return nil, "unsupported", "component count " .. nf
|
||||
end
|
||||
if e - p < 6 + nf * 3 then
|
||||
return nil, "corrupt", "short SOF"
|
||||
end
|
||||
local comps = {}
|
||||
local hmax, vmax = 1, 1
|
||||
for i = 0, nf - 1 do
|
||||
local q = p + 6 + i * 3
|
||||
local hv = readu8(b, q + 1)
|
||||
local h, v, tq = rshift(hv, 4), band(hv, 15), readu8(b, q + 2)
|
||||
if h < 1 or h > 4 or v < 1 or v > 4 then
|
||||
return nil, "corrupt", "bad sampling factors " .. h .. "x" .. v
|
||||
end
|
||||
if tq > 3 then
|
||||
return nil, "corrupt", "bad quantisation table selector " .. tq
|
||||
end
|
||||
local id = readu8(b, q)
|
||||
for _, c in comps do
|
||||
if c.id == id then
|
||||
return nil, "corrupt", "duplicate component id " .. id
|
||||
end
|
||||
end
|
||||
hmax, vmax = math.max(hmax, h), math.max(vmax, v)
|
||||
table.insert(comps, { id = id, h = h, v = v, tq = tq, bpl = 0, bpc = 0, bw = 0, bh = 0, dcTbl = 0, acTbl = 0, pred = 0, ctx = 0 } :: Comp)
|
||||
end
|
||||
local mcusX = math.ceil(width / (8 * hmax))
|
||||
local mcusY = math.ceil(height / (8 * vmax))
|
||||
for _, c in comps do
|
||||
c.bpl = mcusX * c.h
|
||||
c.bpc = mcusY * c.v
|
||||
c.bw = math.ceil(math.ceil(width * c.h / hmax) / 8)
|
||||
c.bh = math.ceil(math.ceil(height * c.v / vmax) / 8)
|
||||
end
|
||||
return {
|
||||
width = width,
|
||||
height = height,
|
||||
precision = prec,
|
||||
progressive = m == 0xC2 or m == 0xCA,
|
||||
arithmetic = m == 0xC9 or m == 0xCA,
|
||||
comps = comps,
|
||||
hmax = hmax,
|
||||
vmax = vmax,
|
||||
mcusX = mcusX,
|
||||
mcusY = mcusY,
|
||||
}
|
||||
end
|
||||
|
||||
local function colorSpaceOf(frame: Frame, adobe: number?, jfif: boolean): string
|
||||
local n = #frame.comps
|
||||
if n == 1 then
|
||||
return "gray"
|
||||
elseif n == 3 then
|
||||
if adobe ~= nil then
|
||||
return if adobe == 0 then "rgb" else "ycbcr"
|
||||
end
|
||||
local c = frame.comps
|
||||
if not jfif and c[1].id == 82 and c[2].id == 71 and c[3].id == 66 then
|
||||
return "rgb"
|
||||
end
|
||||
return "ycbcr"
|
||||
end
|
||||
return if adobe == 2 then "ycck" else "cmyk"
|
||||
end
|
||||
Decode.colorSpaceOf = colorSpaceOf
|
||||
|
||||
-- The IDCT size (8, 4, 2 or 1) for a component at a scale. libjpeg-turbo scales chroma up through a bigger IDCT
|
||||
-- instead of upsampling it, when the sampling ratios allow (jdmaster.c jpeg_calc_output_dimensions).
|
||||
local function idctSize(f: Frame, c: Comp, scale: number): number
|
||||
local minSize = 8 // scale
|
||||
local ssize = minSize
|
||||
while ssize < 8 and (f.hmax * minSize) % (c.h * ssize * 2) == 0 and (f.vmax * minSize) % (c.v * ssize * 2) == 0 do
|
||||
ssize *= 2
|
||||
end
|
||||
return ssize
|
||||
end
|
||||
|
||||
export type State = {
|
||||
frame: any,
|
||||
adobe: number?,
|
||||
jfif: boolean,
|
||||
density: { unit: number, x: number, y: number }?,
|
||||
orientation: number,
|
||||
exif: buffer?,
|
||||
icc: buffer?,
|
||||
comments: { string },
|
||||
truncated: boolean,
|
||||
scale: number,
|
||||
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
|
||||
-- headerOnly it stops at the frame header, otherwise it decodes every scan into the components' coefficients.
|
||||
function Decode.parse(b: buffer, base: number, n: number, opts: any, headerOnly: boolean): (State?, string?, string?)
|
||||
if n - base < 4 or readu8(b, base) ~= 0xFF or readu8(b, base + 1) ~= 0xD8 then
|
||||
return nil, "corrupt", "not a JPEG file (no SOI marker)"
|
||||
end
|
||||
local scale = (opts and opts.scale) or 1
|
||||
if scale ~= 1 and scale ~= 2 and scale ~= 4 and scale ~= 8 then
|
||||
return nil, "arg", "scale must be 1, 2, 4 or 8"
|
||||
end
|
||||
local maxPixels = (opts and opts.maxPixels) or 2 ^ 26
|
||||
local quant: { [number]: buffer } = {}
|
||||
local dcT: { [number]: buffer } = {}
|
||||
local acT: { [number]: buffer } = {}
|
||||
local dcL, dcU, acK = { 0, 0, 0, 0 }, { 1, 1, 1, 1 }, { 5, 5, 5, 5 }
|
||||
local frame: Frame? = nil
|
||||
local st: State = {
|
||||
frame = nil,
|
||||
adobe = nil,
|
||||
jfif = false,
|
||||
density = nil,
|
||||
orientation = 1,
|
||||
exif = nil,
|
||||
icc = nil,
|
||||
comments = {},
|
||||
truncated = false,
|
||||
scale = scale,
|
||||
avi1 = nil,
|
||||
endPos = n,
|
||||
}
|
||||
local iccChunks: { buffer } = {}
|
||||
local ri = 0
|
||||
local scans = 0
|
||||
local clean: buffer? = nil
|
||||
local rst = {}
|
||||
local pos = base + 2
|
||||
while pos < n do
|
||||
-- find the next marker (tolerate garbage and fill bytes)
|
||||
if readu8(b, pos) ~= 0xFF then
|
||||
pos += 1
|
||||
continue
|
||||
end
|
||||
while pos < n and readu8(b, pos) == 0xFF do
|
||||
pos += 1
|
||||
end
|
||||
if pos >= n then
|
||||
break
|
||||
end
|
||||
local m = readu8(b, pos)
|
||||
pos += 1
|
||||
if m == 0xD9 then
|
||||
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)
|
||||
end
|
||||
if pos + 2 > n then
|
||||
st.truncated = true
|
||||
break
|
||||
end
|
||||
local len = be16(b, pos)
|
||||
if len < 2 then
|
||||
return nil, "corrupt", string.format("bad segment length for marker %02X", m)
|
||||
end
|
||||
local p, e = pos + 2, pos + len
|
||||
if e > n then
|
||||
if m == 0xDA and frame and not headerOnly then
|
||||
e = n -- a truncated SOS header still fails below
|
||||
else
|
||||
st.truncated = true
|
||||
break
|
||||
end
|
||||
end
|
||||
pos = e
|
||||
if m == 0xE0 then
|
||||
if e - p >= 12 and buffer.readstring(b, p, 5) == "JFIF\0" then
|
||||
st.jfif = true
|
||||
st.density = { unit = readu8(b, p + 7), x = be16(b, p + 8), y = be16(b, p + 10) }
|
||||
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)
|
||||
if t and not st.exif then
|
||||
local x = buffer.create(e - t)
|
||||
buffer.copy(x, 0, b, t, e - t)
|
||||
st.exif = x
|
||||
end
|
||||
if o then
|
||||
st.orientation = o
|
||||
end
|
||||
elseif m == 0xE2 then
|
||||
-- ICC_PROFILE\0, sequence number, count, data
|
||||
if e - p >= 14 and buffer.readstring(b, p, 12) == "ICC_PROFILE\0" then
|
||||
local seq = readu8(b, p + 12)
|
||||
local x = buffer.create(e - p - 14)
|
||||
buffer.copy(x, 0, b, p + 14, e - p - 14)
|
||||
if seq >= 1 then
|
||||
iccChunks[seq] = x
|
||||
end
|
||||
end
|
||||
elseif m == 0xEE then
|
||||
if e - p >= 12 and buffer.readstring(b, p, 5) == "Adobe" then
|
||||
st.adobe = readu8(b, p + 11)
|
||||
end
|
||||
elseif m == 0xFE then
|
||||
table.insert(st.comments, buffer.readstring(b, p, e - p))
|
||||
elseif m == 0xDB then
|
||||
-- DQT
|
||||
while p < e do
|
||||
local pt = readu8(b, p)
|
||||
local pq, tq = rshift(pt, 4), band(pt, 15)
|
||||
local size = if pq == 0 then 64 else 128
|
||||
if tq > 3 or pq > 1 or p + 1 + size > e then
|
||||
return nil, "corrupt", "bad DQT segment"
|
||||
end
|
||||
local q = buffer.create(128)
|
||||
for k = 0, 63 do
|
||||
local v = if pq == 0 then readu8(b, p + 1 + k) else be16(b, p + 1 + k * 2)
|
||||
buffer.writeu16(q, readu8(Scan.ZIGZAG, k) * 2, v)
|
||||
end
|
||||
quant[tq] = q
|
||||
p += 1 + size
|
||||
end
|
||||
elseif m == 0xC4 then
|
||||
-- DHT
|
||||
while p < e do
|
||||
if p + 17 > e then
|
||||
return nil, "corrupt", "bad DHT segment"
|
||||
end
|
||||
local tc = readu8(b, p)
|
||||
local class, slot = rshift(tc, 4), band(tc, 15)
|
||||
if class > 1 or slot > 3 then
|
||||
return nil, "corrupt", "bad DHT table class / slot"
|
||||
end
|
||||
local counts, total = {}, 0
|
||||
for l = 1, 16 do
|
||||
counts[l] = readu8(b, p + l)
|
||||
total += counts[l]
|
||||
end
|
||||
if total > 256 or p + 17 + total > e then
|
||||
return nil, "corrupt", "bad DHT segment"
|
||||
end
|
||||
local syms = {}
|
||||
for i = 1, total do
|
||||
syms[i] = readu8(b, p + 16 + i)
|
||||
end
|
||||
local t = Scan.buildTable(counts, syms)
|
||||
if class == 0 then
|
||||
dcT[slot] = t
|
||||
else
|
||||
acT[slot] = t
|
||||
end
|
||||
p += 17 + total
|
||||
end
|
||||
elseif m == 0xCC then
|
||||
-- DAC: arithmetic conditioning
|
||||
while p + 2 <= e do
|
||||
local tc, v = readu8(b, p), readu8(b, p + 1)
|
||||
local class, slot = rshift(tc, 4), band(tc, 15)
|
||||
if class > 1 or slot > 3 then
|
||||
return nil, "corrupt", "bad DAC segment"
|
||||
end
|
||||
if class == 0 then
|
||||
local L, U = band(v, 15), rshift(v, 4)
|
||||
if L > U then
|
||||
return nil, "corrupt", "bad DAC value"
|
||||
end
|
||||
dcL[slot + 1], dcU[slot + 1] = L, U
|
||||
else
|
||||
if v < 1 or v > 63 then
|
||||
return nil, "corrupt", "bad DAC value"
|
||||
end
|
||||
acK[slot + 1] = v
|
||||
end
|
||||
p += 2
|
||||
end
|
||||
elseif m == 0xDD then
|
||||
if e - p < 2 then
|
||||
return nil, "corrupt", "bad DRI segment"
|
||||
end
|
||||
ri = be16(b, p)
|
||||
elseif m == 0xC0 or m == 0xC1 or m == 0xC2 or m == 0xC9 or m == 0xCA then
|
||||
if frame then
|
||||
return nil, "corrupt", "more than one frame header"
|
||||
end
|
||||
local f, code, err = parseSof(b, p, e, m)
|
||||
if not f then
|
||||
return nil, code, err
|
||||
end
|
||||
if f.width * f.height > maxPixels then
|
||||
return nil, "limit", string.format("%d x %d is over the %d pixel limit", f.width, f.height, maxPixels)
|
||||
end
|
||||
frame = f
|
||||
st.frame = f
|
||||
if headerOnly then
|
||||
return st
|
||||
end
|
||||
elseif SOF_REFUSED[m] then
|
||||
return nil, "unsupported", SOF_REFUSED[m] .. " JPEG"
|
||||
elseif m == 0xDA then
|
||||
if headerOnly then
|
||||
break
|
||||
end
|
||||
if not frame then
|
||||
return nil, "corrupt", "scan before the frame header"
|
||||
end
|
||||
local f = frame :: Frame
|
||||
local ns = if p < e then readu8(b, p) else 0
|
||||
if ns < 1 or ns > 4 or e - p < 4 + ns * 2 then
|
||||
return nil, "corrupt", "bad SOS segment"
|
||||
end
|
||||
local sc = {}
|
||||
local blocks = 0
|
||||
for i = 0, ns - 1 do
|
||||
local id, t = readu8(b, p + 1 + i * 2), readu8(b, p + 2 + i * 2)
|
||||
local comp = nil
|
||||
for _, c in f.comps do
|
||||
if c.id == id then
|
||||
comp = c
|
||||
end
|
||||
end
|
||||
if not comp or table.find(sc, comp) then
|
||||
return nil, "corrupt", "scan names an unknown component " .. id
|
||||
end
|
||||
local td, ta = rshift(t, 4), band(t, 15)
|
||||
if td > 3 or ta > 3 then
|
||||
return nil, "corrupt", "bad entropy table selector"
|
||||
end
|
||||
comp.dcTbl, comp.acTbl = td, ta
|
||||
if not f.arithmetic then
|
||||
comp.dct = dcT[td] or stdTable("dc", td)
|
||||
comp.act = acT[ta] or stdTable("ac", ta)
|
||||
end
|
||||
blocks += comp.h * comp.v
|
||||
table.insert(sc, comp)
|
||||
end
|
||||
local q = p + 1 + ns * 2
|
||||
local ss, se, a = readu8(b, q), readu8(b, q + 1), readu8(b, q + 2)
|
||||
local ah, al = rshift(a, 4), band(a, 15)
|
||||
if ns > 1 and blocks > 10 then
|
||||
return nil, "corrupt", "more than 10 blocks per MCU"
|
||||
end
|
||||
local mode
|
||||
if not f.progressive then
|
||||
mode = 0
|
||||
ss, se, ah, al = 0, 63, 0, 0
|
||||
else
|
||||
if se > 63 or ss > se or ah > 13 or al > 13 or (ss == 0 and se ~= 0) or (ss > 0 and ns ~= 1) then
|
||||
return nil, "corrupt", "bad progressive scan parameters"
|
||||
end
|
||||
if ss == 0 then
|
||||
mode = if ah == 0 then 1 else 2
|
||||
else
|
||||
mode = if ah == 0 then 3 else 4
|
||||
end
|
||||
end
|
||||
for _, c in sc do
|
||||
if not f.arithmetic then
|
||||
if (mode == 0 or mode == 1) and not c.dct then
|
||||
return nil, "corrupt", "missing DC Huffman table"
|
||||
end
|
||||
if (mode == 0 or mode == 3 or mode == 4) and not c.act then
|
||||
return nil, "corrupt", "missing AC Huffman table"
|
||||
end
|
||||
end
|
||||
if not c.coef then
|
||||
c.coef = buffer.create(c.bpl * c.bpc * 128)
|
||||
end
|
||||
if not c.quant then
|
||||
c.quant = quant[c.tq]
|
||||
end
|
||||
end
|
||||
if not clean then
|
||||
clean = buffer.create(n - base + Scan.PAD)
|
||||
end
|
||||
local cb = clean :: buffer
|
||||
local nextPos, cleanLen, nrst = Scan.destuff(b, pos, n, cb, rst)
|
||||
if nextPos >= n then
|
||||
st.truncated = true -- no EOI
|
||||
end
|
||||
-- a component decoded through the 1x1 IDCT only needs its DC coefficient: skip its AC scans
|
||||
if not (mode >= 3 and idctSize(f, sc[1], scale) == 1) then
|
||||
local params = {
|
||||
comps = sc :: any,
|
||||
mcusX = f.mcusX,
|
||||
mcusY = f.mcusY,
|
||||
ri = ri,
|
||||
mode = mode,
|
||||
ss = ss,
|
||||
se = se,
|
||||
al = al,
|
||||
dcL = dcL,
|
||||
dcU = dcU,
|
||||
acK = acK,
|
||||
}
|
||||
local short
|
||||
if f.arithmetic then
|
||||
short = Arith.run(cb, cleanLen, rst, nrst, params)
|
||||
else
|
||||
local _
|
||||
_, short = Scan.run(cb, cleanLen, rst, nrst, params)
|
||||
end
|
||||
st.truncated = st.truncated or short
|
||||
end
|
||||
scans += 1
|
||||
pos = nextPos
|
||||
end
|
||||
end
|
||||
if not frame then
|
||||
return nil, if st.truncated then "truncated" else "corrupt", "no frame header"
|
||||
end
|
||||
if #iccChunks > 0 then
|
||||
local total = 0
|
||||
for _, c in iccChunks do
|
||||
total += buffer.len(c)
|
||||
end
|
||||
local icc = buffer.create(total)
|
||||
local o = 0
|
||||
for _, c in iccChunks do
|
||||
buffer.copy(icc, o, c)
|
||||
o += buffer.len(c)
|
||||
end
|
||||
st.icc = icc
|
||||
end
|
||||
if headerOnly then
|
||||
return st
|
||||
end
|
||||
if scans == 0 then
|
||||
return nil, "truncated", "no image data"
|
||||
end
|
||||
return st
|
||||
end
|
||||
|
||||
local SPACE_IDS = { gray = Color.GRAY, ycbcr = Color.YCC, rgb = Color.RGB, cmyk = Color.CMYK, ycck = Color.YCCK }
|
||||
|
||||
local tableCache: { [number]: { buffer } } = {}
|
||||
local function yccTables(maxv: number): { buffer }
|
||||
local t = tableCache[maxv]
|
||||
if not t then
|
||||
local a, b, c, d = Color.tables(maxv)
|
||||
t = { a, b, c, d }
|
||||
tableCache[maxv] = t
|
||||
end
|
||||
return t
|
||||
end
|
||||
|
||||
local toByte12: buffer? = nil
|
||||
|
||||
-- output(st) -> width, height, rgba8 pixels, colour space | nil, code, message
|
||||
function Decode.output(st: State): (number?, any, any, string?)
|
||||
local f: Frame = st.frame
|
||||
local scale = st.scale
|
||||
local minSize = 8 // scale
|
||||
local maxv = if f.precision == 12 then 4095 else 255
|
||||
local center = (maxv + 1) // 2
|
||||
local p1 = if f.precision == 12 then 1 else 2
|
||||
local outW = math.ceil(f.width * minSize / 8)
|
||||
local outH = math.ceil(f.height * minSize / 8)
|
||||
local fancy = minSize > 1
|
||||
local ccomps = {}
|
||||
local zeroQ = buffer.create(128)
|
||||
for _, c in f.comps do
|
||||
local ssize = idctSize(f, c, scale)
|
||||
local stride, rows = c.bpl * ssize, c.bpc * ssize
|
||||
local plane = buffer.create(stride * rows * 2)
|
||||
local coef = c.coef or buffer.create(c.bpl * c.bpc * 128)
|
||||
local q = c.quant
|
||||
if not q then
|
||||
if c.coef then
|
||||
return nil, "corrupt", "missing quantisation table " .. c.tq
|
||||
end
|
||||
q = zeroQ -- the component never appeared in a scan: mid grey
|
||||
end
|
||||
Dct.idctComponent(coef, q :: buffer, c.bpl, c.bpc, ssize, plane, p1, center, maxv)
|
||||
local hIn, hOut = c.h * ssize // minSize, f.hmax
|
||||
local vIn, vOut = c.v * ssize // minSize, f.vmax
|
||||
local downW = math.ceil(f.width * c.h * ssize / (f.hmax * 8))
|
||||
local downH = math.ceil(f.height * c.v * ssize / (f.vmax * 8))
|
||||
local method
|
||||
if hIn == hOut and vIn == vOut then
|
||||
method = Color.FULL
|
||||
elseif hIn * 2 == hOut and vIn * 2 == vOut and fancy and downW > 2 then
|
||||
method = Color.H2V2
|
||||
elseif hIn * 2 == hOut and vIn == vOut and fancy and downW > 2 then
|
||||
method = Color.H2V1
|
||||
elseif hIn == hOut and vIn * 2 == vOut and fancy then
|
||||
method = Color.H1V2
|
||||
else
|
||||
method = Color.REPLICATE
|
||||
end
|
||||
table.insert(ccomps, {
|
||||
plane = plane,
|
||||
stride = stride,
|
||||
rows = rows,
|
||||
downW = downW,
|
||||
downH = downH,
|
||||
method = method,
|
||||
hIn = hIn,
|
||||
hOut = hOut,
|
||||
vIn = vIn,
|
||||
vOut = vOut,
|
||||
row = buffer.create((math.max(outW, 2 * stride) + 8) * 2),
|
||||
})
|
||||
c.coef = nil -- free the coefficients early
|
||||
end
|
||||
local space = colorSpaceOf(f, st.adobe, st.jfif)
|
||||
local spaceId = SPACE_IDS[space]
|
||||
if space == "cmyk" and st.adobe == nil then
|
||||
spaceId = Color.CMYK_PLAIN
|
||||
end
|
||||
local t = yccTables(maxv)
|
||||
local tb = nil
|
||||
if maxv == 4095 then
|
||||
if not toByte12 then
|
||||
local tbuf = buffer.create(4096)
|
||||
for v = 0, 4095 do
|
||||
buffer.writeu8(tbuf, v, (v * 255 + 2047) // 4095)
|
||||
end
|
||||
toByte12 = tbuf
|
||||
end
|
||||
tb = toByte12
|
||||
end
|
||||
local pixels = buffer.create(outW * outH * 4)
|
||||
Color.run({
|
||||
comps = ccomps,
|
||||
space = spaceId,
|
||||
outW = outW,
|
||||
outH = outH,
|
||||
maxv = maxv,
|
||||
pixels = pixels,
|
||||
crr = t[1],
|
||||
cbb = t[2],
|
||||
crg = t[3],
|
||||
cbg = t[4],
|
||||
toByte = tb,
|
||||
})
|
||||
return outW, outH, pixels, space
|
||||
end
|
||||
|
||||
-- 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 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).
|
||||
-- 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
|
||||
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" 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
|
||||
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 = scratchPlane(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
|
||||
@@ -0,0 +1,899 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- 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, 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/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
|
||||
|
||||
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), 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)
|
||||
OP = 0
|
||||
ACC, NB = 0, 0
|
||||
GATHER = false
|
||||
EOBRUN, BE = 0, 0
|
||||
|
||||
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
|
||||
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 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
|
||||
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
|
||||
@@ -0,0 +1,456 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- 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,
|
||||
-- records where each RSTn marker fell, and stops at any other marker. The clean buffer is followed by at least
|
||||
-- PAD zero bytes, so the bit reader can read 32 bits at any position up to PAD bytes past the end without a
|
||||
-- bounds check. `run` checks the position once per MCU, and no MCU (at most 10 blocks, enforced by the parser)
|
||||
-- can consume PAD bytes. So every buffer index stays in range, even on garbage data.
|
||||
--
|
||||
-- The bit reader keeps no state but a bit position: `peek` reads the big-endian 32-bit word that holds it.
|
||||
-- Huffman tables (built by `buildTable`) are buffers:
|
||||
-- [0, 1024) fast lookup by the next 9 bits: u16 (length << 8) | symbol, 0 = longer code
|
||||
-- [1024, 1096) maxcode[l], l = 0..17: u32, one past the last code of length l, left-aligned to 16 bits
|
||||
-- [1096, 1168) delta[l]: i32, symbol index = code + delta[l]
|
||||
-- [1168, 1424) symbols
|
||||
-- [1424, 1426) symbol count
|
||||
-- [1428, 3476) fast AC lookup by the next 9 bits: i32 value * 256 + run * 16 + total length, when the code
|
||||
-- and its extra bits fit in 9 bits (0 otherwise)
|
||||
local readu8, readu16, readu32, readi32, readi16 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi32, buffer.readi16
|
||||
local writeu8, writeu16, writeu32, writei32, writei16 = buffer.writeu8, buffer.writeu16, buffer.writeu32, buffer.writei32, buffer.writei16
|
||||
local band, bor, lshift, rshift, byteswap = bit32.band, bit32.bor, bit32.lshift, bit32.rshift, bit32.byteswap
|
||||
|
||||
local Scan = {}
|
||||
|
||||
Scan.PAD = 4096
|
||||
Scan.TABLE_SIZE = 3476
|
||||
|
||||
local T_MAX = 1024
|
||||
local T_DELTA = 1096
|
||||
local T_VAL = 1168
|
||||
local T_COUNT = 1424
|
||||
local T_FASTAC = 1428
|
||||
|
||||
-- zigzag index -> natural (row-major) index, padded with 63s so a run past the end stays in range
|
||||
local ZZ = buffer.create(80)
|
||||
do
|
||||
local i = 0
|
||||
for s = 0, 14 do
|
||||
local lo, hi = math.max(0, s - 7), math.min(s, 7)
|
||||
if s % 2 == 0 then
|
||||
for r = hi, lo, -1 do
|
||||
writeu8(ZZ, i, r * 8 + (s - r))
|
||||
i += 1
|
||||
end
|
||||
else
|
||||
for r = lo, hi do
|
||||
writeu8(ZZ, i, r * 8 + (s - r))
|
||||
i += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
for j = 64, 79 do
|
||||
writeu8(ZZ, j, 63)
|
||||
end
|
||||
end
|
||||
Scan.ZIGZAG = ZZ
|
||||
|
||||
-- Builds a Huffman table from the 16 code-length counts and the symbols (Luau arrays, 1-based). An
|
||||
-- over-subscribed table keeps the codes that fit; the rest decode as invalid.
|
||||
function Scan.buildTable(counts: { number }, symbols: { number }): buffer
|
||||
local t = buffer.create(Scan.TABLE_SIZE)
|
||||
local code, k = 0, 0
|
||||
local nsym = #symbols
|
||||
local codes, sizes = {}, {}
|
||||
local broken = false
|
||||
for l = 1, 16 do
|
||||
writei32(t, T_DELTA + l * 4, k - code)
|
||||
local n = counts[l] or 0
|
||||
for _ = 1, n do
|
||||
if broken or code >= lshift(1, l) or k >= nsym or k >= 256 then
|
||||
broken = true
|
||||
break
|
||||
end
|
||||
k += 1
|
||||
codes[k] = code
|
||||
sizes[k] = l
|
||||
code += 1
|
||||
end
|
||||
writeu32(t, T_MAX + l * 4, if broken then 0 else lshift(code, 16 - l))
|
||||
code *= 2
|
||||
end
|
||||
writeu32(t, T_MAX + 17 * 4, 0xFFFFFFFF)
|
||||
for i = 1, k do
|
||||
writeu8(t, T_VAL + i - 1, symbols[i])
|
||||
end
|
||||
writeu16(t, T_COUNT, k)
|
||||
-- fast lookups
|
||||
for i = 1, k do
|
||||
local l = sizes[i]
|
||||
if l <= 9 then
|
||||
local sym = symbols[i]
|
||||
local base = lshift(codes[i], 9 - l)
|
||||
for j = 0, lshift(1, 9 - l) - 1 do
|
||||
local idx = base + j
|
||||
writeu16(t, idx * 2, l * 256 + sym)
|
||||
local r, s = rshift(sym, 4), band(sym, 15)
|
||||
if s ~= 0 and l + s <= 9 then
|
||||
local v = band(rshift(idx, 9 - l - s), lshift(1, s) - 1)
|
||||
if v < lshift(1, s - 1) then
|
||||
v = v - lshift(1, s) + 1
|
||||
end
|
||||
writei32(t, T_FASTAC + idx * 4, v * 256 + r * 16 + l + s)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return t
|
||||
end
|
||||
|
||||
-- Copies the entropy-coded data at src[pos..n) into dst (at least n - pos + PAD bytes): byte stuffing removed,
|
||||
-- RSTn offsets (in dst) stored in rst[1..]. Returns the source position of the marker that ended the scan (or n),
|
||||
-- the clean length, and the RST count. The PAD bytes after the clean data are zeroed.
|
||||
function Scan.destuff(src: buffer, pos: number, n: number, dst: buffer, rst: { number }): (number, number, number)
|
||||
local o, nr = 0, 0
|
||||
while pos < n do
|
||||
local b = readu8(src, pos)
|
||||
if b ~= 0xFF then
|
||||
writeu8(dst, o, b)
|
||||
o += 1
|
||||
pos += 1
|
||||
else
|
||||
local q = pos + 1
|
||||
while q < n and readu8(src, q) == 0xFF do
|
||||
q += 1
|
||||
end
|
||||
if q >= n then
|
||||
pos = n
|
||||
break
|
||||
end
|
||||
local m = readu8(src, q)
|
||||
if m == 0 then
|
||||
writeu8(dst, o, 0xFF)
|
||||
o += 1
|
||||
pos = q + 1
|
||||
elseif m >= 0xD0 and m <= 0xD7 then
|
||||
nr += 1
|
||||
rst[nr] = o
|
||||
pos = q + 1
|
||||
else
|
||||
pos = q - 1
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
buffer.fill(dst, o, 0, Scan.PAD)
|
||||
return pos, o, nr
|
||||
end
|
||||
|
||||
local function huff(d: buffer, pos: number, t: buffer): (number, number)
|
||||
local w = lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7))
|
||||
local f = readu16(t, rshift(w, 23) * 2)
|
||||
if f ~= 0 then
|
||||
return band(f, 255), pos + rshift(f, 8)
|
||||
end
|
||||
local c = rshift(w, 16)
|
||||
local l = 10
|
||||
while c >= readu32(t, T_MAX + l * 4) do
|
||||
l += 1
|
||||
end
|
||||
if l > 16 then
|
||||
return 0, pos + 16 -- invalid code
|
||||
end
|
||||
local idx = rshift(c, 16 - l) + readi32(t, T_DELTA + l * 4)
|
||||
if idx < 0 or idx >= readu16(t, T_COUNT) then
|
||||
return 0, pos + l
|
||||
end
|
||||
return readu8(t, T_VAL + idx), pos + l
|
||||
end
|
||||
|
||||
-- the next s bits (1 <= s <= 16) as an unsigned number
|
||||
local function bits(d: buffer, pos: number, s: number): number
|
||||
return rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 32 - s)
|
||||
end
|
||||
|
||||
local function extend(v: number, s: number): number
|
||||
if v < lshift(1, s - 1) then
|
||||
return v - lshift(1, s) + 1
|
||||
end
|
||||
return v
|
||||
end
|
||||
|
||||
-- sequential (baseline / extended) block: returns pos, DC predictor
|
||||
local function blockSeq(d: buffer, pos: number, coef: buffer, off: number, dct: buffer, act: buffer, pred: number): (number, number)
|
||||
local s
|
||||
s, pos = huff(d, pos, dct)
|
||||
if s ~= 0 then
|
||||
if s > 16 then
|
||||
s = 16
|
||||
end
|
||||
pred += extend(bits(d, pos, s), s)
|
||||
pos += s
|
||||
end
|
||||
writei16(coef, off, pred)
|
||||
local k = 1
|
||||
while k < 64 do
|
||||
local w = lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7))
|
||||
local fa = readi32(act, T_FASTAC + rshift(w, 23) * 4)
|
||||
if fa ~= 0 then
|
||||
local low = fa % 256
|
||||
k += low // 16
|
||||
pos += low % 16
|
||||
if k > 63 then
|
||||
break
|
||||
end
|
||||
writei16(coef, off + readu8(ZZ, k) * 2, fa // 256)
|
||||
k += 1
|
||||
else
|
||||
local rs
|
||||
rs, pos = huff(d, pos, act)
|
||||
local r, sz = rshift(rs, 4), band(rs, 15)
|
||||
if sz == 0 then
|
||||
if r ~= 15 then
|
||||
break
|
||||
end
|
||||
k += 16
|
||||
else
|
||||
k += r
|
||||
if k > 63 then
|
||||
break
|
||||
end
|
||||
writei16(coef, off + readu8(ZZ, k) * 2, extend(bits(d, pos, sz), sz))
|
||||
pos += sz
|
||||
k += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
return pos, pred
|
||||
end
|
||||
|
||||
local function blockDcFirst(d: buffer, pos: number, coef: buffer, off: number, dct: buffer, pred: number, al: number): (number, number)
|
||||
local s
|
||||
s, pos = huff(d, pos, dct)
|
||||
if s ~= 0 then
|
||||
if s > 16 then
|
||||
s = 16
|
||||
end
|
||||
pred += extend(bits(d, pos, s), s)
|
||||
pos += s
|
||||
end
|
||||
writei16(coef, off, pred * lshift(1, al))
|
||||
return pos, pred
|
||||
end
|
||||
|
||||
local function blockAcFirst(d: buffer, pos: number, coef: buffer, off: number, act: buffer, ss: number, se: number, al: number, eobrun: number): (number, number)
|
||||
if eobrun > 0 then
|
||||
return pos, eobrun - 1
|
||||
end
|
||||
local mul = lshift(1, al)
|
||||
local k = ss
|
||||
while k <= se do
|
||||
local w = lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7))
|
||||
local fa = readi32(act, T_FASTAC + rshift(w, 23) * 4)
|
||||
if fa ~= 0 then
|
||||
local low = fa % 256
|
||||
k += low // 16
|
||||
pos += low % 16
|
||||
if k > se then
|
||||
break
|
||||
end
|
||||
writei16(coef, off + readu8(ZZ, k) * 2, (fa // 256) * mul)
|
||||
k += 1
|
||||
else
|
||||
local rs
|
||||
rs, pos = huff(d, pos, act)
|
||||
local r, s = rshift(rs, 4), band(rs, 15)
|
||||
if s == 0 then
|
||||
if r < 15 then
|
||||
eobrun = lshift(1, r) - 1
|
||||
if r > 0 then
|
||||
eobrun += bits(d, pos, r)
|
||||
pos += r
|
||||
end
|
||||
break
|
||||
end
|
||||
k += 16
|
||||
else
|
||||
k += r
|
||||
if k > se then
|
||||
break
|
||||
end
|
||||
writei16(coef, off + readu8(ZZ, k) * 2, extend(bits(d, pos, s), s) * mul)
|
||||
pos += s
|
||||
k += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
return pos, eobrun
|
||||
end
|
||||
|
||||
-- successive-approximation refinement of AC coefficients ss..se (as stb_image / libjpeg decode_mcu_AC_refine)
|
||||
local function blockAcRefine(d: buffer, pos: number, coef: buffer, off: number, act: buffer, ss: number, se: number, al: number, eobrun: number): (number, number)
|
||||
local bit = lshift(1, al)
|
||||
if eobrun > 0 then
|
||||
for k = ss, se do
|
||||
local o = off + readu8(ZZ, k) * 2
|
||||
local p = readi16(coef, o)
|
||||
if p ~= 0 then
|
||||
local b = rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 31)
|
||||
pos += 1
|
||||
if b ~= 0 and band(p, bit) == 0 then
|
||||
writei16(coef, o, if p > 0 then p + bit else p - bit)
|
||||
end
|
||||
end
|
||||
end
|
||||
return pos, eobrun - 1
|
||||
end
|
||||
local k = ss
|
||||
while k <= se do
|
||||
local rs
|
||||
rs, pos = huff(d, pos, act)
|
||||
local s, r = band(rs, 15), rshift(rs, 4)
|
||||
local val = 0
|
||||
if s == 0 then
|
||||
if r < 15 then
|
||||
eobrun = lshift(1, r) - 1
|
||||
if r > 0 then
|
||||
eobrun += bits(d, pos, r)
|
||||
pos += r
|
||||
end
|
||||
r = 64 -- the rest of the block only refines
|
||||
end
|
||||
else
|
||||
-- s must be 1; anything else is corrupt and treated as 1
|
||||
local b = rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 31)
|
||||
pos += 1
|
||||
val = if b ~= 0 then bit else -bit
|
||||
end
|
||||
while k <= se do
|
||||
local o = off + readu8(ZZ, k) * 2
|
||||
k += 1
|
||||
local p = readi16(coef, o)
|
||||
if p ~= 0 then
|
||||
local b = rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 31)
|
||||
pos += 1
|
||||
if b ~= 0 and band(p, bit) == 0 then
|
||||
writei16(coef, o, if p > 0 then p + bit else p - bit)
|
||||
end
|
||||
else
|
||||
if r == 0 then
|
||||
if val ~= 0 then
|
||||
writei16(coef, o, val)
|
||||
end
|
||||
break
|
||||
end
|
||||
r -= 1
|
||||
end
|
||||
end
|
||||
end
|
||||
-- an EOB run that started in this block counts it already (eobrun = run length - 1)
|
||||
return pos, eobrun
|
||||
end
|
||||
|
||||
export type ScanComp = {
|
||||
coef: buffer, -- i16 coefficients, 64 per block in natural order, blocks row-major on a bpl-wide grid
|
||||
bpl: number,
|
||||
h: number,
|
||||
v: number,
|
||||
bw: number, -- blocks across / down the component itself (non-interleaved scans)
|
||||
bh: number,
|
||||
dct: buffer?,
|
||||
act: buffer?,
|
||||
pred: number,
|
||||
}
|
||||
|
||||
export type ScanParams = {
|
||||
comps: { ScanComp },
|
||||
mcusX: number,
|
||||
mcusY: number,
|
||||
ri: number, -- restart interval in MCUs (0 = none)
|
||||
mode: number, -- 0 sequential, 1 DC first, 2 DC refine, 3 AC first, 4 AC refine
|
||||
ss: number,
|
||||
se: number,
|
||||
al: number,
|
||||
}
|
||||
|
||||
-- Decodes one scan from the clean data d (cleanLen bytes, then PAD zeros). Returns the final bit position and
|
||||
-- whether the data ran out (or overran) before the last MCU.
|
||||
function Scan.run(d: buffer, cleanLen: number, rst: { number }, nrst: number, P: ScanParams): (number, boolean)
|
||||
local comps = P.comps
|
||||
local nc = #comps
|
||||
local mode, ss, se, al, ri = P.mode, P.ss, P.se, P.al, P.ri
|
||||
local endBits = cleanLen * 8
|
||||
local units, ux
|
||||
if nc == 1 then
|
||||
ux = comps[1].bw
|
||||
units = ux * comps[1].bh
|
||||
else
|
||||
ux = P.mcusX
|
||||
units = ux * P.mcusY
|
||||
end
|
||||
for i = 1, nc do
|
||||
comps[i].pred = 0
|
||||
end
|
||||
local pos, eobrun, rstIdx = 0, 0, 0
|
||||
local truncated, skipping = false, false
|
||||
local bit = lshift(1, al)
|
||||
for u = 0, units - 1 do
|
||||
if ri > 0 and u > 0 and u % ri == 0 then
|
||||
rstIdx += 1
|
||||
if rstIdx <= nrst then
|
||||
pos = rst[rstIdx] * 8
|
||||
skipping = false
|
||||
end
|
||||
for i = 1, nc do
|
||||
comps[i].pred = 0
|
||||
end
|
||||
eobrun = 0
|
||||
end
|
||||
if pos > endBits then
|
||||
truncated = true
|
||||
if ri == 0 or rstIdx >= nrst then
|
||||
break
|
||||
end
|
||||
skipping = true
|
||||
end
|
||||
if not skipping then
|
||||
local my, mx = u // ux, u % ux
|
||||
for ci = 1, nc do
|
||||
local c = comps[ci]
|
||||
local bh, bw, by0, bx0
|
||||
if nc == 1 then
|
||||
bh, bw, by0, bx0 = 1, 1, my, mx
|
||||
else
|
||||
bh, bw, by0, bx0 = c.v, c.h, my * c.v, mx * c.h
|
||||
end
|
||||
local coef, bpl = c.coef, c.bpl
|
||||
for by = by0, by0 + bh - 1 do
|
||||
for bx = bx0, bx0 + bw - 1 do
|
||||
local off = (by * bpl + bx) * 128
|
||||
if mode == 0 then
|
||||
pos, c.pred = blockSeq(d, pos, coef, off, c.dct :: buffer, c.act :: buffer, c.pred)
|
||||
elseif mode == 1 then
|
||||
pos, c.pred = blockDcFirst(d, pos, coef, off, c.dct :: buffer, c.pred, al)
|
||||
elseif mode == 2 then
|
||||
local b = rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 31)
|
||||
pos += 1
|
||||
if b ~= 0 then
|
||||
writei16(coef, off, bor(readi16(coef, off), bit))
|
||||
end
|
||||
elseif mode == 3 then
|
||||
pos, eobrun = blockAcFirst(d, pos, coef, off, c.act :: buffer, ss, se, al, eobrun)
|
||||
else
|
||||
pos, eobrun = blockAcRefine(d, pos, coef, off, c.act :: buffer, ss, se, al, eobrun)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return pos, truncated
|
||||
end
|
||||
|
||||
return Scan
|
||||
@@ -0,0 +1,77 @@
|
||||
--!strict
|
||||
-- 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 = {}
|
||||
|
||||
local function range(t: { number }, a: number, b: number)
|
||||
for v = a, b do
|
||||
table.insert(t, v)
|
||||
end
|
||||
end
|
||||
|
||||
-- { counts (16 code-length counts), symbols } per table: dc[1] luma, dc[2] chroma, ac[1], ac[2]
|
||||
local dcl = { 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 }
|
||||
local dcc = { 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 }
|
||||
local dcv = {}
|
||||
range(dcv, 0, 11)
|
||||
local acl = { 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d }
|
||||
local aclv = {
|
||||
0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
|
||||
0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
|
||||
0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
|
||||
0x29, 0x2a,
|
||||
}
|
||||
range(aclv, 0x34, 0x3a)
|
||||
for hi = 4, 8 do
|
||||
range(aclv, hi * 16 + 3, hi * 16 + 10)
|
||||
end
|
||||
for hi = 9, 13 do
|
||||
range(aclv, hi * 16 + 2, hi * 16 + 10)
|
||||
end
|
||||
range(aclv, 0xe1, 0xea)
|
||||
range(aclv, 0xf1, 0xfa)
|
||||
local acc = { 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 }
|
||||
local accv = {
|
||||
0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
|
||||
0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
|
||||
0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
|
||||
0x27, 0x28, 0x29, 0x2a,
|
||||
}
|
||||
range(accv, 0x35, 0x3a)
|
||||
for hi = 4, 7 do
|
||||
range(accv, hi * 16 + 3, hi * 16 + 10)
|
||||
end
|
||||
for hi = 8, 14 do
|
||||
range(accv, hi * 16 + 2, hi * 16 + 10)
|
||||
end
|
||||
range(accv, 0xf2, 0xfa)
|
||||
|
||||
export type Spec = { counts: { number }, symbols: { number } }
|
||||
Tables.DC = { { counts = dcl, symbols = dcv }, { counts = dcc, symbols = dcv } } :: { Spec }
|
||||
Tables.AC = { { counts = acl, symbols = aclv }, { counts = acc, symbols = accv } } :: { Spec }
|
||||
|
||||
-- K.1, natural (row-major) order
|
||||
Tables.LUMA = {
|
||||
16, 11, 10, 16, 24, 40, 51, 61, 12, 12, 14, 19, 26, 58, 60, 55, 14, 13, 16, 24, 40, 57, 69, 56, 14, 17, 22, 29,
|
||||
51, 87, 80, 62, 18, 22, 37, 56, 68, 109, 103, 77, 24, 35, 55, 64, 81, 104, 113, 92, 49, 64, 78, 87, 103, 121,
|
||||
120, 101, 72, 92, 95, 98, 112, 100, 103, 99,
|
||||
}
|
||||
Tables.CHROMA = {
|
||||
17, 18, 24, 47, 99, 99, 99, 99, 18, 21, 26, 66, 99, 99, 99, 99, 24, 26, 56, 99, 99, 99, 99, 99, 47, 66, 99, 99,
|
||||
99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99,
|
||||
99, 99, 99, 99, 99, 99, 99, 99,
|
||||
}
|
||||
|
||||
-- quant(base, quality) -> 64 values (natural order) for quality 1..100, clamped to 1..255 (baseline)
|
||||
function Tables.quant(base: { number }, quality: number): { number }
|
||||
local q = math.clamp(math.floor(quality), 1, 100)
|
||||
local scale = if q < 50 then 5000 // q else 200 - q * 2
|
||||
local out = table.create(64, 1)
|
||||
for i = 1, 64 do
|
||||
out[i] = math.clamp((base[i] * scale + 50) // 100, 1, 255)
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
return Tables
|
||||
@@ -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, 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 quads = w // 4
|
||||
local rest = w - quads * 4
|
||||
for y = 0, h - 1 do
|
||||
local s = y * stride * 2
|
||||
local d = doff + y * w
|
||||
-- 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
|
||||
for k = 0, rest - 1 do
|
||||
writeu8(dst, d + k, readu16(src, s + k * 2))
|
||||
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
|
||||
@@ -0,0 +1,387 @@
|
||||
--!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
|
||||
local source: any = img.meta.source
|
||||
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
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
Reference in new issue
Block a user