diff --git a/src/Formats/codecs/H264/Bitstream.luau b/src/Formats/codecs/H264/Bitstream.luau index 9c8d02e..acdeda9 100644 --- a/src/Formats/codecs/H264/Bitstream.luau +++ b/src/Formats/codecs/H264/Bitstream.luau @@ -8,8 +8,8 @@ -- read is range-checked), and callers check `r.pos > r.size` once per syntax structure. local Bitstream = {} -local readu8, readu32 = buffer.readu8, buffer.readu32 -local band, lshift, rshift, bor, countlz, byteswap = bit32.band, bit32.lshift, bit32.rshift, bit32.bor, bit32.countlz, bit32.byteswap +local readu8 = buffer.readu8 +local band, lshift = bit32.band, bit32.lshift export type Reader = { buf: buffer, -- the RBSP (emulation prevention removed) followed by 8 zero bytes @@ -179,61 +179,92 @@ function Bitstream.reader(buf: buffer, off: number, len: number, skip: number): end -- ------------------------------------------------------------------------------------------------ bits --- peek32(r) -> the next 32 bits (zeros past the end) -local function peek32(r: Reader): number - local pos = r.pos - local p = rshift(pos, 3) - if p + 5 > r.n then +-- Plain arithmetic instead of bit32 (LuaJIT runs bit32 through compat wrappers whose sign fix-ups split traces). +local P2 = table.create(33, 1) -- P2[k + 1] = 2^k +for k = 0, 32 do + P2[k + 1] = 2 ^ k +end +Bitstream.P2 = P2 +local LZ8 = table.create(256, 0) -- LZ8[x + 1] = leading zero bits of the byte x (8 for 0) +for x = 0, 255 do + local n, v = 0, x + while n < 8 and v < 128 do + v *= 2 + n += 1 + end + LZ8[x + 1] = n +end +Bitstream.LZ8 = LZ8 + +-- clz32(v) -> leading zero bits of a 32-bit value +local function clz32(v: number): number + if v >= 16777216 then + return LZ8[v // 16777216 + 1] + elseif v >= 65536 then + return 8 + LZ8[v // 65536 + 1] + elseif v >= 256 then + return 16 + LZ8[v // 256 + 1] + end + return 24 + LZ8[v + 1] +end +Bitstream.clz32 = clz32 + +-- peekAt(b, n, pos) -> the 32 bits at bit position pos of buffer b (n bytes), zeros past the end +local function peekAt(b: buffer, n: number, pos: number): number + local p = pos // 8 + if p + 5 > n then return 0 end - local b = r.buf - local s = band(pos, 7) - local w = byteswap(readu32(b, p)) + local s = pos - p * 8 + local w = readu8(b, p) * 16777216 + readu8(b, p + 1) * 65536 + readu8(b, p + 2) * 256 + readu8(b, p + 3) if s == 0 then return w end - return bor(lshift(w, s), rshift(readu8(b, p + 4), 8 - s)) + return (w * P2[s + 1]) % 4294967296 + readu8(b, p + 4) // P2[9 - s] +end +Bitstream.peekAt = peekAt + +-- peek32(r) -> the next 32 bits (zeros past the end) +local function peek32(r: Reader): number + return peekAt(r.buf, r.n, r.pos) end Bitstream.peek32 = peek32 -- u(r, n) -> n bits (n 1..32) as an unsigned number function Bitstream.u(r: Reader, n: number): number - local v = peek32(r) + local v = peekAt(r.buf, r.n, r.pos) r.pos += n - if n >= 32 then - return v - end - return rshift(v, 32 - n) + return v // P2[33 - n] end -- u1(r) -> one bit function Bitstream.u1(r: Reader): number local pos = r.pos r.pos = pos + 1 - local p = rshift(pos, 3) + local p = pos // 8 if p >= r.n then return 0 end - return band(rshift(readu8(r.buf, p), 7 - band(pos, 7)), 1) + return (readu8(r.buf, p) // P2[8 - (pos - p * 8)]) % 2 end -- ue(r) -> ue(v); a code with more than 31 leading zeros returns 2^32 (out of range for every syntax element) local function ue(r: Reader): number - local v = peek32(r) + local v = peekAt(r.buf, r.n, r.pos) if v == 0 then r.pos += 32 return 4294967296 end - local lz = countlz(v) + local lz = clz32(v) if lz < 16 then local n = 2 * lz + 1 r.pos += n - return rshift(v, 32 - n) - 1 + return v // P2[33 - n] - 1 end r.pos += lz - v = peek32(r) + v = peekAt(r.buf, r.n, r.pos) r.pos += lz + 1 - return rshift(v, 31 - lz) - 1 + return v // P2[32 - lz] - 1 end Bitstream.ue = ue diff --git a/src/Formats/codecs/H264/Cabac.luau b/src/Formats/codecs/H264/Cabac.luau index dc63209..ceb74d5 100644 --- a/src/Formats/codecs/H264/Cabac.luau +++ b/src/Formats/codecs/H264/Cabac.luau @@ -12,6 +12,7 @@ local Tables = require("@formats/codecs/H264/Tables") local Mb = require("@formats/codecs/H264/Mb") local readu8 = buffer.readu8 +local min = math.min local K_I4, K_I8, K_I16, K_PCM, K_P, K_PSKIP, K_B, K_BSKIP, K_BDIRECT = Mb.K_I4, Mb.K_I8, Mb.K_I16, Mb.K_PCM, Mb.K_P, Mb.K_PSKIP, Mb.K_B, Mb.K_BSKIP, Mb.K_BDIRECT local BLK_X, BLK_Y = Mb.BLK_X, Mb.BLK_Y @@ -36,11 +37,18 @@ for r = 1, 511 do end -- state per context: pStateIdx * 2 + valMPS, at ST[ctxIdx + 1] local ST = table.create(460, 0) --- per pState: next state after LPS / MPS -local NEXT_LPS, NEXT_MPS = table.create(64, 0), table.create(64, 0) -for p = 0, 63 do - NEXT_LPS[p + 1] = TRANS[p * 2 + 1] - NEXT_MPS[p + 1] = TRANS[p * 2 + 2] +-- per packed state s (pStateIdx * 2 + valMPS) and LPS bit: the next state and the bin; rangeTabLPS by packed state +local NEXTS, BINS = table.create(256, 0), table.create(256, 0) +local LPSR = table.create(512, 0) +for st = 0, 127 do + local p, mps = st // 2, st % 2 + NEXTS[st * 2 + 1] = TRANS[p * 2 + 2] * 2 + mps + BINS[st * 2 + 1] = mps + NEXTS[st * 2 + 2] = TRANS[p * 2 + 1] * 2 + (if p == 0 then 1 - mps else mps) + BINS[st * 2 + 2] = 1 - mps + for q = 0, 3 do + LPSR[st * 4 + q + 1] = RANGE_LPS[p * 4 + q + 1] + end end -- the engine (one slice at a time) @@ -49,58 +57,42 @@ local epos, elimit = 0, 0 local erange, elow, enb = 510, 0, 0 local function refill() - while enb < 8 do - local b = 0 - if epos < elimit then - b = readu8(ebuf, epos) - end - epos += 1 - elow = elow * 256 + b - enb += 8 + local b = 0 + if epos < elimit then + b = readu8(ebuf, epos) end + epos += 1 + elow = elow * 256 + b + enb += 8 end +-- decision(ctx) -> bin (9.3.3.2.1), branch-free apart from the byte refill: the LPS test is min(1, low // scaled) +-- (low < 2.5 * scaled always), the state step and the bin come from tables local function decision(ctx: number): number local s = ST[ctx + 1] - local p = s // 2 - local mps = s % 2 local range = erange - local lps = RANGE_LPS[p * 4 + (range // 64) % 4 + 1] + local lps = LPSR[s * 4 + (range // 64) % 4 + 1] local r = range - lps local scaled = r * POW2[enb + 1] - local bin - if elow >= scaled then - elow -= scaled - bin = 1 - mps - if p == 0 then - mps = 1 - mps - end - ST[ctx + 1] = NEXT_LPS[p + 1] * 2 + mps - r = lps - else - bin = mps - ST[ctx + 1] = NEXT_MPS[p + 1] * 2 + mps + local bit = min(1, elow // scaled) + elow -= bit * scaled + r += bit * (lps - r) + local k = s * 2 + bit + 1 + ST[ctx + 1] = NEXTS[k] + local sh = NORM[r + 1] + erange = r * POW2[sh + 1] + enb -= sh + if enb < 8 then + refill() end - if r < 256 then - local sh = NORM[r + 1] - r *= POW2[sh + 1] - enb -= sh - if enb < 8 then - refill() - end - end - erange = r - return bin + return BINS[k] end local function bypass(): number enb -= 1 local scaled = erange * POW2[enb + 1] - local bin = 0 - if elow >= scaled then - elow -= scaled - bin = 1 - end + local bin = elow // scaled + elow -= bin * scaled if enb < 8 then refill() end @@ -131,6 +123,7 @@ local function engineInit(b: buffer, p: number, limit: number) elow, enb = 0, -9 refill() refill() + refill() erange = 510 end @@ -165,58 +158,79 @@ local SIGPOS = table.create(64, 0) -- block(cat, out, base, mul, div) -> number of coefficients (cat 0..5); coded_block_flag is decoded by the caller. -- Positions: cat 0 / 2 zig-zag, 1 / 4 zig-zag from 1, 3 raster 0..3, 5 the 8x8 zig-zag +local SCAN = {} +do + local ac = table.create(15, 0) + for i = 1, 15 do + ac[i] = ZZ4[i + 1] + end + SCAN[1], SCAN[2], SCAN[3], SCAN[4], SCAN[5], SCAN[6] = ZZ4, ac, ZZ4, { 0, 1, 2, 3 }, ac, ZZ8 +end +local SIG3 = { 0, 1, 2 } + local function block(cat: number, out: { number }, base: number, mul: { number }?, div: number): number local maxc = MAXC[cat + 1] - local sigBase, lastBase, absBase - if cat == 5 then - sigBase, lastBase, absBase = 402, 417, 426 - else - sigBase = 105 + CAT_SIG[cat + 1] - lastBase = 166 + CAT_SIG[cat + 1] - absBase = 227 + CAT_ABS[cat + 1] - end local n = 0 - local i = 0 local last = false - while i < maxc - 1 do - local inc - if cat == 5 then - inc = SIG8[i + 1] - elseif cat == 3 then - inc = if i < 2 then i else 2 - else - inc = i + -- significance map + if cat == 5 then + for i = 0, 62 do + if decision(402 + SIG8[i + 1]) == 1 then + n += 1 + SIGPOS[n] = i + if decision(417 + LAST8[i + 1]) == 1 then + last = true + break + end + end end - if decision(sigBase + inc) == 1 then - n += 1 - SIGPOS[n] = i - local linc - if cat == 5 then - linc = LAST8[i + 1] - else - linc = inc + elseif cat == 3 then + local sb, lb = 105 + 44, 166 + 44 + for i = 0, 2 do + if decision(sb + SIG3[i + 1]) == 1 then + n += 1 + SIGPOS[n] = i + if decision(lb + SIG3[i + 1]) == 1 then + last = true + break + end end - if decision(lastBase + linc) == 1 then - last = true - break + end + else + local sb = 105 + CAT_SIG[cat + 1] + local lb = 166 + CAT_SIG[cat + 1] + for i = 0, maxc - 2 do + if decision(sb + i) == 1 then + n += 1 + SIGPOS[n] = i + if decision(lb + i) == 1 then + last = true + break + end end end - i += 1 end if not last then n += 1 SIGPOS[n] = maxc - 1 end + -- levels, highest frequency first + local absBase = if cat == 5 then 426 else 227 + CAT_ABS[cat + 1] local gt1, eq1 = 0, 0 local half = div // 2 local catMax = if cat == 3 then 3 else 4 + local scan = SCAN[cat + 1] for k = n, 1, -1 do - local ctx = absBase + (if gt1 ~= 0 then 0 else (if eq1 < 3 then 1 + eq1 else 4)) local v - if decision(ctx) == 0 then + local inc = 0 + if gt1 == 0 then + inc = min(eq1 + 1, 4) + end + if decision(absBase + inc) == 0 then v = 1 + eq1 += 1 else - ctx = absBase + 5 + (if gt1 < catMax then gt1 else catMax) + local ctx = absBase + 5 + min(gt1, catMax) local prefix = 1 while prefix < 14 and decision(ctx) == 1 do prefix += 1 @@ -237,26 +251,12 @@ local function block(cat: number, out: { number }, base: number, mul: { number } v += bypass() * POW2[kk + 1] end end - end - if v == 1 then - eq1 += 1 - else gt1 += 1 end if bypass() == 1 then v = -v end - local idx = SIGPOS[k] - local p - if cat == 0 or cat == 2 then - p = ZZ4[idx + 1] - elseif cat == 1 or cat == 4 then - p = ZZ4[idx + 2] - elseif cat == 3 then - p = idx - else - p = ZZ8[idx + 1] - end + local p = scan[SIGPOS[k] + 1] if mul then out[base + p + 1] = (v * mul[p + 1] + half) // div else @@ -269,10 +269,10 @@ end -- ------------------------------------------------------------------------------------------------ syntax elements -- condition helpers on neighbouring macroblocks (addresses are 1-based here) local function leftAddr(S: any, M: any): number - return if M.aL then M.addr else 0 + return ((M.aL) and (M.addr) or (0)) end local function topAddr(S: any, M: any): number - return if M.aT then M.addr - S.mbW + 1 else 0 + return ((M.aT) and (M.addr - S.mbW + 1) or (0)) end local function mbSkipFlag(S: any, M: any): number @@ -285,7 +285,7 @@ local function mbSkipFlag(S: any, M: any): number if b > 0 and k[b] ~= K_PSKIP and k[b] ~= K_BSKIP then inc += 1 end - return decision((if S.type == 1 then 24 else 11) + inc) + return decision((((S.type == 1) and (24) or (11))) + inc) end -- intra mb_type (I slice: prefix false, offset 3; P / B suffix: offset 17 / 32) -> 0..25 @@ -338,9 +338,9 @@ local function pMbType(): number return -1 end if decision(15) == 0 then - return if decision(16) == 0 then 0 else 3 + return ((decision(16) == 0) and (0) or (3)) end - return if decision(17) == 1 then 1 else 2 + return ((decision(17) == 1) and (1) or (2)) end local function bMbType(S: any, M: any): number @@ -383,7 +383,7 @@ local function pSubType(): number if decision(22) == 0 then return 1 end - return if decision(23) == 1 then 2 else 3 + return ((decision(23) == 1) and (2) or (3)) end local function bSubType(): number @@ -440,8 +440,13 @@ local function mvd(S: any, M: any, grid: { number }, x: number, y: number, comp: if y > 0 or M.aT then sum += grid[2 * (g - S.w4) - 1 + comp] end - local base = if comp == 0 then 40 else 47 - local inc = if sum < 3 then 0 elseif sum <= 32 then 1 else 2 + local base = ((comp == 0) and (40) or (47)) + local inc = 0 + if sum > 32 then + inc = 2 + elseif sum >= 3 then + inc = 1 + end if decision(base + inc) == 0 then return 0 end @@ -502,33 +507,33 @@ local function cbpCabac(S: any, M: any): number local bx, by = b8 % 2, b8 // 2 local condA, condB = 0, 0 if bx == 1 then - if bit32.band(luma, bit32.lshift(1, b8 - 1)) == 0 then + if (luma // POW2[b8 - 1 + 1]) % 2 == 0 then condA = 1 end elseif a > 0 then - if bit32.band(cbpTab[a], bit32.lshift(1, b8 + 1)) == 0 then + if (cbpTab[a] // POW2[b8 + 1 + 1]) % 2 == 0 then condA = 1 end end if by == 1 then - if bit32.band(luma, bit32.lshift(1, b8 - 2)) == 0 then + if (luma // POW2[b8 - 2 + 1]) % 2 == 0 then condB = 1 end elseif b > 0 then - if bit32.band(cbpTab[b], bit32.lshift(1, b8 + 2)) == 0 then + if (cbpTab[b] // POW2[b8 + 2 + 1]) % 2 == 0 then condB = 1 end end if decision(73 + condA + 2 * condB) == 1 then - luma += bit32.lshift(1, b8) + luma += POW2[b8 + 1] end end - local ca = if a > 0 then cbpTab[a] // 16 else 0 - local cb = if b > 0 then cbpTab[b] // 16 else 0 - local inc = (if ca ~= 0 then 1 else 0) + (if cb ~= 0 then 2 else 0) + local ca = ((a > 0) and (cbpTab[a] // 16) or (0)) + local cb = ((b > 0) and (cbpTab[b] // 16) or (0)) + local inc = (((ca ~= 0) and (1) or (0))) + (((cb ~= 0) and (2) or (0))) local chroma = 0 if decision(77 + inc) == 1 then - inc = (if ca == 2 then 1 else 0) + (if cb == 2 then 2 else 0) + inc = (((ca == 2) and (1) or (0))) + (((cb == 2) and (2) or (0))) chroma = 1 + decision(81 + inc) end return luma + 16 * chroma @@ -536,7 +541,7 @@ end local function qpDelta(S: any): number local k = 0 - if decision(60 + (if S.lastQpd then 1 else 0)) == 1 then + if decision(60 + (((S.lastQpd) and (1) or (0)))) == 1 then k = 1 local ctx = 62 while decision(ctx) == 1 do @@ -596,18 +601,18 @@ local function lumaCond(S: any, M: any, bx: number, by: number, intra: boolean): local nzc = S.nzc local ca, cb if bx > 0 then - ca = if nzc[g - 1] ~= 0 then 1 else 0 + ca = ((nzc[g - 1] ~= 0) and (1) or (0)) elseif M.aL then - ca = if nzc[g - 1] ~= 0 then 1 else 0 + ca = ((nzc[g - 1] ~= 0) and (1) or (0)) else - ca = if intra then 1 else 0 + ca = ((intra) and (1) or (0)) end if by > 0 then - cb = if nzc[g - S.w4] ~= 0 then 1 else 0 + cb = ((nzc[g - S.w4] ~= 0) and (1) or (0)) elseif M.aT then - cb = if nzc[g - S.w4] ~= 0 then 1 else 0 + cb = ((nzc[g - S.w4] ~= 0) and (1) or (0)) else - cb = if intra then 1 else 0 + cb = ((intra) and (1) or (0)) end return ca, cb end @@ -617,14 +622,14 @@ local function chromaCond(S: any, M: any, tab: { number }, bx: number, by: numbe local g = M.c0 + by * cw + bx local ca, cb if bx > 0 or M.aL then - ca = if tab[g - 1] ~= 0 then 1 else 0 + ca = ((tab[g - 1] ~= 0) and (1) or (0)) else - ca = if intra then 1 else 0 + ca = ((intra) and (1) or (0)) end if by > 0 or M.aT then - cb = if tab[g - cw] ~= 0 then 1 else 0 + cb = ((tab[g - cw] ~= 0) and (1) or (0)) else - cb = if intra then 1 else 0 + cb = ((intra) and (1) or (0)) end return ca, cb end @@ -634,14 +639,14 @@ local function dcCond(S: any, M: any, bit: number, intra: boolean): (number, num local a, b = leftAddr(S, M), topAddr(S, M) local ca, cb if a > 0 then - ca = if bit32.band(dc[a], bit) ~= 0 then 1 else 0 + ca = (((dc[a] // bit) % 2 ~= 0) and (1) or (0)) else - ca = if intra then 1 else 0 + ca = ((intra) and (1) or (0)) end if b > 0 then - cb = if bit32.band(dc[b], bit) ~= 0 then 1 else 0 + cb = (((dc[b] // bit) % 2 ~= 0) and (1) or (0)) else - cb = if intra then 1 else 0 + cb = ((intra) and (1) or (0)) end return ca, cb end @@ -669,31 +674,31 @@ local function residuals(S: any, M: any): boolean dcBits += 1 end end - local mul4 = dq.d4[if intra then 1 else 4][qp + 1] + local mul4 = dq.d4[((intra) and (1) or (4))][qp + 1] if M.t8 == 1 then - local mul8 = dq.d8[if intra then 1 else 2][qp + 1] + local mul8 = dq.d8[((intra) and (1) or (2))][qp + 1] for i8 = 0, 3 do local bx, by = (i8 % 2) * 2, (i8 // 2) * 2 local n = 0 - if bit32.band(cbp, bit32.lshift(1, i8)) ~= 0 then + if (cbp // POW2[i8 + 1]) % 2 ~= 0 then n = block(5, M.c8, i8 * 64, mul8, 64) if n < 0 then return false end end - local f = if n > 0 then 1 else 0 + local f = ((n > 0) and (1) or (0)) local g = g0 + by * w4 + bx grid[g], grid[g + 1], grid[g + w4], grid[g + w4 + 1] = f, f, f, f nz[by * 4 + bx + 1], nz[by * 4 + bx + 2], nz[by * 4 + bx + 5], nz[by * 4 + bx + 6] = n, n, n, n end else local ac = kind == K_I16 - local cat = if ac then 1 else 2 + local cat = ((ac) and (1) or (2)) for i = 0, 15 do local bx, by = BLK_X[i + 1], BLK_Y[i + 1] local blk = by * 4 + bx local n = 0 - if bit32.band(cbp, bit32.lshift(1, i // 4)) ~= 0 then + if (cbp // POW2[i // 4 + 1]) % 2 ~= 0 then local ca, cb = lumaCond(S, M, bx, by, intra) if cbf(cat, ca, cb) == 1 then n = block(cat, c4, blk * 16, mul4, 16) @@ -702,7 +707,7 @@ local function residuals(S: any, M: any): boolean end end end - grid[g0 + by * w4 + bx] = if n > 0 then 1 else 0 + grid[g0 + by * w4 + bx] = ((n > 0) and (1) or (0)) nz[blk + 1] = n end end @@ -711,7 +716,7 @@ local function residuals(S: any, M: any): boolean local nzc = M.nzc if chroma ~= 0 then for plane = 0, 1 do - local bit = if plane == 0 then 2 else 4 + local bit = ((plane == 0) and (2) or (4)) local ca, cb = dcCond(S, M, bit, intra) if cbf(3, ca, cb) == 1 then local n = block(3, M.dcC, plane * 4, nil, 1) @@ -725,8 +730,8 @@ local function residuals(S: any, M: any): boolean end local cc = M.cc for plane = 0, 1 do - local tab = if plane == 0 then S.nzcCb else S.nzcCr - local mulc = dq.d4[(if intra then 2 else 5) + plane][(if plane == 0 then M.qpc else M.qpc2) + 1] + local tab = ((plane == 0) and (S.nzcCb) or (S.nzcCr)) + local mulc = dq.d4[(((intra) and (2) or (5))) + plane][(((plane == 0) and (M.qpc) or (M.qpc2))) + 1] for blk = 0, 3 do local bx, by = blk % 2, blk // 2 local n = 0 @@ -739,7 +744,7 @@ local function residuals(S: any, M: any): boolean end end end - tab[c0 + by * cw + bx] = if n > 0 then 1 else 0 + tab[c0 + by * cw + bx] = ((n > 0) and (1) or (0)) nzc[plane * 4 + blk + 1] = n end end @@ -832,7 +837,7 @@ local function intraMb(S: any, M: any, r: Bitstream.Reader, t: number): (boolean local rem = decision(69) rem += decision(69) * 2 rem += decision(69) * 4 - mode = if rem < pred then rem else rem + 1 + mode = ((rem < pred) and (rem) or (rem + 1)) end ipm[by * 4 + bx + 1] = mode local g = g0 + by * w4 + bx @@ -847,7 +852,7 @@ local function intraMb(S: any, M: any, r: Bitstream.Reader, t: number): (boolean local rem = decision(69) rem += decision(69) * 2 rem += decision(69) * 4 - mode = if rem < pred then rem else rem + 1 + mode = ((rem < pred) and (rem) or (rem + 1)) end ipm[by * 4 + bx + 1] = mode grid[g0 + by * w4 + bx] = mode @@ -859,7 +864,7 @@ local function intraMb(S: any, M: any, r: Bitstream.Reader, t: number): (boolean else M.kind = K_I16 M.i16 = (t - 1) % 4 - M.cbp = ((t - 1) // 4) % 3 * 16 + (if t >= 13 then 15 else 0) + M.cbp = ((t - 1) // 4) % 3 * 16 + (((t >= 13) and (15) or (0))) M.cpm = chromaPredMode(S, M) S.cpmTab[addr] = M.cpm end @@ -904,7 +909,7 @@ local function interMb(S: any, M: any, r: Bitstream.Reader, t: number, isB: bool fillMvd(S, M, g0, 0, 0, 4, 4, 0, 0) fillMvd(S, M, g1, 0, 0, 4, 4, 0, 0) elseif (not isB and t < 3) or (isB and t <= 21) then - M.kind = if isB then K_B else K_P + M.kind = ((isB) and (K_B) or (K_P)) if not isB then M.part = t pf[1], pf[2] = 1, 1 @@ -912,16 +917,16 @@ local function interMb(S: any, M: any, r: Bitstream.Reader, t: number, isB: bool M.part = 0 pf[1] = t else - M.part = if t % 2 == 0 then 1 else 2 + M.part = ((t % 2 == 0) and (1) or (2)) local k = (t - 4) // 2 + 1 pf[1], pf[2] = BPAIR0[k], BPAIR1[k] end local part = M.part - local n = if part == 0 then 1 else 2 + local n = ((part == 0) and (1) or (2)) for l = 0, 1 do - local rgt = if l == 0 then rgt0 else rgt1 - local nr = if l == 0 then n0 else n1 - local refs = if l == 0 then ref0 else ref1 + local rgt = ((l == 0) and (rgt0) or (rgt1)) + local nr = ((l == 0) and (n0) or (n1)) + local refs = ((l == 0) and (ref0) or (ref1)) for p = 1, n do local x, y, w, h = 0, 0, 4, 4 if part == 1 then @@ -929,7 +934,10 @@ local function interMb(S: any, M: any, r: Bitstream.Reader, t: number, isB: bool elseif part == 2 then x, w = (p - 1) * 2, 2 end - local uses = if l == 0 then pf[p] % 2 == 1 else pf[p] >= 2 + local uses = pf[p] >= 2 + if l == 0 then + uses = pf[p] % 2 == 1 + end local v = 0 if uses and nr > 1 then v = refIdx(S, M, rgt, x, y) @@ -938,12 +946,12 @@ local function interMb(S: any, M: any, r: Bitstream.Reader, t: number, isB: bool end end refs[p] = v - fillRegion(S, M, rgt, x, y, w, h, if uses and v > 0 then 1 else 0) + fillRegion(S, M, rgt, x, y, w, h, ((uses and v > 0) and (1) or (0))) end end for l = 0, 1 do - local grid = if l == 0 then g0 else g1 - local md = if l == 0 then mvd0 else mvd1 + local grid = ((l == 0) and (g0) or (g1)) + local md = ((l == 0) and (mvd0) or (mvd1)) for p = 1, n do local x, y, w, h = 0, 0, 4, 4 if part == 1 then @@ -951,19 +959,22 @@ local function interMb(S: any, M: any, r: Bitstream.Reader, t: number, isB: bool elseif part == 2 then x, w = (p - 1) * 2, 2 end - local uses = if l == 0 then pf[p] % 2 == 1 else pf[p] >= 2 + local uses = pf[p] >= 2 + if l == 0 then + uses = pf[p] % 2 == 1 + end local mx, my = 0, 0 if uses then mx = mvd(S, M, grid, x, y, 0) my = mvd(S, M, grid, x, y, 1) end md[2 * p - 1], md[2 * p] = mx, my - fillMvd(S, M, grid, x, y, w, h, if mx < 0 then -mx else mx, if my < 0 then -my else my) + fillMvd(S, M, grid, x, y, w, h, ((mx < 0) and (-mx) or (mx)), ((my < 0) and (-my) or (my))) end end else -- P_8x8 (3) / P_8x8ref0 (4) / B_8x8 (22) - M.kind = if isB then K_B else K_P + M.kind = ((isB) and (K_B) or (K_P)) M.part = 3 for i = 1, 4 do if isB then @@ -988,12 +999,16 @@ local function interMb(S: any, M: any, r: Bitstream.Reader, t: number, isB: bool end end for l = 0, 1 do - local rgt = if l == 0 then rgt0 else rgt1 - local nr = if l == 0 then n0 else n1 - local refs = if l == 0 then ref0 else ref1 + local rgt = ((l == 0) and (rgt0) or (rgt1)) + local nr = ((l == 0) and (n0) or (n1)) + local refs = ((l == 0) and (ref0) or (ref1)) for i = 1, 4 do local x, y = ((i - 1) % 2) * 2, ((i - 1) // 2) * 2 - local uses = not dir[i] and (if l == 0 then pf[i] % 2 == 1 else pf[i] >= 2) + local uses = pf[i] >= 2 + if l == 0 then + uses = pf[i] % 2 == 1 + end + uses = uses and not dir[i] local v = 0 if uses and nr > 1 then v = refIdx(S, M, rgt, x, y) @@ -1002,15 +1017,19 @@ local function interMb(S: any, M: any, r: Bitstream.Reader, t: number, isB: bool end end refs[i] = v - fillRegion(S, M, rgt, x, y, 2, 2, if uses and v > 0 then 1 else 0) + fillRegion(S, M, rgt, x, y, 2, 2, ((uses and v > 0) and (1) or (0))) end end for l = 0, 1 do - local grid = if l == 0 then g0 else g1 - local md = if l == 0 then mvd0 else mvd1 + local grid = ((l == 0) and (g0) or (g1)) + local md = ((l == 0) and (mvd0) or (mvd1)) for i = 1, 4 do local x0, y0 = ((i - 1) % 2) * 2, ((i - 1) // 2) * 2 - local uses = not dir[i] and (if l == 0 then pf[i] % 2 == 1 else pf[i] >= 2) + local uses = pf[i] >= 2 + if l == 0 then + uses = pf[i] % 2 == 1 + end + uses = uses and not dir[i] if not uses then fillMvd(S, M, grid, x0, y0, 2, 2, 0, 0) else @@ -1030,7 +1049,7 @@ local function interMb(S: any, M: any, r: Bitstream.Reader, t: number, isB: bool local my = mvd(S, M, grid, x, y, 1) local p = (i - 1) * 4 + k + 1 md[2 * p - 1], md[2 * p] = mx, my - fillMvd(S, M, grid, x, y, w, h, if mx < 0 then -mx else mx, if my < 0 then -my else my) + fillMvd(S, M, grid, x, y, w, h, ((mx < 0) and (-mx) or (mx)), ((my < 0) and (-my) or (my))) end end end @@ -1085,12 +1104,12 @@ function Cabac.slice(S: any, M: any, r: Bitstream.Reader): (boolean, string?) return false, "truncated: slice data" end engineInit(r.buf, p, limit) - initContexts(S.qp, if S.type == 2 then 0 else S.cabacInit + 1) + initContexts(S.qp, ((S.type == 2) and (0) or (S.cabacInit + 1))) S.lastQpd = false local addr = S.firstMb local total = S.mbW * S.mbH local st = S.type - local skipKind = if st == 1 then K_BSKIP else K_PSKIP + local skipKind = ((st == 1) and (K_BSKIP) or (K_PSKIP)) while true do if addr >= total then return false, "slice data past the end of the picture" diff --git a/src/Formats/codecs/H264/Cavlc.luau b/src/Formats/codecs/H264/Cavlc.luau index 8d3f98e..f14e42e 100644 --- a/src/Formats/codecs/H264/Cavlc.luau +++ b/src/Formats/codecs/H264/Cavlc.luau @@ -10,8 +10,6 @@ local Bitstream = require("@formats/codecs/H264/Bitstream") local Tables = require("@formats/codecs/H264/Tables") local Mb = require("@formats/codecs/H264/Mb") -local readu8, readu32 = buffer.readu8, buffer.readu32 -local band, lshift, rshift, bor, countlz, byteswap = bit32.band, bit32.lshift, bit32.rshift, bit32.bor, bit32.countlz, bit32.byteswap local u, u1, ue, se = Bitstream.u, Bitstream.u1, Bitstream.ue, Bitstream.se local K_I4, K_I8, K_I16, K_PCM, K_P, K_PSKIP, K_B, K_BSKIP, K_BDIRECT = Mb.K_I4, Mb.K_I8, Mb.K_I16, Mb.K_PCM, Mb.K_P, Mb.K_PSKIP, Mb.K_B, Mb.K_BSKIP, Mb.K_BDIRECT @@ -106,18 +104,9 @@ local INTRA_CBP, INTER_CBP = Tables.INTRA_CBP, Tables.INTER_CBP local LEVEL = table.create(16, 0) local RUN = table.create(16, 0) -local function peek(b: buffer, n: number, pos: number): number - local p = rshift(pos, 3) - if p + 5 > n then - return 0 - end - local s = band(pos, 7) - local w = byteswap(readu32(b, p)) - if s == 0 then - return w - end - return bor(lshift(w, s), rshift(readu8(b, p + 4), 8 - s)) -end +local peek = Bitstream.peekAt +local clz32 = Bitstream.clz32 +local P2 = Bitstream.P2 -- residual(r, nC, maxCoeff, out, base, scan, mul, div) -> TotalCoeff, or -1 on a bad code. Levels go to -- out[base + scan[i] + 1] dequantised as (level * mul[pos + 1] + div / 2) // div (mul nil: raw levels) @@ -136,10 +125,10 @@ local function residual(r: Bitstream.Reader, nC: number, maxCoeff: number, out: else cls = 4 end - local v = rshift(peek(b, n, pos), 16) - local e = CT1[cls][rshift(v, 8) + 1] + local v = peek(b, n, pos) // 65536 + local e = CT1[cls][v // 256 + 1] if e < 0 then - e = CT2[cls][-e + band(v, 255)] + e = CT2[cls][-e + v % 256] end if e == 0 then return -1 @@ -158,13 +147,13 @@ local function residual(r: Bitstream.Reader, nC: number, maxCoeff: number, out: -- levels local w = peek(b, n, pos) for i = 0, t1 - 1 do - LEVEL[i + 1] = if band(w, lshift(1, 31 - i)) ~= 0 then -1 else 1 + LEVEL[i + 1] = 1 - 2 * ((w // P2[32 - i]) % 2) end pos += t1 - local suffixLength = if tc > 10 and t1 < 3 then 1 else 0 + local suffixLength = ((tc > 10 and t1 < 3) and (1) or (0)) for i = t1, tc - 1 do w = peek(b, n, pos) - local prefix = countlz(w) + local prefix = if w == 0 then 32 else clz32(w) if prefix > 28 then return -1 end @@ -175,9 +164,9 @@ local function residual(r: Bitstream.Reader, nC: number, maxCoeff: number, out: elseif prefix >= 15 then size = prefix - 3 end - local levelCode = (if prefix < 15 then prefix else 15) * 2 ^ suffixLength + local levelCode = (((prefix < 15) and (prefix) or (15))) * 2 ^ suffixLength if size > 0 then - levelCode += rshift(peek(b, n, pos), 32 - size) + levelCode += peek(b, n, pos) // P2[33 - size] pos += size end if prefix >= 15 and suffixLength == 0 then @@ -199,7 +188,7 @@ local function residual(r: Bitstream.Reader, nC: number, maxCoeff: number, out: if suffixLength == 0 then suffixLength = 1 end - local a = if level < 0 then -level else level + local a = ((level < 0) and (-level) or (level)) if a > 3 * 2 ^ (suffixLength - 1) and suffixLength < 6 then suffixLength += 1 end @@ -207,16 +196,16 @@ local function residual(r: Bitstream.Reader, nC: number, maxCoeff: number, out: -- total_zeros local zerosLeft = 0 if tc < maxCoeff then - v = rshift(peek(b, n, pos), 16) + v = peek(b, n, pos) // 65536 local l1, l2 if maxCoeff == 4 then l1, l2 = TZC1[tc], TZC2[tc] else l1, l2 = TZ1[tc], TZ2[tc] end - e = l1[rshift(v, 8) + 1] + e = l1[v // 256 + 1] if e < 0 then - e = l2[-e + band(v, 255)] + e = l2[-e + v % 256] end if e == 0 then return -1 @@ -231,11 +220,11 @@ local function residual(r: Bitstream.Reader, nC: number, maxCoeff: number, out: for i = 0, tc - 2 do local run = 0 if zerosLeft > 0 then - local t = if zerosLeft > 7 then 7 else zerosLeft - v = rshift(peek(b, n, pos), 16) - e = RB1[t][rshift(v, 8) + 1] + local t = ((zerosLeft > 7) and (7) or (zerosLeft)) + v = peek(b, n, pos) // 65536 + e = RB1[t][v // 256 + 1] if e < 0 then - e = RB2[t][-e + band(v, 255)] + e = RB2[t][-e + v % 256] end if e == 0 then return -1 @@ -308,9 +297,9 @@ local function residuals(S: any, M: any, r: Bitstream.Reader): (boolean, string? end M.hasDcY = tc > 0 end - local mul4 = dq.d4[if intra then 1 else 4][qp + 1] + local mul4 = dq.d4[((intra) and (1) or (4))][qp + 1] if M.t8 == 1 then - local mul8 = dq.d8[if intra then 1 else 2][qp + 1] + local mul8 = dq.d8[((intra) and (1) or (2))][qp + 1] local c8 = M.c8 for i8 = 0, 3 do local bx0, by0 = (i8 % 2) * 2, (i8 // 2) * 2 @@ -318,7 +307,7 @@ local function residuals(S: any, M: any, r: Bitstream.Reader): (boolean, string? for i4 = 0, 3 do local bx, by = bx0 + i4 % 2, by0 + i4 // 2 local tc = 0 - if band(cbp, lshift(1, i8)) ~= 0 then + if (cbp // P2[i8 + 1]) % 2 ~= 0 then tc = residual(r, Mb.nC(S, M, bx, by), 16, c8, i8 * 64, ZZ8I[i4 + 1], mul8, 64) if tc < 0 then return false, "bad 8x8 luma residual" @@ -338,7 +327,7 @@ local function residuals(S: any, M: any, r: Bitstream.Reader): (boolean, string? local bx, by = BLK_X[i + 1], BLK_Y[i + 1] local blk = by * 4 + bx local tc = 0 - if band(cbp, lshift(1, i // 4)) ~= 0 then + if (cbp // P2[i // 4 + 1]) % 2 ~= 0 then if ac then tc = residual(r, Mb.nC(S, M, bx, by), 15, c4, blk * 16, ZZAC, mul4, 16) else @@ -372,8 +361,8 @@ local function residuals(S: any, M: any, r: Bitstream.Reader): (boolean, string? end local cc = M.cc for plane = 0, 1 do - local tab = if plane == 0 then nzcCb else nzcCr - local mulc = dq.d4[(if intra then 2 else 5) + plane][(if plane == 0 then M.qpc else M.qpc2) + 1] + local tab = ((plane == 0) and (nzcCb) or (nzcCr)) + local mulc = dq.d4[(((intra) and (2) or (5))) + plane][(((plane == 0) and (M.qpc) or (M.qpc2))) + 1] for blk = 0, 3 do local bx, by = blk % 2, blk // 2 local tc = 0 @@ -467,7 +456,7 @@ local function intraMb(S: any, M: any, r: Bitstream.Reader, t: number): (boolean local mode = pred if u1(r) == 0 then local rem = u(r, 3) - mode = if rem < pred then rem else rem + 1 + mode = ((rem < pred) and (rem) or (rem + 1)) end ipm[by * 4 + bx + 1] = mode local g = g0 + by * w4 + bx @@ -480,7 +469,7 @@ local function intraMb(S: any, M: any, r: Bitstream.Reader, t: number): (boolean local mode = pred if u1(r) == 0 then local rem = u(r, 3) - mode = if rem < pred then rem else rem + 1 + mode = ((rem < pred) and (rem) or (rem + 1)) end ipm[by * 4 + bx + 1] = mode grid[g0 + by * w4 + bx] = mode @@ -498,7 +487,7 @@ local function intraMb(S: any, M: any, r: Bitstream.Reader, t: number): (boolean elseif t <= 24 then M.kind = K_I16 M.i16 = (t - 1) % 4 - M.cbp = ((t - 1) // 4) % 3 * 16 + (if t >= 13 then 15 else 0) + M.cbp = ((t - 1) // 4) % 3 * 16 + (((t >= 13) and (15) or (0))) M.cpm = ue(r) if M.cpm > 3 then return false, "intra_chroma_pred_mode out of range" @@ -544,7 +533,7 @@ local function interMb(S: any, M: any, r: Bitstream.Reader, t: number, isB: bool if t > 4 then return false, "mb_type out of range" end - M.part = if t >= 3 then 3 else t + M.part = ((t >= 3) and (3) or (t)) pf[1], pf[2], pf[3], pf[4] = 1, 1, 1, 1 if M.part == 3 then for i = 1, 4 do @@ -558,7 +547,7 @@ local function interMb(S: any, M: any, r: Bitstream.Reader, t: number, isB: bool end end for i = 1, 4 do - local v = if t == 4 then 0 else refIdx(r, n0) + local v = ((t == 4) and (0) or (refIdx(r, n0))) if v < 0 then return false, "ref_idx_l0 out of range" end @@ -572,7 +561,7 @@ local function interMb(S: any, M: any, r: Bitstream.Reader, t: number, isB: bool end end else - local n = if M.part == 0 then 1 else 2 + local n = ((M.part == 0) and (1) or (2)) for p = 1, n do local v = refIdx(r, n0) if v < 0 then @@ -598,11 +587,11 @@ local function interMb(S: any, M: any, r: Bitstream.Reader, t: number, isB: bool M.part = 0 pf[1] = t else - M.part = if t % 2 == 0 then 1 else 2 + M.part = ((t % 2 == 0) and (1) or (2)) local k = (t - 4) // 2 + 1 pf[1], pf[2] = BPAIR0[k], BPAIR1[k] end - local n = if M.part == 0 then 1 else 2 + local n = ((M.part == 0) and (1) or (2)) for p = 1, n do if pf[p] % 2 == 1 then local v = refIdx(r, n0) @@ -671,9 +660,13 @@ local function interMb(S: any, M: any, r: Bitstream.Reader, t: number, isB: bool end end for l = 0, 1 do - local mvd = if l == 0 then mvd0 else mvd1 + local mvd = ((l == 0) and (mvd0) or (mvd1)) for i = 0, 3 do - if not dir[i + 1] and (if l == 0 then pf[i + 1] % 2 == 1 else pf[i + 1] >= 2) then + local uses = pf[i + 1] >= 2 + if l == 0 then + uses = pf[i + 1] % 2 == 1 + end + if uses and not dir[i + 1] then for k = 0, SUB_N[sub[i + 1] + 1] - 1 do local p = i * 4 + k + 1 mvd[2 * p - 1] = se(r) @@ -740,7 +733,7 @@ function Cavlc.slice(S: any, M: any, r: Bitstream.Reader): (boolean, string?) local addr = S.firstMb local total = S.mbW * S.mbH local st = S.type - local skipKind = if st == 1 then K_BSKIP else K_PSKIP + local skipKind = ((st == 1) and (K_BSKIP) or (K_PSKIP)) local more = true repeat if st ~= 2 then diff --git a/src/Formats/codecs/H264/Deblock.luau b/src/Formats/codecs/H264/Deblock.luau index fd0eb71..ffc1051 100644 --- a/src/Formats/codecs/H264/Deblock.luau +++ b/src/Formats/codecs/H264/Deblock.luau @@ -16,18 +16,12 @@ local Deblock = {} local BS = table.create(4, 0) +local min, max = math.min, math.max local function clip3(lo: number, hi: number, v: number): number - if v < lo then - return lo - elseif v > hi then - return hi - end - return v + return min(max(v, lo), hi) end -local function abs(v: number): number - return if v < 0 then -v else v -end +local abs = math.abs -- luma(b, o, across, along, qp, aOff, bOff): filters the 16 samples of one luma edge; `across` steps from q0 to q1 -- (1 for vertical edges, the stride for horizontal ones), `along` to the next sample of the edge; BS holds the four @@ -55,7 +49,7 @@ local function luma(b: buffer, o: number, across: number, along: number, qp: num local ap = abs(p2 - p0) local aq = abs(q2 - q0) if bS < 4 then - local tc = tc0 + (if ap < beta then 1 else 0) + (if aq < beta then 1 else 0) + local tc = tc0 + (((ap < beta) and (1) or (0))) + (((aq < beta) and (1) or (0))) local delta = clip3(-tc, tc, ((q0 - p0) * 4 + (p1 - q1) + 4) // 8) writeu8(b, q - across, clip3(0, 255, p0 + delta)) writeu8(b, q, clip3(0, 255, q0 - delta)) @@ -129,8 +123,8 @@ end local function motionDiffers(pic: any, p: number, q: number): boolean local uid0, uid1, mv0, mv1 = pic.uid0, pic.uid1, pic.mv0, pic.mv1 local pa, pb, qa, qb = uid0[p], uid1[p], uid0[q], uid1[q] - local np = (if pa >= 0 then 1 else 0) + (if pb >= 0 then 1 else 0) - local nq = (if qa >= 0 then 1 else 0) + (if qb >= 0 then 1 else 0) + local np = (((pa >= 0) and (1) or (0))) + (((pb >= 0) and (1) or (0))) + local nq = (((qa >= 0) and (1) or (0))) + (((qb >= 0) and (1) or (0))) if np ~= nq then return true end @@ -187,8 +181,11 @@ function Deblock.picture(S: any, pic: any, params: { any }) local co = pic.co + my * 8 * cs + mx * 8 for dir = 0, 1 do -- dir 0: vertical edges (left neighbour), dir 1: horizontal edges (top neighbour) - local nAddr = if dir == 0 then addr - 1 else addr - mbW - local edgeOk = if dir == 0 then mx > 0 else my > 0 + local nAddr = ((dir == 0) and (addr - 1) or (addr - mbW)) + local edgeOk = my > 0 + if dir == 0 then + edgeOk = mx > 0 + end if edgeOk and idc == 2 and sliceTab[nAddr] ~= sn then edgeOk = false end @@ -221,7 +218,7 @@ function Deblock.picture(S: any, pic: any, params: { any }) end local bS if intraP or intraQ then - bS = if e == 0 then 4 else 3 + bS = ((e == 0) and (4) or (3)) elseif nzDb[qg] ~= 0 or nzDb[pg] ~= 0 then bS = 2 elseif motionDiffers(pic, pg, qg) then diff --git a/src/Formats/codecs/H264/Inter.luau b/src/Formats/codecs/H264/Inter.luau index 0597dbf..7dbe10b 100644 --- a/src/Formats/codecs/H264/Inter.luau +++ b/src/Formats/codecs/H264/Inter.luau @@ -14,127 +14,153 @@ local Inter = {} Inter.PAD = 32 Inter.PADC = 16 +local min, max = math.min, math.max local function clip(v: number): number - if v < 0 then - return 0 - elseif v > 255 then - return 255 - end - return v + return min(max(v, 0), 255) end -- scratch rows of horizontal 6-tap intermediates (unrounded), 21 rows x 16 (+1) columns local B1 = table.create(24 * 17, 0) --- luma(ref, s, base, fx, fy, w, h, P): the w x h luma prediction for a block whose integer sample (0, 0) is at --- ref[base] and whose fractional offset is (fx, fy) quarter samples; P[r * 16 + c + 1] receives the samples -function Inter.luma(ref: buffer, s: number, base: number, fx: number, fy: number, w: number, h: number, P: { number }) - if fx == 0 and fy == 0 then - for r = 0, h - 1 do - local o = base + r * s - local d = r * 16 + 1 - for c = 0, w - 1 do - P[d + c] = readu8(ref, o + c) - end - end - return - end - if fy == 0 then - -- horizontal half sample b, averaged with G (fx 1) or H (fx 3) - for r = 0, h - 1 do - local o = base + r * s - local d = r * 16 + 1 - for c = 0, w - 1 do - local p = o + c - local v = readu8(ref, p - 2) - 5 * readu8(ref, p - 1) + 20 * readu8(ref, p) + 20 * readu8(ref, p + 1) - 5 * readu8(ref, p + 2) + readu8(ref, p + 3) - v = clip((v + 16) // 32) - if fx == 1 then - v = (v + readu8(ref, p) + 1) // 2 - elseif fx == 3 then - v = (v + readu8(ref, p + 1) + 1) // 2 - end - P[d + c] = v - end - end - return - end - if fx == 0 then - -- vertical half sample h, averaged with G (fy 1) or the sample below (fy 3) - local s2 = 2 * s - for r = 0, h - 1 do - local o = base + r * s - local d = r * 16 + 1 - for c = 0, w - 1 do - local p = o + c - local v = readu8(ref, p - s2) - 5 * readu8(ref, p - s) + 20 * readu8(ref, p) + 20 * readu8(ref, p + s) - 5 * readu8(ref, p + s2) + readu8(ref, p + s2 + s) - v = clip((v + 16) // 32) - if fy == 1 then - v = (v + readu8(ref, p) + 1) // 2 - elseif fy == 3 then - v = (v + readu8(ref, p + s) + 1) // 2 - end - P[d + c] = v - end - end - return - end - if fx == 2 or fy == 2 then - -- j (centre), from the unrounded horizontal intermediates of rows -2 .. h + 2 - for r = -2, h + 2 do - local o = base + r * s - local d = (r + 2) * 17 + 1 - for c = 0, w do - local p = o + c - B1[d + c] = readu8(ref, p - 2) - 5 * readu8(ref, p - 1) + 20 * readu8(ref, p) + 20 * readu8(ref, p + 1) - 5 * readu8(ref, p + 2) + readu8(ref, p + 3) - end - end - local s2 = 2 * s - for r = 0, h - 1 do - local d = r * 16 + 1 - local q = (r + 2) * 17 + 1 - local o = base + r * s - for c = 0, w - 1 do - local k = q + c - local j = B1[k - 34] - 5 * B1[k - 17] + 20 * B1[k] + 20 * B1[k + 17] - 5 * B1[k + 34] + B1[k + 51] - j = clip((j + 512) // 1024) - local v - if fx == 2 then - if fy == 2 then - v = j - elseif fy == 1 then -- f: (b + j + 1) >> 1 - v = (j + clip((B1[k] + 16) // 32) + 1) // 2 - else -- q: (s + j + 1) >> 1, s = b of the row below - v = (j + clip((B1[k + 17] + 16) // 32) + 1) // 2 - end - else - -- fy == 2: i (fx 1, with h) or k (fx 3, with m = h of the next column) - local p = o + c + (if fx == 3 then 1 else 0) - local hv = readu8(ref, p - s2) - 5 * readu8(ref, p - s) + 20 * readu8(ref, p) + 20 * readu8(ref, p + s) - 5 * readu8(ref, p + s2) + readu8(ref, p + s2 + s) - v = (j + clip((hv + 16) // 32) + 1) // 2 - end - P[d + c] = v - end - end - return - end - -- diagonal quarter samples e, g, p, r: average of a horizontal half (b at this row or s at the next) and a - -- vertical half (h at this column or m at the next) - local s2 = 2 * s - local ro = if fy == 3 then s else 0 - local co = if fx == 3 then 1 else 0 +-- the six-tap filter cases, each a small function (LuaJIT keeps small loops in one trace); sliding windows read each +-- sample once per row / column +local function lumaCopy(ref: buffer, s: number, base: number, w: number, h: number, P: { number }) for r = 0, h - 1 do local o = base + r * s local d = r * 16 + 1 for c = 0, w - 1 do - local p = o + c + ro - local hb = readu8(ref, p - 2) - 5 * readu8(ref, p - 1) + 20 * readu8(ref, p) + 20 * readu8(ref, p + 1) - 5 * readu8(ref, p + 2) + readu8(ref, p + 3) - p = o + c + co - local vb = readu8(ref, p - s2) - 5 * readu8(ref, p - s) + 20 * readu8(ref, p) + 20 * readu8(ref, p + s) - 5 * readu8(ref, p + s2) + readu8(ref, p + s2 + s) - P[d + c] = (clip((hb + 16) // 32) + clip((vb + 16) // 32) + 1) // 2 + P[d + c] = readu8(ref, o + c) end end end +-- horizontal half sample b; avg 0: b, 1: (G + b + 1) >> 1, 2: (b + H + 1) >> 1 +local function lumaH(ref: buffer, s: number, base: number, w: number, h: number, P: { number }, avg: number) + for r = 0, h - 1 do + local o = base + r * s + local d = r * 16 + 1 + local a0, a1, a2, a3, a4 = readu8(ref, o - 2), readu8(ref, o - 1), readu8(ref, o), readu8(ref, o + 1), readu8(ref, o + 2) + for c = 0, w - 1 do + local a5 = readu8(ref, o + c + 3) + local v = min(max((a0 - 5 * a1 + 20 * a2 + 20 * a3 - 5 * a4 + a5 + 16) // 32, 0), 255) + if avg == 1 then + v = (v + a2 + 1) // 2 + elseif avg == 2 then + v = (v + a3 + 1) // 2 + end + P[d + c] = v + a0, a1, a2, a3, a4 = a1, a2, a3, a4, a5 + end + end +end + +-- vertical half sample h; avg 0: h, 1: (G + h + 1) >> 1, 2: (h + G below + 1) >> 1 +local function lumaV(ref: buffer, s: number, base: number, w: number, h: number, P: { number }, avg: number) + for c = 0, w - 1 do + local o = base + c + local a0, a1, a2, a3, a4 = readu8(ref, o - 2 * s), readu8(ref, o - s), readu8(ref, o), readu8(ref, o + s), readu8(ref, o + 2 * s) + local d = c + 1 + for r = 0, h - 1 do + local a5 = readu8(ref, o + (r + 3) * s) + local v = min(max((a0 - 5 * a1 + 20 * a2 + 20 * a3 - 5 * a4 + a5 + 16) // 32, 0), 255) + if avg == 1 then + v = (v + a2 + 1) // 2 + elseif avg == 2 then + v = (v + a3 + 1) // 2 + end + P[d + r * 16] = v + a0, a1, a2, a3, a4 = a1, a2, a3, a4, a5 + end + end +end + +-- B1 rows -2 .. h + 2, columns 0 .. w (unrounded horizontal intermediates), stride 17 +local function horizontal1(ref: buffer, s: number, base: number, w: number, h: number) + for r = -2, h + 2 do + local o = base + r * s + local d = (r + 2) * 17 + 1 + local a0, a1, a2, a3, a4 = readu8(ref, o - 2), readu8(ref, o - 1), readu8(ref, o), readu8(ref, o + 1), readu8(ref, o + 2) + for c = 0, w do + local a5 = readu8(ref, o + c + 3) + B1[d + c] = a0 - 5 * a1 + 20 * a2 + 20 * a3 - 5 * a4 + a5 + a0, a1, a2, a3, a4 = a1, a2, a3, a4, a5 + end + end +end + +-- centre j; with = 0: j, 1: (b + j + 1) >> 1 (b of this row), 2: (s + j + 1) >> 1 (b of the next row) +local function lumaJ(ref: buffer, s: number, base: number, w: number, h: number, P: { number }, with: number) + horizontal1(ref, s, base, w, h) + for c = 0, w - 1 do + local k = 2 * 17 + 1 + c + local a0, a1, a2, a3, a4 = B1[k - 34], B1[k - 17], B1[k], B1[k + 17], B1[k + 34] + for r = 0, h - 1 do + local a5 = B1[k + 51] + local v = min(max((a0 - 5 * a1 + 20 * a2 + 20 * a3 - 5 * a4 + a5 + 512) // 1024, 0), 255) + if with == 1 then + v = (v + min(max((a2 + 16) // 32, 0), 255) + 1) // 2 + elseif with == 2 then + v = (v + min(max((a3 + 16) // 32, 0), 255) + 1) // 2 + end + P[r * 16 + c + 1] = v + a0, a1, a2, a3, a4 = a1, a2, a3, a4, a5 + k += 17 + end + end +end + +-- (j + h + 1) >> 1 with h at column c + co (co 0: i, 1: k) +local function lumaJV(ref: buffer, s: number, base: number, w: number, h: number, P: { number }, co: number) + lumaJ(ref, s, base, w, h, P, 0) + for c = 0, w - 1 do + local o = base + c + co + local a0, a1, a2, a3, a4 = readu8(ref, o - 2 * s), readu8(ref, o - s), readu8(ref, o), readu8(ref, o + s), readu8(ref, o + 2 * s) + for r = 0, h - 1 do + local a5 = readu8(ref, o + (r + 3) * s) + local hv = min(max((a0 - 5 * a1 + 20 * a2 + 20 * a3 - 5 * a4 + a5 + 16) // 32, 0), 255) + local d = r * 16 + c + 1 + P[d] = (P[d] + hv + 1) // 2 + a0, a1, a2, a3, a4 = a1, a2, a3, a4, a5 + end + end +end + +-- diagonal quarter samples e, g, p, r: (b or s) averaged with (h or m) +local function lumaDiag(ref: buffer, s: number, base: number, w: number, h: number, P: { number }, ro: number, co: number) + lumaH(ref, s, base + ro, w, h, P, 0) + for c = 0, w - 1 do + local o = base + c + co + local a0, a1, a2, a3, a4 = readu8(ref, o - 2 * s), readu8(ref, o - s), readu8(ref, o), readu8(ref, o + s), readu8(ref, o + 2 * s) + for r = 0, h - 1 do + local a5 = readu8(ref, o + (r + 3) * s) + local vb = min(max((a0 - 5 * a1 + 20 * a2 + 20 * a3 - 5 * a4 + a5 + 16) // 32, 0), 255) + local d = r * 16 + c + 1 + P[d] = (P[d] + vb + 1) // 2 + a0, a1, a2, a3, a4 = a1, a2, a3, a4, a5 + end + end +end + +-- luma(ref, s, base, fx, fy, w, h, P): the w x h luma prediction for a block whose integer sample (0, 0) is at +-- ref[base] and whose fractional offset is (fx, fy) quarter samples; P[r * 16 + c + 1] receives the samples +function Inter.luma(ref: buffer, s: number, base: number, fx: number, fy: number, w: number, h: number, P: { number }) + if fy == 0 then + if fx == 0 then + lumaCopy(ref, s, base, w, h, P) + else + lumaH(ref, s, base, w, h, P, if fx == 2 then 0 elseif fx == 1 then 1 else 2) + end + elseif fx == 0 then + lumaV(ref, s, base, w, h, P, if fy == 2 then 0 elseif fy == 1 then 1 else 2) + elseif fx == 2 then + lumaJ(ref, s, base, w, h, P, if fy == 2 then 0 elseif fy == 1 then 1 else 2) + elseif fy == 2 then + lumaJV(ref, s, base, w, h, P, if fx == 3 then 1 else 0) + else + lumaDiag(ref, s, base, w, h, P, if fy == 3 then s else 0, if fx == 3 then 1 else 0) + end +end + -- chroma(ref, s, base, fx, fy, w, h, P): eighth-sample bilinear chroma prediction function Inter.chroma(ref: buffer, s: number, base: number, fx: number, fy: number, w: number, h: number, P: { number }) if fx == 0 and fy == 0 then diff --git a/src/Formats/codecs/H264/Intra.luau b/src/Formats/codecs/H264/Intra.luau index a653b3f..4543050 100644 --- a/src/Formats/codecs/H264/Intra.luau +++ b/src/Formats/codecs/H264/Intra.luau @@ -12,13 +12,9 @@ local Intra = {} local E = table.create(40, 0) -- reference samples: p[-1, y] = E[N - y], p[-1, -1] = E[N + 1], p[x, -1] = E[N + 2 + x] local F = table.create(40, 0) -- filtered 8x8 references, same layout +local min, max = math.min, math.max local function clip(v: number): number - if v < 0 then - return 0 - elseif v > 255 then - return 255 - end - return v + return min(max(v, 0), 255) end -- predNxN: the directional modes 3..8 over the edge array R (N = 4 or 8) diff --git a/src/Formats/codecs/H264/Mb.luau b/src/Formats/codecs/H264/Mb.luau index c1aa116..428e088 100644 --- a/src/Formats/codecs/H264/Mb.luau +++ b/src/Formats/codecs/H264/Mb.luau @@ -18,6 +18,7 @@ local K_I4, K_I8, K_I16, K_PCM, K_P, K_PSKIP, K_B, K_BSKIP, K_BDIRECT = 1, 2, 3, Mb.K_I4, Mb.K_I8, Mb.K_I16, Mb.K_PCM, Mb.K_P, Mb.K_PSKIP, Mb.K_B, Mb.K_BSKIP, Mb.K_BDIRECT = K_I4, K_I8, K_I16, K_PCM, K_P, K_PSKIP, K_B, K_BSKIP, K_BDIRECT local UNAVAIL = -2 +local min, max = math.min, math.max local add4, addDc4, add8 = Transform.add4, Transform.addDc4, Transform.add8 local PAD, PADC = Inter.PAD, Inter.PADC @@ -181,7 +182,7 @@ function Mb.predMode(S: any, M: any, bx: number, by: number): number local ipm = S.ipm local g = M.g0 + by * S.w4 + bx local a, b = ipm[g - 1], ipm[g - S.w4] - return if a < b then a else b + return ((a < b) and (a) or (b)) end -- ------------------------------------------------------------------------------------------------ motion vectors @@ -216,21 +217,15 @@ local function neighbour(S: any, M: any, refs: { number }, mvs: { number }, nx: end local function median(a: number, b: number, c: number): number - if a > b then - a, b = b, a - end - if b > c then - b = c - end - return if a > b then a else b + return max(min(a, b), min(max(a, b), c)) end -- mvp(S, M, list, x, y, w, ref, shape) -> mvpLX for the partition at (x, y) (4x4 units) of width w with reference -- index ref. shape: 0 generic, 1 = 16x8 upper, 2 = 16x8 lower, 3 = 8x16 left, 4 = 8x16 right local function mvp(S: any, M: any, list: number, x: number, y: number, w: number, ref: number, shape: number): (number, number) local pic = S.pic - local refs = if list == 0 then pic.ref0 else pic.ref1 - local mvs = if list == 0 then pic.mv0 else pic.mv1 + local refs = ((list == 0) and (pic.ref0) or (pic.ref1)) + local mvs = ((list == 0) and (pic.mv0) or (pic.mv1)) local rA, ax, ay = neighbour(S, M, refs, mvs, x - 1, y) local rB, bx, by = neighbour(S, M, refs, mvs, x, y - 1) local rC, cx, cy = neighbour(S, M, refs, mvs, x + w, y - 1) @@ -283,8 +278,8 @@ Mb.mvp = mvp local function set(S: any, M: any, x: number, y: number, w: number, h: number, r0: number, m0x: number, m0y: number, r1: number, m1x: number, m1y: number) local pic = S.pic local ref0, ref1, mv0, mv1, uid0, uid1 = pic.ref0, pic.ref1, pic.mv0, pic.mv1, pic.uid0, pic.uid1 - local u0 = if r0 >= 0 then S.uids0[r0 + 1] or -1 else -1 - local u1 = if r1 >= 0 then S.uids1[r1 + 1] or -1 else -1 + local u0 = ((r0 >= 0) and (S.uids0[r0 + 1] or -1) or (-1)) + local u1 = ((r1 >= 0) and (S.uids1[r1 + 1] or -1) or (-1)) local w4 = S.w4 local done = M.done for j = y, y + h - 1 do @@ -308,12 +303,7 @@ end -- clipping helpers local function clip3(lo: number, hi: number, v: number): number - if v < lo then - return lo - elseif v > hi then - return hi - end - return v + return min(max(v, lo), hi) end local function tdiv(a: number, b: number): number @@ -353,8 +343,8 @@ end local function colocated(S: any, M: any, bx: number, by: number): (number, number, number, number) local col = S.colPic if S.direct8x8 then - bx = if bx < 2 then 0 else 3 - by = if by < 2 then 0 else 3 + bx = ((bx < 2) and (0) or (3)) + by = ((by < 2) and (0) or (3)) end if col.mbIntra[M.addr + 1] then return -1, 0, 0, -1 @@ -373,9 +363,9 @@ end local function minPositive(a: number, b: number): number if a >= 0 and b >= 0 then - return if a < b then a else b + return ((a < b) and (a) or (b)) end - return if a > b then a else b + return ((a > b) and (a) or (b)) end -- spatialRefs(S, M): the macroblock-level references and predictors of spatial direct (8.4.1.2.2), cached in M @@ -383,8 +373,8 @@ local function spatialRefs(S: any, M: any) local pic = S.pic local r0, r1 = -1, -1 for l = 0, 1 do - local refs = if l == 0 then pic.ref0 else pic.ref1 - local mvs = if l == 0 then pic.mv0 else pic.mv1 + local refs = ((l == 0) and (pic.ref0) or (pic.ref1)) + local mvs = ((l == 0) and (pic.mv0) or (pic.mv1)) local rA = neighbour(S, M, refs, mvs, -1, 0) local rB = neighbour(S, M, refs, mvs, 0, -1) local rC = neighbour(S, M, refs, mvs, 4, -1) @@ -422,7 +412,7 @@ end -- direct8(S, M, i8): direct motion of 8x8 quadrant i8 (B_Skip, B_Direct_16x16, B_Direct_8x8) local function direct8(S: any, M: any, i8: number) local x0, y0 = (i8 % 2) * 2, (i8 // 2) * 2 - local step = if S.direct8x8 then 2 else 1 + local step = ((S.direct8x8) and (2) or (1)) if S.directSpatial then if not M.dReady then spatialRefs(S, M) @@ -490,7 +480,7 @@ local function motion(S: any, M: any) local part = M.part local mvd0, mvd1 = M.mvd0, M.mvd1 if part < 3 then - local n = if part == 0 then 1 else 2 + local n = ((part == 0) and (1) or (2)) for p = 1, n do local x, y, w, h = 0, 0, 4, 4 local shape = 0 @@ -599,8 +589,8 @@ local function mc(S: any, M: any) local g = M.g0 + y * S.w4 + x local r0, r1 = pic.ref0[g], pic.ref1[g] local m0x, m0y, m1x, m1y = pic.mv0[2 * g - 1], pic.mv0[2 * g], pic.mv1[2 * g - 1], pic.mv1[2 * g] - local ref0 = if r0 >= 0 then refPic(list0, r0) else nil - local ref1 = if r1 >= 0 then refPic(list1, r1) else nil + local ref0 = ((r0 >= 0) and (refPic(list0, r0)) or (nil)) + local ref1 = ((r1 >= 0) and (refPic(list1, r1)) or (nil)) if ref0 == nil and ref1 == nil then ref0 = list0[1] or list1[1] r0 = 0 @@ -637,20 +627,20 @@ local function mc(S: any, M: any) if plane == 0 then predLuma(S, ref0, P0, px, py, lw, lh, m0x, m0y) else - predChroma(S, ref0, P0, if plane == 1 then ref0.u else ref0.v, cx, cy, cw, ch, m0x, m0y) + predChroma(S, ref0, P0, ((plane == 1) and (ref0.u) or (ref0.v)), cx, cy, cw, ch, m0x, m0y) end end if ref1 then if plane == 0 then predLuma(S, ref1, P1, px, py, lw, lh, m1x, m1y) else - predChroma(S, ref1, P1, if plane == 1 then ref1.u else ref1.v, cx, cy, cw, ch, m1x, m1y) + predChroma(S, ref1, P1, ((plane == 1) and (ref1.u) or (ref1.v)), cx, cy, cw, ch, m1x, m1y) end end if wm == 2 and bi then Inter.weight2(P0, P1, bw, bh, dst, o, s, 5, implicitW0, implicitW1, 0) elseif explicit then - local logWD = if plane == 0 then S.lumaDenom else S.chromaDenom + local logWD = ((plane == 0) and (S.lumaDenom) or (S.chromaDenom)) local wi = plane * 2 + 1 if bi then local b0, b1 = r0 * 8, r1 * 8 @@ -707,11 +697,11 @@ local function chromaResidual(S: any, M: any) if M.hasDcC then local dq = S.dq.d4 local intra = M.kind <= K_PCM - Transform.chromaDc(M.dcC, 0, dq[if intra then 2 else 5][M.qpc + 1][1], cc, 0) - Transform.chromaDc(M.dcC, 4, dq[if intra then 3 else 6][M.qpc2 + 1][1], cc, 64) + Transform.chromaDc(M.dcC, 0, dq[((intra) and (2) or (5))][M.qpc + 1][1], cc, 0) + Transform.chromaDc(M.dcC, 4, dq[((intra) and (3) or (6))][M.qpc2 + 1][1], cc, 64) end for plane = 0, 1 do - local b = if plane == 0 then pic.u else pic.v + local b = ((plane == 0) and (pic.u) or (pic.v)) for blk = 0, 3 do local base = (plane * 4 + blk) * 16 local q = o + (blk // 2) * 4 * s + (blk % 2) * 4 @@ -789,7 +779,11 @@ local function intraLuma(S: any, M: any) end local tr if by == 0 then - tr = if bx < 3 then M.iT else M.iTR + if bx < 3 then + tr = M.iT + else + tr = M.iTR + end else tr = not (bx == 3 or (bx == 1 and (by == 1 or by == 3))) end @@ -836,9 +830,9 @@ function Mb.recon(S: any, M: any) S.kind[addr] = kind S.sliceTab[addr] = S.slice S.t8Tab[addr] = M.t8 - S.qpTab[addr] = if kind == K_PCM then 0 else M.qp - S.qpcTab[addr] = if kind == K_PCM then S.qpcOf[1] else M.qpc - S.qpc2Tab[addr] = if kind == K_PCM then S.qpc2Of[1] else M.qpc2 + S.qpTab[addr] = ((kind == K_PCM) and (0) or (M.qp)) + S.qpcTab[addr] = ((kind == K_PCM) and (S.qpcOf[1]) or (M.qpc)) + S.qpc2Tab[addr] = ((kind == K_PCM) and (S.qpc2Of[1]) or (M.qpc2)) pic.mbIntra[addr] = kind <= K_PCM local nzDb = S.nzDb local g0 = M.g0 @@ -878,13 +872,13 @@ function Mb.recon(S: any, M: any) if M.t8 == 1 then for i8 = 0, 3 do local bx, by = (i8 % 2) * 2, (i8 // 2) * 2 - local v = if nz[by * 4 + bx + 1] > 0 then 1 else 0 + local v = ((nz[by * 4 + bx + 1] > 0) and (1) or (0)) local g = g0 + by * w4 + bx nzDb[g], nzDb[g + 1], nzDb[g + w4], nzDb[g + w4 + 1] = v, v, v, v end else for blk = 0, 15 do - nzDb[g0 + (blk // 4) * w4 + blk % 4] = if nz[blk + 1] > 0 then 1 else 0 + nzDb[g0 + (blk // 4) * w4 + blk % 4] = ((nz[blk + 1] > 0) and (1) or (0)) end end if M.cbp % 16 ~= 0 then diff --git a/src/Formats/codecs/H264/Transform.luau b/src/Formats/codecs/H264/Transform.luau index e685d34..6fd463d 100644 --- a/src/Formats/codecs/H264/Transform.luau +++ b/src/Formats/codecs/H264/Transform.luau @@ -10,13 +10,9 @@ local readu8, writeu8 = buffer.readu8, buffer.writeu8 local Transform = {} +local min, max = math.min, math.max local function clip(v: number): number - if v < 0 then - return 0 - elseif v > 255 then - return 255 - end - return v + return min(max(v, 0), 255) end -- add4(c, base, b, o, s): inverse 4x4 transform of c[base + 1 .. base + 16], added to the 4x4 block at b[o] (stride s) diff --git a/src/Formats/codecs/H264/init.luau b/src/Formats/codecs/H264/init.luau index f3f5a04..2da8dd1 100644 --- a/src/Formats/codecs/H264/init.luau +++ b/src/Formats/codecs/H264/init.luau @@ -122,7 +122,7 @@ function DecoderMeta.configure(self: H264Decoder, avcC: any): (boolean?, Err.Err end -- decoder:decode(data, pts?, off?, len?) -> { Frame } | nil, Err. data: an access unit or any run of NAL units: --- Annex B (start codes), length-prefixed (after configure / lengthSize), or one bare NAL unit. +-- length-prefixed (after configure / with opts.lengthSize), else Annex B (start codes) or one bare NAL unit. function DecoderMeta.decode(self: H264Decoder, data: any, pts: number?, off: number?, len: number?): ({ Frame }?, Err.Err?) local b = toBuffer(data) if not b then @@ -133,15 +133,15 @@ function DecoderMeta.decode(self: H264Decoder, data: any, pts: number?, off: num local l = math.clamp(len or (n - o), 0, n - o) local st = self.state local nals - if Bitstream.isAnnexB(b, o, l) then - nals = Bitstream.splitAnnexB(b, o, l) - elseif self.lengthSize then + if self.lengthSize then local all, partial = Bitstream.splitLength(b, o, l, self.lengthSize) nals = all or partial if not all then st.errors += 1 st.lastError = "NAL length past the end of the sample" end + elseif Bitstream.isAnnexB(b, o, l) then + nals = Bitstream.splitAnnexB(b, o, l) else nals = { o, l } end diff --git a/tests/codecs/h264.luau b/tests/codecs/h264.luau new file mode 100644 index 0000000..8ef8bc9 --- /dev/null +++ b/tests/codecs/h264.luau @@ -0,0 +1,172 @@ +-- codecs/H264 tests: libx264 streams at many settings (Baseline / Main / High, CAVLC / CABAC, B frames, references, +-- weighted prediction, 8x8 transforms, scaling matrices, slices, odd sizes with cropping, ...) decoded and compared +-- per frame with ffmpeg's decoder (CRC-32 of the yuv420p planes, bit-exact); the AVCC (avcC + length-prefixed +-- samples) and NAL-at-a-time paths; pts propagation; UNSUPPORTED streams (interlaced, 4:2:2, 4:4:4, 10-bit); error +-- codes; and the fuzz no-throw pass. Fixtures: tools/fixtures/h264.py. +local T = require("@tests/T") +local H264 = require("@formats/codecs/H264") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Cases = require("@tests/gen/h264_cases") +local Bad = require("@tests/gen/h264_bad") + +local t = T.suite("h264") + +-- 1. every stream, whole, against ffmpeg +local nframes = 0 +for _, c in Cases do + local frames, err = H264.decodeAll(c.data) + t:check(frames, c.name .. ": " .. tostring(err)) + t:eq(#frames, #c.frames, c.name .. ": frame count") + local good = 0 + for i, f in frames do + if i == 1 then + t:check(f.image.format == "yuv420p" and f.image.width == c.width and f.image.height == c.height, c.name .. ": size") + end + if Crc32.of(f.image.pixels) == c.frames[i] then + good += 1 + end + end + t:eq(good, #c.frames, c.name .. ": frames bit-exact with ffmpeg") + nframes += good +end +t:note("%d streams, %d frames bit-exact with ffmpeg", #Cases, nframes) + +-- 2. AVCC samples, NAL-at-a-time input, pts +local function splitAnnexB(s: string): { string } + local out = {} + local i = 1 + local starts = {} + while true do + local j = string.find(s, "\0\0\1", i, true) + if not j then + break + end + table.insert(starts, j + 3) + i = j + 3 + end + for k, st in starts do + local e = if starts[k + 1] then starts[k + 1] - 4 else #s + local nal = string.sub(s, st, e) + while string.byte(nal, #nal) == 0 do + nal = string.sub(nal, 1, #nal - 1) + end + table.insert(out, nal) + end + return out +end + +for _, c in Cases do + if c.avcc then + local dec = H264.newDecoder({ avcC = buffer.fromstring(c.avcc) }) + t:check(dec, c.name .. ": avcC") + local got = {} + for i, s in c.samples do + local frames, err = (dec :: any):decode(s, i * 1000) + t:check(frames, c.name .. ": sample " .. i .. ": " .. tostring(err)) + for _, f in frames do + table.insert(got, f) + end + end + for _, f in (dec :: any):flush() do + table.insert(got, f) + end + local good = 0 + local ptsOk = true + local last = -1 + for i, f in got do + if Crc32.of(f.image.pixels) == c.frames[i] then + good += 1 + end + if f.pts % 1000 ~= 0 then + ptsOk = false + end + if f.poc <= last and not f.keyframe then + ptsOk = false + end + last = f.poc + end + t:eq(good, #c.frames, c.name .. ": AVCC samples bit-exact") + t:check(ptsOk, c.name .. ": pts carried per access unit, output in POC order") + -- bare NAL units, one call each + local dec2 = H264.newDecoder() :: any + local got2 = 0 + for _, nal in splitAnnexB(c.data) do + local frames = dec2:decode(nal) + for _, f in frames do + got2 += 1 + t:check(Crc32.of(f.image.pixels) == c.frames[got2], c.name .. ": NAL-at-a-time frame " .. got2) + end + end + for _, f in dec2:flush() do + got2 += 1 + t:check(Crc32.of(f.image.pixels) == c.frames[got2], c.name .. ": NAL-at-a-time frame " .. got2) + end + t:eq(got2, #c.frames, c.name .. ": NAL-at-a-time frame count") + end +end + +-- 3. unsupported streams +for _, c in Bad do + local frames, err = H264.decodeAll(c.data) + t:check(frames == nil and err and err.code == c.code, c.name .. ": " .. tostring(err)) +end + +-- 4. error codes +do + local _, e1 = H264.decodeAll(123 :: any) + t:check(e1 and e1.code == Err.ARG, "decode of a number: ARG") + local _, e2 = H264.decodeAll(Cases[1].data, { maxPixels = 1000 }) + t:check(e2 and e2.code == Err.LIMIT, "maxPixels: LIMIT " .. tostring(e2)) + local _, e3 = H264.newDecoder({ avcC = buffer.fromstring("\1\2") }) + t:check(e3 and e3.code == Err.TRUNCATED, "short avcC: TRUNCATED") + local _, e4 = H264.parseAvcC("\2\0\0\0\0\0\0") + t:check(e4 and e4.code == Err.CORRUPT, "avcC version 2: CORRUPT") + local frames = H264.decodeAll("") + t:check(frames and #frames == 0, "empty input: no frames") + -- a stream cut in half still decodes the first frames (the rest concealed or missing) + local c = Cases[3] + local half = H264.decodeAll(string.sub(c.data, 1, #c.data // 2)) + t:check(half and #half > 0 and Crc32.of(half[1].image.pixels) == c.frames[1], "truncated stream: first frame intact") + -- lowDelay outputs in decoding order (right for streams without reordering) + local ld = H264.decodeAll(c.data, { lowDelay = true }) + t:check(ld and #ld == #c.frames and Crc32.of(ld[#ld].image.pixels) == c.frames[#c.frames], "lowDelay on a P-only stream") +end + +-- 5. fuzz: streams with damaged bytes / truncations must never throw +local samples = {} +for _, c in Cases do + if #c.data < 20000 and #samples < 14 then + table.insert(samples, c.data) + end +end +t:fuzz("decodeAll", function(b: buffer) + return H264.decodeAll(b, { maxPixels = 2 ^ 18 }) +end, samples, { mutations = 10, keepHeader = 40 }) +t:fuzz("decodeAll (headers too)", function(b: buffer) + return H264.decodeAll(b, { maxPixels = 2 ^ 18 }) +end, samples, { mutations = 6, garbage = 100 }) +-- heavier damage: many bytes changed in the slice data +do + local rand = T.rng(99) + local tries, threw = 0, 0 + for _, s in samples do + for _ = 1, 6 do + local b = buffer.fromstring(s) + local n = buffer.len(b) + for _ = 1, 1 + rand(40) do + buffer.writeu8(b, 60 + rand(n - 61), rand(256)) + end + tries += 1 + local ok, err = pcall(H264.decodeAll, b, { maxPixels = 2 ^ 18 }) + if not ok then + threw += 1 + print(" THREW (heavy mutation): " .. tostring(err)) + end + end + end + t:check(threw == 0, "heavy mutations never throw (" .. threw .. " of " .. tries .. ")") + t:note("heavy mutations: %d damaged streams, none threw", tries) +end + +t:done() diff --git a/tools/bench.luau b/tools/bench.luau index 710195d..237989e 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -535,3 +535,15 @@ do Webp.encode(img, { effort = 1 }) end) end +do + -- H.264: frames per second over whole streams (decode + output copies); MB/s of yuv420p output + local H264 = require("@formats/codecs/H264") + local HB = require("@tests/gen/h264_bench") + for _, c in HB do + local n = c.width * c.height * 3 // 2 * #c.frames + local dt = bench("h264 " .. c.name .. " " .. #c.frames .. "f", 2, n, function() + H264.decodeAll(c.data) + end) + print(string.format("%-8s h264 %s: %.1f fps at %dx%d", runtime, c.name, #c.frames / dt, c.width, c.height)) + end +end diff --git a/tools/fixtures/h264.py b/tools/fixtures/h264.py index 330ef46..99560de 100644 --- a/tools/fixtures/h264.py +++ b/tools/fixtures/h264.py @@ -61,6 +61,10 @@ BENCH = [ ("qvga_baseline", "testsrc2", 320, 240, 30, "cabac=0:bframes=0:ref=1:8x8dct=0:crf=23"), ("nhd_cabac_b", "testsrc2", 640, 360, 30, "cabac=1:bframes=3:ref=3:crf=23"), ("nhd_baseline", "testsrc2", 640, 360, 30, "cabac=0:bframes=0:ref=1:8x8dct=0:crf=23"), + ("qvga_mandel_high", "mandel", 320, 240, 30, "cabac=1:bframes=3:ref=3:8x8dct=1:crf=23"), + ("qvga_mandel_base", "mandel", 320, 240, 30, "cabac=0:bframes=0:ref=1:8x8dct=0:crf=23"), + ("nhd_mandel_high", "mandel", 640, 360, 30, "cabac=1:bframes=3:ref=3:8x8dct=1:crf=23"), + ("nhd_mandel_base", "mandel", 640, 360, 30, "cabac=0:bframes=0:ref=1:8x8dct=0:crf=23"), ]