--!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