--!strict --!native --!optimize 2 -- codecs/video/Theora/Decoder: the Theora frame decoder (Theora I specification, section 7; native, never throws). A -- Luau port of libtheora 1.2.0's decoder (Xiph.Org, BSD 3-clause: licenses/libtheora-BSD.txt; decode.c, state.c, -- idct.c, fragment.c) with the bit-exact reconstruction of the specification: -- * frame header, coded super block / block flags (the run-length codes), macro block modes (the 8 mode -- alphabets), motion vectors (VLC / fixed length, last / prior vectors, 4MV with the chroma averages of each pixel -- format), per-block qi indices, DC / AC tokens with EOB runs across blocks, planes and coefficients; -- * DC prediction, dequantisation, the spec's 16-bit integer IDCT (DC-only blocks as libtheora: (dc * q + 15) >> 5), -- half-pel motion compensation (two-reference average toward zero), the loop filter, border extension for -- unrestricted motion vectors, golden / previous reference frames; -- * 4:2:0, 4:2:2 and 4:4:4; empty packets repeat the previous frame. -- Differences from libtheora: coefficients are kept per fragment (64 i16 each) instead of libtheora's token lists, -- the frame is reconstructed whole (no MCU pipelining, same result), there is no post-processing (libtheora's default), -- and intermediate IDCT sums are not wrapped to 16 bits (only out-of-range streams differ). -- -- Planes are stored in Theora's own orientation (row 0 is the bottom of the picture) with 16 (luma) / 8 (subsampled -- chroma) pixels of edge padding; output() turns the picture region into top-down planes. local Header = require("@formats/codecs/video/Theora/Header") local readu8 = buffer.readu8 local writeu8 = buffer.writeu8 local readu16 = buffer.readu16 local readi16 = buffer.readi16 local writei16 = buffer.writei16 local readu32 = buffer.readu32 local writeu32 = buffer.writeu32 local band = bit32.band local bxor = bit32.bxor local bcopy = buffer.copy local bfill = buffer.fill local lshift = bit32.lshift local rshift = bit32.rshift local bswap = bit32.byteswap local D = {} -- macro block modes (libtheora's numbering) local NOMV, INTRA, INTER_MV, MV_LAST, MV_LAST2, GOLD_NOMV, GOLD_MV, FOURMV = 0, 1, 2, 3, 4, 5, 6, 7 -- reference frames of a fragment (refi) local GOLD, PREV, SELF, NONE = 0, 1, 2, 3 local FRAME_FOR_MODE = { [0] = PREV, SELF, PREV, PREV, PREV, GOLD, GOLD, PREV } -- the mode alphabets of schemes 1..7 (scheme 0 sends its own) local ALPHABETS = { { MV_LAST, MV_LAST2, INTER_MV, NOMV, INTRA, GOLD_NOMV, GOLD_MV, FOURMV }, { MV_LAST, MV_LAST2, NOMV, INTER_MV, INTRA, GOLD_NOMV, GOLD_MV, FOURMV }, { MV_LAST, INTER_MV, MV_LAST2, NOMV, INTRA, GOLD_NOMV, GOLD_MV, FOURMV }, { MV_LAST, INTER_MV, NOMV, MV_LAST2, INTRA, GOLD_NOMV, GOLD_MV, FOURMV }, { NOMV, MV_LAST, MV_LAST2, INTER_MV, INTRA, GOLD_NOMV, GOLD_MV, FOURMV }, { NOMV, GOLD_NOMV, MV_LAST, MV_LAST2, INTER_MV, INTRA, GOLD_MV, FOURMV }, { NOMV, INTRA, INTER_MV, MV_LAST, MV_LAST2, GOLD_NOMV, GOLD_MV, FOURMV }, } -- the macro block mode VLC (0, 10, 110, ..., 1111110, 1111111): by the next 7 bits, index * 8 + length local MODE_VLC = table.create(128, 0) for w = 0, 127 do local n = 0 while n < 7 and bit32.extract(w, 6 - n, 1) == 1 do n += 1 end MODE_VLC[w + 1] = n * 8 + (if n < 7 then n + 1 else 7) end -- the motion vector component VLC (Theora spec table 7.23): by the next 8 bits, (value + 32) * 16 + length local MV_VLC = table.create(256, 0) do local function put(code: number, len: number, v: number) local sh = 8 - len for i = 0, 2 ^ sh - 1 do MV_VLC[code * 2 ^ sh + i + 1] = (v + 32) * 16 + len end end put(0, 3, 0) put(1, 3, 1) put(2, 3, -1) put(6, 4, 2) put(7, 4, -2) put(8, 4, 3) put(9, 4, -3) for m = 4, 7 do put(0x28 + (m - 4) * 2, 6, m) put(0x29 + (m - 4) * 2, 6, -m) end for m = 8, 15 do put(0x60 + (m - 8) * 2, 7, m) put(0x61 + (m - 8) * 2, 7, -m) end for m = 16, 31 do put(0xE0 + (m - 16) * 2, 8, m) put(0xE1 + (m - 16) * 2, 8, -m) end end -- DCT tokens: extra bits per token local TOKEN_EXTRA = { -- [token + 1] 0, 0, 0, 2, 3, 4, 12, 3, 6, 0, 0, 0, 0, 1, 1, 1, 1, 2, 3, 4, 5, 6, 10, 1, 1, 1, 1, 1, 3, 4, 2, 3, } -- the zero-run / coefficient tokens (7..31) by token * 1024 + extra bits + 1: run * 4096 + value + 2048, where run is -- the zeros before the value (value 0: a pure zero run of run + 1) local TOKEN_VALUE = table.create(32 * 1024, 2048) for tok = 7, 31 do local ex = TOKEN_EXTRA[tok + 1] for eb = 0, 2 ^ ex - 1 do local v, r = 0, 0 if tok < 9 then r = eb -- zero runs: eb + 1 zeros elseif tok < 13 then v = if tok == 9 then 1 elseif tok == 10 then -1 elseif tok == 11 then 2 else -2 elseif tok < 17 then v = if eb == 1 then -(tok - 10) else tok - 10 elseif tok < 23 then local half = 2 ^ (ex - 1) -- the top extra bit is the sign local base = if tok == 17 then 7 elseif tok == 18 then 9 elseif tok == 19 then 13 elseif tok == 20 then 21 elseif tok == 21 then 37 else 69 v = base + eb % half if eb >= half then v = -v end elseif tok < 28 then r = tok - 22 v = if eb == 1 then -1 else 1 elseif tok == 28 then r = 6 + eb % 4 v = if eb >= 4 then -1 else 1 elseif tok == 29 then r = 10 + eb % 8 v = if eb >= 8 then -1 else 1 elseif tok == 30 then r = 1 v = 2 + eb % 2 if eb >= 2 then v = -v end else r = 2 + eb % 2 v = 2 + (eb // 2) % 2 if eb >= 4 then v = -v end end TOKEN_VALUE[tok * 1024 + eb + 1] = r * 4096 + v + 2048 end end -- natural index of zig-zag position (1-based by position + 1) local ZIGZAG = Header.ZIGZAG -- clamp to 0..255 by lookup: CLAMP[v + COFF], v in [-COFF, COFF + 255] local COFF = 70000 local CLAMP = buffer.create(2 * COFF + 512) for i = 0, 2 * COFF + 511 do buffer.writeu8(CLAMP, i, math.clamp(i - COFF, 0, 255)) end local C1, C2, C3, C4, C5, C6, C7 = 64277, 60547, 54491, 46341, 36410, 25080, 12785 export type State = { pf: number, hdec: number, vdec: number, fw: number, fh: number, pw: { number }, -- plane sizes in pixels, [pli + 1] ph: { number }, nhf: { number }, -- plane sizes in fragments nvf: { number }, foff: { number }, -- first fragment id - 1 of each plane stride: { number }, padx: { number }, pady: { number }, origin: { number }, -- byte offset of pixel (0, 0) planeSize: { number }, nfrags: number, nsbs: number, sbPlane: { number }, -- [pli + 1]: the first super block (0-based) of each plane, and [4] = nsbs sbFr: { number }, -- [sbi * 16 + quad * 4 + bi + 1]: fragment id (1-based) or 0 sbQuadValid: { boolean }, -- [sbi * 4 + quad + 1] nmbs: number, mbMode: { number }, -- [mbi + 1]: -1 outside the frame mbFr: { number }, -- [mbi * 12 + pli * 4 + bi + 1]: fragment id or 0 mapIdx: { number }, -- the valid (pli * 4 + bi) slots of a macro block for this pixel format -- per fragment [fi] coded: { number }, refi: { number }, fmode: { number }, mvx: { number }, mvy: { number }, qii: { number }, dcv: { number }, tis: { number }, last: { number }, fpos: { number }, -- byte offset of the fragment's first pixel in its plane fpl: { number }, -- plane (0..2) coef: buffer, -- i16 [(fi - 1) * 64 + zzi] clist: { { number } }, -- coded fragments per plane, coded order ncl: { number }, act: { { number } }, refs: { { buffer } }, -- [r][pli + 1] gold: number, prev: number, shown: number, -- the reference holding the last decoded picture dequant: buffer, lflim: { number }, huff: { number }, roots: { number }, blk: buffer, -- i16 x 64 work blocks tmp: buffer, bv: { number }, -- the loop filter's bounding values for the frame, [(f + 4) >> 3 + 129] keyframes: number, } -- new(info, setup) -> State function D.new(info: Header.Info, setup: Header.Setup): State local pf = info.pixelFormat local hdec = if pf % 2 == 0 then 1 else 0 local vdec = if pf < 2 then 1 else 0 local fw, fh = info.frameWidth, info.frameHeight local st: any = { pf = pf, hdec = hdec, vdec = vdec, fw = fw, fh = fh, pw = {}, ph = {}, nhf = {}, nvf = {}, foff = {}, stride = {}, padx = {}, pady = {}, origin = {}, planeSize = {}, dequant = setup.dequant, lflim = setup.lflim, huff = setup.huff, roots = setup.roots, blk = buffer.create(128), tmp = buffer.create(128), bv = table.create(257, 0), keyframes = 0, } local nfr = 0 for pli = 0, 2 do local hd, vd = if pli > 0 then hdec else 0, if pli > 0 then vdec else 0 local w, h = fw // 2 ^ hd, fh // 2 ^ vd local px, py = 16 // 2 ^ hd, 16 // 2 ^ vd st.pw[pli + 1], st.ph[pli + 1] = w, h st.nhf[pli + 1], st.nvf[pli + 1] = w // 8, h // 8 st.foff[pli + 1] = nfr nfr += (w // 8) * (h // 8) st.padx[pli + 1], st.pady[pli + 1] = px, py local stride = w + 2 * px st.stride[pli + 1] = stride st.origin[pli + 1] = py * stride + px st.planeSize[pli + 1] = stride * (h + 2 * py) end st.nfrags = nfr st.coded = table.create(nfr, 0) st.refi = table.create(nfr, NONE) st.fmode = table.create(nfr, 0) st.mvx = table.create(nfr, 0) st.mvy = table.create(nfr, 0) st.qii = table.create(nfr, 0) st.dcv = table.create(nfr, 0) st.tis = table.create(nfr, 0) st.last = table.create(nfr, 0) st.fpos = table.create(nfr, 0) st.fpl = table.create(nfr, 0) st.coef = buffer.create(nfr * 128) for pli = 0, 2 do local nh, nv = st.nhf[pli + 1], st.nvf[pli + 1] local stride, origin = st.stride[pli + 1], st.origin[pli + 1] for fy = 0, nv - 1 do for fx = 0, nh - 1 do local fi = st.foff[pli + 1] + fy * nh + fx + 1 st.fpos[fi] = origin + fy * 8 * stride + fx * 8 st.fpl[fi] = pli end end end -- super blocks: 4x4 fragments in Hilbert order (oc_sb_create_plane_mapping) local SB_MAP = { { { 0, 0 }, { 0, 1 }, { 3, 2 }, { 3, 3 } }, { { 0, 3 }, { 0, 2 }, { 3, 1 }, { 3, 0 } }, { { 1, 0 }, { 1, 3 }, { 2, 0 }, { 2, 3 } }, { { 1, 1 }, { 1, 2 }, { 2, 1 }, { 2, 2 } }, } local sbFr: { number } = {} local sbQuadValid: { boolean } = {} local sbPlane: { number } = {} local sbi = 0 for pli = 0, 2 do sbPlane[pli + 1] = sbi local nh, nv = st.nhf[pli + 1], st.nvf[pli + 1] for y = 0, nv - 1, 4 do for x = 0, nh - 1, 4 do for k = 1, 16 do sbFr[sbi * 16 + k] = 0 end for i = 0, math.min(4, nv - y) - 1 do for j = 0, math.min(4, nh - x) - 1 do local m = SB_MAP[i + 1][j + 1] sbFr[sbi * 16 + m[1] * 4 + m[2] + 1] = st.foff[pli + 1] + (y + i) * nh + x + j + 1 end end for q = 0, 3 do -- the upper left block of each quadrant: index 0, but 2 in quadrant 3 local tl = if q == 3 then 2 else 0 sbQuadValid[sbi * 4 + q + 1] = sbFr[sbi * 16 + q * 4 + tl + 1] ~= 0 end sbi += 1 end end end sbPlane[4] = sbi st.nsbs = sbi st.sbFr, st.sbQuadValid, st.sbPlane = sbFr, sbQuadValid, sbPlane -- macro blocks: 4 per luma super block (oc_mb_create_mapping) local nsbl = sbPlane[2] local nmbs = nsbl * 4 local mbMode = table.create(nmbs, 0) local mbFr = table.create(nmbs * 12, 0) local MB_MAP = { { 0, 3 }, { 1, 2 } } local nhl, nvl = st.nhf[1], st.nvf[1] local nhc = st.nhf[2] sbi = 0 for y = 0, nvl - 1, 4 do for x = 0, nhl - 1, 4 do for ymb = 0, 1 do for xmb = 0, 1 do local mbi = sbi * 4 + MB_MAP[ymb + 1][xmb + 1] local mbx, mby = x + xmb * 2, y + ymb * 2 if mbx >= nhl or mby >= nvl then mbMode[mbi + 1] = -1 else local o = mbi * 12 for i = 0, 1 do for j = 0, 1 do mbFr[o + i * 2 + j + 1] = (mby + i) * nhl + mbx + j + 1 end end for pli = 1, 2 do local base = st.foff[pli + 1] + 1 if pf == 0 then mbFr[o + pli * 4 + 1] = base + (mby // 2) * nhc + mbx // 2 elseif pf == 2 then for i = 0, 1 do mbFr[o + pli * 4 + i * 2 + 1] = base + (mby + i) * nhc + mbx // 2 end else for k = 0, 3 do mbFr[o + pli * 4 + k + 1] = mbFr[o + k + 1] + st.foff[pli + 1] end end end end end end sbi += 1 end end st.nmbs, st.mbMode, st.mbFr = nmbs, mbMode, mbFr st.mapIdx = if pf == 0 then { 0, 1, 2, 3, 4, 8 } elseif pf == 2 then { 0, 1, 2, 3, 4, 6, 8, 10 } else { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 } st.clist = { table.create(st.nhf[1] * st.nvf[1], 0), table.create(st.nhf[2] * st.nvf[2], 0), table.create(st.nhf[3] * st.nvf[3], 0) } st.act = { table.create(st.nhf[1] * st.nvf[1], 0), table.create(st.nhf[2] * st.nvf[2], 0), table.create(st.nhf[3] * st.nvf[3], 0) } st.ncl = { 0, 0, 0 } -- three reference frames, grey until the first keyframe st.refs = {} for r = 1, 3 do local planes = {} for pli = 1, 3 do local b = buffer.create(st.planeSize[pli]) bfill(b, 0, 128) planes[pli] = b end st.refs[r] = planes end st.gold, st.prev, st.shown = 1, 1, 1 return st :: State end -- ------------------------------------------------------------------------------------------------ reconstruction -- the 8-point IDCT of libtheora's idct8 (the spec's), on 8 values; returns the 8 outputs local function idct8(x0: number, x1: number, x2: number, x3: number, x4: number, x5: number, x6: number, x7: number): (number, number, number, number, number, number, number, number) local t0 = (C4 * (x0 + x4)) // 65536 local t1 = (C4 * (x0 - x4)) // 65536 local t2 = (C6 * x2) // 65536 - (C2 * x6) // 65536 local t3 = (C2 * x2) // 65536 + (C6 * x6) // 65536 local t4 = (C7 * x1) // 65536 - (C1 * x7) // 65536 local t5 = (C3 * x5) // 65536 - (C5 * x3) // 65536 local t6 = (C5 * x5) // 65536 + (C3 * x3) // 65536 local t7 = (C1 * x1) // 65536 + (C7 * x7) // 65536 local r = t4 + t5 t5 = (C4 * (t4 - t5)) // 65536 t4 = r r = t7 + t6 t6 = (C4 * (t7 - t6)) // 65536 t7 = r r = t0 + t3 t3 = t0 - t3 t0 = r r = t1 + t2 t2 = t1 - t2 t1 = r r = t6 + t5 t5 = t6 - t5 t6 = r return t0 + t7, t1 + t6, t2 + t5, t3 + t4, t3 - t4, t2 - t5, t1 - t6, t0 - t7 end -- the first IDCT pass: the rows of blk (i16, natural order) into the columns of tmp (i16: like libtheora, the -- dequantised coefficients and these intermediate values are 16-bit, which also bounds every residual) local function idctRows(blk: buffer, tmp: buffer) for i = 0, 7 do local o = i * 16 local x0, x1, x2, x3 = readi16(blk, o), readi16(blk, o + 2), readi16(blk, o + 4), readi16(blk, o + 6) local x4, x5, x6, x7 = readi16(blk, o + 8), readi16(blk, o + 10), readi16(blk, o + 12), readi16(blk, o + 14) local c = i * 2 if x1 == 0 and x2 == 0 and x3 == 0 and x4 == 0 and x5 == 0 and x6 == 0 and x7 == 0 then local y = (C4 * x0) // 65536 writei16(tmp, c, y) writei16(tmp, c + 16, y) writei16(tmp, c + 32, y) writei16(tmp, c + 48, y) writei16(tmp, c + 64, y) writei16(tmp, c + 80, y) writei16(tmp, c + 96, y) writei16(tmp, c + 112, y) else local y0, y1, y2, y3, y4, y5, y6, y7 = idct8(x0, x1, x2, x3, x4, x5, x6, x7) writei16(tmp, c, y0) writei16(tmp, c + 16, y1) writei16(tmp, c + 32, y2) writei16(tmp, c + 48, y3) writei16(tmp, c + 64, y4) writei16(tmp, c + 80, y5) writei16(tmp, c + 96, y6) writei16(tmp, c + 112, y7) end end end -- the second pass, added to the prediction already in dst: column c of the block is row c of tmp local function idctAdd(tmp: buffer, dst: buffer, pos: number, stride: number) for c = 0, 7 do local o = c * 16 local y0, y1, y2, y3, y4, y5, y6, y7 = idct8(readi16(tmp, o), readi16(tmp, o + 2), readi16(tmp, o + 4), readi16(tmp, o + 6), readi16(tmp, o + 8), readi16(tmp, o + 10), readi16(tmp, o + 12), readi16(tmp, o + 14)) local p = pos + c writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y0 + 8) // 16 + COFF)) p += stride writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y1 + 8) // 16 + COFF)) p += stride writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y2 + 8) // 16 + COFF)) p += stride writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y3 + 8) // 16 + COFF)) p += stride writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y4 + 8) // 16 + COFF)) p += stride writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y5 + 8) // 16 + COFF)) p += stride writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y6 + 8) // 16 + COFF)) p += stride writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y7 + 8) // 16 + COFF)) end end local function wrap16(v: number): number return (v + 32768) % 65536 - 32768 end -- the motion vector offsets of one component: integer part (toward zero) and the second sample's extra step (away -- from zero) when there is a fraction. q: quarter-pel (subsampled direction) or half-pel local function mvSplit(d: number, q: boolean): (number, number) local div = if q then 4 else 2 local a = if d < 0 then -((-d) // div) else d // div local frac = d - a * div local b = if frac > 0 then 1 elseif frac < 0 then -1 else 0 return a, b end -- reconstruct one coded fragment into dst (the SELF reference planes): the prediction (128 for intra blocks, the -- reference block or the average of two for inter ones) goes to dst first, then the residual is added local function reconFrag(st: State, fi: number, qis: { number }, dstPlanes: { buffer }) local pli = st.fpl[fi] local mode = st.fmode[fi] local qti = if mode == INTRA then 0 else 1 local dq = st.dequant local dcq = readu16(dq, (((qis[1] * 3 + pli) * 2 + qti) * 64) * 2) local dc = st.dcv[fi] local last = st.last[fi] local stride = st.stride[pli + 1] local dst = dstPlanes[pli + 1] local pos = st.fpos[fi] local ri = st.refi[fi] local fv = 0 if last == 0 then fv = wrap16((dc * dcq + 15) // 32) if ri == SELF then local v = readu8(CLAMP, fv + 128 + COFF) for y = 0, 7 do bfill(dst, pos + y * stride, v, 8) end return end else local blk = st.blk bfill(blk, 0, 0, 128) writei16(blk, 0, wrap16(dc * dcq)) local coef = st.coef local co = (fi - 1) * 128 local ao = (((qis[st.qii[fi] + 1] * 3 + pli) * 2 + qti) * 64) * 2 for z = 1, last do local c = readi16(coef, co + z * 2) if c ~= 0 then writei16(coef, co + z * 2, 0) writei16(blk, ZIGZAG[z + 1] * 2, wrap16(c * readu16(dq, ao + z * 2))) end end st.last[fi] = 0 idctRows(blk, st.tmp) end -- the prediction if ri == SELF then for y = 0, 7 do bfill(dst, pos + y * stride, 128, 8) end else local ref = st.refs[if ri == GOLD then st.gold else st.prev][pli + 1] local mx, mx2 = mvSplit(st.mvx[fi], pli > 0 and st.hdec == 1) local my, my2 = mvSplit(st.mvy[fi], pli > 0 and st.vdec == 1) local s1 = pos + my * stride + mx if mx2 ~= 0 or my2 ~= 0 then -- (a + b) >> 1 per byte, four at a time local s2 = s1 + my2 * stride + mx2 for y = 0, 7 do local d, a, b = pos + y * stride, s1 + y * stride, s2 + y * stride local u: number = readu32(ref, a) local v: number = readu32(ref, b) writeu32(dst, d, band(u, v) + rshift(band(bxor(u, v), 0xFEFEFEFE), 1)) local u2: number = readu32(ref, a + 4) local v2: number = readu32(ref, b + 4) writeu32(dst, d + 4, band(u2, v2) + rshift(band(bxor(u2, v2), 0xFEFEFEFE), 1)) end else for y = 0, 7 do local d, a = pos + y * stride, s1 + y * stride writeu32(dst, d, readu32(ref, a)) writeu32(dst, d + 4, readu32(ref, a + 4)) end end end -- the residual if last ~= 0 then idctAdd(st.tmp, dst, pos, stride) elseif fv ~= 0 then for y = 0, 7 do local d = pos + y * stride for x = d, d + 7 do writeu8(dst, x, readu8(CLAMP, readu8(dst, x) + fv + COFF)) end end end end -- ------------------------------------------------------------------------------------------------ loop filter local function filterH(b: buffer, p: number, stride: number, bv: { number }) p -= 2 for _ = 0, 7 do local p0, p1, p2, p3 = readu8(b, p), readu8(b, p + 1), readu8(b, p + 2), readu8(b, p + 3) local f = bv[(p0 - p3 + 3 * (p2 - p1) + 4) // 8 + 129] writeu8(b, p + 1, readu8(CLAMP, p1 + f + COFF)) writeu8(b, p + 2, readu8(CLAMP, p2 - f + COFF)) p += stride end end local function filterV(b: buffer, p: number, stride: number, bv: { number }) local q0, q1, q2 = p - 2 * stride, p - stride, p + stride for x = 0, 7 do local p0, p1, p2, p3 = readu8(b, q0 + x), readu8(b, q1 + x), readu8(b, p + x), readu8(b, q2 + x) local f = bv[(p0 - p3 + 3 * (p2 - p1) + 4) // 8 + 129] writeu8(b, q1 + x, readu8(CLAMP, p1 + f + COFF)) writeu8(b, p + x, readu8(CLAMP, p2 - f + COFF)) end end local function loopFilter(st: State, planes: { buffer }, flimit: number) local bv = st.bv for i = -128, 128 do local a = math.abs(i) local v = 0 if a < flimit then v = i elseif a < 2 * flimit then v = if i > 0 then 2 * flimit - a else a - 2 * flimit end -- libtheora's table stops at index -127 (127 - i - flimit >= 0) if i < -127 then v = 0 end bv[i + 129] = v end local coded = st.coded for pli = 0, 2 do local b = planes[pli + 1] local nh, nv = st.nhf[pli + 1], st.nvf[pli + 1] local stride = st.stride[pli + 1] local base = st.foff[pli + 1] local fpos = st.fpos for fy = 0, nv - 1 do local row = base + fy * nh for fx = 0, nh - 1 do local fi = row + fx + 1 if coded[fi] ~= 0 then local p = fpos[fi] if fx > 0 then filterH(b, p, stride, bv) end if fy > 0 then filterV(b, p, stride, bv) end if fx + 1 < nh and coded[fi + 1] == 0 then filterH(b, p + 8, stride, bv) end if fy + 1 < nv and coded[fi + nh] == 0 then filterV(b, p + 8 * stride, stride, bv) end end end end end end -- extend each plane's edge pixels into its padding (for unrestricted motion vectors) local function borders(st: State, planes: { buffer }) for pli = 1, 3 do local b = planes[pli] local stride, px, py = st.stride[pli], st.padx[pli], st.pady[pli] local w, h = st.pw[pli], st.ph[pli] for y = 0, h - 1 do local o = (y + py) * stride bfill(b, o, readu8(b, o + px), px) bfill(b, o + px + w, readu8(b, o + px + w - 1), px) end local top, bot = py * stride, (py + h - 1) * stride for k = 1, py do bcopy(b, top - k * stride, b, top, stride) bcopy(b, bot + k * stride, b, bot, stride) end end end -- DC prediction (raster order per plane): each coded block's DC adds a prediction from its left / upper neighbours -- coded from the same reference frame (or the last such DC in the plane) local function dcPredict(st: State) local coded, refi, dcv = st.coded, st.refi, st.dcv for pli = 0, 2 do local nh, nv = st.nhf[pli + 1], st.nvf[pli + 1] local base = st.foff[pli + 1] local pl0, pl1, pl2 = 0, 0, 0 -- the last DC of each reference frame (GOLD, PREV, SELF) for fy = 0, nv - 1 do local row = base + fy * nh local lref, ulref, uref = -1, -1, -1 if fy > 0 then uref = refi[row - nh + 1] end for fx = 0, nh - 1 do local fi = row + fx + 1 local urref = -1 if fy > 0 and fx + 1 < nh then urref = refi[fi - nh + 1] end if coded[fi] ~= 0 then local r = refi[fi] local pred: number if fy == 0 then pred = if r == 0 then pl0 elseif r == 1 then pl1 else pl2 else local m = (if lref == r then 1 else 0) + (if ulref == r then 2 else 0) + (if uref == r then 4 else 0) + (if urref == r then 8 else 0) if m == 0 then pred = if r == 0 then pl0 elseif r == 1 then pl1 else pl2 elseif m == 1 or m == 3 then pred = dcv[fi - 1] elseif m == 2 then pred = dcv[fi - nh - 1] elseif m == 4 or m == 6 or m == 12 then pred = dcv[fi - nh] elseif m == 5 then local s = dcv[fi - 1] + dcv[fi - nh] pred = if s < 0 then -((-s) // 2) else s // 2 elseif m == 8 then pred = dcv[fi - nh + 1] elseif m == 9 or m == 11 or m == 13 then local s = 75 * dcv[fi - 1] + 53 * dcv[fi - nh + 1] pred = if s < 0 then -((-s) // 128) else s // 128 elseif m == 10 then local s = dcv[fi - nh - 1] + dcv[fi - nh + 1] pred = if s < 0 then -((-s) // 2) else s // 2 elseif m == 14 then local s = 3 * (dcv[fi - nh - 1] + dcv[fi - nh + 1]) + 10 * dcv[fi - nh] pred = if s < 0 then -((-s) // 16) else s // 16 else local p0, p1, p2 = dcv[fi - 1], dcv[fi - nh - 1], dcv[fi - nh] local s = 29 * (p0 + p2) - 26 * p1 pred = if s < 0 then -((-s) // 32) else s // 32 if math.abs(pred - p2) > 128 then pred = p2 elseif math.abs(pred - p0) > 128 then pred = p0 elseif math.abs(pred - p1) > 128 then pred = p1 end end end local v = wrap16(dcv[fi] + pred) dcv[fi] = v if r == 0 then pl0 = v elseif r == 1 then pl1 = v else pl2 = v end lref = r else lref = -1 end ulref = uref uref = urref end end end end -- ------------------------------------------------------------------------------------------------ frame decode -- decode(st, data, off, len) -> kind ("key" | "inter" | "dup") | nil, message. The picture is then in -- st.refs[st.shown]. function D.decode(st: State, data: buffer, off: number, len: number): (string?, string?) if len <= 0 then return "dup", nil end -- a zero-padded copy: reads past the end give zero bits, every read site clamps pos to the end first local bb = buffer.create(len + 24) bcopy(bb, 0, data, off, len) local maxp = len * 8 local pos = 0 local function bits(n: number): number if pos > maxp then pos = maxp end local w = rshift(lshift(bswap(readu32(bb, rshift(pos, 3))), band(pos, 7)), 32 - n) pos += n return w end local huff = st.huff local function sbRun(): number if bits(1) == 0 then return 1 elseif bits(1) == 0 then return 2 + bits(1) elseif bits(1) == 0 then return 4 + bits(1) elseif bits(1) == 0 then return 6 + bits(2) elseif bits(1) == 0 then return 10 + bits(3) elseif bits(1) == 0 then return 18 + bits(4) end return 34 + bits(12) end local function blockRun(): number if bits(1) == 0 then return 1 + bits(1) elseif bits(1) == 0 then return 3 + bits(1) elseif bits(1) == 0 then return 5 + bits(1) elseif bits(1) == 0 then return 7 + bits(2) elseif bits(1) == 0 then return 11 + bits(2) end return 15 + bits(4) end -- frame header if bits(1) ~= 0 then return nil, "not a data packet" end local intra = bits(1) == 0 local qis = { bits(6) } if bits(1) == 1 then table.insert(qis, bits(6)) if bits(1) == 1 then table.insert(qis, bits(6)) end end if intra then if bits(3) ~= 0 then return nil, "unsupported: reserved keyframe bits set" end end local coded, refi, fmode, dcv, tis, qii = st.coded, st.refi, st.fmode, st.dcv, st.tis, st.qii local mvx, mvy = st.mvx, st.mvy local sbFr, sbQuadValid, sbPlane = st.sbFr, st.sbQuadValid, st.sbPlane local clist, ncl = st.clist, st.ncl local mbMode = st.mbMode local nsbs = st.nsbs local total = 0 if intra then for pli = 0, 2 do local list, n = clist[pli + 1], 0 for sbi = sbPlane[pli + 1], sbPlane[pli + 2] - 1 do for q = 0, 3 do if sbQuadValid[sbi * 4 + q + 1] then for bi = 0, 3 do local fi = sbFr[sbi * 16 + q * 4 + bi + 1] if fi ~= 0 then coded[fi] = 1 refi[fi] = SELF fmode[fi] = INTRA n += 1 list[n] = fi end end end end end ncl[pli + 1] = n total += n end else -- partially coded super blocks, then fully coded ones among the rest local partial, full = table.create(nsbs, false), table.create(nsbs, false) local npartial = 0 local flag = bits(1) local sbi = 0 while sbi < nsbs do local run = sbRun() local fullRun = run >= 4129 repeat partial[sbi + 1] = flag == 1 npartial += flag sbi += 1 run -= 1 until run <= 0 or sbi >= nsbs if fullRun and sbi < nsbs then flag = bits(1) else flag = 1 - flag end end if npartial < nsbs then sbi = 0 while partial[sbi + 1] do sbi += 1 end flag = bits(1) repeat local run = sbRun() local fullRun = run >= 4129 while sbi < nsbs do if not partial[sbi + 1] then if run <= 0 then break end run -= 1 full[sbi + 1] = flag == 1 end sbi += 1 end if fullRun and sbi < nsbs then flag = bits(1) else flag = 1 - flag end until sbi >= nsbs end -- block flags local bflag = 0 if npartial > 0 then bflag = 1 - bits(1) end local run = 0 for pli = 0, 2 do local list, n = clist[pli + 1], 0 for s = sbPlane[pli + 1], sbPlane[pli + 2] - 1 do local isFull, isPartial = full[s + 1], partial[s + 1] for q = 0, 3 do if sbQuadValid[s * 4 + q + 1] then local quadCoded = 0 for bi = 0, 3 do local fi = sbFr[s * 16 + q * 4 + bi + 1] if fi ~= 0 then local c = 0 if isFull then c = 1 elseif isPartial then if run <= 0 then run = blockRun() bflag = 1 - bflag end run -= 1 c = bflag end coded[fi] = c refi[fi] = NONE if c == 1 then n += 1 list[n] = fi quadCoded = 1 end end end if pli == 0 then mbMode[s * 4 + q + 1] = quadCoded end end end end ncl[pli + 1] = n total += n end if total == 0 then return "dup", nil end -- macro block modes local scheme = bits(3) local alphabet: { number } if scheme == 0 then alphabet = table.create(8, NOMV) for mi = 1, 8 do alphabet[bits(3) + 1] = ALPHABETS[7][mi] end else alphabet = ALPHABETS[scheme] end for mbi = 1, st.nmbs do if mbMode[mbi] > 0 then local idx: number if scheme == 7 then idx = bits(3) else local e = MODE_VLC[bits(7) + 1] pos -= 7 - e % 8 idx = e // 8 end mbMode[mbi] = alphabet[idx + 1] end end -- motion vectors local clc = bits(1) == 1 local function mv(): number if clc then local v = bits(6) return if v % 2 == 1 then -(v // 2) else v // 2 end local e = MV_VLC[bits(8) + 1] pos -= 8 - e % 16 return e // 16 - 32 end local mbFr, mapIdx = st.mbFr, st.mapIdx local nmap = #mapIdx local lastX, lastY, priorX, priorY = 0, 0, 0, 0 local lx, ly = { 0, 0, 0, 0 }, { 0, 0, 0, 0 } local cx, cy = { 0, 0, 0, 0 }, { 0, 0, 0, 0 } local pf = st.pf for mbi = 0, st.nmbs - 1 do local mode = mbMode[mbi + 1] if mode >= 0 then local o = mbi * 12 if mode == FOURMV then priorX, priorY = lastX, lastY for bi = 1, 4 do local fi = mbFr[o + bi] if coded[fi] ~= 0 then refi[fi] = PREV fmode[fi] = FOURMV local x = mv() local y = mv() lx[bi], ly[bi] = x, y lastX, lastY = x, y mvx[fi], mvy[fi] = x, y else lx[bi], ly[bi] = 0, 0 end end if pf == 0 then local sx, sy = lx[1] + lx[2] + lx[3] + lx[4], ly[1] + ly[2] + ly[3] + ly[4] cx[1] = (sx + 2 - (if sx < 0 then 1 else 0)) // 4 cy[1] = (sy + 2 - (if sy < 0 then 1 else 0)) // 4 elseif pf == 2 then local sx, sy = lx[1] + lx[2], ly[1] + ly[2] cx[1] = (sx + 1 - (if sx < 0 then 1 else 0)) // 2 cy[1] = (sy + 1 - (if sy < 0 then 1 else 0)) // 2 sx, sy = lx[3] + lx[4], ly[3] + ly[4] cx[3] = (sx + 1 - (if sx < 0 then 1 else 0)) // 2 cy[3] = (sy + 1 - (if sy < 0 then 1 else 0)) // 2 else for k = 1, 4 do cx[k], cy[k] = lx[k], ly[k] end end for m = 5, nmap do local mi = mapIdx[m] local fi = mbFr[o + mi + 1] if coded[fi] ~= 0 then local bi = mi % 4 + 1 refi[fi] = PREV fmode[fi] = FOURMV mvx[fi], mvy[fi] = cx[bi], cy[bi] end end else local x, y = 0, 0 if mode == INTER_MV then priorX, priorY = lastX, lastY x = mv() y = mv() lastX, lastY = x, y elseif mode == MV_LAST then x, y = lastX, lastY elseif mode == MV_LAST2 then x, y = priorX, priorY priorX, priorY = lastX, lastY lastX, lastY = x, y elseif mode == GOLD_MV then x = mv() y = mv() end local r = FRAME_FOR_MODE[mode] for m = 1, nmap do local fi = mbFr[o + mapIdx[m] + 1] if coded[fi] ~= 0 then refi[fi] = r fmode[fi] = mode mvx[fi], mvy[fi] = x, y end end end end end end -- block qi indices (over every coded fragment, planes in order) local nqis = #qis for pli = 1, 3 do local list = clist[pli] for k = 1, ncl[pli] do local fi = list[k] qii[fi] = 0 dcv[fi] = 0 tis[fi] = 0 end end if nqis > 1 then local all = table.create(total, 0) local n = 0 for pli = 1, 3 do local list = clist[pli] for k = 1, ncl[pli] do n += 1 all[n] = list[k] end end local flag = bits(1) local nqi1 = 0 local k = 1 while k <= total do local run = sbRun() local fullRun = run >= 4129 repeat qii[all[k]] = flag nqi1 += flag k += 1 run -= 1 until run <= 0 or k > total if fullRun and k <= total then flag = bits(1) else flag = 1 - flag end end if nqis == 3 and nqi1 > 0 then k = 1 while qii[all[k]] == 0 do k += 1 end flag = bits(1) repeat local run = sbRun() local fullRun = run >= 4129 while k <= total do local fi = all[k] if qii[fi] ~= 0 then if run <= 0 then break end run -= 1 qii[fi] += flag end k += 1 end if fullRun and k <= total then flag = bits(1) else flag = 1 - flag end until k > total end end -- DCT tokens: coefficient by coefficient, plane by plane, block by block in coded order; an EOB run ends the -- next blocks that still wait for a token at their position local coef, last = st.coef, st.last local act = st.act local nact = { 0, 0, 0 } for pli = 1, 3 do local src, dstl = clist[pli], act[pli] for k = 1, ncl[pli] do dstl[k] = src[k] end nact[pli] = ncl[pli] end local roots = st.roots local hy: number = bits(4) local hc: number = bits(4) local eobs = 0 for zzi = 0, 63 do if zzi == 1 then hy = bits(4) hc = bits(4) end local grp: number = if zzi == 0 then 0 elseif zzi < 6 then 16 elseif zzi < 15 then 32 elseif zzi < 28 then 48 else 64 for pli = 1, 3 do local sel: number = if pli == 1 then hy else hc local root = roots[sel + grp + 1] local list = act[pli] local n = nact[pli] local w = 0 for k = 1, n do local fi = list[k] local t = tis[fi] if t == zzi then if eobs > 0 then eobs -= 1 t = 64 else -- the token (inlined: the hottest loop), then its extra bits if pos > maxp then pos = maxp end local o, tok = root, 0 while true do local nb = huff[o] local e = huff[o + 1 + rshift(lshift(bswap(readu32(bb, rshift(pos, 3))), band(pos, 7)), 32 - nb)] if e >= 0 then pos += rshift(e, 6) tok = band(e, 63) break end pos += nb o = -e end local ex = TOKEN_EXTRA[tok + 1] local eb = 0 if ex > 0 then eb = rshift(lshift(bswap(readu32(bb, rshift(pos, 3))), band(pos, 7)), 32 - ex) pos += ex end if tok < 7 then local run: number if tok < 3 then run = tok + 1 elseif tok == 3 then run = 4 + eb elseif tok == 4 then run = 8 + eb elseif tok == 5 then run = 16 + eb else run = if eb == 0 then 2 ^ 31 else eb end eobs = run - 1 t = 64 else -- zero runs and coefficients: run * 4096 + value + 2048 (value 0: a zero run) local e = TOKEN_VALUE[tok * 1024 + eb + 1] local p = zzi + rshift(e, 12) local v = band(e, 4095) - 2048 if v ~= 0 then if p == 0 then dcv[fi] = v elseif p < 64 then writei16(coef, (fi - 1) * 128 + p * 2, v) last[fi] = p end end t = p + 1 end end tis[fi] = t end if t < 64 then w += 1 list[w] = fi end end nact[pli] = w end end dcPredict(st) -- reconstruction into a free reference buffer local self = 1 while self == st.gold or self == st.prev do self += 1 end local dst = st.refs[self] if not intra then local src = st.refs[st.prev] for pli = 1, 3 do bcopy(dst[pli], 0, src[pli], 0, st.planeSize[pli]) end end for pli = 1, 3 do local list = clist[pli] for k = 1, ncl[pli] do reconFrag(st, list[k], qis, dst) end end local flimit = st.lflim[qis[1] + 1] if flimit ~= 0 then loopFilter(st, dst, flimit) end borders(st, dst) if intra then st.gold, st.prev = self, self st.keyframes += 1 else st.prev = self end st.shown = self return if intra then "key" else "inter", nil end -- ------------------------------------------------------------------------------------------------ output -- the picture region of the shown frame as top-down planes: plane(st, pli, x0, y0, w, h) copies a w x h window whose -- top-left corner is (x0, y0) counted from the top of the plane function D.plane(st: State, pli: number, x0: number, y0: number, w: number, h: number): buffer local src = st.refs[st.shown][pli + 1] local stride, origin, ph = st.stride[pli + 1], st.origin[pli + 1], st.ph[pli + 1] local out = buffer.create(w * h) for y = 0, h - 1 do local row = ph - 1 - (y0 + y) -- Theora rows count from the bottom bcopy(out, y * w, src, origin + row * stride + x0, w) end return out end -- downsample(src, cw, ch, hdec, dst, off, ow, oh): 4:2:2 (hdec 1: rows averaged in pairs) or 4:4:4 (hdec 0: 2x2 -- averages) chroma of cw x ch into ow x oh 4:2:0 chroma at dst[off] function D.downsample(src: buffer, cw: number, ch: number, hdec: number, dst: buffer, off: number, ow: number, oh: number) for r = 0, oh - 1 do local r0 = math.min(2 * r, ch - 1) local r1 = math.min(2 * r + 1, ch - 1) local a, b = r0 * cw, r1 * cw local o = off + r * ow if hdec == 1 then for c = 0, math.min(ow, cw) - 1 do writeu8(dst, o + c, (readu8(src, a + c) + readu8(src, b + c) + 1) // 2) end else for c = 0, ow - 1 do local c0 = math.min(2 * c, cw - 1) local c1 = math.min(2 * c + 1, cw - 1) writeu8(dst, o + c, (readu8(src, a + c0) + readu8(src, a + c1) + readu8(src, b + c0) + readu8(src, b + c1) + 2) // 4) end end end end return D