diff --git a/licenses/openh264-LICENSE.txt b/licenses/openh264-LICENSE.txt new file mode 100644 index 0000000..8e730c4 --- /dev/null +++ b/licenses/openh264-LICENSE.txt @@ -0,0 +1,23 @@ +Copyright (c) 2013, Cisco Systems +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, this + list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/src/Formats/codecs/H264/Bitstream.luau b/src/Formats/codecs/H264/Bitstream.luau new file mode 100644 index 0000000..9c8d02e --- /dev/null +++ b/src/Formats/codecs/H264/Bitstream.luau @@ -0,0 +1,262 @@ +--!strict +--!native +--!optimize 2 +-- codecs/H264/Bitstream: NAL unit framing and the RBSP bit reader of ITU-T H.264 (7.3 / 7.4 / 9.1): Annex B start +-- code splitting, AVCC length-prefixed samples, avcC (AVCDecoderConfigurationRecord, ISO/IEC 14496-15 5.3.3) +-- parsing, emulation-prevention removal, and the u(n) / ue(v) / se(v) / te(v) readers. Written from the spec. +-- Never throws: reads past the end of an RBSP return zero bits (the buffer carries 8 zero bytes of padding and every +-- 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 + +export type Reader = { + buf: buffer, -- the RBSP (emulation prevention removed) followed by 8 zero bytes + pos: number, -- bit position + size: number, -- RBSP length in bits (up to the end of the data, trailing bits included) + stop: number, -- bit position of the rbsp_stop_one_bit (size when there is none) + n: number, -- buffer length in bytes +} + +-- ------------------------------------------------------------------------------------------------ framing +-- splitAnnexB(buf, off, len) -> { off1, len1, off2, len2, ... }: NAL unit payload ranges between start codes +-- (00 00 01, with any leading zero bytes); trailing zero bytes of a NAL are dropped. +function Bitstream.splitAnnexB(buf: buffer, off: number, len: number): { number } + local out = {} + local e = off + len + local i = off + local start = -1 + while i + 2 < e do + local b2 = readu8(buf, i + 2) + if b2 > 1 then + i += 3 + elseif readu8(buf, i + 1) ~= 0 then + i += 2 + elseif b2 == 1 and readu8(buf, i) == 0 then + if start >= 0 then + local j = i + while j > start and readu8(buf, j - 1) == 0 do + j -= 1 + end + if j > start then + table.insert(out, start) + table.insert(out, j - start) + end + end + start = i + 3 + i += 3 + else + i += 1 + end + end + if start >= 0 then + local j = e + while j > start and readu8(buf, j - 1) == 0 do + j -= 1 + end + if j > start then + table.insert(out, start) + table.insert(out, j - start) + end + end + return out +end + +-- isAnnexB(buf, off, len) -> true when the data starts with a start code (00 00 01 or 00 00 00 01) +function Bitstream.isAnnexB(buf: buffer, off: number, len: number): boolean + if len >= 3 and readu8(buf, off) == 0 and readu8(buf, off + 1) == 0 then + local b2 = readu8(buf, off + 2) + if b2 == 1 then + return true + end + return b2 == 0 and len >= 4 and readu8(buf, off + 3) == 1 + end + return false +end + +-- splitLength(buf, off, len, size) -> NAL ranges of a length-prefixed (AVCC / MP4 sample) buffer, or nil when a +-- length runs past the end (the NALs before it are kept in the second result) +function Bitstream.splitLength(buf: buffer, off: number, len: number, size: number): ({ number }?, { number }) + local out = {} + local e = off + len + local p = off + while p + size <= e do + local n = 0 + for k = 0, size - 1 do + n = n * 256 + readu8(buf, p + k) + end + p += size + if n > e - p then + return nil, out + end + if n > 0 then + table.insert(out, p) + table.insert(out, n) + end + p += n + end + return out, out +end + +-- parseAvcC(buf, off, len) -> { lengthSize, profile, level, nals = { off, len, ... } (SPS then PPS, + SPS ext) } | +-- nil, message +function Bitstream.parseAvcC(buf: buffer, off: number, len: number): (any, string?) + if len < 7 then + return nil, "truncated: avcC shorter than 7 bytes" + end + if readu8(buf, off) ~= 1 then + return nil, "avcC configurationVersion is not 1" + end + local cfg = { + profile = readu8(buf, off + 1), + compat = readu8(buf, off + 2), + level = readu8(buf, off + 3), + lengthSize = band(readu8(buf, off + 4), 3) + 1, + nals = {} :: { number }, + } + local p = off + 5 + local e = off + len + for pass = 1, 2 do + if p >= e then + return nil, "truncated: avcC parameter set count" + end + local count = if pass == 1 then band(readu8(buf, p), 31) else readu8(buf, p) + p += 1 + for _ = 1, count do + if p + 2 > e then + return nil, "truncated: avcC parameter set length" + end + local n = readu8(buf, p) * 256 + readu8(buf, p + 1) + p += 2 + if p + n > e then + return nil, "truncated: avcC parameter set" + end + table.insert(cfg.nals, p) + table.insert(cfg.nals, n) + p += n + end + end + return cfg, nil +end + +-- ------------------------------------------------------------------------------------------------ rbsp +-- reader(buf, off, len, skip) -> Reader over the RBSP of a NAL unit's bytes [off, off + len), the first `skip` +-- bytes (the NAL header) left out; emulation_prevention_three_byte (00 00 03) removed. +function Bitstream.reader(buf: buffer, off: number, len: number, skip: number): Reader + local out = buffer.create(len + 8) + local o = 0 + local zeros = 0 + for i = off + skip, off + len - 1 do + local b = readu8(buf, i) + if zeros >= 2 and b == 3 then + zeros = 0 + else + buffer.writeu8(out, o, b) + o += 1 + if b == 0 then + zeros += 1 + else + zeros = 0 + end + end + end + -- the rbsp_stop_one_bit: the last set bit of the last non-zero byte + local stop = o * 8 + local j = o - 1 + while j >= 0 and readu8(out, j) == 0 do + j -= 1 + end + if j >= 0 then + local b = readu8(out, j) + local k = 0 + while band(b, lshift(1, k)) == 0 do + k += 1 + end + stop = j * 8 + 7 - k + end + return { buf = out, pos = 0, size = o * 8, stop = stop, n = o + 8 } +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 + return 0 + end + local b = r.buf + 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 +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) + r.pos += n + if n >= 32 then + return v + end + return rshift(v, 32 - 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) + if p >= r.n then + return 0 + end + return band(rshift(readu8(r.buf, p), 7 - band(pos, 7)), 1) +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) + if v == 0 then + r.pos += 32 + return 4294967296 + end + local lz = countlz(v) + if lz < 16 then + local n = 2 * lz + 1 + r.pos += n + return rshift(v, 32 - n) - 1 + end + r.pos += lz + v = peek32(r) + r.pos += lz + 1 + return rshift(v, 31 - lz) - 1 +end +Bitstream.ue = ue + +-- se(r) -> se(v) +function Bitstream.se(r: Reader): number + local k = ue(r) + if k % 2 == 1 then + return (k + 1) // 2 + end + return -(k // 2) +end + +-- te(r, range) -> te(v) with the given range (max value) +function Bitstream.te(r: Reader, range: number): number + if range == 1 then + return 1 - Bitstream.u1(r) + end + return ue(r) +end + +-- moreData(r) -> more_rbsp_data() +function Bitstream.moreData(r: Reader): boolean + return r.pos < r.stop +end + +return Bitstream diff --git a/src/Formats/codecs/H264/Cabac.luau b/src/Formats/codecs/H264/Cabac.luau new file mode 100644 index 0000000..dc63209 --- /dev/null +++ b/src/Formats/codecs/H264/Cabac.luau @@ -0,0 +1,1119 @@ +--!strict +--!native +--!optimize 2 +-- codecs/H264/Cabac: slice data and macroblock layer with CABAC entropy coding (ITU-T H.264 7.3.4, 7.3.5, 9.3): the +-- arithmetic decoding engine (9.3.1.2 / 9.3.3.2), context initialisation (9.3.1.1), the binarizations and context +-- index increments of every syntax element (9.3.2 / 9.3.3.1) and residual_block_cabac for 4x4, 8x8 and DC blocks. +-- Coefficients are dequantised as they are placed. Written from the spec; tables from Tables. +-- The engine keeps codIOffset with `nb` look-ahead bits (low = offset * 2^nb + next bits), so renormalisation is one +-- multiply and bytes are fetched one at a time. Never throws: returns false, "message" on bad data. +local Bitstream = require("@formats/codecs/H264/Bitstream") +local Tables = require("@formats/codecs/H264/Tables") +local Mb = require("@formats/codecs/H264/Mb") + +local readu8 = buffer.readu8 + +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 + +local Cabac = {} + +-- ------------------------------------------------------------------------------------------------ engine +local RANGE_LPS = Tables.RANGE_LPS +local TRANS = Tables.TRANS +local POW2 = table.create(40, 1) +for i = 0, 39 do + POW2[i + 1] = 2 ^ i +end +local NORM = table.create(512, 0) -- NORM[r + 1] = renormalisation shift of range r (r < 512) +for r = 1, 511 do + local s, v = 0, r + while v < 256 do + v *= 2 + s += 1 + end + NORM[r + 1] = s +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] +end + +-- the engine (one slice at a time) +local ebuf: buffer = buffer.create(1) +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 + end +end + +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 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 + 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 +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 + if enb < 8 then + refill() + end + return bin +end + +local function terminate(): number + local r = erange - 2 + local scaled = r * POW2[enb + 1] + if elow >= scaled then + erange = r + return 1 + end + if r < 256 then + r *= 2 + enb -= 1 + if enb < 8 then + refill() + end + end + erange = r + return 0 +end + +-- start the engine at byte p of the rbsp +local function engineInit(b: buffer, p: number, limit: number) + ebuf, epos, elimit = b, p, limit + elow, enb = 0, -9 + refill() + refill() + erange = 510 +end + +-- the bit position the spec's decoder is at (after a terminate bin of 1) +local function bitPos(): number + return epos * 8 - enb +end + +local function initContexts(sliceQp: number, model: number) + local init = Tables.CABAC_INIT + local qp = math.clamp(sliceQp, 0, 51) + for ctx = 0, 459 do + local m = init[ctx * 8 + model * 2 + 1] + local n = init[ctx * 8 + model * 2 + 2] + local pre = math.clamp((m * qp) // 16 + n, 1, 126) + if pre <= 63 then + ST[ctx + 1] = (63 - pre) * 2 + else + ST[ctx + 1] = (pre - 64) * 2 + 1 + end + end +end + +-- ------------------------------------------------------------------------------------------------ residual +local ZZ4, ZZ8 = Tables.ZIGZAG4, Tables.ZIGZAG8 +local SIG8, LAST8 = Tables.SIG8, Tables.LAST8 +local CAT_CBF = { 0, 4, 8, 12, 16 } +local CAT_SIG = { 0, 15, 29, 44, 47 } +local CAT_ABS = { 0, 10, 20, 30, 39 } +local MAXC = { 16, 15, 16, 4, 15, 64 } +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 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 + 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 + end + if decision(lastBase + linc) == 1 then + last = true + break + end + end + i += 1 + end + if not last then + n += 1 + SIGPOS[n] = maxc - 1 + end + local gt1, eq1 = 0, 0 + local half = div // 2 + local catMax = if cat == 3 then 3 else 4 + 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 + v = 1 + else + ctx = absBase + 5 + (if gt1 < catMax then gt1 else catMax) + local prefix = 1 + while prefix < 14 and decision(ctx) == 1 do + prefix += 1 + end + v = prefix + 1 + if prefix == 14 then + -- Exp-Golomb (k = 0) suffix + local kk = 0 + while bypass() == 1 do + v += POW2[kk + 1] + kk += 1 + if kk > 24 then + return -1 + end + end + while kk > 0 do + kk -= 1 + 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 + if mul then + out[base + p + 1] = (v * mul[p + 1] + half) // div + else + out[base + p + 1] = v + end + end + return n +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 +end +local function topAddr(S: any, M: any): number + return if M.aT then M.addr - S.mbW + 1 else 0 +end + +local function mbSkipFlag(S: any, M: any): number + local k = S.kind + local a, b = leftAddr(S, M), topAddr(S, M) + local inc = 0 + if a > 0 and k[a] ~= K_PSKIP and k[a] ~= K_BSKIP then + inc += 1 + end + 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) +end + +-- intra mb_type (I slice: prefix false, offset 3; P / B suffix: offset 17 / 32) -> 0..25 +local function intraType(S: any, M: any, off: number): number + local b0 + if off == 3 then + local k = S.kind + local a, b = leftAddr(S, M), topAddr(S, M) + local inc = 0 + if a > 0 and k[a] ~= K_I4 and k[a] ~= K_I8 then + inc += 1 + end + if b > 0 and k[b] ~= K_I4 and k[b] ~= K_I8 then + inc += 1 + end + b0 = decision(3 + inc) + else + b0 = decision(off) + end + if b0 == 0 then + return 0 + end + if terminate() == 1 then + return 25 + end + local luma, chroma, pred + if off == 3 then + luma = decision(6) + chroma = decision(7) + if chroma == 1 then + chroma += decision(8) + end + pred = decision(9) * 2 + pred += decision(10) + else + luma = decision(off + 1) + chroma = decision(off + 2) + if chroma == 1 then + chroma += decision(off + 2) + end + pred = decision(off + 3) * 2 + pred += decision(off + 3) + end + return 1 + pred + 4 * chroma + 12 * luma +end + +local function pMbType(): number + -- 0..3 inter, 5+ intra (returned as -1: the caller decodes the suffix) + if decision(14) == 1 then + return -1 + end + if decision(15) == 0 then + return if decision(16) == 0 then 0 else 3 + end + return if decision(17) == 1 then 1 else 2 +end + +local function bMbType(S: any, M: any): number + local k = S.kind + local a, b = leftAddr(S, M), topAddr(S, M) + local inc = 0 + if a > 0 and k[a] ~= K_BSKIP and k[a] ~= K_BDIRECT then + inc += 1 + end + if b > 0 and k[b] ~= K_BSKIP and k[b] ~= K_BDIRECT then + inc += 1 + end + if decision(27 + inc) == 0 then + return 0 + end + if decision(30) == 0 then + return 1 + decision(32) + end + local bits = decision(31) * 8 + bits += decision(32) * 4 + bits += decision(32) * 2 + bits += decision(32) + if bits < 8 then + return bits + 3 + elseif bits == 13 then + return -1 -- intra + elseif bits == 14 then + return 11 + elseif bits == 15 then + return 22 + end + bits = bits * 2 + decision(32) + return bits - 4 +end + +local function pSubType(): number + if decision(21) == 1 then + return 0 + end + if decision(22) == 0 then + return 1 + end + return if decision(23) == 1 then 2 else 3 +end + +local function bSubType(): number + if decision(36) == 0 then + return 0 + end + if decision(37) == 0 then + return 1 + decision(39) + end + local t = 3 + if decision(38) == 1 then + if decision(39) == 1 then + return 11 + decision(39) + end + t += 4 + end + t += 2 * decision(39) + t += decision(39) + return t +end + +-- ref_idx for the partition whose top-left 4x4 is (x, y); rgt: the ref > 0 grid of the list +local function refIdx(S: any, M: any, rgt: { number }, x: number, y: number): number + local g = M.g0 + y * S.w4 + x + local inc = 0 + if (x > 0 or M.aL) and rgt[g - 1] ~= 0 then + inc += 1 + end + if (y > 0 or M.aT) and rgt[g - S.w4] ~= 0 then + inc += 2 + end + if decision(54 + inc) == 0 then + return 0 + end + local v = 1 + local ctx = 58 + while decision(ctx) == 1 do + v += 1 + ctx = 59 + if v > 32 then + return -1 + end + end + return v +end + +-- mvd component (comp 0 x, 1 y) for the partition at (x, y); grid holds |mvd| (2 per 4x4) +local function mvd(S: any, M: any, grid: { number }, x: number, y: number, comp: number): number + local g = M.g0 + y * S.w4 + x + local sum = 0 + if x > 0 or M.aL then + sum += grid[2 * (g - 1) - 1 + comp] + end + 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 + if decision(base + inc) == 0 then + return 0 + end + local v = 1 + local ctx = base + 3 + while v < 9 and decision(ctx) == 1 do + v += 1 + if ctx < base + 6 then + ctx += 1 + end + end + if v >= 9 then + local k = 3 + while bypass() == 1 do + v += POW2[k + 1] + k += 1 + if k > 24 then + return 0 + end + end + while k > 0 do + k -= 1 + v += bypass() * POW2[k + 1] + end + end + if bypass() == 1 then + return -v + end + return v +end + +local function fillRegion(S: any, M: any, grid: { number }, x: number, y: number, w: number, h: number, v: number) + local w4 = S.w4 + for j = y, y + h - 1 do + local g = M.g0 + j * w4 + x + for i = 0, w - 1 do + grid[g + i] = v + end + end +end + +local function fillMvd(S: any, M: any, grid: { number }, x: number, y: number, w: number, h: number, ax: number, ay: number) + local w4 = S.w4 + for j = y, y + h - 1 do + local g = M.g0 + j * w4 + x + for i = 0, w - 1 do + grid[2 * (g + i) - 1] = ax + grid[2 * (g + i)] = ay + end + end +end + +local function cbpCabac(S: any, M: any): number + local cbpTab = S.cbpTab + local a, b = leftAddr(S, M), topAddr(S, M) + local luma = 0 + for b8 = 0, 3 do + 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 + condA = 1 + end + elseif a > 0 then + if bit32.band(cbpTab[a], bit32.lshift(1, b8 + 1)) == 0 then + condA = 1 + end + end + if by == 1 then + if bit32.band(luma, bit32.lshift(1, b8 - 2)) == 0 then + condB = 1 + end + elseif b > 0 then + if bit32.band(cbpTab[b], bit32.lshift(1, b8 + 2)) == 0 then + condB = 1 + end + end + if decision(73 + condA + 2 * condB) == 1 then + luma += bit32.lshift(1, b8) + 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 chroma = 0 + if decision(77 + inc) == 1 then + inc = (if ca == 2 then 1 else 0) + (if cb == 2 then 2 else 0) + chroma = 1 + decision(81 + inc) + end + return luma + 16 * chroma +end + +local function qpDelta(S: any): number + local k = 0 + if decision(60 + (if S.lastQpd then 1 else 0)) == 1 then + k = 1 + local ctx = 62 + while decision(ctx) == 1 do + k += 1 + ctx = 63 + if k > 104 then + return 999 + end + end + end + if k % 2 == 1 then + return (k + 1) // 2 + end + return -(k // 2) +end + +local function chromaPredMode(S: any, M: any): number + local a, b = leftAddr(S, M), topAddr(S, M) + local cpm, kind = S.cpmTab, S.kind + local inc = 0 + if a > 0 and kind[a] <= K_I16 and cpm[a] ~= 0 then + inc += 1 + end + if b > 0 and kind[b] <= K_I16 and cpm[b] ~= 0 then + inc += 1 + end + if decision(64 + inc) == 0 then + return 0 + end + if decision(67) == 0 then + return 1 + end + return 2 + decision(67) +end + +local function t8Flag(S: any, M: any): number + local a, b = leftAddr(S, M), topAddr(S, M) + local t8 = S.t8Tab + local inc = 0 + if a > 0 and t8[a] == 1 then + inc += 1 + end + if b > 0 and t8[b] == 1 then + inc += 1 + end + return decision(399 + inc) +end + +-- coded_block_flag condition of a neighbour: v = the neighbour's flag when its block is available +local function cbf(cat: number, condA: number, condB: number): number + return decision(85 + CAT_CBF[cat + 1] + condA + 2 * condB) +end + +-- luma 4x4 coded_block_flag neighbours of (bx, by) +local function lumaCond(S: any, M: any, bx: number, by: number, intra: boolean): (number, number) + local g = M.g0 + by * S.w4 + bx + local nzc = S.nzc + local ca, cb + if bx > 0 then + ca = if nzc[g - 1] ~= 0 then 1 else 0 + elseif M.aL then + ca = if nzc[g - 1] ~= 0 then 1 else 0 + else + ca = if intra then 1 else 0 + end + if by > 0 then + cb = if nzc[g - S.w4] ~= 0 then 1 else 0 + elseif M.aT then + cb = if nzc[g - S.w4] ~= 0 then 1 else 0 + else + cb = if intra then 1 else 0 + end + return ca, cb +end + +local function chromaCond(S: any, M: any, tab: { number }, bx: number, by: number, intra: boolean): (number, number) + local cw = S.cw4 + 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 + else + ca = if intra then 1 else 0 + end + if by > 0 or M.aT then + cb = if tab[g - cw] ~= 0 then 1 else 0 + else + cb = if intra then 1 else 0 + end + return ca, cb +end + +local function dcCond(S: any, M: any, bit: number, intra: boolean): (number, number) + local dc = S.dcTab + 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 + else + ca = if intra then 1 else 0 + end + if b > 0 then + cb = if bit32.band(dc[b], bit) ~= 0 then 1 else 0 + else + cb = if intra then 1 else 0 + end + return ca, cb +end + +-- ------------------------------------------------------------------------------------------------ residual +local function residuals(S: any, M: any): boolean + local kind = M.kind + local cbp = M.cbp + local intra = kind <= K_PCM + local dq = S.dq + local qp = M.qp + local w4, g0 = S.w4, M.g0 + local grid = S.nzc + local nz = M.nz + local c4 = M.c4 + local dcBits = 0 + if kind == K_I16 then + local ca, cb = dcCond(S, M, 1, intra) + if cbf(0, ca, cb) == 1 then + local n = block(0, M.dcY, 0, nil, 1) + if n < 0 then + return false + end + M.hasDcY = true + dcBits += 1 + end + end + local mul4 = dq.d4[if intra then 1 else 4][qp + 1] + if M.t8 == 1 then + local mul8 = dq.d8[if intra then 1 else 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 + 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 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 + 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 + local ca, cb = lumaCond(S, M, bx, by, intra) + if cbf(cat, ca, cb) == 1 then + n = block(cat, c4, blk * 16, mul4, 16) + if n < 0 then + return false + end + end + end + grid[g0 + by * w4 + bx] = if n > 0 then 1 else 0 + nz[blk + 1] = n + end + end + local chroma = cbp // 16 + local cw, c0 = S.cw4, M.c0 + local nzc = M.nzc + if chroma ~= 0 then + for plane = 0, 1 do + local bit = if plane == 0 then 2 else 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) + if n < 0 then + return false + end + M.hasDcC = true + dcBits += bit + end + end + 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] + for blk = 0, 3 do + local bx, by = blk % 2, blk // 2 + local n = 0 + if chroma == 2 then + local ca, cb = chromaCond(S, M, tab, bx, by, intra) + if cbf(4, ca, cb) == 1 then + n = block(4, cc, (plane * 4 + blk) * 16, mulc, 16) + if n < 0 then + return false + end + end + end + tab[c0 + by * cw + bx] = if n > 0 then 1 else 0 + nzc[plane * 4 + blk + 1] = n + end + end + S.dcTab[M.addr + 1] = dcBits + return true +end + +local function setQp(S: any, M: any, delta: number): boolean + if delta < -26 or delta > 25 then + return false + end + local qp = (S.qp + delta + 52) % 52 + S.qp = qp + M.qp = qp + M.qpc = S.qpcOf[qp + 1] + M.qpc2 = S.qpc2Of[qp + 1] + S.lastQpd = delta ~= 0 + return true +end + +local function clearCounts(M: any) + local nz = M.nz + for i = 1, 16 do + nz[i] = 0 + end + local nzc = M.nzc + for i = 1, 8 do + nzc[i] = 0 + end +end + +-- ------------------------------------------------------------------------------------------------ macroblock +local SUBB_PF = { 0, 1, 2, 3, 1, 1, 2, 2, 3, 3, 1, 2, 3 } +local SUBB_SHAPE = { 0, 0, 0, 0, 1, 2, 1, 2, 1, 2, 3, 3, 3 } +local SUB_N = { 1, 2, 2, 4 } +local SUB_W = { 2, 2, 1, 1 } +local SUB_H = { 2, 1, 2, 1 } +local BPAIR0 = { 1, 2, 1, 2, 1, 2, 3, 3, 3 } +local BPAIR1 = { 1, 2, 2, 1, 3, 3, 1, 2, 3 } + +local function intraMb(S: any, M: any, r: Bitstream.Reader, t: number): (boolean, string?) + local addr = M.addr + 1 + local w4, g0 = S.w4, M.g0 + fillRegion(S, M, S.rgt0, 0, 0, 4, 4, 0) + fillRegion(S, M, S.rgt1, 0, 0, 4, 4, 0) + fillMvd(S, M, S.mvd0, 0, 0, 4, 4, 0, 0) + fillMvd(S, M, S.mvd1, 0, 0, 4, 4, 0, 0) + clearCounts(M) + if t == 25 then + M.kind = K_PCM + -- pcm_alignment_zero_bit and the samples follow the terminate bin + local p = (bitPos() + 7) // 8 + if p + 384 > elimit then + return false, "truncated: I_PCM samples" + end + buffer.copy(M.pcm, 0, ebuf, p, 384) + engineInit(ebuf, p + 384, elimit) + M.qp = S.qp + M.qpc, M.qpc2 = 0, 0 + M.cbp = 0x2f + fillRegion(S, M, S.nzc, 0, 0, 4, 4, 16) + local cw, c0 = S.cw4, M.c0 + for j = 0, 1 do + for i = 0, 1 do + S.nzcCb[c0 + j * cw + i] = 16 + S.nzcCr[c0 + j * cw + i] = 16 + end + end + S.cbpTab[addr] = 0x2f + S.dcTab[addr] = 7 + S.cpmTab[addr] = 0 + S.lastQpd = false + Mb.recon(S, M) + return true + end + if t == 0 then + M.kind = K_I4 + if S.t8mode and t8Flag(S, M) == 1 then + M.kind = K_I8 + M.t8 = 1 + end + local ipm = M.ipm + local grid = S.ipm + if M.t8 == 1 then + for i8 = 0, 3 do + local bx, by = (i8 % 2) * 2, (i8 // 2) * 2 + local pred = Mb.predMode(S, M, bx, by) + local mode = pred + if decision(68) == 0 then + local rem = decision(69) + rem += decision(69) * 2 + rem += decision(69) * 4 + mode = if rem < pred then rem else rem + 1 + end + ipm[by * 4 + bx + 1] = mode + local g = g0 + by * w4 + bx + grid[g], grid[g + 1], grid[g + w4], grid[g + w4 + 1] = mode, mode, mode, mode + end + else + for i = 0, 15 do + local bx, by = BLK_X[i + 1], BLK_Y[i + 1] + local pred = Mb.predMode(S, M, bx, by) + local mode = pred + if decision(68) == 0 then + local rem = decision(69) + rem += decision(69) * 2 + rem += decision(69) * 4 + mode = if rem < pred then rem else rem + 1 + end + ipm[by * 4 + bx + 1] = mode + grid[g0 + by * w4 + bx] = mode + end + end + M.cpm = chromaPredMode(S, M) + S.cpmTab[addr] = M.cpm + M.cbp = cbpCabac(S, M) + 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.cpm = chromaPredMode(S, M) + S.cpmTab[addr] = M.cpm + end + S.cbpTab[addr] = M.cbp + S.kind[addr] = M.kind + if M.cbp > 0 or M.kind == K_I16 then + if not setQp(S, M, qpDelta(S)) then + return false, "mb_qp_delta out of range" + end + else + setQp(S, M, 0) + end + S.t8Tab[addr] = M.t8 + if not residuals(S, M) then + return false, "bad residual" + end + Mb.recon(S, M) + return true +end + +local function interMb(S: any, M: any, r: Bitstream.Reader, t: number, isB: boolean): (boolean, string?) + clearCounts(M) + local n0, n1 = S.n0, S.n1 + local pf, sub, dir, ref0, ref1, mvd0, mvd1 = M.pf, M.sub, M.dir, M.ref0, M.ref1, M.mvd0, M.mvd1 + local rgt0, rgt1, g0, g1 = S.rgt0, S.rgt1, S.mvd0, S.mvd1 + for i = 1, 4 do + dir[i] = false + ref0[i], ref1[i] = 0, 0 + pf[i] = 0 + end + for i = 1, 32 do + mvd0[i], mvd1[i] = 0, 0 + end + local noSmall = true + local addr = M.addr + 1 + if isB and t == 0 then + M.kind = K_BDIRECT + M.part = 0 + noSmall = S.direct8x8 + fillRegion(S, M, rgt0, 0, 0, 4, 4, 0) + fillRegion(S, M, rgt1, 0, 0, 4, 4, 0) + 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 + if not isB then + M.part = t + pf[1], pf[2] = 1, 1 + elseif t <= 3 then + M.part = 0 + pf[1] = t + else + M.part = if t % 2 == 0 then 1 else 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 + 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 + for p = 1, n do + local x, y, w, h = 0, 0, 4, 4 + if part == 1 then + y, h = (p - 1) * 2, 2 + 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 v = 0 + if uses and nr > 1 then + v = refIdx(S, M, rgt, x, y) + if v < 0 or v >= nr then + return false, "ref_idx out of range" + end + end + refs[p] = v + fillRegion(S, M, rgt, x, y, w, h, if uses and v > 0 then 1 else 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 + for p = 1, n do + local x, y, w, h = 0, 0, 4, 4 + if part == 1 then + y, h = (p - 1) * 2, 2 + 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 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) + end + end + else + -- P_8x8 (3) / P_8x8ref0 (4) / B_8x8 (22) + M.kind = if isB then K_B else K_P + M.part = 3 + for i = 1, 4 do + if isB then + local s = bSubType() + pf[i] = SUBB_PF[s + 1] + sub[i] = SUBB_SHAPE[s + 1] + dir[i] = s == 0 + if s == 0 then + if not S.direct8x8 then + noSmall = false + end + elseif SUB_N[sub[i] + 1] > 1 then + noSmall = false + end + else + local s = pSubType() + pf[i] = 1 + sub[i] = s + if s > 0 then + noSmall = false + end + 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 + 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 v = 0 + if uses and nr > 1 then + v = refIdx(S, M, rgt, x, y) + if v < 0 or v >= nr then + return false, "ref_idx out of range" + end + end + refs[i] = v + fillRegion(S, M, rgt, x, y, 2, 2, if uses and v > 0 then 1 else 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 + 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) + if not uses then + fillMvd(S, M, grid, x0, y0, 2, 2, 0, 0) + else + local s = sub[i] + local w, h = SUB_W[s + 1], SUB_H[s + 1] + for k = 0, SUB_N[s + 1] - 1 do + local x, y = x0, y0 + if s == 1 then + y += k + elseif s == 2 then + x += k + elseif s == 3 then + x += k % 2 + y += k // 2 + end + local mx = mvd(S, M, grid, x, y, 0) + 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) + end + end + end + end + end + S.kind[addr] = M.kind + M.cbp = cbpCabac(S, M) + S.cbpTab[addr] = M.cbp + S.cpmTab[addr] = 0 + M.t8 = 0 + if M.cbp % 16 ~= 0 and S.t8mode and noSmall then + M.t8 = t8Flag(S, M) + end + S.t8Tab[addr] = M.t8 + if M.cbp > 0 then + if not setQp(S, M, qpDelta(S)) then + return false, "mb_qp_delta out of range" + end + else + setQp(S, M, 0) + end + if not residuals(S, M) then + return false, "bad residual" + end + Mb.recon(S, M) + return true +end + +local function macroblock(S: any, M: any, r: Bitstream.Reader): (boolean, string?) + local st = S.type + if st == 2 then + return intraMb(S, M, r, intraType(S, M, 3)) + elseif st == 0 then + local t = pMbType() + if t < 0 then + return intraMb(S, M, r, intraType(S, M, 17)) + end + return interMb(S, M, r, t, false) + end + local t = bMbType(S, M) + if t < 0 then + return intraMb(S, M, r, intraType(S, M, 32)) + end + return interMb(S, M, r, t, true) +end + +-- slice(S, M, r) -> true | false, message +function Cabac.slice(S: any, M: any, r: Bitstream.Reader): (boolean, string?) + local p = (r.pos + 7) // 8 + local limit = r.size // 8 + if p >= limit then + return false, "truncated: slice data" + end + engineInit(r.buf, p, limit) + initContexts(S.qp, if S.type == 2 then 0 else 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 + while true do + if addr >= total then + return false, "slice data past the end of the picture" + end + Mb.start(S, M, addr) + if st ~= 2 and mbSkipFlag(S, M) == 1 then + Mb.skip(S, M, skipKind) + S.lastQpd = false + else + local ok, err = macroblock(S, M, r) + if not ok then + return false, err + end + end + addr += 1 + if epos > elimit + 8 then + return false, "truncated: slice data" + end + if terminate() == 1 then + break + end + end + return true +end + +return Cabac diff --git a/src/Formats/codecs/H264/Cavlc.luau b/src/Formats/codecs/H264/Cavlc.luau new file mode 100644 index 0000000..8d3f98e --- /dev/null +++ b/src/Formats/codecs/H264/Cavlc.luau @@ -0,0 +1,779 @@ +--!strict +--!native +--!optimize 2 +-- codecs/H264/Cavlc: slice data and macroblock layer with CAVLC entropy coding (ITU-T H.264 7.3.4, 7.3.5, 9.2): +-- mb_skip_run, mb_type / sub_mb_type, intra modes, ref_idx (te), mvd, coded_block_pattern (me), mb_qp_delta and +-- residual_block_cavlc (coeff_token, level_prefix / suffix, total_zeros, run_before) with the 8x8 interleaving. +-- Coefficients are dequantised as they are placed. Written from the spec; VLC tables from Tables. +-- Never throws: returns false, "message" on bad data. +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 +local BLK_X, BLK_Y = Mb.BLK_X, Mb.BLK_Y + +local Cavlc = {} + +-- ------------------------------------------------------------------------------------------------ vlc tables +-- build(entries) -> l1, l2: a two-level lookup on 16 peeked bits. l1[(v >> 8) + 1] = value * 32 + length, or +-- -(base) of a second-level block l2[base + (v & 255)]; 0 = no code +local function build(entries: { { number } }): ({ number }, { number }) + local l1 = table.create(256, 0) + local l2 = {} + local nsub = 0 + for _, e in entries do + local code, len, val = e[1], e[2], e[3] + local packed = val * 32 + len + if len <= 8 then + local s = code * 2 ^ (8 - len) + for k = 0, 2 ^ (8 - len) - 1 do + l1[s + k + 1] = packed + end + else + local prefix = code // 2 ^ (len - 8) + local base = -l1[prefix + 1] + if base <= 0 then + base = nsub * 256 + 1 + nsub += 1 + for k = 0, 255 do + l2[base + k] = 0 + end + l1[prefix + 1] = -base + end + local s = (code % 2 ^ (len - 8)) * 2 ^ (16 - len) + for k = 0, 2 ^ (16 - len) - 1 do + l2[base + s + k] = packed + end + end + end + return l1, l2 +end + +-- coeff_token: CT1[class + 1], CT2[class + 1]; value = TotalCoeff * 4 + TrailingOnes +local CT1, CT2 = {}, {} +for t = 0, 4 do + local src = (Tables :: any)["COEFF_TOKEN_" .. t] + local entries = {} + for i = 1, #src, 4 do + table.insert(entries, { src[i], src[i + 1], src[i + 2] * 4 + src[i + 3] }) + end + CT1[t + 1], CT2[t + 1] = build(entries) +end + +-- total_zeros by tzVlcIndex (luma 1..15, chroma DC 1..3), run_before by min(zerosLeft, 7) +local function group(src: { number }, n: number): ({ { number } }, { { number } }) + local per = {} + for i = 1, n do + per[i] = {} + end + for i = 1, #src, 4 do + table.insert(per[src[i]], { src[i + 1], src[i + 2], src[i + 3] }) + end + local a, b = {}, {} + for i = 1, n do + a[i], b[i] = build(per[i]) + end + return a, b +end +local TZ1, TZ2 = group(Tables.TOTAL_ZEROS, 15) +local TZC1, TZC2 = group(Tables.TOTAL_ZEROS_CDC, 3) +local RB1, RB2 = group(Tables.RUN_BEFORE, 7) + +-- scans: coefficient index (1-based) -> raster position (0-based) +local ZZ4 = Tables.ZIGZAG4 +local ZZAC = table.create(15, 0) +for i = 1, 15 do + ZZAC[i] = ZZ4[i + 1] +end +local ZZ8I = {} -- [i4 + 1][k + 1] = raster position in the 8x8 block of the k-th coefficient of interleaved list i4 +for i4 = 0, 3 do + local t = table.create(16, 0) + for k = 0, 15 do + t[k + 1] = Tables.ZIGZAG8[4 * k + i4 + 1] + end + ZZ8I[i4 + 1] = t +end +local IDENT = { 0, 1, 2, 3 } + +local INTRA_CBP, INTER_CBP = Tables.INTRA_CBP, Tables.INTER_CBP + +-- ------------------------------------------------------------------------------------------------ residual +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 + +-- 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) +local function residual(r: Bitstream.Reader, nC: number, maxCoeff: number, out: { number }, base: number, scan: { number }, mul: { number }?, div: number): number + local b, n = r.buf, r.n + local pos = r.pos + local cls + if nC < 0 then + cls = 5 + elseif nC < 2 then + cls = 1 + elseif nC < 4 then + cls = 2 + elseif nC < 8 then + cls = 3 + else + cls = 4 + end + local v = rshift(peek(b, n, pos), 16) + local e = CT1[cls][rshift(v, 8) + 1] + if e < 0 then + e = CT2[cls][-e + band(v, 255)] + end + if e == 0 then + return -1 + end + pos += e % 32 + local tok = e // 32 + local tc = tok // 4 + local t1 = tok % 4 + if tc == 0 then + r.pos = pos + return 0 + end + if tc > maxCoeff then + return -1 + end + -- 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 + end + pos += t1 + local suffixLength = if tc > 10 and t1 < 3 then 1 else 0 + for i = t1, tc - 1 do + w = peek(b, n, pos) + local prefix = countlz(w) + if prefix > 28 then + return -1 + end + pos += prefix + 1 + local size = suffixLength + if prefix == 14 and suffixLength == 0 then + size = 4 + elseif prefix >= 15 then + size = prefix - 3 + end + local levelCode = (if prefix < 15 then prefix else 15) * 2 ^ suffixLength + if size > 0 then + levelCode += rshift(peek(b, n, pos), 32 - size) + pos += size + end + if prefix >= 15 and suffixLength == 0 then + levelCode += 15 + end + if prefix >= 16 then + levelCode += 2 ^ (prefix - 3) - 4096 + end + if i == t1 and t1 < 3 then + levelCode += 2 + end + local level + if levelCode % 2 == 0 then + level = (levelCode + 2) // 2 + else + level = -((levelCode + 1) // 2) + end + LEVEL[i + 1] = level + if suffixLength == 0 then + suffixLength = 1 + end + local a = if level < 0 then -level else level + if a > 3 * 2 ^ (suffixLength - 1) and suffixLength < 6 then + suffixLength += 1 + end + end + -- total_zeros + local zerosLeft = 0 + if tc < maxCoeff then + v = rshift(peek(b, n, pos), 16) + 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] + if e < 0 then + e = l2[-e + band(v, 255)] + end + if e == 0 then + return -1 + end + pos += e % 32 + zerosLeft = e // 32 + if zerosLeft + tc > maxCoeff then + return -1 + end + end + -- run_before + 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] + if e < 0 then + e = RB2[t][-e + band(v, 255)] + end + if e == 0 then + return -1 + end + pos += e % 32 + run = e // 32 + if run > zerosLeft then + return -1 + end + end + RUN[i + 1] = run + zerosLeft -= run + end + RUN[tc] = zerosLeft + r.pos = pos + -- place (highest frequency first) + local k = -1 + local half = div // 2 + for i = tc - 1, 0, -1 do + k += RUN[i + 1] + 1 + local p = scan[k + 1] + if mul then + out[base + p + 1] = (LEVEL[i + 1] * mul[p + 1] + half) // div + else + out[base + p + 1] = LEVEL[i + 1] + end + end + return tc +end +Cavlc.residual = residual + +-- ------------------------------------------------------------------------------------------------ macroblock +local SUBB_PF = { 0, 1, 2, 3, 1, 1, 2, 2, 3, 3, 1, 2, 3 } +local SUBB_SHAPE = { 0, 0, 0, 0, 1, 2, 1, 2, 1, 2, 3, 3, 3 } +local SUB_N = { 1, 2, 2, 4 } +local BPAIR0 = { 1, 2, 1, 2, 1, 2, 3, 3, 3 } +local BPAIR1 = { 1, 2, 2, 1, 3, 3, 1, 2, 3 } + +local function refIdx(r: Bitstream.Reader, n: number): number + if n <= 1 then + return 0 + end + local v + if n == 2 then + v = 1 - u1(r) + else + v = ue(r) + end + if v >= n then + return -1 + end + return v +end + +-- the residual of the parsed macroblock +local function residuals(S: any, M: any, r: Bitstream.Reader): (boolean, string?) + local kind = M.kind + local cbp = M.cbp + local intra = kind <= K_PCM + local dq = S.dq + local qp = M.qp + local w4, g0 = S.w4, M.g0 + local grid = S.nzc + local nz = M.nz + local c4 = M.c4 + if kind == K_I16 then + local tc = residual(r, Mb.nC(S, M, 0, 0), 16, M.dcY, 0, ZZ4, nil, 1) + if tc < 0 then + return false, "bad Intra16x16 DC residual" + end + M.hasDcY = tc > 0 + end + local mul4 = dq.d4[if intra then 1 else 4][qp + 1] + if M.t8 == 1 then + local mul8 = dq.d8[if intra then 1 else 2][qp + 1] + local c8 = M.c8 + for i8 = 0, 3 do + local bx0, by0 = (i8 % 2) * 2, (i8 // 2) * 2 + local sum = 0 + 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 + 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" + end + end + grid[g0 + by * w4 + bx] = tc + sum += tc + end + nz[by0 * 4 + bx0 + 1] = sum + nz[by0 * 4 + bx0 + 2] = sum + nz[by0 * 4 + bx0 + 5] = sum + nz[by0 * 4 + bx0 + 6] = sum + end + else + local ac = kind == K_I16 + for i = 0, 15 do + 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 ac then + tc = residual(r, Mb.nC(S, M, bx, by), 15, c4, blk * 16, ZZAC, mul4, 16) + else + tc = residual(r, Mb.nC(S, M, bx, by), 16, c4, blk * 16, ZZ4, mul4, 16) + end + if tc < 0 then + return false, "bad luma residual" + end + end + grid[g0 + by * w4 + bx] = tc + nz[blk + 1] = tc + end + end + -- chroma + local chroma = cbp // 16 + local cw, c0 = S.cw4, M.c0 + local nzcCb, nzcCr = S.nzcCb, S.nzcCr + local nzc = M.nzc + if chroma ~= 0 then + local any = false + for plane = 0, 1 do + local tc = residual(r, -1, 4, M.dcC, plane * 4, IDENT, nil, 1) + if tc < 0 then + return false, "bad chroma DC residual" + end + if tc > 0 then + any = true + end + end + M.hasDcC = any + 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] + for blk = 0, 3 do + local bx, by = blk % 2, blk // 2 + local tc = 0 + if chroma == 2 then + tc = residual(r, Mb.nCc(S, M, tab, bx, by), 15, cc, (plane * 4 + blk) * 16, ZZAC, mulc, 16) + if tc < 0 then + return false, "bad chroma AC residual" + end + end + tab[c0 + by * cw + bx] = tc + nzc[plane * 4 + blk + 1] = tc + end + end + return true +end + +local function setQp(S: any, M: any, delta: number): boolean + if delta < -26 or delta > 25 then + return false + end + local qp = (S.qp + delta + 52) % 52 + S.qp = qp + M.qp = qp + M.qpc = S.qpcOf[qp + 1] + M.qpc2 = S.qpc2Of[qp + 1] + return true +end + +local function clearLumaGrids(S: any, M: any, intra: boolean) + -- the CABAC-only grids stay zero for CAVLC; intra modes for non-NxN macroblocks are written by Mb.recon + local _ = intra + local nz = M.nz + for i = 1, 16 do + nz[i] = 0 + end + local nzc = M.nzc + for i = 1, 8 do + nzc[i] = 0 + end +end + +-- intra(S, M, r, t): the intra macroblock types 0..25 (table 7-11) +local function intraMb(S: any, M: any, r: Bitstream.Reader, t: number): (boolean, string?) + local addr = M.addr + 1 + if t == 25 then + M.kind = K_PCM + r.pos = (r.pos + 7) // 8 * 8 + local p = r.pos // 8 + if p + 384 > r.size // 8 then + return false, "truncated: I_PCM samples" + end + buffer.copy(M.pcm, 0, r.buf, p, 384) + r.pos += 3072 + M.qp = S.qp + M.qpc, M.qpc2 = 0, 0 + M.cbp = 0x2f + local w4, g0 = S.w4, M.g0 + for j = 0, 3 do + for i = 0, 3 do + S.nzc[g0 + j * w4 + i] = 16 + end + end + local cw, c0 = S.cw4, M.c0 + for j = 0, 1 do + for i = 0, 1 do + S.nzcCb[c0 + j * cw + i] = 16 + S.nzcCr[c0 + j * cw + i] = 16 + end + end + S.cbpTab[addr] = 0x2f + S.dcTab[addr] = 7 + S.cpmTab[addr] = 0 + S.qpdTab[addr] = 0 + Mb.recon(S, M) + return true + end + clearLumaGrids(S, M, true) + if t == 0 then + M.kind = K_I4 + if S.t8mode and u1(r) == 1 then + M.kind = K_I8 + M.t8 = 1 + end + local ipm = M.ipm + local grid = S.ipm + local w4, g0 = S.w4, M.g0 + if M.t8 == 1 then + for i8 = 0, 3 do + local bx, by = (i8 % 2) * 2, (i8 // 2) * 2 + local pred = Mb.predMode(S, M, bx, by) + local mode = pred + if u1(r) == 0 then + local rem = u(r, 3) + mode = if rem < pred then rem else rem + 1 + end + ipm[by * 4 + bx + 1] = mode + local g = g0 + by * w4 + bx + grid[g], grid[g + 1], grid[g + w4], grid[g + w4 + 1] = mode, mode, mode, mode + end + else + for i = 0, 15 do + local bx, by = BLK_X[i + 1], BLK_Y[i + 1] + local pred = Mb.predMode(S, M, bx, by) + local mode = pred + if u1(r) == 0 then + local rem = u(r, 3) + mode = if rem < pred then rem else rem + 1 + end + ipm[by * 4 + bx + 1] = mode + grid[g0 + by * w4 + bx] = mode + end + end + M.cpm = ue(r) + if M.cpm > 3 then + return false, "intra_chroma_pred_mode out of range" + end + local code = ue(r) + if code > 47 then + return false, "coded_block_pattern out of range" + end + M.cbp = INTRA_CBP[code + 1] + 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.cpm = ue(r) + if M.cpm > 3 then + return false, "intra_chroma_pred_mode out of range" + end + else + return false, "mb_type out of range" + end + S.cpmTab[addr] = M.cpm + S.cbpTab[addr] = M.cbp + if M.cbp > 0 or M.kind == K_I16 then + if not setQp(S, M, Bitstream.se(r)) then + return false, "mb_qp_delta out of range" + end + else + setQp(S, M, 0) + end + if r.pos > r.size then + return false, "truncated: macroblock" + end + local ok, err = residuals(S, M, r) + if not ok then + return false, err + end + Mb.recon(S, M) + return true +end + +-- inter(S, M, r, t, isB): the P (0..4) and B (0..22) inter macroblock types +local function interMb(S: any, M: any, r: Bitstream.Reader, t: number, isB: boolean): (boolean, string?) + clearLumaGrids(S, M, false) + local n0, n1 = S.n0, S.n1 + local pf, sub, dir, ref0, ref1, mvd0, mvd1 = M.pf, M.sub, M.dir, M.ref0, M.ref1, M.mvd0, M.mvd1 + for i = 1, 4 do + dir[i] = false + ref0[i], ref1[i] = 0, 0 + end + for i = 1, 32 do + mvd0[i], mvd1[i] = 0, 0 + end + local noSmall = true + if not isB then + M.kind = K_P + if t > 4 then + return false, "mb_type out of range" + end + M.part = if t >= 3 then 3 else t + pf[1], pf[2], pf[3], pf[4] = 1, 1, 1, 1 + if M.part == 3 then + for i = 1, 4 do + local s = ue(r) + if s > 3 then + return false, "sub_mb_type out of range" + end + sub[i] = s + if s > 0 then + noSmall = false + end + end + for i = 1, 4 do + local v = if t == 4 then 0 else refIdx(r, n0) + if v < 0 then + return false, "ref_idx_l0 out of range" + end + ref0[i] = v + end + for i = 0, 3 do + for k = 0, SUB_N[sub[i + 1] + 1] - 1 do + local p = i * 4 + k + 1 + mvd0[2 * p - 1] = se(r) + mvd0[2 * p] = se(r) + end + end + else + local n = if M.part == 0 then 1 else 2 + for p = 1, n do + local v = refIdx(r, n0) + if v < 0 then + return false, "ref_idx_l0 out of range" + end + ref0[p] = v + end + for p = 1, n do + mvd0[2 * p - 1] = se(r) + mvd0[2 * p] = se(r) + end + end + else + if t == 0 then + M.kind = K_BDIRECT + M.part = 0 + if not S.direct8x8 then + noSmall = false + end + elseif t <= 21 then + M.kind = K_B + if t <= 3 then + M.part = 0 + pf[1] = t + else + M.part = if t % 2 == 0 then 1 else 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 + for p = 1, n do + if pf[p] % 2 == 1 then + local v = refIdx(r, n0) + if v < 0 then + return false, "ref_idx_l0 out of range" + end + ref0[p] = v + end + end + for p = 1, n do + if pf[p] >= 2 then + local v = refIdx(r, n1) + if v < 0 then + return false, "ref_idx_l1 out of range" + end + ref1[p] = v + end + end + for p = 1, n do + if pf[p] % 2 == 1 then + mvd0[2 * p - 1] = se(r) + mvd0[2 * p] = se(r) + end + end + for p = 1, n do + if pf[p] >= 2 then + mvd1[2 * p - 1] = se(r) + mvd1[2 * p] = se(r) + end + end + elseif t == 22 then + M.kind = K_B + M.part = 3 + for i = 1, 4 do + local s = ue(r) + if s > 12 then + return false, "sub_mb_type out of range" + end + pf[i] = SUBB_PF[s + 1] + sub[i] = SUBB_SHAPE[s + 1] + dir[i] = s == 0 + if s == 0 then + if not S.direct8x8 then + noSmall = false + end + elseif SUB_N[sub[i] + 1] > 1 then + noSmall = false + end + end + for i = 1, 4 do + if not dir[i] and pf[i] % 2 == 1 then + local v = refIdx(r, n0) + if v < 0 then + return false, "ref_idx_l0 out of range" + end + ref0[i] = v + end + end + for i = 1, 4 do + if not dir[i] and pf[i] >= 2 then + local v = refIdx(r, n1) + if v < 0 then + return false, "ref_idx_l1 out of range" + end + ref1[i] = v + end + end + for l = 0, 1 do + local mvd = if l == 0 then mvd0 else 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 + for k = 0, SUB_N[sub[i + 1] + 1] - 1 do + local p = i * 4 + k + 1 + mvd[2 * p - 1] = se(r) + mvd[2 * p] = se(r) + end + end + end + end + else + return false, "mb_type out of range" + end + end + local code = ue(r) + if code > 47 then + return false, "coded_block_pattern out of range" + end + M.cbp = INTER_CBP[code + 1] + M.t8 = 0 + if M.cbp % 16 ~= 0 and S.t8mode and noSmall then + M.t8 = u1(r) + end + local addr = M.addr + 1 + S.cbpTab[addr] = M.cbp + S.cpmTab[addr] = 0 + if M.cbp > 0 then + if not setQp(S, M, se(r)) then + return false, "mb_qp_delta out of range" + end + else + setQp(S, M, 0) + end + if r.pos > r.size then + return false, "truncated: macroblock" + end + local ok, err = residuals(S, M, r) + if not ok then + return false, err + end + Mb.recon(S, M) + return true +end + +-- macroblock(S, M, r) -> true | false, message +local function macroblock(S: any, M: any, r: Bitstream.Reader): (boolean, string?) + local t = ue(r) + local st = S.type + if st == 2 then + return intraMb(S, M, r, t) + elseif st == 0 then + if t >= 5 then + return intraMb(S, M, r, t - 5) + end + return interMb(S, M, r, t, false) + end + if t >= 23 then + return intraMb(S, M, r, t - 23) + end + return interMb(S, M, r, t, true) +end + +-- ------------------------------------------------------------------------------------------------ slice data +-- slice(S, M, r) -> true | false, message: decodes macroblocks from S.firstMb until the end of the slice data +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 more = true + repeat + if st ~= 2 then + local run = ue(r) + if run > total - addr then + return false, "mb_skip_run past the end of the picture" + end + for _ = 1, run do + Mb.start(S, M, addr) + Mb.skip(S, M, skipKind) + addr += 1 + end + if run > 0 then + more = Bitstream.moreData(r) + end + end + if more then + if addr >= total then + return false, "slice data past the end of the picture" + end + Mb.start(S, M, addr) + local ok, err = macroblock(S, M, r) + if not ok then + return false, err + end + addr += 1 + if r.pos > r.size then + return false, "truncated: slice data" + end + more = Bitstream.moreData(r) + end + until not more + return true +end + +return Cavlc diff --git a/src/Formats/codecs/H264/Deblock.luau b/src/Formats/codecs/H264/Deblock.luau new file mode 100644 index 0000000..fd0eb71 --- /dev/null +++ b/src/Formats/codecs/H264/Deblock.luau @@ -0,0 +1,263 @@ +--!strict +--!native +--!optimize 2 +-- codecs/H264/Deblock: the in-loop deblocking filter of ITU-T H.264 8.7 for frame macroblocks, 8-bit 4:2:0: +-- boundary strengths (8.7.2.1, from the per-4x4 intra / coefficient / reference / motion grids), alpha / beta / tC0 +-- (tables 8-16 / 8-17), the bS < 4 and bS = 4 luma and chroma filters, disable_deblocking_filter_idc 0 / 1 / 2 and the +-- slice alpha / beta offsets. Written from the spec. Runs over the whole picture in macroblock order once all its +-- slices are decoded (the result equals filtering each macroblock as it is decoded). +-- Never throws. +local Tables = require("@formats/codecs/H264/Tables") + +local readu8, writeu8 = buffer.readu8, buffer.writeu8 +local ALPHA, BETA, TC0 = Tables.ALPHA, Tables.BETA, Tables.TC0 + +local Deblock = {} + +local BS = table.create(4, 0) + +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 +end + +local function abs(v: number): number + return if v < 0 then -v else v +end + +-- 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 +-- strengths +local function luma(b: buffer, o: number, across: number, along: number, qp: number, aOff: number, bOff: number) + local indexA = clip3(0, 51, qp + aOff) + local alpha = ALPHA[indexA + 13] + local beta = BETA[clip3(0, 51, qp + bOff) + 13] + if alpha == 0 or beta == 0 then + return + end + for seg = 0, 3 do + local bS = BS[seg + 1] + if bS > 0 then + local tc0 = TC0[(indexA + 12) * 4 + bS + 1] + for k = 0, 3 do + local q = o + (seg * 4 + k) * along + local p0 = readu8(b, q - across) + local q0 = readu8(b, q) + local p1 = readu8(b, q - 2 * across) + local q1 = readu8(b, q + across) + if abs(p0 - q0) < alpha and abs(p1 - p0) < beta and abs(q1 - q0) < beta then + local p2 = readu8(b, q - 3 * across) + local q2 = readu8(b, q + 2 * across) + 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 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)) + if ap < beta then + writeu8(b, q - 2 * across, p1 + clip3(-tc0, tc0, (p2 + (p0 + q0 + 1) // 2 - 2 * p1) // 2)) + end + if aq < beta then + writeu8(b, q + across, q1 + clip3(-tc0, tc0, (q2 + (p0 + q0 + 1) // 2 - 2 * q1) // 2)) + end + else + local strong = abs(p0 - q0) < alpha // 4 + 2 + if ap < beta and strong then + local p3 = readu8(b, q - 4 * across) + writeu8(b, q - across, (p2 + 2 * p1 + 2 * p0 + 2 * q0 + q1 + 4) // 8) + writeu8(b, q - 2 * across, (p2 + p1 + p0 + q0 + 2) // 4) + writeu8(b, q - 3 * across, (2 * p3 + 3 * p2 + p1 + p0 + q0 + 4) // 8) + else + writeu8(b, q - across, (2 * p1 + p0 + q1 + 2) // 4) + end + if aq < beta and strong then + local q3 = readu8(b, q + 3 * across) + writeu8(b, q, (p1 + 2 * p0 + 2 * q0 + 2 * q1 + q2 + 4) // 8) + writeu8(b, q + across, (p0 + q0 + q1 + q2 + 2) // 4) + writeu8(b, q + 2 * across, (2 * q3 + 3 * q2 + q1 + q0 + p0 + 4) // 8) + else + writeu8(b, q, (2 * q1 + q0 + p1 + 2) // 4) + end + end + end + end + end + end +end + +-- chroma(b, o, across, along, qp, aOff, bOff): the 8 samples of one chroma edge (bS of luma segment i // 2) +local function chroma(b: buffer, o: number, across: number, along: number, qp: number, aOff: number, bOff: number) + local indexA = clip3(0, 51, qp + aOff) + local alpha = ALPHA[indexA + 13] + local beta = BETA[clip3(0, 51, qp + bOff) + 13] + if alpha == 0 or beta == 0 then + return + end + for i = 0, 7 do + local bS = BS[i // 2 + 1] + if bS > 0 then + local q = o + i * along + local p0 = readu8(b, q - across) + local q0 = readu8(b, q) + local p1 = readu8(b, q - 2 * across) + local q1 = readu8(b, q + across) + if abs(p0 - q0) < alpha and abs(p1 - p0) < beta and abs(q1 - q0) < beta then + if bS < 4 then + local tc = TC0[(indexA + 12) * 4 + bS + 1] + 1 + 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)) + else + writeu8(b, q - across, (2 * p1 + p0 + q1 + 2) // 4) + writeu8(b, q, (2 * q1 + q0 + p1 + 2) // 4) + end + end + end + end +end + +-- motionDiffers(pic, p, q) -> true when the 4x4 blocks p and q (grid indices) need bS 1 (8.7.2.1) +local function mvDiff(mvA: { number }, a: number, mvB: { number }, b: number): boolean + return abs(mvA[2 * a - 1] - mvB[2 * b - 1]) >= 4 or abs(mvA[2 * a] - mvB[2 * b]) >= 4 +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) + if np ~= nq then + return true + end + if np == 1 then + local pr, pm = pa, mv0 + if pa < 0 then + pr, pm = pb, mv1 + end + local qr, qm = qa, mv0 + if qa < 0 then + qr, qm = qb, mv1 + end + if pr ~= qr then + return true + end + return mvDiff(pm, p, qm, q) + elseif np == 0 then + return false + end + if not ((pa == qa and pb == qb) or (pa == qb and pb == qa)) then + return true + end + if pa ~= pb then + if pa == qa then + return mvDiff(mv0, p, mv0, q) or mvDiff(mv1, p, mv1, q) + end + return mvDiff(mv0, p, mv1, q) or mvDiff(mv1, p, mv0, q) + end + return (mvDiff(mv0, p, mv0, q) or mvDiff(mv1, p, mv1, q)) and (mvDiff(mv0, p, mv1, q) or mvDiff(mv1, p, mv0, q)) +end + +-- picture(S, pic, params): deblocks the whole picture. params[sliceNum] = { idc, alphaOffset, betaOffset } +function Deblock.picture(S: any, pic: any, params: { any }) + local mbW, mbH = S.mbW, S.mbH + local w4 = S.w4 + local kind, sliceTab, qpTab, qpcTab, qpc2Tab, t8Tab = S.kind, S.sliceTab, S.qpTab, S.qpcTab, S.qpc2Tab, S.t8Tab + local nzDb = S.nzDb + local ys, cs = pic.ys, pic.cs + local Y, U, V = pic.y, pic.u, pic.v + for my = 0, mbH - 1 do + for mx = 0, mbW - 1 do + local addr = my * mbW + mx + 1 + local sn = sliceTab[addr] + local prm = params[sn] + if sn == 0 or not prm or prm[1] == 1 then + continue + end + local idc, aOff, bOff = prm[1], prm[2], prm[3] + local intraQ = kind[addr] <= 4 + local t8 = t8Tab[addr] == 1 + local qpQ, qpcQ, qpc2Q = qpTab[addr], qpcTab[addr], qpc2Tab[addr] + local g0 = my * 4 * w4 + mx * 4 + 1 + local lo = pic.yo + my * 16 * ys + mx * 16 + 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 + if edgeOk and idc == 2 and sliceTab[nAddr] ~= sn then + edgeOk = false + end + if edgeOk and sliceTab[nAddr] == 0 then + edgeOk = false + end + for e = 0, 3 do + if e == 0 and not edgeOk then + continue + end + if t8 and (e == 1 or e == 3) then + continue + end + -- strengths of the four segments + local intraP = intraQ + local qpP, qpcP, qpc2P = qpQ, qpcQ, qpc2Q + if e == 0 then + intraP = kind[nAddr] <= 4 + qpP, qpcP, qpc2P = qpTab[nAddr], qpcTab[nAddr], qpc2Tab[nAddr] + end + local any = false + for k = 0, 3 do + local qg, pg + if dir == 0 then + qg = g0 + k * w4 + e + pg = qg - 1 + else + qg = g0 + e * w4 + k + pg = qg - w4 + end + local bS + if intraP or intraQ then + bS = if e == 0 then 4 else 3 + elseif nzDb[qg] ~= 0 or nzDb[pg] ~= 0 then + bS = 2 + elseif motionDiffers(pic, pg, qg) then + bS = 1 + else + bS = 0 + end + BS[k + 1] = bS + if bS > 0 then + any = true + end + end + if not any then + continue + end + local qpav = (qpP + qpQ + 1) // 2 + if dir == 0 then + luma(Y, lo + e * 4, 1, ys, qpav, aOff, bOff) + else + luma(Y, lo + e * 4 * ys, ys, 1, qpav, aOff, bOff) + end + if e % 2 == 0 then + local qc = (qpcP + qpcQ + 1) // 2 + local qc2 = (qpc2P + qpc2Q + 1) // 2 + if dir == 0 then + chroma(U, co + e * 2, 1, cs, qc, aOff, bOff) + chroma(V, co + e * 2, 1, cs, qc2, aOff, bOff) + else + chroma(U, co + e * 2 * cs, cs, 1, qc, aOff, bOff) + chroma(V, co + e * 2 * cs, cs, 1, qc2, aOff, bOff) + end + end + end + end + end + end +end + +return Deblock diff --git a/src/Formats/codecs/H264/Decoder.luau b/src/Formats/codecs/H264/Decoder.luau new file mode 100644 index 0000000..850b27d --- /dev/null +++ b/src/Formats/codecs/H264/Decoder.luau @@ -0,0 +1,1011 @@ +--!strict +-- codecs/H264/Decoder: the decoding process above the macroblock layer (ITU-T H.264 8.1, 8.2, C.4): NAL unit +-- dispatch, picture boundaries (7.4.1.2.4), picture order count types 0 / 1 / 2 (8.2.1), frame_num gaps (8.2.5.2), +-- reference picture lists with modification (8.2.4), sliding window and adaptive (MMCO 1-6) marking (8.2.5), output +-- in POC order through a reorder buffer (num_reorder_frames, else the DPB size), concealment of lost macroblocks, +-- deblocking and border extension. Written from the spec. +-- Never throws: errors are returned (a corrupt slice is skipped and its macroblocks concealed). +local Bitstream = require("@formats/codecs/H264/Bitstream") +local Params = require("@formats/codecs/H264/Params") +local Slice = require("@formats/codecs/H264/Slice") +local Tables = require("@formats/codecs/H264/Tables") +local Mb = require("@formats/codecs/H264/Mb") +local Cavlc = require("@formats/codecs/H264/Cavlc") +local Cabac = require("@formats/codecs/H264/Cabac") +local Deblock = require("@formats/codecs/H264/Deblock") +local Inter = require("@formats/codecs/H264/Inter") +local Types = require("@formats/Types") + +local PAD, PADC = Inter.PAD, Inter.PADC +local CHROMA_QP = Tables.CHROMA_QP + +local Decoder = {} +Decoder.__index = Decoder + +export type Options = { + maxPixels: number?, -- largest picture accepted (default 2^22: 4096 x 1024) + lowDelay: boolean?, -- output pictures in decoding order without reordering (only right for streams without B frames) + deblock: boolean?, -- false skips the loop filter (not conformant: faster, for previews); default true +} + +-- new(opts) -> decoder state +function Decoder.new(opts: Options?): any + local o = opts or {} + return setmetatable({ + opts = o, + maxPixels = o.maxPixels or 2 ^ 22, + spsTab = {}, + ppsTab = {}, + dqCache = {}, + cur = nil, + curSh = nil, + S = nil, + M = Mb.new(), + refs = {}, -- reference pictures (short and long term) + waiting = {}, -- decoded pictures not output yet + out = {}, + uid = 0, + prevRefFrameNum = 0, + prevPocMsb = 0, + prevPocLsb = 0, + prevFrameNumOffset = 0, + prevFrameNum = 0, + maxLongTermIdx = -1, + pool = {}, + gray = nil, + frames = 0, -- pictures decoded + errors = 0, + lastError = nil, + fatal = nil, + seqW = 0, + seqH = 0, + }, Decoder) +end + +-- ------------------------------------------------------------------------------------------------ pictures +local function newPicture(self: any, sps: any): any + local mbW, mbH = sps.mbWidth, sps.mbHeight + local pool = self.pool + for i = #pool, 1, -1 do + local p = pool[i] + if p.mbW == mbW and p.mbH == mbH then + table.remove(pool, i) + return p + end + end + local w, h = mbW * 16, mbH * 16 + local ys = w + 2 * PAD + local cs = w // 2 + 2 * PADC + local n4 = mbW * mbH * 16 + return { + mbW = mbW, + mbH = mbH, + ys = ys, + cs = cs, + yo = PAD * ys + PAD, + co = PADC * cs + PADC, + y = buffer.create(ys * (h + 2 * PAD)), + u = buffer.create(cs * (h // 2 + 2 * PADC)), + v = buffer.create(cs * (h // 2 + 2 * PADC)), + mbIntra = table.create(mbW * mbH, true), + ref0 = table.create(n4, -1), + ref1 = table.create(n4, -1), + uid0 = table.create(n4, -1), + uid1 = table.create(n4, -1), + mv0 = table.create(n4 * 2, 0), + mv1 = table.create(n4 * 2, 0), + uid = 0, + poc = 0, + frameNum = 0, + long = false, + short = false, + longIdx = 0, + waiting = false, + pts = 0, + } +end + +local function release(self: any, p: any) + if not p.short and not p.long and not p.waiting and p ~= self.cur and p ~= self.gray then + for _, q in self.pool do + if q == p then + return + end + end + table.insert(self.pool, p) + end +end + +local function grayPicture(self: any, sps: any): any + local g = self.gray + if g and g.mbW == sps.mbWidth and g.mbH == sps.mbHeight then + return g + end + g = newPicture(self, sps) + buffer.fill(g.y, 0, 128) + buffer.fill(g.u, 0, 128) + buffer.fill(g.v, 0, 128) + self.uid += 1 + g.uid = self.uid + self.gray = g + return g +end + +-- ------------------------------------------------------------------------------------------------ output +local function emit(self: any, p: any) + p.waiting = false + local sps = p.sps + local W, H = sps.width, sps.height + local img = Types.Image.new(W, H, "yuv420p") + local px = img.pixels + local cx, cy = sps.cropX, sps.cropY + for y = 0, H - 1 do + buffer.copy(px, y * W, p.y, p.yo + (cy + y) * p.ys + cx, W) + end + local cw, ch = (W + 1) // 2, (H + 1) // 2 + local ub, vb = W * H, W * H + cw * ch + for y = 0, ch - 1 do + buffer.copy(px, ub + y * cw, p.u, p.co + (cy // 2 + y) * p.cs + cx // 2, cw) + buffer.copy(px, vb + y * cw, p.v, p.co + (cy // 2 + y) * p.cs + cx // 2, cw) + end + img.meta.source = { format = "h264", bitDepth = 8, profile = sps.profile, level = sps.level, poc = p.poc, keyframe = p.idr } + if sps.sarW and sps.sarH then + img.meta.sar = { sps.sarW, sps.sarH } + end + table.insert(self.out, { image = img, pts = p.pts, duration = 0, poc = p.poc, keyframe = p.idr }) + release(self, p) +end + +local function bump(self: any, keep: number) + local w = self.waiting + while #w > keep do + local best = 1 + for i = 2, #w do + if w[i].poc < w[best].poc then + best = i + end + end + local p = table.remove(w, best) + emit(self, p) + end +end + +local function reorderDepth(self: any, sps: any): number + if self.opts.lowDelay then + return 0 + end + if sps.numReorderFrames then + return sps.numReorderFrames + end + if sps.pocType == 2 then + return 0 + end + return sps.maxDecFrameBuffering or sps.maxDpbFrames +end + +-- ------------------------------------------------------------------------------------------------ reference lists +local function shortRefs(self: any): { any } + local t = {} + for _, p in self.refs do + if p.short then + table.insert(t, p) + end + end + return t +end + +local function longRefs(self: any): { any } + local t = {} + for _, p in self.refs do + if p.long then + table.insert(t, p) + end + end + table.sort(t, function(a, b) + return a.longIdx < b.longIdx + end) + return t +end + +local function picNums(self: any, sh: any) + local maxFrameNum = 2 ^ sh.sps.log2MaxFrameNum + for _, p in self.refs do + if p.short then + p.picNum = if p.frameNum > sh.frameNum then p.frameNum - maxFrameNum else p.frameNum + end + end +end + +local function modify(self: any, list: { any }, ops: { number }, n: number, sh: any): boolean + if #ops == 0 then + return true + end + local maxPicNum = 2 ^ sh.sps.log2MaxFrameNum + local curr = sh.frameNum + local pred = curr + local idx = 0 + for i = 1, #ops, 2 do + local idc, v = ops[i], ops[i + 1] + local pic = nil + if idc == 0 or idc == 1 then + local absDiff = v + 1 + if absDiff > maxPicNum then + return false + end + local noWrap + if idc == 0 then + noWrap = pred - absDiff + if noWrap < 0 then + noWrap += maxPicNum + end + else + noWrap = pred + absDiff + if noWrap >= maxPicNum then + noWrap -= maxPicNum + end + end + pred = noWrap + local picNum = if noWrap > curr then noWrap - maxPicNum else noWrap + for _, p in self.refs do + if p.short and p.picNum == picNum then + pic = p + break + end + end + elseif idc == 2 then + for _, p in self.refs do + if p.long and p.longIdx == v then + pic = p + break + end + end + else + return false + end + if not pic then + return false + end + if idx >= n then + return false + end + table.insert(list, idx + 1, pic) + local k = idx + 2 + while k <= #list do + if list[k] == pic then + table.remove(list, k) + else + k += 1 + end + end + idx += 1 + end + return true +end + +-- buildLists(self, sh, cur) -> list0, list1 (arrays of pictures, truncated to num_ref_idx_active) +local function buildLists(self: any, sh: any, cur: any): ({ any }, { any }, boolean) + picNums(self, sh) + local list0, list1 = {}, {} + local shorts = shortRefs(self) + local longs = longRefs(self) + if sh.type == Slice.P then + table.sort(shorts, function(a, b) + return a.picNum > b.picNum + end) + for _, p in shorts do + table.insert(list0, p) + end + for _, p in longs do + table.insert(list0, p) + end + else + local before, after = {}, {} + for _, p in shorts do + if p.poc < cur.poc then + table.insert(before, p) + else + table.insert(after, p) + end + end + table.sort(before, function(a, b) + return a.poc > b.poc + end) + table.sort(after, function(a, b) + return a.poc < b.poc + end) + for _, p in before do + table.insert(list0, p) + end + for _, p in after do + table.insert(list0, p) + end + for _, p in after do + table.insert(list1, p) + end + for _, p in before do + table.insert(list1, p) + end + for _, p in longs do + table.insert(list0, p) + table.insert(list1, p) + end + if #list1 > 1 and #list0 == #list1 then + local same = true + for i = 1, #list0 do + if list0[i] ~= list1[i] then + same = false + break + end + end + if same then + list1[1], list1[2] = list1[2], list1[1] + end + end + end + local n0, n1 = sh.numRefIdxL0, sh.numRefIdxL1 + for i = #list0, n0 + 1, -1 do + list0[i] = nil + end + for i = #list1, n1 + 1, -1 do + list1[i] = nil + end + local ok = modify(self, list0, sh.mod0 or {}, n0, sh) + if sh.type == Slice.B then + ok = modify(self, list1, sh.mod1 or {}, n1, sh) and ok + end + for i = #list0, n0 + 1, -1 do + list0[i] = nil + end + for i = #list1, n1 + 1, -1 do + list1[i] = nil + end + return list0, list1, ok +end + +-- ------------------------------------------------------------------------------------------------ marking +local function unmark(self: any, p: any) + p.short = false + p.long = false + for i, q in self.refs do + if q == p then + table.remove(self.refs, i) + break + end + end + release(self, p) +end + +local function slidingWindow(self: any, sps: any, frameNum: number) + local maxRefs = math.max(sps.maxRefFrames, 1) + local maxFrameNum = 2 ^ sps.log2MaxFrameNum + while #self.refs >= maxRefs do + local oldest, ow = nil, math.huge + for _, p in self.refs do + if p.short then + local w = if p.frameNum > frameNum then p.frameNum - maxFrameNum else p.frameNum + if w < ow then + oldest, ow = p, w + end + end + end + if not oldest then + -- only long-term references left: drop the lowest index (bad stream) + oldest = self.refs[1] + end + unmark(self, oldest) + end +end + +local function addRef(self: any, p: any) + for _, q in self.refs do + if q == p then + return + end + end + table.insert(self.refs, p) +end + +-- mark(self, cur, sh): 8.2.5 after decoding the current (reference) picture; returns true when MMCO 5 was present +local function mark(self: any, cur: any, sh: any): boolean + local sps = sh.sps + if sh.idr then + while #self.refs > 0 do + unmark(self, self.refs[1]) + end + if sh.longTermReference then + cur.long = true + cur.longIdx = 0 + self.maxLongTermIdx = 0 + else + cur.short = true + self.maxLongTermIdx = -1 + end + addRef(self, cur) + return false + end + local mmco5 = false + local becameLong = false + if sh.adaptive and sh.mmco then + picNums(self, sh) + local ops = sh.mmco + for i = 1, #ops, 3 do + local op, a, b = ops[i], ops[i + 1], ops[i + 2] + if op == 1 then + local picNum = sh.frameNum - a + for _, p in self.refs do + if p.short and p.picNum == picNum then + unmark(self, p) + break + end + end + elseif op == 2 then + for _, p in self.refs do + if p.long and p.longIdx == a then + unmark(self, p) + break + end + end + elseif op == 3 then + local picNum = sh.frameNum - a + for _, p in self.refs do + if p.long and p.longIdx == b then + unmark(self, p) + break + end + end + for _, p in self.refs do + if p.short and p.picNum == picNum then + p.short = false + p.long = true + p.longIdx = b + break + end + end + elseif op == 4 then + self.maxLongTermIdx = a - 1 + local drop = {} + for _, p in self.refs do + if p.long and p.longIdx > self.maxLongTermIdx then + table.insert(drop, p) + end + end + for _, p in drop do + unmark(self, p) + end + elseif op == 5 then + while #self.refs > 0 do + unmark(self, self.refs[1]) + end + self.maxLongTermIdx = -1 + mmco5 = true + elseif op == 6 then + for _, p in self.refs do + if p.long and p.longIdx == b then + unmark(self, p) + break + end + end + cur.long = true + cur.longIdx = b + becameLong = true + end + end + else + slidingWindow(self, sps, sh.frameNum) + end + if not becameLong then + cur.short = true + end + -- a bad stream may leave too many references + local maxRefs = math.max(sps.maxRefFrames, 1) + if #self.refs >= maxRefs and not becameLong then + slidingWindow(self, sps, sh.frameNum) + end + addRef(self, cur) + return mmco5 +end + +-- ------------------------------------------------------------------------------------------------ poc +local function computePoc(self: any, sh: any): (number, number) + local sps = sh.sps + local maxFrameNum = 2 ^ sps.log2MaxFrameNum + if sps.pocType == 0 then + local prevMsb, prevLsb = self.prevPocMsb, self.prevPocLsb + if sh.idr then + prevMsb, prevLsb = 0, 0 + end + local maxLsb = 2 ^ sps.log2MaxPocLsb + local lsb = sh.pocLsb + local msb + if lsb < prevLsb and prevLsb - lsb >= maxLsb / 2 then + msb = prevMsb + maxLsb + elseif lsb > prevLsb and lsb - prevLsb > maxLsb / 2 then + msb = prevMsb - maxLsb + else + msb = prevMsb + end + local top = msb + lsb + local bottom = top + sh.deltaPocBottom + sh.pocMsb = msb + return math.min(top, bottom), top + end + local offset + if sh.idr then + offset = 0 + elseif self.prevFrameNum > sh.frameNum then + offset = self.prevFrameNumOffset + maxFrameNum + else + offset = self.prevFrameNumOffset + end + sh.frameNumOffset = offset + if sps.pocType == 1 then + local n = #sps.offsetsForRefFrame + local absFrameNum = if n ~= 0 then offset + sh.frameNum else 0 + if sh.nalRefIdc == 0 and absFrameNum > 0 then + absFrameNum -= 1 + end + local expected = 0 + if absFrameNum > 0 then + local cycle = (absFrameNum - 1) // n + local inCycle = (absFrameNum - 1) % n + expected = cycle * sps.expectedDeltaPerCycle + for i = 1, inCycle + 1 do + expected += sps.offsetsForRefFrame[i] + end + end + if sh.nalRefIdc == 0 then + expected += sps.offsetNonRef + end + local top = expected + sh.deltaPoc0 + local bottom = top + sps.offsetTopToBottom + sh.deltaPoc1 + return math.min(top, bottom), top + end + local t + if sh.idr then + t = 0 + elseif sh.nalRefIdc == 0 then + t = 2 * (offset + sh.frameNum) - 1 + else + t = 2 * (offset + sh.frameNum) + end + return t, t +end + +-- ------------------------------------------------------------------------------------------------ picture decode +local function setupGrids(self: any, sps: any) + local mbW, mbH = sps.mbWidth, sps.mbHeight + if self.S and self.S.mbW == mbW and self.S.mbH == mbH then + return + end + local S = Mb.grids(mbW, mbH) + S.mbW, S.mbH = mbW, mbH + S.w4 = mbW * 4 + S.cw4 = mbW * 2 + S.qpcOf = table.create(52, 0) + S.qpc2Of = table.create(52, 0) + self.S = S +end + +-- fill a frame_num gap with "non-existing" frames (8.2.5.2), concealed as copies of the latest reference +local function fillGap(self: any, sh: any) + local sps = sh.sps + local maxFrameNum = 2 ^ sps.log2MaxFrameNum + local fn = (self.prevRefFrameNum + 1) % maxFrameNum + local guard = 0 + while fn ~= sh.frameNum and guard < 32 do + guard += 1 + local src = nil + for _, p in self.refs do + if p.short and (src == nil or p.decodeOrder > src.decodeOrder) then + src = p + end + end + local p = newPicture(self, sps) + if src then + buffer.copy(p.y, 0, src.y) + buffer.copy(p.u, 0, src.u) + buffer.copy(p.v, 0, src.v) + else + local g = grayPicture(self, sps) + buffer.copy(p.y, 0, g.y) + buffer.copy(p.u, 0, g.u) + buffer.copy(p.v, 0, g.v) + end + for i = 1, #p.mbIntra do + p.mbIntra[i] = true + end + self.uid += 1 + p.uid = self.uid + p.frameNum = fn + p.poc = if src then src.poc else 0 + p.sps = sps + p.idr = false + p.decodeOrder = self.frames + p.long = false + slidingWindow(self, sps, fn) + p.short = true + addRef(self, p) + self.prevRefFrameNum = fn + self.prevFrameNum = fn + fn = (fn + 1) % maxFrameNum + end +end + +local function startPicture(self: any, sh: any, pts: number?) + local sps = sh.sps + if sps.mbWidth ~= self.seqW or sps.mbHeight ~= self.seqH then + -- a new sequence size: output everything, drop the references + bump(self, 0) + while #self.refs > 0 do + unmark(self, self.refs[1]) + end + self.pool = {} + self.seqW, self.seqH = sps.mbWidth, sps.mbHeight + end + setupGrids(self, sps) + if not sh.idr then + local maxFrameNum = 2 ^ sps.log2MaxFrameNum + if sh.frameNum ~= self.prevRefFrameNum and sh.frameNum ~= (self.prevRefFrameNum + 1) % maxFrameNum then + fillGap(self, sh) + end + end + local p = newPicture(self, sps) + self.uid += 1 + p.uid = self.uid + p.sps = sps + p.frameNum = sh.frameNum + p.idr = sh.idr + p.refIdc = sh.nalRefIdc + p.short, p.long, p.waiting = false, false, false + p.poc, p.topPoc = computePoc(self, sh) + p.pts = pts or self.frames + p.decodeOrder = self.frames + self.frames += 1 + self.cur = p + self.curSh = sh + self.decoded = 0 + self.sliceNum = 0 + self.sliceParams = {} + local S = self.S + local st = S.sliceTab + for i = 1, #st do + st[i] = 0 + end + S.pic = p +end + +local function conceal(self: any, p: any) + local S = self.S + local st = S.sliceTab + local src = nil + for _, q in self.refs do + if q ~= p and (src == nil or q.decodeOrder > src.decodeOrder) then + src = q + end + end + local mbW = S.mbW + for addr = 1, #st do + if st[addr] == 0 then + local mx, my = (addr - 1) % mbW, (addr - 1) // mbW + for y = 0, 15 do + local o = p.yo + (my * 16 + y) * p.ys + mx * 16 + if src then + buffer.copy(p.y, o, src.y, o, 16) + else + buffer.fill(p.y, o, 128, 16) + end + end + for y = 0, 7 do + local o = p.co + (my * 8 + y) * p.cs + mx * 8 + if src then + buffer.copy(p.u, o, src.u, o, 8) + buffer.copy(p.v, o, src.v, o, 8) + else + buffer.fill(p.u, o, 128, 8) + buffer.fill(p.v, o, 128, 8) + end + end + p.mbIntra[addr] = true + local g0 = my * 4 * S.w4 + mx * 4 + 1 + for j = 0, 3 do + for i = 0, 3 do + local g = g0 + j * S.w4 + i + p.ref0[g], p.ref1[g], p.uid0[g], p.uid1[g] = -1, -1, -1, -1 + end + end + S.kind[addr] = 0 + end + end +end + +local function finishPicture(self: any) + local p = self.cur + if not p then + return + end + local sh = self.curSh + local S = self.S + if self.decoded < S.mbW * S.mbH then + conceal(self, p) + end + if self.opts.deblock ~= false then + Deblock.picture(S, p, self.sliceParams) + end + local w, h = S.mbW * 16, S.mbH * 16 + Inter.extend(p.y, p.yo, p.ys, w, h, PAD) + Inter.extend(p.u, p.co, p.cs, w // 2, h // 2, PADC) + Inter.extend(p.v, p.co, p.cs, w // 2, h // 2, PADC) + local mmco5 = false + if sh.nalRefIdc ~= 0 then + mmco5 = mark(self, p, sh) + end + if sh.idr or mmco5 then + bump(self, 0) + end + if mmco5 then + local t = p.poc + p.topPoc -= t + p.poc = 0 + end + -- POC / frame_num state for the next pictures + if sh.nalRefIdc ~= 0 then + if mmco5 then + self.prevPocMsb = 0 + self.prevPocLsb = p.topPoc + self.prevRefFrameNum = 0 + else + self.prevPocMsb = sh.pocMsb or 0 + self.prevPocLsb = sh.pocLsb + self.prevRefFrameNum = sh.frameNum + end + end + if mmco5 then + self.prevFrameNumOffset = 0 + self.prevFrameNum = 0 + else + self.prevFrameNumOffset = sh.frameNumOffset or 0 + self.prevFrameNum = sh.frameNum + end + self.cur = nil + self.curSh = nil + p.waiting = true + table.insert(self.waiting, p) + bump(self, reorderDepth(self, sh.sps)) + release(self, p) +end + +local function sameNewPicture(a: any, b: any): boolean + -- 7.4.1.2.4: true when slice header b starts a new primary picture after a + if a.frameNum ~= b.frameNum or a.ppsId ~= b.ppsId or a.idr ~= b.idr then + return true + end + if (a.nalRefIdc == 0) ~= (b.nalRefIdc == 0) then + return true + end + local sps = b.sps + if sps.pocType == 0 and (a.pocLsb ~= b.pocLsb or a.deltaPocBottom ~= b.deltaPocBottom) then + return true + end + if sps.pocType == 1 and (a.deltaPoc0 ~= b.deltaPoc0 or a.deltaPoc1 ~= b.deltaPoc1) then + return true + end + if a.idr and b.idr and a.idrPicId ~= b.idrPicId then + return true + end + return false +end + +local function fail(self: any, msg: string) + self.errors += 1 + self.lastError = msg +end + +local function decodeSlice(self: any, sh: any, r: Bitstream.Reader) + local S = self.S + local cur = self.cur + local sps, pps = sh.sps, sh.pps + self.sliceNum += 1 + S.slice = self.sliceNum + self.sliceParams[self.sliceNum] = { sh.deblock, sh.alphaOffset, sh.betaOffset } + S.type = sh.type + S.firstMb = sh.firstMb + if sh.firstMb >= S.mbW * S.mbH then + fail(self, "first_mb_in_slice out of range") + return + end + S.qp = sh.qp + for q = 0, 51 do + S.qpcOf[q + 1] = CHROMA_QP[math.clamp(q + pps.chromaQpOffset, 0, 51) + 1] + S.qpc2Of[q + 1] = CHROMA_QP[math.clamp(q + pps.chromaQpOffset2, 0, 51) + 1] + end + S.dq = Params.dequant(sps, pps, self.dqCache) + S.t8mode = pps.transform8x8 + S.constrainedIntra = pps.constrainedIntra + S.direct8x8 = sps.direct8x8 + S.directSpatial = sh.directSpatial + S.n0, S.n1 = sh.numRefIdxL0, sh.numRefIdxL1 + S.cabacInit = sh.cabacInit + local list0, list1 = {}, {} + if sh.type ~= Slice.I then + local ok + list0, list1, ok = buildLists(self, sh, cur) + if not ok then + fail(self, "bad ref_pic_list_modification") + end + if #list0 == 0 then + list0 = { grayPicture(self, sps) } + end + if sh.type == Slice.B and #list1 == 0 then + list1 = { list0[1] } + end + end + S.list0, S.list1 = list0, list1 + local uids0, uids1 = {}, {} + local uidToRef0 = {} + for i, p in list0 do + uids0[i] = p.uid + if uidToRef0[p.uid] == nil then + uidToRef0[p.uid] = i - 1 + end + end + for i, p in list1 do + uids1[i] = p.uid + end + S.uids0, S.uids1, S.uidToRef0 = uids0, uids1, uidToRef0 + S.weightMode = sh.weightMode + S.weights0, S.weights1 = sh.weights0 or {}, sh.weights1 or {} + S.lumaDenom, S.chromaDenom = sh.lumaDenom or 0, sh.chromaDenom or 0 + if sh.type == Slice.B then + local col = list1[1] + S.colPic = col + S.colShort = not col.long + local dsf = {} + for i, p in list0 do + local d = nil + if not p.long then + d = Mb.distScale(cur.poc, p.poc, col.poc) + end + dsf[i] = d or false + end + S.dsf = dsf + if sh.weightMode == 2 then + local imp = table.create(32 * 32, 32) + for i0, p0 in list0 do + for i1, p1 in list1 do + local w1 = 32 + if not p0.long and not p1.long and p1.poc ~= p0.poc then + local d = Mb.distScale(cur.poc, p0.poc, p1.poc) + if d and d // 4 >= -64 and d // 4 <= 128 then + w1 = d // 4 + end + end + imp[(i0 - 1) * 32 + i1] = w1 + end + end + S.implicit = imp + end + end + local before = 0 + local st = S.sliceTab + local ok, err + if pps.cabac then + ok, err = Cabac.slice(S, self.M, r) + else + ok, err = Cavlc.slice(S, self.M, r) + end + for i = 1, #st do + if st[i] ~= 0 then + before += 1 + end + end + self.decoded = before + if not ok then + fail(self, err or "bad slice data") + end +end + +-- nal(self, buf, off, len, pts): one NAL unit (no start code) +function Decoder.nal(self: any, buf: buffer, off: number, len: number, pts: number?) + if len < 1 then + return + end + local hdr = buffer.readu8(buf, off) + if hdr >= 128 then + fail(self, "forbidden_zero_bit set") + return + end + local refIdc = bit32.rshift(hdr, 5) + local t = bit32.band(hdr, 31) + if t == 7 then + local sps, err = Params.sps(Bitstream.reader(buf, off, len, 1)) + if not sps then + if err and string.sub(err, 1, 6) == "limit:" then + self.fatal = err + end + fail(self, err or "bad sps") + return + end + if sps.chromaFormat ~= 1 then + self.unsupported = "chroma format " .. ({ [0] = "4:0:0 (monochrome)", [2] = "4:2:2", [3] = "4:4:4" })[sps.chromaFormat] + elseif sps.bitDepth ~= 8 or sps.bitDepthC ~= 8 then + self.unsupported = "bit depth " .. sps.bitDepth + elseif not sps.frameMbsOnly then + self.unsupported = "interlaced coding (PAFF / MBAFF)" + end + if sps.mbWidth * sps.mbHeight * 256 > self.maxPixels then + self.fatal = "limit: picture of " .. sps.mbWidth * 16 .. " x " .. sps.mbHeight * 16 .. " over maxPixels" + end + self.spsTab[sps.id] = sps + return + elseif t == 8 then + local pps, err = Params.pps(Bitstream.reader(buf, off, len, 1), self.spsTab) + if not pps then + if err and string.sub(err, 1, 12) == "unsupported:" then + self.unsupported = string.sub(err, 14) + end + fail(self, err or "bad pps") + return + end + self.ppsTab[pps.id] = pps + return + elseif t == 1 or t == 5 then + local r = Bitstream.reader(buf, off, len, 1) + local sh, err = Slice.header(r, t, refIdc, self.spsTab, self.ppsTab) + if not sh then + if err and string.sub(err, 1, 12) == "unsupported:" then + self.unsupported = string.sub(err, 14) + end + fail(self, err or "bad slice header") + return + end + local sps = sh.sps + if sps.chromaFormat ~= 1 or sps.bitDepth ~= 8 or sps.bitDepthC ~= 8 or sps.bypass or not sps.frameMbsOnly then + self.unsupported = self.unsupported or "profile features (chroma format / bit depth / lossless)" + return + end + if sps.mbWidth * sps.mbHeight * 256 > self.maxPixels then + self.fatal = "limit: picture over maxPixels" + return + end + if sh.redundantPicCnt and sh.redundantPicCnt > 0 then + return + end + if self.cur and (sameNewPicture(self.curSh, sh) or (sh.firstMb == 0 and self.decoded > 0)) then + finishPicture(self) + end + if not self.cur then + if not sh.idr and #self.refs == 0 and self.frames == 0 and sh.type ~= Slice.I then + -- a stream starting without an intra picture: decode against gray + self.lastError = "stream starts with an inter picture" + end + startPicture(self, sh, pts) + end + decodeSlice(self, sh, r) + if self.decoded >= self.S.mbW * self.S.mbH then + finishPicture(self) + end + return + elseif t == 9 or t == 10 or t == 11 then + finishPicture(self) + return + elseif t >= 2 and t <= 4 then + self.unsupported = "data partitioning (Extended profile)" + return + end + -- SEI (6), filler (12), SPS extension (13), prefix / SVC / MVC (14, 15, 20) and reserved types are ignored +end + +-- flush(self): finish the current picture and output every waiting picture +function Decoder.flush(self: any) + finishPicture(self) + bump(self, 0) +end + +-- take(self) -> the frames output since the last call +function Decoder.take(self: any): { any } + local out = self.out + self.out = {} + return out +end + +return Decoder diff --git a/src/Formats/codecs/H264/Inter.luau b/src/Formats/codecs/H264/Inter.luau new file mode 100644 index 0000000..0597dbf --- /dev/null +++ b/src/Formats/codecs/H264/Inter.luau @@ -0,0 +1,240 @@ +--!strict +--!native +--!optimize 2 +-- codecs/H264/Inter: inter prediction sample interpolation and weighting (ITU-T H.264 8.4.2.2 / 8.4.2.3): the 6-tap +-- quarter-sample luma filter, eighth-sample bilinear chroma, default / explicit / implicit weighted sample +-- prediction, and the picture border extension that makes out-of-picture reference reads equal to the clamped +-- sample positions of 8.4.2.2.1. Written from the spec. +-- Reference planes carry a border of PAD (luma) / PADC (chroma) replicated samples; callers clamp block positions +-- with Inter.clampLuma / clampChroma so every read is inside the buffer. Never throws. +local readu8, writeu8 = buffer.readu8, buffer.writeu8 + +local Inter = {} + +Inter.PAD = 32 +Inter.PADC = 16 + +local function clip(v: number): number + if v < 0 then + return 0 + elseif v > 255 then + return 255 + end + return v +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 + 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 + end + 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 + 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 + local wa = (8 - fx) * (8 - fy) + local wb = fx * (8 - fy) + local wc = (8 - fx) * fy + local wd = fx * fy + 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 + P[d + c] = (wa * readu8(ref, p) + wb * readu8(ref, p + 1) + wc * readu8(ref, p + s) + wd * readu8(ref, p + s + 1) + 32) // 64 + end + end +end + +-- ------------------------------------------------------------------------------------------------ weighting +-- put(P, w, h, b, o, s): P into the picture +function Inter.put(P: { number }, w: number, h: number, b: buffer, o: number, s: number) + for r = 0, h - 1 do + local d = r * 16 + 1 + local q = o + r * s + for c = 0, w - 1 do + writeu8(b, q + c, P[d + c]) + end + end +end + +-- avg(P0, P1, w, h, b, o, s): default bi-prediction (P0 + P1 + 1) >> 1 +function Inter.avg(P0: { number }, P1: { number }, w: number, h: number, b: buffer, o: number, s: number) + for r = 0, h - 1 do + local d = r * 16 + 1 + local q = o + r * s + for c = 0, w - 1 do + writeu8(b, q + c, (P0[d + c] + P1[d + c] + 1) // 2) + end + end +end + +-- weight1(P, w, h, b, o, s, logWD, wt, off): explicit single-list weighting (8-270 / 8-271) +function Inter.weight1(P: { number }, w: number, h: number, b: buffer, o: number, s: number, logWD: number, wt: number, off: number) + if logWD >= 1 then + local rnd = 2 ^ (logWD - 1) + local div = 2 ^ logWD + for r = 0, h - 1 do + local d = r * 16 + 1 + local q = o + r * s + for c = 0, w - 1 do + writeu8(b, q + c, clip((P[d + c] * wt + rnd) // div + off)) + end + end + else + for r = 0, h - 1 do + local d = r * 16 + 1 + local q = o + r * s + for c = 0, w - 1 do + writeu8(b, q + c, clip(P[d + c] * wt + off)) + end + end + end +end + +-- weight2(P0, P1, w, h, b, o, s, logWD, w0, w1, off): explicit / implicit bi-prediction weighting (8-272); +-- off = (o0 + o1 + 1) >> 1 +function Inter.weight2(P0: { number }, P1: { number }, w: number, h: number, b: buffer, o: number, s: number, logWD: number, w0: number, w1: number, off: number) + local rnd = 2 ^ logWD + local div = 2 ^ (logWD + 1) + for r = 0, h - 1 do + local d = r * 16 + 1 + local q = o + r * s + for c = 0, w - 1 do + writeu8(b, q + c, clip((P0[d + c] * w0 + P1[d + c] * w1 + rnd) // div + off)) + end + end +end + +-- ------------------------------------------------------------------------------------------------ borders +-- extend(b, o, s, w, h, pad): replicate the edge samples of the w x h plane at b[o] (stride s) into its border +function Inter.extend(b: buffer, o: number, s: number, w: number, h: number, pad: number) + for y = 0, h - 1 do + local r = o + y * s + buffer.fill(b, r - pad, readu8(b, r), pad) + buffer.fill(b, r + w, readu8(b, r + w - 1), pad) + end + local top = o - pad + local bottom = o + (h - 1) * s - pad + for y = 1, pad do + buffer.copy(b, top - y * s, b, top, w + 2 * pad) + buffer.copy(b, bottom + y * s, b, bottom, w + 2 * pad) + end +end + +return Inter diff --git a/src/Formats/codecs/H264/Intra.luau b/src/Formats/codecs/H264/Intra.luau new file mode 100644 index 0000000..a653b3f --- /dev/null +++ b/src/Formats/codecs/H264/Intra.luau @@ -0,0 +1,414 @@ +--!strict +--!native +--!optimize 2 +-- codecs/H264/Intra: intra prediction (ITU-T H.264 8.3): Intra_4x4 and Intra_8x8 (nine directional modes, with the +-- 8x8 reference sample filter of 8.3.2.2.1), Intra_16x16 and chroma (DC / horizontal / vertical / plane), 8-bit. +-- Written from the spec. Predictions are written straight into the picture plane (row stride `s`, block origin `o`). +-- Never throws: every sample read is inside the padded plane (callers pass availability for the edges). +local readu8, writeu8 = buffer.readu8, buffer.writeu8 + +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 function clip(v: number): number + if v < 0 then + return 0 + elseif v > 255 then + return 255 + end + return v +end + +-- predNxN: the directional modes 3..8 over the edge array R (N = 4 or 8) +local function directional(R: { number }, N: number, mode: number, b: buffer, o: number, s: number) + local c = N + 1 -- R[c] = p[-1, -1]; p[x, -1] = R[c + 1 + x]; p[-1, y] = R[c - 1 - y] + for y = 0, N - 1 do + local row = o + y * s + for x = 0, N - 1 do + local v + if mode == 3 then -- diagonal down left + if x == N - 1 and y == N - 1 then + v = (R[c + 2 * N - 1] + 3 * R[c + 2 * N] + 2) // 4 + else + local i = c + 1 + x + y + v = (R[i] + 2 * R[i + 1] + R[i + 2] + 2) // 4 + end + elseif mode == 4 then -- diagonal down right + if x > y then + local i = c + 1 + x - y + v = (R[i - 2] + 2 * R[i - 1] + R[i] + 2) // 4 + elseif x < y then + local i = c - 1 - (y - x) + v = (R[i + 2] + 2 * R[i + 1] + R[i] + 2) // 4 + else + v = (R[c + 1] + 2 * R[c] + R[c - 1] + 2) // 4 + end + elseif mode == 5 then -- vertical right + local z = 2 * x - y + if z >= 0 and z % 2 == 0 then + local i = c + 1 + x - y // 2 + v = (R[i - 1] + R[i] + 1) // 2 + elseif z > 0 then + local i = c + 1 + x - y // 2 + v = (R[i - 2] + 2 * R[i - 1] + R[i] + 2) // 4 + elseif z == -1 then + v = (R[c - 1] + 2 * R[c] + R[c + 1] + 2) // 4 + else + local i = c - 1 - (y - 2 * x - 1) -- p[-1, y - 2x - 1] + v = (R[i] + 2 * R[i + 1] + R[i + 2] + 2) // 4 + end + elseif mode == 6 then -- horizontal down + local z = 2 * y - x + if z >= 0 and z % 2 == 0 then + local i = c - 1 - (y - x // 2) -- p[-1, y - (x >> 1)] + v = (R[i + 1] + R[i] + 1) // 2 + elseif z > 0 then + local i = c - 1 - (y - x // 2) + v = (R[i + 2] + 2 * R[i + 1] + R[i] + 2) // 4 + elseif z == -1 then + v = (R[c - 1] + 2 * R[c] + R[c + 1] + 2) // 4 + else + local i = c + 1 + (x - 2 * y - 1) -- p[x - 2y - 1, -1] + v = (R[i] + 2 * R[i - 1] + R[i - 2] + 2) // 4 + end + elseif mode == 7 then -- vertical left + local i = c + 1 + x + y // 2 + if y % 2 == 0 then + v = (R[i] + R[i + 1] + 1) // 2 + else + v = (R[i] + 2 * R[i + 1] + R[i + 2] + 2) // 4 + end + else -- horizontal up + local z = x + 2 * y + local i = c - 1 - (y + x // 2) -- p[-1, y + (x >> 1)] + if z > 2 * N - 3 then + v = R[c - N] + elseif z == 2 * N - 3 then + v = (R[c - N + 1] + 3 * R[c - N] + 2) // 4 + elseif z % 2 == 0 then + v = (R[i] + R[i - 1] + 1) // 2 + else + v = (R[i] + 2 * R[i - 1] + R[i - 2] + 2) // 4 + end + end + writeu8(b, row + x, v) + end + end +end + +-- pred4x4(b, o, s, mode, left, top, topRight, topLeft): Intra_4x4 at plane offset o. Unavailable top-right samples +-- repeat p[3, -1]. +function Intra.pred4x4(b: buffer, o: number, s: number, mode: number, left: boolean, top: boolean, topRight: boolean, topLeft: boolean) + if mode == 0 then + local t = o - s + local a0, a1, a2, a3 = readu8(b, t), readu8(b, t + 1), readu8(b, t + 2), readu8(b, t + 3) + for y = 0, 3 do + local r = o + y * s + writeu8(b, r, a0) + writeu8(b, r + 1, a1) + writeu8(b, r + 2, a2) + writeu8(b, r + 3, a3) + end + return + elseif mode == 1 then + for y = 0, 3 do + local r = o + y * s + local v = readu8(b, r - 1) + writeu8(b, r, v) + writeu8(b, r + 1, v) + writeu8(b, r + 2, v) + writeu8(b, r + 3, v) + end + return + elseif mode == 2 then + local sum, n = 0, 0 + if top then + local t = o - s + sum += readu8(b, t) + readu8(b, t + 1) + readu8(b, t + 2) + readu8(b, t + 3) + n += 1 + end + if left then + sum += readu8(b, o - 1) + readu8(b, o + s - 1) + readu8(b, o + 2 * s - 1) + readu8(b, o + 3 * s - 1) + n += 1 + end + local v = 128 + if n == 2 then + v = (sum + 4) // 8 + elseif n == 1 then + v = (sum + 2) // 4 + end + for y = 0, 3 do + local r = o + y * s + writeu8(b, r, v) + writeu8(b, r + 1, v) + writeu8(b, r + 2, v) + writeu8(b, r + 3, v) + end + return + end + -- edges: E[1..4] = p[-1, 3..0], E[5] = p[-1, -1], E[6..13] = p[0..7, -1] + if left then + for y = 0, 3 do + E[4 - y] = readu8(b, o + y * s - 1) + end + end + if topLeft then + E[5] = readu8(b, o - s - 1) + end + if top then + local t = o - s + for x = 0, 3 do + E[6 + x] = readu8(b, t + x) + end + if topRight then + for x = 4, 7 do + E[6 + x] = readu8(b, t + x) + end + else + local v = E[9] + E[10], E[11], E[12], E[13] = v, v, v, v + end + end + directional(E, 4, mode, b, o, s) +end + +-- pred8x8(b, o, s, mode, left, top, topRight, topLeft): Intra_8x8 with the reference sample filter +function Intra.pred8x8(b: buffer, o: number, s: number, mode: number, left: boolean, top: boolean, topRight: boolean, topLeft: boolean) + -- unfiltered edges into E: E[1..8] = p[-1, 7..0], E[9] = p[-1, -1], E[10..25] = p[0..15, -1] + if left then + for y = 0, 7 do + E[8 - y] = readu8(b, o + y * s - 1) + end + end + local tl = 0 + if topLeft then + tl = readu8(b, o - s - 1) + E[9] = tl + end + if top then + local t = o - s + for x = 0, 7 do + E[10 + x] = readu8(b, t + x) + end + if topRight then + for x = 8, 15 do + E[10 + x] = readu8(b, t + x) + end + else + local v = E[17] + for x = 8, 15 do + E[10 + x] = v + end + end + -- filtered top + if topLeft then + F[10] = (tl + 2 * E[10] + E[11] + 2) // 4 + else + F[10] = (3 * E[10] + E[11] + 2) // 4 + end + for x = 1, 14 do + F[10 + x] = (E[9 + x] + 2 * E[10 + x] + E[11 + x] + 2) // 4 + end + F[25] = (E[24] + 3 * E[25] + 2) // 4 + end + if topLeft then + if top and left then + F[9] = (E[10] + 2 * tl + E[8] + 2) // 4 + elseif top then + F[9] = (3 * tl + E[10] + 2) // 4 + elseif left then + F[9] = (3 * tl + E[8] + 2) // 4 + else + F[9] = tl + end + end + if left then + if topLeft then + F[8] = (tl + 2 * E[8] + E[7] + 2) // 4 + else + F[8] = (3 * E[8] + E[7] + 2) // 4 + end + for y = 1, 6 do + F[8 - y] = (E[9 - y] + 2 * E[8 - y] + E[7 - y] + 2) // 4 + end + F[1] = (E[2] + 3 * E[1] + 2) // 4 + end + if mode == 0 then + for y = 0, 7 do + local r = o + y * s + for x = 0, 7 do + writeu8(b, r + x, F[10 + x]) + end + end + elseif mode == 1 then + for y = 0, 7 do + local r = o + y * s + local v = F[8 - y] + for x = 0, 7 do + writeu8(b, r + x, v) + end + end + elseif mode == 2 then + local sum, n = 0, 0 + if top then + for x = 0, 7 do + sum += F[10 + x] + end + n += 1 + end + if left then + for y = 0, 7 do + sum += F[8 - y] + end + n += 1 + end + local v = 128 + if n == 2 then + v = (sum + 8) // 16 + elseif n == 1 then + v = (sum + 4) // 8 + end + for y = 0, 7 do + local r = o + y * s + for x = 0, 7 do + writeu8(b, r + x, v) + end + end + else + directional(F, 8, mode, b, o, s) + end +end + +-- pred16x16(b, o, s, mode, left, top, topLeft) +function Intra.pred16x16(b: buffer, o: number, s: number, mode: number, left: boolean, top: boolean, topLeft: boolean) + if mode == 0 then + local t = o - s + for y = 0, 15 do + buffer.copy(b, o + y * s, b, t, 16) + end + elseif mode == 1 then + for y = 0, 15 do + local r = o + y * s + buffer.fill(b, r, readu8(b, r - 1), 16) + end + elseif mode == 2 then + local sum, n = 0, 0 + if top then + local t = o - s + for x = 0, 15 do + sum += readu8(b, t + x) + end + n += 1 + end + if left then + for y = 0, 15 do + sum += readu8(b, o + y * s - 1) + end + n += 1 + end + local v = 128 + if n == 2 then + v = (sum + 16) // 32 + elseif n == 1 then + v = (sum + 8) // 16 + end + for y = 0, 15 do + buffer.fill(b, o + y * s, v, 16) + end + else + local t = o - s + local H, V = 0, 0 + for i = 0, 7 do + H += (i + 1) * (readu8(b, t + 8 + i) - readu8(b, t + 6 - i)) + V += (i + 1) * (readu8(b, o + (8 + i) * s - 1) - readu8(b, o + (6 - i) * s - 1)) + end + local a = 16 * (readu8(b, o + 15 * s - 1) + readu8(b, t + 15)) + local bb = (5 * H + 32) // 64 + local cc = (5 * V + 32) // 64 + for y = 0, 15 do + local r = o + y * s + local base = a + cc * (y - 7) + 16 - 7 * bb + for x = 0, 15 do + writeu8(b, r + x, clip((base + bb * x) // 32)) + end + end + end +end + +local function fill4(b: buffer, o: number, s: number, v: number) + for y = 0, 3 do + local r = o + y * s + writeu8(b, r, v) + writeu8(b, r + 1, v) + writeu8(b, r + 2, v) + writeu8(b, r + 3, v) + end +end + +-- predChroma(b, o, s, mode, left, top, topLeft): 8x8 chroma (4:2:0); mode 0 DC, 1 horizontal, 2 vertical, 3 plane +function Intra.predChroma(b: buffer, o: number, s: number, mode: number, left: boolean, top: boolean, topLeft: boolean) + if mode == 0 then + local t = o - s + local st0, st1, sl0, sl1 = 0, 0, 0, 0 + if top then + st0 = readu8(b, t) + readu8(b, t + 1) + readu8(b, t + 2) + readu8(b, t + 3) + st1 = readu8(b, t + 4) + readu8(b, t + 5) + readu8(b, t + 6) + readu8(b, t + 7) + end + if left then + sl0 = readu8(b, o - 1) + readu8(b, o + s - 1) + readu8(b, o + 2 * s - 1) + readu8(b, o + 3 * s - 1) + sl1 = readu8(b, o + 4 * s - 1) + readu8(b, o + 5 * s - 1) + readu8(b, o + 6 * s - 1) + readu8(b, o + 7 * s - 1) + end + local v00, v10, v01, v11 = 128, 128, 128, 128 + if top and left then + v00 = (st0 + sl0 + 4) // 8 + v11 = (st1 + sl1 + 4) // 8 + v10 = (st1 + 2) // 4 + v01 = (sl1 + 2) // 4 + elseif left then + v00 = (sl0 + 2) // 4 + v11 = (sl1 + 2) // 4 + v10 = v00 + v01 = v11 + elseif top then + v00 = (st0 + 2) // 4 + v11 = (st1 + 2) // 4 + v10 = v11 + v01 = v00 + end + fill4(b, o, s, v00) + fill4(b, o + 4, s, v10) + fill4(b, o + 4 * s, s, v01) + fill4(b, o + 4 * s + 4, s, v11) + elseif mode == 1 then + for y = 0, 7 do + local r = o + y * s + buffer.fill(b, r, readu8(b, r - 1), 8) + end + elseif mode == 2 then + local t = o - s + for y = 0, 7 do + buffer.copy(b, o + y * s, b, t, 8) + end + else + local t = o - s + local H, V = 0, 0 + for i = 0, 3 do + H += (i + 1) * (readu8(b, t + 4 + i) - readu8(b, t + 2 - i)) + V += (i + 1) * (readu8(b, o + (4 + i) * s - 1) - readu8(b, o + (2 - i) * s - 1)) + end + local a = 16 * (readu8(b, o + 7 * s - 1) + readu8(b, t + 7)) + local bb = (34 * H + 32) // 64 + local cc = (34 * V + 32) // 64 + for y = 0, 7 do + local r = o + y * s + local base = a + cc * (y - 3) + 16 - 3 * bb + for x = 0, 7 do + writeu8(b, r + x, clip((base + bb * x) // 32)) + end + end + end +end + +return Intra diff --git a/src/Formats/codecs/H264/Mb.luau b/src/Formats/codecs/H264/Mb.luau new file mode 100644 index 0000000..c1aa116 --- /dev/null +++ b/src/Formats/codecs/H264/Mb.luau @@ -0,0 +1,936 @@ +--!strict +--!native +--!optimize 2 +-- codecs/H264/Mb: macroblock reconstruction shared by the CAVLC and CABAC parsers (ITU-T H.264 8.3 - 8.5): +-- neighbour availability (6.4.11), Intra4x4 / Intra8x8 mode prediction (8.3.1.1 / 8.3.2.1), motion vector prediction +-- (8.4.1.3), P_Skip (8.4.1.1), B direct spatial and temporal (8.4.1.2), motion compensation with weighting, intra +-- prediction and the residual. Written from the spec; the per-4x4 motion / mode grids follow the usual decoder layout +-- (picture-wide arrays, one entry per 4x4 luma block, 1-based). +-- Never throws: every index is in range by construction; reference indices past the list use the first entry. +local Intra = require("@formats/codecs/H264/Intra") +local Transform = require("@formats/codecs/H264/Transform") +local Inter = require("@formats/codecs/H264/Inter") + +local Mb = {} + +-- macroblock kinds (S.kind per macroblock) +local K_I4, K_I8, K_I16, K_PCM, K_P, K_PSKIP, K_B, K_BSKIP, K_BDIRECT = 1, 2, 3, 4, 5, 6, 7, 8, 9 +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 add4, addDc4, add8 = Transform.add4, Transform.addDc4, Transform.add8 +local PAD, PADC = Inter.PAD, Inter.PADC + +-- raster 4x4 block (bx + 4 by) of the decoding-order block index 0..15 (6.4.3) +local BLK_X = { 0, 1, 0, 1, 2, 3, 2, 3, 0, 1, 0, 1, 2, 3, 2, 3 } +local BLK_Y = { 0, 0, 1, 1, 0, 0, 1, 1, 2, 2, 3, 3, 2, 2, 3, 3 } +Mb.BLK_X, Mb.BLK_Y = BLK_X, BLK_Y + +-- new() -> M, the per-macroblock scratch state +function Mb.new(): any + return { + addr = 0, + x = 0, + y = 0, + g0 = 1, -- grid index of the macroblock's 4x4 block (0, 0) + c0 = 1, -- chroma 4x4 grid index of its block (0, 0) + aL = false, + aT = false, + aTR = false, + aTL = false, + iL = false, -- intra sample availability (constrained_intra_pred aware) + iT = false, + iTR = false, + iTL = false, + kind = 0, + t8 = 0, + i16 = 0, + cpm = 0, + cbp = 0, + qp = 0, + qpd = 0, -- mb_qp_delta + part = 0, -- 0 16x16, 1 16x8, 2 8x16, 3 8x8 + pf = { 0, 0, 0, 0 }, -- prediction flags per partition: 1 L0, 2 L1, 3 Bi + sub = { 0, 0, 0, 0 }, -- sub-macroblock shape: 0 8x8, 1 8x4, 2 4x8, 3 4x4 + dir = { false, false, false, false }, -- B_Direct_8x8 sub-macroblocks + ref0 = { 0, 0, 0, 0 }, + ref1 = { 0, 0, 0, 0 }, + mvd0 = table.create(32, 0), + mvd1 = table.create(32, 0), + ipm = table.create(16, 2), -- intra 4x4 / 8x8 modes by raster block + c4 = table.create(256, 0), -- luma 4x4 coefficients (dequantised), raster block * 16 + raster position + c8 = table.create(256, 0), -- luma 8x8 coefficients, 8x8 block * 64 + raster position + cc = table.create(128, 0), -- chroma: (plane * 4 + block) * 16 + position + dcY = table.create(16, 0), + dcC = table.create(8, 0), + nz = table.create(16, 0), -- coefficients per luma 4x4 block (raster) + nzc = table.create(8, 0), -- coefficients per chroma AC block (plane * 4 + block) + hasDcY = false, + hasDcC = false, + done = table.create(16, false), + reg = table.create(64, 0), -- motion compensation regions: x, y, w, h (4x4 units) + nreg = 0, + P0 = table.create(256, 0), + P1 = table.create(256, 0), + pcm = buffer.create(384), + } +end + +-- grids(mbW, mbH) -> the per-picture decoding grids (shared by the slices of one picture) +function Mb.grids(mbW: number, mbH: number): any + local n = mbW * mbH + local n4 = n * 16 + local nc = n * 4 + return { + sliceTab = table.create(n, 0), + kind = table.create(n, 0), + cbpTab = table.create(n, 0), + qpTab = table.create(n, 0), -- QPY for deblocking (0 for I_PCM) + qpcTab = table.create(n, 0), -- QPc (Cb) + qpc2Tab = table.create(n, 0), -- QPc (Cr) + t8Tab = table.create(n, 0), + cpmTab = table.create(n, 0), + dcTab = table.create(n, 0), -- CABAC coded_block_flag of the DC blocks: 1 luma, 2 Cb, 4 Cr + qpdTab = table.create(n, 0), -- mb_qp_delta ~= 0 + nzc = table.create(n4, 0), + nzcCb = table.create(nc, 0), + nzcCr = table.create(nc, 0), + nzDb = table.create(n4, 0), + ipm = table.create(n4, 2), + mvd0 = table.create(n4 * 2, 0), + mvd1 = table.create(n4 * 2, 0), + rgt0 = table.create(n4, 0), + rgt1 = table.create(n4, 0), + } +end + +-- ------------------------------------------------------------------------------------------------ neighbours +-- start(S, M, addr): position and neighbour availability of macroblock addr +function Mb.start(S: any, M: any, addr: number) + local mbW = S.mbW + local x, y = addr % mbW, addr // mbW + M.addr, M.x, M.y = addr, x, y + local w4 = S.w4 + M.g0 = y * 4 * w4 + x * 4 + 1 + M.c0 = y * 2 * S.cw4 + x * 2 + 1 + local st, sl = S.sliceTab, S.slice + local aL = x > 0 and st[addr] == sl -- addr is 0-based: st[addr] is macroblock addr - 1 + local aT = y > 0 and st[addr - mbW + 1] == sl + local aTR = y > 0 and x < mbW - 1 and st[addr - mbW + 2] == sl + local aTL = y > 0 and x > 0 and st[addr - mbW] == sl + M.aL, M.aT, M.aTR, M.aTL = aL, aT, aTR, aTL + if S.constrainedIntra then + local k = S.kind + M.iL = aL and k[addr] <= K_PCM + M.iT = aT and k[addr - mbW + 1] <= K_PCM + M.iTR = aTR and k[addr - mbW + 2] <= K_PCM + M.iTL = aTL and k[addr - mbW] <= K_PCM + else + M.iL, M.iT, M.iTR, M.iTL = aL, aT, aTR, aTL + end + local done = M.done + for i = 1, 16 do + done[i] = false + end + M.nreg = 0 + M.hasDcY, M.hasDcC = false, false + M.t8 = 0 + M.qpd = 0 +end + +-- nC(S, M, bx, by) -> nC of luma block (bx, by) (9.2.1) +function Mb.nC(S: any, M: any, bx: number, by: number): number + local g = M.g0 + by * S.w4 + bx + local nzc = S.nzc + local la = bx > 0 or M.aL + local ta = by > 0 or M.aT + if la and ta then + return (nzc[g - 1] + nzc[g - S.w4] + 1) // 2 + elseif la then + return nzc[g - 1] + elseif ta then + return nzc[g - S.w4] + end + return 0 +end + +-- nCc(S, M, tab, bx, by) -> nC of chroma AC block (bx, by) of the plane whose counts are in tab +function Mb.nCc(S: any, M: any, tab: { number }, bx: number, by: number): number + local cw = S.cw4 + local g = M.c0 + by * cw + bx + local la = bx > 0 or M.aL + local ta = by > 0 or M.aT + if la and ta then + return (tab[g - 1] + tab[g - cw] + 1) // 2 + elseif la then + return tab[g - 1] + elseif ta then + return tab[g - cw] + end + return 0 +end + +-- predMode(S, M, bx, by) -> predIntra4x4PredMode / predIntra8x8PredMode of the block whose top-left 4x4 is (bx, by) +function Mb.predMode(S: any, M: any, bx: number, by: number): number + local la = bx > 0 or M.iL + local ta = by > 0 or M.iT + if not (la and ta) then + return 2 + end + 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 +end + +-- ------------------------------------------------------------------------------------------------ motion vectors +-- neighbour(S, M, list, nx, ny) -> ref (UNAVAIL when not available), mvx, mvy of the 4x4 at (nx, ny) relative to the +-- macroblock (nx, ny in -1 .. 4) +local function neighbour(S: any, M: any, refs: { number }, mvs: { number }, nx: number, ny: number): (number, number, number) + local ok + if ny < 0 then + if nx < 0 then + ok = M.aTL + elseif nx < 4 then + ok = M.aT + else + ok = M.aTR + end + elseif nx < 0 then + ok = M.aL + elseif nx >= 4 then + ok = false + else + ok = M.done[ny * 4 + nx + 1] + end + if not ok then + return UNAVAIL, 0, 0 + end + local g = M.g0 + ny * S.w4 + nx + local r = refs[g] + if r < 0 then + return -1, 0, 0 + end + return r, mvs[2 * g - 1], mvs[2 * g] +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 +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 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) + if rC == UNAVAIL then + rC, cx, cy = neighbour(S, M, refs, mvs, x - 1, y - 1) + end + if shape == 1 then + if rB == ref then + return bx, by + end + elseif shape == 2 then + if rA == ref then + return ax, ay + end + elseif shape == 3 then + if rA == ref then + return ax, ay + end + elseif shape == 4 then + if rC == ref then + return cx, cy + end + end + if rB == UNAVAIL and rC == UNAVAIL and rA ~= UNAVAIL then + rB, bx, by = rA, ax, ay + rC, cx, cy = rA, ax, ay + end + local n = 0 + if rA == ref then + n += 1 + end + if rB == ref then + n += 2 + end + if rC == ref then + n += 4 + end + if n == 1 then + return ax, ay + elseif n == 2 then + return bx, by + elseif n == 4 then + return cx, cy + end + return median(ax, bx, cx), median(ay, by, cy) +end +Mb.mvp = mvp + +-- set(S, M, x, y, w, h, r0, m0x, m0y, r1, m1x, m1y): motion data of a region into the picture grids +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 w4 = S.w4 + local done = M.done + for j = y, y + h - 1 do + local g = M.g0 + j * w4 + x + for i = x, x + w - 1 do + ref0[g] = r0 + ref1[g] = r1 + mv0[2 * g - 1], mv0[2 * g] = m0x, m0y + mv1[2 * g - 1], mv1[2 * g] = m1x, m1y + uid0[g] = u0 + uid1[g] = u1 + done[j * 4 + i + 1] = true + g += 1 + end + end + local k = M.nreg * 4 + local reg = M.reg + reg[k + 1], reg[k + 2], reg[k + 3], reg[k + 4] = x, y, w, h + M.nreg += 1 +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 +end + +local function tdiv(a: number, b: number): number + local q = a / b + if q >= 0 then + return math.floor(q) + end + return -math.floor(-q) +end + +-- distScale(cur, poc0, poc1) -> DistScaleFactor (8-195 .. 8-198), or nil when td is 0 +function Mb.distScale(cur: number, poc0: number, poc1: number): number? + local tb = clip3(-128, 127, cur - poc0) + local td = clip3(-128, 127, poc1 - poc0) + if td == 0 then + return nil + end + local tx = tdiv(16384 + math.abs(tdiv(td, 2)), td) + return clip3(-1024, 1023, (tb * tx + 32) // 64) +end + +-- pskip(S, M): P_Skip motion (8.4.1.1) +local function pskip(S: any, M: any) + local mx, my = 0, 0 + if M.aL and M.aT then + local pic = S.pic + local rA, ax, ay = neighbour(S, M, pic.ref0, pic.mv0, -1, 0) + local rB, bx, by = neighbour(S, M, pic.ref0, pic.mv0, 0, -1) + if not ((rA == 0 and ax == 0 and ay == 0) or (rB == 0 and bx == 0 and by == 0)) then + mx, my = mvp(S, M, 0, 0, 0, 4, 0, 0) + end + end + set(S, M, 0, 0, 4, 4, 0, mx, my, -1, 0, 0) +end + +-- colocated(S, M, bx, by) -> refIdxCol (-1: intra / none), mvCol x, y, uid of the referenced picture (8.4.1.2.1) +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 + end + if col.mbIntra[M.addr + 1] then + return -1, 0, 0, -1 + end + local g = M.g0 + by * S.w4 + bx + local r = col.ref0[g] + if r >= 0 then + return r, col.mv0[2 * g - 1], col.mv0[2 * g], col.uid0[g] + end + r = col.ref1[g] + if r >= 0 then + return r, col.mv1[2 * g - 1], col.mv1[2 * g], col.uid1[g] + end + return -1, 0, 0, -1 +end + +local function minPositive(a: number, b: number): number + if a >= 0 and b >= 0 then + return if a < b then a else b + end + return if a > b then a else b +end + +-- spatialRefs(S, M): the macroblock-level references and predictors of spatial direct (8.4.1.2.2), cached in M +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 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) + if rC == UNAVAIL then + rC = neighbour(S, M, refs, mvs, -1, -1) + end + local r = minPositive(rA, minPositive(rB, rC)) + if r < -1 then + r = -1 + end + if l == 0 then + r0 = r + else + r1 = r + end + end + M.dZero = false + if r0 < 0 and r1 < 0 then + r0, r1 = 0, 0 + M.dZero = true + end + M.dr0, M.dr1 = r0, r1 + M.d0x, M.d0y, M.d1x, M.d1y = 0, 0, 0, 0 + if not M.dZero then + if r0 >= 0 then + M.d0x, M.d0y = mvp(S, M, 0, 0, 0, 4, r0, 0) + end + if r1 >= 0 then + M.d1x, M.d1y = mvp(S, M, 1, 0, 0, 4, r1, 0) + end + end + M.dReady = true +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 + if S.directSpatial then + if not M.dReady then + spatialRefs(S, M) + end + local r0, r1 = M.dr0, M.dr1 + local l1short = S.colShort + for y = y0, y0 + 1, step do + for x = x0, x0 + 1, step do + local m0x, m0y, m1x, m1y = M.d0x, M.d0y, M.d1x, M.d1y + if not M.dZero and l1short then + local rc, cx, cy = colocated(S, M, x, y) + if rc == 0 and cx >= -1 and cx <= 1 and cy >= -1 and cy <= 1 then + if r0 == 0 then + m0x, m0y = 0, 0 + end + if r1 == 0 then + m1x, m1y = 0, 0 + end + end + end + set(S, M, x, y, step, step, r0, m0x, m0y, r1, m1x, m1y) + end + end + else + for y = y0, y0 + 1, step do + for x = x0, x0 + 1, step do + local rc, cx, cy, cu = colocated(S, M, x, y) + local r0 = 0 + if rc >= 0 then + r0 = S.uidToRef0[cu] or 0 + end + local m0x, m0y, m1x, m1y = cx, cy, 0, 0 + local dsf = S.dsf[r0 + 1] + if dsf then + m0x = (dsf * cx + 128) // 256 + m0y = (dsf * cy + 128) // 256 + m1x = m0x - cx + m1y = m0y - cy + end + set(S, M, x, y, step, step, r0, m0x, m0y, 0, m1x, m1y) + end + end + end +end + +-- partition geometry (4x4 units) of the sub-macroblock shapes +local SUB_N = { 1, 2, 2, 4 } +local SUB_W = { 2, 2, 1, 1 } +local SUB_H = { 2, 1, 2, 1 } + +-- motion(S, M): motion vectors of an inter macroblock into the grids, and its MC regions +local function motion(S: any, M: any) + local kind = M.kind + M.dReady = false + if kind == K_PSKIP then + pskip(S, M) + return + end + if kind == K_BSKIP or kind == K_BDIRECT then + for i8 = 0, 3 do + direct8(S, M, i8) + end + return + end + local part = M.part + local mvd0, mvd1 = M.mvd0, M.mvd1 + if part < 3 then + local n = if part == 0 then 1 else 2 + for p = 1, n do + local x, y, w, h = 0, 0, 4, 4 + local shape = 0 + if part == 1 then + y, h = (p - 1) * 2, 2 + shape = p + elseif part == 2 then + x, w = (p - 1) * 2, 2 + shape = 2 + p + end + local pf = M.pf[p] + local r0, r1 = -1, -1 + local m0x, m0y, m1x, m1y = 0, 0, 0, 0 + if pf % 2 == 1 then + r0 = M.ref0[p] + m0x, m0y = mvp(S, M, 0, x, y, w, r0, shape) + m0x += mvd0[2 * p - 1] + m0y += mvd0[2 * p] + end + if pf >= 2 then + r1 = M.ref1[p] + m1x, m1y = mvp(S, M, 1, x, y, w, r1, shape) + m1x += mvd1[2 * p - 1] + m1y += mvd1[2 * p] + end + set(S, M, x, y, w, h, r0, m0x, m0y, r1, m1x, m1y) + end + return + end + for i8 = 0, 3 do + if M.dir[i8 + 1] then + direct8(S, M, i8) + else + local x0, y0 = (i8 % 2) * 2, (i8 // 2) * 2 + local sub = M.sub[i8 + 1] + local pf = M.pf[i8 + 1] + local w, h = SUB_W[sub + 1], SUB_H[sub + 1] + for k = 0, SUB_N[sub + 1] - 1 do + local x, y = x0, y0 + if sub == 1 then + y += k + elseif sub == 2 then + x += k + elseif sub == 3 then + x += k % 2 + y += k // 2 + end + local p = i8 * 4 + k + 1 + local r0, r1 = -1, -1 + local m0x, m0y, m1x, m1y = 0, 0, 0, 0 + if pf % 2 == 1 then + r0 = M.ref0[i8 + 1] + m0x, m0y = mvp(S, M, 0, x, y, w, r0, 0) + m0x += mvd0[2 * p - 1] + m0y += mvd0[2 * p] + end + if pf >= 2 then + r1 = M.ref1[i8 + 1] + m1x, m1y = mvp(S, M, 1, x, y, w, r1, 0) + m1x += mvd1[2 * p - 1] + m1y += mvd1[2 * p] + end + set(S, M, x, y, w, h, r0, m0x, m0y, r1, m1x, m1y) + end + end + end +end +Mb.motion = motion + +-- ------------------------------------------------------------------------------------------------ motion compensation +-- predict(S, M, pic, P, list, x, y, w, h, mvx, mvy, plane): one list's prediction samples of a region into P +local function predLuma(S: any, ref: any, P: { number }, px: number, py: number, w: number, h: number, mvx: number, mvy: number) + local W, H = S.mbW * 16, S.mbH * 16 + local ix = px + mvx // 4 + local iy = py + mvy // 4 + ix = clip3(2 - PAD, W + PAD - w - 4, ix) + iy = clip3(2 - PAD, H + PAD - h - 4, iy) + local s = ref.ys + Inter.luma(ref.y, s, ref.yo + iy * s + ix, mvx % 4, mvy % 4, w, h, P) +end + +local function predChroma(S: any, ref: any, P: { number }, plane: buffer, px: number, py: number, w: number, h: number, mvx: number, mvy: number) + local W, H = S.mbW * 8, S.mbH * 8 + local ix = px + mvx // 8 + local iy = py + mvy // 8 + ix = clip3(-PADC, W + PADC - 1 - w, ix) + iy = clip3(-PADC, H + PADC - 1 - h, iy) + local s = ref.cs + Inter.chroma(plane, s, ref.co + iy * s + ix, mvx % 8, mvy % 8, w, h, P) +end + +local function refPic(list: { any }, r: number): any + return list[r + 1] or list[1] +end + +-- mc(S, M): inter prediction of every region of the macroblock into the current picture +local function mc(S: any, M: any) + local pic = S.pic + local reg = M.reg + local P0, P1 = M.P0, M.P1 + local ys, cs = pic.ys, pic.cs + local wm = S.weightMode + local list0, list1 = S.list0, S.list1 + for k = 0, M.nreg - 1 do + local x, y, w, h = reg[k * 4 + 1], reg[k * 4 + 2], reg[k * 4 + 3], reg[k * 4 + 4] + 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 + if ref0 == nil and ref1 == nil then + ref0 = list0[1] or list1[1] + r0 = 0 + if ref0 == nil then + continue + end + end + local px, py = M.x * 16 + x * 4, M.y * 16 + y * 4 + local lw, lh = w * 4, h * 4 + local lo = pic.yo + py * ys + px + local cx, cy, cw, ch = M.x * 8 + x * 2, M.y * 8 + y * 2, w * 2, h * 2 + local co = pic.co + cy * cs + cx + -- weights for this pair + local bi = ref0 ~= nil and ref1 ~= nil + local explicit = wm == 1 + local implicitW0, implicitW1 = 32, 32 + if wm == 2 then + if bi then + local iw = S.implicit[r0 * 32 + r1 + 1] + implicitW0, implicitW1 = 64 - iw, iw + else + explicit = false + end + end + local W0, W1 = S.weights0, S.weights1 + for plane = 0, 2 do + local dst, o, s, bw, bh = pic.y, lo, ys, lw, lh + if plane == 1 then + dst, o, s, bw, bh = pic.u, co, cs, cw, ch + elseif plane == 2 then + dst, o, s, bw, bh = pic.v, co, cs, cw, ch + end + if ref0 then + 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) + 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) + 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 wi = plane * 2 + 1 + if bi then + local b0, b1 = r0 * 8, r1 * 8 + Inter.weight2(P0, P1, bw, bh, dst, o, s, logWD, W0[b0 + wi] or 1, W1[b1 + wi] or 1, ((W0[b0 + wi + 1] or 0) + (W1[b1 + wi + 1] or 0) + 1) // 2) + elseif ref0 then + local b0 = r0 * 8 + Inter.weight1(P0, bw, bh, dst, o, s, logWD, W0[b0 + wi] or 1, W0[b0 + wi + 1] or 0) + else + local b1 = r1 * 8 + Inter.weight1(P1, bw, bh, dst, o, s, logWD, W1[b1 + wi] or 1, W1[b1 + wi + 1] or 0) + end + elseif bi then + Inter.avg(P0, P1, bw, bh, dst, o, s) + elseif ref0 then + Inter.put(P0, bw, bh, dst, o, s) + else + Inter.put(P1, bw, bh, dst, o, s) + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ residual +local function lumaResidual(S: any, M: any) + local pic = S.pic + local b, s = pic.y, pic.ys + local o = pic.yo + M.y * 16 * s + M.x * 16 + local nz, c4, c8 = M.nz, M.c4, M.c8 + if M.t8 == 1 then + for i8 = 0, 3 do + local bx, by = (i8 % 2) * 2, (i8 // 2) * 2 + if nz[by * 4 + bx + 1] > 0 then + add8(c8, i8 * 64, b, o + by * 4 * s + bx * 4, s) + end + end + return + end + for blk = 0, 15 do + if nz[blk + 1] > 0 then + local bx, by = blk % 4, blk // 4 + add4(c4, blk * 16, b, o + by * 4 * s + bx * 4, s) + end + end +end + +local function chromaResidual(S: any, M: any) + if not M.hasDcC and M.cbp < 32 then + return + end + local pic = S.pic + local s = pic.cs + local o = pic.co + M.y * 8 * s + M.x * 8 + local cc, nzc = M.cc, M.nzc + 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) + end + for plane = 0, 1 do + local b = if plane == 0 then pic.u else pic.v + for blk = 0, 3 do + local base = (plane * 4 + blk) * 16 + local q = o + (blk // 2) * 4 * s + (blk % 2) * 4 + if nzc[plane * 4 + blk + 1] > 0 then + add4(cc, base, b, q, s) + elseif cc[base + 1] ~= 0 then + addDc4(cc[base + 1], b, q, s) + cc[base + 1] = 0 + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ intra +local function intraLuma(S: any, M: any) + local pic = S.pic + local b, s = pic.y, pic.ys + local o = pic.yo + M.y * 16 * s + M.x * 16 + local kind = M.kind + local ipm = M.ipm + if kind == K_I16 then + Intra.pred16x16(b, o, s, M.i16, M.iL, M.iT, M.iTL) + local c4, nz = M.c4, M.nz + if M.hasDcY then + Transform.lumaDc(M.dcY, S.dq.d4[1][M.qp + 1][1], c4) + end + for blk = 0, 15 do + local bx, by = blk % 4, blk // 4 + local q = o + by * 4 * s + bx * 4 + if nz[blk + 1] > 0 then + add4(c4, blk * 16, b, q, s) + elseif c4[blk * 16 + 1] ~= 0 then + addDc4(c4[blk * 16 + 1], b, q, s) + c4[blk * 16 + 1] = 0 + end + end + elseif kind == K_I8 then + local nz, c8 = M.nz, M.c8 + for i8 = 0, 3 do + local bx, by = (i8 % 2) * 2, (i8 // 2) * 2 + local left = bx > 0 or M.iL + local top = by > 0 or M.iT + local tr, tl + if i8 == 0 then + tr, tl = M.iT, M.iTL + elseif i8 == 1 then + tr, tl = M.iTR, M.iT + elseif i8 == 2 then + tr, tl = true, M.iL + else + tr, tl = false, true + end + local q = o + by * 4 * s + bx * 4 + Intra.pred8x8(b, q, s, ipm[by * 4 + bx + 1], left, top, tr, tl) + if nz[by * 4 + bx + 1] > 0 then + add8(c8, i8 * 64, b, q, s) + end + end + else + local nz, c4 = M.nz, M.c4 + for i = 0, 15 do + local bx, by = BLK_X[i + 1], BLK_Y[i + 1] + local blk = by * 4 + bx + local left = bx > 0 or M.iL + local top = by > 0 or M.iT + local tl + if bx > 0 and by > 0 then + tl = true + elseif bx > 0 then + tl = M.iT + elseif by > 0 then + tl = M.iL + else + tl = M.iTL + end + local tr + if by == 0 then + tr = if bx < 3 then M.iT else M.iTR + else + tr = not (bx == 3 or (bx == 1 and (by == 1 or by == 3))) + end + local q = o + by * 4 * s + bx * 4 + Intra.pred4x4(b, q, s, ipm[blk + 1], left, top, tr, tl) + if nz[blk + 1] > 0 then + add4(c4, blk * 16, b, q, s) + end + end + end +end + +local function intraChroma(S: any, M: any) + local pic = S.pic + local s = pic.cs + local o = pic.co + M.y * 8 * s + M.x * 8 + Intra.predChroma(pic.u, o, s, M.cpm, M.iL, M.iT, M.iTL) + Intra.predChroma(pic.v, o, s, M.cpm, M.iL, M.iT, M.iTL) +end + +local function pcm(S: any, M: any) + local pic = S.pic + local src = M.pcm + local s = pic.ys + local o = pic.yo + M.y * 16 * s + M.x * 16 + for y = 0, 15 do + buffer.copy(pic.y, o + y * s, src, y * 16, 16) + end + s = pic.cs + o = pic.co + M.y * 8 * s + M.x * 8 + for y = 0, 7 do + buffer.copy(pic.u, o + y * s, src, 256 + y * 8, 8) + buffer.copy(pic.v, o + y * s, src, 320 + y * 8, 8) + end +end + +-- ------------------------------------------------------------------------------------------------ macroblock +-- recon(S, M): reconstruct the parsed macroblock and store what later macroblocks / deblocking need +function Mb.recon(S: any, M: any) + local kind = M.kind + local addr = M.addr + 1 + local pic = S.pic + local w4 = S.w4 + 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 + pic.mbIntra[addr] = kind <= K_PCM + local nzDb = S.nzDb + local g0 = M.g0 + if kind <= K_PCM then + -- intra: no motion + local ref0, ref1, uid0, uid1 = pic.ref0, pic.ref1, pic.uid0, pic.uid1 + for j = 0, 3 do + local g = g0 + j * w4 + for i = 0, 3 do + ref0[g + i], ref1[g + i], uid0[g + i], uid1[g + i] = -1, -1, -1, -1 + end + end + if kind == K_PCM or kind == K_I16 then + local ipm = S.ipm + for j = 0, 3 do + local g = g0 + j * w4 + ipm[g], ipm[g + 1], ipm[g + 2], ipm[g + 3] = 2, 2, 2, 2 + end + end + if kind == K_PCM then + pcm(S, M) + return + end + intraLuma(S, M) + intraChroma(S, M) + chromaResidual(S, M) + return + end + local ipm = S.ipm + for j = 0, 3 do + local g = g0 + j * w4 + ipm[g], ipm[g + 1], ipm[g + 2], ipm[g + 3] = 2, 2, 2, 2 + end + motion(S, M) + mc(S, M) + local nz = M.nz + 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 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 + end + end + if M.cbp % 16 ~= 0 then + lumaResidual(S, M) + end + chromaResidual(S, M) +end + +-- skip(S, M, kind): a P_Skip / B_Skip macroblock (no residual) +function Mb.skip(S: any, M: any, kind: number) + M.kind = kind + M.cbp = 0 + M.t8 = 0 + M.qp = S.qp + M.qpc = S.qpcOf[S.qp + 1] + M.qpc2 = S.qpc2Of[S.qp + 1] + local addr = M.addr + 1 + S.cbpTab[addr] = 0 + S.dcTab[addr] = 0 + S.cpmTab[addr] = 0 + S.qpdTab[addr] = 0 + local nz = M.nz + for i = 1, 16 do + nz[i] = 0 + end + local nzc = M.nzc + for i = 1, 8 do + nzc[i] = 0 + end + local w4, g0 = S.w4, M.g0 + local grid, mvd0, mvd1, rgt0, rgt1 = S.nzc, S.mvd0, S.mvd1, S.rgt0, S.rgt1 + for j = 0, 3 do + local g = g0 + j * w4 + for i = 0, 3 do + grid[g + i] = 0 + mvd0[2 * (g + i) - 1], mvd0[2 * (g + i)] = 0, 0 + mvd1[2 * (g + i) - 1], mvd1[2 * (g + i)] = 0, 0 + rgt0[g + i], rgt1[g + i] = 0, 0 + end + end + local cw, c0 = S.cw4, M.c0 + local cb, cr = S.nzcCb, S.nzcCr + cb[c0], cb[c0 + 1], cb[c0 + cw], cb[c0 + cw + 1] = 0, 0, 0, 0 + cr[c0], cr[c0 + 1], cr[c0 + cw], cr[c0 + cw + 1] = 0, 0, 0, 0 + M.hasDcC = false + Mb.recon(S, M) +end + +return Mb diff --git a/src/Formats/codecs/H264/Params.luau b/src/Formats/codecs/H264/Params.luau new file mode 100644 index 0000000..04c2682 --- /dev/null +++ b/src/Formats/codecs/H264/Params.luau @@ -0,0 +1,453 @@ +--!strict +--!native +-- codecs/H264/Params: sequence and picture parameter sets (ITU-T H.264 7.3.2.1 / 7.3.2.2 / E.1), scaling lists with +-- the fall-back rules A and B (7.4.2.1.1 / table 7-2), and the dequantisation tables built from them (8.5.9: the +-- LevelScale4x4 / LevelScale8x8 functions, premultiplied by 2^(qP / 6)). Written from the spec. +-- Never throws: parse functions return nil, "message". +local Bitstream = require("@formats/codecs/H264/Bitstream") +local Tables = require("@formats/codecs/H264/Tables") + +local u, u1, ue, se = Bitstream.u, Bitstream.u1, Bitstream.ue, Bitstream.se + +local Params = {} + +local HIGH_PROFILES = { [100] = true, [110] = true, [122] = true, [244] = true, [44] = true, [83] = true, [86] = true, [118] = true, [128] = true, [138] = true, [139] = true, [134] = true, [135] = true } + +-- MaxDpbMbs by level_idc (table A-1); level 9 is level 1b +local MAX_DPB_MBS = { [9] = 396, [10] = 396, [11] = 900, [12] = 2376, [13] = 2376, [20] = 2376, [21] = 4752, [22] = 8100, [30] = 8100, [31] = 18000, [32] = 20480, [40] = 32768, [41] = 32768, [42] = 34816, [50] = 110400, [51] = 184320, [52] = 184320, [60] = 696320, [61] = 696320, [62] = 696320 } + +local ZIGZAG4, ZIGZAG8 = Tables.ZIGZAG4, Tables.ZIGZAG8 + +-- scaling_list(): returns the list in raster order, or "default" (useDefaultScalingMatrixFlag) +local function scalingList(r: Bitstream.Reader, size: number): any + local list = table.create(size, 0) + local last, nxt = 8, 8 + local zz = if size == 16 then ZIGZAG4 else ZIGZAG8 + for j = 0, size - 1 do + if nxt ~= 0 then + local d = se(r) + if d < -128 or d > 127 then + return nil + end + nxt = (last + d + 256) % 256 + if j == 0 and nxt == 0 then + return "default" + end + end + local v = if nxt == 0 then last else nxt + list[zz[j + 1] + 1] = v + last = v + end + return list +end + +-- lists: 12 entries (false = not present, "default", or a raster list) +local function scalingMatrix(r: Bitstream.Reader, count: number): { any }? + local lists = table.create(12, false) + for i = 1, count do + if u1(r) == 1 then + local l = scalingList(r, if i <= 6 then 16 else 64) + if l == nil then + return nil + end + lists[i] = l + end + end + return lists +end + +local function default(i: number): { number } + local out = {} + if i <= 6 then + local base = if i <= 3 then 0 else 16 + for k = 1, 16 do + out[k] = Tables.DEFAULT_4x4[base + k] + end + else + local base = if (i - 7) % 2 == 0 then 0 else 64 + for k = 1, 64 do + out[k] = Tables.DEFAULT_8x8[base + k] + end + end + return out +end + +local FLAT16, FLAT64 = table.create(16, 16), table.create(64, 16) + +-- resolve(lists, fallback) -> 12 raster lists. fallback: nil = rule A (defaults), else the 12 lists of the SPS (rule B) +local function resolve(lists: { any }, fallback: { { number } }?): { { number } } + local out = {} + for i = 1, 12 do + local l = lists[i] + if l == "default" then + out[i] = default(i) + elseif l then + out[i] = l + elseif i == 1 or i == 4 or i == 7 or i == 8 then + out[i] = if fallback then fallback[i] else default(i) + elseif i <= 6 then + out[i] = out[i - 1] + else + out[i] = out[i - 2] + end + end + return out +end + +-- ------------------------------------------------------------------------------------------------ vui +local function hrd(r: Bitstream.Reader) + local cnt = ue(r) + if cnt > 31 then + return false + end + u(r, 8) + for _ = 0, cnt do + ue(r) + ue(r) + u1(r) + end + u(r, 20) + return true +end + +local function vui(r: Bitstream.Reader, sps: any) + if u1(r) == 1 then + local idc = u(r, 8) + if idc == 255 then + sps.sarW = u(r, 16) + sps.sarH = u(r, 16) + end + sps.aspectIdc = idc + end + if u1(r) == 1 then + u1(r) + end + if u1(r) == 1 then + u(r, 3) + sps.fullRange = u1(r) == 1 + if u1(r) == 1 then + sps.colourPrimaries = u(r, 8) + sps.transfer = u(r, 8) + sps.matrix = u(r, 8) + end + end + if u1(r) == 1 then + ue(r) + ue(r) + end + if u1(r) == 1 then + sps.unitsInTick = u(r, 32) + sps.timeScale = u(r, 32) + sps.fixedRate = u1(r) == 1 + end + local nal = u1(r) == 1 + if nal and not hrd(r) then + return + end + local vcl = u1(r) == 1 + if vcl and not hrd(r) then + return + end + if nal or vcl then + u1(r) + end + u1(r) + if u1(r) == 1 then + u1(r) + ue(r) + ue(r) + ue(r) + ue(r) + local reorder = ue(r) + local dpb = ue(r) + if r.pos <= r.size and reorder <= 16 and dpb <= 16 then + sps.numReorderFrames = reorder + sps.maxDecFrameBuffering = dpb + end + end +end + +-- ------------------------------------------------------------------------------------------------ sps +-- sps(r) -> the SPS table | nil, message. r is positioned after the NAL header. +function Params.sps(r: Bitstream.Reader): (any, string?) + local sps: any = {} + sps.profile = u(r, 8) + sps.constraints = u(r, 8) + sps.level = u(r, 8) + sps.id = ue(r) + if sps.id > 31 then + return nil, "seq_parameter_set_id out of range" + end + sps.chromaFormat = 1 + sps.bitDepth = 8 + sps.bitDepthC = 8 + sps.bypass = false + sps.scaling = nil + if HIGH_PROFILES[sps.profile] then + sps.chromaFormat = ue(r) + if sps.chromaFormat > 3 then + return nil, "chroma_format_idc out of range" + end + if sps.chromaFormat == 3 then + sps.separatePlanes = u1(r) == 1 + end + sps.bitDepth = ue(r) + 8 + sps.bitDepthC = ue(r) + 8 + if sps.bitDepth > 14 or sps.bitDepthC > 14 then + return nil, "bit depth out of range" + end + sps.bypass = u1(r) == 1 + if u1(r) == 1 then + local lists = scalingMatrix(r, if sps.chromaFormat ~= 3 then 8 else 12) + if not lists then + return nil, "bad scaling list" + end + sps.scaling = resolve(lists, nil) + end + end + sps.log2MaxFrameNum = ue(r) + 4 + if sps.log2MaxFrameNum > 16 then + return nil, "log2_max_frame_num out of range" + end + sps.pocType = ue(r) + if sps.pocType == 0 then + sps.log2MaxPocLsb = ue(r) + 4 + if sps.log2MaxPocLsb > 16 then + return nil, "log2_max_pic_order_cnt_lsb out of range" + end + elseif sps.pocType == 1 then + sps.deltaPocAlwaysZero = u1(r) == 1 + sps.offsetNonRef = se(r) + sps.offsetTopToBottom = se(r) + local n = ue(r) + if n > 255 then + return nil, "num_ref_frames_in_pic_order_cnt_cycle out of range" + end + sps.offsetsForRefFrame = {} + local expected = 0 + for i = 1, n do + sps.offsetsForRefFrame[i] = se(r) + expected += sps.offsetsForRefFrame[i] + end + sps.expectedDeltaPerCycle = expected + elseif sps.pocType ~= 2 then + return nil, "pic_order_cnt_type out of range" + end + sps.maxRefFrames = ue(r) + if sps.maxRefFrames > 16 then + return nil, "max_num_ref_frames out of range" + end + sps.gapsAllowed = u1(r) == 1 + sps.mbWidth = ue(r) + 1 + sps.mbHeightMap = ue(r) + 1 + sps.frameMbsOnly = u1(r) == 1 + if not sps.frameMbsOnly then + sps.mbaff = u1(r) == 1 + end + sps.mbHeight = if sps.frameMbsOnly then sps.mbHeightMap else sps.mbHeightMap * 2 + if sps.mbWidth > 1024 or sps.mbHeight > 1024 then + return nil, "limit: picture too large" + end + sps.direct8x8 = u1(r) == 1 + sps.cropLeft, sps.cropRight, sps.cropTop, sps.cropBottom = 0, 0, 0, 0 + if u1(r) == 1 then + sps.cropLeft = ue(r) + sps.cropRight = ue(r) + sps.cropTop = ue(r) + sps.cropBottom = ue(r) + end + if r.pos > r.size then + return nil, "truncated: sequence parameter set" + end + if u1(r) == 1 then + local save = r.pos + vui(r, sps) + if r.pos > r.size then + r.pos = save + end + end + -- derived sizes (4:2:0 crop units: 2 x 2; monochrome / 4:4:4 are rejected later) + local cux, cuy = 2, 2 * (if sps.frameMbsOnly then 1 else 2) + if sps.chromaFormat == 0 or sps.chromaFormat == 3 then + cux, cuy = 1, (if sps.frameMbsOnly then 1 else 2) + elseif sps.chromaFormat == 2 then + cux, cuy = 2, (if sps.frameMbsOnly then 1 else 2) + end + local w, h = sps.mbWidth * 16, sps.mbHeight * 16 + sps.width = w - cux * (sps.cropLeft + sps.cropRight) + sps.height = h - cuy * (sps.cropTop + sps.cropBottom) + sps.cropX = cux * sps.cropLeft + sps.cropY = cuy * sps.cropTop + if sps.width <= 0 or sps.height <= 0 then + return nil, "cropping larger than the picture" + end + local maxMbs = MAX_DPB_MBS[sps.level] or 696320 + if sps.level == 11 and sps.constraints % 32 >= 16 and sps.profile ~= 100 then + maxMbs = 396 -- level 1b + end + sps.maxDpbFrames = math.clamp(maxMbs // (sps.mbWidth * sps.mbHeight), 1, 16) + return sps, nil +end + +-- ------------------------------------------------------------------------------------------------ pps +-- pps(r, spsTable) -> the PPS | nil, message. spsTable: id -> SPS (needed for the scaling list count) +function Params.pps(r: Bitstream.Reader, spsTable: { [number]: any }): (any, string?) + local pps: any = {} + pps.id = ue(r) + if pps.id > 255 then + return nil, "pic_parameter_set_id out of range" + end + pps.spsId = ue(r) + local sps = spsTable[pps.spsId] + if not sps then + return nil, "pps refers to a missing sps" + end + pps.cabac = u1(r) == 1 + pps.bottomFieldPocPresent = u1(r) == 1 + pps.sliceGroups = ue(r) + 1 + if pps.sliceGroups > 1 then + return nil, "unsupported: slice groups (FMO)" + end + pps.numRefIdxL0 = ue(r) + 1 + pps.numRefIdxL1 = ue(r) + 1 + if pps.numRefIdxL0 > 32 or pps.numRefIdxL1 > 32 then + return nil, "num_ref_idx_default_active out of range" + end + pps.weightedPred = u1(r) == 1 + pps.weightedBipred = u(r, 2) + pps.initQp = 26 + se(r) + pps.initQs = 26 + se(r) + pps.chromaQpOffset = se(r) + if pps.initQp < 0 or pps.initQp > 51 or pps.chromaQpOffset < -12 or pps.chromaQpOffset > 12 then + return nil, "pic_init_qp / chroma_qp_index_offset out of range" + end + pps.deblockingControl = u1(r) == 1 + pps.constrainedIntra = u1(r) == 1 + pps.redundantPicCnt = u1(r) == 1 + pps.transform8x8 = false + pps.chromaQpOffset2 = pps.chromaQpOffset + pps.scalingLists = nil + if r.pos > r.size then + return nil, "truncated: picture parameter set" + end + if Bitstream.moreData(r) then + pps.transform8x8 = u1(r) == 1 + if u1(r) == 1 then + local n = 6 + (if pps.transform8x8 then (if sps.chromaFormat ~= 3 then 2 else 6) else 0) + local lists = scalingMatrix(r, n) + if not lists then + return nil, "bad scaling list" + end + pps.scalingLists = lists + end + pps.chromaQpOffset2 = se(r) + if pps.chromaQpOffset2 < -12 or pps.chromaQpOffset2 > 12 then + return nil, "second_chroma_qp_index_offset out of range" + end + if r.pos > r.size then + return nil, "truncated: picture parameter set" + end + end + return pps, nil +end + +-- ------------------------------------------------------------------------------------------------ dequantisation +local V4 = { { 10, 16, 13 }, { 11, 18, 14 }, { 13, 20, 16 }, { 14, 23, 18 }, { 16, 25, 20 }, { 18, 29, 23 } } +local V8 = { + { 20, 18, 32, 19, 25, 24 }, + { 22, 19, 35, 21, 28, 26 }, + { 26, 23, 42, 24, 33, 31 }, + { 28, 25, 45, 26, 35, 33 }, + { 32, 28, 51, 30, 40, 38 }, + { 36, 32, 58, 34, 46, 43 }, +} + +local function norm4(m: number, i: number, j: number): number + local v = V4[m + 1] + if i % 2 == 0 and j % 2 == 0 then + return v[1] + elseif i % 2 == 1 and j % 2 == 1 then + return v[2] + end + return v[3] +end + +local function norm8(m: number, i: number, j: number): number + local v = V8[m + 1] + if i % 4 == 0 and j % 4 == 0 then + return v[1] + elseif i % 2 == 1 and j % 2 == 1 then + return v[2] + elseif i % 4 == 2 and j % 4 == 2 then + return v[3] + elseif (i % 4 == 0 and j % 2 == 1) or (i % 2 == 1 and j % 4 == 0) then + return v[4] + elseif (i % 4 == 0 and j % 4 == 2) or (i % 4 == 2 and j % 4 == 0) then + return v[5] + end + return v[6] +end + +-- dequant tables: dq.d4[list][qp + 1] = 16 multipliers (raster), list 1..6 = Y/Cb/Cr intra, Y/Cb/Cr inter; +-- dq.d8[list][qp + 1] = 64 multipliers, list 1 = Y intra, 2 = Y inter. A 4x4 coefficient c dequantises to +-- (c * m + 8) >> 4, an 8x8 one to (c * m + 32) >> 6 (8.5.12.1 / 8.5.13.1 with LevelScale * 2^(qP / 6)). +local function build(lists: { { number } }): any + local d4, d8 = {}, {} + for l = 1, 6 do + local w = lists[l] + local per = {} + for qp = 0, 51 do + local m, sh = qp % 6, 2 ^ (qp // 6) + local t = table.create(16, 0) + for k = 0, 15 do + local i, j = k % 4, k // 4 + t[k + 1] = w[k + 1] * norm4(m, i, j) * sh + end + per[qp + 1] = t + end + d4[l] = per + end + for l = 1, 2 do + local w = lists[6 + l] + local per = {} + for qp = 0, 51 do + local m, sh = qp % 6, 2 ^ (qp // 6) + local t = table.create(64, 0) + for k = 0, 63 do + local i, j = k % 8, k // 8 + t[k + 1] = w[k + 1] * norm8(m, i, j) * sh + end + per[qp + 1] = t + end + d8[l] = per + end + return { d4 = d4, d8 = d8 } +end + +-- dequant(sps, pps, cache) -> the dequant tables for this pair (cache: a table kept by the decoder, by content) +function Params.dequant(sps: any, pps: any, cache: { [string]: any }): any + local lists: { { number } } + if pps.scalingLists then + lists = resolve(pps.scalingLists, sps.scaling) + elseif sps.scaling then + lists = sps.scaling + else + lists = {} + for i = 1, 12 do + lists[i] = if i <= 6 then FLAT16 else FLAT64 + end + end + local parts = {} + for i = 1, 8 do + parts[i] = table.concat(lists[i], ",") + end + local key = table.concat(parts, ";") + local dq = cache[key] + if not dq then + dq = build(lists) + cache[key] = dq + end + return dq +end + +return Params diff --git a/src/Formats/codecs/H264/Slice.luau b/src/Formats/codecs/H264/Slice.luau new file mode 100644 index 0000000..8aa9acd --- /dev/null +++ b/src/Formats/codecs/H264/Slice.luau @@ -0,0 +1,251 @@ +--!strict +--!native +-- codecs/H264/Slice: the slice header (ITU-T H.264 7.3.3): ref_pic_list_modification, pred_weight_table and +-- dec_ref_pic_marking. Written from the spec. Frame coding only: field pictures (field_pic_flag = 1), MBAFF, +-- SP / SI slices, separate colour planes and redundant pictures return "unsupported: ...". +-- Never throws: header() returns nil, "message". +local Bitstream = require("@formats/codecs/H264/Bitstream") + +local u, u1, ue, se = Bitstream.u, Bitstream.u1, Bitstream.ue, Bitstream.se + +local Slice = {} + +Slice.P, Slice.B, Slice.I, Slice.SP, Slice.SI = 0, 1, 2, 3, 4 + +local function modifications(r: Bitstream.Reader): { number }? + local ops = {} + if u1(r) == 1 then + for _ = 1, 100 do + local idc = ue(r) + if idc == 3 then + return ops + end + if idc > 5 then + return nil + end + table.insert(ops, idc) + table.insert(ops, ue(r)) + if r.pos > r.size then + return nil + end + end + return nil + end + return ops +end + +local function weights(r: Bitstream.Reader, n: number, lw: number, cw: number, chroma: boolean): { number }? + -- per entry: lumaW, lumaO, cbW, cbO, crW, crO, lumaFlag, chromaFlag (8 numbers) + local t = table.create(n * 8, 0) + for i = 0, n - 1 do + local b = i * 8 + t[b + 1], t[b + 2], t[b + 3], t[b + 4], t[b + 5], t[b + 6] = lw, 0, cw, 0, cw, 0 + if u1(r) == 1 then + t[b + 1] = se(r) + t[b + 2] = se(r) + t[b + 7] = 1 + if t[b + 1] < -128 or t[b + 1] > 127 or t[b + 2] < -128 or t[b + 2] > 127 then + return nil + end + end + if chroma and u1(r) == 1 then + for k = 0, 1 do + t[b + 3 + k * 2] = se(r) + t[b + 4 + k * 2] = se(r) + if t[b + 3 + k * 2] < -128 or t[b + 3 + k * 2] > 127 or t[b + 4 + k * 2] < -128 or t[b + 4 + k * 2] > 127 then + return nil + end + end + t[b + 8] = 1 + end + end + return t +end + +-- header(r, nalType, nalRefIdc, spsTable, ppsTable) -> sh | nil, message +function Slice.header(r: Bitstream.Reader, nalType: number, nalRefIdc: number, spsTable: { [number]: any }, ppsTable: { [number]: any }): (any, string?) + local sh: any = {} + sh.nalType = nalType + sh.nalRefIdc = nalRefIdc + sh.idr = nalType == 5 + sh.firstMb = ue(r) + local st = ue(r) + if st > 9 then + return nil, "slice_type out of range" + end + sh.type = st % 5 + if sh.type == Slice.SP or sh.type == Slice.SI then + return nil, "unsupported: SP / SI slices (Extended profile)" + end + sh.ppsId = ue(r) + local pps = ppsTable[sh.ppsId] + if not pps then + return nil, "slice refers to a missing pps" + end + local sps = spsTable[pps.spsId] + if not sps then + return nil, "slice refers to a missing sps" + end + sh.pps, sh.sps = pps, sps + if sps.separatePlanes then + return nil, "unsupported: separate colour planes" + end + sh.frameNum = u(r, sps.log2MaxFrameNum) + if not sps.frameMbsOnly then + if u1(r) == 1 then + return nil, "unsupported: field pictures (PAFF)" + end + if sps.mbaff then + return nil, "unsupported: MBAFF" + end + end + if sh.idr then + sh.idrPicId = ue(r) + end + sh.pocLsb, sh.deltaPocBottom, sh.deltaPoc0, sh.deltaPoc1 = 0, 0, 0, 0 + if sps.pocType == 0 then + sh.pocLsb = u(r, sps.log2MaxPocLsb) + if pps.bottomFieldPocPresent then + sh.deltaPocBottom = se(r) + end + elseif sps.pocType == 1 and not sps.deltaPocAlwaysZero then + sh.deltaPoc0 = se(r) + if pps.bottomFieldPocPresent then + sh.deltaPoc1 = se(r) + end + end + if pps.redundantPicCnt then + sh.redundantPicCnt = ue(r) + end + sh.numRefIdxL0, sh.numRefIdxL1 = 0, 0 + if sh.type == Slice.B then + sh.directSpatial = u1(r) == 1 + end + if sh.type ~= Slice.I then + sh.numRefIdxL0 = pps.numRefIdxL0 + sh.numRefIdxL1 = if sh.type == Slice.B then pps.numRefIdxL1 else 0 + if u1(r) == 1 then + sh.numRefIdxL0 = ue(r) + 1 + if sh.type == Slice.B then + sh.numRefIdxL1 = ue(r) + 1 + end + end + if sh.numRefIdxL0 > 32 or sh.numRefIdxL1 > 32 then + return nil, "num_ref_idx_active out of range" + end + local m = modifications(r) + if not m then + return nil, "bad ref_pic_list_modification" + end + sh.mod0 = m + if sh.type == Slice.B then + m = modifications(r) + if not m then + return nil, "bad ref_pic_list_modification" + end + sh.mod1 = m + end + end + sh.weightMode = 0 -- 0 default, 1 explicit, 2 implicit + if (pps.weightedPred and sh.type == Slice.P) or (pps.weightedBipred == 1 and sh.type == Slice.B) then + sh.weightMode = 1 + sh.lumaDenom = ue(r) + if sh.lumaDenom > 7 then + return nil, "luma_log2_weight_denom out of range" + end + local chroma = sps.chromaFormat ~= 0 + sh.chromaDenom = 0 + if chroma then + sh.chromaDenom = ue(r) + if sh.chromaDenom > 7 then + return nil, "chroma_log2_weight_denom out of range" + end + end + local w = weights(r, sh.numRefIdxL0, 2 ^ sh.lumaDenom, 2 ^ sh.chromaDenom, chroma) + if not w then + return nil, "bad pred_weight_table" + end + sh.weights0 = w + if sh.type == Slice.B then + w = weights(r, sh.numRefIdxL1, 2 ^ sh.lumaDenom, 2 ^ sh.chromaDenom, chroma) + if not w then + return nil, "bad pred_weight_table" + end + sh.weights1 = w + end + elseif pps.weightedBipred == 2 and sh.type == Slice.B then + sh.weightMode = 2 + end + if nalRefIdc ~= 0 then + if sh.idr then + sh.noOutputOfPriorPics = u1(r) == 1 + sh.longTermReference = u1(r) == 1 + else + sh.adaptive = u1(r) == 1 + if sh.adaptive then + local ops = {} + for _ = 1, 100 do + local op = ue(r) + if op == 0 then + break + end + if op > 6 then + return nil, "bad memory_management_control_operation" + end + local a, b = 0, 0 + if op == 1 or op == 3 then + a = ue(r) + 1 -- difference_of_pic_nums + end + if op == 2 then + a = ue(r) -- long_term_pic_num + end + if op == 3 or op == 6 then + b = ue(r) -- long_term_frame_idx + end + if op == 4 then + a = ue(r) -- max_long_term_frame_idx_plus1 + end + if r.pos > r.size then + return nil, "truncated: dec_ref_pic_marking" + end + table.insert(ops, op) + table.insert(ops, a) + table.insert(ops, b) + end + sh.mmco = ops + end + end + end + sh.cabacInit = 0 + if pps.cabac and sh.type ~= Slice.I then + sh.cabacInit = ue(r) + if sh.cabacInit > 2 then + return nil, "cabac_init_idc out of range" + end + end + sh.qp = pps.initQp + se(r) + if sh.qp < 0 or sh.qp > 51 then + return nil, "slice QP out of range" + end + sh.deblock = 0 + sh.alphaOffset, sh.betaOffset = 0, 0 + if pps.deblockingControl then + sh.deblock = ue(r) + if sh.deblock > 2 then + return nil, "disable_deblocking_filter_idc out of range" + end + if sh.deblock ~= 1 then + sh.alphaOffset = se(r) * 2 + sh.betaOffset = se(r) * 2 + if sh.alphaOffset < -12 or sh.alphaOffset > 12 or sh.betaOffset < -12 or sh.betaOffset > 12 then + return nil, "slice_alpha / beta_offset out of range" + end + end + end + if r.pos > r.size then + return nil, "truncated: slice header" + end + return sh, nil +end + +return Slice diff --git a/src/Formats/codecs/H264/Tables.luau b/src/Formats/codecs/H264/Tables.luau new file mode 100644 index 0000000..fdcaec1 --- /dev/null +++ b/src/Formats/codecs/H264/Tables.luau @@ -0,0 +1,42 @@ +--!strict +--!native +-- codecs/H264/Tables: the constant tables of ITU-T H.264 (CAVLC code tables 9-5, 9-7, 9-8, 9-9, 9-10; CABAC context +-- initialisation tables 9-12..9-24, rangeTabLPS 9-44 and the state transitions 9-45; the chroma QP table 8-15; the +-- me(v) coded_block_pattern mapping 9-4; default scaling lists 7-3 / 7-4; zig-zag scans 8-12 / 8-13; table 9-43; the +-- deblocking alpha / beta / tC0 tables 8-16 / 8-17). Values extracted from openh264 2.x (BSD-2-Clause, +-- licenses/openh264-LICENSE.txt): encoder_data_tables.cpp, common_tables.cpp, decoder_data_tables.cpp, +-- wels_common_basis.h, deblocking.cpp. Flat 1-based arrays; the layouts are noted at each table. +local T = {} + +-- coeff_token per nC class (0: 0<=nC<2, 1: 2<=nC<4, 2: 4<=nC<8, 3: 8<=nC, 4: nC=-1 chroma DC): { code, len, TotalCoeff, +-- TrailingOnes } quads. TOTAL_ZEROS / TOTAL_ZEROS_CDC / RUN_BEFORE: { tzVlcIndex | zerosLeft, code, len, value } quads. +-- CABAC_INIT: [ctxIdx * 8 + model * 2 + 1] = m, [... + 2] = n; model 0 = I slices, 1..3 = cabac_init_idc 0..2. +-- RANGE_LPS: [pStateIdx * 4 + qCodIRangeIdx + 1]. TRANS: [pStateIdx * 2 + 1] = transIdxLPS, [+ 2] = transIdxMPS. +-- DEFAULT_4x4 / DEFAULT_8x8: intra list then inter list, raster order. ZIGZAG4 / ZIGZAG8: scan index -> raster index. +-- SIG8 / LAST8: 8x8 significant / last ctxIdxInc by scan index (frame coded). ALPHA / BETA: [indexA + 13] (index +-- -12..63); TC0: [(indexA + 12) * 4 + bS + 1] (bS 0..3; bS 0 is unused). +T.COEFF_TOKEN_0 = { 1, 1, 0, 0, 5, 6, 1, 0, 1, 2, 1, 1, 7, 8, 2, 0, 4, 6, 2, 1, 1, 3, 2, 2, 7, 9, 3, 0, 6, 8, 3, 1, 5, 7, 3, 2, 3, 5, 3, 3, 7, 10, 4, 0, 6, 9, 4, 1, 5, 8, 4, 2, 3, 6, 4, 3, 7, 11, 5, 0, 6, 10, 5, 1, 5, 9, 5, 2, 4, 7, 5, 3, 15, 13, 6, 0, 6, 11, 6, 1, 5, 10, 6, 2, 4, 8, 6, 3, 11, 13, 7, 0, 14, 13, 7, 1, 5, 11, 7, 2, 4, 9, 7, 3, 8, 13, 8, 0, 10, 13, 8, 1, 13, 13, 8, 2, 4, 10, 8, 3, 15, 14, 9, 0, 14, 14, 9, 1, 9, 13, 9, 2, 4, 11, 9, 3, 11, 14, 10, 0, 10, 14, 10, 1, 13, 14, 10, 2, 12, 13, 10, 3, 15, 15, 11, 0, 14, 15, 11, 1, 9, 14, 11, 2, 12, 14, 11, 3, 11, 15, 12, 0, 10, 15, 12, 1, 13, 15, 12, 2, 8, 14, 12, 3, 15, 16, 13, 0, 1, 15, 13, 1, 9, 15, 13, 2, 12, 15, 13, 3, 11, 16, 14, 0, 14, 16, 14, 1, 13, 16, 14, 2, 8, 15, 14, 3, 7, 16, 15, 0, 10, 16, 15, 1, 9, 16, 15, 2, 12, 16, 15, 3, 4, 16, 16, 0, 6, 16, 16, 1, 5, 16, 16, 2, 8, 16, 16, 3 } +T.COEFF_TOKEN_1 = { 3, 2, 0, 0, 11, 6, 1, 0, 2, 2, 1, 1, 7, 6, 2, 0, 7, 5, 2, 1, 3, 3, 2, 2, 7, 7, 3, 0, 10, 6, 3, 1, 9, 6, 3, 2, 5, 4, 3, 3, 7, 8, 4, 0, 6, 6, 4, 1, 5, 6, 4, 2, 4, 4, 4, 3, 4, 8, 5, 0, 6, 7, 5, 1, 5, 7, 5, 2, 6, 5, 5, 3, 7, 9, 6, 0, 6, 8, 6, 1, 5, 8, 6, 2, 8, 6, 6, 3, 15, 11, 7, 0, 6, 9, 7, 1, 5, 9, 7, 2, 4, 6, 7, 3, 11, 11, 8, 0, 14, 11, 8, 1, 13, 11, 8, 2, 4, 7, 8, 3, 15, 12, 9, 0, 10, 11, 9, 1, 9, 11, 9, 2, 4, 9, 9, 3, 11, 12, 10, 0, 14, 12, 10, 1, 13, 12, 10, 2, 12, 11, 10, 3, 8, 12, 11, 0, 10, 12, 11, 1, 9, 12, 11, 2, 8, 11, 11, 3, 15, 13, 12, 0, 14, 13, 12, 1, 13, 13, 12, 2, 12, 12, 12, 3, 11, 13, 13, 0, 10, 13, 13, 1, 9, 13, 13, 2, 12, 13, 13, 3, 7, 13, 14, 0, 11, 14, 14, 1, 6, 13, 14, 2, 8, 13, 14, 3, 9, 14, 15, 0, 8, 14, 15, 1, 10, 14, 15, 2, 1, 13, 15, 3, 7, 14, 16, 0, 6, 14, 16, 1, 5, 14, 16, 2, 4, 14, 16, 3 } +T.COEFF_TOKEN_2 = { 15, 4, 0, 0, 15, 6, 1, 0, 14, 4, 1, 1, 11, 6, 2, 0, 15, 5, 2, 1, 13, 4, 2, 2, 8, 6, 3, 0, 12, 5, 3, 1, 14, 5, 3, 2, 12, 4, 3, 3, 15, 7, 4, 0, 10, 5, 4, 1, 11, 5, 4, 2, 11, 4, 4, 3, 11, 7, 5, 0, 8, 5, 5, 1, 9, 5, 5, 2, 10, 4, 5, 3, 9, 7, 6, 0, 14, 6, 6, 1, 13, 6, 6, 2, 9, 4, 6, 3, 8, 7, 7, 0, 10, 6, 7, 1, 9, 6, 7, 2, 8, 4, 7, 3, 15, 8, 8, 0, 14, 7, 8, 1, 13, 7, 8, 2, 13, 5, 8, 3, 11, 8, 9, 0, 14, 8, 9, 1, 10, 7, 9, 2, 12, 6, 9, 3, 15, 9, 10, 0, 10, 8, 10, 1, 13, 8, 10, 2, 12, 7, 10, 3, 11, 9, 11, 0, 14, 9, 11, 1, 9, 8, 11, 2, 12, 8, 11, 3, 8, 9, 12, 0, 10, 9, 12, 1, 13, 9, 12, 2, 8, 8, 12, 3, 13, 10, 13, 0, 7, 9, 13, 1, 9, 9, 13, 2, 12, 9, 13, 3, 9, 10, 14, 0, 12, 10, 14, 1, 11, 10, 14, 2, 10, 10, 14, 3, 5, 10, 15, 0, 8, 10, 15, 1, 7, 10, 15, 2, 6, 10, 15, 3, 1, 10, 16, 0, 4, 10, 16, 1, 3, 10, 16, 2, 2, 10, 16, 3 } +T.COEFF_TOKEN_3 = { 3, 6, 0, 0, 0, 6, 1, 0, 1, 6, 1, 1, 4, 6, 2, 0, 5, 6, 2, 1, 6, 6, 2, 2, 8, 6, 3, 0, 9, 6, 3, 1, 10, 6, 3, 2, 11, 6, 3, 3, 12, 6, 4, 0, 13, 6, 4, 1, 14, 6, 4, 2, 15, 6, 4, 3, 16, 6, 5, 0, 17, 6, 5, 1, 18, 6, 5, 2, 19, 6, 5, 3, 20, 6, 6, 0, 21, 6, 6, 1, 22, 6, 6, 2, 23, 6, 6, 3, 24, 6, 7, 0, 25, 6, 7, 1, 26, 6, 7, 2, 27, 6, 7, 3, 28, 6, 8, 0, 29, 6, 8, 1, 30, 6, 8, 2, 31, 6, 8, 3, 32, 6, 9, 0, 33, 6, 9, 1, 34, 6, 9, 2, 35, 6, 9, 3, 36, 6, 10, 0, 37, 6, 10, 1, 38, 6, 10, 2, 39, 6, 10, 3, 40, 6, 11, 0, 41, 6, 11, 1, 42, 6, 11, 2, 43, 6, 11, 3, 44, 6, 12, 0, 45, 6, 12, 1, 46, 6, 12, 2, 47, 6, 12, 3, 48, 6, 13, 0, 49, 6, 13, 1, 50, 6, 13, 2, 51, 6, 13, 3, 52, 6, 14, 0, 53, 6, 14, 1, 54, 6, 14, 2, 55, 6, 14, 3, 56, 6, 15, 0, 57, 6, 15, 1, 58, 6, 15, 2, 59, 6, 15, 3, 60, 6, 16, 0, 61, 6, 16, 1, 62, 6, 16, 2, 63, 6, 16, 3 } +T.COEFF_TOKEN_4 = { 1, 2, 0, 0, 7, 6, 1, 0, 1, 1, 1, 1, 4, 6, 2, 0, 6, 6, 2, 1, 1, 3, 2, 2, 3, 6, 3, 0, 3, 7, 3, 1, 2, 7, 3, 2, 5, 6, 3, 3, 2, 6, 4, 0, 3, 8, 4, 1, 2, 8, 4, 2, 0, 7, 4, 3 } +T.TOTAL_ZEROS = { 1, 1, 1, 0, 1, 3, 3, 1, 1, 2, 3, 2, 1, 3, 4, 3, 1, 2, 4, 4, 1, 3, 5, 5, 1, 2, 5, 6, 1, 3, 6, 7, 1, 2, 6, 8, 1, 3, 7, 9, 1, 2, 7, 10, 1, 3, 8, 11, 1, 2, 8, 12, 1, 3, 9, 13, 1, 2, 9, 14, 1, 1, 9, 15, 2, 7, 3, 0, 2, 6, 3, 1, 2, 5, 3, 2, 2, 4, 3, 3, 2, 3, 3, 4, 2, 5, 4, 5, 2, 4, 4, 6, 2, 3, 4, 7, 2, 2, 4, 8, 2, 3, 5, 9, 2, 2, 5, 10, 2, 3, 6, 11, 2, 2, 6, 12, 2, 1, 6, 13, 2, 0, 6, 14, 3, 5, 4, 0, 3, 7, 3, 1, 3, 6, 3, 2, 3, 5, 3, 3, 3, 4, 4, 4, 3, 3, 4, 5, 3, 4, 3, 6, 3, 3, 3, 7, 3, 2, 4, 8, 3, 3, 5, 9, 3, 2, 5, 10, 3, 1, 6, 11, 3, 1, 5, 12, 3, 0, 6, 13, 4, 3, 5, 0, 4, 7, 3, 1, 4, 5, 4, 2, 4, 4, 4, 3, 4, 6, 3, 4, 4, 5, 3, 5, 4, 4, 3, 6, 4, 3, 4, 7, 4, 3, 3, 8, 4, 2, 4, 9, 4, 2, 5, 10, 4, 1, 5, 11, 4, 0, 5, 12, 5, 5, 4, 0, 5, 4, 4, 1, 5, 3, 4, 2, 5, 7, 3, 3, 5, 6, 3, 4, 5, 5, 3, 5, 5, 4, 3, 6, 5, 3, 3, 7, 5, 2, 4, 8, 5, 1, 5, 9, 5, 1, 4, 10, 5, 0, 5, 11, 6, 1, 6, 0, 6, 1, 5, 1, 6, 7, 3, 2, 6, 6, 3, 3, 6, 5, 3, 4, 6, 4, 3, 5, 6, 3, 3, 6, 6, 2, 3, 7, 6, 1, 4, 8, 6, 1, 3, 9, 6, 0, 6, 10, 7, 1, 6, 0, 7, 1, 5, 1, 7, 5, 3, 2, 7, 4, 3, 3, 7, 3, 3, 4, 7, 3, 2, 5, 7, 2, 3, 6, 7, 1, 4, 7, 7, 1, 3, 8, 7, 0, 6, 9, 8, 1, 6, 0, 8, 1, 4, 1, 8, 1, 5, 2, 8, 3, 3, 3, 8, 3, 2, 4, 8, 2, 2, 5, 8, 2, 3, 6, 8, 1, 3, 7, 8, 0, 6, 8, 9, 1, 6, 0, 9, 0, 6, 1, 9, 1, 4, 2, 9, 3, 2, 3, 9, 2, 2, 4, 9, 1, 3, 5, 9, 1, 2, 6, 9, 1, 5, 7, 10, 1, 5, 0, 10, 0, 5, 1, 10, 1, 3, 2, 10, 3, 2, 3, 10, 2, 2, 4, 10, 1, 2, 5, 10, 1, 4, 6, 11, 0, 4, 0, 11, 1, 4, 1, 11, 1, 3, 2, 11, 2, 3, 3, 11, 1, 1, 4, 11, 3, 3, 5, 12, 0, 4, 0, 12, 1, 4, 1, 12, 1, 2, 2, 12, 1, 1, 3, 12, 1, 3, 4, 13, 0, 3, 0, 13, 1, 3, 1, 13, 1, 1, 2, 13, 1, 2, 3, 14, 0, 2, 0, 14, 1, 2, 1, 14, 1, 1, 2, 15, 0, 1, 0, 15, 1, 1, 1 } +T.TOTAL_ZEROS_CDC = { 1, 1, 1, 0, 1, 1, 2, 1, 1, 1, 3, 2, 1, 0, 3, 3, 2, 1, 1, 0, 2, 1, 2, 1, 2, 0, 2, 2, 3, 1, 1, 0, 3, 0, 1, 1 } +T.RUN_BEFORE = { 1, 1, 1, 0, 1, 0, 1, 1, 2, 1, 1, 0, 2, 1, 2, 1, 2, 0, 2, 2, 3, 3, 2, 0, 3, 2, 2, 1, 3, 1, 2, 2, 3, 0, 2, 3, 4, 3, 2, 0, 4, 2, 2, 1, 4, 1, 2, 2, 4, 1, 3, 3, 4, 0, 3, 4, 5, 3, 2, 0, 5, 2, 2, 1, 5, 3, 3, 2, 5, 2, 3, 3, 5, 1, 3, 4, 5, 0, 3, 5, 6, 3, 2, 0, 6, 0, 3, 1, 6, 1, 3, 2, 6, 3, 3, 3, 6, 2, 3, 4, 6, 5, 3, 5, 6, 4, 3, 6, 7, 7, 3, 0, 7, 6, 3, 1, 7, 5, 3, 2, 7, 4, 3, 3, 7, 3, 3, 4, 7, 2, 3, 5, 7, 1, 3, 6, 7, 1, 4, 7, 7, 1, 5, 8, 7, 1, 6, 9, 7, 1, 7, 10, 7, 1, 8, 11, 7, 1, 9, 12, 7, 1, 10, 13, 7, 1, 11, 14 } +T.CABAC_INIT = { 20, -15, 20, -15, 20, -15, 20, -15, 2, 54, 2, 54, 2, 54, 2, 54, 3, 74, 3, 74, 3, 74, 3, 74, 20, -15, 20, -15, 20, -15, 20, -15, 2, 54, 2, 54, 2, 54, 2, 54, 3, 74, 3, 74, 3, 74, 3, 74, -28, 127, -28, 127, -28, 127, -28, 127, -23, 104, -23, 104, -23, 104, -23, 104, -6, 53, -6, 53, -6, 53, -6, 53, -1, 54, -1, 54, -1, 54, -1, 54, 7, 51, 7, 51, 7, 51, 7, 51, 0, 0, 23, 33, 22, 25, 29, 16, 0, 0, 23, 2, 34, 0, 25, 0, 0, 0, 21, 0, 16, 0, 14, 0, 0, 0, 1, 9, -2, 9, -10, 51, 0, 0, 0, 49, 4, 41, -3, 62, 0, 0, -37, 118, -29, 118, -27, 99, 0, 0, 5, 57, 2, 65, 26, 16, 0, 0, -13, 78, -6, 71, -4, 85, 0, 0, -11, 65, -13, 79, -24, 102, 0, 0, 1, 62, 5, 52, 5, 57, 0, 0, 12, 49, 9, 50, 6, 57, 0, 0, -4, 73, -3, 70, -17, 73, 0, 0, 17, 50, 10, 54, 14, 57, 0, 0, 18, 64, 26, 34, 20, 40, 0, 0, 9, 43, 19, 22, 20, 10, 0, 0, 29, 0, 40, 0, 29, 0, 0, 0, 26, 67, 57, 2, 54, 0, 0, 0, 16, 90, 41, 36, 37, 42, 0, 0, 9, 104, 26, 69, 12, 97, 0, 0, -46, 127, -45, 127, -32, 127, 0, 0, -20, 104, -15, 101, -22, 117, 0, 0, 1, 67, -4, 76, -2, 74, 0, 0, -13, 78, -6, 71, -4, 85, 0, 0, -11, 65, -13, 79, -24, 102, 0, 0, 1, 62, 5, 52, 5, 57, 0, 0, -6, 86, 6, 69, -6, 93, 0, 0, -17, 95, -13, 90, -14, 88, 0, 0, -6, 61, 0, 52, -6, 44, 0, 0, 9, 45, 8, 43, 4, 55, 0, 0, -3, 69, -2, 69, -11, 89, 0, 0, -6, 81, -5, 82, -15, 103, 0, 0, -11, 96, -10, 96, -21, 116, 0, 0, 6, 55, 2, 59, 19, 57, 0, 0, 7, 67, 2, 75, 20, 58, 0, 0, -5, 86, -3, 87, 4, 84, 0, 0, 2, 88, -3, 100, 6, 96, 0, 0, 0, 58, 1, 56, 1, 63, 0, 0, -3, 76, -3, 74, -5, 85, 0, 0, -10, 94, -6, 85, -13, 106, 0, 0, 5, 54, 0, 59, 5, 63, 0, 0, 4, 69, -3, 81, 6, 75, 0, 0, -3, 81, -7, 86, -3, 90, 0, 0, 0, 88, -5, 95, -1, 101, 0, 0, -7, 67, -1, 66, 3, 55, 0, 0, -5, 74, -1, 77, -4, 79, 0, 0, -4, 74, 1, 70, -2, 75, 0, 0, -5, 80, -2, 86, -12, 97, 0, 0, -7, 72, -5, 72, -7, 50, 0, 0, 1, 58, 0, 61, 1, 60, 0, 41, 0, 41, 0, 41, 0, 41, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, -9, 83, -9, 83, -9, 83, -9, 83, 4, 86, 4, 86, 4, 86, 4, 86, 0, 97, 0, 97, 0, 97, 0, 97, -7, 72, -7, 72, -7, 72, -7, 72, 13, 41, 13, 41, 13, 41, 13, 41, 3, 62, 3, 62, 3, 62, 3, 62, 0, 11, 0, 45, 13, 15, 7, 34, 1, 55, -4, 78, 7, 51, -9, 88, 0, 69, -3, 96, 2, 80, -20, 127, -17, 127, -27, 126, -39, 127, -36, 127, -13, 102, -28, 98, -18, 91, -17, 91, 0, 82, -25, 101, -17, 96, -14, 95, -7, 74, -23, 67, -26, 81, -25, 84, -21, 107, -28, 82, -35, 98, -25, 86, -27, 127, -20, 94, -24, 102, -12, 89, -31, 127, -16, 83, -23, 97, -17, 91, -24, 127, -22, 110, -27, 119, -31, 127, -18, 95, -21, 91, -24, 99, -14, 76, -27, 127, -18, 102, -21, 110, -18, 103, -21, 114, -13, 93, -18, 102, -13, 90, -30, 127, -29, 127, -36, 127, -37, 127, -17, 123, -7, 92, 0, 80, 11, 80, -12, 115, -5, 89, -5, 89, 5, 76, -16, 122, -7, 96, -7, 94, 2, 84, -11, 115, -13, 108, -4, 92, 5, 78, -12, 63, -3, 46, 0, 39, -6, 55, -2, 68, -1, 65, 0, 65, 4, 61, -15, 84, -1, 57, -15, 84, -14, 83, -13, 104, -9, 93, -35, 127, -37, 127, -3, 70, -3, 74, -2, 73, -5, 79, -8, 93, -9, 92, -12, 104, -11, 104, -10, 90, -8, 87, -9, 91, -11, 91, -30, 127, -23, 126, -31, 127, -30, 127, -1, 74, 5, 54, 3, 55, 0, 65, -6, 97, 6, 60, 7, 56, -2, 79, -7, 91, 6, 59, 7, 55, 0, 72, -20, 127, 6, 69, 8, 61, -4, 92, -4, 56, -1, 48, -3, 53, -6, 56, -5, 82, 0, 68, 0, 68, 3, 68, -7, 76, -4, 69, -7, 74, -8, 71, -22, 125, -8, 88, -9, 88, -13, 98, -7, 93, -2, 85, -13, 103, -4, 86, -11, 87, -6, 78, -13, 91, -12, 88, -3, 77, -1, 75, -9, 89, -5, 82, -5, 71, -7, 77, -14, 92, -3, 72, -4, 63, 2, 54, -8, 76, -4, 67, -4, 68, 5, 50, -12, 87, -8, 72, -12, 84, -3, 68, -23, 110, -16, 89, -7, 62, 1, 50, -24, 105, -9, 69, -7, 65, 6, 42, -10, 78, -1, 59, 8, 61, -4, 81, -20, 112, 5, 66, 5, 56, 1, 63, -17, 99, 4, 57, -2, 66, -4, 70, -78, 127, -4, 71, 1, 64, 0, 67, -70, 127, -2, 71, 0, 61, 2, 57, -50, 127, 2, 58, -2, 78, -2, 76, -46, 127, -1, 74, 1, 50, 11, 35, -4, 66, -4, 44, 7, 52, 4, 64, -5, 78, -1, 69, 10, 35, 1, 61, -4, 71, 0, 62, 0, 44, 11, 35, -8, 72, -7, 51, 11, 38, 18, 25, 2, 59, -4, 47, 1, 45, 12, 24, -1, 55, -6, 42, 0, 46, 13, 29, -7, 70, -3, 41, 5, 44, 13, 36, -6, 75, -6, 53, 31, 17, -10, 93, -8, 89, 8, 76, 1, 51, -7, 73, -34, 119, -9, 78, 7, 50, -2, 73, -3, 75, -11, 83, 28, 19, 13, 46, 32, 20, 9, 52, 16, 33, 9, 49, 30, 22, 0, 67, 14, 62, -7, 100, -44, 127, -5, 90, -13, 108, 9, 53, 0, 54, 1, 67, -15, 100, 2, 53, -5, 61, -15, 72, -13, 101, 5, 53, 0, 58, -5, 75, -13, 91, -2, 61, -1, 60, -8, 80, -12, 94, 0, 56, -3, 61, -21, 83, -10, 88, 0, 56, -8, 67, -21, 64, -16, 84, -13, 63, -25, 84, -13, 31, -10, 86, -5, 60, -14, 74, -25, 64, -7, 83, -1, 62, -5, 65, -29, 94, -13, 87, 4, 57, 5, 52, 9, 75, -19, 94, -6, 69, 2, 57, 17, 63, 1, 70, 4, 57, 0, 61, -8, 74, 0, 72, 14, 39, -9, 69, -5, 35, -5, 74, 4, 51, -11, 70, -2, 27, 18, 59, 13, 68, 18, 55, 13, 91, -8, 102, 3, 64, -4, 71, 3, 65, -15, 100, 1, 61, 0, 58, -7, 69, 0, 95, 9, 63, 7, 61, 8, 77, -4, 75, 7, 50, 9, 41, -10, 66, 2, 72, 16, 39, 18, 25, 3, 62, -11, 75, 5, 44, 9, 32, -3, 68, -3, 71, 4, 52, 5, 43, -20, 81, 15, 46, 11, 48, 9, 47, 0, 30, -13, 69, -5, 60, 0, 44, 1, 7, 0, 62, -1, 59, 0, 51, -3, 23, 0, 65, 0, 59, 2, 46, -21, 74, 21, 37, 22, 33, 19, 38, 16, 66, -15, 72, 5, 44, -4, 66, -23, 124, 9, 57, 14, 43, 15, 38, 17, 37, 16, 54, -1, 78, 12, 42, 44, -18, 0, 62, 0, 60, 9, 34, 50, -34, 12, 72, 9, 69, 0, 89, -22, 127, 24, 0, 11, 28, 4, 45, 4, 39, 15, 9, 2, 40, 10, 28, 0, 42, 8, 25, 3, 44, 10, 31, 7, 34, 13, 18, 0, 49, 33, -11, 11, 29, 15, 9, 0, 46, 52, -43, 8, 31, 13, 19, 2, 44, 18, 15, 6, 37, 10, 37, 2, 51, 28, 0, 7, 42, 12, 18, 0, 47, 35, -22, 3, 40, 6, 29, 4, 39, 38, -25, 8, 33, 20, 33, 2, 62, 34, 0, 13, 43, 15, 30, 6, 46, 39, -18, 13, 36, 4, 45, 0, 54, 32, -12, 4, 47, 1, 58, 3, 54, 102, -94, 3, 55, 0, 62, 2, 58, 0, 0, 2, 58, 7, 61, 4, 63, 56, -15, 6, 60, 12, 38, 6, 51, 33, -4, 8, 44, 11, 45, 6, 57, 29, 10, 11, 44, 15, 39, 7, 53, 37, -5, 14, 42, 11, 42, 6, 52, 51, -29, 7, 48, 13, 44, 6, 55, 39, -9, 4, 56, 16, 45, 11, 45, 52, -34, 4, 52, 12, 41, 14, 36, 69, -58, 13, 37, 10, 49, 8, 53, 67, -63, 9, 49, 30, 34, -1, 82, 44, -5, 19, 58, 18, 42, 7, 55, 32, 7, 10, 48, 10, 55, -3, 78, 55, -29, 12, 45, 17, 51, 15, 46, 32, 1, 0, 69, 17, 46, 22, 31, 0, 0, 20, 33, 0, 89, -1, 84, 27, 36, 8, 63, 26, -19, 25, 7, 33, -25, 35, -18, 22, -17, 30, -7, 34, -30, 33, -25, 26, -17, 28, 3, 36, -28, 28, -3, 30, -25, 28, 4, 38, -28, 24, 10, 28, -20, 32, 0, 38, -27, 27, 0, 33, -23, 34, -1, 34, -18, 34, -14, 37, -27, 30, 6, 35, -16, 52, -44, 33, -23, 30, 6, 34, -14, 39, -24, 40, -28, 32, 9, 32, -8, 19, 17, 38, -17, 31, 19, 37, -6, 31, 25, 33, -11, 26, 27, 35, 0, 36, 29, 40, -15, 26, 30, 30, 10, 24, 33, 41, -6, 37, 20, 28, 18, 34, 15, 38, 1, 28, 34, 26, 25, 30, 20, 41, 17, 17, 70, 29, 41, 22, 73, 30, -6, 1, 67, 0, 75, 20, 34, 27, 3, 5, 59, 2, 72, 19, 31, 26, 22, 9, 67, 8, 77, 27, 44, 37, -16, 16, 30, 14, 35, 19, 16, 35, -4, 18, 32, 18, 31, 15, 36, 38, -8, 18, 35, 17, 35, 15, 36, 38, -3, 22, 29, 21, 30, 21, 28, 37, 3, 24, 31, 17, 45, 25, 21, 38, 5, 23, 38, 20, 42, 30, 20, 42, 0, 18, 43, 18, 45, 31, 12, 35, 16, 20, 41, 27, 26, 27, 16, 39, 22, 11, 63, 16, 54, 24, 42, 14, 48, 9, 59, 7, 66, 0, 93, 27, 37, 9, 64, 16, 56, 14, 56, 21, 60, -1, 94, 11, 73, 15, 57, 12, 68, -2, 89, 10, 67, 26, 38, 2, 97, -9, 108, -10, 116, -24, 127, -3, 71, -6, 76, -23, 112, -24, 115, -6, 42, -2, 44, -15, 71, -22, 82, -5, 50, 0, 45, -7, 61, -9, 62, -3, 54, 0, 52, 0, 53, 0, 53, -2, 62, -3, 64, -5, 66, 0, 59, 0, 58, -2, 59, -11, 77, -14, 85, 1, 63, -4, 70, -9, 80, -13, 89, -2, 72, -4, 75, -9, 84, -13, 94, -1, 74, -8, 82, -10, 87, -11, 92, -9, 91, -17, 102, -34, 127, -29, 127, -5, 67, -9, 77, -21, 101, -21, 100, -5, 27, 3, 24, -3, 39, -14, 57, -3, 39, 0, 42, -5, 53, -12, 67, -2, 44, 0, 48, -7, 61, -11, 71, 0, 46, 0, 55, -11, 75, -10, 77, -16, 64, -6, 59, -15, 77, -21, 85, -8, 68, -7, 71, -17, 91, -16, 88, -10, 78, -12, 83, -25, 107, -23, 104, -6, 77, -11, 87, -25, 111, -15, 98, -10, 86, -30, 119, -28, 122, -37, 127, -12, 92, 1, 58, -11, 76, -10, 82, -15, 55, -3, 29, -10, 44, -8, 48, -10, 60, -1, 36, -10, 52, -8, 61, -6, 62, 1, 38, -10, 57, -8, 66, -4, 65, 2, 43, -9, 58, -7, 70, -12, 73, -6, 55, -16, 72, -14, 75, -8, 76, 0, 58, -7, 69, -10, 79, -7, 80, 0, 64, -4, 69, -9, 83, -9, 88, -3, 74, -5, 74, -12, 92, -17, 110, -10, 90, -9, 86, -18, 108, -11, 97, 0, 70, 2, 66, -4, 79, -20, 84, -4, 29, -9, 34, -22, 69, -11, 79, 5, 31, 1, 32, -16, 75, -6, 73, 7, 42, 11, 31, -2, 58, -4, 74, 1, 59, 5, 52, 1, 58, -13, 86, -2, 58, -2, 55, -13, 78, -13, 96, -3, 72, -2, 67, -9, 83, -11, 97, -3, 81, 0, 73, -4, 81, -19, 117, -11, 97, -8, 89, -13, 99, -8, 78, 0, 58, 3, 52, -13, 81, -5, 33, 8, 5, 7, 4, -6, 38, -4, 48, 10, 14, 10, 8, -13, 62, -2, 53, 14, 18, 17, 8, -6, 58, -3, 62, 13, 27, 16, 19, -2, 59, -13, 71, 2, 40, 3, 37, -16, 73, -10, 79, 0, 58, -1, 61, -10, 76, -12, 86, -3, 70, -5, 73, -13, 86, -13, 90, -6, 79, -1, 70, -9, 83, -14, 97, -8, 85, -4, 78, -10, 87, 0, 0, 0, 0, 0, 0, 0, 0, -6, 93, -13, 106, -21, 126, -22, 127, -6, 84, -16, 106, -23, 124, -25, 127, -8, 79, -10, 87, -20, 110, -25, 120, 0, 66, -21, 114, -26, 126, -27, 127, -1, 71, -18, 110, -25, 124, -19, 114, 0, 62, -14, 98, -17, 105, -23, 117, -2, 60, -22, 110, -27, 121, -25, 118, -2, 59, -21, 106, -27, 117, -26, 117, -5, 75, -18, 103, -17, 102, -24, 113, -3, 62, -21, 107, -26, 117, -28, 118, -4, 58, -23, 108, -27, 116, -31, 120, -9, 66, -26, 112, -33, 122, -37, 124, -1, 79, -10, 96, -10, 95, -10, 94, 0, 71, -12, 95, -14, 100, -15, 102, 3, 68, -5, 91, -8, 95, -10, 99, 10, 44, -9, 93, -17, 111, -13, 106, -7, 62, -22, 94, -28, 114, -50, 127, 15, 36, -5, 86, -6, 89, -5, 92, 14, 40, 9, 67, -2, 80, 17, 57, 16, 27, -4, 80, -4, 82, -5, 86, 12, 29, -10, 85, -9, 85, -13, 94, 1, 44, -1, 70, -8, 81, -12, 91, 20, 36, 7, 60, -1, 72, -2, 77, 18, 32, 9, 58, 5, 64, 0, 71, 5, 42, 5, 61, 1, 67, -1, 73, 1, 48, 12, 50, 9, 56, 4, 64, 10, 62, 15, 50, 0, 69, -7, 81, 17, 46, 18, 49, 1, 69, 5, 64, 9, 64, 17, 54, 7, 69, 15, 57, -12, 104, 10, 41, -7, 69, 1, 67, -11, 97, 7, 46, -6, 67, 0, 68, -16, 96, -1, 51, -16, 77, -10, 67, -7, 88, 7, 49, -2, 64, 1, 68, -8, 85, 8, 52, 2, 61, 0, 77, -7, 85, 9, 41, -6, 67, 2, 64, -9, 85, 6, 47, -3, 64, 0, 68, -13, 88, 2, 55, 2, 57, -5, 78, 4, 66, 13, 41, -3, 65, 7, 55, -3, 77, 10, 44, -3, 66, 5, 59, -3, 76, 6, 50, 0, 62, 2, 65, -6, 76, 5, 53, 9, 51, 14, 54, 10, 58, 13, 49, -1, 66, 15, 44, -1, 76, 4, 63, -2, 71, 5, 60, -1, 83, 6, 64, -2, 75, 2, 70, -7, 99, -2, 69, -1, 70, -2, 76, -14, 95, -2, 59, -9, 72, -18, 86, 2, 95, 6, 70, 14, 60, 12, 70, 0, 76, 10, 44, 16, 37, 5, 64, -5, 74, 9, 31, 0, 47, -12, 70, 0, 70, 12, 43, 18, 35, 11, 55, -11, 75, 3, 53, 11, 37, 5, 56, 1, 68, 14, 34, 12, 41, 0, 69, 0, 65, 10, 38, 10, 41, 2, 65, -14, 73, -3, 52, 2, 48, -6, 74, 3, 62, 13, 40, 12, 41, 5, 54, 4, 62, 17, 32, 13, 41, 7, 54, -1, 68, 7, 44, 0, 59, -6, 76, -13, 75, 7, 38, 3, 50, -11, 82, 11, 55, 13, 50, 19, 40, -2, 77, 5, 64, 10, 57, 3, 66, -2, 77, 12, 70, 26, 43, 18, 50, 25, 42, 15, 6, 14, 11, 19, -6, 17, -13, 6, 19, 11, 14, 18, -6, 16, -9, 7, 16, 9, 11, 14, 0, 17, -12, 12, 14, 18, 11, 26, -12, 27, -21, 18, 13, 21, 9, 31, -16, 37, -30, 13, 11, 23, -2, 33, -25, 41, -40, 13, 15, 32, -15, 33, -22, 42, -41, 15, 16, 32, -15, 37, -28, 48, -47, 12, 23, 34, -21, 39, -30, 39, -32, 13, 23, 39, -23, 42, -30, 46, -40, 15, 20, 42, -33, 47, -42, 52, -51, 14, 26, 41, -31, 45, -36, 46, -41, 14, 44, 46, -28, 49, -34, 52, -39, 17, 40, 38, -12, 41, -17, 43, -19, 17, 47, 21, 29, 32, 9, 32, 11, 24, 17, 45, -24, 69, -71, 61, -55, 21, 21, 53, -45, 63, -63, 56, -46, 25, 22, 48, -26, 66, -64, 62, -50, 31, 27, 65, -43, 77, -74, 81, -67, 22, 29, 43, -19, 54, -39, 45, -20, 19, 35, 39, -10, 52, -35, 35, -2, 14, 50, 30, 9, 41, -10, 28, 15, 10, 57, 18, 26, 36, 0, 34, 1, 7, 63, 20, 27, 40, -1, 39, 1, -2, 77, 0, 57, 30, 14, 30, 17, -4, 82, -14, 82, 28, 26, 20, 38, -3, 94, -5, 75, 23, 37, 18, 45, 9, 69, -19, 97, 12, 55, 15, 54, -12, 109, -35, 125, 11, 65, 0, 79, 36, -35, 27, 0, 37, -33, 36, -16, 36, -34, 28, 0, 39, -36, 37, -14, 32, -26, 31, -4, 40, -37, 37, -17, 37, -30, 27, 6, 38, -30, 32, 1, 44, -32, 34, 8, 46, -33, 34, 15, 34, -18, 30, 10, 42, -30, 29, 15, 34, -15, 24, 22, 40, -24, 24, 25, 40, -15, 33, 19, 49, -29, 34, 22, 33, -7, 22, 32, 38, -12, 31, 16, 35, -5, 26, 31, 40, -10, 35, 18, 33, 0, 21, 41, 38, -3, 31, 28, 38, 2, 26, 44, 46, -5, 33, 41, 33, 13, 23, 47, 31, 20, 36, 28, 23, 35, 16, 65, 29, 30, 27, 47, 13, 58, 14, 71, 25, 44, 21, 62, 29, -3, 8, 60, 12, 48, 18, 31, 26, 0, 6, 63, 11, 49, 19, 26, 22, 30, 17, 65, 26, 45, 36, 24, 31, -7, 21, 24, 22, 22, 24, 23, 35, -15, 23, 20, 23, 22, 27, 16, 34, -3, 26, 23, 27, 21, 24, 30, 34, 3, 27, 32, 33, 20, 31, 29, 36, -1, 28, 23, 26, 28, 22, 41, 34, 5, 28, 24, 30, 24, 22, 42, 32, 11, 23, 40, 27, 34, 16, 60, 35, 5, 24, 32, 18, 42, 15, 52, 34, 12, 28, 29, 25, 39, 14, 60, 39, 11, 23, 42, 18, 50, 3, 78, 30, 29, 19, 57, 12, 70, -16, 123, 34, 26, 22, 53, 21, 54, 21, 53, 29, 39, 22, 61, 14, 71, 22, 56, 19, 66, 11, 86, 11, 83, 25, 61, 31, 21, 12, 40, 25, 32, 21, 33, 31, 31, 11, 51, 21, 49, 19, 50, 25, 50, 14, 59, 21, 54, 17, 61, -17, 120, -4, 79, -5, 85, -3, 78, -20, 112, -7, 71, -6, 81, -8, 74, -18, 114, -5, 69, -10, 77, -9, 72, -11, 85, -9, 70, -7, 81, -10, 72, -15, 92, -8, 66, -17, 80, -18, 75, -14, 89, -10, 68, -18, 73, -12, 71, -26, 71, -19, 73, -4, 74, -11, 63, -15, 81, -12, 69, -10, 83, -5, 70, -14, 80, -16, 70, -9, 71, -17, 75, 0, 68, -15, 67, -9, 67, -14, 72, -14, 70, -20, 62, -1, 61, -16, 67, -24, 56, -19, 70, -8, 66, -8, 53, -23, 68, -16, 66, -14, 66, -14, 59, -24, 50, -22, 65, 0, 59, -9, 52, -11, 74, -20, 63, 2, 59, -11, 68, 23, -13, 9, -2, 17, -10, 9, -2, 26, -13, 26, -9, 32, -13, 30, -10, 40, -15, 33, -9, 42, -9, 31, -4, 49, -14, 39, -7, 49, -5, 33, -1, 44, 3, 41, -2, 53, 0, 33, 7, 45, 6, 45, 3, 64, 3, 31, 12, 44, 34, 49, 9, 68, 10, 37, 23, 33, 54, 45, 27, 66, 27, 31, 38, 19, 82, 36, 59, 47, 57, 20, 64, -3, 75, -6, 66, -5, 71, -9, 71, -1, 23, -7, 35, 0, 24, -7, 37, 1, 34, -7, 42, -1, 36, -8, 44, 1, 43, -8, 45, -2, 42, -11, 49, 0, 54, -5, 48, -2, 52, -10, 56, -2, 55, -12, 56, -9, 57, -12, 59, 0, 61, -6, 60, -6, 63, -8, 63, 1, 64, -5, 62, -4, 65, -9, 67, 0, 68, -8, 66, -4, 67, -6, 68, -9, 92, -8, 76, -7, 82, -10, 79, -14, 106, -5, 85, -3, 81, -3, 78, -13, 97, -6, 81, -3, 76, -8, 74, -15, 90, -10, 77, -7, 72, -9, 72, -12, 90, -7, 81, -6, 78, -10, 72, -18, 88, -17, 80, -12, 72, -18, 75, -10, 73, -18, 73, -14, 68, -12, 71, -9, 79, -4, 74, -3, 70, -11, 63, -14, 86, -10, 83, -6, 76, -5, 70, -10, 73, -9, 71, -5, 66, -17, 75, -10, 70, -9, 67, -5, 62, -14, 72, -10, 69, -1, 61, 0, 57, -16, 67, -5, 66, -8, 66, -4, 61, -8, 53, -9, 64, -14, 66, -9, 60, -14, 59, -5, 58, 0, 59, 1, 54, -9, 52, 2, 59, 2, 59, 2, 58, -11, 68, 21, -10, 21, -13, 17, -10, 9, -2, 24, -11, 33, -14, 32, -13, 30, -10, 28, -8, 39, -7, 42, -9, 31, -4, 28, -1, 46, -2, 49, -5, 33, -1, 29, 3, 51, 2, 53, 0, 33, 7, 29, 9, 60, 6, 64, 3, 31, 12, 35, 20, 61, 17, 68, 10, 37, 23, 29, 36, 55, 34, 66, 27, 31, 38, 14, 67, 42, 62, 47, 57, 20, 64 } +T.RANGE_LPS = { 128, 176, 208, 240, 128, 167, 197, 227, 128, 158, 187, 216, 123, 150, 178, 205, 116, 142, 169, 195, 111, 135, 160, 185, 105, 128, 152, 175, 100, 122, 144, 166, 95, 116, 137, 158, 90, 110, 130, 150, 85, 104, 123, 142, 81, 99, 117, 135, 77, 94, 111, 128, 73, 89, 105, 122, 69, 85, 100, 116, 66, 80, 95, 110, 62, 76, 90, 104, 59, 72, 86, 99, 56, 69, 81, 94, 53, 65, 77, 89, 51, 62, 73, 85, 48, 59, 69, 80, 46, 56, 66, 76, 43, 53, 63, 72, 41, 50, 59, 69, 39, 48, 56, 65, 37, 45, 54, 62, 35, 43, 51, 59, 33, 41, 48, 56, 32, 39, 46, 53, 30, 37, 43, 50, 29, 35, 41, 48, 27, 33, 39, 45, 26, 31, 37, 43, 24, 30, 35, 41, 23, 28, 33, 39, 22, 27, 32, 37, 21, 26, 30, 35, 20, 24, 29, 33, 19, 23, 27, 31, 18, 22, 26, 30, 17, 21, 25, 28, 16, 20, 23, 27, 15, 19, 22, 25, 14, 18, 21, 24, 14, 17, 20, 23, 13, 16, 19, 22, 12, 15, 18, 21, 12, 14, 17, 20, 11, 14, 16, 19, 11, 13, 15, 18, 10, 12, 15, 17, 10, 12, 14, 16, 9, 11, 13, 15, 9, 11, 12, 14, 8, 10, 12, 14, 8, 9, 11, 13, 7, 9, 11, 12, 7, 9, 10, 12, 7, 8, 10, 11, 6, 8, 9, 11, 6, 7, 9, 10, 6, 7, 8, 9, 2, 2, 2, 2 } +T.TRANS = { 0, 1, 0, 2, 1, 3, 2, 4, 2, 5, 4, 6, 4, 7, 5, 8, 6, 9, 7, 10, 8, 11, 9, 12, 9, 13, 11, 14, 11, 15, 12, 16, 13, 17, 13, 18, 15, 19, 15, 20, 16, 21, 16, 22, 18, 23, 18, 24, 19, 25, 19, 26, 21, 27, 21, 28, 22, 29, 22, 30, 23, 31, 24, 32, 24, 33, 25, 34, 26, 35, 26, 36, 27, 37, 27, 38, 28, 39, 29, 40, 29, 41, 30, 42, 30, 43, 30, 44, 31, 45, 32, 46, 32, 47, 33, 48, 33, 49, 33, 50, 34, 51, 34, 52, 35, 53, 35, 54, 35, 55, 36, 56, 36, 57, 36, 58, 37, 59, 37, 60, 37, 61, 38, 62, 38, 62, 63, 63 } +T.CHROMA_QP = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 29, 30, 31, 32, 32, 33, 34, 34, 35, 35, 36, 36, 37, 37, 37, 38, 38, 38, 39, 39, 39, 39 } +T.INTRA_CBP = { 47, 31, 15, 0, 23, 27, 29, 30, 7, 11, 13, 14, 39, 43, 45, 46, 16, 3, 5, 10, 12, 19, 21, 26, 28, 35, 37, 42, 44, 1, 2, 4, 8, 17, 18, 20, 24, 6, 9, 22, 25, 32, 33, 34, 36, 40, 38, 41 } +T.INTER_CBP = { 0, 16, 1, 2, 4, 8, 32, 3, 5, 10, 12, 15, 47, 7, 11, 13, 14, 6, 9, 31, 35, 37, 42, 44, 33, 34, 36, 40, 39, 43, 45, 46, 17, 18, 20, 24, 19, 21, 26, 28, 23, 27, 29, 30, 22, 25, 38, 41 } +T.DEFAULT_4x4 = { 6, 13, 20, 28, 13, 20, 28, 32, 20, 28, 32, 37, 28, 32, 37, 42, 10, 14, 20, 24, 14, 20, 24, 27, 20, 24, 27, 30, 24, 27, 30, 34 } +T.DEFAULT_8x8 = { 6, 10, 13, 16, 18, 23, 25, 27, 10, 11, 16, 18, 23, 25, 27, 29, 13, 16, 18, 23, 25, 27, 29, 31, 16, 18, 23, 25, 27, 29, 31, 33, 18, 23, 25, 27, 29, 31, 33, 36, 23, 25, 27, 29, 31, 33, 36, 38, 25, 27, 29, 31, 33, 36, 38, 40, 27, 29, 31, 33, 36, 38, 40, 42, 9, 13, 15, 17, 19, 21, 22, 24, 13, 13, 17, 19, 21, 22, 24, 25, 15, 17, 19, 21, 22, 24, 25, 27, 17, 19, 21, 22, 24, 25, 27, 28, 19, 21, 22, 24, 25, 27, 28, 30, 21, 22, 24, 25, 27, 28, 30, 32, 22, 24, 25, 27, 28, 30, 32, 33, 24, 25, 27, 28, 30, 32, 33, 35 } +T.ZIGZAG4 = { 0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15 } +T.ZIGZAG8 = { 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63 } +T.SIG8 = { 0, 1, 2, 3, 4, 5, 5, 4, 4, 3, 3, 4, 4, 4, 5, 5, 4, 4, 4, 4, 3, 3, 6, 7, 7, 7, 8, 9, 10, 9, 8, 7, 7, 6, 11, 12, 13, 11, 6, 7, 8, 9, 14, 10, 9, 8, 6, 11, 12, 13, 11, 6, 9, 14, 10, 9, 11, 12, 13, 11, 14, 10, 12, 14 } +T.LAST8 = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8 } +T.ALPHA = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 5, 6, 7, 8, 9, 10, 12, 13, 15, 17, 20, 22, 25, 28, 32, 36, 40, 45, 50, 56, 63, 71, 80, 90, 101, 113, 127, 144, 162, 182, 203, 226, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 } +T.BETA = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18 } +T.TC0 = { -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 1, -1, 0, 0, 1, -1, 0, 0, 1, -1, 0, 0, 1, -1, 0, 1, 1, -1, 0, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 2, -1, 1, 1, 2, -1, 1, 1, 2, -1, 1, 1, 2, -1, 1, 2, 3, -1, 1, 2, 3, -1, 2, 2, 3, -1, 2, 2, 4, -1, 2, 3, 4, -1, 2, 3, 4, -1, 3, 3, 5, -1, 3, 4, 6, -1, 3, 4, 6, -1, 4, 5, 7, -1, 4, 5, 8, -1, 4, 6, 9, -1, 5, 7, 10, -1, 6, 8, 11, -1, 6, 8, 13, -1, 7, 10, 14, -1, 8, 11, 16, -1, 9, 12, 18, -1, 10, 13, 20, -1, 11, 15, 23, -1, 13, 17, 25, -1, 13, 17, 25, -1, 13, 17, 25, -1, 13, 17, 25, -1, 13, 17, 25, -1, 13, 17, 25, -1, 13, 17, 25, -1, 13, 17, 25, -1, 13, 17, 25, -1, 13, 17, 25, -1, 13, 17, 25, -1, 13, 17, 25, -1, 13, 17, 25 } + +return T diff --git a/src/Formats/codecs/H264/Transform.luau b/src/Formats/codecs/H264/Transform.luau new file mode 100644 index 0000000..e685d34 --- /dev/null +++ b/src/Formats/codecs/H264/Transform.luau @@ -0,0 +1,178 @@ +--!strict +--!native +--!optimize 2 +-- codecs/H264/Transform: the inverse transforms of ITU-T H.264 8.5: the 4x4 and 8x8 integer IDCTs with the residual +-- added to the prediction in the plane (8.5.12.2 / 8.5.13.2 / 8.5.14), the 4x4 luma DC and 2x2 chroma DC Hadamard +-- transforms with their scaling (8.5.10 / 8.5.11.2). Written from the spec. Coefficients are dequantised already +-- (Params.dequant), raster order, in a 1-based table at `base + 1 ...`; the functions zero what they read. +-- Never throws. +local readu8, writeu8 = buffer.readu8, buffer.writeu8 + +local Transform = {} + +local function clip(v: number): number + if v < 0 then + return 0 + elseif v > 255 then + return 255 + end + return v +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) +function Transform.add4(c: { number }, base: number, b: buffer, o: number, s: number) + -- rows + for i = 0, 3 do + local k = base + i * 4 + local d0, d1, d2, d3 = c[k + 1], c[k + 2], c[k + 3], c[k + 4] + local e = d0 + d2 + local f = d0 - d2 + local g = d1 // 2 - d3 + local h = d1 + d3 // 2 + c[k + 1] = e + h + c[k + 2] = f + g + c[k + 3] = f - g + c[k + 4] = e - h + end + -- columns + for j = 0, 3 do + local k = base + j + local d0, d1, d2, d3 = c[k + 1], c[k + 5], c[k + 9], c[k + 13] + local e = d0 + d2 + local f = d0 - d2 + local g = d1 // 2 - d3 + local h = d1 + d3 // 2 + c[k + 1], c[k + 5], c[k + 9], c[k + 13] = 0, 0, 0, 0 + local p = o + j + writeu8(b, p, clip(readu8(b, p) + (e + h + 32) // 64)) + p += s + writeu8(b, p, clip(readu8(b, p) + (f + g + 32) // 64)) + p += s + writeu8(b, p, clip(readu8(b, p) + (f - g + 32) // 64)) + p += s + writeu8(b, p, clip(readu8(b, p) + (e - h + 32) // 64)) + end +end + +-- addDc4(dc, b, o, s): a 4x4 block whose only coefficient is the (dequantised) DC +function Transform.addDc4(dc: number, b: buffer, o: number, s: number) + local v = (dc + 32) // 64 + if v == 0 then + return + end + for y = 0, 3 do + local p = o + y * s + writeu8(b, p, clip(readu8(b, p) + v)) + writeu8(b, p + 1, clip(readu8(b, p + 1) + v)) + writeu8(b, p + 2, clip(readu8(b, p + 2) + v)) + writeu8(b, p + 3, clip(readu8(b, p + 3) + v)) + end +end + +local T8 = table.create(64, 0) + +-- add8(c, base, b, o, s): inverse 8x8 transform of c[base + 1 .. base + 64] added to the 8x8 block at b[o] +function Transform.add8(c: { number }, base: number, b: buffer, o: number, s: number) + for pass = 0, 1 do + for i = 0, 7 do + -- pass 0: rows of c into T8; pass 1: columns of T8 + local d0, d1, d2, d3, d4, d5, d6, d7 + if pass == 0 then + local k = base + i * 8 + d0, d1, d2, d3, d4, d5, d6, d7 = c[k + 1], c[k + 2], c[k + 3], c[k + 4], c[k + 5], c[k + 6], c[k + 7], c[k + 8] + c[k + 1], c[k + 2], c[k + 3], c[k + 4], c[k + 5], c[k + 6], c[k + 7], c[k + 8] = 0, 0, 0, 0, 0, 0, 0, 0 + else + d0, d1, d2, d3, d4, d5, d6, d7 = T8[i + 1], T8[i + 9], T8[i + 17], T8[i + 25], T8[i + 33], T8[i + 41], T8[i + 49], T8[i + 57] + end + local a0 = d0 + d4 + local a4 = d0 - d4 + local a2 = d2 // 2 - d6 + local a6 = d2 + d6 // 2 + local b0 = a0 + a6 + local b2 = a4 + a2 + local b4 = a4 - a2 + local b6 = a0 - a6 + local a1 = -d3 + d5 - d7 - d7 // 2 + local a3 = d1 + d7 - d3 - d3 // 2 + local a5 = -d1 + d7 + d5 + d5 // 2 + local a7 = d3 + d5 + d1 + d1 // 2 + local b1 = a1 + a7 // 4 + local b7 = a7 - a1 // 4 + local b3 = a3 + a5 // 4 + local b5 = a3 // 4 - a5 + if pass == 0 then + local k = i * 8 + T8[k + 1] = b0 + b7 + T8[k + 2] = b2 + b5 + T8[k + 3] = b4 + b3 + T8[k + 4] = b6 + b1 + T8[k + 5] = b6 - b1 + T8[k + 6] = b4 - b3 + T8[k + 7] = b2 - b5 + T8[k + 8] = b0 - b7 + else + local p = o + i + writeu8(b, p, clip(readu8(b, p) + (b0 + b7 + 32) // 64)) + p += s + writeu8(b, p, clip(readu8(b, p) + (b2 + b5 + 32) // 64)) + p += s + writeu8(b, p, clip(readu8(b, p) + (b4 + b3 + 32) // 64)) + p += s + writeu8(b, p, clip(readu8(b, p) + (b6 + b1 + 32) // 64)) + p += s + writeu8(b, p, clip(readu8(b, p) + (b6 - b1 + 32) // 64)) + p += s + writeu8(b, p, clip(readu8(b, p) + (b4 - b3 + 32) // 64)) + p += s + writeu8(b, p, clip(readu8(b, p) + (b2 - b5 + 32) // 64)) + p += s + writeu8(b, p, clip(readu8(b, p) + (b0 - b7 + 32) // 64)) + end + end + end +end + +-- lumaDc(dc, m, c): the Intra_16x16 DC levels dc[1..16] (raster 4x4 matrix) -> inverse Hadamard, scaled with the +-- DC multiplier m (LevelScale4x4(qP % 6, 0, 0) * 2^(qP / 6)), stored at c[blk * 16 + 1] (blk = raster block index) +function Transform.lumaDc(dc: { number }, m: number, c: { number }) + for i = 0, 3 do + local k = i * 4 + local d0, d1, d2, d3 = dc[k + 1], dc[k + 2], dc[k + 3], dc[k + 4] + local e = d0 + d1 + local f = d0 - d1 + local g = d2 + d3 + local h = d2 - d3 + dc[k + 1] = e + g + dc[k + 2] = e - g + dc[k + 3] = f - h + dc[k + 4] = f + h + end + for j = 0, 3 do + local d0, d1, d2, d3 = dc[j + 1], dc[j + 5], dc[j + 9], dc[j + 13] + local e = d0 + d1 + local f = d0 - d1 + local g = d2 + d3 + local h = d2 - d3 + dc[j + 1], dc[j + 5], dc[j + 9], dc[j + 13] = 0, 0, 0, 0 + c[j * 16 + 1] = ((e + g) * m + 32) // 64 + c[(4 + j) * 16 + 1] = ((e - g) * m + 32) // 64 + c[(8 + j) * 16 + 1] = ((f - h) * m + 32) // 64 + c[(12 + j) * 16 + 1] = ((f + h) * m + 32) // 64 + end +end + +-- chromaDc(dc, base, m, c, cbase): the 2x2 chroma DC levels dc[base + 1 .. base + 4] -> c[cbase + blk * 16 + 1] +function Transform.chromaDc(dc: { number }, base: number, m: number, c: { number }, cbase: number) + local c0, c1, c2, c3 = dc[base + 1], dc[base + 2], dc[base + 3], dc[base + 4] + dc[base + 1], dc[base + 2], dc[base + 3], dc[base + 4] = 0, 0, 0, 0 + local e = c0 + c1 + local f = c0 - c1 + local g = c2 + c3 + local h = c2 - c3 + c[cbase + 1] = ((e + g) * m) // 32 + c[cbase + 17] = ((f + h) * m) // 32 + c[cbase + 33] = ((e - g) * m) // 32 + c[cbase + 49] = ((f - h) * m) // 32 +end + +return Transform diff --git a/src/Formats/codecs/H264/init.luau b/src/Formats/codecs/H264/init.luau new file mode 100644 index 0000000..f3f5a04 --- /dev/null +++ b/src/Formats/codecs/H264/init.luau @@ -0,0 +1,205 @@ +--!strict +-- codecs/H264: an H.264 / AVC (ITU-T H.264 | ISO/IEC 14496-10) video decoder in pure Luau. A codec (layer 1): the +-- video/h264 format (raw Annex B streams) and the MP4 / MKV / AVI / TS video tracks use it. Clean-room, written from the +-- spec; constant tables taken from openh264 (BSD-2-Clause, licenses/openh264-LICENSE.txt). Bit-exact with the +-- reference decoder (checked against ffmpeg per frame). +-- Supports: Annex B and AVCC (length-prefixed, with avcC extradata) input; SPS / PPS / slices; CAVLC and CABAC; I, P and +-- B slices; every intra mode (4x4, 8x8, 16x16, chroma), quarter-sample luma / eighth-sample chroma motion +-- compensation, explicit and implicit weighted prediction, direct spatial and temporal prediction; the 4x4 and 8x8 +-- transforms with scaling matrices; the deblocking filter; multiple reference frames, long-term references, MMCO and +-- the sliding window, frame_num gaps; POC types 0 / 1 / 2 and output reordering; 8-bit 4:2:0 Constrained Baseline, +-- Main, Extended-without-SP/data-partitioning and High profiles; cropping. Corrupt slices are skipped and their +-- macroblocks concealed (copied from the latest reference picture). +-- Not supported (UNSUPPORTED): interlaced coding (field pictures, MBAFF), 4:0:0 / 4:2:2 / 4:4:4, bit depths above 8, +-- lossless (transform bypass), FMO / ASO slice groups, SP / SI slices, data partitioning, SVC / MVC enhancement layers +-- (their NAL units are ignored). +-- +-- local H264 = require("@formats/codecs/H264") +-- local dec = H264.newDecoder() -- or { avcC = buffer } for MP4 samples (length-prefixed) +-- for _, au in accessUnits do +-- local frames, err = dec:decode(au, pts) -- frames: { { image (yuv420p Types.Image), pts, poc, keyframe } } +-- end +-- local rest = dec:flush() -- the frames still held for reordering +-- +-- Never throws: bad data returns nil, Err (core/Err codes ARG / UNSUPPORTED / LIMIT), or frames with the bad slices +-- concealed (dec.errors counts them, dec.lastError says why). +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Bitstream = require("@formats/codecs/H264/Bitstream") +local Decoder = require("@formats/codecs/H264/Decoder") + +local H264 = {} + +export type Options = { + avcC: buffer?, -- AVCDecoderConfigurationRecord (MP4 'avcC', Matroska CodecPrivate): samples are length-prefixed + lengthSize: number?, -- NAL length field size for length-prefixed input without avcC (1, 2 or 4) + maxPixels: number?, -- largest picture (default 2^22 luma samples) + lowDelay: boolean?, -- output in decoding order, no reordering delay (streams without B frames / reordering) + deblock: boolean?, -- false skips the deblocking filter (faster, not conformant); default true +} + +export type Frame = { + image: Types.Image, -- yuv420p, cropped to the display size; image.meta.source = { format = "h264", poc, ... } + pts: number, -- the pts passed with the access unit holding the picture (default: its decoding index) + duration: number, + poc: number, + keyframe: boolean, +} + +local DecoderMeta = {} +DecoderMeta.__index = DecoderMeta + +export type H264Decoder = typeof(setmetatable({} :: { state: any, lengthSize: number?, errors: number, lastError: string? }, DecoderMeta)) + +local function toBuffer(data: any): buffer? + if type(data) == "buffer" then + return data + elseif type(data) == "string" then + return buffer.fromstring(data) + end + return nil +end + +local function status(self: H264Decoder): Err.Err? + local st = self.state + self.errors = st.errors + self.lastError = st.lastError + if st.fatal then + local m = st.fatal + if string.sub(m, 1, 7) == "limit: " then + return Err.new(Err.LIMIT, string.sub(m, 8)) + end + return Err.new(Err.CORRUPT, m) + end + if st.unsupported then + return Err.new(Err.UNSUPPORTED, st.unsupported) + end + return nil +end + +-- newDecoder(opts?) -> H264Decoder | nil, Err +function H264.newDecoder(opts: Options?): (H264Decoder?, Err.Err?) + local o = opts or {} + if type(o) ~= "table" then + return nil, Err.new(Err.ARG, "newDecoder: options must be a table") + end + local st = Decoder.new(o :: any) + local self = setmetatable({ state = st, lengthSize = o.lengthSize, errors = 0, lastError = nil :: string? }, DecoderMeta) + if o.avcC then + local ok, err = self:configure(o.avcC) + if not ok then + return nil, err + end + end + return self, nil +end + +-- decoder:configure(avcC) -> true | nil, Err: reads an AVCDecoderConfigurationRecord (its SPS / PPS) and switches to +-- length-prefixed input +function DecoderMeta.configure(self: H264Decoder, avcC: any): (boolean?, Err.Err?) + local b = toBuffer(avcC) + if not b then + return nil, Err.new(Err.ARG, "configure: expected a buffer or string") + end + local cfg, err = Bitstream.parseAvcC(b, 0, buffer.len(b)) + if not cfg then + local m = err or "bad avcC" + if string.sub(m, 1, 11) == "truncated: " then + return nil, Err.new(Err.TRUNCATED, string.sub(m, 12)) + end + return nil, Err.new(Err.CORRUPT, m) + end + self.lengthSize = cfg.lengthSize + local nals = cfg.nals + for i = 1, #nals, 2 do + Decoder.nal(self.state, b, nals[i], nals[i + 1], nil) + end + local e = status(self) + if e and e.code ~= Err.CORRUPT then + return nil, e + end + return true, nil +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. +function DecoderMeta.decode(self: H264Decoder, data: any, pts: number?, off: number?, len: number?): ({ Frame }?, Err.Err?) + local b = toBuffer(data) + if not b then + return nil, Err.new(Err.ARG, "decode: expected a buffer or string") + end + local n = buffer.len(b) + local o = math.clamp(off or 0, 0, n) + 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 + 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 + else + nals = { o, l } + end + for i = 1, #nals, 2 do + Decoder.nal(st, b, nals[i], nals[i + 1], pts) + if st.fatal or st.unsupported then + break + end + end + local frames = Decoder.take(st) + local e = status(self) + if e then + return nil, e + end + return frames, nil +end + +-- decoder:flush() -> { Frame }: ends the stream (the current picture and every picture held for reordering) +function DecoderMeta.flush(self: H264Decoder): { Frame } + Decoder.flush(self.state) + status(self) + return Decoder.take(self.state) +end + +-- decodeAll(data, opts?) -> { Frame } | nil, Err: a whole Annex B (or length-prefixed with opts.avcC) stream +function H264.decodeAll(data: any, opts: Options?): ({ Frame }?, Err.Err?) + local dec, err = H264.newDecoder(opts) + if not dec then + return nil, err + end + local frames, e = dec:decode(data) + if not frames then + return nil, e + end + for _, f in dec:flush() do + table.insert(frames, f) + end + return frames, nil +end + +-- parseAvcC(buf) -> { lengthSize, profile, level, nals } | nil, Err +function H264.parseAvcC(data: any): (any, Err.Err?) + local b = toBuffer(data) + if not b then + return nil, Err.new(Err.ARG, "parseAvcC: expected a buffer or string") + end + local cfg, err = Bitstream.parseAvcC(b, 0, buffer.len(b)) + if not cfg then + return nil, Err.new(Err.CORRUPT, err or "bad avcC") + end + return cfg, nil +end + +-- planes(img) -> y, u, v offsets in img.pixels and the chroma width / height +function H264.planes(img: Types.Image): (number, number, number, number, number) + local cw, ch = (img.width + 1) // 2, (img.height + 1) // 2 + local ny = img.width * img.height + return 0, ny, ny + cw * ch, cw, ch +end + +return H264 diff --git a/tools/fixtures/h264.py b/tools/fixtures/h264.py new file mode 100644 index 0000000..330ef46 --- /dev/null +++ b/tools/fixtures/h264.py @@ -0,0 +1,167 @@ +# H.264 fixtures (tools/fixtures.py). Reference tools: ffmpeg's libx264 encodes synthetic clips (testsrc2 / mandelbrot / +# noise) at many settings (profiles, CAVLC / CABAC, B frames, references, weighted prediction, 8x8 transforms, slices, +# scaling matrices, odd sizes with cropping, ...); ffmpeg's own H.264 decoder (-f rawvideo -pix_fmt yuv420p) gives the +# reference frames, compared per frame by CRC-32 of the cropped yuv420p planes. +# tests/gen/h264_cases.luau { name, data (Annex B), width, height, frames = { crc ... }, avcc?, samples? } +# tests/gen/h264_bad.luau streams expected to fail: { name, data, code } +# tests/gen/h264_bench.luau bigger streams for tools/bench.luau: { name, data, width, height, frames } +import os, subprocess, tempfile, zlib + +INPUTS = [] + +SRC = { + "testsrc2": "testsrc2=s={w}x{h}:r=25", + "noise": "testsrc2=s={w}x{h}:r=25,noise=alls=24:allf=t+u", + "mandel": "mandelbrot=s={w}x{h}:r=25", + "fade": "testsrc2=s={w}x{h}:r=25,fade=in:0:8,hue=H=t*2", +} + +# name, source, w, h, frames, x264 params, extra ffmpeg args +CASES = [ + ("cavlc_intra", "testsrc2", 176, 144, 3, "keyint=1:cabac=0:8x8dct=0:bframes=0:ref=1", []), + ("cavlc_intra_noise", "noise", 176, 144, 2, "keyint=1:cabac=0:8x8dct=0:bframes=0:qp=12", []), + ("cavlc_p", "testsrc2", 176, 144, 12, "cabac=0:8x8dct=0:bframes=0:ref=1:weightp=0", []), + ("cavlc_p_refs4", "noise", 176, 144, 12, "cabac=0:8x8dct=0:bframes=0:ref=4:weightp=0:mixed-refs=1", []), + ("cavlc_p_weightp", "fade", 176, 144, 12, "cabac=0:8x8dct=0:bframes=0:ref=3:weightp=2", []), + ("cavlc_slices", "testsrc2", 176, 144, 6, "cabac=0:8x8dct=0:bframes=0:slices=4", []), + ("cavlc_high_8x8", "noise", 176, 144, 8, "cabac=0:8x8dct=1:bframes=0:ref=2", []), + ("cavlc_b3", "testsrc2", 176, 144, 14, "cabac=0:8x8dct=0:bframes=3:b-pyramid=normal:ref=3", []), + ("cavlc_b_temporal", "noise", 176, 144, 10, "cabac=0:bframes=2:direct=temporal:ref=2:b-pyramid=none", []), + ("cavlc_constrained", "noise", 176, 144, 8, "cabac=0:bframes=0:constrained-intra=1:ref=2", []), + ("cabac_intra", "testsrc2", 176, 144, 3, "keyint=1:cabac=1:8x8dct=0:bframes=0", []), + ("cabac_intra_8x8", "noise", 176, 144, 2, "keyint=1:cabac=1:8x8dct=1:bframes=0:qp=10", []), + ("cabac_p", "testsrc2", 176, 144, 12, "cabac=1:8x8dct=0:bframes=0:ref=1:weightp=0", []), + ("cabac_p_refs4", "noise", 176, 144, 12, "cabac=1:bframes=0:ref=4:weightp=1", []), + ("cabac_weightp", "fade", 176, 144, 12, "cabac=1:bframes=0:ref=3:weightp=2", []), + ("cabac_b3", "testsrc2", 176, 144, 16, "cabac=1:bframes=3:b-pyramid=normal:ref=4:weightb=1", []), + ("cabac_b3_noise", "noise", 176, 144, 12, "cabac=1:bframes=3:b-pyramid=strict:ref=3:direct=spatial", []), + ("cabac_b_temporal", "noise", 176, 144, 10, "cabac=1:bframes=2:direct=temporal:ref=3:weightb=0", []), + ("cabac_b_weightb", "fade", 176, 144, 12, "cabac=1:bframes=3:weightb=1:weightp=2:ref=3", []), + ("cabac_slices", "noise", 176, 144, 8, "cabac=1:bframes=2:slices=3:ref=2", []), + ("high_cqm", "noise", 176, 144, 8, "cabac=1:8x8dct=1:bframes=2:cqm=jvt:ref=2", []), + ("high_lowqp", "noise", 176, 144, 4, "cabac=1:8x8dct=1:bframes=1:qp=4", []), + ("cavlc_lowqp", "noise", 176, 144, 4, "cabac=0:8x8dct=1:bframes=1:qp=4", []), + ("deblock_off", "testsrc2", 176, 144, 6, "cabac=1:bframes=1:no-deblock=1", []), + ("deblock_offsets", "noise", 176, 144, 6, "cabac=1:bframes=1:deblock=-3,3", []), + ("qvga_main", "mandel", 320, 240, 6, "cabac=1:bframes=2:ref=2:8x8dct=0", []), + ("odd_98x62", "noise", 98, 62, 6, "cabac=1:bframes=2:ref=2", []), + ("odd_34x18", "testsrc2", 34, 18, 5, "cabac=0:bframes=1:ref=1", []), + ("tiny_16x16", "noise", 16, 16, 4, "cabac=1:bframes=1", []), + ("wide_200x40", "noise", 200, 40, 6, "cabac=1:bframes=3:ref=3:8x8dct=1", []), + ("poc2_baseline", "testsrc2", 176, 144, 8, "cabac=0:bframes=0:ref=2", ["-profile:v", "baseline"]), + ("intra_refresh", "noise", 176, 144, 10, "cabac=0:bframes=0:intra-refresh=1:keyint=6", []), + ("keyint_short", "testsrc2", 176, 144, 14, "cabac=1:bframes=2:keyint=5:min-keyint=1:open-gop=0", []), + ("open_gop", "testsrc2", 176, 144, 14, "cabac=1:bframes=2:keyint=6:open-gop=1", []), + ("partitions_all", "noise", 176, 144, 8, "cabac=1:bframes=2:partitions=all:8x8dct=1:subme=9:me=umh", []), + ("cavlc_partitions_all", "noise", 176, 144, 8, "cabac=0:bframes=2:partitions=all:8x8dct=1:subme=9", []), +] + +BENCH = [ + ("qvga_cabac_b", "testsrc2", 320, 240, 30, "cabac=1:bframes=3:ref=3:crf=23"), + ("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"), +] + + +def ffmpeg(ctx, args): + return ctx.nix("ffmpeg", ["ffmpeg", "-hide_banner", "-loglevel", "error", "-y"] + args) + + +def encode(ctx, tmp, name, src, w, h, n, params, extra): + out = os.path.join(tmp, name + ".h264") + lav = SRC[src].format(w=w, h=h) + ffmpeg(ctx, ["-f", "lavfi", "-i", lav, "-frames:v", str(n), "-pix_fmt", "yuv420p", "-c:v", "libx264", + "-x264-params", params + ":threads=1", *extra, "-f", "h264", out]) + with open(out, "rb") as f: + data = f.read() + ref = os.path.join(tmp, name + ".yuv") + ffmpeg(ctx, ["-threads", "1", "-i", out, "-f", "rawvideo", "-pix_fmt", "yuv420p", ref]) + with open(ref, "rb") as f: + raw = f.read() + fs = w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2) + frames = [zlib.crc32(raw[i:i + fs]) for i in range(0, len(raw), fs)] + return data, frames + + +def to_avcc(data): + """Annex B -> (avcC record, length-prefixed samples split at access unit delimiters / first slices)""" + nals = [] + i = 0 + starts = [] + while True: + j = data.find(b"\x00\x00\x01", i) + if j < 0: + break + starts.append(j + 3) + i = j + 3 + for k, s in enumerate(starts): + e = starts[k + 1] - 3 if k + 1 < len(starts) else len(data) + nal = data[s:e] + while nal.endswith(b"\x00"): + nal = nal[:-1] + nals.append(nal) + sps = [n for n in nals if n[0] & 31 == 7] + pps = [n for n in nals if n[0] & 31 == 8] + rec = bytes([1, sps[0][1], sps[0][2], sps[0][3], 0xFF, 0xE0 | len(sps)]) + for s in sps: + rec += len(s).to_bytes(2, "big") + s + rec += bytes([len(pps)]) + for p in pps: + rec += len(p).to_bytes(2, "big") + p + samples = [] + cur = b"" + has_slice = False + for n in nals: + t = n[0] & 31 + if t in (7, 8): + continue + # a new access unit: SEI / AUD after a slice, or a slice with first_mb_in_slice == 0 (first bit 1) + if has_slice and (t in (6, 9) or (t in (1, 5) and n[1] & 0x80)): + samples.append(cur) + cur = b"" + has_slice = False + cur += len(n).to_bytes(4, "big") + n + if t in (1, 5): + has_slice = True + if cur: + samples.append(cur) + return rec, samples + + +def generate(ctx): + cases = [] + with tempfile.TemporaryDirectory() as tmp: + for name, src, w, h, n, params, extra in CASES: + data, frames = encode(ctx, tmp, name, src, w, h, n, params, extra) + c = {"name": name, "data": data, "width": w, "height": h, "frames": frames} + if name in ("cabac_b3", "cavlc_p"): + rec, samples = to_avcc(data) + c["avcc"] = rec + c["samples"] = samples + cases.append(c) + ctx.emit("h264_cases", cases) + bad = [] + lav = SRC["testsrc2"].format(w=64, h=64) + out = os.path.join(tmp, "interlaced.h264") + ffmpeg(ctx, ["-f", "lavfi", "-i", lav, "-frames:v", "4", "-pix_fmt", "yuv420p", "-c:v", "libx264", + "-x264-params", "interlaced=1:threads=1", "-f", "h264", out]) + bad.append({"name": "interlaced", "data": open(out, "rb").read(), "code": "UNSUPPORTED"}) + out = os.path.join(tmp, "yuv444.h264") + ffmpeg(ctx, ["-f", "lavfi", "-i", lav, "-frames:v", "2", "-pix_fmt", "yuv444p", "-c:v", "libx264", + "-x264-params", "threads=1", "-f", "h264", out]) + bad.append({"name": "yuv444", "data": open(out, "rb").read(), "code": "UNSUPPORTED"}) + out = os.path.join(tmp, "yuv422.h264") + ffmpeg(ctx, ["-f", "lavfi", "-i", lav, "-frames:v", "2", "-pix_fmt", "yuv422p", "-c:v", "libx264", + "-x264-params", "threads=1", "-f", "h264", out]) + bad.append({"name": "yuv422", "data": open(out, "rb").read(), "code": "UNSUPPORTED"}) + out = os.path.join(tmp, "10bit.h264") + ffmpeg(ctx, ["-f", "lavfi", "-i", lav, "-frames:v", "2", "-pix_fmt", "yuv420p10le", "-c:v", "libx264", + "-x264-params", "threads=1", "-f", "h264", out]) + bad.append({"name": "10bit", "data": open(out, "rb").read(), "code": "UNSUPPORTED"}) + ctx.emit("h264_bad", bad) + bench = [] + for name, src, w, h, n, params in BENCH: + data, frames = encode(ctx, tmp, name, src, w, h, n, params, []) + bench.append({"name": name, "data": data, "width": w, "height": h, "frames": frames}) + ctx.emit("h264_bench", bench)